/**
 * @license
 * Cesium - https://github.com/CesiumGS/cesium
 * Version 1.95
 *
 * Copyright 2011-2022 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.
 */

(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  typeof define === 'function' && define.amd ? define(['exports'], factory) :
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Cesium = {}));
})(this, (function (exports) { 'use strict';

  /**
   * @function
   *
   * @param {*} value The object.
   * @returns {Boolean} Returns true if the object is defined, returns false otherwise.
   *
   * @example
   * if (Cesium.defined(positions)) {
   *      doSomething();
   * } else {
   *      doSomethingElse();
   * }
   */
  function defined(value) {
    return value !== undefined && value !== null;
  }

  /**
   * Constructs an exception object that is thrown due to a developer error, e.g., invalid argument,
   * argument out of range, etc.  This exception should only be thrown during development;
   * it usually indicates a bug in the calling code.  This exception should never be
   * caught; instead the calling code should strive not to generate it.
   * <br /><br />
   * On the other hand, a {@link RuntimeError} indicates an exception that may
   * be thrown at runtime, e.g., out of memory, that the calling code should be prepared
   * to catch.
   *
   * @alias DeveloperError
   * @constructor
   * @extends Error
   *
   * @param {String} [message] The error message for this exception.
   *
   * @see RuntimeError
   */
  function DeveloperError(message) {
    /**
     * 'DeveloperError' indicating that this exception was thrown due to a developer error.
     * @type {String}
     * @readonly
     */
    this.name = "DeveloperError";

    /**
     * The explanation for why this exception was thrown.
     * @type {String}
     * @readonly
     */
    this.message = message;

    //Browsers such as IE don't have a stack property until you actually throw the error.
    let stack;
    try {
      throw new Error();
    } catch (e) {
      stack = e.stack;
    }

    /**
     * The stack trace of this exception, if available.
     * @type {String}
     * @readonly
     */
    this.stack = stack;
  }

  if (defined(Object.create)) {
    DeveloperError.prototype = Object.create(Error.prototype);
    DeveloperError.prototype.constructor = DeveloperError;
  }

  DeveloperError.prototype.toString = function () {
    let str = `${this.name}: ${this.message}`;

    if (defined(this.stack)) {
      str += `\n${this.stack.toString()}`;
    }

    return str;
  };

  /**
   * @private
   */
  DeveloperError.throwInstantiationError = function () {
    throw new DeveloperError(
      "This function defines an interface and should not be called directly."
    );
  };

  /**
   * Contains functions for checking that supplied arguments are of a specified type
   * or meet specified conditions
   * @private
   */
  const Check = {};

  /**
   * Contains type checking functions, all using the typeof operator
   */
  Check.typeOf = {};

  function getUndefinedErrorMessage(name) {
    return `${name} is required, actual value was undefined`;
  }

  function getFailedTypeErrorMessage(actual, expected, name) {
    return `Expected ${name} to be typeof ${expected}, actual typeof was ${actual}`;
  }

  /**
   * Throws if test is not defined
   *
   * @param {String} name The name of the variable being tested
   * @param {*} test The value that is to be checked
   * @exception {DeveloperError} test must be defined
   */
  Check.defined = function (name, test) {
    if (!defined(test)) {
      throw new DeveloperError(getUndefinedErrorMessage(name));
    }
  };

  /**
   * Throws if test is not typeof 'function'
   *
   * @param {String} name The name of the variable being tested
   * @param {*} test The value to test
   * @exception {DeveloperError} test must be typeof 'function'
   */
  Check.typeOf.func = function (name, test) {
    if (typeof test !== "function") {
      throw new DeveloperError(
        getFailedTypeErrorMessage(typeof test, "function", name)
      );
    }
  };

  /**
   * Throws if test is not typeof 'string'
   *
   * @param {String} name The name of the variable being tested
   * @param {*} test The value to test
   * @exception {DeveloperError} test must be typeof 'string'
   */
  Check.typeOf.string = function (name, test) {
    if (typeof test !== "string") {
      throw new DeveloperError(
        getFailedTypeErrorMessage(typeof test, "string", name)
      );
    }
  };

  /**
   * Throws if test is not typeof 'number'
   *
   * @param {String} name The name of the variable being tested
   * @param {*} test The value to test
   * @exception {DeveloperError} test must be typeof 'number'
   */
  Check.typeOf.number = function (name, test) {
    if (typeof test !== "number") {
      throw new DeveloperError(
        getFailedTypeErrorMessage(typeof test, "number", name)
      );
    }
  };

  /**
   * Throws if test is not typeof 'number' and less than limit
   *
   * @param {String} name The name of the variable being tested
   * @param {*} test The value to test
   * @param {Number} limit The limit value to compare against
   * @exception {DeveloperError} test must be typeof 'number' and less than limit
   */
  Check.typeOf.number.lessThan = function (name, test, limit) {
    Check.typeOf.number(name, test);
    if (test >= limit) {
      throw new DeveloperError(
        `Expected ${name} to be less than ${limit}, actual value was ${test}`
      );
    }
  };

  /**
   * Throws if test is not typeof 'number' and less than or equal to limit
   *
   * @param {String} name The name of the variable being tested
   * @param {*} test The value to test
   * @param {Number} limit The limit value to compare against
   * @exception {DeveloperError} test must be typeof 'number' and less than or equal to limit
   */
  Check.typeOf.number.lessThanOrEquals = function (name, test, limit) {
    Check.typeOf.number(name, test);
    if (test > limit) {
      throw new DeveloperError(
        `Expected ${name} to be less than or equal to ${limit}, actual value was ${test}`
      );
    }
  };

  /**
   * Throws if test is not typeof 'number' and greater than limit
   *
   * @param {String} name The name of the variable being tested
   * @param {*} test The value to test
   * @param {Number} limit The limit value to compare against
   * @exception {DeveloperError} test must be typeof 'number' and greater than limit
   */
  Check.typeOf.number.greaterThan = function (name, test, limit) {
    Check.typeOf.number(name, test);
    if (test <= limit) {
      throw new DeveloperError(
        `Expected ${name} to be greater than ${limit}, actual value was ${test}`
      );
    }
  };

  /**
   * Throws if test is not typeof 'number' and greater than or equal to limit
   *
   * @param {String} name The name of the variable being tested
   * @param {*} test The value to test
   * @param {Number} limit The limit value to compare against
   * @exception {DeveloperError} test must be typeof 'number' and greater than or equal to limit
   */
  Check.typeOf.number.greaterThanOrEquals = function (name, test, limit) {
    Check.typeOf.number(name, test);
    if (test < limit) {
      throw new DeveloperError(
        `Expected ${name} to be greater than or equal to ${limit}, actual value was ${test}`
      );
    }
  };

  /**
   * Throws if test is not typeof 'object'
   *
   * @param {String} name The name of the variable being tested
   * @param {*} test The value to test
   * @exception {DeveloperError} test must be typeof 'object'
   */
  Check.typeOf.object = function (name, test) {
    if (typeof test !== "object") {
      throw new DeveloperError(
        getFailedTypeErrorMessage(typeof test, "object", name)
      );
    }
  };

  /**
   * Throws if test is not typeof 'boolean'
   *
   * @param {String} name The name of the variable being tested
   * @param {*} test The value to test
   * @exception {DeveloperError} test must be typeof 'boolean'
   */
  Check.typeOf.bool = function (name, test) {
    if (typeof test !== "boolean") {
      throw new DeveloperError(
        getFailedTypeErrorMessage(typeof test, "boolean", name)
      );
    }
  };

  /**
   * Throws if test is not typeof 'bigint'
   *
   * @param {String} name The name of the variable being tested
   * @param {*} test The value to test
   * @exception {DeveloperError} test must be typeof 'bigint'
   */
  Check.typeOf.bigint = function (name, test) {
    if (typeof test !== "bigint") {
      throw new DeveloperError(
        getFailedTypeErrorMessage(typeof test, "bigint", name)
      );
    }
  };

  /**
   * Throws if test1 and test2 is not typeof 'number' and not equal in value
   *
   * @param {String} name1 The name of the first variable being tested
   * @param {String} name2 The name of the second variable being tested against
   * @param {*} test1 The value to test
   * @param {*} test2 The value to test against
   * @exception {DeveloperError} test1 and test2 should be type of 'number' and be equal in value
   */
  Check.typeOf.number.equals = function (name1, name2, test1, test2) {
    Check.typeOf.number(name1, test1);
    Check.typeOf.number(name2, test2);
    if (test1 !== test2) {
      throw new DeveloperError(
        `${name1} must be equal to ${name2}, the actual values are ${test1} and ${test2}`
      );
    }
  };

  /**
   * Returns the first parameter if not undefined, otherwise the second parameter.
   * Useful for setting a default value for a parameter.
   *
   * @function
   *
   * @param {*} a
   * @param {*} b
   * @returns {*} Returns the first parameter if not undefined, otherwise the second parameter.
   *
   * @example
   * param = Cesium.defaultValue(param, 'default');
   */
  function defaultValue(a, b) {
    if (a !== undefined && a !== null) {
      return a;
    }
    return b;
  }

  /**
   * A frozen empty object that can be used as the default value for options passed as
   * an object literal.
   * @type {Object}
   * @memberof defaultValue
   */
  defaultValue.EMPTY_OBJECT = Object.freeze({});

  /* This file is automatically rebuilt by the Cesium build process. */
  /*
    https://github.com/banksean wrapped Makoto Matsumoto and Takuji Nishimura's code in a namespace
    so it's better encapsulated. Now you can have multiple random number generators
    and they won't stomp all over eachother's state.

    If you want to use this as a substitute for Math.random(), use the random()
    method like so:

    var m = new MersenneTwister();
    var randomNumber = m.random();

    You can also call the other genrand_{foo}() methods on the instance.

    If you want to use a specific seed in order to get a repeatable random
    sequence, pass an integer into the constructor:

    var m = new MersenneTwister(123);

    and that will always produce the same random sequence.

    Sean McCullough (banksean@gmail.com)
  */

  /*
     A C-program for MT19937, with initialization improved 2002/1/26.
     Coded by Takuji Nishimura and Makoto Matsumoto.

     Before using, initialize the state by using init_seed(seed)
     or init_by_array(init_key, key_length).

     Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
     All rights reserved.

     Redistribution and use in source and binary forms, with or without
     modification, are permitted provided that the following conditions
     are met:

       1. Redistributions of source code must retain the above copyright
          notice, this list of conditions and the following disclaimer.

       2. Redistributions in binary form must reproduce the above copyright
          notice, this list of conditions and the following disclaimer in the
          documentation and/or other materials provided with the distribution.

       3. The names of its contributors may not be used to endorse or promote
          products derived from this software without specific prior written
          permission.

     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
     A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
     CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
     EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
     PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
     LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
     NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
     SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


     Any feedback is very welcome.
     http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
     email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
  */

  var MersenneTwister = function(seed) {
  	if (seed == undefined) {
  		seed = new Date().getTime();
  	}

  	/* Period parameters */
  	this.N = 624;
  	this.M = 397;
  	this.MATRIX_A = 0x9908b0df;   /* constant vector a */
  	this.UPPER_MASK = 0x80000000; /* most significant w-r bits */
  	this.LOWER_MASK = 0x7fffffff; /* least significant r bits */

  	this.mt = new Array(this.N); /* the array for the state vector */
  	this.mti=this.N+1; /* mti==N+1 means mt[N] is not initialized */

  	if (seed.constructor == Array) {
  		this.init_by_array(seed, seed.length);
  	}
  	else {
  		this.init_seed(seed);
  	}
  };

  /* initializes mt[N] with a seed */
  /* origin name init_genrand */
  MersenneTwister.prototype.init_seed = function(s) {
  	this.mt[0] = s >>> 0;
  	for (this.mti=1; this.mti<this.N; this.mti++) {
  		var s = this.mt[this.mti-1] ^ (this.mt[this.mti-1] >>> 30);
  		this.mt[this.mti] = (((((s & 0xffff0000) >>> 16) * 1812433253) << 16) + (s & 0x0000ffff) * 1812433253)
  		+ this.mti;
  		/* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
  		/* In the previous versions, MSBs of the seed affect   */
  		/* only MSBs of the array mt[].                        */
  		/* 2002/01/09 modified by Makoto Matsumoto             */
  		this.mt[this.mti] >>>= 0;
  		/* for >32 bit machines */
  	}
  };

  /* initialize by an array with array-length */
  /* init_key is the array for initializing keys */
  /* key_length is its length */
  /* slight change for C++, 2004/2/26 */
  MersenneTwister.prototype.init_by_array = function(init_key, key_length) {
  	var i, j, k;
  	this.init_seed(19650218);
  	i=1; j=0;
  	k = (this.N>key_length ? this.N : key_length);
  	for (; k; k--) {
  		var s = this.mt[i-1] ^ (this.mt[i-1] >>> 30);
  		this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1664525) << 16) + ((s & 0x0000ffff) * 1664525)))
  		+ init_key[j] + j; /* non linear */
  		this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */
  		i++; j++;
  		if (i>=this.N) { this.mt[0] = this.mt[this.N-1]; i=1; }
  		if (j>=key_length) j=0;
  	}
  	for (k=this.N-1; k; k--) {
  		var s = this.mt[i-1] ^ (this.mt[i-1] >>> 30);
  		this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1566083941) << 16) + (s & 0x0000ffff) * 1566083941))
  		- i; /* non linear */
  		this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */
  		i++;
  		if (i>=this.N) { this.mt[0] = this.mt[this.N-1]; i=1; }
  	}

  	this.mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */
  };

  /* generates a random number on [0,0xffffffff]-interval */
  /* origin name genrand_int32 */
  MersenneTwister.prototype.random_int = function() {
  	var y;
  	var mag01 = new Array(0x0, this.MATRIX_A);
  	/* mag01[x] = x * MATRIX_A  for x=0,1 */

  	if (this.mti >= this.N) { /* generate N words at one time */
  		var kk;

  		if (this.mti == this.N+1)  /* if init_seed() has not been called, */
  			this.init_seed(5489);  /* a default initial seed is used */

  		for (kk=0;kk<this.N-this.M;kk++) {
  			y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk+1]&this.LOWER_MASK);
  			this.mt[kk] = this.mt[kk+this.M] ^ (y >>> 1) ^ mag01[y & 0x1];
  		}
  		for (;kk<this.N-1;kk++) {
  			y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk+1]&this.LOWER_MASK);
  			this.mt[kk] = this.mt[kk+(this.M-this.N)] ^ (y >>> 1) ^ mag01[y & 0x1];
  		}
  		y = (this.mt[this.N-1]&this.UPPER_MASK)|(this.mt[0]&this.LOWER_MASK);
  		this.mt[this.N-1] = this.mt[this.M-1] ^ (y >>> 1) ^ mag01[y & 0x1];

  		this.mti = 0;
  	}

  	y = this.mt[this.mti++];

  	/* Tempering */
  	y ^= (y >>> 11);
  	y ^= (y << 7) & 0x9d2c5680;
  	y ^= (y << 15) & 0xefc60000;
  	y ^= (y >>> 18);

  	return y >>> 0;
  };

  /* generates a random number on [0,0x7fffffff]-interval */
  /* origin name genrand_int31 */
  MersenneTwister.prototype.random_int31 = function() {
  	return (this.random_int()>>>1);
  };

  /* generates a random number on [0,1]-real-interval */
  /* origin name genrand_real1 */
  MersenneTwister.prototype.random_incl = function() {
  	return this.random_int()*(1.0/4294967295.0);
  	/* divided by 2^32-1 */
  };

  /* generates a random number on [0,1)-real-interval */
  MersenneTwister.prototype.random = function() {
  	return this.random_int()*(1.0/4294967296.0);
  	/* divided by 2^32 */
  };

  /* generates a random number on (0,1)-real-interval */
  /* origin name genrand_real3 */
  MersenneTwister.prototype.random_excl = function() {
  	return (this.random_int() + 0.5)*(1.0/4294967296.0);
  	/* divided by 2^32 */
  };

  /* generates a random number on [0,1) with 53-bit resolution*/
  /* origin name genrand_res53 */
  MersenneTwister.prototype.random_long = function() {
  	var a=this.random_int()>>>5, b=this.random_int()>>>6;
  	return (a*67108864.0+b)*(1.0/9007199254740992.0);
  };

  /* These real versions are due to Isaku Wada, 2002/01/09 added */

  var mersenneTwister = MersenneTwister;

  /**
   * Math functions.
   *
   * @exports CesiumMath
   * @alias Math
   */
  const CesiumMath = {};

  /**
   * 0.1
   * @type {Number}
   * @constant
   */
  CesiumMath.EPSILON1 = 0.1;

  /**
   * 0.01
   * @type {Number}
   * @constant
   */
  CesiumMath.EPSILON2 = 0.01;

  /**
   * 0.001
   * @type {Number}
   * @constant
   */
  CesiumMath.EPSILON3 = 0.001;

  /**
   * 0.0001
   * @type {Number}
   * @constant
   */
  CesiumMath.EPSILON4 = 0.0001;

  /**
   * 0.00001
   * @type {Number}
   * @constant
   */
  CesiumMath.EPSILON5 = 0.00001;

  /**
   * 0.000001
   * @type {Number}
   * @constant
   */
  CesiumMath.EPSILON6 = 0.000001;

  /**
   * 0.0000001
   * @type {Number}
   * @constant
   */
  CesiumMath.EPSILON7 = 0.0000001;

  /**
   * 0.00000001
   * @type {Number}
   * @constant
   */
  CesiumMath.EPSILON8 = 0.00000001;

  /**
   * 0.000000001
   * @type {Number}
   * @constant
   */
  CesiumMath.EPSILON9 = 0.000000001;

  /**
   * 0.0000000001
   * @type {Number}
   * @constant
   */
  CesiumMath.EPSILON10 = 0.0000000001;

  /**
   * 0.00000000001
   * @type {Number}
   * @constant
   */
  CesiumMath.EPSILON11 = 0.00000000001;

  /**
   * 0.000000000001
   * @type {Number}
   * @constant
   */
  CesiumMath.EPSILON12 = 0.000000000001;

  /**
   * 0.0000000000001
   * @type {Number}
   * @constant
   */
  CesiumMath.EPSILON13 = 0.0000000000001;

  /**
   * 0.00000000000001
   * @type {Number}
   * @constant
   */
  CesiumMath.EPSILON14 = 0.00000000000001;

  /**
   * 0.000000000000001
   * @type {Number}
   * @constant
   */
  CesiumMath.EPSILON15 = 0.000000000000001;

  /**
   * 0.0000000000000001
   * @type {Number}
   * @constant
   */
  CesiumMath.EPSILON16 = 0.0000000000000001;

  /**
   * 0.00000000000000001
   * @type {Number}
   * @constant
   */
  CesiumMath.EPSILON17 = 0.00000000000000001;

  /**
   * 0.000000000000000001
   * @type {Number}
   * @constant
   */
  CesiumMath.EPSILON18 = 0.000000000000000001;

  /**
   * 0.0000000000000000001
   * @type {Number}
   * @constant
   */
  CesiumMath.EPSILON19 = 0.0000000000000000001;

  /**
   * 0.00000000000000000001
   * @type {Number}
   * @constant
   */
  CesiumMath.EPSILON20 = 0.00000000000000000001;

  /**
   * 0.000000000000000000001
   * @type {Number}
   * @constant
   */
  CesiumMath.EPSILON21 = 0.000000000000000000001;

  /**
   * The gravitational parameter of the Earth in meters cubed
   * per second squared as defined by the WGS84 model: 3.986004418e14
   * @type {Number}
   * @constant
   */
  CesiumMath.GRAVITATIONALPARAMETER = 3.986004418e14;

  /**
   * Radius of the sun in meters: 6.955e8
   * @type {Number}
   * @constant
   */
  CesiumMath.SOLAR_RADIUS = 6.955e8;

  /**
   * The mean radius of the moon, according to the "Report of the IAU/IAG Working Group on
   * Cartographic Coordinates and Rotational Elements of the Planets and satellites: 2000",
   * Celestial Mechanics 82: 83-110, 2002.
   * @type {Number}
   * @constant
   */
  CesiumMath.LUNAR_RADIUS = 1737400.0;

  /**
   * 64 * 1024
   * @type {Number}
   * @constant
   */
  CesiumMath.SIXTY_FOUR_KILOBYTES = 64 * 1024;

  /**
   * 4 * 1024 * 1024 * 1024
   * @type {Number}
   * @constant
   */
  CesiumMath.FOUR_GIGABYTES = 4 * 1024 * 1024 * 1024;

  /**
   * Returns the sign of the value; 1 if the value is positive, -1 if the value is
   * negative, or 0 if the value is 0.
   *
   * @function
   * @param {Number} value The value to return the sign of.
   * @returns {Number} The sign of value.
   */
  // eslint-disable-next-line es/no-math-sign
  CesiumMath.sign = defaultValue(Math.sign, function sign(value) {
    value = +value; // coerce to number
    if (value === 0 || value !== value) {
      // zero or NaN
      return value;
    }
    return value > 0 ? 1 : -1;
  });

  /**
   * Returns 1.0 if the given value is positive or zero, and -1.0 if it is negative.
   * This is similar to {@link CesiumMath#sign} except that returns 1.0 instead of
   * 0.0 when the input value is 0.0.
   * @param {Number} value The value to return the sign of.
   * @returns {Number} The sign of value.
   */
  CesiumMath.signNotZero = function (value) {
    return value < 0.0 ? -1.0 : 1.0;
  };

  /**
   * Converts a scalar value in the range [-1.0, 1.0] to a SNORM in the range [0, rangeMaximum]
   * @param {Number} value The scalar value in the range [-1.0, 1.0]
   * @param {Number} [rangeMaximum=255] The maximum value in the mapped range, 255 by default.
   * @returns {Number} A SNORM value, where 0 maps to -1.0 and rangeMaximum maps to 1.0.
   *
   * @see CesiumMath.fromSNorm
   */
  CesiumMath.toSNorm = function (value, rangeMaximum) {
    rangeMaximum = defaultValue(rangeMaximum, 255);
    return Math.round(
      (CesiumMath.clamp(value, -1.0, 1.0) * 0.5 + 0.5) * rangeMaximum
    );
  };

  /**
   * Converts a SNORM value in the range [0, rangeMaximum] to a scalar in the range [-1.0, 1.0].
   * @param {Number} value SNORM value in the range [0, rangeMaximum]
   * @param {Number} [rangeMaximum=255] The maximum value in the SNORM range, 255 by default.
   * @returns {Number} Scalar in the range [-1.0, 1.0].
   *
   * @see CesiumMath.toSNorm
   */
  CesiumMath.fromSNorm = function (value, rangeMaximum) {
    rangeMaximum = defaultValue(rangeMaximum, 255);
    return (
      (CesiumMath.clamp(value, 0.0, rangeMaximum) / rangeMaximum) * 2.0 - 1.0
    );
  };

  /**
   * Converts a scalar value in the range [rangeMinimum, rangeMaximum] to a scalar in the range [0.0, 1.0]
   * @param {Number} value The scalar value in the range [rangeMinimum, rangeMaximum]
   * @param {Number} rangeMinimum The minimum value in the mapped range.
   * @param {Number} rangeMaximum The maximum value in the mapped range.
   * @returns {Number} A scalar value, where rangeMinimum maps to 0.0 and rangeMaximum maps to 1.0.
   */
  CesiumMath.normalize = function (value, rangeMinimum, rangeMaximum) {
    rangeMaximum = Math.max(rangeMaximum - rangeMinimum, 0.0);
    return rangeMaximum === 0.0
      ? 0.0
      : CesiumMath.clamp((value - rangeMinimum) / rangeMaximum, 0.0, 1.0);
  };

  /**
   * Returns the hyperbolic sine of a number.
   * The hyperbolic sine of <em>value</em> is defined to be
   * (<em>e<sup>x</sup>&nbsp;-&nbsp;e<sup>-x</sup></em>)/2.0
   * where <i>e</i> is Euler's number, approximately 2.71828183.
   *
   * <p>Special cases:
   *   <ul>
   *     <li>If the argument is NaN, then the result is NaN.</li>
   *
   *     <li>If the argument is infinite, then the result is an infinity
   *     with the same sign as the argument.</li>
   *
   *     <li>If the argument is zero, then the result is a zero with the
   *     same sign as the argument.</li>
   *   </ul>
   *</p>
   *
   * @function
   * @param {Number} value The number whose hyperbolic sine is to be returned.
   * @returns {Number} The hyperbolic sine of <code>value</code>.
   */
  // eslint-disable-next-line es/no-math-sinh
  CesiumMath.sinh = defaultValue(Math.sinh, function sinh(value) {
    return (Math.exp(value) - Math.exp(-value)) / 2.0;
  });

  /**
   * Returns the hyperbolic cosine of a number.
   * The hyperbolic cosine of <strong>value</strong> is defined to be
   * (<em>e<sup>x</sup>&nbsp;+&nbsp;e<sup>-x</sup></em>)/2.0
   * where <i>e</i> is Euler's number, approximately 2.71828183.
   *
   * <p>Special cases:
   *   <ul>
   *     <li>If the argument is NaN, then the result is NaN.</li>
   *
   *     <li>If the argument is infinite, then the result is positive infinity.</li>
   *
   *     <li>If the argument is zero, then the result is 1.0.</li>
   *   </ul>
   *</p>
   *
   * @function
   * @param {Number} value The number whose hyperbolic cosine is to be returned.
   * @returns {Number} The hyperbolic cosine of <code>value</code>.
   */
  // eslint-disable-next-line es/no-math-cosh
  CesiumMath.cosh = defaultValue(Math.cosh, function cosh(value) {
    return (Math.exp(value) + Math.exp(-value)) / 2.0;
  });

  /**
   * Computes the linear interpolation of two values.
   *
   * @param {Number} p The start value to interpolate.
   * @param {Number} q The end value to interpolate.
   * @param {Number} time The time of interpolation generally in the range <code>[0.0, 1.0]</code>.
   * @returns {Number} The linearly interpolated value.
   *
   * @example
   * const n = Cesium.Math.lerp(0.0, 2.0, 0.5); // returns 1.0
   */
  CesiumMath.lerp = function (p, q, time) {
    return (1.0 - time) * p + time * q;
  };

  /**
   * pi
   *
   * @type {Number}
   * @constant
   */
  CesiumMath.PI = Math.PI;

  /**
   * 1/pi
   *
   * @type {Number}
   * @constant
   */
  CesiumMath.ONE_OVER_PI = 1.0 / Math.PI;

  /**
   * pi/2
   *
   * @type {Number}
   * @constant
   */
  CesiumMath.PI_OVER_TWO = Math.PI / 2.0;

  /**
   * pi/3
   *
   * @type {Number}
   * @constant
   */
  CesiumMath.PI_OVER_THREE = Math.PI / 3.0;

  /**
   * pi/4
   *
   * @type {Number}
   * @constant
   */
  CesiumMath.PI_OVER_FOUR = Math.PI / 4.0;

  /**
   * pi/6
   *
   * @type {Number}
   * @constant
   */
  CesiumMath.PI_OVER_SIX = Math.PI / 6.0;

  /**
   * 3pi/2
   *
   * @type {Number}
   * @constant
   */
  CesiumMath.THREE_PI_OVER_TWO = (3.0 * Math.PI) / 2.0;

  /**
   * 2pi
   *
   * @type {Number}
   * @constant
   */
  CesiumMath.TWO_PI = 2.0 * Math.PI;

  /**
   * 1/2pi
   *
   * @type {Number}
   * @constant
   */
  CesiumMath.ONE_OVER_TWO_PI = 1.0 / (2.0 * Math.PI);

  /**
   * The number of radians in a degree.
   *
   * @type {Number}
   * @constant
   */
  CesiumMath.RADIANS_PER_DEGREE = Math.PI / 180.0;

  /**
   * The number of degrees in a radian.
   *
   * @type {Number}
   * @constant
   */
  CesiumMath.DEGREES_PER_RADIAN = 180.0 / Math.PI;

  /**
   * The number of radians in an arc second.
   *
   * @type {Number}
   * @constant
   */
  CesiumMath.RADIANS_PER_ARCSECOND = CesiumMath.RADIANS_PER_DEGREE / 3600.0;

  /**
   * Converts degrees to radians.
   * @param {Number} degrees The angle to convert in degrees.
   * @returns {Number} The corresponding angle in radians.
   */
  CesiumMath.toRadians = function (degrees) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(degrees)) {
      throw new DeveloperError("degrees is required.");
    }
    //>>includeEnd('debug');
    return degrees * CesiumMath.RADIANS_PER_DEGREE;
  };

  /**
   * Converts radians to degrees.
   * @param {Number} radians The angle to convert in radians.
   * @returns {Number} The corresponding angle in degrees.
   */
  CesiumMath.toDegrees = function (radians) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(radians)) {
      throw new DeveloperError("radians is required.");
    }
    //>>includeEnd('debug');
    return radians * CesiumMath.DEGREES_PER_RADIAN;
  };

  /**
   * Converts a longitude value, in radians, to the range [<code>-Math.PI</code>, <code>Math.PI</code>).
   *
   * @param {Number} angle The longitude value, in radians, to convert to the range [<code>-Math.PI</code>, <code>Math.PI</code>).
   * @returns {Number} The equivalent longitude value in the range [<code>-Math.PI</code>, <code>Math.PI</code>).
   *
   * @example
   * // Convert 270 degrees to -90 degrees longitude
   * const longitude = Cesium.Math.convertLongitudeRange(Cesium.Math.toRadians(270.0));
   */
  CesiumMath.convertLongitudeRange = function (angle) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(angle)) {
      throw new DeveloperError("angle is required.");
    }
    //>>includeEnd('debug');
    const twoPi = CesiumMath.TWO_PI;

    const simplified = angle - Math.floor(angle / twoPi) * twoPi;

    if (simplified < -Math.PI) {
      return simplified + twoPi;
    }
    if (simplified >= Math.PI) {
      return simplified - twoPi;
    }

    return simplified;
  };

  /**
   * Convenience function that clamps a latitude value, in radians, to the range [<code>-Math.PI/2</code>, <code>Math.PI/2</code>).
   * Useful for sanitizing data before use in objects requiring correct range.
   *
   * @param {Number} angle The latitude value, in radians, to clamp to the range [<code>-Math.PI/2</code>, <code>Math.PI/2</code>).
   * @returns {Number} The latitude value clamped to the range [<code>-Math.PI/2</code>, <code>Math.PI/2</code>).
   *
   * @example
   * // Clamp 108 degrees latitude to 90 degrees latitude
   * const latitude = Cesium.Math.clampToLatitudeRange(Cesium.Math.toRadians(108.0));
   */
  CesiumMath.clampToLatitudeRange = function (angle) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(angle)) {
      throw new DeveloperError("angle is required.");
    }
    //>>includeEnd('debug');

    return CesiumMath.clamp(
      angle,
      -1 * CesiumMath.PI_OVER_TWO,
      CesiumMath.PI_OVER_TWO
    );
  };

  /**
   * Produces an angle in the range -Pi <= angle <= Pi which is equivalent to the provided angle.
   *
   * @param {Number} angle in radians
   * @returns {Number} The angle in the range [<code>-CesiumMath.PI</code>, <code>CesiumMath.PI</code>].
   */
  CesiumMath.negativePiToPi = function (angle) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(angle)) {
      throw new DeveloperError("angle is required.");
    }
    //>>includeEnd('debug');
    if (angle >= -CesiumMath.PI && angle <= CesiumMath.PI) {
      // Early exit if the input is already inside the range. This avoids
      // unnecessary math which could introduce floating point error.
      return angle;
    }
    return CesiumMath.zeroToTwoPi(angle + CesiumMath.PI) - CesiumMath.PI;
  };

  /**
   * Produces an angle in the range 0 <= angle <= 2Pi which is equivalent to the provided angle.
   *
   * @param {Number} angle in radians
   * @returns {Number} The angle in the range [0, <code>CesiumMath.TWO_PI</code>].
   */
  CesiumMath.zeroToTwoPi = function (angle) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(angle)) {
      throw new DeveloperError("angle is required.");
    }
    //>>includeEnd('debug');
    if (angle >= 0 && angle <= CesiumMath.TWO_PI) {
      // Early exit if the input is already inside the range. This avoids
      // unnecessary math which could introduce floating point error.
      return angle;
    }
    const mod = CesiumMath.mod(angle, CesiumMath.TWO_PI);
    if (
      Math.abs(mod) < CesiumMath.EPSILON14 &&
      Math.abs(angle) > CesiumMath.EPSILON14
    ) {
      return CesiumMath.TWO_PI;
    }
    return mod;
  };

  /**
   * The modulo operation that also works for negative dividends.
   *
   * @param {Number} m The dividend.
   * @param {Number} n The divisor.
   * @returns {Number} The remainder.
   */
  CesiumMath.mod = function (m, n) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(m)) {
      throw new DeveloperError("m is required.");
    }
    if (!defined(n)) {
      throw new DeveloperError("n is required.");
    }
    if (n === 0.0) {
      throw new DeveloperError("divisor cannot be 0.");
    }
    //>>includeEnd('debug');
    if (CesiumMath.sign(m) === CesiumMath.sign(n) && Math.abs(m) < Math.abs(n)) {
      // Early exit if the input does not need to be modded. This avoids
      // unnecessary math which could introduce floating point error.
      return m;
    }

    return ((m % n) + n) % n;
  };

  /**
   * Determines if two values are equal using an absolute or relative tolerance test. This is useful
   * to avoid problems due to roundoff error when comparing floating-point values directly. The values are
   * first compared using an absolute tolerance test. If that fails, a relative tolerance test is performed.
   * Use this test if you are unsure of the magnitudes of left and right.
   *
   * @param {Number} left The first value to compare.
   * @param {Number} right The other value to compare.
   * @param {Number} [relativeEpsilon=0] The maximum inclusive delta between <code>left</code> and <code>right</code> for the relative tolerance test.
   * @param {Number} [absoluteEpsilon=relativeEpsilon] The maximum inclusive delta between <code>left</code> and <code>right</code> for the absolute tolerance test.
   * @returns {Boolean} <code>true</code> if the values are equal within the epsilon; otherwise, <code>false</code>.
   *
   * @example
   * const a = Cesium.Math.equalsEpsilon(0.0, 0.01, Cesium.Math.EPSILON2); // true
   * const b = Cesium.Math.equalsEpsilon(0.0, 0.1, Cesium.Math.EPSILON2);  // false
   * const c = Cesium.Math.equalsEpsilon(3699175.1634344, 3699175.2, Cesium.Math.EPSILON7); // true
   * const d = Cesium.Math.equalsEpsilon(3699175.1634344, 3699175.2, Cesium.Math.EPSILON9); // false
   */
  CesiumMath.equalsEpsilon = function (
    left,
    right,
    relativeEpsilon,
    absoluteEpsilon
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(left)) {
      throw new DeveloperError("left is required.");
    }
    if (!defined(right)) {
      throw new DeveloperError("right is required.");
    }
    //>>includeEnd('debug');

    relativeEpsilon = defaultValue(relativeEpsilon, 0.0);
    absoluteEpsilon = defaultValue(absoluteEpsilon, relativeEpsilon);
    const absDiff = Math.abs(left - right);
    return (
      absDiff <= absoluteEpsilon ||
      absDiff <= relativeEpsilon * Math.max(Math.abs(left), Math.abs(right))
    );
  };

  /**
   * Determines if the left value is less than the right value. If the two values are within
   * <code>absoluteEpsilon</code> of each other, they are considered equal and this function returns false.
   *
   * @param {Number} left The first number to compare.
   * @param {Number} right The second number to compare.
   * @param {Number} absoluteEpsilon The absolute epsilon to use in comparison.
   * @returns {Boolean} <code>true</code> if <code>left</code> is less than <code>right</code> by more than
   *          <code>absoluteEpsilon<code>. <code>false</code> if <code>left</code> is greater or if the two
   *          values are nearly equal.
   */
  CesiumMath.lessThan = function (left, right, absoluteEpsilon) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(left)) {
      throw new DeveloperError("first is required.");
    }
    if (!defined(right)) {
      throw new DeveloperError("second is required.");
    }
    if (!defined(absoluteEpsilon)) {
      throw new DeveloperError("absoluteEpsilon is required.");
    }
    //>>includeEnd('debug');
    return left - right < -absoluteEpsilon;
  };

  /**
   * Determines if the left value is less than or equal to the right value. If the two values are within
   * <code>absoluteEpsilon</code> of each other, they are considered equal and this function returns true.
   *
   * @param {Number} left The first number to compare.
   * @param {Number} right The second number to compare.
   * @param {Number} absoluteEpsilon The absolute epsilon to use in comparison.
   * @returns {Boolean} <code>true</code> if <code>left</code> is less than <code>right</code> or if the
   *          the values are nearly equal.
   */
  CesiumMath.lessThanOrEquals = function (left, right, absoluteEpsilon) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(left)) {
      throw new DeveloperError("first is required.");
    }
    if (!defined(right)) {
      throw new DeveloperError("second is required.");
    }
    if (!defined(absoluteEpsilon)) {
      throw new DeveloperError("absoluteEpsilon is required.");
    }
    //>>includeEnd('debug');
    return left - right < absoluteEpsilon;
  };

  /**
   * Determines if the left value is greater the right value. If the two values are within
   * <code>absoluteEpsilon</code> of each other, they are considered equal and this function returns false.
   *
   * @param {Number} left The first number to compare.
   * @param {Number} right The second number to compare.
   * @param {Number} absoluteEpsilon The absolute epsilon to use in comparison.
   * @returns {Boolean} <code>true</code> if <code>left</code> is greater than <code>right</code> by more than
   *          <code>absoluteEpsilon<code>. <code>false</code> if <code>left</code> is less or if the two
   *          values are nearly equal.
   */
  CesiumMath.greaterThan = function (left, right, absoluteEpsilon) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(left)) {
      throw new DeveloperError("first is required.");
    }
    if (!defined(right)) {
      throw new DeveloperError("second is required.");
    }
    if (!defined(absoluteEpsilon)) {
      throw new DeveloperError("absoluteEpsilon is required.");
    }
    //>>includeEnd('debug');
    return left - right > absoluteEpsilon;
  };

  /**
   * Determines if the left value is greater than or equal to the right value. If the two values are within
   * <code>absoluteEpsilon</code> of each other, they are considered equal and this function returns true.
   *
   * @param {Number} left The first number to compare.
   * @param {Number} right The second number to compare.
   * @param {Number} absoluteEpsilon The absolute epsilon to use in comparison.
   * @returns {Boolean} <code>true</code> if <code>left</code> is greater than <code>right</code> or if the
   *          the values are nearly equal.
   */
  CesiumMath.greaterThanOrEquals = function (left, right, absoluteEpsilon) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(left)) {
      throw new DeveloperError("first is required.");
    }
    if (!defined(right)) {
      throw new DeveloperError("second is required.");
    }
    if (!defined(absoluteEpsilon)) {
      throw new DeveloperError("absoluteEpsilon is required.");
    }
    //>>includeEnd('debug');
    return left - right > -absoluteEpsilon;
  };

  const factorials = [1];

  /**
   * Computes the factorial of the provided number.
   *
   * @param {Number} n The number whose factorial is to be computed.
   * @returns {Number} The factorial of the provided number or undefined if the number is less than 0.
   *
   * @exception {DeveloperError} A number greater than or equal to 0 is required.
   *
   *
   * @example
   * //Compute 7!, which is equal to 5040
   * const computedFactorial = Cesium.Math.factorial(7);
   *
   * @see {@link http://en.wikipedia.org/wiki/Factorial|Factorial on Wikipedia}
   */
  CesiumMath.factorial = function (n) {
    //>>includeStart('debug', pragmas.debug);
    if (typeof n !== "number" || n < 0) {
      throw new DeveloperError(
        "A number greater than or equal to 0 is required."
      );
    }
    //>>includeEnd('debug');

    const length = factorials.length;
    if (n >= length) {
      let sum = factorials[length - 1];
      for (let i = length; i <= n; i++) {
        const next = sum * i;
        factorials.push(next);
        sum = next;
      }
    }
    return factorials[n];
  };

  /**
   * Increments a number with a wrapping to a minimum value if the number exceeds the maximum value.
   *
   * @param {Number} [n] The number to be incremented.
   * @param {Number} [maximumValue] The maximum incremented value before rolling over to the minimum value.
   * @param {Number} [minimumValue=0.0] The number reset to after the maximum value has been exceeded.
   * @returns {Number} The incremented number.
   *
   * @exception {DeveloperError} Maximum value must be greater than minimum value.
   *
   * @example
   * const n = Cesium.Math.incrementWrap(5, 10, 0); // returns 6
   * const m = Cesium.Math.incrementWrap(10, 10, 0); // returns 0
   */
  CesiumMath.incrementWrap = function (n, maximumValue, minimumValue) {
    minimumValue = defaultValue(minimumValue, 0.0);

    //>>includeStart('debug', pragmas.debug);
    if (!defined(n)) {
      throw new DeveloperError("n is required.");
    }
    if (maximumValue <= minimumValue) {
      throw new DeveloperError("maximumValue must be greater than minimumValue.");
    }
    //>>includeEnd('debug');

    ++n;
    if (n > maximumValue) {
      n = minimumValue;
    }
    return n;
  };

  /**
   * Determines if a non-negative integer is a power of two.
   * The maximum allowed input is (2^32)-1 due to 32-bit bitwise operator limitation in Javascript.
   *
   * @param {Number} n The integer to test in the range [0, (2^32)-1].
   * @returns {Boolean} <code>true</code> if the number if a power of two; otherwise, <code>false</code>.
   *
   * @exception {DeveloperError} A number between 0 and (2^32)-1 is required.
   *
   * @example
   * const t = Cesium.Math.isPowerOfTwo(16); // true
   * const f = Cesium.Math.isPowerOfTwo(20); // false
   */
  CesiumMath.isPowerOfTwo = function (n) {
    //>>includeStart('debug', pragmas.debug);
    if (typeof n !== "number" || n < 0 || n > 4294967295) {
      throw new DeveloperError("A number between 0 and (2^32)-1 is required.");
    }
    //>>includeEnd('debug');

    return n !== 0 && (n & (n - 1)) === 0;
  };

  /**
   * Computes the next power-of-two integer greater than or equal to the provided non-negative integer.
   * The maximum allowed input is 2^31 due to 32-bit bitwise operator limitation in Javascript.
   *
   * @param {Number} n The integer to test in the range [0, 2^31].
   * @returns {Number} The next power-of-two integer.
   *
   * @exception {DeveloperError} A number between 0 and 2^31 is required.
   *
   * @example
   * const n = Cesium.Math.nextPowerOfTwo(29); // 32
   * const m = Cesium.Math.nextPowerOfTwo(32); // 32
   */
  CesiumMath.nextPowerOfTwo = function (n) {
    //>>includeStart('debug', pragmas.debug);
    if (typeof n !== "number" || n < 0 || n > 2147483648) {
      throw new DeveloperError("A number between 0 and 2^31 is required.");
    }
    //>>includeEnd('debug');

    // From http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
    --n;
    n |= n >> 1;
    n |= n >> 2;
    n |= n >> 4;
    n |= n >> 8;
    n |= n >> 16;
    ++n;

    return n;
  };

  /**
   * Computes the previous power-of-two integer less than or equal to the provided non-negative integer.
   * The maximum allowed input is (2^32)-1 due to 32-bit bitwise operator limitation in Javascript.
   *
   * @param {Number} n The integer to test in the range [0, (2^32)-1].
   * @returns {Number} The previous power-of-two integer.
   *
   * @exception {DeveloperError} A number between 0 and (2^32)-1 is required.
   *
   * @example
   * const n = Cesium.Math.previousPowerOfTwo(29); // 16
   * const m = Cesium.Math.previousPowerOfTwo(32); // 32
   */
  CesiumMath.previousPowerOfTwo = function (n) {
    //>>includeStart('debug', pragmas.debug);
    if (typeof n !== "number" || n < 0 || n > 4294967295) {
      throw new DeveloperError("A number between 0 and (2^32)-1 is required.");
    }
    //>>includeEnd('debug');

    n |= n >> 1;
    n |= n >> 2;
    n |= n >> 4;
    n |= n >> 8;
    n |= n >> 16;
    n |= n >> 32;

    // The previous bitwise operations implicitly convert to signed 32-bit. Use `>>>` to convert to unsigned
    n = (n >>> 0) - (n >>> 1);

    return n;
  };

  /**
   * Constraint a value to lie between two values.
   *
   * @param {Number} value The value to clamp.
   * @param {Number} min The minimum value.
   * @param {Number} max The maximum value.
   * @returns {Number} The clamped value such that min <= result <= max.
   */
  CesiumMath.clamp = function (value, min, max) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("value", value);
    Check.typeOf.number("min", min);
    Check.typeOf.number("max", max);
    //>>includeEnd('debug');

    return value < min ? min : value > max ? max : value;
  };

  let randomNumberGenerator$2 = new mersenneTwister();

  /**
   * Sets the seed used by the random number generator
   * in {@link CesiumMath#nextRandomNumber}.
   *
   * @param {Number} seed An integer used as the seed.
   */
  CesiumMath.setRandomNumberSeed = function (seed) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(seed)) {
      throw new DeveloperError("seed is required.");
    }
    //>>includeEnd('debug');

    randomNumberGenerator$2 = new mersenneTwister(seed);
  };

  /**
   * Generates a random floating point number in the range of [0.0, 1.0)
   * using a Mersenne twister.
   *
   * @returns {Number} A random number in the range of [0.0, 1.0).
   *
   * @see CesiumMath.setRandomNumberSeed
   * @see {@link http://en.wikipedia.org/wiki/Mersenne_twister|Mersenne twister on Wikipedia}
   */
  CesiumMath.nextRandomNumber = function () {
    return randomNumberGenerator$2.random();
  };

  /**
   * Generates a random number between two numbers.
   *
   * @param {Number} min The minimum value.
   * @param {Number} max The maximum value.
   * @returns {Number} A random number between the min and max.
   */
  CesiumMath.randomBetween = function (min, max) {
    return CesiumMath.nextRandomNumber() * (max - min) + min;
  };

  /**
   * Computes <code>Math.acos(value)</code>, but first clamps <code>value</code> to the range [-1.0, 1.0]
   * so that the function will never return NaN.
   *
   * @param {Number} value The value for which to compute acos.
   * @returns {Number} The acos of the value if the value is in the range [-1.0, 1.0], or the acos of -1.0 or 1.0,
   *          whichever is closer, if the value is outside the range.
   */
  CesiumMath.acosClamped = function (value) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(value)) {
      throw new DeveloperError("value is required.");
    }
    //>>includeEnd('debug');
    return Math.acos(CesiumMath.clamp(value, -1.0, 1.0));
  };

  /**
   * Computes <code>Math.asin(value)</code>, but first clamps <code>value</code> to the range [-1.0, 1.0]
   * so that the function will never return NaN.
   *
   * @param {Number} value The value for which to compute asin.
   * @returns {Number} The asin of the value if the value is in the range [-1.0, 1.0], or the asin of -1.0 or 1.0,
   *          whichever is closer, if the value is outside the range.
   */
  CesiumMath.asinClamped = function (value) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(value)) {
      throw new DeveloperError("value is required.");
    }
    //>>includeEnd('debug');
    return Math.asin(CesiumMath.clamp(value, -1.0, 1.0));
  };

  /**
   * Finds the chord length between two points given the circle's radius and the angle between the points.
   *
   * @param {Number} angle The angle between the two points.
   * @param {Number} radius The radius of the circle.
   * @returns {Number} The chord length.
   */
  CesiumMath.chordLength = function (angle, radius) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(angle)) {
      throw new DeveloperError("angle is required.");
    }
    if (!defined(radius)) {
      throw new DeveloperError("radius is required.");
    }
    //>>includeEnd('debug');
    return 2.0 * radius * Math.sin(angle * 0.5);
  };

  /**
   * Finds the logarithm of a number to a base.
   *
   * @param {Number} number The number.
   * @param {Number} base The base.
   * @returns {Number} The result.
   */
  CesiumMath.logBase = function (number, base) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(number)) {
      throw new DeveloperError("number is required.");
    }
    if (!defined(base)) {
      throw new DeveloperError("base is required.");
    }
    //>>includeEnd('debug');
    return Math.log(number) / Math.log(base);
  };

  /**
   * Finds the cube root of a number.
   * Returns NaN if <code>number</code> is not provided.
   *
   * @function
   * @param {Number} [number] The number.
   * @returns {Number} The result.
   */
  // eslint-disable-next-line es/no-math-cbrt
  CesiumMath.cbrt = defaultValue(Math.cbrt, function cbrt(number) {
    const result = Math.pow(Math.abs(number), 1.0 / 3.0);
    return number < 0.0 ? -result : result;
  });

  /**
   * Finds the base 2 logarithm of a number.
   *
   * @function
   * @param {Number} number The number.
   * @returns {Number} The result.
   */
  // eslint-disable-next-line es/no-math-log2
  CesiumMath.log2 = defaultValue(Math.log2, function log2(number) {
    return Math.log(number) * Math.LOG2E;
  });

  /**
   * @private
   */
  CesiumMath.fog = function (distanceToCamera, density) {
    const scalar = distanceToCamera * density;
    return 1.0 - Math.exp(-(scalar * scalar));
  };

  /**
   * Computes a fast approximation of Atan for input in the range [-1, 1].
   *
   * Based on Michal Drobot's approximation from ShaderFastLibs,
   * which in turn is based on "Efficient approximations for the arctangent function,"
   * Rajan, S. Sichun Wang Inkol, R. Joyal, A., May 2006.
   * Adapted from ShaderFastLibs under MIT License.
   *
   * @param {Number} x An input number in the range [-1, 1]
   * @returns {Number} An approximation of atan(x)
   */
  CesiumMath.fastApproximateAtan = function (x) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("x", x);
    //>>includeEnd('debug');

    return x * (-0.1784 * Math.abs(x) - 0.0663 * x * x + 1.0301);
  };

  /**
   * Computes a fast approximation of Atan2(x, y) for arbitrary input scalars.
   *
   * Range reduction math based on nvidia's cg reference implementation: http://developer.download.nvidia.com/cg/atan2.html
   *
   * @param {Number} x An input number that isn't zero if y is zero.
   * @param {Number} y An input number that isn't zero if x is zero.
   * @returns {Number} An approximation of atan2(x, y)
   */
  CesiumMath.fastApproximateAtan2 = function (x, y) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("x", x);
    Check.typeOf.number("y", y);
    //>>includeEnd('debug');

    // atan approximations are usually only reliable over [-1, 1]
    // So reduce the range by flipping whether x or y is on top based on which is bigger.
    let opposite;
    let t = Math.abs(x); // t used as swap and atan result.
    opposite = Math.abs(y);
    const adjacent = Math.max(t, opposite);
    opposite = Math.min(t, opposite);

    const oppositeOverAdjacent = opposite / adjacent;
    //>>includeStart('debug', pragmas.debug);
    if (isNaN(oppositeOverAdjacent)) {
      throw new DeveloperError("either x or y must be nonzero");
    }
    //>>includeEnd('debug');
    t = CesiumMath.fastApproximateAtan(oppositeOverAdjacent);

    // Undo range reduction
    t = Math.abs(y) > Math.abs(x) ? CesiumMath.PI_OVER_TWO - t : t;
    t = x < 0.0 ? CesiumMath.PI - t : t;
    t = y < 0.0 ? -t : t;
    return t;
  };

  /**
   * A 3D Cartesian point.
   * @alias Cartesian3
   * @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.
   *
   * @see Cartesian2
   * @see Cartesian4
   * @see Packable
   */
  function Cartesian3(x, y, z) {
    /**
     * The X component.
     * @type {Number}
     * @default 0.0
     */
    this.x = defaultValue(x, 0.0);

    /**
     * The Y component.
     * @type {Number}
     * @default 0.0
     */
    this.y = defaultValue(y, 0.0);

    /**
     * The Z component.
     * @type {Number}
     * @default 0.0
     */
    this.z = defaultValue(z, 0.0);
  }

  /**
   * Converts the provided Spherical into Cartesian3 coordinates.
   *
   * @param {Spherical} spherical The Spherical to be converted to Cartesian3.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
   */
  Cartesian3.fromSpherical = function (spherical, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("spherical", spherical);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Cartesian3();
    }

    const clock = spherical.clock;
    const cone = spherical.cone;
    const magnitude = defaultValue(spherical.magnitude, 1.0);
    const radial = magnitude * Math.sin(cone);
    result.x = radial * Math.cos(clock);
    result.y = radial * Math.sin(clock);
    result.z = magnitude * Math.cos(cone);
    return result;
  };

  /**
   * Creates a Cartesian3 instance from x, y and z coordinates.
   *
   * @param {Number} x The x coordinate.
   * @param {Number} y The y coordinate.
   * @param {Number} z The z coordinate.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
   */
  Cartesian3.fromElements = function (x, y, z, result) {
    if (!defined(result)) {
      return new Cartesian3(x, y, z);
    }

    result.x = x;
    result.y = y;
    result.z = z;
    return result;
  };

  /**
   * Duplicates a Cartesian3 instance.
   *
   * @param {Cartesian3} cartesian The Cartesian to duplicate.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided. (Returns undefined if cartesian is undefined)
   */
  Cartesian3.clone = function (cartesian, result) {
    if (!defined(cartesian)) {
      return undefined;
    }
    if (!defined(result)) {
      return new Cartesian3(cartesian.x, cartesian.y, cartesian.z);
    }

    result.x = cartesian.x;
    result.y = cartesian.y;
    result.z = cartesian.z;
    return result;
  };

  /**
   * Creates a Cartesian3 instance from an existing Cartesian4.  This simply takes the
   * x, y, and z properties of the Cartesian4 and drops w.
   * @function
   *
   * @param {Cartesian4} cartesian The Cartesian4 instance to create a Cartesian3 instance from.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
   */
  Cartesian3.fromCartesian4 = Cartesian3.clone;

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  Cartesian3.packedLength = 3;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {Cartesian3} 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
   */
  Cartesian3.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    array[startingIndex++] = value.x;
    array[startingIndex++] = value.y;
    array[startingIndex] = value.z;

    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 {Cartesian3} [result] The object into which to store the result.
   * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
   */
  Cartesian3.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    if (!defined(result)) {
      result = new Cartesian3();
    }
    result.x = array[startingIndex++];
    result.y = array[startingIndex++];
    result.z = array[startingIndex];
    return result;
  };

  /**
   * Flattens an array of Cartesian3s into an array of components.
   *
   * @param {Cartesian3[]} array The array of cartesians to pack.
   * @param {Number[]} [result] The array onto which to store the result. If this is a typed array, it must have array.length * 3 components, else a {@link DeveloperError} will be thrown. If it is a regular array, it will be resized to have (array.length * 3) elements.
   * @returns {Number[]} The packed array.
   */
  Cartesian3.packArray = function (array, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    const length = array.length;
    const resultLength = length * 3;
    if (!defined(result)) {
      result = new Array(resultLength);
    } else if (!Array.isArray(result) && result.length !== resultLength) {
      //>>includeStart('debug', pragmas.debug);
      throw new DeveloperError(
        "If result is a typed array, it must have exactly array.length * 3 elements"
      );
      //>>includeEnd('debug');
    } else if (result.length !== resultLength) {
      result.length = resultLength;
    }

    for (let i = 0; i < length; ++i) {
      Cartesian3.pack(array[i], result, i * 3);
    }
    return result;
  };

  /**
   * Unpacks an array of cartesian components into an array of Cartesian3s.
   *
   * @param {Number[]} array The array of components to unpack.
   * @param {Cartesian3[]} [result] The array onto which to store the result.
   * @returns {Cartesian3[]} The unpacked array.
   */
  Cartesian3.unpackArray = function (array, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    Check.typeOf.number.greaterThanOrEquals("array.length", array.length, 3);
    if (array.length % 3 !== 0) {
      throw new DeveloperError("array length must be a multiple of 3.");
    }
    //>>includeEnd('debug');

    const length = array.length;
    if (!defined(result)) {
      result = new Array(length / 3);
    } else {
      result.length = length / 3;
    }

    for (let i = 0; i < length; i += 3) {
      const index = i / 3;
      result[index] = Cartesian3.unpack(array, i, result[index]);
    }
    return result;
  };

  /**
   * Creates a Cartesian3 from three consecutive elements in an array.
   * @function
   *
   * @param {Number[]} array The array whose three consecutive elements correspond to the x, y, and z components, respectively.
   * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to the x component.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
   *
   * @example
   * // Create a Cartesian3 with (1.0, 2.0, 3.0)
   * const v = [1.0, 2.0, 3.0];
   * const p = Cesium.Cartesian3.fromArray(v);
   *
   * // Create a Cartesian3 with (1.0, 2.0, 3.0) using an offset into an array
   * const v2 = [0.0, 0.0, 1.0, 2.0, 3.0];
   * const p2 = Cesium.Cartesian3.fromArray(v2, 2);
   */
  Cartesian3.fromArray = Cartesian3.unpack;

  /**
   * Computes the value of the maximum component for the supplied Cartesian.
   *
   * @param {Cartesian3} cartesian The cartesian to use.
   * @returns {Number} The value of the maximum component.
   */
  Cartesian3.maximumComponent = function (cartesian) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartesian", cartesian);
    //>>includeEnd('debug');

    return Math.max(cartesian.x, cartesian.y, cartesian.z);
  };

  /**
   * Computes the value of the minimum component for the supplied Cartesian.
   *
   * @param {Cartesian3} cartesian The cartesian to use.
   * @returns {Number} The value of the minimum component.
   */
  Cartesian3.minimumComponent = function (cartesian) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartesian", cartesian);
    //>>includeEnd('debug');

    return Math.min(cartesian.x, cartesian.y, cartesian.z);
  };

  /**
   * Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
   *
   * @param {Cartesian3} first A cartesian to compare.
   * @param {Cartesian3} second A cartesian to compare.
   * @param {Cartesian3} result The object into which to store the result.
   * @returns {Cartesian3} A cartesian with the minimum components.
   */
  Cartesian3.minimumByComponent = function (first, second, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("first", first);
    Check.typeOf.object("second", second);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.x = Math.min(first.x, second.x);
    result.y = Math.min(first.y, second.y);
    result.z = Math.min(first.z, second.z);

    return result;
  };

  /**
   * Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
   *
   * @param {Cartesian3} first A cartesian to compare.
   * @param {Cartesian3} second A cartesian to compare.
   * @param {Cartesian3} result The object into which to store the result.
   * @returns {Cartesian3} A cartesian with the maximum components.
   */
  Cartesian3.maximumByComponent = function (first, second, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("first", first);
    Check.typeOf.object("second", second);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.x = Math.max(first.x, second.x);
    result.y = Math.max(first.y, second.y);
    result.z = Math.max(first.z, second.z);
    return result;
  };

  /**
   * Constrain a value to lie between two values.
   *
   * @param {Cartesian3} cartesian The value to clamp.
   * @param {Cartesian3} min The minimum bound.
   * @param {Cartesian3} max The maximum bound.
   * @param {Cartesian3} result The object into which to store the result.
   * @returns {Cartesian3} The clamped value such that min <= value <= max.
   */
  Cartesian3.clamp = function (value, min, max, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    Check.typeOf.object("min", min);
    Check.typeOf.object("max", max);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const x = CesiumMath.clamp(value.x, min.x, max.x);
    const y = CesiumMath.clamp(value.y, min.y, max.y);
    const z = CesiumMath.clamp(value.z, min.z, max.z);

    result.x = x;
    result.y = y;
    result.z = z;

    return result;
  };

  /**
   * Computes the provided Cartesian's squared magnitude.
   *
   * @param {Cartesian3} cartesian The Cartesian instance whose squared magnitude is to be computed.
   * @returns {Number} The squared magnitude.
   */
  Cartesian3.magnitudeSquared = function (cartesian) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartesian", cartesian);
    //>>includeEnd('debug');

    return (
      cartesian.x * cartesian.x +
      cartesian.y * cartesian.y +
      cartesian.z * cartesian.z
    );
  };

  /**
   * Computes the Cartesian's magnitude (length).
   *
   * @param {Cartesian3} cartesian The Cartesian instance whose magnitude is to be computed.
   * @returns {Number} The magnitude.
   */
  Cartesian3.magnitude = function (cartesian) {
    return Math.sqrt(Cartesian3.magnitudeSquared(cartesian));
  };

  const distanceScratch$3 = new Cartesian3();

  /**
   * Computes the distance between two points.
   *
   * @param {Cartesian3} left The first point to compute the distance from.
   * @param {Cartesian3} right The second point to compute the distance to.
   * @returns {Number} The distance between two points.
   *
   * @example
   * // Returns 1.0
   * const d = Cesium.Cartesian3.distance(new Cesium.Cartesian3(1.0, 0.0, 0.0), new Cesium.Cartesian3(2.0, 0.0, 0.0));
   */
  Cartesian3.distance = function (left, right) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    //>>includeEnd('debug');

    Cartesian3.subtract(left, right, distanceScratch$3);
    return Cartesian3.magnitude(distanceScratch$3);
  };

  /**
   * Computes the squared distance between two points.  Comparing squared distances
   * using this function is more efficient than comparing distances using {@link Cartesian3#distance}.
   *
   * @param {Cartesian3} left The first point to compute the distance from.
   * @param {Cartesian3} right The second point to compute the distance to.
   * @returns {Number} The distance between two points.
   *
   * @example
   * // Returns 4.0, not 2.0
   * const d = Cesium.Cartesian3.distanceSquared(new Cesium.Cartesian3(1.0, 0.0, 0.0), new Cesium.Cartesian3(3.0, 0.0, 0.0));
   */
  Cartesian3.distanceSquared = function (left, right) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    //>>includeEnd('debug');

    Cartesian3.subtract(left, right, distanceScratch$3);
    return Cartesian3.magnitudeSquared(distanceScratch$3);
  };

  /**
   * Computes the normalized form of the supplied Cartesian.
   *
   * @param {Cartesian3} cartesian The Cartesian to be normalized.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter.
   */
  Cartesian3.normalize = function (cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const magnitude = Cartesian3.magnitude(cartesian);

    result.x = cartesian.x / magnitude;
    result.y = cartesian.y / magnitude;
    result.z = cartesian.z / magnitude;

    //>>includeStart('debug', pragmas.debug);
    if (isNaN(result.x) || isNaN(result.y) || isNaN(result.z)) {
      throw new DeveloperError("normalized result is not a number");
    }
    //>>includeEnd('debug');

    return result;
  };

  /**
   * Computes the dot (scalar) product of two Cartesians.
   *
   * @param {Cartesian3} left The first Cartesian.
   * @param {Cartesian3} right The second Cartesian.
   * @returns {Number} The dot product.
   */
  Cartesian3.dot = function (left, right) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    //>>includeEnd('debug');

    return left.x * right.x + left.y * right.y + left.z * right.z;
  };

  /**
   * Computes the componentwise product of two Cartesians.
   *
   * @param {Cartesian3} left The first Cartesian.
   * @param {Cartesian3} right The second Cartesian.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter.
   */
  Cartesian3.multiplyComponents = function (left, right, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    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;
    return result;
  };

  /**
   * Computes the componentwise quotient of two Cartesians.
   *
   * @param {Cartesian3} left The first Cartesian.
   * @param {Cartesian3} right The second Cartesian.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter.
   */
  Cartesian3.divideComponents = function (left, right, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    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;
    return result;
  };

  /**
   * Computes the componentwise sum of two Cartesians.
   *
   * @param {Cartesian3} left The first Cartesian.
   * @param {Cartesian3} right The second Cartesian.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter.
   */
  Cartesian3.add = function (left, right, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    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;
    return result;
  };

  /**
   * Computes the componentwise difference of two Cartesians.
   *
   * @param {Cartesian3} left The first Cartesian.
   * @param {Cartesian3} right The second Cartesian.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter.
   */
  Cartesian3.subtract = function (left, right, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    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;
    return result;
  };

  /**
   * Multiplies the provided Cartesian componentwise by the provided scalar.
   *
   * @param {Cartesian3} cartesian The Cartesian to be scaled.
   * @param {Number} scalar The scalar to multiply with.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter.
   */
  Cartesian3.multiplyByScalar = function (cartesian, scalar, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.number("scalar", scalar);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.x = cartesian.x * scalar;
    result.y = cartesian.y * scalar;
    result.z = cartesian.z * scalar;
    return result;
  };

  /**
   * Divides the provided Cartesian componentwise by the provided scalar.
   *
   * @param {Cartesian3} cartesian The Cartesian to be divided.
   * @param {Number} scalar The scalar to divide by.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter.
   */
  Cartesian3.divideByScalar = function (cartesian, scalar, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.number("scalar", scalar);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.x = cartesian.x / scalar;
    result.y = cartesian.y / scalar;
    result.z = cartesian.z / scalar;
    return result;
  };

  /**
   * Negates the provided Cartesian.
   *
   * @param {Cartesian3} cartesian The Cartesian to be negated.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter.
   */
  Cartesian3.negate = function (cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.x = -cartesian.x;
    result.y = -cartesian.y;
    result.z = -cartesian.z;
    return result;
  };

  /**
   * Computes the absolute value of the provided Cartesian.
   *
   * @param {Cartesian3} cartesian The Cartesian whose absolute value is to be computed.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter.
   */
  Cartesian3.abs = function (cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.x = Math.abs(cartesian.x);
    result.y = Math.abs(cartesian.y);
    result.z = Math.abs(cartesian.z);
    return result;
  };

  const lerpScratch$3 = new Cartesian3();
  /**
   * Computes the linear interpolation or extrapolation at t using the provided cartesians.
   *
   * @param {Cartesian3} start The value corresponding to t at 0.0.
   * @param {Cartesian3} end The value corresponding to t at 1.0.
   * @param {Number} t The point along t at which to interpolate.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter.
   */
  Cartesian3.lerp = function (start, end, t, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("start", start);
    Check.typeOf.object("end", end);
    Check.typeOf.number("t", t);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    Cartesian3.multiplyByScalar(end, t, lerpScratch$3);
    result = Cartesian3.multiplyByScalar(start, 1.0 - t, result);
    return Cartesian3.add(lerpScratch$3, result, result);
  };

  const angleBetweenScratch$1 = new Cartesian3();
  const angleBetweenScratch2$1 = new Cartesian3();
  /**
   * Returns the angle, in radians, between the provided Cartesians.
   *
   * @param {Cartesian3} left The first Cartesian.
   * @param {Cartesian3} right The second Cartesian.
   * @returns {Number} The angle between the Cartesians.
   */
  Cartesian3.angleBetween = function (left, right) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    //>>includeEnd('debug');

    Cartesian3.normalize(left, angleBetweenScratch$1);
    Cartesian3.normalize(right, angleBetweenScratch2$1);
    const cosine = Cartesian3.dot(angleBetweenScratch$1, angleBetweenScratch2$1);
    const sine = Cartesian3.magnitude(
      Cartesian3.cross(
        angleBetweenScratch$1,
        angleBetweenScratch2$1,
        angleBetweenScratch$1
      )
    );
    return Math.atan2(sine, cosine);
  };

  const mostOrthogonalAxisScratch$2 = new Cartesian3();
  /**
   * Returns the axis that is most orthogonal to the provided Cartesian.
   *
   * @param {Cartesian3} cartesian The Cartesian on which to find the most orthogonal axis.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The most orthogonal axis.
   */
  Cartesian3.mostOrthogonalAxis = function (cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const f = Cartesian3.normalize(cartesian, mostOrthogonalAxisScratch$2);
    Cartesian3.abs(f, f);

    if (f.x <= f.y) {
      if (f.x <= f.z) {
        result = Cartesian3.clone(Cartesian3.UNIT_X, result);
      } else {
        result = Cartesian3.clone(Cartesian3.UNIT_Z, result);
      }
    } else if (f.y <= f.z) {
      result = Cartesian3.clone(Cartesian3.UNIT_Y, result);
    } else {
      result = Cartesian3.clone(Cartesian3.UNIT_Z, result);
    }

    return result;
  };

  /**
   * Projects vector a onto vector b
   * @param {Cartesian3} a The vector that needs projecting
   * @param {Cartesian3} b The vector to project onto
   * @param {Cartesian3} result The result cartesian
   * @returns {Cartesian3} The modified result parameter
   */
  Cartesian3.projectVector = function (a, b, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("a", a);
    Check.defined("b", b);
    Check.defined("result", result);
    //>>includeEnd('debug');

    const scalar = Cartesian3.dot(a, b) / Cartesian3.dot(b, b);
    return Cartesian3.multiplyByScalar(b, scalar, result);
  };

  /**
   * Compares the provided Cartesians componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Cartesian3} [left] The first Cartesian.
   * @param {Cartesian3} [right] The second Cartesian.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  Cartesian3.equals = function (left, right) {
    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        left.x === right.x &&
        left.y === right.y &&
        left.z === right.z)
    );
  };

  /**
   * @private
   */
  Cartesian3.equalsArray = function (cartesian, array, offset) {
    return (
      cartesian.x === array[offset] &&
      cartesian.y === array[offset + 1] &&
      cartesian.z === array[offset + 2]
    );
  };

  /**
   * Compares the provided Cartesians componentwise and returns
   * <code>true</code> if they pass an absolute or relative tolerance test,
   * <code>false</code> otherwise.
   *
   * @param {Cartesian3} [left] The first Cartesian.
   * @param {Cartesian3} [right] The second Cartesian.
   * @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} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
   */
  Cartesian3.equalsEpsilon = function (
    left,
    right,
    relativeEpsilon,
    absoluteEpsilon
  ) {
    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        CesiumMath.equalsEpsilon(
          left.x,
          right.x,
          relativeEpsilon,
          absoluteEpsilon
        ) &&
        CesiumMath.equalsEpsilon(
          left.y,
          right.y,
          relativeEpsilon,
          absoluteEpsilon
        ) &&
        CesiumMath.equalsEpsilon(
          left.z,
          right.z,
          relativeEpsilon,
          absoluteEpsilon
        ))
    );
  };

  /**
   * Computes the cross (outer) product of two Cartesians.
   *
   * @param {Cartesian3} left The first Cartesian.
   * @param {Cartesian3} right The second Cartesian.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The cross product.
   */
  Cartesian3.cross = function (left, right, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const leftX = left.x;
    const leftY = left.y;
    const leftZ = left.z;
    const rightX = right.x;
    const rightY = right.y;
    const rightZ = right.z;

    const x = leftY * rightZ - leftZ * rightY;
    const y = leftZ * rightX - leftX * rightZ;
    const z = leftX * rightY - leftY * rightX;

    result.x = x;
    result.y = y;
    result.z = z;
    return result;
  };

  /**
   * Computes the midpoint between the right and left Cartesian.
   * @param {Cartesian3} left The first Cartesian.
   * @param {Cartesian3} right The second Cartesian.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The midpoint.
   */
  Cartesian3.midpoint = function (left, right, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.x = (left.x + right.x) * 0.5;
    result.y = (left.y + right.y) * 0.5;
    result.z = (left.z + right.z) * 0.5;

    return result;
  };

  /**
   * Returns a Cartesian3 position from longitude and latitude values given in degrees.
   *
   * @param {Number} longitude The longitude, in degrees
   * @param {Number} latitude The latitude, in degrees
   * @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} The position
   *
   * @example
   * const position = Cesium.Cartesian3.fromDegrees(-115.0, 37.0);
   */
  Cartesian3.fromDegrees = function (
    longitude,
    latitude,
    height,
    ellipsoid,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("longitude", longitude);
    Check.typeOf.number("latitude", latitude);
    //>>includeEnd('debug');

    longitude = CesiumMath.toRadians(longitude);
    latitude = CesiumMath.toRadians(latitude);
    return Cartesian3.fromRadians(longitude, latitude, height, ellipsoid, result);
  };

  let scratchN = new Cartesian3();
  let scratchK = new Cartesian3();
  const wgs84RadiiSquared = new Cartesian3(
    6378137.0 * 6378137.0,
    6378137.0 * 6378137.0,
    6356752.3142451793 * 6356752.3142451793
  );

  /**
   * Returns a Cartesian3 position from longitude and latitude values given in radians.
   *
   * @param {Number} longitude The longitude, in radians
   * @param {Number} latitude The latitude, in radians
   * @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} The position
   *
   * @example
   * const position = Cesium.Cartesian3.fromRadians(-2.007, 0.645);
   */
  Cartesian3.fromRadians = function (
    longitude,
    latitude,
    height,
    ellipsoid,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("longitude", longitude);
    Check.typeOf.number("latitude", latitude);
    //>>includeEnd('debug');

    height = defaultValue(height, 0.0);
    const radiiSquared = defined(ellipsoid)
      ? ellipsoid.radiiSquared
      : wgs84RadiiSquared;

    const cosLatitude = Math.cos(latitude);
    scratchN.x = cosLatitude * Math.cos(longitude);
    scratchN.y = cosLatitude * Math.sin(longitude);
    scratchN.z = Math.sin(latitude);
    scratchN = Cartesian3.normalize(scratchN, scratchN);

    Cartesian3.multiplyComponents(radiiSquared, scratchN, scratchK);
    const gamma = Math.sqrt(Cartesian3.dot(scratchN, scratchK));
    scratchK = Cartesian3.divideByScalar(scratchK, gamma, scratchK);
    scratchN = Cartesian3.multiplyByScalar(scratchN, height, scratchN);

    if (!defined(result)) {
      result = new Cartesian3();
    }
    return Cartesian3.add(scratchK, scratchN, result);
  };

  /**
   * Returns an array of Cartesian3 positions given an array of longitude and latitude values given in degrees.
   *
   * @param {Number[]} coordinates A list of longitude and latitude values. Values alternate [longitude, latitude, longitude, latitude...].
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the coordinates lie.
   * @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
   * @returns {Cartesian3[]} The array of positions.
   *
   * @example
   * const positions = Cesium.Cartesian3.fromDegreesArray([-115.0, 37.0, -107.0, 33.0]);
   */
  Cartesian3.fromDegreesArray = function (coordinates, ellipsoid, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("coordinates", coordinates);
    if (coordinates.length < 2 || coordinates.length % 2 !== 0) {
      throw new DeveloperError(
        "the number of coordinates must be a multiple of 2 and at least 2"
      );
    }
    //>>includeEnd('debug');

    const length = coordinates.length;
    if (!defined(result)) {
      result = new Array(length / 2);
    } else {
      result.length = length / 2;
    }

    for (let i = 0; i < length; i += 2) {
      const longitude = coordinates[i];
      const latitude = coordinates[i + 1];
      const index = i / 2;
      result[index] = Cartesian3.fromDegrees(
        longitude,
        latitude,
        0,
        ellipsoid,
        result[index]
      );
    }

    return result;
  };

  /**
   * Returns an array of Cartesian3 positions given an array of longitude and latitude values given in radians.
   *
   * @param {Number[]} coordinates A list of longitude and latitude values. Values alternate [longitude, latitude, longitude, latitude...].
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the coordinates lie.
   * @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
   * @returns {Cartesian3[]} The array of positions.
   *
   * @example
   * const positions = Cesium.Cartesian3.fromRadiansArray([-2.007, 0.645, -1.867, .575]);
   */
  Cartesian3.fromRadiansArray = function (coordinates, ellipsoid, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("coordinates", coordinates);
    if (coordinates.length < 2 || coordinates.length % 2 !== 0) {
      throw new DeveloperError(
        "the number of coordinates must be a multiple of 2 and at least 2"
      );
    }
    //>>includeEnd('debug');

    const length = coordinates.length;
    if (!defined(result)) {
      result = new Array(length / 2);
    } else {
      result.length = length / 2;
    }

    for (let i = 0; i < length; i += 2) {
      const longitude = coordinates[i];
      const latitude = coordinates[i + 1];
      const index = i / 2;
      result[index] = Cartesian3.fromRadians(
        longitude,
        latitude,
        0,
        ellipsoid,
        result[index]
      );
    }

    return result;
  };

  /**
   * Returns an array of Cartesian3 positions given an array of longitude, latitude and height values where longitude and latitude are given in degrees.
   *
   * @param {Number[]} coordinates A list of longitude, latitude and height values. Values alternate [longitude, latitude, height, longitude, latitude, height...].
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
   * @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
   * @returns {Cartesian3[]} The array of positions.
   *
   * @example
   * const positions = Cesium.Cartesian3.fromDegreesArrayHeights([-115.0, 37.0, 100000.0, -107.0, 33.0, 150000.0]);
   */
  Cartesian3.fromDegreesArrayHeights = function (coordinates, ellipsoid, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("coordinates", coordinates);
    if (coordinates.length < 3 || coordinates.length % 3 !== 0) {
      throw new DeveloperError(
        "the number of coordinates must be a multiple of 3 and at least 3"
      );
    }
    //>>includeEnd('debug');

    const length = coordinates.length;
    if (!defined(result)) {
      result = new Array(length / 3);
    } else {
      result.length = length / 3;
    }

    for (let i = 0; i < length; i += 3) {
      const longitude = coordinates[i];
      const latitude = coordinates[i + 1];
      const height = coordinates[i + 2];
      const index = i / 3;
      result[index] = Cartesian3.fromDegrees(
        longitude,
        latitude,
        height,
        ellipsoid,
        result[index]
      );
    }

    return result;
  };

  /**
   * Returns an array of Cartesian3 positions given an array of longitude, latitude and height values where longitude and latitude are given in radians.
   *
   * @param {Number[]} coordinates A list of longitude, latitude and height values. Values alternate [longitude, latitude, height, longitude, latitude, height...].
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
   * @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
   * @returns {Cartesian3[]} The array of positions.
   *
   * @example
   * const positions = Cesium.Cartesian3.fromRadiansArrayHeights([-2.007, 0.645, 100000.0, -1.867, .575, 150000.0]);
   */
  Cartesian3.fromRadiansArrayHeights = function (coordinates, ellipsoid, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("coordinates", coordinates);
    if (coordinates.length < 3 || coordinates.length % 3 !== 0) {
      throw new DeveloperError(
        "the number of coordinates must be a multiple of 3 and at least 3"
      );
    }
    //>>includeEnd('debug');

    const length = coordinates.length;
    if (!defined(result)) {
      result = new Array(length / 3);
    } else {
      result.length = length / 3;
    }

    for (let i = 0; i < length; i += 3) {
      const longitude = coordinates[i];
      const latitude = coordinates[i + 1];
      const height = coordinates[i + 2];
      const index = i / 3;
      result[index] = Cartesian3.fromRadians(
        longitude,
        latitude,
        height,
        ellipsoid,
        result[index]
      );
    }

    return result;
  };

  /**
   * An immutable Cartesian3 instance initialized to (0.0, 0.0, 0.0).
   *
   * @type {Cartesian3}
   * @constant
   */
  Cartesian3.ZERO = Object.freeze(new Cartesian3(0.0, 0.0, 0.0));

  /**
   * An immutable Cartesian3 instance initialized to (1.0, 1.0, 1.0).
   *
   * @type {Cartesian3}
   * @constant
   */
  Cartesian3.ONE = Object.freeze(new Cartesian3(1.0, 1.0, 1.0));

  /**
   * An immutable Cartesian3 instance initialized to (1.0, 0.0, 0.0).
   *
   * @type {Cartesian3}
   * @constant
   */
  Cartesian3.UNIT_X = Object.freeze(new Cartesian3(1.0, 0.0, 0.0));

  /**
   * An immutable Cartesian3 instance initialized to (0.0, 1.0, 0.0).
   *
   * @type {Cartesian3}
   * @constant
   */
  Cartesian3.UNIT_Y = Object.freeze(new Cartesian3(0.0, 1.0, 0.0));

  /**
   * An immutable Cartesian3 instance initialized to (0.0, 0.0, 1.0).
   *
   * @type {Cartesian3}
   * @constant
   */
  Cartesian3.UNIT_Z = Object.freeze(new Cartesian3(0.0, 0.0, 1.0));

  /**
   * Duplicates this Cartesian3 instance.
   *
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
   */
  Cartesian3.prototype.clone = function (result) {
    return Cartesian3.clone(this, result);
  };

  /**
   * Compares this Cartesian against the provided Cartesian componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Cartesian3} [right] The right hand side Cartesian.
   * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
   */
  Cartesian3.prototype.equals = function (right) {
    return Cartesian3.equals(this, right);
  };

  /**
   * Compares this Cartesian against the provided Cartesian componentwise and returns
   * <code>true</code> if they pass an absolute or relative tolerance test,
   * <code>false</code> otherwise.
   *
   * @param {Cartesian3} [right] The right hand side Cartesian.
   * @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} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
   */
  Cartesian3.prototype.equalsEpsilon = function (
    right,
    relativeEpsilon,
    absoluteEpsilon
  ) {
    return Cartesian3.equalsEpsilon(
      this,
      right,
      relativeEpsilon,
      absoluteEpsilon
    );
  };

  /**
   * Creates a string representing this Cartesian in the format '(x, y, z)'.
   *
   * @returns {String} A string representing this Cartesian in the format '(x, y, z)'.
   */
  Cartesian3.prototype.toString = function () {
    return `(${this.x}, ${this.y}, ${this.z})`;
  };

  const scaleToGeodeticSurfaceIntersection = new Cartesian3();
  const scaleToGeodeticSurfaceGradient = new Cartesian3();

  /**
   * Scales the provided Cartesian position along the geodetic surface normal
   * so that it is on the surface of this ellipsoid.  If the position is
   * at the center of the ellipsoid, this function returns undefined.
   *
   * @param {Cartesian3} cartesian The Cartesian position to scale.
   * @param {Cartesian3} oneOverRadii One over radii of the ellipsoid.
   * @param {Cartesian3} oneOverRadiiSquared One over radii squared of the ellipsoid.
   * @param {Number} centerToleranceSquared Tolerance for closeness to the center.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter, a new Cartesian3 instance if none was provided, or undefined if the position is at the center.
   *
   * @function scaleToGeodeticSurface
   *
   * @private
   */
  function scaleToGeodeticSurface(
    cartesian,
    oneOverRadii,
    oneOverRadiiSquared,
    centerToleranceSquared,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(cartesian)) {
      throw new DeveloperError("cartesian is required.");
    }
    if (!defined(oneOverRadii)) {
      throw new DeveloperError("oneOverRadii is required.");
    }
    if (!defined(oneOverRadiiSquared)) {
      throw new DeveloperError("oneOverRadiiSquared is required.");
    }
    if (!defined(centerToleranceSquared)) {
      throw new DeveloperError("centerToleranceSquared is required.");
    }
    //>>includeEnd('debug');

    const positionX = cartesian.x;
    const positionY = cartesian.y;
    const positionZ = cartesian.z;

    const oneOverRadiiX = oneOverRadii.x;
    const oneOverRadiiY = oneOverRadii.y;
    const oneOverRadiiZ = oneOverRadii.z;

    const x2 = positionX * positionX * oneOverRadiiX * oneOverRadiiX;
    const y2 = positionY * positionY * oneOverRadiiY * oneOverRadiiY;
    const z2 = positionZ * positionZ * oneOverRadiiZ * oneOverRadiiZ;

    // Compute the squared ellipsoid norm.
    const squaredNorm = x2 + y2 + z2;
    const ratio = Math.sqrt(1.0 / squaredNorm);

    // As an initial approximation, assume that the radial intersection is the projection point.
    const intersection = Cartesian3.multiplyByScalar(
      cartesian,
      ratio,
      scaleToGeodeticSurfaceIntersection
    );

    // If the position is near the center, the iteration will not converge.
    if (squaredNorm < centerToleranceSquared) {
      return !isFinite(ratio)
        ? undefined
        : Cartesian3.clone(intersection, result);
    }

    const oneOverRadiiSquaredX = oneOverRadiiSquared.x;
    const oneOverRadiiSquaredY = oneOverRadiiSquared.y;
    const oneOverRadiiSquaredZ = oneOverRadiiSquared.z;

    // Use the gradient at the intersection point in place of the true unit normal.
    // The difference in magnitude will be absorbed in the multiplier.
    const gradient = scaleToGeodeticSurfaceGradient;
    gradient.x = intersection.x * oneOverRadiiSquaredX * 2.0;
    gradient.y = intersection.y * oneOverRadiiSquaredY * 2.0;
    gradient.z = intersection.z * oneOverRadiiSquaredZ * 2.0;

    // Compute the initial guess at the normal vector multiplier, lambda.
    let lambda =
      ((1.0 - ratio) * Cartesian3.magnitude(cartesian)) /
      (0.5 * Cartesian3.magnitude(gradient));
    let correction = 0.0;

    let func;
    let denominator;
    let xMultiplier;
    let yMultiplier;
    let zMultiplier;
    let xMultiplier2;
    let yMultiplier2;
    let zMultiplier2;
    let xMultiplier3;
    let yMultiplier3;
    let zMultiplier3;

    do {
      lambda -= correction;

      xMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredX);
      yMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredY);
      zMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredZ);

      xMultiplier2 = xMultiplier * xMultiplier;
      yMultiplier2 = yMultiplier * yMultiplier;
      zMultiplier2 = zMultiplier * zMultiplier;

      xMultiplier3 = xMultiplier2 * xMultiplier;
      yMultiplier3 = yMultiplier2 * yMultiplier;
      zMultiplier3 = zMultiplier2 * zMultiplier;

      func = x2 * xMultiplier2 + y2 * yMultiplier2 + z2 * zMultiplier2 - 1.0;

      // "denominator" here refers to the use of this expression in the velocity and acceleration
      // computations in the sections to follow.
      denominator =
        x2 * xMultiplier3 * oneOverRadiiSquaredX +
        y2 * yMultiplier3 * oneOverRadiiSquaredY +
        z2 * zMultiplier3 * oneOverRadiiSquaredZ;

      const derivative = -2.0 * denominator;

      correction = func / derivative;
    } while (Math.abs(func) > CesiumMath.EPSILON12);

    if (!defined(result)) {
      return new Cartesian3(
        positionX * xMultiplier,
        positionY * yMultiplier,
        positionZ * zMultiplier
      );
    }
    result.x = positionX * xMultiplier;
    result.y = positionY * yMultiplier;
    result.z = positionZ * zMultiplier;
    return result;
  }

  /**
   * A position defined by longitude, latitude, and height.
   * @alias Cartographic
   * @constructor
   *
   * @param {Number} [longitude=0.0] The longitude, in radians.
   * @param {Number} [latitude=0.0] The latitude, in radians.
   * @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
   *
   * @see Ellipsoid
   */
  function Cartographic(longitude, latitude, height) {
    /**
     * The longitude, in radians.
     * @type {Number}
     * @default 0.0
     */
    this.longitude = defaultValue(longitude, 0.0);

    /**
     * The latitude, in radians.
     * @type {Number}
     * @default 0.0
     */
    this.latitude = defaultValue(latitude, 0.0);

    /**
     * The height, in meters, above the ellipsoid.
     * @type {Number}
     * @default 0.0
     */
    this.height = defaultValue(height, 0.0);
  }

  /**
   * Creates a new Cartographic instance from longitude and latitude
   * specified in radians.
   *
   * @param {Number} longitude The longitude, in radians.
   * @param {Number} latitude The latitude, in radians.
   * @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
   * @param {Cartographic} [result] The object onto which to store the result.
   * @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided.
   */
  Cartographic.fromRadians = function (longitude, latitude, height, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("longitude", longitude);
    Check.typeOf.number("latitude", latitude);
    //>>includeEnd('debug');

    height = defaultValue(height, 0.0);

    if (!defined(result)) {
      return new Cartographic(longitude, latitude, height);
    }

    result.longitude = longitude;
    result.latitude = latitude;
    result.height = height;
    return result;
  };

  /**
   * Creates a new Cartographic instance from longitude and latitude
   * specified in degrees.  The values in the resulting object will
   * be in radians.
   *
   * @param {Number} longitude The longitude, in degrees.
   * @param {Number} latitude The latitude, in degrees.
   * @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
   * @param {Cartographic} [result] The object onto which to store the result.
   * @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided.
   */
  Cartographic.fromDegrees = function (longitude, latitude, height, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("longitude", longitude);
    Check.typeOf.number("latitude", latitude);
    //>>includeEnd('debug');
    longitude = CesiumMath.toRadians(longitude);
    latitude = CesiumMath.toRadians(latitude);

    return Cartographic.fromRadians(longitude, latitude, height, result);
  };

  const cartesianToCartographicN$1 = new Cartesian3();
  const cartesianToCartographicP$1 = new Cartesian3();
  const cartesianToCartographicH$1 = new Cartesian3();
  const wgs84OneOverRadii = new Cartesian3(
    1.0 / 6378137.0,
    1.0 / 6378137.0,
    1.0 / 6356752.3142451793
  );
  const wgs84OneOverRadiiSquared = new Cartesian3(
    1.0 / (6378137.0 * 6378137.0),
    1.0 / (6378137.0 * 6378137.0),
    1.0 / (6356752.3142451793 * 6356752.3142451793)
  );
  const wgs84CenterToleranceSquared = CesiumMath.EPSILON1;

  /**
   * Creates a new Cartographic instance from a Cartesian position. The values in the
   * resulting object will be in radians.
   *
   * @param {Cartesian3} cartesian The Cartesian position to convert to cartographic representation.
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
   * @param {Cartographic} [result] The object onto which to store the result.
   * @returns {Cartographic} The modified result parameter, new Cartographic instance if none was provided, or undefined if the cartesian is at the center of the ellipsoid.
   */
  Cartographic.fromCartesian = function (cartesian, ellipsoid, result) {
    const oneOverRadii = defined(ellipsoid)
      ? ellipsoid.oneOverRadii
      : wgs84OneOverRadii;
    const oneOverRadiiSquared = defined(ellipsoid)
      ? ellipsoid.oneOverRadiiSquared
      : wgs84OneOverRadiiSquared;
    const centerToleranceSquared = defined(ellipsoid)
      ? ellipsoid._centerToleranceSquared
      : wgs84CenterToleranceSquared;

    //`cartesian is required.` is thrown from scaleToGeodeticSurface
    const p = scaleToGeodeticSurface(
      cartesian,
      oneOverRadii,
      oneOverRadiiSquared,
      centerToleranceSquared,
      cartesianToCartographicP$1
    );

    if (!defined(p)) {
      return undefined;
    }

    let n = Cartesian3.multiplyComponents(
      p,
      oneOverRadiiSquared,
      cartesianToCartographicN$1
    );
    n = Cartesian3.normalize(n, n);

    const h = Cartesian3.subtract(cartesian, p, cartesianToCartographicH$1);

    const longitude = Math.atan2(n.y, n.x);
    const latitude = Math.asin(n.z);
    const height =
      CesiumMath.sign(Cartesian3.dot(h, cartesian)) * Cartesian3.magnitude(h);

    if (!defined(result)) {
      return new Cartographic(longitude, latitude, height);
    }
    result.longitude = longitude;
    result.latitude = latitude;
    result.height = height;
    return result;
  };

  /**
   * Creates a new Cartesian3 instance from a Cartographic input. The values in the inputted
   * object should be in radians.
   *
   * @param {Cartographic} cartographic Input to be converted into a Cartesian3 output.
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} The position
   */
  Cartographic.toCartesian = function (cartographic, ellipsoid, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("cartographic", cartographic);
    //>>includeEnd('debug');

    return Cartesian3.fromRadians(
      cartographic.longitude,
      cartographic.latitude,
      cartographic.height,
      ellipsoid,
      result
    );
  };

  /**
   * Duplicates a Cartographic instance.
   *
   * @param {Cartographic} cartographic The cartographic to duplicate.
   * @param {Cartographic} [result] The object onto which to store the result.
   * @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided. (Returns undefined if cartographic is undefined)
   */
  Cartographic.clone = function (cartographic, result) {
    if (!defined(cartographic)) {
      return undefined;
    }
    if (!defined(result)) {
      return new Cartographic(
        cartographic.longitude,
        cartographic.latitude,
        cartographic.height
      );
    }
    result.longitude = cartographic.longitude;
    result.latitude = cartographic.latitude;
    result.height = cartographic.height;
    return result;
  };

  /**
   * Compares the provided cartographics componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Cartographic} [left] The first cartographic.
   * @param {Cartographic} [right] The second cartographic.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  Cartographic.equals = function (left, right) {
    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        left.longitude === right.longitude &&
        left.latitude === right.latitude &&
        left.height === right.height)
    );
  };

  /**
   * Compares the provided cartographics componentwise and returns
   * <code>true</code> if they are within the provided epsilon,
   * <code>false</code> otherwise.
   *
   * @param {Cartographic} [left] The first cartographic.
   * @param {Cartographic} [right] The second cartographic.
   * @param {Number} [epsilon=0] The epsilon to use for equality testing.
   * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
   */
  Cartographic.equalsEpsilon = function (left, right, epsilon) {
    epsilon = defaultValue(epsilon, 0);

    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        Math.abs(left.longitude - right.longitude) <= epsilon &&
        Math.abs(left.latitude - right.latitude) <= epsilon &&
        Math.abs(left.height - right.height) <= epsilon)
    );
  };

  /**
   * An immutable Cartographic instance initialized to (0.0, 0.0, 0.0).
   *
   * @type {Cartographic}
   * @constant
   */
  Cartographic.ZERO = Object.freeze(new Cartographic(0.0, 0.0, 0.0));

  /**
   * Duplicates this instance.
   *
   * @param {Cartographic} [result] The object onto which to store the result.
   * @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided.
   */
  Cartographic.prototype.clone = function (result) {
    return Cartographic.clone(this, result);
  };

  /**
   * Compares the provided against this cartographic componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Cartographic} [right] The second cartographic.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  Cartographic.prototype.equals = function (right) {
    return Cartographic.equals(this, right);
  };

  /**
   * Compares the provided against this cartographic componentwise and returns
   * <code>true</code> if they are within the provided epsilon,
   * <code>false</code> otherwise.
   *
   * @param {Cartographic} [right] The second cartographic.
   * @param {Number} [epsilon=0] The epsilon to use for equality testing.
   * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
   */
  Cartographic.prototype.equalsEpsilon = function (right, epsilon) {
    return Cartographic.equalsEpsilon(this, right, epsilon);
  };

  /**
   * Creates a string representing this cartographic in the format '(longitude, latitude, height)'.
   *
   * @returns {String} A string representing the provided cartographic in the format '(longitude, latitude, height)'.
   */
  Cartographic.prototype.toString = function () {
    return `(${this.longitude}, ${this.latitude}, ${this.height})`;
  };

  function initialize$p(ellipsoid, x, y, z) {
    x = defaultValue(x, 0.0);
    y = defaultValue(y, 0.0);
    z = defaultValue(z, 0.0);

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number.greaterThanOrEquals("x", x, 0.0);
    Check.typeOf.number.greaterThanOrEquals("y", y, 0.0);
    Check.typeOf.number.greaterThanOrEquals("z", z, 0.0);
    //>>includeEnd('debug');

    ellipsoid._radii = new Cartesian3(x, y, z);

    ellipsoid._radiiSquared = new Cartesian3(x * x, y * y, z * z);

    ellipsoid._radiiToTheFourth = new Cartesian3(
      x * x * x * x,
      y * y * y * y,
      z * z * z * z
    );

    ellipsoid._oneOverRadii = new Cartesian3(
      x === 0.0 ? 0.0 : 1.0 / x,
      y === 0.0 ? 0.0 : 1.0 / y,
      z === 0.0 ? 0.0 : 1.0 / z
    );

    ellipsoid._oneOverRadiiSquared = new Cartesian3(
      x === 0.0 ? 0.0 : 1.0 / (x * x),
      y === 0.0 ? 0.0 : 1.0 / (y * y),
      z === 0.0 ? 0.0 : 1.0 / (z * z)
    );

    ellipsoid._minimumRadius = Math.min(x, y, z);

    ellipsoid._maximumRadius = Math.max(x, y, z);

    ellipsoid._centerToleranceSquared = CesiumMath.EPSILON1;

    if (ellipsoid._radiiSquared.z !== 0) {
      ellipsoid._squaredXOverSquaredZ =
        ellipsoid._radiiSquared.x / ellipsoid._radiiSquared.z;
    }
  }

  /**
   * A quadratic surface defined in Cartesian coordinates by the equation
   * <code>(x / a)^2 + (y / b)^2 + (z / c)^2 = 1</code>.  Primarily used
   * by Cesium to represent the shape of planetary bodies.
   *
   * Rather than constructing this object directly, one of the provided
   * constants is normally used.
   * @alias Ellipsoid
   * @constructor
   *
   * @param {Number} [x=0] The radius in the x direction.
   * @param {Number} [y=0] The radius in the y direction.
   * @param {Number} [z=0] The radius in the z direction.
   *
   * @exception {DeveloperError} All radii components must be greater than or equal to zero.
   *
   * @see Ellipsoid.fromCartesian3
   * @see Ellipsoid.WGS84
   * @see Ellipsoid.UNIT_SPHERE
   */
  function Ellipsoid(x, y, z) {
    this._radii = undefined;
    this._radiiSquared = undefined;
    this._radiiToTheFourth = undefined;
    this._oneOverRadii = undefined;
    this._oneOverRadiiSquared = undefined;
    this._minimumRadius = undefined;
    this._maximumRadius = undefined;
    this._centerToleranceSquared = undefined;
    this._squaredXOverSquaredZ = undefined;

    initialize$p(this, x, y, z);
  }

  Object.defineProperties(Ellipsoid.prototype, {
    /**
     * Gets the radii of the ellipsoid.
     * @memberof Ellipsoid.prototype
     * @type {Cartesian3}
     * @readonly
     */
    radii: {
      get: function () {
        return this._radii;
      },
    },
    /**
     * Gets the squared radii of the ellipsoid.
     * @memberof Ellipsoid.prototype
     * @type {Cartesian3}
     * @readonly
     */
    radiiSquared: {
      get: function () {
        return this._radiiSquared;
      },
    },
    /**
     * Gets the radii of the ellipsoid raise to the fourth power.
     * @memberof Ellipsoid.prototype
     * @type {Cartesian3}
     * @readonly
     */
    radiiToTheFourth: {
      get: function () {
        return this._radiiToTheFourth;
      },
    },
    /**
     * Gets one over the radii of the ellipsoid.
     * @memberof Ellipsoid.prototype
     * @type {Cartesian3}
     * @readonly
     */
    oneOverRadii: {
      get: function () {
        return this._oneOverRadii;
      },
    },
    /**
     * Gets one over the squared radii of the ellipsoid.
     * @memberof Ellipsoid.prototype
     * @type {Cartesian3}
     * @readonly
     */
    oneOverRadiiSquared: {
      get: function () {
        return this._oneOverRadiiSquared;
      },
    },
    /**
     * Gets the minimum radius of the ellipsoid.
     * @memberof Ellipsoid.prototype
     * @type {Number}
     * @readonly
     */
    minimumRadius: {
      get: function () {
        return this._minimumRadius;
      },
    },
    /**
     * Gets the maximum radius of the ellipsoid.
     * @memberof Ellipsoid.prototype
     * @type {Number}
     * @readonly
     */
    maximumRadius: {
      get: function () {
        return this._maximumRadius;
      },
    },
  });

  /**
   * Duplicates an Ellipsoid instance.
   *
   * @param {Ellipsoid} ellipsoid The ellipsoid to duplicate.
   * @param {Ellipsoid} [result] The object onto which to store the result, or undefined if a new
   *                    instance should be created.
   * @returns {Ellipsoid} The cloned Ellipsoid. (Returns undefined if ellipsoid is undefined)
   */
  Ellipsoid.clone = function (ellipsoid, result) {
    if (!defined(ellipsoid)) {
      return undefined;
    }
    const radii = ellipsoid._radii;

    if (!defined(result)) {
      return new Ellipsoid(radii.x, radii.y, radii.z);
    }

    Cartesian3.clone(radii, result._radii);
    Cartesian3.clone(ellipsoid._radiiSquared, result._radiiSquared);
    Cartesian3.clone(ellipsoid._radiiToTheFourth, result._radiiToTheFourth);
    Cartesian3.clone(ellipsoid._oneOverRadii, result._oneOverRadii);
    Cartesian3.clone(ellipsoid._oneOverRadiiSquared, result._oneOverRadiiSquared);
    result._minimumRadius = ellipsoid._minimumRadius;
    result._maximumRadius = ellipsoid._maximumRadius;
    result._centerToleranceSquared = ellipsoid._centerToleranceSquared;

    return result;
  };

  /**
   * Computes an Ellipsoid from a Cartesian specifying the radii in x, y, and z directions.
   *
   * @param {Cartesian3} [cartesian=Cartesian3.ZERO] The ellipsoid's radius in the x, y, and z directions.
   * @param {Ellipsoid} [result] The object onto which to store the result, or undefined if a new
   *                    instance should be created.
   * @returns {Ellipsoid} A new Ellipsoid instance.
   *
   * @exception {DeveloperError} All radii components must be greater than or equal to zero.
   *
   * @see Ellipsoid.WGS84
   * @see Ellipsoid.UNIT_SPHERE
   */
  Ellipsoid.fromCartesian3 = function (cartesian, result) {
    if (!defined(result)) {
      result = new Ellipsoid();
    }

    if (!defined(cartesian)) {
      return result;
    }

    initialize$p(result, cartesian.x, cartesian.y, cartesian.z);
    return result;
  };

  /**
   * An Ellipsoid instance initialized to the WGS84 standard.
   *
   * @type {Ellipsoid}
   * @constant
   */
  Ellipsoid.WGS84 = Object.freeze(
    new Ellipsoid(6378137.0, 6378137.0, 6356752.3142451793)
  );

  /**
   * An Ellipsoid instance initialized to radii of (1.0, 1.0, 1.0).
   *
   * @type {Ellipsoid}
   * @constant
   */
  Ellipsoid.UNIT_SPHERE = Object.freeze(new Ellipsoid(1.0, 1.0, 1.0));

  /**
   * An Ellipsoid instance initialized to a sphere with the lunar radius.
   *
   * @type {Ellipsoid}
   * @constant
   */
  Ellipsoid.MOON = Object.freeze(
    new Ellipsoid(
      CesiumMath.LUNAR_RADIUS,
      CesiumMath.LUNAR_RADIUS,
      CesiumMath.LUNAR_RADIUS
    )
  );

  /**
   * Duplicates an Ellipsoid instance.
   *
   * @param {Ellipsoid} [result] The object onto which to store the result, or undefined if a new
   *                    instance should be created.
   * @returns {Ellipsoid} The cloned Ellipsoid.
   */
  Ellipsoid.prototype.clone = function (result) {
    return Ellipsoid.clone(this, result);
  };

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  Ellipsoid.packedLength = Cartesian3.packedLength;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {Ellipsoid} 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
   */
  Ellipsoid.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    Cartesian3.pack(value._radii, array, startingIndex);

    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 {Ellipsoid} [result] The object into which to store the result.
   * @returns {Ellipsoid} The modified result parameter or a new Ellipsoid instance if one was not provided.
   */
  Ellipsoid.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    const radii = Cartesian3.unpack(array, startingIndex);
    return Ellipsoid.fromCartesian3(radii, result);
  };

  /**
   * Computes the unit vector directed from the center of this ellipsoid toward the provided Cartesian position.
   * @function
   *
   * @param {Cartesian3} cartesian The Cartesian for which to to determine the geocentric normal.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
   */
  Ellipsoid.prototype.geocentricSurfaceNormal = Cartesian3.normalize;

  /**
   * Computes the normal of the plane tangent to the surface of the ellipsoid at the provided position.
   *
   * @param {Cartographic} cartographic The cartographic position for which to to determine the geodetic normal.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
   */
  Ellipsoid.prototype.geodeticSurfaceNormalCartographic = function (
    cartographic,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartographic", cartographic);
    //>>includeEnd('debug');

    const longitude = cartographic.longitude;
    const latitude = cartographic.latitude;
    const cosLatitude = Math.cos(latitude);

    const x = cosLatitude * Math.cos(longitude);
    const y = cosLatitude * Math.sin(longitude);
    const z = Math.sin(latitude);

    if (!defined(result)) {
      result = new Cartesian3();
    }
    result.x = x;
    result.y = y;
    result.z = z;
    return Cartesian3.normalize(result, result);
  };

  /**
   * Computes the normal of the plane tangent to the surface of the ellipsoid at the provided position.
   *
   * @param {Cartesian3} cartesian The Cartesian position for which to to determine the surface normal.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided, or undefined if a normal cannot be found.
   */
  Ellipsoid.prototype.geodeticSurfaceNormal = function (cartesian, result) {
    if (
      Cartesian3.equalsEpsilon(cartesian, Cartesian3.ZERO, CesiumMath.EPSILON14)
    ) {
      return undefined;
    }
    if (!defined(result)) {
      result = new Cartesian3();
    }
    result = Cartesian3.multiplyComponents(
      cartesian,
      this._oneOverRadiiSquared,
      result
    );
    return Cartesian3.normalize(result, result);
  };

  const cartographicToCartesianNormal = new Cartesian3();
  const cartographicToCartesianK = new Cartesian3();

  /**
   * Converts the provided cartographic to Cartesian representation.
   *
   * @param {Cartographic} cartographic The cartographic position.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
   *
   * @example
   * //Create a Cartographic and determine it's Cartesian representation on a WGS84 ellipsoid.
   * const position = new Cesium.Cartographic(Cesium.Math.toRadians(21), Cesium.Math.toRadians(78), 5000);
   * const cartesianPosition = Cesium.Ellipsoid.WGS84.cartographicToCartesian(position);
   */
  Ellipsoid.prototype.cartographicToCartesian = function (cartographic, result) {
    //`cartographic is required` is thrown from geodeticSurfaceNormalCartographic.
    const n = cartographicToCartesianNormal;
    const k = cartographicToCartesianK;
    this.geodeticSurfaceNormalCartographic(cartographic, n);
    Cartesian3.multiplyComponents(this._radiiSquared, n, k);
    const gamma = Math.sqrt(Cartesian3.dot(n, k));
    Cartesian3.divideByScalar(k, gamma, k);
    Cartesian3.multiplyByScalar(n, cartographic.height, n);

    if (!defined(result)) {
      result = new Cartesian3();
    }
    return Cartesian3.add(k, n, result);
  };

  /**
   * Converts the provided array of cartographics to an array of Cartesians.
   *
   * @param {Cartographic[]} cartographics An array of cartographic positions.
   * @param {Cartesian3[]} [result] The object onto which to store the result.
   * @returns {Cartesian3[]} The modified result parameter or a new Array instance if none was provided.
   *
   * @example
   * //Convert an array of Cartographics and determine their Cartesian representation on a WGS84 ellipsoid.
   * const positions = [new Cesium.Cartographic(Cesium.Math.toRadians(21), Cesium.Math.toRadians(78), 0),
   *                  new Cesium.Cartographic(Cesium.Math.toRadians(21.321), Cesium.Math.toRadians(78.123), 100),
   *                  new Cesium.Cartographic(Cesium.Math.toRadians(21.645), Cesium.Math.toRadians(78.456), 250)];
   * const cartesianPositions = Cesium.Ellipsoid.WGS84.cartographicArrayToCartesianArray(positions);
   */
  Ellipsoid.prototype.cartographicArrayToCartesianArray = function (
    cartographics,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("cartographics", cartographics);
    //>>includeEnd('debug')

    const length = cartographics.length;
    if (!defined(result)) {
      result = new Array(length);
    } else {
      result.length = length;
    }
    for (let i = 0; i < length; i++) {
      result[i] = this.cartographicToCartesian(cartographics[i], result[i]);
    }
    return result;
  };

  const cartesianToCartographicN = new Cartesian3();
  const cartesianToCartographicP = new Cartesian3();
  const cartesianToCartographicH = new Cartesian3();

  /**
   * Converts the provided cartesian to cartographic representation.
   * The cartesian is undefined at the center of the ellipsoid.
   *
   * @param {Cartesian3} cartesian The Cartesian position to convert to cartographic representation.
   * @param {Cartographic} [result] The object onto which to store the result.
   * @returns {Cartographic} The modified result parameter, new Cartographic instance if none was provided, or undefined if the cartesian is at the center of the ellipsoid.
   *
   * @example
   * //Create a Cartesian and determine it's Cartographic representation on a WGS84 ellipsoid.
   * const position = new Cesium.Cartesian3(17832.12, 83234.52, 952313.73);
   * const cartographicPosition = Cesium.Ellipsoid.WGS84.cartesianToCartographic(position);
   */
  Ellipsoid.prototype.cartesianToCartographic = function (cartesian, result) {
    //`cartesian is required.` is thrown from scaleToGeodeticSurface
    const p = this.scaleToGeodeticSurface(cartesian, cartesianToCartographicP);

    if (!defined(p)) {
      return undefined;
    }

    const n = this.geodeticSurfaceNormal(p, cartesianToCartographicN);
    const h = Cartesian3.subtract(cartesian, p, cartesianToCartographicH);

    const longitude = Math.atan2(n.y, n.x);
    const latitude = Math.asin(n.z);
    const height =
      CesiumMath.sign(Cartesian3.dot(h, cartesian)) * Cartesian3.magnitude(h);

    if (!defined(result)) {
      return new Cartographic(longitude, latitude, height);
    }
    result.longitude = longitude;
    result.latitude = latitude;
    result.height = height;
    return result;
  };

  /**
   * Converts the provided array of cartesians to an array of cartographics.
   *
   * @param {Cartesian3[]} cartesians An array of Cartesian positions.
   * @param {Cartographic[]} [result] The object onto which to store the result.
   * @returns {Cartographic[]} The modified result parameter or a new Array instance if none was provided.
   *
   * @example
   * //Create an array of Cartesians and determine their Cartographic representation on a WGS84 ellipsoid.
   * const positions = [new Cesium.Cartesian3(17832.12, 83234.52, 952313.73),
   *                  new Cesium.Cartesian3(17832.13, 83234.53, 952313.73),
   *                  new Cesium.Cartesian3(17832.14, 83234.54, 952313.73)]
   * const cartographicPositions = Cesium.Ellipsoid.WGS84.cartesianArrayToCartographicArray(positions);
   */
  Ellipsoid.prototype.cartesianArrayToCartographicArray = function (
    cartesians,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("cartesians", cartesians);
    //>>includeEnd('debug');

    const length = cartesians.length;
    if (!defined(result)) {
      result = new Array(length);
    } else {
      result.length = length;
    }
    for (let i = 0; i < length; ++i) {
      result[i] = this.cartesianToCartographic(cartesians[i], result[i]);
    }
    return result;
  };

  /**
   * Scales the provided Cartesian position along the geodetic surface normal
   * so that it is on the surface of this ellipsoid.  If the position is
   * at the center of the ellipsoid, this function returns undefined.
   *
   * @param {Cartesian3} cartesian The Cartesian position to scale.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter, a new Cartesian3 instance if none was provided, or undefined if the position is at the center.
   */
  Ellipsoid.prototype.scaleToGeodeticSurface = function (cartesian, result) {
    return scaleToGeodeticSurface(
      cartesian,
      this._oneOverRadii,
      this._oneOverRadiiSquared,
      this._centerToleranceSquared,
      result
    );
  };

  /**
   * Scales the provided Cartesian position along the geocentric surface normal
   * so that it is on the surface of this ellipsoid.
   *
   * @param {Cartesian3} cartesian The Cartesian position to scale.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
   */
  Ellipsoid.prototype.scaleToGeocentricSurface = function (cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartesian", cartesian);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Cartesian3();
    }

    const positionX = cartesian.x;
    const positionY = cartesian.y;
    const positionZ = cartesian.z;
    const oneOverRadiiSquared = this._oneOverRadiiSquared;

    const beta =
      1.0 /
      Math.sqrt(
        positionX * positionX * oneOverRadiiSquared.x +
          positionY * positionY * oneOverRadiiSquared.y +
          positionZ * positionZ * oneOverRadiiSquared.z
      );

    return Cartesian3.multiplyByScalar(cartesian, beta, result);
  };

  /**
   * Transforms a Cartesian X, Y, Z position to the ellipsoid-scaled space by multiplying
   * its components by the result of {@link Ellipsoid#oneOverRadii}.
   *
   * @param {Cartesian3} position The position to transform.
   * @param {Cartesian3} [result] The position to which to copy the result, or undefined to create and
   *        return a new instance.
   * @returns {Cartesian3} The position expressed in the scaled space.  The returned instance is the
   *          one passed as the result parameter if it is not undefined, or a new instance of it is.
   */
  Ellipsoid.prototype.transformPositionToScaledSpace = function (
    position,
    result
  ) {
    if (!defined(result)) {
      result = new Cartesian3();
    }

    return Cartesian3.multiplyComponents(position, this._oneOverRadii, result);
  };

  /**
   * Transforms a Cartesian X, Y, Z position from the ellipsoid-scaled space by multiplying
   * its components by the result of {@link Ellipsoid#radii}.
   *
   * @param {Cartesian3} position The position to transform.
   * @param {Cartesian3} [result] The position to which to copy the result, or undefined to create and
   *        return a new instance.
   * @returns {Cartesian3} The position expressed in the unscaled space.  The returned instance is the
   *          one passed as the result parameter if it is not undefined, or a new instance of it is.
   */
  Ellipsoid.prototype.transformPositionFromScaledSpace = function (
    position,
    result
  ) {
    if (!defined(result)) {
      result = new Cartesian3();
    }

    return Cartesian3.multiplyComponents(position, this._radii, result);
  };

  /**
   * Compares this Ellipsoid against the provided Ellipsoid componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Ellipsoid} [right] The other Ellipsoid.
   * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
   */
  Ellipsoid.prototype.equals = function (right) {
    return (
      this === right ||
      (defined(right) && Cartesian3.equals(this._radii, right._radii))
    );
  };

  /**
   * Creates a string representing this Ellipsoid in the format '(radii.x, radii.y, radii.z)'.
   *
   * @returns {String} A string representing this ellipsoid in the format '(radii.x, radii.y, radii.z)'.
   */
  Ellipsoid.prototype.toString = function () {
    return this._radii.toString();
  };

  /**
   * Computes a point which is the intersection of the surface normal with the z-axis.
   *
   * @param {Cartesian3} position the position. must be on the surface of the ellipsoid.
   * @param {Number} [buffer = 0.0] A buffer to subtract from the ellipsoid size when checking if the point is inside the ellipsoid.
   *                                In earth case, with common earth datums, there is no need for this buffer since the intersection point is always (relatively) very close to the center.
   *                                In WGS84 datum, intersection point is at max z = +-42841.31151331382 (0.673% of z-axis).
   *                                Intersection point could be outside the ellipsoid if the ratio of MajorAxis / AxisOfRotation is bigger than the square root of 2
   * @param {Cartesian3} [result] The cartesian to which to copy the result, or undefined to create and
   *        return a new instance.
   * @returns {Cartesian3 | undefined} the intersection point if it's inside the ellipsoid, undefined otherwise
   *
   * @exception {DeveloperError} position is required.
   * @exception {DeveloperError} Ellipsoid must be an ellipsoid of revolution (radii.x == radii.y).
   * @exception {DeveloperError} Ellipsoid.radii.z must be greater than 0.
   */
  Ellipsoid.prototype.getSurfaceNormalIntersectionWithZAxis = function (
    position,
    buffer,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("position", position);

    if (
      !CesiumMath.equalsEpsilon(
        this._radii.x,
        this._radii.y,
        CesiumMath.EPSILON15
      )
    ) {
      throw new DeveloperError(
        "Ellipsoid must be an ellipsoid of revolution (radii.x == radii.y)"
      );
    }

    Check.typeOf.number.greaterThan("Ellipsoid.radii.z", this._radii.z, 0);
    //>>includeEnd('debug');

    buffer = defaultValue(buffer, 0.0);

    const squaredXOverSquaredZ = this._squaredXOverSquaredZ;

    if (!defined(result)) {
      result = new Cartesian3();
    }

    result.x = 0.0;
    result.y = 0.0;
    result.z = position.z * (1 - squaredXOverSquaredZ);

    if (Math.abs(result.z) >= this._radii.z - buffer) {
      return undefined;
    }

    return result;
  };

  const abscissas = [
    0.14887433898163,
    0.43339539412925,
    0.67940956829902,
    0.86506336668898,
    0.97390652851717,
    0.0,
  ];
  const weights = [
    0.29552422471475,
    0.26926671930999,
    0.21908636251598,
    0.14945134915058,
    0.066671344308684,
    0.0,
  ];

  /**
   * Compute the 10th order Gauss-Legendre Quadrature of the given definite integral.
   *
   * @param {Number} a The lower bound for the integration.
   * @param {Number} b The upper bound for the integration.
   * @param {Ellipsoid~RealValuedScalarFunction} func The function to integrate.
   * @returns {Number} The value of the integral of the given function over the given domain.
   *
   * @private
   */
  function gaussLegendreQuadrature(a, b, func) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("a", a);
    Check.typeOf.number("b", b);
    Check.typeOf.func("func", func);
    //>>includeEnd('debug');

    // The range is half of the normal range since the five weights add to one (ten weights add to two).
    // The values of the abscissas are multiplied by two to account for this.
    const xMean = 0.5 * (b + a);
    const xRange = 0.5 * (b - a);

    let sum = 0.0;
    for (let i = 0; i < 5; i++) {
      const dx = xRange * abscissas[i];
      sum += weights[i] * (func(xMean + dx) + func(xMean - dx));
    }

    // Scale the sum to the range of x.
    sum *= xRange;
    return sum;
  }

  /**
   * A real valued scalar function.
   * @callback Ellipsoid~RealValuedScalarFunction
   *
   * @param {Number} x The value used to evaluate the function.
   * @returns {Number} The value of the function at x.
   *
   * @private
   */

  /**
   * Computes an approximation of the surface area of a rectangle on the surface of an ellipsoid using
   * Gauss-Legendre 10th order quadrature.
   *
   * @param {Rectangle} rectangle The rectangle used for computing the surface area.
   * @returns {Number} The approximate area of the rectangle on the surface of this ellipsoid.
   */
  Ellipsoid.prototype.surfaceArea = function (rectangle) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("rectangle", rectangle);
    //>>includeEnd('debug');
    const minLongitude = rectangle.west;
    let maxLongitude = rectangle.east;
    const minLatitude = rectangle.south;
    const maxLatitude = rectangle.north;

    while (maxLongitude < minLongitude) {
      maxLongitude += CesiumMath.TWO_PI;
    }

    const radiiSquared = this._radiiSquared;
    const a2 = radiiSquared.x;
    const b2 = radiiSquared.y;
    const c2 = radiiSquared.z;
    const a2b2 = a2 * b2;
    return gaussLegendreQuadrature(minLatitude, maxLatitude, function (lat) {
      // phi represents the angle measured from the north pole
      // sin(phi) = sin(pi / 2 - lat) = cos(lat), cos(phi) is similar
      const sinPhi = Math.cos(lat);
      const cosPhi = Math.sin(lat);
      return (
        Math.cos(lat) *
        gaussLegendreQuadrature(minLongitude, maxLongitude, function (lon) {
          const cosTheta = Math.cos(lon);
          const sinTheta = Math.sin(lon);
          return Math.sqrt(
            a2b2 * cosPhi * cosPhi +
              c2 *
                (b2 * cosTheta * cosTheta + a2 * sinTheta * sinTheta) *
                sinPhi *
                sinPhi
          );
        })
      );
    });
  };

  /**
   * 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 = defaultValue(ellipsoid, 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 (!defined(result)) {
      return new 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 (!defined(cartesian)) {
      throw new 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 (!defined(result)) {
      return new 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 = defaultValue(start, 0.0);
    /**
     * The end of the interval.
     * @type {Number}
     * @default 0.0
     */
    this.stop = defaultValue(stop, 0.0);
  }

  /**
   * A 3x3 matrix, indexable as a column-major order array.
   * Constructor parameters are in row-major order for code readability.
   * @alias Matrix3
   * @constructor
   * @implements {ArrayLike<number>}
   *
   * @param {Number} [column0Row0=0.0] The value for column 0, row 0.
   * @param {Number} [column1Row0=0.0] The value for column 1, row 0.
   * @param {Number} [column2Row0=0.0] The value for column 2, row 0.
   * @param {Number} [column0Row1=0.0] The value for column 0, row 1.
   * @param {Number} [column1Row1=0.0] The value for column 1, row 1.
   * @param {Number} [column2Row1=0.0] The value for column 2, row 1.
   * @param {Number} [column0Row2=0.0] The value for column 0, row 2.
   * @param {Number} [column1Row2=0.0] The value for column 1, row 2.
   * @param {Number} [column2Row2=0.0] The value for column 2, row 2.
   *
   * @see Matrix3.fromArray
   * @see Matrix3.fromColumnMajorArray
   * @see Matrix3.fromRowMajorArray
   * @see Matrix3.fromQuaternion
   * @see Matrix3.fromHeadingPitchRoll
   * @see Matrix3.fromScale
   * @see Matrix3.fromUniformScale
   * @see Matrix3.fromCrossProduct
   * @see Matrix3.fromRotationX
   * @see Matrix3.fromRotationY
   * @see Matrix3.fromRotationZ
   * @see Matrix2
   * @see Matrix4
   */
  function Matrix3(
    column0Row0,
    column1Row0,
    column2Row0,
    column0Row1,
    column1Row1,
    column2Row1,
    column0Row2,
    column1Row2,
    column2Row2
  ) {
    this[0] = defaultValue(column0Row0, 0.0);
    this[1] = defaultValue(column0Row1, 0.0);
    this[2] = defaultValue(column0Row2, 0.0);
    this[3] = defaultValue(column1Row0, 0.0);
    this[4] = defaultValue(column1Row1, 0.0);
    this[5] = defaultValue(column1Row2, 0.0);
    this[6] = defaultValue(column2Row0, 0.0);
    this[7] = defaultValue(column2Row1, 0.0);
    this[8] = defaultValue(column2Row2, 0.0);
  }

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  Matrix3.packedLength = 9;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {Matrix3} 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
   */
  Matrix3.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    array[startingIndex++] = value[0];
    array[startingIndex++] = value[1];
    array[startingIndex++] = value[2];
    array[startingIndex++] = value[3];
    array[startingIndex++] = value[4];
    array[startingIndex++] = value[5];
    array[startingIndex++] = value[6];
    array[startingIndex++] = value[7];
    array[startingIndex++] = value[8];

    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 {Matrix3} [result] The object into which to store the result.
   * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
   */
  Matrix3.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    if (!defined(result)) {
      result = new Matrix3();
    }

    result[0] = array[startingIndex++];
    result[1] = array[startingIndex++];
    result[2] = array[startingIndex++];
    result[3] = array[startingIndex++];
    result[4] = array[startingIndex++];
    result[5] = array[startingIndex++];
    result[6] = array[startingIndex++];
    result[7] = array[startingIndex++];
    result[8] = array[startingIndex++];
    return result;
  };

  /**
   * Flattens an array of Matrix3s into an array of components. The components
   * are stored in column-major order.
   *
   * @param {Matrix3[]} array The array of matrices to pack.
   * @param {Number[]} [result] The array onto which to store the result. If this is a typed array, it must have array.length * 9 components, else a {@link DeveloperError} will be thrown. If it is a regular array, it will be resized to have (array.length * 9) elements.
   * @returns {Number[]} The packed array.
   */
  Matrix3.packArray = function (array, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    const length = array.length;
    const resultLength = length * 9;
    if (!defined(result)) {
      result = new Array(resultLength);
    } else if (!Array.isArray(result) && result.length !== resultLength) {
      //>>includeStart('debug', pragmas.debug);
      throw new DeveloperError(
        "If result is a typed array, it must have exactly array.length * 9 elements"
      );
      //>>includeEnd('debug');
    } else if (result.length !== resultLength) {
      result.length = resultLength;
    }

    for (let i = 0; i < length; ++i) {
      Matrix3.pack(array[i], result, i * 9);
    }
    return result;
  };

  /**
   * Unpacks an array of column-major matrix components into an array of Matrix3s.
   *
   * @param {Number[]} array The array of components to unpack.
   * @param {Matrix3[]} [result] The array onto which to store the result.
   * @returns {Matrix3[]} The unpacked array.
   */
  Matrix3.unpackArray = function (array, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    Check.typeOf.number.greaterThanOrEquals("array.length", array.length, 9);
    if (array.length % 9 !== 0) {
      throw new DeveloperError("array length must be a multiple of 9.");
    }
    //>>includeEnd('debug');

    const length = array.length;
    if (!defined(result)) {
      result = new Array(length / 9);
    } else {
      result.length = length / 9;
    }

    for (let i = 0; i < length; i += 9) {
      const index = i / 9;
      result[index] = Matrix3.unpack(array, i, result[index]);
    }
    return result;
  };

  /**
   * Duplicates a Matrix3 instance.
   *
   * @param {Matrix3} matrix The matrix to duplicate.
   * @param {Matrix3} [result] The object onto which to store the result.
   * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided. (Returns undefined if matrix is undefined)
   */
  Matrix3.clone = function (matrix, result) {
    if (!defined(matrix)) {
      return undefined;
    }
    if (!defined(result)) {
      return new Matrix3(
        matrix[0],
        matrix[3],
        matrix[6],
        matrix[1],
        matrix[4],
        matrix[7],
        matrix[2],
        matrix[5],
        matrix[8]
      );
    }
    result[0] = matrix[0];
    result[1] = matrix[1];
    result[2] = matrix[2];
    result[3] = matrix[3];
    result[4] = matrix[4];
    result[5] = matrix[5];
    result[6] = matrix[6];
    result[7] = matrix[7];
    result[8] = matrix[8];
    return result;
  };

  /**
   * Creates a Matrix3 from 9 consecutive elements in an array.
   *
   * @function
   * @param {Number[]} array The array whose 9 consecutive elements correspond to the positions of the matrix.  Assumes column-major order.
   * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to first column first row position in the matrix.
   * @param {Matrix3} [result] The object onto which to store the result.
   * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
   *
   * @example
   * // Create the Matrix3:
   * // [1.0, 2.0, 3.0]
   * // [1.0, 2.0, 3.0]
   * // [1.0, 2.0, 3.0]
   *
   * const v = [1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0];
   * const m = Cesium.Matrix3.fromArray(v);
   *
   * // Create same Matrix3 with using an offset into an array
   * const v2 = [0.0, 0.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0];
   * const m2 = Cesium.Matrix3.fromArray(v2, 2);
   */
  Matrix3.fromArray = Matrix3.unpack;

  /**
   * Creates a Matrix3 instance from a column-major order array.
   *
   * @param {Number[]} values The column-major order array.
   * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
   * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
   */
  Matrix3.fromColumnMajorArray = function (values, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("values", values);
    //>>includeEnd('debug');

    return Matrix3.clone(values, result);
  };

  /**
   * Creates a Matrix3 instance from a row-major order array.
   * The resulting matrix will be in column-major order.
   *
   * @param {Number[]} values The row-major order array.
   * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
   * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
   */
  Matrix3.fromRowMajorArray = function (values, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("values", values);
    //>>includeEnd('debug');

    if (!defined(result)) {
      return new Matrix3(
        values[0],
        values[1],
        values[2],
        values[3],
        values[4],
        values[5],
        values[6],
        values[7],
        values[8]
      );
    }
    result[0] = values[0];
    result[1] = values[3];
    result[2] = values[6];
    result[3] = values[1];
    result[4] = values[4];
    result[5] = values[7];
    result[6] = values[2];
    result[7] = values[5];
    result[8] = values[8];
    return result;
  };

  /**
   * Computes a 3x3 rotation matrix from the provided quaternion.
   *
   * @param {Quaternion} quaternion the quaternion to use.
   * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
   * @returns {Matrix3} The 3x3 rotation matrix from this quaternion.
   */
  Matrix3.fromQuaternion = function (quaternion, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("quaternion", quaternion);
    //>>includeEnd('debug');

    const x2 = quaternion.x * quaternion.x;
    const xy = quaternion.x * quaternion.y;
    const xz = quaternion.x * quaternion.z;
    const xw = quaternion.x * quaternion.w;
    const y2 = quaternion.y * quaternion.y;
    const yz = quaternion.y * quaternion.z;
    const yw = quaternion.y * quaternion.w;
    const z2 = quaternion.z * quaternion.z;
    const zw = quaternion.z * quaternion.w;
    const w2 = quaternion.w * quaternion.w;

    const m00 = x2 - y2 - z2 + w2;
    const m01 = 2.0 * (xy - zw);
    const m02 = 2.0 * (xz + yw);

    const m10 = 2.0 * (xy + zw);
    const m11 = -x2 + y2 - z2 + w2;
    const m12 = 2.0 * (yz - xw);

    const m20 = 2.0 * (xz - yw);
    const m21 = 2.0 * (yz + xw);
    const m22 = -x2 - y2 + z2 + w2;

    if (!defined(result)) {
      return new Matrix3(m00, m01, m02, m10, m11, m12, m20, m21, m22);
    }
    result[0] = m00;
    result[1] = m10;
    result[2] = m20;
    result[3] = m01;
    result[4] = m11;
    result[5] = m21;
    result[6] = m02;
    result[7] = m12;
    result[8] = m22;
    return result;
  };

  /**
   * Computes a 3x3 rotation matrix from the provided headingPitchRoll. (see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles )
   *
   * @param {HeadingPitchRoll} headingPitchRoll the headingPitchRoll to use.
   * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
   * @returns {Matrix3} The 3x3 rotation matrix from this headingPitchRoll.
   */
  Matrix3.fromHeadingPitchRoll = function (headingPitchRoll, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("headingPitchRoll", headingPitchRoll);
    //>>includeEnd('debug');

    const cosTheta = Math.cos(-headingPitchRoll.pitch);
    const cosPsi = Math.cos(-headingPitchRoll.heading);
    const cosPhi = Math.cos(headingPitchRoll.roll);
    const sinTheta = Math.sin(-headingPitchRoll.pitch);
    const sinPsi = Math.sin(-headingPitchRoll.heading);
    const sinPhi = Math.sin(headingPitchRoll.roll);

    const m00 = cosTheta * cosPsi;
    const m01 = -cosPhi * sinPsi + sinPhi * sinTheta * cosPsi;
    const m02 = sinPhi * sinPsi + cosPhi * sinTheta * cosPsi;

    const m10 = cosTheta * sinPsi;
    const m11 = cosPhi * cosPsi + sinPhi * sinTheta * sinPsi;
    const m12 = -sinPhi * cosPsi + cosPhi * sinTheta * sinPsi;

    const m20 = -sinTheta;
    const m21 = sinPhi * cosTheta;
    const m22 = cosPhi * cosTheta;

    if (!defined(result)) {
      return new Matrix3(m00, m01, m02, m10, m11, m12, m20, m21, m22);
    }
    result[0] = m00;
    result[1] = m10;
    result[2] = m20;
    result[3] = m01;
    result[4] = m11;
    result[5] = m21;
    result[6] = m02;
    result[7] = m12;
    result[8] = m22;
    return result;
  };

  /**
   * Computes a Matrix3 instance representing a non-uniform scale.
   *
   * @param {Cartesian3} scale The x, y, and z scale factors.
   * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
   * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
   *
   * @example
   * // Creates
   * //   [7.0, 0.0, 0.0]
   * //   [0.0, 8.0, 0.0]
   * //   [0.0, 0.0, 9.0]
   * const m = Cesium.Matrix3.fromScale(new Cesium.Cartesian3(7.0, 8.0, 9.0));
   */
  Matrix3.fromScale = function (scale, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("scale", scale);
    //>>includeEnd('debug');

    if (!defined(result)) {
      return new Matrix3(scale.x, 0.0, 0.0, 0.0, scale.y, 0.0, 0.0, 0.0, scale.z);
    }

    result[0] = scale.x;
    result[1] = 0.0;
    result[2] = 0.0;
    result[3] = 0.0;
    result[4] = scale.y;
    result[5] = 0.0;
    result[6] = 0.0;
    result[7] = 0.0;
    result[8] = scale.z;
    return result;
  };

  /**
   * Computes a Matrix3 instance representing a uniform scale.
   *
   * @param {Number} scale The uniform scale factor.
   * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
   * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
   *
   * @example
   * // Creates
   * //   [2.0, 0.0, 0.0]
   * //   [0.0, 2.0, 0.0]
   * //   [0.0, 0.0, 2.0]
   * const m = Cesium.Matrix3.fromUniformScale(2.0);
   */
  Matrix3.fromUniformScale = function (scale, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("scale", scale);
    //>>includeEnd('debug');

    if (!defined(result)) {
      return new Matrix3(scale, 0.0, 0.0, 0.0, scale, 0.0, 0.0, 0.0, scale);
    }

    result[0] = scale;
    result[1] = 0.0;
    result[2] = 0.0;
    result[3] = 0.0;
    result[4] = scale;
    result[5] = 0.0;
    result[6] = 0.0;
    result[7] = 0.0;
    result[8] = scale;
    return result;
  };

  /**
   * Computes a Matrix3 instance representing the cross product equivalent matrix of a Cartesian3 vector.
   *
   * @param {Cartesian3} vector the vector on the left hand side of the cross product operation.
   * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
   * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
   *
   * @example
   * // Creates
   * //   [0.0, -9.0,  8.0]
   * //   [9.0,  0.0, -7.0]
   * //   [-8.0, 7.0,  0.0]
   * const m = Cesium.Matrix3.fromCrossProduct(new Cesium.Cartesian3(7.0, 8.0, 9.0));
   */
  Matrix3.fromCrossProduct = function (vector, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("vector", vector);
    //>>includeEnd('debug');

    if (!defined(result)) {
      return new Matrix3(
        0.0,
        -vector.z,
        vector.y,
        vector.z,
        0.0,
        -vector.x,
        -vector.y,
        vector.x,
        0.0
      );
    }

    result[0] = 0.0;
    result[1] = vector.z;
    result[2] = -vector.y;
    result[3] = -vector.z;
    result[4] = 0.0;
    result[5] = vector.x;
    result[6] = vector.y;
    result[7] = -vector.x;
    result[8] = 0.0;
    return result;
  };

  /**
   * Creates a rotation matrix around the x-axis.
   *
   * @param {Number} angle The angle, in radians, of the rotation.  Positive angles are counterclockwise.
   * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
   * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
   *
   * @example
   * // Rotate a point 45 degrees counterclockwise around the x-axis.
   * const p = new Cesium.Cartesian3(5, 6, 7);
   * const m = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(45.0));
   * const rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
   */
  Matrix3.fromRotationX = function (angle, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("angle", angle);
    //>>includeEnd('debug');

    const cosAngle = Math.cos(angle);
    const sinAngle = Math.sin(angle);

    if (!defined(result)) {
      return new Matrix3(
        1.0,
        0.0,
        0.0,
        0.0,
        cosAngle,
        -sinAngle,
        0.0,
        sinAngle,
        cosAngle
      );
    }

    result[0] = 1.0;
    result[1] = 0.0;
    result[2] = 0.0;
    result[3] = 0.0;
    result[4] = cosAngle;
    result[5] = sinAngle;
    result[6] = 0.0;
    result[7] = -sinAngle;
    result[8] = cosAngle;

    return result;
  };

  /**
   * Creates a rotation matrix around the y-axis.
   *
   * @param {Number} angle The angle, in radians, of the rotation.  Positive angles are counterclockwise.
   * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
   * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
   *
   * @example
   * // Rotate a point 45 degrees counterclockwise around the y-axis.
   * const p = new Cesium.Cartesian3(5, 6, 7);
   * const m = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(45.0));
   * const rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
   */
  Matrix3.fromRotationY = function (angle, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("angle", angle);
    //>>includeEnd('debug');

    const cosAngle = Math.cos(angle);
    const sinAngle = Math.sin(angle);

    if (!defined(result)) {
      return new Matrix3(
        cosAngle,
        0.0,
        sinAngle,
        0.0,
        1.0,
        0.0,
        -sinAngle,
        0.0,
        cosAngle
      );
    }

    result[0] = cosAngle;
    result[1] = 0.0;
    result[2] = -sinAngle;
    result[3] = 0.0;
    result[4] = 1.0;
    result[5] = 0.0;
    result[6] = sinAngle;
    result[7] = 0.0;
    result[8] = cosAngle;

    return result;
  };

  /**
   * Creates a rotation matrix around the z-axis.
   *
   * @param {Number} angle The angle, in radians, of the rotation.  Positive angles are counterclockwise.
   * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
   * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
   *
   * @example
   * // Rotate a point 45 degrees counterclockwise around the z-axis.
   * const p = new Cesium.Cartesian3(5, 6, 7);
   * const m = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(45.0));
   * const rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
   */
  Matrix3.fromRotationZ = function (angle, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("angle", angle);
    //>>includeEnd('debug');

    const cosAngle = Math.cos(angle);
    const sinAngle = Math.sin(angle);

    if (!defined(result)) {
      return new Matrix3(
        cosAngle,
        -sinAngle,
        0.0,
        sinAngle,
        cosAngle,
        0.0,
        0.0,
        0.0,
        1.0
      );
    }

    result[0] = cosAngle;
    result[1] = sinAngle;
    result[2] = 0.0;
    result[3] = -sinAngle;
    result[4] = cosAngle;
    result[5] = 0.0;
    result[6] = 0.0;
    result[7] = 0.0;
    result[8] = 1.0;

    return result;
  };

  /**
   * Creates an Array from the provided Matrix3 instance.
   * The array will be in column-major order.
   *
   * @param {Matrix3} matrix The matrix to use..
   * @param {Number[]} [result] The Array onto which to store the result.
   * @returns {Number[]} The modified Array parameter or a new Array instance if one was not provided.
   */
  Matrix3.toArray = function (matrix, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    //>>includeEnd('debug');

    if (!defined(result)) {
      return [
        matrix[0],
        matrix[1],
        matrix[2],
        matrix[3],
        matrix[4],
        matrix[5],
        matrix[6],
        matrix[7],
        matrix[8],
      ];
    }
    result[0] = matrix[0];
    result[1] = matrix[1];
    result[2] = matrix[2];
    result[3] = matrix[3];
    result[4] = matrix[4];
    result[5] = matrix[5];
    result[6] = matrix[6];
    result[7] = matrix[7];
    result[8] = matrix[8];
    return result;
  };

  /**
   * Computes the array index of the element at the provided row and column.
   *
   * @param {Number} column The zero-based index of the column.
   * @param {Number} row The zero-based index of the row.
   * @returns {Number} The index of the element at the provided row and column.
   *
   * @exception {DeveloperError} row must be 0, 1, or 2.
   * @exception {DeveloperError} column must be 0, 1, or 2.
   *
   * @example
   * const myMatrix = new Cesium.Matrix3();
   * const column1Row0Index = Cesium.Matrix3.getElementIndex(1, 0);
   * const column1Row0 = myMatrix[column1Row0Index]
   * myMatrix[column1Row0Index] = 10.0;
   */
  Matrix3.getElementIndex = function (column, row) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number.greaterThanOrEquals("row", row, 0);
    Check.typeOf.number.lessThanOrEquals("row", row, 2);
    Check.typeOf.number.greaterThanOrEquals("column", column, 0);
    Check.typeOf.number.lessThanOrEquals("column", column, 2);
    //>>includeEnd('debug');

    return column * 3 + row;
  };

  /**
   * Retrieves a copy of the matrix column at the provided index as a Cartesian3 instance.
   *
   * @param {Matrix3} matrix The matrix to use.
   * @param {Number} index The zero-based index of the column to retrieve.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter.
   *
   * @exception {DeveloperError} index must be 0, 1, or 2.
   */
  Matrix3.getColumn = function (matrix, index, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.number.greaterThanOrEquals("index", index, 0);
    Check.typeOf.number.lessThanOrEquals("index", index, 2);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const startIndex = index * 3;
    const x = matrix[startIndex];
    const y = matrix[startIndex + 1];
    const z = matrix[startIndex + 2];

    result.x = x;
    result.y = y;
    result.z = z;
    return result;
  };

  /**
   * Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian3 instance.
   *
   * @param {Matrix3} matrix The matrix to use.
   * @param {Number} index The zero-based index of the column to set.
   * @param {Cartesian3} cartesian The Cartesian whose values will be assigned to the specified column.
   * @param {Matrix3} result The object onto which to store the result.
   * @returns {Matrix3} The modified result parameter.
   *
   * @exception {DeveloperError} index must be 0, 1, or 2.
   */
  Matrix3.setColumn = function (matrix, index, cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.number.greaterThanOrEquals("index", index, 0);
    Check.typeOf.number.lessThanOrEquals("index", index, 2);
    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result = Matrix3.clone(matrix, result);
    const startIndex = index * 3;
    result[startIndex] = cartesian.x;
    result[startIndex + 1] = cartesian.y;
    result[startIndex + 2] = cartesian.z;
    return result;
  };

  /**
   * Retrieves a copy of the matrix row at the provided index as a Cartesian3 instance.
   *
   * @param {Matrix3} matrix The matrix to use.
   * @param {Number} index The zero-based index of the row to retrieve.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter.
   *
   * @exception {DeveloperError} index must be 0, 1, or 2.
   */
  Matrix3.getRow = function (matrix, index, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.number.greaterThanOrEquals("index", index, 0);
    Check.typeOf.number.lessThanOrEquals("index", index, 2);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const x = matrix[index];
    const y = matrix[index + 3];
    const z = matrix[index + 6];

    result.x = x;
    result.y = y;
    result.z = z;
    return result;
  };

  /**
   * Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian3 instance.
   *
   * @param {Matrix3} matrix The matrix to use.
   * @param {Number} index The zero-based index of the row to set.
   * @param {Cartesian3} cartesian The Cartesian whose values will be assigned to the specified row.
   * @param {Matrix3} result The object onto which to store the result.
   * @returns {Matrix3} The modified result parameter.
   *
   * @exception {DeveloperError} index must be 0, 1, or 2.
   */
  Matrix3.setRow = function (matrix, index, cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.number.greaterThanOrEquals("index", index, 0);
    Check.typeOf.number.lessThanOrEquals("index", index, 2);
    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result = Matrix3.clone(matrix, result);
    result[index] = cartesian.x;
    result[index + 3] = cartesian.y;
    result[index + 6] = cartesian.z;
    return result;
  };

  const scaleScratch1$2 = new Cartesian3();

  /**
   * Computes a new matrix that replaces the scale with the provided scale.
   * This assumes the matrix is an affine transformation.
   *
   * @param {Matrix3} matrix The matrix to use.
   * @param {Cartesian3} scale The scale that replaces the scale of the provided matrix.
   * @param {Matrix3} result The object onto which to store the result.
   * @returns {Matrix3} The modified result parameter.
   *
   * @see Matrix3.setUniformScale
   * @see Matrix3.fromScale
   * @see Matrix3.fromUniformScale
   * @see Matrix3.multiplyByScale
   * @see Matrix3.multiplyByUniformScale
   * @see Matrix3.getScale
   */
  Matrix3.setScale = function (matrix, scale, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("scale", scale);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const existingScale = Matrix3.getScale(matrix, scaleScratch1$2);
    const scaleRatioX = scale.x / existingScale.x;
    const scaleRatioY = scale.y / existingScale.y;
    const scaleRatioZ = scale.z / existingScale.z;

    result[0] = matrix[0] * scaleRatioX;
    result[1] = matrix[1] * scaleRatioX;
    result[2] = matrix[2] * scaleRatioX;
    result[3] = matrix[3] * scaleRatioY;
    result[4] = matrix[4] * scaleRatioY;
    result[5] = matrix[5] * scaleRatioY;
    result[6] = matrix[6] * scaleRatioZ;
    result[7] = matrix[7] * scaleRatioZ;
    result[8] = matrix[8] * scaleRatioZ;

    return result;
  };

  const scaleScratch2$2 = new Cartesian3();

  /**
   * Computes a new matrix that replaces the scale with the provided uniform scale.
   * This assumes the matrix is an affine transformation.
   *
   * @param {Matrix3} matrix The matrix to use.
   * @param {Number} scale The uniform scale that replaces the scale of the provided matrix.
   * @param {Matrix3} result The object onto which to store the result.
   * @returns {Matrix3} The modified result parameter.
   *
   * @see Matrix3.setScale
   * @see Matrix3.fromScale
   * @see Matrix3.fromUniformScale
   * @see Matrix3.multiplyByScale
   * @see Matrix3.multiplyByUniformScale
   * @see Matrix3.getScale
   */
  Matrix3.setUniformScale = function (matrix, scale, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.number("scale", scale);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const existingScale = Matrix3.getScale(matrix, scaleScratch2$2);
    const scaleRatioX = scale / existingScale.x;
    const scaleRatioY = scale / existingScale.y;
    const scaleRatioZ = scale / existingScale.z;

    result[0] = matrix[0] * scaleRatioX;
    result[1] = matrix[1] * scaleRatioX;
    result[2] = matrix[2] * scaleRatioX;
    result[3] = matrix[3] * scaleRatioY;
    result[4] = matrix[4] * scaleRatioY;
    result[5] = matrix[5] * scaleRatioY;
    result[6] = matrix[6] * scaleRatioZ;
    result[7] = matrix[7] * scaleRatioZ;
    result[8] = matrix[8] * scaleRatioZ;

    return result;
  };

  const scratchColumn$2 = new Cartesian3();

  /**
   * Extracts the non-uniform scale assuming the matrix is an affine transformation.
   *
   * @param {Matrix3} matrix The matrix.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter.
   *
   * @see Matrix3.multiplyByScale
   * @see Matrix3.multiplyByUniformScale
   * @see Matrix3.fromScale
   * @see Matrix3.fromUniformScale
   * @see Matrix3.setScale
   * @see Matrix3.setUniformScale
   */
  Matrix3.getScale = function (matrix, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.x = Cartesian3.magnitude(
      Cartesian3.fromElements(matrix[0], matrix[1], matrix[2], scratchColumn$2)
    );
    result.y = Cartesian3.magnitude(
      Cartesian3.fromElements(matrix[3], matrix[4], matrix[5], scratchColumn$2)
    );
    result.z = Cartesian3.magnitude(
      Cartesian3.fromElements(matrix[6], matrix[7], matrix[8], scratchColumn$2)
    );
    return result;
  };

  const scaleScratch3$2 = new Cartesian3();

  /**
   * Computes the maximum scale assuming the matrix is an affine transformation.
   * The maximum scale is the maximum length of the column vectors.
   *
   * @param {Matrix3} matrix The matrix.
   * @returns {Number} The maximum scale.
   */
  Matrix3.getMaximumScale = function (matrix) {
    Matrix3.getScale(matrix, scaleScratch3$2);
    return Cartesian3.maximumComponent(scaleScratch3$2);
  };

  const scaleScratch4$2 = new Cartesian3();

  /**
   * Sets the rotation assuming the matrix is an affine transformation.
   *
   * @param {Matrix3} matrix The matrix.
   * @param {Matrix3} rotation The rotation matrix.
   * @returns {Matrix3} The modified result parameter.
   *
   * @see Matrix3.getRotation
   */
  Matrix3.setRotation = function (matrix, rotation, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const scale = Matrix3.getScale(matrix, scaleScratch4$2);

    result[0] = rotation[0] * scale.x;
    result[1] = rotation[1] * scale.x;
    result[2] = rotation[2] * scale.x;
    result[3] = rotation[3] * scale.y;
    result[4] = rotation[4] * scale.y;
    result[5] = rotation[5] * scale.y;
    result[6] = rotation[6] * scale.z;
    result[7] = rotation[7] * scale.z;
    result[8] = rotation[8] * scale.z;

    return result;
  };

  const scaleScratch5$2 = new Cartesian3();

  /**
   * Extracts the rotation matrix assuming the matrix is an affine transformation.
   *
   * @param {Matrix3} matrix The matrix.
   * @param {Matrix3} result The object onto which to store the result.
   * @returns {Matrix3} The modified result parameter.
   *
   * @see Matrix3.setRotation
   */
  Matrix3.getRotation = function (matrix, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const scale = Matrix3.getScale(matrix, scaleScratch5$2);

    result[0] = matrix[0] / scale.x;
    result[1] = matrix[1] / scale.x;
    result[2] = matrix[2] / scale.x;
    result[3] = matrix[3] / scale.y;
    result[4] = matrix[4] / scale.y;
    result[5] = matrix[5] / scale.y;
    result[6] = matrix[6] / scale.z;
    result[7] = matrix[7] / scale.z;
    result[8] = matrix[8] / scale.z;

    return result;
  };

  /**
   * Computes the product of two matrices.
   *
   * @param {Matrix3} left The first matrix.
   * @param {Matrix3} right The second matrix.
   * @param {Matrix3} result The object onto which to store the result.
   * @returns {Matrix3} The modified result parameter.
   */
  Matrix3.multiply = function (left, right, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const column0Row0 =
      left[0] * right[0] + left[3] * right[1] + left[6] * right[2];
    const column0Row1 =
      left[1] * right[0] + left[4] * right[1] + left[7] * right[2];
    const column0Row2 =
      left[2] * right[0] + left[5] * right[1] + left[8] * right[2];

    const column1Row0 =
      left[0] * right[3] + left[3] * right[4] + left[6] * right[5];
    const column1Row1 =
      left[1] * right[3] + left[4] * right[4] + left[7] * right[5];
    const column1Row2 =
      left[2] * right[3] + left[5] * right[4] + left[8] * right[5];

    const column2Row0 =
      left[0] * right[6] + left[3] * right[7] + left[6] * right[8];
    const column2Row1 =
      left[1] * right[6] + left[4] * right[7] + left[7] * right[8];
    const column2Row2 =
      left[2] * right[6] + left[5] * right[7] + left[8] * right[8];

    result[0] = column0Row0;
    result[1] = column0Row1;
    result[2] = column0Row2;
    result[3] = column1Row0;
    result[4] = column1Row1;
    result[5] = column1Row2;
    result[6] = column2Row0;
    result[7] = column2Row1;
    result[8] = column2Row2;
    return result;
  };

  /**
   * Computes the sum of two matrices.
   *
   * @param {Matrix3} left The first matrix.
   * @param {Matrix3} right The second matrix.
   * @param {Matrix3} result The object onto which to store the result.
   * @returns {Matrix3} The modified result parameter.
   */
  Matrix3.add = function (left, right, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result[0] = left[0] + right[0];
    result[1] = left[1] + right[1];
    result[2] = left[2] + right[2];
    result[3] = left[3] + right[3];
    result[4] = left[4] + right[4];
    result[5] = left[5] + right[5];
    result[6] = left[6] + right[6];
    result[7] = left[7] + right[7];
    result[8] = left[8] + right[8];
    return result;
  };

  /**
   * Computes the difference of two matrices.
   *
   * @param {Matrix3} left The first matrix.
   * @param {Matrix3} right The second matrix.
   * @param {Matrix3} result The object onto which to store the result.
   * @returns {Matrix3} The modified result parameter.
   */
  Matrix3.subtract = function (left, right, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result[0] = left[0] - right[0];
    result[1] = left[1] - right[1];
    result[2] = left[2] - right[2];
    result[3] = left[3] - right[3];
    result[4] = left[4] - right[4];
    result[5] = left[5] - right[5];
    result[6] = left[6] - right[6];
    result[7] = left[7] - right[7];
    result[8] = left[8] - right[8];
    return result;
  };

  /**
   * Computes the product of a matrix and a column vector.
   *
   * @param {Matrix3} matrix The matrix.
   * @param {Cartesian3} cartesian The column.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter.
   */
  Matrix3.multiplyByVector = function (matrix, cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const vX = cartesian.x;
    const vY = cartesian.y;
    const vZ = cartesian.z;

    const x = matrix[0] * vX + matrix[3] * vY + matrix[6] * vZ;
    const y = matrix[1] * vX + matrix[4] * vY + matrix[7] * vZ;
    const z = matrix[2] * vX + matrix[5] * vY + matrix[8] * vZ;

    result.x = x;
    result.y = y;
    result.z = z;
    return result;
  };

  /**
   * Computes the product of a matrix and a scalar.
   *
   * @param {Matrix3} matrix The matrix.
   * @param {Number} scalar The number to multiply by.
   * @param {Matrix3} result The object onto which to store the result.
   * @returns {Matrix3} The modified result parameter.
   */
  Matrix3.multiplyByScalar = function (matrix, scalar, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.number("scalar", scalar);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result[0] = matrix[0] * scalar;
    result[1] = matrix[1] * scalar;
    result[2] = matrix[2] * scalar;
    result[3] = matrix[3] * scalar;
    result[4] = matrix[4] * scalar;
    result[5] = matrix[5] * scalar;
    result[6] = matrix[6] * scalar;
    result[7] = matrix[7] * scalar;
    result[8] = matrix[8] * scalar;
    return result;
  };

  /**
   * Computes the product of a matrix times a (non-uniform) scale, as if the scale were a scale matrix.
   *
   * @param {Matrix3} matrix The matrix on the left-hand side.
   * @param {Number} scale The non-uniform scale on the right-hand side.
   * @param {Matrix3} result The object onto which to store the result.
   * @returns {Matrix3} The modified result parameter.
   *
   *
   * @example
   * // Instead of Cesium.Matrix3.multiply(m, Cesium.Matrix3.fromScale(scale), m);
   * Cesium.Matrix3.multiplyByScale(m, scale, m);
   *
   * @see Matrix3.multiplyByUniformScale
   * @see Matrix3.fromScale
   * @see Matrix3.fromUniformScale
   * @see Matrix3.setScale
   * @see Matrix3.setUniformScale
   * @see Matrix3.getScale
   */
  Matrix3.multiplyByScale = function (matrix, scale, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("scale", scale);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result[0] = matrix[0] * scale.x;
    result[1] = matrix[1] * scale.x;
    result[2] = matrix[2] * scale.x;
    result[3] = matrix[3] * scale.y;
    result[4] = matrix[4] * scale.y;
    result[5] = matrix[5] * scale.y;
    result[6] = matrix[6] * scale.z;
    result[7] = matrix[7] * scale.z;
    result[8] = matrix[8] * scale.z;

    return result;
  };

  /**
   * Computes the product of a matrix times a uniform scale, as if the scale were a scale matrix.
   *
   * @param {Matrix3} matrix The matrix on the left-hand side.
   * @param {Number} scale The uniform scale on the right-hand side.
   * @param {Matrix3} result The object onto which to store the result.
   * @returns {Matrix3} The modified result parameter.
   *
   * @example
   * // Instead of Cesium.Matrix3.multiply(m, Cesium.Matrix3.fromUniformScale(scale), m);
   * Cesium.Matrix3.multiplyByUniformScale(m, scale, m);
   *
   * @see Matrix3.multiplyByScale
   * @see Matrix3.fromScale
   * @see Matrix3.fromUniformScale
   * @see Matrix3.setScale
   * @see Matrix3.setUniformScale
   * @see Matrix3.getScale
   */
  Matrix3.multiplyByUniformScale = function (matrix, scale, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.number("scale", scale);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result[0] = matrix[0] * scale;
    result[1] = matrix[1] * scale;
    result[2] = matrix[2] * scale;
    result[3] = matrix[3] * scale;
    result[4] = matrix[4] * scale;
    result[5] = matrix[5] * scale;
    result[6] = matrix[6] * scale;
    result[7] = matrix[7] * scale;
    result[8] = matrix[8] * scale;

    return result;
  };

  /**
   * Creates a negated copy of the provided matrix.
   *
   * @param {Matrix3} matrix The matrix to negate.
   * @param {Matrix3} result The object onto which to store the result.
   * @returns {Matrix3} The modified result parameter.
   */
  Matrix3.negate = function (matrix, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result[0] = -matrix[0];
    result[1] = -matrix[1];
    result[2] = -matrix[2];
    result[3] = -matrix[3];
    result[4] = -matrix[4];
    result[5] = -matrix[5];
    result[6] = -matrix[6];
    result[7] = -matrix[7];
    result[8] = -matrix[8];
    return result;
  };

  /**
   * Computes the transpose of the provided matrix.
   *
   * @param {Matrix3} matrix The matrix to transpose.
   * @param {Matrix3} result The object onto which to store the result.
   * @returns {Matrix3} The modified result parameter.
   */
  Matrix3.transpose = function (matrix, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const column0Row0 = matrix[0];
    const column0Row1 = matrix[3];
    const column0Row2 = matrix[6];
    const column1Row0 = matrix[1];
    const column1Row1 = matrix[4];
    const column1Row2 = matrix[7];
    const column2Row0 = matrix[2];
    const column2Row1 = matrix[5];
    const column2Row2 = matrix[8];

    result[0] = column0Row0;
    result[1] = column0Row1;
    result[2] = column0Row2;
    result[3] = column1Row0;
    result[4] = column1Row1;
    result[5] = column1Row2;
    result[6] = column2Row0;
    result[7] = column2Row1;
    result[8] = column2Row2;
    return result;
  };

  function computeFrobeniusNorm(matrix) {
    let norm = 0.0;
    for (let i = 0; i < 9; ++i) {
      const temp = matrix[i];
      norm += temp * temp;
    }

    return Math.sqrt(norm);
  }

  const rowVal = [1, 0, 0];
  const colVal = [2, 2, 1];

  function offDiagonalFrobeniusNorm(matrix) {
    // Computes the "off-diagonal" Frobenius norm.
    // Assumes matrix is symmetric.

    let norm = 0.0;
    for (let i = 0; i < 3; ++i) {
      const temp = matrix[Matrix3.getElementIndex(colVal[i], rowVal[i])];
      norm += 2.0 * temp * temp;
    }

    return Math.sqrt(norm);
  }

  function shurDecomposition(matrix, result) {
    // This routine was created based upon Matrix Computations, 3rd ed., by Golub and Van Loan,
    // section 8.4.2 The 2by2 Symmetric Schur Decomposition.
    //
    // The routine takes a matrix, which is assumed to be symmetric, and
    // finds the largest off-diagonal term, and then creates
    // a matrix (result) which can be used to help reduce it

    const tolerance = CesiumMath.EPSILON15;

    let maxDiagonal = 0.0;
    let rotAxis = 1;

    // find pivot (rotAxis) based on max diagonal of matrix
    for (let i = 0; i < 3; ++i) {
      const temp = Math.abs(
        matrix[Matrix3.getElementIndex(colVal[i], rowVal[i])]
      );
      if (temp > maxDiagonal) {
        rotAxis = i;
        maxDiagonal = temp;
      }
    }

    let c = 1.0;
    let s = 0.0;

    const p = rowVal[rotAxis];
    const q = colVal[rotAxis];

    if (Math.abs(matrix[Matrix3.getElementIndex(q, p)]) > tolerance) {
      const qq = matrix[Matrix3.getElementIndex(q, q)];
      const pp = matrix[Matrix3.getElementIndex(p, p)];
      const qp = matrix[Matrix3.getElementIndex(q, p)];

      const tau = (qq - pp) / 2.0 / qp;
      let t;

      if (tau < 0.0) {
        t = -1.0 / (-tau + Math.sqrt(1.0 + tau * tau));
      } else {
        t = 1.0 / (tau + Math.sqrt(1.0 + tau * tau));
      }

      c = 1.0 / Math.sqrt(1.0 + t * t);
      s = t * c;
    }

    result = Matrix3.clone(Matrix3.IDENTITY, result);

    result[Matrix3.getElementIndex(p, p)] = result[
      Matrix3.getElementIndex(q, q)
    ] = c;
    result[Matrix3.getElementIndex(q, p)] = s;
    result[Matrix3.getElementIndex(p, q)] = -s;

    return result;
  }

  const jMatrix = new Matrix3();
  const jMatrixTranspose = new Matrix3();

  /**
   * Computes the eigenvectors and eigenvalues of a symmetric matrix.
   * <p>
   * Returns a diagonal matrix and unitary matrix such that:
   * <code>matrix = unitary matrix * diagonal matrix * transpose(unitary matrix)</code>
   * </p>
   * <p>
   * The values along the diagonal of the diagonal matrix are the eigenvalues. The columns
   * of the unitary matrix are the corresponding eigenvectors.
   * </p>
   *
   * @param {Matrix3} matrix The matrix to decompose into diagonal and unitary matrix. Expected to be symmetric.
   * @param {Object} [result] An object with unitary and diagonal properties which are matrices onto which to store the result.
   * @returns {Object} An object with unitary and diagonal properties which are the unitary and diagonal matrices, respectively.
   *
   * @example
   * const a = //... symetric matrix
   * const result = {
   *     unitary : new Cesium.Matrix3(),
   *     diagonal : new Cesium.Matrix3()
   * };
   * Cesium.Matrix3.computeEigenDecomposition(a, result);
   *
   * const unitaryTranspose = Cesium.Matrix3.transpose(result.unitary, new Cesium.Matrix3());
   * const b = Cesium.Matrix3.multiply(result.unitary, result.diagonal, new Cesium.Matrix3());
   * Cesium.Matrix3.multiply(b, unitaryTranspose, b); // b is now equal to a
   *
   * const lambda = Cesium.Matrix3.getColumn(result.diagonal, 0, new Cesium.Cartesian3()).x;  // first eigenvalue
   * const v = Cesium.Matrix3.getColumn(result.unitary, 0, new Cesium.Cartesian3());          // first eigenvector
   * const c = Cesium.Cartesian3.multiplyByScalar(v, lambda, new Cesium.Cartesian3());        // equal to Cesium.Matrix3.multiplyByVector(a, v)
   */
  Matrix3.computeEigenDecomposition = function (matrix, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    //>>includeEnd('debug');

    // This routine was created based upon Matrix Computations, 3rd ed., by Golub and Van Loan,
    // section 8.4.3 The Classical Jacobi Algorithm

    const tolerance = CesiumMath.EPSILON20;
    const maxSweeps = 10;

    let count = 0;
    let sweep = 0;

    if (!defined(result)) {
      result = {};
    }

    const unitaryMatrix = (result.unitary = Matrix3.clone(
      Matrix3.IDENTITY,
      result.unitary
    ));
    const diagMatrix = (result.diagonal = Matrix3.clone(matrix, result.diagonal));

    const epsilon = tolerance * computeFrobeniusNorm(diagMatrix);

    while (sweep < maxSweeps && offDiagonalFrobeniusNorm(diagMatrix) > epsilon) {
      shurDecomposition(diagMatrix, jMatrix);
      Matrix3.transpose(jMatrix, jMatrixTranspose);
      Matrix3.multiply(diagMatrix, jMatrix, diagMatrix);
      Matrix3.multiply(jMatrixTranspose, diagMatrix, diagMatrix);
      Matrix3.multiply(unitaryMatrix, jMatrix, unitaryMatrix);

      if (++count > 2) {
        ++sweep;
        count = 0;
      }
    }

    return result;
  };

  /**
   * Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
   *
   * @param {Matrix3} matrix The matrix with signed elements.
   * @param {Matrix3} result The object onto which to store the result.
   * @returns {Matrix3} The modified result parameter.
   */
  Matrix3.abs = function (matrix, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result[0] = Math.abs(matrix[0]);
    result[1] = Math.abs(matrix[1]);
    result[2] = Math.abs(matrix[2]);
    result[3] = Math.abs(matrix[3]);
    result[4] = Math.abs(matrix[4]);
    result[5] = Math.abs(matrix[5]);
    result[6] = Math.abs(matrix[6]);
    result[7] = Math.abs(matrix[7]);
    result[8] = Math.abs(matrix[8]);

    return result;
  };

  /**
   * Computes the determinant of the provided matrix.
   *
   * @param {Matrix3} matrix The matrix to use.
   * @returns {Number} The value of the determinant of the matrix.
   */
  Matrix3.determinant = function (matrix) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    //>>includeEnd('debug');

    const m11 = matrix[0];
    const m21 = matrix[3];
    const m31 = matrix[6];
    const m12 = matrix[1];
    const m22 = matrix[4];
    const m32 = matrix[7];
    const m13 = matrix[2];
    const m23 = matrix[5];
    const m33 = matrix[8];

    return (
      m11 * (m22 * m33 - m23 * m32) +
      m12 * (m23 * m31 - m21 * m33) +
      m13 * (m21 * m32 - m22 * m31)
    );
  };

  /**
   * Computes the inverse of the provided matrix.
   *
   * @param {Matrix3} matrix The matrix to invert.
   * @param {Matrix3} result The object onto which to store the result.
   * @returns {Matrix3} The modified result parameter.
   *
   * @exception {DeveloperError} matrix is not invertible.
   */
  Matrix3.inverse = function (matrix, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const m11 = matrix[0];
    const m21 = matrix[1];
    const m31 = matrix[2];
    const m12 = matrix[3];
    const m22 = matrix[4];
    const m32 = matrix[5];
    const m13 = matrix[6];
    const m23 = matrix[7];
    const m33 = matrix[8];

    const determinant = Matrix3.determinant(matrix);

    //>>includeStart('debug', pragmas.debug);
    if (Math.abs(determinant) <= CesiumMath.EPSILON15) {
      throw new DeveloperError("matrix is not invertible");
    }
    //>>includeEnd('debug');

    result[0] = m22 * m33 - m23 * m32;
    result[1] = m23 * m31 - m21 * m33;
    result[2] = m21 * m32 - m22 * m31;
    result[3] = m13 * m32 - m12 * m33;
    result[4] = m11 * m33 - m13 * m31;
    result[5] = m12 * m31 - m11 * m32;
    result[6] = m12 * m23 - m13 * m22;
    result[7] = m13 * m21 - m11 * m23;
    result[8] = m11 * m22 - m12 * m21;

    const scale = 1.0 / determinant;
    return Matrix3.multiplyByScalar(result, scale, result);
  };

  const scratchTransposeMatrix$1 = new Matrix3();

  /**
   * Computes the inverse transpose of a matrix.
   *
   * @param {Matrix3} matrix The matrix to transpose and invert.
   * @param {Matrix3} result The object onto which to store the result.
   * @returns {Matrix3} The modified result parameter.
   */
  Matrix3.inverseTranspose = function (matrix, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    return Matrix3.inverse(
      Matrix3.transpose(matrix, scratchTransposeMatrix$1),
      result
    );
  };

  /**
   * Compares the provided matrices componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Matrix3} [left] The first matrix.
   * @param {Matrix3} [right] The second matrix.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  Matrix3.equals = function (left, right) {
    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        left[0] === right[0] &&
        left[1] === right[1] &&
        left[2] === right[2] &&
        left[3] === right[3] &&
        left[4] === right[4] &&
        left[5] === right[5] &&
        left[6] === right[6] &&
        left[7] === right[7] &&
        left[8] === right[8])
    );
  };

  /**
   * Compares the provided matrices componentwise and returns
   * <code>true</code> if they are within the provided epsilon,
   * <code>false</code> otherwise.
   *
   * @param {Matrix3} [left] The first matrix.
   * @param {Matrix3} [right] The second matrix.
   * @param {Number} [epsilon=0] The epsilon to use for equality testing.
   * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
   */
  Matrix3.equalsEpsilon = function (left, right, epsilon) {
    epsilon = defaultValue(epsilon, 0);

    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        Math.abs(left[0] - right[0]) <= epsilon &&
        Math.abs(left[1] - right[1]) <= epsilon &&
        Math.abs(left[2] - right[2]) <= epsilon &&
        Math.abs(left[3] - right[3]) <= epsilon &&
        Math.abs(left[4] - right[4]) <= epsilon &&
        Math.abs(left[5] - right[5]) <= epsilon &&
        Math.abs(left[6] - right[6]) <= epsilon &&
        Math.abs(left[7] - right[7]) <= epsilon &&
        Math.abs(left[8] - right[8]) <= epsilon)
    );
  };

  /**
   * An immutable Matrix3 instance initialized to the identity matrix.
   *
   * @type {Matrix3}
   * @constant
   */
  Matrix3.IDENTITY = Object.freeze(
    new Matrix3(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0)
  );

  /**
   * An immutable Matrix3 instance initialized to the zero matrix.
   *
   * @type {Matrix3}
   * @constant
   */
  Matrix3.ZERO = Object.freeze(
    new Matrix3(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
  );

  /**
   * The index into Matrix3 for column 0, row 0.
   *
   * @type {Number}
   * @constant
   */
  Matrix3.COLUMN0ROW0 = 0;

  /**
   * The index into Matrix3 for column 0, row 1.
   *
   * @type {Number}
   * @constant
   */
  Matrix3.COLUMN0ROW1 = 1;

  /**
   * The index into Matrix3 for column 0, row 2.
   *
   * @type {Number}
   * @constant
   */
  Matrix3.COLUMN0ROW2 = 2;

  /**
   * The index into Matrix3 for column 1, row 0.
   *
   * @type {Number}
   * @constant
   */
  Matrix3.COLUMN1ROW0 = 3;

  /**
   * The index into Matrix3 for column 1, row 1.
   *
   * @type {Number}
   * @constant
   */
  Matrix3.COLUMN1ROW1 = 4;

  /**
   * The index into Matrix3 for column 1, row 2.
   *
   * @type {Number}
   * @constant
   */
  Matrix3.COLUMN1ROW2 = 5;

  /**
   * The index into Matrix3 for column 2, row 0.
   *
   * @type {Number}
   * @constant
   */
  Matrix3.COLUMN2ROW0 = 6;

  /**
   * The index into Matrix3 for column 2, row 1.
   *
   * @type {Number}
   * @constant
   */
  Matrix3.COLUMN2ROW1 = 7;

  /**
   * The index into Matrix3 for column 2, row 2.
   *
   * @type {Number}
   * @constant
   */
  Matrix3.COLUMN2ROW2 = 8;

  Object.defineProperties(Matrix3.prototype, {
    /**
     * Gets the number of items in the collection.
     * @memberof Matrix3.prototype
     *
     * @type {Number}
     */
    length: {
      get: function () {
        return Matrix3.packedLength;
      },
    },
  });

  /**
   * Duplicates the provided Matrix3 instance.
   *
   * @param {Matrix3} [result] The object onto which to store the result.
   * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
   */
  Matrix3.prototype.clone = function (result) {
    return Matrix3.clone(this, result);
  };

  /**
   * Compares this matrix to the provided matrix componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Matrix3} [right] The right hand side matrix.
   * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
   */
  Matrix3.prototype.equals = function (right) {
    return Matrix3.equals(this, right);
  };

  /**
   * @private
   */
  Matrix3.equalsArray = function (matrix, array, offset) {
    return (
      matrix[0] === array[offset] &&
      matrix[1] === array[offset + 1] &&
      matrix[2] === array[offset + 2] &&
      matrix[3] === array[offset + 3] &&
      matrix[4] === array[offset + 4] &&
      matrix[5] === array[offset + 5] &&
      matrix[6] === array[offset + 6] &&
      matrix[7] === array[offset + 7] &&
      matrix[8] === array[offset + 8]
    );
  };

  /**
   * Compares this matrix to the provided matrix componentwise and returns
   * <code>true</code> if they are within the provided epsilon,
   * <code>false</code> otherwise.
   *
   * @param {Matrix3} [right] The right hand side matrix.
   * @param {Number} [epsilon=0] The epsilon to use for equality testing.
   * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
   */
  Matrix3.prototype.equalsEpsilon = function (right, epsilon) {
    return Matrix3.equalsEpsilon(this, right, epsilon);
  };

  /**
   * Creates a string representing this Matrix with each row being
   * on a separate line and in the format '(column0, column1, column2)'.
   *
   * @returns {String} A string representing the provided Matrix with each row being on a separate line and in the format '(column0, column1, column2)'.
   */
  Matrix3.prototype.toString = function () {
    return (
      `(${this[0]}, ${this[3]}, ${this[6]})\n` +
      `(${this[1]}, ${this[4]}, ${this[7]})\n` +
      `(${this[2]}, ${this[5]}, ${this[8]})`
    );
  };

  /**
   * A 4D Cartesian point.
   * @alias Cartesian4
   * @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 Cartesian2
   * @see Cartesian3
   * @see Packable
   */
  function Cartesian4(x, y, z, w) {
    /**
     * The X component.
     * @type {Number}
     * @default 0.0
     */
    this.x = defaultValue(x, 0.0);

    /**
     * The Y component.
     * @type {Number}
     * @default 0.0
     */
    this.y = defaultValue(y, 0.0);

    /**
     * The Z component.
     * @type {Number}
     * @default 0.0
     */
    this.z = defaultValue(z, 0.0);

    /**
     * The W component.
     * @type {Number}
     * @default 0.0
     */
    this.w = defaultValue(w, 0.0);
  }

  /**
   * Creates a Cartesian4 instance from x, y, z and w coordinates.
   *
   * @param {Number} x The x coordinate.
   * @param {Number} y The y coordinate.
   * @param {Number} z The z coordinate.
   * @param {Number} w The w coordinate.
   * @param {Cartesian4} [result] The object onto which to store the result.
   * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
   */
  Cartesian4.fromElements = function (x, y, z, w, result) {
    if (!defined(result)) {
      return new Cartesian4(x, y, z, w);
    }

    result.x = x;
    result.y = y;
    result.z = z;
    result.w = w;
    return result;
  };

  /**
   * Creates a Cartesian4 instance from a {@link Color}. <code>red</code>, <code>green</code>, <code>blue</code>,
   * and <code>alpha</code> map to <code>x</code>, <code>y</code>, <code>z</code>, and <code>w</code>, respectively.
   *
   * @param {Color} color The source color.
   * @param {Cartesian4} [result] The object onto which to store the result.
   * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
   */
  Cartesian4.fromColor = function (color, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("color", color);
    //>>includeEnd('debug');
    if (!defined(result)) {
      return new Cartesian4(color.red, color.green, color.blue, color.alpha);
    }

    result.x = color.red;
    result.y = color.green;
    result.z = color.blue;
    result.w = color.alpha;
    return result;
  };

  /**
   * Duplicates a Cartesian4 instance.
   *
   * @param {Cartesian4} cartesian The Cartesian to duplicate.
   * @param {Cartesian4} [result] The object onto which to store the result.
   * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided. (Returns undefined if cartesian is undefined)
   */
  Cartesian4.clone = function (cartesian, result) {
    if (!defined(cartesian)) {
      return undefined;
    }

    if (!defined(result)) {
      return new Cartesian4(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
    }

    result.x = cartesian.x;
    result.y = cartesian.y;
    result.z = cartesian.z;
    result.w = cartesian.w;
    return result;
  };

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  Cartesian4.packedLength = 4;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {Cartesian4} 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
   */
  Cartesian4.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = 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 {Cartesian4} [result] The object into which to store the result.
   * @returns {Cartesian4}  The modified result parameter or a new Cartesian4 instance if one was not provided.
   */
  Cartesian4.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    if (!defined(result)) {
      result = new Cartesian4();
    }
    result.x = array[startingIndex++];
    result.y = array[startingIndex++];
    result.z = array[startingIndex++];
    result.w = array[startingIndex];
    return result;
  };

  /**
   * Flattens an array of Cartesian4s into an array of components.
   *
   * @param {Cartesian4[]} array The array of cartesians to pack.
   * @param {Number[]} [result] The array onto which to store the result. If this is a typed array, it must have array.length * 4 components, else a {@link DeveloperError} will be thrown. If it is a regular array, it will be resized to have (array.length * 4) elements.
   * @returns {Number[]} The packed array.
   */
  Cartesian4.packArray = function (array, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    const length = array.length;
    const resultLength = length * 4;
    if (!defined(result)) {
      result = new Array(resultLength);
    } else if (!Array.isArray(result) && result.length !== resultLength) {
      //>>includeStart('debug', pragmas.debug);
      throw new DeveloperError(
        "If result is a typed array, it must have exactly array.length * 4 elements"
      );
      //>>includeEnd('debug');
    } else if (result.length !== resultLength) {
      result.length = resultLength;
    }

    for (let i = 0; i < length; ++i) {
      Cartesian4.pack(array[i], result, i * 4);
    }
    return result;
  };

  /**
   * Unpacks an array of cartesian components into an array of Cartesian4s.
   *
   * @param {Number[]} array The array of components to unpack.
   * @param {Cartesian4[]} [result] The array onto which to store the result.
   * @returns {Cartesian4[]} The unpacked array.
   */
  Cartesian4.unpackArray = function (array, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    Check.typeOf.number.greaterThanOrEquals("array.length", array.length, 4);
    if (array.length % 4 !== 0) {
      throw new DeveloperError("array length must be a multiple of 4.");
    }
    //>>includeEnd('debug');

    const length = array.length;
    if (!defined(result)) {
      result = new Array(length / 4);
    } else {
      result.length = length / 4;
    }

    for (let i = 0; i < length; i += 4) {
      const index = i / 4;
      result[index] = Cartesian4.unpack(array, i, result[index]);
    }
    return result;
  };

  /**
   * Creates a Cartesian4 from four consecutive elements in an array.
   * @function
   *
   * @param {Number[]} array The array whose four consecutive elements correspond to the x, y, z, and w components, respectively.
   * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to the x component.
   * @param {Cartesian4} [result] The object onto which to store the result.
   * @returns {Cartesian4}  The modified result parameter or a new Cartesian4 instance if one was not provided.
   *
   * @example
   * // Create a Cartesian4 with (1.0, 2.0, 3.0, 4.0)
   * const v = [1.0, 2.0, 3.0, 4.0];
   * const p = Cesium.Cartesian4.fromArray(v);
   *
   * // Create a Cartesian4 with (1.0, 2.0, 3.0, 4.0) using an offset into an array
   * const v2 = [0.0, 0.0, 1.0, 2.0, 3.0, 4.0];
   * const p2 = Cesium.Cartesian4.fromArray(v2, 2);
   */
  Cartesian4.fromArray = Cartesian4.unpack;

  /**
   * Computes the value of the maximum component for the supplied Cartesian.
   *
   * @param {Cartesian4} cartesian The cartesian to use.
   * @returns {Number} The value of the maximum component.
   */
  Cartesian4.maximumComponent = function (cartesian) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartesian", cartesian);
    //>>includeEnd('debug');

    return Math.max(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
  };

  /**
   * Computes the value of the minimum component for the supplied Cartesian.
   *
   * @param {Cartesian4} cartesian The cartesian to use.
   * @returns {Number} The value of the minimum component.
   */
  Cartesian4.minimumComponent = function (cartesian) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartesian", cartesian);
    //>>includeEnd('debug');

    return Math.min(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
  };

  /**
   * Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
   *
   * @param {Cartesian4} first A cartesian to compare.
   * @param {Cartesian4} second A cartesian to compare.
   * @param {Cartesian4} result The object into which to store the result.
   * @returns {Cartesian4} A cartesian with the minimum components.
   */
  Cartesian4.minimumByComponent = function (first, second, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("first", first);
    Check.typeOf.object("second", second);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.x = Math.min(first.x, second.x);
    result.y = Math.min(first.y, second.y);
    result.z = Math.min(first.z, second.z);
    result.w = Math.min(first.w, second.w);

    return result;
  };

  /**
   * Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
   *
   * @param {Cartesian4} first A cartesian to compare.
   * @param {Cartesian4} second A cartesian to compare.
   * @param {Cartesian4} result The object into which to store the result.
   * @returns {Cartesian4} A cartesian with the maximum components.
   */
  Cartesian4.maximumByComponent = function (first, second, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("first", first);
    Check.typeOf.object("second", second);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.x = Math.max(first.x, second.x);
    result.y = Math.max(first.y, second.y);
    result.z = Math.max(first.z, second.z);
    result.w = Math.max(first.w, second.w);

    return result;
  };

  /**
   * Constrain a value to lie between two values.
   *
   * @param {Cartesian4} value The value to clamp.
   * @param {Cartesian4} min The minimum bound.
   * @param {Cartesian4} max The maximum bound.
   * @param {Cartesian4} result The object into which to store the result.
   * @returns {Cartesian4} The clamped value such that min <= result <= max.
   */
  Cartesian4.clamp = function (value, min, max, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    Check.typeOf.object("min", min);
    Check.typeOf.object("max", max);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const x = CesiumMath.clamp(value.x, min.x, max.x);
    const y = CesiumMath.clamp(value.y, min.y, max.y);
    const z = CesiumMath.clamp(value.z, min.z, max.z);
    const w = CesiumMath.clamp(value.w, min.w, max.w);

    result.x = x;
    result.y = y;
    result.z = z;
    result.w = w;

    return result;
  };

  /**
   * Computes the provided Cartesian's squared magnitude.
   *
   * @param {Cartesian4} cartesian The Cartesian instance whose squared magnitude is to be computed.
   * @returns {Number} The squared magnitude.
   */
  Cartesian4.magnitudeSquared = function (cartesian) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartesian", cartesian);
    //>>includeEnd('debug');

    return (
      cartesian.x * cartesian.x +
      cartesian.y * cartesian.y +
      cartesian.z * cartesian.z +
      cartesian.w * cartesian.w
    );
  };

  /**
   * Computes the Cartesian's magnitude (length).
   *
   * @param {Cartesian4} cartesian The Cartesian instance whose magnitude is to be computed.
   * @returns {Number} The magnitude.
   */
  Cartesian4.magnitude = function (cartesian) {
    return Math.sqrt(Cartesian4.magnitudeSquared(cartesian));
  };

  const distanceScratch$2 = new Cartesian4();

  /**
   * Computes the 4-space distance between two points.
   *
   * @param {Cartesian4} left The first point to compute the distance from.
   * @param {Cartesian4} right The second point to compute the distance to.
   * @returns {Number} The distance between two points.
   *
   * @example
   * // Returns 1.0
   * const d = Cesium.Cartesian4.distance(
   *   new Cesium.Cartesian4(1.0, 0.0, 0.0, 0.0),
   *   new Cesium.Cartesian4(2.0, 0.0, 0.0, 0.0));
   */
  Cartesian4.distance = function (left, right) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    //>>includeEnd('debug');

    Cartesian4.subtract(left, right, distanceScratch$2);
    return Cartesian4.magnitude(distanceScratch$2);
  };

  /**
   * Computes the squared distance between two points.  Comparing squared distances
   * using this function is more efficient than comparing distances using {@link Cartesian4#distance}.
   *
   * @param {Cartesian4} left The first point to compute the distance from.
   * @param {Cartesian4} right The second point to compute the distance to.
   * @returns {Number} The distance between two points.
   *
   * @example
   * // Returns 4.0, not 2.0
   * const d = Cesium.Cartesian4.distance(
   *   new Cesium.Cartesian4(1.0, 0.0, 0.0, 0.0),
   *   new Cesium.Cartesian4(3.0, 0.0, 0.0, 0.0));
   */
  Cartesian4.distanceSquared = function (left, right) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    //>>includeEnd('debug');

    Cartesian4.subtract(left, right, distanceScratch$2);
    return Cartesian4.magnitudeSquared(distanceScratch$2);
  };

  /**
   * Computes the normalized form of the supplied Cartesian.
   *
   * @param {Cartesian4} cartesian The Cartesian to be normalized.
   * @param {Cartesian4} result The object onto which to store the result.
   * @returns {Cartesian4} The modified result parameter.
   */
  Cartesian4.normalize = function (cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const magnitude = Cartesian4.magnitude(cartesian);

    result.x = cartesian.x / magnitude;
    result.y = cartesian.y / magnitude;
    result.z = cartesian.z / magnitude;
    result.w = cartesian.w / magnitude;

    //>>includeStart('debug', pragmas.debug);
    if (
      isNaN(result.x) ||
      isNaN(result.y) ||
      isNaN(result.z) ||
      isNaN(result.w)
    ) {
      throw new DeveloperError("normalized result is not a number");
    }
    //>>includeEnd('debug');

    return result;
  };

  /**
   * Computes the dot (scalar) product of two Cartesians.
   *
   * @param {Cartesian4} left The first Cartesian.
   * @param {Cartesian4} right The second Cartesian.
   * @returns {Number} The dot product.
   */
  Cartesian4.dot = function (left, right) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    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 componentwise product of two Cartesians.
   *
   * @param {Cartesian4} left The first Cartesian.
   * @param {Cartesian4} right The second Cartesian.
   * @param {Cartesian4} result The object onto which to store the result.
   * @returns {Cartesian4} The modified result parameter.
   */
  Cartesian4.multiplyComponents = function (left, right, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    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 quotient of two Cartesians.
   *
   * @param {Cartesian4} left The first Cartesian.
   * @param {Cartesian4} right The second Cartesian.
   * @param {Cartesian4} result The object onto which to store the result.
   * @returns {Cartesian4} The modified result parameter.
   */
  Cartesian4.divideComponents = function (left, right, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    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 sum of two Cartesians.
   *
   * @param {Cartesian4} left The first Cartesian.
   * @param {Cartesian4} right The second Cartesian.
   * @param {Cartesian4} result The object onto which to store the result.
   * @returns {Cartesian4} The modified result parameter.
   */
  Cartesian4.add = function (left, right, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    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 Cartesians.
   *
   * @param {Cartesian4} left The first Cartesian.
   * @param {Cartesian4} right The second Cartesian.
   * @param {Cartesian4} result The object onto which to store the result.
   * @returns {Cartesian4} The modified result parameter.
   */
  Cartesian4.subtract = function (left, right, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    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;
  };

  /**
   * Multiplies the provided Cartesian componentwise by the provided scalar.
   *
   * @param {Cartesian4} cartesian The Cartesian to be scaled.
   * @param {Number} scalar The scalar to multiply with.
   * @param {Cartesian4} result The object onto which to store the result.
   * @returns {Cartesian4} The modified result parameter.
   */
  Cartesian4.multiplyByScalar = function (cartesian, scalar, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.number("scalar", scalar);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.x = cartesian.x * scalar;
    result.y = cartesian.y * scalar;
    result.z = cartesian.z * scalar;
    result.w = cartesian.w * scalar;
    return result;
  };

  /**
   * Divides the provided Cartesian componentwise by the provided scalar.
   *
   * @param {Cartesian4} cartesian The Cartesian to be divided.
   * @param {Number} scalar The scalar to divide by.
   * @param {Cartesian4} result The object onto which to store the result.
   * @returns {Cartesian4} The modified result parameter.
   */
  Cartesian4.divideByScalar = function (cartesian, scalar, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.number("scalar", scalar);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.x = cartesian.x / scalar;
    result.y = cartesian.y / scalar;
    result.z = cartesian.z / scalar;
    result.w = cartesian.w / scalar;
    return result;
  };

  /**
   * Negates the provided Cartesian.
   *
   * @param {Cartesian4} cartesian The Cartesian to be negated.
   * @param {Cartesian4} result The object onto which to store the result.
   * @returns {Cartesian4} The modified result parameter.
   */
  Cartesian4.negate = function (cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.x = -cartesian.x;
    result.y = -cartesian.y;
    result.z = -cartesian.z;
    result.w = -cartesian.w;
    return result;
  };

  /**
   * Computes the absolute value of the provided Cartesian.
   *
   * @param {Cartesian4} cartesian The Cartesian whose absolute value is to be computed.
   * @param {Cartesian4} result The object onto which to store the result.
   * @returns {Cartesian4} The modified result parameter.
   */
  Cartesian4.abs = function (cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.x = Math.abs(cartesian.x);
    result.y = Math.abs(cartesian.y);
    result.z = Math.abs(cartesian.z);
    result.w = Math.abs(cartesian.w);
    return result;
  };

  const lerpScratch$2 = new Cartesian4();
  /**
   * Computes the linear interpolation or extrapolation at t using the provided cartesians.
   *
   * @param {Cartesian4} start The value corresponding to t at 0.0.
   * @param {Cartesian4}end The value corresponding to t at 1.0.
   * @param {Number} t The point along t at which to interpolate.
   * @param {Cartesian4} result The object onto which to store the result.
   * @returns {Cartesian4} The modified result parameter.
   */
  Cartesian4.lerp = function (start, end, t, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("start", start);
    Check.typeOf.object("end", end);
    Check.typeOf.number("t", t);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    Cartesian4.multiplyByScalar(end, t, lerpScratch$2);
    result = Cartesian4.multiplyByScalar(start, 1.0 - t, result);
    return Cartesian4.add(lerpScratch$2, result, result);
  };

  const mostOrthogonalAxisScratch$1 = new Cartesian4();
  /**
   * Returns the axis that is most orthogonal to the provided Cartesian.
   *
   * @param {Cartesian4} cartesian The Cartesian on which to find the most orthogonal axis.
   * @param {Cartesian4} result The object onto which to store the result.
   * @returns {Cartesian4} The most orthogonal axis.
   */
  Cartesian4.mostOrthogonalAxis = function (cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const f = Cartesian4.normalize(cartesian, mostOrthogonalAxisScratch$1);
    Cartesian4.abs(f, f);

    if (f.x <= f.y) {
      if (f.x <= f.z) {
        if (f.x <= f.w) {
          result = Cartesian4.clone(Cartesian4.UNIT_X, result);
        } else {
          result = Cartesian4.clone(Cartesian4.UNIT_W, result);
        }
      } else if (f.z <= f.w) {
        result = Cartesian4.clone(Cartesian4.UNIT_Z, result);
      } else {
        result = Cartesian4.clone(Cartesian4.UNIT_W, result);
      }
    } else if (f.y <= f.z) {
      if (f.y <= f.w) {
        result = Cartesian4.clone(Cartesian4.UNIT_Y, result);
      } else {
        result = Cartesian4.clone(Cartesian4.UNIT_W, result);
      }
    } else if (f.z <= f.w) {
      result = Cartesian4.clone(Cartesian4.UNIT_Z, result);
    } else {
      result = Cartesian4.clone(Cartesian4.UNIT_W, result);
    }

    return result;
  };

  /**
   * Compares the provided Cartesians componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Cartesian4} [left] The first Cartesian.
   * @param {Cartesian4} [right] The second Cartesian.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  Cartesian4.equals = function (left, right) {
    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        left.x === right.x &&
        left.y === right.y &&
        left.z === right.z &&
        left.w === right.w)
    );
  };

  /**
   * @private
   */
  Cartesian4.equalsArray = function (cartesian, array, offset) {
    return (
      cartesian.x === array[offset] &&
      cartesian.y === array[offset + 1] &&
      cartesian.z === array[offset + 2] &&
      cartesian.w === array[offset + 3]
    );
  };

  /**
   * Compares the provided Cartesians componentwise and returns
   * <code>true</code> if they pass an absolute or relative tolerance test,
   * <code>false</code> otherwise.
   *
   * @param {Cartesian4} [left] The first Cartesian.
   * @param {Cartesian4} [right] The second Cartesian.
   * @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} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
   */
  Cartesian4.equalsEpsilon = function (
    left,
    right,
    relativeEpsilon,
    absoluteEpsilon
  ) {
    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        CesiumMath.equalsEpsilon(
          left.x,
          right.x,
          relativeEpsilon,
          absoluteEpsilon
        ) &&
        CesiumMath.equalsEpsilon(
          left.y,
          right.y,
          relativeEpsilon,
          absoluteEpsilon
        ) &&
        CesiumMath.equalsEpsilon(
          left.z,
          right.z,
          relativeEpsilon,
          absoluteEpsilon
        ) &&
        CesiumMath.equalsEpsilon(
          left.w,
          right.w,
          relativeEpsilon,
          absoluteEpsilon
        ))
    );
  };

  /**
   * An immutable Cartesian4 instance initialized to (0.0, 0.0, 0.0, 0.0).
   *
   * @type {Cartesian4}
   * @constant
   */
  Cartesian4.ZERO = Object.freeze(new Cartesian4(0.0, 0.0, 0.0, 0.0));

  /**
   * An immutable Cartesian4 instance initialized to (1.0, 1.0, 1.0, 1.0).
   *
   * @type {Cartesian4}
   * @constant
   */
  Cartesian4.ONE = Object.freeze(new Cartesian4(1.0, 1.0, 1.0, 1.0));

  /**
   * An immutable Cartesian4 instance initialized to (1.0, 0.0, 0.0, 0.0).
   *
   * @type {Cartesian4}
   * @constant
   */
  Cartesian4.UNIT_X = Object.freeze(new Cartesian4(1.0, 0.0, 0.0, 0.0));

  /**
   * An immutable Cartesian4 instance initialized to (0.0, 1.0, 0.0, 0.0).
   *
   * @type {Cartesian4}
   * @constant
   */
  Cartesian4.UNIT_Y = Object.freeze(new Cartesian4(0.0, 1.0, 0.0, 0.0));

  /**
   * An immutable Cartesian4 instance initialized to (0.0, 0.0, 1.0, 0.0).
   *
   * @type {Cartesian4}
   * @constant
   */
  Cartesian4.UNIT_Z = Object.freeze(new Cartesian4(0.0, 0.0, 1.0, 0.0));

  /**
   * An immutable Cartesian4 instance initialized to (0.0, 0.0, 0.0, 1.0).
   *
   * @type {Cartesian4}
   * @constant
   */
  Cartesian4.UNIT_W = Object.freeze(new Cartesian4(0.0, 0.0, 0.0, 1.0));

  /**
   * Duplicates this Cartesian4 instance.
   *
   * @param {Cartesian4} [result] The object onto which to store the result.
   * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
   */
  Cartesian4.prototype.clone = function (result) {
    return Cartesian4.clone(this, result);
  };

  /**
   * Compares this Cartesian against the provided Cartesian componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Cartesian4} [right] The right hand side Cartesian.
   * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
   */
  Cartesian4.prototype.equals = function (right) {
    return Cartesian4.equals(this, right);
  };

  /**
   * Compares this Cartesian against the provided Cartesian componentwise and returns
   * <code>true</code> if they pass an absolute or relative tolerance test,
   * <code>false</code> otherwise.
   *
   * @param {Cartesian4} [right] The right hand side Cartesian.
   * @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} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
   */
  Cartesian4.prototype.equalsEpsilon = function (
    right,
    relativeEpsilon,
    absoluteEpsilon
  ) {
    return Cartesian4.equalsEpsilon(
      this,
      right,
      relativeEpsilon,
      absoluteEpsilon
    );
  };

  /**
   * Creates a string representing this Cartesian in the format '(x, y, z, w)'.
   *
   * @returns {String} A string representing the provided Cartesian in the format '(x, y, z, w)'.
   */
  Cartesian4.prototype.toString = function () {
    return `(${this.x}, ${this.y}, ${this.z}, ${this.w})`;
  };

  // scratchU8Array and scratchF32Array are views into the same buffer
  const scratchF32Array = new Float32Array(1);
  const scratchU8Array = new Uint8Array(scratchF32Array.buffer);

  const testU32 = new Uint32Array([0x11223344]);
  const testU8 = new Uint8Array(testU32.buffer);
  const littleEndian = testU8[0] === 0x44;

  /**
   * Packs an arbitrary floating point value to 4 values representable using uint8.
   *
   * @param {Number} value A floating point number.
   * @param {Cartesian4} [result] The Cartesian4 that will contain the packed float.
   * @returns {Cartesian4} A Cartesian4 representing the float packed to values in x, y, z, and w.
   */
  Cartesian4.packFloat = function (value, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("value", value);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Cartesian4();
    }

    // scratchU8Array and scratchF32Array are views into the same buffer
    scratchF32Array[0] = value;

    if (littleEndian) {
      result.x = scratchU8Array[0];
      result.y = scratchU8Array[1];
      result.z = scratchU8Array[2];
      result.w = scratchU8Array[3];
    } else {
      // convert from big-endian to little-endian
      result.x = scratchU8Array[3];
      result.y = scratchU8Array[2];
      result.z = scratchU8Array[1];
      result.w = scratchU8Array[0];
    }
    return result;
  };

  /**
   * Unpacks a float packed using Cartesian4.packFloat.
   *
   * @param {Cartesian4} packedFloat A Cartesian4 containing a float packed to 4 values representable using uint8.
   * @returns {Number} The unpacked float.
   * @private
   */
  Cartesian4.unpackFloat = function (packedFloat) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("packedFloat", packedFloat);
    //>>includeEnd('debug');

    // scratchU8Array and scratchF32Array are views into the same buffer
    if (littleEndian) {
      scratchU8Array[0] = packedFloat.x;
      scratchU8Array[1] = packedFloat.y;
      scratchU8Array[2] = packedFloat.z;
      scratchU8Array[3] = packedFloat.w;
    } else {
      // convert from little-endian to big-endian
      scratchU8Array[0] = packedFloat.w;
      scratchU8Array[1] = packedFloat.z;
      scratchU8Array[2] = packedFloat.y;
      scratchU8Array[3] = packedFloat.x;
    }
    return scratchF32Array[0];
  };

  /**
   * Constructs an exception object that is thrown due to an error that can occur at runtime, e.g.,
   * out of memory, could not compile shader, etc.  If a function may throw this
   * exception, the calling code should be prepared to catch it.
   * <br /><br />
   * On the other hand, a {@link DeveloperError} indicates an exception due
   * to a developer error, e.g., invalid argument, that usually indicates a bug in the
   * calling code.
   *
   * @alias RuntimeError
   * @constructor
   * @extends Error
   *
   * @param {String} [message] The error message for this exception.
   *
   * @see DeveloperError
   */
  function RuntimeError(message) {
    /**
     * 'RuntimeError' indicating that this exception was thrown due to a runtime error.
     * @type {String}
     * @readonly
     */
    this.name = "RuntimeError";

    /**
     * The explanation for why this exception was thrown.
     * @type {String}
     * @readonly
     */
    this.message = message;

    //Browsers such as IE don't have a stack property until you actually throw the error.
    let stack;
    try {
      throw new Error();
    } catch (e) {
      stack = e.stack;
    }

    /**
     * The stack trace of this exception, if available.
     * @type {String}
     * @readonly
     */
    this.stack = stack;
  }

  if (defined(Object.create)) {
    RuntimeError.prototype = Object.create(Error.prototype);
    RuntimeError.prototype.constructor = RuntimeError;
  }

  RuntimeError.prototype.toString = function () {
    let str = `${this.name}: ${this.message}`;

    if (defined(this.stack)) {
      str += `\n${this.stack.toString()}`;
    }

    return str;
  };

  /**
   * A 4x4 matrix, indexable as a column-major order array.
   * Constructor parameters are in row-major order for code readability.
   * @alias Matrix4
   * @constructor
   * @implements {ArrayLike<number>}
   *
   * @param {Number} [column0Row0=0.0] The value for column 0, row 0.
   * @param {Number} [column1Row0=0.0] The value for column 1, row 0.
   * @param {Number} [column2Row0=0.0] The value for column 2, row 0.
   * @param {Number} [column3Row0=0.0] The value for column 3, row 0.
   * @param {Number} [column0Row1=0.0] The value for column 0, row 1.
   * @param {Number} [column1Row1=0.0] The value for column 1, row 1.
   * @param {Number} [column2Row1=0.0] The value for column 2, row 1.
   * @param {Number} [column3Row1=0.0] The value for column 3, row 1.
   * @param {Number} [column0Row2=0.0] The value for column 0, row 2.
   * @param {Number} [column1Row2=0.0] The value for column 1, row 2.
   * @param {Number} [column2Row2=0.0] The value for column 2, row 2.
   * @param {Number} [column3Row2=0.0] The value for column 3, row 2.
   * @param {Number} [column0Row3=0.0] The value for column 0, row 3.
   * @param {Number} [column1Row3=0.0] The value for column 1, row 3.
   * @param {Number} [column2Row3=0.0] The value for column 2, row 3.
   * @param {Number} [column3Row3=0.0] The value for column 3, row 3.
   *
   * @see Matrix4.fromArray
   * @see Matrix4.fromColumnMajorArray
   * @see Matrix4.fromRowMajorArray
   * @see Matrix4.fromRotationTranslation
   * @see Matrix4.fromTranslationQuaternionRotationScale
   * @see Matrix4.fromTranslationRotationScale
   * @see Matrix4.fromTranslation
   * @see Matrix4.fromScale
   * @see Matrix4.fromUniformScale
   * @see Matrix4.fromRotation
   * @see Matrix4.fromCamera
   * @see Matrix4.computePerspectiveFieldOfView
   * @see Matrix4.computeOrthographicOffCenter
   * @see Matrix4.computePerspectiveOffCenter
   * @see Matrix4.computeInfinitePerspectiveOffCenter
   * @see Matrix4.computeViewportTransformation
   * @see Matrix4.computeView
   * @see Matrix2
   * @see Matrix3
   * @see Packable
   */
  function Matrix4(
    column0Row0,
    column1Row0,
    column2Row0,
    column3Row0,
    column0Row1,
    column1Row1,
    column2Row1,
    column3Row1,
    column0Row2,
    column1Row2,
    column2Row2,
    column3Row2,
    column0Row3,
    column1Row3,
    column2Row3,
    column3Row3
  ) {
    this[0] = defaultValue(column0Row0, 0.0);
    this[1] = defaultValue(column0Row1, 0.0);
    this[2] = defaultValue(column0Row2, 0.0);
    this[3] = defaultValue(column0Row3, 0.0);
    this[4] = defaultValue(column1Row0, 0.0);
    this[5] = defaultValue(column1Row1, 0.0);
    this[6] = defaultValue(column1Row2, 0.0);
    this[7] = defaultValue(column1Row3, 0.0);
    this[8] = defaultValue(column2Row0, 0.0);
    this[9] = defaultValue(column2Row1, 0.0);
    this[10] = defaultValue(column2Row2, 0.0);
    this[11] = defaultValue(column2Row3, 0.0);
    this[12] = defaultValue(column3Row0, 0.0);
    this[13] = defaultValue(column3Row1, 0.0);
    this[14] = defaultValue(column3Row2, 0.0);
    this[15] = defaultValue(column3Row3, 0.0);
  }

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  Matrix4.packedLength = 16;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {Matrix4} 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
   */
  Matrix4.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    array[startingIndex++] = value[0];
    array[startingIndex++] = value[1];
    array[startingIndex++] = value[2];
    array[startingIndex++] = value[3];
    array[startingIndex++] = value[4];
    array[startingIndex++] = value[5];
    array[startingIndex++] = value[6];
    array[startingIndex++] = value[7];
    array[startingIndex++] = value[8];
    array[startingIndex++] = value[9];
    array[startingIndex++] = value[10];
    array[startingIndex++] = value[11];
    array[startingIndex++] = value[12];
    array[startingIndex++] = value[13];
    array[startingIndex++] = value[14];
    array[startingIndex] = value[15];

    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 {Matrix4} [result] The object into which to store the result.
   * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
   */
  Matrix4.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    if (!defined(result)) {
      result = new Matrix4();
    }

    result[0] = array[startingIndex++];
    result[1] = array[startingIndex++];
    result[2] = array[startingIndex++];
    result[3] = array[startingIndex++];
    result[4] = array[startingIndex++];
    result[5] = array[startingIndex++];
    result[6] = array[startingIndex++];
    result[7] = array[startingIndex++];
    result[8] = array[startingIndex++];
    result[9] = array[startingIndex++];
    result[10] = array[startingIndex++];
    result[11] = array[startingIndex++];
    result[12] = array[startingIndex++];
    result[13] = array[startingIndex++];
    result[14] = array[startingIndex++];
    result[15] = array[startingIndex];
    return result;
  };

  /**
   * Flattens an array of Matrix4s into an array of components. The components
   * are stored in column-major order.
   *
   * @param {Matrix4[]} array The array of matrices to pack.
   * @param {Number[]} [result] The array onto which to store the result. If this is a typed array, it must have array.length * 16 components, else a {@link DeveloperError} will be thrown. If it is a regular array, it will be resized to have (array.length * 16) elements.
   * @returns {Number[]} The packed array.
   */
  Matrix4.packArray = function (array, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    const length = array.length;
    const resultLength = length * 16;
    if (!defined(result)) {
      result = new Array(resultLength);
    } else if (!Array.isArray(result) && result.length !== resultLength) {
      //>>includeStart('debug', pragmas.debug);
      throw new DeveloperError(
        "If result is a typed array, it must have exactly array.length * 16 elements"
      );
      //>>includeEnd('debug');
    } else if (result.length !== resultLength) {
      result.length = resultLength;
    }

    for (let i = 0; i < length; ++i) {
      Matrix4.pack(array[i], result, i * 16);
    }
    return result;
  };

  /**
   * Unpacks an array of column-major matrix components into an array of Matrix4s.
   *
   * @param {Number[]} array The array of components to unpack.
   * @param {Matrix4[]} [result] The array onto which to store the result.
   * @returns {Matrix4[]} The unpacked array.
   */
  Matrix4.unpackArray = function (array, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    Check.typeOf.number.greaterThanOrEquals("array.length", array.length, 16);
    if (array.length % 16 !== 0) {
      throw new DeveloperError("array length must be a multiple of 16.");
    }
    //>>includeEnd('debug');

    const length = array.length;
    if (!defined(result)) {
      result = new Array(length / 16);
    } else {
      result.length = length / 16;
    }

    for (let i = 0; i < length; i += 16) {
      const index = i / 16;
      result[index] = Matrix4.unpack(array, i, result[index]);
    }
    return result;
  };

  /**
   * Duplicates a Matrix4 instance.
   *
   * @param {Matrix4} matrix The matrix to duplicate.
   * @param {Matrix4} [result] The object onto which to store the result.
   * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided. (Returns undefined if matrix is undefined)
   */
  Matrix4.clone = function (matrix, result) {
    if (!defined(matrix)) {
      return undefined;
    }
    if (!defined(result)) {
      return new Matrix4(
        matrix[0],
        matrix[4],
        matrix[8],
        matrix[12],
        matrix[1],
        matrix[5],
        matrix[9],
        matrix[13],
        matrix[2],
        matrix[6],
        matrix[10],
        matrix[14],
        matrix[3],
        matrix[7],
        matrix[11],
        matrix[15]
      );
    }
    result[0] = matrix[0];
    result[1] = matrix[1];
    result[2] = matrix[2];
    result[3] = matrix[3];
    result[4] = matrix[4];
    result[5] = matrix[5];
    result[6] = matrix[6];
    result[7] = matrix[7];
    result[8] = matrix[8];
    result[9] = matrix[9];
    result[10] = matrix[10];
    result[11] = matrix[11];
    result[12] = matrix[12];
    result[13] = matrix[13];
    result[14] = matrix[14];
    result[15] = matrix[15];
    return result;
  };

  /**
   * Creates a Matrix4 from 16 consecutive elements in an array.
   * @function
   *
   * @param {Number[]} array The array whose 16 consecutive elements correspond to the positions of the matrix.  Assumes column-major order.
   * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to first column first row position in the matrix.
   * @param {Matrix4} [result] The object onto which to store the result.
   * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
   *
   * @example
   * // Create the Matrix4:
   * // [1.0, 2.0, 3.0, 4.0]
   * // [1.0, 2.0, 3.0, 4.0]
   * // [1.0, 2.0, 3.0, 4.0]
   * // [1.0, 2.0, 3.0, 4.0]
   *
   * const v = [1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0];
   * const m = Cesium.Matrix4.fromArray(v);
   *
   * // Create same Matrix4 with using an offset into an array
   * const v2 = [0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0];
   * const m2 = Cesium.Matrix4.fromArray(v2, 2);
   */
  Matrix4.fromArray = Matrix4.unpack;

  /**
   * Computes a Matrix4 instance from a column-major order array.
   *
   * @param {Number[]} values The column-major order array.
   * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
   * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
   */
  Matrix4.fromColumnMajorArray = function (values, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("values", values);
    //>>includeEnd('debug');

    return Matrix4.clone(values, result);
  };

  /**
   * Computes a Matrix4 instance from a row-major order array.
   * The resulting matrix will be in column-major order.
   *
   * @param {Number[]} values The row-major order array.
   * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
   * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
   */
  Matrix4.fromRowMajorArray = function (values, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("values", values);
    //>>includeEnd('debug');

    if (!defined(result)) {
      return new Matrix4(
        values[0],
        values[1],
        values[2],
        values[3],
        values[4],
        values[5],
        values[6],
        values[7],
        values[8],
        values[9],
        values[10],
        values[11],
        values[12],
        values[13],
        values[14],
        values[15]
      );
    }
    result[0] = values[0];
    result[1] = values[4];
    result[2] = values[8];
    result[3] = values[12];
    result[4] = values[1];
    result[5] = values[5];
    result[6] = values[9];
    result[7] = values[13];
    result[8] = values[2];
    result[9] = values[6];
    result[10] = values[10];
    result[11] = values[14];
    result[12] = values[3];
    result[13] = values[7];
    result[14] = values[11];
    result[15] = values[15];
    return result;
  };

  /**
   * Computes a Matrix4 instance from a Matrix3 representing the rotation
   * and a Cartesian3 representing the translation.
   *
   * @param {Matrix3} rotation The upper left portion of the matrix representing the rotation.
   * @param {Cartesian3} [translation=Cartesian3.ZERO] The upper right portion of the matrix representing the translation.
   * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
   * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
   */
  Matrix4.fromRotationTranslation = function (rotation, translation, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("rotation", rotation);
    //>>includeEnd('debug');

    translation = defaultValue(translation, Cartesian3.ZERO);

    if (!defined(result)) {
      return new Matrix4(
        rotation[0],
        rotation[3],
        rotation[6],
        translation.x,
        rotation[1],
        rotation[4],
        rotation[7],
        translation.y,
        rotation[2],
        rotation[5],
        rotation[8],
        translation.z,
        0.0,
        0.0,
        0.0,
        1.0
      );
    }

    result[0] = rotation[0];
    result[1] = rotation[1];
    result[2] = rotation[2];
    result[3] = 0.0;
    result[4] = rotation[3];
    result[5] = rotation[4];
    result[6] = rotation[5];
    result[7] = 0.0;
    result[8] = rotation[6];
    result[9] = rotation[7];
    result[10] = rotation[8];
    result[11] = 0.0;
    result[12] = translation.x;
    result[13] = translation.y;
    result[14] = translation.z;
    result[15] = 1.0;
    return result;
  };

  /**
   * Computes a Matrix4 instance from a translation, rotation, and scale (TRS)
   * representation with the rotation represented as a quaternion.
   *
   * @param {Cartesian3} translation The translation transformation.
   * @param {Quaternion} rotation The rotation transformation.
   * @param {Cartesian3} scale The non-uniform scale transformation.
   * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
   * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
   *
   * @example
   * const result = Cesium.Matrix4.fromTranslationQuaternionRotationScale(
   *   new Cesium.Cartesian3(1.0, 2.0, 3.0), // translation
   *   Cesium.Quaternion.IDENTITY,           // rotation
   *   new Cesium.Cartesian3(7.0, 8.0, 9.0), // scale
   *   result);
   */
  Matrix4.fromTranslationQuaternionRotationScale = function (
    translation,
    rotation,
    scale,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("translation", translation);
    Check.typeOf.object("rotation", rotation);
    Check.typeOf.object("scale", scale);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Matrix4();
    }

    const scaleX = scale.x;
    const scaleY = scale.y;
    const scaleZ = scale.z;

    const x2 = rotation.x * rotation.x;
    const xy = rotation.x * rotation.y;
    const xz = rotation.x * rotation.z;
    const xw = rotation.x * rotation.w;
    const y2 = rotation.y * rotation.y;
    const yz = rotation.y * rotation.z;
    const yw = rotation.y * rotation.w;
    const z2 = rotation.z * rotation.z;
    const zw = rotation.z * rotation.w;
    const w2 = rotation.w * rotation.w;

    const m00 = x2 - y2 - z2 + w2;
    const m01 = 2.0 * (xy - zw);
    const m02 = 2.0 * (xz + yw);

    const m10 = 2.0 * (xy + zw);
    const m11 = -x2 + y2 - z2 + w2;
    const m12 = 2.0 * (yz - xw);

    const m20 = 2.0 * (xz - yw);
    const m21 = 2.0 * (yz + xw);
    const m22 = -x2 - y2 + z2 + w2;

    result[0] = m00 * scaleX;
    result[1] = m10 * scaleX;
    result[2] = m20 * scaleX;
    result[3] = 0.0;
    result[4] = m01 * scaleY;
    result[5] = m11 * scaleY;
    result[6] = m21 * scaleY;
    result[7] = 0.0;
    result[8] = m02 * scaleZ;
    result[9] = m12 * scaleZ;
    result[10] = m22 * scaleZ;
    result[11] = 0.0;
    result[12] = translation.x;
    result[13] = translation.y;
    result[14] = translation.z;
    result[15] = 1.0;

    return result;
  };

  /**
   * Creates a Matrix4 instance from a {@link TranslationRotationScale} instance.
   *
   * @param {TranslationRotationScale} translationRotationScale The instance.
   * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
   * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
   */
  Matrix4.fromTranslationRotationScale = function (
    translationRotationScale,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("translationRotationScale", translationRotationScale);
    //>>includeEnd('debug');

    return Matrix4.fromTranslationQuaternionRotationScale(
      translationRotationScale.translation,
      translationRotationScale.rotation,
      translationRotationScale.scale,
      result
    );
  };

  /**
   * Creates a Matrix4 instance from a Cartesian3 representing the translation.
   *
   * @param {Cartesian3} translation The upper right portion of the matrix representing the translation.
   * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
   * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
   *
   * @see Matrix4.multiplyByTranslation
   */
  Matrix4.fromTranslation = function (translation, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("translation", translation);
    //>>includeEnd('debug');

    return Matrix4.fromRotationTranslation(Matrix3.IDENTITY, translation, result);
  };

  /**
   * Computes a Matrix4 instance representing a non-uniform scale.
   *
   * @param {Cartesian3} scale The x, y, and z scale factors.
   * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
   * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
   *
   * @example
   * // Creates
   * //   [7.0, 0.0, 0.0, 0.0]
   * //   [0.0, 8.0, 0.0, 0.0]
   * //   [0.0, 0.0, 9.0, 0.0]
   * //   [0.0, 0.0, 0.0, 1.0]
   * const m = Cesium.Matrix4.fromScale(new Cesium.Cartesian3(7.0, 8.0, 9.0));
   */
  Matrix4.fromScale = function (scale, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("scale", scale);
    //>>includeEnd('debug');

    if (!defined(result)) {
      return new Matrix4(
        scale.x,
        0.0,
        0.0,
        0.0,
        0.0,
        scale.y,
        0.0,
        0.0,
        0.0,
        0.0,
        scale.z,
        0.0,
        0.0,
        0.0,
        0.0,
        1.0
      );
    }

    result[0] = scale.x;
    result[1] = 0.0;
    result[2] = 0.0;
    result[3] = 0.0;
    result[4] = 0.0;
    result[5] = scale.y;
    result[6] = 0.0;
    result[7] = 0.0;
    result[8] = 0.0;
    result[9] = 0.0;
    result[10] = scale.z;
    result[11] = 0.0;
    result[12] = 0.0;
    result[13] = 0.0;
    result[14] = 0.0;
    result[15] = 1.0;
    return result;
  };

  /**
   * Computes a Matrix4 instance representing a uniform scale.
   *
   * @param {Number} scale The uniform scale factor.
   * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
   * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
   *
   * @example
   * // Creates
   * //   [2.0, 0.0, 0.0, 0.0]
   * //   [0.0, 2.0, 0.0, 0.0]
   * //   [0.0, 0.0, 2.0, 0.0]
   * //   [0.0, 0.0, 0.0, 1.0]
   * const m = Cesium.Matrix4.fromUniformScale(2.0);
   */
  Matrix4.fromUniformScale = function (scale, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("scale", scale);
    //>>includeEnd('debug');

    if (!defined(result)) {
      return new Matrix4(
        scale,
        0.0,
        0.0,
        0.0,
        0.0,
        scale,
        0.0,
        0.0,
        0.0,
        0.0,
        scale,
        0.0,
        0.0,
        0.0,
        0.0,
        1.0
      );
    }

    result[0] = scale;
    result[1] = 0.0;
    result[2] = 0.0;
    result[3] = 0.0;
    result[4] = 0.0;
    result[5] = scale;
    result[6] = 0.0;
    result[7] = 0.0;
    result[8] = 0.0;
    result[9] = 0.0;
    result[10] = scale;
    result[11] = 0.0;
    result[12] = 0.0;
    result[13] = 0.0;
    result[14] = 0.0;
    result[15] = 1.0;
    return result;
  };

  /**
   * Creates a rotation matrix.
   *
   * @param {Matrix3} rotation The rotation matrix.
   * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
   * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
   */
  Matrix4.fromRotation = function (rotation, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("rotation", rotation);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Matrix4();
    }
    result[0] = rotation[0];
    result[1] = rotation[1];
    result[2] = rotation[2];
    result[3] = 0.0;

    result[4] = rotation[3];
    result[5] = rotation[4];
    result[6] = rotation[5];
    result[7] = 0.0;

    result[8] = rotation[6];
    result[9] = rotation[7];
    result[10] = rotation[8];
    result[11] = 0.0;

    result[12] = 0.0;
    result[13] = 0.0;
    result[14] = 0.0;
    result[15] = 1.0;

    return result;
  };

  const fromCameraF = new Cartesian3();
  const fromCameraR = new Cartesian3();
  const fromCameraU = new Cartesian3();

  /**
   * Computes a Matrix4 instance from a Camera.
   *
   * @param {Camera} camera The camera to use.
   * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
   * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
   */
  Matrix4.fromCamera = function (camera, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("camera", camera);
    //>>includeEnd('debug');

    const position = camera.position;
    const direction = camera.direction;
    const up = camera.up;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("camera.position", position);
    Check.typeOf.object("camera.direction", direction);
    Check.typeOf.object("camera.up", up);
    //>>includeEnd('debug');

    Cartesian3.normalize(direction, fromCameraF);
    Cartesian3.normalize(
      Cartesian3.cross(fromCameraF, up, fromCameraR),
      fromCameraR
    );
    Cartesian3.normalize(
      Cartesian3.cross(fromCameraR, fromCameraF, fromCameraU),
      fromCameraU
    );

    const sX = fromCameraR.x;
    const sY = fromCameraR.y;
    const sZ = fromCameraR.z;
    const fX = fromCameraF.x;
    const fY = fromCameraF.y;
    const fZ = fromCameraF.z;
    const uX = fromCameraU.x;
    const uY = fromCameraU.y;
    const uZ = fromCameraU.z;
    const positionX = position.x;
    const positionY = position.y;
    const positionZ = position.z;
    const t0 = sX * -positionX + sY * -positionY + sZ * -positionZ;
    const t1 = uX * -positionX + uY * -positionY + uZ * -positionZ;
    const t2 = fX * positionX + fY * positionY + fZ * positionZ;

    // The code below this comment is an optimized
    // version of the commented lines.
    // Rather that create two matrices and then multiply,
    // we just bake in the multiplcation as part of creation.
    // const rotation = new Matrix4(
    //                 sX,  sY,  sZ, 0.0,
    //                 uX,  uY,  uZ, 0.0,
    //                -fX, -fY, -fZ, 0.0,
    //                 0.0,  0.0,  0.0, 1.0);
    // const translation = new Matrix4(
    //                 1.0, 0.0, 0.0, -position.x,
    //                 0.0, 1.0, 0.0, -position.y,
    //                 0.0, 0.0, 1.0, -position.z,
    //                 0.0, 0.0, 0.0, 1.0);
    // return rotation.multiply(translation);
    if (!defined(result)) {
      return new Matrix4(
        sX,
        sY,
        sZ,
        t0,
        uX,
        uY,
        uZ,
        t1,
        -fX,
        -fY,
        -fZ,
        t2,
        0.0,
        0.0,
        0.0,
        1.0
      );
    }
    result[0] = sX;
    result[1] = uX;
    result[2] = -fX;
    result[3] = 0.0;
    result[4] = sY;
    result[5] = uY;
    result[6] = -fY;
    result[7] = 0.0;
    result[8] = sZ;
    result[9] = uZ;
    result[10] = -fZ;
    result[11] = 0.0;
    result[12] = t0;
    result[13] = t1;
    result[14] = t2;
    result[15] = 1.0;
    return result;
  };

  /**
   * Computes a Matrix4 instance representing a perspective transformation matrix.
   *
   * @param {Number} fovY The field of view along the Y axis in radians.
   * @param {Number} aspectRatio The aspect ratio.
   * @param {Number} near The distance to the near plane in meters.
   * @param {Number} far The distance to the far plane in meters.
   * @param {Matrix4} result The object in which the result will be stored.
   * @returns {Matrix4} The modified result parameter.
   *
   * @exception {DeveloperError} fovY must be in (0, PI].
   * @exception {DeveloperError} aspectRatio must be greater than zero.
   * @exception {DeveloperError} near must be greater than zero.
   * @exception {DeveloperError} far must be greater than zero.
   */
  Matrix4.computePerspectiveFieldOfView = function (
    fovY,
    aspectRatio,
    near,
    far,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number.greaterThan("fovY", fovY, 0.0);
    Check.typeOf.number.lessThan("fovY", fovY, Math.PI);
    Check.typeOf.number.greaterThan("near", near, 0.0);
    Check.typeOf.number.greaterThan("far", far, 0.0);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const bottom = Math.tan(fovY * 0.5);

    const column1Row1 = 1.0 / bottom;
    const column0Row0 = column1Row1 / aspectRatio;
    const column2Row2 = (far + near) / (near - far);
    const column3Row2 = (2.0 * far * near) / (near - far);

    result[0] = column0Row0;
    result[1] = 0.0;
    result[2] = 0.0;
    result[3] = 0.0;
    result[4] = 0.0;
    result[5] = column1Row1;
    result[6] = 0.0;
    result[7] = 0.0;
    result[8] = 0.0;
    result[9] = 0.0;
    result[10] = column2Row2;
    result[11] = -1.0;
    result[12] = 0.0;
    result[13] = 0.0;
    result[14] = column3Row2;
    result[15] = 0.0;
    return result;
  };

  /**
   * Computes a Matrix4 instance representing an orthographic transformation matrix.
   *
   * @param {Number} left The number of meters to the left of the camera that will be in view.
   * @param {Number} right The number of meters to the right of the camera that will be in view.
   * @param {Number} bottom The number of meters below of the camera that will be in view.
   * @param {Number} top The number of meters above of the camera that will be in view.
   * @param {Number} near The distance to the near plane in meters.
   * @param {Number} far The distance to the far plane in meters.
   * @param {Matrix4} result The object in which the result will be stored.
   * @returns {Matrix4} The modified result parameter.
   */
  Matrix4.computeOrthographicOffCenter = function (
    left,
    right,
    bottom,
    top,
    near,
    far,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("left", left);
    Check.typeOf.number("right", right);
    Check.typeOf.number("bottom", bottom);
    Check.typeOf.number("top", top);
    Check.typeOf.number("near", near);
    Check.typeOf.number("far", far);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    let a = 1.0 / (right - left);
    let b = 1.0 / (top - bottom);
    let c = 1.0 / (far - near);

    const tx = -(right + left) * a;
    const ty = -(top + bottom) * b;
    const tz = -(far + near) * c;
    a *= 2.0;
    b *= 2.0;
    c *= -2.0;

    result[0] = a;
    result[1] = 0.0;
    result[2] = 0.0;
    result[3] = 0.0;
    result[4] = 0.0;
    result[5] = b;
    result[6] = 0.0;
    result[7] = 0.0;
    result[8] = 0.0;
    result[9] = 0.0;
    result[10] = c;
    result[11] = 0.0;
    result[12] = tx;
    result[13] = ty;
    result[14] = tz;
    result[15] = 1.0;
    return result;
  };

  /**
   * Computes a Matrix4 instance representing an off center perspective transformation.
   *
   * @param {Number} left The number of meters to the left of the camera that will be in view.
   * @param {Number} right The number of meters to the right of the camera that will be in view.
   * @param {Number} bottom The number of meters below of the camera that will be in view.
   * @param {Number} top The number of meters above of the camera that will be in view.
   * @param {Number} near The distance to the near plane in meters.
   * @param {Number} far The distance to the far plane in meters.
   * @param {Matrix4} result The object in which the result will be stored.
   * @returns {Matrix4} The modified result parameter.
   */
  Matrix4.computePerspectiveOffCenter = function (
    left,
    right,
    bottom,
    top,
    near,
    far,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("left", left);
    Check.typeOf.number("right", right);
    Check.typeOf.number("bottom", bottom);
    Check.typeOf.number("top", top);
    Check.typeOf.number("near", near);
    Check.typeOf.number("far", far);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const column0Row0 = (2.0 * near) / (right - left);
    const column1Row1 = (2.0 * near) / (top - bottom);
    const column2Row0 = (right + left) / (right - left);
    const column2Row1 = (top + bottom) / (top - bottom);
    const column2Row2 = -(far + near) / (far - near);
    const column2Row3 = -1.0;
    const column3Row2 = (-2.0 * far * near) / (far - near);

    result[0] = column0Row0;
    result[1] = 0.0;
    result[2] = 0.0;
    result[3] = 0.0;
    result[4] = 0.0;
    result[5] = column1Row1;
    result[6] = 0.0;
    result[7] = 0.0;
    result[8] = column2Row0;
    result[9] = column2Row1;
    result[10] = column2Row2;
    result[11] = column2Row3;
    result[12] = 0.0;
    result[13] = 0.0;
    result[14] = column3Row2;
    result[15] = 0.0;
    return result;
  };

  /**
   * Computes a Matrix4 instance representing an infinite off center perspective transformation.
   *
   * @param {Number} left The number of meters to the left of the camera that will be in view.
   * @param {Number} right The number of meters to the right of the camera that will be in view.
   * @param {Number} bottom The number of meters below of the camera that will be in view.
   * @param {Number} top The number of meters above of the camera that will be in view.
   * @param {Number} near The distance to the near plane in meters.
   * @param {Matrix4} result The object in which the result will be stored.
   * @returns {Matrix4} The modified result parameter.
   */
  Matrix4.computeInfinitePerspectiveOffCenter = function (
    left,
    right,
    bottom,
    top,
    near,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("left", left);
    Check.typeOf.number("right", right);
    Check.typeOf.number("bottom", bottom);
    Check.typeOf.number("top", top);
    Check.typeOf.number("near", near);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const column0Row0 = (2.0 * near) / (right - left);
    const column1Row1 = (2.0 * near) / (top - bottom);
    const column2Row0 = (right + left) / (right - left);
    const column2Row1 = (top + bottom) / (top - bottom);
    const column2Row2 = -1.0;
    const column2Row3 = -1.0;
    const column3Row2 = -2.0 * near;

    result[0] = column0Row0;
    result[1] = 0.0;
    result[2] = 0.0;
    result[3] = 0.0;
    result[4] = 0.0;
    result[5] = column1Row1;
    result[6] = 0.0;
    result[7] = 0.0;
    result[8] = column2Row0;
    result[9] = column2Row1;
    result[10] = column2Row2;
    result[11] = column2Row3;
    result[12] = 0.0;
    result[13] = 0.0;
    result[14] = column3Row2;
    result[15] = 0.0;
    return result;
  };

  /**
   * Computes a Matrix4 instance that transforms from normalized device coordinates to window coordinates.
   *
   * @param {Object} [viewport = { x : 0.0, y : 0.0, width : 0.0, height : 0.0 }] The viewport's corners as shown in Example 1.
   * @param {Number} [nearDepthRange=0.0] The near plane distance in window coordinates.
   * @param {Number} [farDepthRange=1.0] The far plane distance in window coordinates.
   * @param {Matrix4} [result] The object in which the result will be stored.
   * @returns {Matrix4} The modified result parameter.
   *
   * @example
   * // Create viewport transformation using an explicit viewport and depth range.
   * const m = Cesium.Matrix4.computeViewportTransformation({
   *     x : 0.0,
   *     y : 0.0,
   *     width : 1024.0,
   *     height : 768.0
   * }, 0.0, 1.0, new Cesium.Matrix4());
   */
  Matrix4.computeViewportTransformation = function (
    viewport,
    nearDepthRange,
    farDepthRange,
    result
  ) {
    if (!defined(result)) {
      result = new Matrix4();
    }

    viewport = defaultValue(viewport, defaultValue.EMPTY_OBJECT);
    const x = defaultValue(viewport.x, 0.0);
    const y = defaultValue(viewport.y, 0.0);
    const width = defaultValue(viewport.width, 0.0);
    const height = defaultValue(viewport.height, 0.0);
    nearDepthRange = defaultValue(nearDepthRange, 0.0);
    farDepthRange = defaultValue(farDepthRange, 1.0);

    const halfWidth = width * 0.5;
    const halfHeight = height * 0.5;
    const halfDepth = (farDepthRange - nearDepthRange) * 0.5;

    const column0Row0 = halfWidth;
    const column1Row1 = halfHeight;
    const column2Row2 = halfDepth;
    const column3Row0 = x + halfWidth;
    const column3Row1 = y + halfHeight;
    const column3Row2 = nearDepthRange + halfDepth;
    const column3Row3 = 1.0;

    result[0] = column0Row0;
    result[1] = 0.0;
    result[2] = 0.0;
    result[3] = 0.0;
    result[4] = 0.0;
    result[5] = column1Row1;
    result[6] = 0.0;
    result[7] = 0.0;
    result[8] = 0.0;
    result[9] = 0.0;
    result[10] = column2Row2;
    result[11] = 0.0;
    result[12] = column3Row0;
    result[13] = column3Row1;
    result[14] = column3Row2;
    result[15] = column3Row3;

    return result;
  };

  /**
   * Computes a Matrix4 instance that transforms from world space to view space.
   *
   * @param {Cartesian3} position The position of the camera.
   * @param {Cartesian3} direction The forward direction.
   * @param {Cartesian3} up The up direction.
   * @param {Cartesian3} right The right direction.
   * @param {Matrix4} result The object in which the result will be stored.
   * @returns {Matrix4} The modified result parameter.
   */
  Matrix4.computeView = function (position, direction, up, right, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("position", position);
    Check.typeOf.object("direction", direction);
    Check.typeOf.object("up", up);
    Check.typeOf.object("right", right);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result[0] = right.x;
    result[1] = up.x;
    result[2] = -direction.x;
    result[3] = 0.0;
    result[4] = right.y;
    result[5] = up.y;
    result[6] = -direction.y;
    result[7] = 0.0;
    result[8] = right.z;
    result[9] = up.z;
    result[10] = -direction.z;
    result[11] = 0.0;
    result[12] = -Cartesian3.dot(right, position);
    result[13] = -Cartesian3.dot(up, position);
    result[14] = Cartesian3.dot(direction, position);
    result[15] = 1.0;
    return result;
  };

  /**
   * Computes an Array from the provided Matrix4 instance.
   * The array will be in column-major order.
   *
   * @param {Matrix4} matrix The matrix to use..
   * @param {Number[]} [result] The Array onto which to store the result.
   * @returns {Number[]} The modified Array parameter or a new Array instance if one was not provided.
   *
   * @example
   * //create an array from an instance of Matrix4
   * // m = [10.0, 14.0, 18.0, 22.0]
   * //     [11.0, 15.0, 19.0, 23.0]
   * //     [12.0, 16.0, 20.0, 24.0]
   * //     [13.0, 17.0, 21.0, 25.0]
   * const a = Cesium.Matrix4.toArray(m);
   *
   * // m remains the same
   * //creates a = [10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0]
   */
  Matrix4.toArray = function (matrix, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    //>>includeEnd('debug');

    if (!defined(result)) {
      return [
        matrix[0],
        matrix[1],
        matrix[2],
        matrix[3],
        matrix[4],
        matrix[5],
        matrix[6],
        matrix[7],
        matrix[8],
        matrix[9],
        matrix[10],
        matrix[11],
        matrix[12],
        matrix[13],
        matrix[14],
        matrix[15],
      ];
    }
    result[0] = matrix[0];
    result[1] = matrix[1];
    result[2] = matrix[2];
    result[3] = matrix[3];
    result[4] = matrix[4];
    result[5] = matrix[5];
    result[6] = matrix[6];
    result[7] = matrix[7];
    result[8] = matrix[8];
    result[9] = matrix[9];
    result[10] = matrix[10];
    result[11] = matrix[11];
    result[12] = matrix[12];
    result[13] = matrix[13];
    result[14] = matrix[14];
    result[15] = matrix[15];
    return result;
  };

  /**
   * Computes the array index of the element at the provided row and column.
   *
   * @param {Number} row The zero-based index of the row.
   * @param {Number} column The zero-based index of the column.
   * @returns {Number} The index of the element at the provided row and column.
   *
   * @exception {DeveloperError} row must be 0, 1, 2, or 3.
   * @exception {DeveloperError} column must be 0, 1, 2, or 3.
   *
   * @example
   * const myMatrix = new Cesium.Matrix4();
   * const column1Row0Index = Cesium.Matrix4.getElementIndex(1, 0);
   * const column1Row0 = myMatrix[column1Row0Index];
   * myMatrix[column1Row0Index] = 10.0;
   */
  Matrix4.getElementIndex = function (column, row) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number.greaterThanOrEquals("row", row, 0);
    Check.typeOf.number.lessThanOrEquals("row", row, 3);

    Check.typeOf.number.greaterThanOrEquals("column", column, 0);
    Check.typeOf.number.lessThanOrEquals("column", column, 3);
    //>>includeEnd('debug');

    return column * 4 + row;
  };

  /**
   * Retrieves a copy of the matrix column at the provided index as a Cartesian4 instance.
   *
   * @param {Matrix4} matrix The matrix to use.
   * @param {Number} index The zero-based index of the column to retrieve.
   * @param {Cartesian4} result The object onto which to store the result.
   * @returns {Cartesian4} The modified result parameter.
   *
   * @exception {DeveloperError} index must be 0, 1, 2, or 3.
   *
   * @example
   * //returns a Cartesian4 instance with values from the specified column
   * // m = [10.0, 11.0, 12.0, 13.0]
   * //     [14.0, 15.0, 16.0, 17.0]
   * //     [18.0, 19.0, 20.0, 21.0]
   * //     [22.0, 23.0, 24.0, 25.0]
   *
   * //Example 1: Creates an instance of Cartesian
   * const a = Cesium.Matrix4.getColumn(m, 2, new Cesium.Cartesian4());
   *
   * @example
   * //Example 2: Sets values for Cartesian instance
   * const a = new Cesium.Cartesian4();
   * Cesium.Matrix4.getColumn(m, 2, a);
   *
   * // a.x = 12.0; a.y = 16.0; a.z = 20.0; a.w = 24.0;
   */
  Matrix4.getColumn = function (matrix, index, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);

    Check.typeOf.number.greaterThanOrEquals("index", index, 0);
    Check.typeOf.number.lessThanOrEquals("index", index, 3);

    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const startIndex = index * 4;
    const x = matrix[startIndex];
    const y = matrix[startIndex + 1];
    const z = matrix[startIndex + 2];
    const w = matrix[startIndex + 3];

    result.x = x;
    result.y = y;
    result.z = z;
    result.w = w;
    return result;
  };

  /**
   * Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian4 instance.
   *
   * @param {Matrix4} matrix The matrix to use.
   * @param {Number} index The zero-based index of the column to set.
   * @param {Cartesian4} cartesian The Cartesian whose values will be assigned to the specified column.
   * @param {Matrix4} result The object onto which to store the result.
   * @returns {Matrix4} The modified result parameter.
   *
   * @exception {DeveloperError} index must be 0, 1, 2, or 3.
   *
   * @example
   * //creates a new Matrix4 instance with new column values from the Cartesian4 instance
   * // m = [10.0, 11.0, 12.0, 13.0]
   * //     [14.0, 15.0, 16.0, 17.0]
   * //     [18.0, 19.0, 20.0, 21.0]
   * //     [22.0, 23.0, 24.0, 25.0]
   *
   * const a = Cesium.Matrix4.setColumn(m, 2, new Cesium.Cartesian4(99.0, 98.0, 97.0, 96.0), new Cesium.Matrix4());
   *
   * // m remains the same
   * // a = [10.0, 11.0, 99.0, 13.0]
   * //     [14.0, 15.0, 98.0, 17.0]
   * //     [18.0, 19.0, 97.0, 21.0]
   * //     [22.0, 23.0, 96.0, 25.0]
   */
  Matrix4.setColumn = function (matrix, index, cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);

    Check.typeOf.number.greaterThanOrEquals("index", index, 0);
    Check.typeOf.number.lessThanOrEquals("index", index, 3);

    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result = Matrix4.clone(matrix, result);
    const startIndex = index * 4;
    result[startIndex] = cartesian.x;
    result[startIndex + 1] = cartesian.y;
    result[startIndex + 2] = cartesian.z;
    result[startIndex + 3] = cartesian.w;
    return result;
  };

  /**
   * Retrieves a copy of the matrix row at the provided index as a Cartesian4 instance.
   *
   * @param {Matrix4} matrix The matrix to use.
   * @param {Number} index The zero-based index of the row to retrieve.
   * @param {Cartesian4} result The object onto which to store the result.
   * @returns {Cartesian4} The modified result parameter.
   *
   * @exception {DeveloperError} index must be 0, 1, 2, or 3.
   *
   * @example
   * //returns a Cartesian4 instance with values from the specified column
   * // m = [10.0, 11.0, 12.0, 13.0]
   * //     [14.0, 15.0, 16.0, 17.0]
   * //     [18.0, 19.0, 20.0, 21.0]
   * //     [22.0, 23.0, 24.0, 25.0]
   *
   * //Example 1: Returns an instance of Cartesian
   * const a = Cesium.Matrix4.getRow(m, 2, new Cesium.Cartesian4());
   *
   * @example
   * //Example 2: Sets values for a Cartesian instance
   * const a = new Cesium.Cartesian4();
   * Cesium.Matrix4.getRow(m, 2, a);
   *
   * // a.x = 18.0; a.y = 19.0; a.z = 20.0; a.w = 21.0;
   */
  Matrix4.getRow = function (matrix, index, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);

    Check.typeOf.number.greaterThanOrEquals("index", index, 0);
    Check.typeOf.number.lessThanOrEquals("index", index, 3);

    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const x = matrix[index];
    const y = matrix[index + 4];
    const z = matrix[index + 8];
    const w = matrix[index + 12];

    result.x = x;
    result.y = y;
    result.z = z;
    result.w = w;
    return result;
  };

  /**
   * Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian4 instance.
   *
   * @param {Matrix4} matrix The matrix to use.
   * @param {Number} index The zero-based index of the row to set.
   * @param {Cartesian4} cartesian The Cartesian whose values will be assigned to the specified row.
   * @param {Matrix4} result The object onto which to store the result.
   * @returns {Matrix4} The modified result parameter.
   *
   * @exception {DeveloperError} index must be 0, 1, 2, or 3.
   *
   * @example
   * //create a new Matrix4 instance with new row values from the Cartesian4 instance
   * // m = [10.0, 11.0, 12.0, 13.0]
   * //     [14.0, 15.0, 16.0, 17.0]
   * //     [18.0, 19.0, 20.0, 21.0]
   * //     [22.0, 23.0, 24.0, 25.0]
   *
   * const a = Cesium.Matrix4.setRow(m, 2, new Cesium.Cartesian4(99.0, 98.0, 97.0, 96.0), new Cesium.Matrix4());
   *
   * // m remains the same
   * // a = [10.0, 11.0, 12.0, 13.0]
   * //     [14.0, 15.0, 16.0, 17.0]
   * //     [99.0, 98.0, 97.0, 96.0]
   * //     [22.0, 23.0, 24.0, 25.0]
   */
  Matrix4.setRow = function (matrix, index, cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);

    Check.typeOf.number.greaterThanOrEquals("index", index, 0);
    Check.typeOf.number.lessThanOrEquals("index", index, 3);

    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result = Matrix4.clone(matrix, result);
    result[index] = cartesian.x;
    result[index + 4] = cartesian.y;
    result[index + 8] = cartesian.z;
    result[index + 12] = cartesian.w;
    return result;
  };

  /**
   * Computes a new matrix that replaces the translation in the rightmost column of the provided
   * matrix with the provided translation. This assumes the matrix is an affine transformation.
   *
   * @param {Matrix4} matrix The matrix to use.
   * @param {Cartesian3} translation The translation that replaces the translation of the provided matrix.
   * @param {Matrix4} result The object onto which to store the result.
   * @returns {Matrix4} The modified result parameter.
   */
  Matrix4.setTranslation = function (matrix, translation, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("translation", translation);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result[0] = matrix[0];
    result[1] = matrix[1];
    result[2] = matrix[2];
    result[3] = matrix[3];

    result[4] = matrix[4];
    result[5] = matrix[5];
    result[6] = matrix[6];
    result[7] = matrix[7];

    result[8] = matrix[8];
    result[9] = matrix[9];
    result[10] = matrix[10];
    result[11] = matrix[11];

    result[12] = translation.x;
    result[13] = translation.y;
    result[14] = translation.z;
    result[15] = matrix[15];

    return result;
  };

  const scaleScratch1$1 = new Cartesian3();

  /**
   * Computes a new matrix that replaces the scale with the provided scale.
   * This assumes the matrix is an affine transformation.
   *
   * @param {Matrix4} matrix The matrix to use.
   * @param {Cartesian3} scale The scale that replaces the scale of the provided matrix.
   * @param {Matrix4} result The object onto which to store the result.
   * @returns {Matrix4} The modified result parameter.
   *
   * @see Matrix4.setUniformScale
   * @see Matrix4.fromScale
   * @see Matrix4.fromUniformScale
   * @see Matrix4.multiplyByScale
   * @see Matrix4.multiplyByUniformScale
   * @see Matrix4.getScale
   */
  Matrix4.setScale = function (matrix, scale, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("scale", scale);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const existingScale = Matrix4.getScale(matrix, scaleScratch1$1);
    const scaleRatioX = scale.x / existingScale.x;
    const scaleRatioY = scale.y / existingScale.y;
    const scaleRatioZ = scale.z / existingScale.z;

    result[0] = matrix[0] * scaleRatioX;
    result[1] = matrix[1] * scaleRatioX;
    result[2] = matrix[2] * scaleRatioX;
    result[3] = matrix[3];

    result[4] = matrix[4] * scaleRatioY;
    result[5] = matrix[5] * scaleRatioY;
    result[6] = matrix[6] * scaleRatioY;
    result[7] = matrix[7];

    result[8] = matrix[8] * scaleRatioZ;
    result[9] = matrix[9] * scaleRatioZ;
    result[10] = matrix[10] * scaleRatioZ;
    result[11] = matrix[11];

    result[12] = matrix[12];
    result[13] = matrix[13];
    result[14] = matrix[14];
    result[15] = matrix[15];

    return result;
  };

  const scaleScratch2$1 = new Cartesian3();

  /**
   * Computes a new matrix that replaces the scale with the provided uniform scale.
   * This assumes the matrix is an affine transformation.
   *
   * @param {Matrix4} matrix The matrix to use.
   * @param {Number} scale The uniform scale that replaces the scale of the provided matrix.
   * @param {Matrix4} result The object onto which to store the result.
   * @returns {Matrix4} The modified result parameter.
   *
   * @see Matrix4.setScale
   * @see Matrix4.fromScale
   * @see Matrix4.fromUniformScale
   * @see Matrix4.multiplyByScale
   * @see Matrix4.multiplyByUniformScale
   * @see Matrix4.getScale
   */
  Matrix4.setUniformScale = function (matrix, scale, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.number("scale", scale);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const existingScale = Matrix4.getScale(matrix, scaleScratch2$1);
    const scaleRatioX = scale / existingScale.x;
    const scaleRatioY = scale / existingScale.y;
    const scaleRatioZ = scale / existingScale.z;

    result[0] = matrix[0] * scaleRatioX;
    result[1] = matrix[1] * scaleRatioX;
    result[2] = matrix[2] * scaleRatioX;
    result[3] = matrix[3];

    result[4] = matrix[4] * scaleRatioY;
    result[5] = matrix[5] * scaleRatioY;
    result[6] = matrix[6] * scaleRatioY;
    result[7] = matrix[7];

    result[8] = matrix[8] * scaleRatioZ;
    result[9] = matrix[9] * scaleRatioZ;
    result[10] = matrix[10] * scaleRatioZ;
    result[11] = matrix[11];

    result[12] = matrix[12];
    result[13] = matrix[13];
    result[14] = matrix[14];
    result[15] = matrix[15];

    return result;
  };

  const scratchColumn$1 = new Cartesian3();

  /**
   * Extracts the non-uniform scale assuming the matrix is an affine transformation.
   *
   * @param {Matrix4} matrix The matrix.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter
   *
   * @see Matrix4.multiplyByScale
   * @see Matrix4.multiplyByUniformScale
   * @see Matrix4.fromScale
   * @see Matrix4.fromUniformScale
   * @see Matrix4.setScale
   * @see Matrix4.setUniformScale
   */
  Matrix4.getScale = function (matrix, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.x = Cartesian3.magnitude(
      Cartesian3.fromElements(matrix[0], matrix[1], matrix[2], scratchColumn$1)
    );
    result.y = Cartesian3.magnitude(
      Cartesian3.fromElements(matrix[4], matrix[5], matrix[6], scratchColumn$1)
    );
    result.z = Cartesian3.magnitude(
      Cartesian3.fromElements(matrix[8], matrix[9], matrix[10], scratchColumn$1)
    );
    return result;
  };

  const scaleScratch3$1 = new Cartesian3();

  /**
   * Computes the maximum scale assuming the matrix is an affine transformation.
   * The maximum scale is the maximum length of the column vectors in the upper-left
   * 3x3 matrix.
   *
   * @param {Matrix4} matrix The matrix.
   * @returns {Number} The maximum scale.
   */
  Matrix4.getMaximumScale = function (matrix) {
    Matrix4.getScale(matrix, scaleScratch3$1);
    return Cartesian3.maximumComponent(scaleScratch3$1);
  };

  const scaleScratch4$1 = new Cartesian3();

  /**
   * Sets the rotation assuming the matrix is an affine transformation.
   *
   * @param {Matrix4} matrix The matrix.
   * @param {Matrix4} rotation The rotation matrix.
   * @returns {Matrix4} The modified result parameter.
   *
   * @see Matrix4.fromRotation
   * @see Matrix4.getRotation
   */
  Matrix4.setRotation = function (matrix, rotation, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const scale = Matrix4.getScale(matrix, scaleScratch4$1);

    result[0] = rotation[0] * scale.x;
    result[1] = rotation[1] * scale.x;
    result[2] = rotation[2] * scale.x;
    result[3] = matrix[3];

    result[4] = rotation[3] * scale.y;
    result[5] = rotation[4] * scale.y;
    result[6] = rotation[5] * scale.y;
    result[7] = matrix[7];

    result[8] = rotation[6] * scale.z;
    result[9] = rotation[7] * scale.z;
    result[10] = rotation[8] * scale.z;
    result[11] = matrix[11];

    result[12] = matrix[12];
    result[13] = matrix[13];
    result[14] = matrix[14];
    result[15] = matrix[15];

    return result;
  };

  const scaleScratch5$1 = new Cartesian3();

  /**
   * Extracts the rotation matrix assuming the matrix is an affine transformation.
   *
   * @param {Matrix4} matrix The matrix.
   * @param {Matrix4} result The object onto which to store the result.
   * @returns {Matrix4} The modified result parameter.
   *
   * @see Matrix4.setRotation
   * @see Matrix4.fromRotation
   */
  Matrix4.getRotation = function (matrix, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const scale = Matrix4.getScale(matrix, scaleScratch5$1);

    result[0] = matrix[0] / scale.x;
    result[1] = matrix[1] / scale.x;
    result[2] = matrix[2] / scale.x;

    result[3] = matrix[4] / scale.y;
    result[4] = matrix[5] / scale.y;
    result[5] = matrix[6] / scale.y;

    result[6] = matrix[8] / scale.z;
    result[7] = matrix[9] / scale.z;
    result[8] = matrix[10] / scale.z;

    return result;
  };

  /**
   * Computes the product of two matrices.
   *
   * @param {Matrix4} left The first matrix.
   * @param {Matrix4} right The second matrix.
   * @param {Matrix4} result The object onto which to store the result.
   * @returns {Matrix4} The modified result parameter.
   */
  Matrix4.multiply = function (left, right, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const left0 = left[0];
    const left1 = left[1];
    const left2 = left[2];
    const left3 = left[3];
    const left4 = left[4];
    const left5 = left[5];
    const left6 = left[6];
    const left7 = left[7];
    const left8 = left[8];
    const left9 = left[9];
    const left10 = left[10];
    const left11 = left[11];
    const left12 = left[12];
    const left13 = left[13];
    const left14 = left[14];
    const left15 = left[15];

    const right0 = right[0];
    const right1 = right[1];
    const right2 = right[2];
    const right3 = right[3];
    const right4 = right[4];
    const right5 = right[5];
    const right6 = right[6];
    const right7 = right[7];
    const right8 = right[8];
    const right9 = right[9];
    const right10 = right[10];
    const right11 = right[11];
    const right12 = right[12];
    const right13 = right[13];
    const right14 = right[14];
    const right15 = right[15];

    const column0Row0 =
      left0 * right0 + left4 * right1 + left8 * right2 + left12 * right3;
    const column0Row1 =
      left1 * right0 + left5 * right1 + left9 * right2 + left13 * right3;
    const column0Row2 =
      left2 * right0 + left6 * right1 + left10 * right2 + left14 * right3;
    const column0Row3 =
      left3 * right0 + left7 * right1 + left11 * right2 + left15 * right3;

    const column1Row0 =
      left0 * right4 + left4 * right5 + left8 * right6 + left12 * right7;
    const column1Row1 =
      left1 * right4 + left5 * right5 + left9 * right6 + left13 * right7;
    const column1Row2 =
      left2 * right4 + left6 * right5 + left10 * right6 + left14 * right7;
    const column1Row3 =
      left3 * right4 + left7 * right5 + left11 * right6 + left15 * right7;

    const column2Row0 =
      left0 * right8 + left4 * right9 + left8 * right10 + left12 * right11;
    const column2Row1 =
      left1 * right8 + left5 * right9 + left9 * right10 + left13 * right11;
    const column2Row2 =
      left2 * right8 + left6 * right9 + left10 * right10 + left14 * right11;
    const column2Row3 =
      left3 * right8 + left7 * right9 + left11 * right10 + left15 * right11;

    const column3Row0 =
      left0 * right12 + left4 * right13 + left8 * right14 + left12 * right15;
    const column3Row1 =
      left1 * right12 + left5 * right13 + left9 * right14 + left13 * right15;
    const column3Row2 =
      left2 * right12 + left6 * right13 + left10 * right14 + left14 * right15;
    const column3Row3 =
      left3 * right12 + left7 * right13 + left11 * right14 + left15 * right15;

    result[0] = column0Row0;
    result[1] = column0Row1;
    result[2] = column0Row2;
    result[3] = column0Row3;
    result[4] = column1Row0;
    result[5] = column1Row1;
    result[6] = column1Row2;
    result[7] = column1Row3;
    result[8] = column2Row0;
    result[9] = column2Row1;
    result[10] = column2Row2;
    result[11] = column2Row3;
    result[12] = column3Row0;
    result[13] = column3Row1;
    result[14] = column3Row2;
    result[15] = column3Row3;
    return result;
  };

  /**
   * Computes the sum of two matrices.
   *
   * @param {Matrix4} left The first matrix.
   * @param {Matrix4} right The second matrix.
   * @param {Matrix4} result The object onto which to store the result.
   * @returns {Matrix4} The modified result parameter.
   */
  Matrix4.add = function (left, right, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result[0] = left[0] + right[0];
    result[1] = left[1] + right[1];
    result[2] = left[2] + right[2];
    result[3] = left[3] + right[3];
    result[4] = left[4] + right[4];
    result[5] = left[5] + right[5];
    result[6] = left[6] + right[6];
    result[7] = left[7] + right[7];
    result[8] = left[8] + right[8];
    result[9] = left[9] + right[9];
    result[10] = left[10] + right[10];
    result[11] = left[11] + right[11];
    result[12] = left[12] + right[12];
    result[13] = left[13] + right[13];
    result[14] = left[14] + right[14];
    result[15] = left[15] + right[15];
    return result;
  };

  /**
   * Computes the difference of two matrices.
   *
   * @param {Matrix4} left The first matrix.
   * @param {Matrix4} right The second matrix.
   * @param {Matrix4} result The object onto which to store the result.
   * @returns {Matrix4} The modified result parameter.
   */
  Matrix4.subtract = function (left, right, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result[0] = left[0] - right[0];
    result[1] = left[1] - right[1];
    result[2] = left[2] - right[2];
    result[3] = left[3] - right[3];
    result[4] = left[4] - right[4];
    result[5] = left[5] - right[5];
    result[6] = left[6] - right[6];
    result[7] = left[7] - right[7];
    result[8] = left[8] - right[8];
    result[9] = left[9] - right[9];
    result[10] = left[10] - right[10];
    result[11] = left[11] - right[11];
    result[12] = left[12] - right[12];
    result[13] = left[13] - right[13];
    result[14] = left[14] - right[14];
    result[15] = left[15] - right[15];
    return result;
  };

  /**
   * Computes the product of two matrices assuming the matrices are affine transformation matrices,
   * where the upper left 3x3 elements are any matrix, and
   * the upper three elements in the fourth column are the translation.
   * The bottom row is assumed to be [0, 0, 0, 1].
   * The matrix is not verified to be in the proper form.
   * This method is faster than computing the product for general 4x4
   * matrices using {@link Matrix4.multiply}.
   *
   * @param {Matrix4} left The first matrix.
   * @param {Matrix4} right The second matrix.
   * @param {Matrix4} result The object onto which to store the result.
   * @returns {Matrix4} The modified result parameter.
   *
   * @example
   * const m1 = new Cesium.Matrix4(1.0, 6.0, 7.0, 0.0, 2.0, 5.0, 8.0, 0.0, 3.0, 4.0, 9.0, 0.0, 0.0, 0.0, 0.0, 1.0);
   * const m2 = Cesium.Transforms.eastNorthUpToFixedFrame(new Cesium.Cartesian3(1.0, 1.0, 1.0));
   * const m3 = Cesium.Matrix4.multiplyTransformation(m1, m2, new Cesium.Matrix4());
   */
  Matrix4.multiplyTransformation = function (left, right, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const left0 = left[0];
    const left1 = left[1];
    const left2 = left[2];
    const left4 = left[4];
    const left5 = left[5];
    const left6 = left[6];
    const left8 = left[8];
    const left9 = left[9];
    const left10 = left[10];
    const left12 = left[12];
    const left13 = left[13];
    const left14 = left[14];

    const right0 = right[0];
    const right1 = right[1];
    const right2 = right[2];
    const right4 = right[4];
    const right5 = right[5];
    const right6 = right[6];
    const right8 = right[8];
    const right9 = right[9];
    const right10 = right[10];
    const right12 = right[12];
    const right13 = right[13];
    const right14 = right[14];

    const column0Row0 = left0 * right0 + left4 * right1 + left8 * right2;
    const column0Row1 = left1 * right0 + left5 * right1 + left9 * right2;
    const column0Row2 = left2 * right0 + left6 * right1 + left10 * right2;

    const column1Row0 = left0 * right4 + left4 * right5 + left8 * right6;
    const column1Row1 = left1 * right4 + left5 * right5 + left9 * right6;
    const column1Row2 = left2 * right4 + left6 * right5 + left10 * right6;

    const column2Row0 = left0 * right8 + left4 * right9 + left8 * right10;
    const column2Row1 = left1 * right8 + left5 * right9 + left9 * right10;
    const column2Row2 = left2 * right8 + left6 * right9 + left10 * right10;

    const column3Row0 =
      left0 * right12 + left4 * right13 + left8 * right14 + left12;
    const column3Row1 =
      left1 * right12 + left5 * right13 + left9 * right14 + left13;
    const column3Row2 =
      left2 * right12 + left6 * right13 + left10 * right14 + left14;

    result[0] = column0Row0;
    result[1] = column0Row1;
    result[2] = column0Row2;
    result[3] = 0.0;
    result[4] = column1Row0;
    result[5] = column1Row1;
    result[6] = column1Row2;
    result[7] = 0.0;
    result[8] = column2Row0;
    result[9] = column2Row1;
    result[10] = column2Row2;
    result[11] = 0.0;
    result[12] = column3Row0;
    result[13] = column3Row1;
    result[14] = column3Row2;
    result[15] = 1.0;
    return result;
  };

  /**
   * Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
   * by a 3x3 rotation matrix.  This is an optimization
   * for <code>Matrix4.multiply(m, Matrix4.fromRotationTranslation(rotation), m);</code> with less allocations and arithmetic operations.
   *
   * @param {Matrix4} matrix The matrix on the left-hand side.
   * @param {Matrix3} rotation The 3x3 rotation matrix on the right-hand side.
   * @param {Matrix4} result The object onto which to store the result.
   * @returns {Matrix4} The modified result parameter.
   *
   * @example
   * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromRotationTranslation(rotation), m);
   * Cesium.Matrix4.multiplyByMatrix3(m, rotation, m);
   */
  Matrix4.multiplyByMatrix3 = function (matrix, rotation, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("rotation", rotation);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const left0 = matrix[0];
    const left1 = matrix[1];
    const left2 = matrix[2];
    const left4 = matrix[4];
    const left5 = matrix[5];
    const left6 = matrix[6];
    const left8 = matrix[8];
    const left9 = matrix[9];
    const left10 = matrix[10];

    const right0 = rotation[0];
    const right1 = rotation[1];
    const right2 = rotation[2];
    const right4 = rotation[3];
    const right5 = rotation[4];
    const right6 = rotation[5];
    const right8 = rotation[6];
    const right9 = rotation[7];
    const right10 = rotation[8];

    const column0Row0 = left0 * right0 + left4 * right1 + left8 * right2;
    const column0Row1 = left1 * right0 + left5 * right1 + left9 * right2;
    const column0Row2 = left2 * right0 + left6 * right1 + left10 * right2;

    const column1Row0 = left0 * right4 + left4 * right5 + left8 * right6;
    const column1Row1 = left1 * right4 + left5 * right5 + left9 * right6;
    const column1Row2 = left2 * right4 + left6 * right5 + left10 * right6;

    const column2Row0 = left0 * right8 + left4 * right9 + left8 * right10;
    const column2Row1 = left1 * right8 + left5 * right9 + left9 * right10;
    const column2Row2 = left2 * right8 + left6 * right9 + left10 * right10;

    result[0] = column0Row0;
    result[1] = column0Row1;
    result[2] = column0Row2;
    result[3] = 0.0;
    result[4] = column1Row0;
    result[5] = column1Row1;
    result[6] = column1Row2;
    result[7] = 0.0;
    result[8] = column2Row0;
    result[9] = column2Row1;
    result[10] = column2Row2;
    result[11] = 0.0;
    result[12] = matrix[12];
    result[13] = matrix[13];
    result[14] = matrix[14];
    result[15] = matrix[15];
    return result;
  };

  /**
   * Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
   * by an implicit translation matrix defined by a {@link Cartesian3}.  This is an optimization
   * for <code>Matrix4.multiply(m, Matrix4.fromTranslation(position), m);</code> with less allocations and arithmetic operations.
   *
   * @param {Matrix4} matrix The matrix on the left-hand side.
   * @param {Cartesian3} translation The translation on the right-hand side.
   * @param {Matrix4} result The object onto which to store the result.
   * @returns {Matrix4} The modified result parameter.
   *
   * @example
   * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromTranslation(position), m);
   * Cesium.Matrix4.multiplyByTranslation(m, position, m);
   */
  Matrix4.multiplyByTranslation = function (matrix, translation, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("translation", translation);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const x = translation.x;
    const y = translation.y;
    const z = translation.z;

    const tx = x * matrix[0] + y * matrix[4] + z * matrix[8] + matrix[12];
    const ty = x * matrix[1] + y * matrix[5] + z * matrix[9] + matrix[13];
    const tz = x * matrix[2] + y * matrix[6] + z * matrix[10] + matrix[14];

    result[0] = matrix[0];
    result[1] = matrix[1];
    result[2] = matrix[2];
    result[3] = matrix[3];
    result[4] = matrix[4];
    result[5] = matrix[5];
    result[6] = matrix[6];
    result[7] = matrix[7];
    result[8] = matrix[8];
    result[9] = matrix[9];
    result[10] = matrix[10];
    result[11] = matrix[11];
    result[12] = tx;
    result[13] = ty;
    result[14] = tz;
    result[15] = matrix[15];
    return result;
  };

  /**
   * Multiplies an affine transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
   * by an implicit non-uniform scale matrix. This is an optimization
   * for <code>Matrix4.multiply(m, Matrix4.fromUniformScale(scale), m);</code>, where
   * <code>m</code> must be an affine matrix.
   * This function performs fewer allocations and arithmetic operations.
   *
   * @param {Matrix4} matrix The affine matrix on the left-hand side.
   * @param {Cartesian3} scale The non-uniform scale on the right-hand side.
   * @param {Matrix4} result The object onto which to store the result.
   * @returns {Matrix4} The modified result parameter.
   *
   *
   * @example
   * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromScale(scale), m);
   * Cesium.Matrix4.multiplyByScale(m, scale, m);
   *
   * @see Matrix4.multiplyByUniformScale
   * @see Matrix4.fromScale
   * @see Matrix4.fromUniformScale
   * @see Matrix4.setScale
   * @see Matrix4.setUniformScale
   * @see Matrix4.getScale
   */
  Matrix4.multiplyByScale = function (matrix, scale, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("scale", scale);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const scaleX = scale.x;
    const scaleY = scale.y;
    const scaleZ = scale.z;

    // Faster than Cartesian3.equals
    if (scaleX === 1.0 && scaleY === 1.0 && scaleZ === 1.0) {
      return Matrix4.clone(matrix, result);
    }

    result[0] = scaleX * matrix[0];
    result[1] = scaleX * matrix[1];
    result[2] = scaleX * matrix[2];
    result[3] = matrix[3];

    result[4] = scaleY * matrix[4];
    result[5] = scaleY * matrix[5];
    result[6] = scaleY * matrix[6];
    result[7] = matrix[7];

    result[8] = scaleZ * matrix[8];
    result[9] = scaleZ * matrix[9];
    result[10] = scaleZ * matrix[10];
    result[11] = matrix[11];

    result[12] = matrix[12];
    result[13] = matrix[13];
    result[14] = matrix[14];
    result[15] = matrix[15];

    return result;
  };

  /**
   * Computes the product of a matrix times a uniform scale, as if the scale were a scale matrix.
   *
   * @param {Matrix4} matrix The matrix on the left-hand side.
   * @param {Number} scale The uniform scale on the right-hand side.
   * @param {Matrix4} result The object onto which to store the result.
   * @returns {Matrix4} The modified result parameter.
   *
   * @example
   * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromUniformScale(scale), m);
   * Cesium.Matrix4.multiplyByUniformScale(m, scale, m);
   *
   * @see Matrix4.multiplyByScale
   * @see Matrix4.fromScale
   * @see Matrix4.fromUniformScale
   * @see Matrix4.setScale
   * @see Matrix4.setUniformScale
   * @see Matrix4.getScale
   */
  Matrix4.multiplyByUniformScale = function (matrix, scale, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.number("scale", scale);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result[0] = matrix[0] * scale;
    result[1] = matrix[1] * scale;
    result[2] = matrix[2] * scale;
    result[3] = matrix[3];

    result[4] = matrix[4] * scale;
    result[5] = matrix[5] * scale;
    result[6] = matrix[6] * scale;
    result[7] = matrix[7];

    result[8] = matrix[8] * scale;
    result[9] = matrix[9] * scale;
    result[10] = matrix[10] * scale;
    result[11] = matrix[11];

    result[12] = matrix[12];
    result[13] = matrix[13];
    result[14] = matrix[14];
    result[15] = matrix[15];

    return result;
  };

  /**
   * Computes the product of a matrix and a column vector.
   *
   * @param {Matrix4} matrix The matrix.
   * @param {Cartesian4} cartesian The vector.
   * @param {Cartesian4} result The object onto which to store the result.
   * @returns {Cartesian4} The modified result parameter.
   */
  Matrix4.multiplyByVector = function (matrix, cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const vX = cartesian.x;
    const vY = cartesian.y;
    const vZ = cartesian.z;
    const vW = cartesian.w;

    const x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ + matrix[12] * vW;
    const y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ + matrix[13] * vW;
    const z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ + matrix[14] * vW;
    const w = matrix[3] * vX + matrix[7] * vY + matrix[11] * vZ + matrix[15] * vW;

    result.x = x;
    result.y = y;
    result.z = z;
    result.w = w;
    return result;
  };

  /**
   * Computes the product of a matrix and a {@link Cartesian3}.  This is equivalent to calling {@link Matrix4.multiplyByVector}
   * with a {@link Cartesian4} with a <code>w</code> component of zero.
   *
   * @param {Matrix4} matrix The matrix.
   * @param {Cartesian3} cartesian The point.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter.
   *
   * @example
   * const p = new Cesium.Cartesian3(1.0, 2.0, 3.0);
   * const result = Cesium.Matrix4.multiplyByPointAsVector(matrix, p, new Cesium.Cartesian3());
   * // A shortcut for
   * //   Cartesian3 p = ...
   * //   Cesium.Matrix4.multiplyByVector(matrix, new Cesium.Cartesian4(p.x, p.y, p.z, 0.0), result);
   */
  Matrix4.multiplyByPointAsVector = function (matrix, cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const vX = cartesian.x;
    const vY = cartesian.y;
    const vZ = cartesian.z;

    const x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ;
    const y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ;
    const z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ;

    result.x = x;
    result.y = y;
    result.z = z;
    return result;
  };

  /**
   * Computes the product of a matrix and a {@link Cartesian3}. This is equivalent to calling {@link Matrix4.multiplyByVector}
   * with a {@link Cartesian4} with a <code>w</code> component of 1, but returns a {@link Cartesian3} instead of a {@link Cartesian4}.
   *
   * @param {Matrix4} matrix The matrix.
   * @param {Cartesian3} cartesian The point.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter.
   *
   * @example
   * const p = new Cesium.Cartesian3(1.0, 2.0, 3.0);
   * const result = Cesium.Matrix4.multiplyByPoint(matrix, p, new Cesium.Cartesian3());
   */
  Matrix4.multiplyByPoint = function (matrix, cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const vX = cartesian.x;
    const vY = cartesian.y;
    const vZ = cartesian.z;

    const x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ + matrix[12];
    const y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ + matrix[13];
    const z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ + matrix[14];

    result.x = x;
    result.y = y;
    result.z = z;
    return result;
  };

  /**
   * Computes the product of a matrix and a scalar.
   *
   * @param {Matrix4} matrix The matrix.
   * @param {Number} scalar The number to multiply by.
   * @param {Matrix4} result The object onto which to store the result.
   * @returns {Matrix4} The modified result parameter.
   *
   * @example
   * //create a Matrix4 instance which is a scaled version of the supplied Matrix4
   * // m = [10.0, 11.0, 12.0, 13.0]
   * //     [14.0, 15.0, 16.0, 17.0]
   * //     [18.0, 19.0, 20.0, 21.0]
   * //     [22.0, 23.0, 24.0, 25.0]
   *
   * const a = Cesium.Matrix4.multiplyByScalar(m, -2, new Cesium.Matrix4());
   *
   * // m remains the same
   * // a = [-20.0, -22.0, -24.0, -26.0]
   * //     [-28.0, -30.0, -32.0, -34.0]
   * //     [-36.0, -38.0, -40.0, -42.0]
   * //     [-44.0, -46.0, -48.0, -50.0]
   */
  Matrix4.multiplyByScalar = function (matrix, scalar, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.number("scalar", scalar);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result[0] = matrix[0] * scalar;
    result[1] = matrix[1] * scalar;
    result[2] = matrix[2] * scalar;
    result[3] = matrix[3] * scalar;
    result[4] = matrix[4] * scalar;
    result[5] = matrix[5] * scalar;
    result[6] = matrix[6] * scalar;
    result[7] = matrix[7] * scalar;
    result[8] = matrix[8] * scalar;
    result[9] = matrix[9] * scalar;
    result[10] = matrix[10] * scalar;
    result[11] = matrix[11] * scalar;
    result[12] = matrix[12] * scalar;
    result[13] = matrix[13] * scalar;
    result[14] = matrix[14] * scalar;
    result[15] = matrix[15] * scalar;
    return result;
  };

  /**
   * Computes a negated copy of the provided matrix.
   *
   * @param {Matrix4} matrix The matrix to negate.
   * @param {Matrix4} result The object onto which to store the result.
   * @returns {Matrix4} The modified result parameter.
   *
   * @example
   * //create a new Matrix4 instance which is a negation of a Matrix4
   * // m = [10.0, 11.0, 12.0, 13.0]
   * //     [14.0, 15.0, 16.0, 17.0]
   * //     [18.0, 19.0, 20.0, 21.0]
   * //     [22.0, 23.0, 24.0, 25.0]
   *
   * const a = Cesium.Matrix4.negate(m, new Cesium.Matrix4());
   *
   * // m remains the same
   * // a = [-10.0, -11.0, -12.0, -13.0]
   * //     [-14.0, -15.0, -16.0, -17.0]
   * //     [-18.0, -19.0, -20.0, -21.0]
   * //     [-22.0, -23.0, -24.0, -25.0]
   */
  Matrix4.negate = function (matrix, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result[0] = -matrix[0];
    result[1] = -matrix[1];
    result[2] = -matrix[2];
    result[3] = -matrix[3];
    result[4] = -matrix[4];
    result[5] = -matrix[5];
    result[6] = -matrix[6];
    result[7] = -matrix[7];
    result[8] = -matrix[8];
    result[9] = -matrix[9];
    result[10] = -matrix[10];
    result[11] = -matrix[11];
    result[12] = -matrix[12];
    result[13] = -matrix[13];
    result[14] = -matrix[14];
    result[15] = -matrix[15];
    return result;
  };

  /**
   * Computes the transpose of the provided matrix.
   *
   * @param {Matrix4} matrix The matrix to transpose.
   * @param {Matrix4} result The object onto which to store the result.
   * @returns {Matrix4} The modified result parameter.
   *
   * @example
   * //returns transpose of a Matrix4
   * // m = [10.0, 11.0, 12.0, 13.0]
   * //     [14.0, 15.0, 16.0, 17.0]
   * //     [18.0, 19.0, 20.0, 21.0]
   * //     [22.0, 23.0, 24.0, 25.0]
   *
   * const a = Cesium.Matrix4.transpose(m, new Cesium.Matrix4());
   *
   * // m remains the same
   * // a = [10.0, 14.0, 18.0, 22.0]
   * //     [11.0, 15.0, 19.0, 23.0]
   * //     [12.0, 16.0, 20.0, 24.0]
   * //     [13.0, 17.0, 21.0, 25.0]
   */
  Matrix4.transpose = function (matrix, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const matrix1 = matrix[1];
    const matrix2 = matrix[2];
    const matrix3 = matrix[3];
    const matrix6 = matrix[6];
    const matrix7 = matrix[7];
    const matrix11 = matrix[11];

    result[0] = matrix[0];
    result[1] = matrix[4];
    result[2] = matrix[8];
    result[3] = matrix[12];
    result[4] = matrix1;
    result[5] = matrix[5];
    result[6] = matrix[9];
    result[7] = matrix[13];
    result[8] = matrix2;
    result[9] = matrix6;
    result[10] = matrix[10];
    result[11] = matrix[14];
    result[12] = matrix3;
    result[13] = matrix7;
    result[14] = matrix11;
    result[15] = matrix[15];
    return result;
  };

  /**
   * Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
   *
   * @param {Matrix4} matrix The matrix with signed elements.
   * @param {Matrix4} result The object onto which to store the result.
   * @returns {Matrix4} The modified result parameter.
   */
  Matrix4.abs = function (matrix, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result[0] = Math.abs(matrix[0]);
    result[1] = Math.abs(matrix[1]);
    result[2] = Math.abs(matrix[2]);
    result[3] = Math.abs(matrix[3]);
    result[4] = Math.abs(matrix[4]);
    result[5] = Math.abs(matrix[5]);
    result[6] = Math.abs(matrix[6]);
    result[7] = Math.abs(matrix[7]);
    result[8] = Math.abs(matrix[8]);
    result[9] = Math.abs(matrix[9]);
    result[10] = Math.abs(matrix[10]);
    result[11] = Math.abs(matrix[11]);
    result[12] = Math.abs(matrix[12]);
    result[13] = Math.abs(matrix[13]);
    result[14] = Math.abs(matrix[14]);
    result[15] = Math.abs(matrix[15]);

    return result;
  };

  /**
   * Compares the provided matrices componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Matrix4} [left] The first matrix.
   * @param {Matrix4} [right] The second matrix.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   *
   * @example
   * //compares two Matrix4 instances
   *
   * // a = [10.0, 14.0, 18.0, 22.0]
   * //     [11.0, 15.0, 19.0, 23.0]
   * //     [12.0, 16.0, 20.0, 24.0]
   * //     [13.0, 17.0, 21.0, 25.0]
   *
   * // b = [10.0, 14.0, 18.0, 22.0]
   * //     [11.0, 15.0, 19.0, 23.0]
   * //     [12.0, 16.0, 20.0, 24.0]
   * //     [13.0, 17.0, 21.0, 25.0]
   *
   * if(Cesium.Matrix4.equals(a,b)) {
   *      console.log("Both matrices are equal");
   * } else {
   *      console.log("They are not equal");
   * }
   *
   * //Prints "Both matrices are equal" on the console
   */
  Matrix4.equals = function (left, right) {
    // Given that most matrices will be transformation matrices, the elements
    // are tested in order such that the test is likely to fail as early
    // as possible.  I _think_ this is just as friendly to the L1 cache
    // as testing in index order.  It is certainty faster in practice.
    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        // Translation
        left[12] === right[12] &&
        left[13] === right[13] &&
        left[14] === right[14] &&
        // Rotation/scale
        left[0] === right[0] &&
        left[1] === right[1] &&
        left[2] === right[2] &&
        left[4] === right[4] &&
        left[5] === right[5] &&
        left[6] === right[6] &&
        left[8] === right[8] &&
        left[9] === right[9] &&
        left[10] === right[10] &&
        // Bottom row
        left[3] === right[3] &&
        left[7] === right[7] &&
        left[11] === right[11] &&
        left[15] === right[15])
    );
  };

  /**
   * Compares the provided matrices componentwise and returns
   * <code>true</code> if they are within the provided epsilon,
   * <code>false</code> otherwise.
   *
   * @param {Matrix4} [left] The first matrix.
   * @param {Matrix4} [right] The second matrix.
   * @param {Number} [epsilon=0] The epsilon to use for equality testing.
   * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
   *
   * @example
   * //compares two Matrix4 instances
   *
   * // a = [10.5, 14.5, 18.5, 22.5]
   * //     [11.5, 15.5, 19.5, 23.5]
   * //     [12.5, 16.5, 20.5, 24.5]
   * //     [13.5, 17.5, 21.5, 25.5]
   *
   * // b = [10.0, 14.0, 18.0, 22.0]
   * //     [11.0, 15.0, 19.0, 23.0]
   * //     [12.0, 16.0, 20.0, 24.0]
   * //     [13.0, 17.0, 21.0, 25.0]
   *
   * if(Cesium.Matrix4.equalsEpsilon(a,b,0.1)){
   *      console.log("Difference between both the matrices is less than 0.1");
   * } else {
   *      console.log("Difference between both the matrices is not less than 0.1");
   * }
   *
   * //Prints "Difference between both the matrices is not less than 0.1" on the console
   */
  Matrix4.equalsEpsilon = function (left, right, epsilon) {
    epsilon = defaultValue(epsilon, 0);

    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        Math.abs(left[0] - right[0]) <= epsilon &&
        Math.abs(left[1] - right[1]) <= epsilon &&
        Math.abs(left[2] - right[2]) <= epsilon &&
        Math.abs(left[3] - right[3]) <= epsilon &&
        Math.abs(left[4] - right[4]) <= epsilon &&
        Math.abs(left[5] - right[5]) <= epsilon &&
        Math.abs(left[6] - right[6]) <= epsilon &&
        Math.abs(left[7] - right[7]) <= epsilon &&
        Math.abs(left[8] - right[8]) <= epsilon &&
        Math.abs(left[9] - right[9]) <= epsilon &&
        Math.abs(left[10] - right[10]) <= epsilon &&
        Math.abs(left[11] - right[11]) <= epsilon &&
        Math.abs(left[12] - right[12]) <= epsilon &&
        Math.abs(left[13] - right[13]) <= epsilon &&
        Math.abs(left[14] - right[14]) <= epsilon &&
        Math.abs(left[15] - right[15]) <= epsilon)
    );
  };

  /**
   * Gets the translation portion of the provided matrix, assuming the matrix is an affine transformation matrix.
   *
   * @param {Matrix4} matrix The matrix to use.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter.
   */
  Matrix4.getTranslation = function (matrix, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.x = matrix[12];
    result.y = matrix[13];
    result.z = matrix[14];
    return result;
  };

  /**
   * Gets the upper left 3x3 matrix of the provided matrix.
   *
   * @param {Matrix4} matrix The matrix to use.
   * @param {Matrix3} result The object onto which to store the result.
   * @returns {Matrix3} The modified result parameter.
   *
   * @example
   * // returns a Matrix3 instance from a Matrix4 instance
   *
   * // m = [10.0, 14.0, 18.0, 22.0]
   * //     [11.0, 15.0, 19.0, 23.0]
   * //     [12.0, 16.0, 20.0, 24.0]
   * //     [13.0, 17.0, 21.0, 25.0]
   *
   * const b = new Cesium.Matrix3();
   * Cesium.Matrix4.getMatrix3(m,b);
   *
   * // b = [10.0, 14.0, 18.0]
   * //     [11.0, 15.0, 19.0]
   * //     [12.0, 16.0, 20.0]
   */
  Matrix4.getMatrix3 = function (matrix, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result[0] = matrix[0];
    result[1] = matrix[1];
    result[2] = matrix[2];
    result[3] = matrix[4];
    result[4] = matrix[5];
    result[5] = matrix[6];
    result[6] = matrix[8];
    result[7] = matrix[9];
    result[8] = matrix[10];
    return result;
  };

  const scratchInverseRotation = new Matrix3();
  const scratchMatrix3Zero = new Matrix3();
  const scratchBottomRow = new Cartesian4();
  const scratchExpectedBottomRow = new Cartesian4(0.0, 0.0, 0.0, 1.0);

  /**
   * Computes the inverse of the provided matrix using Cramers Rule.
   * If the determinant is zero, the matrix can not be inverted, and an exception is thrown.
   * If the matrix is a proper rigid transformation, it is more efficient
   * to invert it with {@link Matrix4.inverseTransformation}.
   *
   * @param {Matrix4} matrix The matrix to invert.
   * @param {Matrix4} result The object onto which to store the result.
   * @returns {Matrix4} The modified result parameter.
   *
   * @exception {RuntimeError} matrix is not invertible because its determinate is zero.
   */
  Matrix4.inverse = function (matrix, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');
    //
    // Ported from:
    //   ftp://download.intel.com/design/PentiumIII/sml/24504301.pdf
    //
    const src0 = matrix[0];
    const src1 = matrix[4];
    const src2 = matrix[8];
    const src3 = matrix[12];
    const src4 = matrix[1];
    const src5 = matrix[5];
    const src6 = matrix[9];
    const src7 = matrix[13];
    const src8 = matrix[2];
    const src9 = matrix[6];
    const src10 = matrix[10];
    const src11 = matrix[14];
    const src12 = matrix[3];
    const src13 = matrix[7];
    const src14 = matrix[11];
    const src15 = matrix[15];

    // calculate pairs for first 8 elements (cofactors)
    let tmp0 = src10 * src15;
    let tmp1 = src11 * src14;
    let tmp2 = src9 * src15;
    let tmp3 = src11 * src13;
    let tmp4 = src9 * src14;
    let tmp5 = src10 * src13;
    let tmp6 = src8 * src15;
    let tmp7 = src11 * src12;
    let tmp8 = src8 * src14;
    let tmp9 = src10 * src12;
    let tmp10 = src8 * src13;
    let tmp11 = src9 * src12;

    // calculate first 8 elements (cofactors)
    const dst0 =
      tmp0 * src5 +
      tmp3 * src6 +
      tmp4 * src7 -
      (tmp1 * src5 + tmp2 * src6 + tmp5 * src7);
    const dst1 =
      tmp1 * src4 +
      tmp6 * src6 +
      tmp9 * src7 -
      (tmp0 * src4 + tmp7 * src6 + tmp8 * src7);
    const dst2 =
      tmp2 * src4 +
      tmp7 * src5 +
      tmp10 * src7 -
      (tmp3 * src4 + tmp6 * src5 + tmp11 * src7);
    const dst3 =
      tmp5 * src4 +
      tmp8 * src5 +
      tmp11 * src6 -
      (tmp4 * src4 + tmp9 * src5 + tmp10 * src6);
    const dst4 =
      tmp1 * src1 +
      tmp2 * src2 +
      tmp5 * src3 -
      (tmp0 * src1 + tmp3 * src2 + tmp4 * src3);
    const dst5 =
      tmp0 * src0 +
      tmp7 * src2 +
      tmp8 * src3 -
      (tmp1 * src0 + tmp6 * src2 + tmp9 * src3);
    const dst6 =
      tmp3 * src0 +
      tmp6 * src1 +
      tmp11 * src3 -
      (tmp2 * src0 + tmp7 * src1 + tmp10 * src3);
    const dst7 =
      tmp4 * src0 +
      tmp9 * src1 +
      tmp10 * src2 -
      (tmp5 * src0 + tmp8 * src1 + tmp11 * src2);

    // calculate pairs for second 8 elements (cofactors)
    tmp0 = src2 * src7;
    tmp1 = src3 * src6;
    tmp2 = src1 * src7;
    tmp3 = src3 * src5;
    tmp4 = src1 * src6;
    tmp5 = src2 * src5;
    tmp6 = src0 * src7;
    tmp7 = src3 * src4;
    tmp8 = src0 * src6;
    tmp9 = src2 * src4;
    tmp10 = src0 * src5;
    tmp11 = src1 * src4;

    // calculate second 8 elements (cofactors)
    const dst8 =
      tmp0 * src13 +
      tmp3 * src14 +
      tmp4 * src15 -
      (tmp1 * src13 + tmp2 * src14 + tmp5 * src15);
    const dst9 =
      tmp1 * src12 +
      tmp6 * src14 +
      tmp9 * src15 -
      (tmp0 * src12 + tmp7 * src14 + tmp8 * src15);
    const dst10 =
      tmp2 * src12 +
      tmp7 * src13 +
      tmp10 * src15 -
      (tmp3 * src12 + tmp6 * src13 + tmp11 * src15);
    const dst11 =
      tmp5 * src12 +
      tmp8 * src13 +
      tmp11 * src14 -
      (tmp4 * src12 + tmp9 * src13 + tmp10 * src14);
    const dst12 =
      tmp2 * src10 +
      tmp5 * src11 +
      tmp1 * src9 -
      (tmp4 * src11 + tmp0 * src9 + tmp3 * src10);
    const dst13 =
      tmp8 * src11 +
      tmp0 * src8 +
      tmp7 * src10 -
      (tmp6 * src10 + tmp9 * src11 + tmp1 * src8);
    const dst14 =
      tmp6 * src9 +
      tmp11 * src11 +
      tmp3 * src8 -
      (tmp10 * src11 + tmp2 * src8 + tmp7 * src9);
    const dst15 =
      tmp10 * src10 +
      tmp4 * src8 +
      tmp9 * src9 -
      (tmp8 * src9 + tmp11 * src10 + tmp5 * src8);

    // calculate determinant
    let det = src0 * dst0 + src1 * dst1 + src2 * dst2 + src3 * dst3;

    if (Math.abs(det) < CesiumMath.EPSILON21) {
      // Special case for a zero scale matrix that can occur, for example,
      // when a model's node has a [0, 0, 0] scale.
      if (
        Matrix3.equalsEpsilon(
          Matrix4.getMatrix3(matrix, scratchInverseRotation),
          scratchMatrix3Zero,
          CesiumMath.EPSILON7
        ) &&
        Cartesian4.equals(
          Matrix4.getRow(matrix, 3, scratchBottomRow),
          scratchExpectedBottomRow
        )
      ) {
        result[0] = 0.0;
        result[1] = 0.0;
        result[2] = 0.0;
        result[3] = 0.0;
        result[4] = 0.0;
        result[5] = 0.0;
        result[6] = 0.0;
        result[7] = 0.0;
        result[8] = 0.0;
        result[9] = 0.0;
        result[10] = 0.0;
        result[11] = 0.0;
        result[12] = -matrix[12];
        result[13] = -matrix[13];
        result[14] = -matrix[14];
        result[15] = 1.0;
        return result;
      }

      throw new RuntimeError(
        "matrix is not invertible because its determinate is zero."
      );
    }

    // calculate matrix inverse
    det = 1.0 / det;

    result[0] = dst0 * det;
    result[1] = dst1 * det;
    result[2] = dst2 * det;
    result[3] = dst3 * det;
    result[4] = dst4 * det;
    result[5] = dst5 * det;
    result[6] = dst6 * det;
    result[7] = dst7 * det;
    result[8] = dst8 * det;
    result[9] = dst9 * det;
    result[10] = dst10 * det;
    result[11] = dst11 * det;
    result[12] = dst12 * det;
    result[13] = dst13 * det;
    result[14] = dst14 * det;
    result[15] = dst15 * det;
    return result;
  };

  /**
   * Computes the inverse of the provided matrix assuming it is a proper rigid matrix,
   * where the upper left 3x3 elements are a rotation matrix,
   * and the upper three elements in the fourth column are the translation.
   * The bottom row is assumed to be [0, 0, 0, 1].
   * The matrix is not verified to be in the proper form.
   * This method is faster than computing the inverse for a general 4x4
   * matrix using {@link Matrix4.inverse}.
   *
   * @param {Matrix4} matrix The matrix to invert.
   * @param {Matrix4} result The object onto which to store the result.
   * @returns {Matrix4} The modified result parameter.
   */
  Matrix4.inverseTransformation = function (matrix, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    //This function is an optimized version of the below 4 lines.
    //const rT = Matrix3.transpose(Matrix4.getMatrix3(matrix));
    //const rTN = Matrix3.negate(rT);
    //const rTT = Matrix3.multiplyByVector(rTN, Matrix4.getTranslation(matrix));
    //return Matrix4.fromRotationTranslation(rT, rTT, result);

    const matrix0 = matrix[0];
    const matrix1 = matrix[1];
    const matrix2 = matrix[2];
    const matrix4 = matrix[4];
    const matrix5 = matrix[5];
    const matrix6 = matrix[6];
    const matrix8 = matrix[8];
    const matrix9 = matrix[9];
    const matrix10 = matrix[10];

    const vX = matrix[12];
    const vY = matrix[13];
    const vZ = matrix[14];

    const x = -matrix0 * vX - matrix1 * vY - matrix2 * vZ;
    const y = -matrix4 * vX - matrix5 * vY - matrix6 * vZ;
    const z = -matrix8 * vX - matrix9 * vY - matrix10 * vZ;

    result[0] = matrix0;
    result[1] = matrix4;
    result[2] = matrix8;
    result[3] = 0.0;
    result[4] = matrix1;
    result[5] = matrix5;
    result[6] = matrix9;
    result[7] = 0.0;
    result[8] = matrix2;
    result[9] = matrix6;
    result[10] = matrix10;
    result[11] = 0.0;
    result[12] = x;
    result[13] = y;
    result[14] = z;
    result[15] = 1.0;
    return result;
  };

  const scratchTransposeMatrix = new Matrix4();

  /**
   * Computes the inverse transpose of a matrix.
   *
   * @param {Matrix4} matrix The matrix to transpose and invert.
   * @param {Matrix4} result The object onto which to store the result.
   * @returns {Matrix4} The modified result parameter.
   */
  Matrix4.inverseTranspose = function (matrix, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    return Matrix4.inverse(
      Matrix4.transpose(matrix, scratchTransposeMatrix),
      result
    );
  };

  /**
   * An immutable Matrix4 instance initialized to the identity matrix.
   *
   * @type {Matrix4}
   * @constant
   */
  Matrix4.IDENTITY = Object.freeze(
    new Matrix4(
      1.0,
      0.0,
      0.0,
      0.0,
      0.0,
      1.0,
      0.0,
      0.0,
      0.0,
      0.0,
      1.0,
      0.0,
      0.0,
      0.0,
      0.0,
      1.0
    )
  );

  /**
   * An immutable Matrix4 instance initialized to the zero matrix.
   *
   * @type {Matrix4}
   * @constant
   */
  Matrix4.ZERO = Object.freeze(
    new Matrix4(
      0.0,
      0.0,
      0.0,
      0.0,
      0.0,
      0.0,
      0.0,
      0.0,
      0.0,
      0.0,
      0.0,
      0.0,
      0.0,
      0.0,
      0.0,
      0.0
    )
  );

  /**
   * The index into Matrix4 for column 0, row 0.
   *
   * @type {Number}
   * @constant
   */
  Matrix4.COLUMN0ROW0 = 0;

  /**
   * The index into Matrix4 for column 0, row 1.
   *
   * @type {Number}
   * @constant
   */
  Matrix4.COLUMN0ROW1 = 1;

  /**
   * The index into Matrix4 for column 0, row 2.
   *
   * @type {Number}
   * @constant
   */
  Matrix4.COLUMN0ROW2 = 2;

  /**
   * The index into Matrix4 for column 0, row 3.
   *
   * @type {Number}
   * @constant
   */
  Matrix4.COLUMN0ROW3 = 3;

  /**
   * The index into Matrix4 for column 1, row 0.
   *
   * @type {Number}
   * @constant
   */
  Matrix4.COLUMN1ROW0 = 4;

  /**
   * The index into Matrix4 for column 1, row 1.
   *
   * @type {Number}
   * @constant
   */
  Matrix4.COLUMN1ROW1 = 5;

  /**
   * The index into Matrix4 for column 1, row 2.
   *
   * @type {Number}
   * @constant
   */
  Matrix4.COLUMN1ROW2 = 6;

  /**
   * The index into Matrix4 for column 1, row 3.
   *
   * @type {Number}
   * @constant
   */
  Matrix4.COLUMN1ROW3 = 7;

  /**
   * The index into Matrix4 for column 2, row 0.
   *
   * @type {Number}
   * @constant
   */
  Matrix4.COLUMN2ROW0 = 8;

  /**
   * The index into Matrix4 for column 2, row 1.
   *
   * @type {Number}
   * @constant
   */
  Matrix4.COLUMN2ROW1 = 9;

  /**
   * The index into Matrix4 for column 2, row 2.
   *
   * @type {Number}
   * @constant
   */
  Matrix4.COLUMN2ROW2 = 10;

  /**
   * The index into Matrix4 for column 2, row 3.
   *
   * @type {Number}
   * @constant
   */
  Matrix4.COLUMN2ROW3 = 11;

  /**
   * The index into Matrix4 for column 3, row 0.
   *
   * @type {Number}
   * @constant
   */
  Matrix4.COLUMN3ROW0 = 12;

  /**
   * The index into Matrix4 for column 3, row 1.
   *
   * @type {Number}
   * @constant
   */
  Matrix4.COLUMN3ROW1 = 13;

  /**
   * The index into Matrix4 for column 3, row 2.
   *
   * @type {Number}
   * @constant
   */
  Matrix4.COLUMN3ROW2 = 14;

  /**
   * The index into Matrix4 for column 3, row 3.
   *
   * @type {Number}
   * @constant
   */
  Matrix4.COLUMN3ROW3 = 15;

  Object.defineProperties(Matrix4.prototype, {
    /**
     * Gets the number of items in the collection.
     * @memberof Matrix4.prototype
     *
     * @type {Number}
     */
    length: {
      get: function () {
        return Matrix4.packedLength;
      },
    },
  });

  /**
   * Duplicates the provided Matrix4 instance.
   *
   * @param {Matrix4} [result] The object onto which to store the result.
   * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
   */
  Matrix4.prototype.clone = function (result) {
    return Matrix4.clone(this, result);
  };

  /**
   * Compares this matrix to the provided matrix componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Matrix4} [right] The right hand side matrix.
   * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
   */
  Matrix4.prototype.equals = function (right) {
    return Matrix4.equals(this, right);
  };

  /**
   * @private
   */
  Matrix4.equalsArray = function (matrix, array, offset) {
    return (
      matrix[0] === array[offset] &&
      matrix[1] === array[offset + 1] &&
      matrix[2] === array[offset + 2] &&
      matrix[3] === array[offset + 3] &&
      matrix[4] === array[offset + 4] &&
      matrix[5] === array[offset + 5] &&
      matrix[6] === array[offset + 6] &&
      matrix[7] === array[offset + 7] &&
      matrix[8] === array[offset + 8] &&
      matrix[9] === array[offset + 9] &&
      matrix[10] === array[offset + 10] &&
      matrix[11] === array[offset + 11] &&
      matrix[12] === array[offset + 12] &&
      matrix[13] === array[offset + 13] &&
      matrix[14] === array[offset + 14] &&
      matrix[15] === array[offset + 15]
    );
  };

  /**
   * Compares this matrix to the provided matrix componentwise and returns
   * <code>true</code> if they are within the provided epsilon,
   * <code>false</code> otherwise.
   *
   * @param {Matrix4} [right] The right hand side matrix.
   * @param {Number} [epsilon=0] The epsilon to use for equality testing.
   * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
   */
  Matrix4.prototype.equalsEpsilon = function (right, epsilon) {
    return Matrix4.equalsEpsilon(this, right, epsilon);
  };

  /**
   * Computes a string representing this Matrix with each row being
   * on a separate line and in the format '(column0, column1, column2, column3)'.
   *
   * @returns {String} A string representing the provided Matrix with each row being on a separate line and in the format '(column0, column1, column2, column3)'.
   */
  Matrix4.prototype.toString = function () {
    return (
      `(${this[0]}, ${this[4]}, ${this[8]}, ${this[12]})\n` +
      `(${this[1]}, ${this[5]}, ${this[9]}, ${this[13]})\n` +
      `(${this[2]}, ${this[6]}, ${this[10]}, ${this[14]})\n` +
      `(${this[3]}, ${this[7]}, ${this[11]}, ${this[15]})`
    );
  };

  /**
   * A two dimensional region specified as longitude and latitude coordinates.
   *
   * @alias Rectangle
   * @constructor
   *
   * @param {Number} [west=0.0] The westernmost longitude, in radians, in the range [-Pi, Pi].
   * @param {Number} [south=0.0] The southernmost latitude, in radians, in the range [-Pi/2, Pi/2].
   * @param {Number} [east=0.0] The easternmost longitude, in radians, in the range [-Pi, Pi].
   * @param {Number} [north=0.0] The northernmost latitude, in radians, in the range [-Pi/2, Pi/2].
   *
   * @see Packable
   */
  function Rectangle(west, south, east, north) {
    /**
     * The westernmost longitude in radians in the range [-Pi, Pi].
     *
     * @type {Number}
     * @default 0.0
     */
    this.west = defaultValue(west, 0.0);

    /**
     * The southernmost latitude in radians in the range [-Pi/2, Pi/2].
     *
     * @type {Number}
     * @default 0.0
     */
    this.south = defaultValue(south, 0.0);

    /**
     * The easternmost longitude in radians in the range [-Pi, Pi].
     *
     * @type {Number}
     * @default 0.0
     */
    this.east = defaultValue(east, 0.0);

    /**
     * The northernmost latitude in radians in the range [-Pi/2, Pi/2].
     *
     * @type {Number}
     * @default 0.0
     */
    this.north = defaultValue(north, 0.0);
  }

  Object.defineProperties(Rectangle.prototype, {
    /**
     * Gets the width of the rectangle in radians.
     * @memberof Rectangle.prototype
     * @type {Number}
     * @readonly
     */
    width: {
      get: function () {
        return Rectangle.computeWidth(this);
      },
    },

    /**
     * Gets the height of the rectangle in radians.
     * @memberof Rectangle.prototype
     * @type {Number}
     * @readonly
     */
    height: {
      get: function () {
        return Rectangle.computeHeight(this);
      },
    },
  });

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  Rectangle.packedLength = 4;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {Rectangle} 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
   */
  Rectangle.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    array[startingIndex++] = value.west;
    array[startingIndex++] = value.south;
    array[startingIndex++] = value.east;
    array[startingIndex] = value.north;

    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 {Rectangle} [result] The object into which to store the result.
   * @returns {Rectangle} The modified result parameter or a new Rectangle instance if one was not provided.
   */
  Rectangle.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    if (!defined(result)) {
      result = new Rectangle();
    }

    result.west = array[startingIndex++];
    result.south = array[startingIndex++];
    result.east = array[startingIndex++];
    result.north = array[startingIndex];
    return result;
  };

  /**
   * Computes the width of a rectangle in radians.
   * @param {Rectangle} rectangle The rectangle to compute the width of.
   * @returns {Number} The width.
   */
  Rectangle.computeWidth = function (rectangle) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("rectangle", rectangle);
    //>>includeEnd('debug');
    let east = rectangle.east;
    const west = rectangle.west;
    if (east < west) {
      east += CesiumMath.TWO_PI;
    }
    return east - west;
  };

  /**
   * Computes the height of a rectangle in radians.
   * @param {Rectangle} rectangle The rectangle to compute the height of.
   * @returns {Number} The height.
   */
  Rectangle.computeHeight = function (rectangle) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("rectangle", rectangle);
    //>>includeEnd('debug');
    return rectangle.north - rectangle.south;
  };

  /**
   * Creates a rectangle given the boundary longitude and latitude in degrees.
   *
   * @param {Number} [west=0.0] The westernmost longitude in degrees in the range [-180.0, 180.0].
   * @param {Number} [south=0.0] The southernmost latitude in degrees in the range [-90.0, 90.0].
   * @param {Number} [east=0.0] The easternmost longitude in degrees in the range [-180.0, 180.0].
   * @param {Number} [north=0.0] The northernmost latitude in degrees in the range [-90.0, 90.0].
   * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
   * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
   *
   * @example
   * const rectangle = Cesium.Rectangle.fromDegrees(0.0, 20.0, 10.0, 30.0);
   */
  Rectangle.fromDegrees = function (west, south, east, north, result) {
    west = CesiumMath.toRadians(defaultValue(west, 0.0));
    south = CesiumMath.toRadians(defaultValue(south, 0.0));
    east = CesiumMath.toRadians(defaultValue(east, 0.0));
    north = CesiumMath.toRadians(defaultValue(north, 0.0));

    if (!defined(result)) {
      return new Rectangle(west, south, east, north);
    }

    result.west = west;
    result.south = south;
    result.east = east;
    result.north = north;

    return result;
  };

  /**
   * Creates a rectangle given the boundary longitude and latitude in radians.
   *
   * @param {Number} [west=0.0] The westernmost longitude in radians in the range [-Math.PI, Math.PI].
   * @param {Number} [south=0.0] The southernmost latitude in radians in the range [-Math.PI/2, Math.PI/2].
   * @param {Number} [east=0.0] The easternmost longitude in radians in the range [-Math.PI, Math.PI].
   * @param {Number} [north=0.0] The northernmost latitude in radians in the range [-Math.PI/2, Math.PI/2].
   * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
   * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
   *
   * @example
   * const rectangle = Cesium.Rectangle.fromRadians(0.0, Math.PI/4, Math.PI/8, 3*Math.PI/4);
   */
  Rectangle.fromRadians = function (west, south, east, north, result) {
    if (!defined(result)) {
      return new Rectangle(west, south, east, north);
    }

    result.west = defaultValue(west, 0.0);
    result.south = defaultValue(south, 0.0);
    result.east = defaultValue(east, 0.0);
    result.north = defaultValue(north, 0.0);

    return result;
  };

  /**
   * Creates the smallest possible Rectangle that encloses all positions in the provided array.
   *
   * @param {Cartographic[]} cartographics The list of Cartographic instances.
   * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
   * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
   */
  Rectangle.fromCartographicArray = function (cartographics, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("cartographics", cartographics);
    //>>includeEnd('debug');

    let west = Number.MAX_VALUE;
    let east = -Number.MAX_VALUE;
    let westOverIDL = Number.MAX_VALUE;
    let eastOverIDL = -Number.MAX_VALUE;
    let south = Number.MAX_VALUE;
    let north = -Number.MAX_VALUE;

    for (let i = 0, len = cartographics.length; i < len; i++) {
      const position = cartographics[i];
      west = Math.min(west, position.longitude);
      east = Math.max(east, position.longitude);
      south = Math.min(south, position.latitude);
      north = Math.max(north, position.latitude);

      const lonAdjusted =
        position.longitude >= 0
          ? position.longitude
          : position.longitude + CesiumMath.TWO_PI;
      westOverIDL = Math.min(westOverIDL, lonAdjusted);
      eastOverIDL = Math.max(eastOverIDL, lonAdjusted);
    }

    if (east - west > eastOverIDL - westOverIDL) {
      west = westOverIDL;
      east = eastOverIDL;

      if (east > CesiumMath.PI) {
        east = east - CesiumMath.TWO_PI;
      }
      if (west > CesiumMath.PI) {
        west = west - CesiumMath.TWO_PI;
      }
    }

    if (!defined(result)) {
      return new Rectangle(west, south, east, north);
    }

    result.west = west;
    result.south = south;
    result.east = east;
    result.north = north;
    return result;
  };

  /**
   * Creates the smallest possible Rectangle that encloses all positions in the provided array.
   *
   * @param {Cartesian3[]} cartesians The list of Cartesian instances.
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid the cartesians are on.
   * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
   * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
   */
  Rectangle.fromCartesianArray = function (cartesians, ellipsoid, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("cartesians", cartesians);
    //>>includeEnd('debug');
    ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);

    let west = Number.MAX_VALUE;
    let east = -Number.MAX_VALUE;
    let westOverIDL = Number.MAX_VALUE;
    let eastOverIDL = -Number.MAX_VALUE;
    let south = Number.MAX_VALUE;
    let north = -Number.MAX_VALUE;

    for (let i = 0, len = cartesians.length; i < len; i++) {
      const position = ellipsoid.cartesianToCartographic(cartesians[i]);
      west = Math.min(west, position.longitude);
      east = Math.max(east, position.longitude);
      south = Math.min(south, position.latitude);
      north = Math.max(north, position.latitude);

      const lonAdjusted =
        position.longitude >= 0
          ? position.longitude
          : position.longitude + CesiumMath.TWO_PI;
      westOverIDL = Math.min(westOverIDL, lonAdjusted);
      eastOverIDL = Math.max(eastOverIDL, lonAdjusted);
    }

    if (east - west > eastOverIDL - westOverIDL) {
      west = westOverIDL;
      east = eastOverIDL;

      if (east > CesiumMath.PI) {
        east = east - CesiumMath.TWO_PI;
      }
      if (west > CesiumMath.PI) {
        west = west - CesiumMath.TWO_PI;
      }
    }

    if (!defined(result)) {
      return new Rectangle(west, south, east, north);
    }

    result.west = west;
    result.south = south;
    result.east = east;
    result.north = north;
    return result;
  };

  /**
   * Duplicates a Rectangle.
   *
   * @param {Rectangle} rectangle The rectangle to clone.
   * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
   * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided. (Returns undefined if rectangle is undefined)
   */
  Rectangle.clone = function (rectangle, result) {
    if (!defined(rectangle)) {
      return undefined;
    }

    if (!defined(result)) {
      return new Rectangle(
        rectangle.west,
        rectangle.south,
        rectangle.east,
        rectangle.north
      );
    }

    result.west = rectangle.west;
    result.south = rectangle.south;
    result.east = rectangle.east;
    result.north = rectangle.north;
    return result;
  };

  /**
   * Compares the provided Rectangles componentwise and returns
   * <code>true</code> if they pass an absolute or relative tolerance test,
   * <code>false</code> otherwise.
   *
   * @param {Rectangle} [left] The first Rectangle.
   * @param {Rectangle} [right] The second Rectangle.
   * @param {Number} [absoluteEpsilon=0] The absolute epsilon tolerance to use for equality testing.
   * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
   */
  Rectangle.equalsEpsilon = function (left, right, absoluteEpsilon) {
    absoluteEpsilon = defaultValue(absoluteEpsilon, 0);

    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        Math.abs(left.west - right.west) <= absoluteEpsilon &&
        Math.abs(left.south - right.south) <= absoluteEpsilon &&
        Math.abs(left.east - right.east) <= absoluteEpsilon &&
        Math.abs(left.north - right.north) <= absoluteEpsilon)
    );
  };

  /**
   * Duplicates this Rectangle.
   *
   * @param {Rectangle} [result] The object onto which to store the result.
   * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
   */
  Rectangle.prototype.clone = function (result) {
    return Rectangle.clone(this, result);
  };

  /**
   * Compares the provided Rectangle with this Rectangle componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Rectangle} [other] The Rectangle to compare.
   * @returns {Boolean} <code>true</code> if the Rectangles are equal, <code>false</code> otherwise.
   */
  Rectangle.prototype.equals = function (other) {
    return Rectangle.equals(this, other);
  };

  /**
   * Compares the provided rectangles and returns <code>true</code> if they are equal,
   * <code>false</code> otherwise.
   *
   * @param {Rectangle} [left] The first Rectangle.
   * @param {Rectangle} [right] The second Rectangle.
   * @returns {Boolean} <code>true</code> if left and right are equal; otherwise <code>false</code>.
   */
  Rectangle.equals = function (left, right) {
    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        left.west === right.west &&
        left.south === right.south &&
        left.east === right.east &&
        left.north === right.north)
    );
  };

  /**
   * Compares the provided Rectangle with this Rectangle componentwise and returns
   * <code>true</code> if they are within the provided epsilon,
   * <code>false</code> otherwise.
   *
   * @param {Rectangle} [other] The Rectangle to compare.
   * @param {Number} [epsilon=0] The epsilon to use for equality testing.
   * @returns {Boolean} <code>true</code> if the Rectangles are within the provided epsilon, <code>false</code> otherwise.
   */
  Rectangle.prototype.equalsEpsilon = function (other, epsilon) {
    return Rectangle.equalsEpsilon(this, other, epsilon);
  };

  /**
   * Checks a Rectangle's properties and throws if they are not in valid ranges.
   *
   * @param {Rectangle} rectangle The rectangle to validate
   *
   * @exception {DeveloperError} <code>north</code> must be in the interval [<code>-Pi/2</code>, <code>Pi/2</code>].
   * @exception {DeveloperError} <code>south</code> must be in the interval [<code>-Pi/2</code>, <code>Pi/2</code>].
   * @exception {DeveloperError} <code>east</code> must be in the interval [<code>-Pi</code>, <code>Pi</code>].
   * @exception {DeveloperError} <code>west</code> must be in the interval [<code>-Pi</code>, <code>Pi</code>].
   */
  Rectangle.validate = function (rectangle) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("rectangle", rectangle);

    const north = rectangle.north;
    Check.typeOf.number.greaterThanOrEquals(
      "north",
      north,
      -CesiumMath.PI_OVER_TWO
    );
    Check.typeOf.number.lessThanOrEquals("north", north, CesiumMath.PI_OVER_TWO);

    const south = rectangle.south;
    Check.typeOf.number.greaterThanOrEquals(
      "south",
      south,
      -CesiumMath.PI_OVER_TWO
    );
    Check.typeOf.number.lessThanOrEquals("south", south, CesiumMath.PI_OVER_TWO);

    const west = rectangle.west;
    Check.typeOf.number.greaterThanOrEquals("west", west, -Math.PI);
    Check.typeOf.number.lessThanOrEquals("west", west, Math.PI);

    const east = rectangle.east;
    Check.typeOf.number.greaterThanOrEquals("east", east, -Math.PI);
    Check.typeOf.number.lessThanOrEquals("east", east, Math.PI);
    //>>includeEnd('debug');
  };

  /**
   * Computes the southwest corner of a rectangle.
   *
   * @param {Rectangle} rectangle The rectangle for which to find the corner
   * @param {Cartographic} [result] The object onto which to store the result.
   * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
   */
  Rectangle.southwest = function (rectangle, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("rectangle", rectangle);
    //>>includeEnd('debug');

    if (!defined(result)) {
      return new Cartographic(rectangle.west, rectangle.south);
    }
    result.longitude = rectangle.west;
    result.latitude = rectangle.south;
    result.height = 0.0;
    return result;
  };

  /**
   * Computes the northwest corner of a rectangle.
   *
   * @param {Rectangle} rectangle The rectangle for which to find the corner
   * @param {Cartographic} [result] The object onto which to store the result.
   * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
   */
  Rectangle.northwest = function (rectangle, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("rectangle", rectangle);
    //>>includeEnd('debug');

    if (!defined(result)) {
      return new Cartographic(rectangle.west, rectangle.north);
    }
    result.longitude = rectangle.west;
    result.latitude = rectangle.north;
    result.height = 0.0;
    return result;
  };

  /**
   * Computes the northeast corner of a rectangle.
   *
   * @param {Rectangle} rectangle The rectangle for which to find the corner
   * @param {Cartographic} [result] The object onto which to store the result.
   * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
   */
  Rectangle.northeast = function (rectangle, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("rectangle", rectangle);
    //>>includeEnd('debug');

    if (!defined(result)) {
      return new Cartographic(rectangle.east, rectangle.north);
    }
    result.longitude = rectangle.east;
    result.latitude = rectangle.north;
    result.height = 0.0;
    return result;
  };

  /**
   * Computes the southeast corner of a rectangle.
   *
   * @param {Rectangle} rectangle The rectangle for which to find the corner
   * @param {Cartographic} [result] The object onto which to store the result.
   * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
   */
  Rectangle.southeast = function (rectangle, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("rectangle", rectangle);
    //>>includeEnd('debug');

    if (!defined(result)) {
      return new Cartographic(rectangle.east, rectangle.south);
    }
    result.longitude = rectangle.east;
    result.latitude = rectangle.south;
    result.height = 0.0;
    return result;
  };

  /**
   * Computes the center of a rectangle.
   *
   * @param {Rectangle} rectangle The rectangle for which to find the center
   * @param {Cartographic} [result] The object onto which to store the result.
   * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
   */
  Rectangle.center = function (rectangle, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("rectangle", rectangle);
    //>>includeEnd('debug');

    let east = rectangle.east;
    const west = rectangle.west;

    if (east < west) {
      east += CesiumMath.TWO_PI;
    }

    const longitude = CesiumMath.negativePiToPi((west + east) * 0.5);
    const latitude = (rectangle.south + rectangle.north) * 0.5;

    if (!defined(result)) {
      return new Cartographic(longitude, latitude);
    }

    result.longitude = longitude;
    result.latitude = latitude;
    result.height = 0.0;
    return result;
  };

  /**
   * Computes the intersection of two rectangles.  This function assumes that the rectangle's coordinates are
   * latitude and longitude in radians and produces a correct intersection, taking into account the fact that
   * the same angle can be represented with multiple values as well as the wrapping of longitude at the
   * anti-meridian.  For a simple intersection that ignores these factors and can be used with projected
   * coordinates, see {@link Rectangle.simpleIntersection}.
   *
   * @param {Rectangle} rectangle On rectangle to find an intersection
   * @param {Rectangle} otherRectangle Another rectangle to find an intersection
   * @param {Rectangle} [result] The object onto which to store the result.
   * @returns {Rectangle|undefined} The modified result parameter, a new Rectangle instance if none was provided or undefined if there is no intersection.
   */
  Rectangle.intersection = function (rectangle, otherRectangle, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("rectangle", rectangle);
    Check.typeOf.object("otherRectangle", otherRectangle);
    //>>includeEnd('debug');

    let rectangleEast = rectangle.east;
    let rectangleWest = rectangle.west;

    let otherRectangleEast = otherRectangle.east;
    let otherRectangleWest = otherRectangle.west;

    if (rectangleEast < rectangleWest && otherRectangleEast > 0.0) {
      rectangleEast += CesiumMath.TWO_PI;
    } else if (otherRectangleEast < otherRectangleWest && rectangleEast > 0.0) {
      otherRectangleEast += CesiumMath.TWO_PI;
    }

    if (rectangleEast < rectangleWest && otherRectangleWest < 0.0) {
      otherRectangleWest += CesiumMath.TWO_PI;
    } else if (otherRectangleEast < otherRectangleWest && rectangleWest < 0.0) {
      rectangleWest += CesiumMath.TWO_PI;
    }

    const west = CesiumMath.negativePiToPi(
      Math.max(rectangleWest, otherRectangleWest)
    );
    const east = CesiumMath.negativePiToPi(
      Math.min(rectangleEast, otherRectangleEast)
    );

    if (
      (rectangle.west < rectangle.east ||
        otherRectangle.west < otherRectangle.east) &&
      east <= west
    ) {
      return undefined;
    }

    const south = Math.max(rectangle.south, otherRectangle.south);
    const north = Math.min(rectangle.north, otherRectangle.north);

    if (south >= north) {
      return undefined;
    }

    if (!defined(result)) {
      return new Rectangle(west, south, east, north);
    }
    result.west = west;
    result.south = south;
    result.east = east;
    result.north = north;
    return result;
  };

  /**
   * Computes a simple intersection of two rectangles.  Unlike {@link Rectangle.intersection}, this function
   * does not attempt to put the angular coordinates into a consistent range or to account for crossing the
   * anti-meridian.  As such, it can be used for rectangles where the coordinates are not simply latitude
   * and longitude (i.e. projected coordinates).
   *
   * @param {Rectangle} rectangle On rectangle to find an intersection
   * @param {Rectangle} otherRectangle Another rectangle to find an intersection
   * @param {Rectangle} [result] The object onto which to store the result.
   * @returns {Rectangle|undefined} The modified result parameter, a new Rectangle instance if none was provided or undefined if there is no intersection.
   */
  Rectangle.simpleIntersection = function (rectangle, otherRectangle, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("rectangle", rectangle);
    Check.typeOf.object("otherRectangle", otherRectangle);
    //>>includeEnd('debug');

    const west = Math.max(rectangle.west, otherRectangle.west);
    const south = Math.max(rectangle.south, otherRectangle.south);
    const east = Math.min(rectangle.east, otherRectangle.east);
    const north = Math.min(rectangle.north, otherRectangle.north);

    if (south >= north || west >= east) {
      return undefined;
    }

    if (!defined(result)) {
      return new Rectangle(west, south, east, north);
    }

    result.west = west;
    result.south = south;
    result.east = east;
    result.north = north;
    return result;
  };

  /**
   * Computes a rectangle that is the union of two rectangles.
   *
   * @param {Rectangle} rectangle A rectangle to enclose in rectangle.
   * @param {Rectangle} otherRectangle A rectangle to enclose in a rectangle.
   * @param {Rectangle} [result] The object onto which to store the result.
   * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
   */
  Rectangle.union = function (rectangle, otherRectangle, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("rectangle", rectangle);
    Check.typeOf.object("otherRectangle", otherRectangle);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Rectangle();
    }

    let rectangleEast = rectangle.east;
    let rectangleWest = rectangle.west;

    let otherRectangleEast = otherRectangle.east;
    let otherRectangleWest = otherRectangle.west;

    if (rectangleEast < rectangleWest && otherRectangleEast > 0.0) {
      rectangleEast += CesiumMath.TWO_PI;
    } else if (otherRectangleEast < otherRectangleWest && rectangleEast > 0.0) {
      otherRectangleEast += CesiumMath.TWO_PI;
    }

    if (rectangleEast < rectangleWest && otherRectangleWest < 0.0) {
      otherRectangleWest += CesiumMath.TWO_PI;
    } else if (otherRectangleEast < otherRectangleWest && rectangleWest < 0.0) {
      rectangleWest += CesiumMath.TWO_PI;
    }

    const west = CesiumMath.negativePiToPi(
      Math.min(rectangleWest, otherRectangleWest)
    );
    const east = CesiumMath.negativePiToPi(
      Math.max(rectangleEast, otherRectangleEast)
    );

    result.west = west;
    result.south = Math.min(rectangle.south, otherRectangle.south);
    result.east = east;
    result.north = Math.max(rectangle.north, otherRectangle.north);

    return result;
  };

  /**
   * Computes a rectangle by enlarging the provided rectangle until it contains the provided cartographic.
   *
   * @param {Rectangle} rectangle A rectangle to expand.
   * @param {Cartographic} cartographic A cartographic to enclose in a rectangle.
   * @param {Rectangle} [result] The object onto which to store the result.
   * @returns {Rectangle} The modified result parameter or a new Rectangle instance if one was not provided.
   */
  Rectangle.expand = function (rectangle, cartographic, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("rectangle", rectangle);
    Check.typeOf.object("cartographic", cartographic);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Rectangle();
    }

    result.west = Math.min(rectangle.west, cartographic.longitude);
    result.south = Math.min(rectangle.south, cartographic.latitude);
    result.east = Math.max(rectangle.east, cartographic.longitude);
    result.north = Math.max(rectangle.north, cartographic.latitude);

    return result;
  };

  /**
   * Returns true if the cartographic is on or inside the rectangle, false otherwise.
   *
   * @param {Rectangle} rectangle The rectangle
   * @param {Cartographic} cartographic The cartographic to test.
   * @returns {Boolean} true if the provided cartographic is inside the rectangle, false otherwise.
   */
  Rectangle.contains = function (rectangle, cartographic) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("rectangle", rectangle);
    Check.typeOf.object("cartographic", cartographic);
    //>>includeEnd('debug');

    let longitude = cartographic.longitude;
    const latitude = cartographic.latitude;

    const west = rectangle.west;
    let east = rectangle.east;

    if (east < west) {
      east += CesiumMath.TWO_PI;
      if (longitude < 0.0) {
        longitude += CesiumMath.TWO_PI;
      }
    }
    return (
      (longitude > west ||
        CesiumMath.equalsEpsilon(longitude, west, CesiumMath.EPSILON14)) &&
      (longitude < east ||
        CesiumMath.equalsEpsilon(longitude, east, CesiumMath.EPSILON14)) &&
      latitude >= rectangle.south &&
      latitude <= rectangle.north
    );
  };

  const subsampleLlaScratch = new Cartographic();
  /**
   * Samples a rectangle so that it includes a list of Cartesian points suitable for passing to
   * {@link BoundingSphere#fromPoints}.  Sampling is necessary to account
   * for rectangles that cover the poles or cross the equator.
   *
   * @param {Rectangle} rectangle The rectangle to subsample.
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid to use.
   * @param {Number} [surfaceHeight=0.0] The height of the rectangle above the ellipsoid.
   * @param {Cartesian3[]} [result] The array of Cartesians onto which to store the result.
   * @returns {Cartesian3[]} The modified result parameter or a new Array of Cartesians instances if none was provided.
   */
  Rectangle.subsample = function (rectangle, ellipsoid, surfaceHeight, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("rectangle", rectangle);
    //>>includeEnd('debug');

    ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
    surfaceHeight = defaultValue(surfaceHeight, 0.0);

    if (!defined(result)) {
      result = [];
    }
    let length = 0;

    const north = rectangle.north;
    const south = rectangle.south;
    const east = rectangle.east;
    const west = rectangle.west;

    const lla = subsampleLlaScratch;
    lla.height = surfaceHeight;

    lla.longitude = west;
    lla.latitude = north;
    result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
    length++;

    lla.longitude = east;
    result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
    length++;

    lla.latitude = south;
    result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
    length++;

    lla.longitude = west;
    result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
    length++;

    if (north < 0.0) {
      lla.latitude = north;
    } else if (south > 0.0) {
      lla.latitude = south;
    } else {
      lla.latitude = 0.0;
    }

    for (let i = 1; i < 8; ++i) {
      lla.longitude = -Math.PI + i * CesiumMath.PI_OVER_TWO;
      if (Rectangle.contains(rectangle, lla)) {
        result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
        length++;
      }
    }

    if (lla.latitude === 0.0) {
      lla.longitude = west;
      result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
      length++;
      lla.longitude = east;
      result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
      length++;
    }
    result.length = length;
    return result;
  };

  /**
   * Computes a subsection of a rectangle from normalized coordinates in the range [0.0, 1.0].
   *
   * @param {Rectangle} rectangle The rectangle to subsection.
   * @param {Number} westLerp The west interpolation factor in the range [0.0, 1.0]. Must be less than or equal to eastLerp.
   * @param {Number} southLerp The south interpolation factor in the range [0.0, 1.0]. Must be less than or equal to northLerp.
   * @param {Number} eastLerp The east interpolation factor in the range [0.0, 1.0]. Must be greater than or equal to westLerp.
   * @param {Number} northLerp The north interpolation factor in the range [0.0, 1.0]. Must be greater than or equal to southLerp.
   * @param {Rectangle} [result] The object onto which to store the result.
   * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
   */
  Rectangle.subsection = function (
    rectangle,
    westLerp,
    southLerp,
    eastLerp,
    northLerp,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("rectangle", rectangle);
    Check.typeOf.number.greaterThanOrEquals("westLerp", westLerp, 0.0);
    Check.typeOf.number.lessThanOrEquals("westLerp", westLerp, 1.0);
    Check.typeOf.number.greaterThanOrEquals("southLerp", southLerp, 0.0);
    Check.typeOf.number.lessThanOrEquals("southLerp", southLerp, 1.0);
    Check.typeOf.number.greaterThanOrEquals("eastLerp", eastLerp, 0.0);
    Check.typeOf.number.lessThanOrEquals("eastLerp", eastLerp, 1.0);
    Check.typeOf.number.greaterThanOrEquals("northLerp", northLerp, 0.0);
    Check.typeOf.number.lessThanOrEquals("northLerp", northLerp, 1.0);

    Check.typeOf.number.lessThanOrEquals("westLerp", westLerp, eastLerp);
    Check.typeOf.number.lessThanOrEquals("southLerp", southLerp, northLerp);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Rectangle();
    }

    // This function doesn't use CesiumMath.lerp because it has floating point precision problems
    // when the start and end values are the same but the t changes.

    if (rectangle.west <= rectangle.east) {
      const width = rectangle.east - rectangle.west;
      result.west = rectangle.west + westLerp * width;
      result.east = rectangle.west + eastLerp * width;
    } else {
      const width = CesiumMath.TWO_PI + rectangle.east - rectangle.west;
      result.west = CesiumMath.negativePiToPi(rectangle.west + westLerp * width);
      result.east = CesiumMath.negativePiToPi(rectangle.west + eastLerp * width);
    }
    const height = rectangle.north - rectangle.south;
    result.south = rectangle.south + southLerp * height;
    result.north = rectangle.south + northLerp * height;

    // Fix floating point precision problems when t = 1
    if (westLerp === 1.0) {
      result.west = rectangle.east;
    }
    if (eastLerp === 1.0) {
      result.east = rectangle.east;
    }
    if (southLerp === 1.0) {
      result.south = rectangle.north;
    }
    if (northLerp === 1.0) {
      result.north = rectangle.north;
    }

    return result;
  };

  /**
   * The largest possible rectangle.
   *
   * @type {Rectangle}
   * @constant
   */
  Rectangle.MAX_VALUE = Object.freeze(
    new Rectangle(
      -Math.PI,
      -CesiumMath.PI_OVER_TWO,
      Math.PI,
      CesiumMath.PI_OVER_TWO
    )
  );

  /**
   * 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 = Cartesian3.clone(defaultValue(center, Cartesian3.ZERO));

    /**
     * The radius of the sphere.
     * @type {Number}
     * @default 0.0
     */
    this.radius = defaultValue(radius, 0.0);
  }

  const fromPointsXMin = new Cartesian3();
  const fromPointsYMin = new Cartesian3();
  const fromPointsZMin = new Cartesian3();
  const fromPointsXMax = new Cartesian3();
  const fromPointsYMax = new Cartesian3();
  const fromPointsZMax = new Cartesian3();
  const fromPointsCurrentPos = new Cartesian3();
  const fromPointsScratch = new Cartesian3();
  const fromPointsRitterCenter = new Cartesian3();
  const fromPointsMinBoxPt = new Cartesian3();
  const fromPointsMaxBoxPt = new Cartesian3();
  const fromPointsNaiveCenterScratch = new Cartesian3();
  const volumeConstant = (4.0 / 3.0) * 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 <code>x</code>, <code>y</code>, and <code>z</code> 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 (!defined(result)) {
      result = new BoundingSphere();
    }

    if (!defined(positions) || positions.length === 0) {
      result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
      result.radius = 0.0;
      return result;
    }

    const currentPos = Cartesian3.clone(positions[0], fromPointsCurrentPos);

    const xMin = Cartesian3.clone(currentPos, fromPointsXMin);
    const yMin = Cartesian3.clone(currentPos, fromPointsYMin);
    const zMin = Cartesian3.clone(currentPos, fromPointsZMin);

    const xMax = Cartesian3.clone(currentPos, fromPointsXMax);
    const yMax = Cartesian3.clone(currentPos, fromPointsYMax);
    const zMax = Cartesian3.clone(currentPos, fromPointsZMax);

    const numPositions = positions.length;
    let i;
    for (i = 1; i < numPositions; i++) {
      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) {
        Cartesian3.clone(currentPos, xMin);
      }

      if (x > xMax.x) {
        Cartesian3.clone(currentPos, xMax);
      }

      if (y < yMin.y) {
        Cartesian3.clone(currentPos, yMin);
      }

      if (y > yMax.y) {
        Cartesian3.clone(currentPos, yMax);
      }

      if (z < zMin.z) {
        Cartesian3.clone(currentPos, zMin);
      }

      if (z > zMax.z) {
        Cartesian3.clone(currentPos, zMax);
      }
    }

    // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
    const xSpan = Cartesian3.magnitudeSquared(
      Cartesian3.subtract(xMax, xMin, fromPointsScratch)
    );
    const ySpan = Cartesian3.magnitudeSquared(
      Cartesian3.subtract(yMax, yMin, fromPointsScratch)
    );
    const zSpan = Cartesian3.magnitudeSquared(
      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 = Cartesian3.magnitudeSquared(
      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 = 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++) {
      Cartesian3.clone(positions[i], currentPos);

      // Find the furthest point from the naive center to calculate the naive radius.
      const r = Cartesian3.magnitude(
        Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch)
      );
      if (r > naiveRadius) {
        naiveRadius = r;
      }

      // Make adjustments to the Ritter Sphere to include all points.
      const oldCenterToPointSquared = Cartesian3.magnitudeSquared(
        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) {
      Cartesian3.clone(ritterCenter, result.center);
      result.radius = ritterRadius;
    } else {
      Cartesian3.clone(naiveCenter, result.center);
      result.radius = naiveRadius;
    }

    return result;
  };

  const defaultProjection$1 = new GeographicProjection();
  const fromRectangle2DLowerLeft = new Cartesian3();
  const fromRectangle2DUpperRight = new Cartesian3();
  const fromRectangle2DSouthwest = new Cartographic();
  const fromRectangle2DNortheast = new 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 (!defined(result)) {
      result = new BoundingSphere();
    }

    if (!defined(rectangle)) {
      result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
      result.radius = 0.0;
      return result;
    }

    projection = defaultValue(projection, defaultProjection$1);

    Rectangle.southwest(rectangle, fromRectangle2DSouthwest);
    fromRectangle2DSouthwest.height = minimumHeight;
    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 = defaultValue(ellipsoid, Ellipsoid.WGS84);
    surfaceHeight = defaultValue(surfaceHeight, 0.0);

    if (!defined(result)) {
      result = new BoundingSphere();
    }

    if (!defined(rectangle)) {
      result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
      result.radius = 0.0;
      return result;
    }

    const positions = 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 (!defined(result)) {
      result = new BoundingSphere();
    }

    if (!defined(positions) || positions.length === 0) {
      result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
      result.radius = 0.0;
      return result;
    }

    center = defaultValue(center, Cartesian3.ZERO);

    stride = defaultValue(stride, 3);

    //>>includeStart('debug', pragmas.debug);
    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 = Cartesian3.clone(currentPos, fromPointsXMin);
    const yMin = Cartesian3.clone(currentPos, fromPointsYMin);
    const zMin = Cartesian3.clone(currentPos, fromPointsZMin);

    const xMax = Cartesian3.clone(currentPos, fromPointsXMax);
    const yMax = Cartesian3.clone(currentPos, fromPointsYMax);
    const zMax = 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) {
        Cartesian3.clone(currentPos, xMin);
      }

      if (x > xMax.x) {
        Cartesian3.clone(currentPos, xMax);
      }

      if (y < yMin.y) {
        Cartesian3.clone(currentPos, yMin);
      }

      if (y > yMax.y) {
        Cartesian3.clone(currentPos, yMax);
      }

      if (z < zMin.z) {
        Cartesian3.clone(currentPos, zMin);
      }

      if (z > zMax.z) {
        Cartesian3.clone(currentPos, zMax);
      }
    }

    // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
    const xSpan = Cartesian3.magnitudeSquared(
      Cartesian3.subtract(xMax, xMin, fromPointsScratch)
    );
    const ySpan = Cartesian3.magnitudeSquared(
      Cartesian3.subtract(yMax, yMin, fromPointsScratch)
    );
    const zSpan = Cartesian3.magnitudeSquared(
      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 = Cartesian3.magnitudeSquared(
      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 = 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 = Cartesian3.magnitude(
        Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch)
      );
      if (r > naiveRadius) {
        naiveRadius = r;
      }

      // Make adjustments to the Ritter Sphere to include all points.
      const oldCenterToPointSquared = Cartesian3.magnitudeSquared(
        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) {
      Cartesian3.clone(ritterCenter, result.center);
      result.radius = ritterRadius;
    } else {
      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 (!defined(result)) {
      result = new BoundingSphere();
    }

    if (
      !defined(positionsHigh) ||
      !defined(positionsLow) ||
      positionsHigh.length !== positionsLow.length ||
      positionsHigh.length === 0
    ) {
      result.center = Cartesian3.clone(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 = Cartesian3.clone(currentPos, fromPointsXMin);
    const yMin = Cartesian3.clone(currentPos, fromPointsYMin);
    const zMin = Cartesian3.clone(currentPos, fromPointsZMin);

    const xMax = Cartesian3.clone(currentPos, fromPointsXMax);
    const yMax = Cartesian3.clone(currentPos, fromPointsYMax);
    const zMax = 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) {
        Cartesian3.clone(currentPos, xMin);
      }

      if (x > xMax.x) {
        Cartesian3.clone(currentPos, xMax);
      }

      if (y < yMin.y) {
        Cartesian3.clone(currentPos, yMin);
      }

      if (y > yMax.y) {
        Cartesian3.clone(currentPos, yMax);
      }

      if (z < zMin.z) {
        Cartesian3.clone(currentPos, zMin);
      }

      if (z > zMax.z) {
        Cartesian3.clone(currentPos, zMax);
      }
    }

    // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
    const xSpan = Cartesian3.magnitudeSquared(
      Cartesian3.subtract(xMax, xMin, fromPointsScratch)
    );
    const ySpan = Cartesian3.magnitudeSquared(
      Cartesian3.subtract(yMax, yMin, fromPointsScratch)
    );
    const zSpan = Cartesian3.magnitudeSquared(
      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 = Cartesian3.magnitudeSquared(
      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 = 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 = Cartesian3.magnitude(
        Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch)
      );
      if (r > naiveRadius) {
        naiveRadius = r;
      }

      // Make adjustments to the Ritter Sphere to include all points.
      const oldCenterToPointSquared = Cartesian3.magnitudeSquared(
        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) {
      Cartesian3.clone(ritterCenter, result.center);
      result.radius = ritterRadius;
    } else {
      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
   * tightly and fully encompasses 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);
    Check.typeOf.object("corner", corner);
    Check.typeOf.object("oppositeCorner", oppositeCorner);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new BoundingSphere();
    }

    const center = Cartesian3.midpoint(corner, oppositeCorner, result.center);
    result.radius = 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);
    Check.typeOf.object("ellipsoid", ellipsoid);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new BoundingSphere();
    }

    Cartesian3.clone(Cartesian3.ZERO, result.center);
    result.radius = ellipsoid.maximumRadius;
    return result;
  };

  const fromBoundingSpheresScratch = new 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 (!defined(result)) {
      result = new BoundingSphere();
    }

    if (!defined(boundingSpheres) || boundingSpheres.length === 0) {
      result.center = Cartesian3.clone(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,
        Cartesian3.distance(center, tmp.center, fromBoundingSpheresScratch) +
          tmp.radius
      );
    }
    result.radius = radius;

    return result;
  };

  const fromOrientedBoundingBoxScratchU = new Cartesian3();
  const fromOrientedBoundingBoxScratchV = new Cartesian3();
  const fromOrientedBoundingBoxScratchW = new 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);
    Check.defined("orientedBoundingBox", orientedBoundingBox);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new BoundingSphere();
    }

    const halfAxes = orientedBoundingBox.halfAxes;
    const u = Matrix3.getColumn(halfAxes, 0, fromOrientedBoundingBoxScratchU);
    const v = Matrix3.getColumn(halfAxes, 1, fromOrientedBoundingBoxScratchV);
    const w = Matrix3.getColumn(halfAxes, 2, fromOrientedBoundingBoxScratchW);

    Cartesian3.add(u, v, u);
    Cartesian3.add(u, w, u);

    result.center = Cartesian3.clone(orientedBoundingBox.center, result.center);
    result.radius = Cartesian3.magnitude(u);

    return result;
  };

  const scratchFromTransformationCenter = new Cartesian3();
  const scratchFromTransformationScale = new 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);
    Check.typeOf.object("transformation", transformation);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new BoundingSphere();
    }

    const center = Matrix4.getTranslation(
      transformation,
      scratchFromTransformationCenter
    );
    const scale = Matrix4.getScale(
      transformation,
      scratchFromTransformationScale
    );
    const radius = 0.5 * Cartesian3.magnitude(scale);
    result.center = 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 (!defined(sphere)) {
      return undefined;
    }

    if (!defined(result)) {
      return new BoundingSphere(sphere.center, sphere.radius);
    }

    result.center = 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);
    Check.typeOf.object("value", value);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = 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);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    if (!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 Cartesian3();
  const unionScratchCenter = new 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);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new BoundingSphere();
    }

    const leftCenter = left.center;
    const leftRadius = left.radius;
    const rightCenter = right.center;
    const rightRadius = right.radius;

    const toRightCenter = Cartesian3.subtract(
      rightCenter,
      leftCenter,
      unionScratch
    );
    const centerSeparation = 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 = Cartesian3.multiplyByScalar(
      toRightCenter,
      (-leftRadius + halfDistanceBetweenTangentPoints) / centerSeparation,
      unionScratchCenter
    );
    Cartesian3.add(center, leftCenter, center);
    Cartesian3.clone(center, result.center);
    result.radius = halfDistanceBetweenTangentPoints;

    return result;
  };

  const expandScratch = new 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);
    Check.typeOf.object("sphere", sphere);
    Check.typeOf.object("point", point);
    //>>includeEnd('debug');

    result = BoundingSphere.clone(sphere, result);

    const radius = Cartesian3.magnitude(
      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);
    Check.typeOf.object("sphere", sphere);
    Check.typeOf.object("plane", plane);
    //>>includeEnd('debug');

    const center = sphere.center;
    const radius = sphere.radius;
    const normal = plane.normal;
    const distanceToPlane = 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);
    Check.typeOf.object("sphere", sphere);
    Check.typeOf.object("transform", transform);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new BoundingSphere();
    }

    result.center = Matrix4.multiplyByPoint(
      transform,
      sphere.center,
      result.center
    );
    result.radius = Matrix4.getMaximumScale(transform) * sphere.radius;

    return result;
  };

  const distanceSquaredToScratch = new 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);
    Check.typeOf.object("sphere", sphere);
    Check.typeOf.object("cartesian", cartesian);
    //>>includeEnd('debug');

    const diff = Cartesian3.subtract(
      sphere.center,
      cartesian,
      distanceSquaredToScratch
    );

    const distance = 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);
    Check.typeOf.object("sphere", sphere);
    Check.typeOf.object("transform", transform);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new BoundingSphere();
    }

    result.center = Matrix4.multiplyByPoint(
      transform,
      sphere.center,
      result.center
    );
    result.radius = sphere.radius;

    return result;
  };

  const scratchCartesian3$d = new 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.
   * <br>
   * 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);
    Check.typeOf.object("sphere", sphere);
    Check.typeOf.object("position", position);
    Check.typeOf.object("direction", direction);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Interval();
    }

    const toCenter = Cartesian3.subtract(
      sphere.center,
      position,
      scratchCartesian3$d
    );
    const mag = Cartesian3.dot(direction, toCenter);

    result.start = mag - sphere.radius;
    result.stop = mag + sphere.radius;
    return result;
  };

  const projectTo2DNormalScratch = new Cartesian3();
  const projectTo2DEastScratch = new Cartesian3();
  const projectTo2DNorthScratch = new Cartesian3();
  const projectTo2DWestScratch = new Cartesian3();
  const projectTo2DSouthScratch = new Cartesian3();
  const projectTo2DCartographicScratch = new Cartographic();
  const projectTo2DPositionsScratch = new Array(8);
  for (let n = 0; n < 8; ++n) {
    projectTo2DPositionsScratch[n] = new 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);
    Check.typeOf.object("sphere", sphere);
    //>>includeEnd('debug');

    projection = defaultValue(projection, projectTo2DProjection);

    const ellipsoid = projection.ellipsoid;
    let center = sphere.center;
    const radius = sphere.radius;

    let normal;
    if (Cartesian3.equals(center, 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 = Cartesian3.clone(Cartesian3.UNIT_X, projectTo2DNormalScratch);
    } else {
      normal = ellipsoid.geodeticSurfaceNormal(center, projectTo2DNormalScratch);
    }
    const east = Cartesian3.cross(
      Cartesian3.UNIT_Z,
      normal,
      projectTo2DEastScratch
    );
    Cartesian3.normalize(east, east);
    const north = Cartesian3.cross(normal, east, projectTo2DNorthScratch);
    Cartesian3.normalize(north, north);

    Cartesian3.multiplyByScalar(normal, radius, normal);
    Cartesian3.multiplyByScalar(north, radius, north);
    Cartesian3.multiplyByScalar(east, radius, east);

    const south = Cartesian3.negate(north, projectTo2DSouthScratch);
    const west = Cartesian3.negate(east, projectTo2DWestScratch);

    const positions = projectTo2DPositionsScratch;

    // top NE corner
    let corner = positions[0];
    Cartesian3.add(normal, north, corner);
    Cartesian3.add(corner, east, corner);

    // top NW corner
    corner = positions[1];
    Cartesian3.add(normal, north, corner);
    Cartesian3.add(corner, west, corner);

    // top SW corner
    corner = positions[2];
    Cartesian3.add(normal, south, corner);
    Cartesian3.add(corner, west, corner);

    // top SE corner
    corner = positions[3];
    Cartesian3.add(normal, south, corner);
    Cartesian3.add(corner, east, corner);

    Cartesian3.negate(normal, normal);

    // bottom NE corner
    corner = positions[4];
    Cartesian3.add(normal, north, corner);
    Cartesian3.add(corner, east, corner);

    // bottom NW corner
    corner = positions[5];
    Cartesian3.add(normal, north, corner);
    Cartesian3.add(corner, west, corner);

    // bottom SW corner
    corner = positions[6];
    Cartesian3.add(normal, south, corner);
    Cartesian3.add(corner, west, corner);

    // bottom SE corner
    corner = positions[7];
    Cartesian3.add(normal, south, corner);
    Cartesian3.add(corner, east, corner);

    const length = positions.length;
    for (let i = 0; i < length; ++i) {
      const position = positions[i];
      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} <code>true</code> if the sphere is not visible; otherwise <code>false</code>.
   */
  BoundingSphere.isOccluded = function (sphere, occluder) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("sphere", sphere);
    Check.typeOf.object("occluder", occluder);
    //>>includeEnd('debug');
    return !occluder.isBoundingSphereVisible(sphere);
  };

  /**
   * Compares the provided BoundingSphere componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {BoundingSphere} [left] The first BoundingSphere.
   * @param {BoundingSphere} [right] The second BoundingSphere.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  BoundingSphere.equals = function (left, right) {
    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        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.
   * <br>
   * 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} <code>true</code> if the sphere is not visible; otherwise <code>false</code>.
   */
  BoundingSphere.prototype.isOccluded = function (occluder) {
    return BoundingSphere.isOccluded(this, occluder);
  };

  /**
   * Compares this BoundingSphere against the provided BoundingSphere componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {BoundingSphere} [right] The right hand side BoundingSphere.
   * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> 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;
  };

  /* This file is automatically rebuilt by the Cesium build process. */
  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};

  function createCommonjsModule(fn, basedir, module) {
  	return module = {
  		path: basedir,
  		exports: {},
  		require: function (path, base) {
  			return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
  		}
  	}, fn(module, module.exports), module.exports;
  }

  function commonjsRequire () {
  	throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
  }

  /* This file is automatically rebuilt by the Cesium build process. */

  var punycode = createCommonjsModule(function (module, exports) {
  (function(root) {

  	/** Detect free variables */
  	var freeExports = exports &&
  		!exports.nodeType && exports;
  	var freeModule = module &&
  		!module.nodeType && module;
  	var freeGlobal = typeof commonjsGlobal == 'object' && 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 <https://mathiasbynens.be/notes/javascript-encoding>
  	 * @memberOf punycode.ucs2
  	 * @name decode
  	 * @param {String} string The Unicode input string (UCS-2).
  	 * @returns {Array} The new array of code points.
  	 */
  	function ucs2decode(string) {
  		var output = [],
  		    counter = 0,
  		    length = string.length,
  		    value,
  		    extra;
  		while (counter < length) {
  			value = string.charCodeAt(counter++);
  			if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  				// high surrogate, and there is a next character
  				extra = string.charCodeAt(counter++);
  				if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  					output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  				} else {
  					// unmatched surrogate; only append this code unit, in case the next
  					// code unit is the high surrogate of a surrogate pair
  					output.push(value);
  					counter--;
  				}
  			} else {
  				output.push(value);
  			}
  		}
  		return output;
  	}

  	/**
  	 * Creates a string based on an array of numeric code points.
  	 * @see `punycode.ucs2.decode`
  	 * @memberOf punycode.ucs2
  	 * @name encode
  	 * @param {Array} codePoints The array of numeric code points.
  	 * @returns {String} The new Unicode string (UCS-2).
  	 */
  	function ucs2encode(array) {
  		return map(array, function(value) {
  			var output = '';
  			if (value > 0xFFFF) {
  				value -= 0x10000;
  				output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  				value = 0xDC00 | value & 0x3FF;
  			}
  			output += stringFromCharCode(value);
  			return output;
  		}).join('');
  	}

  	/**
  	 * Converts a basic code point into a digit/integer.
  	 * @see `digitToBasic()`
  	 * @private
  	 * @param {Number} codePoint The basic numeric code point value.
  	 * @returns {Number} The numeric value of a basic code point (for use in
  	 * representing integers) in the range `0` to `base - 1`, or `base` if
  	 * the code point does not represent a value.
  	 */
  	function basicToDigit(codePoint) {
  		if (codePoint - 48 < 10) {
  			return codePoint - 22;
  		}
  		if (codePoint - 65 < 26) {
  			return codePoint - 65;
  		}
  		if (codePoint - 97 < 26) {
  			return codePoint - 97;
  		}
  		return base;
  	}

  	/**
  	 * Converts a digit/integer into a basic code point.
  	 * @see `basicToDigit()`
  	 * @private
  	 * @param {Number} digit The numeric value of a basic code point.
  	 * @returns {Number} The basic code point whose value (when used for
  	 * representing integers) is `digit`, which needs to be in the range
  	 * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  	 * used; else, the lowercase form is used. The behavior is undefined
  	 * if `flag` is non-zero and `digit` has no uppercase form.
  	 */
  	function digitToBasic(digit, flag) {
  		//  0..25 map to ASCII a..z or A..Z
  		// 26..35 map to ASCII 0..9
  		return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  	}

  	/**
  	 * Bias adaptation function as per section 3.4 of RFC 3492.
  	 * https://tools.ietf.org/html/rfc3492#section-3.4
  	 * @private
  	 */
  	function adapt(delta, numPoints, firstTime) {
  		var k = 0;
  		delta = firstTime ? floor(delta / damp) : delta >> 1;
  		delta += floor(delta / numPoints);
  		for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
  			delta = floor(delta / baseMinusTMin);
  		}
  		return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  	}

  	/**
  	 * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  	 * symbols.
  	 * @memberOf punycode
  	 * @param {String} input The Punycode string of ASCII-only symbols.
  	 * @returns {String} The resulting string of Unicode symbols.
  	 */
  	function decode(input) {
  		// Don't use UCS-2
  		var output = [],
  		    inputLength = input.length,
  		    out,
  		    i = 0,
  		    n = initialN,
  		    bias = initialBias,
  		    basic,
  		    j,
  		    index,
  		    oldi,
  		    w,
  		    k,
  		    digit,
  		    t,
  		    /** Cached calculation results */
  		    baseMinusT;

  		// Handle the basic code points: let `basic` be the number of input code
  		// points before the last delimiter, or `0` if there is none, then copy
  		// the first basic code points to the output.

  		basic = input.lastIndexOf(delimiter);
  		if (basic < 0) {
  			basic = 0;
  		}

  		for (j = 0; j < basic; ++j) {
  			// if it's not a basic code point
  			if (input.charCodeAt(j) >= 0x80) {
  				error('not-basic');
  			}
  			output.push(input.charCodeAt(j));
  		}

  		// Main decoding loop: start just after the last delimiter if any basic code
  		// points were copied; start at the beginning otherwise.

  		for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {

  			// `index` is the index of the next character to be consumed.
  			// Decode a generalized variable-length integer into `delta`,
  			// which gets added to `i`. The overflow checking is easier
  			// if we increase `i` as we go, then subtract off its starting
  			// value at the end to obtain `delta`.
  			for (oldi = i, w = 1, k = base; /* no condition */; k += base) {

  				if (index >= inputLength) {
  					error('invalid-input');
  				}

  				digit = basicToDigit(input.charCodeAt(index++));

  				if (digit >= base || digit > floor((maxInt - i) / w)) {
  					error('overflow');
  				}

  				i += digit * w;
  				t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);

  				if (digit < t) {
  					break;
  				}

  				baseMinusT = base - t;
  				if (w > floor(maxInt / baseMinusT)) {
  					error('overflow');
  				}

  				w *= baseMinusT;

  			}

  			out = output.length + 1;
  			bias = adapt(i - oldi, out, oldi == 0);

  			// `i` was supposed to wrap around from `out` to `0`,
  			// incrementing `n` each time, so we'll fix that now:
  			if (floor(i / out) > maxInt - n) {
  				error('overflow');
  			}

  			n += floor(i / out);
  			i %= out;

  			// Insert `n` at position `i` of the output
  			output.splice(i++, 0, n);

  		}

  		return ucs2encode(output);
  	}

  	/**
  	 * Converts a string of Unicode symbols (e.g. a domain name label) to a
  	 * Punycode string of ASCII-only symbols.
  	 * @memberOf punycode
  	 * @param {String} input The string of Unicode symbols.
  	 * @returns {String} The resulting Punycode string of ASCII-only symbols.
  	 */
  	function encode(input) {
  		var n,
  		    delta,
  		    handledCPCount,
  		    basicLength,
  		    bias,
  		    j,
  		    m,
  		    q,
  		    k,
  		    t,
  		    currentValue,
  		    output = [],
  		    /** `inputLength` will hold the number of code points in `input`. */
  		    inputLength,
  		    /** Cached calculation results */
  		    handledCPCountPlusOne,
  		    baseMinusT,
  		    qMinusT;

  		// Convert the input in UCS-2 to Unicode
  		input = ucs2decode(input);

  		// Cache the length
  		inputLength = input.length;

  		// Initialize the state
  		n = initialN;
  		delta = 0;
  		bias = initialBias;

  		// Handle the basic code points
  		for (j = 0; j < inputLength; ++j) {
  			currentValue = input[j];
  			if (currentValue < 0x80) {
  				output.push(stringFromCharCode(currentValue));
  			}
  		}

  		handledCPCount = basicLength = output.length;

  		// `handledCPCount` is the number of code points that have been handled;
  		// `basicLength` is the number of basic code points.

  		// Finish the basic string - if it is not empty - with a delimiter
  		if (basicLength) {
  			output.push(delimiter);
  		}

  		// Main encoding loop:
  		while (handledCPCount < inputLength) {

  			// All non-basic code points < n have been handled already. Find the next
  			// larger one:
  			for (m = maxInt, j = 0; j < inputLength; ++j) {
  				currentValue = input[j];
  				if (currentValue >= n && currentValue < m) {
  					m = currentValue;
  				}
  			}

  			// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  			// but guard against overflow
  			handledCPCountPlusOne = handledCPCount + 1;
  			if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  				error('overflow');
  			}

  			delta += (m - n) * handledCPCountPlusOne;
  			n = m;

  			for (j = 0; j < inputLength; ++j) {
  				currentValue = input[j];

  				if (currentValue < n && ++delta > maxInt) {
  					error('overflow');
  				}

  				if (currentValue == n) {
  					// Represent delta as a generalized variable-length integer
  					for (q = delta, k = base; /* no condition */; k += base) {
  						t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  						if (q < t) {
  							break;
  						}
  						qMinusT = q - t;
  						baseMinusT = base - t;
  						output.push(
  							stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  						);
  						q = floor(qMinusT / baseMinusT);
  					}

  					output.push(stringFromCharCode(digitToBasic(q, 0)));
  					bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  					delta = 0;
  					++handledCPCount;
  				}
  			}

  			++delta;
  			++n;

  		}
  		return output.join('');
  	}

  	/**
  	 * Converts a Punycode string representing a domain name or an email address
  	 * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
  	 * it doesn't matter if you call it on a string that has already been
  	 * converted to Unicode.
  	 * @memberOf punycode
  	 * @param {String} input The Punycoded domain name or email address to
  	 * convert to Unicode.
  	 * @returns {String} The Unicode representation of the given Punycode
  	 * string.
  	 */
  	function toUnicode(input) {
  		return mapDomain(input, function(string) {
  			return regexPunycode.test(string)
  				? decode(string.slice(4).toLowerCase())
  				: string;
  		});
  	}

  	/**
  	 * Converts a Unicode string representing a domain name or an email address to
  	 * Punycode. Only the non-ASCII parts of the domain name will be converted,
  	 * i.e. it doesn't matter if you call it with a domain that's already in
  	 * ASCII.
  	 * @memberOf punycode
  	 * @param {String} input The domain name or email address to convert, as a
  	 * Unicode string.
  	 * @returns {String} The Punycode representation of the given domain name or
  	 * email address.
  	 */
  	function toASCII(input) {
  		return mapDomain(input, function(string) {
  			return regexNonASCII.test(string)
  				? 'xn--' + encode(string)
  				: string;
  		});
  	}

  	/*--------------------------------------------------------------------------*/

  	/** Define the public API */
  	punycode = {
  		/**
  		 * A string representing the current Punycode.js version number.
  		 * @memberOf punycode
  		 * @type String
  		 */
  		'version': '1.3.2',
  		/**
  		 * An object of methods to convert from JavaScript's internal character
  		 * representation (UCS-2) to Unicode code points, and back.
  		 * @see <https://mathiasbynens.be/notes/javascript-encoding>
  		 * @memberOf punycode
  		 * @type Object
  		 */
  		'ucs2': {
  			'decode': ucs2decode,
  			'encode': ucs2encode
  		},
  		'decode': decode,
  		'encode': encode,
  		'toASCII': toASCII,
  		'toUnicode': toUnicode
  	};

  	/** Expose `punycode` */
  	// Some AMD build optimizers, like r.js, check for specific condition patterns
  	// like the following:
  	if (freeExports && freeModule) {
  		if (module.exports == freeExports) {
  			// in Node.js, io.js, or RingoJS v0.8.0+
  			freeModule.exports = punycode;
  		} else {
  			// in Narwhal or RingoJS v0.7.0-
  			for (key in punycode) {
  				punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  			}
  		}
  	} else {
  		// in Rhino or a web browser
  		root.punycode = punycode;
  	}

  }(commonjsGlobal));
  });

  var IPv6 = createCommonjsModule(function (module) {
  /*!
   * URI.js - Mutating URLs
   * IPv6 Support
   *
   * Version: 1.19.11
   *
   * Author: Rodney Rehm
   * Web: http://medialize.github.io/URI.js/
   *
   * Licensed under
   *   MIT License http://www.opensource.org/licenses/mit-license
   *
   */

  (function (root, factory) {
    // https://github.com/umdjs/umd/blob/master/returnExports.js
    if (module.exports) {
      // Node
      module.exports = factory();
    } else {
      // Browser globals (root is window)
      root.IPv6 = factory(root);
    }
  }(commonjsGlobal, function (root) {

    /*
    var _in = "fe80:0000:0000:0000:0204:61ff:fe9d:f156";
    var _out = IPv6.best(_in);
    var _expected = "fe80::204:61ff:fe9d:f156";

    console.log(_in, _out, _expected, _out === _expected);
    */

    // save current IPv6 variable, if any
    var _IPv6 = root && root.IPv6;

    function bestPresentation(address) {
      // based on:
      // Javascript to test an IPv6 address for proper format, and to
      // present the "best text representation" according to IETF Draft RFC at
      // http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04
      // 8 Feb 2010 Rich Brown, Dartware, LLC
      // Please feel free to use this code as long as you provide a link to
      // http://www.intermapper.com
      // http://intermapper.com/support/tools/IPV6-Validator.aspx
      // http://download.dartware.com/thirdparty/ipv6validator.js

      var _address = address.toLowerCase();
      var segments = _address.split(':');
      var length = segments.length;
      var total = 8;

      // trim colons (:: or ::a:b:c… or …a:b:c::)
      if (segments[0] === '' && segments[1] === '' && segments[2] === '') {
        // must have been ::
        // remove first two items
        segments.shift();
        segments.shift();
      } else if (segments[0] === '' && segments[1] === '') {
        // must have been ::xxxx
        // remove the first item
        segments.shift();
      } else if (segments[length - 1] === '' && segments[length - 2] === '') {
        // must have been xxxx::
        segments.pop();
      }

      length = segments.length;

      // adjust total segments for IPv4 trailer
      if (segments[length - 1].indexOf('.') !== -1) {
        // found a "." which means IPv4
        total = 7;
      }

      // fill empty segments them with "0000"
      var pos;
      for (pos = 0; pos < length; pos++) {
        if (segments[pos] === '') {
          break;
        }
      }

      if (pos < total) {
        segments.splice(pos, 1, '0000');
        while (segments.length < total) {
          segments.splice(pos, 0, '0000');
        }
      }

      // strip leading zeros
      var _segments;
      for (var i = 0; i < total; i++) {
        _segments = segments[i].split('');
        for (var j = 0; j < 3 ; j++) {
          if (_segments[0] === '0' && _segments.length > 1) {
            _segments.splice(0,1);
          } else {
            break;
          }
        }

        segments[i] = _segments.join('');
      }

      // find longest sequence of zeroes and coalesce them into one segment
      var best = -1;
      var _best = 0;
      var _current = 0;
      var current = -1;
      var inzeroes = false;
      // i; already declared

      for (i = 0; i < total; i++) {
        if (inzeroes) {
          if (segments[i] === '0') {
            _current += 1;
          } else {
            inzeroes = false;
            if (_current > _best) {
              best = current;
              _best = _current;
            }
          }
        } else {
          if (segments[i] === '0') {
            inzeroes = true;
            current = i;
            _current = 1;
          }
        }
      }

      if (_current > _best) {
        best = current;
        _best = _current;
      }

      if (_best > 1) {
        segments.splice(best, _best, '');
      }

      length = segments.length;

      // assemble remaining segments
      var result = '';
      if (segments[0] === '')  {
        result = ':';
      }

      for (i = 0; i < length; i++) {
        result += segments[i];
        if (i === length - 1) {
          break;
        }

        result += ':';
      }

      if (segments[length - 1] === '') {
        result += ':';
      }

      return result;
    }

    function noConflict() {
      /*jshint validthis: true */
      if (root.IPv6 === this) {
        root.IPv6 = _IPv6;
      }

      return this;
    }

    return {
      best: bestPresentation,
      noConflict: noConflict
    };
  }));
  });

  var SecondLevelDomains = createCommonjsModule(function (module) {
  /*!
   * URI.js - Mutating URLs
   * Second Level Domain (SLD) Support
   *
   * Version: 1.19.11
   *
   * Author: Rodney Rehm
   * Web: http://medialize.github.io/URI.js/
   *
   * Licensed under
   *   MIT License http://www.opensource.org/licenses/mit-license
   *
   */

  (function (root, factory) {
    // https://github.com/umdjs/umd/blob/master/returnExports.js
    if (module.exports) {
      // Node
      module.exports = factory();
    } else {
      // Browser globals (root is window)
      root.SecondLevelDomains = factory(root);
    }
  }(commonjsGlobal, function (root) {

    // save current SecondLevelDomains variable, if any
    var _SecondLevelDomains = root && root.SecondLevelDomains;

    var SLD = {
      // list of known Second Level Domains
      // converted list of SLDs from https://github.com/gavingmiller/second-level-domains
      // ----
      // publicsuffix.org is more current and actually used by a couple of browsers internally.
      // downside is it also contains domains like "dyndns.org" - which is fine for the security
      // issues browser have to deal with (SOP for cookies, etc) - but is way overboard for URI.js
      // ----
      list: {
        'ac':' com gov mil net org ',
        'ae':' ac co gov mil name net org pro sch ',
        'af':' com edu gov net org ',
        'al':' com edu gov mil net org ',
        'ao':' co ed gv it og pb ',
        'ar':' com edu gob gov int mil net org tur ',
        'at':' ac co gv or ',
        'au':' asn com csiro edu gov id net org ',
        'ba':' co com edu gov mil net org rs unbi unmo unsa untz unze ',
        'bb':' biz co com edu gov info net org store tv ',
        'bh':' biz cc com edu gov info net org ',
        'bn':' com edu gov net org ',
        'bo':' com edu gob gov int mil net org tv ',
        'br':' adm adv agr am arq art ato b bio blog bmd cim cng cnt com coop ecn edu eng esp etc eti far flog fm fnd fot fst g12 ggf gov imb ind inf jor jus lel mat med mil mus net nom not ntr odo org ppg pro psc psi qsl rec slg srv tmp trd tur tv vet vlog wiki zlg ',
        'bs':' com edu gov net org ',
        'bz':' du et om ov rg ',
        'ca':' ab bc mb nb nf nl ns nt nu on pe qc sk yk ',
        'ck':' biz co edu gen gov info net org ',
        'cn':' ac ah bj com cq edu fj gd gov gs gx gz ha hb he hi hl hn jl js jx ln mil net nm nx org qh sc sd sh sn sx tj tw xj xz yn zj ',
        'co':' com edu gov mil net nom org ',
        'cr':' ac c co ed fi go or sa ',
        'cy':' ac biz com ekloges gov ltd name net org parliament press pro tm ',
        'do':' art com edu gob gov mil net org sld web ',
        'dz':' art asso com edu gov net org pol ',
        'ec':' com edu fin gov info med mil net org pro ',
        'eg':' com edu eun gov mil name net org sci ',
        'er':' com edu gov ind mil net org rochest w ',
        'es':' com edu gob nom org ',
        'et':' biz com edu gov info name net org ',
        'fj':' ac biz com info mil name net org pro ',
        'fk':' ac co gov net nom org ',
        'fr':' asso com f gouv nom prd presse tm ',
        'gg':' co net org ',
        'gh':' com edu gov mil org ',
        'gn':' ac com gov net org ',
        'gr':' com edu gov mil net org ',
        'gt':' com edu gob ind mil net org ',
        'gu':' com edu gov net org ',
        'hk':' com edu gov idv net org ',
        'hu':' 2000 agrar bolt casino city co erotica erotika film forum games hotel info ingatlan jogasz konyvelo lakas media news org priv reklam sex shop sport suli szex tm tozsde utazas video ',
        'id':' ac co go mil net or sch web ',
        'il':' ac co gov idf k12 muni net org ',
        'in':' ac co edu ernet firm gen gov i ind mil net nic org res ',
        'iq':' com edu gov i mil net org ',
        'ir':' ac co dnssec gov i id net org sch ',
        'it':' edu gov ',
        'je':' co net org ',
        'jo':' com edu gov mil name net org sch ',
        'jp':' ac ad co ed go gr lg ne or ',
        'ke':' ac co go info me mobi ne or sc ',
        'kh':' com edu gov mil net org per ',
        'ki':' biz com de edu gov info mob net org tel ',
        'km':' asso com coop edu gouv k medecin mil nom notaires pharmaciens presse tm veterinaire ',
        'kn':' edu gov net org ',
        'kr':' ac busan chungbuk chungnam co daegu daejeon es gangwon go gwangju gyeongbuk gyeonggi gyeongnam hs incheon jeju jeonbuk jeonnam k kg mil ms ne or pe re sc seoul ulsan ',
        'kw':' com edu gov net org ',
        'ky':' com edu gov net org ',
        'kz':' com edu gov mil net org ',
        'lb':' com edu gov net org ',
        'lk':' assn com edu gov grp hotel int ltd net ngo org sch soc web ',
        'lr':' com edu gov net org ',
        'lv':' asn com conf edu gov id mil net org ',
        'ly':' com edu gov id med net org plc sch ',
        'ma':' ac co gov m net org press ',
        'mc':' asso tm ',
        'me':' ac co edu gov its net org priv ',
        'mg':' com edu gov mil nom org prd tm ',
        'mk':' com edu gov inf name net org pro ',
        'ml':' com edu gov net org presse ',
        'mn':' edu gov org ',
        'mo':' com edu gov net org ',
        'mt':' com edu gov net org ',
        'mv':' aero biz com coop edu gov info int mil museum name net org pro ',
        'mw':' ac co com coop edu gov int museum net org ',
        'mx':' com edu gob net org ',
        'my':' com edu gov mil name net org sch ',
        'nf':' arts com firm info net other per rec store web ',
        'ng':' biz com edu gov mil mobi name net org sch ',
        'ni':' ac co com edu gob mil net nom org ',
        'np':' com edu gov mil net org ',
        'nr':' biz com edu gov info net org ',
        'om':' ac biz co com edu gov med mil museum net org pro sch ',
        'pe':' com edu gob mil net nom org sld ',
        'ph':' com edu gov i mil net ngo org ',
        'pk':' biz com edu fam gob gok gon gop gos gov net org web ',
        'pl':' art bialystok biz com edu gda gdansk gorzow gov info katowice krakow lodz lublin mil net ngo olsztyn org poznan pwr radom slupsk szczecin torun warszawa waw wroc wroclaw zgora ',
        'pr':' ac biz com edu est gov info isla name net org pro prof ',
        'ps':' com edu gov net org plo sec ',
        'pw':' belau co ed go ne or ',
        'ro':' arts com firm info nom nt org rec store tm www ',
        'rs':' ac co edu gov in org ',
        'sb':' com edu gov net org ',
        'sc':' com edu gov net org ',
        'sh':' co com edu gov net nom org ',
        'sl':' com edu gov net org ',
        'st':' co com consulado edu embaixada gov mil net org principe saotome store ',
        'sv':' com edu gob org red ',
        'sz':' ac co org ',
        'tr':' av bbs bel biz com dr edu gen gov info k12 name net org pol tel tsk tv web ',
        'tt':' aero biz cat co com coop edu gov info int jobs mil mobi museum name net org pro tel travel ',
        'tw':' club com ebiz edu game gov idv mil net org ',
        'mu':' ac co com gov net or org ',
        'mz':' ac co edu gov org ',
        'na':' co com ',
        'nz':' ac co cri geek gen govt health iwi maori mil net org parliament school ',
        'pa':' abo ac com edu gob ing med net nom org sld ',
        'pt':' com edu gov int net nome org publ ',
        'py':' com edu gov mil net org ',
        'qa':' com edu gov mil net org ',
        're':' asso com nom ',
        'ru':' ac adygeya altai amur arkhangelsk astrakhan bashkiria belgorod bir bryansk buryatia cbg chel chelyabinsk chita chukotka chuvashia com dagestan e-burg edu gov grozny int irkutsk ivanovo izhevsk jar joshkar-ola kalmykia kaluga kamchatka karelia kazan kchr kemerovo khabarovsk khakassia khv kirov koenig komi kostroma kranoyarsk kuban kurgan kursk lipetsk magadan mari mari-el marine mil mordovia mosreg msk murmansk nalchik net nnov nov novosibirsk nsk omsk orenburg org oryol penza perm pp pskov ptz rnd ryazan sakhalin samara saratov simbirsk smolensk spb stavropol stv surgut tambov tatarstan tom tomsk tsaritsyn tsk tula tuva tver tyumen udm udmurtia ulan-ude vladikavkaz vladimir vladivostok volgograd vologda voronezh vrn vyatka yakutia yamal yekaterinburg yuzhno-sakhalinsk ',
        'rw':' ac co com edu gouv gov int mil net ',
        'sa':' com edu gov med net org pub sch ',
        'sd':' com edu gov info med net org tv ',
        'se':' a ac b bd c d e f g h i k l m n o org p parti pp press r s t tm u w x y z ',
        'sg':' com edu gov idn net org per ',
        'sn':' art com edu gouv org perso univ ',
        'sy':' com edu gov mil net news org ',
        'th':' ac co go in mi net or ',
        'tj':' ac biz co com edu go gov info int mil name net nic org test web ',
        'tn':' agrinet com defense edunet ens fin gov ind info intl mincom nat net org perso rnrt rns rnu tourism ',
        'tz':' ac co go ne or ',
        'ua':' biz cherkassy chernigov chernovtsy ck cn co com crimea cv dn dnepropetrovsk donetsk dp edu gov if in ivano-frankivsk kh kharkov kherson khmelnitskiy kiev kirovograd km kr ks kv lg lugansk lutsk lviv me mk net nikolaev od odessa org pl poltava pp rovno rv sebastopol sumy te ternopil uzhgorod vinnica vn zaporizhzhe zhitomir zp zt ',
        'ug':' ac co go ne or org sc ',
        'uk':' ac bl british-library co cym gov govt icnet jet lea ltd me mil mod national-library-scotland nel net nhs nic nls org orgn parliament plc police sch scot soc ',
        'us':' dni fed isa kids nsn ',
        'uy':' com edu gub mil net org ',
        've':' co com edu gob info mil net org web ',
        'vi':' co com k12 net org ',
        'vn':' ac biz com edu gov health info int name net org pro ',
        'ye':' co com gov ltd me net org plc ',
        'yu':' ac co edu gov org ',
        'za':' ac agric alt bourse city co cybernet db edu gov grondar iaccess imt inca landesign law mil net ngo nis nom olivetti org pix school tm web ',
        'zm':' ac co com edu gov net org sch ',
        // https://en.wikipedia.org/wiki/CentralNic#Second-level_domains
        'com': 'ar br cn de eu gb gr hu jpn kr no qc ru sa se uk us uy za ',
        'net': 'gb jp se uk ',
        'org': 'ae',
        'de': 'com '
      },
      // gorhill 2013-10-25: Using indexOf() instead Regexp(). Significant boost
      // in both performance and memory footprint. No initialization required.
      // http://jsperf.com/uri-js-sld-regex-vs-binary-search/4
      // Following methods use lastIndexOf() rather than array.split() in order
      // to avoid any memory allocations.
      has: function(domain) {
        var tldOffset = domain.lastIndexOf('.');
        if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {
          return false;
        }
        var sldOffset = domain.lastIndexOf('.', tldOffset-1);
        if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) {
          return false;
        }
        var sldList = SLD.list[domain.slice(tldOffset+1)];
        if (!sldList) {
          return false;
        }
        return sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') >= 0;
      },
      is: function(domain) {
        var tldOffset = domain.lastIndexOf('.');
        if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {
          return false;
        }
        var sldOffset = domain.lastIndexOf('.', tldOffset-1);
        if (sldOffset >= 0) {
          return false;
        }
        var sldList = SLD.list[domain.slice(tldOffset+1)];
        if (!sldList) {
          return false;
        }
        return sldList.indexOf(' ' + domain.slice(0, tldOffset) + ' ') >= 0;
      },
      get: function(domain) {
        var tldOffset = domain.lastIndexOf('.');
        if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {
          return null;
        }
        var sldOffset = domain.lastIndexOf('.', tldOffset-1);
        if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) {
          return null;
        }
        var sldList = SLD.list[domain.slice(tldOffset+1)];
        if (!sldList) {
          return null;
        }
        if (sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') < 0) {
          return null;
        }
        return domain.slice(sldOffset+1);
      },
      noConflict: function(){
        if (root.SecondLevelDomains === this) {
          root.SecondLevelDomains = _SecondLevelDomains;
        }
        return this;
      }
    };

    return SLD;
  }));
  });

  var URI = createCommonjsModule(function (module) {
  /*!
   * URI.js - Mutating URLs
   *
   * Version: 1.19.11
   *
   * Author: Rodney Rehm
   * Web: http://medialize.github.io/URI.js/
   *
   * Licensed under
   *   MIT License http://www.opensource.org/licenses/mit-license
   *
   */
  (function (root, factory) {
    // https://github.com/umdjs/umd/blob/master/returnExports.js
    if (module.exports) {
      // Node
      module.exports = factory(punycode, IPv6, SecondLevelDomains);
    } else {
      // Browser globals (root is window)
      root.URI = factory(root.punycode, root.IPv6, root.SecondLevelDomains, root);
    }
  }(commonjsGlobal, function (punycode, IPv6, SLD, root) {
    /*global location, escape, unescape */
    // FIXME: v2.0.0 renamce non-camelCase properties to uppercase
    /*jshint camelcase: false */

    // save current URI variable, if any
    var _URI = root && root.URI;

    function URI(url, base) {
      var _urlSupplied = arguments.length >= 1;
      var _baseSupplied = arguments.length >= 2;

      // Allow instantiation without the 'new' keyword
      if (!(this instanceof URI)) {
        if (_urlSupplied) {
          if (_baseSupplied) {
            return new URI(url, base);
          }

          return new URI(url);
        }

        return new URI();
      }

      if (url === undefined) {
        if (_urlSupplied) {
          throw new TypeError('undefined is not a valid argument for URI');
        }

        if (typeof location !== 'undefined') {
          url = location.href + '';
        } else {
          url = '';
        }
      }

      if (url === null) {
        if (_urlSupplied) {
          throw new TypeError('null is not a valid argument for URI');
        }
      }

      this.href(url);

      // resolve to base according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#constructor
      if (base !== undefined) {
        return this.absoluteTo(base);
      }

      return this;
    }

    function isInteger(value) {
      return /^[0-9]+$/.test(value);
    }

    URI.version = '1.19.11';

    var p = URI.prototype;
    var hasOwn = Object.prototype.hasOwnProperty;

    function escapeRegEx(string) {
      // https://github.com/medialize/URI.js/commit/85ac21783c11f8ccab06106dba9735a31a86924d#commitcomment-821963
      return string.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
    }

    function getType(value) {
      // IE8 doesn't return [Object Undefined] but [Object Object] for undefined value
      if (value === undefined) {
        return 'Undefined';
      }

      return String(Object.prototype.toString.call(value)).slice(8, -1);
    }

    function isArray(obj) {
      return getType(obj) === 'Array';
    }

    function filterArrayValues(data, value) {
      var lookup = {};
      var i, length;

      if (getType(value) === 'RegExp') {
        lookup = null;
      } else if (isArray(value)) {
        for (i = 0, length = value.length; i < length; i++) {
          lookup[value[i]] = true;
        }
      } else {
        lookup[value] = true;
      }

      for (i = 0, length = data.length; i < length; i++) {
        /*jshint laxbreak: true */
        var _match = lookup && lookup[data[i]] !== undefined
          || !lookup && value.test(data[i]);
        /*jshint laxbreak: false */
        if (_match) {
          data.splice(i, 1);
          length--;
          i--;
        }
      }

      return data;
    }

    function arrayContains(list, value) {
      var i, length;

      // value may be string, number, array, regexp
      if (isArray(value)) {
        // Note: this can be optimized to O(n) (instead of current O(m * n))
        for (i = 0, length = value.length; i < length; i++) {
          if (!arrayContains(list, value[i])) {
            return false;
          }
        }

        return true;
      }

      var _type = getType(value);
      for (i = 0, length = list.length; i < length; i++) {
        if (_type === 'RegExp') {
          if (typeof list[i] === 'string' && list[i].match(value)) {
            return true;
          }
        } else if (list[i] === value) {
          return true;
        }
      }

      return false;
    }

    function arraysEqual(one, two) {
      if (!isArray(one) || !isArray(two)) {
        return false;
      }

      // arrays can't be equal if they have different amount of content
      if (one.length !== two.length) {
        return false;
      }

      one.sort();
      two.sort();

      for (var i = 0, l = one.length; i < l; i++) {
        if (one[i] !== two[i]) {
          return false;
        }
      }

      return true;
    }

    function trimSlashes(text) {
      var trim_expression = /^\/+|\/+$/g;
      return text.replace(trim_expression, '');
    }

    URI._parts = function() {
      return {
        protocol: null,
        username: null,
        password: null,
        hostname: null,
        urn: null,
        port: null,
        path: null,
        query: null,
        fragment: null,
        // state
        preventInvalidHostname: URI.preventInvalidHostname,
        duplicateQueryParameters: URI.duplicateQueryParameters,
        escapeQuerySpace: URI.escapeQuerySpace
      };
    };
    // state: throw on invalid hostname
    // see https://github.com/medialize/URI.js/pull/345
    // and https://github.com/medialize/URI.js/issues/354
    URI.preventInvalidHostname = false;
    // state: allow duplicate query parameters (a=1&a=1)
    URI.duplicateQueryParameters = false;
    // state: replaces + with %20 (space in query strings)
    URI.escapeQuerySpace = true;
    // static properties
    URI.protocol_expression = /^[a-z][a-z0-9.+-]*$/i;
    URI.idn_expression = /[^a-z0-9\._-]/i;
    URI.punycode_expression = /(xn--)/i;
    // well, 333.444.555.666 matches, but it sure ain't no IPv4 - do we care?
    URI.ip4_expression = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
    // credits to Rich Brown
    // source: http://forums.intermapper.com/viewtopic.php?p=1096#1096
    // specification: http://www.ietf.org/rfc/rfc4291.txt
    URI.ip6_expression = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/;
    // expression used is "gruber revised" (@gruber v2) determined to be the
    // best solution in a regex-golf we did a couple of ages ago at
    // * http://mathiasbynens.be/demo/url-regex
    // * http://rodneyrehm.de/t/url-regex.html
    URI.find_uri_expression = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/ig;
    URI.findUri = {
      // valid "scheme://" or "www."
      start: /\b(?:([a-z][a-z0-9.+-]*:\/\/)|www\.)/gi,
      // everything up to the next whitespace
      end: /[\s\r\n]|$/,
      // trim trailing punctuation captured by end RegExp
      trim: /[`!()\[\]{};:'".,<>?«»“”„‘’]+$/,
      // balanced parens inclusion (), [], {}, <>
      parens: /(\([^\)]*\)|\[[^\]]*\]|\{[^}]*\}|<[^>]*>)/g,
    };
    URI.leading_whitespace_expression = /^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;
    // https://infra.spec.whatwg.org/#ascii-tab-or-newline
    URI.ascii_tab_whitespace = /[\u0009\u000A\u000D]+/g;
    // http://www.iana.org/assignments/uri-schemes.html
    // http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports
    URI.defaultPorts = {
      http: '80',
      https: '443',
      ftp: '21',
      gopher: '70',
      ws: '80',
      wss: '443'
    };
    // list of protocols which always require a hostname
    URI.hostProtocols = [
      'http',
      'https'
    ];

    // allowed hostname characters according to RFC 3986
    // ALPHA DIGIT "-" "." "_" "~" "!" "$" "&" "'" "(" ")" "*" "+" "," ";" "=" %encoded
    // I've never seen a (non-IDN) hostname other than: ALPHA DIGIT . - _
    URI.invalid_hostname_characters = /[^a-zA-Z0-9\.\-:_]/;
    // map DOM Elements to their URI attribute
    URI.domAttributes = {
      'a': 'href',
      'blockquote': 'cite',
      'link': 'href',
      'base': 'href',
      'script': 'src',
      'form': 'action',
      'img': 'src',
      'area': 'href',
      'iframe': 'src',
      'embed': 'src',
      'source': 'src',
      'track': 'src',
      'input': 'src', // but only if type="image"
      'audio': 'src',
      'video': 'src'
    };
    URI.getDomAttribute = function(node) {
      if (!node || !node.nodeName) {
        return undefined;
      }

      var nodeName = node.nodeName.toLowerCase();
      // <input> should only expose src for type="image"
      if (nodeName === 'input' && node.type !== 'image') {
        return undefined;
      }

      return URI.domAttributes[nodeName];
    };

    function escapeForDumbFirefox36(value) {
      // https://github.com/medialize/URI.js/issues/91
      return escape(value);
    }

    // encoding / decoding according to RFC3986
    function strictEncodeURIComponent(string) {
      // see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent
      return encodeURIComponent(string)
        .replace(/[!'()*]/g, escapeForDumbFirefox36)
        .replace(/\*/g, '%2A');
    }
    URI.encode = strictEncodeURIComponent;
    URI.decode = decodeURIComponent;
    URI.iso8859 = function() {
      URI.encode = escape;
      URI.decode = unescape;
    };
    URI.unicode = function() {
      URI.encode = strictEncodeURIComponent;
      URI.decode = decodeURIComponent;
    };
    URI.characters = {
      pathname: {
        encode: {
          // RFC3986 2.1: For consistency, URI producers and normalizers should
          // use uppercase hexadecimal digits for all percent-encodings.
          expression: /%(24|26|2B|2C|3B|3D|3A|40)/ig,
          map: {
            // -._~!'()*
            '%24': '$',
            '%26': '&',
            '%2B': '+',
            '%2C': ',',
            '%3B': ';',
            '%3D': '=',
            '%3A': ':',
            '%40': '@'
          }
        },
        decode: {
          expression: /[\/\?#]/g,
          map: {
            '/': '%2F',
            '?': '%3F',
            '#': '%23'
          }
        }
      },
      reserved: {
        encode: {
          // RFC3986 2.1: For consistency, URI producers and normalizers should
          // use uppercase hexadecimal digits for all percent-encodings.
          expression: /%(21|23|24|26|27|28|29|2A|2B|2C|2F|3A|3B|3D|3F|40|5B|5D)/ig,
          map: {
            // gen-delims
            '%3A': ':',
            '%2F': '/',
            '%3F': '?',
            '%23': '#',
            '%5B': '[',
            '%5D': ']',
            '%40': '@',
            // sub-delims
            '%21': '!',
            '%24': '$',
            '%26': '&',
            '%27': '\'',
            '%28': '(',
            '%29': ')',
            '%2A': '*',
            '%2B': '+',
            '%2C': ',',
            '%3B': ';',
            '%3D': '='
          }
        }
      },
      urnpath: {
        // The characters under `encode` are the characters called out by RFC 2141 as being acceptable
        // for usage in a URN. RFC2141 also calls out "-", ".", and "_" as acceptable characters, but
        // these aren't encoded by encodeURIComponent, so we don't have to call them out here. Also
        // note that the colon character is not featured in the encoding map; this is because URI.js
        // gives the colons in URNs semantic meaning as the delimiters of path segements, and so it
        // should not appear unencoded in a segment itself.
        // See also the note above about RFC3986 and capitalalized hex digits.
        encode: {
          expression: /%(21|24|27|28|29|2A|2B|2C|3B|3D|40)/ig,
          map: {
            '%21': '!',
            '%24': '$',
            '%27': '\'',
            '%28': '(',
            '%29': ')',
            '%2A': '*',
            '%2B': '+',
            '%2C': ',',
            '%3B': ';',
            '%3D': '=',
            '%40': '@'
          }
        },
        // These characters are the characters called out by RFC2141 as "reserved" characters that
        // should never appear in a URN, plus the colon character (see note above).
        decode: {
          expression: /[\/\?#:]/g,
          map: {
            '/': '%2F',
            '?': '%3F',
            '#': '%23',
            ':': '%3A'
          }
        }
      }
    };
    URI.encodeQuery = function(string, escapeQuerySpace) {
      var escaped = URI.encode(string + '');
      if (escapeQuerySpace === undefined) {
        escapeQuerySpace = URI.escapeQuerySpace;
      }

      return escapeQuerySpace ? escaped.replace(/%20/g, '+') : escaped;
    };
    URI.decodeQuery = function(string, escapeQuerySpace) {
      string += '';
      if (escapeQuerySpace === undefined) {
        escapeQuerySpace = URI.escapeQuerySpace;
      }

      try {
        return URI.decode(escapeQuerySpace ? string.replace(/\+/g, '%20') : string);
      } catch(e) {
        // we're not going to mess with weird encodings,
        // give up and return the undecoded original string
        // see https://github.com/medialize/URI.js/issues/87
        // see https://github.com/medialize/URI.js/issues/92
        return string;
      }
    };
    // generate encode/decode path functions
    var _parts = {'encode':'encode', 'decode':'decode'};
    var _part;
    var generateAccessor = function(_group, _part) {
      return function(string) {
        try {
          return URI[_part](string + '').replace(URI.characters[_group][_part].expression, function(c) {
            return URI.characters[_group][_part].map[c];
          });
        } catch (e) {
          // we're not going to mess with weird encodings,
          // give up and return the undecoded original string
          // see https://github.com/medialize/URI.js/issues/87
          // see https://github.com/medialize/URI.js/issues/92
          return string;
        }
      };
    };

    for (_part in _parts) {
      URI[_part + 'PathSegment'] = generateAccessor('pathname', _parts[_part]);
      URI[_part + 'UrnPathSegment'] = generateAccessor('urnpath', _parts[_part]);
    }

    var generateSegmentedPathFunction = function(_sep, _codingFuncName, _innerCodingFuncName) {
      return function(string) {
        // Why pass in names of functions, rather than the function objects themselves? The
        // definitions of some functions (but in particular, URI.decode) will occasionally change due
        // to URI.js having ISO8859 and Unicode modes. Passing in the name and getting it will ensure
        // that the functions we use here are "fresh".
        var actualCodingFunc;
        if (!_innerCodingFuncName) {
          actualCodingFunc = URI[_codingFuncName];
        } else {
          actualCodingFunc = function(string) {
            return URI[_codingFuncName](URI[_innerCodingFuncName](string));
          };
        }

        var segments = (string + '').split(_sep);

        for (var i = 0, length = segments.length; i < length; i++) {
          segments[i] = actualCodingFunc(segments[i]);
        }

        return segments.join(_sep);
      };
    };

    // This takes place outside the above loop because we don't want, e.g., encodeUrnPath functions.
    URI.decodePath = generateSegmentedPathFunction('/', 'decodePathSegment');
    URI.decodeUrnPath = generateSegmentedPathFunction(':', 'decodeUrnPathSegment');
    URI.recodePath = generateSegmentedPathFunction('/', 'encodePathSegment', 'decode');
    URI.recodeUrnPath = generateSegmentedPathFunction(':', 'encodeUrnPathSegment', 'decode');

    URI.encodeReserved = generateAccessor('reserved', 'encode');

    URI.parse = function(string, parts) {
      var pos;
      if (!parts) {
        parts = {
          preventInvalidHostname: URI.preventInvalidHostname
        };
      }

      string = string.replace(URI.leading_whitespace_expression, '');
      // https://infra.spec.whatwg.org/#ascii-tab-or-newline
      string = string.replace(URI.ascii_tab_whitespace, '');

      // [protocol"://"[username[":"password]"@"]hostname[":"port]"/"?][path]["?"querystring]["#"fragment]

      // extract fragment
      pos = string.indexOf('#');
      if (pos > -1) {
        // escaping?
        parts.fragment = string.substring(pos + 1) || null;
        string = string.substring(0, pos);
      }

      // extract query
      pos = string.indexOf('?');
      if (pos > -1) {
        // escaping?
        parts.query = string.substring(pos + 1) || null;
        string = string.substring(0, pos);
      }

      // slashes and backslashes have lost all meaning for the web protocols (https, http, wss, ws)
      string = string.replace(/^(https?|ftp|wss?)?:+[/\\]*/i, '$1://');
      // slashes and backslashes have lost all meaning for scheme relative URLs
      string = string.replace(/^[/\\]{2,}/i, '//');

      // extract protocol
      if (string.substring(0, 2) === '//') {
        // relative-scheme
        parts.protocol = null;
        string = string.substring(2);
        // extract "user:pass@host:port"
        string = URI.parseAuthority(string, parts);
      } else {
        pos = string.indexOf(':');
        if (pos > -1) {
          parts.protocol = string.substring(0, pos) || null;
          if (parts.protocol && !parts.protocol.match(URI.protocol_expression)) {
            // : may be within the path
            parts.protocol = undefined;
          } else if (string.substring(pos + 1, pos + 3).replace(/\\/g, '/') === '//') {
            string = string.substring(pos + 3);

            // extract "user:pass@host:port"
            string = URI.parseAuthority(string, parts);
          } else {
            string = string.substring(pos + 1);
            parts.urn = true;
          }
        }
      }

      // what's left must be the path
      parts.path = string;

      // and we're done
      return parts;
    };
    URI.parseHost = function(string, parts) {
      if (!string) {
        string = '';
      }

      // Copy chrome, IE, opera backslash-handling behavior.
      // Back slashes before the query string get converted to forward slashes
      // See: https://github.com/joyent/node/blob/386fd24f49b0e9d1a8a076592a404168faeecc34/lib/url.js#L115-L124
      // See: https://code.google.com/p/chromium/issues/detail?id=25916
      // https://github.com/medialize/URI.js/pull/233
      string = string.replace(/\\/g, '/');

      // extract host:port
      var pos = string.indexOf('/');
      var bracketPos;
      var t;

      if (pos === -1) {
        pos = string.length;
      }

      if (string.charAt(0) === '[') {
        // IPv6 host - http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04#section-6
        // I claim most client software breaks on IPv6 anyways. To simplify things, URI only accepts
        // IPv6+port in the format [2001:db8::1]:80 (for the time being)
        bracketPos = string.indexOf(']');
        parts.hostname = string.substring(1, bracketPos) || null;
        parts.port = string.substring(bracketPos + 2, pos) || null;
        if (parts.port === '/') {
          parts.port = null;
        }
      } else {
        var firstColon = string.indexOf(':');
        var firstSlash = string.indexOf('/');
        var nextColon = string.indexOf(':', firstColon + 1);
        if (nextColon !== -1 && (firstSlash === -1 || nextColon < firstSlash)) {
          // IPv6 host contains multiple colons - but no port
          // this notation is actually not allowed by RFC 3986, but we're a liberal parser
          parts.hostname = string.substring(0, pos) || null;
          parts.port = null;
        } else {
          t = string.substring(0, pos).split(':');
          parts.hostname = t[0] || null;
          parts.port = t[1] || null;
        }
      }

      if (parts.hostname && string.substring(pos).charAt(0) !== '/') {
        pos++;
        string = '/' + string;
      }

      if (parts.preventInvalidHostname) {
        URI.ensureValidHostname(parts.hostname, parts.protocol);
      }

      if (parts.port) {
        URI.ensureValidPort(parts.port);
      }

      return string.substring(pos) || '/';
    };
    URI.parseAuthority = function(string, parts) {
      string = URI.parseUserinfo(string, parts);
      return URI.parseHost(string, parts);
    };
    URI.parseUserinfo = function(string, parts) {
      // extract username:password
      var _string = string;
      var firstBackSlash = string.indexOf('\\');
      if (firstBackSlash !== -1) {
        string = string.replace(/\\/g, '/');
      }
      var firstSlash = string.indexOf('/');
      var pos = string.lastIndexOf('@', firstSlash > -1 ? firstSlash : string.length - 1);
      var t;

      // authority@ must come before /path or \path
      if (pos > -1 && (firstSlash === -1 || pos < firstSlash)) {
        t = string.substring(0, pos).split(':');
        parts.username = t[0] ? URI.decode(t[0]) : null;
        t.shift();
        parts.password = t[0] ? URI.decode(t.join(':')) : null;
        string = _string.substring(pos + 1);
      } else {
        parts.username = null;
        parts.password = null;
      }

      return string;
    };
    URI.parseQuery = function(string, escapeQuerySpace) {
      if (!string) {
        return {};
      }

      // throw out the funky business - "?"[name"="value"&"]+
      string = string.replace(/&+/g, '&').replace(/^\?*&*|&+$/g, '');

      if (!string) {
        return {};
      }

      var items = {};
      var splits = string.split('&');
      var length = splits.length;
      var v, name, value;

      for (var i = 0; i < length; i++) {
        v = splits[i].split('=');
        name = URI.decodeQuery(v.shift(), escapeQuerySpace);
        // no "=" is null according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#collect-url-parameters
        value = v.length ? URI.decodeQuery(v.join('='), escapeQuerySpace) : null;

        if (name === '__proto__') {
          // ignore attempt at exploiting JavaScript internals
          continue;
        } else if (hasOwn.call(items, name)) {
          if (typeof items[name] === 'string' || items[name] === null) {
            items[name] = [items[name]];
          }

          items[name].push(value);
        } else {
          items[name] = value;
        }
      }

      return items;
    };

    URI.build = function(parts) {
      var t = '';
      var requireAbsolutePath = false;

      if (parts.protocol) {
        t += parts.protocol + ':';
      }

      if (!parts.urn && (t || parts.hostname)) {
        t += '//';
        requireAbsolutePath = true;
      }

      t += (URI.buildAuthority(parts) || '');

      if (typeof parts.path === 'string') {
        if (parts.path.charAt(0) !== '/' && requireAbsolutePath) {
          t += '/';
        }

        t += parts.path;
      }

      if (typeof parts.query === 'string' && parts.query) {
        t += '?' + parts.query;
      }

      if (typeof parts.fragment === 'string' && parts.fragment) {
        t += '#' + parts.fragment;
      }
      return t;
    };
    URI.buildHost = function(parts) {
      var t = '';

      if (!parts.hostname) {
        return '';
      } else if (URI.ip6_expression.test(parts.hostname)) {
        t += '[' + parts.hostname + ']';
      } else {
        t += parts.hostname;
      }

      if (parts.port) {
        t += ':' + parts.port;
      }

      return t;
    };
    URI.buildAuthority = function(parts) {
      return URI.buildUserinfo(parts) + URI.buildHost(parts);
    };
    URI.buildUserinfo = function(parts) {
      var t = '';

      if (parts.username) {
        t += URI.encode(parts.username);
      }

      if (parts.password) {
        t += ':' + URI.encode(parts.password);
      }

      if (t) {
        t += '@';
      }

      return t;
    };
    URI.buildQuery = function(data, duplicateQueryParameters, escapeQuerySpace) {
      // according to http://tools.ietf.org/html/rfc3986 or http://labs.apache.org/webarch/uri/rfc/rfc3986.html
      // being »-._~!$&'()*+,;=:@/?« %HEX and alnum are allowed
      // the RFC explicitly states ?/foo being a valid use case, no mention of parameter syntax!
      // URI.js treats the query string as being application/x-www-form-urlencoded
      // see http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type

      var t = '';
      var unique, key, i, length;
      for (key in data) {
        if (key === '__proto__') {
          // ignore attempt at exploiting JavaScript internals
          continue;
        } else if (hasOwn.call(data, key)) {
          if (isArray(data[key])) {
            unique = {};
            for (i = 0, length = data[key].length; i < length; i++) {
              if (data[key][i] !== undefined && unique[data[key][i] + ''] === undefined) {
                t += '&' + URI.buildQueryParameter(key, data[key][i], escapeQuerySpace);
                if (duplicateQueryParameters !== true) {
                  unique[data[key][i] + ''] = true;
                }
              }
            }
          } else if (data[key] !== undefined) {
            t += '&' + URI.buildQueryParameter(key, data[key], escapeQuerySpace);
          }
        }
      }

      return t.substring(1);
    };
    URI.buildQueryParameter = function(name, value, escapeQuerySpace) {
      // http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type -- application/x-www-form-urlencoded
      // don't append "=" for null values, according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#url-parameter-serialization
      return URI.encodeQuery(name, escapeQuerySpace) + (value !== null ? '=' + URI.encodeQuery(value, escapeQuerySpace) : '');
    };

    URI.addQuery = function(data, name, value) {
      if (typeof name === 'object') {
        for (var key in name) {
          if (hasOwn.call(name, key)) {
            URI.addQuery(data, key, name[key]);
          }
        }
      } else if (typeof name === 'string') {
        if (data[name] === undefined) {
          data[name] = value;
          return;
        } else if (typeof data[name] === 'string') {
          data[name] = [data[name]];
        }

        if (!isArray(value)) {
          value = [value];
        }

        data[name] = (data[name] || []).concat(value);
      } else {
        throw new TypeError('URI.addQuery() accepts an object, string as the name parameter');
      }
    };

    URI.setQuery = function(data, name, value) {
      if (typeof name === 'object') {
        for (var key in name) {
          if (hasOwn.call(name, key)) {
            URI.setQuery(data, key, name[key]);
          }
        }
      } else if (typeof name === 'string') {
        data[name] = value === undefined ? null : value;
      } else {
        throw new TypeError('URI.setQuery() accepts an object, string as the name parameter');
      }
    };

    URI.removeQuery = function(data, name, value) {
      var i, length, key;

      if (isArray(name)) {
        for (i = 0, length = name.length; i < length; i++) {
          data[name[i]] = undefined;
        }
      } else if (getType(name) === 'RegExp') {
        for (key in data) {
          if (name.test(key)) {
            data[key] = undefined;
          }
        }
      } else if (typeof name === 'object') {
        for (key in name) {
          if (hasOwn.call(name, key)) {
            URI.removeQuery(data, key, name[key]);
          }
        }
      } else if (typeof name === 'string') {
        if (value !== undefined) {
          if (getType(value) === 'RegExp') {
            if (!isArray(data[name]) && value.test(data[name])) {
              data[name] = undefined;
            } else {
              data[name] = filterArrayValues(data[name], value);
            }
          } else if (data[name] === String(value) && (!isArray(value) || value.length === 1)) {
            data[name] = undefined;
          } else if (isArray(data[name])) {
            data[name] = filterArrayValues(data[name], value);
          }
        } else {
          data[name] = undefined;
        }
      } else {
        throw new TypeError('URI.removeQuery() accepts an object, string, RegExp as the first parameter');
      }
    };
    URI.hasQuery = function(data, name, value, withinArray) {
      switch (getType(name)) {
        case 'String':
          // Nothing to do here
          break;

        case 'RegExp':
          for (var key in data) {
            if (hasOwn.call(data, key)) {
              if (name.test(key) && (value === undefined || URI.hasQuery(data, key, value))) {
                return true;
              }
            }
          }

          return false;

        case 'Object':
          for (var _key in name) {
            if (hasOwn.call(name, _key)) {
              if (!URI.hasQuery(data, _key, name[_key])) {
                return false;
              }
            }
          }

          return true;

        default:
          throw new TypeError('URI.hasQuery() accepts a string, regular expression or object as the name parameter');
      }

      switch (getType(value)) {
        case 'Undefined':
          // true if exists (but may be empty)
          return name in data; // data[name] !== undefined;

        case 'Boolean':
          // true if exists and non-empty
          var _booly = Boolean(isArray(data[name]) ? data[name].length : data[name]);
          return value === _booly;

        case 'Function':
          // allow complex comparison
          return !!value(data[name], name, data);

        case 'Array':
          if (!isArray(data[name])) {
            return false;
          }

          var op = withinArray ? arrayContains : arraysEqual;
          return op(data[name], value);

        case 'RegExp':
          if (!isArray(data[name])) {
            return Boolean(data[name] && data[name].match(value));
          }

          if (!withinArray) {
            return false;
          }

          return arrayContains(data[name], value);

        case 'Number':
          value = String(value);
          /* falls through */
        case 'String':
          if (!isArray(data[name])) {
            return data[name] === value;
          }

          if (!withinArray) {
            return false;
          }

          return arrayContains(data[name], value);

        default:
          throw new TypeError('URI.hasQuery() accepts undefined, boolean, string, number, RegExp, Function as the value parameter');
      }
    };


    URI.joinPaths = function() {
      var input = [];
      var segments = [];
      var nonEmptySegments = 0;

      for (var i = 0; i < arguments.length; i++) {
        var url = new URI(arguments[i]);
        input.push(url);
        var _segments = url.segment();
        for (var s = 0; s < _segments.length; s++) {
          if (typeof _segments[s] === 'string') {
            segments.push(_segments[s]);
          }

          if (_segments[s]) {
            nonEmptySegments++;
          }
        }
      }

      if (!segments.length || !nonEmptySegments) {
        return new URI('');
      }

      var uri = new URI('').segment(segments);

      if (input[0].path() === '' || input[0].path().slice(0, 1) === '/') {
        uri.path('/' + uri.path());
      }

      return uri.normalize();
    };

    URI.commonPath = function(one, two) {
      var length = Math.min(one.length, two.length);
      var pos;

      // find first non-matching character
      for (pos = 0; pos < length; pos++) {
        if (one.charAt(pos) !== two.charAt(pos)) {
          pos--;
          break;
        }
      }

      if (pos < 1) {
        return one.charAt(0) === two.charAt(0) && one.charAt(0) === '/' ? '/' : '';
      }

      // revert to last /
      if (one.charAt(pos) !== '/' || two.charAt(pos) !== '/') {
        pos = one.substring(0, pos).lastIndexOf('/');
      }

      return one.substring(0, pos + 1);
    };

    URI.withinString = function(string, callback, options) {
      options || (options = {});
      var _start = options.start || URI.findUri.start;
      var _end = options.end || URI.findUri.end;
      var _trim = options.trim || URI.findUri.trim;
      var _parens = options.parens || URI.findUri.parens;
      var _attributeOpen = /[a-z0-9-]=["']?$/i;

      _start.lastIndex = 0;
      while (true) {
        var match = _start.exec(string);
        if (!match) {
          break;
        }

        var start = match.index;
        if (options.ignoreHtml) {
          // attribut(e=["']?$)
          var attributeOpen = string.slice(Math.max(start - 3, 0), start);
          if (attributeOpen && _attributeOpen.test(attributeOpen)) {
            continue;
          }
        }

        var end = start + string.slice(start).search(_end);
        var slice = string.slice(start, end);
        // make sure we include well balanced parens
        var parensEnd = -1;
        while (true) {
          var parensMatch = _parens.exec(slice);
          if (!parensMatch) {
            break;
          }

          var parensMatchEnd = parensMatch.index + parensMatch[0].length;
          parensEnd = Math.max(parensEnd, parensMatchEnd);
        }

        if (parensEnd > -1) {
          slice = slice.slice(0, parensEnd) + slice.slice(parensEnd).replace(_trim, '');
        } else {
          slice = slice.replace(_trim, '');
        }

        if (slice.length <= match[0].length) {
          // the extract only contains the starting marker of a URI,
          // e.g. "www" or "http://"
          continue;
        }

        if (options.ignore && options.ignore.test(slice)) {
          continue;
        }

        end = start + slice.length;
        var result = callback(slice, start, end, string);
        if (result === undefined) {
          _start.lastIndex = end;
          continue;
        }

        result = String(result);
        string = string.slice(0, start) + result + string.slice(end);
        _start.lastIndex = start + result.length;
      }

      _start.lastIndex = 0;
      return string;
    };

    URI.ensureValidHostname = function(v, protocol) {
      // Theoretically URIs allow percent-encoding in Hostnames (according to RFC 3986)
      // they are not part of DNS and therefore ignored by URI.js

      var hasHostname = !!v; // not null and not an empty string
      var hasProtocol = !!protocol;
      var rejectEmptyHostname = false;

      if (hasProtocol) {
        rejectEmptyHostname = arrayContains(URI.hostProtocols, protocol);
      }

      if (rejectEmptyHostname && !hasHostname) {
        throw new TypeError('Hostname cannot be empty, if protocol is ' + protocol);
      } else if (v && v.match(URI.invalid_hostname_characters)) {
        // test punycode
        if (!punycode) {
          throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_] and Punycode.js is not available');
        }
        if (punycode.toASCII(v).match(URI.invalid_hostname_characters)) {
          throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_]');
        }
      }
    };

    URI.ensureValidPort = function (v) {
      if (!v) {
        return;
      }

      var port = Number(v);
      if (isInteger(port) && (port > 0) && (port < 65536)) {
        return;
      }

      throw new TypeError('Port "' + v + '" is not a valid port');
    };

    // noConflict
    URI.noConflict = function(removeAll) {
      if (removeAll) {
        var unconflicted = {
          URI: this.noConflict()
        };

        if (root.URITemplate && typeof root.URITemplate.noConflict === 'function') {
          unconflicted.URITemplate = root.URITemplate.noConflict();
        }

        if (root.IPv6 && typeof root.IPv6.noConflict === 'function') {
          unconflicted.IPv6 = root.IPv6.noConflict();
        }

        if (root.SecondLevelDomains && typeof root.SecondLevelDomains.noConflict === 'function') {
          unconflicted.SecondLevelDomains = root.SecondLevelDomains.noConflict();
        }

        return unconflicted;
      } else if (root.URI === this) {
        root.URI = _URI;
      }

      return this;
    };

    p.build = function(deferBuild) {
      if (deferBuild === true) {
        this._deferred_build = true;
      } else if (deferBuild === undefined || this._deferred_build) {
        this._string = URI.build(this._parts);
        this._deferred_build = false;
      }

      return this;
    };

    p.clone = function() {
      return new URI(this);
    };

    p.valueOf = p.toString = function() {
      return this.build(false)._string;
    };


    function generateSimpleAccessor(_part){
      return function(v, build) {
        if (v === undefined) {
          return this._parts[_part] || '';
        } else {
          this._parts[_part] = v || null;
          this.build(!build);
          return this;
        }
      };
    }

    function generatePrefixAccessor(_part, _key){
      return function(v, build) {
        if (v === undefined) {
          return this._parts[_part] || '';
        } else {
          if (v !== null) {
            v = v + '';
            if (v.charAt(0) === _key) {
              v = v.substring(1);
            }
          }

          this._parts[_part] = v;
          this.build(!build);
          return this;
        }
      };
    }

    p.protocol = generateSimpleAccessor('protocol');
    p.username = generateSimpleAccessor('username');
    p.password = generateSimpleAccessor('password');
    p.hostname = generateSimpleAccessor('hostname');
    p.port = generateSimpleAccessor('port');
    p.query = generatePrefixAccessor('query', '?');
    p.fragment = generatePrefixAccessor('fragment', '#');

    p.search = function(v, build) {
      var t = this.query(v, build);
      return typeof t === 'string' && t.length ? ('?' + t) : t;
    };
    p.hash = function(v, build) {
      var t = this.fragment(v, build);
      return typeof t === 'string' && t.length ? ('#' + t) : t;
    };

    p.pathname = function(v, build) {
      if (v === undefined || v === true) {
        var res = this._parts.path || (this._parts.hostname ? '/' : '');
        return v ? (this._parts.urn ? URI.decodeUrnPath : URI.decodePath)(res) : res;
      } else {
        if (this._parts.urn) {
          this._parts.path = v ? URI.recodeUrnPath(v) : '';
        } else {
          this._parts.path = v ? URI.recodePath(v) : '/';
        }
        this.build(!build);
        return this;
      }
    };
    p.path = p.pathname;
    p.href = function(href, build) {
      var key;

      if (href === undefined) {
        return this.toString();
      }

      this._string = '';
      this._parts = URI._parts();

      var _URI = href instanceof URI;
      var _object = typeof href === 'object' && (href.hostname || href.path || href.pathname);
      if (href.nodeName) {
        var attribute = URI.getDomAttribute(href);
        href = href[attribute] || '';
        _object = false;
      }

      // window.location is reported to be an object, but it's not the sort
      // of object we're looking for:
      // * location.protocol ends with a colon
      // * location.query != object.search
      // * location.hash != object.fragment
      // simply serializing the unknown object should do the trick
      // (for location, not for everything...)
      if (!_URI && _object && href.pathname !== undefined) {
        href = href.toString();
      }

      if (typeof href === 'string' || href instanceof String) {
        this._parts = URI.parse(String(href), this._parts);
      } else if (_URI || _object) {
        var src = _URI ? href._parts : href;
        for (key in src) {
          if (key === 'query') { continue; }
          if (hasOwn.call(this._parts, key)) {
            this._parts[key] = src[key];
          }
        }
        if (src.query) {
          this.query(src.query, false);
        }
      } else {
        throw new TypeError('invalid input');
      }

      this.build(!build);
      return this;
    };

    // identification accessors
    p.is = function(what) {
      var ip = false;
      var ip4 = false;
      var ip6 = false;
      var name = false;
      var sld = false;
      var idn = false;
      var punycode = false;
      var relative = !this._parts.urn;

      if (this._parts.hostname) {
        relative = false;
        ip4 = URI.ip4_expression.test(this._parts.hostname);
        ip6 = URI.ip6_expression.test(this._parts.hostname);
        ip = ip4 || ip6;
        name = !ip;
        sld = name && SLD && SLD.has(this._parts.hostname);
        idn = name && URI.idn_expression.test(this._parts.hostname);
        punycode = name && URI.punycode_expression.test(this._parts.hostname);
      }

      switch (what.toLowerCase()) {
        case 'relative':
          return relative;

        case 'absolute':
          return !relative;

        // hostname identification
        case 'domain':
        case 'name':
          return name;

        case 'sld':
          return sld;

        case 'ip':
          return ip;

        case 'ip4':
        case 'ipv4':
        case 'inet4':
          return ip4;

        case 'ip6':
        case 'ipv6':
        case 'inet6':
          return ip6;

        case 'idn':
          return idn;

        case 'url':
          return !this._parts.urn;

        case 'urn':
          return !!this._parts.urn;

        case 'punycode':
          return punycode;
      }

      return null;
    };

    // component specific input validation
    var _protocol = p.protocol;
    var _port = p.port;
    var _hostname = p.hostname;

    p.protocol = function(v, build) {
      if (v) {
        // accept trailing ://
        v = v.replace(/:(\/\/)?$/, '');

        if (!v.match(URI.protocol_expression)) {
          throw new TypeError('Protocol "' + v + '" contains characters other than [A-Z0-9.+-] or doesn\'t start with [A-Z]');
        }
      }

      return _protocol.call(this, v, build);
    };
    p.scheme = p.protocol;
    p.port = function(v, build) {
      if (this._parts.urn) {
        return v === undefined ? '' : this;
      }

      if (v !== undefined) {
        if (v === 0) {
          v = null;
        }

        if (v) {
          v += '';
          if (v.charAt(0) === ':') {
            v = v.substring(1);
          }

          URI.ensureValidPort(v);
        }
      }
      return _port.call(this, v, build);
    };
    p.hostname = function(v, build) {
      if (this._parts.urn) {
        return v === undefined ? '' : this;
      }

      if (v !== undefined) {
        var x = { preventInvalidHostname: this._parts.preventInvalidHostname };
        var res = URI.parseHost(v, x);
        if (res !== '/') {
          throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]');
        }

        v = x.hostname;
        if (this._parts.preventInvalidHostname) {
          URI.ensureValidHostname(v, this._parts.protocol);
        }
      }

      return _hostname.call(this, v, build);
    };

    // compound accessors
    p.origin = function(v, build) {
      if (this._parts.urn) {
        return v === undefined ? '' : this;
      }

      if (v === undefined) {
        var protocol = this.protocol();
        var authority = this.authority();
        if (!authority) {
          return '';
        }

        return (protocol ? protocol + '://' : '') + this.authority();
      } else {
        var origin = URI(v);
        this
          .protocol(origin.protocol())
          .authority(origin.authority())
          .build(!build);
        return this;
      }
    };
    p.host = function(v, build) {
      if (this._parts.urn) {
        return v === undefined ? '' : this;
      }

      if (v === undefined) {
        return this._parts.hostname ? URI.buildHost(this._parts) : '';
      } else {
        var res = URI.parseHost(v, this._parts);
        if (res !== '/') {
          throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]');
        }

        this.build(!build);
        return this;
      }
    };
    p.authority = function(v, build) {
      if (this._parts.urn) {
        return v === undefined ? '' : this;
      }

      if (v === undefined) {
        return this._parts.hostname ? URI.buildAuthority(this._parts) : '';
      } else {
        var res = URI.parseAuthority(v, this._parts);
        if (res !== '/') {
          throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]');
        }

        this.build(!build);
        return this;
      }
    };
    p.userinfo = function(v, build) {
      if (this._parts.urn) {
        return v === undefined ? '' : this;
      }

      if (v === undefined) {
        var t = URI.buildUserinfo(this._parts);
        return t ? t.substring(0, t.length -1) : t;
      } else {
        if (v[v.length-1] !== '@') {
          v += '@';
        }

        URI.parseUserinfo(v, this._parts);
        this.build(!build);
        return this;
      }
    };
    p.resource = function(v, build) {
      var parts;

      if (v === undefined) {
        return this.path() + this.search() + this.hash();
      }

      parts = URI.parse(v);
      this._parts.path = parts.path;
      this._parts.query = parts.query;
      this._parts.fragment = parts.fragment;
      this.build(!build);
      return this;
    };

    // fraction accessors
    p.subdomain = function(v, build) {
      if (this._parts.urn) {
        return v === undefined ? '' : this;
      }

      // convenience, return "www" from "www.example.org"
      if (v === undefined) {
        if (!this._parts.hostname || this.is('IP')) {
          return '';
        }

        // grab domain and add another segment
        var end = this._parts.hostname.length - this.domain().length - 1;
        return this._parts.hostname.substring(0, end) || '';
      } else {
        var e = this._parts.hostname.length - this.domain().length;
        var sub = this._parts.hostname.substring(0, e);
        var replace = new RegExp('^' + escapeRegEx(sub));

        if (v && v.charAt(v.length - 1) !== '.') {
          v += '.';
        }

        if (v.indexOf(':') !== -1) {
          throw new TypeError('Domains cannot contain colons');
        }

        if (v) {
          URI.ensureValidHostname(v, this._parts.protocol);
        }

        this._parts.hostname = this._parts.hostname.replace(replace, v);
        this.build(!build);
        return this;
      }
    };
    p.domain = function(v, build) {
      if (this._parts.urn) {
        return v === undefined ? '' : this;
      }

      if (typeof v === 'boolean') {
        build = v;
        v = undefined;
      }

      // convenience, return "example.org" from "www.example.org"
      if (v === undefined) {
        if (!this._parts.hostname || this.is('IP')) {
          return '';
        }

        // if hostname consists of 1 or 2 segments, it must be the domain
        var t = this._parts.hostname.match(/\./g);
        if (t && t.length < 2) {
          return this._parts.hostname;
        }

        // grab tld and add another segment
        var end = this._parts.hostname.length - this.tld(build).length - 1;
        end = this._parts.hostname.lastIndexOf('.', end -1) + 1;
        return this._parts.hostname.substring(end) || '';
      } else {
        if (!v) {
          throw new TypeError('cannot set domain empty');
        }

        if (v.indexOf(':') !== -1) {
          throw new TypeError('Domains cannot contain colons');
        }

        URI.ensureValidHostname(v, this._parts.protocol);

        if (!this._parts.hostname || this.is('IP')) {
          this._parts.hostname = v;
        } else {
          var replace = new RegExp(escapeRegEx(this.domain()) + '$');
          this._parts.hostname = this._parts.hostname.replace(replace, v);
        }

        this.build(!build);
        return this;
      }
    };
    p.tld = function(v, build) {
      if (this._parts.urn) {
        return v === undefined ? '' : this;
      }

      if (typeof v === 'boolean') {
        build = v;
        v = undefined;
      }

      // return "org" from "www.example.org"
      if (v === undefined) {
        if (!this._parts.hostname || this.is('IP')) {
          return '';
        }

        var pos = this._parts.hostname.lastIndexOf('.');
        var tld = this._parts.hostname.substring(pos + 1);

        if (build !== true && SLD && SLD.list[tld.toLowerCase()]) {
          return SLD.get(this._parts.hostname) || tld;
        }

        return tld;
      } else {
        var replace;

        if (!v) {
          throw new TypeError('cannot set TLD empty');
        } else if (v.match(/[^a-zA-Z0-9-]/)) {
          if (SLD && SLD.is(v)) {
            replace = new RegExp(escapeRegEx(this.tld()) + '$');
            this._parts.hostname = this._parts.hostname.replace(replace, v);
          } else {
            throw new TypeError('TLD "' + v + '" contains characters other than [A-Z0-9]');
          }
        } else if (!this._parts.hostname || this.is('IP')) {
          throw new ReferenceError('cannot set TLD on non-domain host');
        } else {
          replace = new RegExp(escapeRegEx(this.tld()) + '$');
          this._parts.hostname = this._parts.hostname.replace(replace, v);
        }

        this.build(!build);
        return this;
      }
    };
    p.directory = function(v, build) {
      if (this._parts.urn) {
        return v === undefined ? '' : this;
      }

      if (v === undefined || v === true) {
        if (!this._parts.path && !this._parts.hostname) {
          return '';
        }

        if (this._parts.path === '/') {
          return '/';
        }

        var end = this._parts.path.length - this.filename().length - 1;
        var res = this._parts.path.substring(0, end) || (this._parts.hostname ? '/' : '');

        return v ? URI.decodePath(res) : res;

      } else {
        var e = this._parts.path.length - this.filename().length;
        var directory = this._parts.path.substring(0, e);
        var replace = new RegExp('^' + escapeRegEx(directory));

        // fully qualifier directories begin with a slash
        if (!this.is('relative')) {
          if (!v) {
            v = '/';
          }

          if (v.charAt(0) !== '/') {
            v = '/' + v;
          }
        }

        // directories always end with a slash
        if (v && v.charAt(v.length - 1) !== '/') {
          v += '/';
        }

        v = URI.recodePath(v);
        this._parts.path = this._parts.path.replace(replace, v);
        this.build(!build);
        return this;
      }
    };
    p.filename = function(v, build) {
      if (this._parts.urn) {
        return v === undefined ? '' : this;
      }

      if (typeof v !== 'string') {
        if (!this._parts.path || this._parts.path === '/') {
          return '';
        }

        var pos = this._parts.path.lastIndexOf('/');
        var res = this._parts.path.substring(pos+1);

        return v ? URI.decodePathSegment(res) : res;
      } else {
        var mutatedDirectory = false;

        if (v.charAt(0) === '/') {
          v = v.substring(1);
        }

        if (v.match(/\.?\//)) {
          mutatedDirectory = true;
        }

        var replace = new RegExp(escapeRegEx(this.filename()) + '$');
        v = URI.recodePath(v);
        this._parts.path = this._parts.path.replace(replace, v);

        if (mutatedDirectory) {
          this.normalizePath(build);
        } else {
          this.build(!build);
        }

        return this;
      }
    };
    p.suffix = function(v, build) {
      if (this._parts.urn) {
        return v === undefined ? '' : this;
      }

      if (v === undefined || v === true) {
        if (!this._parts.path || this._parts.path === '/') {
          return '';
        }

        var filename = this.filename();
        var pos = filename.lastIndexOf('.');
        var s, res;

        if (pos === -1) {
          return '';
        }

        // suffix may only contain alnum characters (yup, I made this up.)
        s = filename.substring(pos+1);
        res = (/^[a-z0-9%]+$/i).test(s) ? s : '';
        return v ? URI.decodePathSegment(res) : res;
      } else {
        if (v.charAt(0) === '.') {
          v = v.substring(1);
        }

        var suffix = this.suffix();
        var replace;

        if (!suffix) {
          if (!v) {
            return this;
          }

          this._parts.path += '.' + URI.recodePath(v);
        } else if (!v) {
          replace = new RegExp(escapeRegEx('.' + suffix) + '$');
        } else {
          replace = new RegExp(escapeRegEx(suffix) + '$');
        }

        if (replace) {
          v = URI.recodePath(v);
          this._parts.path = this._parts.path.replace(replace, v);
        }

        this.build(!build);
        return this;
      }
    };
    p.segment = function(segment, v, build) {
      var separator = this._parts.urn ? ':' : '/';
      var path = this.path();
      var absolute = path.substring(0, 1) === '/';
      var segments = path.split(separator);

      if (segment !== undefined && typeof segment !== 'number') {
        build = v;
        v = segment;
        segment = undefined;
      }

      if (segment !== undefined && typeof segment !== 'number') {
        throw new Error('Bad segment "' + segment + '", must be 0-based integer');
      }

      if (absolute) {
        segments.shift();
      }

      if (segment < 0) {
        // allow negative indexes to address from the end
        segment = Math.max(segments.length + segment, 0);
      }

      if (v === undefined) {
        /*jshint laxbreak: true */
        return segment === undefined
          ? segments
          : segments[segment];
        /*jshint laxbreak: false */
      } else if (segment === null || segments[segment] === undefined) {
        if (isArray(v)) {
          segments = [];
          // collapse empty elements within array
          for (var i=0, l=v.length; i < l; i++) {
            if (!v[i].length && (!segments.length || !segments[segments.length -1].length)) {
              continue;
            }

            if (segments.length && !segments[segments.length -1].length) {
              segments.pop();
            }

            segments.push(trimSlashes(v[i]));
          }
        } else if (v || typeof v === 'string') {
          v = trimSlashes(v);
          if (segments[segments.length -1] === '') {
            // empty trailing elements have to be overwritten
            // to prevent results such as /foo//bar
            segments[segments.length -1] = v;
          } else {
            segments.push(v);
          }
        }
      } else {
        if (v) {
          segments[segment] = trimSlashes(v);
        } else {
          segments.splice(segment, 1);
        }
      }

      if (absolute) {
        segments.unshift('');
      }

      return this.path(segments.join(separator), build);
    };
    p.segmentCoded = function(segment, v, build) {
      var segments, i, l;

      if (typeof segment !== 'number') {
        build = v;
        v = segment;
        segment = undefined;
      }

      if (v === undefined) {
        segments = this.segment(segment, v, build);
        if (!isArray(segments)) {
          segments = segments !== undefined ? URI.decode(segments) : undefined;
        } else {
          for (i = 0, l = segments.length; i < l; i++) {
            segments[i] = URI.decode(segments[i]);
          }
        }

        return segments;
      }

      if (!isArray(v)) {
        v = (typeof v === 'string' || v instanceof String) ? URI.encode(v) : v;
      } else {
        for (i = 0, l = v.length; i < l; i++) {
          v[i] = URI.encode(v[i]);
        }
      }

      return this.segment(segment, v, build);
    };

    // mutating query string
    var q = p.query;
    p.query = function(v, build) {
      if (v === true) {
        return URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
      } else if (typeof v === 'function') {
        var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
        var result = v.call(this, data);
        this._parts.query = URI.buildQuery(result || data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
        this.build(!build);
        return this;
      } else if (v !== undefined && typeof v !== 'string') {
        this._parts.query = URI.buildQuery(v, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
        this.build(!build);
        return this;
      } else {
        return q.call(this, v, build);
      }
    };
    p.setQuery = function(name, value, build) {
      var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);

      if (typeof name === 'string' || name instanceof String) {
        data[name] = value !== undefined ? value : null;
      } else if (typeof name === 'object') {
        for (var key in name) {
          if (hasOwn.call(name, key)) {
            data[key] = name[key];
          }
        }
      } else {
        throw new TypeError('URI.addQuery() accepts an object, string as the name parameter');
      }

      this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
      if (typeof name !== 'string') {
        build = value;
      }

      this.build(!build);
      return this;
    };
    p.addQuery = function(name, value, build) {
      var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
      URI.addQuery(data, name, value === undefined ? null : value);
      this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
      if (typeof name !== 'string') {
        build = value;
      }

      this.build(!build);
      return this;
    };
    p.removeQuery = function(name, value, build) {
      var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
      URI.removeQuery(data, name, value);
      this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
      if (typeof name !== 'string') {
        build = value;
      }

      this.build(!build);
      return this;
    };
    p.hasQuery = function(name, value, withinArray) {
      var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
      return URI.hasQuery(data, name, value, withinArray);
    };
    p.setSearch = p.setQuery;
    p.addSearch = p.addQuery;
    p.removeSearch = p.removeQuery;
    p.hasSearch = p.hasQuery;

    // sanitizing URLs
    p.normalize = function() {
      if (this._parts.urn) {
        return this
          .normalizeProtocol(false)
          .normalizePath(false)
          .normalizeQuery(false)
          .normalizeFragment(false)
          .build();
      }

      return this
        .normalizeProtocol(false)
        .normalizeHostname(false)
        .normalizePort(false)
        .normalizePath(false)
        .normalizeQuery(false)
        .normalizeFragment(false)
        .build();
    };
    p.normalizeProtocol = function(build) {
      if (typeof this._parts.protocol === 'string') {
        this._parts.protocol = this._parts.protocol.toLowerCase();
        this.build(!build);
      }

      return this;
    };
    p.normalizeHostname = function(build) {
      if (this._parts.hostname) {
        if (this.is('IDN') && punycode) {
          this._parts.hostname = punycode.toASCII(this._parts.hostname);
        } else if (this.is('IPv6') && IPv6) {
          this._parts.hostname = IPv6.best(this._parts.hostname);
        }

        this._parts.hostname = this._parts.hostname.toLowerCase();
        this.build(!build);
      }

      return this;
    };
    p.normalizePort = function(build) {
      // remove port of it's the protocol's default
      if (typeof this._parts.protocol === 'string' && this._parts.port === URI.defaultPorts[this._parts.protocol]) {
        this._parts.port = null;
        this.build(!build);
      }

      return this;
    };
    p.normalizePath = function(build) {
      var _path = this._parts.path;
      if (!_path) {
        return this;
      }

      if (this._parts.urn) {
        this._parts.path = URI.recodeUrnPath(this._parts.path);
        this.build(!build);
        return this;
      }

      if (this._parts.path === '/') {
        return this;
      }

      _path = URI.recodePath(_path);

      var _was_relative;
      var _leadingParents = '';
      var _parent, _pos;

      // handle relative paths
      if (_path.charAt(0) !== '/') {
        _was_relative = true;
        _path = '/' + _path;
      }

      // handle relative files (as opposed to directories)
      if (_path.slice(-3) === '/..' || _path.slice(-2) === '/.') {
        _path += '/';
      }

      // resolve simples
      _path = _path
        .replace(/(\/(\.\/)+)|(\/\.$)/g, '/')
        .replace(/\/{2,}/g, '/');

      // remember leading parents
      if (_was_relative) {
        _leadingParents = _path.substring(1).match(/^(\.\.\/)+/) || '';
        if (_leadingParents) {
          _leadingParents = _leadingParents[0];
        }
      }

      // resolve parents
      while (true) {
        _parent = _path.search(/\/\.\.(\/|$)/);
        if (_parent === -1) {
          // no more ../ to resolve
          break;
        } else if (_parent === 0) {
          // top level cannot be relative, skip it
          _path = _path.substring(3);
          continue;
        }

        _pos = _path.substring(0, _parent).lastIndexOf('/');
        if (_pos === -1) {
          _pos = _parent;
        }
        _path = _path.substring(0, _pos) + _path.substring(_parent + 3);
      }

      // revert to relative
      if (_was_relative && this.is('relative')) {
        _path = _leadingParents + _path.substring(1);
      }

      this._parts.path = _path;
      this.build(!build);
      return this;
    };
    p.normalizePathname = p.normalizePath;
    p.normalizeQuery = function(build) {
      if (typeof this._parts.query === 'string') {
        if (!this._parts.query.length) {
          this._parts.query = null;
        } else {
          this.query(URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace));
        }

        this.build(!build);
      }

      return this;
    };
    p.normalizeFragment = function(build) {
      if (!this._parts.fragment) {
        this._parts.fragment = null;
        this.build(!build);
      }

      return this;
    };
    p.normalizeSearch = p.normalizeQuery;
    p.normalizeHash = p.normalizeFragment;

    p.iso8859 = function() {
      // expect unicode input, iso8859 output
      var e = URI.encode;
      var d = URI.decode;

      URI.encode = escape;
      URI.decode = decodeURIComponent;
      try {
        this.normalize();
      } finally {
        URI.encode = e;
        URI.decode = d;
      }
      return this;
    };

    p.unicode = function() {
      // expect iso8859 input, unicode output
      var e = URI.encode;
      var d = URI.decode;

      URI.encode = strictEncodeURIComponent;
      URI.decode = unescape;
      try {
        this.normalize();
      } finally {
        URI.encode = e;
        URI.decode = d;
      }
      return this;
    };

    p.readable = function() {
      var uri = this.clone();
      // removing username, password, because they shouldn't be displayed according to RFC 3986
      uri.username('').password('').normalize();
      var t = '';
      if (uri._parts.protocol) {
        t += uri._parts.protocol + '://';
      }

      if (uri._parts.hostname) {
        if (uri.is('punycode') && punycode) {
          t += punycode.toUnicode(uri._parts.hostname);
          if (uri._parts.port) {
            t += ':' + uri._parts.port;
          }
        } else {
          t += uri.host();
        }
      }

      if (uri._parts.hostname && uri._parts.path && uri._parts.path.charAt(0) !== '/') {
        t += '/';
      }

      t += uri.path(true);
      if (uri._parts.query) {
        var q = '';
        for (var i = 0, qp = uri._parts.query.split('&'), l = qp.length; i < l; i++) {
          var kv = (qp[i] || '').split('=');
          q += '&' + URI.decodeQuery(kv[0], this._parts.escapeQuerySpace)
            .replace(/&/g, '%26');

          if (kv[1] !== undefined) {
            q += '=' + URI.decodeQuery(kv[1], this._parts.escapeQuerySpace)
              .replace(/&/g, '%26');
          }
        }
        t += '?' + q.substring(1);
      }

      t += URI.decodeQuery(uri.hash(), true);
      return t;
    };

    // resolving relative and absolute URLs
    p.absoluteTo = function(base) {
      var resolved = this.clone();
      var properties = ['protocol', 'username', 'password', 'hostname', 'port'];
      var basedir, i, p;

      if (this._parts.urn) {
        throw new Error('URNs do not have any generally defined hierarchical components');
      }

      if (!(base instanceof URI)) {
        base = new URI(base);
      }

      if (resolved._parts.protocol) {
        // Directly returns even if this._parts.hostname is empty.
        return resolved;
      } else {
        resolved._parts.protocol = base._parts.protocol;
      }

      if (this._parts.hostname) {
        return resolved;
      }

      for (i = 0; (p = properties[i]); i++) {
        resolved._parts[p] = base._parts[p];
      }

      if (!resolved._parts.path) {
        resolved._parts.path = base._parts.path;
        if (!resolved._parts.query) {
          resolved._parts.query = base._parts.query;
        }
      } else {
        if (resolved._parts.path.substring(-2) === '..') {
          resolved._parts.path += '/';
        }

        if (resolved.path().charAt(0) !== '/') {
          basedir = base.directory();
          basedir = basedir ? basedir : base.path().indexOf('/') === 0 ? '/' : '';
          resolved._parts.path = (basedir ? (basedir + '/') : '') + resolved._parts.path;
          resolved.normalizePath();
        }
      }

      resolved.build();
      return resolved;
    };
    p.relativeTo = function(base) {
      var relative = this.clone().normalize();
      var relativeParts, baseParts, common, relativePath, basePath;

      if (relative._parts.urn) {
        throw new Error('URNs do not have any generally defined hierarchical components');
      }

      base = new URI(base).normalize();
      relativeParts = relative._parts;
      baseParts = base._parts;
      relativePath = relative.path();
      basePath = base.path();

      if (relativePath.charAt(0) !== '/') {
        throw new Error('URI is already relative');
      }

      if (basePath.charAt(0) !== '/') {
        throw new Error('Cannot calculate a URI relative to another relative URI');
      }

      if (relativeParts.protocol === baseParts.protocol) {
        relativeParts.protocol = null;
      }

      if (relativeParts.username !== baseParts.username || relativeParts.password !== baseParts.password) {
        return relative.build();
      }

      if (relativeParts.protocol !== null || relativeParts.username !== null || relativeParts.password !== null) {
        return relative.build();
      }

      if (relativeParts.hostname === baseParts.hostname && relativeParts.port === baseParts.port) {
        relativeParts.hostname = null;
        relativeParts.port = null;
      } else {
        return relative.build();
      }

      if (relativePath === basePath) {
        relativeParts.path = '';
        return relative.build();
      }

      // determine common sub path
      common = URI.commonPath(relativePath, basePath);

      // If the paths have nothing in common, return a relative URL with the absolute path.
      if (!common) {
        return relative.build();
      }

      var parents = baseParts.path
        .substring(common.length)
        .replace(/[^\/]*$/, '')
        .replace(/.*?\//g, '../');

      relativeParts.path = (parents + relativeParts.path.substring(common.length)) || './';

      return relative.build();
    };

    // comparing URIs
    p.equals = function(uri) {
      var one = this.clone();
      var two = new URI(uri);
      var one_map = {};
      var two_map = {};
      var checked = {};
      var one_query, two_query, key;

      one.normalize();
      two.normalize();

      // exact match
      if (one.toString() === two.toString()) {
        return true;
      }

      // extract query string
      one_query = one.query();
      two_query = two.query();
      one.query('');
      two.query('');

      // definitely not equal if not even non-query parts match
      if (one.toString() !== two.toString()) {
        return false;
      }

      // query parameters have the same length, even if they're permuted
      if (one_query.length !== two_query.length) {
        return false;
      }

      one_map = URI.parseQuery(one_query, this._parts.escapeQuerySpace);
      two_map = URI.parseQuery(two_query, this._parts.escapeQuerySpace);

      for (key in one_map) {
        if (hasOwn.call(one_map, key)) {
          if (!isArray(one_map[key])) {
            if (one_map[key] !== two_map[key]) {
              return false;
            }
          } else if (!arraysEqual(one_map[key], two_map[key])) {
            return false;
          }

          checked[key] = true;
        }
      }

      for (key in two_map) {
        if (hasOwn.call(two_map, key)) {
          if (!checked[key]) {
            // two contains a parameter not present in one
            return false;
          }
        }
      }

      return true;
    };

    // state
    p.preventInvalidHostname = function(v) {
      this._parts.preventInvalidHostname = !!v;
      return this;
    };

    p.duplicateQueryParameters = function(v) {
      this._parts.duplicateQueryParameters = !!v;
      return this;
    };

    p.escapeQuerySpace = function(v) {
      this._parts.escapeQuerySpace = !!v;
      return this;
    };

    return URI;
  }));
  });

  /**
   * Given a relative Uri and a base Uri, returns the absolute Uri of the relative Uri.
   * @function
   *
   * @param {String} relative The relative Uri.
   * @param {String} [base] The base Uri.
   * @returns {String} The absolute Uri of the given relative Uri.
   *
   * @example
   * //absolute Uri will be "https://test.com/awesome.png";
   * const absoluteUri = Cesium.getAbsoluteUri('awesome.png', 'https://test.com');
   */
  function getAbsoluteUri(relative, base) {
    let documentObject;
    if (typeof document !== "undefined") {
      documentObject = document;
    }

    return getAbsoluteUri._implementation(relative, base, documentObject);
  }

  getAbsoluteUri._implementation = function (relative, base, documentObject) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(relative)) {
      throw new DeveloperError("relative uri is required.");
    }
    //>>includeEnd('debug');

    if (!defined(base)) {
      if (typeof documentObject === "undefined") {
        return relative;
      }
      base = defaultValue(documentObject.baseURI, documentObject.location.href);
    }

    const relativeUri = new URI(relative);
    if (relativeUri.scheme() !== "") {
      return relativeUri.toString();
    }
    return relativeUri.absoluteTo(base).toString();
  };

  /**
   * @private
   */
  function appendForwardSlash(url) {
    if (url.length === 0 || url[url.length - 1] !== "/") {
      url = `${url}/`;
    }
    return url;
  }

  /**
   * Clones an object, returning a new object containing the same properties.
   *
   * @function
   *
   * @param {Object} object The object to clone.
   * @param {Boolean} [deep=false] If true, all properties will be deep cloned recursively.
   * @returns {Object} The cloned object.
   */
  function clone$1(object, deep) {
    if (object === null || typeof object !== "object") {
      return object;
    }

    deep = defaultValue(deep, false);

    const result = new object.constructor();
    for (const propertyName in object) {
      if (object.hasOwnProperty(propertyName)) {
        let value = object[propertyName];
        if (deep) {
          value = clone$1(value, deep);
        }
        result[propertyName] = value;
      }
    }

    return result;
  }

  /**
   * Merges two objects, copying their properties onto a new combined object. When two objects have the same
   * property, the value of the property on the first object is used.  If either object is undefined,
   * it will be treated as an empty object.
   *
   * @example
   * const object1 = {
   *     propOne : 1,
   *     propTwo : {
   *         value1 : 10
   *     }
   * }
   * const object2 = {
   *     propTwo : 2
   * }
   * const final = Cesium.combine(object1, object2);
   *
   * // final === {
   * //     propOne : 1,
   * //     propTwo : {
   * //         value1 : 10
   * //     }
   * // }
   *
   * @param {Object} [object1] The first object to merge.
   * @param {Object} [object2] The second object to merge.
   * @param {Boolean} [deep=false] Perform a recursive merge.
   * @returns {Object} The combined object containing all properties from both objects.
   *
   * @function
   */
  function combine$2(object1, object2, deep) {
    deep = defaultValue(deep, false);

    const result = {};

    const object1Defined = defined(object1);
    const object2Defined = defined(object2);
    let property;
    let object1Value;
    let object2Value;
    if (object1Defined) {
      for (property in object1) {
        if (object1.hasOwnProperty(property)) {
          object1Value = object1[property];
          if (
            object2Defined &&
            deep &&
            typeof object1Value === "object" &&
            object2.hasOwnProperty(property)
          ) {
            object2Value = object2[property];
            if (typeof object2Value === "object") {
              result[property] = combine$2(object1Value, object2Value, deep);
            } else {
              result[property] = object1Value;
            }
          } else {
            result[property] = object1Value;
          }
        }
      }
    }
    if (object2Defined) {
      for (property in object2) {
        if (
          object2.hasOwnProperty(property) &&
          !result.hasOwnProperty(property)
        ) {
          object2Value = object2[property];
          result[property] = object2Value;
        }
      }
    }
    return result;
  }

  /**
   * A function used to resolve a promise upon completion .
   * @callback defer.resolve
   *
   * @param {*} value The resulting value.
   */

  /**
   * A function used to reject a promise upon failure.
   * @callback defer.reject
   *
   * @param {*} error The error.
   */

  /**
   * An object which contains a promise object, and functions to resolve or reject the promise.
   *
   * @typedef {Object} defer.deferred
   * @property {defer.resolve} resolve Resolves the promise when called.
   * @property {defer.reject} reject Rejects the promise when called.
   * @property {Promise} promise Promise object.
   */

  /**
   * Creates a deferred object, containing a promise object, and functions to resolve or reject the promise.
   * @returns {defer.deferred}
   * @private
   */
  function defer() {
    let resolve;
    let reject;
    const promise = new Promise(function (res, rej) {
      resolve = res;
      reject = rej;
    });

    return {
      resolve: resolve,
      reject: reject,
      promise: promise,
    };
  }

  /**
   * Given a URI, returns the base path of the URI.
   * @function
   *
   * @param {String} uri The Uri.
   * @param {Boolean} [includeQuery = false] Whether or not to include the query string and fragment form the uri
   * @returns {String} The base path of the Uri.
   *
   * @example
   * // basePath will be "/Gallery/";
   * const basePath = Cesium.getBaseUri('/Gallery/simple.czml?value=true&example=false');
   *
   * // basePath will be "/Gallery/?value=true&example=false";
   * const basePath = Cesium.getBaseUri('/Gallery/simple.czml?value=true&example=false', true);
   */
  function getBaseUri(uri, includeQuery) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(uri)) {
      throw new DeveloperError("uri is required.");
    }
    //>>includeEnd('debug');

    let basePath = "";
    const i = uri.lastIndexOf("/");
    if (i !== -1) {
      basePath = uri.substring(0, i + 1);
    }

    if (!includeQuery) {
      return basePath;
    }

    uri = new URI(uri);
    if (uri.query().length !== 0) {
      basePath += `?${uri.query()}`;
    }
    if (uri.fragment().length !== 0) {
      basePath += `#${uri.fragment()}`;
    }

    return basePath;
  }

  /**
   * Given a URI, returns the extension of the URI.
   * @function getExtensionFromUri
   *
   * @param {String} uri The Uri.
   * @returns {String} The extension of the Uri.
   *
   * @example
   * //extension will be "czml";
   * const extension = Cesium.getExtensionFromUri('/Gallery/simple.czml?value=true&example=false');
   */
  function getExtensionFromUri(uri) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(uri)) {
      throw new DeveloperError("uri is required.");
    }
    //>>includeEnd('debug');

    const uriObject = new URI(uri);
    uriObject.normalize();
    let path = uriObject.path();
    let index = path.lastIndexOf("/");
    if (index !== -1) {
      path = path.substr(index + 1);
    }
    index = path.lastIndexOf(".");
    if (index === -1) {
      path = "";
    } else {
      path = path.substr(index + 1);
    }
    return path;
  }

  const context2DsByWidthAndHeight = {};

  /**
   * Extract a pixel array from a loaded image.  Draws the image
   * into a canvas so it can read the pixels back.
   *
   * @function getImagePixels
   *
   * @param {HTMLImageElement|ImageBitmap} image The image to extract pixels from.
   * @param {Number} width The width of the image. If not defined, then image.width is assigned.
   * @param {Number} height The height of the image. If not defined, then image.height is assigned.
   * @returns {ImageData} The pixels of the image.
   */
  function getImagePixels(image, width, height) {
    if (!defined(width)) {
      width = image.width;
    }
    if (!defined(height)) {
      height = image.height;
    }

    let context2DsByHeight = context2DsByWidthAndHeight[width];
    if (!defined(context2DsByHeight)) {
      context2DsByHeight = {};
      context2DsByWidthAndHeight[width] = context2DsByHeight;
    }

    let context2d = context2DsByHeight[height];
    if (!defined(context2d)) {
      const canvas = document.createElement("canvas");
      canvas.width = width;
      canvas.height = height;
      context2d = canvas.getContext("2d");
      context2d.globalCompositeOperation = "copy";
      context2DsByHeight[height] = context2d;
    }

    context2d.drawImage(image, 0, 0, width, height);
    return context2d.getImageData(0, 0, width, height).data;
  }

  const blobUriRegex = /^blob:/i;

  /**
   * Determines if the specified uri is a blob uri.
   *
   * @function isBlobUri
   *
   * @param {String} uri The uri to test.
   * @returns {Boolean} true when the uri is a blob uri; otherwise, false.
   *
   * @private
   */
  function isBlobUri(uri) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("uri", uri);
    //>>includeEnd('debug');

    return blobUriRegex.test(uri);
  }

  let a$2;

  /**
   * Given a URL, determine whether that URL is considered cross-origin to the current page.
   *
   * @private
   */
  function isCrossOriginUrl(url) {
    if (!defined(a$2)) {
      a$2 = document.createElement("a");
    }

    // copy window location into the anchor to get consistent results
    // when the port is default for the protocol (e.g. 80 for HTTP)
    a$2.href = window.location.href;

    // host includes both hostname and port if the port is not standard
    const host = a$2.host;
    const protocol = a$2.protocol;

    a$2.href = url;
    // IE only absolutizes href on get, not set
    // eslint-disable-next-line no-self-assign
    a$2.href = a$2.href;

    return protocol !== a$2.protocol || host !== a$2.host;
  }

  const dataUriRegex$2 = /^data:/i;

  /**
   * Determines if the specified uri is a data uri.
   *
   * @function isDataUri
   *
   * @param {String} uri The uri to test.
   * @returns {Boolean} true when the uri is a data uri; otherwise, false.
   *
   * @private
   */
  function isDataUri(uri) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("uri", uri);
    //>>includeEnd('debug');

    return dataUriRegex$2.test(uri);
  }

  /**
   * @private
   */
  function loadAndExecuteScript(url) {
    const deferred = defer();
    const script = document.createElement("script");
    script.async = true;
    script.src = url;

    const head = document.getElementsByTagName("head")[0];
    script.onload = function () {
      script.onload = undefined;
      head.removeChild(script);
      deferred.resolve();
    };
    script.onerror = function (e) {
      deferred.reject(e);
    };

    head.appendChild(script);

    return deferred.promise;
  }

  /**
   * Converts an object representing a set of name/value pairs into a query string,
   * with names and values encoded properly for use in a URL.  Values that are arrays
   * will produce multiple values with the same name.
   * @function objectToQuery
   *
   * @param {Object} obj The object containing data to encode.
   * @returns {String} An encoded query string.
   *
   *
   * @example
   * const str = Cesium.objectToQuery({
   *     key1 : 'some value',
   *     key2 : 'a/b',
   *     key3 : ['x', 'y']
   * });
   *
   * @see queryToObject
   * // str will be:
   * // 'key1=some%20value&key2=a%2Fb&key3=x&key3=y'
   */
  function objectToQuery(obj) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(obj)) {
      throw new DeveloperError("obj is required.");
    }
    //>>includeEnd('debug');

    let result = "";
    for (const propName in obj) {
      if (obj.hasOwnProperty(propName)) {
        const value = obj[propName];

        const part = `${encodeURIComponent(propName)}=`;
        if (Array.isArray(value)) {
          for (let i = 0, len = value.length; i < len; ++i) {
            result += `${part + encodeURIComponent(value[i])}&`;
          }
        } else {
          result += `${part + encodeURIComponent(value)}&`;
        }
      }
    }

    // trim last &
    result = result.slice(0, -1);

    // This function used to replace %20 with + which is more compact and readable.
    // However, some servers didn't properly handle + as a space.
    // https://github.com/CesiumGS/cesium/issues/2192

    return result;
  }

  /**
   * Parses a query string into an object, where the keys and values of the object are the
   * name/value pairs from the query string, decoded. If a name appears multiple times,
   * the value in the object will be an array of values.
   * @function queryToObject
   *
   * @param {String} queryString The query string.
   * @returns {Object} An object containing the parameters parsed from the query string.
   *
   *
   * @example
   * const obj = Cesium.queryToObject('key1=some%20value&key2=a%2Fb&key3=x&key3=y');
   * // obj will be:
   * // {
   * //   key1 : 'some value',
   * //   key2 : 'a/b',
   * //   key3 : ['x', 'y']
   * // }
   *
   * @see objectToQuery
   */
  function queryToObject(queryString) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(queryString)) {
      throw new DeveloperError("queryString is required.");
    }
    //>>includeEnd('debug');

    const result = {};
    if (queryString === "") {
      return result;
    }
    const parts = queryString.replace(/\+/g, "%20").split(/[&;]/);
    for (let i = 0, len = parts.length; i < len; ++i) {
      const subparts = parts[i].split("=");

      const name = decodeURIComponent(subparts[0]);
      let value = subparts[1];
      if (defined(value)) {
        value = decodeURIComponent(value);
      } else {
        value = "";
      }

      const resultValue = result[name];
      if (typeof resultValue === "string") {
        // expand the single value to an array
        result[name] = [resultValue, value];
      } else if (Array.isArray(resultValue)) {
        resultValue.push(value);
      } else {
        result[name] = value;
      }
    }
    return result;
  }

  /**
   * State of the request.
   *
   * @enum {Number}
   */
  const RequestState = {
    /**
     * Initial unissued state.
     *
     * @type Number
     * @constant
     */
    UNISSUED: 0,

    /**
     * Issued but not yet active. Will become active when open slots are available.
     *
     * @type Number
     * @constant
     */
    ISSUED: 1,

    /**
     * Actual http request has been sent.
     *
     * @type Number
     * @constant
     */
    ACTIVE: 2,

    /**
     * Request completed successfully.
     *
     * @type Number
     * @constant
     */
    RECEIVED: 3,

    /**
     * Request was cancelled, either explicitly or automatically because of low priority.
     *
     * @type Number
     * @constant
     */
    CANCELLED: 4,

    /**
     * Request failed.
     *
     * @type Number
     * @constant
     */
    FAILED: 5,
  };
  var RequestState$1 = Object.freeze(RequestState);

  /**
   * An enum identifying the type of request. Used for finer grained logging and priority sorting.
   *
   * @enum {Number}
   */
  const RequestType = {
    /**
     * Terrain request.
     *
     * @type Number
     * @constant
     */
    TERRAIN: 0,

    /**
     * Imagery request.
     *
     * @type Number
     * @constant
     */
    IMAGERY: 1,

    /**
     * 3D Tiles request.
     *
     * @type Number
     * @constant
     */
    TILES3D: 2,

    /**
     * Other request.
     *
     * @type Number
     * @constant
     */
    OTHER: 3,
  };
  var RequestType$1 = Object.freeze(RequestType);

  /**
   * Stores information for making a request. In general this does not need to be constructed directly.
   *
   * @alias Request
   * @constructor

   * @param {Object} [options] An object with the following properties:
   * @param {String} [options.url] The url to request.
   * @param {Request.RequestCallback} [options.requestFunction] The function that makes the actual data request.
   * @param {Request.CancelCallback} [options.cancelFunction] The function that is called when the request is cancelled.
   * @param {Request.PriorityCallback} [options.priorityFunction] The function that is called to update the request's priority, which occurs once per frame.
   * @param {Number} [options.priority=0.0] The initial priority of the request.
   * @param {Boolean} [options.throttle=false] Whether to throttle and prioritize the request. If false, the request will be sent immediately. If true, the request will be throttled and sent based on priority.
   * @param {Boolean} [options.throttleByServer=false] Whether to throttle the request by server.
   * @param {RequestType} [options.type=RequestType.OTHER] The type of request.
   */
  function Request(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const throttleByServer = defaultValue(options.throttleByServer, false);
    const throttle = defaultValue(options.throttle, false);

    /**
     * The URL to request.
     *
     * @type {String}
     */
    this.url = options.url;

    /**
     * The function that makes the actual data request.
     *
     * @type {Request.RequestCallback}
     */
    this.requestFunction = options.requestFunction;

    /**
     * The function that is called when the request is cancelled.
     *
     * @type {Request.CancelCallback}
     */
    this.cancelFunction = options.cancelFunction;

    /**
     * The function that is called to update the request's priority, which occurs once per frame.
     *
     * @type {Request.PriorityCallback}
     */
    this.priorityFunction = options.priorityFunction;

    /**
     * Priority is a unit-less value where lower values represent higher priority.
     * For world-based objects, this is usually the distance from the camera.
     * A request that does not have a priority function defaults to a priority of 0.
     *
     * If priorityFunction is defined, this value is updated every frame with the result of that call.
     *
     * @type {Number}
     * @default 0.0
     */
    this.priority = defaultValue(options.priority, 0.0);

    /**
     * Whether to throttle and prioritize the request. If false, the request will be sent immediately. If true, the
     * request will be throttled and sent based on priority.
     *
     * @type {Boolean}
     * @readonly
     *
     * @default false
     */
    this.throttle = throttle;

    /**
     * Whether to throttle the request by server. Browsers typically support about 6-8 parallel connections
     * for HTTP/1 servers, and an unlimited amount of connections for HTTP/2 servers. Setting this value
     * to <code>true</code> 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 = 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 (!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 (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
   * @template Listener extends (...args: any[]) => void = (...args: any[]) => void
   * @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 <code>this</code> pointer
   * in which the function will execute.
   *
   * @param {Listener} listener The function to be executed when the event is raised.
   * @param {Object} [scope] An optional object scope to serve as the <code>this</code>
   *        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);
    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 {Listener} listener The function to be unregistered.
   * @param {Object} [scope] The scope that was originally passed to addEventListener.
   * @returns {Boolean} <code>true</code> if the listener was removed; <code>false</code> 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);
    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 {...Parameters<Listener>} 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 (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);
    Check.typeOf.object("options", options);
    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);
        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$3(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 = 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 = 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$3(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);
    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$3(array, index, parent);
        index = parent;
      } else {
        break;
      }
    }

    let removedElement;

    if (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 = defaultValue(index, 0);
    if (this._length === 0) {
      return undefined;
    }
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number.lessThan("index", index, this._length);
    //>>includeEnd('debug');

    const array = this._array;
    const root = array[index];
    swap$3(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 <code>maximumRequestsPerServer</code>
   * @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 (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 <code>desiredRequests</code> more requests.
   * @private
   */
  RequestScheduler.serverHasOpenSlots = function (serverKey, desiredRequests) {
    desiredRequests = defaultValue(desiredRequests, 1);

    const maxRequests = 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} <code>true</code> if the heap has enough available slots to meet the desiredRequests. <code>false</code> 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 = 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))
      .catch(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 (defined(request.deferred)) {
      const deferred = request.deferred;
      request.deferred = undefined;
      deferred.reject();
    }

    if (active) {
      --statistics.numberOfActiveRequests;
      --numberOfActiveRequestsByServer[request.serverKey];
      ++statistics.numberOfCancelledActiveRequests;
    }

    if (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);
    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 (!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);
    Check.typeOf.object("request", request);
    Check.typeOf.string("request.url", request.url);
    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 (!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 (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 (!defined(host)) {
      throw new DeveloperError("host is required.");
    }
    if (!defined(port) || port <= 0) {
      throw new DeveloperError("port is required to be greater than 0.");
    }
    //>>includeEnd('debug');

    const authority = `${host.toLowerCase()}:${port}`;
    if (!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 (!defined(host)) {
      throw new DeveloperError("host is required.");
    }
    if (!defined(port) || port <= 0) {
      throw new DeveloperError("port is required to be greater than 0.");
    }
    //>>includeEnd('debug');

    const authority = `${host.toLowerCase()}:${port}`;
    if (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 (!defined(url)) {
      throw new DeveloperError("url is required.");
    }
    //>>includeEnd('debug');
    const authority = getAuthority(url);
    if (defined(authority) && 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 && !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 (!defined(val)) {
      return defaultVal;
    }

    return defined(val.clone) ? val.clone() : clone$1(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("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$2(q1, q2);
    }

    const result = clone$1(q1, true);
    for (const param in q2) {
      if (q2.hasOwnProperty(param)) {
        let value = result[param];
        const q2Value = q2[param];
        if (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;
  }

  /**
   * @typedef {Object} Resource.ConstructorOptions
   *
   * Initialization options for the Resource constructor
   *
   * @property {String} url The url of the resource.
   * @property {Object} [queryParameters] An object containing query parameters that will be sent when retrieving the resource.
   * @property {Object} [templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
   * @property {Object} [headers={}] Additional HTTP headers that will be sent.
   * @property {Proxy} [proxy] A proxy to be used when loading the resource.
   * @property {Resource.RetryCallback} [retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
   * @property {Number} [retryAttempts=0] The number of times the retryCallback should be called before giving up.
   * @property {Request} [request] A Request object that will be used. Intended for internal use only.
   */

  /**
   * 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|Resource.ConstructorOptions} options A url or an object describing initialization options
   *
   * @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;
   *       })
   *       .catch(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 = defaultValue(options, defaultValue.EMPTY_OBJECT);
    if (typeof options === "string") {
      options = {
        url: options,
      };
    }

    //>>includeStart('debug', pragmas.debug);
    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 = 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 = 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 {Promise<Boolean>} A promise that resolves to true if this browser supports creating an ImageBitmap with options.
   *
   * @private
   */
  Resource.supportsImageBitmapOptions = function () {
    // Until the HTML folks figure out what to do about this, we need to actually try loading an image to
    // know if this browser supports passing options to the createImageBitmap function.
    // https://github.com/whatwg/html/pull/4248
    //
    // We also need to check whether the colorSpaceConversion option is supported.
    // We do this by loading a PNG with an embedded color profile, first with
    // colorSpaceConversion: "none" and then with colorSpaceConversion: "default".
    // If the pixel color is different then we know the option is working.
    // As of Webkit 17612.3.6.1.6 the createImageBitmap promise resolves but the
    // option is not actually supported.
    if (defined(supportsImageBitmapOptionsPromise)) {
      return supportsImageBitmapOptionsPromise;
    }

    if (typeof createImageBitmap !== "function") {
      supportsImageBitmapOptionsPromise = Promise.resolve(false);
      return supportsImageBitmapOptionsPromise;
    }

    const imageDataUri =
      "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAABGdBTUEAAE4g3rEiDgAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAADElEQVQI12Ng6GAAAAEUAIngE3ZiAAAAAElFTkSuQmCC";

    supportsImageBitmapOptionsPromise = Resource.fetchBlob({
      url: imageDataUri,
    })
      .then(function (blob) {
        const imageBitmapOptions = {
          imageOrientation: "flipY", // default is "none"
          premultiplyAlpha: "none", // default is "default"
          colorSpaceConversion: "none", // default is "default"
        };
        return Promise.all([
          createImageBitmap(blob, imageBitmapOptions),
          createImageBitmap(blob),
        ]);
      })
      .then(function (imageBitmaps) {
        // Check whether the colorSpaceConversion option had any effect on the green channel
        const colorWithOptions = getImagePixels(imageBitmaps[0]);
        const colorWithDefaults = getImagePixels(imageBitmaps[1]);
        return colorWithOptions[1] !== colorWithDefaults[1];
      })
      .catch(function () {
        return false;
      });

    return supportsImageBitmapOptionsPromise;
  };

  Object.defineProperties(Resource, {
    /**
     * Returns true if blobs are supported.
     *
     * @memberof Resource
     * @type {Boolean}
     *
     * @readonly
     */
    isBlobSupported: {
      get: function () {
        return xhrBlobSupported;
      },
    },
  });

  Object.defineProperties(Resource.prototype, {
    /**
     * Query parameters appended to the url.
     *
     * @memberof Resource.prototype
     * @type {Object}
     *
     * @readonly
     */
    queryParameters: {
      get: function () {
        return this._queryParameters;
      },
    },

    /**
     * The key/value pairs used to replace template parameters in the url.
     *
     * @memberof Resource.prototype
     * @type {Object}
     *
     * @readonly
     */
    templateValues: {
      get: function () {
        return this._templateValues;
      },
    },

    /**
     * The url to the resource with template values replaced, query string appended and encoded by proxy if one was set.
     *
     * @memberof Resource.prototype
     * @type {String}
     */
    url: {
      get: function () {
        return this.getUrlComponent(true, true);
      },
      set: function (value) {
        const uri = new URI(value);

        parseQuery(uri, this, false);

        // Remove the fragment as it's not sent with a request
        uri.fragment("");

        this._url = uri.toString();
      },
    },

    /**
     * The file extension of the resource.
     *
     * @memberof Resource.prototype
     * @type {String}
     *
     * @readonly
     */
    extension: {
      get: function () {
        return getExtensionFromUri(this._url);
      },
    },

    /**
     * True if the Resource refers to a data URI.
     *
     * @memberof Resource.prototype
     * @type {Boolean}
     */
    isDataUri: {
      get: function () {
        return isDataUri(this._url);
      },
    },

    /**
     * True if the Resource refers to a blob URI.
     *
     * @memberof Resource.prototype
     * @type {Boolean}
     */
    isBlobUri: {
      get: function () {
        return isBlobUri(this._url);
      },
    },

    /**
     * True if the Resource refers to a cross origin URL.
     *
     * @memberof Resource.prototype
     * @type {Boolean}
     */
    isCrossOriginUrl: {
      get: function () {
        return isCrossOriginUrl(this._url);
      },
    },

    /**
     * True if the Resource has request headers. This is equivalent to checking if the headers property has any keys.
     *
     * @memberof Resource.prototype
     * @type {Boolean}
     */
    hasHeaders: {
      get: function () {
        return Object.keys(this.headers).length > 0;
      },
    },
  });

  /**
   * Override Object#toString so that implicit string conversion gives the
   * complete URL represented by this Resource.
   *
   * @returns {String} The URL represented by this Resource
   */
  Resource.prototype.toString = function () {
    return this.getUrlComponent(true, true);
  };

  /**
   * Returns the url, optional with the query string and processed by a proxy.
   *
   * @param {Boolean} [query=false] If true, the query string is included.
   * @param {Boolean} [proxy=false] If true, the url is processed by the proxy object, if defined.
   *
   * @returns {String} The url with all the requested components.
   */
  Resource.prototype.getUrlComponent = function (query, proxy) {
    if (this.isDataUri) {
      return this._url;
    }

    const uri = new URI(this._url);

    if (query) {
      stringifyQuery(uri, this);
    }

    // objectToQuery escapes the placeholders.  Undo that.
    let url = uri.toString().replace(/%7B/g, "{").replace(/%7D/g, "}");

    const templateValues = this._templateValues;
    url = url.replace(/{(.*?)}/g, function (match, key) {
      const replacement = templateValues[key];
      if (defined(replacement)) {
        // use the replacement value from templateValues if there is one...
        return encodeURIComponent(replacement);
      }
      // otherwise leave it unchanged
      return match;
    });

    if (proxy && defined(this.proxy)) {
      url = this.proxy.getURL(url);
    }
    return url;
  };

  /**
   * Combines the specified object and the existing query parameters. This allows you to add many parameters at once,
   *  as opposed to adding them one at a time to the queryParameters property. If a value is already set, it will be replaced with the new value.
   *
   * @param {Object} params The query parameters
   * @param {Boolean} [useAsDefault=false] If true the params will be used as the default values, so they will only be set if they are undefined.
   */
  Resource.prototype.setQueryParameters = function (params, useAsDefault) {
    if (useAsDefault) {
      this._queryParameters = combineQueryParameters(
        this._queryParameters,
        params,
        false
      );
    } else {
      this._queryParameters = combineQueryParameters(
        params,
        this._queryParameters,
        false
      );
    }
  };

  /**
   * Combines the specified object and the existing query parameters. This allows you to add many parameters at once,
   *  as opposed to adding them one at a time to the queryParameters property.
   *
   * @param {Object} params The query parameters
   */
  Resource.prototype.appendQueryParameters = function (params) {
    this._queryParameters = combineQueryParameters(
      params,
      this._queryParameters,
      true
    );
  };

  /**
   * Combines the specified object and the existing template values. This allows you to add many values at once,
   *  as opposed to adding them one at a time to the templateValues property. If a value is already set, it will become an array and the new value will be appended.
   *
   * @param {Object} template The template values
   * @param {Boolean} [useAsDefault=false] If true the values will be used as the default values, so they will only be set if they are undefined.
   */
  Resource.prototype.setTemplateValues = function (template, useAsDefault) {
    if (useAsDefault) {
      this._templateValues = combine$2(this._templateValues, template);
    } else {
      this._templateValues = combine$2(template, this._templateValues);
    }
  };

  /**
   * Returns a resource relative to the current instance. All properties remain the same as the current instance unless overridden in options.
   *
   * @param {Object} options An object with the following properties
   * @param {String} [options.url]  The url that will be resolved relative to the url of the current instance.
   * @param {Object} [options.queryParameters] An object containing query parameters that will be combined with those of the current instance.
   * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}). These will be combined with those of the current instance.
   * @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 loading the resource fails.
   * @param {Number} [options.retryAttempts] 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.preserveQueryParameters=false] If true, this will keep all query parameters from the current resource and derived resource. If false, derived parameters will replace those of the current resource.
   *
   * @returns {Resource} The resource derived from the current one.
   */
  Resource.prototype.getDerivedResource = function (options) {
    const resource = this.clone();
    resource._retryCount = 0;

    if (defined(options.url)) {
      const uri = new URI(options.url);

      const preserveQueryParameters = defaultValue(
        options.preserveQueryParameters,
        false
      );
      parseQuery(uri, resource, true, preserveQueryParameters);

      // Remove the fragment as it's not sent with a request
      uri.fragment("");

      if (uri.scheme() !== "") {
        resource._url = uri.toString();
      } else {
        resource._url = uri
          .absoluteTo(new URI(getAbsoluteUri(this._url)))
          .toString();
      }
    }

    if (defined(options.queryParameters)) {
      resource._queryParameters = combine$2(
        options.queryParameters,
        resource._queryParameters
      );
    }
    if (defined(options.templateValues)) {
      resource._templateValues = combine$2(
        options.templateValues,
        resource.templateValues
      );
    }
    if (defined(options.headers)) {
      resource.headers = combine$2(options.headers, resource.headers);
    }
    if (defined(options.proxy)) {
      resource.proxy = options.proxy;
    }
    if (defined(options.request)) {
      resource.request = options.request;
    }
    if (defined(options.retryCallback)) {
      resource.retryCallback = options.retryCallback;
    }
    if (defined(options.retryAttempts)) {
      resource.retryAttempts = options.retryAttempts;
    }

    return resource;
  };

  /**
   * Called when a resource fails to load. This will call the retryCallback function if defined until retryAttempts is reached.
   *
   * @param {Error} [error] The error that was encountered.
   *
   * @returns {Promise<Boolean>} A promise to a boolean, that if true will cause the resource request to be retried.
   *
   * @private
   */
  Resource.prototype.retryOnError = function (error) {
    const retryCallback = this.retryCallback;
    if (
      typeof retryCallback !== "function" ||
      this._retryCount >= this.retryAttempts
    ) {
      return Promise.resolve(false);
    }

    const that = this;
    return Promise.resolve(retryCallback(this, error)).then(function (result) {
      ++that._retryCount;

      return result;
    });
  };

  /**
   * Duplicates a Resource instance.
   *
   * @param {Resource} [result] The object onto which to store the result.
   *
   * @returns {Resource} The modified result parameter or a new Resource instance if one was not provided.
   */
  Resource.prototype.clone = function (result) {
    if (!defined(result)) {
      result = new Resource({
        url: this._url,
      });
    }

    result._url = this._url;
    result._queryParameters = clone$1(this._queryParameters);
    result._templateValues = clone$1(this._templateValues);
    result.headers = clone$1(this.headers);
    result.proxy = this.proxy;
    result.retryCallback = this.retryCallback;
    result.retryAttempts = this.retryAttempts;
    result._retryCount = 0;
    result.request = this.request.clone();

    return result;
  };

  /**
   * Returns the base path of the Resource.
   *
   * @param {Boolean} [includeQuery = false] Whether or not to include the query string and fragment form the uri
   *
   * @returns {String} The base URI of the resource
   */
  Resource.prototype.getBaseUri = function (includeQuery) {
    return getBaseUri(this.getUrlComponent(includeQuery), includeQuery);
  };

  /**
   * Appends a forward slash to the URL.
   */
  Resource.prototype.appendForwardSlash = function () {
    this._url = appendForwardSlash(this._url);
  };

  /**
   * Asynchronously loads the resource as raw binary data.  Returns a promise that will resolve to
   * an ArrayBuffer 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.<ArrayBuffer>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> 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
   * }).catch(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.<ArrayBuffer>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> 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.<Blob>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> 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
   * }).catch(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.<Blob>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> 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 <code>preferImageBitmap</code> is true and the browser supports <code>createImageBitmap</code> 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 <code>ImageBitmap</code> is returned.
   * @param {Boolean} [options.flipY=false] If true, image will be vertically flipped during decode. Only applies if the browser supports <code>createImageBitmap</code>.
   * @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 <code>createImageBitmap</code>.
   * @returns {Promise.<ImageBitmap|HTMLImageElement>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> 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
   * }).catch(function(error) {
   *     // an error occurred
   * });
   *
   * // load several images in parallel
   * Promise.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 = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const preferImageBitmap = defaultValue(options.preferImageBitmap, false);
    const preferBlob = defaultValue(options.preferBlob, false);
    const flipY = defaultValue(options.flipY, false);
    const skipColorSpaceConversion = 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 (!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 (!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 (!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;
      })
      .catch(function (error) {
        if (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 Promise.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 <code>ImageBitmap</code> is returned.
   * @param {Boolean} [options.flipY] If true, image will be vertically flipped during decode. Only applies if the browser supports <code>createImageBitmap</code>.
   * @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 <code>createImageBitmap</code>.
   * @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 = defer();
      Resource._Implementations.createImage(
        request,
        crossOrigin,
        deferred,
        flipY,
        skipColorSpaceConversion,
        preferImageBitmap
      );

      return deferred.promise;
    };

    const promise = RequestScheduler.request(request);
    if (!defined(promise)) {
      return;
    }

    return promise.catch(function (e) {
      // Don't retry cancelled or otherwise aborted requests
      if (request.state !== RequestState$1.FAILED) {
        return Promise.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 Promise.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 <code>createImageBitmap</code>.
   * @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 <code>ImageBitmap</code> 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 <code>createImageBitmap</code>.
   * @returns {Promise.<ImageBitmap|HTMLImageElement>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> 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.<String>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> 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
   * }).catch(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.<String>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
   */
  Resource.fetchText = function (options) {
    const resource = new Resource(options);
    return resource.fetchText();
  };

  // note: &#42;&#47;&#42; 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,&#42;&#47;&#42;;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 <code>request.throttle</code> is true and the request does not have high enough priority.
   *
   *
   * @example
   * resource.fetchJson().then(function(jsonData) {
   *     // Do something with the JSON object
   * }).catch(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 (!defined(promise)) {
      return undefined;
    }

    return promise.then(function (value) {
      if (!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 <code>request.throttle</code> 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.<XMLDocument>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> 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
   * }).catch(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.<XMLDocument>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> 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 <code>request.throttle</code> 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
   * }).catch(function(error) {
   *     // an error occurred
   * });
   *
   * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
   */
  Resource.prototype.fetchJsonp = function (callbackParameterName) {
    callbackParameterName = defaultValue(callbackParameterName, "callback");

    checkAndResetRequest(this.request);

    //generate a unique function name
    let functionName;
    do {
      functionName = `loadJsonp${CesiumMath.nextRandomNumber()
      .toString()
      .substring(2, 8)}`;
    } while (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 = 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 (!defined(promise)) {
      return;
    }

    return promise.catch(function (e) {
      if (request.state !== RequestState$1.FAILED) {
        return Promise.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 Promise.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 <code>request.throttle</code> 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$2(options.headers, resource.headers);
      const overrideMimeType = options.overrideMimeType;
      const method = options.method;
      const data = options.data;
      const deferred = defer();
      const xhr = Resource._Implementations.loadWithXhr(
        resource.url,
        responseType,
        method,
        data,
        headers,
        deferred,
        overrideMimeType
      );
      if (defined(xhr) && defined(xhr.abort)) {
        request.cancelFunction = function () {
          xhr.abort();
        };
      }
      return deferred.promise;
    };

    const promise = RequestScheduler.request(request);
    if (!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;
      })
      .catch(function (e) {
        request.cancelFunction = undefined;
        if (request.state !== RequestState$1.FAILED) {
          return Promise.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 Promise.reject(e);
        });
      });
  };

  const dataUriRegex$1 = /^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 = 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 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 <code>request.throttle</code> is true and the request does not have high enough priority.
   *
   *
   * @example
   * resource.fetch()
   *   .then(function(body) {
   *       // use the data
   *   }).catch(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 <code>request.throttle</code> 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 <code>request.throttle</code> is true and the request does not have high enough priority.
   *
   *
   * @example
   * resource.delete()
   *   .then(function(body) {
   *       // use the data
   *   }).catch(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 <code>request.throttle</code> 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 <code>request.throttle</code> is true and the request does not have high enough priority.
   *
   *
   * @example
   * resource.head()
   *   .then(function(headers) {
   *       // use the data
   *   }).catch(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 <code>request.throttle</code> 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 <code>request.throttle</code> is true and the request does not have high enough priority.
   *
   *
   * @example
   * resource.options()
   *   .then(function(headers) {
   *       // use the data
   *   }).catch(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 <code>request.throttle</code> 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 <code>request.throttle</code> is true and the request does not have high enough priority.
   *
   *
   * @example
   * resource.post(data)
   *   .then(function(result) {
   *       // use the result
   *   }).catch(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) {
    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 <code>request.throttle</code> 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 <code>request.throttle</code> is true and the request does not have high enough priority.
   *
   *
   * @example
   * resource.put(data)
   *   .then(function(result) {
   *       // use the result
   *   }).catch(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) {
    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 <code>request.throttle</code> 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 <code>request.throttle</code> is true and the request does not have high enough priority.
   *
   *
   * @example
   * resource.patch(data)
   *   .then(function(result) {
   *       // use the result
   *   }).catch(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) {
    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 <code>request.throttle</code> 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 = {};

  Resource._Implementations.loadImageElement = function (
    url,
    crossOrigin,
    deferred
  ) {
    const image = new Image();

    image.onload = function () {
      // work-around a known issue with Firefox and dimensionless SVG, see:
      //   - https://github.com/whatwg/html/issues/3510
      //   - https://bugzilla.mozilla.org/show_bug.cgi?id=700533
      if (
        image.naturalWidth === 0 &&
        image.naturalHeight === 0 &&
        image.width === 0 &&
        image.height === 0
      ) {
        // these values affect rasterization and will likely mar the content
        // until Firefox takes a stance on the issue, marred content is better than no content
        // Chromium uses a more refined heuristic about its choice given nil viewBox, and a better stance and solution is
        // proposed later in the original issue thread:
        //   - Chromium behavior: https://github.com/CesiumGS/cesium/issues/9188#issuecomment-704400825
        //   - Cesium's stance/solve: https://github.com/CesiumGS/cesium/issues/9188#issuecomment-720645777
        image.width = 300;
        image.height = 150;
      }
      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)) {
          Resource._Implementations.loadImageElement(url, crossOrigin, deferred);
          return;
        }
        const responseType = "blob";
        const method = "GET";
        const xhrDeferred = defer();
        const xhr = Resource._Implementations.loadWithXhr(
          url,
          responseType,
          method,
          undefined,
          undefined,
          xhrDeferred,
          undefined,
          undefined,
          undefined
        );

        if (defined(xhr) && defined(xhr.abort)) {
          request.cancelFunction = function () {
            xhr.abort();
          };
        }
        return xhrDeferred.promise
          .then(function (blob) {
            if (!defined(blob)) {
              deferred.reject(
                new RuntimeError(
                  `Successfully retrieved ${url} but it contained no content.`
                )
              );
              return;
            }

            return Resource.createImageBitmapFromBlob(blob, {
              flipY: flipY,
              premultiplyAlpha: false,
              skipColorSpaceConversion: skipColorSpaceConversion,
            });
          })
          .then(function (image) {
            deferred.resolve(image);
          });
      })
      .catch(function (e) {
        deferred.reject(e);
      });
  };

  /**
   * Wrapper for createImageBitmap
   *
   * @private
   */
  Resource.createImageBitmapFromBlob = function (blob, options) {
    Check.defined("options", options);
    Check.typeOf.bool("options.flipY", options.flipY);
    Check.typeOf.bool("options.premultiplyAlpha", options.premultiplyAlpha);
    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("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$1.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 (defined(overrideMimeType) && defined(xhr.overrideMimeType)) {
      xhr.overrideMimeType(overrideMimeType);
    }

    if (defined(headers)) {
      for (const key in headers) {
        if (headers.hasOwnProperty(key)) {
          xhr.setRequestHeader(key, headers[key]);
        }
      }
    }

    if (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 (
        defined(response) &&
        (!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") &&
        defined(xhr.responseXML) &&
        xhr.responseXML.hasChildNodes()
      ) {
        deferred.resolve(xhr.responseXML);
      } else if (
        (browserResponseType === "" || browserResponseType === "text") &&
        defined(xhr.responseText)
      ) {
        deferred.resolve(xhr.responseText);
      } else {
        deferred.reject(
          new 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).catch(function (e) {
      deferred.reject(e);
    });
  };

  /**
   * 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],
    })
  );

  /*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$1;
  function tryMakeAbsolute(url) {
    if (typeof document === "undefined") {
      //Node.js and Web Workers. In both cases, the URL will already be absolute.
      return url;
    }

    if (!defined(a$1)) {
      a$1 = document.createElement("a");
    }
    a$1.href = url;

    // IE only absolutizes href on get, not set
    // eslint-disable-next-line no-self-assign
    a$1.href = a$1.href;
    return a$1.href;
  }

  let baseResource;
  function getCesiumBaseUrl() {
    if (defined(baseResource)) {
      return baseResource;
    }

    let baseUrlString;
    if (typeof CESIUM_BASE_URL !== "undefined") {
      baseUrlString = CESIUM_BASE_URL;
    } else if (
      typeof define === "object" &&
      defined(define.amd) &&
      !define.amd.toUrlUndefined &&
      defined(require.toUrl)
    ) {
      baseUrlString = getAbsoluteUri(
        "..",
        buildModuleUrl("Core/buildModuleUrl.js")
      );
    } else {
      baseUrlString = getBaseUrlFromCesiumScript();
    }

    //>>includeStart('debug', pragmas.debug);
    if (!defined(baseUrlString)) {
      throw new 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$2;

  /**
   * 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 (!defined(implementation$2)) {
      //select implementation
      if (
        typeof define === "object" &&
        defined(define.amd) &&
        !define.amd.toUrlUndefined &&
        defined(require.toUrl)
      ) {
        implementation$2 = buildModuleUrlFromRequireToUrl;
      } else {
        implementation$2 = buildModuleUrlFromBaseUrl;
      }
    }

    const url = implementation$2(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.
   *
   * @function
   * @returns {String} The configured base URL
   */
  buildModuleUrl.getCesiumBaseUrl = getCesiumBaseUrl;

  /**
   * A 2D Cartesian point.
   * @alias Cartesian2
   * @constructor
   *
   * @param {Number} [x=0.0] The X component.
   * @param {Number} [y=0.0] The Y component.
   *
   * @see Cartesian3
   * @see Cartesian4
   * @see Packable
   */
  function Cartesian2(x, y) {
    /**
     * The X component.
     * @type {Number}
     * @default 0.0
     */
    this.x = defaultValue(x, 0.0);

    /**
     * The Y component.
     * @type {Number}
     * @default 0.0
     */
    this.y = defaultValue(y, 0.0);
  }

  /**
   * Creates a Cartesian2 instance from x and y coordinates.
   *
   * @param {Number} x The x coordinate.
   * @param {Number} y The y coordinate.
   * @param {Cartesian2} [result] The object onto which to store the result.
   * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
   */
  Cartesian2.fromElements = function (x, y, result) {
    if (!defined(result)) {
      return new Cartesian2(x, y);
    }

    result.x = x;
    result.y = y;
    return result;
  };

  /**
   * Duplicates a Cartesian2 instance.
   *
   * @param {Cartesian2} cartesian The Cartesian to duplicate.
   * @param {Cartesian2} [result] The object onto which to store the result.
   * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided. (Returns undefined if cartesian is undefined)
   */
  Cartesian2.clone = function (cartesian, result) {
    if (!defined(cartesian)) {
      return undefined;
    }
    if (!defined(result)) {
      return new Cartesian2(cartesian.x, cartesian.y);
    }

    result.x = cartesian.x;
    result.y = cartesian.y;
    return result;
  };

  /**
   * Creates a Cartesian2 instance from an existing Cartesian3.  This simply takes the
   * x and y properties of the Cartesian3 and drops z.
   * @function
   *
   * @param {Cartesian3} cartesian The Cartesian3 instance to create a Cartesian2 instance from.
   * @param {Cartesian2} [result] The object onto which to store the result.
   * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
   */
  Cartesian2.fromCartesian3 = Cartesian2.clone;

  /**
   * Creates a Cartesian2 instance from an existing Cartesian4.  This simply takes the
   * x and y properties of the Cartesian4 and drops z and w.
   * @function
   *
   * @param {Cartesian4} cartesian The Cartesian4 instance to create a Cartesian2 instance from.
   * @param {Cartesian2} [result] The object onto which to store the result.
   * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
   */
  Cartesian2.fromCartesian4 = Cartesian2.clone;

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  Cartesian2.packedLength = 2;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {Cartesian2} 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
   */
  Cartesian2.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    array[startingIndex++] = value.x;
    array[startingIndex] = value.y;

    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 {Cartesian2} [result] The object into which to store the result.
   * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
   */
  Cartesian2.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    if (!defined(result)) {
      result = new Cartesian2();
    }
    result.x = array[startingIndex++];
    result.y = array[startingIndex];
    return result;
  };

  /**
   * Flattens an array of Cartesian2s into an array of components.
   *
   * @param {Cartesian2[]} array The array of cartesians to pack.
   * @param {Number[]} [result] The array onto which to store the result. If this is a typed array, it must have array.length * 2 components, else a {@link DeveloperError} will be thrown. If it is a regular array, it will be resized to have (array.length * 2) elements.
   * @returns {Number[]} The packed array.
   */
  Cartesian2.packArray = function (array, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    const length = array.length;
    const resultLength = length * 2;
    if (!defined(result)) {
      result = new Array(resultLength);
    } else if (!Array.isArray(result) && result.length !== resultLength) {
      //>>includeStart('debug', pragmas.debug);
      throw new DeveloperError(
        "If result is a typed array, it must have exactly array.length * 2 elements"
      );
      //>>includeEnd('debug');
    } else if (result.length !== resultLength) {
      result.length = resultLength;
    }

    for (let i = 0; i < length; ++i) {
      Cartesian2.pack(array[i], result, i * 2);
    }
    return result;
  };

  /**
   * Unpacks an array of cartesian components into an array of Cartesian2s.
   *
   * @param {Number[]} array The array of components to unpack.
   * @param {Cartesian2[]} [result] The array onto which to store the result.
   * @returns {Cartesian2[]} The unpacked array.
   */
  Cartesian2.unpackArray = function (array, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    Check.typeOf.number.greaterThanOrEquals("array.length", array.length, 2);
    if (array.length % 2 !== 0) {
      throw new DeveloperError("array length must be a multiple of 2.");
    }
    //>>includeEnd('debug');

    const length = array.length;
    if (!defined(result)) {
      result = new Array(length / 2);
    } else {
      result.length = length / 2;
    }

    for (let i = 0; i < length; i += 2) {
      const index = i / 2;
      result[index] = Cartesian2.unpack(array, i, result[index]);
    }
    return result;
  };

  /**
   * Creates a Cartesian2 from two consecutive elements in an array.
   * @function
   *
   * @param {Number[]} array The array whose two consecutive elements correspond to the x and y components, respectively.
   * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to the x component.
   * @param {Cartesian2} [result] The object onto which to store the result.
   * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
   *
   * @example
   * // Create a Cartesian2 with (1.0, 2.0)
   * const v = [1.0, 2.0];
   * const p = Cesium.Cartesian2.fromArray(v);
   *
   * // Create a Cartesian2 with (1.0, 2.0) using an offset into an array
   * const v2 = [0.0, 0.0, 1.0, 2.0];
   * const p2 = Cesium.Cartesian2.fromArray(v2, 2);
   */
  Cartesian2.fromArray = Cartesian2.unpack;

  /**
   * Computes the value of the maximum component for the supplied Cartesian.
   *
   * @param {Cartesian2} cartesian The cartesian to use.
   * @returns {Number} The value of the maximum component.
   */
  Cartesian2.maximumComponent = function (cartesian) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartesian", cartesian);
    //>>includeEnd('debug');

    return Math.max(cartesian.x, cartesian.y);
  };

  /**
   * Computes the value of the minimum component for the supplied Cartesian.
   *
   * @param {Cartesian2} cartesian The cartesian to use.
   * @returns {Number} The value of the minimum component.
   */
  Cartesian2.minimumComponent = function (cartesian) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartesian", cartesian);
    //>>includeEnd('debug');

    return Math.min(cartesian.x, cartesian.y);
  };

  /**
   * Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
   *
   * @param {Cartesian2} first A cartesian to compare.
   * @param {Cartesian2} second A cartesian to compare.
   * @param {Cartesian2} result The object into which to store the result.
   * @returns {Cartesian2} A cartesian with the minimum components.
   */
  Cartesian2.minimumByComponent = function (first, second, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("first", first);
    Check.typeOf.object("second", second);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.x = Math.min(first.x, second.x);
    result.y = Math.min(first.y, second.y);

    return result;
  };

  /**
   * Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
   *
   * @param {Cartesian2} first A cartesian to compare.
   * @param {Cartesian2} second A cartesian to compare.
   * @param {Cartesian2} result The object into which to store the result.
   * @returns {Cartesian2} A cartesian with the maximum components.
   */
  Cartesian2.maximumByComponent = function (first, second, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("first", first);
    Check.typeOf.object("second", second);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.x = Math.max(first.x, second.x);
    result.y = Math.max(first.y, second.y);
    return result;
  };

  /**
   * Constrain a value to lie between two values.
   *
   * @param {Cartesian2} value The value to clamp.
   * @param {Cartesian2} min The minimum bound.
   * @param {Cartesian2} max The maximum bound.
   * @param {Cartesian2} result The object into which to store the result.
   * @returns {Cartesian2} The clamped value such that min <= result <= max.
   */
  Cartesian2.clamp = function (value, min, max, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    Check.typeOf.object("min", min);
    Check.typeOf.object("max", max);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const x = CesiumMath.clamp(value.x, min.x, max.x);
    const y = CesiumMath.clamp(value.y, min.y, max.y);

    result.x = x;
    result.y = y;

    return result;
  };

  /**
   * Computes the provided Cartesian's squared magnitude.
   *
   * @param {Cartesian2} cartesian The Cartesian instance whose squared magnitude is to be computed.
   * @returns {Number} The squared magnitude.
   */
  Cartesian2.magnitudeSquared = function (cartesian) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartesian", cartesian);
    //>>includeEnd('debug');

    return cartesian.x * cartesian.x + cartesian.y * cartesian.y;
  };

  /**
   * Computes the Cartesian's magnitude (length).
   *
   * @param {Cartesian2} cartesian The Cartesian instance whose magnitude is to be computed.
   * @returns {Number} The magnitude.
   */
  Cartesian2.magnitude = function (cartesian) {
    return Math.sqrt(Cartesian2.magnitudeSquared(cartesian));
  };

  const distanceScratch$1 = new Cartesian2();

  /**
   * Computes the distance between two points.
   *
   * @param {Cartesian2} left The first point to compute the distance from.
   * @param {Cartesian2} right The second point to compute the distance to.
   * @returns {Number} The distance between two points.
   *
   * @example
   * // Returns 1.0
   * const d = Cesium.Cartesian2.distance(new Cesium.Cartesian2(1.0, 0.0), new Cesium.Cartesian2(2.0, 0.0));
   */
  Cartesian2.distance = function (left, right) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    //>>includeEnd('debug');

    Cartesian2.subtract(left, right, distanceScratch$1);
    return Cartesian2.magnitude(distanceScratch$1);
  };

  /**
   * Computes the squared distance between two points.  Comparing squared distances
   * using this function is more efficient than comparing distances using {@link Cartesian2#distance}.
   *
   * @param {Cartesian2} left The first point to compute the distance from.
   * @param {Cartesian2} right The second point to compute the distance to.
   * @returns {Number} The distance between two points.
   *
   * @example
   * // Returns 4.0, not 2.0
   * const d = Cesium.Cartesian2.distance(new Cesium.Cartesian2(1.0, 0.0), new Cesium.Cartesian2(3.0, 0.0));
   */
  Cartesian2.distanceSquared = function (left, right) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    //>>includeEnd('debug');

    Cartesian2.subtract(left, right, distanceScratch$1);
    return Cartesian2.magnitudeSquared(distanceScratch$1);
  };

  /**
   * Computes the normalized form of the supplied Cartesian.
   *
   * @param {Cartesian2} cartesian The Cartesian to be normalized.
   * @param {Cartesian2} result The object onto which to store the result.
   * @returns {Cartesian2} The modified result parameter.
   */
  Cartesian2.normalize = function (cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const magnitude = Cartesian2.magnitude(cartesian);

    result.x = cartesian.x / magnitude;
    result.y = cartesian.y / magnitude;

    //>>includeStart('debug', pragmas.debug);
    if (isNaN(result.x) || isNaN(result.y)) {
      throw new DeveloperError("normalized result is not a number");
    }
    //>>includeEnd('debug');

    return result;
  };

  /**
   * Computes the dot (scalar) product of two Cartesians.
   *
   * @param {Cartesian2} left The first Cartesian.
   * @param {Cartesian2} right The second Cartesian.
   * @returns {Number} The dot product.
   */
  Cartesian2.dot = function (left, right) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    //>>includeEnd('debug');

    return left.x * right.x + left.y * right.y;
  };

  /**
   * Computes the magnitude of the cross product that would result from implicitly setting the Z coordinate of the input vectors to 0
   *
   * @param {Cartesian2} left The first Cartesian.
   * @param {Cartesian2} right The second Cartesian.
   * @returns {Number} The cross product.
   */
  Cartesian2.cross = function (left, right) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    //>>includeEnd('debug');

    return left.x * right.y - left.y * right.x;
  };

  /**
   * Computes the componentwise product of two Cartesians.
   *
   * @param {Cartesian2} left The first Cartesian.
   * @param {Cartesian2} right The second Cartesian.
   * @param {Cartesian2} result The object onto which to store the result.
   * @returns {Cartesian2} The modified result parameter.
   */
  Cartesian2.multiplyComponents = function (left, right, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.x = left.x * right.x;
    result.y = left.y * right.y;
    return result;
  };

  /**
   * Computes the componentwise quotient of two Cartesians.
   *
   * @param {Cartesian2} left The first Cartesian.
   * @param {Cartesian2} right The second Cartesian.
   * @param {Cartesian2} result The object onto which to store the result.
   * @returns {Cartesian2} The modified result parameter.
   */
  Cartesian2.divideComponents = function (left, right, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.x = left.x / right.x;
    result.y = left.y / right.y;
    return result;
  };

  /**
   * Computes the componentwise sum of two Cartesians.
   *
   * @param {Cartesian2} left The first Cartesian.
   * @param {Cartesian2} right The second Cartesian.
   * @param {Cartesian2} result The object onto which to store the result.
   * @returns {Cartesian2} The modified result parameter.
   */
  Cartesian2.add = function (left, right, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.x = left.x + right.x;
    result.y = left.y + right.y;
    return result;
  };

  /**
   * Computes the componentwise difference of two Cartesians.
   *
   * @param {Cartesian2} left The first Cartesian.
   * @param {Cartesian2} right The second Cartesian.
   * @param {Cartesian2} result The object onto which to store the result.
   * @returns {Cartesian2} The modified result parameter.
   */
  Cartesian2.subtract = function (left, right, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.x = left.x - right.x;
    result.y = left.y - right.y;
    return result;
  };

  /**
   * Multiplies the provided Cartesian componentwise by the provided scalar.
   *
   * @param {Cartesian2} cartesian The Cartesian to be scaled.
   * @param {Number} scalar The scalar to multiply with.
   * @param {Cartesian2} result The object onto which to store the result.
   * @returns {Cartesian2} The modified result parameter.
   */
  Cartesian2.multiplyByScalar = function (cartesian, scalar, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.number("scalar", scalar);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.x = cartesian.x * scalar;
    result.y = cartesian.y * scalar;
    return result;
  };

  /**
   * Divides the provided Cartesian componentwise by the provided scalar.
   *
   * @param {Cartesian2} cartesian The Cartesian to be divided.
   * @param {Number} scalar The scalar to divide by.
   * @param {Cartesian2} result The object onto which to store the result.
   * @returns {Cartesian2} The modified result parameter.
   */
  Cartesian2.divideByScalar = function (cartesian, scalar, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.number("scalar", scalar);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.x = cartesian.x / scalar;
    result.y = cartesian.y / scalar;
    return result;
  };

  /**
   * Negates the provided Cartesian.
   *
   * @param {Cartesian2} cartesian The Cartesian to be negated.
   * @param {Cartesian2} result The object onto which to store the result.
   * @returns {Cartesian2} The modified result parameter.
   */
  Cartesian2.negate = function (cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.x = -cartesian.x;
    result.y = -cartesian.y;
    return result;
  };

  /**
   * Computes the absolute value of the provided Cartesian.
   *
   * @param {Cartesian2} cartesian The Cartesian whose absolute value is to be computed.
   * @param {Cartesian2} result The object onto which to store the result.
   * @returns {Cartesian2} The modified result parameter.
   */
  Cartesian2.abs = function (cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.x = Math.abs(cartesian.x);
    result.y = Math.abs(cartesian.y);
    return result;
  };

  const lerpScratch$1 = new Cartesian2();
  /**
   * Computes the linear interpolation or extrapolation at t using the provided cartesians.
   *
   * @param {Cartesian2} start The value corresponding to t at 0.0.
   * @param {Cartesian2} end The value corresponding to t at 1.0.
   * @param {Number} t The point along t at which to interpolate.
   * @param {Cartesian2} result The object onto which to store the result.
   * @returns {Cartesian2} The modified result parameter.
   */
  Cartesian2.lerp = function (start, end, t, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("start", start);
    Check.typeOf.object("end", end);
    Check.typeOf.number("t", t);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    Cartesian2.multiplyByScalar(end, t, lerpScratch$1);
    result = Cartesian2.multiplyByScalar(start, 1.0 - t, result);
    return Cartesian2.add(lerpScratch$1, result, result);
  };

  const angleBetweenScratch = new Cartesian2();
  const angleBetweenScratch2 = new Cartesian2();
  /**
   * Returns the angle, in radians, between the provided Cartesians.
   *
   * @param {Cartesian2} left The first Cartesian.
   * @param {Cartesian2} right The second Cartesian.
   * @returns {Number} The angle between the Cartesians.
   */
  Cartesian2.angleBetween = function (left, right) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    //>>includeEnd('debug');

    Cartesian2.normalize(left, angleBetweenScratch);
    Cartesian2.normalize(right, angleBetweenScratch2);
    return CesiumMath.acosClamped(
      Cartesian2.dot(angleBetweenScratch, angleBetweenScratch2)
    );
  };

  const mostOrthogonalAxisScratch = new Cartesian2();
  /**
   * Returns the axis that is most orthogonal to the provided Cartesian.
   *
   * @param {Cartesian2} cartesian The Cartesian on which to find the most orthogonal axis.
   * @param {Cartesian2} result The object onto which to store the result.
   * @returns {Cartesian2} The most orthogonal axis.
   */
  Cartesian2.mostOrthogonalAxis = function (cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const f = Cartesian2.normalize(cartesian, mostOrthogonalAxisScratch);
    Cartesian2.abs(f, f);

    if (f.x <= f.y) {
      result = Cartesian2.clone(Cartesian2.UNIT_X, result);
    } else {
      result = Cartesian2.clone(Cartesian2.UNIT_Y, result);
    }

    return result;
  };

  /**
   * Compares the provided Cartesians componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Cartesian2} [left] The first Cartesian.
   * @param {Cartesian2} [right] The second Cartesian.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  Cartesian2.equals = function (left, right) {
    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        left.x === right.x &&
        left.y === right.y)
    );
  };

  /**
   * @private
   */
  Cartesian2.equalsArray = function (cartesian, array, offset) {
    return cartesian.x === array[offset] && cartesian.y === array[offset + 1];
  };

  /**
   * Compares the provided Cartesians componentwise and returns
   * <code>true</code> if they pass an absolute or relative tolerance test,
   * <code>false</code> otherwise.
   *
   * @param {Cartesian2} [left] The first Cartesian.
   * @param {Cartesian2} [right] The second Cartesian.
   * @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} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
   */
  Cartesian2.equalsEpsilon = function (
    left,
    right,
    relativeEpsilon,
    absoluteEpsilon
  ) {
    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        CesiumMath.equalsEpsilon(
          left.x,
          right.x,
          relativeEpsilon,
          absoluteEpsilon
        ) &&
        CesiumMath.equalsEpsilon(
          left.y,
          right.y,
          relativeEpsilon,
          absoluteEpsilon
        ))
    );
  };

  /**
   * An immutable Cartesian2 instance initialized to (0.0, 0.0).
   *
   * @type {Cartesian2}
   * @constant
   */
  Cartesian2.ZERO = Object.freeze(new Cartesian2(0.0, 0.0));

  /**
   * An immutable Cartesian2 instance initialized to (1.0, 1.0).
   *
   * @type {Cartesian2}
   * @constant
   */
  Cartesian2.ONE = Object.freeze(new Cartesian2(1.0, 1.0));

  /**
   * An immutable Cartesian2 instance initialized to (1.0, 0.0).
   *
   * @type {Cartesian2}
   * @constant
   */
  Cartesian2.UNIT_X = Object.freeze(new Cartesian2(1.0, 0.0));

  /**
   * An immutable Cartesian2 instance initialized to (0.0, 1.0).
   *
   * @type {Cartesian2}
   * @constant
   */
  Cartesian2.UNIT_Y = Object.freeze(new Cartesian2(0.0, 1.0));

  /**
   * Duplicates this Cartesian2 instance.
   *
   * @param {Cartesian2} [result] The object onto which to store the result.
   * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
   */
  Cartesian2.prototype.clone = function (result) {
    return Cartesian2.clone(this, result);
  };

  /**
   * Compares this Cartesian against the provided Cartesian componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Cartesian2} [right] The right hand side Cartesian.
   * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
   */
  Cartesian2.prototype.equals = function (right) {
    return Cartesian2.equals(this, right);
  };

  /**
   * Compares this Cartesian against the provided Cartesian componentwise and returns
   * <code>true</code> if they pass an absolute or relative tolerance test,
   * <code>false</code> otherwise.
   *
   * @param {Cartesian2} [right] The right hand side Cartesian.
   * @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} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
   */
  Cartesian2.prototype.equalsEpsilon = function (
    right,
    relativeEpsilon,
    absoluteEpsilon
  ) {
    return Cartesian2.equalsEpsilon(
      this,
      right,
      relativeEpsilon,
      absoluteEpsilon
    );
  };

  /**
   * Creates a string representing this Cartesian in the format '(x, y)'.
   *
   * @returns {String} A string representing the provided Cartesian in the format '(x, y)'.
   */
  Cartesian2.prototype.toString = function () {
    return `(${this.x}, ${this.y})`;
  };

  /**
   * A tiling scheme for geometry referenced to a simple {@link GeographicProjection} where
   * longitude and latitude are directly mapped to X and Y.  This projection is commonly
   * known as geographic, equirectangular, equidistant cylindrical, or plate carrée.
   *
   * @alias GeographicTilingScheme
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid whose surface is being tiled. Defaults to
   * the WGS84 ellipsoid.
   * @param {Rectangle} [options.rectangle=Rectangle.MAX_VALUE] The rectangle, in radians, covered by the tiling scheme.
   * @param {Number} [options.numberOfLevelZeroTilesX=2] The number of tiles in the X direction at level zero of
   * the tile tree.
   * @param {Number} [options.numberOfLevelZeroTilesY=1] The number of tiles in the Y direction at level zero of
   * the tile tree.
   */
  function GeographicTilingScheme(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    this._ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);
    this._rectangle = defaultValue(options.rectangle, Rectangle.MAX_VALUE);
    this._projection = new GeographicProjection(this._ellipsoid);
    this._numberOfLevelZeroTilesX = defaultValue(
      options.numberOfLevelZeroTilesX,
      2
    );
    this._numberOfLevelZeroTilesY = defaultValue(
      options.numberOfLevelZeroTilesY,
      1
    );
  }

  Object.defineProperties(GeographicTilingScheme.prototype, {
    /**
     * Gets the ellipsoid that is tiled by this tiling scheme.
     * @memberof GeographicTilingScheme.prototype
     * @type {Ellipsoid}
     */
    ellipsoid: {
      get: function () {
        return this._ellipsoid;
      },
    },

    /**
     * Gets the rectangle, in radians, covered by this tiling scheme.
     * @memberof GeographicTilingScheme.prototype
     * @type {Rectangle}
     */
    rectangle: {
      get: function () {
        return this._rectangle;
      },
    },

    /**
     * Gets the map projection used by this tiling scheme.
     * @memberof GeographicTilingScheme.prototype
     * @type {MapProjection}
     */
    projection: {
      get: function () {
        return this._projection;
      },
    },
  });

  /**
   * Gets the total number of tiles in the X direction at a specified level-of-detail.
   *
   * @param {Number} level The level-of-detail.
   * @returns {Number} The number of tiles in the X direction at the given level.
   */
  GeographicTilingScheme.prototype.getNumberOfXTilesAtLevel = function (level) {
    return this._numberOfLevelZeroTilesX << level;
  };

  /**
   * Gets the total number of tiles in the Y direction at a specified level-of-detail.
   *
   * @param {Number} level The level-of-detail.
   * @returns {Number} The number of tiles in the Y direction at the given level.
   */
  GeographicTilingScheme.prototype.getNumberOfYTilesAtLevel = function (level) {
    return this._numberOfLevelZeroTilesY << level;
  };

  /**
   * Transforms a rectangle specified in geodetic radians to the native coordinate system
   * of this tiling scheme.
   *
   * @param {Rectangle} rectangle The rectangle to transform.
   * @param {Rectangle} [result] The instance to which to copy the result, or undefined if a new instance
   *        should be created.
   * @returns {Rectangle} The specified 'result', or a new object containing the native rectangle if 'result'
   *          is undefined.
   */
  GeographicTilingScheme.prototype.rectangleToNativeRectangle = function (
    rectangle,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("rectangle", rectangle);
    //>>includeEnd('debug');

    const west = CesiumMath.toDegrees(rectangle.west);
    const south = CesiumMath.toDegrees(rectangle.south);
    const east = CesiumMath.toDegrees(rectangle.east);
    const north = CesiumMath.toDegrees(rectangle.north);

    if (!defined(result)) {
      return new Rectangle(west, south, east, north);
    }

    result.west = west;
    result.south = south;
    result.east = east;
    result.north = north;
    return result;
  };

  /**
   * Converts tile x, y coordinates and level to a rectangle expressed in the native coordinates
   * of the tiling scheme.
   *
   * @param {Number} x The integer x coordinate of the tile.
   * @param {Number} y The integer y coordinate of the tile.
   * @param {Number} level The tile level-of-detail.  Zero is the least detailed.
   * @param {Object} [result] The instance to which to copy the result, or undefined if a new instance
   *        should be created.
   * @returns {Rectangle} The specified 'result', or a new object containing the rectangle
   *          if 'result' is undefined.
   */
  GeographicTilingScheme.prototype.tileXYToNativeRectangle = function (
    x,
    y,
    level,
    result
  ) {
    const rectangleRadians = this.tileXYToRectangle(x, y, level, result);
    rectangleRadians.west = CesiumMath.toDegrees(rectangleRadians.west);
    rectangleRadians.south = CesiumMath.toDegrees(rectangleRadians.south);
    rectangleRadians.east = CesiumMath.toDegrees(rectangleRadians.east);
    rectangleRadians.north = CesiumMath.toDegrees(rectangleRadians.north);
    return rectangleRadians;
  };

  /**
   * Converts tile x, y coordinates and level to a cartographic rectangle in radians.
   *
   * @param {Number} x The integer x coordinate of the tile.
   * @param {Number} y The integer y coordinate of the tile.
   * @param {Number} level The tile level-of-detail.  Zero is the least detailed.
   * @param {Object} [result] The instance to which to copy the result, or undefined if a new instance
   *        should be created.
   * @returns {Rectangle} The specified 'result', or a new object containing the rectangle
   *          if 'result' is undefined.
   */
  GeographicTilingScheme.prototype.tileXYToRectangle = function (
    x,
    y,
    level,
    result
  ) {
    const rectangle = this._rectangle;

    const xTiles = this.getNumberOfXTilesAtLevel(level);
    const yTiles = this.getNumberOfYTilesAtLevel(level);

    const xTileWidth = rectangle.width / xTiles;
    const west = x * xTileWidth + rectangle.west;
    const east = (x + 1) * xTileWidth + rectangle.west;

    const yTileHeight = rectangle.height / yTiles;
    const north = rectangle.north - y * yTileHeight;
    const south = rectangle.north - (y + 1) * yTileHeight;

    if (!defined(result)) {
      result = new Rectangle(west, south, east, north);
    }

    result.west = west;
    result.south = south;
    result.east = east;
    result.north = north;
    return result;
  };

  /**
   * Calculates the tile x, y coordinates of the tile containing
   * a given cartographic position.
   *
   * @param {Cartographic} position The position.
   * @param {Number} level The tile level-of-detail.  Zero is the least detailed.
   * @param {Cartesian2} [result] The instance to which to copy the result, or undefined if a new instance
   *        should be created.
   * @returns {Cartesian2} The specified 'result', or a new object containing the tile x, y coordinates
   *          if 'result' is undefined.
   */
  GeographicTilingScheme.prototype.positionToTileXY = function (
    position,
    level,
    result
  ) {
    const rectangle = this._rectangle;
    if (!Rectangle.contains(rectangle, position)) {
      // outside the bounds of the tiling scheme
      return undefined;
    }

    const xTiles = this.getNumberOfXTilesAtLevel(level);
    const yTiles = this.getNumberOfYTilesAtLevel(level);

    const xTileWidth = rectangle.width / xTiles;
    const yTileHeight = rectangle.height / yTiles;

    let longitude = position.longitude;
    if (rectangle.east < rectangle.west) {
      longitude += CesiumMath.TWO_PI;
    }

    let xTileCoordinate = ((longitude - rectangle.west) / xTileWidth) | 0;
    if (xTileCoordinate >= xTiles) {
      xTileCoordinate = xTiles - 1;
    }

    let yTileCoordinate =
      ((rectangle.north - position.latitude) / yTileHeight) | 0;
    if (yTileCoordinate >= yTiles) {
      yTileCoordinate = yTiles - 1;
    }

    if (!defined(result)) {
      return new Cartesian2(xTileCoordinate, yTileCoordinate);
    }

    result.x = xTileCoordinate;
    result.y = yTileCoordinate;
    return result;
  };

  const scratchDiagonalCartesianNE = new Cartesian3();
  const scratchDiagonalCartesianSW = new Cartesian3();
  const scratchDiagonalCartographic = new Cartographic();
  const scratchCenterCartesian = new Cartesian3();
  const scratchSurfaceCartesian = new Cartesian3();

  const scratchBoundingSphere$5 = new BoundingSphere();
  const tilingScheme = new GeographicTilingScheme();
  const scratchCorners = [
    new Cartographic(),
    new Cartographic(),
    new Cartographic(),
    new Cartographic(),
  ];
  const scratchTileXY = new Cartesian2();

  /**
   * A collection of functions for approximating terrain height
   * @private
   */
  const ApproximateTerrainHeights = {};

  /**
   * Initializes the minimum and maximum terrain heights
   * @return {Promise.<void>}
   */
  ApproximateTerrainHeights.initialize = function () {
    let initPromise = ApproximateTerrainHeights._initPromise;
    if (defined(initPromise)) {
      return initPromise;
    }

    initPromise = Resource.fetchJson(
      buildModuleUrl("Assets/approximateTerrainHeights.json")
    ).then(function (json) {
      ApproximateTerrainHeights._terrainHeights = json;
    });
    ApproximateTerrainHeights._initPromise = initPromise;

    return initPromise;
  };

  /**
   * Computes the minimum and maximum terrain heights for a given rectangle
   * @param {Rectangle} rectangle The bounding rectangle
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid
   * @return {{minimumTerrainHeight: Number, maximumTerrainHeight: Number}}
   */
  ApproximateTerrainHeights.getMinimumMaximumHeights = function (
    rectangle,
    ellipsoid
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("rectangle", rectangle);
    if (!defined(ApproximateTerrainHeights._terrainHeights)) {
      throw new DeveloperError(
        "You must call ApproximateTerrainHeights.initialize and wait for the promise to resolve before using this function"
      );
    }
    //>>includeEnd('debug');
    ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);

    const xyLevel = getTileXYLevel(rectangle);

    // Get the terrain min/max for that tile
    let minTerrainHeight = ApproximateTerrainHeights._defaultMinTerrainHeight;
    let maxTerrainHeight = ApproximateTerrainHeights._defaultMaxTerrainHeight;
    if (defined(xyLevel)) {
      const key = `${xyLevel.level}-${xyLevel.x}-${xyLevel.y}`;
      const heights = ApproximateTerrainHeights._terrainHeights[key];
      if (defined(heights)) {
        minTerrainHeight = heights[0];
        maxTerrainHeight = heights[1];
      }

      // Compute min by taking the center of the NE->SW diagonal and finding distance to the surface
      ellipsoid.cartographicToCartesian(
        Rectangle.northeast(rectangle, scratchDiagonalCartographic),
        scratchDiagonalCartesianNE
      );
      ellipsoid.cartographicToCartesian(
        Rectangle.southwest(rectangle, scratchDiagonalCartographic),
        scratchDiagonalCartesianSW
      );

      Cartesian3.midpoint(
        scratchDiagonalCartesianSW,
        scratchDiagonalCartesianNE,
        scratchCenterCartesian
      );
      const surfacePosition = ellipsoid.scaleToGeodeticSurface(
        scratchCenterCartesian,
        scratchSurfaceCartesian
      );
      if (defined(surfacePosition)) {
        const distance = Cartesian3.distance(
          scratchCenterCartesian,
          surfacePosition
        );
        minTerrainHeight = Math.min(minTerrainHeight, -distance);
      } else {
        minTerrainHeight = ApproximateTerrainHeights._defaultMinTerrainHeight;
      }
    }

    minTerrainHeight = Math.max(
      ApproximateTerrainHeights._defaultMinTerrainHeight,
      minTerrainHeight
    );

    return {
      minimumTerrainHeight: minTerrainHeight,
      maximumTerrainHeight: maxTerrainHeight,
    };
  };

  /**
   * Computes the bounding sphere based on the tile heights in the rectangle
   * @param {Rectangle} rectangle The bounding rectangle
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid
   * @return {BoundingSphere} The result bounding sphere
   */
  ApproximateTerrainHeights.getBoundingSphere = function (rectangle, ellipsoid) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("rectangle", rectangle);
    if (!defined(ApproximateTerrainHeights._terrainHeights)) {
      throw new DeveloperError(
        "You must call ApproximateTerrainHeights.initialize and wait for the promise to resolve before using this function"
      );
    }
    //>>includeEnd('debug');
    ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);

    const xyLevel = getTileXYLevel(rectangle);

    // Get the terrain max for that tile
    let maxTerrainHeight = ApproximateTerrainHeights._defaultMaxTerrainHeight;
    if (defined(xyLevel)) {
      const key = `${xyLevel.level}-${xyLevel.x}-${xyLevel.y}`;
      const heights = ApproximateTerrainHeights._terrainHeights[key];
      if (defined(heights)) {
        maxTerrainHeight = heights[1];
      }
    }

    const result = BoundingSphere.fromRectangle3D(rectangle, ellipsoid, 0.0);
    BoundingSphere.fromRectangle3D(
      rectangle,
      ellipsoid,
      maxTerrainHeight,
      scratchBoundingSphere$5
    );

    return BoundingSphere.union(result, scratchBoundingSphere$5, result);
  };

  function getTileXYLevel(rectangle) {
    Cartographic.fromRadians(
      rectangle.east,
      rectangle.north,
      0.0,
      scratchCorners[0]
    );
    Cartographic.fromRadians(
      rectangle.west,
      rectangle.north,
      0.0,
      scratchCorners[1]
    );
    Cartographic.fromRadians(
      rectangle.east,
      rectangle.south,
      0.0,
      scratchCorners[2]
    );
    Cartographic.fromRadians(
      rectangle.west,
      rectangle.south,
      0.0,
      scratchCorners[3]
    );

    // Determine which tile the bounding rectangle is in
    let lastLevelX = 0,
      lastLevelY = 0;
    let currentX = 0,
      currentY = 0;
    const maxLevel = ApproximateTerrainHeights._terrainHeightsMaxLevel;
    let i;
    for (i = 0; i <= maxLevel; ++i) {
      let failed = false;
      for (let j = 0; j < 4; ++j) {
        const corner = scratchCorners[j];
        tilingScheme.positionToTileXY(corner, i, scratchTileXY);
        if (j === 0) {
          currentX = scratchTileXY.x;
          currentY = scratchTileXY.y;
        } else if (currentX !== scratchTileXY.x || currentY !== scratchTileXY.y) {
          failed = true;
          break;
        }
      }

      if (failed) {
        break;
      }

      lastLevelX = currentX;
      lastLevelY = currentY;
    }

    if (i === 0) {
      return undefined;
    }

    return {
      x: lastLevelX,
      y: lastLevelY,
      level: i > maxLevel ? maxLevel : i - 1,
    };
  }

  ApproximateTerrainHeights._terrainHeightsMaxLevel = 6;
  ApproximateTerrainHeights._defaultMaxTerrainHeight = 9000.0;
  ApproximateTerrainHeights._defaultMinTerrainHeight = -100000.0;
  ApproximateTerrainHeights._terrainHeights = undefined;
  ApproximateTerrainHeights._initPromise = undefined;

  Object.defineProperties(ApproximateTerrainHeights, {
    /**
     * Determines if the terrain heights are initialized and ready to use. To initialize the terrain heights,
     * call {@link ApproximateTerrainHeights#initialize} and wait for the returned promise to resolve.
     * @type {Boolean}
     * @readonly
     * @memberof ApproximateTerrainHeights
     */
    initialized: {
      get: function () {
        return defined(ApproximateTerrainHeights._terrainHeights);
      },
    },
  });

  /* This file is automatically rebuilt by the Cesium build process. */
  /*! @license DOMPurify 2.3.8 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/2.3.8/LICENSE */

  function _typeof(obj) {
    "@babel/helpers - typeof";

    return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
      return typeof obj;
    } : function (obj) {
      return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
    }, _typeof(obj);
  }

  function _setPrototypeOf(o, p) {
    _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
      o.__proto__ = p;
      return o;
    };

    return _setPrototypeOf(o, p);
  }

  function _isNativeReflectConstruct() {
    if (typeof Reflect === "undefined" || !Reflect.construct) return false;
    if (Reflect.construct.sham) return false;
    if (typeof Proxy === "function") return true;

    try {
      Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
      return true;
    } catch (e) {
      return false;
    }
  }

  function _construct(Parent, args, Class) {
    if (_isNativeReflectConstruct()) {
      _construct = Reflect.construct;
    } else {
      _construct = function _construct(Parent, args, Class) {
        var a = [null];
        a.push.apply(a, args);
        var Constructor = Function.bind.apply(Parent, a);
        var instance = new Constructor();
        if (Class) _setPrototypeOf(instance, Class.prototype);
        return instance;
      };
    }

    return _construct.apply(null, arguments);
  }

  function _toConsumableArray(arr) {
    return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
  }

  function _arrayWithoutHoles(arr) {
    if (Array.isArray(arr)) return _arrayLikeToArray(arr);
  }

  function _iterableToArray(iter) {
    if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
  }

  function _unsupportedIterableToArray(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _arrayLikeToArray(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(o);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  }

  function _arrayLikeToArray(arr, len) {
    if (len == null || len > arr.length) len = arr.length;

    for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];

    return arr2;
  }

  function _nonIterableSpread() {
    throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  }

  var hasOwnProperty = Object.hasOwnProperty,
      setPrototypeOf = Object.setPrototypeOf,
      isFrozen = Object.isFrozen,
      getPrototypeOf = Object.getPrototypeOf,
      getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  var freeze = Object.freeze,
      seal = Object.seal,
      create = Object.create; // eslint-disable-line import/no-mutable-exports

  var _ref = typeof Reflect !== 'undefined' && Reflect,
      apply = _ref.apply,
      construct = _ref.construct;

  if (!apply) {
    apply = function apply(fun, thisValue, args) {
      return fun.apply(thisValue, args);
    };
  }

  if (!freeze) {
    freeze = function freeze(x) {
      return x;
    };
  }

  if (!seal) {
    seal = function seal(x) {
      return x;
    };
  }

  if (!construct) {
    construct = function construct(Func, args) {
      return _construct(Func, _toConsumableArray(args));
    };
  }

  var arrayForEach = unapply(Array.prototype.forEach);
  var arrayPop = unapply(Array.prototype.pop);
  var arrayPush = unapply(Array.prototype.push);
  var stringToLowerCase = unapply(String.prototype.toLowerCase);
  var stringMatch = unapply(String.prototype.match);
  var stringReplace = unapply(String.prototype.replace);
  var stringIndexOf = unapply(String.prototype.indexOf);
  var stringTrim = unapply(String.prototype.trim);
  var regExpTest = unapply(RegExp.prototype.test);
  var typeErrorCreate = unconstruct(TypeError);
  function unapply(func) {
    return function (thisArg) {
      for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
        args[_key - 1] = arguments[_key];
      }

      return apply(func, thisArg, args);
    };
  }
  function unconstruct(func) {
    return function () {
      for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
        args[_key2] = arguments[_key2];
      }

      return construct(func, args);
    };
  }
  /* Add properties to a lookup table */

  function addToSet(set, array) {
    if (setPrototypeOf) {
      // Make 'in' and truthy checks like Boolean(set.constructor)
      // independent of any properties defined on Object.prototype.
      // Prevent prototype setters from intercepting set as a this value.
      setPrototypeOf(set, null);
    }

    var l = array.length;

    while (l--) {
      var element = array[l];

      if (typeof element === 'string') {
        var lcElement = stringToLowerCase(element);

        if (lcElement !== element) {
          // Config presets (e.g. tags.js, attrs.js) are immutable.
          if (!isFrozen(array)) {
            array[l] = lcElement;
          }

          element = lcElement;
        }
      }

      set[element] = true;
    }

    return set;
  }
  /* Shallow clone an object */

  function clone(object) {
    var newObject = create(null);
    var property;

    for (property in object) {
      if (apply(hasOwnProperty, object, [property])) {
        newObject[property] = object[property];
      }
    }

    return newObject;
  }
  /* IE10 doesn't support __lookupGetter__ so lets'
   * simulate it. It also automatically checks
   * if the prop is function or getter and behaves
   * accordingly. */

  function lookupGetter(object, prop) {
    while (object !== null) {
      var desc = getOwnPropertyDescriptor(object, prop);

      if (desc) {
        if (desc.get) {
          return unapply(desc.get);
        }

        if (typeof desc.value === 'function') {
          return unapply(desc.value);
        }
      }

      object = getPrototypeOf(object);
    }

    function fallbackValue(element) {
      console.warn('fallback value for', element);
      return null;
    }

    return fallbackValue;
  }

  var html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'select', 'shadow', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']); // SVG

  var svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']);
  var svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']); // List of SVG elements that are disallowed by default.
  // We still need to know them so that we can do namespace
  // checks properly in case one wants to add them to
  // allow-list.

  var svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'fedropshadow', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']);
  var mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover']); // Similarly to SVG, we want to know all MathML elements,
  // even those that we disallow by default.

  var mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
  var text = freeze(['#text']);

  var html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'pattern', 'placeholder', 'playsinline', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'xmlns', 'slot']);
  var svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);
  var mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnsalign', 'columnlines', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lspace', 'lquote', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']);
  var xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);

  var MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode

  var ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
  var DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]/); // eslint-disable-line no-useless-escape

  var ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape

  var IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape
  );
  var IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
  var ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex
  );
  var DOCTYPE_NAME = seal(/^html$/i);

  var getGlobal = function getGlobal() {
    return typeof window === 'undefined' ? null : window;
  };
  /**
   * Creates a no-op policy for internal use only.
   * Don't export this function outside this module!
   * @param {?TrustedTypePolicyFactory} trustedTypes The policy factory.
   * @param {Document} document The document object (to determine policy name suffix)
   * @return {?TrustedTypePolicy} The policy created (or null, if Trusted Types
   * are not supported).
   */


  var _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, document) {
    if (_typeof(trustedTypes) !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
      return null;
    } // Allow the callers to control the unique policy name
    // by adding a data-tt-policy-suffix to the script element with the DOMPurify.
    // Policy creation with duplicate names throws in Trusted Types.


    var suffix = null;
    var ATTR_NAME = 'data-tt-policy-suffix';

    if (document.currentScript && document.currentScript.hasAttribute(ATTR_NAME)) {
      suffix = document.currentScript.getAttribute(ATTR_NAME);
    }

    var policyName = 'dompurify' + (suffix ? '#' + suffix : '');

    try {
      return trustedTypes.createPolicy(policyName, {
        createHTML: function createHTML(html) {
          return html;
        }
      });
    } catch (_) {
      // Policy creation failed (most likely another DOMPurify script has
      // already run). Skip creating the policy, as this will only cause errors
      // if TT are enforced.
      console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
      return null;
    }
  };

  function createDOMPurify() {
    var window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();

    var DOMPurify = function DOMPurify(root) {
      return createDOMPurify(root);
    };
    /**
     * Version label, exposed for easier checks
     * if DOMPurify is up to date or not
     */


    DOMPurify.version = '2.3.8';
    /**
     * Array of elements that DOMPurify removed during sanitation.
     * Empty if nothing was removed.
     */

    DOMPurify.removed = [];

    if (!window || !window.document || window.document.nodeType !== 9) {
      // Not running in a browser, provide a factory function
      // so that you can pass your own Window
      DOMPurify.isSupported = false;
      return DOMPurify;
    }

    var originalDocument = window.document;
    var document = window.document;
    var DocumentFragment = window.DocumentFragment,
        HTMLTemplateElement = window.HTMLTemplateElement,
        Node = window.Node,
        Element = window.Element,
        NodeFilter = window.NodeFilter,
        _window$NamedNodeMap = window.NamedNodeMap,
        NamedNodeMap = _window$NamedNodeMap === void 0 ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap,
        HTMLFormElement = window.HTMLFormElement,
        DOMParser = window.DOMParser,
        trustedTypes = window.trustedTypes;
    var ElementPrototype = Element.prototype;
    var cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
    var getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
    var getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
    var getParentNode = lookupGetter(ElementPrototype, 'parentNode'); // As per issue #47, the web-components registry is inherited by a
    // new document created via createHTMLDocument. As per the spec
    // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
    // a new empty registry is used when creating a template contents owner
    // document, so we use that as our parent document to ensure nothing
    // is inherited.

    if (typeof HTMLTemplateElement === 'function') {
      var template = document.createElement('template');

      if (template.content && template.content.ownerDocument) {
        document = template.content.ownerDocument;
      }
    }

    var trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, originalDocument);

    var emptyHTML = trustedTypesPolicy ? trustedTypesPolicy.createHTML('') : '';
    var _document = document,
        implementation = _document.implementation,
        createNodeIterator = _document.createNodeIterator,
        createDocumentFragment = _document.createDocumentFragment,
        getElementsByTagName = _document.getElementsByTagName;
    var importNode = originalDocument.importNode;
    var documentMode = {};

    try {
      documentMode = clone(document).documentMode ? document.documentMode : {};
    } catch (_) {}

    var hooks = {};
    /**
     * Expose whether this browser supports running the full DOMPurify.
     */

    DOMPurify.isSupported = typeof getParentNode === 'function' && implementation && typeof implementation.createHTMLDocument !== 'undefined' && documentMode !== 9;
    var MUSTACHE_EXPR$1 = MUSTACHE_EXPR,
        ERB_EXPR$1 = ERB_EXPR,
        DATA_ATTR$1 = DATA_ATTR,
        ARIA_ATTR$1 = ARIA_ATTR,
        IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA,
        ATTR_WHITESPACE$1 = ATTR_WHITESPACE;
    var IS_ALLOWED_URI$1 = IS_ALLOWED_URI;
    /**
     * We consider the elements and attributes below to be safe. Ideally
     * don't add any new ones but feel free to remove unwanted ones.
     */

    /* allowed element names */

    var ALLOWED_TAGS = null;
    var DEFAULT_ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray(html$1), _toConsumableArray(svg$1), _toConsumableArray(svgFilters), _toConsumableArray(mathMl$1), _toConsumableArray(text)));
    /* Allowed attribute names */

    var ALLOWED_ATTR = null;
    var DEFAULT_ALLOWED_ATTR = addToSet({}, [].concat(_toConsumableArray(html), _toConsumableArray(svg), _toConsumableArray(mathMl), _toConsumableArray(xml)));
    /*
     * Configure how DOMPUrify should handle custom elements and their attributes as well as customized built-in elements.
     * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)
     * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)
     * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.
     */

    var CUSTOM_ELEMENT_HANDLING = Object.seal(Object.create(null, {
      tagNameCheck: {
        writable: true,
        configurable: false,
        enumerable: true,
        value: null
      },
      attributeNameCheck: {
        writable: true,
        configurable: false,
        enumerable: true,
        value: null
      },
      allowCustomizedBuiltInElements: {
        writable: true,
        configurable: false,
        enumerable: true,
        value: false
      }
    }));
    /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */

    var FORBID_TAGS = null;
    /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */

    var FORBID_ATTR = null;
    /* Decide if ARIA attributes are okay */

    var ALLOW_ARIA_ATTR = true;
    /* Decide if custom data attributes are okay */

    var ALLOW_DATA_ATTR = true;
    /* Decide if unknown protocols are okay */

    var ALLOW_UNKNOWN_PROTOCOLS = false;
    /* Output should be safe for common template engines.
     * This means, DOMPurify removes data attributes, mustaches and ERB
     */

    var SAFE_FOR_TEMPLATES = false;
    /* Decide if document with <html>... should be returned */

    var WHOLE_DOCUMENT = false;
    /* Track whether config is already set on this instance of DOMPurify. */

    var SET_CONFIG = false;
    /* Decide if all elements (e.g. style, script) must be children of
     * document.body. By default, browsers might move them to document.head */

    var FORCE_BODY = false;
    /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html
     * string (or a TrustedHTML object if Trusted Types are supported).
     * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
     */

    var RETURN_DOM = false;
    /* Decide if a DOM `DocumentFragment` should be returned, instead of a html
     * string  (or a TrustedHTML object if Trusted Types are supported) */

    var RETURN_DOM_FRAGMENT = false;
    /* Try to return a Trusted Type object instead of a string, return a string in
     * case Trusted Types are not supported  */

    var RETURN_TRUSTED_TYPE = false;
    /* Output should be free from DOM clobbering attacks? */

    var SANITIZE_DOM = true;
    /* Keep element content when removing element? */

    var KEEP_CONTENT = true;
    /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead
     * of importing it into a new Document and returning a sanitized copy */

    var IN_PLACE = false;
    /* Allow usage of profiles like html, svg and mathMl */

    var USE_PROFILES = {};
    /* Tags to ignore content of when KEEP_CONTENT is true */

    var FORBID_CONTENTS = null;
    var DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);
    /* Tags that are safe for data: URIs */

    var DATA_URI_TAGS = null;
    var DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
    /* Attributes safe for values like "javascript:" */

    var URI_SAFE_ATTRIBUTES = null;
    var DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);
    var MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
    var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
    var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
    /* Document namespace */

    var NAMESPACE = HTML_NAMESPACE;
    var IS_EMPTY_INPUT = false;
    /* Parsing of strict XHTML documents */

    var PARSER_MEDIA_TYPE;
    var SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];
    var DEFAULT_PARSER_MEDIA_TYPE = 'text/html';
    var transformCaseFunc;
    /* Keep a reference to config to pass to hooks */

    var CONFIG = null;
    /* Ideally, do not touch anything below this line */

    /* ______________________________________________ */

    var formElement = document.createElement('form');

    var isRegexOrFunction = function isRegexOrFunction(testValue) {
      return testValue instanceof RegExp || testValue instanceof Function;
    };
    /**
     * _parseConfig
     *
     * @param  {Object} cfg optional config literal
     */
    // eslint-disable-next-line complexity


    var _parseConfig = function _parseConfig(cfg) {
      if (CONFIG && CONFIG === cfg) {
        return;
      }
      /* Shield configuration object from tampering */


      if (!cfg || _typeof(cfg) !== 'object') {
        cfg = {};
      }
      /* Shield configuration object from prototype pollution */


      cfg = clone(cfg);
      /* Set configuration parameters */

      ALLOWED_TAGS = 'ALLOWED_TAGS' in cfg ? addToSet({}, cfg.ALLOWED_TAGS) : DEFAULT_ALLOWED_TAGS;
      ALLOWED_ATTR = 'ALLOWED_ATTR' in cfg ? addToSet({}, cfg.ALLOWED_ATTR) : DEFAULT_ALLOWED_ATTR;
      URI_SAFE_ATTRIBUTES = 'ADD_URI_SAFE_ATTR' in cfg ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR) : DEFAULT_URI_SAFE_ATTRIBUTES;
      DATA_URI_TAGS = 'ADD_DATA_URI_TAGS' in cfg ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS) : DEFAULT_DATA_URI_TAGS;
      FORBID_CONTENTS = 'FORBID_CONTENTS' in cfg ? addToSet({}, cfg.FORBID_CONTENTS) : DEFAULT_FORBID_CONTENTS;
      FORBID_TAGS = 'FORBID_TAGS' in cfg ? addToSet({}, cfg.FORBID_TAGS) : {};
      FORBID_ATTR = 'FORBID_ATTR' in cfg ? addToSet({}, cfg.FORBID_ATTR) : {};
      USE_PROFILES = 'USE_PROFILES' in cfg ? cfg.USE_PROFILES : false;
      ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true

      ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true

      ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false

      SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false

      WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false

      RETURN_DOM = cfg.RETURN_DOM || false; // Default false

      RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false

      RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false

      FORCE_BODY = cfg.FORCE_BODY || false; // Default false

      SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true

      KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true

      IN_PLACE = cfg.IN_PLACE || false; // Default false

      IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI$1;
      NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;

      if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {
        CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;
      }

      if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {
        CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;
      }

      if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') {
        CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;
      }

      PARSER_MEDIA_TYPE = // eslint-disable-next-line unicorn/prefer-includes
      SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? PARSER_MEDIA_TYPE = DEFAULT_PARSER_MEDIA_TYPE : PARSER_MEDIA_TYPE = cfg.PARSER_MEDIA_TYPE; // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.

      transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? function (x) {
        return x;
      } : stringToLowerCase;

      if (SAFE_FOR_TEMPLATES) {
        ALLOW_DATA_ATTR = false;
      }

      if (RETURN_DOM_FRAGMENT) {
        RETURN_DOM = true;
      }
      /* Parse profile info */


      if (USE_PROFILES) {
        ALLOWED_TAGS = addToSet({}, _toConsumableArray(text));
        ALLOWED_ATTR = [];

        if (USE_PROFILES.html === true) {
          addToSet(ALLOWED_TAGS, html$1);
          addToSet(ALLOWED_ATTR, html);
        }

        if (USE_PROFILES.svg === true) {
          addToSet(ALLOWED_TAGS, svg$1);
          addToSet(ALLOWED_ATTR, svg);
          addToSet(ALLOWED_ATTR, xml);
        }

        if (USE_PROFILES.svgFilters === true) {
          addToSet(ALLOWED_TAGS, svgFilters);
          addToSet(ALLOWED_ATTR, svg);
          addToSet(ALLOWED_ATTR, xml);
        }

        if (USE_PROFILES.mathMl === true) {
          addToSet(ALLOWED_TAGS, mathMl$1);
          addToSet(ALLOWED_ATTR, mathMl);
          addToSet(ALLOWED_ATTR, xml);
        }
      }
      /* Merge configuration parameters */


      if (cfg.ADD_TAGS) {
        if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
          ALLOWED_TAGS = clone(ALLOWED_TAGS);
        }

        addToSet(ALLOWED_TAGS, cfg.ADD_TAGS);
      }

      if (cfg.ADD_ATTR) {
        if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
          ALLOWED_ATTR = clone(ALLOWED_ATTR);
        }

        addToSet(ALLOWED_ATTR, cfg.ADD_ATTR);
      }

      if (cfg.ADD_URI_SAFE_ATTR) {
        addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR);
      }

      if (cfg.FORBID_CONTENTS) {
        if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
          FORBID_CONTENTS = clone(FORBID_CONTENTS);
        }

        addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS);
      }
      /* Add #text in case KEEP_CONTENT is set to true */


      if (KEEP_CONTENT) {
        ALLOWED_TAGS['#text'] = true;
      }
      /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */


      if (WHOLE_DOCUMENT) {
        addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);
      }
      /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */


      if (ALLOWED_TAGS.table) {
        addToSet(ALLOWED_TAGS, ['tbody']);
        delete FORBID_TAGS.tbody;
      } // Prevent further manipulation of configuration.
      // Not available in IE8, Safari 5, etc.


      if (freeze) {
        freeze(cfg);
      }

      CONFIG = cfg;
    };

    var MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);
    var HTML_INTEGRATION_POINTS = addToSet({}, ['foreignobject', 'desc', 'title', 'annotation-xml']); // Certain elements are allowed in both SVG and HTML
    // namespace. We need to specify them explicitly
    // so that they don't get erroneously deleted from
    // HTML namespace.

    var COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);
    /* Keep track of all possible SVG and MathML tags
     * so that we can perform the namespace checks
     * correctly. */

    var ALL_SVG_TAGS = addToSet({}, svg$1);
    addToSet(ALL_SVG_TAGS, svgFilters);
    addToSet(ALL_SVG_TAGS, svgDisallowed);
    var ALL_MATHML_TAGS = addToSet({}, mathMl$1);
    addToSet(ALL_MATHML_TAGS, mathMlDisallowed);
    /**
     *
     *
     * @param  {Element} element a DOM element whose namespace is being checked
     * @returns {boolean} Return false if the element has a
     *  namespace that a spec-compliant parser would never
     *  return. Return true otherwise.
     */

    var _checkValidNamespace = function _checkValidNamespace(element) {
      var parent = getParentNode(element); // In JSDOM, if we're inside shadow DOM, then parentNode
      // can be null. We just simulate parent in this case.

      if (!parent || !parent.tagName) {
        parent = {
          namespaceURI: HTML_NAMESPACE,
          tagName: 'template'
        };
      }

      var tagName = stringToLowerCase(element.tagName);
      var parentTagName = stringToLowerCase(parent.tagName);

      if (element.namespaceURI === SVG_NAMESPACE) {
        // The only way to switch from HTML namespace to SVG
        // is via <svg>. If it happens via any other tag, then
        // it should be killed.
        if (parent.namespaceURI === HTML_NAMESPACE) {
          return tagName === 'svg';
        } // The only way to switch from MathML to SVG is via
        // svg if parent is either <annotation-xml> or MathML
        // text integration points.


        if (parent.namespaceURI === MATHML_NAMESPACE) {
          return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
        } // We only allow elements that are defined in SVG
        // spec. All others are disallowed in SVG namespace.


        return Boolean(ALL_SVG_TAGS[tagName]);
      }

      if (element.namespaceURI === MATHML_NAMESPACE) {
        // The only way to switch from HTML namespace to MathML
        // is via <math>. If it happens via any other tag, then
        // it should be killed.
        if (parent.namespaceURI === HTML_NAMESPACE) {
          return tagName === 'math';
        } // The only way to switch from SVG to MathML is via
        // <math> and HTML integration points


        if (parent.namespaceURI === SVG_NAMESPACE) {
          return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
        } // We only allow elements that are defined in MathML
        // spec. All others are disallowed in MathML namespace.


        return Boolean(ALL_MATHML_TAGS[tagName]);
      }

      if (element.namespaceURI === HTML_NAMESPACE) {
        // The only way to switch from SVG to HTML is via
        // HTML integration points, and from MathML to HTML
        // is via MathML text integration points
        if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
          return false;
        }

        if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
          return false;
        } // We disallow tags that are specific for MathML
        // or SVG and should never appear in HTML namespace


        return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
      } // The code should never reach this place (this means
      // that the element somehow got namespace that is not
      // HTML, SVG or MathML). Return false just in case.


      return false;
    };
    /**
     * _forceRemove
     *
     * @param  {Node} node a DOM node
     */


    var _forceRemove = function _forceRemove(node) {
      arrayPush(DOMPurify.removed, {
        element: node
      });

      try {
        // eslint-disable-next-line unicorn/prefer-dom-node-remove
        node.parentNode.removeChild(node);
      } catch (_) {
        try {
          node.outerHTML = emptyHTML;
        } catch (_) {
          node.remove();
        }
      }
    };
    /**
     * _removeAttribute
     *
     * @param  {String} name an Attribute name
     * @param  {Node} node a DOM node
     */


    var _removeAttribute = function _removeAttribute(name, node) {
      try {
        arrayPush(DOMPurify.removed, {
          attribute: node.getAttributeNode(name),
          from: node
        });
      } catch (_) {
        arrayPush(DOMPurify.removed, {
          attribute: null,
          from: node
        });
      }

      node.removeAttribute(name); // We void attribute values for unremovable "is"" attributes

      if (name === 'is' && !ALLOWED_ATTR[name]) {
        if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
          try {
            _forceRemove(node);
          } catch (_) {}
        } else {
          try {
            node.setAttribute(name, '');
          } catch (_) {}
        }
      }
    };
    /**
     * _initDocument
     *
     * @param  {String} dirty a string of dirty markup
     * @return {Document} a DOM, filled with the dirty markup
     */


    var _initDocument = function _initDocument(dirty) {
      /* Create a HTML document */
      var doc;
      var leadingWhitespace;

      if (FORCE_BODY) {
        dirty = '<remove></remove>' + dirty;
      } else {
        /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */
        var matches = stringMatch(dirty, /^[\r\n\t ]+/);
        leadingWhitespace = matches && matches[0];
      }

      if (PARSER_MEDIA_TYPE === 'application/xhtml+xml') {
        // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
        dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
      }

      var dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
      /*
       * Use the DOMParser API by default, fallback later if needs be
       * DOMParser not work for svg when has multiple root element.
       */

      if (NAMESPACE === HTML_NAMESPACE) {
        try {
          doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
        } catch (_) {}
      }
      /* Use createHTMLDocument in case DOMParser is not available */


      if (!doc || !doc.documentElement) {
        doc = implementation.createDocument(NAMESPACE, 'template', null);

        try {
          doc.documentElement.innerHTML = IS_EMPTY_INPUT ? '' : dirtyPayload;
        } catch (_) {// Syntax error if dirtyPayload is invalid xml
        }
      }

      var body = doc.body || doc.documentElement;

      if (dirty && leadingWhitespace) {
        body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);
      }
      /* Work on whole document or just its body */


      if (NAMESPACE === HTML_NAMESPACE) {
        return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
      }

      return WHOLE_DOCUMENT ? doc.documentElement : body;
    };
    /**
     * _createIterator
     *
     * @param  {Document} root document/fragment to create iterator for
     * @return {Iterator} iterator instance
     */


    var _createIterator = function _createIterator(root) {
      return createNodeIterator.call(root.ownerDocument || root, root, // eslint-disable-next-line no-bitwise
      NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT, null, false);
    };
    /**
     * _isClobbered
     *
     * @param  {Node} elm element to check for clobbering attacks
     * @return {Boolean} true if clobbered, false if safe
     */


    var _isClobbered = function _isClobbered(elm) {
      return elm instanceof HTMLFormElement && (typeof elm.nodeName !== 'string' || typeof elm.textContent !== 'string' || typeof elm.removeChild !== 'function' || !(elm.attributes instanceof NamedNodeMap) || typeof elm.removeAttribute !== 'function' || typeof elm.setAttribute !== 'function' || typeof elm.namespaceURI !== 'string' || typeof elm.insertBefore !== 'function');
    };
    /**
     * _isNode
     *
     * @param  {Node} obj object to check whether it's a DOM node
     * @return {Boolean} true is object is a DOM node
     */


    var _isNode = function _isNode(object) {
      return _typeof(Node) === 'object' ? object instanceof Node : object && _typeof(object) === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string';
    };
    /**
     * _executeHook
     * Execute user configurable hooks
     *
     * @param  {String} entryPoint  Name of the hook's entry point
     * @param  {Node} currentNode node to work on with the hook
     * @param  {Object} data additional hook parameters
     */


    var _executeHook = function _executeHook(entryPoint, currentNode, data) {
      if (!hooks[entryPoint]) {
        return;
      }

      arrayForEach(hooks[entryPoint], function (hook) {
        hook.call(DOMPurify, currentNode, data, CONFIG);
      });
    };
    /**
     * _sanitizeElements
     *
     * @protect nodeName
     * @protect textContent
     * @protect removeChild
     *
     * @param   {Node} currentNode to check for permission to exist
     * @return  {Boolean} true if node was killed, false if left alive
     */


    var _sanitizeElements = function _sanitizeElements(currentNode) {
      var content;
      /* Execute a hook if present */

      _executeHook('beforeSanitizeElements', currentNode, null);
      /* Check if element is clobbered or can clobber */


      if (_isClobbered(currentNode)) {
        _forceRemove(currentNode);

        return true;
      }
      /* Check if tagname contains Unicode */


      if (regExpTest(/[\u0080-\uFFFF]/, currentNode.nodeName)) {
        _forceRemove(currentNode);

        return true;
      }
      /* Now let's check the element's type and name */


      var tagName = transformCaseFunc(currentNode.nodeName);
      /* Execute a hook if present */

      _executeHook('uponSanitizeElement', currentNode, {
        tagName: tagName,
        allowedTags: ALLOWED_TAGS
      });
      /* Detect mXSS attempts abusing namespace confusion */


      if (currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && (!_isNode(currentNode.content) || !_isNode(currentNode.content.firstElementChild)) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) {
        _forceRemove(currentNode);

        return true;
      }
      /* Mitigate a problem with templates inside select */


      if (tagName === 'select' && regExpTest(/<template/i, currentNode.innerHTML)) {
        _forceRemove(currentNode);

        return true;
      }
      /* Remove element if anything forbids its presence */


      if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
        /* Check if we have a custom element to handle */
        if (!FORBID_TAGS[tagName] && _basicCustomElementTest(tagName)) {
          if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) return false;
          if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) return false;
        }
        /* Keep content except for bad-listed elements */


        if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
          var parentNode = getParentNode(currentNode) || currentNode.parentNode;
          var childNodes = getChildNodes(currentNode) || currentNode.childNodes;

          if (childNodes && parentNode) {
            var childCount = childNodes.length;

            for (var i = childCount - 1; i >= 0; --i) {
              parentNode.insertBefore(cloneNode(childNodes[i], true), getNextSibling(currentNode));
            }
          }
        }

        _forceRemove(currentNode);

        return true;
      }
      /* Check whether element has a valid namespace */


      if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
        _forceRemove(currentNode);

        return true;
      }

      if ((tagName === 'noscript' || tagName === 'noembed') && regExpTest(/<\/no(script|embed)/i, currentNode.innerHTML)) {
        _forceRemove(currentNode);

        return true;
      }
      /* Sanitize element content to be template-safe */


      if (SAFE_FOR_TEMPLATES && currentNode.nodeType === 3) {
        /* Get the element's text content */
        content = currentNode.textContent;
        content = stringReplace(content, MUSTACHE_EXPR$1, ' ');
        content = stringReplace(content, ERB_EXPR$1, ' ');

        if (currentNode.textContent !== content) {
          arrayPush(DOMPurify.removed, {
            element: currentNode.cloneNode()
          });
          currentNode.textContent = content;
        }
      }
      /* Execute a hook if present */


      _executeHook('afterSanitizeElements', currentNode, null);

      return false;
    };
    /**
     * _isValidAttribute
     *
     * @param  {string} lcTag Lowercase tag name of containing element.
     * @param  {string} lcName Lowercase attribute name.
     * @param  {string} value Attribute value.
     * @return {Boolean} Returns true if `value` is valid, otherwise false.
     */
    // eslint-disable-next-line complexity


    var _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
      /* Make sure attribute cannot clobber */
      if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
        return false;
      }
      /* Allow valid data-* attributes: At least one character after "-"
          (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
          XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
          We don't need to check the value; it's always URI safe. */


      if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR$1, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) ; else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
        if ( // First condition does a very basic check if a) it's basically a valid custom element tagname AND
        // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
        // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
        _basicCustomElementTest(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName)) || // Alternative, second condition checks if it's an `is`-attribute, AND
        // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
        lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ; else {
          return false;
        }
        /* Check value is safe. First, is attr inert? If so, is safe */

      } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; else if (!value) ; else {
        return false;
      }

      return true;
    };
    /**
     * _basicCustomElementCheck
     * checks if at least one dash is included in tagName, and it's not the first char
     * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name
     * @param {string} tagName name of the tag of the node to sanitize
     */


    var _basicCustomElementTest = function _basicCustomElementTest(tagName) {
      return tagName.indexOf('-') > 0;
    };
    /**
     * _sanitizeAttributes
     *
     * @protect attributes
     * @protect nodeName
     * @protect removeAttribute
     * @protect setAttribute
     *
     * @param  {Node} currentNode to sanitize
     */


    var _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
      var attr;
      var value;
      var lcName;
      var l;
      /* Execute a hook if present */

      _executeHook('beforeSanitizeAttributes', currentNode, null);

      var attributes = currentNode.attributes;
      /* Check if we have attributes; if not we might have a text node */

      if (!attributes) {
        return;
      }

      var hookEvent = {
        attrName: '',
        attrValue: '',
        keepAttr: true,
        allowedAttributes: ALLOWED_ATTR
      };
      l = attributes.length;
      /* Go backwards over all attributes; safely remove bad ones */

      while (l--) {
        attr = attributes[l];
        var _attr = attr,
            name = _attr.name,
            namespaceURI = _attr.namespaceURI;
        value = name === 'value' ? attr.value : stringTrim(attr.value);
        lcName = transformCaseFunc(name);
        /* Execute a hook if present */

        hookEvent.attrName = lcName;
        hookEvent.attrValue = value;
        hookEvent.keepAttr = true;
        hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set

        _executeHook('uponSanitizeAttribute', currentNode, hookEvent);

        value = hookEvent.attrValue;
        /* Did the hooks approve of the attribute? */

        if (hookEvent.forceKeepAttr) {
          continue;
        }
        /* Remove attribute */


        _removeAttribute(name, currentNode);
        /* Did the hooks approve of the attribute? */


        if (!hookEvent.keepAttr) {
          continue;
        }
        /* Work around a security issue in jQuery 3.0 */


        if (regExpTest(/\/>/i, value)) {
          _removeAttribute(name, currentNode);

          continue;
        }
        /* Sanitize attribute content to be template-safe */


        if (SAFE_FOR_TEMPLATES) {
          value = stringReplace(value, MUSTACHE_EXPR$1, ' ');
          value = stringReplace(value, ERB_EXPR$1, ' ');
        }
        /* Is `value` valid for this attribute? */


        var lcTag = transformCaseFunc(currentNode.nodeName);

        if (!_isValidAttribute(lcTag, lcName, value)) {
          continue;
        }
        /* Handle invalid data-* attribute set by try-catching it */


        try {
          if (namespaceURI) {
            currentNode.setAttributeNS(namespaceURI, name, value);
          } else {
            /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
            currentNode.setAttribute(name, value);
          }

          arrayPop(DOMPurify.removed);
        } catch (_) {}
      }
      /* Execute a hook if present */


      _executeHook('afterSanitizeAttributes', currentNode, null);
    };
    /**
     * _sanitizeShadowDOM
     *
     * @param  {DocumentFragment} fragment to iterate over recursively
     */


    var _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {
      var shadowNode;

      var shadowIterator = _createIterator(fragment);
      /* Execute a hook if present */


      _executeHook('beforeSanitizeShadowDOM', fragment, null);

      while (shadowNode = shadowIterator.nextNode()) {
        /* Execute a hook if present */
        _executeHook('uponSanitizeShadowNode', shadowNode, null);
        /* Sanitize tags and elements */


        if (_sanitizeElements(shadowNode)) {
          continue;
        }
        /* Deep shadow DOM detected */


        if (shadowNode.content instanceof DocumentFragment) {
          _sanitizeShadowDOM(shadowNode.content);
        }
        /* Check attributes, sanitize if necessary */


        _sanitizeAttributes(shadowNode);
      }
      /* Execute a hook if present */


      _executeHook('afterSanitizeShadowDOM', fragment, null);
    };
    /**
     * Sanitize
     * Public method providing core sanitation functionality
     *
     * @param {String|Node} dirty string or DOM node
     * @param {Object} configuration object
     */
    // eslint-disable-next-line complexity


    DOMPurify.sanitize = function (dirty, cfg) {
      var body;
      var importedNode;
      var currentNode;
      var oldNode;
      var returnNode;
      /* Make sure we have a string to sanitize.
        DO NOT return early, as this will return the wrong type if
        the user has requested a DOM object rather than a string */

      IS_EMPTY_INPUT = !dirty;

      if (IS_EMPTY_INPUT) {
        dirty = '<!-->';
      }
      /* Stringify, in case dirty is an object */


      if (typeof dirty !== 'string' && !_isNode(dirty)) {
        // eslint-disable-next-line no-negated-condition
        if (typeof dirty.toString !== 'function') {
          throw typeErrorCreate('toString is not a function');
        } else {
          dirty = dirty.toString();

          if (typeof dirty !== 'string') {
            throw typeErrorCreate('dirty is not a string, aborting');
          }
        }
      }
      /* Check we can run. Otherwise fall back or ignore */


      if (!DOMPurify.isSupported) {
        if (_typeof(window.toStaticHTML) === 'object' || typeof window.toStaticHTML === 'function') {
          if (typeof dirty === 'string') {
            return window.toStaticHTML(dirty);
          }

          if (_isNode(dirty)) {
            return window.toStaticHTML(dirty.outerHTML);
          }
        }

        return dirty;
      }
      /* Assign config vars */


      if (!SET_CONFIG) {
        _parseConfig(cfg);
      }
      /* Clean up removed elements */


      DOMPurify.removed = [];
      /* Check if dirty is correctly typed for IN_PLACE */

      if (typeof dirty === 'string') {
        IN_PLACE = false;
      }

      if (IN_PLACE) {
        /* Do some early pre-sanitization to avoid unsafe root nodes */
        if (dirty.nodeName) {
          var tagName = transformCaseFunc(dirty.nodeName);

          if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
            throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
          }
        }
      } else if (dirty instanceof Node) {
        /* If dirty is a DOM element, append to an empty document to avoid
           elements being stripped by the parser */
        body = _initDocument('<!---->');
        importedNode = body.ownerDocument.importNode(dirty, true);

        if (importedNode.nodeType === 1 && importedNode.nodeName === 'BODY') {
          /* Node is already a body, use as is */
          body = importedNode;
        } else if (importedNode.nodeName === 'HTML') {
          body = importedNode;
        } else {
          // eslint-disable-next-line unicorn/prefer-dom-node-append
          body.appendChild(importedNode);
        }
      } else {
        /* Exit directly if we have nothing to do */
        if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && // eslint-disable-next-line unicorn/prefer-includes
        dirty.indexOf('<') === -1) {
          return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
        }
        /* Initialize the document to work on */


        body = _initDocument(dirty);
        /* Check we have a DOM node from the data */

        if (!body) {
          return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';
        }
      }
      /* Remove first element node (ours) if FORCE_BODY is set */


      if (body && FORCE_BODY) {
        _forceRemove(body.firstChild);
      }
      /* Get node iterator */


      var nodeIterator = _createIterator(IN_PLACE ? dirty : body);
      /* Now start iterating over the created document */


      while (currentNode = nodeIterator.nextNode()) {
        /* Fix IE's strange behavior with manipulated textNodes #89 */
        if (currentNode.nodeType === 3 && currentNode === oldNode) {
          continue;
        }
        /* Sanitize tags and elements */


        if (_sanitizeElements(currentNode)) {
          continue;
        }
        /* Shadow DOM detected, sanitize it */


        if (currentNode.content instanceof DocumentFragment) {
          _sanitizeShadowDOM(currentNode.content);
        }
        /* Check attributes, sanitize if necessary */


        _sanitizeAttributes(currentNode);

        oldNode = currentNode;
      }

      oldNode = null;
      /* If we sanitized `dirty` in-place, return it. */

      if (IN_PLACE) {
        return dirty;
      }
      /* Return sanitized string or DOM */


      if (RETURN_DOM) {
        if (RETURN_DOM_FRAGMENT) {
          returnNode = createDocumentFragment.call(body.ownerDocument);

          while (body.firstChild) {
            // eslint-disable-next-line unicorn/prefer-dom-node-append
            returnNode.appendChild(body.firstChild);
          }
        } else {
          returnNode = body;
        }

        if (ALLOWED_ATTR.shadowroot) {
          /*
            AdoptNode() is not used because internal state is not reset
            (e.g. the past names map of a HTMLFormElement), this is safe
            in theory but we would rather not risk another attack vector.
            The state that is cloned by importNode() is explicitly defined
            by the specs.
          */
          returnNode = importNode.call(originalDocument, returnNode, true);
        }

        return returnNode;
      }

      var serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
      /* Serialize doctype if allowed */

      if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
        serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;
      }
      /* Sanitize final string template-safe */


      if (SAFE_FOR_TEMPLATES) {
        serializedHTML = stringReplace(serializedHTML, MUSTACHE_EXPR$1, ' ');
        serializedHTML = stringReplace(serializedHTML, ERB_EXPR$1, ' ');
      }

      return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
    };
    /**
     * Public method to set the configuration once
     * setConfig
     *
     * @param {Object} cfg configuration object
     */


    DOMPurify.setConfig = function (cfg) {
      _parseConfig(cfg);

      SET_CONFIG = true;
    };
    /**
     * Public method to remove the configuration
     * clearConfig
     *
     */


    DOMPurify.clearConfig = function () {
      CONFIG = null;
      SET_CONFIG = false;
    };
    /**
     * Public method to check if an attribute value is valid.
     * Uses last set config, if any. Otherwise, uses config defaults.
     * isValidAttribute
     *
     * @param  {string} tag Tag name of containing element.
     * @param  {string} attr Attribute name.
     * @param  {string} value Attribute value.
     * @return {Boolean} Returns true if `value` is valid. Otherwise, returns false.
     */


    DOMPurify.isValidAttribute = function (tag, attr, value) {
      /* Initialize shared config vars if necessary. */
      if (!CONFIG) {
        _parseConfig({});
      }

      var lcTag = transformCaseFunc(tag);
      var lcName = transformCaseFunc(attr);
      return _isValidAttribute(lcTag, lcName, value);
    };
    /**
     * AddHook
     * Public method to add DOMPurify hooks
     *
     * @param {String} entryPoint entry point for the hook to add
     * @param {Function} hookFunction function to execute
     */


    DOMPurify.addHook = function (entryPoint, hookFunction) {
      if (typeof hookFunction !== 'function') {
        return;
      }

      hooks[entryPoint] = hooks[entryPoint] || [];
      arrayPush(hooks[entryPoint], hookFunction);
    };
    /**
     * RemoveHook
     * Public method to remove a DOMPurify hook at a given entryPoint
     * (pops it from the stack of hooks if more are present)
     *
     * @param {String} entryPoint entry point for the hook to remove
     * @return {Function} removed(popped) hook
     */


    DOMPurify.removeHook = function (entryPoint) {
      if (hooks[entryPoint]) {
        return arrayPop(hooks[entryPoint]);
      }
    };
    /**
     * RemoveHooks
     * Public method to remove all DOMPurify hooks at a given entryPoint
     *
     * @param  {String} entryPoint entry point for the hooks to remove
     */


    DOMPurify.removeHooks = function (entryPoint) {
      if (hooks[entryPoint]) {
        hooks[entryPoint] = [];
      }
    };
    /**
     * RemoveAllHooks
     * Public method to remove all DOMPurify hooks
     *
     */


    DOMPurify.removeAllHooks = function () {
      hooks = {};
    };

    return DOMPurify;
  }

  var purify = createDOMPurify();

  let nextCreditId = 0;
  const creditToId = {};

  /**
   * A credit contains data pertaining to how to display attributions/credits for certain content on the screen.
   * @param {String} html An string representing an html code snippet
   * @param {Boolean} [showOnScreen=false] If true, the credit will be visible in the main credit container.  Otherwise, it will appear in a popover
   *
   * @alias Credit
   * @constructor
   *
   * @exception {DeveloperError} html is required.
   *
   * @example
   * //Create a credit with a tooltip, image and link
   * const credit = new Cesium.Credit('<a href="https://cesium.com/" target="_blank"><img src="/images/cesium_logo.png" title="Cesium"/></a>');
   */
  function Credit(html, showOnScreen) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("html", html);
    //>>includeEnd('debug');
    let id;
    const key = html;

    if (defined(creditToId[key])) {
      id = creditToId[key];
    } else {
      id = nextCreditId++;
      creditToId[key] = id;
    }

    showOnScreen = defaultValue(showOnScreen, false);

    // Credits are immutable so generate an id to use to optimize equal()
    this._id = id;
    this._html = html;
    this._showOnScreen = showOnScreen;
    this._element = undefined;
  }

  Object.defineProperties(Credit.prototype, {
    /**
     * The credit content
     * @memberof Credit.prototype
     * @type {String}
     * @readonly
     */
    html: {
      get: function () {
        return this._html;
      },
    },

    /**
     * @memberof Credit.prototype
     * @type {Number}
     * @readonly
     *
     * @private
     */
    id: {
      get: function () {
        return this._id;
      },
    },

    /**
     * Whether the credit should be displayed on screen or in a lightbox
     * @memberof Credit.prototype
     * @type {Boolean}
     */
    showOnScreen: {
      get: function () {
        return this._showOnScreen;
      },
      set: function (value) {
        this._showOnScreen = value;
      },
    },

    /**
     * Gets the credit element
     * @memberof Credit.prototype
     * @type {HTMLElement}
     * @readonly
     */
    element: {
      get: function () {
        if (!defined(this._element)) {
          const html = purify.sanitize(this._html);

          const div = document.createElement("div");
          div._creditId = this._id;
          div.style.display = "inline";
          div.innerHTML = html;

          const links = div.querySelectorAll("a");
          for (let i = 0; i < links.length; i++) {
            links[i].setAttribute("target", "_blank");
          }

          this._element = div;
        }
        return this._element;
      },
    },
  });

  /**
   * Returns true if the credits are equal
   *
   * @param {Credit} left The first credit
   * @param {Credit} right The second credit
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  Credit.equals = function (left, right) {
    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        left._id === right._id &&
        left._showOnScreen === right._showOnScreen)
    );
  };

  /**
   * Returns true if the credits are equal
   *
   * @param {Credit} credit The credit to compare to.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  Credit.prototype.equals = function (credit) {
    return Credit.equals(this, credit);
  };

  /**
   * @private
   * @param attribution
   * @return {Credit}
   */
  Credit.getIonCredit = function (attribution) {
    const showOnScreen =
      defined(attribution.collapsible) && !attribution.collapsible;
    const credit = new Credit(attribution.html, showOnScreen);

    credit._isIon = credit.html.indexOf("ion-credit.png") !== -1;
    return credit;
  };

  /**
   * Duplicates a Credit instance.
   *
   * @param {Credit} [credit] The Credit to duplicate.
   * @returns {Credit} A new Credit instance that is a duplicate of the one provided. (Returns undefined if the credit is undefined)
   */
  Credit.clone = function (credit) {
    if (defined(credit)) {
      return new Credit(credit.html, credit.showOnScreen);
    }
  };

  /**
   * The encoding that is used for a heightmap
   *
   * @enum {Number}
   */
  const HeightmapEncoding = {
    /**
     * No encoding
     *
     * @type {Number}
     * @constant
     */
    NONE: 0,

    /**
     * LERC encoding
     *
     * @type {Number}
     * @constant
     *
     * @see {@link https://github.com/Esri/lerc|The LERC specification}
     */
    LERC: 1,
  };
  var HeightmapEncoding$1 = Object.freeze(HeightmapEncoding);

  /**
   * Creates an instance of an AxisAlignedBoundingBox from the minimum and maximum points along the x, y, and z axes.
   * @alias AxisAlignedBoundingBox
   * @constructor
   *
   * @param {Cartesian3} [minimum=Cartesian3.ZERO] The minimum point along the x, y, and z axes.
   * @param {Cartesian3} [maximum=Cartesian3.ZERO] The maximum point along the x, y, and z axes.
   * @param {Cartesian3} [center] The center of the box; automatically computed if not supplied.
   *
   * @see BoundingSphere
   * @see BoundingRectangle
   */
  function AxisAlignedBoundingBox(minimum, maximum, center) {
    /**
     * The minimum point defining the bounding box.
     * @type {Cartesian3}
     * @default {@link Cartesian3.ZERO}
     */
    this.minimum = Cartesian3.clone(defaultValue(minimum, Cartesian3.ZERO));

    /**
     * The maximum point defining the bounding box.
     * @type {Cartesian3}
     * @default {@link Cartesian3.ZERO}
     */
    this.maximum = Cartesian3.clone(defaultValue(maximum, Cartesian3.ZERO));

    // If center was not defined, compute it.
    if (!defined(center)) {
      center = Cartesian3.midpoint(this.minimum, this.maximum, new Cartesian3());
    } else {
      center = Cartesian3.clone(center);
    }

    /**
     * The center point of the bounding box.
     * @type {Cartesian3}
     */
    this.center = center;
  }

  /**
   * Creates an instance of an AxisAlignedBoundingBox from its corners.
   *
   * @param {Cartesian3} minimum The minimum point along the x, y, and z axes.
   * @param {Cartesian3} maximum The maximum point along the x, y, and z axes.
   * @param {AxisAlignedBoundingBox} [result] The object onto which to store the result.
   * @returns {AxisAlignedBoundingBox} The modified result parameter or a new AxisAlignedBoundingBox instance if one was not provided.
   *
   * @example
   * // Compute an axis aligned bounding box from the two corners.
   * const box = Cesium.AxisAlignedBoundingBox.fromCorners(new Cesium.Cartesian3(-1, -1, -1), new Cesium.Cartesian3(1, 1, 1));
   */
  AxisAlignedBoundingBox.fromCorners = function (minimum, maximum, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("minimum", minimum);
    Check.defined("maximum", maximum);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new AxisAlignedBoundingBox();
    }

    result.minimum = Cartesian3.clone(minimum, result.minimum);
    result.maximum = Cartesian3.clone(maximum, result.maximum);
    result.center = Cartesian3.midpoint(minimum, maximum, result.center);

    return result;
  };

  /**
   * Computes an instance of an AxisAlignedBoundingBox. The box is determined by
   * finding the points spaced the farthest apart on the x, y, and z axes.
   *
   * @param {Cartesian3[]} positions List of points that the bounding box will enclose.  Each point must have a <code>x</code>, <code>y</code>, and <code>z</code> properties.
   * @param {AxisAlignedBoundingBox} [result] The object onto which to store the result.
   * @returns {AxisAlignedBoundingBox} The modified result parameter or a new AxisAlignedBoundingBox instance if one was not provided.
   *
   * @example
   * // Compute an axis aligned bounding box enclosing two points.
   * const box = Cesium.AxisAlignedBoundingBox.fromPoints([new Cesium.Cartesian3(2, 0, 0), new Cesium.Cartesian3(-2, 0, 0)]);
   */
  AxisAlignedBoundingBox.fromPoints = function (positions, result) {
    if (!defined(result)) {
      result = new AxisAlignedBoundingBox();
    }

    if (!defined(positions) || positions.length === 0) {
      result.minimum = Cartesian3.clone(Cartesian3.ZERO, result.minimum);
      result.maximum = Cartesian3.clone(Cartesian3.ZERO, result.maximum);
      result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
      return result;
    }

    let minimumX = positions[0].x;
    let minimumY = positions[0].y;
    let minimumZ = positions[0].z;

    let maximumX = positions[0].x;
    let maximumY = positions[0].y;
    let maximumZ = positions[0].z;

    const length = positions.length;
    for (let i = 1; i < length; i++) {
      const p = positions[i];
      const x = p.x;
      const y = p.y;
      const z = p.z;

      minimumX = Math.min(x, minimumX);
      maximumX = Math.max(x, maximumX);
      minimumY = Math.min(y, minimumY);
      maximumY = Math.max(y, maximumY);
      minimumZ = Math.min(z, minimumZ);
      maximumZ = Math.max(z, maximumZ);
    }

    const minimum = result.minimum;
    minimum.x = minimumX;
    minimum.y = minimumY;
    minimum.z = minimumZ;

    const maximum = result.maximum;
    maximum.x = maximumX;
    maximum.y = maximumY;
    maximum.z = maximumZ;

    result.center = Cartesian3.midpoint(minimum, maximum, result.center);

    return result;
  };

  /**
   * Duplicates a AxisAlignedBoundingBox instance.
   *
   * @param {AxisAlignedBoundingBox} box The bounding box to duplicate.
   * @param {AxisAlignedBoundingBox} [result] The object onto which to store the result.
   * @returns {AxisAlignedBoundingBox} The modified result parameter or a new AxisAlignedBoundingBox instance if none was provided. (Returns undefined if box is undefined)
   */
  AxisAlignedBoundingBox.clone = function (box, result) {
    if (!defined(box)) {
      return undefined;
    }

    if (!defined(result)) {
      return new AxisAlignedBoundingBox(box.minimum, box.maximum, box.center);
    }

    result.minimum = Cartesian3.clone(box.minimum, result.minimum);
    result.maximum = Cartesian3.clone(box.maximum, result.maximum);
    result.center = Cartesian3.clone(box.center, result.center);
    return result;
  };

  /**
   * Compares the provided AxisAlignedBoundingBox componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {AxisAlignedBoundingBox} [left] The first AxisAlignedBoundingBox.
   * @param {AxisAlignedBoundingBox} [right] The second AxisAlignedBoundingBox.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  AxisAlignedBoundingBox.equals = function (left, right) {
    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        Cartesian3.equals(left.center, right.center) &&
        Cartesian3.equals(left.minimum, right.minimum) &&
        Cartesian3.equals(left.maximum, right.maximum))
    );
  };

  let intersectScratch = new Cartesian3();
  /**
   * Determines which side of a plane a box is located.
   *
   * @param {AxisAlignedBoundingBox} box The bounding box to test.
   * @param {Plane} plane The plane to test against.
   * @returns {Intersect} {@link Intersect.INSIDE} if the entire box is on the side of the plane
   *                      the normal is pointing, {@link Intersect.OUTSIDE} if the entire box is
   *                      on the opposite side, and {@link Intersect.INTERSECTING} if the box
   *                      intersects the plane.
   */
  AxisAlignedBoundingBox.intersectPlane = function (box, plane) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("box", box);
    Check.defined("plane", plane);
    //>>includeEnd('debug');

    intersectScratch = Cartesian3.subtract(
      box.maximum,
      box.minimum,
      intersectScratch
    );
    const h = Cartesian3.multiplyByScalar(
      intersectScratch,
      0.5,
      intersectScratch
    ); //The positive half diagonal
    const normal = plane.normal;
    const e =
      h.x * Math.abs(normal.x) +
      h.y * Math.abs(normal.y) +
      h.z * Math.abs(normal.z);
    const s = Cartesian3.dot(box.center, normal) + plane.distance; //signed distance from center

    if (s - e > 0) {
      return Intersect$1.INSIDE;
    }

    if (s + e < 0) {
      //Not in front because normals point inward
      return Intersect$1.OUTSIDE;
    }

    return Intersect$1.INTERSECTING;
  };

  /**
   * Duplicates this AxisAlignedBoundingBox instance.
   *
   * @param {AxisAlignedBoundingBox} [result] The object onto which to store the result.
   * @returns {AxisAlignedBoundingBox} The modified result parameter or a new AxisAlignedBoundingBox instance if one was not provided.
   */
  AxisAlignedBoundingBox.prototype.clone = function (result) {
    return AxisAlignedBoundingBox.clone(this, result);
  };

  /**
   * Determines which side of a plane this box is located.
   *
   * @param {Plane} plane The plane to test against.
   * @returns {Intersect} {@link Intersect.INSIDE} if the entire box is on the side of the plane
   *                      the normal is pointing, {@link Intersect.OUTSIDE} if the entire box is
   *                      on the opposite side, and {@link Intersect.INTERSECTING} if the box
   *                      intersects the plane.
   */
  AxisAlignedBoundingBox.prototype.intersectPlane = function (plane) {
    return AxisAlignedBoundingBox.intersectPlane(this, plane);
  };

  /**
   * Compares this AxisAlignedBoundingBox against the provided AxisAlignedBoundingBox componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {AxisAlignedBoundingBox} [right] The right hand side AxisAlignedBoundingBox.
   * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
   */
  AxisAlignedBoundingBox.prototype.equals = function (right) {
    return AxisAlignedBoundingBox.equals(this, right);
  };

  /**
   * Determine whether or not other objects are visible or hidden behind the visible horizon defined by
   * an {@link Ellipsoid} and a camera position.  The ellipsoid is assumed to be located at the
   * origin of the coordinate system.  This class uses the algorithm described in the
   * {@link https://cesium.com/blog/2013/04/25/Horizon-culling/|Horizon Culling} blog post.
   *
   * @alias EllipsoidalOccluder
   *
   * @param {Ellipsoid} ellipsoid The ellipsoid to use as an occluder.
   * @param {Cartesian3} [cameraPosition] The coordinate of the viewer/camera.  If this parameter is not
   *        specified, {@link EllipsoidalOccluder#cameraPosition} must be called before
   *        testing visibility.
   *
   * @constructor
   *
   * @example
   * // Construct an ellipsoidal occluder with radii 1.0, 1.1, and 0.9.
   * const cameraPosition = new Cesium.Cartesian3(5.0, 6.0, 7.0);
   * const occluderEllipsoid = new Cesium.Ellipsoid(1.0, 1.1, 0.9);
   * const occluder = new Cesium.EllipsoidalOccluder(occluderEllipsoid, cameraPosition);
   *
   * @private
   */
  function EllipsoidalOccluder(ellipsoid, cameraPosition) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("ellipsoid", ellipsoid);
    //>>includeEnd('debug');

    this._ellipsoid = ellipsoid;
    this._cameraPosition = new Cartesian3();
    this._cameraPositionInScaledSpace = new Cartesian3();
    this._distanceToLimbInScaledSpaceSquared = 0.0;

    // cameraPosition fills in the above values
    if (defined(cameraPosition)) {
      this.cameraPosition = cameraPosition;
    }
  }

  Object.defineProperties(EllipsoidalOccluder.prototype, {
    /**
     * Gets the occluding ellipsoid.
     * @memberof EllipsoidalOccluder.prototype
     * @type {Ellipsoid}
     */
    ellipsoid: {
      get: function () {
        return this._ellipsoid;
      },
    },
    /**
     * Gets or sets the position of the camera.
     * @memberof EllipsoidalOccluder.prototype
     * @type {Cartesian3}
     */
    cameraPosition: {
      get: function () {
        return this._cameraPosition;
      },
      set: function (cameraPosition) {
        // See https://cesium.com/blog/2013/04/25/Horizon-culling/
        const ellipsoid = this._ellipsoid;
        const cv = ellipsoid.transformPositionToScaledSpace(
          cameraPosition,
          this._cameraPositionInScaledSpace
        );
        const vhMagnitudeSquared = Cartesian3.magnitudeSquared(cv) - 1.0;

        Cartesian3.clone(cameraPosition, this._cameraPosition);
        this._cameraPositionInScaledSpace = cv;
        this._distanceToLimbInScaledSpaceSquared = vhMagnitudeSquared;
      },
    },
  });

  const scratchCartesian$a = new Cartesian3();

  /**
   * Determines whether or not a point, the <code>occludee</code>, is hidden from view by the occluder.
   *
   * @param {Cartesian3} occludee The point to test for visibility.
   * @returns {Boolean} <code>true</code> if the occludee is visible; otherwise <code>false</code>.
   *
   * @example
   * const cameraPosition = new Cesium.Cartesian3(0, 0, 2.5);
   * const ellipsoid = new Cesium.Ellipsoid(1.0, 1.1, 0.9);
   * const occluder = new Cesium.EllipsoidalOccluder(ellipsoid, cameraPosition);
   * const point = new Cesium.Cartesian3(0, -3, -3);
   * occluder.isPointVisible(point); //returns true
   */
  EllipsoidalOccluder.prototype.isPointVisible = function (occludee) {
    const ellipsoid = this._ellipsoid;
    const occludeeScaledSpacePosition = ellipsoid.transformPositionToScaledSpace(
      occludee,
      scratchCartesian$a
    );
    return isScaledSpacePointVisible(
      occludeeScaledSpacePosition,
      this._cameraPositionInScaledSpace,
      this._distanceToLimbInScaledSpaceSquared
    );
  };

  /**
   * Determines whether or not a point expressed in the ellipsoid scaled space, is hidden from view by the
   * occluder.  To transform a Cartesian X, Y, Z position in the coordinate system aligned with the ellipsoid
   * into the scaled space, call {@link Ellipsoid#transformPositionToScaledSpace}.
   *
   * @param {Cartesian3} occludeeScaledSpacePosition The point to test for visibility, represented in the scaled space.
   * @returns {Boolean} <code>true</code> if the occludee is visible; otherwise <code>false</code>.
   *
   * @example
   * const cameraPosition = new Cesium.Cartesian3(0, 0, 2.5);
   * const ellipsoid = new Cesium.Ellipsoid(1.0, 1.1, 0.9);
   * const occluder = new Cesium.EllipsoidalOccluder(ellipsoid, cameraPosition);
   * const point = new Cesium.Cartesian3(0, -3, -3);
   * const scaledSpacePoint = ellipsoid.transformPositionToScaledSpace(point);
   * occluder.isScaledSpacePointVisible(scaledSpacePoint); //returns true
   */
  EllipsoidalOccluder.prototype.isScaledSpacePointVisible = function (
    occludeeScaledSpacePosition
  ) {
    return isScaledSpacePointVisible(
      occludeeScaledSpacePosition,
      this._cameraPositionInScaledSpace,
      this._distanceToLimbInScaledSpaceSquared
    );
  };

  const scratchCameraPositionInScaledSpaceShrunk = new Cartesian3();

  /**
   * Similar to {@link EllipsoidalOccluder#isScaledSpacePointVisible} except tests against an
   * ellipsoid that has been shrunk by the minimum height when the minimum height is below
   * the ellipsoid. This is intended to be used with points generated by
   * {@link EllipsoidalOccluder#computeHorizonCullingPointPossiblyUnderEllipsoid} or
   * {@link EllipsoidalOccluder#computeHorizonCullingPointFromVerticesPossiblyUnderEllipsoid}.
   *
   * @param {Cartesian3} occludeeScaledSpacePosition The point to test for visibility, represented in the scaled space of the possibly-shrunk ellipsoid.
   * @returns {Boolean} <code>true</code> if the occludee is visible; otherwise <code>false</code>.
   */
  EllipsoidalOccluder.prototype.isScaledSpacePointVisiblePossiblyUnderEllipsoid = function (
    occludeeScaledSpacePosition,
    minimumHeight
  ) {
    const ellipsoid = this._ellipsoid;
    let vhMagnitudeSquared;
    let cv;

    if (
      defined(minimumHeight) &&
      minimumHeight < 0.0 &&
      ellipsoid.minimumRadius > -minimumHeight
    ) {
      // This code is similar to the cameraPosition setter, but unrolled for performance because it will be called a lot.
      cv = scratchCameraPositionInScaledSpaceShrunk;
      cv.x = this._cameraPosition.x / (ellipsoid.radii.x + minimumHeight);
      cv.y = this._cameraPosition.y / (ellipsoid.radii.y + minimumHeight);
      cv.z = this._cameraPosition.z / (ellipsoid.radii.z + minimumHeight);
      vhMagnitudeSquared = cv.x * cv.x + cv.y * cv.y + cv.z * cv.z - 1.0;
    } else {
      cv = this._cameraPositionInScaledSpace;
      vhMagnitudeSquared = this._distanceToLimbInScaledSpaceSquared;
    }

    return isScaledSpacePointVisible(
      occludeeScaledSpacePosition,
      cv,
      vhMagnitudeSquared
    );
  };

  /**
   * Computes a point that can be used for horizon culling from a list of positions.  If the point is below
   * the horizon, all of the positions are guaranteed to be below the horizon as well.  The returned point
   * is expressed in the ellipsoid-scaled space and is suitable for use with
   * {@link EllipsoidalOccluder#isScaledSpacePointVisible}.
   *
   * @param {Cartesian3} directionToPoint The direction that the computed point will lie along.
   *                     A reasonable direction to use is the direction from the center of the ellipsoid to
   *                     the center of the bounding sphere computed from the positions.  The direction need not
   *                     be normalized.
   * @param {Cartesian3[]} positions The positions from which to compute the horizon culling point.  The positions
   *                       must be expressed in a reference frame centered at the ellipsoid and aligned with the
   *                       ellipsoid's axes.
   * @param {Cartesian3} [result] The instance on which to store the result instead of allocating a new instance.
   * @returns {Cartesian3} The computed horizon culling point, expressed in the ellipsoid-scaled space.
   */
  EllipsoidalOccluder.prototype.computeHorizonCullingPoint = function (
    directionToPoint,
    positions,
    result
  ) {
    return computeHorizonCullingPointFromPositions(
      this._ellipsoid,
      directionToPoint,
      positions,
      result
    );
  };

  const scratchEllipsoidShrunk = Ellipsoid.clone(Ellipsoid.UNIT_SPHERE);

  /**
   * Similar to {@link EllipsoidalOccluder#computeHorizonCullingPoint} except computes the culling
   * point relative to an ellipsoid that has been shrunk by the minimum height when the minimum height is below
   * the ellipsoid. The returned point is expressed in the possibly-shrunk ellipsoid-scaled space and is suitable
   * for use with {@link EllipsoidalOccluder#isScaledSpacePointVisiblePossiblyUnderEllipsoid}.
   *
   * @param {Cartesian3} directionToPoint The direction that the computed point will lie along.
   *                     A reasonable direction to use is the direction from the center of the ellipsoid to
   *                     the center of the bounding sphere computed from the positions.  The direction need not
   *                     be normalized.
   * @param {Cartesian3[]} positions The positions from which to compute the horizon culling point.  The positions
   *                       must be expressed in a reference frame centered at the ellipsoid and aligned with the
   *                       ellipsoid's axes.
   * @param {Number} [minimumHeight] The minimum height of all positions. If this value is undefined, all positions are assumed to be above the ellipsoid.
   * @param {Cartesian3} [result] The instance on which to store the result instead of allocating a new instance.
   * @returns {Cartesian3} The computed horizon culling point, expressed in the possibly-shrunk ellipsoid-scaled space.
   */
  EllipsoidalOccluder.prototype.computeHorizonCullingPointPossiblyUnderEllipsoid = function (
    directionToPoint,
    positions,
    minimumHeight,
    result
  ) {
    const possiblyShrunkEllipsoid = getPossiblyShrunkEllipsoid(
      this._ellipsoid,
      minimumHeight,
      scratchEllipsoidShrunk
    );
    return computeHorizonCullingPointFromPositions(
      possiblyShrunkEllipsoid,
      directionToPoint,
      positions,
      result
    );
  };
  /**
   * Computes a point that can be used for horizon culling from a list of positions.  If the point is below
   * the horizon, all of the positions are guaranteed to be below the horizon as well.  The returned point
   * is expressed in the ellipsoid-scaled space and is suitable for use with
   * {@link EllipsoidalOccluder#isScaledSpacePointVisible}.
   *
   * @param {Cartesian3} directionToPoint The direction that the computed point will lie along.
   *                     A reasonable direction to use is the direction from the center of the ellipsoid to
   *                     the center of the bounding sphere computed from the positions.  The direction need not
   *                     be normalized.
   * @param {Number[]} vertices  The vertices from which to compute the horizon culling point.  The positions
   *                   must be expressed in a reference frame centered at the ellipsoid and aligned with the
   *                   ellipsoid's axes.
   * @param {Number} [stride=3]
   * @param {Cartesian3} [center=Cartesian3.ZERO]
   * @param {Cartesian3} [result] The instance on which to store the result instead of allocating a new instance.
   * @returns {Cartesian3} The computed horizon culling point, expressed in the ellipsoid-scaled space.
   */
  EllipsoidalOccluder.prototype.computeHorizonCullingPointFromVertices = function (
    directionToPoint,
    vertices,
    stride,
    center,
    result
  ) {
    return computeHorizonCullingPointFromVertices(
      this._ellipsoid,
      directionToPoint,
      vertices,
      stride,
      center,
      result
    );
  };

  /**
   * Similar to {@link EllipsoidalOccluder#computeHorizonCullingPointFromVertices} except computes the culling
   * point relative to an ellipsoid that has been shrunk by the minimum height when the minimum height is below
   * the ellipsoid. The returned point is expressed in the possibly-shrunk ellipsoid-scaled space and is suitable
   * for use with {@link EllipsoidalOccluder#isScaledSpacePointVisiblePossiblyUnderEllipsoid}.
   *
   * @param {Cartesian3} directionToPoint The direction that the computed point will lie along.
   *                     A reasonable direction to use is the direction from the center of the ellipsoid to
   *                     the center of the bounding sphere computed from the positions.  The direction need not
   *                     be normalized.
   * @param {Number[]} vertices  The vertices from which to compute the horizon culling point.  The positions
   *                   must be expressed in a reference frame centered at the ellipsoid and aligned with the
   *                   ellipsoid's axes.
   * @param {Number} [stride=3]
   * @param {Cartesian3} [center=Cartesian3.ZERO]
   * @param {Number} [minimumHeight] The minimum height of all vertices. If this value is undefined, all vertices are assumed to be above the ellipsoid.
   * @param {Cartesian3} [result] The instance on which to store the result instead of allocating a new instance.
   * @returns {Cartesian3} The computed horizon culling point, expressed in the possibly-shrunk ellipsoid-scaled space.
   */
  EllipsoidalOccluder.prototype.computeHorizonCullingPointFromVerticesPossiblyUnderEllipsoid = function (
    directionToPoint,
    vertices,
    stride,
    center,
    minimumHeight,
    result
  ) {
    const possiblyShrunkEllipsoid = getPossiblyShrunkEllipsoid(
      this._ellipsoid,
      minimumHeight,
      scratchEllipsoidShrunk
    );
    return computeHorizonCullingPointFromVertices(
      possiblyShrunkEllipsoid,
      directionToPoint,
      vertices,
      stride,
      center,
      result
    );
  };

  const subsampleScratch = [];

  /**
   * Computes a point that can be used for horizon culling of a rectangle.  If the point is below
   * the horizon, the ellipsoid-conforming rectangle is guaranteed to be below the horizon as well.
   * The returned point is expressed in the ellipsoid-scaled space and is suitable for use with
   * {@link EllipsoidalOccluder#isScaledSpacePointVisible}.
   *
   * @param {Rectangle} rectangle The rectangle for which to compute the horizon culling point.
   * @param {Ellipsoid} ellipsoid The ellipsoid on which the rectangle is defined.  This may be different from
   *                    the ellipsoid used by this instance for occlusion testing.
   * @param {Cartesian3} [result] The instance on which to store the result instead of allocating a new instance.
   * @returns {Cartesian3} The computed horizon culling point, expressed in the ellipsoid-scaled space.
   */
  EllipsoidalOccluder.prototype.computeHorizonCullingPointFromRectangle = function (
    rectangle,
    ellipsoid,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("rectangle", rectangle);
    //>>includeEnd('debug');

    const positions = Rectangle.subsample(
      rectangle,
      ellipsoid,
      0.0,
      subsampleScratch
    );
    const bs = BoundingSphere.fromPoints(positions);

    // If the bounding sphere center is too close to the center of the occluder, it doesn't make
    // sense to try to horizon cull it.
    if (Cartesian3.magnitude(bs.center) < 0.1 * ellipsoid.minimumRadius) {
      return undefined;
    }

    return this.computeHorizonCullingPoint(bs.center, positions, result);
  };

  const scratchEllipsoidShrunkRadii = new Cartesian3();

  function getPossiblyShrunkEllipsoid(ellipsoid, minimumHeight, result) {
    if (
      defined(minimumHeight) &&
      minimumHeight < 0.0 &&
      ellipsoid.minimumRadius > -minimumHeight
    ) {
      const ellipsoidShrunkRadii = Cartesian3.fromElements(
        ellipsoid.radii.x + minimumHeight,
        ellipsoid.radii.y + minimumHeight,
        ellipsoid.radii.z + minimumHeight,
        scratchEllipsoidShrunkRadii
      );
      ellipsoid = Ellipsoid.fromCartesian3(ellipsoidShrunkRadii, result);
    }
    return ellipsoid;
  }

  function computeHorizonCullingPointFromPositions(
    ellipsoid,
    directionToPoint,
    positions,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("directionToPoint", directionToPoint);
    Check.defined("positions", positions);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Cartesian3();
    }

    const scaledSpaceDirectionToPoint = computeScaledSpaceDirectionToPoint(
      ellipsoid,
      directionToPoint
    );
    let resultMagnitude = 0.0;

    for (let i = 0, len = positions.length; i < len; ++i) {
      const position = positions[i];
      const candidateMagnitude = computeMagnitude(
        ellipsoid,
        position,
        scaledSpaceDirectionToPoint
      );
      if (candidateMagnitude < 0.0) {
        // all points should face the same direction, but this one doesn't, so return undefined
        return undefined;
      }
      resultMagnitude = Math.max(resultMagnitude, candidateMagnitude);
    }

    return magnitudeToPoint(scaledSpaceDirectionToPoint, resultMagnitude, result);
  }

  const positionScratch$d = new Cartesian3();

  function computeHorizonCullingPointFromVertices(
    ellipsoid,
    directionToPoint,
    vertices,
    stride,
    center,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("directionToPoint", directionToPoint);
    Check.defined("vertices", vertices);
    Check.typeOf.number("stride", stride);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Cartesian3();
    }

    stride = defaultValue(stride, 3);
    center = defaultValue(center, Cartesian3.ZERO);
    const scaledSpaceDirectionToPoint = computeScaledSpaceDirectionToPoint(
      ellipsoid,
      directionToPoint
    );
    let resultMagnitude = 0.0;

    for (let i = 0, len = vertices.length; i < len; i += stride) {
      positionScratch$d.x = vertices[i] + center.x;
      positionScratch$d.y = vertices[i + 1] + center.y;
      positionScratch$d.z = vertices[i + 2] + center.z;

      const candidateMagnitude = computeMagnitude(
        ellipsoid,
        positionScratch$d,
        scaledSpaceDirectionToPoint
      );
      if (candidateMagnitude < 0.0) {
        // all points should face the same direction, but this one doesn't, so return undefined
        return undefined;
      }
      resultMagnitude = Math.max(resultMagnitude, candidateMagnitude);
    }

    return magnitudeToPoint(scaledSpaceDirectionToPoint, resultMagnitude, result);
  }

  function isScaledSpacePointVisible(
    occludeeScaledSpacePosition,
    cameraPositionInScaledSpace,
    distanceToLimbInScaledSpaceSquared
  ) {
    // See https://cesium.com/blog/2013/04/25/Horizon-culling/
    const cv = cameraPositionInScaledSpace;
    const vhMagnitudeSquared = distanceToLimbInScaledSpaceSquared;
    const vt = Cartesian3.subtract(
      occludeeScaledSpacePosition,
      cv,
      scratchCartesian$a
    );
    const vtDotVc = -Cartesian3.dot(vt, cv);
    // If vhMagnitudeSquared < 0 then we are below the surface of the ellipsoid and
    // in this case, set the culling plane to be on V.
    const isOccluded =
      vhMagnitudeSquared < 0
        ? vtDotVc > 0
        : vtDotVc > vhMagnitudeSquared &&
          (vtDotVc * vtDotVc) / Cartesian3.magnitudeSquared(vt) >
            vhMagnitudeSquared;
    return !isOccluded;
  }

  const scaledSpaceScratch = new Cartesian3();
  const directionScratch = new Cartesian3();

  function computeMagnitude(ellipsoid, position, scaledSpaceDirectionToPoint) {
    const scaledSpacePosition = ellipsoid.transformPositionToScaledSpace(
      position,
      scaledSpaceScratch
    );
    let magnitudeSquared = Cartesian3.magnitudeSquared(scaledSpacePosition);
    let magnitude = Math.sqrt(magnitudeSquared);
    const direction = Cartesian3.divideByScalar(
      scaledSpacePosition,
      magnitude,
      directionScratch
    );

    // For the purpose of this computation, points below the ellipsoid are consider to be on it instead.
    magnitudeSquared = Math.max(1.0, magnitudeSquared);
    magnitude = Math.max(1.0, magnitude);

    const cosAlpha = Cartesian3.dot(direction, scaledSpaceDirectionToPoint);
    const sinAlpha = Cartesian3.magnitude(
      Cartesian3.cross(direction, scaledSpaceDirectionToPoint, direction)
    );
    const cosBeta = 1.0 / magnitude;
    const sinBeta = Math.sqrt(magnitudeSquared - 1.0) * cosBeta;

    return 1.0 / (cosAlpha * cosBeta - sinAlpha * sinBeta);
  }

  function magnitudeToPoint(
    scaledSpaceDirectionToPoint,
    resultMagnitude,
    result
  ) {
    // The horizon culling point is undefined if there were no positions from which to compute it,
    // the directionToPoint is pointing opposite all of the positions,  or if we computed NaN or infinity.
    if (
      resultMagnitude <= 0.0 ||
      resultMagnitude === 1.0 / 0.0 ||
      resultMagnitude !== resultMagnitude
    ) {
      return undefined;
    }

    return Cartesian3.multiplyByScalar(
      scaledSpaceDirectionToPoint,
      resultMagnitude,
      result
    );
  }

  const directionToPointScratch = new Cartesian3();

  function computeScaledSpaceDirectionToPoint(ellipsoid, directionToPoint) {
    if (Cartesian3.equals(directionToPoint, Cartesian3.ZERO)) {
      return directionToPoint;
    }

    ellipsoid.transformPositionToScaledSpace(
      directionToPoint,
      directionToPointScratch
    );
    return Cartesian3.normalize(directionToPointScratch, directionToPointScratch);
  }

  /**
   * Defines functions for 2nd order polynomial functions of one variable with only real coefficients.
   *
   * @namespace QuadraticRealPolynomial
   */
  const QuadraticRealPolynomial = {};

  /**
   * Provides the discriminant of the quadratic equation from the supplied coefficients.
   *
   * @param {Number} a The coefficient of the 2nd order monomial.
   * @param {Number} b The coefficient of the 1st order monomial.
   * @param {Number} c The coefficient of the 0th order monomial.
   * @returns {Number} The value of the discriminant.
   */
  QuadraticRealPolynomial.computeDiscriminant = function (a, b, c) {
    //>>includeStart('debug', pragmas.debug);
    if (typeof a !== "number") {
      throw new DeveloperError("a is a required number.");
    }
    if (typeof b !== "number") {
      throw new DeveloperError("b is a required number.");
    }
    if (typeof c !== "number") {
      throw new DeveloperError("c is a required number.");
    }
    //>>includeEnd('debug');

    const discriminant = b * b - 4.0 * a * c;
    return discriminant;
  };

  function addWithCancellationCheck$1(left, right, tolerance) {
    const difference = left + right;
    if (
      CesiumMath.sign(left) !== CesiumMath.sign(right) &&
      Math.abs(difference / Math.max(Math.abs(left), Math.abs(right))) < tolerance
    ) {
      return 0.0;
    }

    return difference;
  }

  /**
   * Provides the real valued roots of the quadratic polynomial with the provided coefficients.
   *
   * @param {Number} a The coefficient of the 2nd order monomial.
   * @param {Number} b The coefficient of the 1st order monomial.
   * @param {Number} c The coefficient of the 0th order monomial.
   * @returns {Number[]} The real valued roots.
   */
  QuadraticRealPolynomial.computeRealRoots = function (a, b, c) {
    //>>includeStart('debug', pragmas.debug);
    if (typeof a !== "number") {
      throw new DeveloperError("a is a required number.");
    }
    if (typeof b !== "number") {
      throw new DeveloperError("b is a required number.");
    }
    if (typeof c !== "number") {
      throw new DeveloperError("c is a required number.");
    }
    //>>includeEnd('debug');

    let ratio;
    if (a === 0.0) {
      if (b === 0.0) {
        // Constant function: c = 0.
        return [];
      }

      // Linear function: b * x + c = 0.
      return [-c / b];
    } else if (b === 0.0) {
      if (c === 0.0) {
        // 2nd order monomial: a * x^2 = 0.
        return [0.0, 0.0];
      }

      const cMagnitude = Math.abs(c);
      const aMagnitude = Math.abs(a);

      if (
        cMagnitude < aMagnitude &&
        cMagnitude / aMagnitude < CesiumMath.EPSILON14
      ) {
        // c ~= 0.0.
        // 2nd order monomial: a * x^2 = 0.
        return [0.0, 0.0];
      } else if (
        cMagnitude > aMagnitude &&
        aMagnitude / cMagnitude < CesiumMath.EPSILON14
      ) {
        // a ~= 0.0.
        // Constant function: c = 0.
        return [];
      }

      // a * x^2 + c = 0
      ratio = -c / a;

      if (ratio < 0.0) {
        // Both roots are complex.
        return [];
      }

      // Both roots are real.
      const root = Math.sqrt(ratio);
      return [-root, root];
    } else if (c === 0.0) {
      // a * x^2 + b * x = 0
      ratio = -b / a;
      if (ratio < 0.0) {
        return [ratio, 0.0];
      }

      return [0.0, ratio];
    }

    // a * x^2 + b * x + c = 0
    const b2 = b * b;
    const four_ac = 4.0 * a * c;
    const radicand = addWithCancellationCheck$1(b2, -four_ac, CesiumMath.EPSILON14);

    if (radicand < 0.0) {
      // Both roots are complex.
      return [];
    }

    const q =
      -0.5 *
      addWithCancellationCheck$1(
        b,
        CesiumMath.sign(b) * Math.sqrt(radicand),
        CesiumMath.EPSILON14
      );
    if (b > 0.0) {
      return [q / a, c / q];
    }

    return [c / q, q / a];
  };

  /**
   * Defines functions for 3rd order polynomial functions of one variable with only real coefficients.
   *
   * @namespace CubicRealPolynomial
   */
  const CubicRealPolynomial = {};

  /**
   * Provides the discriminant of the cubic equation from the supplied coefficients.
   *
   * @param {Number} a The coefficient of the 3rd order monomial.
   * @param {Number} b The coefficient of the 2nd order monomial.
   * @param {Number} c The coefficient of the 1st order monomial.
   * @param {Number} d The coefficient of the 0th order monomial.
   * @returns {Number} The value of the discriminant.
   */
  CubicRealPolynomial.computeDiscriminant = function (a, b, c, d) {
    //>>includeStart('debug', pragmas.debug);
    if (typeof a !== "number") {
      throw new DeveloperError("a is a required number.");
    }
    if (typeof b !== "number") {
      throw new DeveloperError("b is a required number.");
    }
    if (typeof c !== "number") {
      throw new DeveloperError("c is a required number.");
    }
    if (typeof d !== "number") {
      throw new DeveloperError("d is a required number.");
    }
    //>>includeEnd('debug');

    const a2 = a * a;
    const b2 = b * b;
    const c2 = c * c;
    const d2 = d * d;

    const discriminant =
      18.0 * a * b * c * d +
      b2 * c2 -
      27.0 * a2 * d2 -
      4.0 * (a * c2 * c + b2 * b * d);
    return discriminant;
  };

  function computeRealRoots(a, b, c, d) {
    const A = a;
    const B = b / 3.0;
    const C = c / 3.0;
    const D = d;

    const AC = A * C;
    const BD = B * D;
    const B2 = B * B;
    const C2 = C * C;
    const delta1 = A * C - B2;
    const delta2 = A * D - B * C;
    const delta3 = B * D - C2;

    const discriminant = 4.0 * delta1 * delta3 - delta2 * delta2;
    let temp;
    let temp1;

    if (discriminant < 0.0) {
      let ABar;
      let CBar;
      let DBar;

      if (B2 * BD >= AC * C2) {
        ABar = A;
        CBar = delta1;
        DBar = -2.0 * B * delta1 + A * delta2;
      } else {
        ABar = D;
        CBar = delta3;
        DBar = -D * delta2 + 2.0 * C * delta3;
      }

      const s = DBar < 0.0 ? -1.0 : 1.0; // This is not Math.Sign()!
      const temp0 = -s * Math.abs(ABar) * Math.sqrt(-discriminant);
      temp1 = -DBar + temp0;

      const x = temp1 / 2.0;
      const p = x < 0.0 ? -Math.pow(-x, 1.0 / 3.0) : Math.pow(x, 1.0 / 3.0);
      const q = temp1 === temp0 ? -p : -CBar / p;

      temp = CBar <= 0.0 ? p + q : -DBar / (p * p + q * q + CBar);

      if (B2 * BD >= AC * C2) {
        return [(temp - B) / A];
      }

      return [-D / (temp + C)];
    }

    const CBarA = delta1;
    const DBarA = -2.0 * B * delta1 + A * delta2;

    const CBarD = delta3;
    const DBarD = -D * delta2 + 2.0 * C * delta3;

    const squareRootOfDiscriminant = Math.sqrt(discriminant);
    const halfSquareRootOf3 = Math.sqrt(3.0) / 2.0;

    let theta = Math.abs(Math.atan2(A * squareRootOfDiscriminant, -DBarA) / 3.0);
    temp = 2.0 * Math.sqrt(-CBarA);
    let cosine = Math.cos(theta);
    temp1 = temp * cosine;
    let temp3 = temp * (-cosine / 2.0 - halfSquareRootOf3 * Math.sin(theta));

    const numeratorLarge = temp1 + temp3 > 2.0 * B ? temp1 - B : temp3 - B;
    const denominatorLarge = A;

    const root1 = numeratorLarge / denominatorLarge;

    theta = Math.abs(Math.atan2(D * squareRootOfDiscriminant, -DBarD) / 3.0);
    temp = 2.0 * Math.sqrt(-CBarD);
    cosine = Math.cos(theta);
    temp1 = temp * cosine;
    temp3 = temp * (-cosine / 2.0 - halfSquareRootOf3 * Math.sin(theta));

    const numeratorSmall = -D;
    const denominatorSmall = temp1 + temp3 < 2.0 * C ? temp1 + C : temp3 + C;

    const root3 = numeratorSmall / denominatorSmall;

    const E = denominatorLarge * denominatorSmall;
    const F =
      -numeratorLarge * denominatorSmall - denominatorLarge * numeratorSmall;
    const G = numeratorLarge * numeratorSmall;

    const root2 = (C * F - B * G) / (-B * F + C * E);

    if (root1 <= root2) {
      if (root1 <= root3) {
        if (root2 <= root3) {
          return [root1, root2, root3];
        }
        return [root1, root3, root2];
      }
      return [root3, root1, root2];
    }
    if (root1 <= root3) {
      return [root2, root1, root3];
    }
    if (root2 <= root3) {
      return [root2, root3, root1];
    }
    return [root3, root2, root1];
  }

  /**
   * Provides the real valued roots of the cubic polynomial with the provided coefficients.
   *
   * @param {Number} a The coefficient of the 3rd order monomial.
   * @param {Number} b The coefficient of the 2nd order monomial.
   * @param {Number} c The coefficient of the 1st order monomial.
   * @param {Number} d The coefficient of the 0th order monomial.
   * @returns {Number[]} The real valued roots.
   */
  CubicRealPolynomial.computeRealRoots = function (a, b, c, d) {
    //>>includeStart('debug', pragmas.debug);
    if (typeof a !== "number") {
      throw new DeveloperError("a is a required number.");
    }
    if (typeof b !== "number") {
      throw new DeveloperError("b is a required number.");
    }
    if (typeof c !== "number") {
      throw new DeveloperError("c is a required number.");
    }
    if (typeof d !== "number") {
      throw new DeveloperError("d is a required number.");
    }
    //>>includeEnd('debug');

    let roots;
    let ratio;
    if (a === 0.0) {
      // Quadratic function: b * x^2 + c * x + d = 0.
      return QuadraticRealPolynomial.computeRealRoots(b, c, d);
    } else if (b === 0.0) {
      if (c === 0.0) {
        if (d === 0.0) {
          // 3rd order monomial: a * x^3 = 0.
          return [0.0, 0.0, 0.0];
        }

        // a * x^3 + d = 0
        ratio = -d / a;
        const root =
          ratio < 0.0 ? -Math.pow(-ratio, 1.0 / 3.0) : Math.pow(ratio, 1.0 / 3.0);
        return [root, root, root];
      } else if (d === 0.0) {
        // x * (a * x^2 + c) = 0.
        roots = QuadraticRealPolynomial.computeRealRoots(a, 0, c);

        // Return the roots in ascending order.
        if (roots.Length === 0) {
          return [0.0];
        }
        return [roots[0], 0.0, roots[1]];
      }

      // Deflated cubic polynomial: a * x^3 + c * x + d= 0.
      return computeRealRoots(a, 0, c, d);
    } else if (c === 0.0) {
      if (d === 0.0) {
        // x^2 * (a * x + b) = 0.
        ratio = -b / a;
        if (ratio < 0.0) {
          return [ratio, 0.0, 0.0];
        }
        return [0.0, 0.0, ratio];
      }
      // a * x^3 + b * x^2 + d = 0.
      return computeRealRoots(a, b, 0, d);
    } else if (d === 0.0) {
      // x * (a * x^2 + b * x + c) = 0
      roots = QuadraticRealPolynomial.computeRealRoots(a, b, c);

      // Return the roots in ascending order.
      if (roots.length === 0) {
        return [0.0];
      } else if (roots[1] <= 0.0) {
        return [roots[0], roots[1], 0.0];
      } else if (roots[0] >= 0.0) {
        return [0.0, roots[0], roots[1]];
      }
      return [roots[0], 0.0, roots[1]];
    }

    return computeRealRoots(a, b, c, d);
  };

  /**
   * Defines functions for 4th order polynomial functions of one variable with only real coefficients.
   *
   * @namespace QuarticRealPolynomial
   */
  const QuarticRealPolynomial = {};

  /**
   * Provides the discriminant of the quartic equation from the supplied coefficients.
   *
   * @param {Number} a The coefficient of the 4th order monomial.
   * @param {Number} b The coefficient of the 3rd order monomial.
   * @param {Number} c The coefficient of the 2nd order monomial.
   * @param {Number} d The coefficient of the 1st order monomial.
   * @param {Number} e The coefficient of the 0th order monomial.
   * @returns {Number} The value of the discriminant.
   */
  QuarticRealPolynomial.computeDiscriminant = function (a, b, c, d, e) {
    //>>includeStart('debug', pragmas.debug);
    if (typeof a !== "number") {
      throw new DeveloperError("a is a required number.");
    }
    if (typeof b !== "number") {
      throw new DeveloperError("b is a required number.");
    }
    if (typeof c !== "number") {
      throw new DeveloperError("c is a required number.");
    }
    if (typeof d !== "number") {
      throw new DeveloperError("d is a required number.");
    }
    if (typeof e !== "number") {
      throw new DeveloperError("e is a required number.");
    }
    //>>includeEnd('debug');

    const a2 = a * a;
    const a3 = a2 * a;
    const b2 = b * b;
    const b3 = b2 * b;
    const c2 = c * c;
    const c3 = c2 * c;
    const d2 = d * d;
    const d3 = d2 * d;
    const e2 = e * e;
    const e3 = e2 * e;

    const discriminant =
      b2 * c2 * d2 -
      4.0 * b3 * d3 -
      4.0 * a * c3 * d2 +
      18 * a * b * c * d3 -
      27.0 * a2 * d2 * d2 +
      256.0 * a3 * e3 +
      e *
        (18.0 * b3 * c * d -
          4.0 * b2 * c3 +
          16.0 * a * c2 * c2 -
          80.0 * a * b * c2 * d -
          6.0 * a * b2 * d2 +
          144.0 * a2 * c * d2) +
      e2 *
        (144.0 * a * b2 * c -
          27.0 * b2 * b2 -
          128.0 * a2 * c2 -
          192.0 * a2 * b * d);
    return discriminant;
  };

  function original(a3, a2, a1, a0) {
    const a3Squared = a3 * a3;

    const p = a2 - (3.0 * a3Squared) / 8.0;
    const q = a1 - (a2 * a3) / 2.0 + (a3Squared * a3) / 8.0;
    const r =
      a0 -
      (a1 * a3) / 4.0 +
      (a2 * a3Squared) / 16.0 -
      (3.0 * a3Squared * a3Squared) / 256.0;

    // Find the roots of the cubic equations:  h^6 + 2 p h^4 + (p^2 - 4 r) h^2 - q^2 = 0.
    const cubicRoots = CubicRealPolynomial.computeRealRoots(
      1.0,
      2.0 * p,
      p * p - 4.0 * r,
      -q * q
    );

    if (cubicRoots.length > 0) {
      const temp = -a3 / 4.0;

      // Use the largest positive root.
      const hSquared = cubicRoots[cubicRoots.length - 1];

      if (Math.abs(hSquared) < CesiumMath.EPSILON14) {
        // y^4 + p y^2 + r = 0.
        const roots = QuadraticRealPolynomial.computeRealRoots(1.0, p, r);

        if (roots.length === 2) {
          const root0 = roots[0];
          const root1 = roots[1];

          let y;
          if (root0 >= 0.0 && root1 >= 0.0) {
            const y0 = Math.sqrt(root0);
            const y1 = Math.sqrt(root1);

            return [temp - y1, temp - y0, temp + y0, temp + y1];
          } else if (root0 >= 0.0 && root1 < 0.0) {
            y = Math.sqrt(root0);
            return [temp - y, temp + y];
          } else if (root0 < 0.0 && root1 >= 0.0) {
            y = Math.sqrt(root1);
            return [temp - y, temp + y];
          }
        }
        return [];
      } else if (hSquared > 0.0) {
        const h = Math.sqrt(hSquared);

        const m = (p + hSquared - q / h) / 2.0;
        const n = (p + hSquared + q / h) / 2.0;

        // Now solve the two quadratic factors:  (y^2 + h y + m)(y^2 - h y + n);
        const roots1 = QuadraticRealPolynomial.computeRealRoots(1.0, h, m);
        const roots2 = QuadraticRealPolynomial.computeRealRoots(1.0, -h, n);

        if (roots1.length !== 0) {
          roots1[0] += temp;
          roots1[1] += temp;

          if (roots2.length !== 0) {
            roots2[0] += temp;
            roots2[1] += temp;

            if (roots1[1] <= roots2[0]) {
              return [roots1[0], roots1[1], roots2[0], roots2[1]];
            } else if (roots2[1] <= roots1[0]) {
              return [roots2[0], roots2[1], roots1[0], roots1[1]];
            } else if (roots1[0] >= roots2[0] && roots1[1] <= roots2[1]) {
              return [roots2[0], roots1[0], roots1[1], roots2[1]];
            } else if (roots2[0] >= roots1[0] && roots2[1] <= roots1[1]) {
              return [roots1[0], roots2[0], roots2[1], roots1[1]];
            } else if (roots1[0] > roots2[0] && roots1[0] < roots2[1]) {
              return [roots2[0], roots1[0], roots2[1], roots1[1]];
            }
            return [roots1[0], roots2[0], roots1[1], roots2[1]];
          }
          return roots1;
        }

        if (roots2.length !== 0) {
          roots2[0] += temp;
          roots2[1] += temp;

          return roots2;
        }
        return [];
      }
    }
    return [];
  }

  function neumark(a3, a2, a1, a0) {
    const a1Squared = a1 * a1;
    const a2Squared = a2 * a2;
    const a3Squared = a3 * a3;

    const p = -2.0 * a2;
    const q = a1 * a3 + a2Squared - 4.0 * a0;
    const r = a3Squared * a0 - a1 * a2 * a3 + a1Squared;

    const cubicRoots = CubicRealPolynomial.computeRealRoots(1.0, p, q, r);

    if (cubicRoots.length > 0) {
      // Use the most positive root
      const y = cubicRoots[0];

      const temp = a2 - y;
      const tempSquared = temp * temp;

      const g1 = a3 / 2.0;
      const h1 = temp / 2.0;

      const m = tempSquared - 4.0 * a0;
      const mError = tempSquared + 4.0 * Math.abs(a0);

      const n = a3Squared - 4.0 * y;
      const nError = a3Squared + 4.0 * Math.abs(y);

      let g2;
      let h2;

      if (y < 0.0 || m * nError < n * mError) {
        const squareRootOfN = Math.sqrt(n);
        g2 = squareRootOfN / 2.0;
        h2 = squareRootOfN === 0.0 ? 0.0 : (a3 * h1 - a1) / squareRootOfN;
      } else {
        const squareRootOfM = Math.sqrt(m);
        g2 = squareRootOfM === 0.0 ? 0.0 : (a3 * h1 - a1) / squareRootOfM;
        h2 = squareRootOfM / 2.0;
      }

      let G;
      let g;
      if (g1 === 0.0 && g2 === 0.0) {
        G = 0.0;
        g = 0.0;
      } else if (CesiumMath.sign(g1) === CesiumMath.sign(g2)) {
        G = g1 + g2;
        g = y / G;
      } else {
        g = g1 - g2;
        G = y / g;
      }

      let H;
      let h;
      if (h1 === 0.0 && h2 === 0.0) {
        H = 0.0;
        h = 0.0;
      } else if (CesiumMath.sign(h1) === CesiumMath.sign(h2)) {
        H = h1 + h2;
        h = a0 / H;
      } else {
        h = h1 - h2;
        H = a0 / h;
      }

      // Now solve the two quadratic factors:  (y^2 + G y + H)(y^2 + g y + h);
      const roots1 = QuadraticRealPolynomial.computeRealRoots(1.0, G, H);
      const roots2 = QuadraticRealPolynomial.computeRealRoots(1.0, g, h);

      if (roots1.length !== 0) {
        if (roots2.length !== 0) {
          if (roots1[1] <= roots2[0]) {
            return [roots1[0], roots1[1], roots2[0], roots2[1]];
          } else if (roots2[1] <= roots1[0]) {
            return [roots2[0], roots2[1], roots1[0], roots1[1]];
          } else if (roots1[0] >= roots2[0] && roots1[1] <= roots2[1]) {
            return [roots2[0], roots1[0], roots1[1], roots2[1]];
          } else if (roots2[0] >= roots1[0] && roots2[1] <= roots1[1]) {
            return [roots1[0], roots2[0], roots2[1], roots1[1]];
          } else if (roots1[0] > roots2[0] && roots1[0] < roots2[1]) {
            return [roots2[0], roots1[0], roots2[1], roots1[1]];
          }
          return [roots1[0], roots2[0], roots1[1], roots2[1]];
        }
        return roots1;
      }
      if (roots2.length !== 0) {
        return roots2;
      }
    }
    return [];
  }

  /**
   * Provides the real valued roots of the quartic polynomial with the provided coefficients.
   *
   * @param {Number} a The coefficient of the 4th order monomial.
   * @param {Number} b The coefficient of the 3rd order monomial.
   * @param {Number} c The coefficient of the 2nd order monomial.
   * @param {Number} d The coefficient of the 1st order monomial.
   * @param {Number} e The coefficient of the 0th order monomial.
   * @returns {Number[]} The real valued roots.
   */
  QuarticRealPolynomial.computeRealRoots = function (a, b, c, d, e) {
    //>>includeStart('debug', pragmas.debug);
    if (typeof a !== "number") {
      throw new DeveloperError("a is a required number.");
    }
    if (typeof b !== "number") {
      throw new DeveloperError("b is a required number.");
    }
    if (typeof c !== "number") {
      throw new DeveloperError("c is a required number.");
    }
    if (typeof d !== "number") {
      throw new DeveloperError("d is a required number.");
    }
    if (typeof e !== "number") {
      throw new DeveloperError("e is a required number.");
    }
    //>>includeEnd('debug');

    if (Math.abs(a) < CesiumMath.EPSILON15) {
      return CubicRealPolynomial.computeRealRoots(b, c, d, e);
    }
    const a3 = b / a;
    const a2 = c / a;
    const a1 = d / a;
    const a0 = e / a;

    let k = a3 < 0.0 ? 1 : 0;
    k += a2 < 0.0 ? k + 1 : k;
    k += a1 < 0.0 ? k + 1 : k;
    k += a0 < 0.0 ? k + 1 : k;

    switch (k) {
      case 0:
        return original(a3, a2, a1, a0);
      case 1:
        return neumark(a3, a2, a1, a0);
      case 2:
        return neumark(a3, a2, a1, a0);
      case 3:
        return original(a3, a2, a1, a0);
      case 4:
        return original(a3, a2, a1, a0);
      case 5:
        return neumark(a3, a2, a1, a0);
      case 6:
        return original(a3, a2, a1, a0);
      case 7:
        return original(a3, a2, a1, a0);
      case 8:
        return neumark(a3, a2, a1, a0);
      case 9:
        return original(a3, a2, a1, a0);
      case 10:
        return original(a3, a2, a1, a0);
      case 11:
        return neumark(a3, a2, a1, a0);
      case 12:
        return original(a3, a2, a1, a0);
      case 13:
        return original(a3, a2, a1, a0);
      case 14:
        return original(a3, a2, a1, a0);
      case 15:
        return original(a3, a2, a1, a0);
      default:
        return undefined;
    }
  };

  /**
   * Represents a ray that extends infinitely from the provided origin in the provided direction.
   * @alias Ray
   * @constructor
   *
   * @param {Cartesian3} [origin=Cartesian3.ZERO] The origin of the ray.
   * @param {Cartesian3} [direction=Cartesian3.ZERO] The direction of the ray.
   */
  function Ray(origin, direction) {
    direction = Cartesian3.clone(defaultValue(direction, Cartesian3.ZERO));
    if (!Cartesian3.equals(direction, Cartesian3.ZERO)) {
      Cartesian3.normalize(direction, direction);
    }

    /**
     * The origin of the ray.
     * @type {Cartesian3}
     * @default {@link Cartesian3.ZERO}
     */
    this.origin = Cartesian3.clone(defaultValue(origin, Cartesian3.ZERO));

    /**
     * The direction of the ray.
     * @type {Cartesian3}
     */
    this.direction = direction;
  }

  /**
   * Duplicates a Ray instance.
   *
   * @param {Ray} ray The ray to duplicate.
   * @param {Ray} [result] The object onto which to store the result.
   * @returns {Ray} The modified result parameter or a new Ray instance if one was not provided. (Returns undefined if ray is undefined)
   */
  Ray.clone = function (ray, result) {
    if (!defined(ray)) {
      return undefined;
    }
    if (!defined(result)) {
      return new Ray(ray.origin, ray.direction);
    }
    result.origin = Cartesian3.clone(ray.origin);
    result.direction = Cartesian3.clone(ray.direction);
    return result;
  };

  /**
   * Computes the point along the ray given by r(t) = o + t*d,
   * where o is the origin of the ray and d is the direction.
   *
   * @param {Ray} ray The ray.
   * @param {Number} t A scalar value.
   * @param {Cartesian3} [result] The object in which the result will be stored.
   * @returns {Cartesian3} The modified result parameter, or a new instance if none was provided.
   *
   * @example
   * //Get the first intersection point of a ray and an ellipsoid.
   * const intersection = Cesium.IntersectionTests.rayEllipsoid(ray, ellipsoid);
   * const point = Cesium.Ray.getPoint(ray, intersection.start);
   */
  Ray.getPoint = function (ray, t, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("ray", ray);
    Check.typeOf.number("t", t);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Cartesian3();
    }

    result = Cartesian3.multiplyByScalar(ray.direction, t, result);
    return Cartesian3.add(ray.origin, result, result);
  };

  /**
   * Functions for computing the intersection between geometries such as rays, planes, triangles, and ellipsoids.
   *
   * @namespace IntersectionTests
   */
  const IntersectionTests = {};

  /**
   * Computes the intersection of a ray and a plane.
   *
   * @param {Ray} ray The ray.
   * @param {Plane} plane The plane.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} The intersection point or undefined if there is no intersections.
   */
  IntersectionTests.rayPlane = function (ray, plane, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(ray)) {
      throw new DeveloperError("ray is required.");
    }
    if (!defined(plane)) {
      throw new DeveloperError("plane is required.");
    }
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Cartesian3();
    }

    const origin = ray.origin;
    const direction = ray.direction;
    const normal = plane.normal;
    const denominator = Cartesian3.dot(normal, direction);

    if (Math.abs(denominator) < CesiumMath.EPSILON15) {
      // Ray is parallel to plane.  The ray may be in the polygon's plane.
      return undefined;
    }

    const t = (-plane.distance - Cartesian3.dot(normal, origin)) / denominator;

    if (t < 0) {
      return undefined;
    }

    result = Cartesian3.multiplyByScalar(direction, t, result);
    return Cartesian3.add(origin, result, result);
  };

  const scratchEdge0 = new Cartesian3();
  const scratchEdge1 = new Cartesian3();
  const scratchPVec = new Cartesian3();
  const scratchTVec = new Cartesian3();
  const scratchQVec = new Cartesian3();

  /**
   * Computes the intersection of a ray and a triangle as a parametric distance along the input ray. The result is negative when the triangle is behind the ray.
   *
   * Implements {@link https://cadxfem.org/inf/Fast%20MinimumStorage%20RayTriangle%20Intersection.pdf|
   * Fast Minimum Storage Ray/Triangle Intersection} by Tomas Moller and Ben Trumbore.
   *
   * @memberof IntersectionTests
   *
   * @param {Ray} ray The ray.
   * @param {Cartesian3} p0 The first vertex of the triangle.
   * @param {Cartesian3} p1 The second vertex of the triangle.
   * @param {Cartesian3} p2 The third vertex of the triangle.
   * @param {Boolean} [cullBackFaces=false] If <code>true</code>, will only compute an intersection with the front face of the triangle
   *                  and return undefined for intersections with the back face.
   * @returns {Number} The intersection as a parametric distance along the ray, or undefined if there is no intersection.
   */
  IntersectionTests.rayTriangleParametric = function (
    ray,
    p0,
    p1,
    p2,
    cullBackFaces
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(ray)) {
      throw new DeveloperError("ray is required.");
    }
    if (!defined(p0)) {
      throw new DeveloperError("p0 is required.");
    }
    if (!defined(p1)) {
      throw new DeveloperError("p1 is required.");
    }
    if (!defined(p2)) {
      throw new DeveloperError("p2 is required.");
    }
    //>>includeEnd('debug');

    cullBackFaces = defaultValue(cullBackFaces, false);

    const origin = ray.origin;
    const direction = ray.direction;

    const edge0 = Cartesian3.subtract(p1, p0, scratchEdge0);
    const edge1 = Cartesian3.subtract(p2, p0, scratchEdge1);

    const p = Cartesian3.cross(direction, edge1, scratchPVec);
    const det = Cartesian3.dot(edge0, p);

    let tvec;
    let q;

    let u;
    let v;
    let t;

    if (cullBackFaces) {
      if (det < CesiumMath.EPSILON6) {
        return undefined;
      }

      tvec = Cartesian3.subtract(origin, p0, scratchTVec);
      u = Cartesian3.dot(tvec, p);
      if (u < 0.0 || u > det) {
        return undefined;
      }

      q = Cartesian3.cross(tvec, edge0, scratchQVec);

      v = Cartesian3.dot(direction, q);
      if (v < 0.0 || u + v > det) {
        return undefined;
      }

      t = Cartesian3.dot(edge1, q) / det;
    } else {
      if (Math.abs(det) < CesiumMath.EPSILON6) {
        return undefined;
      }
      const invDet = 1.0 / det;

      tvec = Cartesian3.subtract(origin, p0, scratchTVec);
      u = Cartesian3.dot(tvec, p) * invDet;
      if (u < 0.0 || u > 1.0) {
        return undefined;
      }

      q = Cartesian3.cross(tvec, edge0, scratchQVec);

      v = Cartesian3.dot(direction, q) * invDet;
      if (v < 0.0 || u + v > 1.0) {
        return undefined;
      }

      t = Cartesian3.dot(edge1, q) * invDet;
    }

    return t;
  };

  /**
   * Computes the intersection of a ray and a triangle as a Cartesian3 coordinate.
   *
   * Implements {@link https://cadxfem.org/inf/Fast%20MinimumStorage%20RayTriangle%20Intersection.pdf|
   * Fast Minimum Storage Ray/Triangle Intersection} by Tomas Moller and Ben Trumbore.
   *
   * @memberof IntersectionTests
   *
   * @param {Ray} ray The ray.
   * @param {Cartesian3} p0 The first vertex of the triangle.
   * @param {Cartesian3} p1 The second vertex of the triangle.
   * @param {Cartesian3} p2 The third vertex of the triangle.
   * @param {Boolean} [cullBackFaces=false] If <code>true</code>, will only compute an intersection with the front face of the triangle
   *                  and return undefined for intersections with the back face.
   * @param {Cartesian3} [result] The <code>Cartesian3</code> onto which to store the result.
   * @returns {Cartesian3} The intersection point or undefined if there is no intersections.
   */
  IntersectionTests.rayTriangle = function (
    ray,
    p0,
    p1,
    p2,
    cullBackFaces,
    result
  ) {
    const t = IntersectionTests.rayTriangleParametric(
      ray,
      p0,
      p1,
      p2,
      cullBackFaces
    );
    if (!defined(t) || t < 0.0) {
      return undefined;
    }

    if (!defined(result)) {
      result = new Cartesian3();
    }

    Cartesian3.multiplyByScalar(ray.direction, t, result);
    return Cartesian3.add(ray.origin, result, result);
  };

  const scratchLineSegmentTriangleRay = new Ray();

  /**
   * Computes the intersection of a line segment and a triangle.
   * @memberof IntersectionTests
   *
   * @param {Cartesian3} v0 The an end point of the line segment.
   * @param {Cartesian3} v1 The other end point of the line segment.
   * @param {Cartesian3} p0 The first vertex of the triangle.
   * @param {Cartesian3} p1 The second vertex of the triangle.
   * @param {Cartesian3} p2 The third vertex of the triangle.
   * @param {Boolean} [cullBackFaces=false] If <code>true</code>, will only compute an intersection with the front face of the triangle
   *                  and return undefined for intersections with the back face.
   * @param {Cartesian3} [result] The <code>Cartesian3</code> onto which to store the result.
   * @returns {Cartesian3} The intersection point or undefined if there is no intersections.
   */
  IntersectionTests.lineSegmentTriangle = function (
    v0,
    v1,
    p0,
    p1,
    p2,
    cullBackFaces,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(v0)) {
      throw new DeveloperError("v0 is required.");
    }
    if (!defined(v1)) {
      throw new DeveloperError("v1 is required.");
    }
    if (!defined(p0)) {
      throw new DeveloperError("p0 is required.");
    }
    if (!defined(p1)) {
      throw new DeveloperError("p1 is required.");
    }
    if (!defined(p2)) {
      throw new DeveloperError("p2 is required.");
    }
    //>>includeEnd('debug');

    const ray = scratchLineSegmentTriangleRay;
    Cartesian3.clone(v0, ray.origin);
    Cartesian3.subtract(v1, v0, ray.direction);
    Cartesian3.normalize(ray.direction, ray.direction);

    const t = IntersectionTests.rayTriangleParametric(
      ray,
      p0,
      p1,
      p2,
      cullBackFaces
    );
    if (!defined(t) || t < 0.0 || t > Cartesian3.distance(v0, v1)) {
      return undefined;
    }

    if (!defined(result)) {
      result = new Cartesian3();
    }

    Cartesian3.multiplyByScalar(ray.direction, t, result);
    return Cartesian3.add(ray.origin, result, result);
  };

  function solveQuadratic(a, b, c, result) {
    const det = b * b - 4.0 * a * c;
    if (det < 0.0) {
      return undefined;
    } else if (det > 0.0) {
      const denom = 1.0 / (2.0 * a);
      const disc = Math.sqrt(det);
      const root0 = (-b + disc) * denom;
      const root1 = (-b - disc) * denom;

      if (root0 < root1) {
        result.root0 = root0;
        result.root1 = root1;
      } else {
        result.root0 = root1;
        result.root1 = root0;
      }

      return result;
    }

    const root = -b / (2.0 * a);
    if (root === 0.0) {
      return undefined;
    }

    result.root0 = result.root1 = root;
    return result;
  }

  const raySphereRoots = {
    root0: 0.0,
    root1: 0.0,
  };

  function raySphere(ray, sphere, result) {
    if (!defined(result)) {
      result = new Interval();
    }

    const origin = ray.origin;
    const direction = ray.direction;

    const center = sphere.center;
    const radiusSquared = sphere.radius * sphere.radius;

    const diff = Cartesian3.subtract(origin, center, scratchPVec);

    const a = Cartesian3.dot(direction, direction);
    const b = 2.0 * Cartesian3.dot(direction, diff);
    const c = Cartesian3.magnitudeSquared(diff) - radiusSquared;

    const roots = solveQuadratic(a, b, c, raySphereRoots);
    if (!defined(roots)) {
      return undefined;
    }

    result.start = roots.root0;
    result.stop = roots.root1;
    return result;
  }

  /**
   * Computes the intersection points of a ray with a sphere.
   * @memberof IntersectionTests
   *
   * @param {Ray} ray The ray.
   * @param {BoundingSphere} sphere The sphere.
   * @param {Interval} [result] The result onto which to store the result.
   * @returns {Interval} The interval containing scalar points along the ray or undefined if there are no intersections.
   */
  IntersectionTests.raySphere = function (ray, sphere, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(ray)) {
      throw new DeveloperError("ray is required.");
    }
    if (!defined(sphere)) {
      throw new DeveloperError("sphere is required.");
    }
    //>>includeEnd('debug');

    result = raySphere(ray, sphere, result);
    if (!defined(result) || result.stop < 0.0) {
      return undefined;
    }

    result.start = Math.max(result.start, 0.0);
    return result;
  };

  const scratchLineSegmentRay = new Ray();

  /**
   * Computes the intersection points of a line segment with a sphere.
   * @memberof IntersectionTests
   *
   * @param {Cartesian3} p0 An end point of the line segment.
   * @param {Cartesian3} p1 The other end point of the line segment.
   * @param {BoundingSphere} sphere The sphere.
   * @param {Interval} [result] The result onto which to store the result.
   * @returns {Interval} The interval containing scalar points along the ray or undefined if there are no intersections.
   */
  IntersectionTests.lineSegmentSphere = function (p0, p1, sphere, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(p0)) {
      throw new DeveloperError("p0 is required.");
    }
    if (!defined(p1)) {
      throw new DeveloperError("p1 is required.");
    }
    if (!defined(sphere)) {
      throw new DeveloperError("sphere is required.");
    }
    //>>includeEnd('debug');

    const ray = scratchLineSegmentRay;
    Cartesian3.clone(p0, ray.origin);
    const direction = Cartesian3.subtract(p1, p0, ray.direction);

    const maxT = Cartesian3.magnitude(direction);
    Cartesian3.normalize(direction, direction);

    result = raySphere(ray, sphere, result);
    if (!defined(result) || result.stop < 0.0 || result.start > maxT) {
      return undefined;
    }

    result.start = Math.max(result.start, 0.0);
    result.stop = Math.min(result.stop, maxT);
    return result;
  };

  const scratchQ = new Cartesian3();
  const scratchW$1 = new Cartesian3();

  /**
   * Computes the intersection points of a ray with an ellipsoid.
   *
   * @param {Ray} ray The ray.
   * @param {Ellipsoid} ellipsoid The ellipsoid.
   * @returns {Interval} The interval containing scalar points along the ray or undefined if there are no intersections.
   */
  IntersectionTests.rayEllipsoid = function (ray, ellipsoid) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(ray)) {
      throw new DeveloperError("ray is required.");
    }
    if (!defined(ellipsoid)) {
      throw new DeveloperError("ellipsoid is required.");
    }
    //>>includeEnd('debug');

    const inverseRadii = ellipsoid.oneOverRadii;
    const q = Cartesian3.multiplyComponents(inverseRadii, ray.origin, scratchQ);
    const w = Cartesian3.multiplyComponents(
      inverseRadii,
      ray.direction,
      scratchW$1
    );

    const q2 = Cartesian3.magnitudeSquared(q);
    const qw = Cartesian3.dot(q, w);

    let difference, w2, product, discriminant, temp;

    if (q2 > 1.0) {
      // Outside ellipsoid.
      if (qw >= 0.0) {
        // Looking outward or tangent (0 intersections).
        return undefined;
      }

      // qw < 0.0.
      const qw2 = qw * qw;
      difference = q2 - 1.0; // Positively valued.
      w2 = Cartesian3.magnitudeSquared(w);
      product = w2 * difference;

      if (qw2 < product) {
        // Imaginary roots (0 intersections).
        return undefined;
      } else if (qw2 > product) {
        // Distinct roots (2 intersections).
        discriminant = qw * qw - product;
        temp = -qw + Math.sqrt(discriminant); // Avoid cancellation.
        const root0 = temp / w2;
        const root1 = difference / temp;
        if (root0 < root1) {
          return new Interval(root0, root1);
        }

        return {
          start: root1,
          stop: root0,
        };
      }
      // qw2 == product.  Repeated roots (2 intersections).
      const root = Math.sqrt(difference / w2);
      return new Interval(root, root);
    } else if (q2 < 1.0) {
      // Inside ellipsoid (2 intersections).
      difference = q2 - 1.0; // Negatively valued.
      w2 = Cartesian3.magnitudeSquared(w);
      product = w2 * difference; // Negatively valued.

      discriminant = qw * qw - product;
      temp = -qw + Math.sqrt(discriminant); // Positively valued.
      return new Interval(0.0, temp / w2);
    }
    // q2 == 1.0. On ellipsoid.
    if (qw < 0.0) {
      // Looking inward.
      w2 = Cartesian3.magnitudeSquared(w);
      return new Interval(0.0, -qw / w2);
    }

    // qw >= 0.0.  Looking outward or tangent.
    return undefined;
  };

  function addWithCancellationCheck(left, right, tolerance) {
    const difference = left + right;
    if (
      CesiumMath.sign(left) !== CesiumMath.sign(right) &&
      Math.abs(difference / Math.max(Math.abs(left), Math.abs(right))) < tolerance
    ) {
      return 0.0;
    }

    return difference;
  }

  function quadraticVectorExpression(A, b, c, x, w) {
    const xSquared = x * x;
    const wSquared = w * w;

    const l2 = (A[Matrix3.COLUMN1ROW1] - A[Matrix3.COLUMN2ROW2]) * wSquared;
    const l1 =
      w *
      (x *
        addWithCancellationCheck(
          A[Matrix3.COLUMN1ROW0],
          A[Matrix3.COLUMN0ROW1],
          CesiumMath.EPSILON15
        ) +
        b.y);
    const l0 =
      A[Matrix3.COLUMN0ROW0] * xSquared +
      A[Matrix3.COLUMN2ROW2] * wSquared +
      x * b.x +
      c;

    const r1 =
      wSquared *
      addWithCancellationCheck(
        A[Matrix3.COLUMN2ROW1],
        A[Matrix3.COLUMN1ROW2],
        CesiumMath.EPSILON15
      );
    const r0 =
      w *
      (x *
        addWithCancellationCheck(A[Matrix3.COLUMN2ROW0], A[Matrix3.COLUMN0ROW2]) +
        b.z);

    let cosines;
    const solutions = [];
    if (r0 === 0.0 && r1 === 0.0) {
      cosines = QuadraticRealPolynomial.computeRealRoots(l2, l1, l0);
      if (cosines.length === 0) {
        return solutions;
      }

      const cosine0 = cosines[0];
      const sine0 = Math.sqrt(Math.max(1.0 - cosine0 * cosine0, 0.0));
      solutions.push(new Cartesian3(x, w * cosine0, w * -sine0));
      solutions.push(new Cartesian3(x, w * cosine0, w * sine0));

      if (cosines.length === 2) {
        const cosine1 = cosines[1];
        const sine1 = Math.sqrt(Math.max(1.0 - cosine1 * cosine1, 0.0));
        solutions.push(new Cartesian3(x, w * cosine1, w * -sine1));
        solutions.push(new Cartesian3(x, w * cosine1, w * sine1));
      }

      return solutions;
    }

    const r0Squared = r0 * r0;
    const r1Squared = r1 * r1;
    const l2Squared = l2 * l2;
    const r0r1 = r0 * r1;

    const c4 = l2Squared + r1Squared;
    const c3 = 2.0 * (l1 * l2 + r0r1);
    const c2 = 2.0 * l0 * l2 + l1 * l1 - r1Squared + r0Squared;
    const c1 = 2.0 * (l0 * l1 - r0r1);
    const c0 = l0 * l0 - r0Squared;

    if (c4 === 0.0 && c3 === 0.0 && c2 === 0.0 && c1 === 0.0) {
      return solutions;
    }

    cosines = QuarticRealPolynomial.computeRealRoots(c4, c3, c2, c1, c0);
    const length = cosines.length;
    if (length === 0) {
      return solutions;
    }

    for (let i = 0; i < length; ++i) {
      const cosine = cosines[i];
      const cosineSquared = cosine * cosine;
      const sineSquared = Math.max(1.0 - cosineSquared, 0.0);
      const sine = Math.sqrt(sineSquared);

      //const left = l2 * cosineSquared + l1 * cosine + l0;
      let left;
      if (CesiumMath.sign(l2) === CesiumMath.sign(l0)) {
        left = addWithCancellationCheck(
          l2 * cosineSquared + l0,
          l1 * cosine,
          CesiumMath.EPSILON12
        );
      } else if (CesiumMath.sign(l0) === CesiumMath.sign(l1 * cosine)) {
        left = addWithCancellationCheck(
          l2 * cosineSquared,
          l1 * cosine + l0,
          CesiumMath.EPSILON12
        );
      } else {
        left = addWithCancellationCheck(
          l2 * cosineSquared + l1 * cosine,
          l0,
          CesiumMath.EPSILON12
        );
      }

      const right = addWithCancellationCheck(
        r1 * cosine,
        r0,
        CesiumMath.EPSILON15
      );
      const product = left * right;

      if (product < 0.0) {
        solutions.push(new Cartesian3(x, w * cosine, w * sine));
      } else if (product > 0.0) {
        solutions.push(new Cartesian3(x, w * cosine, w * -sine));
      } else if (sine !== 0.0) {
        solutions.push(new Cartesian3(x, w * cosine, w * -sine));
        solutions.push(new Cartesian3(x, w * cosine, w * sine));
        ++i;
      } else {
        solutions.push(new Cartesian3(x, w * cosine, w * sine));
      }
    }

    return solutions;
  }

  const firstAxisScratch = new Cartesian3();
  const secondAxisScratch = new Cartesian3();
  const thirdAxisScratch = new Cartesian3();
  const referenceScratch = new Cartesian3();
  const bCart = new Cartesian3();
  const bScratch = new Matrix3();
  const btScratch = new Matrix3();
  const diScratch = new Matrix3();
  const dScratch$1 = new Matrix3();
  const cScratch = new Matrix3();
  const tempMatrix = new Matrix3();
  const aScratch = new Matrix3();
  const sScratch$1 = new Cartesian3();
  const closestScratch = new Cartesian3();
  const surfPointScratch = new Cartographic();

  /**
   * Provides the point along the ray which is nearest to the ellipsoid.
   *
   * @param {Ray} ray The ray.
   * @param {Ellipsoid} ellipsoid The ellipsoid.
   * @returns {Cartesian3} The nearest planetodetic point on the ray.
   */
  IntersectionTests.grazingAltitudeLocation = function (ray, ellipsoid) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(ray)) {
      throw new DeveloperError("ray is required.");
    }
    if (!defined(ellipsoid)) {
      throw new DeveloperError("ellipsoid is required.");
    }
    //>>includeEnd('debug');

    const position = ray.origin;
    const direction = ray.direction;

    if (!Cartesian3.equals(position, Cartesian3.ZERO)) {
      const normal = ellipsoid.geodeticSurfaceNormal(position, firstAxisScratch);
      if (Cartesian3.dot(direction, normal) >= 0.0) {
        // The location provided is the closest point in altitude
        return position;
      }
    }

    const intersects = defined(this.rayEllipsoid(ray, ellipsoid));

    // Compute the scaled direction vector.
    const f = ellipsoid.transformPositionToScaledSpace(
      direction,
      firstAxisScratch
    );

    // Constructs a basis from the unit scaled direction vector. Construct its rotation and transpose.
    const firstAxis = Cartesian3.normalize(f, f);
    const reference = Cartesian3.mostOrthogonalAxis(f, referenceScratch);
    const secondAxis = Cartesian3.normalize(
      Cartesian3.cross(reference, firstAxis, secondAxisScratch),
      secondAxisScratch
    );
    const thirdAxis = Cartesian3.normalize(
      Cartesian3.cross(firstAxis, secondAxis, thirdAxisScratch),
      thirdAxisScratch
    );
    const B = bScratch;
    B[0] = firstAxis.x;
    B[1] = firstAxis.y;
    B[2] = firstAxis.z;
    B[3] = secondAxis.x;
    B[4] = secondAxis.y;
    B[5] = secondAxis.z;
    B[6] = thirdAxis.x;
    B[7] = thirdAxis.y;
    B[8] = thirdAxis.z;

    const B_T = Matrix3.transpose(B, btScratch);

    // Get the scaling matrix and its inverse.
    const D_I = Matrix3.fromScale(ellipsoid.radii, diScratch);
    const D = Matrix3.fromScale(ellipsoid.oneOverRadii, dScratch$1);

    const C = cScratch;
    C[0] = 0.0;
    C[1] = -direction.z;
    C[2] = direction.y;
    C[3] = direction.z;
    C[4] = 0.0;
    C[5] = -direction.x;
    C[6] = -direction.y;
    C[7] = direction.x;
    C[8] = 0.0;

    const temp = Matrix3.multiply(
      Matrix3.multiply(B_T, D, tempMatrix),
      C,
      tempMatrix
    );
    const A = Matrix3.multiply(
      Matrix3.multiply(temp, D_I, aScratch),
      B,
      aScratch
    );
    const b = Matrix3.multiplyByVector(temp, position, bCart);

    // Solve for the solutions to the expression in standard form:
    const solutions = quadraticVectorExpression(
      A,
      Cartesian3.negate(b, firstAxisScratch),
      0.0,
      0.0,
      1.0
    );

    let s;
    let altitude;
    const length = solutions.length;
    if (length > 0) {
      let closest = Cartesian3.clone(Cartesian3.ZERO, closestScratch);
      let maximumValue = Number.NEGATIVE_INFINITY;

      for (let i = 0; i < length; ++i) {
        s = Matrix3.multiplyByVector(
          D_I,
          Matrix3.multiplyByVector(B, solutions[i], sScratch$1),
          sScratch$1
        );
        const v = Cartesian3.normalize(
          Cartesian3.subtract(s, position, referenceScratch),
          referenceScratch
        );
        const dotProduct = Cartesian3.dot(v, direction);

        if (dotProduct > maximumValue) {
          maximumValue = dotProduct;
          closest = Cartesian3.clone(s, closest);
        }
      }

      const surfacePoint = ellipsoid.cartesianToCartographic(
        closest,
        surfPointScratch
      );
      maximumValue = CesiumMath.clamp(maximumValue, 0.0, 1.0);
      altitude =
        Cartesian3.magnitude(
          Cartesian3.subtract(closest, position, referenceScratch)
        ) * Math.sqrt(1.0 - maximumValue * maximumValue);
      altitude = intersects ? -altitude : altitude;
      surfacePoint.height = altitude;
      return ellipsoid.cartographicToCartesian(surfacePoint, new Cartesian3());
    }

    return undefined;
  };

  const lineSegmentPlaneDifference = new Cartesian3();

  /**
   * Computes the intersection of a line segment and a plane.
   *
   * @param {Cartesian3} endPoint0 An end point of the line segment.
   * @param {Cartesian3} endPoint1 The other end point of the line segment.
   * @param {Plane} plane The plane.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} The intersection point or undefined if there is no intersection.
   *
   * @example
   * const origin = Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883);
   * const normal = ellipsoid.geodeticSurfaceNormal(origin);
   * const plane = Cesium.Plane.fromPointNormal(origin, normal);
   *
   * const p0 = new Cesium.Cartesian3(...);
   * const p1 = new Cesium.Cartesian3(...);
   *
   * // find the intersection of the line segment from p0 to p1 and the tangent plane at origin.
   * const intersection = Cesium.IntersectionTests.lineSegmentPlane(p0, p1, plane);
   */
  IntersectionTests.lineSegmentPlane = function (
    endPoint0,
    endPoint1,
    plane,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(endPoint0)) {
      throw new DeveloperError("endPoint0 is required.");
    }
    if (!defined(endPoint1)) {
      throw new DeveloperError("endPoint1 is required.");
    }
    if (!defined(plane)) {
      throw new DeveloperError("plane is required.");
    }
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Cartesian3();
    }

    const difference = Cartesian3.subtract(
      endPoint1,
      endPoint0,
      lineSegmentPlaneDifference
    );
    const normal = plane.normal;
    const nDotDiff = Cartesian3.dot(normal, difference);

    // check if the segment and plane are parallel
    if (Math.abs(nDotDiff) < CesiumMath.EPSILON6) {
      return undefined;
    }

    const nDotP0 = Cartesian3.dot(normal, endPoint0);
    const t = -(plane.distance + nDotP0) / nDotDiff;

    // intersection only if t is in [0, 1]
    if (t < 0.0 || t > 1.0) {
      return undefined;
    }

    // intersection is endPoint0 + t * (endPoint1 - endPoint0)
    Cartesian3.multiplyByScalar(difference, t, result);
    Cartesian3.add(endPoint0, result, result);
    return result;
  };

  /**
   * Computes the intersection of a triangle and a plane
   *
   * @param {Cartesian3} p0 First point of the triangle
   * @param {Cartesian3} p1 Second point of the triangle
   * @param {Cartesian3} p2 Third point of the triangle
   * @param {Plane} plane Intersection plane
   * @returns {Object} An object with properties <code>positions</code> and <code>indices</code>, which are arrays that represent three triangles that do not cross the plane. (Undefined if no intersection exists)
   *
   * @example
   * const origin = Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883);
   * const normal = ellipsoid.geodeticSurfaceNormal(origin);
   * const plane = Cesium.Plane.fromPointNormal(origin, normal);
   *
   * const p0 = new Cesium.Cartesian3(...);
   * const p1 = new Cesium.Cartesian3(...);
   * const p2 = new Cesium.Cartesian3(...);
   *
   * // convert the triangle composed of points (p0, p1, p2) to three triangles that don't cross the plane
   * const triangles = Cesium.IntersectionTests.trianglePlaneIntersection(p0, p1, p2, plane);
   */
  IntersectionTests.trianglePlaneIntersection = function (p0, p1, p2, plane) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(p0) || !defined(p1) || !defined(p2) || !defined(plane)) {
      throw new DeveloperError("p0, p1, p2, and plane are required.");
    }
    //>>includeEnd('debug');

    const planeNormal = plane.normal;
    const planeD = plane.distance;
    const p0Behind = Cartesian3.dot(planeNormal, p0) + planeD < 0.0;
    const p1Behind = Cartesian3.dot(planeNormal, p1) + planeD < 0.0;
    const p2Behind = Cartesian3.dot(planeNormal, p2) + planeD < 0.0;
    // Given these dots products, the calls to lineSegmentPlaneIntersection
    // always have defined results.

    let numBehind = 0;
    numBehind += p0Behind ? 1 : 0;
    numBehind += p1Behind ? 1 : 0;
    numBehind += p2Behind ? 1 : 0;

    let u1, u2;
    if (numBehind === 1 || numBehind === 2) {
      u1 = new Cartesian3();
      u2 = new Cartesian3();
    }

    if (numBehind === 1) {
      if (p0Behind) {
        IntersectionTests.lineSegmentPlane(p0, p1, plane, u1);
        IntersectionTests.lineSegmentPlane(p0, p2, plane, u2);

        return {
          positions: [p0, p1, p2, u1, u2],
          indices: [
            // Behind
            0,
            3,
            4,

            // In front
            1,
            2,
            4,
            1,
            4,
            3,
          ],
        };
      } else if (p1Behind) {
        IntersectionTests.lineSegmentPlane(p1, p2, plane, u1);
        IntersectionTests.lineSegmentPlane(p1, p0, plane, u2);

        return {
          positions: [p0, p1, p2, u1, u2],
          indices: [
            // Behind
            1,
            3,
            4,

            // In front
            2,
            0,
            4,
            2,
            4,
            3,
          ],
        };
      } else if (p2Behind) {
        IntersectionTests.lineSegmentPlane(p2, p0, plane, u1);
        IntersectionTests.lineSegmentPlane(p2, p1, plane, u2);

        return {
          positions: [p0, p1, p2, u1, u2],
          indices: [
            // Behind
            2,
            3,
            4,

            // In front
            0,
            1,
            4,
            0,
            4,
            3,
          ],
        };
      }
    } else if (numBehind === 2) {
      if (!p0Behind) {
        IntersectionTests.lineSegmentPlane(p1, p0, plane, u1);
        IntersectionTests.lineSegmentPlane(p2, p0, plane, u2);

        return {
          positions: [p0, p1, p2, u1, u2],
          indices: [
            // Behind
            1,
            2,
            4,
            1,
            4,
            3,

            // In front
            0,
            3,
            4,
          ],
        };
      } else if (!p1Behind) {
        IntersectionTests.lineSegmentPlane(p2, p1, plane, u1);
        IntersectionTests.lineSegmentPlane(p0, p1, plane, u2);

        return {
          positions: [p0, p1, p2, u1, u2],
          indices: [
            // Behind
            2,
            0,
            4,
            2,
            4,
            3,

            // In front
            1,
            3,
            4,
          ],
        };
      } else if (!p2Behind) {
        IntersectionTests.lineSegmentPlane(p0, p2, plane, u1);
        IntersectionTests.lineSegmentPlane(p1, p2, plane, u2);

        return {
          positions: [p0, p1, p2, u1, u2],
          indices: [
            // Behind
            0,
            1,
            4,
            0,
            4,
            3,

            // In front
            2,
            3,
            4,
          ],
        };
      }
    }

    // if numBehind is 3, the triangle is completely behind the plane;
    // otherwise, it is completely in front (numBehind is 0).
    return undefined;
  };

  /**
   * A plane in Hessian Normal Form defined by
   * <pre>
   * ax + by + cz + d = 0
   * </pre>
   * where (a, b, c) is the plane's <code>normal</code>, d is the signed
   * <code>distance</code> to the plane, and (x, y, z) is any point on
   * the plane.
   *
   * @alias Plane
   * @constructor
   *
   * @param {Cartesian3} normal The plane's normal (normalized).
   * @param {Number} distance The shortest distance from the origin to the plane.  The sign of
   * <code>distance</code> determines which side of the plane the origin
   * is on.  If <code>distance</code> is positive, the origin is in the half-space
   * in the direction of the normal; if negative, the origin is in the half-space
   * opposite to the normal; if zero, the plane passes through the origin.
   *
   * @example
   * // The plane x=0
   * const plane = new Cesium.Plane(Cesium.Cartesian3.UNIT_X, 0.0);
   *
   * @exception {DeveloperError} Normal must be normalized
   */
  function Plane(normal, distance) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("normal", normal);
    if (
      !CesiumMath.equalsEpsilon(
        Cartesian3.magnitude(normal),
        1.0,
        CesiumMath.EPSILON6
      )
    ) {
      throw new DeveloperError("normal must be normalized.");
    }
    Check.typeOf.number("distance", distance);
    //>>includeEnd('debug');

    /**
     * The plane's normal.
     *
     * @type {Cartesian3}
     */
    this.normal = Cartesian3.clone(normal);

    /**
     * The shortest distance from the origin to the plane.  The sign of
     * <code>distance</code> determines which side of the plane the origin
     * is on.  If <code>distance</code> is positive, the origin is in the half-space
     * in the direction of the normal; if negative, the origin is in the half-space
     * opposite to the normal; if zero, the plane passes through the origin.
     *
     * @type {Number}
     */
    this.distance = distance;
  }

  /**
   * Creates a plane from a normal and a point on the plane.
   *
   * @param {Cartesian3} point The point on the plane.
   * @param {Cartesian3} normal The plane's normal (normalized).
   * @param {Plane} [result] The object onto which to store the result.
   * @returns {Plane} A new plane instance or the modified result parameter.
   *
   * @example
   * const point = Cesium.Cartesian3.fromDegrees(-72.0, 40.0);
   * const normal = ellipsoid.geodeticSurfaceNormal(point);
   * const tangentPlane = Cesium.Plane.fromPointNormal(point, normal);
   *
   * @exception {DeveloperError} Normal must be normalized
   */
  Plane.fromPointNormal = function (point, normal, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("point", point);
    Check.typeOf.object("normal", normal);
    if (
      !CesiumMath.equalsEpsilon(
        Cartesian3.magnitude(normal),
        1.0,
        CesiumMath.EPSILON6
      )
    ) {
      throw new DeveloperError("normal must be normalized.");
    }
    //>>includeEnd('debug');

    const distance = -Cartesian3.dot(normal, point);

    if (!defined(result)) {
      return new Plane(normal, distance);
    }

    Cartesian3.clone(normal, result.normal);
    result.distance = distance;
    return result;
  };

  const scratchNormal$7 = new Cartesian3();
  /**
   * Creates a plane from the general equation
   *
   * @param {Cartesian4} coefficients The plane's normal (normalized).
   * @param {Plane} [result] The object onto which to store the result.
   * @returns {Plane} A new plane instance or the modified result parameter.
   *
   * @exception {DeveloperError} Normal must be normalized
   */
  Plane.fromCartesian4 = function (coefficients, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("coefficients", coefficients);
    //>>includeEnd('debug');

    const normal = Cartesian3.fromCartesian4(coefficients, scratchNormal$7);
    const distance = coefficients.w;

    //>>includeStart('debug', pragmas.debug);
    if (
      !CesiumMath.equalsEpsilon(
        Cartesian3.magnitude(normal),
        1.0,
        CesiumMath.EPSILON6
      )
    ) {
      throw new DeveloperError("normal must be normalized.");
    }
    //>>includeEnd('debug');

    if (!defined(result)) {
      return new Plane(normal, distance);
    }
    Cartesian3.clone(normal, result.normal);
    result.distance = distance;
    return result;
  };

  /**
   * Computes the signed shortest distance of a point to a plane.
   * The sign of the distance determines which side of the plane the point
   * is on.  If the distance is positive, the point is in the half-space
   * in the direction of the normal; if negative, the point is in the half-space
   * opposite to the normal; if zero, the plane passes through the point.
   *
   * @param {Plane} plane The plane.
   * @param {Cartesian3} point The point.
   * @returns {Number} The signed shortest distance of the point to the plane.
   */
  Plane.getPointDistance = function (plane, point) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("plane", plane);
    Check.typeOf.object("point", point);
    //>>includeEnd('debug');

    return Cartesian3.dot(plane.normal, point) + plane.distance;
  };

  const scratchCartesian$9 = new Cartesian3();
  /**
   * Projects a point onto the plane.
   * @param {Plane} plane The plane to project the point onto
   * @param {Cartesian3} point The point to project onto the plane
   * @param {Cartesian3} [result] The result point.  If undefined, a new Cartesian3 will be created.
   * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
   */
  Plane.projectPointOntoPlane = function (plane, point, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("plane", plane);
    Check.typeOf.object("point", point);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Cartesian3();
    }

    // projectedPoint = point - (normal.point + scale) * normal
    const pointDistance = Plane.getPointDistance(plane, point);
    const scaledNormal = Cartesian3.multiplyByScalar(
      plane.normal,
      pointDistance,
      scratchCartesian$9
    );

    return Cartesian3.subtract(point, scaledNormal, result);
  };

  const scratchInverseTranspose = new Matrix4();
  const scratchPlaneCartesian4 = new Cartesian4();
  const scratchTransformNormal = new Cartesian3();
  /**
   * Transforms the plane by the given transformation matrix.
   *
   * @param {Plane} plane The plane.
   * @param {Matrix4} transform The transformation matrix.
   * @param {Plane} [result] The object into which to store the result.
   * @returns {Plane} The plane transformed by the given transformation matrix.
   */
  Plane.transform = function (plane, transform, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("plane", plane);
    Check.typeOf.object("transform", transform);
    //>>includeEnd('debug');

    const normal = plane.normal;
    const distance = plane.distance;
    const inverseTranspose = Matrix4.inverseTranspose(
      transform,
      scratchInverseTranspose
    );
    let planeAsCartesian4 = Cartesian4.fromElements(
      normal.x,
      normal.y,
      normal.z,
      distance,
      scratchPlaneCartesian4
    );
    planeAsCartesian4 = Matrix4.multiplyByVector(
      inverseTranspose,
      planeAsCartesian4,
      planeAsCartesian4
    );

    // Convert the transformed plane to Hessian Normal Form
    const transformedNormal = Cartesian3.fromCartesian4(
      planeAsCartesian4,
      scratchTransformNormal
    );

    planeAsCartesian4 = Cartesian4.divideByScalar(
      planeAsCartesian4,
      Cartesian3.magnitude(transformedNormal),
      planeAsCartesian4
    );

    return Plane.fromCartesian4(planeAsCartesian4, result);
  };

  /**
   * Duplicates a Plane instance.
   *
   * @param {Plane} plane The plane to duplicate.
   * @param {Plane} [result] The object onto which to store the result.
   * @returns {Plane} The modified result parameter or a new Plane instance if one was not provided.
   */
  Plane.clone = function (plane, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("plane", plane);
    //>>includeEnd('debug');

    if (!defined(result)) {
      return new Plane(plane.normal, plane.distance);
    }

    Cartesian3.clone(plane.normal, result.normal);
    result.distance = plane.distance;

    return result;
  };

  /**
   * Compares the provided Planes by normal and distance and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Plane} left The first plane.
   * @param {Plane} right The second plane.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  Plane.equals = function (left, right) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    //>>includeEnd('debug');

    return (
      left.distance === right.distance &&
      Cartesian3.equals(left.normal, right.normal)
    );
  };

  /**
   * A constant initialized to the XY plane passing through the origin, with normal in positive Z.
   *
   * @type {Plane}
   * @constant
   */
  Plane.ORIGIN_XY_PLANE = Object.freeze(new Plane(Cartesian3.UNIT_Z, 0.0));

  /**
   * A constant initialized to the YZ plane passing through the origin, with normal in positive X.
   *
   * @type {Plane}
   * @constant
   */
  Plane.ORIGIN_YZ_PLANE = Object.freeze(new Plane(Cartesian3.UNIT_X, 0.0));

  /**
   * A constant initialized to the ZX plane passing through the origin, with normal in positive Y.
   *
   * @type {Plane}
   * @constant
   */
  Plane.ORIGIN_ZX_PLANE = Object.freeze(new Plane(Cartesian3.UNIT_Y, 0.0));

  /**
   * 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 <code>itemToFind</code> in the array, if it exists.  If <code>itemToFind</code>
   *        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);
    Check.defined("array", array);
    Check.defined("itemToFind", itemToFind);
    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 <code>year</code> 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 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: <code>0.001</code>
     * @type {Number}
     * @constant
     */
    SECONDS_PER_MILLISECOND: 0.001,

    /**
     * The number of seconds in one minute: <code>60</code>.
     * @type {Number}
     * @constant
     */
    SECONDS_PER_MINUTE: 60.0,

    /**
     * The number of minutes in one hour: <code>60</code>.
     * @type {Number}
     * @constant
     */
    MINUTES_PER_HOUR: 60.0,

    /**
     * The number of hours in one day: <code>24</code>.
     * @type {Number}
     * @constant
     */
    HOURS_PER_DAY: 24.0,

    /**
     * The number of seconds in one hour: <code>3600</code>.
     * @type {Number}
     * @constant
     */
    SECONDS_PER_HOUR: 3600.0,

    /**
     * The number of minutes in one day: <code>1440</code>.
     * @type {Number}
     * @constant
     */
    MINUTES_PER_DAY: 1440.0,

    /**
     * The number of seconds in one day, ignoring leap seconds: <code>86400</code>.
     * @type {Number}
     * @constant
     */
    SECONDS_PER_DAY: 86400.0,

    /**
     * The number of days in one Julian century: <code>36525</code>.
     * @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
     * <code>UTC = TAI - deltaT</code> where <code>deltaT</code> 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 = defaultValue(julianDayNumber, 0.0);
    secondsOfDay = defaultValue(secondsOfDay, 0.0);
    timeStandard = 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 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 (!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 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 (!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 <code>Date.parse</code> 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 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 (!defined(date)) {
      throw new 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 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 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 &&
                ((!defined(tokens[3]) && dashCount !== 1) ||
                  (defined(tokens[3]) && dashCount !== 2))
              ) {
                throw new 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 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 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 (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 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 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 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 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 (!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 <code>JulianDate.fromDate(new Date());</code>.
   *
   * @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 (!defined(julianDate)) {
      throw new DeveloperError("julianDate is required.");
    }
    //>>includeEnd('debug');

    let isLeapSecond = false;
    let thisUtc = convertTaiToUtc(julianDate, toGregorianDateScratch);
    if (!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 (!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 (!defined(julianDate)) {
      throw new 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 (!defined(julianDate)) {
      throw new 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 (!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 (!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 (!defined(julianDate)) {
      return undefined;
    }
    if (!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 (!defined(left)) {
      throw new DeveloperError("left is required.");
    }
    if (!defined(right)) {
      throw new 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 <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {JulianDate} [left] The first instance.
   * @param {JulianDate} [right] The second instance.
   * @returns {Boolean} <code>true</code> if the dates are equal; otherwise, <code>false</code>.
   */
  JulianDate.equals = function (left, right) {
    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        left.dayNumber === right.dayNumber &&
        left.secondsOfDay === right.secondsOfDay)
    );
  };

  /**
   * Compares two instances and returns <code>true</code> if they are within <code>epsilon</code> seconds of
   * each other.  That is, in order for the dates to be considered equal (and for
   * this function to return <code>true</code>), the absolute value of the difference between them, in
   * seconds, must be less than <code>epsilon</code>.
   *
   * @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} <code>true</code> if the two dates are within <code>epsilon</code> seconds of each other; otherwise <code>false</code>.
   */
  JulianDate.equalsEpsilon = function (left, right, epsilon) {
    epsilon = defaultValue(epsilon, 0);

    return (
      left === right ||
      (defined(left) &&
        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 (!defined(julianDate)) {
      throw new 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 <code>right</code> from <code>left</code>.
   */
  JulianDate.secondsDifference = function (left, right) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(left)) {
      throw new DeveloperError("left is required.");
    }
    if (!defined(right)) {
      throw new 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 <code>right</code> from <code>left</code>.
   */
  JulianDate.daysDifference = function (left, right) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(left)) {
      throw new DeveloperError("left is required.");
    }
    if (!defined(right)) {
      throw new 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 (!defined(julianDate)) {
      throw new DeveloperError("julianDate is required.");
    }
    if (!defined(seconds)) {
      throw new DeveloperError("seconds is required.");
    }
    if (!defined(result)) {
      throw new 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 (!defined(julianDate)) {
      throw new DeveloperError("julianDate is required.");
    }
    if (!defined(minutes)) {
      throw new DeveloperError("minutes is required.");
    }
    if (!defined(result)) {
      throw new 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 (!defined(julianDate)) {
      throw new DeveloperError("julianDate is required.");
    }
    if (!defined(hours)) {
      throw new DeveloperError("hours is required.");
    }
    if (!defined(result)) {
      throw new 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 (!defined(julianDate)) {
      throw new DeveloperError("julianDate is required.");
    }
    if (!defined(days)) {
      throw new DeveloperError("days is required.");
    }
    if (!defined(result)) {
      throw new DeveloperError("result is required.");
    }
    //>>includeEnd('debug');

    const newJulianDayNumber = julianDate.dayNumber + days;
    return setComponents(newJulianDayNumber, julianDate.secondsOfDay, result);
  };

  /**
   * Compares the provided instances and returns <code>true</code> if <code>left</code> is earlier than <code>right</code>, <code>false</code> otherwise.
   *
   * @param {JulianDate} left The first instance.
   * @param {JulianDate} right The second instance.
   * @returns {Boolean} <code>true</code> if <code>left</code> is earlier than <code>right</code>, <code>false</code> otherwise.
   */
  JulianDate.lessThan = function (left, right) {
    return JulianDate.compare(left, right) < 0;
  };

  /**
   * Compares the provided instances and returns <code>true</code> if <code>left</code> is earlier than or equal to <code>right</code>, <code>false</code> otherwise.
   *
   * @param {JulianDate} left The first instance.
   * @param {JulianDate} right The second instance.
   * @returns {Boolean} <code>true</code> if <code>left</code> is earlier than or equal to <code>right</code>, <code>false</code> otherwise.
   */
  JulianDate.lessThanOrEquals = function (left, right) {
    return JulianDate.compare(left, right) <= 0;
  };

  /**
   * Compares the provided instances and returns <code>true</code> if <code>left</code> is later than <code>right</code>, <code>false</code> otherwise.
   *
   * @param {JulianDate} left The first instance.
   * @param {JulianDate} right The second instance.
   * @returns {Boolean} <code>true</code> if <code>left</code> is later than <code>right</code>, <code>false</code> otherwise.
   */
  JulianDate.greaterThan = function (left, right) {
    return JulianDate.compare(left, right) > 0;
  };

  /**
   * Compares the provided instances and returns <code>true</code> if <code>left</code> is later than or equal to <code>right</code>, <code>false</code> otherwise.
   *
   * @param {JulianDate} left The first instance.
   * @param {JulianDate} right The second instance.
   * @returns {Boolean} <code>true</code> if <code>left</code> is later than or equal to <code>right</code>, <code>false</code> 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 <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {JulianDate} [right] The second instance.
   * @returns {Boolean} <code>true</code> if the dates are equal; otherwise, <code>false</code>.
   */
  JulianDate.prototype.equals = function (right) {
    return JulianDate.equals(this, right);
  };

  /**
   * Compares this and the provided instance and returns <code>true</code> if they are within <code>epsilon</code> seconds of
   * each other.  That is, in order for the dates to be considered equal (and for
   * this function to return <code>true</code>), the absolute value of the difference between them, in
   * seconds, must be less than <code>epsilon</code>.
   *
   * @param {JulianDate} [right] The second instance.
   * @param {Number} [epsilon=0] The maximum number of seconds that should separate the two instances.
   * @returns {Boolean} <code>true</code> if the two dates are within <code>epsilon</code> seconds of each other; otherwise <code>false</code>.
   */
  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
  ];

  /**
   * 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 = defaultValue(options, 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 = defaultValue(options.addNewLeapSeconds, true);

    if (defined(options.data)) {
      // Use supplied EOP data.
      onDataReady(this, options.data);
    } else if (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);
        })
        .catch(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 Promise.resolve();
    },
    compute: function (date, result) {
      if (!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 {Promise<void>} The promise.
   */
  EarthOrientationParameters.prototype.getPromiseToLoad = function () {
    return Promise.resolve(this._downloadPromise);
  };

  /**
   * Computes the Earth Orientation Parameters (EOP) for a given date by interpolating.
   * If the EOP data has not yet been download, this method returns undefined.
   *
   * @param {JulianDate} date The date for each to evaluate the EOP.
   * @param {EarthOrientationParametersSample} [result] The instance to which to copy the result.
   *        If this parameter is undefined, a new instance is created and returned.
   * @returns {EarthOrientationParametersSample} The EOP evaluated at the given date, or
   *          undefined if the data necessary to evaluate EOP at the date has not yet been
   *          downloaded.
   *
   * @exception {RuntimeError} The loaded EOP data has an error and cannot be used.
   *
   * @see EarthOrientationParameters#getPromiseToLoad
   */
  EarthOrientationParameters.prototype.compute = function (date, result) {
    // We cannot compute until the samples are available.
    if (!defined(this._samples)) {
      if (defined(this._dataError)) {
        throw new RuntimeError(this._dataError);
      }

      return undefined;
    }

    if (!defined(result)) {
      result = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0);
    }

    if (this._samples.length === 0) {
      result.xPoleWander = 0.0;
      result.yPoleWander = 0.0;
      result.xPoleOffset = 0.0;
      result.yPoleOffset = 0.0;
      result.ut1MinusUtc = 0.0;
      return result;
    }

    const dates = this._dates;
    const lastIndex = this._lastIndex;

    let before = 0;
    let after = 0;
    if (defined(lastIndex)) {
      const previousIndexDate = dates[lastIndex];
      const nextIndexDate = dates[lastIndex + 1];
      const isAfterPrevious = JulianDate.lessThanOrEquals(
        previousIndexDate,
        date
      );
      const isAfterLastSample = !defined(nextIndexDate);
      const isBeforeNext =
        isAfterLastSample || JulianDate.greaterThanOrEquals(nextIndexDate, date);

      if (isAfterPrevious && isBeforeNext) {
        before = lastIndex;

        if (!isAfterLastSample && nextIndexDate.equals(date)) {
          ++before;
        }
        after = before + 1;

        interpolate(this, dates, this._samples, date, before, after, result);
        return result;
      }
    }

    let index = binarySearch(dates, date, JulianDate.compare, this._dateColumn);
    if (index >= 0) {
      // If the next entry is the same date, use the later entry.  This way, if two entries
      // describe the same moment, one before a leap second and the other after, then we will use
      // the post-leap second data.
      if (index < dates.length - 1 && dates[index + 1].equals(date)) {
        ++index;
      }
      before = index;
      after = index;
    } else {
      after = ~index;
      before = after - 1;

      // Use the first entry if the date requested is before the beginning of the data.
      if (before < 0) {
        before = 0;
      }
    }

    this._lastIndex = before;

    interpolate(this, dates, this._samples, date, before, after, result);
    return result;
  };

  function compareLeapSecondDates(leapSecond, dateToFind) {
    return JulianDate.compare(leapSecond.julianDate, dateToFind);
  }

  function onDataReady(eop, eopData) {
    if (!defined(eopData.columnNames)) {
      eop._dataError =
        "Error in loaded EOP data: The columnNames property is required.";
      return;
    }

    if (!defined(eopData.samples)) {
      eop._dataError =
        "Error in loaded EOP data: The samples property is required.";
      return;
    }

    const dateColumn = eopData.columnNames.indexOf("modifiedJulianDateUtc");
    const xPoleWanderRadiansColumn = eopData.columnNames.indexOf(
      "xPoleWanderRadians"
    );
    const yPoleWanderRadiansColumn = eopData.columnNames.indexOf(
      "yPoleWanderRadians"
    );
    const ut1MinusUtcSecondsColumn = eopData.columnNames.indexOf(
      "ut1MinusUtcSeconds"
    );
    const xCelestialPoleOffsetRadiansColumn = eopData.columnNames.indexOf(
      "xCelestialPoleOffsetRadians"
    );
    const yCelestialPoleOffsetRadiansColumn = eopData.columnNames.indexOf(
      "yCelestialPoleOffsetRadians"
    );
    const taiMinusUtcSecondsColumn = eopData.columnNames.indexOf(
      "taiMinusUtcSeconds"
    );

    if (
      dateColumn < 0 ||
      xPoleWanderRadiansColumn < 0 ||
      yPoleWanderRadiansColumn < 0 ||
      ut1MinusUtcSecondsColumn < 0 ||
      xCelestialPoleOffsetRadiansColumn < 0 ||
      yCelestialPoleOffsetRadiansColumn < 0 ||
      taiMinusUtcSecondsColumn < 0
    ) {
      eop._dataError =
        "Error in loaded EOP data: The columnNames property must include modifiedJulianDateUtc, xPoleWanderRadians, yPoleWanderRadians, ut1MinusUtcSeconds, xCelestialPoleOffsetRadians, yCelestialPoleOffsetRadians, and taiMinusUtcSeconds columns";
      return;
    }

    const samples = (eop._samples = eopData.samples);
    const dates = (eop._dates = []);

    eop._dateColumn = dateColumn;
    eop._xPoleWanderRadiansColumn = xPoleWanderRadiansColumn;
    eop._yPoleWanderRadiansColumn = yPoleWanderRadiansColumn;
    eop._ut1MinusUtcSecondsColumn = ut1MinusUtcSecondsColumn;
    eop._xCelestialPoleOffsetRadiansColumn = xCelestialPoleOffsetRadiansColumn;
    eop._yCelestialPoleOffsetRadiansColumn = yCelestialPoleOffsetRadiansColumn;
    eop._taiMinusUtcSecondsColumn = taiMinusUtcSecondsColumn;

    eop._columnCount = eopData.columnNames.length;
    eop._lastIndex = undefined;

    let lastTaiMinusUtc;

    const addNewLeapSeconds = eop._addNewLeapSeconds;

    // Convert the ISO8601 dates to JulianDates.
    for (let i = 0, len = samples.length; i < len; i += eop._columnCount) {
      const mjd = samples[i + dateColumn];
      const taiMinusUtc = samples[i + taiMinusUtcSecondsColumn];
      const day = mjd + TimeConstants$1.MODIFIED_JULIAN_DATE_DIFFERENCE;
      const date = new JulianDate(day, taiMinusUtc, TimeStandard$1.TAI);
      dates.push(date);

      if (addNewLeapSeconds) {
        if (taiMinusUtc !== lastTaiMinusUtc && defined(lastTaiMinusUtc)) {
          // We crossed a leap second boundary, so add the leap second
          // if it does not already exist.
          const leapSeconds = JulianDate.leapSeconds;
          const leapSecondIndex = binarySearch(
            leapSeconds,
            date,
            compareLeapSecondDates
          );
          if (leapSecondIndex < 0) {
            const leapSecond = new LeapSecond(date, taiMinusUtc);
            leapSeconds.splice(~leapSecondIndex, 0, leapSecond);
          }
        }
        lastTaiMinusUtc = taiMinusUtc;
      }
    }
  }

  function fillResultFromIndex(eop, samples, index, columnCount, result) {
    const start = index * columnCount;
    result.xPoleWander = samples[start + eop._xPoleWanderRadiansColumn];
    result.yPoleWander = samples[start + eop._yPoleWanderRadiansColumn];
    result.xPoleOffset = samples[start + eop._xCelestialPoleOffsetRadiansColumn];
    result.yPoleOffset = samples[start + eop._yCelestialPoleOffsetRadiansColumn];
    result.ut1MinusUtc = samples[start + eop._ut1MinusUtcSecondsColumn];
  }

  function linearInterp(dx, y1, y2) {
    return y1 + dx * (y2 - y1);
  }

  function interpolate(eop, dates, samples, date, before, after, result) {
    const columnCount = eop._columnCount;

    // First check the bounds on the EOP data
    // If we are after the bounds of the data, return zeros.
    // The 'before' index should never be less than zero.
    if (after > dates.length - 1) {
      result.xPoleWander = 0;
      result.yPoleWander = 0;
      result.xPoleOffset = 0;
      result.yPoleOffset = 0;
      result.ut1MinusUtc = 0;
      return result;
    }

    const beforeDate = dates[before];
    const afterDate = dates[after];
    if (beforeDate.equals(afterDate) || date.equals(beforeDate)) {
      fillResultFromIndex(eop, samples, before, columnCount, result);
      return result;
    } else if (date.equals(afterDate)) {
      fillResultFromIndex(eop, samples, after, columnCount, result);
      return result;
    }

    const factor =
      JulianDate.secondsDifference(date, beforeDate) /
      JulianDate.secondsDifference(afterDate, beforeDate);

    const startBefore = before * columnCount;
    const startAfter = after * columnCount;

    // Handle UT1 leap second edge case
    let beforeUt1MinusUtc = samples[startBefore + eop._ut1MinusUtcSecondsColumn];
    let afterUt1MinusUtc = samples[startAfter + eop._ut1MinusUtcSecondsColumn];

    const offsetDifference = afterUt1MinusUtc - beforeUt1MinusUtc;
    if (offsetDifference > 0.5 || offsetDifference < -0.5) {
      // The absolute difference between the values is more than 0.5, so we may have
      // crossed a leap second.  Check if this is the case and, if so, adjust the
      // afterValue to account for the leap second.  This way, our interpolation will
      // produce reasonable results.
      const beforeTaiMinusUtc =
        samples[startBefore + eop._taiMinusUtcSecondsColumn];
      const afterTaiMinusUtc =
        samples[startAfter + eop._taiMinusUtcSecondsColumn];
      if (beforeTaiMinusUtc !== afterTaiMinusUtc) {
        if (afterDate.equals(date)) {
          // If we are at the end of the leap second interval, take the second value
          // Otherwise, the interpolation below will yield the wrong side of the
          // discontinuity
          // At the end of the leap second, we need to start accounting for the jump
          beforeUt1MinusUtc = afterUt1MinusUtc;
        } else {
          // Otherwise, remove the leap second so that the interpolation is correct
          afterUt1MinusUtc -= afterTaiMinusUtc - beforeTaiMinusUtc;
        }
      }
    }

    result.xPoleWander = linearInterp(
      factor,
      samples[startBefore + eop._xPoleWanderRadiansColumn],
      samples[startAfter + eop._xPoleWanderRadiansColumn]
    );
    result.yPoleWander = linearInterp(
      factor,
      samples[startBefore + eop._yPoleWanderRadiansColumn],
      samples[startAfter + eop._yPoleWanderRadiansColumn]
    );
    result.xPoleOffset = linearInterp(
      factor,
      samples[startBefore + eop._xCelestialPoleOffsetRadiansColumn],
      samples[startAfter + eop._xCelestialPoleOffsetRadiansColumn]
    );
    result.yPoleOffset = linearInterp(
      factor,
      samples[startBefore + eop._yCelestialPoleOffsetRadiansColumn],
      samples[startAfter + eop._yCelestialPoleOffsetRadiansColumn]
    );
    result.ut1MinusUtc = linearInterp(
      factor,
      beforeUt1MinusUtc,
      afterUt1MinusUtc
    );
    return result;
  }

  /**
   * A rotation expressed as a heading, pitch, and roll. 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.
   * @alias HeadingPitchRoll
   * @constructor
   *
   * @param {Number} [heading=0.0] The heading component in radians.
   * @param {Number} [pitch=0.0] The pitch component in radians.
   * @param {Number} [roll=0.0] The roll component in radians.
   */
  function HeadingPitchRoll(heading, pitch, roll) {
    /**
     * Gets or sets the heading.
     * @type {Number}
     * @default 0.0
     */
    this.heading = defaultValue(heading, 0.0);
    /**
     * Gets or sets the pitch.
     * @type {Number}
     * @default 0.0
     */
    this.pitch = defaultValue(pitch, 0.0);
    /**
     * Gets or sets the roll.
     * @type {Number}
     * @default 0.0
     */
    this.roll = defaultValue(roll, 0.0);
  }

  /**
   * Computes the heading, pitch and roll from a quaternion (see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles )
   *
   * @param {Quaternion} quaternion The quaternion from which to retrieve heading, pitch, and roll, all expressed in radians.
   * @param {HeadingPitchRoll} [result] The object in which to store the result. If not provided, a new instance is created and returned.
   * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided.
   */
  HeadingPitchRoll.fromQuaternion = function (quaternion, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(quaternion)) {
      throw new DeveloperError("quaternion is required");
    }
    //>>includeEnd('debug');
    if (!defined(result)) {
      result = new HeadingPitchRoll();
    }
    const test = 2 * (quaternion.w * quaternion.y - quaternion.z * quaternion.x);
    const denominatorRoll =
      1 - 2 * (quaternion.x * quaternion.x + quaternion.y * quaternion.y);
    const numeratorRoll =
      2 * (quaternion.w * quaternion.x + quaternion.y * quaternion.z);
    const denominatorHeading =
      1 - 2 * (quaternion.y * quaternion.y + quaternion.z * quaternion.z);
    const numeratorHeading =
      2 * (quaternion.w * quaternion.z + quaternion.x * quaternion.y);
    result.heading = -Math.atan2(numeratorHeading, denominatorHeading);
    result.roll = Math.atan2(numeratorRoll, denominatorRoll);
    result.pitch = -CesiumMath.asinClamped(test);
    return result;
  };

  /**
   * Returns a new HeadingPitchRoll instance from angles given in degrees.
   *
   * @param {Number} heading the heading in degrees
   * @param {Number} pitch the pitch in degrees
   * @param {Number} roll the heading in degrees
   * @param {HeadingPitchRoll} [result] The object in which to store the result. If not provided, a new instance is created and returned.
   * @returns {HeadingPitchRoll} A new HeadingPitchRoll instance
   */
  HeadingPitchRoll.fromDegrees = function (heading, pitch, roll, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(heading)) {
      throw new DeveloperError("heading is required");
    }
    if (!defined(pitch)) {
      throw new DeveloperError("pitch is required");
    }
    if (!defined(roll)) {
      throw new DeveloperError("roll is required");
    }
    //>>includeEnd('debug');
    if (!defined(result)) {
      result = new HeadingPitchRoll();
    }
    result.heading = heading * CesiumMath.RADIANS_PER_DEGREE;
    result.pitch = pitch * CesiumMath.RADIANS_PER_DEGREE;
    result.roll = roll * CesiumMath.RADIANS_PER_DEGREE;
    return result;
  };

  /**
   * Duplicates a HeadingPitchRoll instance.
   *
   * @param {HeadingPitchRoll} headingPitchRoll The HeadingPitchRoll to duplicate.
   * @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. (Returns undefined if headingPitchRoll is undefined)
   */
  HeadingPitchRoll.clone = function (headingPitchRoll, result) {
    if (!defined(headingPitchRoll)) {
      return undefined;
    }
    if (!defined(result)) {
      return new HeadingPitchRoll(
        headingPitchRoll.heading,
        headingPitchRoll.pitch,
        headingPitchRoll.roll
      );
    }
    result.heading = headingPitchRoll.heading;
    result.pitch = headingPitchRoll.pitch;
    result.roll = headingPitchRoll.roll;
    return result;
  };

  /**
   * Compares the provided HeadingPitchRolls componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {HeadingPitchRoll} [left] The first HeadingPitchRoll.
   * @param {HeadingPitchRoll} [right] The second HeadingPitchRoll.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  HeadingPitchRoll.equals = function (left, right) {
    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        left.heading === right.heading &&
        left.pitch === right.pitch &&
        left.roll === right.roll)
    );
  };

  /**
   * Compares the provided HeadingPitchRolls componentwise and returns
   * <code>true</code> if they pass an absolute or relative tolerance test,
   * <code>false</code> 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} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
   */
  HeadingPitchRoll.equalsEpsilon = function (
    left,
    right,
    relativeEpsilon,
    absoluteEpsilon
  ) {
    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        CesiumMath.equalsEpsilon(
          left.heading,
          right.heading,
          relativeEpsilon,
          absoluteEpsilon
        ) &&
        CesiumMath.equalsEpsilon(
          left.pitch,
          right.pitch,
          relativeEpsilon,
          absoluteEpsilon
        ) &&
        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
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {HeadingPitchRoll} [right] The right hand side HeadingPitchRoll.
   * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
   */
  HeadingPitchRoll.prototype.equals = function (right) {
    return HeadingPitchRoll.equals(this, right);
  };

  /**
   * Compares this HeadingPitchRoll against the provided HeadingPitchRoll componentwise and returns
   * <code>true</code> if they pass an absolute or relative tolerance test,
   * <code>false</code> 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} <code>true</code> if they are within the provided epsilon, <code>false</code> 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})`;
  };

  /**
   * 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 = defaultValue(options, defaultValue.EMPTY_OBJECT);

    this._xysFileUrlTemplate = Resource.createIfNeeded(
      options.xysFileUrlTemplate
    );
    this._interpolationOrder = defaultValue(options.interpolationOrder, 9);
    this._sampleZeroJulianEphemerisDate = defaultValue(
      options.sampleZeroJulianEphemerisDate,
      2442396.5
    );
    this._sampleZeroDateTT = new JulianDate(
      this._sampleZeroJulianEphemerisDate,
      0.0,
      TimeStandard$1.TAI
    );
    this._stepSizeDays = defaultValue(options.stepSizeDays, 1.0);
    this._samplesPerXysFile = defaultValue(options.samplesPerXysFile, 1000);
    this._totalSamples = 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$1 = new JulianDate(0, 0.0, TimeStandard$1.TAI);

  function getDaysSinceEpoch(xys, dayTT, secondTT) {
    const dateTT = julianDateScratch$1;
    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 {Promise<void>} A promise that, when resolved, indicates that the requested interval has been
   *                    preloaded.
   */
  Iau2006XysData.prototype.preload = function (
    startDayTT,
    startSecondTT,
    stopDayTT,
    stopSecondTT
  ) {
    const startDaysSinceEpoch = getDaysSinceEpoch(
      this,
      startDayTT,
      startSecondTT
    );
    const stopDaysSinceEpoch = getDaysSinceEpoch(this, stopDayTT, stopSecondTT);

    let startIndex =
      (startDaysSinceEpoch / this._stepSizeDays - this._interpolationOrder / 2) |
      0;
    if (startIndex < 0) {
      startIndex = 0;
    }

    let stopIndex =
      (stopDaysSinceEpoch / this._stepSizeDays - this._interpolationOrder / 2) |
      (0 + this._interpolationOrder);
    if (stopIndex >= this._totalSamples) {
      stopIndex = this._totalSamples - 1;
    }

    const startChunk = (startIndex / this._samplesPerXysFile) | 0;
    const stopChunk = (stopIndex / this._samplesPerXysFile) | 0;

    const promises = [];
    for (let i = startChunk; i <= stopChunk; ++i) {
      promises.push(requestXysChunk(this, i));
    }

    return Promise.all(promises);
  };

  /**
   * Computes the XYS values for a given date by interpolating.  If the required data is not yet downloaded,
   * this method will return undefined.
   *
   * @param {Number} dayTT The Julian day number for which to compute the XYS value, expressed in
   *                 the Terrestrial Time (TT) time standard.
   * @param {Number} secondTT The seconds past noon of the date for which to compute the XYS value, expressed in
   *                 the Terrestrial Time (TT) time standard.
   * @param {Iau2006XysSample} [result] The instance to which to copy the interpolated result.  If this parameter
   *                           is undefined, a new instance is allocated and returned.
   * @returns {Iau2006XysSample} The interpolated XYS values, or undefined if the required data for this
   *                             computation has not yet been downloaded.
   *
   * @see Iau2006XysData#preload
   */
  Iau2006XysData.prototype.computeXysRadians = function (
    dayTT,
    secondTT,
    result
  ) {
    const daysSinceEpoch = getDaysSinceEpoch(this, dayTT, secondTT);
    if (daysSinceEpoch < 0.0) {
      // Can't evaluate prior to the epoch of the data.
      return undefined;
    }

    const centerIndex = (daysSinceEpoch / this._stepSizeDays) | 0;
    if (centerIndex >= this._totalSamples) {
      // Can't evaluate after the last sample in the data.
      return undefined;
    }

    const degree = this._interpolationOrder;

    let firstIndex = centerIndex - ((degree / 2) | 0);
    if (firstIndex < 0) {
      firstIndex = 0;
    }
    let lastIndex = firstIndex + degree;
    if (lastIndex >= this._totalSamples) {
      lastIndex = this._totalSamples - 1;
      firstIndex = lastIndex - degree;
      if (firstIndex < 0) {
        firstIndex = 0;
      }
    }

    // Are all the samples we need present?
    // We can assume so if the first and last are present
    let isDataMissing = false;
    const samples = this._samples;
    if (!defined(samples[firstIndex * 3])) {
      requestXysChunk(this, (firstIndex / this._samplesPerXysFile) | 0);
      isDataMissing = true;
    }

    if (!defined(samples[lastIndex * 3])) {
      requestXysChunk(this, (lastIndex / this._samplesPerXysFile) | 0);
      isDataMissing = true;
    }

    if (isDataMissing) {
      return undefined;
    }

    if (!defined(result)) {
      result = new Iau2006XysSample(0.0, 0.0, 0.0);
    } else {
      result.x = 0.0;
      result.y = 0.0;
      result.s = 0.0;
    }

    const x = daysSinceEpoch - firstIndex * this._stepSizeDays;

    const work = this._work;
    const denom = this._denominators;
    const coef = this._coef;
    const xTable = this._xTable;

    let i, j;
    for (i = 0; i <= degree; ++i) {
      work[i] = x - xTable[i];
    }

    for (i = 0; i <= degree; ++i) {
      coef[i] = 1.0;

      for (j = 0; j <= degree; ++j) {
        if (j !== i) {
          coef[i] *= work[j];
        }
      }

      coef[i] *= denom[i];

      let sampleIndex = (firstIndex + i) * 3;
      result.x += coef[i] * samples[sampleIndex++];
      result.y += coef[i] * samples[sampleIndex++];
      result.s += coef[i] * samples[sampleIndex];
    }

    return result;
  };

  function requestXysChunk(xysData, chunkIndex) {
    if (xysData._chunkDownloadsInProgress[chunkIndex]) {
      // Chunk has already been requested.
      return xysData._chunkDownloadsInProgress[chunkIndex];
    }

    const deferred = defer();

    xysData._chunkDownloadsInProgress[chunkIndex] = deferred;

    let chunkUrl;
    const xysFileUrlTemplate = xysData._xysFileUrlTemplate;
    if (defined(xysFileUrlTemplate)) {
      chunkUrl = xysFileUrlTemplate.getDerivedResource({
        templateValues: {
          0: chunkIndex,
        },
      });
    } else {
      chunkUrl = new Resource({
        url: buildModuleUrl(`Assets/IAU2006_XYS/IAU2006_XYS_${chunkIndex}.json`),
      });
    }

    chunkUrl.fetchJson().then(function (chunk) {
      xysData._chunkDownloadsInProgress[chunkIndex] = false;

      const samples = xysData._samples;
      const newSamples = chunk.samples;
      const startIndex = chunkIndex * xysData._samplesPerXysFile * 3;

      for (let i = 0, len = newSamples.length; i < len; ++i) {
        samples[startIndex + i] = newSamples[i];
      }

      deferred.resolve();
    });

    return deferred.promise;
  }

  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} <code>true</code> if the browser supports the standard fullscreen API,
   * <code>false</code> otherwise.
   */
  Fullscreen.supportsFullscreen = function () {
    if (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 (!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 (!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 (!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 (!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 (!defined(isEdgeResult)) {
      isEdgeResult = false;
      const fields = / Edg\/([\.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 (!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 (!defined(isWindowsResult)) {
      isWindowsResult = /Windows/i.test(theNavigator.appVersion);
    }
    return isWindowsResult;
  }

  let isIPadOrIOSResult;
  function isIPadOrIOS() {
    if (!defined(isIPadOrIOSResult)) {
      isIPadOrIOSResult =
        navigator.platform === "iPhone" ||
        navigator.platform === "iPod" ||
        navigator.platform === "iPad";
    }

    return isIPadOrIOSResult;
  }

  function firefoxVersion() {
    return isFirefox() && firefoxVersionResult;
  }

  let hasPointerEvents;
  function supportsPointerEvents() {
    if (!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" &&
        (!defined(theNavigator.pointerEnabled) || theNavigator.pointerEnabled);
    }
    return hasPointerEvents;
  }

  let imageRenderingValueResult;
  let supportsImageRenderingPixelatedResult;
  function supportsImageRenderingPixelated() {
    if (!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 = 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 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 (defined(supportsWebP._promise)) {
      return supportsWebP._promise;
    }

    const supportsWebPDeferred = 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 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,
    isIPadOrIOS: isIPadOrIOS,
    hardwareConcurrency: 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";
  };

  /**
   * 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 = defaultValue(x, 0.0);

    /**
     * The Y component.
     * @type {Number}
     * @default 0.0
     */
    this.y = defaultValue(y, 0.0);

    /**
     * The Z component.
     * @type {Number}
     * @default 0.0
     */
    this.z = defaultValue(z, 0.0);

    /**
     * The W component.
     * @type {Number}
     * @default 0.0
     */
    this.w = defaultValue(w, 0.0);
  }

  let fromAxisAngleScratch = new 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);
    Check.typeOf.object("axis", axis);
    Check.typeOf.number("angle", angle);
    //>>includeEnd('debug');

    const halfAngle = angle / 2.0;
    const s = Math.sin(halfAngle);
    fromAxisAngleScratch = 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 (!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);
    Check.typeOf.object("matrix", matrix);
    //>>includeEnd('debug');

    let root;
    let x;
    let y;
    let z;
    let w;

    const m00 = matrix[Matrix3.COLUMN0ROW0];
    const m11 = matrix[Matrix3.COLUMN1ROW1];
    const m22 = matrix[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[Matrix3.COLUMN1ROW2] - matrix[Matrix3.COLUMN2ROW1]) * root;
      y = (matrix[Matrix3.COLUMN2ROW0] - matrix[Matrix3.COLUMN0ROW2]) * root;
      z = (matrix[Matrix3.COLUMN0ROW1] - matrix[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[Matrix3.getElementIndex(i, i)] -
          matrix[Matrix3.getElementIndex(j, j)] -
          matrix[Matrix3.getElementIndex(k, k)] +
          1.0
      );

      const quat = fromRotationMatrixQuat;
      quat[i] = 0.5 * root;
      root = 0.5 / root;
      w =
        (matrix[Matrix3.getElementIndex(k, j)] -
          matrix[Matrix3.getElementIndex(j, k)]) *
        root;
      quat[j] =
        (matrix[Matrix3.getElementIndex(j, i)] +
          matrix[Matrix3.getElementIndex(i, j)]) *
        root;
      quat[k] =
        (matrix[Matrix3.getElementIndex(k, i)] +
          matrix[Matrix3.getElementIndex(i, k)]) *
        root;

      x = -quat[0];
      y = -quat[1];
      z = -quat[2];
    }

    if (!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);
    Check.typeOf.object("headingPitchRoll", headingPitchRoll);
    //>>includeEnd('debug');

    scratchRollQuaternion = Quaternion.fromAxisAngle(
      Cartesian3.UNIT_X,
      headingPitchRoll.roll,
      scratchHPRQuaternion$1
    );
    scratchPitchQuaternion = Quaternion.fromAxisAngle(
      Cartesian3.UNIT_Y,
      -headingPitchRoll.pitch,
      result
    );
    result = Quaternion.multiply(
      scratchPitchQuaternion,
      scratchRollQuaternion,
      scratchPitchQuaternion
    );
    scratchHeadingQuaternion = Quaternion.fromAxisAngle(
      Cartesian3.UNIT_Z,
      -headingPitchRoll.heading,
      scratchHPRQuaternion$1
    );
    return Quaternion.multiply(scratchHeadingQuaternion, result, result);
  };

  const sampledQuaternionAxis = new Cartesian3();
  const sampledQuaternionRotation = new 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);
    Check.typeOf.object("value", value);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = 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);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    if (!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 (!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 (!defined(result)) {
      result = new Quaternion();
    }
    Cartesian3.fromArray(array, 0, sampledQuaternionRotation);
    const magnitude = 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 (!defined(quaternion)) {
      return undefined;
    }

    if (!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);
    Check.typeOf.object("quaternion", quaternion);
    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);
    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);
    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);
    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);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    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);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    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);
    Check.typeOf.object("quaternion", quaternion);
    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);
    Check.typeOf.object("left", left);
    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);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    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);
    Check.typeOf.object("quaternion", quaternion);
    Check.typeOf.number("scalar", scalar);
    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);
    Check.typeOf.object("quaternion", quaternion);
    Check.typeOf.number("scalar", scalar);
    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);
    Check.typeOf.object("quaternion", quaternion);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const w = quaternion.w;
    if (Math.abs(w - 1.0) < 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);
    Check.typeOf.object("quaternion", quaternion);
    //>>includeEnd('debug');

    if (Math.abs(quaternion.w - 1.0) < 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);
    Check.typeOf.object("start", start);
    Check.typeOf.object("end", end);
    Check.typeOf.number("t", t);
    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);
    Check.typeOf.object("start", start);
    Check.typeOf.object("end", end);
    Check.typeOf.number("t", t);
    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 < 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);
    Check.typeOf.object("quaternion", quaternion);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const theta = CesiumMath.acosClamped(quaternion.w);
    let thetaOverSinTheta = 0.0;

    if (theta !== 0.0) {
      thetaOverSinTheta = theta / Math.sin(theta);
    }

    return 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);
    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const theta = 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 Cartesian3();
  const squadScratchCartesian1 = new Cartesian3();
  const squadScratchQuaternion0 = new Quaternion();
  const squadScratchQuaternion1 = new Quaternion();

  /**
   * Computes an inner quadrangle point.
   * <p>This will compute quaternions that ensure a squad curve is C<sup>1</sup>.</p>
   *
   * @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);
    Check.typeOf.object("q0", q0);
    Check.typeOf.object("q1", q1);
    Check.typeOf.object("q2", q2);
    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);

    Cartesian3.add(cart0, cart1, cart0);
    Cartesian3.multiplyByScalar(cart0, 0.25, cart0);
    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);
    Check.typeOf.object("q0", q0);
    Check.typeOf.object("q1", q1);
    Check.typeOf.object("s0", s0);
    Check.typeOf.object("s1", s1);
    Check.typeOf.number("t", t);
    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<sup>-6</sup>.
   *
   * @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);
    Check.typeOf.object("start", start);
    Check.typeOf.object("end", end);
    Check.typeOf.number("t", t);
    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);
    Check.typeOf.object("q0", q0);
    Check.typeOf.object("q1", q1);
    Check.typeOf.object("s0", s0);
    Check.typeOf.object("s1", s1);
    Check.typeOf.number("t", t);
    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
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Quaternion} [left] The first quaternion.
   * @param {Quaternion} [right] The second quaternion.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  Quaternion.equals = function (left, right) {
    return (
      left === right ||
      (defined(left) &&
        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
   * <code>true</code> if they are within the provided epsilon,
   * <code>false</code> 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} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
   */
  Quaternion.equalsEpsilon = function (left, right, epsilon) {
    epsilon = defaultValue(epsilon, 0);

    return (
      left === right ||
      (defined(left) &&
        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
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Quaternion} [right] The right hand side quaternion.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  Quaternion.prototype.equals = function (right) {
    return Quaternion.equals(this, right);
  };

  /**
   * Compares this and the provided quaternion componentwise and returns
   * <code>true</code> if they are within the provided epsilon,
   * <code>false</code> otherwise.
   *
   * @param {Quaternion} [right] The right hand side quaternion.
   * @param {Number} [epsilon=0] The epsilon to use for equality testing.
   * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> 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})`;
  };

  /**
   * Contains functions for transforming positions to various reference frames.
   *
   * @namespace Transforms
   */
  const Transforms = {};

  const vectorProductLocalFrame = {
    up: {
      south: "east",
      north: "west",
      west: "south",
      east: "north",
    },
    down: {
      south: "west",
      north: "east",
      west: "north",
      east: "south",
    },
    south: {
      up: "west",
      down: "east",
      west: "down",
      east: "up",
    },
    north: {
      up: "east",
      down: "west",
      west: "up",
      east: "down",
    },
    west: {
      up: "north",
      down: "south",
      north: "down",
      south: "up",
    },
    east: {
      up: "south",
      down: "north",
      north: "up",
      south: "down",
    },
  };

  const degeneratePositionLocalFrame = {
    north: [-1, 0, 0],
    east: [0, 1, 0],
    up: [0, 0, 1],
    south: [1, 0, 0],
    west: [0, -1, 0],
    down: [0, 0, -1],
  };

  const localFrameToFixedFrameCache = {};

  const scratchCalculateCartesian = {
    east: new Cartesian3(),
    north: new Cartesian3(),
    up: new Cartesian3(),
    west: new Cartesian3(),
    south: new Cartesian3(),
    down: new Cartesian3(),
  };
  let scratchFirstCartesian = new Cartesian3();
  let scratchSecondCartesian = new Cartesian3();
  let scratchThirdCartesian = new Cartesian3();
  /**
   * Generates a function that computes a 4x4 transformation matrix from a reference frame
   * centered at the provided origin to the provided ellipsoid's fixed reference frame.
   * @param  {String} firstAxis  name of the first axis of the local reference frame. Must be
   *  'east', 'north', 'up', 'west', 'south' or 'down'.
   * @param  {String} secondAxis  name of the second axis of the local reference frame. Must be
   *  'east', 'north', 'up', 'west', 'south' or 'down'.
   * @return {Transforms.LocalFrameToFixedFrame} The function that will computes a
   * 4x4 transformation matrix from a reference frame, with first axis and second axis compliant with the parameters,
   */
  Transforms.localFrameToFixedFrameGenerator = function (firstAxis, secondAxis) {
    if (
      !vectorProductLocalFrame.hasOwnProperty(firstAxis) ||
      !vectorProductLocalFrame[firstAxis].hasOwnProperty(secondAxis)
    ) {
      throw new DeveloperError(
        "firstAxis and secondAxis must be east, north, up, west, south or down."
      );
    }
    const thirdAxis = vectorProductLocalFrame[firstAxis][secondAxis];

    /**
     * Computes a 4x4 transformation matrix from a reference frame
     * centered at the provided origin to the provided ellipsoid's fixed reference frame.
     * @callback Transforms.LocalFrameToFixedFrame
     * @param {Cartesian3} origin The center point of the local reference frame.
     * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
     * @param {Matrix4} [result] The object onto which to store the result.
     * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
     */
    let resultat;
    const hashAxis = firstAxis + secondAxis;
    if (defined(localFrameToFixedFrameCache[hashAxis])) {
      resultat = localFrameToFixedFrameCache[hashAxis];
    } else {
      resultat = function (origin, ellipsoid, result) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(origin)) {
          throw new DeveloperError("origin is required.");
        }
        //>>includeEnd('debug');
        if (!defined(result)) {
          result = new Matrix4();
        }
        if (
          Cartesian3.equalsEpsilon(origin, Cartesian3.ZERO, CesiumMath.EPSILON14)
        ) {
          // If x, y, and z are zero, use the degenerate local frame, which is a special case
          Cartesian3.unpack(
            degeneratePositionLocalFrame[firstAxis],
            0,
            scratchFirstCartesian
          );
          Cartesian3.unpack(
            degeneratePositionLocalFrame[secondAxis],
            0,
            scratchSecondCartesian
          );
          Cartesian3.unpack(
            degeneratePositionLocalFrame[thirdAxis],
            0,
            scratchThirdCartesian
          );
        } else if (
          CesiumMath.equalsEpsilon(origin.x, 0.0, CesiumMath.EPSILON14) &&
          CesiumMath.equalsEpsilon(origin.y, 0.0, CesiumMath.EPSILON14)
        ) {
          // If x and y are zero, assume origin is at a pole, which is a special case.
          const sign = CesiumMath.sign(origin.z);

          Cartesian3.unpack(
            degeneratePositionLocalFrame[firstAxis],
            0,
            scratchFirstCartesian
          );
          if (firstAxis !== "east" && firstAxis !== "west") {
            Cartesian3.multiplyByScalar(
              scratchFirstCartesian,
              sign,
              scratchFirstCartesian
            );
          }

          Cartesian3.unpack(
            degeneratePositionLocalFrame[secondAxis],
            0,
            scratchSecondCartesian
          );
          if (secondAxis !== "east" && secondAxis !== "west") {
            Cartesian3.multiplyByScalar(
              scratchSecondCartesian,
              sign,
              scratchSecondCartesian
            );
          }

          Cartesian3.unpack(
            degeneratePositionLocalFrame[thirdAxis],
            0,
            scratchThirdCartesian
          );
          if (thirdAxis !== "east" && thirdAxis !== "west") {
            Cartesian3.multiplyByScalar(
              scratchThirdCartesian,
              sign,
              scratchThirdCartesian
            );
          }
        } else {
          ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
          ellipsoid.geodeticSurfaceNormal(origin, scratchCalculateCartesian.up);

          const up = scratchCalculateCartesian.up;
          const east = scratchCalculateCartesian.east;
          east.x = -origin.y;
          east.y = origin.x;
          east.z = 0.0;
          Cartesian3.normalize(east, scratchCalculateCartesian.east);
          Cartesian3.cross(up, east, scratchCalculateCartesian.north);

          Cartesian3.multiplyByScalar(
            scratchCalculateCartesian.up,
            -1,
            scratchCalculateCartesian.down
          );
          Cartesian3.multiplyByScalar(
            scratchCalculateCartesian.east,
            -1,
            scratchCalculateCartesian.west
          );
          Cartesian3.multiplyByScalar(
            scratchCalculateCartesian.north,
            -1,
            scratchCalculateCartesian.south
          );

          scratchFirstCartesian = scratchCalculateCartesian[firstAxis];
          scratchSecondCartesian = scratchCalculateCartesian[secondAxis];
          scratchThirdCartesian = scratchCalculateCartesian[thirdAxis];
        }
        result[0] = scratchFirstCartesian.x;
        result[1] = scratchFirstCartesian.y;
        result[2] = scratchFirstCartesian.z;
        result[3] = 0.0;
        result[4] = scratchSecondCartesian.x;
        result[5] = scratchSecondCartesian.y;
        result[6] = scratchSecondCartesian.z;
        result[7] = 0.0;
        result[8] = scratchThirdCartesian.x;
        result[9] = scratchThirdCartesian.y;
        result[10] = scratchThirdCartesian.z;
        result[11] = 0.0;
        result[12] = origin.x;
        result[13] = origin.y;
        result[14] = origin.z;
        result[15] = 1.0;
        return result;
      };
      localFrameToFixedFrameCache[hashAxis] = resultat;
    }
    return resultat;
  };

  /**
   * Computes a 4x4 transformation matrix from a reference frame with an east-north-up axes
   * centered at the provided origin to the provided ellipsoid's fixed reference frame.
   * The local axes are defined as:
   * <ul>
   * <li>The <code>x</code> axis points in the local east direction.</li>
   * <li>The <code>y</code> axis points in the local north direction.</li>
   * <li>The <code>z</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
   * </ul>
   *
   * @function
   * @param {Cartesian3} origin The center point of the local reference frame.
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
   * @param {Matrix4} [result] The object onto which to store the result.
   * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
   *
   * @example
   * // Get the transform from local east-north-up at cartographic (0.0, 0.0) to Earth's fixed frame.
   * const center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
   * const transform = Cesium.Transforms.eastNorthUpToFixedFrame(center);
   */
  Transforms.eastNorthUpToFixedFrame = Transforms.localFrameToFixedFrameGenerator(
    "east",
    "north"
  );

  /**
   * Computes a 4x4 transformation matrix from a reference frame with an north-east-down axes
   * centered at the provided origin to the provided ellipsoid's fixed reference frame.
   * The local axes are defined as:
   * <ul>
   * <li>The <code>x</code> axis points in the local north direction.</li>
   * <li>The <code>y</code> axis points in the local east direction.</li>
   * <li>The <code>z</code> axis points in the opposite direction of the ellipsoid surface normal which passes through the position.</li>
   * </ul>
   *
   * @function
   * @param {Cartesian3} origin The center point of the local reference frame.
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
   * @param {Matrix4} [result] The object onto which to store the result.
   * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
   *
   * @example
   * // Get the transform from local north-east-down at cartographic (0.0, 0.0) to Earth's fixed frame.
   * const center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
   * const transform = Cesium.Transforms.northEastDownToFixedFrame(center);
   */
  Transforms.northEastDownToFixedFrame = Transforms.localFrameToFixedFrameGenerator(
    "north",
    "east"
  );

  /**
   * Computes a 4x4 transformation matrix from a reference frame with an north-up-east axes
   * centered at the provided origin to the provided ellipsoid's fixed reference frame.
   * The local axes are defined as:
   * <ul>
   * <li>The <code>x</code> axis points in the local north direction.</li>
   * <li>The <code>y</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
   * <li>The <code>z</code> axis points in the local east direction.</li>
   * </ul>
   *
   * @function
   * @param {Cartesian3} origin The center point of the local reference frame.
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
   * @param {Matrix4} [result] The object onto which to store the result.
   * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
   *
   * @example
   * // Get the transform from local north-up-east at cartographic (0.0, 0.0) to Earth's fixed frame.
   * const center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
   * const transform = Cesium.Transforms.northUpEastToFixedFrame(center);
   */
  Transforms.northUpEastToFixedFrame = Transforms.localFrameToFixedFrameGenerator(
    "north",
    "up"
  );

  /**
   * Computes a 4x4 transformation matrix from a reference frame with an north-west-up axes
   * centered at the provided origin to the provided ellipsoid's fixed reference frame.
   * The local axes are defined as:
   * <ul>
   * <li>The <code>x</code> axis points in the local north direction.</li>
   * <li>The <code>y</code> axis points in the local west direction.</li>
   * <li>The <code>z</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
   * </ul>
   *
   * @function
   * @param {Cartesian3} origin The center point of the local reference frame.
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
   * @param {Matrix4} [result] The object onto which to store the result.
   * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
   *
   * @example
   * // Get the transform from local north-West-Up at cartographic (0.0, 0.0) to Earth's fixed frame.
   * const center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
   * const transform = Cesium.Transforms.northWestUpToFixedFrame(center);
   */
  Transforms.northWestUpToFixedFrame = Transforms.localFrameToFixedFrameGenerator(
    "north",
    "west"
  );

  const scratchHPRQuaternion = new Quaternion();
  const scratchScale$5 = new Cartesian3(1.0, 1.0, 1.0);
  const scratchHPRMatrix4 = new Matrix4();

  /**
   * Computes a 4x4 transformation matrix from a reference frame with axes computed from the heading-pitch-roll angles
   * centered at the provided origin to the provided ellipsoid's fixed reference frame. Heading is the rotation from the local north
   * direction where a positive angle is increasing eastward. Pitch is the rotation from the local east-north plane. Positive pitch angles
   * are above the plane. Negative pitch angles are below the plane. Roll is the first rotation applied about the local east axis.
   *
   * @param {Cartesian3} origin The center point of the local reference frame.
   * @param {HeadingPitchRoll} headingPitchRoll The heading, pitch, and roll.
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
   * @param {Transforms.LocalFrameToFixedFrame} [fixedFrameTransform=Transforms.eastNorthUpToFixedFrame] A 4x4 transformation
   *  matrix from a reference frame to the provided ellipsoid's fixed reference frame
   * @param {Matrix4} [result] The object onto which to store the result.
   * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
   *
   * @example
   * // Get the transform from local heading-pitch-roll at cartographic (0.0, 0.0) to Earth's fixed frame.
   * const center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
   * const heading = -Cesium.Math.PI_OVER_TWO;
   * const pitch = Cesium.Math.PI_OVER_FOUR;
   * const roll = 0.0;
   * const hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll);
   * const transform = Cesium.Transforms.headingPitchRollToFixedFrame(center, hpr);
   */
  Transforms.headingPitchRollToFixedFrame = function (
    origin,
    headingPitchRoll,
    ellipsoid,
    fixedFrameTransform,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("HeadingPitchRoll", headingPitchRoll);
    //>>includeEnd('debug');

    fixedFrameTransform = defaultValue(
      fixedFrameTransform,
      Transforms.eastNorthUpToFixedFrame
    );
    const hprQuaternion = Quaternion.fromHeadingPitchRoll(
      headingPitchRoll,
      scratchHPRQuaternion
    );
    const hprMatrix = Matrix4.fromTranslationQuaternionRotationScale(
      Cartesian3.ZERO,
      hprQuaternion,
      scratchScale$5,
      scratchHPRMatrix4
    );
    result = fixedFrameTransform(origin, ellipsoid, result);
    return Matrix4.multiply(result, hprMatrix, result);
  };

  const scratchENUMatrix4 = new Matrix4();
  const scratchHPRMatrix3 = new Matrix3();

  /**
   * Computes a quaternion from a reference frame with axes computed from the heading-pitch-roll angles
   * centered at the provided origin. Heading is the rotation from the local north
   * direction where a positive angle is increasing eastward. Pitch is the rotation from the local east-north plane. Positive pitch angles
   * are above the plane. Negative pitch angles are below the plane. Roll is the first rotation applied about the local east axis.
   *
   * @param {Cartesian3} origin The center point of the local reference frame.
   * @param {HeadingPitchRoll} headingPitchRoll The heading, pitch, and roll.
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
   * @param {Transforms.LocalFrameToFixedFrame} [fixedFrameTransform=Transforms.eastNorthUpToFixedFrame] A 4x4 transformation
   *  matrix from a reference frame to the provided ellipsoid's fixed reference frame
   * @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.
   *
   * @example
   * // Get the quaternion from local heading-pitch-roll at cartographic (0.0, 0.0) to Earth's fixed frame.
   * const center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
   * const heading = -Cesium.Math.PI_OVER_TWO;
   * const pitch = Cesium.Math.PI_OVER_FOUR;
   * const roll = 0.0;
   * const hpr = new HeadingPitchRoll(heading, pitch, roll);
   * const quaternion = Cesium.Transforms.headingPitchRollQuaternion(center, hpr);
   */
  Transforms.headingPitchRollQuaternion = function (
    origin,
    headingPitchRoll,
    ellipsoid,
    fixedFrameTransform,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("HeadingPitchRoll", headingPitchRoll);
    //>>includeEnd('debug');

    const transform = Transforms.headingPitchRollToFixedFrame(
      origin,
      headingPitchRoll,
      ellipsoid,
      fixedFrameTransform,
      scratchENUMatrix4
    );
    const rotation = Matrix4.getMatrix3(transform, scratchHPRMatrix3);
    return Quaternion.fromRotationMatrix(rotation, result);
  };

  const noScale = new Cartesian3(1.0, 1.0, 1.0);
  const hprCenterScratch = new Cartesian3();
  const ffScratch = new Matrix4();
  const hprTransformScratch = new Matrix4();
  const hprRotationScratch = new Matrix3();
  const hprQuaternionScratch = new Quaternion();
  /**
   * Computes heading-pitch-roll angles from a transform in a particular reference frame. Heading is the rotation from the local north
   * direction where a positive angle is increasing eastward. Pitch is the rotation from the local east-north plane. Positive pitch angles
   * are above the plane. Negative pitch angles are below the plane. Roll is the first rotation applied about the local east axis.
   *
   * @param {Matrix4} transform The transform
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
   * @param {Transforms.LocalFrameToFixedFrame} [fixedFrameTransform=Transforms.eastNorthUpToFixedFrame] A 4x4 transformation
   *  matrix from a reference frame to the provided ellipsoid's fixed reference frame
   * @param {HeadingPitchRoll} [result] The object onto which to store the result.
   * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if none was provided.
   */
  Transforms.fixedFrameToHeadingPitchRoll = function (
    transform,
    ellipsoid,
    fixedFrameTransform,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("transform", transform);
    //>>includeEnd('debug');

    ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
    fixedFrameTransform = defaultValue(
      fixedFrameTransform,
      Transforms.eastNorthUpToFixedFrame
    );
    if (!defined(result)) {
      result = new HeadingPitchRoll();
    }

    const center = Matrix4.getTranslation(transform, hprCenterScratch);
    if (Cartesian3.equals(center, Cartesian3.ZERO)) {
      result.heading = 0;
      result.pitch = 0;
      result.roll = 0;
      return result;
    }
    let toFixedFrame = Matrix4.inverseTransformation(
      fixedFrameTransform(center, ellipsoid, ffScratch),
      ffScratch
    );
    let transformCopy = Matrix4.setScale(transform, noScale, hprTransformScratch);
    transformCopy = Matrix4.setTranslation(
      transformCopy,
      Cartesian3.ZERO,
      transformCopy
    );

    toFixedFrame = Matrix4.multiply(toFixedFrame, transformCopy, toFixedFrame);
    let quaternionRotation = Quaternion.fromRotationMatrix(
      Matrix4.getMatrix3(toFixedFrame, hprRotationScratch),
      hprQuaternionScratch
    );
    quaternionRotation = Quaternion.normalize(
      quaternionRotation,
      quaternionRotation
    );

    return HeadingPitchRoll.fromQuaternion(quaternionRotation, result);
  };

  const gmstConstant0 = 6 * 3600 + 41 * 60 + 50.54841;
  const gmstConstant1 = 8640184.812866;
  const gmstConstant2 = 0.093104;
  const gmstConstant3 = -6.2e-6;
  const rateCoef = 1.1772758384668e-19;
  const wgs84WRPrecessing = 7.2921158553e-5;
  const twoPiOverSecondsInDay = CesiumMath.TWO_PI / 86400.0;
  let dateInUtc = new JulianDate();

  /**
   * Computes a rotation matrix to transform a point or vector from True Equator Mean Equinox (TEME) axes to the
   * pseudo-fixed axes at a given time.  This method treats the UT1 time standard as equivalent to UTC.
   *
   * @param {JulianDate} date The time at which to compute the rotation matrix.
   * @param {Matrix3} [result] The object onto which to store the result.
   * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if none was provided.
   *
   * @example
   * //Set the view to the inertial frame.
   * scene.postUpdate.addEventListener(function(scene, time) {
   *    const now = Cesium.JulianDate.now();
   *    const offset = Cesium.Matrix4.multiplyByPoint(camera.transform, camera.position, new Cesium.Cartesian3());
   *    const transform = Cesium.Matrix4.fromRotationTranslation(Cesium.Transforms.computeTemeToPseudoFixedMatrix(now));
   *    const inverseTransform = Cesium.Matrix4.inverseTransformation(transform, new Cesium.Matrix4());
   *    Cesium.Matrix4.multiplyByPoint(inverseTransform, offset, offset);
   *    camera.lookAtTransform(transform, offset);
   * });
   */
  Transforms.computeTemeToPseudoFixedMatrix = function (date, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(date)) {
      throw new DeveloperError("date is required.");
    }
    //>>includeEnd('debug');

    // GMST is actually computed using UT1.  We're using UTC as an approximation of UT1.
    // We do not want to use the function like convertTaiToUtc in JulianDate because
    // we explicitly do not want to fail when inside the leap second.

    dateInUtc = JulianDate.addSeconds(
      date,
      -JulianDate.computeTaiMinusUtc(date),
      dateInUtc
    );
    const utcDayNumber = dateInUtc.dayNumber;
    const utcSecondsIntoDay = dateInUtc.secondsOfDay;

    let t;
    const diffDays = utcDayNumber - 2451545;
    if (utcSecondsIntoDay >= 43200.0) {
      t = (diffDays + 0.5) / TimeConstants$1.DAYS_PER_JULIAN_CENTURY;
    } else {
      t = (diffDays - 0.5) / TimeConstants$1.DAYS_PER_JULIAN_CENTURY;
    }

    const gmst0 =
      gmstConstant0 +
      t * (gmstConstant1 + t * (gmstConstant2 + t * gmstConstant3));
    const angle = (gmst0 * twoPiOverSecondsInDay) % CesiumMath.TWO_PI;
    const ratio = wgs84WRPrecessing + rateCoef * (utcDayNumber - 2451545.5);
    const secondsSinceMidnight =
      (utcSecondsIntoDay + TimeConstants$1.SECONDS_PER_DAY * 0.5) %
      TimeConstants$1.SECONDS_PER_DAY;
    const gha = angle + ratio * secondsSinceMidnight;
    const cosGha = Math.cos(gha);
    const sinGha = Math.sin(gha);

    if (!defined(result)) {
      return new Matrix3(
        cosGha,
        sinGha,
        0.0,
        -sinGha,
        cosGha,
        0.0,
        0.0,
        0.0,
        1.0
      );
    }
    result[0] = cosGha;
    result[1] = -sinGha;
    result[2] = 0.0;
    result[3] = sinGha;
    result[4] = cosGha;
    result[5] = 0.0;
    result[6] = 0.0;
    result[7] = 0.0;
    result[8] = 1.0;
    return result;
  };

  /**
   * The source of IAU 2006 XYS data, used for computing the transformation between the
   * Fixed and ICRF axes.
   * @type {Iau2006XysData}
   *
   * @see Transforms.computeIcrfToFixedMatrix
   * @see Transforms.computeFixedToIcrfMatrix
   *
   * @private
   */
  Transforms.iau2006XysData = new Iau2006XysData();

  /**
   * The source of Earth Orientation Parameters (EOP) data, used for computing the transformation
   * between the Fixed and ICRF axes.  By default, zero values are used for all EOP values,
   * yielding a reasonable but not completely accurate representation of the ICRF axes.
   * @type {EarthOrientationParameters}
   *
   * @see Transforms.computeIcrfToFixedMatrix
   * @see Transforms.computeFixedToIcrfMatrix
   *
   * @private
   */
  Transforms.earthOrientationParameters = EarthOrientationParameters.NONE;

  const ttMinusTai = 32.184;
  const j2000ttDays = 2451545.0;

  /**
   * Preloads the data necessary to transform between the ICRF and Fixed axes, in either
   * direction, over a given interval.  This function returns a promise that, when resolved,
   * indicates that the preload has completed.
   *
   * @param {TimeInterval} timeInterval The interval to preload.
   * @returns {Promise<void>} A promise that, when resolved, indicates that the preload has completed
   *          and evaluation of the transformation between the fixed and ICRF axes will
   *          no longer return undefined for a time inside the interval.
   *
   *
   * @example
   * const interval = new Cesium.TimeInterval(...);
   * Promise.resolve(Cesium.Transforms.preloadIcrfFixed(interval)).then(function() {
   *     // the data is now loaded
   * });
   *
   * @see Transforms.computeIcrfToFixedMatrix
   * @see Transforms.computeFixedToIcrfMatrix
   */
  Transforms.preloadIcrfFixed = function (timeInterval) {
    const startDayTT = timeInterval.start.dayNumber;
    const startSecondTT = timeInterval.start.secondsOfDay + ttMinusTai;
    const stopDayTT = timeInterval.stop.dayNumber;
    const stopSecondTT = timeInterval.stop.secondsOfDay + ttMinusTai;

    const xysPromise = Transforms.iau2006XysData.preload(
      startDayTT,
      startSecondTT,
      stopDayTT,
      stopSecondTT
    );
    const eopPromise = Transforms.earthOrientationParameters.getPromiseToLoad();

    return Promise.all([xysPromise, eopPromise]);
  };

  /**
   * Computes a rotation matrix to transform a point or vector from the International Celestial
   * Reference Frame (GCRF/ICRF) inertial frame axes to the Earth-Fixed frame axes (ITRF)
   * at a given time.  This function may return undefined if the data necessary to
   * do the transformation is not yet loaded.
   *
   * @param {JulianDate} date The time at which to compute the rotation matrix.
   * @param {Matrix3} [result] The object onto which to store the result.  If this parameter is
   *                  not specified, a new instance is created and returned.
   * @returns {Matrix3} The rotation matrix, or undefined if the data necessary to do the
   *                   transformation is not yet loaded.
   *
   *
   * @example
   * scene.postUpdate.addEventListener(function(scene, time) {
   *   // View in ICRF.
   *   const icrfToFixed = Cesium.Transforms.computeIcrfToFixedMatrix(time);
   *   if (Cesium.defined(icrfToFixed)) {
   *     const offset = Cesium.Cartesian3.clone(camera.position);
   *     const transform = Cesium.Matrix4.fromRotationTranslation(icrfToFixed);
   *     camera.lookAtTransform(transform, offset);
   *   }
   * });
   *
   * @see Transforms.preloadIcrfFixed
   */
  Transforms.computeIcrfToFixedMatrix = function (date, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(date)) {
      throw new DeveloperError("date is required.");
    }
    //>>includeEnd('debug');
    if (!defined(result)) {
      result = new Matrix3();
    }

    const fixedToIcrfMtx = Transforms.computeFixedToIcrfMatrix(date, result);
    if (!defined(fixedToIcrfMtx)) {
      return undefined;
    }

    return Matrix3.transpose(fixedToIcrfMtx, result);
  };

  const xysScratch = new Iau2006XysSample(0.0, 0.0, 0.0);
  const eopScratch = new EarthOrientationParametersSample(
    0.0,
    0.0,
    0.0,
    0.0,
    0.0);
  const rotation1Scratch = new Matrix3();
  const rotation2Scratch = new Matrix3();

  /**
   * Computes a rotation matrix to transform a point or vector from the Earth-Fixed frame axes (ITRF)
   * to the International Celestial Reference Frame (GCRF/ICRF) inertial frame axes
   * at a given time.  This function may return undefined if the data necessary to
   * do the transformation is not yet loaded.
   *
   * @param {JulianDate} date The time at which to compute the rotation matrix.
   * @param {Matrix3} [result] The object onto which to store the result.  If this parameter is
   *                  not specified, a new instance is created and returned.
   * @returns {Matrix3} The rotation matrix, or undefined if the data necessary to do the
   *                   transformation is not yet loaded.
   *
   *
   * @example
   * // Transform a point from the ICRF axes to the Fixed axes.
   * const now = Cesium.JulianDate.now();
   * const pointInFixed = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
   * const fixedToIcrf = Cesium.Transforms.computeIcrfToFixedMatrix(now);
   * let pointInInertial = new Cesium.Cartesian3();
   * if (Cesium.defined(fixedToIcrf)) {
   *     pointInInertial = Cesium.Matrix3.multiplyByVector(fixedToIcrf, pointInFixed, pointInInertial);
   * }
   *
   * @see Transforms.preloadIcrfFixed
   */
  Transforms.computeFixedToIcrfMatrix = function (date, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(date)) {
      throw new DeveloperError("date is required.");
    }
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Matrix3();
    }

    // Compute pole wander
    const eop = Transforms.earthOrientationParameters.compute(date, eopScratch);
    if (!defined(eop)) {
      return undefined;
    }

    // There is no external conversion to Terrestrial Time (TT).
    // So use International Atomic Time (TAI) and convert using offsets.
    // Here we are assuming that dayTT and secondTT are positive
    const dayTT = date.dayNumber;
    // It's possible here that secondTT could roll over 86400
    // This does not seem to affect the precision (unit tests check for this)
    const secondTT = date.secondsOfDay + ttMinusTai;

    const xys = Transforms.iau2006XysData.computeXysRadians(
      dayTT,
      secondTT,
      xysScratch
    );
    if (!defined(xys)) {
      return undefined;
    }

    const x = xys.x + eop.xPoleOffset;
    const y = xys.y + eop.yPoleOffset;

    // Compute XYS rotation
    const a = 1.0 / (1.0 + Math.sqrt(1.0 - x * x - y * y));

    const rotation1 = rotation1Scratch;
    rotation1[0] = 1.0 - a * x * x;
    rotation1[3] = -a * x * y;
    rotation1[6] = x;
    rotation1[1] = -a * x * y;
    rotation1[4] = 1 - a * y * y;
    rotation1[7] = y;
    rotation1[2] = -x;
    rotation1[5] = -y;
    rotation1[8] = 1 - a * (x * x + y * y);

    const rotation2 = Matrix3.fromRotationZ(-xys.s, rotation2Scratch);
    const matrixQ = Matrix3.multiply(rotation1, rotation2, rotation1Scratch);

    // Similar to TT conversions above
    // It's possible here that secondTT could roll over 86400
    // This does not seem to affect the precision (unit tests check for this)
    const dateUt1day = date.dayNumber;
    const dateUt1sec =
      date.secondsOfDay - JulianDate.computeTaiMinusUtc(date) + eop.ut1MinusUtc;

    // Compute Earth rotation angle
    // The IERS standard for era is
    //    era = 0.7790572732640 + 1.00273781191135448 * Tu
    // where
    //    Tu = JulianDateInUt1 - 2451545.0
    // However, you get much more precision if you make the following simplification
    //    era = a + (1 + b) * (JulianDayNumber + FractionOfDay - 2451545)
    //    era = a + (JulianDayNumber - 2451545) + FractionOfDay + b (JulianDayNumber - 2451545 + FractionOfDay)
    //    era = a + FractionOfDay + b (JulianDayNumber - 2451545 + FractionOfDay)
    // since (JulianDayNumber - 2451545) represents an integer number of revolutions which will be discarded anyway.
    const daysSinceJ2000 = dateUt1day - 2451545;
    const fractionOfDay = dateUt1sec / TimeConstants$1.SECONDS_PER_DAY;
    let era =
      0.779057273264 +
      fractionOfDay +
      0.00273781191135448 * (daysSinceJ2000 + fractionOfDay);
    era = (era % 1.0) * CesiumMath.TWO_PI;

    const earthRotation = Matrix3.fromRotationZ(era, rotation2Scratch);

    // pseudoFixed to ICRF
    const pfToIcrf = Matrix3.multiply(matrixQ, earthRotation, rotation1Scratch);

    // Compute pole wander matrix
    const cosxp = Math.cos(eop.xPoleWander);
    const cosyp = Math.cos(eop.yPoleWander);
    const sinxp = Math.sin(eop.xPoleWander);
    const sinyp = Math.sin(eop.yPoleWander);

    let ttt = dayTT - j2000ttDays + secondTT / TimeConstants$1.SECONDS_PER_DAY;
    ttt /= 36525.0;

    // approximate sp value in rad
    const sp = (-47.0e-6 * ttt * CesiumMath.RADIANS_PER_DEGREE) / 3600.0;
    const cossp = Math.cos(sp);
    const sinsp = Math.sin(sp);

    const fToPfMtx = rotation2Scratch;
    fToPfMtx[0] = cosxp * cossp;
    fToPfMtx[1] = cosxp * sinsp;
    fToPfMtx[2] = sinxp;
    fToPfMtx[3] = -cosyp * sinsp + sinyp * sinxp * cossp;
    fToPfMtx[4] = cosyp * cossp + sinyp * sinxp * sinsp;
    fToPfMtx[5] = -sinyp * cosxp;
    fToPfMtx[6] = -sinyp * sinsp - cosyp * sinxp * cossp;
    fToPfMtx[7] = sinyp * cossp - cosyp * sinxp * sinsp;
    fToPfMtx[8] = cosyp * cosxp;

    return Matrix3.multiply(pfToIcrf, fToPfMtx, result);
  };

  const pointToWindowCoordinatesTemp = new Cartesian4();

  /**
   * Transform a point from model coordinates to window coordinates.
   *
   * @param {Matrix4} modelViewProjectionMatrix The 4x4 model-view-projection matrix.
   * @param {Matrix4} viewportTransformation The 4x4 viewport transformation.
   * @param {Cartesian3} point The point to transform.
   * @param {Cartesian2} [result] The object onto which to store the result.
   * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if none was provided.
   */
  Transforms.pointToWindowCoordinates = function (
    modelViewProjectionMatrix,
    viewportTransformation,
    point,
    result
  ) {
    result = Transforms.pointToGLWindowCoordinates(
      modelViewProjectionMatrix,
      viewportTransformation,
      point,
      result
    );
    result.y = 2.0 * viewportTransformation[5] - result.y;
    return result;
  };

  /**
   * @private
   */
  Transforms.pointToGLWindowCoordinates = function (
    modelViewProjectionMatrix,
    viewportTransformation,
    point,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(modelViewProjectionMatrix)) {
      throw new DeveloperError("modelViewProjectionMatrix is required.");
    }

    if (!defined(viewportTransformation)) {
      throw new DeveloperError("viewportTransformation is required.");
    }

    if (!defined(point)) {
      throw new DeveloperError("point is required.");
    }
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Cartesian2();
    }

    const tmp = pointToWindowCoordinatesTemp;

    Matrix4.multiplyByVector(
      modelViewProjectionMatrix,
      Cartesian4.fromElements(point.x, point.y, point.z, 1, tmp),
      tmp
    );
    Cartesian4.multiplyByScalar(tmp, 1.0 / tmp.w, tmp);
    Matrix4.multiplyByVector(viewportTransformation, tmp, tmp);
    return Cartesian2.fromCartesian4(tmp, result);
  };

  const normalScratch$5 = new Cartesian3();
  const rightScratch$1 = new Cartesian3();
  const upScratch = new Cartesian3();

  /**
   * Transform a position and velocity to a rotation matrix.
   *
   * @param {Cartesian3} position The position to transform.
   * @param {Cartesian3} velocity The velocity vector to transform.
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
   * @param {Matrix3} [result] The object onto which to store the result.
   * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if none was provided.
   */
  Transforms.rotationMatrixFromPositionVelocity = function (
    position,
    velocity,
    ellipsoid,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(position)) {
      throw new DeveloperError("position is required.");
    }

    if (!defined(velocity)) {
      throw new DeveloperError("velocity is required.");
    }
    //>>includeEnd('debug');

    const normal = defaultValue(ellipsoid, Ellipsoid.WGS84).geodeticSurfaceNormal(
      position,
      normalScratch$5
    );
    let right = Cartesian3.cross(velocity, normal, rightScratch$1);

    if (Cartesian3.equalsEpsilon(right, Cartesian3.ZERO, CesiumMath.EPSILON6)) {
      right = Cartesian3.clone(Cartesian3.UNIT_X, right);
    }

    const up = Cartesian3.cross(right, velocity, upScratch);
    Cartesian3.normalize(up, up);
    Cartesian3.cross(velocity, up, right);
    Cartesian3.negate(right, right);
    Cartesian3.normalize(right, right);

    if (!defined(result)) {
      result = new Matrix3();
    }

    result[0] = velocity.x;
    result[1] = velocity.y;
    result[2] = velocity.z;
    result[3] = right.x;
    result[4] = right.y;
    result[5] = right.z;
    result[6] = up.x;
    result[7] = up.y;
    result[8] = up.z;

    return result;
  };

  const swizzleMatrix = new Matrix4(
    0.0,
    0.0,
    1.0,
    0.0,
    1.0,
    0.0,
    0.0,
    0.0,
    0.0,
    1.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    1.0
  );

  const scratchCartographic$i = new Cartographic();
  const scratchCartesian3Projection$1 = new Cartesian3();
  const scratchCenter$8 = new Cartesian3();
  const scratchRotation$2 = new Matrix3();
  const scratchFromENU = new Matrix4();
  const scratchToENU = new Matrix4();

  /**
   * @private
   */
  Transforms.basisTo2D = function (projection, matrix, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(projection)) {
      throw new DeveloperError("projection is required.");
    }
    if (!defined(matrix)) {
      throw new DeveloperError("matrix is required.");
    }
    if (!defined(result)) {
      throw new DeveloperError("result is required.");
    }
    //>>includeEnd('debug');

    const rtcCenter = Matrix4.getTranslation(matrix, scratchCenter$8);
    const ellipsoid = projection.ellipsoid;

    // Get the 2D Center
    const cartographic = ellipsoid.cartesianToCartographic(
      rtcCenter,
      scratchCartographic$i
    );
    const projectedPosition = projection.project(
      cartographic,
      scratchCartesian3Projection$1
    );
    Cartesian3.fromElements(
      projectedPosition.z,
      projectedPosition.x,
      projectedPosition.y,
      projectedPosition
    );

    // Assuming the instance are positioned in WGS84, invert the WGS84 transform to get the local transform and then convert to 2D
    const fromENU = Transforms.eastNorthUpToFixedFrame(
      rtcCenter,
      ellipsoid,
      scratchFromENU
    );
    const toENU = Matrix4.inverseTransformation(fromENU, scratchToENU);
    const rotation = Matrix4.getMatrix3(matrix, scratchRotation$2);
    const local = Matrix4.multiplyByMatrix3(toENU, rotation, result);
    Matrix4.multiply(swizzleMatrix, local, result); // Swap x, y, z for 2D
    Matrix4.setTranslation(result, projectedPosition, result); // Use the projected center

    return result;
  };

  /**
   * @private
   */
  Transforms.wgs84To2DModelMatrix = function (projection, center, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(projection)) {
      throw new DeveloperError("projection is required.");
    }
    if (!defined(center)) {
      throw new DeveloperError("center is required.");
    }
    if (!defined(result)) {
      throw new DeveloperError("result is required.");
    }
    //>>includeEnd('debug');

    const ellipsoid = projection.ellipsoid;

    const fromENU = Transforms.eastNorthUpToFixedFrame(
      center,
      ellipsoid,
      scratchFromENU
    );
    const toENU = Matrix4.inverseTransformation(fromENU, scratchToENU);

    const cartographic = ellipsoid.cartesianToCartographic(
      center,
      scratchCartographic$i
    );
    const projectedPosition = projection.project(
      cartographic,
      scratchCartesian3Projection$1
    );
    Cartesian3.fromElements(
      projectedPosition.z,
      projectedPosition.x,
      projectedPosition.y,
      projectedPosition
    );

    const translation = Matrix4.fromTranslation(
      projectedPosition,
      scratchFromENU
    );
    Matrix4.multiply(swizzleMatrix, toENU, result);
    Matrix4.multiply(translation, result, result);

    return result;
  };

  const scratchCart4 = new Cartesian4();
  /**
   * A plane tangent to the provided ellipsoid at the provided origin.
   * If origin is not on the surface of the ellipsoid, it's surface projection will be used.
   * If origin is at the center of the ellipsoid, an exception will be thrown.
   * @alias EllipsoidTangentPlane
   * @constructor
   *
   * @param {Cartesian3} origin The point on the surface of the ellipsoid where the tangent plane touches.
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid to use.
   *
   * @exception {DeveloperError} origin must not be at the center of the ellipsoid.
   */
  function EllipsoidTangentPlane(origin, ellipsoid) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("origin", origin);
    //>>includeEnd('debug');

    ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
    origin = ellipsoid.scaleToGeodeticSurface(origin);

    //>>includeStart('debug', pragmas.debug);
    if (!defined(origin)) {
      throw new DeveloperError(
        "origin must not be at the center of the ellipsoid."
      );
    }
    //>>includeEnd('debug');

    const eastNorthUp = Transforms.eastNorthUpToFixedFrame(origin, ellipsoid);
    this._ellipsoid = ellipsoid;
    this._origin = origin;
    this._xAxis = Cartesian3.fromCartesian4(
      Matrix4.getColumn(eastNorthUp, 0, scratchCart4)
    );
    this._yAxis = Cartesian3.fromCartesian4(
      Matrix4.getColumn(eastNorthUp, 1, scratchCart4)
    );

    const normal = Cartesian3.fromCartesian4(
      Matrix4.getColumn(eastNorthUp, 2, scratchCart4)
    );
    this._plane = Plane.fromPointNormal(origin, normal);
  }

  Object.defineProperties(EllipsoidTangentPlane.prototype, {
    /**
     * Gets the ellipsoid.
     * @memberof EllipsoidTangentPlane.prototype
     * @type {Ellipsoid}
     */
    ellipsoid: {
      get: function () {
        return this._ellipsoid;
      },
    },

    /**
     * Gets the origin.
     * @memberof EllipsoidTangentPlane.prototype
     * @type {Cartesian3}
     */
    origin: {
      get: function () {
        return this._origin;
      },
    },

    /**
     * Gets the plane which is tangent to the ellipsoid.
     * @memberof EllipsoidTangentPlane.prototype
     * @readonly
     * @type {Plane}
     */
    plane: {
      get: function () {
        return this._plane;
      },
    },

    /**
     * Gets the local X-axis (east) of the tangent plane.
     * @memberof EllipsoidTangentPlane.prototype
     * @readonly
     * @type {Cartesian3}
     */
    xAxis: {
      get: function () {
        return this._xAxis;
      },
    },

    /**
     * Gets the local Y-axis (north) of the tangent plane.
     * @memberof EllipsoidTangentPlane.prototype
     * @readonly
     * @type {Cartesian3}
     */
    yAxis: {
      get: function () {
        return this._yAxis;
      },
    },

    /**
     * Gets the local Z-axis (up) of the tangent plane.
     * @memberof EllipsoidTangentPlane.prototype
     * @readonly
     * @type {Cartesian3}
     */
    zAxis: {
      get: function () {
        return this._plane.normal;
      },
    },
  });

  const tmp = new AxisAlignedBoundingBox();
  /**
   * Creates a new instance from the provided ellipsoid and the center
   * point of the provided Cartesians.
   *
   * @param {Cartesian3[]} cartesians The list of positions surrounding the center point.
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid to use.
   * @returns {EllipsoidTangentPlane} The new instance of EllipsoidTangentPlane.
   */
  EllipsoidTangentPlane.fromPoints = function (cartesians, ellipsoid) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("cartesians", cartesians);
    //>>includeEnd('debug');

    const box = AxisAlignedBoundingBox.fromPoints(cartesians, tmp);
    return new EllipsoidTangentPlane(box.center, ellipsoid);
  };

  const scratchProjectPointOntoPlaneRay = new Ray();
  const scratchProjectPointOntoPlaneCartesian3 = new Cartesian3();

  /**
   * Computes the projection of the provided 3D position onto the 2D plane, radially outward from the {@link EllipsoidTangentPlane.ellipsoid} coordinate system origin.
   *
   * @param {Cartesian3} cartesian The point to project.
   * @param {Cartesian2} [result] The object onto which to store the result.
   * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if none was provided. Undefined if there is no intersection point
   */
  EllipsoidTangentPlane.prototype.projectPointOntoPlane = function (
    cartesian,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("cartesian", cartesian);
    //>>includeEnd('debug');

    const ray = scratchProjectPointOntoPlaneRay;
    ray.origin = cartesian;
    Cartesian3.normalize(cartesian, ray.direction);

    let intersectionPoint = IntersectionTests.rayPlane(
      ray,
      this._plane,
      scratchProjectPointOntoPlaneCartesian3
    );
    if (!defined(intersectionPoint)) {
      Cartesian3.negate(ray.direction, ray.direction);
      intersectionPoint = IntersectionTests.rayPlane(
        ray,
        this._plane,
        scratchProjectPointOntoPlaneCartesian3
      );
    }

    if (defined(intersectionPoint)) {
      const v = Cartesian3.subtract(
        intersectionPoint,
        this._origin,
        intersectionPoint
      );
      const x = Cartesian3.dot(this._xAxis, v);
      const y = Cartesian3.dot(this._yAxis, v);

      if (!defined(result)) {
        return new Cartesian2(x, y);
      }
      result.x = x;
      result.y = y;
      return result;
    }
    return undefined;
  };

  /**
   * Computes the projection of the provided 3D positions onto the 2D plane (where possible), radially outward from the global origin.
   * The resulting array may be shorter than the input array - if a single projection is impossible it will not be included.
   *
   * @see EllipsoidTangentPlane.projectPointOntoPlane
   *
   * @param {Cartesian3[]} cartesians The array of points to project.
   * @param {Cartesian2[]} [result] The array of Cartesian2 instances onto which to store results.
   * @returns {Cartesian2[]} The modified result parameter or a new array of Cartesian2 instances if none was provided.
   */
  EllipsoidTangentPlane.prototype.projectPointsOntoPlane = function (
    cartesians,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("cartesians", cartesians);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = [];
    }

    let count = 0;
    const length = cartesians.length;
    for (let i = 0; i < length; i++) {
      const p = this.projectPointOntoPlane(cartesians[i], result[count]);
      if (defined(p)) {
        result[count] = p;
        count++;
      }
    }
    result.length = count;
    return result;
  };

  /**
   * Computes the projection of the provided 3D position onto the 2D plane, along the plane normal.
   *
   * @param {Cartesian3} cartesian The point to project.
   * @param {Cartesian2} [result] The object onto which to store the result.
   * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if none was provided.
   */
  EllipsoidTangentPlane.prototype.projectPointToNearestOnPlane = function (
    cartesian,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("cartesian", cartesian);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Cartesian2();
    }

    const ray = scratchProjectPointOntoPlaneRay;
    ray.origin = cartesian;
    Cartesian3.clone(this._plane.normal, ray.direction);

    let intersectionPoint = IntersectionTests.rayPlane(
      ray,
      this._plane,
      scratchProjectPointOntoPlaneCartesian3
    );
    if (!defined(intersectionPoint)) {
      Cartesian3.negate(ray.direction, ray.direction);
      intersectionPoint = IntersectionTests.rayPlane(
        ray,
        this._plane,
        scratchProjectPointOntoPlaneCartesian3
      );
    }

    const v = Cartesian3.subtract(
      intersectionPoint,
      this._origin,
      intersectionPoint
    );
    const x = Cartesian3.dot(this._xAxis, v);
    const y = Cartesian3.dot(this._yAxis, v);

    result.x = x;
    result.y = y;
    return result;
  };

  /**
   * Computes the projection of the provided 3D positions onto the 2D plane, along the plane normal.
   *
   * @see EllipsoidTangentPlane.projectPointToNearestOnPlane
   *
   * @param {Cartesian3[]} cartesians The array of points to project.
   * @param {Cartesian2[]} [result] The array of Cartesian2 instances onto which to store results.
   * @returns {Cartesian2[]} The modified result parameter or a new array of Cartesian2 instances if none was provided. This will have the same length as <code>cartesians</code>.
   */
  EllipsoidTangentPlane.prototype.projectPointsToNearestOnPlane = function (
    cartesians,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("cartesians", cartesians);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = [];
    }

    const length = cartesians.length;
    result.length = length;
    for (let i = 0; i < length; i++) {
      result[i] = this.projectPointToNearestOnPlane(cartesians[i], result[i]);
    }
    return result;
  };

  const projectPointsOntoEllipsoidScratch = new Cartesian3();
  /**
   * Computes the projection of the provided 2D position onto the 3D ellipsoid.
   *
   * @param {Cartesian2} cartesian The points to project.
   * @param {Cartesian3} [result] The Cartesian3 instance to store result.
   * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
   */
  EllipsoidTangentPlane.prototype.projectPointOntoEllipsoid = function (
    cartesian,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("cartesian", cartesian);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Cartesian3();
    }

    const ellipsoid = this._ellipsoid;
    const origin = this._origin;
    const xAxis = this._xAxis;
    const yAxis = this._yAxis;
    const tmp = projectPointsOntoEllipsoidScratch;

    Cartesian3.multiplyByScalar(xAxis, cartesian.x, tmp);
    result = Cartesian3.add(origin, tmp, result);
    Cartesian3.multiplyByScalar(yAxis, cartesian.y, tmp);
    Cartesian3.add(result, tmp, result);
    ellipsoid.scaleToGeocentricSurface(result, result);

    return result;
  };

  /**
   * Computes the projection of the provided 2D positions onto the 3D ellipsoid.
   *
   * @param {Cartesian2[]} cartesians The array of points to project.
   * @param {Cartesian3[]} [result] The array of Cartesian3 instances onto which to store results.
   * @returns {Cartesian3[]} The modified result parameter or a new array of Cartesian3 instances if none was provided.
   */
  EllipsoidTangentPlane.prototype.projectPointsOntoEllipsoid = function (
    cartesians,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("cartesians", cartesians);
    //>>includeEnd('debug');

    const length = cartesians.length;
    if (!defined(result)) {
      result = new Array(length);
    } else {
      result.length = length;
    }

    for (let i = 0; i < length; ++i) {
      result[i] = this.projectPointOntoEllipsoid(cartesians[i], result[i]);
    }

    return result;
  };

  /**
   * Creates an instance of an OrientedBoundingBox.
   * An OrientedBoundingBox of some object is a closed and convex cuboid. It can provide a tighter bounding volume than {@link BoundingSphere} or {@link AxisAlignedBoundingBox} in many cases.
   * @alias OrientedBoundingBox
   * @constructor
   *
   * @param {Cartesian3} [center=Cartesian3.ZERO] The center of the box.
   * @param {Matrix3} [halfAxes=Matrix3.ZERO] The three orthogonal half-axes of the bounding box.
   *                                          Equivalently, the transformation matrix, to rotate and scale a 0x0x0
   *                                          cube centered at the origin.
   *
   *
   * @example
   * // Create an OrientedBoundingBox using a transformation matrix, a position where the box will be translated, and a scale.
   * const center = new Cesium.Cartesian3(1.0, 0.0, 0.0);
   * const halfAxes = Cesium.Matrix3.fromScale(new Cesium.Cartesian3(1.0, 3.0, 2.0), new Cesium.Matrix3());
   *
   * const obb = new Cesium.OrientedBoundingBox(center, halfAxes);
   *
   * @see BoundingSphere
   * @see BoundingRectangle
   */
  function OrientedBoundingBox(center, halfAxes) {
    /**
     * The center of the box.
     * @type {Cartesian3}
     * @default {@link Cartesian3.ZERO}
     */
    this.center = Cartesian3.clone(defaultValue(center, Cartesian3.ZERO));
    /**
     * The transformation matrix, to rotate the box to the right position.
     * @type {Matrix3}
     * @default {@link Matrix3.ZERO}
     */
    this.halfAxes = Matrix3.clone(defaultValue(halfAxes, Matrix3.ZERO));
  }

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  OrientedBoundingBox.packedLength =
    Cartesian3.packedLength + Matrix3.packedLength;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {OrientedBoundingBox} 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
   */
  OrientedBoundingBox.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    Cartesian3.pack(value.center, array, startingIndex);
    Matrix3.pack(value.halfAxes, array, startingIndex + Cartesian3.packedLength);

    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 {OrientedBoundingBox} [result] The object into which to store the result.
   * @returns {OrientedBoundingBox} The modified result parameter or a new OrientedBoundingBox instance if one was not provided.
   */
  OrientedBoundingBox.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    if (!defined(result)) {
      result = new OrientedBoundingBox();
    }

    Cartesian3.unpack(array, startingIndex, result.center);
    Matrix3.unpack(
      array,
      startingIndex + Cartesian3.packedLength,
      result.halfAxes
    );
    return result;
  };

  const scratchCartesian1$8 = new Cartesian3();
  const scratchCartesian2$b = new Cartesian3();
  const scratchCartesian3$c = new Cartesian3();
  const scratchCartesian4$6 = new Cartesian3();
  const scratchCartesian5$2 = new Cartesian3();
  const scratchCartesian6$1 = new Cartesian3();
  const scratchCovarianceResult = new Matrix3();
  const scratchEigenResult = {
    unitary: new Matrix3(),
    diagonal: new Matrix3(),
  };

  /**
   * Computes an instance of an OrientedBoundingBox of the given positions.
   * This is an implementation of Stefan Gottschalk's Collision Queries using Oriented Bounding Boxes solution (PHD thesis).
   * Reference: http://gamma.cs.unc.edu/users/gottschalk/main.pdf
   *
   * @param {Cartesian3[]} [positions] List of {@link Cartesian3} points that the bounding box will enclose.
   * @param {OrientedBoundingBox} [result] The object onto which to store the result.
   * @returns {OrientedBoundingBox} The modified result parameter or a new OrientedBoundingBox instance if one was not provided.
   *
   * @example
   * // Compute an object oriented bounding box enclosing two points.
   * const box = Cesium.OrientedBoundingBox.fromPoints([new Cesium.Cartesian3(2, 0, 0), new Cesium.Cartesian3(-2, 0, 0)]);
   */
  OrientedBoundingBox.fromPoints = function (positions, result) {
    if (!defined(result)) {
      result = new OrientedBoundingBox();
    }

    if (!defined(positions) || positions.length === 0) {
      result.halfAxes = Matrix3.ZERO;
      result.center = Cartesian3.ZERO;
      return result;
    }

    let i;
    const length = positions.length;

    const meanPoint = Cartesian3.clone(positions[0], scratchCartesian1$8);
    for (i = 1; i < length; i++) {
      Cartesian3.add(meanPoint, positions[i], meanPoint);
    }
    const invLength = 1.0 / length;
    Cartesian3.multiplyByScalar(meanPoint, invLength, meanPoint);

    let exx = 0.0;
    let exy = 0.0;
    let exz = 0.0;
    let eyy = 0.0;
    let eyz = 0.0;
    let ezz = 0.0;
    let p;

    for (i = 0; i < length; i++) {
      p = Cartesian3.subtract(positions[i], meanPoint, scratchCartesian2$b);
      exx += p.x * p.x;
      exy += p.x * p.y;
      exz += p.x * p.z;
      eyy += p.y * p.y;
      eyz += p.y * p.z;
      ezz += p.z * p.z;
    }

    exx *= invLength;
    exy *= invLength;
    exz *= invLength;
    eyy *= invLength;
    eyz *= invLength;
    ezz *= invLength;

    const covarianceMatrix = scratchCovarianceResult;
    covarianceMatrix[0] = exx;
    covarianceMatrix[1] = exy;
    covarianceMatrix[2] = exz;
    covarianceMatrix[3] = exy;
    covarianceMatrix[4] = eyy;
    covarianceMatrix[5] = eyz;
    covarianceMatrix[6] = exz;
    covarianceMatrix[7] = eyz;
    covarianceMatrix[8] = ezz;

    const eigenDecomposition = Matrix3.computeEigenDecomposition(
      covarianceMatrix,
      scratchEigenResult
    );
    const rotation = Matrix3.clone(eigenDecomposition.unitary, result.halfAxes);

    let v1 = Matrix3.getColumn(rotation, 0, scratchCartesian4$6);
    let v2 = Matrix3.getColumn(rotation, 1, scratchCartesian5$2);
    let v3 = Matrix3.getColumn(rotation, 2, scratchCartesian6$1);

    let u1 = -Number.MAX_VALUE;
    let u2 = -Number.MAX_VALUE;
    let u3 = -Number.MAX_VALUE;
    let l1 = Number.MAX_VALUE;
    let l2 = Number.MAX_VALUE;
    let l3 = Number.MAX_VALUE;

    for (i = 0; i < length; i++) {
      p = positions[i];
      u1 = Math.max(Cartesian3.dot(v1, p), u1);
      u2 = Math.max(Cartesian3.dot(v2, p), u2);
      u3 = Math.max(Cartesian3.dot(v3, p), u3);

      l1 = Math.min(Cartesian3.dot(v1, p), l1);
      l2 = Math.min(Cartesian3.dot(v2, p), l2);
      l3 = Math.min(Cartesian3.dot(v3, p), l3);
    }

    v1 = Cartesian3.multiplyByScalar(v1, 0.5 * (l1 + u1), v1);
    v2 = Cartesian3.multiplyByScalar(v2, 0.5 * (l2 + u2), v2);
    v3 = Cartesian3.multiplyByScalar(v3, 0.5 * (l3 + u3), v3);

    const center = Cartesian3.add(v1, v2, result.center);
    Cartesian3.add(center, v3, center);

    const scale = scratchCartesian3$c;
    scale.x = u1 - l1;
    scale.y = u2 - l2;
    scale.z = u3 - l3;
    Cartesian3.multiplyByScalar(scale, 0.5, scale);
    Matrix3.multiplyByScale(result.halfAxes, scale, result.halfAxes);

    return result;
  };

  const scratchOffset = new Cartesian3();
  const scratchScale$4 = new Cartesian3();
  function fromPlaneExtents(
    planeOrigin,
    planeXAxis,
    planeYAxis,
    planeZAxis,
    minimumX,
    maximumX,
    minimumY,
    maximumY,
    minimumZ,
    maximumZ,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (
      !defined(minimumX) ||
      !defined(maximumX) ||
      !defined(minimumY) ||
      !defined(maximumY) ||
      !defined(minimumZ) ||
      !defined(maximumZ)
    ) {
      throw new DeveloperError(
        "all extents (minimum/maximum X/Y/Z) are required."
      );
    }
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new OrientedBoundingBox();
    }

    const halfAxes = result.halfAxes;
    Matrix3.setColumn(halfAxes, 0, planeXAxis, halfAxes);
    Matrix3.setColumn(halfAxes, 1, planeYAxis, halfAxes);
    Matrix3.setColumn(halfAxes, 2, planeZAxis, halfAxes);

    let centerOffset = scratchOffset;
    centerOffset.x = (minimumX + maximumX) / 2.0;
    centerOffset.y = (minimumY + maximumY) / 2.0;
    centerOffset.z = (minimumZ + maximumZ) / 2.0;

    const scale = scratchScale$4;
    scale.x = (maximumX - minimumX) / 2.0;
    scale.y = (maximumY - minimumY) / 2.0;
    scale.z = (maximumZ - minimumZ) / 2.0;

    const center = result.center;
    centerOffset = Matrix3.multiplyByVector(halfAxes, centerOffset, centerOffset);
    Cartesian3.add(planeOrigin, centerOffset, center);
    Matrix3.multiplyByScale(halfAxes, scale, halfAxes);

    return result;
  }

  const scratchRectangleCenterCartographic = new Cartographic();
  const scratchRectangleCenter = new Cartesian3();
  const scratchPerimeterCartographicNC = new Cartographic();
  const scratchPerimeterCartographicNW = new Cartographic();
  const scratchPerimeterCartographicCW = new Cartographic();
  const scratchPerimeterCartographicSW = new Cartographic();
  const scratchPerimeterCartographicSC = new Cartographic();
  const scratchPerimeterCartesianNC = new Cartesian3();
  const scratchPerimeterCartesianNW = new Cartesian3();
  const scratchPerimeterCartesianCW = new Cartesian3();
  const scratchPerimeterCartesianSW = new Cartesian3();
  const scratchPerimeterCartesianSC = new Cartesian3();
  const scratchPerimeterProjectedNC = new Cartesian2();
  const scratchPerimeterProjectedNW = new Cartesian2();
  const scratchPerimeterProjectedCW = new Cartesian2();
  const scratchPerimeterProjectedSW = new Cartesian2();
  const scratchPerimeterProjectedSC = new Cartesian2();

  const scratchPlaneOrigin = new Cartesian3();
  const scratchPlaneNormal$1 = new Cartesian3();
  const scratchPlaneXAxis = new Cartesian3();
  const scratchHorizonCartesian = new Cartesian3();
  const scratchHorizonProjected = new Cartesian2();
  const scratchMaxY = new Cartesian3();
  const scratchMinY = new Cartesian3();
  const scratchZ = new Cartesian3();
  const scratchPlane$2 = new Plane(Cartesian3.UNIT_X, 0.0);

  /**
   * Computes an OrientedBoundingBox that bounds a {@link Rectangle} on the surface of an {@link Ellipsoid}.
   * There are no guarantees about the orientation of the bounding box.
   *
   * @param {Rectangle} rectangle The cartographic rectangle on the surface of the ellipsoid.
   * @param {Number} [minimumHeight=0.0] The minimum height (elevation) within the tile.
   * @param {Number} [maximumHeight=0.0] The maximum height (elevation) within the tile.
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the rectangle is defined.
   * @param {OrientedBoundingBox} [result] The object onto which to store the result.
   * @returns {OrientedBoundingBox} The modified result parameter or a new OrientedBoundingBox instance if none was provided.
   *
   * @exception {DeveloperError} rectangle.width must be between 0 and pi.
   * @exception {DeveloperError} rectangle.height must be between 0 and pi.
   * @exception {DeveloperError} ellipsoid must be an ellipsoid of revolution (<code>radii.x == radii.y</code>)
   */
  OrientedBoundingBox.fromRectangle = function (
    rectangle,
    minimumHeight,
    maximumHeight,
    ellipsoid,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(rectangle)) {
      throw new DeveloperError("rectangle is required");
    }
    if (rectangle.width < 0.0 || rectangle.width > CesiumMath.TWO_PI) {
      throw new DeveloperError("Rectangle width must be between 0 and 2*pi");
    }
    if (rectangle.height < 0.0 || rectangle.height > CesiumMath.PI) {
      throw new DeveloperError("Rectangle height must be between 0 and pi");
    }
    if (
      defined(ellipsoid) &&
      !CesiumMath.equalsEpsilon(
        ellipsoid.radii.x,
        ellipsoid.radii.y,
        CesiumMath.EPSILON15
      )
    ) {
      throw new DeveloperError(
        "Ellipsoid must be an ellipsoid of revolution (radii.x == radii.y)"
      );
    }
    //>>includeEnd('debug');

    minimumHeight = defaultValue(minimumHeight, 0.0);
    maximumHeight = defaultValue(maximumHeight, 0.0);
    ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);

    let minX, maxX, minY, maxY, minZ, maxZ, plane;

    if (rectangle.width <= CesiumMath.PI) {
      // The bounding box will be aligned with the tangent plane at the center of the rectangle.
      const tangentPointCartographic = Rectangle.center(
        rectangle,
        scratchRectangleCenterCartographic
      );
      const tangentPoint = ellipsoid.cartographicToCartesian(
        tangentPointCartographic,
        scratchRectangleCenter
      );
      const tangentPlane = new EllipsoidTangentPlane(tangentPoint, ellipsoid);
      plane = tangentPlane.plane;

      // If the rectangle spans the equator, CW is instead aligned with the equator (because it sticks out the farthest at the equator).
      const lonCenter = tangentPointCartographic.longitude;
      const latCenter =
        rectangle.south < 0.0 && rectangle.north > 0.0
          ? 0.0
          : tangentPointCartographic.latitude;

      // Compute XY extents using the rectangle at maximum height
      const perimeterCartographicNC = Cartographic.fromRadians(
        lonCenter,
        rectangle.north,
        maximumHeight,
        scratchPerimeterCartographicNC
      );
      const perimeterCartographicNW = Cartographic.fromRadians(
        rectangle.west,
        rectangle.north,
        maximumHeight,
        scratchPerimeterCartographicNW
      );
      const perimeterCartographicCW = Cartographic.fromRadians(
        rectangle.west,
        latCenter,
        maximumHeight,
        scratchPerimeterCartographicCW
      );
      const perimeterCartographicSW = Cartographic.fromRadians(
        rectangle.west,
        rectangle.south,
        maximumHeight,
        scratchPerimeterCartographicSW
      );
      const perimeterCartographicSC = Cartographic.fromRadians(
        lonCenter,
        rectangle.south,
        maximumHeight,
        scratchPerimeterCartographicSC
      );

      const perimeterCartesianNC = ellipsoid.cartographicToCartesian(
        perimeterCartographicNC,
        scratchPerimeterCartesianNC
      );
      let perimeterCartesianNW = ellipsoid.cartographicToCartesian(
        perimeterCartographicNW,
        scratchPerimeterCartesianNW
      );
      const perimeterCartesianCW = ellipsoid.cartographicToCartesian(
        perimeterCartographicCW,
        scratchPerimeterCartesianCW
      );
      let perimeterCartesianSW = ellipsoid.cartographicToCartesian(
        perimeterCartographicSW,
        scratchPerimeterCartesianSW
      );
      const perimeterCartesianSC = ellipsoid.cartographicToCartesian(
        perimeterCartographicSC,
        scratchPerimeterCartesianSC
      );

      const perimeterProjectedNC = tangentPlane.projectPointToNearestOnPlane(
        perimeterCartesianNC,
        scratchPerimeterProjectedNC
      );
      const perimeterProjectedNW = tangentPlane.projectPointToNearestOnPlane(
        perimeterCartesianNW,
        scratchPerimeterProjectedNW
      );
      const perimeterProjectedCW = tangentPlane.projectPointToNearestOnPlane(
        perimeterCartesianCW,
        scratchPerimeterProjectedCW
      );
      const perimeterProjectedSW = tangentPlane.projectPointToNearestOnPlane(
        perimeterCartesianSW,
        scratchPerimeterProjectedSW
      );
      const perimeterProjectedSC = tangentPlane.projectPointToNearestOnPlane(
        perimeterCartesianSC,
        scratchPerimeterProjectedSC
      );

      minX = Math.min(
        perimeterProjectedNW.x,
        perimeterProjectedCW.x,
        perimeterProjectedSW.x
      );
      maxX = -minX; // symmetrical

      maxY = Math.max(perimeterProjectedNW.y, perimeterProjectedNC.y);
      minY = Math.min(perimeterProjectedSW.y, perimeterProjectedSC.y);

      // Compute minimum Z using the rectangle at minimum height, since it will be deeper than the maximum height
      perimeterCartographicNW.height = perimeterCartographicSW.height = minimumHeight;
      perimeterCartesianNW = ellipsoid.cartographicToCartesian(
        perimeterCartographicNW,
        scratchPerimeterCartesianNW
      );
      perimeterCartesianSW = ellipsoid.cartographicToCartesian(
        perimeterCartographicSW,
        scratchPerimeterCartesianSW
      );

      minZ = Math.min(
        Plane.getPointDistance(plane, perimeterCartesianNW),
        Plane.getPointDistance(plane, perimeterCartesianSW)
      );
      maxZ = maximumHeight; // Since the tangent plane touches the surface at height = 0, this is okay

      return fromPlaneExtents(
        tangentPlane.origin,
        tangentPlane.xAxis,
        tangentPlane.yAxis,
        tangentPlane.zAxis,
        minX,
        maxX,
        minY,
        maxY,
        minZ,
        maxZ,
        result
      );
    }

    // Handle the case where rectangle width is greater than PI (wraps around more than half the ellipsoid).
    const fullyAboveEquator = rectangle.south > 0.0;
    const fullyBelowEquator = rectangle.north < 0.0;
    const latitudeNearestToEquator = fullyAboveEquator
      ? rectangle.south
      : fullyBelowEquator
      ? rectangle.north
      : 0.0;
    const centerLongitude = Rectangle.center(
      rectangle,
      scratchRectangleCenterCartographic
    ).longitude;

    // Plane is located at the rectangle's center longitude and the rectangle's latitude that is closest to the equator. It rotates around the Z axis.
    // This results in a better fit than the obb approach for smaller rectangles, which orients with the rectangle's center normal.
    const planeOrigin = Cartesian3.fromRadians(
      centerLongitude,
      latitudeNearestToEquator,
      maximumHeight,
      ellipsoid,
      scratchPlaneOrigin
    );
    planeOrigin.z = 0.0; // center the plane on the equator to simpify plane normal calculation
    const isPole =
      Math.abs(planeOrigin.x) < CesiumMath.EPSILON10 &&
      Math.abs(planeOrigin.y) < CesiumMath.EPSILON10;
    const planeNormal = !isPole
      ? Cartesian3.normalize(planeOrigin, scratchPlaneNormal$1)
      : Cartesian3.UNIT_X;
    const planeYAxis = Cartesian3.UNIT_Z;
    const planeXAxis = Cartesian3.cross(
      planeNormal,
      planeYAxis,
      scratchPlaneXAxis
    );
    plane = Plane.fromPointNormal(planeOrigin, planeNormal, scratchPlane$2);

    // Get the horizon point relative to the center. This will be the farthest extent in the plane's X dimension.
    const horizonCartesian = Cartesian3.fromRadians(
      centerLongitude + CesiumMath.PI_OVER_TWO,
      latitudeNearestToEquator,
      maximumHeight,
      ellipsoid,
      scratchHorizonCartesian
    );
    maxX = Cartesian3.dot(
      Plane.projectPointOntoPlane(
        plane,
        horizonCartesian,
        scratchHorizonProjected
      ),
      planeXAxis
    );
    minX = -maxX; // symmetrical

    // Get the min and max Y, using the height that will give the largest extent
    maxY = Cartesian3.fromRadians(
      0.0,
      rectangle.north,
      fullyBelowEquator ? minimumHeight : maximumHeight,
      ellipsoid,
      scratchMaxY
    ).z;
    minY = Cartesian3.fromRadians(
      0.0,
      rectangle.south,
      fullyAboveEquator ? minimumHeight : maximumHeight,
      ellipsoid,
      scratchMinY
    ).z;

    const farZ = Cartesian3.fromRadians(
      rectangle.east,
      latitudeNearestToEquator,
      maximumHeight,
      ellipsoid,
      scratchZ
    );
    minZ = Plane.getPointDistance(plane, farZ);
    maxZ = 0.0; // plane origin starts at maxZ already

    // min and max are local to the plane axes
    return fromPlaneExtents(
      planeOrigin,
      planeXAxis,
      planeYAxis,
      planeNormal,
      minX,
      maxX,
      minY,
      maxY,
      minZ,
      maxZ,
      result
    );
  };

  /**
   * Computes an OrientedBoundingBox that bounds an affine transformation.
   *
   * @param {Matrix4} transformation The affine transformation.
   * @param {OrientedBoundingBox} [result] The object onto which to store the result.
   * @returns {OrientedBoundingBox} The modified result parameter or a new OrientedBoundingBox instance if none was provided.
   */
  OrientedBoundingBox.fromTransformation = function (transformation, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("transformation", transformation);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new OrientedBoundingBox();
    }

    result.center = Matrix4.getTranslation(transformation, result.center);
    result.halfAxes = Matrix4.getMatrix3(transformation, result.halfAxes);
    result.halfAxes = Matrix3.multiplyByScalar(
      result.halfAxes,
      0.5,
      result.halfAxes
    );
    return result;
  };

  /**
   * Duplicates a OrientedBoundingBox instance.
   *
   * @param {OrientedBoundingBox} box The bounding box to duplicate.
   * @param {OrientedBoundingBox} [result] The object onto which to store the result.
   * @returns {OrientedBoundingBox} The modified result parameter or a new OrientedBoundingBox instance if none was provided. (Returns undefined if box is undefined)
   */
  OrientedBoundingBox.clone = function (box, result) {
    if (!defined(box)) {
      return undefined;
    }

    if (!defined(result)) {
      return new OrientedBoundingBox(box.center, box.halfAxes);
    }

    Cartesian3.clone(box.center, result.center);
    Matrix3.clone(box.halfAxes, result.halfAxes);

    return result;
  };

  /**
   * Determines which side of a plane the oriented bounding box is located.
   *
   * @param {OrientedBoundingBox} box The oriented bounding box to test.
   * @param {Plane} plane The plane to test against.
   * @returns {Intersect} {@link Intersect.INSIDE} if the entire box is on the side of the plane
   *                      the normal is pointing, {@link Intersect.OUTSIDE} if the entire box is
   *                      on the opposite side, and {@link Intersect.INTERSECTING} if the box
   *                      intersects the plane.
   */
  OrientedBoundingBox.intersectPlane = function (box, plane) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(box)) {
      throw new DeveloperError("box is required.");
    }

    if (!defined(plane)) {
      throw new DeveloperError("plane is required.");
    }
    //>>includeEnd('debug');

    const center = box.center;
    const normal = plane.normal;
    const halfAxes = box.halfAxes;
    const normalX = normal.x,
      normalY = normal.y,
      normalZ = normal.z;
    // plane is used as if it is its normal; the first three components are assumed to be normalized
    const radEffective =
      Math.abs(
        normalX * halfAxes[Matrix3.COLUMN0ROW0] +
          normalY * halfAxes[Matrix3.COLUMN0ROW1] +
          normalZ * halfAxes[Matrix3.COLUMN0ROW2]
      ) +
      Math.abs(
        normalX * halfAxes[Matrix3.COLUMN1ROW0] +
          normalY * halfAxes[Matrix3.COLUMN1ROW1] +
          normalZ * halfAxes[Matrix3.COLUMN1ROW2]
      ) +
      Math.abs(
        normalX * halfAxes[Matrix3.COLUMN2ROW0] +
          normalY * halfAxes[Matrix3.COLUMN2ROW1] +
          normalZ * halfAxes[Matrix3.COLUMN2ROW2]
      );
    const distanceToPlane = Cartesian3.dot(normal, center) + plane.distance;

    if (distanceToPlane <= -radEffective) {
      // The entire box is on the negative side of the plane normal
      return Intersect$1.OUTSIDE;
    } else if (distanceToPlane >= radEffective) {
      // The entire box is on the positive side of the plane normal
      return Intersect$1.INSIDE;
    }
    return Intersect$1.INTERSECTING;
  };

  const scratchCartesianU = new Cartesian3();
  const scratchCartesianV = new Cartesian3();
  const scratchCartesianW = new Cartesian3();
  const scratchValidAxis2 = new Cartesian3();
  const scratchValidAxis3 = new Cartesian3();
  const scratchPPrime = new Cartesian3();

  /**
   * Computes the estimated distance squared from the closest point on a bounding box to a point.
   *
   * @param {OrientedBoundingBox} box The box.
   * @param {Cartesian3} cartesian The point
   * @returns {Number} The distance squared from the oriented bounding box to the point. Returns 0 if the point is inside the box.
   *
   * @example
   * // Sort bounding boxes from back to front
   * boxes.sort(function(a, b) {
   *     return Cesium.OrientedBoundingBox.distanceSquaredTo(b, camera.positionWC) - Cesium.OrientedBoundingBox.distanceSquaredTo(a, camera.positionWC);
   * });
   */
  OrientedBoundingBox.distanceSquaredTo = function (box, cartesian) {
    // See Geometric Tools for Computer Graphics 10.4.2

    //>>includeStart('debug', pragmas.debug);
    if (!defined(box)) {
      throw new DeveloperError("box is required.");
    }
    if (!defined(cartesian)) {
      throw new DeveloperError("cartesian is required.");
    }
    //>>includeEnd('debug');

    const offset = Cartesian3.subtract(cartesian, box.center, scratchOffset);

    const halfAxes = box.halfAxes;
    let u = Matrix3.getColumn(halfAxes, 0, scratchCartesianU);
    let v = Matrix3.getColumn(halfAxes, 1, scratchCartesianV);
    let w = Matrix3.getColumn(halfAxes, 2, scratchCartesianW);

    const uHalf = Cartesian3.magnitude(u);
    const vHalf = Cartesian3.magnitude(v);
    const wHalf = Cartesian3.magnitude(w);

    let uValid = true;
    let vValid = true;
    let wValid = true;

    if (uHalf > 0) {
      Cartesian3.divideByScalar(u, uHalf, u);
    } else {
      uValid = false;
    }

    if (vHalf > 0) {
      Cartesian3.divideByScalar(v, vHalf, v);
    } else {
      vValid = false;
    }

    if (wHalf > 0) {
      Cartesian3.divideByScalar(w, wHalf, w);
    } else {
      wValid = false;
    }

    const numberOfDegenerateAxes = !uValid + !vValid + !wValid;
    let validAxis1;
    let validAxis2;
    let validAxis3;

    if (numberOfDegenerateAxes === 1) {
      let degenerateAxis = u;
      validAxis1 = v;
      validAxis2 = w;
      if (!vValid) {
        degenerateAxis = v;
        validAxis1 = u;
      } else if (!wValid) {
        degenerateAxis = w;
        validAxis2 = u;
      }

      validAxis3 = Cartesian3.cross(validAxis1, validAxis2, scratchValidAxis3);

      if (degenerateAxis === u) {
        u = validAxis3;
      } else if (degenerateAxis === v) {
        v = validAxis3;
      } else if (degenerateAxis === w) {
        w = validAxis3;
      }
    } else if (numberOfDegenerateAxes === 2) {
      validAxis1 = u;
      if (vValid) {
        validAxis1 = v;
      } else if (wValid) {
        validAxis1 = w;
      }

      let crossVector = Cartesian3.UNIT_Y;
      if (crossVector.equalsEpsilon(validAxis1, CesiumMath.EPSILON3)) {
        crossVector = Cartesian3.UNIT_X;
      }

      validAxis2 = Cartesian3.cross(validAxis1, crossVector, scratchValidAxis2);
      Cartesian3.normalize(validAxis2, validAxis2);
      validAxis3 = Cartesian3.cross(validAxis1, validAxis2, scratchValidAxis3);
      Cartesian3.normalize(validAxis3, validAxis3);

      if (validAxis1 === u) {
        v = validAxis2;
        w = validAxis3;
      } else if (validAxis1 === v) {
        w = validAxis2;
        u = validAxis3;
      } else if (validAxis1 === w) {
        u = validAxis2;
        v = validAxis3;
      }
    } else if (numberOfDegenerateAxes === 3) {
      u = Cartesian3.UNIT_X;
      v = Cartesian3.UNIT_Y;
      w = Cartesian3.UNIT_Z;
    }

    const pPrime = scratchPPrime;
    pPrime.x = Cartesian3.dot(offset, u);
    pPrime.y = Cartesian3.dot(offset, v);
    pPrime.z = Cartesian3.dot(offset, w);

    let distanceSquared = 0.0;
    let d;

    if (pPrime.x < -uHalf) {
      d = pPrime.x + uHalf;
      distanceSquared += d * d;
    } else if (pPrime.x > uHalf) {
      d = pPrime.x - uHalf;
      distanceSquared += d * d;
    }

    if (pPrime.y < -vHalf) {
      d = pPrime.y + vHalf;
      distanceSquared += d * d;
    } else if (pPrime.y > vHalf) {
      d = pPrime.y - vHalf;
      distanceSquared += d * d;
    }

    if (pPrime.z < -wHalf) {
      d = pPrime.z + wHalf;
      distanceSquared += d * d;
    } else if (pPrime.z > wHalf) {
      d = pPrime.z - wHalf;
      distanceSquared += d * d;
    }

    return distanceSquared;
  };

  const scratchCorner = new Cartesian3();
  const scratchToCenter$1 = new Cartesian3();

  /**
   * The distances calculated by the vector from the center of the bounding box to position projected onto direction.
   * <br>
   * 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 box.
   *
   * @param {OrientedBoundingBox} box The bounding box 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 box from position in direction.
   */
  OrientedBoundingBox.computePlaneDistances = function (
    box,
    position,
    direction,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(box)) {
      throw new DeveloperError("box is required.");
    }

    if (!defined(position)) {
      throw new DeveloperError("position is required.");
    }

    if (!defined(direction)) {
      throw new DeveloperError("direction is required.");
    }
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Interval();
    }

    let minDist = Number.POSITIVE_INFINITY;
    let maxDist = Number.NEGATIVE_INFINITY;

    const center = box.center;
    const halfAxes = box.halfAxes;

    const u = Matrix3.getColumn(halfAxes, 0, scratchCartesianU);
    const v = Matrix3.getColumn(halfAxes, 1, scratchCartesianV);
    const w = Matrix3.getColumn(halfAxes, 2, scratchCartesianW);

    // project first corner
    const corner = Cartesian3.add(u, v, scratchCorner);
    Cartesian3.add(corner, w, corner);
    Cartesian3.add(corner, center, corner);

    const toCenter = Cartesian3.subtract(corner, position, scratchToCenter$1);
    let mag = Cartesian3.dot(direction, toCenter);

    minDist = Math.min(mag, minDist);
    maxDist = Math.max(mag, maxDist);

    // project second corner
    Cartesian3.add(center, u, corner);
    Cartesian3.add(corner, v, corner);
    Cartesian3.subtract(corner, w, corner);

    Cartesian3.subtract(corner, position, toCenter);
    mag = Cartesian3.dot(direction, toCenter);

    minDist = Math.min(mag, minDist);
    maxDist = Math.max(mag, maxDist);

    // project third corner
    Cartesian3.add(center, u, corner);
    Cartesian3.subtract(corner, v, corner);
    Cartesian3.add(corner, w, corner);

    Cartesian3.subtract(corner, position, toCenter);
    mag = Cartesian3.dot(direction, toCenter);

    minDist = Math.min(mag, minDist);
    maxDist = Math.max(mag, maxDist);

    // project fourth corner
    Cartesian3.add(center, u, corner);
    Cartesian3.subtract(corner, v, corner);
    Cartesian3.subtract(corner, w, corner);

    Cartesian3.subtract(corner, position, toCenter);
    mag = Cartesian3.dot(direction, toCenter);

    minDist = Math.min(mag, minDist);
    maxDist = Math.max(mag, maxDist);

    // project fifth corner
    Cartesian3.subtract(center, u, corner);
    Cartesian3.add(corner, v, corner);
    Cartesian3.add(corner, w, corner);

    Cartesian3.subtract(corner, position, toCenter);
    mag = Cartesian3.dot(direction, toCenter);

    minDist = Math.min(mag, minDist);
    maxDist = Math.max(mag, maxDist);

    // project sixth corner
    Cartesian3.subtract(center, u, corner);
    Cartesian3.add(corner, v, corner);
    Cartesian3.subtract(corner, w, corner);

    Cartesian3.subtract(corner, position, toCenter);
    mag = Cartesian3.dot(direction, toCenter);

    minDist = Math.min(mag, minDist);
    maxDist = Math.max(mag, maxDist);

    // project seventh corner
    Cartesian3.subtract(center, u, corner);
    Cartesian3.subtract(corner, v, corner);
    Cartesian3.add(corner, w, corner);

    Cartesian3.subtract(corner, position, toCenter);
    mag = Cartesian3.dot(direction, toCenter);

    minDist = Math.min(mag, minDist);
    maxDist = Math.max(mag, maxDist);

    // project eighth corner
    Cartesian3.subtract(center, u, corner);
    Cartesian3.subtract(corner, v, corner);
    Cartesian3.subtract(corner, w, corner);

    Cartesian3.subtract(corner, position, toCenter);
    mag = Cartesian3.dot(direction, toCenter);

    minDist = Math.min(mag, minDist);
    maxDist = Math.max(mag, maxDist);

    result.start = minDist;
    result.stop = maxDist;
    return result;
  };

  const scratchXAxis$1 = new Cartesian3();
  const scratchYAxis$1 = new Cartesian3();
  const scratchZAxis$1 = new Cartesian3();

  /**
   * Computes the eight corners of an oriented bounding box. The corners are ordered by (-X, -Y, -Z), (-X, -Y, +Z), (-X, +Y, -Z), (-X, +Y, +Z), (+X, -Y, -Z), (+X, -Y, +Z), (+X, +Y, -Z), (+X, +Y, +Z).
   *
   * @param {OrientedBoundingBox} box The oriented bounding box.
   * @param {Cartesian3[]} [result] An array of eight {@link Cartesian3} instances onto which to store the corners.
   * @returns {Cartesian3[]} The modified result parameter or a new array if none was provided.
   */
  OrientedBoundingBox.computeCorners = function (box, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("box", box);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = [
        new Cartesian3(),
        new Cartesian3(),
        new Cartesian3(),
        new Cartesian3(),
        new Cartesian3(),
        new Cartesian3(),
        new Cartesian3(),
        new Cartesian3(),
      ];
    }

    const center = box.center;
    const halfAxes = box.halfAxes;
    const xAxis = Matrix3.getColumn(halfAxes, 0, scratchXAxis$1);
    const yAxis = Matrix3.getColumn(halfAxes, 1, scratchYAxis$1);
    const zAxis = Matrix3.getColumn(halfAxes, 2, scratchZAxis$1);

    Cartesian3.clone(center, result[0]);
    Cartesian3.subtract(result[0], xAxis, result[0]);
    Cartesian3.subtract(result[0], yAxis, result[0]);
    Cartesian3.subtract(result[0], zAxis, result[0]);

    Cartesian3.clone(center, result[1]);
    Cartesian3.subtract(result[1], xAxis, result[1]);
    Cartesian3.subtract(result[1], yAxis, result[1]);
    Cartesian3.add(result[1], zAxis, result[1]);

    Cartesian3.clone(center, result[2]);
    Cartesian3.subtract(result[2], xAxis, result[2]);
    Cartesian3.add(result[2], yAxis, result[2]);
    Cartesian3.subtract(result[2], zAxis, result[2]);

    Cartesian3.clone(center, result[3]);
    Cartesian3.subtract(result[3], xAxis, result[3]);
    Cartesian3.add(result[3], yAxis, result[3]);
    Cartesian3.add(result[3], zAxis, result[3]);

    Cartesian3.clone(center, result[4]);
    Cartesian3.add(result[4], xAxis, result[4]);
    Cartesian3.subtract(result[4], yAxis, result[4]);
    Cartesian3.subtract(result[4], zAxis, result[4]);

    Cartesian3.clone(center, result[5]);
    Cartesian3.add(result[5], xAxis, result[5]);
    Cartesian3.subtract(result[5], yAxis, result[5]);
    Cartesian3.add(result[5], zAxis, result[5]);

    Cartesian3.clone(center, result[6]);
    Cartesian3.add(result[6], xAxis, result[6]);
    Cartesian3.add(result[6], yAxis, result[6]);
    Cartesian3.subtract(result[6], zAxis, result[6]);

    Cartesian3.clone(center, result[7]);
    Cartesian3.add(result[7], xAxis, result[7]);
    Cartesian3.add(result[7], yAxis, result[7]);
    Cartesian3.add(result[7], zAxis, result[7]);

    return result;
  };

  const scratchRotationScale$1 = new Matrix3();

  /**
   * Computes a transformation matrix from an oriented bounding box.
   *
   * @param {OrientedBoundingBox} box The oriented bounding box.
   * @param {Matrix4} result The object onto which to store the result.
   * @returns {Matrix4} The modified result parameter or a new {@link Matrix4} instance if none was provided.
   */
  OrientedBoundingBox.computeTransformation = function (box, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("box", box);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Matrix4();
    }

    const translation = box.center;
    const rotationScale = Matrix3.multiplyByUniformScale(
      box.halfAxes,
      2.0,
      scratchRotationScale$1
    );
    return Matrix4.fromRotationTranslation(rotationScale, translation, result);
  };

  const scratchBoundingSphere$4 = new BoundingSphere();

  /**
   * Determines whether or not a bounding box is hidden from view by the occluder.
   *
   * @param {OrientedBoundingBox} box The bounding box surrounding the occludee object.
   * @param {Occluder} occluder The occluder.
   * @returns {Boolean} <code>true</code> if the box is not visible; otherwise <code>false</code>.
   */
  OrientedBoundingBox.isOccluded = function (box, occluder) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(box)) {
      throw new DeveloperError("box is required.");
    }
    if (!defined(occluder)) {
      throw new DeveloperError("occluder is required.");
    }
    //>>includeEnd('debug');

    const sphere = BoundingSphere.fromOrientedBoundingBox(
      box,
      scratchBoundingSphere$4
    );

    return !occluder.isBoundingSphereVisible(sphere);
  };

  /**
   * Determines which side of a plane the oriented bounding box is located.
   *
   * @param {Plane} plane The plane to test against.
   * @returns {Intersect} {@link Intersect.INSIDE} if the entire box is on the side of the plane
   *                      the normal is pointing, {@link Intersect.OUTSIDE} if the entire box is
   *                      on the opposite side, and {@link Intersect.INTERSECTING} if the box
   *                      intersects the plane.
   */
  OrientedBoundingBox.prototype.intersectPlane = function (plane) {
    return OrientedBoundingBox.intersectPlane(this, plane);
  };

  /**
   * Computes the estimated distance squared from the closest point on a bounding box to a point.
   *
   * @param {Cartesian3} cartesian The point
   * @returns {Number} The estimated distance squared from the bounding sphere to the point.
   *
   * @example
   * // Sort bounding boxes from back to front
   * boxes.sort(function(a, b) {
   *     return b.distanceSquaredTo(camera.positionWC) - a.distanceSquaredTo(camera.positionWC);
   * });
   */
  OrientedBoundingBox.prototype.distanceSquaredTo = function (cartesian) {
    return OrientedBoundingBox.distanceSquaredTo(this, cartesian);
  };

  /**
   * The distances calculated by the vector from the center of the bounding box to position projected onto direction.
   * <br>
   * 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 box.
   *
   * @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 box from position in direction.
   */
  OrientedBoundingBox.prototype.computePlaneDistances = function (
    position,
    direction,
    result
  ) {
    return OrientedBoundingBox.computePlaneDistances(
      this,
      position,
      direction,
      result
    );
  };

  /**
   * Computes the eight corners of an oriented bounding box. The corners are ordered by (-X, -Y, -Z), (-X, -Y, +Z), (-X, +Y, -Z), (-X, +Y, +Z), (+X, -Y, -Z), (+X, -Y, +Z), (+X, +Y, -Z), (+X, +Y, +Z).
   *
   * @param {Cartesian3[]} [result] An array of eight {@link Cartesian3} instances onto which to store the corners.
   * @returns {Cartesian3[]} The modified result parameter or a new array if none was provided.
   */
  OrientedBoundingBox.prototype.computeCorners = function (result) {
    return OrientedBoundingBox.computeCorners(this, result);
  };

  /**
   * Computes a transformation matrix from an oriented bounding box.
   *
   * @param {Matrix4} result The object onto which to store the result.
   * @returns {Matrix4} The modified result parameter or a new {@link Matrix4} instance if none was provided.
   */
  OrientedBoundingBox.prototype.computeTransformation = function (result) {
    return OrientedBoundingBox.computeTransformation(this, result);
  };

  /**
   * Determines whether or not a bounding box is hidden from view by the occluder.
   *
   * @param {Occluder} occluder The occluder.
   * @returns {Boolean} <code>true</code> if the sphere is not visible; otherwise <code>false</code>.
   */
  OrientedBoundingBox.prototype.isOccluded = function (occluder) {
    return OrientedBoundingBox.isOccluded(this, occluder);
  };

  /**
   * Compares the provided OrientedBoundingBox componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {OrientedBoundingBox} left The first OrientedBoundingBox.
   * @param {OrientedBoundingBox} right The second OrientedBoundingBox.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  OrientedBoundingBox.equals = function (left, right) {
    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        Cartesian3.equals(left.center, right.center) &&
        Matrix3.equals(left.halfAxes, right.halfAxes))
    );
  };

  /**
   * Duplicates this OrientedBoundingBox instance.
   *
   * @param {OrientedBoundingBox} [result] The object onto which to store the result.
   * @returns {OrientedBoundingBox} The modified result parameter or a new OrientedBoundingBox instance if one was not provided.
   */
  OrientedBoundingBox.prototype.clone = function (result) {
    return OrientedBoundingBox.clone(this, result);
  };

  /**
   * Compares this OrientedBoundingBox against the provided OrientedBoundingBox componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {OrientedBoundingBox} [right] The right hand side OrientedBoundingBox.
   * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
   */
  OrientedBoundingBox.prototype.equals = function (right) {
    return OrientedBoundingBox.equals(this, right);
  };

  /**
   * Enum containing WebGL Constant values by name.
   * for use without an active WebGL context, or in cases where certain constants are unavailable using the WebGL context
   * (For example, in [Safari 9]{@link https://github.com/CesiumGS/cesium/issues/2989}).
   *
   * These match the constants from the [WebGL 1.0]{@link https://www.khronos.org/registry/webgl/specs/latest/1.0/}
   * and [WebGL 2.0]{@link https://www.khronos.org/registry/webgl/specs/latest/2.0/}
   * specifications.
   *
   * @enum {Number}
   */
  const WebGLConstants = {
    DEPTH_BUFFER_BIT: 0x00000100,
    STENCIL_BUFFER_BIT: 0x00000400,
    COLOR_BUFFER_BIT: 0x00004000,
    POINTS: 0x0000,
    LINES: 0x0001,
    LINE_LOOP: 0x0002,
    LINE_STRIP: 0x0003,
    TRIANGLES: 0x0004,
    TRIANGLE_STRIP: 0x0005,
    TRIANGLE_FAN: 0x0006,
    ZERO: 0,
    ONE: 1,
    SRC_COLOR: 0x0300,
    ONE_MINUS_SRC_COLOR: 0x0301,
    SRC_ALPHA: 0x0302,
    ONE_MINUS_SRC_ALPHA: 0x0303,
    DST_ALPHA: 0x0304,
    ONE_MINUS_DST_ALPHA: 0x0305,
    DST_COLOR: 0x0306,
    ONE_MINUS_DST_COLOR: 0x0307,
    SRC_ALPHA_SATURATE: 0x0308,
    FUNC_ADD: 0x8006,
    BLEND_EQUATION: 0x8009,
    BLEND_EQUATION_RGB: 0x8009, // same as BLEND_EQUATION
    BLEND_EQUATION_ALPHA: 0x883d,
    FUNC_SUBTRACT: 0x800a,
    FUNC_REVERSE_SUBTRACT: 0x800b,
    BLEND_DST_RGB: 0x80c8,
    BLEND_SRC_RGB: 0x80c9,
    BLEND_DST_ALPHA: 0x80ca,
    BLEND_SRC_ALPHA: 0x80cb,
    CONSTANT_COLOR: 0x8001,
    ONE_MINUS_CONSTANT_COLOR: 0x8002,
    CONSTANT_ALPHA: 0x8003,
    ONE_MINUS_CONSTANT_ALPHA: 0x8004,
    BLEND_COLOR: 0x8005,
    ARRAY_BUFFER: 0x8892,
    ELEMENT_ARRAY_BUFFER: 0x8893,
    ARRAY_BUFFER_BINDING: 0x8894,
    ELEMENT_ARRAY_BUFFER_BINDING: 0x8895,
    STREAM_DRAW: 0x88e0,
    STATIC_DRAW: 0x88e4,
    DYNAMIC_DRAW: 0x88e8,
    BUFFER_SIZE: 0x8764,
    BUFFER_USAGE: 0x8765,
    CURRENT_VERTEX_ATTRIB: 0x8626,
    FRONT: 0x0404,
    BACK: 0x0405,
    FRONT_AND_BACK: 0x0408,
    CULL_FACE: 0x0b44,
    BLEND: 0x0be2,
    DITHER: 0x0bd0,
    STENCIL_TEST: 0x0b90,
    DEPTH_TEST: 0x0b71,
    SCISSOR_TEST: 0x0c11,
    POLYGON_OFFSET_FILL: 0x8037,
    SAMPLE_ALPHA_TO_COVERAGE: 0x809e,
    SAMPLE_COVERAGE: 0x80a0,
    NO_ERROR: 0,
    INVALID_ENUM: 0x0500,
    INVALID_VALUE: 0x0501,
    INVALID_OPERATION: 0x0502,
    OUT_OF_MEMORY: 0x0505,
    CW: 0x0900,
    CCW: 0x0901,
    LINE_WIDTH: 0x0b21,
    ALIASED_POINT_SIZE_RANGE: 0x846d,
    ALIASED_LINE_WIDTH_RANGE: 0x846e,
    CULL_FACE_MODE: 0x0b45,
    FRONT_FACE: 0x0b46,
    DEPTH_RANGE: 0x0b70,
    DEPTH_WRITEMASK: 0x0b72,
    DEPTH_CLEAR_VALUE: 0x0b73,
    DEPTH_FUNC: 0x0b74,
    STENCIL_CLEAR_VALUE: 0x0b91,
    STENCIL_FUNC: 0x0b92,
    STENCIL_FAIL: 0x0b94,
    STENCIL_PASS_DEPTH_FAIL: 0x0b95,
    STENCIL_PASS_DEPTH_PASS: 0x0b96,
    STENCIL_REF: 0x0b97,
    STENCIL_VALUE_MASK: 0x0b93,
    STENCIL_WRITEMASK: 0x0b98,
    STENCIL_BACK_FUNC: 0x8800,
    STENCIL_BACK_FAIL: 0x8801,
    STENCIL_BACK_PASS_DEPTH_FAIL: 0x8802,
    STENCIL_BACK_PASS_DEPTH_PASS: 0x8803,
    STENCIL_BACK_REF: 0x8ca3,
    STENCIL_BACK_VALUE_MASK: 0x8ca4,
    STENCIL_BACK_WRITEMASK: 0x8ca5,
    VIEWPORT: 0x0ba2,
    SCISSOR_BOX: 0x0c10,
    COLOR_CLEAR_VALUE: 0x0c22,
    COLOR_WRITEMASK: 0x0c23,
    UNPACK_ALIGNMENT: 0x0cf5,
    PACK_ALIGNMENT: 0x0d05,
    MAX_TEXTURE_SIZE: 0x0d33,
    MAX_VIEWPORT_DIMS: 0x0d3a,
    SUBPIXEL_BITS: 0x0d50,
    RED_BITS: 0x0d52,
    GREEN_BITS: 0x0d53,
    BLUE_BITS: 0x0d54,
    ALPHA_BITS: 0x0d55,
    DEPTH_BITS: 0x0d56,
    STENCIL_BITS: 0x0d57,
    POLYGON_OFFSET_UNITS: 0x2a00,
    POLYGON_OFFSET_FACTOR: 0x8038,
    TEXTURE_BINDING_2D: 0x8069,
    SAMPLE_BUFFERS: 0x80a8,
    SAMPLES: 0x80a9,
    SAMPLE_COVERAGE_VALUE: 0x80aa,
    SAMPLE_COVERAGE_INVERT: 0x80ab,
    COMPRESSED_TEXTURE_FORMATS: 0x86a3,
    DONT_CARE: 0x1100,
    FASTEST: 0x1101,
    NICEST: 0x1102,
    GENERATE_MIPMAP_HINT: 0x8192,
    BYTE: 0x1400,
    UNSIGNED_BYTE: 0x1401,
    SHORT: 0x1402,
    UNSIGNED_SHORT: 0x1403,
    INT: 0x1404,
    UNSIGNED_INT: 0x1405,
    FLOAT: 0x1406,
    DEPTH_COMPONENT: 0x1902,
    ALPHA: 0x1906,
    RGB: 0x1907,
    RGBA: 0x1908,
    LUMINANCE: 0x1909,
    LUMINANCE_ALPHA: 0x190a,
    UNSIGNED_SHORT_4_4_4_4: 0x8033,
    UNSIGNED_SHORT_5_5_5_1: 0x8034,
    UNSIGNED_SHORT_5_6_5: 0x8363,
    FRAGMENT_SHADER: 0x8b30,
    VERTEX_SHADER: 0x8b31,
    MAX_VERTEX_ATTRIBS: 0x8869,
    MAX_VERTEX_UNIFORM_VECTORS: 0x8dfb,
    MAX_VARYING_VECTORS: 0x8dfc,
    MAX_COMBINED_TEXTURE_IMAGE_UNITS: 0x8b4d,
    MAX_VERTEX_TEXTURE_IMAGE_UNITS: 0x8b4c,
    MAX_TEXTURE_IMAGE_UNITS: 0x8872,
    MAX_FRAGMENT_UNIFORM_VECTORS: 0x8dfd,
    SHADER_TYPE: 0x8b4f,
    DELETE_STATUS: 0x8b80,
    LINK_STATUS: 0x8b82,
    VALIDATE_STATUS: 0x8b83,
    ATTACHED_SHADERS: 0x8b85,
    ACTIVE_UNIFORMS: 0x8b86,
    ACTIVE_ATTRIBUTES: 0x8b89,
    SHADING_LANGUAGE_VERSION: 0x8b8c,
    CURRENT_PROGRAM: 0x8b8d,
    NEVER: 0x0200,
    LESS: 0x0201,
    EQUAL: 0x0202,
    LEQUAL: 0x0203,
    GREATER: 0x0204,
    NOTEQUAL: 0x0205,
    GEQUAL: 0x0206,
    ALWAYS: 0x0207,
    KEEP: 0x1e00,
    REPLACE: 0x1e01,
    INCR: 0x1e02,
    DECR: 0x1e03,
    INVERT: 0x150a,
    INCR_WRAP: 0x8507,
    DECR_WRAP: 0x8508,
    VENDOR: 0x1f00,
    RENDERER: 0x1f01,
    VERSION: 0x1f02,
    NEAREST: 0x2600,
    LINEAR: 0x2601,
    NEAREST_MIPMAP_NEAREST: 0x2700,
    LINEAR_MIPMAP_NEAREST: 0x2701,
    NEAREST_MIPMAP_LINEAR: 0x2702,
    LINEAR_MIPMAP_LINEAR: 0x2703,
    TEXTURE_MAG_FILTER: 0x2800,
    TEXTURE_MIN_FILTER: 0x2801,
    TEXTURE_WRAP_S: 0x2802,
    TEXTURE_WRAP_T: 0x2803,
    TEXTURE_2D: 0x0de1,
    TEXTURE: 0x1702,
    TEXTURE_CUBE_MAP: 0x8513,
    TEXTURE_BINDING_CUBE_MAP: 0x8514,
    TEXTURE_CUBE_MAP_POSITIVE_X: 0x8515,
    TEXTURE_CUBE_MAP_NEGATIVE_X: 0x8516,
    TEXTURE_CUBE_MAP_POSITIVE_Y: 0x8517,
    TEXTURE_CUBE_MAP_NEGATIVE_Y: 0x8518,
    TEXTURE_CUBE_MAP_POSITIVE_Z: 0x8519,
    TEXTURE_CUBE_MAP_NEGATIVE_Z: 0x851a,
    MAX_CUBE_MAP_TEXTURE_SIZE: 0x851c,
    TEXTURE0: 0x84c0,
    TEXTURE1: 0x84c1,
    TEXTURE2: 0x84c2,
    TEXTURE3: 0x84c3,
    TEXTURE4: 0x84c4,
    TEXTURE5: 0x84c5,
    TEXTURE6: 0x84c6,
    TEXTURE7: 0x84c7,
    TEXTURE8: 0x84c8,
    TEXTURE9: 0x84c9,
    TEXTURE10: 0x84ca,
    TEXTURE11: 0x84cb,
    TEXTURE12: 0x84cc,
    TEXTURE13: 0x84cd,
    TEXTURE14: 0x84ce,
    TEXTURE15: 0x84cf,
    TEXTURE16: 0x84d0,
    TEXTURE17: 0x84d1,
    TEXTURE18: 0x84d2,
    TEXTURE19: 0x84d3,
    TEXTURE20: 0x84d4,
    TEXTURE21: 0x84d5,
    TEXTURE22: 0x84d6,
    TEXTURE23: 0x84d7,
    TEXTURE24: 0x84d8,
    TEXTURE25: 0x84d9,
    TEXTURE26: 0x84da,
    TEXTURE27: 0x84db,
    TEXTURE28: 0x84dc,
    TEXTURE29: 0x84dd,
    TEXTURE30: 0x84de,
    TEXTURE31: 0x84df,
    ACTIVE_TEXTURE: 0x84e0,
    REPEAT: 0x2901,
    CLAMP_TO_EDGE: 0x812f,
    MIRRORED_REPEAT: 0x8370,
    FLOAT_VEC2: 0x8b50,
    FLOAT_VEC3: 0x8b51,
    FLOAT_VEC4: 0x8b52,
    INT_VEC2: 0x8b53,
    INT_VEC3: 0x8b54,
    INT_VEC4: 0x8b55,
    BOOL: 0x8b56,
    BOOL_VEC2: 0x8b57,
    BOOL_VEC3: 0x8b58,
    BOOL_VEC4: 0x8b59,
    FLOAT_MAT2: 0x8b5a,
    FLOAT_MAT3: 0x8b5b,
    FLOAT_MAT4: 0x8b5c,
    SAMPLER_2D: 0x8b5e,
    SAMPLER_CUBE: 0x8b60,
    VERTEX_ATTRIB_ARRAY_ENABLED: 0x8622,
    VERTEX_ATTRIB_ARRAY_SIZE: 0x8623,
    VERTEX_ATTRIB_ARRAY_STRIDE: 0x8624,
    VERTEX_ATTRIB_ARRAY_TYPE: 0x8625,
    VERTEX_ATTRIB_ARRAY_NORMALIZED: 0x886a,
    VERTEX_ATTRIB_ARRAY_POINTER: 0x8645,
    VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: 0x889f,
    IMPLEMENTATION_COLOR_READ_TYPE: 0x8b9a,
    IMPLEMENTATION_COLOR_READ_FORMAT: 0x8b9b,
    COMPILE_STATUS: 0x8b81,
    LOW_FLOAT: 0x8df0,
    MEDIUM_FLOAT: 0x8df1,
    HIGH_FLOAT: 0x8df2,
    LOW_INT: 0x8df3,
    MEDIUM_INT: 0x8df4,
    HIGH_INT: 0x8df5,
    FRAMEBUFFER: 0x8d40,
    RENDERBUFFER: 0x8d41,
    RGBA4: 0x8056,
    RGB5_A1: 0x8057,
    RGB565: 0x8d62,
    DEPTH_COMPONENT16: 0x81a5,
    STENCIL_INDEX: 0x1901,
    STENCIL_INDEX8: 0x8d48,
    DEPTH_STENCIL: 0x84f9,
    RENDERBUFFER_WIDTH: 0x8d42,
    RENDERBUFFER_HEIGHT: 0x8d43,
    RENDERBUFFER_INTERNAL_FORMAT: 0x8d44,
    RENDERBUFFER_RED_SIZE: 0x8d50,
    RENDERBUFFER_GREEN_SIZE: 0x8d51,
    RENDERBUFFER_BLUE_SIZE: 0x8d52,
    RENDERBUFFER_ALPHA_SIZE: 0x8d53,
    RENDERBUFFER_DEPTH_SIZE: 0x8d54,
    RENDERBUFFER_STENCIL_SIZE: 0x8d55,
    FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: 0x8cd0,
    FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: 0x8cd1,
    FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: 0x8cd2,
    FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: 0x8cd3,
    COLOR_ATTACHMENT0: 0x8ce0,
    DEPTH_ATTACHMENT: 0x8d00,
    STENCIL_ATTACHMENT: 0x8d20,
    DEPTH_STENCIL_ATTACHMENT: 0x821a,
    NONE: 0,
    FRAMEBUFFER_COMPLETE: 0x8cd5,
    FRAMEBUFFER_INCOMPLETE_ATTACHMENT: 0x8cd6,
    FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: 0x8cd7,
    FRAMEBUFFER_INCOMPLETE_DIMENSIONS: 0x8cd9,
    FRAMEBUFFER_UNSUPPORTED: 0x8cdd,
    FRAMEBUFFER_BINDING: 0x8ca6,
    RENDERBUFFER_BINDING: 0x8ca7,
    MAX_RENDERBUFFER_SIZE: 0x84e8,
    INVALID_FRAMEBUFFER_OPERATION: 0x0506,
    UNPACK_FLIP_Y_WEBGL: 0x9240,
    UNPACK_PREMULTIPLY_ALPHA_WEBGL: 0x9241,
    CONTEXT_LOST_WEBGL: 0x9242,
    UNPACK_COLORSPACE_CONVERSION_WEBGL: 0x9243,
    BROWSER_DEFAULT_WEBGL: 0x9244,

    // WEBGL_compressed_texture_s3tc
    COMPRESSED_RGB_S3TC_DXT1_EXT: 0x83f0,
    COMPRESSED_RGBA_S3TC_DXT1_EXT: 0x83f1,
    COMPRESSED_RGBA_S3TC_DXT3_EXT: 0x83f2,
    COMPRESSED_RGBA_S3TC_DXT5_EXT: 0x83f3,

    // WEBGL_compressed_texture_pvrtc
    COMPRESSED_RGB_PVRTC_4BPPV1_IMG: 0x8c00,
    COMPRESSED_RGB_PVRTC_2BPPV1_IMG: 0x8c01,
    COMPRESSED_RGBA_PVRTC_4BPPV1_IMG: 0x8c02,
    COMPRESSED_RGBA_PVRTC_2BPPV1_IMG: 0x8c03,

    // WEBGL_compressed_texture_astc
    COMPRESSED_RGBA_ASTC_4x4_WEBGL: 0x93b0,

    // WEBGL_compressed_texture_etc1
    COMPRESSED_RGB_ETC1_WEBGL: 0x8d64,

    // EXT_texture_compression_bptc
    COMPRESSED_RGBA_BPTC_UNORM: 0x8e8c,

    // EXT_color_buffer_half_float
    HALF_FLOAT_OES: 0x8d61,

    // Desktop OpenGL
    DOUBLE: 0x140a,

    // WebGL 2
    READ_BUFFER: 0x0c02,
    UNPACK_ROW_LENGTH: 0x0cf2,
    UNPACK_SKIP_ROWS: 0x0cf3,
    UNPACK_SKIP_PIXELS: 0x0cf4,
    PACK_ROW_LENGTH: 0x0d02,
    PACK_SKIP_ROWS: 0x0d03,
    PACK_SKIP_PIXELS: 0x0d04,
    COLOR: 0x1800,
    DEPTH: 0x1801,
    STENCIL: 0x1802,
    RED: 0x1903,
    RGB8: 0x8051,
    RGBA8: 0x8058,
    RGB10_A2: 0x8059,
    TEXTURE_BINDING_3D: 0x806a,
    UNPACK_SKIP_IMAGES: 0x806d,
    UNPACK_IMAGE_HEIGHT: 0x806e,
    TEXTURE_3D: 0x806f,
    TEXTURE_WRAP_R: 0x8072,
    MAX_3D_TEXTURE_SIZE: 0x8073,
    UNSIGNED_INT_2_10_10_10_REV: 0x8368,
    MAX_ELEMENTS_VERTICES: 0x80e8,
    MAX_ELEMENTS_INDICES: 0x80e9,
    TEXTURE_MIN_LOD: 0x813a,
    TEXTURE_MAX_LOD: 0x813b,
    TEXTURE_BASE_LEVEL: 0x813c,
    TEXTURE_MAX_LEVEL: 0x813d,
    MIN: 0x8007,
    MAX: 0x8008,
    DEPTH_COMPONENT24: 0x81a6,
    MAX_TEXTURE_LOD_BIAS: 0x84fd,
    TEXTURE_COMPARE_MODE: 0x884c,
    TEXTURE_COMPARE_FUNC: 0x884d,
    CURRENT_QUERY: 0x8865,
    QUERY_RESULT: 0x8866,
    QUERY_RESULT_AVAILABLE: 0x8867,
    STREAM_READ: 0x88e1,
    STREAM_COPY: 0x88e2,
    STATIC_READ: 0x88e5,
    STATIC_COPY: 0x88e6,
    DYNAMIC_READ: 0x88e9,
    DYNAMIC_COPY: 0x88ea,
    MAX_DRAW_BUFFERS: 0x8824,
    DRAW_BUFFER0: 0x8825,
    DRAW_BUFFER1: 0x8826,
    DRAW_BUFFER2: 0x8827,
    DRAW_BUFFER3: 0x8828,
    DRAW_BUFFER4: 0x8829,
    DRAW_BUFFER5: 0x882a,
    DRAW_BUFFER6: 0x882b,
    DRAW_BUFFER7: 0x882c,
    DRAW_BUFFER8: 0x882d,
    DRAW_BUFFER9: 0x882e,
    DRAW_BUFFER10: 0x882f,
    DRAW_BUFFER11: 0x8830,
    DRAW_BUFFER12: 0x8831,
    DRAW_BUFFER13: 0x8832,
    DRAW_BUFFER14: 0x8833,
    DRAW_BUFFER15: 0x8834,
    MAX_FRAGMENT_UNIFORM_COMPONENTS: 0x8b49,
    MAX_VERTEX_UNIFORM_COMPONENTS: 0x8b4a,
    SAMPLER_3D: 0x8b5f,
    SAMPLER_2D_SHADOW: 0x8b62,
    FRAGMENT_SHADER_DERIVATIVE_HINT: 0x8b8b,
    PIXEL_PACK_BUFFER: 0x88eb,
    PIXEL_UNPACK_BUFFER: 0x88ec,
    PIXEL_PACK_BUFFER_BINDING: 0x88ed,
    PIXEL_UNPACK_BUFFER_BINDING: 0x88ef,
    FLOAT_MAT2x3: 0x8b65,
    FLOAT_MAT2x4: 0x8b66,
    FLOAT_MAT3x2: 0x8b67,
    FLOAT_MAT3x4: 0x8b68,
    FLOAT_MAT4x2: 0x8b69,
    FLOAT_MAT4x3: 0x8b6a,
    SRGB: 0x8c40,
    SRGB8: 0x8c41,
    SRGB8_ALPHA8: 0x8c43,
    COMPARE_REF_TO_TEXTURE: 0x884e,
    RGBA32F: 0x8814,
    RGB32F: 0x8815,
    RGBA16F: 0x881a,
    RGB16F: 0x881b,
    VERTEX_ATTRIB_ARRAY_INTEGER: 0x88fd,
    MAX_ARRAY_TEXTURE_LAYERS: 0x88ff,
    MIN_PROGRAM_TEXEL_OFFSET: 0x8904,
    MAX_PROGRAM_TEXEL_OFFSET: 0x8905,
    MAX_VARYING_COMPONENTS: 0x8b4b,
    TEXTURE_2D_ARRAY: 0x8c1a,
    TEXTURE_BINDING_2D_ARRAY: 0x8c1d,
    R11F_G11F_B10F: 0x8c3a,
    UNSIGNED_INT_10F_11F_11F_REV: 0x8c3b,
    RGB9_E5: 0x8c3d,
    UNSIGNED_INT_5_9_9_9_REV: 0x8c3e,
    TRANSFORM_FEEDBACK_BUFFER_MODE: 0x8c7f,
    MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS: 0x8c80,
    TRANSFORM_FEEDBACK_VARYINGS: 0x8c83,
    TRANSFORM_FEEDBACK_BUFFER_START: 0x8c84,
    TRANSFORM_FEEDBACK_BUFFER_SIZE: 0x8c85,
    TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN: 0x8c88,
    RASTERIZER_DISCARD: 0x8c89,
    MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS: 0x8c8a,
    MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS: 0x8c8b,
    INTERLEAVED_ATTRIBS: 0x8c8c,
    SEPARATE_ATTRIBS: 0x8c8d,
    TRANSFORM_FEEDBACK_BUFFER: 0x8c8e,
    TRANSFORM_FEEDBACK_BUFFER_BINDING: 0x8c8f,
    RGBA32UI: 0x8d70,
    RGB32UI: 0x8d71,
    RGBA16UI: 0x8d76,
    RGB16UI: 0x8d77,
    RGBA8UI: 0x8d7c,
    RGB8UI: 0x8d7d,
    RGBA32I: 0x8d82,
    RGB32I: 0x8d83,
    RGBA16I: 0x8d88,
    RGB16I: 0x8d89,
    RGBA8I: 0x8d8e,
    RGB8I: 0x8d8f,
    RED_INTEGER: 0x8d94,
    RGB_INTEGER: 0x8d98,
    RGBA_INTEGER: 0x8d99,
    SAMPLER_2D_ARRAY: 0x8dc1,
    SAMPLER_2D_ARRAY_SHADOW: 0x8dc4,
    SAMPLER_CUBE_SHADOW: 0x8dc5,
    UNSIGNED_INT_VEC2: 0x8dc6,
    UNSIGNED_INT_VEC3: 0x8dc7,
    UNSIGNED_INT_VEC4: 0x8dc8,
    INT_SAMPLER_2D: 0x8dca,
    INT_SAMPLER_3D: 0x8dcb,
    INT_SAMPLER_CUBE: 0x8dcc,
    INT_SAMPLER_2D_ARRAY: 0x8dcf,
    UNSIGNED_INT_SAMPLER_2D: 0x8dd2,
    UNSIGNED_INT_SAMPLER_3D: 0x8dd3,
    UNSIGNED_INT_SAMPLER_CUBE: 0x8dd4,
    UNSIGNED_INT_SAMPLER_2D_ARRAY: 0x8dd7,
    DEPTH_COMPONENT32F: 0x8cac,
    DEPTH32F_STENCIL8: 0x8cad,
    FLOAT_32_UNSIGNED_INT_24_8_REV: 0x8dad,
    FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING: 0x8210,
    FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE: 0x8211,
    FRAMEBUFFER_ATTACHMENT_RED_SIZE: 0x8212,
    FRAMEBUFFER_ATTACHMENT_GREEN_SIZE: 0x8213,
    FRAMEBUFFER_ATTACHMENT_BLUE_SIZE: 0x8214,
    FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE: 0x8215,
    FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE: 0x8216,
    FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE: 0x8217,
    FRAMEBUFFER_DEFAULT: 0x8218,
    UNSIGNED_INT_24_8: 0x84fa,
    DEPTH24_STENCIL8: 0x88f0,
    UNSIGNED_NORMALIZED: 0x8c17,
    DRAW_FRAMEBUFFER_BINDING: 0x8ca6, // Same as FRAMEBUFFER_BINDING
    READ_FRAMEBUFFER: 0x8ca8,
    DRAW_FRAMEBUFFER: 0x8ca9,
    READ_FRAMEBUFFER_BINDING: 0x8caa,
    RENDERBUFFER_SAMPLES: 0x8cab,
    FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER: 0x8cd4,
    MAX_COLOR_ATTACHMENTS: 0x8cdf,
    COLOR_ATTACHMENT1: 0x8ce1,
    COLOR_ATTACHMENT2: 0x8ce2,
    COLOR_ATTACHMENT3: 0x8ce3,
    COLOR_ATTACHMENT4: 0x8ce4,
    COLOR_ATTACHMENT5: 0x8ce5,
    COLOR_ATTACHMENT6: 0x8ce6,
    COLOR_ATTACHMENT7: 0x8ce7,
    COLOR_ATTACHMENT8: 0x8ce8,
    COLOR_ATTACHMENT9: 0x8ce9,
    COLOR_ATTACHMENT10: 0x8cea,
    COLOR_ATTACHMENT11: 0x8ceb,
    COLOR_ATTACHMENT12: 0x8cec,
    COLOR_ATTACHMENT13: 0x8ced,
    COLOR_ATTACHMENT14: 0x8cee,
    COLOR_ATTACHMENT15: 0x8cef,
    FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: 0x8d56,
    MAX_SAMPLES: 0x8d57,
    HALF_FLOAT: 0x140b,
    RG: 0x8227,
    RG_INTEGER: 0x8228,
    R8: 0x8229,
    RG8: 0x822b,
    R16F: 0x822d,
    R32F: 0x822e,
    RG16F: 0x822f,
    RG32F: 0x8230,
    R8I: 0x8231,
    R8UI: 0x8232,
    R16I: 0x8233,
    R16UI: 0x8234,
    R32I: 0x8235,
    R32UI: 0x8236,
    RG8I: 0x8237,
    RG8UI: 0x8238,
    RG16I: 0x8239,
    RG16UI: 0x823a,
    RG32I: 0x823b,
    RG32UI: 0x823c,
    VERTEX_ARRAY_BINDING: 0x85b5,
    R8_SNORM: 0x8f94,
    RG8_SNORM: 0x8f95,
    RGB8_SNORM: 0x8f96,
    RGBA8_SNORM: 0x8f97,
    SIGNED_NORMALIZED: 0x8f9c,
    COPY_READ_BUFFER: 0x8f36,
    COPY_WRITE_BUFFER: 0x8f37,
    COPY_READ_BUFFER_BINDING: 0x8f36, // Same as COPY_READ_BUFFER
    COPY_WRITE_BUFFER_BINDING: 0x8f37, // Same as COPY_WRITE_BUFFER
    UNIFORM_BUFFER: 0x8a11,
    UNIFORM_BUFFER_BINDING: 0x8a28,
    UNIFORM_BUFFER_START: 0x8a29,
    UNIFORM_BUFFER_SIZE: 0x8a2a,
    MAX_VERTEX_UNIFORM_BLOCKS: 0x8a2b,
    MAX_FRAGMENT_UNIFORM_BLOCKS: 0x8a2d,
    MAX_COMBINED_UNIFORM_BLOCKS: 0x8a2e,
    MAX_UNIFORM_BUFFER_BINDINGS: 0x8a2f,
    MAX_UNIFORM_BLOCK_SIZE: 0x8a30,
    MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS: 0x8a31,
    MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS: 0x8a33,
    UNIFORM_BUFFER_OFFSET_ALIGNMENT: 0x8a34,
    ACTIVE_UNIFORM_BLOCKS: 0x8a36,
    UNIFORM_TYPE: 0x8a37,
    UNIFORM_SIZE: 0x8a38,
    UNIFORM_BLOCK_INDEX: 0x8a3a,
    UNIFORM_OFFSET: 0x8a3b,
    UNIFORM_ARRAY_STRIDE: 0x8a3c,
    UNIFORM_MATRIX_STRIDE: 0x8a3d,
    UNIFORM_IS_ROW_MAJOR: 0x8a3e,
    UNIFORM_BLOCK_BINDING: 0x8a3f,
    UNIFORM_BLOCK_DATA_SIZE: 0x8a40,
    UNIFORM_BLOCK_ACTIVE_UNIFORMS: 0x8a42,
    UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES: 0x8a43,
    UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER: 0x8a44,
    UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER: 0x8a46,
    INVALID_INDEX: 0xffffffff,
    MAX_VERTEX_OUTPUT_COMPONENTS: 0x9122,
    MAX_FRAGMENT_INPUT_COMPONENTS: 0x9125,
    MAX_SERVER_WAIT_TIMEOUT: 0x9111,
    OBJECT_TYPE: 0x9112,
    SYNC_CONDITION: 0x9113,
    SYNC_STATUS: 0x9114,
    SYNC_FLAGS: 0x9115,
    SYNC_FENCE: 0x9116,
    SYNC_GPU_COMMANDS_COMPLETE: 0x9117,
    UNSIGNALED: 0x9118,
    SIGNALED: 0x9119,
    ALREADY_SIGNALED: 0x911a,
    TIMEOUT_EXPIRED: 0x911b,
    CONDITION_SATISFIED: 0x911c,
    WAIT_FAILED: 0x911d,
    SYNC_FLUSH_COMMANDS_BIT: 0x00000001,
    VERTEX_ATTRIB_ARRAY_DIVISOR: 0x88fe,
    ANY_SAMPLES_PASSED: 0x8c2f,
    ANY_SAMPLES_PASSED_CONSERVATIVE: 0x8d6a,
    SAMPLER_BINDING: 0x8919,
    RGB10_A2UI: 0x906f,
    INT_2_10_10_10_REV: 0x8d9f,
    TRANSFORM_FEEDBACK: 0x8e22,
    TRANSFORM_FEEDBACK_PAUSED: 0x8e23,
    TRANSFORM_FEEDBACK_ACTIVE: 0x8e24,
    TRANSFORM_FEEDBACK_BINDING: 0x8e25,
    COMPRESSED_R11_EAC: 0x9270,
    COMPRESSED_SIGNED_R11_EAC: 0x9271,
    COMPRESSED_RG11_EAC: 0x9272,
    COMPRESSED_SIGNED_RG11_EAC: 0x9273,
    COMPRESSED_RGB8_ETC2: 0x9274,
    COMPRESSED_SRGB8_ETC2: 0x9275,
    COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2: 0x9276,
    COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2: 0x9277,
    COMPRESSED_RGBA8_ETC2_EAC: 0x9278,
    COMPRESSED_SRGB8_ALPHA8_ETC2_EAC: 0x9279,
    TEXTURE_IMMUTABLE_FORMAT: 0x912f,
    MAX_ELEMENT_INDEX: 0x8d6b,
    TEXTURE_IMMUTABLE_LEVELS: 0x82df,

    // Extensions
    MAX_TEXTURE_MAX_ANISOTROPY_EXT: 0x84ff,
  };
  var WebGLConstants$1 = Object.freeze(WebGLConstants);

  /**
   * WebGL component datatypes.  Components are intrinsics,
   * which form attributes, which form vertices.
   *
   * @enum {Number}
   */
  const ComponentDatatype = {
    /**
     * 8-bit signed byte corresponding to <code>gl.BYTE</code> and the type
     * of an element in <code>Int8Array</code>.
     *
     * @type {Number}
     * @constant
     */
    BYTE: WebGLConstants$1.BYTE,

    /**
     * 8-bit unsigned byte corresponding to <code>UNSIGNED_BYTE</code> and the type
     * of an element in <code>Uint8Array</code>.
     *
     * @type {Number}
     * @constant
     */
    UNSIGNED_BYTE: WebGLConstants$1.UNSIGNED_BYTE,

    /**
     * 16-bit signed short corresponding to <code>SHORT</code> and the type
     * of an element in <code>Int16Array</code>.
     *
     * @type {Number}
     * @constant
     */
    SHORT: WebGLConstants$1.SHORT,

    /**
     * 16-bit unsigned short corresponding to <code>UNSIGNED_SHORT</code> and the type
     * of an element in <code>Uint16Array</code>.
     *
     * @type {Number}
     * @constant
     */
    UNSIGNED_SHORT: WebGLConstants$1.UNSIGNED_SHORT,

    /**
     * 32-bit signed int corresponding to <code>INT</code> and the type
     * of an element in <code>Int32Array</code>.
     *
     * @memberOf ComponentDatatype
     *
     * @type {Number}
     * @constant
     */
    INT: WebGLConstants$1.INT,

    /**
     * 32-bit unsigned int corresponding to <code>UNSIGNED_INT</code> and the type
     * of an element in <code>Uint32Array</code>.
     *
     * @memberOf ComponentDatatype
     *
     * @type {Number}
     * @constant
     */
    UNSIGNED_INT: WebGLConstants$1.UNSIGNED_INT,

    /**
     * 32-bit floating-point corresponding to <code>FLOAT</code> and the type
     * of an element in <code>Float32Array</code>.
     *
     * @type {Number}
     * @constant
     */
    FLOAT: WebGLConstants$1.FLOAT,

    /**
     * 64-bit floating-point corresponding to <code>gl.DOUBLE</code> (in Desktop OpenGL;
     * this is not supported in WebGL, and is emulated in Cesium via {@link GeometryPipeline.encodeAttribute})
     * and the type of an element in <code>Float64Array</code>.
     *
     * @memberOf ComponentDatatype
     *
     * @type {Number}
     * @constant
     * @default 0x140A
     */
    DOUBLE: WebGLConstants$1.DOUBLE,
  };

  /**
   * Returns the size, in bytes, of the corresponding datatype.
   *
   * @param {ComponentDatatype} componentDatatype The component datatype to get the size of.
   * @returns {Number} The size in bytes.
   *
   * @exception {DeveloperError} componentDatatype is not a valid value.
   *
   * @example
   * // Returns Int8Array.BYTES_PER_ELEMENT
   * const size = Cesium.ComponentDatatype.getSizeInBytes(Cesium.ComponentDatatype.BYTE);
   */
  ComponentDatatype.getSizeInBytes = function (componentDatatype) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(componentDatatype)) {
      throw new DeveloperError("value is required.");
    }
    //>>includeEnd('debug');

    switch (componentDatatype) {
      case ComponentDatatype.BYTE:
        return Int8Array.BYTES_PER_ELEMENT;
      case ComponentDatatype.UNSIGNED_BYTE:
        return Uint8Array.BYTES_PER_ELEMENT;
      case ComponentDatatype.SHORT:
        return Int16Array.BYTES_PER_ELEMENT;
      case ComponentDatatype.UNSIGNED_SHORT:
        return Uint16Array.BYTES_PER_ELEMENT;
      case ComponentDatatype.INT:
        return Int32Array.BYTES_PER_ELEMENT;
      case ComponentDatatype.UNSIGNED_INT:
        return Uint32Array.BYTES_PER_ELEMENT;
      case ComponentDatatype.FLOAT:
        return Float32Array.BYTES_PER_ELEMENT;
      case ComponentDatatype.DOUBLE:
        return Float64Array.BYTES_PER_ELEMENT;
      //>>includeStart('debug', pragmas.debug);
      default:
        throw new DeveloperError("componentDatatype is not a valid value.");
      //>>includeEnd('debug');
    }
  };

  /**
   * Gets the {@link ComponentDatatype} for the provided TypedArray instance.
   *
   * @param {Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} array The typed array.
   * @returns {ComponentDatatype} The ComponentDatatype for the provided array, or undefined if the array is not a TypedArray.
   */
  ComponentDatatype.fromTypedArray = function (array) {
    if (array instanceof Int8Array) {
      return ComponentDatatype.BYTE;
    }
    if (array instanceof Uint8Array) {
      return ComponentDatatype.UNSIGNED_BYTE;
    }
    if (array instanceof Int16Array) {
      return ComponentDatatype.SHORT;
    }
    if (array instanceof Uint16Array) {
      return ComponentDatatype.UNSIGNED_SHORT;
    }
    if (array instanceof Int32Array) {
      return ComponentDatatype.INT;
    }
    if (array instanceof Uint32Array) {
      return ComponentDatatype.UNSIGNED_INT;
    }
    if (array instanceof Float32Array) {
      return ComponentDatatype.FLOAT;
    }
    if (array instanceof Float64Array) {
      return ComponentDatatype.DOUBLE;
    }

    //>>includeStart('debug', pragmas.debug);
    throw new DeveloperError(
      "array must be an Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, or Float64Array."
    );
    //>>includeEnd('debug');
  };

  /**
   * Validates that the provided component datatype is a valid {@link ComponentDatatype}
   *
   * @param {ComponentDatatype} componentDatatype The component datatype to validate.
   * @returns {Boolean} <code>true</code> if the provided component datatype is a valid value; otherwise, <code>false</code>.
   *
   * @example
   * if (!Cesium.ComponentDatatype.validate(componentDatatype)) {
   *   throw new Cesium.DeveloperError('componentDatatype must be a valid value.');
   * }
   */
  ComponentDatatype.validate = function (componentDatatype) {
    return (
      defined(componentDatatype) &&
      (componentDatatype === ComponentDatatype.BYTE ||
        componentDatatype === ComponentDatatype.UNSIGNED_BYTE ||
        componentDatatype === ComponentDatatype.SHORT ||
        componentDatatype === ComponentDatatype.UNSIGNED_SHORT ||
        componentDatatype === ComponentDatatype.INT ||
        componentDatatype === ComponentDatatype.UNSIGNED_INT ||
        componentDatatype === ComponentDatatype.FLOAT ||
        componentDatatype === ComponentDatatype.DOUBLE)
    );
  };

  /**
   * Creates a typed array corresponding to component data type.
   *
   * @param {ComponentDatatype} componentDatatype The component data type.
   * @param {Number|Array} valuesOrLength The length of the array to create or an array.
   * @returns {Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} A typed array.
   *
   * @exception {DeveloperError} componentDatatype is not a valid value.
   *
   * @example
   * // creates a Float32Array with length of 100
   * const typedArray = Cesium.ComponentDatatype.createTypedArray(Cesium.ComponentDatatype.FLOAT, 100);
   */
  ComponentDatatype.createTypedArray = function (
    componentDatatype,
    valuesOrLength
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(componentDatatype)) {
      throw new DeveloperError("componentDatatype is required.");
    }
    if (!defined(valuesOrLength)) {
      throw new DeveloperError("valuesOrLength is required.");
    }
    //>>includeEnd('debug');

    switch (componentDatatype) {
      case ComponentDatatype.BYTE:
        return new Int8Array(valuesOrLength);
      case ComponentDatatype.UNSIGNED_BYTE:
        return new Uint8Array(valuesOrLength);
      case ComponentDatatype.SHORT:
        return new Int16Array(valuesOrLength);
      case ComponentDatatype.UNSIGNED_SHORT:
        return new Uint16Array(valuesOrLength);
      case ComponentDatatype.INT:
        return new Int32Array(valuesOrLength);
      case ComponentDatatype.UNSIGNED_INT:
        return new Uint32Array(valuesOrLength);
      case ComponentDatatype.FLOAT:
        return new Float32Array(valuesOrLength);
      case ComponentDatatype.DOUBLE:
        return new Float64Array(valuesOrLength);
      //>>includeStart('debug', pragmas.debug);
      default:
        throw new DeveloperError("componentDatatype is not a valid value.");
      //>>includeEnd('debug');
    }
  };

  /**
   * Creates a typed view of an array of bytes.
   *
   * @param {ComponentDatatype} componentDatatype The type of the view to create.
   * @param {ArrayBuffer} buffer The buffer storage to use for the view.
   * @param {Number} [byteOffset] The offset, in bytes, to the first element in the view.
   * @param {Number} [length] The number of elements in the view.
   * @returns {Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} A typed array view of the buffer.
   *
   * @exception {DeveloperError} componentDatatype is not a valid value.
   */
  ComponentDatatype.createArrayBufferView = function (
    componentDatatype,
    buffer,
    byteOffset,
    length
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(componentDatatype)) {
      throw new DeveloperError("componentDatatype is required.");
    }
    if (!defined(buffer)) {
      throw new DeveloperError("buffer is required.");
    }
    //>>includeEnd('debug');

    byteOffset = defaultValue(byteOffset, 0);
    length = defaultValue(
      length,
      (buffer.byteLength - byteOffset) /
        ComponentDatatype.getSizeInBytes(componentDatatype)
    );

    switch (componentDatatype) {
      case ComponentDatatype.BYTE:
        return new Int8Array(buffer, byteOffset, length);
      case ComponentDatatype.UNSIGNED_BYTE:
        return new Uint8Array(buffer, byteOffset, length);
      case ComponentDatatype.SHORT:
        return new Int16Array(buffer, byteOffset, length);
      case ComponentDatatype.UNSIGNED_SHORT:
        return new Uint16Array(buffer, byteOffset, length);
      case ComponentDatatype.INT:
        return new Int32Array(buffer, byteOffset, length);
      case ComponentDatatype.UNSIGNED_INT:
        return new Uint32Array(buffer, byteOffset, length);
      case ComponentDatatype.FLOAT:
        return new Float32Array(buffer, byteOffset, length);
      case ComponentDatatype.DOUBLE:
        return new Float64Array(buffer, byteOffset, length);
      //>>includeStart('debug', pragmas.debug);
      default:
        throw new DeveloperError("componentDatatype is not a valid value.");
      //>>includeEnd('debug');
    }
  };

  /**
   * Get the ComponentDatatype from its name.
   *
   * @param {String} name The name of the ComponentDatatype.
   * @returns {ComponentDatatype} The ComponentDatatype.
   *
   * @exception {DeveloperError} name is not a valid value.
   */
  ComponentDatatype.fromName = function (name) {
    switch (name) {
      case "BYTE":
        return ComponentDatatype.BYTE;
      case "UNSIGNED_BYTE":
        return ComponentDatatype.UNSIGNED_BYTE;
      case "SHORT":
        return ComponentDatatype.SHORT;
      case "UNSIGNED_SHORT":
        return ComponentDatatype.UNSIGNED_SHORT;
      case "INT":
        return ComponentDatatype.INT;
      case "UNSIGNED_INT":
        return ComponentDatatype.UNSIGNED_INT;
      case "FLOAT":
        return ComponentDatatype.FLOAT;
      case "DOUBLE":
        return ComponentDatatype.DOUBLE;
      //>>includeStart('debug', pragmas.debug);
      default:
        throw new DeveloperError("name is not a valid value.");
      //>>includeEnd('debug');
    }
  };
  var ComponentDatatype$1 = Object.freeze(ComponentDatatype);

  /**
   * A 2x2 matrix, indexable as a column-major order array.
   * Constructor parameters are in row-major order for code readability.
   * @alias Matrix2
   * @constructor
   * @implements {ArrayLike<number>}
   *
   * @param {Number} [column0Row0=0.0] The value for column 0, row 0.
   * @param {Number} [column1Row0=0.0] The value for column 1, row 0.
   * @param {Number} [column0Row1=0.0] The value for column 0, row 1.
   * @param {Number} [column1Row1=0.0] The value for column 1, row 1.
   *
   * @see Matrix2.fromArray
   * @see Matrix2.fromColumnMajorArray
   * @see Matrix2.fromRowMajorArray
   * @see Matrix2.fromScale
   * @see Matrix2.fromUniformScale
   * @see Matrix2.fromRotation
   * @see Matrix3
   * @see Matrix4
   */
  function Matrix2(column0Row0, column1Row0, column0Row1, column1Row1) {
    this[0] = defaultValue(column0Row0, 0.0);
    this[1] = defaultValue(column0Row1, 0.0);
    this[2] = defaultValue(column1Row0, 0.0);
    this[3] = defaultValue(column1Row1, 0.0);
  }

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  Matrix2.packedLength = 4;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {Matrix2} 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
   */
  Matrix2.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    array[startingIndex++] = value[0];
    array[startingIndex++] = value[1];
    array[startingIndex++] = value[2];
    array[startingIndex++] = value[3];

    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 {Matrix2} [result] The object into which to store the result.
   * @returns {Matrix2} The modified result parameter or a new Matrix2 instance if one was not provided.
   */
  Matrix2.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    if (!defined(result)) {
      result = new Matrix2();
    }

    result[0] = array[startingIndex++];
    result[1] = array[startingIndex++];
    result[2] = array[startingIndex++];
    result[3] = array[startingIndex++];
    return result;
  };

  /**
   * Flattens an array of Matrix2s into an array of components. The components
   * are stored in column-major order.
   *
   * @param {Matrix2[]} array The array of matrices to pack.
   * @param {Number[]} [result] The array onto which to store the result. If this is a typed array, it must have array.length * 4 components, else a {@link DeveloperError} will be thrown. If it is a regular array, it will be resized to have (array.length * 4) elements.
   * @returns {Number[]} The packed array.
   */
  Matrix2.packArray = function (array, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    const length = array.length;
    const resultLength = length * 4;
    if (!defined(result)) {
      result = new Array(resultLength);
    } else if (!Array.isArray(result) && result.length !== resultLength) {
      //>>includeStart('debug', pragmas.debug);
      throw new DeveloperError(
        "If result is a typed array, it must have exactly array.length * 4 elements"
      );
      //>>includeEnd('debug');
    } else if (result.length !== resultLength) {
      result.length = resultLength;
    }

    for (let i = 0; i < length; ++i) {
      Matrix2.pack(array[i], result, i * 4);
    }
    return result;
  };

  /**
   * Unpacks an array of column-major matrix components into an array of Matrix2s.
   *
   * @param {Number[]} array The array of components to unpack.
   * @param {Matrix2[]} [result] The array onto which to store the result.
   * @returns {Matrix2[]} The unpacked array.
   */
  Matrix2.unpackArray = function (array, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    Check.typeOf.number.greaterThanOrEquals("array.length", array.length, 4);
    if (array.length % 4 !== 0) {
      throw new DeveloperError("array length must be a multiple of 4.");
    }
    //>>includeEnd('debug');

    const length = array.length;
    if (!defined(result)) {
      result = new Array(length / 4);
    } else {
      result.length = length / 4;
    }

    for (let i = 0; i < length; i += 4) {
      const index = i / 4;
      result[index] = Matrix2.unpack(array, i, result[index]);
    }
    return result;
  };

  /**
   * Duplicates a Matrix2 instance.
   *
   * @param {Matrix2} matrix The matrix to duplicate.
   * @param {Matrix2} [result] The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter or a new Matrix2 instance if one was not provided. (Returns undefined if matrix is undefined)
   */
  Matrix2.clone = function (matrix, result) {
    if (!defined(matrix)) {
      return undefined;
    }
    if (!defined(result)) {
      return new Matrix2(matrix[0], matrix[2], matrix[1], matrix[3]);
    }
    result[0] = matrix[0];
    result[1] = matrix[1];
    result[2] = matrix[2];
    result[3] = matrix[3];
    return result;
  };

  /**
   * Creates a Matrix2 from 4 consecutive elements in an array.
   *
   * @function
   * @param {Number[]} array The array whose 4 consecutive elements correspond to the positions of the matrix.  Assumes column-major order.
   * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to first column first row position in the matrix.
   * @param {Matrix2} [result] The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter or a new Matrix2 instance if one was not provided.
   *
   * @example
   * // Create the Matrix2:
   * // [1.0, 2.0]
   * // [1.0, 2.0]
   *
   * const v = [1.0, 1.0, 2.0, 2.0];
   * const m = Cesium.Matrix2.fromArray(v);
   *
   * // Create same Matrix2 with using an offset into an array
   * const v2 = [0.0, 0.0, 1.0, 1.0, 2.0, 2.0];
   * const m2 = Cesium.Matrix2.fromArray(v2, 2);
   */
  Matrix2.fromArray = Matrix2.unpack;
  /**
   * Creates a Matrix2 instance from a column-major order array.
   *
   * @param {Number[]} values The column-major order array.
   * @param {Matrix2} [result] The object in which the result will be stored, if undefined a new instance will be created.
   * @returns {Matrix2} The modified result parameter, or a new Matrix2 instance if one was not provided.
   */
  Matrix2.fromColumnMajorArray = function (values, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("values", values);
    //>>includeEnd('debug');

    return Matrix2.clone(values, result);
  };

  /**
   * Creates a Matrix2 instance from a row-major order array.
   * The resulting matrix will be in column-major order.
   *
   * @param {Number[]} values The row-major order array.
   * @param {Matrix2} [result] The object in which the result will be stored, if undefined a new instance will be created.
   * @returns {Matrix2} The modified result parameter, or a new Matrix2 instance if one was not provided.
   */
  Matrix2.fromRowMajorArray = function (values, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("values", values);
    //>>includeEnd('debug');

    if (!defined(result)) {
      return new Matrix2(values[0], values[1], values[2], values[3]);
    }
    result[0] = values[0];
    result[1] = values[2];
    result[2] = values[1];
    result[3] = values[3];
    return result;
  };

  /**
   * Computes a Matrix2 instance representing a non-uniform scale.
   *
   * @param {Cartesian2} scale The x and y scale factors.
   * @param {Matrix2} [result] The object in which the result will be stored, if undefined a new instance will be created.
   * @returns {Matrix2} The modified result parameter, or a new Matrix2 instance if one was not provided.
   *
   * @example
   * // Creates
   * //   [7.0, 0.0]
   * //   [0.0, 8.0]
   * const m = Cesium.Matrix2.fromScale(new Cesium.Cartesian2(7.0, 8.0));
   */
  Matrix2.fromScale = function (scale, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("scale", scale);
    //>>includeEnd('debug');

    if (!defined(result)) {
      return new Matrix2(scale.x, 0.0, 0.0, scale.y);
    }

    result[0] = scale.x;
    result[1] = 0.0;
    result[2] = 0.0;
    result[3] = scale.y;
    return result;
  };

  /**
   * Computes a Matrix2 instance representing a uniform scale.
   *
   * @param {Number} scale The uniform scale factor.
   * @param {Matrix2} [result] The object in which the result will be stored, if undefined a new instance will be created.
   * @returns {Matrix2} The modified result parameter, or a new Matrix2 instance if one was not provided.
   *
   * @example
   * // Creates
   * //   [2.0, 0.0]
   * //   [0.0, 2.0]
   * const m = Cesium.Matrix2.fromUniformScale(2.0);
   */
  Matrix2.fromUniformScale = function (scale, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("scale", scale);
    //>>includeEnd('debug');

    if (!defined(result)) {
      return new Matrix2(scale, 0.0, 0.0, scale);
    }

    result[0] = scale;
    result[1] = 0.0;
    result[2] = 0.0;
    result[3] = scale;
    return result;
  };

  /**
   * Creates a rotation matrix.
   *
   * @param {Number} angle The angle, in radians, of the rotation.  Positive angles are counterclockwise.
   * @param {Matrix2} [result] The object in which the result will be stored, if undefined a new instance will be created.
   * @returns {Matrix2} The modified result parameter, or a new Matrix2 instance if one was not provided.
   *
   * @example
   * // Rotate a point 45 degrees counterclockwise.
   * const p = new Cesium.Cartesian2(5, 6);
   * const m = Cesium.Matrix2.fromRotation(Cesium.Math.toRadians(45.0));
   * const rotated = Cesium.Matrix2.multiplyByVector(m, p, new Cesium.Cartesian2());
   */
  Matrix2.fromRotation = function (angle, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("angle", angle);
    //>>includeEnd('debug');

    const cosAngle = Math.cos(angle);
    const sinAngle = Math.sin(angle);

    if (!defined(result)) {
      return new Matrix2(cosAngle, -sinAngle, sinAngle, cosAngle);
    }
    result[0] = cosAngle;
    result[1] = sinAngle;
    result[2] = -sinAngle;
    result[3] = cosAngle;
    return result;
  };

  /**
   * Creates an Array from the provided Matrix2 instance.
   * The array will be in column-major order.
   *
   * @param {Matrix2} matrix The matrix to use..
   * @param {Number[]} [result] The Array onto which to store the result.
   * @returns {Number[]} The modified Array parameter or a new Array instance if one was not provided.
   */
  Matrix2.toArray = function (matrix, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    //>>includeEnd('debug');

    if (!defined(result)) {
      return [matrix[0], matrix[1], matrix[2], matrix[3]];
    }
    result[0] = matrix[0];
    result[1] = matrix[1];
    result[2] = matrix[2];
    result[3] = matrix[3];
    return result;
  };

  /**
   * Computes the array index of the element at the provided row and column.
   *
   * @param {Number} row The zero-based index of the row.
   * @param {Number} column The zero-based index of the column.
   * @returns {Number} The index of the element at the provided row and column.
   *
   * @exception {DeveloperError} row must be 0 or 1.
   * @exception {DeveloperError} column must be 0 or 1.
   *
   * @example
   * const myMatrix = new Cesium.Matrix2();
   * const column1Row0Index = Cesium.Matrix2.getElementIndex(1, 0);
   * const column1Row0 = myMatrix[column1Row0Index]
   * myMatrix[column1Row0Index] = 10.0;
   */
  Matrix2.getElementIndex = function (column, row) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number.greaterThanOrEquals("row", row, 0);
    Check.typeOf.number.lessThanOrEquals("row", row, 1);

    Check.typeOf.number.greaterThanOrEquals("column", column, 0);
    Check.typeOf.number.lessThanOrEquals("column", column, 1);
    //>>includeEnd('debug');

    return column * 2 + row;
  };

  /**
   * Retrieves a copy of the matrix column at the provided index as a Cartesian2 instance.
   *
   * @param {Matrix2} matrix The matrix to use.
   * @param {Number} index The zero-based index of the column to retrieve.
   * @param {Cartesian2} result The object onto which to store the result.
   * @returns {Cartesian2} The modified result parameter.
   *
   * @exception {DeveloperError} index must be 0 or 1.
   */
  Matrix2.getColumn = function (matrix, index, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);

    Check.typeOf.number.greaterThanOrEquals("index", index, 0);
    Check.typeOf.number.lessThanOrEquals("index", index, 1);

    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const startIndex = index * 2;
    const x = matrix[startIndex];
    const y = matrix[startIndex + 1];

    result.x = x;
    result.y = y;
    return result;
  };

  /**
   * Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian2 instance.
   *
   * @param {Matrix2} matrix The matrix to use.
   * @param {Number} index The zero-based index of the column to set.
   * @param {Cartesian2} cartesian The Cartesian whose values will be assigned to the specified column.
   * @param {Cartesian2} result The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter.
   *
   * @exception {DeveloperError} index must be 0 or 1.
   */
  Matrix2.setColumn = function (matrix, index, cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);

    Check.typeOf.number.greaterThanOrEquals("index", index, 0);
    Check.typeOf.number.lessThanOrEquals("index", index, 1);

    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result = Matrix2.clone(matrix, result);
    const startIndex = index * 2;
    result[startIndex] = cartesian.x;
    result[startIndex + 1] = cartesian.y;
    return result;
  };

  /**
   * Retrieves a copy of the matrix row at the provided index as a Cartesian2 instance.
   *
   * @param {Matrix2} matrix The matrix to use.
   * @param {Number} index The zero-based index of the row to retrieve.
   * @param {Cartesian2} result The object onto which to store the result.
   * @returns {Cartesian2} The modified result parameter.
   *
   * @exception {DeveloperError} index must be 0 or 1.
   */
  Matrix2.getRow = function (matrix, index, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);

    Check.typeOf.number.greaterThanOrEquals("index", index, 0);
    Check.typeOf.number.lessThanOrEquals("index", index, 1);

    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const x = matrix[index];
    const y = matrix[index + 2];

    result.x = x;
    result.y = y;
    return result;
  };

  /**
   * Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian2 instance.
   *
   * @param {Matrix2} matrix The matrix to use.
   * @param {Number} index The zero-based index of the row to set.
   * @param {Cartesian2} cartesian The Cartesian whose values will be assigned to the specified row.
   * @param {Matrix2} result The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter.
   *
   * @exception {DeveloperError} index must be 0 or 1.
   */
  Matrix2.setRow = function (matrix, index, cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);

    Check.typeOf.number.greaterThanOrEquals("index", index, 0);
    Check.typeOf.number.lessThanOrEquals("index", index, 1);

    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result = Matrix2.clone(matrix, result);
    result[index] = cartesian.x;
    result[index + 2] = cartesian.y;
    return result;
  };

  const scaleScratch1 = new Cartesian2();

  /**
   * Computes a new matrix that replaces the scale with the provided scale.
   * This assumes the matrix is an affine transformation.
   *
   * @param {Matrix2} matrix The matrix to use.
   * @param {Cartesian2} scale The scale that replaces the scale of the provided matrix.
   * @param {Matrix2} result The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter.
   *
   * @see Matrix2.setUniformScale
   * @see Matrix2.fromScale
   * @see Matrix2.fromUniformScale
   * @see Matrix2.multiplyByScale
   * @see Matrix2.multiplyByUniformScale
   * @see Matrix2.getScale
   */
  Matrix2.setScale = function (matrix, scale, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("scale", scale);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const existingScale = Matrix2.getScale(matrix, scaleScratch1);
    const scaleRatioX = scale.x / existingScale.x;
    const scaleRatioY = scale.y / existingScale.y;

    result[0] = matrix[0] * scaleRatioX;
    result[1] = matrix[1] * scaleRatioX;
    result[2] = matrix[2] * scaleRatioY;
    result[3] = matrix[3] * scaleRatioY;

    return result;
  };

  const scaleScratch2 = new Cartesian2();

  /**
   * Computes a new matrix that replaces the scale with the provided uniform scale.
   * This assumes the matrix is an affine transformation.
   *
   * @param {Matrix2} matrix The matrix to use.
   * @param {Number} scale The uniform scale that replaces the scale of the provided matrix.
   * @param {Matrix2} result The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter.
   *
   * @see Matrix2.setScale
   * @see Matrix2.fromScale
   * @see Matrix2.fromUniformScale
   * @see Matrix2.multiplyByScale
   * @see Matrix2.multiplyByUniformScale
   * @see Matrix2.getScale
   */
  Matrix2.setUniformScale = function (matrix, scale, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.number("scale", scale);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const existingScale = Matrix2.getScale(matrix, scaleScratch2);
    const scaleRatioX = scale / existingScale.x;
    const scaleRatioY = scale / existingScale.y;

    result[0] = matrix[0] * scaleRatioX;
    result[1] = matrix[1] * scaleRatioX;
    result[2] = matrix[2] * scaleRatioY;
    result[3] = matrix[3] * scaleRatioY;

    return result;
  };

  const scratchColumn = new Cartesian2();

  /**
   * Extracts the non-uniform scale assuming the matrix is an affine transformation.
   *
   * @param {Matrix2} matrix The matrix.
   * @param {Cartesian2} result The object onto which to store the result.
   * @returns {Cartesian2} The modified result parameter.
   *
   * @see Matrix2.multiplyByScale
   * @see Matrix2.multiplyByUniformScale
   * @see Matrix2.fromScale
   * @see Matrix2.fromUniformScale
   * @see Matrix2.setScale
   * @see Matrix2.setUniformScale
   */
  Matrix2.getScale = function (matrix, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.x = Cartesian2.magnitude(
      Cartesian2.fromElements(matrix[0], matrix[1], scratchColumn)
    );
    result.y = Cartesian2.magnitude(
      Cartesian2.fromElements(matrix[2], matrix[3], scratchColumn)
    );
    return result;
  };

  const scaleScratch3 = new Cartesian2();

  /**
   * Computes the maximum scale assuming the matrix is an affine transformation.
   * The maximum scale is the maximum length of the column vectors.
   *
   * @param {Matrix2} matrix The matrix.
   * @returns {Number} The maximum scale.
   */
  Matrix2.getMaximumScale = function (matrix) {
    Matrix2.getScale(matrix, scaleScratch3);
    return Cartesian2.maximumComponent(scaleScratch3);
  };

  const scaleScratch4 = new Cartesian2();

  /**
   * Sets the rotation assuming the matrix is an affine transformation.
   *
   * @param {Matrix2} matrix The matrix.
   * @param {Matrix2} rotation The rotation matrix.
   * @returns {Matrix2} The modified result parameter.
   *
   * @see Matrix2.fromRotation
   * @see Matrix2.getRotation
   */
  Matrix2.setRotation = function (matrix, rotation, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const scale = Matrix2.getScale(matrix, scaleScratch4);

    result[0] = rotation[0] * scale.x;
    result[1] = rotation[1] * scale.x;
    result[2] = rotation[2] * scale.y;
    result[3] = rotation[3] * scale.y;

    return result;
  };

  const scaleScratch5 = new Cartesian2();

  /**
   * Extracts the rotation matrix assuming the matrix is an affine transformation.
   *
   * @param {Matrix2} matrix The matrix.
   * @param {Matrix2} result The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter.
   *
   * @see Matrix2.setRotation
   * @see Matrix2.fromRotation
   */
  Matrix2.getRotation = function (matrix, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const scale = Matrix2.getScale(matrix, scaleScratch5);

    result[0] = matrix[0] / scale.x;
    result[1] = matrix[1] / scale.x;
    result[2] = matrix[2] / scale.y;
    result[3] = matrix[3] / scale.y;

    return result;
  };

  /**
   * Computes the product of two matrices.
   *
   * @param {Matrix2} left The first matrix.
   * @param {Matrix2} right The second matrix.
   * @param {Matrix2} result The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter.
   */
  Matrix2.multiply = function (left, right, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const column0Row0 = left[0] * right[0] + left[2] * right[1];
    const column1Row0 = left[0] * right[2] + left[2] * right[3];
    const column0Row1 = left[1] * right[0] + left[3] * right[1];
    const column1Row1 = left[1] * right[2] + left[3] * right[3];

    result[0] = column0Row0;
    result[1] = column0Row1;
    result[2] = column1Row0;
    result[3] = column1Row1;
    return result;
  };

  /**
   * Computes the sum of two matrices.
   *
   * @param {Matrix2} left The first matrix.
   * @param {Matrix2} right The second matrix.
   * @param {Matrix2} result The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter.
   */
  Matrix2.add = function (left, right, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result[0] = left[0] + right[0];
    result[1] = left[1] + right[1];
    result[2] = left[2] + right[2];
    result[3] = left[3] + right[3];
    return result;
  };

  /**
   * Computes the difference of two matrices.
   *
   * @param {Matrix2} left The first matrix.
   * @param {Matrix2} right The second matrix.
   * @param {Matrix2} result The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter.
   */
  Matrix2.subtract = function (left, right, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result[0] = left[0] - right[0];
    result[1] = left[1] - right[1];
    result[2] = left[2] - right[2];
    result[3] = left[3] - right[3];
    return result;
  };

  /**
   * Computes the product of a matrix and a column vector.
   *
   * @param {Matrix2} matrix The matrix.
   * @param {Cartesian2} cartesian The column.
   * @param {Cartesian2} result The object onto which to store the result.
   * @returns {Cartesian2} The modified result parameter.
   */
  Matrix2.multiplyByVector = function (matrix, cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const x = matrix[0] * cartesian.x + matrix[2] * cartesian.y;
    const y = matrix[1] * cartesian.x + matrix[3] * cartesian.y;

    result.x = x;
    result.y = y;
    return result;
  };

  /**
   * Computes the product of a matrix and a scalar.
   *
   * @param {Matrix2} matrix The matrix.
   * @param {Number} scalar The number to multiply by.
   * @param {Matrix2} result The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter.
   */
  Matrix2.multiplyByScalar = function (matrix, scalar, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.number("scalar", scalar);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result[0] = matrix[0] * scalar;
    result[1] = matrix[1] * scalar;
    result[2] = matrix[2] * scalar;
    result[3] = matrix[3] * scalar;
    return result;
  };

  /**
   * Computes the product of a matrix times a (non-uniform) scale, as if the scale were a scale matrix.
   *
   * @param {Matrix2} matrix The matrix on the left-hand side.
   * @param {Number} scale The non-uniform scale on the right-hand side.
   * @param {Matrix2} result The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter.
   *
   *
   * @example
   * // Instead of Cesium.Matrix2.multiply(m, Cesium.Matrix2.fromScale(scale), m);
   * Cesium.Matrix2.multiplyByScale(m, scale, m);
   *
   * @see Matrix2.multiplyByUniformScale
   * @see Matrix2.fromScale
   * @see Matrix2.fromUniformScale
   * @see Matrix2.setScale
   * @see Matrix2.setUniformScale
   * @see Matrix2.getScale
   */
  Matrix2.multiplyByScale = function (matrix, scale, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("scale", scale);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result[0] = matrix[0] * scale.x;
    result[1] = matrix[1] * scale.x;
    result[2] = matrix[2] * scale.y;
    result[3] = matrix[3] * scale.y;

    return result;
  };

  /**
   * Computes the product of a matrix times a uniform scale, as if the scale were a scale matrix.
   *
   * @param {Matrix2} matrix The matrix on the left-hand side.
   * @param {Number} scale The uniform scale on the right-hand side.
   * @param {Matrix2} result The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter.
   *
   * @example
   * // Instead of Cesium.Matrix2.multiply(m, Cesium.Matrix2.fromUniformScale(scale), m);
   * Cesium.Matrix2.multiplyByUniformScale(m, scale, m);
   *
   * @see Matrix2.multiplyByScale
   * @see Matrix2.fromScale
   * @see Matrix2.fromUniformScale
   * @see Matrix2.setScale
   * @see Matrix2.setUniformScale
   * @see Matrix2.getScale
   */
  Matrix2.multiplyByUniformScale = function (matrix, scale, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.number("scale", scale);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result[0] = matrix[0] * scale;
    result[1] = matrix[1] * scale;
    result[2] = matrix[2] * scale;
    result[3] = matrix[3] * scale;

    return result;
  };

  /**
   * Creates a negated copy of the provided matrix.
   *
   * @param {Matrix2} matrix The matrix to negate.
   * @param {Matrix2} result The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter.
   */
  Matrix2.negate = function (matrix, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result[0] = -matrix[0];
    result[1] = -matrix[1];
    result[2] = -matrix[2];
    result[3] = -matrix[3];
    return result;
  };

  /**
   * Computes the transpose of the provided matrix.
   *
   * @param {Matrix2} matrix The matrix to transpose.
   * @param {Matrix2} result The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter.
   */
  Matrix2.transpose = function (matrix, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const column0Row0 = matrix[0];
    const column0Row1 = matrix[2];
    const column1Row0 = matrix[1];
    const column1Row1 = matrix[3];

    result[0] = column0Row0;
    result[1] = column0Row1;
    result[2] = column1Row0;
    result[3] = column1Row1;
    return result;
  };

  /**
   * Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
   *
   * @param {Matrix2} matrix The matrix with signed elements.
   * @param {Matrix2} result The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter.
   */
  Matrix2.abs = function (matrix, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("matrix", matrix);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result[0] = Math.abs(matrix[0]);
    result[1] = Math.abs(matrix[1]);
    result[2] = Math.abs(matrix[2]);
    result[3] = Math.abs(matrix[3]);

    return result;
  };

  /**
   * Compares the provided matrices componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Matrix2} [left] The first matrix.
   * @param {Matrix2} [right] The second matrix.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  Matrix2.equals = function (left, right) {
    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        left[0] === right[0] &&
        left[1] === right[1] &&
        left[2] === right[2] &&
        left[3] === right[3])
    );
  };

  /**
   * @private
   */
  Matrix2.equalsArray = function (matrix, array, offset) {
    return (
      matrix[0] === array[offset] &&
      matrix[1] === array[offset + 1] &&
      matrix[2] === array[offset + 2] &&
      matrix[3] === array[offset + 3]
    );
  };

  /**
   * Compares the provided matrices componentwise and returns
   * <code>true</code> if they are within the provided epsilon,
   * <code>false</code> otherwise.
   *
   * @param {Matrix2} [left] The first matrix.
   * @param {Matrix2} [right] The second matrix.
   * @param {Number} [epsilon=0] The epsilon to use for equality testing.
   * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
   */
  Matrix2.equalsEpsilon = function (left, right, epsilon) {
    epsilon = defaultValue(epsilon, 0);
    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        Math.abs(left[0] - right[0]) <= epsilon &&
        Math.abs(left[1] - right[1]) <= epsilon &&
        Math.abs(left[2] - right[2]) <= epsilon &&
        Math.abs(left[3] - right[3]) <= epsilon)
    );
  };

  /**
   * An immutable Matrix2 instance initialized to the identity matrix.
   *
   * @type {Matrix2}
   * @constant
   */
  Matrix2.IDENTITY = Object.freeze(new Matrix2(1.0, 0.0, 0.0, 1.0));

  /**
   * An immutable Matrix2 instance initialized to the zero matrix.
   *
   * @type {Matrix2}
   * @constant
   */
  Matrix2.ZERO = Object.freeze(new Matrix2(0.0, 0.0, 0.0, 0.0));

  /**
   * The index into Matrix2 for column 0, row 0.
   *
   * @type {Number}
   * @constant
   *
   * @example
   * const matrix = new Cesium.Matrix2();
   * matrix[Cesium.Matrix2.COLUMN0ROW0] = 5.0; // set column 0, row 0 to 5.0
   */
  Matrix2.COLUMN0ROW0 = 0;

  /**
   * The index into Matrix2 for column 0, row 1.
   *
   * @type {Number}
   * @constant
   *
   * @example
   * const matrix = new Cesium.Matrix2();
   * matrix[Cesium.Matrix2.COLUMN0ROW1] = 5.0; // set column 0, row 1 to 5.0
   */
  Matrix2.COLUMN0ROW1 = 1;

  /**
   * The index into Matrix2 for column 1, row 0.
   *
   * @type {Number}
   * @constant
   *
   * @example
   * const matrix = new Cesium.Matrix2();
   * matrix[Cesium.Matrix2.COLUMN1ROW0] = 5.0; // set column 1, row 0 to 5.0
   */
  Matrix2.COLUMN1ROW0 = 2;

  /**
   * The index into Matrix2 for column 1, row 1.
   *
   * @type {Number}
   * @constant
   *
   * @example
   * const matrix = new Cesium.Matrix2();
   * matrix[Cesium.Matrix2.COLUMN1ROW1] = 5.0; // set column 1, row 1 to 5.0
   */
  Matrix2.COLUMN1ROW1 = 3;

  Object.defineProperties(Matrix2.prototype, {
    /**
     * Gets the number of items in the collection.
     * @memberof Matrix2.prototype
     *
     * @type {Number}
     */
    length: {
      get: function () {
        return Matrix2.packedLength;
      },
    },
  });

  /**
   * Duplicates the provided Matrix2 instance.
   *
   * @param {Matrix2} [result] The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter or a new Matrix2 instance if one was not provided.
   */
  Matrix2.prototype.clone = function (result) {
    return Matrix2.clone(this, result);
  };

  /**
   * Compares this matrix to the provided matrix componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Matrix2} [right] The right hand side matrix.
   * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
   */
  Matrix2.prototype.equals = function (right) {
    return Matrix2.equals(this, right);
  };

  /**
   * Compares this matrix to the provided matrix componentwise and returns
   * <code>true</code> if they are within the provided epsilon,
   * <code>false</code> otherwise.
   *
   * @param {Matrix2} [right] The right hand side matrix.
   * @param {Number} [epsilon=0] The epsilon to use for equality testing.
   * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
   */
  Matrix2.prototype.equalsEpsilon = function (right, epsilon) {
    return Matrix2.equalsEpsilon(this, right, epsilon);
  };

  /**
   * Creates a string representing this Matrix with each row being
   * on a separate line and in the format '(column0, column1)'.
   *
   * @returns {String} A string representing the provided Matrix with each row being on a separate line and in the format '(column0, column1)'.
   */
  Matrix2.prototype.toString = function () {
    return `(${this[0]}, ${this[2]})\n` + `(${this[1]}, ${this[3]})`;
  };

  /**
   * An enum describing the attribute type for glTF and 3D Tiles.
   *
   * @enum {String}
   *
   * @private
   */
  const AttributeType = {
    /**
     * The attribute is a single component.
     *
     * @type {String}
     * @constant
     */
    SCALAR: "SCALAR",

    /**
     * The attribute is a two-component vector.
     *
     * @type {String}
     * @constant
     */
    VEC2: "VEC2",

    /**
     * The attribute is a three-component vector.
     *
     * @type {String}
     * @constant
     */
    VEC3: "VEC3",

    /**
     * The attribute is a four-component vector.
     *
     * @type {String}
     * @constant
     */
    VEC4: "VEC4",

    /**
     * The attribute is a 2x2 matrix.
     *
     * @type {String}
     * @constant
     */
    MAT2: "MAT2",

    /**
     * The attribute is a 3x3 matrix.
     *
     * @type {String}
     * @constant
     */
    MAT3: "MAT3",

    /**
     * The attribute is a 4x4 matrix.
     *
     * @type {String}
     * @constant
     */
    MAT4: "MAT4",
  };

  /**
   * Gets the scalar, vector, or matrix type for the attribute type.
   *
   * @param {AttributeType} attributeType The attribute type.
   * @returns {*} The math type.
   *
   * @private
   */
  AttributeType.getMathType = function (attributeType) {
    switch (attributeType) {
      case AttributeType.SCALAR:
        return Number;
      case AttributeType.VEC2:
        return Cartesian2;
      case AttributeType.VEC3:
        return Cartesian3;
      case AttributeType.VEC4:
        return Cartesian4;
      case AttributeType.MAT2:
        return Matrix2;
      case AttributeType.MAT3:
        return Matrix3;
      case AttributeType.MAT4:
        return Matrix4;
      //>>includeStart('debug', pragmas.debug);
      default:
        throw new DeveloperError("attributeType is not a valid value.");
      //>>includeEnd('debug');
    }
  };

  /**
   * Gets the number of components per attribute.
   *
   * @param {AttributeType} attributeType The attribute type.
   * @returns {Number} The number of components.
   *
   * @private
   */
  AttributeType.getNumberOfComponents = function (attributeType) {
    switch (attributeType) {
      case AttributeType.SCALAR:
        return 1;
      case AttributeType.VEC2:
        return 2;
      case AttributeType.VEC3:
        return 3;
      case AttributeType.VEC4:
      case AttributeType.MAT2:
        return 4;
      case AttributeType.MAT3:
        return 9;
      case AttributeType.MAT4:
        return 16;
      //>>includeStart('debug', pragmas.debug);
      default:
        throw new DeveloperError("attributeType is not a valid value.");
      //>>includeEnd('debug');
    }
  };

  /**
   * Get the number of attribute locations needed to fit this attribute. Most
   * types require one, but matrices require multiple attribute locations.
   *
   * @param {AttributeType} attributeType The attribute type.
   * @returns {Number} The number of attribute locations needed in the shader
   *
   * @private
   */
  AttributeType.getAttributeLocationCount = function (attributeType) {
    switch (attributeType) {
      case AttributeType.SCALAR:
      case AttributeType.VEC2:
      case AttributeType.VEC3:
      case AttributeType.VEC4:
        return 1;
      case AttributeType.MAT2:
        return 2;
      case AttributeType.MAT3:
        return 3;
      case AttributeType.MAT4:
        return 4;
      //>>includeStart('debug', pragmas.debug);
      default:
        throw new DeveloperError("attributeType is not a valid value.");
      //>>includeEnd('debug');
    }
  };

  /**
   * Gets the GLSL type for the attribute type.
   *
   * @param {AttributeType} attributeType The attribute type.
   * @returns {String} The GLSL type for the attribute type.
   *
   * @private
   */
  AttributeType.getGlslType = function (attributeType) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("attributeType", attributeType);
    //>>includeEnd('debug');

    switch (attributeType) {
      case AttributeType.SCALAR:
        return "float";
      case AttributeType.VEC2:
        return "vec2";
      case AttributeType.VEC3:
        return "vec3";
      case AttributeType.VEC4:
        return "vec4";
      case AttributeType.MAT2:
        return "mat2";
      case AttributeType.MAT3:
        return "mat3";
      case AttributeType.MAT4:
        return "mat4";
      //>>includeStart('debug', pragmas.debug);
      default:
        throw new DeveloperError("attributeType is not a valid value.");
      //>>includeEnd('debug');
    }
  };

  var AttributeType$1 = Object.freeze(AttributeType);

  const RIGHT_SHIFT = 1.0 / 256.0;
  const LEFT_SHIFT = 256.0;

  /**
   * Attribute compression and decompression functions.
   *
   * @namespace AttributeCompression
   *
   * @private
   */
  const AttributeCompression = {};

  /**
   * Encodes a normalized vector into 2 SNORM values in the range of [0-rangeMax] following the 'oct' encoding.
   *
   * Oct encoding is a compact representation of unit length vectors.
   * The 'oct' encoding is described in "A Survey of Efficient Representations of Independent Unit Vectors",
   * Cigolle et al 2014: {@link http://jcgt.org/published/0003/02/01/}
   *
   * @param {Cartesian3} vector The normalized vector to be compressed into 2 component 'oct' encoding.
   * @param {Cartesian2} result The 2 component oct-encoded unit length vector.
   * @param {Number} rangeMax The maximum value of the SNORM range. The encoded vector is stored in log2(rangeMax+1) bits.
   * @returns {Cartesian2} The 2 component oct-encoded unit length vector.
   *
   * @exception {DeveloperError} vector must be normalized.
   *
   * @see AttributeCompression.octDecodeInRange
   */
  AttributeCompression.octEncodeInRange = function (vector, rangeMax, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("vector", vector);
    Check.defined("result", result);
    const magSquared = Cartesian3.magnitudeSquared(vector);
    if (Math.abs(magSquared - 1.0) > CesiumMath.EPSILON6) {
      throw new DeveloperError("vector must be normalized.");
    }
    //>>includeEnd('debug');

    result.x =
      vector.x / (Math.abs(vector.x) + Math.abs(vector.y) + Math.abs(vector.z));
    result.y =
      vector.y / (Math.abs(vector.x) + Math.abs(vector.y) + Math.abs(vector.z));
    if (vector.z < 0) {
      const x = result.x;
      const y = result.y;
      result.x = (1.0 - Math.abs(y)) * CesiumMath.signNotZero(x);
      result.y = (1.0 - Math.abs(x)) * CesiumMath.signNotZero(y);
    }

    result.x = CesiumMath.toSNorm(result.x, rangeMax);
    result.y = CesiumMath.toSNorm(result.y, rangeMax);

    return result;
  };

  /**
   * Encodes a normalized vector into 2 SNORM values in the range of [0-255] following the 'oct' encoding.
   *
   * @param {Cartesian3} vector The normalized vector to be compressed into 2 byte 'oct' encoding.
   * @param {Cartesian2} result The 2 byte oct-encoded unit length vector.
   * @returns {Cartesian2} The 2 byte oct-encoded unit length vector.
   *
   * @exception {DeveloperError} vector must be normalized.
   *
   * @see AttributeCompression.octEncodeInRange
   * @see AttributeCompression.octDecode
   */
  AttributeCompression.octEncode = function (vector, result) {
    return AttributeCompression.octEncodeInRange(vector, 255, result);
  };

  const octEncodeScratch = new Cartesian2();
  const uint8ForceArray = new Uint8Array(1);
  function forceUint8(value) {
    uint8ForceArray[0] = value;
    return uint8ForceArray[0];
  }
  /**
   * @param {Cartesian3} vector The normalized vector to be compressed into 4 byte 'oct' encoding.
   * @param {Cartesian4} result The 4 byte oct-encoded unit length vector.
   * @returns {Cartesian4} The 4 byte oct-encoded unit length vector.
   *
   * @exception {DeveloperError} vector must be normalized.
   *
   * @see AttributeCompression.octEncodeInRange
   * @see AttributeCompression.octDecodeFromCartesian4
   */
  AttributeCompression.octEncodeToCartesian4 = function (vector, result) {
    AttributeCompression.octEncodeInRange(vector, 65535, octEncodeScratch);
    result.x = forceUint8(octEncodeScratch.x * RIGHT_SHIFT);
    result.y = forceUint8(octEncodeScratch.x);
    result.z = forceUint8(octEncodeScratch.y * RIGHT_SHIFT);
    result.w = forceUint8(octEncodeScratch.y);
    return result;
  };

  /**
   * Decodes a unit-length vector in 'oct' encoding to a normalized 3-component vector.
   *
   * @param {Number} x The x component of the oct-encoded unit length vector.
   * @param {Number} y The y component of the oct-encoded unit length vector.
   * @param {Number} rangeMax The maximum value of the SNORM range. The encoded vector is stored in log2(rangeMax+1) bits.
   * @param {Cartesian3} result The decoded and normalized vector
   * @returns {Cartesian3} The decoded and normalized vector.
   *
   * @exception {DeveloperError} x and y must be unsigned normalized integers between 0 and rangeMax.
   *
   * @see AttributeCompression.octEncodeInRange
   */
  AttributeCompression.octDecodeInRange = function (x, y, rangeMax, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("result", result);
    if (x < 0 || x > rangeMax || y < 0 || y > rangeMax) {
      throw new DeveloperError(
        `x and y must be unsigned normalized integers between 0 and ${rangeMax}`
      );
    }
    //>>includeEnd('debug');

    result.x = CesiumMath.fromSNorm(x, rangeMax);
    result.y = CesiumMath.fromSNorm(y, rangeMax);
    result.z = 1.0 - (Math.abs(result.x) + Math.abs(result.y));

    if (result.z < 0.0) {
      const oldVX = result.x;
      result.x = (1.0 - Math.abs(result.y)) * CesiumMath.signNotZero(oldVX);
      result.y = (1.0 - Math.abs(oldVX)) * CesiumMath.signNotZero(result.y);
    }

    return Cartesian3.normalize(result, result);
  };

  /**
   * Decodes a unit-length vector in 2 byte 'oct' encoding to a normalized 3-component vector.
   *
   * @param {Number} x The x component of the oct-encoded unit length vector.
   * @param {Number} y The y component of the oct-encoded unit length vector.
   * @param {Cartesian3} result The decoded and normalized vector.
   * @returns {Cartesian3} The decoded and normalized vector.
   *
   * @exception {DeveloperError} x and y must be an unsigned normalized integer between 0 and 255.
   *
   * @see AttributeCompression.octDecodeInRange
   */
  AttributeCompression.octDecode = function (x, y, result) {
    return AttributeCompression.octDecodeInRange(x, y, 255, result);
  };

  /**
   * Decodes a unit-length vector in 4 byte 'oct' encoding to a normalized 3-component vector.
   *
   * @param {Cartesian4} encoded The oct-encoded unit length vector.
   * @param {Cartesian3} result The decoded and normalized vector.
   * @returns {Cartesian3} The decoded and normalized vector.
   *
   * @exception {DeveloperError} x, y, z, and w must be unsigned normalized integers between 0 and 255.
   *
   * @see AttributeCompression.octDecodeInRange
   * @see AttributeCompression.octEncodeToCartesian4
   */
  AttributeCompression.octDecodeFromCartesian4 = function (encoded, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("encoded", encoded);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');
    const x = encoded.x;
    const y = encoded.y;
    const z = encoded.z;
    const w = encoded.w;
    //>>includeStart('debug', pragmas.debug);
    if (
      x < 0 ||
      x > 255 ||
      y < 0 ||
      y > 255 ||
      z < 0 ||
      z > 255 ||
      w < 0 ||
      w > 255
    ) {
      throw new DeveloperError(
        "x, y, z, and w must be unsigned normalized integers between 0 and 255"
      );
    }
    //>>includeEnd('debug');

    const xOct16 = x * LEFT_SHIFT + y;
    const yOct16 = z * LEFT_SHIFT + w;
    return AttributeCompression.octDecodeInRange(xOct16, yOct16, 65535, result);
  };

  /**
   * Packs an oct encoded vector into a single floating-point number.
   *
   * @param {Cartesian2} encoded The oct encoded vector.
   * @returns {Number} The oct encoded vector packed into a single float.
   *
   */
  AttributeCompression.octPackFloat = function (encoded) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("encoded", encoded);
    //>>includeEnd('debug');
    return 256.0 * encoded.x + encoded.y;
  };

  const scratchEncodeCart2 = new Cartesian2();

  /**
   * Encodes a normalized vector into 2 SNORM values in the range of [0-255] following the 'oct' encoding and
   * stores those values in a single float-point number.
   *
   * @param {Cartesian3} vector The normalized vector to be compressed into 2 byte 'oct' encoding.
   * @returns {Number} The 2 byte oct-encoded unit length vector.
   *
   * @exception {DeveloperError} vector must be normalized.
   */
  AttributeCompression.octEncodeFloat = function (vector) {
    AttributeCompression.octEncode(vector, scratchEncodeCart2);
    return AttributeCompression.octPackFloat(scratchEncodeCart2);
  };

  /**
   * Decodes a unit-length vector in 'oct' encoding packed in a floating-point number to a normalized 3-component vector.
   *
   * @param {Number} value The oct-encoded unit length vector stored as a single floating-point number.
   * @param {Cartesian3} result The decoded and normalized vector
   * @returns {Cartesian3} The decoded and normalized vector.
   *
   */
  AttributeCompression.octDecodeFloat = function (value, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("value", value);
    //>>includeEnd('debug');

    const temp = value / 256.0;
    const x = Math.floor(temp);
    const y = (temp - x) * 256.0;

    return AttributeCompression.octDecode(x, y, result);
  };

  /**
   * Encodes three normalized vectors into 6 SNORM values in the range of [0-255] following the 'oct' encoding and
   * packs those into two floating-point numbers.
   *
   * @param {Cartesian3} v1 A normalized vector to be compressed.
   * @param {Cartesian3} v2 A normalized vector to be compressed.
   * @param {Cartesian3} v3 A normalized vector to be compressed.
   * @param {Cartesian2} result The 'oct' encoded vectors packed into two floating-point numbers.
   * @returns {Cartesian2} The 'oct' encoded vectors packed into two floating-point numbers.
   *
   */
  AttributeCompression.octPack = function (v1, v2, v3, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("v1", v1);
    Check.defined("v2", v2);
    Check.defined("v3", v3);
    Check.defined("result", result);
    //>>includeEnd('debug');

    const encoded1 = AttributeCompression.octEncodeFloat(v1);
    const encoded2 = AttributeCompression.octEncodeFloat(v2);

    const encoded3 = AttributeCompression.octEncode(v3, scratchEncodeCart2);
    result.x = 65536.0 * encoded3.x + encoded1;
    result.y = 65536.0 * encoded3.y + encoded2;
    return result;
  };

  /**
   * Decodes three unit-length vectors in 'oct' encoding packed into a floating-point number to a normalized 3-component vector.
   *
   * @param {Cartesian2} packed The three oct-encoded unit length vectors stored as two floating-point number.
   * @param {Cartesian3} v1 One decoded and normalized vector.
   * @param {Cartesian3} v2 One decoded and normalized vector.
   * @param {Cartesian3} v3 One decoded and normalized vector.
   */
  AttributeCompression.octUnpack = function (packed, v1, v2, v3) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("packed", packed);
    Check.defined("v1", v1);
    Check.defined("v2", v2);
    Check.defined("v3", v3);
    //>>includeEnd('debug');

    let temp = packed.x / 65536.0;
    const x = Math.floor(temp);
    const encodedFloat1 = (temp - x) * 65536.0;

    temp = packed.y / 65536.0;
    const y = Math.floor(temp);
    const encodedFloat2 = (temp - y) * 65536.0;

    AttributeCompression.octDecodeFloat(encodedFloat1, v1);
    AttributeCompression.octDecodeFloat(encodedFloat2, v2);
    AttributeCompression.octDecode(x, y, v3);
  };

  /**
   * Pack texture coordinates into a single float. The texture coordinates will only preserve 12 bits of precision.
   *
   * @param {Cartesian2} textureCoordinates The texture coordinates to compress.  Both coordinates must be in the range 0.0-1.0.
   * @returns {Number} The packed texture coordinates.
   *
   */
  AttributeCompression.compressTextureCoordinates = function (
    textureCoordinates
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("textureCoordinates", textureCoordinates);
    //>>includeEnd('debug');

    // Move x and y to the range 0-4095;
    const x = (textureCoordinates.x * 4095.0) | 0;
    const y = (textureCoordinates.y * 4095.0) | 0;
    return 4096.0 * x + y;
  };

  /**
   * Decompresses texture coordinates that were packed into a single float.
   *
   * @param {Number} compressed The compressed texture coordinates.
   * @param {Cartesian2} result The decompressed texture coordinates.
   * @returns {Cartesian2} The modified result parameter.
   *
   */
  AttributeCompression.decompressTextureCoordinates = function (
    compressed,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("compressed", compressed);
    Check.defined("result", result);
    //>>includeEnd('debug');

    const temp = compressed / 4096.0;
    const xZeroTo4095 = Math.floor(temp);
    result.x = xZeroTo4095 / 4095.0;
    result.y = (compressed - xZeroTo4095 * 4096) / 4095;
    return result;
  };

  function zigZagDecode(value) {
    return (value >> 1) ^ -(value & 1);
  }

  /**
   * Decodes delta and ZigZag encoded vertices. This modifies the buffers in place.
   *
   * @param {Uint16Array} uBuffer The buffer view of u values.
   * @param {Uint16Array} vBuffer The buffer view of v values.
   * @param {Uint16Array} [heightBuffer] The buffer view of height values.
   *
   * @see {@link https://github.com/CesiumGS/quantized-mesh|quantized-mesh-1.0 terrain format}
   */
  AttributeCompression.zigZagDeltaDecode = function (
    uBuffer,
    vBuffer,
    heightBuffer
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("uBuffer", uBuffer);
    Check.defined("vBuffer", vBuffer);
    Check.typeOf.number.equals(
      "uBuffer.length",
      "vBuffer.length",
      uBuffer.length,
      vBuffer.length
    );
    if (defined(heightBuffer)) {
      Check.typeOf.number.equals(
        "uBuffer.length",
        "heightBuffer.length",
        uBuffer.length,
        heightBuffer.length
      );
    }
    //>>includeEnd('debug');

    const count = uBuffer.length;

    let u = 0;
    let v = 0;
    let height = 0;

    for (let i = 0; i < count; ++i) {
      u += zigZagDecode(uBuffer[i]);
      v += zigZagDecode(vBuffer[i]);

      uBuffer[i] = u;
      vBuffer[i] = v;

      if (defined(heightBuffer)) {
        height += zigZagDecode(heightBuffer[i]);
        heightBuffer[i] = height;
      }
    }
  };

  /**
   * Dequantizes a quantized typed array into a floating point typed array.
   *
   * @see {@link https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization#encoding-quantized-data}
   *
   * @param {Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array} typedArray The typed array for the quantized data.
   * @param {ComponentDatatype} componentDatatype The component datatype of the quantized data.
   * @param {AttributeType} type The attribute type of the quantized data.
   * @param {Number} count The number of attributes referenced in the dequantized array.
   *
   * @returns {Float32Array} The dequantized array.
   */
  AttributeCompression.dequantize = function (
    typedArray,
    componentDatatype,
    type,
    count
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("typedArray", typedArray);
    Check.defined("componentDatatype", componentDatatype);
    Check.defined("type", type);
    Check.defined("count", count);
    //>>includeEnd('debug');

    const componentsPerAttribute = AttributeType$1.getNumberOfComponents(type);

    let divisor;
    switch (componentDatatype) {
      case ComponentDatatype$1.BYTE:
        divisor = 127.0;
        break;
      case ComponentDatatype$1.UNSIGNED_BYTE:
        divisor = 255.0;
        break;
      case ComponentDatatype$1.SHORT:
        divisor = 32767.0;
        break;
      case ComponentDatatype$1.UNSIGNED_SHORT:
        divisor = 65535.0;
        break;
      case ComponentDatatype$1.INT:
        divisor = 2147483647.0;
        break;
      case ComponentDatatype$1.UNSIGNED_INT:
        divisor = 4294967295.0;
        break;
      //>>includeStart('debug', pragmas.debug);
      default:
        throw new DeveloperError(
          `Cannot dequantize component datatype: ${componentDatatype}`
        );
      //>>includeEnd('debug');
    }

    const dequantizedTypedArray = new Float32Array(
      count * componentsPerAttribute
    );

    for (let i = 0; i < count; i++) {
      for (let j = 0; j < componentsPerAttribute; j++) {
        const index = i * componentsPerAttribute + j;
        dequantizedTypedArray[index] = Math.max(
          typedArray[index] / divisor,
          -1.0
        );
      }
    }

    return dequantizedTypedArray;
  };

  /**
   * Decode RGB565-encoded colors into a floating point typed array containing
   * normalized RGB values.
   *
   * @param {Uint16Array} typedArray Array of RGB565 values
   * @param {Float32Array} [result] Array to store the normalized VEC3 result
   */
  AttributeCompression.decodeRGB565 = function (typedArray, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("typedArray", typedArray);

    const expectedLength = typedArray.length * 3;
    if (defined(result)) {
      Check.typeOf.number.equals(
        "result.length",
        "typedArray.length * 3",
        result.length,
        expectedLength
      );
    }
    //>>includeEnd('debug');

    const count = typedArray.length;
    if (!defined(result)) {
      result = new Float32Array(count * 3);
    }

    const mask5 = (1 << 5) - 1;
    const mask6 = (1 << 6) - 1;
    const normalize5 = 1.0 / 31.0;
    const normalize6 = 1.0 / 63.0;
    for (let i = 0; i < count; i++) {
      const value = typedArray[i];
      const red = value >> 11;
      const green = (value >> 5) & mask6;
      const blue = value & mask5;

      const offset = 3 * i;
      result[offset] = red * normalize5;
      result[offset + 1] = green * normalize6;
      result[offset + 2] = blue * normalize5;
    }

    return result;
  };

  /**
   * @private
   */
  const TerrainExaggeration = {};

  /**
   * Scales a height relative to an offset.
   *
   * @param {Number} height The height.
   * @param {Number} scale A scalar used to exaggerate the terrain. If the value is 1.0 there will be no effect.
   * @param {Number} relativeHeight The height relative to which terrain is exaggerated. If the value is 0.0 terrain will be exaggerated relative to the ellipsoid surface.
   */
  TerrainExaggeration.getHeight = function (height, scale, relativeHeight) {
    return (height - relativeHeight) * scale + relativeHeight;
  };

  const scratchCartographic$h = new Cartesian3();

  /**
   * Scales a position by exaggeration.
   */
  TerrainExaggeration.getPosition = function (
    position,
    ellipsoid,
    terrainExaggeration,
    terrainExaggerationRelativeHeight,
    result
  ) {
    const cartographic = ellipsoid.cartesianToCartographic(
      position,
      scratchCartographic$h
    );
    const newHeight = TerrainExaggeration.getHeight(
      cartographic.height,
      terrainExaggeration,
      terrainExaggerationRelativeHeight
    );
    return Cartesian3.fromRadians(
      cartographic.longitude,
      cartographic.latitude,
      newHeight,
      ellipsoid,
      result
    );
  };

  /**
   * This enumerated type is used to determine how the vertices of the terrain mesh are compressed.
   *
   * @enum {Number}
   *
   * @private
   */
  const TerrainQuantization = {
    /**
     * The vertices are not compressed.
     *
     * @type {Number}
     * @constant
     */
    NONE: 0,

    /**
     * The vertices are compressed to 12 bits.
     *
     * @type {Number}
     * @constant
     */
    BITS12: 1,
  };
  var TerrainQuantization$1 = Object.freeze(TerrainQuantization);

  const cartesian3Scratch$3 = new Cartesian3();
  const cartesian3DimScratch = new Cartesian3();
  const cartesian2Scratch = new Cartesian2();
  const matrix4Scratch$1 = new Matrix4();
  const matrix4Scratch2 = new Matrix4();

  const SHIFT_LEFT_12 = Math.pow(2.0, 12.0);

  /**
   * Data used to quantize and pack the terrain mesh. The position can be unpacked for picking and all attributes
   * are unpacked in the vertex shader.
   *
   * @alias TerrainEncoding
   * @constructor
   *
   * @param {Cartesian3} center The center point of the vertices.
   * @param {AxisAlignedBoundingBox} axisAlignedBoundingBox The bounds of the tile in the east-north-up coordinates at the tiles center.
   * @param {Number} minimumHeight The minimum height.
   * @param {Number} maximumHeight The maximum height.
   * @param {Matrix4} fromENU The east-north-up to fixed frame matrix at the center of the terrain mesh.
   * @param {Boolean} hasVertexNormals If the mesh has vertex normals.
   * @param {Boolean} [hasWebMercatorT=false] true if the terrain data includes a Web Mercator texture coordinate; otherwise, false.
   * @param {Boolean} [hasGeodeticSurfaceNormals=false] true if the terrain data includes geodetic surface normals; otherwise, false.
   * @param {Number} [exaggeration=1.0] A scalar used to exaggerate terrain.
   * @param {Number} [exaggerationRelativeHeight=0.0] The relative height from which terrain is exaggerated.
   *
   * @private
   */
  function TerrainEncoding(
    center,
    axisAlignedBoundingBox,
    minimumHeight,
    maximumHeight,
    fromENU,
    hasVertexNormals,
    hasWebMercatorT,
    hasGeodeticSurfaceNormals,
    exaggeration,
    exaggerationRelativeHeight
  ) {
    let quantization = TerrainQuantization$1.NONE;
    let toENU;
    let matrix;

    if (
      defined(axisAlignedBoundingBox) &&
      defined(minimumHeight) &&
      defined(maximumHeight) &&
      defined(fromENU)
    ) {
      const minimum = axisAlignedBoundingBox.minimum;
      const maximum = axisAlignedBoundingBox.maximum;

      const dimensions = Cartesian3.subtract(
        maximum,
        minimum,
        cartesian3DimScratch
      );
      const hDim = maximumHeight - minimumHeight;
      const maxDim = Math.max(Cartesian3.maximumComponent(dimensions), hDim);

      if (maxDim < SHIFT_LEFT_12 - 1.0) {
        quantization = TerrainQuantization$1.BITS12;
      } else {
        quantization = TerrainQuantization$1.NONE;
      }

      toENU = Matrix4.inverseTransformation(fromENU, new Matrix4());

      const translation = Cartesian3.negate(minimum, cartesian3Scratch$3);
      Matrix4.multiply(
        Matrix4.fromTranslation(translation, matrix4Scratch$1),
        toENU,
        toENU
      );

      const scale = cartesian3Scratch$3;
      scale.x = 1.0 / dimensions.x;
      scale.y = 1.0 / dimensions.y;
      scale.z = 1.0 / dimensions.z;
      Matrix4.multiply(Matrix4.fromScale(scale, matrix4Scratch$1), toENU, toENU);

      matrix = Matrix4.clone(fromENU);
      Matrix4.setTranslation(matrix, Cartesian3.ZERO, matrix);

      fromENU = Matrix4.clone(fromENU, new Matrix4());

      const translationMatrix = Matrix4.fromTranslation(minimum, matrix4Scratch$1);
      const scaleMatrix = Matrix4.fromScale(dimensions, matrix4Scratch2);
      const st = Matrix4.multiply(translationMatrix, scaleMatrix, matrix4Scratch$1);

      Matrix4.multiply(fromENU, st, fromENU);
      Matrix4.multiply(matrix, st, matrix);
    }

    /**
     * How the vertices of the mesh were compressed.
     * @type {TerrainQuantization}
     */
    this.quantization = quantization;

    /**
     * The minimum height of the tile including the skirts.
     * @type {Number}
     */
    this.minimumHeight = minimumHeight;

    /**
     * The maximum height of the tile.
     * @type {Number}
     */
    this.maximumHeight = maximumHeight;

    /**
     * The center of the tile.
     * @type {Cartesian3}
     */
    this.center = Cartesian3.clone(center);

    /**
     * A matrix that takes a vertex from the tile, transforms it to east-north-up at the center and scales
     * it so each component is in the [0, 1] range.
     * @type {Matrix4}
     */
    this.toScaledENU = toENU;

    /**
     * A matrix that restores a vertex transformed with toScaledENU back to the earth fixed reference frame
     * @type {Matrix4}
     */
    this.fromScaledENU = fromENU;

    /**
     * The matrix used to decompress the terrain vertices in the shader for RTE rendering.
     * @type {Matrix4}
     */
    this.matrix = matrix;

    /**
     * The terrain mesh contains normals.
     * @type {Boolean}
     */
    this.hasVertexNormals = hasVertexNormals;

    /**
     * The terrain mesh contains a vertical texture coordinate following the Web Mercator projection.
     * @type {Boolean}
     */
    this.hasWebMercatorT = defaultValue(hasWebMercatorT, false);

    /**
     * The terrain mesh contains geodetic surface normals, used for terrain exaggeration.
     * @type {Boolean}
     */
    this.hasGeodeticSurfaceNormals = defaultValue(
      hasGeodeticSurfaceNormals,
      false
    );

    /**
     * A scalar used to exaggerate terrain.
     * @type {Number}
     */
    this.exaggeration = defaultValue(exaggeration, 1.0);

    /**
     * The relative height from which terrain is exaggerated.
     */
    this.exaggerationRelativeHeight = defaultValue(
      exaggerationRelativeHeight,
      0.0
    );

    /**
     * The number of components in each vertex. This value can differ with different quantizations.
     * @type {Number}
     */
    this.stride = 0;

    this._offsetGeodeticSurfaceNormal = 0;
    this._offsetVertexNormal = 0;

    // Calculate the stride and offsets declared above
    this._calculateStrideAndOffsets();
  }

  TerrainEncoding.prototype.encode = function (
    vertexBuffer,
    bufferIndex,
    position,
    uv,
    height,
    normalToPack,
    webMercatorT,
    geodeticSurfaceNormal
  ) {
    const u = uv.x;
    const v = uv.y;

    if (this.quantization === TerrainQuantization$1.BITS12) {
      position = Matrix4.multiplyByPoint(
        this.toScaledENU,
        position,
        cartesian3Scratch$3
      );

      position.x = CesiumMath.clamp(position.x, 0.0, 1.0);
      position.y = CesiumMath.clamp(position.y, 0.0, 1.0);
      position.z = CesiumMath.clamp(position.z, 0.0, 1.0);

      const hDim = this.maximumHeight - this.minimumHeight;
      const h = CesiumMath.clamp((height - this.minimumHeight) / hDim, 0.0, 1.0);

      Cartesian2.fromElements(position.x, position.y, cartesian2Scratch);
      const compressed0 = AttributeCompression.compressTextureCoordinates(
        cartesian2Scratch
      );

      Cartesian2.fromElements(position.z, h, cartesian2Scratch);
      const compressed1 = AttributeCompression.compressTextureCoordinates(
        cartesian2Scratch
      );

      Cartesian2.fromElements(u, v, cartesian2Scratch);
      const compressed2 = AttributeCompression.compressTextureCoordinates(
        cartesian2Scratch
      );

      vertexBuffer[bufferIndex++] = compressed0;
      vertexBuffer[bufferIndex++] = compressed1;
      vertexBuffer[bufferIndex++] = compressed2;

      if (this.hasWebMercatorT) {
        Cartesian2.fromElements(webMercatorT, 0.0, cartesian2Scratch);
        const compressed3 = AttributeCompression.compressTextureCoordinates(
          cartesian2Scratch
        );
        vertexBuffer[bufferIndex++] = compressed3;
      }
    } else {
      Cartesian3.subtract(position, this.center, cartesian3Scratch$3);

      vertexBuffer[bufferIndex++] = cartesian3Scratch$3.x;
      vertexBuffer[bufferIndex++] = cartesian3Scratch$3.y;
      vertexBuffer[bufferIndex++] = cartesian3Scratch$3.z;
      vertexBuffer[bufferIndex++] = height;
      vertexBuffer[bufferIndex++] = u;
      vertexBuffer[bufferIndex++] = v;

      if (this.hasWebMercatorT) {
        vertexBuffer[bufferIndex++] = webMercatorT;
      }
    }

    if (this.hasVertexNormals) {
      vertexBuffer[bufferIndex++] = AttributeCompression.octPackFloat(
        normalToPack
      );
    }

    if (this.hasGeodeticSurfaceNormals) {
      vertexBuffer[bufferIndex++] = geodeticSurfaceNormal.x;
      vertexBuffer[bufferIndex++] = geodeticSurfaceNormal.y;
      vertexBuffer[bufferIndex++] = geodeticSurfaceNormal.z;
    }

    return bufferIndex;
  };

  const scratchPosition$f = new Cartesian3();
  const scratchGeodeticSurfaceNormal = new Cartesian3();

  TerrainEncoding.prototype.addGeodeticSurfaceNormals = function (
    oldBuffer,
    newBuffer,
    ellipsoid
  ) {
    if (this.hasGeodeticSurfaceNormals) {
      return;
    }

    const oldStride = this.stride;
    const vertexCount = oldBuffer.length / oldStride;
    this.hasGeodeticSurfaceNormals = true;
    this._calculateStrideAndOffsets();
    const newStride = this.stride;

    for (let index = 0; index < vertexCount; index++) {
      for (let offset = 0; offset < oldStride; offset++) {
        const oldIndex = index * oldStride + offset;
        const newIndex = index * newStride + offset;
        newBuffer[newIndex] = oldBuffer[oldIndex];
      }
      const position = this.decodePosition(newBuffer, index, scratchPosition$f);
      const geodeticSurfaceNormal = ellipsoid.geodeticSurfaceNormal(
        position,
        scratchGeodeticSurfaceNormal
      );

      const bufferIndex = index * newStride + this._offsetGeodeticSurfaceNormal;
      newBuffer[bufferIndex] = geodeticSurfaceNormal.x;
      newBuffer[bufferIndex + 1] = geodeticSurfaceNormal.y;
      newBuffer[bufferIndex + 2] = geodeticSurfaceNormal.z;
    }
  };

  TerrainEncoding.prototype.removeGeodeticSurfaceNormals = function (
    oldBuffer,
    newBuffer
  ) {
    if (!this.hasGeodeticSurfaceNormals) {
      return;
    }

    const oldStride = this.stride;
    const vertexCount = oldBuffer.length / oldStride;
    this.hasGeodeticSurfaceNormals = false;
    this._calculateStrideAndOffsets();
    const newStride = this.stride;

    for (let index = 0; index < vertexCount; index++) {
      for (let offset = 0; offset < newStride; offset++) {
        const oldIndex = index * oldStride + offset;
        const newIndex = index * newStride + offset;
        newBuffer[newIndex] = oldBuffer[oldIndex];
      }
    }
  };

  TerrainEncoding.prototype.decodePosition = function (buffer, index, result) {
    if (!defined(result)) {
      result = new Cartesian3();
    }

    index *= this.stride;

    if (this.quantization === TerrainQuantization$1.BITS12) {
      const xy = AttributeCompression.decompressTextureCoordinates(
        buffer[index],
        cartesian2Scratch
      );
      result.x = xy.x;
      result.y = xy.y;

      const zh = AttributeCompression.decompressTextureCoordinates(
        buffer[index + 1],
        cartesian2Scratch
      );
      result.z = zh.x;

      return Matrix4.multiplyByPoint(this.fromScaledENU, result, result);
    }

    result.x = buffer[index];
    result.y = buffer[index + 1];
    result.z = buffer[index + 2];
    return Cartesian3.add(result, this.center, result);
  };

  TerrainEncoding.prototype.getExaggeratedPosition = function (
    buffer,
    index,
    result
  ) {
    result = this.decodePosition(buffer, index, result);

    const exaggeration = this.exaggeration;
    const exaggerationRelativeHeight = this.exaggerationRelativeHeight;
    const hasExaggeration = exaggeration !== 1.0;
    if (hasExaggeration && this.hasGeodeticSurfaceNormals) {
      const geodeticSurfaceNormal = this.decodeGeodeticSurfaceNormal(
        buffer,
        index,
        scratchGeodeticSurfaceNormal
      );
      const rawHeight = this.decodeHeight(buffer, index);
      const heightDifference =
        TerrainExaggeration.getHeight(
          rawHeight,
          exaggeration,
          exaggerationRelativeHeight
        ) - rawHeight;

      // some math is unrolled for better performance
      result.x += geodeticSurfaceNormal.x * heightDifference;
      result.y += geodeticSurfaceNormal.y * heightDifference;
      result.z += geodeticSurfaceNormal.z * heightDifference;
    }

    return result;
  };

  TerrainEncoding.prototype.decodeTextureCoordinates = function (
    buffer,
    index,
    result
  ) {
    if (!defined(result)) {
      result = new Cartesian2();
    }

    index *= this.stride;

    if (this.quantization === TerrainQuantization$1.BITS12) {
      return AttributeCompression.decompressTextureCoordinates(
        buffer[index + 2],
        result
      );
    }

    return Cartesian2.fromElements(buffer[index + 4], buffer[index + 5], result);
  };

  TerrainEncoding.prototype.decodeHeight = function (buffer, index) {
    index *= this.stride;

    if (this.quantization === TerrainQuantization$1.BITS12) {
      const zh = AttributeCompression.decompressTextureCoordinates(
        buffer[index + 1],
        cartesian2Scratch
      );
      return (
        zh.y * (this.maximumHeight - this.minimumHeight) + this.minimumHeight
      );
    }

    return buffer[index + 3];
  };

  TerrainEncoding.prototype.decodeWebMercatorT = function (buffer, index) {
    index *= this.stride;

    if (this.quantization === TerrainQuantization$1.BITS12) {
      return AttributeCompression.decompressTextureCoordinates(
        buffer[index + 3],
        cartesian2Scratch
      ).x;
    }

    return buffer[index + 6];
  };

  TerrainEncoding.prototype.getOctEncodedNormal = function (
    buffer,
    index,
    result
  ) {
    index = index * this.stride + this._offsetVertexNormal;

    const temp = buffer[index] / 256.0;
    const x = Math.floor(temp);
    const y = (temp - x) * 256.0;

    return Cartesian2.fromElements(x, y, result);
  };

  TerrainEncoding.prototype.decodeGeodeticSurfaceNormal = function (
    buffer,
    index,
    result
  ) {
    index = index * this.stride + this._offsetGeodeticSurfaceNormal;

    result.x = buffer[index];
    result.y = buffer[index + 1];
    result.z = buffer[index + 2];
    return result;
  };

  TerrainEncoding.prototype._calculateStrideAndOffsets = function () {
    let vertexStride = 0;

    switch (this.quantization) {
      case TerrainQuantization$1.BITS12:
        vertexStride += 3;
        break;
      default:
        vertexStride += 6;
    }
    if (this.hasWebMercatorT) {
      vertexStride += 1;
    }
    if (this.hasVertexNormals) {
      this._offsetVertexNormal = vertexStride;
      vertexStride += 1;
    }
    if (this.hasGeodeticSurfaceNormals) {
      this._offsetGeodeticSurfaceNormal = vertexStride;
      vertexStride += 3;
    }

    this.stride = vertexStride;
  };

  const attributesIndicesNone = {
    position3DAndHeight: 0,
    textureCoordAndEncodedNormals: 1,
    geodeticSurfaceNormal: 2,
  };
  const attributesIndicesBits12 = {
    compressed0: 0,
    compressed1: 1,
    geodeticSurfaceNormal: 2,
  };

  TerrainEncoding.prototype.getAttributes = function (buffer) {
    const datatype = ComponentDatatype$1.FLOAT;
    const sizeInBytes = ComponentDatatype$1.getSizeInBytes(datatype);
    const strideInBytes = this.stride * sizeInBytes;
    let offsetInBytes = 0;

    const attributes = [];
    function addAttribute(index, componentsPerAttribute) {
      attributes.push({
        index: index,
        vertexBuffer: buffer,
        componentDatatype: datatype,
        componentsPerAttribute: componentsPerAttribute,
        offsetInBytes: offsetInBytes,
        strideInBytes: strideInBytes,
      });
      offsetInBytes += componentsPerAttribute * sizeInBytes;
    }

    if (this.quantization === TerrainQuantization$1.NONE) {
      addAttribute(attributesIndicesNone.position3DAndHeight, 4);

      let componentsTexCoordAndNormals = 2;
      componentsTexCoordAndNormals += this.hasWebMercatorT ? 1 : 0;
      componentsTexCoordAndNormals += this.hasVertexNormals ? 1 : 0;
      addAttribute(
        attributesIndicesNone.textureCoordAndEncodedNormals,
        componentsTexCoordAndNormals
      );

      if (this.hasGeodeticSurfaceNormals) {
        addAttribute(attributesIndicesNone.geodeticSurfaceNormal, 3);
      }
    } else {
      // When there is no webMercatorT or vertex normals, the attribute only needs 3 components: x/y, z/h, u/v.
      // WebMercatorT and vertex normals each take up one component, so if only one of them is present the first
      // attribute gets a 4th component. If both are present, we need an additional attribute that has 1 component.
      const usingAttribute0Component4 =
        this.hasWebMercatorT || this.hasVertexNormals;
      const usingAttribute1Component1 =
        this.hasWebMercatorT && this.hasVertexNormals;
      addAttribute(
        attributesIndicesBits12.compressed0,
        usingAttribute0Component4 ? 4 : 3
      );

      if (usingAttribute1Component1) {
        addAttribute(attributesIndicesBits12.compressed1, 1);
      }

      if (this.hasGeodeticSurfaceNormals) {
        addAttribute(attributesIndicesBits12.geodeticSurfaceNormal, 3);
      }
    }

    return attributes;
  };

  TerrainEncoding.prototype.getAttributeLocations = function () {
    if (this.quantization === TerrainQuantization$1.NONE) {
      return attributesIndicesNone;
    }
    return attributesIndicesBits12;
  };

  TerrainEncoding.clone = function (encoding, result) {
    if (!defined(encoding)) {
      return undefined;
    }
    if (!defined(result)) {
      result = new TerrainEncoding();
    }

    result.quantization = encoding.quantization;
    result.minimumHeight = encoding.minimumHeight;
    result.maximumHeight = encoding.maximumHeight;
    result.center = Cartesian3.clone(encoding.center);
    result.toScaledENU = Matrix4.clone(encoding.toScaledENU);
    result.fromScaledENU = Matrix4.clone(encoding.fromScaledENU);
    result.matrix = Matrix4.clone(encoding.matrix);
    result.hasVertexNormals = encoding.hasVertexNormals;
    result.hasWebMercatorT = encoding.hasWebMercatorT;
    result.hasGeodeticSurfaceNormals = encoding.hasGeodeticSurfaceNormals;
    result.exaggeration = encoding.exaggeration;
    result.exaggerationRelativeHeight = encoding.exaggerationRelativeHeight;

    result._calculateStrideAndOffsets();

    return result;
  };

  /**
   * The map projection used by Google Maps, Bing Maps, and most of ArcGIS Online, EPSG:3857.  This
   * projection use longitude and latitude expressed with the WGS84 and transforms them to Mercator using
   * the spherical (rather than ellipsoidal) equations.
   *
   * @alias WebMercatorProjection
   * @constructor
   *
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid.
   *
   * @see GeographicProjection
   */
  function WebMercatorProjection(ellipsoid) {
    this._ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
    this._semimajorAxis = this._ellipsoid.maximumRadius;
    this._oneOverSemimajorAxis = 1.0 / this._semimajorAxis;
  }

  Object.defineProperties(WebMercatorProjection.prototype, {
    /**
     * Gets the {@link Ellipsoid}.
     *
     * @memberof WebMercatorProjection.prototype
     *
     * @type {Ellipsoid}
     * @readonly
     */
    ellipsoid: {
      get: function () {
        return this._ellipsoid;
      },
    },
  });

  /**
   * Converts a Mercator angle, in the range -PI to PI, to a geodetic latitude
   * in the range -PI/2 to PI/2.
   *
   * @param {Number} mercatorAngle The angle to convert.
   * @returns {Number} The geodetic latitude in radians.
   */
  WebMercatorProjection.mercatorAngleToGeodeticLatitude = function (
    mercatorAngle
  ) {
    return CesiumMath.PI_OVER_TWO - 2.0 * Math.atan(Math.exp(-mercatorAngle));
  };

  /**
   * Converts a geodetic latitude in radians, in the range -PI/2 to PI/2, to a Mercator
   * angle in the range -PI to PI.
   *
   * @param {Number} latitude The geodetic latitude in radians.
   * @returns {Number} The Mercator angle.
   */
  WebMercatorProjection.geodeticLatitudeToMercatorAngle = function (latitude) {
    // Clamp the latitude coordinate to the valid Mercator bounds.
    if (latitude > WebMercatorProjection.MaximumLatitude) {
      latitude = WebMercatorProjection.MaximumLatitude;
    } else if (latitude < -WebMercatorProjection.MaximumLatitude) {
      latitude = -WebMercatorProjection.MaximumLatitude;
    }
    const sinLatitude = Math.sin(latitude);
    return 0.5 * Math.log((1.0 + sinLatitude) / (1.0 - sinLatitude));
  };

  /**
   * The maximum latitude (both North and South) supported by a Web Mercator
   * (EPSG:3857) projection.  Technically, the Mercator projection is defined
   * for any latitude up to (but not including) 90 degrees, but it makes sense
   * to cut it off sooner because it grows exponentially with increasing latitude.
   * The logic behind this particular cutoff value, which is the one used by
   * Google Maps, Bing Maps, and Esri, is that it makes the projection
   * square.  That is, the rectangle is equal in the X and Y directions.
   *
   * The constant value is computed by calling:
   *    WebMercatorProjection.mercatorAngleToGeodeticLatitude(Math.PI)
   *
   * @type {Number}
   */
  WebMercatorProjection.MaximumLatitude = WebMercatorProjection.mercatorAngleToGeodeticLatitude(
    Math.PI
  );

  /**
   * Converts geodetic ellipsoid coordinates, in radians, to the equivalent Web Mercator
   * X, Y, Z coordinates expressed in meters and returned in a {@link Cartesian3}.  The height
   * is copied unmodified to the Z coordinate.
   *
   * @param {Cartographic} cartographic The cartographic coordinates in radians.
   * @param {Cartesian3} [result] The instance to which to copy the result, or undefined if a
   *        new instance should be created.
   * @returns {Cartesian3} The equivalent web mercator X, Y, Z coordinates, in meters.
   */
  WebMercatorProjection.prototype.project = function (cartographic, result) {
    const semimajorAxis = this._semimajorAxis;
    const x = cartographic.longitude * semimajorAxis;
    const y =
      WebMercatorProjection.geodeticLatitudeToMercatorAngle(
        cartographic.latitude
      ) * semimajorAxis;
    const z = cartographic.height;

    if (!defined(result)) {
      return new Cartesian3(x, y, z);
    }

    result.x = x;
    result.y = y;
    result.z = z;
    return result;
  };

  /**
   * Converts Web Mercator X, Y coordinates, expressed in meters, to a {@link Cartographic}
   * containing geodetic ellipsoid coordinates.  The Z coordinate is copied unmodified to the
   * height.
   *
   * @param {Cartesian3} cartesian The web mercator Cartesian position to unrproject with height (z) in meters.
   * @param {Cartographic} [result] The instance to which to copy the result, or undefined if a
   *        new instance should be created.
   * @returns {Cartographic} The equivalent cartographic coordinates.
   */
  WebMercatorProjection.prototype.unproject = function (cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(cartesian)) {
      throw new DeveloperError("cartesian is required");
    }
    //>>includeEnd('debug');

    const oneOverEarthSemimajorAxis = this._oneOverSemimajorAxis;
    const longitude = cartesian.x * oneOverEarthSemimajorAxis;
    const latitude = WebMercatorProjection.mercatorAngleToGeodeticLatitude(
      cartesian.y * oneOverEarthSemimajorAxis
    );
    const height = cartesian.z;

    if (!defined(result)) {
      return new Cartographic(longitude, latitude, height);
    }

    result.longitude = longitude;
    result.latitude = latitude;
    result.height = height;
    return result;
  };

  /**
   * Contains functions to create a mesh from a heightmap image.
   *
   * @namespace HeightmapTessellator
   *
   * @private
   */
  const HeightmapTessellator = {};

  /**
   * The default structure of a heightmap, as given to {@link HeightmapTessellator.computeVertices}.
   *
   * @constant
   */
  HeightmapTessellator.DEFAULT_STRUCTURE = Object.freeze({
    heightScale: 1.0,
    heightOffset: 0.0,
    elementsPerHeight: 1,
    stride: 1,
    elementMultiplier: 256.0,
    isBigEndian: false,
  });

  const cartesian3Scratch$2 = new Cartesian3();
  const matrix4Scratch = new Matrix4();
  const minimumScratch = new Cartesian3();
  const maximumScratch = new Cartesian3();

  /**
   * Fills an array of vertices from a heightmap image.
   *
   * @param {Object} options Object with the following properties:
   * @param {Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} options.heightmap The heightmap to tessellate.
   * @param {Number} options.width The width of the heightmap, in height samples.
   * @param {Number} options.height The height of the heightmap, in height samples.
   * @param {Number} options.skirtHeight The height of skirts to drape at the edges of the heightmap.
   * @param {Rectangle} options.nativeRectangle A rectangle in the native coordinates of the heightmap's projection.  For
   *                 a heightmap with a geographic projection, this is degrees.  For the web mercator
   *                 projection, this is meters.
   * @param {Number} [options.exaggeration=1.0] The scale used to exaggerate the terrain.
   * @param {Number} [options.exaggerationRelativeHeight=0.0] The height from which terrain is exaggerated.
   * @param {Rectangle} [options.rectangle] The rectangle covered by the heightmap, in geodetic coordinates with north, south, east and
   *                 west properties in radians.  Either rectangle or nativeRectangle must be provided.  If both
   *                 are provided, they're assumed to be consistent.
   * @param {Boolean} [options.isGeographic=true] True if the heightmap uses a {@link GeographicProjection}, or false if it uses
   *                  a {@link WebMercatorProjection}.
   * @param {Cartesian3} [options.relativeToCenter=Cartesian3.ZERO] The positions will be computed as <code>Cartesian3.subtract(worldPosition, relativeToCenter)</code>.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid to which the heightmap applies.
   * @param {Object} [options.structure] An object describing the structure of the height data.
   * @param {Number} [options.structure.heightScale=1.0] The factor by which to multiply height samples in order to obtain
   *                 the height above the heightOffset, in meters.  The heightOffset is added to the resulting
   *                 height after multiplying by the scale.
   * @param {Number} [options.structure.heightOffset=0.0] The offset to add to the scaled height to obtain the final
   *                 height in meters.  The offset is added after the height sample is multiplied by the
   *                 heightScale.
   * @param {Number} [options.structure.elementsPerHeight=1] The number of elements in the buffer that make up a single height
   *                 sample.  This is usually 1, indicating that each element is a separate height sample.  If
   *                 it is greater than 1, that number of elements together form the height sample, which is
   *                 computed according to the structure.elementMultiplier and structure.isBigEndian properties.
   * @param {Number} [options.structure.stride=1] The number of elements to skip to get from the first element of
   *                 one height to the first element of the next height.
   * @param {Number} [options.structure.elementMultiplier=256.0] The multiplier used to compute the height value when the
   *                 stride property is greater than 1.  For example, if the stride is 4 and the strideMultiplier
   *                 is 256, the height is computed as follows:
   *                 `height = buffer[index] + buffer[index + 1] * 256 + buffer[index + 2] * 256 * 256 + buffer[index + 3] * 256 * 256 * 256`
   *                 This is assuming that the isBigEndian property is false.  If it is true, the order of the
   *                 elements is reversed.
   * @param {Number} [options.structure.lowestEncodedHeight] The lowest value that can be stored in the height buffer.  Any heights that are lower
   *                 than this value after encoding with the `heightScale` and `heightOffset` are clamped to this value.  For example, if the height
   *                 buffer is a `Uint16Array`, this value should be 0 because a `Uint16Array` cannot store negative numbers.  If this parameter is
   *                 not specified, no minimum value is enforced.
   * @param {Number} [options.structure.highestEncodedHeight] The highest value that can be stored in the height buffer.  Any heights that are higher
   *                 than this value after encoding with the `heightScale` and `heightOffset` are clamped to this value.  For example, if the height
   *                 buffer is a `Uint16Array`, this value should be `256 * 256 - 1` or 65535 because a `Uint16Array` cannot store numbers larger
   *                 than 65535.  If this parameter is not specified, no maximum value is enforced.
   * @param {Boolean} [options.structure.isBigEndian=false] Indicates endianness of the elements in the buffer when the
   *                  stride property is greater than 1.  If this property is false, the first element is the
   *                  low-order element.  If it is true, the first element is the high-order element.
   *
   * @example
   * const width = 5;
   * const height = 5;
   * const statistics = Cesium.HeightmapTessellator.computeVertices({
   *     heightmap : [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0],
   *     width : width,
   *     height : height,
   *     skirtHeight : 0.0,
   *     nativeRectangle : {
   *         west : 10.0,
   *         east : 20.0,
   *         south : 30.0,
   *         north : 40.0
   *     }
   * });
   *
   * const encoding = statistics.encoding;
   * const position = encoding.decodePosition(statistics.vertices, index);
   */
  HeightmapTessellator.computeVertices = function (options) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(options) || !defined(options.heightmap)) {
      throw new DeveloperError("options.heightmap is required.");
    }
    if (!defined(options.width) || !defined(options.height)) {
      throw new DeveloperError("options.width and options.height are required.");
    }
    if (!defined(options.nativeRectangle)) {
      throw new DeveloperError("options.nativeRectangle is required.");
    }
    if (!defined(options.skirtHeight)) {
      throw new DeveloperError("options.skirtHeight is required.");
    }
    //>>includeEnd('debug');

    // This function tends to be a performance hotspot for terrain rendering,
    // so it employs a lot of inlining and unrolling as an optimization.
    // In particular, the functionality of Ellipsoid.cartographicToCartesian
    // is inlined.

    const cos = Math.cos;
    const sin = Math.sin;
    const sqrt = Math.sqrt;
    const atan = Math.atan;
    const exp = Math.exp;
    const piOverTwo = CesiumMath.PI_OVER_TWO;
    const toRadians = CesiumMath.toRadians;

    const heightmap = options.heightmap;
    const width = options.width;
    const height = options.height;
    const skirtHeight = options.skirtHeight;
    const hasSkirts = skirtHeight > 0.0;

    const isGeographic = defaultValue(options.isGeographic, true);
    const ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);

    const oneOverGlobeSemimajorAxis = 1.0 / ellipsoid.maximumRadius;

    const nativeRectangle = Rectangle.clone(options.nativeRectangle);
    const rectangle = Rectangle.clone(options.rectangle);

    let geographicWest;
    let geographicSouth;
    let geographicEast;
    let geographicNorth;

    if (!defined(rectangle)) {
      if (isGeographic) {
        geographicWest = toRadians(nativeRectangle.west);
        geographicSouth = toRadians(nativeRectangle.south);
        geographicEast = toRadians(nativeRectangle.east);
        geographicNorth = toRadians(nativeRectangle.north);
      } else {
        geographicWest = nativeRectangle.west * oneOverGlobeSemimajorAxis;
        geographicSouth =
          piOverTwo -
          2.0 * atan(exp(-nativeRectangle.south * oneOverGlobeSemimajorAxis));
        geographicEast = nativeRectangle.east * oneOverGlobeSemimajorAxis;
        geographicNorth =
          piOverTwo -
          2.0 * atan(exp(-nativeRectangle.north * oneOverGlobeSemimajorAxis));
      }
    } else {
      geographicWest = rectangle.west;
      geographicSouth = rectangle.south;
      geographicEast = rectangle.east;
      geographicNorth = rectangle.north;
    }

    let relativeToCenter = options.relativeToCenter;
    const hasRelativeToCenter = defined(relativeToCenter);
    relativeToCenter = hasRelativeToCenter ? relativeToCenter : Cartesian3.ZERO;
    const includeWebMercatorT = defaultValue(options.includeWebMercatorT, false);

    const exaggeration = defaultValue(options.exaggeration, 1.0);
    const exaggerationRelativeHeight = defaultValue(
      options.exaggerationRelativeHeight,
      0.0
    );
    const hasExaggeration = exaggeration !== 1.0;
    const includeGeodeticSurfaceNormals = hasExaggeration;

    const structure = defaultValue(
      options.structure,
      HeightmapTessellator.DEFAULT_STRUCTURE
    );
    const heightScale = defaultValue(
      structure.heightScale,
      HeightmapTessellator.DEFAULT_STRUCTURE.heightScale
    );
    const heightOffset = defaultValue(
      structure.heightOffset,
      HeightmapTessellator.DEFAULT_STRUCTURE.heightOffset
    );
    const elementsPerHeight = defaultValue(
      structure.elementsPerHeight,
      HeightmapTessellator.DEFAULT_STRUCTURE.elementsPerHeight
    );
    const stride = defaultValue(
      structure.stride,
      HeightmapTessellator.DEFAULT_STRUCTURE.stride
    );
    const elementMultiplier = defaultValue(
      structure.elementMultiplier,
      HeightmapTessellator.DEFAULT_STRUCTURE.elementMultiplier
    );
    const isBigEndian = defaultValue(
      structure.isBigEndian,
      HeightmapTessellator.DEFAULT_STRUCTURE.isBigEndian
    );

    let rectangleWidth = Rectangle.computeWidth(nativeRectangle);
    let rectangleHeight = Rectangle.computeHeight(nativeRectangle);

    const granularityX = rectangleWidth / (width - 1);
    const granularityY = rectangleHeight / (height - 1);

    if (!isGeographic) {
      rectangleWidth *= oneOverGlobeSemimajorAxis;
      rectangleHeight *= oneOverGlobeSemimajorAxis;
    }

    const radiiSquared = ellipsoid.radiiSquared;
    const radiiSquaredX = radiiSquared.x;
    const radiiSquaredY = radiiSquared.y;
    const radiiSquaredZ = radiiSquared.z;

    let minimumHeight = 65536.0;
    let maximumHeight = -65536.0;

    const fromENU = Transforms.eastNorthUpToFixedFrame(
      relativeToCenter,
      ellipsoid
    );
    const toENU = Matrix4.inverseTransformation(fromENU, matrix4Scratch);

    let southMercatorY;
    let oneOverMercatorHeight;
    if (includeWebMercatorT) {
      southMercatorY = WebMercatorProjection.geodeticLatitudeToMercatorAngle(
        geographicSouth
      );
      oneOverMercatorHeight =
        1.0 /
        (WebMercatorProjection.geodeticLatitudeToMercatorAngle(geographicNorth) -
          southMercatorY);
    }

    const minimum = minimumScratch;
    minimum.x = Number.POSITIVE_INFINITY;
    minimum.y = Number.POSITIVE_INFINITY;
    minimum.z = Number.POSITIVE_INFINITY;

    const maximum = maximumScratch;
    maximum.x = Number.NEGATIVE_INFINITY;
    maximum.y = Number.NEGATIVE_INFINITY;
    maximum.z = Number.NEGATIVE_INFINITY;

    let hMin = Number.POSITIVE_INFINITY;

    const gridVertexCount = width * height;
    const edgeVertexCount = skirtHeight > 0.0 ? width * 2 + height * 2 : 0;
    const vertexCount = gridVertexCount + edgeVertexCount;

    const positions = new Array(vertexCount);
    const heights = new Array(vertexCount);
    const uvs = new Array(vertexCount);
    const webMercatorTs = includeWebMercatorT ? new Array(vertexCount) : [];
    const geodeticSurfaceNormals = includeGeodeticSurfaceNormals
      ? new Array(vertexCount)
      : [];

    let startRow = 0;
    let endRow = height;
    let startCol = 0;
    let endCol = width;

    if (hasSkirts) {
      --startRow;
      ++endRow;
      --startCol;
      ++endCol;
    }

    const skirtOffsetPercentage = 0.00001;

    for (let rowIndex = startRow; rowIndex < endRow; ++rowIndex) {
      let row = rowIndex;
      if (row < 0) {
        row = 0;
      }
      if (row >= height) {
        row = height - 1;
      }

      let latitude = nativeRectangle.north - granularityY * row;

      if (!isGeographic) {
        latitude =
          piOverTwo - 2.0 * atan(exp(-latitude * oneOverGlobeSemimajorAxis));
      } else {
        latitude = toRadians(latitude);
      }

      let v = (latitude - geographicSouth) / (geographicNorth - geographicSouth);
      v = CesiumMath.clamp(v, 0.0, 1.0);

      const isNorthEdge = rowIndex === startRow;
      const isSouthEdge = rowIndex === endRow - 1;
      if (skirtHeight > 0.0) {
        if (isNorthEdge) {
          latitude += skirtOffsetPercentage * rectangleHeight;
        } else if (isSouthEdge) {
          latitude -= skirtOffsetPercentage * rectangleHeight;
        }
      }

      const cosLatitude = cos(latitude);
      const nZ = sin(latitude);
      const kZ = radiiSquaredZ * nZ;

      let webMercatorT;
      if (includeWebMercatorT) {
        webMercatorT =
          (WebMercatorProjection.geodeticLatitudeToMercatorAngle(latitude) -
            southMercatorY) *
          oneOverMercatorHeight;
      }

      for (let colIndex = startCol; colIndex < endCol; ++colIndex) {
        let col = colIndex;
        if (col < 0) {
          col = 0;
        }
        if (col >= width) {
          col = width - 1;
        }

        const terrainOffset = row * (width * stride) + col * stride;

        let heightSample;
        if (elementsPerHeight === 1) {
          heightSample = heightmap[terrainOffset];
        } else {
          heightSample = 0;

          let elementOffset;
          if (isBigEndian) {
            for (
              elementOffset = 0;
              elementOffset < elementsPerHeight;
              ++elementOffset
            ) {
              heightSample =
                heightSample * elementMultiplier +
                heightmap[terrainOffset + elementOffset];
            }
          } else {
            for (
              elementOffset = elementsPerHeight - 1;
              elementOffset >= 0;
              --elementOffset
            ) {
              heightSample =
                heightSample * elementMultiplier +
                heightmap[terrainOffset + elementOffset];
            }
          }
        }

        heightSample = heightSample * heightScale + heightOffset;

        maximumHeight = Math.max(maximumHeight, heightSample);
        minimumHeight = Math.min(minimumHeight, heightSample);

        let longitude = nativeRectangle.west + granularityX * col;

        if (!isGeographic) {
          longitude = longitude * oneOverGlobeSemimajorAxis;
        } else {
          longitude = toRadians(longitude);
        }

        let u = (longitude - geographicWest) / (geographicEast - geographicWest);
        u = CesiumMath.clamp(u, 0.0, 1.0);

        let index = row * width + col;

        if (skirtHeight > 0.0) {
          const isWestEdge = colIndex === startCol;
          const isEastEdge = colIndex === endCol - 1;
          const isEdge = isNorthEdge || isSouthEdge || isWestEdge || isEastEdge;
          const isCorner =
            (isNorthEdge || isSouthEdge) && (isWestEdge || isEastEdge);
          if (isCorner) {
            // Don't generate skirts on the corners.
            continue;
          } else if (isEdge) {
            heightSample -= skirtHeight;

            if (isWestEdge) {
              // The outer loop iterates north to south but the indices are ordered south to north, hence the index flip below
              index = gridVertexCount + (height - row - 1);
              longitude -= skirtOffsetPercentage * rectangleWidth;
            } else if (isSouthEdge) {
              // Add after west indices. South indices are ordered east to west.
              index = gridVertexCount + height + (width - col - 1);
            } else if (isEastEdge) {
              // Add after west and south indices. East indices are ordered north to south. The index is flipped like above.
              index = gridVertexCount + height + width + row;
              longitude += skirtOffsetPercentage * rectangleWidth;
            } else if (isNorthEdge) {
              // Add after west, south, and east indices. North indices are ordered west to east.
              index = gridVertexCount + height + width + height + col;
            }
          }
        }

        const nX = cosLatitude * cos(longitude);
        const nY = cosLatitude * sin(longitude);

        const kX = radiiSquaredX * nX;
        const kY = radiiSquaredY * nY;

        const gamma = sqrt(kX * nX + kY * nY + kZ * nZ);
        const oneOverGamma = 1.0 / gamma;

        const rSurfaceX = kX * oneOverGamma;
        const rSurfaceY = kY * oneOverGamma;
        const rSurfaceZ = kZ * oneOverGamma;

        const position = new Cartesian3();
        position.x = rSurfaceX + nX * heightSample;
        position.y = rSurfaceY + nY * heightSample;
        position.z = rSurfaceZ + nZ * heightSample;

        Matrix4.multiplyByPoint(toENU, position, cartesian3Scratch$2);
        Cartesian3.minimumByComponent(cartesian3Scratch$2, minimum, minimum);
        Cartesian3.maximumByComponent(cartesian3Scratch$2, maximum, maximum);
        hMin = Math.min(hMin, heightSample);

        positions[index] = position;
        uvs[index] = new Cartesian2(u, v);
        heights[index] = heightSample;

        if (includeWebMercatorT) {
          webMercatorTs[index] = webMercatorT;
        }

        if (includeGeodeticSurfaceNormals) {
          geodeticSurfaceNormals[index] = ellipsoid.geodeticSurfaceNormal(
            position
          );
        }
      }
    }

    const boundingSphere3D = BoundingSphere.fromPoints(positions);
    let orientedBoundingBox;
    if (defined(rectangle)) {
      orientedBoundingBox = OrientedBoundingBox.fromRectangle(
        rectangle,
        minimumHeight,
        maximumHeight,
        ellipsoid
      );
    }

    let occludeePointInScaledSpace;
    if (hasRelativeToCenter) {
      const occluder = new EllipsoidalOccluder(ellipsoid);
      occludeePointInScaledSpace = occluder.computeHorizonCullingPointPossiblyUnderEllipsoid(
        relativeToCenter,
        positions,
        minimumHeight
      );
    }

    const aaBox = new AxisAlignedBoundingBox(minimum, maximum, relativeToCenter);
    const encoding = new TerrainEncoding(
      relativeToCenter,
      aaBox,
      hMin,
      maximumHeight,
      fromENU,
      false,
      includeWebMercatorT,
      includeGeodeticSurfaceNormals,
      exaggeration,
      exaggerationRelativeHeight
    );
    const vertices = new Float32Array(vertexCount * encoding.stride);

    let bufferIndex = 0;
    for (let j = 0; j < vertexCount; ++j) {
      bufferIndex = encoding.encode(
        vertices,
        bufferIndex,
        positions[j],
        uvs[j],
        heights[j],
        undefined,
        webMercatorTs[j],
        geodeticSurfaceNormals[j]
      );
    }

    return {
      vertices: vertices,
      maximumHeight: maximumHeight,
      minimumHeight: minimumHeight,
      encoding: encoding,
      boundingSphere3D: boundingSphere3D,
      orientedBoundingBox: orientedBoundingBox,
      occludeePointInScaledSpace: occludeePointInScaledSpace,
    };
  };

  function returnTrue() {
    return true;
  }

  /**
   * Destroys an object.  Each of the object's functions, including functions in its prototype,
   * is replaced with a function that throws a {@link DeveloperError}, except for the object's
   * <code>isDestroyed</code> function, which is set to a function that returns <code>true</code>.
   * The object's properties are removed with <code>delete</code>.
   * <br /><br />
   * This function is used by objects that hold native resources, e.g., WebGL resources, which
   * need to be explicitly released.  Client code calls an object's <code>destroy</code> function,
   * which then releases the native resource and calls <code>destroyObject</code> to put itself
   * in a destroyed state.
   *
   * @function
   *
   * @param {Object} object The object to destroy.
   * @param {String} [message] The message to include in the exception that is thrown if
   *                           a destroyed object's function is called.
   *
   *
   * @example
   * // How a texture would destroy itself.
   * this.destroy = function () {
   *     _gl.deleteTexture(_texture);
   *     return Cesium.destroyObject(this);
   * };
   *
   * @see DeveloperError
   */
  function destroyObject(object, message) {
    message = defaultValue(
      message,
      "This object was destroyed, i.e., destroy() was called."
    );

    function throwOnDestroyed() {
      //>>includeStart('debug', pragmas.debug);
      throw new DeveloperError(message);
      //>>includeEnd('debug');
    }

    for (const key in object) {
      if (typeof object[key] === "function") {
        object[key] = throwOnDestroyed;
      }
    }

    object.isDestroyed = returnTrue;

    return undefined;
  }

  function canTransferArrayBuffer() {
    if (!defined(TaskProcessor._canTransferArrayBuffer)) {
      const worker = new Worker(
        getWorkerUrl("Workers/transferTypedArrayTest.js")
      );
      worker.postMessage = defaultValue(
        worker.webkitPostMessage,
        worker.postMessage
      );

      const value = 99;
      const array = new Int8Array([value]);

      try {
        // postMessage might fail with a DataCloneError
        // if transferring array buffers is not supported.
        worker.postMessage(
          {
            array: array,
          },
          [array.buffer]
        );
      } catch (e) {
        TaskProcessor._canTransferArrayBuffer = false;
        return TaskProcessor._canTransferArrayBuffer;
      }

      const deferred = defer();

      worker.onmessage = function (event) {
        const array = event.data.array;

        // some versions of Firefox silently fail to transfer typed arrays.
        // https://bugzilla.mozilla.org/show_bug.cgi?id=841904
        // Check to make sure the value round-trips successfully.
        const result = defined(array) && array[0] === value;
        deferred.resolve(result);

        worker.terminate();

        TaskProcessor._canTransferArrayBuffer = result;
      };

      TaskProcessor._canTransferArrayBuffer = deferred.promise;
    }

    return TaskProcessor._canTransferArrayBuffer;
  }

  const taskCompletedEvent = new Event();

  function completeTask(processor, data) {
    --processor._activeTasks;

    const id = data.id;
    if (!defined(id)) {
      // This is not one of ours.
      return;
    }

    const deferreds = processor._deferreds;
    const deferred = deferreds[id];

    if (defined(data.error)) {
      let error = data.error;
      if (error.name === "RuntimeError") {
        error = new RuntimeError(data.error.message);
        error.stack = data.error.stack;
      } else if (error.name === "DeveloperError") {
        error = new DeveloperError(data.error.message);
        error.stack = data.error.stack;
      }
      taskCompletedEvent.raiseEvent(error);
      deferred.reject(error);
    } else {
      taskCompletedEvent.raiseEvent();
      deferred.resolve(data.result);
    }

    delete deferreds[id];
  }

  function getWorkerUrl(moduleID) {
    let url = buildModuleUrl(moduleID);

    if (isCrossOriginUrl(url)) {
      //to load cross-origin, create a shim worker from a blob URL
      const script = `importScripts("${url}");`;

      let blob;
      try {
        blob = new Blob([script], {
          type: "application/javascript",
        });
      } catch (e) {
        const BlobBuilder =
          window.BlobBuilder ||
          window.WebKitBlobBuilder ||
          window.MozBlobBuilder ||
          window.MSBlobBuilder;
        const blobBuilder = new BlobBuilder();
        blobBuilder.append(script);
        blob = blobBuilder.getBlob("application/javascript");
      }

      const URL = window.URL || window.webkitURL;
      url = URL.createObjectURL(blob);
    }

    return url;
  }

  let bootstrapperUrlResult;
  function getBootstrapperUrl() {
    if (!defined(bootstrapperUrlResult)) {
      bootstrapperUrlResult = getWorkerUrl("Workers/cesiumWorkerBootstrapper.js");
    }
    return bootstrapperUrlResult;
  }

  function createWorker(processor) {
    const worker = new Worker(getBootstrapperUrl());
    worker.postMessage = defaultValue(
      worker.webkitPostMessage,
      worker.postMessage
    );

    const bootstrapMessage = {
      loaderConfig: {
        paths: {
          Workers: buildModuleUrl("Workers"),
        },
        baseUrl: buildModuleUrl.getCesiumBaseUrl().url,
      },
      workerModule: processor._workerPath,
    };

    worker.postMessage(bootstrapMessage);
    worker.onmessage = function (event) {
      completeTask(processor, event.data);
    };

    return worker;
  }

  function getWebAssemblyLoaderConfig(processor, wasmOptions) {
    const config = {
      modulePath: undefined,
      wasmBinaryFile: undefined,
      wasmBinary: undefined,
    };

    // Web assembly not supported, use fallback js module if provided
    if (!FeatureDetection.supportsWebAssembly()) {
      if (!defined(wasmOptions.fallbackModulePath)) {
        throw new RuntimeError(
          `This browser does not support Web Assembly, and no backup module was provided for ${processor._workerPath}`
        );
      }

      config.modulePath = buildModuleUrl(wasmOptions.fallbackModulePath);
      return Promise.resolve(config);
    }

    config.modulePath = buildModuleUrl(wasmOptions.modulePath);
    config.wasmBinaryFile = buildModuleUrl(wasmOptions.wasmBinaryFile);

    return Resource.fetchArrayBuffer({
      url: config.wasmBinaryFile,
    }).then(function (arrayBuffer) {
      config.wasmBinary = arrayBuffer;
      return config;
    });
  }

  /**
   * A wrapper around a web worker that allows scheduling tasks for a given worker,
   * returning results asynchronously via a promise.
   *
   * The Worker is not constructed until a task is scheduled.
   *
   * @alias TaskProcessor
   * @constructor
   *
   * @param {String} workerPath The Url to the worker. This can either be an absolute path or relative to the Cesium Workers folder.
   * @param {Number} [maximumActiveTasks=Number.POSITIVE_INFINITY] The maximum number of active tasks.  Once exceeded,
   *                                        scheduleTask will not queue any more tasks, allowing
   *                                        work to be rescheduled in future frames.
   */
  function TaskProcessor(workerPath, maximumActiveTasks) {
    const uri = new URI(workerPath);
    this._workerPath =
      uri.scheme().length !== 0 && uri.fragment().length === 0
        ? workerPath
        : TaskProcessor._workerModulePrefix + workerPath;
    this._maximumActiveTasks = defaultValue(
      maximumActiveTasks,
      Number.POSITIVE_INFINITY
    );
    this._activeTasks = 0;
    this._deferreds = {};
    this._nextID = 0;
  }

  const emptyTransferableObjectArray = [];

  /**
   * Schedule a task to be processed by the web worker asynchronously.  If there are currently more
   * tasks active than the maximum set by the constructor, will immediately return undefined.
   * Otherwise, returns a promise that will resolve to the result posted back by the worker when
   * finished.
   *
   * @param {Object} parameters Any input data that will be posted to the worker.
   * @param {Object[]} [transferableObjects] An array of objects contained in parameters that should be
   *                                      transferred to the worker instead of copied.
   * @returns {Promise.<Object>|undefined} Either a promise that will resolve to the result when available, or undefined
   *                    if there are too many active tasks,
   *
   * @example
   * const taskProcessor = new Cesium.TaskProcessor('myWorkerPath');
   * const promise = taskProcessor.scheduleTask({
   *     someParameter : true,
   *     another : 'hello'
   * });
   * if (!Cesium.defined(promise)) {
   *     // too many active tasks - try again later
   * } else {
   *     promise.then(function(result) {
   *         // use the result of the task
   *     });
   * }
   */
  TaskProcessor.prototype.scheduleTask = function (
    parameters,
    transferableObjects
  ) {
    if (!defined(this._worker)) {
      this._worker = createWorker(this);
    }

    if (this._activeTasks >= this._maximumActiveTasks) {
      return undefined;
    }

    ++this._activeTasks;

    const processor = this;
    return Promise.resolve(canTransferArrayBuffer()).then(function (
      canTransferArrayBuffer
    ) {
      if (!defined(transferableObjects)) {
        transferableObjects = emptyTransferableObjectArray;
      } else if (!canTransferArrayBuffer) {
        transferableObjects.length = 0;
      }

      const id = processor._nextID++;
      const deferred = defer();
      processor._deferreds[id] = deferred;

      processor._worker.postMessage(
        {
          id: id,
          parameters: parameters,
          canTransferArrayBuffer: canTransferArrayBuffer,
        },
        transferableObjects
      );

      return deferred.promise;
    });
  };

  /**
   * Posts a message to a web worker with configuration to initialize loading
   * and compiling a web assembly module asychronously, as well as an optional
   * fallback JavaScript module to use if Web Assembly is not supported.
   *
   * @param {Object} [webAssemblyOptions] An object with the following properties:
   * @param {String} [webAssemblyOptions.modulePath] The path of the web assembly JavaScript wrapper module.
   * @param {String} [webAssemblyOptions.wasmBinaryFile] The path of the web assembly binary file.
   * @param {String} [webAssemblyOptions.fallbackModulePath] The path of the fallback JavaScript module to use if web assembly is not supported.
   * @returns {Promise.<Object>} A promise that resolves to the result when the web worker has loaded and compiled the web assembly module and is ready to process tasks.
   */
  TaskProcessor.prototype.initWebAssemblyModule = function (webAssemblyOptions) {
    if (!defined(this._worker)) {
      this._worker = createWorker(this);
    }

    const deferred = defer();
    const processor = this;
    const worker = this._worker;
    getWebAssemblyLoaderConfig(this, webAssemblyOptions).then(function (
      wasmConfig
    ) {
      return Promise.resolve(canTransferArrayBuffer()).then(function (
        canTransferArrayBuffer
      ) {
        let transferableObjects;
        const binary = wasmConfig.wasmBinary;
        if (defined(binary) && canTransferArrayBuffer) {
          transferableObjects = [binary];
        }

        worker.onmessage = function (event) {
          worker.onmessage = function (event) {
            completeTask(processor, event.data);
          };

          deferred.resolve(event.data);
        };

        worker.postMessage(
          { webAssemblyConfig: wasmConfig },
          transferableObjects
        );
      });
    });

    return deferred.promise;
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} True if this object was destroyed; otherwise, false.
   *
   * @see TaskProcessor#destroy
   */
  TaskProcessor.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys this object.  This will immediately terminate the Worker.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   */
  TaskProcessor.prototype.destroy = function () {
    if (defined(this._worker)) {
      this._worker.terminate();
    }
    return destroyObject(this);
  };

  /**
   * An event that's raised when a task is completed successfully.  Event handlers are passed
   * the error object is a task fails.
   *
   * @type {Event}
   *
   * @private
   */
  TaskProcessor.taskCompletedEvent = taskCompletedEvent;

  // exposed for testing purposes
  TaskProcessor._defaultWorkerModulePrefix = "Workers/";
  TaskProcessor._workerModulePrefix = TaskProcessor._defaultWorkerModulePrefix;
  TaskProcessor._canTransferArrayBuffer = undefined;

  /**
   * Terrain data for a single tile.  This type describes an
   * interface and is not intended to be instantiated directly.
   *
   * @alias TerrainData
   * @constructor
   *
   * @see HeightmapTerrainData
   * @see QuantizedMeshTerrainData
   * @see GoogleEarthEnterpriseTerrainData
   */
  function TerrainData() {
    DeveloperError.throwInstantiationError();
  }

  Object.defineProperties(TerrainData.prototype, {
    /**
     * An array of credits for this tile.
     * @memberof TerrainData.prototype
     * @type {Credit[]}
     */
    credits: {
      get: DeveloperError.throwInstantiationError,
    },
    /**
     * The water mask included in this terrain data, if any.  A water mask is a rectangular
     * Uint8Array or image where a value of 255 indicates water and a value of 0 indicates land.
     * Values in between 0 and 255 are allowed as well to smoothly blend between land and water.
     * @memberof TerrainData.prototype
     * @type {Uint8Array|HTMLImageElement|HTMLCanvasElement}
     */
    waterMask: {
      get: DeveloperError.throwInstantiationError,
    },
  });

  /**
   * Computes the terrain height at a specified longitude and latitude.
   * @function
   *
   * @param {Rectangle} rectangle The rectangle covered by this terrain data.
   * @param {Number} longitude The longitude in radians.
   * @param {Number} latitude The latitude in radians.
   * @returns {Number} The terrain height at the specified position.  If the position
   *          is outside the rectangle, this method will extrapolate the height, which is likely to be wildly
   *          incorrect for positions far outside the rectangle.
   */
  TerrainData.prototype.interpolateHeight =
    DeveloperError.throwInstantiationError;

  /**
   * Determines if a given child tile is available, based on the
   * {@link TerrainData#childTileMask}.  The given child tile coordinates are assumed
   * to be one of the four children of this tile.  If non-child tile coordinates are
   * given, the availability of the southeast child tile is returned.
   * @function
   *
   * @param {Number} thisX The tile X coordinate of this (the parent) tile.
   * @param {Number} thisY The tile Y coordinate of this (the parent) tile.
   * @param {Number} childX The tile X coordinate of the child tile to check for availability.
   * @param {Number} childY The tile Y coordinate of the child tile to check for availability.
   * @returns {Boolean} True if the child tile is available; otherwise, false.
   */
  TerrainData.prototype.isChildAvailable = DeveloperError.throwInstantiationError;

  /**
   * Creates a {@link TerrainMesh} from this terrain data.
   * @function
   *
   * @private
   *
   * @param {Object} options Object with the following properties:
   * @param {TilingScheme} options.tilingScheme The tiling scheme to which this tile belongs.
   * @param {Number} options.x The X coordinate of the tile for which to create the terrain data.
   * @param {Number} options.y The Y coordinate of the tile for which to create the terrain data.
   * @param {Number} options.level The level of the tile for which to create the terrain data.
   * @param {Number} [options.exaggeration=1.0] The scale used to exaggerate the terrain.
   * @param {Number} [options.exaggerationRelativeHeight=0.0] The height relative to which terrain is exaggerated.
   * @param {Boolean} [options.throttle=true] If true, indicates that this operation will need to be retried if too many asynchronous mesh creations are already in progress.
   * @returns {Promise.<TerrainMesh>|undefined} A promise for the terrain mesh, or undefined if too many
   *          asynchronous mesh creations are already in progress and the operation should
   *          be retried later.
   */
  TerrainData.prototype.createMesh = DeveloperError.throwInstantiationError;

  /**
   * Upsamples this terrain data for use by a descendant tile.
   * @function
   *
   * @param {TilingScheme} tilingScheme The tiling scheme of this terrain data.
   * @param {Number} thisX The X coordinate of this tile in the tiling scheme.
   * @param {Number} thisY The Y coordinate of this tile in the tiling scheme.
   * @param {Number} thisLevel The level of this tile in the tiling scheme.
   * @param {Number} descendantX The X coordinate within the tiling scheme of the descendant tile for which we are upsampling.
   * @param {Number} descendantY The Y coordinate within the tiling scheme of the descendant tile for which we are upsampling.
   * @param {Number} descendantLevel The level within the tiling scheme of the descendant tile for which we are upsampling.
   * @returns {Promise.<TerrainData>|undefined} A promise for upsampled terrain data for the descendant tile,
   *          or undefined if too many asynchronous upsample operations are in progress and the request has been
   *          deferred.
   */
  TerrainData.prototype.upsample = DeveloperError.throwInstantiationError;

  /**
   * Gets a value indicating whether or not this terrain data was created by upsampling lower resolution
   * terrain data.  If this value is false, the data was obtained from some other source, such
   * as by downloading it from a remote server.  This method should return true for instances
   * returned from a call to {@link TerrainData#upsample}.
   * @function
   *
   * @returns {Boolean} True if this instance was created by upsampling; otherwise, false.
   */
  TerrainData.prototype.wasCreatedByUpsampling =
    DeveloperError.throwInstantiationError;

  /**
   * The maximum number of asynchronous tasks used for terrain processing.
   *
   * @type {Number}
   * @private
   */
  TerrainData.maximumAsynchronousTasks = 5;

  /**
   * A mesh plus related metadata for a single tile of terrain.  Instances of this type are
   * usually created from raw {@link TerrainData}.
   *
   * @alias TerrainMesh
   * @constructor
   *
   * @param {Cartesian3} center The center of the tile.  Vertex positions are specified relative to this center.
   * @param {Float32Array} vertices The vertex data, including positions, texture coordinates, and heights.
   *                       The vertex data is in the order [X, Y, Z, H, U, V], where X, Y, and Z represent
   *                       the Cartesian position of the vertex, H is the height above the ellipsoid, and
   *                       U and V are the texture coordinates.
   * @param {Uint8Array|Uint16Array|Uint32Array} indices The indices describing how the vertices are connected to form triangles.
   * @param {Number} indexCountWithoutSkirts The index count of the mesh not including skirts.
   * @param {Number} vertexCountWithoutSkirts The vertex count of the mesh not including skirts.
   * @param {Number} minimumHeight The lowest height in the tile, in meters above the ellipsoid.
   * @param {Number} maximumHeight The highest height in the tile, in meters above the ellipsoid.
   * @param {BoundingSphere} boundingSphere3D A bounding sphere that completely contains the tile.
   * @param {Cartesian3} occludeePointInScaledSpace The occludee point of the tile, represented in ellipsoid-
   *                     scaled space, and used for horizon culling.  If this point is below the horizon,
   *                     the tile is considered to be entirely below the horizon.
   * @param {Number} [vertexStride=6] The number of components in each vertex.
   * @param {OrientedBoundingBox} [orientedBoundingBox] A bounding box that completely contains the tile.
   * @param {TerrainEncoding} encoding Information used to decode the mesh.
   * @param {Number[]} westIndicesSouthToNorth The indices of the vertices on the Western edge of the tile, ordered from South to North (clockwise).
   * @param {Number[]} southIndicesEastToWest The indices of the vertices on the Southern edge of the tile, ordered from East to West (clockwise).
   * @param {Number[]} eastIndicesNorthToSouth The indices of the vertices on the Eastern edge of the tile, ordered from North to South (clockwise).
   * @param {Number[]} northIndicesWestToEast The indices of the vertices on the Northern edge of the tile, ordered from West to East (clockwise).
   *
   * @private
   */
  function TerrainMesh(
    center,
    vertices,
    indices,
    indexCountWithoutSkirts,
    vertexCountWithoutSkirts,
    minimumHeight,
    maximumHeight,
    boundingSphere3D,
    occludeePointInScaledSpace,
    vertexStride,
    orientedBoundingBox,
    encoding,
    westIndicesSouthToNorth,
    southIndicesEastToWest,
    eastIndicesNorthToSouth,
    northIndicesWestToEast
  ) {
    /**
     * The center of the tile.  Vertex positions are specified relative to this center.
     * @type {Cartesian3}
     */
    this.center = center;

    /**
     * The vertex data, including positions, texture coordinates, and heights.
     * The vertex data is in the order [X, Y, Z, H, U, V], where X, Y, and Z represent
     * the Cartesian position of the vertex, H is the height above the ellipsoid, and
     * U and V are the texture coordinates.  The vertex data may have additional attributes after those
     * mentioned above when the {@link TerrainMesh#stride} is greater than 6.
     * @type {Float32Array}
     */
    this.vertices = vertices;

    /**
     * The number of components in each vertex.  Typically this is 6 for the 6 components
     * [X, Y, Z, H, U, V], but if each vertex has additional data (such as a vertex normal), this value
     * may be higher.
     * @type {Number}
     */
    this.stride = defaultValue(vertexStride, 6);

    /**
     * The indices describing how the vertices are connected to form triangles.
     * @type {Uint8Array|Uint16Array|Uint32Array}
     */
    this.indices = indices;

    /**
     * The index count of the mesh not including skirts.
     * @type {Number}
     */
    this.indexCountWithoutSkirts = indexCountWithoutSkirts;

    /**
     * The vertex count of the mesh not including skirts.
     * @type {Number}
     */
    this.vertexCountWithoutSkirts = vertexCountWithoutSkirts;

    /**
     * The lowest height in the tile, in meters above the ellipsoid.
     * @type {Number}
     */
    this.minimumHeight = minimumHeight;

    /**
     * The highest height in the tile, in meters above the ellipsoid.
     * @type {Number}
     */
    this.maximumHeight = maximumHeight;

    /**
     * A bounding sphere that completely contains the tile.
     * @type {BoundingSphere}
     */
    this.boundingSphere3D = boundingSphere3D;

    /**
     * The occludee point of the tile, represented in ellipsoid-
     * scaled space, and used for horizon culling.  If this point is below the horizon,
     * the tile is considered to be entirely below the horizon.
     * @type {Cartesian3}
     */
    this.occludeePointInScaledSpace = occludeePointInScaledSpace;

    /**
     * A bounding box that completely contains the tile.
     * @type {OrientedBoundingBox}
     */
    this.orientedBoundingBox = orientedBoundingBox;

    /**
     * Information for decoding the mesh vertices.
     * @type {TerrainEncoding}
     */
    this.encoding = encoding;

    /**
     * The indices of the vertices on the Western edge of the tile, ordered from South to North (clockwise).
     * @type {Number[]}
     */
    this.westIndicesSouthToNorth = westIndicesSouthToNorth;

    /**
     * The indices of the vertices on the Southern edge of the tile, ordered from East to West (clockwise).
     * @type {Number[]}
     */
    this.southIndicesEastToWest = southIndicesEastToWest;

    /**
     * The indices of the vertices on the Eastern edge of the tile, ordered from North to South (clockwise).
     * @type {Number[]}
     */
    this.eastIndicesNorthToSouth = eastIndicesNorthToSouth;

    /**
     * The indices of the vertices on the Northern edge of the tile, ordered from West to East (clockwise).
     * @type {Number[]}
     */
    this.northIndicesWestToEast = northIndicesWestToEast;
  }

  /**
   * Constants for WebGL index datatypes.  These corresponds to the
   * <code>type</code> parameter of {@link http://www.khronos.org/opengles/sdk/docs/man/xhtml/glDrawElements.xml|drawElements}.
   *
   * @enum {Number}
   */
  const IndexDatatype = {
    /**
     * 8-bit unsigned byte corresponding to <code>UNSIGNED_BYTE</code> and the type
     * of an element in <code>Uint8Array</code>.
     *
     * @type {Number}
     * @constant
     */
    UNSIGNED_BYTE: WebGLConstants$1.UNSIGNED_BYTE,

    /**
     * 16-bit unsigned short corresponding to <code>UNSIGNED_SHORT</code> and the type
     * of an element in <code>Uint16Array</code>.
     *
     * @type {Number}
     * @constant
     */
    UNSIGNED_SHORT: WebGLConstants$1.UNSIGNED_SHORT,

    /**
     * 32-bit unsigned int corresponding to <code>UNSIGNED_INT</code> and the type
     * of an element in <code>Uint32Array</code>.
     *
     * @type {Number}
     * @constant
     */
    UNSIGNED_INT: WebGLConstants$1.UNSIGNED_INT,
  };

  /**
   * Returns the size, in bytes, of the corresponding datatype.
   *
   * @param {IndexDatatype} indexDatatype The index datatype to get the size of.
   * @returns {Number} The size in bytes.
   *
   * @example
   * // Returns 2
   * const size = Cesium.IndexDatatype.getSizeInBytes(Cesium.IndexDatatype.UNSIGNED_SHORT);
   */
  IndexDatatype.getSizeInBytes = function (indexDatatype) {
    switch (indexDatatype) {
      case IndexDatatype.UNSIGNED_BYTE:
        return Uint8Array.BYTES_PER_ELEMENT;
      case IndexDatatype.UNSIGNED_SHORT:
        return Uint16Array.BYTES_PER_ELEMENT;
      case IndexDatatype.UNSIGNED_INT:
        return Uint32Array.BYTES_PER_ELEMENT;
    }

    //>>includeStart('debug', pragmas.debug);
    throw new DeveloperError(
      "indexDatatype is required and must be a valid IndexDatatype constant."
    );
    //>>includeEnd('debug');
  };

  /**
   * Gets the datatype with a given size in bytes.
   *
   * @param {Number} sizeInBytes The size of a single index in bytes.
   * @returns {IndexDatatype} The index datatype with the given size.
   */
  IndexDatatype.fromSizeInBytes = function (sizeInBytes) {
    switch (sizeInBytes) {
      case 2:
        return IndexDatatype.UNSIGNED_SHORT;
      case 4:
        return IndexDatatype.UNSIGNED_INT;
      case 1:
        return IndexDatatype.UNSIGNED_BYTE;
      //>>includeStart('debug', pragmas.debug);
      default:
        throw new DeveloperError(
          "Size in bytes cannot be mapped to an IndexDatatype"
        );
      //>>includeEnd('debug');
    }
  };

  /**
   * Validates that the provided index datatype is a valid {@link IndexDatatype}.
   *
   * @param {IndexDatatype} indexDatatype The index datatype to validate.
   * @returns {Boolean} <code>true</code> if the provided index datatype is a valid value; otherwise, <code>false</code>.
   *
   * @example
   * if (!Cesium.IndexDatatype.validate(indexDatatype)) {
   *   throw new Cesium.DeveloperError('indexDatatype must be a valid value.');
   * }
   */
  IndexDatatype.validate = function (indexDatatype) {
    return (
      defined(indexDatatype) &&
      (indexDatatype === IndexDatatype.UNSIGNED_BYTE ||
        indexDatatype === IndexDatatype.UNSIGNED_SHORT ||
        indexDatatype === IndexDatatype.UNSIGNED_INT)
    );
  };

  /**
   * Creates a typed array that will store indices, using either <code><Uint16Array</code>
   * or <code>Uint32Array</code> depending on the number of vertices.
   *
   * @param {Number} numberOfVertices Number of vertices that the indices will reference.
   * @param {Number|Array} indicesLengthOrArray Passed through to the typed array constructor.
   * @returns {Uint16Array|Uint32Array} A <code>Uint16Array</code> or <code>Uint32Array</code> constructed with <code>indicesLengthOrArray</code>.
   *
   * @example
   * this.indices = Cesium.IndexDatatype.createTypedArray(positions.length / 3, numberOfIndices);
   */
  IndexDatatype.createTypedArray = function (
    numberOfVertices,
    indicesLengthOrArray
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(numberOfVertices)) {
      throw new DeveloperError("numberOfVertices is required.");
    }
    //>>includeEnd('debug');

    if (numberOfVertices >= CesiumMath.SIXTY_FOUR_KILOBYTES) {
      return new Uint32Array(indicesLengthOrArray);
    }

    return new Uint16Array(indicesLengthOrArray);
  };

  /**
   * Creates a typed array from a source array buffer.  The resulting typed array will store indices, using either <code><Uint16Array</code>
   * or <code>Uint32Array</code> depending on the number of vertices.
   *
   * @param {Number} numberOfVertices Number of vertices that the indices will reference.
   * @param {ArrayBuffer} sourceArray Passed through to the typed array constructor.
   * @param {Number} byteOffset Passed through to the typed array constructor.
   * @param {Number} length Passed through to the typed array constructor.
   * @returns {Uint16Array|Uint32Array} A <code>Uint16Array</code> or <code>Uint32Array</code> constructed with <code>sourceArray</code>, <code>byteOffset</code>, and <code>length</code>.
   *
   */
  IndexDatatype.createTypedArrayFromArrayBuffer = function (
    numberOfVertices,
    sourceArray,
    byteOffset,
    length
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(numberOfVertices)) {
      throw new DeveloperError("numberOfVertices is required.");
    }
    if (!defined(sourceArray)) {
      throw new DeveloperError("sourceArray is required.");
    }
    if (!defined(byteOffset)) {
      throw new DeveloperError("byteOffset is required.");
    }
    //>>includeEnd('debug');

    if (numberOfVertices >= CesiumMath.SIXTY_FOUR_KILOBYTES) {
      return new Uint32Array(sourceArray, byteOffset, length);
    }

    return new Uint16Array(sourceArray, byteOffset, length);
  };

  /**
   * Gets the {@link IndexDatatype} for the provided TypedArray instance.
   *
   * @param {Uint8Array|Uint16Array|Uint32Array} array The typed array.
   * @returns {IndexDatatype} The IndexDatatype for the provided array, or undefined if the array is not a Uint8Array, Uint16Array, or Uint32Array.
   */
  IndexDatatype.fromTypedArray = function (array) {
    if (array instanceof Uint8Array) {
      return IndexDatatype.UNSIGNED_BYTE;
    }
    if (array instanceof Uint16Array) {
      return IndexDatatype.UNSIGNED_SHORT;
    }
    if (array instanceof Uint32Array) {
      return IndexDatatype.UNSIGNED_INT;
    }

    //>>includeStart('debug', pragmas.debug);
    throw new DeveloperError(
      "array must be a Uint8Array, Uint16Array, or Uint32Array."
    );
    //>>includeEnd('debug');
  };

  var IndexDatatype$1 = Object.freeze(IndexDatatype);

  /**
   * Provides terrain or other geometry for the surface of an ellipsoid.  The surface geometry is
   * organized into a pyramid of tiles according to a {@link TilingScheme}.  This type describes an
   * interface and is not intended to be instantiated directly.
   *
   * @alias TerrainProvider
   * @constructor
   *
   * @see EllipsoidTerrainProvider
   * @see CesiumTerrainProvider
   * @see VRTheWorldTerrainProvider
   * @see GoogleEarthEnterpriseTerrainProvider
   */
  function TerrainProvider() {
    DeveloperError.throwInstantiationError();
  }

  Object.defineProperties(TerrainProvider.prototype, {
    /**
     * Gets an event that is raised when the terrain provider encounters an asynchronous error..  By subscribing
     * to the event, you will be notified of the error and can potentially recover from it.  Event listeners
     * are passed an instance of {@link TileProviderError}.
     * @memberof TerrainProvider.prototype
     * @type {Event<TerrainProvider.ErrorEvent>}
     * @readonly
     */
    errorEvent: {
      get: DeveloperError.throwInstantiationError,
    },

    /**
     * Gets the credit to display when this terrain provider is active.  Typically this is used to credit
     * the source of the terrain. This function should
     * not be called before {@link TerrainProvider#ready} returns true.
     * @memberof TerrainProvider.prototype
     * @type {Credit}
     * @readonly
     */
    credit: {
      get: DeveloperError.throwInstantiationError,
    },

    /**
     * Gets the tiling scheme used by the provider.  This function should
     * not be called before {@link TerrainProvider#ready} returns true.
     * @memberof TerrainProvider.prototype
     * @type {TilingScheme}
     * @readonly
     */
    tilingScheme: {
      get: DeveloperError.throwInstantiationError,
    },

    /**
     * Gets a value indicating whether or not the provider is ready for use.
     * @memberof TerrainProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    ready: {
      get: DeveloperError.throwInstantiationError,
    },

    /**
     * Gets a promise that resolves to true when the provider is ready for use.
     * @memberof TerrainProvider.prototype
     * @type {Promise.<Boolean>}
     * @readonly
     */
    readyPromise: {
      get: DeveloperError.throwInstantiationError,
    },

    /**
     * Gets a value indicating whether or not the provider includes a water mask.  The water mask
     * indicates which areas of the globe are water rather than land, so they can be rendered
     * as a reflective surface with animated waves.  This function should not be
     * called before {@link TerrainProvider#ready} returns true.
     * @memberof TerrainProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    hasWaterMask: {
      get: DeveloperError.throwInstantiationError,
    },

    /**
     * Gets a value indicating whether or not the requested tiles include vertex normals.
     * This function should not be called before {@link TerrainProvider#ready} returns true.
     * @memberof TerrainProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    hasVertexNormals: {
      get: DeveloperError.throwInstantiationError,
    },

    /**
     * Gets an object that can be used to determine availability of terrain from this provider, such as
     * at points and in rectangles.  This function should not be called before
     * {@link TerrainProvider#ready} returns true.  This property may be undefined if availability
     * information is not available.
     * @memberof TerrainProvider.prototype
     * @type {TileAvailability}
     * @readonly
     */
    availability: {
      get: DeveloperError.throwInstantiationError,
    },
  });

  const regularGridIndicesCache = [];

  /**
   * Gets a list of indices for a triangle mesh representing a regular grid.  Calling
   * this function multiple times with the same grid width and height returns the
   * same list of indices.  The total number of vertices must be less than or equal
   * to 65536.
   *
   * @param {Number} width The number of vertices in the regular grid in the horizontal direction.
   * @param {Number} height The number of vertices in the regular grid in the vertical direction.
   * @returns {Uint16Array|Uint32Array} The list of indices. Uint16Array gets returned for 64KB or less and Uint32Array for 4GB or less.
   */
  TerrainProvider.getRegularGridIndices = function (width, height) {
    //>>includeStart('debug', pragmas.debug);
    if (width * height >= CesiumMath.FOUR_GIGABYTES) {
      throw new DeveloperError(
        "The total number of vertices (width * height) must be less than 4,294,967,296."
      );
    }
    //>>includeEnd('debug');

    let byWidth = regularGridIndicesCache[width];
    if (!defined(byWidth)) {
      regularGridIndicesCache[width] = byWidth = [];
    }

    let indices = byWidth[height];
    if (!defined(indices)) {
      if (width * height < CesiumMath.SIXTY_FOUR_KILOBYTES) {
        indices = byWidth[height] = new Uint16Array(
          (width - 1) * (height - 1) * 6
        );
      } else {
        indices = byWidth[height] = new Uint32Array(
          (width - 1) * (height - 1) * 6
        );
      }
      addRegularGridIndices(width, height, indices, 0);
    }

    return indices;
  };

  const regularGridAndEdgeIndicesCache = [];

  /**
   * @private
   */
  TerrainProvider.getRegularGridIndicesAndEdgeIndices = function (width, height) {
    //>>includeStart('debug', pragmas.debug);
    if (width * height >= CesiumMath.FOUR_GIGABYTES) {
      throw new DeveloperError(
        "The total number of vertices (width * height) must be less than 4,294,967,296."
      );
    }
    //>>includeEnd('debug');

    let byWidth = regularGridAndEdgeIndicesCache[width];
    if (!defined(byWidth)) {
      regularGridAndEdgeIndicesCache[width] = byWidth = [];
    }

    let indicesAndEdges = byWidth[height];
    if (!defined(indicesAndEdges)) {
      const indices = TerrainProvider.getRegularGridIndices(width, height);

      const edgeIndices = getEdgeIndices(width, height);
      const westIndicesSouthToNorth = edgeIndices.westIndicesSouthToNorth;
      const southIndicesEastToWest = edgeIndices.southIndicesEastToWest;
      const eastIndicesNorthToSouth = edgeIndices.eastIndicesNorthToSouth;
      const northIndicesWestToEast = edgeIndices.northIndicesWestToEast;

      indicesAndEdges = byWidth[height] = {
        indices: indices,
        westIndicesSouthToNorth: westIndicesSouthToNorth,
        southIndicesEastToWest: southIndicesEastToWest,
        eastIndicesNorthToSouth: eastIndicesNorthToSouth,
        northIndicesWestToEast: northIndicesWestToEast,
      };
    }

    return indicesAndEdges;
  };

  const regularGridAndSkirtAndEdgeIndicesCache = [];

  /**
   * @private
   */
  TerrainProvider.getRegularGridAndSkirtIndicesAndEdgeIndices = function (
    width,
    height
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (width * height >= CesiumMath.FOUR_GIGABYTES) {
      throw new DeveloperError(
        "The total number of vertices (width * height) must be less than 4,294,967,296."
      );
    }
    //>>includeEnd('debug');

    let byWidth = regularGridAndSkirtAndEdgeIndicesCache[width];
    if (!defined(byWidth)) {
      regularGridAndSkirtAndEdgeIndicesCache[width] = byWidth = [];
    }

    let indicesAndEdges = byWidth[height];
    if (!defined(indicesAndEdges)) {
      const gridVertexCount = width * height;
      const gridIndexCount = (width - 1) * (height - 1) * 6;
      const edgeVertexCount = width * 2 + height * 2;
      const edgeIndexCount = Math.max(0, edgeVertexCount - 4) * 6;
      const vertexCount = gridVertexCount + edgeVertexCount;
      const indexCount = gridIndexCount + edgeIndexCount;

      const edgeIndices = getEdgeIndices(width, height);
      const westIndicesSouthToNorth = edgeIndices.westIndicesSouthToNorth;
      const southIndicesEastToWest = edgeIndices.southIndicesEastToWest;
      const eastIndicesNorthToSouth = edgeIndices.eastIndicesNorthToSouth;
      const northIndicesWestToEast = edgeIndices.northIndicesWestToEast;

      const indices = IndexDatatype$1.createTypedArray(vertexCount, indexCount);
      addRegularGridIndices(width, height, indices, 0);
      TerrainProvider.addSkirtIndices(
        westIndicesSouthToNorth,
        southIndicesEastToWest,
        eastIndicesNorthToSouth,
        northIndicesWestToEast,
        gridVertexCount,
        indices,
        gridIndexCount
      );

      indicesAndEdges = byWidth[height] = {
        indices: indices,
        westIndicesSouthToNorth: westIndicesSouthToNorth,
        southIndicesEastToWest: southIndicesEastToWest,
        eastIndicesNorthToSouth: eastIndicesNorthToSouth,
        northIndicesWestToEast: northIndicesWestToEast,
        indexCountWithoutSkirts: gridIndexCount,
      };
    }

    return indicesAndEdges;
  };

  /**
   * @private
   */
  TerrainProvider.addSkirtIndices = function (
    westIndicesSouthToNorth,
    southIndicesEastToWest,
    eastIndicesNorthToSouth,
    northIndicesWestToEast,
    vertexCount,
    indices,
    offset
  ) {
    let vertexIndex = vertexCount;
    offset = addSkirtIndices(
      westIndicesSouthToNorth,
      vertexIndex,
      indices,
      offset
    );
    vertexIndex += westIndicesSouthToNorth.length;
    offset = addSkirtIndices(
      southIndicesEastToWest,
      vertexIndex,
      indices,
      offset
    );
    vertexIndex += southIndicesEastToWest.length;
    offset = addSkirtIndices(
      eastIndicesNorthToSouth,
      vertexIndex,
      indices,
      offset
    );
    vertexIndex += eastIndicesNorthToSouth.length;
    addSkirtIndices(northIndicesWestToEast, vertexIndex, indices, offset);
  };

  function getEdgeIndices(width, height) {
    const westIndicesSouthToNorth = new Array(height);
    const southIndicesEastToWest = new Array(width);
    const eastIndicesNorthToSouth = new Array(height);
    const northIndicesWestToEast = new Array(width);

    let i;
    for (i = 0; i < width; ++i) {
      northIndicesWestToEast[i] = i;
      southIndicesEastToWest[i] = width * height - 1 - i;
    }

    for (i = 0; i < height; ++i) {
      eastIndicesNorthToSouth[i] = (i + 1) * width - 1;
      westIndicesSouthToNorth[i] = (height - i - 1) * width;
    }

    return {
      westIndicesSouthToNorth: westIndicesSouthToNorth,
      southIndicesEastToWest: southIndicesEastToWest,
      eastIndicesNorthToSouth: eastIndicesNorthToSouth,
      northIndicesWestToEast: northIndicesWestToEast,
    };
  }

  function addRegularGridIndices(width, height, indices, offset) {
    let index = 0;
    for (let j = 0; j < height - 1; ++j) {
      for (let i = 0; i < width - 1; ++i) {
        const upperLeft = index;
        const lowerLeft = upperLeft + width;
        const lowerRight = lowerLeft + 1;
        const upperRight = upperLeft + 1;

        indices[offset++] = upperLeft;
        indices[offset++] = lowerLeft;
        indices[offset++] = upperRight;
        indices[offset++] = upperRight;
        indices[offset++] = lowerLeft;
        indices[offset++] = lowerRight;

        ++index;
      }
      ++index;
    }
  }

  function addSkirtIndices(edgeIndices, vertexIndex, indices, offset) {
    let previousIndex = edgeIndices[0];

    const length = edgeIndices.length;
    for (let i = 1; i < length; ++i) {
      const index = edgeIndices[i];

      indices[offset++] = previousIndex;
      indices[offset++] = index;
      indices[offset++] = vertexIndex;

      indices[offset++] = vertexIndex;
      indices[offset++] = index;
      indices[offset++] = vertexIndex + 1;

      previousIndex = index;
      ++vertexIndex;
    }

    return offset;
  }

  /**
   * Specifies the quality of terrain created from heightmaps.  A value of 1.0 will
   * ensure that adjacent heightmap vertices are separated by no more than
   * {@link Globe.maximumScreenSpaceError} screen pixels and will probably go very slowly.
   * A value of 0.5 will cut the estimated level zero geometric error in half, allowing twice the
   * screen pixels between adjacent heightmap vertices and thus rendering more quickly.
   * @type {Number}
   */
  TerrainProvider.heightmapTerrainQuality = 0.25;

  /**
   * Determines an appropriate geometric error estimate when the geometry comes from a heightmap.
   *
   * @param {Ellipsoid} ellipsoid The ellipsoid to which the terrain is attached.
   * @param {Number} tileImageWidth The width, in pixels, of the heightmap associated with a single tile.
   * @param {Number} numberOfTilesAtLevelZero The number of tiles in the horizontal direction at tile level zero.
   * @returns {Number} An estimated geometric error.
   */
  TerrainProvider.getEstimatedLevelZeroGeometricErrorForAHeightmap = function (
    ellipsoid,
    tileImageWidth,
    numberOfTilesAtLevelZero
  ) {
    return (
      (ellipsoid.maximumRadius *
        2 *
        Math.PI *
        TerrainProvider.heightmapTerrainQuality) /
      (tileImageWidth * numberOfTilesAtLevelZero)
    );
  };

  /**
   * Requests the geometry for a given tile.  This function should not be called before
   * {@link TerrainProvider#ready} returns true.  The result must include terrain data and
   * may optionally include a water mask and an indication of which child tiles are available.
   * @function
   *
   * @param {Number} x The X coordinate of the tile for which to request geometry.
   * @param {Number} y The Y coordinate of the tile for which to request geometry.
   * @param {Number} level The level of the tile for which to request geometry.
   * @param {Request} [request] The request object. Intended for internal use only.
   *
   * @returns {Promise.<TerrainData>|undefined} A promise for the requested geometry.  If this method
   *          returns undefined instead of a promise, it is an indication that too many requests are already
   *          pending and the request will be retried later.
   */
  TerrainProvider.prototype.requestTileGeometry =
    DeveloperError.throwInstantiationError;

  /**
   * Gets the maximum geometric error allowed in a tile at a given level.  This function should not be
   * called before {@link TerrainProvider#ready} returns true.
   * @function
   *
   * @param {Number} level The tile level for which to get the maximum geometric error.
   * @returns {Number} The maximum geometric error.
   */
  TerrainProvider.prototype.getLevelMaximumGeometricError =
    DeveloperError.throwInstantiationError;

  /**
   * Determines whether data for a tile is available to be loaded.
   * @function
   *
   * @param {Number} x The X coordinate of the tile for which to request geometry.
   * @param {Number} y The Y coordinate of the tile for which to request geometry.
   * @param {Number} level The level of the tile for which to request geometry.
   * @returns {Boolean|undefined} Undefined if not supported by the terrain provider, otherwise true or false.
   */
  TerrainProvider.prototype.getTileDataAvailable =
    DeveloperError.throwInstantiationError;

  /**
   * Makes sure we load availability data for a tile
   * @function
   *
   * @param {Number} x The X coordinate of the tile for which to request geometry.
   * @param {Number} y The Y coordinate of the tile for which to request geometry.
   * @param {Number} level The level of the tile for which to request geometry.
   * @returns {undefined|Promise<void>} Undefined if nothing need to be loaded or a Promise that resolves when all required tiles are loaded
   */
  TerrainProvider.prototype.loadTileDataAvailability =
    DeveloperError.throwInstantiationError;

  /**
   * A function that is called when an error occurs.
   * @callback TerrainProvider.ErrorEvent
   *
   * @this TerrainProvider
   * @param {TileProviderError} err An object holding details about the error that occurred.
   */

  /**
   * Terrain data for a single tile where the terrain data is represented as a heightmap.  A heightmap
   * is a rectangular array of heights in row-major order from north to south and west to east.
   *
   * @alias HeightmapTerrainData
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} options.buffer The buffer containing height data.
   * @param {Number} options.width The width (longitude direction) of the heightmap, in samples.
   * @param {Number} options.height The height (latitude direction) of the heightmap, in samples.
   * @param {Number} [options.childTileMask=15] A bit mask indicating which of this tile's four children exist.
   *                 If a child's bit is set, geometry will be requested for that tile as well when it
   *                 is needed.  If the bit is cleared, the child tile is not requested and geometry is
   *                 instead upsampled from the parent.  The bit values are as follows:
   *                 <table>
   *                  <tr><th>Bit Position</th><th>Bit Value</th><th>Child Tile</th></tr>
   *                  <tr><td>0</td><td>1</td><td>Southwest</td></tr>
   *                  <tr><td>1</td><td>2</td><td>Southeast</td></tr>
   *                  <tr><td>2</td><td>4</td><td>Northwest</td></tr>
   *                  <tr><td>3</td><td>8</td><td>Northeast</td></tr>
   *                 </table>
   * @param {Uint8Array} [options.waterMask] The water mask included in this terrain data, if any.  A water mask is a square
   *                     Uint8Array or image where a value of 255 indicates water and a value of 0 indicates land.
   *                     Values in between 0 and 255 are allowed as well to smoothly blend between land and water.
   * @param {Object} [options.structure] An object describing the structure of the height data.
   * @param {Number} [options.structure.heightScale=1.0] The factor by which to multiply height samples in order to obtain
   *                 the height above the heightOffset, in meters.  The heightOffset is added to the resulting
   *                 height after multiplying by the scale.
   * @param {Number} [options.structure.heightOffset=0.0] The offset to add to the scaled height to obtain the final
   *                 height in meters.  The offset is added after the height sample is multiplied by the
   *                 heightScale.
   * @param {Number} [options.structure.elementsPerHeight=1] The number of elements in the buffer that make up a single height
   *                 sample.  This is usually 1, indicating that each element is a separate height sample.  If
   *                 it is greater than 1, that number of elements together form the height sample, which is
   *                 computed according to the structure.elementMultiplier and structure.isBigEndian properties.
   * @param {Number} [options.structure.stride=1] The number of elements to skip to get from the first element of
   *                 one height to the first element of the next height.
   * @param {Number} [options.structure.elementMultiplier=256.0] The multiplier used to compute the height value when the
   *                 stride property is greater than 1.  For example, if the stride is 4 and the strideMultiplier
   *                 is 256, the height is computed as follows:
   *                 `height = buffer[index] + buffer[index + 1] * 256 + buffer[index + 2] * 256 * 256 + buffer[index + 3] * 256 * 256 * 256`
   *                 This is assuming that the isBigEndian property is false.  If it is true, the order of the
   *                 elements is reversed.
   * @param {Boolean} [options.structure.isBigEndian=false] Indicates endianness of the elements in the buffer when the
   *                  stride property is greater than 1.  If this property is false, the first element is the
   *                  low-order element.  If it is true, the first element is the high-order element.
   * @param {Number} [options.structure.lowestEncodedHeight] The lowest value that can be stored in the height buffer.  Any heights that are lower
   *                 than this value after encoding with the `heightScale` and `heightOffset` are clamped to this value.  For example, if the height
   *                 buffer is a `Uint16Array`, this value should be 0 because a `Uint16Array` cannot store negative numbers.  If this parameter is
   *                 not specified, no minimum value is enforced.
   * @param {Number} [options.structure.highestEncodedHeight] The highest value that can be stored in the height buffer.  Any heights that are higher
   *                 than this value after encoding with the `heightScale` and `heightOffset` are clamped to this value.  For example, if the height
   *                 buffer is a `Uint16Array`, this value should be `256 * 256 - 1` or 65535 because a `Uint16Array` cannot store numbers larger
   *                 than 65535.  If this parameter is not specified, no maximum value is enforced.
   * @param {HeightmapEncoding} [options.encoding=HeightmapEncoding.NONE] The encoding that is used on the buffer.
   * @param {Boolean} [options.createdByUpsampling=false] True if this instance was created by upsampling another instance;
   *                  otherwise, false.
   *
   *
   * @example
   * const buffer = ...
   * const heightBuffer = new Uint16Array(buffer, 0, that._heightmapWidth * that._heightmapWidth);
   * const childTileMask = new Uint8Array(buffer, heightBuffer.byteLength, 1)[0];
   * const waterMask = new Uint8Array(buffer, heightBuffer.byteLength + 1, buffer.byteLength - heightBuffer.byteLength - 1);
   * const terrainData = new Cesium.HeightmapTerrainData({
   *   buffer : heightBuffer,
   *   width : 65,
   *   height : 65,
   *   childTileMask : childTileMask,
   *   waterMask : waterMask
   * });
   *
   * @see TerrainData
   * @see QuantizedMeshTerrainData
   * @see GoogleEarthEnterpriseTerrainData
   */
  function HeightmapTerrainData(options) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(options) || !defined(options.buffer)) {
      throw new DeveloperError("options.buffer is required.");
    }
    if (!defined(options.width)) {
      throw new DeveloperError("options.width is required.");
    }
    if (!defined(options.height)) {
      throw new DeveloperError("options.height is required.");
    }
    //>>includeEnd('debug');

    this._buffer = options.buffer;
    this._width = options.width;
    this._height = options.height;
    this._childTileMask = defaultValue(options.childTileMask, 15);
    this._encoding = defaultValue(options.encoding, HeightmapEncoding$1.NONE);

    const defaultStructure = HeightmapTessellator.DEFAULT_STRUCTURE;
    let structure = options.structure;
    if (!defined(structure)) {
      structure = defaultStructure;
    } else if (structure !== defaultStructure) {
      structure.heightScale = defaultValue(
        structure.heightScale,
        defaultStructure.heightScale
      );
      structure.heightOffset = defaultValue(
        structure.heightOffset,
        defaultStructure.heightOffset
      );
      structure.elementsPerHeight = defaultValue(
        structure.elementsPerHeight,
        defaultStructure.elementsPerHeight
      );
      structure.stride = defaultValue(structure.stride, defaultStructure.stride);
      structure.elementMultiplier = defaultValue(
        structure.elementMultiplier,
        defaultStructure.elementMultiplier
      );
      structure.isBigEndian = defaultValue(
        structure.isBigEndian,
        defaultStructure.isBigEndian
      );
    }

    this._structure = structure;
    this._createdByUpsampling = defaultValue(options.createdByUpsampling, false);
    this._waterMask = options.waterMask;

    this._skirtHeight = undefined;
    this._bufferType =
      this._encoding === HeightmapEncoding$1.LERC
        ? Float32Array
        : this._buffer.constructor;
    this._mesh = undefined;
  }

  Object.defineProperties(HeightmapTerrainData.prototype, {
    /**
     * An array of credits for this tile.
     * @memberof HeightmapTerrainData.prototype
     * @type {Credit[]}
     */
    credits: {
      get: function () {
        return undefined;
      },
    },
    /**
     * The water mask included in this terrain data, if any.  A water mask is a square
     * Uint8Array or image where a value of 255 indicates water and a value of 0 indicates land.
     * Values in between 0 and 255 are allowed as well to smoothly blend between land and water.
     * @memberof HeightmapTerrainData.prototype
     * @type {Uint8Array|HTMLImageElement|HTMLCanvasElement}
     */
    waterMask: {
      get: function () {
        return this._waterMask;
      },
    },

    childTileMask: {
      get: function () {
        return this._childTileMask;
      },
    },
  });

  const createMeshTaskName$2 = "createVerticesFromHeightmap";
  const createMeshTaskProcessorNoThrottle$2 = new TaskProcessor(createMeshTaskName$2);
  const createMeshTaskProcessorThrottle$2 = new TaskProcessor(
    createMeshTaskName$2,
    TerrainData.maximumAsynchronousTasks
  );

  /**
   * Creates a {@link TerrainMesh} from this terrain data.
   *
   * @private
   *
   * @param {Object} options Object with the following properties:
   * @param {TilingScheme} options.tilingScheme The tiling scheme to which this tile belongs.
   * @param {Number} options.x The X coordinate of the tile for which to create the terrain data.
   * @param {Number} options.y The Y coordinate of the tile for which to create the terrain data.
   * @param {Number} options.level The level of the tile for which to create the terrain data.
   * @param {Number} [options.exaggeration=1.0] The scale used to exaggerate the terrain.
   * @param {Number} [options.exaggerationRelativeHeight=0.0] The height relative to which terrain is exaggerated.
   * @param {Boolean} [options.throttle=true] If true, indicates that this operation will need to be retried if too many asynchronous mesh creations are already in progress.
   * @returns {Promise.<TerrainMesh>|undefined} A promise for the terrain mesh, or undefined if too many
   *          asynchronous mesh creations are already in progress and the operation should
   *          be retried later.
   */
  HeightmapTerrainData.prototype.createMesh = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.tilingScheme", options.tilingScheme);
    Check.typeOf.number("options.x", options.x);
    Check.typeOf.number("options.y", options.y);
    Check.typeOf.number("options.level", options.level);
    //>>includeEnd('debug');

    const tilingScheme = options.tilingScheme;
    const x = options.x;
    const y = options.y;
    const level = options.level;
    const exaggeration = defaultValue(options.exaggeration, 1.0);
    const exaggerationRelativeHeight = defaultValue(
      options.exaggerationRelativeHeight,
      0.0
    );
    const throttle = defaultValue(options.throttle, true);

    const ellipsoid = tilingScheme.ellipsoid;
    const nativeRectangle = tilingScheme.tileXYToNativeRectangle(x, y, level);
    const rectangle = tilingScheme.tileXYToRectangle(x, y, level);

    // Compute the center of the tile for RTC rendering.
    const center = ellipsoid.cartographicToCartesian(Rectangle.center(rectangle));

    const structure = this._structure;

    const levelZeroMaxError = TerrainProvider.getEstimatedLevelZeroGeometricErrorForAHeightmap(
      ellipsoid,
      this._width,
      tilingScheme.getNumberOfXTilesAtLevel(0)
    );
    const thisLevelMaxError = levelZeroMaxError / (1 << level);
    this._skirtHeight = Math.min(thisLevelMaxError * 4.0, 1000.0);

    const createMeshTaskProcessor = throttle
      ? createMeshTaskProcessorThrottle$2
      : createMeshTaskProcessorNoThrottle$2;

    const verticesPromise = createMeshTaskProcessor.scheduleTask({
      heightmap: this._buffer,
      structure: structure,
      includeWebMercatorT: true,
      width: this._width,
      height: this._height,
      nativeRectangle: nativeRectangle,
      rectangle: rectangle,
      relativeToCenter: center,
      ellipsoid: ellipsoid,
      skirtHeight: this._skirtHeight,
      isGeographic: tilingScheme.projection instanceof GeographicProjection,
      exaggeration: exaggeration,
      exaggerationRelativeHeight: exaggerationRelativeHeight,
      encoding: this._encoding,
    });

    if (!defined(verticesPromise)) {
      // Postponed
      return undefined;
    }

    const that = this;
    return Promise.resolve(verticesPromise).then(function (result) {
      let indicesAndEdges;
      if (that._skirtHeight > 0.0) {
        indicesAndEdges = TerrainProvider.getRegularGridAndSkirtIndicesAndEdgeIndices(
          result.gridWidth,
          result.gridHeight
        );
      } else {
        indicesAndEdges = TerrainProvider.getRegularGridIndicesAndEdgeIndices(
          result.gridWidth,
          result.gridHeight
        );
      }

      const vertexCountWithoutSkirts = result.gridWidth * result.gridHeight;

      // Clone complex result objects because the transfer from the web worker
      // has stripped them down to JSON-style objects.
      that._mesh = new TerrainMesh(
        center,
        new Float32Array(result.vertices),
        indicesAndEdges.indices,
        indicesAndEdges.indexCountWithoutSkirts,
        vertexCountWithoutSkirts,
        result.minimumHeight,
        result.maximumHeight,
        BoundingSphere.clone(result.boundingSphere3D),
        Cartesian3.clone(result.occludeePointInScaledSpace),
        result.numberOfAttributes,
        OrientedBoundingBox.clone(result.orientedBoundingBox),
        TerrainEncoding.clone(result.encoding),
        indicesAndEdges.westIndicesSouthToNorth,
        indicesAndEdges.southIndicesEastToWest,
        indicesAndEdges.eastIndicesNorthToSouth,
        indicesAndEdges.northIndicesWestToEast
      );

      // Free memory received from server after mesh is created.
      that._buffer = undefined;
      return that._mesh;
    });
  };

  /**
   * @param {Object} options Object with the following properties:
   * @param {TilingScheme} options.tilingScheme The tiling scheme to which this tile belongs.
   * @param {Number} options.x The X coordinate of the tile for which to create the terrain data.
   * @param {Number} options.y The Y coordinate of the tile for which to create the terrain data.
   * @param {Number} options.level The level of the tile for which to create the terrain data.
   * @param {Number} [options.exaggeration=1.0] The scale used to exaggerate the terrain.
   * @param {Number} [options.exaggerationRelativeHeight=0.0] The height relative to which terrain is exaggerated.
   *
   * @private
   */
  HeightmapTerrainData.prototype._createMeshSync = function (options) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.tilingScheme", options.tilingScheme);
    Check.typeOf.number("options.x", options.x);
    Check.typeOf.number("options.y", options.y);
    Check.typeOf.number("options.level", options.level);
    //>>includeEnd('debug');

    const tilingScheme = options.tilingScheme;
    const x = options.x;
    const y = options.y;
    const level = options.level;
    const exaggeration = defaultValue(options.exaggeration, 1.0);
    const exaggerationRelativeHeight = defaultValue(
      options.exaggerationRelativeHeight,
      0.0
    );

    const ellipsoid = tilingScheme.ellipsoid;
    const nativeRectangle = tilingScheme.tileXYToNativeRectangle(x, y, level);
    const rectangle = tilingScheme.tileXYToRectangle(x, y, level);

    // Compute the center of the tile for RTC rendering.
    const center = ellipsoid.cartographicToCartesian(Rectangle.center(rectangle));

    const structure = this._structure;

    const levelZeroMaxError = TerrainProvider.getEstimatedLevelZeroGeometricErrorForAHeightmap(
      ellipsoid,
      this._width,
      tilingScheme.getNumberOfXTilesAtLevel(0)
    );
    const thisLevelMaxError = levelZeroMaxError / (1 << level);
    this._skirtHeight = Math.min(thisLevelMaxError * 4.0, 1000.0);

    const result = HeightmapTessellator.computeVertices({
      heightmap: this._buffer,
      structure: structure,
      includeWebMercatorT: true,
      width: this._width,
      height: this._height,
      nativeRectangle: nativeRectangle,
      rectangle: rectangle,
      relativeToCenter: center,
      ellipsoid: ellipsoid,
      skirtHeight: this._skirtHeight,
      isGeographic: tilingScheme.projection instanceof GeographicProjection,
      exaggeration: exaggeration,
      exaggerationRelativeHeight: exaggerationRelativeHeight,
    });

    // Free memory received from server after mesh is created.
    this._buffer = undefined;

    let indicesAndEdges;
    if (this._skirtHeight > 0.0) {
      indicesAndEdges = TerrainProvider.getRegularGridAndSkirtIndicesAndEdgeIndices(
        this._width,
        this._height
      );
    } else {
      indicesAndEdges = TerrainProvider.getRegularGridIndicesAndEdgeIndices(
        this._width,
        this._height
      );
    }

    const vertexCountWithoutSkirts = result.gridWidth * result.gridHeight;

    // No need to clone here (as we do in the async version) because the result
    // is not coming from a web worker.
    this._mesh = new TerrainMesh(
      center,
      result.vertices,
      indicesAndEdges.indices,
      indicesAndEdges.indexCountWithoutSkirts,
      vertexCountWithoutSkirts,
      result.minimumHeight,
      result.maximumHeight,
      result.boundingSphere3D,
      result.occludeePointInScaledSpace,
      result.encoding.stride,
      result.orientedBoundingBox,
      result.encoding,
      indicesAndEdges.westIndicesSouthToNorth,
      indicesAndEdges.southIndicesEastToWest,
      indicesAndEdges.eastIndicesNorthToSouth,
      indicesAndEdges.northIndicesWestToEast
    );

    return this._mesh;
  };

  /**
   * Computes the terrain height at a specified longitude and latitude.
   *
   * @param {Rectangle} rectangle The rectangle covered by this terrain data.
   * @param {Number} longitude The longitude in radians.
   * @param {Number} latitude The latitude in radians.
   * @returns {Number} The terrain height at the specified position.  If the position
   *          is outside the rectangle, this method will extrapolate the height, which is likely to be wildly
   *          incorrect for positions far outside the rectangle.
   */
  HeightmapTerrainData.prototype.interpolateHeight = function (
    rectangle,
    longitude,
    latitude
  ) {
    const width = this._width;
    const height = this._height;

    const structure = this._structure;
    const stride = structure.stride;
    const elementsPerHeight = structure.elementsPerHeight;
    const elementMultiplier = structure.elementMultiplier;
    const isBigEndian = structure.isBigEndian;
    const heightOffset = structure.heightOffset;
    const heightScale = structure.heightScale;

    const isMeshCreated = defined(this._mesh);
    const isLERCEncoding = this._encoding === HeightmapEncoding$1.LERC;
    const isInterpolationImpossible = !isMeshCreated && isLERCEncoding;
    if (isInterpolationImpossible) {
      // We can't interpolate using the buffer because it's LERC encoded
      //  so please call createMesh() first and interpolate using the mesh;
      //  as mesh creation will decode the LERC buffer
      return undefined;
    }

    let heightSample;
    if (isMeshCreated) {
      const buffer = this._mesh.vertices;
      const encoding = this._mesh.encoding;
      heightSample = interpolateMeshHeight$2(
        buffer,
        encoding,
        heightOffset,
        heightScale,
        rectangle,
        width,
        height,
        longitude,
        latitude
      );
    } else {
      heightSample = interpolateHeight$2(
        this._buffer,
        elementsPerHeight,
        elementMultiplier,
        stride,
        isBigEndian,
        rectangle,
        width,
        height,
        longitude,
        latitude
      );
      heightSample = heightSample * heightScale + heightOffset;
    }

    return heightSample;
  };

  /**
   * Upsamples this terrain data for use by a descendant tile.  The resulting instance will contain a subset of the
   * height samples in this instance, interpolated if necessary.
   *
   * @param {TilingScheme} tilingScheme The tiling scheme of this terrain data.
   * @param {Number} thisX The X coordinate of this tile in the tiling scheme.
   * @param {Number} thisY The Y coordinate of this tile in the tiling scheme.
   * @param {Number} thisLevel The level of this tile in the tiling scheme.
   * @param {Number} descendantX The X coordinate within the tiling scheme of the descendant tile for which we are upsampling.
   * @param {Number} descendantY The Y coordinate within the tiling scheme of the descendant tile for which we are upsampling.
   * @param {Number} descendantLevel The level within the tiling scheme of the descendant tile for which we are upsampling.
   * @returns {Promise.<HeightmapTerrainData>|undefined} A promise for upsampled heightmap terrain data for the descendant tile,
   *          or undefined if the mesh is unavailable.
   */
  HeightmapTerrainData.prototype.upsample = function (
    tilingScheme,
    thisX,
    thisY,
    thisLevel,
    descendantX,
    descendantY,
    descendantLevel
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(tilingScheme)) {
      throw new DeveloperError("tilingScheme is required.");
    }
    if (!defined(thisX)) {
      throw new DeveloperError("thisX is required.");
    }
    if (!defined(thisY)) {
      throw new DeveloperError("thisY is required.");
    }
    if (!defined(thisLevel)) {
      throw new DeveloperError("thisLevel is required.");
    }
    if (!defined(descendantX)) {
      throw new DeveloperError("descendantX is required.");
    }
    if (!defined(descendantY)) {
      throw new DeveloperError("descendantY is required.");
    }
    if (!defined(descendantLevel)) {
      throw new DeveloperError("descendantLevel is required.");
    }
    const levelDifference = descendantLevel - thisLevel;
    if (levelDifference > 1) {
      throw new DeveloperError(
        "Upsampling through more than one level at a time is not currently supported."
      );
    }
    //>>includeEnd('debug');

    const meshData = this._mesh;
    if (!defined(meshData)) {
      return undefined;
    }

    const width = this._width;
    const height = this._height;
    const structure = this._structure;
    const stride = structure.stride;

    const heights = new this._bufferType(width * height * stride);

    const buffer = meshData.vertices;
    const encoding = meshData.encoding;

    // PERFORMANCE_IDEA: don't recompute these rectangles - the caller already knows them.
    const sourceRectangle = tilingScheme.tileXYToRectangle(
      thisX,
      thisY,
      thisLevel
    );
    const destinationRectangle = tilingScheme.tileXYToRectangle(
      descendantX,
      descendantY,
      descendantLevel
    );

    const heightOffset = structure.heightOffset;
    const heightScale = structure.heightScale;

    const elementsPerHeight = structure.elementsPerHeight;
    const elementMultiplier = structure.elementMultiplier;
    const isBigEndian = structure.isBigEndian;

    const divisor = Math.pow(elementMultiplier, elementsPerHeight - 1);

    for (let j = 0; j < height; ++j) {
      const latitude = CesiumMath.lerp(
        destinationRectangle.north,
        destinationRectangle.south,
        j / (height - 1)
      );
      for (let i = 0; i < width; ++i) {
        const longitude = CesiumMath.lerp(
          destinationRectangle.west,
          destinationRectangle.east,
          i / (width - 1)
        );
        let heightSample = interpolateMeshHeight$2(
          buffer,
          encoding,
          heightOffset,
          heightScale,
          sourceRectangle,
          width,
          height,
          longitude,
          latitude
        );

        // Use conditionals here instead of Math.min and Math.max so that an undefined
        // lowestEncodedHeight or highestEncodedHeight has no effect.
        heightSample =
          heightSample < structure.lowestEncodedHeight
            ? structure.lowestEncodedHeight
            : heightSample;
        heightSample =
          heightSample > structure.highestEncodedHeight
            ? structure.highestEncodedHeight
            : heightSample;

        setHeight(
          heights,
          elementsPerHeight,
          elementMultiplier,
          divisor,
          stride,
          isBigEndian,
          j * width + i,
          heightSample
        );
      }
    }

    return Promise.resolve(
      new HeightmapTerrainData({
        buffer: heights,
        width: width,
        height: height,
        childTileMask: 0,
        structure: this._structure,
        createdByUpsampling: true,
      })
    );
  };

  /**
   * Determines if a given child tile is available, based on the
   * {@link HeightmapTerrainData.childTileMask}.  The given child tile coordinates are assumed
   * to be one of the four children of this tile.  If non-child tile coordinates are
   * given, the availability of the southeast child tile is returned.
   *
   * @param {Number} thisX The tile X coordinate of this (the parent) tile.
   * @param {Number} thisY The tile Y coordinate of this (the parent) tile.
   * @param {Number} childX The tile X coordinate of the child tile to check for availability.
   * @param {Number} childY The tile Y coordinate of the child tile to check for availability.
   * @returns {Boolean} True if the child tile is available; otherwise, false.
   */
  HeightmapTerrainData.prototype.isChildAvailable = function (
    thisX,
    thisY,
    childX,
    childY
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(thisX)) {
      throw new DeveloperError("thisX is required.");
    }
    if (!defined(thisY)) {
      throw new DeveloperError("thisY is required.");
    }
    if (!defined(childX)) {
      throw new DeveloperError("childX is required.");
    }
    if (!defined(childY)) {
      throw new DeveloperError("childY is required.");
    }
    //>>includeEnd('debug');

    let bitNumber = 2; // northwest child
    if (childX !== thisX * 2) {
      ++bitNumber; // east child
    }
    if (childY !== thisY * 2) {
      bitNumber -= 2; // south child
    }

    return (this._childTileMask & (1 << bitNumber)) !== 0;
  };

  /**
   * Gets a value indicating whether or not this terrain data was created by upsampling lower resolution
   * terrain data.  If this value is false, the data was obtained from some other source, such
   * as by downloading it from a remote server.  This method should return true for instances
   * returned from a call to {@link HeightmapTerrainData#upsample}.
   *
   * @returns {Boolean} True if this instance was created by upsampling; otherwise, false.
   */
  HeightmapTerrainData.prototype.wasCreatedByUpsampling = function () {
    return this._createdByUpsampling;
  };

  function interpolateHeight$2(
    sourceHeights,
    elementsPerHeight,
    elementMultiplier,
    stride,
    isBigEndian,
    sourceRectangle,
    width,
    height,
    longitude,
    latitude
  ) {
    const fromWest =
      ((longitude - sourceRectangle.west) * (width - 1)) /
      (sourceRectangle.east - sourceRectangle.west);
    const fromSouth =
      ((latitude - sourceRectangle.south) * (height - 1)) /
      (sourceRectangle.north - sourceRectangle.south);

    let westInteger = fromWest | 0;
    let eastInteger = westInteger + 1;
    if (eastInteger >= width) {
      eastInteger = width - 1;
      westInteger = width - 2;
    }

    let southInteger = fromSouth | 0;
    let northInteger = southInteger + 1;
    if (northInteger >= height) {
      northInteger = height - 1;
      southInteger = height - 2;
    }

    const dx = fromWest - westInteger;
    const dy = fromSouth - southInteger;

    southInteger = height - 1 - southInteger;
    northInteger = height - 1 - northInteger;

    const southwestHeight = getHeight(
      sourceHeights,
      elementsPerHeight,
      elementMultiplier,
      stride,
      isBigEndian,
      southInteger * width + westInteger
    );
    const southeastHeight = getHeight(
      sourceHeights,
      elementsPerHeight,
      elementMultiplier,
      stride,
      isBigEndian,
      southInteger * width + eastInteger
    );
    const northwestHeight = getHeight(
      sourceHeights,
      elementsPerHeight,
      elementMultiplier,
      stride,
      isBigEndian,
      northInteger * width + westInteger
    );
    const northeastHeight = getHeight(
      sourceHeights,
      elementsPerHeight,
      elementMultiplier,
      stride,
      isBigEndian,
      northInteger * width + eastInteger
    );

    return triangleInterpolateHeight(
      dx,
      dy,
      southwestHeight,
      southeastHeight,
      northwestHeight,
      northeastHeight
    );
  }

  function interpolateMeshHeight$2(
    buffer,
    encoding,
    heightOffset,
    heightScale,
    sourceRectangle,
    width,
    height,
    longitude,
    latitude
  ) {
    // returns a height encoded according to the structure's heightScale and heightOffset.
    const fromWest =
      ((longitude - sourceRectangle.west) * (width - 1)) /
      (sourceRectangle.east - sourceRectangle.west);
    const fromSouth =
      ((latitude - sourceRectangle.south) * (height - 1)) /
      (sourceRectangle.north - sourceRectangle.south);

    let westInteger = fromWest | 0;
    let eastInteger = westInteger + 1;
    if (eastInteger >= width) {
      eastInteger = width - 1;
      westInteger = width - 2;
    }

    let southInteger = fromSouth | 0;
    let northInteger = southInteger + 1;
    if (northInteger >= height) {
      northInteger = height - 1;
      southInteger = height - 2;
    }

    const dx = fromWest - westInteger;
    const dy = fromSouth - southInteger;

    southInteger = height - 1 - southInteger;
    northInteger = height - 1 - northInteger;

    const southwestHeight =
      (encoding.decodeHeight(buffer, southInteger * width + westInteger) -
        heightOffset) /
      heightScale;
    const southeastHeight =
      (encoding.decodeHeight(buffer, southInteger * width + eastInteger) -
        heightOffset) /
      heightScale;
    const northwestHeight =
      (encoding.decodeHeight(buffer, northInteger * width + westInteger) -
        heightOffset) /
      heightScale;
    const northeastHeight =
      (encoding.decodeHeight(buffer, northInteger * width + eastInteger) -
        heightOffset) /
      heightScale;

    return triangleInterpolateHeight(
      dx,
      dy,
      southwestHeight,
      southeastHeight,
      northwestHeight,
      northeastHeight
    );
  }

  function triangleInterpolateHeight(
    dX,
    dY,
    southwestHeight,
    southeastHeight,
    northwestHeight,
    northeastHeight
  ) {
    // The HeightmapTessellator bisects the quad from southwest to northeast.
    if (dY < dX) {
      // Lower right triangle
      return (
        southwestHeight +
        dX * (southeastHeight - southwestHeight) +
        dY * (northeastHeight - southeastHeight)
      );
    }

    // Upper left triangle
    return (
      southwestHeight +
      dX * (northeastHeight - northwestHeight) +
      dY * (northwestHeight - southwestHeight)
    );
  }

  function getHeight(
    heights,
    elementsPerHeight,
    elementMultiplier,
    stride,
    isBigEndian,
    index
  ) {
    index *= stride;

    let height = 0;
    let i;

    if (isBigEndian) {
      for (i = 0; i < elementsPerHeight; ++i) {
        height = height * elementMultiplier + heights[index + i];
      }
    } else {
      for (i = elementsPerHeight - 1; i >= 0; --i) {
        height = height * elementMultiplier + heights[index + i];
      }
    }

    return height;
  }

  function setHeight(
    heights,
    elementsPerHeight,
    elementMultiplier,
    divisor,
    stride,
    isBigEndian,
    index,
    height
  ) {
    index *= stride;

    let i;
    if (isBigEndian) {
      for (i = 0; i < elementsPerHeight - 1; ++i) {
        heights[index + i] = (height / divisor) | 0;
        height -= heights[index + i] * divisor;
        divisor /= elementMultiplier;
      }
    } else {
      for (i = elementsPerHeight - 1; i > 0; --i) {
        heights[index + i] = (height / divisor) | 0;
        height -= heights[index + i] * divisor;
        divisor /= elementMultiplier;
      }
    }
    heights[index + i] = height;
  }

  /**
   * Reports the availability of tiles in a {@link TilingScheme}.
   *
   * @alias TileAvailability
   * @constructor
   *
   * @param {TilingScheme} tilingScheme The tiling scheme in which to report availability.
   * @param {Number} maximumLevel The maximum tile level that is potentially available.
   */
  function TileAvailability(tilingScheme, maximumLevel) {
    this._tilingScheme = tilingScheme;
    this._maximumLevel = maximumLevel;

    this._rootNodes = [];
  }

  const rectangleScratch$6 = new Rectangle();

  function findNode$1(level, x, y, nodes) {
    const count = nodes.length;
    for (let i = 0; i < count; ++i) {
      const node = nodes[i];
      if (node.x === x && node.y === y && node.level === level) {
        return true;
      }
    }

    return false;
  }

  /**
   * Marks a rectangular range of tiles in a particular level as being available.  For best performance,
   * add your ranges in order of increasing level.
   *
   * @param {Number} level The level.
   * @param {Number} startX The X coordinate of the first available tiles at the level.
   * @param {Number} startY The Y coordinate of the first available tiles at the level.
   * @param {Number} endX The X coordinate of the last available tiles at the level.
   * @param {Number} endY The Y coordinate of the last available tiles at the level.
   */
  TileAvailability.prototype.addAvailableTileRange = function (
    level,
    startX,
    startY,
    endX,
    endY
  ) {
    const tilingScheme = this._tilingScheme;

    const rootNodes = this._rootNodes;
    if (level === 0) {
      for (let y = startY; y <= endY; ++y) {
        for (let x = startX; x <= endX; ++x) {
          if (!findNode$1(level, x, y, rootNodes)) {
            rootNodes.push(new QuadtreeNode(tilingScheme, undefined, 0, x, y));
          }
        }
      }
    }

    tilingScheme.tileXYToRectangle(startX, startY, level, rectangleScratch$6);
    const west = rectangleScratch$6.west;
    const north = rectangleScratch$6.north;

    tilingScheme.tileXYToRectangle(endX, endY, level, rectangleScratch$6);
    const east = rectangleScratch$6.east;
    const south = rectangleScratch$6.south;

    const rectangleWithLevel = new RectangleWithLevel(
      level,
      west,
      south,
      east,
      north
    );

    for (let i = 0; i < rootNodes.length; ++i) {
      const rootNode = rootNodes[i];
      if (rectanglesOverlap(rootNode.extent, rectangleWithLevel)) {
        putRectangleInQuadtree(this._maximumLevel, rootNode, rectangleWithLevel);
      }
    }
  };

  /**
   * Determines the level of the most detailed tile covering the position.  This function
   * usually completes in time logarithmic to the number of rectangles added with
   * {@link TileAvailability#addAvailableTileRange}.
   *
   * @param {Cartographic} position The position for which to determine the maximum available level.  The height component is ignored.
   * @return {Number} The level of the most detailed tile covering the position.
   * @throws {DeveloperError} If position is outside any tile according to the tiling scheme.
   */
  TileAvailability.prototype.computeMaximumLevelAtPosition = function (position) {
    // Find the root node that contains this position.
    let node;
    for (let nodeIndex = 0; nodeIndex < this._rootNodes.length; ++nodeIndex) {
      const rootNode = this._rootNodes[nodeIndex];
      if (rectangleContainsPosition(rootNode.extent, position)) {
        node = rootNode;
        break;
      }
    }

    if (!defined(node)) {
      return -1;
    }

    return findMaxLevelFromNode(undefined, node, position);
  };

  const rectanglesScratch = [];
  const remainingToCoverByLevelScratch = [];
  const westScratch$1 = new Rectangle();
  const eastScratch = new Rectangle();

  /**
   * Finds the most detailed level that is available _everywhere_ within a given rectangle.  More detailed
   * tiles may be available in parts of the rectangle, but not the whole thing.  The return value of this
   * function may be safely passed to {@link sampleTerrain} for any position within the rectangle.  This function
   * usually completes in time logarithmic to the number of rectangles added with
   * {@link TileAvailability#addAvailableTileRange}.
   *
   * @param {Rectangle} rectangle The rectangle.
   * @return {Number} The best available level for the entire rectangle.
   */
  TileAvailability.prototype.computeBestAvailableLevelOverRectangle = function (
    rectangle
  ) {
    const rectangles = rectanglesScratch;
    rectangles.length = 0;

    if (rectangle.east < rectangle.west) {
      // Rectangle crosses the IDL, make it two rectangles.
      rectangles.push(
        Rectangle.fromRadians(
          -Math.PI,
          rectangle.south,
          rectangle.east,
          rectangle.north,
          westScratch$1
        )
      );
      rectangles.push(
        Rectangle.fromRadians(
          rectangle.west,
          rectangle.south,
          Math.PI,
          rectangle.north,
          eastScratch
        )
      );
    } else {
      rectangles.push(rectangle);
    }

    const remainingToCoverByLevel = remainingToCoverByLevelScratch;
    remainingToCoverByLevel.length = 0;

    let i;
    for (i = 0; i < this._rootNodes.length; ++i) {
      updateCoverageWithNode(
        remainingToCoverByLevel,
        this._rootNodes[i],
        rectangles
      );
    }

    for (i = remainingToCoverByLevel.length - 1; i >= 0; --i) {
      if (
        defined(remainingToCoverByLevel[i]) &&
        remainingToCoverByLevel[i].length === 0
      ) {
        return i;
      }
    }

    return 0;
  };

  const cartographicScratch$4 = new Cartographic();

  /**
   * Determines if a particular tile is available.
   * @param {Number} level The tile level to check.
   * @param {Number} x The X coordinate of the tile to check.
   * @param {Number} y The Y coordinate of the tile to check.
   * @return {Boolean} True if the tile is available; otherwise, false.
   */
  TileAvailability.prototype.isTileAvailable = function (level, x, y) {
    // Get the center of the tile and find the maximum level at that position.
    // Because availability is by tile, if the level is available at that point, it
    // is sure to be available for the whole tile.  We assume that if a tile at level n exists,
    // then all its parent tiles back to level 0 exist too.  This isn't really enforced
    // anywhere, but Cesium would never load a tile for which this is not true.
    const rectangle = this._tilingScheme.tileXYToRectangle(
      x,
      y,
      level,
      rectangleScratch$6
    );
    Rectangle.center(rectangle, cartographicScratch$4);
    return this.computeMaximumLevelAtPosition(cartographicScratch$4) >= level;
  };

  /**
   * Computes a bit mask indicating which of a tile's four children exist.
   * If a child's bit is set, a tile is available for that child.  If it is cleared,
   * the tile is not available.  The bit values are as follows:
   * <table>
   *     <tr><th>Bit Position</th><th>Bit Value</th><th>Child Tile</th></tr>
   *     <tr><td>0</td><td>1</td><td>Southwest</td></tr>
   *     <tr><td>1</td><td>2</td><td>Southeast</td></tr>
   *     <tr><td>2</td><td>4</td><td>Northwest</td></tr>
   *     <tr><td>3</td><td>8</td><td>Northeast</td></tr>
   * </table>
   *
   * @param {Number} level The level of the parent tile.
   * @param {Number} x The X coordinate of the parent tile.
   * @param {Number} y The Y coordinate of the parent tile.
   * @return {Number} The bit mask indicating child availability.
   */
  TileAvailability.prototype.computeChildMaskForTile = function (level, x, y) {
    const childLevel = level + 1;
    if (childLevel >= this._maximumLevel) {
      return 0;
    }

    let mask = 0;

    mask |= this.isTileAvailable(childLevel, 2 * x, 2 * y + 1) ? 1 : 0;
    mask |= this.isTileAvailable(childLevel, 2 * x + 1, 2 * y + 1) ? 2 : 0;
    mask |= this.isTileAvailable(childLevel, 2 * x, 2 * y) ? 4 : 0;
    mask |= this.isTileAvailable(childLevel, 2 * x + 1, 2 * y) ? 8 : 0;

    return mask;
  };

  function QuadtreeNode(tilingScheme, parent, level, x, y) {
    this.tilingScheme = tilingScheme;
    this.parent = parent;
    this.level = level;
    this.x = x;
    this.y = y;
    this.extent = tilingScheme.tileXYToRectangle(x, y, level);

    this.rectangles = [];
    this._sw = undefined;
    this._se = undefined;
    this._nw = undefined;
    this._ne = undefined;
  }

  Object.defineProperties(QuadtreeNode.prototype, {
    nw: {
      get: function () {
        if (!this._nw) {
          this._nw = new QuadtreeNode(
            this.tilingScheme,
            this,
            this.level + 1,
            this.x * 2,
            this.y * 2
          );
        }
        return this._nw;
      },
    },

    ne: {
      get: function () {
        if (!this._ne) {
          this._ne = new QuadtreeNode(
            this.tilingScheme,
            this,
            this.level + 1,
            this.x * 2 + 1,
            this.y * 2
          );
        }
        return this._ne;
      },
    },

    sw: {
      get: function () {
        if (!this._sw) {
          this._sw = new QuadtreeNode(
            this.tilingScheme,
            this,
            this.level + 1,
            this.x * 2,
            this.y * 2 + 1
          );
        }
        return this._sw;
      },
    },

    se: {
      get: function () {
        if (!this._se) {
          this._se = new QuadtreeNode(
            this.tilingScheme,
            this,
            this.level + 1,
            this.x * 2 + 1,
            this.y * 2 + 1
          );
        }
        return this._se;
      },
    },
  });

  function RectangleWithLevel(level, west, south, east, north) {
    this.level = level;
    this.west = west;
    this.south = south;
    this.east = east;
    this.north = north;
  }

  function rectanglesOverlap(rectangle1, rectangle2) {
    const west = Math.max(rectangle1.west, rectangle2.west);
    const south = Math.max(rectangle1.south, rectangle2.south);
    const east = Math.min(rectangle1.east, rectangle2.east);
    const north = Math.min(rectangle1.north, rectangle2.north);
    return south < north && west < east;
  }

  function putRectangleInQuadtree(maxDepth, node, rectangle) {
    while (node.level < maxDepth) {
      if (rectangleFullyContainsRectangle(node.nw.extent, rectangle)) {
        node = node.nw;
      } else if (rectangleFullyContainsRectangle(node.ne.extent, rectangle)) {
        node = node.ne;
      } else if (rectangleFullyContainsRectangle(node.sw.extent, rectangle)) {
        node = node.sw;
      } else if (rectangleFullyContainsRectangle(node.se.extent, rectangle)) {
        node = node.se;
      } else {
        break;
      }
    }

    if (
      node.rectangles.length === 0 ||
      node.rectangles[node.rectangles.length - 1].level <= rectangle.level
    ) {
      node.rectangles.push(rectangle);
    } else {
      // Maintain ordering by level when inserting.
      let index = binarySearch(
        node.rectangles,
        rectangle.level,
        rectangleLevelComparator
      );
      if (index < 0) {
        index = ~index;
      }
      node.rectangles.splice(index, 0, rectangle);
    }
  }

  function rectangleLevelComparator(a, b) {
    return a.level - b;
  }

  function rectangleFullyContainsRectangle(potentialContainer, rectangleToTest) {
    return (
      rectangleToTest.west >= potentialContainer.west &&
      rectangleToTest.east <= potentialContainer.east &&
      rectangleToTest.south >= potentialContainer.south &&
      rectangleToTest.north <= potentialContainer.north
    );
  }

  function rectangleContainsPosition(potentialContainer, positionToTest) {
    return (
      positionToTest.longitude >= potentialContainer.west &&
      positionToTest.longitude <= potentialContainer.east &&
      positionToTest.latitude >= potentialContainer.south &&
      positionToTest.latitude <= potentialContainer.north
    );
  }

  function findMaxLevelFromNode(stopNode, node, position) {
    let maxLevel = 0;

    // Find the deepest quadtree node containing this point.
    let found = false;
    while (!found) {
      const nw = node._nw && rectangleContainsPosition(node._nw.extent, position);
      const ne = node._ne && rectangleContainsPosition(node._ne.extent, position);
      const sw = node._sw && rectangleContainsPosition(node._sw.extent, position);
      const se = node._se && rectangleContainsPosition(node._se.extent, position);

      // The common scenario is that the point is in only one quadrant and we can simply
      // iterate down the tree.  But if the point is on a boundary between tiles, it is
      // in multiple tiles and we need to check all of them, so use recursion.
      if (nw + ne + sw + se > 1) {
        if (nw) {
          maxLevel = Math.max(
            maxLevel,
            findMaxLevelFromNode(node, node._nw, position)
          );
        }
        if (ne) {
          maxLevel = Math.max(
            maxLevel,
            findMaxLevelFromNode(node, node._ne, position)
          );
        }
        if (sw) {
          maxLevel = Math.max(
            maxLevel,
            findMaxLevelFromNode(node, node._sw, position)
          );
        }
        if (se) {
          maxLevel = Math.max(
            maxLevel,
            findMaxLevelFromNode(node, node._se, position)
          );
        }
        break;
      } else if (nw) {
        node = node._nw;
      } else if (ne) {
        node = node._ne;
      } else if (sw) {
        node = node._sw;
      } else if (se) {
        node = node._se;
      } else {
        found = true;
      }
    }

    // Work up the tree until we find a rectangle that contains this point.
    while (node !== stopNode) {
      const rectangles = node.rectangles;

      // Rectangles are sorted by level, lowest first.
      for (
        let i = rectangles.length - 1;
        i >= 0 && rectangles[i].level > maxLevel;
        --i
      ) {
        const rectangle = rectangles[i];
        if (rectangleContainsPosition(rectangle, position)) {
          maxLevel = rectangle.level;
        }
      }

      node = node.parent;
    }

    return maxLevel;
  }

  function updateCoverageWithNode(
    remainingToCoverByLevel,
    node,
    rectanglesToCover
  ) {
    if (!node) {
      return;
    }

    let i;
    let anyOverlap = false;
    for (i = 0; i < rectanglesToCover.length; ++i) {
      anyOverlap =
        anyOverlap || rectanglesOverlap(node.extent, rectanglesToCover[i]);
    }

    if (!anyOverlap) {
      // This node is not applicable to the rectangle(s).
      return;
    }

    const rectangles = node.rectangles;
    for (i = 0; i < rectangles.length; ++i) {
      const rectangle = rectangles[i];

      if (!remainingToCoverByLevel[rectangle.level]) {
        remainingToCoverByLevel[rectangle.level] = rectanglesToCover;
      }

      remainingToCoverByLevel[rectangle.level] = subtractRectangle(
        remainingToCoverByLevel[rectangle.level],
        rectangle
      );
    }

    // Update with child nodes.
    updateCoverageWithNode(remainingToCoverByLevel, node._nw, rectanglesToCover);
    updateCoverageWithNode(remainingToCoverByLevel, node._ne, rectanglesToCover);
    updateCoverageWithNode(remainingToCoverByLevel, node._sw, rectanglesToCover);
    updateCoverageWithNode(remainingToCoverByLevel, node._se, rectanglesToCover);
  }

  function subtractRectangle(rectangleList, rectangleToSubtract) {
    const result = [];
    for (let i = 0; i < rectangleList.length; ++i) {
      const rectangle = rectangleList[i];
      if (!rectanglesOverlap(rectangle, rectangleToSubtract)) {
        // Disjoint rectangles.  Original rectangle is unmodified.
        result.push(rectangle);
      } else {
        // rectangleToSubtract partially or completely overlaps rectangle.
        if (rectangle.west < rectangleToSubtract.west) {
          result.push(
            new Rectangle(
              rectangle.west,
              rectangle.south,
              rectangleToSubtract.west,
              rectangle.north
            )
          );
        }
        if (rectangle.east > rectangleToSubtract.east) {
          result.push(
            new Rectangle(
              rectangleToSubtract.east,
              rectangle.south,
              rectangle.east,
              rectangle.north
            )
          );
        }
        if (rectangle.south < rectangleToSubtract.south) {
          result.push(
            new Rectangle(
              Math.max(rectangleToSubtract.west, rectangle.west),
              rectangle.south,
              Math.min(rectangleToSubtract.east, rectangle.east),
              rectangleToSubtract.south
            )
          );
        }
        if (rectangle.north > rectangleToSubtract.north) {
          result.push(
            new Rectangle(
              Math.max(rectangleToSubtract.west, rectangle.west),
              rectangleToSubtract.north,
              Math.min(rectangleToSubtract.east, rectangle.east),
              rectangle.north
            )
          );
        }
      }
    }

    return result;
  }

  /**
   * Formats an error object into a String.  If available, uses name, message, and stack
   * properties, otherwise, falls back on toString().
   *
   * @function
   *
   * @param {*} object The item to find in the array.
   * @returns {String} A string containing the formatted error.
   */
  function formatError(object) {
    let result;

    const name = object.name;
    const message = object.message;
    if (defined(name) && defined(message)) {
      result = `${name}: ${message}`;
    } else {
      result = object.toString();
    }

    const stack = object.stack;
    if (defined(stack)) {
      result += `\n${stack}`;
    }

    return result;
  }

  /**
   * Provides details about an error that occurred in an {@link ImageryProvider} or a {@link TerrainProvider}.
   *
   * @alias TileProviderError
   * @constructor
   *
   * @param {ImageryProvider|TerrainProvider} provider The imagery or terrain provider that experienced the error.
   * @param {String} message A message describing the error.
   * @param {Number} [x] The X coordinate of the tile that experienced the error, or undefined if the error
   *        is not specific to a particular tile.
   * @param {Number} [y] The Y coordinate of the tile that experienced the error, or undefined if the error
   *        is not specific to a particular tile.
   * @param {Number} [level] The level of the tile that experienced the error, or undefined if the error
   *        is not specific to a particular tile.
   * @param {Number} [timesRetried=0] The number of times this operation has been retried.
   * @param {Error} [error] The error or exception that occurred, if any.
   */
  function TileProviderError(
    provider,
    message,
    x,
    y,
    level,
    timesRetried,
    error
  ) {
    /**
     * The {@link ImageryProvider} or {@link TerrainProvider} that experienced the error.
     * @type {ImageryProvider|TerrainProvider}
     */
    this.provider = provider;

    /**
     * The message describing the error.
     * @type {String}
     */
    this.message = message;

    /**
     * The X coordinate of the tile that experienced the error.  If the error is not specific
     * to a particular tile, this property will be undefined.
     * @type {Number}
     */
    this.x = x;

    /**
     * The Y coordinate of the tile that experienced the error.  If the error is not specific
     * to a particular tile, this property will be undefined.
     * @type {Number}
     */
    this.y = y;

    /**
     * The level-of-detail of the tile that experienced the error.  If the error is not specific
     * to a particular tile, this property will be undefined.
     * @type {Number}
     */
    this.level = level;

    /**
     * The number of times this operation has been retried.
     * @type {Number}
     * @default 0
     */
    this.timesRetried = defaultValue(timesRetried, 0);

    /**
     * True if the failed operation should be retried; otherwise, false.  The imagery or terrain provider
     * will set the initial value of this property before raising the event, but any listeners
     * can change it.  The value after the last listener is invoked will be acted upon.
     * @type {Boolean}
     * @default false
     */
    this.retry = false;

    /**
     * The error or exception that occurred, if any.
     * @type {Error}
     */
    this.error = error;
  }

  /**
   * Handles an error in an {@link ImageryProvider} or {@link TerrainProvider} by raising an event if it has any listeners, or by
   * logging the error to the console if the event has no listeners.  This method also tracks the number
   * of times the operation has been retried and will automatically retry if requested to do so by the
   * event listeners.
   *
   * @param {TileProviderError} previousError The error instance returned by this function the last
   *        time it was called for this error, or undefined if this is the first time this error has
   *        occurred.
   * @param {ImageryProvider|TerrainProvider} provider The imagery or terrain provider that encountered the error.
   * @param {Event} event The event to raise to inform listeners of the error.
   * @param {String} message The message describing the error.
   * @param {Number} x The X coordinate of the tile that experienced the error, or undefined if the
   *        error is not specific to a particular tile.
   * @param {Number} y The Y coordinate of the tile that experienced the error, or undefined if the
   *        error is not specific to a particular tile.
   * @param {Number} level The level-of-detail of the tile that experienced the error, or undefined if the
   *        error is not specific to a particular tile.
   * @param {TileProviderError.RetryFunction} retryFunction The function to call to retry the operation.  If undefined, the
   *        operation will not be retried.
   * @param {Error} [errorDetails] The error or exception that occurred, if any.
   * @returns {TileProviderError} The error instance that was passed to the event listeners and that
   *          should be passed to this function the next time it is called for the same error in order
   *          to track retry counts.
   */
  TileProviderError.handleError = function (
    previousError,
    provider,
    event,
    message,
    x,
    y,
    level,
    retryFunction,
    errorDetails
  ) {
    let error = previousError;
    if (!defined(previousError)) {
      error = new TileProviderError(
        provider,
        message,
        x,
        y,
        level,
        0,
        errorDetails
      );
    } else {
      error.provider = provider;
      error.message = message;
      error.x = x;
      error.y = y;
      error.level = level;
      error.retry = false;
      error.error = errorDetails;
      ++error.timesRetried;
    }

    if (event.numberOfListeners > 0) {
      event.raiseEvent(error);
    } else {
      console.log(
        `An error occurred in "${provider.constructor.name}": ${formatError(
        message
      )}`
      );
    }

    if (error.retry && defined(retryFunction)) {
      retryFunction();
    }

    return error;
  };

  /**
   * Handles success of an operation by resetting the retry count of a previous error, if any.  This way,
   * if the error occurs again in the future, the listeners will be informed that it has not yet been retried.
   *
   * @param {TileProviderError} previousError The previous error, or undefined if this operation has
   *        not previously resulted in an error.
   */
  TileProviderError.handleSuccess = function (previousError) {
    if (defined(previousError)) {
      previousError.timesRetried = -1;
    }
  };

  /**
   * A tiling scheme for geometry referenced to a {@link WebMercatorProjection}, EPSG:3857.  This is
   * the tiling scheme used by Google Maps, Microsoft Bing Maps, and most of ESRI ArcGIS Online.
   *
   * @alias WebMercatorTilingScheme
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid whose surface is being tiled. Defaults to
   * the WGS84 ellipsoid.
   * @param {Number} [options.numberOfLevelZeroTilesX=1] The number of tiles in the X direction at level zero of
   *        the tile tree.
   * @param {Number} [options.numberOfLevelZeroTilesY=1] The number of tiles in the Y direction at level zero of
   *        the tile tree.
   * @param {Cartesian2} [options.rectangleSouthwestInMeters] The southwest corner of the rectangle covered by the
   *        tiling scheme, in meters.  If this parameter or rectangleNortheastInMeters is not specified, the entire
   *        globe is covered in the longitude direction and an equal distance is covered in the latitude
   *        direction, resulting in a square projection.
   * @param {Cartesian2} [options.rectangleNortheastInMeters] The northeast corner of the rectangle covered by the
   *        tiling scheme, in meters.  If this parameter or rectangleSouthwestInMeters is not specified, the entire
   *        globe is covered in the longitude direction and an equal distance is covered in the latitude
   *        direction, resulting in a square projection.
   */
  function WebMercatorTilingScheme(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    this._ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);
    this._numberOfLevelZeroTilesX = defaultValue(
      options.numberOfLevelZeroTilesX,
      1
    );
    this._numberOfLevelZeroTilesY = defaultValue(
      options.numberOfLevelZeroTilesY,
      1
    );

    this._projection = new WebMercatorProjection(this._ellipsoid);

    if (
      defined(options.rectangleSouthwestInMeters) &&
      defined(options.rectangleNortheastInMeters)
    ) {
      this._rectangleSouthwestInMeters = options.rectangleSouthwestInMeters;
      this._rectangleNortheastInMeters = options.rectangleNortheastInMeters;
    } else {
      const semimajorAxisTimesPi = this._ellipsoid.maximumRadius * Math.PI;
      this._rectangleSouthwestInMeters = new Cartesian2(
        -semimajorAxisTimesPi,
        -semimajorAxisTimesPi
      );
      this._rectangleNortheastInMeters = new Cartesian2(
        semimajorAxisTimesPi,
        semimajorAxisTimesPi
      );
    }

    const southwest = this._projection.unproject(
      this._rectangleSouthwestInMeters
    );
    const northeast = this._projection.unproject(
      this._rectangleNortheastInMeters
    );
    this._rectangle = new Rectangle(
      southwest.longitude,
      southwest.latitude,
      northeast.longitude,
      northeast.latitude
    );
  }

  Object.defineProperties(WebMercatorTilingScheme.prototype, {
    /**
     * Gets the ellipsoid that is tiled by this tiling scheme.
     * @memberof WebMercatorTilingScheme.prototype
     * @type {Ellipsoid}
     */
    ellipsoid: {
      get: function () {
        return this._ellipsoid;
      },
    },

    /**
     * Gets the rectangle, in radians, covered by this tiling scheme.
     * @memberof WebMercatorTilingScheme.prototype
     * @type {Rectangle}
     */
    rectangle: {
      get: function () {
        return this._rectangle;
      },
    },

    /**
     * Gets the map projection used by this tiling scheme.
     * @memberof WebMercatorTilingScheme.prototype
     * @type {MapProjection}
     */
    projection: {
      get: function () {
        return this._projection;
      },
    },
  });

  /**
   * Gets the total number of tiles in the X direction at a specified level-of-detail.
   *
   * @param {Number} level The level-of-detail.
   * @returns {Number} The number of tiles in the X direction at the given level.
   */
  WebMercatorTilingScheme.prototype.getNumberOfXTilesAtLevel = function (level) {
    return this._numberOfLevelZeroTilesX << level;
  };

  /**
   * Gets the total number of tiles in the Y direction at a specified level-of-detail.
   *
   * @param {Number} level The level-of-detail.
   * @returns {Number} The number of tiles in the Y direction at the given level.
   */
  WebMercatorTilingScheme.prototype.getNumberOfYTilesAtLevel = function (level) {
    return this._numberOfLevelZeroTilesY << level;
  };

  /**
   * Transforms a rectangle specified in geodetic radians to the native coordinate system
   * of this tiling scheme.
   *
   * @param {Rectangle} rectangle The rectangle to transform.
   * @param {Rectangle} [result] The instance to which to copy the result, or undefined if a new instance
   *        should be created.
   * @returns {Rectangle} The specified 'result', or a new object containing the native rectangle if 'result'
   *          is undefined.
   */
  WebMercatorTilingScheme.prototype.rectangleToNativeRectangle = function (
    rectangle,
    result
  ) {
    const projection = this._projection;
    const southwest = projection.project(Rectangle.southwest(rectangle));
    const northeast = projection.project(Rectangle.northeast(rectangle));

    if (!defined(result)) {
      return new Rectangle(southwest.x, southwest.y, northeast.x, northeast.y);
    }

    result.west = southwest.x;
    result.south = southwest.y;
    result.east = northeast.x;
    result.north = northeast.y;
    return result;
  };

  /**
   * Converts tile x, y coordinates and level to a rectangle expressed in the native coordinates
   * of the tiling scheme.
   *
   * @param {Number} x The integer x coordinate of the tile.
   * @param {Number} y The integer y coordinate of the tile.
   * @param {Number} level The tile level-of-detail.  Zero is the least detailed.
   * @param {Object} [result] The instance to which to copy the result, or undefined if a new instance
   *        should be created.
   * @returns {Rectangle} The specified 'result', or a new object containing the rectangle
   *          if 'result' is undefined.
   */
  WebMercatorTilingScheme.prototype.tileXYToNativeRectangle = function (
    x,
    y,
    level,
    result
  ) {
    const xTiles = this.getNumberOfXTilesAtLevel(level);
    const yTiles = this.getNumberOfYTilesAtLevel(level);

    const xTileWidth =
      (this._rectangleNortheastInMeters.x - this._rectangleSouthwestInMeters.x) /
      xTiles;
    const west = this._rectangleSouthwestInMeters.x + x * xTileWidth;
    const east = this._rectangleSouthwestInMeters.x + (x + 1) * xTileWidth;

    const yTileHeight =
      (this._rectangleNortheastInMeters.y - this._rectangleSouthwestInMeters.y) /
      yTiles;
    const north = this._rectangleNortheastInMeters.y - y * yTileHeight;
    const south = this._rectangleNortheastInMeters.y - (y + 1) * yTileHeight;

    if (!defined(result)) {
      return new Rectangle(west, south, east, north);
    }

    result.west = west;
    result.south = south;
    result.east = east;
    result.north = north;
    return result;
  };

  /**
   * Converts tile x, y coordinates and level to a cartographic rectangle in radians.
   *
   * @param {Number} x The integer x coordinate of the tile.
   * @param {Number} y The integer y coordinate of the tile.
   * @param {Number} level The tile level-of-detail.  Zero is the least detailed.
   * @param {Object} [result] The instance to which to copy the result, or undefined if a new instance
   *        should be created.
   * @returns {Rectangle} The specified 'result', or a new object containing the rectangle
   *          if 'result' is undefined.
   */
  WebMercatorTilingScheme.prototype.tileXYToRectangle = function (
    x,
    y,
    level,
    result
  ) {
    const nativeRectangle = this.tileXYToNativeRectangle(x, y, level, result);

    const projection = this._projection;
    const southwest = projection.unproject(
      new Cartesian2(nativeRectangle.west, nativeRectangle.south)
    );
    const northeast = projection.unproject(
      new Cartesian2(nativeRectangle.east, nativeRectangle.north)
    );

    nativeRectangle.west = southwest.longitude;
    nativeRectangle.south = southwest.latitude;
    nativeRectangle.east = northeast.longitude;
    nativeRectangle.north = northeast.latitude;
    return nativeRectangle;
  };

  /**
   * Calculates the tile x, y coordinates of the tile containing
   * a given cartographic position.
   *
   * @param {Cartographic} position The position.
   * @param {Number} level The tile level-of-detail.  Zero is the least detailed.
   * @param {Cartesian2} [result] The instance to which to copy the result, or undefined if a new instance
   *        should be created.
   * @returns {Cartesian2} The specified 'result', or a new object containing the tile x, y coordinates
   *          if 'result' is undefined.
   */
  WebMercatorTilingScheme.prototype.positionToTileXY = function (
    position,
    level,
    result
  ) {
    const rectangle = this._rectangle;
    if (!Rectangle.contains(rectangle, position)) {
      // outside the bounds of the tiling scheme
      return undefined;
    }

    const xTiles = this.getNumberOfXTilesAtLevel(level);
    const yTiles = this.getNumberOfYTilesAtLevel(level);

    const overallWidth =
      this._rectangleNortheastInMeters.x - this._rectangleSouthwestInMeters.x;
    const xTileWidth = overallWidth / xTiles;
    const overallHeight =
      this._rectangleNortheastInMeters.y - this._rectangleSouthwestInMeters.y;
    const yTileHeight = overallHeight / yTiles;

    const projection = this._projection;

    const webMercatorPosition = projection.project(position);
    const distanceFromWest =
      webMercatorPosition.x - this._rectangleSouthwestInMeters.x;
    const distanceFromNorth =
      this._rectangleNortheastInMeters.y - webMercatorPosition.y;

    let xTileCoordinate = (distanceFromWest / xTileWidth) | 0;
    if (xTileCoordinate >= xTiles) {
      xTileCoordinate = xTiles - 1;
    }
    let yTileCoordinate = (distanceFromNorth / yTileHeight) | 0;
    if (yTileCoordinate >= yTiles) {
      yTileCoordinate = yTiles - 1;
    }

    if (!defined(result)) {
      return new Cartesian2(xTileCoordinate, yTileCoordinate);
    }

    result.x = xTileCoordinate;
    result.y = yTileCoordinate;
    return result;
  };

  const ALL_CHILDREN = 15;

  /**
   * A {@link TerrainProvider} that produces terrain geometry by tessellating height maps
   * retrieved from Elevation Tiles of an an ArcGIS ImageService.
   *
   * @alias ArcGISTiledElevationTerrainProvider
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Resource|String|Promise<Resource>|Promise<String>} options.url The URL of the ArcGIS ImageServer service.
   * @param {String} [options.token] The authorization token to use to connect to the service.
   * @param {Ellipsoid} [options.ellipsoid] The ellipsoid.  If the tilingScheme is specified,
   *                    this parameter is ignored and the tiling scheme's ellipsoid is used instead.
   *                    If neither parameter is specified, the WGS84 ellipsoid is used.
   *
   * @example
   * const terrainProvider = new Cesium.ArcGISTiledElevationTerrainProvider({
   *   url : 'https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer',
   *   token : 'KED1aF_I4UzXOHy3BnhwyBHU4l5oY6rO6walkmHoYqGp4XyIWUd5YZUC1ZrLAzvV40pR6gBXQayh0eFA8m6vPg..'
   * });
   * viewer.terrainProvider = terrainProvider;
   *
   *  @see TerrainProvider
   */
  function ArcGISTiledElevationTerrainProvider(options) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(options) || !defined(options.url)) {
      throw new DeveloperError("options.url is required.");
    }
    //>>includeEnd('debug');

    this._resource = undefined;
    this._credit = undefined;
    this._tilingScheme = undefined;
    this._levelZeroMaximumGeometricError = undefined;
    this._maxLevel = undefined;
    this._terrainDataStructure = undefined;
    this._ready = false;
    this._width = undefined;
    this._height = undefined;
    this._encoding = undefined;
    const token = options.token;

    this._hasAvailability = false;
    this._tilesAvailable = undefined;
    this._tilesAvailablityLoaded = undefined;
    this._availableCache = {};

    const that = this;
    const ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);
    this._readyPromise = Promise.resolve(options.url)
      .then(function (url) {
        let resource = Resource.createIfNeeded(url);
        resource.appendForwardSlash();
        if (defined(token)) {
          resource = resource.getDerivedResource({
            queryParameters: {
              token: token,
            },
          });
        }
        that._resource = resource;

        const metadataResource = resource.getDerivedResource({
          queryParameters: {
            f: "pjson",
          },
        });

        return metadataResource.fetchJson();
      })
      .then(function (metadata) {
        const copyrightText = metadata.copyrightText;
        if (defined(copyrightText)) {
          that._credit = new Credit(copyrightText);
        }

        const spatialReference = metadata.spatialReference;
        const wkid = defaultValue(
          spatialReference.latestWkid,
          spatialReference.wkid
        );
        const extent = metadata.extent;
        const tilingSchemeOptions = {
          ellipsoid: ellipsoid,
        };
        if (wkid === 4326) {
          tilingSchemeOptions.rectangle = Rectangle.fromDegrees(
            extent.xmin,
            extent.ymin,
            extent.xmax,
            extent.ymax
          );
          that._tilingScheme = new GeographicTilingScheme(tilingSchemeOptions);
        } else if (wkid === 3857) {
          tilingSchemeOptions.rectangleSouthwestInMeters = new Cartesian2(
            extent.xmin,
            extent.ymin
          );
          tilingSchemeOptions.rectangleNortheastInMeters = new Cartesian2(
            extent.xmax,
            extent.ymax
          );
          that._tilingScheme = new WebMercatorTilingScheme(tilingSchemeOptions);
        } else {
          return Promise.reject(new RuntimeError("Invalid spatial reference"));
        }

        const tileInfo = metadata.tileInfo;
        if (!defined(tileInfo)) {
          return Promise.reject(new RuntimeError("tileInfo is required"));
        }

        that._width = tileInfo.rows + 1;
        that._height = tileInfo.cols + 1;
        that._encoding =
          tileInfo.format === "LERC"
            ? HeightmapEncoding$1.LERC
            : HeightmapEncoding$1.NONE;
        that._lodCount = tileInfo.lods.length - 1;

        const hasAvailability = (that._hasAvailability =
          metadata.capabilities.indexOf("Tilemap") !== -1);
        if (hasAvailability) {
          that._tilesAvailable = new TileAvailability(
            that._tilingScheme,
            that._lodCount
          );
          that._tilesAvailable.addAvailableTileRange(
            0,
            0,
            0,
            that._tilingScheme.getNumberOfXTilesAtLevel(0),
            that._tilingScheme.getNumberOfYTilesAtLevel(0)
          );
          that._tilesAvailablityLoaded = new TileAvailability(
            that._tilingScheme,
            that._lodCount
          );
        }

        that._levelZeroMaximumGeometricError = TerrainProvider.getEstimatedLevelZeroGeometricErrorForAHeightmap(
          that._tilingScheme.ellipsoid,
          that._width,
          that._tilingScheme.getNumberOfXTilesAtLevel(0)
        );

        if (metadata.bandCount > 1) {
          console.log(
            "ArcGISTiledElevationTerrainProvider: Terrain data has more than 1 band. Using the first one."
          );
        }

        that._terrainDataStructure = {
          elementMultiplier: 1.0,
          lowestEncodedHeight: metadata.minValues[0],
          highestEncodedHeight: metadata.maxValues[0],
        };

        that._ready = true;

        return true;
      })
      .catch(function (error) {
        const message = `An error occurred while accessing ${that._resource.url}.`;
        TileProviderError.handleError(undefined, that, that._errorEvent, message);
        return Promise.reject(error);
      });

    this._errorEvent = new Event();
  }

  Object.defineProperties(ArcGISTiledElevationTerrainProvider.prototype, {
    /**
     * Gets an event that is raised when the terrain provider encounters an asynchronous error.  By subscribing
     * to the event, you will be notified of the error and can potentially recover from it.  Event listeners
     * are passed an instance of {@link TileProviderError}.
     * @memberof ArcGISTiledElevationTerrainProvider.prototype
     * @type {Event}
     * @readonly
     */
    errorEvent: {
      get: function () {
        return this._errorEvent;
      },
    },

    /**
     * Gets the credit to display when this terrain provider is active.  Typically this is used to credit
     * the source of the terrain.  This function should not be called before {@link ArcGISTiledElevationTerrainProvider#ready} returns true.
     * @memberof ArcGISTiledElevationTerrainProvider.prototype
     * @type {Credit}
     * @readonly
     */
    credit: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this.ready) {
          throw new DeveloperError(
            "credit must not be called before ready returns true."
          );
        }
        //>>includeEnd('debug');
        return this._credit;
      },
    },

    /**
     * Gets the tiling scheme used by this provider.  This function should
     * not be called before {@link ArcGISTiledElevationTerrainProvider#ready} returns true.
     * @memberof ArcGISTiledElevationTerrainProvider.prototype
     * @type {GeographicTilingScheme}
     * @readonly
     */
    tilingScheme: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this.ready) {
          throw new DeveloperError(
            "tilingScheme must not be called before ready returns true."
          );
        }
        //>>includeEnd('debug');
        return this._tilingScheme;
      },
    },

    /**
     * Gets a value indicating whether or not the provider is ready for use.
     * @memberof ArcGISTiledElevationTerrainProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    ready: {
      get: function () {
        return this._ready;
      },
    },

    /**
     * Gets a promise that resolves to true when the provider is ready for use.
     * @memberof ArcGISTiledElevationTerrainProvider.prototype
     * @type {Promise.<Boolean>}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._readyPromise;
      },
    },

    /**
     * Gets a value indicating whether or not the provider includes a water mask.  The water mask
     * indicates which areas of the globe are water rather than land, so they can be rendered
     * as a reflective surface with animated waves.  This function should not be
     * called before {@link ArcGISTiledElevationTerrainProvider#ready} returns true.
     * @memberof ArcGISTiledElevationTerrainProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    hasWaterMask: {
      get: function () {
        return false;
      },
    },

    /**
     * Gets a value indicating whether or not the requested tiles include vertex normals.
     * This function should not be called before {@link ArcGISTiledElevationTerrainProvider#ready} returns true.
     * @memberof ArcGISTiledElevationTerrainProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    hasVertexNormals: {
      get: function () {
        return false;
      },
    },
    /**
     * Gets an object that can be used to determine availability of terrain from this provider, such as
     * at points and in rectangles.  This function should not be called before
     * {@link TerrainProvider#ready} returns true.  This property may be undefined if availability
     * information is not available.
     * @memberof ArcGISTiledElevationTerrainProvider.prototype
     * @type {TileAvailability}
     * @readonly
     */
    availability: {
      get: function () {
        //>>includeStart('debug', pragmas.debug)
        if (!this._ready) {
          throw new DeveloperError(
            "availability must not be called before the terrain provider is ready."
          );
        }
        //>>includeEnd('debug');
        return this._tilesAvailable;
      },
    },
  });

  /**
   * Requests the geometry for a given tile.  This function should not be called before
   * {@link ArcGISTiledElevationTerrainProvider#ready} returns true.  The result includes terrain
   * data and indicates that all child tiles are available.
   *
   * @param {Number} x The X coordinate of the tile for which to request geometry.
   * @param {Number} y The Y coordinate of the tile for which to request geometry.
   * @param {Number} level The level of the tile for which to request geometry.
   * @param {Request} [request] The request object. Intended for internal use only.
   * @returns {Promise.<TerrainData>|undefined} A promise for the requested geometry.  If this method
   *          returns undefined instead of a promise, it is an indication that too many requests are already
   *          pending and the request will be retried later.
   */
  ArcGISTiledElevationTerrainProvider.prototype.requestTileGeometry = function (
    x,
    y,
    level,
    request
  ) {
    //>>includeStart('debug', pragmas.debug)
    if (!this._ready) {
      throw new DeveloperError(
        "requestTileGeometry must not be called before the terrain provider is ready."
      );
    }
    //>>includeEnd('debug');

    const tileResource = this._resource.getDerivedResource({
      url: `tile/${level}/${y}/${x}`,
      request: request,
    });

    const hasAvailability = this._hasAvailability;
    let availabilityPromise = Promise.resolve(true);
    let availabilityRequest;
    if (
      hasAvailability &&
      !defined(isTileAvailable(this, level + 1, x * 2, y * 2))
    ) {
      // We need to load child availability
      const availabilityResult = requestAvailability(
        this,
        level + 1,
        x * 2,
        y * 2
      );

      availabilityPromise = availabilityResult.promise;
      availabilityRequest = availabilityResult.request;
    }

    const promise = tileResource.fetchArrayBuffer();
    if (!defined(promise) || !defined(availabilityPromise)) {
      return undefined;
    }

    const that = this;
    const tilesAvailable = this._tilesAvailable;
    return Promise.all([promise, availabilityPromise])
      .then(function (result) {
        return new HeightmapTerrainData({
          buffer: result[0],
          width: that._width,
          height: that._height,
          childTileMask: hasAvailability
            ? tilesAvailable.computeChildMaskForTile(level, x, y)
            : ALL_CHILDREN,
          structure: that._terrainDataStructure,
          encoding: that._encoding,
        });
      })
      .catch(function (error) {
        if (
          defined(availabilityRequest) &&
          availabilityRequest.state === RequestState$1.CANCELLED
        ) {
          request.cancel();

          // Don't reject the promise till the request is actually cancelled
          // Otherwise it will think the request failed, but it didn't.
          return request.deferred.promise.finally(function () {
            request.state = RequestState$1.CANCELLED;
            return Promise.reject(error);
          });
        }
        return Promise.reject(error);
      });
  };

  function isTileAvailable(that, level, x, y) {
    if (!that._hasAvailability) {
      return undefined;
    }

    const tilesAvailablityLoaded = that._tilesAvailablityLoaded;
    const tilesAvailable = that._tilesAvailable;

    if (level > that._lodCount) {
      return false;
    }

    // Check if tiles are known to be available
    if (tilesAvailable.isTileAvailable(level, x, y)) {
      return true;
    }

    // or to not be available
    if (tilesAvailablityLoaded.isTileAvailable(level, x, y)) {
      return false;
    }

    return undefined;
  }

  /**
   * Gets the maximum geometric error allowed in a tile at a given level.
   *
   * @param {Number} level The tile level for which to get the maximum geometric error.
   * @returns {Number} The maximum geometric error.
   */
  ArcGISTiledElevationTerrainProvider.prototype.getLevelMaximumGeometricError = function (
    level
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!this.ready) {
      throw new DeveloperError(
        "getLevelMaximumGeometricError must not be called before ready returns true."
      );
    }
    //>>includeEnd('debug');

    return this._levelZeroMaximumGeometricError / (1 << level);
  };

  /**
   * Determines whether data for a tile is available to be loaded.
   *
   * @param {Number} x The X coordinate of the tile for which to request geometry.
   * @param {Number} y The Y coordinate of the tile for which to request geometry.
   * @param {Number} level The level of the tile for which to request geometry.
   * @returns {Boolean|undefined} Undefined if not supported, otherwise true or false.
   */
  ArcGISTiledElevationTerrainProvider.prototype.getTileDataAvailable = function (
    x,
    y,
    level
  ) {
    if (!this._hasAvailability) {
      return undefined;
    }

    const result = isTileAvailable(this, level, x, y);
    if (defined(result)) {
      return result;
    }

    requestAvailability(this, level, x, y);

    return undefined;
  };

  /**
   * Makes sure we load availability data for a tile
   *
   * @param {Number} x The X coordinate of the tile for which to request geometry.
   * @param {Number} y The Y coordinate of the tile for which to request geometry.
   * @param {Number} level The level of the tile for which to request geometry.
   * @returns {undefined} This provider does not support loading availability.
   */
  ArcGISTiledElevationTerrainProvider.prototype.loadTileDataAvailability = function (
    x,
    y,
    level
  ) {
    return undefined;
  };

  function findRange(origin, width, height, data) {
    const endCol = width - 1;
    const endRow = height - 1;

    const value = data[origin.y * width + origin.x];
    const endingIndices = [];
    const range = {
      startX: origin.x,
      startY: origin.y,
      endX: 0,
      endY: 0,
    };

    const corner = new Cartesian2(origin.x + 1, origin.y + 1);
    let doneX = false;
    let doneY = false;
    while (!(doneX && doneY)) {
      // We want to use the original value when checking Y,
      //  so get it before it possibly gets incremented
      let endX = corner.x;

      // If we no longer move in the Y direction we need to check the corner tile in X pass
      const endY = doneY ? corner.y + 1 : corner.y;

      // Check X range
      if (!doneX) {
        for (let y = origin.y; y < endY; ++y) {
          if (data[y * width + corner.x] !== value) {
            doneX = true;
            break;
          }
        }

        if (doneX) {
          endingIndices.push(new Cartesian2(corner.x, origin.y));

          // Use the last good column so we can continue with Y
          --corner.x;
          --endX;
          range.endX = corner.x;
        } else if (corner.x === endCol) {
          range.endX = corner.x;
          doneX = true;
        } else {
          ++corner.x;
        }
      }

      // Check Y range - The corner tile is checked here
      if (!doneY) {
        const col = corner.y * width;
        for (let x = origin.x; x <= endX; ++x) {
          if (data[col + x] !== value) {
            doneY = true;
            break;
          }
        }

        if (doneY) {
          endingIndices.push(new Cartesian2(origin.x, corner.y));

          // Use the last good row so we can continue with X
          --corner.y;
          range.endY = corner.y;
        } else if (corner.y === endRow) {
          range.endY = corner.y;
          doneY = true;
        } else {
          ++corner.y;
        }
      }
    }

    return {
      endingIndices: endingIndices,
      range: range,
      value: value,
    };
  }

  function computeAvailability(x, y, width, height, data) {
    const ranges = [];

    const singleValue = data.every(function (val) {
      return val === data[0];
    });
    if (singleValue) {
      if (data[0] === 1) {
        ranges.push({
          startX: x,
          startY: y,
          endX: x + width - 1,
          endY: y + height - 1,
        });
      }

      return ranges;
    }

    let positions = [new Cartesian2(0, 0)];
    while (positions.length > 0) {
      const origin = positions.pop();
      const result = findRange(origin, width, height, data);

      if (result.value === 1) {
        // Convert range into the array into global tile coordinates
        const range = result.range;
        range.startX += x;
        range.endX += x;
        range.startY += y;
        range.endY += y;
        ranges.push(range);
      }

      const endingIndices = result.endingIndices;
      if (endingIndices.length > 0) {
        positions = positions.concat(endingIndices);
      }
    }

    return ranges;
  }

  function requestAvailability(that, level, x, y) {
    if (!that._hasAvailability) {
      return {};
    }

    // Fetch 128x128 availability list, so we make the minimum amount of requests
    const xOffset = Math.floor(x / 128) * 128;
    const yOffset = Math.floor(y / 128) * 128;

    const dim = Math.min(1 << level, 128);
    const url = `tilemap/${level}/${yOffset}/${xOffset}/${dim}/${dim}`;

    const availableCache = that._availableCache;
    if (defined(availableCache[url])) {
      return availableCache[url];
    }

    const request = new Request({
      throttle: false,
      throttleByServer: true,
      type: RequestType$1.TERRAIN,
    });

    const tilemapResource = that._resource.getDerivedResource({
      url: url,
      request: request,
    });

    let promise = tilemapResource.fetchJson();
    if (!defined(promise)) {
      return {};
    }

    promise = promise.then(function (result) {
      const available = computeAvailability(
        xOffset,
        yOffset,
        dim,
        dim,
        result.data
      );

      // Mark whole area as having availability loaded
      that._tilesAvailablityLoaded.addAvailableTileRange(
        level,
        xOffset,
        yOffset,
        xOffset + dim,
        yOffset + dim
      );

      const tilesAvailable = that._tilesAvailable;
      for (let i = 0; i < available.length; ++i) {
        const range = available[i];
        tilesAvailable.addAvailableTileRange(
          level,
          range.startX,
          range.startY,
          range.endX,
          range.endY
        );
      }

      // Conveniently return availability of original tile
      return isTileAvailable(that, level, x, y);
    });

    availableCache[url] = {
      promise: promise,
      request: request,
    };

    promise = promise.finally(function (result) {
      delete availableCache[url];

      return result;
    });

    return {
      promise: promise,
      request: request,
    };
  }

  /**
   * ArcType defines the path that should be taken connecting vertices.
   *
   * @enum {Number}
   */
  const ArcType = {
    /**
     * Straight line that does not conform to the surface of the ellipsoid.
     *
     * @type {Number}
     * @constant
     */
    NONE: 0,

    /**
     * Follow geodesic path.
     *
     * @type {Number}
     * @constant
     */
    GEODESIC: 1,

    /**
     * Follow rhumb or loxodrome path.
     *
     * @type {Number}
     * @constant
     */
    RHUMB: 2,
  };
  var ArcType$1 = Object.freeze(ArcType);

  /**
   * An enum describing the type of motion that is defined by an articulation stage
   * in the AGI_articulations extension.
   *
   * @alias {ArticulationStageType}
   * @enum {String}
   *
   * @private
   */
  const ArticulationStageType = {
    XTRANSLATE: "xTranslate",
    YTRANSLATE: "yTranslate",
    ZTRANSLATE: "zTranslate",
    XROTATE: "xRotate",
    YROTATE: "yRotate",
    ZROTATE: "zRotate",
    XSCALE: "xScale",
    YSCALE: "yScale",
    ZSCALE: "zScale",
    UNIFORMSCALE: "uniformScale",
  };

  var ArticulationStageType$1 = Object.freeze(ArticulationStageType);

  /**
   * A collection of key-value pairs that is stored as a hash for easy
   * lookup but also provides an array for fast iteration.
   * @alias AssociativeArray
   * @constructor
   */
  function AssociativeArray() {
    this._array = [];
    this._hash = {};
  }

  Object.defineProperties(AssociativeArray.prototype, {
    /**
     * Gets the number of items in the collection.
     * @memberof AssociativeArray.prototype
     *
     * @type {Number}
     */
    length: {
      get: function () {
        return this._array.length;
      },
    },
    /**
     * Gets an unordered array of all values in the collection.
     * This is a live array that will automatically reflect the values in the collection,
     * it should not be modified directly.
     * @memberof AssociativeArray.prototype
     *
     * @type {Array}
     */
    values: {
      get: function () {
        return this._array;
      },
    },
  });

  /**
   * Determines if the provided key is in the array.
   *
   * @param {String|Number} key The key to check.
   * @returns {Boolean} <code>true</code> if the key is in the array, <code>false</code> otherwise.
   */
  AssociativeArray.prototype.contains = function (key) {
    //>>includeStart('debug', pragmas.debug);
    if (typeof key !== "string" && typeof key !== "number") {
      throw new DeveloperError("key is required to be a string or number.");
    }
    //>>includeEnd('debug');
    return defined(this._hash[key]);
  };

  /**
   * Associates the provided key with the provided value.  If the key already
   * exists, it is overwritten with the new value.
   *
   * @param {String|Number} key A unique identifier.
   * @param {*} value The value to associate with the provided key.
   */
  AssociativeArray.prototype.set = function (key, value) {
    //>>includeStart('debug', pragmas.debug);
    if (typeof key !== "string" && typeof key !== "number") {
      throw new DeveloperError("key is required to be a string or number.");
    }
    //>>includeEnd('debug');

    const oldValue = this._hash[key];
    if (value !== oldValue) {
      this.remove(key);
      this._hash[key] = value;
      this._array.push(value);
    }
  };

  /**
   * Retrieves the value associated with the provided key.
   *
   * @param {String|Number} key The key whose value is to be retrieved.
   * @returns {*} The associated value, or undefined if the key does not exist in the collection.
   */
  AssociativeArray.prototype.get = function (key) {
    //>>includeStart('debug', pragmas.debug);
    if (typeof key !== "string" && typeof key !== "number") {
      throw new DeveloperError("key is required to be a string or number.");
    }
    //>>includeEnd('debug');
    return this._hash[key];
  };

  /**
   * Removes a key-value pair from the collection.
   *
   * @param {String|Number} key The key to be removed.
   * @returns {Boolean} True if it was removed, false if the key was not in the collection.
   */
  AssociativeArray.prototype.remove = function (key) {
    //>>includeStart('debug', pragmas.debug);
    if (defined(key) && typeof key !== "string" && typeof key !== "number") {
      throw new DeveloperError("key is required to be a string or number.");
    }
    //>>includeEnd('debug');

    const value = this._hash[key];
    const hasValue = defined(value);
    if (hasValue) {
      const array = this._array;
      array.splice(array.indexOf(value), 1);
      delete this._hash[key];
    }
    return hasValue;
  };

  /**
   * Clears the collection.
   */
  AssociativeArray.prototype.removeAll = function () {
    const array = this._array;
    if (array.length > 0) {
      this._hash = {};
      array.length = 0;
    }
  };

  const url = "https://dev.virtualearth.net/REST/v1/Locations";

  /**
   * Provides geocoding through Bing Maps.
   * @alias BingMapsGeocoderService
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {String} options.key A key to use with the Bing Maps geocoding service
   * @param {String} [options.culture] A Bing Maps {@link https://docs.microsoft.com/en-us/bingmaps/rest-services/common-parameters-and-types/supported-culture-codes|Culture Code} to return results in a specific culture and language.
   */
  function BingMapsGeocoderService(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const key = options.key;
    //>>includeStart('debug', pragmas.debug);
    if (!defined(key)) {
      throw new DeveloperError("options.key is required.");
    }
    //>>includeEnd('debug');

    this._key = key;

    const queryParameters = {
      key: key,
    };

    if (defined(options.culture)) {
      queryParameters.culture = options.culture;
    }

    this._resource = new Resource({
      url: url,
      queryParameters: queryParameters,
    });
  }

  Object.defineProperties(BingMapsGeocoderService.prototype, {
    /**
     * The URL endpoint for the Bing geocoder service
     * @type {String}
     * @memberof BingMapsGeocoderService.prototype
     * @readonly
     */
    url: {
      get: function () {
        return url;
      },
    },

    /**
     * The key for the Bing geocoder service
     * @type {String}
     * @memberof BingMapsGeocoderService.prototype
     * @readonly
     */
    key: {
      get: function () {
        return this._key;
      },
    },
  });

  /**
   * @function
   *
   * @param {String} query The query to be sent to the geocoder service
   * @returns {Promise<GeocoderService.Result[]>}
   */
  BingMapsGeocoderService.prototype.geocode = function (query) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("query", query);
    //>>includeEnd('debug');

    const resource = this._resource.getDerivedResource({
      queryParameters: {
        query: query,
      },
    });

    return resource.fetchJsonp("jsonp").then(function (result) {
      if (result.resourceSets.length === 0) {
        return [];
      }

      const results = result.resourceSets[0].resources;

      return results.map(function (resource) {
        const bbox = resource.bbox;
        const south = bbox[0];
        const west = bbox[1];
        const north = bbox[2];
        const east = bbox[3];
        return {
          displayName: resource.name,
          destination: Rectangle.fromDegrees(west, south, east, north),
        };
      });
    });
  };

  /**
   * A bounding rectangle given by a corner, width and height.
   * @alias BoundingRectangle
   * @constructor
   *
   * @param {Number} [x=0.0] The x coordinate of the rectangle.
   * @param {Number} [y=0.0] The y coordinate of the rectangle.
   * @param {Number} [width=0.0] The width of the rectangle.
   * @param {Number} [height=0.0] The height of the rectangle.
   *
   * @see BoundingSphere
   * @see Packable
   */
  function BoundingRectangle(x, y, width, height) {
    /**
     * The x coordinate of the rectangle.
     * @type {Number}
     * @default 0.0
     */
    this.x = defaultValue(x, 0.0);

    /**
     * The y coordinate of the rectangle.
     * @type {Number}
     * @default 0.0
     */
    this.y = defaultValue(y, 0.0);

    /**
     * The width of the rectangle.
     * @type {Number}
     * @default 0.0
     */
    this.width = defaultValue(width, 0.0);

    /**
     * The height of the rectangle.
     * @type {Number}
     * @default 0.0
     */
    this.height = defaultValue(height, 0.0);
  }

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  BoundingRectangle.packedLength = 4;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {BoundingRectangle} 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
   */
  BoundingRectangle.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    array[startingIndex++] = value.x;
    array[startingIndex++] = value.y;
    array[startingIndex++] = value.width;
    array[startingIndex] = value.height;

    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 {BoundingRectangle} [result] The object into which to store the result.
   * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided.
   */
  BoundingRectangle.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    if (!defined(result)) {
      result = new BoundingRectangle();
    }
    result.x = array[startingIndex++];
    result.y = array[startingIndex++];
    result.width = array[startingIndex++];
    result.height = array[startingIndex];
    return result;
  };

  /**
   * Computes a bounding rectangle enclosing the list of 2D points.
   * The rectangle is oriented with the corner at the bottom left.
   *
   * @param {Cartesian2[]} positions List of points that the bounding rectangle will enclose.  Each point must have <code>x</code> and <code>y</code> properties.
   * @param {BoundingRectangle} [result] The object onto which to store the result.
   * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided.
   */
  BoundingRectangle.fromPoints = function (positions, result) {
    if (!defined(result)) {
      result = new BoundingRectangle();
    }

    if (!defined(positions) || positions.length === 0) {
      result.x = 0;
      result.y = 0;
      result.width = 0;
      result.height = 0;
      return result;
    }

    const length = positions.length;

    let minimumX = positions[0].x;
    let minimumY = positions[0].y;

    let maximumX = positions[0].x;
    let maximumY = positions[0].y;

    for (let i = 1; i < length; i++) {
      const p = positions[i];
      const x = p.x;
      const y = p.y;

      minimumX = Math.min(x, minimumX);
      maximumX = Math.max(x, maximumX);
      minimumY = Math.min(y, minimumY);
      maximumY = Math.max(y, maximumY);
    }

    result.x = minimumX;
    result.y = minimumY;
    result.width = maximumX - minimumX;
    result.height = maximumY - minimumY;
    return result;
  };

  const defaultProjection = new GeographicProjection();
  const fromRectangleLowerLeft = new Cartographic();
  const fromRectangleUpperRight = new Cartographic();
  /**
   * Computes a bounding rectangle from a rectangle.
   *
   * @param {Rectangle} rectangle The valid rectangle used to create a bounding rectangle.
   * @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
   * @param {BoundingRectangle} [result] The object onto which to store the result.
   * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided.
   */
  BoundingRectangle.fromRectangle = function (rectangle, projection, result) {
    if (!defined(result)) {
      result = new BoundingRectangle();
    }

    if (!defined(rectangle)) {
      result.x = 0;
      result.y = 0;
      result.width = 0;
      result.height = 0;
      return result;
    }

    projection = defaultValue(projection, defaultProjection);

    const lowerLeft = projection.project(
      Rectangle.southwest(rectangle, fromRectangleLowerLeft)
    );
    const upperRight = projection.project(
      Rectangle.northeast(rectangle, fromRectangleUpperRight)
    );

    Cartesian2.subtract(upperRight, lowerLeft, upperRight);

    result.x = lowerLeft.x;
    result.y = lowerLeft.y;
    result.width = upperRight.x;
    result.height = upperRight.y;
    return result;
  };

  /**
   * Duplicates a BoundingRectangle instance.
   *
   * @param {BoundingRectangle} rectangle The bounding rectangle to duplicate.
   * @param {BoundingRectangle} [result] The object onto which to store the result.
   * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided. (Returns undefined if rectangle is undefined)
   */
  BoundingRectangle.clone = function (rectangle, result) {
    if (!defined(rectangle)) {
      return undefined;
    }

    if (!defined(result)) {
      return new BoundingRectangle(
        rectangle.x,
        rectangle.y,
        rectangle.width,
        rectangle.height
      );
    }

    result.x = rectangle.x;
    result.y = rectangle.y;
    result.width = rectangle.width;
    result.height = rectangle.height;
    return result;
  };

  /**
   * Computes a bounding rectangle that is the union of the left and right bounding rectangles.
   *
   * @param {BoundingRectangle} left A rectangle to enclose in bounding rectangle.
   * @param {BoundingRectangle} right A rectangle to enclose in a bounding rectangle.
   * @param {BoundingRectangle} [result] The object onto which to store the result.
   * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided.
   */
  BoundingRectangle.union = function (left, right, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new BoundingRectangle();
    }

    const lowerLeftX = Math.min(left.x, right.x);
    const lowerLeftY = Math.min(left.y, right.y);
    const upperRightX = Math.max(left.x + left.width, right.x + right.width);
    const upperRightY = Math.max(left.y + left.height, right.y + right.height);

    result.x = lowerLeftX;
    result.y = lowerLeftY;
    result.width = upperRightX - lowerLeftX;
    result.height = upperRightY - lowerLeftY;
    return result;
  };

  /**
   * Computes a bounding rectangle by enlarging the provided rectangle until it contains the provided point.
   *
   * @param {BoundingRectangle} rectangle A rectangle to expand.
   * @param {Cartesian2} point A point to enclose in a bounding rectangle.
   * @param {BoundingRectangle} [result] The object onto which to store the result.
   * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided.
   */
  BoundingRectangle.expand = function (rectangle, point, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("rectangle", rectangle);
    Check.typeOf.object("point", point);
    //>>includeEnd('debug');

    result = BoundingRectangle.clone(rectangle, result);

    const width = point.x - result.x;
    const height = point.y - result.y;

    if (width > result.width) {
      result.width = width;
    } else if (width < 0) {
      result.width -= width;
      result.x = point.x;
    }

    if (height > result.height) {
      result.height = height;
    } else if (height < 0) {
      result.height -= height;
      result.y = point.y;
    }

    return result;
  };

  /**
   * Determines if two rectangles intersect.
   *
   * @param {BoundingRectangle} left A rectangle to check for intersection.
   * @param {BoundingRectangle} right The other rectangle to check for intersection.
   * @returns {Intersect} <code>Intersect.INTERSECTING</code> if the rectangles intersect, <code>Intersect.OUTSIDE</code> otherwise.
   */
  BoundingRectangle.intersect = function (left, right) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    //>>includeEnd('debug');

    const leftX = left.x;
    const leftY = left.y;
    const rightX = right.x;
    const rightY = right.y;
    if (
      !(
        leftX > rightX + right.width ||
        leftX + left.width < rightX ||
        leftY + left.height < rightY ||
        leftY > rightY + right.height
      )
    ) {
      return Intersect$1.INTERSECTING;
    }

    return Intersect$1.OUTSIDE;
  };

  /**
   * Compares the provided BoundingRectangles componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {BoundingRectangle} [left] The first BoundingRectangle.
   * @param {BoundingRectangle} [right] The second BoundingRectangle.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  BoundingRectangle.equals = function (left, right) {
    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        left.x === right.x &&
        left.y === right.y &&
        left.width === right.width &&
        left.height === right.height)
    );
  };

  /**
   * Duplicates this BoundingRectangle instance.
   *
   * @param {BoundingRectangle} [result] The object onto which to store the result.
   * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided.
   */
  BoundingRectangle.prototype.clone = function (result) {
    return BoundingRectangle.clone(this, result);
  };

  /**
   * Determines if this rectangle intersects with another.
   *
   * @param {BoundingRectangle} right A rectangle to check for intersection.
   * @returns {Intersect} <code>Intersect.INTERSECTING</code> if the rectangles intersect, <code>Intersect.OUTSIDE</code> otherwise.
   */
  BoundingRectangle.prototype.intersect = function (right) {
    return BoundingRectangle.intersect(this, right);
  };

  /**
   * Compares this BoundingRectangle against the provided BoundingRectangle componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {BoundingRectangle} [right] The right hand side BoundingRectangle.
   * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
   */
  BoundingRectangle.prototype.equals = function (right) {
    return BoundingRectangle.equals(this, right);
  };

  /**
   * @private
   */
  const GeometryType = {
    NONE: 0,
    TRIANGLES: 1,
    LINES: 2,
    POLYLINES: 3,
  };
  var GeometryType$1 = Object.freeze(GeometryType);

  /**
   * The type of a geometric primitive, i.e., points, lines, and triangles.
   *
   * @enum {Number}
   */
  const PrimitiveType = {
    /**
     * Points primitive where each vertex (or index) is a separate point.
     *
     * @type {Number}
     * @constant
     */
    POINTS: WebGLConstants$1.POINTS,

    /**
     * Lines primitive where each two vertices (or indices) is a line segment.  Line segments are not necessarily connected.
     *
     * @type {Number}
     * @constant
     */
    LINES: WebGLConstants$1.LINES,

    /**
     * Line loop primitive where each vertex (or index) after the first connects a line to
     * the previous vertex, and the last vertex implicitly connects to the first.
     *
     * @type {Number}
     * @constant
     */
    LINE_LOOP: WebGLConstants$1.LINE_LOOP,

    /**
     * Line strip primitive where each vertex (or index) after the first connects a line to the previous vertex.
     *
     * @type {Number}
     * @constant
     */
    LINE_STRIP: WebGLConstants$1.LINE_STRIP,

    /**
     * Triangles primitive where each three vertices (or indices) is a triangle.  Triangles do not necessarily share edges.
     *
     * @type {Number}
     * @constant
     */
    TRIANGLES: WebGLConstants$1.TRIANGLES,

    /**
     * Triangle strip primitive where each vertex (or index) after the first two connect to
     * the previous two vertices forming a triangle.  For example, this can be used to model a wall.
     *
     * @type {Number}
     * @constant
     */
    TRIANGLE_STRIP: WebGLConstants$1.TRIANGLE_STRIP,

    /**
     * Triangle fan primitive where each vertex (or index) after the first two connect to
     * the previous vertex and the first vertex forming a triangle.  For example, this can be used
     * to model a cone or circle.
     *
     * @type {Number}
     * @constant
     */
    TRIANGLE_FAN: WebGLConstants$1.TRIANGLE_FAN,
  };

  /**
   * @private
   */
  PrimitiveType.isLines = function (primitiveType) {
    return (
      primitiveType === PrimitiveType.LINES ||
      primitiveType === PrimitiveType.LINE_LOOP ||
      primitiveType === PrimitiveType.LINE_STRIP
    );
  };

  /**
   * @private
   */
  PrimitiveType.isTriangles = function (primitiveType) {
    return (
      primitiveType === PrimitiveType.TRIANGLES ||
      primitiveType === PrimitiveType.TRIANGLE_STRIP ||
      primitiveType === PrimitiveType.TRIANGLE_FAN
    );
  };

  /**
   * @private
   */
  PrimitiveType.validate = function (primitiveType) {
    return (
      primitiveType === PrimitiveType.POINTS ||
      primitiveType === PrimitiveType.LINES ||
      primitiveType === PrimitiveType.LINE_LOOP ||
      primitiveType === PrimitiveType.LINE_STRIP ||
      primitiveType === PrimitiveType.TRIANGLES ||
      primitiveType === PrimitiveType.TRIANGLE_STRIP ||
      primitiveType === PrimitiveType.TRIANGLE_FAN
    );
  };

  var PrimitiveType$1 = Object.freeze(PrimitiveType);

  /**
   * A geometry representation with attributes forming vertices and optional index data
   * defining primitives.  Geometries and an {@link Appearance}, which describes the shading,
   * can be assigned to a {@link Primitive} for visualization.  A <code>Primitive</code> can
   * be created from many heterogeneous - in many cases - geometries for performance.
   * <p>
   * Geometries can be transformed and optimized using functions in {@link GeometryPipeline}.
   * </p>
   *
   * @alias Geometry
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {GeometryAttributes} options.attributes Attributes, which make up the geometry's vertices.
   * @param {PrimitiveType} [options.primitiveType=PrimitiveType.TRIANGLES] The type of primitives in the geometry.
   * @param {Uint16Array|Uint32Array} [options.indices] Optional index data that determines the primitives in the geometry.
   * @param {BoundingSphere} [options.boundingSphere] An optional bounding sphere that fully enclosed the geometry.
   *
   * @see PolygonGeometry
   * @see RectangleGeometry
   * @see EllipseGeometry
   * @see CircleGeometry
   * @see WallGeometry
   * @see SimplePolylineGeometry
   * @see BoxGeometry
   * @see EllipsoidGeometry
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Geometry%20and%20Appearances.html|Geometry and Appearances Demo}
   *
   * @example
   * // Create geometry with a position attribute and indexed lines.
   * const positions = new Float64Array([
   *   0.0, 0.0, 0.0,
   *   7500000.0, 0.0, 0.0,
   *   0.0, 7500000.0, 0.0
   * ]);
   *
   * const geometry = new Cesium.Geometry({
   *   attributes : {
   *     position : new Cesium.GeometryAttribute({
   *       componentDatatype : Cesium.ComponentDatatype.DOUBLE,
   *       componentsPerAttribute : 3,
   *       values : positions
   *     })
   *   },
   *   indices : new Uint16Array([0, 1, 1, 2, 2, 0]),
   *   primitiveType : Cesium.PrimitiveType.LINES,
   *   boundingSphere : Cesium.BoundingSphere.fromVertices(positions)
   * });
   */
  function Geometry(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.attributes", options.attributes);
    //>>includeEnd('debug');

    /**
     * Attributes, which make up the geometry's vertices.  Each property in this object corresponds to a
     * {@link GeometryAttribute} containing the attribute's data.
     * <p>
     * Attributes are always stored non-interleaved in a Geometry.
     * </p>
     * <p>
     * There are reserved attribute names with well-known semantics.  The following attributes
     * are created by a Geometry (depending on the provided {@link VertexFormat}.
     * <ul>
     *    <li><code>position</code> - 3D vertex position.  64-bit floating-point (for precision).  3 components per attribute.  See {@link VertexFormat#position}.</li>
     *    <li><code>normal</code> - Normal (normalized), commonly used for lighting.  32-bit floating-point.  3 components per attribute.  See {@link VertexFormat#normal}.</li>
     *    <li><code>st</code> - 2D texture coordinate.  32-bit floating-point.  2 components per attribute.  See {@link VertexFormat#st}.</li>
     *    <li><code>bitangent</code> - Bitangent (normalized), used for tangent-space effects like bump mapping.  32-bit floating-point.  3 components per attribute.  See {@link VertexFormat#bitangent}.</li>
     *    <li><code>tangent</code> - Tangent (normalized), used for tangent-space effects like bump mapping.  32-bit floating-point.  3 components per attribute.  See {@link VertexFormat#tangent}.</li>
     * </ul>
     * </p>
     * <p>
     * The following attribute names are generally not created by a Geometry, but are added
     * to a Geometry by a {@link Primitive} or {@link GeometryPipeline} functions to prepare
     * the geometry for rendering.
     * <ul>
     *    <li><code>position3DHigh</code> - High 32 bits for encoded 64-bit position computed with {@link GeometryPipeline.encodeAttribute}.  32-bit floating-point.  4 components per attribute.</li>
     *    <li><code>position3DLow</code> - Low 32 bits for encoded 64-bit position computed with {@link GeometryPipeline.encodeAttribute}.  32-bit floating-point.  4 components per attribute.</li>
     *    <li><code>position3DHigh</code> - High 32 bits for encoded 64-bit 2D (Columbus view) position computed with {@link GeometryPipeline.encodeAttribute}.  32-bit floating-point.  4 components per attribute.</li>
     *    <li><code>position2DLow</code> - Low 32 bits for encoded 64-bit 2D (Columbus view) position computed with {@link GeometryPipeline.encodeAttribute}.  32-bit floating-point.  4 components per attribute.</li>
     *    <li><code>color</code> - RGBA color (normalized) usually from {@link GeometryInstance#color}.  32-bit floating-point.  4 components per attribute.</li>
     *    <li><code>pickColor</code> - RGBA color used for picking.  32-bit floating-point.  4 components per attribute.</li>
     * </ul>
     * </p>
     *
     * @type GeometryAttributes
     *
     * @default undefined
     *
     *
     * @example
     * geometry.attributes.position = new Cesium.GeometryAttribute({
     *   componentDatatype : Cesium.ComponentDatatype.FLOAT,
     *   componentsPerAttribute : 3,
     *   values : new Float32Array(0)
     * });
     *
     * @see GeometryAttribute
     * @see VertexFormat
     */
    this.attributes = options.attributes;

    /**
     * Optional index data that - along with {@link Geometry#primitiveType} -
     * determines the primitives in the geometry.
     *
     * @type Array
     *
     * @default undefined
     */
    this.indices = options.indices;

    /**
     * The type of primitives in the geometry.  This is most often {@link PrimitiveType.TRIANGLES},
     * but can varying based on the specific geometry.
     *
     * @type PrimitiveType
     *
     * @default undefined
     */
    this.primitiveType = defaultValue(
      options.primitiveType,
      PrimitiveType$1.TRIANGLES
    );

    /**
     * An optional bounding sphere that fully encloses the geometry.  This is
     * commonly used for culling.
     *
     * @type BoundingSphere
     *
     * @default undefined
     */
    this.boundingSphere = options.boundingSphere;

    /**
     * @private
     */
    this.geometryType = defaultValue(options.geometryType, GeometryType$1.NONE);

    /**
     * @private
     */
    this.boundingSphereCV = options.boundingSphereCV;

    /**
     * Used for computing the bounding sphere for geometry using the applyOffset vertex attribute
     * @private
     */
    this.offsetAttribute = options.offsetAttribute;
  }

  /**
   * Computes the number of vertices in a geometry.  The runtime is linear with
   * respect to the number of attributes in a vertex, not the number of vertices.
   *
   * @param {Geometry} geometry The geometry.
   * @returns {Number} The number of vertices in the geometry.
   *
   * @example
   * const numVertices = Cesium.Geometry.computeNumberOfVertices(geometry);
   */
  Geometry.computeNumberOfVertices = function (geometry) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("geometry", geometry);
    //>>includeEnd('debug');

    let numberOfVertices = -1;
    for (const property in geometry.attributes) {
      if (
        geometry.attributes.hasOwnProperty(property) &&
        defined(geometry.attributes[property]) &&
        defined(geometry.attributes[property].values)
      ) {
        const attribute = geometry.attributes[property];
        const num = attribute.values.length / attribute.componentsPerAttribute;
        //>>includeStart('debug', pragmas.debug);
        if (numberOfVertices !== num && numberOfVertices !== -1) {
          throw new DeveloperError(
            "All attribute lists must have the same number of attributes."
          );
        }
        //>>includeEnd('debug');
        numberOfVertices = num;
      }
    }

    return numberOfVertices;
  };

  const rectangleCenterScratch$3 = new Cartographic();
  const enuCenterScratch = new Cartesian3();
  const fixedFrameToEnuScratch = new Matrix4();
  const boundingRectanglePointsCartographicScratch = [
    new Cartographic(),
    new Cartographic(),
    new Cartographic(),
  ];
  const boundingRectanglePointsEnuScratch = [
    new Cartesian2(),
    new Cartesian2(),
    new Cartesian2(),
  ];
  const points2DScratch$2 = [new Cartesian2(), new Cartesian2(), new Cartesian2()];
  const pointEnuScratch = new Cartesian3();
  const enuRotationScratch = new Quaternion();
  const enuRotationMatrixScratch = new Matrix4();
  const rotation2DScratch$1 = new Matrix2();

  /**
   * For remapping texture coordinates when rendering GroundPrimitives with materials.
   * GroundPrimitive texture coordinates are computed to align with the cartographic coordinate system on the globe.
   * However, EllipseGeometry, RectangleGeometry, and PolygonGeometry all bake rotations to per-vertex texture coordinates
   * using different strategies.
   *
   * This method is used by EllipseGeometry and PolygonGeometry to approximate the same visual effect.
   * We encapsulate rotation and scale by computing a "transformed" texture coordinate system and computing
   * a set of reference points from which "cartographic" texture coordinates can be remapped to the "transformed"
   * system using distances to lines in 2D.
   *
   * This approximation becomes less accurate as the covered area increases, especially for GroundPrimitives near the poles,
   * but is generally reasonable for polygons and ellipses around the size of USA states.
   *
   * RectangleGeometry has its own version of this method that computes remapping coordinates using cartographic space
   * as an intermediary instead of local ENU, which is more accurate for large-area rectangles.
   *
   * @param {Cartesian3[]} positions Array of positions outlining the geometry
   * @param {Number} stRotation Texture coordinate rotation.
   * @param {Ellipsoid} ellipsoid Ellipsoid for projecting and generating local vectors.
   * @param {Rectangle} boundingRectangle Bounding rectangle around the positions.
   * @returns {Number[]} An array of 6 numbers specifying [minimum point, u extent, v extent] as points in the "cartographic" system.
   * @private
   */
  Geometry._textureCoordinateRotationPoints = function (
    positions,
    stRotation,
    ellipsoid,
    boundingRectangle
  ) {
    let i;

    // Create a local east-north-up coordinate system centered on the polygon's bounding rectangle.
    // Project the southwest, northwest, and southeast corners of the bounding rectangle into the plane of ENU as 2D points.
    // These are the equivalents of (0,0), (0,1), and (1,0) in the texture coordiante system computed in ShadowVolumeAppearanceFS,
    // aka "ENU texture space."
    const rectangleCenter = Rectangle.center(
      boundingRectangle,
      rectangleCenterScratch$3
    );
    const enuCenter = Cartographic.toCartesian(
      rectangleCenter,
      ellipsoid,
      enuCenterScratch
    );
    const enuToFixedFrame = Transforms.eastNorthUpToFixedFrame(
      enuCenter,
      ellipsoid,
      fixedFrameToEnuScratch
    );
    const fixedFrameToEnu = Matrix4.inverse(
      enuToFixedFrame,
      fixedFrameToEnuScratch
    );

    const boundingPointsEnu = boundingRectanglePointsEnuScratch;
    const boundingPointsCarto = boundingRectanglePointsCartographicScratch;

    boundingPointsCarto[0].longitude = boundingRectangle.west;
    boundingPointsCarto[0].latitude = boundingRectangle.south;

    boundingPointsCarto[1].longitude = boundingRectangle.west;
    boundingPointsCarto[1].latitude = boundingRectangle.north;

    boundingPointsCarto[2].longitude = boundingRectangle.east;
    boundingPointsCarto[2].latitude = boundingRectangle.south;

    let posEnu = pointEnuScratch;

    for (i = 0; i < 3; i++) {
      Cartographic.toCartesian(boundingPointsCarto[i], ellipsoid, posEnu);
      posEnu = Matrix4.multiplyByPointAsVector(fixedFrameToEnu, posEnu, posEnu);
      boundingPointsEnu[i].x = posEnu.x;
      boundingPointsEnu[i].y = posEnu.y;
    }

    // Rotate each point in the polygon around the up vector in the ENU by -stRotation and project into ENU as 2D.
    // Compute the bounding box of these rotated points in the 2D ENU plane.
    // Rotate the corners back by stRotation, then compute their equivalents in the ENU texture space using the corners computed earlier.
    const rotation = Quaternion.fromAxisAngle(
      Cartesian3.UNIT_Z,
      -stRotation,
      enuRotationScratch
    );
    const textureMatrix = Matrix3.fromQuaternion(
      rotation,
      enuRotationMatrixScratch
    );

    const positionsLength = positions.length;
    let enuMinX = Number.POSITIVE_INFINITY;
    let enuMinY = Number.POSITIVE_INFINITY;
    let enuMaxX = Number.NEGATIVE_INFINITY;
    let enuMaxY = Number.NEGATIVE_INFINITY;
    for (i = 0; i < positionsLength; i++) {
      posEnu = Matrix4.multiplyByPointAsVector(
        fixedFrameToEnu,
        positions[i],
        posEnu
      );
      posEnu = Matrix3.multiplyByVector(textureMatrix, posEnu, posEnu);

      enuMinX = Math.min(enuMinX, posEnu.x);
      enuMinY = Math.min(enuMinY, posEnu.y);
      enuMaxX = Math.max(enuMaxX, posEnu.x);
      enuMaxY = Math.max(enuMaxY, posEnu.y);
    }

    const toDesiredInComputed = Matrix2.fromRotation(
      stRotation,
      rotation2DScratch$1
    );

    const points2D = points2DScratch$2;
    points2D[0].x = enuMinX;
    points2D[0].y = enuMinY;

    points2D[1].x = enuMinX;
    points2D[1].y = enuMaxY;

    points2D[2].x = enuMaxX;
    points2D[2].y = enuMinY;

    const boundingEnuMin = boundingPointsEnu[0];
    const boundingPointsWidth = boundingPointsEnu[2].x - boundingEnuMin.x;
    const boundingPointsHeight = boundingPointsEnu[1].y - boundingEnuMin.y;

    for (i = 0; i < 3; i++) {
      const point2D = points2D[i];
      // rotate back
      Matrix2.multiplyByVector(toDesiredInComputed, point2D, point2D);

      // Convert point into east-north texture coordinate space
      point2D.x = (point2D.x - boundingEnuMin.x) / boundingPointsWidth;
      point2D.y = (point2D.y - boundingEnuMin.y) / boundingPointsHeight;
    }

    const minXYCorner = points2D[0];
    const maxYCorner = points2D[1];
    const maxXCorner = points2D[2];
    const result = new Array(6);
    Cartesian2.pack(minXYCorner, result);
    Cartesian2.pack(maxYCorner, result, 2);
    Cartesian2.pack(maxXCorner, result, 4);

    return result;
  };

  /**
   * Values and type information for geometry attributes.  A {@link Geometry}
   * generally contains one or more attributes.  All attributes together form
   * the geometry's vertices.
   *
   * @alias GeometryAttribute
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {ComponentDatatype} [options.componentDatatype] The datatype of each component in the attribute, e.g., individual elements in values.
   * @param {Number} [options.componentsPerAttribute] A number between 1 and 4 that defines the number of components in an attributes.
   * @param {Boolean} [options.normalize=false] When <code>true</code> and <code>componentDatatype</code> is an integer format, indicate that the components should be mapped to the range [0, 1] (unsigned) or [-1, 1] (signed) when they are accessed as floating-point for rendering.
   * @param {number[]|Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} [options.values] The values for the attributes stored in a typed array.
   *
   * @exception {DeveloperError} options.componentsPerAttribute must be between 1 and 4.
   *
   *
   * @example
   * const geometry = new Cesium.Geometry({
   *   attributes : {
   *     position : new Cesium.GeometryAttribute({
   *       componentDatatype : Cesium.ComponentDatatype.FLOAT,
   *       componentsPerAttribute : 3,
   *       values : new Float32Array([
   *         0.0, 0.0, 0.0,
   *         7500000.0, 0.0, 0.0,
   *         0.0, 7500000.0, 0.0
   *       ])
   *     })
   *   },
   *   primitiveType : Cesium.PrimitiveType.LINE_LOOP
   * });
   *
   * @see Geometry
   */
  function GeometryAttribute(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    if (!defined(options.componentDatatype)) {
      throw new DeveloperError("options.componentDatatype is required.");
    }
    if (!defined(options.componentsPerAttribute)) {
      throw new DeveloperError("options.componentsPerAttribute is required.");
    }
    if (
      options.componentsPerAttribute < 1 ||
      options.componentsPerAttribute > 4
    ) {
      throw new DeveloperError(
        "options.componentsPerAttribute must be between 1 and 4."
      );
    }
    if (!defined(options.values)) {
      throw new DeveloperError("options.values is required.");
    }
    //>>includeEnd('debug');

    /**
     * The datatype of each component in the attribute, e.g., individual elements in
     * {@link GeometryAttribute#values}.
     *
     * @type ComponentDatatype
     *
     * @default undefined
     */
    this.componentDatatype = options.componentDatatype;

    /**
     * A number between 1 and 4 that defines the number of components in an attributes.
     * For example, a position attribute with x, y, and z components would have 3 as
     * shown in the code example.
     *
     * @type Number
     *
     * @default undefined
     *
     * @example
     * attribute.componentDatatype = Cesium.ComponentDatatype.FLOAT;
     * attribute.componentsPerAttribute = 3;
     * attribute.values = new Float32Array([
     *   0.0, 0.0, 0.0,
     *   7500000.0, 0.0, 0.0,
     *   0.0, 7500000.0, 0.0
     * ]);
     */
    this.componentsPerAttribute = options.componentsPerAttribute;

    /**
     * When <code>true</code> and <code>componentDatatype</code> is an integer format,
     * indicate that the components should be mapped to the range [0, 1] (unsigned)
     * or [-1, 1] (signed) when they are accessed as floating-point for rendering.
     * <p>
     * This is commonly used when storing colors using {@link ComponentDatatype.UNSIGNED_BYTE}.
     * </p>
     *
     * @type Boolean
     *
     * @default false
     *
     * @example
     * attribute.componentDatatype = Cesium.ComponentDatatype.UNSIGNED_BYTE;
     * attribute.componentsPerAttribute = 4;
     * attribute.normalize = true;
     * attribute.values = new Uint8Array([
     *   Cesium.Color.floatToByte(color.red),
     *   Cesium.Color.floatToByte(color.green),
     *   Cesium.Color.floatToByte(color.blue),
     *   Cesium.Color.floatToByte(color.alpha)
     * ]);
     */
    this.normalize = defaultValue(options.normalize, false);

    /**
     * The values for the attributes stored in a typed array.  In the code example,
     * every three elements in <code>values</code> defines one attributes since
     * <code>componentsPerAttribute</code> is 3.
     *
     * @type {number[]|Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array}
     *
     * @default undefined
     *
     * @example
     * attribute.componentDatatype = Cesium.ComponentDatatype.FLOAT;
     * attribute.componentsPerAttribute = 3;
     * attribute.values = new Float32Array([
     *   0.0, 0.0, 0.0,
     *   7500000.0, 0.0, 0.0,
     *   0.0, 7500000.0, 0.0
     * ]);
     */
    this.values = options.values;
  }

  /**
   * Attributes, which make up a geometry's vertices.  Each property in this object corresponds to a
   * {@link GeometryAttribute} containing the attribute's data.
   * <p>
   * Attributes are always stored non-interleaved in a Geometry.
   * </p>
   *
   * @alias GeometryAttributes
   * @constructor
   */
  function GeometryAttributes(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    /**
     * The 3D position attribute.
     * <p>
     * 64-bit floating-point (for precision).  3 components per attribute.
     * </p>
     *
     * @type GeometryAttribute
     *
     * @default undefined
     */
    this.position = options.position;

    /**
     * The normal attribute (normalized), which is commonly used for lighting.
     * <p>
     * 32-bit floating-point.  3 components per attribute.
     * </p>
     *
     * @type GeometryAttribute
     *
     * @default undefined
     */
    this.normal = options.normal;

    /**
     * The 2D texture coordinate attribute.
     * <p>
     * 32-bit floating-point.  2 components per attribute
     * </p>
     *
     * @type GeometryAttribute
     *
     * @default undefined
     */
    this.st = options.st;

    /**
     * The bitangent attribute (normalized), which is used for tangent-space effects like bump mapping.
     * <p>
     * 32-bit floating-point.  3 components per attribute.
     * </p>
     *
     * @type GeometryAttribute
     *
     * @default undefined
     */
    this.bitangent = options.bitangent;

    /**
     * The tangent attribute (normalized), which is used for tangent-space effects like bump mapping.
     * <p>
     * 32-bit floating-point.  3 components per attribute.
     * </p>
     *
     * @type GeometryAttribute
     *
     * @default undefined
     */
    this.tangent = options.tangent;

    /**
     * The color attribute.
     * <p>
     * 8-bit unsigned integer. 4 components per attribute.
     * </p>
     *
     * @type GeometryAttribute
     *
     * @default undefined
     */
    this.color = options.color;
  }

  /**
   * Represents which vertices should have a value of `true` for the `applyOffset` attribute
   * @private
   */
  const GeometryOffsetAttribute = {
    NONE: 0,
    TOP: 1,
    ALL: 2,
  };
  var GeometryOffsetAttribute$1 = Object.freeze(GeometryOffsetAttribute);

  /**
   * A vertex format defines what attributes make up a vertex.  A VertexFormat can be provided
   * to a {@link Geometry} to request that certain properties be computed, e.g., just position,
   * position and normal, etc.
   *
   * @param {Object} [options] An object with boolean properties corresponding to VertexFormat properties as shown in the code example.
   *
   * @alias VertexFormat
   * @constructor
   *
   * @example
   * // Create a vertex format with position and 2D texture coordinate attributes.
   * const format = new Cesium.VertexFormat({
   *   position : true,
   *   st : true
   * });
   *
   * @see Geometry#attributes
   * @see Packable
   */
  function VertexFormat(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    /**
     * When <code>true</code>, the vertex has a 3D position attribute.
     * <p>
     * 64-bit floating-point (for precision).  3 components per attribute.
     * </p>
     *
     * @type Boolean
     *
     * @default false
     */
    this.position = defaultValue(options.position, false);

    /**
     * When <code>true</code>, the vertex has a normal attribute (normalized), which is commonly used for lighting.
     * <p>
     * 32-bit floating-point.  3 components per attribute.
     * </p>
     *
     * @type Boolean
     *
     * @default false
     */
    this.normal = defaultValue(options.normal, false);

    /**
     * When <code>true</code>, the vertex has a 2D texture coordinate attribute.
     * <p>
     * 32-bit floating-point.  2 components per attribute
     * </p>
     *
     * @type Boolean
     *
     * @default false
     */
    this.st = defaultValue(options.st, false);

    /**
     * When <code>true</code>, the vertex has a bitangent attribute (normalized), which is used for tangent-space effects like bump mapping.
     * <p>
     * 32-bit floating-point.  3 components per attribute.
     * </p>
     *
     * @type Boolean
     *
     * @default false
     */
    this.bitangent = defaultValue(options.bitangent, false);

    /**
     * When <code>true</code>, the vertex has a tangent attribute (normalized), which is used for tangent-space effects like bump mapping.
     * <p>
     * 32-bit floating-point.  3 components per attribute.
     * </p>
     *
     * @type Boolean
     *
     * @default false
     */
    this.tangent = defaultValue(options.tangent, false);

    /**
     * When <code>true</code>, the vertex has an RGB color attribute.
     * <p>
     * 8-bit unsigned byte.  3 components per attribute.
     * </p>
     *
     * @type Boolean
     *
     * @default false
     */
    this.color = defaultValue(options.color, false);
  }

  /**
   * An immutable vertex format with only a position attribute.
   *
   * @type {VertexFormat}
   * @constant
   *
   * @see VertexFormat#position
   */
  VertexFormat.POSITION_ONLY = Object.freeze(
    new VertexFormat({
      position: true,
    })
  );

  /**
   * An immutable vertex format with position and normal attributes.
   * This is compatible with per-instance color appearances like {@link PerInstanceColorAppearance}.
   *
   * @type {VertexFormat}
   * @constant
   *
   * @see VertexFormat#position
   * @see VertexFormat#normal
   */
  VertexFormat.POSITION_AND_NORMAL = Object.freeze(
    new VertexFormat({
      position: true,
      normal: true,
    })
  );

  /**
   * An immutable vertex format with position, normal, and st attributes.
   * This is compatible with {@link MaterialAppearance} when {@link MaterialAppearance#materialSupport}
   * is <code>TEXTURED/code>.
   *
   * @type {VertexFormat}
   * @constant
   *
   * @see VertexFormat#position
   * @see VertexFormat#normal
   * @see VertexFormat#st
   */
  VertexFormat.POSITION_NORMAL_AND_ST = Object.freeze(
    new VertexFormat({
      position: true,
      normal: true,
      st: true,
    })
  );

  /**
   * An immutable vertex format with position and st attributes.
   * This is compatible with {@link EllipsoidSurfaceAppearance}.
   *
   * @type {VertexFormat}
   * @constant
   *
   * @see VertexFormat#position
   * @see VertexFormat#st
   */
  VertexFormat.POSITION_AND_ST = Object.freeze(
    new VertexFormat({
      position: true,
      st: true,
    })
  );

  /**
   * An immutable vertex format with position and color attributes.
   *
   * @type {VertexFormat}
   * @constant
   *
   * @see VertexFormat#position
   * @see VertexFormat#color
   */
  VertexFormat.POSITION_AND_COLOR = Object.freeze(
    new VertexFormat({
      position: true,
      color: true,
    })
  );

  /**
   * An immutable vertex format with well-known attributes: position, normal, st, tangent, and bitangent.
   *
   * @type {VertexFormat}
   * @constant
   *
   * @see VertexFormat#position
   * @see VertexFormat#normal
   * @see VertexFormat#st
   * @see VertexFormat#tangent
   * @see VertexFormat#bitangent
   */
  VertexFormat.ALL = Object.freeze(
    new VertexFormat({
      position: true,
      normal: true,
      st: true,
      tangent: true,
      bitangent: true,
    })
  );

  /**
   * An immutable vertex format with position, normal, and st attributes.
   * This is compatible with most appearances and materials; however
   * normal and st attributes are not always required.  When this is
   * known in advance, another <code>VertexFormat</code> should be used.
   *
   * @type {VertexFormat}
   * @constant
   *
   * @see VertexFormat#position
   * @see VertexFormat#normal
   */
  VertexFormat.DEFAULT = VertexFormat.POSITION_NORMAL_AND_ST;

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  VertexFormat.packedLength = 6;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {VertexFormat} 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
   */
  VertexFormat.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(value)) {
      throw new DeveloperError("value is required");
    }
    if (!defined(array)) {
      throw new DeveloperError("array is required");
    }
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    array[startingIndex++] = value.position ? 1.0 : 0.0;
    array[startingIndex++] = value.normal ? 1.0 : 0.0;
    array[startingIndex++] = value.st ? 1.0 : 0.0;
    array[startingIndex++] = value.tangent ? 1.0 : 0.0;
    array[startingIndex++] = value.bitangent ? 1.0 : 0.0;
    array[startingIndex] = value.color ? 1.0 : 0.0;

    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 {VertexFormat} [result] The object into which to store the result.
   * @returns {VertexFormat} The modified result parameter or a new VertexFormat instance if one was not provided.
   */
  VertexFormat.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(array)) {
      throw new DeveloperError("array is required");
    }
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    if (!defined(result)) {
      result = new VertexFormat();
    }

    result.position = array[startingIndex++] === 1.0;
    result.normal = array[startingIndex++] === 1.0;
    result.st = array[startingIndex++] === 1.0;
    result.tangent = array[startingIndex++] === 1.0;
    result.bitangent = array[startingIndex++] === 1.0;
    result.color = array[startingIndex] === 1.0;
    return result;
  };

  /**
   * Duplicates a VertexFormat instance.
   *
   * @param {VertexFormat} vertexFormat The vertex format to duplicate.
   * @param {VertexFormat} [result] The object onto which to store the result.
   * @returns {VertexFormat} The modified result parameter or a new VertexFormat instance if one was not provided. (Returns undefined if vertexFormat is undefined)
   */
  VertexFormat.clone = function (vertexFormat, result) {
    if (!defined(vertexFormat)) {
      return undefined;
    }
    if (!defined(result)) {
      result = new VertexFormat();
    }

    result.position = vertexFormat.position;
    result.normal = vertexFormat.normal;
    result.st = vertexFormat.st;
    result.tangent = vertexFormat.tangent;
    result.bitangent = vertexFormat.bitangent;
    result.color = vertexFormat.color;
    return result;
  };

  const diffScratch$1 = new Cartesian3();

  /**
   * Describes a cube centered at the origin.
   *
   * @alias BoxGeometry
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Cartesian3} options.minimum The minimum x, y, and z coordinates of the box.
   * @param {Cartesian3} options.maximum The maximum x, y, and z coordinates of the box.
   * @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
   *
   * @see BoxGeometry.fromDimensions
   * @see BoxGeometry.createGeometry
   * @see Packable
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Box.html|Cesium Sandcastle Box Demo}
   *
   * @example
   * const box = new Cesium.BoxGeometry({
   *   vertexFormat : Cesium.VertexFormat.POSITION_ONLY,
   *   maximum : new Cesium.Cartesian3(250000.0, 250000.0, 250000.0),
   *   minimum : new Cesium.Cartesian3(-250000.0, -250000.0, -250000.0)
   * });
   * const geometry = Cesium.BoxGeometry.createGeometry(box);
   */
  function BoxGeometry(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const min = options.minimum;
    const max = options.maximum;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("min", min);
    Check.typeOf.object("max", max);
    if (
      defined(options.offsetAttribute) &&
      options.offsetAttribute === GeometryOffsetAttribute$1.TOP
    ) {
      throw new DeveloperError(
        "GeometryOffsetAttribute.TOP is not a supported options.offsetAttribute for this geometry."
      );
    }
    //>>includeEnd('debug');

    const vertexFormat = defaultValue(options.vertexFormat, VertexFormat.DEFAULT);

    this._minimum = Cartesian3.clone(min);
    this._maximum = Cartesian3.clone(max);
    this._vertexFormat = vertexFormat;
    this._offsetAttribute = options.offsetAttribute;
    this._workerName = "createBoxGeometry";
  }

  /**
   * Creates a cube centered at the origin given its dimensions.
   *
   * @param {Object} options Object with the following properties:
   * @param {Cartesian3} options.dimensions The width, depth, and height of the box stored in the x, y, and z coordinates of the <code>Cartesian3</code>, respectively.
   * @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
   * @returns {BoxGeometry}
   *
   * @exception {DeveloperError} All dimensions components must be greater than or equal to zero.
   *
   *
   * @example
   * const box = Cesium.BoxGeometry.fromDimensions({
   *   vertexFormat : Cesium.VertexFormat.POSITION_ONLY,
   *   dimensions : new Cesium.Cartesian3(500000.0, 500000.0, 500000.0)
   * });
   * const geometry = Cesium.BoxGeometry.createGeometry(box);
   *
   * @see BoxGeometry.createGeometry
   */
  BoxGeometry.fromDimensions = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const dimensions = options.dimensions;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("dimensions", dimensions);
    Check.typeOf.number.greaterThanOrEquals("dimensions.x", dimensions.x, 0);
    Check.typeOf.number.greaterThanOrEquals("dimensions.y", dimensions.y, 0);
    Check.typeOf.number.greaterThanOrEquals("dimensions.z", dimensions.z, 0);
    //>>includeEnd('debug');

    const corner = Cartesian3.multiplyByScalar(dimensions, 0.5, new Cartesian3());

    return new BoxGeometry({
      minimum: Cartesian3.negate(corner, new Cartesian3()),
      maximum: corner,
      vertexFormat: options.vertexFormat,
      offsetAttribute: options.offsetAttribute,
    });
  };

  /**
   * Creates a cube from the dimensions of an AxisAlignedBoundingBox.
   *
   * @param {AxisAlignedBoundingBox} boundingBox A description of the AxisAlignedBoundingBox.
   * @returns {BoxGeometry}
   *
   *
   *
   * @example
   * const aabb = Cesium.AxisAlignedBoundingBox.fromPoints(Cesium.Cartesian3.fromDegreesArray([
   *      -72.0, 40.0,
   *      -70.0, 35.0,
   *      -75.0, 30.0,
   *      -70.0, 30.0,
   *      -68.0, 40.0
   * ]));
   * const box = Cesium.BoxGeometry.fromAxisAlignedBoundingBox(aabb);
   *
   * @see BoxGeometry.createGeometry
   */
  BoxGeometry.fromAxisAlignedBoundingBox = function (boundingBox) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("boundingBox", boundingBox);
    //>>includeEnd('debug');

    return new BoxGeometry({
      minimum: boundingBox.minimum,
      maximum: boundingBox.maximum,
    });
  };

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  BoxGeometry.packedLength =
    2 * Cartesian3.packedLength + VertexFormat.packedLength + 1;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {BoxGeometry} 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
   */
  BoxGeometry.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    Cartesian3.pack(value._minimum, array, startingIndex);
    Cartesian3.pack(
      value._maximum,
      array,
      startingIndex + Cartesian3.packedLength
    );
    VertexFormat.pack(
      value._vertexFormat,
      array,
      startingIndex + 2 * Cartesian3.packedLength
    );
    array[
      startingIndex + 2 * Cartesian3.packedLength + VertexFormat.packedLength
    ] = defaultValue(value._offsetAttribute, -1);

    return array;
  };

  const scratchMin$4 = new Cartesian3();
  const scratchMax$4 = new Cartesian3();
  const scratchVertexFormat$c = new VertexFormat();
  const scratchOptions$n = {
    minimum: scratchMin$4,
    maximum: scratchMax$4,
    vertexFormat: scratchVertexFormat$c,
    offsetAttribute: undefined,
  };

  /**
   * 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 {BoxGeometry} [result] The object into which to store the result.
   * @returns {BoxGeometry} The modified result parameter or a new BoxGeometry instance if one was not provided.
   */
  BoxGeometry.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    const min = Cartesian3.unpack(array, startingIndex, scratchMin$4);
    const max = Cartesian3.unpack(
      array,
      startingIndex + Cartesian3.packedLength,
      scratchMax$4
    );
    const vertexFormat = VertexFormat.unpack(
      array,
      startingIndex + 2 * Cartesian3.packedLength,
      scratchVertexFormat$c
    );
    const offsetAttribute =
      array[
        startingIndex + 2 * Cartesian3.packedLength + VertexFormat.packedLength
      ];

    if (!defined(result)) {
      scratchOptions$n.offsetAttribute =
        offsetAttribute === -1 ? undefined : offsetAttribute;
      return new BoxGeometry(scratchOptions$n);
    }

    result._minimum = Cartesian3.clone(min, result._minimum);
    result._maximum = Cartesian3.clone(max, result._maximum);
    result._vertexFormat = VertexFormat.clone(vertexFormat, result._vertexFormat);
    result._offsetAttribute =
      offsetAttribute === -1 ? undefined : offsetAttribute;

    return result;
  };

  /**
   * Computes the geometric representation of a box, including its vertices, indices, and a bounding sphere.
   *
   * @param {BoxGeometry} boxGeometry A description of the box.
   * @returns {Geometry|undefined} The computed vertices and indices.
   */
  BoxGeometry.createGeometry = function (boxGeometry) {
    const min = boxGeometry._minimum;
    const max = boxGeometry._maximum;
    const vertexFormat = boxGeometry._vertexFormat;

    if (Cartesian3.equals(min, max)) {
      return;
    }

    const attributes = new GeometryAttributes();
    let indices;
    let positions;

    if (
      vertexFormat.position &&
      (vertexFormat.st ||
        vertexFormat.normal ||
        vertexFormat.tangent ||
        vertexFormat.bitangent)
    ) {
      if (vertexFormat.position) {
        // 8 corner points.  Duplicated 3 times each for each incident edge/face.
        positions = new Float64Array(6 * 4 * 3);

        // +z face
        positions[0] = min.x;
        positions[1] = min.y;
        positions[2] = max.z;
        positions[3] = max.x;
        positions[4] = min.y;
        positions[5] = max.z;
        positions[6] = max.x;
        positions[7] = max.y;
        positions[8] = max.z;
        positions[9] = min.x;
        positions[10] = max.y;
        positions[11] = max.z;

        // -z face
        positions[12] = min.x;
        positions[13] = min.y;
        positions[14] = min.z;
        positions[15] = max.x;
        positions[16] = min.y;
        positions[17] = min.z;
        positions[18] = max.x;
        positions[19] = max.y;
        positions[20] = min.z;
        positions[21] = min.x;
        positions[22] = max.y;
        positions[23] = min.z;

        // +x face
        positions[24] = max.x;
        positions[25] = min.y;
        positions[26] = min.z;
        positions[27] = max.x;
        positions[28] = max.y;
        positions[29] = min.z;
        positions[30] = max.x;
        positions[31] = max.y;
        positions[32] = max.z;
        positions[33] = max.x;
        positions[34] = min.y;
        positions[35] = max.z;

        // -x face
        positions[36] = min.x;
        positions[37] = min.y;
        positions[38] = min.z;
        positions[39] = min.x;
        positions[40] = max.y;
        positions[41] = min.z;
        positions[42] = min.x;
        positions[43] = max.y;
        positions[44] = max.z;
        positions[45] = min.x;
        positions[46] = min.y;
        positions[47] = max.z;

        // +y face
        positions[48] = min.x;
        positions[49] = max.y;
        positions[50] = min.z;
        positions[51] = max.x;
        positions[52] = max.y;
        positions[53] = min.z;
        positions[54] = max.x;
        positions[55] = max.y;
        positions[56] = max.z;
        positions[57] = min.x;
        positions[58] = max.y;
        positions[59] = max.z;

        // -y face
        positions[60] = min.x;
        positions[61] = min.y;
        positions[62] = min.z;
        positions[63] = max.x;
        positions[64] = min.y;
        positions[65] = min.z;
        positions[66] = max.x;
        positions[67] = min.y;
        positions[68] = max.z;
        positions[69] = min.x;
        positions[70] = min.y;
        positions[71] = max.z;

        attributes.position = new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.DOUBLE,
          componentsPerAttribute: 3,
          values: positions,
        });
      }

      if (vertexFormat.normal) {
        const normals = new Float32Array(6 * 4 * 3);

        // +z face
        normals[0] = 0.0;
        normals[1] = 0.0;
        normals[2] = 1.0;
        normals[3] = 0.0;
        normals[4] = 0.0;
        normals[5] = 1.0;
        normals[6] = 0.0;
        normals[7] = 0.0;
        normals[8] = 1.0;
        normals[9] = 0.0;
        normals[10] = 0.0;
        normals[11] = 1.0;

        // -z face
        normals[12] = 0.0;
        normals[13] = 0.0;
        normals[14] = -1.0;
        normals[15] = 0.0;
        normals[16] = 0.0;
        normals[17] = -1.0;
        normals[18] = 0.0;
        normals[19] = 0.0;
        normals[20] = -1.0;
        normals[21] = 0.0;
        normals[22] = 0.0;
        normals[23] = -1.0;

        // +x face
        normals[24] = 1.0;
        normals[25] = 0.0;
        normals[26] = 0.0;
        normals[27] = 1.0;
        normals[28] = 0.0;
        normals[29] = 0.0;
        normals[30] = 1.0;
        normals[31] = 0.0;
        normals[32] = 0.0;
        normals[33] = 1.0;
        normals[34] = 0.0;
        normals[35] = 0.0;

        // -x face
        normals[36] = -1.0;
        normals[37] = 0.0;
        normals[38] = 0.0;
        normals[39] = -1.0;
        normals[40] = 0.0;
        normals[41] = 0.0;
        normals[42] = -1.0;
        normals[43] = 0.0;
        normals[44] = 0.0;
        normals[45] = -1.0;
        normals[46] = 0.0;
        normals[47] = 0.0;

        // +y face
        normals[48] = 0.0;
        normals[49] = 1.0;
        normals[50] = 0.0;
        normals[51] = 0.0;
        normals[52] = 1.0;
        normals[53] = 0.0;
        normals[54] = 0.0;
        normals[55] = 1.0;
        normals[56] = 0.0;
        normals[57] = 0.0;
        normals[58] = 1.0;
        normals[59] = 0.0;

        // -y face
        normals[60] = 0.0;
        normals[61] = -1.0;
        normals[62] = 0.0;
        normals[63] = 0.0;
        normals[64] = -1.0;
        normals[65] = 0.0;
        normals[66] = 0.0;
        normals[67] = -1.0;
        normals[68] = 0.0;
        normals[69] = 0.0;
        normals[70] = -1.0;
        normals[71] = 0.0;

        attributes.normal = new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 3,
          values: normals,
        });
      }

      if (vertexFormat.st) {
        const texCoords = new Float32Array(6 * 4 * 2);

        // +z face
        texCoords[0] = 0.0;
        texCoords[1] = 0.0;
        texCoords[2] = 1.0;
        texCoords[3] = 0.0;
        texCoords[4] = 1.0;
        texCoords[5] = 1.0;
        texCoords[6] = 0.0;
        texCoords[7] = 1.0;

        // -z face
        texCoords[8] = 1.0;
        texCoords[9] = 0.0;
        texCoords[10] = 0.0;
        texCoords[11] = 0.0;
        texCoords[12] = 0.0;
        texCoords[13] = 1.0;
        texCoords[14] = 1.0;
        texCoords[15] = 1.0;

        //+x face
        texCoords[16] = 0.0;
        texCoords[17] = 0.0;
        texCoords[18] = 1.0;
        texCoords[19] = 0.0;
        texCoords[20] = 1.0;
        texCoords[21] = 1.0;
        texCoords[22] = 0.0;
        texCoords[23] = 1.0;

        // -x face
        texCoords[24] = 1.0;
        texCoords[25] = 0.0;
        texCoords[26] = 0.0;
        texCoords[27] = 0.0;
        texCoords[28] = 0.0;
        texCoords[29] = 1.0;
        texCoords[30] = 1.0;
        texCoords[31] = 1.0;

        // +y face
        texCoords[32] = 1.0;
        texCoords[33] = 0.0;
        texCoords[34] = 0.0;
        texCoords[35] = 0.0;
        texCoords[36] = 0.0;
        texCoords[37] = 1.0;
        texCoords[38] = 1.0;
        texCoords[39] = 1.0;

        // -y face
        texCoords[40] = 0.0;
        texCoords[41] = 0.0;
        texCoords[42] = 1.0;
        texCoords[43] = 0.0;
        texCoords[44] = 1.0;
        texCoords[45] = 1.0;
        texCoords[46] = 0.0;
        texCoords[47] = 1.0;

        attributes.st = new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 2,
          values: texCoords,
        });
      }

      if (vertexFormat.tangent) {
        const tangents = new Float32Array(6 * 4 * 3);

        // +z face
        tangents[0] = 1.0;
        tangents[1] = 0.0;
        tangents[2] = 0.0;
        tangents[3] = 1.0;
        tangents[4] = 0.0;
        tangents[5] = 0.0;
        tangents[6] = 1.0;
        tangents[7] = 0.0;
        tangents[8] = 0.0;
        tangents[9] = 1.0;
        tangents[10] = 0.0;
        tangents[11] = 0.0;

        // -z face
        tangents[12] = -1.0;
        tangents[13] = 0.0;
        tangents[14] = 0.0;
        tangents[15] = -1.0;
        tangents[16] = 0.0;
        tangents[17] = 0.0;
        tangents[18] = -1.0;
        tangents[19] = 0.0;
        tangents[20] = 0.0;
        tangents[21] = -1.0;
        tangents[22] = 0.0;
        tangents[23] = 0.0;

        // +x face
        tangents[24] = 0.0;
        tangents[25] = 1.0;
        tangents[26] = 0.0;
        tangents[27] = 0.0;
        tangents[28] = 1.0;
        tangents[29] = 0.0;
        tangents[30] = 0.0;
        tangents[31] = 1.0;
        tangents[32] = 0.0;
        tangents[33] = 0.0;
        tangents[34] = 1.0;
        tangents[35] = 0.0;

        // -x face
        tangents[36] = 0.0;
        tangents[37] = -1.0;
        tangents[38] = 0.0;
        tangents[39] = 0.0;
        tangents[40] = -1.0;
        tangents[41] = 0.0;
        tangents[42] = 0.0;
        tangents[43] = -1.0;
        tangents[44] = 0.0;
        tangents[45] = 0.0;
        tangents[46] = -1.0;
        tangents[47] = 0.0;

        // +y face
        tangents[48] = -1.0;
        tangents[49] = 0.0;
        tangents[50] = 0.0;
        tangents[51] = -1.0;
        tangents[52] = 0.0;
        tangents[53] = 0.0;
        tangents[54] = -1.0;
        tangents[55] = 0.0;
        tangents[56] = 0.0;
        tangents[57] = -1.0;
        tangents[58] = 0.0;
        tangents[59] = 0.0;

        // -y face
        tangents[60] = 1.0;
        tangents[61] = 0.0;
        tangents[62] = 0.0;
        tangents[63] = 1.0;
        tangents[64] = 0.0;
        tangents[65] = 0.0;
        tangents[66] = 1.0;
        tangents[67] = 0.0;
        tangents[68] = 0.0;
        tangents[69] = 1.0;
        tangents[70] = 0.0;
        tangents[71] = 0.0;

        attributes.tangent = new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 3,
          values: tangents,
        });
      }

      if (vertexFormat.bitangent) {
        const bitangents = new Float32Array(6 * 4 * 3);

        // +z face
        bitangents[0] = 0.0;
        bitangents[1] = 1.0;
        bitangents[2] = 0.0;
        bitangents[3] = 0.0;
        bitangents[4] = 1.0;
        bitangents[5] = 0.0;
        bitangents[6] = 0.0;
        bitangents[7] = 1.0;
        bitangents[8] = 0.0;
        bitangents[9] = 0.0;
        bitangents[10] = 1.0;
        bitangents[11] = 0.0;

        // -z face
        bitangents[12] = 0.0;
        bitangents[13] = 1.0;
        bitangents[14] = 0.0;
        bitangents[15] = 0.0;
        bitangents[16] = 1.0;
        bitangents[17] = 0.0;
        bitangents[18] = 0.0;
        bitangents[19] = 1.0;
        bitangents[20] = 0.0;
        bitangents[21] = 0.0;
        bitangents[22] = 1.0;
        bitangents[23] = 0.0;

        // +x face
        bitangents[24] = 0.0;
        bitangents[25] = 0.0;
        bitangents[26] = 1.0;
        bitangents[27] = 0.0;
        bitangents[28] = 0.0;
        bitangents[29] = 1.0;
        bitangents[30] = 0.0;
        bitangents[31] = 0.0;
        bitangents[32] = 1.0;
        bitangents[33] = 0.0;
        bitangents[34] = 0.0;
        bitangents[35] = 1.0;

        // -x face
        bitangents[36] = 0.0;
        bitangents[37] = 0.0;
        bitangents[38] = 1.0;
        bitangents[39] = 0.0;
        bitangents[40] = 0.0;
        bitangents[41] = 1.0;
        bitangents[42] = 0.0;
        bitangents[43] = 0.0;
        bitangents[44] = 1.0;
        bitangents[45] = 0.0;
        bitangents[46] = 0.0;
        bitangents[47] = 1.0;

        // +y face
        bitangents[48] = 0.0;
        bitangents[49] = 0.0;
        bitangents[50] = 1.0;
        bitangents[51] = 0.0;
        bitangents[52] = 0.0;
        bitangents[53] = 1.0;
        bitangents[54] = 0.0;
        bitangents[55] = 0.0;
        bitangents[56] = 1.0;
        bitangents[57] = 0.0;
        bitangents[58] = 0.0;
        bitangents[59] = 1.0;

        // -y face
        bitangents[60] = 0.0;
        bitangents[61] = 0.0;
        bitangents[62] = 1.0;
        bitangents[63] = 0.0;
        bitangents[64] = 0.0;
        bitangents[65] = 1.0;
        bitangents[66] = 0.0;
        bitangents[67] = 0.0;
        bitangents[68] = 1.0;
        bitangents[69] = 0.0;
        bitangents[70] = 0.0;
        bitangents[71] = 1.0;

        attributes.bitangent = new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 3,
          values: bitangents,
        });
      }

      // 12 triangles:  6 faces, 2 triangles each.
      indices = new Uint16Array(6 * 2 * 3);

      // +z face
      indices[0] = 0;
      indices[1] = 1;
      indices[2] = 2;
      indices[3] = 0;
      indices[4] = 2;
      indices[5] = 3;

      // -z face
      indices[6] = 4 + 2;
      indices[7] = 4 + 1;
      indices[8] = 4 + 0;
      indices[9] = 4 + 3;
      indices[10] = 4 + 2;
      indices[11] = 4 + 0;

      // +x face
      indices[12] = 8 + 0;
      indices[13] = 8 + 1;
      indices[14] = 8 + 2;
      indices[15] = 8 + 0;
      indices[16] = 8 + 2;
      indices[17] = 8 + 3;

      // -x face
      indices[18] = 12 + 2;
      indices[19] = 12 + 1;
      indices[20] = 12 + 0;
      indices[21] = 12 + 3;
      indices[22] = 12 + 2;
      indices[23] = 12 + 0;

      // +y face
      indices[24] = 16 + 2;
      indices[25] = 16 + 1;
      indices[26] = 16 + 0;
      indices[27] = 16 + 3;
      indices[28] = 16 + 2;
      indices[29] = 16 + 0;

      // -y face
      indices[30] = 20 + 0;
      indices[31] = 20 + 1;
      indices[32] = 20 + 2;
      indices[33] = 20 + 0;
      indices[34] = 20 + 2;
      indices[35] = 20 + 3;
    } else {
      // Positions only - no need to duplicate corner points
      positions = new Float64Array(8 * 3);

      positions[0] = min.x;
      positions[1] = min.y;
      positions[2] = min.z;
      positions[3] = max.x;
      positions[4] = min.y;
      positions[5] = min.z;
      positions[6] = max.x;
      positions[7] = max.y;
      positions[8] = min.z;
      positions[9] = min.x;
      positions[10] = max.y;
      positions[11] = min.z;
      positions[12] = min.x;
      positions[13] = min.y;
      positions[14] = max.z;
      positions[15] = max.x;
      positions[16] = min.y;
      positions[17] = max.z;
      positions[18] = max.x;
      positions[19] = max.y;
      positions[20] = max.z;
      positions[21] = min.x;
      positions[22] = max.y;
      positions[23] = max.z;

      attributes.position = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.DOUBLE,
        componentsPerAttribute: 3,
        values: positions,
      });

      // 12 triangles:  6 faces, 2 triangles each.
      indices = new Uint16Array(6 * 2 * 3);

      // plane z = corner.Z
      indices[0] = 4;
      indices[1] = 5;
      indices[2] = 6;
      indices[3] = 4;
      indices[4] = 6;
      indices[5] = 7;

      // plane z = -corner.Z
      indices[6] = 1;
      indices[7] = 0;
      indices[8] = 3;
      indices[9] = 1;
      indices[10] = 3;
      indices[11] = 2;

      // plane x = corner.X
      indices[12] = 1;
      indices[13] = 6;
      indices[14] = 5;
      indices[15] = 1;
      indices[16] = 2;
      indices[17] = 6;

      // plane y = corner.Y
      indices[18] = 2;
      indices[19] = 3;
      indices[20] = 7;
      indices[21] = 2;
      indices[22] = 7;
      indices[23] = 6;

      // plane x = -corner.X
      indices[24] = 3;
      indices[25] = 0;
      indices[26] = 4;
      indices[27] = 3;
      indices[28] = 4;
      indices[29] = 7;

      // plane y = -corner.Y
      indices[30] = 0;
      indices[31] = 1;
      indices[32] = 5;
      indices[33] = 0;
      indices[34] = 5;
      indices[35] = 4;
    }

    const diff = Cartesian3.subtract(max, min, diffScratch$1);
    const radius = Cartesian3.magnitude(diff) * 0.5;

    if (defined(boxGeometry._offsetAttribute)) {
      const length = positions.length;
      const offsetValue =
        boxGeometry._offsetAttribute === GeometryOffsetAttribute$1.NONE ? 0 : 1;
      const applyOffset = new Uint8Array(length / 3).fill(offsetValue);
      attributes.applyOffset = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
        componentsPerAttribute: 1,
        values: applyOffset,
      });
    }

    return new Geometry({
      attributes: attributes,
      indices: indices,
      primitiveType: PrimitiveType$1.TRIANGLES,
      boundingSphere: new BoundingSphere(Cartesian3.ZERO, radius),
      offsetAttribute: boxGeometry._offsetAttribute,
    });
  };

  let unitBoxGeometry;

  /**
   * Returns the geometric representation of a unit box, including its vertices, indices, and a bounding sphere.
   * @returns {Geometry} The computed vertices and indices.
   *
   * @private
   */
  BoxGeometry.getUnitBox = function () {
    if (!defined(unitBoxGeometry)) {
      unitBoxGeometry = BoxGeometry.createGeometry(
        BoxGeometry.fromDimensions({
          dimensions: new Cartesian3(1.0, 1.0, 1.0),
          vertexFormat: VertexFormat.POSITION_ONLY,
        })
      );
    }
    return unitBoxGeometry;
  };

  const diffScratch = new Cartesian3();

  /**
   * A description of the outline of a cube centered at the origin.
   *
   * @alias BoxOutlineGeometry
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Cartesian3} options.minimum The minimum x, y, and z coordinates of the box.
   * @param {Cartesian3} options.maximum The maximum x, y, and z coordinates of the box.
   *
   * @see BoxOutlineGeometry.fromDimensions
   * @see BoxOutlineGeometry.createGeometry
   * @see Packable
   *
   * @example
   * const box = new Cesium.BoxOutlineGeometry({
   *   maximum : new Cesium.Cartesian3(250000.0, 250000.0, 250000.0),
   *   minimum : new Cesium.Cartesian3(-250000.0, -250000.0, -250000.0)
   * });
   * const geometry = Cesium.BoxOutlineGeometry.createGeometry(box);
   */
  function BoxOutlineGeometry(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const min = options.minimum;
    const max = options.maximum;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("min", min);
    Check.typeOf.object("max", max);
    if (
      defined(options.offsetAttribute) &&
      options.offsetAttribute === GeometryOffsetAttribute$1.TOP
    ) {
      throw new DeveloperError(
        "GeometryOffsetAttribute.TOP is not a supported options.offsetAttribute for this geometry."
      );
    }
    //>>includeEnd('debug');

    this._min = Cartesian3.clone(min);
    this._max = Cartesian3.clone(max);
    this._offsetAttribute = options.offsetAttribute;
    this._workerName = "createBoxOutlineGeometry";
  }

  /**
   * Creates an outline of a cube centered at the origin given its dimensions.
   *
   * @param {Object} options Object with the following properties:
   * @param {Cartesian3} options.dimensions The width, depth, and height of the box stored in the x, y, and z coordinates of the <code>Cartesian3</code>, respectively.
   * @returns {BoxOutlineGeometry}
   *
   * @exception {DeveloperError} All dimensions components must be greater than or equal to zero.
   *
   *
   * @example
   * const box = Cesium.BoxOutlineGeometry.fromDimensions({
   *   dimensions : new Cesium.Cartesian3(500000.0, 500000.0, 500000.0)
   * });
   * const geometry = Cesium.BoxOutlineGeometry.createGeometry(box);
   *
   * @see BoxOutlineGeometry.createGeometry
   */
  BoxOutlineGeometry.fromDimensions = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const dimensions = options.dimensions;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("dimensions", dimensions);
    Check.typeOf.number.greaterThanOrEquals("dimensions.x", dimensions.x, 0);
    Check.typeOf.number.greaterThanOrEquals("dimensions.y", dimensions.y, 0);
    Check.typeOf.number.greaterThanOrEquals("dimensions.z", dimensions.z, 0);
    //>>includeEnd('debug');

    const corner = Cartesian3.multiplyByScalar(dimensions, 0.5, new Cartesian3());

    return new BoxOutlineGeometry({
      minimum: Cartesian3.negate(corner, new Cartesian3()),
      maximum: corner,
      offsetAttribute: options.offsetAttribute,
    });
  };

  /**
   * Creates an outline of a cube from the dimensions of an AxisAlignedBoundingBox.
   *
   * @param {AxisAlignedBoundingBox} boundingBox A description of the AxisAlignedBoundingBox.
   * @returns {BoxOutlineGeometry}
   *
   *
   *
   * @example
   * const aabb = Cesium.AxisAlignedBoundingBox.fromPoints(Cesium.Cartesian3.fromDegreesArray([
   *      -72.0, 40.0,
   *      -70.0, 35.0,
   *      -75.0, 30.0,
   *      -70.0, 30.0,
   *      -68.0, 40.0
   * ]));
   * const box = Cesium.BoxOutlineGeometry.fromAxisAlignedBoundingBox(aabb);
   *
   *  @see BoxOutlineGeometry.createGeometry
   */
  BoxOutlineGeometry.fromAxisAlignedBoundingBox = function (boundingBox) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("boundindBox", boundingBox);
    //>>includeEnd('debug');

    return new BoxOutlineGeometry({
      minimum: boundingBox.minimum,
      maximum: boundingBox.maximum,
    });
  };

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  BoxOutlineGeometry.packedLength = 2 * Cartesian3.packedLength + 1;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {BoxOutlineGeometry} 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
   */
  BoxOutlineGeometry.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    Cartesian3.pack(value._min, array, startingIndex);
    Cartesian3.pack(value._max, array, startingIndex + Cartesian3.packedLength);
    array[startingIndex + Cartesian3.packedLength * 2] = defaultValue(
      value._offsetAttribute,
      -1
    );

    return array;
  };

  const scratchMin$3 = new Cartesian3();
  const scratchMax$3 = new Cartesian3();
  const scratchOptions$m = {
    minimum: scratchMin$3,
    maximum: scratchMax$3,
    offsetAttribute: undefined,
  };

  /**
   * 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 {BoxOutlineGeometry} [result] The object into which to store the result.
   * @returns {BoxOutlineGeometry} The modified result parameter or a new BoxOutlineGeometry instance if one was not provided.
   */
  BoxOutlineGeometry.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    const min = Cartesian3.unpack(array, startingIndex, scratchMin$3);
    const max = Cartesian3.unpack(
      array,
      startingIndex + Cartesian3.packedLength,
      scratchMax$3
    );
    const offsetAttribute = array[startingIndex + Cartesian3.packedLength * 2];

    if (!defined(result)) {
      scratchOptions$m.offsetAttribute =
        offsetAttribute === -1 ? undefined : offsetAttribute;
      return new BoxOutlineGeometry(scratchOptions$m);
    }

    result._min = Cartesian3.clone(min, result._min);
    result._max = Cartesian3.clone(max, result._max);
    result._offsetAttribute =
      offsetAttribute === -1 ? undefined : offsetAttribute;

    return result;
  };

  /**
   * Computes the geometric representation of an outline of a box, including its vertices, indices, and a bounding sphere.
   *
   * @param {BoxOutlineGeometry} boxGeometry A description of the box outline.
   * @returns {Geometry|undefined} The computed vertices and indices.
   */
  BoxOutlineGeometry.createGeometry = function (boxGeometry) {
    const min = boxGeometry._min;
    const max = boxGeometry._max;

    if (Cartesian3.equals(min, max)) {
      return;
    }

    const attributes = new GeometryAttributes();
    const indices = new Uint16Array(12 * 2);
    const positions = new Float64Array(8 * 3);

    positions[0] = min.x;
    positions[1] = min.y;
    positions[2] = min.z;
    positions[3] = max.x;
    positions[4] = min.y;
    positions[5] = min.z;
    positions[6] = max.x;
    positions[7] = max.y;
    positions[8] = min.z;
    positions[9] = min.x;
    positions[10] = max.y;
    positions[11] = min.z;

    positions[12] = min.x;
    positions[13] = min.y;
    positions[14] = max.z;
    positions[15] = max.x;
    positions[16] = min.y;
    positions[17] = max.z;
    positions[18] = max.x;
    positions[19] = max.y;
    positions[20] = max.z;
    positions[21] = min.x;
    positions[22] = max.y;
    positions[23] = max.z;

    attributes.position = new GeometryAttribute({
      componentDatatype: ComponentDatatype$1.DOUBLE,
      componentsPerAttribute: 3,
      values: positions,
    });

    // top
    indices[0] = 4;
    indices[1] = 5;
    indices[2] = 5;
    indices[3] = 6;
    indices[4] = 6;
    indices[5] = 7;
    indices[6] = 7;
    indices[7] = 4;

    // bottom
    indices[8] = 0;
    indices[9] = 1;
    indices[10] = 1;
    indices[11] = 2;
    indices[12] = 2;
    indices[13] = 3;
    indices[14] = 3;
    indices[15] = 0;

    // left
    indices[16] = 0;
    indices[17] = 4;
    indices[18] = 1;
    indices[19] = 5;

    //right
    indices[20] = 2;
    indices[21] = 6;
    indices[22] = 3;
    indices[23] = 7;

    const diff = Cartesian3.subtract(max, min, diffScratch);
    const radius = Cartesian3.magnitude(diff) * 0.5;

    if (defined(boxGeometry._offsetAttribute)) {
      const length = positions.length;
      const offsetValue =
        boxGeometry._offsetAttribute === GeometryOffsetAttribute$1.NONE ? 0 : 1;
      const applyOffset = new Uint8Array(length / 3).fill(offsetValue);
      attributes.applyOffset = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
        componentsPerAttribute: 1,
        values: applyOffset,
      });
    }

    return new Geometry({
      attributes: attributes,
      indices: indices,
      primitiveType: PrimitiveType$1.LINES,
      boundingSphere: new BoundingSphere(Cartesian3.ZERO, radius),
      offsetAttribute: boxGeometry._offsetAttribute,
    });
  };

  /**
   * Geocodes queries containing longitude and latitude coordinates and an optional height.
   * Query format: `longitude latitude (height)` with longitude/latitude in degrees and height in meters.
   *
   * @alias CartographicGeocoderService
   * @constructor
   */
  function CartographicGeocoderService() {}

  /**
   * @function
   *
   * @param {String} query The query to be sent to the geocoder service
   * @returns {Promise<GeocoderService.Result[]>}
   */
  CartographicGeocoderService.prototype.geocode = function (query) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("query", query);
    //>>includeEnd('debug');

    const splitQuery = query.match(/[^\s,\n]+/g);
    if (splitQuery.length === 2 || splitQuery.length === 3) {
      let longitude = +splitQuery[0];
      let latitude = +splitQuery[1];
      const height = splitQuery.length === 3 ? +splitQuery[2] : 300.0;

      if (isNaN(longitude) && isNaN(latitude)) {
        const coordTest = /^(\d+.?\d*)([nsew])/i;
        for (let i = 0; i < splitQuery.length; ++i) {
          const splitCoord = splitQuery[i].match(coordTest);
          if (coordTest.test(splitQuery[i]) && splitCoord.length === 3) {
            if (/^[ns]/i.test(splitCoord[2])) {
              latitude = /^[n]/i.test(splitCoord[2])
                ? +splitCoord[1]
                : -splitCoord[1];
            } else if (/^[ew]/i.test(splitCoord[2])) {
              longitude = /^[e]/i.test(splitCoord[2])
                ? +splitCoord[1]
                : -splitCoord[1];
            }
          }
        }
      }

      if (!isNaN(longitude) && !isNaN(latitude) && !isNaN(height)) {
        const result = {
          displayName: query,
          destination: Cartesian3.fromDegrees(longitude, latitude, height),
        };
        return Promise.resolve([result]);
      }
    }
    return Promise.resolve([]);
  };

  /**
   * Creates a curve parameterized and evaluated by time. This type describes an interface
   * and is not intended to be instantiated directly.
   *
   * @alias Spline
   * @constructor
   *
   * @see CatmullRomSpline
   * @see LinearSpline
   * @see HermiteSpline
   * @see QuaternionSpline
   * @see MorphWeightSpline
   */
  function Spline() {
    /**
     * An array of times for the control points.
     * @type {Number[]}
     * @default undefined
     */
    this.times = undefined;

    /**
     * An array of control points.
     * @type {Cartesian3[]|Quaternion[]}
     * @default undefined
     */
    this.points = undefined;

    DeveloperError.throwInstantiationError();
  }

  /**
   * Gets the type of the point. This helps a spline determine how to interpolate
   * and return its values.
   *
   * @param {Number|Cartesian3|Quaternion} point
   * @returns {*} The type of the point.
   *
   * @exception {DeveloperError} value must be a Cartesian3, Quaternion, or Number.
   *
   * @private
   */
  Spline.getPointType = function (point) {
    if (typeof point === "number") {
      return Number;
    }
    if (point instanceof Cartesian3) {
      return Cartesian3;
    }
    if (point instanceof Quaternion) {
      return Quaternion;
    }

    //>>includeStart('debug', pragmas.debug);
    throw new DeveloperError(
      "point must be a Cartesian3, Quaternion, or Number."
    );
    //>>includeEnd('debug');
  };

  /**
   * Evaluates the curve at a given time.
   * @function
   *
   * @param {Number} time The time at which to evaluate the curve.
   * @param {Cartesian3|Quaternion|Number[]} [result] The object onto which to store the result.
   * @returns {Cartesian3|Quaternion|Number[]} The modified result parameter or a new instance of the point on the curve at the given time.
   *
   * @exception {DeveloperError} time must be in the range <code>[t<sub>0</sub>, t<sub>n</sub>]</code>, where <code>t<sub>0</sub></code>
   *                             is the first element in the array <code>times</code> and <code>t<sub>n</sub></code> is the last element
   *                             in the array <code>times</code>.
   */
  Spline.prototype.evaluate = DeveloperError.throwInstantiationError;

  /**
   * Finds an index <code>i</code> in <code>times</code> such that the parameter
   * <code>time</code> is in the interval <code>[times[i], times[i + 1]]</code>.
   *
   * @param {Number} time The time.
   * @param {Number} startIndex The index from which to start the search.
   * @returns {Number} The index for the element at the start of the interval.
   *
   * @exception {DeveloperError} time must be in the range <code>[t<sub>0</sub>, t<sub>n</sub>]</code>, where <code>t<sub>0</sub></code>
   *                             is the first element in the array <code>times</code> and <code>t<sub>n</sub></code> is the last element
   *                             in the array <code>times</code>.
   */
  Spline.prototype.findTimeInterval = function (time, startIndex) {
    const times = this.times;
    const length = times.length;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("time", time);
    if (time < times[0] || time > times[length - 1]) {
      throw new DeveloperError("time is out of range.");
    }
    //>>includeEnd('debug');

    // Take advantage of temporal coherence by checking current, next and previous intervals
    // for containment of time.
    startIndex = defaultValue(startIndex, 0);

    if (time >= times[startIndex]) {
      if (startIndex + 1 < length && time < times[startIndex + 1]) {
        return startIndex;
      } else if (startIndex + 2 < length && time < times[startIndex + 2]) {
        return startIndex + 1;
      }
    } else if (startIndex - 1 >= 0 && time >= times[startIndex - 1]) {
      return startIndex - 1;
    }

    // The above failed so do a linear search. For the use cases so far, the
    // length of the list is less than 10. In the future, if there is a bottle neck,
    // it might be here.

    let i;
    if (time > times[startIndex]) {
      for (i = startIndex; i < length - 1; ++i) {
        if (time >= times[i] && time < times[i + 1]) {
          break;
        }
      }
    } else {
      for (i = startIndex - 1; i >= 0; --i) {
        if (time >= times[i] && time < times[i + 1]) {
          break;
        }
      }
    }

    if (i === length - 1) {
      i = length - 2;
    }

    return i;
  };

  /**
   * Wraps the given time to the period covered by the spline.
   * @function
   *
   * @param {Number} time The time.
   * @return {Number} The time, wrapped around the animation period.
   */
  Spline.prototype.wrapTime = function (time) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("time", time);
    //>>includeEnd('debug');

    const times = this.times;
    const timeEnd = times[times.length - 1];
    const timeStart = times[0];
    const timeStretch = timeEnd - timeStart;
    let divs;
    if (time < timeStart) {
      divs = Math.floor((timeStart - time) / timeStretch) + 1;
      time += divs * timeStretch;
    }
    if (time > timeEnd) {
      divs = Math.floor((time - timeEnd) / timeStretch) + 1;
      time -= divs * timeStretch;
    }
    return time;
  };

  /**
   * Clamps the given time to the period covered by the spline.
   * @function
   *
   * @param {Number} time The time.
   * @return {Number} The time, clamped to the animation period.
   */
  Spline.prototype.clampTime = function (time) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("time", time);
    //>>includeEnd('debug');

    const times = this.times;
    return CesiumMath.clamp(time, times[0], times[times.length - 1]);
  };

  /**
   * A spline that uses piecewise linear interpolation to create a curve.
   *
   * @alias LinearSpline
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Number[]} options.times An array of strictly increasing, unit-less, floating-point times at each point.
   *                The values are in no way connected to the clock time. They are the parameterization for the curve.
   * @param {Number[]|Cartesian3[]} options.points The array of control points.
   *
   * @exception {DeveloperError} points.length must be greater than or equal to 2.
   * @exception {DeveloperError} times.length must be equal to points.length.
   *
   *
   * @example
   * const times = [ 0.0, 1.5, 3.0, 4.5, 6.0 ];
   * const spline = new Cesium.LinearSpline({
   *     times : times,
   *     points : [
   *         new Cesium.Cartesian3(1235398.0, -4810983.0, 4146266.0),
   *         new Cesium.Cartesian3(1372574.0, -5345182.0, 4606657.0),
   *         new Cesium.Cartesian3(-757983.0, -5542796.0, 4514323.0),
   *         new Cesium.Cartesian3(-2821260.0, -5248423.0, 4021290.0),
   *         new Cesium.Cartesian3(-2539788.0, -4724797.0, 3620093.0)
   *     ]
   * });
   *
   * const p0 = spline.evaluate(times[0]);
   *
   * @see ConstantSpline
   * @see SteppedSpline
   * @see HermiteSpline
   * @see CatmullRomSpline
   * @see QuaternionSpline
   * @see MorphWeightSpline
   */
  function LinearSpline(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const points = options.points;
    const times = options.times;

    //>>includeStart('debug', pragmas.debug);
    if (!defined(points) || !defined(times)) {
      throw new DeveloperError("points and times are required.");
    }
    if (points.length < 2) {
      throw new DeveloperError(
        "points.length must be greater than or equal to 2."
      );
    }
    if (times.length !== points.length) {
      throw new DeveloperError("times.length must be equal to points.length.");
    }
    //>>includeEnd('debug');

    this._times = times;
    this._points = points;
    this._pointType = Spline.getPointType(points[0]);

    this._lastTimeIndex = 0;
  }

  Object.defineProperties(LinearSpline.prototype, {
    /**
     * An array of times for the control points.
     *
     * @memberof LinearSpline.prototype
     *
     * @type {Number[]}
     * @readonly
     */
    times: {
      get: function () {
        return this._times;
      },
    },

    /**
     * An array of {@link Cartesian3} control points.
     *
     * @memberof LinearSpline.prototype
     *
     * @type {Number[]|Cartesian3[]}
     * @readonly
     */
    points: {
      get: function () {
        return this._points;
      },
    },
  });

  /**
   * Finds an index <code>i</code> in <code>times</code> such that the parameter
   * <code>time</code> is in the interval <code>[times[i], times[i + 1]]</code>.
   * @function
   *
   * @param {Number} time The time.
   * @returns {Number} The index for the element at the start of the interval.
   *
   * @exception {DeveloperError} time must be in the range <code>[t<sub>0</sub>, t<sub>n</sub>]</code>, where <code>t<sub>0</sub></code>
   *                             is the first element in the array <code>times</code> and <code>t<sub>n</sub></code> is the last element
   *                             in the array <code>times</code>.
   */
  LinearSpline.prototype.findTimeInterval = Spline.prototype.findTimeInterval;

  /**
   * Wraps the given time to the period covered by the spline.
   * @function
   *
   * @param {Number} time The time.
   * @return {Number} The time, wrapped around to the updated animation.
   */
  LinearSpline.prototype.wrapTime = Spline.prototype.wrapTime;

  /**
   * Clamps the given time to the period covered by the spline.
   * @function
   *
   * @param {Number} time The time.
   * @return {Number} The time, clamped to the animation period.
   */
  LinearSpline.prototype.clampTime = Spline.prototype.clampTime;

  /**
   * Evaluates the curve at a given time.
   *
   * @param {Number} time The time at which to evaluate the curve.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Number|Cartesian3} The modified result parameter or a new instance of the point on the curve at the given time.
   *
   * @exception {DeveloperError} time must be in the range <code>[t<sub>0</sub>, t<sub>n</sub>]</code>, where <code>t<sub>0</sub></code>
   *                             is the first element in the array <code>times</code> and <code>t<sub>n</sub></code> is the last element
   *                             in the array <code>times</code>.
   */
  LinearSpline.prototype.evaluate = function (time, result) {
    const points = this.points;
    const times = this.times;

    const i = (this._lastTimeIndex = this.findTimeInterval(
      time,
      this._lastTimeIndex
    ));
    const u = (time - times[i]) / (times[i + 1] - times[i]);

    const PointType = this._pointType;
    if (PointType === Number) {
      return (1.0 - u) * points[i] + u * points[i + 1];
    }

    if (!defined(result)) {
      result = new Cartesian3();
    }

    return Cartesian3.lerp(points[i], points[i + 1], u, result);
  };

  /**
   * Uses the Tridiagonal Matrix Algorithm, also known as the Thomas Algorithm, to solve
   * a system of linear equations where the coefficient matrix is a tridiagonal matrix.
   *
   * @namespace TridiagonalSystemSolver
   */
  const TridiagonalSystemSolver = {};

  /**
   * Solves a tridiagonal system of linear equations.
   *
   * @param {Number[]} diagonal An array with length <code>n</code> that contains the diagonal of the coefficient matrix.
   * @param {Number[]} lower An array with length <code>n - 1</code> that contains the lower diagonal of the coefficient matrix.
   * @param {Number[]} upper An array with length <code>n - 1</code> that contains the upper diagonal of the coefficient matrix.
   * @param {Cartesian3[]} right An array of Cartesians with length <code>n</code> that is the right side of the system of equations.
   *
   * @exception {DeveloperError} diagonal and right must have the same lengths.
   * @exception {DeveloperError} lower and upper must have the same lengths.
   * @exception {DeveloperError} lower and upper must be one less than the length of diagonal.
   *
   * @performance Linear time.
   *
   * @example
   * const lowerDiagonal = [1.0, 1.0, 1.0, 1.0];
   * const diagonal = [2.0, 4.0, 4.0, 4.0, 2.0];
   * const upperDiagonal = [1.0, 1.0, 1.0, 1.0];
   * const rightHandSide = [
   *     new Cesium.Cartesian3(410757.0, -1595711.0, 1375302.0),
   *     new Cesium.Cartesian3(-5986705.0, -2190640.0, 1099600.0),
   *     new Cesium.Cartesian3(-12593180.0, 288588.0, -1755549.0),
   *     new Cesium.Cartesian3(-5349898.0, 2457005.0, -2685438.0),
   *     new Cesium.Cartesian3(845820.0, 1573488.0, -1205591.0)
   * ];
   *
   * const solution = Cesium.TridiagonalSystemSolver.solve(lowerDiagonal, diagonal, upperDiagonal, rightHandSide);
   *
   * @returns {Cartesian3[]} An array of Cartesians with length <code>n</code> that is the solution to the tridiagonal system of equations.
   */
  TridiagonalSystemSolver.solve = function (lower, diagonal, upper, right) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(lower) || !(lower instanceof Array)) {
      throw new DeveloperError("The array lower is required.");
    }
    if (!defined(diagonal) || !(diagonal instanceof Array)) {
      throw new DeveloperError("The array diagonal is required.");
    }
    if (!defined(upper) || !(upper instanceof Array)) {
      throw new DeveloperError("The array upper is required.");
    }
    if (!defined(right) || !(right instanceof Array)) {
      throw new DeveloperError("The array right is required.");
    }
    if (diagonal.length !== right.length) {
      throw new DeveloperError("diagonal and right must have the same lengths.");
    }
    if (lower.length !== upper.length) {
      throw new DeveloperError("lower and upper must have the same lengths.");
    } else if (lower.length !== diagonal.length - 1) {
      throw new DeveloperError(
        "lower and upper must be one less than the length of diagonal."
      );
    }
    //>>includeEnd('debug');

    const c = new Array(upper.length);
    const d = new Array(right.length);
    const x = new Array(right.length);

    let i;
    for (i = 0; i < d.length; i++) {
      d[i] = new Cartesian3();
      x[i] = new Cartesian3();
    }

    c[0] = upper[0] / diagonal[0];
    d[0] = Cartesian3.multiplyByScalar(right[0], 1.0 / diagonal[0], d[0]);

    let scalar;
    for (i = 1; i < c.length; ++i) {
      scalar = 1.0 / (diagonal[i] - c[i - 1] * lower[i - 1]);
      c[i] = upper[i] * scalar;
      d[i] = Cartesian3.subtract(
        right[i],
        Cartesian3.multiplyByScalar(d[i - 1], lower[i - 1], d[i]),
        d[i]
      );
      d[i] = Cartesian3.multiplyByScalar(d[i], scalar, d[i]);
    }

    scalar = 1.0 / (diagonal[i] - c[i - 1] * lower[i - 1]);
    d[i] = Cartesian3.subtract(
      right[i],
      Cartesian3.multiplyByScalar(d[i - 1], lower[i - 1], d[i]),
      d[i]
    );
    d[i] = Cartesian3.multiplyByScalar(d[i], scalar, d[i]);

    x[x.length - 1] = d[d.length - 1];
    for (i = x.length - 2; i >= 0; --i) {
      x[i] = Cartesian3.subtract(
        d[i],
        Cartesian3.multiplyByScalar(x[i + 1], c[i], x[i]),
        x[i]
      );
    }

    return x;
  };

  const scratchLower = [];
  const scratchDiagonal = [];
  const scratchUpper = [];
  const scratchRight$3 = [];

  function generateClamped(points, firstTangent, lastTangent) {
    const l = scratchLower;
    const u = scratchUpper;
    const d = scratchDiagonal;
    const r = scratchRight$3;

    l.length = u.length = points.length - 1;
    d.length = r.length = points.length;

    let i;
    l[0] = d[0] = 1.0;
    u[0] = 0.0;

    let right = r[0];
    if (!defined(right)) {
      right = r[0] = new Cartesian3();
    }
    Cartesian3.clone(firstTangent, right);

    for (i = 1; i < l.length - 1; ++i) {
      l[i] = u[i] = 1.0;
      d[i] = 4.0;

      right = r[i];
      if (!defined(right)) {
        right = r[i] = new Cartesian3();
      }
      Cartesian3.subtract(points[i + 1], points[i - 1], right);
      Cartesian3.multiplyByScalar(right, 3.0, right);
    }

    l[i] = 0.0;
    u[i] = 1.0;
    d[i] = 4.0;

    right = r[i];
    if (!defined(right)) {
      right = r[i] = new Cartesian3();
    }
    Cartesian3.subtract(points[i + 1], points[i - 1], right);
    Cartesian3.multiplyByScalar(right, 3.0, right);

    d[i + 1] = 1.0;
    right = r[i + 1];
    if (!defined(right)) {
      right = r[i + 1] = new Cartesian3();
    }
    Cartesian3.clone(lastTangent, right);

    return TridiagonalSystemSolver.solve(l, d, u, r);
  }

  function generateNatural(points) {
    const l = scratchLower;
    const u = scratchUpper;
    const d = scratchDiagonal;
    const r = scratchRight$3;

    l.length = u.length = points.length - 1;
    d.length = r.length = points.length;

    let i;
    l[0] = u[0] = 1.0;
    d[0] = 2.0;

    let right = r[0];
    if (!defined(right)) {
      right = r[0] = new Cartesian3();
    }
    Cartesian3.subtract(points[1], points[0], right);
    Cartesian3.multiplyByScalar(right, 3.0, right);

    for (i = 1; i < l.length; ++i) {
      l[i] = u[i] = 1.0;
      d[i] = 4.0;

      right = r[i];
      if (!defined(right)) {
        right = r[i] = new Cartesian3();
      }
      Cartesian3.subtract(points[i + 1], points[i - 1], right);
      Cartesian3.multiplyByScalar(right, 3.0, right);
    }

    d[i] = 2.0;

    right = r[i];
    if (!defined(right)) {
      right = r[i] = new Cartesian3();
    }
    Cartesian3.subtract(points[i], points[i - 1], right);
    Cartesian3.multiplyByScalar(right, 3.0, right);

    return TridiagonalSystemSolver.solve(l, d, u, r);
  }

  /**
   * A Hermite spline is a cubic interpolating spline. Points, incoming tangents, outgoing tangents, and times
   * must be defined for each control point. The outgoing tangents are defined for points [0, n - 2] and the incoming
   * tangents are defined for points [1, n - 1]. For example, when interpolating a segment of the curve between <code>points[i]</code> and
   * <code>points[i + 1]</code>, the tangents at the points will be <code>outTangents[i]</code> and <code>inTangents[i]</code>,
   * respectively.
   *
   * @alias HermiteSpline
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Number[]} options.times An array of strictly increasing, unit-less, floating-point times at each point.
   *                The values are in no way connected to the clock time. They are the parameterization for the curve.
   * @param {Cartesian3[]} options.points The array of control points.
   * @param {Cartesian3[]} options.inTangents The array of incoming tangents at each control point.
   * @param {Cartesian3[]} options.outTangents The array of outgoing tangents at each control point.
   *
   * @exception {DeveloperError} points.length must be greater than or equal to 2.
   * @exception {DeveloperError} times.length must be equal to points.length.
   * @exception {DeveloperError} inTangents and outTangents must have a length equal to points.length - 1.
   * @exception {DeveloperError} inTangents and outTangents must be of the same type as points.
   *
   * @example
   * // Create a G<sup>1</sup> continuous Hermite spline
   * const times = [ 0.0, 1.5, 3.0, 4.5, 6.0 ];
   * const spline = new Cesium.HermiteSpline({
   *     times : times,
   *     points : [
   *         new Cesium.Cartesian3(1235398.0, -4810983.0, 4146266.0),
   *         new Cesium.Cartesian3(1372574.0, -5345182.0, 4606657.0),
   *         new Cesium.Cartesian3(-757983.0, -5542796.0, 4514323.0),
   *         new Cesium.Cartesian3(-2821260.0, -5248423.0, 4021290.0),
   *         new Cesium.Cartesian3(-2539788.0, -4724797.0, 3620093.0)
   *     ],
   *     outTangents : [
   *         new Cesium.Cartesian3(1125196, -161816, 270551),
   *         new Cesium.Cartesian3(-996690.5, -365906.5, 184028.5),
   *         new Cesium.Cartesian3(-2096917, 48379.5, -292683.5),
   *         new Cesium.Cartesian3(-890902.5, 408999.5, -447115)
   *     ],
   *     inTangents : [
   *         new Cesium.Cartesian3(-1993381, -731813, 368057),
   *         new Cesium.Cartesian3(-4193834, 96759, -585367),
   *         new Cesium.Cartesian3(-1781805, 817999, -894230),
   *         new Cesium.Cartesian3(1165345, 112641, 47281)
   *     ]
   * });
   *
   * const p0 = spline.evaluate(times[0]);
   *
   * @see ConstantSpline
   * @see SteppedSpline
   * @see LinearSpline
   * @see CatmullRomSpline
   * @see QuaternionSpline
   * @see MorphWeightSpline
   */
  function HermiteSpline(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const points = options.points;
    const times = options.times;
    const inTangents = options.inTangents;
    const outTangents = options.outTangents;

    //>>includeStart('debug', pragmas.debug);
    if (
      !defined(points) ||
      !defined(times) ||
      !defined(inTangents) ||
      !defined(outTangents)
    ) {
      throw new DeveloperError(
        "times, points, inTangents, and outTangents are required."
      );
    }
    if (points.length < 2) {
      throw new DeveloperError(
        "points.length must be greater than or equal to 2."
      );
    }
    if (times.length !== points.length) {
      throw new DeveloperError("times.length must be equal to points.length.");
    }
    if (
      inTangents.length !== outTangents.length ||
      inTangents.length !== points.length - 1
    ) {
      throw new DeveloperError(
        "inTangents and outTangents must have a length equal to points.length - 1."
      );
    }
    //>>includeEnd('debug');

    this._times = times;
    this._points = points;
    this._pointType = Spline.getPointType(points[0]);
    //>>includeStart('debug', pragmas.debug);
    if (
      this._pointType !== Spline.getPointType(inTangents[0]) ||
      this._pointType !== Spline.getPointType(outTangents[0])
    ) {
      throw new DeveloperError(
        "inTangents and outTangents must be of the same type as points."
      );
    }
    //>>includeEnd('debug');

    this._inTangents = inTangents;
    this._outTangents = outTangents;

    this._lastTimeIndex = 0;
  }

  Object.defineProperties(HermiteSpline.prototype, {
    /**
     * An array of times for the control points.
     *
     * @memberof HermiteSpline.prototype
     *
     * @type {Number[]}
     * @readonly
     */
    times: {
      get: function () {
        return this._times;
      },
    },

    /**
     * An array of control points.
     *
     * @memberof HermiteSpline.prototype
     *
     * @type {Cartesian3[]}
     * @readonly
     */
    points: {
      get: function () {
        return this._points;
      },
    },

    /**
     * An array of incoming tangents at each control point.
     *
     * @memberof HermiteSpline.prototype
     *
     * @type {Cartesian3[]}
     * @readonly
     */
    inTangents: {
      get: function () {
        return this._inTangents;
      },
    },

    /**
     * An array of outgoing tangents at each control point.
     *
     * @memberof HermiteSpline.prototype
     *
     * @type {Cartesian3[]}
     * @readonly
     */
    outTangents: {
      get: function () {
        return this._outTangents;
      },
    },
  });

  /**
   * Creates a spline where the tangents at each control point are the same.
   * The curves are guaranteed to be at least in the class C<sup>1</sup>.
   *
   * @param {Object} options Object with the following properties:
   * @param {Number[]} options.times The array of control point times.
   * @param {Cartesian3[]} options.points The array of control points.
   * @param {Cartesian3[]} options.tangents The array of tangents at the control points.
   * @returns {HermiteSpline} A hermite spline.
   *
   * @exception {DeveloperError} points, times and tangents are required.
   * @exception {DeveloperError} points.length must be greater than or equal to 2.
   * @exception {DeveloperError} times, points and tangents must have the same length.
   *
   * @example
   * const points = [
   *     new Cesium.Cartesian3(1235398.0, -4810983.0, 4146266.0),
   *     new Cesium.Cartesian3(1372574.0, -5345182.0, 4606657.0),
   *     new Cesium.Cartesian3(-757983.0, -5542796.0, 4514323.0),
   *     new Cesium.Cartesian3(-2821260.0, -5248423.0, 4021290.0),
   *     new Cesium.Cartesian3(-2539788.0, -4724797.0, 3620093.0)
   * ];
   *
   * // Add tangents
   * const tangents = new Array(points.length);
   * tangents[0] = new Cesium.Cartesian3(1125196, -161816, 270551);
   * const temp = new Cesium.Cartesian3();
   * for (let i = 1; i < tangents.length - 1; ++i) {
   *     tangents[i] = Cesium.Cartesian3.multiplyByScalar(Cesium.Cartesian3.subtract(points[i + 1], points[i - 1], temp), 0.5, new Cesium.Cartesian3());
   * }
   * tangents[tangents.length - 1] = new Cesium.Cartesian3(1165345, 112641, 47281);
   *
   * const spline = Cesium.HermiteSpline.createC1({
   *     times : times,
   *     points : points,
   *     tangents : tangents
   * });
   */
  HermiteSpline.createC1 = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const times = options.times;
    const points = options.points;
    const tangents = options.tangents;

    //>>includeStart('debug', pragmas.debug);
    if (!defined(points) || !defined(times) || !defined(tangents)) {
      throw new DeveloperError("points, times and tangents are required.");
    }
    if (points.length < 2) {
      throw new DeveloperError(
        "points.length must be greater than or equal to 2."
      );
    }
    if (times.length !== points.length || times.length !== tangents.length) {
      throw new DeveloperError(
        "times, points and tangents must have the same length."
      );
    }
    //>>includeEnd('debug');

    const outTangents = tangents.slice(0, tangents.length - 1);
    const inTangents = tangents.slice(1, tangents.length);

    return new HermiteSpline({
      times: times,
      points: points,
      inTangents: inTangents,
      outTangents: outTangents,
    });
  };

  /**
   * Creates a natural cubic spline. The tangents at the control points are generated
   * to create a curve in the class C<sup>2</sup>.
   *
   * @param {Object} options Object with the following properties:
   * @param {Number[]} options.times The array of control point times.
   * @param {Cartesian3[]} options.points The array of control points.
   * @returns {HermiteSpline|LinearSpline} A hermite spline, or a linear spline if less than 3 control points were given.
   *
   * @exception {DeveloperError} points and times are required.
   * @exception {DeveloperError} points.length must be greater than or equal to 2.
   * @exception {DeveloperError} times.length must be equal to points.length.
   *
   * @example
   * // Create a natural cubic spline above the earth from Philadelphia to Los Angeles.
   * const spline = Cesium.HermiteSpline.createNaturalCubic({
   *     times : [ 0.0, 1.5, 3.0, 4.5, 6.0 ],
   *     points : [
   *         new Cesium.Cartesian3(1235398.0, -4810983.0, 4146266.0),
   *         new Cesium.Cartesian3(1372574.0, -5345182.0, 4606657.0),
   *         new Cesium.Cartesian3(-757983.0, -5542796.0, 4514323.0),
   *         new Cesium.Cartesian3(-2821260.0, -5248423.0, 4021290.0),
   *         new Cesium.Cartesian3(-2539788.0, -4724797.0, 3620093.0)
   *     ]
   * });
   */
  HermiteSpline.createNaturalCubic = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const times = options.times;
    const points = options.points;

    //>>includeStart('debug', pragmas.debug);
    if (!defined(points) || !defined(times)) {
      throw new DeveloperError("points and times are required.");
    }
    if (points.length < 2) {
      throw new DeveloperError(
        "points.length must be greater than or equal to 2."
      );
    }
    if (times.length !== points.length) {
      throw new DeveloperError("times.length must be equal to points.length.");
    }
    //>>includeEnd('debug');

    if (points.length < 3) {
      return new LinearSpline({
        points: points,
        times: times,
      });
    }

    const tangents = generateNatural(points);
    const outTangents = tangents.slice(0, tangents.length - 1);
    const inTangents = tangents.slice(1, tangents.length);

    return new HermiteSpline({
      times: times,
      points: points,
      inTangents: inTangents,
      outTangents: outTangents,
    });
  };

  /**
   * Creates a clamped cubic spline. The tangents at the interior control points are generated
   * to create a curve in the class C<sup>2</sup>.
   *
   * @param {Object} options Object with the following properties:
   * @param {Number[]} options.times The array of control point times.
   * @param {Number[]|Cartesian3[]} options.points The array of control points.
   * @param {Cartesian3} options.firstTangent The outgoing tangent of the first control point.
   * @param {Cartesian3} options.lastTangent The incoming tangent of the last control point.
   * @returns {HermiteSpline|LinearSpline} A hermite spline, or a linear spline if less than 3 control points were given.
   *
   * @exception {DeveloperError} points, times, firstTangent and lastTangent are required.
   * @exception {DeveloperError} points.length must be greater than or equal to 2.
   * @exception {DeveloperError} times.length must be equal to points.length.
   * @exception {DeveloperError} firstTangent and lastTangent must be of the same type as points.
   *
   * @example
   * // Create a clamped cubic spline above the earth from Philadelphia to Los Angeles.
   * const spline = Cesium.HermiteSpline.createClampedCubic({
   *     times : [ 0.0, 1.5, 3.0, 4.5, 6.0 ],
   *     points : [
   *         new Cesium.Cartesian3(1235398.0, -4810983.0, 4146266.0),
   *         new Cesium.Cartesian3(1372574.0, -5345182.0, 4606657.0),
   *         new Cesium.Cartesian3(-757983.0, -5542796.0, 4514323.0),
   *         new Cesium.Cartesian3(-2821260.0, -5248423.0, 4021290.0),
   *         new Cesium.Cartesian3(-2539788.0, -4724797.0, 3620093.0)
   *     ],
   *     firstTangent : new Cesium.Cartesian3(1125196, -161816, 270551),
   *     lastTangent : new Cesium.Cartesian3(1165345, 112641, 47281)
   * });
   */
  HermiteSpline.createClampedCubic = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const times = options.times;
    const points = options.points;
    const firstTangent = options.firstTangent;
    const lastTangent = options.lastTangent;

    //>>includeStart('debug', pragmas.debug);
    if (
      !defined(points) ||
      !defined(times) ||
      !defined(firstTangent) ||
      !defined(lastTangent)
    ) {
      throw new DeveloperError(
        "points, times, firstTangent and lastTangent are required."
      );
    }
    if (points.length < 2) {
      throw new DeveloperError(
        "points.length must be greater than or equal to 2."
      );
    }
    if (times.length !== points.length) {
      throw new DeveloperError("times.length must be equal to points.length.");
    }
    //>>includeEnd('debug');

    const PointType = Spline.getPointType(points[0]);

    //>>includeStart('debug', pragmas.debug);
    if (
      PointType !== Spline.getPointType(firstTangent) ||
      PointType !== Spline.getPointType(lastTangent)
    ) {
      throw new DeveloperError(
        "firstTangent and lastTangent must be of the same type as points."
      );
    }
    //>>includeEnd('debug');

    if (points.length < 3) {
      return new LinearSpline({
        points: points,
        times: times,
      });
    }

    const tangents = generateClamped(points, firstTangent, lastTangent);
    const outTangents = tangents.slice(0, tangents.length - 1);
    const inTangents = tangents.slice(1, tangents.length);

    return new HermiteSpline({
      times: times,
      points: points,
      inTangents: inTangents,
      outTangents: outTangents,
    });
  };

  //prettier-ignore
  HermiteSpline.hermiteCoefficientMatrix = new Matrix4(
    2.0, -3.0, 0.0, 1.0,
    -2.0, 3.0, 0.0, 0.0,
    1.0, -2.0, 1.0, 0.0,
    1.0, -1.0, 0.0, 0.0
  );

  /**
   * Finds an index <code>i</code> in <code>times</code> such that the parameter
   * <code>time</code> is in the interval <code>[times[i], times[i + 1]]</code>.
   * @function
   *
   * @param {Number} time The time.
   * @returns {Number} The index for the element at the start of the interval.
   *
   * @exception {DeveloperError} time must be in the range <code>[t<sub>0</sub>, t<sub>n</sub>]</code>, where <code>t<sub>0</sub></code>
   *                             is the first element in the array <code>times</code> and <code>t<sub>n</sub></code> is the last element
   *                             in the array <code>times</code>.
   */
  HermiteSpline.prototype.findTimeInterval = Spline.prototype.findTimeInterval;

  const scratchTimeVec$1 = new Cartesian4();
  const scratchTemp = new Cartesian3();

  /**
   * Wraps the given time to the period covered by the spline.
   * @function
   *
   * @param {Number} time The time.
   * @return {Number} The time, wrapped around to the updated animation.
   */
  HermiteSpline.prototype.wrapTime = Spline.prototype.wrapTime;

  /**
   * Clamps the given time to the period covered by the spline.
   * @function
   *
   * @param {Number} time The time.
   * @return {Number} The time, clamped to the animation period.
   */
  HermiteSpline.prototype.clampTime = Spline.prototype.clampTime;

  /**
   * Evaluates the curve at a given time.
   *
   * @param {Number} time The time at which to evaluate the curve.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter or a new instance of the point on the curve at the given time.
   *
   * @exception {DeveloperError} time must be in the range <code>[t<sub>0</sub>, t<sub>n</sub>]</code>, where <code>t<sub>0</sub></code>
   *                             is the first element in the array <code>times</code> and <code>t<sub>n</sub></code> is the last element
   *                             in the array <code>times</code>.
   */
  HermiteSpline.prototype.evaluate = function (time, result) {
    const points = this.points;
    const times = this.times;
    const inTangents = this.inTangents;
    const outTangents = this.outTangents;

    this._lastTimeIndex = this.findTimeInterval(time, this._lastTimeIndex);
    const i = this._lastTimeIndex;

    const timesDelta = times[i + 1] - times[i];
    const u = (time - times[i]) / timesDelta;

    const timeVec = scratchTimeVec$1;
    timeVec.z = u;
    timeVec.y = u * u;
    timeVec.x = timeVec.y * u;
    timeVec.w = 1.0;

    // Coefficients are returned in the following order:
    // start, end, out-tangent, in-tangent
    const coefs = Matrix4.multiplyByVector(
      HermiteSpline.hermiteCoefficientMatrix,
      timeVec,
      timeVec
    );

    // Multiply the out-tangent and in-tangent values by the time delta.
    coefs.z *= timesDelta;
    coefs.w *= timesDelta;

    const PointType = this._pointType;

    if (PointType === Number) {
      return (
        points[i] * coefs.x +
        points[i + 1] * coefs.y +
        outTangents[i] * coefs.z +
        inTangents[i] * coefs.w
      );
    }

    if (!defined(result)) {
      result = new PointType();
    }

    result = PointType.multiplyByScalar(points[i], coefs.x, result);
    PointType.multiplyByScalar(points[i + 1], coefs.y, scratchTemp);
    PointType.add(result, scratchTemp, result);
    PointType.multiplyByScalar(outTangents[i], coefs.z, scratchTemp);
    PointType.add(result, scratchTemp, result);
    PointType.multiplyByScalar(inTangents[i], coefs.w, scratchTemp);
    return PointType.add(result, scratchTemp, result);
  };

  const scratchTimeVec = new Cartesian4();
  const scratchTemp0 = new Cartesian3();
  const scratchTemp1 = new Cartesian3();

  function createEvaluateFunction$1(spline) {
    const points = spline.points;
    const times = spline.times;

    if (points.length < 3) {
      const t0 = times[0];
      const invSpan = 1.0 / (times[1] - t0);

      const p0 = points[0];
      const p1 = points[1];

      return function (time, result) {
        if (!defined(result)) {
          result = new Cartesian3();
        }
        const u = (time - t0) * invSpan;
        return Cartesian3.lerp(p0, p1, u, result);
      };
    }

    return function (time, result) {
      if (!defined(result)) {
        result = new Cartesian3();
      }
      const i = (spline._lastTimeIndex = spline.findTimeInterval(
        time,
        spline._lastTimeIndex
      ));
      const u = (time - times[i]) / (times[i + 1] - times[i]);

      const timeVec = scratchTimeVec;
      timeVec.z = u;
      timeVec.y = u * u;
      timeVec.x = timeVec.y * u;
      timeVec.w = 1.0;

      let p0;
      let p1;
      let p2;
      let p3;
      let coefs;

      if (i === 0) {
        p0 = points[0];
        p1 = points[1];
        p2 = spline.firstTangent;

        p3 = Cartesian3.subtract(points[2], p0, scratchTemp0);
        Cartesian3.multiplyByScalar(p3, 0.5, p3);

        coefs = Matrix4.multiplyByVector(
          HermiteSpline.hermiteCoefficientMatrix,
          timeVec,
          timeVec
        );
      } else if (i === points.length - 2) {
        p0 = points[i];
        p1 = points[i + 1];
        p3 = spline.lastTangent;

        p2 = Cartesian3.subtract(p1, points[i - 1], scratchTemp0);
        Cartesian3.multiplyByScalar(p2, 0.5, p2);

        coefs = Matrix4.multiplyByVector(
          HermiteSpline.hermiteCoefficientMatrix,
          timeVec,
          timeVec
        );
      } else {
        p0 = points[i - 1];
        p1 = points[i];
        p2 = points[i + 1];
        p3 = points[i + 2];
        coefs = Matrix4.multiplyByVector(
          CatmullRomSpline.catmullRomCoefficientMatrix,
          timeVec,
          timeVec
        );
      }
      result = Cartesian3.multiplyByScalar(p0, coefs.x, result);
      Cartesian3.multiplyByScalar(p1, coefs.y, scratchTemp1);
      Cartesian3.add(result, scratchTemp1, result);
      Cartesian3.multiplyByScalar(p2, coefs.z, scratchTemp1);
      Cartesian3.add(result, scratchTemp1, result);
      Cartesian3.multiplyByScalar(p3, coefs.w, scratchTemp1);
      return Cartesian3.add(result, scratchTemp1, result);
    };
  }

  const firstTangentScratch = new Cartesian3();
  const lastTangentScratch = new Cartesian3();

  /**
   * A Catmull-Rom spline is a cubic spline where the tangent at control points,
   * except the first and last, are computed using the previous and next control points.
   * Catmull-Rom splines are in the class C<sup>1</sup>.
   *
   * @alias CatmullRomSpline
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Number[]} options.times An array of strictly increasing, unit-less, floating-point times at each point.
   *                The values are in no way connected to the clock time. They are the parameterization for the curve.
   * @param {Cartesian3[]} options.points The array of {@link Cartesian3} control points.
   * @param {Cartesian3} [options.firstTangent] The tangent of the curve at the first control point.
   *                     If the tangent is not given, it will be estimated.
   * @param {Cartesian3} [options.lastTangent] The tangent of the curve at the last control point.
   *                     If the tangent is not given, it will be estimated.
   *
   * @exception {DeveloperError} points.length must be greater than or equal to 2.
   * @exception {DeveloperError} times.length must be equal to points.length.
   *
   *
   * @example
   * // spline above the earth from Philadelphia to Los Angeles
   * const spline = new Cesium.CatmullRomSpline({
   *     times : [ 0.0, 1.5, 3.0, 4.5, 6.0 ],
   *     points : [
   *         new Cesium.Cartesian3(1235398.0, -4810983.0, 4146266.0),
   *         new Cesium.Cartesian3(1372574.0, -5345182.0, 4606657.0),
   *         new Cesium.Cartesian3(-757983.0, -5542796.0, 4514323.0),
   *         new Cesium.Cartesian3(-2821260.0, -5248423.0, 4021290.0),
   *         new Cesium.Cartesian3(-2539788.0, -4724797.0, 3620093.0)
   *     ]
   * });
   *
   * const p0 = spline.evaluate(times[i]);         // equal to positions[i]
   * const p1 = spline.evaluate(times[i] + delta); // interpolated value when delta < times[i + 1] - times[i]
   *
   * @see ConstantSpline
   * @see SteppedSpline
   * @see HermiteSpline
   * @see LinearSpline
   * @see QuaternionSpline
   * @see MorphWeightSpline
   */
  function CatmullRomSpline(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const points = options.points;
    const times = options.times;
    let firstTangent = options.firstTangent;
    let lastTangent = options.lastTangent;

    //>>includeStart('debug', pragmas.debug);
    Check.defined("points", points);
    Check.defined("times", times);
    Check.typeOf.number.greaterThanOrEquals("points.length", points.length, 2);
    Check.typeOf.number.equals(
      "times.length",
      "points.length",
      times.length,
      points.length
    );
    //>>includeEnd('debug');

    if (points.length > 2) {
      if (!defined(firstTangent)) {
        firstTangent = firstTangentScratch;
        Cartesian3.multiplyByScalar(points[1], 2.0, firstTangent);
        Cartesian3.subtract(firstTangent, points[2], firstTangent);
        Cartesian3.subtract(firstTangent, points[0], firstTangent);
        Cartesian3.multiplyByScalar(firstTangent, 0.5, firstTangent);
      }

      if (!defined(lastTangent)) {
        const n = points.length - 1;
        lastTangent = lastTangentScratch;
        Cartesian3.multiplyByScalar(points[n - 1], 2.0, lastTangent);
        Cartesian3.subtract(points[n], lastTangent, lastTangent);
        Cartesian3.add(lastTangent, points[n - 2], lastTangent);
        Cartesian3.multiplyByScalar(lastTangent, 0.5, lastTangent);
      }
    }

    this._times = times;
    this._points = points;
    this._firstTangent = Cartesian3.clone(firstTangent);
    this._lastTangent = Cartesian3.clone(lastTangent);

    this._evaluateFunction = createEvaluateFunction$1(this);
    this._lastTimeIndex = 0;
  }

  Object.defineProperties(CatmullRomSpline.prototype, {
    /**
     * An array of times for the control points.
     *
     * @memberof CatmullRomSpline.prototype
     *
     * @type {Number[]}
     * @readonly
     */
    times: {
      get: function () {
        return this._times;
      },
    },

    /**
     * An array of {@link Cartesian3} control points.
     *
     * @memberof CatmullRomSpline.prototype
     *
     * @type {Cartesian3[]}
     * @readonly
     */
    points: {
      get: function () {
        return this._points;
      },
    },

    /**
     * The tangent at the first control point.
     *
     * @memberof CatmullRomSpline.prototype
     *
     * @type {Cartesian3}
     * @readonly
     */
    firstTangent: {
      get: function () {
        return this._firstTangent;
      },
    },

    /**
     * The tangent at the last control point.
     *
     * @memberof CatmullRomSpline.prototype
     *
     * @type {Cartesian3}
     * @readonly
     */
    lastTangent: {
      get: function () {
        return this._lastTangent;
      },
    },
  });

  /**
   * @private
   */
  CatmullRomSpline.catmullRomCoefficientMatrix = new Matrix4(
    -0.5,
    1.0,
    -0.5,
    0.0,
    1.5,
    -2.5,
    0.0,
    1.0,
    -1.5,
    2.0,
    0.5,
    0.0,
    0.5,
    -0.5,
    0.0,
    0.0
  );

  /**
   * Finds an index <code>i</code> in <code>times</code> such that the parameter
   * <code>time</code> is in the interval <code>[times[i], times[i + 1]]</code>.
   * @function
   *
   * @param {Number} time The time.
   * @returns {Number} The index for the element at the start of the interval.
   *
   * @exception {DeveloperError} time must be in the range <code>[t<sub>0</sub>, t<sub>n</sub>]</code>, where <code>t<sub>0</sub></code>
   *                             is the first element in the array <code>times</code> and <code>t<sub>n</sub></code> is the last element
   *                             in the array <code>times</code>.
   */
  CatmullRomSpline.prototype.findTimeInterval = Spline.prototype.findTimeInterval;

  /**
   * Wraps the given time to the period covered by the spline.
   * @function
   *
   * @param {Number} time The time.
   * @return {Number} The time, wrapped around to the updated animation.
   */
  CatmullRomSpline.prototype.wrapTime = Spline.prototype.wrapTime;

  /**
   * Clamps the given time to the period covered by the spline.
   * @function
   *
   * @param {Number} time The time.
   * @return {Number} The time, clamped to the animation period.
   */
  CatmullRomSpline.prototype.clampTime = Spline.prototype.clampTime;

  /**
   * Evaluates the curve at a given time.
   *
   * @param {Number} time The time at which to evaluate the curve.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter or a new instance of the point on the curve at the given time.
   *
   * @exception {DeveloperError} time must be in the range <code>[t<sub>0</sub>, t<sub>n</sub>]</code>, where <code>t<sub>0</sub></code>
   *                             is the first element in the array <code>times</code> and <code>t<sub>n</sub></code> is the last element
   *                             in the array <code>times</code>.
   */
  CatmullRomSpline.prototype.evaluate = function (time, result) {
    return this._evaluateFunction(time, result);
  };

  /**
   * Reads a string from a Uint8Array.
   *
   * @function
   *
   * @param {Uint8Array} uint8Array The Uint8Array to read from.
   * @param {Number} [byteOffset=0] The byte offset to start reading from.
   * @param {Number} [byteLength] The byte length to read. If byteLength is omitted the remainder of the buffer is read.
   * @returns {String} The string.
   *
   * @private
   */
  function getStringFromTypedArray(uint8Array, byteOffset, byteLength) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(uint8Array)) {
      throw new DeveloperError("uint8Array is required.");
    }
    if (byteOffset < 0) {
      throw new DeveloperError("byteOffset cannot be negative.");
    }
    if (byteLength < 0) {
      throw new DeveloperError("byteLength cannot be negative.");
    }
    if (byteOffset + byteLength > uint8Array.byteLength) {
      throw new DeveloperError("sub-region exceeds array bounds.");
    }
    //>>includeEnd('debug');

    byteOffset = defaultValue(byteOffset, 0);
    byteLength = defaultValue(byteLength, uint8Array.byteLength - byteOffset);

    uint8Array = uint8Array.subarray(byteOffset, byteOffset + byteLength);

    return getStringFromTypedArray.decode(uint8Array);
  }

  // Exposed functions for testing
  getStringFromTypedArray.decodeWithTextDecoder = function (view) {
    const decoder = new TextDecoder("utf-8");
    return decoder.decode(view);
  };

  getStringFromTypedArray.decodeWithFromCharCode = function (view) {
    let result = "";
    const codePoints = utf8Handler(view);
    const length = codePoints.length;
    for (let i = 0; i < length; ++i) {
      let cp = codePoints[i];
      if (cp <= 0xffff) {
        result += String.fromCharCode(cp);
      } else {
        cp -= 0x10000;
        result += String.fromCharCode((cp >> 10) + 0xd800, (cp & 0x3ff) + 0xdc00);
      }
    }
    return result;
  };

  function inRange(a, min, max) {
    return min <= a && a <= max;
  }

  // This code is inspired by public domain code found here: https://github.com/inexorabletash/text-encoding
  function utf8Handler(utfBytes) {
    let codePoint = 0;
    let bytesSeen = 0;
    let bytesNeeded = 0;
    let lowerBoundary = 0x80;
    let upperBoundary = 0xbf;

    const codePoints = [];
    const length = utfBytes.length;
    for (let i = 0; i < length; ++i) {
      const currentByte = utfBytes[i];

      // If bytesNeeded = 0, then we are starting a new character
      if (bytesNeeded === 0) {
        // 1 Byte Ascii character
        if (inRange(currentByte, 0x00, 0x7f)) {
          // Return a code point whose value is byte.
          codePoints.push(currentByte);
          continue;
        }

        // 2 Byte character
        if (inRange(currentByte, 0xc2, 0xdf)) {
          bytesNeeded = 1;
          codePoint = currentByte & 0x1f;
          continue;
        }

        // 3 Byte character
        if (inRange(currentByte, 0xe0, 0xef)) {
          // If byte is 0xE0, set utf-8 lower boundary to 0xA0.
          if (currentByte === 0xe0) {
            lowerBoundary = 0xa0;
          }
          // If byte is 0xED, set utf-8 upper boundary to 0x9F.
          if (currentByte === 0xed) {
            upperBoundary = 0x9f;
          }

          bytesNeeded = 2;
          codePoint = currentByte & 0xf;
          continue;
        }

        // 4 Byte character
        if (inRange(currentByte, 0xf0, 0xf4)) {
          // If byte is 0xF0, set utf-8 lower boundary to 0x90.
          if (currentByte === 0xf0) {
            lowerBoundary = 0x90;
          }
          // If byte is 0xF4, set utf-8 upper boundary to 0x8F.
          if (currentByte === 0xf4) {
            upperBoundary = 0x8f;
          }

          bytesNeeded = 3;
          codePoint = currentByte & 0x7;
          continue;
        }

        throw new RuntimeError("String decoding failed.");
      }

      // Out of range, so ignore the first part(s) of the character and continue with this byte on its own
      if (!inRange(currentByte, lowerBoundary, upperBoundary)) {
        codePoint = bytesNeeded = bytesSeen = 0;
        lowerBoundary = 0x80;
        upperBoundary = 0xbf;
        --i;
        continue;
      }

      // Set appropriate boundaries, since we've now checked byte 2 of a potential longer character
      lowerBoundary = 0x80;
      upperBoundary = 0xbf;

      // Add byte to code point
      codePoint = (codePoint << 6) | (currentByte & 0x3f);

      // We have the correct number of bytes, so push and reset for next character
      ++bytesSeen;
      if (bytesSeen === bytesNeeded) {
        codePoints.push(codePoint);
        codePoint = bytesNeeded = bytesSeen = 0;
      }
    }

    return codePoints;
  }

  if (typeof TextDecoder !== "undefined") {
    getStringFromTypedArray.decode =
      getStringFromTypedArray.decodeWithTextDecoder;
  } else {
    getStringFromTypedArray.decode =
      getStringFromTypedArray.decodeWithFromCharCode;
  }

  /**
   * Parses JSON from a Uint8Array.
   *
   * @function
   *
   * @param {Uint8Array} uint8Array The Uint8Array to read from.
   * @param {Number} [byteOffset=0] The byte offset to start reading from.
   * @param {Number} [byteLength] The byte length to read. If byteLength is omitted the remainder of the buffer is read.
   * @returns {Object} An object containing the parsed JSON.
   *
   * @private
   */
  function getJsonFromTypedArray(uint8Array, byteOffset, byteLength) {
    return JSON.parse(
      getStringFromTypedArray(uint8Array, byteOffset, byteLength)
    );
  }

  /**
   * Contains functions for operating on 2D triangles.
   *
   * @namespace Intersections2D
   */
  const Intersections2D = {};

  /**
   * Splits a 2D triangle at given axis-aligned threshold value and returns the resulting
   * polygon on a given side of the threshold.  The resulting polygon may have 0, 1, 2,
   * 3, or 4 vertices.
   *
   * @param {Number} threshold The threshold coordinate value at which to clip the triangle.
   * @param {Boolean} keepAbove true to keep the portion of the triangle above the threshold, or false
   *                            to keep the portion below.
   * @param {Number} u0 The coordinate of the first vertex in the triangle, in counter-clockwise order.
   * @param {Number} u1 The coordinate of the second vertex in the triangle, in counter-clockwise order.
   * @param {Number} u2 The coordinate of the third vertex in the triangle, in counter-clockwise order.
   * @param {Number[]} [result] The array into which to copy the result.  If this parameter is not supplied,
   *                            a new array is constructed and returned.
   * @returns {Number[]} The polygon that results after the clip, specified as a list of
   *                     vertices.  The vertices are specified in counter-clockwise order.
   *                     Each vertex is either an index from the existing list (identified as
   *                     a 0, 1, or 2) or -1 indicating a new vertex not in the original triangle.
   *                     For new vertices, the -1 is followed by three additional numbers: the
   *                     index of each of the two original vertices forming the line segment that
   *                     the new vertex lies on, and the fraction of the distance from the first
   *                     vertex to the second one.
   *
   * @example
   * const result = Cesium.Intersections2D.clipTriangleAtAxisAlignedThreshold(0.5, false, 0.2, 0.6, 0.4);
   * // result === [2, 0, -1, 1, 0, 0.25, -1, 1, 2, 0.5]
   */
  Intersections2D.clipTriangleAtAxisAlignedThreshold = function (
    threshold,
    keepAbove,
    u0,
    u1,
    u2,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(threshold)) {
      throw new DeveloperError("threshold is required.");
    }
    if (!defined(keepAbove)) {
      throw new DeveloperError("keepAbove is required.");
    }
    if (!defined(u0)) {
      throw new DeveloperError("u0 is required.");
    }
    if (!defined(u1)) {
      throw new DeveloperError("u1 is required.");
    }
    if (!defined(u2)) {
      throw new DeveloperError("u2 is required.");
    }
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = [];
    } else {
      result.length = 0;
    }

    let u0Behind;
    let u1Behind;
    let u2Behind;
    if (keepAbove) {
      u0Behind = u0 < threshold;
      u1Behind = u1 < threshold;
      u2Behind = u2 < threshold;
    } else {
      u0Behind = u0 > threshold;
      u1Behind = u1 > threshold;
      u2Behind = u2 > threshold;
    }

    const numBehind = u0Behind + u1Behind + u2Behind;

    let u01Ratio;
    let u02Ratio;
    let u12Ratio;
    let u10Ratio;
    let u20Ratio;
    let u21Ratio;

    if (numBehind === 1) {
      if (u0Behind) {
        u01Ratio = (threshold - u0) / (u1 - u0);
        u02Ratio = (threshold - u0) / (u2 - u0);

        result.push(1);

        result.push(2);

        if (u02Ratio !== 1.0) {
          result.push(-1);
          result.push(0);
          result.push(2);
          result.push(u02Ratio);
        }

        if (u01Ratio !== 1.0) {
          result.push(-1);
          result.push(0);
          result.push(1);
          result.push(u01Ratio);
        }
      } else if (u1Behind) {
        u12Ratio = (threshold - u1) / (u2 - u1);
        u10Ratio = (threshold - u1) / (u0 - u1);

        result.push(2);

        result.push(0);

        if (u10Ratio !== 1.0) {
          result.push(-1);
          result.push(1);
          result.push(0);
          result.push(u10Ratio);
        }

        if (u12Ratio !== 1.0) {
          result.push(-1);
          result.push(1);
          result.push(2);
          result.push(u12Ratio);
        }
      } else if (u2Behind) {
        u20Ratio = (threshold - u2) / (u0 - u2);
        u21Ratio = (threshold - u2) / (u1 - u2);

        result.push(0);

        result.push(1);

        if (u21Ratio !== 1.0) {
          result.push(-1);
          result.push(2);
          result.push(1);
          result.push(u21Ratio);
        }

        if (u20Ratio !== 1.0) {
          result.push(-1);
          result.push(2);
          result.push(0);
          result.push(u20Ratio);
        }
      }
    } else if (numBehind === 2) {
      if (!u0Behind && u0 !== threshold) {
        u10Ratio = (threshold - u1) / (u0 - u1);
        u20Ratio = (threshold - u2) / (u0 - u2);

        result.push(0);

        result.push(-1);
        result.push(1);
        result.push(0);
        result.push(u10Ratio);

        result.push(-1);
        result.push(2);
        result.push(0);
        result.push(u20Ratio);
      } else if (!u1Behind && u1 !== threshold) {
        u21Ratio = (threshold - u2) / (u1 - u2);
        u01Ratio = (threshold - u0) / (u1 - u0);

        result.push(1);

        result.push(-1);
        result.push(2);
        result.push(1);
        result.push(u21Ratio);

        result.push(-1);
        result.push(0);
        result.push(1);
        result.push(u01Ratio);
      } else if (!u2Behind && u2 !== threshold) {
        u02Ratio = (threshold - u0) / (u2 - u0);
        u12Ratio = (threshold - u1) / (u2 - u1);

        result.push(2);

        result.push(-1);
        result.push(0);
        result.push(2);
        result.push(u02Ratio);

        result.push(-1);
        result.push(1);
        result.push(2);
        result.push(u12Ratio);
      }
    } else if (numBehind !== 3) {
      // Completely in front of threshold
      result.push(0);
      result.push(1);
      result.push(2);
    }
    // else Completely behind threshold

    return result;
  };

  /**
   * Compute the barycentric coordinates of a 2D position within a 2D triangle.
   *
   * @param {Number} x The x coordinate of the position for which to find the barycentric coordinates.
   * @param {Number} y The y coordinate of the position for which to find the barycentric coordinates.
   * @param {Number} x1 The x coordinate of the triangle's first vertex.
   * @param {Number} y1 The y coordinate of the triangle's first vertex.
   * @param {Number} x2 The x coordinate of the triangle's second vertex.
   * @param {Number} y2 The y coordinate of the triangle's second vertex.
   * @param {Number} x3 The x coordinate of the triangle's third vertex.
   * @param {Number} y3 The y coordinate of the triangle's third vertex.
   * @param {Cartesian3} [result] The instance into to which to copy the result.  If this parameter
   *                     is undefined, a new instance is created and returned.
   * @returns {Cartesian3} The barycentric coordinates of the position within the triangle.
   *
   * @example
   * const result = Cesium.Intersections2D.computeBarycentricCoordinates(0.0, 0.0, 0.0, 1.0, -1, -0.5, 1, -0.5);
   * // result === new Cesium.Cartesian3(1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0);
   */
  Intersections2D.computeBarycentricCoordinates = function (
    x,
    y,
    x1,
    y1,
    x2,
    y2,
    x3,
    y3,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(x)) {
      throw new DeveloperError("x is required.");
    }
    if (!defined(y)) {
      throw new DeveloperError("y is required.");
    }
    if (!defined(x1)) {
      throw new DeveloperError("x1 is required.");
    }
    if (!defined(y1)) {
      throw new DeveloperError("y1 is required.");
    }
    if (!defined(x2)) {
      throw new DeveloperError("x2 is required.");
    }
    if (!defined(y2)) {
      throw new DeveloperError("y2 is required.");
    }
    if (!defined(x3)) {
      throw new DeveloperError("x3 is required.");
    }
    if (!defined(y3)) {
      throw new DeveloperError("y3 is required.");
    }
    //>>includeEnd('debug');

    const x1mx3 = x1 - x3;
    const x3mx2 = x3 - x2;
    const y2my3 = y2 - y3;
    const y1my3 = y1 - y3;
    const inverseDeterminant = 1.0 / (y2my3 * x1mx3 + x3mx2 * y1my3);
    const ymy3 = y - y3;
    const xmx3 = x - x3;
    const l1 = (y2my3 * xmx3 + x3mx2 * ymy3) * inverseDeterminant;
    const l2 = (-y1my3 * xmx3 + x1mx3 * ymy3) * inverseDeterminant;
    const l3 = 1.0 - l1 - l2;

    if (defined(result)) {
      result.x = l1;
      result.y = l2;
      result.z = l3;
      return result;
    }
    return new Cartesian3(l1, l2, l3);
  };

  /**
   * Compute the intersection between 2 line segments
   *
   * @param {Number} x00 The x coordinate of the first line's first vertex.
   * @param {Number} y00 The y coordinate of the first line's first vertex.
   * @param {Number} x01 The x coordinate of the first line's second vertex.
   * @param {Number} y01 The y coordinate of the first line's second vertex.
   * @param {Number} x10 The x coordinate of the second line's first vertex.
   * @param {Number} y10 The y coordinate of the second line's first vertex.
   * @param {Number} x11 The x coordinate of the second line's second vertex.
   * @param {Number} y11 The y coordinate of the second line's second vertex.
   * @param {Cartesian2} [result] The instance into to which to copy the result. If this parameter
   *                     is undefined, a new instance is created and returned.
   * @returns {Cartesian2} The intersection point, undefined if there is no intersection point or lines are coincident.
   *
   * @example
   * const result = Cesium.Intersections2D.computeLineSegmentLineSegmentIntersection(0.0, 0.0, 0.0, 2.0, -1, 1, 1, 1);
   * // result === new Cesium.Cartesian2(0.0, 1.0);
   */
  Intersections2D.computeLineSegmentLineSegmentIntersection = function (
    x00,
    y00,
    x01,
    y01,
    x10,
    y10,
    x11,
    y11,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("x00", x00);
    Check.typeOf.number("y00", y00);
    Check.typeOf.number("x01", x01);
    Check.typeOf.number("y01", y01);
    Check.typeOf.number("x10", x10);
    Check.typeOf.number("y10", y10);
    Check.typeOf.number("x11", x11);
    Check.typeOf.number("y11", y11);
    //>>includeEnd('debug');

    const numerator1A = (x11 - x10) * (y00 - y10) - (y11 - y10) * (x00 - x10);
    const numerator1B = (x01 - x00) * (y00 - y10) - (y01 - y00) * (x00 - x10);
    const denominator1 = (y11 - y10) * (x01 - x00) - (x11 - x10) * (y01 - y00);

    // If denominator = 0, then lines are parallel. If denominator = 0 and both numerators are 0, then coincident
    if (denominator1 === 0) {
      return;
    }

    const ua1 = numerator1A / denominator1;
    const ub1 = numerator1B / denominator1;

    if (ua1 >= 0 && ua1 <= 1 && ub1 >= 0 && ub1 <= 1) {
      if (!defined(result)) {
        result = new Cartesian2();
      }

      result.x = x00 + ua1 * (x01 - x00);
      result.y = y00 + ua1 * (y01 - y00);

      return result;
    }
  };

  /**
   * Terrain data for a single tile where the terrain data is represented as a quantized mesh.  A quantized
   * mesh consists of three vertex attributes, longitude, latitude, and height.  All attributes are expressed
   * as 16-bit values in the range 0 to 32767.  Longitude and latitude are zero at the southwest corner
   * of the tile and 32767 at the northeast corner.  Height is zero at the minimum height in the tile
   * and 32767 at the maximum height in the tile.
   *
   * @alias QuantizedMeshTerrainData
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Uint16Array} options.quantizedVertices The buffer containing the quantized mesh.
   * @param {Uint16Array|Uint32Array} options.indices The indices specifying how the quantized vertices are linked
   *                      together into triangles.  Each three indices specifies one triangle.
   * @param {Number} options.minimumHeight The minimum terrain height within the tile, in meters above the ellipsoid.
   * @param {Number} options.maximumHeight The maximum terrain height within the tile, in meters above the ellipsoid.
   * @param {BoundingSphere} options.boundingSphere A sphere bounding all of the vertices in the mesh.
   * @param {OrientedBoundingBox} [options.orientedBoundingBox] An OrientedBoundingBox bounding all of the vertices in the mesh.
   * @param {Cartesian3} options.horizonOcclusionPoint The horizon occlusion point of the mesh.  If this point
   *                      is below the horizon, the entire tile is assumed to be below the horizon as well.
   *                      The point is expressed in ellipsoid-scaled coordinates.
   * @param {Number[]} options.westIndices The indices of the vertices on the western edge of the tile.
   * @param {Number[]} options.southIndices The indices of the vertices on the southern edge of the tile.
   * @param {Number[]} options.eastIndices The indices of the vertices on the eastern edge of the tile.
   * @param {Number[]} options.northIndices The indices of the vertices on the northern edge of the tile.
   * @param {Number} options.westSkirtHeight The height of the skirt to add on the western edge of the tile.
   * @param {Number} options.southSkirtHeight The height of the skirt to add on the southern edge of the tile.
   * @param {Number} options.eastSkirtHeight The height of the skirt to add on the eastern edge of the tile.
   * @param {Number} options.northSkirtHeight The height of the skirt to add on the northern edge of the tile.
   * @param {Number} [options.childTileMask=15] A bit mask indicating which of this tile's four children exist.
   *                 If a child's bit is set, geometry will be requested for that tile as well when it
   *                 is needed.  If the bit is cleared, the child tile is not requested and geometry is
   *                 instead upsampled from the parent.  The bit values are as follows:
   *                 <table>
   *                  <tr><th>Bit Position</th><th>Bit Value</th><th>Child Tile</th></tr>
   *                  <tr><td>0</td><td>1</td><td>Southwest</td></tr>
   *                  <tr><td>1</td><td>2</td><td>Southeast</td></tr>
   *                  <tr><td>2</td><td>4</td><td>Northwest</td></tr>
   *                  <tr><td>3</td><td>8</td><td>Northeast</td></tr>
   *                 </table>
   * @param {Boolean} [options.createdByUpsampling=false] True if this instance was created by upsampling another instance;
   *                  otherwise, false.
   * @param {Uint8Array} [options.encodedNormals] The buffer containing per vertex normals, encoded using 'oct' encoding
   * @param {Uint8Array} [options.waterMask] The buffer containing the watermask.
   * @param {Credit[]} [options.credits] Array of credits for this tile.
   *
   *
   * @example
   * const data = new Cesium.QuantizedMeshTerrainData({
   *     minimumHeight : -100,
   *     maximumHeight : 2101,
   *     quantizedVertices : new Uint16Array([// order is SW NW SE NE
   *                                          // longitude
   *                                          0, 0, 32767, 32767,
   *                                          // latitude
   *                                          0, 32767, 0, 32767,
   *                                          // heights
   *                                          16384, 0, 32767, 16384]),
   *     indices : new Uint16Array([0, 3, 1,
   *                                0, 2, 3]),
   *     boundingSphere : new Cesium.BoundingSphere(new Cesium.Cartesian3(1.0, 2.0, 3.0), 10000),
   *     orientedBoundingBox : new Cesium.OrientedBoundingBox(new Cesium.Cartesian3(1.0, 2.0, 3.0), Cesium.Matrix3.fromRotationX(Cesium.Math.PI, new Cesium.Matrix3())),
   *     horizonOcclusionPoint : new Cesium.Cartesian3(3.0, 2.0, 1.0),
   *     westIndices : [0, 1],
   *     southIndices : [0, 1],
   *     eastIndices : [2, 3],
   *     northIndices : [1, 3],
   *     westSkirtHeight : 1.0,
   *     southSkirtHeight : 1.0,
   *     eastSkirtHeight : 1.0,
   *     northSkirtHeight : 1.0
   * });
   *
   * @see TerrainData
   * @see HeightmapTerrainData
   * @see GoogleEarthEnterpriseTerrainData
   */
  function QuantizedMeshTerrainData(options) {
    //>>includeStart('debug', pragmas.debug)
    if (!defined(options) || !defined(options.quantizedVertices)) {
      throw new DeveloperError("options.quantizedVertices is required.");
    }
    if (!defined(options.indices)) {
      throw new DeveloperError("options.indices is required.");
    }
    if (!defined(options.minimumHeight)) {
      throw new DeveloperError("options.minimumHeight is required.");
    }
    if (!defined(options.maximumHeight)) {
      throw new DeveloperError("options.maximumHeight is required.");
    }
    if (!defined(options.maximumHeight)) {
      throw new DeveloperError("options.maximumHeight is required.");
    }
    if (!defined(options.boundingSphere)) {
      throw new DeveloperError("options.boundingSphere is required.");
    }
    if (!defined(options.horizonOcclusionPoint)) {
      throw new DeveloperError("options.horizonOcclusionPoint is required.");
    }
    if (!defined(options.westIndices)) {
      throw new DeveloperError("options.westIndices is required.");
    }
    if (!defined(options.southIndices)) {
      throw new DeveloperError("options.southIndices is required.");
    }
    if (!defined(options.eastIndices)) {
      throw new DeveloperError("options.eastIndices is required.");
    }
    if (!defined(options.northIndices)) {
      throw new DeveloperError("options.northIndices is required.");
    }
    if (!defined(options.westSkirtHeight)) {
      throw new DeveloperError("options.westSkirtHeight is required.");
    }
    if (!defined(options.southSkirtHeight)) {
      throw new DeveloperError("options.southSkirtHeight is required.");
    }
    if (!defined(options.eastSkirtHeight)) {
      throw new DeveloperError("options.eastSkirtHeight is required.");
    }
    if (!defined(options.northSkirtHeight)) {
      throw new DeveloperError("options.northSkirtHeight is required.");
    }
    //>>includeEnd('debug');

    this._quantizedVertices = options.quantizedVertices;
    this._encodedNormals = options.encodedNormals;
    this._indices = options.indices;
    this._minimumHeight = options.minimumHeight;
    this._maximumHeight = options.maximumHeight;
    this._boundingSphere = options.boundingSphere;
    this._orientedBoundingBox = options.orientedBoundingBox;
    this._horizonOcclusionPoint = options.horizonOcclusionPoint;
    this._credits = options.credits;

    const vertexCount = this._quantizedVertices.length / 3;
    const uValues = (this._uValues = this._quantizedVertices.subarray(
      0,
      vertexCount
    ));
    const vValues = (this._vValues = this._quantizedVertices.subarray(
      vertexCount,
      2 * vertexCount
    ));
    this._heightValues = this._quantizedVertices.subarray(
      2 * vertexCount,
      3 * vertexCount
    );

    // We don't assume that we can count on the edge vertices being sorted by u or v.
    function sortByV(a, b) {
      return vValues[a] - vValues[b];
    }

    function sortByU(a, b) {
      return uValues[a] - uValues[b];
    }

    this._westIndices = sortIndicesIfNecessary(
      options.westIndices,
      sortByV,
      vertexCount
    );
    this._southIndices = sortIndicesIfNecessary(
      options.southIndices,
      sortByU,
      vertexCount
    );
    this._eastIndices = sortIndicesIfNecessary(
      options.eastIndices,
      sortByV,
      vertexCount
    );
    this._northIndices = sortIndicesIfNecessary(
      options.northIndices,
      sortByU,
      vertexCount
    );

    this._westSkirtHeight = options.westSkirtHeight;
    this._southSkirtHeight = options.southSkirtHeight;
    this._eastSkirtHeight = options.eastSkirtHeight;
    this._northSkirtHeight = options.northSkirtHeight;

    this._childTileMask = defaultValue(options.childTileMask, 15);

    this._createdByUpsampling = defaultValue(options.createdByUpsampling, false);
    this._waterMask = options.waterMask;

    this._mesh = undefined;
  }

  Object.defineProperties(QuantizedMeshTerrainData.prototype, {
    /**
     * An array of credits for this tile.
     * @memberof QuantizedMeshTerrainData.prototype
     * @type {Credit[]}
     */
    credits: {
      get: function () {
        return this._credits;
      },
    },
    /**
     * The water mask included in this terrain data, if any.  A water mask is a rectangular
     * Uint8Array or image where a value of 255 indicates water and a value of 0 indicates land.
     * Values in between 0 and 255 are allowed as well to smoothly blend between land and water.
     * @memberof QuantizedMeshTerrainData.prototype
     * @type {Uint8Array|HTMLImageElement|HTMLCanvasElement}
     */
    waterMask: {
      get: function () {
        return this._waterMask;
      },
    },

    childTileMask: {
      get: function () {
        return this._childTileMask;
      },
    },

    canUpsample: {
      get: function () {
        return defined(this._mesh);
      },
    },
  });

  const arrayScratch$1 = [];

  function sortIndicesIfNecessary(indices, sortFunction, vertexCount) {
    arrayScratch$1.length = indices.length;

    let needsSort = false;
    for (let i = 0, len = indices.length; i < len; ++i) {
      arrayScratch$1[i] = indices[i];
      needsSort =
        needsSort || (i > 0 && sortFunction(indices[i - 1], indices[i]) > 0);
    }

    if (needsSort) {
      arrayScratch$1.sort(sortFunction);
      return IndexDatatype$1.createTypedArray(vertexCount, arrayScratch$1);
    }
    return indices;
  }

  const createMeshTaskName$1 = "createVerticesFromQuantizedTerrainMesh";
  const createMeshTaskProcessorNoThrottle$1 = new TaskProcessor(createMeshTaskName$1);
  const createMeshTaskProcessorThrottle$1 = new TaskProcessor(
    createMeshTaskName$1,
    TerrainData.maximumAsynchronousTasks
  );

  /**
   * Creates a {@link TerrainMesh} from this terrain data.
   *
   * @private
   *
   * @param {Object} options Object with the following properties:
   * @param {TilingScheme} options.tilingScheme The tiling scheme to which this tile belongs.
   * @param {Number} options.x The X coordinate of the tile for which to create the terrain data.
   * @param {Number} options.y The Y coordinate of the tile for which to create the terrain data.
   * @param {Number} options.level The level of the tile for which to create the terrain data.
   * @param {Number} [options.exaggeration=1.0] The scale used to exaggerate the terrain.
   * @param {Number} [options.exaggerationRelativeHeight=0.0] The height relative to which terrain is exaggerated.
   * @param {Boolean} [options.throttle=true] If true, indicates that this operation will need to be retried if too many asynchronous mesh creations are already in progress.
   * @returns {Promise.<TerrainMesh>|undefined} A promise for the terrain mesh, or undefined if too many
   *          asynchronous mesh creations are already in progress and the operation should
   *          be retried later.
   */
  QuantizedMeshTerrainData.prototype.createMesh = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.tilingScheme", options.tilingScheme);
    Check.typeOf.number("options.x", options.x);
    Check.typeOf.number("options.y", options.y);
    Check.typeOf.number("options.level", options.level);
    //>>includeEnd('debug');

    const tilingScheme = options.tilingScheme;
    const x = options.x;
    const y = options.y;
    const level = options.level;
    const exaggeration = defaultValue(options.exaggeration, 1.0);
    const exaggerationRelativeHeight = defaultValue(
      options.exaggerationRelativeHeight,
      0.0
    );
    const throttle = defaultValue(options.throttle, true);

    const ellipsoid = tilingScheme.ellipsoid;
    const rectangle = tilingScheme.tileXYToRectangle(x, y, level);

    const createMeshTaskProcessor = throttle
      ? createMeshTaskProcessorThrottle$1
      : createMeshTaskProcessorNoThrottle$1;

    const verticesPromise = createMeshTaskProcessor.scheduleTask({
      minimumHeight: this._minimumHeight,
      maximumHeight: this._maximumHeight,
      quantizedVertices: this._quantizedVertices,
      octEncodedNormals: this._encodedNormals,
      includeWebMercatorT: true,
      indices: this._indices,
      westIndices: this._westIndices,
      southIndices: this._southIndices,
      eastIndices: this._eastIndices,
      northIndices: this._northIndices,
      westSkirtHeight: this._westSkirtHeight,
      southSkirtHeight: this._southSkirtHeight,
      eastSkirtHeight: this._eastSkirtHeight,
      northSkirtHeight: this._northSkirtHeight,
      rectangle: rectangle,
      relativeToCenter: this._boundingSphere.center,
      ellipsoid: ellipsoid,
      exaggeration: exaggeration,
      exaggerationRelativeHeight: exaggerationRelativeHeight,
    });

    if (!defined(verticesPromise)) {
      // Postponed
      return undefined;
    }

    const that = this;
    return Promise.resolve(verticesPromise).then(function (result) {
      const vertexCountWithoutSkirts = that._quantizedVertices.length / 3;
      const vertexCount =
        vertexCountWithoutSkirts +
        that._westIndices.length +
        that._southIndices.length +
        that._eastIndices.length +
        that._northIndices.length;
      const indicesTypedArray = IndexDatatype$1.createTypedArray(
        vertexCount,
        result.indices
      );

      const vertices = new Float32Array(result.vertices);
      const rtc = result.center;
      const minimumHeight = result.minimumHeight;
      const maximumHeight = result.maximumHeight;
      const boundingSphere = that._boundingSphere;
      const obb = that._orientedBoundingBox;
      const occludeePointInScaledSpace = defaultValue(
        Cartesian3.clone(result.occludeePointInScaledSpace),
        that._horizonOcclusionPoint
      );
      const stride = result.vertexStride;
      const terrainEncoding = TerrainEncoding.clone(result.encoding);

      // Clone complex result objects because the transfer from the web worker
      // has stripped them down to JSON-style objects.
      that._mesh = new TerrainMesh(
        rtc,
        vertices,
        indicesTypedArray,
        result.indexCountWithoutSkirts,
        vertexCountWithoutSkirts,
        minimumHeight,
        maximumHeight,
        boundingSphere,
        occludeePointInScaledSpace,
        stride,
        obb,
        terrainEncoding,
        result.westIndicesSouthToNorth,
        result.southIndicesEastToWest,
        result.eastIndicesNorthToSouth,
        result.northIndicesWestToEast
      );

      // Free memory received from server after mesh is created.
      that._quantizedVertices = undefined;
      that._encodedNormals = undefined;
      that._indices = undefined;

      that._uValues = undefined;
      that._vValues = undefined;
      that._heightValues = undefined;

      that._westIndices = undefined;
      that._southIndices = undefined;
      that._eastIndices = undefined;
      that._northIndices = undefined;

      return that._mesh;
    });
  };

  const upsampleTaskProcessor$1 = new TaskProcessor(
    "upsampleQuantizedTerrainMesh",
    TerrainData.maximumAsynchronousTasks
  );

  /**
   * Upsamples this terrain data for use by a descendant tile.  The resulting instance will contain a subset of the
   * vertices in this instance, interpolated if necessary.
   *
   * @param {TilingScheme} tilingScheme The tiling scheme of this terrain data.
   * @param {Number} thisX The X coordinate of this tile in the tiling scheme.
   * @param {Number} thisY The Y coordinate of this tile in the tiling scheme.
   * @param {Number} thisLevel The level of this tile in the tiling scheme.
   * @param {Number} descendantX The X coordinate within the tiling scheme of the descendant tile for which we are upsampling.
   * @param {Number} descendantY The Y coordinate within the tiling scheme of the descendant tile for which we are upsampling.
   * @param {Number} descendantLevel The level within the tiling scheme of the descendant tile for which we are upsampling.
   * @returns {Promise.<QuantizedMeshTerrainData>|undefined} A promise for upsampled heightmap terrain data for the descendant tile,
   *          or undefined if too many asynchronous upsample operations are in progress and the request has been
   *          deferred.
   */
  QuantizedMeshTerrainData.prototype.upsample = function (
    tilingScheme,
    thisX,
    thisY,
    thisLevel,
    descendantX,
    descendantY,
    descendantLevel
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(tilingScheme)) {
      throw new DeveloperError("tilingScheme is required.");
    }
    if (!defined(thisX)) {
      throw new DeveloperError("thisX is required.");
    }
    if (!defined(thisY)) {
      throw new DeveloperError("thisY is required.");
    }
    if (!defined(thisLevel)) {
      throw new DeveloperError("thisLevel is required.");
    }
    if (!defined(descendantX)) {
      throw new DeveloperError("descendantX is required.");
    }
    if (!defined(descendantY)) {
      throw new DeveloperError("descendantY is required.");
    }
    if (!defined(descendantLevel)) {
      throw new DeveloperError("descendantLevel is required.");
    }
    const levelDifference = descendantLevel - thisLevel;
    if (levelDifference > 1) {
      throw new DeveloperError(
        "Upsampling through more than one level at a time is not currently supported."
      );
    }
    //>>includeEnd('debug');

    const mesh = this._mesh;
    if (!defined(this._mesh)) {
      return undefined;
    }

    const isEastChild = thisX * 2 !== descendantX;
    const isNorthChild = thisY * 2 === descendantY;

    const ellipsoid = tilingScheme.ellipsoid;
    const childRectangle = tilingScheme.tileXYToRectangle(
      descendantX,
      descendantY,
      descendantLevel
    );

    const upsamplePromise = upsampleTaskProcessor$1.scheduleTask({
      vertices: mesh.vertices,
      vertexCountWithoutSkirts: mesh.vertexCountWithoutSkirts,
      indices: mesh.indices,
      indexCountWithoutSkirts: mesh.indexCountWithoutSkirts,
      encoding: mesh.encoding,
      minimumHeight: this._minimumHeight,
      maximumHeight: this._maximumHeight,
      isEastChild: isEastChild,
      isNorthChild: isNorthChild,
      childRectangle: childRectangle,
      ellipsoid: ellipsoid,
    });

    if (!defined(upsamplePromise)) {
      // Postponed
      return undefined;
    }

    let shortestSkirt = Math.min(this._westSkirtHeight, this._eastSkirtHeight);
    shortestSkirt = Math.min(shortestSkirt, this._southSkirtHeight);
    shortestSkirt = Math.min(shortestSkirt, this._northSkirtHeight);

    const westSkirtHeight = isEastChild
      ? shortestSkirt * 0.5
      : this._westSkirtHeight;
    const southSkirtHeight = isNorthChild
      ? shortestSkirt * 0.5
      : this._southSkirtHeight;
    const eastSkirtHeight = isEastChild
      ? this._eastSkirtHeight
      : shortestSkirt * 0.5;
    const northSkirtHeight = isNorthChild
      ? this._northSkirtHeight
      : shortestSkirt * 0.5;
    const credits = this._credits;

    return Promise.resolve(upsamplePromise).then(function (result) {
      const quantizedVertices = new Uint16Array(result.vertices);
      const indicesTypedArray = IndexDatatype$1.createTypedArray(
        quantizedVertices.length / 3,
        result.indices
      );
      let encodedNormals;
      if (defined(result.encodedNormals)) {
        encodedNormals = new Uint8Array(result.encodedNormals);
      }

      return new QuantizedMeshTerrainData({
        quantizedVertices: quantizedVertices,
        indices: indicesTypedArray,
        encodedNormals: encodedNormals,
        minimumHeight: result.minimumHeight,
        maximumHeight: result.maximumHeight,
        boundingSphere: BoundingSphere.clone(result.boundingSphere),
        orientedBoundingBox: OrientedBoundingBox.clone(
          result.orientedBoundingBox
        ),
        horizonOcclusionPoint: Cartesian3.clone(result.horizonOcclusionPoint),
        westIndices: result.westIndices,
        southIndices: result.southIndices,
        eastIndices: result.eastIndices,
        northIndices: result.northIndices,
        westSkirtHeight: westSkirtHeight,
        southSkirtHeight: southSkirtHeight,
        eastSkirtHeight: eastSkirtHeight,
        northSkirtHeight: northSkirtHeight,
        childTileMask: 0,
        credits: credits,
        createdByUpsampling: true,
      });
    });
  };

  const maxShort$1 = 32767;
  const barycentricCoordinateScratch$1 = new Cartesian3();

  /**
   * Computes the terrain height at a specified longitude and latitude.
   *
   * @param {Rectangle} rectangle The rectangle covered by this terrain data.
   * @param {Number} longitude The longitude in radians.
   * @param {Number} latitude The latitude in radians.
   * @returns {Number} The terrain height at the specified position.  The position is clamped to
   *          the rectangle, so expect incorrect results for positions far outside the rectangle.
   */
  QuantizedMeshTerrainData.prototype.interpolateHeight = function (
    rectangle,
    longitude,
    latitude
  ) {
    let u = CesiumMath.clamp(
      (longitude - rectangle.west) / rectangle.width,
      0.0,
      1.0
    );
    u *= maxShort$1;
    let v = CesiumMath.clamp(
      (latitude - rectangle.south) / rectangle.height,
      0.0,
      1.0
    );
    v *= maxShort$1;

    if (!defined(this._mesh)) {
      return interpolateHeight$1(this, u, v);
    }

    return interpolateMeshHeight$1(this, u, v);
  };

  function pointInBoundingBox(u, v, u0, v0, u1, v1, u2, v2) {
    const minU = Math.min(u0, u1, u2);
    const maxU = Math.max(u0, u1, u2);
    const minV = Math.min(v0, v1, v2);
    const maxV = Math.max(v0, v1, v2);
    return u >= minU && u <= maxU && v >= minV && v <= maxV;
  }

  const texCoordScratch0$1 = new Cartesian2();
  const texCoordScratch1$1 = new Cartesian2();
  const texCoordScratch2$1 = new Cartesian2();

  function interpolateMeshHeight$1(terrainData, u, v) {
    const mesh = terrainData._mesh;
    const vertices = mesh.vertices;
    const encoding = mesh.encoding;
    const indices = mesh.indices;

    for (let i = 0, len = indices.length; i < len; i += 3) {
      const i0 = indices[i];
      const i1 = indices[i + 1];
      const i2 = indices[i + 2];

      const uv0 = encoding.decodeTextureCoordinates(
        vertices,
        i0,
        texCoordScratch0$1
      );
      const uv1 = encoding.decodeTextureCoordinates(
        vertices,
        i1,
        texCoordScratch1$1
      );
      const uv2 = encoding.decodeTextureCoordinates(
        vertices,
        i2,
        texCoordScratch2$1
      );

      if (pointInBoundingBox(u, v, uv0.x, uv0.y, uv1.x, uv1.y, uv2.x, uv2.y)) {
        const barycentric = Intersections2D.computeBarycentricCoordinates(
          u,
          v,
          uv0.x,
          uv0.y,
          uv1.x,
          uv1.y,
          uv2.x,
          uv2.y,
          barycentricCoordinateScratch$1
        );
        if (
          barycentric.x >= -1e-15 &&
          barycentric.y >= -1e-15 &&
          barycentric.z >= -1e-15
        ) {
          const h0 = encoding.decodeHeight(vertices, i0);
          const h1 = encoding.decodeHeight(vertices, i1);
          const h2 = encoding.decodeHeight(vertices, i2);
          return barycentric.x * h0 + barycentric.y * h1 + barycentric.z * h2;
        }
      }
    }

    // Position does not lie in any triangle in this mesh.
    return undefined;
  }

  function interpolateHeight$1(terrainData, u, v) {
    const uBuffer = terrainData._uValues;
    const vBuffer = terrainData._vValues;
    const heightBuffer = terrainData._heightValues;

    const indices = terrainData._indices;
    for (let i = 0, len = indices.length; i < len; i += 3) {
      const i0 = indices[i];
      const i1 = indices[i + 1];
      const i2 = indices[i + 2];

      const u0 = uBuffer[i0];
      const u1 = uBuffer[i1];
      const u2 = uBuffer[i2];

      const v0 = vBuffer[i0];
      const v1 = vBuffer[i1];
      const v2 = vBuffer[i2];

      if (pointInBoundingBox(u, v, u0, v0, u1, v1, u2, v2)) {
        const barycentric = Intersections2D.computeBarycentricCoordinates(
          u,
          v,
          u0,
          v0,
          u1,
          v1,
          u2,
          v2,
          barycentricCoordinateScratch$1
        );
        if (
          barycentric.x >= -1e-15 &&
          barycentric.y >= -1e-15 &&
          barycentric.z >= -1e-15
        ) {
          const quantizedHeight =
            barycentric.x * heightBuffer[i0] +
            barycentric.y * heightBuffer[i1] +
            barycentric.z * heightBuffer[i2];
          return CesiumMath.lerp(
            terrainData._minimumHeight,
            terrainData._maximumHeight,
            quantizedHeight / maxShort$1
          );
        }
      }
    }

    // Position does not lie in any triangle in this mesh.
    return undefined;
  }

  /**
   * Determines if a given child tile is available, based on the
   * {@link HeightmapTerrainData.childTileMask}.  The given child tile coordinates are assumed
   * to be one of the four children of this tile.  If non-child tile coordinates are
   * given, the availability of the southeast child tile is returned.
   *
   * @param {Number} thisX The tile X coordinate of this (the parent) tile.
   * @param {Number} thisY The tile Y coordinate of this (the parent) tile.
   * @param {Number} childX The tile X coordinate of the child tile to check for availability.
   * @param {Number} childY The tile Y coordinate of the child tile to check for availability.
   * @returns {Boolean} True if the child tile is available; otherwise, false.
   */
  QuantizedMeshTerrainData.prototype.isChildAvailable = function (
    thisX,
    thisY,
    childX,
    childY
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(thisX)) {
      throw new DeveloperError("thisX is required.");
    }
    if (!defined(thisY)) {
      throw new DeveloperError("thisY is required.");
    }
    if (!defined(childX)) {
      throw new DeveloperError("childX is required.");
    }
    if (!defined(childY)) {
      throw new DeveloperError("childY is required.");
    }
    //>>includeEnd('debug');

    let bitNumber = 2; // northwest child
    if (childX !== thisX * 2) {
      ++bitNumber; // east child
    }
    if (childY !== thisY * 2) {
      bitNumber -= 2; // south child
    }

    return (this._childTileMask & (1 << bitNumber)) !== 0;
  };

  /**
   * Gets a value indicating whether or not this terrain data was created by upsampling lower resolution
   * terrain data.  If this value is false, the data was obtained from some other source, such
   * as by downloading it from a remote server.  This method should return true for instances
   * returned from a call to {@link HeightmapTerrainData#upsample}.
   *
   * @returns {Boolean} True if this instance was created by upsampling; otherwise, false.
   */
  QuantizedMeshTerrainData.prototype.wasCreatedByUpsampling = function () {
    return this._createdByUpsampling;
  };

  function LayerInformation(layer) {
    this.resource = layer.resource;
    this.version = layer.version;
    this.isHeightmap = layer.isHeightmap;
    this.tileUrlTemplates = layer.tileUrlTemplates;
    this.availability = layer.availability;
    this.hasVertexNormals = layer.hasVertexNormals;
    this.hasWaterMask = layer.hasWaterMask;
    this.hasMetadata = layer.hasMetadata;
    this.availabilityLevels = layer.availabilityLevels;
    this.availabilityTilesLoaded = layer.availabilityTilesLoaded;
    this.littleEndianExtensionSize = layer.littleEndianExtensionSize;
    this.availabilityPromiseCache = {};
  }

  /**
   * A {@link TerrainProvider} that accesses terrain data in a Cesium terrain format.
   * Terrain formats can be one of the following:
   * <ul>
   * <li> {@link https://github.com/AnalyticalGraphicsInc/quantized-mesh Quantized Mesh} </li>
   * <li> {@link https://github.com/AnalyticalGraphicsInc/cesium/wiki/heightmap-1.0 Height Map} </li>
   * </ul>
   *
   * @alias CesiumTerrainProvider
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Resource|String|Promise<Resource>|Promise<String>} options.url The URL of the Cesium terrain server.
   * @param {Boolean} [options.requestVertexNormals=false] Flag that indicates if the client should request additional lighting information from the server, in the form of per vertex normals if available.
   * @param {Boolean} [options.requestWaterMask=false] Flag that indicates if the client should request per tile water masks from the server,  if available.
   * @param {Boolean} [options.requestMetadata=true] Flag that indicates if the client should request per tile metadata from the server, if available.
   * @param {Ellipsoid} [options.ellipsoid] The ellipsoid.  If not specified, the WGS84 ellipsoid is used.
   * @param {Credit|String} [options.credit] A credit for the data source, which is displayed on the canvas.
   *
   *
   * @example
   * // Create Arctic DEM terrain with normals.
   * const viewer = new Cesium.Viewer('cesiumContainer', {
   *     terrainProvider : new Cesium.CesiumTerrainProvider({
   *         url : Cesium.IonResource.fromAssetId(3956),
   *         requestVertexNormals : true
   *     })
   * });
   *
   * @see createWorldTerrain
   * @see TerrainProvider
   */
  function CesiumTerrainProvider(options) {
    //>>includeStart('debug', pragmas.debug)
    if (!defined(options) || !defined(options.url)) {
      throw new DeveloperError("options.url is required.");
    }
    //>>includeEnd('debug');

    this._heightmapWidth = 65;
    this._heightmapStructure = undefined;
    this._hasWaterMask = false;
    this._hasVertexNormals = false;
    this._ellipsoid = options.ellipsoid;

    /**
     * Boolean flag that indicates if the client should request vertex normals from the server.
     * @type {Boolean}
     * @default false
     * @private
     */
    this._requestVertexNormals = defaultValue(
      options.requestVertexNormals,
      false
    );

    /**
     * Boolean flag that indicates if the client should request tile watermasks from the server.
     * @type {Boolean}
     * @default false
     * @private
     */
    this._requestWaterMask = defaultValue(options.requestWaterMask, false);

    /**
     * Boolean flag that indicates if the client should request tile metadata from the server.
     * @type {Boolean}
     * @default true
     * @private
     */
    this._requestMetadata = defaultValue(options.requestMetadata, true);

    this._errorEvent = new Event();

    let credit = options.credit;
    if (typeof credit === "string") {
      credit = new Credit(credit);
    }
    this._credit = credit;

    this._availability = undefined;

    const deferred = defer();
    this._ready = false;
    this._readyPromise = deferred;
    this._tileCredits = undefined;

    const that = this;
    let lastResource;
    let layerJsonResource;
    let metadataError;

    const layers = (this._layers = []);
    let attribution = "";
    const overallAvailability = [];
    let overallMaxZoom = 0;
    Promise.resolve(options.url)
      .then(function (url) {
        const resource = Resource.createIfNeeded(url);
        resource.appendForwardSlash();
        lastResource = resource;
        layerJsonResource = lastResource.getDerivedResource({
          url: "layer.json",
        });

        // ion resources have a credits property we can use for additional attribution.
        that._tileCredits = resource.credits;

        requestLayerJson();
      })
      .catch(function (e) {
        deferred.reject(e);
      });

    function parseMetadataSuccess(data) {
      let message;

      if (!data.format) {
        message = "The tile format is not specified in the layer.json file.";
        metadataError = TileProviderError.handleError(
          metadataError,
          that,
          that._errorEvent,
          message,
          undefined,
          undefined,
          undefined,
          requestLayerJson
        );
        return;
      }

      if (!data.tiles || data.tiles.length === 0) {
        message = "The layer.json file does not specify any tile URL templates.";
        metadataError = TileProviderError.handleError(
          metadataError,
          that,
          that._errorEvent,
          message,
          undefined,
          undefined,
          undefined,
          requestLayerJson
        );
        return;
      }

      let hasVertexNormals = false;
      let hasWaterMask = false;
      let hasMetadata = false;
      let littleEndianExtensionSize = true;
      let isHeightmap = false;
      if (data.format === "heightmap-1.0") {
        isHeightmap = true;
        if (!defined(that._heightmapStructure)) {
          that._heightmapStructure = {
            heightScale: 1.0 / 5.0,
            heightOffset: -1000.0,
            elementsPerHeight: 1,
            stride: 1,
            elementMultiplier: 256.0,
            isBigEndian: false,
            lowestEncodedHeight: 0,
            highestEncodedHeight: 256 * 256 - 1,
          };
        }
        hasWaterMask = true;
        that._requestWaterMask = true;
      } else if (data.format.indexOf("quantized-mesh-1.") !== 0) {
        message = `The tile format "${data.format}" is invalid or not supported.`;
        metadataError = TileProviderError.handleError(
          metadataError,
          that,
          that._errorEvent,
          message,
          undefined,
          undefined,
          undefined,
          requestLayerJson
        );
        return;
      }

      const tileUrlTemplates = data.tiles;

      const maxZoom = data.maxzoom;
      overallMaxZoom = Math.max(overallMaxZoom, maxZoom);
      // Keeps track of which of the availablity containing tiles have been loaded

      if (!data.projection || data.projection === "EPSG:4326") {
        that._tilingScheme = new GeographicTilingScheme({
          numberOfLevelZeroTilesX: 2,
          numberOfLevelZeroTilesY: 1,
          ellipsoid: that._ellipsoid,
        });
      } else if (data.projection === "EPSG:3857") {
        that._tilingScheme = new WebMercatorTilingScheme({
          numberOfLevelZeroTilesX: 1,
          numberOfLevelZeroTilesY: 1,
          ellipsoid: that._ellipsoid,
        });
      } else {
        message = `The projection "${data.projection}" is invalid or not supported.`;
        metadataError = TileProviderError.handleError(
          metadataError,
          that,
          that._errorEvent,
          message,
          undefined,
          undefined,
          undefined,
          requestLayerJson
        );
        return;
      }

      that._levelZeroMaximumGeometricError = TerrainProvider.getEstimatedLevelZeroGeometricErrorForAHeightmap(
        that._tilingScheme.ellipsoid,
        that._heightmapWidth,
        that._tilingScheme.getNumberOfXTilesAtLevel(0)
      );
      if (!data.scheme || data.scheme === "tms" || data.scheme === "slippyMap") {
        that._scheme = data.scheme;
      } else {
        message = `The scheme "${data.scheme}" is invalid or not supported.`;
        metadataError = TileProviderError.handleError(
          metadataError,
          that,
          that._errorEvent,
          message,
          undefined,
          undefined,
          undefined,
          requestLayerJson
        );
        return;
      }

      let availabilityTilesLoaded;

      // The vertex normals defined in the 'octvertexnormals' extension is identical to the original
      // contents of the original 'vertexnormals' extension.  'vertexnormals' extension is now
      // deprecated, as the extensionLength for this extension was incorrectly using big endian.
      // We maintain backwards compatibility with the legacy 'vertexnormal' implementation
      // by setting the _littleEndianExtensionSize to false. Always prefer 'octvertexnormals'
      // over 'vertexnormals' if both extensions are supported by the server.
      if (
        defined(data.extensions) &&
        data.extensions.indexOf("octvertexnormals") !== -1
      ) {
        hasVertexNormals = true;
      } else if (
        defined(data.extensions) &&
        data.extensions.indexOf("vertexnormals") !== -1
      ) {
        hasVertexNormals = true;
        littleEndianExtensionSize = false;
      }
      if (
        defined(data.extensions) &&
        data.extensions.indexOf("watermask") !== -1
      ) {
        hasWaterMask = true;
      }
      if (
        defined(data.extensions) &&
        data.extensions.indexOf("metadata") !== -1
      ) {
        hasMetadata = true;
      }

      const availabilityLevels = data.metadataAvailability;
      const availableTiles = data.available;
      let availability;
      if (defined(availableTiles) && !defined(availabilityLevels)) {
        availability = new TileAvailability(
          that._tilingScheme,
          availableTiles.length
        );
        for (let level = 0; level < availableTiles.length; ++level) {
          const rangesAtLevel = availableTiles[level];
          const yTiles = that._tilingScheme.getNumberOfYTilesAtLevel(level);
          if (!defined(overallAvailability[level])) {
            overallAvailability[level] = [];
          }

          for (
            let rangeIndex = 0;
            rangeIndex < rangesAtLevel.length;
            ++rangeIndex
          ) {
            const range = rangesAtLevel[rangeIndex];
            const yStart = yTiles - range.endY - 1;
            const yEnd = yTiles - range.startY - 1;
            overallAvailability[level].push([
              range.startX,
              yStart,
              range.endX,
              yEnd,
            ]);
            availability.addAvailableTileRange(
              level,
              range.startX,
              yStart,
              range.endX,
              yEnd
            );
          }
        }
      } else if (defined(availabilityLevels)) {
        availabilityTilesLoaded = new TileAvailability(
          that._tilingScheme,
          maxZoom
        );
        availability = new TileAvailability(that._tilingScheme, maxZoom);
        overallAvailability[0] = [[0, 0, 1, 0]];
        availability.addAvailableTileRange(0, 0, 0, 1, 0);
      }

      that._hasWaterMask = that._hasWaterMask || hasWaterMask;
      that._hasVertexNormals = that._hasVertexNormals || hasVertexNormals;
      that._hasMetadata = that._hasMetadata || hasMetadata;
      if (defined(data.attribution)) {
        if (attribution.length > 0) {
          attribution += " ";
        }
        attribution += data.attribution;
      }

      layers.push(
        new LayerInformation({
          resource: lastResource,
          version: data.version,
          isHeightmap: isHeightmap,
          tileUrlTemplates: tileUrlTemplates,
          availability: availability,
          hasVertexNormals: hasVertexNormals,
          hasWaterMask: hasWaterMask,
          hasMetadata: hasMetadata,
          availabilityLevels: availabilityLevels,
          availabilityTilesLoaded: availabilityTilesLoaded,
          littleEndianExtensionSize: littleEndianExtensionSize,
        })
      );

      const parentUrl = data.parentUrl;
      if (defined(parentUrl)) {
        if (!defined(availability)) {
          console.log(
            "A layer.json can't have a parentUrl if it does't have an available array."
          );
          return Promise.resolve();
        }
        lastResource = lastResource.getDerivedResource({
          url: parentUrl,
        });
        lastResource.appendForwardSlash(); // Terrain always expects a directory
        layerJsonResource = lastResource.getDerivedResource({
          url: "layer.json",
        });
        const parentMetadata = layerJsonResource.fetchJson();
        return Promise.resolve(parentMetadata)
          .then(parseMetadataSuccess)
          .catch(parseMetadataFailure);
      }

      return Promise.resolve();
    }

    function parseMetadataFailure(data) {
      const message = `An error occurred while accessing ${layerJsonResource.url}.`;
      metadataError = TileProviderError.handleError(
        metadataError,
        that,
        that._errorEvent,
        message,
        undefined,
        undefined,
        undefined,
        requestLayerJson
      );
    }

    function metadataSuccess(data) {
      parseMetadataSuccess(data).then(function () {
        if (defined(metadataError)) {
          return;
        }

        const length = overallAvailability.length;
        if (length > 0) {
          const availability = (that._availability = new TileAvailability(
            that._tilingScheme,
            overallMaxZoom
          ));
          for (let level = 0; level < length; ++level) {
            const levelRanges = overallAvailability[level];
            for (let i = 0; i < levelRanges.length; ++i) {
              const range = levelRanges[i];
              availability.addAvailableTileRange(
                level,
                range[0],
                range[1],
                range[2],
                range[3]
              );
            }
          }
        }

        if (attribution.length > 0) {
          const layerJsonCredit = new Credit(attribution);

          if (defined(that._tileCredits)) {
            that._tileCredits.push(layerJsonCredit);
          } else {
            that._tileCredits = [layerJsonCredit];
          }
        }

        that._ready = true;
        that._readyPromise.resolve(true);
      });
    }

    function metadataFailure(data) {
      // If the metadata is not found, assume this is a pre-metadata heightmap tileset.
      if (defined(data) && data.statusCode === 404) {
        metadataSuccess({
          tilejson: "2.1.0",
          format: "heightmap-1.0",
          version: "1.0.0",
          scheme: "tms",
          tiles: ["{z}/{x}/{y}.terrain?v={version}"],
        });
        return;
      }
      parseMetadataFailure();
    }

    function requestLayerJson() {
      Promise.resolve(layerJsonResource.fetchJson())
        .then(metadataSuccess)
        .catch(metadataFailure);
    }
  }

  /**
   * When using the Quantized-Mesh format, a tile may be returned that includes additional extensions, such as PerVertexNormals, watermask, etc.
   * This enumeration defines the unique identifiers for each type of extension data that has been appended to the standard mesh data.
   *
   * @namespace QuantizedMeshExtensionIds
   * @see CesiumTerrainProvider
   * @private
   */
  const QuantizedMeshExtensionIds = {
    /**
     * Oct-Encoded Per-Vertex Normals are included as an extension to the tile mesh
     *
     * @type {Number}
     * @constant
     * @default 1
     */
    OCT_VERTEX_NORMALS: 1,
    /**
     * A watermask is included as an extension to the tile mesh
     *
     * @type {Number}
     * @constant
     * @default 2
     */
    WATER_MASK: 2,
    /**
     * A json object contain metadata about the tile
     *
     * @type {Number}
     * @constant
     * @default 4
     */
    METADATA: 4,
  };

  function getRequestHeader(extensionsList) {
    if (!defined(extensionsList) || extensionsList.length === 0) {
      return {
        Accept:
          "application/vnd.quantized-mesh,application/octet-stream;q=0.9,*/*;q=0.01",
      };
    }
    const extensions = extensionsList.join("-");
    return {
      Accept: `application/vnd.quantized-mesh;extensions=${extensions},application/octet-stream;q=0.9,*/*;q=0.01`,
    };
  }

  function createHeightmapTerrainData(provider, buffer, level, x, y) {
    const heightBuffer = new Uint16Array(
      buffer,
      0,
      provider._heightmapWidth * provider._heightmapWidth
    );
    return new HeightmapTerrainData({
      buffer: heightBuffer,
      childTileMask: new Uint8Array(buffer, heightBuffer.byteLength, 1)[0],
      waterMask: new Uint8Array(
        buffer,
        heightBuffer.byteLength + 1,
        buffer.byteLength - heightBuffer.byteLength - 1
      ),
      width: provider._heightmapWidth,
      height: provider._heightmapWidth,
      structure: provider._heightmapStructure,
      credits: provider._tileCredits,
    });
  }

  function createQuantizedMeshTerrainData(provider, buffer, level, x, y, layer) {
    const littleEndianExtensionSize = layer.littleEndianExtensionSize;
    let pos = 0;
    const cartesian3Elements = 3;
    const boundingSphereElements = cartesian3Elements + 1;
    const cartesian3Length = Float64Array.BYTES_PER_ELEMENT * cartesian3Elements;
    const boundingSphereLength =
      Float64Array.BYTES_PER_ELEMENT * boundingSphereElements;
    const encodedVertexElements = 3;
    const encodedVertexLength =
      Uint16Array.BYTES_PER_ELEMENT * encodedVertexElements;
    const triangleElements = 3;
    let bytesPerIndex = Uint16Array.BYTES_PER_ELEMENT;
    let triangleLength = bytesPerIndex * triangleElements;

    const view = new DataView(buffer);
    const center = new Cartesian3(
      view.getFloat64(pos, true),
      view.getFloat64(pos + 8, true),
      view.getFloat64(pos + 16, true)
    );
    pos += cartesian3Length;

    const minimumHeight = view.getFloat32(pos, true);
    pos += Float32Array.BYTES_PER_ELEMENT;
    const maximumHeight = view.getFloat32(pos, true);
    pos += Float32Array.BYTES_PER_ELEMENT;

    const boundingSphere = new BoundingSphere(
      new Cartesian3(
        view.getFloat64(pos, true),
        view.getFloat64(pos + 8, true),
        view.getFloat64(pos + 16, true)
      ),
      view.getFloat64(pos + cartesian3Length, true)
    );
    pos += boundingSphereLength;

    const horizonOcclusionPoint = new Cartesian3(
      view.getFloat64(pos, true),
      view.getFloat64(pos + 8, true),
      view.getFloat64(pos + 16, true)
    );
    pos += cartesian3Length;

    const vertexCount = view.getUint32(pos, true);
    pos += Uint32Array.BYTES_PER_ELEMENT;
    const encodedVertexBuffer = new Uint16Array(buffer, pos, vertexCount * 3);
    pos += vertexCount * encodedVertexLength;

    if (vertexCount > 64 * 1024) {
      // More than 64k vertices, so indices are 32-bit.
      bytesPerIndex = Uint32Array.BYTES_PER_ELEMENT;
      triangleLength = bytesPerIndex * triangleElements;
    }

    // Decode the vertex buffer.
    const uBuffer = encodedVertexBuffer.subarray(0, vertexCount);
    const vBuffer = encodedVertexBuffer.subarray(vertexCount, 2 * vertexCount);
    const heightBuffer = encodedVertexBuffer.subarray(
      vertexCount * 2,
      3 * vertexCount
    );

    AttributeCompression.zigZagDeltaDecode(uBuffer, vBuffer, heightBuffer);

    // skip over any additional padding that was added for 2/4 byte alignment
    if (pos % bytesPerIndex !== 0) {
      pos += bytesPerIndex - (pos % bytesPerIndex);
    }

    const triangleCount = view.getUint32(pos, true);
    pos += Uint32Array.BYTES_PER_ELEMENT;
    const indices = IndexDatatype$1.createTypedArrayFromArrayBuffer(
      vertexCount,
      buffer,
      pos,
      triangleCount * triangleElements
    );
    pos += triangleCount * triangleLength;

    // High water mark decoding based on decompressIndices_ in webgl-loader's loader.js.
    // https://code.google.com/p/webgl-loader/source/browse/trunk/samples/loader.js?r=99#55
    // Copyright 2012 Google Inc., Apache 2.0 license.
    let highest = 0;
    const length = indices.length;
    for (let i = 0; i < length; ++i) {
      const code = indices[i];
      indices[i] = highest - code;
      if (code === 0) {
        ++highest;
      }
    }

    const westVertexCount = view.getUint32(pos, true);
    pos += Uint32Array.BYTES_PER_ELEMENT;
    const westIndices = IndexDatatype$1.createTypedArrayFromArrayBuffer(
      vertexCount,
      buffer,
      pos,
      westVertexCount
    );
    pos += westVertexCount * bytesPerIndex;

    const southVertexCount = view.getUint32(pos, true);
    pos += Uint32Array.BYTES_PER_ELEMENT;
    const southIndices = IndexDatatype$1.createTypedArrayFromArrayBuffer(
      vertexCount,
      buffer,
      pos,
      southVertexCount
    );
    pos += southVertexCount * bytesPerIndex;

    const eastVertexCount = view.getUint32(pos, true);
    pos += Uint32Array.BYTES_PER_ELEMENT;
    const eastIndices = IndexDatatype$1.createTypedArrayFromArrayBuffer(
      vertexCount,
      buffer,
      pos,
      eastVertexCount
    );
    pos += eastVertexCount * bytesPerIndex;

    const northVertexCount = view.getUint32(pos, true);
    pos += Uint32Array.BYTES_PER_ELEMENT;
    const northIndices = IndexDatatype$1.createTypedArrayFromArrayBuffer(
      vertexCount,
      buffer,
      pos,
      northVertexCount
    );
    pos += northVertexCount * bytesPerIndex;

    let encodedNormalBuffer;
    let waterMaskBuffer;
    while (pos < view.byteLength) {
      const extensionId = view.getUint8(pos, true);
      pos += Uint8Array.BYTES_PER_ELEMENT;
      const extensionLength = view.getUint32(pos, littleEndianExtensionSize);
      pos += Uint32Array.BYTES_PER_ELEMENT;

      if (
        extensionId === QuantizedMeshExtensionIds.OCT_VERTEX_NORMALS &&
        provider._requestVertexNormals
      ) {
        encodedNormalBuffer = new Uint8Array(buffer, pos, vertexCount * 2);
      } else if (
        extensionId === QuantizedMeshExtensionIds.WATER_MASK &&
        provider._requestWaterMask
      ) {
        waterMaskBuffer = new Uint8Array(buffer, pos, extensionLength);
      } else if (
        extensionId === QuantizedMeshExtensionIds.METADATA &&
        provider._requestMetadata
      ) {
        const stringLength = view.getUint32(pos, true);
        if (stringLength > 0) {
          const metadata = getJsonFromTypedArray(
            new Uint8Array(buffer),
            pos + Uint32Array.BYTES_PER_ELEMENT,
            stringLength
          );
          const availableTiles = metadata.available;
          if (defined(availableTiles)) {
            for (let offset = 0; offset < availableTiles.length; ++offset) {
              const availableLevel = level + offset + 1;
              const rangesAtLevel = availableTiles[offset];
              const yTiles = provider._tilingScheme.getNumberOfYTilesAtLevel(
                availableLevel
              );

              for (
                let rangeIndex = 0;
                rangeIndex < rangesAtLevel.length;
                ++rangeIndex
              ) {
                const range = rangesAtLevel[rangeIndex];
                const yStart = yTiles - range.endY - 1;
                const yEnd = yTiles - range.startY - 1;
                provider.availability.addAvailableTileRange(
                  availableLevel,
                  range.startX,
                  yStart,
                  range.endX,
                  yEnd
                );
                layer.availability.addAvailableTileRange(
                  availableLevel,
                  range.startX,
                  yStart,
                  range.endX,
                  yEnd
                );
              }
            }
          }
        }
        layer.availabilityTilesLoaded.addAvailableTileRange(level, x, y, x, y);
      }
      pos += extensionLength;
    }

    const skirtHeight = provider.getLevelMaximumGeometricError(level) * 5.0;

    // The skirt is not included in the OBB computation. If this ever
    // causes any rendering artifacts (cracks), they are expected to be
    // minor and in the corners of the screen. It's possible that this
    // might need to be changed - just change to `minimumHeight - skirtHeight`
    // A similar change might also be needed in `upsampleQuantizedTerrainMesh.js`.
    const rectangle = provider._tilingScheme.tileXYToRectangle(x, y, level);
    const orientedBoundingBox = OrientedBoundingBox.fromRectangle(
      rectangle,
      minimumHeight,
      maximumHeight,
      provider._tilingScheme.ellipsoid
    );

    return new QuantizedMeshTerrainData({
      center: center,
      minimumHeight: minimumHeight,
      maximumHeight: maximumHeight,
      boundingSphere: boundingSphere,
      orientedBoundingBox: orientedBoundingBox,
      horizonOcclusionPoint: horizonOcclusionPoint,
      quantizedVertices: encodedVertexBuffer,
      encodedNormals: encodedNormalBuffer,
      indices: indices,
      westIndices: westIndices,
      southIndices: southIndices,
      eastIndices: eastIndices,
      northIndices: northIndices,
      westSkirtHeight: skirtHeight,
      southSkirtHeight: skirtHeight,
      eastSkirtHeight: skirtHeight,
      northSkirtHeight: skirtHeight,
      childTileMask: provider.availability.computeChildMaskForTile(level, x, y),
      waterMask: waterMaskBuffer,
      credits: provider._tileCredits,
    });
  }

  /**
   * Requests the geometry for a given tile.  This function should not be called before
   * {@link CesiumTerrainProvider#ready} returns true.  The result must include terrain data and
   * may optionally include a water mask and an indication of which child tiles are available.
   *
   * @param {Number} x The X coordinate of the tile for which to request geometry.
   * @param {Number} y The Y coordinate of the tile for which to request geometry.
   * @param {Number} level The level of the tile for which to request geometry.
   * @param {Request} [request] The request object. Intended for internal use only.
   *
   * @returns {Promise.<TerrainData>|undefined} A promise for the requested geometry.  If this method
   *          returns undefined instead of a promise, it is an indication that too many requests are already
   *          pending and the request will be retried later.
   *
   * @exception {DeveloperError} This function must not be called before {@link CesiumTerrainProvider#ready}
   *            returns true.
   */
  CesiumTerrainProvider.prototype.requestTileGeometry = function (
    x,
    y,
    level,
    request
  ) {
    //>>includeStart('debug', pragmas.debug)
    if (!this._ready) {
      throw new DeveloperError(
        "requestTileGeometry must not be called before the terrain provider is ready."
      );
    }
    //>>includeEnd('debug');

    const layers = this._layers;
    let layerToUse;
    const layerCount = layers.length;

    if (layerCount === 1) {
      // Optimized path for single layers
      layerToUse = layers[0];
    } else {
      for (let i = 0; i < layerCount; ++i) {
        const layer = layers[i];
        if (
          !defined(layer.availability) ||
          layer.availability.isTileAvailable(level, x, y)
        ) {
          layerToUse = layer;
          break;
        }
      }
    }

    return requestTileGeometry$1(this, x, y, level, layerToUse, request);
  };

  function requestTileGeometry$1(provider, x, y, level, layerToUse, request) {
    if (!defined(layerToUse)) {
      return Promise.reject(new RuntimeError("Terrain tile doesn't exist"));
    }

    const urlTemplates = layerToUse.tileUrlTemplates;
    if (urlTemplates.length === 0) {
      return undefined;
    }

    // The TileMapService scheme counts from the bottom left
    let terrainY;
    if (!provider._scheme || provider._scheme === "tms") {
      const yTiles = provider._tilingScheme.getNumberOfYTilesAtLevel(level);
      terrainY = yTiles - y - 1;
    } else {
      terrainY = y;
    }

    const extensionList = [];
    if (provider._requestVertexNormals && layerToUse.hasVertexNormals) {
      extensionList.push(
        layerToUse.littleEndianExtensionSize
          ? "octvertexnormals"
          : "vertexnormals"
      );
    }
    if (provider._requestWaterMask && layerToUse.hasWaterMask) {
      extensionList.push("watermask");
    }
    if (provider._requestMetadata && layerToUse.hasMetadata) {
      extensionList.push("metadata");
    }

    let headers;
    let query;
    const url = urlTemplates[(x + terrainY + level) % urlTemplates.length];

    const resource = layerToUse.resource;
    if (
      defined(resource._ionEndpoint) &&
      !defined(resource._ionEndpoint.externalType)
    ) {
      // ion uses query paremeters to request extensions
      if (extensionList.length !== 0) {
        query = { extensions: extensionList.join("-") };
      }
      headers = getRequestHeader(undefined);
    } else {
      //All other terrain servers
      headers = getRequestHeader(extensionList);
    }

    const promise = resource
      .getDerivedResource({
        url: url,
        templateValues: {
          version: layerToUse.version,
          z: level,
          x: x,
          y: terrainY,
        },
        queryParameters: query,
        headers: headers,
        request: request,
      })
      .fetchArrayBuffer();

    if (!defined(promise)) {
      return undefined;
    }

    return promise.then(function (buffer) {
      if (defined(provider._heightmapStructure)) {
        return createHeightmapTerrainData(provider, buffer);
      }
      return createQuantizedMeshTerrainData(
        provider,
        buffer,
        level,
        x,
        y,
        layerToUse
      );
    });
  }

  Object.defineProperties(CesiumTerrainProvider.prototype, {
    /**
     * Gets an event that is raised when the terrain provider encounters an asynchronous error.  By subscribing
     * to the event, you will be notified of the error and can potentially recover from it.  Event listeners
     * are passed an instance of {@link TileProviderError}.
     * @memberof CesiumTerrainProvider.prototype
     * @type {Event}
     * @readonly
     */
    errorEvent: {
      get: function () {
        return this._errorEvent;
      },
    },

    /**
     * Gets the credit to display when this terrain provider is active.  Typically this is used to credit
     * the source of the terrain.  This function should not be called before {@link CesiumTerrainProvider#ready} returns true.
     * @memberof CesiumTerrainProvider.prototype
     * @type {Credit}
     * @readonly
     */
    credit: {
      get: function () {
        //>>includeStart('debug', pragmas.debug)
        if (!this._ready) {
          throw new DeveloperError(
            "credit must not be called before the terrain provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._credit;
      },
    },

    /**
     * Gets the tiling scheme used by this provider.  This function should
     * not be called before {@link CesiumTerrainProvider#ready} returns true.
     * @memberof CesiumTerrainProvider.prototype
     * @type {GeographicTilingScheme}
     * @readonly
     */
    tilingScheme: {
      get: function () {
        //>>includeStart('debug', pragmas.debug)
        if (!this._ready) {
          throw new DeveloperError(
            "tilingScheme must not be called before the terrain provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._tilingScheme;
      },
    },

    /**
     * Gets a value indicating whether or not the provider is ready for use.
     * @memberof CesiumTerrainProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    ready: {
      get: function () {
        return this._ready;
      },
    },

    /**
     * Gets a promise that resolves to true when the provider is ready for use.
     * @memberof CesiumTerrainProvider.prototype
     * @type {Promise.<Boolean>}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._readyPromise.promise;
      },
    },

    /**
     * Gets a value indicating whether or not the provider includes a water mask.  The water mask
     * indicates which areas of the globe are water rather than land, so they can be rendered
     * as a reflective surface with animated waves.  This function should not be
     * called before {@link CesiumTerrainProvider#ready} returns true.
     * @memberof CesiumTerrainProvider.prototype
     * @type {Boolean}
     * @readonly
     * @exception {DeveloperError} This property must not be called before {@link CesiumTerrainProvider#ready}
     */
    hasWaterMask: {
      get: function () {
        //>>includeStart('debug', pragmas.debug)
        if (!this._ready) {
          throw new DeveloperError(
            "hasWaterMask must not be called before the terrain provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._hasWaterMask && this._requestWaterMask;
      },
    },

    /**
     * Gets a value indicating whether or not the requested tiles include vertex normals.
     * This function should not be called before {@link CesiumTerrainProvider#ready} returns true.
     * @memberof CesiumTerrainProvider.prototype
     * @type {Boolean}
     * @readonly
     * @exception {DeveloperError} This property must not be called before {@link CesiumTerrainProvider#ready}
     */
    hasVertexNormals: {
      get: function () {
        //>>includeStart('debug', pragmas.debug)
        if (!this._ready) {
          throw new DeveloperError(
            "hasVertexNormals must not be called before the terrain provider is ready."
          );
        }
        //>>includeEnd('debug');

        // returns true if we can request vertex normals from the server
        return this._hasVertexNormals && this._requestVertexNormals;
      },
    },

    /**
     * Gets a value indicating whether or not the requested tiles include metadata.
     * This function should not be called before {@link CesiumTerrainProvider#ready} returns true.
     * @memberof CesiumTerrainProvider.prototype
     * @type {Boolean}
     * @readonly
     * @exception {DeveloperError} This property must not be called before {@link CesiumTerrainProvider#ready}
     */
    hasMetadata: {
      get: function () {
        //>>includeStart('debug', pragmas.debug)
        if (!this._ready) {
          throw new DeveloperError(
            "hasMetadata must not be called before the terrain provider is ready."
          );
        }
        //>>includeEnd('debug');

        // returns true if we can request metadata from the server
        return this._hasMetadata && this._requestMetadata;
      },
    },

    /**
     * Boolean flag that indicates if the client should request vertex normals from the server.
     * Vertex normals data is appended to the standard tile mesh data only if the client requests the vertex normals and
     * if the server provides vertex normals.
     * @memberof CesiumTerrainProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    requestVertexNormals: {
      get: function () {
        return this._requestVertexNormals;
      },
    },

    /**
     * Boolean flag that indicates if the client should request a watermask from the server.
     * Watermask data is appended to the standard tile mesh data only if the client requests the watermask and
     * if the server provides a watermask.
     * @memberof CesiumTerrainProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    requestWaterMask: {
      get: function () {
        return this._requestWaterMask;
      },
    },

    /**
     * Boolean flag that indicates if the client should request metadata from the server.
     * Metadata is appended to the standard tile mesh data only if the client requests the metadata and
     * if the server provides a metadata.
     * @memberof CesiumTerrainProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    requestMetadata: {
      get: function () {
        return this._requestMetadata;
      },
    },

    /**
     * Gets an object that can be used to determine availability of terrain from this provider, such as
     * at points and in rectangles.  This function should not be called before
     * {@link CesiumTerrainProvider#ready} returns true.  This property may be undefined if availability
     * information is not available. Note that this reflects tiles that are known to be available currently.
     * Additional tiles may be discovered to be available in the future, e.g. if availability information
     * exists deeper in the tree rather than it all being discoverable at the root. However, a tile that
     * is available now will not become unavailable in the future.
     * @memberof CesiumTerrainProvider.prototype
     * @type {TileAvailability}
     * @readonly
     */
    availability: {
      get: function () {
        //>>includeStart('debug', pragmas.debug)
        if (!this._ready) {
          throw new DeveloperError(
            "availability must not be called before the terrain provider is ready."
          );
        }
        //>>includeEnd('debug');
        return this._availability;
      },
    },
  });

  /**
   * Gets the maximum geometric error allowed in a tile at a given level.
   *
   * @param {Number} level The tile level for which to get the maximum geometric error.
   * @returns {Number} The maximum geometric error.
   */
  CesiumTerrainProvider.prototype.getLevelMaximumGeometricError = function (
    level
  ) {
    return this._levelZeroMaximumGeometricError / (1 << level);
  };

  /**
   * Determines whether data for a tile is available to be loaded.
   *
   * @param {Number} x The X coordinate of the tile for which to request geometry.
   * @param {Number} y The Y coordinate of the tile for which to request geometry.
   * @param {Number} level The level of the tile for which to request geometry.
   * @returns {Boolean|undefined} Undefined if not supported or availability is unknown, otherwise true or false.
   */
  CesiumTerrainProvider.prototype.getTileDataAvailable = function (x, y, level) {
    if (!defined(this._availability)) {
      return undefined;
    }
    if (level > this._availability._maximumLevel) {
      return false;
    }

    if (this._availability.isTileAvailable(level, x, y)) {
      // If the tile is listed as available, then we are done
      return true;
    }
    if (!this._hasMetadata) {
      // If we don't have any layers with the metadata extension then we don't have this tile
      return false;
    }

    const layers = this._layers;
    const count = layers.length;
    for (let i = 0; i < count; ++i) {
      const layerResult = checkLayer(this, x, y, level, layers[i], i === 0);
      if (layerResult.result) {
        // There is a layer that may or may not have the tile
        return undefined;
      }
    }

    return false;
  };

  /**
   * Makes sure we load availability data for a tile
   *
   * @param {Number} x The X coordinate of the tile for which to request geometry.
   * @param {Number} y The Y coordinate of the tile for which to request geometry.
   * @param {Number} level The level of the tile for which to request geometry.
   * @returns {undefined|Promise<void>} Undefined if nothing need to be loaded or a Promise that resolves when all required tiles are loaded
   */
  CesiumTerrainProvider.prototype.loadTileDataAvailability = function (
    x,
    y,
    level
  ) {
    if (
      !defined(this._availability) ||
      level > this._availability._maximumLevel ||
      this._availability.isTileAvailable(level, x, y) ||
      !this._hasMetadata
    ) {
      // We know the tile is either available or not available so nothing to wait on
      return undefined;
    }

    const layers = this._layers;
    const count = layers.length;
    for (let i = 0; i < count; ++i) {
      const layerResult = checkLayer(this, x, y, level, layers[i], i === 0);
      if (defined(layerResult.promise)) {
        return layerResult.promise;
      }
    }
  };

  function getAvailabilityTile(layer, x, y, level) {
    if (level === 0) {
      return;
    }

    const availabilityLevels = layer.availabilityLevels;
    const parentLevel =
      level % availabilityLevels === 0
        ? level - availabilityLevels
        : ((level / availabilityLevels) | 0) * availabilityLevels;
    const divisor = 1 << (level - parentLevel);
    const parentX = (x / divisor) | 0;
    const parentY = (y / divisor) | 0;

    return {
      level: parentLevel,
      x: parentX,
      y: parentY,
    };
  }

  function checkLayer(provider, x, y, level, layer, topLayer) {
    if (!defined(layer.availabilityLevels)) {
      // It's definitely not in this layer
      return {
        result: false,
      };
    }

    let cacheKey;
    const deleteFromCache = function () {
      delete layer.availabilityPromiseCache[cacheKey];
    };
    const availabilityTilesLoaded = layer.availabilityTilesLoaded;
    const availability = layer.availability;

    let tile = getAvailabilityTile(layer, x, y, level);
    while (defined(tile)) {
      if (
        availability.isTileAvailable(tile.level, tile.x, tile.y) &&
        !availabilityTilesLoaded.isTileAvailable(tile.level, tile.x, tile.y)
      ) {
        let requestPromise;
        if (!topLayer) {
          cacheKey = `${tile.level}-${tile.x}-${tile.y}`;
          requestPromise = layer.availabilityPromiseCache[cacheKey];
          if (!defined(requestPromise)) {
            // For cutout terrain, if this isn't the top layer the availability tiles
            //  may never get loaded, so request it here.
            const request = new Request({
              throttle: false,
              throttleByServer: true,
              type: RequestType$1.TERRAIN,
            });
            requestPromise = requestTileGeometry$1(
              provider,
              tile.x,
              tile.y,
              tile.level,
              layer,
              request
            );
            if (defined(requestPromise)) {
              layer.availabilityPromiseCache[cacheKey] = requestPromise;
              requestPromise.then(deleteFromCache);
            }
          }
        }

        // The availability tile is available, but not loaded, so there
        //  is still a chance that it may become available at some point
        return {
          result: true,
          promise: requestPromise,
        };
      }

      tile = getAvailabilityTile(layer, tile.x, tile.y, tile.level);
    }

    return {
      result: false,
    };
  }

  // Used for testing
  CesiumTerrainProvider._getAvailabilityTile = getAvailabilityTile;

  const EllipseGeometryLibrary = {};

  const rotAxis = new Cartesian3();
  const tempVec = new Cartesian3();
  const unitQuat = new Quaternion();
  const rotMtx = new Matrix3();

  function pointOnEllipsoid(
    theta,
    rotation,
    northVec,
    eastVec,
    aSqr,
    ab,
    bSqr,
    mag,
    unitPos,
    result
  ) {
    const azimuth = theta + rotation;

    Cartesian3.multiplyByScalar(eastVec, Math.cos(azimuth), rotAxis);
    Cartesian3.multiplyByScalar(northVec, Math.sin(azimuth), tempVec);
    Cartesian3.add(rotAxis, tempVec, rotAxis);

    let cosThetaSquared = Math.cos(theta);
    cosThetaSquared = cosThetaSquared * cosThetaSquared;

    let sinThetaSquared = Math.sin(theta);
    sinThetaSquared = sinThetaSquared * sinThetaSquared;

    const radius =
      ab / Math.sqrt(bSqr * cosThetaSquared + aSqr * sinThetaSquared);
    const angle = radius / mag;

    // Create the quaternion to rotate the position vector to the boundary of the ellipse.
    Quaternion.fromAxisAngle(rotAxis, angle, unitQuat);
    Matrix3.fromQuaternion(unitQuat, rotMtx);

    Matrix3.multiplyByVector(rotMtx, unitPos, result);
    Cartesian3.normalize(result, result);
    Cartesian3.multiplyByScalar(result, mag, result);
    return result;
  }

  const scratchCartesian1$7 = new Cartesian3();
  const scratchCartesian2$a = new Cartesian3();
  const scratchCartesian3$b = new Cartesian3();
  const scratchNormal$6 = new Cartesian3();
  /**
   * Returns the positions raised to the given heights
   * @private
   */
  EllipseGeometryLibrary.raisePositionsToHeight = function (
    positions,
    options,
    extrude
  ) {
    const ellipsoid = options.ellipsoid;
    const height = options.height;
    const extrudedHeight = options.extrudedHeight;
    const size = extrude ? (positions.length / 3) * 2 : positions.length / 3;

    const finalPositions = new Float64Array(size * 3);

    const length = positions.length;
    const bottomOffset = extrude ? length : 0;
    for (let i = 0; i < length; i += 3) {
      const i1 = i + 1;
      const i2 = i + 2;

      const position = Cartesian3.fromArray(positions, i, scratchCartesian1$7);
      ellipsoid.scaleToGeodeticSurface(position, position);

      const extrudedPosition = Cartesian3.clone(position, scratchCartesian2$a);
      const normal = ellipsoid.geodeticSurfaceNormal(position, scratchNormal$6);
      const scaledNormal = Cartesian3.multiplyByScalar(
        normal,
        height,
        scratchCartesian3$b
      );
      Cartesian3.add(position, scaledNormal, position);

      if (extrude) {
        Cartesian3.multiplyByScalar(normal, extrudedHeight, scaledNormal);
        Cartesian3.add(extrudedPosition, scaledNormal, extrudedPosition);

        finalPositions[i + bottomOffset] = extrudedPosition.x;
        finalPositions[i1 + bottomOffset] = extrudedPosition.y;
        finalPositions[i2 + bottomOffset] = extrudedPosition.z;
      }

      finalPositions[i] = position.x;
      finalPositions[i1] = position.y;
      finalPositions[i2] = position.z;
    }

    return finalPositions;
  };

  const unitPosScratch = new Cartesian3();
  const eastVecScratch = new Cartesian3();
  const northVecScratch = new Cartesian3();
  /**
   * Returns an array of positions that make up the ellipse.
   * @private
   */
  EllipseGeometryLibrary.computeEllipsePositions = function (
    options,
    addFillPositions,
    addEdgePositions
  ) {
    const semiMinorAxis = options.semiMinorAxis;
    const semiMajorAxis = options.semiMajorAxis;
    const rotation = options.rotation;
    const center = options.center;

    // Computing the arc-length of the ellipse is too expensive to be practical. Estimating it using the
    // arc length of the sphere is too inaccurate and creates sharp edges when either the semi-major or
    // semi-minor axis is much bigger than the other. Instead, scale the angle delta to make
    // the distance along the ellipse boundary more closely match the granularity.
    const granularity = options.granularity * 8.0;

    const aSqr = semiMinorAxis * semiMinorAxis;
    const bSqr = semiMajorAxis * semiMajorAxis;
    const ab = semiMajorAxis * semiMinorAxis;

    const mag = Cartesian3.magnitude(center);

    const unitPos = Cartesian3.normalize(center, unitPosScratch);
    let eastVec = Cartesian3.cross(Cartesian3.UNIT_Z, center, eastVecScratch);
    eastVec = Cartesian3.normalize(eastVec, eastVec);
    const northVec = Cartesian3.cross(unitPos, eastVec, northVecScratch);

    // The number of points in the first quadrant
    let numPts = 1 + Math.ceil(CesiumMath.PI_OVER_TWO / granularity);

    const deltaTheta = CesiumMath.PI_OVER_TWO / (numPts - 1);
    let theta = CesiumMath.PI_OVER_TWO - numPts * deltaTheta;
    if (theta < 0.0) {
      numPts -= Math.ceil(Math.abs(theta) / deltaTheta);
    }

    // If the number of points were three, the ellipse
    // would be tessellated like below:
    //
    //         *---*
    //       / | \ | \
    //     *---*---*---*
    //   / | \ | \ | \ | \
    //  / .*---*---*---*. \
    // * ` | \ | \ | \ | `*
    //  \`.*---*---*---*.`/
    //   \ | \ | \ | \ | /
    //     *---*---*---*
    //       \ | \ | /
    //         *---*
    // The first and last column have one position and fan to connect to the adjacent column.
    // Each other vertical column contains an even number of positions.
    const size = 2 * (numPts * (numPts + 2));
    const positions = addFillPositions ? new Array(size * 3) : undefined;
    let positionIndex = 0;
    let position = scratchCartesian1$7;
    let reflectedPosition = scratchCartesian2$a;

    const outerPositionsLength = numPts * 4 * 3;
    let outerRightIndex = outerPositionsLength - 1;
    let outerLeftIndex = 0;
    const outerPositions = addEdgePositions
      ? new Array(outerPositionsLength)
      : undefined;

    let i;
    let j;
    let numInterior;
    let t;
    let interiorPosition;

    // Compute points in the 'eastern' half of the ellipse
    theta = CesiumMath.PI_OVER_TWO;
    position = pointOnEllipsoid(
      theta,
      rotation,
      northVec,
      eastVec,
      aSqr,
      ab,
      bSqr,
      mag,
      unitPos,
      position
    );
    if (addFillPositions) {
      positions[positionIndex++] = position.x;
      positions[positionIndex++] = position.y;
      positions[positionIndex++] = position.z;
    }
    if (addEdgePositions) {
      outerPositions[outerRightIndex--] = position.z;
      outerPositions[outerRightIndex--] = position.y;
      outerPositions[outerRightIndex--] = position.x;
    }
    theta = CesiumMath.PI_OVER_TWO - deltaTheta;
    for (i = 1; i < numPts + 1; ++i) {
      position = pointOnEllipsoid(
        theta,
        rotation,
        northVec,
        eastVec,
        aSqr,
        ab,
        bSqr,
        mag,
        unitPos,
        position
      );
      reflectedPosition = pointOnEllipsoid(
        Math.PI - theta,
        rotation,
        northVec,
        eastVec,
        aSqr,
        ab,
        bSqr,
        mag,
        unitPos,
        reflectedPosition
      );

      if (addFillPositions) {
        positions[positionIndex++] = position.x;
        positions[positionIndex++] = position.y;
        positions[positionIndex++] = position.z;

        numInterior = 2 * i + 2;
        for (j = 1; j < numInterior - 1; ++j) {
          t = j / (numInterior - 1);
          interiorPosition = Cartesian3.lerp(
            position,
            reflectedPosition,
            t,
            scratchCartesian3$b
          );
          positions[positionIndex++] = interiorPosition.x;
          positions[positionIndex++] = interiorPosition.y;
          positions[positionIndex++] = interiorPosition.z;
        }

        positions[positionIndex++] = reflectedPosition.x;
        positions[positionIndex++] = reflectedPosition.y;
        positions[positionIndex++] = reflectedPosition.z;
      }

      if (addEdgePositions) {
        outerPositions[outerRightIndex--] = position.z;
        outerPositions[outerRightIndex--] = position.y;
        outerPositions[outerRightIndex--] = position.x;
        outerPositions[outerLeftIndex++] = reflectedPosition.x;
        outerPositions[outerLeftIndex++] = reflectedPosition.y;
        outerPositions[outerLeftIndex++] = reflectedPosition.z;
      }

      theta = CesiumMath.PI_OVER_TWO - (i + 1) * deltaTheta;
    }

    // Compute points in the 'western' half of the ellipse
    for (i = numPts; i > 1; --i) {
      theta = CesiumMath.PI_OVER_TWO - (i - 1) * deltaTheta;

      position = pointOnEllipsoid(
        -theta,
        rotation,
        northVec,
        eastVec,
        aSqr,
        ab,
        bSqr,
        mag,
        unitPos,
        position
      );
      reflectedPosition = pointOnEllipsoid(
        theta + Math.PI,
        rotation,
        northVec,
        eastVec,
        aSqr,
        ab,
        bSqr,
        mag,
        unitPos,
        reflectedPosition
      );

      if (addFillPositions) {
        positions[positionIndex++] = position.x;
        positions[positionIndex++] = position.y;
        positions[positionIndex++] = position.z;

        numInterior = 2 * (i - 1) + 2;
        for (j = 1; j < numInterior - 1; ++j) {
          t = j / (numInterior - 1);
          interiorPosition = Cartesian3.lerp(
            position,
            reflectedPosition,
            t,
            scratchCartesian3$b
          );
          positions[positionIndex++] = interiorPosition.x;
          positions[positionIndex++] = interiorPosition.y;
          positions[positionIndex++] = interiorPosition.z;
        }

        positions[positionIndex++] = reflectedPosition.x;
        positions[positionIndex++] = reflectedPosition.y;
        positions[positionIndex++] = reflectedPosition.z;
      }

      if (addEdgePositions) {
        outerPositions[outerRightIndex--] = position.z;
        outerPositions[outerRightIndex--] = position.y;
        outerPositions[outerRightIndex--] = position.x;
        outerPositions[outerLeftIndex++] = reflectedPosition.x;
        outerPositions[outerLeftIndex++] = reflectedPosition.y;
        outerPositions[outerLeftIndex++] = reflectedPosition.z;
      }
    }

    theta = CesiumMath.PI_OVER_TWO;
    position = pointOnEllipsoid(
      -theta,
      rotation,
      northVec,
      eastVec,
      aSqr,
      ab,
      bSqr,
      mag,
      unitPos,
      position
    );

    const r = {};
    if (addFillPositions) {
      positions[positionIndex++] = position.x;
      positions[positionIndex++] = position.y;
      positions[positionIndex++] = position.z;
      r.positions = positions;
      r.numPts = numPts;
    }
    if (addEdgePositions) {
      outerPositions[outerRightIndex--] = position.z;
      outerPositions[outerRightIndex--] = position.y;
      outerPositions[outerRightIndex--] = position.x;
      r.outerPositions = outerPositions;
    }

    return r;
  };

  /**
   * Geometry instancing allows one {@link Geometry} object to be positions in several
   * different locations and colored uniquely.  For example, one {@link BoxGeometry} can
   * be instanced several times, each with a different <code>modelMatrix</code> to change
   * its position, rotation, and scale.
   *
   * @alias GeometryInstance
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Geometry|GeometryFactory} options.geometry The geometry to instance.
   * @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] The model matrix that transforms to transform the geometry from model to world coordinates.
   * @param {Object} [options.id] A user-defined object to return when the instance is picked with {@link Scene#pick} or get/set per-instance attributes with {@link Primitive#getGeometryInstanceAttributes}.
   * @param {Object} [options.attributes] Per-instance attributes like a show or color attribute shown in the example below.
   *
   *
   * @example
   * // Create geometry for a box, and two instances that refer to it.
   * // One instance positions the box on the bottom and colored aqua.
   * // The other instance positions the box on the top and color white.
   * const geometry = Cesium.BoxGeometry.fromDimensions({
   *   vertexFormat : Cesium.VertexFormat.POSITION_AND_NORMAL,
   *   dimensions : new Cesium.Cartesian3(1000000.0, 1000000.0, 500000.0)
   * });
   * const instanceBottom = new Cesium.GeometryInstance({
   *   geometry : geometry,
   *   modelMatrix : Cesium.Matrix4.multiplyByTranslation(Cesium.Transforms.eastNorthUpToFixedFrame(
   *     Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883)), new Cesium.Cartesian3(0.0, 0.0, 1000000.0), new Cesium.Matrix4()),
   *   attributes : {
   *     color : Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.AQUA)
   *   },
   *   id : 'bottom'
   * });
   * const instanceTop = new Cesium.GeometryInstance({
   *   geometry : geometry,
   *   modelMatrix : Cesium.Matrix4.multiplyByTranslation(Cesium.Transforms.eastNorthUpToFixedFrame(
   *     Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883)), new Cesium.Cartesian3(0.0, 0.0, 3000000.0), new Cesium.Matrix4()),
   *   attributes : {
   *     color : Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.AQUA)
   *   },
   *   id : 'top'
   * });
   *
   * @see Geometry
   */
  function GeometryInstance(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    if (!defined(options.geometry)) {
      throw new DeveloperError("options.geometry is required.");
    }
    //>>includeEnd('debug');

    /**
     * The geometry being instanced.
     *
     * @type Geometry
     *
     * @default undefined
     */
    this.geometry = options.geometry;

    /**
     * The 4x4 transformation matrix that transforms the geometry from model to world coordinates.
     * When this is the identity matrix, the geometry is drawn in world coordinates, i.e., Earth's WGS84 coordinates.
     * Local reference frames can be used by providing a different transformation matrix, like that returned
     * by {@link Transforms.eastNorthUpToFixedFrame}.
     *
     * @type Matrix4
     *
     * @default Matrix4.IDENTITY
     */
    this.modelMatrix = Matrix4.clone(
      defaultValue(options.modelMatrix, Matrix4.IDENTITY)
    );

    /**
     * User-defined object returned when the instance is picked or used to get/set per-instance attributes.
     *
     * @type Object
     *
     * @default undefined
     *
     * @see Scene#pick
     * @see Primitive#getGeometryInstanceAttributes
     */
    this.id = options.id;

    /**
     * Used for picking primitives that wrap geometry instances.
     *
     * @private
     */
    this.pickPrimitive = options.pickPrimitive;

    /**
     * Per-instance attributes like {@link ColorGeometryInstanceAttribute} or {@link ShowGeometryInstanceAttribute}.
     * {@link Geometry} attributes varying per vertex; these attributes are constant for the entire instance.
     *
     * @type Object
     *
     * @default undefined
     */
    this.attributes = defaultValue(options.attributes, {});

    /**
     * @private
     */
    this.westHemisphereGeometry = undefined;
    /**
     * @private
     */
    this.eastHemisphereGeometry = undefined;
  }

  const scratchCartesian1$6 = new Cartesian3();
  const scratchCartesian2$9 = new Cartesian3();
  const scratchCartesian3$a = new Cartesian3();

  /**
   * Computes the barycentric coordinates for a point with respect to a triangle.
   *
   * @function
   *
   * @param {Cartesian2|Cartesian3} point The point to test.
   * @param {Cartesian2|Cartesian3} p0 The first point of the triangle, corresponding to the barycentric x-axis.
   * @param {Cartesian2|Cartesian3} p1 The second point of the triangle, corresponding to the barycentric y-axis.
   * @param {Cartesian2|Cartesian3} p2 The third point of the triangle, corresponding to the barycentric z-axis.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3|undefined} The modified result parameter or a new Cartesian3 instance if one was not provided. If the triangle is degenerate the function will return undefined.
   *
   * @example
   * // Returns Cartesian3.UNIT_X
   * const p = new Cesium.Cartesian3(-1.0, 0.0, 0.0);
   * const b = Cesium.barycentricCoordinates(p,
   *   new Cesium.Cartesian3(-1.0, 0.0, 0.0),
   *   new Cesium.Cartesian3( 1.0, 0.0, 0.0),
   *   new Cesium.Cartesian3( 0.0, 1.0, 1.0));
   */
  function barycentricCoordinates(point, p0, p1, p2, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("point", point);
    Check.defined("p0", p0);
    Check.defined("p1", p1);
    Check.defined("p2", p2);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Cartesian3();
    }

    // Implementation based on http://www.blackpawn.com/texts/pointinpoly/default.html.
    let v0;
    let v1;
    let v2;
    let dot00;
    let dot01;
    let dot02;
    let dot11;
    let dot12;

    if (!defined(p0.z)) {
      if (Cartesian2.equalsEpsilon(point, p0, CesiumMath.EPSILON14)) {
        return Cartesian3.clone(Cartesian3.UNIT_X, result);
      }
      if (Cartesian2.equalsEpsilon(point, p1, CesiumMath.EPSILON14)) {
        return Cartesian3.clone(Cartesian3.UNIT_Y, result);
      }
      if (Cartesian2.equalsEpsilon(point, p2, CesiumMath.EPSILON14)) {
        return Cartesian3.clone(Cartesian3.UNIT_Z, result);
      }

      v0 = Cartesian2.subtract(p1, p0, scratchCartesian1$6);
      v1 = Cartesian2.subtract(p2, p0, scratchCartesian2$9);
      v2 = Cartesian2.subtract(point, p0, scratchCartesian3$a);

      dot00 = Cartesian2.dot(v0, v0);
      dot01 = Cartesian2.dot(v0, v1);
      dot02 = Cartesian2.dot(v0, v2);
      dot11 = Cartesian2.dot(v1, v1);
      dot12 = Cartesian2.dot(v1, v2);
    } else {
      if (Cartesian3.equalsEpsilon(point, p0, CesiumMath.EPSILON14)) {
        return Cartesian3.clone(Cartesian3.UNIT_X, result);
      }
      if (Cartesian3.equalsEpsilon(point, p1, CesiumMath.EPSILON14)) {
        return Cartesian3.clone(Cartesian3.UNIT_Y, result);
      }
      if (Cartesian3.equalsEpsilon(point, p2, CesiumMath.EPSILON14)) {
        return Cartesian3.clone(Cartesian3.UNIT_Z, result);
      }

      v0 = Cartesian3.subtract(p1, p0, scratchCartesian1$6);
      v1 = Cartesian3.subtract(p2, p0, scratchCartesian2$9);
      v2 = Cartesian3.subtract(point, p0, scratchCartesian3$a);

      dot00 = Cartesian3.dot(v0, v0);
      dot01 = Cartesian3.dot(v0, v1);
      dot02 = Cartesian3.dot(v0, v2);
      dot11 = Cartesian3.dot(v1, v1);
      dot12 = Cartesian3.dot(v1, v2);
    }

    result.y = dot11 * dot02 - dot01 * dot12;
    result.z = dot00 * dot12 - dot01 * dot02;
    const q = dot00 * dot11 - dot01 * dot01;

    // Triangle is degenerate
    if (q === 0) {
      return undefined;
    }

    result.y /= q;
    result.z /= q;
    result.x = 1.0 - result.y - result.z;
    return result;
  }

  /**
   * A fixed-point encoding of a {@link Cartesian3} with 64-bit floating-point components, as two {@link Cartesian3}
   * values that, when converted to 32-bit floating-point and added, approximate the original input.
   * <p>
   * This is used to encode positions in vertex buffers for rendering without jittering artifacts
   * as described in {@link http://help.agi.com/AGIComponents/html/BlogPrecisionsPrecisions.htm|Precisions, Precisions}.
   * </p>
   *
   * @alias EncodedCartesian3
   * @constructor
   *
   * @private
   */
  function EncodedCartesian3() {
    /**
     * The high bits for each component.  Bits 0 to 22 store the whole value.  Bits 23 to 31 are not used.
     *
     * @type {Cartesian3}
     * @default {@link Cartesian3.ZERO}
     */
    this.high = Cartesian3.clone(Cartesian3.ZERO);

    /**
     * The low bits for each component.  Bits 7 to 22 store the whole value, and bits 0 to 6 store the fraction.  Bits 23 to 31 are not used.
     *
     * @type {Cartesian3}
     * @default {@link Cartesian3.ZERO}
     */
    this.low = Cartesian3.clone(Cartesian3.ZERO);
  }

  /**
   * Encodes a 64-bit floating-point value as two floating-point values that, when converted to
   * 32-bit floating-point and added, approximate the original input.  The returned object
   * has <code>high</code> and <code>low</code> properties for the high and low bits, respectively.
   * <p>
   * The fixed-point encoding follows {@link http://help.agi.com/AGIComponents/html/BlogPrecisionsPrecisions.htm|Precisions, Precisions}.
   * </p>
   *
   * @param {Number} value The floating-point value to encode.
   * @param {Object} [result] The object onto which to store the result.
   * @returns {Object} The modified result parameter or a new instance if one was not provided.
   *
   * @example
   * const value = 1234567.1234567;
   * const splitValue = Cesium.EncodedCartesian3.encode(value);
   */
  EncodedCartesian3.encode = function (value, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("value", value);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = {
        high: 0.0,
        low: 0.0,
      };
    }

    let doubleHigh;
    if (value >= 0.0) {
      doubleHigh = Math.floor(value / 65536.0) * 65536.0;
      result.high = doubleHigh;
      result.low = value - doubleHigh;
    } else {
      doubleHigh = Math.floor(-value / 65536.0) * 65536.0;
      result.high = -doubleHigh;
      result.low = value + doubleHigh;
    }

    return result;
  };

  const scratchEncode = {
    high: 0.0,
    low: 0.0,
  };

  /**
   * Encodes a {@link Cartesian3} with 64-bit floating-point components as two {@link Cartesian3}
   * values that, when converted to 32-bit floating-point and added, approximate the original input.
   * <p>
   * The fixed-point encoding follows {@link https://help.agi.com/AGIComponents/html/BlogPrecisionsPrecisions.htm|Precisions, Precisions}.
   * </p>
   *
   * @param {Cartesian3} cartesian The cartesian to encode.
   * @param {EncodedCartesian3} [result] The object onto which to store the result.
   * @returns {EncodedCartesian3} The modified result parameter or a new EncodedCartesian3 instance if one was not provided.
   *
   * @example
   * const cart = new Cesium.Cartesian3(-10000000.0, 0.0, 10000000.0);
   * const encoded = Cesium.EncodedCartesian3.fromCartesian(cart);
   */
  EncodedCartesian3.fromCartesian = function (cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartesian", cartesian);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new EncodedCartesian3();
    }

    const high = result.high;
    const low = result.low;

    EncodedCartesian3.encode(cartesian.x, scratchEncode);
    high.x = scratchEncode.high;
    low.x = scratchEncode.low;

    EncodedCartesian3.encode(cartesian.y, scratchEncode);
    high.y = scratchEncode.high;
    low.y = scratchEncode.low;

    EncodedCartesian3.encode(cartesian.z, scratchEncode);
    high.z = scratchEncode.high;
    low.z = scratchEncode.low;

    return result;
  };

  const encodedP = new EncodedCartesian3();

  /**
   * Encodes the provided <code>cartesian</code>, and writes it to an array with <code>high</code>
   * components followed by <code>low</code> components, i.e. <code>[high.x, high.y, high.z, low.x, low.y, low.z]</code>.
   * <p>
   * This is used to create interleaved high-precision position vertex attributes.
   * </p>
   *
   * @param {Cartesian3} cartesian The cartesian to encode.
   * @param {Number[]} cartesianArray The array to write to.
   * @param {Number} index The index into the array to start writing.  Six elements will be written.
   *
   * @exception {DeveloperError} index must be a number greater than or equal to 0.
   *
   * @example
   * const positions = [
   *    new Cesium.Cartesian3(),
   *    // ...
   * ];
   * const encodedPositions = new Float32Array(2 * 3 * positions.length);
   * let j = 0;
   * for (let i = 0; i < positions.length; ++i) {
   *   Cesium.EncodedCartesian3.writeElement(positions[i], encodedPositions, j);
   *   j += 6;
   * }
   */
  EncodedCartesian3.writeElements = function (cartesian, cartesianArray, index) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("cartesianArray", cartesianArray);
    Check.typeOf.number("index", index);
    Check.typeOf.number.greaterThanOrEquals("index", index, 0);
    //>>includeEnd('debug');

    EncodedCartesian3.fromCartesian(cartesian, encodedP);
    const high = encodedP.high;
    const low = encodedP.low;

    cartesianArray[index] = high.x;
    cartesianArray[index + 1] = high.y;
    cartesianArray[index + 2] = high.z;
    cartesianArray[index + 3] = low.x;
    cartesianArray[index + 4] = low.y;
    cartesianArray[index + 5] = low.z;
  };

  /**
   * Encapsulates an algorithm to optimize triangles for the post
   * vertex-shader cache.  This is based on the 2007 SIGGRAPH paper
   * 'Fast Triangle Reordering for Vertex Locality and Reduced Overdraw.'
   * The runtime is linear but several passes are made.
   *
   * @namespace Tipsify
   *
   * @see <a href='http://gfx.cs.princeton.edu/pubs/Sander_2007_%3ETR/tipsy.pdf'>
   * Fast Triangle Reordering for Vertex Locality and Reduced Overdraw</a>
   * by Sander, Nehab, and Barczak
   *
   * @private
   */
  const Tipsify = {};

  /**
   * Calculates the average cache miss ratio (ACMR) for a given set of indices.
   *
   * @param {Object} options Object with the following properties:
   * @param {Number[]} options.indices Lists triads of numbers corresponding to the indices of the vertices
   *                        in the vertex buffer that define the geometry's triangles.
   * @param {Number} [options.maximumIndex] The maximum value of the elements in <code>args.indices</code>.
   *                                     If not supplied, this value will be computed.
   * @param {Number} [options.cacheSize=24] The number of vertices that can be stored in the cache at any one time.
   * @returns {Number} The average cache miss ratio (ACMR).
   *
   * @exception {DeveloperError} indices length must be a multiple of three.
   * @exception {DeveloperError} cacheSize must be greater than two.
   *
   * @example
   * const indices = [0, 1, 2, 3, 4, 5];
   * const maxIndex = 5;
   * const cacheSize = 3;
   * const acmr = Cesium.Tipsify.calculateACMR({indices : indices, maxIndex : maxIndex, cacheSize : cacheSize});
   */
  Tipsify.calculateACMR = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const indices = options.indices;
    let maximumIndex = options.maximumIndex;
    const cacheSize = defaultValue(options.cacheSize, 24);

    //>>includeStart('debug', pragmas.debug);
    if (!defined(indices)) {
      throw new DeveloperError("indices is required.");
    }
    //>>includeEnd('debug');

    const numIndices = indices.length;

    //>>includeStart('debug', pragmas.debug);
    if (numIndices < 3 || numIndices % 3 !== 0) {
      throw new DeveloperError("indices length must be a multiple of three.");
    }
    if (maximumIndex <= 0) {
      throw new DeveloperError("maximumIndex must be greater than zero.");
    }
    if (cacheSize < 3) {
      throw new DeveloperError("cacheSize must be greater than two.");
    }
    //>>includeEnd('debug');

    // Compute the maximumIndex if not given
    if (!defined(maximumIndex)) {
      maximumIndex = 0;
      let currentIndex = 0;
      let intoIndices = indices[currentIndex];
      while (currentIndex < numIndices) {
        if (intoIndices > maximumIndex) {
          maximumIndex = intoIndices;
        }
        ++currentIndex;
        intoIndices = indices[currentIndex];
      }
    }

    // Vertex time stamps
    const vertexTimeStamps = [];
    for (let i = 0; i < maximumIndex + 1; i++) {
      vertexTimeStamps[i] = 0;
    }

    // Cache processing
    let s = cacheSize + 1;
    for (let j = 0; j < numIndices; ++j) {
      if (s - vertexTimeStamps[indices[j]] > cacheSize) {
        vertexTimeStamps[indices[j]] = s;
        ++s;
      }
    }

    return (s - cacheSize + 1) / (numIndices / 3);
  };

  /**
   * Optimizes triangles for the post-vertex shader cache.
   *
   * @param {Object} options Object with the following properties:
   * @param {Number[]} options.indices Lists triads of numbers corresponding to the indices of the vertices
   *                        in the vertex buffer that define the geometry's triangles.
   * @param {Number} [options.maximumIndex] The maximum value of the elements in <code>args.indices</code>.
   *                                     If not supplied, this value will be computed.
   * @param {Number} [options.cacheSize=24] The number of vertices that can be stored in the cache at any one time.
   * @returns {Number[]} A list of the input indices in an optimized order.
   *
   * @exception {DeveloperError} indices length must be a multiple of three.
   * @exception {DeveloperError} cacheSize must be greater than two.
   *
   * @example
   * const indices = [0, 1, 2, 3, 4, 5];
   * const maxIndex = 5;
   * const cacheSize = 3;
   * const reorderedIndices = Cesium.Tipsify.tipsify({indices : indices, maxIndex : maxIndex, cacheSize : cacheSize});
   */
  Tipsify.tipsify = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const indices = options.indices;
    const maximumIndex = options.maximumIndex;
    const cacheSize = defaultValue(options.cacheSize, 24);

    let cursor;

    function skipDeadEnd(vertices, deadEnd, indices, maximumIndexPlusOne) {
      while (deadEnd.length >= 1) {
        // while the stack is not empty
        const d = deadEnd[deadEnd.length - 1]; // top of the stack
        deadEnd.splice(deadEnd.length - 1, 1); // pop the stack

        if (vertices[d].numLiveTriangles > 0) {
          return d;
        }
      }

      while (cursor < maximumIndexPlusOne) {
        if (vertices[cursor].numLiveTriangles > 0) {
          ++cursor;
          return cursor - 1;
        }
        ++cursor;
      }
      return -1;
    }

    function getNextVertex(
      indices,
      cacheSize,
      oneRing,
      vertices,
      s,
      deadEnd,
      maximumIndexPlusOne
    ) {
      let n = -1;
      let p;
      let m = -1;
      let itOneRing = 0;
      while (itOneRing < oneRing.length) {
        const index = oneRing[itOneRing];
        if (vertices[index].numLiveTriangles) {
          p = 0;
          if (
            s -
              vertices[index].timeStamp +
              2 * vertices[index].numLiveTriangles <=
            cacheSize
          ) {
            p = s - vertices[index].timeStamp;
          }
          if (p > m || m === -1) {
            m = p;
            n = index;
          }
        }
        ++itOneRing;
      }
      if (n === -1) {
        return skipDeadEnd(vertices, deadEnd, indices, maximumIndexPlusOne);
      }
      return n;
    }

    //>>includeStart('debug', pragmas.debug);
    if (!defined(indices)) {
      throw new DeveloperError("indices is required.");
    }
    //>>includeEnd('debug');

    const numIndices = indices.length;

    //>>includeStart('debug', pragmas.debug);
    if (numIndices < 3 || numIndices % 3 !== 0) {
      throw new DeveloperError("indices length must be a multiple of three.");
    }
    if (maximumIndex <= 0) {
      throw new DeveloperError("maximumIndex must be greater than zero.");
    }
    if (cacheSize < 3) {
      throw new DeveloperError("cacheSize must be greater than two.");
    }
    //>>includeEnd('debug');

    // Determine maximum index
    let maximumIndexPlusOne = 0;
    let currentIndex = 0;
    let intoIndices = indices[currentIndex];
    const endIndex = numIndices;
    if (defined(maximumIndex)) {
      maximumIndexPlusOne = maximumIndex + 1;
    } else {
      while (currentIndex < endIndex) {
        if (intoIndices > maximumIndexPlusOne) {
          maximumIndexPlusOne = intoIndices;
        }
        ++currentIndex;
        intoIndices = indices[currentIndex];
      }
      if (maximumIndexPlusOne === -1) {
        return 0;
      }
      ++maximumIndexPlusOne;
    }

    // Vertices
    const vertices = [];
    let i;
    for (i = 0; i < maximumIndexPlusOne; i++) {
      vertices[i] = {
        numLiveTriangles: 0,
        timeStamp: 0,
        vertexTriangles: [],
      };
    }
    currentIndex = 0;
    let triangle = 0;
    while (currentIndex < endIndex) {
      vertices[indices[currentIndex]].vertexTriangles.push(triangle);
      ++vertices[indices[currentIndex]].numLiveTriangles;
      vertices[indices[currentIndex + 1]].vertexTriangles.push(triangle);
      ++vertices[indices[currentIndex + 1]].numLiveTriangles;
      vertices[indices[currentIndex + 2]].vertexTriangles.push(triangle);
      ++vertices[indices[currentIndex + 2]].numLiveTriangles;
      ++triangle;
      currentIndex += 3;
    }

    // Starting index
    let f = 0;

    // Time Stamp
    let s = cacheSize + 1;
    cursor = 1;

    // Process
    let oneRing = [];
    const deadEnd = []; //Stack
    let vertex;
    let intoVertices;
    let currentOutputIndex = 0;
    const outputIndices = [];
    const numTriangles = numIndices / 3;
    const triangleEmitted = [];
    for (i = 0; i < numTriangles; i++) {
      triangleEmitted[i] = false;
    }
    let index;
    let limit;
    while (f !== -1) {
      oneRing = [];
      intoVertices = vertices[f];
      limit = intoVertices.vertexTriangles.length;
      for (let k = 0; k < limit; ++k) {
        triangle = intoVertices.vertexTriangles[k];
        if (!triangleEmitted[triangle]) {
          triangleEmitted[triangle] = true;
          currentIndex = triangle + triangle + triangle;
          for (let j = 0; j < 3; ++j) {
            // Set this index as a possible next index
            index = indices[currentIndex];
            oneRing.push(index);
            deadEnd.push(index);

            // Output index
            outputIndices[currentOutputIndex] = index;
            ++currentOutputIndex;

            // Cache processing
            vertex = vertices[index];
            --vertex.numLiveTriangles;
            if (s - vertex.timeStamp > cacheSize) {
              vertex.timeStamp = s;
              ++s;
            }
            ++currentIndex;
          }
        }
      }
      f = getNextVertex(
        indices,
        cacheSize,
        oneRing,
        vertices,
        s,
        deadEnd,
        maximumIndexPlusOne
      );
    }

    return outputIndices;
  };

  /**
   * Content pipeline functions for geometries.
   *
   * @namespace GeometryPipeline
   *
   * @see Geometry
   */
  const GeometryPipeline = {};

  function addTriangle(lines, index, i0, i1, i2) {
    lines[index++] = i0;
    lines[index++] = i1;

    lines[index++] = i1;
    lines[index++] = i2;

    lines[index++] = i2;
    lines[index] = i0;
  }

  function trianglesToLines(triangles) {
    const count = triangles.length;
    const size = (count / 3) * 6;
    const lines = IndexDatatype$1.createTypedArray(count, size);

    let index = 0;
    for (let i = 0; i < count; i += 3, index += 6) {
      addTriangle(lines, index, triangles[i], triangles[i + 1], triangles[i + 2]);
    }

    return lines;
  }

  function triangleStripToLines(triangles) {
    const count = triangles.length;
    if (count >= 3) {
      const size = (count - 2) * 6;
      const lines = IndexDatatype$1.createTypedArray(count, size);

      addTriangle(lines, 0, triangles[0], triangles[1], triangles[2]);
      let index = 6;

      for (let i = 3; i < count; ++i, index += 6) {
        addTriangle(
          lines,
          index,
          triangles[i - 1],
          triangles[i],
          triangles[i - 2]
        );
      }

      return lines;
    }

    return new Uint16Array();
  }

  function triangleFanToLines(triangles) {
    if (triangles.length > 0) {
      const count = triangles.length - 1;
      const size = (count - 1) * 6;
      const lines = IndexDatatype$1.createTypedArray(count, size);

      const base = triangles[0];
      let index = 0;
      for (let i = 1; i < count; ++i, index += 6) {
        addTriangle(lines, index, base, triangles[i], triangles[i + 1]);
      }

      return lines;
    }

    return new Uint16Array();
  }

  /**
   * Converts a geometry's triangle indices to line indices.  If the geometry has an <code>indices</code>
   * and its <code>primitiveType</code> is <code>TRIANGLES</code>, <code>TRIANGLE_STRIP</code>,
   * <code>TRIANGLE_FAN</code>, it is converted to <code>LINES</code>; otherwise, the geometry is not changed.
   * <p>
   * This is commonly used to create a wireframe geometry for visual debugging.
   * </p>
   *
   * @param {Geometry} geometry The geometry to modify.
   * @returns {Geometry} The modified <code>geometry</code> argument, with its triangle indices converted to lines.
   *
   * @exception {DeveloperError} geometry.primitiveType must be TRIANGLES, TRIANGLE_STRIP, or TRIANGLE_FAN.
   *
   * @example
   * geometry = Cesium.GeometryPipeline.toWireframe(geometry);
   */
  GeometryPipeline.toWireframe = function (geometry) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(geometry)) {
      throw new DeveloperError("geometry is required.");
    }
    //>>includeEnd('debug');

    const indices = geometry.indices;
    if (defined(indices)) {
      switch (geometry.primitiveType) {
        case PrimitiveType$1.TRIANGLES:
          geometry.indices = trianglesToLines(indices);
          break;
        case PrimitiveType$1.TRIANGLE_STRIP:
          geometry.indices = triangleStripToLines(indices);
          break;
        case PrimitiveType$1.TRIANGLE_FAN:
          geometry.indices = triangleFanToLines(indices);
          break;
        //>>includeStart('debug', pragmas.debug);
        default:
          throw new DeveloperError(
            "geometry.primitiveType must be TRIANGLES, TRIANGLE_STRIP, or TRIANGLE_FAN."
          );
        //>>includeEnd('debug');
      }

      geometry.primitiveType = PrimitiveType$1.LINES;
    }

    return geometry;
  };

  /**
   * Creates a new {@link Geometry} with <code>LINES</code> representing the provided
   * attribute (<code>attributeName</code>) for the provided geometry.  This is used to
   * visualize vector attributes like normals, tangents, and bitangents.
   *
   * @param {Geometry} geometry The <code>Geometry</code> instance with the attribute.
   * @param {String} [attributeName='normal'] The name of the attribute.
   * @param {Number} [length=10000.0] The length of each line segment in meters.  This can be negative to point the vector in the opposite direction.
   * @returns {Geometry} A new <code>Geometry</code> instance with line segments for the vector.
   *
   * @exception {DeveloperError} geometry.attributes must have an attribute with the same name as the attributeName parameter.
   *
   * @example
   * const geometry = Cesium.GeometryPipeline.createLineSegmentsForVectors(instance.geometry, 'bitangent', 100000.0);
   */
  GeometryPipeline.createLineSegmentsForVectors = function (
    geometry,
    attributeName,
    length
  ) {
    attributeName = defaultValue(attributeName, "normal");

    //>>includeStart('debug', pragmas.debug);
    if (!defined(geometry)) {
      throw new DeveloperError("geometry is required.");
    }
    if (!defined(geometry.attributes.position)) {
      throw new DeveloperError("geometry.attributes.position is required.");
    }
    if (!defined(geometry.attributes[attributeName])) {
      throw new DeveloperError(
        `geometry.attributes must have an attribute with the same name as the attributeName parameter, ${attributeName}.`
      );
    }
    //>>includeEnd('debug');

    length = defaultValue(length, 10000.0);

    const positions = geometry.attributes.position.values;
    const vectors = geometry.attributes[attributeName].values;
    const positionsLength = positions.length;

    const newPositions = new Float64Array(2 * positionsLength);

    let j = 0;
    for (let i = 0; i < positionsLength; i += 3) {
      newPositions[j++] = positions[i];
      newPositions[j++] = positions[i + 1];
      newPositions[j++] = positions[i + 2];

      newPositions[j++] = positions[i] + vectors[i] * length;
      newPositions[j++] = positions[i + 1] + vectors[i + 1] * length;
      newPositions[j++] = positions[i + 2] + vectors[i + 2] * length;
    }

    let newBoundingSphere;
    const bs = geometry.boundingSphere;
    if (defined(bs)) {
      newBoundingSphere = new BoundingSphere(bs.center, bs.radius + length);
    }

    return new Geometry({
      attributes: {
        position: new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.DOUBLE,
          componentsPerAttribute: 3,
          values: newPositions,
        }),
      },
      primitiveType: PrimitiveType$1.LINES,
      boundingSphere: newBoundingSphere,
    });
  };

  /**
   * Creates an object that maps attribute names to unique locations (indices)
   * for matching vertex attributes and shader programs.
   *
   * @param {Geometry} geometry The geometry, which is not modified, to create the object for.
   * @returns {Object} An object with attribute name / index pairs.
   *
   * @example
   * const attributeLocations = Cesium.GeometryPipeline.createAttributeLocations(geometry);
   * // Example output
   * // {
   * //   'position' : 0,
   * //   'normal' : 1
   * // }
   */
  GeometryPipeline.createAttributeLocations = function (geometry) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(geometry)) {
      throw new DeveloperError("geometry is required.");
    }
    //>>includeEnd('debug')

    // There can be a WebGL performance hit when attribute 0 is disabled, so
    // assign attribute locations to well-known attributes.
    const semantics = [
      "position",
      "positionHigh",
      "positionLow",

      // From VertexFormat.position - after 2D projection and high-precision encoding
      "position3DHigh",
      "position3DLow",
      "position2DHigh",
      "position2DLow",

      // From Primitive
      "pickColor",

      // From VertexFormat
      "normal",
      "st",
      "tangent",
      "bitangent",

      // For shadow volumes
      "extrudeDirection",

      // From compressing texture coordinates and normals
      "compressedAttributes",
    ];

    const attributes = geometry.attributes;
    const indices = {};
    let j = 0;
    let i;
    const len = semantics.length;

    // Attribute locations for well-known attributes
    for (i = 0; i < len; ++i) {
      const semantic = semantics[i];

      if (defined(attributes[semantic])) {
        indices[semantic] = j++;
      }
    }

    // Locations for custom attributes
    for (const name in attributes) {
      if (attributes.hasOwnProperty(name) && !defined(indices[name])) {
        indices[name] = j++;
      }
    }

    return indices;
  };

  /**
   * Reorders a geometry's attributes and <code>indices</code> to achieve better performance from the GPU's pre-vertex-shader cache.
   *
   * @param {Geometry} geometry The geometry to modify.
   * @returns {Geometry} The modified <code>geometry</code> argument, with its attributes and indices reordered for the GPU's pre-vertex-shader cache.
   *
   * @exception {DeveloperError} Each attribute array in geometry.attributes must have the same number of attributes.
   *
   *
   * @example
   * geometry = Cesium.GeometryPipeline.reorderForPreVertexCache(geometry);
   *
   * @see GeometryPipeline.reorderForPostVertexCache
   */
  GeometryPipeline.reorderForPreVertexCache = function (geometry) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(geometry)) {
      throw new DeveloperError("geometry is required.");
    }
    //>>includeEnd('debug');

    const numVertices = Geometry.computeNumberOfVertices(geometry);

    const indices = geometry.indices;
    if (defined(indices)) {
      const indexCrossReferenceOldToNew = new Int32Array(numVertices);
      for (let i = 0; i < numVertices; i++) {
        indexCrossReferenceOldToNew[i] = -1;
      }

      // Construct cross reference and reorder indices
      const indicesIn = indices;
      const numIndices = indicesIn.length;
      const indicesOut = IndexDatatype$1.createTypedArray(numVertices, numIndices);

      let intoIndicesIn = 0;
      let intoIndicesOut = 0;
      let nextIndex = 0;
      let tempIndex;
      while (intoIndicesIn < numIndices) {
        tempIndex = indexCrossReferenceOldToNew[indicesIn[intoIndicesIn]];
        if (tempIndex !== -1) {
          indicesOut[intoIndicesOut] = tempIndex;
        } else {
          tempIndex = indicesIn[intoIndicesIn];
          indexCrossReferenceOldToNew[tempIndex] = nextIndex;

          indicesOut[intoIndicesOut] = nextIndex;
          ++nextIndex;
        }
        ++intoIndicesIn;
        ++intoIndicesOut;
      }
      geometry.indices = indicesOut;

      // Reorder attributes
      const attributes = geometry.attributes;
      for (const property in attributes) {
        if (
          attributes.hasOwnProperty(property) &&
          defined(attributes[property]) &&
          defined(attributes[property].values)
        ) {
          const attribute = attributes[property];
          const elementsIn = attribute.values;
          let intoElementsIn = 0;
          const numComponents = attribute.componentsPerAttribute;
          const elementsOut = ComponentDatatype$1.createTypedArray(
            attribute.componentDatatype,
            nextIndex * numComponents
          );
          while (intoElementsIn < numVertices) {
            const temp = indexCrossReferenceOldToNew[intoElementsIn];
            if (temp !== -1) {
              for (let j = 0; j < numComponents; j++) {
                elementsOut[numComponents * temp + j] =
                  elementsIn[numComponents * intoElementsIn + j];
              }
            }
            ++intoElementsIn;
          }
          attribute.values = elementsOut;
        }
      }
    }

    return geometry;
  };

  /**
   * Reorders a geometry's <code>indices</code> to achieve better performance from the GPU's
   * post vertex-shader cache by using the Tipsify algorithm.  If the geometry <code>primitiveType</code>
   * is not <code>TRIANGLES</code> or the geometry does not have an <code>indices</code>, this function has no effect.
   *
   * @param {Geometry} geometry The geometry to modify.
   * @param {Number} [cacheCapacity=24] The number of vertices that can be held in the GPU's vertex cache.
   * @returns {Geometry} The modified <code>geometry</code> argument, with its indices reordered for the post-vertex-shader cache.
   *
   * @exception {DeveloperError} cacheCapacity must be greater than two.
   *
   *
   * @example
   * geometry = Cesium.GeometryPipeline.reorderForPostVertexCache(geometry);
   *
   * @see GeometryPipeline.reorderForPreVertexCache
   * @see {@link http://gfx.cs.princ0eton.edu/pubs/Sander_2007_%3ETR/tipsy.pdf|Fast Triangle Reordering for Vertex Locality and Reduced Overdraw}
   * by Sander, Nehab, and Barczak
   */
  GeometryPipeline.reorderForPostVertexCache = function (
    geometry,
    cacheCapacity
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(geometry)) {
      throw new DeveloperError("geometry is required.");
    }
    //>>includeEnd('debug');

    const indices = geometry.indices;
    if (geometry.primitiveType === PrimitiveType$1.TRIANGLES && defined(indices)) {
      const numIndices = indices.length;
      let maximumIndex = 0;
      for (let j = 0; j < numIndices; j++) {
        if (indices[j] > maximumIndex) {
          maximumIndex = indices[j];
        }
      }
      geometry.indices = Tipsify.tipsify({
        indices: indices,
        maximumIndex: maximumIndex,
        cacheSize: cacheCapacity,
      });
    }

    return geometry;
  };

  function copyAttributesDescriptions(attributes) {
    const newAttributes = {};

    for (const attribute in attributes) {
      if (
        attributes.hasOwnProperty(attribute) &&
        defined(attributes[attribute]) &&
        defined(attributes[attribute].values)
      ) {
        const attr = attributes[attribute];
        newAttributes[attribute] = new GeometryAttribute({
          componentDatatype: attr.componentDatatype,
          componentsPerAttribute: attr.componentsPerAttribute,
          normalize: attr.normalize,
          values: [],
        });
      }
    }

    return newAttributes;
  }

  function copyVertex(destinationAttributes, sourceAttributes, index) {
    for (const attribute in sourceAttributes) {
      if (
        sourceAttributes.hasOwnProperty(attribute) &&
        defined(sourceAttributes[attribute]) &&
        defined(sourceAttributes[attribute].values)
      ) {
        const attr = sourceAttributes[attribute];

        for (let k = 0; k < attr.componentsPerAttribute; ++k) {
          destinationAttributes[attribute].values.push(
            attr.values[index * attr.componentsPerAttribute + k]
          );
        }
      }
    }
  }

  /**
   * Splits a geometry into multiple geometries, if necessary, to ensure that indices in the
   * <code>indices</code> fit into unsigned shorts.  This is used to meet the WebGL requirements
   * when unsigned int indices are not supported.
   * <p>
   * If the geometry does not have any <code>indices</code>, this function has no effect.
   * </p>
   *
   * @param {Geometry} geometry The geometry to be split into multiple geometries.
   * @returns {Geometry[]} An array of geometries, each with indices that fit into unsigned shorts.
   *
   * @exception {DeveloperError} geometry.primitiveType must equal to PrimitiveType.TRIANGLES, PrimitiveType.LINES, or PrimitiveType.POINTS
   * @exception {DeveloperError} All geometry attribute lists must have the same number of attributes.
   *
   * @example
   * const geometries = Cesium.GeometryPipeline.fitToUnsignedShortIndices(geometry);
   */
  GeometryPipeline.fitToUnsignedShortIndices = function (geometry) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(geometry)) {
      throw new DeveloperError("geometry is required.");
    }
    if (
      defined(geometry.indices) &&
      geometry.primitiveType !== PrimitiveType$1.TRIANGLES &&
      geometry.primitiveType !== PrimitiveType$1.LINES &&
      geometry.primitiveType !== PrimitiveType$1.POINTS
    ) {
      throw new DeveloperError(
        "geometry.primitiveType must equal to PrimitiveType.TRIANGLES, PrimitiveType.LINES, or PrimitiveType.POINTS."
      );
    }
    //>>includeEnd('debug');

    const geometries = [];

    // If there's an index list and more than 64K attributes, it is possible that
    // some indices are outside the range of unsigned short [0, 64K - 1]
    const numberOfVertices = Geometry.computeNumberOfVertices(geometry);
    if (
      defined(geometry.indices) &&
      numberOfVertices >= CesiumMath.SIXTY_FOUR_KILOBYTES
    ) {
      let oldToNewIndex = [];
      let newIndices = [];
      let currentIndex = 0;
      let newAttributes = copyAttributesDescriptions(geometry.attributes);

      const originalIndices = geometry.indices;
      const numberOfIndices = originalIndices.length;

      let indicesPerPrimitive;

      if (geometry.primitiveType === PrimitiveType$1.TRIANGLES) {
        indicesPerPrimitive = 3;
      } else if (geometry.primitiveType === PrimitiveType$1.LINES) {
        indicesPerPrimitive = 2;
      } else if (geometry.primitiveType === PrimitiveType$1.POINTS) {
        indicesPerPrimitive = 1;
      }

      for (let j = 0; j < numberOfIndices; j += indicesPerPrimitive) {
        for (let k = 0; k < indicesPerPrimitive; ++k) {
          const x = originalIndices[j + k];
          let i = oldToNewIndex[x];
          if (!defined(i)) {
            i = currentIndex++;
            oldToNewIndex[x] = i;
            copyVertex(newAttributes, geometry.attributes, x);
          }
          newIndices.push(i);
        }

        if (
          currentIndex + indicesPerPrimitive >=
          CesiumMath.SIXTY_FOUR_KILOBYTES
        ) {
          geometries.push(
            new Geometry({
              attributes: newAttributes,
              indices: newIndices,
              primitiveType: geometry.primitiveType,
              boundingSphere: geometry.boundingSphere,
              boundingSphereCV: geometry.boundingSphereCV,
            })
          );

          // Reset for next vertex-array
          oldToNewIndex = [];
          newIndices = [];
          currentIndex = 0;
          newAttributes = copyAttributesDescriptions(geometry.attributes);
        }
      }

      if (newIndices.length !== 0) {
        geometries.push(
          new Geometry({
            attributes: newAttributes,
            indices: newIndices,
            primitiveType: geometry.primitiveType,
            boundingSphere: geometry.boundingSphere,
            boundingSphereCV: geometry.boundingSphereCV,
          })
        );
      }
    } else {
      // No need to split into multiple geometries
      geometries.push(geometry);
    }

    return geometries;
  };

  const scratchProjectTo2DCartesian3 = new Cartesian3();
  const scratchProjectTo2DCartographic = new Cartographic();

  /**
   * Projects a geometry's 3D <code>position</code> attribute to 2D, replacing the <code>position</code>
   * attribute with separate <code>position3D</code> and <code>position2D</code> attributes.
   * <p>
   * If the geometry does not have a <code>position</code>, this function has no effect.
   * </p>
   *
   * @param {Geometry} geometry The geometry to modify.
   * @param {String} attributeName The name of the attribute.
   * @param {String} attributeName3D The name of the attribute in 3D.
   * @param {String} attributeName2D The name of the attribute in 2D.
   * @param {Object} [projection=new GeographicProjection()] The projection to use.
   * @returns {Geometry} The modified <code>geometry</code> argument with <code>position3D</code> and <code>position2D</code> attributes.
   *
   * @exception {DeveloperError} geometry must have attribute matching the attributeName argument.
   * @exception {DeveloperError} The attribute componentDatatype must be ComponentDatatype.DOUBLE.
   * @exception {DeveloperError} Could not project a point to 2D.
   *
   * @example
   * geometry = Cesium.GeometryPipeline.projectTo2D(geometry, 'position', 'position3D', 'position2D');
   */
  GeometryPipeline.projectTo2D = function (
    geometry,
    attributeName,
    attributeName3D,
    attributeName2D,
    projection
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(geometry)) {
      throw new DeveloperError("geometry is required.");
    }
    if (!defined(attributeName)) {
      throw new DeveloperError("attributeName is required.");
    }
    if (!defined(attributeName3D)) {
      throw new DeveloperError("attributeName3D is required.");
    }
    if (!defined(attributeName2D)) {
      throw new DeveloperError("attributeName2D is required.");
    }
    if (!defined(geometry.attributes[attributeName])) {
      throw new DeveloperError(
        `geometry must have attribute matching the attributeName argument: ${attributeName}.`
      );
    }
    if (
      geometry.attributes[attributeName].componentDatatype !==
      ComponentDatatype$1.DOUBLE
    ) {
      throw new DeveloperError(
        "The attribute componentDatatype must be ComponentDatatype.DOUBLE."
      );
    }
    //>>includeEnd('debug');

    const attribute = geometry.attributes[attributeName];
    projection = defined(projection) ? projection : new GeographicProjection();
    const ellipsoid = projection.ellipsoid;

    // Project original values to 2D.
    const values3D = attribute.values;
    const projectedValues = new Float64Array(values3D.length);
    let index = 0;

    for (let i = 0; i < values3D.length; i += 3) {
      const value = Cartesian3.fromArray(
        values3D,
        i,
        scratchProjectTo2DCartesian3
      );

      const lonLat = ellipsoid.cartesianToCartographic(
        value,
        scratchProjectTo2DCartographic
      );
      //>>includeStart('debug', pragmas.debug);
      if (!defined(lonLat)) {
        throw new DeveloperError(
          `Could not project point (${value.x}, ${value.y}, ${value.z}) to 2D.`
        );
      }
      //>>includeEnd('debug');

      const projectedLonLat = projection.project(
        lonLat,
        scratchProjectTo2DCartesian3
      );

      projectedValues[index++] = projectedLonLat.x;
      projectedValues[index++] = projectedLonLat.y;
      projectedValues[index++] = projectedLonLat.z;
    }

    // Rename original cartesians to WGS84 cartesians.
    geometry.attributes[attributeName3D] = attribute;

    // Replace original cartesians with 2D projected cartesians
    geometry.attributes[attributeName2D] = new GeometryAttribute({
      componentDatatype: ComponentDatatype$1.DOUBLE,
      componentsPerAttribute: 3,
      values: projectedValues,
    });
    delete geometry.attributes[attributeName];

    return geometry;
  };

  const encodedResult = {
    high: 0.0,
    low: 0.0,
  };

  /**
   * Encodes floating-point geometry attribute values as two separate attributes to improve
   * rendering precision.
   * <p>
   * This is commonly used to create high-precision position vertex attributes.
   * </p>
   *
   * @param {Geometry} geometry The geometry to modify.
   * @param {String} attributeName The name of the attribute.
   * @param {String} attributeHighName The name of the attribute for the encoded high bits.
   * @param {String} attributeLowName The name of the attribute for the encoded low bits.
   * @returns {Geometry} The modified <code>geometry</code> argument, with its encoded attribute.
   *
   * @exception {DeveloperError} geometry must have attribute matching the attributeName argument.
   * @exception {DeveloperError} The attribute componentDatatype must be ComponentDatatype.DOUBLE.
   *
   * @example
   * geometry = Cesium.GeometryPipeline.encodeAttribute(geometry, 'position3D', 'position3DHigh', 'position3DLow');
   */
  GeometryPipeline.encodeAttribute = function (
    geometry,
    attributeName,
    attributeHighName,
    attributeLowName
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(geometry)) {
      throw new DeveloperError("geometry is required.");
    }
    if (!defined(attributeName)) {
      throw new DeveloperError("attributeName is required.");
    }
    if (!defined(attributeHighName)) {
      throw new DeveloperError("attributeHighName is required.");
    }
    if (!defined(attributeLowName)) {
      throw new DeveloperError("attributeLowName is required.");
    }
    if (!defined(geometry.attributes[attributeName])) {
      throw new DeveloperError(
        `geometry must have attribute matching the attributeName argument: ${attributeName}.`
      );
    }
    if (
      geometry.attributes[attributeName].componentDatatype !==
      ComponentDatatype$1.DOUBLE
    ) {
      throw new DeveloperError(
        "The attribute componentDatatype must be ComponentDatatype.DOUBLE."
      );
    }
    //>>includeEnd('debug');

    const attribute = geometry.attributes[attributeName];
    const values = attribute.values;
    const length = values.length;
    const highValues = new Float32Array(length);
    const lowValues = new Float32Array(length);

    for (let i = 0; i < length; ++i) {
      EncodedCartesian3.encode(values[i], encodedResult);
      highValues[i] = encodedResult.high;
      lowValues[i] = encodedResult.low;
    }

    const componentsPerAttribute = attribute.componentsPerAttribute;

    geometry.attributes[attributeHighName] = new GeometryAttribute({
      componentDatatype: ComponentDatatype$1.FLOAT,
      componentsPerAttribute: componentsPerAttribute,
      values: highValues,
    });
    geometry.attributes[attributeLowName] = new GeometryAttribute({
      componentDatatype: ComponentDatatype$1.FLOAT,
      componentsPerAttribute: componentsPerAttribute,
      values: lowValues,
    });
    delete geometry.attributes[attributeName];

    return geometry;
  };

  let scratchCartesian3$9 = new Cartesian3();

  function transformPoint(matrix, attribute) {
    if (defined(attribute)) {
      const values = attribute.values;
      const length = values.length;
      for (let i = 0; i < length; i += 3) {
        Cartesian3.unpack(values, i, scratchCartesian3$9);
        Matrix4.multiplyByPoint(matrix, scratchCartesian3$9, scratchCartesian3$9);
        Cartesian3.pack(scratchCartesian3$9, values, i);
      }
    }
  }

  function transformVector(matrix, attribute) {
    if (defined(attribute)) {
      const values = attribute.values;
      const length = values.length;
      for (let i = 0; i < length; i += 3) {
        Cartesian3.unpack(values, i, scratchCartesian3$9);
        Matrix3.multiplyByVector(matrix, scratchCartesian3$9, scratchCartesian3$9);
        scratchCartesian3$9 = Cartesian3.normalize(
          scratchCartesian3$9,
          scratchCartesian3$9
        );
        Cartesian3.pack(scratchCartesian3$9, values, i);
      }
    }
  }

  const inverseTranspose = new Matrix4();
  const normalMatrix = new Matrix3();

  /**
   * Transforms a geometry instance to world coordinates.  This changes
   * the instance's <code>modelMatrix</code> to {@link Matrix4.IDENTITY} and transforms the
   * following attributes if they are present: <code>position</code>, <code>normal</code>,
   * <code>tangent</code>, and <code>bitangent</code>.
   *
   * @param {GeometryInstance} instance The geometry instance to modify.
   * @returns {GeometryInstance} The modified <code>instance</code> argument, with its attributes transforms to world coordinates.
   *
   * @example
   * Cesium.GeometryPipeline.transformToWorldCoordinates(instance);
   */
  GeometryPipeline.transformToWorldCoordinates = function (instance) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(instance)) {
      throw new DeveloperError("instance is required.");
    }
    //>>includeEnd('debug');

    const modelMatrix = instance.modelMatrix;

    if (Matrix4.equals(modelMatrix, Matrix4.IDENTITY)) {
      // Already in world coordinates
      return instance;
    }

    const attributes = instance.geometry.attributes;

    // Transform attributes in known vertex formats
    transformPoint(modelMatrix, attributes.position);
    transformPoint(modelMatrix, attributes.prevPosition);
    transformPoint(modelMatrix, attributes.nextPosition);

    if (
      defined(attributes.normal) ||
      defined(attributes.tangent) ||
      defined(attributes.bitangent)
    ) {
      Matrix4.inverse(modelMatrix, inverseTranspose);
      Matrix4.transpose(inverseTranspose, inverseTranspose);
      Matrix4.getMatrix3(inverseTranspose, normalMatrix);

      transformVector(normalMatrix, attributes.normal);
      transformVector(normalMatrix, attributes.tangent);
      transformVector(normalMatrix, attributes.bitangent);
    }

    const boundingSphere = instance.geometry.boundingSphere;
    if (defined(boundingSphere)) {
      instance.geometry.boundingSphere = BoundingSphere.transform(
        boundingSphere,
        modelMatrix,
        boundingSphere
      );
    }

    instance.modelMatrix = Matrix4.clone(Matrix4.IDENTITY);

    return instance;
  };

  function findAttributesInAllGeometries(instances, propertyName) {
    const length = instances.length;

    const attributesInAllGeometries = {};

    const attributes0 = instances[0][propertyName].attributes;
    let name;

    for (name in attributes0) {
      if (
        attributes0.hasOwnProperty(name) &&
        defined(attributes0[name]) &&
        defined(attributes0[name].values)
      ) {
        const attribute = attributes0[name];
        let numberOfComponents = attribute.values.length;
        let inAllGeometries = true;

        // Does this same attribute exist in all geometries?
        for (let i = 1; i < length; ++i) {
          const otherAttribute = instances[i][propertyName].attributes[name];

          if (
            !defined(otherAttribute) ||
            attribute.componentDatatype !== otherAttribute.componentDatatype ||
            attribute.componentsPerAttribute !==
              otherAttribute.componentsPerAttribute ||
            attribute.normalize !== otherAttribute.normalize
          ) {
            inAllGeometries = false;
            break;
          }

          numberOfComponents += otherAttribute.values.length;
        }

        if (inAllGeometries) {
          attributesInAllGeometries[name] = new GeometryAttribute({
            componentDatatype: attribute.componentDatatype,
            componentsPerAttribute: attribute.componentsPerAttribute,
            normalize: attribute.normalize,
            values: ComponentDatatype$1.createTypedArray(
              attribute.componentDatatype,
              numberOfComponents
            ),
          });
        }
      }
    }

    return attributesInAllGeometries;
  }

  const tempScratch$1 = new Cartesian3();

  function combineGeometries(instances, propertyName) {
    const length = instances.length;

    let name;
    let i;
    let j;
    let k;

    const m = instances[0].modelMatrix;
    const haveIndices = defined(instances[0][propertyName].indices);
    const primitiveType = instances[0][propertyName].primitiveType;

    //>>includeStart('debug', pragmas.debug);
    for (i = 1; i < length; ++i) {
      if (!Matrix4.equals(instances[i].modelMatrix, m)) {
        throw new DeveloperError("All instances must have the same modelMatrix.");
      }
      if (defined(instances[i][propertyName].indices) !== haveIndices) {
        throw new DeveloperError(
          "All instance geometries must have an indices or not have one."
        );
      }
      if (instances[i][propertyName].primitiveType !== primitiveType) {
        throw new DeveloperError(
          "All instance geometries must have the same primitiveType."
        );
      }
    }
    //>>includeEnd('debug');

    // Find subset of attributes in all geometries
    const attributes = findAttributesInAllGeometries(instances, propertyName);
    let values;
    let sourceValues;
    let sourceValuesLength;

    // Combine attributes from each geometry into a single typed array
    for (name in attributes) {
      if (attributes.hasOwnProperty(name)) {
        values = attributes[name].values;

        k = 0;
        for (i = 0; i < length; ++i) {
          sourceValues = instances[i][propertyName].attributes[name].values;
          sourceValuesLength = sourceValues.length;

          for (j = 0; j < sourceValuesLength; ++j) {
            values[k++] = sourceValues[j];
          }
        }
      }
    }

    // Combine index lists
    let indices;

    if (haveIndices) {
      let numberOfIndices = 0;
      for (i = 0; i < length; ++i) {
        numberOfIndices += instances[i][propertyName].indices.length;
      }

      const numberOfVertices = Geometry.computeNumberOfVertices(
        new Geometry({
          attributes: attributes,
          primitiveType: PrimitiveType$1.POINTS,
        })
      );
      const destIndices = IndexDatatype$1.createTypedArray(
        numberOfVertices,
        numberOfIndices
      );

      let destOffset = 0;
      let offset = 0;

      for (i = 0; i < length; ++i) {
        const sourceIndices = instances[i][propertyName].indices;
        const sourceIndicesLen = sourceIndices.length;

        for (k = 0; k < sourceIndicesLen; ++k) {
          destIndices[destOffset++] = offset + sourceIndices[k];
        }

        offset += Geometry.computeNumberOfVertices(instances[i][propertyName]);
      }

      indices = destIndices;
    }

    // Create bounding sphere that includes all instances
    let center = new Cartesian3();
    let radius = 0.0;
    let bs;

    for (i = 0; i < length; ++i) {
      bs = instances[i][propertyName].boundingSphere;
      if (!defined(bs)) {
        // If any geometries have an undefined bounding sphere, then so does the combined geometry
        center = undefined;
        break;
      }

      Cartesian3.add(bs.center, center, center);
    }

    if (defined(center)) {
      Cartesian3.divideByScalar(center, length, center);

      for (i = 0; i < length; ++i) {
        bs = instances[i][propertyName].boundingSphere;
        const tempRadius =
          Cartesian3.magnitude(
            Cartesian3.subtract(bs.center, center, tempScratch$1)
          ) + bs.radius;

        if (tempRadius > radius) {
          radius = tempRadius;
        }
      }
    }

    return new Geometry({
      attributes: attributes,
      indices: indices,
      primitiveType: primitiveType,
      boundingSphere: defined(center)
        ? new BoundingSphere(center, radius)
        : undefined,
    });
  }

  /**
   * Combines geometry from several {@link GeometryInstance} objects into one geometry.
   * This concatenates the attributes, concatenates and adjusts the indices, and creates
   * a bounding sphere encompassing all instances.
   * <p>
   * If the instances do not have the same attributes, a subset of attributes common
   * to all instances is used, and the others are ignored.
   * </p>
   * <p>
   * This is used by {@link Primitive} to efficiently render a large amount of static data.
   * </p>
   *
   * @private
   *
   * @param {GeometryInstance[]} [instances] The array of {@link GeometryInstance} objects whose geometry will be combined.
   * @returns {Geometry} A single geometry created from the provided geometry instances.
   *
   * @exception {DeveloperError} All instances must have the same modelMatrix.
   * @exception {DeveloperError} All instance geometries must have an indices or not have one.
   * @exception {DeveloperError} All instance geometries must have the same primitiveType.
   *
   *
   * @example
   * for (let i = 0; i < instances.length; ++i) {
   *   Cesium.GeometryPipeline.transformToWorldCoordinates(instances[i]);
   * }
   * const geometries = Cesium.GeometryPipeline.combineInstances(instances);
   *
   * @see GeometryPipeline.transformToWorldCoordinates
   */
  GeometryPipeline.combineInstances = function (instances) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(instances) || instances.length < 1) {
      throw new DeveloperError(
        "instances is required and must have length greater than zero."
      );
    }
    //>>includeEnd('debug');

    const instanceGeometry = [];
    const instanceSplitGeometry = [];
    const length = instances.length;
    for (let i = 0; i < length; ++i) {
      const instance = instances[i];

      if (defined(instance.geometry)) {
        instanceGeometry.push(instance);
      } else if (
        defined(instance.westHemisphereGeometry) &&
        defined(instance.eastHemisphereGeometry)
      ) {
        instanceSplitGeometry.push(instance);
      }
    }

    const geometries = [];
    if (instanceGeometry.length > 0) {
      geometries.push(combineGeometries(instanceGeometry, "geometry"));
    }

    if (instanceSplitGeometry.length > 0) {
      geometries.push(
        combineGeometries(instanceSplitGeometry, "westHemisphereGeometry")
      );
      geometries.push(
        combineGeometries(instanceSplitGeometry, "eastHemisphereGeometry")
      );
    }

    return geometries;
  };

  const normal = new Cartesian3();
  const v0 = new Cartesian3();
  const v1$1 = new Cartesian3();
  const v2$1 = new Cartesian3();

  /**
   * Computes per-vertex normals for a geometry containing <code>TRIANGLES</code> by averaging the normals of
   * all triangles incident to the vertex.  The result is a new <code>normal</code> attribute added to the geometry.
   * This assumes a counter-clockwise winding order.
   *
   * @param {Geometry} geometry The geometry to modify.
   * @returns {Geometry} The modified <code>geometry</code> argument with the computed <code>normal</code> attribute.
   *
   * @exception {DeveloperError} geometry.indices length must be greater than 0 and be a multiple of 3.
   * @exception {DeveloperError} geometry.primitiveType must be {@link PrimitiveType.TRIANGLES}.
   *
   * @example
   * Cesium.GeometryPipeline.computeNormal(geometry);
   */
  GeometryPipeline.computeNormal = function (geometry) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(geometry)) {
      throw new DeveloperError("geometry is required.");
    }
    if (
      !defined(geometry.attributes.position) ||
      !defined(geometry.attributes.position.values)
    ) {
      throw new DeveloperError(
        "geometry.attributes.position.values is required."
      );
    }
    if (!defined(geometry.indices)) {
      throw new DeveloperError("geometry.indices is required.");
    }
    if (geometry.indices.length < 2 || geometry.indices.length % 3 !== 0) {
      throw new DeveloperError(
        "geometry.indices length must be greater than 0 and be a multiple of 3."
      );
    }
    if (geometry.primitiveType !== PrimitiveType$1.TRIANGLES) {
      throw new DeveloperError(
        "geometry.primitiveType must be PrimitiveType.TRIANGLES."
      );
    }
    //>>includeEnd('debug');

    const indices = geometry.indices;
    const attributes = geometry.attributes;
    const vertices = attributes.position.values;
    const numVertices = attributes.position.values.length / 3;
    const numIndices = indices.length;
    const normalsPerVertex = new Array(numVertices);
    const normalsPerTriangle = new Array(numIndices / 3);
    const normalIndices = new Array(numIndices);
    let i;
    for (i = 0; i < numVertices; i++) {
      normalsPerVertex[i] = {
        indexOffset: 0,
        count: 0,
        currentCount: 0,
      };
    }

    let j = 0;
    for (i = 0; i < numIndices; i += 3) {
      const i0 = indices[i];
      const i1 = indices[i + 1];
      const i2 = indices[i + 2];
      const i03 = i0 * 3;
      const i13 = i1 * 3;
      const i23 = i2 * 3;

      v0.x = vertices[i03];
      v0.y = vertices[i03 + 1];
      v0.z = vertices[i03 + 2];
      v1$1.x = vertices[i13];
      v1$1.y = vertices[i13 + 1];
      v1$1.z = vertices[i13 + 2];
      v2$1.x = vertices[i23];
      v2$1.y = vertices[i23 + 1];
      v2$1.z = vertices[i23 + 2];

      normalsPerVertex[i0].count++;
      normalsPerVertex[i1].count++;
      normalsPerVertex[i2].count++;

      Cartesian3.subtract(v1$1, v0, v1$1);
      Cartesian3.subtract(v2$1, v0, v2$1);
      normalsPerTriangle[j] = Cartesian3.cross(v1$1, v2$1, new Cartesian3());
      j++;
    }

    let indexOffset = 0;
    for (i = 0; i < numVertices; i++) {
      normalsPerVertex[i].indexOffset += indexOffset;
      indexOffset += normalsPerVertex[i].count;
    }

    j = 0;
    let vertexNormalData;
    for (i = 0; i < numIndices; i += 3) {
      vertexNormalData = normalsPerVertex[indices[i]];
      let index = vertexNormalData.indexOffset + vertexNormalData.currentCount;
      normalIndices[index] = j;
      vertexNormalData.currentCount++;

      vertexNormalData = normalsPerVertex[indices[i + 1]];
      index = vertexNormalData.indexOffset + vertexNormalData.currentCount;
      normalIndices[index] = j;
      vertexNormalData.currentCount++;

      vertexNormalData = normalsPerVertex[indices[i + 2]];
      index = vertexNormalData.indexOffset + vertexNormalData.currentCount;
      normalIndices[index] = j;
      vertexNormalData.currentCount++;

      j++;
    }

    const normalValues = new Float32Array(numVertices * 3);
    for (i = 0; i < numVertices; i++) {
      const i3 = i * 3;
      vertexNormalData = normalsPerVertex[i];
      Cartesian3.clone(Cartesian3.ZERO, normal);
      if (vertexNormalData.count > 0) {
        for (j = 0; j < vertexNormalData.count; j++) {
          Cartesian3.add(
            normal,
            normalsPerTriangle[normalIndices[vertexNormalData.indexOffset + j]],
            normal
          );
        }

        // We can run into an issue where a vertex is used with 2 primitives that have opposite winding order.
        if (
          Cartesian3.equalsEpsilon(Cartesian3.ZERO, normal, CesiumMath.EPSILON10)
        ) {
          Cartesian3.clone(
            normalsPerTriangle[normalIndices[vertexNormalData.indexOffset]],
            normal
          );
        }
      }

      // We end up with a zero vector probably because of a degenerate triangle
      if (
        Cartesian3.equalsEpsilon(Cartesian3.ZERO, normal, CesiumMath.EPSILON10)
      ) {
        // Default to (0,0,1)
        normal.z = 1.0;
      }

      Cartesian3.normalize(normal, normal);
      normalValues[i3] = normal.x;
      normalValues[i3 + 1] = normal.y;
      normalValues[i3 + 2] = normal.z;
    }

    geometry.attributes.normal = new GeometryAttribute({
      componentDatatype: ComponentDatatype$1.FLOAT,
      componentsPerAttribute: 3,
      values: normalValues,
    });

    return geometry;
  };

  const normalScratch$4 = new Cartesian3();
  const normalScale = new Cartesian3();
  const tScratch = new Cartesian3();

  /**
   * Computes per-vertex tangents and bitangents for a geometry containing <code>TRIANGLES</code>.
   * The result is new <code>tangent</code> and <code>bitangent</code> attributes added to the geometry.
   * This assumes a counter-clockwise winding order.
   * <p>
   * Based on <a href="http://www.terathon.com/code/tangent.html">Computing Tangent Space Basis Vectors
   * for an Arbitrary Mesh</a> by Eric Lengyel.
   * </p>
   *
   * @param {Geometry} geometry The geometry to modify.
   * @returns {Geometry} The modified <code>geometry</code> argument with the computed <code>tangent</code> and <code>bitangent</code> attributes.
   *
   * @exception {DeveloperError} geometry.indices length must be greater than 0 and be a multiple of 3.
   * @exception {DeveloperError} geometry.primitiveType must be {@link PrimitiveType.TRIANGLES}.
   *
   * @example
   * Cesium.GeometryPipeline.computeTangentAndBiTangent(geometry);
   */
  GeometryPipeline.computeTangentAndBitangent = function (geometry) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(geometry)) {
      throw new DeveloperError("geometry is required.");
    }
    //>>includeEnd('debug');

    const attributes = geometry.attributes;
    const indices = geometry.indices;

    //>>includeStart('debug', pragmas.debug);
    if (!defined(attributes.position) || !defined(attributes.position.values)) {
      throw new DeveloperError(
        "geometry.attributes.position.values is required."
      );
    }
    if (!defined(attributes.normal) || !defined(attributes.normal.values)) {
      throw new DeveloperError("geometry.attributes.normal.values is required.");
    }
    if (!defined(attributes.st) || !defined(attributes.st.values)) {
      throw new DeveloperError("geometry.attributes.st.values is required.");
    }
    if (!defined(indices)) {
      throw new DeveloperError("geometry.indices is required.");
    }
    if (indices.length < 2 || indices.length % 3 !== 0) {
      throw new DeveloperError(
        "geometry.indices length must be greater than 0 and be a multiple of 3."
      );
    }
    if (geometry.primitiveType !== PrimitiveType$1.TRIANGLES) {
      throw new DeveloperError(
        "geometry.primitiveType must be PrimitiveType.TRIANGLES."
      );
    }
    //>>includeEnd('debug');

    const vertices = geometry.attributes.position.values;
    const normals = geometry.attributes.normal.values;
    const st = geometry.attributes.st.values;

    const numVertices = geometry.attributes.position.values.length / 3;
    const numIndices = indices.length;
    const tan1 = new Array(numVertices * 3);

    let i;
    for (i = 0; i < tan1.length; i++) {
      tan1[i] = 0;
    }

    let i03;
    let i13;
    let i23;
    for (i = 0; i < numIndices; i += 3) {
      const i0 = indices[i];
      const i1 = indices[i + 1];
      const i2 = indices[i + 2];
      i03 = i0 * 3;
      i13 = i1 * 3;
      i23 = i2 * 3;
      const i02 = i0 * 2;
      const i12 = i1 * 2;
      const i22 = i2 * 2;

      const ux = vertices[i03];
      const uy = vertices[i03 + 1];
      const uz = vertices[i03 + 2];

      const wx = st[i02];
      const wy = st[i02 + 1];
      const t1 = st[i12 + 1] - wy;
      const t2 = st[i22 + 1] - wy;

      const r = 1.0 / ((st[i12] - wx) * t2 - (st[i22] - wx) * t1);
      const sdirx = (t2 * (vertices[i13] - ux) - t1 * (vertices[i23] - ux)) * r;
      const sdiry =
        (t2 * (vertices[i13 + 1] - uy) - t1 * (vertices[i23 + 1] - uy)) * r;
      const sdirz =
        (t2 * (vertices[i13 + 2] - uz) - t1 * (vertices[i23 + 2] - uz)) * r;

      tan1[i03] += sdirx;
      tan1[i03 + 1] += sdiry;
      tan1[i03 + 2] += sdirz;

      tan1[i13] += sdirx;
      tan1[i13 + 1] += sdiry;
      tan1[i13 + 2] += sdirz;

      tan1[i23] += sdirx;
      tan1[i23 + 1] += sdiry;
      tan1[i23 + 2] += sdirz;
    }

    const tangentValues = new Float32Array(numVertices * 3);
    const bitangentValues = new Float32Array(numVertices * 3);

    for (i = 0; i < numVertices; i++) {
      i03 = i * 3;
      i13 = i03 + 1;
      i23 = i03 + 2;

      const n = Cartesian3.fromArray(normals, i03, normalScratch$4);
      const t = Cartesian3.fromArray(tan1, i03, tScratch);
      const scalar = Cartesian3.dot(n, t);
      Cartesian3.multiplyByScalar(n, scalar, normalScale);
      Cartesian3.normalize(Cartesian3.subtract(t, normalScale, t), t);

      tangentValues[i03] = t.x;
      tangentValues[i13] = t.y;
      tangentValues[i23] = t.z;

      Cartesian3.normalize(Cartesian3.cross(n, t, t), t);

      bitangentValues[i03] = t.x;
      bitangentValues[i13] = t.y;
      bitangentValues[i23] = t.z;
    }

    geometry.attributes.tangent = new GeometryAttribute({
      componentDatatype: ComponentDatatype$1.FLOAT,
      componentsPerAttribute: 3,
      values: tangentValues,
    });

    geometry.attributes.bitangent = new GeometryAttribute({
      componentDatatype: ComponentDatatype$1.FLOAT,
      componentsPerAttribute: 3,
      values: bitangentValues,
    });

    return geometry;
  };

  const scratchCartesian2$8 = new Cartesian2();
  const toEncode1 = new Cartesian3();
  const toEncode2 = new Cartesian3();
  const toEncode3 = new Cartesian3();
  let encodeResult2 = new Cartesian2();
  /**
   * Compresses and packs geometry normal attribute values to save memory.
   *
   * @param {Geometry} geometry The geometry to modify.
   * @returns {Geometry} The modified <code>geometry</code> argument, with its normals compressed and packed.
   *
   * @example
   * geometry = Cesium.GeometryPipeline.compressVertices(geometry);
   */
  GeometryPipeline.compressVertices = function (geometry) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(geometry)) {
      throw new DeveloperError("geometry is required.");
    }
    //>>includeEnd('debug');

    const extrudeAttribute = geometry.attributes.extrudeDirection;
    let i;
    let numVertices;
    if (defined(extrudeAttribute)) {
      //only shadow volumes use extrudeDirection, and shadow volumes use vertexFormat: POSITION_ONLY so we don't need to check other attributes
      const extrudeDirections = extrudeAttribute.values;
      numVertices = extrudeDirections.length / 3.0;
      const compressedDirections = new Float32Array(numVertices * 2);

      let i2 = 0;
      for (i = 0; i < numVertices; ++i) {
        Cartesian3.fromArray(extrudeDirections, i * 3.0, toEncode1);
        if (Cartesian3.equals(toEncode1, Cartesian3.ZERO)) {
          i2 += 2;
          continue;
        }
        encodeResult2 = AttributeCompression.octEncodeInRange(
          toEncode1,
          65535,
          encodeResult2
        );
        compressedDirections[i2++] = encodeResult2.x;
        compressedDirections[i2++] = encodeResult2.y;
      }

      geometry.attributes.compressedAttributes = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 2,
        values: compressedDirections,
      });
      delete geometry.attributes.extrudeDirection;
      return geometry;
    }

    const normalAttribute = geometry.attributes.normal;
    const stAttribute = geometry.attributes.st;

    const hasNormal = defined(normalAttribute);
    const hasSt = defined(stAttribute);
    if (!hasNormal && !hasSt) {
      return geometry;
    }

    const tangentAttribute = geometry.attributes.tangent;
    const bitangentAttribute = geometry.attributes.bitangent;

    const hasTangent = defined(tangentAttribute);
    const hasBitangent = defined(bitangentAttribute);

    let normals;
    let st;
    let tangents;
    let bitangents;

    if (hasNormal) {
      normals = normalAttribute.values;
    }
    if (hasSt) {
      st = stAttribute.values;
    }
    if (hasTangent) {
      tangents = tangentAttribute.values;
    }
    if (hasBitangent) {
      bitangents = bitangentAttribute.values;
    }

    const length = hasNormal ? normals.length : st.length;
    const numComponents = hasNormal ? 3.0 : 2.0;
    numVertices = length / numComponents;

    let compressedLength = numVertices;
    let numCompressedComponents = hasSt && hasNormal ? 2.0 : 1.0;
    numCompressedComponents += hasTangent || hasBitangent ? 1.0 : 0.0;
    compressedLength *= numCompressedComponents;

    const compressedAttributes = new Float32Array(compressedLength);

    let normalIndex = 0;
    for (i = 0; i < numVertices; ++i) {
      if (hasSt) {
        Cartesian2.fromArray(st, i * 2.0, scratchCartesian2$8);
        compressedAttributes[
          normalIndex++
        ] = AttributeCompression.compressTextureCoordinates(scratchCartesian2$8);
      }

      const index = i * 3.0;
      if (hasNormal && defined(tangents) && defined(bitangents)) {
        Cartesian3.fromArray(normals, index, toEncode1);
        Cartesian3.fromArray(tangents, index, toEncode2);
        Cartesian3.fromArray(bitangents, index, toEncode3);

        AttributeCompression.octPack(
          toEncode1,
          toEncode2,
          toEncode3,
          scratchCartesian2$8
        );
        compressedAttributes[normalIndex++] = scratchCartesian2$8.x;
        compressedAttributes[normalIndex++] = scratchCartesian2$8.y;
      } else {
        if (hasNormal) {
          Cartesian3.fromArray(normals, index, toEncode1);
          compressedAttributes[
            normalIndex++
          ] = AttributeCompression.octEncodeFloat(toEncode1);
        }

        if (hasTangent) {
          Cartesian3.fromArray(tangents, index, toEncode1);
          compressedAttributes[
            normalIndex++
          ] = AttributeCompression.octEncodeFloat(toEncode1);
        }

        if (hasBitangent) {
          Cartesian3.fromArray(bitangents, index, toEncode1);
          compressedAttributes[
            normalIndex++
          ] = AttributeCompression.octEncodeFloat(toEncode1);
        }
      }
    }

    geometry.attributes.compressedAttributes = new GeometryAttribute({
      componentDatatype: ComponentDatatype$1.FLOAT,
      componentsPerAttribute: numCompressedComponents,
      values: compressedAttributes,
    });

    if (hasNormal) {
      delete geometry.attributes.normal;
    }
    if (hasSt) {
      delete geometry.attributes.st;
    }
    if (hasBitangent) {
      delete geometry.attributes.bitangent;
    }
    if (hasTangent) {
      delete geometry.attributes.tangent;
    }

    return geometry;
  };

  function indexTriangles(geometry) {
    if (defined(geometry.indices)) {
      return geometry;
    }
    const numberOfVertices = Geometry.computeNumberOfVertices(geometry);

    //>>includeStart('debug', pragmas.debug);
    if (numberOfVertices < 3) {
      throw new DeveloperError("The number of vertices must be at least three.");
    }
    if (numberOfVertices % 3 !== 0) {
      throw new DeveloperError(
        "The number of vertices must be a multiple of three."
      );
    }
    //>>includeEnd('debug');

    const indices = IndexDatatype$1.createTypedArray(
      numberOfVertices,
      numberOfVertices
    );
    for (let i = 0; i < numberOfVertices; ++i) {
      indices[i] = i;
    }

    geometry.indices = indices;
    return geometry;
  }

  function indexTriangleFan(geometry) {
    const numberOfVertices = Geometry.computeNumberOfVertices(geometry);

    //>>includeStart('debug', pragmas.debug);
    if (numberOfVertices < 3) {
      throw new DeveloperError("The number of vertices must be at least three.");
    }
    //>>includeEnd('debug');

    const indices = IndexDatatype$1.createTypedArray(
      numberOfVertices,
      (numberOfVertices - 2) * 3
    );
    indices[0] = 1;
    indices[1] = 0;
    indices[2] = 2;

    let indicesIndex = 3;
    for (let i = 3; i < numberOfVertices; ++i) {
      indices[indicesIndex++] = i - 1;
      indices[indicesIndex++] = 0;
      indices[indicesIndex++] = i;
    }

    geometry.indices = indices;
    geometry.primitiveType = PrimitiveType$1.TRIANGLES;
    return geometry;
  }

  function indexTriangleStrip(geometry) {
    const numberOfVertices = Geometry.computeNumberOfVertices(geometry);

    //>>includeStart('debug', pragmas.debug);
    if (numberOfVertices < 3) {
      throw new DeveloperError("The number of vertices must be at least 3.");
    }
    //>>includeEnd('debug');

    const indices = IndexDatatype$1.createTypedArray(
      numberOfVertices,
      (numberOfVertices - 2) * 3
    );
    indices[0] = 0;
    indices[1] = 1;
    indices[2] = 2;

    if (numberOfVertices > 3) {
      indices[3] = 0;
      indices[4] = 2;
      indices[5] = 3;
    }

    let indicesIndex = 6;
    for (let i = 3; i < numberOfVertices - 1; i += 2) {
      indices[indicesIndex++] = i;
      indices[indicesIndex++] = i - 1;
      indices[indicesIndex++] = i + 1;

      if (i + 2 < numberOfVertices) {
        indices[indicesIndex++] = i;
        indices[indicesIndex++] = i + 1;
        indices[indicesIndex++] = i + 2;
      }
    }

    geometry.indices = indices;
    geometry.primitiveType = PrimitiveType$1.TRIANGLES;
    return geometry;
  }

  function indexLines(geometry) {
    if (defined(geometry.indices)) {
      return geometry;
    }
    const numberOfVertices = Geometry.computeNumberOfVertices(geometry);

    //>>includeStart('debug', pragmas.debug);
    if (numberOfVertices < 2) {
      throw new DeveloperError("The number of vertices must be at least two.");
    }
    if (numberOfVertices % 2 !== 0) {
      throw new DeveloperError("The number of vertices must be a multiple of 2.");
    }
    //>>includeEnd('debug');

    const indices = IndexDatatype$1.createTypedArray(
      numberOfVertices,
      numberOfVertices
    );
    for (let i = 0; i < numberOfVertices; ++i) {
      indices[i] = i;
    }

    geometry.indices = indices;
    return geometry;
  }

  function indexLineStrip(geometry) {
    const numberOfVertices = Geometry.computeNumberOfVertices(geometry);

    //>>includeStart('debug', pragmas.debug);
    if (numberOfVertices < 2) {
      throw new DeveloperError("The number of vertices must be at least two.");
    }
    //>>includeEnd('debug');

    const indices = IndexDatatype$1.createTypedArray(
      numberOfVertices,
      (numberOfVertices - 1) * 2
    );
    indices[0] = 0;
    indices[1] = 1;
    let indicesIndex = 2;
    for (let i = 2; i < numberOfVertices; ++i) {
      indices[indicesIndex++] = i - 1;
      indices[indicesIndex++] = i;
    }

    geometry.indices = indices;
    geometry.primitiveType = PrimitiveType$1.LINES;
    return geometry;
  }

  function indexLineLoop(geometry) {
    const numberOfVertices = Geometry.computeNumberOfVertices(geometry);

    //>>includeStart('debug', pragmas.debug);
    if (numberOfVertices < 2) {
      throw new DeveloperError("The number of vertices must be at least two.");
    }
    //>>includeEnd('debug');

    const indices = IndexDatatype$1.createTypedArray(
      numberOfVertices,
      numberOfVertices * 2
    );

    indices[0] = 0;
    indices[1] = 1;

    let indicesIndex = 2;
    for (let i = 2; i < numberOfVertices; ++i) {
      indices[indicesIndex++] = i - 1;
      indices[indicesIndex++] = i;
    }

    indices[indicesIndex++] = numberOfVertices - 1;
    indices[indicesIndex] = 0;

    geometry.indices = indices;
    geometry.primitiveType = PrimitiveType$1.LINES;
    return geometry;
  }

  function indexPrimitive(geometry) {
    switch (geometry.primitiveType) {
      case PrimitiveType$1.TRIANGLE_FAN:
        return indexTriangleFan(geometry);
      case PrimitiveType$1.TRIANGLE_STRIP:
        return indexTriangleStrip(geometry);
      case PrimitiveType$1.TRIANGLES:
        return indexTriangles(geometry);
      case PrimitiveType$1.LINE_STRIP:
        return indexLineStrip(geometry);
      case PrimitiveType$1.LINE_LOOP:
        return indexLineLoop(geometry);
      case PrimitiveType$1.LINES:
        return indexLines(geometry);
    }

    return geometry;
  }

  function offsetPointFromXZPlane(p, isBehind) {
    if (Math.abs(p.y) < CesiumMath.EPSILON6) {
      if (isBehind) {
        p.y = -CesiumMath.EPSILON6;
      } else {
        p.y = CesiumMath.EPSILON6;
      }
    }
  }

  function offsetTriangleFromXZPlane(p0, p1, p2) {
    if (p0.y !== 0.0 && p1.y !== 0.0 && p2.y !== 0.0) {
      offsetPointFromXZPlane(p0, p0.y < 0.0);
      offsetPointFromXZPlane(p1, p1.y < 0.0);
      offsetPointFromXZPlane(p2, p2.y < 0.0);
      return;
    }

    const p0y = Math.abs(p0.y);
    const p1y = Math.abs(p1.y);
    const p2y = Math.abs(p2.y);

    let sign;
    if (p0y > p1y) {
      if (p0y > p2y) {
        sign = CesiumMath.sign(p0.y);
      } else {
        sign = CesiumMath.sign(p2.y);
      }
    } else if (p1y > p2y) {
      sign = CesiumMath.sign(p1.y);
    } else {
      sign = CesiumMath.sign(p2.y);
    }

    const isBehind = sign < 0.0;
    offsetPointFromXZPlane(p0, isBehind);
    offsetPointFromXZPlane(p1, isBehind);
    offsetPointFromXZPlane(p2, isBehind);
  }

  const c3$1 = new Cartesian3();
  function getXZIntersectionOffsetPoints(p, p1, u1, v1) {
    Cartesian3.add(
      p,
      Cartesian3.multiplyByScalar(
        Cartesian3.subtract(p1, p, c3$1),
        p.y / (p.y - p1.y),
        c3$1
      ),
      u1
    );
    Cartesian3.clone(u1, v1);
    offsetPointFromXZPlane(u1, true);
    offsetPointFromXZPlane(v1, false);
  }

  const u1 = new Cartesian3();
  const u2 = new Cartesian3();
  const q1 = new Cartesian3();
  const q2 = new Cartesian3();

  const splitTriangleResult = {
    positions: new Array(7),
    indices: new Array(3 * 3),
  };

  function splitTriangle(p0, p1, p2) {
    // In WGS84 coordinates, for a triangle approximately on the
    // ellipsoid to cross the IDL, first it needs to be on the
    // negative side of the plane x = 0.
    if (p0.x >= 0.0 || p1.x >= 0.0 || p2.x >= 0.0) {
      return undefined;
    }

    offsetTriangleFromXZPlane(p0, p1, p2);

    const p0Behind = p0.y < 0.0;
    const p1Behind = p1.y < 0.0;
    const p2Behind = p2.y < 0.0;

    let numBehind = 0;
    numBehind += p0Behind ? 1 : 0;
    numBehind += p1Behind ? 1 : 0;
    numBehind += p2Behind ? 1 : 0;

    const indices = splitTriangleResult.indices;

    if (numBehind === 1) {
      indices[1] = 3;
      indices[2] = 4;
      indices[5] = 6;
      indices[7] = 6;
      indices[8] = 5;

      if (p0Behind) {
        getXZIntersectionOffsetPoints(p0, p1, u1, q1);
        getXZIntersectionOffsetPoints(p0, p2, u2, q2);

        indices[0] = 0;
        indices[3] = 1;
        indices[4] = 2;
        indices[6] = 1;
      } else if (p1Behind) {
        getXZIntersectionOffsetPoints(p1, p2, u1, q1);
        getXZIntersectionOffsetPoints(p1, p0, u2, q2);

        indices[0] = 1;
        indices[3] = 2;
        indices[4] = 0;
        indices[6] = 2;
      } else if (p2Behind) {
        getXZIntersectionOffsetPoints(p2, p0, u1, q1);
        getXZIntersectionOffsetPoints(p2, p1, u2, q2);

        indices[0] = 2;
        indices[3] = 0;
        indices[4] = 1;
        indices[6] = 0;
      }
    } else if (numBehind === 2) {
      indices[2] = 4;
      indices[4] = 4;
      indices[5] = 3;
      indices[7] = 5;
      indices[8] = 6;

      if (!p0Behind) {
        getXZIntersectionOffsetPoints(p0, p1, u1, q1);
        getXZIntersectionOffsetPoints(p0, p2, u2, q2);

        indices[0] = 1;
        indices[1] = 2;
        indices[3] = 1;
        indices[6] = 0;
      } else if (!p1Behind) {
        getXZIntersectionOffsetPoints(p1, p2, u1, q1);
        getXZIntersectionOffsetPoints(p1, p0, u2, q2);

        indices[0] = 2;
        indices[1] = 0;
        indices[3] = 2;
        indices[6] = 1;
      } else if (!p2Behind) {
        getXZIntersectionOffsetPoints(p2, p0, u1, q1);
        getXZIntersectionOffsetPoints(p2, p1, u2, q2);

        indices[0] = 0;
        indices[1] = 1;
        indices[3] = 0;
        indices[6] = 2;
      }
    }

    const positions = splitTriangleResult.positions;
    positions[0] = p0;
    positions[1] = p1;
    positions[2] = p2;
    positions.length = 3;

    if (numBehind === 1 || numBehind === 2) {
      positions[3] = u1;
      positions[4] = u2;
      positions[5] = q1;
      positions[6] = q2;
      positions.length = 7;
    }

    return splitTriangleResult;
  }

  function updateGeometryAfterSplit(geometry, computeBoundingSphere) {
    const attributes = geometry.attributes;

    if (attributes.position.values.length === 0) {
      return undefined;
    }

    for (const property in attributes) {
      if (
        attributes.hasOwnProperty(property) &&
        defined(attributes[property]) &&
        defined(attributes[property].values)
      ) {
        const attribute = attributes[property];
        attribute.values = ComponentDatatype$1.createTypedArray(
          attribute.componentDatatype,
          attribute.values
        );
      }
    }

    const numberOfVertices = Geometry.computeNumberOfVertices(geometry);
    geometry.indices = IndexDatatype$1.createTypedArray(
      numberOfVertices,
      geometry.indices
    );

    if (computeBoundingSphere) {
      geometry.boundingSphere = BoundingSphere.fromVertices(
        attributes.position.values
      );
    }

    return geometry;
  }

  function copyGeometryForSplit(geometry) {
    const attributes = geometry.attributes;
    const copiedAttributes = {};

    for (const property in attributes) {
      if (
        attributes.hasOwnProperty(property) &&
        defined(attributes[property]) &&
        defined(attributes[property].values)
      ) {
        const attribute = attributes[property];
        copiedAttributes[property] = new GeometryAttribute({
          componentDatatype: attribute.componentDatatype,
          componentsPerAttribute: attribute.componentsPerAttribute,
          normalize: attribute.normalize,
          values: [],
        });
      }
    }

    return new Geometry({
      attributes: copiedAttributes,
      indices: [],
      primitiveType: geometry.primitiveType,
    });
  }

  function updateInstanceAfterSplit(instance, westGeometry, eastGeometry) {
    const computeBoundingSphere = defined(instance.geometry.boundingSphere);

    westGeometry = updateGeometryAfterSplit(westGeometry, computeBoundingSphere);
    eastGeometry = updateGeometryAfterSplit(eastGeometry, computeBoundingSphere);

    if (defined(eastGeometry) && !defined(westGeometry)) {
      instance.geometry = eastGeometry;
    } else if (!defined(eastGeometry) && defined(westGeometry)) {
      instance.geometry = westGeometry;
    } else {
      instance.westHemisphereGeometry = westGeometry;
      instance.eastHemisphereGeometry = eastGeometry;
      instance.geometry = undefined;
    }
  }

  function generateBarycentricInterpolateFunction(
    CartesianType,
    numberOfComponents
  ) {
    const v0Scratch = new CartesianType();
    const v1Scratch = new CartesianType();
    const v2Scratch = new CartesianType();

    return function (
      i0,
      i1,
      i2,
      coords,
      sourceValues,
      currentValues,
      insertedIndex,
      normalize
    ) {
      const v0 = CartesianType.fromArray(
        sourceValues,
        i0 * numberOfComponents,
        v0Scratch
      );
      const v1 = CartesianType.fromArray(
        sourceValues,
        i1 * numberOfComponents,
        v1Scratch
      );
      const v2 = CartesianType.fromArray(
        sourceValues,
        i2 * numberOfComponents,
        v2Scratch
      );

      CartesianType.multiplyByScalar(v0, coords.x, v0);
      CartesianType.multiplyByScalar(v1, coords.y, v1);
      CartesianType.multiplyByScalar(v2, coords.z, v2);

      const value = CartesianType.add(v0, v1, v0);
      CartesianType.add(value, v2, value);

      if (normalize) {
        CartesianType.normalize(value, value);
      }

      CartesianType.pack(
        value,
        currentValues,
        insertedIndex * numberOfComponents
      );
    };
  }

  const interpolateAndPackCartesian4 = generateBarycentricInterpolateFunction(
    Cartesian4,
    4
  );
  const interpolateAndPackCartesian3 = generateBarycentricInterpolateFunction(
    Cartesian3,
    3
  );
  const interpolateAndPackCartesian2 = generateBarycentricInterpolateFunction(
    Cartesian2,
    2
  );
  const interpolateAndPackBoolean = function (
    i0,
    i1,
    i2,
    coords,
    sourceValues,
    currentValues,
    insertedIndex
  ) {
    const v1 = sourceValues[i0] * coords.x;
    const v2 = sourceValues[i1] * coords.y;
    const v3 = sourceValues[i2] * coords.z;
    currentValues[insertedIndex] = v1 + v2 + v3 > CesiumMath.EPSILON6 ? 1 : 0;
  };

  const p0Scratch = new Cartesian3();
  const p1Scratch$2 = new Cartesian3();
  const p2Scratch$2 = new Cartesian3();
  const barycentricScratch = new Cartesian3();

  function computeTriangleAttributes(
    i0,
    i1,
    i2,
    point,
    positions,
    normals,
    tangents,
    bitangents,
    texCoords,
    extrudeDirections,
    applyOffset,
    currentAttributes,
    customAttributeNames,
    customAttributesLength,
    allAttributes,
    insertedIndex
  ) {
    if (
      !defined(normals) &&
      !defined(tangents) &&
      !defined(bitangents) &&
      !defined(texCoords) &&
      !defined(extrudeDirections) &&
      customAttributesLength === 0
    ) {
      return;
    }

    const p0 = Cartesian3.fromArray(positions, i0 * 3, p0Scratch);
    const p1 = Cartesian3.fromArray(positions, i1 * 3, p1Scratch$2);
    const p2 = Cartesian3.fromArray(positions, i2 * 3, p2Scratch$2);
    const coords = barycentricCoordinates(point, p0, p1, p2, barycentricScratch);
    if (!defined(coords)) {
      return;
    }

    if (defined(normals)) {
      interpolateAndPackCartesian3(
        i0,
        i1,
        i2,
        coords,
        normals,
        currentAttributes.normal.values,
        insertedIndex,
        true
      );
    }

    if (defined(extrudeDirections)) {
      const d0 = Cartesian3.fromArray(extrudeDirections, i0 * 3, p0Scratch);
      const d1 = Cartesian3.fromArray(extrudeDirections, i1 * 3, p1Scratch$2);
      const d2 = Cartesian3.fromArray(extrudeDirections, i2 * 3, p2Scratch$2);

      Cartesian3.multiplyByScalar(d0, coords.x, d0);
      Cartesian3.multiplyByScalar(d1, coords.y, d1);
      Cartesian3.multiplyByScalar(d2, coords.z, d2);

      let direction;
      if (
        !Cartesian3.equals(d0, Cartesian3.ZERO) ||
        !Cartesian3.equals(d1, Cartesian3.ZERO) ||
        !Cartesian3.equals(d2, Cartesian3.ZERO)
      ) {
        direction = Cartesian3.add(d0, d1, d0);
        Cartesian3.add(direction, d2, direction);
        Cartesian3.normalize(direction, direction);
      } else {
        direction = p0Scratch;
        direction.x = 0;
        direction.y = 0;
        direction.z = 0;
      }
      Cartesian3.pack(
        direction,
        currentAttributes.extrudeDirection.values,
        insertedIndex * 3
      );
    }

    if (defined(applyOffset)) {
      interpolateAndPackBoolean(
        i0,
        i1,
        i2,
        coords,
        applyOffset,
        currentAttributes.applyOffset.values,
        insertedIndex
      );
    }

    if (defined(tangents)) {
      interpolateAndPackCartesian3(
        i0,
        i1,
        i2,
        coords,
        tangents,
        currentAttributes.tangent.values,
        insertedIndex,
        true
      );
    }

    if (defined(bitangents)) {
      interpolateAndPackCartesian3(
        i0,
        i1,
        i2,
        coords,
        bitangents,
        currentAttributes.bitangent.values,
        insertedIndex,
        true
      );
    }

    if (defined(texCoords)) {
      interpolateAndPackCartesian2(
        i0,
        i1,
        i2,
        coords,
        texCoords,
        currentAttributes.st.values,
        insertedIndex
      );
    }

    if (customAttributesLength > 0) {
      for (let i = 0; i < customAttributesLength; i++) {
        const attributeName = customAttributeNames[i];
        genericInterpolate(
          i0,
          i1,
          i2,
          coords,
          insertedIndex,
          allAttributes[attributeName],
          currentAttributes[attributeName]
        );
      }
    }
  }

  function genericInterpolate(
    i0,
    i1,
    i2,
    coords,
    insertedIndex,
    sourceAttribute,
    currentAttribute
  ) {
    const componentsPerAttribute = sourceAttribute.componentsPerAttribute;
    const sourceValues = sourceAttribute.values;
    const currentValues = currentAttribute.values;
    switch (componentsPerAttribute) {
      case 4:
        interpolateAndPackCartesian4(
          i0,
          i1,
          i2,
          coords,
          sourceValues,
          currentValues,
          insertedIndex,
          false
        );
        break;
      case 3:
        interpolateAndPackCartesian3(
          i0,
          i1,
          i2,
          coords,
          sourceValues,
          currentValues,
          insertedIndex,
          false
        );
        break;
      case 2:
        interpolateAndPackCartesian2(
          i0,
          i1,
          i2,
          coords,
          sourceValues,
          currentValues,
          insertedIndex,
          false
        );
        break;
      default:
        currentValues[insertedIndex] =
          sourceValues[i0] * coords.x +
          sourceValues[i1] * coords.y +
          sourceValues[i2] * coords.z;
    }
  }

  function insertSplitPoint(
    currentAttributes,
    currentIndices,
    currentIndexMap,
    indices,
    currentIndex,
    point
  ) {
    const insertIndex = currentAttributes.position.values.length / 3;

    if (currentIndex !== -1) {
      const prevIndex = indices[currentIndex];
      const newIndex = currentIndexMap[prevIndex];

      if (newIndex === -1) {
        currentIndexMap[prevIndex] = insertIndex;
        currentAttributes.position.values.push(point.x, point.y, point.z);
        currentIndices.push(insertIndex);
        return insertIndex;
      }

      currentIndices.push(newIndex);
      return newIndex;
    }

    currentAttributes.position.values.push(point.x, point.y, point.z);
    currentIndices.push(insertIndex);
    return insertIndex;
  }

  const NAMED_ATTRIBUTES = {
    position: true,
    normal: true,
    bitangent: true,
    tangent: true,
    st: true,
    extrudeDirection: true,
    applyOffset: true,
  };
  function splitLongitudeTriangles(instance) {
    const geometry = instance.geometry;
    const attributes = geometry.attributes;
    const positions = attributes.position.values;
    const normals = defined(attributes.normal)
      ? attributes.normal.values
      : undefined;
    const bitangents = defined(attributes.bitangent)
      ? attributes.bitangent.values
      : undefined;
    const tangents = defined(attributes.tangent)
      ? attributes.tangent.values
      : undefined;
    const texCoords = defined(attributes.st) ? attributes.st.values : undefined;
    const extrudeDirections = defined(attributes.extrudeDirection)
      ? attributes.extrudeDirection.values
      : undefined;
    const applyOffset = defined(attributes.applyOffset)
      ? attributes.applyOffset.values
      : undefined;
    const indices = geometry.indices;

    const customAttributeNames = [];
    for (const attributeName in attributes) {
      if (
        attributes.hasOwnProperty(attributeName) &&
        !NAMED_ATTRIBUTES[attributeName] &&
        defined(attributes[attributeName])
      ) {
        customAttributeNames.push(attributeName);
      }
    }
    const customAttributesLength = customAttributeNames.length;

    const eastGeometry = copyGeometryForSplit(geometry);
    const westGeometry = copyGeometryForSplit(geometry);

    let currentAttributes;
    let currentIndices;
    let currentIndexMap;
    let insertedIndex;
    let i;

    const westGeometryIndexMap = [];
    westGeometryIndexMap.length = positions.length / 3;

    const eastGeometryIndexMap = [];
    eastGeometryIndexMap.length = positions.length / 3;

    for (i = 0; i < westGeometryIndexMap.length; ++i) {
      westGeometryIndexMap[i] = -1;
      eastGeometryIndexMap[i] = -1;
    }

    const len = indices.length;
    for (i = 0; i < len; i += 3) {
      const i0 = indices[i];
      const i1 = indices[i + 1];
      const i2 = indices[i + 2];

      let p0 = Cartesian3.fromArray(positions, i0 * 3);
      let p1 = Cartesian3.fromArray(positions, i1 * 3);
      let p2 = Cartesian3.fromArray(positions, i2 * 3);

      const result = splitTriangle(p0, p1, p2);
      if (defined(result) && result.positions.length > 3) {
        const resultPositions = result.positions;
        const resultIndices = result.indices;
        const resultLength = resultIndices.length;

        for (let j = 0; j < resultLength; ++j) {
          const resultIndex = resultIndices[j];
          const point = resultPositions[resultIndex];

          if (point.y < 0.0) {
            currentAttributes = westGeometry.attributes;
            currentIndices = westGeometry.indices;
            currentIndexMap = westGeometryIndexMap;
          } else {
            currentAttributes = eastGeometry.attributes;
            currentIndices = eastGeometry.indices;
            currentIndexMap = eastGeometryIndexMap;
          }

          insertedIndex = insertSplitPoint(
            currentAttributes,
            currentIndices,
            currentIndexMap,
            indices,
            resultIndex < 3 ? i + resultIndex : -1,
            point
          );
          computeTriangleAttributes(
            i0,
            i1,
            i2,
            point,
            positions,
            normals,
            tangents,
            bitangents,
            texCoords,
            extrudeDirections,
            applyOffset,
            currentAttributes,
            customAttributeNames,
            customAttributesLength,
            attributes,
            insertedIndex
          );
        }
      } else {
        if (defined(result)) {
          p0 = result.positions[0];
          p1 = result.positions[1];
          p2 = result.positions[2];
        }

        if (p0.y < 0.0) {
          currentAttributes = westGeometry.attributes;
          currentIndices = westGeometry.indices;
          currentIndexMap = westGeometryIndexMap;
        } else {
          currentAttributes = eastGeometry.attributes;
          currentIndices = eastGeometry.indices;
          currentIndexMap = eastGeometryIndexMap;
        }

        insertedIndex = insertSplitPoint(
          currentAttributes,
          currentIndices,
          currentIndexMap,
          indices,
          i,
          p0
        );
        computeTriangleAttributes(
          i0,
          i1,
          i2,
          p0,
          positions,
          normals,
          tangents,
          bitangents,
          texCoords,
          extrudeDirections,
          applyOffset,
          currentAttributes,
          customAttributeNames,
          customAttributesLength,
          attributes,
          insertedIndex
        );

        insertedIndex = insertSplitPoint(
          currentAttributes,
          currentIndices,
          currentIndexMap,
          indices,
          i + 1,
          p1
        );
        computeTriangleAttributes(
          i0,
          i1,
          i2,
          p1,
          positions,
          normals,
          tangents,
          bitangents,
          texCoords,
          extrudeDirections,
          applyOffset,
          currentAttributes,
          customAttributeNames,
          customAttributesLength,
          attributes,
          insertedIndex
        );

        insertedIndex = insertSplitPoint(
          currentAttributes,
          currentIndices,
          currentIndexMap,
          indices,
          i + 2,
          p2
        );
        computeTriangleAttributes(
          i0,
          i1,
          i2,
          p2,
          positions,
          normals,
          tangents,
          bitangents,
          texCoords,
          extrudeDirections,
          applyOffset,
          currentAttributes,
          customAttributeNames,
          customAttributesLength,
          attributes,
          insertedIndex
        );
      }
    }

    updateInstanceAfterSplit(instance, westGeometry, eastGeometry);
  }

  const xzPlane = Plane.fromPointNormal(Cartesian3.ZERO, Cartesian3.UNIT_Y);

  const offsetScratch$c = new Cartesian3();
  const offsetPointScratch = new Cartesian3();

  function computeLineAttributes(
    i0,
    i1,
    point,
    positions,
    insertIndex,
    currentAttributes,
    applyOffset
  ) {
    if (!defined(applyOffset)) {
      return;
    }

    const p0 = Cartesian3.fromArray(positions, i0 * 3, p0Scratch);
    if (Cartesian3.equalsEpsilon(p0, point, CesiumMath.EPSILON10)) {
      currentAttributes.applyOffset.values[insertIndex] = applyOffset[i0];
    } else {
      currentAttributes.applyOffset.values[insertIndex] = applyOffset[i1];
    }
  }

  function splitLongitudeLines(instance) {
    const geometry = instance.geometry;
    const attributes = geometry.attributes;
    const positions = attributes.position.values;
    const applyOffset = defined(attributes.applyOffset)
      ? attributes.applyOffset.values
      : undefined;
    const indices = geometry.indices;

    const eastGeometry = copyGeometryForSplit(geometry);
    const westGeometry = copyGeometryForSplit(geometry);

    let i;
    const length = indices.length;

    const westGeometryIndexMap = [];
    westGeometryIndexMap.length = positions.length / 3;

    const eastGeometryIndexMap = [];
    eastGeometryIndexMap.length = positions.length / 3;

    for (i = 0; i < westGeometryIndexMap.length; ++i) {
      westGeometryIndexMap[i] = -1;
      eastGeometryIndexMap[i] = -1;
    }

    for (i = 0; i < length; i += 2) {
      const i0 = indices[i];
      const i1 = indices[i + 1];

      const p0 = Cartesian3.fromArray(positions, i0 * 3, p0Scratch);
      const p1 = Cartesian3.fromArray(positions, i1 * 3, p1Scratch$2);
      let insertIndex;

      if (Math.abs(p0.y) < CesiumMath.EPSILON6) {
        if (p0.y < 0.0) {
          p0.y = -CesiumMath.EPSILON6;
        } else {
          p0.y = CesiumMath.EPSILON6;
        }
      }

      if (Math.abs(p1.y) < CesiumMath.EPSILON6) {
        if (p1.y < 0.0) {
          p1.y = -CesiumMath.EPSILON6;
        } else {
          p1.y = CesiumMath.EPSILON6;
        }
      }

      let p0Attributes = eastGeometry.attributes;
      let p0Indices = eastGeometry.indices;
      let p0IndexMap = eastGeometryIndexMap;
      let p1Attributes = westGeometry.attributes;
      let p1Indices = westGeometry.indices;
      let p1IndexMap = westGeometryIndexMap;

      const intersection = IntersectionTests.lineSegmentPlane(
        p0,
        p1,
        xzPlane,
        p2Scratch$2
      );
      if (defined(intersection)) {
        // move point on the xz-plane slightly away from the plane
        const offset = Cartesian3.multiplyByScalar(
          Cartesian3.UNIT_Y,
          5.0 * CesiumMath.EPSILON9,
          offsetScratch$c
        );
        if (p0.y < 0.0) {
          Cartesian3.negate(offset, offset);

          p0Attributes = westGeometry.attributes;
          p0Indices = westGeometry.indices;
          p0IndexMap = westGeometryIndexMap;
          p1Attributes = eastGeometry.attributes;
          p1Indices = eastGeometry.indices;
          p1IndexMap = eastGeometryIndexMap;
        }

        const offsetPoint = Cartesian3.add(
          intersection,
          offset,
          offsetPointScratch
        );

        insertIndex = insertSplitPoint(
          p0Attributes,
          p0Indices,
          p0IndexMap,
          indices,
          i,
          p0
        );
        computeLineAttributes(
          i0,
          i1,
          p0,
          positions,
          insertIndex,
          p0Attributes,
          applyOffset
        );

        insertIndex = insertSplitPoint(
          p0Attributes,
          p0Indices,
          p0IndexMap,
          indices,
          -1,
          offsetPoint
        );
        computeLineAttributes(
          i0,
          i1,
          offsetPoint,
          positions,
          insertIndex,
          p0Attributes,
          applyOffset
        );

        Cartesian3.negate(offset, offset);
        Cartesian3.add(intersection, offset, offsetPoint);
        insertIndex = insertSplitPoint(
          p1Attributes,
          p1Indices,
          p1IndexMap,
          indices,
          -1,
          offsetPoint
        );
        computeLineAttributes(
          i0,
          i1,
          offsetPoint,
          positions,
          insertIndex,
          p1Attributes,
          applyOffset
        );

        insertIndex = insertSplitPoint(
          p1Attributes,
          p1Indices,
          p1IndexMap,
          indices,
          i + 1,
          p1
        );
        computeLineAttributes(
          i0,
          i1,
          p1,
          positions,
          insertIndex,
          p1Attributes,
          applyOffset
        );
      } else {
        let currentAttributes;
        let currentIndices;
        let currentIndexMap;

        if (p0.y < 0.0) {
          currentAttributes = westGeometry.attributes;
          currentIndices = westGeometry.indices;
          currentIndexMap = westGeometryIndexMap;
        } else {
          currentAttributes = eastGeometry.attributes;
          currentIndices = eastGeometry.indices;
          currentIndexMap = eastGeometryIndexMap;
        }

        insertIndex = insertSplitPoint(
          currentAttributes,
          currentIndices,
          currentIndexMap,
          indices,
          i,
          p0
        );
        computeLineAttributes(
          i0,
          i1,
          p0,
          positions,
          insertIndex,
          currentAttributes,
          applyOffset
        );

        insertIndex = insertSplitPoint(
          currentAttributes,
          currentIndices,
          currentIndexMap,
          indices,
          i + 1,
          p1
        );
        computeLineAttributes(
          i0,
          i1,
          p1,
          positions,
          insertIndex,
          currentAttributes,
          applyOffset
        );
      }
    }

    updateInstanceAfterSplit(instance, westGeometry, eastGeometry);
  }

  const cartesian2Scratch0 = new Cartesian2();
  const cartesian2Scratch1 = new Cartesian2();

  const cartesian3Scratch0 = new Cartesian3();
  const cartesian3Scratch2$1 = new Cartesian3();
  const cartesian3Scratch3$1 = new Cartesian3();
  const cartesian3Scratch4 = new Cartesian3();
  const cartesian3Scratch5 = new Cartesian3();
  const cartesian3Scratch6 = new Cartesian3();

  const cartesian4Scratch0 = new Cartesian4();

  function updateAdjacencyAfterSplit(geometry) {
    const attributes = geometry.attributes;
    const positions = attributes.position.values;
    const prevPositions = attributes.prevPosition.values;
    const nextPositions = attributes.nextPosition.values;

    const length = positions.length;
    for (let j = 0; j < length; j += 3) {
      const position = Cartesian3.unpack(positions, j, cartesian3Scratch0);
      if (position.x > 0.0) {
        continue;
      }

      const prevPosition = Cartesian3.unpack(
        prevPositions,
        j,
        cartesian3Scratch2$1
      );
      if (
        (position.y < 0.0 && prevPosition.y > 0.0) ||
        (position.y > 0.0 && prevPosition.y < 0.0)
      ) {
        if (j - 3 > 0) {
          prevPositions[j] = positions[j - 3];
          prevPositions[j + 1] = positions[j - 2];
          prevPositions[j + 2] = positions[j - 1];
        } else {
          Cartesian3.pack(position, prevPositions, j);
        }
      }

      const nextPosition = Cartesian3.unpack(
        nextPositions,
        j,
        cartesian3Scratch3$1
      );
      if (
        (position.y < 0.0 && nextPosition.y > 0.0) ||
        (position.y > 0.0 && nextPosition.y < 0.0)
      ) {
        if (j + 3 < length) {
          nextPositions[j] = positions[j + 3];
          nextPositions[j + 1] = positions[j + 4];
          nextPositions[j + 2] = positions[j + 5];
        } else {
          Cartesian3.pack(position, nextPositions, j);
        }
      }
    }
  }

  const offsetScalar = 5.0 * CesiumMath.EPSILON9;
  const coplanarOffset = CesiumMath.EPSILON6;

  function splitLongitudePolyline(instance) {
    const geometry = instance.geometry;
    const attributes = geometry.attributes;
    const positions = attributes.position.values;
    const prevPositions = attributes.prevPosition.values;
    const nextPositions = attributes.nextPosition.values;
    const expandAndWidths = attributes.expandAndWidth.values;

    const texCoords = defined(attributes.st) ? attributes.st.values : undefined;
    const colors = defined(attributes.color)
      ? attributes.color.values
      : undefined;

    const eastGeometry = copyGeometryForSplit(geometry);
    const westGeometry = copyGeometryForSplit(geometry);

    let i;
    let j;
    let index;

    let intersectionFound = false;

    const length = positions.length / 3;
    for (i = 0; i < length; i += 4) {
      const i0 = i;
      const i2 = i + 2;

      const p0 = Cartesian3.fromArray(positions, i0 * 3, cartesian3Scratch0);
      const p2 = Cartesian3.fromArray(positions, i2 * 3, cartesian3Scratch2$1);

      // Offset points that are close to the 180 longitude and change the previous/next point
      // to be the same offset point so it can be projected to 2D. There is special handling in the
      // shader for when position == prevPosition || position == nextPosition.
      if (Math.abs(p0.y) < coplanarOffset) {
        p0.y = coplanarOffset * (p2.y < 0.0 ? -1.0 : 1.0);
        positions[i * 3 + 1] = p0.y;
        positions[(i + 1) * 3 + 1] = p0.y;

        for (j = i0 * 3; j < i0 * 3 + 4 * 3; j += 3) {
          prevPositions[j] = positions[i * 3];
          prevPositions[j + 1] = positions[i * 3 + 1];
          prevPositions[j + 2] = positions[i * 3 + 2];
        }
      }

      // Do the same but for when the line crosses 180 longitude in the opposite direction.
      if (Math.abs(p2.y) < coplanarOffset) {
        p2.y = coplanarOffset * (p0.y < 0.0 ? -1.0 : 1.0);
        positions[(i + 2) * 3 + 1] = p2.y;
        positions[(i + 3) * 3 + 1] = p2.y;

        for (j = i0 * 3; j < i0 * 3 + 4 * 3; j += 3) {
          nextPositions[j] = positions[(i + 2) * 3];
          nextPositions[j + 1] = positions[(i + 2) * 3 + 1];
          nextPositions[j + 2] = positions[(i + 2) * 3 + 2];
        }
      }

      let p0Attributes = eastGeometry.attributes;
      let p0Indices = eastGeometry.indices;
      let p2Attributes = westGeometry.attributes;
      let p2Indices = westGeometry.indices;

      const intersection = IntersectionTests.lineSegmentPlane(
        p0,
        p2,
        xzPlane,
        cartesian3Scratch4
      );
      if (defined(intersection)) {
        intersectionFound = true;

        // move point on the xz-plane slightly away from the plane
        const offset = Cartesian3.multiplyByScalar(
          Cartesian3.UNIT_Y,
          offsetScalar,
          cartesian3Scratch5
        );
        if (p0.y < 0.0) {
          Cartesian3.negate(offset, offset);
          p0Attributes = westGeometry.attributes;
          p0Indices = westGeometry.indices;
          p2Attributes = eastGeometry.attributes;
          p2Indices = eastGeometry.indices;
        }

        const offsetPoint = Cartesian3.add(
          intersection,
          offset,
          cartesian3Scratch6
        );
        p0Attributes.position.values.push(p0.x, p0.y, p0.z, p0.x, p0.y, p0.z);
        p0Attributes.position.values.push(
          offsetPoint.x,
          offsetPoint.y,
          offsetPoint.z
        );
        p0Attributes.position.values.push(
          offsetPoint.x,
          offsetPoint.y,
          offsetPoint.z
        );

        p0Attributes.prevPosition.values.push(
          prevPositions[i0 * 3],
          prevPositions[i0 * 3 + 1],
          prevPositions[i0 * 3 + 2]
        );
        p0Attributes.prevPosition.values.push(
          prevPositions[i0 * 3 + 3],
          prevPositions[i0 * 3 + 4],
          prevPositions[i0 * 3 + 5]
        );
        p0Attributes.prevPosition.values.push(p0.x, p0.y, p0.z, p0.x, p0.y, p0.z);

        p0Attributes.nextPosition.values.push(
          offsetPoint.x,
          offsetPoint.y,
          offsetPoint.z
        );
        p0Attributes.nextPosition.values.push(
          offsetPoint.x,
          offsetPoint.y,
          offsetPoint.z
        );
        p0Attributes.nextPosition.values.push(
          offsetPoint.x,
          offsetPoint.y,
          offsetPoint.z
        );
        p0Attributes.nextPosition.values.push(
          offsetPoint.x,
          offsetPoint.y,
          offsetPoint.z
        );

        Cartesian3.negate(offset, offset);
        Cartesian3.add(intersection, offset, offsetPoint);
        p2Attributes.position.values.push(
          offsetPoint.x,
          offsetPoint.y,
          offsetPoint.z
        );
        p2Attributes.position.values.push(
          offsetPoint.x,
          offsetPoint.y,
          offsetPoint.z
        );
        p2Attributes.position.values.push(p2.x, p2.y, p2.z, p2.x, p2.y, p2.z);

        p2Attributes.prevPosition.values.push(
          offsetPoint.x,
          offsetPoint.y,
          offsetPoint.z
        );
        p2Attributes.prevPosition.values.push(
          offsetPoint.x,
          offsetPoint.y,
          offsetPoint.z
        );
        p2Attributes.prevPosition.values.push(
          offsetPoint.x,
          offsetPoint.y,
          offsetPoint.z
        );
        p2Attributes.prevPosition.values.push(
          offsetPoint.x,
          offsetPoint.y,
          offsetPoint.z
        );

        p2Attributes.nextPosition.values.push(p2.x, p2.y, p2.z, p2.x, p2.y, p2.z);
        p2Attributes.nextPosition.values.push(
          nextPositions[i2 * 3],
          nextPositions[i2 * 3 + 1],
          nextPositions[i2 * 3 + 2]
        );
        p2Attributes.nextPosition.values.push(
          nextPositions[i2 * 3 + 3],
          nextPositions[i2 * 3 + 4],
          nextPositions[i2 * 3 + 5]
        );

        const ew0 = Cartesian2.fromArray(
          expandAndWidths,
          i0 * 2,
          cartesian2Scratch0
        );
        const width = Math.abs(ew0.y);

        p0Attributes.expandAndWidth.values.push(-1, width, 1, width);
        p0Attributes.expandAndWidth.values.push(-1, -width, 1, -width);
        p2Attributes.expandAndWidth.values.push(-1, width, 1, width);
        p2Attributes.expandAndWidth.values.push(-1, -width, 1, -width);

        let t = Cartesian3.magnitudeSquared(
          Cartesian3.subtract(intersection, p0, cartesian3Scratch3$1)
        );
        t /= Cartesian3.magnitudeSquared(
          Cartesian3.subtract(p2, p0, cartesian3Scratch3$1)
        );

        if (defined(colors)) {
          const c0 = Cartesian4.fromArray(colors, i0 * 4, cartesian4Scratch0);
          const c2 = Cartesian4.fromArray(colors, i2 * 4, cartesian4Scratch0);

          const r = CesiumMath.lerp(c0.x, c2.x, t);
          const g = CesiumMath.lerp(c0.y, c2.y, t);
          const b = CesiumMath.lerp(c0.z, c2.z, t);
          const a = CesiumMath.lerp(c0.w, c2.w, t);

          for (j = i0 * 4; j < i0 * 4 + 2 * 4; ++j) {
            p0Attributes.color.values.push(colors[j]);
          }
          p0Attributes.color.values.push(r, g, b, a);
          p0Attributes.color.values.push(r, g, b, a);
          p2Attributes.color.values.push(r, g, b, a);
          p2Attributes.color.values.push(r, g, b, a);
          for (j = i2 * 4; j < i2 * 4 + 2 * 4; ++j) {
            p2Attributes.color.values.push(colors[j]);
          }
        }

        if (defined(texCoords)) {
          const s0 = Cartesian2.fromArray(texCoords, i0 * 2, cartesian2Scratch0);
          const s3 = Cartesian2.fromArray(
            texCoords,
            (i + 3) * 2,
            cartesian2Scratch1
          );

          const sx = CesiumMath.lerp(s0.x, s3.x, t);

          for (j = i0 * 2; j < i0 * 2 + 2 * 2; ++j) {
            p0Attributes.st.values.push(texCoords[j]);
          }
          p0Attributes.st.values.push(sx, s0.y);
          p0Attributes.st.values.push(sx, s3.y);
          p2Attributes.st.values.push(sx, s0.y);
          p2Attributes.st.values.push(sx, s3.y);
          for (j = i2 * 2; j < i2 * 2 + 2 * 2; ++j) {
            p2Attributes.st.values.push(texCoords[j]);
          }
        }

        index = p0Attributes.position.values.length / 3 - 4;
        p0Indices.push(index, index + 2, index + 1);
        p0Indices.push(index + 1, index + 2, index + 3);

        index = p2Attributes.position.values.length / 3 - 4;
        p2Indices.push(index, index + 2, index + 1);
        p2Indices.push(index + 1, index + 2, index + 3);
      } else {
        let currentAttributes;
        let currentIndices;

        if (p0.y < 0.0) {
          currentAttributes = westGeometry.attributes;
          currentIndices = westGeometry.indices;
        } else {
          currentAttributes = eastGeometry.attributes;
          currentIndices = eastGeometry.indices;
        }

        currentAttributes.position.values.push(p0.x, p0.y, p0.z);
        currentAttributes.position.values.push(p0.x, p0.y, p0.z);
        currentAttributes.position.values.push(p2.x, p2.y, p2.z);
        currentAttributes.position.values.push(p2.x, p2.y, p2.z);

        for (j = i * 3; j < i * 3 + 4 * 3; ++j) {
          currentAttributes.prevPosition.values.push(prevPositions[j]);
          currentAttributes.nextPosition.values.push(nextPositions[j]);
        }

        for (j = i * 2; j < i * 2 + 4 * 2; ++j) {
          currentAttributes.expandAndWidth.values.push(expandAndWidths[j]);
          if (defined(texCoords)) {
            currentAttributes.st.values.push(texCoords[j]);
          }
        }

        if (defined(colors)) {
          for (j = i * 4; j < i * 4 + 4 * 4; ++j) {
            currentAttributes.color.values.push(colors[j]);
          }
        }

        index = currentAttributes.position.values.length / 3 - 4;
        currentIndices.push(index, index + 2, index + 1);
        currentIndices.push(index + 1, index + 2, index + 3);
      }
    }

    if (intersectionFound) {
      updateAdjacencyAfterSplit(westGeometry);
      updateAdjacencyAfterSplit(eastGeometry);
    }

    updateInstanceAfterSplit(instance, westGeometry, eastGeometry);
  }

  /**
   * Splits the instances's geometry, by introducing new vertices and indices,that
   * intersect the International Date Line and Prime Meridian so that no primitives cross longitude
   * -180/180 degrees.  This is not required for 3D drawing, but is required for
   * correcting drawing in 2D and Columbus view.
   *
   * @private
   *
   * @param {GeometryInstance} instance The instance to modify.
   * @returns {GeometryInstance} The modified <code>instance</code> argument, with it's geometry split at the International Date Line.
   *
   * @example
   * instance = Cesium.GeometryPipeline.splitLongitude(instance);
   */
  GeometryPipeline.splitLongitude = function (instance) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(instance)) {
      throw new DeveloperError("instance is required.");
    }
    //>>includeEnd('debug');

    const geometry = instance.geometry;
    const boundingSphere = geometry.boundingSphere;
    if (defined(boundingSphere)) {
      const minX = boundingSphere.center.x - boundingSphere.radius;
      if (
        minX > 0 ||
        BoundingSphere.intersectPlane(boundingSphere, Plane.ORIGIN_ZX_PLANE) !==
          Intersect$1.INTERSECTING
      ) {
        return instance;
      }
    }

    if (geometry.geometryType !== GeometryType$1.NONE) {
      switch (geometry.geometryType) {
        case GeometryType$1.POLYLINES:
          splitLongitudePolyline(instance);
          break;
        case GeometryType$1.TRIANGLES:
          splitLongitudeTriangles(instance);
          break;
        case GeometryType$1.LINES:
          splitLongitudeLines(instance);
          break;
      }
    } else {
      indexPrimitive(geometry);
      if (geometry.primitiveType === PrimitiveType$1.TRIANGLES) {
        splitLongitudeTriangles(instance);
      } else if (geometry.primitiveType === PrimitiveType$1.LINES) {
        splitLongitudeLines(instance);
      }
    }

    return instance;
  };

  const scratchCartesian1$5 = new Cartesian3();
  const scratchCartesian2$7 = new Cartesian3();
  const scratchCartesian3$8 = new Cartesian3();
  const scratchCartesian4$5 = new Cartesian3();
  const texCoordScratch = new Cartesian2();
  const textureMatrixScratch$1 = new Matrix3();
  const tangentMatrixScratch$1 = new Matrix3();
  const quaternionScratch$3 = new Quaternion();

  const scratchNormal$5 = new Cartesian3();
  const scratchTangent$4 = new Cartesian3();
  const scratchBitangent$4 = new Cartesian3();

  const scratchCartographic$g = new Cartographic();
  const projectedCenterScratch = new Cartesian3();

  const scratchMinTexCoord = new Cartesian2();
  const scratchMaxTexCoord = new Cartesian2();

  function computeTopBottomAttributes(positions, options, extrude) {
    const vertexFormat = options.vertexFormat;
    const center = options.center;
    const semiMajorAxis = options.semiMajorAxis;
    const semiMinorAxis = options.semiMinorAxis;
    const ellipsoid = options.ellipsoid;
    const stRotation = options.stRotation;
    const size = extrude ? (positions.length / 3) * 2 : positions.length / 3;
    const shadowVolume = options.shadowVolume;

    const textureCoordinates = vertexFormat.st
      ? new Float32Array(size * 2)
      : undefined;
    const normals = vertexFormat.normal ? new Float32Array(size * 3) : undefined;
    const tangents = vertexFormat.tangent
      ? new Float32Array(size * 3)
      : undefined;
    const bitangents = vertexFormat.bitangent
      ? new Float32Array(size * 3)
      : undefined;

    const extrudeNormals = shadowVolume ? new Float32Array(size * 3) : undefined;

    let textureCoordIndex = 0;

    // Raise positions to a height above the ellipsoid and compute the
    // texture coordinates, normals, tangents, and bitangents.
    let normal = scratchNormal$5;
    let tangent = scratchTangent$4;
    let bitangent = scratchBitangent$4;

    const projection = new GeographicProjection(ellipsoid);
    const projectedCenter = projection.project(
      ellipsoid.cartesianToCartographic(center, scratchCartographic$g),
      projectedCenterScratch
    );

    const geodeticNormal = ellipsoid.scaleToGeodeticSurface(
      center,
      scratchCartesian1$5
    );
    ellipsoid.geodeticSurfaceNormal(geodeticNormal, geodeticNormal);

    let textureMatrix = textureMatrixScratch$1;
    let tangentMatrix = tangentMatrixScratch$1;
    if (stRotation !== 0) {
      let rotation = Quaternion.fromAxisAngle(
        geodeticNormal,
        stRotation,
        quaternionScratch$3
      );
      textureMatrix = Matrix3.fromQuaternion(rotation, textureMatrix);

      rotation = Quaternion.fromAxisAngle(
        geodeticNormal,
        -stRotation,
        quaternionScratch$3
      );
      tangentMatrix = Matrix3.fromQuaternion(rotation, tangentMatrix);
    } else {
      textureMatrix = Matrix3.clone(Matrix3.IDENTITY, textureMatrix);
      tangentMatrix = Matrix3.clone(Matrix3.IDENTITY, tangentMatrix);
    }

    const minTexCoord = Cartesian2.fromElements(
      Number.POSITIVE_INFINITY,
      Number.POSITIVE_INFINITY,
      scratchMinTexCoord
    );
    const maxTexCoord = Cartesian2.fromElements(
      Number.NEGATIVE_INFINITY,
      Number.NEGATIVE_INFINITY,
      scratchMaxTexCoord
    );

    let length = positions.length;
    const bottomOffset = extrude ? length : 0;
    const stOffset = (bottomOffset / 3) * 2;
    for (let i = 0; i < length; i += 3) {
      const i1 = i + 1;
      const i2 = i + 2;
      const position = Cartesian3.fromArray(positions, i, scratchCartesian1$5);

      if (vertexFormat.st) {
        const rotatedPoint = Matrix3.multiplyByVector(
          textureMatrix,
          position,
          scratchCartesian2$7
        );
        const projectedPoint = projection.project(
          ellipsoid.cartesianToCartographic(rotatedPoint, scratchCartographic$g),
          scratchCartesian3$8
        );
        Cartesian3.subtract(projectedPoint, projectedCenter, projectedPoint);

        texCoordScratch.x =
          (projectedPoint.x + semiMajorAxis) / (2.0 * semiMajorAxis);
        texCoordScratch.y =
          (projectedPoint.y + semiMinorAxis) / (2.0 * semiMinorAxis);

        minTexCoord.x = Math.min(texCoordScratch.x, minTexCoord.x);
        minTexCoord.y = Math.min(texCoordScratch.y, minTexCoord.y);
        maxTexCoord.x = Math.max(texCoordScratch.x, maxTexCoord.x);
        maxTexCoord.y = Math.max(texCoordScratch.y, maxTexCoord.y);

        if (extrude) {
          textureCoordinates[textureCoordIndex + stOffset] = texCoordScratch.x;
          textureCoordinates[textureCoordIndex + 1 + stOffset] =
            texCoordScratch.y;
        }

        textureCoordinates[textureCoordIndex++] = texCoordScratch.x;
        textureCoordinates[textureCoordIndex++] = texCoordScratch.y;
      }

      if (
        vertexFormat.normal ||
        vertexFormat.tangent ||
        vertexFormat.bitangent ||
        shadowVolume
      ) {
        normal = ellipsoid.geodeticSurfaceNormal(position, normal);

        if (shadowVolume) {
          extrudeNormals[i + bottomOffset] = -normal.x;
          extrudeNormals[i1 + bottomOffset] = -normal.y;
          extrudeNormals[i2 + bottomOffset] = -normal.z;
        }

        if (
          vertexFormat.normal ||
          vertexFormat.tangent ||
          vertexFormat.bitangent
        ) {
          if (vertexFormat.tangent || vertexFormat.bitangent) {
            tangent = Cartesian3.normalize(
              Cartesian3.cross(Cartesian3.UNIT_Z, normal, tangent),
              tangent
            );
            Matrix3.multiplyByVector(tangentMatrix, tangent, tangent);
          }
          if (vertexFormat.normal) {
            normals[i] = normal.x;
            normals[i1] = normal.y;
            normals[i2] = normal.z;
            if (extrude) {
              normals[i + bottomOffset] = -normal.x;
              normals[i1 + bottomOffset] = -normal.y;
              normals[i2 + bottomOffset] = -normal.z;
            }
          }

          if (vertexFormat.tangent) {
            tangents[i] = tangent.x;
            tangents[i1] = tangent.y;
            tangents[i2] = tangent.z;
            if (extrude) {
              tangents[i + bottomOffset] = -tangent.x;
              tangents[i1 + bottomOffset] = -tangent.y;
              tangents[i2 + bottomOffset] = -tangent.z;
            }
          }

          if (vertexFormat.bitangent) {
            bitangent = Cartesian3.normalize(
              Cartesian3.cross(normal, tangent, bitangent),
              bitangent
            );
            bitangents[i] = bitangent.x;
            bitangents[i1] = bitangent.y;
            bitangents[i2] = bitangent.z;
            if (extrude) {
              bitangents[i + bottomOffset] = bitangent.x;
              bitangents[i1 + bottomOffset] = bitangent.y;
              bitangents[i2 + bottomOffset] = bitangent.z;
            }
          }
        }
      }
    }

    if (vertexFormat.st) {
      length = textureCoordinates.length;
      for (let k = 0; k < length; k += 2) {
        textureCoordinates[k] =
          (textureCoordinates[k] - minTexCoord.x) /
          (maxTexCoord.x - minTexCoord.x);
        textureCoordinates[k + 1] =
          (textureCoordinates[k + 1] - minTexCoord.y) /
          (maxTexCoord.y - minTexCoord.y);
      }
    }

    const attributes = new GeometryAttributes();

    if (vertexFormat.position) {
      const finalPositions = EllipseGeometryLibrary.raisePositionsToHeight(
        positions,
        options,
        extrude
      );
      attributes.position = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.DOUBLE,
        componentsPerAttribute: 3,
        values: finalPositions,
      });
    }

    if (vertexFormat.st) {
      attributes.st = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 2,
        values: textureCoordinates,
      });
    }

    if (vertexFormat.normal) {
      attributes.normal = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 3,
        values: normals,
      });
    }

    if (vertexFormat.tangent) {
      attributes.tangent = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 3,
        values: tangents,
      });
    }

    if (vertexFormat.bitangent) {
      attributes.bitangent = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 3,
        values: bitangents,
      });
    }

    if (shadowVolume) {
      attributes.extrudeDirection = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 3,
        values: extrudeNormals,
      });
    }

    if (extrude && defined(options.offsetAttribute)) {
      let offsetAttribute = new Uint8Array(size);
      if (options.offsetAttribute === GeometryOffsetAttribute$1.TOP) {
        offsetAttribute = offsetAttribute.fill(1, 0, size / 2);
      } else {
        const offsetValue =
          options.offsetAttribute === GeometryOffsetAttribute$1.NONE ? 0 : 1;
        offsetAttribute = offsetAttribute.fill(offsetValue);
      }

      attributes.applyOffset = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
        componentsPerAttribute: 1,
        values: offsetAttribute,
      });
    }

    return attributes;
  }

  function topIndices(numPts) {
    // numTriangles in half = 3 + 8 + 12 + ... = -1 + 4 + (4 + 4) + (4 + 4 + 4) + ... = -1 + 4 * (1 + 2 + 3 + ...)
    //              = -1 + 4 * ((n * ( n + 1)) / 2)
    // total triangles = 2 * numTrangles in half
    // indices = total triangles * 3;
    // Substitute numPts for n above

    const indices = new Array(12 * (numPts * (numPts + 1)) - 6);
    let indicesIndex = 0;
    let prevIndex;
    let numInterior;
    let positionIndex;
    let i;
    let j;
    // Indices triangles to the 'right' of the north vector

    prevIndex = 0;
    positionIndex = 1;
    for (i = 0; i < 3; i++) {
      indices[indicesIndex++] = positionIndex++;
      indices[indicesIndex++] = prevIndex;
      indices[indicesIndex++] = positionIndex;
    }

    for (i = 2; i < numPts + 1; ++i) {
      positionIndex = i * (i + 1) - 1;
      prevIndex = (i - 1) * i - 1;

      indices[indicesIndex++] = positionIndex++;
      indices[indicesIndex++] = prevIndex;
      indices[indicesIndex++] = positionIndex;

      numInterior = 2 * i;
      for (j = 0; j < numInterior - 1; ++j) {
        indices[indicesIndex++] = positionIndex;
        indices[indicesIndex++] = prevIndex++;
        indices[indicesIndex++] = prevIndex;

        indices[indicesIndex++] = positionIndex++;
        indices[indicesIndex++] = prevIndex;
        indices[indicesIndex++] = positionIndex;
      }

      indices[indicesIndex++] = positionIndex++;
      indices[indicesIndex++] = prevIndex;
      indices[indicesIndex++] = positionIndex;
    }

    // Indices for center column of triangles
    numInterior = numPts * 2;
    ++positionIndex;
    ++prevIndex;
    for (i = 0; i < numInterior - 1; ++i) {
      indices[indicesIndex++] = positionIndex;
      indices[indicesIndex++] = prevIndex++;
      indices[indicesIndex++] = prevIndex;

      indices[indicesIndex++] = positionIndex++;
      indices[indicesIndex++] = prevIndex;
      indices[indicesIndex++] = positionIndex;
    }

    indices[indicesIndex++] = positionIndex;
    indices[indicesIndex++] = prevIndex++;
    indices[indicesIndex++] = prevIndex;

    indices[indicesIndex++] = positionIndex++;
    indices[indicesIndex++] = prevIndex++;
    indices[indicesIndex++] = prevIndex;

    // Reverse the process creating indices to the 'left' of the north vector
    ++prevIndex;
    for (i = numPts - 1; i > 1; --i) {
      indices[indicesIndex++] = prevIndex++;
      indices[indicesIndex++] = prevIndex;
      indices[indicesIndex++] = positionIndex;

      numInterior = 2 * i;
      for (j = 0; j < numInterior - 1; ++j) {
        indices[indicesIndex++] = positionIndex;
        indices[indicesIndex++] = prevIndex++;
        indices[indicesIndex++] = prevIndex;

        indices[indicesIndex++] = positionIndex++;
        indices[indicesIndex++] = prevIndex;
        indices[indicesIndex++] = positionIndex;
      }

      indices[indicesIndex++] = prevIndex++;
      indices[indicesIndex++] = prevIndex++;
      indices[indicesIndex++] = positionIndex++;
    }

    for (i = 0; i < 3; i++) {
      indices[indicesIndex++] = prevIndex++;
      indices[indicesIndex++] = prevIndex;
      indices[indicesIndex++] = positionIndex;
    }
    return indices;
  }

  let boundingSphereCenter$1 = new Cartesian3();

  function computeEllipse$1(options) {
    const center = options.center;
    boundingSphereCenter$1 = Cartesian3.multiplyByScalar(
      options.ellipsoid.geodeticSurfaceNormal(center, boundingSphereCenter$1),
      options.height,
      boundingSphereCenter$1
    );
    boundingSphereCenter$1 = Cartesian3.add(
      center,
      boundingSphereCenter$1,
      boundingSphereCenter$1
    );
    const boundingSphere = new BoundingSphere(
      boundingSphereCenter$1,
      options.semiMajorAxis
    );
    const cep = EllipseGeometryLibrary.computeEllipsePositions(
      options,
      true,
      false
    );
    const positions = cep.positions;
    const numPts = cep.numPts;
    const attributes = computeTopBottomAttributes(positions, options, false);
    let indices = topIndices(numPts);
    indices = IndexDatatype$1.createTypedArray(positions.length / 3, indices);
    return {
      boundingSphere: boundingSphere,
      attributes: attributes,
      indices: indices,
    };
  }

  function computeWallAttributes(positions, options) {
    const vertexFormat = options.vertexFormat;
    const center = options.center;
    const semiMajorAxis = options.semiMajorAxis;
    const semiMinorAxis = options.semiMinorAxis;
    const ellipsoid = options.ellipsoid;
    const height = options.height;
    const extrudedHeight = options.extrudedHeight;
    const stRotation = options.stRotation;
    const size = (positions.length / 3) * 2;

    const finalPositions = new Float64Array(size * 3);
    const textureCoordinates = vertexFormat.st
      ? new Float32Array(size * 2)
      : undefined;
    const normals = vertexFormat.normal ? new Float32Array(size * 3) : undefined;
    const tangents = vertexFormat.tangent
      ? new Float32Array(size * 3)
      : undefined;
    const bitangents = vertexFormat.bitangent
      ? new Float32Array(size * 3)
      : undefined;

    const shadowVolume = options.shadowVolume;
    const extrudeNormals = shadowVolume ? new Float32Array(size * 3) : undefined;

    let textureCoordIndex = 0;

    // Raise positions to a height above the ellipsoid and compute the
    // texture coordinates, normals, tangents, and bitangents.
    let normal = scratchNormal$5;
    let tangent = scratchTangent$4;
    let bitangent = scratchBitangent$4;

    const projection = new GeographicProjection(ellipsoid);
    const projectedCenter = projection.project(
      ellipsoid.cartesianToCartographic(center, scratchCartographic$g),
      projectedCenterScratch
    );

    const geodeticNormal = ellipsoid.scaleToGeodeticSurface(
      center,
      scratchCartesian1$5
    );
    ellipsoid.geodeticSurfaceNormal(geodeticNormal, geodeticNormal);
    const rotation = Quaternion.fromAxisAngle(
      geodeticNormal,
      stRotation,
      quaternionScratch$3
    );
    const textureMatrix = Matrix3.fromQuaternion(rotation, textureMatrixScratch$1);

    const minTexCoord = Cartesian2.fromElements(
      Number.POSITIVE_INFINITY,
      Number.POSITIVE_INFINITY,
      scratchMinTexCoord
    );
    const maxTexCoord = Cartesian2.fromElements(
      Number.NEGATIVE_INFINITY,
      Number.NEGATIVE_INFINITY,
      scratchMaxTexCoord
    );

    let length = positions.length;
    const stOffset = (length / 3) * 2;
    for (let i = 0; i < length; i += 3) {
      const i1 = i + 1;
      const i2 = i + 2;
      let position = Cartesian3.fromArray(positions, i, scratchCartesian1$5);
      let extrudedPosition;

      if (vertexFormat.st) {
        const rotatedPoint = Matrix3.multiplyByVector(
          textureMatrix,
          position,
          scratchCartesian2$7
        );
        const projectedPoint = projection.project(
          ellipsoid.cartesianToCartographic(rotatedPoint, scratchCartographic$g),
          scratchCartesian3$8
        );
        Cartesian3.subtract(projectedPoint, projectedCenter, projectedPoint);

        texCoordScratch.x =
          (projectedPoint.x + semiMajorAxis) / (2.0 * semiMajorAxis);
        texCoordScratch.y =
          (projectedPoint.y + semiMinorAxis) / (2.0 * semiMinorAxis);

        minTexCoord.x = Math.min(texCoordScratch.x, minTexCoord.x);
        minTexCoord.y = Math.min(texCoordScratch.y, minTexCoord.y);
        maxTexCoord.x = Math.max(texCoordScratch.x, maxTexCoord.x);
        maxTexCoord.y = Math.max(texCoordScratch.y, maxTexCoord.y);

        textureCoordinates[textureCoordIndex + stOffset] = texCoordScratch.x;
        textureCoordinates[textureCoordIndex + 1 + stOffset] = texCoordScratch.y;

        textureCoordinates[textureCoordIndex++] = texCoordScratch.x;
        textureCoordinates[textureCoordIndex++] = texCoordScratch.y;
      }

      position = ellipsoid.scaleToGeodeticSurface(position, position);
      extrudedPosition = Cartesian3.clone(position, scratchCartesian2$7);
      normal = ellipsoid.geodeticSurfaceNormal(position, normal);

      if (shadowVolume) {
        extrudeNormals[i + length] = -normal.x;
        extrudeNormals[i1 + length] = -normal.y;
        extrudeNormals[i2 + length] = -normal.z;
      }

      let scaledNormal = Cartesian3.multiplyByScalar(
        normal,
        height,
        scratchCartesian4$5
      );
      position = Cartesian3.add(position, scaledNormal, position);
      scaledNormal = Cartesian3.multiplyByScalar(
        normal,
        extrudedHeight,
        scaledNormal
      );
      extrudedPosition = Cartesian3.add(
        extrudedPosition,
        scaledNormal,
        extrudedPosition
      );

      if (vertexFormat.position) {
        finalPositions[i + length] = extrudedPosition.x;
        finalPositions[i1 + length] = extrudedPosition.y;
        finalPositions[i2 + length] = extrudedPosition.z;

        finalPositions[i] = position.x;
        finalPositions[i1] = position.y;
        finalPositions[i2] = position.z;
      }

      if (vertexFormat.normal || vertexFormat.tangent || vertexFormat.bitangent) {
        bitangent = Cartesian3.clone(normal, bitangent);
        const next = Cartesian3.fromArray(
          positions,
          (i + 3) % length,
          scratchCartesian4$5
        );
        Cartesian3.subtract(next, position, next);
        const bottom = Cartesian3.subtract(
          extrudedPosition,
          position,
          scratchCartesian3$8
        );

        normal = Cartesian3.normalize(
          Cartesian3.cross(bottom, next, normal),
          normal
        );

        if (vertexFormat.normal) {
          normals[i] = normal.x;
          normals[i1] = normal.y;
          normals[i2] = normal.z;

          normals[i + length] = normal.x;
          normals[i1 + length] = normal.y;
          normals[i2 + length] = normal.z;
        }

        if (vertexFormat.tangent) {
          tangent = Cartesian3.normalize(
            Cartesian3.cross(bitangent, normal, tangent),
            tangent
          );
          tangents[i] = tangent.x;
          tangents[i1] = tangent.y;
          tangents[i2] = tangent.z;

          tangents[i + length] = tangent.x;
          tangents[i + 1 + length] = tangent.y;
          tangents[i + 2 + length] = tangent.z;
        }

        if (vertexFormat.bitangent) {
          bitangents[i] = bitangent.x;
          bitangents[i1] = bitangent.y;
          bitangents[i2] = bitangent.z;

          bitangents[i + length] = bitangent.x;
          bitangents[i1 + length] = bitangent.y;
          bitangents[i2 + length] = bitangent.z;
        }
      }
    }

    if (vertexFormat.st) {
      length = textureCoordinates.length;
      for (let k = 0; k < length; k += 2) {
        textureCoordinates[k] =
          (textureCoordinates[k] - minTexCoord.x) /
          (maxTexCoord.x - minTexCoord.x);
        textureCoordinates[k + 1] =
          (textureCoordinates[k + 1] - minTexCoord.y) /
          (maxTexCoord.y - minTexCoord.y);
      }
    }

    const attributes = new GeometryAttributes();

    if (vertexFormat.position) {
      attributes.position = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.DOUBLE,
        componentsPerAttribute: 3,
        values: finalPositions,
      });
    }

    if (vertexFormat.st) {
      attributes.st = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 2,
        values: textureCoordinates,
      });
    }

    if (vertexFormat.normal) {
      attributes.normal = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 3,
        values: normals,
      });
    }

    if (vertexFormat.tangent) {
      attributes.tangent = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 3,
        values: tangents,
      });
    }

    if (vertexFormat.bitangent) {
      attributes.bitangent = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 3,
        values: bitangents,
      });
    }

    if (shadowVolume) {
      attributes.extrudeDirection = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 3,
        values: extrudeNormals,
      });
    }

    if (defined(options.offsetAttribute)) {
      let offsetAttribute = new Uint8Array(size);
      if (options.offsetAttribute === GeometryOffsetAttribute$1.TOP) {
        offsetAttribute = offsetAttribute.fill(1, 0, size / 2);
      } else {
        const offsetValue =
          options.offsetAttribute === GeometryOffsetAttribute$1.NONE ? 0 : 1;
        offsetAttribute = offsetAttribute.fill(offsetValue);
      }
      attributes.applyOffset = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
        componentsPerAttribute: 1,
        values: offsetAttribute,
      });
    }

    return attributes;
  }

  function computeWallIndices(positions) {
    const length = positions.length / 3;
    const indices = IndexDatatype$1.createTypedArray(length, length * 6);
    let index = 0;
    for (let i = 0; i < length; i++) {
      const UL = i;
      const LL = i + length;
      const UR = (UL + 1) % length;
      const LR = UR + length;
      indices[index++] = UL;
      indices[index++] = LL;
      indices[index++] = UR;
      indices[index++] = UR;
      indices[index++] = LL;
      indices[index++] = LR;
    }

    return indices;
  }

  const topBoundingSphere$3 = new BoundingSphere();
  const bottomBoundingSphere$3 = new BoundingSphere();

  function computeExtrudedEllipse$1(options) {
    const center = options.center;
    const ellipsoid = options.ellipsoid;
    const semiMajorAxis = options.semiMajorAxis;
    let scaledNormal = Cartesian3.multiplyByScalar(
      ellipsoid.geodeticSurfaceNormal(center, scratchCartesian1$5),
      options.height,
      scratchCartesian1$5
    );
    topBoundingSphere$3.center = Cartesian3.add(
      center,
      scaledNormal,
      topBoundingSphere$3.center
    );
    topBoundingSphere$3.radius = semiMajorAxis;

    scaledNormal = Cartesian3.multiplyByScalar(
      ellipsoid.geodeticSurfaceNormal(center, scaledNormal),
      options.extrudedHeight,
      scaledNormal
    );
    bottomBoundingSphere$3.center = Cartesian3.add(
      center,
      scaledNormal,
      bottomBoundingSphere$3.center
    );
    bottomBoundingSphere$3.radius = semiMajorAxis;

    const cep = EllipseGeometryLibrary.computeEllipsePositions(
      options,
      true,
      true
    );
    const positions = cep.positions;
    const numPts = cep.numPts;
    const outerPositions = cep.outerPositions;
    const boundingSphere = BoundingSphere.union(
      topBoundingSphere$3,
      bottomBoundingSphere$3
    );
    const topBottomAttributes = computeTopBottomAttributes(
      positions,
      options,
      true
    );
    let indices = topIndices(numPts);
    const length = indices.length;
    indices.length = length * 2;
    const posLength = positions.length / 3;
    for (let i = 0; i < length; i += 3) {
      indices[i + length] = indices[i + 2] + posLength;
      indices[i + 1 + length] = indices[i + 1] + posLength;
      indices[i + 2 + length] = indices[i] + posLength;
    }

    const topBottomIndices = IndexDatatype$1.createTypedArray(
      (posLength * 2) / 3,
      indices
    );

    const topBottomGeo = new Geometry({
      attributes: topBottomAttributes,
      indices: topBottomIndices,
      primitiveType: PrimitiveType$1.TRIANGLES,
    });

    const wallAttributes = computeWallAttributes(outerPositions, options);
    indices = computeWallIndices(outerPositions);
    const wallIndices = IndexDatatype$1.createTypedArray(
      (outerPositions.length * 2) / 3,
      indices
    );

    const wallGeo = new Geometry({
      attributes: wallAttributes,
      indices: wallIndices,
      primitiveType: PrimitiveType$1.TRIANGLES,
    });

    const geo = GeometryPipeline.combineInstances([
      new GeometryInstance({
        geometry: topBottomGeo,
      }),
      new GeometryInstance({
        geometry: wallGeo,
      }),
    ]);

    return {
      boundingSphere: boundingSphere,
      attributes: geo[0].attributes,
      indices: geo[0].indices,
    };
  }

  function computeRectangle$3(
    center,
    semiMajorAxis,
    semiMinorAxis,
    rotation,
    granularity,
    ellipsoid,
    result
  ) {
    const cep = EllipseGeometryLibrary.computeEllipsePositions(
      {
        center: center,
        semiMajorAxis: semiMajorAxis,
        semiMinorAxis: semiMinorAxis,
        rotation: rotation,
        granularity: granularity,
      },
      false,
      true
    );
    const positionsFlat = cep.outerPositions;
    const positionsCount = positionsFlat.length / 3;
    const positions = new Array(positionsCount);
    for (let i = 0; i < positionsCount; ++i) {
      positions[i] = Cartesian3.fromArray(positionsFlat, i * 3);
    }
    const rectangle = Rectangle.fromCartesianArray(positions, ellipsoid, result);
    // Rectangle width goes beyond 180 degrees when the ellipse crosses a pole.
    // When this happens, make the rectangle into a "circle" around the pole
    if (rectangle.width > CesiumMath.PI) {
      rectangle.north =
        rectangle.north > 0.0
          ? CesiumMath.PI_OVER_TWO - CesiumMath.EPSILON7
          : rectangle.north;
      rectangle.south =
        rectangle.south < 0.0
          ? CesiumMath.EPSILON7 - CesiumMath.PI_OVER_TWO
          : rectangle.south;
      rectangle.east = CesiumMath.PI;
      rectangle.west = -CesiumMath.PI;
    }
    return rectangle;
  }

  /**
   * A description of an ellipse on an ellipsoid. Ellipse geometry can be rendered with both {@link Primitive} and {@link GroundPrimitive}.
   *
   * @alias EllipseGeometry
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Cartesian3} options.center The ellipse's center point in the fixed frame.
   * @param {Number} options.semiMajorAxis The length of the ellipse's semi-major axis in meters.
   * @param {Number} options.semiMinorAxis The length of the ellipse's semi-minor axis in meters.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid the ellipse will be on.
   * @param {Number} [options.height=0.0] The distance in meters between the ellipse and the ellipsoid surface.
   * @param {Number} [options.extrudedHeight] The distance in meters between the ellipse's extruded face and the ellipsoid surface.
   * @param {Number} [options.rotation=0.0] The angle of rotation counter-clockwise from north.
   * @param {Number} [options.stRotation=0.0] The rotation of the texture coordinates counter-clockwise from north.
   * @param {Number} [options.granularity=CesiumMath.RADIANS_PER_DEGREE] The angular distance between points on the ellipse in radians.
   * @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
   *
   * @exception {DeveloperError} semiMajorAxis and semiMinorAxis must be greater than zero.
   * @exception {DeveloperError} semiMajorAxis must be greater than or equal to the semiMinorAxis.
   * @exception {DeveloperError} granularity must be greater than zero.
   *
   *
   * @example
   * // Create an ellipse.
   * const ellipse = new Cesium.EllipseGeometry({
   *   center : Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883),
   *   semiMajorAxis : 500000.0,
   *   semiMinorAxis : 300000.0,
   *   rotation : Cesium.Math.toRadians(60.0)
   * });
   * const geometry = Cesium.EllipseGeometry.createGeometry(ellipse);
   *
   * @see EllipseGeometry.createGeometry
   */
  function EllipseGeometry(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const center = options.center;
    const ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);
    const semiMajorAxis = options.semiMajorAxis;
    const semiMinorAxis = options.semiMinorAxis;
    const granularity = defaultValue(
      options.granularity,
      CesiumMath.RADIANS_PER_DEGREE
    );
    const vertexFormat = defaultValue(options.vertexFormat, VertexFormat.DEFAULT);

    //>>includeStart('debug', pragmas.debug);
    Check.defined("options.center", center);
    Check.typeOf.number("options.semiMajorAxis", semiMajorAxis);
    Check.typeOf.number("options.semiMinorAxis", semiMinorAxis);
    if (semiMajorAxis < semiMinorAxis) {
      throw new DeveloperError(
        "semiMajorAxis must be greater than or equal to the semiMinorAxis."
      );
    }
    if (granularity <= 0.0) {
      throw new DeveloperError("granularity must be greater than zero.");
    }
    //>>includeEnd('debug');

    const height = defaultValue(options.height, 0.0);
    const extrudedHeight = defaultValue(options.extrudedHeight, height);

    this._center = Cartesian3.clone(center);
    this._semiMajorAxis = semiMajorAxis;
    this._semiMinorAxis = semiMinorAxis;
    this._ellipsoid = Ellipsoid.clone(ellipsoid);
    this._rotation = defaultValue(options.rotation, 0.0);
    this._stRotation = defaultValue(options.stRotation, 0.0);
    this._height = Math.max(extrudedHeight, height);
    this._granularity = granularity;
    this._vertexFormat = VertexFormat.clone(vertexFormat);
    this._extrudedHeight = Math.min(extrudedHeight, height);
    this._shadowVolume = defaultValue(options.shadowVolume, false);
    this._workerName = "createEllipseGeometry";
    this._offsetAttribute = options.offsetAttribute;

    this._rectangle = undefined;
    this._textureCoordinateRotationPoints = undefined;
  }

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  EllipseGeometry.packedLength =
    Cartesian3.packedLength +
    Ellipsoid.packedLength +
    VertexFormat.packedLength +
    9;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {EllipseGeometry} 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
   */
  EllipseGeometry.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("value", value);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    Cartesian3.pack(value._center, array, startingIndex);
    startingIndex += Cartesian3.packedLength;

    Ellipsoid.pack(value._ellipsoid, array, startingIndex);
    startingIndex += Ellipsoid.packedLength;

    VertexFormat.pack(value._vertexFormat, array, startingIndex);
    startingIndex += VertexFormat.packedLength;

    array[startingIndex++] = value._semiMajorAxis;
    array[startingIndex++] = value._semiMinorAxis;
    array[startingIndex++] = value._rotation;
    array[startingIndex++] = value._stRotation;
    array[startingIndex++] = value._height;
    array[startingIndex++] = value._granularity;
    array[startingIndex++] = value._extrudedHeight;
    array[startingIndex++] = value._shadowVolume ? 1.0 : 0.0;
    array[startingIndex] = defaultValue(value._offsetAttribute, -1);

    return array;
  };

  const scratchCenter$7 = new Cartesian3();
  const scratchEllipsoid$e = new Ellipsoid();
  const scratchVertexFormat$b = new VertexFormat();
  const scratchOptions$l = {
    center: scratchCenter$7,
    ellipsoid: scratchEllipsoid$e,
    vertexFormat: scratchVertexFormat$b,
    semiMajorAxis: undefined,
    semiMinorAxis: undefined,
    rotation: undefined,
    stRotation: undefined,
    height: undefined,
    granularity: undefined,
    extrudedHeight: undefined,
    shadowVolume: undefined,
    offsetAttribute: undefined,
  };

  /**
   * 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 {EllipseGeometry} [result] The object into which to store the result.
   * @returns {EllipseGeometry} The modified result parameter or a new EllipseGeometry instance if one was not provided.
   */
  EllipseGeometry.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    const center = Cartesian3.unpack(array, startingIndex, scratchCenter$7);
    startingIndex += Cartesian3.packedLength;

    const ellipsoid = Ellipsoid.unpack(array, startingIndex, scratchEllipsoid$e);
    startingIndex += Ellipsoid.packedLength;

    const vertexFormat = VertexFormat.unpack(
      array,
      startingIndex,
      scratchVertexFormat$b
    );
    startingIndex += VertexFormat.packedLength;

    const semiMajorAxis = array[startingIndex++];
    const semiMinorAxis = array[startingIndex++];
    const rotation = array[startingIndex++];
    const stRotation = array[startingIndex++];
    const height = array[startingIndex++];
    const granularity = array[startingIndex++];
    const extrudedHeight = array[startingIndex++];
    const shadowVolume = array[startingIndex++] === 1.0;
    const offsetAttribute = array[startingIndex];

    if (!defined(result)) {
      scratchOptions$l.height = height;
      scratchOptions$l.extrudedHeight = extrudedHeight;
      scratchOptions$l.granularity = granularity;
      scratchOptions$l.stRotation = stRotation;
      scratchOptions$l.rotation = rotation;
      scratchOptions$l.semiMajorAxis = semiMajorAxis;
      scratchOptions$l.semiMinorAxis = semiMinorAxis;
      scratchOptions$l.shadowVolume = shadowVolume;
      scratchOptions$l.offsetAttribute =
        offsetAttribute === -1 ? undefined : offsetAttribute;

      return new EllipseGeometry(scratchOptions$l);
    }

    result._center = Cartesian3.clone(center, result._center);
    result._ellipsoid = Ellipsoid.clone(ellipsoid, result._ellipsoid);
    result._vertexFormat = VertexFormat.clone(vertexFormat, result._vertexFormat);
    result._semiMajorAxis = semiMajorAxis;
    result._semiMinorAxis = semiMinorAxis;
    result._rotation = rotation;
    result._stRotation = stRotation;
    result._height = height;
    result._granularity = granularity;
    result._extrudedHeight = extrudedHeight;
    result._shadowVolume = shadowVolume;
    result._offsetAttribute =
      offsetAttribute === -1 ? undefined : offsetAttribute;

    return result;
  };

  /**
   * Computes the bounding rectangle based on the provided options
   *
   * @param {Object} options Object with the following properties:
   * @param {Cartesian3} options.center The ellipse's center point in the fixed frame.
   * @param {Number} options.semiMajorAxis The length of the ellipse's semi-major axis in meters.
   * @param {Number} options.semiMinorAxis The length of the ellipse's semi-minor axis in meters.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid the ellipse will be on.
   * @param {Number} [options.rotation=0.0] The angle of rotation counter-clockwise from north.
   * @param {Number} [options.granularity=CesiumMath.RADIANS_PER_DEGREE] The angular distance between points on the ellipse in radians.
   * @param {Rectangle} [result] An object in which to store the result
   *
   * @returns {Rectangle} The result rectangle
   */
  EllipseGeometry.computeRectangle = function (options, result) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const center = options.center;
    const ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);
    const semiMajorAxis = options.semiMajorAxis;
    const semiMinorAxis = options.semiMinorAxis;
    const granularity = defaultValue(
      options.granularity,
      CesiumMath.RADIANS_PER_DEGREE
    );
    const rotation = defaultValue(options.rotation, 0.0);

    //>>includeStart('debug', pragmas.debug);
    Check.defined("options.center", center);
    Check.typeOf.number("options.semiMajorAxis", semiMajorAxis);
    Check.typeOf.number("options.semiMinorAxis", semiMinorAxis);
    if (semiMajorAxis < semiMinorAxis) {
      throw new DeveloperError(
        "semiMajorAxis must be greater than or equal to the semiMinorAxis."
      );
    }
    if (granularity <= 0.0) {
      throw new DeveloperError("granularity must be greater than zero.");
    }
    //>>includeEnd('debug');

    return computeRectangle$3(
      center,
      semiMajorAxis,
      semiMinorAxis,
      rotation,
      granularity,
      ellipsoid,
      result
    );
  };

  /**
   * Computes the geometric representation of a ellipse on an ellipsoid, including its vertices, indices, and a bounding sphere.
   *
   * @param {EllipseGeometry} ellipseGeometry A description of the ellipse.
   * @returns {Geometry|undefined} The computed vertices and indices.
   */
  EllipseGeometry.createGeometry = function (ellipseGeometry) {
    if (
      ellipseGeometry._semiMajorAxis <= 0.0 ||
      ellipseGeometry._semiMinorAxis <= 0.0
    ) {
      return;
    }

    const height = ellipseGeometry._height;
    const extrudedHeight = ellipseGeometry._extrudedHeight;
    const extrude = !CesiumMath.equalsEpsilon(
      height,
      extrudedHeight,
      0,
      CesiumMath.EPSILON2
    );

    ellipseGeometry._center = ellipseGeometry._ellipsoid.scaleToGeodeticSurface(
      ellipseGeometry._center,
      ellipseGeometry._center
    );
    const options = {
      center: ellipseGeometry._center,
      semiMajorAxis: ellipseGeometry._semiMajorAxis,
      semiMinorAxis: ellipseGeometry._semiMinorAxis,
      ellipsoid: ellipseGeometry._ellipsoid,
      rotation: ellipseGeometry._rotation,
      height: height,
      granularity: ellipseGeometry._granularity,
      vertexFormat: ellipseGeometry._vertexFormat,
      stRotation: ellipseGeometry._stRotation,
    };
    let geometry;
    if (extrude) {
      options.extrudedHeight = extrudedHeight;
      options.shadowVolume = ellipseGeometry._shadowVolume;
      options.offsetAttribute = ellipseGeometry._offsetAttribute;
      geometry = computeExtrudedEllipse$1(options);
    } else {
      geometry = computeEllipse$1(options);

      if (defined(ellipseGeometry._offsetAttribute)) {
        const length = geometry.attributes.position.values.length;
        const offsetValue =
          ellipseGeometry._offsetAttribute === GeometryOffsetAttribute$1.NONE
            ? 0
            : 1;
        const applyOffset = new Uint8Array(length / 3).fill(offsetValue);
        geometry.attributes.applyOffset = new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
          componentsPerAttribute: 1,
          values: applyOffset,
        });
      }
    }

    return new Geometry({
      attributes: geometry.attributes,
      indices: geometry.indices,
      primitiveType: PrimitiveType$1.TRIANGLES,
      boundingSphere: geometry.boundingSphere,
      offsetAttribute: ellipseGeometry._offsetAttribute,
    });
  };

  /**
   * @private
   */
  EllipseGeometry.createShadowVolume = function (
    ellipseGeometry,
    minHeightFunc,
    maxHeightFunc
  ) {
    const granularity = ellipseGeometry._granularity;
    const ellipsoid = ellipseGeometry._ellipsoid;

    const minHeight = minHeightFunc(granularity, ellipsoid);
    const maxHeight = maxHeightFunc(granularity, ellipsoid);

    return new EllipseGeometry({
      center: ellipseGeometry._center,
      semiMajorAxis: ellipseGeometry._semiMajorAxis,
      semiMinorAxis: ellipseGeometry._semiMinorAxis,
      ellipsoid: ellipsoid,
      rotation: ellipseGeometry._rotation,
      stRotation: ellipseGeometry._stRotation,
      granularity: granularity,
      extrudedHeight: minHeight,
      height: maxHeight,
      vertexFormat: VertexFormat.POSITION_ONLY,
      shadowVolume: true,
    });
  };

  function textureCoordinateRotationPoints$2(ellipseGeometry) {
    const stRotation = -ellipseGeometry._stRotation;
    if (stRotation === 0.0) {
      return [0, 0, 0, 1, 1, 0];
    }

    const cep = EllipseGeometryLibrary.computeEllipsePositions(
      {
        center: ellipseGeometry._center,
        semiMajorAxis: ellipseGeometry._semiMajorAxis,
        semiMinorAxis: ellipseGeometry._semiMinorAxis,
        rotation: ellipseGeometry._rotation,
        granularity: ellipseGeometry._granularity,
      },
      false,
      true
    );
    const positionsFlat = cep.outerPositions;
    const positionsCount = positionsFlat.length / 3;
    const positions = new Array(positionsCount);
    for (let i = 0; i < positionsCount; ++i) {
      positions[i] = Cartesian3.fromArray(positionsFlat, i * 3);
    }

    const ellipsoid = ellipseGeometry._ellipsoid;
    const boundingRectangle = ellipseGeometry.rectangle;
    return Geometry._textureCoordinateRotationPoints(
      positions,
      stRotation,
      ellipsoid,
      boundingRectangle
    );
  }

  Object.defineProperties(EllipseGeometry.prototype, {
    /**
     * @private
     */
    rectangle: {
      get: function () {
        if (!defined(this._rectangle)) {
          this._rectangle = computeRectangle$3(
            this._center,
            this._semiMajorAxis,
            this._semiMinorAxis,
            this._rotation,
            this._granularity,
            this._ellipsoid
          );
        }
        return this._rectangle;
      },
    },
    /**
     * For remapping texture coordinates when rendering EllipseGeometries as GroundPrimitives.
     * @private
     */
    textureCoordinateRotationPoints: {
      get: function () {
        if (!defined(this._textureCoordinateRotationPoints)) {
          this._textureCoordinateRotationPoints = textureCoordinateRotationPoints$2(
            this
          );
        }
        return this._textureCoordinateRotationPoints;
      },
    },
  });

  /**
   * A description of a circle on the ellipsoid. Circle geometry can be rendered with both {@link Primitive} and {@link GroundPrimitive}.
   *
   * @alias CircleGeometry
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Cartesian3} options.center The circle's center point in the fixed frame.
   * @param {Number} options.radius The radius in meters.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid the circle will be on.
   * @param {Number} [options.height=0.0] The distance in meters between the circle and the ellipsoid surface.
   * @param {Number} [options.granularity=0.02] The angular distance between points on the circle in radians.
   * @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
   * @param {Number} [options.extrudedHeight=0.0] The distance in meters between the circle's extruded face and the ellipsoid surface.
   * @param {Number} [options.stRotation=0.0] The rotation of the texture coordinates, in radians. A positive rotation is counter-clockwise.
   *
   * @exception {DeveloperError} radius must be greater than zero.
   * @exception {DeveloperError} granularity must be greater than zero.
   *
   * @see CircleGeometry.createGeometry
   * @see Packable
   *
   * @example
   * // Create a circle.
   * const circle = new Cesium.CircleGeometry({
   *   center : Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883),
   *   radius : 100000.0
   * });
   * const geometry = Cesium.CircleGeometry.createGeometry(circle);
   */
  function CircleGeometry(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const radius = options.radius;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("radius", radius);
    //>>includeEnd('debug');

    const ellipseGeometryOptions = {
      center: options.center,
      semiMajorAxis: radius,
      semiMinorAxis: radius,
      ellipsoid: options.ellipsoid,
      height: options.height,
      extrudedHeight: options.extrudedHeight,
      granularity: options.granularity,
      vertexFormat: options.vertexFormat,
      stRotation: options.stRotation,
      shadowVolume: options.shadowVolume,
    };
    this._ellipseGeometry = new EllipseGeometry(ellipseGeometryOptions);
    this._workerName = "createCircleGeometry";
  }

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  CircleGeometry.packedLength = EllipseGeometry.packedLength;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {CircleGeometry} 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
   */
  CircleGeometry.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    //>>includeEnd('debug');
    return EllipseGeometry.pack(value._ellipseGeometry, array, startingIndex);
  };

  const scratchEllipseGeometry$1 = new EllipseGeometry({
    center: new Cartesian3(),
    semiMajorAxis: 1.0,
    semiMinorAxis: 1.0,
  });
  const scratchOptions$k = {
    center: new Cartesian3(),
    radius: undefined,
    ellipsoid: Ellipsoid.clone(Ellipsoid.UNIT_SPHERE),
    height: undefined,
    extrudedHeight: undefined,
    granularity: undefined,
    vertexFormat: new VertexFormat(),
    stRotation: undefined,
    semiMajorAxis: undefined,
    semiMinorAxis: undefined,
    shadowVolume: undefined,
  };

  /**
   * 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 {CircleGeometry} [result] The object into which to store the result.
   * @returns {CircleGeometry} The modified result parameter or a new CircleGeometry instance if one was not provided.
   */
  CircleGeometry.unpack = function (array, startingIndex, result) {
    const ellipseGeometry = EllipseGeometry.unpack(
      array,
      startingIndex,
      scratchEllipseGeometry$1
    );
    scratchOptions$k.center = Cartesian3.clone(
      ellipseGeometry._center,
      scratchOptions$k.center
    );
    scratchOptions$k.ellipsoid = Ellipsoid.clone(
      ellipseGeometry._ellipsoid,
      scratchOptions$k.ellipsoid
    );
    scratchOptions$k.height = ellipseGeometry._height;
    scratchOptions$k.extrudedHeight = ellipseGeometry._extrudedHeight;
    scratchOptions$k.granularity = ellipseGeometry._granularity;
    scratchOptions$k.vertexFormat = VertexFormat.clone(
      ellipseGeometry._vertexFormat,
      scratchOptions$k.vertexFormat
    );
    scratchOptions$k.stRotation = ellipseGeometry._stRotation;
    scratchOptions$k.shadowVolume = ellipseGeometry._shadowVolume;

    if (!defined(result)) {
      scratchOptions$k.radius = ellipseGeometry._semiMajorAxis;
      return new CircleGeometry(scratchOptions$k);
    }

    scratchOptions$k.semiMajorAxis = ellipseGeometry._semiMajorAxis;
    scratchOptions$k.semiMinorAxis = ellipseGeometry._semiMinorAxis;
    result._ellipseGeometry = new EllipseGeometry(scratchOptions$k);
    return result;
  };

  /**
   * Computes the geometric representation of a circle on an ellipsoid, including its vertices, indices, and a bounding sphere.
   *
   * @param {CircleGeometry} circleGeometry A description of the circle.
   * @returns {Geometry|undefined} The computed vertices and indices.
   */
  CircleGeometry.createGeometry = function (circleGeometry) {
    return EllipseGeometry.createGeometry(circleGeometry._ellipseGeometry);
  };

  /**
   * @private
   */
  CircleGeometry.createShadowVolume = function (
    circleGeometry,
    minHeightFunc,
    maxHeightFunc
  ) {
    const granularity = circleGeometry._ellipseGeometry._granularity;
    const ellipsoid = circleGeometry._ellipseGeometry._ellipsoid;

    const minHeight = minHeightFunc(granularity, ellipsoid);
    const maxHeight = maxHeightFunc(granularity, ellipsoid);

    return new CircleGeometry({
      center: circleGeometry._ellipseGeometry._center,
      radius: circleGeometry._ellipseGeometry._semiMajorAxis,
      ellipsoid: ellipsoid,
      stRotation: circleGeometry._ellipseGeometry._stRotation,
      granularity: granularity,
      extrudedHeight: minHeight,
      height: maxHeight,
      vertexFormat: VertexFormat.POSITION_ONLY,
      shadowVolume: true,
    });
  };

  Object.defineProperties(CircleGeometry.prototype, {
    /**
     * @private
     */
    rectangle: {
      get: function () {
        return this._ellipseGeometry.rectangle;
      },
    },
    /**
     * For remapping texture coordinates when rendering CircleGeometries as GroundPrimitives.
     * @private
     */
    textureCoordinateRotationPoints: {
      get: function () {
        return this._ellipseGeometry.textureCoordinateRotationPoints;
      },
    },
  });

  const scratchCartesian1$4 = new Cartesian3();
  let boundingSphereCenter = new Cartesian3();

  function computeEllipse(options) {
    const center = options.center;
    boundingSphereCenter = Cartesian3.multiplyByScalar(
      options.ellipsoid.geodeticSurfaceNormal(center, boundingSphereCenter),
      options.height,
      boundingSphereCenter
    );
    boundingSphereCenter = Cartesian3.add(
      center,
      boundingSphereCenter,
      boundingSphereCenter
    );
    const boundingSphere = new BoundingSphere(
      boundingSphereCenter,
      options.semiMajorAxis
    );
    const positions = EllipseGeometryLibrary.computeEllipsePositions(
      options,
      false,
      true
    ).outerPositions;

    const attributes = new GeometryAttributes({
      position: new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.DOUBLE,
        componentsPerAttribute: 3,
        values: EllipseGeometryLibrary.raisePositionsToHeight(
          positions,
          options,
          false
        ),
      }),
    });

    const length = positions.length / 3;
    const indices = IndexDatatype$1.createTypedArray(length, length * 2);
    let index = 0;
    for (let i = 0; i < length; ++i) {
      indices[index++] = i;
      indices[index++] = (i + 1) % length;
    }

    return {
      boundingSphere: boundingSphere,
      attributes: attributes,
      indices: indices,
    };
  }

  const topBoundingSphere$2 = new BoundingSphere();
  const bottomBoundingSphere$2 = new BoundingSphere();
  function computeExtrudedEllipse(options) {
    const center = options.center;
    const ellipsoid = options.ellipsoid;
    const semiMajorAxis = options.semiMajorAxis;
    let scaledNormal = Cartesian3.multiplyByScalar(
      ellipsoid.geodeticSurfaceNormal(center, scratchCartesian1$4),
      options.height,
      scratchCartesian1$4
    );
    topBoundingSphere$2.center = Cartesian3.add(
      center,
      scaledNormal,
      topBoundingSphere$2.center
    );
    topBoundingSphere$2.radius = semiMajorAxis;

    scaledNormal = Cartesian3.multiplyByScalar(
      ellipsoid.geodeticSurfaceNormal(center, scaledNormal),
      options.extrudedHeight,
      scaledNormal
    );
    bottomBoundingSphere$2.center = Cartesian3.add(
      center,
      scaledNormal,
      bottomBoundingSphere$2.center
    );
    bottomBoundingSphere$2.radius = semiMajorAxis;

    let positions = EllipseGeometryLibrary.computeEllipsePositions(
      options,
      false,
      true
    ).outerPositions;
    const attributes = new GeometryAttributes({
      position: new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.DOUBLE,
        componentsPerAttribute: 3,
        values: EllipseGeometryLibrary.raisePositionsToHeight(
          positions,
          options,
          true
        ),
      }),
    });

    positions = attributes.position.values;
    const boundingSphere = BoundingSphere.union(
      topBoundingSphere$2,
      bottomBoundingSphere$2
    );
    let length = positions.length / 3;

    if (defined(options.offsetAttribute)) {
      let applyOffset = new Uint8Array(length);
      if (options.offsetAttribute === GeometryOffsetAttribute$1.TOP) {
        applyOffset = applyOffset.fill(1, 0, length / 2);
      } else {
        const offsetValue =
          options.offsetAttribute === GeometryOffsetAttribute$1.NONE ? 0 : 1;
        applyOffset = applyOffset.fill(offsetValue);
      }

      attributes.applyOffset = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
        componentsPerAttribute: 1,
        values: applyOffset,
      });
    }

    let numberOfVerticalLines = defaultValue(options.numberOfVerticalLines, 16);
    numberOfVerticalLines = CesiumMath.clamp(
      numberOfVerticalLines,
      0,
      length / 2
    );

    const indices = IndexDatatype$1.createTypedArray(
      length,
      length * 2 + numberOfVerticalLines * 2
    );

    length /= 2;
    let index = 0;
    let i;
    for (i = 0; i < length; ++i) {
      indices[index++] = i;
      indices[index++] = (i + 1) % length;
      indices[index++] = i + length;
      indices[index++] = ((i + 1) % length) + length;
    }

    let numSide;
    if (numberOfVerticalLines > 0) {
      const numSideLines = Math.min(numberOfVerticalLines, length);
      numSide = Math.round(length / numSideLines);

      const maxI = Math.min(numSide * numberOfVerticalLines, length);
      for (i = 0; i < maxI; i += numSide) {
        indices[index++] = i;
        indices[index++] = i + length;
      }
    }

    return {
      boundingSphere: boundingSphere,
      attributes: attributes,
      indices: indices,
    };
  }

  /**
   * A description of the outline of an ellipse on an ellipsoid.
   *
   * @alias EllipseOutlineGeometry
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Cartesian3} options.center The ellipse's center point in the fixed frame.
   * @param {Number} options.semiMajorAxis The length of the ellipse's semi-major axis in meters.
   * @param {Number} options.semiMinorAxis The length of the ellipse's semi-minor axis in meters.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid the ellipse will be on.
   * @param {Number} [options.height=0.0] The distance in meters between the ellipse and the ellipsoid surface.
   * @param {Number} [options.extrudedHeight] The distance in meters between the ellipse's extruded face and the ellipsoid surface.
   * @param {Number} [options.rotation=0.0] The angle from north (counter-clockwise) in radians.
   * @param {Number} [options.granularity=0.02] The angular distance between points on the ellipse in radians.
   * @param {Number} [options.numberOfVerticalLines=16] Number of lines to draw between the top and bottom surface of an extruded ellipse.
   *
   * @exception {DeveloperError} semiMajorAxis and semiMinorAxis must be greater than zero.
   * @exception {DeveloperError} semiMajorAxis must be greater than or equal to the semiMinorAxis.
   * @exception {DeveloperError} granularity must be greater than zero.
   *
   * @see EllipseOutlineGeometry.createGeometry
   *
   * @example
   * const ellipse = new Cesium.EllipseOutlineGeometry({
   *   center : Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883),
   *   semiMajorAxis : 500000.0,
   *   semiMinorAxis : 300000.0,
   *   rotation : Cesium.Math.toRadians(60.0)
   * });
   * const geometry = Cesium.EllipseOutlineGeometry.createGeometry(ellipse);
   */
  function EllipseOutlineGeometry(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const center = options.center;
    const ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);
    const semiMajorAxis = options.semiMajorAxis;
    const semiMinorAxis = options.semiMinorAxis;
    const granularity = defaultValue(
      options.granularity,
      CesiumMath.RADIANS_PER_DEGREE
    );

    //>>includeStart('debug', pragmas.debug);
    if (!defined(center)) {
      throw new DeveloperError("center is required.");
    }
    if (!defined(semiMajorAxis)) {
      throw new DeveloperError("semiMajorAxis is required.");
    }
    if (!defined(semiMinorAxis)) {
      throw new DeveloperError("semiMinorAxis is required.");
    }
    if (semiMajorAxis < semiMinorAxis) {
      throw new DeveloperError(
        "semiMajorAxis must be greater than or equal to the semiMinorAxis."
      );
    }
    if (granularity <= 0.0) {
      throw new DeveloperError("granularity must be greater than zero.");
    }
    //>>includeEnd('debug');

    const height = defaultValue(options.height, 0.0);
    const extrudedHeight = defaultValue(options.extrudedHeight, height);

    this._center = Cartesian3.clone(center);
    this._semiMajorAxis = semiMajorAxis;
    this._semiMinorAxis = semiMinorAxis;
    this._ellipsoid = Ellipsoid.clone(ellipsoid);
    this._rotation = defaultValue(options.rotation, 0.0);
    this._height = Math.max(extrudedHeight, height);
    this._granularity = granularity;
    this._extrudedHeight = Math.min(extrudedHeight, height);
    this._numberOfVerticalLines = Math.max(
      defaultValue(options.numberOfVerticalLines, 16),
      0
    );
    this._offsetAttribute = options.offsetAttribute;
    this._workerName = "createEllipseOutlineGeometry";
  }

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  EllipseOutlineGeometry.packedLength =
    Cartesian3.packedLength + Ellipsoid.packedLength + 8;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {EllipseOutlineGeometry} 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
   */
  EllipseOutlineGeometry.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(value)) {
      throw new DeveloperError("value is required");
    }
    if (!defined(array)) {
      throw new DeveloperError("array is required");
    }
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    Cartesian3.pack(value._center, array, startingIndex);
    startingIndex += Cartesian3.packedLength;

    Ellipsoid.pack(value._ellipsoid, array, startingIndex);
    startingIndex += Ellipsoid.packedLength;

    array[startingIndex++] = value._semiMajorAxis;
    array[startingIndex++] = value._semiMinorAxis;
    array[startingIndex++] = value._rotation;
    array[startingIndex++] = value._height;
    array[startingIndex++] = value._granularity;
    array[startingIndex++] = value._extrudedHeight;
    array[startingIndex++] = value._numberOfVerticalLines;
    array[startingIndex] = defaultValue(value._offsetAttribute, -1);

    return array;
  };

  const scratchCenter$6 = new Cartesian3();
  const scratchEllipsoid$d = new Ellipsoid();
  const scratchOptions$j = {
    center: scratchCenter$6,
    ellipsoid: scratchEllipsoid$d,
    semiMajorAxis: undefined,
    semiMinorAxis: undefined,
    rotation: undefined,
    height: undefined,
    granularity: undefined,
    extrudedHeight: undefined,
    numberOfVerticalLines: undefined,
    offsetAttribute: undefined,
  };

  /**
   * 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 {EllipseOutlineGeometry} [result] The object into which to store the result.
   * @returns {EllipseOutlineGeometry} The modified result parameter or a new EllipseOutlineGeometry instance if one was not provided.
   */
  EllipseOutlineGeometry.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(array)) {
      throw new DeveloperError("array is required");
    }
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    const center = Cartesian3.unpack(array, startingIndex, scratchCenter$6);
    startingIndex += Cartesian3.packedLength;

    const ellipsoid = Ellipsoid.unpack(array, startingIndex, scratchEllipsoid$d);
    startingIndex += Ellipsoid.packedLength;

    const semiMajorAxis = array[startingIndex++];
    const semiMinorAxis = array[startingIndex++];
    const rotation = array[startingIndex++];
    const height = array[startingIndex++];
    const granularity = array[startingIndex++];
    const extrudedHeight = array[startingIndex++];
    const numberOfVerticalLines = array[startingIndex++];
    const offsetAttribute = array[startingIndex];

    if (!defined(result)) {
      scratchOptions$j.height = height;
      scratchOptions$j.extrudedHeight = extrudedHeight;
      scratchOptions$j.granularity = granularity;
      scratchOptions$j.rotation = rotation;
      scratchOptions$j.semiMajorAxis = semiMajorAxis;
      scratchOptions$j.semiMinorAxis = semiMinorAxis;
      scratchOptions$j.numberOfVerticalLines = numberOfVerticalLines;
      scratchOptions$j.offsetAttribute =
        offsetAttribute === -1 ? undefined : offsetAttribute;

      return new EllipseOutlineGeometry(scratchOptions$j);
    }

    result._center = Cartesian3.clone(center, result._center);
    result._ellipsoid = Ellipsoid.clone(ellipsoid, result._ellipsoid);
    result._semiMajorAxis = semiMajorAxis;
    result._semiMinorAxis = semiMinorAxis;
    result._rotation = rotation;
    result._height = height;
    result._granularity = granularity;
    result._extrudedHeight = extrudedHeight;
    result._numberOfVerticalLines = numberOfVerticalLines;
    result._offsetAttribute =
      offsetAttribute === -1 ? undefined : offsetAttribute;

    return result;
  };

  /**
   * Computes the geometric representation of an outline of an ellipse on an ellipsoid, including its vertices, indices, and a bounding sphere.
   *
   * @param {EllipseOutlineGeometry} ellipseGeometry A description of the ellipse.
   * @returns {Geometry|undefined} The computed vertices and indices.
   */
  EllipseOutlineGeometry.createGeometry = function (ellipseGeometry) {
    if (
      ellipseGeometry._semiMajorAxis <= 0.0 ||
      ellipseGeometry._semiMinorAxis <= 0.0
    ) {
      return;
    }

    const height = ellipseGeometry._height;
    const extrudedHeight = ellipseGeometry._extrudedHeight;
    const extrude = !CesiumMath.equalsEpsilon(
      height,
      extrudedHeight,
      0,
      CesiumMath.EPSILON2
    );

    ellipseGeometry._center = ellipseGeometry._ellipsoid.scaleToGeodeticSurface(
      ellipseGeometry._center,
      ellipseGeometry._center
    );
    const options = {
      center: ellipseGeometry._center,
      semiMajorAxis: ellipseGeometry._semiMajorAxis,
      semiMinorAxis: ellipseGeometry._semiMinorAxis,
      ellipsoid: ellipseGeometry._ellipsoid,
      rotation: ellipseGeometry._rotation,
      height: height,
      granularity: ellipseGeometry._granularity,
      numberOfVerticalLines: ellipseGeometry._numberOfVerticalLines,
    };
    let geometry;
    if (extrude) {
      options.extrudedHeight = extrudedHeight;
      options.offsetAttribute = ellipseGeometry._offsetAttribute;
      geometry = computeExtrudedEllipse(options);
    } else {
      geometry = computeEllipse(options);

      if (defined(ellipseGeometry._offsetAttribute)) {
        const length = geometry.attributes.position.values.length;
        const offsetValue =
          ellipseGeometry._offsetAttribute === GeometryOffsetAttribute$1.NONE
            ? 0
            : 1;
        const applyOffset = new Uint8Array(length / 3).fill(offsetValue);
        geometry.attributes.applyOffset = new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
          componentsPerAttribute: 1,
          values: applyOffset,
        });
      }
    }

    return new Geometry({
      attributes: geometry.attributes,
      indices: geometry.indices,
      primitiveType: PrimitiveType$1.LINES,
      boundingSphere: geometry.boundingSphere,
      offsetAttribute: ellipseGeometry._offsetAttribute,
    });
  };

  /**
   * A description of the outline of a circle on the ellipsoid.
   *
   * @alias CircleOutlineGeometry
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Cartesian3} options.center The circle's center point in the fixed frame.
   * @param {Number} options.radius The radius in meters.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid the circle will be on.
   * @param {Number} [options.height=0.0] The distance in meters between the circle and the ellipsoid surface.
   * @param {Number} [options.granularity=0.02] The angular distance between points on the circle in radians.
   * @param {Number} [options.extrudedHeight=0.0] The distance in meters between the circle's extruded face and the ellipsoid surface.
   * @param {Number} [options.numberOfVerticalLines=16] Number of lines to draw between the top and bottom of an extruded circle.
   *
   * @exception {DeveloperError} radius must be greater than zero.
   * @exception {DeveloperError} granularity must be greater than zero.
   *
   * @see CircleOutlineGeometry.createGeometry
   * @see Packable
   *
   * @example
   * // Create a circle.
   * const circle = new Cesium.CircleOutlineGeometry({
   *   center : Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883),
   *   radius : 100000.0
   * });
   * const geometry = Cesium.CircleOutlineGeometry.createGeometry(circle);
   */
  function CircleOutlineGeometry(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const radius = options.radius;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("radius", radius);
    //>>includeEnd('debug');

    const ellipseGeometryOptions = {
      center: options.center,
      semiMajorAxis: radius,
      semiMinorAxis: radius,
      ellipsoid: options.ellipsoid,
      height: options.height,
      extrudedHeight: options.extrudedHeight,
      granularity: options.granularity,
      numberOfVerticalLines: options.numberOfVerticalLines,
    };
    this._ellipseGeometry = new EllipseOutlineGeometry(ellipseGeometryOptions);
    this._workerName = "createCircleOutlineGeometry";
  }

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  CircleOutlineGeometry.packedLength = EllipseOutlineGeometry.packedLength;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {CircleOutlineGeometry} 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
   */
  CircleOutlineGeometry.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    //>>includeEnd('debug');
    return EllipseOutlineGeometry.pack(
      value._ellipseGeometry,
      array,
      startingIndex
    );
  };

  const scratchEllipseGeometry = new EllipseOutlineGeometry({
    center: new Cartesian3(),
    semiMajorAxis: 1.0,
    semiMinorAxis: 1.0,
  });
  const scratchOptions$i = {
    center: new Cartesian3(),
    radius: undefined,
    ellipsoid: Ellipsoid.clone(Ellipsoid.UNIT_SPHERE),
    height: undefined,
    extrudedHeight: undefined,
    granularity: undefined,
    numberOfVerticalLines: undefined,
    semiMajorAxis: undefined,
    semiMinorAxis: undefined,
  };

  /**
   * 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 {CircleOutlineGeometry} [result] The object into which to store the result.
   * @returns {CircleOutlineGeometry} The modified result parameter or a new CircleOutlineGeometry instance if one was not provided.
   */
  CircleOutlineGeometry.unpack = function (array, startingIndex, result) {
    const ellipseGeometry = EllipseOutlineGeometry.unpack(
      array,
      startingIndex,
      scratchEllipseGeometry
    );
    scratchOptions$i.center = Cartesian3.clone(
      ellipseGeometry._center,
      scratchOptions$i.center
    );
    scratchOptions$i.ellipsoid = Ellipsoid.clone(
      ellipseGeometry._ellipsoid,
      scratchOptions$i.ellipsoid
    );
    scratchOptions$i.height = ellipseGeometry._height;
    scratchOptions$i.extrudedHeight = ellipseGeometry._extrudedHeight;
    scratchOptions$i.granularity = ellipseGeometry._granularity;
    scratchOptions$i.numberOfVerticalLines = ellipseGeometry._numberOfVerticalLines;

    if (!defined(result)) {
      scratchOptions$i.radius = ellipseGeometry._semiMajorAxis;
      return new CircleOutlineGeometry(scratchOptions$i);
    }

    scratchOptions$i.semiMajorAxis = ellipseGeometry._semiMajorAxis;
    scratchOptions$i.semiMinorAxis = ellipseGeometry._semiMinorAxis;
    result._ellipseGeometry = new EllipseOutlineGeometry(scratchOptions$i);
    return result;
  };

  /**
   * Computes the geometric representation of an outline of a circle on an ellipsoid, including its vertices, indices, and a bounding sphere.
   *
   * @param {CircleOutlineGeometry} circleGeometry A description of the circle.
   * @returns {Geometry|undefined} The computed vertices and indices.
   */
  CircleOutlineGeometry.createGeometry = function (circleGeometry) {
    return EllipseOutlineGeometry.createGeometry(circleGeometry._ellipseGeometry);
  };

  /**
   * Constants used by {@link Clock#tick} to determine behavior
   * when {@link Clock#startTime} or {@link Clock#stopTime} is reached.
   *
   * @enum {Number}
   *
   * @see Clock
   * @see ClockStep
   */
  const ClockRange = {
    /**
     * {@link Clock#tick} will always advances the clock in its current direction.
     *
     * @type {Number}
     * @constant
     */
    UNBOUNDED: 0,

    /**
     * When {@link Clock#startTime} or {@link Clock#stopTime} is reached,
     * {@link Clock#tick} will not advance {@link Clock#currentTime} any further.
     *
     * @type {Number}
     * @constant
     */
    CLAMPED: 1,

    /**
     * When {@link Clock#stopTime} is reached, {@link Clock#tick} will advance
     * {@link Clock#currentTime} to the opposite end of the interval.  When
     * time is moving backwards, {@link Clock#tick} will not advance past
     * {@link Clock#startTime}
     *
     * @type {Number}
     * @constant
     */
    LOOP_STOP: 2,
  };
  var ClockRange$1 = Object.freeze(ClockRange);

  /**
   * Constants to determine how much time advances with each call
   * to {@link Clock#tick}.
   *
   * @enum {Number}
   *
   * @see Clock
   * @see ClockRange
   */
  const ClockStep = {
    /**
     * {@link Clock#tick} advances the current time by a fixed step,
     * which is the number of seconds specified by {@link Clock#multiplier}.
     *
     * @type {Number}
     * @constant
     */
    TICK_DEPENDENT: 0,

    /**
     * {@link Clock#tick} advances the current time by the amount of system
     * time elapsed since the previous call multiplied by {@link Clock#multiplier}.
     *
     * @type {Number}
     * @constant
     */
    SYSTEM_CLOCK_MULTIPLIER: 1,

    /**
     * {@link Clock#tick} sets the clock to the current system time;
     * ignoring all other settings.
     *
     * @type {Number}
     * @constant
     */
    SYSTEM_CLOCK: 2,
  };
  var ClockStep$1 = Object.freeze(ClockStep);

  /**
   * Gets a timestamp that can be used in measuring the time between events.  Timestamps
   * are expressed in milliseconds, but it is not specified what the milliseconds are
   * measured from.  This function uses performance.now() if it is available, or Date.now()
   * otherwise.
   *
   * @function getTimestamp
   *
   * @returns {Number} The timestamp in milliseconds since some unspecified reference time.
   */
  let getTimestamp;

  if (
    typeof performance !== "undefined" &&
    typeof performance.now === "function" &&
    isFinite(performance.now())
  ) {
    getTimestamp = function () {
      return performance.now();
    };
  } else {
    getTimestamp = function () {
      return Date.now();
    };
  }
  var getTimestamp$1 = getTimestamp;

  /**
   * A simple clock for keeping track of simulated time.
   *
   * @alias Clock
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {JulianDate} [options.startTime] The start time of the clock.
   * @param {JulianDate} [options.stopTime] The stop time of the clock.
   * @param {JulianDate} [options.currentTime] The current time.
   * @param {Number} [options.multiplier=1.0] Determines how much time advances when {@link Clock#tick} is called, negative values allow for advancing backwards.
   * @param {ClockStep} [options.clockStep=ClockStep.SYSTEM_CLOCK_MULTIPLIER] Determines if calls to {@link Clock#tick} are frame dependent or system clock dependent.
   * @param {ClockRange} [options.clockRange=ClockRange.UNBOUNDED] Determines how the clock should behave when {@link Clock#startTime} or {@link Clock#stopTime} is reached.
   * @param {Boolean} [options.canAnimate=true] Indicates whether {@link Clock#tick} can advance time.  This could be false if data is being buffered, for example.  The clock will only tick when both {@link Clock#canAnimate} and {@link Clock#shouldAnimate} are true.
   * @param {Boolean} [options.shouldAnimate=false] Indicates whether {@link Clock#tick} should attempt to advance time.  The clock will only tick when both {@link Clock#canAnimate} and {@link Clock#shouldAnimate} are true.
   *
   * @exception {DeveloperError} startTime must come before stopTime.
   *
   *
   * @example
   * // Create a clock that loops on Christmas day 2013 and runs in real-time.
   * const clock = new Cesium.Clock({
   *    startTime : Cesium.JulianDate.fromIso8601("2013-12-25"),
   *    currentTime : Cesium.JulianDate.fromIso8601("2013-12-25"),
   *    stopTime : Cesium.JulianDate.fromIso8601("2013-12-26"),
   *    clockRange : Cesium.ClockRange.LOOP_STOP,
   *    clockStep : Cesium.ClockStep.SYSTEM_CLOCK_MULTIPLIER
   * });
   *
   * @see ClockStep
   * @see ClockRange
   * @see JulianDate
   */
  function Clock(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    let currentTime = options.currentTime;
    let startTime = options.startTime;
    let stopTime = options.stopTime;

    if (!defined(currentTime)) {
      // if not specified, current time is the start time,
      // or if that is not specified, 1 day before the stop time,
      // or if that is not specified, then now.
      if (defined(startTime)) {
        currentTime = JulianDate.clone(startTime);
      } else if (defined(stopTime)) {
        currentTime = JulianDate.addDays(stopTime, -1.0, new JulianDate());
      } else {
        currentTime = JulianDate.now();
      }
    } else {
      currentTime = JulianDate.clone(currentTime);
    }

    if (!defined(startTime)) {
      // if not specified, start time is the current time
      // (as determined above)
      startTime = JulianDate.clone(currentTime);
    } else {
      startTime = JulianDate.clone(startTime);
    }

    if (!defined(stopTime)) {
      // if not specified, stop time is 1 day after the start time
      // (as determined above)
      stopTime = JulianDate.addDays(startTime, 1.0, new JulianDate());
    } else {
      stopTime = JulianDate.clone(stopTime);
    }

    //>>includeStart('debug', pragmas.debug);
    if (JulianDate.greaterThan(startTime, stopTime)) {
      throw new DeveloperError("startTime must come before stopTime.");
    }
    //>>includeEnd('debug');

    /**
     * The start time of the clock.
     * @type {JulianDate}
     */
    this.startTime = startTime;

    /**
     * The stop time of the clock.
     * @type {JulianDate}
     */
    this.stopTime = stopTime;

    /**
     * Determines how the clock should behave when
     * {@link Clock#startTime} or {@link Clock#stopTime}
     * is reached.
     * @type {ClockRange}
     * @default {@link ClockRange.UNBOUNDED}
     */
    this.clockRange = defaultValue(options.clockRange, ClockRange$1.UNBOUNDED);

    /**
     * Indicates whether {@link Clock#tick} can advance time.  This could be false if data is being buffered,
     * for example.  The clock will only advance time when both
     * {@link Clock#canAnimate} and {@link Clock#shouldAnimate} are true.
     * @type {Boolean}
     * @default true
     */
    this.canAnimate = defaultValue(options.canAnimate, true);

    /**
     * An {@link Event} that is fired whenever {@link Clock#tick} is called.
     * @type {Event}
     */
    this.onTick = new Event();
    /**
     * An {@link Event} that is fired whenever {@link Clock#stopTime} is reached.
     * @type {Event}
     */
    this.onStop = new Event();

    this._currentTime = undefined;
    this._multiplier = undefined;
    this._clockStep = undefined;
    this._shouldAnimate = undefined;
    this._lastSystemTime = getTimestamp$1();

    // set values using the property setters to
    // make values consistent.

    this.currentTime = currentTime;
    this.multiplier = defaultValue(options.multiplier, 1.0);
    this.shouldAnimate = defaultValue(options.shouldAnimate, false);
    this.clockStep = defaultValue(
      options.clockStep,
      ClockStep$1.SYSTEM_CLOCK_MULTIPLIER
    );
  }

  Object.defineProperties(Clock.prototype, {
    /**
     * The current time.
     * Changing this property will change
     * {@link Clock#clockStep} from {@link ClockStep.SYSTEM_CLOCK} to
     * {@link ClockStep.SYSTEM_CLOCK_MULTIPLIER}.
     * @memberof Clock.prototype
     * @type {JulianDate}
     */
    currentTime: {
      get: function () {
        return this._currentTime;
      },
      set: function (value) {
        if (JulianDate.equals(this._currentTime, value)) {
          return;
        }

        if (this._clockStep === ClockStep$1.SYSTEM_CLOCK) {
          this._clockStep = ClockStep$1.SYSTEM_CLOCK_MULTIPLIER;
        }

        this._currentTime = value;
      },
    },

    /**
     * Gets or sets how much time advances when {@link Clock#tick} is called. Negative values allow for advancing backwards.
     * If {@link Clock#clockStep} is set to {@link ClockStep.TICK_DEPENDENT}, this is the number of seconds to advance.
     * If {@link Clock#clockStep} is set to {@link ClockStep.SYSTEM_CLOCK_MULTIPLIER}, this value is multiplied by the
     * elapsed system time since the last call to {@link Clock#tick}.
     * Changing this property will change
     * {@link Clock#clockStep} from {@link ClockStep.SYSTEM_CLOCK} to
     * {@link ClockStep.SYSTEM_CLOCK_MULTIPLIER}.
     * @memberof Clock.prototype
     * @type {Number}
     * @default 1.0
     */
    multiplier: {
      get: function () {
        return this._multiplier;
      },
      set: function (value) {
        if (this._multiplier === value) {
          return;
        }

        if (this._clockStep === ClockStep$1.SYSTEM_CLOCK) {
          this._clockStep = ClockStep$1.SYSTEM_CLOCK_MULTIPLIER;
        }

        this._multiplier = value;
      },
    },

    /**
     * Determines if calls to {@link Clock#tick} are frame dependent or system clock dependent.
     * Changing this property to {@link ClockStep.SYSTEM_CLOCK} will set
     * {@link Clock#multiplier} to 1.0, {@link Clock#shouldAnimate} to true, and
     * {@link Clock#currentTime} to the current system clock time.
     * @memberof Clock.prototype
     * @type ClockStep
     * @default {@link ClockStep.SYSTEM_CLOCK_MULTIPLIER}
     */
    clockStep: {
      get: function () {
        return this._clockStep;
      },
      set: function (value) {
        if (value === ClockStep$1.SYSTEM_CLOCK) {
          this._multiplier = 1.0;
          this._shouldAnimate = true;
          this._currentTime = JulianDate.now();
        }

        this._clockStep = value;
      },
    },

    /**
     * Indicates whether {@link Clock#tick} should attempt to advance time.
     * The clock will only advance time when both
     * {@link Clock#canAnimate} and {@link Clock#shouldAnimate} are true.
     * Changing this property will change
     * {@link Clock#clockStep} from {@link ClockStep.SYSTEM_CLOCK} to
     * {@link ClockStep.SYSTEM_CLOCK_MULTIPLIER}.
     * @memberof Clock.prototype
     * @type {Boolean}
     * @default false
     */
    shouldAnimate: {
      get: function () {
        return this._shouldAnimate;
      },
      set: function (value) {
        if (this._shouldAnimate === value) {
          return;
        }

        if (this._clockStep === ClockStep$1.SYSTEM_CLOCK) {
          this._clockStep = ClockStep$1.SYSTEM_CLOCK_MULTIPLIER;
        }

        this._shouldAnimate = value;
      },
    },
  });

  /**
   * Advances the clock from the current time based on the current configuration options.
   * tick should be called every frame, regardless of whether animation is taking place
   * or not.  To control animation, use the {@link Clock#shouldAnimate} property.
   *
   * @returns {JulianDate} The new value of the {@link Clock#currentTime} property.
   */
  Clock.prototype.tick = function () {
    const currentSystemTime = getTimestamp$1();
    let currentTime = JulianDate.clone(this._currentTime);

    if (this.canAnimate && this._shouldAnimate) {
      const clockStep = this._clockStep;
      if (clockStep === ClockStep$1.SYSTEM_CLOCK) {
        currentTime = JulianDate.now(currentTime);
      } else {
        const multiplier = this._multiplier;

        if (clockStep === ClockStep$1.TICK_DEPENDENT) {
          currentTime = JulianDate.addSeconds(
            currentTime,
            multiplier,
            currentTime
          );
        } else {
          const milliseconds = currentSystemTime - this._lastSystemTime;
          currentTime = JulianDate.addSeconds(
            currentTime,
            multiplier * (milliseconds / 1000.0),
            currentTime
          );
        }

        const clockRange = this.clockRange;
        const startTime = this.startTime;
        const stopTime = this.stopTime;

        if (clockRange === ClockRange$1.CLAMPED) {
          if (JulianDate.lessThan(currentTime, startTime)) {
            currentTime = JulianDate.clone(startTime, currentTime);
          } else if (JulianDate.greaterThan(currentTime, stopTime)) {
            currentTime = JulianDate.clone(stopTime, currentTime);
            this.onStop.raiseEvent(this);
          }
        } else if (clockRange === ClockRange$1.LOOP_STOP) {
          if (JulianDate.lessThan(currentTime, startTime)) {
            currentTime = JulianDate.clone(startTime, currentTime);
          }
          while (JulianDate.greaterThan(currentTime, stopTime)) {
            currentTime = JulianDate.addSeconds(
              startTime,
              JulianDate.secondsDifference(currentTime, stopTime),
              currentTime
            );
            this.onStop.raiseEvent(this);
          }
        }
      }
    }

    this._currentTime = currentTime;
    this._lastSystemTime = currentSystemTime;
    this.onTick.raiseEvent(this);
    return currentTime;
  };

  function hue2rgb(m1, m2, h) {
    if (h < 0) {
      h += 1;
    }
    if (h > 1) {
      h -= 1;
    }
    if (h * 6 < 1) {
      return m1 + (m2 - m1) * 6 * h;
    }
    if (h * 2 < 1) {
      return m2;
    }
    if (h * 3 < 2) {
      return m1 + (m2 - m1) * (2 / 3 - h) * 6;
    }
    return m1;
  }

  /**
   * A color, specified using red, green, blue, and alpha values,
   * which range from <code>0</code> (no intensity) to <code>1.0</code> (full intensity).
   * @param {Number} [red=1.0] The red component.
   * @param {Number} [green=1.0] The green component.
   * @param {Number} [blue=1.0] The blue component.
   * @param {Number} [alpha=1.0] The alpha component.
   *
   * @constructor
   * @alias Color
   *
   * @see Packable
   */
  function Color(red, green, blue, alpha) {
    /**
     * The red component.
     * @type {Number}
     * @default 1.0
     */
    this.red = defaultValue(red, 1.0);
    /**
     * The green component.
     * @type {Number}
     * @default 1.0
     */
    this.green = defaultValue(green, 1.0);
    /**
     * The blue component.
     * @type {Number}
     * @default 1.0
     */
    this.blue = defaultValue(blue, 1.0);
    /**
     * The alpha component.
     * @type {Number}
     * @default 1.0
     */
    this.alpha = defaultValue(alpha, 1.0);
  }

  /**
   * Creates a Color instance from a {@link Cartesian4}. <code>x</code>, <code>y</code>, <code>z</code>,
   * and <code>w</code> map to <code>red</code>, <code>green</code>, <code>blue</code>, and <code>alpha</code>, respectively.
   *
   * @param {Cartesian4} cartesian The source cartesian.
   * @param {Color} [result] The object onto which to store the result.
   * @returns {Color} The modified result parameter or a new Color instance if one was not provided.
   */
  Color.fromCartesian4 = function (cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartesian", cartesian);
    //>>includeEnd('debug');

    if (!defined(result)) {
      return new Color(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
    }

    result.red = cartesian.x;
    result.green = cartesian.y;
    result.blue = cartesian.z;
    result.alpha = cartesian.w;
    return result;
  };

  /**
   * Creates a new Color specified using red, green, blue, and alpha values
   * that are in the range of 0 to 255, converting them internally to a range of 0.0 to 1.0.
   *
   * @param {Number} [red=255] The red component.
   * @param {Number} [green=255] The green component.
   * @param {Number} [blue=255] The blue component.
   * @param {Number} [alpha=255] The alpha component.
   * @param {Color} [result] The object onto which to store the result.
   * @returns {Color} The modified result parameter or a new Color instance if one was not provided.
   */
  Color.fromBytes = function (red, green, blue, alpha, result) {
    red = Color.byteToFloat(defaultValue(red, 255.0));
    green = Color.byteToFloat(defaultValue(green, 255.0));
    blue = Color.byteToFloat(defaultValue(blue, 255.0));
    alpha = Color.byteToFloat(defaultValue(alpha, 255.0));

    if (!defined(result)) {
      return new Color(red, green, blue, alpha);
    }

    result.red = red;
    result.green = green;
    result.blue = blue;
    result.alpha = alpha;
    return result;
  };

  /**
   * Creates a new Color that has the same red, green, and blue components
   * of the specified color, but with the specified alpha value.
   *
   * @param {Color} color The base color
   * @param {Number} alpha The new alpha component.
   * @param {Color} [result] The object onto which to store the result.
   * @returns {Color} The modified result parameter or a new Color instance if one was not provided.
   *
   * @example const translucentRed = Cesium.Color.fromAlpha(Cesium.Color.RED, 0.9);
   */
  Color.fromAlpha = function (color, alpha, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("color", color);
    Check.typeOf.number("alpha", alpha);
    //>>includeEnd('debug');

    if (!defined(result)) {
      return new Color(color.red, color.green, color.blue, alpha);
    }

    result.red = color.red;
    result.green = color.green;
    result.blue = color.blue;
    result.alpha = alpha;
    return result;
  };

  let scratchArrayBuffer;
  let scratchUint32Array;
  let scratchUint8Array;
  if (FeatureDetection.supportsTypedArrays()) {
    scratchArrayBuffer = new ArrayBuffer(4);
    scratchUint32Array = new Uint32Array(scratchArrayBuffer);
    scratchUint8Array = new Uint8Array(scratchArrayBuffer);
  }

  /**
   * Creates a new Color from a single numeric unsigned 32-bit RGBA value, using the endianness
   * of the system.
   *
   * @param {Number} rgba A single numeric unsigned 32-bit RGBA value.
   * @param {Color} [result] The object to store the result in, if undefined a new instance will be created.
   * @returns {Color} The color object.
   *
   * @example
   * const color = Cesium.Color.fromRgba(0x67ADDFFF);
   *
   * @see Color#toRgba
   */
  Color.fromRgba = function (rgba, result) {
    // scratchUint32Array and scratchUint8Array share an underlying array buffer
    scratchUint32Array[0] = rgba;
    return Color.fromBytes(
      scratchUint8Array[0],
      scratchUint8Array[1],
      scratchUint8Array[2],
      scratchUint8Array[3],
      result
    );
  };

  /**
   * Creates a Color instance from hue, saturation, and lightness.
   *
   * @param {Number} [hue=0] The hue angle 0...1
   * @param {Number} [saturation=0] The saturation value 0...1
   * @param {Number} [lightness=0] The lightness value 0...1
   * @param {Number} [alpha=1.0] The alpha component 0...1
   * @param {Color} [result] The object to store the result in, if undefined a new instance will be created.
   * @returns {Color} The color object.
   *
   * @see {@link http://www.w3.org/TR/css3-color/#hsl-color|CSS color values}
   */
  Color.fromHsl = function (hue, saturation, lightness, alpha, result) {
    hue = defaultValue(hue, 0.0) % 1.0;
    saturation = defaultValue(saturation, 0.0);
    lightness = defaultValue(lightness, 0.0);
    alpha = defaultValue(alpha, 1.0);

    let red = lightness;
    let green = lightness;
    let blue = lightness;

    if (saturation !== 0) {
      let m2;
      if (lightness < 0.5) {
        m2 = lightness * (1 + saturation);
      } else {
        m2 = lightness + saturation - lightness * saturation;
      }

      const m1 = 2.0 * lightness - m2;
      red = hue2rgb(m1, m2, hue + 1 / 3);
      green = hue2rgb(m1, m2, hue);
      blue = hue2rgb(m1, m2, hue - 1 / 3);
    }

    if (!defined(result)) {
      return new Color(red, green, blue, alpha);
    }

    result.red = red;
    result.green = green;
    result.blue = blue;
    result.alpha = alpha;
    return result;
  };

  /**
   * Creates a random color using the provided options. For reproducible random colors, you should
   * call {@link CesiumMath#setRandomNumberSeed} once at the beginning of your application.
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Number} [options.red] If specified, the red component to use instead of a randomized value.
   * @param {Number} [options.minimumRed=0.0] The maximum red value to generate if none was specified.
   * @param {Number} [options.maximumRed=1.0] The minimum red value to generate if none was specified.
   * @param {Number} [options.green] If specified, the green component to use instead of a randomized value.
   * @param {Number} [options.minimumGreen=0.0] The maximum green value to generate if none was specified.
   * @param {Number} [options.maximumGreen=1.0] The minimum green value to generate if none was specified.
   * @param {Number} [options.blue] If specified, the blue component to use instead of a randomized value.
   * @param {Number} [options.minimumBlue=0.0] The maximum blue value to generate if none was specified.
   * @param {Number} [options.maximumBlue=1.0] The minimum blue value to generate if none was specified.
   * @param {Number} [options.alpha] If specified, the alpha component to use instead of a randomized value.
   * @param {Number} [options.minimumAlpha=0.0] The maximum alpha value to generate if none was specified.
   * @param {Number} [options.maximumAlpha=1.0] The minimum alpha value to generate if none was specified.
   * @param {Color} [result] The object to store the result in, if undefined a new instance will be created.
   * @returns {Color} The modified result parameter or a new instance if result was undefined.
   *
   * @exception {DeveloperError} minimumRed must be less than or equal to maximumRed.
   * @exception {DeveloperError} minimumGreen must be less than or equal to maximumGreen.
   * @exception {DeveloperError} minimumBlue must be less than or equal to maximumBlue.
   * @exception {DeveloperError} minimumAlpha must be less than or equal to maximumAlpha.
   *
   * @example
   * //Create a completely random color
   * const color = Cesium.Color.fromRandom();
   *
   * //Create a random shade of yellow.
   * const color1 = Cesium.Color.fromRandom({
   *     red : 1.0,
   *     green : 1.0,
   *     alpha : 1.0
   * });
   *
   * //Create a random bright color.
   * const color2 = Cesium.Color.fromRandom({
   *     minimumRed : 0.75,
   *     minimumGreen : 0.75,
   *     minimumBlue : 0.75,
   *     alpha : 1.0
   * });
   */
  Color.fromRandom = function (options, result) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    let red = options.red;
    if (!defined(red)) {
      const minimumRed = defaultValue(options.minimumRed, 0);
      const maximumRed = defaultValue(options.maximumRed, 1.0);

      //>>includeStart('debug', pragmas.debug);
      Check.typeOf.number.lessThanOrEquals("minimumRed", minimumRed, maximumRed);
      //>>includeEnd('debug');

      red =
        minimumRed + CesiumMath.nextRandomNumber() * (maximumRed - minimumRed);
    }

    let green = options.green;
    if (!defined(green)) {
      const minimumGreen = defaultValue(options.minimumGreen, 0);
      const maximumGreen = defaultValue(options.maximumGreen, 1.0);

      //>>includeStart('debug', pragmas.debug);
      Check.typeOf.number.lessThanOrEquals(
        "minimumGreen",
        minimumGreen,
        maximumGreen
      );
      //>>includeEnd('debug');
      green =
        minimumGreen +
        CesiumMath.nextRandomNumber() * (maximumGreen - minimumGreen);
    }

    let blue = options.blue;
    if (!defined(blue)) {
      const minimumBlue = defaultValue(options.minimumBlue, 0);
      const maximumBlue = defaultValue(options.maximumBlue, 1.0);

      //>>includeStart('debug', pragmas.debug);
      Check.typeOf.number.lessThanOrEquals(
        "minimumBlue",
        minimumBlue,
        maximumBlue
      );
      //>>includeEnd('debug');

      blue =
        minimumBlue + CesiumMath.nextRandomNumber() * (maximumBlue - minimumBlue);
    }

    let alpha = options.alpha;
    if (!defined(alpha)) {
      const minimumAlpha = defaultValue(options.minimumAlpha, 0);
      const maximumAlpha = defaultValue(options.maximumAlpha, 1.0);

      //>>includeStart('debug', pragmas.debug);
      Check.typeOf.number.lessThanOrEquals(
        "minumumAlpha",
        minimumAlpha,
        maximumAlpha
      );
      //>>includeEnd('debug');

      alpha =
        minimumAlpha +
        CesiumMath.nextRandomNumber() * (maximumAlpha - minimumAlpha);
    }

    if (!defined(result)) {
      return new Color(red, green, blue, alpha);
    }

    result.red = red;
    result.green = green;
    result.blue = blue;
    result.alpha = alpha;
    return result;
  };

  //#rgba
  const rgbaMatcher = /^#([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])?$/i;
  //#rrggbbaa
  const rrggbbaaMatcher = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?$/i;
  //rgb(), rgba(), or rgb%()
  const rgbParenthesesMatcher = /^rgba?\(\s*([0-9.]+%?)\s*,\s*([0-9.]+%?)\s*,\s*([0-9.]+%?)(?:\s*,\s*([0-9.]+))?\s*\)$/i;
  //hsl() or hsla()
  const hslParenthesesMatcher = /^hsla?\(\s*([0-9.]+)\s*,\s*([0-9.]+%)\s*,\s*([0-9.]+%)(?:\s*,\s*([0-9.]+))?\s*\)$/i;

  /**
   * Creates a Color instance from a CSS color value.
   *
   * @param {String} color The CSS color value in #rgb, #rgba, #rrggbb, #rrggbbaa, rgb(), rgba(), hsl(), or hsla() format.
   * @param {Color} [result] The object to store the result in, if undefined a new instance will be created.
   * @returns {Color} The color object, or undefined if the string was not a valid CSS color.
   *
   *
   * @example
   * const cesiumBlue = Cesium.Color.fromCssColorString('#67ADDF');
   * const green = Cesium.Color.fromCssColorString('green');
   *
   * @see {@link http://www.w3.org/TR/css3-color|CSS color values}
   */
  Color.fromCssColorString = function (color, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("color", color);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Color();
    }

    // Remove all whitespaces from the color string
    color = color.replace(/\s/g, "");

    const namedColor = Color[color.toUpperCase()];
    if (defined(namedColor)) {
      Color.clone(namedColor, result);
      return result;
    }

    let matches = rgbaMatcher.exec(color);
    if (matches !== null) {
      result.red = parseInt(matches[1], 16) / 15;
      result.green = parseInt(matches[2], 16) / 15.0;
      result.blue = parseInt(matches[3], 16) / 15.0;
      result.alpha = parseInt(defaultValue(matches[4], "f"), 16) / 15.0;
      return result;
    }

    matches = rrggbbaaMatcher.exec(color);
    if (matches !== null) {
      result.red = parseInt(matches[1], 16) / 255.0;
      result.green = parseInt(matches[2], 16) / 255.0;
      result.blue = parseInt(matches[3], 16) / 255.0;
      result.alpha = parseInt(defaultValue(matches[4], "ff"), 16) / 255.0;
      return result;
    }

    matches = rgbParenthesesMatcher.exec(color);
    if (matches !== null) {
      result.red =
        parseFloat(matches[1]) / ("%" === matches[1].substr(-1) ? 100.0 : 255.0);
      result.green =
        parseFloat(matches[2]) / ("%" === matches[2].substr(-1) ? 100.0 : 255.0);
      result.blue =
        parseFloat(matches[3]) / ("%" === matches[3].substr(-1) ? 100.0 : 255.0);
      result.alpha = parseFloat(defaultValue(matches[4], "1.0"));
      return result;
    }

    matches = hslParenthesesMatcher.exec(color);
    if (matches !== null) {
      return Color.fromHsl(
        parseFloat(matches[1]) / 360.0,
        parseFloat(matches[2]) / 100.0,
        parseFloat(matches[3]) / 100.0,
        parseFloat(defaultValue(matches[4], "1.0")),
        result
      );
    }

    result = undefined;
    return result;
  };

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  Color.packedLength = 4;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {Color} 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
   */
  Color.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);
    array[startingIndex++] = value.red;
    array[startingIndex++] = value.green;
    array[startingIndex++] = value.blue;
    array[startingIndex] = value.alpha;

    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 {Color} [result] The object into which to store the result.
   * @returns {Color} The modified result parameter or a new Color instance if one was not provided.
   */
  Color.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);
    if (!defined(result)) {
      result = new Color();
    }
    result.red = array[startingIndex++];
    result.green = array[startingIndex++];
    result.blue = array[startingIndex++];
    result.alpha = array[startingIndex];
    return result;
  };

  /**
   * Converts a 'byte' color component in the range of 0 to 255 into
   * a 'float' color component in the range of 0 to 1.0.
   *
   * @param {Number} number The number to be converted.
   * @returns {Number} The converted number.
   */
  Color.byteToFloat = function (number) {
    return number / 255.0;
  };

  /**
   * Converts a 'float' color component in the range of 0 to 1.0 into
   * a 'byte' color component in the range of 0 to 255.
   *
   * @param {Number} number The number to be converted.
   * @returns {Number} The converted number.
   */
  Color.floatToByte = function (number) {
    return number === 1.0 ? 255.0 : (number * 256.0) | 0;
  };

  /**
   * Duplicates a Color.
   *
   * @param {Color} color The Color to duplicate.
   * @param {Color} [result] The object to store the result in, if undefined a new instance will be created.
   * @returns {Color} The modified result parameter or a new instance if result was undefined. (Returns undefined if color is undefined)
   */
  Color.clone = function (color, result) {
    if (!defined(color)) {
      return undefined;
    }
    if (!defined(result)) {
      return new Color(color.red, color.green, color.blue, color.alpha);
    }
    result.red = color.red;
    result.green = color.green;
    result.blue = color.blue;
    result.alpha = color.alpha;
    return result;
  };

  /**
   * Returns true if the first Color equals the second color.
   *
   * @param {Color} left The first Color to compare for equality.
   * @param {Color} right The second Color to compare for equality.
   * @returns {Boolean} <code>true</code> if the Colors are equal; otherwise, <code>false</code>.
   */
  Color.equals = function (left, right) {
    return (
      left === right || //
      (defined(left) && //
        defined(right) && //
        left.red === right.red && //
        left.green === right.green && //
        left.blue === right.blue && //
        left.alpha === right.alpha)
    );
  };

  /**
   * @private
   */
  Color.equalsArray = function (color, array, offset) {
    return (
      color.red === array[offset] &&
      color.green === array[offset + 1] &&
      color.blue === array[offset + 2] &&
      color.alpha === array[offset + 3]
    );
  };

  /**
   * Returns a duplicate of a Color instance.
   *
   * @param {Color} [result] The object to store the result in, if undefined a new instance will be created.
   * @returns {Color} The modified result parameter or a new instance if result was undefined.
   */
  Color.prototype.clone = function (result) {
    return Color.clone(this, result);
  };

  /**
   * Returns true if this Color equals other.
   *
   * @param {Color} other The Color to compare for equality.
   * @returns {Boolean} <code>true</code> if the Colors are equal; otherwise, <code>false</code>.
   */
  Color.prototype.equals = function (other) {
    return Color.equals(this, other);
  };

  /**
   * Returns <code>true</code> if this Color equals other componentwise within the specified epsilon.
   *
   * @param {Color} other The Color to compare for equality.
   * @param {Number} [epsilon=0.0] The epsilon to use for equality testing.
   * @returns {Boolean} <code>true</code> if the Colors are equal within the specified epsilon; otherwise, <code>false</code>.
   */
  Color.prototype.equalsEpsilon = function (other, epsilon) {
    return (
      this === other || //
      (defined(other) && //
        Math.abs(this.red - other.red) <= epsilon && //
        Math.abs(this.green - other.green) <= epsilon && //
        Math.abs(this.blue - other.blue) <= epsilon && //
        Math.abs(this.alpha - other.alpha) <= epsilon)
    );
  };

  /**
   * Creates a string representing this Color in the format '(red, green, blue, alpha)'.
   *
   * @returns {String} A string representing this Color in the format '(red, green, blue, alpha)'.
   */
  Color.prototype.toString = function () {
    return `(${this.red}, ${this.green}, ${this.blue}, ${this.alpha})`;
  };

  /**
   * Creates a string containing the CSS color value for this color.
   *
   * @returns {String} The CSS equivalent of this color.
   *
   * @see {@link http://www.w3.org/TR/css3-color/#rgba-color|CSS RGB or RGBA color values}
   */
  Color.prototype.toCssColorString = function () {
    const red = Color.floatToByte(this.red);
    const green = Color.floatToByte(this.green);
    const blue = Color.floatToByte(this.blue);
    if (this.alpha === 1) {
      return `rgb(${red},${green},${blue})`;
    }
    return `rgba(${red},${green},${blue},${this.alpha})`;
  };

  /**
   * Creates a string containing CSS hex string color value for this color.
   *
   * @returns {String} The CSS hex string equivalent of this color.
   */
  Color.prototype.toCssHexString = function () {
    let r = Color.floatToByte(this.red).toString(16);
    if (r.length < 2) {
      r = `0${r}`;
    }
    let g = Color.floatToByte(this.green).toString(16);
    if (g.length < 2) {
      g = `0${g}`;
    }
    let b = Color.floatToByte(this.blue).toString(16);
    if (b.length < 2) {
      b = `0${b}`;
    }
    if (this.alpha < 1) {
      let hexAlpha = Color.floatToByte(this.alpha).toString(16);
      if (hexAlpha.length < 2) {
        hexAlpha = `0${hexAlpha}`;
      }
      return `#${r}${g}${b}${hexAlpha}`;
    }
    return `#${r}${g}${b}`;
  };

  /**
   * Converts this color to an array of red, green, blue, and alpha values
   * that are in the range of 0 to 255.
   *
   * @param {Number[]} [result] The array to store the result in, if undefined a new instance will be created.
   * @returns {Number[]} The modified result parameter or a new instance if result was undefined.
   */
  Color.prototype.toBytes = function (result) {
    const red = Color.floatToByte(this.red);
    const green = Color.floatToByte(this.green);
    const blue = Color.floatToByte(this.blue);
    const alpha = Color.floatToByte(this.alpha);

    if (!defined(result)) {
      return [red, green, blue, alpha];
    }
    result[0] = red;
    result[1] = green;
    result[2] = blue;
    result[3] = alpha;
    return result;
  };

  /**
   * Converts this color to a single numeric unsigned 32-bit RGBA value, using the endianness
   * of the system.
   *
   * @returns {Number} A single numeric unsigned 32-bit RGBA value.
   *
   *
   * @example
   * const rgba = Cesium.Color.BLUE.toRgba();
   *
   * @see Color.fromRgba
   */
  Color.prototype.toRgba = function () {
    // scratchUint32Array and scratchUint8Array share an underlying array buffer
    scratchUint8Array[0] = Color.floatToByte(this.red);
    scratchUint8Array[1] = Color.floatToByte(this.green);
    scratchUint8Array[2] = Color.floatToByte(this.blue);
    scratchUint8Array[3] = Color.floatToByte(this.alpha);
    return scratchUint32Array[0];
  };

  /**
   * Brightens this color by the provided magnitude.
   *
   * @param {Number} magnitude A positive number indicating the amount to brighten.
   * @param {Color} result The object onto which to store the result.
   * @returns {Color} The modified result parameter.
   *
   * @example
   * const brightBlue = Cesium.Color.BLUE.brighten(0.5, new Cesium.Color());
   */
  Color.prototype.brighten = function (magnitude, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("magnitude", magnitude);
    Check.typeOf.number.greaterThanOrEquals("magnitude", magnitude, 0.0);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    magnitude = 1.0 - magnitude;
    result.red = 1.0 - (1.0 - this.red) * magnitude;
    result.green = 1.0 - (1.0 - this.green) * magnitude;
    result.blue = 1.0 - (1.0 - this.blue) * magnitude;
    result.alpha = this.alpha;
    return result;
  };

  /**
   * Darkens this color by the provided magnitude.
   *
   * @param {Number} magnitude A positive number indicating the amount to darken.
   * @param {Color} result The object onto which to store the result.
   * @returns {Color} The modified result parameter.
   *
   * @example
   * const darkBlue = Cesium.Color.BLUE.darken(0.5, new Cesium.Color());
   */
  Color.prototype.darken = function (magnitude, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("magnitude", magnitude);
    Check.typeOf.number.greaterThanOrEquals("magnitude", magnitude, 0.0);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    magnitude = 1.0 - magnitude;
    result.red = this.red * magnitude;
    result.green = this.green * magnitude;
    result.blue = this.blue * magnitude;
    result.alpha = this.alpha;
    return result;
  };

  /**
   * Creates a new Color that has the same red, green, and blue components
   * as this Color, but with the specified alpha value.
   *
   * @param {Number} alpha The new alpha component.
   * @param {Color} [result] The object onto which to store the result.
   * @returns {Color} The modified result parameter or a new Color instance if one was not provided.
   *
   * @example const translucentRed = Cesium.Color.RED.withAlpha(0.9);
   */
  Color.prototype.withAlpha = function (alpha, result) {
    return Color.fromAlpha(this, alpha, result);
  };

  /**
   * Computes the componentwise sum of two Colors.
   *
   * @param {Color} left The first Color.
   * @param {Color} right The second Color.
   * @param {Color} result The object onto which to store the result.
   * @returns {Color} The modified result parameter.
   */
  Color.add = function (left, right, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.red = left.red + right.red;
    result.green = left.green + right.green;
    result.blue = left.blue + right.blue;
    result.alpha = left.alpha + right.alpha;
    return result;
  };

  /**
   * Computes the componentwise difference of two Colors.
   *
   * @param {Color} left The first Color.
   * @param {Color} right The second Color.
   * @param {Color} result The object onto which to store the result.
   * @returns {Color} The modified result parameter.
   */
  Color.subtract = function (left, right, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.red = left.red - right.red;
    result.green = left.green - right.green;
    result.blue = left.blue - right.blue;
    result.alpha = left.alpha - right.alpha;
    return result;
  };

  /**
   * Computes the componentwise product of two Colors.
   *
   * @param {Color} left The first Color.
   * @param {Color} right The second Color.
   * @param {Color} result The object onto which to store the result.
   * @returns {Color} The modified result parameter.
   */
  Color.multiply = function (left, right, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.red = left.red * right.red;
    result.green = left.green * right.green;
    result.blue = left.blue * right.blue;
    result.alpha = left.alpha * right.alpha;
    return result;
  };

  /**
   * Computes the componentwise quotient of two Colors.
   *
   * @param {Color} left The first Color.
   * @param {Color} right The second Color.
   * @param {Color} result The object onto which to store the result.
   * @returns {Color} The modified result parameter.
   */
  Color.divide = function (left, right, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.red = left.red / right.red;
    result.green = left.green / right.green;
    result.blue = left.blue / right.blue;
    result.alpha = left.alpha / right.alpha;
    return result;
  };

  /**
   * Computes the componentwise modulus of two Colors.
   *
   * @param {Color} left The first Color.
   * @param {Color} right The second Color.
   * @param {Color} result The object onto which to store the result.
   * @returns {Color} The modified result parameter.
   */
  Color.mod = function (left, right, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.red = left.red % right.red;
    result.green = left.green % right.green;
    result.blue = left.blue % right.blue;
    result.alpha = left.alpha % right.alpha;
    return result;
  };

  /**
   * Computes the linear interpolation or extrapolation at t between the provided colors.
   *
   * @param {Color} start The color corresponding to t at 0.0.
   * @param {Color} end The color corresponding to t at 1.0.
   * @param {Number} t The point along t at which to interpolate.
   * @param {Color} result The object onto which to store the result.
   * @returns {Color} The modified result parameter.
   */
  Color.lerp = function (start, end, t, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("start", start);
    Check.typeOf.object("end", end);
    Check.typeOf.number("t", t);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.red = CesiumMath.lerp(start.red, end.red, t);
    result.green = CesiumMath.lerp(start.green, end.green, t);
    result.blue = CesiumMath.lerp(start.blue, end.blue, t);
    result.alpha = CesiumMath.lerp(start.alpha, end.alpha, t);
    return result;
  };

  /**
   * Multiplies the provided Color componentwise by the provided scalar.
   *
   * @param {Color} color The Color to be scaled.
   * @param {Number} scalar The scalar to multiply with.
   * @param {Color} result The object onto which to store the result.
   * @returns {Color} The modified result parameter.
   */
  Color.multiplyByScalar = function (color, scalar, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("color", color);
    Check.typeOf.number("scalar", scalar);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.red = color.red * scalar;
    result.green = color.green * scalar;
    result.blue = color.blue * scalar;
    result.alpha = color.alpha * scalar;
    return result;
  };

  /**
   * Divides the provided Color componentwise by the provided scalar.
   *
   * @param {Color} color The Color to be divided.
   * @param {Number} scalar The scalar to divide with.
   * @param {Color} result The object onto which to store the result.
   * @returns {Color} The modified result parameter.
   */
  Color.divideByScalar = function (color, scalar, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("color", color);
    Check.typeOf.number("scalar", scalar);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    result.red = color.red / scalar;
    result.green = color.green / scalar;
    result.blue = color.blue / scalar;
    result.alpha = color.alpha / scalar;
    return result;
  };

  /**
   * An immutable Color instance initialized to CSS color #F0F8FF
   * <span class="colorSwath" style="background: #F0F8FF;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.ALICEBLUE = Object.freeze(Color.fromCssColorString("#F0F8FF"));

  /**
   * An immutable Color instance initialized to CSS color #FAEBD7
   * <span class="colorSwath" style="background: #FAEBD7;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.ANTIQUEWHITE = Object.freeze(Color.fromCssColorString("#FAEBD7"));

  /**
   * An immutable Color instance initialized to CSS color #00FFFF
   * <span class="colorSwath" style="background: #00FFFF;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.AQUA = Object.freeze(Color.fromCssColorString("#00FFFF"));

  /**
   * An immutable Color instance initialized to CSS color #7FFFD4
   * <span class="colorSwath" style="background: #7FFFD4;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.AQUAMARINE = Object.freeze(Color.fromCssColorString("#7FFFD4"));

  /**
   * An immutable Color instance initialized to CSS color #F0FFFF
   * <span class="colorSwath" style="background: #F0FFFF;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.AZURE = Object.freeze(Color.fromCssColorString("#F0FFFF"));

  /**
   * An immutable Color instance initialized to CSS color #F5F5DC
   * <span class="colorSwath" style="background: #F5F5DC;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.BEIGE = Object.freeze(Color.fromCssColorString("#F5F5DC"));

  /**
   * An immutable Color instance initialized to CSS color #FFE4C4
   * <span class="colorSwath" style="background: #FFE4C4;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.BISQUE = Object.freeze(Color.fromCssColorString("#FFE4C4"));

  /**
   * An immutable Color instance initialized to CSS color #000000
   * <span class="colorSwath" style="background: #000000;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.BLACK = Object.freeze(Color.fromCssColorString("#000000"));

  /**
   * An immutable Color instance initialized to CSS color #FFEBCD
   * <span class="colorSwath" style="background: #FFEBCD;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.BLANCHEDALMOND = Object.freeze(Color.fromCssColorString("#FFEBCD"));

  /**
   * An immutable Color instance initialized to CSS color #0000FF
   * <span class="colorSwath" style="background: #0000FF;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.BLUE = Object.freeze(Color.fromCssColorString("#0000FF"));

  /**
   * An immutable Color instance initialized to CSS color #8A2BE2
   * <span class="colorSwath" style="background: #8A2BE2;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.BLUEVIOLET = Object.freeze(Color.fromCssColorString("#8A2BE2"));

  /**
   * An immutable Color instance initialized to CSS color #A52A2A
   * <span class="colorSwath" style="background: #A52A2A;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.BROWN = Object.freeze(Color.fromCssColorString("#A52A2A"));

  /**
   * An immutable Color instance initialized to CSS color #DEB887
   * <span class="colorSwath" style="background: #DEB887;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.BURLYWOOD = Object.freeze(Color.fromCssColorString("#DEB887"));

  /**
   * An immutable Color instance initialized to CSS color #5F9EA0
   * <span class="colorSwath" style="background: #5F9EA0;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.CADETBLUE = Object.freeze(Color.fromCssColorString("#5F9EA0"));
  /**
   * An immutable Color instance initialized to CSS color #7FFF00
   * <span class="colorSwath" style="background: #7FFF00;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.CHARTREUSE = Object.freeze(Color.fromCssColorString("#7FFF00"));

  /**
   * An immutable Color instance initialized to CSS color #D2691E
   * <span class="colorSwath" style="background: #D2691E;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.CHOCOLATE = Object.freeze(Color.fromCssColorString("#D2691E"));

  /**
   * An immutable Color instance initialized to CSS color #FF7F50
   * <span class="colorSwath" style="background: #FF7F50;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.CORAL = Object.freeze(Color.fromCssColorString("#FF7F50"));

  /**
   * An immutable Color instance initialized to CSS color #6495ED
   * <span class="colorSwath" style="background: #6495ED;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.CORNFLOWERBLUE = Object.freeze(Color.fromCssColorString("#6495ED"));

  /**
   * An immutable Color instance initialized to CSS color #FFF8DC
   * <span class="colorSwath" style="background: #FFF8DC;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.CORNSILK = Object.freeze(Color.fromCssColorString("#FFF8DC"));

  /**
   * An immutable Color instance initialized to CSS color #DC143C
   * <span class="colorSwath" style="background: #DC143C;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.CRIMSON = Object.freeze(Color.fromCssColorString("#DC143C"));

  /**
   * An immutable Color instance initialized to CSS color #00FFFF
   * <span class="colorSwath" style="background: #00FFFF;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.CYAN = Object.freeze(Color.fromCssColorString("#00FFFF"));

  /**
   * An immutable Color instance initialized to CSS color #00008B
   * <span class="colorSwath" style="background: #00008B;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.DARKBLUE = Object.freeze(Color.fromCssColorString("#00008B"));

  /**
   * An immutable Color instance initialized to CSS color #008B8B
   * <span class="colorSwath" style="background: #008B8B;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.DARKCYAN = Object.freeze(Color.fromCssColorString("#008B8B"));

  /**
   * An immutable Color instance initialized to CSS color #B8860B
   * <span class="colorSwath" style="background: #B8860B;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.DARKGOLDENROD = Object.freeze(Color.fromCssColorString("#B8860B"));

  /**
   * An immutable Color instance initialized to CSS color #A9A9A9
   * <span class="colorSwath" style="background: #A9A9A9;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.DARKGRAY = Object.freeze(Color.fromCssColorString("#A9A9A9"));

  /**
   * An immutable Color instance initialized to CSS color #006400
   * <span class="colorSwath" style="background: #006400;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.DARKGREEN = Object.freeze(Color.fromCssColorString("#006400"));

  /**
   * An immutable Color instance initialized to CSS color #A9A9A9
   * <span class="colorSwath" style="background: #A9A9A9;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.DARKGREY = Color.DARKGRAY;

  /**
   * An immutable Color instance initialized to CSS color #BDB76B
   * <span class="colorSwath" style="background: #BDB76B;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.DARKKHAKI = Object.freeze(Color.fromCssColorString("#BDB76B"));

  /**
   * An immutable Color instance initialized to CSS color #8B008B
   * <span class="colorSwath" style="background: #8B008B;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.DARKMAGENTA = Object.freeze(Color.fromCssColorString("#8B008B"));

  /**
   * An immutable Color instance initialized to CSS color #556B2F
   * <span class="colorSwath" style="background: #556B2F;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.DARKOLIVEGREEN = Object.freeze(Color.fromCssColorString("#556B2F"));

  /**
   * An immutable Color instance initialized to CSS color #FF8C00
   * <span class="colorSwath" style="background: #FF8C00;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.DARKORANGE = Object.freeze(Color.fromCssColorString("#FF8C00"));

  /**
   * An immutable Color instance initialized to CSS color #9932CC
   * <span class="colorSwath" style="background: #9932CC;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.DARKORCHID = Object.freeze(Color.fromCssColorString("#9932CC"));

  /**
   * An immutable Color instance initialized to CSS color #8B0000
   * <span class="colorSwath" style="background: #8B0000;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.DARKRED = Object.freeze(Color.fromCssColorString("#8B0000"));

  /**
   * An immutable Color instance initialized to CSS color #E9967A
   * <span class="colorSwath" style="background: #E9967A;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.DARKSALMON = Object.freeze(Color.fromCssColorString("#E9967A"));

  /**
   * An immutable Color instance initialized to CSS color #8FBC8F
   * <span class="colorSwath" style="background: #8FBC8F;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.DARKSEAGREEN = Object.freeze(Color.fromCssColorString("#8FBC8F"));

  /**
   * An immutable Color instance initialized to CSS color #483D8B
   * <span class="colorSwath" style="background: #483D8B;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.DARKSLATEBLUE = Object.freeze(Color.fromCssColorString("#483D8B"));

  /**
   * An immutable Color instance initialized to CSS color #2F4F4F
   * <span class="colorSwath" style="background: #2F4F4F;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.DARKSLATEGRAY = Object.freeze(Color.fromCssColorString("#2F4F4F"));

  /**
   * An immutable Color instance initialized to CSS color #2F4F4F
   * <span class="colorSwath" style="background: #2F4F4F;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.DARKSLATEGREY = Color.DARKSLATEGRAY;

  /**
   * An immutable Color instance initialized to CSS color #00CED1
   * <span class="colorSwath" style="background: #00CED1;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.DARKTURQUOISE = Object.freeze(Color.fromCssColorString("#00CED1"));

  /**
   * An immutable Color instance initialized to CSS color #9400D3
   * <span class="colorSwath" style="background: #9400D3;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.DARKVIOLET = Object.freeze(Color.fromCssColorString("#9400D3"));

  /**
   * An immutable Color instance initialized to CSS color #FF1493
   * <span class="colorSwath" style="background: #FF1493;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.DEEPPINK = Object.freeze(Color.fromCssColorString("#FF1493"));

  /**
   * An immutable Color instance initialized to CSS color #00BFFF
   * <span class="colorSwath" style="background: #00BFFF;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.DEEPSKYBLUE = Object.freeze(Color.fromCssColorString("#00BFFF"));

  /**
   * An immutable Color instance initialized to CSS color #696969
   * <span class="colorSwath" style="background: #696969;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.DIMGRAY = Object.freeze(Color.fromCssColorString("#696969"));

  /**
   * An immutable Color instance initialized to CSS color #696969
   * <span class="colorSwath" style="background: #696969;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.DIMGREY = Color.DIMGRAY;

  /**
   * An immutable Color instance initialized to CSS color #1E90FF
   * <span class="colorSwath" style="background: #1E90FF;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.DODGERBLUE = Object.freeze(Color.fromCssColorString("#1E90FF"));

  /**
   * An immutable Color instance initialized to CSS color #B22222
   * <span class="colorSwath" style="background: #B22222;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.FIREBRICK = Object.freeze(Color.fromCssColorString("#B22222"));

  /**
   * An immutable Color instance initialized to CSS color #FFFAF0
   * <span class="colorSwath" style="background: #FFFAF0;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.FLORALWHITE = Object.freeze(Color.fromCssColorString("#FFFAF0"));

  /**
   * An immutable Color instance initialized to CSS color #228B22
   * <span class="colorSwath" style="background: #228B22;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.FORESTGREEN = Object.freeze(Color.fromCssColorString("#228B22"));

  /**
   * An immutable Color instance initialized to CSS color #FF00FF
   * <span class="colorSwath" style="background: #FF00FF;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.FUCHSIA = Object.freeze(Color.fromCssColorString("#FF00FF"));

  /**
   * An immutable Color instance initialized to CSS color #DCDCDC
   * <span class="colorSwath" style="background: #DCDCDC;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.GAINSBORO = Object.freeze(Color.fromCssColorString("#DCDCDC"));

  /**
   * An immutable Color instance initialized to CSS color #F8F8FF
   * <span class="colorSwath" style="background: #F8F8FF;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.GHOSTWHITE = Object.freeze(Color.fromCssColorString("#F8F8FF"));

  /**
   * An immutable Color instance initialized to CSS color #FFD700
   * <span class="colorSwath" style="background: #FFD700;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.GOLD = Object.freeze(Color.fromCssColorString("#FFD700"));

  /**
   * An immutable Color instance initialized to CSS color #DAA520
   * <span class="colorSwath" style="background: #DAA520;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.GOLDENROD = Object.freeze(Color.fromCssColorString("#DAA520"));

  /**
   * An immutable Color instance initialized to CSS color #808080
   * <span class="colorSwath" style="background: #808080;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.GRAY = Object.freeze(Color.fromCssColorString("#808080"));

  /**
   * An immutable Color instance initialized to CSS color #008000
   * <span class="colorSwath" style="background: #008000;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.GREEN = Object.freeze(Color.fromCssColorString("#008000"));

  /**
   * An immutable Color instance initialized to CSS color #ADFF2F
   * <span class="colorSwath" style="background: #ADFF2F;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.GREENYELLOW = Object.freeze(Color.fromCssColorString("#ADFF2F"));

  /**
   * An immutable Color instance initialized to CSS color #808080
   * <span class="colorSwath" style="background: #808080;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.GREY = Color.GRAY;

  /**
   * An immutable Color instance initialized to CSS color #F0FFF0
   * <span class="colorSwath" style="background: #F0FFF0;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.HONEYDEW = Object.freeze(Color.fromCssColorString("#F0FFF0"));

  /**
   * An immutable Color instance initialized to CSS color #FF69B4
   * <span class="colorSwath" style="background: #FF69B4;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.HOTPINK = Object.freeze(Color.fromCssColorString("#FF69B4"));

  /**
   * An immutable Color instance initialized to CSS color #CD5C5C
   * <span class="colorSwath" style="background: #CD5C5C;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.INDIANRED = Object.freeze(Color.fromCssColorString("#CD5C5C"));

  /**
   * An immutable Color instance initialized to CSS color #4B0082
   * <span class="colorSwath" style="background: #4B0082;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.INDIGO = Object.freeze(Color.fromCssColorString("#4B0082"));

  /**
   * An immutable Color instance initialized to CSS color #FFFFF0
   * <span class="colorSwath" style="background: #FFFFF0;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.IVORY = Object.freeze(Color.fromCssColorString("#FFFFF0"));

  /**
   * An immutable Color instance initialized to CSS color #F0E68C
   * <span class="colorSwath" style="background: #F0E68C;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.KHAKI = Object.freeze(Color.fromCssColorString("#F0E68C"));

  /**
   * An immutable Color instance initialized to CSS color #E6E6FA
   * <span class="colorSwath" style="background: #E6E6FA;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.LAVENDER = Object.freeze(Color.fromCssColorString("#E6E6FA"));

  /**
   * An immutable Color instance initialized to CSS color #FFF0F5
   * <span class="colorSwath" style="background: #FFF0F5;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.LAVENDAR_BLUSH = Object.freeze(Color.fromCssColorString("#FFF0F5"));

  /**
   * An immutable Color instance initialized to CSS color #7CFC00
   * <span class="colorSwath" style="background: #7CFC00;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.LAWNGREEN = Object.freeze(Color.fromCssColorString("#7CFC00"));

  /**
   * An immutable Color instance initialized to CSS color #FFFACD
   * <span class="colorSwath" style="background: #FFFACD;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.LEMONCHIFFON = Object.freeze(Color.fromCssColorString("#FFFACD"));

  /**
   * An immutable Color instance initialized to CSS color #ADD8E6
   * <span class="colorSwath" style="background: #ADD8E6;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.LIGHTBLUE = Object.freeze(Color.fromCssColorString("#ADD8E6"));

  /**
   * An immutable Color instance initialized to CSS color #F08080
   * <span class="colorSwath" style="background: #F08080;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.LIGHTCORAL = Object.freeze(Color.fromCssColorString("#F08080"));

  /**
   * An immutable Color instance initialized to CSS color #E0FFFF
   * <span class="colorSwath" style="background: #E0FFFF;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.LIGHTCYAN = Object.freeze(Color.fromCssColorString("#E0FFFF"));

  /**
   * An immutable Color instance initialized to CSS color #FAFAD2
   * <span class="colorSwath" style="background: #FAFAD2;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.LIGHTGOLDENRODYELLOW = Object.freeze(Color.fromCssColorString("#FAFAD2"));

  /**
   * An immutable Color instance initialized to CSS color #D3D3D3
   * <span class="colorSwath" style="background: #D3D3D3;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.LIGHTGRAY = Object.freeze(Color.fromCssColorString("#D3D3D3"));

  /**
   * An immutable Color instance initialized to CSS color #90EE90
   * <span class="colorSwath" style="background: #90EE90;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.LIGHTGREEN = Object.freeze(Color.fromCssColorString("#90EE90"));

  /**
   * An immutable Color instance initialized to CSS color #D3D3D3
   * <span class="colorSwath" style="background: #D3D3D3;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.LIGHTGREY = Color.LIGHTGRAY;

  /**
   * An immutable Color instance initialized to CSS color #FFB6C1
   * <span class="colorSwath" style="background: #FFB6C1;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.LIGHTPINK = Object.freeze(Color.fromCssColorString("#FFB6C1"));

  /**
   * An immutable Color instance initialized to CSS color #20B2AA
   * <span class="colorSwath" style="background: #20B2AA;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.LIGHTSEAGREEN = Object.freeze(Color.fromCssColorString("#20B2AA"));

  /**
   * An immutable Color instance initialized to CSS color #87CEFA
   * <span class="colorSwath" style="background: #87CEFA;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.LIGHTSKYBLUE = Object.freeze(Color.fromCssColorString("#87CEFA"));

  /**
   * An immutable Color instance initialized to CSS color #778899
   * <span class="colorSwath" style="background: #778899;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.LIGHTSLATEGRAY = Object.freeze(Color.fromCssColorString("#778899"));

  /**
   * An immutable Color instance initialized to CSS color #778899
   * <span class="colorSwath" style="background: #778899;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.LIGHTSLATEGREY = Color.LIGHTSLATEGRAY;

  /**
   * An immutable Color instance initialized to CSS color #B0C4DE
   * <span class="colorSwath" style="background: #B0C4DE;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.LIGHTSTEELBLUE = Object.freeze(Color.fromCssColorString("#B0C4DE"));

  /**
   * An immutable Color instance initialized to CSS color #FFFFE0
   * <span class="colorSwath" style="background: #FFFFE0;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.LIGHTYELLOW = Object.freeze(Color.fromCssColorString("#FFFFE0"));

  /**
   * An immutable Color instance initialized to CSS color #00FF00
   * <span class="colorSwath" style="background: #00FF00;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.LIME = Object.freeze(Color.fromCssColorString("#00FF00"));

  /**
   * An immutable Color instance initialized to CSS color #32CD32
   * <span class="colorSwath" style="background: #32CD32;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.LIMEGREEN = Object.freeze(Color.fromCssColorString("#32CD32"));

  /**
   * An immutable Color instance initialized to CSS color #FAF0E6
   * <span class="colorSwath" style="background: #FAF0E6;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.LINEN = Object.freeze(Color.fromCssColorString("#FAF0E6"));

  /**
   * An immutable Color instance initialized to CSS color #FF00FF
   * <span class="colorSwath" style="background: #FF00FF;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.MAGENTA = Object.freeze(Color.fromCssColorString("#FF00FF"));

  /**
   * An immutable Color instance initialized to CSS color #800000
   * <span class="colorSwath" style="background: #800000;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.MAROON = Object.freeze(Color.fromCssColorString("#800000"));

  /**
   * An immutable Color instance initialized to CSS color #66CDAA
   * <span class="colorSwath" style="background: #66CDAA;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.MEDIUMAQUAMARINE = Object.freeze(Color.fromCssColorString("#66CDAA"));

  /**
   * An immutable Color instance initialized to CSS color #0000CD
   * <span class="colorSwath" style="background: #0000CD;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.MEDIUMBLUE = Object.freeze(Color.fromCssColorString("#0000CD"));

  /**
   * An immutable Color instance initialized to CSS color #BA55D3
   * <span class="colorSwath" style="background: #BA55D3;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.MEDIUMORCHID = Object.freeze(Color.fromCssColorString("#BA55D3"));

  /**
   * An immutable Color instance initialized to CSS color #9370DB
   * <span class="colorSwath" style="background: #9370DB;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.MEDIUMPURPLE = Object.freeze(Color.fromCssColorString("#9370DB"));

  /**
   * An immutable Color instance initialized to CSS color #3CB371
   * <span class="colorSwath" style="background: #3CB371;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.MEDIUMSEAGREEN = Object.freeze(Color.fromCssColorString("#3CB371"));

  /**
   * An immutable Color instance initialized to CSS color #7B68EE
   * <span class="colorSwath" style="background: #7B68EE;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.MEDIUMSLATEBLUE = Object.freeze(Color.fromCssColorString("#7B68EE"));

  /**
   * An immutable Color instance initialized to CSS color #00FA9A
   * <span class="colorSwath" style="background: #00FA9A;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.MEDIUMSPRINGGREEN = Object.freeze(Color.fromCssColorString("#00FA9A"));

  /**
   * An immutable Color instance initialized to CSS color #48D1CC
   * <span class="colorSwath" style="background: #48D1CC;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.MEDIUMTURQUOISE = Object.freeze(Color.fromCssColorString("#48D1CC"));

  /**
   * An immutable Color instance initialized to CSS color #C71585
   * <span class="colorSwath" style="background: #C71585;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.MEDIUMVIOLETRED = Object.freeze(Color.fromCssColorString("#C71585"));

  /**
   * An immutable Color instance initialized to CSS color #191970
   * <span class="colorSwath" style="background: #191970;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.MIDNIGHTBLUE = Object.freeze(Color.fromCssColorString("#191970"));

  /**
   * An immutable Color instance initialized to CSS color #F5FFFA
   * <span class="colorSwath" style="background: #F5FFFA;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.MINTCREAM = Object.freeze(Color.fromCssColorString("#F5FFFA"));

  /**
   * An immutable Color instance initialized to CSS color #FFE4E1
   * <span class="colorSwath" style="background: #FFE4E1;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.MISTYROSE = Object.freeze(Color.fromCssColorString("#FFE4E1"));

  /**
   * An immutable Color instance initialized to CSS color #FFE4B5
   * <span class="colorSwath" style="background: #FFE4B5;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.MOCCASIN = Object.freeze(Color.fromCssColorString("#FFE4B5"));

  /**
   * An immutable Color instance initialized to CSS color #FFDEAD
   * <span class="colorSwath" style="background: #FFDEAD;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.NAVAJOWHITE = Object.freeze(Color.fromCssColorString("#FFDEAD"));

  /**
   * An immutable Color instance initialized to CSS color #000080
   * <span class="colorSwath" style="background: #000080;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.NAVY = Object.freeze(Color.fromCssColorString("#000080"));

  /**
   * An immutable Color instance initialized to CSS color #FDF5E6
   * <span class="colorSwath" style="background: #FDF5E6;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.OLDLACE = Object.freeze(Color.fromCssColorString("#FDF5E6"));

  /**
   * An immutable Color instance initialized to CSS color #808000
   * <span class="colorSwath" style="background: #808000;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.OLIVE = Object.freeze(Color.fromCssColorString("#808000"));

  /**
   * An immutable Color instance initialized to CSS color #6B8E23
   * <span class="colorSwath" style="background: #6B8E23;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.OLIVEDRAB = Object.freeze(Color.fromCssColorString("#6B8E23"));

  /**
   * An immutable Color instance initialized to CSS color #FFA500
   * <span class="colorSwath" style="background: #FFA500;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.ORANGE = Object.freeze(Color.fromCssColorString("#FFA500"));

  /**
   * An immutable Color instance initialized to CSS color #FF4500
   * <span class="colorSwath" style="background: #FF4500;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.ORANGERED = Object.freeze(Color.fromCssColorString("#FF4500"));

  /**
   * An immutable Color instance initialized to CSS color #DA70D6
   * <span class="colorSwath" style="background: #DA70D6;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.ORCHID = Object.freeze(Color.fromCssColorString("#DA70D6"));

  /**
   * An immutable Color instance initialized to CSS color #EEE8AA
   * <span class="colorSwath" style="background: #EEE8AA;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.PALEGOLDENROD = Object.freeze(Color.fromCssColorString("#EEE8AA"));

  /**
   * An immutable Color instance initialized to CSS color #98FB98
   * <span class="colorSwath" style="background: #98FB98;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.PALEGREEN = Object.freeze(Color.fromCssColorString("#98FB98"));

  /**
   * An immutable Color instance initialized to CSS color #AFEEEE
   * <span class="colorSwath" style="background: #AFEEEE;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.PALETURQUOISE = Object.freeze(Color.fromCssColorString("#AFEEEE"));

  /**
   * An immutable Color instance initialized to CSS color #DB7093
   * <span class="colorSwath" style="background: #DB7093;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.PALEVIOLETRED = Object.freeze(Color.fromCssColorString("#DB7093"));

  /**
   * An immutable Color instance initialized to CSS color #FFEFD5
   * <span class="colorSwath" style="background: #FFEFD5;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.PAPAYAWHIP = Object.freeze(Color.fromCssColorString("#FFEFD5"));

  /**
   * An immutable Color instance initialized to CSS color #FFDAB9
   * <span class="colorSwath" style="background: #FFDAB9;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.PEACHPUFF = Object.freeze(Color.fromCssColorString("#FFDAB9"));

  /**
   * An immutable Color instance initialized to CSS color #CD853F
   * <span class="colorSwath" style="background: #CD853F;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.PERU = Object.freeze(Color.fromCssColorString("#CD853F"));

  /**
   * An immutable Color instance initialized to CSS color #FFC0CB
   * <span class="colorSwath" style="background: #FFC0CB;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.PINK = Object.freeze(Color.fromCssColorString("#FFC0CB"));

  /**
   * An immutable Color instance initialized to CSS color #DDA0DD
   * <span class="colorSwath" style="background: #DDA0DD;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.PLUM = Object.freeze(Color.fromCssColorString("#DDA0DD"));

  /**
   * An immutable Color instance initialized to CSS color #B0E0E6
   * <span class="colorSwath" style="background: #B0E0E6;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.POWDERBLUE = Object.freeze(Color.fromCssColorString("#B0E0E6"));

  /**
   * An immutable Color instance initialized to CSS color #800080
   * <span class="colorSwath" style="background: #800080;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.PURPLE = Object.freeze(Color.fromCssColorString("#800080"));

  /**
   * An immutable Color instance initialized to CSS color #FF0000
   * <span class="colorSwath" style="background: #FF0000;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.RED = Object.freeze(Color.fromCssColorString("#FF0000"));

  /**
   * An immutable Color instance initialized to CSS color #BC8F8F
   * <span class="colorSwath" style="background: #BC8F8F;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.ROSYBROWN = Object.freeze(Color.fromCssColorString("#BC8F8F"));

  /**
   * An immutable Color instance initialized to CSS color #4169E1
   * <span class="colorSwath" style="background: #4169E1;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.ROYALBLUE = Object.freeze(Color.fromCssColorString("#4169E1"));

  /**
   * An immutable Color instance initialized to CSS color #8B4513
   * <span class="colorSwath" style="background: #8B4513;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.SADDLEBROWN = Object.freeze(Color.fromCssColorString("#8B4513"));

  /**
   * An immutable Color instance initialized to CSS color #FA8072
   * <span class="colorSwath" style="background: #FA8072;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.SALMON = Object.freeze(Color.fromCssColorString("#FA8072"));

  /**
   * An immutable Color instance initialized to CSS color #F4A460
   * <span class="colorSwath" style="background: #F4A460;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.SANDYBROWN = Object.freeze(Color.fromCssColorString("#F4A460"));

  /**
   * An immutable Color instance initialized to CSS color #2E8B57
   * <span class="colorSwath" style="background: #2E8B57;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.SEAGREEN = Object.freeze(Color.fromCssColorString("#2E8B57"));

  /**
   * An immutable Color instance initialized to CSS color #FFF5EE
   * <span class="colorSwath" style="background: #FFF5EE;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.SEASHELL = Object.freeze(Color.fromCssColorString("#FFF5EE"));

  /**
   * An immutable Color instance initialized to CSS color #A0522D
   * <span class="colorSwath" style="background: #A0522D;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.SIENNA = Object.freeze(Color.fromCssColorString("#A0522D"));

  /**
   * An immutable Color instance initialized to CSS color #C0C0C0
   * <span class="colorSwath" style="background: #C0C0C0;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.SILVER = Object.freeze(Color.fromCssColorString("#C0C0C0"));

  /**
   * An immutable Color instance initialized to CSS color #87CEEB
   * <span class="colorSwath" style="background: #87CEEB;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.SKYBLUE = Object.freeze(Color.fromCssColorString("#87CEEB"));

  /**
   * An immutable Color instance initialized to CSS color #6A5ACD
   * <span class="colorSwath" style="background: #6A5ACD;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.SLATEBLUE = Object.freeze(Color.fromCssColorString("#6A5ACD"));

  /**
   * An immutable Color instance initialized to CSS color #708090
   * <span class="colorSwath" style="background: #708090;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.SLATEGRAY = Object.freeze(Color.fromCssColorString("#708090"));

  /**
   * An immutable Color instance initialized to CSS color #708090
   * <span class="colorSwath" style="background: #708090;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.SLATEGREY = Color.SLATEGRAY;

  /**
   * An immutable Color instance initialized to CSS color #FFFAFA
   * <span class="colorSwath" style="background: #FFFAFA;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.SNOW = Object.freeze(Color.fromCssColorString("#FFFAFA"));

  /**
   * An immutable Color instance initialized to CSS color #00FF7F
   * <span class="colorSwath" style="background: #00FF7F;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.SPRINGGREEN = Object.freeze(Color.fromCssColorString("#00FF7F"));

  /**
   * An immutable Color instance initialized to CSS color #4682B4
   * <span class="colorSwath" style="background: #4682B4;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.STEELBLUE = Object.freeze(Color.fromCssColorString("#4682B4"));

  /**
   * An immutable Color instance initialized to CSS color #D2B48C
   * <span class="colorSwath" style="background: #D2B48C;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.TAN = Object.freeze(Color.fromCssColorString("#D2B48C"));

  /**
   * An immutable Color instance initialized to CSS color #008080
   * <span class="colorSwath" style="background: #008080;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.TEAL = Object.freeze(Color.fromCssColorString("#008080"));

  /**
   * An immutable Color instance initialized to CSS color #D8BFD8
   * <span class="colorSwath" style="background: #D8BFD8;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.THISTLE = Object.freeze(Color.fromCssColorString("#D8BFD8"));

  /**
   * An immutable Color instance initialized to CSS color #FF6347
   * <span class="colorSwath" style="background: #FF6347;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.TOMATO = Object.freeze(Color.fromCssColorString("#FF6347"));

  /**
   * An immutable Color instance initialized to CSS color #40E0D0
   * <span class="colorSwath" style="background: #40E0D0;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.TURQUOISE = Object.freeze(Color.fromCssColorString("#40E0D0"));

  /**
   * An immutable Color instance initialized to CSS color #EE82EE
   * <span class="colorSwath" style="background: #EE82EE;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.VIOLET = Object.freeze(Color.fromCssColorString("#EE82EE"));

  /**
   * An immutable Color instance initialized to CSS color #F5DEB3
   * <span class="colorSwath" style="background: #F5DEB3;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.WHEAT = Object.freeze(Color.fromCssColorString("#F5DEB3"));

  /**
   * An immutable Color instance initialized to CSS color #FFFFFF
   * <span class="colorSwath" style="background: #FFFFFF;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.WHITE = Object.freeze(Color.fromCssColorString("#FFFFFF"));

  /**
   * An immutable Color instance initialized to CSS color #F5F5F5
   * <span class="colorSwath" style="background: #F5F5F5;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.WHITESMOKE = Object.freeze(Color.fromCssColorString("#F5F5F5"));

  /**
   * An immutable Color instance initialized to CSS color #FFFF00
   * <span class="colorSwath" style="background: #FFFF00;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.YELLOW = Object.freeze(Color.fromCssColorString("#FFFF00"));

  /**
   * An immutable Color instance initialized to CSS color #9ACD32
   * <span class="colorSwath" style="background: #9ACD32;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.YELLOWGREEN = Object.freeze(Color.fromCssColorString("#9ACD32"));

  /**
   * An immutable Color instance initialized to CSS transparent.
   * <span class="colorSwath" style="background: transparent;"></span>
   *
   * @constant
   * @type {Color}
   */
  Color.TRANSPARENT = Object.freeze(new Color(0, 0, 0, 0));

  /**
   * Value and type information for per-instance geometry color.
   *
   * @alias ColorGeometryInstanceAttribute
   * @constructor
   *
   * @param {Number} [red=1.0] The red component.
   * @param {Number} [green=1.0] The green component.
   * @param {Number} [blue=1.0] The blue component.
   * @param {Number} [alpha=1.0] The alpha component.
   *
   *
   * @example
   * const instance = new Cesium.GeometryInstance({
   *   geometry : Cesium.BoxGeometry.fromDimensions({
   *     dimensions : new Cesium.Cartesian3(1000000.0, 1000000.0, 500000.0)
   *   }),
   *   modelMatrix : Cesium.Matrix4.multiplyByTranslation(Cesium.Transforms.eastNorthUpToFixedFrame(
   *     Cesium.Cartesian3.fromDegrees(0.0, 0.0)), new Cesium.Cartesian3(0.0, 0.0, 1000000.0), new Cesium.Matrix4()),
   *   id : 'box',
   *   attributes : {
   *     color : new Cesium.ColorGeometryInstanceAttribute(red, green, blue, alpha)
   *   }
   * });
   *
   * @see GeometryInstance
   * @see GeometryInstanceAttribute
   */
  function ColorGeometryInstanceAttribute(red, green, blue, alpha) {
    red = defaultValue(red, 1.0);
    green = defaultValue(green, 1.0);
    blue = defaultValue(blue, 1.0);
    alpha = defaultValue(alpha, 1.0);

    /**
     * The values for the attributes stored in a typed array.
     *
     * @type Uint8Array
     *
     * @default [255, 255, 255, 255]
     */
    this.value = new Uint8Array([
      Color.floatToByte(red),
      Color.floatToByte(green),
      Color.floatToByte(blue),
      Color.floatToByte(alpha),
    ]);
  }

  Object.defineProperties(ColorGeometryInstanceAttribute.prototype, {
    /**
     * The datatype of each component in the attribute, e.g., individual elements in
     * {@link ColorGeometryInstanceAttribute#value}.
     *
     * @memberof ColorGeometryInstanceAttribute.prototype
     *
     * @type {ComponentDatatype}
     * @readonly
     *
     * @default {@link ComponentDatatype.UNSIGNED_BYTE}
     */
    componentDatatype: {
      get: function () {
        return ComponentDatatype$1.UNSIGNED_BYTE;
      },
    },

    /**
     * The number of components in the attributes, i.e., {@link ColorGeometryInstanceAttribute#value}.
     *
     * @memberof ColorGeometryInstanceAttribute.prototype
     *
     * @type {Number}
     * @readonly
     *
     * @default 4
     */
    componentsPerAttribute: {
      get: function () {
        return 4;
      },
    },

    /**
     * When <code>true</code> and <code>componentDatatype</code> is an integer format,
     * indicate that the components should be mapped to the range [0, 1] (unsigned)
     * or [-1, 1] (signed) when they are accessed as floating-point for rendering.
     *
     * @memberof ColorGeometryInstanceAttribute.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default true
     */
    normalize: {
      get: function () {
        return true;
      },
    },
  });

  /**
   * Creates a new {@link ColorGeometryInstanceAttribute} instance given the provided {@link Color}.
   *
   * @param {Color} color The color.
   * @returns {ColorGeometryInstanceAttribute} The new {@link ColorGeometryInstanceAttribute} instance.
   *
   * @example
   * const instance = new Cesium.GeometryInstance({
   *   geometry : geometry,
   *   attributes : {
   *     color : Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.CORNFLOWERBLUE),
   *   }
   * });
   */
  ColorGeometryInstanceAttribute.fromColor = function (color) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(color)) {
      throw new DeveloperError("color is required.");
    }
    //>>includeEnd('debug');

    return new ColorGeometryInstanceAttribute(
      color.red,
      color.green,
      color.blue,
      color.alpha
    );
  };

  /**
   * Converts a color to a typed array that can be used to assign a color attribute.
   *
   * @param {Color} color The color.
   * @param {Uint8Array} [result] The array to store the result in, if undefined a new instance will be created.
   *
   * @returns {Uint8Array} The modified result parameter or a new instance if result was undefined.
   *
   * @example
   * const attributes = primitive.getGeometryInstanceAttributes('an id');
   * attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.AQUA, attributes.color);
   */
  ColorGeometryInstanceAttribute.toValue = function (color, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(color)) {
      throw new DeveloperError("color is required.");
    }
    //>>includeEnd('debug');

    if (!defined(result)) {
      return new Uint8Array(color.toBytes());
    }
    return color.toBytes(result);
  };

  /**
   * Compares the provided ColorGeometryInstanceAttributes and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {ColorGeometryInstanceAttribute} [left] The first ColorGeometryInstanceAttribute.
   * @param {ColorGeometryInstanceAttribute} [right] The second ColorGeometryInstanceAttribute.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  ColorGeometryInstanceAttribute.equals = function (left, right) {
    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        left.value[0] === right.value[0] &&
        left.value[1] === right.value[1] &&
        left.value[2] === right.value[2] &&
        left.value[3] === right.value[3])
    );
  };

  /**
   * Describes a compressed texture and contains a compressed texture buffer.
   * @alias CompressedTextureBuffer
   * @constructor
   *
   * @param {PixelFormat} internalFormat The pixel format of the compressed texture.
   * @param {PixelDatatype} pixelDatatype The pixel datatype of the compressed texture.
   * @param {Number} width The width of the texture.
   * @param {Number} height The height of the texture.
   * @param {Uint8Array} buffer The compressed texture buffer.
   */
  function CompressedTextureBuffer(
    internalFormat,
    pixelDatatype,
    width,
    height,
    buffer
  ) {
    this._format = internalFormat;
    this._datatype = pixelDatatype;
    this._width = width;
    this._height = height;
    this._buffer = buffer;
  }

  Object.defineProperties(CompressedTextureBuffer.prototype, {
    /**
     * The format of the compressed texture.
     * @type PixelFormat
     * @readonly
     * @memberof CompressedTextureBuffer.prototype
     */
    internalFormat: {
      get: function () {
        return this._format;
      },
    },
    /**
     * The datatype of the compressed texture.
     * @type PixelDatatype
     * @readonly
     * @memberof CompressedTextureBuffer.prototype
     */
    pixelDatatype: {
      get: function () {
        return this._datatype;
      },
    },
    /**
     * The width of the texture.
     * @type Number
     * @readonly
     * @memberof CompressedTextureBuffer.prototype
     */
    width: {
      get: function () {
        return this._width;
      },
    },
    /**
     * The height of the texture.
     * @type Number
     * @readonly
     * @memberof CompressedTextureBuffer.prototype
     */
    height: {
      get: function () {
        return this._height;
      },
    },
    /**
     * The compressed texture buffer.
     * @type Uint8Array
     * @readonly
     * @memberof CompressedTextureBuffer.prototype
     */
    bufferView: {
      get: function () {
        return this._buffer;
      },
    },
  });

  /**
   * Creates a shallow clone of a compressed texture buffer.
   *
   * @param {CompressedTextureBuffer} object The compressed texture buffer to be cloned.
   * @return {CompressedTextureBuffer} A shallow clone of the compressed texture buffer.
   */
  CompressedTextureBuffer.clone = function (object) {
    if (!defined(object)) {
      return undefined;
    }

    return new CompressedTextureBuffer(
      object._format,
      object._datatype,
      object._width,
      object._height,
      object._buffer
    );
  };

  /**
   * Creates a shallow clone of this compressed texture buffer.
   *
   * @return {CompressedTextureBuffer} A shallow clone of the compressed texture buffer.
   */
  CompressedTextureBuffer.prototype.clone = function () {
    return CompressedTextureBuffer.clone(this);
  };

  /**
   * A spline that evaluates to a constant value. Although this follows the {@link Spline} interface,
   * it does not maintain an internal array of times since its value never changes.
   *
   * @alias ConstantSpline
   * @constructor
   *
   * @param {Number|Cartesian3|Quaternion} value The constant value that the spline evaluates to.
   *
   * @example
   * const position = new Cesium.Cartesian3(1.0, 2.0, 3.0);
   * const spline = new Cesium.ConstantSpline(position);
   *
   * const p0 = spline.evaluate(0.0);
   *
   * @see LinearSpline
   * @see HermiteSpline
   * @see CatmullRomSpline
   * @see QuaternionSpline
   * @see MorphWeightSpline
   */
  function ConstantSpline(value) {
    this._value = value;
    this._valueType = Spline.getPointType(value);
  }

  Object.defineProperties(ConstantSpline.prototype, {
    /**
     * The constant value that the spline evaluates to.
     *
     * @memberof ConstantSpline.prototype
     *
     * @type {Number|Cartesian3|Quaternion}
     * @readonly
     */
    value: {
      get: function () {
        return this._value;
      },
    },
  });

  /**
   * Finds an index <code>i</code> in <code>times</code> such that the parameter
   * <code>time</code> is in the interval <code>[times[i], times[i + 1]]</code>.
   *
   * Since a constant spline has no internal times array, this will throw an error.
   * @function
   *
   * @param {Number} time The time.
   *
   * @exception {DeveloperError} findTimeInterval cannot be called on a ConstantSpline.
   */
  ConstantSpline.prototype.findTimeInterval = function (time) {
    //>>includeStart('debug', pragmas.debug);
    throw new DeveloperError(
      "findTimeInterval cannot be called on a ConstantSpline."
    );
    //>>includeEnd('debug');
  };

  /**
   * Wraps the given time to the period covered by the spline.
   * @function
   *
   * @param {Number} time The time.
   * @return {Number} The time, wrapped around to the updated animation.
   */
  ConstantSpline.prototype.wrapTime = function (time) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("time", time);
    //>>includeEnd('debug');

    return 0.0;
  };

  /**
   * Clamps the given time to the period covered by the spline.
   * @function
   *
   * @param {Number} time The time.
   * @return {Number} The time, clamped to the animation period.
   */
  ConstantSpline.prototype.clampTime = function (time) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("time", time);
    //>>includeEnd('debug');

    return 0.0;
  };

  /**
   * Evaluates the curve at a given time.
   * @function
   *
   * @param {Number} time The time at which to evaluate the curve.
   * @param {Cartesian3|Quaternion} [result] The object onto which to store the result.
   * @returns {Number|Cartesian3|Quaternion} The modified result parameter or the value that the constant spline represents.
   */
  ConstantSpline.prototype.evaluate = function (time, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("time", time);
    //>>includeEnd('debug');

    const value = this._value;
    const ValueType = this._valueType;

    if (ValueType === Number) {
      return value;
    }

    return ValueType.clone(value, result);
  };

  const removeDuplicatesEpsilon = CesiumMath.EPSILON10;

  /**
   * Removes adjacent duplicate values in an array of values.
   *
   * @param {Array.<*>} [values] The array of values.
   * @param {Function} equalsEpsilon Function to compare values with an epsilon. Boolean equalsEpsilon(left, right, epsilon).
   * @param {Boolean} [wrapAround=false] Compare the last value in the array against the first value. If they are equal, the last value is removed.
   * @param {Array.<Number>} [removedIndices=undefined] Store the indices that correspond to the duplicate items removed from the array, if there were any.
   * @returns {Array.<*>|undefined} A new array of values with no adjacent duplicate values or the input array if no duplicates were found.
   *
   * @example
   * // Returns [(1.0, 1.0, 1.0), (2.0, 2.0, 2.0), (3.0, 3.0, 3.0), (1.0, 1.0, 1.0)]
   * const values = [
   *     new Cesium.Cartesian3(1.0, 1.0, 1.0),
   *     new Cesium.Cartesian3(1.0, 1.0, 1.0),
   *     new Cesium.Cartesian3(2.0, 2.0, 2.0),
   *     new Cesium.Cartesian3(3.0, 3.0, 3.0),
   *     new Cesium.Cartesian3(1.0, 1.0, 1.0)];
   * const nonDuplicatevalues = Cesium.PolylinePipeline.removeDuplicates(values, Cartesian3.equalsEpsilon);
   *
   * @example
   * // Returns [(1.0, 1.0, 1.0), (2.0, 2.0, 2.0), (3.0, 3.0, 3.0)]
   * const values = [
   *     new Cesium.Cartesian3(1.0, 1.0, 1.0),
   *     new Cesium.Cartesian3(1.0, 1.0, 1.0),
   *     new Cesium.Cartesian3(2.0, 2.0, 2.0),
   *     new Cesium.Cartesian3(3.0, 3.0, 3.0),
   *     new Cesium.Cartesian3(1.0, 1.0, 1.0)];
   * const nonDuplicatevalues = Cesium.PolylinePipeline.removeDuplicates(values, Cartesian3.equalsEpsilon, true);
   *
   * @example
   * // Returns [(1.0, 1.0, 1.0), (2.0, 2.0, 2.0), (3.0, 3.0, 3.0)]
   * // removedIndices will be equal to [1, 3, 5]
   * const values = [
   *     new Cesium.Cartesian3(1.0, 1.0, 1.0),
   *     new Cesium.Cartesian3(1.0, 1.0, 1.0),
   *     new Cesium.Cartesian3(2.0, 2.0, 2.0),
   *     new Cesium.Cartesian3(2.0, 2.0, 2.0),
   *     new Cesium.Cartesian3(3.0, 3.0, 3.0),
   *     new Cesium.Cartesian3(1.0, 1.0, 1.0)];
   * const nonDuplicatevalues = Cesium.PolylinePipeline.removeDuplicates(values, Cartesian3.equalsEpsilon, true);
   * @private
   */
  function arrayRemoveDuplicates(
    values,
    equalsEpsilon,
    wrapAround,
    removedIndices
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("equalsEpsilon", equalsEpsilon);
    //>>includeEnd('debug');

    if (!defined(values)) {
      return undefined;
    }

    wrapAround = defaultValue(wrapAround, false);
    const storeRemovedIndices = defined(removedIndices);

    const length = values.length;
    if (length < 2) {
      return values;
    }

    let i;
    let v0 = values[0];
    let v1;

    // We only want to create a new array if there are duplicates in the array.
    // As such, cleanedValues is undefined until it encounters the first duplicate, if it exists.
    let cleanedValues;
    let lastCleanIndex = 0;

    // removedIndexLCI keeps track of where lastCleanIndex would be if it were sorted into the removedIndices array.
    // In case of arrays such as [A, B, C, ..., A, A, A], removedIndices will not be sorted properly without this.
    let removedIndexLCI = -1;

    for (i = 1; i < length; ++i) {
      v1 = values[i];
      if (equalsEpsilon(v0, v1, removeDuplicatesEpsilon)) {
        if (!defined(cleanedValues)) {
          cleanedValues = values.slice(0, i);
          lastCleanIndex = i - 1;
          removedIndexLCI = 0;
        }
        if (storeRemovedIndices) {
          removedIndices.push(i);
        }
      } else {
        if (defined(cleanedValues)) {
          cleanedValues.push(v1);
          lastCleanIndex = i;
          if (storeRemovedIndices) {
            removedIndexLCI = removedIndices.length;
          }
        }
        v0 = v1;
      }
    }

    if (
      wrapAround &&
      equalsEpsilon(values[0], values[length - 1], removeDuplicatesEpsilon)
    ) {
      if (storeRemovedIndices) {
        if (defined(cleanedValues)) {
          removedIndices.splice(removedIndexLCI, 0, lastCleanIndex);
        } else {
          removedIndices.push(length - 1);
        }
      }

      if (defined(cleanedValues)) {
        cleanedValues.length -= 1;
      } else {
        cleanedValues = values.slice(0, -1);
      }
    }

    return defined(cleanedValues) ? cleanedValues : values;
  }

  /**
   * @private
   */
  const CoplanarPolygonGeometryLibrary = {};

  const scratchIntersectionPoint = new Cartesian3();
  const scratchXAxis = new Cartesian3();
  const scratchYAxis = new Cartesian3();
  const scratchZAxis = new Cartesian3();
  const obbScratch = new OrientedBoundingBox();

  CoplanarPolygonGeometryLibrary.validOutline = function (positions) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("positions", positions);
    //>>includeEnd('debug');

    const orientedBoundingBox = OrientedBoundingBox.fromPoints(
      positions,
      obbScratch
    );
    const halfAxes = orientedBoundingBox.halfAxes;
    const xAxis = Matrix3.getColumn(halfAxes, 0, scratchXAxis);
    const yAxis = Matrix3.getColumn(halfAxes, 1, scratchYAxis);
    const zAxis = Matrix3.getColumn(halfAxes, 2, scratchZAxis);

    const xMag = Cartesian3.magnitude(xAxis);
    const yMag = Cartesian3.magnitude(yAxis);
    const zMag = Cartesian3.magnitude(zAxis);

    // If all the points are on a line return undefined because we can't draw a polygon
    return !(
      (xMag === 0 && (yMag === 0 || zMag === 0)) ||
      (yMag === 0 && zMag === 0)
    );
  };

  // call after removeDuplicates
  CoplanarPolygonGeometryLibrary.computeProjectTo2DArguments = function (
    positions,
    centerResult,
    planeAxis1Result,
    planeAxis2Result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("positions", positions);
    Check.defined("centerResult", centerResult);
    Check.defined("planeAxis1Result", planeAxis1Result);
    Check.defined("planeAxis2Result", planeAxis2Result);
    //>>includeEnd('debug');

    const orientedBoundingBox = OrientedBoundingBox.fromPoints(
      positions,
      obbScratch
    );
    const halfAxes = orientedBoundingBox.halfAxes;
    const xAxis = Matrix3.getColumn(halfAxes, 0, scratchXAxis);
    const yAxis = Matrix3.getColumn(halfAxes, 1, scratchYAxis);
    const zAxis = Matrix3.getColumn(halfAxes, 2, scratchZAxis);

    const xMag = Cartesian3.magnitude(xAxis);
    const yMag = Cartesian3.magnitude(yAxis);
    const zMag = Cartesian3.magnitude(zAxis);
    const min = Math.min(xMag, yMag, zMag);

    // If all the points are on a line return undefined because we can't draw a polygon
    if (
      (xMag === 0 && (yMag === 0 || zMag === 0)) ||
      (yMag === 0 && zMag === 0)
    ) {
      return false;
    }

    let planeAxis1;
    let planeAxis2;

    if (min === yMag || min === zMag) {
      planeAxis1 = xAxis;
    }
    if (min === xMag) {
      planeAxis1 = yAxis;
    } else if (min === zMag) {
      planeAxis2 = yAxis;
    }
    if (min === xMag || min === yMag) {
      planeAxis2 = zAxis;
    }

    Cartesian3.normalize(planeAxis1, planeAxis1Result);
    Cartesian3.normalize(planeAxis2, planeAxis2Result);
    Cartesian3.clone(orientedBoundingBox.center, centerResult);
    return true;
  };

  function projectTo2D(position, center, axis1, axis2, result) {
    const v = Cartesian3.subtract(position, center, scratchIntersectionPoint);
    const x = Cartesian3.dot(axis1, v);
    const y = Cartesian3.dot(axis2, v);

    return Cartesian2.fromElements(x, y, result);
  }

  CoplanarPolygonGeometryLibrary.createProjectPointsTo2DFunction = function (
    center,
    axis1,
    axis2
  ) {
    return function (positions) {
      const positionResults = new Array(positions.length);
      for (let i = 0; i < positions.length; i++) {
        positionResults[i] = projectTo2D(positions[i], center, axis1, axis2);
      }

      return positionResults;
    };
  };

  CoplanarPolygonGeometryLibrary.createProjectPointTo2DFunction = function (
    center,
    axis1,
    axis2
  ) {
    return function (position, result) {
      return projectTo2D(position, center, axis1, axis2, result);
    };
  };

  function calculateM(ellipticity, major, latitude) {
    if (ellipticity === 0.0) {
      // sphere
      return major * latitude;
    }

    const e2 = ellipticity * ellipticity;
    const e4 = e2 * e2;
    const e6 = e4 * e2;
    const e8 = e6 * e2;
    const e10 = e8 * e2;
    const e12 = e10 * e2;
    const phi = latitude;
    const sin2Phi = Math.sin(2 * phi);
    const sin4Phi = Math.sin(4 * phi);
    const sin6Phi = Math.sin(6 * phi);
    const sin8Phi = Math.sin(8 * phi);
    const sin10Phi = Math.sin(10 * phi);
    const sin12Phi = Math.sin(12 * phi);

    return (
      major *
      ((1 -
        e2 / 4 -
        (3 * e4) / 64 -
        (5 * e6) / 256 -
        (175 * e8) / 16384 -
        (441 * e10) / 65536 -
        (4851 * e12) / 1048576) *
        phi -
        ((3 * e2) / 8 +
          (3 * e4) / 32 +
          (45 * e6) / 1024 +
          (105 * e8) / 4096 +
          (2205 * e10) / 131072 +
          (6237 * e12) / 524288) *
          sin2Phi +
        ((15 * e4) / 256 +
          (45 * e6) / 1024 +
          (525 * e8) / 16384 +
          (1575 * e10) / 65536 +
          (155925 * e12) / 8388608) *
          sin4Phi -
        ((35 * e6) / 3072 +
          (175 * e8) / 12288 +
          (3675 * e10) / 262144 +
          (13475 * e12) / 1048576) *
          sin6Phi +
        ((315 * e8) / 131072 + (2205 * e10) / 524288 + (43659 * e12) / 8388608) *
          sin8Phi -
        ((693 * e10) / 1310720 + (6237 * e12) / 5242880) * sin10Phi +
        ((1001 * e12) / 8388608) * sin12Phi)
    );
  }

  function calculateInverseM(M, ellipticity, major) {
    const d = M / major;

    if (ellipticity === 0.0) {
      // sphere
      return d;
    }

    const d2 = d * d;
    const d3 = d2 * d;
    const d4 = d3 * d;
    const e = ellipticity;
    const e2 = e * e;
    const e4 = e2 * e2;
    const e6 = e4 * e2;
    const e8 = e6 * e2;
    const e10 = e8 * e2;
    const e12 = e10 * e2;
    const sin2D = Math.sin(2 * d);
    const cos2D = Math.cos(2 * d);
    const sin4D = Math.sin(4 * d);
    const cos4D = Math.cos(4 * d);
    const sin6D = Math.sin(6 * d);
    const cos6D = Math.cos(6 * d);
    const sin8D = Math.sin(8 * d);
    const cos8D = Math.cos(8 * d);
    const sin10D = Math.sin(10 * d);
    const cos10D = Math.cos(10 * d);
    const sin12D = Math.sin(12 * d);

    return (
      d +
      (d * e2) / 4 +
      (7 * d * e4) / 64 +
      (15 * d * e6) / 256 +
      (579 * d * e8) / 16384 +
      (1515 * d * e10) / 65536 +
      (16837 * d * e12) / 1048576 +
      ((3 * d * e4) / 16 +
        (45 * d * e6) / 256 -
        (d * (32 * d2 - 561) * e8) / 4096 -
        (d * (232 * d2 - 1677) * e10) / 16384 +
        (d * (399985 - 90560 * d2 + 512 * d4) * e12) / 5242880) *
        cos2D +
      ((21 * d * e6) / 256 +
        (483 * d * e8) / 4096 -
        (d * (224 * d2 - 1969) * e10) / 16384 -
        (d * (33152 * d2 - 112599) * e12) / 1048576) *
        cos4D +
      ((151 * d * e8) / 4096 +
        (4681 * d * e10) / 65536 +
        (1479 * d * e12) / 16384 -
        (453 * d3 * e12) / 32768) *
        cos6D +
      ((1097 * d * e10) / 65536 + (42783 * d * e12) / 1048576) * cos8D +
      ((8011 * d * e12) / 1048576) * cos10D +
      ((3 * e2) / 8 +
        (3 * e4) / 16 +
        (213 * e6) / 2048 -
        (3 * d2 * e6) / 64 +
        (255 * e8) / 4096 -
        (33 * d2 * e8) / 512 +
        (20861 * e10) / 524288 -
        (33 * d2 * e10) / 512 +
        (d4 * e10) / 1024 +
        (28273 * e12) / 1048576 -
        (471 * d2 * e12) / 8192 +
        (9 * d4 * e12) / 4096) *
        sin2D +
      ((21 * e4) / 256 +
        (21 * e6) / 256 +
        (533 * e8) / 8192 -
        (21 * d2 * e8) / 512 +
        (197 * e10) / 4096 -
        (315 * d2 * e10) / 4096 +
        (584039 * e12) / 16777216 -
        (12517 * d2 * e12) / 131072 +
        (7 * d4 * e12) / 2048) *
        sin4D +
      ((151 * e6) / 6144 +
        (151 * e8) / 4096 +
        (5019 * e10) / 131072 -
        (453 * d2 * e10) / 16384 +
        (26965 * e12) / 786432 -
        (8607 * d2 * e12) / 131072) *
        sin6D +
      ((1097 * e8) / 131072 +
        (1097 * e10) / 65536 +
        (225797 * e12) / 10485760 -
        (1097 * d2 * e12) / 65536) *
        sin8D +
      ((8011 * e10) / 2621440 + (8011 * e12) / 1048576) * sin10D +
      ((293393 * e12) / 251658240) * sin12D
    );
  }

  function calculateSigma(ellipticity, latitude) {
    if (ellipticity === 0.0) {
      // sphere
      return Math.log(Math.tan(0.5 * (CesiumMath.PI_OVER_TWO + latitude)));
    }

    const eSinL = ellipticity * Math.sin(latitude);
    return (
      Math.log(Math.tan(0.5 * (CesiumMath.PI_OVER_TWO + latitude))) -
      (ellipticity / 2.0) * Math.log((1 + eSinL) / (1 - eSinL))
    );
  }

  function calculateHeading(
    ellipsoidRhumbLine,
    firstLongitude,
    firstLatitude,
    secondLongitude,
    secondLatitude
  ) {
    const sigma1 = calculateSigma(ellipsoidRhumbLine._ellipticity, firstLatitude);
    const sigma2 = calculateSigma(
      ellipsoidRhumbLine._ellipticity,
      secondLatitude
    );
    return Math.atan2(
      CesiumMath.negativePiToPi(secondLongitude - firstLongitude),
      sigma2 - sigma1
    );
  }

  function calculateArcLength(
    ellipsoidRhumbLine,
    major,
    minor,
    firstLongitude,
    firstLatitude,
    secondLongitude,
    secondLatitude
  ) {
    const heading = ellipsoidRhumbLine._heading;
    const deltaLongitude = secondLongitude - firstLongitude;

    let distance = 0.0;

    //Check to see if the rhumb line has constant latitude
    //This equation will diverge if heading gets close to 90 degrees
    if (
      CesiumMath.equalsEpsilon(
        Math.abs(heading),
        CesiumMath.PI_OVER_TWO,
        CesiumMath.EPSILON8
      )
    ) {
      //If heading is close to 90 degrees
      if (major === minor) {
        distance =
          major *
          Math.cos(firstLatitude) *
          CesiumMath.negativePiToPi(deltaLongitude);
      } else {
        const sinPhi = Math.sin(firstLatitude);
        distance =
          (major *
            Math.cos(firstLatitude) *
            CesiumMath.negativePiToPi(deltaLongitude)) /
          Math.sqrt(1 - ellipsoidRhumbLine._ellipticitySquared * sinPhi * sinPhi);
      }
    } else {
      const M1 = calculateM(
        ellipsoidRhumbLine._ellipticity,
        major,
        firstLatitude
      );
      const M2 = calculateM(
        ellipsoidRhumbLine._ellipticity,
        major,
        secondLatitude
      );

      distance = (M2 - M1) / Math.cos(heading);
    }
    return Math.abs(distance);
  }

  const scratchCart1$1 = new Cartesian3();
  const scratchCart2$2 = new Cartesian3();

  function computeProperties$1(ellipsoidRhumbLine, start, end, ellipsoid) {
    const firstCartesian = Cartesian3.normalize(
      ellipsoid.cartographicToCartesian(start, scratchCart2$2),
      scratchCart1$1
    );
    const lastCartesian = Cartesian3.normalize(
      ellipsoid.cartographicToCartesian(end, scratchCart2$2),
      scratchCart2$2
    );

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number.greaterThanOrEquals(
      "value",
      Math.abs(
        Math.abs(Cartesian3.angleBetween(firstCartesian, lastCartesian)) - Math.PI
      ),
      0.0125
    );
    //>>includeEnd('debug');

    const major = ellipsoid.maximumRadius;
    const minor = ellipsoid.minimumRadius;
    const majorSquared = major * major;
    const minorSquared = minor * minor;
    ellipsoidRhumbLine._ellipticitySquared =
      (majorSquared - minorSquared) / majorSquared;
    ellipsoidRhumbLine._ellipticity = Math.sqrt(
      ellipsoidRhumbLine._ellipticitySquared
    );

    ellipsoidRhumbLine._start = Cartographic.clone(
      start,
      ellipsoidRhumbLine._start
    );
    ellipsoidRhumbLine._start.height = 0;

    ellipsoidRhumbLine._end = Cartographic.clone(end, ellipsoidRhumbLine._end);
    ellipsoidRhumbLine._end.height = 0;

    ellipsoidRhumbLine._heading = calculateHeading(
      ellipsoidRhumbLine,
      start.longitude,
      start.latitude,
      end.longitude,
      end.latitude
    );
    ellipsoidRhumbLine._distance = calculateArcLength(
      ellipsoidRhumbLine,
      ellipsoid.maximumRadius,
      ellipsoid.minimumRadius,
      start.longitude,
      start.latitude,
      end.longitude,
      end.latitude
    );
  }

  function interpolateUsingSurfaceDistance(
    start,
    heading,
    distance,
    major,
    ellipticity,
    result
  ) {
    if (distance === 0.0) {
      return Cartographic.clone(start, result);
    }

    const ellipticitySquared = ellipticity * ellipticity;

    let longitude;
    let latitude;
    let deltaLongitude;

    //Check to see if the rhumb line has constant latitude
    //This won't converge if heading is close to 90 degrees
    if (
      Math.abs(CesiumMath.PI_OVER_TWO - Math.abs(heading)) > CesiumMath.EPSILON8
    ) {
      //Calculate latitude of the second point
      const M1 = calculateM(ellipticity, major, start.latitude);
      const deltaM = distance * Math.cos(heading);
      const M2 = M1 + deltaM;
      latitude = calculateInverseM(M2, ellipticity, major);

      //Now find the longitude of the second point
      const sigma1 = calculateSigma(ellipticity, start.latitude);
      const sigma2 = calculateSigma(ellipticity, latitude);
      deltaLongitude = Math.tan(heading) * (sigma2 - sigma1);
      longitude = CesiumMath.negativePiToPi(start.longitude + deltaLongitude);
    } else {
      //If heading is close to 90 degrees
      latitude = start.latitude;
      let localRad;

      if (ellipticity === 0.0) {
        // sphere
        localRad = major * Math.cos(start.latitude);
      } else {
        const sinPhi = Math.sin(start.latitude);
        localRad =
          (major * Math.cos(start.latitude)) /
          Math.sqrt(1 - ellipticitySquared * sinPhi * sinPhi);
      }

      deltaLongitude = distance / localRad;
      if (heading > 0.0) {
        longitude = CesiumMath.negativePiToPi(start.longitude + deltaLongitude);
      } else {
        longitude = CesiumMath.negativePiToPi(start.longitude - deltaLongitude);
      }
    }

    if (defined(result)) {
      result.longitude = longitude;
      result.latitude = latitude;
      result.height = 0;

      return result;
    }

    return new Cartographic(longitude, latitude, 0);
  }

  /**
   * Initializes a rhumb line on the ellipsoid connecting the two provided planetodetic points.
   *
   * @alias EllipsoidRhumbLine
   * @constructor
   *
   * @param {Cartographic} [start] The initial planetodetic point on the path.
   * @param {Cartographic} [end] The final planetodetic point on the path.
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the rhumb line lies.
   *
   * @exception {DeveloperError} angle between start and end must be at least 0.0125 radians.
   */
  function EllipsoidRhumbLine(start, end, ellipsoid) {
    const e = defaultValue(ellipsoid, Ellipsoid.WGS84);
    this._ellipsoid = e;
    this._start = new Cartographic();
    this._end = new Cartographic();

    this._heading = undefined;
    this._distance = undefined;
    this._ellipticity = undefined;
    this._ellipticitySquared = undefined;

    if (defined(start) && defined(end)) {
      computeProperties$1(this, start, end, e);
    }
  }

  Object.defineProperties(EllipsoidRhumbLine.prototype, {
    /**
     * Gets the ellipsoid.
     * @memberof EllipsoidRhumbLine.prototype
     * @type {Ellipsoid}
     * @readonly
     */
    ellipsoid: {
      get: function () {
        return this._ellipsoid;
      },
    },

    /**
     * Gets the surface distance between the start and end point
     * @memberof EllipsoidRhumbLine.prototype
     * @type {Number}
     * @readonly
     */
    surfaceDistance: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        Check.defined("distance", this._distance);
        //>>includeEnd('debug');

        return this._distance;
      },
    },

    /**
     * Gets the initial planetodetic point on the path.
     * @memberof EllipsoidRhumbLine.prototype
     * @type {Cartographic}
     * @readonly
     */
    start: {
      get: function () {
        return this._start;
      },
    },

    /**
     * Gets the final planetodetic point on the path.
     * @memberof EllipsoidRhumbLine.prototype
     * @type {Cartographic}
     * @readonly
     */
    end: {
      get: function () {
        return this._end;
      },
    },

    /**
     * Gets the heading from the start point to the end point.
     * @memberof EllipsoidRhumbLine.prototype
     * @type {Number}
     * @readonly
     */
    heading: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        Check.defined("distance", this._distance);
        //>>includeEnd('debug');

        return this._heading;
      },
    },
  });

  /**
   * Create a rhumb line using an initial position with a heading and distance.
   *
   * @param {Cartographic} start The initial planetodetic point on the path.
   * @param {Number} heading The heading in radians.
   * @param {Number} distance The rhumb line distance between the start and end point.
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the rhumb line lies.
   * @param {EllipsoidRhumbLine} [result] The object in which to store the result.
   * @returns {EllipsoidRhumbLine} The EllipsoidRhumbLine object.
   */
  EllipsoidRhumbLine.fromStartHeadingDistance = function (
    start,
    heading,
    distance,
    ellipsoid,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("start", start);
    Check.defined("heading", heading);
    Check.defined("distance", distance);
    Check.typeOf.number.greaterThan("distance", distance, 0.0);
    //>>includeEnd('debug');

    const e = defaultValue(ellipsoid, Ellipsoid.WGS84);
    const major = e.maximumRadius;
    const minor = e.minimumRadius;
    const majorSquared = major * major;
    const minorSquared = minor * minor;
    const ellipticity = Math.sqrt((majorSquared - minorSquared) / majorSquared);

    heading = CesiumMath.negativePiToPi(heading);
    const end = interpolateUsingSurfaceDistance(
      start,
      heading,
      distance,
      e.maximumRadius,
      ellipticity
    );

    if (
      !defined(result) ||
      (defined(ellipsoid) && !ellipsoid.equals(result.ellipsoid))
    ) {
      return new EllipsoidRhumbLine(start, end, e);
    }

    result.setEndPoints(start, end);
    return result;
  };

  /**
   * Sets the start and end points of the rhumb line.
   *
   * @param {Cartographic} start The initial planetodetic point on the path.
   * @param {Cartographic} end The final planetodetic point on the path.
   */
  EllipsoidRhumbLine.prototype.setEndPoints = function (start, end) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("start", start);
    Check.defined("end", end);
    //>>includeEnd('debug');

    computeProperties$1(this, start, end, this._ellipsoid);
  };

  /**
   * Provides the location of a point at the indicated portion along the rhumb line.
   *
   * @param {Number} fraction The portion of the distance between the initial and final points.
   * @param {Cartographic} [result] The object in which to store the result.
   * @returns {Cartographic} The location of the point along the rhumb line.
   */
  EllipsoidRhumbLine.prototype.interpolateUsingFraction = function (
    fraction,
    result
  ) {
    return this.interpolateUsingSurfaceDistance(
      fraction * this._distance,
      result
    );
  };

  /**
   * Provides the location of a point at the indicated distance along the rhumb line.
   *
   * @param {Number} distance The distance from the inital point to the point of interest along the rhumbLine.
   * @param {Cartographic} [result] The object in which to store the result.
   * @returns {Cartographic} The location of the point along the rhumb line.
   *
   * @exception {DeveloperError} start and end must be set before calling function interpolateUsingSurfaceDistance
   */
  EllipsoidRhumbLine.prototype.interpolateUsingSurfaceDistance = function (
    distance,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("distance", distance);
    if (!defined(this._distance) || this._distance === 0.0) {
      throw new DeveloperError(
        "EllipsoidRhumbLine must have distinct start and end set."
      );
    }
    //>>includeEnd('debug');

    return interpolateUsingSurfaceDistance(
      this._start,
      this._heading,
      distance,
      this._ellipsoid.maximumRadius,
      this._ellipticity,
      result
    );
  };

  /**
   * Provides the location of a point at the indicated longitude along the rhumb line.
   * If the longitude is outside the range of start and end points, the first intersection with the longitude from the start point in the direction of the heading is returned. This follows the spiral property of a rhumb line.
   *
   * @param {Number} intersectionLongitude The longitude, in radians, at which to find the intersection point from the starting point using the heading.
   * @param {Cartographic} [result] The object in which to store the result.
   * @returns {Cartographic} The location of the intersection point along the rhumb line, undefined if there is no intersection or infinite intersections.
   *
   * @exception {DeveloperError} start and end must be set before calling function findIntersectionWithLongitude.
   */
  EllipsoidRhumbLine.prototype.findIntersectionWithLongitude = function (
    intersectionLongitude,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("intersectionLongitude", intersectionLongitude);
    if (!defined(this._distance) || this._distance === 0.0) {
      throw new DeveloperError(
        "EllipsoidRhumbLine must have distinct start and end set."
      );
    }
    //>>includeEnd('debug');

    const ellipticity = this._ellipticity;
    const heading = this._heading;
    const absHeading = Math.abs(heading);
    const start = this._start;

    intersectionLongitude = CesiumMath.negativePiToPi(intersectionLongitude);

    if (
      CesiumMath.equalsEpsilon(
        Math.abs(intersectionLongitude),
        Math.PI,
        CesiumMath.EPSILON14
      )
    ) {
      intersectionLongitude = CesiumMath.sign(start.longitude) * Math.PI;
    }

    if (!defined(result)) {
      result = new Cartographic();
    }

    // If heading is -PI/2 or PI/2, this is an E-W rhumb line
    // If heading is 0 or PI, this is an N-S rhumb line
    if (Math.abs(CesiumMath.PI_OVER_TWO - absHeading) <= CesiumMath.EPSILON8) {
      result.longitude = intersectionLongitude;
      result.latitude = start.latitude;
      result.height = 0;
      return result;
    } else if (
      CesiumMath.equalsEpsilon(
        Math.abs(CesiumMath.PI_OVER_TWO - absHeading),
        CesiumMath.PI_OVER_TWO,
        CesiumMath.EPSILON8
      )
    ) {
      if (
        CesiumMath.equalsEpsilon(
          intersectionLongitude,
          start.longitude,
          CesiumMath.EPSILON12
        )
      ) {
        return undefined;
      }

      result.longitude = intersectionLongitude;
      result.latitude =
        CesiumMath.PI_OVER_TWO *
        CesiumMath.sign(CesiumMath.PI_OVER_TWO - heading);
      result.height = 0;
      return result;
    }

    // Use iterative solver from Equation 9 from http://edwilliams.org/ellipsoid/ellipsoid.pdf
    const phi1 = start.latitude;
    const eSinPhi1 = ellipticity * Math.sin(phi1);
    const leftComponent =
      Math.tan(0.5 * (CesiumMath.PI_OVER_TWO + phi1)) *
      Math.exp((intersectionLongitude - start.longitude) / Math.tan(heading));
    const denominator = (1 + eSinPhi1) / (1 - eSinPhi1);

    let newPhi = start.latitude;
    let phi;
    do {
      phi = newPhi;
      const eSinPhi = ellipticity * Math.sin(phi);
      const numerator = (1 + eSinPhi) / (1 - eSinPhi);
      newPhi =
        2 *
          Math.atan(
            leftComponent * Math.pow(numerator / denominator, ellipticity / 2)
          ) -
        CesiumMath.PI_OVER_TWO;
    } while (!CesiumMath.equalsEpsilon(newPhi, phi, CesiumMath.EPSILON12));

    result.longitude = intersectionLongitude;
    result.latitude = newPhi;
    result.height = 0;
    return result;
  };

  /**
   * Provides the location of a point at the indicated latitude along the rhumb line.
   * If the latitude is outside the range of start and end points, the first intersection with the latitude from that start point in the direction of the heading is returned. This follows the spiral property of a rhumb line.
   *
   * @param {Number} intersectionLatitude The latitude, in radians, at which to find the intersection point from the starting point using the heading.
   * @param {Cartographic} [result] The object in which to store the result.
   * @returns {Cartographic} The location of the intersection point along the rhumb line, undefined if there is no intersection or infinite intersections.
   *
   * @exception {DeveloperError} start and end must be set before calling function findIntersectionWithLongitude.
   */
  EllipsoidRhumbLine.prototype.findIntersectionWithLatitude = function (
    intersectionLatitude,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("intersectionLatitude", intersectionLatitude);
    if (!defined(this._distance) || this._distance === 0.0) {
      throw new DeveloperError(
        "EllipsoidRhumbLine must have distinct start and end set."
      );
    }
    //>>includeEnd('debug');

    const ellipticity = this._ellipticity;
    const heading = this._heading;
    const start = this._start;

    // If start and end have same latitude, return undefined since it's either no intersection or infinite intersections
    if (
      CesiumMath.equalsEpsilon(
        Math.abs(heading),
        CesiumMath.PI_OVER_TWO,
        CesiumMath.EPSILON8
      )
    ) {
      return;
    }

    // Can be solved using the same equations from interpolateUsingSurfaceDistance
    const sigma1 = calculateSigma(ellipticity, start.latitude);
    const sigma2 = calculateSigma(ellipticity, intersectionLatitude);
    const deltaLongitude = Math.tan(heading) * (sigma2 - sigma1);
    const longitude = CesiumMath.negativePiToPi(start.longitude + deltaLongitude);

    if (defined(result)) {
      result.longitude = longitude;
      result.latitude = intersectionLatitude;
      result.height = 0;

      return result;
    }

    return new Cartographic(longitude, intersectionLatitude, 0);
  };

  /* This file is automatically rebuilt by the Cesium build process. */
  var earcut_1 = earcut;
  var _default = earcut;

  function earcut(data, holeIndices, dim) {

      dim = dim || 2;

      var hasHoles = holeIndices && holeIndices.length,
          outerLen = hasHoles ? holeIndices[0] * dim : data.length,
          outerNode = linkedList(data, 0, outerLen, dim, true),
          triangles = [];

      if (!outerNode || outerNode.next === outerNode.prev) return triangles;

      var minX, minY, maxX, maxY, x, y, invSize;

      if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);

      // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
      if (data.length > 80 * dim) {
          minX = maxX = data[0];
          minY = maxY = data[1];

          for (var i = dim; i < outerLen; i += dim) {
              x = data[i];
              y = data[i + 1];
              if (x < minX) minX = x;
              if (y < minY) minY = y;
              if (x > maxX) maxX = x;
              if (y > maxY) maxY = y;
          }

          // minX, minY and invSize are later used to transform coords into integers for z-order calculation
          invSize = Math.max(maxX - minX, maxY - minY);
          invSize = invSize !== 0 ? 1 / invSize : 0;
      }

      earcutLinked(outerNode, triangles, dim, minX, minY, invSize);

      return triangles;
  }

  // create a circular doubly linked list from polygon points in the specified winding order
  function linkedList(data, start, end, dim, clockwise) {
      var i, last;

      if (clockwise === (signedArea(data, start, end, dim) > 0)) {
          for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
      } else {
          for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
      }

      if (last && equals(last, last.next)) {
          removeNode(last);
          last = last.next;
      }

      return last;
  }

  // eliminate colinear or duplicate points
  function filterPoints(start, end) {
      if (!start) return start;
      if (!end) end = start;

      var p = start,
          again;
      do {
          again = false;

          if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
              removeNode(p);
              p = end = p.prev;
              if (p === p.next) break;
              again = true;

          } else {
              p = p.next;
          }
      } while (again || p !== end);

      return end;
  }

  // main ear slicing loop which triangulates a polygon (given as a linked list)
  function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
      if (!ear) return;

      // interlink polygon nodes in z-order
      if (!pass && invSize) indexCurve(ear, minX, minY, invSize);

      var stop = ear,
          prev, next;

      // iterate through ears, slicing them one by one
      while (ear.prev !== ear.next) {
          prev = ear.prev;
          next = ear.next;

          if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
              // cut off the triangle
              triangles.push(prev.i / dim);
              triangles.push(ear.i / dim);
              triangles.push(next.i / dim);

              removeNode(ear);

              // skipping the next vertex leads to less sliver triangles
              ear = next.next;
              stop = next.next;

              continue;
          }

          ear = next;

          // if we looped through the whole remaining polygon and can't find any more ears
          if (ear === stop) {
              // try filtering points and slicing again
              if (!pass) {
                  earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);

              // if this didn't work, try curing all small self-intersections locally
              } else if (pass === 1) {
                  ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
                  earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);

              // as a last resort, try splitting the remaining polygon into two
              } else if (pass === 2) {
                  splitEarcut(ear, triangles, dim, minX, minY, invSize);
              }

              break;
          }
      }
  }

  // check whether a polygon node forms a valid ear with adjacent nodes
  function isEar(ear) {
      var a = ear.prev,
          b = ear,
          c = ear.next;

      if (area(a, b, c) >= 0) return false; // reflex, can't be an ear

      // now make sure we don't have other points inside the potential ear
      var p = ear.next.next;

      while (p !== ear.prev) {
          if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
              area(p.prev, p, p.next) >= 0) return false;
          p = p.next;
      }

      return true;
  }

  function isEarHashed(ear, minX, minY, invSize) {
      var a = ear.prev,
          b = ear,
          c = ear.next;

      if (area(a, b, c) >= 0) return false; // reflex, can't be an ear

      // triangle bbox; min & max are calculated like this for speed
      var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x),
          minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y),
          maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x),
          maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);

      // z-order range for the current triangle bbox;
      var minZ = zOrder(minTX, minTY, minX, minY, invSize),
          maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);

      var p = ear.prevZ,
          n = ear.nextZ;

      // look for points inside the triangle in both directions
      while (p && p.z >= minZ && n && n.z <= maxZ) {
          if (p !== ear.prev && p !== ear.next &&
              pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
              area(p.prev, p, p.next) >= 0) return false;
          p = p.prevZ;

          if (n !== ear.prev && n !== ear.next &&
              pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) &&
              area(n.prev, n, n.next) >= 0) return false;
          n = n.nextZ;
      }

      // look for remaining points in decreasing z-order
      while (p && p.z >= minZ) {
          if (p !== ear.prev && p !== ear.next &&
              pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
              area(p.prev, p, p.next) >= 0) return false;
          p = p.prevZ;
      }

      // look for remaining points in increasing z-order
      while (n && n.z <= maxZ) {
          if (n !== ear.prev && n !== ear.next &&
              pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) &&
              area(n.prev, n, n.next) >= 0) return false;
          n = n.nextZ;
      }

      return true;
  }

  // go through all polygon nodes and cure small local self-intersections
  function cureLocalIntersections(start, triangles, dim) {
      var p = start;
      do {
          var a = p.prev,
              b = p.next.next;

          if (!equals(a, b) && intersects$1(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {

              triangles.push(a.i / dim);
              triangles.push(p.i / dim);
              triangles.push(b.i / dim);

              // remove two nodes involved
              removeNode(p);
              removeNode(p.next);

              p = start = b;
          }
          p = p.next;
      } while (p !== start);

      return filterPoints(p);
  }

  // try splitting polygon into two and triangulate them independently
  function splitEarcut(start, triangles, dim, minX, minY, invSize) {
      // look for a valid diagonal that divides the polygon into two
      var a = start;
      do {
          var b = a.next.next;
          while (b !== a.prev) {
              if (a.i !== b.i && isValidDiagonal(a, b)) {
                  // split the polygon in two by the diagonal
                  var c = splitPolygon(a, b);

                  // filter colinear points around the cuts
                  a = filterPoints(a, a.next);
                  c = filterPoints(c, c.next);

                  // run earcut on each half
                  earcutLinked(a, triangles, dim, minX, minY, invSize);
                  earcutLinked(c, triangles, dim, minX, minY, invSize);
                  return;
              }
              b = b.next;
          }
          a = a.next;
      } while (a !== start);
  }

  // link every hole into the outer loop, producing a single-ring polygon without holes
  function eliminateHoles(data, holeIndices, outerNode, dim) {
      var queue = [],
          i, len, start, end, list;

      for (i = 0, len = holeIndices.length; i < len; i++) {
          start = holeIndices[i] * dim;
          end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
          list = linkedList(data, start, end, dim, false);
          if (list === list.next) list.steiner = true;
          queue.push(getLeftmost(list));
      }

      queue.sort(compareX);

      // process holes from left to right
      for (i = 0; i < queue.length; i++) {
          outerNode = eliminateHole(queue[i], outerNode);
          outerNode = filterPoints(outerNode, outerNode.next);
      }

      return outerNode;
  }

  function compareX(a, b) {
      return a.x - b.x;
  }

  // find a bridge between vertices that connects hole with an outer ring and and link it
  function eliminateHole(hole, outerNode) {
      var bridge = findHoleBridge(hole, outerNode);
      if (!bridge) {
          return outerNode;
      }

      var bridgeReverse = splitPolygon(bridge, hole);

      // filter collinear points around the cuts
      var filteredBridge = filterPoints(bridge, bridge.next);
      filterPoints(bridgeReverse, bridgeReverse.next);

      // Check if input node was removed by the filtering
      return outerNode === bridge ? filteredBridge : outerNode;
  }

  // David Eberly's algorithm for finding a bridge between hole and outer polygon
  function findHoleBridge(hole, outerNode) {
      var p = outerNode,
          hx = hole.x,
          hy = hole.y,
          qx = -Infinity,
          m;

      // find a segment intersected by a ray from the hole's leftmost point to the left;
      // segment's endpoint with lesser x will be potential connection point
      do {
          if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
              var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
              if (x <= hx && x > qx) {
                  qx = x;
                  if (x === hx) {
                      if (hy === p.y) return p;
                      if (hy === p.next.y) return p.next;
                  }
                  m = p.x < p.next.x ? p : p.next;
              }
          }
          p = p.next;
      } while (p !== outerNode);

      if (!m) return null;

      if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint

      // look for points inside the triangle of hole point, segment intersection and endpoint;
      // if there are no points found, we have a valid connection;
      // otherwise choose the point of the minimum angle with the ray as connection point

      var stop = m,
          mx = m.x,
          my = m.y,
          tanMin = Infinity,
          tan;

      p = m;

      do {
          if (hx >= p.x && p.x >= mx && hx !== p.x &&
                  pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {

              tan = Math.abs(hy - p.y) / (hx - p.x); // tangential

              if (locallyInside(p, hole) &&
                  (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {
                  m = p;
                  tanMin = tan;
              }
          }

          p = p.next;
      } while (p !== stop);

      return m;
  }

  // whether sector in vertex m contains sector in vertex p in the same coordinates
  function sectorContainsSector(m, p) {
      return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  }

  // interlink polygon nodes in z-order
  function indexCurve(start, minX, minY, invSize) {
      var p = start;
      do {
          if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
          p.prevZ = p.prev;
          p.nextZ = p.next;
          p = p.next;
      } while (p !== start);

      p.prevZ.nextZ = null;
      p.prevZ = null;

      sortLinked(p);
  }

  // Simon Tatham's linked list merge sort algorithm
  // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  function sortLinked(list) {
      var i, p, q, e, tail, numMerges, pSize, qSize,
          inSize = 1;

      do {
          p = list;
          list = null;
          tail = null;
          numMerges = 0;

          while (p) {
              numMerges++;
              q = p;
              pSize = 0;
              for (i = 0; i < inSize; i++) {
                  pSize++;
                  q = q.nextZ;
                  if (!q) break;
              }
              qSize = inSize;

              while (pSize > 0 || (qSize > 0 && q)) {

                  if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
                      e = p;
                      p = p.nextZ;
                      pSize--;
                  } else {
                      e = q;
                      q = q.nextZ;
                      qSize--;
                  }

                  if (tail) tail.nextZ = e;
                  else list = e;

                  e.prevZ = tail;
                  tail = e;
              }

              p = q;
          }

          tail.nextZ = null;
          inSize *= 2;

      } while (numMerges > 1);

      return list;
  }

  // z-order of a point given coords and inverse of the longer side of data bbox
  function zOrder(x, y, minX, minY, invSize) {
      // coords are transformed into non-negative 15-bit integer range
      x = 32767 * (x - minX) * invSize;
      y = 32767 * (y - minY) * invSize;

      x = (x | (x << 8)) & 0x00FF00FF;
      x = (x | (x << 4)) & 0x0F0F0F0F;
      x = (x | (x << 2)) & 0x33333333;
      x = (x | (x << 1)) & 0x55555555;

      y = (y | (y << 8)) & 0x00FF00FF;
      y = (y | (y << 4)) & 0x0F0F0F0F;
      y = (y | (y << 2)) & 0x33333333;
      y = (y | (y << 1)) & 0x55555555;

      return x | (y << 1);
  }

  // find the leftmost node of a polygon ring
  function getLeftmost(start) {
      var p = start,
          leftmost = start;
      do {
          if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;
          p = p.next;
      } while (p !== start);

      return leftmost;
  }

  // check if a point lies within a convex triangle
  function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
      return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
             (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
             (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  }

  // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  function isValidDiagonal(a, b) {
      return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges
             (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
              (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
              equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  }

  // signed area of a triangle
  function area(p, q, r) {
      return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  }

  // check if two points are equal
  function equals(p1, p2) {
      return p1.x === p2.x && p1.y === p2.y;
  }

  // check if two segments intersect
  function intersects$1(p1, q1, p2, q2) {
      var o1 = sign(area(p1, q1, p2));
      var o2 = sign(area(p1, q1, q2));
      var o3 = sign(area(p2, q2, p1));
      var o4 = sign(area(p2, q2, q1));

      if (o1 !== o2 && o3 !== o4) return true; // general case

      if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
      if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
      if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
      if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2

      return false;
  }

  // for collinear points p, q, r, check if point q lies on segment pr
  function onSegment(p, q, r) {
      return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);
  }

  function sign(num) {
      return num > 0 ? 1 : num < 0 ? -1 : 0;
  }

  // check if a polygon diagonal intersects any polygon segments
  function intersectsPolygon(a, b) {
      var p = a;
      do {
          if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
                  intersects$1(p, p.next, a, b)) return true;
          p = p.next;
      } while (p !== a);

      return false;
  }

  // check if a polygon diagonal is locally inside the polygon
  function locallyInside(a, b) {
      return area(a.prev, a, a.next) < 0 ?
          area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
          area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  }

  // check if the middle point of a polygon diagonal is inside the polygon
  function middleInside(a, b) {
      var p = a,
          inside = false,
          px = (a.x + b.x) / 2,
          py = (a.y + b.y) / 2;
      do {
          if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
                  (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
              inside = !inside;
          p = p.next;
      } while (p !== a);

      return inside;
  }

  // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  function splitPolygon(a, b) {
      var a2 = new Node$5(a.i, a.x, a.y),
          b2 = new Node$5(b.i, b.x, b.y),
          an = a.next,
          bp = b.prev;

      a.next = b;
      b.prev = a;

      a2.next = an;
      an.prev = a2;

      b2.next = a2;
      a2.prev = b2;

      bp.next = b2;
      b2.prev = bp;

      return b2;
  }

  // create a node and optionally link it with previous one (in a circular doubly linked list)
  function insertNode(i, x, y, last) {
      var p = new Node$5(i, x, y);

      if (!last) {
          p.prev = p;
          p.next = p;

      } else {
          p.next = last.next;
          p.prev = last;
          last.next.prev = p;
          last.next = p;
      }
      return p;
  }

  function removeNode(p) {
      p.next.prev = p.prev;
      p.prev.next = p.next;

      if (p.prevZ) p.prevZ.nextZ = p.nextZ;
      if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  }

  function Node$5(i, x, y) {
      // vertex index in coordinates array
      this.i = i;

      // vertex coordinates
      this.x = x;
      this.y = y;

      // previous and next vertex nodes in a polygon ring
      this.prev = null;
      this.next = null;

      // z-order curve value
      this.z = null;

      // previous and next nodes in z-order
      this.prevZ = null;
      this.nextZ = null;

      // indicates whether this is a steiner point
      this.steiner = false;
  }

  // return a percentage difference between the polygon area and its triangulation area;
  // used to verify correctness of triangulation
  earcut.deviation = function (data, holeIndices, dim, triangles) {
      var hasHoles = holeIndices && holeIndices.length;
      var outerLen = hasHoles ? holeIndices[0] * dim : data.length;

      var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
      if (hasHoles) {
          for (var i = 0, len = holeIndices.length; i < len; i++) {
              var start = holeIndices[i] * dim;
              var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
              polygonArea -= Math.abs(signedArea(data, start, end, dim));
          }
      }

      var trianglesArea = 0;
      for (i = 0; i < triangles.length; i += 3) {
          var a = triangles[i] * dim;
          var b = triangles[i + 1] * dim;
          var c = triangles[i + 2] * dim;
          trianglesArea += Math.abs(
              (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
              (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
      }

      return polygonArea === 0 && trianglesArea === 0 ? 0 :
          Math.abs((trianglesArea - polygonArea) / polygonArea);
  };

  function signedArea(data, start, end, dim) {
      var sum = 0;
      for (var i = start, j = end - dim; i < end; i += dim) {
          sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
          j = i;
      }
      return sum;
  }

  // turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  earcut.flatten = function (data) {
      var dim = data[0][0].length,
          result = {vertices: [], holes: [], dimensions: dim},
          holeIndex = 0;

      for (var i = 0; i < data.length; i++) {
          for (var j = 0; j < data[i].length; j++) {
              for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);
          }
          if (i > 0) {
              holeIndex += data[i - 1].length;
              result.holes.push(holeIndex);
          }
      }
      return result;
  };
  earcut_1.default = _default;

  /**
   * Winding order defines the order of vertices for a triangle to be considered front-facing.
   *
   * @enum {Number}
   */
  const WindingOrder = {
    /**
     * Vertices are in clockwise order.
     *
     * @type {Number}
     * @constant
     */
    CLOCKWISE: WebGLConstants$1.CW,

    /**
     * Vertices are in counter-clockwise order.
     *
     * @type {Number}
     * @constant
     */
    COUNTER_CLOCKWISE: WebGLConstants$1.CCW,
  };

  /**
   * @private
   */
  WindingOrder.validate = function (windingOrder) {
    return (
      windingOrder === WindingOrder.CLOCKWISE ||
      windingOrder === WindingOrder.COUNTER_CLOCKWISE
    );
  };

  var WindingOrder$1 = Object.freeze(WindingOrder);

  const scaleToGeodeticHeightN = new Cartesian3();
  const scaleToGeodeticHeightP = new Cartesian3();

  /**
   * @private
   */
  const PolygonPipeline = {};

  /**
   * @exception {DeveloperError} At least three positions are required.
   */
  PolygonPipeline.computeArea2D = function (positions) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("positions", positions);
    Check.typeOf.number.greaterThanOrEquals(
      "positions.length",
      positions.length,
      3
    );
    //>>includeEnd('debug');

    const length = positions.length;
    let area = 0.0;

    for (let i0 = length - 1, i1 = 0; i1 < length; i0 = i1++) {
      const v0 = positions[i0];
      const v1 = positions[i1];

      area += v0.x * v1.y - v1.x * v0.y;
    }

    return area * 0.5;
  };

  /**
   * @returns {WindingOrder} The winding order.
   *
   * @exception {DeveloperError} At least three positions are required.
   */
  PolygonPipeline.computeWindingOrder2D = function (positions) {
    const area = PolygonPipeline.computeArea2D(positions);
    return area > 0.0 ? WindingOrder$1.COUNTER_CLOCKWISE : WindingOrder$1.CLOCKWISE;
  };

  /**
   * Triangulate a polygon.
   *
   * @param {Cartesian2[]} positions Cartesian2 array containing the vertices of the polygon
   * @param {Number[]} [holes] An array of the staring indices of the holes.
   * @returns {Number[]} Index array representing triangles that fill the polygon
   */
  PolygonPipeline.triangulate = function (positions, holes) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("positions", positions);
    //>>includeEnd('debug');

    const flattenedPositions = Cartesian2.packArray(positions);
    return earcut_1(flattenedPositions, holes, 2);
  };

  const subdivisionV0Scratch = new Cartesian3();
  const subdivisionV1Scratch = new Cartesian3();
  const subdivisionV2Scratch = new Cartesian3();
  const subdivisionS0Scratch = new Cartesian3();
  const subdivisionS1Scratch = new Cartesian3();
  const subdivisionS2Scratch = new Cartesian3();
  const subdivisionMidScratch = new Cartesian3();
  const subdivisionT0Scratch = new Cartesian2();
  const subdivisionT1Scratch = new Cartesian2();
  const subdivisionT2Scratch = new Cartesian2();
  const subdivisionTexcoordMidScratch = new Cartesian2();

  /**
   * Subdivides positions and raises points to the surface of the ellipsoid.
   *
   * @param {Ellipsoid} ellipsoid The ellipsoid the polygon in on.
   * @param {Cartesian3[]} positions An array of {@link Cartesian3} positions of the polygon.
   * @param {Number[]} indices An array of indices that determines the triangles in the polygon.
   * @param {Cartesian2[]} texcoords An optional array of {@link Cartesian2} texture coordinates of the polygon.
   * @param {Number} [granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
   *
   * @exception {DeveloperError} At least three indices are required.
   * @exception {DeveloperError} The number of indices must be divisable by three.
   * @exception {DeveloperError} Granularity must be greater than zero.
   */
  PolygonPipeline.computeSubdivision = function (
    ellipsoid,
    positions,
    indices,
    texcoords,
    granularity
  ) {
    granularity = defaultValue(granularity, CesiumMath.RADIANS_PER_DEGREE);

    const hasTexcoords = defined(texcoords);

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("ellipsoid", ellipsoid);
    Check.defined("positions", positions);
    Check.defined("indices", indices);
    Check.typeOf.number.greaterThanOrEquals("indices.length", indices.length, 3);
    Check.typeOf.number.equals("indices.length % 3", "0", indices.length % 3, 0);
    Check.typeOf.number.greaterThan("granularity", granularity, 0.0);
    //>>includeEnd('debug');

    // triangles that need (or might need) to be subdivided.
    const triangles = indices.slice(0);

    // New positions due to edge splits are appended to the positions list.
    let i;
    const length = positions.length;
    const subdividedPositions = new Array(length * 3);
    const subdividedTexcoords = new Array(length * 2);
    let q = 0;
    let p = 0;
    for (i = 0; i < length; i++) {
      const item = positions[i];
      subdividedPositions[q++] = item.x;
      subdividedPositions[q++] = item.y;
      subdividedPositions[q++] = item.z;

      if (hasTexcoords) {
        const texcoordItem = texcoords[i];
        subdividedTexcoords[p++] = texcoordItem.x;
        subdividedTexcoords[p++] = texcoordItem.y;
      }
    }

    const subdividedIndices = [];

    // Used to make sure shared edges are not split more than once.
    const edges = {};

    const radius = ellipsoid.maximumRadius;
    const minDistance = CesiumMath.chordLength(granularity, radius);
    const minDistanceSqrd = minDistance * minDistance;

    while (triangles.length > 0) {
      const i2 = triangles.pop();
      const i1 = triangles.pop();
      const i0 = triangles.pop();

      const v0 = Cartesian3.fromArray(
        subdividedPositions,
        i0 * 3,
        subdivisionV0Scratch
      );
      const v1 = Cartesian3.fromArray(
        subdividedPositions,
        i1 * 3,
        subdivisionV1Scratch
      );
      const v2 = Cartesian3.fromArray(
        subdividedPositions,
        i2 * 3,
        subdivisionV2Scratch
      );

      let t0, t1, t2;
      if (hasTexcoords) {
        t0 = Cartesian2.fromArray(
          subdividedTexcoords,
          i0 * 2,
          subdivisionT0Scratch
        );
        t1 = Cartesian2.fromArray(
          subdividedTexcoords,
          i1 * 2,
          subdivisionT1Scratch
        );
        t2 = Cartesian2.fromArray(
          subdividedTexcoords,
          i2 * 2,
          subdivisionT2Scratch
        );
      }

      const s0 = Cartesian3.multiplyByScalar(
        Cartesian3.normalize(v0, subdivisionS0Scratch),
        radius,
        subdivisionS0Scratch
      );
      const s1 = Cartesian3.multiplyByScalar(
        Cartesian3.normalize(v1, subdivisionS1Scratch),
        radius,
        subdivisionS1Scratch
      );
      const s2 = Cartesian3.multiplyByScalar(
        Cartesian3.normalize(v2, subdivisionS2Scratch),
        radius,
        subdivisionS2Scratch
      );

      const g0 = Cartesian3.magnitudeSquared(
        Cartesian3.subtract(s0, s1, subdivisionMidScratch)
      );
      const g1 = Cartesian3.magnitudeSquared(
        Cartesian3.subtract(s1, s2, subdivisionMidScratch)
      );
      const g2 = Cartesian3.magnitudeSquared(
        Cartesian3.subtract(s2, s0, subdivisionMidScratch)
      );

      const max = Math.max(g0, g1, g2);
      let edge;
      let mid;
      let midTexcoord;

      // if the max length squared of a triangle edge is greater than the chord length of squared
      // of the granularity, subdivide the triangle
      if (max > minDistanceSqrd) {
        if (g0 === max) {
          edge = `${Math.min(i0, i1)} ${Math.max(i0, i1)}`;

          i = edges[edge];
          if (!defined(i)) {
            mid = Cartesian3.add(v0, v1, subdivisionMidScratch);
            Cartesian3.multiplyByScalar(mid, 0.5, mid);
            subdividedPositions.push(mid.x, mid.y, mid.z);
            i = subdividedPositions.length / 3 - 1;
            edges[edge] = i;

            if (hasTexcoords) {
              midTexcoord = Cartesian2.add(t0, t1, subdivisionTexcoordMidScratch);
              Cartesian2.multiplyByScalar(midTexcoord, 0.5, midTexcoord);
              subdividedTexcoords.push(midTexcoord.x, midTexcoord.y);
            }
          }

          triangles.push(i0, i, i2);
          triangles.push(i, i1, i2);
        } else if (g1 === max) {
          edge = `${Math.min(i1, i2)} ${Math.max(i1, i2)}`;

          i = edges[edge];
          if (!defined(i)) {
            mid = Cartesian3.add(v1, v2, subdivisionMidScratch);
            Cartesian3.multiplyByScalar(mid, 0.5, mid);
            subdividedPositions.push(mid.x, mid.y, mid.z);
            i = subdividedPositions.length / 3 - 1;
            edges[edge] = i;

            if (hasTexcoords) {
              midTexcoord = Cartesian2.add(t1, t2, subdivisionTexcoordMidScratch);
              Cartesian2.multiplyByScalar(midTexcoord, 0.5, midTexcoord);
              subdividedTexcoords.push(midTexcoord.x, midTexcoord.y);
            }
          }

          triangles.push(i1, i, i0);
          triangles.push(i, i2, i0);
        } else if (g2 === max) {
          edge = `${Math.min(i2, i0)} ${Math.max(i2, i0)}`;

          i = edges[edge];
          if (!defined(i)) {
            mid = Cartesian3.add(v2, v0, subdivisionMidScratch);
            Cartesian3.multiplyByScalar(mid, 0.5, mid);
            subdividedPositions.push(mid.x, mid.y, mid.z);
            i = subdividedPositions.length / 3 - 1;
            edges[edge] = i;

            if (hasTexcoords) {
              midTexcoord = Cartesian2.add(t2, t0, subdivisionTexcoordMidScratch);
              Cartesian2.multiplyByScalar(midTexcoord, 0.5, midTexcoord);
              subdividedTexcoords.push(midTexcoord.x, midTexcoord.y);
            }
          }

          triangles.push(i2, i, i1);
          triangles.push(i, i0, i1);
        }
      } else {
        subdividedIndices.push(i0);
        subdividedIndices.push(i1);
        subdividedIndices.push(i2);
      }
    }

    const geometryOptions = {
      attributes: {
        position: new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.DOUBLE,
          componentsPerAttribute: 3,
          values: subdividedPositions,
        }),
      },
      indices: subdividedIndices,
      primitiveType: PrimitiveType$1.TRIANGLES,
    };

    if (hasTexcoords) {
      geometryOptions.attributes.st = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 2,
        values: subdividedTexcoords,
      });
    }

    return new Geometry(geometryOptions);
  };

  const subdivisionC0Scratch = new Cartographic();
  const subdivisionC1Scratch = new Cartographic();
  const subdivisionC2Scratch = new Cartographic();
  const subdivisionCartographicScratch = new Cartographic();

  /**
   * Subdivides positions on rhumb lines and raises points to the surface of the ellipsoid.
   *
   * @param {Ellipsoid} ellipsoid The ellipsoid the polygon in on.
   * @param {Cartesian3[]} positions An array of {@link Cartesian3} positions of the polygon.
   * @param {Number[]} indices An array of indices that determines the triangles in the polygon.
   * @param {Cartesian2[]} texcoords An optional array of {@link Cartesian2} texture coordinates of the polygon.
   * @param {Number} [granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
   *
   * @exception {DeveloperError} At least three indices are required.
   * @exception {DeveloperError} The number of indices must be divisable by three.
   * @exception {DeveloperError} Granularity must be greater than zero.
   */
  PolygonPipeline.computeRhumbLineSubdivision = function (
    ellipsoid,
    positions,
    indices,
    texcoords,
    granularity
  ) {
    granularity = defaultValue(granularity, CesiumMath.RADIANS_PER_DEGREE);

    const hasTexcoords = defined(texcoords);

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("ellipsoid", ellipsoid);
    Check.defined("positions", positions);
    Check.defined("indices", indices);
    Check.typeOf.number.greaterThanOrEquals("indices.length", indices.length, 3);
    Check.typeOf.number.equals("indices.length % 3", "0", indices.length % 3, 0);
    Check.typeOf.number.greaterThan("granularity", granularity, 0.0);
    //>>includeEnd('debug');

    // triangles that need (or might need) to be subdivided.
    const triangles = indices.slice(0);

    // New positions due to edge splits are appended to the positions list.
    let i;
    const length = positions.length;
    const subdividedPositions = new Array(length * 3);
    const subdividedTexcoords = new Array(length * 2);
    let q = 0;
    let p = 0;
    for (i = 0; i < length; i++) {
      const item = positions[i];
      subdividedPositions[q++] = item.x;
      subdividedPositions[q++] = item.y;
      subdividedPositions[q++] = item.z;

      if (hasTexcoords) {
        const texcoordItem = texcoords[i];
        subdividedTexcoords[p++] = texcoordItem.x;
        subdividedTexcoords[p++] = texcoordItem.y;
      }
    }

    const subdividedIndices = [];

    // Used to make sure shared edges are not split more than once.
    const edges = {};

    const radius = ellipsoid.maximumRadius;
    const minDistance = CesiumMath.chordLength(granularity, radius);

    const rhumb0 = new EllipsoidRhumbLine(undefined, undefined, ellipsoid);
    const rhumb1 = new EllipsoidRhumbLine(undefined, undefined, ellipsoid);
    const rhumb2 = new EllipsoidRhumbLine(undefined, undefined, ellipsoid);

    while (triangles.length > 0) {
      const i2 = triangles.pop();
      const i1 = triangles.pop();
      const i0 = triangles.pop();

      const v0 = Cartesian3.fromArray(
        subdividedPositions,
        i0 * 3,
        subdivisionV0Scratch
      );
      const v1 = Cartesian3.fromArray(
        subdividedPositions,
        i1 * 3,
        subdivisionV1Scratch
      );
      const v2 = Cartesian3.fromArray(
        subdividedPositions,
        i2 * 3,
        subdivisionV2Scratch
      );

      let t0, t1, t2;
      if (hasTexcoords) {
        t0 = Cartesian2.fromArray(
          subdividedTexcoords,
          i0 * 2,
          subdivisionT0Scratch
        );
        t1 = Cartesian2.fromArray(
          subdividedTexcoords,
          i1 * 2,
          subdivisionT1Scratch
        );
        t2 = Cartesian2.fromArray(
          subdividedTexcoords,
          i2 * 2,
          subdivisionT2Scratch
        );
      }

      const c0 = ellipsoid.cartesianToCartographic(v0, subdivisionC0Scratch);
      const c1 = ellipsoid.cartesianToCartographic(v1, subdivisionC1Scratch);
      const c2 = ellipsoid.cartesianToCartographic(v2, subdivisionC2Scratch);

      rhumb0.setEndPoints(c0, c1);
      const g0 = rhumb0.surfaceDistance;
      rhumb1.setEndPoints(c1, c2);
      const g1 = rhumb1.surfaceDistance;
      rhumb2.setEndPoints(c2, c0);
      const g2 = rhumb2.surfaceDistance;

      const max = Math.max(g0, g1, g2);
      let edge;
      let mid;
      let midHeight;
      let midCartesian3;
      let midTexcoord;

      // if the max length squared of a triangle edge is greater than granularity, subdivide the triangle
      if (max > minDistance) {
        if (g0 === max) {
          edge = `${Math.min(i0, i1)} ${Math.max(i0, i1)}`;

          i = edges[edge];
          if (!defined(i)) {
            mid = rhumb0.interpolateUsingFraction(
              0.5,
              subdivisionCartographicScratch
            );
            midHeight = (c0.height + c1.height) * 0.5;
            midCartesian3 = Cartesian3.fromRadians(
              mid.longitude,
              mid.latitude,
              midHeight,
              ellipsoid,
              subdivisionMidScratch
            );
            subdividedPositions.push(
              midCartesian3.x,
              midCartesian3.y,
              midCartesian3.z
            );
            i = subdividedPositions.length / 3 - 1;
            edges[edge] = i;

            if (hasTexcoords) {
              midTexcoord = Cartesian2.add(t0, t1, subdivisionTexcoordMidScratch);
              Cartesian2.multiplyByScalar(midTexcoord, 0.5, midTexcoord);
              subdividedTexcoords.push(midTexcoord.x, midTexcoord.y);
            }
          }

          triangles.push(i0, i, i2);
          triangles.push(i, i1, i2);
        } else if (g1 === max) {
          edge = `${Math.min(i1, i2)} ${Math.max(i1, i2)}`;

          i = edges[edge];
          if (!defined(i)) {
            mid = rhumb1.interpolateUsingFraction(
              0.5,
              subdivisionCartographicScratch
            );
            midHeight = (c1.height + c2.height) * 0.5;
            midCartesian3 = Cartesian3.fromRadians(
              mid.longitude,
              mid.latitude,
              midHeight,
              ellipsoid,
              subdivisionMidScratch
            );
            subdividedPositions.push(
              midCartesian3.x,
              midCartesian3.y,
              midCartesian3.z
            );
            i = subdividedPositions.length / 3 - 1;
            edges[edge] = i;

            if (hasTexcoords) {
              midTexcoord = Cartesian2.add(t1, t2, subdivisionTexcoordMidScratch);
              Cartesian2.multiplyByScalar(midTexcoord, 0.5, midTexcoord);
              subdividedTexcoords.push(midTexcoord.x, midTexcoord.y);
            }
          }

          triangles.push(i1, i, i0);
          triangles.push(i, i2, i0);
        } else if (g2 === max) {
          edge = `${Math.min(i2, i0)} ${Math.max(i2, i0)}`;

          i = edges[edge];
          if (!defined(i)) {
            mid = rhumb2.interpolateUsingFraction(
              0.5,
              subdivisionCartographicScratch
            );
            midHeight = (c2.height + c0.height) * 0.5;
            midCartesian3 = Cartesian3.fromRadians(
              mid.longitude,
              mid.latitude,
              midHeight,
              ellipsoid,
              subdivisionMidScratch
            );
            subdividedPositions.push(
              midCartesian3.x,
              midCartesian3.y,
              midCartesian3.z
            );
            i = subdividedPositions.length / 3 - 1;
            edges[edge] = i;

            if (hasTexcoords) {
              midTexcoord = Cartesian2.add(t2, t0, subdivisionTexcoordMidScratch);
              Cartesian2.multiplyByScalar(midTexcoord, 0.5, midTexcoord);
              subdividedTexcoords.push(midTexcoord.x, midTexcoord.y);
            }
          }

          triangles.push(i2, i, i1);
          triangles.push(i, i0, i1);
        }
      } else {
        subdividedIndices.push(i0);
        subdividedIndices.push(i1);
        subdividedIndices.push(i2);
      }
    }

    const geometryOptions = {
      attributes: {
        position: new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.DOUBLE,
          componentsPerAttribute: 3,
          values: subdividedPositions,
        }),
      },
      indices: subdividedIndices,
      primitiveType: PrimitiveType$1.TRIANGLES,
    };

    if (hasTexcoords) {
      geometryOptions.attributes.st = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 2,
        values: subdividedTexcoords,
      });
    }

    return new Geometry(geometryOptions);
  };

  /**
   * Scales each position of a geometry's position attribute to a height, in place.
   *
   * @param {Number[]} positions The array of numbers representing the positions to be scaled
   * @param {Number} [height=0.0] The desired height to add to the positions
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the positions lie.
   * @param {Boolean} [scaleToSurface=true] <code>true</code> if the positions need to be scaled to the surface before the height is added.
   * @returns {Number[]} The input array of positions, scaled to height
   */
  PolygonPipeline.scaleToGeodeticHeight = function (
    positions,
    height,
    ellipsoid,
    scaleToSurface
  ) {
    ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);

    let n = scaleToGeodeticHeightN;
    let p = scaleToGeodeticHeightP;

    height = defaultValue(height, 0.0);
    scaleToSurface = defaultValue(scaleToSurface, true);

    if (defined(positions)) {
      const length = positions.length;

      for (let i = 0; i < length; i += 3) {
        Cartesian3.fromArray(positions, i, p);

        if (scaleToSurface) {
          p = ellipsoid.scaleToGeodeticSurface(p, p);
        }

        if (height !== 0) {
          n = ellipsoid.geodeticSurfaceNormal(p, n);

          Cartesian3.multiplyByScalar(n, height, n);
          Cartesian3.add(p, n, p);
        }

        positions[i] = p.x;
        positions[i + 1] = p.y;
        positions[i + 2] = p.z;
      }
    }

    return positions;
  };

  /**
   * A queue that can enqueue items at the end, and dequeue items from the front.
   *
   * @alias Queue
   * @constructor
   */
  function Queue() {
    this._array = [];
    this._offset = 0;
    this._length = 0;
  }

  Object.defineProperties(Queue.prototype, {
    /**
     * The length of the queue.
     *
     * @memberof Queue.prototype
     *
     * @type {Number}
     * @readonly
     */
    length: {
      get: function () {
        return this._length;
      },
    },
  });

  /**
   * Enqueues the specified item.
   *
   * @param {*} item The item to enqueue.
   */
  Queue.prototype.enqueue = function (item) {
    this._array.push(item);
    this._length++;
  };

  /**
   * Dequeues an item.  Returns undefined if the queue is empty.
   *
   * @returns {*} The the dequeued item.
   */
  Queue.prototype.dequeue = function () {
    if (this._length === 0) {
      return undefined;
    }

    const array = this._array;
    let offset = this._offset;
    const item = array[offset];
    array[offset] = undefined;

    offset++;
    if (offset > 10 && offset * 2 > array.length) {
      //compact array
      this._array = array.slice(offset);
      offset = 0;
    }

    this._offset = offset;
    this._length--;

    return item;
  };

  /**
   * Returns the item at the front of the queue.  Returns undefined if the queue is empty.
   *
   * @returns {*} The item at the front of the queue.
   */
  Queue.prototype.peek = function () {
    if (this._length === 0) {
      return undefined;
    }

    return this._array[this._offset];
  };

  /**
   * Check whether this queue contains the specified item.
   *
   * @param {*} item The item to search for.
   */
  Queue.prototype.contains = function (item) {
    return this._array.indexOf(item) !== -1;
  };

  /**
   * Remove all items from the queue.
   */
  Queue.prototype.clear = function () {
    this._array.length = this._offset = this._length = 0;
  };

  /**
   * Sort the items in the queue in-place.
   *
   * @param {Queue.Comparator} compareFunction A function that defines the sort order.
   */
  Queue.prototype.sort = function (compareFunction) {
    if (this._offset > 0) {
      //compact array
      this._array = this._array.slice(this._offset);
      this._offset = 0;
    }

    this._array.sort(compareFunction);
  };

  /**
   * @private
   */
  const PolygonGeometryLibrary = {};

  PolygonGeometryLibrary.computeHierarchyPackedLength = function (
    polygonHierarchy,
    CartesianX
  ) {
    let numComponents = 0;
    const stack = [polygonHierarchy];
    while (stack.length > 0) {
      const hierarchy = stack.pop();
      if (!defined(hierarchy)) {
        continue;
      }

      numComponents += 2;

      const positions = hierarchy.positions;
      const holes = hierarchy.holes;

      if (defined(positions) && positions.length > 0) {
        numComponents += positions.length * CartesianX.packedLength;
      }

      if (defined(holes)) {
        const length = holes.length;
        for (let i = 0; i < length; ++i) {
          stack.push(holes[i]);
        }
      }
    }

    return numComponents;
  };

  PolygonGeometryLibrary.packPolygonHierarchy = function (
    polygonHierarchy,
    array,
    startingIndex,
    CartesianX
  ) {
    const stack = [polygonHierarchy];
    while (stack.length > 0) {
      const hierarchy = stack.pop();
      if (!defined(hierarchy)) {
        continue;
      }

      const positions = hierarchy.positions;
      const holes = hierarchy.holes;

      array[startingIndex++] = defined(positions) ? positions.length : 0;
      array[startingIndex++] = defined(holes) ? holes.length : 0;

      if (defined(positions)) {
        const positionsLength = positions.length;
        for (
          let i = 0;
          i < positionsLength;
          ++i, startingIndex += CartesianX.packedLength
        ) {
          CartesianX.pack(positions[i], array, startingIndex);
        }
      }

      if (defined(holes)) {
        const holesLength = holes.length;
        for (let j = 0; j < holesLength; ++j) {
          stack.push(holes[j]);
        }
      }
    }

    return startingIndex;
  };

  PolygonGeometryLibrary.unpackPolygonHierarchy = function (
    array,
    startingIndex,
    CartesianX
  ) {
    const positionsLength = array[startingIndex++];
    const holesLength = array[startingIndex++];

    const positions = new Array(positionsLength);
    const holes = holesLength > 0 ? new Array(holesLength) : undefined;

    for (
      let i = 0;
      i < positionsLength;
      ++i, startingIndex += CartesianX.packedLength
    ) {
      positions[i] = CartesianX.unpack(array, startingIndex);
    }

    for (let j = 0; j < holesLength; ++j) {
      holes[j] = PolygonGeometryLibrary.unpackPolygonHierarchy(
        array,
        startingIndex,
        CartesianX
      );
      startingIndex = holes[j].startingIndex;
      delete holes[j].startingIndex;
    }

    return {
      positions: positions,
      holes: holes,
      startingIndex: startingIndex,
    };
  };

  const distance2DScratch = new Cartesian2();
  function getPointAtDistance2D(p0, p1, distance, length) {
    Cartesian2.subtract(p1, p0, distance2DScratch);
    Cartesian2.multiplyByScalar(
      distance2DScratch,
      distance / length,
      distance2DScratch
    );
    Cartesian2.add(p0, distance2DScratch, distance2DScratch);
    return [distance2DScratch.x, distance2DScratch.y];
  }

  const distanceScratch = new Cartesian3();
  function getPointAtDistance(p0, p1, distance, length) {
    Cartesian3.subtract(p1, p0, distanceScratch);
    Cartesian3.multiplyByScalar(
      distanceScratch,
      distance / length,
      distanceScratch
    );
    Cartesian3.add(p0, distanceScratch, distanceScratch);
    return [distanceScratch.x, distanceScratch.y, distanceScratch.z];
  }

  PolygonGeometryLibrary.subdivideLineCount = function (p0, p1, minDistance) {
    const distance = Cartesian3.distance(p0, p1);
    const n = distance / minDistance;
    const countDivide = Math.max(0, Math.ceil(CesiumMath.log2(n)));
    return Math.pow(2, countDivide);
  };

  const scratchCartographic0$1 = new Cartographic();
  const scratchCartographic1$2 = new Cartographic();
  const scratchCartographic2$1 = new Cartographic();
  const scratchCartesian0 = new Cartesian3();
  const scratchRhumbLine = new EllipsoidRhumbLine();
  PolygonGeometryLibrary.subdivideRhumbLineCount = function (
    ellipsoid,
    p0,
    p1,
    minDistance
  ) {
    const c0 = ellipsoid.cartesianToCartographic(p0, scratchCartographic0$1);
    const c1 = ellipsoid.cartesianToCartographic(p1, scratchCartographic1$2);
    const rhumb = new EllipsoidRhumbLine(c0, c1, ellipsoid);
    const n = rhumb.surfaceDistance / minDistance;
    const countDivide = Math.max(0, Math.ceil(CesiumMath.log2(n)));
    return Math.pow(2, countDivide);
  };

  /**
   * Subdivides texture coordinates based on the subdivision of the associated world positions.
   *
   * @param {Cartesian2} t0 First texture coordinate.
   * @param {Cartesian2} t1 Second texture coordinate.
   * @param {Cartesian3} p0 First world position.
   * @param {Cartesian3} p1 Second world position.
   * @param {Number} minDistance Minimum distance for a segment.
   * @param {Array<Cartesian2>} result The subdivided texture coordinates.
   *
   * @private
   */
  PolygonGeometryLibrary.subdivideTexcoordLine = function (
    t0,
    t1,
    p0,
    p1,
    minDistance,
    result
  ) {
    // Compute the number of subdivisions.
    const subdivisions = PolygonGeometryLibrary.subdivideLineCount(
      p0,
      p1,
      minDistance
    );

    // Compute the distance between each subdivided point.
    const length2D = Cartesian2.distance(t0, t1);
    const distanceBetweenCoords = length2D / subdivisions;

    // Resize the result array.
    const texcoords = result;
    texcoords.length = subdivisions * 2;

    // Compute texture coordinates using linear interpolation.
    let index = 0;
    for (let i = 0; i < subdivisions; i++) {
      const t = getPointAtDistance2D(t0, t1, i * distanceBetweenCoords, length2D);
      texcoords[index++] = t[0];
      texcoords[index++] = t[1];
    }

    return texcoords;
  };

  PolygonGeometryLibrary.subdivideLine = function (p0, p1, minDistance, result) {
    const numVertices = PolygonGeometryLibrary.subdivideLineCount(
      p0,
      p1,
      minDistance
    );
    const length = Cartesian3.distance(p0, p1);
    const distanceBetweenVertices = length / numVertices;

    if (!defined(result)) {
      result = [];
    }

    const positions = result;
    positions.length = numVertices * 3;

    let index = 0;
    for (let i = 0; i < numVertices; i++) {
      const p = getPointAtDistance(p0, p1, i * distanceBetweenVertices, length);
      positions[index++] = p[0];
      positions[index++] = p[1];
      positions[index++] = p[2];
    }

    return positions;
  };

  /**
   * Subdivides texture coordinates based on the subdivision of the associated world positions using a rhumb line.
   *
   * @param {Cartesian2} t0 First texture coordinate.
   * @param {Cartesian2} t1 Second texture coordinate.
   * @param {Ellipsoid} ellipsoid The ellipsoid.
   * @param {Cartesian3} p0 First world position.
   * @param {Cartesian3} p1 Second world position.
   * @param {Number} minDistance Minimum distance for a segment.
   * @param {Array<Cartesian2>} result The subdivided texture coordinates.
   *
   * @private
   */
  PolygonGeometryLibrary.subdivideTexcoordRhumbLine = function (
    t0,
    t1,
    ellipsoid,
    p0,
    p1,
    minDistance,
    result
  ) {
    // Compute the surface distance.
    const c0 = ellipsoid.cartesianToCartographic(p0, scratchCartographic0$1);
    const c1 = ellipsoid.cartesianToCartographic(p1, scratchCartographic1$2);
    scratchRhumbLine.setEndPoints(c0, c1);
    const n = scratchRhumbLine.surfaceDistance / minDistance;

    // Compute the number of subdivisions.
    const countDivide = Math.max(0, Math.ceil(CesiumMath.log2(n)));
    const subdivisions = Math.pow(2, countDivide);

    // Compute the distance between each subdivided point.
    const length2D = Cartesian2.distance(t0, t1);
    const distanceBetweenCoords = length2D / subdivisions;

    // Resize the result array.
    const texcoords = result;
    texcoords.length = subdivisions * 2;

    // Compute texture coordinates using linear interpolation.
    let index = 0;
    for (let i = 0; i < subdivisions; i++) {
      const t = getPointAtDistance2D(t0, t1, i * distanceBetweenCoords, length2D);
      texcoords[index++] = t[0];
      texcoords[index++] = t[1];
    }

    return texcoords;
  };

  PolygonGeometryLibrary.subdivideRhumbLine = function (
    ellipsoid,
    p0,
    p1,
    minDistance,
    result
  ) {
    const c0 = ellipsoid.cartesianToCartographic(p0, scratchCartographic0$1);
    const c1 = ellipsoid.cartesianToCartographic(p1, scratchCartographic1$2);
    const rhumb = new EllipsoidRhumbLine(c0, c1, ellipsoid);

    const n = rhumb.surfaceDistance / minDistance;
    const countDivide = Math.max(0, Math.ceil(CesiumMath.log2(n)));
    const numVertices = Math.pow(2, countDivide);
    const distanceBetweenVertices = rhumb.surfaceDistance / numVertices;

    if (!defined(result)) {
      result = [];
    }

    const positions = result;
    positions.length = numVertices * 3;

    let index = 0;
    for (let i = 0; i < numVertices; i++) {
      const c = rhumb.interpolateUsingSurfaceDistance(
        i * distanceBetweenVertices,
        scratchCartographic2$1
      );
      const p = ellipsoid.cartographicToCartesian(c, scratchCartesian0);
      positions[index++] = p.x;
      positions[index++] = p.y;
      positions[index++] = p.z;
    }

    return positions;
  };

  const scaleToGeodeticHeightN1 = new Cartesian3();
  const scaleToGeodeticHeightN2 = new Cartesian3();
  const scaleToGeodeticHeightP1 = new Cartesian3();
  const scaleToGeodeticHeightP2 = new Cartesian3();

  PolygonGeometryLibrary.scaleToGeodeticHeightExtruded = function (
    geometry,
    maxHeight,
    minHeight,
    ellipsoid,
    perPositionHeight
  ) {
    ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);

    const n1 = scaleToGeodeticHeightN1;
    let n2 = scaleToGeodeticHeightN2;
    const p = scaleToGeodeticHeightP1;
    let p2 = scaleToGeodeticHeightP2;

    if (
      defined(geometry) &&
      defined(geometry.attributes) &&
      defined(geometry.attributes.position)
    ) {
      const positions = geometry.attributes.position.values;
      const length = positions.length / 2;

      for (let i = 0; i < length; i += 3) {
        Cartesian3.fromArray(positions, i, p);

        ellipsoid.geodeticSurfaceNormal(p, n1);
        p2 = ellipsoid.scaleToGeodeticSurface(p, p2);
        n2 = Cartesian3.multiplyByScalar(n1, minHeight, n2);
        n2 = Cartesian3.add(p2, n2, n2);
        positions[i + length] = n2.x;
        positions[i + 1 + length] = n2.y;
        positions[i + 2 + length] = n2.z;

        if (perPositionHeight) {
          p2 = Cartesian3.clone(p, p2);
        }
        n2 = Cartesian3.multiplyByScalar(n1, maxHeight, n2);
        n2 = Cartesian3.add(p2, n2, n2);
        positions[i] = n2.x;
        positions[i + 1] = n2.y;
        positions[i + 2] = n2.z;
      }
    }
    return geometry;
  };

  PolygonGeometryLibrary.polygonOutlinesFromHierarchy = function (
    polygonHierarchy,
    scaleToEllipsoidSurface,
    ellipsoid
  ) {
    // create from a polygon hierarchy
    // Algorithm adapted from http://www.geometrictools.com/Documentation/TriangulationByEarClipping.pdf
    const polygons = [];
    const queue = new Queue();
    queue.enqueue(polygonHierarchy);
    let i;
    let j;
    let length;
    while (queue.length !== 0) {
      const outerNode = queue.dequeue();
      let outerRing = outerNode.positions;
      if (scaleToEllipsoidSurface) {
        length = outerRing.length;
        for (i = 0; i < length; i++) {
          ellipsoid.scaleToGeodeticSurface(outerRing[i], outerRing[i]);
        }
      }
      outerRing = arrayRemoveDuplicates(
        outerRing,
        Cartesian3.equalsEpsilon,
        true
      );
      if (outerRing.length < 3) {
        continue;
      }

      const numChildren = outerNode.holes ? outerNode.holes.length : 0;
      // The outer polygon contains inner polygons
      for (i = 0; i < numChildren; i++) {
        const hole = outerNode.holes[i];
        let holePositions = hole.positions;
        if (scaleToEllipsoidSurface) {
          length = holePositions.length;
          for (j = 0; j < length; ++j) {
            ellipsoid.scaleToGeodeticSurface(holePositions[j], holePositions[j]);
          }
        }
        holePositions = arrayRemoveDuplicates(
          holePositions,
          Cartesian3.equalsEpsilon,
          true
        );
        if (holePositions.length < 3) {
          continue;
        }
        polygons.push(holePositions);

        let numGrandchildren = 0;
        if (defined(hole.holes)) {
          numGrandchildren = hole.holes.length;
        }

        for (j = 0; j < numGrandchildren; j++) {
          queue.enqueue(hole.holes[j]);
        }
      }

      polygons.push(outerRing);
    }

    return polygons;
  };

  PolygonGeometryLibrary.polygonsFromHierarchy = function (
    polygonHierarchy,
    keepDuplicates,
    projectPointsTo2D,
    scaleToEllipsoidSurface,
    ellipsoid
  ) {
    // create from a polygon hierarchy
    // Algorithm adapted from http://www.geometrictools.com/Documentation/TriangulationByEarClipping.pdf
    const hierarchy = [];
    const polygons = [];

    const queue = new Queue();
    queue.enqueue(polygonHierarchy);

    while (queue.length !== 0) {
      const outerNode = queue.dequeue();
      let outerRing = outerNode.positions;
      const holes = outerNode.holes;

      let i;
      let length;
      if (scaleToEllipsoidSurface) {
        length = outerRing.length;
        for (i = 0; i < length; i++) {
          ellipsoid.scaleToGeodeticSurface(outerRing[i], outerRing[i]);
        }
      }

      if (!keepDuplicates) {
        outerRing = arrayRemoveDuplicates(
          outerRing,
          Cartesian3.equalsEpsilon,
          true
        );
      }
      if (outerRing.length < 3) {
        continue;
      }

      let positions2D = projectPointsTo2D(outerRing);
      if (!defined(positions2D)) {
        continue;
      }
      const holeIndices = [];

      let originalWindingOrder = PolygonPipeline.computeWindingOrder2D(
        positions2D
      );
      if (originalWindingOrder === WindingOrder$1.CLOCKWISE) {
        positions2D.reverse();
        outerRing = outerRing.slice().reverse();
      }

      let positions = outerRing.slice();
      const numChildren = defined(holes) ? holes.length : 0;
      const polygonHoles = [];
      let j;

      for (i = 0; i < numChildren; i++) {
        const hole = holes[i];
        let holePositions = hole.positions;
        if (scaleToEllipsoidSurface) {
          length = holePositions.length;
          for (j = 0; j < length; ++j) {
            ellipsoid.scaleToGeodeticSurface(holePositions[j], holePositions[j]);
          }
        }

        if (!keepDuplicates) {
          holePositions = arrayRemoveDuplicates(
            holePositions,
            Cartesian3.equalsEpsilon,
            true
          );
        }
        if (holePositions.length < 3) {
          continue;
        }

        const holePositions2D = projectPointsTo2D(holePositions);
        if (!defined(holePositions2D)) {
          continue;
        }

        originalWindingOrder = PolygonPipeline.computeWindingOrder2D(
          holePositions2D
        );
        if (originalWindingOrder === WindingOrder$1.CLOCKWISE) {
          holePositions2D.reverse();
          holePositions = holePositions.slice().reverse();
        }

        polygonHoles.push(holePositions);
        holeIndices.push(positions.length);
        positions = positions.concat(holePositions);
        positions2D = positions2D.concat(holePositions2D);

        let numGrandchildren = 0;
        if (defined(hole.holes)) {
          numGrandchildren = hole.holes.length;
        }

        for (j = 0; j < numGrandchildren; j++) {
          queue.enqueue(hole.holes[j]);
        }
      }

      hierarchy.push({
        outerRing: outerRing,
        holes: polygonHoles,
      });
      polygons.push({
        positions: positions,
        positions2D: positions2D,
        holes: holeIndices,
      });
    }

    return {
      hierarchy: hierarchy,
      polygons: polygons,
    };
  };

  const computeBoundingRectangleCartesian2 = new Cartesian2();
  const computeBoundingRectangleCartesian3 = new Cartesian3();
  const computeBoundingRectangleQuaternion = new Quaternion();
  const computeBoundingRectangleMatrix3 = new Matrix3();
  PolygonGeometryLibrary.computeBoundingRectangle = function (
    planeNormal,
    projectPointTo2D,
    positions,
    angle,
    result
  ) {
    const rotation = Quaternion.fromAxisAngle(
      planeNormal,
      angle,
      computeBoundingRectangleQuaternion
    );
    const textureMatrix = Matrix3.fromQuaternion(
      rotation,
      computeBoundingRectangleMatrix3
    );

    let minX = Number.POSITIVE_INFINITY;
    let maxX = Number.NEGATIVE_INFINITY;
    let minY = Number.POSITIVE_INFINITY;
    let maxY = Number.NEGATIVE_INFINITY;

    const length = positions.length;
    for (let i = 0; i < length; ++i) {
      const p = Cartesian3.clone(
        positions[i],
        computeBoundingRectangleCartesian3
      );
      Matrix3.multiplyByVector(textureMatrix, p, p);
      const st = projectPointTo2D(p, computeBoundingRectangleCartesian2);

      if (defined(st)) {
        minX = Math.min(minX, st.x);
        maxX = Math.max(maxX, st.x);

        minY = Math.min(minY, st.y);
        maxY = Math.max(maxY, st.y);
      }
    }

    result.x = minX;
    result.y = minY;
    result.width = maxX - minX;
    result.height = maxY - minY;
    return result;
  };

  PolygonGeometryLibrary.createGeometryFromPositions = function (
    ellipsoid,
    polygon,
    textureCoordinates,
    granularity,
    perPositionHeight,
    vertexFormat,
    arcType
  ) {
    let indices = PolygonPipeline.triangulate(polygon.positions2D, polygon.holes);

    /* If polygon is completely unrenderable, just use the first three vertices */
    if (indices.length < 3) {
      indices = [0, 1, 2];
    }

    const positions = polygon.positions;

    const hasTexcoords = defined(textureCoordinates);
    const texcoords = hasTexcoords ? textureCoordinates.positions : undefined;

    if (perPositionHeight) {
      const length = positions.length;
      const flattenedPositions = new Array(length * 3);
      let index = 0;
      for (let i = 0; i < length; i++) {
        const p = positions[i];
        flattenedPositions[index++] = p.x;
        flattenedPositions[index++] = p.y;
        flattenedPositions[index++] = p.z;
      }

      const geometryOptions = {
        attributes: {
          position: new GeometryAttribute({
            componentDatatype: ComponentDatatype$1.DOUBLE,
            componentsPerAttribute: 3,
            values: flattenedPositions,
          }),
        },
        indices: indices,
        primitiveType: PrimitiveType$1.TRIANGLES,
      };

      if (hasTexcoords) {
        geometryOptions.attributes.st = new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 2,
          values: Cartesian2.packArray(texcoords),
        });
      }

      const geometry = new Geometry(geometryOptions);

      if (vertexFormat.normal) {
        return GeometryPipeline.computeNormal(geometry);
      }

      return geometry;
    }

    if (arcType === ArcType$1.GEODESIC) {
      return PolygonPipeline.computeSubdivision(
        ellipsoid,
        positions,
        indices,
        texcoords,
        granularity
      );
    } else if (arcType === ArcType$1.RHUMB) {
      return PolygonPipeline.computeRhumbLineSubdivision(
        ellipsoid,
        positions,
        indices,
        texcoords,
        granularity
      );
    }
  };

  const computeWallTexcoordsSubdivided = [];
  const computeWallIndicesSubdivided = [];
  const p1Scratch$1 = new Cartesian3();
  const p2Scratch$1 = new Cartesian3();

  PolygonGeometryLibrary.computeWallGeometry = function (
    positions,
    textureCoordinates,
    ellipsoid,
    granularity,
    perPositionHeight,
    arcType
  ) {
    let edgePositions;
    let topEdgeLength;
    let i;
    let p1;
    let p2;
    let t1;
    let t2;
    let edgeTexcoords;
    let topEdgeTexcoordLength;

    let length = positions.length;
    let index = 0;
    let textureIndex = 0;

    const hasTexcoords = defined(textureCoordinates);
    const texcoords = hasTexcoords ? textureCoordinates.positions : undefined;

    if (!perPositionHeight) {
      const minDistance = CesiumMath.chordLength(
        granularity,
        ellipsoid.maximumRadius
      );

      let numVertices = 0;
      if (arcType === ArcType$1.GEODESIC) {
        for (i = 0; i < length; i++) {
          numVertices += PolygonGeometryLibrary.subdivideLineCount(
            positions[i],
            positions[(i + 1) % length],
            minDistance
          );
        }
      } else if (arcType === ArcType$1.RHUMB) {
        for (i = 0; i < length; i++) {
          numVertices += PolygonGeometryLibrary.subdivideRhumbLineCount(
            ellipsoid,
            positions[i],
            positions[(i + 1) % length],
            minDistance
          );
        }
      }

      topEdgeLength = (numVertices + length) * 3;
      edgePositions = new Array(topEdgeLength * 2);

      if (hasTexcoords) {
        topEdgeTexcoordLength = (numVertices + length) * 2;
        edgeTexcoords = new Array(topEdgeTexcoordLength * 2);
      }

      for (i = 0; i < length; i++) {
        p1 = positions[i];
        p2 = positions[(i + 1) % length];

        let tempPositions;
        let tempTexcoords;

        if (hasTexcoords) {
          t1 = texcoords[i];
          t2 = texcoords[(i + 1) % length];
        }

        if (arcType === ArcType$1.GEODESIC) {
          tempPositions = PolygonGeometryLibrary.subdivideLine(
            p1,
            p2,
            minDistance,
            computeWallIndicesSubdivided
          );
          if (hasTexcoords) {
            tempTexcoords = PolygonGeometryLibrary.subdivideTexcoordLine(
              t1,
              t2,
              p1,
              p2,
              minDistance,
              computeWallTexcoordsSubdivided
            );
          }
        } else if (arcType === ArcType$1.RHUMB) {
          tempPositions = PolygonGeometryLibrary.subdivideRhumbLine(
            ellipsoid,
            p1,
            p2,
            minDistance,
            computeWallIndicesSubdivided
          );
          if (hasTexcoords) {
            tempTexcoords = PolygonGeometryLibrary.subdivideTexcoordRhumbLine(
              t1,
              t2,
              ellipsoid,
              p1,
              p2,
              minDistance,
              computeWallTexcoordsSubdivided
            );
          }
        }
        const tempPositionsLength = tempPositions.length;
        for (let j = 0; j < tempPositionsLength; ++j, ++index) {
          edgePositions[index] = tempPositions[j];
          edgePositions[index + topEdgeLength] = tempPositions[j];
        }

        edgePositions[index] = p2.x;
        edgePositions[index + topEdgeLength] = p2.x;
        ++index;

        edgePositions[index] = p2.y;
        edgePositions[index + topEdgeLength] = p2.y;
        ++index;

        edgePositions[index] = p2.z;
        edgePositions[index + topEdgeLength] = p2.z;
        ++index;

        if (hasTexcoords) {
          const tempTexcoordsLength = tempTexcoords.length;
          for (let k = 0; k < tempTexcoordsLength; ++k, ++textureIndex) {
            edgeTexcoords[textureIndex] = tempTexcoords[k];
            edgeTexcoords[textureIndex + topEdgeTexcoordLength] =
              tempTexcoords[k];
          }

          edgeTexcoords[textureIndex] = t2.x;
          edgeTexcoords[textureIndex + topEdgeTexcoordLength] = t2.x;
          ++textureIndex;

          edgeTexcoords[textureIndex] = t2.y;
          edgeTexcoords[textureIndex + topEdgeTexcoordLength] = t2.y;
          ++textureIndex;
        }
      }
    } else {
      topEdgeLength = length * 3 * 2;
      edgePositions = new Array(topEdgeLength * 2);

      if (hasTexcoords) {
        topEdgeTexcoordLength = length * 2 * 2;
        edgeTexcoords = new Array(topEdgeTexcoordLength * 2);
      }

      for (i = 0; i < length; i++) {
        p1 = positions[i];
        p2 = positions[(i + 1) % length];
        edgePositions[index] = edgePositions[index + topEdgeLength] = p1.x;
        ++index;
        edgePositions[index] = edgePositions[index + topEdgeLength] = p1.y;
        ++index;
        edgePositions[index] = edgePositions[index + topEdgeLength] = p1.z;
        ++index;
        edgePositions[index] = edgePositions[index + topEdgeLength] = p2.x;
        ++index;
        edgePositions[index] = edgePositions[index + topEdgeLength] = p2.y;
        ++index;
        edgePositions[index] = edgePositions[index + topEdgeLength] = p2.z;
        ++index;

        if (hasTexcoords) {
          t1 = texcoords[i];
          t2 = texcoords[(i + 1) % length];
          edgeTexcoords[textureIndex] = edgeTexcoords[
            textureIndex + topEdgeTexcoordLength
          ] = t1.x;
          ++textureIndex;
          edgeTexcoords[textureIndex] = edgeTexcoords[
            textureIndex + topEdgeTexcoordLength
          ] = t1.y;
          ++textureIndex;
          edgeTexcoords[textureIndex] = edgeTexcoords[
            textureIndex + topEdgeTexcoordLength
          ] = t2.x;
          ++textureIndex;
          edgeTexcoords[textureIndex] = edgeTexcoords[
            textureIndex + topEdgeTexcoordLength
          ] = t2.y;
          ++textureIndex;
        }
      }
    }

    length = edgePositions.length;
    const indices = IndexDatatype$1.createTypedArray(
      length / 3,
      length - positions.length * 6
    );
    let edgeIndex = 0;
    length /= 6;

    for (i = 0; i < length; i++) {
      const UL = i;
      const UR = UL + 1;
      const LL = UL + length;
      const LR = LL + 1;

      p1 = Cartesian3.fromArray(edgePositions, UL * 3, p1Scratch$1);
      p2 = Cartesian3.fromArray(edgePositions, UR * 3, p2Scratch$1);
      if (
        Cartesian3.equalsEpsilon(
          p1,
          p2,
          CesiumMath.EPSILON10,
          CesiumMath.EPSILON10
        )
      ) {
        //skip corner
        continue;
      }

      indices[edgeIndex++] = UL;
      indices[edgeIndex++] = LL;
      indices[edgeIndex++] = UR;
      indices[edgeIndex++] = UR;
      indices[edgeIndex++] = LL;
      indices[edgeIndex++] = LR;
    }

    const geometryOptions = {
      attributes: new GeometryAttributes({
        position: new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.DOUBLE,
          componentsPerAttribute: 3,
          values: edgePositions,
        }),
      }),
      indices: indices,
      primitiveType: PrimitiveType$1.TRIANGLES,
    };

    if (hasTexcoords) {
      geometryOptions.attributes.st = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 2,
        values: edgeTexcoords,
      });
    }

    const geometry = new Geometry(geometryOptions);

    return geometry;
  };

  const scratchPosition$e = new Cartesian3();
  const scratchBR = new BoundingRectangle();
  const stScratch$1 = new Cartesian2();
  const textureCoordinatesOrigin = new Cartesian2();
  const scratchNormal$4 = new Cartesian3();
  const scratchTangent$3 = new Cartesian3();
  const scratchBitangent$3 = new Cartesian3();
  const centerScratch$5 = new Cartesian3();
  const axis1Scratch = new Cartesian3();
  const axis2Scratch = new Cartesian3();
  const quaternionScratch$2 = new Quaternion();
  const textureMatrixScratch = new Matrix3();
  const tangentRotationScratch = new Matrix3();
  const surfaceNormalScratch = new Cartesian3();

  function createGeometryFromPolygon(
    polygon,
    vertexFormat,
    boundingRectangle,
    stRotation,
    hardcodedTextureCoordinates,
    projectPointTo2D,
    normal,
    tangent,
    bitangent
  ) {
    const positions = polygon.positions;
    let indices = PolygonPipeline.triangulate(polygon.positions2D, polygon.holes);

    /* If polygon is completely unrenderable, just use the first three vertices */
    if (indices.length < 3) {
      indices = [0, 1, 2];
    }

    const newIndices = IndexDatatype$1.createTypedArray(
      positions.length,
      indices.length
    );
    newIndices.set(indices);

    let textureMatrix = textureMatrixScratch;
    if (stRotation !== 0.0) {
      let rotation = Quaternion.fromAxisAngle(
        normal,
        stRotation,
        quaternionScratch$2
      );
      textureMatrix = Matrix3.fromQuaternion(rotation, textureMatrix);

      if (vertexFormat.tangent || vertexFormat.bitangent) {
        rotation = Quaternion.fromAxisAngle(
          normal,
          -stRotation,
          quaternionScratch$2
        );
        const tangentRotation = Matrix3.fromQuaternion(
          rotation,
          tangentRotationScratch
        );

        tangent = Cartesian3.normalize(
          Matrix3.multiplyByVector(tangentRotation, tangent, tangent),
          tangent
        );
        if (vertexFormat.bitangent) {
          bitangent = Cartesian3.normalize(
            Cartesian3.cross(normal, tangent, bitangent),
            bitangent
          );
        }
      }
    } else {
      textureMatrix = Matrix3.clone(Matrix3.IDENTITY, textureMatrix);
    }

    const stOrigin = textureCoordinatesOrigin;
    if (vertexFormat.st) {
      stOrigin.x = boundingRectangle.x;
      stOrigin.y = boundingRectangle.y;
    }

    const length = positions.length;
    const size = length * 3;
    const flatPositions = new Float64Array(size);
    const normals = vertexFormat.normal ? new Float32Array(size) : undefined;
    const tangents = vertexFormat.tangent ? new Float32Array(size) : undefined;
    const bitangents = vertexFormat.bitangent
      ? new Float32Array(size)
      : undefined;
    const textureCoordinates = vertexFormat.st
      ? new Float32Array(length * 2)
      : undefined;

    let positionIndex = 0;
    let normalIndex = 0;
    let bitangentIndex = 0;
    let tangentIndex = 0;
    let stIndex = 0;

    for (let i = 0; i < length; i++) {
      const position = positions[i];
      flatPositions[positionIndex++] = position.x;
      flatPositions[positionIndex++] = position.y;
      flatPositions[positionIndex++] = position.z;

      if (vertexFormat.st) {
        if (
          defined(hardcodedTextureCoordinates) &&
          hardcodedTextureCoordinates.positions.length === length
        ) {
          textureCoordinates[stIndex++] =
            hardcodedTextureCoordinates.positions[i].x;
          textureCoordinates[stIndex++] =
            hardcodedTextureCoordinates.positions[i].y;
        } else {
          const p = Matrix3.multiplyByVector(
            textureMatrix,
            position,
            scratchPosition$e
          );
          const st = projectPointTo2D(p, stScratch$1);
          Cartesian2.subtract(st, stOrigin, st);

          const stx = CesiumMath.clamp(st.x / boundingRectangle.width, 0, 1);
          const sty = CesiumMath.clamp(st.y / boundingRectangle.height, 0, 1);
          textureCoordinates[stIndex++] = stx;
          textureCoordinates[stIndex++] = sty;
        }
      }

      if (vertexFormat.normal) {
        normals[normalIndex++] = normal.x;
        normals[normalIndex++] = normal.y;
        normals[normalIndex++] = normal.z;
      }

      if (vertexFormat.tangent) {
        tangents[tangentIndex++] = tangent.x;
        tangents[tangentIndex++] = tangent.y;
        tangents[tangentIndex++] = tangent.z;
      }

      if (vertexFormat.bitangent) {
        bitangents[bitangentIndex++] = bitangent.x;
        bitangents[bitangentIndex++] = bitangent.y;
        bitangents[bitangentIndex++] = bitangent.z;
      }
    }

    const attributes = new GeometryAttributes();

    if (vertexFormat.position) {
      attributes.position = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.DOUBLE,
        componentsPerAttribute: 3,
        values: flatPositions,
      });
    }

    if (vertexFormat.normal) {
      attributes.normal = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 3,
        values: normals,
      });
    }

    if (vertexFormat.tangent) {
      attributes.tangent = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 3,
        values: tangents,
      });
    }

    if (vertexFormat.bitangent) {
      attributes.bitangent = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 3,
        values: bitangents,
      });
    }

    if (vertexFormat.st) {
      attributes.st = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 2,
        values: textureCoordinates,
      });
    }

    return new Geometry({
      attributes: attributes,
      indices: newIndices,
      primitiveType: PrimitiveType$1.TRIANGLES,
    });
  }

  /**
   * A description of a polygon composed of arbitrary coplanar positions.
   *
   * @alias CoplanarPolygonGeometry
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {PolygonHierarchy} options.polygonHierarchy A polygon hierarchy that can include holes.
   * @param {Number} [options.stRotation=0.0] The rotation of the texture coordinates, in radians. A positive rotation is counter-clockwise.
   * @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid to be used as a reference.
   * @param {PolygonHierarchy} [options.textureCoordinates] Texture coordinates as a {@link PolygonHierarchy} of {@link Cartesian2} points.
   *
   * @example
   * const polygonGeometry = new Cesium.CoplanarPolygonGeometry({
   *  polygonHierarchy: new Cesium.PolygonHierarchy(
   *     Cesium.Cartesian3.fromDegreesArrayHeights([
   *      -90.0, 30.0, 0.0,
   *      -90.0, 30.0, 300000.0,
   *      -80.0, 30.0, 300000.0,
   *      -80.0, 30.0, 0.0
   *   ]))
   * });
   *
   */
  function CoplanarPolygonGeometry(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const polygonHierarchy = options.polygonHierarchy;
    const textureCoordinates = options.textureCoordinates;
    //>>includeStart('debug', pragmas.debug);
    Check.defined("options.polygonHierarchy", polygonHierarchy);
    //>>includeEnd('debug');

    const vertexFormat = defaultValue(options.vertexFormat, VertexFormat.DEFAULT);
    this._vertexFormat = VertexFormat.clone(vertexFormat);
    this._polygonHierarchy = polygonHierarchy;
    this._stRotation = defaultValue(options.stRotation, 0.0);
    this._ellipsoid = Ellipsoid.clone(
      defaultValue(options.ellipsoid, Ellipsoid.WGS84)
    );
    this._workerName = "createCoplanarPolygonGeometry";
    this._textureCoordinates = textureCoordinates;

    /**
     * The number of elements used to pack the object into an array.
     * @type {Number}
     */
    this.packedLength =
      PolygonGeometryLibrary.computeHierarchyPackedLength(
        polygonHierarchy,
        Cartesian3
      ) +
      VertexFormat.packedLength +
      Ellipsoid.packedLength +
      (defined(textureCoordinates)
        ? PolygonGeometryLibrary.computeHierarchyPackedLength(
            textureCoordinates,
            Cartesian2
          )
        : 1) +
      2;
  }

  /**
   * A description of a coplanar polygon from an array of positions.
   *
   * @param {Object} options Object with the following properties:
   * @param {Cartesian3[]} options.positions An array of positions that defined the corner points of the polygon.
   * @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
   * @param {Number} [options.stRotation=0.0] The rotation of the texture coordinates, in radians. A positive rotation is counter-clockwise.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid to be used as a reference.
   * @param {PolygonHierarchy} [options.textureCoordinates] Texture coordinates as a {@link PolygonHierarchy} of {@link Cartesian2} points.
   * @returns {CoplanarPolygonGeometry}
   *
   * @example
   * // create a polygon from points
   * const polygon = Cesium.CoplanarPolygonGeometry.fromPositions({
   *   positions : Cesium.Cartesian3.fromDegreesArray([
   *     -72.0, 40.0,
   *     -70.0, 35.0,
   *     -75.0, 30.0,
   *     -70.0, 30.0,
   *     -68.0, 40.0
   *   ])
   * });
   * const geometry = Cesium.PolygonGeometry.createGeometry(polygon);
   *
   * @see PolygonGeometry#createGeometry
   */
  CoplanarPolygonGeometry.fromPositions = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    Check.defined("options.positions", options.positions);
    //>>includeEnd('debug');

    const newOptions = {
      polygonHierarchy: {
        positions: options.positions,
      },
      vertexFormat: options.vertexFormat,
      stRotation: options.stRotation,
      ellipsoid: options.ellipsoid,
      textureCoordinates: options.textureCoordinates,
    };
    return new CoplanarPolygonGeometry(newOptions);
  };

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {CoplanarPolygonGeometry} 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
   */
  CoplanarPolygonGeometry.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    startingIndex = PolygonGeometryLibrary.packPolygonHierarchy(
      value._polygonHierarchy,
      array,
      startingIndex,
      Cartesian3
    );

    Ellipsoid.pack(value._ellipsoid, array, startingIndex);
    startingIndex += Ellipsoid.packedLength;

    VertexFormat.pack(value._vertexFormat, array, startingIndex);
    startingIndex += VertexFormat.packedLength;

    array[startingIndex++] = value._stRotation;
    if (defined(value._textureCoordinates)) {
      startingIndex = PolygonGeometryLibrary.packPolygonHierarchy(
        value._textureCoordinates,
        array,
        startingIndex,
        Cartesian2
      );
    } else {
      array[startingIndex++] = -1.0;
    }
    array[startingIndex++] = value.packedLength;

    return array;
  };

  const scratchEllipsoid$c = Ellipsoid.clone(Ellipsoid.UNIT_SPHERE);
  const scratchVertexFormat$a = new VertexFormat();
  const scratchOptions$h = {
    polygonHierarchy: {},
  };
  /**
   * 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 {CoplanarPolygonGeometry} [result] The object into which to store the result.
   * @returns {CoplanarPolygonGeometry} The modified result parameter or a new CoplanarPolygonGeometry instance if one was not provided.
   */
  CoplanarPolygonGeometry.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    const polygonHierarchy = PolygonGeometryLibrary.unpackPolygonHierarchy(
      array,
      startingIndex,
      Cartesian3
    );
    startingIndex = polygonHierarchy.startingIndex;
    delete polygonHierarchy.startingIndex;

    const ellipsoid = Ellipsoid.unpack(array, startingIndex, scratchEllipsoid$c);
    startingIndex += Ellipsoid.packedLength;

    const vertexFormat = VertexFormat.unpack(
      array,
      startingIndex,
      scratchVertexFormat$a
    );
    startingIndex += VertexFormat.packedLength;

    const stRotation = array[startingIndex++];
    const textureCoordinates =
      array[startingIndex] === -1.0
        ? undefined
        : PolygonGeometryLibrary.unpackPolygonHierarchy(
            array,
            startingIndex,
            Cartesian2
          );
    if (defined(textureCoordinates)) {
      startingIndex = textureCoordinates.startingIndex;
      delete textureCoordinates.startingIndex;
    } else {
      startingIndex++;
    }
    const packedLength = array[startingIndex++];

    if (!defined(result)) {
      result = new CoplanarPolygonGeometry(scratchOptions$h);
    }

    result._polygonHierarchy = polygonHierarchy;
    result._ellipsoid = Ellipsoid.clone(ellipsoid, result._ellipsoid);
    result._vertexFormat = VertexFormat.clone(vertexFormat, result._vertexFormat);
    result._stRotation = stRotation;
    result._textureCoordinates = textureCoordinates;
    result.packedLength = packedLength;

    return result;
  };

  /**
   * Computes the geometric representation of an arbitrary coplanar polygon, including its vertices, indices, and a bounding sphere.
   *
   * @param {CoplanarPolygonGeometry} polygonGeometry A description of the polygon.
   * @returns {Geometry|undefined} The computed vertices and indices.
   */
  CoplanarPolygonGeometry.createGeometry = function (polygonGeometry) {
    const vertexFormat = polygonGeometry._vertexFormat;
    const polygonHierarchy = polygonGeometry._polygonHierarchy;
    const stRotation = polygonGeometry._stRotation;
    const textureCoordinates = polygonGeometry._textureCoordinates;
    const hasTextureCoordinates = defined(textureCoordinates);

    let outerPositions = polygonHierarchy.positions;
    outerPositions = arrayRemoveDuplicates(
      outerPositions,
      Cartesian3.equalsEpsilon,
      true
    );
    if (outerPositions.length < 3) {
      return;
    }

    let normal = scratchNormal$4;
    let tangent = scratchTangent$3;
    let bitangent = scratchBitangent$3;
    let axis1 = axis1Scratch;
    const axis2 = axis2Scratch;

    const validGeometry = CoplanarPolygonGeometryLibrary.computeProjectTo2DArguments(
      outerPositions,
      centerScratch$5,
      axis1,
      axis2
    );
    if (!validGeometry) {
      return undefined;
    }

    normal = Cartesian3.cross(axis1, axis2, normal);
    normal = Cartesian3.normalize(normal, normal);

    if (
      !Cartesian3.equalsEpsilon(
        centerScratch$5,
        Cartesian3.ZERO,
        CesiumMath.EPSILON6
      )
    ) {
      const surfaceNormal = polygonGeometry._ellipsoid.geodeticSurfaceNormal(
        centerScratch$5,
        surfaceNormalScratch
      );
      if (Cartesian3.dot(normal, surfaceNormal) < 0) {
        normal = Cartesian3.negate(normal, normal);
        axis1 = Cartesian3.negate(axis1, axis1);
      }
    }

    const projectPoints = CoplanarPolygonGeometryLibrary.createProjectPointsTo2DFunction(
      centerScratch$5,
      axis1,
      axis2
    );
    const projectPoint = CoplanarPolygonGeometryLibrary.createProjectPointTo2DFunction(
      centerScratch$5,
      axis1,
      axis2
    );

    if (vertexFormat.tangent) {
      tangent = Cartesian3.clone(axis1, tangent);
    }
    if (vertexFormat.bitangent) {
      bitangent = Cartesian3.clone(axis2, bitangent);
    }

    const results = PolygonGeometryLibrary.polygonsFromHierarchy(
      polygonHierarchy,
      hasTextureCoordinates,
      projectPoints,
      false
    );
    const hierarchy = results.hierarchy;
    const polygons = results.polygons;

    const dummyFunction = function (identity) {
      return identity;
    };

    const textureCoordinatePolygons = hasTextureCoordinates
      ? PolygonGeometryLibrary.polygonsFromHierarchy(
          textureCoordinates,
          true,
          dummyFunction,
          false
        ).polygons
      : undefined;

    if (hierarchy.length === 0) {
      return;
    }
    outerPositions = hierarchy[0].outerRing;

    const boundingSphere = BoundingSphere.fromPoints(outerPositions);
    const boundingRectangle = PolygonGeometryLibrary.computeBoundingRectangle(
      normal,
      projectPoint,
      outerPositions,
      stRotation,
      scratchBR
    );

    const geometries = [];
    for (let i = 0; i < polygons.length; i++) {
      const geometryInstance = new GeometryInstance({
        geometry: createGeometryFromPolygon(
          polygons[i],
          vertexFormat,
          boundingRectangle,
          stRotation,
          hasTextureCoordinates ? textureCoordinatePolygons[i] : undefined,
          projectPoint,
          normal,
          tangent,
          bitangent
        ),
      });

      geometries.push(geometryInstance);
    }

    const geometry = GeometryPipeline.combineInstances(geometries)[0];
    geometry.attributes.position.values = new Float64Array(
      geometry.attributes.position.values
    );
    geometry.indices = IndexDatatype$1.createTypedArray(
      geometry.attributes.position.values.length / 3,
      geometry.indices
    );

    const attributes = geometry.attributes;
    if (!vertexFormat.position) {
      delete attributes.position;
    }
    return new Geometry({
      attributes: attributes,
      indices: geometry.indices,
      primitiveType: geometry.primitiveType,
      boundingSphere: boundingSphere,
    });
  };

  function createGeometryFromPositions$1(positions) {
    const length = positions.length;
    const flatPositions = new Float64Array(length * 3);
    const indices = IndexDatatype$1.createTypedArray(length, length * 2);

    let positionIndex = 0;
    let index = 0;

    for (let i = 0; i < length; i++) {
      const position = positions[i];
      flatPositions[positionIndex++] = position.x;
      flatPositions[positionIndex++] = position.y;
      flatPositions[positionIndex++] = position.z;

      indices[index++] = i;
      indices[index++] = (i + 1) % length;
    }

    const attributes = new GeometryAttributes({
      position: new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.DOUBLE,
        componentsPerAttribute: 3,
        values: flatPositions,
      }),
    });

    return new Geometry({
      attributes: attributes,
      indices: indices,
      primitiveType: PrimitiveType$1.LINES,
    });
  }

  /**
   * A description of the outline of a polygon composed of arbitrary coplanar positions.
   *
   * @alias CoplanarPolygonOutlineGeometry
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {PolygonHierarchy} options.polygonHierarchy A polygon hierarchy that can include holes.
   *
   * @see CoplanarPolygonOutlineGeometry.createGeometry
   *
   * @example
   * const polygonOutline = new Cesium.CoplanarPolygonOutlineGeometry({
   *   positions : Cesium.Cartesian3.fromDegreesArrayHeights([
   *      -90.0, 30.0, 0.0,
   *      -90.0, 30.0, 1000.0,
   *      -80.0, 30.0, 1000.0,
   *      -80.0, 30.0, 0.0
   *   ])
   * });
   * const geometry = Cesium.CoplanarPolygonOutlineGeometry.createGeometry(polygonOutline);
   */
  function CoplanarPolygonOutlineGeometry(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const polygonHierarchy = options.polygonHierarchy;
    //>>includeStart('debug', pragmas.debug);
    Check.defined("options.polygonHierarchy", polygonHierarchy);
    //>>includeEnd('debug');

    this._polygonHierarchy = polygonHierarchy;
    this._workerName = "createCoplanarPolygonOutlineGeometry";

    /**
     * The number of elements used to pack the object into an array.
     * @type {Number}
     */
    this.packedLength =
      PolygonGeometryLibrary.computeHierarchyPackedLength(
        polygonHierarchy,
        Cartesian3
      ) + 1;
  }

  /**
   * A description of a coplanar polygon outline from an array of positions.
   *
   * @param {Object} options Object with the following properties:
   * @param {Cartesian3[]} options.positions An array of positions that defined the corner points of the polygon.
   * @returns {CoplanarPolygonOutlineGeometry}
   */
  CoplanarPolygonOutlineGeometry.fromPositions = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    Check.defined("options.positions", options.positions);
    //>>includeEnd('debug');

    const newOptions = {
      polygonHierarchy: {
        positions: options.positions,
      },
    };
    return new CoplanarPolygonOutlineGeometry(newOptions);
  };

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {CoplanarPolygonOutlineGeometry} 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
   */
  CoplanarPolygonOutlineGeometry.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    startingIndex = PolygonGeometryLibrary.packPolygonHierarchy(
      value._polygonHierarchy,
      array,
      startingIndex,
      Cartesian3
    );

    array[startingIndex] = value.packedLength;

    return array;
  };

  const scratchOptions$g = {
    polygonHierarchy: {},
  };
  /**
   * 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 {CoplanarPolygonOutlineGeometry} [result] The object into which to store the result.
   * @returns {CoplanarPolygonOutlineGeometry} The modified result parameter or a new CoplanarPolygonOutlineGeometry instance if one was not provided.
   */
  CoplanarPolygonOutlineGeometry.unpack = function (
    array,
    startingIndex,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    const polygonHierarchy = PolygonGeometryLibrary.unpackPolygonHierarchy(
      array,
      startingIndex,
      Cartesian3
    );
    startingIndex = polygonHierarchy.startingIndex;
    delete polygonHierarchy.startingIndex;
    const packedLength = array[startingIndex];

    if (!defined(result)) {
      result = new CoplanarPolygonOutlineGeometry(scratchOptions$g);
    }

    result._polygonHierarchy = polygonHierarchy;
    result.packedLength = packedLength;

    return result;
  };

  /**
   * Computes the geometric representation of an arbitrary coplanar polygon, including its vertices, indices, and a bounding sphere.
   *
   * @param {CoplanarPolygonOutlineGeometry} polygonGeometry A description of the polygon.
   * @returns {Geometry|undefined} The computed vertices and indices.
   */
  CoplanarPolygonOutlineGeometry.createGeometry = function (polygonGeometry) {
    const polygonHierarchy = polygonGeometry._polygonHierarchy;

    let outerPositions = polygonHierarchy.positions;
    outerPositions = arrayRemoveDuplicates(
      outerPositions,
      Cartesian3.equalsEpsilon,
      true
    );
    if (outerPositions.length < 3) {
      return;
    }
    const isValid = CoplanarPolygonGeometryLibrary.validOutline(outerPositions);
    if (!isValid) {
      return undefined;
    }

    const polygons = PolygonGeometryLibrary.polygonOutlinesFromHierarchy(
      polygonHierarchy,
      false
    );

    if (polygons.length === 0) {
      return undefined;
    }

    const geometries = [];

    for (let i = 0; i < polygons.length; i++) {
      const geometryInstance = new GeometryInstance({
        geometry: createGeometryFromPositions$1(polygons[i]),
      });
      geometries.push(geometryInstance);
    }

    const geometry = GeometryPipeline.combineInstances(geometries)[0];
    const boundingSphere = BoundingSphere.fromPoints(polygonHierarchy.positions);

    return new Geometry({
      attributes: geometry.attributes,
      indices: geometry.indices,
      primitiveType: geometry.primitiveType,
      boundingSphere: boundingSphere,
    });
  };

  /**
   * Style options for corners.
   *
   * @demo The {@link https://sandcastle.cesium.com/index.html?src=Corridor.html&label=Geometries|Corridor Demo}
   * demonstrates the three corner types, as used by {@link CorridorGraphics}.
   *
   * @enum {Number}
   */
  const CornerType = {
    /**
     * <img src="Images/CornerTypeRounded.png" style="vertical-align: middle;" width="186" height="189" />
     *
     * Corner has a smooth edge.
     * @type {Number}
     * @constant
     */
    ROUNDED: 0,

    /**
     * <img src="Images/CornerTypeMitered.png" style="vertical-align: middle;" width="186" height="189" />
     *
     * Corner point is the intersection of adjacent edges.
     * @type {Number}
     * @constant
     */
    MITERED: 1,

    /**
     * <img src="Images/CornerTypeBeveled.png" style="vertical-align: middle;" width="186" height="189" />
     *
     * Corner is clipped.
     * @type {Number}
     * @constant
     */
    BEVELED: 2,
  };
  var CornerType$1 = Object.freeze(CornerType);

  function setConstants(ellipsoidGeodesic) {
    const uSquared = ellipsoidGeodesic._uSquared;
    const a = ellipsoidGeodesic._ellipsoid.maximumRadius;
    const b = ellipsoidGeodesic._ellipsoid.minimumRadius;
    const f = (a - b) / a;

    const cosineHeading = Math.cos(ellipsoidGeodesic._startHeading);
    const sineHeading = Math.sin(ellipsoidGeodesic._startHeading);

    const tanU = (1 - f) * Math.tan(ellipsoidGeodesic._start.latitude);

    const cosineU = 1.0 / Math.sqrt(1.0 + tanU * tanU);
    const sineU = cosineU * tanU;

    const sigma = Math.atan2(tanU, cosineHeading);

    const sineAlpha = cosineU * sineHeading;
    const sineSquaredAlpha = sineAlpha * sineAlpha;

    const cosineSquaredAlpha = 1.0 - sineSquaredAlpha;
    const cosineAlpha = Math.sqrt(cosineSquaredAlpha);

    const u2Over4 = uSquared / 4.0;
    const u4Over16 = u2Over4 * u2Over4;
    const u6Over64 = u4Over16 * u2Over4;
    const u8Over256 = u4Over16 * u4Over16;

    const a0 =
      1.0 +
      u2Over4 -
      (3.0 * u4Over16) / 4.0 +
      (5.0 * u6Over64) / 4.0 -
      (175.0 * u8Over256) / 64.0;
    const a1 = 1.0 - u2Over4 + (15.0 * u4Over16) / 8.0 - (35.0 * u6Over64) / 8.0;
    const a2 = 1.0 - 3.0 * u2Over4 + (35.0 * u4Over16) / 4.0;
    const a3 = 1.0 - 5.0 * u2Over4;

    const distanceRatio =
      a0 * sigma -
      (a1 * Math.sin(2.0 * sigma) * u2Over4) / 2.0 -
      (a2 * Math.sin(4.0 * sigma) * u4Over16) / 16.0 -
      (a3 * Math.sin(6.0 * sigma) * u6Over64) / 48.0 -
      (Math.sin(8.0 * sigma) * 5.0 * u8Over256) / 512;

    const constants = ellipsoidGeodesic._constants;

    constants.a = a;
    constants.b = b;
    constants.f = f;
    constants.cosineHeading = cosineHeading;
    constants.sineHeading = sineHeading;
    constants.tanU = tanU;
    constants.cosineU = cosineU;
    constants.sineU = sineU;
    constants.sigma = sigma;
    constants.sineAlpha = sineAlpha;
    constants.sineSquaredAlpha = sineSquaredAlpha;
    constants.cosineSquaredAlpha = cosineSquaredAlpha;
    constants.cosineAlpha = cosineAlpha;
    constants.u2Over4 = u2Over4;
    constants.u4Over16 = u4Over16;
    constants.u6Over64 = u6Over64;
    constants.u8Over256 = u8Over256;
    constants.a0 = a0;
    constants.a1 = a1;
    constants.a2 = a2;
    constants.a3 = a3;
    constants.distanceRatio = distanceRatio;
  }

  function computeC(f, cosineSquaredAlpha) {
    return (
      (f * cosineSquaredAlpha * (4.0 + f * (4.0 - 3.0 * cosineSquaredAlpha))) /
      16.0
    );
  }

  function computeDeltaLambda(
    f,
    sineAlpha,
    cosineSquaredAlpha,
    sigma,
    sineSigma,
    cosineSigma,
    cosineTwiceSigmaMidpoint
  ) {
    const C = computeC(f, cosineSquaredAlpha);

    return (
      (1.0 - C) *
      f *
      sineAlpha *
      (sigma +
        C *
          sineSigma *
          (cosineTwiceSigmaMidpoint +
            C *
              cosineSigma *
              (2.0 * cosineTwiceSigmaMidpoint * cosineTwiceSigmaMidpoint - 1.0)))
    );
  }

  function vincentyInverseFormula(
    ellipsoidGeodesic,
    major,
    minor,
    firstLongitude,
    firstLatitude,
    secondLongitude,
    secondLatitude
  ) {
    const eff = (major - minor) / major;
    const l = secondLongitude - firstLongitude;

    const u1 = Math.atan((1 - eff) * Math.tan(firstLatitude));
    const u2 = Math.atan((1 - eff) * Math.tan(secondLatitude));

    const cosineU1 = Math.cos(u1);
    const sineU1 = Math.sin(u1);
    const cosineU2 = Math.cos(u2);
    const sineU2 = Math.sin(u2);

    const cc = cosineU1 * cosineU2;
    const cs = cosineU1 * sineU2;
    const ss = sineU1 * sineU2;
    const sc = sineU1 * cosineU2;

    let lambda = l;
    let lambdaDot = CesiumMath.TWO_PI;

    let cosineLambda = Math.cos(lambda);
    let sineLambda = Math.sin(lambda);

    let sigma;
    let cosineSigma;
    let sineSigma;
    let cosineSquaredAlpha;
    let cosineTwiceSigmaMidpoint;

    do {
      cosineLambda = Math.cos(lambda);
      sineLambda = Math.sin(lambda);

      const temp = cs - sc * cosineLambda;
      sineSigma = Math.sqrt(
        cosineU2 * cosineU2 * sineLambda * sineLambda + temp * temp
      );
      cosineSigma = ss + cc * cosineLambda;

      sigma = Math.atan2(sineSigma, cosineSigma);

      let sineAlpha;

      if (sineSigma === 0.0) {
        sineAlpha = 0.0;
        cosineSquaredAlpha = 1.0;
      } else {
        sineAlpha = (cc * sineLambda) / sineSigma;
        cosineSquaredAlpha = 1.0 - sineAlpha * sineAlpha;
      }

      lambdaDot = lambda;

      cosineTwiceSigmaMidpoint = cosineSigma - (2.0 * ss) / cosineSquaredAlpha;

      if (!isFinite(cosineTwiceSigmaMidpoint)) {
        cosineTwiceSigmaMidpoint = 0.0;
      }

      lambda =
        l +
        computeDeltaLambda(
          eff,
          sineAlpha,
          cosineSquaredAlpha,
          sigma,
          sineSigma,
          cosineSigma,
          cosineTwiceSigmaMidpoint
        );
    } while (Math.abs(lambda - lambdaDot) > CesiumMath.EPSILON12);

    const uSquared =
      (cosineSquaredAlpha * (major * major - minor * minor)) / (minor * minor);
    const A =
      1.0 +
      (uSquared *
        (4096.0 + uSquared * (uSquared * (320.0 - 175.0 * uSquared) - 768.0))) /
        16384.0;
    const B =
      (uSquared *
        (256.0 + uSquared * (uSquared * (74.0 - 47.0 * uSquared) - 128.0))) /
      1024.0;

    const cosineSquaredTwiceSigmaMidpoint =
      cosineTwiceSigmaMidpoint * cosineTwiceSigmaMidpoint;
    const deltaSigma =
      B *
      sineSigma *
      (cosineTwiceSigmaMidpoint +
        (B *
          (cosineSigma * (2.0 * cosineSquaredTwiceSigmaMidpoint - 1.0) -
            (B *
              cosineTwiceSigmaMidpoint *
              (4.0 * sineSigma * sineSigma - 3.0) *
              (4.0 * cosineSquaredTwiceSigmaMidpoint - 3.0)) /
              6.0)) /
          4.0);

    const distance = minor * A * (sigma - deltaSigma);

    const startHeading = Math.atan2(
      cosineU2 * sineLambda,
      cs - sc * cosineLambda
    );
    const endHeading = Math.atan2(cosineU1 * sineLambda, cs * cosineLambda - sc);

    ellipsoidGeodesic._distance = distance;
    ellipsoidGeodesic._startHeading = startHeading;
    ellipsoidGeodesic._endHeading = endHeading;
    ellipsoidGeodesic._uSquared = uSquared;
  }

  const scratchCart1 = new Cartesian3();
  const scratchCart2$1 = new Cartesian3();
  function computeProperties(ellipsoidGeodesic, start, end, ellipsoid) {
    const firstCartesian = Cartesian3.normalize(
      ellipsoid.cartographicToCartesian(start, scratchCart2$1),
      scratchCart1
    );
    const lastCartesian = Cartesian3.normalize(
      ellipsoid.cartographicToCartesian(end, scratchCart2$1),
      scratchCart2$1
    );

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number.greaterThanOrEquals(
      "value",
      Math.abs(
        Math.abs(Cartesian3.angleBetween(firstCartesian, lastCartesian)) - Math.PI
      ),
      0.0125
    );
    //>>includeEnd('debug');

    vincentyInverseFormula(
      ellipsoidGeodesic,
      ellipsoid.maximumRadius,
      ellipsoid.minimumRadius,
      start.longitude,
      start.latitude,
      end.longitude,
      end.latitude
    );

    ellipsoidGeodesic._start = Cartographic.clone(
      start,
      ellipsoidGeodesic._start
    );
    ellipsoidGeodesic._end = Cartographic.clone(end, ellipsoidGeodesic._end);
    ellipsoidGeodesic._start.height = 0;
    ellipsoidGeodesic._end.height = 0;

    setConstants(ellipsoidGeodesic);
  }

  /**
   * Initializes a geodesic on the ellipsoid connecting the two provided planetodetic points.
   *
   * @alias EllipsoidGeodesic
   * @constructor
   *
   * @param {Cartographic} [start] The initial planetodetic point on the path.
   * @param {Cartographic} [end] The final planetodetic point on the path.
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the geodesic lies.
   */
  function EllipsoidGeodesic(start, end, ellipsoid) {
    const e = defaultValue(ellipsoid, Ellipsoid.WGS84);
    this._ellipsoid = e;
    this._start = new Cartographic();
    this._end = new Cartographic();

    this._constants = {};
    this._startHeading = undefined;
    this._endHeading = undefined;
    this._distance = undefined;
    this._uSquared = undefined;

    if (defined(start) && defined(end)) {
      computeProperties(this, start, end, e);
    }
  }

  Object.defineProperties(EllipsoidGeodesic.prototype, {
    /**
     * Gets the ellipsoid.
     * @memberof EllipsoidGeodesic.prototype
     * @type {Ellipsoid}
     * @readonly
     */
    ellipsoid: {
      get: function () {
        return this._ellipsoid;
      },
    },

    /**
     * Gets the surface distance between the start and end point
     * @memberof EllipsoidGeodesic.prototype
     * @type {Number}
     * @readonly
     */
    surfaceDistance: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        Check.defined("distance", this._distance);
        //>>includeEnd('debug');

        return this._distance;
      },
    },

    /**
     * Gets the initial planetodetic point on the path.
     * @memberof EllipsoidGeodesic.prototype
     * @type {Cartographic}
     * @readonly
     */
    start: {
      get: function () {
        return this._start;
      },
    },

    /**
     * Gets the final planetodetic point on the path.
     * @memberof EllipsoidGeodesic.prototype
     * @type {Cartographic}
     * @readonly
     */
    end: {
      get: function () {
        return this._end;
      },
    },

    /**
     * Gets the heading at the initial point.
     * @memberof EllipsoidGeodesic.prototype
     * @type {Number}
     * @readonly
     */
    startHeading: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        Check.defined("distance", this._distance);
        //>>includeEnd('debug');

        return this._startHeading;
      },
    },

    /**
     * Gets the heading at the final point.
     * @memberof EllipsoidGeodesic.prototype
     * @type {Number}
     * @readonly
     */
    endHeading: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        Check.defined("distance", this._distance);
        //>>includeEnd('debug');

        return this._endHeading;
      },
    },
  });

  /**
   * Sets the start and end points of the geodesic
   *
   * @param {Cartographic} start The initial planetodetic point on the path.
   * @param {Cartographic} end The final planetodetic point on the path.
   */
  EllipsoidGeodesic.prototype.setEndPoints = function (start, end) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("start", start);
    Check.defined("end", end);
    //>>includeEnd('debug');

    computeProperties(this, start, end, this._ellipsoid);
  };

  /**
   * Provides the location of a point at the indicated portion along the geodesic.
   *
   * @param {Number} fraction The portion of the distance between the initial and final points.
   * @param {Cartographic} [result] The object in which to store the result.
   * @returns {Cartographic} The location of the point along the geodesic.
   */
  EllipsoidGeodesic.prototype.interpolateUsingFraction = function (
    fraction,
    result
  ) {
    return this.interpolateUsingSurfaceDistance(
      this._distance * fraction,
      result
    );
  };

  /**
   * Provides the location of a point at the indicated distance along the geodesic.
   *
   * @param {Number} distance The distance from the inital point to the point of interest along the geodesic
   * @param {Cartographic} [result] The object in which to store the result.
   * @returns {Cartographic} The location of the point along the geodesic.
   *
   * @exception {DeveloperError} start and end must be set before calling function interpolateUsingSurfaceDistance
   */
  EllipsoidGeodesic.prototype.interpolateUsingSurfaceDistance = function (
    distance,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("distance", this._distance);
    //>>includeEnd('debug');

    const constants = this._constants;

    const s = constants.distanceRatio + distance / constants.b;

    const cosine2S = Math.cos(2.0 * s);
    const cosine4S = Math.cos(4.0 * s);
    const cosine6S = Math.cos(6.0 * s);
    const sine2S = Math.sin(2.0 * s);
    const sine4S = Math.sin(4.0 * s);
    const sine6S = Math.sin(6.0 * s);
    const sine8S = Math.sin(8.0 * s);

    const s2 = s * s;
    const s3 = s * s2;

    const u8Over256 = constants.u8Over256;
    const u2Over4 = constants.u2Over4;
    const u6Over64 = constants.u6Over64;
    const u4Over16 = constants.u4Over16;
    let sigma =
      (2.0 * s3 * u8Over256 * cosine2S) / 3.0 +
      s *
        (1.0 -
          u2Over4 +
          (7.0 * u4Over16) / 4.0 -
          (15.0 * u6Over64) / 4.0 +
          (579.0 * u8Over256) / 64.0 -
          (u4Over16 - (15.0 * u6Over64) / 4.0 + (187.0 * u8Over256) / 16.0) *
            cosine2S -
          ((5.0 * u6Over64) / 4.0 - (115.0 * u8Over256) / 16.0) * cosine4S -
          (29.0 * u8Over256 * cosine6S) / 16.0) +
      (u2Over4 / 2.0 -
        u4Over16 +
        (71.0 * u6Over64) / 32.0 -
        (85.0 * u8Over256) / 16.0) *
        sine2S +
      ((5.0 * u4Over16) / 16.0 -
        (5.0 * u6Over64) / 4.0 +
        (383.0 * u8Over256) / 96.0) *
        sine4S -
      s2 *
        ((u6Over64 - (11.0 * u8Over256) / 2.0) * sine2S +
          (5.0 * u8Over256 * sine4S) / 2.0) +
      ((29.0 * u6Over64) / 96.0 - (29.0 * u8Over256) / 16.0) * sine6S +
      (539.0 * u8Over256 * sine8S) / 1536.0;

    const theta = Math.asin(Math.sin(sigma) * constants.cosineAlpha);
    const latitude = Math.atan((constants.a / constants.b) * Math.tan(theta));

    // Redefine in terms of relative argument of latitude.
    sigma = sigma - constants.sigma;

    const cosineTwiceSigmaMidpoint = Math.cos(2.0 * constants.sigma + sigma);

    const sineSigma = Math.sin(sigma);
    const cosineSigma = Math.cos(sigma);

    const cc = constants.cosineU * cosineSigma;
    const ss = constants.sineU * sineSigma;

    const lambda = Math.atan2(
      sineSigma * constants.sineHeading,
      cc - ss * constants.cosineHeading
    );

    const l =
      lambda -
      computeDeltaLambda(
        constants.f,
        constants.sineAlpha,
        constants.cosineSquaredAlpha,
        sigma,
        sineSigma,
        cosineSigma,
        cosineTwiceSigmaMidpoint
      );

    if (defined(result)) {
      result.longitude = this._start.longitude + l;
      result.latitude = latitude;
      result.height = 0.0;
      return result;
    }

    return new Cartographic(this._start.longitude + l, latitude, 0.0);
  };

  /**
   * @private
   */
  const PolylinePipeline = {};

  PolylinePipeline.numberOfPoints = function (p0, p1, minDistance) {
    const distance = Cartesian3.distance(p0, p1);
    return Math.ceil(distance / minDistance);
  };

  PolylinePipeline.numberOfPointsRhumbLine = function (p0, p1, granularity) {
    const radiansDistanceSquared =
      Math.pow(p0.longitude - p1.longitude, 2) +
      Math.pow(p0.latitude - p1.latitude, 2);

    return Math.max(
      1,
      Math.ceil(Math.sqrt(radiansDistanceSquared / (granularity * granularity)))
    );
  };

  const cartoScratch$2 = new Cartographic();
  PolylinePipeline.extractHeights = function (positions, ellipsoid) {
    const length = positions.length;
    const heights = new Array(length);
    for (let i = 0; i < length; i++) {
      const p = positions[i];
      heights[i] = ellipsoid.cartesianToCartographic(p, cartoScratch$2).height;
    }
    return heights;
  };

  const wrapLongitudeInversMatrix = new Matrix4();
  const wrapLongitudeOrigin = new Cartesian3();
  const wrapLongitudeXZNormal = new Cartesian3();
  const wrapLongitudeXZPlane = new Plane(Cartesian3.UNIT_X, 0.0);
  const wrapLongitudeYZNormal = new Cartesian3();
  const wrapLongitudeYZPlane = new Plane(Cartesian3.UNIT_X, 0.0);
  const wrapLongitudeIntersection = new Cartesian3();
  const wrapLongitudeOffset = new Cartesian3();

  const subdivideHeightsScratchArray = [];

  function subdivideHeights$1(numPoints, h0, h1) {
    const heights = subdivideHeightsScratchArray;
    heights.length = numPoints;

    let i;
    if (h0 === h1) {
      for (i = 0; i < numPoints; i++) {
        heights[i] = h0;
      }
      return heights;
    }

    const dHeight = h1 - h0;
    const heightPerVertex = dHeight / numPoints;

    for (i = 0; i < numPoints; i++) {
      const h = h0 + i * heightPerVertex;
      heights[i] = h;
    }

    return heights;
  }

  const carto1 = new Cartographic();
  const carto2 = new Cartographic();
  const cartesian = new Cartesian3();
  const scaleFirst = new Cartesian3();
  const scaleLast = new Cartesian3();
  const ellipsoidGeodesic$1 = new EllipsoidGeodesic();
  let ellipsoidRhumb = new EllipsoidRhumbLine();

  //Returns subdivided line scaled to ellipsoid surface starting at p1 and ending at p2.
  //Result includes p1, but not include p2.  This function is called for a sequence of line segments,
  //and this prevents duplication of end point.
  function generateCartesianArc(
    p0,
    p1,
    minDistance,
    ellipsoid,
    h0,
    h1,
    array,
    offset
  ) {
    const first = ellipsoid.scaleToGeodeticSurface(p0, scaleFirst);
    const last = ellipsoid.scaleToGeodeticSurface(p1, scaleLast);
    const numPoints = PolylinePipeline.numberOfPoints(p0, p1, minDistance);
    const start = ellipsoid.cartesianToCartographic(first, carto1);
    const end = ellipsoid.cartesianToCartographic(last, carto2);
    const heights = subdivideHeights$1(numPoints, h0, h1);

    ellipsoidGeodesic$1.setEndPoints(start, end);
    const surfaceDistanceBetweenPoints =
      ellipsoidGeodesic$1.surfaceDistance / numPoints;

    let index = offset;
    start.height = h0;
    let cart = ellipsoid.cartographicToCartesian(start, cartesian);
    Cartesian3.pack(cart, array, index);
    index += 3;

    for (let i = 1; i < numPoints; i++) {
      const carto = ellipsoidGeodesic$1.interpolateUsingSurfaceDistance(
        i * surfaceDistanceBetweenPoints,
        carto2
      );
      carto.height = heights[i];
      cart = ellipsoid.cartographicToCartesian(carto, cartesian);
      Cartesian3.pack(cart, array, index);
      index += 3;
    }

    return index;
  }

  //Returns subdivided line scaled to ellipsoid surface starting at p1 and ending at p2.
  //Result includes p1, but not include p2.  This function is called for a sequence of line segments,
  //and this prevents duplication of end point.
  function generateCartesianRhumbArc(
    p0,
    p1,
    granularity,
    ellipsoid,
    h0,
    h1,
    array,
    offset
  ) {
    const start = ellipsoid.cartesianToCartographic(p0, carto1);
    const end = ellipsoid.cartesianToCartographic(p1, carto2);
    const numPoints = PolylinePipeline.numberOfPointsRhumbLine(
      start,
      end,
      granularity
    );
    start.height = 0.0;
    end.height = 0.0;
    const heights = subdivideHeights$1(numPoints, h0, h1);

    if (!ellipsoidRhumb.ellipsoid.equals(ellipsoid)) {
      ellipsoidRhumb = new EllipsoidRhumbLine(undefined, undefined, ellipsoid);
    }
    ellipsoidRhumb.setEndPoints(start, end);
    const surfaceDistanceBetweenPoints =
      ellipsoidRhumb.surfaceDistance / numPoints;

    let index = offset;
    start.height = h0;
    let cart = ellipsoid.cartographicToCartesian(start, cartesian);
    Cartesian3.pack(cart, array, index);
    index += 3;

    for (let i = 1; i < numPoints; i++) {
      const carto = ellipsoidRhumb.interpolateUsingSurfaceDistance(
        i * surfaceDistanceBetweenPoints,
        carto2
      );
      carto.height = heights[i];
      cart = ellipsoid.cartographicToCartesian(carto, cartesian);
      Cartesian3.pack(cart, array, index);
      index += 3;
    }

    return index;
  }

  /**
   * Breaks a {@link Polyline} into segments such that it does not cross the &plusmn;180 degree meridian of an ellipsoid.
   *
   * @param {Cartesian3[]} positions The polyline's Cartesian positions.
   * @param {Matrix4} [modelMatrix=Matrix4.IDENTITY] The polyline's model matrix. Assumed to be an affine
   * transformation matrix, where the upper left 3x3 elements are a rotation matrix, and
   * the upper three elements in the fourth column are the translation.  The bottom row is assumed to be [0, 0, 0, 1].
   * The matrix is not verified to be in the proper form.
   * @returns {Object} An object with a <code>positions</code> property that is an array of positions and a
   * <code>segments</code> property.
   *
   *
   * @example
   * const polylines = new Cesium.PolylineCollection();
   * const polyline = polylines.add(...);
   * const positions = polyline.positions;
   * const modelMatrix = polylines.modelMatrix;
   * const segments = Cesium.PolylinePipeline.wrapLongitude(positions, modelMatrix);
   *
   * @see PolygonPipeline.wrapLongitude
   * @see Polyline
   * @see PolylineCollection
   */
  PolylinePipeline.wrapLongitude = function (positions, modelMatrix) {
    const cartesians = [];
    const segments = [];

    if (defined(positions) && positions.length > 0) {
      modelMatrix = defaultValue(modelMatrix, Matrix4.IDENTITY);
      const inverseModelMatrix = Matrix4.inverseTransformation(
        modelMatrix,
        wrapLongitudeInversMatrix
      );

      const origin = Matrix4.multiplyByPoint(
        inverseModelMatrix,
        Cartesian3.ZERO,
        wrapLongitudeOrigin
      );
      const xzNormal = Cartesian3.normalize(
        Matrix4.multiplyByPointAsVector(
          inverseModelMatrix,
          Cartesian3.UNIT_Y,
          wrapLongitudeXZNormal
        ),
        wrapLongitudeXZNormal
      );
      const xzPlane = Plane.fromPointNormal(
        origin,
        xzNormal,
        wrapLongitudeXZPlane
      );
      const yzNormal = Cartesian3.normalize(
        Matrix4.multiplyByPointAsVector(
          inverseModelMatrix,
          Cartesian3.UNIT_X,
          wrapLongitudeYZNormal
        ),
        wrapLongitudeYZNormal
      );
      const yzPlane = Plane.fromPointNormal(
        origin,
        yzNormal,
        wrapLongitudeYZPlane
      );

      let count = 1;
      cartesians.push(Cartesian3.clone(positions[0]));
      let prev = cartesians[0];

      const length = positions.length;
      for (let i = 1; i < length; ++i) {
        const cur = positions[i];

        // intersects the IDL if either endpoint is on the negative side of the yz-plane
        if (
          Plane.getPointDistance(yzPlane, prev) < 0.0 ||
          Plane.getPointDistance(yzPlane, cur) < 0.0
        ) {
          // and intersects the xz-plane
          const intersection = IntersectionTests.lineSegmentPlane(
            prev,
            cur,
            xzPlane,
            wrapLongitudeIntersection
          );
          if (defined(intersection)) {
            // move point on the xz-plane slightly away from the plane
            const offset = Cartesian3.multiplyByScalar(
              xzNormal,
              5.0e-9,
              wrapLongitudeOffset
            );
            if (Plane.getPointDistance(xzPlane, prev) < 0.0) {
              Cartesian3.negate(offset, offset);
            }

            cartesians.push(
              Cartesian3.add(intersection, offset, new Cartesian3())
            );
            segments.push(count + 1);

            Cartesian3.negate(offset, offset);
            cartesians.push(
              Cartesian3.add(intersection, offset, new Cartesian3())
            );
            count = 1;
          }
        }

        cartesians.push(Cartesian3.clone(positions[i]));
        count++;

        prev = cur;
      }

      segments.push(count);
    }

    return {
      positions: cartesians,
      lengths: segments,
    };
  };

  /**
   * Subdivides polyline and raises all points to the specified height.  Returns an array of numbers to represent the positions.
   * @param {Object} options Object with the following properties:
   * @param {Cartesian3[]} options.positions The array of type {Cartesian3} representing positions.
   * @param {Number|Number[]} [options.height=0.0] A number or array of numbers representing the heights of each position.
   * @param {Number} [options.granularity = CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the positions lie.
   * @returns {Number[]} A new array of positions of type {Number} that have been subdivided and raised to the surface of the ellipsoid.
   *
   * @example
   * const positions = Cesium.Cartesian3.fromDegreesArray([
   *   -105.0, 40.0,
   *   -100.0, 38.0,
   *   -105.0, 35.0,
   *   -100.0, 32.0
   * ]);
   * const surfacePositions = Cesium.PolylinePipeline.generateArc({
   *   positons: positions
   * });
   */
  PolylinePipeline.generateArc = function (options) {
    if (!defined(options)) {
      options = {};
    }
    const positions = options.positions;
    //>>includeStart('debug', pragmas.debug);
    if (!defined(positions)) {
      throw new DeveloperError("options.positions is required.");
    }
    //>>includeEnd('debug');

    const length = positions.length;
    const ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);
    let height = defaultValue(options.height, 0);
    const hasHeightArray = Array.isArray(height);

    if (length < 1) {
      return [];
    } else if (length === 1) {
      const p = ellipsoid.scaleToGeodeticSurface(positions[0], scaleFirst);
      height = hasHeightArray ? height[0] : height;
      if (height !== 0) {
        const n = ellipsoid.geodeticSurfaceNormal(p, cartesian);
        Cartesian3.multiplyByScalar(n, height, n);
        Cartesian3.add(p, n, p);
      }

      return [p.x, p.y, p.z];
    }

    let minDistance = options.minDistance;
    if (!defined(minDistance)) {
      const granularity = defaultValue(
        options.granularity,
        CesiumMath.RADIANS_PER_DEGREE
      );
      minDistance = CesiumMath.chordLength(granularity, ellipsoid.maximumRadius);
    }

    let numPoints = 0;
    let i;

    for (i = 0; i < length - 1; i++) {
      numPoints += PolylinePipeline.numberOfPoints(
        positions[i],
        positions[i + 1],
        minDistance
      );
    }

    const arrayLength = (numPoints + 1) * 3;
    const newPositions = new Array(arrayLength);
    let offset = 0;

    for (i = 0; i < length - 1; i++) {
      const p0 = positions[i];
      const p1 = positions[i + 1];

      const h0 = hasHeightArray ? height[i] : height;
      const h1 = hasHeightArray ? height[i + 1] : height;

      offset = generateCartesianArc(
        p0,
        p1,
        minDistance,
        ellipsoid,
        h0,
        h1,
        newPositions,
        offset
      );
    }

    subdivideHeightsScratchArray.length = 0;

    const lastPoint = positions[length - 1];
    const carto = ellipsoid.cartesianToCartographic(lastPoint, carto1);
    carto.height = hasHeightArray ? height[length - 1] : height;
    const cart = ellipsoid.cartographicToCartesian(carto, cartesian);
    Cartesian3.pack(cart, newPositions, arrayLength - 3);

    return newPositions;
  };

  const scratchCartographic0 = new Cartographic();
  const scratchCartographic1$1 = new Cartographic();

  /**
   * Subdivides polyline and raises all points to the specified height using Rhumb lines.  Returns an array of numbers to represent the positions.
   * @param {Object} options Object with the following properties:
   * @param {Cartesian3[]} options.positions The array of type {Cartesian3} representing positions.
   * @param {Number|Number[]} [options.height=0.0] A number or array of numbers representing the heights of each position.
   * @param {Number} [options.granularity = CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the positions lie.
   * @returns {Number[]} A new array of positions of type {Number} that have been subdivided and raised to the surface of the ellipsoid.
   *
   * @example
   * const positions = Cesium.Cartesian3.fromDegreesArray([
   *   -105.0, 40.0,
   *   -100.0, 38.0,
   *   -105.0, 35.0,
   *   -100.0, 32.0
   * ]);
   * const surfacePositions = Cesium.PolylinePipeline.generateRhumbArc({
   *   positons: positions
   * });
   */
  PolylinePipeline.generateRhumbArc = function (options) {
    if (!defined(options)) {
      options = {};
    }
    const positions = options.positions;
    //>>includeStart('debug', pragmas.debug);
    if (!defined(positions)) {
      throw new DeveloperError("options.positions is required.");
    }
    //>>includeEnd('debug');

    const length = positions.length;
    const ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);
    let height = defaultValue(options.height, 0);
    const hasHeightArray = Array.isArray(height);

    if (length < 1) {
      return [];
    } else if (length === 1) {
      const p = ellipsoid.scaleToGeodeticSurface(positions[0], scaleFirst);
      height = hasHeightArray ? height[0] : height;
      if (height !== 0) {
        const n = ellipsoid.geodeticSurfaceNormal(p, cartesian);
        Cartesian3.multiplyByScalar(n, height, n);
        Cartesian3.add(p, n, p);
      }

      return [p.x, p.y, p.z];
    }

    const granularity = defaultValue(
      options.granularity,
      CesiumMath.RADIANS_PER_DEGREE
    );

    let numPoints = 0;
    let i;

    let c0 = ellipsoid.cartesianToCartographic(
      positions[0],
      scratchCartographic0
    );
    let c1;
    for (i = 0; i < length - 1; i++) {
      c1 = ellipsoid.cartesianToCartographic(
        positions[i + 1],
        scratchCartographic1$1
      );
      numPoints += PolylinePipeline.numberOfPointsRhumbLine(c0, c1, granularity);
      c0 = Cartographic.clone(c1, scratchCartographic0);
    }

    const arrayLength = (numPoints + 1) * 3;
    const newPositions = new Array(arrayLength);
    let offset = 0;

    for (i = 0; i < length - 1; i++) {
      const p0 = positions[i];
      const p1 = positions[i + 1];

      const h0 = hasHeightArray ? height[i] : height;
      const h1 = hasHeightArray ? height[i + 1] : height;

      offset = generateCartesianRhumbArc(
        p0,
        p1,
        granularity,
        ellipsoid,
        h0,
        h1,
        newPositions,
        offset
      );
    }

    subdivideHeightsScratchArray.length = 0;

    const lastPoint = positions[length - 1];
    const carto = ellipsoid.cartesianToCartographic(lastPoint, carto1);
    carto.height = hasHeightArray ? height[length - 1] : height;
    const cart = ellipsoid.cartographicToCartesian(carto, cartesian);
    Cartesian3.pack(cart, newPositions, arrayLength - 3);

    return newPositions;
  };

  /**
   * Subdivides polyline and raises all points to the specified height. Returns an array of new {Cartesian3} positions.
   * @param {Object} options Object with the following properties:
   * @param {Cartesian3[]} options.positions The array of type {Cartesian3} representing positions.
   * @param {Number|Number[]} [options.height=0.0] A number or array of numbers representing the heights of each position.
   * @param {Number} [options.granularity = CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the positions lie.
   * @returns {Cartesian3[]} A new array of cartesian3 positions that have been subdivided and raised to the surface of the ellipsoid.
   *
   * @example
   * const positions = Cesium.Cartesian3.fromDegreesArray([
   *   -105.0, 40.0,
   *   -100.0, 38.0,
   *   -105.0, 35.0,
   *   -100.0, 32.0
   * ]);
   * const surfacePositions = Cesium.PolylinePipeline.generateCartesianArc({
   *   positons: positions
   * });
   */
  PolylinePipeline.generateCartesianArc = function (options) {
    const numberArray = PolylinePipeline.generateArc(options);
    const size = numberArray.length / 3;
    const newPositions = new Array(size);
    for (let i = 0; i < size; i++) {
      newPositions[i] = Cartesian3.unpack(numberArray, i * 3);
    }
    return newPositions;
  };

  /**
   * Subdivides polyline and raises all points to the specified height using Rhumb Lines. Returns an array of new {Cartesian3} positions.
   * @param {Object} options Object with the following properties:
   * @param {Cartesian3[]} options.positions The array of type {Cartesian3} representing positions.
   * @param {Number|Number[]} [options.height=0.0] A number or array of numbers representing the heights of each position.
   * @param {Number} [options.granularity = CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the positions lie.
   * @returns {Cartesian3[]} A new array of cartesian3 positions that have been subdivided and raised to the surface of the ellipsoid.
   *
   * @example
   * const positions = Cesium.Cartesian3.fromDegreesArray([
   *   -105.0, 40.0,
   *   -100.0, 38.0,
   *   -105.0, 35.0,
   *   -100.0, 32.0
   * ]);
   * const surfacePositions = Cesium.PolylinePipeline.generateCartesianRhumbArc({
   *   positons: positions
   * });
   */
  PolylinePipeline.generateCartesianRhumbArc = function (options) {
    const numberArray = PolylinePipeline.generateRhumbArc(options);
    const size = numberArray.length / 3;
    const newPositions = new Array(size);
    for (let i = 0; i < size; i++) {
      newPositions[i] = Cartesian3.unpack(numberArray, i * 3);
    }
    return newPositions;
  };

  const warnings = {};

  /**
   * Logs a one time message to the console.  Use this function instead of
   * <code>console.log</code> directly since this does not log duplicate messages
   * unless it is called from multiple workers.
   *
   * @function oneTimeWarning
   *
   * @param {String} identifier The unique identifier for this warning.
   * @param {String} [message=identifier] The message to log to the console.
   *
   * @example
   * for(let i=0;i<foo.length;++i) {
   *    if (!defined(foo[i].bar)) {
   *       // Something that can be recovered from but may happen a lot
   *       oneTimeWarning('foo.bar undefined', 'foo.bar is undefined. Setting to 0.');
   *       foo[i].bar = 0;
   *       // ...
   *    }
   * }
   *
   * @private
   */
  function oneTimeWarning(identifier, message) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(identifier)) {
      throw new DeveloperError("identifier is required.");
    }
    //>>includeEnd('debug');

    if (!defined(warnings[identifier])) {
      warnings[identifier] = true;
      console.warn(defaultValue(message, identifier));
    }
  }

  oneTimeWarning.geometryOutlines =
    "Entity geometry outlines are unsupported on terrain. Outlines will be disabled. To enable outlines, disable geometry terrain clamping by explicitly setting height to 0.";

  oneTimeWarning.geometryZIndex =
    "Entity geometry with zIndex are unsupported when height or extrudedHeight are defined.  zIndex will be ignored";

  oneTimeWarning.geometryHeightReference =
    "Entity corridor, ellipse, polygon or rectangle with heightReference must also have a defined height.  heightReference will be ignored";
  oneTimeWarning.geometryExtrudedHeightReference =
    "Entity corridor, ellipse, polygon or rectangle with extrudedHeightReference must also have a defined extrudedHeight.  extrudedHeightReference will be ignored";

  const scratch2Array = [new Cartesian3(), new Cartesian3()];
  const scratchCartesian1$3 = new Cartesian3();
  const scratchCartesian2$6 = new Cartesian3();
  const scratchCartesian3$7 = new Cartesian3();
  const scratchCartesian4$4 = new Cartesian3();
  const scratchCartesian5$1 = new Cartesian3();
  const scratchCartesian6 = new Cartesian3();
  const scratchCartesian7 = new Cartesian3();
  const scratchCartesian8 = new Cartesian3();
  const scratchCartesian9 = new Cartesian3();

  const scratch1$2 = new Cartesian3();
  const scratch2$2 = new Cartesian3();

  /**
   * @private
   */
  const PolylineVolumeGeometryLibrary = {};

  let cartographic = new Cartographic();
  function scaleToSurface$2(positions, ellipsoid) {
    const heights = new Array(positions.length);
    for (let i = 0; i < positions.length; i++) {
      const pos = positions[i];
      cartographic = ellipsoid.cartesianToCartographic(pos, cartographic);
      heights[i] = cartographic.height;
      positions[i] = ellipsoid.scaleToGeodeticSurface(pos, pos);
    }
    return heights;
  }

  function subdivideHeights(points, h0, h1, granularity) {
    const p0 = points[0];
    const p1 = points[1];
    const angleBetween = Cartesian3.angleBetween(p0, p1);
    const numPoints = Math.ceil(angleBetween / granularity);
    const heights = new Array(numPoints);
    let i;
    if (h0 === h1) {
      for (i = 0; i < numPoints; i++) {
        heights[i] = h0;
      }
      heights.push(h1);
      return heights;
    }

    const dHeight = h1 - h0;
    const heightPerVertex = dHeight / numPoints;

    for (i = 1; i < numPoints; i++) {
      const h = h0 + i * heightPerVertex;
      heights[i] = h;
    }

    heights[0] = h0;
    heights.push(h1);
    return heights;
  }

  const nextScratch = new Cartesian3();
  const prevScratch = new Cartesian3();

  function computeRotationAngle(start, end, position, ellipsoid) {
    const tangentPlane = new EllipsoidTangentPlane(position, ellipsoid);
    const next = tangentPlane.projectPointOntoPlane(
      Cartesian3.add(position, start, nextScratch),
      nextScratch
    );
    const prev = tangentPlane.projectPointOntoPlane(
      Cartesian3.add(position, end, prevScratch),
      prevScratch
    );
    const angle = Cartesian2.angleBetween(next, prev);

    return prev.x * next.y - prev.y * next.x >= 0.0 ? -angle : angle;
  }

  const negativeX = new Cartesian3(-1, 0, 0);
  let transform$2 = new Matrix4();
  const translation$1 = new Matrix4();
  let rotationZ = new Matrix3();
  const scaleMatrix = Matrix3.IDENTITY.clone();
  const westScratch = new Cartesian3();
  const finalPosScratch = new Cartesian4();
  const heightCartesian = new Cartesian3();
  function addPosition(
    center,
    left,
    shape,
    finalPositions,
    ellipsoid,
    height,
    xScalar,
    repeat
  ) {
    let west = westScratch;
    let finalPosition = finalPosScratch;
    transform$2 = Transforms.eastNorthUpToFixedFrame(center, ellipsoid, transform$2);

    west = Matrix4.multiplyByPointAsVector(transform$2, negativeX, west);
    west = Cartesian3.normalize(west, west);
    const angle = computeRotationAngle(west, left, center, ellipsoid);
    rotationZ = Matrix3.fromRotationZ(angle, rotationZ);

    heightCartesian.z = height;
    transform$2 = Matrix4.multiplyTransformation(
      transform$2,
      Matrix4.fromRotationTranslation(rotationZ, heightCartesian, translation$1),
      transform$2
    );
    const scale = scaleMatrix;
    scale[0] = xScalar;

    for (let j = 0; j < repeat; j++) {
      for (let i = 0; i < shape.length; i += 3) {
        finalPosition = Cartesian3.fromArray(shape, i, finalPosition);
        finalPosition = Matrix3.multiplyByVector(
          scale,
          finalPosition,
          finalPosition
        );
        finalPosition = Matrix4.multiplyByPoint(
          transform$2,
          finalPosition,
          finalPosition
        );
        finalPositions.push(finalPosition.x, finalPosition.y, finalPosition.z);
      }
    }

    return finalPositions;
  }

  const centerScratch$4 = new Cartesian3();
  function addPositions(
    centers,
    left,
    shape,
    finalPositions,
    ellipsoid,
    heights,
    xScalar
  ) {
    for (let i = 0; i < centers.length; i += 3) {
      const center = Cartesian3.fromArray(centers, i, centerScratch$4);
      finalPositions = addPosition(
        center,
        left,
        shape,
        finalPositions,
        ellipsoid,
        heights[i / 3],
        xScalar,
        1
      );
    }
    return finalPositions;
  }

  function convertShapeTo3DDuplicate(shape2D, boundingRectangle) {
    //orientate 2D shape to XZ plane center at (0, 0, 0), duplicate points
    const length = shape2D.length;
    const shape = new Array(length * 6);
    let index = 0;
    const xOffset = boundingRectangle.x + boundingRectangle.width / 2;
    const yOffset = boundingRectangle.y + boundingRectangle.height / 2;

    let point = shape2D[0];
    shape[index++] = point.x - xOffset;
    shape[index++] = 0.0;
    shape[index++] = point.y - yOffset;
    for (let i = 1; i < length; i++) {
      point = shape2D[i];
      const x = point.x - xOffset;
      const z = point.y - yOffset;
      shape[index++] = x;
      shape[index++] = 0.0;
      shape[index++] = z;

      shape[index++] = x;
      shape[index++] = 0.0;
      shape[index++] = z;
    }
    point = shape2D[0];
    shape[index++] = point.x - xOffset;
    shape[index++] = 0.0;
    shape[index++] = point.y - yOffset;

    return shape;
  }

  function convertShapeTo3D(shape2D, boundingRectangle) {
    //orientate 2D shape to XZ plane center at (0, 0, 0)
    const length = shape2D.length;
    const shape = new Array(length * 3);
    let index = 0;
    const xOffset = boundingRectangle.x + boundingRectangle.width / 2;
    const yOffset = boundingRectangle.y + boundingRectangle.height / 2;

    for (let i = 0; i < length; i++) {
      shape[index++] = shape2D[i].x - xOffset;
      shape[index++] = 0;
      shape[index++] = shape2D[i].y - yOffset;
    }

    return shape;
  }

  const quaterion$1 = new Quaternion();
  const startPointScratch = new Cartesian3();
  const rotMatrix$1 = new Matrix3();
  function computeRoundCorner$1(
    pivot,
    startPoint,
    endPoint,
    cornerType,
    leftIsOutside,
    ellipsoid,
    finalPositions,
    shape,
    height,
    duplicatePoints
  ) {
    const angle = Cartesian3.angleBetween(
      Cartesian3.subtract(startPoint, pivot, scratch1$2),
      Cartesian3.subtract(endPoint, pivot, scratch2$2)
    );
    const granularity =
      cornerType === CornerType$1.BEVELED
        ? 0
        : Math.ceil(angle / CesiumMath.toRadians(5));

    let m;
    if (leftIsOutside) {
      m = Matrix3.fromQuaternion(
        Quaternion.fromAxisAngle(
          Cartesian3.negate(pivot, scratch1$2),
          angle / (granularity + 1),
          quaterion$1
        ),
        rotMatrix$1
      );
    } else {
      m = Matrix3.fromQuaternion(
        Quaternion.fromAxisAngle(pivot, angle / (granularity + 1), quaterion$1),
        rotMatrix$1
      );
    }

    let left;
    let surfacePoint;
    startPoint = Cartesian3.clone(startPoint, startPointScratch);
    if (granularity > 0) {
      const repeat = duplicatePoints ? 2 : 1;
      for (let i = 0; i < granularity; i++) {
        startPoint = Matrix3.multiplyByVector(m, startPoint, startPoint);
        left = Cartesian3.subtract(startPoint, pivot, scratch1$2);
        left = Cartesian3.normalize(left, left);
        if (!leftIsOutside) {
          left = Cartesian3.negate(left, left);
        }
        surfacePoint = ellipsoid.scaleToGeodeticSurface(startPoint, scratch2$2);
        finalPositions = addPosition(
          surfacePoint,
          left,
          shape,
          finalPositions,
          ellipsoid,
          height,
          1,
          repeat
        );
      }
    } else {
      left = Cartesian3.subtract(startPoint, pivot, scratch1$2);
      left = Cartesian3.normalize(left, left);
      if (!leftIsOutside) {
        left = Cartesian3.negate(left, left);
      }
      surfacePoint = ellipsoid.scaleToGeodeticSurface(startPoint, scratch2$2);
      finalPositions = addPosition(
        surfacePoint,
        left,
        shape,
        finalPositions,
        ellipsoid,
        height,
        1,
        1
      );

      endPoint = Cartesian3.clone(endPoint, startPointScratch);
      left = Cartesian3.subtract(endPoint, pivot, scratch1$2);
      left = Cartesian3.normalize(left, left);
      if (!leftIsOutside) {
        left = Cartesian3.negate(left, left);
      }
      surfacePoint = ellipsoid.scaleToGeodeticSurface(endPoint, scratch2$2);
      finalPositions = addPosition(
        surfacePoint,
        left,
        shape,
        finalPositions,
        ellipsoid,
        height,
        1,
        1
      );
    }

    return finalPositions;
  }

  PolylineVolumeGeometryLibrary.removeDuplicatesFromShape = function (
    shapePositions
  ) {
    const length = shapePositions.length;
    const cleanedPositions = [];
    for (let i0 = length - 1, i1 = 0; i1 < length; i0 = i1++) {
      const v0 = shapePositions[i0];
      const v1 = shapePositions[i1];

      if (!Cartesian2.equals(v0, v1)) {
        cleanedPositions.push(v1); // Shallow copy!
      }
    }

    return cleanedPositions;
  };

  PolylineVolumeGeometryLibrary.angleIsGreaterThanPi = function (
    forward,
    backward,
    position,
    ellipsoid
  ) {
    const tangentPlane = new EllipsoidTangentPlane(position, ellipsoid);
    const next = tangentPlane.projectPointOntoPlane(
      Cartesian3.add(position, forward, nextScratch),
      nextScratch
    );
    const prev = tangentPlane.projectPointOntoPlane(
      Cartesian3.add(position, backward, prevScratch),
      prevScratch
    );

    return prev.x * next.y - prev.y * next.x >= 0.0;
  };

  const scratchForwardProjection$1 = new Cartesian3();
  const scratchBackwardProjection$1 = new Cartesian3();

  PolylineVolumeGeometryLibrary.computePositions = function (
    positions,
    shape2D,
    boundingRectangle,
    geometry,
    duplicatePoints
  ) {
    const ellipsoid = geometry._ellipsoid;
    const heights = scaleToSurface$2(positions, ellipsoid);
    const granularity = geometry._granularity;
    const cornerType = geometry._cornerType;
    const shapeForSides = duplicatePoints
      ? convertShapeTo3DDuplicate(shape2D, boundingRectangle)
      : convertShapeTo3D(shape2D, boundingRectangle);
    const shapeForEnds = duplicatePoints
      ? convertShapeTo3D(shape2D, boundingRectangle)
      : undefined;
    const heightOffset = boundingRectangle.height / 2;
    const width = boundingRectangle.width / 2;
    let length = positions.length;
    let finalPositions = [];
    let ends = duplicatePoints ? [] : undefined;

    let forward = scratchCartesian1$3;
    let backward = scratchCartesian2$6;
    let cornerDirection = scratchCartesian3$7;
    let surfaceNormal = scratchCartesian4$4;
    let pivot = scratchCartesian5$1;
    let start = scratchCartesian6;
    let end = scratchCartesian7;
    let left = scratchCartesian8;
    let previousPosition = scratchCartesian9;

    let position = positions[0];
    let nextPosition = positions[1];
    surfaceNormal = ellipsoid.geodeticSurfaceNormal(position, surfaceNormal);
    forward = Cartesian3.subtract(nextPosition, position, forward);
    forward = Cartesian3.normalize(forward, forward);
    left = Cartesian3.cross(surfaceNormal, forward, left);
    left = Cartesian3.normalize(left, left);
    let h0 = heights[0];
    let h1 = heights[1];
    if (duplicatePoints) {
      ends = addPosition(
        position,
        left,
        shapeForEnds,
        ends,
        ellipsoid,
        h0 + heightOffset,
        1,
        1
      );
    }
    previousPosition = Cartesian3.clone(position, previousPosition);
    position = nextPosition;
    backward = Cartesian3.negate(forward, backward);
    let subdividedHeights;
    let subdividedPositions;
    for (let i = 1; i < length - 1; i++) {
      const repeat = duplicatePoints ? 2 : 1;
      nextPosition = positions[i + 1];
      if (position.equals(nextPosition)) {
        oneTimeWarning(
          "Positions are too close and are considered equivalent with rounding error."
        );
        continue;
      }
      forward = Cartesian3.subtract(nextPosition, position, forward);
      forward = Cartesian3.normalize(forward, forward);
      cornerDirection = Cartesian3.add(forward, backward, cornerDirection);
      cornerDirection = Cartesian3.normalize(cornerDirection, cornerDirection);
      surfaceNormal = ellipsoid.geodeticSurfaceNormal(position, surfaceNormal);

      const forwardProjection = Cartesian3.multiplyByScalar(
        surfaceNormal,
        Cartesian3.dot(forward, surfaceNormal),
        scratchForwardProjection$1
      );
      Cartesian3.subtract(forward, forwardProjection, forwardProjection);
      Cartesian3.normalize(forwardProjection, forwardProjection);

      const backwardProjection = Cartesian3.multiplyByScalar(
        surfaceNormal,
        Cartesian3.dot(backward, surfaceNormal),
        scratchBackwardProjection$1
      );
      Cartesian3.subtract(backward, backwardProjection, backwardProjection);
      Cartesian3.normalize(backwardProjection, backwardProjection);

      const doCorner = !CesiumMath.equalsEpsilon(
        Math.abs(Cartesian3.dot(forwardProjection, backwardProjection)),
        1.0,
        CesiumMath.EPSILON7
      );

      if (doCorner) {
        cornerDirection = Cartesian3.cross(
          cornerDirection,
          surfaceNormal,
          cornerDirection
        );
        cornerDirection = Cartesian3.cross(
          surfaceNormal,
          cornerDirection,
          cornerDirection
        );
        cornerDirection = Cartesian3.normalize(cornerDirection, cornerDirection);
        const scalar =
          1 /
          Math.max(
            0.25,
            Cartesian3.magnitude(
              Cartesian3.cross(cornerDirection, backward, scratch1$2)
            )
          );
        const leftIsOutside = PolylineVolumeGeometryLibrary.angleIsGreaterThanPi(
          forward,
          backward,
          position,
          ellipsoid
        );
        if (leftIsOutside) {
          pivot = Cartesian3.add(
            position,
            Cartesian3.multiplyByScalar(
              cornerDirection,
              scalar * width,
              cornerDirection
            ),
            pivot
          );
          start = Cartesian3.add(
            pivot,
            Cartesian3.multiplyByScalar(left, width, start),
            start
          );
          scratch2Array[0] = Cartesian3.clone(previousPosition, scratch2Array[0]);
          scratch2Array[1] = Cartesian3.clone(start, scratch2Array[1]);
          subdividedHeights = subdivideHeights(
            scratch2Array,
            h0 + heightOffset,
            h1 + heightOffset,
            granularity
          );
          subdividedPositions = PolylinePipeline.generateArc({
            positions: scratch2Array,
            granularity: granularity,
            ellipsoid: ellipsoid,
          });
          finalPositions = addPositions(
            subdividedPositions,
            left,
            shapeForSides,
            finalPositions,
            ellipsoid,
            subdividedHeights,
            1
          );
          left = Cartesian3.cross(surfaceNormal, forward, left);
          left = Cartesian3.normalize(left, left);
          end = Cartesian3.add(
            pivot,
            Cartesian3.multiplyByScalar(left, width, end),
            end
          );
          if (
            cornerType === CornerType$1.ROUNDED ||
            cornerType === CornerType$1.BEVELED
          ) {
            computeRoundCorner$1(
              pivot,
              start,
              end,
              cornerType,
              leftIsOutside,
              ellipsoid,
              finalPositions,
              shapeForSides,
              h1 + heightOffset,
              duplicatePoints
            );
          } else {
            cornerDirection = Cartesian3.negate(cornerDirection, cornerDirection);
            finalPositions = addPosition(
              position,
              cornerDirection,
              shapeForSides,
              finalPositions,
              ellipsoid,
              h1 + heightOffset,
              scalar,
              repeat
            );
          }
          previousPosition = Cartesian3.clone(end, previousPosition);
        } else {
          pivot = Cartesian3.add(
            position,
            Cartesian3.multiplyByScalar(
              cornerDirection,
              scalar * width,
              cornerDirection
            ),
            pivot
          );
          start = Cartesian3.add(
            pivot,
            Cartesian3.multiplyByScalar(left, -width, start),
            start
          );
          scratch2Array[0] = Cartesian3.clone(previousPosition, scratch2Array[0]);
          scratch2Array[1] = Cartesian3.clone(start, scratch2Array[1]);
          subdividedHeights = subdivideHeights(
            scratch2Array,
            h0 + heightOffset,
            h1 + heightOffset,
            granularity
          );
          subdividedPositions = PolylinePipeline.generateArc({
            positions: scratch2Array,
            granularity: granularity,
            ellipsoid: ellipsoid,
          });
          finalPositions = addPositions(
            subdividedPositions,
            left,
            shapeForSides,
            finalPositions,
            ellipsoid,
            subdividedHeights,
            1
          );
          left = Cartesian3.cross(surfaceNormal, forward, left);
          left = Cartesian3.normalize(left, left);
          end = Cartesian3.add(
            pivot,
            Cartesian3.multiplyByScalar(left, -width, end),
            end
          );
          if (
            cornerType === CornerType$1.ROUNDED ||
            cornerType === CornerType$1.BEVELED
          ) {
            computeRoundCorner$1(
              pivot,
              start,
              end,
              cornerType,
              leftIsOutside,
              ellipsoid,
              finalPositions,
              shapeForSides,
              h1 + heightOffset,
              duplicatePoints
            );
          } else {
            finalPositions = addPosition(
              position,
              cornerDirection,
              shapeForSides,
              finalPositions,
              ellipsoid,
              h1 + heightOffset,
              scalar,
              repeat
            );
          }
          previousPosition = Cartesian3.clone(end, previousPosition);
        }
        backward = Cartesian3.negate(forward, backward);
      } else {
        finalPositions = addPosition(
          previousPosition,
          left,
          shapeForSides,
          finalPositions,
          ellipsoid,
          h0 + heightOffset,
          1,
          1
        );
        previousPosition = position;
      }
      h0 = h1;
      h1 = heights[i + 1];
      position = nextPosition;
    }

    scratch2Array[0] = Cartesian3.clone(previousPosition, scratch2Array[0]);
    scratch2Array[1] = Cartesian3.clone(position, scratch2Array[1]);
    subdividedHeights = subdivideHeights(
      scratch2Array,
      h0 + heightOffset,
      h1 + heightOffset,
      granularity
    );
    subdividedPositions = PolylinePipeline.generateArc({
      positions: scratch2Array,
      granularity: granularity,
      ellipsoid: ellipsoid,
    });
    finalPositions = addPositions(
      subdividedPositions,
      left,
      shapeForSides,
      finalPositions,
      ellipsoid,
      subdividedHeights,
      1
    );
    if (duplicatePoints) {
      ends = addPosition(
        position,
        left,
        shapeForEnds,
        ends,
        ellipsoid,
        h1 + heightOffset,
        1,
        1
      );
    }

    length = finalPositions.length;
    const posLength = duplicatePoints ? length + ends.length : length;
    const combinedPositions = new Float64Array(posLength);
    combinedPositions.set(finalPositions);
    if (duplicatePoints) {
      combinedPositions.set(ends, length);
    }

    return combinedPositions;
  };

  /**
   * @private
   */
  const CorridorGeometryLibrary = {};

  const scratch1$1 = new Cartesian3();
  const scratch2$1 = new Cartesian3();
  const scratch3 = new Cartesian3();
  const scratch4 = new Cartesian3();

  const scaleArray2 = [new Cartesian3(), new Cartesian3()];

  const cartesian1$2 = new Cartesian3();
  const cartesian2$2 = new Cartesian3();
  const cartesian3$2 = new Cartesian3();
  const cartesian4$1 = new Cartesian3();
  const cartesian5$1 = new Cartesian3();
  const cartesian6$1 = new Cartesian3();
  const cartesian7 = new Cartesian3();
  const cartesian8 = new Cartesian3();
  const cartesian9 = new Cartesian3();
  const cartesian10 = new Cartesian3();

  const quaterion = new Quaternion();
  const rotMatrix = new Matrix3();
  function computeRoundCorner(
    cornerPoint,
    startPoint,
    endPoint,
    cornerType,
    leftIsOutside
  ) {
    const angle = Cartesian3.angleBetween(
      Cartesian3.subtract(startPoint, cornerPoint, scratch1$1),
      Cartesian3.subtract(endPoint, cornerPoint, scratch2$1)
    );
    const granularity =
      cornerType === CornerType$1.BEVELED
        ? 1
        : Math.ceil(angle / CesiumMath.toRadians(5)) + 1;

    const size = granularity * 3;
    const array = new Array(size);

    array[size - 3] = endPoint.x;
    array[size - 2] = endPoint.y;
    array[size - 1] = endPoint.z;

    let m;
    if (leftIsOutside) {
      m = Matrix3.fromQuaternion(
        Quaternion.fromAxisAngle(
          Cartesian3.negate(cornerPoint, scratch1$1),
          angle / granularity,
          quaterion
        ),
        rotMatrix
      );
    } else {
      m = Matrix3.fromQuaternion(
        Quaternion.fromAxisAngle(cornerPoint, angle / granularity, quaterion),
        rotMatrix
      );
    }

    let index = 0;
    startPoint = Cartesian3.clone(startPoint, scratch1$1);
    for (let i = 0; i < granularity; i++) {
      startPoint = Matrix3.multiplyByVector(m, startPoint, startPoint);
      array[index++] = startPoint.x;
      array[index++] = startPoint.y;
      array[index++] = startPoint.z;
    }

    return array;
  }

  function addEndCaps(calculatedPositions) {
    let cornerPoint = cartesian1$2;
    let startPoint = cartesian2$2;
    let endPoint = cartesian3$2;

    let leftEdge = calculatedPositions[1];
    startPoint = Cartesian3.fromArray(
      calculatedPositions[1],
      leftEdge.length - 3,
      startPoint
    );
    endPoint = Cartesian3.fromArray(calculatedPositions[0], 0, endPoint);
    cornerPoint = Cartesian3.midpoint(startPoint, endPoint, cornerPoint);
    const firstEndCap = computeRoundCorner(
      cornerPoint,
      startPoint,
      endPoint,
      CornerType$1.ROUNDED,
      false
    );

    const length = calculatedPositions.length - 1;
    const rightEdge = calculatedPositions[length - 1];
    leftEdge = calculatedPositions[length];
    startPoint = Cartesian3.fromArray(
      rightEdge,
      rightEdge.length - 3,
      startPoint
    );
    endPoint = Cartesian3.fromArray(leftEdge, 0, endPoint);
    cornerPoint = Cartesian3.midpoint(startPoint, endPoint, cornerPoint);
    const lastEndCap = computeRoundCorner(
      cornerPoint,
      startPoint,
      endPoint,
      CornerType$1.ROUNDED,
      false
    );

    return [firstEndCap, lastEndCap];
  }

  function computeMiteredCorner(
    position,
    leftCornerDirection,
    lastPoint,
    leftIsOutside
  ) {
    let cornerPoint = scratch1$1;
    if (leftIsOutside) {
      cornerPoint = Cartesian3.add(position, leftCornerDirection, cornerPoint);
    } else {
      leftCornerDirection = Cartesian3.negate(
        leftCornerDirection,
        leftCornerDirection
      );
      cornerPoint = Cartesian3.add(position, leftCornerDirection, cornerPoint);
    }
    return [
      cornerPoint.x,
      cornerPoint.y,
      cornerPoint.z,
      lastPoint.x,
      lastPoint.y,
      lastPoint.z,
    ];
  }

  function addShiftedPositions(positions, left, scalar, calculatedPositions) {
    const rightPositions = new Array(positions.length);
    const leftPositions = new Array(positions.length);
    const scaledLeft = Cartesian3.multiplyByScalar(left, scalar, scratch1$1);
    const scaledRight = Cartesian3.negate(scaledLeft, scratch2$1);
    let rightIndex = 0;
    let leftIndex = positions.length - 1;

    for (let i = 0; i < positions.length; i += 3) {
      const pos = Cartesian3.fromArray(positions, i, scratch3);
      const rightPos = Cartesian3.add(pos, scaledRight, scratch4);
      rightPositions[rightIndex++] = rightPos.x;
      rightPositions[rightIndex++] = rightPos.y;
      rightPositions[rightIndex++] = rightPos.z;

      const leftPos = Cartesian3.add(pos, scaledLeft, scratch4);
      leftPositions[leftIndex--] = leftPos.z;
      leftPositions[leftIndex--] = leftPos.y;
      leftPositions[leftIndex--] = leftPos.x;
    }
    calculatedPositions.push(rightPositions, leftPositions);

    return calculatedPositions;
  }

  /**
   * @private
   */
  CorridorGeometryLibrary.addAttribute = function (
    attribute,
    value,
    front,
    back
  ) {
    const x = value.x;
    const y = value.y;
    const z = value.z;
    if (defined(front)) {
      attribute[front] = x;
      attribute[front + 1] = y;
      attribute[front + 2] = z;
    }
    if (defined(back)) {
      attribute[back] = z;
      attribute[back - 1] = y;
      attribute[back - 2] = x;
    }
  };

  const scratchForwardProjection = new Cartesian3();
  const scratchBackwardProjection = new Cartesian3();

  /**
   * @private
   */
  CorridorGeometryLibrary.computePositions = function (params) {
    const granularity = params.granularity;
    const positions = params.positions;
    const ellipsoid = params.ellipsoid;
    const width = params.width / 2;
    const cornerType = params.cornerType;
    const saveAttributes = params.saveAttributes;
    let normal = cartesian1$2;
    let forward = cartesian2$2;
    let backward = cartesian3$2;
    let left = cartesian4$1;
    let cornerDirection = cartesian5$1;
    let startPoint = cartesian6$1;
    let previousPos = cartesian7;
    let rightPos = cartesian8;
    let leftPos = cartesian9;
    let center = cartesian10;
    let calculatedPositions = [];
    const calculatedLefts = saveAttributes ? [] : undefined;
    const calculatedNormals = saveAttributes ? [] : undefined;
    let position = positions[0]; //add first point
    let nextPosition = positions[1];

    forward = Cartesian3.normalize(
      Cartesian3.subtract(nextPosition, position, forward),
      forward
    );
    normal = ellipsoid.geodeticSurfaceNormal(position, normal);
    left = Cartesian3.normalize(Cartesian3.cross(normal, forward, left), left);
    if (saveAttributes) {
      calculatedLefts.push(left.x, left.y, left.z);
      calculatedNormals.push(normal.x, normal.y, normal.z);
    }
    previousPos = Cartesian3.clone(position, previousPos);
    position = nextPosition;
    backward = Cartesian3.negate(forward, backward);

    let subdividedPositions;
    const corners = [];
    let i;
    const length = positions.length;
    for (i = 1; i < length - 1; i++) {
      // add middle points and corners
      normal = ellipsoid.geodeticSurfaceNormal(position, normal);
      nextPosition = positions[i + 1];
      forward = Cartesian3.normalize(
        Cartesian3.subtract(nextPosition, position, forward),
        forward
      );
      cornerDirection = Cartesian3.normalize(
        Cartesian3.add(forward, backward, cornerDirection),
        cornerDirection
      );

      const forwardProjection = Cartesian3.multiplyByScalar(
        normal,
        Cartesian3.dot(forward, normal),
        scratchForwardProjection
      );
      Cartesian3.subtract(forward, forwardProjection, forwardProjection);
      Cartesian3.normalize(forwardProjection, forwardProjection);

      const backwardProjection = Cartesian3.multiplyByScalar(
        normal,
        Cartesian3.dot(backward, normal),
        scratchBackwardProjection
      );
      Cartesian3.subtract(backward, backwardProjection, backwardProjection);
      Cartesian3.normalize(backwardProjection, backwardProjection);

      const doCorner = !CesiumMath.equalsEpsilon(
        Math.abs(Cartesian3.dot(forwardProjection, backwardProjection)),
        1.0,
        CesiumMath.EPSILON7
      );

      if (doCorner) {
        cornerDirection = Cartesian3.cross(
          cornerDirection,
          normal,
          cornerDirection
        );
        cornerDirection = Cartesian3.cross(
          normal,
          cornerDirection,
          cornerDirection
        );
        cornerDirection = Cartesian3.normalize(cornerDirection, cornerDirection);
        const scalar =
          width /
          Math.max(
            0.25,
            Cartesian3.magnitude(
              Cartesian3.cross(cornerDirection, backward, scratch1$1)
            )
          );
        const leftIsOutside = PolylineVolumeGeometryLibrary.angleIsGreaterThanPi(
          forward,
          backward,
          position,
          ellipsoid
        );
        cornerDirection = Cartesian3.multiplyByScalar(
          cornerDirection,
          scalar,
          cornerDirection
        );
        if (leftIsOutside) {
          rightPos = Cartesian3.add(position, cornerDirection, rightPos);
          center = Cartesian3.add(
            rightPos,
            Cartesian3.multiplyByScalar(left, width, center),
            center
          );
          leftPos = Cartesian3.add(
            rightPos,
            Cartesian3.multiplyByScalar(left, width * 2, leftPos),
            leftPos
          );
          scaleArray2[0] = Cartesian3.clone(previousPos, scaleArray2[0]);
          scaleArray2[1] = Cartesian3.clone(center, scaleArray2[1]);
          subdividedPositions = PolylinePipeline.generateArc({
            positions: scaleArray2,
            granularity: granularity,
            ellipsoid: ellipsoid,
          });
          calculatedPositions = addShiftedPositions(
            subdividedPositions,
            left,
            width,
            calculatedPositions
          );
          if (saveAttributes) {
            calculatedLefts.push(left.x, left.y, left.z);
            calculatedNormals.push(normal.x, normal.y, normal.z);
          }
          startPoint = Cartesian3.clone(leftPos, startPoint);
          left = Cartesian3.normalize(
            Cartesian3.cross(normal, forward, left),
            left
          );
          leftPos = Cartesian3.add(
            rightPos,
            Cartesian3.multiplyByScalar(left, width * 2, leftPos),
            leftPos
          );
          previousPos = Cartesian3.add(
            rightPos,
            Cartesian3.multiplyByScalar(left, width, previousPos),
            previousPos
          );
          if (
            cornerType === CornerType$1.ROUNDED ||
            cornerType === CornerType$1.BEVELED
          ) {
            corners.push({
              leftPositions: computeRoundCorner(
                rightPos,
                startPoint,
                leftPos,
                cornerType,
                leftIsOutside
              ),
            });
          } else {
            corners.push({
              leftPositions: computeMiteredCorner(
                position,
                Cartesian3.negate(cornerDirection, cornerDirection),
                leftPos,
                leftIsOutside
              ),
            });
          }
        } else {
          leftPos = Cartesian3.add(position, cornerDirection, leftPos);
          center = Cartesian3.add(
            leftPos,
            Cartesian3.negate(
              Cartesian3.multiplyByScalar(left, width, center),
              center
            ),
            center
          );
          rightPos = Cartesian3.add(
            leftPos,
            Cartesian3.negate(
              Cartesian3.multiplyByScalar(left, width * 2, rightPos),
              rightPos
            ),
            rightPos
          );
          scaleArray2[0] = Cartesian3.clone(previousPos, scaleArray2[0]);
          scaleArray2[1] = Cartesian3.clone(center, scaleArray2[1]);
          subdividedPositions = PolylinePipeline.generateArc({
            positions: scaleArray2,
            granularity: granularity,
            ellipsoid: ellipsoid,
          });
          calculatedPositions = addShiftedPositions(
            subdividedPositions,
            left,
            width,
            calculatedPositions
          );
          if (saveAttributes) {
            calculatedLefts.push(left.x, left.y, left.z);
            calculatedNormals.push(normal.x, normal.y, normal.z);
          }
          startPoint = Cartesian3.clone(rightPos, startPoint);
          left = Cartesian3.normalize(
            Cartesian3.cross(normal, forward, left),
            left
          );
          rightPos = Cartesian3.add(
            leftPos,
            Cartesian3.negate(
              Cartesian3.multiplyByScalar(left, width * 2, rightPos),
              rightPos
            ),
            rightPos
          );
          previousPos = Cartesian3.add(
            leftPos,
            Cartesian3.negate(
              Cartesian3.multiplyByScalar(left, width, previousPos),
              previousPos
            ),
            previousPos
          );
          if (
            cornerType === CornerType$1.ROUNDED ||
            cornerType === CornerType$1.BEVELED
          ) {
            corners.push({
              rightPositions: computeRoundCorner(
                leftPos,
                startPoint,
                rightPos,
                cornerType,
                leftIsOutside
              ),
            });
          } else {
            corners.push({
              rightPositions: computeMiteredCorner(
                position,
                cornerDirection,
                rightPos,
                leftIsOutside
              ),
            });
          }
        }
        backward = Cartesian3.negate(forward, backward);
      }
      position = nextPosition;
    }

    normal = ellipsoid.geodeticSurfaceNormal(position, normal);
    scaleArray2[0] = Cartesian3.clone(previousPos, scaleArray2[0]);
    scaleArray2[1] = Cartesian3.clone(position, scaleArray2[1]);
    subdividedPositions = PolylinePipeline.generateArc({
      positions: scaleArray2,
      granularity: granularity,
      ellipsoid: ellipsoid,
    });
    calculatedPositions = addShiftedPositions(
      subdividedPositions,
      left,
      width,
      calculatedPositions
    );
    if (saveAttributes) {
      calculatedLefts.push(left.x, left.y, left.z);
      calculatedNormals.push(normal.x, normal.y, normal.z);
    }

    let endPositions;
    if (cornerType === CornerType$1.ROUNDED) {
      endPositions = addEndCaps(calculatedPositions);
    }

    return {
      positions: calculatedPositions,
      corners: corners,
      lefts: calculatedLefts,
      normals: calculatedNormals,
      endPositions: endPositions,
    };
  };

  const cartesian1$1 = new Cartesian3();
  const cartesian2$1 = new Cartesian3();
  const cartesian3$1 = new Cartesian3();
  const cartesian4 = new Cartesian3();
  const cartesian5 = new Cartesian3();
  const cartesian6 = new Cartesian3();

  const scratch1 = new Cartesian3();
  const scratch2 = new Cartesian3();

  function scaleToSurface$1(positions, ellipsoid) {
    for (let i = 0; i < positions.length; i++) {
      positions[i] = ellipsoid.scaleToGeodeticSurface(positions[i], positions[i]);
    }
    return positions;
  }

  function addNormals(attr, normal, left, front, back, vertexFormat) {
    const normals = attr.normals;
    const tangents = attr.tangents;
    const bitangents = attr.bitangents;
    const forward = Cartesian3.normalize(
      Cartesian3.cross(left, normal, scratch1),
      scratch1
    );
    if (vertexFormat.normal) {
      CorridorGeometryLibrary.addAttribute(normals, normal, front, back);
    }
    if (vertexFormat.tangent) {
      CorridorGeometryLibrary.addAttribute(tangents, forward, front, back);
    }
    if (vertexFormat.bitangent) {
      CorridorGeometryLibrary.addAttribute(bitangents, left, front, back);
    }
  }

  function combine$1(computedPositions, vertexFormat, ellipsoid) {
    const positions = computedPositions.positions;
    const corners = computedPositions.corners;
    const endPositions = computedPositions.endPositions;
    const computedLefts = computedPositions.lefts;
    const computedNormals = computedPositions.normals;
    const attributes = new GeometryAttributes();
    let corner;
    let leftCount = 0;
    let rightCount = 0;
    let i;
    let indicesLength = 0;
    let length;
    for (i = 0; i < positions.length; i += 2) {
      length = positions[i].length - 3;
      leftCount += length; //subtracting 3 to account for duplicate points at corners
      indicesLength += length * 2;
      rightCount += positions[i + 1].length - 3;
    }
    leftCount += 3; //add back count for end positions
    rightCount += 3;
    for (i = 0; i < corners.length; i++) {
      corner = corners[i];
      const leftSide = corners[i].leftPositions;
      if (defined(leftSide)) {
        length = leftSide.length;
        leftCount += length;
        indicesLength += length;
      } else {
        length = corners[i].rightPositions.length;
        rightCount += length;
        indicesLength += length;
      }
    }

    const addEndPositions = defined(endPositions);
    let endPositionLength;
    if (addEndPositions) {
      endPositionLength = endPositions[0].length - 3;
      leftCount += endPositionLength;
      rightCount += endPositionLength;
      endPositionLength /= 3;
      indicesLength += endPositionLength * 6;
    }
    const size = leftCount + rightCount;
    const finalPositions = new Float64Array(size);
    const normals = vertexFormat.normal ? new Float32Array(size) : undefined;
    const tangents = vertexFormat.tangent ? new Float32Array(size) : undefined;
    const bitangents = vertexFormat.bitangent
      ? new Float32Array(size)
      : undefined;
    const attr = {
      normals: normals,
      tangents: tangents,
      bitangents: bitangents,
    };
    let front = 0;
    let back = size - 1;
    let UL, LL, UR, LR;
    let normal = cartesian1$1;
    let left = cartesian2$1;
    let rightPos, leftPos;
    const halfLength = endPositionLength / 2;

    const indices = IndexDatatype$1.createTypedArray(size / 3, indicesLength);
    let index = 0;
    if (addEndPositions) {
      // add rounded end
      leftPos = cartesian3$1;
      rightPos = cartesian4;
      const firstEndPositions = endPositions[0];
      normal = Cartesian3.fromArray(computedNormals, 0, normal);
      left = Cartesian3.fromArray(computedLefts, 0, left);
      for (i = 0; i < halfLength; i++) {
        leftPos = Cartesian3.fromArray(
          firstEndPositions,
          (halfLength - 1 - i) * 3,
          leftPos
        );
        rightPos = Cartesian3.fromArray(
          firstEndPositions,
          (halfLength + i) * 3,
          rightPos
        );
        CorridorGeometryLibrary.addAttribute(finalPositions, rightPos, front);
        CorridorGeometryLibrary.addAttribute(
          finalPositions,
          leftPos,
          undefined,
          back
        );
        addNormals(attr, normal, left, front, back, vertexFormat);

        LL = front / 3;
        LR = LL + 1;
        UL = (back - 2) / 3;
        UR = UL - 1;
        indices[index++] = UL;
        indices[index++] = LL;
        indices[index++] = UR;
        indices[index++] = UR;
        indices[index++] = LL;
        indices[index++] = LR;

        front += 3;
        back -= 3;
      }
    }

    let posIndex = 0;
    let compIndex = 0;
    let rightEdge = positions[posIndex++]; //add first two edges
    let leftEdge = positions[posIndex++];
    finalPositions.set(rightEdge, front);
    finalPositions.set(leftEdge, back - leftEdge.length + 1);

    left = Cartesian3.fromArray(computedLefts, compIndex, left);
    let rightNormal;
    let leftNormal;
    length = leftEdge.length - 3;
    for (i = 0; i < length; i += 3) {
      rightNormal = ellipsoid.geodeticSurfaceNormal(
        Cartesian3.fromArray(rightEdge, i, scratch1),
        scratch1
      );
      leftNormal = ellipsoid.geodeticSurfaceNormal(
        Cartesian3.fromArray(leftEdge, length - i, scratch2),
        scratch2
      );
      normal = Cartesian3.normalize(
        Cartesian3.add(rightNormal, leftNormal, normal),
        normal
      );
      addNormals(attr, normal, left, front, back, vertexFormat);

      LL = front / 3;
      LR = LL + 1;
      UL = (back - 2) / 3;
      UR = UL - 1;
      indices[index++] = UL;
      indices[index++] = LL;
      indices[index++] = UR;
      indices[index++] = UR;
      indices[index++] = LL;
      indices[index++] = LR;

      front += 3;
      back -= 3;
    }

    rightNormal = ellipsoid.geodeticSurfaceNormal(
      Cartesian3.fromArray(rightEdge, length, scratch1),
      scratch1
    );
    leftNormal = ellipsoid.geodeticSurfaceNormal(
      Cartesian3.fromArray(leftEdge, length, scratch2),
      scratch2
    );
    normal = Cartesian3.normalize(
      Cartesian3.add(rightNormal, leftNormal, normal),
      normal
    );
    compIndex += 3;
    for (i = 0; i < corners.length; i++) {
      let j;
      corner = corners[i];
      const l = corner.leftPositions;
      const r = corner.rightPositions;
      let pivot;
      let start;
      let outsidePoint = cartesian6;
      let previousPoint = cartesian3$1;
      let nextPoint = cartesian4;
      normal = Cartesian3.fromArray(computedNormals, compIndex, normal);
      if (defined(l)) {
        addNormals(attr, normal, left, undefined, back, vertexFormat);
        back -= 3;
        pivot = LR;
        start = UR;
        for (j = 0; j < l.length / 3; j++) {
          outsidePoint = Cartesian3.fromArray(l, j * 3, outsidePoint);
          indices[index++] = pivot;
          indices[index++] = start - j - 1;
          indices[index++] = start - j;
          CorridorGeometryLibrary.addAttribute(
            finalPositions,
            outsidePoint,
            undefined,
            back
          );
          previousPoint = Cartesian3.fromArray(
            finalPositions,
            (start - j - 1) * 3,
            previousPoint
          );
          nextPoint = Cartesian3.fromArray(finalPositions, pivot * 3, nextPoint);
          left = Cartesian3.normalize(
            Cartesian3.subtract(previousPoint, nextPoint, left),
            left
          );
          addNormals(attr, normal, left, undefined, back, vertexFormat);
          back -= 3;
        }
        outsidePoint = Cartesian3.fromArray(
          finalPositions,
          pivot * 3,
          outsidePoint
        );
        previousPoint = Cartesian3.subtract(
          Cartesian3.fromArray(finalPositions, start * 3, previousPoint),
          outsidePoint,
          previousPoint
        );
        nextPoint = Cartesian3.subtract(
          Cartesian3.fromArray(finalPositions, (start - j) * 3, nextPoint),
          outsidePoint,
          nextPoint
        );
        left = Cartesian3.normalize(
          Cartesian3.add(previousPoint, nextPoint, left),
          left
        );
        addNormals(attr, normal, left, front, undefined, vertexFormat);
        front += 3;
      } else {
        addNormals(attr, normal, left, front, undefined, vertexFormat);
        front += 3;
        pivot = UR;
        start = LR;
        for (j = 0; j < r.length / 3; j++) {
          outsidePoint = Cartesian3.fromArray(r, j * 3, outsidePoint);
          indices[index++] = pivot;
          indices[index++] = start + j;
          indices[index++] = start + j + 1;
          CorridorGeometryLibrary.addAttribute(
            finalPositions,
            outsidePoint,
            front
          );
          previousPoint = Cartesian3.fromArray(
            finalPositions,
            pivot * 3,
            previousPoint
          );
          nextPoint = Cartesian3.fromArray(
            finalPositions,
            (start + j) * 3,
            nextPoint
          );
          left = Cartesian3.normalize(
            Cartesian3.subtract(previousPoint, nextPoint, left),
            left
          );
          addNormals(attr, normal, left, front, undefined, vertexFormat);
          front += 3;
        }
        outsidePoint = Cartesian3.fromArray(
          finalPositions,
          pivot * 3,
          outsidePoint
        );
        previousPoint = Cartesian3.subtract(
          Cartesian3.fromArray(finalPositions, (start + j) * 3, previousPoint),
          outsidePoint,
          previousPoint
        );
        nextPoint = Cartesian3.subtract(
          Cartesian3.fromArray(finalPositions, start * 3, nextPoint),
          outsidePoint,
          nextPoint
        );
        left = Cartesian3.normalize(
          Cartesian3.negate(Cartesian3.add(nextPoint, previousPoint, left), left),
          left
        );
        addNormals(attr, normal, left, undefined, back, vertexFormat);
        back -= 3;
      }
      rightEdge = positions[posIndex++];
      leftEdge = positions[posIndex++];
      rightEdge.splice(0, 3); //remove duplicate points added by corner
      leftEdge.splice(leftEdge.length - 3, 3);
      finalPositions.set(rightEdge, front);
      finalPositions.set(leftEdge, back - leftEdge.length + 1);
      length = leftEdge.length - 3;

      compIndex += 3;
      left = Cartesian3.fromArray(computedLefts, compIndex, left);
      for (j = 0; j < leftEdge.length; j += 3) {
        rightNormal = ellipsoid.geodeticSurfaceNormal(
          Cartesian3.fromArray(rightEdge, j, scratch1),
          scratch1
        );
        leftNormal = ellipsoid.geodeticSurfaceNormal(
          Cartesian3.fromArray(leftEdge, length - j, scratch2),
          scratch2
        );
        normal = Cartesian3.normalize(
          Cartesian3.add(rightNormal, leftNormal, normal),
          normal
        );
        addNormals(attr, normal, left, front, back, vertexFormat);

        LR = front / 3;
        LL = LR - 1;
        UR = (back - 2) / 3;
        UL = UR + 1;
        indices[index++] = UL;
        indices[index++] = LL;
        indices[index++] = UR;
        indices[index++] = UR;
        indices[index++] = LL;
        indices[index++] = LR;

        front += 3;
        back -= 3;
      }
      front -= 3;
      back += 3;
    }
    normal = Cartesian3.fromArray(
      computedNormals,
      computedNormals.length - 3,
      normal
    );
    addNormals(attr, normal, left, front, back, vertexFormat);

    if (addEndPositions) {
      // add rounded end
      front += 3;
      back -= 3;
      leftPos = cartesian3$1;
      rightPos = cartesian4;
      const lastEndPositions = endPositions[1];
      for (i = 0; i < halfLength; i++) {
        leftPos = Cartesian3.fromArray(
          lastEndPositions,
          (endPositionLength - i - 1) * 3,
          leftPos
        );
        rightPos = Cartesian3.fromArray(lastEndPositions, i * 3, rightPos);
        CorridorGeometryLibrary.addAttribute(
          finalPositions,
          leftPos,
          undefined,
          back
        );
        CorridorGeometryLibrary.addAttribute(finalPositions, rightPos, front);
        addNormals(attr, normal, left, front, back, vertexFormat);

        LR = front / 3;
        LL = LR - 1;
        UR = (back - 2) / 3;
        UL = UR + 1;
        indices[index++] = UL;
        indices[index++] = LL;
        indices[index++] = UR;
        indices[index++] = UR;
        indices[index++] = LL;
        indices[index++] = LR;

        front += 3;
        back -= 3;
      }
    }

    attributes.position = new GeometryAttribute({
      componentDatatype: ComponentDatatype$1.DOUBLE,
      componentsPerAttribute: 3,
      values: finalPositions,
    });

    if (vertexFormat.st) {
      const st = new Float32Array((size / 3) * 2);
      let rightSt;
      let leftSt;
      let stIndex = 0;
      if (addEndPositions) {
        leftCount /= 3;
        rightCount /= 3;
        const theta = Math.PI / (endPositionLength + 1);
        leftSt = 1 / (leftCount - endPositionLength + 1);
        rightSt = 1 / (rightCount - endPositionLength + 1);
        let a;
        const halfEndPos = endPositionLength / 2;
        for (i = halfEndPos + 1; i < endPositionLength + 1; i++) {
          // lower left rounded end
          a = CesiumMath.PI_OVER_TWO + theta * i;
          st[stIndex++] = rightSt * (1 + Math.cos(a));
          st[stIndex++] = 0.5 * (1 + Math.sin(a));
        }
        for (i = 1; i < rightCount - endPositionLength + 1; i++) {
          // bottom edge
          st[stIndex++] = i * rightSt;
          st[stIndex++] = 0;
        }
        for (i = endPositionLength; i > halfEndPos; i--) {
          // lower right rounded end
          a = CesiumMath.PI_OVER_TWO - i * theta;
          st[stIndex++] = 1 - rightSt * (1 + Math.cos(a));
          st[stIndex++] = 0.5 * (1 + Math.sin(a));
        }
        for (i = halfEndPos; i > 0; i--) {
          // upper right rounded end
          a = CesiumMath.PI_OVER_TWO - theta * i;
          st[stIndex++] = 1 - leftSt * (1 + Math.cos(a));
          st[stIndex++] = 0.5 * (1 + Math.sin(a));
        }
        for (i = leftCount - endPositionLength; i > 0; i--) {
          // top edge
          st[stIndex++] = i * leftSt;
          st[stIndex++] = 1;
        }
        for (i = 1; i < halfEndPos + 1; i++) {
          // upper left rounded end
          a = CesiumMath.PI_OVER_TWO + theta * i;
          st[stIndex++] = leftSt * (1 + Math.cos(a));
          st[stIndex++] = 0.5 * (1 + Math.sin(a));
        }
      } else {
        leftCount /= 3;
        rightCount /= 3;
        leftSt = 1 / (leftCount - 1);
        rightSt = 1 / (rightCount - 1);
        for (i = 0; i < rightCount; i++) {
          // bottom edge
          st[stIndex++] = i * rightSt;
          st[stIndex++] = 0;
        }
        for (i = leftCount; i > 0; i--) {
          // top edge
          st[stIndex++] = (i - 1) * leftSt;
          st[stIndex++] = 1;
        }
      }

      attributes.st = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 2,
        values: st,
      });
    }

    if (vertexFormat.normal) {
      attributes.normal = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 3,
        values: attr.normals,
      });
    }

    if (vertexFormat.tangent) {
      attributes.tangent = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 3,
        values: attr.tangents,
      });
    }

    if (vertexFormat.bitangent) {
      attributes.bitangent = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 3,
        values: attr.bitangents,
      });
    }

    return {
      attributes: attributes,
      indices: indices,
    };
  }

  function extrudedAttributes(attributes, vertexFormat) {
    if (
      !vertexFormat.normal &&
      !vertexFormat.tangent &&
      !vertexFormat.bitangent &&
      !vertexFormat.st
    ) {
      return attributes;
    }
    const positions = attributes.position.values;
    let topNormals;
    let topBitangents;
    if (vertexFormat.normal || vertexFormat.bitangent) {
      topNormals = attributes.normal.values;
      topBitangents = attributes.bitangent.values;
    }
    const size = attributes.position.values.length / 18;
    const threeSize = size * 3;
    const twoSize = size * 2;
    const sixSize = threeSize * 2;
    let i;
    if (vertexFormat.normal || vertexFormat.bitangent || vertexFormat.tangent) {
      const normals = vertexFormat.normal
        ? new Float32Array(threeSize * 6)
        : undefined;
      const tangents = vertexFormat.tangent
        ? new Float32Array(threeSize * 6)
        : undefined;
      const bitangents = vertexFormat.bitangent
        ? new Float32Array(threeSize * 6)
        : undefined;
      let topPosition = cartesian1$1;
      let bottomPosition = cartesian2$1;
      let previousPosition = cartesian3$1;
      let normal = cartesian4;
      let tangent = cartesian5;
      let bitangent = cartesian6;
      let attrIndex = sixSize;
      for (i = 0; i < threeSize; i += 3) {
        const attrIndexOffset = attrIndex + sixSize;
        topPosition = Cartesian3.fromArray(positions, i, topPosition);
        bottomPosition = Cartesian3.fromArray(
          positions,
          i + threeSize,
          bottomPosition
        );
        previousPosition = Cartesian3.fromArray(
          positions,
          (i + 3) % threeSize,
          previousPosition
        );
        bottomPosition = Cartesian3.subtract(
          bottomPosition,
          topPosition,
          bottomPosition
        );
        previousPosition = Cartesian3.subtract(
          previousPosition,
          topPosition,
          previousPosition
        );
        normal = Cartesian3.normalize(
          Cartesian3.cross(bottomPosition, previousPosition, normal),
          normal
        );
        if (vertexFormat.normal) {
          CorridorGeometryLibrary.addAttribute(normals, normal, attrIndexOffset);
          CorridorGeometryLibrary.addAttribute(
            normals,
            normal,
            attrIndexOffset + 3
          );
          CorridorGeometryLibrary.addAttribute(normals, normal, attrIndex);
          CorridorGeometryLibrary.addAttribute(normals, normal, attrIndex + 3);
        }
        if (vertexFormat.tangent || vertexFormat.bitangent) {
          bitangent = Cartesian3.fromArray(topNormals, i, bitangent);
          if (vertexFormat.bitangent) {
            CorridorGeometryLibrary.addAttribute(
              bitangents,
              bitangent,
              attrIndexOffset
            );
            CorridorGeometryLibrary.addAttribute(
              bitangents,
              bitangent,
              attrIndexOffset + 3
            );
            CorridorGeometryLibrary.addAttribute(
              bitangents,
              bitangent,
              attrIndex
            );
            CorridorGeometryLibrary.addAttribute(
              bitangents,
              bitangent,
              attrIndex + 3
            );
          }

          if (vertexFormat.tangent) {
            tangent = Cartesian3.normalize(
              Cartesian3.cross(bitangent, normal, tangent),
              tangent
            );
            CorridorGeometryLibrary.addAttribute(
              tangents,
              tangent,
              attrIndexOffset
            );
            CorridorGeometryLibrary.addAttribute(
              tangents,
              tangent,
              attrIndexOffset + 3
            );
            CorridorGeometryLibrary.addAttribute(tangents, tangent, attrIndex);
            CorridorGeometryLibrary.addAttribute(
              tangents,
              tangent,
              attrIndex + 3
            );
          }
        }
        attrIndex += 6;
      }

      if (vertexFormat.normal) {
        normals.set(topNormals); //top
        for (i = 0; i < threeSize; i += 3) {
          //bottom normals
          normals[i + threeSize] = -topNormals[i];
          normals[i + threeSize + 1] = -topNormals[i + 1];
          normals[i + threeSize + 2] = -topNormals[i + 2];
        }
        attributes.normal.values = normals;
      } else {
        attributes.normal = undefined;
      }

      if (vertexFormat.bitangent) {
        bitangents.set(topBitangents); //top
        bitangents.set(topBitangents, threeSize); //bottom
        attributes.bitangent.values = bitangents;
      } else {
        attributes.bitangent = undefined;
      }

      if (vertexFormat.tangent) {
        const topTangents = attributes.tangent.values;
        tangents.set(topTangents); //top
        tangents.set(topTangents, threeSize); //bottom
        attributes.tangent.values = tangents;
      }
    }
    if (vertexFormat.st) {
      const topSt = attributes.st.values;
      const st = new Float32Array(twoSize * 6);
      st.set(topSt); //top
      st.set(topSt, twoSize); //bottom
      let index = twoSize * 2;

      for (let j = 0; j < 2; j++) {
        st[index++] = topSt[0];
        st[index++] = topSt[1];
        for (i = 2; i < twoSize; i += 2) {
          const s = topSt[i];
          const t = topSt[i + 1];
          st[index++] = s;
          st[index++] = t;
          st[index++] = s;
          st[index++] = t;
        }
        st[index++] = topSt[0];
        st[index++] = topSt[1];
      }
      attributes.st.values = st;
    }

    return attributes;
  }

  function addWallPositions$1(positions, index, wallPositions) {
    wallPositions[index++] = positions[0];
    wallPositions[index++] = positions[1];
    wallPositions[index++] = positions[2];
    for (let i = 3; i < positions.length; i += 3) {
      const x = positions[i];
      const y = positions[i + 1];
      const z = positions[i + 2];
      wallPositions[index++] = x;
      wallPositions[index++] = y;
      wallPositions[index++] = z;
      wallPositions[index++] = x;
      wallPositions[index++] = y;
      wallPositions[index++] = z;
    }
    wallPositions[index++] = positions[0];
    wallPositions[index++] = positions[1];
    wallPositions[index++] = positions[2];

    return wallPositions;
  }

  function computePositionsExtruded$1(params, vertexFormat) {
    const topVertexFormat = new VertexFormat({
      position: vertexFormat.position,
      normal:
        vertexFormat.normal || vertexFormat.bitangent || params.shadowVolume,
      tangent: vertexFormat.tangent,
      bitangent: vertexFormat.normal || vertexFormat.bitangent,
      st: vertexFormat.st,
    });
    const ellipsoid = params.ellipsoid;
    const computedPositions = CorridorGeometryLibrary.computePositions(params);
    const attr = combine$1(computedPositions, topVertexFormat, ellipsoid);
    const height = params.height;
    const extrudedHeight = params.extrudedHeight;
    let attributes = attr.attributes;
    const indices = attr.indices;
    let positions = attributes.position.values;
    let length = positions.length;
    const newPositions = new Float64Array(length * 6);
    let extrudedPositions = new Float64Array(length);
    extrudedPositions.set(positions);
    let wallPositions = new Float64Array(length * 4);

    positions = PolygonPipeline.scaleToGeodeticHeight(
      positions,
      height,
      ellipsoid
    );
    wallPositions = addWallPositions$1(positions, 0, wallPositions);
    extrudedPositions = PolygonPipeline.scaleToGeodeticHeight(
      extrudedPositions,
      extrudedHeight,
      ellipsoid
    );
    wallPositions = addWallPositions$1(
      extrudedPositions,
      length * 2,
      wallPositions
    );
    newPositions.set(positions);
    newPositions.set(extrudedPositions, length);
    newPositions.set(wallPositions, length * 2);
    attributes.position.values = newPositions;

    attributes = extrudedAttributes(attributes, vertexFormat);
    let i;
    const size = length / 3;
    if (params.shadowVolume) {
      const topNormals = attributes.normal.values;
      length = topNormals.length;

      let extrudeNormals = new Float32Array(length * 6);
      for (i = 0; i < length; i++) {
        topNormals[i] = -topNormals[i];
      }
      //only get normals for bottom layer that's going to be pushed down
      extrudeNormals.set(topNormals, length); //bottom face
      extrudeNormals = addWallPositions$1(topNormals, length * 4, extrudeNormals); //bottom wall
      attributes.extrudeDirection = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 3,
        values: extrudeNormals,
      });
      if (!vertexFormat.normal) {
        attributes.normal = undefined;
      }
    }
    if (defined(params.offsetAttribute)) {
      let applyOffset = new Uint8Array(size * 6);
      if (params.offsetAttribute === GeometryOffsetAttribute$1.TOP) {
        applyOffset = applyOffset
          .fill(1, 0, size) // top face
          .fill(1, size * 2, size * 4); // top wall
      } else {
        const applyOffsetValue =
          params.offsetAttribute === GeometryOffsetAttribute$1.NONE ? 0 : 1;
        applyOffset = applyOffset.fill(applyOffsetValue);
      }
      attributes.applyOffset = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
        componentsPerAttribute: 1,
        values: applyOffset,
      });
    }

    const iLength = indices.length;
    const twoSize = size + size;
    const newIndices = IndexDatatype$1.createTypedArray(
      newPositions.length / 3,
      iLength * 2 + twoSize * 3
    );
    newIndices.set(indices);
    let index = iLength;
    for (i = 0; i < iLength; i += 3) {
      // bottom indices
      const v0 = indices[i];
      const v1 = indices[i + 1];
      const v2 = indices[i + 2];
      newIndices[index++] = v2 + size;
      newIndices[index++] = v1 + size;
      newIndices[index++] = v0 + size;
    }

    let UL, LL, UR, LR;

    for (i = 0; i < twoSize; i += 2) {
      //wall indices
      UL = i + twoSize;
      LL = UL + twoSize;
      UR = UL + 1;
      LR = LL + 1;
      newIndices[index++] = UL;
      newIndices[index++] = LL;
      newIndices[index++] = UR;
      newIndices[index++] = UR;
      newIndices[index++] = LL;
      newIndices[index++] = LR;
    }

    return {
      attributes: attributes,
      indices: newIndices,
    };
  }

  const scratchCartesian1$2 = new Cartesian3();
  const scratchCartesian2$5 = new Cartesian3();
  const scratchCartographic$f = new Cartographic();

  function computeOffsetPoints(
    position1,
    position2,
    ellipsoid,
    halfWidth,
    min,
    max
  ) {
    // Compute direction of offset the point
    const direction = Cartesian3.subtract(
      position2,
      position1,
      scratchCartesian1$2
    );
    Cartesian3.normalize(direction, direction);
    const normal = ellipsoid.geodeticSurfaceNormal(position1, scratchCartesian2$5);
    const offsetDirection = Cartesian3.cross(
      direction,
      normal,
      scratchCartesian1$2
    );
    Cartesian3.multiplyByScalar(offsetDirection, halfWidth, offsetDirection);

    let minLat = min.latitude;
    let minLon = min.longitude;
    let maxLat = max.latitude;
    let maxLon = max.longitude;

    // Compute 2 offset points
    Cartesian3.add(position1, offsetDirection, scratchCartesian2$5);
    ellipsoid.cartesianToCartographic(scratchCartesian2$5, scratchCartographic$f);

    let lat = scratchCartographic$f.latitude;
    let lon = scratchCartographic$f.longitude;
    minLat = Math.min(minLat, lat);
    minLon = Math.min(minLon, lon);
    maxLat = Math.max(maxLat, lat);
    maxLon = Math.max(maxLon, lon);

    Cartesian3.subtract(position1, offsetDirection, scratchCartesian2$5);
    ellipsoid.cartesianToCartographic(scratchCartesian2$5, scratchCartographic$f);

    lat = scratchCartographic$f.latitude;
    lon = scratchCartographic$f.longitude;
    minLat = Math.min(minLat, lat);
    minLon = Math.min(minLon, lon);
    maxLat = Math.max(maxLat, lat);
    maxLon = Math.max(maxLon, lon);

    min.latitude = minLat;
    min.longitude = minLon;
    max.latitude = maxLat;
    max.longitude = maxLon;
  }

  const scratchCartesianOffset = new Cartesian3();
  const scratchCartesianEnds = new Cartesian3();
  const scratchCartographicMin = new Cartographic();
  const scratchCartographicMax = new Cartographic();

  function computeRectangle$2(positions, ellipsoid, width, cornerType, result) {
    positions = scaleToSurface$1(positions, ellipsoid);
    const cleanPositions = arrayRemoveDuplicates(
      positions,
      Cartesian3.equalsEpsilon
    );
    const length = cleanPositions.length;
    if (length < 2 || width <= 0) {
      return new Rectangle();
    }
    const halfWidth = width * 0.5;

    scratchCartographicMin.latitude = Number.POSITIVE_INFINITY;
    scratchCartographicMin.longitude = Number.POSITIVE_INFINITY;
    scratchCartographicMax.latitude = Number.NEGATIVE_INFINITY;
    scratchCartographicMax.longitude = Number.NEGATIVE_INFINITY;

    let lat, lon;
    if (cornerType === CornerType$1.ROUNDED) {
      // Compute start cap
      const first = cleanPositions[0];
      Cartesian3.subtract(first, cleanPositions[1], scratchCartesianOffset);
      Cartesian3.normalize(scratchCartesianOffset, scratchCartesianOffset);
      Cartesian3.multiplyByScalar(
        scratchCartesianOffset,
        halfWidth,
        scratchCartesianOffset
      );
      Cartesian3.add(first, scratchCartesianOffset, scratchCartesianEnds);

      ellipsoid.cartesianToCartographic(
        scratchCartesianEnds,
        scratchCartographic$f
      );
      lat = scratchCartographic$f.latitude;
      lon = scratchCartographic$f.longitude;
      scratchCartographicMin.latitude = Math.min(
        scratchCartographicMin.latitude,
        lat
      );
      scratchCartographicMin.longitude = Math.min(
        scratchCartographicMin.longitude,
        lon
      );
      scratchCartographicMax.latitude = Math.max(
        scratchCartographicMax.latitude,
        lat
      );
      scratchCartographicMax.longitude = Math.max(
        scratchCartographicMax.longitude,
        lon
      );
    }

    // Compute the rest
    for (let i = 0; i < length - 1; ++i) {
      computeOffsetPoints(
        cleanPositions[i],
        cleanPositions[i + 1],
        ellipsoid,
        halfWidth,
        scratchCartographicMin,
        scratchCartographicMax
      );
    }

    // Compute ending point
    const last = cleanPositions[length - 1];
    Cartesian3.subtract(last, cleanPositions[length - 2], scratchCartesianOffset);
    Cartesian3.normalize(scratchCartesianOffset, scratchCartesianOffset);
    Cartesian3.multiplyByScalar(
      scratchCartesianOffset,
      halfWidth,
      scratchCartesianOffset
    );
    Cartesian3.add(last, scratchCartesianOffset, scratchCartesianEnds);
    computeOffsetPoints(
      last,
      scratchCartesianEnds,
      ellipsoid,
      halfWidth,
      scratchCartographicMin,
      scratchCartographicMax
    );

    if (cornerType === CornerType$1.ROUNDED) {
      // Compute end cap
      ellipsoid.cartesianToCartographic(
        scratchCartesianEnds,
        scratchCartographic$f
      );
      lat = scratchCartographic$f.latitude;
      lon = scratchCartographic$f.longitude;
      scratchCartographicMin.latitude = Math.min(
        scratchCartographicMin.latitude,
        lat
      );
      scratchCartographicMin.longitude = Math.min(
        scratchCartographicMin.longitude,
        lon
      );
      scratchCartographicMax.latitude = Math.max(
        scratchCartographicMax.latitude,
        lat
      );
      scratchCartographicMax.longitude = Math.max(
        scratchCartographicMax.longitude,
        lon
      );
    }

    const rectangle = defined(result) ? result : new Rectangle();
    rectangle.north = scratchCartographicMax.latitude;
    rectangle.south = scratchCartographicMin.latitude;
    rectangle.east = scratchCartographicMax.longitude;
    rectangle.west = scratchCartographicMin.longitude;

    return rectangle;
  }

  /**
   * A description of a corridor. Corridor geometry can be rendered with both {@link Primitive} and {@link GroundPrimitive}.
   *
   * @alias CorridorGeometry
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Cartesian3[]} options.positions An array of positions that define the center of the corridor.
   * @param {Number} options.width The distance between the edges of the corridor in meters.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid to be used as a reference.
   * @param {Number} [options.granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
   * @param {Number} [options.height=0] The distance in meters between the ellipsoid surface and the positions.
   * @param {Number} [options.extrudedHeight] The distance in meters between the ellipsoid surface and the extruded face.
   * @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
   * @param {CornerType} [options.cornerType=CornerType.ROUNDED] Determines the style of the corners.
   *
   * @see CorridorGeometry.createGeometry
   * @see Packable
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Corridor.html|Cesium Sandcastle Corridor Demo}
   *
   * @example
   * const corridor = new Cesium.CorridorGeometry({
   *   vertexFormat : Cesium.VertexFormat.POSITION_ONLY,
   *   positions : Cesium.Cartesian3.fromDegreesArray([-72.0, 40.0, -70.0, 35.0]),
   *   width : 100000
   * });
   */
  function CorridorGeometry(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const positions = options.positions;
    const width = options.width;

    //>>includeStart('debug', pragmas.debug);
    Check.defined("options.positions", positions);
    Check.defined("options.width", width);
    //>>includeEnd('debug');

    const height = defaultValue(options.height, 0.0);
    const extrudedHeight = defaultValue(options.extrudedHeight, height);

    this._positions = positions;
    this._ellipsoid = Ellipsoid.clone(
      defaultValue(options.ellipsoid, Ellipsoid.WGS84)
    );
    this._vertexFormat = VertexFormat.clone(
      defaultValue(options.vertexFormat, VertexFormat.DEFAULT)
    );
    this._width = width;
    this._height = Math.max(height, extrudedHeight);
    this._extrudedHeight = Math.min(height, extrudedHeight);
    this._cornerType = defaultValue(options.cornerType, CornerType$1.ROUNDED);
    this._granularity = defaultValue(
      options.granularity,
      CesiumMath.RADIANS_PER_DEGREE
    );
    this._shadowVolume = defaultValue(options.shadowVolume, false);
    this._workerName = "createCorridorGeometry";
    this._offsetAttribute = options.offsetAttribute;
    this._rectangle = undefined;

    /**
     * The number of elements used to pack the object into an array.
     * @type {Number}
     */
    this.packedLength =
      1 +
      positions.length * Cartesian3.packedLength +
      Ellipsoid.packedLength +
      VertexFormat.packedLength +
      7;
  }

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {CorridorGeometry} 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
   */
  CorridorGeometry.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("value", value);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    const positions = value._positions;
    const length = positions.length;
    array[startingIndex++] = length;

    for (let i = 0; i < length; ++i, startingIndex += Cartesian3.packedLength) {
      Cartesian3.pack(positions[i], array, startingIndex);
    }

    Ellipsoid.pack(value._ellipsoid, array, startingIndex);
    startingIndex += Ellipsoid.packedLength;

    VertexFormat.pack(value._vertexFormat, array, startingIndex);
    startingIndex += VertexFormat.packedLength;

    array[startingIndex++] = value._width;
    array[startingIndex++] = value._height;
    array[startingIndex++] = value._extrudedHeight;
    array[startingIndex++] = value._cornerType;
    array[startingIndex++] = value._granularity;
    array[startingIndex++] = value._shadowVolume ? 1.0 : 0.0;
    array[startingIndex] = defaultValue(value._offsetAttribute, -1);

    return array;
  };

  const scratchEllipsoid$b = Ellipsoid.clone(Ellipsoid.UNIT_SPHERE);
  const scratchVertexFormat$9 = new VertexFormat();
  const scratchOptions$f = {
    positions: undefined,
    ellipsoid: scratchEllipsoid$b,
    vertexFormat: scratchVertexFormat$9,
    width: undefined,
    height: undefined,
    extrudedHeight: undefined,
    cornerType: undefined,
    granularity: undefined,
    shadowVolume: undefined,
    offsetAttribute: undefined,
  };

  /**
   * 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 {CorridorGeometry} [result] The object into which to store the result.
   * @returns {CorridorGeometry} The modified result parameter or a new CorridorGeometry instance if one was not provided.
   */
  CorridorGeometry.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    const length = array[startingIndex++];
    const positions = new Array(length);

    for (let i = 0; i < length; ++i, startingIndex += Cartesian3.packedLength) {
      positions[i] = Cartesian3.unpack(array, startingIndex);
    }

    const ellipsoid = Ellipsoid.unpack(array, startingIndex, scratchEllipsoid$b);
    startingIndex += Ellipsoid.packedLength;

    const vertexFormat = VertexFormat.unpack(
      array,
      startingIndex,
      scratchVertexFormat$9
    );
    startingIndex += VertexFormat.packedLength;

    const width = array[startingIndex++];
    const height = array[startingIndex++];
    const extrudedHeight = array[startingIndex++];
    const cornerType = array[startingIndex++];
    const granularity = array[startingIndex++];
    const shadowVolume = array[startingIndex++] === 1.0;
    const offsetAttribute = array[startingIndex];

    if (!defined(result)) {
      scratchOptions$f.positions = positions;
      scratchOptions$f.width = width;
      scratchOptions$f.height = height;
      scratchOptions$f.extrudedHeight = extrudedHeight;
      scratchOptions$f.cornerType = cornerType;
      scratchOptions$f.granularity = granularity;
      scratchOptions$f.shadowVolume = shadowVolume;
      scratchOptions$f.offsetAttribute =
        offsetAttribute === -1 ? undefined : offsetAttribute;

      return new CorridorGeometry(scratchOptions$f);
    }

    result._positions = positions;
    result._ellipsoid = Ellipsoid.clone(ellipsoid, result._ellipsoid);
    result._vertexFormat = VertexFormat.clone(vertexFormat, result._vertexFormat);
    result._width = width;
    result._height = height;
    result._extrudedHeight = extrudedHeight;
    result._cornerType = cornerType;
    result._granularity = granularity;
    result._shadowVolume = shadowVolume;
    result._offsetAttribute =
      offsetAttribute === -1 ? undefined : offsetAttribute;

    return result;
  };

  /**
   * Computes the bounding rectangle given the provided options
   *
   * @param {Object} options Object with the following properties:
   * @param {Cartesian3[]} options.positions An array of positions that define the center of the corridor.
   * @param {Number} options.width The distance between the edges of the corridor in meters.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid to be used as a reference.
   * @param {CornerType} [options.cornerType=CornerType.ROUNDED] Determines the style of the corners.
   * @param {Rectangle} [result] An object in which to store the result.
   *
   * @returns {Rectangle} The result rectangle.
   */
  CorridorGeometry.computeRectangle = function (options, result) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const positions = options.positions;
    const width = options.width;

    //>>includeStart('debug', pragmas.debug);
    Check.defined("options.positions", positions);
    Check.defined("options.width", width);
    //>>includeEnd('debug');

    const ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);
    const cornerType = defaultValue(options.cornerType, CornerType$1.ROUNDED);

    return computeRectangle$2(positions, ellipsoid, width, cornerType, result);
  };

  /**
   * Computes the geometric representation of a corridor, including its vertices, indices, and a bounding sphere.
   *
   * @param {CorridorGeometry} corridorGeometry A description of the corridor.
   * @returns {Geometry|undefined} The computed vertices and indices.
   */
  CorridorGeometry.createGeometry = function (corridorGeometry) {
    let positions = corridorGeometry._positions;
    const width = corridorGeometry._width;
    const ellipsoid = corridorGeometry._ellipsoid;

    positions = scaleToSurface$1(positions, ellipsoid);
    const cleanPositions = arrayRemoveDuplicates(
      positions,
      Cartesian3.equalsEpsilon
    );

    if (cleanPositions.length < 2 || width <= 0) {
      return;
    }

    const height = corridorGeometry._height;
    const extrudedHeight = corridorGeometry._extrudedHeight;
    const extrude = !CesiumMath.equalsEpsilon(
      height,
      extrudedHeight,
      0,
      CesiumMath.EPSILON2
    );

    const vertexFormat = corridorGeometry._vertexFormat;
    const params = {
      ellipsoid: ellipsoid,
      positions: cleanPositions,
      width: width,
      cornerType: corridorGeometry._cornerType,
      granularity: corridorGeometry._granularity,
      saveAttributes: true,
    };
    let attr;
    if (extrude) {
      params.height = height;
      params.extrudedHeight = extrudedHeight;
      params.shadowVolume = corridorGeometry._shadowVolume;
      params.offsetAttribute = corridorGeometry._offsetAttribute;
      attr = computePositionsExtruded$1(params, vertexFormat);
    } else {
      const computedPositions = CorridorGeometryLibrary.computePositions(params);
      attr = combine$1(computedPositions, vertexFormat, ellipsoid);
      attr.attributes.position.values = PolygonPipeline.scaleToGeodeticHeight(
        attr.attributes.position.values,
        height,
        ellipsoid
      );

      if (defined(corridorGeometry._offsetAttribute)) {
        const applyOffsetValue =
          corridorGeometry._offsetAttribute === GeometryOffsetAttribute$1.NONE
            ? 0
            : 1;
        const length = attr.attributes.position.values.length;
        const applyOffset = new Uint8Array(length / 3).fill(applyOffsetValue);
        attr.attributes.applyOffset = new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
          componentsPerAttribute: 1,
          values: applyOffset,
        });
      }
    }
    const attributes = attr.attributes;
    const boundingSphere = BoundingSphere.fromVertices(
      attributes.position.values,
      undefined,
      3
    );
    if (!vertexFormat.position) {
      attr.attributes.position.values = undefined;
    }

    return new Geometry({
      attributes: attributes,
      indices: attr.indices,
      primitiveType: PrimitiveType$1.TRIANGLES,
      boundingSphere: boundingSphere,
      offsetAttribute: corridorGeometry._offsetAttribute,
    });
  };

  /**
   * @private
   */
  CorridorGeometry.createShadowVolume = function (
    corridorGeometry,
    minHeightFunc,
    maxHeightFunc
  ) {
    const granularity = corridorGeometry._granularity;
    const ellipsoid = corridorGeometry._ellipsoid;

    const minHeight = minHeightFunc(granularity, ellipsoid);
    const maxHeight = maxHeightFunc(granularity, ellipsoid);

    return new CorridorGeometry({
      positions: corridorGeometry._positions,
      width: corridorGeometry._width,
      cornerType: corridorGeometry._cornerType,
      ellipsoid: ellipsoid,
      granularity: granularity,
      extrudedHeight: minHeight,
      height: maxHeight,
      vertexFormat: VertexFormat.POSITION_ONLY,
      shadowVolume: true,
    });
  };

  Object.defineProperties(CorridorGeometry.prototype, {
    /**
     * @private
     */
    rectangle: {
      get: function () {
        if (!defined(this._rectangle)) {
          this._rectangle = computeRectangle$2(
            this._positions,
            this._ellipsoid,
            this._width,
            this._cornerType
          );
        }
        return this._rectangle;
      },
    },
    /**
     * For remapping texture coordinates when rendering CorridorGeometries as GroundPrimitives.
     *
     * Corridors don't support stRotation,
     * so just return the corners of the original system.
     * @private
     */
    textureCoordinateRotationPoints: {
      get: function () {
        return [0, 0, 0, 1, 1, 0];
      },
    },
  });

  const cartesian1 = new Cartesian3();
  const cartesian2 = new Cartesian3();
  const cartesian3 = new Cartesian3();

  function scaleToSurface(positions, ellipsoid) {
    for (let i = 0; i < positions.length; i++) {
      positions[i] = ellipsoid.scaleToGeodeticSurface(positions[i], positions[i]);
    }
    return positions;
  }

  function combine(computedPositions, cornerType) {
    const wallIndices = [];
    const positions = computedPositions.positions;
    const corners = computedPositions.corners;
    const endPositions = computedPositions.endPositions;
    const attributes = new GeometryAttributes();
    let corner;
    let leftCount = 0;
    let rightCount = 0;
    let i;
    let indicesLength = 0;
    let length;
    for (i = 0; i < positions.length; i += 2) {
      length = positions[i].length - 3;
      leftCount += length; //subtracting 3 to account for duplicate points at corners
      indicesLength += (length / 3) * 4;
      rightCount += positions[i + 1].length - 3;
    }
    leftCount += 3; //add back count for end positions
    rightCount += 3;
    for (i = 0; i < corners.length; i++) {
      corner = corners[i];
      const leftSide = corners[i].leftPositions;
      if (defined(leftSide)) {
        length = leftSide.length;
        leftCount += length;
        indicesLength += (length / 3) * 2;
      } else {
        length = corners[i].rightPositions.length;
        rightCount += length;
        indicesLength += (length / 3) * 2;
      }
    }

    const addEndPositions = defined(endPositions);
    let endPositionLength;
    if (addEndPositions) {
      endPositionLength = endPositions[0].length - 3;
      leftCount += endPositionLength;
      rightCount += endPositionLength;
      endPositionLength /= 3;
      indicesLength += endPositionLength * 4;
    }
    const size = leftCount + rightCount;
    const finalPositions = new Float64Array(size);
    let front = 0;
    let back = size - 1;
    let UL, LL, UR, LR;
    let rightPos, leftPos;
    const halfLength = endPositionLength / 2;

    const indices = IndexDatatype$1.createTypedArray(size / 3, indicesLength + 4);
    let index = 0;

    indices[index++] = front / 3;
    indices[index++] = (back - 2) / 3;
    if (addEndPositions) {
      // add rounded end
      wallIndices.push(front / 3);
      leftPos = cartesian1;
      rightPos = cartesian2;
      const firstEndPositions = endPositions[0];
      for (i = 0; i < halfLength; i++) {
        leftPos = Cartesian3.fromArray(
          firstEndPositions,
          (halfLength - 1 - i) * 3,
          leftPos
        );
        rightPos = Cartesian3.fromArray(
          firstEndPositions,
          (halfLength + i) * 3,
          rightPos
        );
        CorridorGeometryLibrary.addAttribute(finalPositions, rightPos, front);
        CorridorGeometryLibrary.addAttribute(
          finalPositions,
          leftPos,
          undefined,
          back
        );

        LL = front / 3;
        LR = LL + 1;
        UL = (back - 2) / 3;
        UR = UL - 1;
        indices[index++] = UL;
        indices[index++] = UR;
        indices[index++] = LL;
        indices[index++] = LR;

        front += 3;
        back -= 3;
      }
    }

    let posIndex = 0;
    let rightEdge = positions[posIndex++]; //add first two edges
    let leftEdge = positions[posIndex++];
    finalPositions.set(rightEdge, front);
    finalPositions.set(leftEdge, back - leftEdge.length + 1);

    length = leftEdge.length - 3;
    wallIndices.push(front / 3, (back - 2) / 3);
    for (i = 0; i < length; i += 3) {
      LL = front / 3;
      LR = LL + 1;
      UL = (back - 2) / 3;
      UR = UL - 1;
      indices[index++] = UL;
      indices[index++] = UR;
      indices[index++] = LL;
      indices[index++] = LR;

      front += 3;
      back -= 3;
    }

    for (i = 0; i < corners.length; i++) {
      let j;
      corner = corners[i];
      const l = corner.leftPositions;
      const r = corner.rightPositions;
      let start;
      let outsidePoint = cartesian3;
      if (defined(l)) {
        back -= 3;
        start = UR;
        wallIndices.push(LR);
        for (j = 0; j < l.length / 3; j++) {
          outsidePoint = Cartesian3.fromArray(l, j * 3, outsidePoint);
          indices[index++] = start - j - 1;
          indices[index++] = start - j;
          CorridorGeometryLibrary.addAttribute(
            finalPositions,
            outsidePoint,
            undefined,
            back
          );
          back -= 3;
        }
        wallIndices.push(start - Math.floor(l.length / 6));
        if (cornerType === CornerType$1.BEVELED) {
          wallIndices.push((back - 2) / 3 + 1);
        }
        front += 3;
      } else {
        front += 3;
        start = LR;
        wallIndices.push(UR);
        for (j = 0; j < r.length / 3; j++) {
          outsidePoint = Cartesian3.fromArray(r, j * 3, outsidePoint);
          indices[index++] = start + j;
          indices[index++] = start + j + 1;
          CorridorGeometryLibrary.addAttribute(
            finalPositions,
            outsidePoint,
            front
          );
          front += 3;
        }
        wallIndices.push(start + Math.floor(r.length / 6));
        if (cornerType === CornerType$1.BEVELED) {
          wallIndices.push(front / 3 - 1);
        }
        back -= 3;
      }
      rightEdge = positions[posIndex++];
      leftEdge = positions[posIndex++];
      rightEdge.splice(0, 3); //remove duplicate points added by corner
      leftEdge.splice(leftEdge.length - 3, 3);
      finalPositions.set(rightEdge, front);
      finalPositions.set(leftEdge, back - leftEdge.length + 1);
      length = leftEdge.length - 3;

      for (j = 0; j < leftEdge.length; j += 3) {
        LR = front / 3;
        LL = LR - 1;
        UR = (back - 2) / 3;
        UL = UR + 1;
        indices[index++] = UL;
        indices[index++] = UR;
        indices[index++] = LL;
        indices[index++] = LR;
        front += 3;
        back -= 3;
      }
      front -= 3;
      back += 3;
      wallIndices.push(front / 3, (back - 2) / 3);
    }

    if (addEndPositions) {
      // add rounded end
      front += 3;
      back -= 3;
      leftPos = cartesian1;
      rightPos = cartesian2;
      const lastEndPositions = endPositions[1];
      for (i = 0; i < halfLength; i++) {
        leftPos = Cartesian3.fromArray(
          lastEndPositions,
          (endPositionLength - i - 1) * 3,
          leftPos
        );
        rightPos = Cartesian3.fromArray(lastEndPositions, i * 3, rightPos);
        CorridorGeometryLibrary.addAttribute(
          finalPositions,
          leftPos,
          undefined,
          back
        );
        CorridorGeometryLibrary.addAttribute(finalPositions, rightPos, front);

        LR = front / 3;
        LL = LR - 1;
        UR = (back - 2) / 3;
        UL = UR + 1;
        indices[index++] = UL;
        indices[index++] = UR;
        indices[index++] = LL;
        indices[index++] = LR;

        front += 3;
        back -= 3;
      }

      wallIndices.push(front / 3);
    } else {
      wallIndices.push(front / 3, (back - 2) / 3);
    }
    indices[index++] = front / 3;
    indices[index++] = (back - 2) / 3;

    attributes.position = new GeometryAttribute({
      componentDatatype: ComponentDatatype$1.DOUBLE,
      componentsPerAttribute: 3,
      values: finalPositions,
    });

    return {
      attributes: attributes,
      indices: indices,
      wallIndices: wallIndices,
    };
  }

  function computePositionsExtruded(params) {
    const ellipsoid = params.ellipsoid;
    const computedPositions = CorridorGeometryLibrary.computePositions(params);
    const attr = combine(computedPositions, params.cornerType);
    const wallIndices = attr.wallIndices;
    const height = params.height;
    const extrudedHeight = params.extrudedHeight;
    const attributes = attr.attributes;
    const indices = attr.indices;
    let positions = attributes.position.values;
    let length = positions.length;
    let extrudedPositions = new Float64Array(length);
    extrudedPositions.set(positions);
    const newPositions = new Float64Array(length * 2);

    positions = PolygonPipeline.scaleToGeodeticHeight(
      positions,
      height,
      ellipsoid
    );
    extrudedPositions = PolygonPipeline.scaleToGeodeticHeight(
      extrudedPositions,
      extrudedHeight,
      ellipsoid
    );
    newPositions.set(positions);
    newPositions.set(extrudedPositions, length);
    attributes.position.values = newPositions;

    length /= 3;
    if (defined(params.offsetAttribute)) {
      let applyOffset = new Uint8Array(length * 2);
      if (params.offsetAttribute === GeometryOffsetAttribute$1.TOP) {
        applyOffset = applyOffset.fill(1, 0, length);
      } else {
        const applyOffsetValue =
          params.offsetAttribute === GeometryOffsetAttribute$1.NONE ? 0 : 1;
        applyOffset = applyOffset.fill(applyOffsetValue);
      }

      attributes.applyOffset = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
        componentsPerAttribute: 1,
        values: applyOffset,
      });
    }

    let i;
    const iLength = indices.length;
    const newIndices = IndexDatatype$1.createTypedArray(
      newPositions.length / 3,
      (iLength + wallIndices.length) * 2
    );
    newIndices.set(indices);
    let index = iLength;
    for (i = 0; i < iLength; i += 2) {
      // bottom indices
      const v0 = indices[i];
      const v1 = indices[i + 1];
      newIndices[index++] = v0 + length;
      newIndices[index++] = v1 + length;
    }

    let UL, LL;
    for (i = 0; i < wallIndices.length; i++) {
      //wall indices
      UL = wallIndices[i];
      LL = UL + length;
      newIndices[index++] = UL;
      newIndices[index++] = LL;
    }

    return {
      attributes: attributes,
      indices: newIndices,
    };
  }

  /**
   * A description of a corridor outline.
   *
   * @alias CorridorOutlineGeometry
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Cartesian3[]} options.positions An array of positions that define the center of the corridor outline.
   * @param {Number} options.width The distance between the edges of the corridor outline.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid to be used as a reference.
   * @param {Number} [options.granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
   * @param {Number} [options.height=0] The distance in meters between the positions and the ellipsoid surface.
   * @param {Number} [options.extrudedHeight] The distance in meters between the extruded face and the ellipsoid surface.
   * @param {CornerType} [options.cornerType=CornerType.ROUNDED] Determines the style of the corners.
   *
   * @see CorridorOutlineGeometry.createGeometry
   *
   * @example
   * const corridor = new Cesium.CorridorOutlineGeometry({
   *   positions : Cesium.Cartesian3.fromDegreesArray([-72.0, 40.0, -70.0, 35.0]),
   *   width : 100000
   * });
   */
  function CorridorOutlineGeometry(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const positions = options.positions;
    const width = options.width;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.positions", positions);
    Check.typeOf.number("options.width", width);
    //>>includeEnd('debug');

    const height = defaultValue(options.height, 0.0);
    const extrudedHeight = defaultValue(options.extrudedHeight, height);

    this._positions = positions;
    this._ellipsoid = Ellipsoid.clone(
      defaultValue(options.ellipsoid, Ellipsoid.WGS84)
    );
    this._width = width;
    this._height = Math.max(height, extrudedHeight);
    this._extrudedHeight = Math.min(height, extrudedHeight);
    this._cornerType = defaultValue(options.cornerType, CornerType$1.ROUNDED);
    this._granularity = defaultValue(
      options.granularity,
      CesiumMath.RADIANS_PER_DEGREE
    );
    this._offsetAttribute = options.offsetAttribute;
    this._workerName = "createCorridorOutlineGeometry";

    /**
     * The number of elements used to pack the object into an array.
     * @type {Number}
     */
    this.packedLength =
      1 + positions.length * Cartesian3.packedLength + Ellipsoid.packedLength + 6;
  }

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {CorridorOutlineGeometry} 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
   */
  CorridorOutlineGeometry.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    Check.typeOf.object("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    const positions = value._positions;
    const length = positions.length;
    array[startingIndex++] = length;

    for (let i = 0; i < length; ++i, startingIndex += Cartesian3.packedLength) {
      Cartesian3.pack(positions[i], array, startingIndex);
    }

    Ellipsoid.pack(value._ellipsoid, array, startingIndex);
    startingIndex += Ellipsoid.packedLength;

    array[startingIndex++] = value._width;
    array[startingIndex++] = value._height;
    array[startingIndex++] = value._extrudedHeight;
    array[startingIndex++] = value._cornerType;
    array[startingIndex++] = value._granularity;
    array[startingIndex] = defaultValue(value._offsetAttribute, -1);

    return array;
  };

  const scratchEllipsoid$a = Ellipsoid.clone(Ellipsoid.UNIT_SPHERE);
  const scratchOptions$e = {
    positions: undefined,
    ellipsoid: scratchEllipsoid$a,
    width: undefined,
    height: undefined,
    extrudedHeight: undefined,
    cornerType: undefined,
    granularity: undefined,
    offsetAttribute: undefined,
  };

  /**
   * 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 {CorridorOutlineGeometry} [result] The object into which to store the result.
   * @returns {CorridorOutlineGeometry} The modified result parameter or a new CorridorOutlineGeometry instance if one was not provided.
   */
  CorridorOutlineGeometry.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    const length = array[startingIndex++];
    const positions = new Array(length);

    for (let i = 0; i < length; ++i, startingIndex += Cartesian3.packedLength) {
      positions[i] = Cartesian3.unpack(array, startingIndex);
    }

    const ellipsoid = Ellipsoid.unpack(array, startingIndex, scratchEllipsoid$a);
    startingIndex += Ellipsoid.packedLength;

    const width = array[startingIndex++];
    const height = array[startingIndex++];
    const extrudedHeight = array[startingIndex++];
    const cornerType = array[startingIndex++];
    const granularity = array[startingIndex++];
    const offsetAttribute = array[startingIndex];

    if (!defined(result)) {
      scratchOptions$e.positions = positions;
      scratchOptions$e.width = width;
      scratchOptions$e.height = height;
      scratchOptions$e.extrudedHeight = extrudedHeight;
      scratchOptions$e.cornerType = cornerType;
      scratchOptions$e.granularity = granularity;
      scratchOptions$e.offsetAttribute =
        offsetAttribute === -1 ? undefined : offsetAttribute;
      return new CorridorOutlineGeometry(scratchOptions$e);
    }

    result._positions = positions;
    result._ellipsoid = Ellipsoid.clone(ellipsoid, result._ellipsoid);
    result._width = width;
    result._height = height;
    result._extrudedHeight = extrudedHeight;
    result._cornerType = cornerType;
    result._granularity = granularity;
    result._offsetAttribute =
      offsetAttribute === -1 ? undefined : offsetAttribute;

    return result;
  };

  /**
   * Computes the geometric representation of a corridor, including its vertices, indices, and a bounding sphere.
   *
   * @param {CorridorOutlineGeometry} corridorOutlineGeometry A description of the corridor.
   * @returns {Geometry|undefined} The computed vertices and indices.
   */
  CorridorOutlineGeometry.createGeometry = function (corridorOutlineGeometry) {
    let positions = corridorOutlineGeometry._positions;
    const width = corridorOutlineGeometry._width;
    const ellipsoid = corridorOutlineGeometry._ellipsoid;

    positions = scaleToSurface(positions, ellipsoid);
    const cleanPositions = arrayRemoveDuplicates(
      positions,
      Cartesian3.equalsEpsilon
    );

    if (cleanPositions.length < 2 || width <= 0) {
      return;
    }

    const height = corridorOutlineGeometry._height;
    const extrudedHeight = corridorOutlineGeometry._extrudedHeight;
    const extrude = !CesiumMath.equalsEpsilon(
      height,
      extrudedHeight,
      0,
      CesiumMath.EPSILON2
    );

    const params = {
      ellipsoid: ellipsoid,
      positions: cleanPositions,
      width: width,
      cornerType: corridorOutlineGeometry._cornerType,
      granularity: corridorOutlineGeometry._granularity,
      saveAttributes: false,
    };
    let attr;
    if (extrude) {
      params.height = height;
      params.extrudedHeight = extrudedHeight;
      params.offsetAttribute = corridorOutlineGeometry._offsetAttribute;
      attr = computePositionsExtruded(params);
    } else {
      const computedPositions = CorridorGeometryLibrary.computePositions(params);
      attr = combine(computedPositions, params.cornerType);
      attr.attributes.position.values = PolygonPipeline.scaleToGeodeticHeight(
        attr.attributes.position.values,
        height,
        ellipsoid
      );

      if (defined(corridorOutlineGeometry._offsetAttribute)) {
        const length = attr.attributes.position.values.length;
        const offsetValue =
          corridorOutlineGeometry._offsetAttribute ===
          GeometryOffsetAttribute$1.NONE
            ? 0
            : 1;
        const applyOffset = new Uint8Array(length / 3).fill(offsetValue);
        attr.attributes.applyOffset = new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
          componentsPerAttribute: 1,
          values: applyOffset,
        });
      }
    }
    const attributes = attr.attributes;
    const boundingSphere = BoundingSphere.fromVertices(
      attributes.position.values,
      undefined,
      3
    );

    return new Geometry({
      attributes: attributes,
      indices: attr.indices,
      primitiveType: PrimitiveType$1.LINES,
      boundingSphere: boundingSphere,
      offsetAttribute: corridorOutlineGeometry._offsetAttribute,
    });
  };

  /**
   * The culling volume defined by planes.
   *
   * @alias CullingVolume
   * @constructor
   *
   * @param {Cartesian4[]} [planes] An array of clipping planes.
   */
  function CullingVolume(planes) {
    /**
     * Each plane is represented by a Cartesian4 object, where the x, y, and z components
     * define the unit vector normal to the plane, and the w component is the distance of the
     * plane from the origin.
     * @type {Cartesian4[]}
     * @default []
     */
    this.planes = defaultValue(planes, []);
  }

  const faces = [new Cartesian3(), new Cartesian3(), new Cartesian3()];
  Cartesian3.clone(Cartesian3.UNIT_X, faces[0]);
  Cartesian3.clone(Cartesian3.UNIT_Y, faces[1]);
  Cartesian3.clone(Cartesian3.UNIT_Z, faces[2]);

  const scratchPlaneCenter = new Cartesian3();
  const scratchPlaneNormal = new Cartesian3();
  const scratchPlane$1 = new Plane(new Cartesian3(1.0, 0.0, 0.0), 0.0);

  /**
   * Constructs a culling volume from a bounding sphere. Creates six planes that create a box containing the sphere.
   * The planes are aligned to the x, y, and z axes in world coordinates.
   *
   * @param {BoundingSphere} boundingSphere The bounding sphere used to create the culling volume.
   * @param {CullingVolume} [result] The object onto which to store the result.
   * @returns {CullingVolume} The culling volume created from the bounding sphere.
   */
  CullingVolume.fromBoundingSphere = function (boundingSphere, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(boundingSphere)) {
      throw new DeveloperError("boundingSphere is required.");
    }
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new CullingVolume();
    }

    const length = faces.length;
    const planes = result.planes;
    planes.length = 2 * length;

    const center = boundingSphere.center;
    const radius = boundingSphere.radius;

    let planeIndex = 0;

    for (let i = 0; i < length; ++i) {
      const faceNormal = faces[i];

      let plane0 = planes[planeIndex];
      let plane1 = planes[planeIndex + 1];

      if (!defined(plane0)) {
        plane0 = planes[planeIndex] = new Cartesian4();
      }
      if (!defined(plane1)) {
        plane1 = planes[planeIndex + 1] = new Cartesian4();
      }

      Cartesian3.multiplyByScalar(faceNormal, -radius, scratchPlaneCenter);
      Cartesian3.add(center, scratchPlaneCenter, scratchPlaneCenter);

      plane0.x = faceNormal.x;
      plane0.y = faceNormal.y;
      plane0.z = faceNormal.z;
      plane0.w = -Cartesian3.dot(faceNormal, scratchPlaneCenter);

      Cartesian3.multiplyByScalar(faceNormal, radius, scratchPlaneCenter);
      Cartesian3.add(center, scratchPlaneCenter, scratchPlaneCenter);

      plane1.x = -faceNormal.x;
      plane1.y = -faceNormal.y;
      plane1.z = -faceNormal.z;
      plane1.w = -Cartesian3.dot(
        Cartesian3.negate(faceNormal, scratchPlaneNormal),
        scratchPlaneCenter
      );

      planeIndex += 2;
    }

    return result;
  };

  /**
   * Determines whether a bounding volume intersects the culling volume.
   *
   * @param {Object} boundingVolume The bounding volume whose intersection with the culling volume is to be tested.
   * @returns {Intersect}  Intersect.OUTSIDE, Intersect.INTERSECTING, or Intersect.INSIDE.
   */
  CullingVolume.prototype.computeVisibility = function (boundingVolume) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(boundingVolume)) {
      throw new DeveloperError("boundingVolume is required.");
    }
    //>>includeEnd('debug');

    const planes = this.planes;
    let intersecting = false;
    for (let k = 0, len = planes.length; k < len; ++k) {
      const result = boundingVolume.intersectPlane(
        Plane.fromCartesian4(planes[k], scratchPlane$1)
      );
      if (result === Intersect$1.OUTSIDE) {
        return Intersect$1.OUTSIDE;
      } else if (result === Intersect$1.INTERSECTING) {
        intersecting = true;
      }
    }

    return intersecting ? Intersect$1.INTERSECTING : Intersect$1.INSIDE;
  };

  /**
   * Determines whether a bounding volume intersects the culling volume.
   *
   * @param {Object} boundingVolume The bounding volume whose intersection with the culling volume is to be tested.
   * @param {Number} parentPlaneMask A bit mask from the boundingVolume's parent's check against the same culling
   *                                 volume, such that if (planeMask & (1 << planeIndex) === 0), for k < 31, then
   *                                 the parent (and therefore this) volume is completely inside plane[planeIndex]
   *                                 and that plane check can be skipped.
   * @returns {Number} A plane mask as described above (which can be applied to this boundingVolume's children).
   *
   * @private
   */
  CullingVolume.prototype.computeVisibilityWithPlaneMask = function (
    boundingVolume,
    parentPlaneMask
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(boundingVolume)) {
      throw new DeveloperError("boundingVolume is required.");
    }
    if (!defined(parentPlaneMask)) {
      throw new DeveloperError("parentPlaneMask is required.");
    }
    //>>includeEnd('debug');

    if (
      parentPlaneMask === CullingVolume.MASK_OUTSIDE ||
      parentPlaneMask === CullingVolume.MASK_INSIDE
    ) {
      // parent is completely outside or completely inside, so this child is as well.
      return parentPlaneMask;
    }

    // Start with MASK_INSIDE (all zeros) so that after the loop, the return value can be compared with MASK_INSIDE.
    // (Because if there are fewer than 31 planes, the upper bits wont be changed.)
    let mask = CullingVolume.MASK_INSIDE;

    const planes = this.planes;
    for (let k = 0, len = planes.length; k < len; ++k) {
      // For k greater than 31 (since 31 is the maximum number of INSIDE/INTERSECTING bits we can store), skip the optimization.
      const flag = k < 31 ? 1 << k : 0;
      if (k < 31 && (parentPlaneMask & flag) === 0) {
        // boundingVolume is known to be INSIDE this plane.
        continue;
      }

      const result = boundingVolume.intersectPlane(
        Plane.fromCartesian4(planes[k], scratchPlane$1)
      );
      if (result === Intersect$1.OUTSIDE) {
        return CullingVolume.MASK_OUTSIDE;
      } else if (result === Intersect$1.INTERSECTING) {
        mask |= flag;
      }
    }

    return mask;
  };

  /**
   * For plane masks (as used in {@link CullingVolume#computeVisibilityWithPlaneMask}), this special value
   * represents the case where the object bounding volume is entirely outside the culling volume.
   *
   * @type {Number}
   * @private
   */
  CullingVolume.MASK_OUTSIDE = 0xffffffff;

  /**
   * For plane masks (as used in {@link CullingVolume.prototype.computeVisibilityWithPlaneMask}), this value
   * represents the case where the object bounding volume is entirely inside the culling volume.
   *
   * @type {Number}
   * @private
   */
  CullingVolume.MASK_INSIDE = 0x00000000;

  /**
   * For plane masks (as used in {@link CullingVolume.prototype.computeVisibilityWithPlaneMask}), this value
   * represents the case where the object bounding volume (may) intersect all planes of the culling volume.
   *
   * @type {Number}
   * @private
   */
  CullingVolume.MASK_INDETERMINATE = 0x7fffffff;

  /**
   * @callback CustomHeightmapTerrainProvider.GeometryCallback
   * @param {Number} x The X coordinate of the tile for which to request geometry.
   * @param {Number} y The Y coordinate of the tile for which to request geometry.
   * @param {Number} level The level of the tile for which to request geometry.
   * @returns {Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array|Number[]|Promise.<Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array|Number[]>|undefined} An array or a promise to an array of heights in row-major order. If undefined, the globe will render the parent tile.
   */

  /**
   * A simple {@link TerrainProvider} that gets height values from a callback function.
   * It can be used for procedurally generated terrain or as a way to load custom
   * heightmap data without creating a subclass of {@link TerrainProvider}.
   *
   * There are some limitations such as no water mask, no vertex normals, and no
   * availability, so a full-fledged {@link TerrainProvider} subclass is better suited
   * for these more sophisticated use cases.
   *
   * @alias CustomHeightmapTerrainProvider
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {CustomHeightmapTerrainProvider.GeometryCallback} options.callback The callback function for requesting tile geometry.
   * @param {Number} options.width The number of columns per heightmap tile.
   * @param {Number} options.height The number of rows per heightmap tile.
   * @param {TilingScheme} [options.tilingScheme] The tiling scheme specifying how the ellipsoidal
   * surface is broken into tiles. If this parameter is not provided, a {@link GeographicTilingScheme}
   * is used.
   * @param {Ellipsoid} [options.ellipsoid] The ellipsoid.  If the tilingScheme is specified,
   * this parameter is ignored and the tiling scheme's ellipsoid is used instead. If neither
   * parameter is specified, the WGS84 ellipsoid is used.
   * @param {Credit|String} [options.credit] A credit for the data source, which is displayed on the canvas.
   *
   * @example
   * const viewer = new Cesium.Viewer("cesiumContainer", {
   *   terrainProvider: new Cesium.CustomHeightmapTerrainProvider({
   *     width: 32,
   *     height: 32,
   *     callback: function (x, y, level) {
   *       return new Float32Array(32 * 32); // all zeros
   *     },
   *   }),
   * });
   *
   * @see TerrainProvider
   */
  function CustomHeightmapTerrainProvider(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    Check.defined("options.callback", options.callback);
    Check.defined("options.width", options.width);
    Check.defined("options.height", options.height);
    //>>includeEnd('debug');

    this._callback = options.callback;

    this._tilingScheme = options.tilingScheme;
    if (!defined(this._tilingScheme)) {
      this._tilingScheme = new GeographicTilingScheme({
        ellipsoid: defaultValue(options.ellipsoid, Ellipsoid.WGS84),
      });
    }

    this._width = options.width;
    this._height = options.height;
    const maxTileDimensions = Math.max(this._width, this._height);

    this._levelZeroMaximumGeometricError = TerrainProvider.getEstimatedLevelZeroGeometricErrorForAHeightmap(
      this._tilingScheme.ellipsoid,
      maxTileDimensions,
      this._tilingScheme.getNumberOfXTilesAtLevel(0)
    );

    this._errorEvent = new Event();

    let credit = options.credit;
    if (typeof credit === "string") {
      credit = new Credit(credit);
    }
    this._credit = credit;

    this._readyPromise = Promise.resolve(true);
  }

  Object.defineProperties(CustomHeightmapTerrainProvider.prototype, {
    /**
     * Gets an event that is raised when the terrain provider encounters an asynchronous error. By subscribing
     * to the event, you will be notified of the error and can potentially recover from it. Event listeners
     * are passed an instance of {@link TileProviderError}.
     * @memberof CustomHeightmapTerrainProvider.prototype
     * @type {Event}
     * @readonly
     */
    errorEvent: {
      get: function () {
        return this._errorEvent;
      },
    },

    /**
     * Gets the credit to display when this terrain provider is active. Typically this is used to credit
     * the source of the terrain.
     * @memberof CustomHeightmapTerrainProvider.prototype
     * @type {Credit}
     * @readonly
     */
    credit: {
      get: function () {
        return this._credit;
      },
    },

    /**
     * Gets the tiling scheme used by this provider.
     * @memberof CustomHeightmapTerrainProvider.prototype
     * @type {TilingScheme}
     * @readonly
     */
    tilingScheme: {
      get: function () {
        return this._tilingScheme;
      },
    },

    /**
     * Gets a value indicating whether or not the provider is ready for use.
     * @memberof CustomHeightmapTerrainProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    ready: {
      get: function () {
        return true;
      },
    },

    /**
     * Gets a promise that resolves to true when the provider is ready for use.
     * @memberof CustomHeightmapTerrainProvider.prototype
     * @type {Promise.<Boolean>}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._readyPromise;
      },
    },

    /**
     * Gets a value indicating whether or not the provider includes a water mask. The water mask
     * indicates which areas of the globe are water rather than land, so they can be rendered
     * as a reflective surface with animated waves.
     * Water mask is not supported by {@link CustomHeightmapTerrainProvider}, so the return
     * value will always be false.
     * @memberof CustomHeightmapTerrainProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    hasWaterMask: {
      get: function () {
        return false;
      },
    },

    /**
     * Gets a value indicating whether or not the requested tiles include vertex normals.
     * Vertex normals are not supported by {@link CustomHeightmapTerrainProvider}, so the return
     * value will always be false.
     * @memberof CustomHeightmapTerrainProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    hasVertexNormals: {
      get: function () {
        return false;
      },
    },

    /**
     * Gets the number of columns per heightmap tile.
     * @memberof CustomHeightmapTerrainProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    width: {
      get: function () {
        return this._width;
      },
    },

    /**
     * Gets the number of rows per heightmap tile.
     * @memberof CustomHeightmapTerrainProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    height: {
      get: function () {
        return this._height;
      },
    },
  });

  /**
   * Requests the geometry for a given tile. The result includes terrain
   * data and indicates that all child tiles are available.
   *
   * @param {Number} x The X coordinate of the tile for which to request geometry.
   * @param {Number} y The Y coordinate of the tile for which to request geometry.
   * @param {Number} level The level of the tile for which to request geometry.
   * @param {Request} [request] The request object. Intended for internal use only.
   *
   * @returns {Promise.<TerrainData>|undefined} A promise for the requested geometry. If this method
   *          returns undefined instead of a promise, it is an indication that too many requests are already
   *          pending and the request will be retried later.
   */
  CustomHeightmapTerrainProvider.prototype.requestTileGeometry = function (
    x,
    y,
    level,
    request
  ) {
    const promise = this._callback(x, y, level);
    if (!defined(promise)) {
      return undefined;
    }

    const width = this._width;
    const height = this._height;

    return Promise.resolve(promise).then(function (heightmapData) {
      let buffer = heightmapData;
      if (Array.isArray(buffer)) {
        // HeightmapTerrainData expects a TypedArray, so convert from Number[] to Float64Array
        buffer = new Float64Array(buffer);
      }

      return new HeightmapTerrainData({
        buffer: buffer,
        width: width,
        height: height,
      });
    });
  };

  /**
   * Gets the maximum geometric error allowed in a tile at a given level.
   *
   * @param {Number} level The tile level for which to get the maximum geometric error.
   * @returns {Number} The maximum geometric error.
   */
  CustomHeightmapTerrainProvider.prototype.getLevelMaximumGeometricError = function (
    level
  ) {
    return this._levelZeroMaximumGeometricError / (1 << level);
  };

  /**
   * Determines whether data for a tile is available to be loaded.
   *
   * @param {Number} x The X coordinate of the tile for which to request geometry.
   * @param {Number} y The Y coordinate of the tile for which to request geometry.
   * @param {Number} level The level of the tile for which to request geometry.
   * @returns {Boolean|undefined} Undefined if not supported, otherwise true or false.
   */
  CustomHeightmapTerrainProvider.prototype.getTileDataAvailable = function (
    x,
    y,
    level
  ) {
    return undefined;
  };

  /**
   * Makes sure we load availability data for a tile
   *
   * @param {Number} x The X coordinate of the tile for which to request geometry.
   * @param {Number} y The Y coordinate of the tile for which to request geometry.
   * @param {Number} level The level of the tile for which to request geometry.
   * @returns {undefined|Promise<void>} Undefined if nothing need to be loaded or a Promise that resolves when all required tiles are loaded
   */
  CustomHeightmapTerrainProvider.prototype.loadTileDataAvailability = function (
    x,
    y,
    level
  ) {
    return undefined;
  };

  /**
   * @private
   */
  const CylinderGeometryLibrary = {};

  /**
   * @private
   */
  CylinderGeometryLibrary.computePositions = function (
    length,
    topRadius,
    bottomRadius,
    slices,
    fill
  ) {
    const topZ = length * 0.5;
    const bottomZ = -topZ;

    const twoSlice = slices + slices;
    const size = fill ? 2 * twoSlice : twoSlice;
    const positions = new Float64Array(size * 3);
    let i;
    let index = 0;
    let tbIndex = 0;
    const bottomOffset = fill ? twoSlice * 3 : 0;
    const topOffset = fill ? (twoSlice + slices) * 3 : slices * 3;

    for (i = 0; i < slices; i++) {
      const angle = (i / slices) * CesiumMath.TWO_PI;
      const x = Math.cos(angle);
      const y = Math.sin(angle);
      const bottomX = x * bottomRadius;
      const bottomY = y * bottomRadius;
      const topX = x * topRadius;
      const topY = y * topRadius;

      positions[tbIndex + bottomOffset] = bottomX;
      positions[tbIndex + bottomOffset + 1] = bottomY;
      positions[tbIndex + bottomOffset + 2] = bottomZ;

      positions[tbIndex + topOffset] = topX;
      positions[tbIndex + topOffset + 1] = topY;
      positions[tbIndex + topOffset + 2] = topZ;
      tbIndex += 3;
      if (fill) {
        positions[index++] = bottomX;
        positions[index++] = bottomY;
        positions[index++] = bottomZ;
        positions[index++] = topX;
        positions[index++] = topY;
        positions[index++] = topZ;
      }
    }

    return positions;
  };

  const radiusScratch$1 = new Cartesian2();
  const normalScratch$3 = new Cartesian3();
  const bitangentScratch$1 = new Cartesian3();
  const tangentScratch$1 = new Cartesian3();
  const positionScratch$c = new Cartesian3();

  /**
   * A description of a cylinder.
   *
   * @alias CylinderGeometry
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Number} options.length The length of the cylinder.
   * @param {Number} options.topRadius The radius of the top of the cylinder.
   * @param {Number} options.bottomRadius The radius of the bottom of the cylinder.
   * @param {Number} [options.slices=128] The number of edges around the perimeter of the cylinder.
   * @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
   *
   * @exception {DeveloperError} options.slices must be greater than or equal to 3.
   *
   * @see CylinderGeometry.createGeometry
   *
   * @example
   * // create cylinder geometry
   * const cylinder = new Cesium.CylinderGeometry({
   *     length: 200000,
   *     topRadius: 80000,
   *     bottomRadius: 200000,
   * });
   * const geometry = Cesium.CylinderGeometry.createGeometry(cylinder);
   */
  function CylinderGeometry(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const length = options.length;
    const topRadius = options.topRadius;
    const bottomRadius = options.bottomRadius;
    const vertexFormat = defaultValue(options.vertexFormat, VertexFormat.DEFAULT);
    const slices = defaultValue(options.slices, 128);

    //>>includeStart('debug', pragmas.debug);
    if (!defined(length)) {
      throw new DeveloperError("options.length must be defined.");
    }
    if (!defined(topRadius)) {
      throw new DeveloperError("options.topRadius must be defined.");
    }
    if (!defined(bottomRadius)) {
      throw new DeveloperError("options.bottomRadius must be defined.");
    }
    if (slices < 3) {
      throw new DeveloperError(
        "options.slices must be greater than or equal to 3."
      );
    }
    if (
      defined(options.offsetAttribute) &&
      options.offsetAttribute === GeometryOffsetAttribute$1.TOP
    ) {
      throw new DeveloperError(
        "GeometryOffsetAttribute.TOP is not a supported options.offsetAttribute for this geometry."
      );
    }
    //>>includeEnd('debug');

    this._length = length;
    this._topRadius = topRadius;
    this._bottomRadius = bottomRadius;
    this._vertexFormat = VertexFormat.clone(vertexFormat);
    this._slices = slices;
    this._offsetAttribute = options.offsetAttribute;
    this._workerName = "createCylinderGeometry";
  }

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  CylinderGeometry.packedLength = VertexFormat.packedLength + 5;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {CylinderGeometry} 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
   */
  CylinderGeometry.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(value)) {
      throw new DeveloperError("value is required");
    }
    if (!defined(array)) {
      throw new DeveloperError("array is required");
    }
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    VertexFormat.pack(value._vertexFormat, array, startingIndex);
    startingIndex += VertexFormat.packedLength;

    array[startingIndex++] = value._length;
    array[startingIndex++] = value._topRadius;
    array[startingIndex++] = value._bottomRadius;
    array[startingIndex++] = value._slices;
    array[startingIndex] = defaultValue(value._offsetAttribute, -1);

    return array;
  };

  const scratchVertexFormat$8 = new VertexFormat();
  const scratchOptions$d = {
    vertexFormat: scratchVertexFormat$8,
    length: undefined,
    topRadius: undefined,
    bottomRadius: undefined,
    slices: undefined,
    offsetAttribute: undefined,
  };

  /**
   * 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 {CylinderGeometry} [result] The object into which to store the result.
   * @returns {CylinderGeometry} The modified result parameter or a new CylinderGeometry instance if one was not provided.
   */
  CylinderGeometry.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(array)) {
      throw new DeveloperError("array is required");
    }
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    const vertexFormat = VertexFormat.unpack(
      array,
      startingIndex,
      scratchVertexFormat$8
    );
    startingIndex += VertexFormat.packedLength;

    const length = array[startingIndex++];
    const topRadius = array[startingIndex++];
    const bottomRadius = array[startingIndex++];
    const slices = array[startingIndex++];
    const offsetAttribute = array[startingIndex];

    if (!defined(result)) {
      scratchOptions$d.length = length;
      scratchOptions$d.topRadius = topRadius;
      scratchOptions$d.bottomRadius = bottomRadius;
      scratchOptions$d.slices = slices;
      scratchOptions$d.offsetAttribute =
        offsetAttribute === -1 ? undefined : offsetAttribute;
      return new CylinderGeometry(scratchOptions$d);
    }

    result._vertexFormat = VertexFormat.clone(vertexFormat, result._vertexFormat);
    result._length = length;
    result._topRadius = topRadius;
    result._bottomRadius = bottomRadius;
    result._slices = slices;
    result._offsetAttribute =
      offsetAttribute === -1 ? undefined : offsetAttribute;

    return result;
  };

  /**
   * Computes the geometric representation of a cylinder, including its vertices, indices, and a bounding sphere.
   *
   * @param {CylinderGeometry} cylinderGeometry A description of the cylinder.
   * @returns {Geometry|undefined} The computed vertices and indices.
   */
  CylinderGeometry.createGeometry = function (cylinderGeometry) {
    let length = cylinderGeometry._length;
    const topRadius = cylinderGeometry._topRadius;
    const bottomRadius = cylinderGeometry._bottomRadius;
    const vertexFormat = cylinderGeometry._vertexFormat;
    const slices = cylinderGeometry._slices;

    if (
      length <= 0 ||
      topRadius < 0 ||
      bottomRadius < 0 ||
      (topRadius === 0 && bottomRadius === 0)
    ) {
      return;
    }

    const twoSlices = slices + slices;
    const threeSlices = slices + twoSlices;
    const numVertices = twoSlices + twoSlices;

    const positions = CylinderGeometryLibrary.computePositions(
      length,
      topRadius,
      bottomRadius,
      slices,
      true
    );

    const st = vertexFormat.st ? new Float32Array(numVertices * 2) : undefined;
    const normals = vertexFormat.normal
      ? new Float32Array(numVertices * 3)
      : undefined;
    const tangents = vertexFormat.tangent
      ? new Float32Array(numVertices * 3)
      : undefined;
    const bitangents = vertexFormat.bitangent
      ? new Float32Array(numVertices * 3)
      : undefined;

    let i;
    const computeNormal =
      vertexFormat.normal || vertexFormat.tangent || vertexFormat.bitangent;

    if (computeNormal) {
      const computeTangent = vertexFormat.tangent || vertexFormat.bitangent;

      let normalIndex = 0;
      let tangentIndex = 0;
      let bitangentIndex = 0;

      const theta = Math.atan2(bottomRadius - topRadius, length);
      const normal = normalScratch$3;
      normal.z = Math.sin(theta);
      const normalScale = Math.cos(theta);
      let tangent = tangentScratch$1;
      let bitangent = bitangentScratch$1;

      for (i = 0; i < slices; i++) {
        const angle = (i / slices) * CesiumMath.TWO_PI;
        const x = normalScale * Math.cos(angle);
        const y = normalScale * Math.sin(angle);
        if (computeNormal) {
          normal.x = x;
          normal.y = y;

          if (computeTangent) {
            tangent = Cartesian3.normalize(
              Cartesian3.cross(Cartesian3.UNIT_Z, normal, tangent),
              tangent
            );
          }

          if (vertexFormat.normal) {
            normals[normalIndex++] = normal.x;
            normals[normalIndex++] = normal.y;
            normals[normalIndex++] = normal.z;
            normals[normalIndex++] = normal.x;
            normals[normalIndex++] = normal.y;
            normals[normalIndex++] = normal.z;
          }

          if (vertexFormat.tangent) {
            tangents[tangentIndex++] = tangent.x;
            tangents[tangentIndex++] = tangent.y;
            tangents[tangentIndex++] = tangent.z;
            tangents[tangentIndex++] = tangent.x;
            tangents[tangentIndex++] = tangent.y;
            tangents[tangentIndex++] = tangent.z;
          }

          if (vertexFormat.bitangent) {
            bitangent = Cartesian3.normalize(
              Cartesian3.cross(normal, tangent, bitangent),
              bitangent
            );
            bitangents[bitangentIndex++] = bitangent.x;
            bitangents[bitangentIndex++] = bitangent.y;
            bitangents[bitangentIndex++] = bitangent.z;
            bitangents[bitangentIndex++] = bitangent.x;
            bitangents[bitangentIndex++] = bitangent.y;
            bitangents[bitangentIndex++] = bitangent.z;
          }
        }
      }

      for (i = 0; i < slices; i++) {
        if (vertexFormat.normal) {
          normals[normalIndex++] = 0;
          normals[normalIndex++] = 0;
          normals[normalIndex++] = -1;
        }
        if (vertexFormat.tangent) {
          tangents[tangentIndex++] = 1;
          tangents[tangentIndex++] = 0;
          tangents[tangentIndex++] = 0;
        }
        if (vertexFormat.bitangent) {
          bitangents[bitangentIndex++] = 0;
          bitangents[bitangentIndex++] = -1;
          bitangents[bitangentIndex++] = 0;
        }
      }

      for (i = 0; i < slices; i++) {
        if (vertexFormat.normal) {
          normals[normalIndex++] = 0;
          normals[normalIndex++] = 0;
          normals[normalIndex++] = 1;
        }
        if (vertexFormat.tangent) {
          tangents[tangentIndex++] = 1;
          tangents[tangentIndex++] = 0;
          tangents[tangentIndex++] = 0;
        }
        if (vertexFormat.bitangent) {
          bitangents[bitangentIndex++] = 0;
          bitangents[bitangentIndex++] = 1;
          bitangents[bitangentIndex++] = 0;
        }
      }
    }

    const numIndices = 12 * slices - 12;
    const indices = IndexDatatype$1.createTypedArray(numVertices, numIndices);
    let index = 0;
    let j = 0;
    for (i = 0; i < slices - 1; i++) {
      indices[index++] = j;
      indices[index++] = j + 2;
      indices[index++] = j + 3;

      indices[index++] = j;
      indices[index++] = j + 3;
      indices[index++] = j + 1;

      j += 2;
    }

    indices[index++] = twoSlices - 2;
    indices[index++] = 0;
    indices[index++] = 1;
    indices[index++] = twoSlices - 2;
    indices[index++] = 1;
    indices[index++] = twoSlices - 1;

    for (i = 1; i < slices - 1; i++) {
      indices[index++] = twoSlices + i + 1;
      indices[index++] = twoSlices + i;
      indices[index++] = twoSlices;
    }

    for (i = 1; i < slices - 1; i++) {
      indices[index++] = threeSlices;
      indices[index++] = threeSlices + i;
      indices[index++] = threeSlices + i + 1;
    }

    let textureCoordIndex = 0;
    if (vertexFormat.st) {
      const rad = Math.max(topRadius, bottomRadius);
      for (i = 0; i < numVertices; i++) {
        const position = Cartesian3.fromArray(positions, i * 3, positionScratch$c);
        st[textureCoordIndex++] = (position.x + rad) / (2.0 * rad);
        st[textureCoordIndex++] = (position.y + rad) / (2.0 * rad);
      }
    }

    const attributes = new GeometryAttributes();
    if (vertexFormat.position) {
      attributes.position = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.DOUBLE,
        componentsPerAttribute: 3,
        values: positions,
      });
    }

    if (vertexFormat.normal) {
      attributes.normal = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 3,
        values: normals,
      });
    }

    if (vertexFormat.tangent) {
      attributes.tangent = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 3,
        values: tangents,
      });
    }

    if (vertexFormat.bitangent) {
      attributes.bitangent = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 3,
        values: bitangents,
      });
    }

    if (vertexFormat.st) {
      attributes.st = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 2,
        values: st,
      });
    }

    radiusScratch$1.x = length * 0.5;
    radiusScratch$1.y = Math.max(bottomRadius, topRadius);

    const boundingSphere = new BoundingSphere(
      Cartesian3.ZERO,
      Cartesian2.magnitude(radiusScratch$1)
    );

    if (defined(cylinderGeometry._offsetAttribute)) {
      length = positions.length;
      const offsetValue =
        cylinderGeometry._offsetAttribute === GeometryOffsetAttribute$1.NONE
          ? 0
          : 1;
      const applyOffset = new Uint8Array(length / 3).fill(offsetValue);
      attributes.applyOffset = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
        componentsPerAttribute: 1,
        values: applyOffset,
      });
    }

    return new Geometry({
      attributes: attributes,
      indices: indices,
      primitiveType: PrimitiveType$1.TRIANGLES,
      boundingSphere: boundingSphere,
      offsetAttribute: cylinderGeometry._offsetAttribute,
    });
  };

  let unitCylinderGeometry;

  /**
   * Returns the geometric representation of a unit cylinder, including its vertices, indices, and a bounding sphere.
   * @returns {Geometry} The computed vertices and indices.
   *
   * @private
   */
  CylinderGeometry.getUnitCylinder = function () {
    if (!defined(unitCylinderGeometry)) {
      unitCylinderGeometry = CylinderGeometry.createGeometry(
        new CylinderGeometry({
          topRadius: 1.0,
          bottomRadius: 1.0,
          length: 1.0,
          vertexFormat: VertexFormat.POSITION_ONLY,
        })
      );
    }
    return unitCylinderGeometry;
  };

  const radiusScratch = new Cartesian2();

  /**
   * A description of the outline of a cylinder.
   *
   * @alias CylinderOutlineGeometry
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Number} options.length The length of the cylinder.
   * @param {Number} options.topRadius The radius of the top of the cylinder.
   * @param {Number} options.bottomRadius The radius of the bottom of the cylinder.
   * @param {Number} [options.slices=128] The number of edges around the perimeter of the cylinder.
   * @param {Number} [options.numberOfVerticalLines=16] Number of lines to draw between the top and bottom surfaces of the cylinder.
   *
   * @exception {DeveloperError} options.length must be greater than 0.
   * @exception {DeveloperError} options.topRadius must be greater than 0.
   * @exception {DeveloperError} options.bottomRadius must be greater than 0.
   * @exception {DeveloperError} bottomRadius and topRadius cannot both equal 0.
   * @exception {DeveloperError} options.slices must be greater than or equal to 3.
   *
   * @see CylinderOutlineGeometry.createGeometry
   *
   * @example
   * // create cylinder geometry
   * const cylinder = new Cesium.CylinderOutlineGeometry({
   *     length: 200000,
   *     topRadius: 80000,
   *     bottomRadius: 200000,
   * });
   * const geometry = Cesium.CylinderOutlineGeometry.createGeometry(cylinder);
   */
  function CylinderOutlineGeometry(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const length = options.length;
    const topRadius = options.topRadius;
    const bottomRadius = options.bottomRadius;
    const slices = defaultValue(options.slices, 128);
    const numberOfVerticalLines = Math.max(
      defaultValue(options.numberOfVerticalLines, 16),
      0
    );

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("options.positions", length);
    Check.typeOf.number("options.topRadius", topRadius);
    Check.typeOf.number("options.bottomRadius", bottomRadius);
    Check.typeOf.number.greaterThanOrEquals("options.slices", slices, 3);
    if (
      defined(options.offsetAttribute) &&
      options.offsetAttribute === GeometryOffsetAttribute$1.TOP
    ) {
      throw new DeveloperError(
        "GeometryOffsetAttribute.TOP is not a supported options.offsetAttribute for this geometry."
      );
    }
    //>>includeEnd('debug');

    this._length = length;
    this._topRadius = topRadius;
    this._bottomRadius = bottomRadius;
    this._slices = slices;
    this._numberOfVerticalLines = numberOfVerticalLines;
    this._offsetAttribute = options.offsetAttribute;
    this._workerName = "createCylinderOutlineGeometry";
  }

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  CylinderOutlineGeometry.packedLength = 6;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {CylinderOutlineGeometry} 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
   */
  CylinderOutlineGeometry.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    array[startingIndex++] = value._length;
    array[startingIndex++] = value._topRadius;
    array[startingIndex++] = value._bottomRadius;
    array[startingIndex++] = value._slices;
    array[startingIndex++] = value._numberOfVerticalLines;
    array[startingIndex] = defaultValue(value._offsetAttribute, -1);

    return array;
  };

  const scratchOptions$c = {
    length: undefined,
    topRadius: undefined,
    bottomRadius: undefined,
    slices: undefined,
    numberOfVerticalLines: undefined,
    offsetAttribute: undefined,
  };

  /**
   * 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 {CylinderOutlineGeometry} [result] The object into which to store the result.
   * @returns {CylinderOutlineGeometry} The modified result parameter or a new CylinderOutlineGeometry instance if one was not provided.
   */
  CylinderOutlineGeometry.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    const length = array[startingIndex++];
    const topRadius = array[startingIndex++];
    const bottomRadius = array[startingIndex++];
    const slices = array[startingIndex++];
    const numberOfVerticalLines = array[startingIndex++];
    const offsetAttribute = array[startingIndex];

    if (!defined(result)) {
      scratchOptions$c.length = length;
      scratchOptions$c.topRadius = topRadius;
      scratchOptions$c.bottomRadius = bottomRadius;
      scratchOptions$c.slices = slices;
      scratchOptions$c.numberOfVerticalLines = numberOfVerticalLines;
      scratchOptions$c.offsetAttribute =
        offsetAttribute === -1 ? undefined : offsetAttribute;
      return new CylinderOutlineGeometry(scratchOptions$c);
    }

    result._length = length;
    result._topRadius = topRadius;
    result._bottomRadius = bottomRadius;
    result._slices = slices;
    result._numberOfVerticalLines = numberOfVerticalLines;
    result._offsetAttribute =
      offsetAttribute === -1 ? undefined : offsetAttribute;

    return result;
  };

  /**
   * Computes the geometric representation of an outline of a cylinder, including its vertices, indices, and a bounding sphere.
   *
   * @param {CylinderOutlineGeometry} cylinderGeometry A description of the cylinder outline.
   * @returns {Geometry|undefined} The computed vertices and indices.
   */
  CylinderOutlineGeometry.createGeometry = function (cylinderGeometry) {
    let length = cylinderGeometry._length;
    const topRadius = cylinderGeometry._topRadius;
    const bottomRadius = cylinderGeometry._bottomRadius;
    const slices = cylinderGeometry._slices;
    const numberOfVerticalLines = cylinderGeometry._numberOfVerticalLines;

    if (
      length <= 0 ||
      topRadius < 0 ||
      bottomRadius < 0 ||
      (topRadius === 0 && bottomRadius === 0)
    ) {
      return;
    }

    const numVertices = slices * 2;

    const positions = CylinderGeometryLibrary.computePositions(
      length,
      topRadius,
      bottomRadius,
      slices,
      false
    );
    let numIndices = slices * 2;
    let numSide;
    if (numberOfVerticalLines > 0) {
      const numSideLines = Math.min(numberOfVerticalLines, slices);
      numSide = Math.round(slices / numSideLines);
      numIndices += numSideLines;
    }

    const indices = IndexDatatype$1.createTypedArray(numVertices, numIndices * 2);
    let index = 0;
    let i;
    for (i = 0; i < slices - 1; i++) {
      indices[index++] = i;
      indices[index++] = i + 1;
      indices[index++] = i + slices;
      indices[index++] = i + 1 + slices;
    }

    indices[index++] = slices - 1;
    indices[index++] = 0;
    indices[index++] = slices + slices - 1;
    indices[index++] = slices;

    if (numberOfVerticalLines > 0) {
      for (i = 0; i < slices; i += numSide) {
        indices[index++] = i;
        indices[index++] = i + slices;
      }
    }

    const attributes = new GeometryAttributes();
    attributes.position = new GeometryAttribute({
      componentDatatype: ComponentDatatype$1.DOUBLE,
      componentsPerAttribute: 3,
      values: positions,
    });

    radiusScratch.x = length * 0.5;
    radiusScratch.y = Math.max(bottomRadius, topRadius);

    const boundingSphere = new BoundingSphere(
      Cartesian3.ZERO,
      Cartesian2.magnitude(radiusScratch)
    );

    if (defined(cylinderGeometry._offsetAttribute)) {
      length = positions.length;
      const offsetValue =
        cylinderGeometry._offsetAttribute === GeometryOffsetAttribute$1.NONE
          ? 0
          : 1;
      const applyOffset = new Uint8Array(length / 3).fill(offsetValue);
      attributes.applyOffset = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
        componentsPerAttribute: 1,
        values: applyOffset,
      });
    }

    return new Geometry({
      attributes: attributes,
      indices: indices,
      primitiveType: PrimitiveType$1.LINES,
      boundingSphere: boundingSphere,
      offsetAttribute: cylinderGeometry._offsetAttribute,
    });
  };

  /**
   * A simple proxy that appends the desired resource as the sole query parameter
   * to the given proxy URL.
   *
   * @alias DefaultProxy
   * @constructor
   * @extends {Proxy}
   *
   * @param {String} proxy The proxy URL that will be used to requests all resources.
   */
  function DefaultProxy(proxy) {
    this.proxy = proxy;
  }

  /**
   * Get the final URL to use to request a given resource.
   *
   * @param {String} resource The resource to request.
   * @returns {String} proxied resource
   */
  DefaultProxy.prototype.getURL = function (resource) {
    const prefix = this.proxy.indexOf("?") === -1 ? "?" : "";
    return this.proxy + prefix + encodeURIComponent(resource);
  };

  /**
   * Determines visibility based on the distance to the camera.
   *
   * @alias DistanceDisplayCondition
   * @constructor
   *
   * @param {Number} [near=0.0] The smallest distance in the interval where the object is visible.
   * @param {Number} [far=Number.MAX_VALUE] The largest distance in the interval where the object is visible.
   *
   * @example
   * // Make a billboard that is only visible when the distance to the camera is between 10 and 20 meters.
   * billboard.distanceDisplayCondition = new Cesium.DistanceDisplayCondition(10.0, 20.0);
   */
  function DistanceDisplayCondition(near, far) {
    near = defaultValue(near, 0.0);
    this._near = near;

    far = defaultValue(far, Number.MAX_VALUE);
    this._far = far;
  }

  Object.defineProperties(DistanceDisplayCondition.prototype, {
    /**
     * The smallest distance in the interval where the object is visible.
     * @memberof DistanceDisplayCondition.prototype
     * @type {Number}
     * @default 0.0
     */
    near: {
      get: function () {
        return this._near;
      },
      set: function (value) {
        this._near = value;
      },
    },
    /**
     * The largest distance in the interval where the object is visible.
     * @memberof DistanceDisplayCondition.prototype
     * @type {Number}
     * @default Number.MAX_VALUE
     */
    far: {
      get: function () {
        return this._far;
      },
      set: function (value) {
        this._far = value;
      },
    },
  });

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  DistanceDisplayCondition.packedLength = 2;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {DistanceDisplayCondition} 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
   */
  DistanceDisplayCondition.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(value)) {
      throw new DeveloperError("value is required");
    }
    if (!defined(array)) {
      throw new DeveloperError("array is required");
    }
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    array[startingIndex++] = value.near;
    array[startingIndex] = value.far;

    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 {DistanceDisplayCondition} [result] The object into which to store the result.
   * @returns {DistanceDisplayCondition} The modified result parameter or a new DistanceDisplayCondition instance if one was not provided.
   */
  DistanceDisplayCondition.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(array)) {
      throw new DeveloperError("array is required");
    }
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    if (!defined(result)) {
      result = new DistanceDisplayCondition();
    }
    result.near = array[startingIndex++];
    result.far = array[startingIndex];
    return result;
  };

  /**
   * Determines if two distance display conditions are equal.
   *
   * @param {DistanceDisplayCondition} left A distance display condition.
   * @param {DistanceDisplayCondition} right Another distance display condition.
   * @return {Boolean} Whether the two distance display conditions are equal.
   */
  DistanceDisplayCondition.equals = function (left, right) {
    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        left.near === right.near &&
        left.far === right.far)
    );
  };

  /**
   * Duplicates a distance display condition instance.
   *
   * @param {DistanceDisplayCondition} [value] The distance display condition to duplicate.
   * @param {DistanceDisplayCondition} [result] The result onto which to store the result.
   * @return {DistanceDisplayCondition} The duplicated instance.
   */
  DistanceDisplayCondition.clone = function (value, result) {
    if (!defined(value)) {
      return undefined;
    }

    if (!defined(result)) {
      result = new DistanceDisplayCondition();
    }

    result.near = value.near;
    result.far = value.far;
    return result;
  };

  /**
   * Duplicates this instance.
   *
   * @param {DistanceDisplayCondition} [result] The result onto which to store the result.
   * @return {DistanceDisplayCondition} The duplicated instance.
   */
  DistanceDisplayCondition.prototype.clone = function (result) {
    return DistanceDisplayCondition.clone(this, result);
  };

  /**
   * Determines if this distance display condition is equal to another.
   *
   * @param {DistanceDisplayCondition} other Another distance display condition.
   * @return {Boolean} Whether this distance display condition is equal to the other.
   */
  DistanceDisplayCondition.prototype.equals = function (other) {
    return DistanceDisplayCondition.equals(this, other);
  };

  /**
   * Value and type information for per-instance geometry attribute that determines if the geometry instance has a distance display condition.
   *
   * @alias DistanceDisplayConditionGeometryInstanceAttribute
   * @constructor
   *
   * @param {Number} [near=0.0] The near distance.
   * @param {Number} [far=Number.MAX_VALUE] The far distance.
   *
   * @exception {DeveloperError} far must be greater than near.
   *
   * @example
   * const instance = new Cesium.GeometryInstance({
   *   geometry : new Cesium.BoxGeometry({
   *     vertexFormat : Cesium.VertexFormat.POSITION_AND_NORMAL,
   *     minimum : new Cesium.Cartesian3(-250000.0, -250000.0, -250000.0),
   *     maximum : new Cesium.Cartesian3(250000.0, 250000.0, 250000.0)
   *   }),
   *   modelMatrix : Cesium.Matrix4.multiplyByTranslation(Cesium.Transforms.eastNorthUpToFixedFrame(
   *     Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883)), new Cesium.Cartesian3(0.0, 0.0, 1000000.0), new Cesium.Matrix4()),
   *   id : 'box',
   *   attributes : {
   *     distanceDisplayCondition : new Cesium.DistanceDisplayConditionGeometryInstanceAttribute(100.0, 10000.0)
   *   }
   * });
   *
   * @see GeometryInstance
   * @see GeometryInstanceAttribute
   */
  function DistanceDisplayConditionGeometryInstanceAttribute(near, far) {
    near = defaultValue(near, 0.0);
    far = defaultValue(far, Number.MAX_VALUE);

    //>>includeStart('debug', pragmas.debug);
    if (far <= near) {
      throw new DeveloperError(
        "far distance must be greater than near distance."
      );
    }
    //>>includeEnd('debug');

    /**
     * The values for the attributes stored in a typed array.
     *
     * @type Float32Array
     *
     * @default [0.0, 0.0, Number.MAX_VALUE]
     */
    this.value = new Float32Array([near, far]);
  }

  Object.defineProperties(
    DistanceDisplayConditionGeometryInstanceAttribute.prototype,
    {
      /**
       * The datatype of each component in the attribute, e.g., individual elements in
       * {@link DistanceDisplayConditionGeometryInstanceAttribute#value}.
       *
       * @memberof DistanceDisplayConditionGeometryInstanceAttribute.prototype
       *
       * @type {ComponentDatatype}
       * @readonly
       *
       * @default {@link ComponentDatatype.FLOAT}
       */
      componentDatatype: {
        get: function () {
          return ComponentDatatype$1.FLOAT;
        },
      },

      /**
       * The number of components in the attributes, i.e., {@link DistanceDisplayConditionGeometryInstanceAttribute#value}.
       *
       * @memberof DistanceDisplayConditionGeometryInstanceAttribute.prototype
       *
       * @type {Number}
       * @readonly
       *
       * @default 3
       */
      componentsPerAttribute: {
        get: function () {
          return 2;
        },
      },

      /**
       * When <code>true</code> and <code>componentDatatype</code> is an integer format,
       * indicate that the components should be mapped to the range [0, 1] (unsigned)
       * or [-1, 1] (signed) when they are accessed as floating-point for rendering.
       *
       * @memberof DistanceDisplayConditionGeometryInstanceAttribute.prototype
       *
       * @type {Boolean}
       * @readonly
       *
       * @default false
       */
      normalize: {
        get: function () {
          return false;
        },
      },
    }
  );

  /**
   * Creates a new {@link DistanceDisplayConditionGeometryInstanceAttribute} instance given the provided an enabled flag and {@link DistanceDisplayCondition}.
   *
   * @param {DistanceDisplayCondition} distanceDisplayCondition The distance display condition.
   * @returns {DistanceDisplayConditionGeometryInstanceAttribute} The new {@link DistanceDisplayConditionGeometryInstanceAttribute} instance.
   *
   * @exception {DeveloperError} distanceDisplayCondition.far must be greater than distanceDisplayCondition.near
   *
   * @example
   * const distanceDisplayCondition = new Cesium.DistanceDisplayCondition(100.0, 10000.0);
   * const instance = new Cesium.GeometryInstance({
   *   geometry : geometry,
   *   attributes : {
   *     distanceDisplayCondition : Cesium.DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(distanceDisplayCondition)
   *   }
   * });
   */
  DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition = function (
    distanceDisplayCondition
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(distanceDisplayCondition)) {
      throw new DeveloperError("distanceDisplayCondition is required.");
    }
    if (distanceDisplayCondition.far <= distanceDisplayCondition.near) {
      throw new DeveloperError(
        "distanceDisplayCondition.far distance must be greater than distanceDisplayCondition.near distance."
      );
    }
    //>>includeEnd('debug');

    return new DistanceDisplayConditionGeometryInstanceAttribute(
      distanceDisplayCondition.near,
      distanceDisplayCondition.far
    );
  };

  /**
   * Converts a distance display condition to a typed array that can be used to assign a distance display condition attribute.
   *
   * @param {DistanceDisplayCondition} distanceDisplayCondition The distance display condition value.
   * @param {Float32Array} [result] The array to store the result in, if undefined a new instance will be created.
   * @returns {Float32Array} The modified result parameter or a new instance if result was undefined.
   *
   * @example
   * const attributes = primitive.getGeometryInstanceAttributes('an id');
   * attributes.distanceDisplayCondition = Cesium.DistanceDisplayConditionGeometryInstanceAttribute.toValue(distanceDisplayCondition, attributes.distanceDisplayCondition);
   */
  DistanceDisplayConditionGeometryInstanceAttribute.toValue = function (
    distanceDisplayCondition,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(distanceDisplayCondition)) {
      throw new DeveloperError("distanceDisplayCondition is required.");
    }
    //>>includeEnd('debug');

    if (!defined(result)) {
      return new Float32Array([
        distanceDisplayCondition.near,
        distanceDisplayCondition.far,
      ]);
    }
    result[0] = distanceDisplayCondition.near;
    result[1] = distanceDisplayCondition.far;
    return result;
  };

  /**
   * Array-backed min-max heap implementation of a double-ended priority queue.
   * This data structure allows for efficient removal of minimum and maximum elements.
   *
   * @alias DoubleEndedPriorityQueue
   * @constructor
   * @private
   *
   * @param {Object} options Object with the following properties:
   * @param {DoubleEndedPriorityQueue.ComparatorCallback} options.comparator The comparator to use for the queue. If comparator(a, b) is less than 0, a is lower priority than b.
   * @param {Number} [options.maximumLength] The maximum length of the queue. If an element is inserted when the queue is at full capacity, the minimum element is removed. By default, the size of the queue is unlimited.
   */
  function DoubleEndedPriorityQueue(options) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options", options);
    Check.defined("options.comparator", options.comparator);
    if (defined(options.maximumLength)) {
      Check.typeOf.number.greaterThanOrEquals(
        "options.maximumLength",
        options.maximumLength,
        0
      );
    }
    //>>includeEnd('debug');

    this._comparator = options.comparator;
    this._maximumLength = options.maximumLength;
    this._array = defined(options.maximumLength)
      ? new Array(options.maximumLength)
      : [];
    this._length = 0;
  }

  Object.defineProperties(DoubleEndedPriorityQueue.prototype, {
    /**
     * Gets the number of elements in the queue.
     *
     * @memberof DoubleEndedPriorityQueue.prototype
     *
     * @type {Number}
     * @readonly
     */
    length: {
      get: function () {
        return this._length;
      },
    },

    /**
     * Gets or sets the maximum number of elements in the queue.
     * If set to a smaller value than the current length of the queue, the lowest priority elements are removed.
     * If an element is inserted when the queue is at full capacity, the minimum element is removed.
     * If set to undefined, the size of the queue is unlimited.
     *
     * @memberof DoubleEndedPriorityQueue.prototype
     *
     * @type {Number}
     * @readonly
     */
    maximumLength: {
      get: function () {
        return this._maximumLength;
      },
      set: function (value) {
        if (defined(value)) {
          //>>includeStart('debug', pragmas.debug);
          Check.typeOf.number.greaterThanOrEquals("maximumLength", value, 0);
          //>>includeEnd('debug');

          // Remove elements until the maximum length is met.
          while (this._length > value) {
            this.removeMinimum();
          }

          // The array size is fixed to the maximum length
          this._array.length = value;
        }
        this._maximumLength = value;
      },
    },

    /**
     * Gets the internal array.
     *
     * @memberof DoubleEndedPriorityQueue.prototype
     *
     * @type {Array}
     * @readonly
     */
    internalArray: {
      get: function () {
        return this._array;
      },
    },

    /**
     * The comparator used by the queue.
     * If comparator(a, b) is less than 0, a is lower priority than b.
     *
     * @memberof DoubleEndedPriorityQueue.prototype
     *
     * @type {DoubleEndedPriorityQueue.ComparatorCallback}
     * @readonly
     */
    comparator: {
      get: function () {
        return this._comparator;
      },
    },
  });

  /**
   * Clones the double ended priority queue.
   *
   * @returns {DoubleEndedPriorityQueue} The cloned double ended priority queue.
   */
  DoubleEndedPriorityQueue.prototype.clone = function () {
    const maximumLength = this._maximumLength;
    const comparator = this._comparator;
    const array = this._array;
    const length = this._length;

    const result = new DoubleEndedPriorityQueue({
      comparator: comparator,
      maximumLength: maximumLength,
    });

    result._length = length;
    for (let i = 0; i < length; i++) {
      result._array[i] = array[i];
    }

    return result;
  };

  /**
   * Removes all elements from the queue.
   */
  DoubleEndedPriorityQueue.prototype.reset = function () {
    this._length = 0;

    // Dereference elements
    const maximumLength = this._maximumLength;
    if (defined(maximumLength)) {
      // Dereference all elements but keep the array the same size
      for (let i = 0; i < maximumLength; i++) {
        this._array[i] = undefined;
      }
    } else {
      // Dereference all elements by clearing the array
      this._array.length = 0;
    }
  };

  /**
   * Resort the queue.
   */
  DoubleEndedPriorityQueue.prototype.resort = function () {
    const length = this._length;

    // Fix the queue from the top-down
    for (let i = 0; i < length; i++) {
      pushUp(this, i);
    }
  };

  /**
   * Inserts an element into the queue.
   * If the queue is at full capacity, the minimum element is removed.
   * The new element is returned (and not added) if it is less than or equal priority to the minimum element.
   *
   * @param {*} element
   * @returns {*|undefined} The minimum element if the queue is at full capacity. Returns undefined if there is no maximum length.
   */
  DoubleEndedPriorityQueue.prototype.insert = function (element) {
    let removedElement;

    const maximumLength = this._maximumLength;
    if (defined(maximumLength)) {
      if (maximumLength === 0) {
        return undefined;
      } else if (this._length === maximumLength) {
        // It's faster to access the minimum directly instead of calling the getter
        // because it avoids the length === 0 check.
        const minimumElement = this._array[0];
        if (this._comparator(element, minimumElement) <= 0.0) {
          // The element that is being inserted is less than or equal to
          // the minimum element, so don't insert anything and exit early.
          return element;
        }
        removedElement = this.removeMinimum();
      }
    }

    const index = this._length;
    this._array[index] = element;
    this._length++;
    pushUp(this, index);

    return removedElement;
  };

  /**
   * Removes the minimum element from the queue and returns it.
   * If the queue is empty, the return value is undefined.
   *
   * @returns {*|undefined} The minimum element, or undefined if the queue is empty.
   */
  DoubleEndedPriorityQueue.prototype.removeMinimum = function () {
    const length = this._length;
    if (length === 0) {
      return undefined;
    }

    this._length--;

    // The minimum element is always the root
    const minimumElement = this._array[0];

    if (length >= 2) {
      this._array[0] = this._array[length - 1];
      pushDown(this, 0);
    }

    // Dereference removed element
    this._array[length - 1] = undefined;

    return minimumElement;
  };

  /**
   * Removes the maximum element from the queue and returns it.
   * If the queue is empty, the return value is undefined.
   *
   * @returns {*|undefined} The maximum element, or undefined if the queue is empty.
   */
  DoubleEndedPriorityQueue.prototype.removeMaximum = function () {
    const length = this._length;
    if (length === 0) {
      return undefined;
    }

    this._length--;
    let maximumElement;

    // If the root has no children, the maximum is the root.
    // If the root has one child, the maximum is the child.
    if (length <= 2) {
      maximumElement = this._array[length - 1];
    } else {
      // Otherwise, the maximum is the larger of the root's two children.
      const maximumElementIndex = greaterThan(this, 1, 2) ? 1 : 2;
      maximumElement = this._array[maximumElementIndex];

      // Re-balance the heap
      this._array[maximumElementIndex] = this._array[length - 1];
      if (length >= 4) {
        pushDown(this, maximumElementIndex);
      }
    }

    // Dereference removed element
    this._array[length - 1] = undefined;

    return maximumElement;
  };

  /**
   * Gets the minimum element in the queue.
   * If the queue is empty, the result is undefined.
   *
   * @returns {*|undefined} element
   */

  DoubleEndedPriorityQueue.prototype.getMinimum = function () {
    const length = this._length;
    if (length === 0) {
      return undefined;
    }

    // The minimum element is always the root
    return this._array[0];
  };

  /**
   * Gets the maximum element in the queue.
   * If the queue is empty, the result is undefined.
   *
   * @returns {*|undefined} element
   */
  DoubleEndedPriorityQueue.prototype.getMaximum = function () {
    const length = this._length;
    if (length === 0) {
      return undefined;
    }

    // If the root has no children, the maximum is the root.
    // If the root has one child, the maximum is the child.
    if (length <= 2) {
      return this._array[length - 1];
    }

    // Otherwise, the maximum is the larger of the root's two children.
    return this._array[greaterThan(this, 1, 2) ? 1 : 2];
  };

  // Helper functions

  function swap$2(that, indexA, indexB) {
    const array = that._array;
    const temp = array[indexA];
    array[indexA] = array[indexB];
    array[indexB] = temp;
  }

  function lessThan(that, indexA, indexB) {
    return that._comparator(that._array[indexA], that._array[indexB]) < 0.0;
  }

  function greaterThan(that, indexA, indexB) {
    return that._comparator(that._array[indexA], that._array[indexB]) > 0.0;
  }

  function pushUp(that, index) {
    if (index === 0) {
      return;
    }
    const onMinLevel = Math.floor(CesiumMath.log2(index + 1)) % 2 === 0;
    const parentIndex = Math.floor((index - 1) / 2);
    const lessThanParent = lessThan(that, index, parentIndex);

    // Get the element onto the correct level if it's not already
    if (lessThanParent !== onMinLevel) {
      swap$2(that, index, parentIndex);
      index = parentIndex;
    }

    // Swap element with grandparent as long as it:
    // 1) has a grandparent
    // 2A) is less than the grandparent when on a min level
    // 2B) is greater than the grandparent when on a max level
    while (index >= 3) {
      const grandparentIndex = Math.floor((index - 3) / 4);
      if (lessThan(that, index, grandparentIndex) !== lessThanParent) {
        break;
      }
      swap$2(that, index, grandparentIndex);
      index = grandparentIndex;
    }
  }

  function pushDown(that, index) {
    const length = that._length;
    const onMinLevel = Math.floor(CesiumMath.log2(index + 1)) % 2 === 0;

    // Loop as long as there is a left child.
    let leftChildIndex;
    while ((leftChildIndex = 2 * index + 1) < length) {
      // Find the minimum (or maximum) child or grandchild
      let target = leftChildIndex;
      const rightChildIndex = leftChildIndex + 1;
      if (rightChildIndex < length) {
        if (lessThan(that, rightChildIndex, target) === onMinLevel) {
          target = rightChildIndex;
        }
        const grandChildStart = 2 * leftChildIndex + 1;
        const grandChildCount = Math.max(
          Math.min(length - grandChildStart, 4),
          0
        );
        for (let i = 0; i < grandChildCount; i++) {
          const grandChildIndex = grandChildStart + i;
          if (lessThan(that, grandChildIndex, target) === onMinLevel) {
            target = grandChildIndex;
          }
        }
      }

      // Swap the element into the correct spot
      if (lessThan(that, target, index) === onMinLevel) {
        swap$2(that, target, index);
        if (target !== leftChildIndex && target !== rightChildIndex) {
          const parentOfGrandchildIndex = Math.floor((target - 1) / 2);
          if (greaterThan(that, target, parentOfGrandchildIndex) === onMinLevel) {
            swap$2(that, target, parentOfGrandchildIndex);
          }
        }
      }

      index = target;
    }
  }

  /**
   * @private
   */
  function DoublyLinkedList() {
    this.head = undefined;
    this.tail = undefined;
    this._length = 0;
  }

  Object.defineProperties(DoublyLinkedList.prototype, {
    length: {
      get: function () {
        return this._length;
      },
    },
  });

  /**
   * @private
   */
  function DoublyLinkedListNode(item, previous, next) {
    this.item = item;
    this.previous = previous;
    this.next = next;
  }

  /**
   * Adds the item to the end of the list
   * @param {*} [item]
   * @return {DoublyLinkedListNode}
   */
  DoublyLinkedList.prototype.add = function (item) {
    const node = new DoublyLinkedListNode(item, this.tail, undefined);

    if (defined(this.tail)) {
      this.tail.next = node;
      this.tail = node;
    } else {
      this.head = node;
      this.tail = node;
    }

    ++this._length;

    return node;
  };

  function remove$2(list, node) {
    if (defined(node.previous) && defined(node.next)) {
      node.previous.next = node.next;
      node.next.previous = node.previous;
    } else if (defined(node.previous)) {
      // Remove last node
      node.previous.next = undefined;
      list.tail = node.previous;
    } else if (defined(node.next)) {
      // Remove first node
      node.next.previous = undefined;
      list.head = node.next;
    } else {
      // Remove last node in the linked list
      list.head = undefined;
      list.tail = undefined;
    }

    node.next = undefined;
    node.previous = undefined;
  }

  /**
   * Removes the given node from the list
   * @param {DoublyLinkedListNode} node
   */
  DoublyLinkedList.prototype.remove = function (node) {
    if (!defined(node)) {
      return;
    }

    remove$2(this, node);

    --this._length;
  };

  /**
   * Moves nextNode after node
   * @param {DoublyLinkedListNode} node
   * @param {DoublyLinkedListNode} nextNode
   */
  DoublyLinkedList.prototype.splice = function (node, nextNode) {
    if (node === nextNode) {
      return;
    }

    // Remove nextNode, then insert after node
    remove$2(this, nextNode);

    const oldNodeNext = node.next;
    node.next = nextNode;

    // nextNode is the new tail
    if (this.tail === node) {
      this.tail = nextNode;
    } else {
      oldNodeNext.previous = nextNode;
    }

    nextNode.next = oldNodeNext;
    nextNode.previous = node;
  };

  /* This file is automatically rebuilt by the Cesium build process. */

  var Tween$1 = createCommonjsModule(function (module, exports) {
  /**
   * Tween.js - Licensed under the MIT license
   * https://github.com/tweenjs/tween.js
   * ----------------------------------------------
   *
   * See https://github.com/tweenjs/tween.js/graphs/contributors for the full list of contributors.
   * Thank you all, you're awesome!
   */

  var TWEEN = TWEEN || (function () {

  	var _tweens = [];

  	return {

  		getAll: function () {

  			return _tweens;

  		},

  		removeAll: function () {

  			_tweens = [];

  		},

  		add: function (tween) {

  			_tweens.push(tween);

  		},

  		remove: function (tween) {

  			var i = _tweens.indexOf(tween);

  			if (i !== -1) {
  				_tweens.splice(i, 1);
  			}

  		},

  		update: function (time, preserve) {

  			if (_tweens.length === 0) {
  				return false;
  			}

  			var i = 0;

  			time = time !== undefined ? time : TWEEN.now();

  			while (i < _tweens.length) {

  				if (_tweens[i].update(time) || preserve) {
  					i++;
  				} else {
  					_tweens.splice(i, 1);
  				}

  			}

  			return true;

  		}
  	};

  })();


  // Include a performance.now polyfill.
  // In node.js, use process.hrtime.
  if (typeof (window) === 'undefined' && typeof (process) !== 'undefined') {
  	TWEEN.now = function () {
  		var time = process.hrtime();

  		// Convert [seconds, nanoseconds] to milliseconds.
  		return time[0] * 1000 + time[1] / 1000000;
  	};
  }
  // In a browser, use window.performance.now if it is available.
  else if (typeof (window) !== 'undefined' &&
           window.performance !== undefined &&
  		 window.performance.now !== undefined) {
  	// This must be bound, because directly assigning this function
  	// leads to an invocation exception in Chrome.
  	TWEEN.now = window.performance.now.bind(window.performance);
  }
  // Use Date.now if it is available.
  else if (Date.now !== undefined) {
  	TWEEN.now = Date.now;
  }
  // Otherwise, use 'new Date().getTime()'.
  else {
  	TWEEN.now = function () {
  		return new Date().getTime();
  	};
  }


  TWEEN.Tween = function (object) {

  	var _object = object;
  	var _valuesStart = {};
  	var _valuesEnd = {};
  	var _valuesStartRepeat = {};
  	var _duration = 1000;
  	var _repeat = 0;
  	var _repeatDelayTime;
  	var _yoyo = false;
  	var _isPlaying = false;
  	var _delayTime = 0;
  	var _startTime = null;
  	var _easingFunction = TWEEN.Easing.Linear.None;
  	var _interpolationFunction = TWEEN.Interpolation.Linear;
  	var _chainedTweens = [];
  	var _onStartCallback = null;
  	var _onStartCallbackFired = false;
  	var _onUpdateCallback = null;
  	var _onCompleteCallback = null;
  	var _onStopCallback = null;

  	this.to = function (properties, duration) {

  		_valuesEnd = properties;

  		if (duration !== undefined) {
  			_duration = duration;
  		}

  		return this;

  	};

  	this.start = function (time) {

  		TWEEN.add(this);

  		_isPlaying = true;

  		_onStartCallbackFired = false;

  		_startTime = time !== undefined ? time : TWEEN.now();
  		_startTime += _delayTime;

  		for (var property in _valuesEnd) {

  			// Check if an Array was provided as property value
  			if (_valuesEnd[property] instanceof Array) {

  				if (_valuesEnd[property].length === 0) {
  					continue;
  				}

  				// Create a local copy of the Array with the start value at the front
  				_valuesEnd[property] = [_object[property]].concat(_valuesEnd[property]);

  			}

  			// If `to()` specifies a property that doesn't exist in the source object,
  			// we should not set that property in the object
  			if (_object[property] === undefined) {
  				continue;
  			}

  			// Save the starting value.
  			_valuesStart[property] = _object[property];

  			if ((_valuesStart[property] instanceof Array) === false) {
  				_valuesStart[property] *= 1.0; // Ensures we're using numbers, not strings
  			}

  			_valuesStartRepeat[property] = _valuesStart[property] || 0;

  		}

  		return this;

  	};

  	this.stop = function () {

  		if (!_isPlaying) {
  			return this;
  		}

  		TWEEN.remove(this);
  		_isPlaying = false;

  		if (_onStopCallback !== null) {
  			_onStopCallback.call(_object, _object);
  		}

  		this.stopChainedTweens();
  		return this;

  	};

  	this.end = function () {

  		this.update(_startTime + _duration);
  		return this;

  	};

  	this.stopChainedTweens = function () {

  		for (var i = 0, numChainedTweens = _chainedTweens.length; i < numChainedTweens; i++) {
  			_chainedTweens[i].stop();
  		}

  	};

  	this.delay = function (amount) {

  		_delayTime = amount;
  		return this;

  	};

  	this.repeat = function (times) {

  		_repeat = times;
  		return this;

  	};

  	this.repeatDelay = function (amount) {

  		_repeatDelayTime = amount;
  		return this;

  	};

  	this.yoyo = function (yoyo) {

  		_yoyo = yoyo;
  		return this;

  	};


  	this.easing = function (easing) {

  		_easingFunction = easing;
  		return this;

  	};

  	this.interpolation = function (interpolation) {

  		_interpolationFunction = interpolation;
  		return this;

  	};

  	this.chain = function () {

  		_chainedTweens = arguments;
  		return this;

  	};

  	this.onStart = function (callback) {

  		_onStartCallback = callback;
  		return this;

  	};

  	this.onUpdate = function (callback) {

  		_onUpdateCallback = callback;
  		return this;

  	};

  	this.onComplete = function (callback) {

  		_onCompleteCallback = callback;
  		return this;

  	};

  	this.onStop = function (callback) {

  		_onStopCallback = callback;
  		return this;

  	};

  	this.update = function (time) {

  		var property;
  		var elapsed;
  		var value;

  		if (time < _startTime) {
  			return true;
  		}

  		if (_onStartCallbackFired === false) {

  			if (_onStartCallback !== null) {
  				_onStartCallback.call(_object, _object);
  			}

  			_onStartCallbackFired = true;
  		}

  		elapsed = (time - _startTime) / _duration;
  		elapsed = elapsed > 1 ? 1 : elapsed;

  		value = _easingFunction(elapsed);

  		for (property in _valuesEnd) {

  			// Don't update properties that do not exist in the source object
  			if (_valuesStart[property] === undefined) {
  				continue;
  			}

  			var start = _valuesStart[property] || 0;
  			var end = _valuesEnd[property];

  			if (end instanceof Array) {

  				_object[property] = _interpolationFunction(end, value);

  			} else {

  				// Parses relative end values with start as base (e.g.: +10, -3)
  				if (typeof (end) === 'string') {

  					if (end.charAt(0) === '+' || end.charAt(0) === '-') {
  						end = start + parseFloat(end);
  					} else {
  						end = parseFloat(end);
  					}
  				}

  				// Protect against non numeric properties.
  				if (typeof (end) === 'number') {
  					_object[property] = start + (end - start) * value;
  				}

  			}

  		}

  		if (_onUpdateCallback !== null) {
  			_onUpdateCallback.call(_object, value);
  		}

  		if (elapsed === 1) {

  			if (_repeat > 0) {

  				if (isFinite(_repeat)) {
  					_repeat--;
  				}

  				// Reassign starting values, restart by making startTime = now
  				for (property in _valuesStartRepeat) {

  					if (typeof (_valuesEnd[property]) === 'string') {
  						_valuesStartRepeat[property] = _valuesStartRepeat[property] + parseFloat(_valuesEnd[property]);
  					}

  					if (_yoyo) {
  						var tmp = _valuesStartRepeat[property];

  						_valuesStartRepeat[property] = _valuesEnd[property];
  						_valuesEnd[property] = tmp;
  					}

  					_valuesStart[property] = _valuesStartRepeat[property];

  				}

  				if (_repeatDelayTime !== undefined) {
  					_startTime = time + _repeatDelayTime;
  				} else {
  					_startTime = time + _delayTime;
  				}

  				return true;

  			} else {

  				if (_onCompleteCallback !== null) {

  					_onCompleteCallback.call(_object, _object);
  				}

  				for (var i = 0, numChainedTweens = _chainedTweens.length; i < numChainedTweens; i++) {
  					// Make the chained tweens start exactly at the time they should,
  					// even if the `update()` method was called way past the duration of the tween
  					_chainedTweens[i].start(_startTime + _duration);
  				}

  				return false;

  			}

  		}

  		return true;

  	};

  };


  TWEEN.Easing = {

  	Linear: {

  		None: function (k) {

  			return k;

  		}

  	},

  	Quadratic: {

  		In: function (k) {

  			return k * k;

  		},

  		Out: function (k) {

  			return k * (2 - k);

  		},

  		InOut: function (k) {

  			if ((k *= 2) < 1) {
  				return 0.5 * k * k;
  			}

  			return - 0.5 * (--k * (k - 2) - 1);

  		}

  	},

  	Cubic: {

  		In: function (k) {

  			return k * k * k;

  		},

  		Out: function (k) {

  			return --k * k * k + 1;

  		},

  		InOut: function (k) {

  			if ((k *= 2) < 1) {
  				return 0.5 * k * k * k;
  			}

  			return 0.5 * ((k -= 2) * k * k + 2);

  		}

  	},

  	Quartic: {

  		In: function (k) {

  			return k * k * k * k;

  		},

  		Out: function (k) {

  			return 1 - (--k * k * k * k);

  		},

  		InOut: function (k) {

  			if ((k *= 2) < 1) {
  				return 0.5 * k * k * k * k;
  			}

  			return - 0.5 * ((k -= 2) * k * k * k - 2);

  		}

  	},

  	Quintic: {

  		In: function (k) {

  			return k * k * k * k * k;

  		},

  		Out: function (k) {

  			return --k * k * k * k * k + 1;

  		},

  		InOut: function (k) {

  			if ((k *= 2) < 1) {
  				return 0.5 * k * k * k * k * k;
  			}

  			return 0.5 * ((k -= 2) * k * k * k * k + 2);

  		}

  	},

  	Sinusoidal: {

  		In: function (k) {

  			return 1 - Math.cos(k * Math.PI / 2);

  		},

  		Out: function (k) {

  			return Math.sin(k * Math.PI / 2);

  		},

  		InOut: function (k) {

  			return 0.5 * (1 - Math.cos(Math.PI * k));

  		}

  	},

  	Exponential: {

  		In: function (k) {

  			return k === 0 ? 0 : Math.pow(1024, k - 1);

  		},

  		Out: function (k) {

  			return k === 1 ? 1 : 1 - Math.pow(2, - 10 * k);

  		},

  		InOut: function (k) {

  			if (k === 0) {
  				return 0;
  			}

  			if (k === 1) {
  				return 1;
  			}

  			if ((k *= 2) < 1) {
  				return 0.5 * Math.pow(1024, k - 1);
  			}

  			return 0.5 * (- Math.pow(2, - 10 * (k - 1)) + 2);

  		}

  	},

  	Circular: {

  		In: function (k) {

  			return 1 - Math.sqrt(1 - k * k);

  		},

  		Out: function (k) {

  			return Math.sqrt(1 - (--k * k));

  		},

  		InOut: function (k) {

  			if ((k *= 2) < 1) {
  				return - 0.5 * (Math.sqrt(1 - k * k) - 1);
  			}

  			return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);

  		}

  	},

  	Elastic: {

  		In: function (k) {

  			if (k === 0) {
  				return 0;
  			}

  			if (k === 1) {
  				return 1;
  			}

  			return -Math.pow(2, 10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI);

  		},

  		Out: function (k) {

  			if (k === 0) {
  				return 0;
  			}

  			if (k === 1) {
  				return 1;
  			}

  			return Math.pow(2, -10 * k) * Math.sin((k - 0.1) * 5 * Math.PI) + 1;

  		},

  		InOut: function (k) {

  			if (k === 0) {
  				return 0;
  			}

  			if (k === 1) {
  				return 1;
  			}

  			k *= 2;

  			if (k < 1) {
  				return -0.5 * Math.pow(2, 10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI);
  			}

  			return 0.5 * Math.pow(2, -10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI) + 1;

  		}

  	},

  	Back: {

  		In: function (k) {

  			var s = 1.70158;

  			return k * k * ((s + 1) * k - s);

  		},

  		Out: function (k) {

  			var s = 1.70158;

  			return --k * k * ((s + 1) * k + s) + 1;

  		},

  		InOut: function (k) {

  			var s = 1.70158 * 1.525;

  			if ((k *= 2) < 1) {
  				return 0.5 * (k * k * ((s + 1) * k - s));
  			}

  			return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);

  		}

  	},

  	Bounce: {

  		In: function (k) {

  			return 1 - TWEEN.Easing.Bounce.Out(1 - k);

  		},

  		Out: function (k) {

  			if (k < (1 / 2.75)) {
  				return 7.5625 * k * k;
  			} else if (k < (2 / 2.75)) {
  				return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  			} else if (k < (2.5 / 2.75)) {
  				return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  			} else {
  				return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  			}

  		},

  		InOut: function (k) {

  			if (k < 0.5) {
  				return TWEEN.Easing.Bounce.In(k * 2) * 0.5;
  			}

  			return TWEEN.Easing.Bounce.Out(k * 2 - 1) * 0.5 + 0.5;

  		}

  	}

  };

  TWEEN.Interpolation = {

  	Linear: function (v, k) {

  		var m = v.length - 1;
  		var f = m * k;
  		var i = Math.floor(f);
  		var fn = TWEEN.Interpolation.Utils.Linear;

  		if (k < 0) {
  			return fn(v[0], v[1], f);
  		}

  		if (k > 1) {
  			return fn(v[m], v[m - 1], m - f);
  		}

  		return fn(v[i], v[i + 1 > m ? m : i + 1], f - i);

  	},

  	Bezier: function (v, k) {

  		var b = 0;
  		var n = v.length - 1;
  		var pw = Math.pow;
  		var bn = TWEEN.Interpolation.Utils.Bernstein;

  		for (var i = 0; i <= n; i++) {
  			b += pw(1 - k, n - i) * pw(k, i) * v[i] * bn(n, i);
  		}

  		return b;

  	},

  	CatmullRom: function (v, k) {

  		var m = v.length - 1;
  		var f = m * k;
  		var i = Math.floor(f);
  		var fn = TWEEN.Interpolation.Utils.CatmullRom;

  		if (v[0] === v[m]) {

  			if (k < 0) {
  				i = Math.floor(f = m * (1 + k));
  			}

  			return fn(v[(i - 1 + m) % m], v[i], v[(i + 1) % m], v[(i + 2) % m], f - i);

  		} else {

  			if (k < 0) {
  				return v[0] - (fn(v[0], v[0], v[1], v[1], -f) - v[0]);
  			}

  			if (k > 1) {
  				return v[m] - (fn(v[m], v[m], v[m - 1], v[m - 1], f - m) - v[m]);
  			}

  			return fn(v[i ? i - 1 : 0], v[i], v[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2], f - i);

  		}

  	},

  	Utils: {

  		Linear: function (p0, p1, t) {

  			return (p1 - p0) * t + p0;

  		},

  		Bernstein: function (n, i) {

  			var fc = TWEEN.Interpolation.Utils.Factorial;

  			return fc(n) / fc(i) / fc(n - i);

  		},

  		Factorial: (function () {

  			var a = [1];

  			return function (n) {

  				var s = 1;

  				if (a[n]) {
  					return a[n];
  				}

  				for (var i = n; i > 1; i--) {
  					s *= i;
  				}

  				a[n] = s;
  				return s;

  			};

  		})(),

  		CatmullRom: function (p0, p1, p2, p3, t) {

  			var v0 = (p2 - p0) * 0.5;
  			var v1 = (p3 - p1) * 0.5;
  			var t2 = t * t;
  			var t3 = t * t2;

  			return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (- 3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;

  		}

  	}

  };

  // UMD (Universal Module Definition)
  (function (root) {

  	{

  		// Node.js
  		module.exports = TWEEN;

  	}

  })();
  });

  /**
   * Easing functions for use with TweenCollection.  These function are from
   * {@link https://github.com/sole/tween.js/|Tween.js} and Robert Penner.  See the
   * {@link http://sole.github.io/tween.js/examples/03_graphs.html|Tween.js graphs for each function}.
   *
   * @namespace
   */
  const EasingFunction = {
    /**
     * Linear easing.
     *
     * @type {EasingFunction.Callback}
     * @constant
     */
    LINEAR_NONE: Tween$1.Easing.Linear.None,

    /**
     * Quadratic in.
     *
     * @type {EasingFunction.Callback}
     * @constant
     */
    QUADRATIC_IN: Tween$1.Easing.Quadratic.In,
    /**
     * Quadratic out.
     *
     * @type {EasingFunction.Callback}
     * @constant
     */
    QUADRATIC_OUT: Tween$1.Easing.Quadratic.Out,
    /**
     * Quadratic in then out.
     *
     * @type {EasingFunction.Callback}
     * @constant
     */
    QUADRATIC_IN_OUT: Tween$1.Easing.Quadratic.InOut,

    /**
     * Cubic in.
     *
     * @type {EasingFunction.Callback}
     * @constant
     */
    CUBIC_IN: Tween$1.Easing.Cubic.In,
    /**
     * Cubic out.
     *
     * @type {EasingFunction.Callback}
     * @constant
     */
    CUBIC_OUT: Tween$1.Easing.Cubic.Out,
    /**
     * Cubic in then out.
     *
     * @type {EasingFunction.Callback}
     * @constant
     */
    CUBIC_IN_OUT: Tween$1.Easing.Cubic.InOut,

    /**
     * Quartic in.
     *
     * @type {EasingFunction.Callback}
     * @constant
     */
    QUARTIC_IN: Tween$1.Easing.Quartic.In,
    /**
     * Quartic out.
     *
     * @type {EasingFunction.Callback}
     * @constant
     */
    QUARTIC_OUT: Tween$1.Easing.Quartic.Out,
    /**
     * Quartic in then out.
     *
     * @type {EasingFunction.Callback}
     * @constant
     */
    QUARTIC_IN_OUT: Tween$1.Easing.Quartic.InOut,

    /**
     * Quintic in.
     *
     * @type {EasingFunction.Callback}
     * @constant
     */
    QUINTIC_IN: Tween$1.Easing.Quintic.In,
    /**
     * Quintic out.
     *
     * @type {EasingFunction.Callback}
     * @constant
     */
    QUINTIC_OUT: Tween$1.Easing.Quintic.Out,
    /**
     * Quintic in then out.
     *
     * @type {EasingFunction.Callback}
     * @constant
     */
    QUINTIC_IN_OUT: Tween$1.Easing.Quintic.InOut,

    /**
     * Sinusoidal in.
     *
     * @type {EasingFunction.Callback}
     * @constant
     */
    SINUSOIDAL_IN: Tween$1.Easing.Sinusoidal.In,
    /**
     * Sinusoidal out.
     *
     * @type {EasingFunction.Callback}
     * @constant
     */
    SINUSOIDAL_OUT: Tween$1.Easing.Sinusoidal.Out,
    /**
     * Sinusoidal in then out.
     *
     * @type {EasingFunction.Callback}
     * @constant
     */
    SINUSOIDAL_IN_OUT: Tween$1.Easing.Sinusoidal.InOut,

    /**
     * Exponential in.
     *
     * @type {EasingFunction.Callback}
     * @constant
     */
    EXPONENTIAL_IN: Tween$1.Easing.Exponential.In,
    /**
     * Exponential out.
     *
     * @type {EasingFunction.Callback}
     * @constant
     */
    EXPONENTIAL_OUT: Tween$1.Easing.Exponential.Out,
    /**
     * Exponential in then out.
     *
     * @type {EasingFunction.Callback}
     * @constant
     */
    EXPONENTIAL_IN_OUT: Tween$1.Easing.Exponential.InOut,

    /**
     * Circular in.
     *
     * @type {EasingFunction.Callback}
     * @constant
     */
    CIRCULAR_IN: Tween$1.Easing.Circular.In,
    /**
     * Circular out.
     *
     * @type {EasingFunction.Callback}
     * @constant
     */
    CIRCULAR_OUT: Tween$1.Easing.Circular.Out,
    /**
     * Circular in then out.
     *
     * @type {EasingFunction.Callback}
     * @constant
     */
    CIRCULAR_IN_OUT: Tween$1.Easing.Circular.InOut,

    /**
     * Elastic in.
     *
     * @type {EasingFunction.Callback}
     * @constant
     */
    ELASTIC_IN: Tween$1.Easing.Elastic.In,
    /**
     * Elastic out.
     *
     * @type {EasingFunction.Callback}
     * @constant
     */
    ELASTIC_OUT: Tween$1.Easing.Elastic.Out,
    /**
     * Elastic in then out.
     *
     * @type {EasingFunction.Callback}
     * @constant
     */
    ELASTIC_IN_OUT: Tween$1.Easing.Elastic.InOut,

    /**
     * Back in.
     *
     * @type {EasingFunction.Callback}
     * @constant
     */
    BACK_IN: Tween$1.Easing.Back.In,
    /**
     * Back out.
     *
     * @type {EasingFunction.Callback}
     * @constant
     */
    BACK_OUT: Tween$1.Easing.Back.Out,
    /**
     * Back in then out.
     *
     * @type {EasingFunction.Callback}
     * @constant
     */
    BACK_IN_OUT: Tween$1.Easing.Back.InOut,

    /**
     * Bounce in.
     *
     * @type {EasingFunction.Callback}
     * @constant
     */
    BOUNCE_IN: Tween$1.Easing.Bounce.In,
    /**
     * Bounce out.
     *
     * @type {EasingFunction.Callback}
     * @constant
     */
    BOUNCE_OUT: Tween$1.Easing.Bounce.Out,
    /**
     * Bounce in then out.
     *
     * @type {EasingFunction.Callback}
     * @constant
     */
    BOUNCE_IN_OUT: Tween$1.Easing.Bounce.InOut,
  };

  /**
   * Function interface for implementing a custom easing function.
   * @callback EasingFunction.Callback
   * @param {Number} time The time in the range <code>[0, 1]</code>.
   * @returns {Number} The value of the function at the given time.
   *
   * @example
   * function quadraticIn(time) {
   *     return time * time;
   * }
   *
   * @example
   * function quadraticOut(time) {
   *     return time * (2.0 - time);
   * }
   */

  var EasingFunction$1 = Object.freeze(EasingFunction);

  const scratchPosition$d = new Cartesian3();
  const scratchNormal$3 = new Cartesian3();
  const scratchTangent$2 = new Cartesian3();
  const scratchBitangent$2 = new Cartesian3();
  const scratchNormalST = new Cartesian3();
  const defaultRadii$1 = new Cartesian3(1.0, 1.0, 1.0);

  const cos$2 = Math.cos;
  const sin$2 = Math.sin;

  /**
   * A description of an ellipsoid centered at the origin.
   *
   * @alias EllipsoidGeometry
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Cartesian3} [options.radii=Cartesian3(1.0, 1.0, 1.0)] The radii of the ellipsoid in the x, y, and z directions.
   * @param {Cartesian3} [options.innerRadii=options.radii] The inner radii of the ellipsoid in the x, y, and z directions.
   * @param {Number} [options.minimumClock=0.0] The minimum angle lying in the xy-plane measured from the positive x-axis and toward the positive y-axis.
   * @param {Number} [options.maximumClock=2*PI] The maximum angle lying in the xy-plane measured from the positive x-axis and toward the positive y-axis.
   * @param {Number} [options.minimumCone=0.0] The minimum angle measured from the positive z-axis and toward the negative z-axis.
   * @param {Number} [options.maximumCone=PI] The maximum angle measured from the positive z-axis and toward the negative z-axis.
   * @param {Number} [options.stackPartitions=64] The number of times to partition the ellipsoid into stacks.
   * @param {Number} [options.slicePartitions=64] The number of times to partition the ellipsoid into radial slices.
   * @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
   *
   * @exception {DeveloperError} options.slicePartitions cannot be less than three.
   * @exception {DeveloperError} options.stackPartitions cannot be less than three.
   *
   * @see EllipsoidGeometry#createGeometry
   *
   * @example
   * const ellipsoid = new Cesium.EllipsoidGeometry({
   *   vertexFormat : Cesium.VertexFormat.POSITION_ONLY,
   *   radii : new Cesium.Cartesian3(1000000.0, 500000.0, 500000.0)
   * });
   * const geometry = Cesium.EllipsoidGeometry.createGeometry(ellipsoid);
   */
  function EllipsoidGeometry(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const radii = defaultValue(options.radii, defaultRadii$1);
    const innerRadii = defaultValue(options.innerRadii, radii);
    const minimumClock = defaultValue(options.minimumClock, 0.0);
    const maximumClock = defaultValue(options.maximumClock, CesiumMath.TWO_PI);
    const minimumCone = defaultValue(options.minimumCone, 0.0);
    const maximumCone = defaultValue(options.maximumCone, CesiumMath.PI);
    const stackPartitions = Math.round(defaultValue(options.stackPartitions, 64));
    const slicePartitions = Math.round(defaultValue(options.slicePartitions, 64));
    const vertexFormat = defaultValue(options.vertexFormat, VertexFormat.DEFAULT);

    //>>includeStart('debug', pragmas.debug);
    if (slicePartitions < 3) {
      throw new DeveloperError(
        "options.slicePartitions cannot be less than three."
      );
    }
    if (stackPartitions < 3) {
      throw new DeveloperError(
        "options.stackPartitions cannot be less than three."
      );
    }
    //>>includeEnd('debug');

    this._radii = Cartesian3.clone(radii);
    this._innerRadii = Cartesian3.clone(innerRadii);
    this._minimumClock = minimumClock;
    this._maximumClock = maximumClock;
    this._minimumCone = minimumCone;
    this._maximumCone = maximumCone;
    this._stackPartitions = stackPartitions;
    this._slicePartitions = slicePartitions;
    this._vertexFormat = VertexFormat.clone(vertexFormat);
    this._offsetAttribute = options.offsetAttribute;
    this._workerName = "createEllipsoidGeometry";
  }

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  EllipsoidGeometry.packedLength =
    2 * Cartesian3.packedLength + VertexFormat.packedLength + 7;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {EllipsoidGeometry} 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
   */
  EllipsoidGeometry.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(value)) {
      throw new DeveloperError("value is required");
    }
    if (!defined(array)) {
      throw new DeveloperError("array is required");
    }
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    Cartesian3.pack(value._radii, array, startingIndex);
    startingIndex += Cartesian3.packedLength;

    Cartesian3.pack(value._innerRadii, array, startingIndex);
    startingIndex += Cartesian3.packedLength;

    VertexFormat.pack(value._vertexFormat, array, startingIndex);
    startingIndex += VertexFormat.packedLength;

    array[startingIndex++] = value._minimumClock;
    array[startingIndex++] = value._maximumClock;
    array[startingIndex++] = value._minimumCone;
    array[startingIndex++] = value._maximumCone;
    array[startingIndex++] = value._stackPartitions;
    array[startingIndex++] = value._slicePartitions;
    array[startingIndex] = defaultValue(value._offsetAttribute, -1);

    return array;
  };

  const scratchRadii$2 = new Cartesian3();
  const scratchInnerRadii$1 = new Cartesian3();
  const scratchVertexFormat$7 = new VertexFormat();
  const scratchOptions$b = {
    radii: scratchRadii$2,
    innerRadii: scratchInnerRadii$1,
    vertexFormat: scratchVertexFormat$7,
    minimumClock: undefined,
    maximumClock: undefined,
    minimumCone: undefined,
    maximumCone: undefined,
    stackPartitions: undefined,
    slicePartitions: undefined,
    offsetAttribute: undefined,
  };

  /**
   * 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 {EllipsoidGeometry} [result] The object into which to store the result.
   * @returns {EllipsoidGeometry} The modified result parameter or a new EllipsoidGeometry instance if one was not provided.
   */
  EllipsoidGeometry.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(array)) {
      throw new DeveloperError("array is required");
    }
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    const radii = Cartesian3.unpack(array, startingIndex, scratchRadii$2);
    startingIndex += Cartesian3.packedLength;

    const innerRadii = Cartesian3.unpack(array, startingIndex, scratchInnerRadii$1);
    startingIndex += Cartesian3.packedLength;

    const vertexFormat = VertexFormat.unpack(
      array,
      startingIndex,
      scratchVertexFormat$7
    );
    startingIndex += VertexFormat.packedLength;

    const minimumClock = array[startingIndex++];
    const maximumClock = array[startingIndex++];
    const minimumCone = array[startingIndex++];
    const maximumCone = array[startingIndex++];
    const stackPartitions = array[startingIndex++];
    const slicePartitions = array[startingIndex++];
    const offsetAttribute = array[startingIndex];

    if (!defined(result)) {
      scratchOptions$b.minimumClock = minimumClock;
      scratchOptions$b.maximumClock = maximumClock;
      scratchOptions$b.minimumCone = minimumCone;
      scratchOptions$b.maximumCone = maximumCone;
      scratchOptions$b.stackPartitions = stackPartitions;
      scratchOptions$b.slicePartitions = slicePartitions;
      scratchOptions$b.offsetAttribute =
        offsetAttribute === -1 ? undefined : offsetAttribute;
      return new EllipsoidGeometry(scratchOptions$b);
    }

    result._radii = Cartesian3.clone(radii, result._radii);
    result._innerRadii = Cartesian3.clone(innerRadii, result._innerRadii);
    result._vertexFormat = VertexFormat.clone(vertexFormat, result._vertexFormat);
    result._minimumClock = minimumClock;
    result._maximumClock = maximumClock;
    result._minimumCone = minimumCone;
    result._maximumCone = maximumCone;
    result._stackPartitions = stackPartitions;
    result._slicePartitions = slicePartitions;
    result._offsetAttribute =
      offsetAttribute === -1 ? undefined : offsetAttribute;

    return result;
  };

  /**
   * Computes the geometric representation of an ellipsoid, including its vertices, indices, and a bounding sphere.
   *
   * @param {EllipsoidGeometry} ellipsoidGeometry A description of the ellipsoid.
   * @returns {Geometry|undefined} The computed vertices and indices.
   */
  EllipsoidGeometry.createGeometry = function (ellipsoidGeometry) {
    const radii = ellipsoidGeometry._radii;
    if (radii.x <= 0 || radii.y <= 0 || radii.z <= 0) {
      return;
    }

    const innerRadii = ellipsoidGeometry._innerRadii;
    if (innerRadii.x <= 0 || innerRadii.y <= 0 || innerRadii.z <= 0) {
      return;
    }

    const minimumClock = ellipsoidGeometry._minimumClock;
    const maximumClock = ellipsoidGeometry._maximumClock;
    const minimumCone = ellipsoidGeometry._minimumCone;
    const maximumCone = ellipsoidGeometry._maximumCone;
    const vertexFormat = ellipsoidGeometry._vertexFormat;

    // Add an extra slice and stack so that the number of partitions is the
    // number of surfaces rather than the number of joints
    let slicePartitions = ellipsoidGeometry._slicePartitions + 1;
    let stackPartitions = ellipsoidGeometry._stackPartitions + 1;

    slicePartitions = Math.round(
      (slicePartitions * Math.abs(maximumClock - minimumClock)) /
        CesiumMath.TWO_PI
    );
    stackPartitions = Math.round(
      (stackPartitions * Math.abs(maximumCone - minimumCone)) / CesiumMath.PI
    );

    if (slicePartitions < 2) {
      slicePartitions = 2;
    }
    if (stackPartitions < 2) {
      stackPartitions = 2;
    }

    let i;
    let j;
    let index = 0;

    // Create arrays for theta and phi. Duplicate first and last angle to
    // allow different normals at the intersections.
    const phis = [minimumCone];
    const thetas = [minimumClock];
    for (i = 0; i < stackPartitions; i++) {
      phis.push(
        minimumCone + (i * (maximumCone - minimumCone)) / (stackPartitions - 1)
      );
    }
    phis.push(maximumCone);
    for (j = 0; j < slicePartitions; j++) {
      thetas.push(
        minimumClock + (j * (maximumClock - minimumClock)) / (slicePartitions - 1)
      );
    }
    thetas.push(maximumClock);
    const numPhis = phis.length;
    const numThetas = thetas.length;

    // Allow for extra indices if there is an inner surface and if we need
    // to close the sides if the clock range is not a full circle
    let extraIndices = 0;
    let vertexMultiplier = 1.0;
    const hasInnerSurface =
      innerRadii.x !== radii.x ||
      innerRadii.y !== radii.y ||
      innerRadii.z !== radii.z;
    let isTopOpen = false;
    let isBotOpen = false;
    let isClockOpen = false;
    if (hasInnerSurface) {
      vertexMultiplier = 2.0;
      if (minimumCone > 0.0) {
        isTopOpen = true;
        extraIndices += slicePartitions - 1;
      }
      if (maximumCone < Math.PI) {
        isBotOpen = true;
        extraIndices += slicePartitions - 1;
      }
      if ((maximumClock - minimumClock) % CesiumMath.TWO_PI) {
        isClockOpen = true;
        extraIndices += (stackPartitions - 1) * 2 + 1;
      } else {
        extraIndices += 1;
      }
    }

    const vertexCount = numThetas * numPhis * vertexMultiplier;
    const positions = new Float64Array(vertexCount * 3);
    const isInner = new Array(vertexCount).fill(false);
    const negateNormal = new Array(vertexCount).fill(false);

    // Multiply by 6 because there are two triangles per sector
    const indexCount = slicePartitions * stackPartitions * vertexMultiplier;
    const numIndices =
      6 *
      (indexCount +
        extraIndices +
        1 -
        (slicePartitions + stackPartitions) * vertexMultiplier);
    const indices = IndexDatatype$1.createTypedArray(indexCount, numIndices);

    const normals = vertexFormat.normal
      ? new Float32Array(vertexCount * 3)
      : undefined;
    const tangents = vertexFormat.tangent
      ? new Float32Array(vertexCount * 3)
      : undefined;
    const bitangents = vertexFormat.bitangent
      ? new Float32Array(vertexCount * 3)
      : undefined;
    const st = vertexFormat.st ? new Float32Array(vertexCount * 2) : undefined;

    // Calculate sin/cos phi
    const sinPhi = new Array(numPhis);
    const cosPhi = new Array(numPhis);
    for (i = 0; i < numPhis; i++) {
      sinPhi[i] = sin$2(phis[i]);
      cosPhi[i] = cos$2(phis[i]);
    }

    // Calculate sin/cos theta
    const sinTheta = new Array(numThetas);
    const cosTheta = new Array(numThetas);
    for (j = 0; j < numThetas; j++) {
      cosTheta[j] = cos$2(thetas[j]);
      sinTheta[j] = sin$2(thetas[j]);
    }

    // Create outer surface
    for (i = 0; i < numPhis; i++) {
      for (j = 0; j < numThetas; j++) {
        positions[index++] = radii.x * sinPhi[i] * cosTheta[j];
        positions[index++] = radii.y * sinPhi[i] * sinTheta[j];
        positions[index++] = radii.z * cosPhi[i];
      }
    }

    // Create inner surface
    let vertexIndex = vertexCount / 2.0;
    if (hasInnerSurface) {
      for (i = 0; i < numPhis; i++) {
        for (j = 0; j < numThetas; j++) {
          positions[index++] = innerRadii.x * sinPhi[i] * cosTheta[j];
          positions[index++] = innerRadii.y * sinPhi[i] * sinTheta[j];
          positions[index++] = innerRadii.z * cosPhi[i];

          // Keep track of which vertices are the inner and which ones
          // need the normal to be negated
          isInner[vertexIndex] = true;
          if (i > 0 && i !== numPhis - 1 && j !== 0 && j !== numThetas - 1) {
            negateNormal[vertexIndex] = true;
          }
          vertexIndex++;
        }
      }
    }

    // Create indices for outer surface
    index = 0;
    let topOffset;
    let bottomOffset;
    for (i = 1; i < numPhis - 2; i++) {
      topOffset = i * numThetas;
      bottomOffset = (i + 1) * numThetas;

      for (j = 1; j < numThetas - 2; j++) {
        indices[index++] = bottomOffset + j;
        indices[index++] = bottomOffset + j + 1;
        indices[index++] = topOffset + j + 1;

        indices[index++] = bottomOffset + j;
        indices[index++] = topOffset + j + 1;
        indices[index++] = topOffset + j;
      }
    }

    // Create indices for inner surface
    if (hasInnerSurface) {
      const offset = numPhis * numThetas;
      for (i = 1; i < numPhis - 2; i++) {
        topOffset = offset + i * numThetas;
        bottomOffset = offset + (i + 1) * numThetas;

        for (j = 1; j < numThetas - 2; j++) {
          indices[index++] = bottomOffset + j;
          indices[index++] = topOffset + j;
          indices[index++] = topOffset + j + 1;

          indices[index++] = bottomOffset + j;
          indices[index++] = topOffset + j + 1;
          indices[index++] = bottomOffset + j + 1;
        }
      }
    }

    let outerOffset;
    let innerOffset;
    if (hasInnerSurface) {
      if (isTopOpen) {
        // Connect the top of the inner surface to the top of the outer surface
        innerOffset = numPhis * numThetas;
        for (i = 1; i < numThetas - 2; i++) {
          indices[index++] = i;
          indices[index++] = i + 1;
          indices[index++] = innerOffset + i + 1;

          indices[index++] = i;
          indices[index++] = innerOffset + i + 1;
          indices[index++] = innerOffset + i;
        }
      }

      if (isBotOpen) {
        // Connect the bottom of the inner surface to the bottom of the outer surface
        outerOffset = numPhis * numThetas - numThetas;
        innerOffset = numPhis * numThetas * vertexMultiplier - numThetas;
        for (i = 1; i < numThetas - 2; i++) {
          indices[index++] = outerOffset + i + 1;
          indices[index++] = outerOffset + i;
          indices[index++] = innerOffset + i;

          indices[index++] = outerOffset + i + 1;
          indices[index++] = innerOffset + i;
          indices[index++] = innerOffset + i + 1;
        }
      }
    }

    // Connect the edges if clock is not closed
    if (isClockOpen) {
      for (i = 1; i < numPhis - 2; i++) {
        innerOffset = numThetas * numPhis + numThetas * i;
        outerOffset = numThetas * i;
        indices[index++] = innerOffset;
        indices[index++] = outerOffset + numThetas;
        indices[index++] = outerOffset;

        indices[index++] = innerOffset;
        indices[index++] = innerOffset + numThetas;
        indices[index++] = outerOffset + numThetas;
      }

      for (i = 1; i < numPhis - 2; i++) {
        innerOffset = numThetas * numPhis + numThetas * (i + 1) - 1;
        outerOffset = numThetas * (i + 1) - 1;
        indices[index++] = outerOffset + numThetas;
        indices[index++] = innerOffset;
        indices[index++] = outerOffset;

        indices[index++] = outerOffset + numThetas;
        indices[index++] = innerOffset + numThetas;
        indices[index++] = innerOffset;
      }
    }

    const attributes = new GeometryAttributes();

    if (vertexFormat.position) {
      attributes.position = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.DOUBLE,
        componentsPerAttribute: 3,
        values: positions,
      });
    }

    let stIndex = 0;
    let normalIndex = 0;
    let tangentIndex = 0;
    let bitangentIndex = 0;
    const vertexCountHalf = vertexCount / 2.0;

    let ellipsoid;
    const ellipsoidOuter = Ellipsoid.fromCartesian3(radii);
    const ellipsoidInner = Ellipsoid.fromCartesian3(innerRadii);

    if (
      vertexFormat.st ||
      vertexFormat.normal ||
      vertexFormat.tangent ||
      vertexFormat.bitangent
    ) {
      for (i = 0; i < vertexCount; i++) {
        ellipsoid = isInner[i] ? ellipsoidInner : ellipsoidOuter;
        const position = Cartesian3.fromArray(positions, i * 3, scratchPosition$d);
        const normal = ellipsoid.geodeticSurfaceNormal(position, scratchNormal$3);
        if (negateNormal[i]) {
          Cartesian3.negate(normal, normal);
        }

        if (vertexFormat.st) {
          const normalST = Cartesian2.negate(normal, scratchNormalST);
          st[stIndex++] =
            Math.atan2(normalST.y, normalST.x) / CesiumMath.TWO_PI + 0.5;
          st[stIndex++] = Math.asin(normal.z) / Math.PI + 0.5;
        }

        if (vertexFormat.normal) {
          normals[normalIndex++] = normal.x;
          normals[normalIndex++] = normal.y;
          normals[normalIndex++] = normal.z;
        }

        if (vertexFormat.tangent || vertexFormat.bitangent) {
          const tangent = scratchTangent$2;

          // Use UNIT_X for the poles
          let tangetOffset = 0;
          let unit;
          if (isInner[i]) {
            tangetOffset = vertexCountHalf;
          }
          if (
            !isTopOpen &&
            i >= tangetOffset &&
            i < tangetOffset + numThetas * 2
          ) {
            unit = Cartesian3.UNIT_X;
          } else {
            unit = Cartesian3.UNIT_Z;
          }
          Cartesian3.cross(unit, normal, tangent);
          Cartesian3.normalize(tangent, tangent);

          if (vertexFormat.tangent) {
            tangents[tangentIndex++] = tangent.x;
            tangents[tangentIndex++] = tangent.y;
            tangents[tangentIndex++] = tangent.z;
          }

          if (vertexFormat.bitangent) {
            const bitangent = Cartesian3.cross(normal, tangent, scratchBitangent$2);
            Cartesian3.normalize(bitangent, bitangent);

            bitangents[bitangentIndex++] = bitangent.x;
            bitangents[bitangentIndex++] = bitangent.y;
            bitangents[bitangentIndex++] = bitangent.z;
          }
        }
      }

      if (vertexFormat.st) {
        attributes.st = new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 2,
          values: st,
        });
      }

      if (vertexFormat.normal) {
        attributes.normal = new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 3,
          values: normals,
        });
      }

      if (vertexFormat.tangent) {
        attributes.tangent = new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 3,
          values: tangents,
        });
      }

      if (vertexFormat.bitangent) {
        attributes.bitangent = new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 3,
          values: bitangents,
        });
      }
    }

    if (defined(ellipsoidGeometry._offsetAttribute)) {
      const length = positions.length;
      const offsetValue =
        ellipsoidGeometry._offsetAttribute === GeometryOffsetAttribute$1.NONE
          ? 0
          : 1;
      const applyOffset = new Uint8Array(length / 3).fill(offsetValue);
      attributes.applyOffset = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
        componentsPerAttribute: 1,
        values: applyOffset,
      });
    }

    return new Geometry({
      attributes: attributes,
      indices: indices,
      primitiveType: PrimitiveType$1.TRIANGLES,
      boundingSphere: BoundingSphere.fromEllipsoid(ellipsoidOuter),
      offsetAttribute: ellipsoidGeometry._offsetAttribute,
    });
  };

  let unitEllipsoidGeometry;

  /**
   * Returns the geometric representation of a unit ellipsoid, including its vertices, indices, and a bounding sphere.
   * @returns {Geometry} The computed vertices and indices.
   *
   * @private
   */
  EllipsoidGeometry.getUnitEllipsoid = function () {
    if (!defined(unitEllipsoidGeometry)) {
      unitEllipsoidGeometry = EllipsoidGeometry.createGeometry(
        new EllipsoidGeometry({
          radii: new Cartesian3(1.0, 1.0, 1.0),
          vertexFormat: VertexFormat.POSITION_ONLY,
        })
      );
    }
    return unitEllipsoidGeometry;
  };

  const defaultRadii = new Cartesian3(1.0, 1.0, 1.0);
  const cos$1 = Math.cos;
  const sin$1 = Math.sin;

  /**
   * A description of the outline of an ellipsoid centered at the origin.
   *
   * @alias EllipsoidOutlineGeometry
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Cartesian3} [options.radii=Cartesian3(1.0, 1.0, 1.0)] The radii of the ellipsoid in the x, y, and z directions.
   * @param {Cartesian3} [options.innerRadii=options.radii] The inner radii of the ellipsoid in the x, y, and z directions.
   * @param {Number} [options.minimumClock=0.0] The minimum angle lying in the xy-plane measured from the positive x-axis and toward the positive y-axis.
   * @param {Number} [options.maximumClock=2*PI] The maximum angle lying in the xy-plane measured from the positive x-axis and toward the positive y-axis.
   * @param {Number} [options.minimumCone=0.0] The minimum angle measured from the positive z-axis and toward the negative z-axis.
   * @param {Number} [options.maximumCone=PI] The maximum angle measured from the positive z-axis and toward the negative z-axis.
   * @param {Number} [options.stackPartitions=10] The count of stacks for the ellipsoid (1 greater than the number of parallel lines).
   * @param {Number} [options.slicePartitions=8] The count of slices for the ellipsoid (Equal to the number of radial lines).
   * @param {Number} [options.subdivisions=128] The number of points per line, determining the granularity of the curvature.
   *
   * @exception {DeveloperError} options.stackPartitions must be greater than or equal to one.
   * @exception {DeveloperError} options.slicePartitions must be greater than or equal to zero.
   * @exception {DeveloperError} options.subdivisions must be greater than or equal to zero.
   *
   * @example
   * const ellipsoid = new Cesium.EllipsoidOutlineGeometry({
   *   radii : new Cesium.Cartesian3(1000000.0, 500000.0, 500000.0),
   *   stackPartitions: 6,
   *   slicePartitions: 5
   * });
   * const geometry = Cesium.EllipsoidOutlineGeometry.createGeometry(ellipsoid);
   */
  function EllipsoidOutlineGeometry(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const radii = defaultValue(options.radii, defaultRadii);
    const innerRadii = defaultValue(options.innerRadii, radii);
    const minimumClock = defaultValue(options.minimumClock, 0.0);
    const maximumClock = defaultValue(options.maximumClock, CesiumMath.TWO_PI);
    const minimumCone = defaultValue(options.minimumCone, 0.0);
    const maximumCone = defaultValue(options.maximumCone, CesiumMath.PI);
    const stackPartitions = Math.round(defaultValue(options.stackPartitions, 10));
    const slicePartitions = Math.round(defaultValue(options.slicePartitions, 8));
    const subdivisions = Math.round(defaultValue(options.subdivisions, 128));

    //>>includeStart('debug', pragmas.debug);
    if (stackPartitions < 1) {
      throw new DeveloperError("options.stackPartitions cannot be less than 1");
    }
    if (slicePartitions < 0) {
      throw new DeveloperError("options.slicePartitions cannot be less than 0");
    }
    if (subdivisions < 0) {
      throw new DeveloperError(
        "options.subdivisions must be greater than or equal to zero."
      );
    }
    if (
      defined(options.offsetAttribute) &&
      options.offsetAttribute === GeometryOffsetAttribute$1.TOP
    ) {
      throw new DeveloperError(
        "GeometryOffsetAttribute.TOP is not a supported options.offsetAttribute for this geometry."
      );
    }
    //>>includeEnd('debug');

    this._radii = Cartesian3.clone(radii);
    this._innerRadii = Cartesian3.clone(innerRadii);
    this._minimumClock = minimumClock;
    this._maximumClock = maximumClock;
    this._minimumCone = minimumCone;
    this._maximumCone = maximumCone;
    this._stackPartitions = stackPartitions;
    this._slicePartitions = slicePartitions;
    this._subdivisions = subdivisions;
    this._offsetAttribute = options.offsetAttribute;
    this._workerName = "createEllipsoidOutlineGeometry";
  }

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  EllipsoidOutlineGeometry.packedLength = 2 * Cartesian3.packedLength + 8;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {EllipsoidOutlineGeometry} 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
   */
  EllipsoidOutlineGeometry.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(value)) {
      throw new DeveloperError("value is required");
    }
    if (!defined(array)) {
      throw new DeveloperError("array is required");
    }
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    Cartesian3.pack(value._radii, array, startingIndex);
    startingIndex += Cartesian3.packedLength;

    Cartesian3.pack(value._innerRadii, array, startingIndex);
    startingIndex += Cartesian3.packedLength;

    array[startingIndex++] = value._minimumClock;
    array[startingIndex++] = value._maximumClock;
    array[startingIndex++] = value._minimumCone;
    array[startingIndex++] = value._maximumCone;
    array[startingIndex++] = value._stackPartitions;
    array[startingIndex++] = value._slicePartitions;
    array[startingIndex++] = value._subdivisions;
    array[startingIndex] = defaultValue(value._offsetAttribute, -1);

    return array;
  };

  const scratchRadii$1 = new Cartesian3();
  const scratchInnerRadii = new Cartesian3();
  const scratchOptions$a = {
    radii: scratchRadii$1,
    innerRadii: scratchInnerRadii,
    minimumClock: undefined,
    maximumClock: undefined,
    minimumCone: undefined,
    maximumCone: undefined,
    stackPartitions: undefined,
    slicePartitions: undefined,
    subdivisions: undefined,
    offsetAttribute: undefined,
  };

  /**
   * 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 {EllipsoidOutlineGeometry} [result] The object into which to store the result.
   * @returns {EllipsoidOutlineGeometry} The modified result parameter or a new EllipsoidOutlineGeometry instance if one was not provided.
   */
  EllipsoidOutlineGeometry.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(array)) {
      throw new DeveloperError("array is required");
    }
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    const radii = Cartesian3.unpack(array, startingIndex, scratchRadii$1);
    startingIndex += Cartesian3.packedLength;

    const innerRadii = Cartesian3.unpack(array, startingIndex, scratchInnerRadii);
    startingIndex += Cartesian3.packedLength;

    const minimumClock = array[startingIndex++];
    const maximumClock = array[startingIndex++];
    const minimumCone = array[startingIndex++];
    const maximumCone = array[startingIndex++];
    const stackPartitions = array[startingIndex++];
    const slicePartitions = array[startingIndex++];
    const subdivisions = array[startingIndex++];
    const offsetAttribute = array[startingIndex];

    if (!defined(result)) {
      scratchOptions$a.minimumClock = minimumClock;
      scratchOptions$a.maximumClock = maximumClock;
      scratchOptions$a.minimumCone = minimumCone;
      scratchOptions$a.maximumCone = maximumCone;
      scratchOptions$a.stackPartitions = stackPartitions;
      scratchOptions$a.slicePartitions = slicePartitions;
      scratchOptions$a.subdivisions = subdivisions;
      scratchOptions$a.offsetAttribute =
        offsetAttribute === -1 ? undefined : offsetAttribute;
      return new EllipsoidOutlineGeometry(scratchOptions$a);
    }

    result._radii = Cartesian3.clone(radii, result._radii);
    result._innerRadii = Cartesian3.clone(innerRadii, result._innerRadii);
    result._minimumClock = minimumClock;
    result._maximumClock = maximumClock;
    result._minimumCone = minimumCone;
    result._maximumCone = maximumCone;
    result._stackPartitions = stackPartitions;
    result._slicePartitions = slicePartitions;
    result._subdivisions = subdivisions;
    result._offsetAttribute =
      offsetAttribute === -1 ? undefined : offsetAttribute;

    return result;
  };

  /**
   * Computes the geometric representation of an outline of an ellipsoid, including its vertices, indices, and a bounding sphere.
   *
   * @param {EllipsoidOutlineGeometry} ellipsoidGeometry A description of the ellipsoid outline.
   * @returns {Geometry|undefined} The computed vertices and indices.
   */
  EllipsoidOutlineGeometry.createGeometry = function (ellipsoidGeometry) {
    const radii = ellipsoidGeometry._radii;
    if (radii.x <= 0 || radii.y <= 0 || radii.z <= 0) {
      return;
    }

    const innerRadii = ellipsoidGeometry._innerRadii;
    if (innerRadii.x <= 0 || innerRadii.y <= 0 || innerRadii.z <= 0) {
      return;
    }

    const minimumClock = ellipsoidGeometry._minimumClock;
    const maximumClock = ellipsoidGeometry._maximumClock;
    const minimumCone = ellipsoidGeometry._minimumCone;
    const maximumCone = ellipsoidGeometry._maximumCone;
    const subdivisions = ellipsoidGeometry._subdivisions;
    const ellipsoid = Ellipsoid.fromCartesian3(radii);

    // Add an extra slice and stack to remain consistent with EllipsoidGeometry
    let slicePartitions = ellipsoidGeometry._slicePartitions + 1;
    let stackPartitions = ellipsoidGeometry._stackPartitions + 1;

    slicePartitions = Math.round(
      (slicePartitions * Math.abs(maximumClock - minimumClock)) /
        CesiumMath.TWO_PI
    );
    stackPartitions = Math.round(
      (stackPartitions * Math.abs(maximumCone - minimumCone)) / CesiumMath.PI
    );

    if (slicePartitions < 2) {
      slicePartitions = 2;
    }
    if (stackPartitions < 2) {
      stackPartitions = 2;
    }

    let extraIndices = 0;
    let vertexMultiplier = 1.0;
    const hasInnerSurface =
      innerRadii.x !== radii.x ||
      innerRadii.y !== radii.y ||
      innerRadii.z !== radii.z;
    let isTopOpen = false;
    let isBotOpen = false;
    if (hasInnerSurface) {
      vertexMultiplier = 2.0;
      // Add 2x slicePartitions to connect the top/bottom of the outer to
      // the top/bottom of the inner
      if (minimumCone > 0.0) {
        isTopOpen = true;
        extraIndices += slicePartitions;
      }
      if (maximumCone < Math.PI) {
        isBotOpen = true;
        extraIndices += slicePartitions;
      }
    }

    const vertexCount =
      subdivisions * vertexMultiplier * (stackPartitions + slicePartitions);
    const positions = new Float64Array(vertexCount * 3);

    // Multiply by two because two points define each line segment
    const numIndices =
      2 *
      (vertexCount +
        extraIndices -
        (slicePartitions + stackPartitions) * vertexMultiplier);
    const indices = IndexDatatype$1.createTypedArray(vertexCount, numIndices);

    let i;
    let j;
    let theta;
    let phi;
    let index = 0;

    // Calculate sin/cos phi
    const sinPhi = new Array(stackPartitions);
    const cosPhi = new Array(stackPartitions);
    for (i = 0; i < stackPartitions; i++) {
      phi =
        minimumCone + (i * (maximumCone - minimumCone)) / (stackPartitions - 1);
      sinPhi[i] = sin$1(phi);
      cosPhi[i] = cos$1(phi);
    }

    // Calculate sin/cos theta
    const sinTheta = new Array(subdivisions);
    const cosTheta = new Array(subdivisions);
    for (i = 0; i < subdivisions; i++) {
      theta =
        minimumClock + (i * (maximumClock - minimumClock)) / (subdivisions - 1);
      sinTheta[i] = sin$1(theta);
      cosTheta[i] = cos$1(theta);
    }

    // Calculate the latitude lines on the outer surface
    for (i = 0; i < stackPartitions; i++) {
      for (j = 0; j < subdivisions; j++) {
        positions[index++] = radii.x * sinPhi[i] * cosTheta[j];
        positions[index++] = radii.y * sinPhi[i] * sinTheta[j];
        positions[index++] = radii.z * cosPhi[i];
      }
    }

    // Calculate the latitude lines on the inner surface
    if (hasInnerSurface) {
      for (i = 0; i < stackPartitions; i++) {
        for (j = 0; j < subdivisions; j++) {
          positions[index++] = innerRadii.x * sinPhi[i] * cosTheta[j];
          positions[index++] = innerRadii.y * sinPhi[i] * sinTheta[j];
          positions[index++] = innerRadii.z * cosPhi[i];
        }
      }
    }

    // Calculate sin/cos phi
    sinPhi.length = subdivisions;
    cosPhi.length = subdivisions;
    for (i = 0; i < subdivisions; i++) {
      phi = minimumCone + (i * (maximumCone - minimumCone)) / (subdivisions - 1);
      sinPhi[i] = sin$1(phi);
      cosPhi[i] = cos$1(phi);
    }

    // Calculate sin/cos theta for each slice partition
    sinTheta.length = slicePartitions;
    cosTheta.length = slicePartitions;
    for (i = 0; i < slicePartitions; i++) {
      theta =
        minimumClock +
        (i * (maximumClock - minimumClock)) / (slicePartitions - 1);
      sinTheta[i] = sin$1(theta);
      cosTheta[i] = cos$1(theta);
    }

    // Calculate the longitude lines on the outer surface
    for (i = 0; i < subdivisions; i++) {
      for (j = 0; j < slicePartitions; j++) {
        positions[index++] = radii.x * sinPhi[i] * cosTheta[j];
        positions[index++] = radii.y * sinPhi[i] * sinTheta[j];
        positions[index++] = radii.z * cosPhi[i];
      }
    }

    // Calculate the longitude lines on the inner surface
    if (hasInnerSurface) {
      for (i = 0; i < subdivisions; i++) {
        for (j = 0; j < slicePartitions; j++) {
          positions[index++] = innerRadii.x * sinPhi[i] * cosTheta[j];
          positions[index++] = innerRadii.y * sinPhi[i] * sinTheta[j];
          positions[index++] = innerRadii.z * cosPhi[i];
        }
      }
    }

    // Create indices for the latitude lines
    index = 0;
    for (i = 0; i < stackPartitions * vertexMultiplier; i++) {
      const topOffset = i * subdivisions;
      for (j = 0; j < subdivisions - 1; j++) {
        indices[index++] = topOffset + j;
        indices[index++] = topOffset + j + 1;
      }
    }

    // Create indices for the outer longitude lines
    let offset = stackPartitions * subdivisions * vertexMultiplier;
    for (i = 0; i < slicePartitions; i++) {
      for (j = 0; j < subdivisions - 1; j++) {
        indices[index++] = offset + i + j * slicePartitions;
        indices[index++] = offset + i + (j + 1) * slicePartitions;
      }
    }

    // Create indices for the inner longitude lines
    if (hasInnerSurface) {
      offset =
        stackPartitions * subdivisions * vertexMultiplier +
        slicePartitions * subdivisions;
      for (i = 0; i < slicePartitions; i++) {
        for (j = 0; j < subdivisions - 1; j++) {
          indices[index++] = offset + i + j * slicePartitions;
          indices[index++] = offset + i + (j + 1) * slicePartitions;
        }
      }
    }

    if (hasInnerSurface) {
      let outerOffset = stackPartitions * subdivisions * vertexMultiplier;
      let innerOffset = outerOffset + subdivisions * slicePartitions;
      if (isTopOpen) {
        // Draw lines from the top of the inner surface to the top of the outer surface
        for (i = 0; i < slicePartitions; i++) {
          indices[index++] = outerOffset + i;
          indices[index++] = innerOffset + i;
        }
      }

      if (isBotOpen) {
        // Draw lines from the top of the inner surface to the top of the outer surface
        outerOffset += subdivisions * slicePartitions - slicePartitions;
        innerOffset += subdivisions * slicePartitions - slicePartitions;
        for (i = 0; i < slicePartitions; i++) {
          indices[index++] = outerOffset + i;
          indices[index++] = innerOffset + i;
        }
      }
    }

    const attributes = new GeometryAttributes({
      position: new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.DOUBLE,
        componentsPerAttribute: 3,
        values: positions,
      }),
    });

    if (defined(ellipsoidGeometry._offsetAttribute)) {
      const length = positions.length;
      const offsetValue =
        ellipsoidGeometry._offsetAttribute === GeometryOffsetAttribute$1.NONE
          ? 0
          : 1;
      const applyOffset = new Uint8Array(length / 3).fill(offsetValue);
      attributes.applyOffset = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
        componentsPerAttribute: 1,
        values: applyOffset,
      });
    }

    return new Geometry({
      attributes: attributes,
      indices: indices,
      primitiveType: PrimitiveType$1.LINES,
      boundingSphere: BoundingSphere.fromEllipsoid(ellipsoid),
      offsetAttribute: ellipsoidGeometry._offsetAttribute,
    });
  };

  /**
   * A very simple {@link TerrainProvider} that produces geometry by tessellating an ellipsoidal
   * surface.
   *
   * @alias EllipsoidTerrainProvider
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {TilingScheme} [options.tilingScheme] The tiling scheme specifying how the ellipsoidal
   * surface is broken into tiles.  If this parameter is not provided, a {@link GeographicTilingScheme}
   * is used.
   * @param {Ellipsoid} [options.ellipsoid] The ellipsoid.  If the tilingScheme is specified,
   * this parameter is ignored and the tiling scheme's ellipsoid is used instead. If neither
   * parameter is specified, the WGS84 ellipsoid is used.
   *
   * @see TerrainProvider
   */
  function EllipsoidTerrainProvider(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    this._tilingScheme = options.tilingScheme;
    if (!defined(this._tilingScheme)) {
      this._tilingScheme = new GeographicTilingScheme({
        ellipsoid: defaultValue(options.ellipsoid, Ellipsoid.WGS84),
      });
    }

    // Note: the 64 below does NOT need to match the actual vertex dimensions, because
    // the ellipsoid is significantly smoother than actual terrain.
    this._levelZeroMaximumGeometricError = TerrainProvider.getEstimatedLevelZeroGeometricErrorForAHeightmap(
      this._tilingScheme.ellipsoid,
      64,
      this._tilingScheme.getNumberOfXTilesAtLevel(0)
    );

    this._errorEvent = new Event();
    this._readyPromise = Promise.resolve(true);
  }

  Object.defineProperties(EllipsoidTerrainProvider.prototype, {
    /**
     * Gets an event that is raised when the terrain provider encounters an asynchronous error.  By subscribing
     * to the event, you will be notified of the error and can potentially recover from it.  Event listeners
     * are passed an instance of {@link TileProviderError}.
     * @memberof EllipsoidTerrainProvider.prototype
     * @type {Event}
     * @readonly
     */
    errorEvent: {
      get: function () {
        return this._errorEvent;
      },
    },

    /**
     * Gets the credit to display when this terrain provider is active.  Typically this is used to credit
     * the source of the terrain.  This function should not be called before {@link EllipsoidTerrainProvider#ready} returns true.
     * @memberof EllipsoidTerrainProvider.prototype
     * @type {Credit}
     * @readonly
     */
    credit: {
      get: function () {
        return undefined;
      },
    },

    /**
     * Gets the tiling scheme used by this provider.  This function should
     * not be called before {@link EllipsoidTerrainProvider#ready} returns true.
     * @memberof EllipsoidTerrainProvider.prototype
     * @type {GeographicTilingScheme}
     * @readonly
     */
    tilingScheme: {
      get: function () {
        return this._tilingScheme;
      },
    },

    /**
     * Gets a value indicating whether or not the provider is ready for use.
     * @memberof EllipsoidTerrainProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    ready: {
      get: function () {
        return true;
      },
    },

    /**
     * Gets a promise that resolves to true when the provider is ready for use.
     * @memberof EllipsoidTerrainProvider.prototype
     * @type {Promise.<Boolean>}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._readyPromise;
      },
    },

    /**
     * Gets a value indicating whether or not the provider includes a water mask.  The water mask
     * indicates which areas of the globe are water rather than land, so they can be rendered
     * as a reflective surface with animated waves.  This function should not be
     * called before {@link EllipsoidTerrainProvider#ready} returns true.
     * @memberof EllipsoidTerrainProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    hasWaterMask: {
      get: function () {
        return false;
      },
    },

    /**
     * Gets a value indicating whether or not the requested tiles include vertex normals.
     * This function should not be called before {@link EllipsoidTerrainProvider#ready} returns true.
     * @memberof EllipsoidTerrainProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    hasVertexNormals: {
      get: function () {
        return false;
      },
    },
    /**
     * Gets an object that can be used to determine availability of terrain from this provider, such as
     * at points and in rectangles.  This function should not be called before
     * {@link TerrainProvider#ready} returns true.  This property may be undefined if availability
     * information is not available.
     * @memberof EllipsoidTerrainProvider.prototype
     * @type {TileAvailability}
     * @readonly
     */
    availability: {
      get: function () {
        return undefined;
      },
    },
  });

  /**
   * Requests the geometry for a given tile.  This function should not be called before
   * {@link TerrainProvider#ready} returns true.  The result includes terrain
   * data and indicates that all child tiles are available.
   *
   * @param {Number} x The X coordinate of the tile for which to request geometry.
   * @param {Number} y The Y coordinate of the tile for which to request geometry.
   * @param {Number} level The level of the tile for which to request geometry.
   * @param {Request} [request] The request object. Intended for internal use only.
   *
   * @returns {Promise.<TerrainData>|undefined} A promise for the requested geometry.  If this method
   *          returns undefined instead of a promise, it is an indication that too many requests are already
   *          pending and the request will be retried later.
   */
  EllipsoidTerrainProvider.prototype.requestTileGeometry = function (
    x,
    y,
    level,
    request
  ) {
    const width = 16;
    const height = 16;
    return Promise.resolve(
      new HeightmapTerrainData({
        buffer: new Uint8Array(width * height),
        width: width,
        height: height,
      })
    );
  };

  /**
   * Gets the maximum geometric error allowed in a tile at a given level.
   *
   * @param {Number} level The tile level for which to get the maximum geometric error.
   * @returns {Number} The maximum geometric error.
   */
  EllipsoidTerrainProvider.prototype.getLevelMaximumGeometricError = function (
    level
  ) {
    return this._levelZeroMaximumGeometricError / (1 << level);
  };

  /**
   * Determines whether data for a tile is available to be loaded.
   *
   * @param {Number} x The X coordinate of the tile for which to request geometry.
   * @param {Number} y The Y coordinate of the tile for which to request geometry.
   * @param {Number} level The level of the tile for which to request geometry.
   * @returns {Boolean|undefined} Undefined if not supported, otherwise true or false.
   */
  EllipsoidTerrainProvider.prototype.getTileDataAvailable = function (
    x,
    y,
    level
  ) {
    return undefined;
  };

  /**
   * Makes sure we load availability data for a tile
   *
   * @param {Number} x The X coordinate of the tile for which to request geometry.
   * @param {Number} y The Y coordinate of the tile for which to request geometry.
   * @param {Number} level The level of the tile for which to request geometry.
   * @returns {undefined} This provider does not support loading availability.
   */
  EllipsoidTerrainProvider.prototype.loadTileDataAvailability = function (
    x,
    y,
    level
  ) {
    return undefined;
  };

  /**
   * A convenience object that simplifies the common pattern of attaching event listeners
   * to several events, then removing all those listeners at once later, for example, in
   * a destroy method.
   *
   * @alias EventHelper
   * @constructor
   *
   *
   * @example
   * const helper = new Cesium.EventHelper();
   *
   * helper.add(someObject.event, listener1, this);
   * helper.add(otherObject.event, listener2, this);
   *
   * // later...
   * helper.removeAll();
   *
   * @see Event
   */
  function EventHelper() {
    this._removalFunctions = [];
  }

  /**
   * Adds a listener to an event, and records the registration to be cleaned up later.
   *
   * @param {Event} event The event to attach to.
   * @param {Function} listener The function to be executed when the event is raised.
   * @param {Object} [scope] An optional object scope to serve as the <code>this</code>
   *        pointer in which the listener function will execute.
   * @returns {EventHelper.RemoveCallback} A function that will remove this event listener when invoked.
   *
   * @see Event#addEventListener
   */
  EventHelper.prototype.add = function (event, listener, scope) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(event)) {
      throw new DeveloperError("event is required");
    }
    //>>includeEnd('debug');

    const removalFunction = event.addEventListener(listener, scope);
    this._removalFunctions.push(removalFunction);

    const that = this;
    return function () {
      removalFunction();
      const removalFunctions = that._removalFunctions;
      removalFunctions.splice(removalFunctions.indexOf(removalFunction), 1);
    };
  };

  /**
   * Unregisters all previously added listeners.
   *
   * @see Event#removeEventListener
   */
  EventHelper.prototype.removeAll = function () {
    const removalFunctions = this._removalFunctions;
    for (let i = 0, len = removalFunctions.length; i < len; ++i) {
      removalFunctions[i]();
    }
    removalFunctions.length = 0;
  };

  /**
   * Flags to enable experimental features in CesiumJS. Stability and performance
   * may not be optimal when these are enabled. Experimental features are subject
   * to change without Cesium's standard deprecation policy.
   * <p>
   * Experimental features must still uphold Cesium's quality standards. Here
   * are some guidelines:
   * </p>
   * <ul>
   *   <li>Experimental features must have high unit test coverage like any other feature.</li>
   *   <li>Experimental features are intended for large features where there is benefit of merging some of the code sooner (e.g. to avoid long-running staging branches)</li>
   *   <li>Experimental flags should be short-lived. Make it clear in the PR what it would take to promote the feature to a regular feature.</li>
   *   <li>To avoid cluttering the code, check the flag in as few places as possible. Ideally this would be a single place.</li>
   * </ul>
   *
   * @namespace
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  const ExperimentalFeatures = {
    /**
     * Toggles the usage of the ModelExperimental class.
     *
     * @type {Boolean}
     */
    enableModelExperimental: false,
  };

  /**
   * Constants to determine how an interpolated value is extrapolated
   * when querying outside the bounds of available data.
   *
   * @enum {Number}
   *
   * @see SampledProperty
   */
  const ExtrapolationType = {
    /**
     * No extrapolation occurs.
     *
     * @type {Number}
     * @constant
     */
    NONE: 0,

    /**
     * The first or last value is used when outside the range of sample data.
     *
     * @type {Number}
     * @constant
     */
    HOLD: 1,

    /**
     * The value is extrapolated.
     *
     * @type {Number}
     * @constant
     */
    EXTRAPOLATE: 2,
  };
  var ExtrapolationType$1 = Object.freeze(ExtrapolationType);

  /**
   * The viewing frustum is defined by 6 planes.
   * Each plane is represented by a {@link Cartesian4} object, where the x, y, and z components
   * define the unit vector normal to the plane, and the w component is the distance of the
   * plane from the origin/camera position.
   *
   * @alias OrthographicOffCenterFrustum
   * @constructor
   *
   * @param {Object} [options] An object with the following properties:
   * @param {Number} [options.left] The left clipping plane distance.
   * @param {Number} [options.right] The right clipping plane distance.
   * @param {Number} [options.top] The top clipping plane distance.
   * @param {Number} [options.bottom] The bottom clipping plane distance.
   * @param {Number} [options.near=1.0] The near clipping plane distance.
   * @param {Number} [options.far=500000000.0] The far clipping plane distance.
   *
   * @example
   * const maxRadii = ellipsoid.maximumRadius;
   *
   * const frustum = new Cesium.OrthographicOffCenterFrustum();
   * frustum.right = maxRadii * Cesium.Math.PI;
   * frustum.left = -c.frustum.right;
   * frustum.top = c.frustum.right * (canvas.clientHeight / canvas.clientWidth);
   * frustum.bottom = -c.frustum.top;
   * frustum.near = 0.01 * maxRadii;
   * frustum.far = 50.0 * maxRadii;
   */
  function OrthographicOffCenterFrustum(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    /**
     * The left clipping plane.
     * @type {Number}
     * @default undefined
     */
    this.left = options.left;
    this._left = undefined;

    /**
     * The right clipping plane.
     * @type {Number}
     * @default undefined
     */
    this.right = options.right;
    this._right = undefined;

    /**
     * The top clipping plane.
     * @type {Number}
     * @default undefined
     */
    this.top = options.top;
    this._top = undefined;

    /**
     * The bottom clipping plane.
     * @type {Number}
     * @default undefined
     */
    this.bottom = options.bottom;
    this._bottom = undefined;

    /**
     * The distance of the near plane.
     * @type {Number}
     * @default 1.0
     */
    this.near = defaultValue(options.near, 1.0);
    this._near = this.near;

    /**
     * The distance of the far plane.
     * @type {Number}
     * @default 500000000.0;
     */
    this.far = defaultValue(options.far, 500000000.0);
    this._far = this.far;

    this._cullingVolume = new CullingVolume();
    this._orthographicMatrix = new Matrix4();
  }

  function update$5(frustum) {
    //>>includeStart('debug', pragmas.debug);
    if (
      !defined(frustum.right) ||
      !defined(frustum.left) ||
      !defined(frustum.top) ||
      !defined(frustum.bottom) ||
      !defined(frustum.near) ||
      !defined(frustum.far)
    ) {
      throw new DeveloperError(
        "right, left, top, bottom, near, or far parameters are not set."
      );
    }
    //>>includeEnd('debug');

    if (
      frustum.top !== frustum._top ||
      frustum.bottom !== frustum._bottom ||
      frustum.left !== frustum._left ||
      frustum.right !== frustum._right ||
      frustum.near !== frustum._near ||
      frustum.far !== frustum._far
    ) {
      //>>includeStart('debug', pragmas.debug);
      if (frustum.left > frustum.right) {
        throw new DeveloperError("right must be greater than left.");
      }
      if (frustum.bottom > frustum.top) {
        throw new DeveloperError("top must be greater than bottom.");
      }
      if (frustum.near <= 0 || frustum.near > frustum.far) {
        throw new DeveloperError(
          "near must be greater than zero and less than far."
        );
      }
      //>>includeEnd('debug');

      frustum._left = frustum.left;
      frustum._right = frustum.right;
      frustum._top = frustum.top;
      frustum._bottom = frustum.bottom;
      frustum._near = frustum.near;
      frustum._far = frustum.far;
      frustum._orthographicMatrix = Matrix4.computeOrthographicOffCenter(
        frustum.left,
        frustum.right,
        frustum.bottom,
        frustum.top,
        frustum.near,
        frustum.far,
        frustum._orthographicMatrix
      );
    }
  }

  Object.defineProperties(OrthographicOffCenterFrustum.prototype, {
    /**
     * Gets the orthographic projection matrix computed from the view frustum.
     * @memberof OrthographicOffCenterFrustum.prototype
     * @type {Matrix4}
     * @readonly
     */
    projectionMatrix: {
      get: function () {
        update$5(this);
        return this._orthographicMatrix;
      },
    },
  });

  const getPlanesRight$1 = new Cartesian3();
  const getPlanesNearCenter$1 = new Cartesian3();
  const getPlanesPoint = new Cartesian3();
  const negateScratch = new Cartesian3();

  /**
   * Creates a culling volume for this frustum.
   *
   * @param {Cartesian3} position The eye position.
   * @param {Cartesian3} direction The view direction.
   * @param {Cartesian3} up The up direction.
   * @returns {CullingVolume} A culling volume at the given position and orientation.
   *
   * @example
   * // Check if a bounding volume intersects the frustum.
   * const cullingVolume = frustum.computeCullingVolume(cameraPosition, cameraDirection, cameraUp);
   * const intersect = cullingVolume.computeVisibility(boundingVolume);
   */
  OrthographicOffCenterFrustum.prototype.computeCullingVolume = function (
    position,
    direction,
    up
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(position)) {
      throw new DeveloperError("position is required.");
    }
    if (!defined(direction)) {
      throw new DeveloperError("direction is required.");
    }
    if (!defined(up)) {
      throw new DeveloperError("up is required.");
    }
    //>>includeEnd('debug');

    const planes = this._cullingVolume.planes;
    const t = this.top;
    const b = this.bottom;
    const r = this.right;
    const l = this.left;
    const n = this.near;
    const f = this.far;

    const right = Cartesian3.cross(direction, up, getPlanesRight$1);
    Cartesian3.normalize(right, right);
    const nearCenter = getPlanesNearCenter$1;
    Cartesian3.multiplyByScalar(direction, n, nearCenter);
    Cartesian3.add(position, nearCenter, nearCenter);

    const point = getPlanesPoint;

    // Left plane
    Cartesian3.multiplyByScalar(right, l, point);
    Cartesian3.add(nearCenter, point, point);

    let plane = planes[0];
    if (!defined(plane)) {
      plane = planes[0] = new Cartesian4();
    }
    plane.x = right.x;
    plane.y = right.y;
    plane.z = right.z;
    plane.w = -Cartesian3.dot(right, point);

    // Right plane
    Cartesian3.multiplyByScalar(right, r, point);
    Cartesian3.add(nearCenter, point, point);

    plane = planes[1];
    if (!defined(plane)) {
      plane = planes[1] = new Cartesian4();
    }
    plane.x = -right.x;
    plane.y = -right.y;
    plane.z = -right.z;
    plane.w = -Cartesian3.dot(Cartesian3.negate(right, negateScratch), point);

    // Bottom plane
    Cartesian3.multiplyByScalar(up, b, point);
    Cartesian3.add(nearCenter, point, point);

    plane = planes[2];
    if (!defined(plane)) {
      plane = planes[2] = new Cartesian4();
    }
    plane.x = up.x;
    plane.y = up.y;
    plane.z = up.z;
    plane.w = -Cartesian3.dot(up, point);

    // Top plane
    Cartesian3.multiplyByScalar(up, t, point);
    Cartesian3.add(nearCenter, point, point);

    plane = planes[3];
    if (!defined(plane)) {
      plane = planes[3] = new Cartesian4();
    }
    plane.x = -up.x;
    plane.y = -up.y;
    plane.z = -up.z;
    plane.w = -Cartesian3.dot(Cartesian3.negate(up, negateScratch), point);

    // Near plane
    plane = planes[4];
    if (!defined(plane)) {
      plane = planes[4] = new Cartesian4();
    }
    plane.x = direction.x;
    plane.y = direction.y;
    plane.z = direction.z;
    plane.w = -Cartesian3.dot(direction, nearCenter);

    // Far plane
    Cartesian3.multiplyByScalar(direction, f, point);
    Cartesian3.add(position, point, point);

    plane = planes[5];
    if (!defined(plane)) {
      plane = planes[5] = new Cartesian4();
    }
    plane.x = -direction.x;
    plane.y = -direction.y;
    plane.z = -direction.z;
    plane.w = -Cartesian3.dot(Cartesian3.negate(direction, negateScratch), point);

    return this._cullingVolume;
  };

  /**
   * Returns the pixel's width and height in meters.
   *
   * @param {Number} drawingBufferWidth The width of the drawing buffer.
   * @param {Number} drawingBufferHeight The height of the drawing buffer.
   * @param {Number} distance The distance to the near plane in meters.
   * @param {Number} pixelRatio The scaling factor from pixel space to coordinate space.
   * @param {Cartesian2} result The object onto which to store the result.
   * @returns {Cartesian2} The modified result parameter or a new instance of {@link Cartesian2} with the pixel's width and height in the x and y properties, respectively.
   *
   * @exception {DeveloperError} drawingBufferWidth must be greater than zero.
   * @exception {DeveloperError} drawingBufferHeight must be greater than zero.
   * @exception {DeveloperError} pixelRatio must be greater than zero.
   *
   * @example
   * // Example 1
   * // Get the width and height of a pixel.
   * const pixelSize = camera.frustum.getPixelDimensions(scene.drawingBufferWidth, scene.drawingBufferHeight, 0.0, scene.pixelRatio, new Cesium.Cartesian2());
   */
  OrthographicOffCenterFrustum.prototype.getPixelDimensions = function (
    drawingBufferWidth,
    drawingBufferHeight,
    distance,
    pixelRatio,
    result
  ) {
    update$5(this);

    //>>includeStart('debug', pragmas.debug);
    if (!defined(drawingBufferWidth) || !defined(drawingBufferHeight)) {
      throw new DeveloperError(
        "Both drawingBufferWidth and drawingBufferHeight are required."
      );
    }
    if (drawingBufferWidth <= 0) {
      throw new DeveloperError("drawingBufferWidth must be greater than zero.");
    }
    if (drawingBufferHeight <= 0) {
      throw new DeveloperError("drawingBufferHeight must be greater than zero.");
    }
    if (!defined(distance)) {
      throw new DeveloperError("distance is required.");
    }
    if (!defined(pixelRatio)) {
      throw new DeveloperError("pixelRatio is required.");
    }
    if (pixelRatio <= 0) {
      throw new DeveloperError("pixelRatio must be greater than zero.");
    }
    if (!defined(result)) {
      throw new DeveloperError("A result object is required.");
    }
    //>>includeEnd('debug');

    const frustumWidth = this.right - this.left;
    const frustumHeight = this.top - this.bottom;
    const pixelWidth = (pixelRatio * frustumWidth) / drawingBufferWidth;
    const pixelHeight = (pixelRatio * frustumHeight) / drawingBufferHeight;

    result.x = pixelWidth;
    result.y = pixelHeight;
    return result;
  };

  /**
   * Returns a duplicate of a OrthographicOffCenterFrustum instance.
   *
   * @param {OrthographicOffCenterFrustum} [result] The object onto which to store the result.
   * @returns {OrthographicOffCenterFrustum} The modified result parameter or a new OrthographicOffCenterFrustum instance if one was not provided.
   */
  OrthographicOffCenterFrustum.prototype.clone = function (result) {
    if (!defined(result)) {
      result = new OrthographicOffCenterFrustum();
    }

    result.left = this.left;
    result.right = this.right;
    result.top = this.top;
    result.bottom = this.bottom;
    result.near = this.near;
    result.far = this.far;

    // force update of clone to compute matrices
    result._left = undefined;
    result._right = undefined;
    result._top = undefined;
    result._bottom = undefined;
    result._near = undefined;
    result._far = undefined;

    return result;
  };

  /**
   * Compares the provided OrthographicOffCenterFrustum componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {OrthographicOffCenterFrustum} [other] The right hand side OrthographicOffCenterFrustum.
   * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
   */
  OrthographicOffCenterFrustum.prototype.equals = function (other) {
    return (
      defined(other) &&
      other instanceof OrthographicOffCenterFrustum &&
      this.right === other.right &&
      this.left === other.left &&
      this.top === other.top &&
      this.bottom === other.bottom &&
      this.near === other.near &&
      this.far === other.far
    );
  };

  /**
   * Compares the provided OrthographicOffCenterFrustum componentwise and returns
   * <code>true</code> if they pass an absolute or relative tolerance test,
   * <code>false</code> otherwise.
   *
   * @param {OrthographicOffCenterFrustum} other The right hand side OrthographicOffCenterFrustum.
   * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
   * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
   * @returns {Boolean} <code>true</code> if this and other are within the provided epsilon, <code>false</code> otherwise.
   */
  OrthographicOffCenterFrustum.prototype.equalsEpsilon = function (
    other,
    relativeEpsilon,
    absoluteEpsilon
  ) {
    return (
      other === this ||
      (defined(other) &&
        other instanceof OrthographicOffCenterFrustum &&
        CesiumMath.equalsEpsilon(
          this.right,
          other.right,
          relativeEpsilon,
          absoluteEpsilon
        ) &&
        CesiumMath.equalsEpsilon(
          this.left,
          other.left,
          relativeEpsilon,
          absoluteEpsilon
        ) &&
        CesiumMath.equalsEpsilon(
          this.top,
          other.top,
          relativeEpsilon,
          absoluteEpsilon
        ) &&
        CesiumMath.equalsEpsilon(
          this.bottom,
          other.bottom,
          relativeEpsilon,
          absoluteEpsilon
        ) &&
        CesiumMath.equalsEpsilon(
          this.near,
          other.near,
          relativeEpsilon,
          absoluteEpsilon
        ) &&
        CesiumMath.equalsEpsilon(
          this.far,
          other.far,
          relativeEpsilon,
          absoluteEpsilon
        ))
    );
  };

  /**
   * The viewing frustum is defined by 6 planes.
   * Each plane is represented by a {@link Cartesian4} object, where the x, y, and z components
   * define the unit vector normal to the plane, and the w component is the distance of the
   * plane from the origin/camera position.
   *
   * @alias OrthographicFrustum
   * @constructor
   *
   * @param {Object} [options] An object with the following properties:
   * @param {Number} [options.width] The width of the frustum in meters.
   * @param {Number} [options.aspectRatio] The aspect ratio of the frustum's width to it's height.
   * @param {Number} [options.near=1.0] The distance of the near plane.
   * @param {Number} [options.far=500000000.0] The distance of the far plane.
   *
   * @example
   * const maxRadii = ellipsoid.maximumRadius;
   *
   * const frustum = new Cesium.OrthographicFrustum();
   * frustum.near = 0.01 * maxRadii;
   * frustum.far = 50.0 * maxRadii;
   */
  function OrthographicFrustum(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    this._offCenterFrustum = new OrthographicOffCenterFrustum();

    /**
     * The horizontal width of the frustum in meters.
     * @type {Number}
     * @default undefined
     */
    this.width = options.width;
    this._width = undefined;

    /**
     * The aspect ratio of the frustum's width to it's height.
     * @type {Number}
     * @default undefined
     */
    this.aspectRatio = options.aspectRatio;
    this._aspectRatio = undefined;

    /**
     * The distance of the near plane.
     * @type {Number}
     * @default 1.0
     */
    this.near = defaultValue(options.near, 1.0);
    this._near = this.near;

    /**
     * The distance of the far plane.
     * @type {Number}
     * @default 500000000.0;
     */
    this.far = defaultValue(options.far, 500000000.0);
    this._far = this.far;
  }

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  OrthographicFrustum.packedLength = 4;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {OrthographicFrustum} 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
   */
  OrthographicFrustum.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    array[startingIndex++] = value.width;
    array[startingIndex++] = value.aspectRatio;
    array[startingIndex++] = value.near;
    array[startingIndex] = value.far;

    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 {OrthographicFrustum} [result] The object into which to store the result.
   * @returns {OrthographicFrustum} The modified result parameter or a new OrthographicFrustum instance if one was not provided.
   */
  OrthographicFrustum.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    if (!defined(result)) {
      result = new OrthographicFrustum();
    }

    result.width = array[startingIndex++];
    result.aspectRatio = array[startingIndex++];
    result.near = array[startingIndex++];
    result.far = array[startingIndex];

    return result;
  };

  function update$4(frustum) {
    //>>includeStart('debug', pragmas.debug);
    if (
      !defined(frustum.width) ||
      !defined(frustum.aspectRatio) ||
      !defined(frustum.near) ||
      !defined(frustum.far)
    ) {
      throw new DeveloperError(
        "width, aspectRatio, near, or far parameters are not set."
      );
    }
    //>>includeEnd('debug');

    const f = frustum._offCenterFrustum;

    if (
      frustum.width !== frustum._width ||
      frustum.aspectRatio !== frustum._aspectRatio ||
      frustum.near !== frustum._near ||
      frustum.far !== frustum._far
    ) {
      //>>includeStart('debug', pragmas.debug);
      if (frustum.aspectRatio < 0) {
        throw new DeveloperError("aspectRatio must be positive.");
      }
      if (frustum.near < 0 || frustum.near > frustum.far) {
        throw new DeveloperError(
          "near must be greater than zero and less than far."
        );
      }
      //>>includeEnd('debug');

      frustum._aspectRatio = frustum.aspectRatio;
      frustum._width = frustum.width;
      frustum._near = frustum.near;
      frustum._far = frustum.far;

      const ratio = 1.0 / frustum.aspectRatio;
      f.right = frustum.width * 0.5;
      f.left = -f.right;
      f.top = ratio * f.right;
      f.bottom = -f.top;
      f.near = frustum.near;
      f.far = frustum.far;
    }
  }

  Object.defineProperties(OrthographicFrustum.prototype, {
    /**
     * Gets the orthographic projection matrix computed from the view frustum.
     * @memberof OrthographicFrustum.prototype
     * @type {Matrix4}
     * @readonly
     */
    projectionMatrix: {
      get: function () {
        update$4(this);
        return this._offCenterFrustum.projectionMatrix;
      },
    },
  });

  /**
   * Creates a culling volume for this frustum.
   *
   * @param {Cartesian3} position The eye position.
   * @param {Cartesian3} direction The view direction.
   * @param {Cartesian3} up The up direction.
   * @returns {CullingVolume} A culling volume at the given position and orientation.
   *
   * @example
   * // Check if a bounding volume intersects the frustum.
   * const cullingVolume = frustum.computeCullingVolume(cameraPosition, cameraDirection, cameraUp);
   * const intersect = cullingVolume.computeVisibility(boundingVolume);
   */
  OrthographicFrustum.prototype.computeCullingVolume = function (
    position,
    direction,
    up
  ) {
    update$4(this);
    return this._offCenterFrustum.computeCullingVolume(position, direction, up);
  };

  /**
   * Returns the pixel's width and height in meters.
   *
   * @param {Number} drawingBufferWidth The width of the drawing buffer.
   * @param {Number} drawingBufferHeight The height of the drawing buffer.
   * @param {Number} distance The distance to the near plane in meters.
   * @param {Number} pixelRatio The scaling factor from pixel space to coordinate space.
   * @param {Cartesian2} result The object onto which to store the result.
   * @returns {Cartesian2} The modified result parameter or a new instance of {@link Cartesian2} with the pixel's width and height in the x and y properties, respectively.
   *
   * @exception {DeveloperError} drawingBufferWidth must be greater than zero.
   * @exception {DeveloperError} drawingBufferHeight must be greater than zero.
   * @exception {DeveloperError} pixelRatio must be greater than zero.
   *
   * @example
   * // Example 1
   * // Get the width and height of a pixel.
   * const pixelSize = camera.frustum.getPixelDimensions(scene.drawingBufferWidth, scene.drawingBufferHeight, 0.0, scene.pixelRatio, new Cesium.Cartesian2());
   */
  OrthographicFrustum.prototype.getPixelDimensions = function (
    drawingBufferWidth,
    drawingBufferHeight,
    distance,
    pixelRatio,
    result
  ) {
    update$4(this);
    return this._offCenterFrustum.getPixelDimensions(
      drawingBufferWidth,
      drawingBufferHeight,
      distance,
      pixelRatio,
      result
    );
  };

  /**
   * Returns a duplicate of a OrthographicFrustum instance.
   *
   * @param {OrthographicFrustum} [result] The object onto which to store the result.
   * @returns {OrthographicFrustum} The modified result parameter or a new OrthographicFrustum instance if one was not provided.
   */
  OrthographicFrustum.prototype.clone = function (result) {
    if (!defined(result)) {
      result = new OrthographicFrustum();
    }

    result.aspectRatio = this.aspectRatio;
    result.width = this.width;
    result.near = this.near;
    result.far = this.far;

    // force update of clone to compute matrices
    result._aspectRatio = undefined;
    result._width = undefined;
    result._near = undefined;
    result._far = undefined;

    this._offCenterFrustum.clone(result._offCenterFrustum);

    return result;
  };

  /**
   * Compares the provided OrthographicFrustum componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {OrthographicFrustum} [other] The right hand side OrthographicFrustum.
   * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
   */
  OrthographicFrustum.prototype.equals = function (other) {
    if (!defined(other) || !(other instanceof OrthographicFrustum)) {
      return false;
    }

    update$4(this);
    update$4(other);

    return (
      this.width === other.width &&
      this.aspectRatio === other.aspectRatio &&
      this._offCenterFrustum.equals(other._offCenterFrustum)
    );
  };

  /**
   * Compares the provided OrthographicFrustum componentwise and returns
   * <code>true</code> if they pass an absolute or relative tolerance test,
   * <code>false</code> otherwise.
   *
   * @param {OrthographicFrustum} other The right hand side OrthographicFrustum.
   * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
   * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
   * @returns {Boolean} <code>true</code> if this and other are within the provided epsilon, <code>false</code> otherwise.
   */
  OrthographicFrustum.prototype.equalsEpsilon = function (
    other,
    relativeEpsilon,
    absoluteEpsilon
  ) {
    if (!defined(other) || !(other instanceof OrthographicFrustum)) {
      return false;
    }

    update$4(this);
    update$4(other);

    return (
      CesiumMath.equalsEpsilon(
        this.width,
        other.width,
        relativeEpsilon,
        absoluteEpsilon
      ) &&
      CesiumMath.equalsEpsilon(
        this.aspectRatio,
        other.aspectRatio,
        relativeEpsilon,
        absoluteEpsilon
      ) &&
      this._offCenterFrustum.equalsEpsilon(
        other._offCenterFrustum,
        relativeEpsilon,
        absoluteEpsilon
      )
    );
  };

  /**
   * The viewing frustum is defined by 6 planes.
   * Each plane is represented by a {@link Cartesian4} object, where the x, y, and z components
   * define the unit vector normal to the plane, and the w component is the distance of the
   * plane from the origin/camera position.
   *
   * @alias PerspectiveOffCenterFrustum
   * @constructor
   *
   * @param {Object} [options] An object with the following properties:
   * @param {Number} [options.left] The left clipping plane distance.
   * @param {Number} [options.right] The right clipping plane distance.
   * @param {Number} [options.top] The top clipping plane distance.
   * @param {Number} [options.bottom] The bottom clipping plane distance.
   * @param {Number} [options.near=1.0] The near clipping plane distance.
   * @param {Number} [options.far=500000000.0] The far clipping plane distance.
   *
   * @example
   * const frustum = new Cesium.PerspectiveOffCenterFrustum({
   *     left : -1.0,
   *     right : 1.0,
   *     top : 1.0,
   *     bottom : -1.0,
   *     near : 1.0,
   *     far : 100.0
   * });
   *
   * @see PerspectiveFrustum
   */
  function PerspectiveOffCenterFrustum(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    /**
     * Defines the left clipping plane.
     * @type {Number}
     * @default undefined
     */
    this.left = options.left;
    this._left = undefined;

    /**
     * Defines the right clipping plane.
     * @type {Number}
     * @default undefined
     */
    this.right = options.right;
    this._right = undefined;

    /**
     * Defines the top clipping plane.
     * @type {Number}
     * @default undefined
     */
    this.top = options.top;
    this._top = undefined;

    /**
     * Defines the bottom clipping plane.
     * @type {Number}
     * @default undefined
     */
    this.bottom = options.bottom;
    this._bottom = undefined;

    /**
     * The distance of the near plane.
     * @type {Number}
     * @default 1.0
     */
    this.near = defaultValue(options.near, 1.0);
    this._near = this.near;

    /**
     * The distance of the far plane.
     * @type {Number}
     * @default 500000000.0
     */
    this.far = defaultValue(options.far, 500000000.0);
    this._far = this.far;

    this._cullingVolume = new CullingVolume();
    this._perspectiveMatrix = new Matrix4();
    this._infinitePerspective = new Matrix4();
  }

  function update$3(frustum) {
    //>>includeStart('debug', pragmas.debug);
    if (
      !defined(frustum.right) ||
      !defined(frustum.left) ||
      !defined(frustum.top) ||
      !defined(frustum.bottom) ||
      !defined(frustum.near) ||
      !defined(frustum.far)
    ) {
      throw new DeveloperError(
        "right, left, top, bottom, near, or far parameters are not set."
      );
    }
    //>>includeEnd('debug');

    const t = frustum.top;
    const b = frustum.bottom;
    const r = frustum.right;
    const l = frustum.left;
    const n = frustum.near;
    const f = frustum.far;

    if (
      t !== frustum._top ||
      b !== frustum._bottom ||
      l !== frustum._left ||
      r !== frustum._right ||
      n !== frustum._near ||
      f !== frustum._far
    ) {
      //>>includeStart('debug', pragmas.debug);
      if (frustum.near <= 0 || frustum.near > frustum.far) {
        throw new DeveloperError(
          "near must be greater than zero and less than far."
        );
      }
      //>>includeEnd('debug');

      frustum._left = l;
      frustum._right = r;
      frustum._top = t;
      frustum._bottom = b;
      frustum._near = n;
      frustum._far = f;
      frustum._perspectiveMatrix = Matrix4.computePerspectiveOffCenter(
        l,
        r,
        b,
        t,
        n,
        f,
        frustum._perspectiveMatrix
      );
      frustum._infinitePerspective = Matrix4.computeInfinitePerspectiveOffCenter(
        l,
        r,
        b,
        t,
        n,
        frustum._infinitePerspective
      );
    }
  }

  Object.defineProperties(PerspectiveOffCenterFrustum.prototype, {
    /**
     * Gets the perspective projection matrix computed from the view frustum.
     * @memberof PerspectiveOffCenterFrustum.prototype
     * @type {Matrix4}
     * @readonly
     *
     * @see PerspectiveOffCenterFrustum#infiniteProjectionMatrix
     */
    projectionMatrix: {
      get: function () {
        update$3(this);
        return this._perspectiveMatrix;
      },
    },

    /**
     * Gets the perspective projection matrix computed from the view frustum with an infinite far plane.
     * @memberof PerspectiveOffCenterFrustum.prototype
     * @type {Matrix4}
     * @readonly
     *
     * @see PerspectiveOffCenterFrustum#projectionMatrix
     */
    infiniteProjectionMatrix: {
      get: function () {
        update$3(this);
        return this._infinitePerspective;
      },
    },
  });

  const getPlanesRight = new Cartesian3();
  const getPlanesNearCenter = new Cartesian3();
  const getPlanesFarCenter = new Cartesian3();
  const getPlanesNormal = new Cartesian3();
  /**
   * Creates a culling volume for this frustum.
   *
   * @param {Cartesian3} position The eye position.
   * @param {Cartesian3} direction The view direction.
   * @param {Cartesian3} up The up direction.
   * @returns {CullingVolume} A culling volume at the given position and orientation.
   *
   * @example
   * // Check if a bounding volume intersects the frustum.
   * const cullingVolume = frustum.computeCullingVolume(cameraPosition, cameraDirection, cameraUp);
   * const intersect = cullingVolume.computeVisibility(boundingVolume);
   */
  PerspectiveOffCenterFrustum.prototype.computeCullingVolume = function (
    position,
    direction,
    up
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(position)) {
      throw new DeveloperError("position is required.");
    }

    if (!defined(direction)) {
      throw new DeveloperError("direction is required.");
    }

    if (!defined(up)) {
      throw new DeveloperError("up is required.");
    }
    //>>includeEnd('debug');

    const planes = this._cullingVolume.planes;

    const t = this.top;
    const b = this.bottom;
    const r = this.right;
    const l = this.left;
    const n = this.near;
    const f = this.far;

    const right = Cartesian3.cross(direction, up, getPlanesRight);

    const nearCenter = getPlanesNearCenter;
    Cartesian3.multiplyByScalar(direction, n, nearCenter);
    Cartesian3.add(position, nearCenter, nearCenter);

    const farCenter = getPlanesFarCenter;
    Cartesian3.multiplyByScalar(direction, f, farCenter);
    Cartesian3.add(position, farCenter, farCenter);

    const normal = getPlanesNormal;

    //Left plane computation
    Cartesian3.multiplyByScalar(right, l, normal);
    Cartesian3.add(nearCenter, normal, normal);
    Cartesian3.subtract(normal, position, normal);
    Cartesian3.normalize(normal, normal);
    Cartesian3.cross(normal, up, normal);
    Cartesian3.normalize(normal, normal);

    let plane = planes[0];
    if (!defined(plane)) {
      plane = planes[0] = new Cartesian4();
    }
    plane.x = normal.x;
    plane.y = normal.y;
    plane.z = normal.z;
    plane.w = -Cartesian3.dot(normal, position);

    //Right plane computation
    Cartesian3.multiplyByScalar(right, r, normal);
    Cartesian3.add(nearCenter, normal, normal);
    Cartesian3.subtract(normal, position, normal);
    Cartesian3.cross(up, normal, normal);
    Cartesian3.normalize(normal, normal);

    plane = planes[1];
    if (!defined(plane)) {
      plane = planes[1] = new Cartesian4();
    }
    plane.x = normal.x;
    plane.y = normal.y;
    plane.z = normal.z;
    plane.w = -Cartesian3.dot(normal, position);

    //Bottom plane computation
    Cartesian3.multiplyByScalar(up, b, normal);
    Cartesian3.add(nearCenter, normal, normal);
    Cartesian3.subtract(normal, position, normal);
    Cartesian3.cross(right, normal, normal);
    Cartesian3.normalize(normal, normal);

    plane = planes[2];
    if (!defined(plane)) {
      plane = planes[2] = new Cartesian4();
    }
    plane.x = normal.x;
    plane.y = normal.y;
    plane.z = normal.z;
    plane.w = -Cartesian3.dot(normal, position);

    //Top plane computation
    Cartesian3.multiplyByScalar(up, t, normal);
    Cartesian3.add(nearCenter, normal, normal);
    Cartesian3.subtract(normal, position, normal);
    Cartesian3.cross(normal, right, normal);
    Cartesian3.normalize(normal, normal);

    plane = planes[3];
    if (!defined(plane)) {
      plane = planes[3] = new Cartesian4();
    }
    plane.x = normal.x;
    plane.y = normal.y;
    plane.z = normal.z;
    plane.w = -Cartesian3.dot(normal, position);

    //Near plane computation
    plane = planes[4];
    if (!defined(plane)) {
      plane = planes[4] = new Cartesian4();
    }
    plane.x = direction.x;
    plane.y = direction.y;
    plane.z = direction.z;
    plane.w = -Cartesian3.dot(direction, nearCenter);

    //Far plane computation
    Cartesian3.negate(direction, normal);

    plane = planes[5];
    if (!defined(plane)) {
      plane = planes[5] = new Cartesian4();
    }
    plane.x = normal.x;
    plane.y = normal.y;
    plane.z = normal.z;
    plane.w = -Cartesian3.dot(normal, farCenter);

    return this._cullingVolume;
  };

  /**
   * Returns the pixel's width and height in meters.
   *
   * @param {Number} drawingBufferWidth The width of the drawing buffer.
   * @param {Number} drawingBufferHeight The height of the drawing buffer.
   * @param {Number} distance The distance to the near plane in meters.
   * @param {Number} pixelRatio The scaling factor from pixel space to coordinate space.
   * @param {Cartesian2} result The object onto which to store the result.
   * @returns {Cartesian2} The modified result parameter or a new instance of {@link Cartesian2} with the pixel's width and height in the x and y properties, respectively.
   *
   * @exception {DeveloperError} drawingBufferWidth must be greater than zero.
   * @exception {DeveloperError} drawingBufferHeight must be greater than zero.
   * @exception {DeveloperError} pixelRatio must be greater than zero.
   *
   * @example
   * // Example 1
   * // Get the width and height of a pixel.
   * const pixelSize = camera.frustum.getPixelDimensions(scene.drawingBufferWidth, scene.drawingBufferHeight, 1.0, scene.pixelRatio, new Cesium.Cartesian2());
   *
   * @example
   * // Example 2
   * // Get the width and height of a pixel if the near plane was set to 'distance'.
   * // For example, get the size of a pixel of an image on a billboard.
   * const position = camera.position;
   * const direction = camera.direction;
   * const toCenter = Cesium.Cartesian3.subtract(primitive.boundingVolume.center, position, new Cesium.Cartesian3());      // vector from camera to a primitive
   * const toCenterProj = Cesium.Cartesian3.multiplyByScalar(direction, Cesium.Cartesian3.dot(direction, toCenter), new Cesium.Cartesian3()); // project vector onto camera direction vector
   * const distance = Cesium.Cartesian3.magnitude(toCenterProj);
   * const pixelSize = camera.frustum.getPixelDimensions(scene.drawingBufferWidth, scene.drawingBufferHeight, distance, scene.pixelRatio, new Cesium.Cartesian2());
   */
  PerspectiveOffCenterFrustum.prototype.getPixelDimensions = function (
    drawingBufferWidth,
    drawingBufferHeight,
    distance,
    pixelRatio,
    result
  ) {
    update$3(this);

    //>>includeStart('debug', pragmas.debug);
    if (!defined(drawingBufferWidth) || !defined(drawingBufferHeight)) {
      throw new DeveloperError(
        "Both drawingBufferWidth and drawingBufferHeight are required."
      );
    }
    if (drawingBufferWidth <= 0) {
      throw new DeveloperError("drawingBufferWidth must be greater than zero.");
    }
    if (drawingBufferHeight <= 0) {
      throw new DeveloperError("drawingBufferHeight must be greater than zero.");
    }
    if (!defined(distance)) {
      throw new DeveloperError("distance is required.");
    }
    if (!defined(pixelRatio)) {
      throw new DeveloperError("pixelRatio is required");
    }
    if (pixelRatio <= 0) {
      throw new DeveloperError("pixelRatio must be greater than zero.");
    }
    if (!defined(result)) {
      throw new DeveloperError("A result object is required.");
    }
    //>>includeEnd('debug');

    const inverseNear = 1.0 / this.near;
    let tanTheta = this.top * inverseNear;
    const pixelHeight =
      (2.0 * pixelRatio * distance * tanTheta) / drawingBufferHeight;
    tanTheta = this.right * inverseNear;
    const pixelWidth =
      (2.0 * pixelRatio * distance * tanTheta) / drawingBufferWidth;

    result.x = pixelWidth;
    result.y = pixelHeight;
    return result;
  };

  /**
   * Returns a duplicate of a PerspectiveOffCenterFrustum instance.
   *
   * @param {PerspectiveOffCenterFrustum} [result] The object onto which to store the result.
   * @returns {PerspectiveOffCenterFrustum} The modified result parameter or a new PerspectiveFrustum instance if one was not provided.
   */
  PerspectiveOffCenterFrustum.prototype.clone = function (result) {
    if (!defined(result)) {
      result = new PerspectiveOffCenterFrustum();
    }

    result.right = this.right;
    result.left = this.left;
    result.top = this.top;
    result.bottom = this.bottom;
    result.near = this.near;
    result.far = this.far;

    // force update of clone to compute matrices
    result._left = undefined;
    result._right = undefined;
    result._top = undefined;
    result._bottom = undefined;
    result._near = undefined;
    result._far = undefined;

    return result;
  };

  /**
   * Compares the provided PerspectiveOffCenterFrustum componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {PerspectiveOffCenterFrustum} [other] The right hand side PerspectiveOffCenterFrustum.
   * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
   */
  PerspectiveOffCenterFrustum.prototype.equals = function (other) {
    return (
      defined(other) &&
      other instanceof PerspectiveOffCenterFrustum &&
      this.right === other.right &&
      this.left === other.left &&
      this.top === other.top &&
      this.bottom === other.bottom &&
      this.near === other.near &&
      this.far === other.far
    );
  };

  /**
   * Compares the provided PerspectiveOffCenterFrustum componentwise and returns
   * <code>true</code> if they pass an absolute or relative tolerance test,
   * <code>false</code> otherwise.
   *
   * @param {PerspectiveOffCenterFrustum} other The right hand side PerspectiveOffCenterFrustum.
   * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
   * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
   * @returns {Boolean} <code>true</code> if this and other are within the provided epsilon, <code>false</code> otherwise.
   */
  PerspectiveOffCenterFrustum.prototype.equalsEpsilon = function (
    other,
    relativeEpsilon,
    absoluteEpsilon
  ) {
    return (
      other === this ||
      (defined(other) &&
        other instanceof PerspectiveOffCenterFrustum &&
        CesiumMath.equalsEpsilon(
          this.right,
          other.right,
          relativeEpsilon,
          absoluteEpsilon
        ) &&
        CesiumMath.equalsEpsilon(
          this.left,
          other.left,
          relativeEpsilon,
          absoluteEpsilon
        ) &&
        CesiumMath.equalsEpsilon(
          this.top,
          other.top,
          relativeEpsilon,
          absoluteEpsilon
        ) &&
        CesiumMath.equalsEpsilon(
          this.bottom,
          other.bottom,
          relativeEpsilon,
          absoluteEpsilon
        ) &&
        CesiumMath.equalsEpsilon(
          this.near,
          other.near,
          relativeEpsilon,
          absoluteEpsilon
        ) &&
        CesiumMath.equalsEpsilon(
          this.far,
          other.far,
          relativeEpsilon,
          absoluteEpsilon
        ))
    );
  };

  /**
   * The viewing frustum is defined by 6 planes.
   * Each plane is represented by a {@link Cartesian4} object, where the x, y, and z components
   * define the unit vector normal to the plane, and the w component is the distance of the
   * plane from the origin/camera position.
   *
   * @alias PerspectiveFrustum
   * @constructor
   *
   * @param {Object} [options] An object with the following properties:
   * @param {Number} [options.fov] The angle of the field of view (FOV), in radians.
   * @param {Number} [options.aspectRatio] The aspect ratio of the frustum's width to it's height.
   * @param {Number} [options.near=1.0] The distance of the near plane.
   * @param {Number} [options.far=500000000.0] The distance of the far plane.
   * @param {Number} [options.xOffset=0.0] The offset in the x direction.
   * @param {Number} [options.yOffset=0.0] The offset in the y direction.
   *
   * @example
   * const frustum = new Cesium.PerspectiveFrustum({
   *     fov : Cesium.Math.PI_OVER_THREE,
   *     aspectRatio : canvas.clientWidth / canvas.clientHeight
   *     near : 1.0,
   *     far : 1000.0
   * });
   *
   * @see PerspectiveOffCenterFrustum
   */
  function PerspectiveFrustum(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    this._offCenterFrustum = new PerspectiveOffCenterFrustum();

    /**
     * The angle of the field of view (FOV), in radians.  This angle will be used
     * as the horizontal FOV if the width is greater than the height, otherwise
     * it will be the vertical FOV.
     * @type {Number}
     * @default undefined
     */
    this.fov = options.fov;
    this._fov = undefined;
    this._fovy = undefined;

    this._sseDenominator = undefined;

    /**
     * The aspect ratio of the frustum's width to it's height.
     * @type {Number}
     * @default undefined
     */
    this.aspectRatio = options.aspectRatio;
    this._aspectRatio = undefined;

    /**
     * The distance of the near plane.
     * @type {Number}
     * @default 1.0
     */
    this.near = defaultValue(options.near, 1.0);
    this._near = this.near;

    /**
     * The distance of the far plane.
     * @type {Number}
     * @default 500000000.0
     */
    this.far = defaultValue(options.far, 500000000.0);
    this._far = this.far;

    /**
     * Offsets the frustum in the x direction.
     * @type {Number}
     * @default 0.0
     */
    this.xOffset = defaultValue(options.xOffset, 0.0);
    this._xOffset = this.xOffset;

    /**
     * Offsets the frustum in the y direction.
     * @type {Number}
     * @default 0.0
     */
    this.yOffset = defaultValue(options.yOffset, 0.0);
    this._yOffset = this.yOffset;
  }

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  PerspectiveFrustum.packedLength = 6;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {PerspectiveFrustum} 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
   */
  PerspectiveFrustum.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    array[startingIndex++] = value.fov;
    array[startingIndex++] = value.aspectRatio;
    array[startingIndex++] = value.near;
    array[startingIndex++] = value.far;
    array[startingIndex++] = value.xOffset;
    array[startingIndex] = value.yOffset;

    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 {PerspectiveFrustum} [result] The object into which to store the result.
   * @returns {PerspectiveFrustum} The modified result parameter or a new PerspectiveFrustum instance if one was not provided.
   */
  PerspectiveFrustum.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    if (!defined(result)) {
      result = new PerspectiveFrustum();
    }

    result.fov = array[startingIndex++];
    result.aspectRatio = array[startingIndex++];
    result.near = array[startingIndex++];
    result.far = array[startingIndex++];
    result.xOffset = array[startingIndex++];
    result.yOffset = array[startingIndex];

    return result;
  };

  function update$2(frustum) {
    //>>includeStart('debug', pragmas.debug);
    if (
      !defined(frustum.fov) ||
      !defined(frustum.aspectRatio) ||
      !defined(frustum.near) ||
      !defined(frustum.far)
    ) {
      throw new DeveloperError(
        "fov, aspectRatio, near, or far parameters are not set."
      );
    }
    //>>includeEnd('debug');

    const f = frustum._offCenterFrustum;

    if (
      frustum.fov !== frustum._fov ||
      frustum.aspectRatio !== frustum._aspectRatio ||
      frustum.near !== frustum._near ||
      frustum.far !== frustum._far ||
      frustum.xOffset !== frustum._xOffset ||
      frustum.yOffset !== frustum._yOffset
    ) {
      //>>includeStart('debug', pragmas.debug);
      if (frustum.fov < 0 || frustum.fov >= Math.PI) {
        throw new DeveloperError("fov must be in the range [0, PI).");
      }

      if (frustum.aspectRatio < 0) {
        throw new DeveloperError("aspectRatio must be positive.");
      }

      if (frustum.near < 0 || frustum.near > frustum.far) {
        throw new DeveloperError(
          "near must be greater than zero and less than far."
        );
      }
      //>>includeEnd('debug');

      frustum._aspectRatio = frustum.aspectRatio;
      frustum._fov = frustum.fov;
      frustum._fovy =
        frustum.aspectRatio <= 1
          ? frustum.fov
          : Math.atan(Math.tan(frustum.fov * 0.5) / frustum.aspectRatio) * 2.0;
      frustum._near = frustum.near;
      frustum._far = frustum.far;
      frustum._sseDenominator = 2.0 * Math.tan(0.5 * frustum._fovy);
      frustum._xOffset = frustum.xOffset;
      frustum._yOffset = frustum.yOffset;

      f.top = frustum.near * Math.tan(0.5 * frustum._fovy);
      f.bottom = -f.top;
      f.right = frustum.aspectRatio * f.top;
      f.left = -f.right;
      f.near = frustum.near;
      f.far = frustum.far;

      f.right += frustum.xOffset;
      f.left += frustum.xOffset;
      f.top += frustum.yOffset;
      f.bottom += frustum.yOffset;
    }
  }

  Object.defineProperties(PerspectiveFrustum.prototype, {
    /**
     * Gets the perspective projection matrix computed from the view frustum.
     * @memberof PerspectiveFrustum.prototype
     * @type {Matrix4}
     * @readonly
     *
     * @see PerspectiveFrustum#infiniteProjectionMatrix
     */
    projectionMatrix: {
      get: function () {
        update$2(this);
        return this._offCenterFrustum.projectionMatrix;
      },
    },

    /**
     * The perspective projection matrix computed from the view frustum with an infinite far plane.
     * @memberof PerspectiveFrustum.prototype
     * @type {Matrix4}
     * @readonly
     *
     * @see PerspectiveFrustum#projectionMatrix
     */
    infiniteProjectionMatrix: {
      get: function () {
        update$2(this);
        return this._offCenterFrustum.infiniteProjectionMatrix;
      },
    },

    /**
     * Gets the angle of the vertical field of view, in radians.
     * @memberof PerspectiveFrustum.prototype
     * @type {Number}
     * @readonly
     * @default undefined
     */
    fovy: {
      get: function () {
        update$2(this);
        return this._fovy;
      },
    },

    /**
     * @readonly
     * @private
     */
    sseDenominator: {
      get: function () {
        update$2(this);
        return this._sseDenominator;
      },
    },
  });

  /**
   * Creates a culling volume for this frustum.
   *
   * @param {Cartesian3} position The eye position.
   * @param {Cartesian3} direction The view direction.
   * @param {Cartesian3} up The up direction.
   * @returns {CullingVolume} A culling volume at the given position and orientation.
   *
   * @example
   * // Check if a bounding volume intersects the frustum.
   * const cullingVolume = frustum.computeCullingVolume(cameraPosition, cameraDirection, cameraUp);
   * const intersect = cullingVolume.computeVisibility(boundingVolume);
   */
  PerspectiveFrustum.prototype.computeCullingVolume = function (
    position,
    direction,
    up
  ) {
    update$2(this);
    return this._offCenterFrustum.computeCullingVolume(position, direction, up);
  };

  /**
   * Returns the pixel's width and height in meters.
   *
   * @param {Number} drawingBufferWidth The width of the drawing buffer.
   * @param {Number} drawingBufferHeight The height of the drawing buffer.
   * @param {Number} distance The distance to the near plane in meters.
   * @param {Number} pixelRatio The scaling factor from pixel space to coordinate space.
   * @param {Cartesian2} result The object onto which to store the result.
   * @returns {Cartesian2} The modified result parameter or a new instance of {@link Cartesian2} with the pixel's width and height in the x and y properties, respectively.
   *
   * @exception {DeveloperError} drawingBufferWidth must be greater than zero.
   * @exception {DeveloperError} drawingBufferHeight must be greater than zero.
   * @exception {DeveloperError} pixelRatio must be greater than zero.
   *
   * @example
   * // Example 1
   * // Get the width and height of a pixel.
   * const pixelSize = camera.frustum.getPixelDimensions(scene.drawingBufferWidth, scene.drawingBufferHeight, 1.0, scene.pixelRatio, new Cesium.Cartesian2());
   *
   * @example
   * // Example 2
   * // Get the width and height of a pixel if the near plane was set to 'distance'.
   * // For example, get the size of a pixel of an image on a billboard.
   * const position = camera.position;
   * const direction = camera.direction;
   * const toCenter = Cesium.Cartesian3.subtract(primitive.boundingVolume.center, position, new Cesium.Cartesian3());      // vector from camera to a primitive
   * const toCenterProj = Cesium.Cartesian3.multiplyByScalar(direction, Cesium.Cartesian3.dot(direction, toCenter), new Cesium.Cartesian3()); // project vector onto camera direction vector
   * const distance = Cesium.Cartesian3.magnitude(toCenterProj);
   * const pixelSize = camera.frustum.getPixelDimensions(scene.drawingBufferWidth, scene.drawingBufferHeight, distance, scene.pixelRatio, new Cesium.Cartesian2());
   */
  PerspectiveFrustum.prototype.getPixelDimensions = function (
    drawingBufferWidth,
    drawingBufferHeight,
    distance,
    pixelRatio,
    result
  ) {
    update$2(this);
    return this._offCenterFrustum.getPixelDimensions(
      drawingBufferWidth,
      drawingBufferHeight,
      distance,
      pixelRatio,
      result
    );
  };

  /**
   * Returns a duplicate of a PerspectiveFrustum instance.
   *
   * @param {PerspectiveFrustum} [result] The object onto which to store the result.
   * @returns {PerspectiveFrustum} The modified result parameter or a new PerspectiveFrustum instance if one was not provided.
   */
  PerspectiveFrustum.prototype.clone = function (result) {
    if (!defined(result)) {
      result = new PerspectiveFrustum();
    }

    result.aspectRatio = this.aspectRatio;
    result.fov = this.fov;
    result.near = this.near;
    result.far = this.far;

    // force update of clone to compute matrices
    result._aspectRatio = undefined;
    result._fov = undefined;
    result._near = undefined;
    result._far = undefined;

    this._offCenterFrustum.clone(result._offCenterFrustum);

    return result;
  };

  /**
   * Compares the provided PerspectiveFrustum componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {PerspectiveFrustum} [other] The right hand side PerspectiveFrustum.
   * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
   */
  PerspectiveFrustum.prototype.equals = function (other) {
    if (!defined(other) || !(other instanceof PerspectiveFrustum)) {
      return false;
    }

    update$2(this);
    update$2(other);

    return (
      this.fov === other.fov &&
      this.aspectRatio === other.aspectRatio &&
      this._offCenterFrustum.equals(other._offCenterFrustum)
    );
  };

  /**
   * Compares the provided PerspectiveFrustum componentwise and returns
   * <code>true</code> if they pass an absolute or relative tolerance test,
   * <code>false</code> otherwise.
   *
   * @param {PerspectiveFrustum} other The right hand side PerspectiveFrustum.
   * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
   * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
   * @returns {Boolean} <code>true</code> if this and other are within the provided epsilon, <code>false</code> otherwise.
   */
  PerspectiveFrustum.prototype.equalsEpsilon = function (
    other,
    relativeEpsilon,
    absoluteEpsilon
  ) {
    if (!defined(other) || !(other instanceof PerspectiveFrustum)) {
      return false;
    }

    update$2(this);
    update$2(other);

    return (
      CesiumMath.equalsEpsilon(
        this.fov,
        other.fov,
        relativeEpsilon,
        absoluteEpsilon
      ) &&
      CesiumMath.equalsEpsilon(
        this.aspectRatio,
        other.aspectRatio,
        relativeEpsilon,
        absoluteEpsilon
      ) &&
      this._offCenterFrustum.equalsEpsilon(
        other._offCenterFrustum,
        relativeEpsilon,
        absoluteEpsilon
      )
    );
  };

  const PERSPECTIVE$1 = 0;
  const ORTHOGRAPHIC$1 = 1;

  /**
   * Describes a frustum at the given the origin and orientation.
   *
   * @alias FrustumGeometry
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {PerspectiveFrustum|OrthographicFrustum} options.frustum The frustum.
   * @param {Cartesian3} options.origin The origin of the frustum.
   * @param {Quaternion} options.orientation The orientation of the frustum.
   * @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
   */
  function FrustumGeometry(options) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options", options);
    Check.typeOf.object("options.frustum", options.frustum);
    Check.typeOf.object("options.origin", options.origin);
    Check.typeOf.object("options.orientation", options.orientation);
    //>>includeEnd('debug');

    const frustum = options.frustum;
    const orientation = options.orientation;
    const origin = options.origin;
    const vertexFormat = defaultValue(options.vertexFormat, VertexFormat.DEFAULT);

    // This is private because it is used by DebugCameraPrimitive to draw a multi-frustum by
    // creating multiple FrustumGeometrys. This way the near plane of one frustum doesn't overlap
    // the far plane of another.
    const drawNearPlane = defaultValue(options._drawNearPlane, true);

    let frustumType;
    let frustumPackedLength;
    if (frustum instanceof PerspectiveFrustum) {
      frustumType = PERSPECTIVE$1;
      frustumPackedLength = PerspectiveFrustum.packedLength;
    } else if (frustum instanceof OrthographicFrustum) {
      frustumType = ORTHOGRAPHIC$1;
      frustumPackedLength = OrthographicFrustum.packedLength;
    }

    this._frustumType = frustumType;
    this._frustum = frustum.clone();
    this._origin = Cartesian3.clone(origin);
    this._orientation = Quaternion.clone(orientation);
    this._drawNearPlane = drawNearPlane;
    this._vertexFormat = vertexFormat;
    this._workerName = "createFrustumGeometry";

    /**
     * The number of elements used to pack the object into an array.
     * @type {Number}
     */
    this.packedLength =
      2 +
      frustumPackedLength +
      Cartesian3.packedLength +
      Quaternion.packedLength +
      VertexFormat.packedLength;
  }

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {FrustumGeometry} 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
   */
  FrustumGeometry.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    const frustumType = value._frustumType;
    const frustum = value._frustum;

    array[startingIndex++] = frustumType;

    if (frustumType === PERSPECTIVE$1) {
      PerspectiveFrustum.pack(frustum, array, startingIndex);
      startingIndex += PerspectiveFrustum.packedLength;
    } else {
      OrthographicFrustum.pack(frustum, array, startingIndex);
      startingIndex += OrthographicFrustum.packedLength;
    }

    Cartesian3.pack(value._origin, array, startingIndex);
    startingIndex += Cartesian3.packedLength;
    Quaternion.pack(value._orientation, array, startingIndex);
    startingIndex += Quaternion.packedLength;
    VertexFormat.pack(value._vertexFormat, array, startingIndex);
    startingIndex += VertexFormat.packedLength;
    array[startingIndex] = value._drawNearPlane ? 1.0 : 0.0;

    return array;
  };

  const scratchPackPerspective$1 = new PerspectiveFrustum();
  const scratchPackOrthographic$1 = new OrthographicFrustum();
  const scratchPackQuaternion$1 = new Quaternion();
  const scratchPackorigin$1 = new Cartesian3();
  const scratchVertexFormat$6 = new VertexFormat();

  /**
   * 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 {FrustumGeometry} [result] The object into which to store the result.
   */
  FrustumGeometry.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    const frustumType = array[startingIndex++];

    let frustum;
    if (frustumType === PERSPECTIVE$1) {
      frustum = PerspectiveFrustum.unpack(
        array,
        startingIndex,
        scratchPackPerspective$1
      );
      startingIndex += PerspectiveFrustum.packedLength;
    } else {
      frustum = OrthographicFrustum.unpack(
        array,
        startingIndex,
        scratchPackOrthographic$1
      );
      startingIndex += OrthographicFrustum.packedLength;
    }

    const origin = Cartesian3.unpack(array, startingIndex, scratchPackorigin$1);
    startingIndex += Cartesian3.packedLength;
    const orientation = Quaternion.unpack(
      array,
      startingIndex,
      scratchPackQuaternion$1
    );
    startingIndex += Quaternion.packedLength;
    const vertexFormat = VertexFormat.unpack(
      array,
      startingIndex,
      scratchVertexFormat$6
    );
    startingIndex += VertexFormat.packedLength;
    const drawNearPlane = array[startingIndex] === 1.0;

    if (!defined(result)) {
      return new FrustumGeometry({
        frustum: frustum,
        origin: origin,
        orientation: orientation,
        vertexFormat: vertexFormat,
        _drawNearPlane: drawNearPlane,
      });
    }

    const frustumResult =
      frustumType === result._frustumType ? result._frustum : undefined;
    result._frustum = frustum.clone(frustumResult);

    result._frustumType = frustumType;
    result._origin = Cartesian3.clone(origin, result._origin);
    result._orientation = Quaternion.clone(orientation, result._orientation);
    result._vertexFormat = VertexFormat.clone(vertexFormat, result._vertexFormat);
    result._drawNearPlane = drawNearPlane;

    return result;
  };

  function getAttributes(
    offset,
    normals,
    tangents,
    bitangents,
    st,
    normal,
    tangent,
    bitangent
  ) {
    const stOffset = (offset / 3) * 2;

    for (let i = 0; i < 4; ++i) {
      if (defined(normals)) {
        normals[offset] = normal.x;
        normals[offset + 1] = normal.y;
        normals[offset + 2] = normal.z;
      }
      if (defined(tangents)) {
        tangents[offset] = tangent.x;
        tangents[offset + 1] = tangent.y;
        tangents[offset + 2] = tangent.z;
      }
      if (defined(bitangents)) {
        bitangents[offset] = bitangent.x;
        bitangents[offset + 1] = bitangent.y;
        bitangents[offset + 2] = bitangent.z;
      }
      offset += 3;
    }

    st[stOffset] = 0.0;
    st[stOffset + 1] = 0.0;
    st[stOffset + 2] = 1.0;
    st[stOffset + 3] = 0.0;
    st[stOffset + 4] = 1.0;
    st[stOffset + 5] = 1.0;
    st[stOffset + 6] = 0.0;
    st[stOffset + 7] = 1.0;
  }

  const scratchRotationMatrix = new Matrix3();
  const scratchViewMatrix = new Matrix4();
  const scratchInverseMatrix = new Matrix4();

  const scratchXDirection = new Cartesian3();
  const scratchYDirection = new Cartesian3();
  const scratchZDirection = new Cartesian3();
  const scratchNegativeX = new Cartesian3();
  const scratchNegativeY = new Cartesian3();
  const scratchNegativeZ = new Cartesian3();

  const frustumSplits = new Array(3);

  const frustumCornersNDC$1 = new Array(4);
  frustumCornersNDC$1[0] = new Cartesian4(-1.0, -1.0, 1.0, 1.0);
  frustumCornersNDC$1[1] = new Cartesian4(1.0, -1.0, 1.0, 1.0);
  frustumCornersNDC$1[2] = new Cartesian4(1.0, 1.0, 1.0, 1.0);
  frustumCornersNDC$1[3] = new Cartesian4(-1.0, 1.0, 1.0, 1.0);

  const scratchFrustumCorners$1 = new Array(4);
  for (let i = 0; i < 4; ++i) {
    scratchFrustumCorners$1[i] = new Cartesian4();
  }

  FrustumGeometry._computeNearFarPlanes = function (
    origin,
    orientation,
    frustumType,
    frustum,
    positions,
    xDirection,
    yDirection,
    zDirection
  ) {
    const rotationMatrix = Matrix3.fromQuaternion(
      orientation,
      scratchRotationMatrix
    );
    let x = defaultValue(xDirection, scratchXDirection);
    let y = defaultValue(yDirection, scratchYDirection);
    let z = defaultValue(zDirection, scratchZDirection);

    x = Matrix3.getColumn(rotationMatrix, 0, x);
    y = Matrix3.getColumn(rotationMatrix, 1, y);
    z = Matrix3.getColumn(rotationMatrix, 2, z);

    Cartesian3.normalize(x, x);
    Cartesian3.normalize(y, y);
    Cartesian3.normalize(z, z);

    Cartesian3.negate(x, x);

    const view = Matrix4.computeView(origin, z, y, x, scratchViewMatrix);

    let inverseView;
    let inverseViewProjection;
    if (frustumType === PERSPECTIVE$1) {
      const projection = frustum.projectionMatrix;
      const viewProjection = Matrix4.multiply(
        projection,
        view,
        scratchInverseMatrix
      );
      inverseViewProjection = Matrix4.inverse(
        viewProjection,
        scratchInverseMatrix
      );
    } else {
      inverseView = Matrix4.inverseTransformation(view, scratchInverseMatrix);
    }

    if (defined(inverseViewProjection)) {
      frustumSplits[0] = frustum.near;
      frustumSplits[1] = frustum.far;
    } else {
      frustumSplits[0] = 0.0;
      frustumSplits[1] = frustum.near;
      frustumSplits[2] = frustum.far;
    }

    for (let i = 0; i < 2; ++i) {
      for (let j = 0; j < 4; ++j) {
        let corner = Cartesian4.clone(
          frustumCornersNDC$1[j],
          scratchFrustumCorners$1[j]
        );

        if (!defined(inverseViewProjection)) {
          if (defined(frustum._offCenterFrustum)) {
            frustum = frustum._offCenterFrustum;
          }

          const near = frustumSplits[i];
          const far = frustumSplits[i + 1];

          corner.x =
            (corner.x * (frustum.right - frustum.left) +
              frustum.left +
              frustum.right) *
            0.5;
          corner.y =
            (corner.y * (frustum.top - frustum.bottom) +
              frustum.bottom +
              frustum.top) *
            0.5;
          corner.z = (corner.z * (near - far) - near - far) * 0.5;
          corner.w = 1.0;

          Matrix4.multiplyByVector(inverseView, corner, corner);
        } else {
          corner = Matrix4.multiplyByVector(
            inverseViewProjection,
            corner,
            corner
          );

          // Reverse perspective divide
          const w = 1.0 / corner.w;
          Cartesian3.multiplyByScalar(corner, w, corner);

          Cartesian3.subtract(corner, origin, corner);
          Cartesian3.normalize(corner, corner);

          const fac = Cartesian3.dot(z, corner);
          Cartesian3.multiplyByScalar(corner, frustumSplits[i] / fac, corner);
          Cartesian3.add(corner, origin, corner);
        }

        positions[12 * i + j * 3] = corner.x;
        positions[12 * i + j * 3 + 1] = corner.y;
        positions[12 * i + j * 3 + 2] = corner.z;
      }
    }
  };

  /**
   * Computes the geometric representation of a frustum, including its vertices, indices, and a bounding sphere.
   *
   * @param {FrustumGeometry} frustumGeometry A description of the frustum.
   * @returns {Geometry|undefined} The computed vertices and indices.
   */
  FrustumGeometry.createGeometry = function (frustumGeometry) {
    const frustumType = frustumGeometry._frustumType;
    const frustum = frustumGeometry._frustum;
    const origin = frustumGeometry._origin;
    const orientation = frustumGeometry._orientation;
    const drawNearPlane = frustumGeometry._drawNearPlane;
    const vertexFormat = frustumGeometry._vertexFormat;

    const numberOfPlanes = drawNearPlane ? 6 : 5;
    let positions = new Float64Array(3 * 4 * 6);
    FrustumGeometry._computeNearFarPlanes(
      origin,
      orientation,
      frustumType,
      frustum,
      positions
    );

    // -x plane
    let offset = 3 * 4 * 2;
    positions[offset] = positions[3 * 4];
    positions[offset + 1] = positions[3 * 4 + 1];
    positions[offset + 2] = positions[3 * 4 + 2];
    positions[offset + 3] = positions[0];
    positions[offset + 4] = positions[1];
    positions[offset + 5] = positions[2];
    positions[offset + 6] = positions[3 * 3];
    positions[offset + 7] = positions[3 * 3 + 1];
    positions[offset + 8] = positions[3 * 3 + 2];
    positions[offset + 9] = positions[3 * 7];
    positions[offset + 10] = positions[3 * 7 + 1];
    positions[offset + 11] = positions[3 * 7 + 2];

    // -y plane
    offset += 3 * 4;
    positions[offset] = positions[3 * 5];
    positions[offset + 1] = positions[3 * 5 + 1];
    positions[offset + 2] = positions[3 * 5 + 2];
    positions[offset + 3] = positions[3];
    positions[offset + 4] = positions[3 + 1];
    positions[offset + 5] = positions[3 + 2];
    positions[offset + 6] = positions[0];
    positions[offset + 7] = positions[1];
    positions[offset + 8] = positions[2];
    positions[offset + 9] = positions[3 * 4];
    positions[offset + 10] = positions[3 * 4 + 1];
    positions[offset + 11] = positions[3 * 4 + 2];

    // +x plane
    offset += 3 * 4;
    positions[offset] = positions[3];
    positions[offset + 1] = positions[3 + 1];
    positions[offset + 2] = positions[3 + 2];
    positions[offset + 3] = positions[3 * 5];
    positions[offset + 4] = positions[3 * 5 + 1];
    positions[offset + 5] = positions[3 * 5 + 2];
    positions[offset + 6] = positions[3 * 6];
    positions[offset + 7] = positions[3 * 6 + 1];
    positions[offset + 8] = positions[3 * 6 + 2];
    positions[offset + 9] = positions[3 * 2];
    positions[offset + 10] = positions[3 * 2 + 1];
    positions[offset + 11] = positions[3 * 2 + 2];

    // +y plane
    offset += 3 * 4;
    positions[offset] = positions[3 * 2];
    positions[offset + 1] = positions[3 * 2 + 1];
    positions[offset + 2] = positions[3 * 2 + 2];
    positions[offset + 3] = positions[3 * 6];
    positions[offset + 4] = positions[3 * 6 + 1];
    positions[offset + 5] = positions[3 * 6 + 2];
    positions[offset + 6] = positions[3 * 7];
    positions[offset + 7] = positions[3 * 7 + 1];
    positions[offset + 8] = positions[3 * 7 + 2];
    positions[offset + 9] = positions[3 * 3];
    positions[offset + 10] = positions[3 * 3 + 1];
    positions[offset + 11] = positions[3 * 3 + 2];

    if (!drawNearPlane) {
      positions = positions.subarray(3 * 4);
    }

    const attributes = new GeometryAttributes({
      position: new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.DOUBLE,
        componentsPerAttribute: 3,
        values: positions,
      }),
    });

    if (
      defined(vertexFormat.normal) ||
      defined(vertexFormat.tangent) ||
      defined(vertexFormat.bitangent) ||
      defined(vertexFormat.st)
    ) {
      const normals = defined(vertexFormat.normal)
        ? new Float32Array(3 * 4 * numberOfPlanes)
        : undefined;
      const tangents = defined(vertexFormat.tangent)
        ? new Float32Array(3 * 4 * numberOfPlanes)
        : undefined;
      const bitangents = defined(vertexFormat.bitangent)
        ? new Float32Array(3 * 4 * numberOfPlanes)
        : undefined;
      const st = defined(vertexFormat.st)
        ? new Float32Array(2 * 4 * numberOfPlanes)
        : undefined;

      const x = scratchXDirection;
      const y = scratchYDirection;
      const z = scratchZDirection;

      const negativeX = Cartesian3.negate(x, scratchNegativeX);
      const negativeY = Cartesian3.negate(y, scratchNegativeY);
      const negativeZ = Cartesian3.negate(z, scratchNegativeZ);

      offset = 0;
      if (drawNearPlane) {
        getAttributes(offset, normals, tangents, bitangents, st, negativeZ, x, y); // near
        offset += 3 * 4;
      }
      getAttributes(offset, normals, tangents, bitangents, st, z, negativeX, y); // far
      offset += 3 * 4;
      getAttributes(
        offset,
        normals,
        tangents,
        bitangents,
        st,
        negativeX,
        negativeZ,
        y
      ); // -x
      offset += 3 * 4;
      getAttributes(
        offset,
        normals,
        tangents,
        bitangents,
        st,
        negativeY,
        negativeZ,
        negativeX
      ); // -y
      offset += 3 * 4;
      getAttributes(offset, normals, tangents, bitangents, st, x, z, y); // +x
      offset += 3 * 4;
      getAttributes(offset, normals, tangents, bitangents, st, y, z, negativeX); // +y

      if (defined(normals)) {
        attributes.normal = new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 3,
          values: normals,
        });
      }
      if (defined(tangents)) {
        attributes.tangent = new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 3,
          values: tangents,
        });
      }
      if (defined(bitangents)) {
        attributes.bitangent = new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 3,
          values: bitangents,
        });
      }
      if (defined(st)) {
        attributes.st = new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 2,
          values: st,
        });
      }
    }

    const indices = new Uint16Array(6 * numberOfPlanes);
    for (let i = 0; i < numberOfPlanes; ++i) {
      const indexOffset = i * 6;
      const index = i * 4;

      indices[indexOffset] = index;
      indices[indexOffset + 1] = index + 1;
      indices[indexOffset + 2] = index + 2;
      indices[indexOffset + 3] = index;
      indices[indexOffset + 4] = index + 2;
      indices[indexOffset + 5] = index + 3;
    }

    return new Geometry({
      attributes: attributes,
      indices: indices,
      primitiveType: PrimitiveType$1.TRIANGLES,
      boundingSphere: BoundingSphere.fromVertices(positions),
    });
  };

  const PERSPECTIVE = 0;
  const ORTHOGRAPHIC = 1;

  /**
   * A description of the outline of a frustum with the given the origin and orientation.
   *
   * @alias FrustumOutlineGeometry
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {PerspectiveFrustum|OrthographicFrustum} options.frustum The frustum.
   * @param {Cartesian3} options.origin The origin of the frustum.
   * @param {Quaternion} options.orientation The orientation of the frustum.
   */
  function FrustumOutlineGeometry(options) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options", options);
    Check.typeOf.object("options.frustum", options.frustum);
    Check.typeOf.object("options.origin", options.origin);
    Check.typeOf.object("options.orientation", options.orientation);
    //>>includeEnd('debug');

    const frustum = options.frustum;
    const orientation = options.orientation;
    const origin = options.origin;

    // This is private because it is used by DebugCameraPrimitive to draw a multi-frustum by
    // creating multiple FrustumOutlineGeometrys. This way the near plane of one frustum doesn't overlap
    // the far plane of another.
    const drawNearPlane = defaultValue(options._drawNearPlane, true);

    let frustumType;
    let frustumPackedLength;
    if (frustum instanceof PerspectiveFrustum) {
      frustumType = PERSPECTIVE;
      frustumPackedLength = PerspectiveFrustum.packedLength;
    } else if (frustum instanceof OrthographicFrustum) {
      frustumType = ORTHOGRAPHIC;
      frustumPackedLength = OrthographicFrustum.packedLength;
    }

    this._frustumType = frustumType;
    this._frustum = frustum.clone();
    this._origin = Cartesian3.clone(origin);
    this._orientation = Quaternion.clone(orientation);
    this._drawNearPlane = drawNearPlane;
    this._workerName = "createFrustumOutlineGeometry";

    /**
     * The number of elements used to pack the object into an array.
     * @type {Number}
     */
    this.packedLength =
      2 + frustumPackedLength + Cartesian3.packedLength + Quaternion.packedLength;
  }

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {FrustumOutlineGeometry} 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
   */
  FrustumOutlineGeometry.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    const frustumType = value._frustumType;
    const frustum = value._frustum;

    array[startingIndex++] = frustumType;

    if (frustumType === PERSPECTIVE) {
      PerspectiveFrustum.pack(frustum, array, startingIndex);
      startingIndex += PerspectiveFrustum.packedLength;
    } else {
      OrthographicFrustum.pack(frustum, array, startingIndex);
      startingIndex += OrthographicFrustum.packedLength;
    }

    Cartesian3.pack(value._origin, array, startingIndex);
    startingIndex += Cartesian3.packedLength;
    Quaternion.pack(value._orientation, array, startingIndex);
    startingIndex += Quaternion.packedLength;
    array[startingIndex] = value._drawNearPlane ? 1.0 : 0.0;

    return array;
  };

  const scratchPackPerspective = new PerspectiveFrustum();
  const scratchPackOrthographic = new OrthographicFrustum();
  const scratchPackQuaternion = new Quaternion();
  const scratchPackorigin = new Cartesian3();

  /**
   * 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 {FrustumOutlineGeometry} [result] The object into which to store the result.
   */
  FrustumOutlineGeometry.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    const frustumType = array[startingIndex++];

    let frustum;
    if (frustumType === PERSPECTIVE) {
      frustum = PerspectiveFrustum.unpack(
        array,
        startingIndex,
        scratchPackPerspective
      );
      startingIndex += PerspectiveFrustum.packedLength;
    } else {
      frustum = OrthographicFrustum.unpack(
        array,
        startingIndex,
        scratchPackOrthographic
      );
      startingIndex += OrthographicFrustum.packedLength;
    }

    const origin = Cartesian3.unpack(array, startingIndex, scratchPackorigin);
    startingIndex += Cartesian3.packedLength;
    const orientation = Quaternion.unpack(
      array,
      startingIndex,
      scratchPackQuaternion
    );
    startingIndex += Quaternion.packedLength;
    const drawNearPlane = array[startingIndex] === 1.0;

    if (!defined(result)) {
      return new FrustumOutlineGeometry({
        frustum: frustum,
        origin: origin,
        orientation: orientation,
        _drawNearPlane: drawNearPlane,
      });
    }

    const frustumResult =
      frustumType === result._frustumType ? result._frustum : undefined;
    result._frustum = frustum.clone(frustumResult);

    result._frustumType = frustumType;
    result._origin = Cartesian3.clone(origin, result._origin);
    result._orientation = Quaternion.clone(orientation, result._orientation);
    result._drawNearPlane = drawNearPlane;

    return result;
  };

  /**
   * Computes the geometric representation of a frustum outline, including its vertices, indices, and a bounding sphere.
   *
   * @param {FrustumOutlineGeometry} frustumGeometry A description of the frustum.
   * @returns {Geometry|undefined} The computed vertices and indices.
   */
  FrustumOutlineGeometry.createGeometry = function (frustumGeometry) {
    const frustumType = frustumGeometry._frustumType;
    const frustum = frustumGeometry._frustum;
    const origin = frustumGeometry._origin;
    const orientation = frustumGeometry._orientation;
    const drawNearPlane = frustumGeometry._drawNearPlane;

    const positions = new Float64Array(3 * 4 * 2);
    FrustumGeometry._computeNearFarPlanes(
      origin,
      orientation,
      frustumType,
      frustum,
      positions
    );

    const attributes = new GeometryAttributes({
      position: new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.DOUBLE,
        componentsPerAttribute: 3,
        values: positions,
      }),
    });

    let offset;
    let index;

    const numberOfPlanes = drawNearPlane ? 2 : 1;
    const indices = new Uint16Array(8 * (numberOfPlanes + 1));

    // Build the near/far planes
    let i = drawNearPlane ? 0 : 1;
    for (; i < 2; ++i) {
      offset = drawNearPlane ? i * 8 : 0;
      index = i * 4;

      indices[offset] = index;
      indices[offset + 1] = index + 1;
      indices[offset + 2] = index + 1;
      indices[offset + 3] = index + 2;
      indices[offset + 4] = index + 2;
      indices[offset + 5] = index + 3;
      indices[offset + 6] = index + 3;
      indices[offset + 7] = index;
    }

    // Build the sides of the frustums
    for (i = 0; i < 2; ++i) {
      offset = (numberOfPlanes + i) * 8;
      index = i * 4;

      indices[offset] = index;
      indices[offset + 1] = index + 4;
      indices[offset + 2] = index + 1;
      indices[offset + 3] = index + 5;
      indices[offset + 4] = index + 2;
      indices[offset + 5] = index + 6;
      indices[offset + 6] = index + 3;
      indices[offset + 7] = index + 7;
    }

    return new Geometry({
      attributes: attributes,
      indices: indices,
      primitiveType: PrimitiveType$1.LINES,
      boundingSphere: BoundingSphere.fromVertices(positions),
    });
  };

  /**
   * The type of geocoding to be performed by a {@link GeocoderService}.
   * @enum {Number}
   * @see Geocoder
   */
  const GeocodeType = {
    /**
     * Perform a search where the input is considered complete.
     *
     * @type {Number}
     * @constant
     */
    SEARCH: 0,

    /**
     * Perform an auto-complete using partial input, typically
     * reserved for providing possible results as a user is typing.
     *
     * @type {Number}
     * @constant
     */
    AUTOCOMPLETE: 1,
  };
  var GeocodeType$1 = Object.freeze(GeocodeType);

  /**
   * @typedef {Object} GeocoderService.Result
   * @property {String} displayName The display name for a location
   * @property {Rectangle|Cartesian3} destination The bounding box for a location
   */

  /**
   * Provides geocoding through an external service. This type describes an interface and
   * is not intended to be used.
   * @alias GeocoderService
   * @constructor
   *
   * @see BingMapsGeocoderService
   * @see PeliasGeocoderService
   * @see OpenCageGeocoderService
   */
  function GeocoderService() {}

  /**
   * @function
   *
   * @param {String} query The query to be sent to the geocoder service
   * @param {GeocodeType} [type=GeocodeType.SEARCH] The type of geocode to perform.
   * @returns {Promise<GeocoderService.Result[]>}
   */
  GeocoderService.prototype.geocode = DeveloperError.throwInstantiationError;

  /**
   * Base class for all geometry creation utility classes that can be passed to {@link GeometryInstance}
   * for asynchronous geometry creation.
   *
   * @constructor
   * @class
   * @abstract
   */
  function GeometryFactory() {
    DeveloperError.throwInstantiationError();
  }

  /**
   * Returns a geometry.
   *
   * @param {GeometryFactory} geometryFactory A description of the circle.
   * @returns {Geometry|undefined} The computed vertices and indices.
   */
  GeometryFactory.createGeometry = function (geometryFactory) {
    DeveloperError.throwInstantiationError();
  };

  /**
   * Values and type information for per-instance geometry attributes.
   *
   * @alias GeometryInstanceAttribute
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {ComponentDatatype} options.componentDatatype The datatype of each component in the attribute, e.g., individual elements in values.
   * @param {Number} options.componentsPerAttribute A number between 1 and 4 that defines the number of components in an attributes.
   * @param {Boolean} [options.normalize=false] When <code>true</code> and <code>componentDatatype</code> is an integer format, indicate that the components should be mapped to the range [0, 1] (unsigned) or [-1, 1] (signed) when they are accessed as floating-point for rendering.
   * @param {Number[]} options.value The value for the attribute.
   *
   * @exception {DeveloperError} options.componentsPerAttribute must be between 1 and 4.
   *
   *
   * @example
   * const instance = new Cesium.GeometryInstance({
   *   geometry : Cesium.BoxGeometry.fromDimensions({
   *     dimensions : new Cesium.Cartesian3(1000000.0, 1000000.0, 500000.0)
   *   }),
   *   modelMatrix : Cesium.Matrix4.multiplyByTranslation(Cesium.Transforms.eastNorthUpToFixedFrame(
   *     Cesium.Cartesian3.fromDegrees(0.0, 0.0)), new Cesium.Cartesian3(0.0, 0.0, 1000000.0), new Cesium.Matrix4()),
   *   id : 'box',
   *   attributes : {
   *     color : new Cesium.GeometryInstanceAttribute({
   *       componentDatatype : Cesium.ComponentDatatype.UNSIGNED_BYTE,
   *       componentsPerAttribute : 4,
   *       normalize : true,
   *       value : [255, 255, 0, 255]
   *     })
   *   }
   * });
   *
   * @see ColorGeometryInstanceAttribute
   * @see ShowGeometryInstanceAttribute
   * @see DistanceDisplayConditionGeometryInstanceAttribute
   */
  function GeometryInstanceAttribute(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    if (!defined(options.componentDatatype)) {
      throw new DeveloperError("options.componentDatatype is required.");
    }
    if (!defined(options.componentsPerAttribute)) {
      throw new DeveloperError("options.componentsPerAttribute is required.");
    }
    if (
      options.componentsPerAttribute < 1 ||
      options.componentsPerAttribute > 4
    ) {
      throw new DeveloperError(
        "options.componentsPerAttribute must be between 1 and 4."
      );
    }
    if (!defined(options.value)) {
      throw new DeveloperError("options.value is required.");
    }
    //>>includeEnd('debug');

    /**
     * The datatype of each component in the attribute, e.g., individual elements in
     * {@link GeometryInstanceAttribute#value}.
     *
     * @type ComponentDatatype
     *
     * @default undefined
     */
    this.componentDatatype = options.componentDatatype;

    /**
     * A number between 1 and 4 that defines the number of components in an attributes.
     * For example, a position attribute with x, y, and z components would have 3 as
     * shown in the code example.
     *
     * @type Number
     *
     * @default undefined
     *
     * @example
     * show : new Cesium.GeometryInstanceAttribute({
     *   componentDatatype : Cesium.ComponentDatatype.UNSIGNED_BYTE,
     *   componentsPerAttribute : 1,
     *   normalize : true,
     *   value : [1.0]
     * })
     */
    this.componentsPerAttribute = options.componentsPerAttribute;

    /**
     * When <code>true</code> and <code>componentDatatype</code> is an integer format,
     * indicate that the components should be mapped to the range [0, 1] (unsigned)
     * or [-1, 1] (signed) when they are accessed as floating-point for rendering.
     * <p>
     * This is commonly used when storing colors using {@link ComponentDatatype.UNSIGNED_BYTE}.
     * </p>
     *
     * @type Boolean
     *
     * @default false
     *
     * @example
     * attribute.componentDatatype = Cesium.ComponentDatatype.UNSIGNED_BYTE;
     * attribute.componentsPerAttribute = 4;
     * attribute.normalize = true;
     * attribute.value = [
     *   Cesium.Color.floatToByte(color.red),
     *   Cesium.Color.floatToByte(color.green),
     *   Cesium.Color.floatToByte(color.blue),
     *   Cesium.Color.floatToByte(color.alpha)
     * ];
     */
    this.normalize = defaultValue(options.normalize, false);

    /**
     * The values for the attributes stored in a typed array.  In the code example,
     * every three elements in <code>values</code> defines one attributes since
     * <code>componentsPerAttribute</code> is 3.
     *
     * @type {Number[]}
     *
     * @default undefined
     *
     * @example
     * show : new Cesium.GeometryInstanceAttribute({
     *   componentDatatype : Cesium.ComponentDatatype.UNSIGNED_BYTE,
     *   componentsPerAttribute : 1,
     *   normalize : true,
     *   value : [1.0]
     * })
     */
    this.value = options.value;
  }

  /* This file is automatically rebuilt by the Cesium build process. */

  function _mergeNamespaces$1(n, m) {
      m.forEach(function (e) {
          e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) {
              if (k !== 'default' && !(k in n)) {
                  var d = Object.getOwnPropertyDescriptor(e, k);
                  Object.defineProperty(n, k, d.get ? d : {
                      enumerable: true,
                      get: function () { return e[k]; }
                  });
              }
          });
      });
      return Object.freeze(n);
  }

  var protobuf = createCommonjsModule(function (module) {
  /*!
   * protobuf.js v6.7.0 (c) 2016, Daniel Wirtz
   * Compiled Sun, 02 Apr 2017 11:28:29 UTC
   * Licensed under the BSD-3-Clause License
   * see: https://github.com/dcodeIO/protobuf.js for details
   */
  (function(global,undefined$1){(function prelude(modules, cache, entries) {

      // This is the prelude used to bundle protobuf.js for the browser. Wraps up the CommonJS
      // sources through a conflict-free require shim and is again wrapped within an iife that
      // provides a unified `global` and a minification-friendly `undefined` var plus a global
      // "use strict" directive so that minification can remove the directives of each module.

      function $require(name) {
          var $module = cache[name];
          if (!$module)
              modules[name][0].call($module = cache[name] = { exports: {} }, $require, $module, $module.exports);
          return $module.exports;
      }

      // Expose globally
      var protobuf = global.protobuf = $require(entries[0]);

      // Be nice to AMD
      if (typeof undefined$1 === "function" && undefined$1.amd)
          undefined$1(["long"], function(Long) {
              if (Long && Long.isLong) {
                  protobuf.util.Long = Long;
                  protobuf.configure();
              }
              return protobuf;
          });

      // Be nice to CommonJS
      if (module && module.exports)
          module.exports = protobuf;

  })/* end of prelude */({1:[function(require,module,exports){
  module.exports = asPromise;

  /**
   * Returns a promise from a node-style callback function.
   * @memberof util
   * @param {function(?Error, ...*)} fn Function to call
   * @param {*} ctx Function context
   * @param {...*} params Function arguments
   * @returns {Promise<*>} Promisified function
   */
  function asPromise(fn, ctx/*, varargs */) {
      var params = [];
      for (var i = 2; i < arguments.length;)
          params.push(arguments[i++]);
      var pending = true;
      return new Promise(function asPromiseExecutor(resolve, reject) {
          params.push(function asPromiseCallback(err/*, varargs */) {
              if (pending) {
                  pending = false;
                  if (err)
                      reject(err);
                  else {
                      var args = [];
                      for (var i = 1; i < arguments.length;)
                          args.push(arguments[i++]);
                      resolve.apply(null, args);
                  }
              }
          });
          try {
              fn.apply(ctx || this, params); // eslint-disable-line no-invalid-this
          } catch (err) {
              if (pending) {
                  pending = false;
                  reject(err);
              }
          }
      });
  }

  },{}],2:[function(require,module,exports){

  /**
   * A minimal base64 implementation for number arrays.
   * @memberof util
   * @namespace
   */
  var base64 = exports;

  /**
   * Calculates the byte length of a base64 encoded string.
   * @param {string} string Base64 encoded string
   * @returns {number} Byte length
   */
  base64.length = function length(string) {
      var p = string.length;
      if (!p)
          return 0;
      var n = 0;
      while (--p % 4 > 1 && string.charAt(p) === "=")
          ++n;
      return Math.ceil(string.length * 3) / 4 - n;
  };

  // Base64 encoding table
  var b64 = new Array(64);

  // Base64 decoding table
  var s64 = new Array(123);

  // 65..90, 97..122, 48..57, 43, 47
  for (var i = 0; i < 64;)
      s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;

  /**
   * Encodes a buffer to a base64 encoded string.
   * @param {Uint8Array} buffer Source buffer
   * @param {number} start Source start
   * @param {number} end Source end
   * @returns {string} Base64 encoded string
   */
  base64.encode = function encode(buffer, start, end) {
      var string = []; // alt: new Array(Math.ceil((end - start) / 3) * 4);
      var i = 0, // output index
          j = 0, // goto index
          t;     // temporary
      while (start < end) {
          var b = buffer[start++];
          switch (j) {
              case 0:
                  string[i++] = b64[b >> 2];
                  t = (b & 3) << 4;
                  j = 1;
                  break;
              case 1:
                  string[i++] = b64[t | b >> 4];
                  t = (b & 15) << 2;
                  j = 2;
                  break;
              case 2:
                  string[i++] = b64[t | b >> 6];
                  string[i++] = b64[b & 63];
                  j = 0;
                  break;
          }
      }
      if (j) {
          string[i++] = b64[t];
          string[i  ] = 61;
          if (j === 1)
              string[i + 1] = 61;
      }
      return String.fromCharCode.apply(String, string);
  };

  var invalidEncoding = "invalid encoding";

  /**
   * Decodes a base64 encoded string to a buffer.
   * @param {string} string Source string
   * @param {Uint8Array} buffer Destination buffer
   * @param {number} offset Destination offset
   * @returns {number} Number of bytes written
   * @throws {Error} If encoding is invalid
   */
  base64.decode = function decode(string, buffer, offset) {
      var start = offset;
      var j = 0, // goto index
          t;     // temporary
      for (var i = 0; i < string.length;) {
          var c = string.charCodeAt(i++);
          if (c === 61 && j > 1)
              break;
          if ((c = s64[c]) === undefined$1)
              throw Error(invalidEncoding);
          switch (j) {
              case 0:
                  t = c;
                  j = 1;
                  break;
              case 1:
                  buffer[offset++] = t << 2 | (c & 48) >> 4;
                  t = c;
                  j = 2;
                  break;
              case 2:
                  buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;
                  t = c;
                  j = 3;
                  break;
              case 3:
                  buffer[offset++] = (t & 3) << 6 | c;
                  j = 0;
                  break;
          }
      }
      if (j === 1)
          throw Error(invalidEncoding);
      return offset - start;
  };

  /**
   * Tests if the specified string appears to be base64 encoded.
   * @param {string} string String to test
   * @returns {boolean} `true` if probably base64 encoded, otherwise false
   */
  base64.test = function test(string) {
      return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string);
  };

  },{}],3:[function(require,module,exports){
  module.exports = EventEmitter;

  /**
   * Constructs a new event emitter instance.
   * @classdesc A minimal event emitter.
   * @memberof util
   * @constructor
   */
  function EventEmitter() {

      /**
       * Registered listeners.
       * @type {Object.<string,*>}
       * @private
       */
      this._listeners = {};
  }

  /**
   * Registers an event listener.
   * @param {string} evt Event name
   * @param {function} fn Listener
   * @param {*} [ctx] Listener context
   * @returns {util.EventEmitter} `this`
   */
  EventEmitter.prototype.on = function on(evt, fn, ctx) {
      (this._listeners[evt] || (this._listeners[evt] = [])).push({
          fn  : fn,
          ctx : ctx || this
      });
      return this;
  };

  /**
   * Removes an event listener or any matching listeners if arguments are omitted.
   * @param {string} [evt] Event name. Removes all listeners if omitted.
   * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted.
   * @returns {util.EventEmitter} `this`
   */
  EventEmitter.prototype.off = function off(evt, fn) {
      if (evt === undefined$1)
          this._listeners = {};
      else {
          if (fn === undefined$1)
              this._listeners[evt] = [];
          else {
              var listeners = this._listeners[evt];
              for (var i = 0; i < listeners.length;)
                  if (listeners[i].fn === fn)
                      listeners.splice(i, 1);
                  else
                      ++i;
          }
      }
      return this;
  };

  /**
   * Emits an event by calling its listeners with the specified arguments.
   * @param {string} evt Event name
   * @param {...*} args Arguments
   * @returns {util.EventEmitter} `this`
   */
  EventEmitter.prototype.emit = function emit(evt) {
      var listeners = this._listeners[evt];
      if (listeners) {
          var args = [],
              i = 1;
          for (; i < arguments.length;)
              args.push(arguments[i++]);
          for (i = 0; i < listeners.length;)
              listeners[i].fn.apply(listeners[i++].ctx, args);
      }
      return this;
  };

  },{}],4:[function(require,module,exports){

  module.exports = factory(factory);

  /**
   * Reads / writes floats / doubles from / to buffers.
   * @name util.float
   * @namespace
   */

  /**
   * Writes a 32 bit float to a buffer using little endian byte order.
   * @name util.float.writeFloatLE
   * @function
   * @param {number} val Value to write
   * @param {Uint8Array} buf Target buffer
   * @param {number} pos Target buffer offset
   * @returns {undefined}
   */

  /**
   * Writes a 32 bit float to a buffer using big endian byte order.
   * @name util.float.writeFloatBE
   * @function
   * @param {number} val Value to write
   * @param {Uint8Array} buf Target buffer
   * @param {number} pos Target buffer offset
   * @returns {undefined}
   */

  /**
   * Reads a 32 bit float from a buffer using little endian byte order.
   * @name util.float.readFloatLE
   * @function
   * @param {Uint8Array} buf Source buffer
   * @param {number} pos Source buffer offset
   * @returns {number} Value read
   */

  /**
   * Reads a 32 bit float from a buffer using big endian byte order.
   * @name util.float.readFloatBE
   * @function
   * @param {Uint8Array} buf Source buffer
   * @param {number} pos Source buffer offset
   * @returns {number} Value read
   */

  /**
   * Writes a 64 bit double to a buffer using little endian byte order.
   * @name util.float.writeDoubleLE
   * @function
   * @param {number} val Value to write
   * @param {Uint8Array} buf Target buffer
   * @param {number} pos Target buffer offset
   * @returns {undefined}
   */

  /**
   * Writes a 64 bit double to a buffer using big endian byte order.
   * @name util.float.writeDoubleBE
   * @function
   * @param {number} val Value to write
   * @param {Uint8Array} buf Target buffer
   * @param {number} pos Target buffer offset
   * @returns {undefined}
   */

  /**
   * Reads a 64 bit double from a buffer using little endian byte order.
   * @name util.float.readDoubleLE
   * @function
   * @param {Uint8Array} buf Source buffer
   * @param {number} pos Source buffer offset
   * @returns {number} Value read
   */

  /**
   * Reads a 64 bit double from a buffer using big endian byte order.
   * @name util.float.readDoubleBE
   * @function
   * @param {Uint8Array} buf Source buffer
   * @param {number} pos Source buffer offset
   * @returns {number} Value read
   */

  // Factory function for the purpose of node-based testing in modified global environments
  function factory(exports) {

      // float: typed array
      if (typeof Float32Array !== "undefined") (function() {

          var f32 = new Float32Array([ -0 ]),
              f8b = new Uint8Array(f32.buffer),
              le  = f8b[3] === 128;

          function writeFloat_f32_cpy(val, buf, pos) {
              f32[0] = val;
              buf[pos    ] = f8b[0];
              buf[pos + 1] = f8b[1];
              buf[pos + 2] = f8b[2];
              buf[pos + 3] = f8b[3];
          }

          function writeFloat_f32_rev(val, buf, pos) {
              f32[0] = val;
              buf[pos    ] = f8b[3];
              buf[pos + 1] = f8b[2];
              buf[pos + 2] = f8b[1];
              buf[pos + 3] = f8b[0];
          }

          /* istanbul ignore next */
          exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;
          /* istanbul ignore next */
          exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;

          function readFloat_f32_cpy(buf, pos) {
              f8b[0] = buf[pos    ];
              f8b[1] = buf[pos + 1];
              f8b[2] = buf[pos + 2];
              f8b[3] = buf[pos + 3];
              return f32[0];
          }

          function readFloat_f32_rev(buf, pos) {
              f8b[3] = buf[pos    ];
              f8b[2] = buf[pos + 1];
              f8b[1] = buf[pos + 2];
              f8b[0] = buf[pos + 3];
              return f32[0];
          }

          /* istanbul ignore next */
          exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;
          /* istanbul ignore next */
          exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;

      // float: ieee754
      })(); else (function() {

          function writeFloat_ieee754(writeUint, val, buf, pos) {
              var sign = val < 0 ? 1 : 0;
              if (sign)
                  val = -val;
              if (val === 0)
                  writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos);
              else if (isNaN(val))
                  writeUint(2143289344, buf, pos);
              else if (val > 3.4028234663852886e+38) // +-Infinity
                  writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);
              else if (val < 1.1754943508222875e-38) // denormal
                  writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos);
              else {
                  var exponent = Math.floor(Math.log(val) / Math.LN2),
                      mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;
                  writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos);
              }
          }

          exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);
          exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);

          function readFloat_ieee754(readUint, buf, pos) {
              var uint = readUint(buf, pos),
                  sign = (uint >> 31) * 2 + 1,
                  exponent = uint >>> 23 & 255,
                  mantissa = uint & 8388607;
              return exponent === 255
                  ? mantissa
                  ? NaN
                  : sign * Infinity
                  : exponent === 0 // denormal
                  ? sign * 1.401298464324817e-45 * mantissa
                  : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);
          }

          exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE);
          exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE);

      })();

      // double: typed array
      if (typeof Float64Array !== "undefined") (function() {

          var f64 = new Float64Array([-0]),
              f8b = new Uint8Array(f64.buffer),
              le  = f8b[7] === 128;

          function writeDouble_f64_cpy(val, buf, pos) {
              f64[0] = val;
              buf[pos    ] = f8b[0];
              buf[pos + 1] = f8b[1];
              buf[pos + 2] = f8b[2];
              buf[pos + 3] = f8b[3];
              buf[pos + 4] = f8b[4];
              buf[pos + 5] = f8b[5];
              buf[pos + 6] = f8b[6];
              buf[pos + 7] = f8b[7];
          }

          function writeDouble_f64_rev(val, buf, pos) {
              f64[0] = val;
              buf[pos    ] = f8b[7];
              buf[pos + 1] = f8b[6];
              buf[pos + 2] = f8b[5];
              buf[pos + 3] = f8b[4];
              buf[pos + 4] = f8b[3];
              buf[pos + 5] = f8b[2];
              buf[pos + 6] = f8b[1];
              buf[pos + 7] = f8b[0];
          }

          /* istanbul ignore next */
          exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;
          /* istanbul ignore next */
          exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;

          function readDouble_f64_cpy(buf, pos) {
              f8b[0] = buf[pos    ];
              f8b[1] = buf[pos + 1];
              f8b[2] = buf[pos + 2];
              f8b[3] = buf[pos + 3];
              f8b[4] = buf[pos + 4];
              f8b[5] = buf[pos + 5];
              f8b[6] = buf[pos + 6];
              f8b[7] = buf[pos + 7];
              return f64[0];
          }

          function readDouble_f64_rev(buf, pos) {
              f8b[7] = buf[pos    ];
              f8b[6] = buf[pos + 1];
              f8b[5] = buf[pos + 2];
              f8b[4] = buf[pos + 3];
              f8b[3] = buf[pos + 4];
              f8b[2] = buf[pos + 5];
              f8b[1] = buf[pos + 6];
              f8b[0] = buf[pos + 7];
              return f64[0];
          }

          /* istanbul ignore next */
          exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;
          /* istanbul ignore next */
          exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;

      // double: ieee754
      })(); else (function() {

          function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) {
              var sign = val < 0 ? 1 : 0;
              if (sign)
                  val = -val;
              if (val === 0) {
                  writeUint(0, buf, pos + off0);
                  writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1);
              } else if (isNaN(val)) {
                  writeUint(0, buf, pos + off0);
                  writeUint(2146959360, buf, pos + off1);
              } else if (val > 1.7976931348623157e+308) { // +-Infinity
                  writeUint(0, buf, pos + off0);
                  writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);
              } else {
                  var mantissa;
                  if (val < 2.2250738585072014e-308) { // denormal
                      mantissa = val / 5e-324;
                      writeUint(mantissa >>> 0, buf, pos + off0);
                      writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1);
                  } else {
                      var exponent = Math.floor(Math.log(val) / Math.LN2);
                      if (exponent === 1024)
                          exponent = 1023;
                      mantissa = val * Math.pow(2, -exponent);
                      writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0);
                      writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1);
                  }
              }
          }

          exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);
          exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);

          function readDouble_ieee754(readUint, off0, off1, buf, pos) {
              var lo = readUint(buf, pos + off0),
                  hi = readUint(buf, pos + off1);
              var sign = (hi >> 31) * 2 + 1,
                  exponent = hi >>> 20 & 2047,
                  mantissa = 4294967296 * (hi & 1048575) + lo;
              return exponent === 2047
                  ? mantissa
                  ? NaN
                  : sign * Infinity
                  : exponent === 0 // denormal
                  ? sign * 5e-324 * mantissa
                  : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);
          }

          exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);
          exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);

      })();

      return exports;
  }

  // uint helpers

  function writeUintLE(val, buf, pos) {
      buf[pos    ] =  val        & 255;
      buf[pos + 1] =  val >>> 8  & 255;
      buf[pos + 2] =  val >>> 16 & 255;
      buf[pos + 3] =  val >>> 24;
  }

  function writeUintBE(val, buf, pos) {
      buf[pos    ] =  val >>> 24;
      buf[pos + 1] =  val >>> 16 & 255;
      buf[pos + 2] =  val >>> 8  & 255;
      buf[pos + 3] =  val        & 255;
  }

  function readUintLE(buf, pos) {
      return (buf[pos    ]
            | buf[pos + 1] << 8
            | buf[pos + 2] << 16
            | buf[pos + 3] << 24) >>> 0;
  }

  function readUintBE(buf, pos) {
      return (buf[pos    ] << 24
            | buf[pos + 1] << 16
            | buf[pos + 2] << 8
            | buf[pos + 3]) >>> 0;
  }

  },{}],5:[function(require,module,exports){
  module.exports = inquire;

  /**
   * Requires a module only if available.
   * @memberof util
   * @param {string} moduleName Module to require
   * @returns {?Object} Required module if available and not empty, otherwise `null`
   */
  function inquire(moduleName) {
      try {
          var mod = eval("quire".replace(/^/,"re"))(moduleName); // eslint-disable-line no-eval
          if (mod && (mod.length || Object.keys(mod).length))
              return mod;
      } catch (e) {} // eslint-disable-line no-empty
      return null;
  }

  },{}],6:[function(require,module,exports){
  module.exports = pool;

  /**
   * An allocator as used by {@link util.pool}.
   * @typedef PoolAllocator
   * @type {function}
   * @param {number} size Buffer size
   * @returns {Uint8Array} Buffer
   */

  /**
   * A slicer as used by {@link util.pool}.
   * @typedef PoolSlicer
   * @type {function}
   * @param {number} start Start offset
   * @param {number} end End offset
   * @returns {Uint8Array} Buffer slice
   * @this {Uint8Array}
   */

  /**
   * A general purpose buffer pool.
   * @memberof util
   * @function
   * @param {PoolAllocator} alloc Allocator
   * @param {PoolSlicer} slice Slicer
   * @param {number} [size=8192] Slab size
   * @returns {PoolAllocator} Pooled allocator
   */
  function pool(alloc, slice, size) {
      var SIZE   = size || 8192;
      var MAX    = SIZE >>> 1;
      var slab   = null;
      var offset = SIZE;
      return function pool_alloc(size) {
          if (size < 1 || size > MAX)
              return alloc(size);
          if (offset + size > SIZE) {
              slab = alloc(SIZE);
              offset = 0;
          }
          var buf = slice.call(slab, offset, offset += size);
          if (offset & 7) // align to 32 bit
              offset = (offset | 7) + 1;
          return buf;
      };
  }

  },{}],7:[function(require,module,exports){

  /**
   * A minimal UTF8 implementation for number arrays.
   * @memberof util
   * @namespace
   */
  var utf8 = exports;

  /**
   * Calculates the UTF8 byte length of a string.
   * @param {string} string String
   * @returns {number} Byte length
   */
  utf8.length = function utf8_length(string) {
      var len = 0,
          c = 0;
      for (var i = 0; i < string.length; ++i) {
          c = string.charCodeAt(i);
          if (c < 128)
              len += 1;
          else if (c < 2048)
              len += 2;
          else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {
              ++i;
              len += 4;
          } else
              len += 3;
      }
      return len;
  };

  /**
   * Reads UTF8 bytes as a string.
   * @param {Uint8Array} buffer Source buffer
   * @param {number} start Source start
   * @param {number} end Source end
   * @returns {string} String read
   */
  utf8.read = function utf8_read(buffer, start, end) {
      var len = end - start;
      if (len < 1)
          return "";
      var parts = null,
          chunk = [],
          i = 0, // char offset
          t;     // temporary
      while (start < end) {
          t = buffer[start++];
          if (t < 128)
              chunk[i++] = t;
          else if (t > 191 && t < 224)
              chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;
          else if (t > 239 && t < 365) {
              t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;
              chunk[i++] = 0xD800 + (t >> 10);
              chunk[i++] = 0xDC00 + (t & 1023);
          } else
              chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;
          if (i > 8191) {
              (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
              i = 0;
          }
      }
      if (parts) {
          if (i)
              parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));
          return parts.join("");
      }
      return String.fromCharCode.apply(String, chunk.slice(0, i));
  };

  /**
   * Writes a string as UTF8 bytes.
   * @param {string} string Source string
   * @param {Uint8Array} buffer Destination buffer
   * @param {number} offset Destination offset
   * @returns {number} Bytes written
   */
  utf8.write = function utf8_write(string, buffer, offset) {
      var start = offset,
          c1, // character 1
          c2; // character 2
      for (var i = 0; i < string.length; ++i) {
          c1 = string.charCodeAt(i);
          if (c1 < 128) {
              buffer[offset++] = c1;
          } else if (c1 < 2048) {
              buffer[offset++] = c1 >> 6       | 192;
              buffer[offset++] = c1       & 63 | 128;
          } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {
              c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);
              ++i;
              buffer[offset++] = c1 >> 18      | 240;
              buffer[offset++] = c1 >> 12 & 63 | 128;
              buffer[offset++] = c1 >> 6  & 63 | 128;
              buffer[offset++] = c1       & 63 | 128;
          } else {
              buffer[offset++] = c1 >> 12      | 224;
              buffer[offset++] = c1 >> 6  & 63 | 128;
              buffer[offset++] = c1       & 63 | 128;
          }
      }
      return offset - start;
  };

  },{}],8:[function(require,module,exports){
  var protobuf = exports;

  /**
   * Build type, one of `"full"`, `"light"` or `"minimal"`.
   * @name build
   * @type {string}
   * @const
   */
  protobuf.build = "minimal";

  /**
   * Named roots.
   * This is where pbjs stores generated structures (the option `-r, --root` specifies a name).
   * Can also be used manually to make roots available accross modules.
   * @name roots
   * @type {Object.<string,Root>}
   * @example
   * // pbjs -r myroot -o compiled.js ...
   *
   * // in another module:
   * require("./compiled.js");
   *
   * // in any subsequent module:
   * var root = protobuf.roots["myroot"];
   */
  protobuf.roots = {};

  // Serialization
  protobuf.Writer       = require(15);
  protobuf.BufferWriter = require(16);
  protobuf.Reader       = require(9);
  protobuf.BufferReader = require(10);

  // Utility
  protobuf.util         = require(14);
  protobuf.rpc          = require(11);
  protobuf.configure    = configure;

  /* istanbul ignore next */
  /**
   * Reconfigures the library according to the environment.
   * @returns {undefined}
   */
  function configure() {
      protobuf.Reader._configure(protobuf.BufferReader);
      protobuf.util._configure();
  }

  // Configure serialization
  protobuf.Writer._configure(protobuf.BufferWriter);
  configure();

  },{"10":10,"11":11,"14":14,"15":15,"16":16,"9":9}],9:[function(require,module,exports){
  module.exports = Reader;

  var util      = require(14);

  var BufferReader; // cyclic

  var LongBits  = util.LongBits,
      utf8      = util.utf8;

  /* istanbul ignore next */
  function indexOutOfRange(reader, writeLength) {
      return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len);
  }

  /**
   * Constructs a new reader instance using the specified buffer.
   * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`.
   * @constructor
   * @param {Uint8Array} buffer Buffer to read from
   */
  function Reader(buffer) {

      /**
       * Read buffer.
       * @type {Uint8Array}
       */
      this.buf = buffer;

      /**
       * Read buffer position.
       * @type {number}
       */
      this.pos = 0;

      /**
       * Read buffer length.
       * @type {number}
       */
      this.len = buffer.length;
  }

  var create_array = typeof Uint8Array !== "undefined"
      ? function create_typed_array(buffer) {
          if (buffer instanceof Uint8Array || Array.isArray(buffer))
              return new Reader(buffer);
          throw Error("illegal buffer");
      }
      /* istanbul ignore next */
      : function create_array(buffer) {
          if (Array.isArray(buffer))
              return new Reader(buffer);
          throw Error("illegal buffer");
      };

  /**
   * Creates a new reader using the specified buffer.
   * @function
   * @param {Uint8Array|Buffer} buffer Buffer to read from
   * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}
   * @throws {Error} If `buffer` is not a valid buffer
   */
  Reader.create = util.Buffer
      ? function create_buffer_setup(buffer) {
          return (Reader.create = function create_buffer(buffer) {
              return util.Buffer.isBuffer(buffer)
                  ? new BufferReader(buffer)
                  /* istanbul ignore next */
                  : create_array(buffer);
          })(buffer);
      }
      /* istanbul ignore next */
      : create_array;

  Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice;

  /**
   * Reads a varint as an unsigned 32 bit value.
   * @function
   * @returns {number} Value read
   */
  Reader.prototype.uint32 = (function read_uint32_setup() {
      var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!)
      return function read_uint32() {
          value = (         this.buf[this.pos] & 127       ) >>> 0; if (this.buf[this.pos++] < 128) return value;
          value = (value | (this.buf[this.pos] & 127) <<  7) >>> 0; if (this.buf[this.pos++] < 128) return value;
          value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value;
          value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value;
          value = (value | (this.buf[this.pos] &  15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value;

          /* istanbul ignore if */
          if ((this.pos += 5) > this.len) {
              this.pos = this.len;
              throw indexOutOfRange(this, 10);
          }
          return value;
      };
  })();

  /**
   * Reads a varint as a signed 32 bit value.
   * @returns {number} Value read
   */
  Reader.prototype.int32 = function read_int32() {
      return this.uint32() | 0;
  };

  /**
   * Reads a zig-zag encoded varint as a signed 32 bit value.
   * @returns {number} Value read
   */
  Reader.prototype.sint32 = function read_sint32() {
      var value = this.uint32();
      return value >>> 1 ^ -(value & 1) | 0;
  };

  /* eslint-disable no-invalid-this */

  function readLongVarint() {
      // tends to deopt with local vars for octet etc.
      var bits = new LongBits(0, 0);
      var i = 0;
      if (this.len - this.pos > 4) { // fast route (lo)
          for (; i < 4; ++i) {
              // 1st..4th
              bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;
              if (this.buf[this.pos++] < 128)
                  return bits;
          }
          // 5th
          bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;
          bits.hi = (bits.hi | (this.buf[this.pos] & 127) >>  4) >>> 0;
          if (this.buf[this.pos++] < 128)
              return bits;
          i = 0;
      } else {
          for (; i < 3; ++i) {
              /* istanbul ignore if */
              if (this.pos >= this.len)
                  throw indexOutOfRange(this);
              // 1st..3th
              bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;
              if (this.buf[this.pos++] < 128)
                  return bits;
          }
          // 4th
          bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;
          return bits;
      }
      if (this.len - this.pos > 4) { // fast route (hi)
          for (; i < 5; ++i) {
              // 6th..10th
              bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;
              if (this.buf[this.pos++] < 128)
                  return bits;
          }
      } else {
          for (; i < 5; ++i) {
              /* istanbul ignore if */
              if (this.pos >= this.len)
                  throw indexOutOfRange(this);
              // 6th..10th
              bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;
              if (this.buf[this.pos++] < 128)
                  return bits;
          }
      }
      /* istanbul ignore next */
      throw Error("invalid varint encoding");
  }

  /* eslint-enable no-invalid-this */

  /**
   * Reads a varint as a signed 64 bit value.
   * @name Reader#int64
   * @function
   * @returns {Long} Value read
   */

  /**
   * Reads a varint as an unsigned 64 bit value.
   * @name Reader#uint64
   * @function
   * @returns {Long} Value read
   */

  /**
   * Reads a zig-zag encoded varint as a signed 64 bit value.
   * @name Reader#sint64
   * @function
   * @returns {Long} Value read
   */

  /**
   * Reads a varint as a boolean.
   * @returns {boolean} Value read
   */
  Reader.prototype.bool = function read_bool() {
      return this.uint32() !== 0;
  };

  function readFixed32_end(buf, end) { // note that this uses `end`, not `pos`
      return (buf[end - 4]
            | buf[end - 3] << 8
            | buf[end - 2] << 16
            | buf[end - 1] << 24) >>> 0;
  }

  /**
   * Reads fixed 32 bits as an unsigned 32 bit integer.
   * @returns {number} Value read
   */
  Reader.prototype.fixed32 = function read_fixed32() {

      /* istanbul ignore if */
      if (this.pos + 4 > this.len)
          throw indexOutOfRange(this, 4);

      return readFixed32_end(this.buf, this.pos += 4);
  };

  /**
   * Reads fixed 32 bits as a signed 32 bit integer.
   * @returns {number} Value read
   */
  Reader.prototype.sfixed32 = function read_sfixed32() {

      /* istanbul ignore if */
      if (this.pos + 4 > this.len)
          throw indexOutOfRange(this, 4);

      return readFixed32_end(this.buf, this.pos += 4) | 0;
  };

  /* eslint-disable no-invalid-this */

  function readFixed64(/* this: Reader */) {

      /* istanbul ignore if */
      if (this.pos + 8 > this.len)
          throw indexOutOfRange(this, 8);

      return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));
  }

  /* eslint-enable no-invalid-this */

  /**
   * Reads fixed 64 bits.
   * @name Reader#fixed64
   * @function
   * @returns {Long} Value read
   */

  /**
   * Reads zig-zag encoded fixed 64 bits.
   * @name Reader#sfixed64
   * @function
   * @returns {Long} Value read
   */

  /**
   * Reads a float (32 bit) as a number.
   * @function
   * @returns {number} Value read
   */
  Reader.prototype.float = function read_float() {

      /* istanbul ignore if */
      if (this.pos + 4 > this.len)
          throw indexOutOfRange(this, 4);

      var value = util.float.readFloatLE(this.buf, this.pos);
      this.pos += 4;
      return value;
  };

  /**
   * Reads a double (64 bit float) as a number.
   * @function
   * @returns {number} Value read
   */
  Reader.prototype.double = function read_double() {

      /* istanbul ignore if */
      if (this.pos + 8 > this.len)
          throw indexOutOfRange(this, 4);

      var value = util.float.readDoubleLE(this.buf, this.pos);
      this.pos += 8;
      return value;
  };

  /**
   * Reads a sequence of bytes preceeded by its length as a varint.
   * @returns {Uint8Array} Value read
   */
  Reader.prototype.bytes = function read_bytes() {
      var length = this.uint32(),
          start  = this.pos,
          end    = this.pos + length;

      /* istanbul ignore if */
      if (end > this.len)
          throw indexOutOfRange(this, length);

      this.pos += length;
      return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1
          ? new this.buf.constructor(0)
          : this._slice.call(this.buf, start, end);
  };

  /**
   * Reads a string preceeded by its byte length as a varint.
   * @returns {string} Value read
   */
  Reader.prototype.string = function read_string() {
      var bytes = this.bytes();
      return utf8.read(bytes, 0, bytes.length);
  };

  /**
   * Skips the specified number of bytes if specified, otherwise skips a varint.
   * @param {number} [length] Length if known, otherwise a varint is assumed
   * @returns {Reader} `this`
   */
  Reader.prototype.skip = function skip(length) {
      if (typeof length === "number") {
          /* istanbul ignore if */
          if (this.pos + length > this.len)
              throw indexOutOfRange(this, length);
          this.pos += length;
      } else {
          do {
              /* istanbul ignore if */
              if (this.pos >= this.len)
                  throw indexOutOfRange(this);
          } while (this.buf[this.pos++] & 128);
      }
      return this;
  };

  /**
   * Skips the next element of the specified wire type.
   * @param {number} wireType Wire type received
   * @returns {Reader} `this`
   */
  Reader.prototype.skipType = function(wireType) {
      switch (wireType) {
          case 0:
              this.skip();
              break;
          case 1:
              this.skip(8);
              break;
          case 2:
              this.skip(this.uint32());
              break;
          case 3:
              do { // eslint-disable-line no-constant-condition
                  if ((wireType = this.uint32() & 7) === 4)
                      break;
                  this.skipType(wireType);
              } while (true);
              break;
          case 5:
              this.skip(4);
              break;

          /* istanbul ignore next */
          default:
              throw Error("invalid wire type " + wireType + " at offset " + this.pos);
      }
      return this;
  };

  Reader._configure = function(BufferReader_) {
      BufferReader = BufferReader_;

      var fn = util.Long ? "toLong" : /* istanbul ignore next */ "toNumber";
      util.merge(Reader.prototype, {

          int64: function read_int64() {
              return readLongVarint.call(this)[fn](false);
          },

          uint64: function read_uint64() {
              return readLongVarint.call(this)[fn](true);
          },

          sint64: function read_sint64() {
              return readLongVarint.call(this).zzDecode()[fn](false);
          },

          fixed64: function read_fixed64() {
              return readFixed64.call(this)[fn](true);
          },

          sfixed64: function read_sfixed64() {
              return readFixed64.call(this)[fn](false);
          }

      });
  };

  },{"14":14}],10:[function(require,module,exports){
  module.exports = BufferReader;

  // extends Reader
  var Reader = require(9);
  (BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;

  var util = require(14);

  /**
   * Constructs a new buffer reader instance.
   * @classdesc Wire format reader using node buffers.
   * @extends Reader
   * @constructor
   * @param {Buffer} buffer Buffer to read from
   */
  function BufferReader(buffer) {
      Reader.call(this, buffer);

      /**
       * Read buffer.
       * @name BufferReader#buf
       * @type {Buffer}
       */
  }

  /* istanbul ignore else */
  if (util.Buffer)
      BufferReader.prototype._slice = util.Buffer.prototype.slice;

  /**
   * @override
   */
  BufferReader.prototype.string = function read_string_buffer() {
      var len = this.uint32(); // modifies pos
      return this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len));
  };

  /**
   * Reads a sequence of bytes preceeded by its length as a varint.
   * @name BufferReader#bytes
   * @function
   * @returns {Buffer} Value read
   */

  },{"14":14,"9":9}],11:[function(require,module,exports){

  /**
   * Streaming RPC helpers.
   * @namespace
   */
  var rpc = exports;

  /**
   * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets.
   * @typedef RPCImpl
   * @type {function}
   * @param {Method|rpc.ServiceMethod} method Reflected or static method being called
   * @param {Uint8Array} requestData Request data
   * @param {RPCImplCallback} callback Callback function
   * @returns {undefined}
   * @example
   * function rpcImpl(method, requestData, callback) {
   *     if (protobuf.util.lcFirst(method.name) !== "myMethod") // compatible with static code
   *         throw Error("no such method");
   *     asynchronouslyObtainAResponse(requestData, function(err, responseData) {
   *         callback(err, responseData);
   *     });
   * }
   */

  /**
   * Node-style callback as used by {@link RPCImpl}.
   * @typedef RPCImplCallback
   * @type {function}
   * @param {?Error} error Error, if any, otherwise `null`
   * @param {?Uint8Array} [response] Response data or `null` to signal end of stream, if there hasn't been an error
   * @returns {undefined}
   */

  rpc.Service = require(12);

  },{"12":12}],12:[function(require,module,exports){
  module.exports = Service;

  var util = require(14);

  // Extends EventEmitter
  (Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;

  /**
   * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.
   *
   * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.
   * @typedef rpc.ServiceMethodCallback
   * @type {function}
   * @param {?Error} error Error, if any
   * @param {?Message} [response] Response message
   * @returns {undefined}
   */

  /**
   * A service method part of a {@link rpc.ServiceMethodMixin|ServiceMethodMixin} and thus {@link rpc.Service} as created by {@link Service.create}.
   * @typedef rpc.ServiceMethod
   * @type {function}
   * @param {Message|Object.<string,*>} request Request message or plain object
   * @param {rpc.ServiceMethodCallback} [callback] Node-style callback called with the error, if any, and the response message
   * @returns {Promise<Message>} Promise if `callback` has been omitted, otherwise `undefined`
   */

  /**
   * A service method mixin.
   *
   * When using TypeScript, mixed in service methods are only supported directly with a type definition of a static module (used with reflection). Otherwise, explicit casting is required.
   * @typedef rpc.ServiceMethodMixin
   * @type {Object.<string,rpc.ServiceMethod>}
   * @example
   * // Explicit casting with TypeScript
   * (myRpcService["myMethod"] as protobuf.rpc.ServiceMethod)(...)
   */

  /**
   * Constructs a new RPC service instance.
   * @classdesc An RPC service as returned by {@link Service#create}.
   * @exports rpc.Service
   * @extends util.EventEmitter
   * @augments rpc.ServiceMethodMixin
   * @constructor
   * @param {RPCImpl} rpcImpl RPC implementation
   * @param {boolean} [requestDelimited=false] Whether requests are length-delimited
   * @param {boolean} [responseDelimited=false] Whether responses are length-delimited
   */
  function Service(rpcImpl, requestDelimited, responseDelimited) {

      if (typeof rpcImpl !== "function")
          throw TypeError("rpcImpl must be a function");

      util.EventEmitter.call(this);

      /**
       * RPC implementation. Becomes `null` once the service is ended.
       * @type {?RPCImpl}
       */
      this.rpcImpl = rpcImpl;

      /**
       * Whether requests are length-delimited.
       * @type {boolean}
       */
      this.requestDelimited = Boolean(requestDelimited);

      /**
       * Whether responses are length-delimited.
       * @type {boolean}
       */
      this.responseDelimited = Boolean(responseDelimited);
  }

  /**
   * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}.
   * @param {Method|rpc.ServiceMethod} method Reflected or static method
   * @param {function} requestCtor Request constructor
   * @param {function} responseCtor Response constructor
   * @param {Message|Object.<string,*>} request Request message or plain object
   * @param {rpc.ServiceMethodCallback} callback Service callback
   * @returns {undefined}
   */
  Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) {

      if (!request)
          throw TypeError("request must be specified");

      var self = this;
      if (!callback)
          return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request);

      if (!self.rpcImpl) {
          setTimeout(function() { callback(Error("already ended")); }, 0);
          return undefined$1;
      }

      try {
          return self.rpcImpl(
              method,
              requestCtor[self.requestDelimited ? "encodeDelimited" : "encode"](request).finish(),
              function rpcCallback(err, response) {

                  if (err) {
                      self.emit("error", err, method);
                      return callback(err);
                  }

                  if (response === null) {
                      self.end(/* endedByRPC */ true);
                      return undefined$1;
                  }

                  if (!(response instanceof responseCtor)) {
                      try {
                          response = responseCtor[self.responseDelimited ? "decodeDelimited" : "decode"](response);
                      } catch (err) {
                          self.emit("error", err, method);
                          return callback(err);
                      }
                  }

                  self.emit("data", response, method);
                  return callback(null, response);
              }
          );
      } catch (err) {
          self.emit("error", err, method);
          setTimeout(function() { callback(err); }, 0);
          return undefined$1;
      }
  };

  /**
   * Ends this service and emits the `end` event.
   * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation.
   * @returns {rpc.Service} `this`
   */
  Service.prototype.end = function end(endedByRPC) {
      if (this.rpcImpl) {
          if (!endedByRPC) // signal end to rpcImpl
              this.rpcImpl(null, null, null);
          this.rpcImpl = null;
          this.emit("end").off();
      }
      return this;
  };

  },{"14":14}],13:[function(require,module,exports){
  module.exports = LongBits;

  var util = require(14);

  /**
   * Constructs new long bits.
   * @classdesc Helper class for working with the low and high bits of a 64 bit value.
   * @memberof util
   * @constructor
   * @param {number} lo Low 32 bits, unsigned
   * @param {number} hi High 32 bits, unsigned
   */
  function LongBits(lo, hi) {

      // note that the casts below are theoretically unnecessary as of today, but older statically
      // generated converter code might still call the ctor with signed 32bits. kept for compat.

      /**
       * Low bits.
       * @type {number}
       */
      this.lo = lo >>> 0;

      /**
       * High bits.
       * @type {number}
       */
      this.hi = hi >>> 0;
  }

  /**
   * Zero bits.
   * @memberof util.LongBits
   * @type {util.LongBits}
   */
  var zero = LongBits.zero = new LongBits(0, 0);

  zero.toNumber = function() { return 0; };
  zero.zzEncode = zero.zzDecode = function() { return this; };
  zero.length = function() { return 1; };

  /**
   * Zero hash.
   * @memberof util.LongBits
   * @type {string}
   */
  var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0";

  /**
   * Constructs new long bits from the specified number.
   * @param {number} value Value
   * @returns {util.LongBits} Instance
   */
  LongBits.fromNumber = function fromNumber(value) {
      if (value === 0)
          return zero;
      var sign = value < 0;
      if (sign)
          value = -value;
      var lo = value >>> 0,
          hi = (value - lo) / 4294967296 >>> 0;
      if (sign) {
          hi = ~hi >>> 0;
          lo = ~lo >>> 0;
          if (++lo > 4294967295) {
              lo = 0;
              if (++hi > 4294967295)
                  hi = 0;
          }
      }
      return new LongBits(lo, hi);
  };

  /**
   * Constructs new long bits from a number, long or string.
   * @param {Long|number|string} value Value
   * @returns {util.LongBits} Instance
   */
  LongBits.from = function from(value) {
      if (typeof value === "number")
          return LongBits.fromNumber(value);
      if (util.isString(value)) {
          /* istanbul ignore else */
          if (util.Long)
              value = util.Long.fromString(value);
          else
              return LongBits.fromNumber(parseInt(value, 10));
      }
      return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;
  };

  /**
   * Converts this long bits to a possibly unsafe JavaScript number.
   * @param {boolean} [unsigned=false] Whether unsigned or not
   * @returns {number} Possibly unsafe number
   */
  LongBits.prototype.toNumber = function toNumber(unsigned) {
      if (!unsigned && this.hi >>> 31) {
          var lo = ~this.lo + 1 >>> 0,
              hi = ~this.hi     >>> 0;
          if (!lo)
              hi = hi + 1 >>> 0;
          return -(lo + hi * 4294967296);
      }
      return this.lo + this.hi * 4294967296;
  };

  /**
   * Converts this long bits to a long.
   * @param {boolean} [unsigned=false] Whether unsigned or not
   * @returns {Long} Long
   */
  LongBits.prototype.toLong = function toLong(unsigned) {
      return util.Long
          ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))
          /* istanbul ignore next */
          : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };
  };

  var charCodeAt = String.prototype.charCodeAt;

  /**
   * Constructs new long bits from the specified 8 characters long hash.
   * @param {string} hash Hash
   * @returns {util.LongBits} Bits
   */
  LongBits.fromHash = function fromHash(hash) {
      if (hash === zeroHash)
          return zero;
      return new LongBits(
          ( charCodeAt.call(hash, 0)
          | charCodeAt.call(hash, 1) << 8
          | charCodeAt.call(hash, 2) << 16
          | charCodeAt.call(hash, 3) << 24) >>> 0
      ,
          ( charCodeAt.call(hash, 4)
          | charCodeAt.call(hash, 5) << 8
          | charCodeAt.call(hash, 6) << 16
          | charCodeAt.call(hash, 7) << 24) >>> 0
      );
  };

  /**
   * Converts this long bits to a 8 characters long hash.
   * @returns {string} Hash
   */
  LongBits.prototype.toHash = function toHash() {
      return String.fromCharCode(
          this.lo        & 255,
          this.lo >>> 8  & 255,
          this.lo >>> 16 & 255,
          this.lo >>> 24      ,
          this.hi        & 255,
          this.hi >>> 8  & 255,
          this.hi >>> 16 & 255,
          this.hi >>> 24
      );
  };

  /**
   * Zig-zag encodes this long bits.
   * @returns {util.LongBits} `this`
   */
  LongBits.prototype.zzEncode = function zzEncode() {
      var mask =   this.hi >> 31;
      this.hi  = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;
      this.lo  = ( this.lo << 1                   ^ mask) >>> 0;
      return this;
  };

  /**
   * Zig-zag decodes this long bits.
   * @returns {util.LongBits} `this`
   */
  LongBits.prototype.zzDecode = function zzDecode() {
      var mask = -(this.lo & 1);
      this.lo  = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;
      this.hi  = ( this.hi >>> 1                  ^ mask) >>> 0;
      return this;
  };

  /**
   * Calculates the length of this longbits when encoded as a varint.
   * @returns {number} Length
   */
  LongBits.prototype.length = function length() {
      var part0 =  this.lo,
          part1 = (this.lo >>> 28 | this.hi << 4) >>> 0,
          part2 =  this.hi >>> 24;
      return part2 === 0
           ? part1 === 0
             ? part0 < 16384
               ? part0 < 128 ? 1 : 2
               : part0 < 2097152 ? 3 : 4
             : part1 < 16384
               ? part1 < 128 ? 5 : 6
               : part1 < 2097152 ? 7 : 8
           : part2 < 128 ? 9 : 10;
  };

  },{"14":14}],14:[function(require,module,exports){
  var util = exports;

  // used to return a Promise where callback is omitted
  util.asPromise = require(1);

  // converts to / from base64 encoded strings
  util.base64 = require(2);

  // base class of rpc.Service
  util.EventEmitter = require(3);

  // float handling accross browsers
  util.float = require(4);

  // requires modules optionally and hides the call from bundlers
  util.inquire = require(5);

  // converts to / from utf8 encoded strings
  util.utf8 = require(7);

  // provides a node-like buffer pool in the browser
  util.pool = require(6);

  // utility to work with the low and high bits of a 64 bit value
  util.LongBits = require(13);

  /**
   * An immuable empty array.
   * @memberof util
   * @type {Array.<*>}
   * @const
   */
  util.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes

  /**
   * An immutable empty object.
   * @type {Object}
   * @const
   */
  util.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes

  /**
   * Whether running within node or not.
   * @memberof util
   * @type {boolean}
   * @const
   */
  util.isNode = Boolean(global.process && global.process.versions && global.process.versions.node);

  /**
   * Tests if the specified value is an integer.
   * @function
   * @param {*} value Value to test
   * @returns {boolean} `true` if the value is an integer
   */
  util.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) {
      return typeof value === "number" && isFinite(value) && Math.floor(value) === value;
  };

  /**
   * Tests if the specified value is a string.
   * @param {*} value Value to test
   * @returns {boolean} `true` if the value is a string
   */
  util.isString = function isString(value) {
      return typeof value === "string" || value instanceof String;
  };

  /**
   * Tests if the specified value is a non-null object.
   * @param {*} value Value to test
   * @returns {boolean} `true` if the value is a non-null object
   */
  util.isObject = function isObject(value) {
      return value && typeof value === "object";
  };

  /**
   * Checks if a property on a message is considered to be present.
   * This is an alias of {@link util.isSet}.
   * @function
   * @param {Object} obj Plain object or message instance
   * @param {string} prop Property name
   * @returns {boolean} `true` if considered to be present, otherwise `false`
   */
  util.isset =

  /**
   * Checks if a property on a message is considered to be present.
   * @param {Object} obj Plain object or message instance
   * @param {string} prop Property name
   * @returns {boolean} `true` if considered to be present, otherwise `false`
   */
  util.isSet = function isSet(obj, prop) {
      var value = obj[prop];
      if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins
          return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;
      return false;
  };

  /*
   * Any compatible Buffer instance.
   * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings.
   * @typedef Buffer
   * @type {Uint8Array}
   */

  /**
   * Node's Buffer class if available.
   * @type {?function(new: Buffer)}
   */
  util.Buffer = (function() {
      try {
          var Buffer = util.inquire("buffer").Buffer;
          // refuse to use non-node buffers if not explicitly assigned (perf reasons):
          return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null;
      } catch (e) {
          /* istanbul ignore next */
          return null;
      }
  })();

  /**
   * Internal alias of or polyfull for Buffer.from.
   * @type {?function}
   * @param {string|number[]} value Value
   * @param {string} [encoding] Encoding if value is a string
   * @returns {Uint8Array}
   * @private
   */
  util._Buffer_from = null;

  /**
   * Internal alias of or polyfill for Buffer.allocUnsafe.
   * @type {?function}
   * @param {number} size Buffer size
   * @returns {Uint8Array}
   * @private
   */
  util._Buffer_allocUnsafe = null;

  /**
   * Creates a new buffer of whatever type supported by the environment.
   * @param {number|number[]} [sizeOrArray=0] Buffer size or number array
   * @returns {Uint8Array|Buffer} Buffer
   */
  util.newBuffer = function newBuffer(sizeOrArray) {
      /* istanbul ignore next */
      return typeof sizeOrArray === "number"
          ? util.Buffer
              ? util._Buffer_allocUnsafe(sizeOrArray)
              : new util.Array(sizeOrArray)
          : util.Buffer
              ? util._Buffer_from(sizeOrArray)
              : typeof Uint8Array === "undefined"
                  ? sizeOrArray
                  : new Uint8Array(sizeOrArray);
  };

  /**
   * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.
   * @type {?function(new: Uint8Array, *)}
   */
  util.Array = typeof Uint8Array !== "undefined" ? Uint8Array /* istanbul ignore next */ : Array;

  /*
   * Any compatible Long instance.
   * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js.
   * @typedef Long
   * @type {Object}
   * @property {number} low Low bits
   * @property {number} high High bits
   * @property {boolean} unsigned Whether unsigned or not
   */

  /**
   * Long.js's Long class if available.
   * @type {?function(new: Long)}
   */
  util.Long = /* istanbul ignore next */ global.dcodeIO && /* istanbul ignore next */ global.dcodeIO.Long || util.inquire("long");

  /**
   * Regular expression used to verify 2 bit (`bool`) map keys.
   * @type {RegExp}
   * @const
   */
  util.key2Re = /^true|false|0|1$/;

  /**
   * Regular expression used to verify 32 bit (`int32` etc.) map keys.
   * @type {RegExp}
   * @const
   */
  util.key32Re = /^-?(?:0|[1-9][0-9]*)$/;

  /**
   * Regular expression used to verify 64 bit (`int64` etc.) map keys.
   * @type {RegExp}
   * @const
   */
  util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;

  /**
   * Converts a number or long to an 8 characters long hash string.
   * @param {Long|number} value Value to convert
   * @returns {string} Hash
   */
  util.longToHash = function longToHash(value) {
      return value
          ? util.LongBits.from(value).toHash()
          : util.LongBits.zeroHash;
  };

  /**
   * Converts an 8 characters long hash string to a long or number.
   * @param {string} hash Hash
   * @param {boolean} [unsigned=false] Whether unsigned or not
   * @returns {Long|number} Original value
   */
  util.longFromHash = function longFromHash(hash, unsigned) {
      var bits = util.LongBits.fromHash(hash);
      if (util.Long)
          return util.Long.fromBits(bits.lo, bits.hi, unsigned);
      return bits.toNumber(Boolean(unsigned));
  };

  /**
   * Merges the properties of the source object into the destination object.
   * @memberof util
   * @param {Object.<string,*>} dst Destination object
   * @param {Object.<string,*>} src Source object
   * @param {boolean} [ifNotSet=false] Merges only if the key is not already set
   * @returns {Object.<string,*>} Destination object
   */
  function merge(dst, src, ifNotSet) { // used by converters
      for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)
          if (dst[keys[i]] === undefined$1 || !ifNotSet)
              dst[keys[i]] = src[keys[i]];
      return dst;
  }

  util.merge = merge;

  /**
   * Converts the first character of a string to lower case.
   * @param {string} str String to convert
   * @returns {string} Converted string
   */
  util.lcFirst = function lcFirst(str) {
      return str.charAt(0).toLowerCase() + str.substring(1);
  };

  /**
   * Creates a custom error constructor.
   * @memberof util
   * @param {string} name Error name
   * @returns {function} Custom error constructor
   */
  function newError(name) {

      function CustomError(message, properties) {

          if (!(this instanceof CustomError))
              return new CustomError(message, properties);

          // Error.call(this, message);
          // ^ just returns a new error instance because the ctor can be called as a function

          Object.defineProperty(this, "message", { get: function() { return message; } });

          /* istanbul ignore next */
          if (Error.captureStackTrace) // node
              Error.captureStackTrace(this, CustomError);
          else
              Object.defineProperty(this, "stack", { value: (new Error()).stack || "" });

          if (properties)
              merge(this, properties);
      }

      (CustomError.prototype = Object.create(Error.prototype)).constructor = CustomError;

      Object.defineProperty(CustomError.prototype, "name", { get: function() { return name; } });

      CustomError.prototype.toString = function toString() {
          return this.name + ": " + this.message;
      };

      return CustomError;
  }

  util.newError = newError;

  /**
   * Constructs a new protocol error.
   * @classdesc Error subclass indicating a protocol specifc error.
   * @memberof util
   * @extends Error
   * @constructor
   * @param {string} message Error message
   * @param {Object.<string,*>=} properties Additional properties
   * @example
   * try {
   *     MyMessage.decode(someBuffer); // throws if required fields are missing
   * } catch (e) {
   *     if (e instanceof ProtocolError && e.instance)
   *         console.log("decoded so far: " + JSON.stringify(e.instance));
   * }
   */
  util.ProtocolError = newError("ProtocolError");

  /**
   * So far decoded message instance.
   * @name util.ProtocolError#instance
   * @type {Message}
   */

  /**
   * Builds a getter for a oneof's present field name.
   * @param {string[]} fieldNames Field names
   * @returns {function():string|undefined} Unbound getter
   */
  util.oneOfGetter = function getOneOf(fieldNames) {
      var fieldMap = {};
      for (var i = 0; i < fieldNames.length; ++i)
          fieldMap[fieldNames[i]] = 1;

      /**
       * @returns {string|undefined} Set field name, if any
       * @this Object
       * @ignore
       */
      return function() { // eslint-disable-line consistent-return
          for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i)
              if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined$1 && this[keys[i]] !== null)
                  return keys[i];
      };
  };

  /**
   * Builds a setter for a oneof's present field name.
   * @param {string[]} fieldNames Field names
   * @returns {function(?string):undefined} Unbound setter
   */
  util.oneOfSetter = function setOneOf(fieldNames) {

      /**
       * @param {string} name Field name
       * @returns {undefined}
       * @this Object
       * @ignore
       */
      return function(name) {
          for (var i = 0; i < fieldNames.length; ++i)
              if (fieldNames[i] !== name)
                  delete this[fieldNames[i]];
      };
  };

  /* istanbul ignore next */
  /**
   * Lazily resolves fully qualified type names against the specified root.
   * @param {Root} root Root instanceof
   * @param {Object.<number,string|ReflectionObject>} lazyTypes Type names
   * @returns {undefined}
   * @deprecated since 6.7.0 static code does not emit lazy types anymore
   */
  util.lazyResolve = function lazyResolve(root, lazyTypes) {
      for (var i = 0; i < lazyTypes.length; ++i) {
          for (var keys = Object.keys(lazyTypes[i]), j = 0; j < keys.length; ++j) {
              var path = lazyTypes[i][keys[j]].split("."),
                  ptr  = root;
              while (path.length)
                  ptr = ptr[path.shift()];
              lazyTypes[i][keys[j]] = ptr;
          }
      }
  };

  /**
   * Default conversion options used for {@link Message#toJSON} implementations. Longs, enums and bytes are converted to strings by default.
   * @type {ConversionOptions}
   */
  util.toJSONOptions = {
      longs: String,
      enums: String,
      bytes: String
  };

  util._configure = function() {
      var Buffer = util.Buffer;
      /* istanbul ignore if */
      if (!Buffer) {
          util._Buffer_from = util._Buffer_allocUnsafe = null;
          return;
      }
      // because node 4.x buffers are incompatible & immutable
      // see: https://github.com/dcodeIO/protobuf.js/pull/665
      util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from ||
          /* istanbul ignore next */
          function Buffer_from(value, encoding) {
              return new Buffer(value, encoding);
          };
      util._Buffer_allocUnsafe = Buffer.allocUnsafe ||
          /* istanbul ignore next */
          function Buffer_allocUnsafe(size) {
              return new Buffer(size);
          };
  };

  },{"1":1,"13":13,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7}],15:[function(require,module,exports){
  module.exports = Writer;

  var util      = require(14);

  var BufferWriter; // cyclic

  var LongBits  = util.LongBits,
      base64    = util.base64,
      utf8      = util.utf8;

  /**
   * Constructs a new writer operation instance.
   * @classdesc Scheduled writer operation.
   * @constructor
   * @param {function(*, Uint8Array, number)} fn Function to call
   * @param {number} len Value byte length
   * @param {*} val Value to write
   * @ignore
   */
  function Op(fn, len, val) {

      /**
       * Function to call.
       * @type {function(Uint8Array, number, *)}
       */
      this.fn = fn;

      /**
       * Value byte length.
       * @type {number}
       */
      this.len = len;

      /**
       * Next operation.
       * @type {Writer.Op|undefined}
       */
      this.next = undefined$1;

      /**
       * Value to write.
       * @type {*}
       */
      this.val = val; // type varies
  }

  /* istanbul ignore next */
  function noop() {} // eslint-disable-line no-empty-function

  /**
   * Constructs a new writer state instance.
   * @classdesc Copied writer state.
   * @memberof Writer
   * @constructor
   * @param {Writer} writer Writer to copy state from
   * @private
   * @ignore
   */
  function State(writer) {

      /**
       * Current head.
       * @type {Writer.Op}
       */
      this.head = writer.head;

      /**
       * Current tail.
       * @type {Writer.Op}
       */
      this.tail = writer.tail;

      /**
       * Current buffer length.
       * @type {number}
       */
      this.len = writer.len;

      /**
       * Next state.
       * @type {?State}
       */
      this.next = writer.states;
  }

  /**
   * Constructs a new writer instance.
   * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`.
   * @constructor
   */
  function Writer() {

      /**
       * Current length.
       * @type {number}
       */
      this.len = 0;

      /**
       * Operations head.
       * @type {Object}
       */
      this.head = new Op(noop, 0, 0);

      /**
       * Operations tail
       * @type {Object}
       */
      this.tail = this.head;

      /**
       * Linked forked states.
       * @type {?Object}
       */
      this.states = null;

      // When a value is written, the writer calculates its byte length and puts it into a linked
      // list of operations to perform when finish() is called. This both allows us to allocate
      // buffers of the exact required size and reduces the amount of work we have to do compared
      // to first calculating over objects and then encoding over objects. In our case, the encoding
      // part is just a linked list walk calling operations with already prepared values.
  }

  /**
   * Creates a new writer.
   * @function
   * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}
   */
  Writer.create = util.Buffer
      ? function create_buffer_setup() {
          return (Writer.create = function create_buffer() {
              return new BufferWriter();
          })();
      }
      /* istanbul ignore next */
      : function create_array() {
          return new Writer();
      };

  /**
   * Allocates a buffer of the specified size.
   * @param {number} size Buffer size
   * @returns {Uint8Array} Buffer
   */
  Writer.alloc = function alloc(size) {
      return new util.Array(size);
  };

  // Use Uint8Array buffer pool in the browser, just like node does with buffers
  /* istanbul ignore else */
  if (util.Array !== Array)
      Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);

  /**
   * Pushes a new operation to the queue.
   * @param {function(Uint8Array, number, *)} fn Function to call
   * @param {number} len Value byte length
   * @param {number} val Value to write
   * @returns {Writer} `this`
   */
  Writer.prototype.push = function push(fn, len, val) {
      this.tail = this.tail.next = new Op(fn, len, val);
      this.len += len;
      return this;
  };

  function writeByte(val, buf, pos) {
      buf[pos] = val & 255;
  }

  function writeVarint32(val, buf, pos) {
      while (val > 127) {
          buf[pos++] = val & 127 | 128;
          val >>>= 7;
      }
      buf[pos] = val;
  }

  /**
   * Constructs a new varint writer operation instance.
   * @classdesc Scheduled varint writer operation.
   * @extends Op
   * @constructor
   * @param {number} len Value byte length
   * @param {number} val Value to write
   * @ignore
   */
  function VarintOp(len, val) {
      this.len = len;
      this.next = undefined$1;
      this.val = val;
  }

  VarintOp.prototype = Object.create(Op.prototype);
  VarintOp.prototype.fn = writeVarint32;

  /**
   * Writes an unsigned 32 bit value as a varint.
   * @param {number} value Value to write
   * @returns {Writer} `this`
   */
  Writer.prototype.uint32 = function write_uint32(value) {
      // here, the call to this.push has been inlined and a varint specific Op subclass is used.
      // uint32 is by far the most frequently used operation and benefits significantly from this.
      this.len += (this.tail = this.tail.next = new VarintOp(
          (value = value >>> 0)
                  < 128       ? 1
          : value < 16384     ? 2
          : value < 2097152   ? 3
          : value < 268435456 ? 4
          :                     5,
      value)).len;
      return this;
  };

  /**
   * Writes a signed 32 bit value as a varint.
   * @function
   * @param {number} value Value to write
   * @returns {Writer} `this`
   */
  Writer.prototype.int32 = function write_int32(value) {
      return value < 0
          ? this.push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec
          : this.uint32(value);
  };

  /**
   * Writes a 32 bit value as a varint, zig-zag encoded.
   * @param {number} value Value to write
   * @returns {Writer} `this`
   */
  Writer.prototype.sint32 = function write_sint32(value) {
      return this.uint32((value << 1 ^ value >> 31) >>> 0);
  };

  function writeVarint64(val, buf, pos) {
      while (val.hi) {
          buf[pos++] = val.lo & 127 | 128;
          val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;
          val.hi >>>= 7;
      }
      while (val.lo > 127) {
          buf[pos++] = val.lo & 127 | 128;
          val.lo = val.lo >>> 7;
      }
      buf[pos++] = val.lo;
  }

  /**
   * Writes an unsigned 64 bit value as a varint.
   * @param {Long|number|string} value Value to write
   * @returns {Writer} `this`
   * @throws {TypeError} If `value` is a string and no long library is present.
   */
  Writer.prototype.uint64 = function write_uint64(value) {
      var bits = LongBits.from(value);
      return this.push(writeVarint64, bits.length(), bits);
  };

  /**
   * Writes a signed 64 bit value as a varint.
   * @function
   * @param {Long|number|string} value Value to write
   * @returns {Writer} `this`
   * @throws {TypeError} If `value` is a string and no long library is present.
   */
  Writer.prototype.int64 = Writer.prototype.uint64;

  /**
   * Writes a signed 64 bit value as a varint, zig-zag encoded.
   * @param {Long|number|string} value Value to write
   * @returns {Writer} `this`
   * @throws {TypeError} If `value` is a string and no long library is present.
   */
  Writer.prototype.sint64 = function write_sint64(value) {
      var bits = LongBits.from(value).zzEncode();
      return this.push(writeVarint64, bits.length(), bits);
  };

  /**
   * Writes a boolish value as a varint.
   * @param {boolean} value Value to write
   * @returns {Writer} `this`
   */
  Writer.prototype.bool = function write_bool(value) {
      return this.push(writeByte, 1, value ? 1 : 0);
  };

  function writeFixed32(val, buf, pos) {
      buf[pos    ] =  val         & 255;
      buf[pos + 1] =  val >>> 8   & 255;
      buf[pos + 2] =  val >>> 16  & 255;
      buf[pos + 3] =  val >>> 24;
  }

  /**
   * Writes an unsigned 32 bit value as fixed 32 bits.
   * @param {number} value Value to write
   * @returns {Writer} `this`
   */
  Writer.prototype.fixed32 = function write_fixed32(value) {
      return this.push(writeFixed32, 4, value >>> 0);
  };

  /**
   * Writes a signed 32 bit value as fixed 32 bits.
   * @function
   * @param {number} value Value to write
   * @returns {Writer} `this`
   */
  Writer.prototype.sfixed32 = Writer.prototype.fixed32;

  /**
   * Writes an unsigned 64 bit value as fixed 64 bits.
   * @param {Long|number|string} value Value to write
   * @returns {Writer} `this`
   * @throws {TypeError} If `value` is a string and no long library is present.
   */
  Writer.prototype.fixed64 = function write_fixed64(value) {
      var bits = LongBits.from(value);
      return this.push(writeFixed32, 4, bits.lo).push(writeFixed32, 4, bits.hi);
  };

  /**
   * Writes a signed 64 bit value as fixed 64 bits.
   * @function
   * @param {Long|number|string} value Value to write
   * @returns {Writer} `this`
   * @throws {TypeError} If `value` is a string and no long library is present.
   */
  Writer.prototype.sfixed64 = Writer.prototype.fixed64;

  /**
   * Writes a float (32 bit).
   * @function
   * @param {number} value Value to write
   * @returns {Writer} `this`
   */
  Writer.prototype.float = function write_float(value) {
      return this.push(util.float.writeFloatLE, 4, value);
  };

  /**
   * Writes a double (64 bit float).
   * @function
   * @param {number} value Value to write
   * @returns {Writer} `this`
   */
  Writer.prototype.double = function write_double(value) {
      return this.push(util.float.writeDoubleLE, 8, value);
  };

  var writeBytes = util.Array.prototype.set
      ? function writeBytes_set(val, buf, pos) {
          buf.set(val, pos); // also works for plain array values
      }
      /* istanbul ignore next */
      : function writeBytes_for(val, buf, pos) {
          for (var i = 0; i < val.length; ++i)
              buf[pos + i] = val[i];
      };

  /**
   * Writes a sequence of bytes.
   * @param {Uint8Array|string} value Buffer or base64 encoded string to write
   * @returns {Writer} `this`
   */
  Writer.prototype.bytes = function write_bytes(value) {
      var len = value.length >>> 0;
      if (!len)
          return this.push(writeByte, 1, 0);
      if (util.isString(value)) {
          var buf = Writer.alloc(len = base64.length(value));
          base64.decode(value, buf, 0);
          value = buf;
      }
      return this.uint32(len).push(writeBytes, len, value);
  };

  /**
   * Writes a string.
   * @param {string} value Value to write
   * @returns {Writer} `this`
   */
  Writer.prototype.string = function write_string(value) {
      var len = utf8.length(value);
      return len
          ? this.uint32(len).push(utf8.write, len, value)
          : this.push(writeByte, 1, 0);
  };

  /**
   * Forks this writer's state by pushing it to a stack.
   * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.
   * @returns {Writer} `this`
   */
  Writer.prototype.fork = function fork() {
      this.states = new State(this);
      this.head = this.tail = new Op(noop, 0, 0);
      this.len = 0;
      return this;
  };

  /**
   * Resets this instance to the last state.
   * @returns {Writer} `this`
   */
  Writer.prototype.reset = function reset() {
      if (this.states) {
          this.head   = this.states.head;
          this.tail   = this.states.tail;
          this.len    = this.states.len;
          this.states = this.states.next;
      } else {
          this.head = this.tail = new Op(noop, 0, 0);
          this.len  = 0;
      }
      return this;
  };

  /**
   * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.
   * @returns {Writer} `this`
   */
  Writer.prototype.ldelim = function ldelim() {
      var head = this.head,
          tail = this.tail,
          len  = this.len;
      this.reset().uint32(len);
      if (len) {
          this.tail.next = head.next; // skip noop
          this.tail = tail;
          this.len += len;
      }
      return this;
  };

  /**
   * Finishes the write operation.
   * @returns {Uint8Array} Finished buffer
   */
  Writer.prototype.finish = function finish() {
      var head = this.head.next, // skip noop
          buf  = this.constructor.alloc(this.len),
          pos  = 0;
      while (head) {
          head.fn(head.val, buf, pos);
          pos += head.len;
          head = head.next;
      }
      // this.head = this.tail = null;
      return buf;
  };

  Writer._configure = function(BufferWriter_) {
      BufferWriter = BufferWriter_;
  };

  },{"14":14}],16:[function(require,module,exports){
  module.exports = BufferWriter;

  // extends Writer
  var Writer = require(15);
  (BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;

  var util = require(14);

  var Buffer = util.Buffer;

  /**
   * Constructs a new buffer writer instance.
   * @classdesc Wire format writer using node buffers.
   * @extends Writer
   * @constructor
   */
  function BufferWriter() {
      Writer.call(this);
  }

  /**
   * Allocates a buffer of the specified size.
   * @param {number} size Buffer size
   * @returns {Buffer} Buffer
   */
  BufferWriter.alloc = function alloc_buffer(size) {
      return (BufferWriter.alloc = util._Buffer_allocUnsafe)(size);
  };

  var writeBytesBuffer = Buffer && Buffer.prototype instanceof Uint8Array && Buffer.prototype.set.name === "set"
      ? function writeBytesBuffer_set(val, buf, pos) {
          buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)
                             // also works for plain array values
      }
      /* istanbul ignore next */
      : function writeBytesBuffer_copy(val, buf, pos) {
          if (val.copy) // Buffer values
              val.copy(buf, pos, 0, val.length);
          else for (var i = 0; i < val.length;) // plain array values
              buf[pos++] = val[i++];
      };

  /**
   * @override
   */
  BufferWriter.prototype.bytes = function write_bytes_buffer(value) {
      if (util.isString(value))
          value = util._Buffer_from(value, "base64");
      var len = value.length >>> 0;
      this.uint32(len);
      if (len)
          this.push(writeBytesBuffer, len, value);
      return this;
  };

  function writeStringBuffer(val, buf, pos) {
      if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)
          util.utf8.write(val, buf, pos);
      else
          buf.utf8Write(val, pos);
  }

  /**
   * @override
   */
  BufferWriter.prototype.string = function write_string_buffer(value) {
      var len = Buffer.byteLength(value);
      this.uint32(len);
      if (len)
          this.push(writeStringBuffer, len, value);
      return this;
  };


  /**
   * Finishes the write operation.
   * @name BufferWriter#finish
   * @function
   * @returns {Buffer} Finished buffer
   */

  },{"14":14,"15":15}]},{},[8]);

  })(typeof window==="object"&&window||typeof self==="object"&&self||commonjsGlobal);

  });

  var protobuf$1 = /*#__PURE__*/_mergeNamespaces$1({
      __proto__: null,
      'default': protobuf
  }, [protobuf]);

  /**
   * @private
   */
  function isBitSet(bits, mask) {
    return (bits & mask) !== 0;
  }

  // Bitmask for checking tile properties
  const childrenBitmasks = [0x01, 0x02, 0x04, 0x08];
  const anyChildBitmask = 0x0f;
  const cacheFlagBitmask = 0x10; // True if there is a child subtree
  const imageBitmask = 0x40;
  const terrainBitmask = 0x80;

  /**
   * Contains information about each tile from a Google Earth Enterprise server
   *
   * @param {Number} bits Bitmask that contains the type of data and available children for each tile.
   * @param {Number} cnodeVersion Version of the request for subtree metadata.
   * @param {Number} imageryVersion Version of the request for imagery tile.
   * @param {Number} terrainVersion Version of the request for terrain tile.
   * @param {Number} imageryProvider Id of imagery provider.
   * @param {Number} terrainProvider Id of terrain provider.
   *
   * @private
   */
  function GoogleEarthEnterpriseTileInformation(
    bits,
    cnodeVersion,
    imageryVersion,
    terrainVersion,
    imageryProvider,
    terrainProvider
  ) {
    this._bits = bits;
    this.cnodeVersion = cnodeVersion;
    this.imageryVersion = imageryVersion;
    this.terrainVersion = terrainVersion;
    this.imageryProvider = imageryProvider;
    this.terrainProvider = terrainProvider;
    this.ancestorHasTerrain = false; // Set it later once we find its parent
    this.terrainState = undefined;
  }

  /**
   * Creates GoogleEarthEnterpriseTileInformation from an object
   *
   * @param {Object} info Object to be cloned
   * @param {GoogleEarthEnterpriseTileInformation} [result] The object onto which to store the result.
   * @returns {GoogleEarthEnterpriseTileInformation} The modified result parameter or a new GoogleEarthEnterpriseTileInformation instance if none was provided.
   */
  GoogleEarthEnterpriseTileInformation.clone = function (info, result) {
    if (!defined(result)) {
      result = new GoogleEarthEnterpriseTileInformation(
        info._bits,
        info.cnodeVersion,
        info.imageryVersion,
        info.terrainVersion,
        info.imageryProvider,
        info.terrainProvider
      );
    } else {
      result._bits = info._bits;
      result.cnodeVersion = info.cnodeVersion;
      result.imageryVersion = info.imageryVersion;
      result.terrainVersion = info.terrainVersion;
      result.imageryProvider = info.imageryProvider;
      result.terrainProvider = info.terrainProvider;
    }
    result.ancestorHasTerrain = info.ancestorHasTerrain;
    result.terrainState = info.terrainState;

    return result;
  };

  /**
   * Sets the parent for the tile
   *
   * @param {GoogleEarthEnterpriseTileInformation} parent Parent tile
   */
  GoogleEarthEnterpriseTileInformation.prototype.setParent = function (parent) {
    this.ancestorHasTerrain = parent.ancestorHasTerrain || this.hasTerrain();
  };

  /**
   * Gets whether a subtree is available
   *
   * @returns {Boolean} true if subtree is available, false otherwise.
   */
  GoogleEarthEnterpriseTileInformation.prototype.hasSubtree = function () {
    return isBitSet(this._bits, cacheFlagBitmask);
  };

  /**
   * Gets whether imagery is available
   *
   * @returns {Boolean} true if imagery is available, false otherwise.
   */
  GoogleEarthEnterpriseTileInformation.prototype.hasImagery = function () {
    return isBitSet(this._bits, imageBitmask);
  };

  /**
   * Gets whether terrain is available
   *
   * @returns {Boolean} true if terrain is available, false otherwise.
   */
  GoogleEarthEnterpriseTileInformation.prototype.hasTerrain = function () {
    return isBitSet(this._bits, terrainBitmask);
  };

  /**
   * Gets whether any children are present
   *
   * @returns {Boolean} true if any children are available, false otherwise.
   */
  GoogleEarthEnterpriseTileInformation.prototype.hasChildren = function () {
    return isBitSet(this._bits, anyChildBitmask);
  };

  /**
   * Gets whether a specified child is available
   *
   * @param {Number} index Index of child tile
   *
   * @returns {Boolean} true if child is available, false otherwise
   */
  GoogleEarthEnterpriseTileInformation.prototype.hasChild = function (index) {
    return isBitSet(this._bits, childrenBitmasks[index]);
  };

  /**
   * Gets bitmask containing children
   *
   * @returns {Number} Children bitmask
   */
  GoogleEarthEnterpriseTileInformation.prototype.getChildBitmask = function () {
    return this._bits & anyChildBitmask;
  };

  function stringToBuffer(str) {
    const len = str.length;
    const buffer = new ArrayBuffer(len);
    const ui8 = new Uint8Array(buffer);
    for (let i = 0; i < len; ++i) {
      ui8[i] = str.charCodeAt(i);
    }

    return buffer;
  }

  // Decodes packet with a key that has been around since the beginning of Google Earth Enterprise
  const defaultKey = stringToBuffer(
    "\x45\xf4\xbd\x0b\x79\xe2\x6a\x45\x22\x05\x92\x2c\x17\xcd\x06\x71\xf8\x49\x10\x46\x67\x51\x00\x42\x25\xc6\xe8\x61\x2c\x66\x29\x08\xc6\x34\xdc\x6a\x62\x25\x79\x0a\x77\x1d\x6d\x69\xd6\xf0\x9c\x6b\x93\xa1\xbd\x4e\x75\xe0\x41\x04\x5b\xdf\x40\x56\x0c\xd9\xbb\x72\x9b\x81\x7c\x10\x33\x53\xee\x4f\x6c\xd4\x71\x05\xb0\x7b\xc0\x7f\x45\x03\x56\x5a\xad\x77\x55\x65\x0b\x33\x92\x2a\xac\x19\x6c\x35\x14\xc5\x1d\x30\x73\xf8\x33\x3e\x6d\x46\x38\x4a\xb4\xdd\xf0\x2e\xdd\x17\x75\x16\xda\x8c\x44\x74\x22\x06\xfa\x61\x22\x0c\x33\x22\x53\x6f\xaf\x39\x44\x0b\x8c\x0e\x39\xd9\x39\x13\x4c\xb9\xbf\x7f\xab\x5c\x8c\x50\x5f\x9f\x22\x75\x78\x1f\xe9\x07\x71\x91\x68\x3b\xc1\xc4\x9b\x7f\xf0\x3c\x56\x71\x48\x82\x05\x27\x55\x66\x59\x4e\x65\x1d\x98\x75\xa3\x61\x46\x7d\x61\x3f\x15\x41\x00\x9f\x14\x06\xd7\xb4\x34\x4d\xce\x13\x87\x46\xb0\x1a\xd5\x05\x1c\xb8\x8a\x27\x7b\x8b\xdc\x2b\xbb\x4d\x67\x30\xc8\xd1\xf6\x5c\x8f\x50\xfa\x5b\x2f\x46\x9b\x6e\x35\x18\x2f\x27\x43\x2e\xeb\x0a\x0c\x5e\x10\x05\x10\xa5\x73\x1b\x65\x34\xe5\x6c\x2e\x6a\x43\x27\x63\x14\x23\x55\xa9\x3f\x71\x7b\x67\x43\x7d\x3a\xaf\xcd\xe2\x54\x55\x9c\xfd\x4b\xc6\xe2\x9f\x2f\x28\xed\xcb\x5c\xc6\x2d\x66\x07\x88\xa7\x3b\x2f\x18\x2a\x22\x4e\x0e\xb0\x6b\x2e\xdd\x0d\x95\x7d\x7d\x47\xba\x43\xb2\x11\xb2\x2b\x3e\x4d\xaa\x3e\x7d\xe6\xce\x49\x89\xc6\xe6\x78\x0c\x61\x31\x05\x2d\x01\xa4\x4f\xa5\x7e\x71\x20\x88\xec\x0d\x31\xe8\x4e\x0b\x00\x6e\x50\x68\x7d\x17\x3d\x08\x0d\x17\x95\xa6\x6e\xa3\x68\x97\x24\x5b\x6b\xf3\x17\x23\xf3\xb6\x73\xb3\x0d\x0b\x40\xc0\x9f\xd8\x04\x51\x5d\xfa\x1a\x17\x22\x2e\x15\x6a\xdf\x49\x00\xb9\xa0\x77\x55\xc6\xef\x10\x6a\xbf\x7b\x47\x4c\x7f\x83\x17\x05\xee\xdc\xdc\x46\x85\xa9\xad\x53\x07\x2b\x53\x34\x06\x07\xff\x14\x94\x59\x19\x02\xe4\x38\xe8\x31\x83\x4e\xb9\x58\x46\x6b\xcb\x2d\x23\x86\x92\x70\x00\x35\x88\x22\xcf\x31\xb2\x26\x2f\xe7\xc3\x75\x2d\x36\x2c\x72\x74\xb0\x23\x47\xb7\xd3\xd1\x26\x16\x85\x37\x72\xe2\x00\x8c\x44\xcf\x10\xda\x33\x2d\x1a\xde\x60\x86\x69\x23\x69\x2a\x7c\xcd\x4b\x51\x0d\x95\x54\x39\x77\x2e\x29\xea\x1b\xa6\x50\xa2\x6a\x8f\x6f\x50\x99\x5c\x3e\x54\xfb\xef\x50\x5b\x0b\x07\x45\x17\x89\x6d\x28\x13\x77\x37\x1d\xdb\x8e\x1e\x4a\x05\x66\x4a\x6f\x99\x20\xe5\x70\xe2\xb9\x71\x7e\x0c\x6d\x49\x04\x2d\x7a\xfe\x72\xc7\xf2\x59\x30\x8f\xbb\x02\x5d\x73\xe5\xc9\x20\xea\x78\xec\x20\x90\xf0\x8a\x7f\x42\x17\x7c\x47\x19\x60\xb0\x16\xbd\x26\xb7\x71\xb6\xc7\x9f\x0e\xd1\x33\x82\x3d\xd3\xab\xee\x63\x99\xc8\x2b\x53\xa0\x44\x5c\x71\x01\xc6\xcc\x44\x1f\x32\x4f\x3c\xca\xc0\x29\x3d\x52\xd3\x61\x19\x58\xa9\x7d\x65\xb4\xdc\xcf\x0d\xf4\x3d\xf1\x08\xa9\x42\xda\x23\x09\xd8\xbf\x5e\x50\x49\xf8\x4d\xc0\xcb\x47\x4c\x1c\x4f\xf7\x7b\x2b\xd8\x16\x18\xc5\x31\x92\x3b\xb5\x6f\xdc\x6c\x0d\x92\x88\x16\xd1\x9e\xdb\x3f\xe2\xe9\xda\x5f\xd4\x84\xe2\x46\x61\x5a\xde\x1c\x55\xcf\xa4\x00\xbe\xfd\xce\x67\xf1\x4a\x69\x1c\x97\xe6\x20\x48\xd8\x5d\x7f\x7e\xae\x71\x20\x0e\x4e\xae\xc0\x56\xa9\x91\x01\x3c\x82\x1d\x0f\x72\xe7\x76\xec\x29\x49\xd6\x5d\x2d\x83\xe3\xdb\x36\x06\xa9\x3b\x66\x13\x97\x87\x6a\xd5\xb6\x3d\x50\x5e\x52\xb9\x4b\xc7\x73\x57\x78\xc9\xf4\x2e\x59\x07\x95\x93\x6f\xd0\x4b\x17\x57\x19\x3e\x27\x27\xc7\x60\xdb\x3b\xed\x9a\x0e\x53\x44\x16\x3e\x3f\x8d\x92\x6d\x77\xa2\x0a\xeb\x3f\x52\xa8\xc6\x55\x5e\x31\x49\x37\x85\xf4\xc5\x1f\x26\x2d\xa9\x1c\xbf\x8b\x27\x54\xda\xc3\x6a\x20\xe5\x2a\x78\x04\xb0\xd6\x90\x70\x72\xaa\x8b\x68\xbd\x88\xf7\x02\x5f\x48\xb1\x7e\xc0\x58\x4c\x3f\x66\x1a\xf9\x3e\xe1\x65\xc0\x70\xa7\xcf\x38\x69\xaf\xf0\x56\x6c\x64\x49\x9c\x27\xad\x78\x74\x4f\xc2\x87\xde\x56\x39\x00\xda\x77\x0b\xcb\x2d\x1b\x89\xfb\x35\x4f\x02\xf5\x08\x51\x13\x60\xc1\x0a\x5a\x47\x4d\x26\x1c\x33\x30\x78\xda\xc0\x9c\x46\x47\xe2\x5b\x79\x60\x49\x6e\x37\x67\x53\x0a\x3e\xe9\xec\x46\x39\xb2\xf1\x34\x0d\xc6\x84\x53\x75\x6e\xe1\x0c\x59\xd9\x1e\xde\x29\x85\x10\x7b\x49\x49\xa5\x77\x79\xbe\x49\x56\x2e\x36\xe7\x0b\x3a\xbb\x4f\x03\x62\x7b\xd2\x4d\x31\x95\x2f\xbd\x38\x7b\xa8\x4f\x21\xe1\xec\x46\x70\x76\x95\x7d\x29\x22\x78\x88\x0a\x90\xdd\x9d\x5c\xda\xde\x19\x51\xcf\xf0\xfc\x59\x52\x65\x7c\x33\x13\xdf\xf3\x48\xda\xbb\x2a\x75\xdb\x60\xb2\x02\x15\xd4\xfc\x19\xed\x1b\xec\x7f\x35\xa8\xff\x28\x31\x07\x2d\x12\xc8\xdc\x88\x46\x7c\x8a\x5b\x22"
  );

  /**
   * Provides metadata using the Google Earth Enterprise REST API. This is used by the GoogleEarthEnterpriseImageryProvider
   *  and GoogleEarthEnterpriseTerrainProvider to share metadata requests.
   *
   * @alias GoogleEarthEnterpriseMetadata
   * @constructor
   *
   * @param {Resource|String} resourceOrUrl The url of the Google Earth Enterprise server hosting the imagery
   *
   * @see GoogleEarthEnterpriseImageryProvider
   * @see GoogleEarthEnterpriseTerrainProvider
   *
   */
  function GoogleEarthEnterpriseMetadata(resourceOrUrl) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("resourceOrUrl", resourceOrUrl);
    //>>includeEnd('debug');

    let url = resourceOrUrl;

    if (typeof url !== "string" && !(url instanceof Resource)) {
      //>>includeStart('debug', pragmas.debug);
      Check.typeOf.string("resourceOrUrl.url", resourceOrUrl.url);
      //>>includeEnd('debug');

      url = resourceOrUrl.url;
    }

    const resource = Resource.createIfNeeded(url);
    resource.appendForwardSlash();
    this._resource = resource;

    /**
     * True if imagery is available.
     * @type {Boolean}
     * @default true
     */
    this.imageryPresent = true;

    /**
     * True if imagery is sent as a protocol buffer, false if sent as plain images. If undefined we will try both.
     * @type {Boolean}
     * @default undefined
     */
    this.protoImagery = undefined;

    /**
     * True if terrain is available.
     * @type {Boolean}
     * @default true
     */
    this.terrainPresent = true;

    /**
     * Exponent used to compute constant to calculate negative height values.
     * @type {Number}
     * @default 32
     */
    this.negativeAltitudeExponentBias = 32;

    /**
     * Threshold where any numbers smaller are actually negative values. They are multiplied by -2^negativeAltitudeExponentBias.
     * @type {Number}
     * @default EPSILON12
     */
    this.negativeAltitudeThreshold = CesiumMath.EPSILON12;

    /**
     * Dictionary of provider id to copyright strings.
     * @type {Object}
     * @default {}
     */
    this.providers = {};

    /**
     * Key used to decode packets
     * @type {ArrayBuffer}
     */
    this.key = undefined;

    this._quadPacketVersion = 1;

    this._tileInfo = {};
    this._subtreePromises = {};

    const that = this;
    this._readyPromise = requestDbRoot(this)
      .then(function () {
        return that.getQuadTreePacket("", that._quadPacketVersion);
      })
      .then(function () {
        return true;
      })
      .catch(function (e) {
        const message = `An error occurred while accessing ${
        getMetadataResource(that, "", 1).url
      }.`;
        return Promise.reject(new RuntimeError(message));
      });
  }

  Object.defineProperties(GoogleEarthEnterpriseMetadata.prototype, {
    /**
     * Gets the name of the Google Earth Enterprise server.
     * @memberof GoogleEarthEnterpriseMetadata.prototype
     * @type {String}
     * @readonly
     */
    url: {
      get: function () {
        return this._resource.url;
      },
    },

    /**
     * Gets the proxy used for metadata requests.
     * @memberof GoogleEarthEnterpriseMetadata.prototype
     * @type {Proxy}
     * @readonly
     */
    proxy: {
      get: function () {
        return this._resource.proxy;
      },
    },

    /**
     * Gets the resource used for metadata requests.
     * @memberof GoogleEarthEnterpriseMetadata.prototype
     * @type {Resource}
     * @readonly
     */
    resource: {
      get: function () {
        return this._resource;
      },
    },

    /**
     * Gets a promise that resolves to true when the metadata is ready for use.
     * @memberof GoogleEarthEnterpriseMetadata.prototype
     * @type {Promise.<Boolean>}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._readyPromise;
      },
    },
  });

  /**
   * Converts a tiles (x, y, level) position into a quadkey used to request an image
   * from a Google Earth Enterprise server.
   *
   * @param {Number} x The tile's x coordinate.
   * @param {Number} y The tile's y coordinate.
   * @param {Number} level The tile's zoom level.
   *
   * @see GoogleEarthEnterpriseMetadata#quadKeyToTileXY
   */
  GoogleEarthEnterpriseMetadata.tileXYToQuadKey = function (x, y, level) {
    let quadkey = "";
    for (let i = level; i >= 0; --i) {
      const bitmask = 1 << i;
      let digit = 0;

      // Tile Layout
      // ___ ___
      //|   |   |
      //| 3 | 2 |
      //|-------|
      //| 0 | 1 |
      //|___|___|
      //

      if (!isBitSet(y, bitmask)) {
        // Top Row
        digit |= 2;
        if (!isBitSet(x, bitmask)) {
          // Right to left
          digit |= 1;
        }
      } else if (isBitSet(x, bitmask)) {
        // Left to right
        digit |= 1;
      }

      quadkey += digit;
    }
    return quadkey;
  };

  /**
   * Converts a tile's quadkey used to request an image from a Google Earth Enterprise server into the
   * (x, y, level) position.
   *
   * @param {String} quadkey The tile's quad key
   *
   * @see GoogleEarthEnterpriseMetadata#tileXYToQuadKey
   */
  GoogleEarthEnterpriseMetadata.quadKeyToTileXY = function (quadkey) {
    let x = 0;
    let y = 0;
    const level = quadkey.length - 1;
    for (let i = level; i >= 0; --i) {
      const bitmask = 1 << i;
      const digit = +quadkey[level - i];

      if (isBitSet(digit, 2)) {
        // Top Row
        if (!isBitSet(digit, 1)) {
          // // Right to left
          x |= bitmask;
        }
      } else {
        y |= bitmask;
        if (isBitSet(digit, 1)) {
          // Left to right
          x |= bitmask;
        }
      }
    }
    return {
      x: x,
      y: y,
      level: level,
    };
  };

  GoogleEarthEnterpriseMetadata.prototype.isValid = function (quadKey) {
    let info = this.getTileInformationFromQuadKey(quadKey);
    if (defined(info)) {
      return info !== null;
    }

    let valid = true;
    let q = quadKey;
    let last;
    while (q.length > 1) {
      last = q.substring(q.length - 1);
      q = q.substring(0, q.length - 1);
      info = this.getTileInformationFromQuadKey(q);
      if (defined(info)) {
        if (!info.hasSubtree() && !info.hasChild(parseInt(last))) {
          // We have no subtree or child available at some point in this node's ancestry
          valid = false;
        }

        break;
      } else if (info === null) {
        // Some node in the ancestry was loaded and said there wasn't a subtree
        valid = false;
        break;
      }
    }

    return valid;
  };

  const taskProcessor$1 = new TaskProcessor("decodeGoogleEarthEnterprisePacket");

  /**
   * Retrieves a Google Earth Enterprise quadtree packet.
   *
   * @param {String} [quadKey=''] The quadkey to retrieve the packet for.
   * @param {Number} [version=1] The cnode version to be used in the request.
   * @param {Request} [request] The request object. Intended for internal use only.
   *
   * @private
   */
  GoogleEarthEnterpriseMetadata.prototype.getQuadTreePacket = function (
    quadKey,
    version,
    request
  ) {
    version = defaultValue(version, 1);
    quadKey = defaultValue(quadKey, "");
    const resource = getMetadataResource(this, quadKey, version, request);

    const promise = resource.fetchArrayBuffer();

    if (!defined(promise)) {
      return undefined; // Throttled
    }

    const tileInfo = this._tileInfo;
    const key = this.key;
    return promise.then(function (metadata) {
      const decodePromise = taskProcessor$1.scheduleTask(
        {
          buffer: metadata,
          quadKey: quadKey,
          type: "Metadata",
          key: key,
        },
        [metadata]
      );

      return decodePromise.then(function (result) {
        let root;
        let topLevelKeyLength = -1;
        if (quadKey !== "") {
          // Root tile has no data except children bits, so put them into the tile info
          topLevelKeyLength = quadKey.length + 1;
          const top = result[quadKey];
          root = tileInfo[quadKey];
          root._bits |= top._bits;

          delete result[quadKey];
        }

        // Copy the resulting objects into tileInfo
        // Make sure we start with shorter quadkeys first, so we know the parents have
        //  already been processed. Otherwise we can lose ancestorHasTerrain along the way.
        const keys = Object.keys(result);
        keys.sort(function (a, b) {
          return a.length - b.length;
        });
        const keysLength = keys.length;
        for (let i = 0; i < keysLength; ++i) {
          const key = keys[i];
          const r = result[key];
          if (r !== null) {
            const info = GoogleEarthEnterpriseTileInformation.clone(result[key]);
            const keyLength = key.length;
            if (keyLength === topLevelKeyLength) {
              info.setParent(root);
            } else if (keyLength > 1) {
              const parent = tileInfo[key.substring(0, key.length - 1)];
              info.setParent(parent);
            }
            tileInfo[key] = info;
          } else {
            tileInfo[key] = null;
          }
        }
      });
    });
  };

  /**
   * Populates the metadata subtree down to the specified tile.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level.
   * @param {Request} [request] The request object. Intended for internal use only.
   *
   * @returns {Promise<GoogleEarthEnterpriseTileInformation>} A promise that resolves to the tile info for the requested quad key
   *
   * @private
   */
  GoogleEarthEnterpriseMetadata.prototype.populateSubtree = function (
    x,
    y,
    level,
    request
  ) {
    const quadkey = GoogleEarthEnterpriseMetadata.tileXYToQuadKey(x, y, level);
    return populateSubtree(this, quadkey, request);
  };

  function populateSubtree(that, quadKey, request) {
    const tileInfo = that._tileInfo;
    let q = quadKey;
    let t = tileInfo[q];
    // If we have tileInfo make sure sure it is not a node with a subtree that's not loaded
    if (defined(t) && (!t.hasSubtree() || t.hasChildren())) {
      return t;
    }

    while (t === undefined && q.length > 1) {
      q = q.substring(0, q.length - 1);
      t = tileInfo[q];
    }

    let subtreeRequest;
    const subtreePromises = that._subtreePromises;
    let promise = subtreePromises[q];
    if (defined(promise)) {
      return promise.then(function () {
        // Recursively call this in case we need multiple subtree requests
        subtreeRequest = new Request({
          throttle: request.throttle,
          throttleByServer: request.throttleByServer,
          type: request.type,
          priorityFunction: request.priorityFunction,
        });
        return populateSubtree(that, quadKey, subtreeRequest);
      });
    }

    // t is either
    //   null so one of its parents was a leaf node, so this tile doesn't exist
    //   exists but doesn't have a subtree to request
    //   undefined so no parent exists - this shouldn't ever happen once the provider is ready
    if (!defined(t) || !t.hasSubtree()) {
      return Promise.reject(
        new RuntimeError(`Couldn't load metadata for tile ${quadKey}`)
      );
    }

    // We need to split up the promise here because when will execute syncronously if getQuadTreePacket
    //  is already resolved (like in the tests), so subtreePromises will never get cleared out.
    //  Only the initial request will also remove the promise from subtreePromises.
    promise = that.getQuadTreePacket(q, t.cnodeVersion, request);
    if (!defined(promise)) {
      return undefined;
    }
    subtreePromises[q] = promise;

    return promise
      .then(function () {
        // Recursively call this in case we need multiple subtree requests
        subtreeRequest = new Request({
          throttle: request.throttle,
          throttleByServer: request.throttleByServer,
          type: request.type,
          priorityFunction: request.priorityFunction,
        });
        return populateSubtree(that, quadKey, subtreeRequest);
      })
      .finally(function () {
        delete subtreePromises[q];
      });
  }

  /**
   * Gets information about a tile
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level.
   * @returns {GoogleEarthEnterpriseTileInformation|undefined} Information about the tile or undefined if it isn't loaded.
   *
   * @private
   */
  GoogleEarthEnterpriseMetadata.prototype.getTileInformation = function (
    x,
    y,
    level
  ) {
    const quadkey = GoogleEarthEnterpriseMetadata.tileXYToQuadKey(x, y, level);
    return this._tileInfo[quadkey];
  };

  /**
   * Gets information about a tile from a quadKey
   *
   * @param {String} quadkey The quadkey for the tile
   * @returns {GoogleEarthEnterpriseTileInformation|undefined} Information about the tile or undefined if it isn't loaded.
   *
   * @private
   */
  GoogleEarthEnterpriseMetadata.prototype.getTileInformationFromQuadKey = function (
    quadkey
  ) {
    return this._tileInfo[quadkey];
  };

  function getMetadataResource(that, quadKey, version, request) {
    return that._resource.getDerivedResource({
      url: `flatfile?q2-0${quadKey}-q.${version.toString()}`,
      request: request,
    });
  }

  let dbrootParser;
  let dbrootParserPromise;
  function requestDbRoot(that) {
    const resource = that._resource.getDerivedResource({
      url: "dbRoot.v5",
      queryParameters: {
        output: "proto",
      },
    });

    if (!defined(dbrootParserPromise)) {
      const url = buildModuleUrl("ThirdParty/google-earth-dbroot-parser.js");
      const oldValue = window.cesiumGoogleEarthDbRootParser;
      dbrootParserPromise = loadAndExecuteScript(url).then(function () {
        dbrootParser = window.cesiumGoogleEarthDbRootParser(protobuf$1);
        if (defined(oldValue)) {
          window.cesiumGoogleEarthDbRootParser = oldValue;
        } else {
          delete window.cesiumGoogleEarthDbRootParser;
        }
      });
    }

    return dbrootParserPromise
      .then(function () {
        return resource.fetchArrayBuffer();
      })
      .then(function (buf) {
        const encryptedDbRootProto = dbrootParser.EncryptedDbRootProto.decode(
          new Uint8Array(buf)
        );

        let byteArray = encryptedDbRootProto.encryptionData;
        let offset = byteArray.byteOffset;
        let end = offset + byteArray.byteLength;
        const key = (that.key = byteArray.buffer.slice(offset, end));

        byteArray = encryptedDbRootProto.dbrootData;
        offset = byteArray.byteOffset;
        end = offset + byteArray.byteLength;
        const dbRootCompressed = byteArray.buffer.slice(offset, end);
        return taskProcessor$1.scheduleTask(
          {
            buffer: dbRootCompressed,
            type: "DbRoot",
            key: key,
          },
          [dbRootCompressed]
        );
      })
      .then(function (result) {
        const dbRoot = dbrootParser.DbRootProto.decode(
          new Uint8Array(result.buffer)
        );
        that.imageryPresent = defaultValue(
          dbRoot.imageryPresent,
          that.imageryPresent
        );
        that.protoImagery = dbRoot.protoImagery;
        that.terrainPresent = defaultValue(
          dbRoot.terrainPresent,
          that.terrainPresent
        );
        if (defined(dbRoot.endSnippet) && defined(dbRoot.endSnippet.model)) {
          const model = dbRoot.endSnippet.model;
          that.negativeAltitudeExponentBias = defaultValue(
            model.negativeAltitudeExponentBias,
            that.negativeAltitudeExponentBias
          );
          that.negativeAltitudeThreshold = defaultValue(
            model.compressedNegativeAltitudeThreshold,
            that.negativeAltitudeThreshold
          );
        }
        if (defined(dbRoot.databaseVersion)) {
          that._quadPacketVersion = defaultValue(
            dbRoot.databaseVersion.quadtreeVersion,
            that._quadPacketVersion
          );
        }
        const providers = that.providers;
        const providerInfo = defaultValue(dbRoot.providerInfo, []);
        const count = providerInfo.length;
        for (let i = 0; i < count; ++i) {
          const provider = providerInfo[i];
          const copyrightString = provider.copyrightString;
          if (defined(copyrightString)) {
            providers[provider.providerId] = new Credit(copyrightString.value);
          }
        }
      })
      .catch(function () {
        // Just eat the error and use the default values.
        console.log(`Failed to retrieve ${resource.url}. Using defaults.`);
        that.key = defaultKey;
      });
  }

  /**
   * Terrain data for a single tile from a Google Earth Enterprise server.
   *
   * @alias GoogleEarthEnterpriseTerrainData
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {ArrayBuffer} options.buffer The buffer containing terrain data.
   * @param {Number} options.negativeAltitudeExponentBias Multiplier for negative terrain heights that are encoded as very small positive values.
   * @param {Number} options.negativeElevationThreshold Threshold for negative values
   * @param {Number} [options.childTileMask=15] A bit mask indicating which of this tile's four children exist.
   *                 If a child's bit is set, geometry will be requested for that tile as well when it
   *                 is needed.  If the bit is cleared, the child tile is not requested and geometry is
   *                 instead upsampled from the parent.  The bit values are as follows:
   *                 <table>
   *                  <tr><th>Bit Position</th><th>Bit Value</th><th>Child Tile</th></tr>
   *                  <tr><td>0</td><td>1</td><td>Southwest</td></tr>
   *                  <tr><td>1</td><td>2</td><td>Southeast</td></tr>
   *                  <tr><td>2</td><td>4</td><td>Northeast</td></tr>
   *                  <tr><td>3</td><td>8</td><td>Northwest</td></tr>
   *                 </table>
   * @param {Boolean} [options.createdByUpsampling=false] True if this instance was created by upsampling another instance;
   *                  otherwise, false.
   * @param {Credit[]} [options.credits] Array of credits for this tile.
   *
   *
   * @example
   * const buffer = ...
   * const childTileMask = ...
   * const terrainData = new Cesium.GoogleEarthEnterpriseTerrainData({
   *   buffer : heightBuffer,
   *   childTileMask : childTileMask
   * });
   *
   * @see TerrainData
   * @see HeightmapTerrainData
   * @see QuantizedMeshTerrainData
   */
  function GoogleEarthEnterpriseTerrainData(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.buffer", options.buffer);
    Check.typeOf.number(
      "options.negativeAltitudeExponentBias",
      options.negativeAltitudeExponentBias
    );
    Check.typeOf.number(
      "options.negativeElevationThreshold",
      options.negativeElevationThreshold
    );
    //>>includeEnd('debug');

    this._buffer = options.buffer;
    this._credits = options.credits;
    this._negativeAltitudeExponentBias = options.negativeAltitudeExponentBias;
    this._negativeElevationThreshold = options.negativeElevationThreshold;

    // Convert from google layout to layout of other providers
    // 3 2 -> 2 3
    // 0 1 -> 0 1
    const googleChildTileMask = defaultValue(options.childTileMask, 15);
    let childTileMask = googleChildTileMask & 3; // Bottom row is identical
    childTileMask |= googleChildTileMask & 4 ? 8 : 0; // NE
    childTileMask |= googleChildTileMask & 8 ? 4 : 0; // NW

    this._childTileMask = childTileMask;

    this._createdByUpsampling = defaultValue(options.createdByUpsampling, false);

    this._skirtHeight = undefined;
    this._bufferType = this._buffer.constructor;
    this._mesh = undefined;
    this._minimumHeight = undefined;
    this._maximumHeight = undefined;
  }

  Object.defineProperties(GoogleEarthEnterpriseTerrainData.prototype, {
    /**
     * An array of credits for this tile
     * @memberof GoogleEarthEnterpriseTerrainData.prototype
     * @type {Credit[]}
     */
    credits: {
      get: function () {
        return this._credits;
      },
    },
    /**
     * The water mask included in this terrain data, if any.  A water mask is a rectangular
     * Uint8Array or image where a value of 255 indicates water and a value of 0 indicates land.
     * Values in between 0 and 255 are allowed as well to smoothly blend between land and water.
     * @memberof GoogleEarthEnterpriseTerrainData.prototype
     * @type {Uint8Array|HTMLImageElement|HTMLCanvasElement}
     */
    waterMask: {
      get: function () {
        return undefined;
      },
    },
  });

  const createMeshTaskName = "createVerticesFromGoogleEarthEnterpriseBuffer";
  const createMeshTaskProcessorNoThrottle = new TaskProcessor(createMeshTaskName);
  const createMeshTaskProcessorThrottle = new TaskProcessor(
    createMeshTaskName,
    TerrainData.maximumAsynchronousTasks
  );

  const nativeRectangleScratch = new Rectangle();
  const rectangleScratch$5 = new Rectangle();

  /**
   * Creates a {@link TerrainMesh} from this terrain data.
   *
   * @private
   *
   * @param {Object} options Object with the following properties:
   * @param {TilingScheme} options.tilingScheme The tiling scheme to which this tile belongs.
   * @param {Number} options.x The X coordinate of the tile for which to create the terrain data.
   * @param {Number} options.y The Y coordinate of the tile for which to create the terrain data.
   * @param {Number} options.level The level of the tile for which to create the terrain data.
   * @param {Number} [options.exaggeration=1.0] The scale used to exaggerate the terrain.
   * @param {Number} [options.exaggerationRelativeHeight=0.0] The height from which terrain is exaggerated.
   * @param {Boolean} [options.throttle=true] If true, indicates that this operation will need to be retried if too many asynchronous mesh creations are already in progress.
   * @returns {Promise.<TerrainMesh>|undefined} A promise for the terrain mesh, or undefined if too many
   *          asynchronous mesh creations are already in progress and the operation should
   *          be retried later.
   */
  GoogleEarthEnterpriseTerrainData.prototype.createMesh = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.tilingScheme", options.tilingScheme);
    Check.typeOf.number("options.x", options.x);
    Check.typeOf.number("options.y", options.y);
    Check.typeOf.number("options.level", options.level);
    //>>includeEnd('debug');

    const tilingScheme = options.tilingScheme;
    const x = options.x;
    const y = options.y;
    const level = options.level;
    const exaggeration = defaultValue(options.exaggeration, 1.0);
    const exaggerationRelativeHeight = defaultValue(
      options.exaggerationRelativeHeight,
      0.0
    );
    const throttle = defaultValue(options.throttle, true);

    const ellipsoid = tilingScheme.ellipsoid;
    tilingScheme.tileXYToNativeRectangle(x, y, level, nativeRectangleScratch);
    tilingScheme.tileXYToRectangle(x, y, level, rectangleScratch$5);

    // Compute the center of the tile for RTC rendering.
    const center = ellipsoid.cartographicToCartesian(
      Rectangle.center(rectangleScratch$5)
    );

    const levelZeroMaxError = 40075.16; // From Google's Doc
    const thisLevelMaxError = levelZeroMaxError / (1 << level);
    this._skirtHeight = Math.min(thisLevelMaxError * 8.0, 1000.0);

    const createMeshTaskProcessor = throttle
      ? createMeshTaskProcessorThrottle
      : createMeshTaskProcessorNoThrottle;

    const verticesPromise = createMeshTaskProcessor.scheduleTask({
      buffer: this._buffer,
      nativeRectangle: nativeRectangleScratch,
      rectangle: rectangleScratch$5,
      relativeToCenter: center,
      ellipsoid: ellipsoid,
      skirtHeight: this._skirtHeight,
      exaggeration: exaggeration,
      exaggerationRelativeHeight: exaggerationRelativeHeight,
      includeWebMercatorT: true,
      negativeAltitudeExponentBias: this._negativeAltitudeExponentBias,
      negativeElevationThreshold: this._negativeElevationThreshold,
    });

    if (!defined(verticesPromise)) {
      // Postponed
      return undefined;
    }

    const that = this;
    return verticesPromise.then(function (result) {
      // Clone complex result objects because the transfer from the web worker
      // has stripped them down to JSON-style objects.
      that._mesh = new TerrainMesh(
        center,
        new Float32Array(result.vertices),
        new Uint16Array(result.indices),
        result.indexCountWithoutSkirts,
        result.vertexCountWithoutSkirts,
        result.minimumHeight,
        result.maximumHeight,
        BoundingSphere.clone(result.boundingSphere3D),
        Cartesian3.clone(result.occludeePointInScaledSpace),
        result.numberOfAttributes,
        OrientedBoundingBox.clone(result.orientedBoundingBox),
        TerrainEncoding.clone(result.encoding),
        result.westIndicesSouthToNorth,
        result.southIndicesEastToWest,
        result.eastIndicesNorthToSouth,
        result.northIndicesWestToEast
      );

      that._minimumHeight = result.minimumHeight;
      that._maximumHeight = result.maximumHeight;

      // Free memory received from server after mesh is created.
      that._buffer = undefined;
      return that._mesh;
    });
  };

  /**
   * Computes the terrain height at a specified longitude and latitude.
   *
   * @param {Rectangle} rectangle The rectangle covered by this terrain data.
   * @param {Number} longitude The longitude in radians.
   * @param {Number} latitude The latitude in radians.
   * @returns {Number} The terrain height at the specified position.  If the position
   *          is outside the rectangle, this method will extrapolate the height, which is likely to be wildly
   *          incorrect for positions far outside the rectangle.
   */
  GoogleEarthEnterpriseTerrainData.prototype.interpolateHeight = function (
    rectangle,
    longitude,
    latitude
  ) {
    const u = CesiumMath.clamp(
      (longitude - rectangle.west) / rectangle.width,
      0.0,
      1.0
    );
    const v = CesiumMath.clamp(
      (latitude - rectangle.south) / rectangle.height,
      0.0,
      1.0
    );

    if (!defined(this._mesh)) {
      return interpolateHeight(this, u, v, rectangle);
    }

    return interpolateMeshHeight(this, u, v);
  };

  const upsampleTaskProcessor = new TaskProcessor(
    "upsampleQuantizedTerrainMesh",
    TerrainData.maximumAsynchronousTasks
  );

  /**
   * Upsamples this terrain data for use by a descendant tile.  The resulting instance will contain a subset of the
   * height samples in this instance, interpolated if necessary.
   *
   * @param {TilingScheme} tilingScheme The tiling scheme of this terrain data.
   * @param {Number} thisX The X coordinate of this tile in the tiling scheme.
   * @param {Number} thisY The Y coordinate of this tile in the tiling scheme.
   * @param {Number} thisLevel The level of this tile in the tiling scheme.
   * @param {Number} descendantX The X coordinate within the tiling scheme of the descendant tile for which we are upsampling.
   * @param {Number} descendantY The Y coordinate within the tiling scheme of the descendant tile for which we are upsampling.
   * @param {Number} descendantLevel The level within the tiling scheme of the descendant tile for which we are upsampling.
   * @returns {Promise.<HeightmapTerrainData>|undefined} A promise for upsampled heightmap terrain data for the descendant tile,
   *          or undefined if too many asynchronous upsample operations are in progress and the request has been
   *          deferred.
   */
  GoogleEarthEnterpriseTerrainData.prototype.upsample = function (
    tilingScheme,
    thisX,
    thisY,
    thisLevel,
    descendantX,
    descendantY,
    descendantLevel
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("tilingScheme", tilingScheme);
    Check.typeOf.number("thisX", thisX);
    Check.typeOf.number("thisY", thisY);
    Check.typeOf.number("thisLevel", thisLevel);
    Check.typeOf.number("descendantX", descendantX);
    Check.typeOf.number("descendantY", descendantY);
    Check.typeOf.number("descendantLevel", descendantLevel);
    const levelDifference = descendantLevel - thisLevel;
    if (levelDifference > 1) {
      throw new DeveloperError(
        "Upsampling through more than one level at a time is not currently supported."
      );
    }
    //>>includeEnd('debug');

    const mesh = this._mesh;
    if (!defined(this._mesh)) {
      return undefined;
    }

    const isEastChild = thisX * 2 !== descendantX;
    const isNorthChild = thisY * 2 === descendantY;

    const ellipsoid = tilingScheme.ellipsoid;
    const childRectangle = tilingScheme.tileXYToRectangle(
      descendantX,
      descendantY,
      descendantLevel
    );

    const upsamplePromise = upsampleTaskProcessor.scheduleTask({
      vertices: mesh.vertices,
      indices: mesh.indices,
      indexCountWithoutSkirts: mesh.indexCountWithoutSkirts,
      vertexCountWithoutSkirts: mesh.vertexCountWithoutSkirts,
      encoding: mesh.encoding,
      minimumHeight: this._minimumHeight,
      maximumHeight: this._maximumHeight,
      isEastChild: isEastChild,
      isNorthChild: isNorthChild,
      childRectangle: childRectangle,
      ellipsoid: ellipsoid,
    });

    if (!defined(upsamplePromise)) {
      // Postponed
      return undefined;
    }

    const that = this;
    return upsamplePromise.then(function (result) {
      const quantizedVertices = new Uint16Array(result.vertices);
      const indicesTypedArray = IndexDatatype$1.createTypedArray(
        quantizedVertices.length / 3,
        result.indices
      );

      const skirtHeight = that._skirtHeight;

      // Use QuantizedMeshTerrainData since we have what we need already parsed
      return new QuantizedMeshTerrainData({
        quantizedVertices: quantizedVertices,
        indices: indicesTypedArray,
        minimumHeight: result.minimumHeight,
        maximumHeight: result.maximumHeight,
        boundingSphere: BoundingSphere.clone(result.boundingSphere),
        orientedBoundingBox: OrientedBoundingBox.clone(
          result.orientedBoundingBox
        ),
        horizonOcclusionPoint: Cartesian3.clone(result.horizonOcclusionPoint),
        westIndices: result.westIndices,
        southIndices: result.southIndices,
        eastIndices: result.eastIndices,
        northIndices: result.northIndices,
        westSkirtHeight: skirtHeight,
        southSkirtHeight: skirtHeight,
        eastSkirtHeight: skirtHeight,
        northSkirtHeight: skirtHeight,
        childTileMask: 0,
        createdByUpsampling: true,
        credits: that._credits,
      });
    });
  };

  /**
   * Determines if a given child tile is available, based on the
   * {@link HeightmapTerrainData.childTileMask}.  The given child tile coordinates are assumed
   * to be one of the four children of this tile.  If non-child tile coordinates are
   * given, the availability of the southeast child tile is returned.
   *
   * @param {Number} thisX The tile X coordinate of this (the parent) tile.
   * @param {Number} thisY The tile Y coordinate of this (the parent) tile.
   * @param {Number} childX The tile X coordinate of the child tile to check for availability.
   * @param {Number} childY The tile Y coordinate of the child tile to check for availability.
   * @returns {Boolean} True if the child tile is available; otherwise, false.
   */
  GoogleEarthEnterpriseTerrainData.prototype.isChildAvailable = function (
    thisX,
    thisY,
    childX,
    childY
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("thisX", thisX);
    Check.typeOf.number("thisY", thisY);
    Check.typeOf.number("childX", childX);
    Check.typeOf.number("childY", childY);
    //>>includeEnd('debug');

    let bitNumber = 2; // northwest child
    if (childX !== thisX * 2) {
      ++bitNumber; // east child
    }
    if (childY !== thisY * 2) {
      bitNumber -= 2; // south child
    }

    return (this._childTileMask & (1 << bitNumber)) !== 0;
  };

  /**
   * Gets a value indicating whether or not this terrain data was created by upsampling lower resolution
   * terrain data.  If this value is false, the data was obtained from some other source, such
   * as by downloading it from a remote server.  This method should return true for instances
   * returned from a call to {@link HeightmapTerrainData#upsample}.
   *
   * @returns {Boolean} True if this instance was created by upsampling; otherwise, false.
   */
  GoogleEarthEnterpriseTerrainData.prototype.wasCreatedByUpsampling = function () {
    return this._createdByUpsampling;
  };

  const texCoordScratch0 = new Cartesian2();
  const texCoordScratch1 = new Cartesian2();
  const texCoordScratch2 = new Cartesian2();
  const barycentricCoordinateScratch = new Cartesian3();

  function interpolateMeshHeight(terrainData, u, v) {
    const mesh = terrainData._mesh;
    const vertices = mesh.vertices;
    const encoding = mesh.encoding;
    const indices = mesh.indices;

    for (let i = 0, len = indices.length; i < len; i += 3) {
      const i0 = indices[i];
      const i1 = indices[i + 1];
      const i2 = indices[i + 2];

      const uv0 = encoding.decodeTextureCoordinates(
        vertices,
        i0,
        texCoordScratch0
      );
      const uv1 = encoding.decodeTextureCoordinates(
        vertices,
        i1,
        texCoordScratch1
      );
      const uv2 = encoding.decodeTextureCoordinates(
        vertices,
        i2,
        texCoordScratch2
      );

      const barycentric = Intersections2D.computeBarycentricCoordinates(
        u,
        v,
        uv0.x,
        uv0.y,
        uv1.x,
        uv1.y,
        uv2.x,
        uv2.y,
        barycentricCoordinateScratch
      );
      if (
        barycentric.x >= -1e-15 &&
        barycentric.y >= -1e-15 &&
        barycentric.z >= -1e-15
      ) {
        const h0 = encoding.decodeHeight(vertices, i0);
        const h1 = encoding.decodeHeight(vertices, i1);
        const h2 = encoding.decodeHeight(vertices, i2);
        return barycentric.x * h0 + barycentric.y * h1 + barycentric.z * h2;
      }
    }

    // Position does not lie in any triangle in this mesh.
    return undefined;
  }

  const sizeOfUint16 = Uint16Array.BYTES_PER_ELEMENT;
  const sizeOfUint32$7 = Uint32Array.BYTES_PER_ELEMENT;
  const sizeOfInt32 = Int32Array.BYTES_PER_ELEMENT;
  const sizeOfFloat = Float32Array.BYTES_PER_ELEMENT;
  const sizeOfDouble = Float64Array.BYTES_PER_ELEMENT;

  function interpolateHeight(terrainData, u, v, rectangle) {
    const buffer = terrainData._buffer;
    let quad = 0; // SW
    let uStart = 0.0;
    let vStart = 0.0;
    if (v > 0.5) {
      // Upper row
      if (u > 0.5) {
        // NE
        quad = 2;
        uStart = 0.5;
      } else {
        // NW
        quad = 3;
      }
      vStart = 0.5;
    } else if (u > 0.5) {
      // SE
      quad = 1;
      uStart = 0.5;
    }

    const dv = new DataView(buffer);
    let offset = 0;
    for (let q = 0; q < quad; ++q) {
      offset += dv.getUint32(offset, true);
      offset += sizeOfUint32$7;
    }
    offset += sizeOfUint32$7; // Skip length of quad
    offset += 2 * sizeOfDouble; // Skip origin

    // Read sizes
    const xSize = CesiumMath.toRadians(dv.getFloat64(offset, true) * 180.0);
    offset += sizeOfDouble;
    const ySize = CesiumMath.toRadians(dv.getFloat64(offset, true) * 180.0);
    offset += sizeOfDouble;

    // Samples per quad
    const xScale = rectangle.width / xSize / 2;
    const yScale = rectangle.height / ySize / 2;

    // Number of points
    const numPoints = dv.getInt32(offset, true);
    offset += sizeOfInt32;

    // Number of faces
    const numIndices = dv.getInt32(offset, true) * 3;
    offset += sizeOfInt32;

    offset += sizeOfInt32; // Skip Level

    const uBuffer = new Array(numPoints);
    const vBuffer = new Array(numPoints);
    const heights = new Array(numPoints);
    let i;
    for (i = 0; i < numPoints; ++i) {
      uBuffer[i] = uStart + dv.getUint8(offset++) * xScale;
      vBuffer[i] = vStart + dv.getUint8(offset++) * yScale;

      // Height is stored in units of (1/EarthRadius) or (1/6371010.0)
      heights[i] = dv.getFloat32(offset, true) * 6371010.0;
      offset += sizeOfFloat;
    }

    const indices = new Array(numIndices);
    for (i = 0; i < numIndices; ++i) {
      indices[i] = dv.getUint16(offset, true);
      offset += sizeOfUint16;
    }

    for (i = 0; i < numIndices; i += 3) {
      const i0 = indices[i];
      const i1 = indices[i + 1];
      const i2 = indices[i + 2];

      const u0 = uBuffer[i0];
      const u1 = uBuffer[i1];
      const u2 = uBuffer[i2];

      const v0 = vBuffer[i0];
      const v1 = vBuffer[i1];
      const v2 = vBuffer[i2];

      const barycentric = Intersections2D.computeBarycentricCoordinates(
        u,
        v,
        u0,
        v0,
        u1,
        v1,
        u2,
        v2,
        barycentricCoordinateScratch
      );
      if (
        barycentric.x >= -1e-15 &&
        barycentric.y >= -1e-15 &&
        barycentric.z >= -1e-15
      ) {
        return (
          barycentric.x * heights[i0] +
          barycentric.y * heights[i1] +
          barycentric.z * heights[i2]
        );
      }
    }

    // Position does not lie in any triangle in this mesh.
    return undefined;
  }

  const TerrainState$2 = {
    UNKNOWN: 0,
    NONE: 1,
    SELF: 2,
    PARENT: 3,
  };

  const julianDateScratch = new JulianDate();

  function TerrainCache() {
    this._terrainCache = {};
    this._lastTidy = JulianDate.now();
  }

  TerrainCache.prototype.add = function (quadKey, buffer) {
    this._terrainCache[quadKey] = {
      buffer: buffer,
      timestamp: JulianDate.now(),
    };
  };

  TerrainCache.prototype.get = function (quadKey) {
    const terrainCache = this._terrainCache;
    const result = terrainCache[quadKey];
    if (defined(result)) {
      delete this._terrainCache[quadKey];
      return result.buffer;
    }
  };

  TerrainCache.prototype.tidy = function () {
    JulianDate.now(julianDateScratch);
    if (JulianDate.secondsDifference(julianDateScratch, this._lastTidy) > 10) {
      const terrainCache = this._terrainCache;
      const keys = Object.keys(terrainCache);
      const count = keys.length;
      for (let i = 0; i < count; ++i) {
        const k = keys[i];
        const e = terrainCache[k];
        if (JulianDate.secondsDifference(julianDateScratch, e.timestamp) > 10) {
          delete terrainCache[k];
        }
      }

      JulianDate.clone(julianDateScratch, this._lastTidy);
    }
  };

  /**
   * Provides tiled terrain using the Google Earth Enterprise REST API.
   *
   * @alias GoogleEarthEnterpriseTerrainProvider
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Resource|String} options.url The url of the Google Earth Enterprise server hosting the imagery.
   * @param {GoogleEarthEnterpriseMetadata} options.metadata A metadata object that can be used to share metadata requests with a GoogleEarthEnterpriseImageryProvider.
   * @param {Ellipsoid} [options.ellipsoid] The ellipsoid.  If not specified, the WGS84 ellipsoid is used.
   * @param {Credit|String} [options.credit] A credit for the data source, which is displayed on the canvas.
   *
   * @see GoogleEarthEnterpriseImageryProvider
   * @see CesiumTerrainProvider
   *
   * @example
   * const geeMetadata = new GoogleEarthEnterpriseMetadata('http://www.example.com');
   * const gee = new Cesium.GoogleEarthEnterpriseTerrainProvider({
   *     metadata : geeMetadata
   * });
   *
   * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
   */
  function GoogleEarthEnterpriseTerrainProvider(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    if (!(defined(options.url) || defined(options.metadata))) {
      throw new DeveloperError("options.url or options.metadata is required.");
    }
    //>>includeEnd('debug');

    let metadata;
    if (defined(options.metadata)) {
      metadata = options.metadata;
    } else {
      const resource = Resource.createIfNeeded(options.url);
      metadata = new GoogleEarthEnterpriseMetadata(resource);
    }

    this._metadata = metadata;
    this._tilingScheme = new GeographicTilingScheme({
      numberOfLevelZeroTilesX: 2,
      numberOfLevelZeroTilesY: 2,
      rectangle: new Rectangle(
        -CesiumMath.PI,
        -CesiumMath.PI,
        CesiumMath.PI,
        CesiumMath.PI
      ),
      ellipsoid: options.ellipsoid,
    });

    let credit = options.credit;
    if (typeof credit === "string") {
      credit = new Credit(credit);
    }
    this._credit = credit;

    // Pulled from Google's documentation
    this._levelZeroMaximumGeometricError = 40075.16;

    this._terrainCache = new TerrainCache();
    this._terrainPromises = {};
    this._terrainRequests = {};

    this._errorEvent = new Event();

    this._ready = false;
    const that = this;
    let metadataError;
    this._readyPromise = metadata.readyPromise
      .then(function (result) {
        if (!metadata.terrainPresent) {
          const e = new RuntimeError(
            `The server ${metadata.url} doesn't have terrain`
          );
          metadataError = TileProviderError.handleError(
            metadataError,
            that,
            that._errorEvent,
            e.message,
            undefined,
            undefined,
            undefined,
            e
          );
          return Promise.reject(e);
        }

        TileProviderError.handleSuccess(metadataError);
        that._ready = result;
        return result;
      })
      .catch(function (e) {
        metadataError = TileProviderError.handleError(
          metadataError,
          that,
          that._errorEvent,
          e.message,
          undefined,
          undefined,
          undefined,
          e
        );
        return Promise.reject(e);
      });
  }

  Object.defineProperties(GoogleEarthEnterpriseTerrainProvider.prototype, {
    /**
     * Gets the name of the Google Earth Enterprise server url hosting the imagery.
     * @memberof GoogleEarthEnterpriseTerrainProvider.prototype
     * @type {String}
     * @readonly
     */
    url: {
      get: function () {
        return this._metadata.url;
      },
    },

    /**
     * Gets the proxy used by this provider.
     * @memberof GoogleEarthEnterpriseTerrainProvider.prototype
     * @type {Proxy}
     * @readonly
     */
    proxy: {
      get: function () {
        return this._metadata.proxy;
      },
    },

    /**
     * Gets the tiling scheme used by this provider.  This function should
     * not be called before {@link GoogleEarthEnterpriseTerrainProvider#ready} returns true.
     * @memberof GoogleEarthEnterpriseTerrainProvider.prototype
     * @type {TilingScheme}
     * @readonly
     */
    tilingScheme: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "tilingScheme must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._tilingScheme;
      },
    },

    /**
     * Gets an event that is raised when the imagery provider encounters an asynchronous error.  By subscribing
     * to the event, you will be notified of the error and can potentially recover from it.  Event listeners
     * are passed an instance of {@link TileProviderError}.
     * @memberof GoogleEarthEnterpriseTerrainProvider.prototype
     * @type {Event}
     * @readonly
     */
    errorEvent: {
      get: function () {
        return this._errorEvent;
      },
    },

    /**
     * Gets a value indicating whether or not the provider is ready for use.
     * @memberof GoogleEarthEnterpriseTerrainProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    ready: {
      get: function () {
        return this._ready;
      },
    },

    /**
     * Gets a promise that resolves to true when the provider is ready for use.
     * @memberof GoogleEarthEnterpriseTerrainProvider.prototype
     * @type {Promise.<Boolean>}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._readyPromise;
      },
    },

    /**
     * Gets the credit to display when this terrain provider is active.  Typically this is used to credit
     * the source of the terrain.  This function should not be called before {@link GoogleEarthEnterpriseTerrainProvider#ready} returns true.
     * @memberof GoogleEarthEnterpriseTerrainProvider.prototype
     * @type {Credit}
     * @readonly
     */
    credit: {
      get: function () {
        return this._credit;
      },
    },

    /**
     * Gets a value indicating whether or not the provider includes a water mask.  The water mask
     * indicates which areas of the globe are water rather than land, so they can be rendered
     * as a reflective surface with animated waves.  This function should not be
     * called before {@link GoogleEarthEnterpriseTerrainProvider#ready} returns true.
     * @memberof GoogleEarthEnterpriseTerrainProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    hasWaterMask: {
      get: function () {
        return false;
      },
    },

    /**
     * Gets a value indicating whether or not the requested tiles include vertex normals.
     * This function should not be called before {@link GoogleEarthEnterpriseTerrainProvider#ready} returns true.
     * @memberof GoogleEarthEnterpriseTerrainProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    hasVertexNormals: {
      get: function () {
        return false;
      },
    },

    /**
     * Gets an object that can be used to determine availability of terrain from this provider, such as
     * at points and in rectangles.  This function should not be called before
     * {@link GoogleEarthEnterpriseTerrainProvider#ready} returns true.  This property may be undefined if availability
     * information is not available.
     * @memberof GoogleEarthEnterpriseTerrainProvider.prototype
     * @type {TileAvailability}
     * @readonly
     */
    availability: {
      get: function () {
        return undefined;
      },
    },
  });

  const taskProcessor = new TaskProcessor("decodeGoogleEarthEnterprisePacket");

  // If the tile has its own terrain, then you can just use its child bitmask. If it was requested using it's parent
  //  then you need to check all of its children to see if they have terrain.
  function computeChildMask(quadKey, info, metadata) {
    let childMask = info.getChildBitmask();
    if (info.terrainState === TerrainState$2.PARENT) {
      childMask = 0;
      for (let i = 0; i < 4; ++i) {
        const child = metadata.getTileInformationFromQuadKey(
          quadKey + i.toString()
        );
        if (defined(child) && child.hasTerrain()) {
          childMask |= 1 << i;
        }
      }
    }

    return childMask;
  }

  /**
   * Requests the geometry for a given tile.  This function should not be called before
   * {@link GoogleEarthEnterpriseTerrainProvider#ready} returns true.  The result must include terrain data and
   * may optionally include a water mask and an indication of which child tiles are available.
   *
   * @param {Number} x The X coordinate of the tile for which to request geometry.
   * @param {Number} y The Y coordinate of the tile for which to request geometry.
   * @param {Number} level The level of the tile for which to request geometry.
   * @param {Request} [request] The request object. Intended for internal use only.
   * @returns {Promise.<TerrainData>|undefined} A promise for the requested geometry.  If this method
   *          returns undefined instead of a promise, it is an indication that too many requests are already
   *          pending and the request will be retried later.
   *
   * @exception {DeveloperError} This function must not be called before {@link GoogleEarthEnterpriseTerrainProvider#ready}
   *            returns true.
   */
  GoogleEarthEnterpriseTerrainProvider.prototype.requestTileGeometry = function (
    x,
    y,
    level,
    request
  ) {
    //>>includeStart('debug', pragmas.debug)
    if (!this._ready) {
      throw new DeveloperError(
        "requestTileGeometry must not be called before the terrain provider is ready."
      );
    }
    //>>includeEnd('debug');

    const quadKey = GoogleEarthEnterpriseMetadata.tileXYToQuadKey(x, y, level);
    const terrainCache = this._terrainCache;
    const metadata = this._metadata;
    const info = metadata.getTileInformationFromQuadKey(quadKey);

    // Check if this tile is even possibly available
    if (!defined(info)) {
      return Promise.reject(new RuntimeError("Terrain tile doesn't exist"));
    }

    let terrainState = info.terrainState;
    if (!defined(terrainState)) {
      // First time we have tried to load this tile, so set terrain state to UNKNOWN
      terrainState = info.terrainState = TerrainState$2.UNKNOWN;
    }

    // If its in the cache, return it
    const buffer = terrainCache.get(quadKey);
    if (defined(buffer)) {
      const credit = metadata.providers[info.terrainProvider];
      return Promise.resolve(
        new GoogleEarthEnterpriseTerrainData({
          buffer: buffer,
          childTileMask: computeChildMask(quadKey, info, metadata),
          credits: defined(credit) ? [credit] : undefined,
          negativeAltitudeExponentBias: metadata.negativeAltitudeExponentBias,
          negativeElevationThreshold: metadata.negativeAltitudeThreshold,
        })
      );
    }

    // Clean up the cache
    terrainCache.tidy();

    // We have a tile, check to see if no ancestors have terrain or that we know for sure it doesn't
    if (!info.ancestorHasTerrain) {
      // We haven't reached a level with terrain, so return the ellipsoid
      return Promise.resolve(
        new HeightmapTerrainData({
          buffer: new Uint8Array(16 * 16),
          width: 16,
          height: 16,
        })
      );
    } else if (terrainState === TerrainState$2.NONE) {
      // Already have info and there isn't any terrain here
      return Promise.reject(new RuntimeError("Terrain tile doesn't exist"));
    }

    // Figure out where we are getting the terrain and what version
    let parentInfo;
    let q = quadKey;
    let terrainVersion = -1;
    switch (terrainState) {
      case TerrainState$2.SELF: // We have terrain and have retrieved it before
        terrainVersion = info.terrainVersion;
        break;
      case TerrainState$2.PARENT: // We have terrain in our parent
        q = q.substring(0, q.length - 1);
        parentInfo = metadata.getTileInformationFromQuadKey(q);
        terrainVersion = parentInfo.terrainVersion;
        break;
      case TerrainState$2.UNKNOWN: // We haven't tried to retrieve terrain yet
        if (info.hasTerrain()) {
          terrainVersion = info.terrainVersion; // We should have terrain
        } else {
          q = q.substring(0, q.length - 1);
          parentInfo = metadata.getTileInformationFromQuadKey(q);
          if (defined(parentInfo) && parentInfo.hasTerrain()) {
            terrainVersion = parentInfo.terrainVersion; // Try checking in the parent
          }
        }
        break;
    }

    // We can't figure out where to get the terrain
    if (terrainVersion < 0) {
      return Promise.reject(new RuntimeError("Terrain tile doesn't exist"));
    }

    // Load that terrain
    const terrainPromises = this._terrainPromises;
    const terrainRequests = this._terrainRequests;
    let sharedPromise;
    let sharedRequest;
    if (defined(terrainPromises[q])) {
      // Already being loaded possibly from another child, so return existing promise
      sharedPromise = terrainPromises[q];
      sharedRequest = terrainRequests[q];
    } else {
      // Create new request for terrain
      sharedRequest = request;
      const requestPromise = buildTerrainResource(
        this,
        q,
        terrainVersion,
        sharedRequest
      ).fetchArrayBuffer();

      if (!defined(requestPromise)) {
        return undefined; // Throttled
      }

      sharedPromise = requestPromise.then(function (terrain) {
        if (defined(terrain)) {
          return taskProcessor
            .scheduleTask(
              {
                buffer: terrain,
                type: "Terrain",
                key: metadata.key,
              },
              [terrain]
            )
            .then(function (terrainTiles) {
              // Add requested tile and mark it as SELF
              const requestedInfo = metadata.getTileInformationFromQuadKey(q);
              requestedInfo.terrainState = TerrainState$2.SELF;
              terrainCache.add(q, terrainTiles[0]);
              const provider = requestedInfo.terrainProvider;

              // Add children to cache
              const count = terrainTiles.length - 1;
              for (let j = 0; j < count; ++j) {
                const childKey = q + j.toString();
                const child = metadata.getTileInformationFromQuadKey(childKey);
                if (defined(child)) {
                  terrainCache.add(childKey, terrainTiles[j + 1]);
                  child.terrainState = TerrainState$2.PARENT;
                  if (child.terrainProvider === 0) {
                    child.terrainProvider = provider;
                  }
                }
              }
            });
        }

        return Promise.reject(new RuntimeError("Failed to load terrain."));
      });

      terrainPromises[q] = sharedPromise; // Store promise without delete from terrainPromises
      terrainRequests[q] = sharedRequest;

      // Set promise so we remove from terrainPromises just one time
      sharedPromise = sharedPromise.finally(function () {
        delete terrainPromises[q];
        delete terrainRequests[q];
      });
    }

    return sharedPromise
      .then(function () {
        const buffer = terrainCache.get(quadKey);
        if (defined(buffer)) {
          const credit = metadata.providers[info.terrainProvider];
          return new GoogleEarthEnterpriseTerrainData({
            buffer: buffer,
            childTileMask: computeChildMask(quadKey, info, metadata),
            credits: defined(credit) ? [credit] : undefined,
            negativeAltitudeExponentBias: metadata.negativeAltitudeExponentBias,
            negativeElevationThreshold: metadata.negativeAltitudeThreshold,
          });
        }

        return Promise.reject(new RuntimeError("Failed to load terrain."));
      })
      .catch(function (error) {
        if (sharedRequest.state === RequestState$1.CANCELLED) {
          request.state = sharedRequest.state;
          return Promise.reject(error);
        }
        info.terrainState = TerrainState$2.NONE;
        return Promise.reject(error);
      });
  };

  /**
   * Gets the maximum geometric error allowed in a tile at a given level.
   *
   * @param {Number} level The tile level for which to get the maximum geometric error.
   * @returns {Number} The maximum geometric error.
   */
  GoogleEarthEnterpriseTerrainProvider.prototype.getLevelMaximumGeometricError = function (
    level
  ) {
    return this._levelZeroMaximumGeometricError / (1 << level);
  };

  /**
   * Determines whether data for a tile is available to be loaded.
   *
   * @param {Number} x The X coordinate of the tile for which to request geometry.
   * @param {Number} y The Y coordinate of the tile for which to request geometry.
   * @param {Number} level The level of the tile for which to request geometry.
   * @returns {Boolean|undefined} Undefined if not supported, otherwise true or false.
   */
  GoogleEarthEnterpriseTerrainProvider.prototype.getTileDataAvailable = function (
    x,
    y,
    level
  ) {
    const metadata = this._metadata;
    let quadKey = GoogleEarthEnterpriseMetadata.tileXYToQuadKey(x, y, level);

    const info = metadata.getTileInformation(x, y, level);
    if (info === null) {
      return false;
    }

    if (defined(info)) {
      if (!info.ancestorHasTerrain) {
        return true; // We'll just return the ellipsoid
      }

      const terrainState = info.terrainState;
      if (terrainState === TerrainState$2.NONE) {
        return false; // Terrain is not available
      }

      if (!defined(terrainState) || terrainState === TerrainState$2.UNKNOWN) {
        info.terrainState = TerrainState$2.UNKNOWN;
        if (!info.hasTerrain()) {
          quadKey = quadKey.substring(0, quadKey.length - 1);
          const parentInfo = metadata.getTileInformationFromQuadKey(quadKey);
          if (!defined(parentInfo) || !parentInfo.hasTerrain()) {
            return false;
          }
        }
      }

      return true;
    }

    if (metadata.isValid(quadKey)) {
      // We will need this tile, so request metadata and return false for now
      const request = new Request({
        throttle: false,
        throttleByServer: true,
        type: RequestType$1.TERRAIN,
      });
      metadata.populateSubtree(x, y, level, request);
    }
    return false;
  };

  /**
   * Makes sure we load availability data for a tile
   *
   * @param {Number} x The X coordinate of the tile for which to request geometry.
   * @param {Number} y The Y coordinate of the tile for which to request geometry.
   * @param {Number} level The level of the tile for which to request geometry.
   * @returns {undefined}
   */
  GoogleEarthEnterpriseTerrainProvider.prototype.loadTileDataAvailability = function (
    x,
    y,
    level
  ) {
    return undefined;
  };

  //
  // Functions to handle imagery packets
  //
  function buildTerrainResource(terrainProvider, quadKey, version, request) {
    version = defined(version) && version > 0 ? version : 1;
    return terrainProvider._metadata.resource.getDerivedResource({
      url: `flatfile?f1c-0${quadKey}-t.${version.toString()}`,
      request: request,
    });
  }

  const PROJECTIONS = [GeographicProjection, WebMercatorProjection];
  const PROJECTION_COUNT = PROJECTIONS.length;

  const MITER_BREAK_SMALL = Math.cos(CesiumMath.toRadians(30.0));
  const MITER_BREAK_LARGE = Math.cos(CesiumMath.toRadians(150.0));

  // Initial heights for constructing the wall.
  // Keeping WALL_INITIAL_MIN_HEIGHT near the ellipsoid surface helps
  // prevent precision problems with planes in the shader.
  // Putting the start point of a plane at ApproximateTerrainHeights._defaultMinTerrainHeight,
  // which is a highly conservative bound, usually puts the plane origin several thousands
  // of meters away from the actual terrain, causing floating point problems when checking
  // fragments on terrain against the plane.
  // Ellipsoid height is generally much closer.
  // The initial max height is arbitrary.
  // Both heights are corrected using ApproximateTerrainHeights for computing the actual volume geometry.
  const WALL_INITIAL_MIN_HEIGHT = 0.0;
  const WALL_INITIAL_MAX_HEIGHT = 1000.0;

  /**
   * A description of a polyline on terrain or 3D Tiles. Only to be used with {@link GroundPolylinePrimitive}.
   *
   * @alias GroundPolylineGeometry
   * @constructor
   *
   * @param {Object} options Options with the following properties:
   * @param {Cartesian3[]} options.positions An array of {@link Cartesian3} defining the polyline's points. Heights above the ellipsoid will be ignored.
   * @param {Number} [options.width=1.0] The screen space width in pixels.
   * @param {Number} [options.granularity=9999.0] The distance interval in meters used for interpolating options.points. Defaults to 9999.0 meters. Zero indicates no interpolation.
   * @param {Boolean} [options.loop=false] Whether during geometry creation a line segment will be added between the last and first line positions to make this Polyline a loop.
   * @param {ArcType} [options.arcType=ArcType.GEODESIC] The type of line the polyline segments must follow. Valid options are {@link ArcType.GEODESIC} and {@link ArcType.RHUMB}.
   *
   * @exception {DeveloperError} At least two positions are required.
   *
   * @see GroundPolylinePrimitive
   *
   * @example
   * const positions = Cesium.Cartesian3.fromDegreesArray([
   *   -112.1340164450331, 36.05494287836128,
   *   -112.08821010582645, 36.097804071380715,
   *   -112.13296079730024, 36.168769146801104
   * ]);
   *
   * const geometry = new Cesium.GroundPolylineGeometry({
   *   positions : positions
   * });
   */
  function GroundPolylineGeometry(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const positions = options.positions;

    //>>includeStart('debug', pragmas.debug);
    if (!defined(positions) || positions.length < 2) {
      throw new DeveloperError("At least two positions are required.");
    }
    if (
      defined(options.arcType) &&
      options.arcType !== ArcType$1.GEODESIC &&
      options.arcType !== ArcType$1.RHUMB
    ) {
      throw new DeveloperError(
        "Valid options for arcType are ArcType.GEODESIC and ArcType.RHUMB."
      );
    }
    //>>includeEnd('debug');

    /**
     * The screen space width in pixels.
     * @type {Number}
     */
    this.width = defaultValue(options.width, 1.0); // Doesn't get packed, not necessary for computing geometry.

    this._positions = positions;

    /**
     * The distance interval used for interpolating options.points. Zero indicates no interpolation.
     * Default of 9999.0 allows centimeter accuracy with 32 bit floating point.
     * @type {Boolean}
     * @default 9999.0
     */
    this.granularity = defaultValue(options.granularity, 9999.0);

    /**
     * Whether during geometry creation a line segment will be added between the last and first line positions to make this Polyline a loop.
     * If the geometry has two positions this parameter will be ignored.
     * @type {Boolean}
     * @default false
     */
    this.loop = defaultValue(options.loop, false);

    /**
     * The type of path the polyline must follow. Valid options are {@link ArcType.GEODESIC} and {@link ArcType.RHUMB}.
     * @type {ArcType}
     * @default ArcType.GEODESIC
     */
    this.arcType = defaultValue(options.arcType, ArcType$1.GEODESIC);

    this._ellipsoid = Ellipsoid.WGS84;

    // MapProjections can't be packed, so store the index to a known MapProjection.
    this._projectionIndex = 0;
    this._workerName = "createGroundPolylineGeometry";

    // Used by GroundPolylinePrimitive to signal worker that scenemode is 3D only.
    this._scene3DOnly = false;
  }

  Object.defineProperties(GroundPolylineGeometry.prototype, {
    /**
     * The number of elements used to pack the object into an array.
     * @memberof GroundPolylineGeometry.prototype
     * @type {Number}
     * @readonly
     * @private
     */
    packedLength: {
      get: function () {
        return (
          1.0 +
          this._positions.length * 3 +
          1.0 +
          1.0 +
          1.0 +
          Ellipsoid.packedLength +
          1.0 +
          1.0
        );
      },
    },
  });

  /**
   * Set the GroundPolylineGeometry's projection and ellipsoid.
   * Used by GroundPolylinePrimitive to signal scene information to the geometry for generating 2D attributes.
   *
   * @param {GroundPolylineGeometry} groundPolylineGeometry GroundPolylinGeometry describing a polyline on terrain or 3D Tiles.
   * @param {Projection} mapProjection A MapProjection used for projecting cartographic coordinates to 2D.
   * @private
   */
  GroundPolylineGeometry.setProjectionAndEllipsoid = function (
    groundPolylineGeometry,
    mapProjection
  ) {
    let projectionIndex = 0;
    for (let i = 0; i < PROJECTION_COUNT; i++) {
      if (mapProjection instanceof PROJECTIONS[i]) {
        projectionIndex = i;
        break;
      }
    }

    groundPolylineGeometry._projectionIndex = projectionIndex;
    groundPolylineGeometry._ellipsoid = mapProjection.ellipsoid;
  };

  const cart3Scratch1 = new Cartesian3();
  const cart3Scratch2 = new Cartesian3();
  const cart3Scratch3 = new Cartesian3();
  function computeRightNormal(start, end, maxHeight, ellipsoid, result) {
    const startBottom = getPosition$2(ellipsoid, start, 0.0, cart3Scratch1);
    const startTop = getPosition$2(ellipsoid, start, maxHeight, cart3Scratch2);
    const endBottom = getPosition$2(ellipsoid, end, 0.0, cart3Scratch3);

    const up = direction(startTop, startBottom, cart3Scratch2);
    const forward = direction(endBottom, startBottom, cart3Scratch3);

    Cartesian3.cross(forward, up, result);
    return Cartesian3.normalize(result, result);
  }

  const interpolatedCartographicScratch$1 = new Cartographic();
  const interpolatedBottomScratch = new Cartesian3();
  const interpolatedTopScratch = new Cartesian3();
  const interpolatedNormalScratch = new Cartesian3();
  function interpolateSegment(
    start,
    end,
    minHeight,
    maxHeight,
    granularity,
    arcType,
    ellipsoid,
    normalsArray,
    bottomPositionsArray,
    topPositionsArray,
    cartographicsArray
  ) {
    if (granularity === 0.0) {
      return;
    }

    let ellipsoidLine;
    if (arcType === ArcType$1.GEODESIC) {
      ellipsoidLine = new EllipsoidGeodesic(start, end, ellipsoid);
    } else if (arcType === ArcType$1.RHUMB) {
      ellipsoidLine = new EllipsoidRhumbLine(start, end, ellipsoid);
    }

    const surfaceDistance = ellipsoidLine.surfaceDistance;
    if (surfaceDistance < granularity) {
      return;
    }

    // Compute rightwards normal applicable at all interpolated points
    const interpolatedNormal = computeRightNormal(
      start,
      end,
      maxHeight,
      ellipsoid,
      interpolatedNormalScratch
    );

    const segments = Math.ceil(surfaceDistance / granularity);
    const interpointDistance = surfaceDistance / segments;
    let distanceFromStart = interpointDistance;
    const pointsToAdd = segments - 1;
    let packIndex = normalsArray.length;
    for (let i = 0; i < pointsToAdd; i++) {
      const interpolatedCartographic = ellipsoidLine.interpolateUsingSurfaceDistance(
        distanceFromStart,
        interpolatedCartographicScratch$1
      );
      const interpolatedBottom = getPosition$2(
        ellipsoid,
        interpolatedCartographic,
        minHeight,
        interpolatedBottomScratch
      );
      const interpolatedTop = getPosition$2(
        ellipsoid,
        interpolatedCartographic,
        maxHeight,
        interpolatedTopScratch
      );

      Cartesian3.pack(interpolatedNormal, normalsArray, packIndex);
      Cartesian3.pack(interpolatedBottom, bottomPositionsArray, packIndex);
      Cartesian3.pack(interpolatedTop, topPositionsArray, packIndex);
      cartographicsArray.push(interpolatedCartographic.latitude);
      cartographicsArray.push(interpolatedCartographic.longitude);

      packIndex += 3;
      distanceFromStart += interpointDistance;
    }
  }

  const heightlessCartographicScratch = new Cartographic();
  function getPosition$2(ellipsoid, cartographic, height, result) {
    Cartographic.clone(cartographic, heightlessCartographicScratch);
    heightlessCartographicScratch.height = height;
    return Cartographic.toCartesian(
      heightlessCartographicScratch,
      ellipsoid,
      result
    );
  }

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {PolygonGeometry} 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
   */
  GroundPolylineGeometry.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    Check.defined("array", array);
    //>>includeEnd('debug');

    let index = defaultValue(startingIndex, 0);

    const positions = value._positions;
    const positionsLength = positions.length;

    array[index++] = positionsLength;

    for (let i = 0; i < positionsLength; ++i) {
      const cartesian = positions[i];
      Cartesian3.pack(cartesian, array, index);
      index += 3;
    }

    array[index++] = value.granularity;
    array[index++] = value.loop ? 1.0 : 0.0;
    array[index++] = value.arcType;

    Ellipsoid.pack(value._ellipsoid, array, index);
    index += Ellipsoid.packedLength;

    array[index++] = value._projectionIndex;
    array[index++] = value._scene3DOnly ? 1.0 : 0.0;

    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 {PolygonGeometry} [result] The object into which to store the result.
   */
  GroundPolylineGeometry.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    let index = defaultValue(startingIndex, 0);
    const positionsLength = array[index++];
    const positions = new Array(positionsLength);

    for (let i = 0; i < positionsLength; i++) {
      positions[i] = Cartesian3.unpack(array, index);
      index += 3;
    }

    const granularity = array[index++];
    const loop = array[index++] === 1.0;
    const arcType = array[index++];

    const ellipsoid = Ellipsoid.unpack(array, index);
    index += Ellipsoid.packedLength;

    const projectionIndex = array[index++];
    const scene3DOnly = array[index++] === 1.0;

    if (!defined(result)) {
      result = new GroundPolylineGeometry({
        positions: positions,
      });
    }

    result._positions = positions;
    result.granularity = granularity;
    result.loop = loop;
    result.arcType = arcType;
    result._ellipsoid = ellipsoid;
    result._projectionIndex = projectionIndex;
    result._scene3DOnly = scene3DOnly;

    return result;
  };

  function direction(target, origin, result) {
    Cartesian3.subtract(target, origin, result);
    Cartesian3.normalize(result, result);
    return result;
  }

  function tangentDirection(target, origin, up, result) {
    result = direction(target, origin, result);

    // orthogonalize
    result = Cartesian3.cross(result, up, result);
    result = Cartesian3.normalize(result, result);
    result = Cartesian3.cross(up, result, result);
    return result;
  }

  const toPreviousScratch = new Cartesian3();
  const toNextScratch = new Cartesian3();
  const forwardScratch = new Cartesian3();
  const vertexUpScratch = new Cartesian3();
  const cosine90 = 0.0;
  const cosine180 = -1.0;
  function computeVertexMiterNormal(
    previousBottom,
    vertexBottom,
    vertexTop,
    nextBottom,
    result
  ) {
    const up = direction(vertexTop, vertexBottom, vertexUpScratch);

    // Compute vectors pointing towards neighboring points but tangent to this point on the ellipsoid
    const toPrevious = tangentDirection(
      previousBottom,
      vertexBottom,
      up,
      toPreviousScratch
    );
    const toNext = tangentDirection(nextBottom, vertexBottom, up, toNextScratch);

    // Check if tangents are almost opposite - if so, no need to miter.
    if (
      CesiumMath.equalsEpsilon(
        Cartesian3.dot(toPrevious, toNext),
        cosine180,
        CesiumMath.EPSILON5
      )
    ) {
      result = Cartesian3.cross(up, toPrevious, result);
      result = Cartesian3.normalize(result, result);
      return result;
    }

    // Average directions to previous and to next in the plane of Up
    result = Cartesian3.add(toNext, toPrevious, result);
    result = Cartesian3.normalize(result, result);

    // Flip the normal if it isn't pointing roughly bound right (aka if forward is pointing more "backwards")
    const forward = Cartesian3.cross(up, result, forwardScratch);
    if (Cartesian3.dot(toNext, forward) < cosine90) {
      result = Cartesian3.negate(result, result);
    }

    return result;
  }

  const XZ_PLANE = Plane.fromPointNormal(Cartesian3.ZERO, Cartesian3.UNIT_Y);

  const previousBottomScratch = new Cartesian3();
  const vertexBottomScratch = new Cartesian3();
  const vertexTopScratch = new Cartesian3();
  const nextBottomScratch = new Cartesian3();
  const vertexNormalScratch = new Cartesian3();
  const intersectionScratch$1 = new Cartesian3();
  const cartographicScratch0 = new Cartographic();
  const cartographicScratch1 = new Cartographic();
  const cartographicIntersectionScratch = new Cartographic();
  /**
   * Computes shadow volumes for the ground polyline, consisting of its vertices, indices, and a bounding sphere.
   * Vertices are "fat," packing all the data needed in each volume to describe a line on terrain or 3D Tiles.
   * Should not be called independent of {@link GroundPolylinePrimitive}.
   *
   * @param {GroundPolylineGeometry} groundPolylineGeometry
   * @private
   */
  GroundPolylineGeometry.createGeometry = function (groundPolylineGeometry) {
    const compute2dAttributes = !groundPolylineGeometry._scene3DOnly;
    let loop = groundPolylineGeometry.loop;
    const ellipsoid = groundPolylineGeometry._ellipsoid;
    const granularity = groundPolylineGeometry.granularity;
    const arcType = groundPolylineGeometry.arcType;
    const projection = new PROJECTIONS[groundPolylineGeometry._projectionIndex](
      ellipsoid
    );

    const minHeight = WALL_INITIAL_MIN_HEIGHT;
    const maxHeight = WALL_INITIAL_MAX_HEIGHT;

    let index;
    let i;

    const positions = groundPolylineGeometry._positions;
    const positionsLength = positions.length;

    if (positionsLength === 2) {
      loop = false;
    }

    // Split positions across the IDL and the Prime Meridian as well.
    // Split across prime meridian because very large geometries crossing the Prime Meridian but not the IDL
    // may get split by the plane of IDL + Prime Meridian.
    let p0;
    let p1;
    let c0;
    let c1;
    const rhumbLine = new EllipsoidRhumbLine(undefined, undefined, ellipsoid);
    let intersection;
    let intersectionCartographic;
    let intersectionLongitude;
    const splitPositions = [positions[0]];
    for (i = 0; i < positionsLength - 1; i++) {
      p0 = positions[i];
      p1 = positions[i + 1];
      intersection = IntersectionTests.lineSegmentPlane(
        p0,
        p1,
        XZ_PLANE,
        intersectionScratch$1
      );
      if (
        defined(intersection) &&
        !Cartesian3.equalsEpsilon(intersection, p0, CesiumMath.EPSILON7) &&
        !Cartesian3.equalsEpsilon(intersection, p1, CesiumMath.EPSILON7)
      ) {
        if (groundPolylineGeometry.arcType === ArcType$1.GEODESIC) {
          splitPositions.push(Cartesian3.clone(intersection));
        } else if (groundPolylineGeometry.arcType === ArcType$1.RHUMB) {
          intersectionLongitude = ellipsoid.cartesianToCartographic(
            intersection,
            cartographicScratch0
          ).longitude;
          c0 = ellipsoid.cartesianToCartographic(p0, cartographicScratch0);
          c1 = ellipsoid.cartesianToCartographic(p1, cartographicScratch1);
          rhumbLine.setEndPoints(c0, c1);
          intersectionCartographic = rhumbLine.findIntersectionWithLongitude(
            intersectionLongitude,
            cartographicIntersectionScratch
          );
          intersection = ellipsoid.cartographicToCartesian(
            intersectionCartographic,
            intersectionScratch$1
          );
          if (
            defined(intersection) &&
            !Cartesian3.equalsEpsilon(intersection, p0, CesiumMath.EPSILON7) &&
            !Cartesian3.equalsEpsilon(intersection, p1, CesiumMath.EPSILON7)
          ) {
            splitPositions.push(Cartesian3.clone(intersection));
          }
        }
      }
      splitPositions.push(p1);
    }

    if (loop) {
      p0 = positions[positionsLength - 1];
      p1 = positions[0];
      intersection = IntersectionTests.lineSegmentPlane(
        p0,
        p1,
        XZ_PLANE,
        intersectionScratch$1
      );
      if (
        defined(intersection) &&
        !Cartesian3.equalsEpsilon(intersection, p0, CesiumMath.EPSILON7) &&
        !Cartesian3.equalsEpsilon(intersection, p1, CesiumMath.EPSILON7)
      ) {
        if (groundPolylineGeometry.arcType === ArcType$1.GEODESIC) {
          splitPositions.push(Cartesian3.clone(intersection));
        } else if (groundPolylineGeometry.arcType === ArcType$1.RHUMB) {
          intersectionLongitude = ellipsoid.cartesianToCartographic(
            intersection,
            cartographicScratch0
          ).longitude;
          c0 = ellipsoid.cartesianToCartographic(p0, cartographicScratch0);
          c1 = ellipsoid.cartesianToCartographic(p1, cartographicScratch1);
          rhumbLine.setEndPoints(c0, c1);
          intersectionCartographic = rhumbLine.findIntersectionWithLongitude(
            intersectionLongitude,
            cartographicIntersectionScratch
          );
          intersection = ellipsoid.cartographicToCartesian(
            intersectionCartographic,
            intersectionScratch$1
          );
          if (
            defined(intersection) &&
            !Cartesian3.equalsEpsilon(intersection, p0, CesiumMath.EPSILON7) &&
            !Cartesian3.equalsEpsilon(intersection, p1, CesiumMath.EPSILON7)
          ) {
            splitPositions.push(Cartesian3.clone(intersection));
          }
        }
      }
    }
    let cartographicsLength = splitPositions.length;

    let cartographics = new Array(cartographicsLength);
    for (i = 0; i < cartographicsLength; i++) {
      const cartographic = Cartographic.fromCartesian(
        splitPositions[i],
        ellipsoid
      );
      cartographic.height = 0.0;
      cartographics[i] = cartographic;
    }

    cartographics = arrayRemoveDuplicates(
      cartographics,
      Cartographic.equalsEpsilon
    );
    cartographicsLength = cartographics.length;

    if (cartographicsLength < 2) {
      return undefined;
    }

    /**** Build heap-side arrays for positions, interpolated cartographics, and normals from which to compute vertices ****/
    // We build a "wall" and then decompose it into separately connected component "volumes" because we need a lot
    // of information about the wall. Also, this simplifies interpolation.
    // Convention: "next" and "end" are locally forward to each segment of the wall,
    // and we are computing normals pointing towards the local right side of the vertices in each segment.
    const cartographicsArray = [];
    const normalsArray = [];
    const bottomPositionsArray = [];
    const topPositionsArray = [];

    let previousBottom = previousBottomScratch;
    let vertexBottom = vertexBottomScratch;
    let vertexTop = vertexTopScratch;
    let nextBottom = nextBottomScratch;
    let vertexNormal = vertexNormalScratch;

    // First point - either loop or attach a "perpendicular" normal
    const startCartographic = cartographics[0];
    const nextCartographic = cartographics[1];

    const prestartCartographic = cartographics[cartographicsLength - 1];
    previousBottom = getPosition$2(
      ellipsoid,
      prestartCartographic,
      minHeight,
      previousBottom
    );
    nextBottom = getPosition$2(ellipsoid, nextCartographic, minHeight, nextBottom);
    vertexBottom = getPosition$2(
      ellipsoid,
      startCartographic,
      minHeight,
      vertexBottom
    );
    vertexTop = getPosition$2(ellipsoid, startCartographic, maxHeight, vertexTop);

    if (loop) {
      vertexNormal = computeVertexMiterNormal(
        previousBottom,
        vertexBottom,
        vertexTop,
        nextBottom,
        vertexNormal
      );
    } else {
      vertexNormal = computeRightNormal(
        startCartographic,
        nextCartographic,
        maxHeight,
        ellipsoid,
        vertexNormal
      );
    }

    Cartesian3.pack(vertexNormal, normalsArray, 0);
    Cartesian3.pack(vertexBottom, bottomPositionsArray, 0);
    Cartesian3.pack(vertexTop, topPositionsArray, 0);
    cartographicsArray.push(startCartographic.latitude);
    cartographicsArray.push(startCartographic.longitude);

    interpolateSegment(
      startCartographic,
      nextCartographic,
      minHeight,
      maxHeight,
      granularity,
      arcType,
      ellipsoid,
      normalsArray,
      bottomPositionsArray,
      topPositionsArray,
      cartographicsArray
    );

    // All inbetween points
    for (i = 1; i < cartographicsLength - 1; ++i) {
      previousBottom = Cartesian3.clone(vertexBottom, previousBottom);
      vertexBottom = Cartesian3.clone(nextBottom, vertexBottom);
      const vertexCartographic = cartographics[i];
      getPosition$2(ellipsoid, vertexCartographic, maxHeight, vertexTop);
      getPosition$2(ellipsoid, cartographics[i + 1], minHeight, nextBottom);

      computeVertexMiterNormal(
        previousBottom,
        vertexBottom,
        vertexTop,
        nextBottom,
        vertexNormal
      );

      index = normalsArray.length;
      Cartesian3.pack(vertexNormal, normalsArray, index);
      Cartesian3.pack(vertexBottom, bottomPositionsArray, index);
      Cartesian3.pack(vertexTop, topPositionsArray, index);
      cartographicsArray.push(vertexCartographic.latitude);
      cartographicsArray.push(vertexCartographic.longitude);

      interpolateSegment(
        cartographics[i],
        cartographics[i + 1],
        minHeight,
        maxHeight,
        granularity,
        arcType,
        ellipsoid,
        normalsArray,
        bottomPositionsArray,
        topPositionsArray,
        cartographicsArray
      );
    }

    // Last point - either loop or attach a normal "perpendicular" to the wall.
    const endCartographic = cartographics[cartographicsLength - 1];
    const preEndCartographic = cartographics[cartographicsLength - 2];

    vertexBottom = getPosition$2(
      ellipsoid,
      endCartographic,
      minHeight,
      vertexBottom
    );
    vertexTop = getPosition$2(ellipsoid, endCartographic, maxHeight, vertexTop);

    if (loop) {
      const postEndCartographic = cartographics[0];
      previousBottom = getPosition$2(
        ellipsoid,
        preEndCartographic,
        minHeight,
        previousBottom
      );
      nextBottom = getPosition$2(
        ellipsoid,
        postEndCartographic,
        minHeight,
        nextBottom
      );

      vertexNormal = computeVertexMiterNormal(
        previousBottom,
        vertexBottom,
        vertexTop,
        nextBottom,
        vertexNormal
      );
    } else {
      vertexNormal = computeRightNormal(
        preEndCartographic,
        endCartographic,
        maxHeight,
        ellipsoid,
        vertexNormal
      );
    }

    index = normalsArray.length;
    Cartesian3.pack(vertexNormal, normalsArray, index);
    Cartesian3.pack(vertexBottom, bottomPositionsArray, index);
    Cartesian3.pack(vertexTop, topPositionsArray, index);
    cartographicsArray.push(endCartographic.latitude);
    cartographicsArray.push(endCartographic.longitude);

    if (loop) {
      interpolateSegment(
        endCartographic,
        startCartographic,
        minHeight,
        maxHeight,
        granularity,
        arcType,
        ellipsoid,
        normalsArray,
        bottomPositionsArray,
        topPositionsArray,
        cartographicsArray
      );
      index = normalsArray.length;
      for (i = 0; i < 3; ++i) {
        normalsArray[index + i] = normalsArray[i];
        bottomPositionsArray[index + i] = bottomPositionsArray[i];
        topPositionsArray[index + i] = topPositionsArray[i];
      }
      cartographicsArray.push(startCartographic.latitude);
      cartographicsArray.push(startCartographic.longitude);
    }

    return generateGeometryAttributes(
      loop,
      projection,
      bottomPositionsArray,
      topPositionsArray,
      normalsArray,
      cartographicsArray,
      compute2dAttributes
    );
  };

  // If the end normal angle is too steep compared to the direction of the line segment,
  // "break" the miter by rotating the normal 90 degrees around the "up" direction at the point
  // For ultra precision we would want to project into a plane, but in practice this is sufficient.
  const lineDirectionScratch = new Cartesian3();
  const matrix3Scratch$1 = new Matrix3();
  const quaternionScratch$1 = new Quaternion();
  function breakMiter(endGeometryNormal, startBottom, endBottom, endTop) {
    const lineDirection = direction(endBottom, startBottom, lineDirectionScratch);

    const dot = Cartesian3.dot(lineDirection, endGeometryNormal);
    if (dot > MITER_BREAK_SMALL || dot < MITER_BREAK_LARGE) {
      const vertexUp = direction(endTop, endBottom, vertexUpScratch);
      const angle =
        dot < MITER_BREAK_LARGE
          ? CesiumMath.PI_OVER_TWO
          : -CesiumMath.PI_OVER_TWO;
      const quaternion = Quaternion.fromAxisAngle(
        vertexUp,
        angle,
        quaternionScratch$1
      );
      const rotationMatrix = Matrix3.fromQuaternion(quaternion, matrix3Scratch$1);
      Matrix3.multiplyByVector(
        rotationMatrix,
        endGeometryNormal,
        endGeometryNormal
      );
      return true;
    }
    return false;
  }

  const endPosCartographicScratch = new Cartographic();
  const normalStartpointScratch = new Cartesian3();
  const normalEndpointScratch = new Cartesian3();
  function projectNormal(
    projection,
    cartographic,
    normal,
    projectedPosition,
    result
  ) {
    const position = Cartographic.toCartesian(
      cartographic,
      projection._ellipsoid,
      normalStartpointScratch
    );
    let normalEndpoint = Cartesian3.add(position, normal, normalEndpointScratch);
    let flipNormal = false;

    const ellipsoid = projection._ellipsoid;
    let normalEndpointCartographic = ellipsoid.cartesianToCartographic(
      normalEndpoint,
      endPosCartographicScratch
    );
    // If normal crosses the IDL, go the other way and flip the result.
    // In practice this almost never happens because the cartographic start
    // and end points of each segment are "nudged" to be on the same side
    // of the IDL and slightly away from the IDL.
    if (
      Math.abs(cartographic.longitude - normalEndpointCartographic.longitude) >
      CesiumMath.PI_OVER_TWO
    ) {
      flipNormal = true;
      normalEndpoint = Cartesian3.subtract(
        position,
        normal,
        normalEndpointScratch
      );
      normalEndpointCartographic = ellipsoid.cartesianToCartographic(
        normalEndpoint,
        endPosCartographicScratch
      );
    }

    normalEndpointCartographic.height = 0.0;
    const normalEndpointProjected = projection.project(
      normalEndpointCartographic,
      result
    );
    result = Cartesian3.subtract(
      normalEndpointProjected,
      projectedPosition,
      result
    );
    result.z = 0.0;
    result = Cartesian3.normalize(result, result);
    if (flipNormal) {
      Cartesian3.negate(result, result);
    }
    return result;
  }

  const adjustHeightNormalScratch = new Cartesian3();
  const adjustHeightOffsetScratch = new Cartesian3();
  function adjustHeights(
    bottom,
    top,
    minHeight,
    maxHeight,
    adjustHeightBottom,
    adjustHeightTop
  ) {
    // bottom and top should be at WALL_INITIAL_MIN_HEIGHT and WALL_INITIAL_MAX_HEIGHT, respectively
    const adjustHeightNormal = Cartesian3.subtract(
      top,
      bottom,
      adjustHeightNormalScratch
    );
    Cartesian3.normalize(adjustHeightNormal, adjustHeightNormal);

    const distanceForBottom = minHeight - WALL_INITIAL_MIN_HEIGHT;
    let adjustHeightOffset = Cartesian3.multiplyByScalar(
      adjustHeightNormal,
      distanceForBottom,
      adjustHeightOffsetScratch
    );
    Cartesian3.add(bottom, adjustHeightOffset, adjustHeightBottom);

    const distanceForTop = maxHeight - WALL_INITIAL_MAX_HEIGHT;
    adjustHeightOffset = Cartesian3.multiplyByScalar(
      adjustHeightNormal,
      distanceForTop,
      adjustHeightOffsetScratch
    );
    Cartesian3.add(top, adjustHeightOffset, adjustHeightTop);
  }

  const nudgeDirectionScratch = new Cartesian3();
  function nudgeXZ(start, end) {
    const startToXZdistance = Plane.getPointDistance(XZ_PLANE, start);
    const endToXZdistance = Plane.getPointDistance(XZ_PLANE, end);
    let offset = nudgeDirectionScratch;
    // Larger epsilon than what's used in GeometryPipeline, a centimeter in world space
    if (CesiumMath.equalsEpsilon(startToXZdistance, 0.0, CesiumMath.EPSILON2)) {
      offset = direction(end, start, offset);
      Cartesian3.multiplyByScalar(offset, CesiumMath.EPSILON2, offset);
      Cartesian3.add(start, offset, start);
    } else if (
      CesiumMath.equalsEpsilon(endToXZdistance, 0.0, CesiumMath.EPSILON2)
    ) {
      offset = direction(start, end, offset);
      Cartesian3.multiplyByScalar(offset, CesiumMath.EPSILON2, offset);
      Cartesian3.add(end, offset, end);
    }
  }

  // "Nudge" cartographic coordinates so start and end are on the same side of the IDL.
  // Nudge amounts are tiny, basically just an IDL flip.
  // Only used for 2D/CV.
  function nudgeCartographic(start, end) {
    const absStartLon = Math.abs(start.longitude);
    const absEndLon = Math.abs(end.longitude);
    if (
      CesiumMath.equalsEpsilon(absStartLon, CesiumMath.PI, CesiumMath.EPSILON11)
    ) {
      const endSign = CesiumMath.sign(end.longitude);
      start.longitude = endSign * (absStartLon - CesiumMath.EPSILON11);
      return 1;
    } else if (
      CesiumMath.equalsEpsilon(absEndLon, CesiumMath.PI, CesiumMath.EPSILON11)
    ) {
      const startSign = CesiumMath.sign(start.longitude);
      end.longitude = startSign * (absEndLon - CesiumMath.EPSILON11);
      return 2;
    }
    return 0;
  }

  const startCartographicScratch$1 = new Cartographic();
  const endCartographicScratch$1 = new Cartographic();

  const segmentStartTopScratch = new Cartesian3();
  const segmentEndTopScratch = new Cartesian3();
  const segmentStartBottomScratch = new Cartesian3();
  const segmentEndBottomScratch = new Cartesian3();
  const segmentStartNormalScratch = new Cartesian3();
  const segmentEndNormalScratch = new Cartesian3();

  const getHeightCartographics = [
    startCartographicScratch$1,
    endCartographicScratch$1,
  ];
  const getHeightRectangleScratch = new Rectangle();

  const adjustHeightStartTopScratch = new Cartesian3();
  const adjustHeightEndTopScratch = new Cartesian3();
  const adjustHeightStartBottomScratch = new Cartesian3();
  const adjustHeightEndBottomScratch = new Cartesian3();

  const segmentStart2DScratch = new Cartesian3();
  const segmentEnd2DScratch = new Cartesian3();
  const segmentStartNormal2DScratch = new Cartesian3();
  const segmentEndNormal2DScratch = new Cartesian3();

  const offsetScratch$b = new Cartesian3();
  const startUpScratch = new Cartesian3();
  const endUpScratch = new Cartesian3();
  const rightScratch = new Cartesian3();
  const startPlaneNormalScratch = new Cartesian3();
  const endPlaneNormalScratch = new Cartesian3();
  const encodeScratch$1 = new EncodedCartesian3();

  const encodeScratch2D = new EncodedCartesian3();
  const forwardOffset2DScratch = new Cartesian3();
  const right2DScratch = new Cartesian3();

  const normalNudgeScratch = new Cartesian3();

  const scratchBoundingSpheres = [new BoundingSphere(), new BoundingSphere()];

  // Winding order is reversed so each segment's volume is inside-out
  const REFERENCE_INDICES = [
    0,
    2,
    1,
    0,
    3,
    2, // right
    0,
    7,
    3,
    0,
    4,
    7, // start
    0,
    5,
    4,
    0,
    1,
    5, // bottom
    5,
    7,
    4,
    5,
    6,
    7, // left
    5,
    2,
    6,
    5,
    1,
    2, // end
    3,
    6,
    2,
    3,
    7,
    6, // top
  ];
  const REFERENCE_INDICES_LENGTH = REFERENCE_INDICES.length;

  // Decompose the "wall" into a series of shadow volumes.
  // Each shadow volume's vertices encode a description of the line it contains,
  // including mitering planes at the end points, a plane along the line itself,
  // and attributes for computing length-wise texture coordinates.
  function generateGeometryAttributes(
    loop,
    projection,
    bottomPositionsArray,
    topPositionsArray,
    normalsArray,
    cartographicsArray,
    compute2dAttributes
  ) {
    let i;
    let index;
    const ellipsoid = projection._ellipsoid;

    // Each segment will have 8 vertices
    const segmentCount = bottomPositionsArray.length / 3 - 1;
    const vertexCount = segmentCount * 8;
    const arraySizeVec4 = vertexCount * 4;
    const indexCount = segmentCount * 36;

    const indices =
      vertexCount > 65535
        ? new Uint32Array(indexCount)
        : new Uint16Array(indexCount);
    const positionsArray = new Float64Array(vertexCount * 3);

    const startHiAndForwardOffsetX = new Float32Array(arraySizeVec4);
    const startLoAndForwardOffsetY = new Float32Array(arraySizeVec4);
    const startNormalAndForwardOffsetZ = new Float32Array(arraySizeVec4);
    const endNormalAndTextureCoordinateNormalizationX = new Float32Array(
      arraySizeVec4
    );
    const rightNormalAndTextureCoordinateNormalizationY = new Float32Array(
      arraySizeVec4
    );

    let startHiLo2D;
    let offsetAndRight2D;
    let startEndNormals2D;
    let texcoordNormalization2D;

    if (compute2dAttributes) {
      startHiLo2D = new Float32Array(arraySizeVec4);
      offsetAndRight2D = new Float32Array(arraySizeVec4);
      startEndNormals2D = new Float32Array(arraySizeVec4);
      texcoordNormalization2D = new Float32Array(vertexCount * 2);
    }

    /*** Compute total lengths for texture coordinate normalization ***/
    // 2D
    const cartographicsLength = cartographicsArray.length / 2;
    let length2D = 0.0;

    const startCartographic = startCartographicScratch$1;
    startCartographic.height = 0.0;
    const endCartographic = endCartographicScratch$1;
    endCartographic.height = 0.0;

    let segmentStartCartesian = segmentStartTopScratch;
    let segmentEndCartesian = segmentEndTopScratch;

    if (compute2dAttributes) {
      index = 0;
      for (i = 1; i < cartographicsLength; i++) {
        // Don't clone anything from previous segment b/c possible IDL touch
        startCartographic.latitude = cartographicsArray[index];
        startCartographic.longitude = cartographicsArray[index + 1];
        endCartographic.latitude = cartographicsArray[index + 2];
        endCartographic.longitude = cartographicsArray[index + 3];

        segmentStartCartesian = projection.project(
          startCartographic,
          segmentStartCartesian
        );
        segmentEndCartesian = projection.project(
          endCartographic,
          segmentEndCartesian
        );
        length2D += Cartesian3.distance(
          segmentStartCartesian,
          segmentEndCartesian
        );
        index += 2;
      }
    }

    // 3D
    const positionsLength = topPositionsArray.length / 3;
    segmentEndCartesian = Cartesian3.unpack(
      topPositionsArray,
      0,
      segmentEndCartesian
    );
    let length3D = 0.0;

    index = 3;
    for (i = 1; i < positionsLength; i++) {
      segmentStartCartesian = Cartesian3.clone(
        segmentEndCartesian,
        segmentStartCartesian
      );
      segmentEndCartesian = Cartesian3.unpack(
        topPositionsArray,
        index,
        segmentEndCartesian
      );
      length3D += Cartesian3.distance(segmentStartCartesian, segmentEndCartesian);
      index += 3;
    }

    /*** Generate segments ***/
    let j;
    index = 3;
    let cartographicsIndex = 0;
    let vec2sWriteIndex = 0;
    let vec3sWriteIndex = 0;
    let vec4sWriteIndex = 0;
    let miterBroken = false;

    let endBottom = Cartesian3.unpack(
      bottomPositionsArray,
      0,
      segmentEndBottomScratch
    );
    let endTop = Cartesian3.unpack(topPositionsArray, 0, segmentEndTopScratch);
    let endGeometryNormal = Cartesian3.unpack(
      normalsArray,
      0,
      segmentEndNormalScratch
    );

    if (loop) {
      const preEndBottom = Cartesian3.unpack(
        bottomPositionsArray,
        bottomPositionsArray.length - 6,
        segmentStartBottomScratch
      );
      if (breakMiter(endGeometryNormal, preEndBottom, endBottom, endTop)) {
        // Miter broken as if for the last point in the loop, needs to be inverted for first point (clone of endBottom)
        endGeometryNormal = Cartesian3.negate(
          endGeometryNormal,
          endGeometryNormal
        );
      }
    }

    let lengthSoFar3D = 0.0;
    let lengthSoFar2D = 0.0;

    // For translating bounding volume
    let sumHeights = 0.0;

    for (i = 0; i < segmentCount; i++) {
      const startBottom = Cartesian3.clone(endBottom, segmentStartBottomScratch);
      const startTop = Cartesian3.clone(endTop, segmentStartTopScratch);
      let startGeometryNormal = Cartesian3.clone(
        endGeometryNormal,
        segmentStartNormalScratch
      );

      if (miterBroken) {
        startGeometryNormal = Cartesian3.negate(
          startGeometryNormal,
          startGeometryNormal
        );
      }

      endBottom = Cartesian3.unpack(
        bottomPositionsArray,
        index,
        segmentEndBottomScratch
      );
      endTop = Cartesian3.unpack(topPositionsArray, index, segmentEndTopScratch);
      endGeometryNormal = Cartesian3.unpack(
        normalsArray,
        index,
        segmentEndNormalScratch
      );

      miterBroken = breakMiter(endGeometryNormal, startBottom, endBottom, endTop);

      // 2D - don't clone anything from previous segment b/c possible IDL touch
      startCartographic.latitude = cartographicsArray[cartographicsIndex];
      startCartographic.longitude = cartographicsArray[cartographicsIndex + 1];
      endCartographic.latitude = cartographicsArray[cartographicsIndex + 2];
      endCartographic.longitude = cartographicsArray[cartographicsIndex + 3];
      let start2D;
      let end2D;
      let startGeometryNormal2D;
      let endGeometryNormal2D;

      if (compute2dAttributes) {
        const nudgeResult = nudgeCartographic(startCartographic, endCartographic);
        start2D = projection.project(startCartographic, segmentStart2DScratch);
        end2D = projection.project(endCartographic, segmentEnd2DScratch);
        const direction2D = direction(end2D, start2D, forwardOffset2DScratch);
        direction2D.y = Math.abs(direction2D.y);

        startGeometryNormal2D = segmentStartNormal2DScratch;
        endGeometryNormal2D = segmentEndNormal2DScratch;
        if (
          nudgeResult === 0 ||
          Cartesian3.dot(direction2D, Cartesian3.UNIT_Y) > MITER_BREAK_SMALL
        ) {
          // No nudge - project the original normal
          // Or, if the line's angle relative to the IDL is very acute,
          // in which case snapping will produce oddly shaped volumes.
          startGeometryNormal2D = projectNormal(
            projection,
            startCartographic,
            startGeometryNormal,
            start2D,
            segmentStartNormal2DScratch
          );
          endGeometryNormal2D = projectNormal(
            projection,
            endCartographic,
            endGeometryNormal,
            end2D,
            segmentEndNormal2DScratch
          );
        } else if (nudgeResult === 1) {
          // Start is close to IDL - snap start normal to align with IDL
          endGeometryNormal2D = projectNormal(
            projection,
            endCartographic,
            endGeometryNormal,
            end2D,
            segmentEndNormal2DScratch
          );
          startGeometryNormal2D.x = 0.0;
          // If start longitude is negative and end longitude is less negative, relative right is unit -Y
          // If start longitude is positive and end longitude is less positive, relative right is unit +Y
          startGeometryNormal2D.y = CesiumMath.sign(
            startCartographic.longitude - Math.abs(endCartographic.longitude)
          );
          startGeometryNormal2D.z = 0.0;
        } else {
          // End is close to IDL - snap end normal to align with IDL
          startGeometryNormal2D = projectNormal(
            projection,
            startCartographic,
            startGeometryNormal,
            start2D,
            segmentStartNormal2DScratch
          );
          endGeometryNormal2D.x = 0.0;
          // If end longitude is negative and start longitude is less negative, relative right is unit Y
          // If end longitude is positive and start longitude is less positive, relative right is unit -Y
          endGeometryNormal2D.y = CesiumMath.sign(
            startCartographic.longitude - endCartographic.longitude
          );
          endGeometryNormal2D.z = 0.0;
        }
      }

      /****************************************
       * Geometry descriptors of a "line on terrain,"
       * as opposed to the "shadow volume used to draw
       * the line on terrain":
       * - position of start + offset to end
       * - start, end, and right-facing planes
       * - encoded texture coordinate offsets
       ****************************************/

      /* 3D */
      const segmentLength3D = Cartesian3.distance(startTop, endTop);

      const encodedStart = EncodedCartesian3.fromCartesian(
        startBottom,
        encodeScratch$1
      );
      const forwardOffset = Cartesian3.subtract(
        endBottom,
        startBottom,
        offsetScratch$b
      );
      const forward = Cartesian3.normalize(forwardOffset, rightScratch);

      let startUp = Cartesian3.subtract(startTop, startBottom, startUpScratch);
      startUp = Cartesian3.normalize(startUp, startUp);
      let rightNormal = Cartesian3.cross(forward, startUp, rightScratch);
      rightNormal = Cartesian3.normalize(rightNormal, rightNormal);

      let startPlaneNormal = Cartesian3.cross(
        startUp,
        startGeometryNormal,
        startPlaneNormalScratch
      );
      startPlaneNormal = Cartesian3.normalize(startPlaneNormal, startPlaneNormal);

      let endUp = Cartesian3.subtract(endTop, endBottom, endUpScratch);
      endUp = Cartesian3.normalize(endUp, endUp);
      let endPlaneNormal = Cartesian3.cross(
        endGeometryNormal,
        endUp,
        endPlaneNormalScratch
      );
      endPlaneNormal = Cartesian3.normalize(endPlaneNormal, endPlaneNormal);

      const texcoordNormalization3DX = segmentLength3D / length3D;
      const texcoordNormalization3DY = lengthSoFar3D / length3D;

      /* 2D */
      let segmentLength2D = 0.0;
      let encodedStart2D;
      let forwardOffset2D;
      let right2D;
      let texcoordNormalization2DX = 0.0;
      let texcoordNormalization2DY = 0.0;
      if (compute2dAttributes) {
        segmentLength2D = Cartesian3.distance(start2D, end2D);

        encodedStart2D = EncodedCartesian3.fromCartesian(
          start2D,
          encodeScratch2D
        );
        forwardOffset2D = Cartesian3.subtract(
          end2D,
          start2D,
          forwardOffset2DScratch
        );

        // Right direction is just forward direction rotated by -90 degrees around Z
        // Similarly with plane normals
        right2D = Cartesian3.normalize(forwardOffset2D, right2DScratch);
        const swap = right2D.x;
        right2D.x = right2D.y;
        right2D.y = -swap;

        texcoordNormalization2DX = segmentLength2D / length2D;
        texcoordNormalization2DY = lengthSoFar2D / length2D;
      }
      /** Pack **/
      for (j = 0; j < 8; j++) {
        const vec4Index = vec4sWriteIndex + j * 4;
        const vec2Index = vec2sWriteIndex + j * 2;
        const wIndex = vec4Index + 3;

        // Encode sidedness of vertex relative to right plane in texture coordinate normalization X,
        // whether vertex is top or bottom of volume in sign/magnitude of normalization Y.
        const rightPlaneSide = j < 4 ? 1.0 : -1.0;
        const topBottomSide =
          j === 2 || j === 3 || j === 6 || j === 7 ? 1.0 : -1.0;

        // 3D
        Cartesian3.pack(encodedStart.high, startHiAndForwardOffsetX, vec4Index);
        startHiAndForwardOffsetX[wIndex] = forwardOffset.x;

        Cartesian3.pack(encodedStart.low, startLoAndForwardOffsetY, vec4Index);
        startLoAndForwardOffsetY[wIndex] = forwardOffset.y;

        Cartesian3.pack(
          startPlaneNormal,
          startNormalAndForwardOffsetZ,
          vec4Index
        );
        startNormalAndForwardOffsetZ[wIndex] = forwardOffset.z;

        Cartesian3.pack(
          endPlaneNormal,
          endNormalAndTextureCoordinateNormalizationX,
          vec4Index
        );
        endNormalAndTextureCoordinateNormalizationX[wIndex] =
          texcoordNormalization3DX * rightPlaneSide;

        Cartesian3.pack(
          rightNormal,
          rightNormalAndTextureCoordinateNormalizationY,
          vec4Index
        );

        let texcoordNormalization = texcoordNormalization3DY * topBottomSide;
        if (texcoordNormalization === 0.0 && topBottomSide < 0.0) {
          texcoordNormalization = 9.0; // some value greater than 1.0
        }
        rightNormalAndTextureCoordinateNormalizationY[
          wIndex
        ] = texcoordNormalization;

        // 2D
        if (compute2dAttributes) {
          startHiLo2D[vec4Index] = encodedStart2D.high.x;
          startHiLo2D[vec4Index + 1] = encodedStart2D.high.y;
          startHiLo2D[vec4Index + 2] = encodedStart2D.low.x;
          startHiLo2D[vec4Index + 3] = encodedStart2D.low.y;

          startEndNormals2D[vec4Index] = -startGeometryNormal2D.y;
          startEndNormals2D[vec4Index + 1] = startGeometryNormal2D.x;
          startEndNormals2D[vec4Index + 2] = endGeometryNormal2D.y;
          startEndNormals2D[vec4Index + 3] = -endGeometryNormal2D.x;

          offsetAndRight2D[vec4Index] = forwardOffset2D.x;
          offsetAndRight2D[vec4Index + 1] = forwardOffset2D.y;
          offsetAndRight2D[vec4Index + 2] = right2D.x;
          offsetAndRight2D[vec4Index + 3] = right2D.y;

          texcoordNormalization2D[vec2Index] =
            texcoordNormalization2DX * rightPlaneSide;

          texcoordNormalization = texcoordNormalization2DY * topBottomSide;
          if (texcoordNormalization === 0.0 && topBottomSide < 0.0) {
            texcoordNormalization = 9.0; // some value greater than 1.0
          }
          texcoordNormalization2D[vec2Index + 1] = texcoordNormalization;
        }
      }

      // Adjust height of volume in 3D
      const adjustHeightStartBottom = adjustHeightStartBottomScratch;
      const adjustHeightEndBottom = adjustHeightEndBottomScratch;
      const adjustHeightStartTop = adjustHeightStartTopScratch;
      const adjustHeightEndTop = adjustHeightEndTopScratch;

      const getHeightsRectangle = Rectangle.fromCartographicArray(
        getHeightCartographics,
        getHeightRectangleScratch
      );
      const minMaxHeights = ApproximateTerrainHeights.getMinimumMaximumHeights(
        getHeightsRectangle,
        ellipsoid
      );
      const minHeight = minMaxHeights.minimumTerrainHeight;
      const maxHeight = minMaxHeights.maximumTerrainHeight;

      sumHeights += minHeight;
      sumHeights += maxHeight;

      adjustHeights(
        startBottom,
        startTop,
        minHeight,
        maxHeight,
        adjustHeightStartBottom,
        adjustHeightStartTop
      );
      adjustHeights(
        endBottom,
        endTop,
        minHeight,
        maxHeight,
        adjustHeightEndBottom,
        adjustHeightEndTop
      );

      // Nudge the positions away from the "polyline" a little bit to prevent errors in GeometryPipeline
      let normalNudge = Cartesian3.multiplyByScalar(
        rightNormal,
        CesiumMath.EPSILON5,
        normalNudgeScratch
      );
      Cartesian3.add(
        adjustHeightStartBottom,
        normalNudge,
        adjustHeightStartBottom
      );
      Cartesian3.add(adjustHeightEndBottom, normalNudge, adjustHeightEndBottom);
      Cartesian3.add(adjustHeightStartTop, normalNudge, adjustHeightStartTop);
      Cartesian3.add(adjustHeightEndTop, normalNudge, adjustHeightEndTop);

      // If the segment is very close to the XZ plane, nudge the vertices slightly to avoid touching it.
      nudgeXZ(adjustHeightStartBottom, adjustHeightEndBottom);
      nudgeXZ(adjustHeightStartTop, adjustHeightEndTop);

      Cartesian3.pack(adjustHeightStartBottom, positionsArray, vec3sWriteIndex);
      Cartesian3.pack(adjustHeightEndBottom, positionsArray, vec3sWriteIndex + 3);
      Cartesian3.pack(adjustHeightEndTop, positionsArray, vec3sWriteIndex + 6);
      Cartesian3.pack(adjustHeightStartTop, positionsArray, vec3sWriteIndex + 9);

      normalNudge = Cartesian3.multiplyByScalar(
        rightNormal,
        -2.0 * CesiumMath.EPSILON5,
        normalNudgeScratch
      );
      Cartesian3.add(
        adjustHeightStartBottom,
        normalNudge,
        adjustHeightStartBottom
      );
      Cartesian3.add(adjustHeightEndBottom, normalNudge, adjustHeightEndBottom);
      Cartesian3.add(adjustHeightStartTop, normalNudge, adjustHeightStartTop);
      Cartesian3.add(adjustHeightEndTop, normalNudge, adjustHeightEndTop);

      nudgeXZ(adjustHeightStartBottom, adjustHeightEndBottom);
      nudgeXZ(adjustHeightStartTop, adjustHeightEndTop);

      Cartesian3.pack(
        adjustHeightStartBottom,
        positionsArray,
        vec3sWriteIndex + 12
      );
      Cartesian3.pack(
        adjustHeightEndBottom,
        positionsArray,
        vec3sWriteIndex + 15
      );
      Cartesian3.pack(adjustHeightEndTop, positionsArray, vec3sWriteIndex + 18);
      Cartesian3.pack(adjustHeightStartTop, positionsArray, vec3sWriteIndex + 21);

      cartographicsIndex += 2;
      index += 3;

      vec2sWriteIndex += 16;
      vec3sWriteIndex += 24;
      vec4sWriteIndex += 32;

      lengthSoFar3D += segmentLength3D;
      lengthSoFar2D += segmentLength2D;
    }

    index = 0;
    let indexOffset = 0;
    for (i = 0; i < segmentCount; i++) {
      for (j = 0; j < REFERENCE_INDICES_LENGTH; j++) {
        indices[index + j] = REFERENCE_INDICES[j] + indexOffset;
      }
      indexOffset += 8;
      index += REFERENCE_INDICES_LENGTH;
    }

    const boundingSpheres = scratchBoundingSpheres;
    BoundingSphere.fromVertices(
      bottomPositionsArray,
      Cartesian3.ZERO,
      3,
      boundingSpheres[0]
    );
    BoundingSphere.fromVertices(
      topPositionsArray,
      Cartesian3.ZERO,
      3,
      boundingSpheres[1]
    );
    const boundingSphere = BoundingSphere.fromBoundingSpheres(boundingSpheres);

    // Adjust bounding sphere height and radius to cover more of the volume
    boundingSphere.radius += sumHeights / (segmentCount * 2.0);

    const attributes = {
      position: new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.DOUBLE,
        componentsPerAttribute: 3,
        normalize: false,
        values: positionsArray,
      }),
      startHiAndForwardOffsetX: getVec4GeometryAttribute(
        startHiAndForwardOffsetX
      ),
      startLoAndForwardOffsetY: getVec4GeometryAttribute(
        startLoAndForwardOffsetY
      ),
      startNormalAndForwardOffsetZ: getVec4GeometryAttribute(
        startNormalAndForwardOffsetZ
      ),
      endNormalAndTextureCoordinateNormalizationX: getVec4GeometryAttribute(
        endNormalAndTextureCoordinateNormalizationX
      ),
      rightNormalAndTextureCoordinateNormalizationY: getVec4GeometryAttribute(
        rightNormalAndTextureCoordinateNormalizationY
      ),
    };

    if (compute2dAttributes) {
      attributes.startHiLo2D = getVec4GeometryAttribute(startHiLo2D);
      attributes.offsetAndRight2D = getVec4GeometryAttribute(offsetAndRight2D);
      attributes.startEndNormals2D = getVec4GeometryAttribute(startEndNormals2D);
      attributes.texcoordNormalization2D = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 2,
        normalize: false,
        values: texcoordNormalization2D,
      });
    }

    return new Geometry({
      attributes: attributes,
      indices: indices,
      boundingSphere: boundingSphere,
    });
  }

  function getVec4GeometryAttribute(typedArray) {
    return new GeometryAttribute({
      componentDatatype: ComponentDatatype$1.FLOAT,
      componentsPerAttribute: 4,
      normalize: false,
      values: typedArray,
    });
  }

  /**
   * Approximates an ellipsoid-tangent vector in 2D by projecting the end point into 2D.
   * Exposed for testing.
   *
   * @param {MapProjection} projection Map Projection for projecting coordinates to 2D.
   * @param {Cartographic} cartographic The cartographic origin point of the normal.
   *   Used to check if the normal crosses the IDL during projection.
   * @param {Cartesian3} normal The normal in 3D.
   * @param {Cartesian3} projectedPosition The projected origin point of the normal in 2D.
   * @param {Cartesian3} result Result parameter on which to store the projected normal.
   * @private
   */
  GroundPolylineGeometry._projectNormal = projectNormal;

  /**
   * Defines a heading angle, pitch angle, and range in a local frame.
   * Heading is the rotation from the local north direction where a positive angle is increasing eastward.
   * Pitch is the rotation from the local xy-plane. Positive pitch angles are above the plane. Negative pitch
   * angles are below the plane. Range is the distance from the center of the frame.
   * @alias HeadingPitchRange
   * @constructor
   *
   * @param {Number} [heading=0.0] The heading angle in radians.
   * @param {Number} [pitch=0.0] The pitch angle in radians.
   * @param {Number} [range=0.0] The distance from the center in meters.
   */
  function HeadingPitchRange(heading, pitch, range) {
    /**
     * Heading is the rotation from the local north direction where a positive angle is increasing eastward.
     * @type {Number}
     * @default 0.0
     */
    this.heading = defaultValue(heading, 0.0);

    /**
     * Pitch is the rotation from the local xy-plane. Positive pitch angles
     * are above the plane. Negative pitch angles are below the plane.
     * @type {Number}
     * @default 0.0
     */
    this.pitch = defaultValue(pitch, 0.0);

    /**
     * Range is the distance from the center of the local frame.
     * @type {Number}
     * @default 0.0
     */
    this.range = defaultValue(range, 0.0);
  }

  /**
   * Duplicates a HeadingPitchRange instance.
   *
   * @param {HeadingPitchRange} hpr The HeadingPitchRange to duplicate.
   * @param {HeadingPitchRange} [result] The object onto which to store the result.
   * @returns {HeadingPitchRange} The modified result parameter or a new HeadingPitchRange instance if one was not provided. (Returns undefined if hpr is undefined)
   */
  HeadingPitchRange.clone = function (hpr, result) {
    if (!defined(hpr)) {
      return undefined;
    }
    if (!defined(result)) {
      result = new HeadingPitchRange();
    }

    result.heading = hpr.heading;
    result.pitch = hpr.pitch;
    result.range = hpr.range;
    return result;
  };

  const factorial = CesiumMath.factorial;

  function calculateCoefficientTerm(
    x,
    zIndices,
    xTable,
    derivOrder,
    termOrder,
    reservedIndices
  ) {
    let result = 0;
    let reserved;
    let i;
    let j;

    if (derivOrder > 0) {
      for (i = 0; i < termOrder; i++) {
        reserved = false;
        for (j = 0; j < reservedIndices.length && !reserved; j++) {
          if (i === reservedIndices[j]) {
            reserved = true;
          }
        }

        if (!reserved) {
          reservedIndices.push(i);
          result += calculateCoefficientTerm(
            x,
            zIndices,
            xTable,
            derivOrder - 1,
            termOrder,
            reservedIndices
          );
          reservedIndices.splice(reservedIndices.length - 1, 1);
        }
      }

      return result;
    }

    result = 1;
    for (i = 0; i < termOrder; i++) {
      reserved = false;
      for (j = 0; j < reservedIndices.length && !reserved; j++) {
        if (i === reservedIndices[j]) {
          reserved = true;
        }
      }

      if (!reserved) {
        result *= x - xTable[zIndices[i]];
      }
    }

    return result;
  }

  /**
   * An {@link InterpolationAlgorithm} for performing Hermite interpolation.
   *
   * @namespace HermitePolynomialApproximation
   */
  const HermitePolynomialApproximation = {
    type: "Hermite",
  };

  /**
   * Given the desired degree, returns the number of data points required for interpolation.
   *
   * @param {Number} degree The desired degree of interpolation.
   * @param {Number} [inputOrder=0]  The order of the inputs (0 means just the data, 1 means the data and its derivative, etc).
   * @returns {Number} The number of required data points needed for the desired degree of interpolation.
   * @exception {DeveloperError} degree must be 0 or greater.
   * @exception {DeveloperError} inputOrder must be 0 or greater.
   */
  HermitePolynomialApproximation.getRequiredDataPoints = function (
    degree,
    inputOrder
  ) {
    inputOrder = defaultValue(inputOrder, 0);

    //>>includeStart('debug', pragmas.debug);
    if (!defined(degree)) {
      throw new DeveloperError("degree is required.");
    }
    if (degree < 0) {
      throw new DeveloperError("degree must be 0 or greater.");
    }
    if (inputOrder < 0) {
      throw new DeveloperError("inputOrder must be 0 or greater.");
    }
    //>>includeEnd('debug');

    return Math.max(Math.floor((degree + 1) / (inputOrder + 1)), 2);
  };

  /**
   * Interpolates values using Hermite Polynomial Approximation.
   *
   * @param {Number} x The independent variable for which the dependent variables will be interpolated.
   * @param {Number[]} xTable The array of independent variables to use to interpolate.  The values
   * in this array must be in increasing order and the same value must not occur twice in the array.
   * @param {Number[]} yTable The array of dependent variables to use to interpolate.  For a set of three
   * dependent values (p,q,w) at time 1 and time 2 this should be as follows: {p1, q1, w1, p2, q2, w2}.
   * @param {Number} yStride The number of dependent variable values in yTable corresponding to
   * each independent variable value in xTable.
   * @param {Number[]} [result] An existing array into which to store the result.
   * @returns {Number[]} The array of interpolated values, or the result parameter if one was provided.
   */
  HermitePolynomialApproximation.interpolateOrderZero = function (
    x,
    xTable,
    yTable,
    yStride,
    result
  ) {
    if (!defined(result)) {
      result = new Array(yStride);
    }

    let i;
    let j;
    let d;
    let s;
    let len;
    let index;
    const length = xTable.length;
    const coefficients = new Array(yStride);

    for (i = 0; i < yStride; i++) {
      result[i] = 0;

      const l = new Array(length);
      coefficients[i] = l;
      for (j = 0; j < length; j++) {
        l[j] = [];
      }
    }

    const zIndicesLength = length,
      zIndices = new Array(zIndicesLength);

    for (i = 0; i < zIndicesLength; i++) {
      zIndices[i] = i;
    }

    let highestNonZeroCoef = length - 1;
    for (s = 0; s < yStride; s++) {
      for (j = 0; j < zIndicesLength; j++) {
        index = zIndices[j] * yStride + s;
        coefficients[s][0].push(yTable[index]);
      }

      for (i = 1; i < zIndicesLength; i++) {
        let nonZeroCoefficients = false;
        for (j = 0; j < zIndicesLength - i; j++) {
          const zj = xTable[zIndices[j]];
          const zn = xTable[zIndices[j + i]];

          let numerator;
          if (zn - zj <= 0) {
            index = zIndices[j] * yStride + yStride * i + s;
            numerator = yTable[index];
            coefficients[s][i].push(numerator / factorial(i));
          } else {
            numerator = coefficients[s][i - 1][j + 1] - coefficients[s][i - 1][j];
            coefficients[s][i].push(numerator / (zn - zj));
          }
          nonZeroCoefficients = nonZeroCoefficients || numerator !== 0;
        }

        if (!nonZeroCoefficients) {
          highestNonZeroCoef = i - 1;
        }
      }
    }

    for (d = 0, len = 0; d <= len; d++) {
      for (i = d; i <= highestNonZeroCoef; i++) {
        const tempTerm = calculateCoefficientTerm(x, zIndices, xTable, d, i, []);
        for (s = 0; s < yStride; s++) {
          const coeff = coefficients[s][i][0];
          result[s + d * yStride] += coeff * tempTerm;
        }
      }
    }

    return result;
  };

  const arrayScratch = [];

  /**
   * Interpolates values using Hermite Polynomial Approximation.
   *
   * @param {Number} x The independent variable for which the dependent variables will be interpolated.
   * @param {Number[]} xTable The array of independent variables to use to interpolate.  The values
   * in this array must be in increasing order and the same value must not occur twice in the array.
   * @param {Number[]} yTable The array of dependent variables to use to interpolate.  For a set of three
   * dependent values (p,q,w) at time 1 and time 2 this should be as follows: {p1, q1, w1, p2, q2, w2}.
   * @param {Number} yStride The number of dependent variable values in yTable corresponding to
   * each independent variable value in xTable.
   * @param {Number} inputOrder The number of derivatives supplied for input.
   * @param {Number} outputOrder The number of derivatives desired for output.
   * @param {Number[]} [result] An existing array into which to store the result.
   *
   * @returns {Number[]} The array of interpolated values, or the result parameter if one was provided.
   */
  HermitePolynomialApproximation.interpolate = function (
    x,
    xTable,
    yTable,
    yStride,
    inputOrder,
    outputOrder,
    result
  ) {
    const resultLength = yStride * (outputOrder + 1);
    if (!defined(result)) {
      result = new Array(resultLength);
    }
    for (let r = 0; r < resultLength; r++) {
      result[r] = 0;
    }

    const length = xTable.length;
    // The zIndices array holds copies of the addresses of the xTable values
    // in the range we're looking at. Even though this just holds information already
    // available in xTable this is a much more convenient format.
    const zIndices = new Array(length * (inputOrder + 1));
    let i;
    for (i = 0; i < length; i++) {
      for (let j = 0; j < inputOrder + 1; j++) {
        zIndices[i * (inputOrder + 1) + j] = i;
      }
    }

    const zIndiceslength = zIndices.length;
    const coefficients = arrayScratch;
    const highestNonZeroCoef = fillCoefficientList(
      coefficients,
      zIndices,
      xTable,
      yTable,
      yStride,
      inputOrder
    );
    const reservedIndices = [];

    const tmp = (zIndiceslength * (zIndiceslength + 1)) / 2;
    const loopStop = Math.min(highestNonZeroCoef, outputOrder);
    for (let d = 0; d <= loopStop; d++) {
      for (i = d; i <= highestNonZeroCoef; i++) {
        reservedIndices.length = 0;
        const tempTerm = calculateCoefficientTerm(
          x,
          zIndices,
          xTable,
          d,
          i,
          reservedIndices
        );
        const dimTwo = Math.floor((i * (1 - i)) / 2) + zIndiceslength * i;

        for (let s = 0; s < yStride; s++) {
          const dimOne = Math.floor(s * tmp);
          const coef = coefficients[dimOne + dimTwo];
          result[s + d * yStride] += coef * tempTerm;
        }
      }
    }

    return result;
  };

  function fillCoefficientList(
    coefficients,
    zIndices,
    xTable,
    yTable,
    yStride,
    inputOrder
  ) {
    let j;
    let index;
    let highestNonZero = -1;
    const zIndiceslength = zIndices.length;
    const tmp = (zIndiceslength * (zIndiceslength + 1)) / 2;

    for (let s = 0; s < yStride; s++) {
      const dimOne = Math.floor(s * tmp);

      for (j = 0; j < zIndiceslength; j++) {
        index = zIndices[j] * yStride * (inputOrder + 1) + s;
        coefficients[dimOne + j] = yTable[index];
      }

      for (let i = 1; i < zIndiceslength; i++) {
        let coefIndex = 0;
        const dimTwo = Math.floor((i * (1 - i)) / 2) + zIndiceslength * i;
        let nonZeroCoefficients = false;

        for (j = 0; j < zIndiceslength - i; j++) {
          const zj = xTable[zIndices[j]];
          const zn = xTable[zIndices[j + i]];

          let numerator;
          let coefficient;
          if (zn - zj <= 0) {
            index = zIndices[j] * yStride * (inputOrder + 1) + yStride * i + s;
            numerator = yTable[index];
            coefficient = numerator / CesiumMath.factorial(i);
            coefficients[dimOne + dimTwo + coefIndex] = coefficient;
            coefIndex++;
          } else {
            const dimTwoMinusOne =
              Math.floor(((i - 1) * (2 - i)) / 2) + zIndiceslength * (i - 1);
            numerator =
              coefficients[dimOne + dimTwoMinusOne + j + 1] -
              coefficients[dimOne + dimTwoMinusOne + j];
            coefficient = numerator / (zn - zj);
            coefficients[dimOne + dimTwo + coefIndex] = coefficient;
            coefIndex++;
          }
          nonZeroCoefficients = nonZeroCoefficients || numerator !== 0.0;
        }

        if (nonZeroCoefficients) {
          highestNonZero = Math.max(highestNonZero, i);
        }
      }
    }

    return highestNonZero;
  }

  /**
   * Hilbert Order helper functions.
   *
   * @namespace HilbertOrder
   */
  const HilbertOrder = {};

  /**
   * Computes the Hilbert index at the given level from 2D coordinates.
   *
   * @param {Number} level The level of the curve
   * @param {Number} x The X coordinate
   * @param {Number} y The Y coordinate
   * @returns {Number} The Hilbert index.
   * @private
   */
  HilbertOrder.encode2D = function (level, x, y) {
    const n = Math.pow(2, level);
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("level", level);
    Check.typeOf.number("x", x);
    Check.typeOf.number("y", y);
    if (level < 1) {
      throw new DeveloperError("Hilbert level cannot be less than 1.");
    }
    if (x < 0 || x >= n || y < 0 || y >= n) {
      throw new DeveloperError("Invalid coordinates for given level.");
    }
    //>>includeEnd('debug');

    const p = {
      x: x,
      y: y,
    };
    let rx,
      ry,
      s,
      // eslint-disable-next-line no-undef
      index = BigInt(0);

    for (s = n / 2; s > 0; s /= 2) {
      rx = (p.x & s) > 0 ? 1 : 0;
      ry = (p.y & s) > 0 ? 1 : 0;
      // eslint-disable-next-line no-undef
      index += BigInt(((3 * rx) ^ ry) * s * s);
      rotate$1(n, p, rx, ry);
    }

    return index;
  };

  /**
   * Computes the 2D coordinates from the Hilbert index at the given level.
   *
   * @param {Number} level The level of the curve
   * @param {BigInt} index The Hilbert index
   * @returns {Number[]} An array containing the 2D coordinates ([x, y]) corresponding to the Morton index.
   * @private
   */
  HilbertOrder.decode2D = function (level, index) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("level", level);
    Check.typeOf.bigint("index", index);
    if (level < 1) {
      throw new DeveloperError("Hilbert level cannot be less than 1.");
    }
    // eslint-disable-next-line no-undef
    if (index < BigInt(0) || index >= BigInt(Math.pow(4, level))) {
      throw new DeveloperError(
        "Hilbert index exceeds valid maximum for given level."
      );
    }
    //>>includeEnd('debug');

    const n = Math.pow(2, level);
    const p = {
      x: 0,
      y: 0,
    };
    let rx, ry, s, t;

    for (s = 1, t = index; s < n; s *= 2) {
      // eslint-disable-next-line no-undef
      rx = 1 & Number(t / BigInt(2));
      // eslint-disable-next-line no-undef
      ry = 1 & Number(t ^ BigInt(rx));
      rotate$1(s, p, rx, ry);
      p.x += s * rx;
      p.y += s * ry;
      // eslint-disable-next-line no-undef
      t /= BigInt(4);
    }

    return [p.x, p.y];
  };

  /**
   * @private
   */
  function rotate$1(n, p, rx, ry) {
    if (ry !== 0) {
      return;
    }

    if (rx === 1) {
      p.x = n - 1 - p.x;
      p.y = n - 1 - p.y;
    }

    const t = p.x;
    p.x = p.y;
    p.y = t;
  }

  /**
   * A structure containing the orientation data computed at a particular time. The data
   * represents the direction of the pole of rotation and the rotation about that pole.
   * <p>
   * These parameters correspond to the parameters in the Report from the IAU/IAG Working Group
   * except that they are expressed in radians.
   * </p>
   *
   * @namespace IauOrientationParameters
   *
   * @private
   */
  function IauOrientationParameters(
    rightAscension,
    declination,
    rotation,
    rotationRate
  ) {
    /**
     * The right ascension of the north pole of the body with respect to
     * the International Celestial Reference Frame, in radians.
     * @type {Number}
     *
     * @private
     */
    this.rightAscension = rightAscension;

    /**
     * The declination of the north pole of the body with respect to
     * the International Celestial Reference Frame, in radians.
     * @type {Number}
     *
     * @private
     */
    this.declination = declination;

    /**
     * The rotation about the north pole used to align a set of axes with
     * the meridian defined by the IAU report, in radians.
     * @type {Number}
     *
     * @private
     */
    this.rotation = rotation;

    /**
     * The instantaneous rotation rate about the north pole, in radians per second.
     * @type {Number}
     *
     * @private
     */
    this.rotationRate = rotationRate;
  }

  /**
   * This is a collection of the orientation information available for central bodies.
   * The data comes from the Report of the IAU/IAG Working Group on Cartographic
   * Coordinates and Rotational Elements: 2000.
   *
   * @namespace Iau2000Orientation
   *
   * @private
   */
  const Iau2000Orientation = {};

  const TdtMinusTai$1 = 32.184;
  const J2000d$1 = 2451545.0;

  const c1 = -0.0529921;
  const c2 = -0.1059842;
  const c3 = 13.0120009;
  const c4 = 13.3407154;
  const c5 = 0.9856003;
  const c6 = 26.4057084;
  const c7 = 13.064993;
  const c8 = 0.3287146;
  const c9 = 1.7484877;
  const c10 = -0.1589763;
  const c11 = 0.0036096;
  const c12 = 0.1643573;
  const c13 = 12.9590088;
  let dateTT = new JulianDate();

  /**
   * Compute the orientation parameters for the Moon.
   *
   * @param {JulianDate} [date=JulianDate.now()] The date to evaluate the parameters.
   * @param {IauOrientationParameters} [result] The object onto which to store the result.
   * @returns {IauOrientationParameters} The modified result parameter or a new instance representing the orientation of the Earth's Moon.
   * @private
   */
  Iau2000Orientation.ComputeMoon = function (date, result) {
    if (!defined(date)) {
      date = JulianDate.now();
    }

    dateTT = JulianDate.addSeconds(date, TdtMinusTai$1, dateTT);
    const d = JulianDate.totalDays(dateTT) - J2000d$1;
    const T = d / TimeConstants$1.DAYS_PER_JULIAN_CENTURY;

    const E1 = (125.045 + c1 * d) * CesiumMath.RADIANS_PER_DEGREE;
    const E2 = (250.089 + c2 * d) * CesiumMath.RADIANS_PER_DEGREE;
    const E3 = (260.008 + c3 * d) * CesiumMath.RADIANS_PER_DEGREE;
    const E4 = (176.625 + c4 * d) * CesiumMath.RADIANS_PER_DEGREE;
    const E5 = (357.529 + c5 * d) * CesiumMath.RADIANS_PER_DEGREE;
    const E6 = (311.589 + c6 * d) * CesiumMath.RADIANS_PER_DEGREE;
    const E7 = (134.963 + c7 * d) * CesiumMath.RADIANS_PER_DEGREE;
    const E8 = (276.617 + c8 * d) * CesiumMath.RADIANS_PER_DEGREE;
    const E9 = (34.226 + c9 * d) * CesiumMath.RADIANS_PER_DEGREE;
    const E10 = (15.134 + c10 * d) * CesiumMath.RADIANS_PER_DEGREE;
    const E11 = (119.743 + c11 * d) * CesiumMath.RADIANS_PER_DEGREE;
    const E12 = (239.961 + c12 * d) * CesiumMath.RADIANS_PER_DEGREE;
    const E13 = (25.053 + c13 * d) * CesiumMath.RADIANS_PER_DEGREE;

    const sinE1 = Math.sin(E1);
    const sinE2 = Math.sin(E2);
    const sinE3 = Math.sin(E3);
    const sinE4 = Math.sin(E4);
    const sinE5 = Math.sin(E5);
    const sinE6 = Math.sin(E6);
    const sinE7 = Math.sin(E7);
    const sinE8 = Math.sin(E8);
    const sinE9 = Math.sin(E9);
    const sinE10 = Math.sin(E10);
    const sinE11 = Math.sin(E11);
    const sinE12 = Math.sin(E12);
    const sinE13 = Math.sin(E13);

    const cosE1 = Math.cos(E1);
    const cosE2 = Math.cos(E2);
    const cosE3 = Math.cos(E3);
    const cosE4 = Math.cos(E4);
    const cosE5 = Math.cos(E5);
    const cosE6 = Math.cos(E6);
    const cosE7 = Math.cos(E7);
    const cosE8 = Math.cos(E8);
    const cosE9 = Math.cos(E9);
    const cosE10 = Math.cos(E10);
    const cosE11 = Math.cos(E11);
    const cosE12 = Math.cos(E12);
    const cosE13 = Math.cos(E13);

    const rightAscension =
      (269.9949 +
        0.0031 * T -
        3.8787 * sinE1 -
        0.1204 * sinE2 +
        0.07 * sinE3 -
        0.0172 * sinE4 +
        0.0072 * sinE6 -
        0.0052 * sinE10 +
        0.0043 * sinE13) *
      CesiumMath.RADIANS_PER_DEGREE;
    const declination =
      (66.5392 +
        0.013 * T +
        1.5419 * cosE1 +
        0.0239 * cosE2 -
        0.0278 * cosE3 +
        0.0068 * cosE4 -
        0.0029 * cosE6 +
        0.0009 * cosE7 +
        0.0008 * cosE10 -
        0.0009 * cosE13) *
      CesiumMath.RADIANS_PER_DEGREE;
    const rotation =
      (38.3213 +
        13.17635815 * d -
        1.4e-12 * d * d +
        3.561 * sinE1 +
        0.1208 * sinE2 -
        0.0642 * sinE3 +
        0.0158 * sinE4 +
        0.0252 * sinE5 -
        0.0066 * sinE6 -
        0.0047 * sinE7 -
        0.0046 * sinE8 +
        0.0028 * sinE9 +
        0.0052 * sinE10 +
        0.004 * sinE11 +
        0.0019 * sinE12 -
        0.0044 * sinE13) *
      CesiumMath.RADIANS_PER_DEGREE;

    const rotationRate =
      ((13.17635815 -
        1.4e-12 * (2.0 * d) +
        3.561 * cosE1 * c1 +
        0.1208 * cosE2 * c2 -
        0.0642 * cosE3 * c3 +
        0.0158 * cosE4 * c4 +
        0.0252 * cosE5 * c5 -
        0.0066 * cosE6 * c6 -
        0.0047 * cosE7 * c7 -
        0.0046 * cosE8 * c8 +
        0.0028 * cosE9 * c9 +
        0.0052 * cosE10 * c10 +
        0.004 * cosE11 * c11 +
        0.0019 * cosE12 * c12 -
        0.0044 * cosE13 * c13) /
        86400.0) *
      CesiumMath.RADIANS_PER_DEGREE;

    if (!defined(result)) {
      result = new IauOrientationParameters();
    }

    result.rightAscension = rightAscension;
    result.declination = declination;
    result.rotation = rotation;
    result.rotationRate = rotationRate;

    return result;
  };

  /**
   * The Axes representing the orientation of a Globe as represented by the data
   * from the IAU/IAG Working Group reports on rotational elements.
   * @alias IauOrientationAxes
   * @constructor
   *
   * @param {IauOrientationAxes.ComputeFunction} [computeFunction] The function that computes the {@link IauOrientationParameters} given a {@link JulianDate}.
   *
   * @see Iau2000Orientation
   *
   * @private
   */
  function IauOrientationAxes(computeFunction) {
    if (!defined(computeFunction) || typeof computeFunction !== "function") {
      computeFunction = Iau2000Orientation.ComputeMoon;
    }

    this._computeFunction = computeFunction;
  }

  const xAxisScratch = new Cartesian3();
  const yAxisScratch = new Cartesian3();
  const zAxisScratch = new Cartesian3();

  function computeRotationMatrix(alpha, delta, result) {
    const xAxis = xAxisScratch;
    xAxis.x = Math.cos(alpha + CesiumMath.PI_OVER_TWO);
    xAxis.y = Math.sin(alpha + CesiumMath.PI_OVER_TWO);
    xAxis.z = 0.0;

    const cosDec = Math.cos(delta);

    const zAxis = zAxisScratch;
    zAxis.x = cosDec * Math.cos(alpha);
    zAxis.y = cosDec * Math.sin(alpha);
    zAxis.z = Math.sin(delta);

    const yAxis = Cartesian3.cross(zAxis, xAxis, yAxisScratch);

    if (!defined(result)) {
      result = new Matrix3();
    }

    result[0] = xAxis.x;
    result[1] = yAxis.x;
    result[2] = zAxis.x;
    result[3] = xAxis.y;
    result[4] = yAxis.y;
    result[5] = zAxis.y;
    result[6] = xAxis.z;
    result[7] = yAxis.z;
    result[8] = zAxis.z;

    return result;
  }

  const rotMtxScratch = new Matrix3();
  const quatScratch = new Quaternion();

  /**
   * Computes a rotation from ICRF to a Globe's Fixed axes.
   *
   * @param {JulianDate} date The date to evaluate the matrix.
   * @param {Matrix3} result The object onto which to store the result.
   * @returns {Matrix3} The modified result parameter or a new instance of the rotation from ICRF to Fixed.
   */
  IauOrientationAxes.prototype.evaluate = function (date, result) {
    if (!defined(date)) {
      date = JulianDate.now();
    }

    const alphaDeltaW = this._computeFunction(date);
    const precMtx = computeRotationMatrix(
      alphaDeltaW.rightAscension,
      alphaDeltaW.declination,
      result
    );

    const rot = CesiumMath.zeroToTwoPi(alphaDeltaW.rotation);
    const quat = Quaternion.fromAxisAngle(Cartesian3.UNIT_Z, rot, quatScratch);
    const rotMtx = Matrix3.fromQuaternion(
      Quaternion.conjugate(quat, quat),
      rotMtxScratch
    );

    const cbi2cbf = Matrix3.multiply(rotMtx, precMtx, precMtx);
    return cbi2cbf;
  };

  /**
   * The interface for interpolation algorithms.
   *
   * @interface InterpolationAlgorithm
   *
   * @see LagrangePolynomialApproximation
   * @see LinearApproximation
   * @see HermitePolynomialApproximation
   */
  const InterpolationAlgorithm = {};

  /**
   * Gets the name of this interpolation algorithm.
   * @type {String}
   */
  InterpolationAlgorithm.type = undefined;

  /**
   * Given the desired degree, returns the number of data points required for interpolation.
   * @function
   *
   * @param {Number} degree The desired degree of interpolation.
   * @returns {Number} The number of required data points needed for the desired degree of interpolation.
   */
  InterpolationAlgorithm.getRequiredDataPoints =
    DeveloperError.throwInstantiationError;

  /**
   * Performs zero order interpolation.
   * @function
   *
   * @param {Number} x The independent variable for which the dependent variables will be interpolated.
   * @param {Number[]} xTable The array of independent variables to use to interpolate.  The values
   * in this array must be in increasing order and the same value must not occur twice in the array.
   * @param {Number[]} yTable The array of dependent variables to use to interpolate.  For a set of three
   * dependent values (p,q,w) at time 1 and time 2 this should be as follows: {p1, q1, w1, p2, q2, w2}.
   * @param {Number} yStride The number of dependent variable values in yTable corresponding to
   * each independent variable value in xTable.
   * @param {Number[]} [result] An existing array into which to store the result.
   *
   * @returns {Number[]} The array of interpolated values, or the result parameter if one was provided.
   */
  InterpolationAlgorithm.interpolateOrderZero =
    DeveloperError.throwInstantiationError;

  /**
   * Performs higher order interpolation.  Not all interpolators need to support high-order interpolation,
   * if this function remains undefined on implementing objects, interpolateOrderZero will be used instead.
   * @function
   * @param {Number} x The independent variable for which the dependent variables will be interpolated.
   * @param {Number[]} xTable The array of independent variables to use to interpolate.  The values
   * in this array must be in increasing order and the same value must not occur twice in the array.
   * @param {Number[]} yTable The array of dependent variables to use to interpolate.  For a set of three
   * dependent values (p,q,w) at time 1 and time 2 this should be as follows: {p1, q1, w1, p2, q2, w2}.
   * @param {Number} yStride The number of dependent variable values in yTable corresponding to
   * each independent variable value in xTable.
   * @param {Number} inputOrder The number of derivatives supplied for input.
   * @param {Number} outputOrder The number of derivatives desired for output.
   * @param {Number[]} [result] An existing array into which to store the result.
   * @returns {Number[]} The array of interpolated values, or the result parameter if one was provided.
   */
  InterpolationAlgorithm.interpolate = DeveloperError.throwInstantiationError;

  /**
   * An enum describing the type of interpolation used in a glTF animation.
   *
   * @enum {Number}
   *
   * @private
   */
  const InterpolationType = {
    STEP: 0,
    LINEAR: 1,
    CUBICSPLINE: 2,
  };

  var InterpolationType$1 = Object.freeze(InterpolationType);

  let defaultTokenCredit;
  const defaultAccessToken =
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIwNzAxODk2YS03MTc4LTQxYmYtOWYwMC0xZmUwNTQ5ZWYwMDYiLCJpZCI6MjU5LCJpYXQiOjE2NTY2ODI5ODF9.9O2dVq-nQdlJbXG3lZYFNpzv_tR0jF_xjr0gb02x9M4";

  /**
   * Default settings for accessing the Cesium ion API.
   *
   * An ion access token is only required if you are using any ion related APIs.
   * A default access token is provided for evaluation purposes only.
   * Sign up for a free ion account and get your own access token at {@link https://cesium.com}
   *
   * @see IonResource
   * @see IonImageryProvider
   * @see IonGeocoderService
   * @see createWorldImagery
   * @see createWorldTerrain
   * @namespace Ion
   */
  const Ion = {};

  /**
   * Gets or sets the default Cesium ion access token.
   *
   * @type {String}
   */
  Ion.defaultAccessToken = defaultAccessToken;

  /**
   * Gets or sets the default Cesium ion server.
   *
   * @type {String|Resource}
   * @default https://api.cesium.com
   */
  Ion.defaultServer = new Resource({ url: "https://api.cesium.com/" });

  Ion.getDefaultTokenCredit = function (providedKey) {
    if (providedKey !== defaultAccessToken) {
      return undefined;
    }

    if (!defined(defaultTokenCredit)) {
      const defaultTokenMessage =
        '<b> \
            This application is using Cesium\'s default ion access token. Please assign <i>Cesium.Ion.defaultAccessToken</i> \
            with an access token from your ion account before making any Cesium API calls. \
            You can sign up for a free ion account at <a href="https://cesium.com">https://cesium.com</a>.</b>';

      defaultTokenCredit = new Credit(defaultTokenMessage, true);
    }

    return defaultTokenCredit;
  };

  /**
   * Provides geocoding via a {@link https://pelias.io/|Pelias} server.
   * @alias PeliasGeocoderService
   * @constructor
   *
   * @param {Resource|String} url The endpoint to the Pelias server.
   *
   * @example
   * // Configure a Viewer to use the Pelias server hosted by https://geocode.earth/
   * const viewer = new Cesium.Viewer('cesiumContainer', {
   *   geocoder: new Cesium.PeliasGeocoderService(new Cesium.Resource({
   *     url: 'https://api.geocode.earth/v1/',
   *       queryParameters: {
   *         api_key: '<Your geocode.earth API key>'
   *     }
   *   }))
   * });
   */
  function PeliasGeocoderService(url) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("url", url);
    //>>includeEnd('debug');

    this._url = Resource.createIfNeeded(url);
    this._url.appendForwardSlash();
  }

  Object.defineProperties(PeliasGeocoderService.prototype, {
    /**
     * The Resource used to access the Pelias endpoint.
     * @type {Resource}
     * @memberof PeliasGeocoderService.prototype
     * @readonly
     */
    url: {
      get: function () {
        return this._url;
      },
    },
  });

  /**
   * @function
   *
   * @param {String} query The query to be sent to the geocoder service
   * @param {GeocodeType} [type=GeocodeType.SEARCH] The type of geocode to perform.
   * @returns {Promise<GeocoderService.Result[]>}
   */
  PeliasGeocoderService.prototype.geocode = function (query, type) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("query", query);
    //>>includeEnd('debug');

    const resource = this._url.getDerivedResource({
      url: type === GeocodeType$1.AUTOCOMPLETE ? "autocomplete" : "search",
      queryParameters: {
        text: query,
      },
    });

    return resource.fetchJson().then(function (results) {
      return results.features.map(function (resultObject) {
        let destination;
        const bboxDegrees = resultObject.bbox;

        if (defined(bboxDegrees)) {
          destination = Rectangle.fromDegrees(
            bboxDegrees[0],
            bboxDegrees[1],
            bboxDegrees[2],
            bboxDegrees[3]
          );
        } else {
          const lon = resultObject.geometry.coordinates[0];
          const lat = resultObject.geometry.coordinates[1];
          destination = Cartesian3.fromDegrees(lon, lat);
        }

        return {
          displayName: resultObject.properties.label,
          destination: destination,
        };
      });
    });
  };

  /**
   * Provides geocoding through Cesium ion.
   * @alias IonGeocoderService
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Scene} options.scene The scene
   * @param {String} [options.accessToken=Ion.defaultAccessToken] The access token to use.
   * @param {String|Resource} [options.server=Ion.defaultServer] The resource to the Cesium ion API server.
   *
   * @see Ion
   */
  function IonGeocoderService(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.scene", options.scene);
    //>>includeEnd('debug');

    const accessToken = defaultValue(options.accessToken, Ion.defaultAccessToken);
    const server = Resource.createIfNeeded(
      defaultValue(options.server, Ion.defaultServer)
    );
    server.appendForwardSlash();

    const defaultTokenCredit = Ion.getDefaultTokenCredit(accessToken);
    if (defined(defaultTokenCredit)) {
      options.scene.frameState.creditDisplay.addDefaultCredit(
        Credit.clone(defaultTokenCredit)
      );
    }

    const searchEndpoint = server.getDerivedResource({
      url: "v1/geocode",
    });

    if (defined(accessToken)) {
      searchEndpoint.appendQueryParameters({ access_token: accessToken });
    }

    this._accessToken = accessToken;
    this._server = server;
    this._pelias = new PeliasGeocoderService(searchEndpoint);
  }

  /**
   * @function
   *
   * @param {String} query The query to be sent to the geocoder service
   * @param {GeocodeType} [type=GeocodeType.SEARCH] The type of geocode to perform.
   * @returns {Promise<GeocoderService.Result[]>}
   */
  IonGeocoderService.prototype.geocode = function (query, geocodeType) {
    return this._pelias.geocode(query, geocodeType);
  };

  /**
   * A {@link Resource} instance that encapsulates Cesium ion asset access.
   * This object is normally not instantiated directly, use {@link IonResource.fromAssetId}.
   *
   * @alias IonResource
   * @constructor
   * @augments Resource
   *
   * @param {Object} endpoint The result of the Cesium ion asset endpoint service.
   * @param {Resource} endpointResource The resource used to retreive the endpoint.
   *
   * @see Ion
   * @see IonImageryProvider
   * @see createWorldTerrain
   * @see https://cesium.com
   */
  function IonResource(endpoint, endpointResource) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("endpoint", endpoint);
    Check.defined("endpointResource", endpointResource);
    //>>includeEnd('debug');

    let options;
    const externalType = endpoint.externalType;
    const isExternal = defined(externalType);

    if (!isExternal) {
      options = {
        url: endpoint.url,
        retryAttempts: 1,
        retryCallback: retryCallback,
      };
    } else if (
      externalType === "3DTILES" ||
      externalType === "STK_TERRAIN_SERVER"
    ) {
      // 3D Tiles and STK Terrain Server external assets can still be represented as an IonResource
      options = { url: endpoint.options.url };
    } else {
      //External imagery assets have additional configuration that can't be represented as a Resource
      throw new RuntimeError(
        "Ion.createResource does not support external imagery assets; use IonImageryProvider instead."
      );
    }

    Resource.call(this, options);

    // The asset endpoint data returned from ion.
    this._ionEndpoint = endpoint;
    this._ionEndpointDomain = isExternal
      ? undefined
      : new URI(endpoint.url).authority();

    // The endpoint resource to fetch when a new token is needed
    this._ionEndpointResource = endpointResource;

    // The primary IonResource from which an instance is derived
    this._ionRoot = undefined;

    // Shared promise for endpooint requests amd credits (only ever set on the root request)
    this._pendingPromise = undefined;
    this._credits = undefined;
    this._isExternal = isExternal;
  }

  if (defined(Object.create)) {
    IonResource.prototype = Object.create(Resource.prototype);
    IonResource.prototype.constructor = IonResource;
  }

  /**
   * Asynchronously creates an instance.
   *
   * @param {Number} assetId The Cesium ion asset id.
   * @param {Object} [options] An object with the following properties:
   * @param {String} [options.accessToken=Ion.defaultAccessToken] The access token to use.
   * @param {String|Resource} [options.server=Ion.defaultServer] The resource to the Cesium ion API server.
   * @returns {Promise.<IonResource>} A Promise to am instance representing the Cesium ion Asset.
   *
   * @example
   * //Load a Cesium3DTileset with asset ID of 124624234
   * viewer.scene.primitives.add(new Cesium.Cesium3DTileset({ url: Cesium.IonResource.fromAssetId(124624234) }));
   *
   * @example
   * //Load a CZML file with asset ID of 10890
   * Cesium.IonResource.fromAssetId(10890)
   *   .then(function (resource) {
   *     viewer.dataSources.add(Cesium.CzmlDataSource.load(resource));
   *   });
   */
  IonResource.fromAssetId = function (assetId, options) {
    const endpointResource = IonResource._createEndpointResource(
      assetId,
      options
    );

    return endpointResource.fetchJson().then(function (endpoint) {
      return new IonResource(endpoint, endpointResource);
    });
  };

  Object.defineProperties(IonResource.prototype, {
    /**
     * Gets the credits required for attribution of the asset.
     *
     * @memberof IonResource.prototype
     * @type {Credit[]}
     * @readonly
     */
    credits: {
      get: function () {
        // Only we're not the root, return its credits;
        if (defined(this._ionRoot)) {
          return this._ionRoot.credits;
        }

        // We are the root
        if (defined(this._credits)) {
          return this._credits;
        }

        this._credits = IonResource.getCreditsFromEndpoint(
          this._ionEndpoint,
          this._ionEndpointResource
        );

        return this._credits;
      },
    },
  });

  /** @private */
  IonResource.getCreditsFromEndpoint = function (endpoint, endpointResource) {
    const credits = endpoint.attributions.map(Credit.getIonCredit);
    const defaultTokenCredit = Ion.getDefaultTokenCredit(
      endpointResource.queryParameters.access_token
    );
    if (defined(defaultTokenCredit)) {
      credits.push(Credit.clone(defaultTokenCredit));
    }
    return credits;
  };

  /** @inheritdoc */
  IonResource.prototype.clone = function (result) {
    // We always want to use the root's information because it's the most up-to-date
    const ionRoot = defaultValue(this._ionRoot, this);

    if (!defined(result)) {
      result = new IonResource(
        ionRoot._ionEndpoint,
        ionRoot._ionEndpointResource
      );
    }

    result = Resource.prototype.clone.call(this, result);
    result._ionRoot = ionRoot;
    result._isExternal = this._isExternal;

    return result;
  };

  IonResource.prototype.fetchImage = function (options) {
    if (!this._isExternal) {
      const userOptions = options;
      options = {
        preferBlob: true,
      };
      if (defined(userOptions)) {
        options.flipY = userOptions.flipY;
        options.preferImageBitmap = userOptions.preferImageBitmap;
      }
    }

    return Resource.prototype.fetchImage.call(this, options);
  };

  IonResource.prototype._makeRequest = function (options) {
    // Don't send ion access token to non-ion servers.
    if (
      this._isExternal ||
      new URI(this.url).authority() !== this._ionEndpointDomain
    ) {
      return Resource.prototype._makeRequest.call(this, options);
    }

    if (!defined(options.headers)) {
      options.headers = {};
    }
    options.headers.Authorization = `Bearer ${this._ionEndpoint.accessToken}`;

    return Resource.prototype._makeRequest.call(this, options);
  };

  /**
   * @private
   */
  IonResource._createEndpointResource = function (assetId, options) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("assetId", assetId);
    //>>includeEnd('debug');

    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    let server = defaultValue(options.server, Ion.defaultServer);
    const accessToken = defaultValue(options.accessToken, Ion.defaultAccessToken);
    server = Resource.createIfNeeded(server);

    const resourceOptions = {
      url: `v1/assets/${assetId}/endpoint`,
    };

    if (defined(accessToken)) {
      resourceOptions.queryParameters = { access_token: accessToken };
    }

    return server.getDerivedResource(resourceOptions);
  };

  function retryCallback(that, error) {
    const ionRoot = defaultValue(that._ionRoot, that);
    const endpointResource = ionRoot._ionEndpointResource;

    // Image is not available in worker threads, so this avoids
    // a ReferenceError
    const imageDefined = typeof Image !== "undefined";

    // We only want to retry in the case of invalid credentials (401) or image
    // requests(since Image failures can not provide a status code)
    if (
      !defined(error) ||
      (error.statusCode !== 401 &&
        !(imageDefined && error.target instanceof Image))
    ) {
      return Promise.resolve(false);
    }

    // We use a shared pending promise for all derived assets, since they share
    // a common access_token.  If we're already requesting a new token for this
    // asset, we wait on the same promise.
    if (!defined(ionRoot._pendingPromise)) {
      ionRoot._pendingPromise = endpointResource
        .fetchJson()
        .then(function (newEndpoint) {
          //Set the token for root resource so new derived resources automatically pick it up
          ionRoot._ionEndpoint = newEndpoint;
          return newEndpoint;
        })
        .finally(function (newEndpoint) {
          // Pass or fail, we're done with this promise, the next failure should use a new one.
          ionRoot._pendingPromise = undefined;
          return newEndpoint;
        });
    }

    return ionRoot._pendingPromise.then(function (newEndpoint) {
      // Set the new token and endpoint for this resource
      that._ionEndpoint = newEndpoint;
      return true;
    });
  }

  /**
   * An interval defined by a start and a stop time; optionally including those times as part of the interval.
   * Arbitrary data can optionally be associated with each instance for used with {@link TimeIntervalCollection}.
   *
   * @alias TimeInterval
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {JulianDate} [options.start=new JulianDate()] The start time of the interval.
   * @param {JulianDate} [options.stop=new JulianDate()] The stop time of the interval.
   * @param {Boolean} [options.isStartIncluded=true] <code>true</code> if <code>options.start</code> is included in the interval, <code>false</code> otherwise.
   * @param {Boolean} [options.isStopIncluded=true] <code>true</code> if <code>options.stop</code> is included in the interval, <code>false</code> otherwise.
   * @param {Object} [options.data] Arbitrary data associated with this interval.
   *
   * @example
   * // Create an instance that spans August 1st, 1980 and is associated
   * // with a Cartesian position.
   * const timeInterval = new Cesium.TimeInterval({
   *     start : Cesium.JulianDate.fromIso8601('1980-08-01T00:00:00Z'),
   *     stop : Cesium.JulianDate.fromIso8601('1980-08-02T00:00:00Z'),
   *     isStartIncluded : true,
   *     isStopIncluded : false,
   *     data : Cesium.Cartesian3.fromDegrees(39.921037, -75.170082)
   * });
   *
   * @example
   * // Create two instances from ISO 8601 intervals with associated numeric data
   * // then compute their intersection, summing the data they contain.
   * const left = Cesium.TimeInterval.fromIso8601({
   *     iso8601 : '2000/2010',
   *     data : 2
   * });
   *
   * const right = Cesium.TimeInterval.fromIso8601({
   *     iso8601 : '1995/2005',
   *     data : 3
   * });
   *
   * //The result of the below intersection will be an interval equivalent to
   * //const intersection = Cesium.TimeInterval.fromIso8601({
   * //  iso8601 : '2000/2005',
   * //  data : 5
   * //});
   * const intersection = new Cesium.TimeInterval();
   * Cesium.TimeInterval.intersect(left, right, intersection, function(leftData, rightData) {
   *     return leftData + rightData;
   * });
   *
   * @example
   * // Check if an interval contains a specific time.
   * const dateToCheck = Cesium.JulianDate.fromIso8601('1982-09-08T11:30:00Z');
   * const containsDate = Cesium.TimeInterval.contains(timeInterval, dateToCheck);
   */
  function TimeInterval(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    /**
     * Gets or sets the start time of this interval.
     * @type {JulianDate}
     */
    this.start = defined(options.start)
      ? JulianDate.clone(options.start)
      : new JulianDate();

    /**
     * Gets or sets the stop time of this interval.
     * @type {JulianDate}
     */
    this.stop = defined(options.stop)
      ? JulianDate.clone(options.stop)
      : new JulianDate();

    /**
     * Gets or sets the data associated with this interval.
     * @type {*}
     */
    this.data = options.data;

    /**
     * Gets or sets whether or not the start time is included in this interval.
     * @type {Boolean}
     * @default true
     */
    this.isStartIncluded = defaultValue(options.isStartIncluded, true);

    /**
     * Gets or sets whether or not the stop time is included in this interval.
     * @type {Boolean}
     * @default true
     */
    this.isStopIncluded = defaultValue(options.isStopIncluded, true);
  }

  Object.defineProperties(TimeInterval.prototype, {
    /**
     * Gets whether or not this interval is empty.
     * @memberof TimeInterval.prototype
     * @type {Boolean}
     * @readonly
     */
    isEmpty: {
      get: function () {
        const stopComparedToStart = JulianDate.compare(this.stop, this.start);
        return (
          stopComparedToStart < 0 ||
          (stopComparedToStart === 0 &&
            (!this.isStartIncluded || !this.isStopIncluded))
        );
      },
    },
  });

  const scratchInterval = {
    start: undefined,
    stop: undefined,
    isStartIncluded: undefined,
    isStopIncluded: undefined,
    data: undefined,
  };

  /**
   * Creates a new instance from a {@link http://en.wikipedia.org/wiki/ISO_8601|ISO 8601} interval.
   *
   * @throws DeveloperError if options.iso8601 does not match proper formatting.
   *
   * @param {Object} options Object with the following properties:
   * @param {String} options.iso8601 An ISO 8601 interval.
   * @param {Boolean} [options.isStartIncluded=true] <code>true</code> if <code>options.start</code> is included in the interval, <code>false</code> otherwise.
   * @param {Boolean} [options.isStopIncluded=true] <code>true</code> if <code>options.stop</code> is included in the interval, <code>false</code> otherwise.
   * @param {Object} [options.data] Arbitrary data associated with this interval.
   * @param {TimeInterval} [result] An existing instance to use for the result.
   * @returns {TimeInterval} The modified result parameter or a new instance if none was provided.
   */
  TimeInterval.fromIso8601 = function (options, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options", options);
    Check.typeOf.string("options.iso8601", options.iso8601);
    //>>includeEnd('debug');

    const dates = options.iso8601.split("/");
    if (dates.length !== 2) {
      throw new DeveloperError(
        "options.iso8601 is an invalid ISO 8601 interval."
      );
    }
    const start = JulianDate.fromIso8601(dates[0]);
    const stop = JulianDate.fromIso8601(dates[1]);
    const isStartIncluded = defaultValue(options.isStartIncluded, true);
    const isStopIncluded = defaultValue(options.isStopIncluded, true);
    const data = options.data;

    if (!defined(result)) {
      scratchInterval.start = start;
      scratchInterval.stop = stop;
      scratchInterval.isStartIncluded = isStartIncluded;
      scratchInterval.isStopIncluded = isStopIncluded;
      scratchInterval.data = data;
      return new TimeInterval(scratchInterval);
    }

    result.start = start;
    result.stop = stop;
    result.isStartIncluded = isStartIncluded;
    result.isStopIncluded = isStopIncluded;
    result.data = data;
    return result;
  };

  /**
   * Creates an ISO8601 representation of the provided interval.
   *
   * @param {TimeInterval} timeInterval The interval 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 interval.
   */
  TimeInterval.toIso8601 = function (timeInterval, precision) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("timeInterval", timeInterval);
    //>>includeEnd('debug');

    return `${JulianDate.toIso8601(
    timeInterval.start,
    precision
  )}/${JulianDate.toIso8601(timeInterval.stop, precision)}`;
  };

  /**
   * Duplicates the provided instance.
   *
   * @param {TimeInterval} [timeInterval] The instance to clone.
   * @param {TimeInterval} [result] An existing instance to use for the result.
   * @returns {TimeInterval} The modified result parameter or a new instance if none was provided.
   */
  TimeInterval.clone = function (timeInterval, result) {
    if (!defined(timeInterval)) {
      return undefined;
    }
    if (!defined(result)) {
      return new TimeInterval(timeInterval);
    }
    result.start = timeInterval.start;
    result.stop = timeInterval.stop;
    result.isStartIncluded = timeInterval.isStartIncluded;
    result.isStopIncluded = timeInterval.isStopIncluded;
    result.data = timeInterval.data;
    return result;
  };

  /**
   * Compares two instances and returns <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {TimeInterval} [left] The first instance.
   * @param {TimeInterval} [right] The second instance.
   * @param {TimeInterval.DataComparer} [dataComparer] A function which compares the data of the two intervals.  If omitted, reference equality is used.
   * @returns {Boolean} <code>true</code> if the dates are equal; otherwise, <code>false</code>.
   */
  TimeInterval.equals = function (left, right, dataComparer) {
    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        ((left.isEmpty && right.isEmpty) ||
          (left.isStartIncluded === right.isStartIncluded &&
            left.isStopIncluded === right.isStopIncluded &&
            JulianDate.equals(left.start, right.start) &&
            JulianDate.equals(left.stop, right.stop) &&
            (left.data === right.data ||
              (defined(dataComparer) && dataComparer(left.data, right.data))))))
    );
  };

  /**
   * Compares two instances and returns <code>true</code> if they are within <code>epsilon</code> seconds of
   * each other.  That is, in order for the dates to be considered equal (and for
   * this function to return <code>true</code>), the absolute value of the difference between them, in
   * seconds, must be less than <code>epsilon</code>.
   *
   * @param {TimeInterval} [left] The first instance.
   * @param {TimeInterval} [right] The second instance.
   * @param {Number} [epsilon=0] The maximum number of seconds that should separate the two instances.
   * @param {TimeInterval.DataComparer} [dataComparer] A function which compares the data of the two intervals.  If omitted, reference equality is used.
   * @returns {Boolean} <code>true</code> if the two dates are within <code>epsilon</code> seconds of each other; otherwise <code>false</code>.
   */
  TimeInterval.equalsEpsilon = function (left, right, epsilon, dataComparer) {
    epsilon = defaultValue(epsilon, 0);

    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        ((left.isEmpty && right.isEmpty) ||
          (left.isStartIncluded === right.isStartIncluded &&
            left.isStopIncluded === right.isStopIncluded &&
            JulianDate.equalsEpsilon(left.start, right.start, epsilon) &&
            JulianDate.equalsEpsilon(left.stop, right.stop, epsilon) &&
            (left.data === right.data ||
              (defined(dataComparer) && dataComparer(left.data, right.data))))))
    );
  };

  /**
   * Computes the intersection of two intervals, optionally merging their data.
   *
   * @param {TimeInterval} left The first interval.
   * @param {TimeInterval} [right] The second interval.
   * @param {TimeInterval} [result] An existing instance to use for the result.
   * @param {TimeInterval.MergeCallback} [mergeCallback] A function which merges the data of the two intervals. If omitted, the data from the left interval will be used.
   * @returns {TimeInterval} The modified result parameter.
   */
  TimeInterval.intersect = function (left, right, result, mergeCallback) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("left", left);
    //>>includeEnd('debug');

    if (!defined(right)) {
      return TimeInterval.clone(TimeInterval.EMPTY, result);
    }

    const leftStart = left.start;
    const leftStop = left.stop;

    const rightStart = right.start;
    const rightStop = right.stop;

    const intersectsStartRight =
      JulianDate.greaterThanOrEquals(rightStart, leftStart) &&
      JulianDate.greaterThanOrEquals(leftStop, rightStart);
    const intersectsStartLeft =
      !intersectsStartRight &&
      JulianDate.lessThanOrEquals(rightStart, leftStart) &&
      JulianDate.lessThanOrEquals(leftStart, rightStop);

    if (!intersectsStartRight && !intersectsStartLeft) {
      return TimeInterval.clone(TimeInterval.EMPTY, result);
    }

    const leftIsStartIncluded = left.isStartIncluded;
    const leftIsStopIncluded = left.isStopIncluded;
    const rightIsStartIncluded = right.isStartIncluded;
    const rightIsStopIncluded = right.isStopIncluded;
    const leftLessThanRight = JulianDate.lessThan(leftStop, rightStop);

    if (!defined(result)) {
      result = new TimeInterval();
    }

    result.start = intersectsStartRight ? rightStart : leftStart;
    result.isStartIncluded =
      (leftIsStartIncluded && rightIsStartIncluded) ||
      (!JulianDate.equals(rightStart, leftStart) &&
        ((intersectsStartRight && rightIsStartIncluded) ||
          (intersectsStartLeft && leftIsStartIncluded)));
    result.stop = leftLessThanRight ? leftStop : rightStop;
    result.isStopIncluded = leftLessThanRight
      ? leftIsStopIncluded
      : (leftIsStopIncluded && rightIsStopIncluded) ||
        (!JulianDate.equals(rightStop, leftStop) && rightIsStopIncluded);
    result.data = defined(mergeCallback)
      ? mergeCallback(left.data, right.data)
      : left.data;
    return result;
  };

  /**
   * Checks if the specified date is inside the provided interval.
   *
   * @param {TimeInterval} timeInterval The interval.
   * @param {JulianDate} julianDate The date to check.
   * @returns {Boolean} <code>true</code> if the interval contains the specified date, <code>false</code> otherwise.
   */
  TimeInterval.contains = function (timeInterval, julianDate) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("timeInterval", timeInterval);
    Check.typeOf.object("julianDate", julianDate);
    //>>includeEnd('debug');

    if (timeInterval.isEmpty) {
      return false;
    }

    const startComparedToDate = JulianDate.compare(
      timeInterval.start,
      julianDate
    );
    if (startComparedToDate === 0) {
      return timeInterval.isStartIncluded;
    }

    const dateComparedToStop = JulianDate.compare(julianDate, timeInterval.stop);
    if (dateComparedToStop === 0) {
      return timeInterval.isStopIncluded;
    }

    return startComparedToDate < 0 && dateComparedToStop < 0;
  };

  /**
   * Duplicates this instance.
   *
   * @param {TimeInterval} [result] An existing instance to use for the result.
   * @returns {TimeInterval} The modified result parameter or a new instance if none was provided.
   */
  TimeInterval.prototype.clone = function (result) {
    return TimeInterval.clone(this, result);
  };

  /**
   * Compares this instance against the provided instance componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {TimeInterval} [right] The right hand side interval.
   * @param {TimeInterval.DataComparer} [dataComparer] A function which compares the data of the two intervals.  If omitted, reference equality is used.
   * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
   */
  TimeInterval.prototype.equals = function (right, dataComparer) {
    return TimeInterval.equals(this, right, dataComparer);
  };

  /**
   * Compares this instance against the provided instance componentwise and returns
   * <code>true</code> if they are within the provided epsilon,
   * <code>false</code> otherwise.
   *
   * @param {TimeInterval} [right] The right hand side interval.
   * @param {Number} [epsilon=0] The epsilon to use for equality testing.
   * @param {TimeInterval.DataComparer} [dataComparer] A function which compares the data of the two intervals.  If omitted, reference equality is used.
   * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
   */
  TimeInterval.prototype.equalsEpsilon = function (right, epsilon, dataComparer) {
    return TimeInterval.equalsEpsilon(this, right, epsilon, dataComparer);
  };

  /**
   * Creates a string representing this TimeInterval in ISO8601 format.
   *
   * @returns {String} A string representing this TimeInterval in ISO8601 format.
   */
  TimeInterval.prototype.toString = function () {
    return TimeInterval.toIso8601(this);
  };

  /**
   * An immutable empty interval.
   *
   * @type {TimeInterval}
   * @constant
   */
  TimeInterval.EMPTY = Object.freeze(
    new TimeInterval({
      start: new JulianDate(),
      stop: new JulianDate(),
      isStartIncluded: false,
      isStopIncluded: false,
    })
  );

  const MINIMUM_VALUE = Object.freeze(
    JulianDate.fromIso8601("0000-01-01T00:00:00Z")
  );
  const MAXIMUM_VALUE = Object.freeze(
    JulianDate.fromIso8601("9999-12-31T24:00:00Z")
  );
  const MAXIMUM_INTERVAL = Object.freeze(
    new TimeInterval({
      start: MINIMUM_VALUE,
      stop: MAXIMUM_VALUE,
    })
  );

  /**
   * Constants related to ISO8601 support.
   *
   * @namespace
   *
   * @see {@link http://en.wikipedia.org/wiki/ISO_8601|ISO 8601 on Wikipedia}
   * @see JulianDate
   * @see TimeInterval
   */
  const Iso8601 = {
    /**
     * A {@link JulianDate} representing the earliest time representable by an ISO8601 date.
     * This is equivalent to the date string '0000-01-01T00:00:00Z'
     *
     * @type {JulianDate}
     * @constant
     */
    MINIMUM_VALUE: MINIMUM_VALUE,

    /**
     * A {@link JulianDate} representing the latest time representable by an ISO8601 date.
     * This is equivalent to the date string '9999-12-31T24:00:00Z'
     *
     * @type {JulianDate}
     * @constant
     */
    MAXIMUM_VALUE: MAXIMUM_VALUE,

    /**
     * A {@link TimeInterval} representing the largest interval representable by an ISO8601 interval.
     * This is equivalent to the interval string '0000-01-01T00:00:00Z/9999-12-31T24:00:00Z'
     *
     * @type {TimeInterval}
     * @constant
     */
    MAXIMUM_INTERVAL: MAXIMUM_INTERVAL,
  };

  /**
   * Transcodes KTX2 textures using web workers.
   *
   * @private
   */
  function KTX2Transcoder() {}

  KTX2Transcoder._transcodeTaskProcessor = new TaskProcessor(
    "transcodeKTX2",
    Number.POSITIVE_INFINITY // KTX2 transcoding is used in place of Resource.fetchImage, so it can't reject as "just soooo busy right now"
  );

  KTX2Transcoder._readyPromise = undefined;

  function makeReadyPromise() {
    const readyPromise = KTX2Transcoder._transcodeTaskProcessor
      .initWebAssemblyModule({
        modulePath: "ThirdParty/Workers/basis_transcoder.js",
        wasmBinaryFile: "ThirdParty/basis_transcoder.wasm",
      })
      .then(function () {
        return KTX2Transcoder._transcodeTaskProcessor;
      });
    KTX2Transcoder._readyPromise = readyPromise;
  }

  KTX2Transcoder.transcode = function (ktx2Buffer, supportedTargetFormats) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("supportedTargetFormats", supportedTargetFormats);
    //>>includeEnd('debug');

    if (!defined(KTX2Transcoder._readyPromise)) {
      makeReadyPromise();
    }

    return KTX2Transcoder._readyPromise
      .then(function (taskProcessor) {
        let parameters;
        if (ktx2Buffer instanceof ArrayBuffer) {
          const view = new Uint8Array(ktx2Buffer);
          parameters = {
            supportedTargetFormats: supportedTargetFormats,
            ktx2Buffer: view,
          };
          return taskProcessor.scheduleTask(parameters, [ktx2Buffer]);
        }
        parameters = {
          supportedTargetFormats: supportedTargetFormats,
          ktx2Buffer: ktx2Buffer,
        };
        return taskProcessor.scheduleTask(parameters, [ktx2Buffer.buffer]);
      })
      .then(function (result) {
        const levelsLength = result.length;
        const faceKeys = Object.keys(result[0]);
        const faceKeysLength = faceKeys.length;

        let i;
        for (i = 0; i < levelsLength; i++) {
          const faces = result[i];
          for (let j = 0; j < faceKeysLength; j++) {
            const face = faces[faceKeys[j]];
            faces[faceKeys[j]] = new CompressedTextureBuffer(
              face.internalFormat,
              face.datatype,
              face.width,
              face.height,
              face.levelBuffer
            );
          }
        }

        // Cleaning up parsed result if it's a single image
        if (faceKeysLength === 1) {
          for (i = 0; i < levelsLength; ++i) {
            result[i] = result[i][faceKeys[0]];
          }

          if (levelsLength === 1) {
            result = result[0];
          }
        }
        return result;
      })
      .catch(function (error) {
        throw error;
      });
  };

  /**
   * This enumerated type is for representing keyboard modifiers. These are keys
   * that are held down in addition to other event types.
   *
   * @enum {Number}
   */
  const KeyboardEventModifier = {
    /**
     * Represents the shift key being held down.
     *
     * @type {Number}
     * @constant
     */
    SHIFT: 0,

    /**
     * Represents the control key being held down.
     *
     * @type {Number}
     * @constant
     */
    CTRL: 1,

    /**
     * Represents the alt key being held down.
     *
     * @type {Number}
     * @constant
     */
    ALT: 2,
  };
  var KeyboardEventModifier$1 = Object.freeze(KeyboardEventModifier);

  /**
   * An {@link InterpolationAlgorithm} for performing Lagrange interpolation.
   *
   * @namespace LagrangePolynomialApproximation
   */
  const LagrangePolynomialApproximation = {
    type: "Lagrange",
  };

  /**
   * Given the desired degree, returns the number of data points required for interpolation.
   *
   * @param {Number} degree The desired degree of interpolation.
   * @returns {Number} The number of required data points needed for the desired degree of interpolation.
   */
  LagrangePolynomialApproximation.getRequiredDataPoints = function (degree) {
    return Math.max(degree + 1.0, 2);
  };

  /**
   * Interpolates values using Lagrange Polynomial Approximation.
   *
   * @param {Number} x The independent variable for which the dependent variables will be interpolated.
   * @param {Number[]} xTable The array of independent variables to use to interpolate.  The values
   * in this array must be in increasing order and the same value must not occur twice in the array.
   * @param {Number[]} yTable The array of dependent variables to use to interpolate.  For a set of three
   * dependent values (p,q,w) at time 1 and time 2 this should be as follows: {p1, q1, w1, p2, q2, w2}.
   * @param {Number} yStride The number of dependent variable values in yTable corresponding to
   * each independent variable value in xTable.
   * @param {Number[]} [result] An existing array into which to store the result.
   * @returns {Number[]} The array of interpolated values, or the result parameter if one was provided.
   */
  LagrangePolynomialApproximation.interpolateOrderZero = function (
    x,
    xTable,
    yTable,
    yStride,
    result
  ) {
    if (!defined(result)) {
      result = new Array(yStride);
    }

    let i;
    let j;
    const length = xTable.length;

    for (i = 0; i < yStride; i++) {
      result[i] = 0;
    }

    for (i = 0; i < length; i++) {
      let coefficient = 1;

      for (j = 0; j < length; j++) {
        if (j !== i) {
          const diffX = xTable[i] - xTable[j];
          coefficient *= (x - xTable[j]) / diffX;
        }
      }

      for (j = 0; j < yStride; j++) {
        result[j] += coefficient * yTable[i * yStride + j];
      }
    }

    return result;
  };

  /**
   * An {@link InterpolationAlgorithm} for performing linear interpolation.
   *
   * @namespace LinearApproximation
   */
  const LinearApproximation = {
    type: "Linear",
  };

  /**
   * Given the desired degree, returns the number of data points required for interpolation.
   * Since linear interpolation can only generate a first degree polynomial, this function
   * always returns 2.
   * @param {Number} degree The desired degree of interpolation.
   * @returns {Number} This function always returns 2.
   *
   */
  LinearApproximation.getRequiredDataPoints = function (degree) {
    return 2;
  };

  /**
   * Interpolates values using linear approximation.
   *
   * @param {Number} x The independent variable for which the dependent variables will be interpolated.
   * @param {Number[]} xTable The array of independent variables to use to interpolate.  The values
   * in this array must be in increasing order and the same value must not occur twice in the array.
   * @param {Number[]} yTable The array of dependent variables to use to interpolate.  For a set of three
   * dependent values (p,q,w) at time 1 and time 2 this should be as follows: {p1, q1, w1, p2, q2, w2}.
   * @param {Number} yStride The number of dependent variable values in yTable corresponding to
   * each independent variable value in xTable.
   * @param {Number[]} [result] An existing array into which to store the result.
   * @returns {Number[]} The array of interpolated values, or the result parameter if one was provided.
   */
  LinearApproximation.interpolateOrderZero = function (
    x,
    xTable,
    yTable,
    yStride,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (xTable.length !== 2) {
      throw new DeveloperError(
        "The xTable provided to the linear interpolator must have exactly two elements."
      );
    } else if (yStride <= 0) {
      throw new DeveloperError(
        "There must be at least 1 dependent variable for each independent variable."
      );
    }
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Array(yStride);
    }

    let i;
    let y0;
    let y1;
    const x0 = xTable[0];
    const x1 = xTable[1];

    //>>includeStart('debug', pragmas.debug);
    if (x0 === x1) {
      throw new DeveloperError(
        "Divide by zero error: xTable[0] and xTable[1] are equal"
      );
    }
    //>>includeEnd('debug');

    for (i = 0; i < yStride; i++) {
      y0 = yTable[i];
      y1 = yTable[i + yStride];
      result[i] = ((y1 - y0) * x + x1 * y0 - x0 * y1) / (x1 - x0);
    }

    return result;
  };

  /**
   * A wrapper around arrays so that the internal length of the array can be manually managed.
   *
   * @alias ManagedArray
   * @constructor
   * @private
   *
   * @param {Number} [length=0] The initial length of the array.
   */
  function ManagedArray(length) {
    length = defaultValue(length, 0);
    this._array = new Array(length);
    this._length = length;
  }

  Object.defineProperties(ManagedArray.prototype, {
    /**
     * Gets or sets the length of the array.
     * If the set length is greater than the length of the internal array, the internal array is resized.
     *
     * @memberof ManagedArray.prototype
     * @type Number
     */
    length: {
      get: function () {
        return this._length;
      },
      set: function (length) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number.greaterThanOrEquals("length", length, 0);
        //>>includeEnd('debug');
        const array = this._array;
        const originalLength = this._length;
        if (length < originalLength) {
          // Remove trailing references
          for (let i = length; i < originalLength; ++i) {
            array[i] = undefined;
          }
        } else if (length > array.length) {
          array.length = length;
        }
        this._length = length;
      },
    },

    /**
     * Gets the internal array.
     *
     * @memberof ManagedArray.prototype
     * @type Array
     * @readonly
     */
    values: {
      get: function () {
        return this._array;
      },
    },
  });

  /**
   * Gets the element at an index.
   *
   * @param {Number} index The index to get.
   */
  ManagedArray.prototype.get = function (index) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number.lessThan("index", index, this._array.length);
    //>>includeEnd('debug');

    return this._array[index];
  };

  /**
   * Sets the element at an index. Resizes the array if index is greater than the length of the array.
   *
   * @param {Number} index The index to set.
   * @param {*} element The element to set at index.
   */
  ManagedArray.prototype.set = function (index, element) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("index", index);
    //>>includeEnd('debug');

    if (index >= this._length) {
      this.length = index + 1;
    }
    this._array[index] = element;
  };

  /**
   * Returns the last element in the array without modifying the array.
   *
   * @returns {*} The last element in the array.
   */
  ManagedArray.prototype.peek = function () {
    return this._array[this._length - 1];
  };

  /**
   * Push an element into the array.
   *
   * @param {*} element The element to push.
   */
  ManagedArray.prototype.push = function (element) {
    const index = this.length++;
    this._array[index] = element;
  };

  /**
   * Pop an element from the array.
   *
   * @returns {*} The last element in the array.
   */
  ManagedArray.prototype.pop = function () {
    if (this._length === 0) {
      return undefined;
    }
    const element = this._array[this._length - 1];
    --this.length;
    return element;
  };

  /**
   * Resize the internal array if length > _array.length.
   *
   * @param {Number} length The length.
   */
  ManagedArray.prototype.reserve = function (length) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number.greaterThanOrEquals("length", length, 0);
    //>>includeEnd('debug');

    if (length > this._array.length) {
      this._array.length = length;
    }
  };

  /**
   * Resize the array.
   *
   * @param {Number} length The length.
   */
  ManagedArray.prototype.resize = function (length) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number.greaterThanOrEquals("length", length, 0);
    //>>includeEnd('debug');

    this.length = length;
  };

  /**
   * Trim the internal array to the specified length. Defaults to the current length.
   *
   * @param {Number} [length] The length.
   */
  ManagedArray.prototype.trim = function (length) {
    length = defaultValue(length, this._length);
    this._array.length = length;
  };

  /**
   * Defines how geodetic ellipsoid coordinates ({@link Cartographic}) project to a
   * flat map like Cesium's 2D and Columbus View modes.
   *
   * @alias MapProjection
   * @constructor
   * @abstract
   *
   * @see GeographicProjection
   * @see WebMercatorProjection
   */
  function MapProjection() {
    DeveloperError.throwInstantiationError();
  }

  Object.defineProperties(MapProjection.prototype, {
    /**
     * Gets the {@link Ellipsoid}.
     *
     * @memberof MapProjection.prototype
     *
     * @type {Ellipsoid}
     * @readonly
     */
    ellipsoid: {
      get: DeveloperError.throwInstantiationError,
    },
  });

  /**
   * Projects {@link Cartographic} coordinates, in radians, to projection-specific map coordinates, in meters.
   *
   * @memberof MapProjection
   * @function
   *
   * @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.
   */
  MapProjection.prototype.project = DeveloperError.throwInstantiationError;

  /**
   * Unprojects projection-specific map {@link Cartesian3} coordinates, in meters, to {@link Cartographic}
   * coordinates, in radians.
   *
   * @memberof MapProjection
   * @function
   *
   * @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.
   */
  MapProjection.prototype.unproject = DeveloperError.throwInstantiationError;

  /**
   * A spline that linearly interpolates over an array of weight values used by morph targets.
   *
   * @alias MorphWeightSpline
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Number[]} options.times An array of strictly increasing, unit-less, floating-point times at each point.
   *                The values are in no way connected to the clock time. They are the parameterization for the curve.
   * @param {Number[]} options.weights The array of floating-point control weights given. The weights are ordered such
   *                that all weights for the targets are given in chronological order and order in which they appear in
   *                the glTF from which the morph targets come. This means for 2 targets, weights = [w(0,0), w(0,1), w(1,0), w(1,1) ...]
   *                where i and j in w(i,j) are the time indices and target indices, respectively.
   *
   * @exception {DeveloperError} weights.length must be greater than or equal to 2.
   * @exception {DeveloperError} times.length must be a factor of weights.length.
   *
   *
   * @example
   * const times = [ 0.0, 1.5, 3.0, 4.5, 6.0 ];
   * const weights = [0.0, 1.0, 0.25, 0.75, 0.5, 0.5, 0.75, 0.25, 1.0, 0.0]; //Two targets
   * const spline = new Cesium.WeightSpline({
   *     times : times,
   *     weights : weights
   * });
   *
   * const p0 = spline.evaluate(times[0]);
   *
   * @see ConstantSpline
   * @see SteppedSpline
   * @see LinearSpline
   * @see HermiteSpline
   * @see CatmullRomSpline
   * @see QuaternionSpline
   */
  function MorphWeightSpline(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const weights = options.weights;
    const times = options.times;

    //>>includeStart('debug', pragmas.debug);
    Check.defined("weights", weights);
    Check.defined("times", times);
    Check.typeOf.number.greaterThanOrEquals("weights.length", weights.length, 3);
    if (weights.length % times.length !== 0) {
      throw new DeveloperError(
        "times.length must be a factor of weights.length."
      );
    }
    //>>includeEnd('debug');

    this._times = times;
    this._weights = weights;
    this._count = weights.length / times.length;

    this._lastTimeIndex = 0;
  }

  Object.defineProperties(MorphWeightSpline.prototype, {
    /**
     * An array of times for the control weights.
     *
     * @memberof WeightSpline.prototype
     *
     * @type {Number[]}
     * @readonly
     */
    times: {
      get: function () {
        return this._times;
      },
    },

    /**
     * An array of floating-point array control weights.
     *
     * @memberof WeightSpline.prototype
     *
     * @type {Number[]}
     * @readonly
     */
    weights: {
      get: function () {
        return this._weights;
      },
    },
  });

  /**
   * Finds an index <code>i</code> in <code>times</code> such that the parameter
   * <code>time</code> is in the interval <code>[times[i], times[i + 1]]</code>.
   * @function
   *
   * @param {Number} time The time.
   * @returns {Number} The index for the element at the start of the interval.
   *
   * @exception {DeveloperError} time must be in the range <code>[t<sub>0</sub>, t<sub>n</sub>]</code>, where <code>t<sub>0</sub></code>
   *                             is the first element in the array <code>times</code> and <code>t<sub>n</sub></code> is the last element
   *                             in the array <code>times</code>.
   */
  MorphWeightSpline.prototype.findTimeInterval =
    Spline.prototype.findTimeInterval;

  /**
   * Wraps the given time to the period covered by the spline.
   * @function
   *
   * @param {Number} time The time.
   * @return {Number} The time, wrapped around to the updated animation.
   */
  MorphWeightSpline.prototype.wrapTime = Spline.prototype.wrapTime;

  /**
   * Clamps the given time to the period covered by the spline.
   * @function
   *
   * @param {Number} time The time.
   * @return {Number} The time, clamped to the animation period.
   */
  MorphWeightSpline.prototype.clampTime = Spline.prototype.clampTime;

  /**
   * Evaluates the curve at a given time.
   *
   * @param {Number} time The time at which to evaluate the curve.
   * @param {Number[]} [result] The object onto which to store the result.
   * @returns {Number[]} The modified result parameter or a new instance of the point on the curve at the given time.
   *
   * @exception {DeveloperError} time must be in the range <code>[t<sub>0</sub>, t<sub>n</sub>]</code>, where <code>t<sub>0</sub></code>
   *                             is the first element in the array <code>times</code> and <code>t<sub>n</sub></code> is the last element
   *                             in the array <code>times</code>.
   */
  MorphWeightSpline.prototype.evaluate = function (time, result) {
    const weights = this.weights;
    const times = this.times;

    const i = (this._lastTimeIndex = this.findTimeInterval(
      time,
      this._lastTimeIndex
    ));
    const u = (time - times[i]) / (times[i + 1] - times[i]);

    if (!defined(result)) {
      result = new Array(this._count);
    }

    for (let j = 0; j < this._count; j++) {
      const index = i * this._count + j;
      result[j] = weights[index] * (1.0 - u) + weights[index + this._count] * u;
    }

    return result;
  };

  /**
   * Morton Order (aka Z-Order Curve) helper functions.
   * @see {@link https://en.wikipedia.org/wiki/Z-order_curve}
   *
   * @namespace MortonOrder
   * @private
   */
  const MortonOrder = {};

  /**
   * Inserts one 0 bit of spacing between a number's bits. This is the opposite of removeOneSpacing.
   *
   * Example:
   *  input: 6
   *  input (binary):  110
   *  output (binary): 10100
   *                    ^ ^ (added)
   *  output: 20
   *
   * @private
   * @param {Number} v A 16-bit unsigned integer.
   * @returns {Number} A 32-bit unsigned integer.
   * @see {@link https://fgiesen.wordpress.com/2009/12/13/decoding-morton-codes/}
   * @private
   */
  function insertOneSpacing(v) {
    v = (v ^ (v << 8)) & 0x00ff00ff;
    v = (v ^ (v << 4)) & 0x0f0f0f0f;
    v = (v ^ (v << 2)) & 0x33333333;
    v = (v ^ (v << 1)) & 0x55555555;
    return v;
  }

  /**
   * Inserts two 0 bits of spacing between a number's bits. This is the opposite of removeTwoSpacing.
   *
   * Example:
   *  input: 6
   *  input (binary):  110
   *  output (binary): 1001000
   *                    ^^ ^^ (added)
   *  output: 72
   *
   * @private
   * @param {Number} v A 10-bit unsigned integer.
   * @returns {Number} A 30-bit unsigned integer.
   * @see {@link https://fgiesen.wordpress.com/2009/12/13/decoding-morton-codes/}
   */
  function insertTwoSpacing(v) {
    v = (v ^ (v << 16)) & 0x030000ff;
    v = (v ^ (v << 8)) & 0x0300f00f;
    v = (v ^ (v << 4)) & 0x030c30c3;
    v = (v ^ (v << 2)) & 0x09249249;
    return v;
  }

  /**
   * Removes one bit of spacing between bits. This is the opposite of insertOneSpacing.
   *
   * Example:
   *  input: 20
   *  input (binary):  10100
   *                    ^ ^ (removed)
   *  output (binary): 110
   *  output: 6
   *
   * @private
   * @param {Number} v A 32-bit unsigned integer.
   * @returns {Number} A 16-bit unsigned integer.
   * @see {@link https://fgiesen.wordpress.com/2009/12/13/decoding-morton-codes/}
   */
  function removeOneSpacing(v) {
    v &= 0x55555555;
    v = (v ^ (v >> 1)) & 0x33333333;
    v = (v ^ (v >> 2)) & 0x0f0f0f0f;
    v = (v ^ (v >> 4)) & 0x00ff00ff;
    v = (v ^ (v >> 8)) & 0x0000ffff;
    return v;
  }

  /**
   * Removes two bits of spacing between bits. This is the opposite of insertTwoSpacing.
   *
   * Example:
   *  input: 72
   *  input (binary):  1001000
   *                    ^^ ^^ (removed)
   *  output (binary): 110
   *  output: 6
   *
   * @private
   * @param {Number} v A 30-bit unsigned integer.
   * @returns {Number} A 10-bit unsigned integer.
   * @see {@link https://fgiesen.wordpress.com/2009/12/13/decoding-morton-codes/}
   */
  function removeTwoSpacing(v) {
    v &= 0x09249249;
    v = (v ^ (v >> 2)) & 0x030c30c3;
    v = (v ^ (v >> 4)) & 0x0300f00f;
    v = (v ^ (v >> 8)) & 0xff0000ff;
    v = (v ^ (v >> 16)) & 0x000003ff;
    return v;
  }

  /**
   * Computes the Morton index from 2D coordinates. This is equivalent to interleaving their bits.
   * The inputs must be 16-bit unsigned integers (resulting in 32-bit Morton index) due to 32-bit bitwise operator limitation in JavaScript.
   *
   * @param {Number} x The X coordinate in the range [0, (2^16)-1].
   * @param {Number} y The Y coordinate in the range [0, (2^16)-1].
   * @returns {Number} The Morton index.
   * @private
   */
  MortonOrder.encode2D = function (x, y) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("x", x);
    Check.typeOf.number("y", y);
    if (x < 0 || x > 65535 || y < 0 || y > 65535) {
      throw new DeveloperError("inputs must be 16-bit unsigned integers");
    }
    //>>includeEnd('debug');

    // Note: JavaScript bitwise operations return signed 32-bit integers, so the
    // final result needs to be reintepreted as an unsigned integer using >>> 0.
    // This is not needed for encode3D because the result is guaranteed to be at most
    // 30 bits and thus will always be interpreted as an unsigned value.
    return (insertOneSpacing(x) | (insertOneSpacing(y) << 1)) >>> 0;
  };

  /**
   * Computes the 2D coordinates from a Morton index. This is equivalent to deinterleaving their bits.
   * The input must be a 32-bit unsigned integer (resulting in 16 bits per coordinate) due to 32-bit bitwise operator limitation in JavaScript.
   *
   * @param {Number} mortonIndex The Morton index in the range [0, (2^32)-1].
   * @param {Number[]} [result] The array onto which to store the result.
   * @returns {Number[]} An array containing the 2D coordinates correspoding to the Morton index.
   * @private
   */
  MortonOrder.decode2D = function (mortonIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("mortonIndex", mortonIndex);
    if (mortonIndex < 0 || mortonIndex > 4294967295) {
      throw new DeveloperError("input must be a 32-bit unsigned integer");
    }
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Array(2);
    }

    result[0] = removeOneSpacing(mortonIndex);
    result[1] = removeOneSpacing(mortonIndex >> 1);
    return result;
  };

  /**
   * Computes the Morton index from 3D coordinates. This is equivalent to interleaving their bits.
   * The inputs must be 10-bit unsigned integers (resulting in 30-bit Morton index) due to 32-bit bitwise operator limitation in JavaScript.
   *
   * @param {Number} x The X coordinate in the range [0, (2^10)-1].
   * @param {Number} y The Y coordinate in the range [0, (2^10)-1].
   * @param {Number} z The Z coordinate in the range [0, (2^10)-1].
   * @returns {Number} The Morton index.
   * @private
   */
  MortonOrder.encode3D = function (x, y, z) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("x", x);
    Check.typeOf.number("y", y);
    Check.typeOf.number("z", z);
    if (x < 0 || x > 1023 || y < 0 || y > 1023 || z < 0 || z > 1023) {
      throw new DeveloperError("inputs must be 10-bit unsigned integers");
    }
    //>>includeEnd('debug');

    return (
      insertTwoSpacing(x) |
      (insertTwoSpacing(y) << 1) |
      (insertTwoSpacing(z) << 2)
    );
  };

  /**
   * Computes the 3D coordinates from a Morton index. This is equivalent to deinterleaving their bits.
   * The input must be a 30-bit unsigned integer (resulting in 10 bits per coordinate) due to 32-bit bitwise operator limitation in JavaScript.
   *
   * @param {Number} mortonIndex The Morton index in the range [0, (2^30)-1].
   * @param {Number[]} [result] The array onto which to store the result.
   * @returns {Number[]} An array containing the 3D coordinates corresponding to the Morton index.
   * @private
   */
  MortonOrder.decode3D = function (mortonIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("mortonIndex", mortonIndex);
    if (mortonIndex < 0 || mortonIndex > 1073741823) {
      throw new DeveloperError("input must be a 30-bit unsigned integer");
    }
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Array(3);
    }

    result[0] = removeTwoSpacing(mortonIndex);
    result[1] = removeTwoSpacing(mortonIndex >> 1);
    result[2] = removeTwoSpacing(mortonIndex >> 2);
    return result;
  };

  /**
   * Represents a scalar value's lower and upper bound at a near distance and far distance in eye space.
   * @alias NearFarScalar
   * @constructor
   *
   * @param {Number} [near=0.0] The lower bound of the camera range.
   * @param {Number} [nearValue=0.0] The value at the lower bound of the camera range.
   * @param {Number} [far=1.0] The upper bound of the camera range.
   * @param {Number} [farValue=0.0] The value at the upper bound of the camera range.
   *
   * @see Packable
   */
  function NearFarScalar(near, nearValue, far, farValue) {
    /**
     * The lower bound of the camera range.
     * @type {Number}
     * @default 0.0
     */
    this.near = defaultValue(near, 0.0);
    /**
     * The value at the lower bound of the camera range.
     * @type {Number}
     * @default 0.0
     */
    this.nearValue = defaultValue(nearValue, 0.0);
    /**
     * The upper bound of the camera range.
     * @type {Number}
     * @default 1.0
     */
    this.far = defaultValue(far, 1.0);
    /**
     * The value at the upper bound of the camera range.
     * @type {Number}
     * @default 0.0
     */
    this.farValue = defaultValue(farValue, 0.0);
  }

  /**
   * Duplicates a NearFarScalar instance.
   *
   * @param {NearFarScalar} nearFarScalar The NearFarScalar to duplicate.
   * @param {NearFarScalar} [result] The object onto which to store the result.
   * @returns {NearFarScalar} The modified result parameter or a new NearFarScalar instance if one was not provided. (Returns undefined if nearFarScalar is undefined)
   */
  NearFarScalar.clone = function (nearFarScalar, result) {
    if (!defined(nearFarScalar)) {
      return undefined;
    }

    if (!defined(result)) {
      return new NearFarScalar(
        nearFarScalar.near,
        nearFarScalar.nearValue,
        nearFarScalar.far,
        nearFarScalar.farValue
      );
    }

    result.near = nearFarScalar.near;
    result.nearValue = nearFarScalar.nearValue;
    result.far = nearFarScalar.far;
    result.farValue = nearFarScalar.farValue;
    return result;
  };

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  NearFarScalar.packedLength = 4;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {NearFarScalar} 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
   */
  NearFarScalar.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(value)) {
      throw new DeveloperError("value is required");
    }
    if (!defined(array)) {
      throw new DeveloperError("array is required");
    }
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    array[startingIndex++] = value.near;
    array[startingIndex++] = value.nearValue;
    array[startingIndex++] = value.far;
    array[startingIndex] = value.farValue;

    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 {NearFarScalar} [result] The object into which to store the result.
   * @returns {NearFarScalar} The modified result parameter or a new NearFarScalar instance if one was not provided.
   */
  NearFarScalar.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(array)) {
      throw new DeveloperError("array is required");
    }
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    if (!defined(result)) {
      result = new NearFarScalar();
    }
    result.near = array[startingIndex++];
    result.nearValue = array[startingIndex++];
    result.far = array[startingIndex++];
    result.farValue = array[startingIndex];
    return result;
  };

  /**
   * Compares the provided NearFarScalar and returns <code>true</code> if they are equal,
   * <code>false</code> otherwise.
   *
   * @param {NearFarScalar} [left] The first NearFarScalar.
   * @param {NearFarScalar} [right] The second NearFarScalar.
   * @returns {Boolean} <code>true</code> if left and right are equal; otherwise <code>false</code>.
   */
  NearFarScalar.equals = function (left, right) {
    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        left.near === right.near &&
        left.nearValue === right.nearValue &&
        left.far === right.far &&
        left.farValue === right.farValue)
    );
  };

  /**
   * Duplicates this instance.
   *
   * @param {NearFarScalar} [result] The object onto which to store the result.
   * @returns {NearFarScalar} The modified result parameter or a new NearFarScalar instance if one was not provided.
   */
  NearFarScalar.prototype.clone = function (result) {
    return NearFarScalar.clone(this, result);
  };

  /**
   * Compares this instance to the provided NearFarScalar and returns <code>true</code> if they are equal,
   * <code>false</code> otherwise.
   *
   * @param {NearFarScalar} [right] The right hand side NearFarScalar.
   * @returns {Boolean} <code>true</code> if left and right are equal; otherwise <code>false</code>.
   */
  NearFarScalar.prototype.equals = function (right) {
    return NearFarScalar.equals(this, right);
  };

  /**
   * This enumerated type is used in determining to what extent an object, the occludee,
   * is visible during horizon culling. An occluder may fully block an occludee, in which case
   * it has no visibility, may partially block an occludee from view, or may not block it at all,
   * leading to full visibility.
   *
   * @enum {Number}
   */
  const Visibility = {
    /**
     * Represents that no part of an object is visible.
     *
     * @type {Number}
     * @constant
     */
    NONE: -1,

    /**
     * Represents that part, but not all, of an object is visible
     *
     * @type {Number}
     * @constant
     */
    PARTIAL: 0,

    /**
     * Represents that an object is visible in its entirety.
     *
     * @type {Number}
     * @constant
     */
    FULL: 1,
  };
  var Visibility$1 = Object.freeze(Visibility);

  /**
   * Creates an Occluder derived from an object's position and radius, as well as the camera position.
   * The occluder can be used to determine whether or not other objects are visible or hidden behind the
   * visible horizon defined by the occluder and camera position.
   *
   * @alias Occluder
   *
   * @param {BoundingSphere} occluderBoundingSphere The bounding sphere surrounding the occluder.
   * @param {Cartesian3} cameraPosition The coordinate of the viewer/camera.
   *
   * @constructor
   *
   * @example
   * // Construct an occluder one unit away from the origin with a radius of one.
   * const cameraPosition = Cesium.Cartesian3.ZERO;
   * const occluderBoundingSphere = new Cesium.BoundingSphere(new Cesium.Cartesian3(0, 0, -1), 1);
   * const occluder = new Cesium.Occluder(occluderBoundingSphere, cameraPosition);
   */
  function Occluder(occluderBoundingSphere, cameraPosition) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(occluderBoundingSphere)) {
      throw new DeveloperError("occluderBoundingSphere is required.");
    }
    if (!defined(cameraPosition)) {
      throw new DeveloperError("camera position is required.");
    }
    //>>includeEnd('debug');

    this._occluderPosition = Cartesian3.clone(occluderBoundingSphere.center);
    this._occluderRadius = occluderBoundingSphere.radius;

    this._horizonDistance = 0.0;
    this._horizonPlaneNormal = undefined;
    this._horizonPlanePosition = undefined;
    this._cameraPosition = undefined;

    // cameraPosition fills in the above values
    this.cameraPosition = cameraPosition;
  }

  const scratchCartesian3$6 = new Cartesian3();

  Object.defineProperties(Occluder.prototype, {
    /**
     * The position of the occluder.
     * @memberof Occluder.prototype
     * @type {Cartesian3}
     */
    position: {
      get: function () {
        return this._occluderPosition;
      },
    },

    /**
     * The radius of the occluder.
     * @memberof Occluder.prototype
     * @type {Number}
     */
    radius: {
      get: function () {
        return this._occluderRadius;
      },
    },

    /**
     * The position of the camera.
     * @memberof Occluder.prototype
     * @type {Cartesian3}
     */
    cameraPosition: {
      set: function (cameraPosition) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(cameraPosition)) {
          throw new DeveloperError("cameraPosition is required.");
        }
        //>>includeEnd('debug');

        cameraPosition = Cartesian3.clone(cameraPosition, this._cameraPosition);

        const cameraToOccluderVec = Cartesian3.subtract(
          this._occluderPosition,
          cameraPosition,
          scratchCartesian3$6
        );
        let invCameraToOccluderDistance = Cartesian3.magnitudeSquared(
          cameraToOccluderVec
        );
        const occluderRadiusSqrd = this._occluderRadius * this._occluderRadius;

        let horizonDistance;
        let horizonPlaneNormal;
        let horizonPlanePosition;
        if (invCameraToOccluderDistance > occluderRadiusSqrd) {
          horizonDistance = Math.sqrt(
            invCameraToOccluderDistance - occluderRadiusSqrd
          );
          invCameraToOccluderDistance =
            1.0 / Math.sqrt(invCameraToOccluderDistance);
          horizonPlaneNormal = Cartesian3.multiplyByScalar(
            cameraToOccluderVec,
            invCameraToOccluderDistance,
            scratchCartesian3$6
          );
          const nearPlaneDistance =
            horizonDistance * horizonDistance * invCameraToOccluderDistance;
          horizonPlanePosition = Cartesian3.add(
            cameraPosition,
            Cartesian3.multiplyByScalar(
              horizonPlaneNormal,
              nearPlaneDistance,
              scratchCartesian3$6
            ),
            scratchCartesian3$6
          );
        } else {
          horizonDistance = Number.MAX_VALUE;
        }

        this._horizonDistance = horizonDistance;
        this._horizonPlaneNormal = horizonPlaneNormal;
        this._horizonPlanePosition = horizonPlanePosition;
        this._cameraPosition = cameraPosition;
      },
    },
  });

  /**
   * Creates an occluder from a bounding sphere and the camera position.
   *
   * @param {BoundingSphere} occluderBoundingSphere The bounding sphere surrounding the occluder.
   * @param {Cartesian3} cameraPosition The coordinate of the viewer/camera.
   * @param {Occluder} [result] The object onto which to store the result.
   * @returns {Occluder} The occluder derived from an object's position and radius, as well as the camera position.
   */
  Occluder.fromBoundingSphere = function (
    occluderBoundingSphere,
    cameraPosition,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(occluderBoundingSphere)) {
      throw new DeveloperError("occluderBoundingSphere is required.");
    }

    if (!defined(cameraPosition)) {
      throw new DeveloperError("camera position is required.");
    }
    //>>includeEnd('debug');

    if (!defined(result)) {
      return new Occluder(occluderBoundingSphere, cameraPosition);
    }

    Cartesian3.clone(occluderBoundingSphere.center, result._occluderPosition);
    result._occluderRadius = occluderBoundingSphere.radius;
    result.cameraPosition = cameraPosition;

    return result;
  };

  const tempVecScratch = new Cartesian3();

  /**
   * Determines whether or not a point, the <code>occludee</code>, is hidden from view by the occluder.
   *
   * @param {Cartesian3} occludee The point surrounding the occludee object.
   * @returns {Boolean} <code>true</code> if the occludee is visible; otherwise <code>false</code>.
   *
   *
   * @example
   * const cameraPosition = new Cesium.Cartesian3(0, 0, 0);
   * const littleSphere = new Cesium.BoundingSphere(new Cesium.Cartesian3(0, 0, -1), 0.25);
   * const occluder = new Cesium.Occluder(littleSphere, cameraPosition);
   * const point = new Cesium.Cartesian3(0, 0, -3);
   * occluder.isPointVisible(point); //returns true
   *
   * @see Occluder#computeVisibility
   */
  Occluder.prototype.isPointVisible = function (occludee) {
    if (this._horizonDistance !== Number.MAX_VALUE) {
      let tempVec = Cartesian3.subtract(
        occludee,
        this._occluderPosition,
        tempVecScratch
      );
      let temp = this._occluderRadius;
      temp = Cartesian3.magnitudeSquared(tempVec) - temp * temp;
      if (temp > 0.0) {
        temp = Math.sqrt(temp) + this._horizonDistance;
        tempVec = Cartesian3.subtract(occludee, this._cameraPosition, tempVec);
        return temp * temp > Cartesian3.magnitudeSquared(tempVec);
      }
    }
    return false;
  };

  const occludeePositionScratch = new Cartesian3();

  /**
   * Determines whether or not a sphere, the <code>occludee</code>, is hidden from view by the occluder.
   *
   * @param {BoundingSphere} occludee The bounding sphere surrounding the occludee object.
   * @returns {Boolean} <code>true</code> if the occludee is visible; otherwise <code>false</code>.
   *
   *
   * @example
   * const cameraPosition = new Cesium.Cartesian3(0, 0, 0);
   * const littleSphere = new Cesium.BoundingSphere(new Cesium.Cartesian3(0, 0, -1), 0.25);
   * const occluder = new Cesium.Occluder(littleSphere, cameraPosition);
   * const bigSphere = new Cesium.BoundingSphere(new Cesium.Cartesian3(0, 0, -3), 1);
   * occluder.isBoundingSphereVisible(bigSphere); //returns true
   *
   * @see Occluder#computeVisibility
   */
  Occluder.prototype.isBoundingSphereVisible = function (occludee) {
    const occludeePosition = Cartesian3.clone(
      occludee.center,
      occludeePositionScratch
    );
    const occludeeRadius = occludee.radius;

    if (this._horizonDistance !== Number.MAX_VALUE) {
      let tempVec = Cartesian3.subtract(
        occludeePosition,
        this._occluderPosition,
        tempVecScratch
      );
      let temp = this._occluderRadius - occludeeRadius;
      temp = Cartesian3.magnitudeSquared(tempVec) - temp * temp;
      if (occludeeRadius < this._occluderRadius) {
        if (temp > 0.0) {
          temp = Math.sqrt(temp) + this._horizonDistance;
          tempVec = Cartesian3.subtract(
            occludeePosition,
            this._cameraPosition,
            tempVec
          );
          return (
            temp * temp + occludeeRadius * occludeeRadius >
            Cartesian3.magnitudeSquared(tempVec)
          );
        }
        return false;
      }

      // Prevent against the case where the occludee radius is larger than the occluder's; since this is
      // an uncommon case, the following code should rarely execute.
      if (temp > 0.0) {
        tempVec = Cartesian3.subtract(
          occludeePosition,
          this._cameraPosition,
          tempVec
        );
        const tempVecMagnitudeSquared = Cartesian3.magnitudeSquared(tempVec);
        const occluderRadiusSquared = this._occluderRadius * this._occluderRadius;
        const occludeeRadiusSquared = occludeeRadius * occludeeRadius;
        if (
          (this._horizonDistance * this._horizonDistance +
            occluderRadiusSquared) *
            occludeeRadiusSquared >
          tempVecMagnitudeSquared * occluderRadiusSquared
        ) {
          // The occludee is close enough that the occluder cannot possible occlude the occludee
          return true;
        }
        temp = Math.sqrt(temp) + this._horizonDistance;
        return temp * temp + occludeeRadiusSquared > tempVecMagnitudeSquared;
      }

      // The occludee completely encompasses the occluder
      return true;
    }

    return false;
  };

  const tempScratch = new Cartesian3();
  /**
   * Determine to what extent an occludee is visible (not visible, partially visible,  or fully visible).
   *
   * @param {BoundingSphere} occludeeBS The bounding sphere of the occludee.
   * @returns {Visibility} Visibility.NONE if the occludee is not visible,
   *                       Visibility.PARTIAL if the occludee is partially visible, or
   *                       Visibility.FULL if the occludee is fully visible.
   *
   *
   * @example
   * const sphere1 = new Cesium.BoundingSphere(new Cesium.Cartesian3(0, 0, -1.5), 0.5);
   * const sphere2 = new Cesium.BoundingSphere(new Cesium.Cartesian3(0, 0, -2.5), 0.5);
   * const cameraPosition = new Cesium.Cartesian3(0, 0, 0);
   * const occluder = new Cesium.Occluder(sphere1, cameraPosition);
   * occluder.computeVisibility(sphere2); //returns Visibility.NONE
   *
   * @see Occluder#isVisible
   */
  Occluder.prototype.computeVisibility = function (occludeeBS) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(occludeeBS)) {
      throw new DeveloperError("occludeeBS is required.");
    }
    //>>includeEnd('debug');

    // If the occludee radius is larger than the occluders, this will return that
    // the entire ocludee is visible, even though that may not be the case, though this should
    // not occur too often.
    const occludeePosition = Cartesian3.clone(occludeeBS.center);
    const occludeeRadius = occludeeBS.radius;

    if (occludeeRadius > this._occluderRadius) {
      return Visibility$1.FULL;
    }

    if (this._horizonDistance !== Number.MAX_VALUE) {
      // The camera is outside the occluder
      let tempVec = Cartesian3.subtract(
        occludeePosition,
        this._occluderPosition,
        tempScratch
      );
      let temp = this._occluderRadius - occludeeRadius;
      const occluderToOccludeeDistSqrd = Cartesian3.magnitudeSquared(tempVec);
      temp = occluderToOccludeeDistSqrd - temp * temp;
      if (temp > 0.0) {
        // The occludee is not completely inside the occluder
        // Check to see if the occluder completely hides the occludee
        temp = Math.sqrt(temp) + this._horizonDistance;
        tempVec = Cartesian3.subtract(
          occludeePosition,
          this._cameraPosition,
          tempVec
        );
        const cameraToOccludeeDistSqrd = Cartesian3.magnitudeSquared(tempVec);
        if (
          temp * temp + occludeeRadius * occludeeRadius <
          cameraToOccludeeDistSqrd
        ) {
          return Visibility$1.NONE;
        }

        // Check to see whether the occluder is fully or partially visible
        // when the occludee does not intersect the occluder
        temp = this._occluderRadius + occludeeRadius;
        temp = occluderToOccludeeDistSqrd - temp * temp;
        if (temp > 0.0) {
          // The occludee does not intersect the occluder.
          temp = Math.sqrt(temp) + this._horizonDistance;
          return cameraToOccludeeDistSqrd <
            temp * temp + occludeeRadius * occludeeRadius
            ? Visibility$1.FULL
            : Visibility$1.PARTIAL;
        }

        //Check to see if the occluder is fully or partially visible when the occludee DOES
        //intersect the occluder
        tempVec = Cartesian3.subtract(
          occludeePosition,
          this._horizonPlanePosition,
          tempVec
        );
        return Cartesian3.dot(tempVec, this._horizonPlaneNormal) > -occludeeRadius
          ? Visibility$1.PARTIAL
          : Visibility$1.FULL;
      }
    }
    return Visibility$1.NONE;
  };

  const occludeePointScratch = new Cartesian3();
  /**
   * Computes a point that can be used as the occludee position to the visibility functions.
   * Use a radius of zero for the occludee radius.  Typically, a user computes a bounding sphere around
   * an object that is used for visibility; however it is also possible to compute a point that if
   * seen/not seen would also indicate if an object is visible/not visible.  This function is better
   * called for objects that do not move relative to the occluder and is large, such as a chunk of
   * terrain.  You are better off not calling this and using the object's bounding sphere for objects
   * such as a satellite or ground vehicle.
   *
   * @param {BoundingSphere} occluderBoundingSphere The bounding sphere surrounding the occluder.
   * @param {Cartesian3} occludeePosition The point where the occludee (bounding sphere of radius 0) is located.
   * @param {Cartesian3[]} positions List of altitude points on the horizon near the surface of the occluder.
   * @returns {Object} An object containing two attributes: <code>occludeePoint</code> and <code>valid</code>
   * which is a boolean value.
   *
   * @exception {DeveloperError} <code>positions</code> must contain at least one element.
   * @exception {DeveloperError} <code>occludeePosition</code> must have a value other than <code>occluderBoundingSphere.center</code>.
   *
   * @example
   * const cameraPosition = new Cesium.Cartesian3(0, 0, 0);
   * const occluderBoundingSphere = new Cesium.BoundingSphere(new Cesium.Cartesian3(0, 0, -8), 2);
   * const occluder = new Cesium.Occluder(occluderBoundingSphere, cameraPosition);
   * const positions = [new Cesium.Cartesian3(-0.25, 0, -5.3), new Cesium.Cartesian3(0.25, 0, -5.3)];
   * const tileOccluderSphere = Cesium.BoundingSphere.fromPoints(positions);
   * const occludeePosition = tileOccluderSphere.center;
   * const occludeePt = Cesium.Occluder.computeOccludeePoint(occluderBoundingSphere, occludeePosition, positions);
   */
  Occluder.computeOccludeePoint = function (
    occluderBoundingSphere,
    occludeePosition,
    positions
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(occluderBoundingSphere)) {
      throw new DeveloperError("occluderBoundingSphere is required.");
    }
    if (!defined(positions)) {
      throw new DeveloperError("positions is required.");
    }
    if (positions.length === 0) {
      throw new DeveloperError("positions must contain at least one element");
    }
    //>>includeEnd('debug');

    const occludeePos = Cartesian3.clone(occludeePosition);
    const occluderPosition = Cartesian3.clone(occluderBoundingSphere.center);
    const occluderRadius = occluderBoundingSphere.radius;
    const numPositions = positions.length;

    //>>includeStart('debug', pragmas.debug);
    if (Cartesian3.equals(occluderPosition, occludeePosition)) {
      throw new DeveloperError(
        "occludeePosition must be different than occluderBoundingSphere.center"
      );
    }
    //>>includeEnd('debug');

    // Compute a plane with a normal from the occluder to the occludee position.
    const occluderPlaneNormal = Cartesian3.normalize(
      Cartesian3.subtract(occludeePos, occluderPosition, occludeePointScratch),
      occludeePointScratch
    );
    const occluderPlaneD = -Cartesian3.dot(occluderPlaneNormal, occluderPosition);

    //For each position, determine the horizon intersection. Choose the position and intersection
    //that results in the greatest angle with the occcluder plane.
    const aRotationVector = Occluder._anyRotationVector(
      occluderPosition,
      occluderPlaneNormal,
      occluderPlaneD
    );
    let dot = Occluder._horizonToPlaneNormalDotProduct(
      occluderBoundingSphere,
      occluderPlaneNormal,
      occluderPlaneD,
      aRotationVector,
      positions[0]
    );
    if (!dot) {
      //The position is inside the mimimum radius, which is invalid
      return undefined;
    }
    let tempDot;
    for (let i = 1; i < numPositions; ++i) {
      tempDot = Occluder._horizonToPlaneNormalDotProduct(
        occluderBoundingSphere,
        occluderPlaneNormal,
        occluderPlaneD,
        aRotationVector,
        positions[i]
      );
      if (!tempDot) {
        //The position is inside the minimum radius, which is invalid
        return undefined;
      }
      if (tempDot < dot) {
        dot = tempDot;
      }
    }
    //Verify that the dot is not near 90 degress
    if (dot < 0.00174532836589830883577820272085) {
      return undefined;
    }

    const distance = occluderRadius / dot;
    return Cartesian3.add(
      occluderPosition,
      Cartesian3.multiplyByScalar(
        occluderPlaneNormal,
        distance,
        occludeePointScratch
      ),
      occludeePointScratch
    );
  };

  const computeOccludeePointFromRectangleScratch = [];
  /**
   * Computes a point that can be used as the occludee position to the visibility functions from a rectangle.
   *
   * @param {Rectangle} rectangle The rectangle used to create a bounding sphere.
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid used to determine positions of the rectangle.
   * @returns {Object} An object containing two attributes: <code>occludeePoint</code> and <code>valid</code>
   * which is a boolean value.
   */
  Occluder.computeOccludeePointFromRectangle = function (rectangle, ellipsoid) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(rectangle)) {
      throw new DeveloperError("rectangle is required.");
    }
    //>>includeEnd('debug');

    ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
    const positions = Rectangle.subsample(
      rectangle,
      ellipsoid,
      0.0,
      computeOccludeePointFromRectangleScratch
    );
    const bs = BoundingSphere.fromPoints(positions);

    // TODO: get correct ellipsoid center
    const ellipsoidCenter = Cartesian3.ZERO;
    if (!Cartesian3.equals(ellipsoidCenter, bs.center)) {
      return Occluder.computeOccludeePoint(
        new BoundingSphere(ellipsoidCenter, ellipsoid.minimumRadius),
        bs.center,
        positions
      );
    }

    return undefined;
  };

  const tempVec0Scratch = new Cartesian3();
  Occluder._anyRotationVector = function (
    occluderPosition,
    occluderPlaneNormal,
    occluderPlaneD
  ) {
    const tempVec0 = Cartesian3.abs(occluderPlaneNormal, tempVec0Scratch);
    let majorAxis = tempVec0.x > tempVec0.y ? 0 : 1;
    if (
      (majorAxis === 0 && tempVec0.z > tempVec0.x) ||
      (majorAxis === 1 && tempVec0.z > tempVec0.y)
    ) {
      majorAxis = 2;
    }
    const tempVec = new Cartesian3();
    let tempVec1;
    if (majorAxis === 0) {
      tempVec0.x = occluderPosition.x;
      tempVec0.y = occluderPosition.y + 1.0;
      tempVec0.z = occluderPosition.z + 1.0;
      tempVec1 = Cartesian3.UNIT_X;
    } else if (majorAxis === 1) {
      tempVec0.x = occluderPosition.x + 1.0;
      tempVec0.y = occluderPosition.y;
      tempVec0.z = occluderPosition.z + 1.0;
      tempVec1 = Cartesian3.UNIT_Y;
    } else {
      tempVec0.x = occluderPosition.x + 1.0;
      tempVec0.y = occluderPosition.y + 1.0;
      tempVec0.z = occluderPosition.z;
      tempVec1 = Cartesian3.UNIT_Z;
    }
    const u =
      (Cartesian3.dot(occluderPlaneNormal, tempVec0) + occluderPlaneD) /
      -Cartesian3.dot(occluderPlaneNormal, tempVec1);
    return Cartesian3.normalize(
      Cartesian3.subtract(
        Cartesian3.add(
          tempVec0,
          Cartesian3.multiplyByScalar(tempVec1, u, tempVec),
          tempVec0
        ),
        occluderPosition,
        tempVec0
      ),
      tempVec0
    );
  };

  const posDirectionScratch = new Cartesian3();
  Occluder._rotationVector = function (
    occluderPosition,
    occluderPlaneNormal,
    occluderPlaneD,
    position,
    anyRotationVector
  ) {
    //Determine the angle between the occluder plane normal and the position direction
    let positionDirection = Cartesian3.subtract(
      position,
      occluderPosition,
      posDirectionScratch
    );
    positionDirection = Cartesian3.normalize(
      positionDirection,
      positionDirection
    );
    if (
      Cartesian3.dot(occluderPlaneNormal, positionDirection) <
      0.99999998476912904932780850903444
    ) {
      const crossProduct = Cartesian3.cross(
        occluderPlaneNormal,
        positionDirection,
        positionDirection
      );
      const length = Cartesian3.magnitude(crossProduct);
      if (length > CesiumMath.EPSILON13) {
        return Cartesian3.normalize(crossProduct, new Cartesian3());
      }
    }
    //The occluder plane normal and the position direction are colinear. Use any
    //vector in the occluder plane as the rotation vector
    return anyRotationVector;
  };

  const posScratch1 = new Cartesian3();
  const occluerPosScratch = new Cartesian3();
  const posScratch2 = new Cartesian3();
  const horizonPlanePosScratch = new Cartesian3();
  Occluder._horizonToPlaneNormalDotProduct = function (
    occluderBS,
    occluderPlaneNormal,
    occluderPlaneD,
    anyRotationVector,
    position
  ) {
    const pos = Cartesian3.clone(position, posScratch1);
    const occluderPosition = Cartesian3.clone(
      occluderBS.center,
      occluerPosScratch
    );
    const occluderRadius = occluderBS.radius;

    //Verify that the position is outside the occluder
    let positionToOccluder = Cartesian3.subtract(
      occluderPosition,
      pos,
      posScratch2
    );
    const occluderToPositionDistanceSquared = Cartesian3.magnitudeSquared(
      positionToOccluder
    );
    const occluderRadiusSquared = occluderRadius * occluderRadius;
    if (occluderToPositionDistanceSquared < occluderRadiusSquared) {
      return false;
    }

    //Horizon parameters
    const horizonDistanceSquared =
      occluderToPositionDistanceSquared - occluderRadiusSquared;
    const horizonDistance = Math.sqrt(horizonDistanceSquared);
    const occluderToPositionDistance = Math.sqrt(
      occluderToPositionDistanceSquared
    );
    const invOccluderToPositionDistance = 1.0 / occluderToPositionDistance;
    const cosTheta = horizonDistance * invOccluderToPositionDistance;
    const horizonPlaneDistance = cosTheta * horizonDistance;
    positionToOccluder = Cartesian3.normalize(
      positionToOccluder,
      positionToOccluder
    );
    const horizonPlanePosition = Cartesian3.add(
      pos,
      Cartesian3.multiplyByScalar(
        positionToOccluder,
        horizonPlaneDistance,
        horizonPlanePosScratch
      ),
      horizonPlanePosScratch
    );
    const horizonCrossDistance = Math.sqrt(
      horizonDistanceSquared - horizonPlaneDistance * horizonPlaneDistance
    );

    //Rotate the position to occluder vector 90 degrees
    let tempVec = this._rotationVector(
      occluderPosition,
      occluderPlaneNormal,
      occluderPlaneD,
      pos,
      anyRotationVector
    );
    let horizonCrossDirection = Cartesian3.fromElements(
      tempVec.x * tempVec.x * positionToOccluder.x +
        (tempVec.x * tempVec.y - tempVec.z) * positionToOccluder.y +
        (tempVec.x * tempVec.z + tempVec.y) * positionToOccluder.z,
      (tempVec.x * tempVec.y + tempVec.z) * positionToOccluder.x +
        tempVec.y * tempVec.y * positionToOccluder.y +
        (tempVec.y * tempVec.z - tempVec.x) * positionToOccluder.z,
      (tempVec.x * tempVec.z - tempVec.y) * positionToOccluder.x +
        (tempVec.y * tempVec.z + tempVec.x) * positionToOccluder.y +
        tempVec.z * tempVec.z * positionToOccluder.z,
      posScratch1
    );
    horizonCrossDirection = Cartesian3.normalize(
      horizonCrossDirection,
      horizonCrossDirection
    );

    //Horizon positions
    const offset = Cartesian3.multiplyByScalar(
      horizonCrossDirection,
      horizonCrossDistance,
      posScratch1
    );
    tempVec = Cartesian3.normalize(
      Cartesian3.subtract(
        Cartesian3.add(horizonPlanePosition, offset, posScratch2),
        occluderPosition,
        posScratch2
      ),
      posScratch2
    );
    const dot0 = Cartesian3.dot(occluderPlaneNormal, tempVec);
    tempVec = Cartesian3.normalize(
      Cartesian3.subtract(
        Cartesian3.subtract(horizonPlanePosition, offset, tempVec),
        occluderPosition,
        tempVec
      ),
      tempVec
    );
    const dot1 = Cartesian3.dot(occluderPlaneNormal, tempVec);
    return dot0 < dot1 ? dot0 : dot1;
  };

  /**
   * Value and type information for per-instance geometry attribute that determines the geometry instance offset
   *
   * @alias OffsetGeometryInstanceAttribute
   * @constructor
   *
   * @param {Number} [x=0] The x translation
   * @param {Number} [y=0] The y translation
   * @param {Number} [z=0] The z translation
   *
   * @private
   *
   * @see GeometryInstance
   * @see GeometryInstanceAttribute
   */
  function OffsetGeometryInstanceAttribute(x, y, z) {
    x = defaultValue(x, 0);
    y = defaultValue(y, 0);
    z = defaultValue(z, 0);

    /**
     * The values for the attributes stored in a typed array.
     *
     * @type Float32Array
     */
    this.value = new Float32Array([x, y, z]);
  }

  Object.defineProperties(OffsetGeometryInstanceAttribute.prototype, {
    /**
     * The datatype of each component in the attribute, e.g., individual elements in
     * {@link OffsetGeometryInstanceAttribute#value}.
     *
     * @memberof OffsetGeometryInstanceAttribute.prototype
     *
     * @type {ComponentDatatype}
     * @readonly
     *
     * @default {@link ComponentDatatype.FLOAT}
     */
    componentDatatype: {
      get: function () {
        return ComponentDatatype$1.FLOAT;
      },
    },

    /**
     * The number of components in the attributes, i.e., {@link OffsetGeometryInstanceAttribute#value}.
     *
     * @memberof OffsetGeometryInstanceAttribute.prototype
     *
     * @type {Number}
     * @readonly
     *
     * @default 3
     */
    componentsPerAttribute: {
      get: function () {
        return 3;
      },
    },

    /**
     * When <code>true</code> and <code>componentDatatype</code> is an integer format,
     * indicate that the components should be mapped to the range [0, 1] (unsigned)
     * or [-1, 1] (signed) when they are accessed as floating-point for rendering.
     *
     * @memberof OffsetGeometryInstanceAttribute.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default false
     */
    normalize: {
      get: function () {
        return false;
      },
    },
  });

  /**
   * Creates a new {@link OffsetGeometryInstanceAttribute} instance given the provided an enabled flag and {@link DistanceDisplayCondition}.
   *
   * @param {Cartesian3} offset The cartesian offset
   * @returns {OffsetGeometryInstanceAttribute} The new {@link OffsetGeometryInstanceAttribute} instance.
   */
  OffsetGeometryInstanceAttribute.fromCartesian3 = function (offset) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("offset", offset);
    //>>includeEnd('debug');

    return new OffsetGeometryInstanceAttribute(offset.x, offset.y, offset.z);
  };

  /**
   * Converts a distance display condition to a typed array that can be used to assign a distance display condition attribute.
   *
   * @param {Cartesian3} offset The cartesian offset
   * @param {Float32Array} [result] The array to store the result in, if undefined a new instance will be created.
   * @returns {Float32Array} The modified result parameter or a new instance if result was undefined.
   *
   * @example
   * const attributes = primitive.getGeometryInstanceAttributes('an id');
   * attributes.modelMatrix = Cesium.OffsetGeometryInstanceAttribute.toValue(modelMatrix, attributes.modelMatrix);
   */
  OffsetGeometryInstanceAttribute.toValue = function (offset, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("offset", offset);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Float32Array([offset.x, offset.y, offset.z]);
    }

    result[0] = offset.x;
    result[1] = offset.y;
    result[2] = offset.z;
    return result;
  };

  /**
   * Provides geocoding via a {@link https://opencagedata.com/|OpenCage} server.
   * @alias OpenCageGeocoderService
   * @constructor
   *
   * @param {Resource|String} url The endpoint to the OpenCage server.
   * @param {String} apiKey The OpenCage API Key.
   * @param {Object} [params] An object with the following properties (See https://opencagedata.com/api#forward-opt):
   * @param {Number} [params.abbrv] When set to 1 we attempt to abbreviate and shorten the formatted string we return.
   * @param {Number} [options.add_request] When set to 1 the various request parameters are added to the response for ease of debugging.
   * @param {String} [options.bounds] Provides the geocoder with a hint to the region that the query resides in.
   * @param {String} [options.countrycode] Restricts the results to the specified country or countries (as defined by the ISO 3166-1 Alpha 2 standard).
   * @param {String} [options.jsonp] Wraps the returned JSON with a function name.
   * @param {String} [options.language] An IETF format language code.
   * @param {Number} [options.limit] The maximum number of results we should return.
   * @param {Number} [options.min_confidence] An integer from 1-10. Only results with at least this confidence will be returned.
   * @param {Number} [options.no_annotations] When set to 1 results will not contain annotations.
   * @param {Number} [options.no_dedupe] When set to 1 results will not be deduplicated.
   * @param {Number} [options.no_record] When set to 1 the query contents are not logged.
   * @param {Number} [options.pretty] When set to 1 results are 'pretty' printed for easier reading. Useful for debugging.
   * @param {String} [options.proximity] Provides the geocoder with a hint to bias results in favour of those closer to the specified location (For example: 41.40139,2.12870).
   *
   * @example
   * // Configure a Viewer to use the OpenCage Geocoder
   * const viewer = new Cesium.Viewer('cesiumContainer', {
   *   geocoder: new Cesium.OpenCageGeocoderService('https://api.opencagedata.com/geocode/v1/', '<API key>')
   * });
   */
  function OpenCageGeocoderService(url, apiKey, params) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("url", url);
    Check.defined("apiKey", apiKey);
    if (defined(params)) {
      Check.typeOf.object("params", params);
    }
    //>>includeEnd('debug');

    url = Resource.createIfNeeded(url);
    url.appendForwardSlash();
    url.setQueryParameters({ key: apiKey });
    this._url = url;
    this._params = defaultValue(params, {});
  }

  Object.defineProperties(OpenCageGeocoderService.prototype, {
    /**
     * The Resource used to access the OpenCage endpoint.
     * @type {Resource}
     * @memberof OpenCageGeocoderService.prototype
     * @readonly
     */
    url: {
      get: function () {
        return this._url;
      },
    },
    /**
     * Optional params passed to OpenCage in order to customize geocoding
     * @type {Object}
     * @memberof OpenCageGeocoderService.prototype
     * @readonly
     */
    params: {
      get: function () {
        return this._params;
      },
    },
  });

  /**
   * @function
   *
   * @param {String} query The query to be sent to the geocoder service
   * @returns {Promise<GeocoderService.Result[]>}
   */
  OpenCageGeocoderService.prototype.geocode = function (query) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("query", query);
    //>>includeEnd('debug');

    const resource = this._url.getDerivedResource({
      url: "json",
      queryParameters: combine$2(this._params, { q: query }),
    });
    return resource.fetchJson().then(function (response) {
      return response.results.map(function (resultObject) {
        let destination;
        const bounds = resultObject.bounds;

        if (defined(bounds)) {
          destination = Rectangle.fromDegrees(
            bounds.southwest.lng,
            bounds.southwest.lat,
            bounds.northeast.lng,
            bounds.northeast.lat
          );
        } else {
          const lon = resultObject.geometry.lat;
          const lat = resultObject.geometry.lng;
          destination = Cartesian3.fromDegrees(lon, lat);
        }

        return {
          displayName: resultObject.formatted,
          destination: destination,
        };
      });
    });
  };

  /**
   * Static interface for types which can store their values as packed
   * elements in an array.  These methods and properties are expected to be
   * defined on a constructor function.
   *
   * @interface Packable
   *
   * @see PackableForInterpolation
   */
  const Packable = {
    /**
     * The number of elements used to pack the object into an array.
     * @type {Number}
     */
    packedLength: undefined,

    /**
     * Stores the provided instance into the provided array.
     * @function
     *
     * @param {*} 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.
     */
    pack: DeveloperError.throwInstantiationError,

    /**
     * Retrieves an instance from a packed array.
     * @function
     *
     * @param {Number[]} array The packed array.
     * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
     * @param {Object} [result] The object into which to store the result.
     * @returns {Object} The modified result parameter or a new Object instance if one was not provided.
     */
    unpack: DeveloperError.throwInstantiationError,
  };

  /**
   * Static interface for {@link Packable} types which are interpolated in a
   * different representation than their packed value.  These methods and
   * properties are expected to be defined on a constructor function.
   *
   * @namespace PackableForInterpolation
   *
   * @see Packable
   */
  const PackableForInterpolation = {
    /**
     * The number of elements used to store the object into an array in its interpolatable form.
     * @type {Number}
     */
    packedInterpolationLength: undefined,

    /**
     * Converts a packed array into a form suitable for interpolation.
     * @function
     *
     * @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.
     */
    convertPackedArrayForInterpolation: DeveloperError.throwInstantiationError,

    /**
     * Retrieves an instance from a packed array converted with {@link PackableForInterpolation.convertPackedArrayForInterpolation}.
     * @function
     *
     * @param {Number[]} array The array previously packed for interpolation.
     * @param {Number[]} sourceArray The original packed array.
     * @param {Number} [startingIndex=0] The startingIndex used to convert the array.
     * @param {Number} [lastIndex=packedArray.length] The lastIndex used to convert the array.
     * @param {Object} [result] The object into which to store the result.
     * @returns {Object} The modified result parameter or a new Object instance if one was not provided.
     */
    unpackInterpolationResult: DeveloperError.throwInstantiationError,
  };

  function measureText(context2D, textString, font, stroke, fill) {
    const metrics = context2D.measureText(textString);
    const isSpace = !/\S/.test(textString);

    if (!isSpace) {
      const fontSize = document.defaultView
        .getComputedStyle(context2D.canvas)
        .getPropertyValue("font-size")
        .replace("px", "");
      const canvas = document.createElement("canvas");
      const padding = 100;
      const width = (metrics.width + padding) | 0;
      const height = 3 * fontSize;
      const baseline = height / 2;
      canvas.width = width;
      canvas.height = height;

      const ctx = canvas.getContext("2d");
      ctx.font = font;
      ctx.fillStyle = "white";
      ctx.fillRect(0, 0, canvas.width + 1, canvas.height + 1);

      if (stroke) {
        ctx.strokeStyle = "black";
        ctx.lineWidth = context2D.lineWidth;
        ctx.strokeText(textString, padding / 2, baseline);
      }

      if (fill) {
        ctx.fillStyle = "black";
        ctx.fillText(textString, padding / 2, baseline);
      }

      // Context image data has width * height * 4 elements, because
      // each pixel's R, G, B and A are consecutive values in the array.
      const pixelData = ctx.getImageData(0, 0, width, height).data;
      const length = pixelData.length;
      const width4 = width * 4;
      let i, j;

      let ascent, descent;
      // Find the number of rows (from the top) until the first non-white pixel
      for (i = 0; i < length; ++i) {
        if (pixelData[i] !== 255) {
          ascent = (i / width4) | 0;
          break;
        }
      }

      // Find the number of rows (from the bottom) until the first non-white pixel
      for (i = length - 1; i >= 0; --i) {
        if (pixelData[i] !== 255) {
          descent = (i / width4) | 0;
          break;
        }
      }

      let minx = -1;
      // For each column, for each row, check for first non-white pixel
      for (i = 0; i < width && minx === -1; ++i) {
        for (j = 0; j < height; ++j) {
          const pixelIndex = i * 4 + j * width4;
          if (
            pixelData[pixelIndex] !== 255 ||
            pixelData[pixelIndex + 1] !== 255 ||
            pixelData[pixelIndex + 2] !== 255 ||
            pixelData[pixelIndex + 3] !== 255
          ) {
            minx = i;
            break;
          }
        }
      }

      return {
        width: metrics.width,
        height: descent - ascent,
        ascent: baseline - ascent,
        descent: descent - baseline,
        minx: minx - padding / 2,
      };
    }

    return {
      width: metrics.width,
      height: 0,
      ascent: 0,
      descent: 0,
      minx: 0,
    };
  }

  let imageSmoothingEnabledName;

  /**
   * Writes the given text into a new canvas.  The canvas will be sized to fit the text.
   * If text is blank, returns undefined.
   *
   * @param {String} text The text to write.
   * @param {Object} [options] Object with the following properties:
   * @param {String} [options.font='10px sans-serif'] The CSS font to use.
   * @param {String} [options.textBaseline='bottom'] The baseline of the text.
   * @param {Boolean} [options.fill=true] Whether to fill the text.
   * @param {Boolean} [options.stroke=false] Whether to stroke the text.
   * @param {Color} [options.fillColor=Color.WHITE] The fill color.
   * @param {Color} [options.strokeColor=Color.BLACK] The stroke color.
   * @param {Number} [options.strokeWidth=1] The stroke width.
   * @param {Color} [options.backgroundColor=Color.TRANSPARENT] The background color of the canvas.
   * @param {Number} [options.padding=0] The pixel size of the padding to add around the text.
   * @returns {HTMLCanvasElement|undefined} A new canvas with the given text drawn into it.  The dimensions object
   *                   from measureText will also be added to the returned canvas. If text is
   *                   blank, returns undefined.
   * @function writeTextToCanvas
   */
  function writeTextToCanvas(text, options) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(text)) {
      throw new DeveloperError("text is required.");
    }
    //>>includeEnd('debug');
    if (text === "") {
      return undefined;
    }

    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const font = defaultValue(options.font, "10px sans-serif");
    const stroke = defaultValue(options.stroke, false);
    const fill = defaultValue(options.fill, true);
    const strokeWidth = defaultValue(options.strokeWidth, 1);
    const backgroundColor = defaultValue(
      options.backgroundColor,
      Color.TRANSPARENT
    );
    const padding = defaultValue(options.padding, 0);
    const doublePadding = padding * 2.0;

    const canvas = document.createElement("canvas");
    canvas.width = 1;
    canvas.height = 1;
    canvas.style.font = font;
    const context2D = canvas.getContext("2d");

    if (!defined(imageSmoothingEnabledName)) {
      if (defined(context2D.imageSmoothingEnabled)) {
        imageSmoothingEnabledName = "imageSmoothingEnabled";
      } else if (defined(context2D.mozImageSmoothingEnabled)) {
        imageSmoothingEnabledName = "mozImageSmoothingEnabled";
      } else if (defined(context2D.webkitImageSmoothingEnabled)) {
        imageSmoothingEnabledName = "webkitImageSmoothingEnabled";
      } else if (defined(context2D.msImageSmoothingEnabled)) {
        imageSmoothingEnabledName = "msImageSmoothingEnabled";
      }
    }

    context2D.font = font;
    context2D.lineJoin = "round";
    context2D.lineWidth = strokeWidth;
    context2D[imageSmoothingEnabledName] = false;

    // in order for measureText to calculate style, the canvas has to be
    // (temporarily) added to the DOM.
    canvas.style.visibility = "hidden";
    document.body.appendChild(canvas);

    const dimensions = measureText(context2D, text, font, stroke, fill);
    // Set canvas.dimensions to be accessed in LabelCollection
    canvas.dimensions = dimensions;

    document.body.removeChild(canvas);
    canvas.style.visibility = "";

    // Some characters, such as the letter j, have a non-zero starting position.
    // This value is used for kerning later, but we need to take it into account
    // now in order to draw the text completely on the canvas
    const x = -dimensions.minx;

    // Expand the width to include the starting position.
    const width = Math.ceil(dimensions.width) + x + doublePadding;

    // While the height of the letter is correct, we need to adjust
    // where we start drawing it so that letters like j and y properly dip
    // below the line.

    const height = dimensions.height + doublePadding;
    const baseline = height - dimensions.ascent + padding;
    const y = height - baseline + doublePadding;

    canvas.width = width;
    canvas.height = height;

    // Properties must be explicitly set again after changing width and height
    context2D.font = font;
    context2D.lineJoin = "round";
    context2D.lineWidth = strokeWidth;
    context2D[imageSmoothingEnabledName] = false;

    // Draw background
    if (backgroundColor !== Color.TRANSPARENT) {
      context2D.fillStyle = backgroundColor.toCssColorString();
      context2D.fillRect(0, 0, canvas.width, canvas.height);
    }

    if (stroke) {
      const strokeColor = defaultValue(options.strokeColor, Color.BLACK);
      context2D.strokeStyle = strokeColor.toCssColorString();
      context2D.strokeText(text, x + padding, y);
    }

    if (fill) {
      const fillColor = defaultValue(options.fillColor, Color.WHITE);
      context2D.fillStyle = fillColor.toCssColorString();
      context2D.fillText(text, x + padding, y);
    }

    return canvas;
  }

  /**
   * A utility class for generating custom map pins as canvas elements.
   * <br /><br />
   * <div align='center'>
   * <img src='Images/PinBuilder.png' width='500'/><br />
   * Example pins generated using both the maki icon set, which ships with Cesium, and single character text.
   * </div>
   *
   * @alias PinBuilder
   * @constructor
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Map%20Pins.html|Cesium Sandcastle PinBuilder Demo}
   */
  function PinBuilder() {
    this._cache = {};
  }

  /**
   * Creates an empty pin of the specified color and size.
   *
   * @param {Color} color The color of the pin.
   * @param {Number} size The size of the pin, in pixels.
   * @returns {HTMLCanvasElement} The canvas element that represents the generated pin.
   */
  PinBuilder.prototype.fromColor = function (color, size) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(color)) {
      throw new DeveloperError("color is required");
    }
    if (!defined(size)) {
      throw new DeveloperError("size is required");
    }
    //>>includeEnd('debug');
    return createPin(undefined, undefined, color, size, this._cache);
  };

  /**
   * Creates a pin with the specified icon, color, and size.
   *
   * @param {Resource|String} url The url of the image to be stamped onto the pin.
   * @param {Color} color The color of the pin.
   * @param {Number} size The size of the pin, in pixels.
   * @returns {HTMLCanvasElement|Promise.<HTMLCanvasElement>} The canvas element or a Promise to the canvas element that represents the generated pin.
   */
  PinBuilder.prototype.fromUrl = function (url, color, size) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(url)) {
      throw new DeveloperError("url is required");
    }
    if (!defined(color)) {
      throw new DeveloperError("color is required");
    }
    if (!defined(size)) {
      throw new DeveloperError("size is required");
    }
    //>>includeEnd('debug');
    return createPin(url, undefined, color, size, this._cache);
  };

  /**
   * Creates a pin with the specified {@link https://www.mapbox.com/maki/|maki} icon identifier, color, and size.
   *
   * @param {String} id The id of the maki icon to be stamped onto the pin.
   * @param {Color} color The color of the pin.
   * @param {Number} size The size of the pin, in pixels.
   * @returns {HTMLCanvasElement|Promise.<HTMLCanvasElement>} The canvas element or a Promise to the canvas element that represents the generated pin.
   */
  PinBuilder.prototype.fromMakiIconId = function (id, color, size) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(id)) {
      throw new DeveloperError("id is required");
    }
    if (!defined(color)) {
      throw new DeveloperError("color is required");
    }
    if (!defined(size)) {
      throw new DeveloperError("size is required");
    }
    //>>includeEnd('debug');
    return createPin(
      buildModuleUrl(`Assets/Textures/maki/${encodeURIComponent(id)}.png`),
      undefined,
      color,
      size,
      this._cache
    );
  };

  /**
   * Creates a pin with the specified text, color, and size.  The text will be sized to be as large as possible
   * while still being contained completely within the pin.
   *
   * @param {String} text The text to be stamped onto the pin.
   * @param {Color} color The color of the pin.
   * @param {Number} size The size of the pin, in pixels.
   * @returns {HTMLCanvasElement} The canvas element that represents the generated pin.
   */
  PinBuilder.prototype.fromText = function (text, color, size) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(text)) {
      throw new DeveloperError("text is required");
    }
    if (!defined(color)) {
      throw new DeveloperError("color is required");
    }
    if (!defined(size)) {
      throw new DeveloperError("size is required");
    }
    //>>includeEnd('debug');

    return createPin(undefined, text, color, size, this._cache);
  };

  const colorScratch$7 = new Color();

  //This function (except for the 3 commented lines) was auto-generated from an online tool,
  //http://www.professorcloud.com/svg-to-canvas/, using Assets/Textures/pin.svg as input.
  //The reason we simply can't load and draw the SVG directly to the canvas is because
  //it taints the canvas in Internet Explorer (and possibly some other browsers); making
  //it impossible to create a WebGL texture from the result.
  function drawPin(context2D, color, size) {
    context2D.save();
    context2D.scale(size / 24, size / 24); //Added to auto-generated code to scale up to desired size.
    context2D.fillStyle = color.toCssColorString(); //Modified from auto-generated code.
    context2D.strokeStyle = color.brighten(0.6, colorScratch$7).toCssColorString(); //Modified from auto-generated code.
    context2D.lineWidth = 0.846;
    context2D.beginPath();
    context2D.moveTo(6.72, 0.422);
    context2D.lineTo(17.28, 0.422);
    context2D.bezierCurveTo(18.553, 0.422, 19.577, 1.758, 19.577, 3.415);
    context2D.lineTo(19.577, 10.973);
    context2D.bezierCurveTo(19.577, 12.63, 18.553, 13.966, 17.282, 13.966);
    context2D.lineTo(14.386, 14.008);
    context2D.lineTo(11.826, 23.578);
    context2D.lineTo(9.614, 14.008);
    context2D.lineTo(6.719, 13.965);
    context2D.bezierCurveTo(5.446, 13.983, 4.422, 12.629, 4.422, 10.972);
    context2D.lineTo(4.422, 3.416);
    context2D.bezierCurveTo(4.423, 1.76, 5.447, 0.423, 6.718, 0.423);
    context2D.closePath();
    context2D.fill();
    context2D.stroke();
    context2D.restore();
  }

  //This function takes an image or canvas and uses it as a template
  //to "stamp" the pin with a white image outlined in black.  The color
  //values of the input image are ignored completely and only the alpha
  //values are used.
  function drawIcon(context2D, image, size) {
    //Size is the largest image that looks good inside of pin box.
    const imageSize = size / 2.5;
    let sizeX = imageSize;
    let sizeY = imageSize;

    if (image.width > image.height) {
      sizeY = imageSize * (image.height / image.width);
    } else if (image.width < image.height) {
      sizeX = imageSize * (image.width / image.height);
    }

    //x and y are the center of the pin box
    const x = Math.round((size - sizeX) / 2);
    const y = Math.round((7 / 24) * size - sizeY / 2);

    context2D.globalCompositeOperation = "destination-out";
    context2D.drawImage(image, x - 1, y, sizeX, sizeY);
    context2D.drawImage(image, x, y - 1, sizeX, sizeY);
    context2D.drawImage(image, x + 1, y, sizeX, sizeY);
    context2D.drawImage(image, x, y + 1, sizeX, sizeY);

    context2D.globalCompositeOperation = "destination-over";
    context2D.fillStyle = Color.BLACK.toCssColorString();
    context2D.fillRect(x - 1, y - 1, sizeX + 2, sizeY + 2);

    context2D.globalCompositeOperation = "destination-out";
    context2D.drawImage(image, x, y, sizeX, sizeY);

    context2D.globalCompositeOperation = "destination-over";
    context2D.fillStyle = Color.WHITE.toCssColorString();
    context2D.fillRect(x - 1, y - 2, sizeX + 2, sizeY + 2);
  }

  const stringifyScratch = new Array(4);
  function createPin(url, label, color, size, cache) {
    //Use the parameters as a unique ID for caching.
    stringifyScratch[0] = url;
    stringifyScratch[1] = label;
    stringifyScratch[2] = color;
    stringifyScratch[3] = size;
    const id = JSON.stringify(stringifyScratch);

    const item = cache[id];
    if (defined(item)) {
      return item;
    }

    const canvas = document.createElement("canvas");
    canvas.width = size;
    canvas.height = size;

    const context2D = canvas.getContext("2d");
    drawPin(context2D, color, size);

    if (defined(url)) {
      const resource = Resource.createIfNeeded(url);

      //If we have an image url, load it and then stamp the pin.
      const promise = resource.fetchImage().then(function (image) {
        drawIcon(context2D, image, size);
        cache[id] = canvas;
        return canvas;
      });
      cache[id] = promise;
      return promise;
    } else if (defined(label)) {
      //If we have a label, write it to a canvas and then stamp the pin.
      const image = writeTextToCanvas(label, {
        font: `bold ${size}px sans-serif`,
      });
      drawIcon(context2D, image, size);
    }

    cache[id] = canvas;
    return canvas;
  }

  /**
   * The data type of a pixel.
   *
   * @enum {Number}
   * @see PostProcessStage
   */
  const PixelDatatype = {
    UNSIGNED_BYTE: WebGLConstants$1.UNSIGNED_BYTE,
    UNSIGNED_SHORT: WebGLConstants$1.UNSIGNED_SHORT,
    UNSIGNED_INT: WebGLConstants$1.UNSIGNED_INT,
    FLOAT: WebGLConstants$1.FLOAT,
    HALF_FLOAT: WebGLConstants$1.HALF_FLOAT_OES,
    UNSIGNED_INT_24_8: WebGLConstants$1.UNSIGNED_INT_24_8,
    UNSIGNED_SHORT_4_4_4_4: WebGLConstants$1.UNSIGNED_SHORT_4_4_4_4,
    UNSIGNED_SHORT_5_5_5_1: WebGLConstants$1.UNSIGNED_SHORT_5_5_5_1,
    UNSIGNED_SHORT_5_6_5: WebGLConstants$1.UNSIGNED_SHORT_5_6_5,
  };

  /**
    @private
  */
  PixelDatatype.toWebGLConstant = function (pixelDatatype, context) {
    switch (pixelDatatype) {
      case PixelDatatype.UNSIGNED_BYTE:
        return WebGLConstants$1.UNSIGNED_BYTE;
      case PixelDatatype.UNSIGNED_SHORT:
        return WebGLConstants$1.UNSIGNED_SHORT;
      case PixelDatatype.UNSIGNED_INT:
        return WebGLConstants$1.UNSIGNED_INT;
      case PixelDatatype.FLOAT:
        return WebGLConstants$1.FLOAT;
      case PixelDatatype.HALF_FLOAT:
        return context.webgl2
          ? WebGLConstants$1.HALF_FLOAT
          : WebGLConstants$1.HALF_FLOAT_OES;
      case PixelDatatype.UNSIGNED_INT_24_8:
        return WebGLConstants$1.UNSIGNED_INT_24_8;
      case PixelDatatype.UNSIGNED_SHORT_4_4_4_4:
        return WebGLConstants$1.UNSIGNED_SHORT_4_4_4_4;
      case PixelDatatype.UNSIGNED_SHORT_5_5_5_1:
        return WebGLConstants$1.UNSIGNED_SHORT_5_5_5_1;
      case PixelDatatype.UNSIGNED_SHORT_5_6_5:
        return PixelDatatype.UNSIGNED_SHORT_5_6_5;
    }
  };

  /**
    @private
  */
  PixelDatatype.isPacked = function (pixelDatatype) {
    return (
      pixelDatatype === PixelDatatype.UNSIGNED_INT_24_8 ||
      pixelDatatype === PixelDatatype.UNSIGNED_SHORT_4_4_4_4 ||
      pixelDatatype === PixelDatatype.UNSIGNED_SHORT_5_5_5_1 ||
      pixelDatatype === PixelDatatype.UNSIGNED_SHORT_5_6_5
    );
  };

  /**
    @private
  */
  PixelDatatype.sizeInBytes = function (pixelDatatype) {
    switch (pixelDatatype) {
      case PixelDatatype.UNSIGNED_BYTE:
        return 1;
      case PixelDatatype.UNSIGNED_SHORT:
      case PixelDatatype.UNSIGNED_SHORT_4_4_4_4:
      case PixelDatatype.UNSIGNED_SHORT_5_5_5_1:
      case PixelDatatype.UNSIGNED_SHORT_5_6_5:
      case PixelDatatype.HALF_FLOAT:
        return 2;
      case PixelDatatype.UNSIGNED_INT:
      case PixelDatatype.FLOAT:
      case PixelDatatype.UNSIGNED_INT_24_8:
        return 4;
    }
  };

  /**
    @private
  */
  PixelDatatype.validate = function (pixelDatatype) {
    return (
      pixelDatatype === PixelDatatype.UNSIGNED_BYTE ||
      pixelDatatype === PixelDatatype.UNSIGNED_SHORT ||
      pixelDatatype === PixelDatatype.UNSIGNED_INT ||
      pixelDatatype === PixelDatatype.FLOAT ||
      pixelDatatype === PixelDatatype.HALF_FLOAT ||
      pixelDatatype === PixelDatatype.UNSIGNED_INT_24_8 ||
      pixelDatatype === PixelDatatype.UNSIGNED_SHORT_4_4_4_4 ||
      pixelDatatype === PixelDatatype.UNSIGNED_SHORT_5_5_5_1 ||
      pixelDatatype === PixelDatatype.UNSIGNED_SHORT_5_6_5
    );
  };

  var PixelDatatype$1 = Object.freeze(PixelDatatype);

  /**
   * The format of a pixel, i.e., the number of components it has and what they represent.
   *
   * @enum {Number}
   */
  const PixelFormat = {
    /**
     * A pixel format containing a depth value.
     *
     * @type {Number}
     * @constant
     */
    DEPTH_COMPONENT: WebGLConstants$1.DEPTH_COMPONENT,

    /**
     * A pixel format containing a depth and stencil value, most often used with {@link PixelDatatype.UNSIGNED_INT_24_8}.
     *
     * @type {Number}
     * @constant
     */
    DEPTH_STENCIL: WebGLConstants$1.DEPTH_STENCIL,

    /**
     * A pixel format containing an alpha channel.
     *
     * @type {Number}
     * @constant
     */
    ALPHA: WebGLConstants$1.ALPHA,

    /**
     * A pixel format containing red, green, and blue channels.
     *
     * @type {Number}
     * @constant
     */
    RGB: WebGLConstants$1.RGB,

    /**
     * A pixel format containing red, green, blue, and alpha channels.
     *
     * @type {Number}
     * @constant
     */
    RGBA: WebGLConstants$1.RGBA,

    /**
     * A pixel format containing a luminance (intensity) channel.
     *
     * @type {Number}
     * @constant
     */
    LUMINANCE: WebGLConstants$1.LUMINANCE,

    /**
     * A pixel format containing luminance (intensity) and alpha channels.
     *
     * @type {Number}
     * @constant
     */
    LUMINANCE_ALPHA: WebGLConstants$1.LUMINANCE_ALPHA,

    /**
     * A pixel format containing red, green, and blue channels that is DXT1 compressed.
     *
     * @type {Number}
     * @constant
     */
    RGB_DXT1: WebGLConstants$1.COMPRESSED_RGB_S3TC_DXT1_EXT,

    /**
     * A pixel format containing red, green, blue, and alpha channels that is DXT1 compressed.
     *
     * @type {Number}
     * @constant
     */
    RGBA_DXT1: WebGLConstants$1.COMPRESSED_RGBA_S3TC_DXT1_EXT,

    /**
     * A pixel format containing red, green, blue, and alpha channels that is DXT3 compressed.
     *
     * @type {Number}
     * @constant
     */
    RGBA_DXT3: WebGLConstants$1.COMPRESSED_RGBA_S3TC_DXT3_EXT,

    /**
     * A pixel format containing red, green, blue, and alpha channels that is DXT5 compressed.
     *
     * @type {Number}
     * @constant
     */
    RGBA_DXT5: WebGLConstants$1.COMPRESSED_RGBA_S3TC_DXT5_EXT,

    /**
     * A pixel format containing red, green, and blue channels that is PVR 4bpp compressed.
     *
     * @type {Number}
     * @constant
     */
    RGB_PVRTC_4BPPV1: WebGLConstants$1.COMPRESSED_RGB_PVRTC_4BPPV1_IMG,

    /**
     * A pixel format containing red, green, and blue channels that is PVR 2bpp compressed.
     *
     * @type {Number}
     * @constant
     */
    RGB_PVRTC_2BPPV1: WebGLConstants$1.COMPRESSED_RGB_PVRTC_2BPPV1_IMG,

    /**
     * A pixel format containing red, green, blue, and alpha channels that is PVR 4bpp compressed.
     *
     * @type {Number}
     * @constant
     */
    RGBA_PVRTC_4BPPV1: WebGLConstants$1.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG,

    /**
     * A pixel format containing red, green, blue, and alpha channels that is PVR 2bpp compressed.
     *
     * @type {Number}
     * @constant
     */
    RGBA_PVRTC_2BPPV1: WebGLConstants$1.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG,

    /**
     * A pixel format containing red, green, blue, and alpha channels that is ASTC compressed.
     *
     * @type {Number}
     * @constant
     */
    RGBA_ASTC: WebGLConstants$1.COMPRESSED_RGBA_ASTC_4x4_WEBGL,

    /**
     * A pixel format containing red, green, and blue channels that is ETC1 compressed.
     *
     * @type {Number}
     * @constant
     */
    RGB_ETC1: WebGLConstants$1.COMPRESSED_RGB_ETC1_WEBGL,

    /**
     * A pixel format containing red, green, and blue channels that is ETC2 compressed.
     *
     * @type {Number}
     * @constant
     */
    RGB8_ETC2: WebGLConstants$1.COMPRESSED_RGB8_ETC2,

    /**
     * A pixel format containing red, green, blue, and alpha channels that is ETC2 compressed.
     *
     * @type {Number}
     * @constant
     */
    RGBA8_ETC2_EAC: WebGLConstants$1.COMPRESSED_RGBA8_ETC2_EAC,

    /**
     * A pixel format containing red, green, blue, and alpha channels that is BC7 compressed.
     *
     * @type {Number}
     * @constant
     */
    RGBA_BC7: WebGLConstants$1.COMPRESSED_RGBA_BPTC_UNORM,
  };

  /**
   * @private
   */
  PixelFormat.componentsLength = function (pixelFormat) {
    switch (pixelFormat) {
      case PixelFormat.RGB:
        return 3;
      case PixelFormat.RGBA:
        return 4;
      case PixelFormat.LUMINANCE_ALPHA:
        return 2;
      case PixelFormat.ALPHA:
      case PixelFormat.LUMINANCE:
        return 1;
      default:
        return 1;
    }
  };

  /**
   * @private
   */
  PixelFormat.validate = function (pixelFormat) {
    return (
      pixelFormat === PixelFormat.DEPTH_COMPONENT ||
      pixelFormat === PixelFormat.DEPTH_STENCIL ||
      pixelFormat === PixelFormat.ALPHA ||
      pixelFormat === PixelFormat.RGB ||
      pixelFormat === PixelFormat.RGBA ||
      pixelFormat === PixelFormat.LUMINANCE ||
      pixelFormat === PixelFormat.LUMINANCE_ALPHA ||
      pixelFormat === PixelFormat.RGB_DXT1 ||
      pixelFormat === PixelFormat.RGBA_DXT1 ||
      pixelFormat === PixelFormat.RGBA_DXT3 ||
      pixelFormat === PixelFormat.RGBA_DXT5 ||
      pixelFormat === PixelFormat.RGB_PVRTC_4BPPV1 ||
      pixelFormat === PixelFormat.RGB_PVRTC_2BPPV1 ||
      pixelFormat === PixelFormat.RGBA_PVRTC_4BPPV1 ||
      pixelFormat === PixelFormat.RGBA_PVRTC_2BPPV1 ||
      pixelFormat === PixelFormat.RGBA_ASTC ||
      pixelFormat === PixelFormat.RGB_ETC1 ||
      pixelFormat === PixelFormat.RGB8_ETC2 ||
      pixelFormat === PixelFormat.RGBA8_ETC2_EAC ||
      pixelFormat === PixelFormat.RGBA_BC7
    );
  };

  /**
   * @private
   */
  PixelFormat.isColorFormat = function (pixelFormat) {
    return (
      pixelFormat === PixelFormat.ALPHA ||
      pixelFormat === PixelFormat.RGB ||
      pixelFormat === PixelFormat.RGBA ||
      pixelFormat === PixelFormat.LUMINANCE ||
      pixelFormat === PixelFormat.LUMINANCE_ALPHA
    );
  };

  /**
   * @private
   */
  PixelFormat.isDepthFormat = function (pixelFormat) {
    return (
      pixelFormat === PixelFormat.DEPTH_COMPONENT ||
      pixelFormat === PixelFormat.DEPTH_STENCIL
    );
  };

  /**
   * @private
   */
  PixelFormat.isCompressedFormat = function (pixelFormat) {
    return (
      pixelFormat === PixelFormat.RGB_DXT1 ||
      pixelFormat === PixelFormat.RGBA_DXT1 ||
      pixelFormat === PixelFormat.RGBA_DXT3 ||
      pixelFormat === PixelFormat.RGBA_DXT5 ||
      pixelFormat === PixelFormat.RGB_PVRTC_4BPPV1 ||
      pixelFormat === PixelFormat.RGB_PVRTC_2BPPV1 ||
      pixelFormat === PixelFormat.RGBA_PVRTC_4BPPV1 ||
      pixelFormat === PixelFormat.RGBA_PVRTC_2BPPV1 ||
      pixelFormat === PixelFormat.RGBA_ASTC ||
      pixelFormat === PixelFormat.RGB_ETC1 ||
      pixelFormat === PixelFormat.RGB8_ETC2 ||
      pixelFormat === PixelFormat.RGBA8_ETC2_EAC ||
      pixelFormat === PixelFormat.RGBA_BC7
    );
  };

  /**
   * @private
   */
  PixelFormat.isDXTFormat = function (pixelFormat) {
    return (
      pixelFormat === PixelFormat.RGB_DXT1 ||
      pixelFormat === PixelFormat.RGBA_DXT1 ||
      pixelFormat === PixelFormat.RGBA_DXT3 ||
      pixelFormat === PixelFormat.RGBA_DXT5
    );
  };

  /**
   * @private
   */
  PixelFormat.isPVRTCFormat = function (pixelFormat) {
    return (
      pixelFormat === PixelFormat.RGB_PVRTC_4BPPV1 ||
      pixelFormat === PixelFormat.RGB_PVRTC_2BPPV1 ||
      pixelFormat === PixelFormat.RGBA_PVRTC_4BPPV1 ||
      pixelFormat === PixelFormat.RGBA_PVRTC_2BPPV1
    );
  };

  /**
   * @private
   */
  PixelFormat.isASTCFormat = function (pixelFormat) {
    return pixelFormat === PixelFormat.RGBA_ASTC;
  };

  /**
   * @private
   */
  PixelFormat.isETC1Format = function (pixelFormat) {
    return pixelFormat === PixelFormat.RGB_ETC1;
  };

  /**
   * @private
   */
  PixelFormat.isETC2Format = function (pixelFormat) {
    return (
      pixelFormat === PixelFormat.RGB8_ETC2 ||
      pixelFormat === PixelFormat.RGBA8_ETC2_EAC
    );
  };

  /**
   * @private
   */
  PixelFormat.isBC7Format = function (pixelFormat) {
    return pixelFormat === PixelFormat.RGBA_BC7;
  };

  /**
   * @private
   */
  PixelFormat.compressedTextureSizeInBytes = function (
    pixelFormat,
    width,
    height
  ) {
    switch (pixelFormat) {
      case PixelFormat.RGB_DXT1:
      case PixelFormat.RGBA_DXT1:
      case PixelFormat.RGB_ETC1:
      case PixelFormat.RGB8_ETC2:
        return Math.floor((width + 3) / 4) * Math.floor((height + 3) / 4) * 8;

      case PixelFormat.RGBA_DXT3:
      case PixelFormat.RGBA_DXT5:
      case PixelFormat.RGBA_ASTC:
      case PixelFormat.RGBA8_ETC2_EAC:
        return Math.floor((width + 3) / 4) * Math.floor((height + 3) / 4) * 16;

      case PixelFormat.RGB_PVRTC_4BPPV1:
      case PixelFormat.RGBA_PVRTC_4BPPV1:
        return Math.floor((Math.max(width, 8) * Math.max(height, 8) * 4 + 7) / 8);

      case PixelFormat.RGB_PVRTC_2BPPV1:
      case PixelFormat.RGBA_PVRTC_2BPPV1:
        return Math.floor(
          (Math.max(width, 16) * Math.max(height, 8) * 2 + 7) / 8
        );

      case PixelFormat.RGBA_BC7:
        return Math.ceil(width / 4) * Math.ceil(height / 4) * 16;

      default:
        return 0;
    }
  };

  /**
   * @private
   */
  PixelFormat.textureSizeInBytes = function (
    pixelFormat,
    pixelDatatype,
    width,
    height
  ) {
    let componentsLength = PixelFormat.componentsLength(pixelFormat);
    if (PixelDatatype$1.isPacked(pixelDatatype)) {
      componentsLength = 1;
    }
    return (
      componentsLength * PixelDatatype$1.sizeInBytes(pixelDatatype) * width * height
    );
  };

  /**
   * @private
   */
  PixelFormat.alignmentInBytes = function (pixelFormat, pixelDatatype, width) {
    const mod =
      PixelFormat.textureSizeInBytes(pixelFormat, pixelDatatype, width, 1) % 4;
    return mod === 0 ? 4 : mod === 2 ? 2 : 1;
  };

  /**
   * @private
   */
  PixelFormat.createTypedArray = function (
    pixelFormat,
    pixelDatatype,
    width,
    height
  ) {
    let constructor;
    const sizeInBytes = PixelDatatype$1.sizeInBytes(pixelDatatype);
    if (sizeInBytes === Uint8Array.BYTES_PER_ELEMENT) {
      constructor = Uint8Array;
    } else if (sizeInBytes === Uint16Array.BYTES_PER_ELEMENT) {
      constructor = Uint16Array;
    } else if (
      sizeInBytes === Float32Array.BYTES_PER_ELEMENT &&
      pixelDatatype === PixelDatatype$1.FLOAT
    ) {
      constructor = Float32Array;
    } else {
      constructor = Uint32Array;
    }

    const size = PixelFormat.componentsLength(pixelFormat) * width * height;
    return new constructor(size);
  };

  /**
   * @private
   */
  PixelFormat.flipY = function (
    bufferView,
    pixelFormat,
    pixelDatatype,
    width,
    height
  ) {
    if (height === 1) {
      return bufferView;
    }
    const flipped = PixelFormat.createTypedArray(
      pixelFormat,
      pixelDatatype,
      width,
      height
    );
    const numberOfComponents = PixelFormat.componentsLength(pixelFormat);
    const textureWidth = width * numberOfComponents;
    for (let i = 0; i < height; ++i) {
      const row = i * width * numberOfComponents;
      const flippedRow = (height - i - 1) * width * numberOfComponents;
      for (let j = 0; j < textureWidth; ++j) {
        flipped[flippedRow + j] = bufferView[row + j];
      }
    }
    return flipped;
  };

  /**
   * @private
   */
  PixelFormat.toInternalFormat = function (pixelFormat, pixelDatatype, context) {
    // WebGL 1 require internalFormat to be the same as PixelFormat
    if (!context.webgl2) {
      return pixelFormat;
    }

    // Convert pixelFormat to correct internalFormat for WebGL 2
    if (pixelFormat === PixelFormat.DEPTH_STENCIL) {
      return WebGLConstants$1.DEPTH24_STENCIL8;
    }

    if (pixelFormat === PixelFormat.DEPTH_COMPONENT) {
      if (pixelDatatype === PixelDatatype$1.UNSIGNED_SHORT) {
        return WebGLConstants$1.DEPTH_COMPONENT16;
      } else if (pixelDatatype === PixelDatatype$1.UNSIGNED_INT) {
        return WebGLConstants$1.DEPTH_COMPONENT24;
      }
    }

    if (pixelDatatype === PixelDatatype$1.FLOAT) {
      switch (pixelFormat) {
        case PixelFormat.RGBA:
          return WebGLConstants$1.RGBA32F;
        case PixelFormat.RGB:
          return WebGLConstants$1.RGB32F;
        case PixelFormat.RG:
          return WebGLConstants$1.RG32F;
        case PixelFormat.R:
          return WebGLConstants$1.R32F;
      }
    }

    if (pixelDatatype === PixelDatatype$1.HALF_FLOAT) {
      switch (pixelFormat) {
        case PixelFormat.RGBA:
          return WebGLConstants$1.RGBA16F;
        case PixelFormat.RGB:
          return WebGLConstants$1.RGB16F;
        case PixelFormat.RG:
          return WebGLConstants$1.RG16F;
        case PixelFormat.R:
          return WebGLConstants$1.R16F;
      }
    }

    return pixelFormat;
  };

  var PixelFormat$1 = Object.freeze(PixelFormat);

  /**
   * Describes geometry representing a plane centered at the origin, with a unit width and length.
   *
   * @alias PlaneGeometry
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
   *
   * @example
   * const planeGeometry = new Cesium.PlaneGeometry({
   *   vertexFormat : Cesium.VertexFormat.POSITION_ONLY
   * });
   */
  function PlaneGeometry(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const vertexFormat = defaultValue(options.vertexFormat, VertexFormat.DEFAULT);

    this._vertexFormat = vertexFormat;
    this._workerName = "createPlaneGeometry";
  }

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  PlaneGeometry.packedLength = VertexFormat.packedLength;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {PlaneGeometry} 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
   */
  PlaneGeometry.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    VertexFormat.pack(value._vertexFormat, array, startingIndex);

    return array;
  };

  const scratchVertexFormat$5 = new VertexFormat();
  const scratchOptions$9 = {
    vertexFormat: scratchVertexFormat$5,
  };

  /**
   * 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 {PlaneGeometry} [result] The object into which to store the result.
   * @returns {PlaneGeometry} The modified result parameter or a new PlaneGeometry instance if one was not provided.
   */
  PlaneGeometry.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    const vertexFormat = VertexFormat.unpack(
      array,
      startingIndex,
      scratchVertexFormat$5
    );

    if (!defined(result)) {
      return new PlaneGeometry(scratchOptions$9);
    }

    result._vertexFormat = VertexFormat.clone(vertexFormat, result._vertexFormat);

    return result;
  };

  const min$1 = new Cartesian3(-0.5, -0.5, 0.0);
  const max$1 = new Cartesian3(0.5, 0.5, 0.0);

  /**
   * Computes the geometric representation of a plane, including its vertices, indices, and a bounding sphere.
   *
   * @param {PlaneGeometry} planeGeometry A description of the plane.
   * @returns {Geometry|undefined} The computed vertices and indices.
   */
  PlaneGeometry.createGeometry = function (planeGeometry) {
    const vertexFormat = planeGeometry._vertexFormat;

    const attributes = new GeometryAttributes();
    let indices;
    let positions;

    if (vertexFormat.position) {
      // 4 corner points.  Duplicated 3 times each for each incident edge/face.
      positions = new Float64Array(4 * 3);

      // +z face
      positions[0] = min$1.x;
      positions[1] = min$1.y;
      positions[2] = 0.0;
      positions[3] = max$1.x;
      positions[4] = min$1.y;
      positions[5] = 0.0;
      positions[6] = max$1.x;
      positions[7] = max$1.y;
      positions[8] = 0.0;
      positions[9] = min$1.x;
      positions[10] = max$1.y;
      positions[11] = 0.0;

      attributes.position = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.DOUBLE,
        componentsPerAttribute: 3,
        values: positions,
      });

      if (vertexFormat.normal) {
        const normals = new Float32Array(4 * 3);

        // +z face
        normals[0] = 0.0;
        normals[1] = 0.0;
        normals[2] = 1.0;
        normals[3] = 0.0;
        normals[4] = 0.0;
        normals[5] = 1.0;
        normals[6] = 0.0;
        normals[7] = 0.0;
        normals[8] = 1.0;
        normals[9] = 0.0;
        normals[10] = 0.0;
        normals[11] = 1.0;

        attributes.normal = new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 3,
          values: normals,
        });
      }

      if (vertexFormat.st) {
        const texCoords = new Float32Array(4 * 2);

        // +z face
        texCoords[0] = 0.0;
        texCoords[1] = 0.0;
        texCoords[2] = 1.0;
        texCoords[3] = 0.0;
        texCoords[4] = 1.0;
        texCoords[5] = 1.0;
        texCoords[6] = 0.0;
        texCoords[7] = 1.0;

        attributes.st = new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 2,
          values: texCoords,
        });
      }

      if (vertexFormat.tangent) {
        const tangents = new Float32Array(4 * 3);

        // +z face
        tangents[0] = 1.0;
        tangents[1] = 0.0;
        tangents[2] = 0.0;
        tangents[3] = 1.0;
        tangents[4] = 0.0;
        tangents[5] = 0.0;
        tangents[6] = 1.0;
        tangents[7] = 0.0;
        tangents[8] = 0.0;
        tangents[9] = 1.0;
        tangents[10] = 0.0;
        tangents[11] = 0.0;

        attributes.tangent = new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 3,
          values: tangents,
        });
      }

      if (vertexFormat.bitangent) {
        const bitangents = new Float32Array(4 * 3);

        // +z face
        bitangents[0] = 0.0;
        bitangents[1] = 1.0;
        bitangents[2] = 0.0;
        bitangents[3] = 0.0;
        bitangents[4] = 1.0;
        bitangents[5] = 0.0;
        bitangents[6] = 0.0;
        bitangents[7] = 1.0;
        bitangents[8] = 0.0;
        bitangents[9] = 0.0;
        bitangents[10] = 1.0;
        bitangents[11] = 0.0;

        attributes.bitangent = new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 3,
          values: bitangents,
        });
      }

      // 2 triangles
      indices = new Uint16Array(2 * 3);

      // +z face
      indices[0] = 0;
      indices[1] = 1;
      indices[2] = 2;
      indices[3] = 0;
      indices[4] = 2;
      indices[5] = 3;
    }

    return new Geometry({
      attributes: attributes,
      indices: indices,
      primitiveType: PrimitiveType$1.TRIANGLES,
      boundingSphere: new BoundingSphere(Cartesian3.ZERO, Math.sqrt(2.0)),
    });
  };

  /**
   * Describes geometry representing the outline of a plane centered at the origin, with a unit width and length.
   *
   * @alias PlaneOutlineGeometry
   * @constructor
   *
   */
  function PlaneOutlineGeometry() {
    this._workerName = "createPlaneOutlineGeometry";
  }

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  PlaneOutlineGeometry.packedLength = 0;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {PlaneOutlineGeometry} value The value to pack.
   * @param {Number[]} array The array to pack into.
   *
   * @returns {Number[]} The array that was packed into
   */
  PlaneOutlineGeometry.pack = function (value, array) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("value", value);
    Check.defined("array", array);
    //>>includeEnd('debug');

    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 {PlaneOutlineGeometry} [result] The object into which to store the result.
   * @returns {PlaneOutlineGeometry} The modified result parameter or a new PlaneOutlineGeometry instance if one was not provided.
   */
  PlaneOutlineGeometry.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    if (!defined(result)) {
      return new PlaneOutlineGeometry();
    }

    return result;
  };

  const min = new Cartesian3(-0.5, -0.5, 0.0);
  const max = new Cartesian3(0.5, 0.5, 0.0);

  /**
   * Computes the geometric representation of an outline of a plane, including its vertices, indices, and a bounding sphere.
   *
   * @returns {Geometry|undefined} The computed vertices and indices.
   */
  PlaneOutlineGeometry.createGeometry = function () {
    const attributes = new GeometryAttributes();
    const indices = new Uint16Array(4 * 2);
    const positions = new Float64Array(4 * 3);

    positions[0] = min.x;
    positions[1] = min.y;
    positions[2] = min.z;
    positions[3] = max.x;
    positions[4] = min.y;
    positions[5] = min.z;
    positions[6] = max.x;
    positions[7] = max.y;
    positions[8] = min.z;
    positions[9] = min.x;
    positions[10] = max.y;
    positions[11] = min.z;

    attributes.position = new GeometryAttribute({
      componentDatatype: ComponentDatatype$1.DOUBLE,
      componentsPerAttribute: 3,
      values: positions,
    });

    indices[0] = 0;
    indices[1] = 1;
    indices[2] = 1;
    indices[3] = 2;
    indices[4] = 2;
    indices[5] = 3;
    indices[6] = 3;
    indices[7] = 0;

    return new Geometry({
      attributes: attributes,
      indices: indices,
      primitiveType: PrimitiveType$1.LINES,
      boundingSphere: new BoundingSphere(Cartesian3.ZERO, Math.sqrt(2.0)),
    });
  };

  const scratchCarto1 = new Cartographic();
  const scratchCarto2 = new Cartographic();
  function adjustPosHeightsForNormal(position, p1, p2, ellipsoid) {
    const carto1 = ellipsoid.cartesianToCartographic(position, scratchCarto1);
    const height = carto1.height;
    const p1Carto = ellipsoid.cartesianToCartographic(p1, scratchCarto2);
    p1Carto.height = height;
    ellipsoid.cartographicToCartesian(p1Carto, p1);

    const p2Carto = ellipsoid.cartesianToCartographic(p2, scratchCarto2);
    p2Carto.height = height - 100;
    ellipsoid.cartographicToCartesian(p2Carto, p2);
  }

  const scratchBoundingRectangle = new BoundingRectangle();
  const scratchPosition$c = new Cartesian3();
  const scratchNormal$2 = new Cartesian3();
  const scratchTangent$1 = new Cartesian3();
  const scratchBitangent$1 = new Cartesian3();
  const p1Scratch = new Cartesian3();
  const p2Scratch = new Cartesian3();
  let scratchPerPosNormal = new Cartesian3();
  let scratchPerPosTangent = new Cartesian3();
  let scratchPerPosBitangent = new Cartesian3();

  const appendTextureCoordinatesOrigin = new Cartesian2();
  const appendTextureCoordinatesCartesian2 = new Cartesian2();
  const appendTextureCoordinatesCartesian3 = new Cartesian3();
  const appendTextureCoordinatesQuaternion = new Quaternion();
  const appendTextureCoordinatesMatrix3 = new Matrix3();
  const tangentMatrixScratch = new Matrix3();

  function computeAttributes$2(options) {
    const vertexFormat = options.vertexFormat;
    const geometry = options.geometry;
    const shadowVolume = options.shadowVolume;
    const flatPositions = geometry.attributes.position.values;
    const flatTexcoords = defined(geometry.attributes.st)
      ? geometry.attributes.st.values
      : undefined;

    let length = flatPositions.length;
    const wall = options.wall;
    const top = options.top || wall;
    const bottom = options.bottom || wall;
    if (
      vertexFormat.st ||
      vertexFormat.normal ||
      vertexFormat.tangent ||
      vertexFormat.bitangent ||
      shadowVolume
    ) {
      // PERFORMANCE_IDEA: Compute before subdivision, then just interpolate during subdivision.
      // PERFORMANCE_IDEA: Compute with createGeometryFromPositions() for fast path when there's no holes.
      const boundingRectangle = options.boundingRectangle;
      const tangentPlane = options.tangentPlane;
      const ellipsoid = options.ellipsoid;
      const stRotation = options.stRotation;
      const perPositionHeight = options.perPositionHeight;

      const origin = appendTextureCoordinatesOrigin;
      origin.x = boundingRectangle.x;
      origin.y = boundingRectangle.y;

      const textureCoordinates = vertexFormat.st
        ? new Float32Array(2 * (length / 3))
        : undefined;
      let normals;
      if (vertexFormat.normal) {
        if (perPositionHeight && top && !wall) {
          normals = geometry.attributes.normal.values;
        } else {
          normals = new Float32Array(length);
        }
      }
      const tangents = vertexFormat.tangent
        ? new Float32Array(length)
        : undefined;
      const bitangents = vertexFormat.bitangent
        ? new Float32Array(length)
        : undefined;
      const extrudeNormals = shadowVolume ? new Float32Array(length) : undefined;

      let textureCoordIndex = 0;
      let attrIndex = 0;

      let normal = scratchNormal$2;
      let tangent = scratchTangent$1;
      let bitangent = scratchBitangent$1;
      let recomputeNormal = true;

      let textureMatrix = appendTextureCoordinatesMatrix3;
      let tangentRotationMatrix = tangentMatrixScratch;
      if (stRotation !== 0.0) {
        let rotation = Quaternion.fromAxisAngle(
          tangentPlane._plane.normal,
          stRotation,
          appendTextureCoordinatesQuaternion
        );
        textureMatrix = Matrix3.fromQuaternion(rotation, textureMatrix);

        rotation = Quaternion.fromAxisAngle(
          tangentPlane._plane.normal,
          -stRotation,
          appendTextureCoordinatesQuaternion
        );
        tangentRotationMatrix = Matrix3.fromQuaternion(
          rotation,
          tangentRotationMatrix
        );
      } else {
        textureMatrix = Matrix3.clone(Matrix3.IDENTITY, textureMatrix);
        tangentRotationMatrix = Matrix3.clone(
          Matrix3.IDENTITY,
          tangentRotationMatrix
        );
      }

      let bottomOffset = 0;
      let bottomOffset2 = 0;

      if (top && bottom) {
        bottomOffset = length / 2;
        bottomOffset2 = length / 3;

        length /= 2;
      }

      for (let i = 0; i < length; i += 3) {
        const position = Cartesian3.fromArray(
          flatPositions,
          i,
          appendTextureCoordinatesCartesian3
        );

        if (vertexFormat.st) {
          if (!defined(flatTexcoords)) {
            let p = Matrix3.multiplyByVector(
              textureMatrix,
              position,
              scratchPosition$c
            );
            p = ellipsoid.scaleToGeodeticSurface(p, p);
            const st = tangentPlane.projectPointOntoPlane(
              p,
              appendTextureCoordinatesCartesian2
            );
            Cartesian2.subtract(st, origin, st);

            const stx = CesiumMath.clamp(st.x / boundingRectangle.width, 0, 1);
            const sty = CesiumMath.clamp(st.y / boundingRectangle.height, 0, 1);
            if (bottom) {
              textureCoordinates[textureCoordIndex + bottomOffset2] = stx;
              textureCoordinates[textureCoordIndex + 1 + bottomOffset2] = sty;
            }
            if (top) {
              textureCoordinates[textureCoordIndex] = stx;
              textureCoordinates[textureCoordIndex + 1] = sty;
            }

            textureCoordIndex += 2;
          }
        }

        if (
          vertexFormat.normal ||
          vertexFormat.tangent ||
          vertexFormat.bitangent ||
          shadowVolume
        ) {
          const attrIndex1 = attrIndex + 1;
          const attrIndex2 = attrIndex + 2;

          if (wall) {
            if (i + 3 < length) {
              const p1 = Cartesian3.fromArray(flatPositions, i + 3, p1Scratch);

              if (recomputeNormal) {
                const p2 = Cartesian3.fromArray(
                  flatPositions,
                  i + length,
                  p2Scratch
                );
                if (perPositionHeight) {
                  adjustPosHeightsForNormal(position, p1, p2, ellipsoid);
                }
                Cartesian3.subtract(p1, position, p1);
                Cartesian3.subtract(p2, position, p2);
                normal = Cartesian3.normalize(
                  Cartesian3.cross(p2, p1, normal),
                  normal
                );
                recomputeNormal = false;
              }

              if (Cartesian3.equalsEpsilon(p1, position, CesiumMath.EPSILON10)) {
                // if we've reached a corner
                recomputeNormal = true;
              }
            }

            if (vertexFormat.tangent || vertexFormat.bitangent) {
              bitangent = ellipsoid.geodeticSurfaceNormal(position, bitangent);
              if (vertexFormat.tangent) {
                tangent = Cartesian3.normalize(
                  Cartesian3.cross(bitangent, normal, tangent),
                  tangent
                );
              }
            }
          } else {
            normal = ellipsoid.geodeticSurfaceNormal(position, normal);
            if (vertexFormat.tangent || vertexFormat.bitangent) {
              if (perPositionHeight) {
                scratchPerPosNormal = Cartesian3.fromArray(
                  normals,
                  attrIndex,
                  scratchPerPosNormal
                );
                scratchPerPosTangent = Cartesian3.cross(
                  Cartesian3.UNIT_Z,
                  scratchPerPosNormal,
                  scratchPerPosTangent
                );
                scratchPerPosTangent = Cartesian3.normalize(
                  Matrix3.multiplyByVector(
                    tangentRotationMatrix,
                    scratchPerPosTangent,
                    scratchPerPosTangent
                  ),
                  scratchPerPosTangent
                );
                if (vertexFormat.bitangent) {
                  scratchPerPosBitangent = Cartesian3.normalize(
                    Cartesian3.cross(
                      scratchPerPosNormal,
                      scratchPerPosTangent,
                      scratchPerPosBitangent
                    ),
                    scratchPerPosBitangent
                  );
                }
              }

              tangent = Cartesian3.cross(Cartesian3.UNIT_Z, normal, tangent);
              tangent = Cartesian3.normalize(
                Matrix3.multiplyByVector(tangentRotationMatrix, tangent, tangent),
                tangent
              );
              if (vertexFormat.bitangent) {
                bitangent = Cartesian3.normalize(
                  Cartesian3.cross(normal, tangent, bitangent),
                  bitangent
                );
              }
            }
          }

          if (vertexFormat.normal) {
            if (options.wall) {
              normals[attrIndex + bottomOffset] = normal.x;
              normals[attrIndex1 + bottomOffset] = normal.y;
              normals[attrIndex2 + bottomOffset] = normal.z;
            } else if (bottom) {
              normals[attrIndex + bottomOffset] = -normal.x;
              normals[attrIndex1 + bottomOffset] = -normal.y;
              normals[attrIndex2 + bottomOffset] = -normal.z;
            }

            if ((top && !perPositionHeight) || wall) {
              normals[attrIndex] = normal.x;
              normals[attrIndex1] = normal.y;
              normals[attrIndex2] = normal.z;
            }
          }

          if (shadowVolume) {
            if (wall) {
              normal = ellipsoid.geodeticSurfaceNormal(position, normal);
            }
            extrudeNormals[attrIndex + bottomOffset] = -normal.x;
            extrudeNormals[attrIndex1 + bottomOffset] = -normal.y;
            extrudeNormals[attrIndex2 + bottomOffset] = -normal.z;
          }

          if (vertexFormat.tangent) {
            if (options.wall) {
              tangents[attrIndex + bottomOffset] = tangent.x;
              tangents[attrIndex1 + bottomOffset] = tangent.y;
              tangents[attrIndex2 + bottomOffset] = tangent.z;
            } else if (bottom) {
              tangents[attrIndex + bottomOffset] = -tangent.x;
              tangents[attrIndex1 + bottomOffset] = -tangent.y;
              tangents[attrIndex2 + bottomOffset] = -tangent.z;
            }

            if (top) {
              if (perPositionHeight) {
                tangents[attrIndex] = scratchPerPosTangent.x;
                tangents[attrIndex1] = scratchPerPosTangent.y;
                tangents[attrIndex2] = scratchPerPosTangent.z;
              } else {
                tangents[attrIndex] = tangent.x;
                tangents[attrIndex1] = tangent.y;
                tangents[attrIndex2] = tangent.z;
              }
            }
          }

          if (vertexFormat.bitangent) {
            if (bottom) {
              bitangents[attrIndex + bottomOffset] = bitangent.x;
              bitangents[attrIndex1 + bottomOffset] = bitangent.y;
              bitangents[attrIndex2 + bottomOffset] = bitangent.z;
            }
            if (top) {
              if (perPositionHeight) {
                bitangents[attrIndex] = scratchPerPosBitangent.x;
                bitangents[attrIndex1] = scratchPerPosBitangent.y;
                bitangents[attrIndex2] = scratchPerPosBitangent.z;
              } else {
                bitangents[attrIndex] = bitangent.x;
                bitangents[attrIndex1] = bitangent.y;
                bitangents[attrIndex2] = bitangent.z;
              }
            }
          }
          attrIndex += 3;
        }
      }

      if (vertexFormat.st && !defined(flatTexcoords)) {
        geometry.attributes.st = new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 2,
          values: textureCoordinates,
        });
      }

      if (vertexFormat.normal) {
        geometry.attributes.normal = new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 3,
          values: normals,
        });
      }

      if (vertexFormat.tangent) {
        geometry.attributes.tangent = new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 3,
          values: tangents,
        });
      }

      if (vertexFormat.bitangent) {
        geometry.attributes.bitangent = new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 3,
          values: bitangents,
        });
      }

      if (shadowVolume) {
        geometry.attributes.extrudeDirection = new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 3,
          values: extrudeNormals,
        });
      }
    }

    if (options.extrude && defined(options.offsetAttribute)) {
      const size = flatPositions.length / 3;
      let offsetAttribute = new Uint8Array(size);

      if (options.offsetAttribute === GeometryOffsetAttribute$1.TOP) {
        if ((top && bottom) || wall) {
          offsetAttribute = offsetAttribute.fill(1, 0, size / 2);
        } else if (top) {
          offsetAttribute = offsetAttribute.fill(1);
        }
      } else {
        const offsetValue =
          options.offsetAttribute === GeometryOffsetAttribute$1.NONE ? 0 : 1;
        offsetAttribute = offsetAttribute.fill(offsetValue);
      }

      geometry.attributes.applyOffset = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
        componentsPerAttribute: 1,
        values: offsetAttribute,
      });
    }

    return geometry;
  }

  const startCartographicScratch = new Cartographic();
  const endCartographicScratch = new Cartographic();
  const idlCross = {
    westOverIDL: 0.0,
    eastOverIDL: 0.0,
  };
  let ellipsoidGeodesic = new EllipsoidGeodesic();
  function computeRectangle$1(positions, ellipsoid, arcType, granularity, result) {
    result = defaultValue(result, new Rectangle());
    if (!defined(positions) || positions.length < 3) {
      result.west = 0.0;
      result.north = 0.0;
      result.south = 0.0;
      result.east = 0.0;
      return result;
    }

    if (arcType === ArcType$1.RHUMB) {
      return Rectangle.fromCartesianArray(positions, ellipsoid, result);
    }

    if (!ellipsoidGeodesic.ellipsoid.equals(ellipsoid)) {
      ellipsoidGeodesic = new EllipsoidGeodesic(undefined, undefined, ellipsoid);
    }

    result.west = Number.POSITIVE_INFINITY;
    result.east = Number.NEGATIVE_INFINITY;
    result.south = Number.POSITIVE_INFINITY;
    result.north = Number.NEGATIVE_INFINITY;

    idlCross.westOverIDL = Number.POSITIVE_INFINITY;
    idlCross.eastOverIDL = Number.NEGATIVE_INFINITY;

    const inverseChordLength =
      1.0 / CesiumMath.chordLength(granularity, ellipsoid.maximumRadius);
    const positionsLength = positions.length;
    let endCartographic = ellipsoid.cartesianToCartographic(
      positions[0],
      endCartographicScratch
    );
    let startCartographic = startCartographicScratch;
    let swap;

    for (let i = 1; i < positionsLength; i++) {
      swap = startCartographic;
      startCartographic = endCartographic;
      endCartographic = ellipsoid.cartesianToCartographic(positions[i], swap);
      ellipsoidGeodesic.setEndPoints(startCartographic, endCartographic);
      interpolateAndGrowRectangle(
        ellipsoidGeodesic,
        inverseChordLength,
        result,
        idlCross
      );
    }

    swap = startCartographic;
    startCartographic = endCartographic;
    endCartographic = ellipsoid.cartesianToCartographic(positions[0], swap);
    ellipsoidGeodesic.setEndPoints(startCartographic, endCartographic);
    interpolateAndGrowRectangle(
      ellipsoidGeodesic,
      inverseChordLength,
      result,
      idlCross
    );

    if (result.east - result.west > idlCross.eastOverIDL - idlCross.westOverIDL) {
      result.west = idlCross.westOverIDL;
      result.east = idlCross.eastOverIDL;

      if (result.east > CesiumMath.PI) {
        result.east = result.east - CesiumMath.TWO_PI;
      }
      if (result.west > CesiumMath.PI) {
        result.west = result.west - CesiumMath.TWO_PI;
      }
    }

    return result;
  }

  const interpolatedCartographicScratch = new Cartographic();
  function interpolateAndGrowRectangle(
    ellipsoidGeodesic,
    inverseChordLength,
    result,
    idlCross
  ) {
    const segmentLength = ellipsoidGeodesic.surfaceDistance;

    const numPoints = Math.ceil(segmentLength * inverseChordLength);
    const subsegmentDistance =
      numPoints > 0 ? segmentLength / (numPoints - 1) : Number.POSITIVE_INFINITY;
    let interpolationDistance = 0.0;

    for (let i = 0; i < numPoints; i++) {
      const interpolatedCartographic = ellipsoidGeodesic.interpolateUsingSurfaceDistance(
        interpolationDistance,
        interpolatedCartographicScratch
      );
      interpolationDistance += subsegmentDistance;
      const longitude = interpolatedCartographic.longitude;
      const latitude = interpolatedCartographic.latitude;

      result.west = Math.min(result.west, longitude);
      result.east = Math.max(result.east, longitude);
      result.south = Math.min(result.south, latitude);
      result.north = Math.max(result.north, latitude);

      const lonAdjusted =
        longitude >= 0 ? longitude : longitude + CesiumMath.TWO_PI;
      idlCross.westOverIDL = Math.min(idlCross.westOverIDL, lonAdjusted);
      idlCross.eastOverIDL = Math.max(idlCross.eastOverIDL, lonAdjusted);
    }
  }

  const createGeometryFromPositionsExtrudedPositions = [];

  function createGeometryFromPositionsExtruded$1(
    ellipsoid,
    polygon,
    textureCoordinates,
    granularity,
    hierarchy,
    perPositionHeight,
    closeTop,
    closeBottom,
    vertexFormat,
    arcType
  ) {
    const geos = {
      walls: [],
    };
    let i;

    if (closeTop || closeBottom) {
      const topGeo = PolygonGeometryLibrary.createGeometryFromPositions(
        ellipsoid,
        polygon,
        textureCoordinates,
        granularity,
        perPositionHeight,
        vertexFormat,
        arcType
      );

      const edgePoints = topGeo.attributes.position.values;
      const indices = topGeo.indices;
      let numPositions;
      let newIndices;

      if (closeTop && closeBottom) {
        const topBottomPositions = edgePoints.concat(edgePoints);

        numPositions = topBottomPositions.length / 3;

        newIndices = IndexDatatype$1.createTypedArray(
          numPositions,
          indices.length * 2
        );
        newIndices.set(indices);
        const ilength = indices.length;

        const length = numPositions / 2;

        for (i = 0; i < ilength; i += 3) {
          const i0 = newIndices[i] + length;
          const i1 = newIndices[i + 1] + length;
          const i2 = newIndices[i + 2] + length;

          newIndices[i + ilength] = i2;
          newIndices[i + 1 + ilength] = i1;
          newIndices[i + 2 + ilength] = i0;
        }

        topGeo.attributes.position.values = topBottomPositions;
        if (perPositionHeight && vertexFormat.normal) {
          const normals = topGeo.attributes.normal.values;
          topGeo.attributes.normal.values = new Float32Array(
            topBottomPositions.length
          );
          topGeo.attributes.normal.values.set(normals);
        }

        if (vertexFormat.st && defined(textureCoordinates)) {
          const texcoords = topGeo.attributes.st.values;
          topGeo.attributes.st.values = new Float32Array(numPositions * 2);
          topGeo.attributes.st.values = texcoords.concat(texcoords);
        }

        topGeo.indices = newIndices;
      } else if (closeBottom) {
        numPositions = edgePoints.length / 3;
        newIndices = IndexDatatype$1.createTypedArray(numPositions, indices.length);

        for (i = 0; i < indices.length; i += 3) {
          newIndices[i] = indices[i + 2];
          newIndices[i + 1] = indices[i + 1];
          newIndices[i + 2] = indices[i];
        }

        topGeo.indices = newIndices;
      }

      geos.topAndBottom = new GeometryInstance({
        geometry: topGeo,
      });
    }

    let outerRing = hierarchy.outerRing;
    let tangentPlane = EllipsoidTangentPlane.fromPoints(outerRing, ellipsoid);
    let positions2D = tangentPlane.projectPointsOntoPlane(
      outerRing,
      createGeometryFromPositionsExtrudedPositions
    );

    let windingOrder = PolygonPipeline.computeWindingOrder2D(positions2D);
    if (windingOrder === WindingOrder$1.CLOCKWISE) {
      outerRing = outerRing.slice().reverse();
    }

    let wallGeo = PolygonGeometryLibrary.computeWallGeometry(
      outerRing,
      textureCoordinates,
      ellipsoid,
      granularity,
      perPositionHeight,
      arcType
    );
    geos.walls.push(
      new GeometryInstance({
        geometry: wallGeo,
      })
    );

    const holes = hierarchy.holes;
    for (i = 0; i < holes.length; i++) {
      let hole = holes[i];

      tangentPlane = EllipsoidTangentPlane.fromPoints(hole, ellipsoid);
      positions2D = tangentPlane.projectPointsOntoPlane(
        hole,
        createGeometryFromPositionsExtrudedPositions
      );

      windingOrder = PolygonPipeline.computeWindingOrder2D(positions2D);
      if (windingOrder === WindingOrder$1.COUNTER_CLOCKWISE) {
        hole = hole.slice().reverse();
      }

      wallGeo = PolygonGeometryLibrary.computeWallGeometry(
        hole,
        textureCoordinates,
        ellipsoid,
        granularity,
        perPositionHeight,
        arcType
      );
      geos.walls.push(
        new GeometryInstance({
          geometry: wallGeo,
        })
      );
    }

    return geos;
  }

  /**
   * A description of a polygon on the ellipsoid. The polygon is defined by a polygon hierarchy. Polygon geometry can be rendered with both {@link Primitive} and {@link GroundPrimitive}.
   *
   * @alias PolygonGeometry
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {PolygonHierarchy} options.polygonHierarchy A polygon hierarchy that can include holes.
   * @param {Number} [options.height=0.0] The distance in meters between the polygon and the ellipsoid surface.
   * @param {Number} [options.extrudedHeight] The distance in meters between the polygon's extruded face and the ellipsoid surface.
   * @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
   * @param {Number} [options.stRotation=0.0] The rotation of the texture coordinates, in radians. A positive rotation is counter-clockwise.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid to be used as a reference.
   * @param {Number} [options.granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
   * @param {Boolean} [options.perPositionHeight=false] Use the height of options.positions for each position instead of using options.height to determine the height.
   * @param {Boolean} [options.closeTop=true] When false, leaves off the top of an extruded polygon open.
   * @param {Boolean} [options.closeBottom=true] When false, leaves off the bottom of an extruded polygon open.
   * @param {ArcType} [options.arcType=ArcType.GEODESIC] The type of line the polygon edges must follow. Valid options are {@link ArcType.GEODESIC} and {@link ArcType.RHUMB}.
   * @param {PolygonHierarchy} [options.textureCoordinates] Texture coordinates as a {@link PolygonHierarchy} of {@link Cartesian2} points. Has no effect for ground primitives.
   *
   * @see PolygonGeometry#createGeometry
   * @see PolygonGeometry#fromPositions
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Polygon.html|Cesium Sandcastle Polygon Demo}
   *
   * @example
   * // 1. create a polygon from points
   * const polygon = new Cesium.PolygonGeometry({
   *   polygonHierarchy : new Cesium.PolygonHierarchy(
   *     Cesium.Cartesian3.fromDegreesArray([
   *       -72.0, 40.0,
   *       -70.0, 35.0,
   *       -75.0, 30.0,
   *       -70.0, 30.0,
   *       -68.0, 40.0
   *     ])
   *   )
   * });
   * const geometry = Cesium.PolygonGeometry.createGeometry(polygon);
   *
   * // 2. create a nested polygon with holes
   * const polygonWithHole = new Cesium.PolygonGeometry({
   *   polygonHierarchy : new Cesium.PolygonHierarchy(
   *     Cesium.Cartesian3.fromDegreesArray([
   *       -109.0, 30.0,
   *       -95.0, 30.0,
   *       -95.0, 40.0,
   *       -109.0, 40.0
   *     ]),
   *     [new Cesium.PolygonHierarchy(
   *       Cesium.Cartesian3.fromDegreesArray([
   *         -107.0, 31.0,
   *         -107.0, 39.0,
   *         -97.0, 39.0,
   *         -97.0, 31.0
   *       ]),
   *       [new Cesium.PolygonHierarchy(
   *         Cesium.Cartesian3.fromDegreesArray([
   *           -105.0, 33.0,
   *           -99.0, 33.0,
   *           -99.0, 37.0,
   *           -105.0, 37.0
   *         ]),
   *         [new Cesium.PolygonHierarchy(
   *           Cesium.Cartesian3.fromDegreesArray([
   *             -103.0, 34.0,
   *             -101.0, 34.0,
   *             -101.0, 36.0,
   *             -103.0, 36.0
   *           ])
   *         )]
   *       )]
   *     )]
   *   )
   * });
   * const geometry = Cesium.PolygonGeometry.createGeometry(polygonWithHole);
   *
   * // 3. create extruded polygon
   * const extrudedPolygon = new Cesium.PolygonGeometry({
   *   polygonHierarchy : new Cesium.PolygonHierarchy(
   *     Cesium.Cartesian3.fromDegreesArray([
   *       -72.0, 40.0,
   *       -70.0, 35.0,
   *       -75.0, 30.0,
   *       -70.0, 30.0,
   *       -68.0, 40.0
   *     ])
   *   ),
   *   extrudedHeight: 300000
   * });
   * const geometry = Cesium.PolygonGeometry.createGeometry(extrudedPolygon);
   */
  function PolygonGeometry(options) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options", options);
    Check.typeOf.object("options.polygonHierarchy", options.polygonHierarchy);
    if (
      defined(options.perPositionHeight) &&
      options.perPositionHeight &&
      defined(options.height)
    ) {
      throw new DeveloperError(
        "Cannot use both options.perPositionHeight and options.height"
      );
    }
    if (
      defined(options.arcType) &&
      options.arcType !== ArcType$1.GEODESIC &&
      options.arcType !== ArcType$1.RHUMB
    ) {
      throw new DeveloperError(
        "Invalid arcType. Valid options are ArcType.GEODESIC and ArcType.RHUMB."
      );
    }
    //>>includeEnd('debug');

    const polygonHierarchy = options.polygonHierarchy;
    const vertexFormat = defaultValue(options.vertexFormat, VertexFormat.DEFAULT);
    const ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);
    const granularity = defaultValue(
      options.granularity,
      CesiumMath.RADIANS_PER_DEGREE
    );
    const stRotation = defaultValue(options.stRotation, 0.0);
    const textureCoordinates = options.textureCoordinates;
    const perPositionHeight = defaultValue(options.perPositionHeight, false);
    const perPositionHeightExtrude =
      perPositionHeight && defined(options.extrudedHeight);
    let height = defaultValue(options.height, 0.0);
    let extrudedHeight = defaultValue(options.extrudedHeight, height);

    if (!perPositionHeightExtrude) {
      const h = Math.max(height, extrudedHeight);
      extrudedHeight = Math.min(height, extrudedHeight);
      height = h;
    }

    this._vertexFormat = VertexFormat.clone(vertexFormat);
    this._ellipsoid = Ellipsoid.clone(ellipsoid);
    this._granularity = granularity;
    this._stRotation = stRotation;
    this._height = height;
    this._extrudedHeight = extrudedHeight;
    this._closeTop = defaultValue(options.closeTop, true);
    this._closeBottom = defaultValue(options.closeBottom, true);
    this._polygonHierarchy = polygonHierarchy;
    this._perPositionHeight = perPositionHeight;
    this._perPositionHeightExtrude = perPositionHeightExtrude;
    this._shadowVolume = defaultValue(options.shadowVolume, false);
    this._workerName = "createPolygonGeometry";
    this._offsetAttribute = options.offsetAttribute;
    this._arcType = defaultValue(options.arcType, ArcType$1.GEODESIC);

    this._rectangle = undefined;
    this._textureCoordinateRotationPoints = undefined;
    this._textureCoordinates = textureCoordinates;

    /**
     * The number of elements used to pack the object into an array.
     * @type {Number}
     */
    this.packedLength =
      PolygonGeometryLibrary.computeHierarchyPackedLength(
        polygonHierarchy,
        Cartesian3
      ) +
      Ellipsoid.packedLength +
      VertexFormat.packedLength +
      (textureCoordinates
        ? PolygonGeometryLibrary.computeHierarchyPackedLength(
            textureCoordinates,
            Cartesian2
          )
        : 1) +
      12;
  }

  /**
   * A description of a polygon from an array of positions. Polygon geometry can be rendered with both {@link Primitive} and {@link GroundPrimitive}.
   *
   * @param {Object} options Object with the following properties:
   * @param {Cartesian3[]} options.positions An array of positions that defined the corner points of the polygon.
   * @param {Number} [options.height=0.0] The height of the polygon.
   * @param {Number} [options.extrudedHeight] The height of the polygon extrusion.
   * @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
   * @param {Number} [options.stRotation=0.0] The rotation of the texture coordinates, in radians. A positive rotation is counter-clockwise.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid to be used as a reference.
   * @param {Number} [options.granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
   * @param {Boolean} [options.perPositionHeight=false] Use the height of options.positions for each position instead of using options.height to determine the height.
   * @param {Boolean} [options.closeTop=true] When false, leaves off the top of an extruded polygon open.
   * @param {Boolean} [options.closeBottom=true] When false, leaves off the bottom of an extruded polygon open.
   * @param {ArcType} [options.arcType=ArcType.GEODESIC] The type of line the polygon edges must follow. Valid options are {@link ArcType.GEODESIC} and {@link ArcType.RHUMB}.
   * @param {PolygonHierarchy} [options.textureCoordinates] Texture coordinates as a {@link PolygonHierarchy} of {@link Cartesian2} points. Has no effect for ground primitives.
   * @returns {PolygonGeometry}
   *
   * @example
   * // create a polygon from points
   * const polygon = Cesium.PolygonGeometry.fromPositions({
   *   positions : Cesium.Cartesian3.fromDegreesArray([
   *     -72.0, 40.0,
   *     -70.0, 35.0,
   *     -75.0, 30.0,
   *     -70.0, 30.0,
   *     -68.0, 40.0
   *   ])
   * });
   * const geometry = Cesium.PolygonGeometry.createGeometry(polygon);
   *
   * @see PolygonGeometry#createGeometry
   */
  PolygonGeometry.fromPositions = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    Check.defined("options.positions", options.positions);
    //>>includeEnd('debug');

    const newOptions = {
      polygonHierarchy: {
        positions: options.positions,
      },
      height: options.height,
      extrudedHeight: options.extrudedHeight,
      vertexFormat: options.vertexFormat,
      stRotation: options.stRotation,
      ellipsoid: options.ellipsoid,
      granularity: options.granularity,
      perPositionHeight: options.perPositionHeight,
      closeTop: options.closeTop,
      closeBottom: options.closeBottom,
      offsetAttribute: options.offsetAttribute,
      arcType: options.arcType,
      textureCoordinates: options.textureCoordinates,
    };
    return new PolygonGeometry(newOptions);
  };

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {PolygonGeometry} 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
   */
  PolygonGeometry.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    startingIndex = PolygonGeometryLibrary.packPolygonHierarchy(
      value._polygonHierarchy,
      array,
      startingIndex,
      Cartesian3
    );

    Ellipsoid.pack(value._ellipsoid, array, startingIndex);
    startingIndex += Ellipsoid.packedLength;

    VertexFormat.pack(value._vertexFormat, array, startingIndex);
    startingIndex += VertexFormat.packedLength;

    array[startingIndex++] = value._height;
    array[startingIndex++] = value._extrudedHeight;
    array[startingIndex++] = value._granularity;
    array[startingIndex++] = value._stRotation;
    array[startingIndex++] = value._perPositionHeightExtrude ? 1.0 : 0.0;
    array[startingIndex++] = value._perPositionHeight ? 1.0 : 0.0;
    array[startingIndex++] = value._closeTop ? 1.0 : 0.0;
    array[startingIndex++] = value._closeBottom ? 1.0 : 0.0;
    array[startingIndex++] = value._shadowVolume ? 1.0 : 0.0;
    array[startingIndex++] = defaultValue(value._offsetAttribute, -1);
    array[startingIndex++] = value._arcType;
    if (defined(value._textureCoordinates)) {
      startingIndex = PolygonGeometryLibrary.packPolygonHierarchy(
        value._textureCoordinates,
        array,
        startingIndex,
        Cartesian2
      );
    } else {
      array[startingIndex++] = -1.0;
    }
    array[startingIndex++] = value.packedLength;
    return array;
  };

  const scratchEllipsoid$9 = Ellipsoid.clone(Ellipsoid.UNIT_SPHERE);
  const scratchVertexFormat$4 = new VertexFormat();

  //Only used to avoid inability to default construct.
  const dummyOptions$1 = {
    polygonHierarchy: {},
  };

  /**
   * 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 {PolygonGeometry} [result] The object into which to store the result.
   */
  PolygonGeometry.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    const polygonHierarchy = PolygonGeometryLibrary.unpackPolygonHierarchy(
      array,
      startingIndex,
      Cartesian3
    );
    startingIndex = polygonHierarchy.startingIndex;
    delete polygonHierarchy.startingIndex;

    const ellipsoid = Ellipsoid.unpack(array, startingIndex, scratchEllipsoid$9);
    startingIndex += Ellipsoid.packedLength;

    const vertexFormat = VertexFormat.unpack(
      array,
      startingIndex,
      scratchVertexFormat$4
    );
    startingIndex += VertexFormat.packedLength;

    const height = array[startingIndex++];
    const extrudedHeight = array[startingIndex++];
    const granularity = array[startingIndex++];
    const stRotation = array[startingIndex++];
    const perPositionHeightExtrude = array[startingIndex++] === 1.0;
    const perPositionHeight = array[startingIndex++] === 1.0;
    const closeTop = array[startingIndex++] === 1.0;
    const closeBottom = array[startingIndex++] === 1.0;
    const shadowVolume = array[startingIndex++] === 1.0;
    const offsetAttribute = array[startingIndex++];
    const arcType = array[startingIndex++];
    const textureCoordinates =
      array[startingIndex] === -1.0
        ? undefined
        : PolygonGeometryLibrary.unpackPolygonHierarchy(
            array,
            startingIndex,
            Cartesian2
          );
    if (defined(textureCoordinates)) {
      startingIndex = textureCoordinates.startingIndex;
      delete textureCoordinates.startingIndex;
    } else {
      startingIndex++;
    }
    const packedLength = array[startingIndex++];

    if (!defined(result)) {
      result = new PolygonGeometry(dummyOptions$1);
    }

    result._polygonHierarchy = polygonHierarchy;
    result._ellipsoid = Ellipsoid.clone(ellipsoid, result._ellipsoid);
    result._vertexFormat = VertexFormat.clone(vertexFormat, result._vertexFormat);
    result._height = height;
    result._extrudedHeight = extrudedHeight;
    result._granularity = granularity;
    result._stRotation = stRotation;
    result._perPositionHeightExtrude = perPositionHeightExtrude;
    result._perPositionHeight = perPositionHeight;
    result._closeTop = closeTop;
    result._closeBottom = closeBottom;
    result._shadowVolume = shadowVolume;
    result._offsetAttribute =
      offsetAttribute === -1 ? undefined : offsetAttribute;
    result._arcType = arcType;
    result._textureCoordinates = textureCoordinates;
    result.packedLength = packedLength;

    return result;
  };

  /**
   * Returns the bounding rectangle given the provided options
   *
   * @param {Object} options Object with the following properties:
   * @param {PolygonHierarchy} options.polygonHierarchy A polygon hierarchy that can include holes.
   * @param {Number} [options.granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions sampled.
   * @param {ArcType} [options.arcType=ArcType.GEODESIC] The type of line the polygon edges must follow. Valid options are {@link ArcType.GEODESIC} and {@link ArcType.RHUMB}.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid to be used as a reference.
   * @param {Rectangle} [result] An object in which to store the result.
   *
   * @returns {Rectangle} The result rectangle
   */
  PolygonGeometry.computeRectangle = function (options, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options", options);
    Check.typeOf.object("options.polygonHierarchy", options.polygonHierarchy);
    //>>includeEnd('debug');

    const granularity = defaultValue(
      options.granularity,
      CesiumMath.RADIANS_PER_DEGREE
    );
    const arcType = defaultValue(options.arcType, ArcType$1.GEODESIC);
    //>>includeStart('debug', pragmas.debug);
    if (arcType !== ArcType$1.GEODESIC && arcType !== ArcType$1.RHUMB) {
      throw new DeveloperError(
        "Invalid arcType. Valid options are ArcType.GEODESIC and ArcType.RHUMB."
      );
    }
    //>>includeEnd('debug');

    const polygonHierarchy = options.polygonHierarchy;
    const ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);

    return computeRectangle$1(
      polygonHierarchy.positions,
      ellipsoid,
      arcType,
      granularity,
      result
    );
  };

  /**
   * Computes the geometric representation of a polygon, including its vertices, indices, and a bounding sphere.
   *
   * @param {PolygonGeometry} polygonGeometry A description of the polygon.
   * @returns {Geometry|undefined} The computed vertices and indices.
   */
  PolygonGeometry.createGeometry = function (polygonGeometry) {
    const vertexFormat = polygonGeometry._vertexFormat;
    const ellipsoid = polygonGeometry._ellipsoid;
    const granularity = polygonGeometry._granularity;
    const stRotation = polygonGeometry._stRotation;
    const polygonHierarchy = polygonGeometry._polygonHierarchy;
    const perPositionHeight = polygonGeometry._perPositionHeight;
    const closeTop = polygonGeometry._closeTop;
    const closeBottom = polygonGeometry._closeBottom;
    const arcType = polygonGeometry._arcType;
    const textureCoordinates = polygonGeometry._textureCoordinates;

    const hasTextureCoordinates = defined(textureCoordinates);

    let outerPositions = polygonHierarchy.positions;
    if (outerPositions.length < 3) {
      return;
    }

    const tangentPlane = EllipsoidTangentPlane.fromPoints(
      outerPositions,
      ellipsoid
    );

    const results = PolygonGeometryLibrary.polygonsFromHierarchy(
      polygonHierarchy,
      hasTextureCoordinates,
      tangentPlane.projectPointsOntoPlane.bind(tangentPlane),
      !perPositionHeight,
      ellipsoid
    );

    const hierarchy = results.hierarchy;
    const polygons = results.polygons;

    const dummyFunction = function (identity) {
      return identity;
    };

    const textureCoordinatePolygons = hasTextureCoordinates
      ? PolygonGeometryLibrary.polygonsFromHierarchy(
          textureCoordinates,
          true,
          dummyFunction,
          false
        ).polygons
      : undefined;

    if (hierarchy.length === 0) {
      return;
    }

    outerPositions = hierarchy[0].outerRing;
    const boundingRectangle = PolygonGeometryLibrary.computeBoundingRectangle(
      tangentPlane.plane.normal,
      tangentPlane.projectPointOntoPlane.bind(tangentPlane),
      outerPositions,
      stRotation,
      scratchBoundingRectangle
    );

    const geometries = [];

    const height = polygonGeometry._height;
    const extrudedHeight = polygonGeometry._extrudedHeight;
    const extrude =
      polygonGeometry._perPositionHeightExtrude ||
      !CesiumMath.equalsEpsilon(height, extrudedHeight, 0, CesiumMath.EPSILON2);

    const options = {
      perPositionHeight: perPositionHeight,
      vertexFormat: vertexFormat,
      geometry: undefined,
      tangentPlane: tangentPlane,
      boundingRectangle: boundingRectangle,
      ellipsoid: ellipsoid,
      stRotation: stRotation,
      textureCoordinates: undefined,
      bottom: false,
      top: true,
      wall: false,
      extrude: false,
      arcType: arcType,
    };

    let i;

    if (extrude) {
      options.extrude = true;
      options.top = closeTop;
      options.bottom = closeBottom;
      options.shadowVolume = polygonGeometry._shadowVolume;
      options.offsetAttribute = polygonGeometry._offsetAttribute;
      for (i = 0; i < polygons.length; i++) {
        const splitGeometry = createGeometryFromPositionsExtruded$1(
          ellipsoid,
          polygons[i],
          hasTextureCoordinates ? textureCoordinatePolygons[i] : undefined,
          granularity,
          hierarchy[i],
          perPositionHeight,
          closeTop,
          closeBottom,
          vertexFormat,
          arcType
        );

        let topAndBottom;
        if (closeTop && closeBottom) {
          topAndBottom = splitGeometry.topAndBottom;
          options.geometry = PolygonGeometryLibrary.scaleToGeodeticHeightExtruded(
            topAndBottom.geometry,
            height,
            extrudedHeight,
            ellipsoid,
            perPositionHeight
          );
        } else if (closeTop) {
          topAndBottom = splitGeometry.topAndBottom;
          topAndBottom.geometry.attributes.position.values = PolygonPipeline.scaleToGeodeticHeight(
            topAndBottom.geometry.attributes.position.values,
            height,
            ellipsoid,
            !perPositionHeight
          );
          options.geometry = topAndBottom.geometry;
        } else if (closeBottom) {
          topAndBottom = splitGeometry.topAndBottom;
          topAndBottom.geometry.attributes.position.values = PolygonPipeline.scaleToGeodeticHeight(
            topAndBottom.geometry.attributes.position.values,
            extrudedHeight,
            ellipsoid,
            true
          );
          options.geometry = topAndBottom.geometry;
        }
        if (closeTop || closeBottom) {
          options.wall = false;
          topAndBottom.geometry = computeAttributes$2(options);
          geometries.push(topAndBottom);
        }

        const walls = splitGeometry.walls;
        options.wall = true;
        for (let k = 0; k < walls.length; k++) {
          const wall = walls[k];
          options.geometry = PolygonGeometryLibrary.scaleToGeodeticHeightExtruded(
            wall.geometry,
            height,
            extrudedHeight,
            ellipsoid,
            perPositionHeight
          );
          wall.geometry = computeAttributes$2(options);
          geometries.push(wall);
        }
      }
    } else {
      for (i = 0; i < polygons.length; i++) {
        const geometryInstance = new GeometryInstance({
          geometry: PolygonGeometryLibrary.createGeometryFromPositions(
            ellipsoid,
            polygons[i],
            hasTextureCoordinates ? textureCoordinatePolygons[i] : undefined,
            granularity,
            perPositionHeight,
            vertexFormat,
            arcType
          ),
        });
        geometryInstance.geometry.attributes.position.values = PolygonPipeline.scaleToGeodeticHeight(
          geometryInstance.geometry.attributes.position.values,
          height,
          ellipsoid,
          !perPositionHeight
        );
        options.geometry = geometryInstance.geometry;

        geometryInstance.geometry = computeAttributes$2(options);

        if (defined(polygonGeometry._offsetAttribute)) {
          const length =
            geometryInstance.geometry.attributes.position.values.length;
          const offsetValue =
            polygonGeometry._offsetAttribute === GeometryOffsetAttribute$1.NONE
              ? 0
              : 1;
          const applyOffset = new Uint8Array(length / 3).fill(offsetValue);
          geometryInstance.geometry.attributes.applyOffset = new GeometryAttribute(
            {
              componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
              componentsPerAttribute: 1,
              values: applyOffset,
            }
          );
        }

        geometries.push(geometryInstance);
      }
    }

    const geometry = GeometryPipeline.combineInstances(geometries)[0];
    geometry.attributes.position.values = new Float64Array(
      geometry.attributes.position.values
    );
    geometry.indices = IndexDatatype$1.createTypedArray(
      geometry.attributes.position.values.length / 3,
      geometry.indices
    );

    const attributes = geometry.attributes;
    const boundingSphere = BoundingSphere.fromVertices(
      attributes.position.values
    );

    if (!vertexFormat.position) {
      delete attributes.position;
    }

    return new Geometry({
      attributes: attributes,
      indices: geometry.indices,
      primitiveType: geometry.primitiveType,
      boundingSphere: boundingSphere,
      offsetAttribute: polygonGeometry._offsetAttribute,
    });
  };

  /**
   * @private
   */
  PolygonGeometry.createShadowVolume = function (
    polygonGeometry,
    minHeightFunc,
    maxHeightFunc
  ) {
    const granularity = polygonGeometry._granularity;
    const ellipsoid = polygonGeometry._ellipsoid;

    const minHeight = minHeightFunc(granularity, ellipsoid);
    const maxHeight = maxHeightFunc(granularity, ellipsoid);

    return new PolygonGeometry({
      polygonHierarchy: polygonGeometry._polygonHierarchy,
      ellipsoid: ellipsoid,
      stRotation: polygonGeometry._stRotation,
      granularity: granularity,
      perPositionHeight: false,
      extrudedHeight: minHeight,
      height: maxHeight,
      vertexFormat: VertexFormat.POSITION_ONLY,
      shadowVolume: true,
      arcType: polygonGeometry._arcType,
    });
  };

  function textureCoordinateRotationPoints$1(polygonGeometry) {
    const stRotation = -polygonGeometry._stRotation;
    if (stRotation === 0.0) {
      return [0, 0, 0, 1, 1, 0];
    }
    const ellipsoid = polygonGeometry._ellipsoid;
    const positions = polygonGeometry._polygonHierarchy.positions;
    const boundingRectangle = polygonGeometry.rectangle;
    return Geometry._textureCoordinateRotationPoints(
      positions,
      stRotation,
      ellipsoid,
      boundingRectangle
    );
  }

  Object.defineProperties(PolygonGeometry.prototype, {
    /**
     * @private
     */
    rectangle: {
      get: function () {
        if (!defined(this._rectangle)) {
          const positions = this._polygonHierarchy.positions;
          this._rectangle = computeRectangle$1(
            positions,
            this._ellipsoid,
            this._arcType,
            this._granularity
          );
        }

        return this._rectangle;
      },
    },
    /**
     * For remapping texture coordinates when rendering PolygonGeometries as GroundPrimitives.
     * @private
     */
    textureCoordinateRotationPoints: {
      get: function () {
        if (!defined(this._textureCoordinateRotationPoints)) {
          this._textureCoordinateRotationPoints = textureCoordinateRotationPoints$1(
            this
          );
        }
        return this._textureCoordinateRotationPoints;
      },
    },
  });

  /**
   * An hierarchy of linear rings which define a polygon and its holes.
   * The holes themselves may also have holes which nest inner polygons.
   * @alias PolygonHierarchy
   * @constructor
   *
   * @param {Cartesian3[]} [positions] A linear ring defining the outer boundary of the polygon or hole.
   * @param {PolygonHierarchy[]} [holes] An array of polygon hierarchies defining holes in the polygon.
   */
  function PolygonHierarchy(positions, holes) {
    /**
     * A linear ring defining the outer boundary of the polygon or hole.
     * @type {Cartesian3[]}
     */
    this.positions = defined(positions) ? positions : [];

    /**
     * An array of polygon hierarchies defining holes in the polygon.
     * @type {PolygonHierarchy[]}
     */
    this.holes = defined(holes) ? holes : [];
  }

  const createGeometryFromPositionsPositions = [];
  const createGeometryFromPositionsSubdivided = [];

  function createGeometryFromPositions(
    ellipsoid,
    positions,
    minDistance,
    perPositionHeight,
    arcType
  ) {
    const tangentPlane = EllipsoidTangentPlane.fromPoints(positions, ellipsoid);
    const positions2D = tangentPlane.projectPointsOntoPlane(
      positions,
      createGeometryFromPositionsPositions
    );

    const originalWindingOrder = PolygonPipeline.computeWindingOrder2D(
      positions2D
    );
    if (originalWindingOrder === WindingOrder$1.CLOCKWISE) {
      positions2D.reverse();
      positions = positions.slice().reverse();
    }

    let subdividedPositions;
    let i;

    let length = positions.length;
    let index = 0;

    if (!perPositionHeight) {
      let numVertices = 0;
      if (arcType === ArcType$1.GEODESIC) {
        for (i = 0; i < length; i++) {
          numVertices += PolygonGeometryLibrary.subdivideLineCount(
            positions[i],
            positions[(i + 1) % length],
            minDistance
          );
        }
      } else if (arcType === ArcType$1.RHUMB) {
        for (i = 0; i < length; i++) {
          numVertices += PolygonGeometryLibrary.subdivideRhumbLineCount(
            ellipsoid,
            positions[i],
            positions[(i + 1) % length],
            minDistance
          );
        }
      }
      subdividedPositions = new Float64Array(numVertices * 3);
      for (i = 0; i < length; i++) {
        let tempPositions;
        if (arcType === ArcType$1.GEODESIC) {
          tempPositions = PolygonGeometryLibrary.subdivideLine(
            positions[i],
            positions[(i + 1) % length],
            minDistance,
            createGeometryFromPositionsSubdivided
          );
        } else if (arcType === ArcType$1.RHUMB) {
          tempPositions = PolygonGeometryLibrary.subdivideRhumbLine(
            ellipsoid,
            positions[i],
            positions[(i + 1) % length],
            minDistance,
            createGeometryFromPositionsSubdivided
          );
        }
        const tempPositionsLength = tempPositions.length;
        for (let j = 0; j < tempPositionsLength; ++j) {
          subdividedPositions[index++] = tempPositions[j];
        }
      }
    } else {
      subdividedPositions = new Float64Array(length * 2 * 3);
      for (i = 0; i < length; i++) {
        const p0 = positions[i];
        const p1 = positions[(i + 1) % length];
        subdividedPositions[index++] = p0.x;
        subdividedPositions[index++] = p0.y;
        subdividedPositions[index++] = p0.z;
        subdividedPositions[index++] = p1.x;
        subdividedPositions[index++] = p1.y;
        subdividedPositions[index++] = p1.z;
      }
    }

    length = subdividedPositions.length / 3;
    const indicesSize = length * 2;
    const indices = IndexDatatype$1.createTypedArray(length, indicesSize);
    index = 0;
    for (i = 0; i < length - 1; i++) {
      indices[index++] = i;
      indices[index++] = i + 1;
    }
    indices[index++] = length - 1;
    indices[index++] = 0;

    return new GeometryInstance({
      geometry: new Geometry({
        attributes: new GeometryAttributes({
          position: new GeometryAttribute({
            componentDatatype: ComponentDatatype$1.DOUBLE,
            componentsPerAttribute: 3,
            values: subdividedPositions,
          }),
        }),
        indices: indices,
        primitiveType: PrimitiveType$1.LINES,
      }),
    });
  }

  function createGeometryFromPositionsExtruded(
    ellipsoid,
    positions,
    minDistance,
    perPositionHeight,
    arcType
  ) {
    const tangentPlane = EllipsoidTangentPlane.fromPoints(positions, ellipsoid);
    const positions2D = tangentPlane.projectPointsOntoPlane(
      positions,
      createGeometryFromPositionsPositions
    );

    const originalWindingOrder = PolygonPipeline.computeWindingOrder2D(
      positions2D
    );
    if (originalWindingOrder === WindingOrder$1.CLOCKWISE) {
      positions2D.reverse();
      positions = positions.slice().reverse();
    }

    let subdividedPositions;
    let i;

    let length = positions.length;
    const corners = new Array(length);
    let index = 0;

    if (!perPositionHeight) {
      let numVertices = 0;
      if (arcType === ArcType$1.GEODESIC) {
        for (i = 0; i < length; i++) {
          numVertices += PolygonGeometryLibrary.subdivideLineCount(
            positions[i],
            positions[(i + 1) % length],
            minDistance
          );
        }
      } else if (arcType === ArcType$1.RHUMB) {
        for (i = 0; i < length; i++) {
          numVertices += PolygonGeometryLibrary.subdivideRhumbLineCount(
            ellipsoid,
            positions[i],
            positions[(i + 1) % length],
            minDistance
          );
        }
      }

      subdividedPositions = new Float64Array(numVertices * 3 * 2);
      for (i = 0; i < length; ++i) {
        corners[i] = index / 3;
        let tempPositions;
        if (arcType === ArcType$1.GEODESIC) {
          tempPositions = PolygonGeometryLibrary.subdivideLine(
            positions[i],
            positions[(i + 1) % length],
            minDistance,
            createGeometryFromPositionsSubdivided
          );
        } else if (arcType === ArcType$1.RHUMB) {
          tempPositions = PolygonGeometryLibrary.subdivideRhumbLine(
            ellipsoid,
            positions[i],
            positions[(i + 1) % length],
            minDistance,
            createGeometryFromPositionsSubdivided
          );
        }
        const tempPositionsLength = tempPositions.length;
        for (let j = 0; j < tempPositionsLength; ++j) {
          subdividedPositions[index++] = tempPositions[j];
        }
      }
    } else {
      subdividedPositions = new Float64Array(length * 2 * 3 * 2);
      for (i = 0; i < length; ++i) {
        corners[i] = index / 3;
        const p0 = positions[i];
        const p1 = positions[(i + 1) % length];

        subdividedPositions[index++] = p0.x;
        subdividedPositions[index++] = p0.y;
        subdividedPositions[index++] = p0.z;
        subdividedPositions[index++] = p1.x;
        subdividedPositions[index++] = p1.y;
        subdividedPositions[index++] = p1.z;
      }
    }

    length = subdividedPositions.length / (3 * 2);
    const cornersLength = corners.length;

    const indicesSize = (length * 2 + cornersLength) * 2;
    const indices = IndexDatatype$1.createTypedArray(
      length + cornersLength,
      indicesSize
    );

    index = 0;
    for (i = 0; i < length; ++i) {
      indices[index++] = i;
      indices[index++] = (i + 1) % length;
      indices[index++] = i + length;
      indices[index++] = ((i + 1) % length) + length;
    }

    for (i = 0; i < cornersLength; i++) {
      const corner = corners[i];
      indices[index++] = corner;
      indices[index++] = corner + length;
    }

    return new GeometryInstance({
      geometry: new Geometry({
        attributes: new GeometryAttributes({
          position: new GeometryAttribute({
            componentDatatype: ComponentDatatype$1.DOUBLE,
            componentsPerAttribute: 3,
            values: subdividedPositions,
          }),
        }),
        indices: indices,
        primitiveType: PrimitiveType$1.LINES,
      }),
    });
  }

  /**
   * A description of the outline of a polygon on the ellipsoid. The polygon is defined by a polygon hierarchy.
   *
   * @alias PolygonOutlineGeometry
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {PolygonHierarchy} options.polygonHierarchy A polygon hierarchy that can include holes.
   * @param {Number} [options.height=0.0] The distance in meters between the polygon and the ellipsoid surface.
   * @param {Number} [options.extrudedHeight] The distance in meters between the polygon's extruded face and the ellipsoid surface.
   * @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid to be used as a reference.
   * @param {Number} [options.granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
   * @param {Boolean} [options.perPositionHeight=false] Use the height of options.positions for each position instead of using options.height to determine the height.
   * @param {ArcType} [options.arcType=ArcType.GEODESIC] The type of path the outline must follow. Valid options are {@link ArcType.GEODESIC} and {@link ArcType.RHUMB}.
   *
   * @see PolygonOutlineGeometry#createGeometry
   * @see PolygonOutlineGeometry#fromPositions
   *
   * @example
   * // 1. create a polygon outline from points
   * const polygon = new Cesium.PolygonOutlineGeometry({
   *   polygonHierarchy : new Cesium.PolygonHierarchy(
   *     Cesium.Cartesian3.fromDegreesArray([
   *       -72.0, 40.0,
   *       -70.0, 35.0,
   *       -75.0, 30.0,
   *       -70.0, 30.0,
   *       -68.0, 40.0
   *     ])
   *   )
   * });
   * const geometry = Cesium.PolygonOutlineGeometry.createGeometry(polygon);
   *
   * // 2. create a nested polygon with holes outline
   * const polygonWithHole = new Cesium.PolygonOutlineGeometry({
   *   polygonHierarchy : new Cesium.PolygonHierarchy(
   *     Cesium.Cartesian3.fromDegreesArray([
   *       -109.0, 30.0,
   *       -95.0, 30.0,
   *       -95.0, 40.0,
   *       -109.0, 40.0
   *     ]),
   *     [new Cesium.PolygonHierarchy(
   *       Cesium.Cartesian3.fromDegreesArray([
   *         -107.0, 31.0,
   *         -107.0, 39.0,
   *         -97.0, 39.0,
   *         -97.0, 31.0
   *       ]),
   *       [new Cesium.PolygonHierarchy(
   *         Cesium.Cartesian3.fromDegreesArray([
   *           -105.0, 33.0,
   *           -99.0, 33.0,
   *           -99.0, 37.0,
   *           -105.0, 37.0
   *         ]),
   *         [new Cesium.PolygonHierarchy(
   *           Cesium.Cartesian3.fromDegreesArray([
   *             -103.0, 34.0,
   *             -101.0, 34.0,
   *             -101.0, 36.0,
   *             -103.0, 36.0
   *           ])
   *         )]
   *       )]
   *     )]
   *   )
   * });
   * const geometry = Cesium.PolygonOutlineGeometry.createGeometry(polygonWithHole);
   *
   * // 3. create extruded polygon outline
   * const extrudedPolygon = new Cesium.PolygonOutlineGeometry({
   *   polygonHierarchy : new Cesium.PolygonHierarchy(
   *     Cesium.Cartesian3.fromDegreesArray([
   *       -72.0, 40.0,
   *       -70.0, 35.0,
   *       -75.0, 30.0,
   *       -70.0, 30.0,
   *       -68.0, 40.0
   *     ])
   *   ),
   *   extrudedHeight: 300000
   * });
   * const geometry = Cesium.PolygonOutlineGeometry.createGeometry(extrudedPolygon);
   */
  function PolygonOutlineGeometry(options) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options", options);
    Check.typeOf.object("options.polygonHierarchy", options.polygonHierarchy);

    if (options.perPositionHeight && defined(options.height)) {
      throw new DeveloperError(
        "Cannot use both options.perPositionHeight and options.height"
      );
    }
    if (
      defined(options.arcType) &&
      options.arcType !== ArcType$1.GEODESIC &&
      options.arcType !== ArcType$1.RHUMB
    ) {
      throw new DeveloperError(
        "Invalid arcType. Valid options are ArcType.GEODESIC and ArcType.RHUMB."
      );
    }
    //>>includeEnd('debug');

    const polygonHierarchy = options.polygonHierarchy;
    const ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);
    const granularity = defaultValue(
      options.granularity,
      CesiumMath.RADIANS_PER_DEGREE
    );
    const perPositionHeight = defaultValue(options.perPositionHeight, false);
    const perPositionHeightExtrude =
      perPositionHeight && defined(options.extrudedHeight);
    const arcType = defaultValue(options.arcType, ArcType$1.GEODESIC);

    let height = defaultValue(options.height, 0.0);
    let extrudedHeight = defaultValue(options.extrudedHeight, height);

    if (!perPositionHeightExtrude) {
      const h = Math.max(height, extrudedHeight);
      extrudedHeight = Math.min(height, extrudedHeight);
      height = h;
    }

    this._ellipsoid = Ellipsoid.clone(ellipsoid);
    this._granularity = granularity;
    this._height = height;
    this._extrudedHeight = extrudedHeight;
    this._arcType = arcType;
    this._polygonHierarchy = polygonHierarchy;
    this._perPositionHeight = perPositionHeight;
    this._perPositionHeightExtrude = perPositionHeightExtrude;
    this._offsetAttribute = options.offsetAttribute;
    this._workerName = "createPolygonOutlineGeometry";

    /**
     * The number of elements used to pack the object into an array.
     * @type {Number}
     */
    this.packedLength =
      PolygonGeometryLibrary.computeHierarchyPackedLength(
        polygonHierarchy,
        Cartesian3
      ) +
      Ellipsoid.packedLength +
      8;
  }

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {PolygonOutlineGeometry} 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
   */
  PolygonOutlineGeometry.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    startingIndex = PolygonGeometryLibrary.packPolygonHierarchy(
      value._polygonHierarchy,
      array,
      startingIndex,
      Cartesian3
    );

    Ellipsoid.pack(value._ellipsoid, array, startingIndex);
    startingIndex += Ellipsoid.packedLength;

    array[startingIndex++] = value._height;
    array[startingIndex++] = value._extrudedHeight;
    array[startingIndex++] = value._granularity;
    array[startingIndex++] = value._perPositionHeightExtrude ? 1.0 : 0.0;
    array[startingIndex++] = value._perPositionHeight ? 1.0 : 0.0;
    array[startingIndex++] = value._arcType;
    array[startingIndex++] = defaultValue(value._offsetAttribute, -1);
    array[startingIndex] = value.packedLength;

    return array;
  };

  const scratchEllipsoid$8 = Ellipsoid.clone(Ellipsoid.UNIT_SPHERE);
  const dummyOptions = {
    polygonHierarchy: {},
  };

  /**
   * 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 {PolygonOutlineGeometry} [result] The object into which to store the result.
   * @returns {PolygonOutlineGeometry} The modified result parameter or a new PolygonOutlineGeometry instance if one was not provided.
   */
  PolygonOutlineGeometry.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    const polygonHierarchy = PolygonGeometryLibrary.unpackPolygonHierarchy(
      array,
      startingIndex,
      Cartesian3
    );
    startingIndex = polygonHierarchy.startingIndex;
    delete polygonHierarchy.startingIndex;

    const ellipsoid = Ellipsoid.unpack(array, startingIndex, scratchEllipsoid$8);
    startingIndex += Ellipsoid.packedLength;

    const height = array[startingIndex++];
    const extrudedHeight = array[startingIndex++];
    const granularity = array[startingIndex++];
    const perPositionHeightExtrude = array[startingIndex++] === 1.0;
    const perPositionHeight = array[startingIndex++] === 1.0;
    const arcType = array[startingIndex++];
    const offsetAttribute = array[startingIndex++];
    const packedLength = array[startingIndex];

    if (!defined(result)) {
      result = new PolygonOutlineGeometry(dummyOptions);
    }

    result._polygonHierarchy = polygonHierarchy;
    result._ellipsoid = Ellipsoid.clone(ellipsoid, result._ellipsoid);
    result._height = height;
    result._extrudedHeight = extrudedHeight;
    result._granularity = granularity;
    result._perPositionHeight = perPositionHeight;
    result._perPositionHeightExtrude = perPositionHeightExtrude;
    result._arcType = arcType;
    result._offsetAttribute =
      offsetAttribute === -1 ? undefined : offsetAttribute;
    result.packedLength = packedLength;

    return result;
  };

  /**
   * A description of a polygon outline from an array of positions.
   *
   * @param {Object} options Object with the following properties:
   * @param {Cartesian3[]} options.positions An array of positions that defined the corner points of the polygon.
   * @param {Number} [options.height=0.0] The height of the polygon.
   * @param {Number} [options.extrudedHeight] The height of the polygon extrusion.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid to be used as a reference.
   * @param {Number} [options.granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
   * @param {Boolean} [options.perPositionHeight=false] Use the height of options.positions for each position instead of using options.height to determine the height.
   * @param {ArcType} [options.arcType=ArcType.GEODESIC] The type of path the outline must follow. Valid options are {@link LinkType.GEODESIC} and {@link ArcType.RHUMB}.
   * @returns {PolygonOutlineGeometry}
   *
   *
   * @example
   * // create a polygon from points
   * const polygon = Cesium.PolygonOutlineGeometry.fromPositions({
   *   positions : Cesium.Cartesian3.fromDegreesArray([
   *     -72.0, 40.0,
   *     -70.0, 35.0,
   *     -75.0, 30.0,
   *     -70.0, 30.0,
   *     -68.0, 40.0
   *   ])
   * });
   * const geometry = Cesium.PolygonOutlineGeometry.createGeometry(polygon);
   *
   * @see PolygonOutlineGeometry#createGeometry
   */
  PolygonOutlineGeometry.fromPositions = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    Check.defined("options.positions", options.positions);
    //>>includeEnd('debug');

    const newOptions = {
      polygonHierarchy: {
        positions: options.positions,
      },
      height: options.height,
      extrudedHeight: options.extrudedHeight,
      ellipsoid: options.ellipsoid,
      granularity: options.granularity,
      perPositionHeight: options.perPositionHeight,
      arcType: options.arcType,
      offsetAttribute: options.offsetAttribute,
    };
    return new PolygonOutlineGeometry(newOptions);
  };

  /**
   * Computes the geometric representation of a polygon outline, including its vertices, indices, and a bounding sphere.
   *
   * @param {PolygonOutlineGeometry} polygonGeometry A description of the polygon outline.
   * @returns {Geometry|undefined} The computed vertices and indices.
   */
  PolygonOutlineGeometry.createGeometry = function (polygonGeometry) {
    const ellipsoid = polygonGeometry._ellipsoid;
    const granularity = polygonGeometry._granularity;
    const polygonHierarchy = polygonGeometry._polygonHierarchy;
    const perPositionHeight = polygonGeometry._perPositionHeight;
    const arcType = polygonGeometry._arcType;

    const polygons = PolygonGeometryLibrary.polygonOutlinesFromHierarchy(
      polygonHierarchy,
      !perPositionHeight,
      ellipsoid
    );

    if (polygons.length === 0) {
      return undefined;
    }

    let geometryInstance;
    const geometries = [];
    const minDistance = CesiumMath.chordLength(
      granularity,
      ellipsoid.maximumRadius
    );

    const height = polygonGeometry._height;
    const extrudedHeight = polygonGeometry._extrudedHeight;
    const extrude =
      polygonGeometry._perPositionHeightExtrude ||
      !CesiumMath.equalsEpsilon(height, extrudedHeight, 0, CesiumMath.EPSILON2);
    let offsetValue;
    let i;
    if (extrude) {
      for (i = 0; i < polygons.length; i++) {
        geometryInstance = createGeometryFromPositionsExtruded(
          ellipsoid,
          polygons[i],
          minDistance,
          perPositionHeight,
          arcType
        );
        geometryInstance.geometry = PolygonGeometryLibrary.scaleToGeodeticHeightExtruded(
          geometryInstance.geometry,
          height,
          extrudedHeight,
          ellipsoid,
          perPositionHeight
        );
        if (defined(polygonGeometry._offsetAttribute)) {
          const size =
            geometryInstance.geometry.attributes.position.values.length / 3;
          let offsetAttribute = new Uint8Array(size);
          if (polygonGeometry._offsetAttribute === GeometryOffsetAttribute$1.TOP) {
            offsetAttribute = offsetAttribute.fill(1, 0, size / 2);
          } else {
            offsetValue =
              polygonGeometry._offsetAttribute === GeometryOffsetAttribute$1.NONE
                ? 0
                : 1;
            offsetAttribute = offsetAttribute.fill(offsetValue);
          }

          geometryInstance.geometry.attributes.applyOffset = new GeometryAttribute(
            {
              componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
              componentsPerAttribute: 1,
              values: offsetAttribute,
            }
          );
        }
        geometries.push(geometryInstance);
      }
    } else {
      for (i = 0; i < polygons.length; i++) {
        geometryInstance = createGeometryFromPositions(
          ellipsoid,
          polygons[i],
          minDistance,
          perPositionHeight,
          arcType
        );
        geometryInstance.geometry.attributes.position.values = PolygonPipeline.scaleToGeodeticHeight(
          geometryInstance.geometry.attributes.position.values,
          height,
          ellipsoid,
          !perPositionHeight
        );

        if (defined(polygonGeometry._offsetAttribute)) {
          const length =
            geometryInstance.geometry.attributes.position.values.length;
          offsetValue =
            polygonGeometry._offsetAttribute === GeometryOffsetAttribute$1.NONE
              ? 0
              : 1;
          const applyOffset = new Uint8Array(length / 3).fill(offsetValue);
          geometryInstance.geometry.attributes.applyOffset = new GeometryAttribute(
            {
              componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
              componentsPerAttribute: 1,
              values: applyOffset,
            }
          );
        }

        geometries.push(geometryInstance);
      }
    }

    const geometry = GeometryPipeline.combineInstances(geometries)[0];
    const boundingSphere = BoundingSphere.fromVertices(
      geometry.attributes.position.values
    );

    return new Geometry({
      attributes: geometry.attributes,
      indices: geometry.indices,
      primitiveType: geometry.primitiveType,
      boundingSphere: boundingSphere,
      offsetAttribute: polygonGeometry._offsetAttribute,
    });
  };

  const scratchInterpolateColorsArray = [];

  function interpolateColors$1(p0, p1, color0, color1, numPoints) {
    const colors = scratchInterpolateColorsArray;
    colors.length = numPoints;
    let i;

    const r0 = color0.red;
    const g0 = color0.green;
    const b0 = color0.blue;
    const a0 = color0.alpha;

    const r1 = color1.red;
    const g1 = color1.green;
    const b1 = color1.blue;
    const a1 = color1.alpha;

    if (Color.equals(color0, color1)) {
      for (i = 0; i < numPoints; i++) {
        colors[i] = Color.clone(color0);
      }
      return colors;
    }

    const redPerVertex = (r1 - r0) / numPoints;
    const greenPerVertex = (g1 - g0) / numPoints;
    const bluePerVertex = (b1 - b0) / numPoints;
    const alphaPerVertex = (a1 - a0) / numPoints;

    for (i = 0; i < numPoints; i++) {
      colors[i] = new Color(
        r0 + i * redPerVertex,
        g0 + i * greenPerVertex,
        b0 + i * bluePerVertex,
        a0 + i * alphaPerVertex
      );
    }

    return colors;
  }

  /**
   * A description of a polyline modeled as a line strip; the first two positions define a line segment,
   * and each additional position defines a line segment from the previous position. The polyline is capable of
   * displaying with a material.
   *
   * @alias PolylineGeometry
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Cartesian3[]} options.positions An array of {@link Cartesian3} defining the positions in the polyline as a line strip.
   * @param {Number} [options.width=1.0] The width in pixels.
   * @param {Color[]} [options.colors] An Array of {@link Color} defining the per vertex or per segment colors.
   * @param {Boolean} [options.colorsPerVertex=false] A boolean that determines whether the colors will be flat across each segment of the line or interpolated across the vertices.
   * @param {ArcType} [options.arcType=ArcType.GEODESIC] The type of line the polyline segments must follow.
   * @param {Number} [options.granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude if options.arcType is not ArcType.NONE. Determines the number of positions in the buffer.
   * @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid to be used as a reference.
   *
   * @exception {DeveloperError} At least two positions are required.
   * @exception {DeveloperError} width must be greater than or equal to one.
   * @exception {DeveloperError} colors has an invalid length.
   *
   * @see PolylineGeometry#createGeometry
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Polyline.html|Cesium Sandcastle Polyline Demo}
   *
   * @example
   * // A polyline with two connected line segments
   * const polyline = new Cesium.PolylineGeometry({
   *   positions : Cesium.Cartesian3.fromDegreesArray([
   *     0.0, 0.0,
   *     5.0, 0.0,
   *     5.0, 5.0
   *   ]),
   *   width : 10.0
   * });
   * const geometry = Cesium.PolylineGeometry.createGeometry(polyline);
   */
  function PolylineGeometry(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const positions = options.positions;
    const colors = options.colors;
    const width = defaultValue(options.width, 1.0);
    const colorsPerVertex = defaultValue(options.colorsPerVertex, false);

    //>>includeStart('debug', pragmas.debug);
    if (!defined(positions) || positions.length < 2) {
      throw new DeveloperError("At least two positions are required.");
    }
    if (typeof width !== "number") {
      throw new DeveloperError("width must be a number");
    }
    if (
      defined(colors) &&
      ((colorsPerVertex && colors.length < positions.length) ||
        (!colorsPerVertex && colors.length < positions.length - 1))
    ) {
      throw new DeveloperError("colors has an invalid length.");
    }
    //>>includeEnd('debug');

    this._positions = positions;
    this._colors = colors;
    this._width = width;
    this._colorsPerVertex = colorsPerVertex;
    this._vertexFormat = VertexFormat.clone(
      defaultValue(options.vertexFormat, VertexFormat.DEFAULT)
    );

    this._arcType = defaultValue(options.arcType, ArcType$1.GEODESIC);
    this._granularity = defaultValue(
      options.granularity,
      CesiumMath.RADIANS_PER_DEGREE
    );
    this._ellipsoid = Ellipsoid.clone(
      defaultValue(options.ellipsoid, Ellipsoid.WGS84)
    );
    this._workerName = "createPolylineGeometry";

    let numComponents = 1 + positions.length * Cartesian3.packedLength;
    numComponents += defined(colors) ? 1 + colors.length * Color.packedLength : 1;

    /**
     * The number of elements used to pack the object into an array.
     * @type {Number}
     */
    this.packedLength =
      numComponents + Ellipsoid.packedLength + VertexFormat.packedLength + 4;
  }

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {PolylineGeometry} 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
   */
  PolylineGeometry.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(value)) {
      throw new DeveloperError("value is required");
    }
    if (!defined(array)) {
      throw new DeveloperError("array is required");
    }
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    let i;

    const positions = value._positions;
    let length = positions.length;
    array[startingIndex++] = length;

    for (i = 0; i < length; ++i, startingIndex += Cartesian3.packedLength) {
      Cartesian3.pack(positions[i], array, startingIndex);
    }

    const colors = value._colors;
    length = defined(colors) ? colors.length : 0.0;
    array[startingIndex++] = length;

    for (i = 0; i < length; ++i, startingIndex += Color.packedLength) {
      Color.pack(colors[i], array, startingIndex);
    }

    Ellipsoid.pack(value._ellipsoid, array, startingIndex);
    startingIndex += Ellipsoid.packedLength;

    VertexFormat.pack(value._vertexFormat, array, startingIndex);
    startingIndex += VertexFormat.packedLength;

    array[startingIndex++] = value._width;
    array[startingIndex++] = value._colorsPerVertex ? 1.0 : 0.0;
    array[startingIndex++] = value._arcType;
    array[startingIndex] = value._granularity;

    return array;
  };

  const scratchEllipsoid$7 = Ellipsoid.clone(Ellipsoid.UNIT_SPHERE);
  const scratchVertexFormat$3 = new VertexFormat();
  const scratchOptions$8 = {
    positions: undefined,
    colors: undefined,
    ellipsoid: scratchEllipsoid$7,
    vertexFormat: scratchVertexFormat$3,
    width: undefined,
    colorsPerVertex: undefined,
    arcType: undefined,
    granularity: undefined,
  };

  /**
   * 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 {PolylineGeometry} [result] The object into which to store the result.
   * @returns {PolylineGeometry} The modified result parameter or a new PolylineGeometry instance if one was not provided.
   */
  PolylineGeometry.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(array)) {
      throw new DeveloperError("array is required");
    }
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    let i;

    let length = array[startingIndex++];
    const positions = new Array(length);

    for (i = 0; i < length; ++i, startingIndex += Cartesian3.packedLength) {
      positions[i] = Cartesian3.unpack(array, startingIndex);
    }

    length = array[startingIndex++];
    const colors = length > 0 ? new Array(length) : undefined;

    for (i = 0; i < length; ++i, startingIndex += Color.packedLength) {
      colors[i] = Color.unpack(array, startingIndex);
    }

    const ellipsoid = Ellipsoid.unpack(array, startingIndex, scratchEllipsoid$7);
    startingIndex += Ellipsoid.packedLength;

    const vertexFormat = VertexFormat.unpack(
      array,
      startingIndex,
      scratchVertexFormat$3
    );
    startingIndex += VertexFormat.packedLength;

    const width = array[startingIndex++];
    const colorsPerVertex = array[startingIndex++] === 1.0;
    const arcType = array[startingIndex++];
    const granularity = array[startingIndex];

    if (!defined(result)) {
      scratchOptions$8.positions = positions;
      scratchOptions$8.colors = colors;
      scratchOptions$8.width = width;
      scratchOptions$8.colorsPerVertex = colorsPerVertex;
      scratchOptions$8.arcType = arcType;
      scratchOptions$8.granularity = granularity;
      return new PolylineGeometry(scratchOptions$8);
    }

    result._positions = positions;
    result._colors = colors;
    result._ellipsoid = Ellipsoid.clone(ellipsoid, result._ellipsoid);
    result._vertexFormat = VertexFormat.clone(vertexFormat, result._vertexFormat);
    result._width = width;
    result._colorsPerVertex = colorsPerVertex;
    result._arcType = arcType;
    result._granularity = granularity;

    return result;
  };

  const scratchCartesian3$5 = new Cartesian3();
  const scratchPosition$b = new Cartesian3();
  const scratchPrevPosition = new Cartesian3();
  const scratchNextPosition = new Cartesian3();

  /**
   * Computes the geometric representation of a polyline, including its vertices, indices, and a bounding sphere.
   *
   * @param {PolylineGeometry} polylineGeometry A description of the polyline.
   * @returns {Geometry|undefined} The computed vertices and indices.
   */
  PolylineGeometry.createGeometry = function (polylineGeometry) {
    const width = polylineGeometry._width;
    const vertexFormat = polylineGeometry._vertexFormat;
    let colors = polylineGeometry._colors;
    const colorsPerVertex = polylineGeometry._colorsPerVertex;
    const arcType = polylineGeometry._arcType;
    const granularity = polylineGeometry._granularity;
    const ellipsoid = polylineGeometry._ellipsoid;

    let i;
    let j;
    let k;

    const removedIndices = [];
    let positions = arrayRemoveDuplicates(
      polylineGeometry._positions,
      Cartesian3.equalsEpsilon,
      false,
      removedIndices
    );

    if (defined(colors) && removedIndices.length > 0) {
      let removedArrayIndex = 0;
      let nextRemovedIndex = removedIndices[0];
      colors = colors.filter(function (color, index) {
        let remove = false;
        if (colorsPerVertex) {
          remove =
            index === nextRemovedIndex || (index === 0 && nextRemovedIndex === 1);
        } else {
          remove = index + 1 === nextRemovedIndex;
        }

        if (remove) {
          removedArrayIndex++;
          nextRemovedIndex = removedIndices[removedArrayIndex];
          return false;
        }
        return true;
      });
    }

    let positionsLength = positions.length;

    // A width of a pixel or less is not a valid geometry, but in order to support external data
    // that may have errors we treat this as an empty geometry.
    if (positionsLength < 2 || width <= 0.0) {
      return undefined;
    }

    if (arcType === ArcType$1.GEODESIC || arcType === ArcType$1.RHUMB) {
      let subdivisionSize;
      let numberOfPointsFunction;
      if (arcType === ArcType$1.GEODESIC) {
        subdivisionSize = CesiumMath.chordLength(
          granularity,
          ellipsoid.maximumRadius
        );
        numberOfPointsFunction = PolylinePipeline.numberOfPoints;
      } else {
        subdivisionSize = granularity;
        numberOfPointsFunction = PolylinePipeline.numberOfPointsRhumbLine;
      }

      const heights = PolylinePipeline.extractHeights(positions, ellipsoid);

      if (defined(colors)) {
        let colorLength = 1;
        for (i = 0; i < positionsLength - 1; ++i) {
          colorLength += numberOfPointsFunction(
            positions[i],
            positions[i + 1],
            subdivisionSize
          );
        }

        const newColors = new Array(colorLength);
        let newColorIndex = 0;

        for (i = 0; i < positionsLength - 1; ++i) {
          const p0 = positions[i];
          const p1 = positions[i + 1];
          const c0 = colors[i];

          const numColors = numberOfPointsFunction(p0, p1, subdivisionSize);
          if (colorsPerVertex && i < colorLength) {
            const c1 = colors[i + 1];
            const interpolatedColors = interpolateColors$1(
              p0,
              p1,
              c0,
              c1,
              numColors
            );
            const interpolatedColorsLength = interpolatedColors.length;
            for (j = 0; j < interpolatedColorsLength; ++j) {
              newColors[newColorIndex++] = interpolatedColors[j];
            }
          } else {
            for (j = 0; j < numColors; ++j) {
              newColors[newColorIndex++] = Color.clone(c0);
            }
          }
        }

        newColors[newColorIndex] = Color.clone(colors[colors.length - 1]);
        colors = newColors;

        scratchInterpolateColorsArray.length = 0;
      }

      if (arcType === ArcType$1.GEODESIC) {
        positions = PolylinePipeline.generateCartesianArc({
          positions: positions,
          minDistance: subdivisionSize,
          ellipsoid: ellipsoid,
          height: heights,
        });
      } else {
        positions = PolylinePipeline.generateCartesianRhumbArc({
          positions: positions,
          granularity: subdivisionSize,
          ellipsoid: ellipsoid,
          height: heights,
        });
      }
    }

    positionsLength = positions.length;
    const size = positionsLength * 4.0 - 4.0;

    const finalPositions = new Float64Array(size * 3);
    const prevPositions = new Float64Array(size * 3);
    const nextPositions = new Float64Array(size * 3);
    const expandAndWidth = new Float32Array(size * 2);
    const st = vertexFormat.st ? new Float32Array(size * 2) : undefined;
    const finalColors = defined(colors) ? new Uint8Array(size * 4) : undefined;

    let positionIndex = 0;
    let expandAndWidthIndex = 0;
    let stIndex = 0;
    let colorIndex = 0;
    let position;

    for (j = 0; j < positionsLength; ++j) {
      if (j === 0) {
        position = scratchCartesian3$5;
        Cartesian3.subtract(positions[0], positions[1], position);
        Cartesian3.add(positions[0], position, position);
      } else {
        position = positions[j - 1];
      }

      Cartesian3.clone(position, scratchPrevPosition);
      Cartesian3.clone(positions[j], scratchPosition$b);

      if (j === positionsLength - 1) {
        position = scratchCartesian3$5;
        Cartesian3.subtract(
          positions[positionsLength - 1],
          positions[positionsLength - 2],
          position
        );
        Cartesian3.add(positions[positionsLength - 1], position, position);
      } else {
        position = positions[j + 1];
      }

      Cartesian3.clone(position, scratchNextPosition);

      let color0, color1;
      if (defined(finalColors)) {
        if (j !== 0 && !colorsPerVertex) {
          color0 = colors[j - 1];
        } else {
          color0 = colors[j];
        }

        if (j !== positionsLength - 1) {
          color1 = colors[j];
        }
      }

      const startK = j === 0 ? 2 : 0;
      const endK = j === positionsLength - 1 ? 2 : 4;

      for (k = startK; k < endK; ++k) {
        Cartesian3.pack(scratchPosition$b, finalPositions, positionIndex);
        Cartesian3.pack(scratchPrevPosition, prevPositions, positionIndex);
        Cartesian3.pack(scratchNextPosition, nextPositions, positionIndex);
        positionIndex += 3;

        const direction = k - 2 < 0 ? -1.0 : 1.0;
        expandAndWidth[expandAndWidthIndex++] = 2 * (k % 2) - 1; // expand direction
        expandAndWidth[expandAndWidthIndex++] = direction * width;

        if (vertexFormat.st) {
          st[stIndex++] = j / (positionsLength - 1);
          st[stIndex++] = Math.max(expandAndWidth[expandAndWidthIndex - 2], 0.0);
        }

        if (defined(finalColors)) {
          const color = k < 2 ? color0 : color1;

          finalColors[colorIndex++] = Color.floatToByte(color.red);
          finalColors[colorIndex++] = Color.floatToByte(color.green);
          finalColors[colorIndex++] = Color.floatToByte(color.blue);
          finalColors[colorIndex++] = Color.floatToByte(color.alpha);
        }
      }
    }

    const attributes = new GeometryAttributes();

    attributes.position = new GeometryAttribute({
      componentDatatype: ComponentDatatype$1.DOUBLE,
      componentsPerAttribute: 3,
      values: finalPositions,
    });

    attributes.prevPosition = new GeometryAttribute({
      componentDatatype: ComponentDatatype$1.DOUBLE,
      componentsPerAttribute: 3,
      values: prevPositions,
    });

    attributes.nextPosition = new GeometryAttribute({
      componentDatatype: ComponentDatatype$1.DOUBLE,
      componentsPerAttribute: 3,
      values: nextPositions,
    });

    attributes.expandAndWidth = new GeometryAttribute({
      componentDatatype: ComponentDatatype$1.FLOAT,
      componentsPerAttribute: 2,
      values: expandAndWidth,
    });

    if (vertexFormat.st) {
      attributes.st = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 2,
        values: st,
      });
    }

    if (defined(finalColors)) {
      attributes.color = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
        componentsPerAttribute: 4,
        values: finalColors,
        normalize: true,
      });
    }

    const indices = IndexDatatype$1.createTypedArray(size, positionsLength * 6 - 6);
    let index = 0;
    let indicesIndex = 0;
    const length = positionsLength - 1.0;
    for (j = 0; j < length; ++j) {
      indices[indicesIndex++] = index;
      indices[indicesIndex++] = index + 2;
      indices[indicesIndex++] = index + 1;

      indices[indicesIndex++] = index + 1;
      indices[indicesIndex++] = index + 2;
      indices[indicesIndex++] = index + 3;

      index += 4;
    }

    return new Geometry({
      attributes: attributes,
      indices: indices,
      primitiveType: PrimitiveType$1.TRIANGLES,
      boundingSphere: BoundingSphere.fromPoints(positions),
      geometryType: GeometryType$1.POLYLINES,
    });
  };

  function computeAttributes$1(
    combinedPositions,
    shape,
    boundingRectangle,
    vertexFormat
  ) {
    const attributes = new GeometryAttributes();
    if (vertexFormat.position) {
      attributes.position = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.DOUBLE,
        componentsPerAttribute: 3,
        values: combinedPositions,
      });
    }
    const shapeLength = shape.length;
    const vertexCount = combinedPositions.length / 3;
    const length = (vertexCount - shapeLength * 2) / (shapeLength * 2);
    const firstEndIndices = PolygonPipeline.triangulate(shape);

    const indicesCount =
      (length - 1) * shapeLength * 6 + firstEndIndices.length * 2;
    const indices = IndexDatatype$1.createTypedArray(vertexCount, indicesCount);
    let i, j;
    let ll, ul, ur, lr;
    const offset = shapeLength * 2;
    let index = 0;
    for (i = 0; i < length - 1; i++) {
      for (j = 0; j < shapeLength - 1; j++) {
        ll = j * 2 + i * shapeLength * 2;
        lr = ll + offset;
        ul = ll + 1;
        ur = ul + offset;

        indices[index++] = ul;
        indices[index++] = ll;
        indices[index++] = ur;
        indices[index++] = ur;
        indices[index++] = ll;
        indices[index++] = lr;
      }
      ll = shapeLength * 2 - 2 + i * shapeLength * 2;
      ul = ll + 1;
      ur = ul + offset;
      lr = ll + offset;

      indices[index++] = ul;
      indices[index++] = ll;
      indices[index++] = ur;
      indices[index++] = ur;
      indices[index++] = ll;
      indices[index++] = lr;
    }

    if (vertexFormat.st || vertexFormat.tangent || vertexFormat.bitangent) {
      // st required for tangent/bitangent calculation
      const st = new Float32Array(vertexCount * 2);
      const lengthSt = 1 / (length - 1);
      const heightSt = 1 / boundingRectangle.height;
      const heightOffset = boundingRectangle.height / 2;
      let s, t;
      let stindex = 0;
      for (i = 0; i < length; i++) {
        s = i * lengthSt;
        t = heightSt * (shape[0].y + heightOffset);
        st[stindex++] = s;
        st[stindex++] = t;
        for (j = 1; j < shapeLength; j++) {
          t = heightSt * (shape[j].y + heightOffset);
          st[stindex++] = s;
          st[stindex++] = t;
          st[stindex++] = s;
          st[stindex++] = t;
        }
        t = heightSt * (shape[0].y + heightOffset);
        st[stindex++] = s;
        st[stindex++] = t;
      }
      for (j = 0; j < shapeLength; j++) {
        s = 0;
        t = heightSt * (shape[j].y + heightOffset);
        st[stindex++] = s;
        st[stindex++] = t;
      }
      for (j = 0; j < shapeLength; j++) {
        s = (length - 1) * lengthSt;
        t = heightSt * (shape[j].y + heightOffset);
        st[stindex++] = s;
        st[stindex++] = t;
      }

      attributes.st = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 2,
        values: new Float32Array(st),
      });
    }

    const endOffset = vertexCount - shapeLength * 2;
    for (i = 0; i < firstEndIndices.length; i += 3) {
      const v0 = firstEndIndices[i] + endOffset;
      const v1 = firstEndIndices[i + 1] + endOffset;
      const v2 = firstEndIndices[i + 2] + endOffset;

      indices[index++] = v0;
      indices[index++] = v1;
      indices[index++] = v2;
      indices[index++] = v2 + shapeLength;
      indices[index++] = v1 + shapeLength;
      indices[index++] = v0 + shapeLength;
    }

    let geometry = new Geometry({
      attributes: attributes,
      indices: indices,
      boundingSphere: BoundingSphere.fromVertices(combinedPositions),
      primitiveType: PrimitiveType$1.TRIANGLES,
    });

    if (vertexFormat.normal) {
      geometry = GeometryPipeline.computeNormal(geometry);
    }

    if (vertexFormat.tangent || vertexFormat.bitangent) {
      try {
        geometry = GeometryPipeline.computeTangentAndBitangent(geometry);
      } catch (e) {
        oneTimeWarning(
          "polyline-volume-tangent-bitangent",
          "Unable to compute tangents and bitangents for polyline volume geometry"
        );
        //TODO https://github.com/CesiumGS/cesium/issues/3609
      }

      if (!vertexFormat.tangent) {
        geometry.attributes.tangent = undefined;
      }
      if (!vertexFormat.bitangent) {
        geometry.attributes.bitangent = undefined;
      }
      if (!vertexFormat.st) {
        geometry.attributes.st = undefined;
      }
    }

    return geometry;
  }

  /**
   * A description of a polyline with a volume (a 2D shape extruded along a polyline).
   *
   * @alias PolylineVolumeGeometry
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Cartesian3[]} options.polylinePositions An array of {@link Cartesian3} positions that define the center of the polyline volume.
   * @param {Cartesian2[]} options.shapePositions An array of {@link Cartesian2} positions that define the shape to be extruded along the polyline
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid to be used as a reference.
   * @param {Number} [options.granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
   * @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
   * @param {CornerType} [options.cornerType=CornerType.ROUNDED] Determines the style of the corners.
   *
   * @see PolylineVolumeGeometry#createGeometry
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Polyline%20Volume.html|Cesium Sandcastle Polyline Volume Demo}
   *
   * @example
   * function computeCircle(radius) {
   *   const positions = [];
   *   for (let i = 0; i < 360; i++) {
   *     const radians = Cesium.Math.toRadians(i);
   *     positions.push(new Cesium.Cartesian2(radius * Math.cos(radians), radius * Math.sin(radians)));
   *   }
   *   return positions;
   * }
   *
   * const volume = new Cesium.PolylineVolumeGeometry({
   *   vertexFormat : Cesium.VertexFormat.POSITION_ONLY,
   *   polylinePositions : Cesium.Cartesian3.fromDegreesArray([
   *     -72.0, 40.0,
   *     -70.0, 35.0
   *   ]),
   *   shapePositions : computeCircle(100000.0)
   * });
   */
  function PolylineVolumeGeometry(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const positions = options.polylinePositions;
    const shape = options.shapePositions;

    //>>includeStart('debug', pragmas.debug);
    if (!defined(positions)) {
      throw new DeveloperError("options.polylinePositions is required.");
    }
    if (!defined(shape)) {
      throw new DeveloperError("options.shapePositions is required.");
    }
    //>>includeEnd('debug');

    this._positions = positions;
    this._shape = shape;
    this._ellipsoid = Ellipsoid.clone(
      defaultValue(options.ellipsoid, Ellipsoid.WGS84)
    );
    this._cornerType = defaultValue(options.cornerType, CornerType$1.ROUNDED);
    this._vertexFormat = VertexFormat.clone(
      defaultValue(options.vertexFormat, VertexFormat.DEFAULT)
    );
    this._granularity = defaultValue(
      options.granularity,
      CesiumMath.RADIANS_PER_DEGREE
    );
    this._workerName = "createPolylineVolumeGeometry";

    let numComponents = 1 + positions.length * Cartesian3.packedLength;
    numComponents += 1 + shape.length * Cartesian2.packedLength;

    /**
     * The number of elements used to pack the object into an array.
     * @type {Number}
     */
    this.packedLength =
      numComponents + Ellipsoid.packedLength + VertexFormat.packedLength + 2;
  }

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {PolylineVolumeGeometry} 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
   */
  PolylineVolumeGeometry.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(value)) {
      throw new DeveloperError("value is required");
    }
    if (!defined(array)) {
      throw new DeveloperError("array is required");
    }
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    let i;

    const positions = value._positions;
    let length = positions.length;
    array[startingIndex++] = length;

    for (i = 0; i < length; ++i, startingIndex += Cartesian3.packedLength) {
      Cartesian3.pack(positions[i], array, startingIndex);
    }

    const shape = value._shape;
    length = shape.length;
    array[startingIndex++] = length;

    for (i = 0; i < length; ++i, startingIndex += Cartesian2.packedLength) {
      Cartesian2.pack(shape[i], array, startingIndex);
    }

    Ellipsoid.pack(value._ellipsoid, array, startingIndex);
    startingIndex += Ellipsoid.packedLength;

    VertexFormat.pack(value._vertexFormat, array, startingIndex);
    startingIndex += VertexFormat.packedLength;

    array[startingIndex++] = value._cornerType;
    array[startingIndex] = value._granularity;

    return array;
  };

  const scratchEllipsoid$6 = Ellipsoid.clone(Ellipsoid.UNIT_SPHERE);
  const scratchVertexFormat$2 = new VertexFormat();
  const scratchOptions$7 = {
    polylinePositions: undefined,
    shapePositions: undefined,
    ellipsoid: scratchEllipsoid$6,
    vertexFormat: scratchVertexFormat$2,
    cornerType: undefined,
    granularity: undefined,
  };

  /**
   * 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 {PolylineVolumeGeometry} [result] The object into which to store the result.
   * @returns {PolylineVolumeGeometry} The modified result parameter or a new PolylineVolumeGeometry instance if one was not provided.
   */
  PolylineVolumeGeometry.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(array)) {
      throw new DeveloperError("array is required");
    }
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    let i;

    let length = array[startingIndex++];
    const positions = new Array(length);

    for (i = 0; i < length; ++i, startingIndex += Cartesian3.packedLength) {
      positions[i] = Cartesian3.unpack(array, startingIndex);
    }

    length = array[startingIndex++];
    const shape = new Array(length);

    for (i = 0; i < length; ++i, startingIndex += Cartesian2.packedLength) {
      shape[i] = Cartesian2.unpack(array, startingIndex);
    }

    const ellipsoid = Ellipsoid.unpack(array, startingIndex, scratchEllipsoid$6);
    startingIndex += Ellipsoid.packedLength;

    const vertexFormat = VertexFormat.unpack(
      array,
      startingIndex,
      scratchVertexFormat$2
    );
    startingIndex += VertexFormat.packedLength;

    const cornerType = array[startingIndex++];
    const granularity = array[startingIndex];

    if (!defined(result)) {
      scratchOptions$7.polylinePositions = positions;
      scratchOptions$7.shapePositions = shape;
      scratchOptions$7.cornerType = cornerType;
      scratchOptions$7.granularity = granularity;
      return new PolylineVolumeGeometry(scratchOptions$7);
    }

    result._positions = positions;
    result._shape = shape;
    result._ellipsoid = Ellipsoid.clone(ellipsoid, result._ellipsoid);
    result._vertexFormat = VertexFormat.clone(vertexFormat, result._vertexFormat);
    result._cornerType = cornerType;
    result._granularity = granularity;

    return result;
  };

  const brScratch$1 = new BoundingRectangle();

  /**
   * Computes the geometric representation of a polyline with a volume, including its vertices, indices, and a bounding sphere.
   *
   * @param {PolylineVolumeGeometry} polylineVolumeGeometry A description of the polyline volume.
   * @returns {Geometry|undefined} The computed vertices and indices.
   */
  PolylineVolumeGeometry.createGeometry = function (polylineVolumeGeometry) {
    const positions = polylineVolumeGeometry._positions;
    const cleanPositions = arrayRemoveDuplicates(
      positions,
      Cartesian3.equalsEpsilon
    );
    let shape2D = polylineVolumeGeometry._shape;
    shape2D = PolylineVolumeGeometryLibrary.removeDuplicatesFromShape(shape2D);

    if (cleanPositions.length < 2 || shape2D.length < 3) {
      return undefined;
    }

    if (
      PolygonPipeline.computeWindingOrder2D(shape2D) === WindingOrder$1.CLOCKWISE
    ) {
      shape2D.reverse();
    }
    const boundingRectangle = BoundingRectangle.fromPoints(shape2D, brScratch$1);

    const computedPositions = PolylineVolumeGeometryLibrary.computePositions(
      cleanPositions,
      shape2D,
      boundingRectangle,
      polylineVolumeGeometry,
      true
    );
    return computeAttributes$1(
      computedPositions,
      shape2D,
      boundingRectangle,
      polylineVolumeGeometry._vertexFormat
    );
  };

  function computeAttributes(positions, shape) {
    const attributes = new GeometryAttributes();
    attributes.position = new GeometryAttribute({
      componentDatatype: ComponentDatatype$1.DOUBLE,
      componentsPerAttribute: 3,
      values: positions,
    });

    const shapeLength = shape.length;
    const vertexCount = attributes.position.values.length / 3;
    const positionLength = positions.length / 3;
    const shapeCount = positionLength / shapeLength;
    const indices = IndexDatatype$1.createTypedArray(
      vertexCount,
      2 * shapeLength * (shapeCount + 1)
    );
    let i, j;
    let index = 0;
    i = 0;
    let offset = i * shapeLength;
    for (j = 0; j < shapeLength - 1; j++) {
      indices[index++] = j + offset;
      indices[index++] = j + offset + 1;
    }
    indices[index++] = shapeLength - 1 + offset;
    indices[index++] = offset;

    i = shapeCount - 1;
    offset = i * shapeLength;
    for (j = 0; j < shapeLength - 1; j++) {
      indices[index++] = j + offset;
      indices[index++] = j + offset + 1;
    }
    indices[index++] = shapeLength - 1 + offset;
    indices[index++] = offset;

    for (i = 0; i < shapeCount - 1; i++) {
      const firstOffset = shapeLength * i;
      const secondOffset = firstOffset + shapeLength;
      for (j = 0; j < shapeLength; j++) {
        indices[index++] = j + firstOffset;
        indices[index++] = j + secondOffset;
      }
    }

    const geometry = new Geometry({
      attributes: attributes,
      indices: IndexDatatype$1.createTypedArray(vertexCount, indices),
      boundingSphere: BoundingSphere.fromVertices(positions),
      primitiveType: PrimitiveType$1.LINES,
    });

    return geometry;
  }

  /**
   * A description of a polyline with a volume (a 2D shape extruded along a polyline).
   *
   * @alias PolylineVolumeOutlineGeometry
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Cartesian3[]} options.polylinePositions An array of positions that define the center of the polyline volume.
   * @param {Cartesian2[]} options.shapePositions An array of positions that define the shape to be extruded along the polyline
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid to be used as a reference.
   * @param {Number} [options.granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
   * @param {CornerType} [options.cornerType=CornerType.ROUNDED] Determines the style of the corners.
   *
   * @see PolylineVolumeOutlineGeometry#createGeometry
   *
   * @example
   * function computeCircle(radius) {
   *   const positions = [];
   *   for (let i = 0; i < 360; i++) {
   *     const radians = Cesium.Math.toRadians(i);
   *     positions.push(new Cesium.Cartesian2(radius * Math.cos(radians), radius * Math.sin(radians)));
   *   }
   *   return positions;
   * }
   *
   * const volumeOutline = new Cesium.PolylineVolumeOutlineGeometry({
   *   polylinePositions : Cesium.Cartesian3.fromDegreesArray([
   *     -72.0, 40.0,
   *     -70.0, 35.0
   *   ]),
   *   shapePositions : computeCircle(100000.0)
   * });
   */
  function PolylineVolumeOutlineGeometry(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const positions = options.polylinePositions;
    const shape = options.shapePositions;

    //>>includeStart('debug', pragmas.debug);
    if (!defined(positions)) {
      throw new DeveloperError("options.polylinePositions is required.");
    }
    if (!defined(shape)) {
      throw new DeveloperError("options.shapePositions is required.");
    }
    //>>includeEnd('debug');

    this._positions = positions;
    this._shape = shape;
    this._ellipsoid = Ellipsoid.clone(
      defaultValue(options.ellipsoid, Ellipsoid.WGS84)
    );
    this._cornerType = defaultValue(options.cornerType, CornerType$1.ROUNDED);
    this._granularity = defaultValue(
      options.granularity,
      CesiumMath.RADIANS_PER_DEGREE
    );
    this._workerName = "createPolylineVolumeOutlineGeometry";

    let numComponents = 1 + positions.length * Cartesian3.packedLength;
    numComponents += 1 + shape.length * Cartesian2.packedLength;

    /**
     * The number of elements used to pack the object into an array.
     * @type {Number}
     */
    this.packedLength = numComponents + Ellipsoid.packedLength + 2;
  }

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {PolylineVolumeOutlineGeometry} 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
   */
  PolylineVolumeOutlineGeometry.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(value)) {
      throw new DeveloperError("value is required");
    }
    if (!defined(array)) {
      throw new DeveloperError("array is required");
    }
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    let i;

    const positions = value._positions;
    let length = positions.length;
    array[startingIndex++] = length;

    for (i = 0; i < length; ++i, startingIndex += Cartesian3.packedLength) {
      Cartesian3.pack(positions[i], array, startingIndex);
    }

    const shape = value._shape;
    length = shape.length;
    array[startingIndex++] = length;

    for (i = 0; i < length; ++i, startingIndex += Cartesian2.packedLength) {
      Cartesian2.pack(shape[i], array, startingIndex);
    }

    Ellipsoid.pack(value._ellipsoid, array, startingIndex);
    startingIndex += Ellipsoid.packedLength;

    array[startingIndex++] = value._cornerType;
    array[startingIndex] = value._granularity;

    return array;
  };

  const scratchEllipsoid$5 = Ellipsoid.clone(Ellipsoid.UNIT_SPHERE);
  const scratchOptions$6 = {
    polylinePositions: undefined,
    shapePositions: undefined,
    ellipsoid: scratchEllipsoid$5,
    height: undefined,
    cornerType: undefined,
    granularity: undefined,
  };

  /**
   * 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 {PolylineVolumeOutlineGeometry} [result] The object into which to store the result.
   * @returns {PolylineVolumeOutlineGeometry} The modified result parameter or a new PolylineVolumeOutlineGeometry instance if one was not provided.
   */
  PolylineVolumeOutlineGeometry.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(array)) {
      throw new DeveloperError("array is required");
    }
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    let i;

    let length = array[startingIndex++];
    const positions = new Array(length);

    for (i = 0; i < length; ++i, startingIndex += Cartesian3.packedLength) {
      positions[i] = Cartesian3.unpack(array, startingIndex);
    }

    length = array[startingIndex++];
    const shape = new Array(length);

    for (i = 0; i < length; ++i, startingIndex += Cartesian2.packedLength) {
      shape[i] = Cartesian2.unpack(array, startingIndex);
    }

    const ellipsoid = Ellipsoid.unpack(array, startingIndex, scratchEllipsoid$5);
    startingIndex += Ellipsoid.packedLength;

    const cornerType = array[startingIndex++];
    const granularity = array[startingIndex];

    if (!defined(result)) {
      scratchOptions$6.polylinePositions = positions;
      scratchOptions$6.shapePositions = shape;
      scratchOptions$6.cornerType = cornerType;
      scratchOptions$6.granularity = granularity;
      return new PolylineVolumeOutlineGeometry(scratchOptions$6);
    }

    result._positions = positions;
    result._shape = shape;
    result._ellipsoid = Ellipsoid.clone(ellipsoid, result._ellipsoid);
    result._cornerType = cornerType;
    result._granularity = granularity;

    return result;
  };

  const brScratch = new BoundingRectangle();

  /**
   * Computes the geometric representation of the outline of a polyline with a volume, including its vertices, indices, and a bounding sphere.
   *
   * @param {PolylineVolumeOutlineGeometry} polylineVolumeOutlineGeometry A description of the polyline volume outline.
   * @returns {Geometry|undefined} The computed vertices and indices.
   */
  PolylineVolumeOutlineGeometry.createGeometry = function (
    polylineVolumeOutlineGeometry
  ) {
    const positions = polylineVolumeOutlineGeometry._positions;
    const cleanPositions = arrayRemoveDuplicates(
      positions,
      Cartesian3.equalsEpsilon
    );
    let shape2D = polylineVolumeOutlineGeometry._shape;
    shape2D = PolylineVolumeGeometryLibrary.removeDuplicatesFromShape(shape2D);

    if (cleanPositions.length < 2 || shape2D.length < 3) {
      return undefined;
    }

    if (
      PolygonPipeline.computeWindingOrder2D(shape2D) === WindingOrder$1.CLOCKWISE
    ) {
      shape2D.reverse();
    }
    const boundingRectangle = BoundingRectangle.fromPoints(shape2D, brScratch);

    const computedPositions = PolylineVolumeGeometryLibrary.computePositions(
      cleanPositions,
      shape2D,
      boundingRectangle,
      polylineVolumeOutlineGeometry,
      false
    );
    return computeAttributes(computedPositions, shape2D);
  };

  /**
   * Base class for proxying requested made by {@link Resource}.
   *
   * @alias Proxy
   * @constructor
   *
   * @see DefaultProxy
   */
  function Proxy$1() {
    DeveloperError.throwInstantiationError();
  }

  /**
   * Get the final URL to use to request a given resource.
   *
   * @param {String} resource The resource to request.
   * @returns {String} proxied resource
   * @function
   */
  Proxy$1.prototype.getURL = DeveloperError.throwInstantiationError;

  function createEvaluateFunction(spline) {
    const points = spline.points;
    const times = spline.times;

    // use slerp interpolation
    return function (time, result) {
      if (!defined(result)) {
        result = new Quaternion();
      }
      const i = (spline._lastTimeIndex = spline.findTimeInterval(
        time,
        spline._lastTimeIndex
      ));
      const u = (time - times[i]) / (times[i + 1] - times[i]);

      const q0 = points[i];
      const q1 = points[i + 1];

      return Quaternion.fastSlerp(q0, q1, u, result);
    };
  }

  /**
   * A spline that uses spherical linear (slerp) interpolation to create a quaternion curve.
   * The generated curve is in the class C<sup>1</sup>.
   *
   * @alias QuaternionSpline
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Number[]} options.times An array of strictly increasing, unit-less, floating-point times at each point.
   *                The values are in no way connected to the clock time. They are the parameterization for the curve.
   * @param {Quaternion[]} options.points The array of {@link Quaternion} control points.
   *
   * @exception {DeveloperError} points and times are required
   * @exception {DeveloperError} points.length must be greater than or equal to 2.
   * @exception {DeveloperError} times.length must be equal to points.length.

   * @see ConstantSpline
   * @see SteppedSpline
   * @see HermiteSpline
   * @see CatmullRomSpline
   * @see LinearSpline
   * @see MorphWeightSpline
   */
  function QuaternionSpline(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const points = options.points;
    const times = options.times;

    //>>includeStart('debug', pragmas.debug);
    if (!defined(points) || !defined(times)) {
      throw new DeveloperError("points and times are required.");
    }
    if (points.length < 2) {
      throw new DeveloperError(
        "points.length must be greater than or equal to 2."
      );
    }
    if (times.length !== points.length) {
      throw new DeveloperError("times.length must be equal to points.length.");
    }
    //>>includeEnd('debug');

    this._times = times;
    this._points = points;

    this._evaluateFunction = createEvaluateFunction(this);
    this._lastTimeIndex = 0;
  }

  Object.defineProperties(QuaternionSpline.prototype, {
    /**
     * An array of times for the control points.
     *
     * @memberof QuaternionSpline.prototype
     *
     * @type {Number[]}
     * @readonly
     */
    times: {
      get: function () {
        return this._times;
      },
    },

    /**
     * An array of {@link Quaternion} control points.
     *
     * @memberof QuaternionSpline.prototype
     *
     * @type {Quaternion[]}
     * @readonly
     */
    points: {
      get: function () {
        return this._points;
      },
    },
  });

  /**
   * Finds an index <code>i</code> in <code>times</code> such that the parameter
   * <code>time</code> is in the interval <code>[times[i], times[i + 1]]</code>.
   * @function
   *
   * @param {Number} time The time.
   * @returns {Number} The index for the element at the start of the interval.
   *
   * @exception {DeveloperError} time must be in the range <code>[t<sub>0</sub>, t<sub>n</sub>]</code>, where <code>t<sub>0</sub></code>
   *                             is the first element in the array <code>times</code> and <code>t<sub>n</sub></code> is the last element
   *                             in the array <code>times</code>.
   */
  QuaternionSpline.prototype.findTimeInterval = Spline.prototype.findTimeInterval;

  /**
   * Wraps the given time to the period covered by the spline.
   * @function
   *
   * @param {Number} time The time.
   * @return {Number} The time, wrapped around to the updated animation.
   */
  QuaternionSpline.prototype.wrapTime = Spline.prototype.wrapTime;

  /**
   * Clamps the given time to the period covered by the spline.
   * @function
   *
   * @param {Number} time The time.
   * @return {Number} The time, clamped to the animation period.
   */
  QuaternionSpline.prototype.clampTime = Spline.prototype.clampTime;

  /**
   * Evaluates the curve at a given time.
   *
   * @param {Number} time The time at which to evaluate the curve.
   * @param {Quaternion} [result] The object onto which to store the result.
   * @returns {Quaternion} The modified result parameter or a new instance of the point on the curve at the given time.
   *
   * @exception {DeveloperError} time must be in the range <code>[t<sub>0</sub>, t<sub>n</sub>]</code>, where <code>t<sub>0</sub></code>
   *                             is the first element in the array <code>times</code> and <code>t<sub>n</sub></code> is the last element
   *                             in the array <code>times</code>.
   */
  QuaternionSpline.prototype.evaluate = function (time, result) {
    return this._evaluateFunction(time, result);
  };

  /* This file is automatically rebuilt by the Cesium build process. */
  function quickselect(arr, k, left, right, compare) {
      quickselectStep(arr, k, left || 0, right || (arr.length - 1), compare || defaultCompare);
  }

  function quickselectStep(arr, k, left, right, compare) {

      while (right > left) {
          if (right - left > 600) {
              var n = right - left + 1;
              var m = k - left + 1;
              var z = Math.log(n);
              var s = 0.5 * Math.exp(2 * z / 3);
              var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
              var newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
              var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
              quickselectStep(arr, k, newLeft, newRight, compare);
          }

          var t = arr[k];
          var i = left;
          var j = right;

          swap$1(arr, left, k);
          if (compare(arr[right], t) > 0) swap$1(arr, left, right);

          while (i < j) {
              swap$1(arr, i, j);
              i++;
              j--;
              while (compare(arr[i], t) < 0) i++;
              while (compare(arr[j], t) > 0) j--;
          }

          if (compare(arr[left], t) === 0) swap$1(arr, left, j);
          else {
              j++;
              swap$1(arr, j, right);
          }

          if (j <= k) left = j + 1;
          if (k <= j) right = j - 1;
      }
  }

  function swap$1(arr, i, j) {
      var tmp = arr[i];
      arr[i] = arr[j];
      arr[j] = tmp;
  }

  function defaultCompare(a, b) {
      return a < b ? -1 : a > b ? 1 : 0;
  }

  class RBush {
      constructor(maxEntries = 9) {
          // max entries in a node is 9 by default; min node fill is 40% for best performance
          this._maxEntries = Math.max(4, maxEntries);
          this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4));
          this.clear();
      }

      all() {
          return this._all(this.data, []);
      }

      search(bbox) {
          let node = this.data;
          const result = [];

          if (!intersects(bbox, node)) return result;

          const toBBox = this.toBBox;
          const nodesToSearch = [];

          while (node) {
              for (let i = 0; i < node.children.length; i++) {
                  const child = node.children[i];
                  const childBBox = node.leaf ? toBBox(child) : child;

                  if (intersects(bbox, childBBox)) {
                      if (node.leaf) result.push(child);
                      else if (contains$1(bbox, childBBox)) this._all(child, result);
                      else nodesToSearch.push(child);
                  }
              }
              node = nodesToSearch.pop();
          }

          return result;
      }

      collides(bbox) {
          let node = this.data;

          if (!intersects(bbox, node)) return false;

          const nodesToSearch = [];
          while (node) {
              for (let i = 0; i < node.children.length; i++) {
                  const child = node.children[i];
                  const childBBox = node.leaf ? this.toBBox(child) : child;

                  if (intersects(bbox, childBBox)) {
                      if (node.leaf || contains$1(bbox, childBBox)) return true;
                      nodesToSearch.push(child);
                  }
              }
              node = nodesToSearch.pop();
          }

          return false;
      }

      load(data) {
          if (!(data && data.length)) return this;

          if (data.length < this._minEntries) {
              for (let i = 0; i < data.length; i++) {
                  this.insert(data[i]);
              }
              return this;
          }

          // recursively build the tree with the given data from scratch using OMT algorithm
          let node = this._build(data.slice(), 0, data.length - 1, 0);

          if (!this.data.children.length) {
              // save as is if tree is empty
              this.data = node;

          } else if (this.data.height === node.height) {
              // split root if trees have the same height
              this._splitRoot(this.data, node);

          } else {
              if (this.data.height < node.height) {
                  // swap trees if inserted one is bigger
                  const tmpNode = this.data;
                  this.data = node;
                  node = tmpNode;
              }

              // insert the small tree into the large tree at appropriate level
              this._insert(node, this.data.height - node.height - 1, true);
          }

          return this;
      }

      insert(item) {
          if (item) this._insert(item, this.data.height - 1);
          return this;
      }

      clear() {
          this.data = createNode([]);
          return this;
      }

      remove(item, equalsFn) {
          if (!item) return this;

          let node = this.data;
          const bbox = this.toBBox(item);
          const path = [];
          const indexes = [];
          let i, parent, goingUp;

          // depth-first iterative tree traversal
          while (node || path.length) {

              if (!node) { // go up
                  node = path.pop();
                  parent = path[path.length - 1];
                  i = indexes.pop();
                  goingUp = true;
              }

              if (node.leaf) { // check current node
                  const index = findItem(item, node.children, equalsFn);

                  if (index !== -1) {
                      // item found, remove the item and condense tree upwards
                      node.children.splice(index, 1);
                      path.push(node);
                      this._condense(path);
                      return this;
                  }
              }

              if (!goingUp && !node.leaf && contains$1(node, bbox)) { // go down
                  path.push(node);
                  indexes.push(i);
                  i = 0;
                  parent = node;
                  node = node.children[0];

              } else if (parent) { // go right
                  i++;
                  node = parent.children[i];
                  goingUp = false;

              } else node = null; // nothing found
          }

          return this;
      }

      toBBox(item) { return item; }

      compareMinX(a, b) { return a.minX - b.minX; }
      compareMinY(a, b) { return a.minY - b.minY; }

      toJSON() { return this.data; }

      fromJSON(data) {
          this.data = data;
          return this;
      }

      _all(node, result) {
          const nodesToSearch = [];
          while (node) {
              if (node.leaf) result.push(...node.children);
              else nodesToSearch.push(...node.children);

              node = nodesToSearch.pop();
          }
          return result;
      }

      _build(items, left, right, height) {

          const N = right - left + 1;
          let M = this._maxEntries;
          let node;

          if (N <= M) {
              // reached leaf level; return leaf
              node = createNode(items.slice(left, right + 1));
              calcBBox(node, this.toBBox);
              return node;
          }

          if (!height) {
              // target height of the bulk-loaded tree
              height = Math.ceil(Math.log(N) / Math.log(M));

              // target number of root entries to maximize storage utilization
              M = Math.ceil(N / Math.pow(M, height - 1));
          }

          node = createNode([]);
          node.leaf = false;
          node.height = height;

          // split the items into M mostly square tiles

          const N2 = Math.ceil(N / M);
          const N1 = N2 * Math.ceil(Math.sqrt(M));

          multiSelect(items, left, right, N1, this.compareMinX);

          for (let i = left; i <= right; i += N1) {

              const right2 = Math.min(i + N1 - 1, right);

              multiSelect(items, i, right2, N2, this.compareMinY);

              for (let j = i; j <= right2; j += N2) {

                  const right3 = Math.min(j + N2 - 1, right2);

                  // pack each entry recursively
                  node.children.push(this._build(items, j, right3, height - 1));
              }
          }

          calcBBox(node, this.toBBox);

          return node;
      }

      _chooseSubtree(bbox, node, level, path) {
          while (true) {
              path.push(node);

              if (node.leaf || path.length - 1 === level) break;

              let minArea = Infinity;
              let minEnlargement = Infinity;
              let targetNode;

              for (let i = 0; i < node.children.length; i++) {
                  const child = node.children[i];
                  const area = bboxArea(child);
                  const enlargement = enlargedArea(bbox, child) - area;

                  // choose entry with the least area enlargement
                  if (enlargement < minEnlargement) {
                      minEnlargement = enlargement;
                      minArea = area < minArea ? area : minArea;
                      targetNode = child;

                  } else if (enlargement === minEnlargement) {
                      // otherwise choose one with the smallest area
                      if (area < minArea) {
                          minArea = area;
                          targetNode = child;
                      }
                  }
              }

              node = targetNode || node.children[0];
          }

          return node;
      }

      _insert(item, level, isNode) {
          const bbox = isNode ? item : this.toBBox(item);
          const insertPath = [];

          // find the best node for accommodating the item, saving all nodes along the path too
          const node = this._chooseSubtree(bbox, this.data, level, insertPath);

          // put the item into the node
          node.children.push(item);
          extend(node, bbox);

          // split on node overflow; propagate upwards if necessary
          while (level >= 0) {
              if (insertPath[level].children.length > this._maxEntries) {
                  this._split(insertPath, level);
                  level--;
              } else break;
          }

          // adjust bboxes along the insertion path
          this._adjustParentBBoxes(bbox, insertPath, level);
      }

      // split overflowed node into two
      _split(insertPath, level) {
          const node = insertPath[level];
          const M = node.children.length;
          const m = this._minEntries;

          this._chooseSplitAxis(node, m, M);

          const splitIndex = this._chooseSplitIndex(node, m, M);

          const newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex));
          newNode.height = node.height;
          newNode.leaf = node.leaf;

          calcBBox(node, this.toBBox);
          calcBBox(newNode, this.toBBox);

          if (level) insertPath[level - 1].children.push(newNode);
          else this._splitRoot(node, newNode);
      }

      _splitRoot(node, newNode) {
          // split root node
          this.data = createNode([node, newNode]);
          this.data.height = node.height + 1;
          this.data.leaf = false;
          calcBBox(this.data, this.toBBox);
      }

      _chooseSplitIndex(node, m, M) {
          let index;
          let minOverlap = Infinity;
          let minArea = Infinity;

          for (let i = m; i <= M - m; i++) {
              const bbox1 = distBBox(node, 0, i, this.toBBox);
              const bbox2 = distBBox(node, i, M, this.toBBox);

              const overlap = intersectionArea(bbox1, bbox2);
              const area = bboxArea(bbox1) + bboxArea(bbox2);

              // choose distribution with minimum overlap
              if (overlap < minOverlap) {
                  minOverlap = overlap;
                  index = i;

                  minArea = area < minArea ? area : minArea;

              } else if (overlap === minOverlap) {
                  // otherwise choose distribution with minimum area
                  if (area < minArea) {
                      minArea = area;
                      index = i;
                  }
              }
          }

          return index || M - m;
      }

      // sorts node children by the best axis for split
      _chooseSplitAxis(node, m, M) {
          const compareMinX = node.leaf ? this.compareMinX : compareNodeMinX;
          const compareMinY = node.leaf ? this.compareMinY : compareNodeMinY;
          const xMargin = this._allDistMargin(node, m, M, compareMinX);
          const yMargin = this._allDistMargin(node, m, M, compareMinY);

          // if total distributions margin value is minimal for x, sort by minX,
          // otherwise it's already sorted by minY
          if (xMargin < yMargin) node.children.sort(compareMinX);
      }

      // total margin of all possible split distributions where each node is at least m full
      _allDistMargin(node, m, M, compare) {
          node.children.sort(compare);

          const toBBox = this.toBBox;
          const leftBBox = distBBox(node, 0, m, toBBox);
          const rightBBox = distBBox(node, M - m, M, toBBox);
          let margin = bboxMargin(leftBBox) + bboxMargin(rightBBox);

          for (let i = m; i < M - m; i++) {
              const child = node.children[i];
              extend(leftBBox, node.leaf ? toBBox(child) : child);
              margin += bboxMargin(leftBBox);
          }

          for (let i = M - m - 1; i >= m; i--) {
              const child = node.children[i];
              extend(rightBBox, node.leaf ? toBBox(child) : child);
              margin += bboxMargin(rightBBox);
          }

          return margin;
      }

      _adjustParentBBoxes(bbox, path, level) {
          // adjust bboxes along the given tree path
          for (let i = level; i >= 0; i--) {
              extend(path[i], bbox);
          }
      }

      _condense(path) {
          // go through the path, removing empty nodes and updating bboxes
          for (let i = path.length - 1, siblings; i >= 0; i--) {
              if (path[i].children.length === 0) {
                  if (i > 0) {
                      siblings = path[i - 1].children;
                      siblings.splice(siblings.indexOf(path[i]), 1);

                  } else this.clear();

              } else calcBBox(path[i], this.toBBox);
          }
      }
  }

  function findItem(item, items, equalsFn) {
      if (!equalsFn) return items.indexOf(item);

      for (let i = 0; i < items.length; i++) {
          if (equalsFn(item, items[i])) return i;
      }
      return -1;
  }

  // calculate node's bbox from bboxes of its children
  function calcBBox(node, toBBox) {
      distBBox(node, 0, node.children.length, toBBox, node);
  }

  // min bounding rectangle of node children from k to p-1
  function distBBox(node, k, p, toBBox, destNode) {
      if (!destNode) destNode = createNode(null);
      destNode.minX = Infinity;
      destNode.minY = Infinity;
      destNode.maxX = -Infinity;
      destNode.maxY = -Infinity;

      for (let i = k; i < p; i++) {
          const child = node.children[i];
          extend(destNode, node.leaf ? toBBox(child) : child);
      }

      return destNode;
  }

  function extend(a, b) {
      a.minX = Math.min(a.minX, b.minX);
      a.minY = Math.min(a.minY, b.minY);
      a.maxX = Math.max(a.maxX, b.maxX);
      a.maxY = Math.max(a.maxY, b.maxY);
      return a;
  }

  function compareNodeMinX(a, b) { return a.minX - b.minX; }
  function compareNodeMinY(a, b) { return a.minY - b.minY; }

  function bboxArea(a)   { return (a.maxX - a.minX) * (a.maxY - a.minY); }
  function bboxMargin(a) { return (a.maxX - a.minX) + (a.maxY - a.minY); }

  function enlargedArea(a, b) {
      return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) *
             (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY));
  }

  function intersectionArea(a, b) {
      const minX = Math.max(a.minX, b.minX);
      const minY = Math.max(a.minY, b.minY);
      const maxX = Math.min(a.maxX, b.maxX);
      const maxY = Math.min(a.maxY, b.maxY);

      return Math.max(0, maxX - minX) *
             Math.max(0, maxY - minY);
  }

  function contains$1(a, b) {
      return a.minX <= b.minX &&
             a.minY <= b.minY &&
             b.maxX <= a.maxX &&
             b.maxY <= a.maxY;
  }

  function intersects(a, b) {
      return b.minX <= a.maxX &&
             b.minY <= a.maxY &&
             b.maxX >= a.minX &&
             b.maxY >= a.minY;
  }

  function createNode(children) {
      return {
          children,
          height: 1,
          leaf: true,
          minX: Infinity,
          minY: Infinity,
          maxX: -Infinity,
          maxY: -Infinity
      };
  }

  // sort an array so that items come in groups of n unsorted items, with groups sorted between each other;
  // combines selection algorithm with binary divide & conquer approach

  function multiSelect(arr, left, right, n, compare) {
      const stack = [left, right];

      while (stack.length) {
          right = stack.pop();
          left = stack.pop();

          if (right - left <= n) continue;

          const mid = left + Math.ceil((right - left) / n / 2) * n;
          quickselect(arr, mid, left, right, compare);

          stack.push(left, mid, mid, right);
      }
  }

  /**
   * Wrapper around rbush for use with Rectangle types.
   * @private
   */
  function RectangleCollisionChecker() {
    this._tree = new RBush();
  }

  function RectangleWithId() {
    this.minX = 0.0;
    this.minY = 0.0;
    this.maxX = 0.0;
    this.maxY = 0.0;
    this.id = "";
  }

  RectangleWithId.fromRectangleAndId = function (id, rectangle, result) {
    result.minX = rectangle.west;
    result.minY = rectangle.south;
    result.maxX = rectangle.east;
    result.maxY = rectangle.north;
    result.id = id;
    return result;
  };

  /**
   * Insert a rectangle into the collision checker.
   *
   * @param {String} id Unique string ID for the rectangle being inserted.
   * @param {Rectangle} rectangle A Rectangle
   * @private
   */
  RectangleCollisionChecker.prototype.insert = function (id, rectangle) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("id", id);
    Check.typeOf.object("rectangle", rectangle);
    //>>includeEnd('debug');

    const withId = RectangleWithId.fromRectangleAndId(
      id,
      rectangle,
      new RectangleWithId()
    );
    this._tree.insert(withId);
  };

  function idCompare(a, b) {
    return a.id === b.id;
  }

  const removalScratch = new RectangleWithId();
  /**
   * Remove a rectangle from the collision checker.
   *
   * @param {String} id Unique string ID for the rectangle being removed.
   * @param {Rectangle} rectangle A Rectangle
   * @private
   */
  RectangleCollisionChecker.prototype.remove = function (id, rectangle) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("id", id);
    Check.typeOf.object("rectangle", rectangle);
    //>>includeEnd('debug');

    const withId = RectangleWithId.fromRectangleAndId(
      id,
      rectangle,
      removalScratch
    );
    this._tree.remove(withId, idCompare);
  };

  const collisionScratch = new RectangleWithId();
  /**
   * Checks if a given rectangle collides with any of the rectangles in the collection.
   *
   * @param {Rectangle} rectangle A Rectangle that should be checked against the rectangles in the collision checker.
   * @returns {Boolean} Whether the rectangle collides with any of the rectangles in the collision checker.
   */
  RectangleCollisionChecker.prototype.collides = function (rectangle) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("rectangle", rectangle);
    //>>includeEnd('debug');

    const withId = RectangleWithId.fromRectangleAndId(
      "",
      rectangle,
      collisionScratch
    );
    return this._tree.collides(withId);
  };

  const cos = Math.cos;
  const sin = Math.sin;
  const sqrt = Math.sqrt;

  /**
   * @private
   */
  const RectangleGeometryLibrary = {};

  /**
   * @private
   */
  RectangleGeometryLibrary.computePosition = function (
    computedOptions,
    ellipsoid,
    computeST,
    row,
    col,
    position,
    st
  ) {
    const radiiSquared = ellipsoid.radiiSquared;
    const nwCorner = computedOptions.nwCorner;
    const rectangle = computedOptions.boundingRectangle;

    let stLatitude =
      nwCorner.latitude -
      computedOptions.granYCos * row +
      col * computedOptions.granXSin;
    const cosLatitude = cos(stLatitude);
    const nZ = sin(stLatitude);
    const kZ = radiiSquared.z * nZ;

    let stLongitude =
      nwCorner.longitude +
      row * computedOptions.granYSin +
      col * computedOptions.granXCos;
    const nX = cosLatitude * cos(stLongitude);
    const nY = cosLatitude * sin(stLongitude);

    const kX = radiiSquared.x * nX;
    const kY = radiiSquared.y * nY;

    const gamma = sqrt(kX * nX + kY * nY + kZ * nZ);

    position.x = kX / gamma;
    position.y = kY / gamma;
    position.z = kZ / gamma;

    if (computeST) {
      const stNwCorner = computedOptions.stNwCorner;
      if (defined(stNwCorner)) {
        stLatitude =
          stNwCorner.latitude -
          computedOptions.stGranYCos * row +
          col * computedOptions.stGranXSin;
        stLongitude =
          stNwCorner.longitude +
          row * computedOptions.stGranYSin +
          col * computedOptions.stGranXCos;

        st.x = (stLongitude - computedOptions.stWest) * computedOptions.lonScalar;
        st.y = (stLatitude - computedOptions.stSouth) * computedOptions.latScalar;
      } else {
        st.x = (stLongitude - rectangle.west) * computedOptions.lonScalar;
        st.y = (stLatitude - rectangle.south) * computedOptions.latScalar;
      }
    }
  };

  const rotationMatrixScratch = new Matrix2();
  let nwCartesian = new Cartesian3();
  const centerScratch$3 = new Cartographic();
  let centerCartesian = new Cartesian3();
  const proj = new GeographicProjection();

  function getRotationOptions(
    nwCorner,
    rotation,
    granularityX,
    granularityY,
    center,
    width,
    height
  ) {
    const cosRotation = Math.cos(rotation);
    const granYCos = granularityY * cosRotation;
    const granXCos = granularityX * cosRotation;

    const sinRotation = Math.sin(rotation);
    const granYSin = granularityY * sinRotation;
    const granXSin = granularityX * sinRotation;

    nwCartesian = proj.project(nwCorner, nwCartesian);

    nwCartesian = Cartesian3.subtract(nwCartesian, centerCartesian, nwCartesian);
    const rotationMatrix = Matrix2.fromRotation(rotation, rotationMatrixScratch);
    nwCartesian = Matrix2.multiplyByVector(
      rotationMatrix,
      nwCartesian,
      nwCartesian
    );
    nwCartesian = Cartesian3.add(nwCartesian, centerCartesian, nwCartesian);
    nwCorner = proj.unproject(nwCartesian, nwCorner);

    width -= 1;
    height -= 1;

    const latitude = nwCorner.latitude;
    const latitude0 = latitude + width * granXSin;
    const latitude1 = latitude - granYCos * height;
    const latitude2 = latitude - granYCos * height + width * granXSin;

    const north = Math.max(latitude, latitude0, latitude1, latitude2);
    const south = Math.min(latitude, latitude0, latitude1, latitude2);

    const longitude = nwCorner.longitude;
    const longitude0 = longitude + width * granXCos;
    const longitude1 = longitude + height * granYSin;
    const longitude2 = longitude + height * granYSin + width * granXCos;

    const east = Math.max(longitude, longitude0, longitude1, longitude2);
    const west = Math.min(longitude, longitude0, longitude1, longitude2);

    return {
      north: north,
      south: south,
      east: east,
      west: west,
      granYCos: granYCos,
      granYSin: granYSin,
      granXCos: granXCos,
      granXSin: granXSin,
      nwCorner: nwCorner,
    };
  }

  /**
   * @private
   */
  RectangleGeometryLibrary.computeOptions = function (
    rectangle,
    granularity,
    rotation,
    stRotation,
    boundingRectangleScratch,
    nwCornerResult,
    stNwCornerResult
  ) {
    let east = rectangle.east;
    let west = rectangle.west;
    let north = rectangle.north;
    let south = rectangle.south;

    let northCap = false;
    let southCap = false;

    if (north === CesiumMath.PI_OVER_TWO) {
      northCap = true;
    }
    if (south === -CesiumMath.PI_OVER_TWO) {
      southCap = true;
    }

    let dx;
    const dy = north - south;
    if (west > east) {
      dx = CesiumMath.TWO_PI - west + east;
    } else {
      dx = east - west;
    }

    const width = Math.ceil(dx / granularity) + 1;
    const height = Math.ceil(dy / granularity) + 1;
    const granularityX = dx / (width - 1);
    const granularityY = dy / (height - 1);

    const nwCorner = Rectangle.northwest(rectangle, nwCornerResult);
    const center = Rectangle.center(rectangle, centerScratch$3);
    if (rotation !== 0 || stRotation !== 0) {
      if (center.longitude < nwCorner.longitude) {
        center.longitude += CesiumMath.TWO_PI;
      }
      centerCartesian = proj.project(center, centerCartesian);
    }

    const granYCos = granularityY;
    const granXCos = granularityX;
    const granYSin = 0.0;
    const granXSin = 0.0;

    const boundingRectangle = Rectangle.clone(
      rectangle,
      boundingRectangleScratch
    );

    const computedOptions = {
      granYCos: granYCos,
      granYSin: granYSin,
      granXCos: granXCos,
      granXSin: granXSin,
      nwCorner: nwCorner,
      boundingRectangle: boundingRectangle,
      width: width,
      height: height,
      northCap: northCap,
      southCap: southCap,
    };

    if (rotation !== 0) {
      const rotationOptions = getRotationOptions(
        nwCorner,
        rotation,
        granularityX,
        granularityY,
        center,
        width,
        height
      );
      north = rotationOptions.north;
      south = rotationOptions.south;
      east = rotationOptions.east;
      west = rotationOptions.west;

      //>>includeStart('debug', pragmas.debug);
      if (
        north < -CesiumMath.PI_OVER_TWO ||
        north > CesiumMath.PI_OVER_TWO ||
        south < -CesiumMath.PI_OVER_TWO ||
        south > CesiumMath.PI_OVER_TWO
      ) {
        throw new DeveloperError(
          "Rotated rectangle is invalid.  It crosses over either the north or south pole."
        );
      }
      //>>includeEnd('debug')

      computedOptions.granYCos = rotationOptions.granYCos;
      computedOptions.granYSin = rotationOptions.granYSin;
      computedOptions.granXCos = rotationOptions.granXCos;
      computedOptions.granXSin = rotationOptions.granXSin;

      boundingRectangle.north = north;
      boundingRectangle.south = south;
      boundingRectangle.east = east;
      boundingRectangle.west = west;
    }

    if (stRotation !== 0) {
      rotation = rotation - stRotation;
      const stNwCorner = Rectangle.northwest(boundingRectangle, stNwCornerResult);

      const stRotationOptions = getRotationOptions(
        stNwCorner,
        rotation,
        granularityX,
        granularityY,
        center,
        width,
        height
      );

      computedOptions.stGranYCos = stRotationOptions.granYCos;
      computedOptions.stGranXCos = stRotationOptions.granXCos;
      computedOptions.stGranYSin = stRotationOptions.granYSin;
      computedOptions.stGranXSin = stRotationOptions.granXSin;
      computedOptions.stNwCorner = stNwCorner;
      computedOptions.stWest = stRotationOptions.west;
      computedOptions.stSouth = stRotationOptions.south;
    }

    return computedOptions;
  };

  const positionScratch$b = new Cartesian3();
  const normalScratch$2 = new Cartesian3();
  const tangentScratch = new Cartesian3();
  const bitangentScratch = new Cartesian3();
  const rectangleScratch$4 = new Rectangle();
  const stScratch = new Cartesian2();
  const bottomBoundingSphere$1 = new BoundingSphere();
  const topBoundingSphere$1 = new BoundingSphere();

  function createAttributes(vertexFormat, attributes) {
    const geo = new Geometry({
      attributes: new GeometryAttributes(),
      primitiveType: PrimitiveType$1.TRIANGLES,
    });

    geo.attributes.position = new GeometryAttribute({
      componentDatatype: ComponentDatatype$1.DOUBLE,
      componentsPerAttribute: 3,
      values: attributes.positions,
    });
    if (vertexFormat.normal) {
      geo.attributes.normal = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 3,
        values: attributes.normals,
      });
    }
    if (vertexFormat.tangent) {
      geo.attributes.tangent = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 3,
        values: attributes.tangents,
      });
    }
    if (vertexFormat.bitangent) {
      geo.attributes.bitangent = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 3,
        values: attributes.bitangents,
      });
    }
    return geo;
  }

  function calculateAttributes(
    positions,
    vertexFormat,
    ellipsoid,
    tangentRotationMatrix
  ) {
    const length = positions.length;

    const normals = vertexFormat.normal ? new Float32Array(length) : undefined;
    const tangents = vertexFormat.tangent ? new Float32Array(length) : undefined;
    const bitangents = vertexFormat.bitangent
      ? new Float32Array(length)
      : undefined;

    let attrIndex = 0;
    const bitangent = bitangentScratch;
    const tangent = tangentScratch;
    let normal = normalScratch$2;
    if (vertexFormat.normal || vertexFormat.tangent || vertexFormat.bitangent) {
      for (let i = 0; i < length; i += 3) {
        const p = Cartesian3.fromArray(positions, i, positionScratch$b);
        const attrIndex1 = attrIndex + 1;
        const attrIndex2 = attrIndex + 2;

        normal = ellipsoid.geodeticSurfaceNormal(p, normal);
        if (vertexFormat.tangent || vertexFormat.bitangent) {
          Cartesian3.cross(Cartesian3.UNIT_Z, normal, tangent);
          Matrix3.multiplyByVector(tangentRotationMatrix, tangent, tangent);
          Cartesian3.normalize(tangent, tangent);

          if (vertexFormat.bitangent) {
            Cartesian3.normalize(
              Cartesian3.cross(normal, tangent, bitangent),
              bitangent
            );
          }
        }

        if (vertexFormat.normal) {
          normals[attrIndex] = normal.x;
          normals[attrIndex1] = normal.y;
          normals[attrIndex2] = normal.z;
        }
        if (vertexFormat.tangent) {
          tangents[attrIndex] = tangent.x;
          tangents[attrIndex1] = tangent.y;
          tangents[attrIndex2] = tangent.z;
        }
        if (vertexFormat.bitangent) {
          bitangents[attrIndex] = bitangent.x;
          bitangents[attrIndex1] = bitangent.y;
          bitangents[attrIndex2] = bitangent.z;
        }
        attrIndex += 3;
      }
    }
    return createAttributes(vertexFormat, {
      positions: positions,
      normals: normals,
      tangents: tangents,
      bitangents: bitangents,
    });
  }

  const v1Scratch = new Cartesian3();
  const v2Scratch = new Cartesian3();

  function calculateAttributesWall(positions, vertexFormat, ellipsoid) {
    const length = positions.length;

    const normals = vertexFormat.normal ? new Float32Array(length) : undefined;
    const tangents = vertexFormat.tangent ? new Float32Array(length) : undefined;
    const bitangents = vertexFormat.bitangent
      ? new Float32Array(length)
      : undefined;

    let normalIndex = 0;
    let tangentIndex = 0;
    let bitangentIndex = 0;
    let recomputeNormal = true;

    let bitangent = bitangentScratch;
    let tangent = tangentScratch;
    let normal = normalScratch$2;
    if (vertexFormat.normal || vertexFormat.tangent || vertexFormat.bitangent) {
      for (let i = 0; i < length; i += 6) {
        const p = Cartesian3.fromArray(positions, i, positionScratch$b);
        const p1 = Cartesian3.fromArray(positions, (i + 6) % length, v1Scratch);
        if (recomputeNormal) {
          const p2 = Cartesian3.fromArray(positions, (i + 3) % length, v2Scratch);
          Cartesian3.subtract(p1, p, p1);
          Cartesian3.subtract(p2, p, p2);
          normal = Cartesian3.normalize(Cartesian3.cross(p2, p1, normal), normal);
          recomputeNormal = false;
        }

        if (Cartesian3.equalsEpsilon(p1, p, CesiumMath.EPSILON10)) {
          // if we've reached a corner
          recomputeNormal = true;
        }

        if (vertexFormat.tangent || vertexFormat.bitangent) {
          bitangent = ellipsoid.geodeticSurfaceNormal(p, bitangent);
          if (vertexFormat.tangent) {
            tangent = Cartesian3.normalize(
              Cartesian3.cross(bitangent, normal, tangent),
              tangent
            );
          }
        }

        if (vertexFormat.normal) {
          normals[normalIndex++] = normal.x;
          normals[normalIndex++] = normal.y;
          normals[normalIndex++] = normal.z;
          normals[normalIndex++] = normal.x;
          normals[normalIndex++] = normal.y;
          normals[normalIndex++] = normal.z;
        }

        if (vertexFormat.tangent) {
          tangents[tangentIndex++] = tangent.x;
          tangents[tangentIndex++] = tangent.y;
          tangents[tangentIndex++] = tangent.z;
          tangents[tangentIndex++] = tangent.x;
          tangents[tangentIndex++] = tangent.y;
          tangents[tangentIndex++] = tangent.z;
        }

        if (vertexFormat.bitangent) {
          bitangents[bitangentIndex++] = bitangent.x;
          bitangents[bitangentIndex++] = bitangent.y;
          bitangents[bitangentIndex++] = bitangent.z;
          bitangents[bitangentIndex++] = bitangent.x;
          bitangents[bitangentIndex++] = bitangent.y;
          bitangents[bitangentIndex++] = bitangent.z;
        }
      }
    }

    return createAttributes(vertexFormat, {
      positions: positions,
      normals: normals,
      tangents: tangents,
      bitangents: bitangents,
    });
  }

  function constructRectangle$1(rectangleGeometry, computedOptions) {
    const vertexFormat = rectangleGeometry._vertexFormat;
    const ellipsoid = rectangleGeometry._ellipsoid;
    const height = computedOptions.height;
    const width = computedOptions.width;
    const northCap = computedOptions.northCap;
    const southCap = computedOptions.southCap;

    let rowStart = 0;
    let rowEnd = height;
    let rowHeight = height;
    let size = 0;
    if (northCap) {
      rowStart = 1;
      rowHeight -= 1;
      size += 1;
    }
    if (southCap) {
      rowEnd -= 1;
      rowHeight -= 1;
      size += 1;
    }
    size += width * rowHeight;

    const positions = vertexFormat.position
      ? new Float64Array(size * 3)
      : undefined;
    const textureCoordinates = vertexFormat.st
      ? new Float32Array(size * 2)
      : undefined;

    let posIndex = 0;
    let stIndex = 0;

    const position = positionScratch$b;
    const st = stScratch;

    let minX = Number.MAX_VALUE;
    let minY = Number.MAX_VALUE;
    let maxX = -Number.MAX_VALUE;
    let maxY = -Number.MAX_VALUE;

    for (let row = rowStart; row < rowEnd; ++row) {
      for (let col = 0; col < width; ++col) {
        RectangleGeometryLibrary.computePosition(
          computedOptions,
          ellipsoid,
          vertexFormat.st,
          row,
          col,
          position,
          st
        );

        positions[posIndex++] = position.x;
        positions[posIndex++] = position.y;
        positions[posIndex++] = position.z;

        if (vertexFormat.st) {
          textureCoordinates[stIndex++] = st.x;
          textureCoordinates[stIndex++] = st.y;

          minX = Math.min(minX, st.x);
          minY = Math.min(minY, st.y);
          maxX = Math.max(maxX, st.x);
          maxY = Math.max(maxY, st.y);
        }
      }
    }
    if (northCap) {
      RectangleGeometryLibrary.computePosition(
        computedOptions,
        ellipsoid,
        vertexFormat.st,
        0,
        0,
        position,
        st
      );

      positions[posIndex++] = position.x;
      positions[posIndex++] = position.y;
      positions[posIndex++] = position.z;

      if (vertexFormat.st) {
        textureCoordinates[stIndex++] = st.x;
        textureCoordinates[stIndex++] = st.y;

        minX = st.x;
        minY = st.y;
        maxX = st.x;
        maxY = st.y;
      }
    }
    if (southCap) {
      RectangleGeometryLibrary.computePosition(
        computedOptions,
        ellipsoid,
        vertexFormat.st,
        height - 1,
        0,
        position,
        st
      );

      positions[posIndex++] = position.x;
      positions[posIndex++] = position.y;
      positions[posIndex] = position.z;

      if (vertexFormat.st) {
        textureCoordinates[stIndex++] = st.x;
        textureCoordinates[stIndex] = st.y;

        minX = Math.min(minX, st.x);
        minY = Math.min(minY, st.y);
        maxX = Math.max(maxX, st.x);
        maxY = Math.max(maxY, st.y);
      }
    }

    if (
      vertexFormat.st &&
      (minX < 0.0 || minY < 0.0 || maxX > 1.0 || maxY > 1.0)
    ) {
      for (let k = 0; k < textureCoordinates.length; k += 2) {
        textureCoordinates[k] = (textureCoordinates[k] - minX) / (maxX - minX);
        textureCoordinates[k + 1] =
          (textureCoordinates[k + 1] - minY) / (maxY - minY);
      }
    }

    const geo = calculateAttributes(
      positions,
      vertexFormat,
      ellipsoid,
      computedOptions.tangentRotationMatrix
    );

    let indicesSize = 6 * (width - 1) * (rowHeight - 1);
    if (northCap) {
      indicesSize += 3 * (width - 1);
    }
    if (southCap) {
      indicesSize += 3 * (width - 1);
    }
    const indices = IndexDatatype$1.createTypedArray(size, indicesSize);
    let index = 0;
    let indicesIndex = 0;
    let i;
    for (i = 0; i < rowHeight - 1; ++i) {
      for (let j = 0; j < width - 1; ++j) {
        const upperLeft = index;
        const lowerLeft = upperLeft + width;
        const lowerRight = lowerLeft + 1;
        const upperRight = upperLeft + 1;
        indices[indicesIndex++] = upperLeft;
        indices[indicesIndex++] = lowerLeft;
        indices[indicesIndex++] = upperRight;
        indices[indicesIndex++] = upperRight;
        indices[indicesIndex++] = lowerLeft;
        indices[indicesIndex++] = lowerRight;
        ++index;
      }
      ++index;
    }
    if (northCap || southCap) {
      let northIndex = size - 1;
      const southIndex = size - 1;
      if (northCap && southCap) {
        northIndex = size - 2;
      }

      let p1;
      let p2;
      index = 0;

      if (northCap) {
        for (i = 0; i < width - 1; i++) {
          p1 = index;
          p2 = p1 + 1;
          indices[indicesIndex++] = northIndex;
          indices[indicesIndex++] = p1;
          indices[indicesIndex++] = p2;
          ++index;
        }
      }
      if (southCap) {
        index = (rowHeight - 1) * width;
        for (i = 0; i < width - 1; i++) {
          p1 = index;
          p2 = p1 + 1;
          indices[indicesIndex++] = p1;
          indices[indicesIndex++] = southIndex;
          indices[indicesIndex++] = p2;
          ++index;
        }
      }
    }

    geo.indices = indices;
    if (vertexFormat.st) {
      geo.attributes.st = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 2,
        values: textureCoordinates,
      });
    }

    return geo;
  }

  function addWallPositions(
    wallPositions,
    posIndex,
    i,
    topPositions,
    bottomPositions
  ) {
    wallPositions[posIndex++] = topPositions[i];
    wallPositions[posIndex++] = topPositions[i + 1];
    wallPositions[posIndex++] = topPositions[i + 2];
    wallPositions[posIndex++] = bottomPositions[i];
    wallPositions[posIndex++] = bottomPositions[i + 1];
    wallPositions[posIndex] = bottomPositions[i + 2];
    return wallPositions;
  }

  function addWallTextureCoordinates(wallTextures, stIndex, i, st) {
    wallTextures[stIndex++] = st[i];
    wallTextures[stIndex++] = st[i + 1];
    wallTextures[stIndex++] = st[i];
    wallTextures[stIndex] = st[i + 1];
    return wallTextures;
  }

  const scratchVertexFormat$1 = new VertexFormat();

  function constructExtrudedRectangle$1(rectangleGeometry, computedOptions) {
    const shadowVolume = rectangleGeometry._shadowVolume;
    const offsetAttributeValue = rectangleGeometry._offsetAttribute;
    const vertexFormat = rectangleGeometry._vertexFormat;
    const minHeight = rectangleGeometry._extrudedHeight;
    const maxHeight = rectangleGeometry._surfaceHeight;
    const ellipsoid = rectangleGeometry._ellipsoid;

    const height = computedOptions.height;
    const width = computedOptions.width;

    let i;

    if (shadowVolume) {
      const newVertexFormat = VertexFormat.clone(
        vertexFormat,
        scratchVertexFormat$1
      );
      newVertexFormat.normal = true;
      rectangleGeometry._vertexFormat = newVertexFormat;
    }

    const topBottomGeo = constructRectangle$1(rectangleGeometry, computedOptions);

    if (shadowVolume) {
      rectangleGeometry._vertexFormat = vertexFormat;
    }

    let topPositions = PolygonPipeline.scaleToGeodeticHeight(
      topBottomGeo.attributes.position.values,
      maxHeight,
      ellipsoid,
      false
    );
    topPositions = new Float64Array(topPositions);
    let length = topPositions.length;
    const newLength = length * 2;
    const positions = new Float64Array(newLength);
    positions.set(topPositions);
    const bottomPositions = PolygonPipeline.scaleToGeodeticHeight(
      topBottomGeo.attributes.position.values,
      minHeight,
      ellipsoid
    );
    positions.set(bottomPositions, length);
    topBottomGeo.attributes.position.values = positions;

    const normals = vertexFormat.normal ? new Float32Array(newLength) : undefined;
    const tangents = vertexFormat.tangent
      ? new Float32Array(newLength)
      : undefined;
    const bitangents = vertexFormat.bitangent
      ? new Float32Array(newLength)
      : undefined;
    const textures = vertexFormat.st
      ? new Float32Array((newLength / 3) * 2)
      : undefined;
    let topSt;
    let topNormals;
    if (vertexFormat.normal) {
      topNormals = topBottomGeo.attributes.normal.values;
      normals.set(topNormals);
      for (i = 0; i < length; i++) {
        topNormals[i] = -topNormals[i];
      }
      normals.set(topNormals, length);
      topBottomGeo.attributes.normal.values = normals;
    }
    if (shadowVolume) {
      topNormals = topBottomGeo.attributes.normal.values;
      if (!vertexFormat.normal) {
        topBottomGeo.attributes.normal = undefined;
      }
      const extrudeNormals = new Float32Array(newLength);
      for (i = 0; i < length; i++) {
        topNormals[i] = -topNormals[i];
      }
      extrudeNormals.set(topNormals, length); //only get normals for bottom layer that's going to be pushed down
      topBottomGeo.attributes.extrudeDirection = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 3,
        values: extrudeNormals,
      });
    }

    let offsetValue;
    const hasOffsets = defined(offsetAttributeValue);
    if (hasOffsets) {
      const size = (length / 3) * 2;
      let offsetAttribute = new Uint8Array(size);
      if (offsetAttributeValue === GeometryOffsetAttribute$1.TOP) {
        offsetAttribute = offsetAttribute.fill(1, 0, size / 2);
      } else {
        offsetValue =
          offsetAttributeValue === GeometryOffsetAttribute$1.NONE ? 0 : 1;
        offsetAttribute = offsetAttribute.fill(offsetValue);
      }

      topBottomGeo.attributes.applyOffset = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
        componentsPerAttribute: 1,
        values: offsetAttribute,
      });
    }

    if (vertexFormat.tangent) {
      const topTangents = topBottomGeo.attributes.tangent.values;
      tangents.set(topTangents);
      for (i = 0; i < length; i++) {
        topTangents[i] = -topTangents[i];
      }
      tangents.set(topTangents, length);
      topBottomGeo.attributes.tangent.values = tangents;
    }
    if (vertexFormat.bitangent) {
      const topBitangents = topBottomGeo.attributes.bitangent.values;
      bitangents.set(topBitangents);
      bitangents.set(topBitangents, length);
      topBottomGeo.attributes.bitangent.values = bitangents;
    }
    if (vertexFormat.st) {
      topSt = topBottomGeo.attributes.st.values;
      textures.set(topSt);
      textures.set(topSt, (length / 3) * 2);
      topBottomGeo.attributes.st.values = textures;
    }

    const indices = topBottomGeo.indices;
    const indicesLength = indices.length;
    const posLength = length / 3;
    const newIndices = IndexDatatype$1.createTypedArray(
      newLength / 3,
      indicesLength * 2
    );
    newIndices.set(indices);
    for (i = 0; i < indicesLength; i += 3) {
      newIndices[i + indicesLength] = indices[i + 2] + posLength;
      newIndices[i + 1 + indicesLength] = indices[i + 1] + posLength;
      newIndices[i + 2 + indicesLength] = indices[i] + posLength;
    }
    topBottomGeo.indices = newIndices;

    const northCap = computedOptions.northCap;
    const southCap = computedOptions.southCap;

    let rowHeight = height;
    let widthMultiplier = 2;
    let perimeterPositions = 0;
    let corners = 4;
    let dupliateCorners = 4;
    if (northCap) {
      widthMultiplier -= 1;
      rowHeight -= 1;
      perimeterPositions += 1;
      corners -= 2;
      dupliateCorners -= 1;
    }
    if (southCap) {
      widthMultiplier -= 1;
      rowHeight -= 1;
      perimeterPositions += 1;
      corners -= 2;
      dupliateCorners -= 1;
    }
    perimeterPositions += widthMultiplier * width + 2 * rowHeight - corners;

    const wallCount = (perimeterPositions + dupliateCorners) * 2;

    let wallPositions = new Float64Array(wallCount * 3);
    const wallExtrudeNormals = shadowVolume
      ? new Float32Array(wallCount * 3)
      : undefined;
    let wallOffsetAttribute = hasOffsets ? new Uint8Array(wallCount) : undefined;
    let wallTextures = vertexFormat.st
      ? new Float32Array(wallCount * 2)
      : undefined;

    const computeTopOffsets =
      offsetAttributeValue === GeometryOffsetAttribute$1.TOP;
    if (hasOffsets && !computeTopOffsets) {
      offsetValue = offsetAttributeValue === GeometryOffsetAttribute$1.ALL ? 1 : 0;
      wallOffsetAttribute = wallOffsetAttribute.fill(offsetValue);
    }

    let posIndex = 0;
    let stIndex = 0;
    let extrudeNormalIndex = 0;
    let wallOffsetIndex = 0;
    const area = width * rowHeight;
    let threeI;
    for (i = 0; i < area; i += width) {
      threeI = i * 3;
      wallPositions = addWallPositions(
        wallPositions,
        posIndex,
        threeI,
        topPositions,
        bottomPositions
      );
      posIndex += 6;
      if (vertexFormat.st) {
        wallTextures = addWallTextureCoordinates(
          wallTextures,
          stIndex,
          i * 2,
          topSt
        );
        stIndex += 4;
      }
      if (shadowVolume) {
        extrudeNormalIndex += 3;
        wallExtrudeNormals[extrudeNormalIndex++] = topNormals[threeI];
        wallExtrudeNormals[extrudeNormalIndex++] = topNormals[threeI + 1];
        wallExtrudeNormals[extrudeNormalIndex++] = topNormals[threeI + 2];
      }
      if (computeTopOffsets) {
        wallOffsetAttribute[wallOffsetIndex++] = 1;
        wallOffsetIndex += 1;
      }
    }

    if (!southCap) {
      for (i = area - width; i < area; i++) {
        threeI = i * 3;
        wallPositions = addWallPositions(
          wallPositions,
          posIndex,
          threeI,
          topPositions,
          bottomPositions
        );
        posIndex += 6;
        if (vertexFormat.st) {
          wallTextures = addWallTextureCoordinates(
            wallTextures,
            stIndex,
            i * 2,
            topSt
          );
          stIndex += 4;
        }
        if (shadowVolume) {
          extrudeNormalIndex += 3;
          wallExtrudeNormals[extrudeNormalIndex++] = topNormals[threeI];
          wallExtrudeNormals[extrudeNormalIndex++] = topNormals[threeI + 1];
          wallExtrudeNormals[extrudeNormalIndex++] = topNormals[threeI + 2];
        }
        if (computeTopOffsets) {
          wallOffsetAttribute[wallOffsetIndex++] = 1;
          wallOffsetIndex += 1;
        }
      }
    } else {
      const southIndex = northCap ? area + 1 : area;
      threeI = southIndex * 3;

      for (i = 0; i < 2; i++) {
        // duplicate corner points
        wallPositions = addWallPositions(
          wallPositions,
          posIndex,
          threeI,
          topPositions,
          bottomPositions
        );
        posIndex += 6;
        if (vertexFormat.st) {
          wallTextures = addWallTextureCoordinates(
            wallTextures,
            stIndex,
            southIndex * 2,
            topSt
          );
          stIndex += 4;
        }
        if (shadowVolume) {
          extrudeNormalIndex += 3;
          wallExtrudeNormals[extrudeNormalIndex++] = topNormals[threeI];
          wallExtrudeNormals[extrudeNormalIndex++] = topNormals[threeI + 1];
          wallExtrudeNormals[extrudeNormalIndex++] = topNormals[threeI + 2];
        }
        if (computeTopOffsets) {
          wallOffsetAttribute[wallOffsetIndex++] = 1;
          wallOffsetIndex += 1;
        }
      }
    }

    for (i = area - 1; i > 0; i -= width) {
      threeI = i * 3;
      wallPositions = addWallPositions(
        wallPositions,
        posIndex,
        threeI,
        topPositions,
        bottomPositions
      );
      posIndex += 6;
      if (vertexFormat.st) {
        wallTextures = addWallTextureCoordinates(
          wallTextures,
          stIndex,
          i * 2,
          topSt
        );
        stIndex += 4;
      }
      if (shadowVolume) {
        extrudeNormalIndex += 3;
        wallExtrudeNormals[extrudeNormalIndex++] = topNormals[threeI];
        wallExtrudeNormals[extrudeNormalIndex++] = topNormals[threeI + 1];
        wallExtrudeNormals[extrudeNormalIndex++] = topNormals[threeI + 2];
      }
      if (computeTopOffsets) {
        wallOffsetAttribute[wallOffsetIndex++] = 1;
        wallOffsetIndex += 1;
      }
    }

    if (!northCap) {
      for (i = width - 1; i >= 0; i--) {
        threeI = i * 3;
        wallPositions = addWallPositions(
          wallPositions,
          posIndex,
          threeI,
          topPositions,
          bottomPositions
        );
        posIndex += 6;
        if (vertexFormat.st) {
          wallTextures = addWallTextureCoordinates(
            wallTextures,
            stIndex,
            i * 2,
            topSt
          );
          stIndex += 4;
        }
        if (shadowVolume) {
          extrudeNormalIndex += 3;
          wallExtrudeNormals[extrudeNormalIndex++] = topNormals[threeI];
          wallExtrudeNormals[extrudeNormalIndex++] = topNormals[threeI + 1];
          wallExtrudeNormals[extrudeNormalIndex++] = topNormals[threeI + 2];
        }
        if (computeTopOffsets) {
          wallOffsetAttribute[wallOffsetIndex++] = 1;
          wallOffsetIndex += 1;
        }
      }
    } else {
      const northIndex = area;
      threeI = northIndex * 3;

      for (i = 0; i < 2; i++) {
        // duplicate corner points
        wallPositions = addWallPositions(
          wallPositions,
          posIndex,
          threeI,
          topPositions,
          bottomPositions
        );
        posIndex += 6;
        if (vertexFormat.st) {
          wallTextures = addWallTextureCoordinates(
            wallTextures,
            stIndex,
            northIndex * 2,
            topSt
          );
          stIndex += 4;
        }
        if (shadowVolume) {
          extrudeNormalIndex += 3;
          wallExtrudeNormals[extrudeNormalIndex++] = topNormals[threeI];
          wallExtrudeNormals[extrudeNormalIndex++] = topNormals[threeI + 1];
          wallExtrudeNormals[extrudeNormalIndex++] = topNormals[threeI + 2];
        }
        if (computeTopOffsets) {
          wallOffsetAttribute[wallOffsetIndex++] = 1;
          wallOffsetIndex += 1;
        }
      }
    }

    let geo = calculateAttributesWall(wallPositions, vertexFormat, ellipsoid);

    if (vertexFormat.st) {
      geo.attributes.st = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 2,
        values: wallTextures,
      });
    }
    if (shadowVolume) {
      geo.attributes.extrudeDirection = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 3,
        values: wallExtrudeNormals,
      });
    }
    if (hasOffsets) {
      geo.attributes.applyOffset = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
        componentsPerAttribute: 1,
        values: wallOffsetAttribute,
      });
    }

    const wallIndices = IndexDatatype$1.createTypedArray(
      wallCount,
      perimeterPositions * 6
    );

    let upperLeft;
    let lowerLeft;
    let lowerRight;
    let upperRight;
    length = wallPositions.length / 3;
    let index = 0;
    for (i = 0; i < length - 1; i += 2) {
      upperLeft = i;
      upperRight = (upperLeft + 2) % length;
      const p1 = Cartesian3.fromArray(wallPositions, upperLeft * 3, v1Scratch);
      const p2 = Cartesian3.fromArray(wallPositions, upperRight * 3, v2Scratch);
      if (Cartesian3.equalsEpsilon(p1, p2, CesiumMath.EPSILON10)) {
        continue;
      }
      lowerLeft = (upperLeft + 1) % length;
      lowerRight = (lowerLeft + 2) % length;
      wallIndices[index++] = upperLeft;
      wallIndices[index++] = lowerLeft;
      wallIndices[index++] = upperRight;
      wallIndices[index++] = upperRight;
      wallIndices[index++] = lowerLeft;
      wallIndices[index++] = lowerRight;
    }

    geo.indices = wallIndices;

    geo = GeometryPipeline.combineInstances([
      new GeometryInstance({
        geometry: topBottomGeo,
      }),
      new GeometryInstance({
        geometry: geo,
      }),
    ]);

    return geo[0];
  }

  const scratchRectanglePoints = [
    new Cartesian3(),
    new Cartesian3(),
    new Cartesian3(),
    new Cartesian3(),
  ];
  const nwScratch$1 = new Cartographic();
  const stNwScratch = new Cartographic();
  function computeRectangle(rectangle, granularity, rotation, ellipsoid, result) {
    if (rotation === 0.0) {
      return Rectangle.clone(rectangle, result);
    }

    const computedOptions = RectangleGeometryLibrary.computeOptions(
      rectangle,
      granularity,
      rotation,
      0,
      rectangleScratch$4,
      nwScratch$1
    );

    const height = computedOptions.height;
    const width = computedOptions.width;

    const positions = scratchRectanglePoints;
    RectangleGeometryLibrary.computePosition(
      computedOptions,
      ellipsoid,
      false,
      0,
      0,
      positions[0]
    );
    RectangleGeometryLibrary.computePosition(
      computedOptions,
      ellipsoid,
      false,
      0,
      width - 1,
      positions[1]
    );
    RectangleGeometryLibrary.computePosition(
      computedOptions,
      ellipsoid,
      false,
      height - 1,
      0,
      positions[2]
    );
    RectangleGeometryLibrary.computePosition(
      computedOptions,
      ellipsoid,
      false,
      height - 1,
      width - 1,
      positions[3]
    );

    return Rectangle.fromCartesianArray(positions, ellipsoid, result);
  }

  /**
   * A description of a cartographic rectangle on an ellipsoid centered at the origin. Rectangle geometry can be rendered with both {@link Primitive} and {@link GroundPrimitive}.
   *
   * @alias RectangleGeometry
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Rectangle} options.rectangle A cartographic rectangle with north, south, east and west properties in radians.
   * @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the rectangle lies.
   * @param {Number} [options.granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
   * @param {Number} [options.height=0.0] The distance in meters between the rectangle and the ellipsoid surface.
   * @param {Number} [options.rotation=0.0] The rotation of the rectangle, in radians. A positive rotation is counter-clockwise.
   * @param {Number} [options.stRotation=0.0] The rotation of the texture coordinates, in radians. A positive rotation is counter-clockwise.
   * @param {Number} [options.extrudedHeight] The distance in meters between the rectangle's extruded face and the ellipsoid surface.
   *
   * @exception {DeveloperError} <code>options.rectangle.north</code> must be in the interval [<code>-Pi/2</code>, <code>Pi/2</code>].
   * @exception {DeveloperError} <code>options.rectangle.south</code> must be in the interval [<code>-Pi/2</code>, <code>Pi/2</code>].
   * @exception {DeveloperError} <code>options.rectangle.east</code> must be in the interval [<code>-Pi</code>, <code>Pi</code>].
   * @exception {DeveloperError} <code>options.rectangle.west</code> must be in the interval [<code>-Pi</code>, <code>Pi</code>].
   * @exception {DeveloperError} <code>options.rectangle.north</code> must be greater than <code>options.rectangle.south</code>.
   *
   * @see RectangleGeometry#createGeometry
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Rectangle.html|Cesium Sandcastle Rectangle Demo}
   *
   * @example
   * // 1. create a rectangle
   * const rectangle = new Cesium.RectangleGeometry({
   *   ellipsoid : Cesium.Ellipsoid.WGS84,
   *   rectangle : Cesium.Rectangle.fromDegrees(-80.0, 39.0, -74.0, 42.0),
   *   height : 10000.0
   * });
   * const geometry = Cesium.RectangleGeometry.createGeometry(rectangle);
   *
   * // 2. create an extruded rectangle without a top
   * const rectangle = new Cesium.RectangleGeometry({
   *   ellipsoid : Cesium.Ellipsoid.WGS84,
   *   rectangle : Cesium.Rectangle.fromDegrees(-80.0, 39.0, -74.0, 42.0),
   *   height : 10000.0,
   *   extrudedHeight: 300000
   * });
   * const geometry = Cesium.RectangleGeometry.createGeometry(rectangle);
   */
  function RectangleGeometry(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const rectangle = options.rectangle;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("rectangle", rectangle);
    Rectangle.validate(rectangle);
    if (rectangle.north < rectangle.south) {
      throw new DeveloperError(
        "options.rectangle.north must be greater than or equal to options.rectangle.south"
      );
    }
    //>>includeEnd('debug');

    const height = defaultValue(options.height, 0.0);
    const extrudedHeight = defaultValue(options.extrudedHeight, height);

    this._rectangle = Rectangle.clone(rectangle);
    this._granularity = defaultValue(
      options.granularity,
      CesiumMath.RADIANS_PER_DEGREE
    );
    this._ellipsoid = Ellipsoid.clone(
      defaultValue(options.ellipsoid, Ellipsoid.WGS84)
    );
    this._surfaceHeight = Math.max(height, extrudedHeight);
    this._rotation = defaultValue(options.rotation, 0.0);
    this._stRotation = defaultValue(options.stRotation, 0.0);
    this._vertexFormat = VertexFormat.clone(
      defaultValue(options.vertexFormat, VertexFormat.DEFAULT)
    );
    this._extrudedHeight = Math.min(height, extrudedHeight);
    this._shadowVolume = defaultValue(options.shadowVolume, false);
    this._workerName = "createRectangleGeometry";
    this._offsetAttribute = options.offsetAttribute;
    this._rotatedRectangle = undefined;

    this._textureCoordinateRotationPoints = undefined;
  }

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  RectangleGeometry.packedLength =
    Rectangle.packedLength +
    Ellipsoid.packedLength +
    VertexFormat.packedLength +
    7;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {RectangleGeometry} 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
   */
  RectangleGeometry.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    Rectangle.pack(value._rectangle, array, startingIndex);
    startingIndex += Rectangle.packedLength;

    Ellipsoid.pack(value._ellipsoid, array, startingIndex);
    startingIndex += Ellipsoid.packedLength;

    VertexFormat.pack(value._vertexFormat, array, startingIndex);
    startingIndex += VertexFormat.packedLength;

    array[startingIndex++] = value._granularity;
    array[startingIndex++] = value._surfaceHeight;
    array[startingIndex++] = value._rotation;
    array[startingIndex++] = value._stRotation;
    array[startingIndex++] = value._extrudedHeight;
    array[startingIndex++] = value._shadowVolume ? 1.0 : 0.0;
    array[startingIndex] = defaultValue(value._offsetAttribute, -1);

    return array;
  };

  const scratchRectangle$8 = new Rectangle();
  const scratchEllipsoid$4 = Ellipsoid.clone(Ellipsoid.UNIT_SPHERE);
  const scratchOptions$5 = {
    rectangle: scratchRectangle$8,
    ellipsoid: scratchEllipsoid$4,
    vertexFormat: scratchVertexFormat$1,
    granularity: undefined,
    height: undefined,
    rotation: undefined,
    stRotation: undefined,
    extrudedHeight: undefined,
    shadowVolume: undefined,
    offsetAttribute: undefined,
  };

  /**
   * 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 {RectangleGeometry} [result] The object into which to store the result.
   * @returns {RectangleGeometry} The modified result parameter or a new RectangleGeometry instance if one was not provided.
   */
  RectangleGeometry.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("array", array);
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    const rectangle = Rectangle.unpack(array, startingIndex, scratchRectangle$8);
    startingIndex += Rectangle.packedLength;

    const ellipsoid = Ellipsoid.unpack(array, startingIndex, scratchEllipsoid$4);
    startingIndex += Ellipsoid.packedLength;

    const vertexFormat = VertexFormat.unpack(
      array,
      startingIndex,
      scratchVertexFormat$1
    );
    startingIndex += VertexFormat.packedLength;

    const granularity = array[startingIndex++];
    const surfaceHeight = array[startingIndex++];
    const rotation = array[startingIndex++];
    const stRotation = array[startingIndex++];
    const extrudedHeight = array[startingIndex++];
    const shadowVolume = array[startingIndex++] === 1.0;
    const offsetAttribute = array[startingIndex];

    if (!defined(result)) {
      scratchOptions$5.granularity = granularity;
      scratchOptions$5.height = surfaceHeight;
      scratchOptions$5.rotation = rotation;
      scratchOptions$5.stRotation = stRotation;
      scratchOptions$5.extrudedHeight = extrudedHeight;
      scratchOptions$5.shadowVolume = shadowVolume;
      scratchOptions$5.offsetAttribute =
        offsetAttribute === -1 ? undefined : offsetAttribute;

      return new RectangleGeometry(scratchOptions$5);
    }

    result._rectangle = Rectangle.clone(rectangle, result._rectangle);
    result._ellipsoid = Ellipsoid.clone(ellipsoid, result._ellipsoid);
    result._vertexFormat = VertexFormat.clone(vertexFormat, result._vertexFormat);
    result._granularity = granularity;
    result._surfaceHeight = surfaceHeight;
    result._rotation = rotation;
    result._stRotation = stRotation;
    result._extrudedHeight = extrudedHeight;
    result._shadowVolume = shadowVolume;
    result._offsetAttribute =
      offsetAttribute === -1 ? undefined : offsetAttribute;

    return result;
  };

  /**
   * Computes the bounding rectangle based on the provided options
   *
   * @param {Object} options Object with the following properties:
   * @param {Rectangle} options.rectangle A cartographic rectangle with north, south, east and west properties in radians.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the rectangle lies.
   * @param {Number} [options.granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
   * @param {Number} [options.rotation=0.0] The rotation of the rectangle, in radians. A positive rotation is counter-clockwise.
   * @param {Rectangle} [result] An object in which to store the result.
   *
   * @returns {Rectangle} The result rectangle
   */
  RectangleGeometry.computeRectangle = function (options, result) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const rectangle = options.rectangle;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("rectangle", rectangle);
    Rectangle.validate(rectangle);
    if (rectangle.north < rectangle.south) {
      throw new DeveloperError(
        "options.rectangle.north must be greater than or equal to options.rectangle.south"
      );
    }
    //>>includeEnd('debug');

    const granularity = defaultValue(
      options.granularity,
      CesiumMath.RADIANS_PER_DEGREE
    );
    const ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);
    const rotation = defaultValue(options.rotation, 0.0);

    return computeRectangle(rectangle, granularity, rotation, ellipsoid, result);
  };

  const tangentRotationMatrixScratch = new Matrix3();
  const quaternionScratch = new Quaternion();
  const centerScratch$2 = new Cartographic();
  /**
   * Computes the geometric representation of a rectangle, including its vertices, indices, and a bounding sphere.
   *
   * @param {RectangleGeometry} rectangleGeometry A description of the rectangle.
   * @returns {Geometry|undefined} The computed vertices and indices.
   *
   * @exception {DeveloperError} Rotated rectangle is invalid.
   */
  RectangleGeometry.createGeometry = function (rectangleGeometry) {
    if (
      CesiumMath.equalsEpsilon(
        rectangleGeometry._rectangle.north,
        rectangleGeometry._rectangle.south,
        CesiumMath.EPSILON10
      ) ||
      CesiumMath.equalsEpsilon(
        rectangleGeometry._rectangle.east,
        rectangleGeometry._rectangle.west,
        CesiumMath.EPSILON10
      )
    ) {
      return undefined;
    }

    let rectangle = rectangleGeometry._rectangle;
    const ellipsoid = rectangleGeometry._ellipsoid;
    const rotation = rectangleGeometry._rotation;
    const stRotation = rectangleGeometry._stRotation;
    const vertexFormat = rectangleGeometry._vertexFormat;

    const computedOptions = RectangleGeometryLibrary.computeOptions(
      rectangle,
      rectangleGeometry._granularity,
      rotation,
      stRotation,
      rectangleScratch$4,
      nwScratch$1,
      stNwScratch
    );

    const tangentRotationMatrix = tangentRotationMatrixScratch;
    if (stRotation !== 0 || rotation !== 0) {
      const center = Rectangle.center(rectangle, centerScratch$2);
      const axis = ellipsoid.geodeticSurfaceNormalCartographic(center, v1Scratch);
      Quaternion.fromAxisAngle(axis, -stRotation, quaternionScratch);
      Matrix3.fromQuaternion(quaternionScratch, tangentRotationMatrix);
    } else {
      Matrix3.clone(Matrix3.IDENTITY, tangentRotationMatrix);
    }

    const surfaceHeight = rectangleGeometry._surfaceHeight;
    const extrudedHeight = rectangleGeometry._extrudedHeight;
    const extrude = !CesiumMath.equalsEpsilon(
      surfaceHeight,
      extrudedHeight,
      0,
      CesiumMath.EPSILON2
    );

    computedOptions.lonScalar = 1.0 / rectangleGeometry._rectangle.width;
    computedOptions.latScalar = 1.0 / rectangleGeometry._rectangle.height;
    computedOptions.tangentRotationMatrix = tangentRotationMatrix;

    let geometry;
    let boundingSphere;
    rectangle = rectangleGeometry._rectangle;
    if (extrude) {
      geometry = constructExtrudedRectangle$1(rectangleGeometry, computedOptions);
      const topBS = BoundingSphere.fromRectangle3D(
        rectangle,
        ellipsoid,
        surfaceHeight,
        topBoundingSphere$1
      );
      const bottomBS = BoundingSphere.fromRectangle3D(
        rectangle,
        ellipsoid,
        extrudedHeight,
        bottomBoundingSphere$1
      );
      boundingSphere = BoundingSphere.union(topBS, bottomBS);
    } else {
      geometry = constructRectangle$1(rectangleGeometry, computedOptions);
      geometry.attributes.position.values = PolygonPipeline.scaleToGeodeticHeight(
        geometry.attributes.position.values,
        surfaceHeight,
        ellipsoid,
        false
      );

      if (defined(rectangleGeometry._offsetAttribute)) {
        const length = geometry.attributes.position.values.length;
        const offsetValue =
          rectangleGeometry._offsetAttribute === GeometryOffsetAttribute$1.NONE
            ? 0
            : 1;
        const applyOffset = new Uint8Array(length / 3).fill(offsetValue);
        geometry.attributes.applyOffset = new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
          componentsPerAttribute: 1,
          values: applyOffset,
        });
      }

      boundingSphere = BoundingSphere.fromRectangle3D(
        rectangle,
        ellipsoid,
        surfaceHeight
      );
    }

    if (!vertexFormat.position) {
      delete geometry.attributes.position;
    }

    return new Geometry({
      attributes: geometry.attributes,
      indices: geometry.indices,
      primitiveType: geometry.primitiveType,
      boundingSphere: boundingSphere,
      offsetAttribute: rectangleGeometry._offsetAttribute,
    });
  };

  /**
   * @private
   */
  RectangleGeometry.createShadowVolume = function (
    rectangleGeometry,
    minHeightFunc,
    maxHeightFunc
  ) {
    const granularity = rectangleGeometry._granularity;
    const ellipsoid = rectangleGeometry._ellipsoid;

    const minHeight = minHeightFunc(granularity, ellipsoid);
    const maxHeight = maxHeightFunc(granularity, ellipsoid);

    return new RectangleGeometry({
      rectangle: rectangleGeometry._rectangle,
      rotation: rectangleGeometry._rotation,
      ellipsoid: ellipsoid,
      stRotation: rectangleGeometry._stRotation,
      granularity: granularity,
      extrudedHeight: maxHeight,
      height: minHeight,
      vertexFormat: VertexFormat.POSITION_ONLY,
      shadowVolume: true,
    });
  };

  const unrotatedTextureRectangleScratch = new Rectangle();
  const points2DScratch$1 = [new Cartesian2(), new Cartesian2(), new Cartesian2()];
  const rotation2DScratch = new Matrix2();
  const rectangleCenterScratch$2 = new Cartographic();

  function textureCoordinateRotationPoints(rectangleGeometry) {
    if (rectangleGeometry._stRotation === 0.0) {
      return [0, 0, 0, 1, 1, 0];
    }

    const rectangle = Rectangle.clone(
      rectangleGeometry._rectangle,
      unrotatedTextureRectangleScratch
    );
    const granularity = rectangleGeometry._granularity;
    const ellipsoid = rectangleGeometry._ellipsoid;

    // Rotate to align the texture coordinates with ENU
    const rotation = rectangleGeometry._rotation - rectangleGeometry._stRotation;

    const unrotatedTextureRectangle = computeRectangle(
      rectangle,
      granularity,
      rotation,
      ellipsoid,
      unrotatedTextureRectangleScratch
    );

    // Assume a computed "east-north" texture coordinate system based on spherical or planar tricks, bounded by `boundingRectangle`.
    // The "desired" texture coordinate system forms an oriented rectangle (un-oriented computed) around the geometry that completely and tightly bounds it.
    // We want to map from the "east-north" texture coordinate system into the "desired" system using a pair of lines (analagous planes in 2D)
    // Compute 3 corners of the "desired" texture coordinate system in "east-north" texture space by the following in cartographic space:
    // - rotate 3 of the corners in unrotatedTextureRectangle by stRotation around the center of the bounding rectangle
    // - apply the "east-north" system's normalization formula to the rotated cartographics, even though this is likely to produce values outside [0-1].
    // This gives us a set of points in the "east-north" texture coordinate system that can be used to map "east-north" texture coordinates to "desired."

    const points2D = points2DScratch$1;
    points2D[0].x = unrotatedTextureRectangle.west;
    points2D[0].y = unrotatedTextureRectangle.south;

    points2D[1].x = unrotatedTextureRectangle.west;
    points2D[1].y = unrotatedTextureRectangle.north;

    points2D[2].x = unrotatedTextureRectangle.east;
    points2D[2].y = unrotatedTextureRectangle.south;

    const boundingRectangle = rectangleGeometry.rectangle;
    const toDesiredInComputed = Matrix2.fromRotation(
      rectangleGeometry._stRotation,
      rotation2DScratch
    );
    const boundingRectangleCenter = Rectangle.center(
      boundingRectangle,
      rectangleCenterScratch$2
    );

    for (let i = 0; i < 3; ++i) {
      const point2D = points2D[i];
      point2D.x -= boundingRectangleCenter.longitude;
      point2D.y -= boundingRectangleCenter.latitude;
      Matrix2.multiplyByVector(toDesiredInComputed, point2D, point2D);
      point2D.x += boundingRectangleCenter.longitude;
      point2D.y += boundingRectangleCenter.latitude;

      // Convert point into east-north texture coordinate space
      point2D.x = (point2D.x - boundingRectangle.west) / boundingRectangle.width;
      point2D.y =
        (point2D.y - boundingRectangle.south) / boundingRectangle.height;
    }

    const minXYCorner = points2D[0];
    const maxYCorner = points2D[1];
    const maxXCorner = points2D[2];
    const result = new Array(6);
    Cartesian2.pack(minXYCorner, result);
    Cartesian2.pack(maxYCorner, result, 2);
    Cartesian2.pack(maxXCorner, result, 4);
    return result;
  }

  Object.defineProperties(RectangleGeometry.prototype, {
    /**
     * @private
     */
    rectangle: {
      get: function () {
        if (!defined(this._rotatedRectangle)) {
          this._rotatedRectangle = computeRectangle(
            this._rectangle,
            this._granularity,
            this._rotation,
            this._ellipsoid
          );
        }
        return this._rotatedRectangle;
      },
    },
    /**
     * For remapping texture coordinates when rendering RectangleGeometries as GroundPrimitives.
     * This version permits skew in textures by computing offsets directly in cartographic space and
     * more accurately approximates rendering RectangleGeometries with height as standard Primitives.
     * @see Geometry#_textureCoordinateRotationPoints
     * @private
     */
    textureCoordinateRotationPoints: {
      get: function () {
        if (!defined(this._textureCoordinateRotationPoints)) {
          this._textureCoordinateRotationPoints = textureCoordinateRotationPoints(
            this
          );
        }
        return this._textureCoordinateRotationPoints;
      },
    },
  });

  const bottomBoundingSphere = new BoundingSphere();
  const topBoundingSphere = new BoundingSphere();
  const positionScratch$a = new Cartesian3();
  const rectangleScratch$3 = new Rectangle();

  function constructRectangle(geometry, computedOptions) {
    const ellipsoid = geometry._ellipsoid;
    const height = computedOptions.height;
    const width = computedOptions.width;
    const northCap = computedOptions.northCap;
    const southCap = computedOptions.southCap;

    let rowHeight = height;
    let widthMultiplier = 2;
    let size = 0;
    let corners = 4;
    if (northCap) {
      widthMultiplier -= 1;
      rowHeight -= 1;
      size += 1;
      corners -= 2;
    }
    if (southCap) {
      widthMultiplier -= 1;
      rowHeight -= 1;
      size += 1;
      corners -= 2;
    }
    size += widthMultiplier * width + 2 * rowHeight - corners;

    const positions = new Float64Array(size * 3);

    let posIndex = 0;
    let row = 0;
    let col;
    const position = positionScratch$a;
    if (northCap) {
      RectangleGeometryLibrary.computePosition(
        computedOptions,
        ellipsoid,
        false,
        row,
        0,
        position
      );
      positions[posIndex++] = position.x;
      positions[posIndex++] = position.y;
      positions[posIndex++] = position.z;
    } else {
      for (col = 0; col < width; col++) {
        RectangleGeometryLibrary.computePosition(
          computedOptions,
          ellipsoid,
          false,
          row,
          col,
          position
        );
        positions[posIndex++] = position.x;
        positions[posIndex++] = position.y;
        positions[posIndex++] = position.z;
      }
    }

    col = width - 1;
    for (row = 1; row < height; row++) {
      RectangleGeometryLibrary.computePosition(
        computedOptions,
        ellipsoid,
        false,
        row,
        col,
        position
      );
      positions[posIndex++] = position.x;
      positions[posIndex++] = position.y;
      positions[posIndex++] = position.z;
    }

    row = height - 1;
    if (!southCap) {
      // if southCap is true, we dont need to add any more points because the south pole point was added by the iteration above
      for (col = width - 2; col >= 0; col--) {
        RectangleGeometryLibrary.computePosition(
          computedOptions,
          ellipsoid,
          false,
          row,
          col,
          position
        );
        positions[posIndex++] = position.x;
        positions[posIndex++] = position.y;
        positions[posIndex++] = position.z;
      }
    }

    col = 0;
    for (row = height - 2; row > 0; row--) {
      RectangleGeometryLibrary.computePosition(
        computedOptions,
        ellipsoid,
        false,
        row,
        col,
        position
      );
      positions[posIndex++] = position.x;
      positions[posIndex++] = position.y;
      positions[posIndex++] = position.z;
    }

    const indicesSize = (positions.length / 3) * 2;
    const indices = IndexDatatype$1.createTypedArray(
      positions.length / 3,
      indicesSize
    );

    let index = 0;
    for (let i = 0; i < positions.length / 3 - 1; i++) {
      indices[index++] = i;
      indices[index++] = i + 1;
    }
    indices[index++] = positions.length / 3 - 1;
    indices[index++] = 0;

    const geo = new Geometry({
      attributes: new GeometryAttributes(),
      primitiveType: PrimitiveType$1.LINES,
    });

    geo.attributes.position = new GeometryAttribute({
      componentDatatype: ComponentDatatype$1.DOUBLE,
      componentsPerAttribute: 3,
      values: positions,
    });
    geo.indices = indices;

    return geo;
  }

  function constructExtrudedRectangle(rectangleGeometry, computedOptions) {
    const surfaceHeight = rectangleGeometry._surfaceHeight;
    const extrudedHeight = rectangleGeometry._extrudedHeight;
    const ellipsoid = rectangleGeometry._ellipsoid;
    const minHeight = extrudedHeight;
    const maxHeight = surfaceHeight;
    const geo = constructRectangle(rectangleGeometry, computedOptions);

    const height = computedOptions.height;
    const width = computedOptions.width;

    const topPositions = PolygonPipeline.scaleToGeodeticHeight(
      geo.attributes.position.values,
      maxHeight,
      ellipsoid,
      false
    );
    let length = topPositions.length;
    const positions = new Float64Array(length * 2);
    positions.set(topPositions);
    const bottomPositions = PolygonPipeline.scaleToGeodeticHeight(
      geo.attributes.position.values,
      minHeight,
      ellipsoid
    );
    positions.set(bottomPositions, length);
    geo.attributes.position.values = positions;

    const northCap = computedOptions.northCap;
    const southCap = computedOptions.southCap;
    let corners = 4;
    if (northCap) {
      corners -= 1;
    }
    if (southCap) {
      corners -= 1;
    }

    const indicesSize = (positions.length / 3 + corners) * 2;
    const indices = IndexDatatype$1.createTypedArray(
      positions.length / 3,
      indicesSize
    );
    length = positions.length / 6;
    let index = 0;
    for (let i = 0; i < length - 1; i++) {
      indices[index++] = i;
      indices[index++] = i + 1;
      indices[index++] = i + length;
      indices[index++] = i + length + 1;
    }
    indices[index++] = length - 1;
    indices[index++] = 0;
    indices[index++] = length + length - 1;
    indices[index++] = length;

    indices[index++] = 0;
    indices[index++] = length;

    let bottomCorner;
    if (northCap) {
      bottomCorner = height - 1;
    } else {
      const topRightCorner = width - 1;
      indices[index++] = topRightCorner;
      indices[index++] = topRightCorner + length;
      bottomCorner = width + height - 2;
    }

    indices[index++] = bottomCorner;
    indices[index++] = bottomCorner + length;

    if (!southCap) {
      const bottomLeftCorner = width + bottomCorner - 1;
      indices[index++] = bottomLeftCorner;
      indices[index] = bottomLeftCorner + length;
    }

    geo.indices = indices;

    return geo;
  }

  /**
   * A description of the outline of a a cartographic rectangle on an ellipsoid centered at the origin.
   *
   * @alias RectangleOutlineGeometry
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Rectangle} options.rectangle A cartographic rectangle with north, south, east and west properties in radians.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the rectangle lies.
   * @param {Number} [options.granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
   * @param {Number} [options.height=0.0] The distance in meters between the rectangle and the ellipsoid surface.
   * @param {Number} [options.rotation=0.0] The rotation of the rectangle, in radians. A positive rotation is counter-clockwise.
   * @param {Number} [options.extrudedHeight] The distance in meters between the rectangle's extruded face and the ellipsoid surface.
   *
   * @exception {DeveloperError} <code>options.rectangle.north</code> must be in the interval [<code>-Pi/2</code>, <code>Pi/2</code>].
   * @exception {DeveloperError} <code>options.rectangle.south</code> must be in the interval [<code>-Pi/2</code>, <code>Pi/2</code>].
   * @exception {DeveloperError} <code>options.rectangle.east</code> must be in the interval [<code>-Pi</code>, <code>Pi</code>].
   * @exception {DeveloperError} <code>options.rectangle.west</code> must be in the interval [<code>-Pi</code>, <code>Pi</code>].
   * @exception {DeveloperError} <code>options.rectangle.north</code> must be greater than <code>rectangle.south</code>.
   *
   * @see RectangleOutlineGeometry#createGeometry
   *
   * @example
   * const rectangle = new Cesium.RectangleOutlineGeometry({
   *   ellipsoid : Cesium.Ellipsoid.WGS84,
   *   rectangle : Cesium.Rectangle.fromDegrees(-80.0, 39.0, -74.0, 42.0),
   *   height : 10000.0
   * });
   * const geometry = Cesium.RectangleOutlineGeometry.createGeometry(rectangle);
   */
  function RectangleOutlineGeometry(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const rectangle = options.rectangle;
    const granularity = defaultValue(
      options.granularity,
      CesiumMath.RADIANS_PER_DEGREE
    );
    const ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);
    const rotation = defaultValue(options.rotation, 0.0);

    //>>includeStart('debug', pragmas.debug);
    if (!defined(rectangle)) {
      throw new DeveloperError("rectangle is required.");
    }
    Rectangle.validate(rectangle);
    if (rectangle.north < rectangle.south) {
      throw new DeveloperError(
        "options.rectangle.north must be greater than options.rectangle.south"
      );
    }
    //>>includeEnd('debug');

    const height = defaultValue(options.height, 0.0);
    const extrudedHeight = defaultValue(options.extrudedHeight, height);

    this._rectangle = Rectangle.clone(rectangle);
    this._granularity = granularity;
    this._ellipsoid = ellipsoid;
    this._surfaceHeight = Math.max(height, extrudedHeight);
    this._rotation = rotation;
    this._extrudedHeight = Math.min(height, extrudedHeight);
    this._offsetAttribute = options.offsetAttribute;
    this._workerName = "createRectangleOutlineGeometry";
  }

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  RectangleOutlineGeometry.packedLength =
    Rectangle.packedLength + Ellipsoid.packedLength + 5;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {RectangleOutlineGeometry} 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
   */
  RectangleOutlineGeometry.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(value)) {
      throw new DeveloperError("value is required");
    }

    if (!defined(array)) {
      throw new DeveloperError("array is required");
    }
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    Rectangle.pack(value._rectangle, array, startingIndex);
    startingIndex += Rectangle.packedLength;

    Ellipsoid.pack(value._ellipsoid, array, startingIndex);
    startingIndex += Ellipsoid.packedLength;

    array[startingIndex++] = value._granularity;
    array[startingIndex++] = value._surfaceHeight;
    array[startingIndex++] = value._rotation;
    array[startingIndex++] = value._extrudedHeight;
    array[startingIndex] = defaultValue(value._offsetAttribute, -1);

    return array;
  };

  const scratchRectangle$7 = new Rectangle();
  const scratchEllipsoid$3 = Ellipsoid.clone(Ellipsoid.UNIT_SPHERE);
  const scratchOptions$4 = {
    rectangle: scratchRectangle$7,
    ellipsoid: scratchEllipsoid$3,
    granularity: undefined,
    height: undefined,
    rotation: undefined,
    extrudedHeight: undefined,
    offsetAttribute: undefined,
  };

  /**
   * 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 {RectangleOutlineGeometry} [result] The object into which to store the result.
   * @returns {RectangleOutlineGeometry} The modified result parameter or a new Quaternion instance if one was not provided.
   */
  RectangleOutlineGeometry.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(array)) {
      throw new DeveloperError("array is required");
    }
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    const rectangle = Rectangle.unpack(array, startingIndex, scratchRectangle$7);
    startingIndex += Rectangle.packedLength;

    const ellipsoid = Ellipsoid.unpack(array, startingIndex, scratchEllipsoid$3);
    startingIndex += Ellipsoid.packedLength;

    const granularity = array[startingIndex++];
    const height = array[startingIndex++];
    const rotation = array[startingIndex++];
    const extrudedHeight = array[startingIndex++];
    const offsetAttribute = array[startingIndex];

    if (!defined(result)) {
      scratchOptions$4.granularity = granularity;
      scratchOptions$4.height = height;
      scratchOptions$4.rotation = rotation;
      scratchOptions$4.extrudedHeight = extrudedHeight;
      scratchOptions$4.offsetAttribute =
        offsetAttribute === -1 ? undefined : offsetAttribute;

      return new RectangleOutlineGeometry(scratchOptions$4);
    }

    result._rectangle = Rectangle.clone(rectangle, result._rectangle);
    result._ellipsoid = Ellipsoid.clone(ellipsoid, result._ellipsoid);
    result._surfaceHeight = height;
    result._rotation = rotation;
    result._extrudedHeight = extrudedHeight;
    result._offsetAttribute =
      offsetAttribute === -1 ? undefined : offsetAttribute;

    return result;
  };

  const nwScratch = new Cartographic();
  /**
   * Computes the geometric representation of an outline of a rectangle, including its vertices, indices, and a bounding sphere.
   *
   * @param {RectangleOutlineGeometry} rectangleGeometry A description of the rectangle outline.
   * @returns {Geometry|undefined} The computed vertices and indices.
   *
   * @exception {DeveloperError} Rotated rectangle is invalid.
   */
  RectangleOutlineGeometry.createGeometry = function (rectangleGeometry) {
    const rectangle = rectangleGeometry._rectangle;
    const ellipsoid = rectangleGeometry._ellipsoid;
    const computedOptions = RectangleGeometryLibrary.computeOptions(
      rectangle,
      rectangleGeometry._granularity,
      rectangleGeometry._rotation,
      0,
      rectangleScratch$3,
      nwScratch
    );

    let geometry;
    let boundingSphere;

    if (
      CesiumMath.equalsEpsilon(
        rectangle.north,
        rectangle.south,
        CesiumMath.EPSILON10
      ) ||
      CesiumMath.equalsEpsilon(
        rectangle.east,
        rectangle.west,
        CesiumMath.EPSILON10
      )
    ) {
      return undefined;
    }

    const surfaceHeight = rectangleGeometry._surfaceHeight;
    const extrudedHeight = rectangleGeometry._extrudedHeight;
    const extrude = !CesiumMath.equalsEpsilon(
      surfaceHeight,
      extrudedHeight,
      0,
      CesiumMath.EPSILON2
    );
    let offsetValue;
    if (extrude) {
      geometry = constructExtrudedRectangle(rectangleGeometry, computedOptions);
      if (defined(rectangleGeometry._offsetAttribute)) {
        const size = geometry.attributes.position.values.length / 3;
        let offsetAttribute = new Uint8Array(size);
        if (rectangleGeometry._offsetAttribute === GeometryOffsetAttribute$1.TOP) {
          offsetAttribute = offsetAttribute.fill(1, 0, size / 2);
        } else {
          offsetValue =
            rectangleGeometry._offsetAttribute === GeometryOffsetAttribute$1.NONE
              ? 0
              : 1;
          offsetAttribute = offsetAttribute.fill(offsetValue);
        }

        geometry.attributes.applyOffset = new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
          componentsPerAttribute: 1,
          values: offsetAttribute,
        });
      }
      const topBS = BoundingSphere.fromRectangle3D(
        rectangle,
        ellipsoid,
        surfaceHeight,
        topBoundingSphere
      );
      const bottomBS = BoundingSphere.fromRectangle3D(
        rectangle,
        ellipsoid,
        extrudedHeight,
        bottomBoundingSphere
      );
      boundingSphere = BoundingSphere.union(topBS, bottomBS);
    } else {
      geometry = constructRectangle(rectangleGeometry, computedOptions);
      geometry.attributes.position.values = PolygonPipeline.scaleToGeodeticHeight(
        geometry.attributes.position.values,
        surfaceHeight,
        ellipsoid,
        false
      );

      if (defined(rectangleGeometry._offsetAttribute)) {
        const length = geometry.attributes.position.values.length;
        offsetValue =
          rectangleGeometry._offsetAttribute === GeometryOffsetAttribute$1.NONE
            ? 0
            : 1;
        const applyOffset = new Uint8Array(length / 3).fill(offsetValue);
        geometry.attributes.applyOffset = new GeometryAttribute({
          componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
          componentsPerAttribute: 1,
          values: applyOffset,
        });
      }

      boundingSphere = BoundingSphere.fromRectangle3D(
        rectangle,
        ellipsoid,
        surfaceHeight
      );
    }

    return new Geometry({
      attributes: geometry.attributes,
      indices: geometry.indices,
      primitiveType: PrimitiveType$1.LINES,
      boundingSphere: boundingSphere,
      offsetAttribute: rectangleGeometry._offsetAttribute,
    });
  };

  /**
   * Constants for identifying well-known reference frames.
   *
   * @enum {Number}
   */
  const ReferenceFrame = {
    /**
     * The fixed frame.
     *
     * @type {Number}
     * @constant
     */
    FIXED: 0,

    /**
     * The inertial frame.
     *
     * @type {Number}
     * @constant
     */
    INERTIAL: 1,
  };
  var ReferenceFrame$1 = Object.freeze(ReferenceFrame);

  /* eslint-disable new-cap */

  /**
   * S2
   * --
   *
   * This implementation is based on the S2 C++ reference implementation: https://github.com/google/s2geometry
   *
   *
   * Overview:
   * ---------
   * The S2 library decomposes the unit sphere into a hierarchy of cells. A cell is a quadrilateral bounded by 4 geodesics.
   * The 6 root cells are obtained by projecting the six faces of a cube on a unit sphere. Each root cell follows a quadtree
   * subdivision scheme, i.e. each cell subdivides into 4 smaller cells that cover the same area as the parent cell. The S2 cell
   * hierarchy extends from level 0 (root cells) to level 30 (leaf cells). The root cells are rotated to enable a continuous Hilbert
   * curve to map all 6 faces of the cube.
   *
   *
   * Cell ID:
   * --------
   * Each cell in S2 can be uniquely identified using a 64-bit unsigned integer, its cell ID. The first 3 bits of the cell ID are the face bits, i.e.
   * they indicate which of the 6 faces of the cube a cell lies on. After the face bits are the position bits, i.e. they indicate the position
   * of the cell along the Hilbert curve. After the positions bits is the sentinel bit, which is always set to 1, and it indicates the level of the
   * cell. Again, the level can be between 0 and 30 in S2.
   *
   *   Note: In the illustration below, the face bits are marked with 'f', the position bits are marked with 'p', the zero bits are marked with '-'.
   *
   *   Cell ID (base 10): 3170534137668829184
   *   Cell ID (base 2) : 0010110000000000000000000000000000000000000000000000000000000000
   *
   *   001 0110000000000000000000000000000000000000000000000000000000000
   *   fff pps----------------------------------------------------------
   *
   * For the cell above, we can see that it lies on face 1 (01), with a Hilbert index of 1 (1).
   *
   *
   * Cell Subdivision:
   * ------------------
   * Cells in S2 subdivide recursively using quadtree subdivision. For each cell, you can get a child of index [0-3]. To compute the child at index i,
   * insert the base 2 representation of i to the right of the parent's position bits. Ensure that the sentinel bit is also shifted two places to the right.
   *
   *   Parent Cell ID (base 10) : 3170534137668829184
   *   Parent Cell ID (base 2)  : 0010110000000000000000000000000000000000000000000000000000000000
   *
   *   001 0110000000000000000000000000000000000000000000000000000000000
   *   fff pps----------------------------------------------------------
   *
   *   To get the 3rd child of the cell above, we insert the binary representation of 3 to the right of the parent's position bits:
   *
   *   Note: In the illustration below, the bits to be added are highlighted with '^'.
   *
   *   001 0111100000000000000000000000000000000000000000000000000000000
   *   fff pppps--------------------------------------------------------
   *         ^^
   *
   *   Child(3) Cell ID (base 10) : 3386706919782612992
   *   Child(3) Cell ID (base 2)  : 0010111100000000000000000000000000000000000000000000000000000000
   *
   * Cell Token:
   * -----------
   * To provide a more concise representation of the S2 cell ID, we can use their hexadecimal representation.
   *
   *   Cell ID (base 10): 3170534137668829184
   *   Cell ID (base 2) : 0010110000000000000000000000000000000000000000000000000000000000
   *
   *   We remove all trailing zero bits, until we reach the nybble (4 bits) that contains the sentinel bit.
   *
   *   Note: In the illustration below, the bits to be removed are highlighted with 'X'.
   *
   *   0010110000000000000000000000000000000000000000000000000000000000
   *   fffpps--XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
   *
   *   We convert the remaining bits to their hexadecimal representation.
   *
   *   Base 2: 0010 1100
   *   Base 16: "2"  "c"
   *
   *   Cell Token: "2c"
   *
   * To compute the cell ID from the token, we simply add enough zeros to the right to make the ID span 64 bits.
   *
   * Coordinate Transforms:
   * ----------------------
   *
   * To go from a cell in S2 to a point on the ellipsoid, the following order of transforms is applied:
   *
   *   1. (Cell ID): S2 cell ID
   *   2. (Face, I, J): Leaf cell coordinates, where i and j are in range [0, 2^30 - 1]
   *   3. (Face, S, T): Cell space coordinates, where s and t are in range [0, 1].
   *   4. (Face, Si, Ti): Discrete cell space coordinates, where si and ti are in range [0, 2^31]
   *   5. (Face, U, V): Cube space coordinates, where u and v are in range [-1, 1]. We apply the non-linear quadratic transform here.
   *   6. (X, Y, Z): Direction vector, where vector may not be unit length. Can be normalized to obtain point on unit sphere
   *   7. (Latitude, Longitude): Direction vector, where latitude is in range [-90, 90] and longitude is in range [-180, 180]
   *
   * @ignore
   */

  // The maximum level supported within an S2 cell ID. Each level is represented by two bits in the final cell ID
  const S2_MAX_LEVEL = 30;

  // The maximum index of a valid leaf cell plus one.  The range of valid leaf cell indices is [0..S2_LIMIT_IJ-1].
  const S2_LIMIT_IJ = 1 << S2_MAX_LEVEL;

  // The maximum value of an si- or ti-coordinate.  The range of valid (si,ti) values is [0..S2_MAX_SITI].  Use `>>>` to convert to unsigned.
  const S2_MAX_SITI = (1 << (S2_MAX_LEVEL + 1)) >>> 0;

  // The number of bits in a S2 cell ID used for specifying the position along the Hilbert curve
  const S2_POSITION_BITS = 2 * S2_MAX_LEVEL + 1;

  // The number of bits per I and J in the lookup tables
  const S2_LOOKUP_BITS = 4;

  // Lookup table for mapping 10 bits of IJ + orientation to 10 bits of Hilbert curve position + orientation.
  const S2_LOOKUP_POSITIONS = [];

  // Lookup table for mapping 10 bits of IJ + orientation to 10 bits of Hilbert curve position + orientation.
  const S2_LOOKUP_IJ = [];

  // Lookup table of two bits of IJ from two bits of curve position, based also on the current curve orientation from the swap and invert bits
  const S2_POSITION_TO_IJ = [
    [0, 1, 3, 2], // 0: Normal order, no swap or invert
    [0, 2, 3, 1], // 1: Swap bit set, swap I and J bits
    [3, 2, 0, 1], // 2: Invert bit set, invert bits
    [3, 1, 0, 2], // 3: Swap and invert bits set
  ];

  // Mask that specifies the swap orientation bit for the Hilbert curve
  const S2_SWAP_MASK = 1;

  // Mask that specifies the invert orientation bit for the Hilbert curve
  const S2_INVERT_MASK = 2;

  // Lookup for the orientation update mask of one of the four sub-cells within a higher level cell.
  // This mask is XOR'ed with the current orientation to get the sub-cell orientation.
  const S2_POSITION_TO_ORIENTATION_MASK = [
    S2_SWAP_MASK,
    0,
    0,
    S2_SWAP_MASK | S2_INVERT_MASK,
  ];

  /**
   * Represents a cell in the S2 geometry library.
   *
   * @alias S2Cell
   * @constructor
   *
   * @param {BigInt} [cellId] The 64-bit S2CellId.
   * @private
   */
  function S2Cell(cellId) {
    if (!FeatureDetection.supportsBigInt()) {
      throw new RuntimeError("S2 required BigInt support");
    }
    //>>includeStart('debug', pragmas.debug);
    if (!defined(cellId)) {
      throw new DeveloperError("cell ID is required.");
    }
    if (!S2Cell.isValidId(cellId)) {
      throw new DeveloperError("cell ID is invalid.");
    }
    //>>includeEnd('debug');

    this._cellId = cellId;
    this._level = S2Cell.getLevel(cellId);
  }

  /**
   * Creates a new S2Cell from a token. A token is a hexadecimal representation of the 64-bit S2CellId.
   *
   * @param {String} token The token for the S2 Cell.
   * @returns {S2Cell} Returns a new S2Cell.
   * @private
   */
  S2Cell.fromToken = function (token) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("token", token);
    if (!S2Cell.isValidToken(token)) {
      throw new DeveloperError("token is invalid.");
    }
    //>>includeEnd('debug');

    return new S2Cell(S2Cell.getIdFromToken(token));
  };

  /**
   * Validates an S2 cell ID.
   *
   * @param {BigInt} [cellId] The S2CellId.
   * @returns {Boolean} Returns true if the cell ID is valid, returns false otherwise.
   * @private
   */
  S2Cell.isValidId = function (cellId) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.bigint("cellId", cellId);
    //>>includeEnd('debug');

    // Check if sentinel bit is missing.
    if (cellId <= 0) {
      return false;
    }

    // Check if face bits indicate a valid value, in range [0-5].
    // eslint-disable-next-line
    if (cellId >> BigInt(S2_POSITION_BITS) > 5) {
      return false;
    }

    // Check trailing 1 bit is in one of the even bit positions allowed for the 30 levels, using a bitmask.
    // eslint-disable-next-line no-undef
    const lowestSetBit = cellId & (~cellId + BigInt(1));
    // eslint-disable-next-line
    if (!(lowestSetBit & BigInt("0x1555555555555555"))) {
      return false;
    }

    return true;
  };

  /**
   * Validates an S2 cell token.
   *
   * @param {String} [token] The hexadecimal representation of an S2CellId.
   * @returns {Boolean} Returns true if the token is valid, returns false otherwise.
   * @private
   */
  S2Cell.isValidToken = function (token) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("token", token);
    //>>includeEnd('debug');

    if (!/^[0-9a-fA-F]{1,16}$/.test(token)) {
      return false;
    }

    return S2Cell.isValidId(S2Cell.getIdFromToken(token));
  };

  /**
   * Converts an S2 cell token to a 64-bit S2 cell ID.
   *
   * @param {String} [token] The hexadecimal representation of an S2CellId. Expected to be a valid S2 token.
   * @returns {BigInt} Returns the S2 cell ID.
   * @private
   */
  S2Cell.getIdFromToken = function (token) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("token", token);
    //>>includeEnd('debug');

    return BigInt("0x" + token + "0".repeat(16 - token.length)); // eslint-disable-line
  };

  /**
   * Converts a 64-bit S2 cell ID to an S2 cell token.
   *
   * @param {BigInt} [cellId] The S2 cell ID.
   * @returns {BigInt} Returns hexadecimal representation of an S2CellId.
   * @private
   */
  S2Cell.getTokenFromId = function (cellId) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.bigint("cellId", cellId);
    //>>includeEnd('debug');

    const trailingZeroHexChars = Math.floor(countTrailingZeroBits(cellId) / 4);
    const hexString = cellId.toString(16).replace(/0*$/, "");

    const zeroString = Array(17 - trailingZeroHexChars - hexString.length).join(
      "0"
    );
    return zeroString + hexString;
  };

  /**
   * Gets the level of the cell from the cell ID.
   *
   * @param {BigInt} [cellId] The S2 cell ID.
   * @returns {number} Returns the level of the cell.
   * @private
   */
  S2Cell.getLevel = function (cellId) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.bigint("cellId", cellId);
    if (!S2Cell.isValidId(cellId)) {
      throw new DeveloperError();
    }
    //>>includeEnd('debug');

    let lsbPosition = 0;
    // eslint-disable-next-line
    while (cellId !== BigInt(0)) {
      // eslint-disable-next-line
      if (cellId & BigInt(1)) {
        break;
      }
      lsbPosition++;
      cellId = cellId >> BigInt(1); // eslint-disable-line
    }

    // We use (>> 1) because there are 2 bits per level.
    return S2_MAX_LEVEL - (lsbPosition >> 1);
  };

  /**
   * Gets the child cell of the cell at the given index.
   *
   * @param {Number} index An integer index of the child.
   * @returns {S2Cell} The child of the S2Cell.
   * @private
   */
  S2Cell.prototype.getChild = function (index) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("index", index);
    if (index < 0 || index > 3) {
      throw new DeveloperError("child index must be in the range [0-3].");
    }
    if (this._level === 30) {
      throw new DeveloperError("cannot get child of leaf cell.");
    }
    //>>includeEnd('debug');

    // Shift sentinel bit 2 positions to the right.
    // eslint-disable-next-line no-undef
    const newLsb = lsb(this._cellId) >> BigInt(2);
    // Insert child index before the sentinel bit.
    // eslint-disable-next-line no-undef
    const childCellId = this._cellId + BigInt(2 * index + 1 - 4) * newLsb;
    return new S2Cell(childCellId);
  };

  /**
   * Gets the parent cell of an S2Cell.
   *
   * @returns {S2Cell} Returns the parent of the S2Cell.
   * @private
   */
  S2Cell.prototype.getParent = function () {
    //>>includeStart('debug', pragmas.debug);
    if (this._level === 0) {
      throw new DeveloperError("cannot get parent of root cell.");
    }
    //>>includeEnd('debug');
    // Shift the sentinel bit 2 positions to the left.
    // eslint-disable-next-line no-undef
    const newLsb = lsb(this._cellId) << BigInt(2);
    // Erase the left over bits to the right of the sentinel bit.
    // eslint-disable-next-line no-undef
    return new S2Cell((this._cellId & (~newLsb + BigInt(1))) | newLsb);
  };

  /**
   * Gets the parent cell at the given level.
   *
   * @returns {S2Cell} Returns the parent of the S2Cell.
   * @private
   */
  S2Cell.prototype.getParentAtLevel = function (level) {
    //>>includeStart('debug', pragmas.debug);
    if (this._level === 0 || level < 0 || this._level < level) {
      throw new DeveloperError("cannot get parent at invalid level.");
    }
    //>>includeEnd('debug');
    const newLsb = lsbForLevel(level);
    return new S2Cell((this._cellId & -newLsb) | newLsb);
  };

  /**
   * Get center of the S2 cell.
   *
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid.
   * @returns {Cartesian} The position of center of the S2 cell.
   * @private
   */
  S2Cell.prototype.getCenter = function (ellipsoid) {
    ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);

    let center = getS2Center(this._cellId, this._level);
    // Normalize XYZ.
    center = Cartesian3.normalize(center, center);
    const cartographic = new Cartographic.fromCartesian(
      center,
      Ellipsoid.UNIT_SPHERE
    );
    // Interpret as geodetic coordinates on the ellipsoid.
    return Cartographic.toCartesian(cartographic, ellipsoid, new Cartesian3());
  };

  /**
   * Get vertex of the S2 cell. Vertices are indexed in CCW order.
   *
   * @param {Number} index An integer index of the vertex. Must be in the range [0-3].
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid.
   * @returns {Cartesian} The position of the vertex of the S2 cell.
   * @private
   */
  S2Cell.prototype.getVertex = function (index, ellipsoid) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("index", index);
    if (index < 0 || index > 3) {
      throw new DeveloperError("vertex index must be in the range [0-3].");
    }
    //>>includeEnd('debug');

    ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);

    let vertex = getS2Vertex(this._cellId, this._level, index);
    // Normalize XYZ.
    vertex = Cartesian3.normalize(vertex, vertex);
    const cartographic = new Cartographic.fromCartesian(
      vertex,
      Ellipsoid.UNIT_SPHERE
    );
    // Interpret as geodetic coordinates on the ellipsoid.
    return Cartographic.toCartesian(cartographic, ellipsoid, new Cartesian3());
  };

  /**
   * Creates an S2Cell from its face, position along the Hilbert curve for a given level.
   *
   * @param {Number} face The root face of S2 this cell is on. Must be in the range [0-5].
   * @param {BigInt} position The position along the Hilbert curve. Must be in the range [0-4**level).
   * @param {Number} level The level of the S2 curve. Must be in the range [0-30].
   * @returns {S2Cell} A new S2Cell from the given parameters.
   * @private
   */
  S2Cell.fromFacePositionLevel = function (face, position, level) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.bigint("position", position);
    if (face < 0 || face > 5) {
      throw new DeveloperError("Invalid S2 Face (must be within 0-5)");
    }

    if (level < 0 || level > S2_MAX_LEVEL) {
      throw new DeveloperError("Invalid level (must be within 0-30)");
    }
    if (position < 0 || position >= Math.pow(4, level)) {
      throw new DeveloperError("Invalid Hilbert position for level");
    }
    //>>includeEnd('debug');

    const faceBitString =
      (face < 4 ? "0" : "") + (face < 2 ? "0" : "") + face.toString(2);
    const positionBitString = position.toString(2);
    const positionPrefixPadding = Array(
      2 * level - positionBitString.length + 1
    ).join("0");
    const positionSuffixPadding = Array(S2_POSITION_BITS - 2 * level).join("0");

    // eslint-disable-next-line no-undef
    const cellId = BigInt(
      `0b${faceBitString}${positionPrefixPadding}${positionBitString}1${
      // Adding the sentinel bit that always follows the position bits.
      positionSuffixPadding
    }`
    );
    return new S2Cell(cellId);
  };

  /**
   * @private
   */
  function getS2Center(cellId, level) {
    const faceSiTi = convertCellIdToFaceSiTi(cellId, level);
    return convertFaceSiTitoXYZ(faceSiTi[0], faceSiTi[1], faceSiTi[2]);
  }
  /**
   * @private
   */
  function getS2Vertex(cellId, level, index) {
    const faceIJ = convertCellIdToFaceIJ(cellId);
    const uv = convertIJLeveltoBoundUV([faceIJ[1], faceIJ[2]], level);
    // Handles CCW ordering of the vertices.
    const y = (index >> 1) & 1;
    return convertFaceUVtoXYZ(faceIJ[0], uv[0][y ^ (index & 1)], uv[1][y]);
  }

  // S2 Coordinate Conversions

  /**
   * @private
   */
  function convertCellIdToFaceSiTi(cellId, level) {
    const faceIJ = convertCellIdToFaceIJ(cellId);
    const face = faceIJ[0];
    const i = faceIJ[1];
    const j = faceIJ[2];

    // We're resolving the center when we do the coordinate transform here. For the leaf cells, we're adding half the cell size
    // (remember that this space has 31 levels - which allows us to pick center and edges of the leaf cells). For non leaf cells,
    // we get one of either two cells diagonal to the cell center. The correction is used to make sure we pick the leaf cell edges
    // that represent the parent cell center.
    const isLeaf = level === 30;
    const shouldCorrect =
      !isLeaf && (BigInt(i) ^ (cellId >> BigInt(2))) & BigInt(1); // eslint-disable-line
    const correction = isLeaf ? 1 : shouldCorrect ? 2 : 0;
    const si = (i << 1) + correction;
    const ti = (j << 1) + correction;
    return [face, si, ti];
  }

  /**
   * @private
   */
  function convertCellIdToFaceIJ(cellId) {
    if (S2_LOOKUP_POSITIONS.length === 0) {
      generateLookupTable();
    }

    // eslint-disable-next-line no-undef
    const face = Number(cellId >> BigInt(S2_POSITION_BITS));
    let bits = face & S2_SWAP_MASK;
    const lookupMask = (1 << S2_LOOKUP_BITS) - 1;

    let i = 0;
    let j = 0;

    for (let k = 7; k >= 0; k--) {
      const numberOfBits =
        k === 7 ? S2_MAX_LEVEL - 7 * S2_LOOKUP_BITS : S2_LOOKUP_BITS;
      const extractMask = (1 << (2 * numberOfBits)) - 1;
      bits +=
        Number(
          (cellId >> BigInt(k * 2 * S2_LOOKUP_BITS + 1)) & BigInt(extractMask) // eslint-disable-line
        ) << 2;

      bits = S2_LOOKUP_IJ[bits];

      const offset = k * S2_LOOKUP_BITS;
      i += (bits >> (S2_LOOKUP_BITS + 2)) << offset;
      j += ((bits >> 2) & lookupMask) << offset;

      bits &= S2_SWAP_MASK | S2_INVERT_MASK;
    }

    return [face, i, j];
  }

  /**
   * @private
   */
  function convertFaceSiTitoXYZ(face, si, ti) {
    const s = convertSiTitoST(si);
    const t = convertSiTitoST(ti);

    const u = convertSTtoUV(s);
    const v = convertSTtoUV(t);
    return convertFaceUVtoXYZ(face, u, v);
  }

  /**
   * @private
   */
  function convertFaceUVtoXYZ(face, u, v) {
    switch (face) {
      case 0:
        return new Cartesian3(1, u, v);
      case 1:
        return new Cartesian3(-u, 1, v);
      case 2:
        return new Cartesian3(-u, -v, 1);
      case 3:
        return new Cartesian3(-1, -v, -u);
      case 4:
        return new Cartesian3(v, -1, -u);
      default:
        return new Cartesian3(v, u, -1);
    }
  }

  /**
   * S2 provides 3 methods for the non-linear transform: linear, quadratic and tangential.
   * This implementation uses the quadratic method because it provides a good balance of
   * accuracy and speed.
   *
   * For a more detailed comparison of these transform methods, see
   * {@link https://github.com/google/s2geometry/blob/0c4c460bdfe696da303641771f9def900b3e440f/src/s2/s2metrics.cc}
   * @private
   */
  function convertSTtoUV(s) {
    if (s >= 0.5) return (1 / 3) * (4 * s * s - 1);
    return (1 / 3) * (1 - 4 * (1 - s) * (1 - s));
  }

  /**
   * @private
   */
  function convertSiTitoST(si) {
    return (1.0 / S2_MAX_SITI) * si;
  }

  /**
   * @private
   */
  function convertIJLeveltoBoundUV(ij, level) {
    const result = [[], []];
    const cellSize = getSizeIJ(level);
    for (let d = 0; d < 2; ++d) {
      const ijLow = ij[d] & -cellSize;
      const ijHigh = ijLow + cellSize;
      result[d][0] = convertSTtoUV(convertIJtoSTMinimum(ijLow));
      result[d][1] = convertSTtoUV(convertIJtoSTMinimum(ijHigh));
    }
    return result;
  }

  /**
   * @private
   */
  function getSizeIJ(level) {
    return (1 << (S2_MAX_LEVEL - level)) >>> 0;
  }

  /**
   * @private
   */
  function convertIJtoSTMinimum(i) {
    return (1.0 / S2_LIMIT_IJ) * i;
  }

  // Utility Functions

  /**
   * This function generates 4 variations of a Hilbert curve of level 4, based on the S2_POSITION_TO_IJ table, for fast lookups of (i, j)
   * to position along Hilbert curve. The reference C++ implementation uses an iterative approach, however, this function is implemented
   * recursively.
   *
   * See {@link https://github.com/google/s2geometry/blob/c59d0ca01ae3976db7f8abdc83fcc871a3a95186/src/s2/s2cell_id.cc#L75-L109}
   * @private
   */
  function generateLookupCell(
    level,
    i,
    j,
    originalOrientation,
    position,
    orientation
  ) {
    if (level === S2_LOOKUP_BITS) {
      const ij = (i << S2_LOOKUP_BITS) + j;
      S2_LOOKUP_POSITIONS[(ij << 2) + originalOrientation] =
        (position << 2) + orientation;
      S2_LOOKUP_IJ[(position << 2) + originalOrientation] =
        (ij << 2) + orientation;
    } else {
      level++;
      i <<= 1;
      j <<= 1;
      position <<= 2;
      const r = S2_POSITION_TO_IJ[orientation];
      generateLookupCell(
        level,
        i + (r[0] >> 1),
        j + (r[0] & 1),
        originalOrientation,
        position,
        orientation ^ S2_POSITION_TO_ORIENTATION_MASK[0]
      );
      generateLookupCell(
        level,
        i + (r[1] >> 1),
        j + (r[1] & 1),
        originalOrientation,
        position + 1,
        orientation ^ S2_POSITION_TO_ORIENTATION_MASK[1]
      );
      generateLookupCell(
        level,
        i + (r[2] >> 1),
        j + (r[2] & 1),
        originalOrientation,
        position + 2,
        orientation ^ S2_POSITION_TO_ORIENTATION_MASK[2]
      );
      generateLookupCell(
        level,
        i + (r[3] >> 1),
        j + (r[3] & 1),
        originalOrientation,
        position + 3,
        orientation ^ S2_POSITION_TO_ORIENTATION_MASK[3]
      );
    }
  }

  /**
   * @private
   */
  function generateLookupTable() {
    generateLookupCell(0, 0, 0, 0, 0, 0);
    generateLookupCell(0, 0, 0, S2_SWAP_MASK, 0, S2_SWAP_MASK);
    generateLookupCell(0, 0, 0, S2_INVERT_MASK, 0, S2_INVERT_MASK);
    generateLookupCell(
      0,
      0,
      0,
      S2_SWAP_MASK | S2_INVERT_MASK,
      0,
      S2_SWAP_MASK | S2_INVERT_MASK
    );
  }

  /**
   * Return the lowest-numbered bit that is on for this cell id
   * @private
   */
  function lsb(cellId) {
    return cellId & (~cellId + BigInt(1)); // eslint-disable-line
  }

  /**
   * Return the lowest-numbered bit that is on for cells at the given level.
   * @private
   */
  function lsbForLevel(level) {
    return BigInt(1) << BigInt(2 * (S2_MAX_LEVEL - level)); // eslint-disable-line
  }

  // Lookup table for getting trailing zero bits.
  // https://graphics.stanford.edu/~seander/bithacks.html
  const Mod67BitPosition = [
    64,
    0,
    1,
    39,
    2,
    15,
    40,
    23,
    3,
    12,
    16,
    59,
    41,
    19,
    24,
    54,
    4,
    64,
    13,
    10,
    17,
    62,
    60,
    28,
    42,
    30,
    20,
    51,
    25,
    44,
    55,
    47,
    5,
    32,
    65,
    38,
    14,
    22,
    11,
    58,
    18,
    53,
    63,
    9,
    61,
    27,
    29,
    50,
    43,
    46,
    31,
    37,
    21,
    57,
    52,
    8,
    26,
    49,
    45,
    36,
    56,
    7,
    48,
    35,
    6,
    34,
    33,
    0,
  ];

  /**
   * Return the number of trailing zeros in number.
   * @private
   */
  function countTrailingZeroBits(x) {
    return Mod67BitPosition[(-x & x) % BigInt(67)]; // eslint-disable-line
  }

  /**
   * This enumerated type is for classifying mouse events: down, up, click, double click, move and move while a button is held down.
   *
   * @enum {Number}
   */
  const ScreenSpaceEventType = {
    /**
     * Represents a mouse left button down event.
     *
     * @type {Number}
     * @constant
     */
    LEFT_DOWN: 0,

    /**
     * Represents a mouse left button up event.
     *
     * @type {Number}
     * @constant
     */
    LEFT_UP: 1,

    /**
     * Represents a mouse left click event.
     *
     * @type {Number}
     * @constant
     */
    LEFT_CLICK: 2,

    /**
     * Represents a mouse left double click event.
     *
     * @type {Number}
     * @constant
     */
    LEFT_DOUBLE_CLICK: 3,

    /**
     * Represents a mouse left button down event.
     *
     * @type {Number}
     * @constant
     */
    RIGHT_DOWN: 5,

    /**
     * Represents a mouse right button up event.
     *
     * @type {Number}
     * @constant
     */
    RIGHT_UP: 6,

    /**
     * Represents a mouse right click event.
     *
     * @type {Number}
     * @constant
     */
    RIGHT_CLICK: 7,

    /**
     * Represents a mouse middle button down event.
     *
     * @type {Number}
     * @constant
     */
    MIDDLE_DOWN: 10,

    /**
     * Represents a mouse middle button up event.
     *
     * @type {Number}
     * @constant
     */
    MIDDLE_UP: 11,

    /**
     * Represents a mouse middle click event.
     *
     * @type {Number}
     * @constant
     */
    MIDDLE_CLICK: 12,

    /**
     * Represents a mouse move event.
     *
     * @type {Number}
     * @constant
     */
    MOUSE_MOVE: 15,

    /**
     * Represents a mouse wheel event.
     *
     * @type {Number}
     * @constant
     */
    WHEEL: 16,

    /**
     * Represents the start of a two-finger event on a touch surface.
     *
     * @type {Number}
     * @constant
     */
    PINCH_START: 17,

    /**
     * Represents the end of a two-finger event on a touch surface.
     *
     * @type {Number}
     * @constant
     */
    PINCH_END: 18,

    /**
     * Represents a change of a two-finger event on a touch surface.
     *
     * @type {Number}
     * @constant
     */
    PINCH_MOVE: 19,
  };
  var ScreenSpaceEventType$1 = Object.freeze(ScreenSpaceEventType);

  function getPosition$1(screenSpaceEventHandler, event, result) {
    const element = screenSpaceEventHandler._element;
    if (element === document) {
      result.x = event.clientX;
      result.y = event.clientY;
      return result;
    }

    const rect = element.getBoundingClientRect();
    result.x = event.clientX - rect.left;
    result.y = event.clientY - rect.top;
    return result;
  }

  function getInputEventKey(type, modifier) {
    let key = type;
    if (defined(modifier)) {
      key += `+${modifier}`;
    }
    return key;
  }

  function getModifier(event) {
    if (event.shiftKey) {
      return KeyboardEventModifier$1.SHIFT;
    } else if (event.ctrlKey) {
      return KeyboardEventModifier$1.CTRL;
    } else if (event.altKey) {
      return KeyboardEventModifier$1.ALT;
    }

    return undefined;
  }

  const MouseButton = {
    LEFT: 0,
    MIDDLE: 1,
    RIGHT: 2,
  };

  function registerListener(screenSpaceEventHandler, domType, element, callback) {
    function listener(e) {
      callback(screenSpaceEventHandler, e);
    }

    if (FeatureDetection.isInternetExplorer()) {
      element.addEventListener(domType, listener, false);
    } else {
      element.addEventListener(domType, listener, {
        capture: false,
        passive: false,
      });
    }

    screenSpaceEventHandler._removalFunctions.push(function () {
      element.removeEventListener(domType, listener, false);
    });
  }

  function registerListeners(screenSpaceEventHandler) {
    const element = screenSpaceEventHandler._element;

    // some listeners may be registered on the document, so we still get events even after
    // leaving the bounds of element.
    // this is affected by the existence of an undocumented disableRootEvents property on element.
    const alternateElement = !defined(element.disableRootEvents)
      ? document
      : element;

    if (FeatureDetection.supportsPointerEvents()) {
      registerListener(
        screenSpaceEventHandler,
        "pointerdown",
        element,
        handlePointerDown
      );
      registerListener(
        screenSpaceEventHandler,
        "pointerup",
        element,
        handlePointerUp
      );
      registerListener(
        screenSpaceEventHandler,
        "pointermove",
        element,
        handlePointerMove
      );
      registerListener(
        screenSpaceEventHandler,
        "pointercancel",
        element,
        handlePointerUp
      );
    } else {
      registerListener(
        screenSpaceEventHandler,
        "mousedown",
        element,
        handleMouseDown
      );
      registerListener(
        screenSpaceEventHandler,
        "mouseup",
        alternateElement,
        handleMouseUp
      );
      registerListener(
        screenSpaceEventHandler,
        "mousemove",
        alternateElement,
        handleMouseMove
      );
      registerListener(
        screenSpaceEventHandler,
        "touchstart",
        element,
        handleTouchStart
      );
      registerListener(
        screenSpaceEventHandler,
        "touchend",
        alternateElement,
        handleTouchEnd
      );
      registerListener(
        screenSpaceEventHandler,
        "touchmove",
        alternateElement,
        handleTouchMove
      );
      registerListener(
        screenSpaceEventHandler,
        "touchcancel",
        alternateElement,
        handleTouchEnd
      );
    }

    registerListener(
      screenSpaceEventHandler,
      "dblclick",
      element,
      handleDblClick
    );

    // detect available wheel event
    let wheelEvent;
    if ("onwheel" in element) {
      // spec event type
      wheelEvent = "wheel";
    } else if (document.onmousewheel !== undefined) {
      // legacy event type
      wheelEvent = "mousewheel";
    } else {
      // older Firefox
      wheelEvent = "DOMMouseScroll";
    }

    registerListener(screenSpaceEventHandler, wheelEvent, element, handleWheel);
  }

  function unregisterListeners(screenSpaceEventHandler) {
    const removalFunctions = screenSpaceEventHandler._removalFunctions;
    for (let i = 0; i < removalFunctions.length; ++i) {
      removalFunctions[i]();
    }
  }

  const mouseDownEvent = {
    position: new Cartesian2(),
  };

  function gotTouchEvent(screenSpaceEventHandler) {
    screenSpaceEventHandler._lastSeenTouchEvent = getTimestamp$1();
  }

  function canProcessMouseEvent(screenSpaceEventHandler) {
    return (
      getTimestamp$1() - screenSpaceEventHandler._lastSeenTouchEvent >
      ScreenSpaceEventHandler.mouseEmulationIgnoreMilliseconds
    );
  }

  function checkPixelTolerance(startPosition, endPosition, pixelTolerance) {
    const xDiff = startPosition.x - endPosition.x;
    const yDiff = startPosition.y - endPosition.y;
    const totalPixels = Math.sqrt(xDiff * xDiff + yDiff * yDiff);

    return totalPixels < pixelTolerance;
  }

  function handleMouseDown(screenSpaceEventHandler, event) {
    if (!canProcessMouseEvent(screenSpaceEventHandler)) {
      return;
    }

    const button = event.button;
    screenSpaceEventHandler._buttonDown[button] = true;

    let screenSpaceEventType;
    if (button === MouseButton.LEFT) {
      screenSpaceEventType = ScreenSpaceEventType$1.LEFT_DOWN;
    } else if (button === MouseButton.MIDDLE) {
      screenSpaceEventType = ScreenSpaceEventType$1.MIDDLE_DOWN;
    } else if (button === MouseButton.RIGHT) {
      screenSpaceEventType = ScreenSpaceEventType$1.RIGHT_DOWN;
    } else {
      return;
    }

    const position = getPosition$1(
      screenSpaceEventHandler,
      event,
      screenSpaceEventHandler._primaryPosition
    );
    Cartesian2.clone(position, screenSpaceEventHandler._primaryStartPosition);
    Cartesian2.clone(position, screenSpaceEventHandler._primaryPreviousPosition);

    const modifier = getModifier(event);

    const action = screenSpaceEventHandler.getInputAction(
      screenSpaceEventType,
      modifier
    );

    if (defined(action)) {
      Cartesian2.clone(position, mouseDownEvent.position);

      action(mouseDownEvent);

      event.preventDefault();
    }
  }

  const mouseUpEvent = {
    position: new Cartesian2(),
  };
  const mouseClickEvent = {
    position: new Cartesian2(),
  };

  function cancelMouseEvent(
    screenSpaceEventHandler,
    screenSpaceEventType,
    clickScreenSpaceEventType,
    event
  ) {
    const modifier = getModifier(event);

    const action = screenSpaceEventHandler.getInputAction(
      screenSpaceEventType,
      modifier
    );
    const clickAction = screenSpaceEventHandler.getInputAction(
      clickScreenSpaceEventType,
      modifier
    );

    if (defined(action) || defined(clickAction)) {
      const position = getPosition$1(
        screenSpaceEventHandler,
        event,
        screenSpaceEventHandler._primaryPosition
      );

      if (defined(action)) {
        Cartesian2.clone(position, mouseUpEvent.position);

        action(mouseUpEvent);
      }

      if (defined(clickAction)) {
        const startPosition = screenSpaceEventHandler._primaryStartPosition;
        if (
          checkPixelTolerance(
            startPosition,
            position,
            screenSpaceEventHandler._clickPixelTolerance
          )
        ) {
          Cartesian2.clone(position, mouseClickEvent.position);

          clickAction(mouseClickEvent);
        }
      }
    }
  }

  function handleMouseUp(screenSpaceEventHandler, event) {
    if (!canProcessMouseEvent(screenSpaceEventHandler)) {
      return;
    }

    const button = event.button;

    if (
      button !== MouseButton.LEFT &&
      button !== MouseButton.MIDDLE &&
      button !== MouseButton.RIGHT
    ) {
      return;
    }

    if (screenSpaceEventHandler._buttonDown[MouseButton.LEFT]) {
      cancelMouseEvent(
        screenSpaceEventHandler,
        ScreenSpaceEventType$1.LEFT_UP,
        ScreenSpaceEventType$1.LEFT_CLICK,
        event
      );
      screenSpaceEventHandler._buttonDown[MouseButton.LEFT] = false;
    }
    if (screenSpaceEventHandler._buttonDown[MouseButton.MIDDLE]) {
      cancelMouseEvent(
        screenSpaceEventHandler,
        ScreenSpaceEventType$1.MIDDLE_UP,
        ScreenSpaceEventType$1.MIDDLE_CLICK,
        event
      );
      screenSpaceEventHandler._buttonDown[MouseButton.MIDDLE] = false;
    }
    if (screenSpaceEventHandler._buttonDown[MouseButton.RIGHT]) {
      cancelMouseEvent(
        screenSpaceEventHandler,
        ScreenSpaceEventType$1.RIGHT_UP,
        ScreenSpaceEventType$1.RIGHT_CLICK,
        event
      );
      screenSpaceEventHandler._buttonDown[MouseButton.RIGHT] = false;
    }
  }

  const mouseMoveEvent = {
    startPosition: new Cartesian2(),
    endPosition: new Cartesian2(),
  };

  function handleMouseMove(screenSpaceEventHandler, event) {
    if (!canProcessMouseEvent(screenSpaceEventHandler)) {
      return;
    }

    const modifier = getModifier(event);

    const position = getPosition$1(
      screenSpaceEventHandler,
      event,
      screenSpaceEventHandler._primaryPosition
    );
    const previousPosition = screenSpaceEventHandler._primaryPreviousPosition;

    const action = screenSpaceEventHandler.getInputAction(
      ScreenSpaceEventType$1.MOUSE_MOVE,
      modifier
    );

    if (defined(action)) {
      Cartesian2.clone(previousPosition, mouseMoveEvent.startPosition);
      Cartesian2.clone(position, mouseMoveEvent.endPosition);

      action(mouseMoveEvent);
    }

    Cartesian2.clone(position, previousPosition);

    if (
      screenSpaceEventHandler._buttonDown[MouseButton.LEFT] ||
      screenSpaceEventHandler._buttonDown[MouseButton.MIDDLE] ||
      screenSpaceEventHandler._buttonDown[MouseButton.RIGHT]
    ) {
      event.preventDefault();
    }
  }

  const mouseDblClickEvent = {
    position: new Cartesian2(),
  };

  function handleDblClick(screenSpaceEventHandler, event) {
    const button = event.button;

    let screenSpaceEventType;
    if (button === MouseButton.LEFT) {
      screenSpaceEventType = ScreenSpaceEventType$1.LEFT_DOUBLE_CLICK;
    } else {
      return;
    }

    const modifier = getModifier(event);

    const action = screenSpaceEventHandler.getInputAction(
      screenSpaceEventType,
      modifier
    );

    if (defined(action)) {
      getPosition$1(screenSpaceEventHandler, event, mouseDblClickEvent.position);

      action(mouseDblClickEvent);
    }
  }

  function handleWheel(screenSpaceEventHandler, event) {
    // currently this event exposes the delta value in terms of
    // the obsolete mousewheel event type.  so, for now, we adapt the other
    // values to that scheme.
    let delta;

    // standard wheel event uses deltaY.  sign is opposite wheelDelta.
    // deltaMode indicates what unit it is in.
    if (defined(event.deltaY)) {
      const deltaMode = event.deltaMode;
      if (deltaMode === event.DOM_DELTA_PIXEL) {
        delta = -event.deltaY;
      } else if (deltaMode === event.DOM_DELTA_LINE) {
        delta = -event.deltaY * 40;
      } else {
        // DOM_DELTA_PAGE
        delta = -event.deltaY * 120;
      }
    } else if (event.detail > 0) {
      // old Firefox versions use event.detail to count the number of clicks. The sign
      // of the integer is the direction the wheel is scrolled.
      delta = event.detail * -120;
    } else {
      delta = event.wheelDelta;
    }

    if (!defined(delta)) {
      return;
    }

    const modifier = getModifier(event);
    const action = screenSpaceEventHandler.getInputAction(
      ScreenSpaceEventType$1.WHEEL,
      modifier
    );

    if (defined(action)) {
      action(delta);

      event.preventDefault();
    }
  }

  function handleTouchStart(screenSpaceEventHandler, event) {
    gotTouchEvent(screenSpaceEventHandler);

    const changedTouches = event.changedTouches;

    let i;
    const length = changedTouches.length;
    let touch;
    let identifier;
    const positions = screenSpaceEventHandler._positions;

    for (i = 0; i < length; ++i) {
      touch = changedTouches[i];
      identifier = touch.identifier;
      positions.set(
        identifier,
        getPosition$1(screenSpaceEventHandler, touch, new Cartesian2())
      );
    }

    fireTouchEvents(screenSpaceEventHandler, event);

    const previousPositions = screenSpaceEventHandler._previousPositions;

    for (i = 0; i < length; ++i) {
      touch = changedTouches[i];
      identifier = touch.identifier;
      previousPositions.set(
        identifier,
        Cartesian2.clone(positions.get(identifier))
      );
    }
  }

  function handleTouchEnd(screenSpaceEventHandler, event) {
    gotTouchEvent(screenSpaceEventHandler);

    const changedTouches = event.changedTouches;

    let i;
    const length = changedTouches.length;
    let touch;
    let identifier;
    const positions = screenSpaceEventHandler._positions;

    for (i = 0; i < length; ++i) {
      touch = changedTouches[i];
      identifier = touch.identifier;
      positions.remove(identifier);
    }

    fireTouchEvents(screenSpaceEventHandler, event);

    const previousPositions = screenSpaceEventHandler._previousPositions;

    for (i = 0; i < length; ++i) {
      touch = changedTouches[i];
      identifier = touch.identifier;
      previousPositions.remove(identifier);
    }
  }

  const touchStartEvent = {
    position: new Cartesian2(),
  };
  const touch2StartEvent = {
    position1: new Cartesian2(),
    position2: new Cartesian2(),
  };
  const touchEndEvent = {
    position: new Cartesian2(),
  };
  const touchClickEvent = {
    position: new Cartesian2(),
  };
  const touchHoldEvent = {
    position: new Cartesian2(),
  };

  function fireTouchEvents(screenSpaceEventHandler, event) {
    const modifier = getModifier(event);
    const positions = screenSpaceEventHandler._positions;
    const numberOfTouches = positions.length;
    let action;
    let clickAction;
    const pinching = screenSpaceEventHandler._isPinching;

    if (
      numberOfTouches !== 1 &&
      screenSpaceEventHandler._buttonDown[MouseButton.LEFT]
    ) {
      // transitioning from single touch, trigger UP and might trigger CLICK
      screenSpaceEventHandler._buttonDown[MouseButton.LEFT] = false;

      if (defined(screenSpaceEventHandler._touchHoldTimer)) {
        clearTimeout(screenSpaceEventHandler._touchHoldTimer);
        screenSpaceEventHandler._touchHoldTimer = undefined;
      }

      action = screenSpaceEventHandler.getInputAction(
        ScreenSpaceEventType$1.LEFT_UP,
        modifier
      );

      if (defined(action)) {
        Cartesian2.clone(
          screenSpaceEventHandler._primaryPosition,
          touchEndEvent.position
        );

        action(touchEndEvent);
      }

      if (numberOfTouches === 0 && !screenSpaceEventHandler._isTouchHolding) {
        // releasing single touch, check for CLICK
        clickAction = screenSpaceEventHandler.getInputAction(
          ScreenSpaceEventType$1.LEFT_CLICK,
          modifier
        );

        if (defined(clickAction)) {
          const startPosition = screenSpaceEventHandler._primaryStartPosition;
          const endPosition =
            screenSpaceEventHandler._previousPositions.values[0];
          if (
            checkPixelTolerance(
              startPosition,
              endPosition,
              screenSpaceEventHandler._clickPixelTolerance
            )
          ) {
            Cartesian2.clone(
              screenSpaceEventHandler._primaryPosition,
              touchClickEvent.position
            );

            clickAction(touchClickEvent);
          }
        }
      }

      screenSpaceEventHandler._isTouchHolding = false;

      // Otherwise don't trigger CLICK, because we are adding more touches.
    }

    if (numberOfTouches === 0 && pinching) {
      // transitioning from pinch, trigger PINCH_END
      screenSpaceEventHandler._isPinching = false;

      action = screenSpaceEventHandler.getInputAction(
        ScreenSpaceEventType$1.PINCH_END,
        modifier
      );

      if (defined(action)) {
        action();
      }
    }

    if (numberOfTouches === 1 && !pinching) {
      // transitioning to single touch, trigger DOWN
      const position = positions.values[0];
      Cartesian2.clone(position, screenSpaceEventHandler._primaryPosition);
      Cartesian2.clone(position, screenSpaceEventHandler._primaryStartPosition);
      Cartesian2.clone(
        position,
        screenSpaceEventHandler._primaryPreviousPosition
      );

      screenSpaceEventHandler._buttonDown[MouseButton.LEFT] = true;

      action = screenSpaceEventHandler.getInputAction(
        ScreenSpaceEventType$1.LEFT_DOWN,
        modifier
      );

      if (defined(action)) {
        Cartesian2.clone(position, touchStartEvent.position);

        action(touchStartEvent);
      }

      screenSpaceEventHandler._touchHoldTimer = setTimeout(function () {
        if (!screenSpaceEventHandler.isDestroyed()) {
          screenSpaceEventHandler._touchHoldTimer = undefined;
          screenSpaceEventHandler._isTouchHolding = true;

          clickAction = screenSpaceEventHandler.getInputAction(
            ScreenSpaceEventType$1.RIGHT_CLICK,
            modifier
          );

          if (defined(clickAction)) {
            const startPosition = screenSpaceEventHandler._primaryStartPosition;
            const endPosition =
              screenSpaceEventHandler._previousPositions.values[0];
            if (
              checkPixelTolerance(
                startPosition,
                endPosition,
                screenSpaceEventHandler._holdPixelTolerance
              )
            ) {
              Cartesian2.clone(
                screenSpaceEventHandler._primaryPosition,
                touchHoldEvent.position
              );

              clickAction(touchHoldEvent);
            }
          }
        }
      }, ScreenSpaceEventHandler.touchHoldDelayMilliseconds);

      event.preventDefault();
    }

    if (numberOfTouches === 2 && !pinching) {
      // transitioning to pinch, trigger PINCH_START
      screenSpaceEventHandler._isPinching = true;

      action = screenSpaceEventHandler.getInputAction(
        ScreenSpaceEventType$1.PINCH_START,
        modifier
      );

      if (defined(action)) {
        Cartesian2.clone(positions.values[0], touch2StartEvent.position1);
        Cartesian2.clone(positions.values[1], touch2StartEvent.position2);

        action(touch2StartEvent);

        // Touch-enabled devices, in particular iOS can have many default behaviours for
        // "pinch" events, which can still be executed unless we prevent them here.
        event.preventDefault();
      }
    }
  }

  function handleTouchMove(screenSpaceEventHandler, event) {
    gotTouchEvent(screenSpaceEventHandler);

    const changedTouches = event.changedTouches;

    let i;
    const length = changedTouches.length;
    let touch;
    let identifier;
    const positions = screenSpaceEventHandler._positions;

    for (i = 0; i < length; ++i) {
      touch = changedTouches[i];
      identifier = touch.identifier;
      const position = positions.get(identifier);
      if (defined(position)) {
        getPosition$1(screenSpaceEventHandler, touch, position);
      }
    }

    fireTouchMoveEvents(screenSpaceEventHandler, event);

    const previousPositions = screenSpaceEventHandler._previousPositions;

    for (i = 0; i < length; ++i) {
      touch = changedTouches[i];
      identifier = touch.identifier;
      Cartesian2.clone(
        positions.get(identifier),
        previousPositions.get(identifier)
      );
    }
  }

  const touchMoveEvent = {
    startPosition: new Cartesian2(),
    endPosition: new Cartesian2(),
  };
  const touchPinchMovementEvent = {
    distance: {
      startPosition: new Cartesian2(),
      endPosition: new Cartesian2(),
    },
    angleAndHeight: {
      startPosition: new Cartesian2(),
      endPosition: new Cartesian2(),
    },
  };

  function fireTouchMoveEvents(screenSpaceEventHandler, event) {
    const modifier = getModifier(event);
    const positions = screenSpaceEventHandler._positions;
    const previousPositions = screenSpaceEventHandler._previousPositions;
    const numberOfTouches = positions.length;
    let action;

    if (
      numberOfTouches === 1 &&
      screenSpaceEventHandler._buttonDown[MouseButton.LEFT]
    ) {
      // moving single touch
      const position = positions.values[0];
      Cartesian2.clone(position, screenSpaceEventHandler._primaryPosition);

      const previousPosition = screenSpaceEventHandler._primaryPreviousPosition;

      action = screenSpaceEventHandler.getInputAction(
        ScreenSpaceEventType$1.MOUSE_MOVE,
        modifier
      );

      if (defined(action)) {
        Cartesian2.clone(previousPosition, touchMoveEvent.startPosition);
        Cartesian2.clone(position, touchMoveEvent.endPosition);

        action(touchMoveEvent);
      }

      Cartesian2.clone(position, previousPosition);

      event.preventDefault();
    } else if (numberOfTouches === 2 && screenSpaceEventHandler._isPinching) {
      // moving pinch

      action = screenSpaceEventHandler.getInputAction(
        ScreenSpaceEventType$1.PINCH_MOVE,
        modifier
      );
      if (defined(action)) {
        const position1 = positions.values[0];
        const position2 = positions.values[1];
        const previousPosition1 = previousPositions.values[0];
        const previousPosition2 = previousPositions.values[1];

        const dX = position2.x - position1.x;
        const dY = position2.y - position1.y;
        const dist = Math.sqrt(dX * dX + dY * dY) * 0.25;

        const prevDX = previousPosition2.x - previousPosition1.x;
        const prevDY = previousPosition2.y - previousPosition1.y;
        const prevDist = Math.sqrt(prevDX * prevDX + prevDY * prevDY) * 0.25;

        const cY = (position2.y + position1.y) * 0.125;
        const prevCY = (previousPosition2.y + previousPosition1.y) * 0.125;
        const angle = Math.atan2(dY, dX);
        const prevAngle = Math.atan2(prevDY, prevDX);

        Cartesian2.fromElements(
          0.0,
          prevDist,
          touchPinchMovementEvent.distance.startPosition
        );
        Cartesian2.fromElements(
          0.0,
          dist,
          touchPinchMovementEvent.distance.endPosition
        );

        Cartesian2.fromElements(
          prevAngle,
          prevCY,
          touchPinchMovementEvent.angleAndHeight.startPosition
        );
        Cartesian2.fromElements(
          angle,
          cY,
          touchPinchMovementEvent.angleAndHeight.endPosition
        );

        action(touchPinchMovementEvent);
      }
    }
  }

  function handlePointerDown(screenSpaceEventHandler, event) {
    event.target.setPointerCapture(event.pointerId);

    if (event.pointerType === "touch") {
      const positions = screenSpaceEventHandler._positions;

      const identifier = event.pointerId;
      positions.set(
        identifier,
        getPosition$1(screenSpaceEventHandler, event, new Cartesian2())
      );

      fireTouchEvents(screenSpaceEventHandler, event);

      const previousPositions = screenSpaceEventHandler._previousPositions;
      previousPositions.set(
        identifier,
        Cartesian2.clone(positions.get(identifier))
      );
    } else {
      handleMouseDown(screenSpaceEventHandler, event);
    }
  }

  function handlePointerUp(screenSpaceEventHandler, event) {
    if (event.pointerType === "touch") {
      const positions = screenSpaceEventHandler._positions;

      const identifier = event.pointerId;
      positions.remove(identifier);

      fireTouchEvents(screenSpaceEventHandler, event);

      const previousPositions = screenSpaceEventHandler._previousPositions;
      previousPositions.remove(identifier);
    } else {
      handleMouseUp(screenSpaceEventHandler, event);
    }
  }

  function handlePointerMove(screenSpaceEventHandler, event) {
    if (event.pointerType === "touch") {
      const positions = screenSpaceEventHandler._positions;

      const identifier = event.pointerId;
      const position = positions.get(identifier);
      if (!defined(position)) {
        return;
      }

      getPosition$1(screenSpaceEventHandler, event, position);
      fireTouchMoveEvents(screenSpaceEventHandler, event);

      const previousPositions = screenSpaceEventHandler._previousPositions;
      Cartesian2.clone(
        positions.get(identifier),
        previousPositions.get(identifier)
      );
    } else {
      handleMouseMove(screenSpaceEventHandler, event);
    }
  }

  /**
   * @typedef {Object} ScreenSpaceEventHandler.PositionedEvent
   *
   * An Event that occurs at a single position on screen.
   *
   * @property {Cartesian2} position
   */

  /**
   * @callback ScreenSpaceEventHandler.PositionedEventCallback
   *
   * The callback invoked when a positioned event triggers an event listener.
   *
   * @param {ScreenSpaceEventHandler.PositionedEvent} event The event which triggered the listener
   */

  /**
   * @typedef {Object} ScreenSpaceEventHandler.MotionEvent
   *
   * An Event that starts at one position and ends at another.
   *
   * @property {Cartesian2} startPosition
   * @property {Cartesian2} endPosition
   */

  /**
   * @callback ScreenSpaceEventHandler.MotionEventCallback
   *
   * The callback invoked when a motion event triggers an event listener.
   *
   * @param {ScreenSpaceEventHandler.MotionEvent} event The event which triggered the listener
   */

  /**
   * @typedef {Object} ScreenSpaceEventHandler.TwoPointEvent
   *
   * An Event that occurs at a two positions on screen.
   *
   * @property {Cartesian2} position1
   * @property {Cartesian2} position2
   */

  /**
   * @callback ScreenSpaceEventHandler.TwoPointEventCallback
   *
   * The callback invoked when a two-point event triggers an event listener.
   *
   * @param {ScreenSpaceEventHandler.TwoPointEvent} event The event which triggered the listener
   */

  /**
   * @typedef {Object} ScreenSpaceEventHandler.TwoPointMotionEvent
   *
   * An Event that starts at a two positions on screen and moves to two other positions.
   *
   * @property {Cartesian2} position1
   * @property {Cartesian2} position2
   * @property {Cartesian2} previousPosition1
   * @property {Cartesian2} previousPosition2
   */

  /**
   * @callback ScreenSpaceEventHandler.TwoPointMotionEventCallback
   *
   * The callback invoked when a two-point motion event triggers an event listener.
   *
   * @param {ScreenSpaceEventHandler.TwoPointMotionEvent} event The event which triggered the listener
   */

  /**
   * @callback ScreenSpaceEventHandler.WheelEventCallback
   *
   * The callback invoked when a mouse-wheel event triggers an event listener.
   *
   * @param {number} delta The amount that the mouse wheel moved
   */

  /**
   * Handles user input events. Custom functions can be added to be executed on
   * when the user enters input.
   *
   * @alias ScreenSpaceEventHandler
   *
   * @param {HTMLCanvasElement} [element=document] The element to add events to.
   *
   * @constructor
   */
  function ScreenSpaceEventHandler(element) {
    this._inputEvents = {};
    this._buttonDown = {
      LEFT: false,
      MIDDLE: false,
      RIGHT: false,
    };
    this._isPinching = false;
    this._isTouchHolding = false;
    this._lastSeenTouchEvent = -ScreenSpaceEventHandler.mouseEmulationIgnoreMilliseconds;

    this._primaryStartPosition = new Cartesian2();
    this._primaryPosition = new Cartesian2();
    this._primaryPreviousPosition = new Cartesian2();

    this._positions = new AssociativeArray();
    this._previousPositions = new AssociativeArray();

    this._removalFunctions = [];

    this._touchHoldTimer = undefined;

    // TODO: Revisit when doing mobile development. May need to be configurable
    // or determined based on the platform?
    this._clickPixelTolerance = 5;
    this._holdPixelTolerance = 25;

    this._element = defaultValue(element, document);

    registerListeners(this);
  }

  /**
   * Set a function to be executed on an input event.
   *
   * @param {ScreenSpaceEventHandler.PositionedEventCallback|ScreenSpaceEventHandler.MotionEventCallback|ScreenSpaceEventHandler.WheelEventCallback|ScreenSpaceEventHandler.TwoPointEventCallback|ScreenSpaceEventHandler.TwoPointMotionEventCallback} action Function to be executed when the input event occurs.
   * @param {ScreenSpaceEventType} type The ScreenSpaceEventType of input event.
   * @param {KeyboardEventModifier} [modifier] A KeyboardEventModifier key that is held when a <code>type</code>
   * event occurs.
   *
   * @see ScreenSpaceEventHandler#getInputAction
   * @see ScreenSpaceEventHandler#removeInputAction
   */
  ScreenSpaceEventHandler.prototype.setInputAction = function (
    action,
    type,
    modifier
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(action)) {
      throw new DeveloperError("action is required.");
    }
    if (!defined(type)) {
      throw new DeveloperError("type is required.");
    }
    //>>includeEnd('debug');

    const key = getInputEventKey(type, modifier);
    this._inputEvents[key] = action;
  };

  /**
   * Returns the function to be executed on an input event.
   *
   * @param {ScreenSpaceEventType} type The ScreenSpaceEventType of input event.
   * @param {KeyboardEventModifier} [modifier] A KeyboardEventModifier key that is held when a <code>type</code>
   * event occurs.
   *
   * @returns {ScreenSpaceEventHandler.PositionedEventCallback|ScreenSpaceEventHandler.MotionEventCallback|ScreenSpaceEventHandler.WheelEventCallback|ScreenSpaceEventHandler.TwoPointEventCallback|ScreenSpaceEventHandler.TwoPointMotionEventCallback} The function to be executed on an input event.
   *
   * @see ScreenSpaceEventHandler#setInputAction
   * @see ScreenSpaceEventHandler#removeInputAction
   */
  ScreenSpaceEventHandler.prototype.getInputAction = function (type, modifier) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(type)) {
      throw new DeveloperError("type is required.");
    }
    //>>includeEnd('debug');

    const key = getInputEventKey(type, modifier);
    return this._inputEvents[key];
  };

  /**
   * Removes the function to be executed on an input event.
   *
   * @param {ScreenSpaceEventType} type The ScreenSpaceEventType of input event.
   * @param {KeyboardEventModifier} [modifier] A KeyboardEventModifier key that is held when a <code>type</code>
   * event occurs.
   *
   * @see ScreenSpaceEventHandler#getInputAction
   * @see ScreenSpaceEventHandler#setInputAction
   */
  ScreenSpaceEventHandler.prototype.removeInputAction = function (
    type,
    modifier
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(type)) {
      throw new DeveloperError("type is required.");
    }
    //>>includeEnd('debug');

    const key = getInputEventKey(type, modifier);
    delete this._inputEvents[key];
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see ScreenSpaceEventHandler#destroy
   */
  ScreenSpaceEventHandler.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Removes listeners held by this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * handler = handler && handler.destroy();
   *
   * @see ScreenSpaceEventHandler#isDestroyed
   */
  ScreenSpaceEventHandler.prototype.destroy = function () {
    unregisterListeners(this);

    return destroyObject(this);
  };

  /**
   * The amount of time, in milliseconds, that mouse events will be disabled after
   * receiving any touch events, such that any emulated mouse events will be ignored.
   * @type {Number}
   * @default 800
   */
  ScreenSpaceEventHandler.mouseEmulationIgnoreMilliseconds = 800;

  /**
   * The amount of time, in milliseconds, before a touch on the screen becomes a
   * touch and hold.
   * @type {Number}
   * @default 1500
   */
  ScreenSpaceEventHandler.touchHoldDelayMilliseconds = 1500;

  /**
   * Value and type information for per-instance geometry attribute that determines if the geometry instance will be shown.
   *
   * @alias ShowGeometryInstanceAttribute
   * @constructor
   *
   * @param {Boolean} [show=true] Determines if the geometry instance will be shown.
   *
   *
   * @example
   * const instance = new Cesium.GeometryInstance({
   *   geometry : new Cesium.BoxGeometry({
   *     vertexFormat : Cesium.VertexFormat.POSITION_AND_NORMAL,
   *     minimum : new Cesium.Cartesian3(-250000.0, -250000.0, -250000.0),
   *     maximum : new Cesium.Cartesian3(250000.0, 250000.0, 250000.0)
   *   }),
   *   modelMatrix : Cesium.Matrix4.multiplyByTranslation(Cesium.Transforms.eastNorthUpToFixedFrame(
   *     Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883)), new Cesium.Cartesian3(0.0, 0.0, 1000000.0), new Cesium.Matrix4()),
   *   id : 'box',
   *   attributes : {
   *     show : new Cesium.ShowGeometryInstanceAttribute(false)
   *   }
   * });
   *
   * @see GeometryInstance
   * @see GeometryInstanceAttribute
   */
  function ShowGeometryInstanceAttribute(show) {
    show = defaultValue(show, true);

    /**
     * The values for the attributes stored in a typed array.
     *
     * @type Uint8Array
     *
     * @default [1.0]
     */
    this.value = ShowGeometryInstanceAttribute.toValue(show);
  }

  Object.defineProperties(ShowGeometryInstanceAttribute.prototype, {
    /**
     * The datatype of each component in the attribute, e.g., individual elements in
     * {@link ColorGeometryInstanceAttribute#value}.
     *
     * @memberof ShowGeometryInstanceAttribute.prototype
     *
     * @type {ComponentDatatype}
     * @readonly
     *
     * @default {@link ComponentDatatype.UNSIGNED_BYTE}
     */
    componentDatatype: {
      get: function () {
        return ComponentDatatype$1.UNSIGNED_BYTE;
      },
    },

    /**
     * The number of components in the attributes, i.e., {@link ColorGeometryInstanceAttribute#value}.
     *
     * @memberof ShowGeometryInstanceAttribute.prototype
     *
     * @type {Number}
     * @readonly
     *
     * @default 1
     */
    componentsPerAttribute: {
      get: function () {
        return 1;
      },
    },

    /**
     * When <code>true</code> and <code>componentDatatype</code> is an integer format,
     * indicate that the components should be mapped to the range [0, 1] (unsigned)
     * or [-1, 1] (signed) when they are accessed as floating-point for rendering.
     *
     * @memberof ShowGeometryInstanceAttribute.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default true
     */
    normalize: {
      get: function () {
        return false;
      },
    },
  });

  /**
   * Converts a boolean show to a typed array that can be used to assign a show attribute.
   *
   * @param {Boolean} show The show value.
   * @param {Uint8Array} [result] The array to store the result in, if undefined a new instance will be created.
   * @returns {Uint8Array} The modified result parameter or a new instance if result was undefined.
   *
   * @example
   * const attributes = primitive.getGeometryInstanceAttributes('an id');
   * attributes.show = Cesium.ShowGeometryInstanceAttribute.toValue(true, attributes.show);
   */
  ShowGeometryInstanceAttribute.toValue = function (show, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(show)) {
      throw new DeveloperError("show is required.");
    }
    //>>includeEnd('debug');

    if (!defined(result)) {
      return new Uint8Array([show]);
    }
    result[0] = show;
    return result;
  };

  /**
   * Contains functions for finding the Cartesian coordinates of the sun and the moon in the
   * Earth-centered inertial frame.
   *
   * @namespace Simon1994PlanetaryPositions
   */
  const Simon1994PlanetaryPositions = {};

  function computeTdbMinusTtSpice(daysSinceJ2000InTerrestrialTime) {
    /* STK Comments ------------------------------------------------------
     * This function uses constants designed to be consistent with
     * the SPICE Toolkit from JPL version N0051 (unitim.c)
     * M0 = 6.239996
     * M0Dot = 1.99096871e-7 rad/s = 0.01720197 rad/d
     * EARTH_ECC = 1.671e-2
     * TDB_AMPL = 1.657e-3 secs
     *--------------------------------------------------------------------*/

    //* Values taken as specified in STK Comments except: 0.01720197 rad/day = 1.99096871e-7 rad/sec
    //* Here we use the more precise value taken from the SPICE value 1.99096871e-7 rad/sec converted to rad/day
    //* All other constants are consistent with the SPICE implementation of the TDB conversion
    //* except where we treat the independent time parameter to be in TT instead of TDB.
    //* This is an approximation made to facilitate performance due to the higher prevalance of
    //* the TT2TDB conversion over TDB2TT in order to avoid having to iterate when converting to TDB for the JPL ephemeris.
    //* Days are used instead of seconds to provide a slight improvement in numerical precision.

    //* For more information see:
    //* http://www.cv.nrao.edu/~rfisher/Ephemerides/times.html#TDB
    //* ftp://ssd.jpl.nasa.gov/pub/eph/planets/ioms/ExplSupplChap8.pdf

    const g = 6.239996 + 0.0172019696544 * daysSinceJ2000InTerrestrialTime;
    return 1.657e-3 * Math.sin(g + 1.671e-2 * Math.sin(g));
  }

  const TdtMinusTai = 32.184;
  const J2000d = 2451545;
  function taiToTdb(date, result) {
    //Converts TAI to TT
    result = JulianDate.addSeconds(date, TdtMinusTai, result);

    //Converts TT to TDB
    const days = JulianDate.totalDays(result) - J2000d;
    result = JulianDate.addSeconds(result, computeTdbMinusTtSpice(days), result);

    return result;
  }

  const epoch = new JulianDate(2451545, 0, TimeStandard$1.TAI); //Actually TDB (not TAI)
  const MetersPerKilometer = 1000.0;
  const RadiansPerDegree = CesiumMath.RADIANS_PER_DEGREE;
  const RadiansPerArcSecond = CesiumMath.RADIANS_PER_ARCSECOND;
  const MetersPerAstronomicalUnit = 1.4959787e11; // IAU 1976 value

  const perifocalToEquatorial = new Matrix3();
  function elementsToCartesian(
    semimajorAxis,
    eccentricity,
    inclination,
    longitudeOfPerigee,
    longitudeOfNode,
    meanLongitude,
    result
  ) {
    if (inclination < 0.0) {
      inclination = -inclination;
      longitudeOfNode += CesiumMath.PI;
    }

    //>>includeStart('debug', pragmas.debug);
    if (inclination < 0 || inclination > CesiumMath.PI) {
      throw new DeveloperError(
        "The inclination is out of range. Inclination must be greater than or equal to zero and less than or equal to Pi radians."
      );
    }
    //>>includeEnd('debug')

    const radiusOfPeriapsis = semimajorAxis * (1.0 - eccentricity);
    const argumentOfPeriapsis = longitudeOfPerigee - longitudeOfNode;
    const rightAscensionOfAscendingNode = longitudeOfNode;
    const trueAnomaly = meanAnomalyToTrueAnomaly(
      meanLongitude - longitudeOfPerigee,
      eccentricity
    );
    const type = chooseOrbit(eccentricity, 0.0);

    //>>includeStart('debug', pragmas.debug);
    if (
      type === "Hyperbolic" &&
      Math.abs(CesiumMath.negativePiToPi(trueAnomaly)) >=
        Math.acos(-1.0 / eccentricity)
    ) {
      throw new DeveloperError(
        "The true anomaly of the hyperbolic orbit lies outside of the bounds of the hyperbola."
      );
    }
    //>>includeEnd('debug')

    perifocalToCartesianMatrix(
      argumentOfPeriapsis,
      inclination,
      rightAscensionOfAscendingNode,
      perifocalToEquatorial
    );
    const semilatus = radiusOfPeriapsis * (1.0 + eccentricity);
    const costheta = Math.cos(trueAnomaly);
    const sintheta = Math.sin(trueAnomaly);

    const denom = 1.0 + eccentricity * costheta;

    //>>includeStart('debug', pragmas.debug);
    if (denom <= CesiumMath.Epsilon10) {
      throw new DeveloperError("elements cannot be converted to cartesian");
    }
    //>>includeEnd('debug')

    const radius = semilatus / denom;
    if (!defined(result)) {
      result = new Cartesian3(radius * costheta, radius * sintheta, 0.0);
    } else {
      result.x = radius * costheta;
      result.y = radius * sintheta;
      result.z = 0.0;
    }

    return Matrix3.multiplyByVector(perifocalToEquatorial, result, result);
  }

  function chooseOrbit(eccentricity, tolerance) {
    //>>includeStart('debug', pragmas.debug);
    if (eccentricity < 0) {
      throw new DeveloperError("eccentricity cannot be negative.");
    }
    //>>includeEnd('debug')

    if (eccentricity <= tolerance) {
      return "Circular";
    } else if (eccentricity < 1.0 - tolerance) {
      return "Elliptical";
    } else if (eccentricity <= 1.0 + tolerance) {
      return "Parabolic";
    }
    return "Hyperbolic";
  }

  // Calculates the true anomaly given the mean anomaly and the eccentricity.
  function meanAnomalyToTrueAnomaly(meanAnomaly, eccentricity) {
    //>>includeStart('debug', pragmas.debug);
    if (eccentricity < 0.0 || eccentricity >= 1.0) {
      throw new DeveloperError("eccentricity out of range.");
    }
    //>>includeEnd('debug')

    const eccentricAnomaly = meanAnomalyToEccentricAnomaly(
      meanAnomaly,
      eccentricity
    );
    return eccentricAnomalyToTrueAnomaly(eccentricAnomaly, eccentricity);
  }

  const maxIterationCount = 50;
  const keplerEqConvergence = CesiumMath.EPSILON8;
  // Calculates the eccentric anomaly given the mean anomaly and the eccentricity.
  function meanAnomalyToEccentricAnomaly(meanAnomaly, eccentricity) {
    //>>includeStart('debug', pragmas.debug);
    if (eccentricity < 0.0 || eccentricity >= 1.0) {
      throw new DeveloperError("eccentricity out of range.");
    }
    //>>includeEnd('debug')

    const revs = Math.floor(meanAnomaly / CesiumMath.TWO_PI);

    // Find angle in current revolution
    meanAnomaly -= revs * CesiumMath.TWO_PI;

    // calculate starting value for iteration sequence
    let iterationValue =
      meanAnomaly +
      (eccentricity * Math.sin(meanAnomaly)) /
        (1.0 - Math.sin(meanAnomaly + eccentricity) + Math.sin(meanAnomaly));

    // Perform Newton-Raphson iteration on Kepler's equation
    let eccentricAnomaly = Number.MAX_VALUE;

    let count;
    for (
      count = 0;
      count < maxIterationCount &&
      Math.abs(eccentricAnomaly - iterationValue) > keplerEqConvergence;
      ++count
    ) {
      eccentricAnomaly = iterationValue;
      const NRfunction =
        eccentricAnomaly -
        eccentricity * Math.sin(eccentricAnomaly) -
        meanAnomaly;
      const dNRfunction = 1 - eccentricity * Math.cos(eccentricAnomaly);
      iterationValue = eccentricAnomaly - NRfunction / dNRfunction;
    }

    //>>includeStart('debug', pragmas.debug);
    if (count >= maxIterationCount) {
      throw new DeveloperError("Kepler equation did not converge");
      // STK Components uses a numerical method to find the eccentric anomaly in the case that Kepler's
      // equation does not converge. We don't expect that to ever be necessary for the reasonable orbits used here.
    }
    //>>includeEnd('debug')

    eccentricAnomaly = iterationValue + revs * CesiumMath.TWO_PI;
    return eccentricAnomaly;
  }

  // Calculates the true anomaly given the eccentric anomaly and the eccentricity.
  function eccentricAnomalyToTrueAnomaly(eccentricAnomaly, eccentricity) {
    //>>includeStart('debug', pragmas.debug);
    if (eccentricity < 0.0 || eccentricity >= 1.0) {
      throw new DeveloperError("eccentricity out of range.");
    }
    //>>includeEnd('debug')

    // Calculate the number of previous revolutions
    const revs = Math.floor(eccentricAnomaly / CesiumMath.TWO_PI);

    // Find angle in current revolution
    eccentricAnomaly -= revs * CesiumMath.TWO_PI;

    // Calculate true anomaly from eccentric anomaly
    const trueAnomalyX = Math.cos(eccentricAnomaly) - eccentricity;
    const trueAnomalyY =
      Math.sin(eccentricAnomaly) * Math.sqrt(1 - eccentricity * eccentricity);

    let trueAnomaly = Math.atan2(trueAnomalyY, trueAnomalyX);

    // Ensure the correct quadrant
    trueAnomaly = CesiumMath.zeroToTwoPi(trueAnomaly);
    if (eccentricAnomaly < 0) {
      trueAnomaly -= CesiumMath.TWO_PI;
    }

    // Add on previous revolutions
    trueAnomaly += revs * CesiumMath.TWO_PI;

    return trueAnomaly;
  }

  // Calculates the transformation matrix to convert from the perifocal (PQW) coordinate
  // system to inertial cartesian coordinates.
  function perifocalToCartesianMatrix(
    argumentOfPeriapsis,
    inclination,
    rightAscension,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (inclination < 0 || inclination > CesiumMath.PI) {
      throw new DeveloperError("inclination out of range");
    }
    //>>includeEnd('debug')

    const cosap = Math.cos(argumentOfPeriapsis);
    const sinap = Math.sin(argumentOfPeriapsis);

    const cosi = Math.cos(inclination);
    const sini = Math.sin(inclination);

    const cosraan = Math.cos(rightAscension);
    const sinraan = Math.sin(rightAscension);
    if (!defined(result)) {
      result = new Matrix3(
        cosraan * cosap - sinraan * sinap * cosi,
        -cosraan * sinap - sinraan * cosap * cosi,
        sinraan * sini,

        sinraan * cosap + cosraan * sinap * cosi,
        -sinraan * sinap + cosraan * cosap * cosi,
        -cosraan * sini,

        sinap * sini,
        cosap * sini,
        cosi
      );
    } else {
      result[0] = cosraan * cosap - sinraan * sinap * cosi;
      result[1] = sinraan * cosap + cosraan * sinap * cosi;
      result[2] = sinap * sini;
      result[3] = -cosraan * sinap - sinraan * cosap * cosi;
      result[4] = -sinraan * sinap + cosraan * cosap * cosi;
      result[5] = cosap * sini;
      result[6] = sinraan * sini;
      result[7] = -cosraan * sini;
      result[8] = cosi;
    }
    return result;
  }

  // From section 5.8
  const semiMajorAxis0 = 1.0000010178 * MetersPerAstronomicalUnit;
  const meanLongitude0 = 100.46645683 * RadiansPerDegree;
  const meanLongitude1 = 1295977422.83429 * RadiansPerArcSecond;

  // From table 6
  const p1u = 16002;
  const p2u = 21863;
  const p3u = 32004;
  const p4u = 10931;
  const p5u = 14529;
  const p6u = 16368;
  const p7u = 15318;
  const p8u = 32794;

  const Ca1 = 64 * 1e-7 * MetersPerAstronomicalUnit;
  const Ca2 = -152 * 1e-7 * MetersPerAstronomicalUnit;
  const Ca3 = 62 * 1e-7 * MetersPerAstronomicalUnit;
  const Ca4 = -8 * 1e-7 * MetersPerAstronomicalUnit;
  const Ca5 = 32 * 1e-7 * MetersPerAstronomicalUnit;
  const Ca6 = -41 * 1e-7 * MetersPerAstronomicalUnit;
  const Ca7 = 19 * 1e-7 * MetersPerAstronomicalUnit;
  const Ca8 = -11 * 1e-7 * MetersPerAstronomicalUnit;

  const Sa1 = -150 * 1e-7 * MetersPerAstronomicalUnit;
  const Sa2 = -46 * 1e-7 * MetersPerAstronomicalUnit;
  const Sa3 = 68 * 1e-7 * MetersPerAstronomicalUnit;
  const Sa4 = 54 * 1e-7 * MetersPerAstronomicalUnit;
  const Sa5 = 14 * 1e-7 * MetersPerAstronomicalUnit;
  const Sa6 = 24 * 1e-7 * MetersPerAstronomicalUnit;
  const Sa7 = -28 * 1e-7 * MetersPerAstronomicalUnit;
  const Sa8 = 22 * 1e-7 * MetersPerAstronomicalUnit;

  const q1u = 10;
  const q2u = 16002;
  const q3u = 21863;
  const q4u = 10931;
  const q5u = 1473;
  const q6u = 32004;
  const q7u = 4387;
  const q8u = 73;

  const Cl1 = -325 * 1e-7;
  const Cl2 = -322 * 1e-7;
  const Cl3 = -79 * 1e-7;
  const Cl4 = 232 * 1e-7;
  const Cl5 = -52 * 1e-7;
  const Cl6 = 97 * 1e-7;
  const Cl7 = 55 * 1e-7;
  const Cl8 = -41 * 1e-7;

  const Sl1 = -105 * 1e-7;
  const Sl2 = -137 * 1e-7;
  const Sl3 = 258 * 1e-7;
  const Sl4 = 35 * 1e-7;
  const Sl5 = -116 * 1e-7;
  const Sl6 = -88 * 1e-7;
  const Sl7 = -112 * 1e-7;
  const Sl8 = -80 * 1e-7;

  const scratchDate$1 = new JulianDate(0, 0.0, TimeStandard$1.TAI);
  // Gets a point describing the motion of the Earth-Moon barycenter according to the equations described in section 6.
  function computeSimonEarthMoonBarycenter(date, result) {
    // t is thousands of years from J2000 TDB
    taiToTdb(date, scratchDate$1);
    const x =
      scratchDate$1.dayNumber -
      epoch.dayNumber +
      (scratchDate$1.secondsOfDay - epoch.secondsOfDay) /
        TimeConstants$1.SECONDS_PER_DAY;
    const t = x / (TimeConstants$1.DAYS_PER_JULIAN_CENTURY * 10.0);

    const u = 0.3595362 * t;
    const semimajorAxis =
      semiMajorAxis0 +
      Ca1 * Math.cos(p1u * u) +
      Sa1 * Math.sin(p1u * u) +
      Ca2 * Math.cos(p2u * u) +
      Sa2 * Math.sin(p2u * u) +
      Ca3 * Math.cos(p3u * u) +
      Sa3 * Math.sin(p3u * u) +
      Ca4 * Math.cos(p4u * u) +
      Sa4 * Math.sin(p4u * u) +
      Ca5 * Math.cos(p5u * u) +
      Sa5 * Math.sin(p5u * u) +
      Ca6 * Math.cos(p6u * u) +
      Sa6 * Math.sin(p6u * u) +
      Ca7 * Math.cos(p7u * u) +
      Sa7 * Math.sin(p7u * u) +
      Ca8 * Math.cos(p8u * u) +
      Sa8 * Math.sin(p8u * u);
    const meanLongitude =
      meanLongitude0 +
      meanLongitude1 * t +
      Cl1 * Math.cos(q1u * u) +
      Sl1 * Math.sin(q1u * u) +
      Cl2 * Math.cos(q2u * u) +
      Sl2 * Math.sin(q2u * u) +
      Cl3 * Math.cos(q3u * u) +
      Sl3 * Math.sin(q3u * u) +
      Cl4 * Math.cos(q4u * u) +
      Sl4 * Math.sin(q4u * u) +
      Cl5 * Math.cos(q5u * u) +
      Sl5 * Math.sin(q5u * u) +
      Cl6 * Math.cos(q6u * u) +
      Sl6 * Math.sin(q6u * u) +
      Cl7 * Math.cos(q7u * u) +
      Sl7 * Math.sin(q7u * u) +
      Cl8 * Math.cos(q8u * u) +
      Sl8 * Math.sin(q8u * u);

    // All constants in this part are from section 5.8
    const eccentricity = 0.0167086342 - 0.0004203654 * t;
    const longitudeOfPerigee =
      102.93734808 * RadiansPerDegree + 11612.3529 * RadiansPerArcSecond * t;
    const inclination = 469.97289 * RadiansPerArcSecond * t;
    const longitudeOfNode =
      174.87317577 * RadiansPerDegree - 8679.27034 * RadiansPerArcSecond * t;

    return elementsToCartesian(
      semimajorAxis,
      eccentricity,
      inclination,
      longitudeOfPerigee,
      longitudeOfNode,
      meanLongitude,
      result
    );
  }

  // Gets a point describing the position of the moon according to the equations described in section 4.
  function computeSimonMoon(date, result) {
    taiToTdb(date, scratchDate$1);
    const x =
      scratchDate$1.dayNumber -
      epoch.dayNumber +
      (scratchDate$1.secondsOfDay - epoch.secondsOfDay) /
        TimeConstants$1.SECONDS_PER_DAY;
    const t = x / TimeConstants$1.DAYS_PER_JULIAN_CENTURY;
    const t2 = t * t;
    const t3 = t2 * t;
    const t4 = t3 * t;

    // Terms from section 3.4 (b.1)
    let semimajorAxis = 383397.7725 + 0.004 * t;
    let eccentricity = 0.055545526 - 0.000000016 * t;
    const inclinationConstant = 5.15668983 * RadiansPerDegree;
    let inclinationSecPart =
      -0.00008 * t + 0.02966 * t2 - 0.000042 * t3 - 0.00000013 * t4;
    const longitudeOfPerigeeConstant = 83.35324312 * RadiansPerDegree;
    let longitudeOfPerigeeSecPart =
      14643420.2669 * t - 38.2702 * t2 - 0.045047 * t3 + 0.00021301 * t4;
    const longitudeOfNodeConstant = 125.04455501 * RadiansPerDegree;
    let longitudeOfNodeSecPart =
      -6967919.3631 * t + 6.3602 * t2 + 0.007625 * t3 - 0.00003586 * t4;
    const meanLongitudeConstant = 218.31664563 * RadiansPerDegree;
    let meanLongitudeSecPart =
      1732559343.4847 * t - 6.391 * t2 + 0.006588 * t3 - 0.00003169 * t4;

    // Delaunay arguments from section 3.5 b
    const D =
      297.85019547 * RadiansPerDegree +
      RadiansPerArcSecond *
        (1602961601.209 * t - 6.3706 * t2 + 0.006593 * t3 - 0.00003169 * t4);
    const F =
      93.27209062 * RadiansPerDegree +
      RadiansPerArcSecond *
        (1739527262.8478 * t - 12.7512 * t2 - 0.001037 * t3 + 0.00000417 * t4);
    const l =
      134.96340251 * RadiansPerDegree +
      RadiansPerArcSecond *
        (1717915923.2178 * t + 31.8792 * t2 + 0.051635 * t3 - 0.0002447 * t4);
    const lprime =
      357.52910918 * RadiansPerDegree +
      RadiansPerArcSecond *
        (129596581.0481 * t - 0.5532 * t2 + 0.000136 * t3 - 0.00001149 * t4);
    const psi =
      310.17137918 * RadiansPerDegree -
      RadiansPerArcSecond *
        (6967051.436 * t + 6.2068 * t2 + 0.007618 * t3 - 0.00003219 * t4);

    // Add terms from Table 4
    const twoD = 2.0 * D;
    const fourD = 4.0 * D;
    const sixD = 6.0 * D;
    const twol = 2.0 * l;
    const threel = 3.0 * l;
    const fourl = 4.0 * l;
    const twoF = 2.0 * F;
    semimajorAxis +=
      3400.4 * Math.cos(twoD) -
      635.6 * Math.cos(twoD - l) -
      235.6 * Math.cos(l) +
      218.1 * Math.cos(twoD - lprime) +
      181.0 * Math.cos(twoD + l);
    eccentricity +=
      0.014216 * Math.cos(twoD - l) +
      0.008551 * Math.cos(twoD - twol) -
      0.001383 * Math.cos(l) +
      0.001356 * Math.cos(twoD + l) -
      0.001147 * Math.cos(fourD - threel) -
      0.000914 * Math.cos(fourD - twol) +
      0.000869 * Math.cos(twoD - lprime - l) -
      0.000627 * Math.cos(twoD) -
      0.000394 * Math.cos(fourD - fourl) +
      0.000282 * Math.cos(twoD - lprime - twol) -
      0.000279 * Math.cos(D - l) -
      0.000236 * Math.cos(twol) +
      0.000231 * Math.cos(fourD) +
      0.000229 * Math.cos(sixD - fourl) -
      0.000201 * Math.cos(twol - twoF);
    inclinationSecPart +=
      486.26 * Math.cos(twoD - twoF) -
      40.13 * Math.cos(twoD) +
      37.51 * Math.cos(twoF) +
      25.73 * Math.cos(twol - twoF) +
      19.97 * Math.cos(twoD - lprime - twoF);
    longitudeOfPerigeeSecPart +=
      -55609 * Math.sin(twoD - l) -
      34711 * Math.sin(twoD - twol) -
      9792 * Math.sin(l) +
      9385 * Math.sin(fourD - threel) +
      7505 * Math.sin(fourD - twol) +
      5318 * Math.sin(twoD + l) +
      3484 * Math.sin(fourD - fourl) -
      3417 * Math.sin(twoD - lprime - l) -
      2530 * Math.sin(sixD - fourl) -
      2376 * Math.sin(twoD) -
      2075 * Math.sin(twoD - threel) -
      1883 * Math.sin(twol) -
      1736 * Math.sin(sixD - 5.0 * l) +
      1626 * Math.sin(lprime) -
      1370 * Math.sin(sixD - threel);
    longitudeOfNodeSecPart +=
      -5392 * Math.sin(twoD - twoF) -
      540 * Math.sin(lprime) -
      441 * Math.sin(twoD) +
      423 * Math.sin(twoF) -
      288 * Math.sin(twol - twoF);
    meanLongitudeSecPart +=
      -3332.9 * Math.sin(twoD) +
      1197.4 * Math.sin(twoD - l) -
      662.5 * Math.sin(lprime) +
      396.3 * Math.sin(l) -
      218.0 * Math.sin(twoD - lprime);

    // Add terms from Table 5
    const twoPsi = 2.0 * psi;
    const threePsi = 3.0 * psi;
    inclinationSecPart +=
      46.997 * Math.cos(psi) * t -
      0.614 * Math.cos(twoD - twoF + psi) * t +
      0.614 * Math.cos(twoD - twoF - psi) * t -
      0.0297 * Math.cos(twoPsi) * t2 -
      0.0335 * Math.cos(psi) * t2 +
      0.0012 * Math.cos(twoD - twoF + twoPsi) * t2 -
      0.00016 * Math.cos(psi) * t3 +
      0.00004 * Math.cos(threePsi) * t3 +
      0.00004 * Math.cos(twoPsi) * t3;
    const perigeeAndMean =
      2.116 * Math.sin(psi) * t -
      0.111 * Math.sin(twoD - twoF - psi) * t -
      0.0015 * Math.sin(psi) * t2;
    longitudeOfPerigeeSecPart += perigeeAndMean;
    meanLongitudeSecPart += perigeeAndMean;
    longitudeOfNodeSecPart +=
      -520.77 * Math.sin(psi) * t +
      13.66 * Math.sin(twoD - twoF + psi) * t +
      1.12 * Math.sin(twoD - psi) * t -
      1.06 * Math.sin(twoF - psi) * t +
      0.66 * Math.sin(twoPsi) * t2 +
      0.371 * Math.sin(psi) * t2 -
      0.035 * Math.sin(twoD - twoF + twoPsi) * t2 -
      0.015 * Math.sin(twoD - twoF + psi) * t2 +
      0.0014 * Math.sin(psi) * t3 -
      0.0011 * Math.sin(threePsi) * t3 -
      0.0009 * Math.sin(twoPsi) * t3;

    // Add constants and convert units
    semimajorAxis *= MetersPerKilometer;
    const inclination =
      inclinationConstant + inclinationSecPart * RadiansPerArcSecond;
    const longitudeOfPerigee =
      longitudeOfPerigeeConstant +
      longitudeOfPerigeeSecPart * RadiansPerArcSecond;
    const meanLongitude =
      meanLongitudeConstant + meanLongitudeSecPart * RadiansPerArcSecond;
    const longitudeOfNode =
      longitudeOfNodeConstant + longitudeOfNodeSecPart * RadiansPerArcSecond;

    return elementsToCartesian(
      semimajorAxis,
      eccentricity,
      inclination,
      longitudeOfPerigee,
      longitudeOfNode,
      meanLongitude,
      result
    );
  }

  // Gets a point describing the motion of the Earth.  This point uses the Moon point and
  // the 1992 mu value (ratio between Moon and Earth masses) in Table 2 of the paper in order
  // to determine the position of the Earth relative to the Earth-Moon barycenter.
  const moonEarthMassRatio = 0.012300034; // From 1992 mu value in Table 2
  const factor = (moonEarthMassRatio / (moonEarthMassRatio + 1.0)) * -1;
  function computeSimonEarth(date, result) {
    result = computeSimonMoon(date, result);
    return Cartesian3.multiplyByScalar(result, factor, result);
  }

  // Values for the <code>axesTransformation</code> needed for the rotation were found using the STK Components
  // GreographicTransformer on the position of the sun center of mass point and the earth J2000 frame.

  const axesTransformation = new Matrix3(
    1.0000000000000002,
    5.619723173785822e-16,
    4.690511510146299e-19,
    -5.154129427414611e-16,
    0.9174820620691819,
    -0.39777715593191376,
    -2.23970096136568e-16,
    0.39777715593191376,
    0.9174820620691819
  );
  let translation = new Cartesian3();
  /**
   * Computes the position of the Sun in the Earth-centered inertial frame
   *
   * @param {JulianDate} [julianDate] The time at which to compute the Sun's position, if not provided the current system time is used.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} Calculated sun position
   */
  Simon1994PlanetaryPositions.computeSunPositionInEarthInertialFrame = function (
    julianDate,
    result
  ) {
    if (!defined(julianDate)) {
      julianDate = JulianDate.now();
    }

    if (!defined(result)) {
      result = new Cartesian3();
    }

    //first forward transformation
    translation = computeSimonEarthMoonBarycenter(julianDate, translation);
    result = Cartesian3.negate(translation, result);

    //second forward transformation
    computeSimonEarth(julianDate, translation);

    Cartesian3.subtract(result, translation, result);
    Matrix3.multiplyByVector(axesTransformation, result, result);

    return result;
  };

  /**
   * Computes the position of the Moon in the Earth-centered inertial frame
   *
   * @param {JulianDate} [julianDate] The time at which to compute the Sun's position, if not provided the current system time is used.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} Calculated moon position
   */
  Simon1994PlanetaryPositions.computeMoonPositionInEarthInertialFrame = function (
    julianDate,
    result
  ) {
    if (!defined(julianDate)) {
      julianDate = JulianDate.now();
    }

    result = computeSimonMoon(julianDate, result);
    Matrix3.multiplyByVector(axesTransformation, result, result);

    return result;
  };

  function interpolateColors(p0, p1, color0, color1, minDistance, array, offset) {
    const numPoints = PolylinePipeline.numberOfPoints(p0, p1, minDistance);
    let i;

    const r0 = color0.red;
    const g0 = color0.green;
    const b0 = color0.blue;
    const a0 = color0.alpha;

    const r1 = color1.red;
    const g1 = color1.green;
    const b1 = color1.blue;
    const a1 = color1.alpha;

    if (Color.equals(color0, color1)) {
      for (i = 0; i < numPoints; i++) {
        array[offset++] = Color.floatToByte(r0);
        array[offset++] = Color.floatToByte(g0);
        array[offset++] = Color.floatToByte(b0);
        array[offset++] = Color.floatToByte(a0);
      }
      return offset;
    }

    const redPerVertex = (r1 - r0) / numPoints;
    const greenPerVertex = (g1 - g0) / numPoints;
    const bluePerVertex = (b1 - b0) / numPoints;
    const alphaPerVertex = (a1 - a0) / numPoints;

    let index = offset;
    for (i = 0; i < numPoints; i++) {
      array[index++] = Color.floatToByte(r0 + i * redPerVertex);
      array[index++] = Color.floatToByte(g0 + i * greenPerVertex);
      array[index++] = Color.floatToByte(b0 + i * bluePerVertex);
      array[index++] = Color.floatToByte(a0 + i * alphaPerVertex);
    }

    return index;
  }

  /**
   * A description of a polyline modeled as a line strip; the first two positions define a line segment,
   * and each additional position defines a line segment from the previous position.
   *
   * @alias SimplePolylineGeometry
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Cartesian3[]} options.positions An array of {@link Cartesian3} defining the positions in the polyline as a line strip.
   * @param {Color[]} [options.colors] An Array of {@link Color} defining the per vertex or per segment colors.
   * @param {Boolean} [options.colorsPerVertex=false] A boolean that determines whether the colors will be flat across each segment of the line or interpolated across the vertices.
   * @param {ArcType} [options.arcType=ArcType.GEODESIC] The type of line the polyline segments must follow.
   * @param {Number} [options.granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude if options.arcType is not ArcType.NONE. Determines the number of positions in the buffer.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid to be used as a reference.
   *
   * @exception {DeveloperError} At least two positions are required.
   * @exception {DeveloperError} colors has an invalid length.
   *
   * @see SimplePolylineGeometry#createGeometry
   *
   * @example
   * // A polyline with two connected line segments
   * const polyline = new Cesium.SimplePolylineGeometry({
   *   positions : Cesium.Cartesian3.fromDegreesArray([
   *     0.0, 0.0,
   *     5.0, 0.0,
   *     5.0, 5.0
   *   ])
   * });
   * const geometry = Cesium.SimplePolylineGeometry.createGeometry(polyline);
   */
  function SimplePolylineGeometry(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const positions = options.positions;
    const colors = options.colors;
    const colorsPerVertex = defaultValue(options.colorsPerVertex, false);

    //>>includeStart('debug', pragmas.debug);
    if (!defined(positions) || positions.length < 2) {
      throw new DeveloperError("At least two positions are required.");
    }
    if (
      defined(colors) &&
      ((colorsPerVertex && colors.length < positions.length) ||
        (!colorsPerVertex && colors.length < positions.length - 1))
    ) {
      throw new DeveloperError("colors has an invalid length.");
    }
    //>>includeEnd('debug');

    this._positions = positions;
    this._colors = colors;
    this._colorsPerVertex = colorsPerVertex;

    this._arcType = defaultValue(options.arcType, ArcType$1.GEODESIC);
    this._granularity = defaultValue(
      options.granularity,
      CesiumMath.RADIANS_PER_DEGREE
    );
    this._ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);
    this._workerName = "createSimplePolylineGeometry";

    let numComponents = 1 + positions.length * Cartesian3.packedLength;
    numComponents += defined(colors) ? 1 + colors.length * Color.packedLength : 1;

    /**
     * The number of elements used to pack the object into an array.
     * @type {Number}
     */
    this.packedLength = numComponents + Ellipsoid.packedLength + 3;
  }

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {SimplePolylineGeometry} 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
   */
  SimplePolylineGeometry.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(value)) {
      throw new DeveloperError("value is required");
    }
    if (!defined(array)) {
      throw new DeveloperError("array is required");
    }
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    let i;

    const positions = value._positions;
    let length = positions.length;
    array[startingIndex++] = length;

    for (i = 0; i < length; ++i, startingIndex += Cartesian3.packedLength) {
      Cartesian3.pack(positions[i], array, startingIndex);
    }

    const colors = value._colors;
    length = defined(colors) ? colors.length : 0.0;
    array[startingIndex++] = length;

    for (i = 0; i < length; ++i, startingIndex += Color.packedLength) {
      Color.pack(colors[i], array, startingIndex);
    }

    Ellipsoid.pack(value._ellipsoid, array, startingIndex);
    startingIndex += Ellipsoid.packedLength;

    array[startingIndex++] = value._colorsPerVertex ? 1.0 : 0.0;
    array[startingIndex++] = value._arcType;
    array[startingIndex] = value._granularity;

    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 {SimplePolylineGeometry} [result] The object into which to store the result.
   * @returns {SimplePolylineGeometry} The modified result parameter or a new SimplePolylineGeometry instance if one was not provided.
   */
  SimplePolylineGeometry.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(array)) {
      throw new DeveloperError("array is required");
    }
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    let i;

    let length = array[startingIndex++];
    const positions = new Array(length);

    for (i = 0; i < length; ++i, startingIndex += Cartesian3.packedLength) {
      positions[i] = Cartesian3.unpack(array, startingIndex);
    }

    length = array[startingIndex++];
    const colors = length > 0 ? new Array(length) : undefined;

    for (i = 0; i < length; ++i, startingIndex += Color.packedLength) {
      colors[i] = Color.unpack(array, startingIndex);
    }

    const ellipsoid = Ellipsoid.unpack(array, startingIndex);
    startingIndex += Ellipsoid.packedLength;

    const colorsPerVertex = array[startingIndex++] === 1.0;
    const arcType = array[startingIndex++];
    const granularity = array[startingIndex];

    if (!defined(result)) {
      return new SimplePolylineGeometry({
        positions: positions,
        colors: colors,
        ellipsoid: ellipsoid,
        colorsPerVertex: colorsPerVertex,
        arcType: arcType,
        granularity: granularity,
      });
    }

    result._positions = positions;
    result._colors = colors;
    result._ellipsoid = ellipsoid;
    result._colorsPerVertex = colorsPerVertex;
    result._arcType = arcType;
    result._granularity = granularity;

    return result;
  };

  const scratchArray1 = new Array(2);
  const scratchArray2 = new Array(2);
  const generateArcOptionsScratch$1 = {
    positions: scratchArray1,
    height: scratchArray2,
    ellipsoid: undefined,
    minDistance: undefined,
    granularity: undefined,
  };

  /**
   * Computes the geometric representation of a simple polyline, including its vertices, indices, and a bounding sphere.
   *
   * @param {SimplePolylineGeometry} simplePolylineGeometry A description of the polyline.
   * @returns {Geometry|undefined} The computed vertices and indices.
   */
  SimplePolylineGeometry.createGeometry = function (simplePolylineGeometry) {
    const positions = simplePolylineGeometry._positions;
    const colors = simplePolylineGeometry._colors;
    const colorsPerVertex = simplePolylineGeometry._colorsPerVertex;
    const arcType = simplePolylineGeometry._arcType;
    const granularity = simplePolylineGeometry._granularity;
    const ellipsoid = simplePolylineGeometry._ellipsoid;

    const minDistance = CesiumMath.chordLength(
      granularity,
      ellipsoid.maximumRadius
    );
    const perSegmentColors = defined(colors) && !colorsPerVertex;

    let i;
    const length = positions.length;

    let positionValues;
    let numberOfPositions;
    let colorValues;
    let color;
    let offset = 0;

    if (arcType === ArcType$1.GEODESIC || arcType === ArcType$1.RHUMB) {
      let subdivisionSize;
      let numberOfPointsFunction;
      let generateArcFunction;
      if (arcType === ArcType$1.GEODESIC) {
        subdivisionSize = CesiumMath.chordLength(
          granularity,
          ellipsoid.maximumRadius
        );
        numberOfPointsFunction = PolylinePipeline.numberOfPoints;
        generateArcFunction = PolylinePipeline.generateArc;
      } else {
        subdivisionSize = granularity;
        numberOfPointsFunction = PolylinePipeline.numberOfPointsRhumbLine;
        generateArcFunction = PolylinePipeline.generateRhumbArc;
      }

      const heights = PolylinePipeline.extractHeights(positions, ellipsoid);

      const generateArcOptions = generateArcOptionsScratch$1;
      if (arcType === ArcType$1.GEODESIC) {
        generateArcOptions.minDistance = minDistance;
      } else {
        generateArcOptions.granularity = granularity;
      }
      generateArcOptions.ellipsoid = ellipsoid;

      if (perSegmentColors) {
        let positionCount = 0;
        for (i = 0; i < length - 1; i++) {
          positionCount +=
            numberOfPointsFunction(
              positions[i],
              positions[i + 1],
              subdivisionSize
            ) + 1;
        }

        positionValues = new Float64Array(positionCount * 3);
        colorValues = new Uint8Array(positionCount * 4);

        generateArcOptions.positions = scratchArray1;
        generateArcOptions.height = scratchArray2;

        let ci = 0;
        for (i = 0; i < length - 1; ++i) {
          scratchArray1[0] = positions[i];
          scratchArray1[1] = positions[i + 1];

          scratchArray2[0] = heights[i];
          scratchArray2[1] = heights[i + 1];

          const pos = generateArcFunction(generateArcOptions);

          if (defined(colors)) {
            const segLen = pos.length / 3;
            color = colors[i];
            for (let k = 0; k < segLen; ++k) {
              colorValues[ci++] = Color.floatToByte(color.red);
              colorValues[ci++] = Color.floatToByte(color.green);
              colorValues[ci++] = Color.floatToByte(color.blue);
              colorValues[ci++] = Color.floatToByte(color.alpha);
            }
          }

          positionValues.set(pos, offset);
          offset += pos.length;
        }
      } else {
        generateArcOptions.positions = positions;
        generateArcOptions.height = heights;
        positionValues = new Float64Array(
          generateArcFunction(generateArcOptions)
        );

        if (defined(colors)) {
          colorValues = new Uint8Array((positionValues.length / 3) * 4);

          for (i = 0; i < length - 1; ++i) {
            const p0 = positions[i];
            const p1 = positions[i + 1];
            const c0 = colors[i];
            const c1 = colors[i + 1];
            offset = interpolateColors(
              p0,
              p1,
              c0,
              c1,
              minDistance,
              colorValues,
              offset
            );
          }

          const lastColor = colors[length - 1];
          colorValues[offset++] = Color.floatToByte(lastColor.red);
          colorValues[offset++] = Color.floatToByte(lastColor.green);
          colorValues[offset++] = Color.floatToByte(lastColor.blue);
          colorValues[offset++] = Color.floatToByte(lastColor.alpha);
        }
      }
    } else {
      numberOfPositions = perSegmentColors ? length * 2 - 2 : length;
      positionValues = new Float64Array(numberOfPositions * 3);
      colorValues = defined(colors)
        ? new Uint8Array(numberOfPositions * 4)
        : undefined;

      let positionIndex = 0;
      let colorIndex = 0;

      for (i = 0; i < length; ++i) {
        const p = positions[i];

        if (perSegmentColors && i > 0) {
          Cartesian3.pack(p, positionValues, positionIndex);
          positionIndex += 3;

          color = colors[i - 1];
          colorValues[colorIndex++] = Color.floatToByte(color.red);
          colorValues[colorIndex++] = Color.floatToByte(color.green);
          colorValues[colorIndex++] = Color.floatToByte(color.blue);
          colorValues[colorIndex++] = Color.floatToByte(color.alpha);
        }

        if (perSegmentColors && i === length - 1) {
          break;
        }

        Cartesian3.pack(p, positionValues, positionIndex);
        positionIndex += 3;

        if (defined(colors)) {
          color = colors[i];
          colorValues[colorIndex++] = Color.floatToByte(color.red);
          colorValues[colorIndex++] = Color.floatToByte(color.green);
          colorValues[colorIndex++] = Color.floatToByte(color.blue);
          colorValues[colorIndex++] = Color.floatToByte(color.alpha);
        }
      }
    }

    const attributes = new GeometryAttributes();
    attributes.position = new GeometryAttribute({
      componentDatatype: ComponentDatatype$1.DOUBLE,
      componentsPerAttribute: 3,
      values: positionValues,
    });

    if (defined(colors)) {
      attributes.color = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
        componentsPerAttribute: 4,
        values: colorValues,
        normalize: true,
      });
    }

    numberOfPositions = positionValues.length / 3;
    const numberOfIndices = (numberOfPositions - 1) * 2;
    const indices = IndexDatatype$1.createTypedArray(
      numberOfPositions,
      numberOfIndices
    );

    let index = 0;
    for (i = 0; i < numberOfPositions - 1; ++i) {
      indices[index++] = i;
      indices[index++] = i + 1;
    }

    return new Geometry({
      attributes: attributes,
      indices: indices,
      primitiveType: PrimitiveType$1.LINES,
      boundingSphere: BoundingSphere.fromPoints(positions),
    });
  };

  /**
   * A description of a sphere centered at the origin.
   *
   * @alias SphereGeometry
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Number} [options.radius=1.0] The radius of the sphere.
   * @param {Number} [options.stackPartitions=64] The number of times to partition the ellipsoid into stacks.
   * @param {Number} [options.slicePartitions=64] The number of times to partition the ellipsoid into radial slices.
   * @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
   *
   * @exception {DeveloperError} options.slicePartitions cannot be less than three.
   * @exception {DeveloperError} options.stackPartitions cannot be less than three.
   *
   * @see SphereGeometry#createGeometry
   *
   * @example
   * const sphere = new Cesium.SphereGeometry({
   *   radius : 100.0,
   *   vertexFormat : Cesium.VertexFormat.POSITION_ONLY
   * });
   * const geometry = Cesium.SphereGeometry.createGeometry(sphere);
   */
  function SphereGeometry(options) {
    const radius = defaultValue(options.radius, 1.0);
    const radii = new Cartesian3(radius, radius, radius);
    const ellipsoidOptions = {
      radii: radii,
      stackPartitions: options.stackPartitions,
      slicePartitions: options.slicePartitions,
      vertexFormat: options.vertexFormat,
    };

    this._ellipsoidGeometry = new EllipsoidGeometry(ellipsoidOptions);
    this._workerName = "createSphereGeometry";
  }

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  SphereGeometry.packedLength = EllipsoidGeometry.packedLength;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {SphereGeometry} 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
   */
  SphereGeometry.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    //>>includeEnd('debug');

    return EllipsoidGeometry.pack(value._ellipsoidGeometry, array, startingIndex);
  };

  const scratchEllipsoidGeometry$1 = new EllipsoidGeometry();
  const scratchOptions$3 = {
    radius: undefined,
    radii: new Cartesian3(),
    vertexFormat: new VertexFormat(),
    stackPartitions: undefined,
    slicePartitions: undefined,
  };

  /**
   * 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 {SphereGeometry} [result] The object into which to store the result.
   * @returns {SphereGeometry} The modified result parameter or a new SphereGeometry instance if one was not provided.
   */
  SphereGeometry.unpack = function (array, startingIndex, result) {
    const ellipsoidGeometry = EllipsoidGeometry.unpack(
      array,
      startingIndex,
      scratchEllipsoidGeometry$1
    );
    scratchOptions$3.vertexFormat = VertexFormat.clone(
      ellipsoidGeometry._vertexFormat,
      scratchOptions$3.vertexFormat
    );
    scratchOptions$3.stackPartitions = ellipsoidGeometry._stackPartitions;
    scratchOptions$3.slicePartitions = ellipsoidGeometry._slicePartitions;

    if (!defined(result)) {
      scratchOptions$3.radius = ellipsoidGeometry._radii.x;
      return new SphereGeometry(scratchOptions$3);
    }

    Cartesian3.clone(ellipsoidGeometry._radii, scratchOptions$3.radii);
    result._ellipsoidGeometry = new EllipsoidGeometry(scratchOptions$3);
    return result;
  };

  /**
   * Computes the geometric representation of a sphere, including its vertices, indices, and a bounding sphere.
   *
   * @param {SphereGeometry} sphereGeometry A description of the sphere.
   * @returns {Geometry|undefined} The computed vertices and indices.
   */
  SphereGeometry.createGeometry = function (sphereGeometry) {
    return EllipsoidGeometry.createGeometry(sphereGeometry._ellipsoidGeometry);
  };

  /**
   * A description of the outline of a sphere.
   *
   * @alias SphereOutlineGeometry
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Number} [options.radius=1.0] The radius of the sphere.
   * @param {Number} [options.stackPartitions=10] The count of stacks for the sphere (1 greater than the number of parallel lines).
   * @param {Number} [options.slicePartitions=8] The count of slices for the sphere (Equal to the number of radial lines).
   * @param {Number} [options.subdivisions=200] The number of points per line, determining the granularity of the curvature .
   *
   * @exception {DeveloperError} options.stackPartitions must be greater than or equal to one.
   * @exception {DeveloperError} options.slicePartitions must be greater than or equal to zero.
   * @exception {DeveloperError} options.subdivisions must be greater than or equal to zero.
   *
   * @example
   * const sphere = new Cesium.SphereOutlineGeometry({
   *   radius : 100.0,
   *   stackPartitions : 6,
   *   slicePartitions: 5
   * });
   * const geometry = Cesium.SphereOutlineGeometry.createGeometry(sphere);
   */
  function SphereOutlineGeometry(options) {
    const radius = defaultValue(options.radius, 1.0);
    const radii = new Cartesian3(radius, radius, radius);
    const ellipsoidOptions = {
      radii: radii,
      stackPartitions: options.stackPartitions,
      slicePartitions: options.slicePartitions,
      subdivisions: options.subdivisions,
    };

    this._ellipsoidGeometry = new EllipsoidOutlineGeometry(ellipsoidOptions);
    this._workerName = "createSphereOutlineGeometry";
  }

  /**
   * The number of elements used to pack the object into an array.
   * @type {Number}
   */
  SphereOutlineGeometry.packedLength = EllipsoidOutlineGeometry.packedLength;

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {SphereOutlineGeometry} 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
   */
  SphereOutlineGeometry.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    //>>includeEnd('debug');

    return EllipsoidOutlineGeometry.pack(
      value._ellipsoidGeometry,
      array,
      startingIndex
    );
  };

  const scratchEllipsoidGeometry = new EllipsoidOutlineGeometry();
  const scratchOptions$2 = {
    radius: undefined,
    radii: new Cartesian3(),
    stackPartitions: undefined,
    slicePartitions: undefined,
    subdivisions: undefined,
  };

  /**
   * 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 {SphereOutlineGeometry} [result] The object into which to store the result.
   * @returns {SphereOutlineGeometry} The modified result parameter or a new SphereOutlineGeometry instance if one was not provided.
   */
  SphereOutlineGeometry.unpack = function (array, startingIndex, result) {
    const ellipsoidGeometry = EllipsoidOutlineGeometry.unpack(
      array,
      startingIndex,
      scratchEllipsoidGeometry
    );
    scratchOptions$2.stackPartitions = ellipsoidGeometry._stackPartitions;
    scratchOptions$2.slicePartitions = ellipsoidGeometry._slicePartitions;
    scratchOptions$2.subdivisions = ellipsoidGeometry._subdivisions;

    if (!defined(result)) {
      scratchOptions$2.radius = ellipsoidGeometry._radii.x;
      return new SphereOutlineGeometry(scratchOptions$2);
    }

    Cartesian3.clone(ellipsoidGeometry._radii, scratchOptions$2.radii);
    result._ellipsoidGeometry = new EllipsoidOutlineGeometry(scratchOptions$2);
    return result;
  };

  /**
   * Computes the geometric representation of an outline of a sphere, including its vertices, indices, and a bounding sphere.
   *
   * @param {SphereOutlineGeometry} sphereGeometry A description of the sphere outline.
   * @returns {Geometry|undefined} The computed vertices and indices.
   */
  SphereOutlineGeometry.createGeometry = function (sphereGeometry) {
    return EllipsoidOutlineGeometry.createGeometry(
      sphereGeometry._ellipsoidGeometry
    );
  };

  /**
   * A set of curvilinear 3-dimensional coordinates.
   *
   * @alias Spherical
   * @constructor
   *
   * @param {Number} [clock=0.0] The angular coordinate lying in the xy-plane measured from the positive x-axis and toward the positive y-axis.
   * @param {Number} [cone=0.0] The angular coordinate measured from the positive z-axis and toward the negative z-axis.
   * @param {Number} [magnitude=1.0] The linear coordinate measured from the origin.
   */
  function Spherical(clock, cone, magnitude) {
    /**
     * The clock component.
     * @type {Number}
     * @default 0.0
     */
    this.clock = defaultValue(clock, 0.0);
    /**
     * The cone component.
     * @type {Number}
     * @default 0.0
     */
    this.cone = defaultValue(cone, 0.0);
    /**
     * The magnitude component.
     * @type {Number}
     * @default 1.0
     */
    this.magnitude = defaultValue(magnitude, 1.0);
  }

  /**
   * Converts the provided Cartesian3 into Spherical coordinates.
   *
   * @param {Cartesian3} cartesian3 The Cartesian3 to be converted to Spherical.
   * @param {Spherical} [result] The object in which the result will be stored, if undefined a new instance will be created.
   * @returns {Spherical} The modified result parameter, or a new instance if one was not provided.
   */
  Spherical.fromCartesian3 = function (cartesian3, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("cartesian3", cartesian3);
    //>>includeEnd('debug');

    const x = cartesian3.x;
    const y = cartesian3.y;
    const z = cartesian3.z;
    const radialSquared = x * x + y * y;

    if (!defined(result)) {
      result = new Spherical();
    }

    result.clock = Math.atan2(y, x);
    result.cone = Math.atan2(Math.sqrt(radialSquared), z);
    result.magnitude = Math.sqrt(radialSquared + z * z);
    return result;
  };

  /**
   * Creates a duplicate of a Spherical.
   *
   * @param {Spherical} spherical The spherical to clone.
   * @param {Spherical} [result] The object to store the result into, if undefined a new instance will be created.
   * @returns {Spherical} The modified result parameter or a new instance if result was undefined. (Returns undefined if spherical is undefined)
   */
  Spherical.clone = function (spherical, result) {
    if (!defined(spherical)) {
      return undefined;
    }

    if (!defined(result)) {
      return new Spherical(spherical.clock, spherical.cone, spherical.magnitude);
    }

    result.clock = spherical.clock;
    result.cone = spherical.cone;
    result.magnitude = spherical.magnitude;
    return result;
  };

  /**
   * Computes the normalized version of the provided spherical.
   *
   * @param {Spherical} spherical The spherical to be normalized.
   * @param {Spherical} [result] The object to store the result into, if undefined a new instance will be created.
   * @returns {Spherical} The modified result parameter or a new instance if result was undefined.
   */
  Spherical.normalize = function (spherical, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("spherical", spherical);
    //>>includeEnd('debug');

    if (!defined(result)) {
      return new Spherical(spherical.clock, spherical.cone, 1.0);
    }

    result.clock = spherical.clock;
    result.cone = spherical.cone;
    result.magnitude = 1.0;
    return result;
  };

  /**
   * Returns true if the first spherical is equal to the second spherical, false otherwise.
   *
   * @param {Spherical} left The first Spherical to be compared.
   * @param {Spherical} right The second Spherical to be compared.
   * @returns {Boolean} true if the first spherical is equal to the second spherical, false otherwise.
   */
  Spherical.equals = function (left, right) {
    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        left.clock === right.clock &&
        left.cone === right.cone &&
        left.magnitude === right.magnitude)
    );
  };

  /**
   * Returns true if the first spherical is within the provided epsilon of the second spherical, false otherwise.
   *
   * @param {Spherical} left The first Spherical to be compared.
   * @param {Spherical} right The second Spherical to be compared.
   * @param {Number} [epsilon=0.0] The epsilon to compare against.
   * @returns {Boolean} true if the first spherical is within the provided epsilon of the second spherical, false otherwise.
   */
  Spherical.equalsEpsilon = function (left, right, epsilon) {
    epsilon = defaultValue(epsilon, 0.0);
    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        Math.abs(left.clock - right.clock) <= epsilon &&
        Math.abs(left.cone - right.cone) <= epsilon &&
        Math.abs(left.magnitude - right.magnitude) <= epsilon)
    );
  };

  /**
   * Returns true if this spherical is equal to the provided spherical, false otherwise.
   *
   * @param {Spherical} other The Spherical to be compared.
   * @returns {Boolean} true if this spherical is equal to the provided spherical, false otherwise.
   */
  Spherical.prototype.equals = function (other) {
    return Spherical.equals(this, other);
  };

  /**
   * Creates a duplicate of this Spherical.
   *
   * @param {Spherical} [result] The object to store the result into, if undefined a new instance will be created.
   * @returns {Spherical} The modified result parameter or a new instance if result was undefined.
   */
  Spherical.prototype.clone = function (result) {
    return Spherical.clone(this, result);
  };

  /**
   * Returns true if this spherical is within the provided epsilon of the provided spherical, false otherwise.
   *
   * @param {Spherical} other The Spherical to be compared.
   * @param {Number} epsilon The epsilon to compare against.
   * @returns {Boolean} true if this spherical is within the provided epsilon of the provided spherical, false otherwise.
   */
  Spherical.prototype.equalsEpsilon = function (other, epsilon) {
    return Spherical.equalsEpsilon(this, other, epsilon);
  };

  /**
   * Returns a string representing this instance in the format (clock, cone, magnitude).
   *
   * @returns {String} A string representing this instance.
   */
  Spherical.prototype.toString = function () {
    return `(${this.clock}, ${this.cone}, ${this.magnitude})`;
  };

  /**
   * A spline that is composed of piecewise constants representing a step function.
   *
   * @alias SteppedSpline
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Number[]} options.times An array of strictly increasing, unit-less, floating-point times at each point. The values are in no way connected to the clock time. They are the parameterization for the curve.
   * @param {Number[]|Cartesian3[]|Quaternion[]} options.points The array of control points.
   *
   * @exception {DeveloperError} points.length must be greater than or equal to 2.
   * @exception {DeveloperError} times.length must be equal to points.length.
   *
   * @example
   * const times = [ 0.0, 1.5, 3.0, 4.5, 6.0 ];
   * const spline = new Cesium.SteppedSpline({
   *     times : times,
   *     points : [
   *         new Cesium.Cartesian3(1235398.0, -4810983.0, 4146266.0),
   *         new Cesium.Cartesian3(1372574.0, -5345182.0, 4606657.0),
   *         new Cesium.Cartesian3(-757983.0, -5542796.0, 4514323.0),
   *         new Cesium.Cartesian3(-2821260.0, -5248423.0, 4021290.0),
   *         new Cesium.Cartesian3(-2539788.0, -4724797.0, 3620093.0)
   *     ]
   * });
   *
   * const p0 = spline.evaluate(times[0]);
   *
   * @see ConstantSpline
   * @see CatmullRomSpline
   * @see HermiteSpline
   * @see LinearSpline
   * @see QuaternionSpline
   * @see MorphWeightSpline
   */
  function SteppedSpline$1(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const points = options.points;
    const times = options.times;

    //>>includeStart('debug', pragmas.debug);
    if (!defined(points) || !defined(times)) {
      throw new DeveloperError("points and times are required.");
    }
    if (points.length < 2) {
      throw new DeveloperError(
        "points.length must be greater than or equal to 2."
      );
    }
    if (times.length !== points.length) {
      throw new DeveloperError("times.length must be equal to points.length.");
    }
    //>>includeEnd('debug');

    this._times = times;
    this._points = points;
    this._pointType = Spline.getPointType(points[0]);

    this._lastTimeIndex = 0;
  }

  Object.defineProperties(SteppedSpline$1.prototype, {
    /**
     * An array of times for the control points.
     *
     * @memberof SteppedSpline.prototype
     *
     * @type {Number[]}
     * @readonly
     */
    times: {
      get: function () {
        return this._times;
      },
    },

    /**
     * An array of control points.
     *
     * @memberof SteppedSpline.prototype
     *
     * @type {Number[]|Cartesian3[]|Quaternion[]}
     * @readonly
     */
    points: {
      get: function () {
        return this._points;
      },
    },
  });

  /**
   * Finds an index <code>i</code> in <code>times</code> such that the parameter
   * <code>time</code> is in the interval <code>[times[i], times[i + 1]]</code>.
   * @function
   *
   * @param {Number} time The time.
   * @param {Number} startIndex The index from which to start the search.
   * @returns {Number} The index for the element at the start of the interval.
   *
   * @exception {DeveloperError} time must be in the range <code>[t<sub>0</sub>, t<sub>n</sub>]</code>, where <code>t<sub>0</sub></code>
   *                             is the first element in the array <code>times</code> and <code>t<sub>n</sub></code> is the last element
   *                             in the array <code>times</code>.
   */
  SteppedSpline$1.prototype.findTimeInterval = Spline.prototype.findTimeInterval;

  /**
   * Wraps the given time to the period covered by the spline.
   * @function
   *
   * @param {Number} time The time.
   * @return {Number} The time, wrapped around to the updated animation.
   */
  SteppedSpline$1.prototype.wrapTime = Spline.prototype.wrapTime;

  /**
   * Clamps the given time to the period covered by the spline.
   * @function
   *
   * @param {Number} time The time.
   * @return {Number} The time, clamped to the animation period.
   */
  SteppedSpline$1.prototype.clampTime = Spline.prototype.clampTime;

  /**
   * Evaluates the curve at a given time.
   *
   * @param {Number} time The time at which to evaluate the curve.
   * @param {Cartesian3|Quaternion} [result] The object onto which to store the result.
   * @returns {Number|Cartesian3|Quaternion} The modified result parameter or a new instance of the point on the curve at the given time.
   *
   * @exception {DeveloperError} time must be in the range <code>[t<sub>0</sub>, t<sub>n</sub>]</code>, where <code>t<sub>0</sub></code>
   *                             is the first element in the array <code>times</code> and <code>t<sub>n</sub></code> is the last element
   *                             in the array <code>times</code>.
   */
  SteppedSpline$1.prototype.evaluate = function (time, result) {
    const points = this.points;

    this._lastTimeIndex = this.findTimeInterval(time, this._lastTimeIndex);
    const i = this._lastTimeIndex;

    const PointType = this._pointType;
    if (PointType === Number) {
      return points[i];
    }

    if (!defined(result)) {
      result = new PointType();
    }

    return PointType.clone(points[i], result);
  };

  /**
   * @private
   */
  const TileEdge = {
    WEST: 0,
    NORTH: 1,
    EAST: 2,
    SOUTH: 3,
    NORTHWEST: 4,
    NORTHEAST: 5,
    SOUTHWEST: 6,
    SOUTHEAST: 7,
  };

  /**
   * A tiling scheme for geometry or imagery on the surface of an ellipsoid.  At level-of-detail zero,
   * the coarsest, least-detailed level, the number of tiles is configurable.
   * At level of detail one, each of the level zero tiles has four children, two in each direction.
   * At level of detail two, each of the level one tiles has four children, two in each direction.
   * This continues for as many levels as are present in the geometry or imagery source.
   *
   * @alias TilingScheme
   * @constructor
   *
   * @see WebMercatorTilingScheme
   * @see GeographicTilingScheme
   */
  function TilingScheme(options) {
    //>>includeStart('debug', pragmas.debug);
    throw new DeveloperError(
      "This type should not be instantiated directly.  Instead, use WebMercatorTilingScheme or GeographicTilingScheme."
    );
    //>>includeEnd('debug');
  }

  Object.defineProperties(TilingScheme.prototype, {
    /**
     * Gets the ellipsoid that is tiled by the tiling scheme.
     * @memberof TilingScheme.prototype
     * @type {Ellipsoid}
     */
    ellipsoid: {
      get: DeveloperError.throwInstantiationError,
    },

    /**
     * Gets the rectangle, in radians, covered by this tiling scheme.
     * @memberof TilingScheme.prototype
     * @type {Rectangle}
     */
    rectangle: {
      get: DeveloperError.throwInstantiationError,
    },

    /**
     * Gets the map projection used by the tiling scheme.
     * @memberof TilingScheme.prototype
     * @type {MapProjection}
     */
    projection: {
      get: DeveloperError.throwInstantiationError,
    },
  });

  /**
   * Gets the total number of tiles in the X direction at a specified level-of-detail.
   * @function
   *
   * @param {Number} level The level-of-detail.
   * @returns {Number} The number of tiles in the X direction at the given level.
   */
  TilingScheme.prototype.getNumberOfXTilesAtLevel =
    DeveloperError.throwInstantiationError;

  /**
   * Gets the total number of tiles in the Y direction at a specified level-of-detail.
   * @function
   *
   * @param {Number} level The level-of-detail.
   * @returns {Number} The number of tiles in the Y direction at the given level.
   */
  TilingScheme.prototype.getNumberOfYTilesAtLevel =
    DeveloperError.throwInstantiationError;

  /**
   * Transforms a rectangle specified in geodetic radians to the native coordinate system
   * of this tiling scheme.
   * @function
   *
   * @param {Rectangle} rectangle The rectangle to transform.
   * @param {Rectangle} [result] The instance to which to copy the result, or undefined if a new instance
   *        should be created.
   * @returns {Rectangle} The specified 'result', or a new object containing the native rectangle if 'result'
   *          is undefined.
   */
  TilingScheme.prototype.rectangleToNativeRectangle =
    DeveloperError.throwInstantiationError;

  /**
   * Converts tile x, y coordinates and level to a rectangle expressed in the native coordinates
   * of the tiling scheme.
   * @function
   *
   * @param {Number} x The integer x coordinate of the tile.
   * @param {Number} y The integer y coordinate of the tile.
   * @param {Number} level The tile level-of-detail.  Zero is the least detailed.
   * @param {Object} [result] The instance to which to copy the result, or undefined if a new instance
   *        should be created.
   * @returns {Rectangle} The specified 'result', or a new object containing the rectangle
   *          if 'result' is undefined.
   */
  TilingScheme.prototype.tileXYToNativeRectangle =
    DeveloperError.throwInstantiationError;

  /**
   * Converts tile x, y coordinates and level to a cartographic rectangle in radians.
   * @function
   *
   * @param {Number} x The integer x coordinate of the tile.
   * @param {Number} y The integer y coordinate of the tile.
   * @param {Number} level The tile level-of-detail.  Zero is the least detailed.
   * @param {Object} [result] The instance to which to copy the result, or undefined if a new instance
   *        should be created.
   * @returns {Rectangle} The specified 'result', or a new object containing the rectangle
   *          if 'result' is undefined.
   */
  TilingScheme.prototype.tileXYToRectangle =
    DeveloperError.throwInstantiationError;

  /**
   * Calculates the tile x, y coordinates of the tile containing
   * a given cartographic position.
   * @function
   *
   * @param {Cartographic} position The position.
   * @param {Number} level The tile level-of-detail.  Zero is the least detailed.
   * @param {Cartesian2} [result] The instance to which to copy the result, or undefined if a new instance
   *        should be created.
   * @returns {Cartesian2} The specified 'result', or a new object containing the tile x, y coordinates
   *          if 'result' is undefined.
   */
  TilingScheme.prototype.positionToTileXY =
    DeveloperError.throwInstantiationError;

  function compareIntervalStartTimes(left, right) {
    return JulianDate.compare(left.start, right.start);
  }

  /**
   * A non-overlapping collection of {@link TimeInterval} instances sorted by start time.
   * @alias TimeIntervalCollection
   * @constructor
   *
   * @param {TimeInterval[]} [intervals] An array of intervals to add to the collection.
   */
  function TimeIntervalCollection(intervals) {
    this._intervals = [];
    this._changedEvent = new Event();

    if (defined(intervals)) {
      const length = intervals.length;
      for (let i = 0; i < length; i++) {
        this.addInterval(intervals[i]);
      }
    }
  }

  Object.defineProperties(TimeIntervalCollection.prototype, {
    /**
     * Gets an event that is raised whenever the collection of intervals change.
     * @memberof TimeIntervalCollection.prototype
     * @type {Event}
     * @readonly
     */
    changedEvent: {
      get: function () {
        return this._changedEvent;
      },
    },

    /**
     * Gets the start time of the collection.
     * @memberof TimeIntervalCollection.prototype
     * @type {JulianDate}
     * @readonly
     */
    start: {
      get: function () {
        const intervals = this._intervals;
        return intervals.length === 0 ? undefined : intervals[0].start;
      },
    },

    /**
     * Gets whether or not the start time is included in the collection.
     * @memberof TimeIntervalCollection.prototype
     * @type {Boolean}
     * @readonly
     */
    isStartIncluded: {
      get: function () {
        const intervals = this._intervals;
        return intervals.length === 0 ? false : intervals[0].isStartIncluded;
      },
    },

    /**
     * Gets the stop time of the collection.
     * @memberof TimeIntervalCollection.prototype
     * @type {JulianDate}
     * @readonly
     */
    stop: {
      get: function () {
        const intervals = this._intervals;
        const length = intervals.length;
        return length === 0 ? undefined : intervals[length - 1].stop;
      },
    },

    /**
     * Gets whether or not the stop time is included in the collection.
     * @memberof TimeIntervalCollection.prototype
     * @type {Boolean}
     * @readonly
     */
    isStopIncluded: {
      get: function () {
        const intervals = this._intervals;
        const length = intervals.length;
        return length === 0 ? false : intervals[length - 1].isStopIncluded;
      },
    },

    /**
     * Gets the number of intervals in the collection.
     * @memberof TimeIntervalCollection.prototype
     * @type {Number}
     * @readonly
     */
    length: {
      get: function () {
        return this._intervals.length;
      },
    },

    /**
     * Gets whether or not the collection is empty.
     * @memberof TimeIntervalCollection.prototype
     * @type {Boolean}
     * @readonly
     */
    isEmpty: {
      get: function () {
        return this._intervals.length === 0;
      },
    },
  });

  /**
   * Compares this instance against the provided instance componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {TimeIntervalCollection} [right] The right hand side collection.
   * @param {TimeInterval.DataComparer} [dataComparer] A function which compares the data of the two intervals.  If omitted, reference equality is used.
   * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
   */
  TimeIntervalCollection.prototype.equals = function (right, dataComparer) {
    if (this === right) {
      return true;
    }
    if (!(right instanceof TimeIntervalCollection)) {
      return false;
    }
    const intervals = this._intervals;
    const rightIntervals = right._intervals;
    const length = intervals.length;
    if (length !== rightIntervals.length) {
      return false;
    }
    for (let i = 0; i < length; i++) {
      if (!TimeInterval.equals(intervals[i], rightIntervals[i], dataComparer)) {
        return false;
      }
    }
    return true;
  };

  /**
   * Gets the interval at the specified index.
   *
   * @param {Number} index The index of the interval to retrieve.
   * @returns {TimeInterval|undefined} The interval at the specified index, or <code>undefined</code> if no interval exists as that index.
   */
  TimeIntervalCollection.prototype.get = function (index) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(index)) {
      throw new DeveloperError("index is required.");
    }
    //>>includeEnd('debug');

    return this._intervals[index];
  };

  /**
   * Removes all intervals from the collection.
   */
  TimeIntervalCollection.prototype.removeAll = function () {
    if (this._intervals.length > 0) {
      this._intervals.length = 0;
      this._changedEvent.raiseEvent(this);
    }
  };

  /**
   * Finds and returns the interval that contains the specified date.
   *
   * @param {JulianDate} date The date to search for.
   * @returns {TimeInterval|undefined} The interval containing the specified date, <code>undefined</code> if no such interval exists.
   */
  TimeIntervalCollection.prototype.findIntervalContainingDate = function (date) {
    const index = this.indexOf(date);
    return index >= 0 ? this._intervals[index] : undefined;
  };

  /**
   * Finds and returns the data for the interval that contains the specified date.
   *
   * @param {JulianDate} date The date to search for.
   * @returns {Object} The data for the interval containing the specified date, or <code>undefined</code> if no such interval exists.
   */
  TimeIntervalCollection.prototype.findDataForIntervalContainingDate = function (
    date
  ) {
    const index = this.indexOf(date);
    return index >= 0 ? this._intervals[index].data : undefined;
  };

  /**
   * Checks if the specified date is inside this collection.
   *
   * @param {JulianDate} julianDate The date to check.
   * @returns {Boolean} <code>true</code> if the collection contains the specified date, <code>false</code> otherwise.
   */
  TimeIntervalCollection.prototype.contains = function (julianDate) {
    return this.indexOf(julianDate) >= 0;
  };

  const indexOfScratch = new TimeInterval();

  /**
   * Finds and returns the index of the interval in the collection that contains the specified date.
   *
   * @param {JulianDate} date The date to search for.
   * @returns {Number} The index of the interval that contains the specified date, if no such interval exists,
   * it returns a negative number which is the bitwise complement of the index of the next interval that
   * starts after the date, or if no interval starts after the specified date, the bitwise complement of
   * the length of the collection.
   */
  TimeIntervalCollection.prototype.indexOf = function (date) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(date)) {
      throw new DeveloperError("date is required");
    }
    //>>includeEnd('debug');

    const intervals = this._intervals;
    indexOfScratch.start = date;
    indexOfScratch.stop = date;
    let index = binarySearch(
      intervals,
      indexOfScratch,
      compareIntervalStartTimes
    );
    if (index >= 0) {
      if (intervals[index].isStartIncluded) {
        return index;
      }

      if (
        index > 0 &&
        intervals[index - 1].stop.equals(date) &&
        intervals[index - 1].isStopIncluded
      ) {
        return index - 1;
      }
      return ~index;
    }

    index = ~index;
    if (
      index > 0 &&
      index - 1 < intervals.length &&
      TimeInterval.contains(intervals[index - 1], date)
    ) {
      return index - 1;
    }
    return ~index;
  };

  /**
   * Returns the first interval in the collection that matches the specified parameters.
   * All parameters are optional and <code>undefined</code> parameters are treated as a don't care condition.
   *
   * @param {Object} [options] Object with the following properties:
   * @param {JulianDate} [options.start] The start time of the interval.
   * @param {JulianDate} [options.stop] The stop time of the interval.
   * @param {Boolean} [options.isStartIncluded] <code>true</code> if <code>options.start</code> is included in the interval, <code>false</code> otherwise.
   * @param {Boolean} [options.isStopIncluded] <code>true</code> if <code>options.stop</code> is included in the interval, <code>false</code> otherwise.
   * @returns {TimeInterval|undefined} The first interval in the collection that matches the specified parameters.
   */
  TimeIntervalCollection.prototype.findInterval = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const start = options.start;
    const stop = options.stop;
    const isStartIncluded = options.isStartIncluded;
    const isStopIncluded = options.isStopIncluded;

    const intervals = this._intervals;
    for (let i = 0, len = intervals.length; i < len; i++) {
      const interval = intervals[i];
      if (
        (!defined(start) || interval.start.equals(start)) &&
        (!defined(stop) || interval.stop.equals(stop)) &&
        (!defined(isStartIncluded) ||
          interval.isStartIncluded === isStartIncluded) &&
        (!defined(isStopIncluded) || interval.isStopIncluded === isStopIncluded)
      ) {
        return intervals[i];
      }
    }
    return undefined;
  };

  /**
   * Adds an interval to the collection, merging intervals that contain the same data and
   * splitting intervals of different data as needed in order to maintain a non-overlapping collection.
   * The data in the new interval takes precedence over any existing intervals in the collection.
   *
   * @param {TimeInterval} interval The interval to add.
   * @param {TimeInterval.DataComparer} [dataComparer] A function which compares the data of the two intervals.  If omitted, reference equality is used.
   */
  TimeIntervalCollection.prototype.addInterval = function (
    interval,
    dataComparer
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(interval)) {
      throw new DeveloperError("interval is required");
    }
    //>>includeEnd('debug');

    if (interval.isEmpty) {
      return;
    }

    const intervals = this._intervals;

    // Handle the common case quickly: we're adding a new interval which is after all existing intervals.
    if (
      intervals.length === 0 ||
      JulianDate.greaterThan(interval.start, intervals[intervals.length - 1].stop)
    ) {
      intervals.push(interval);
      this._changedEvent.raiseEvent(this);
      return;
    }

    // Keep the list sorted by the start date
    let index = binarySearch(intervals, interval, compareIntervalStartTimes);
    if (index < 0) {
      index = ~index;
    } else {
      // interval's start date exactly equals the start date of at least one interval in the collection.
      // It could actually equal the start date of two intervals if one of them does not actually
      // include the date.  In that case, the binary search could have found either.  We need to
      // look at the surrounding intervals and their IsStartIncluded properties in order to make sure
      // we're working with the correct interval.

      // eslint-disable-next-line no-lonely-if
      if (
        index > 0 &&
        interval.isStartIncluded &&
        intervals[index - 1].isStartIncluded &&
        intervals[index - 1].start.equals(interval.start)
      ) {
        --index;
      } else if (
        index < intervals.length &&
        !interval.isStartIncluded &&
        intervals[index].isStartIncluded &&
        intervals[index].start.equals(interval.start)
      ) {
        ++index;
      }
    }

    let comparison;
    if (index > 0) {
      // Not the first thing in the list, so see if the interval before this one
      // overlaps this one.

      comparison = JulianDate.compare(intervals[index - 1].stop, interval.start);
      if (
        comparison > 0 ||
        (comparison === 0 &&
          (intervals[index - 1].isStopIncluded || interval.isStartIncluded))
      ) {
        // There is an overlap
        if (
          defined(dataComparer)
            ? dataComparer(intervals[index - 1].data, interval.data)
            : intervals[index - 1].data === interval.data
        ) {
          // Overlapping intervals have the same data, so combine them
          if (JulianDate.greaterThan(interval.stop, intervals[index - 1].stop)) {
            interval = new TimeInterval({
              start: intervals[index - 1].start,
              stop: interval.stop,
              isStartIncluded: intervals[index - 1].isStartIncluded,
              isStopIncluded: interval.isStopIncluded,
              data: interval.data,
            });
          } else {
            interval = new TimeInterval({
              start: intervals[index - 1].start,
              stop: intervals[index - 1].stop,
              isStartIncluded: intervals[index - 1].isStartIncluded,
              isStopIncluded:
                intervals[index - 1].isStopIncluded ||
                (interval.stop.equals(intervals[index - 1].stop) &&
                  interval.isStopIncluded),
              data: interval.data,
            });
          }
          intervals.splice(index - 1, 1);
          --index;
        } else {
          // Overlapping intervals have different data.  The new interval
          // being added 'wins' so truncate the previous interval.
          // If the existing interval extends past the end of the new one,
          // split the existing interval into two intervals.
          comparison = JulianDate.compare(
            intervals[index - 1].stop,
            interval.stop
          );
          if (
            comparison > 0 ||
            (comparison === 0 &&
              intervals[index - 1].isStopIncluded &&
              !interval.isStopIncluded)
          ) {
            intervals.splice(
              index,
              0,
              new TimeInterval({
                start: interval.stop,
                stop: intervals[index - 1].stop,
                isStartIncluded: !interval.isStopIncluded,
                isStopIncluded: intervals[index - 1].isStopIncluded,
                data: intervals[index - 1].data,
              })
            );
          }
          intervals[index - 1] = new TimeInterval({
            start: intervals[index - 1].start,
            stop: interval.start,
            isStartIncluded: intervals[index - 1].isStartIncluded,
            isStopIncluded: !interval.isStartIncluded,
            data: intervals[index - 1].data,
          });
        }
      }
    }

    while (index < intervals.length) {
      // Not the last thing in the list, so see if the intervals after this one overlap this one.
      comparison = JulianDate.compare(interval.stop, intervals[index].start);
      if (
        comparison > 0 ||
        (comparison === 0 &&
          (interval.isStopIncluded || intervals[index].isStartIncluded))
      ) {
        // There is an overlap
        if (
          defined(dataComparer)
            ? dataComparer(intervals[index].data, interval.data)
            : intervals[index].data === interval.data
        ) {
          // Overlapping intervals have the same data, so combine them
          interval = new TimeInterval({
            start: interval.start,
            stop: JulianDate.greaterThan(intervals[index].stop, interval.stop)
              ? intervals[index].stop
              : interval.stop,
            isStartIncluded: interval.isStartIncluded,
            isStopIncluded: JulianDate.greaterThan(
              intervals[index].stop,
              interval.stop
            )
              ? intervals[index].isStopIncluded
              : interval.isStopIncluded,
            data: interval.data,
          });
          intervals.splice(index, 1);
        } else {
          // Overlapping intervals have different data.  The new interval
          // being added 'wins' so truncate the next interval.
          intervals[index] = new TimeInterval({
            start: interval.stop,
            stop: intervals[index].stop,
            isStartIncluded: !interval.isStopIncluded,
            isStopIncluded: intervals[index].isStopIncluded,
            data: intervals[index].data,
          });

          if (intervals[index].isEmpty) {
            intervals.splice(index, 1);
          } else {
            // Found a partial span, so it is not possible for the next
            // interval to be spanned at all.  Stop looking.
            break;
          }
        }
      } else {
        // Found the last one we're spanning, so stop looking.
        break;
      }
    }

    // Add the new interval
    intervals.splice(index, 0, interval);
    this._changedEvent.raiseEvent(this);
  };

  /**
   * Removes the specified interval from this interval collection, creating a hole over the specified interval.
   * The data property of the input interval is ignored.
   *
   * @param {TimeInterval} interval The interval to remove.
   * @returns {Boolean} <code>true</code> if the interval was removed, <code>false</code> if no part of the interval was in the collection.
   */
  TimeIntervalCollection.prototype.removeInterval = function (interval) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(interval)) {
      throw new DeveloperError("interval is required");
    }
    //>>includeEnd('debug');

    if (interval.isEmpty) {
      return false;
    }

    const intervals = this._intervals;

    let index = binarySearch(intervals, interval, compareIntervalStartTimes);
    if (index < 0) {
      index = ~index;
    }

    let result = false;

    // Check for truncation of the end of the previous interval.
    if (
      index > 0 &&
      (JulianDate.greaterThan(intervals[index - 1].stop, interval.start) ||
        (intervals[index - 1].stop.equals(interval.start) &&
          intervals[index - 1].isStopIncluded &&
          interval.isStartIncluded))
    ) {
      result = true;

      if (
        JulianDate.greaterThan(intervals[index - 1].stop, interval.stop) ||
        (intervals[index - 1].isStopIncluded &&
          !interval.isStopIncluded &&
          intervals[index - 1].stop.equals(interval.stop))
      ) {
        // Break the existing interval into two pieces
        intervals.splice(
          index,
          0,
          new TimeInterval({
            start: interval.stop,
            stop: intervals[index - 1].stop,
            isStartIncluded: !interval.isStopIncluded,
            isStopIncluded: intervals[index - 1].isStopIncluded,
            data: intervals[index - 1].data,
          })
        );
      }
      intervals[index - 1] = new TimeInterval({
        start: intervals[index - 1].start,
        stop: interval.start,
        isStartIncluded: intervals[index - 1].isStartIncluded,
        isStopIncluded: !interval.isStartIncluded,
        data: intervals[index - 1].data,
      });
    }

    // Check if the Start of the current interval should remain because interval.start is the same but
    // it is not included.
    if (
      index < intervals.length &&
      !interval.isStartIncluded &&
      intervals[index].isStartIncluded &&
      interval.start.equals(intervals[index].start)
    ) {
      result = true;

      intervals.splice(
        index,
        0,
        new TimeInterval({
          start: intervals[index].start,
          stop: intervals[index].start,
          isStartIncluded: true,
          isStopIncluded: true,
          data: intervals[index].data,
        })
      );
      ++index;
    }

    // Remove any intervals that are completely overlapped by the input interval.
    while (
      index < intervals.length &&
      JulianDate.greaterThan(interval.stop, intervals[index].stop)
    ) {
      result = true;
      intervals.splice(index, 1);
    }

    // Check for the case where the input interval ends on the same date
    // as an existing interval.
    if (index < intervals.length && interval.stop.equals(intervals[index].stop)) {
      result = true;

      if (!interval.isStopIncluded && intervals[index].isStopIncluded) {
        // Last point of interval should remain because the stop date is included in
        // the existing interval but is not included in the input interval.
        if (
          index + 1 < intervals.length &&
          intervals[index + 1].start.equals(interval.stop) &&
          intervals[index].data === intervals[index + 1].data
        ) {
          // Combine single point with the next interval
          intervals.splice(index, 1);
          intervals[index] = new TimeInterval({
            start: intervals[index].start,
            stop: intervals[index].stop,
            isStartIncluded: true,
            isStopIncluded: intervals[index].isStopIncluded,
            data: intervals[index].data,
          });
        } else {
          intervals[index] = new TimeInterval({
            start: interval.stop,
            stop: interval.stop,
            isStartIncluded: true,
            isStopIncluded: true,
            data: intervals[index].data,
          });
        }
      } else {
        // Interval is completely overlapped
        intervals.splice(index, 1);
      }
    }

    // Truncate any partially-overlapped intervals.
    if (
      index < intervals.length &&
      (JulianDate.greaterThan(interval.stop, intervals[index].start) ||
        (interval.stop.equals(intervals[index].start) &&
          interval.isStopIncluded &&
          intervals[index].isStartIncluded))
    ) {
      result = true;
      intervals[index] = new TimeInterval({
        start: interval.stop,
        stop: intervals[index].stop,
        isStartIncluded: !interval.isStopIncluded,
        isStopIncluded: intervals[index].isStopIncluded,
        data: intervals[index].data,
      });
    }

    if (result) {
      this._changedEvent.raiseEvent(this);
    }

    return result;
  };

  /**
   * Creates a new instance that is the intersection of this collection and the provided collection.
   *
   * @param {TimeIntervalCollection} other The collection to intersect with.
   * @param {TimeInterval.DataComparer} [dataComparer] A function which compares the data of the two intervals.  If omitted, reference equality is used.
   * @param {TimeInterval.MergeCallback} [mergeCallback] A function which merges the data of the two intervals. If omitted, the data from the left interval will be used.
   * @returns {TimeIntervalCollection} A new TimeIntervalCollection which is the intersection of this collection and the provided collection.
   */
  TimeIntervalCollection.prototype.intersect = function (
    other,
    dataComparer,
    mergeCallback
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(other)) {
      throw new DeveloperError("other is required.");
    }
    //>>includeEnd('debug');

    const result = new TimeIntervalCollection();
    let left = 0;
    let right = 0;
    const intervals = this._intervals;
    const otherIntervals = other._intervals;

    while (left < intervals.length && right < otherIntervals.length) {
      const leftInterval = intervals[left];
      const rightInterval = otherIntervals[right];
      if (JulianDate.lessThan(leftInterval.stop, rightInterval.start)) {
        ++left;
      } else if (JulianDate.lessThan(rightInterval.stop, leftInterval.start)) {
        ++right;
      } else {
        // The following will return an intersection whose data is 'merged' if the callback is defined
        if (
          defined(mergeCallback) ||
          (defined(dataComparer) &&
            dataComparer(leftInterval.data, rightInterval.data)) ||
          (!defined(dataComparer) && rightInterval.data === leftInterval.data)
        ) {
          const intersection = TimeInterval.intersect(
            leftInterval,
            rightInterval,
            new TimeInterval(),
            mergeCallback
          );
          if (!intersection.isEmpty) {
            // Since we start with an empty collection for 'result', and there are no overlapping intervals in 'this' (as a rule),
            // the 'intersection' will never overlap with a previous interval in 'result'.  So, no need to do any additional 'merging'.
            result.addInterval(intersection, dataComparer);
          }
        }

        if (
          JulianDate.lessThan(leftInterval.stop, rightInterval.stop) ||
          (leftInterval.stop.equals(rightInterval.stop) &&
            !leftInterval.isStopIncluded &&
            rightInterval.isStopIncluded)
        ) {
          ++left;
        } else {
          ++right;
        }
      }
    }
    return result;
  };

  /**
   * Creates a new instance from a JulianDate array.
   *
   * @param {Object} options Object with the following properties:
   * @param {JulianDate[]} options.julianDates An array of ISO 8601 dates.
   * @param {Boolean} [options.isStartIncluded=true] <code>true</code> if start time is included in the interval, <code>false</code> otherwise.
   * @param {Boolean} [options.isStopIncluded=true] <code>true</code> if stop time is included in the interval, <code>false</code> otherwise.
   * @param {Boolean} [options.leadingInterval=false] <code>true</code> if you want to add a interval from Iso8601.MINIMUM_VALUE to start time,  <code>false</code> otherwise.
   * @param {Boolean} [options.trailingInterval=false] <code>true</code> if you want to add a interval from stop time to Iso8601.MAXIMUM_VALUE,  <code>false</code> otherwise.
   * @param {Function} [options.dataCallback] A function that will be return the data that is called with each interval before it is added to the collection. If unspecified, the data will be the index in the collection.
   * @param {TimeIntervalCollection} [result] An existing instance to use for the result.
   * @returns {TimeIntervalCollection} The modified result parameter or a new instance if none was provided.
   */
  TimeIntervalCollection.fromJulianDateArray = function (options, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(options)) {
      throw new DeveloperError("options is required.");
    }
    if (!defined(options.julianDates)) {
      throw new DeveloperError("options.iso8601Array is required.");
    }
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new TimeIntervalCollection();
    }

    const julianDates = options.julianDates;
    const length = julianDates.length;
    const dataCallback = options.dataCallback;

    const isStartIncluded = defaultValue(options.isStartIncluded, true);
    const isStopIncluded = defaultValue(options.isStopIncluded, true);
    const leadingInterval = defaultValue(options.leadingInterval, false);
    const trailingInterval = defaultValue(options.trailingInterval, false);
    let interval;

    // Add a default interval, which will only end up being used up to first interval
    let startIndex = 0;
    if (leadingInterval) {
      ++startIndex;
      interval = new TimeInterval({
        start: Iso8601.MINIMUM_VALUE,
        stop: julianDates[0],
        isStartIncluded: true,
        isStopIncluded: !isStartIncluded,
      });
      interval.data = defined(dataCallback)
        ? dataCallback(interval, result.length)
        : result.length;
      result.addInterval(interval);
    }

    for (let i = 0; i < length - 1; ++i) {
      let startDate = julianDates[i];
      const endDate = julianDates[i + 1];

      interval = new TimeInterval({
        start: startDate,
        stop: endDate,
        isStartIncluded: result.length === startIndex ? isStartIncluded : true,
        isStopIncluded: i === length - 2 ? isStopIncluded : false,
      });
      interval.data = defined(dataCallback)
        ? dataCallback(interval, result.length)
        : result.length;
      result.addInterval(interval);

      startDate = endDate;
    }

    if (trailingInterval) {
      interval = new TimeInterval({
        start: julianDates[length - 1],
        stop: Iso8601.MAXIMUM_VALUE,
        isStartIncluded: !isStopIncluded,
        isStopIncluded: true,
      });
      interval.data = defined(dataCallback)
        ? dataCallback(interval, result.length)
        : result.length;
      result.addInterval(interval);
    }

    return result;
  };

  const scratchGregorianDate = new GregorianDate();
  const monthLengths = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

  /**
   * Adds duration represented as a GregorianDate to a JulianDate
   *
   * @param {JulianDate} julianDate The date.
   * @param {GregorianDate} duration An duration represented as a GregorianDate.
   * @param {JulianDate} result An existing instance to use for the result.
   * @returns {JulianDate} The modified result parameter.
   *
   * @private
   */
  function addToDate(julianDate, duration, result) {
    if (!defined(result)) {
      result = new JulianDate();
    }
    JulianDate.toGregorianDate(julianDate, scratchGregorianDate);

    let millisecond = scratchGregorianDate.millisecond + duration.millisecond;
    let second = scratchGregorianDate.second + duration.second;
    let minute = scratchGregorianDate.minute + duration.minute;
    let hour = scratchGregorianDate.hour + duration.hour;
    let day = scratchGregorianDate.day + duration.day;
    let month = scratchGregorianDate.month + duration.month;
    let year = scratchGregorianDate.year + duration.year;

    if (millisecond >= 1000) {
      second += Math.floor(millisecond / 1000);
      millisecond = millisecond % 1000;
    }

    if (second >= 60) {
      minute += Math.floor(second / 60);
      second = second % 60;
    }

    if (minute >= 60) {
      hour += Math.floor(minute / 60);
      minute = minute % 60;
    }

    if (hour >= 24) {
      day += Math.floor(hour / 24);
      hour = hour % 24;
    }

    // If days is greater than the month's length we need to remove those number of days,
    //  readjust month and year and repeat until days is less than the month's length.
    monthLengths[2] = isLeapYear(year) ? 29 : 28;
    while (day > monthLengths[month] || month >= 13) {
      if (day > monthLengths[month]) {
        day -= monthLengths[month];
        ++month;
      }

      if (month >= 13) {
        --month;
        year += Math.floor(month / 12);
        month = month % 12;
        ++month;
      }

      monthLengths[2] = isLeapYear(year) ? 29 : 28;
    }

    scratchGregorianDate.millisecond = millisecond;
    scratchGregorianDate.second = second;
    scratchGregorianDate.minute = minute;
    scratchGregorianDate.hour = hour;
    scratchGregorianDate.day = day;
    scratchGregorianDate.month = month;
    scratchGregorianDate.year = year;

    return JulianDate.fromGregorianDate(scratchGregorianDate, result);
  }

  const scratchJulianDate$2 = new JulianDate();
  const durationRegex = /P(?:([\d.,]+)Y)?(?:([\d.,]+)M)?(?:([\d.,]+)W)?(?:([\d.,]+)D)?(?:T(?:([\d.,]+)H)?(?:([\d.,]+)M)?(?:([\d.,]+)S)?)?/;

  /**
   * Parses ISO8601 duration string
   *
   * @param {String} iso8601 An ISO 8601 duration.
   * @param {GregorianDate} result An existing instance to use for the result.
   * @returns {Boolean} True is parsing succeeded, false otherwise
   *
   * @private
   */
  function parseDuration(iso8601, result) {
    if (!defined(iso8601) || iso8601.length === 0) {
      return false;
    }

    // Reset object
    result.year = 0;
    result.month = 0;
    result.day = 0;
    result.hour = 0;
    result.minute = 0;
    result.second = 0;
    result.millisecond = 0;

    if (iso8601[0] === "P") {
      const matches = iso8601.match(durationRegex);
      if (!defined(matches)) {
        return false;
      }
      if (defined(matches[1])) {
        // Years
        result.year = Number(matches[1].replace(",", "."));
      }
      if (defined(matches[2])) {
        // Months
        result.month = Number(matches[2].replace(",", "."));
      }
      if (defined(matches[3])) {
        // Weeks
        result.day = Number(matches[3].replace(",", ".")) * 7;
      }
      if (defined(matches[4])) {
        // Days
        result.day += Number(matches[4].replace(",", "."));
      }
      if (defined(matches[5])) {
        // Hours
        result.hour = Number(matches[5].replace(",", "."));
      }
      if (defined(matches[6])) {
        // Weeks
        result.minute = Number(matches[6].replace(",", "."));
      }
      if (defined(matches[7])) {
        // Seconds
        const seconds = Number(matches[7].replace(",", "."));
        result.second = Math.floor(seconds);
        result.millisecond = (seconds % 1) * 1000;
      }
    } else {
      // They can technically specify the duration as a normal date with some caveats. Try our best to load it.
      if (iso8601[iso8601.length - 1] !== "Z") {
        // It's not a date, its a duration, so it always has to be UTC
        iso8601 += "Z";
      }
      JulianDate.toGregorianDate(
        JulianDate.fromIso8601(iso8601, scratchJulianDate$2),
        result
      );
    }

    // A duration of 0 will cause an infinite loop, so just make sure something is non-zero
    return (
      result.year ||
      result.month ||
      result.day ||
      result.hour ||
      result.minute ||
      result.second ||
      result.millisecond
    );
  }

  const scratchDuration = new GregorianDate();
  /**
   * Creates a new instance from an {@link http://en.wikipedia.org/wiki/ISO_8601|ISO 8601} time interval (start/end/duration).
   *
   * @param {Object} options Object with the following properties:
   * @param {String} options.iso8601 An ISO 8601 interval.
   * @param {Boolean} [options.isStartIncluded=true] <code>true</code> if start time is included in the interval, <code>false</code> otherwise.
   * @param {Boolean} [options.isStopIncluded=true] <code>true</code> if stop time is included in the interval, <code>false</code> otherwise.
   * @param {Boolean} [options.leadingInterval=false] <code>true</code> if you want to add a interval from Iso8601.MINIMUM_VALUE to start time,  <code>false</code> otherwise.
   * @param {Boolean} [options.trailingInterval=false] <code>true</code> if you want to add a interval from stop time to Iso8601.MAXIMUM_VALUE,  <code>false</code> otherwise.
   * @param {Function} [options.dataCallback] A function that will be return the data that is called with each interval before it is added to the collection. If unspecified, the data will be the index in the collection.
   * @param {TimeIntervalCollection} [result] An existing instance to use for the result.
   * @returns {TimeIntervalCollection} The modified result parameter or a new instance if none was provided.
   */
  TimeIntervalCollection.fromIso8601 = function (options, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(options)) {
      throw new DeveloperError("options is required.");
    }
    if (!defined(options.iso8601)) {
      throw new DeveloperError("options.iso8601 is required.");
    }
    //>>includeEnd('debug');

    const dates = options.iso8601.split("/");
    const start = JulianDate.fromIso8601(dates[0]);
    const stop = JulianDate.fromIso8601(dates[1]);
    const julianDates = [];

    if (!parseDuration(dates[2], scratchDuration)) {
      julianDates.push(start, stop);
    } else {
      let date = JulianDate.clone(start);
      julianDates.push(date);
      while (JulianDate.compare(date, stop) < 0) {
        date = addToDate(date, scratchDuration);
        const afterStop = JulianDate.compare(stop, date) <= 0;
        if (afterStop) {
          JulianDate.clone(stop, date);
        }

        julianDates.push(date);
      }
    }

    return TimeIntervalCollection.fromJulianDateArray(
      {
        julianDates: julianDates,
        isStartIncluded: options.isStartIncluded,
        isStopIncluded: options.isStopIncluded,
        leadingInterval: options.leadingInterval,
        trailingInterval: options.trailingInterval,
        dataCallback: options.dataCallback,
      },
      result
    );
  };

  /**
   * Creates a new instance from a {@link http://en.wikipedia.org/wiki/ISO_8601|ISO 8601} date array.
   *
   * @param {Object} options Object with the following properties:
   * @param {String[]} options.iso8601Dates An array of ISO 8601 dates.
   * @param {Boolean} [options.isStartIncluded=true] <code>true</code> if start time is included in the interval, <code>false</code> otherwise.
   * @param {Boolean} [options.isStopIncluded=true] <code>true</code> if stop time is included in the interval, <code>false</code> otherwise.
   * @param {Boolean} [options.leadingInterval=false] <code>true</code> if you want to add a interval from Iso8601.MINIMUM_VALUE to start time,  <code>false</code> otherwise.
   * @param {Boolean} [options.trailingInterval=false] <code>true</code> if you want to add a interval from stop time to Iso8601.MAXIMUM_VALUE,  <code>false</code> otherwise.
   * @param {Function} [options.dataCallback] A function that will be return the data that is called with each interval before it is added to the collection. If unspecified, the data will be the index in the collection.
   * @param {TimeIntervalCollection} [result] An existing instance to use for the result.
   * @returns {TimeIntervalCollection} The modified result parameter or a new instance if none was provided.
   */
  TimeIntervalCollection.fromIso8601DateArray = function (options, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(options)) {
      throw new DeveloperError("options is required.");
    }
    if (!defined(options.iso8601Dates)) {
      throw new DeveloperError("options.iso8601Dates is required.");
    }
    //>>includeEnd('debug');

    return TimeIntervalCollection.fromJulianDateArray(
      {
        julianDates: options.iso8601Dates.map(function (date) {
          return JulianDate.fromIso8601(date);
        }),
        isStartIncluded: options.isStartIncluded,
        isStopIncluded: options.isStopIncluded,
        leadingInterval: options.leadingInterval,
        trailingInterval: options.trailingInterval,
        dataCallback: options.dataCallback,
      },
      result
    );
  };

  /**
   * Creates a new instance from a {@link http://en.wikipedia.org/wiki/ISO_8601|ISO 8601} duration array.
   *
   * @param {Object} options Object with the following properties:
   * @param {JulianDate} options.epoch An date that the durations are relative to.
   * @param {String} options.iso8601Durations An array of ISO 8601 durations.
   * @param {Boolean} [options.relativeToPrevious=false] <code>true</code> if durations are relative to previous date, <code>false</code> if always relative to the epoch.
   * @param {Boolean} [options.isStartIncluded=true] <code>true</code> if start time is included in the interval, <code>false</code> otherwise.
   * @param {Boolean} [options.isStopIncluded=true] <code>true</code> if stop time is included in the interval, <code>false</code> otherwise.
   * @param {Boolean} [options.leadingInterval=false] <code>true</code> if you want to add a interval from Iso8601.MINIMUM_VALUE to start time,  <code>false</code> otherwise.
   * @param {Boolean} [options.trailingInterval=false] <code>true</code> if you want to add a interval from stop time to Iso8601.MAXIMUM_VALUE,  <code>false</code> otherwise.
   * @param {Function} [options.dataCallback] A function that will be return the data that is called with each interval before it is added to the collection. If unspecified, the data will be the index in the collection.
   * @param {TimeIntervalCollection} [result] An existing instance to use for the result.
   * @returns {TimeIntervalCollection} The modified result parameter or a new instance if none was provided.
   */
  TimeIntervalCollection.fromIso8601DurationArray = function (options, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(options)) {
      throw new DeveloperError("options is required.");
    }
    if (!defined(options.epoch)) {
      throw new DeveloperError("options.epoch is required.");
    }
    if (!defined(options.iso8601Durations)) {
      throw new DeveloperError("options.iso8601Durations is required.");
    }
    //>>includeEnd('debug');

    const epoch = options.epoch;
    const iso8601Durations = options.iso8601Durations;
    const relativeToPrevious = defaultValue(options.relativeToPrevious, false);
    const julianDates = [];
    let date, previousDate;

    const length = iso8601Durations.length;
    for (let i = 0; i < length; ++i) {
      // Allow a duration of 0 on the first iteration, because then it is just the epoch
      if (parseDuration(iso8601Durations[i], scratchDuration) || i === 0) {
        if (relativeToPrevious && defined(previousDate)) {
          date = addToDate(previousDate, scratchDuration);
        } else {
          date = addToDate(epoch, scratchDuration);
        }
        julianDates.push(date);
        previousDate = date;
      }
    }

    return TimeIntervalCollection.fromJulianDateArray(
      {
        julianDates: julianDates,
        isStartIncluded: options.isStartIncluded,
        isStopIncluded: options.isStopIncluded,
        leadingInterval: options.leadingInterval,
        trailingInterval: options.trailingInterval,
        dataCallback: options.dataCallback,
      },
      result
    );
  };

  const defaultScale$4 = new Cartesian3(1.0, 1.0, 1.0);
  const defaultTranslation = Cartesian3.ZERO;
  const defaultRotation$1 = Quaternion.IDENTITY;

  /**
   * An affine transformation defined by a translation, rotation, and scale.
   * @alias TranslationRotationScale
   * @constructor
   *
   * @param {Cartesian3} [translation=Cartesian3.ZERO] A {@link Cartesian3} specifying the (x, y, z) translation to apply to the node.
   * @param {Quaternion} [rotation=Quaternion.IDENTITY] A {@link Quaternion} specifying the (x, y, z, w) rotation to apply to the node.
   * @param {Cartesian3} [scale=new Cartesian3(1.0, 1.0, 1.0)] A {@link Cartesian3} specifying the (x, y, z) scaling to apply to the node.
   */
  function TranslationRotationScale(translation, rotation, scale) {
    /**
     * Gets or sets the (x, y, z) translation to apply to the node.
     * @type {Cartesian3}
     * @default Cartesian3.ZERO
     */
    this.translation = Cartesian3.clone(
      defaultValue(translation, defaultTranslation)
    );

    /**
     * Gets or sets the (x, y, z, w) rotation to apply to the node.
     * @type {Quaternion}
     * @default Quaternion.IDENTITY
     */
    this.rotation = Quaternion.clone(defaultValue(rotation, defaultRotation$1));

    /**
     * Gets or sets the (x, y, z) scaling to apply to the node.
     * @type {Cartesian3}
     * @default new Cartesian3(1.0, 1.0, 1.0)
     */
    this.scale = Cartesian3.clone(defaultValue(scale, defaultScale$4));
  }

  /**
   * Compares this instance against the provided instance and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {TranslationRotationScale} [right] The right hand side TranslationRotationScale.
   * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
   */
  TranslationRotationScale.prototype.equals = function (right) {
    return (
      this === right ||
      (defined(right) &&
        Cartesian3.equals(this.translation, right.translation) &&
        Quaternion.equals(this.rotation, right.rotation) &&
        Cartesian3.equals(this.scale, right.scale))
    );
  };

  function DataRectangle(rectangle, maxLevel) {
    this.rectangle = rectangle;
    this.maxLevel = maxLevel;
  }

  /**
   * A {@link TerrainProvider} that produces terrain geometry by tessellating height maps
   * retrieved from a {@link http://vr-theworld.com/|VT MÄK VR-TheWorld server}.
   *
   * @alias VRTheWorldTerrainProvider
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Resource|String} options.url The URL of the VR-TheWorld TileMap.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid.  If this parameter is not
   *                    specified, the WGS84 ellipsoid is used.
   * @param {Credit|String} [options.credit] A credit for the data source, which is displayed on the canvas.
   *
   *
   * @example
   * const terrainProvider = new Cesium.VRTheWorldTerrainProvider({
   *   url : 'https://www.vr-theworld.com/vr-theworld/tiles1.0.0/73/'
   * });
   * viewer.terrainProvider = terrainProvider;
   *
   * @see TerrainProvider
   */
  function VRTheWorldTerrainProvider(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    //>>includeStart('debug', pragmas.debug);
    if (!defined(options.url)) {
      throw new DeveloperError("options.url is required.");
    }
    //>>includeEnd('debug');

    const resource = Resource.createIfNeeded(options.url);

    this._resource = resource;

    this._errorEvent = new Event();
    this._ready = false;
    this._readyPromise = defer();

    this._terrainDataStructure = {
      heightScale: 1.0 / 1000.0,
      heightOffset: -1000.0,
      elementsPerHeight: 3,
      stride: 4,
      elementMultiplier: 256.0,
      isBigEndian: true,
      lowestEncodedHeight: 0,
      highestEncodedHeight: 256 * 256 * 256 - 1,
    };

    let credit = options.credit;
    if (typeof credit === "string") {
      credit = new Credit(credit);
    }
    this._credit = credit;

    this._tilingScheme = undefined;
    this._rectangles = [];

    const that = this;
    let metadataError;
    const ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);

    function metadataSuccess(xml) {
      const srs = xml.getElementsByTagName("SRS")[0].textContent;
      if (srs === "EPSG:4326") {
        that._tilingScheme = new GeographicTilingScheme({ ellipsoid: ellipsoid });
      } else {
        metadataFailure(`SRS ${srs} is not supported.`);
        return;
      }

      const tileFormat = xml.getElementsByTagName("TileFormat")[0];
      that._heightmapWidth = parseInt(tileFormat.getAttribute("width"), 10);
      that._heightmapHeight = parseInt(tileFormat.getAttribute("height"), 10);
      that._levelZeroMaximumGeometricError = TerrainProvider.getEstimatedLevelZeroGeometricErrorForAHeightmap(
        ellipsoid,
        Math.min(that._heightmapWidth, that._heightmapHeight),
        that._tilingScheme.getNumberOfXTilesAtLevel(0)
      );

      const dataRectangles = xml.getElementsByTagName("DataExtent");

      for (let i = 0; i < dataRectangles.length; ++i) {
        const dataRectangle = dataRectangles[i];

        const west = CesiumMath.toRadians(
          parseFloat(dataRectangle.getAttribute("minx"))
        );
        const south = CesiumMath.toRadians(
          parseFloat(dataRectangle.getAttribute("miny"))
        );
        const east = CesiumMath.toRadians(
          parseFloat(dataRectangle.getAttribute("maxx"))
        );
        const north = CesiumMath.toRadians(
          parseFloat(dataRectangle.getAttribute("maxy"))
        );
        const maxLevel = parseInt(dataRectangle.getAttribute("maxlevel"), 10);

        that._rectangles.push(
          new DataRectangle(new Rectangle(west, south, east, north), maxLevel)
        );
      }

      that._ready = true;
      that._readyPromise.resolve(true);
    }

    function metadataFailure(e) {
      const message = defaultValue(
        e,
        `An error occurred while accessing ${that._resource.url}.`
      );
      metadataError = TileProviderError.handleError(
        metadataError,
        that,
        that._errorEvent,
        message,
        undefined,
        undefined,
        undefined,
        requestMetadata
      );
    }

    function requestMetadata() {
      that._resource.fetchXML().then(metadataSuccess).catch(metadataFailure);
    }

    requestMetadata();
  }

  Object.defineProperties(VRTheWorldTerrainProvider.prototype, {
    /**
     * Gets an event that is raised when the terrain provider encounters an asynchronous error.  By subscribing
     * to the event, you will be notified of the error and can potentially recover from it.  Event listeners
     * are passed an instance of {@link TileProviderError}.
     * @memberof VRTheWorldTerrainProvider.prototype
     * @type {Event}
     * @readonly
     */
    errorEvent: {
      get: function () {
        return this._errorEvent;
      },
    },

    /**
     * Gets the credit to display when this terrain provider is active.  Typically this is used to credit
     * the source of the terrain.  This function should not be called before {@link VRTheWorldTerrainProvider#ready} returns true.
     * @memberof VRTheWorldTerrainProvider.prototype
     * @type {Credit}
     * @readonly
     */
    credit: {
      get: function () {
        return this._credit;
      },
    },

    /**
     * Gets the tiling scheme used by this provider.  This function should
     * not be called before {@link VRTheWorldTerrainProvider#ready} returns true.
     * @memberof VRTheWorldTerrainProvider.prototype
     * @type {GeographicTilingScheme}
     * @readonly
     */
    tilingScheme: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this.ready) {
          throw new DeveloperError(
            "requestTileGeometry must not be called before ready returns true."
          );
        }
        //>>includeEnd('debug');

        return this._tilingScheme;
      },
    },

    /**
     * Gets a value indicating whether or not the provider is ready for use.
     * @memberof VRTheWorldTerrainProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    ready: {
      get: function () {
        return this._ready;
      },
    },

    /**
     * Gets a promise that resolves to true when the provider is ready for use.
     * @memberof VRTheWorldTerrainProvider.prototype
     * @type {Promise.<Boolean>}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._readyPromise.promise;
      },
    },

    /**
     * Gets a value indicating whether or not the provider includes a water mask.  The water mask
     * indicates which areas of the globe are water rather than land, so they can be rendered
     * as a reflective surface with animated waves.  This function should not be
     * called before {@link VRTheWorldTerrainProvider#ready} returns true.
     * @memberof VRTheWorldTerrainProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    hasWaterMask: {
      get: function () {
        return false;
      },
    },

    /**
     * Gets a value indicating whether or not the requested tiles include vertex normals.
     * This function should not be called before {@link VRTheWorldTerrainProvider#ready} returns true.
     * @memberof VRTheWorldTerrainProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    hasVertexNormals: {
      get: function () {
        return false;
      },
    },
    /**
     * Gets an object that can be used to determine availability of terrain from this provider, such as
     * at points and in rectangles.  This function should not be called before
     * {@link TerrainProvider#ready} returns true.  This property may be undefined if availability
     * information is not available.
     * @memberof VRTheWorldTerrainProvider.prototype
     * @type {TileAvailability}
     * @readonly
     */
    availability: {
      get: function () {
        return undefined;
      },
    },
  });

  /**
   * Requests the geometry for a given tile.  This function should not be called before
   * {@link VRTheWorldTerrainProvider#ready} returns true.  The result includes terrain
   * data and indicates that all child tiles are available.
   *
   * @param {Number} x The X coordinate of the tile for which to request geometry.
   * @param {Number} y The Y coordinate of the tile for which to request geometry.
   * @param {Number} level The level of the tile for which to request geometry.
   * @param {Request} [request] The request object. Intended for internal use only.
   * @returns {Promise.<TerrainData>|undefined} A promise for the requested geometry.  If this method
   *          returns undefined instead of a promise, it is an indication that too many requests are already
   *          pending and the request will be retried later.
   */
  VRTheWorldTerrainProvider.prototype.requestTileGeometry = function (
    x,
    y,
    level,
    request
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!this.ready) {
      throw new DeveloperError(
        "requestTileGeometry must not be called before ready returns true."
      );
    }
    //>>includeEnd('debug');

    const yTiles = this._tilingScheme.getNumberOfYTilesAtLevel(level);
    const resource = this._resource.getDerivedResource({
      url: `${level}/${x}/${yTiles - y - 1}.tif`,
      queryParameters: {
        cesium: true,
      },
      request: request,
    });
    const promise = resource.fetchImage({
      preferImageBitmap: true,
    });
    if (!defined(promise)) {
      return undefined;
    }

    const that = this;
    return Promise.resolve(promise).then(function (image) {
      return new HeightmapTerrainData({
        buffer: getImagePixels(image),
        width: that._heightmapWidth,
        height: that._heightmapHeight,
        childTileMask: getChildMask(that, x, y, level),
        structure: that._terrainDataStructure,
      });
    });
  };

  /**
   * Gets the maximum geometric error allowed in a tile at a given level.
   *
   * @param {Number} level The tile level for which to get the maximum geometric error.
   * @returns {Number} The maximum geometric error.
   */
  VRTheWorldTerrainProvider.prototype.getLevelMaximumGeometricError = function (
    level
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!this.ready) {
      throw new DeveloperError(
        "requestTileGeometry must not be called before ready returns true."
      );
    }
    //>>includeEnd('debug');
    return this._levelZeroMaximumGeometricError / (1 << level);
  };

  const rectangleScratch$2 = new Rectangle();

  function getChildMask(provider, x, y, level) {
    const tilingScheme = provider._tilingScheme;
    const rectangles = provider._rectangles;
    const parentRectangle = tilingScheme.tileXYToRectangle(x, y, level);

    let childMask = 0;

    for (let i = 0; i < rectangles.length && childMask !== 15; ++i) {
      const rectangle = rectangles[i];
      if (rectangle.maxLevel <= level) {
        continue;
      }

      const testRectangle = rectangle.rectangle;

      const intersection = Rectangle.intersection(
        testRectangle,
        parentRectangle,
        rectangleScratch$2
      );
      if (defined(intersection)) {
        // Parent tile is inside this rectangle, so at least one child is, too.
        if (
          isTileInRectangle(tilingScheme, testRectangle, x * 2, y * 2, level + 1)
        ) {
          childMask |= 4; // northwest
        }
        if (
          isTileInRectangle(
            tilingScheme,
            testRectangle,
            x * 2 + 1,
            y * 2,
            level + 1
          )
        ) {
          childMask |= 8; // northeast
        }
        if (
          isTileInRectangle(
            tilingScheme,
            testRectangle,
            x * 2,
            y * 2 + 1,
            level + 1
          )
        ) {
          childMask |= 1; // southwest
        }
        if (
          isTileInRectangle(
            tilingScheme,
            testRectangle,
            x * 2 + 1,
            y * 2 + 1,
            level + 1
          )
        ) {
          childMask |= 2; // southeast
        }
      }
    }

    return childMask;
  }

  function isTileInRectangle(tilingScheme, rectangle, x, y, level) {
    const tileRectangle = tilingScheme.tileXYToRectangle(x, y, level);
    return defined(
      Rectangle.intersection(tileRectangle, rectangle, rectangleScratch$2)
    );
  }

  /**
   * Determines whether data for a tile is available to be loaded.
   *
   * @param {Number} x The X coordinate of the tile for which to request geometry.
   * @param {Number} y The Y coordinate of the tile for which to request geometry.
   * @param {Number} level The level of the tile for which to request geometry.
   * @returns {Boolean|undefined} Undefined if not supported, otherwise true or false.
   */
  VRTheWorldTerrainProvider.prototype.getTileDataAvailable = function (
    x,
    y,
    level
  ) {
    return undefined;
  };

  /**
   * Makes sure we load availability data for a tile
   *
   * @param {Number} x The X coordinate of the tile for which to request geometry.
   * @param {Number} y The Y coordinate of the tile for which to request geometry.
   * @param {Number} level The level of the tile for which to request geometry.
   * @returns {undefined|Promise<void>} Undefined if nothing need to be loaded or a Promise that resolves when all required tiles are loaded
   */
  VRTheWorldTerrainProvider.prototype.loadTileDataAvailability = function (
    x,
    y,
    level
  ) {
    return undefined;
  };

  /**
   * Synchronizes a video element with a simulation clock.
   *
   * @alias VideoSynchronizer
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Clock} [options.clock] The clock instance used to drive the video.
   * @param {HTMLVideoElement} [options.element] The video element to be synchronized.
   * @param {JulianDate} [options.epoch=Iso8601.MINIMUM_VALUE] The simulation time that marks the start of the video.
   * @param {Number} [options.tolerance=1.0] The maximum amount of time, in seconds, that the clock and video can diverge.
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Video.html|Video Material Demo}
   */
  function VideoSynchronizer(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    this._clock = undefined;
    this._element = undefined;
    this._clockSubscription = undefined;
    this._seekFunction = undefined;
    this._lastPlaybackRate = undefined;

    this.clock = options.clock;
    this.element = options.element;

    /**
     * Gets or sets the simulation time that marks the start of the video.
     * @type {JulianDate}
     * @default Iso8601.MINIMUM_VALUE
     */
    this.epoch = defaultValue(options.epoch, Iso8601.MINIMUM_VALUE);

    /**
     * Gets or sets the amount of time in seconds the video's currentTime
     * and the clock's currentTime can diverge before a video seek is performed.
     * Lower values make the synchronization more accurate but video
     * performance might suffer.  Higher values provide better performance
     * but at the cost of accuracy.
     * @type {Number}
     * @default 1.0
     */
    this.tolerance = defaultValue(options.tolerance, 1.0);

    this._seeking = false;
    this._seekFunction = undefined;
    this._firstTickAfterSeek = false;
  }

  Object.defineProperties(VideoSynchronizer.prototype, {
    /**
     * Gets or sets the clock used to drive the video element.
     *
     * @memberof VideoSynchronizer.prototype
     * @type {Clock}
     */
    clock: {
      get: function () {
        return this._clock;
      },
      set: function (value) {
        const oldValue = this._clock;

        if (oldValue === value) {
          return;
        }

        if (defined(oldValue)) {
          this._clockSubscription();
          this._clockSubscription = undefined;
        }

        if (defined(value)) {
          this._clockSubscription = value.onTick.addEventListener(
            VideoSynchronizer.prototype._onTick,
            this
          );
        }

        this._clock = value;
      },
    },
    /**
     * Gets or sets the video element to synchronize.
     *
     * @memberof VideoSynchronizer.prototype
     * @type {HTMLVideoElement}
     */
    element: {
      get: function () {
        return this._element;
      },
      set: function (value) {
        const oldValue = this._element;

        if (oldValue === value) {
          return;
        }

        if (defined(oldValue)) {
          oldValue.removeEventListener("seeked", this._seekFunction, false);
        }

        if (defined(value)) {
          this._seeking = false;
          this._seekFunction = createSeekFunction(this);
          value.addEventListener("seeked", this._seekFunction, false);
        }

        this._element = value;
        this._seeking = false;
        this._firstTickAfterSeek = false;
      },
    },
  });

  /**
   * Destroys and resources used by the object.  Once an object is destroyed, it should not be used.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   */
  VideoSynchronizer.prototype.destroy = function () {
    this.element = undefined;
    this.clock = undefined;
    return destroyObject(this);
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   *
   * @returns {Boolean} True if this object was destroyed; otherwise, false.
   */
  VideoSynchronizer.prototype.isDestroyed = function () {
    return false;
  };

  VideoSynchronizer.prototype._trySetPlaybackRate = function (clock) {
    if (this._lastPlaybackRate === clock.multiplier) {
      return;
    }

    const element = this._element;
    try {
      element.playbackRate = clock.multiplier;
    } catch (error) {
      // Seek manually for unsupported playbackRates.
      element.playbackRate = 0.0;
    }
    this._lastPlaybackRate = clock.multiplier;
  };

  VideoSynchronizer.prototype._onTick = function (clock) {
    const element = this._element;
    if (!defined(element) || element.readyState < 2) {
      return;
    }

    const paused = element.paused;
    const shouldAnimate = clock.shouldAnimate;
    if (shouldAnimate === paused) {
      if (shouldAnimate) {
        element.play();
      } else {
        element.pause();
      }
    }

    //We need to avoid constant seeking or the video will
    //never contain a complete frame for us to render.
    //So don't do anything if we're seeing or on the first
    //tick after a seek (the latter of which allows the frame
    //to actually be rendered.
    if (this._seeking || this._firstTickAfterSeek) {
      this._firstTickAfterSeek = false;
      return;
    }

    this._trySetPlaybackRate(clock);

    const clockTime = clock.currentTime;
    const epoch = defaultValue(this.epoch, Iso8601.MINIMUM_VALUE);
    let videoTime = JulianDate.secondsDifference(clockTime, epoch);

    const duration = element.duration;
    let desiredTime;
    const currentTime = element.currentTime;
    if (element.loop) {
      videoTime = videoTime % duration;
      if (videoTime < 0.0) {
        videoTime = duration - videoTime;
      }
      desiredTime = videoTime;
    } else if (videoTime > duration) {
      desiredTime = duration;
    } else if (videoTime < 0.0) {
      desiredTime = 0.0;
    } else {
      desiredTime = videoTime;
    }

    //If the playing video's time and the scene's clock time
    //ever drift too far apart, we want to set the video to match
    const tolerance = shouldAnimate ? defaultValue(this.tolerance, 1.0) : 0.001;
    if (Math.abs(desiredTime - currentTime) > tolerance) {
      this._seeking = true;
      element.currentTime = desiredTime;
    }
  };

  function createSeekFunction(that) {
    return function () {
      that._seeking = false;
      that._firstTickAfterSeek = true;
    };
  }

  /**
   * Enum containing Vulkan Constant values by name.
   *
   * These match the constants from the {@link https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#formats-definition|Vulkan 1.2 specification}.
   *
   * @enum {Number}
   * @private
   */
  const VulkanConstants = {
    VK_FORMAT_UNDEFINED: 0,
    VK_FORMAT_R4G4_UNORM_PACK8: 1,
    VK_FORMAT_R4G4B4A4_UNORM_PACK16: 2,
    VK_FORMAT_B4G4R4A4_UNORM_PACK16: 3,
    VK_FORMAT_R5G6B5_UNORM_PACK16: 4,
    VK_FORMAT_B5G6R5_UNORM_PACK16: 5,
    VK_FORMAT_R5G5B5A1_UNORM_PACK16: 6,
    VK_FORMAT_B5G5R5A1_UNORM_PACK16: 7,
    VK_FORMAT_A1R5G5B5_UNORM_PACK16: 8,
    VK_FORMAT_R8_UNORM: 9,
    VK_FORMAT_R8_SNORM: 10,
    VK_FORMAT_R8_USCALED: 11,
    VK_FORMAT_R8_SSCALED: 12,
    VK_FORMAT_R8_UINT: 13,
    VK_FORMAT_R8_SINT: 14,
    VK_FORMAT_R8_SRGB: 15,
    VK_FORMAT_R8G8_UNORM: 16,
    VK_FORMAT_R8G8_SNORM: 17,
    VK_FORMAT_R8G8_USCALED: 18,
    VK_FORMAT_R8G8_SSCALED: 19,
    VK_FORMAT_R8G8_UINT: 20,
    VK_FORMAT_R8G8_SINT: 21,
    VK_FORMAT_R8G8_SRGB: 22,
    VK_FORMAT_R8G8B8_UNORM: 23,
    VK_FORMAT_R8G8B8_SNORM: 24,
    VK_FORMAT_R8G8B8_USCALED: 25,
    VK_FORMAT_R8G8B8_SSCALED: 26,
    VK_FORMAT_R8G8B8_UINT: 27,
    VK_FORMAT_R8G8B8_SINT: 28,
    VK_FORMAT_R8G8B8_SRGB: 29,
    VK_FORMAT_B8G8R8_UNORM: 30,
    VK_FORMAT_B8G8R8_SNORM: 31,
    VK_FORMAT_B8G8R8_USCALED: 32,
    VK_FORMAT_B8G8R8_SSCALED: 33,
    VK_FORMAT_B8G8R8_UINT: 34,
    VK_FORMAT_B8G8R8_SINT: 35,
    VK_FORMAT_B8G8R8_SRGB: 36,
    VK_FORMAT_R8G8B8A8_UNORM: 37,
    VK_FORMAT_R8G8B8A8_SNORM: 38,
    VK_FORMAT_R8G8B8A8_USCALED: 39,
    VK_FORMAT_R8G8B8A8_SSCALED: 40,
    VK_FORMAT_R8G8B8A8_UINT: 41,
    VK_FORMAT_R8G8B8A8_SINT: 42,
    VK_FORMAT_R8G8B8A8_SRGB: 43,
    VK_FORMAT_B8G8R8A8_UNORM: 44,
    VK_FORMAT_B8G8R8A8_SNORM: 45,
    VK_FORMAT_B8G8R8A8_USCALED: 46,
    VK_FORMAT_B8G8R8A8_SSCALED: 47,
    VK_FORMAT_B8G8R8A8_UINT: 48,
    VK_FORMAT_B8G8R8A8_SINT: 49,
    VK_FORMAT_B8G8R8A8_SRGB: 50,
    VK_FORMAT_A8B8G8R8_UNORM_PACK32: 51,
    VK_FORMAT_A8B8G8R8_SNORM_PACK32: 52,
    VK_FORMAT_A8B8G8R8_USCALED_PACK32: 53,
    VK_FORMAT_A8B8G8R8_SSCALED_PACK32: 54,
    VK_FORMAT_A8B8G8R8_UINT_PACK32: 55,
    VK_FORMAT_A8B8G8R8_SINT_PACK32: 56,
    VK_FORMAT_A8B8G8R8_SRGB_PACK32: 57,
    VK_FORMAT_A2R10G10B10_UNORM_PACK32: 58,
    VK_FORMAT_A2R10G10B10_SNORM_PACK32: 59,
    VK_FORMAT_A2R10G10B10_USCALED_PACK32: 60,
    VK_FORMAT_A2R10G10B10_SSCALED_PACK32: 61,
    VK_FORMAT_A2R10G10B10_UINT_PACK32: 62,
    VK_FORMAT_A2R10G10B10_SINT_PACK32: 63,
    VK_FORMAT_A2B10G10R10_UNORM_PACK32: 64,
    VK_FORMAT_A2B10G10R10_SNORM_PACK32: 65,
    VK_FORMAT_A2B10G10R10_USCALED_PACK32: 66,
    VK_FORMAT_A2B10G10R10_SSCALED_PACK32: 67,
    VK_FORMAT_A2B10G10R10_UINT_PACK32: 68,
    VK_FORMAT_A2B10G10R10_SINT_PACK32: 69,
    VK_FORMAT_R16_UNORM: 70,
    VK_FORMAT_R16_SNORM: 71,
    VK_FORMAT_R16_USCALED: 72,
    VK_FORMAT_R16_SSCALED: 73,
    VK_FORMAT_R16_UINT: 74,
    VK_FORMAT_R16_SINT: 75,
    VK_FORMAT_R16_SFLOAT: 76,
    VK_FORMAT_R16G16_UNORM: 77,
    VK_FORMAT_R16G16_SNORM: 78,
    VK_FORMAT_R16G16_USCALED: 79,
    VK_FORMAT_R16G16_SSCALED: 80,
    VK_FORMAT_R16G16_UINT: 81,
    VK_FORMAT_R16G16_SINT: 82,
    VK_FORMAT_R16G16_SFLOAT: 83,
    VK_FORMAT_R16G16B16_UNORM: 84,
    VK_FORMAT_R16G16B16_SNORM: 85,
    VK_FORMAT_R16G16B16_USCALED: 86,
    VK_FORMAT_R16G16B16_SSCALED: 87,
    VK_FORMAT_R16G16B16_UINT: 88,
    VK_FORMAT_R16G16B16_SINT: 89,
    VK_FORMAT_R16G16B16_SFLOAT: 90,
    VK_FORMAT_R16G16B16A16_UNORM: 91,
    VK_FORMAT_R16G16B16A16_SNORM: 92,
    VK_FORMAT_R16G16B16A16_USCALED: 93,
    VK_FORMAT_R16G16B16A16_SSCALED: 94,
    VK_FORMAT_R16G16B16A16_UINT: 95,
    VK_FORMAT_R16G16B16A16_SINT: 96,
    VK_FORMAT_R16G16B16A16_SFLOAT: 97,
    VK_FORMAT_R32_UINT: 98,
    VK_FORMAT_R32_SINT: 99,
    VK_FORMAT_R32_SFLOAT: 100,
    VK_FORMAT_R32G32_UINT: 101,
    VK_FORMAT_R32G32_SINT: 102,
    VK_FORMAT_R32G32_SFLOAT: 103,
    VK_FORMAT_R32G32B32_UINT: 104,
    VK_FORMAT_R32G32B32_SINT: 105,
    VK_FORMAT_R32G32B32_SFLOAT: 106,
    VK_FORMAT_R32G32B32A32_UINT: 107,
    VK_FORMAT_R32G32B32A32_SINT: 108,
    VK_FORMAT_R32G32B32A32_SFLOAT: 109,
    VK_FORMAT_R64_UINT: 110,
    VK_FORMAT_R64_SINT: 111,
    VK_FORMAT_R64_SFLOAT: 112,
    VK_FORMAT_R64G64_UINT: 113,
    VK_FORMAT_R64G64_SINT: 114,
    VK_FORMAT_R64G64_SFLOAT: 115,
    VK_FORMAT_R64G64B64_UINT: 116,
    VK_FORMAT_R64G64B64_SINT: 117,
    VK_FORMAT_R64G64B64_SFLOAT: 118,
    VK_FORMAT_R64G64B64A64_UINT: 119,
    VK_FORMAT_R64G64B64A64_SINT: 120,
    VK_FORMAT_R64G64B64A64_SFLOAT: 121,
    VK_FORMAT_B10G11R11_UFLOAT_PACK32: 122,
    VK_FORMAT_E5B9G9R9_UFLOAT_PACK32: 123,
    VK_FORMAT_D16_UNORM: 124,
    VK_FORMAT_X8_D24_UNORM_PACK32: 125,
    VK_FORMAT_D32_SFLOAT: 126,
    VK_FORMAT_S8_UINT: 127,
    VK_FORMAT_D16_UNORM_S8_UINT: 128,
    VK_FORMAT_D24_UNORM_S8_UINT: 129,
    VK_FORMAT_D32_SFLOAT_S8_UINT: 130,
    VK_FORMAT_BC1_RGB_UNORM_BLOCK: 131,
    VK_FORMAT_BC1_RGB_SRGB_BLOCK: 132,
    VK_FORMAT_BC1_RGBA_UNORM_BLOCK: 133,
    VK_FORMAT_BC1_RGBA_SRGB_BLOCK: 134,
    VK_FORMAT_BC2_UNORM_BLOCK: 135,
    VK_FORMAT_BC2_SRGB_BLOCK: 136,
    VK_FORMAT_BC3_UNORM_BLOCK: 137,
    VK_FORMAT_BC3_SRGB_BLOCK: 138,
    VK_FORMAT_BC4_UNORM_BLOCK: 139,
    VK_FORMAT_BC4_SNORM_BLOCK: 140,
    VK_FORMAT_BC5_UNORM_BLOCK: 141,
    VK_FORMAT_BC5_SNORM_BLOCK: 142,
    VK_FORMAT_BC6H_UFLOAT_BLOCK: 143,
    VK_FORMAT_BC6H_SFLOAT_BLOCK: 144,
    VK_FORMAT_BC7_UNORM_BLOCK: 145,
    VK_FORMAT_BC7_SRGB_BLOCK: 146,
    VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK: 147,
    VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK: 148,
    VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK: 149,
    VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK: 150,
    VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK: 151,
    VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK: 152,
    VK_FORMAT_EAC_R11_UNORM_BLOCK: 153,
    VK_FORMAT_EAC_R11_SNORM_BLOCK: 154,
    VK_FORMAT_EAC_R11G11_UNORM_BLOCK: 155,
    VK_FORMAT_EAC_R11G11_SNORM_BLOCK: 156,
    VK_FORMAT_ASTC_4x4_UNORM_BLOCK: 157,
    VK_FORMAT_ASTC_4x4_SRGB_BLOCK: 158,
    VK_FORMAT_ASTC_5x4_UNORM_BLOCK: 159,
    VK_FORMAT_ASTC_5x4_SRGB_BLOCK: 160,
    VK_FORMAT_ASTC_5x5_UNORM_BLOCK: 161,
    VK_FORMAT_ASTC_5x5_SRGB_BLOCK: 162,
    VK_FORMAT_ASTC_6x5_UNORM_BLOCK: 163,
    VK_FORMAT_ASTC_6x5_SRGB_BLOCK: 164,
    VK_FORMAT_ASTC_6x6_UNORM_BLOCK: 165,
    VK_FORMAT_ASTC_6x6_SRGB_BLOCK: 166,
    VK_FORMAT_ASTC_8x5_UNORM_BLOCK: 167,
    VK_FORMAT_ASTC_8x5_SRGB_BLOCK: 168,
    VK_FORMAT_ASTC_8x6_UNORM_BLOCK: 169,
    VK_FORMAT_ASTC_8x6_SRGB_BLOCK: 170,
    VK_FORMAT_ASTC_8x8_UNORM_BLOCK: 171,
    VK_FORMAT_ASTC_8x8_SRGB_BLOCK: 172,
    VK_FORMAT_ASTC_10x5_UNORM_BLOCK: 173,
    VK_FORMAT_ASTC_10x5_SRGB_BLOCK: 174,
    VK_FORMAT_ASTC_10x6_UNORM_BLOCK: 175,
    VK_FORMAT_ASTC_10x6_SRGB_BLOCK: 176,
    VK_FORMAT_ASTC_10x8_UNORM_BLOCK: 177,
    VK_FORMAT_ASTC_10x8_SRGB_BLOCK: 178,
    VK_FORMAT_ASTC_10x10_UNORM_BLOCK: 179,
    VK_FORMAT_ASTC_10x10_SRGB_BLOCK: 180,
    VK_FORMAT_ASTC_12x10_UNORM_BLOCK: 181,
    VK_FORMAT_ASTC_12x10_SRGB_BLOCK: 182,
    VK_FORMAT_ASTC_12x12_UNORM_BLOCK: 183,
    VK_FORMAT_ASTC_12x12_SRGB_BLOCK: 184,
    VK_FORMAT_G8B8G8R8_422_UNORM: 1000156000,
    VK_FORMAT_B8G8R8G8_422_UNORM: 1000156001,
    VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM: 1000156002,
    VK_FORMAT_G8_B8R8_2PLANE_420_UNORM: 1000156003,
    VK_FORMAT_G8_B8_R8_3PLANE_422_UNORM: 1000156004,
    VK_FORMAT_G8_B8R8_2PLANE_422_UNORM: 1000156005,
    VK_FORMAT_G8_B8_R8_3PLANE_444_UNORM: 1000156006,
    VK_FORMAT_R10X6_UNORM_PACK16: 1000156007,
    VK_FORMAT_R10X6G10X6_UNORM_2PACK16: 1000156008,
    VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16: 1000156009,
    VK_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16: 1000156010,
    VK_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16: 1000156011,
    VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16: 1000156012,
    VK_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16: 1000156013,
    VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16: 1000156014,
    VK_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16: 1000156015,
    VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16: 1000156016,
    VK_FORMAT_R12X4_UNORM_PACK16: 1000156017,
    VK_FORMAT_R12X4G12X4_UNORM_2PACK16: 1000156018,
    VK_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16: 1000156019,
    VK_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16: 1000156020,
    VK_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16: 1000156021,
    VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16: 1000156022,
    VK_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16: 1000156023,
    VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16: 1000156024,
    VK_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16: 1000156025,
    VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16: 1000156026,
    VK_FORMAT_G16B16G16R16_422_UNORM: 1000156027,
    VK_FORMAT_B16G16R16G16_422_UNORM: 1000156028,
    VK_FORMAT_G16_B16_R16_3PLANE_420_UNORM: 1000156029,
    VK_FORMAT_G16_B16R16_2PLANE_420_UNORM: 1000156030,
    VK_FORMAT_G16_B16_R16_3PLANE_422_UNORM: 1000156031,
    VK_FORMAT_G16_B16R16_2PLANE_422_UNORM: 1000156032,
    VK_FORMAT_G16_B16_R16_3PLANE_444_UNORM: 1000156033,
    VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG: 1000054000,
    VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG: 1000054001,
    VK_FORMAT_PVRTC2_2BPP_UNORM_BLOCK_IMG: 1000054002,
    VK_FORMAT_PVRTC2_4BPP_UNORM_BLOCK_IMG: 1000054003,
    VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG: 1000054004,
    VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG: 1000054005,
    VK_FORMAT_PVRTC2_2BPP_SRGB_BLOCK_IMG: 1000054006,
    VK_FORMAT_PVRTC2_4BPP_SRGB_BLOCK_IMG: 1000054007,
    VK_FORMAT_ASTC_4x4_SFLOAT_BLOCK_EXT: 1000066000,
    VK_FORMAT_ASTC_5x4_SFLOAT_BLOCK_EXT: 1000066001,
    VK_FORMAT_ASTC_5x5_SFLOAT_BLOCK_EXT: 1000066002,
    VK_FORMAT_ASTC_6x5_SFLOAT_BLOCK_EXT: 1000066003,
    VK_FORMAT_ASTC_6x6_SFLOAT_BLOCK_EXT: 1000066004,
    VK_FORMAT_ASTC_8x5_SFLOAT_BLOCK_EXT: 1000066005,
    VK_FORMAT_ASTC_8x6_SFLOAT_BLOCK_EXT: 1000066006,
    VK_FORMAT_ASTC_8x8_SFLOAT_BLOCK_EXT: 1000066007,
    VK_FORMAT_ASTC_10x5_SFLOAT_BLOCK_EXT: 1000066008,
    VK_FORMAT_ASTC_10x6_SFLOAT_BLOCK_EXT: 1000066009,
    VK_FORMAT_ASTC_10x8_SFLOAT_BLOCK_EXT: 1000066010,
    VK_FORMAT_ASTC_10x10_SFLOAT_BLOCK_EXT: 1000066011,
    VK_FORMAT_ASTC_12x10_SFLOAT_BLOCK_EXT: 1000066012,
    VK_FORMAT_ASTC_12x12_SFLOAT_BLOCK_EXT: 1000066013,
    VK_FORMAT_G8B8G8R8_422_UNORM_KHR: 1000156000,
    VK_FORMAT_B8G8R8G8_422_UNORM_KHR: 1000156001,
    VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM_KHR: 1000156002,
    VK_FORMAT_G8_B8R8_2PLANE_420_UNORM_KHR: 1000156003,
    VK_FORMAT_G8_B8_R8_3PLANE_422_UNORM_KHR: 1000156004,
    VK_FORMAT_G8_B8R8_2PLANE_422_UNORM_KHR: 1000156005,
    VK_FORMAT_G8_B8_R8_3PLANE_444_UNORM_KHR: 1000156006,
    VK_FORMAT_R10X6_UNORM_PACK16_KHR: 1000156007,
    VK_FORMAT_R10X6G10X6_UNORM_2PACK16_KHR: 1000156008,
    VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16_KHR: 1000156009,
    VK_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16_KHR: 1000156010,
    VK_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16_KHR: 1000156011,
    VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16_KHR: 1000156012,
    VK_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16_KHR: 1000156013,
    VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16_KHR: 1000156014,
    VK_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16_KHR: 1000156015,
    VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16_KHR: 1000156016,
    VK_FORMAT_R12X4_UNORM_PACK16_KHR: 1000156017,
    VK_FORMAT_R12X4G12X4_UNORM_2PACK16_KHR: 1000156018,
    VK_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16_KHR: 1000156019,
    VK_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16_KHR: 1000156020,
    VK_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16_KHR: 1000156021,
    VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16_KHR: 1000156022,
    VK_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16_KHR: 1000156023,
    VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16_KHR: 1000156024,
    VK_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16_KHR: 1000156025,
    VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16_KHR: 1000156026,
    VK_FORMAT_G16B16G16R16_422_UNORM_KHR: 1000156027,
    VK_FORMAT_B16G16R16G16_422_UNORM_KHR: 1000156028,
    VK_FORMAT_G16_B16_R16_3PLANE_420_UNORM_KHR: 1000156029,
    VK_FORMAT_G16_B16R16_2PLANE_420_UNORM_KHR: 1000156030,
    VK_FORMAT_G16_B16_R16_3PLANE_422_UNORM_KHR: 1000156031,
    VK_FORMAT_G16_B16R16_2PLANE_422_UNORM_KHR: 1000156032,
    VK_FORMAT_G16_B16_R16_3PLANE_444_UNORM_KHR: 1000156033,
  };
  var VulkanConstants$1 = Object.freeze(VulkanConstants);

  /**
   * @private
   */
  const WallGeometryLibrary = {};

  function latLonEquals(c0, c1) {
    return (
      CesiumMath.equalsEpsilon(c0.latitude, c1.latitude, CesiumMath.EPSILON10) &&
      CesiumMath.equalsEpsilon(c0.longitude, c1.longitude, CesiumMath.EPSILON10)
    );
  }

  const scratchCartographic1 = new Cartographic();
  const scratchCartographic2 = new Cartographic();
  function removeDuplicates$1(ellipsoid, positions, topHeights, bottomHeights) {
    positions = arrayRemoveDuplicates(positions, Cartesian3.equalsEpsilon);

    const length = positions.length;
    if (length < 2) {
      return;
    }

    const hasBottomHeights = defined(bottomHeights);
    const hasTopHeights = defined(topHeights);

    const cleanedPositions = new Array(length);
    const cleanedTopHeights = new Array(length);
    const cleanedBottomHeights = new Array(length);

    const v0 = positions[0];
    cleanedPositions[0] = v0;

    const c0 = ellipsoid.cartesianToCartographic(v0, scratchCartographic1);
    if (hasTopHeights) {
      c0.height = topHeights[0];
    }

    cleanedTopHeights[0] = c0.height;

    if (hasBottomHeights) {
      cleanedBottomHeights[0] = bottomHeights[0];
    } else {
      cleanedBottomHeights[0] = 0.0;
    }

    const startTopHeight = cleanedTopHeights[0];
    const startBottomHeight = cleanedBottomHeights[0];
    let hasAllSameHeights = startTopHeight === startBottomHeight;

    let index = 1;
    for (let i = 1; i < length; ++i) {
      const v1 = positions[i];
      const c1 = ellipsoid.cartesianToCartographic(v1, scratchCartographic2);
      if (hasTopHeights) {
        c1.height = topHeights[i];
      }
      hasAllSameHeights = hasAllSameHeights && c1.height === 0;

      if (!latLonEquals(c0, c1)) {
        cleanedPositions[index] = v1; // Shallow copy!
        cleanedTopHeights[index] = c1.height;

        if (hasBottomHeights) {
          cleanedBottomHeights[index] = bottomHeights[i];
        } else {
          cleanedBottomHeights[index] = 0.0;
        }
        hasAllSameHeights =
          hasAllSameHeights &&
          cleanedTopHeights[index] === cleanedBottomHeights[index];

        Cartographic.clone(c1, c0);
        ++index;
      } else if (c0.height < c1.height) {
        // two adjacent positions are the same, so use whichever has the greater height
        cleanedTopHeights[index - 1] = c1.height;
      }
    }

    if (hasAllSameHeights || index < 2) {
      return;
    }

    cleanedPositions.length = index;
    cleanedTopHeights.length = index;
    cleanedBottomHeights.length = index;

    return {
      positions: cleanedPositions,
      topHeights: cleanedTopHeights,
      bottomHeights: cleanedBottomHeights,
    };
  }

  const positionsArrayScratch = new Array(2);
  const heightsArrayScratch = new Array(2);
  const generateArcOptionsScratch = {
    positions: undefined,
    height: undefined,
    granularity: undefined,
    ellipsoid: undefined,
  };

  /**
   * @private
   */
  WallGeometryLibrary.computePositions = function (
    ellipsoid,
    wallPositions,
    maximumHeights,
    minimumHeights,
    granularity,
    duplicateCorners
  ) {
    const o = removeDuplicates$1(
      ellipsoid,
      wallPositions,
      maximumHeights,
      minimumHeights
    );

    if (!defined(o)) {
      return;
    }

    wallPositions = o.positions;
    maximumHeights = o.topHeights;
    minimumHeights = o.bottomHeights;

    const length = wallPositions.length;
    const numCorners = length - 2;
    let topPositions;
    let bottomPositions;

    const minDistance = CesiumMath.chordLength(
      granularity,
      ellipsoid.maximumRadius
    );

    const generateArcOptions = generateArcOptionsScratch;
    generateArcOptions.minDistance = minDistance;
    generateArcOptions.ellipsoid = ellipsoid;

    if (duplicateCorners) {
      let count = 0;
      let i;

      for (i = 0; i < length - 1; i++) {
        count +=
          PolylinePipeline.numberOfPoints(
            wallPositions[i],
            wallPositions[i + 1],
            minDistance
          ) + 1;
      }

      topPositions = new Float64Array(count * 3);
      bottomPositions = new Float64Array(count * 3);

      const generateArcPositions = positionsArrayScratch;
      const generateArcHeights = heightsArrayScratch;
      generateArcOptions.positions = generateArcPositions;
      generateArcOptions.height = generateArcHeights;

      let offset = 0;
      for (i = 0; i < length - 1; i++) {
        generateArcPositions[0] = wallPositions[i];
        generateArcPositions[1] = wallPositions[i + 1];

        generateArcHeights[0] = maximumHeights[i];
        generateArcHeights[1] = maximumHeights[i + 1];

        const pos = PolylinePipeline.generateArc(generateArcOptions);
        topPositions.set(pos, offset);

        generateArcHeights[0] = minimumHeights[i];
        generateArcHeights[1] = minimumHeights[i + 1];

        bottomPositions.set(
          PolylinePipeline.generateArc(generateArcOptions),
          offset
        );

        offset += pos.length;
      }
    } else {
      generateArcOptions.positions = wallPositions;
      generateArcOptions.height = maximumHeights;
      topPositions = new Float64Array(
        PolylinePipeline.generateArc(generateArcOptions)
      );

      generateArcOptions.height = minimumHeights;
      bottomPositions = new Float64Array(
        PolylinePipeline.generateArc(generateArcOptions)
      );
    }

    return {
      bottomPositions: bottomPositions,
      topPositions: topPositions,
      numCorners: numCorners,
    };
  };

  const scratchCartesian3Position1$1 = new Cartesian3();
  const scratchCartesian3Position2$1 = new Cartesian3();
  const scratchCartesian3Position4 = new Cartesian3();
  const scratchCartesian3Position5 = new Cartesian3();
  const scratchBitangent = new Cartesian3();
  const scratchTangent = new Cartesian3();
  const scratchNormal$1 = new Cartesian3();

  /**
   * A description of a wall, which is similar to a KML line string. A wall is defined by a series of points,
   * which extrude down to the ground. Optionally, they can extrude downwards to a specified height.
   *
   * @alias WallGeometry
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Cartesian3[]} options.positions An array of Cartesian objects, which are the points of the wall.
   * @param {Number} [options.granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
   * @param {Number[]} [options.maximumHeights] An array parallel to <code>positions</code> that give the maximum height of the
   *        wall at <code>positions</code>. If undefined, the height of each position in used.
   * @param {Number[]} [options.minimumHeights] An array parallel to <code>positions</code> that give the minimum height of the
   *        wall at <code>positions</code>. If undefined, the height at each position is 0.0.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid for coordinate manipulation
   * @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
   *
   * @exception {DeveloperError} positions length must be greater than or equal to 2.
   * @exception {DeveloperError} positions and maximumHeights must have the same length.
   * @exception {DeveloperError} positions and minimumHeights must have the same length.
   *
   * @see WallGeometry#createGeometry
   * @see WallGeometry#fromConstantHeight
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Wall.html|Cesium Sandcastle Wall Demo}
   *
   * @example
   * // create a wall that spans from ground level to 10000 meters
   * const wall = new Cesium.WallGeometry({
   *   positions : Cesium.Cartesian3.fromDegreesArrayHeights([
   *     19.0, 47.0, 10000.0,
   *     19.0, 48.0, 10000.0,
   *     20.0, 48.0, 10000.0,
   *     20.0, 47.0, 10000.0,
   *     19.0, 47.0, 10000.0
   *   ])
   * });
   * const geometry = Cesium.WallGeometry.createGeometry(wall);
   */
  function WallGeometry(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const wallPositions = options.positions;
    const maximumHeights = options.maximumHeights;
    const minimumHeights = options.minimumHeights;

    //>>includeStart('debug', pragmas.debug);
    if (!defined(wallPositions)) {
      throw new DeveloperError("options.positions is required.");
    }
    if (
      defined(maximumHeights) &&
      maximumHeights.length !== wallPositions.length
    ) {
      throw new DeveloperError(
        "options.positions and options.maximumHeights must have the same length."
      );
    }
    if (
      defined(minimumHeights) &&
      minimumHeights.length !== wallPositions.length
    ) {
      throw new DeveloperError(
        "options.positions and options.minimumHeights must have the same length."
      );
    }
    //>>includeEnd('debug');

    const vertexFormat = defaultValue(options.vertexFormat, VertexFormat.DEFAULT);
    const granularity = defaultValue(
      options.granularity,
      CesiumMath.RADIANS_PER_DEGREE
    );
    const ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);

    this._positions = wallPositions;
    this._minimumHeights = minimumHeights;
    this._maximumHeights = maximumHeights;
    this._vertexFormat = VertexFormat.clone(vertexFormat);
    this._granularity = granularity;
    this._ellipsoid = Ellipsoid.clone(ellipsoid);
    this._workerName = "createWallGeometry";

    let numComponents = 1 + wallPositions.length * Cartesian3.packedLength + 2;
    if (defined(minimumHeights)) {
      numComponents += minimumHeights.length;
    }
    if (defined(maximumHeights)) {
      numComponents += maximumHeights.length;
    }

    /**
     * The number of elements used to pack the object into an array.
     * @type {Number}
     */
    this.packedLength =
      numComponents + Ellipsoid.packedLength + VertexFormat.packedLength + 1;
  }

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {WallGeometry} 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
   */
  WallGeometry.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(value)) {
      throw new DeveloperError("value is required");
    }
    if (!defined(array)) {
      throw new DeveloperError("array is required");
    }
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    let i;

    const positions = value._positions;
    let length = positions.length;
    array[startingIndex++] = length;

    for (i = 0; i < length; ++i, startingIndex += Cartesian3.packedLength) {
      Cartesian3.pack(positions[i], array, startingIndex);
    }

    const minimumHeights = value._minimumHeights;
    length = defined(minimumHeights) ? minimumHeights.length : 0;
    array[startingIndex++] = length;

    if (defined(minimumHeights)) {
      for (i = 0; i < length; ++i) {
        array[startingIndex++] = minimumHeights[i];
      }
    }

    const maximumHeights = value._maximumHeights;
    length = defined(maximumHeights) ? maximumHeights.length : 0;
    array[startingIndex++] = length;

    if (defined(maximumHeights)) {
      for (i = 0; i < length; ++i) {
        array[startingIndex++] = maximumHeights[i];
      }
    }

    Ellipsoid.pack(value._ellipsoid, array, startingIndex);
    startingIndex += Ellipsoid.packedLength;

    VertexFormat.pack(value._vertexFormat, array, startingIndex);
    startingIndex += VertexFormat.packedLength;

    array[startingIndex] = value._granularity;

    return array;
  };

  const scratchEllipsoid$2 = Ellipsoid.clone(Ellipsoid.UNIT_SPHERE);
  const scratchVertexFormat = new VertexFormat();
  const scratchOptions$1 = {
    positions: undefined,
    minimumHeights: undefined,
    maximumHeights: undefined,
    ellipsoid: scratchEllipsoid$2,
    vertexFormat: scratchVertexFormat,
    granularity: undefined,
  };

  /**
   * 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 {WallGeometry} [result] The object into which to store the result.
   * @returns {WallGeometry} The modified result parameter or a new WallGeometry instance if one was not provided.
   */
  WallGeometry.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(array)) {
      throw new DeveloperError("array is required");
    }
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    let i;

    let length = array[startingIndex++];
    const positions = new Array(length);

    for (i = 0; i < length; ++i, startingIndex += Cartesian3.packedLength) {
      positions[i] = Cartesian3.unpack(array, startingIndex);
    }

    length = array[startingIndex++];
    let minimumHeights;

    if (length > 0) {
      minimumHeights = new Array(length);
      for (i = 0; i < length; ++i) {
        minimumHeights[i] = array[startingIndex++];
      }
    }

    length = array[startingIndex++];
    let maximumHeights;

    if (length > 0) {
      maximumHeights = new Array(length);
      for (i = 0; i < length; ++i) {
        maximumHeights[i] = array[startingIndex++];
      }
    }

    const ellipsoid = Ellipsoid.unpack(array, startingIndex, scratchEllipsoid$2);
    startingIndex += Ellipsoid.packedLength;

    const vertexFormat = VertexFormat.unpack(
      array,
      startingIndex,
      scratchVertexFormat
    );
    startingIndex += VertexFormat.packedLength;

    const granularity = array[startingIndex];

    if (!defined(result)) {
      scratchOptions$1.positions = positions;
      scratchOptions$1.minimumHeights = minimumHeights;
      scratchOptions$1.maximumHeights = maximumHeights;
      scratchOptions$1.granularity = granularity;
      return new WallGeometry(scratchOptions$1);
    }

    result._positions = positions;
    result._minimumHeights = minimumHeights;
    result._maximumHeights = maximumHeights;
    result._ellipsoid = Ellipsoid.clone(ellipsoid, result._ellipsoid);
    result._vertexFormat = VertexFormat.clone(vertexFormat, result._vertexFormat);
    result._granularity = granularity;

    return result;
  };

  /**
   * A description of a wall, which is similar to a KML line string. A wall is defined by a series of points,
   * which extrude down to the ground. Optionally, they can extrude downwards to a specified height.
   *
   * @param {Object} options Object with the following properties:
   * @param {Cartesian3[]} options.positions An array of Cartesian objects, which are the points of the wall.
   * @param {Number} [options.maximumHeight] A constant that defines the maximum height of the
   *        wall at <code>positions</code>. If undefined, the height of each position in used.
   * @param {Number} [options.minimumHeight] A constant that defines the minimum height of the
   *        wall at <code>positions</code>. If undefined, the height at each position is 0.0.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid for coordinate manipulation
   * @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
   * @returns {WallGeometry}
   *
   *
   * @example
   * // create a wall that spans from 10000 meters to 20000 meters
   * const wall = Cesium.WallGeometry.fromConstantHeights({
   *   positions : Cesium.Cartesian3.fromDegreesArray([
   *     19.0, 47.0,
   *     19.0, 48.0,
   *     20.0, 48.0,
   *     20.0, 47.0,
   *     19.0, 47.0,
   *   ]),
   *   minimumHeight : 20000.0,
   *   maximumHeight : 10000.0
   * });
   * const geometry = Cesium.WallGeometry.createGeometry(wall);
   *
   * @see WallGeometry#createGeometry
   */
  WallGeometry.fromConstantHeights = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const positions = options.positions;

    //>>includeStart('debug', pragmas.debug);
    if (!defined(positions)) {
      throw new DeveloperError("options.positions is required.");
    }
    //>>includeEnd('debug');

    let minHeights;
    let maxHeights;

    const min = options.minimumHeight;
    const max = options.maximumHeight;

    const doMin = defined(min);
    const doMax = defined(max);
    if (doMin || doMax) {
      const length = positions.length;
      minHeights = doMin ? new Array(length) : undefined;
      maxHeights = doMax ? new Array(length) : undefined;

      for (let i = 0; i < length; ++i) {
        if (doMin) {
          minHeights[i] = min;
        }

        if (doMax) {
          maxHeights[i] = max;
        }
      }
    }

    const newOptions = {
      positions: positions,
      maximumHeights: maxHeights,
      minimumHeights: minHeights,
      ellipsoid: options.ellipsoid,
      vertexFormat: options.vertexFormat,
    };
    return new WallGeometry(newOptions);
  };

  /**
   * Computes the geometric representation of a wall, including its vertices, indices, and a bounding sphere.
   *
   * @param {WallGeometry} wallGeometry A description of the wall.
   * @returns {Geometry|undefined} The computed vertices and indices.
   */
  WallGeometry.createGeometry = function (wallGeometry) {
    const wallPositions = wallGeometry._positions;
    const minimumHeights = wallGeometry._minimumHeights;
    const maximumHeights = wallGeometry._maximumHeights;
    const vertexFormat = wallGeometry._vertexFormat;
    const granularity = wallGeometry._granularity;
    const ellipsoid = wallGeometry._ellipsoid;

    const pos = WallGeometryLibrary.computePositions(
      ellipsoid,
      wallPositions,
      maximumHeights,
      minimumHeights,
      granularity,
      true
    );
    if (!defined(pos)) {
      return;
    }

    const bottomPositions = pos.bottomPositions;
    const topPositions = pos.topPositions;
    const numCorners = pos.numCorners;

    let length = topPositions.length;
    let size = length * 2;

    const positions = vertexFormat.position ? new Float64Array(size) : undefined;
    const normals = vertexFormat.normal ? new Float32Array(size) : undefined;
    const tangents = vertexFormat.tangent ? new Float32Array(size) : undefined;
    const bitangents = vertexFormat.bitangent
      ? new Float32Array(size)
      : undefined;
    const textureCoordinates = vertexFormat.st
      ? new Float32Array((size / 3) * 2)
      : undefined;

    let positionIndex = 0;
    let normalIndex = 0;
    let bitangentIndex = 0;
    let tangentIndex = 0;
    let stIndex = 0;

    // add lower and upper points one after the other, lower
    // points being even and upper points being odd
    let normal = scratchNormal$1;
    let tangent = scratchTangent;
    let bitangent = scratchBitangent;
    let recomputeNormal = true;
    length /= 3;
    let i;
    let s = 0;
    const ds = 1 / (length - numCorners - 1);
    for (i = 0; i < length; ++i) {
      const i3 = i * 3;
      const topPosition = Cartesian3.fromArray(
        topPositions,
        i3,
        scratchCartesian3Position1$1
      );
      const bottomPosition = Cartesian3.fromArray(
        bottomPositions,
        i3,
        scratchCartesian3Position2$1
      );
      if (vertexFormat.position) {
        // insert the lower point
        positions[positionIndex++] = bottomPosition.x;
        positions[positionIndex++] = bottomPosition.y;
        positions[positionIndex++] = bottomPosition.z;

        // insert the upper point
        positions[positionIndex++] = topPosition.x;
        positions[positionIndex++] = topPosition.y;
        positions[positionIndex++] = topPosition.z;
      }

      if (vertexFormat.st) {
        textureCoordinates[stIndex++] = s;
        textureCoordinates[stIndex++] = 0.0;

        textureCoordinates[stIndex++] = s;
        textureCoordinates[stIndex++] = 1.0;
      }

      if (vertexFormat.normal || vertexFormat.tangent || vertexFormat.bitangent) {
        let nextTop = Cartesian3.clone(
          Cartesian3.ZERO,
          scratchCartesian3Position5
        );
        const groundPosition = Cartesian3.subtract(
          topPosition,
          ellipsoid.geodeticSurfaceNormal(
            topPosition,
            scratchCartesian3Position2$1
          ),
          scratchCartesian3Position2$1
        );
        if (i + 1 < length) {
          nextTop = Cartesian3.fromArray(
            topPositions,
            i3 + 3,
            scratchCartesian3Position5
          );
        }

        if (recomputeNormal) {
          const scalednextPosition = Cartesian3.subtract(
            nextTop,
            topPosition,
            scratchCartesian3Position4
          );
          const scaledGroundPosition = Cartesian3.subtract(
            groundPosition,
            topPosition,
            scratchCartesian3Position1$1
          );
          normal = Cartesian3.normalize(
            Cartesian3.cross(scaledGroundPosition, scalednextPosition, normal),
            normal
          );
          recomputeNormal = false;
        }

        if (
          Cartesian3.equalsEpsilon(topPosition, nextTop, CesiumMath.EPSILON10)
        ) {
          recomputeNormal = true;
        } else {
          s += ds;
          if (vertexFormat.tangent) {
            tangent = Cartesian3.normalize(
              Cartesian3.subtract(nextTop, topPosition, tangent),
              tangent
            );
          }
          if (vertexFormat.bitangent) {
            bitangent = Cartesian3.normalize(
              Cartesian3.cross(normal, tangent, bitangent),
              bitangent
            );
          }
        }

        if (vertexFormat.normal) {
          normals[normalIndex++] = normal.x;
          normals[normalIndex++] = normal.y;
          normals[normalIndex++] = normal.z;

          normals[normalIndex++] = normal.x;
          normals[normalIndex++] = normal.y;
          normals[normalIndex++] = normal.z;
        }

        if (vertexFormat.tangent) {
          tangents[tangentIndex++] = tangent.x;
          tangents[tangentIndex++] = tangent.y;
          tangents[tangentIndex++] = tangent.z;

          tangents[tangentIndex++] = tangent.x;
          tangents[tangentIndex++] = tangent.y;
          tangents[tangentIndex++] = tangent.z;
        }

        if (vertexFormat.bitangent) {
          bitangents[bitangentIndex++] = bitangent.x;
          bitangents[bitangentIndex++] = bitangent.y;
          bitangents[bitangentIndex++] = bitangent.z;

          bitangents[bitangentIndex++] = bitangent.x;
          bitangents[bitangentIndex++] = bitangent.y;
          bitangents[bitangentIndex++] = bitangent.z;
        }
      }
    }

    const attributes = new GeometryAttributes();

    if (vertexFormat.position) {
      attributes.position = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.DOUBLE,
        componentsPerAttribute: 3,
        values: positions,
      });
    }

    if (vertexFormat.normal) {
      attributes.normal = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 3,
        values: normals,
      });
    }

    if (vertexFormat.tangent) {
      attributes.tangent = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 3,
        values: tangents,
      });
    }

    if (vertexFormat.bitangent) {
      attributes.bitangent = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 3,
        values: bitangents,
      });
    }

    if (vertexFormat.st) {
      attributes.st = new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 2,
        values: textureCoordinates,
      });
    }

    // prepare the side walls, two triangles for each wall
    //
    //    A (i+1)  B (i+3) E
    //    +--------+-------+
    //    |      / |      /|    triangles:  A C B
    //    |     /  |     / |                B C D
    //    |    /   |    /  |
    //    |   /    |   /   |
    //    |  /     |  /    |
    //    | /      | /     |
    //    +--------+-------+
    //    C (i)    D (i+2) F
    //

    const numVertices = size / 3;
    size -= 6 * (numCorners + 1);
    const indices = IndexDatatype$1.createTypedArray(numVertices, size);

    let edgeIndex = 0;
    for (i = 0; i < numVertices - 2; i += 2) {
      const LL = i;
      const LR = i + 2;
      const pl = Cartesian3.fromArray(
        positions,
        LL * 3,
        scratchCartesian3Position1$1
      );
      const pr = Cartesian3.fromArray(
        positions,
        LR * 3,
        scratchCartesian3Position2$1
      );
      if (Cartesian3.equalsEpsilon(pl, pr, CesiumMath.EPSILON10)) {
        continue;
      }
      const UL = i + 1;
      const UR = i + 3;

      indices[edgeIndex++] = UL;
      indices[edgeIndex++] = LL;
      indices[edgeIndex++] = UR;
      indices[edgeIndex++] = UR;
      indices[edgeIndex++] = LL;
      indices[edgeIndex++] = LR;
    }

    return new Geometry({
      attributes: attributes,
      indices: indices,
      primitiveType: PrimitiveType$1.TRIANGLES,
      boundingSphere: new BoundingSphere.fromVertices(positions),
    });
  };

  const scratchCartesian3Position1 = new Cartesian3();
  const scratchCartesian3Position2 = new Cartesian3();

  /**
   * A description of a wall outline. A wall is defined by a series of points,
   * which extrude down to the ground. Optionally, they can extrude downwards to a specified height.
   *
   * @alias WallOutlineGeometry
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Cartesian3[]} options.positions An array of Cartesian objects, which are the points of the wall.
   * @param {Number} [options.granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
   * @param {Number[]} [options.maximumHeights] An array parallel to <code>positions</code> that give the maximum height of the
   *        wall at <code>positions</code>. If undefined, the height of each position in used.
   * @param {Number[]} [options.minimumHeights] An array parallel to <code>positions</code> that give the minimum height of the
   *        wall at <code>positions</code>. If undefined, the height at each position is 0.0.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid for coordinate manipulation
   *
   * @exception {DeveloperError} positions length must be greater than or equal to 2.
   * @exception {DeveloperError} positions and maximumHeights must have the same length.
   * @exception {DeveloperError} positions and minimumHeights must have the same length.
   *
   * @see WallGeometry#createGeometry
   * @see WallGeometry#fromConstantHeight
   *
   * @example
   * // create a wall outline that spans from ground level to 10000 meters
   * const wall = new Cesium.WallOutlineGeometry({
   *   positions : Cesium.Cartesian3.fromDegreesArrayHeights([
   *     19.0, 47.0, 10000.0,
   *     19.0, 48.0, 10000.0,
   *     20.0, 48.0, 10000.0,
   *     20.0, 47.0, 10000.0,
   *     19.0, 47.0, 10000.0
   *   ])
   * });
   * const geometry = Cesium.WallOutlineGeometry.createGeometry(wall);
   */
  function WallOutlineGeometry(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const wallPositions = options.positions;
    const maximumHeights = options.maximumHeights;
    const minimumHeights = options.minimumHeights;

    //>>includeStart('debug', pragmas.debug);
    if (!defined(wallPositions)) {
      throw new DeveloperError("options.positions is required.");
    }
    if (
      defined(maximumHeights) &&
      maximumHeights.length !== wallPositions.length
    ) {
      throw new DeveloperError(
        "options.positions and options.maximumHeights must have the same length."
      );
    }
    if (
      defined(minimumHeights) &&
      minimumHeights.length !== wallPositions.length
    ) {
      throw new DeveloperError(
        "options.positions and options.minimumHeights must have the same length."
      );
    }
    //>>includeEnd('debug');

    const granularity = defaultValue(
      options.granularity,
      CesiumMath.RADIANS_PER_DEGREE
    );
    const ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);

    this._positions = wallPositions;
    this._minimumHeights = minimumHeights;
    this._maximumHeights = maximumHeights;
    this._granularity = granularity;
    this._ellipsoid = Ellipsoid.clone(ellipsoid);
    this._workerName = "createWallOutlineGeometry";

    let numComponents = 1 + wallPositions.length * Cartesian3.packedLength + 2;
    if (defined(minimumHeights)) {
      numComponents += minimumHeights.length;
    }
    if (defined(maximumHeights)) {
      numComponents += maximumHeights.length;
    }

    /**
     * The number of elements used to pack the object into an array.
     * @type {Number}
     */
    this.packedLength = numComponents + Ellipsoid.packedLength + 1;
  }

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {WallOutlineGeometry} 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
   */
  WallOutlineGeometry.pack = function (value, array, startingIndex) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(value)) {
      throw new DeveloperError("value is required");
    }
    if (!defined(array)) {
      throw new DeveloperError("array is required");
    }
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    let i;

    const positions = value._positions;
    let length = positions.length;
    array[startingIndex++] = length;

    for (i = 0; i < length; ++i, startingIndex += Cartesian3.packedLength) {
      Cartesian3.pack(positions[i], array, startingIndex);
    }

    const minimumHeights = value._minimumHeights;
    length = defined(minimumHeights) ? minimumHeights.length : 0;
    array[startingIndex++] = length;

    if (defined(minimumHeights)) {
      for (i = 0; i < length; ++i) {
        array[startingIndex++] = minimumHeights[i];
      }
    }

    const maximumHeights = value._maximumHeights;
    length = defined(maximumHeights) ? maximumHeights.length : 0;
    array[startingIndex++] = length;

    if (defined(maximumHeights)) {
      for (i = 0; i < length; ++i) {
        array[startingIndex++] = maximumHeights[i];
      }
    }

    Ellipsoid.pack(value._ellipsoid, array, startingIndex);
    startingIndex += Ellipsoid.packedLength;

    array[startingIndex] = value._granularity;

    return array;
  };

  const scratchEllipsoid$1 = Ellipsoid.clone(Ellipsoid.UNIT_SPHERE);
  const scratchOptions = {
    positions: undefined,
    minimumHeights: undefined,
    maximumHeights: undefined,
    ellipsoid: scratchEllipsoid$1,
    granularity: undefined,
  };

  /**
   * 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 {WallOutlineGeometry} [result] The object into which to store the result.
   * @returns {WallOutlineGeometry} The modified result parameter or a new WallOutlineGeometry instance if one was not provided.
   */
  WallOutlineGeometry.unpack = function (array, startingIndex, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(array)) {
      throw new DeveloperError("array is required");
    }
    //>>includeEnd('debug');

    startingIndex = defaultValue(startingIndex, 0);

    let i;

    let length = array[startingIndex++];
    const positions = new Array(length);

    for (i = 0; i < length; ++i, startingIndex += Cartesian3.packedLength) {
      positions[i] = Cartesian3.unpack(array, startingIndex);
    }

    length = array[startingIndex++];
    let minimumHeights;

    if (length > 0) {
      minimumHeights = new Array(length);
      for (i = 0; i < length; ++i) {
        minimumHeights[i] = array[startingIndex++];
      }
    }

    length = array[startingIndex++];
    let maximumHeights;

    if (length > 0) {
      maximumHeights = new Array(length);
      for (i = 0; i < length; ++i) {
        maximumHeights[i] = array[startingIndex++];
      }
    }

    const ellipsoid = Ellipsoid.unpack(array, startingIndex, scratchEllipsoid$1);
    startingIndex += Ellipsoid.packedLength;

    const granularity = array[startingIndex];

    if (!defined(result)) {
      scratchOptions.positions = positions;
      scratchOptions.minimumHeights = minimumHeights;
      scratchOptions.maximumHeights = maximumHeights;
      scratchOptions.granularity = granularity;
      return new WallOutlineGeometry(scratchOptions);
    }

    result._positions = positions;
    result._minimumHeights = minimumHeights;
    result._maximumHeights = maximumHeights;
    result._ellipsoid = Ellipsoid.clone(ellipsoid, result._ellipsoid);
    result._granularity = granularity;

    return result;
  };

  /**
   * A description of a walloutline. A wall is defined by a series of points,
   * which extrude down to the ground. Optionally, they can extrude downwards to a specified height.
   *
   * @param {Object} options Object with the following properties:
   * @param {Cartesian3[]} options.positions An array of Cartesian objects, which are the points of the wall.
   * @param {Number} [options.maximumHeight] A constant that defines the maximum height of the
   *        wall at <code>positions</code>. If undefined, the height of each position in used.
   * @param {Number} [options.minimumHeight] A constant that defines the minimum height of the
   *        wall at <code>positions</code>. If undefined, the height at each position is 0.0.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid for coordinate manipulation
   * @returns {WallOutlineGeometry}
   *
   *
   * @example
   * // create a wall that spans from 10000 meters to 20000 meters
   * const wall = Cesium.WallOutlineGeometry.fromConstantHeights({
   *   positions : Cesium.Cartesian3.fromDegreesArray([
   *     19.0, 47.0,
   *     19.0, 48.0,
   *     20.0, 48.0,
   *     20.0, 47.0,
   *     19.0, 47.0,
   *   ]),
   *   minimumHeight : 20000.0,
   *   maximumHeight : 10000.0
   * });
   * const geometry = Cesium.WallOutlineGeometry.createGeometry(wall);
   *
   * @see WallOutlineGeometry#createGeometry
   */
  WallOutlineGeometry.fromConstantHeights = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const positions = options.positions;

    //>>includeStart('debug', pragmas.debug);
    if (!defined(positions)) {
      throw new DeveloperError("options.positions is required.");
    }
    //>>includeEnd('debug');

    let minHeights;
    let maxHeights;

    const min = options.minimumHeight;
    const max = options.maximumHeight;

    const doMin = defined(min);
    const doMax = defined(max);
    if (doMin || doMax) {
      const length = positions.length;
      minHeights = doMin ? new Array(length) : undefined;
      maxHeights = doMax ? new Array(length) : undefined;

      for (let i = 0; i < length; ++i) {
        if (doMin) {
          minHeights[i] = min;
        }

        if (doMax) {
          maxHeights[i] = max;
        }
      }
    }

    const newOptions = {
      positions: positions,
      maximumHeights: maxHeights,
      minimumHeights: minHeights,
      ellipsoid: options.ellipsoid,
    };
    return new WallOutlineGeometry(newOptions);
  };

  /**
   * Computes the geometric representation of a wall outline, including its vertices, indices, and a bounding sphere.
   *
   * @param {WallOutlineGeometry} wallGeometry A description of the wall outline.
   * @returns {Geometry|undefined} The computed vertices and indices.
   */
  WallOutlineGeometry.createGeometry = function (wallGeometry) {
    const wallPositions = wallGeometry._positions;
    const minimumHeights = wallGeometry._minimumHeights;
    const maximumHeights = wallGeometry._maximumHeights;
    const granularity = wallGeometry._granularity;
    const ellipsoid = wallGeometry._ellipsoid;

    const pos = WallGeometryLibrary.computePositions(
      ellipsoid,
      wallPositions,
      maximumHeights,
      minimumHeights,
      granularity,
      false
    );
    if (!defined(pos)) {
      return;
    }

    const bottomPositions = pos.bottomPositions;
    const topPositions = pos.topPositions;

    let length = topPositions.length;
    let size = length * 2;

    const positions = new Float64Array(size);
    let positionIndex = 0;

    // add lower and upper points one after the other, lower
    // points being even and upper points being odd
    length /= 3;
    let i;
    for (i = 0; i < length; ++i) {
      const i3 = i * 3;
      const topPosition = Cartesian3.fromArray(
        topPositions,
        i3,
        scratchCartesian3Position1
      );
      const bottomPosition = Cartesian3.fromArray(
        bottomPositions,
        i3,
        scratchCartesian3Position2
      );

      // insert the lower point
      positions[positionIndex++] = bottomPosition.x;
      positions[positionIndex++] = bottomPosition.y;
      positions[positionIndex++] = bottomPosition.z;

      // insert the upper point
      positions[positionIndex++] = topPosition.x;
      positions[positionIndex++] = topPosition.y;
      positions[positionIndex++] = topPosition.z;
    }

    const attributes = new GeometryAttributes({
      position: new GeometryAttribute({
        componentDatatype: ComponentDatatype$1.DOUBLE,
        componentsPerAttribute: 3,
        values: positions,
      }),
    });

    const numVertices = size / 3;
    size = 2 * numVertices - 4 + numVertices;
    const indices = IndexDatatype$1.createTypedArray(numVertices, size);

    let edgeIndex = 0;
    for (i = 0; i < numVertices - 2; i += 2) {
      const LL = i;
      const LR = i + 2;
      const pl = Cartesian3.fromArray(
        positions,
        LL * 3,
        scratchCartesian3Position1
      );
      const pr = Cartesian3.fromArray(
        positions,
        LR * 3,
        scratchCartesian3Position2
      );
      if (Cartesian3.equalsEpsilon(pl, pr, CesiumMath.EPSILON10)) {
        continue;
      }
      const UL = i + 1;
      const UR = i + 3;

      indices[edgeIndex++] = UL;
      indices[edgeIndex++] = LL;
      indices[edgeIndex++] = UL;
      indices[edgeIndex++] = UR;
      indices[edgeIndex++] = LL;
      indices[edgeIndex++] = LR;
    }

    indices[edgeIndex++] = numVertices - 2;
    indices[edgeIndex++] = numVertices - 1;

    return new Geometry({
      attributes: attributes,
      indices: indices,
      primitiveType: PrimitiveType$1.LINES,
      boundingSphere: new BoundingSphere.fromVertices(positions),
    });
  };

  /**
   * Functions for generating indices for model wireframes. The indices are
   * outputted as typed arrays, which can then be put into buffers for rendering.
   *
   * @namespace WireframeIndexGenerator
   * @private
   */
  const WireframeIndexGenerator = {};

  function createWireframeFromTriangles(vertexCount) {
    const wireframeIndices = IndexDatatype$1.createTypedArray(
      vertexCount,
      vertexCount * 2
    );
    const length = vertexCount;
    let index = 0;
    for (let i = 0; i < length; i += 3) {
      wireframeIndices[index++] = i;
      wireframeIndices[index++] = i + 1;
      wireframeIndices[index++] = i + 1;
      wireframeIndices[index++] = i + 2;
      wireframeIndices[index++] = i + 2;
      wireframeIndices[index++] = i;
    }

    return wireframeIndices;
  }

  function createWireframeFromTriangleIndices(vertexCount, originalIndices) {
    const originalIndicesCount = originalIndices.length;
    const wireframeIndices = IndexDatatype$1.createTypedArray(
      vertexCount,
      originalIndicesCount * 2
    );
    let index = 0;
    for (let i = 0; i < originalIndicesCount; i += 3) {
      const point0 = originalIndices[i];
      const point1 = originalIndices[i + 1];
      const point2 = originalIndices[i + 2];

      wireframeIndices[index++] = point0;
      wireframeIndices[index++] = point1;
      wireframeIndices[index++] = point1;
      wireframeIndices[index++] = point2;
      wireframeIndices[index++] = point2;
      wireframeIndices[index++] = point0;
    }

    return wireframeIndices;
  }

  function createWireframeFromTriangleStrip(vertexCount) {
    const numberOfTriangles = vertexCount - 2;
    const wireframeIndicesCount = 2 + numberOfTriangles * 4;
    const wireframeIndices = IndexDatatype$1.createTypedArray(
      vertexCount,
      wireframeIndicesCount
    );
    let index = 0;

    // Handle the first edge
    wireframeIndices[index++] = 0;
    wireframeIndices[index++] = 1;

    // Add two edges for every triangle in the strip
    for (let i = 0; i < numberOfTriangles; i++) {
      wireframeIndices[index++] = i + 1;
      wireframeIndices[index++] = i + 2;
      wireframeIndices[index++] = i + 2;
      wireframeIndices[index++] = i;
    }

    return wireframeIndices;
  }

  function createWireframeFromTriangleStripIndices(vertexCount, originalIndices) {
    const originalIndicesCount = originalIndices.length;
    const numberOfTriangles = originalIndicesCount - 2;
    const wireframeIndicesCount = 2 + numberOfTriangles * 4;
    const wireframeIndices = IndexDatatype$1.createTypedArray(
      vertexCount,
      wireframeIndicesCount
    );
    let index = 0;

    // Handle the first edge
    wireframeIndices[index++] = originalIndices[0];
    wireframeIndices[index++] = originalIndices[1];

    // Add two edges for every triangle in the strip
    for (let i = 0; i < numberOfTriangles; i++) {
      const point0 = originalIndices[i];
      const point1 = originalIndices[i + 1];
      const point2 = originalIndices[i + 2];

      wireframeIndices[index++] = point1;
      wireframeIndices[index++] = point2;
      wireframeIndices[index++] = point2;
      wireframeIndices[index++] = point0;
    }

    return wireframeIndices;
  }

  function createWireframeFromTriangleFan(vertexCount) {
    const numberOfTriangles = vertexCount - 2;
    const wireframeIndicesCount = 2 + numberOfTriangles * 4;
    const wireframeIndices = IndexDatatype$1.createTypedArray(
      vertexCount,
      wireframeIndicesCount
    );
    let index = 0;

    // Handle the first edge
    wireframeIndices[index++] = 0;
    wireframeIndices[index++] = 1;

    // Add two edges for every triangle in the fan
    for (let i = 0; i < numberOfTriangles; i++) {
      wireframeIndices[index++] = i + 1;
      wireframeIndices[index++] = i + 2;
      wireframeIndices[index++] = i + 2;
      wireframeIndices[index++] = 0;
    }

    return wireframeIndices;
  }

  function createWireframeFromTriangleFanIndices(vertexCount, originalIndices) {
    const originalIndicesCount = originalIndices.length;
    const numberOfTriangles = originalIndicesCount - 2;
    const wireframeIndicesCount = 2 + numberOfTriangles * 4;
    const wireframeIndices = IndexDatatype$1.createTypedArray(
      vertexCount,
      wireframeIndicesCount
    );
    let index = 0;

    // Handle the first edge
    const firstPoint = originalIndices[0];
    wireframeIndices[index++] = firstPoint;
    wireframeIndices[index++] = originalIndices[1];

    // Add two edges for every triangle in the fan
    for (let i = 0; i < numberOfTriangles; i++) {
      const point1 = originalIndices[i + 1];
      const point2 = originalIndices[i + 2];

      wireframeIndices[index++] = point1;
      wireframeIndices[index++] = point2;
      wireframeIndices[index++] = point2;
      wireframeIndices[index++] = firstPoint;
    }

    return wireframeIndices;
  }

  /**
   * Generates a wireframe index buffer for a primitive, either by reindexing the existing indices
   * or creating them from scratch if the model had none.
   *
   * @param {PrimitiveType} primitiveType The primitive type.
   * @param {Number} vertexCount The number of vertices in the primitive.
   * @param {Uint8Array|Uint16Array|Uint32Array} [originalIndices] A typed array containing the original indices of the primitive.
   *
   * @return {Uint16Array|Uint32Array} A typed array with the wireframe indices, or undefined if the primitive type does not use triangles.
   *
   * @private
   */
  WireframeIndexGenerator.createWireframeIndices = function (
    primitiveType,
    vertexCount,
    originalIndices
  ) {
    const hasOriginalIndices = defined(originalIndices);
    if (primitiveType === PrimitiveType$1.TRIANGLES) {
      return hasOriginalIndices
        ? createWireframeFromTriangleIndices(vertexCount, originalIndices)
        : createWireframeFromTriangles(vertexCount);
    }

    if (primitiveType === PrimitiveType$1.TRIANGLE_STRIP) {
      return hasOriginalIndices
        ? createWireframeFromTriangleStripIndices(vertexCount, originalIndices)
        : createWireframeFromTriangleStrip(vertexCount);
    }

    if (primitiveType === PrimitiveType$1.TRIANGLE_FAN) {
      return hasOriginalIndices
        ? createWireframeFromTriangleFanIndices(vertexCount, originalIndices)
        : createWireframeFromTriangleFan(vertexCount);
    }

    return undefined;
  };

  /**
   * Gets the number of indices in the wireframe index buffer of a primitive type.
   *
   * @param {PrimitiveType} primitiveType The primitive type.
   * @param {Number} originalCount The original number of vertices or indices in the primitive.
   * @return {Number} The number of indices in the primitive's wireframe.
   *
   * @private
   */
  WireframeIndexGenerator.getWireframeIndicesCount = function (
    primitiveType,
    originalCount
  ) {
    // For TRIANGLES, the wireframe takes every triangle (i.e. three of the original
    // indices) and turns it into lines. Each triangle has three lines, and each line
    // requires two indices, so the final count is twice the original.
    if (primitiveType === PrimitiveType$1.TRIANGLES) {
      return originalCount * 2;
    }

    // For TRIANGLE_STRIP and TRIANGLE_FAN, the number of triangles in the primitive
    // is equal to the total number of vertices minus two. This is because after the
    // first edge is specified by the first two indices, every point afterwards
    // contributes two more edges with two of the previous points, forming a new triangle.
    // Each of these edges requires two indices, so each triangle in the primitive
    // results in four indices in addition to the first two.
    if (
      primitiveType === PrimitiveType$1.TRIANGLE_STRIP ||
      primitiveType === PrimitiveType$1.TRIANGLE_FAN
    ) {
      const numberOfTriangles = originalCount - 2;
      return 2 + numberOfTriangles * 4;
    }

    return originalCount;
  };

  let implementation$1;
  if (typeof cancelAnimationFrame !== "undefined") {
    implementation$1 = cancelAnimationFrame;
  }

  (function () {
    // look for vendor prefixed function
    if (!defined(implementation$1) && typeof window !== "undefined") {
      const vendors = ["webkit", "moz", "ms", "o"];
      let i = 0;
      const len = vendors.length;
      while (i < len && !defined(implementation$1)) {
        implementation$1 = window[`${vendors[i]}CancelAnimationFrame`];
        if (!defined(implementation$1)) {
          implementation$1 = window[`${vendors[i]}CancelRequestAnimationFrame`];
        }
        ++i;
      }
    }

    // otherwise, assume requestAnimationFrame is based on setTimeout, so use clearTimeout
    if (!defined(implementation$1)) {
      implementation$1 = clearTimeout;
    }
  })();

  /**
   * A browser-independent function to cancel an animation frame requested using {@link requestAnimationFrame}.
   *
   * @function cancelAnimationFrame
   *
   * @param {Number} requestID The value returned by {@link requestAnimationFrame}.
   *
   * @see {@link http://www.w3.org/TR/animation-timing/#the-WindowAnimationTiming-interface|The WindowAnimationTiming interface}
   */
  function cancelAnimationFramePolyfill(requestID) {
    // we need this extra wrapper function because the native cancelAnimationFrame
    // functions must be invoked on the global scope (window), which is not the case
    // if invoked as Cesium.cancelAnimationFrame(requestID)
    implementation$1(requestID);
  }

  /**
   * Creates a Globally unique identifier (GUID) string.  A GUID is 128 bits long, and can guarantee uniqueness across space and time.
   *
   * @function
   *
   * @returns {String}
   *
   *
   * @example
   * this.guid = Cesium.createGuid();
   *
   * @see {@link http://www.ietf.org/rfc/rfc4122.txt|RFC 4122 A Universally Unique IDentifier (UUID) URN Namespace}
   */
  function createGuid() {
    // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
    return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
      const r = (Math.random() * 16) | 0;
      const v = c === "x" ? r : (r & 0x3) | 0x8;
      return v.toString(16);
    });
  }

  /**
   * Creates a {@link CesiumTerrainProvider} instance for the {@link https://cesium.com/content/#cesium-world-terrain|Cesium World Terrain}.
   *
   * @function
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Boolean} [options.requestVertexNormals=false] Flag that indicates if the client should request additional lighting information from the server if available.
   * @param {Boolean} [options.requestWaterMask=false] Flag that indicates if the client should request per tile water masks from the server if available.
   * @returns {CesiumTerrainProvider}
   *
   * @see Ion
   *
   * @example
   * // Create Cesium World Terrain with default settings
   * const viewer = new Cesium.Viewer('cesiumContainer', {
   *     terrainProvider : Cesium.createWorldTerrain();
   * });
   *
   * @example
   * // Create Cesium World Terrain with water and normals.
   * const viewer1 = new Cesium.Viewer('cesiumContainer', {
   *     terrainProvider : Cesium.createWorldTerrain({
   *         requestWaterMask : true,
   *         requestVertexNormals : true
   *     });
   * });
   *
   */
  function createWorldTerrain(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    return new CesiumTerrainProvider({
      url: IonResource.fromAssetId(1),
      requestVertexNormals: defaultValue(options.requestVertexNormals, false),
      requestWaterMask: defaultValue(options.requestWaterMask, false),
    });
  }

  const compressedMagic = 0x7468dead;
  const compressedMagicSwap = 0xadde6874;

  /**
   * Decodes data that is received from the Google Earth Enterprise server.
   *
   * @param {ArrayBuffer} key The key used during decoding.
   * @param {ArrayBuffer} data The data to be decoded.
   *
   * @private
   */
  function decodeGoogleEarthEnterpriseData(key, data) {
    if (decodeGoogleEarthEnterpriseData.passThroughDataForTesting) {
      return data;
    }

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("key", key);
    Check.typeOf.object("data", data);
    //>>includeEnd('debug');

    const keyLength = key.byteLength;
    if (keyLength === 0 || keyLength % 4 !== 0) {
      throw new RuntimeError(
        "The length of key must be greater than 0 and a multiple of 4."
      );
    }

    const dataView = new DataView(data);
    const magic = dataView.getUint32(0, true);
    if (magic === compressedMagic || magic === compressedMagicSwap) {
      // Occasionally packets don't come back encoded, so just return
      return data;
    }

    const keyView = new DataView(key);

    let dp = 0;
    const dpend = data.byteLength;
    const dpend64 = dpend - (dpend % 8);
    const kpend = keyLength;
    let kp;
    let off = 8;

    // This algorithm is intentionally asymmetric to make it more difficult to
    // guess. Security through obscurity. :-(

    // while we have a full uint64 (8 bytes) left to do
    // assumes buffer is 64bit aligned (or processor doesn't care)
    while (dp < dpend64) {
      // rotate the key each time through by using the offets 16,0,8,16,0,8,...
      off = (off + 8) % 24;
      kp = off;

      // run through one key length xor'ing one uint64 at a time
      // then drop out to rotate the key for the next bit
      while (dp < dpend64 && kp < kpend) {
        dataView.setUint32(
          dp,
          dataView.getUint32(dp, true) ^ keyView.getUint32(kp, true),
          true
        );
        dataView.setUint32(
          dp + 4,
          dataView.getUint32(dp + 4, true) ^ keyView.getUint32(kp + 4, true),
          true
        );
        dp += 8;
        kp += 24;
      }
    }

    // now the remaining 1 to 7 bytes
    if (dp < dpend) {
      if (kp >= kpend) {
        // rotate the key one last time (if necessary)
        off = (off + 8) % 24;
        kp = off;
      }

      while (dp < dpend) {
        dataView.setUint8(dp, dataView.getUint8(dp) ^ keyView.getUint8(kp));
        dp++;
        kp++;
      }
    }
  }

  decodeGoogleEarthEnterpriseData.passThroughDataForTesting = false;

  const maxShort = 32767;

  const scratchBVCartographic$1 = new Cartographic();
  const scratchEncodedPosition = new Cartesian3();

  function decodeVectorPolylinePositions(
    positions,
    rectangle,
    minimumHeight,
    maximumHeight,
    ellipsoid
  ) {
    const positionsLength = positions.length / 3;
    const uBuffer = positions.subarray(0, positionsLength);
    const vBuffer = positions.subarray(positionsLength, 2 * positionsLength);
    const heightBuffer = positions.subarray(
      2 * positionsLength,
      3 * positionsLength
    );
    AttributeCompression.zigZagDeltaDecode(uBuffer, vBuffer, heightBuffer);

    const decoded = new Float64Array(positions.length);
    for (let i = 0; i < positionsLength; ++i) {
      const u = uBuffer[i];
      const v = vBuffer[i];
      const h = heightBuffer[i];

      const lon = CesiumMath.lerp(rectangle.west, rectangle.east, u / maxShort);
      const lat = CesiumMath.lerp(rectangle.south, rectangle.north, v / maxShort);
      const alt = CesiumMath.lerp(minimumHeight, maximumHeight, h / maxShort);

      const cartographic = Cartographic.fromRadians(
        lon,
        lat,
        alt,
        scratchBVCartographic$1
      );
      const decodedPosition = ellipsoid.cartographicToCartesian(
        cartographic,
        scratchEncodedPosition
      );
      Cartesian3.pack(decodedPosition, decoded, i * 3);
    }
    return decoded;
  }

  /**
   * Logs a deprecation message to the console.  Use this function instead of
   * <code>console.log</code> directly since this does not log duplicate messages
   * unless it is called from multiple workers.
   *
   * @function deprecationWarning
   *
   * @param {String} identifier The unique identifier for this deprecated API.
   * @param {String} message The message to log to the console.
   *
   * @example
   * // Deprecated function or class
   * function Foo() {
   *    deprecationWarning('Foo', 'Foo was deprecated in Cesium 1.01.  It will be removed in 1.03.  Use newFoo instead.');
   *    // ...
   * }
   *
   * // Deprecated function
   * Bar.prototype.func = function() {
   *    deprecationWarning('Bar.func', 'Bar.func() was deprecated in Cesium 1.01.  It will be removed in 1.03.  Use Bar.newFunc() instead.');
   *    // ...
   * };
   *
   * // Deprecated property
   * Object.defineProperties(Bar.prototype, {
   *     prop : {
   *         get : function() {
   *             deprecationWarning('Bar.prop', 'Bar.prop was deprecated in Cesium 1.01.  It will be removed in 1.03.  Use Bar.newProp instead.');
   *             // ...
   *         },
   *         set : function(value) {
   *             deprecationWarning('Bar.prop', 'Bar.prop was deprecated in Cesium 1.01.  It will be removed in 1.03.  Use Bar.newProp instead.');
   *             // ...
   *         }
   *     }
   * });
   *
   * @private
   */
  function deprecationWarning(identifier, message) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(identifier) || !defined(message)) {
      throw new DeveloperError("identifier and message are required.");
    }
    //>>includeEnd('debug');

    oneTimeWarning(identifier, message);
  }

  /**
   * Given a URI, returns the last segment of the URI, removing any path or query information.
   * @function getFilenameFromUri
   *
   * @param {String} uri The Uri.
   * @returns {String} The last segment of the Uri.
   *
   * @example
   * //fileName will be"simple.czml";
   * const fileName = Cesium.getFilenameFromUri('/Gallery/simple.czml?value=true&example=false');
   */
  function getFilenameFromUri(uri) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(uri)) {
      throw new DeveloperError("uri is required.");
    }
    //>>includeEnd('debug');

    const uriObject = new URI(uri);
    uriObject.normalize();
    let path = uriObject.path();
    const index = path.lastIndexOf("/");
    if (index !== -1) {
      path = path.substr(index + 1);
    }
    return path;
  }

  /**
   * Constructs an image from a TypedArray of pixel values
   *
   * @param {Uint8Array} typedArray The array of pixel values
   * @param {Number} width The width of the image to create
   * @param {Number} height The height of the image to create
   * @returns {HTMLCanvasElement} A new canvas containing the constructed image
   *
   * @private
   */
  function getImageFromTypedArray(typedArray, width, height) {
    // Input typedArray is Uint8Array, ImageData needs Uint8ClampedArray
    // To avoid copying, make a new DataView of the same buffer
    const dataArray = new Uint8ClampedArray(typedArray.buffer);
    const imageData = new ImageData(dataArray, width, height);

    const canvas = document.createElement("canvas");
    canvas.width = width;
    canvas.height = height;
    canvas.getContext("2d").putImageData(imageData, 0, 0);

    return canvas;
  }

  /**
   * @private
   */
  function getMagic(uint8Array, byteOffset) {
    byteOffset = defaultValue(byteOffset, 0);
    return getStringFromTypedArray(
      uint8Array,
      byteOffset,
      Math.min(4, uint8Array.length)
    );
  }

  /**
   * @private
   */
  function loadImageFromTypedArray(options) {
    const uint8Array = options.uint8Array;
    const format = options.format;
    const request = options.request;
    const flipY = defaultValue(options.flipY, false);
    const skipColorSpaceConversion = defaultValue(
      options.skipColorSpaceConversion,
      false
    );
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("uint8Array", uint8Array);
    Check.typeOf.string("format", format);
    //>>includeEnd('debug');

    const blob = new Blob([uint8Array], {
      type: format,
    });

    let blobUrl;
    return Resource.supportsImageBitmapOptions()
      .then(function (result) {
        if (result) {
          return Promise.resolve(
            Resource.createImageBitmapFromBlob(blob, {
              flipY: flipY,
              premultiplyAlpha: false,
              skipColorSpaceConversion: skipColorSpaceConversion,
            })
          );
        }

        blobUrl = window.URL.createObjectURL(blob);
        const resource = new Resource({
          url: blobUrl,
          request: request,
        });

        return resource.fetchImage({
          flipY: flipY,
          skipColorSpaceConversion: skipColorSpaceConversion,
        });
      })
      .then(function (result) {
        if (defined(blobUrl)) {
          window.URL.revokeObjectURL(blobUrl);
        }
        return result;
      })
      .catch(function (error) {
        if (defined(blobUrl)) {
          window.URL.revokeObjectURL(blobUrl);
        }
        return Promise.reject(error);
      });
  }

  /**
   * Stores the supported formats that KTX2 can transcode to. Called during context creation.
   *
   * @param {Boolean} s3tc Whether or not S3TC is supported
   * @param {Boolean} pvrtc Whether or not PVRTC is supported
   * @param {Boolean} astc Whether or not ASTC is supported
   * @param {Boolean} etc Whether or not ETC is supported
   * @param {Boolean} etc1 Whether or not ETC1 is supported
   * @param {Boolean} bc7 Whether or not BC7 is supported
   * @private
   */
  let supportedTranscoderFormats;

  loadKTX2.setKTX2SupportedFormats = function (
    s3tc,
    pvrtc,
    astc,
    etc,
    etc1,
    bc7
  ) {
    supportedTranscoderFormats = {
      s3tc: s3tc,
      pvrtc: pvrtc,
      astc: astc,
      etc: etc,
      etc1: etc1,
      bc7: bc7,
    };
  };

  /**
   * Asynchronously loads and parses the given URL to a KTX2 file or parses the raw binary data of a KTX2 file.
   * Returns a promise that will resolve to an object containing the image buffer, width, height, and format once loaded,
   * or reject if the URL failed to load or failed to parse the data. 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.
   * <p>
   * The following are part of the KTX2 format specification but are not supported:
   * <ul>
   *     <li>Metadata</li>
   *     <li>3D textures</li>
   *     <li>Texture Arrays</li>
   *     <li>Video</li>
   * </ul>
   * </p>
   *
   * @function loadKTX2
   *
   * @param {Resource|String|ArrayBuffer} resourceOrUrlOrBuffer The URL of the binary data or an ArrayBuffer.
   * @returns {Promise.<CompressedTextureBuffer>|undefined} A promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
   *
   * @exception {RuntimeError} Invalid KTX2 file.
   * @exception {RuntimeError} KTX2 texture arrays are not supported.
   * @exception {RuntimeError} KTX2 3D textures are unsupported.
   * @exception {RuntimeError} No transcoding format target available for ETC1S compressed ktx2s.
   * @exception {RuntimeError} No transcoding format target available for UASTC compressed ktx2s.
   * @exception {RuntimeError} startTranscoding() failed.
   * @exception {RuntimeError} transcodeImage() failed.
   *
   * @example
   * // load a single URL asynchronously
   * Cesium.loadKTX2('some/url').then(function (ktx2Data) {
   *     const width = ktx2Data.width;
   *     const height = ktx2Data.height;
   *     const format = ktx2Data.internalFormat;
   *     const arrayBufferView = ktx2Data.bufferView;
   *     // use the data to create a texture
   * }).catch(function (error) {
   *     // an error occurred.
   * });
   *
   * @see {@link https://github.com/KhronosGroup/KTX-Specification|KTX file format}
   * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
   * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
   * @private
   */
  function loadKTX2(resourceOrUrlOrBuffer) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("resourceOrUrlOrBuffer", resourceOrUrlOrBuffer);
    //>>includeEnd('debug');

    let loadPromise;
    if (
      resourceOrUrlOrBuffer instanceof ArrayBuffer ||
      ArrayBuffer.isView(resourceOrUrlOrBuffer)
    ) {
      loadPromise = Promise.resolve(resourceOrUrlOrBuffer);
    } else {
      const resource = Resource.createIfNeeded(resourceOrUrlOrBuffer);
      loadPromise = resource.fetchArrayBuffer();
    }

    // load module then return
    return loadPromise.then(function (data) {
      return KTX2Transcoder.transcode(data, supportedTranscoderFormats);
    });
  }

  const leftScratchArray = [];
  const rightScratchArray = [];

  function merge$1(array, compare, userDefinedObject, start, middle, end) {
    const leftLength = middle - start + 1;
    const rightLength = end - middle;

    const left = leftScratchArray;
    const right = rightScratchArray;

    let i;
    let j;

    for (i = 0; i < leftLength; ++i) {
      left[i] = array[start + i];
    }

    for (j = 0; j < rightLength; ++j) {
      right[j] = array[middle + j + 1];
    }

    i = 0;
    j = 0;
    for (let k = start; k <= end; ++k) {
      const leftElement = left[i];
      const rightElement = right[j];
      if (
        i < leftLength &&
        (j >= rightLength ||
          compare(leftElement, rightElement, userDefinedObject) <= 0)
      ) {
        array[k] = leftElement;
        ++i;
      } else if (j < rightLength) {
        array[k] = rightElement;
        ++j;
      }
    }
  }

  function sort(array, compare, userDefinedObject, start, end) {
    if (start >= end) {
      return;
    }

    const middle = Math.floor((start + end) * 0.5);
    sort(array, compare, userDefinedObject, start, middle);
    sort(array, compare, userDefinedObject, middle + 1, end);
    merge$1(array, compare, userDefinedObject, start, middle, end);
  }

  /**
   * A stable merge sort.
   *
   * @function mergeSort
   * @param {Array} array The array to sort.
   * @param {mergeSortComparator} comparator The function to use to compare elements in the array.
   * @param {*} [userDefinedObject] Any item to pass as the third parameter to <code>comparator</code>.
   *
   * @example
   * // Assume array contains BoundingSpheres in world coordinates.
   * // Sort them in ascending order of distance from the camera.
   * const position = camera.positionWC;
   * Cesium.mergeSort(array, function(a, b, position) {
   *     return Cesium.BoundingSphere.distanceSquaredTo(b, position) - Cesium.BoundingSphere.distanceSquaredTo(a, position);
   * }, position);
   */
  function mergeSort(array, comparator, userDefinedObject) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(array)) {
      throw new DeveloperError("array is required.");
    }
    if (!defined(comparator)) {
      throw new DeveloperError("comparator is required.");
    }
    //>>includeEnd('debug');

    const length = array.length;
    const scratchLength = Math.ceil(length * 0.5);

    // preallocate space in scratch arrays
    leftScratchArray.length = scratchLength;
    rightScratchArray.length = scratchLength;

    sort(array, comparator, userDefinedObject, 0, length - 1);

    // trim scratch arrays
    leftScratchArray.length = 0;
    rightScratchArray.length = 0;
  }

  const scratchBarycentricCoords = new Cartesian3();

  /**
   * Determines if a point is inside a triangle.
   *
   * @function pointInsideTriangle
   *
   * @param {Cartesian2|Cartesian3} point The point to test.
   * @param {Cartesian2|Cartesian3} p0 The first point of the triangle.
   * @param {Cartesian2|Cartesian3} p1 The second point of the triangle.
   * @param {Cartesian2|Cartesian3} p2 The third point of the triangle.
   * @returns {Boolean} <code>true</code> if the point is inside the triangle; otherwise, <code>false</code>.
   *
   * @example
   * // Returns true
   * const p = new Cesium.Cartesian2(0.25, 0.25);
   * const b = Cesium.pointInsideTriangle(p,
   *   new Cesium.Cartesian2(0.0, 0.0),
   *   new Cesium.Cartesian2(1.0, 0.0),
   *   new Cesium.Cartesian2(0.0, 1.0));
   */
  function pointInsideTriangle(point, p0, p1, p2) {
    const coords = barycentricCoordinates(
      point,
      p0,
      p1,
      p2,
      scratchBarycentricCoords
    );
    if (!defined(coords)) {
      return false;
    }
    return coords.x > 0.0 && coords.y > 0.0 && coords.z > 0;
  }

  let implementation;
  if (typeof requestAnimationFrame !== "undefined") {
    implementation = requestAnimationFrame;
  }

  (function () {
    // look for vendor prefixed function
    if (!defined(implementation) && typeof window !== "undefined") {
      const vendors = ["webkit", "moz", "ms", "o"];
      let i = 0;
      const len = vendors.length;
      while (i < len && !defined(implementation)) {
        implementation = window[`${vendors[i]}RequestAnimationFrame`];
        ++i;
      }
    }

    // build an implementation based on setTimeout
    if (!defined(implementation)) {
      const msPerFrame = 1000.0 / 60.0;
      let lastFrameTime = 0;
      implementation = function (callback) {
        const currentTime = getTimestamp$1();

        // schedule the callback to target 60fps, 16.7ms per frame,
        // accounting for the time taken by the callback
        const delay = Math.max(msPerFrame - (currentTime - lastFrameTime), 0);
        lastFrameTime = currentTime + delay;

        return setTimeout(function () {
          callback(lastFrameTime);
        }, delay);
      };
    }
  })();

  /**
   * A browser-independent function to request a new animation frame.  This is used to create
   * an application's draw loop as shown in the example below.
   *
   * @function requestAnimationFrame
   *
   * @param {requestAnimationFrameCallback} callback The function to call when the next frame should be drawn.
   * @returns {Number} An ID that can be passed to {@link cancelAnimationFrame} to cancel the request.
   *
   *
   * @example
   * // Create a draw loop using requestAnimationFrame. The
   * // tick callback function is called for every animation frame.
   * function tick() {
   *   scene.render();
   *   Cesium.requestAnimationFrame(tick);
   * }
   * tick();
   *
   * @see {@link https://www.w3.org/TR/html51/webappapis.html#animation-frames|The Web API Animation Frames interface}
   */
  function requestAnimationFramePolyFill(callback) {
    // we need this extra wrapper function because the native requestAnimationFrame
    // functions must be invoked on the global scope (window), which is not the case
    // if invoked as Cesium.requestAnimationFrame(callback)
    return implementation(callback);
  }

  /**
   * Resizes an image to ensure both width and height are powers of 2.
   * NOTE: The input image is resampled larger, rather than padded.
   * The aspect ratio of the image may change.
   *
   * @param {HTMLImageElement|HTMLCanvasElement} image The image to be resized
   * @returns {HTMLCanvasElement} A new canvas with the resized image drawn to it
   *
   * @private
   */
  function resizeImageToNextPowerOfTwo(image) {
    const canvas = document.createElement("canvas");
    canvas.width = CesiumMath.nextPowerOfTwo(image.width);
    canvas.height = CesiumMath.nextPowerOfTwo(image.height);
    const canvasContext = canvas.getContext("2d");
    canvasContext.drawImage(
      image,
      0,
      0,
      image.width,
      image.height,
      0,
      0,
      canvas.width,
      canvas.height
    );
    return canvas;
  }

  /**
   * Initiates a terrain height query for an array of {@link Cartographic} positions by
   * requesting tiles from a terrain provider, sampling, and interpolating.  The interpolation
   * matches the triangles used to render the terrain at the specified level.  The query
   * happens asynchronously, so this function returns a promise that is resolved when
   * the query completes.  Each point height is modified in place.  If a height can not be
   * determined because no terrain data is available for the specified level at that location,
   * or another error occurs, the height is set to undefined.  As is typical of the
   * {@link Cartographic} type, the supplied height is a height above the reference ellipsoid
   * (such as {@link Ellipsoid.WGS84}) rather than an altitude above mean sea level.  In other
   * words, it will not necessarily be 0.0 if sampled in the ocean. This function needs the
   * terrain level of detail as input, if you need to get the altitude of the terrain as precisely
   * as possible (i.e. with maximum level of detail) use {@link sampleTerrainMostDetailed}.
   *
   * @function sampleTerrain
   *
   * @param {TerrainProvider} terrainProvider The terrain provider from which to query heights.
   * @param {Number} level The terrain level-of-detail from which to query terrain heights.
   * @param {Cartographic[]} positions The positions to update with terrain heights.
   * @returns {Promise.<Cartographic[]>} A promise that resolves to the provided list of positions when terrain the query has completed.
   *
   * @see sampleTerrainMostDetailed
   *
   * @example
   * // Query the terrain height of two Cartographic positions
   * const terrainProvider = Cesium.createWorldTerrain();
   * const positions = [
   *     Cesium.Cartographic.fromDegrees(86.925145, 27.988257),
   *     Cesium.Cartographic.fromDegrees(87.0, 28.0)
   * ];
   * const promise = Cesium.sampleTerrain(terrainProvider, 11, positions);
   * Promise.resolve(promise).then(function(updatedPositions) {
   *     // positions[0].height and positions[1].height have been updated.
   *     // updatedPositions is just a reference to positions.
   * });
   */
  function sampleTerrain(terrainProvider, level, positions) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("terrainProvider", terrainProvider);
    Check.typeOf.number("level", level);
    Check.defined("positions", positions);
    //>>includeEnd('debug');

    return terrainProvider.readyPromise.then(function () {
      return doSampling(terrainProvider, level, positions);
    });
  }

  /**
   * @param {Array.<Object>} tileRequests The mutated list of requests, the first one will be attempted
   * @param {Array.<Promise<void>>} results The list to put the result promises into
   * @returns {boolean} true if the request was made, and we are okay to attempt the next item immediately,
   *  or false if we were throttled and should wait awhile before retrying.
   *
   * @private
   */
  function attemptConsumeNextQueueItem(tileRequests, results) {
    const tileRequest = tileRequests[0];
    const requestPromise = tileRequest.terrainProvider.requestTileGeometry(
      tileRequest.x,
      tileRequest.y,
      tileRequest.level
    );

    if (!requestPromise) {
      // getting back undefined instead of a promise indicates we should retry a bit later
      return false;
    }

    const promise = requestPromise
      .then(createInterpolateFunction(tileRequest))
      .catch(createMarkFailedFunction(tileRequest));

    // remove the request we've just done from the queue
    //  and add its promise result to the result list
    tileRequests.shift();
    results.push(promise);

    // indicate we should synchronously attempt the next request as well
    return true;
  }

  /**
   * Wrap window.setTimeout in a Promise
   * @param {number} ms
   * @private
   */
  function delay(ms) {
    return new Promise(function (res) {
      setTimeout(res, ms);
    });
  }

  /**
   * Recursively consumes all the tileRequests until the list has been emptied
   *  and a Promise of each result has been put into the results list
   * @param {Array.<Object>} tileRequests The list of requests desired to be made
   * @param {Array.<Promise<void>>} results The list to put all the result promises into
   * @returns {Promise<void>} A promise which resolves once all requests have been started
   *
   * @private
   */
  function drainTileRequestQueue(tileRequests, results) {
    // nothing left to do
    if (!tileRequests.length) {
      return Promise.resolve();
    }

    // consume an item from the queue, which will
    //  mutate the request and result lists, and return true if we should
    //  immediately attempt to consume the next item as well
    const success = attemptConsumeNextQueueItem(tileRequests, results);
    if (success) {
      return drainTileRequestQueue(tileRequests, results);
    }

    // wait a small fixed amount of time first, before retrying the same request again
    return delay(100).then(() => {
      return drainTileRequestQueue(tileRequests, results);
    });
  }

  function doSampling(terrainProvider, level, positions) {
    const tilingScheme = terrainProvider.tilingScheme;

    let i;

    // Sort points into a set of tiles
    const tileRequests = []; // Result will be an Array as it's easier to work with
    const tileRequestSet = {}; // A unique set
    for (i = 0; i < positions.length; ++i) {
      const xy = tilingScheme.positionToTileXY(positions[i], level);
      const key = xy.toString();

      if (!tileRequestSet.hasOwnProperty(key)) {
        // When tile is requested for the first time
        const value = {
          x: xy.x,
          y: xy.y,
          level: level,
          tilingScheme: tilingScheme,
          terrainProvider: terrainProvider,
          positions: [],
        };
        tileRequestSet[key] = value;
        tileRequests.push(value);
      }

      // Now append to array of points for the tile
      tileRequestSet[key].positions.push(positions[i]);
    }

    // create our list of result promises to be filled
    const tilePromises = [];
    return drainTileRequestQueue(tileRequests, tilePromises).then(function () {
      // now all the required requests have been started
      //  we just wait for them all to finish
      return Promise.all(tilePromises).then(function () {
        return positions;
      });
    });
  }

  /**
   * Calls {@link TerrainData#interpolateHeight} on a given {@link TerrainData} for a given {@link Cartographic} and
   *  will assign the height property if the return value is not undefined.
   *
   * If the return value is false; it's suggesting that you should call {@link TerrainData#createMesh} first.
   * @param {Cartographic} position The position to interpolate for and assign the height value to
   * @param {TerrainData} terrainData
   * @param {Rectangle} rectangle
   * @returns {Boolean} If the height was actually interpolated and assigned
   * @private
   */
  function interpolateAndAssignHeight(position, terrainData, rectangle) {
    const height = terrainData.interpolateHeight(
      rectangle,
      position.longitude,
      position.latitude
    );
    if (height === undefined) {
      // if height comes back as undefined, it may implicitly mean the terrain data
      //  requires us to call TerrainData.createMesh() first (ArcGIS requires this in particular)
      //  so we'll return false and do that next!
      return false;
    }
    position.height = height;
    return true;
  }

  function createInterpolateFunction(tileRequest) {
    const tilePositions = tileRequest.positions;
    const rectangle = tileRequest.tilingScheme.tileXYToRectangle(
      tileRequest.x,
      tileRequest.y,
      tileRequest.level
    );
    return function (terrainData) {
      let isMeshRequired = false;
      for (let i = 0; i < tilePositions.length; ++i) {
        const position = tilePositions[i];
        const isHeightAssigned = interpolateAndAssignHeight(
          position,
          terrainData,
          rectangle
        );
        // we've found a position which returned undefined - hinting to us
        //  that we probably need to create a mesh for this terrain data.
        // so break out of this loop and create the mesh - then we'll interpolate all the heights again
        if (!isHeightAssigned) {
          isMeshRequired = true;
          break;
        }
      }

      if (!isMeshRequired) {
        // all position heights were interpolated - we don't need the mesh
        return Promise.resolve();
      }

      // create the mesh - and interpolate all the positions again
      // note: terrain exaggeration is not passed in - we are only interested in the raw data
      return terrainData
        .createMesh({
          tilingScheme: tileRequest.tilingScheme,
          x: tileRequest.x,
          y: tileRequest.y,
          level: tileRequest.level,
          // don't throttle this mesh creation because we've asked to sample these points;
          //  so sample them! We don't care how many tiles that is!
          throttle: false,
        })
        .then(function () {
          // mesh has been created - so go through every position (maybe again)
          //  and re-interpolate the heights - presumably using the mesh this time
          for (let i = 0; i < tilePositions.length; ++i) {
            const position = tilePositions[i];
            // if it doesn't work this time - that's fine, we tried.
            interpolateAndAssignHeight(position, terrainData, rectangle);
          }
        });
    };
  }

  function createMarkFailedFunction(tileRequest) {
    const tilePositions = tileRequest.positions;
    return function () {
      for (let i = 0; i < tilePositions.length; ++i) {
        const position = tilePositions[i];
        position.height = undefined;
      }
    };
  }

  const scratchCartesian2$4 = new Cartesian2();

  /**
   * Initiates a sampleTerrain() request at the maximum available tile level for a terrain dataset.
   *
   * @function sampleTerrainMostDetailed
   *
   * @param {TerrainProvider} terrainProvider The terrain provider from which to query heights.
   * @param {Cartographic[]} positions The positions to update with terrain heights.
   * @returns {Promise.<Cartographic[]>} A promise that resolves to the provided list of positions when terrain the query has completed.  This
   *                                     promise will reject if the terrain provider's `availability` property is undefined.
   *
   * @example
   * // Query the terrain height of two Cartographic positions
   * const terrainProvider = Cesium.createWorldTerrain();
   * const positions = [
   *     Cesium.Cartographic.fromDegrees(86.925145, 27.988257),
   *     Cesium.Cartographic.fromDegrees(87.0, 28.0)
   * ];
   * const promise = Cesium.sampleTerrainMostDetailed(terrainProvider, positions);
   * Promise.resolve(promise).then(function(updatedPositions) {
   *     // positions[0].height and positions[1].height have been updated.
   *     // updatedPositions is just a reference to positions.
   * });
   */
  function sampleTerrainMostDetailed(terrainProvider, positions) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(terrainProvider)) {
      throw new DeveloperError("terrainProvider is required.");
    }
    if (!defined(positions)) {
      throw new DeveloperError("positions is required.");
    }
    //>>includeEnd('debug');

    return terrainProvider.readyPromise.then(function () {
      const byLevel = [];
      const maxLevels = [];

      const availability = terrainProvider.availability;

      //>>includeStart('debug', pragmas.debug);
      if (!defined(availability)) {
        throw new DeveloperError(
          "sampleTerrainMostDetailed requires a terrain provider that has tile availability."
        );
      }
      //>>includeEnd('debug');

      const promises = [];
      for (let i = 0; i < positions.length; ++i) {
        const position = positions[i];
        const maxLevel = availability.computeMaximumLevelAtPosition(position);
        maxLevels[i] = maxLevel;
        if (maxLevel === 0) {
          // This is a special case where we have a parent terrain and we are requesting
          // heights from an area that isn't covered by the top level terrain at all.
          // This will essentially trigger the loading of the parent terrains root tile
          terrainProvider.tilingScheme.positionToTileXY(
            position,
            1,
            scratchCartesian2$4
          );
          const promise = terrainProvider.loadTileDataAvailability(
            scratchCartesian2$4.x,
            scratchCartesian2$4.y,
            1
          );
          if (defined(promise)) {
            promises.push(promise);
          }
        }

        let atLevel = byLevel[maxLevel];
        if (!defined(atLevel)) {
          byLevel[maxLevel] = atLevel = [];
        }
        atLevel.push(position);
      }

      return Promise.all(promises)
        .then(function () {
          return Promise.all(
            byLevel.map(function (positionsAtLevel, index) {
              if (defined(positionsAtLevel)) {
                return sampleTerrain(terrainProvider, index, positionsAtLevel);
              }
            })
          );
        })
        .then(function () {
          const changedPositions = [];
          for (let i = 0; i < positions.length; ++i) {
            const position = positions[i];
            const maxLevel = availability.computeMaximumLevelAtPosition(position);

            if (maxLevel !== maxLevels[i]) {
              // Now that we loaded the max availability, a higher level has become available
              changedPositions.push(position);
            }
          }

          if (changedPositions.length > 0) {
            return sampleTerrainMostDetailed(terrainProvider, changedPositions);
          }
        })
        .then(function () {
          return positions;
        });
    });
  }

  /**
   * Subdivides an array into a number of smaller, equal sized arrays.
   *
   * @function subdivideArray
   *
   * @param {Array} array The array to divide.
   * @param {Number} numberOfArrays The number of arrays to divide the provided array into.
   *
   * @exception {DeveloperError} numberOfArrays must be greater than 0.
   */
  function subdivideArray(array, numberOfArrays) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(array)) {
      throw new DeveloperError("array is required.");
    }

    if (!defined(numberOfArrays) || numberOfArrays < 1) {
      throw new DeveloperError("numberOfArrays must be greater than 0.");
    }
    //>>includeEnd('debug');

    const result = [];
    const len = array.length;
    let i = 0;
    while (i < len) {
      const size = Math.ceil((len - i) / numberOfArrays--);
      result.push(array.slice(i, i + size));
      i += size;
    }
    return result;
  }

  function webGLConstantToGlslType(webGLValue) {
    switch (webGLValue) {
      case WebGLConstants$1.FLOAT:
        return "float";
      case WebGLConstants$1.FLOAT_VEC2:
        return "vec2";
      case WebGLConstants$1.FLOAT_VEC3:
        return "vec3";
      case WebGLConstants$1.FLOAT_VEC4:
        return "vec4";
      case WebGLConstants$1.FLOAT_MAT2:
        return "mat2";
      case WebGLConstants$1.FLOAT_MAT3:
        return "mat3";
      case WebGLConstants$1.FLOAT_MAT4:
        return "mat4";
      case WebGLConstants$1.SAMPLER_2D:
        return "sampler2D";
      case WebGLConstants$1.BOOL:
        return "bool";
    }
  }

  /**
   * Wraps a function on the provided objects with another function called in the
   * object's context so that the new function is always called immediately
   * before the old one.
   *
   * @private
   */
  function wrapFunction(obj, oldFunction, newFunction) {
    //>>includeStart('debug', pragmas.debug);
    if (typeof oldFunction !== "function") {
      throw new DeveloperError("oldFunction is required to be a function.");
    }

    if (typeof newFunction !== "function") {
      throw new DeveloperError("oldFunction is required to be a function.");
    }
    //>>includeEnd('debug');

    return function () {
      newFunction.apply(obj, arguments);
      oldFunction.apply(obj, arguments);
    };
  }

  /**
   * A {@link Property} whose value does not change with respect to simulation time.
   *
   * @alias ConstantProperty
   * @constructor
   *
   * @param {*} [value] The property value.
   *
   * @see ConstantPositionProperty
   */
  function ConstantProperty(value) {
    this._value = undefined;
    this._hasClone = false;
    this._hasEquals = false;
    this._definitionChanged = new Event();
    this.setValue(value);
  }

  Object.defineProperties(ConstantProperty.prototype, {
    /**
     * Gets a value indicating if this property is constant.
     * This property always returns <code>true</code>.
     * @memberof ConstantProperty.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    isConstant: {
      value: true,
    },
    /**
     * Gets the event that is raised whenever the definition of this property changes.
     * The definition is changed whenever setValue is called with data different
     * than the current value.
     * @memberof ConstantProperty.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },
  });

  /**
   * Gets the value of the property.
   *
   * @param {JulianDate} [time] The time for which to retrieve the value.  This parameter is unused since the value does not change with respect to time.
   * @param {Object} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Object} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  ConstantProperty.prototype.getValue = function (time, result) {
    return this._hasClone ? this._value.clone(result) : this._value;
  };

  /**
   * Sets the value of the property.
   *
   * @param {*} value The property value.
   */
  ConstantProperty.prototype.setValue = function (value) {
    const oldValue = this._value;
    if (oldValue !== value) {
      const isDefined = defined(value);
      const hasClone = isDefined && typeof value.clone === "function";
      const hasEquals = isDefined && typeof value.equals === "function";

      const changed = !hasEquals || !value.equals(oldValue);
      if (changed) {
        this._hasClone = hasClone;
        this._hasEquals = hasEquals;
        this._value = !hasClone ? value : value.clone(this._value);
        this._definitionChanged.raiseEvent(this);
      }
    }
  };

  /**
   * Compares this property to the provided property and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Property} [other] The other property.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  ConstantProperty.prototype.equals = function (other) {
    return (
      this === other || //
      (other instanceof ConstantProperty && //
        ((!this._hasEquals && this._value === other._value) || //
          (this._hasEquals && this._value.equals(other._value))))
    );
  };

  /**
   * Gets this property's value.
   *
   * @returns {*} This property's value.
   */
  ConstantProperty.prototype.valueOf = function () {
    return this._value;
  };

  /**
   * Creates a string representing this property's value.
   *
   * @returns {String} A string representing the property's value.
   */
  ConstantProperty.prototype.toString = function () {
    return String(this._value);
  };

  function createProperty(
    name,
    privateName,
    subscriptionName,
    configurable,
    createPropertyCallback
  ) {
    return {
      configurable: configurable,
      get: function () {
        return this[privateName];
      },
      set: function (value) {
        const oldValue = this[privateName];
        const subscription = this[subscriptionName];
        if (defined(subscription)) {
          subscription();
          this[subscriptionName] = undefined;
        }

        const hasValue = value !== undefined;
        if (
          hasValue &&
          (!defined(value) || !defined(value.getValue)) &&
          defined(createPropertyCallback)
        ) {
          value = createPropertyCallback(value);
        }

        if (oldValue !== value) {
          this[privateName] = value;
          this._definitionChanged.raiseEvent(this, name, value, oldValue);
        }

        if (defined(value) && defined(value.definitionChanged)) {
          this[subscriptionName] = value.definitionChanged.addEventListener(
            function () {
              this._definitionChanged.raiseEvent(this, name, value, value);
            },
            this
          );
        }
      },
    };
  }

  function createConstantProperty$1(value) {
    return new ConstantProperty(value);
  }

  /**
   * Used to consistently define all DataSources graphics objects.
   * This is broken into two functions because the Chrome profiler does a better
   * job of optimizing lookups if it notices that the string is constant throughout the function.
   * @private
   */
  function createPropertyDescriptor(name, configurable, createPropertyCallback) {
    //Safari 8.0.3 has a JavaScript bug that causes it to confuse two variables and treat them as the same.
    //The two extra toString calls work around the issue.
    return createProperty(
      name,
      `_${name.toString()}`,
      `_${name.toString()}Subscription`,
      defaultValue(configurable, false),
      defaultValue(createPropertyCallback, createConstantProperty$1)
    );
  }

  /**
   * @typedef {Object} BillboardGraphics.ConstructorOptions
   *
   * Initialization options for the BillboardGraphics constructor
   *
   * @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the billboard.
   * @property {Property | string | HTMLCanvasElement} [image] A Property specifying the Image, URI, or Canvas to use for the billboard.
   * @property {Property | number} [scale=1.0] A numeric Property specifying the scale to apply to the image size.
   * @property {Property | Cartesian2} [pixelOffset=Cartesian2.ZERO] A {@link Cartesian2} Property specifying the pixel offset.
   * @property {Property | Cartesian3} [eyeOffset=Cartesian3.ZERO] A {@link Cartesian3} Property specifying the eye offset.
   * @property {Property | HorizontalOrigin} [horizontalOrigin=HorizontalOrigin.CENTER] A Property specifying the {@link HorizontalOrigin}.
   * @property {Property | VerticalOrigin} [verticalOrigin=VerticalOrigin.CENTER] A Property specifying the {@link VerticalOrigin}.
   * @property {Property | HeightReference} [heightReference=HeightReference.NONE] A Property specifying what the height is relative to.
   * @property {Property | Color} [color=Color.WHITE] A Property specifying the tint {@link Color} of the image.
   * @property {Property | number} [rotation=0] A numeric Property specifying the rotation about the alignedAxis.
   * @property {Property | Cartesian3} [alignedAxis=Cartesian3.ZERO] A {@link Cartesian3} Property specifying the unit vector axis of rotation.
   * @property {Property | boolean} [sizeInMeters] A boolean Property specifying whether this billboard's size should be measured in meters.
   * @property {Property | number} [width] A numeric Property specifying the width of the billboard in pixels, overriding the native size.
   * @property {Property | number} [height] A numeric Property specifying the height of the billboard in pixels, overriding the native size.
   * @property {Property | NearFarScalar} [scaleByDistance] A {@link NearFarScalar} Property used to scale the point based on distance from the camera.
   * @property {Property | NearFarScalar} [translucencyByDistance] A {@link NearFarScalar} Property used to set translucency based on distance from the camera.
   * @property {Property | NearFarScalar} [pixelOffsetScaleByDistance] A {@link NearFarScalar} Property used to set pixelOffset based on distance from the camera.
   * @property {Property | BoundingRectangle} [imageSubRegion] A Property specifying a {@link BoundingRectangle} that defines a sub-region of the image to use for the billboard, rather than the entire image, measured in pixels from the bottom-left.
   * @property {Property | DistanceDisplayCondition} [distanceDisplayCondition] A Property specifying at what distance from the camera that this billboard will be displayed.
   * @property {Property | number} [disableDepthTestDistance] A Property specifying the distance from the camera at which to disable the depth test to.
   */

  /**
   * Describes a two dimensional icon located at the position of the containing {@link Entity}.
   * <p>
   * <div align='center'>
   * <img src='Images/Billboard.png' width='400' height='300' /><br />
   * Example billboards
   * </div>
   * </p>
   *
   * @alias BillboardGraphics
   * @constructor
   *
   * @param {BillboardGraphics.ConstructorOptions} [options] Object describing initialization options
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Billboards.html|Cesium Sandcastle Billboard Demo}
   */
  function BillboardGraphics(options) {
    this._definitionChanged = new Event();
    this._show = undefined;
    this._showSubscription = undefined;
    this._image = undefined;
    this._imageSubscription = undefined;
    this._scale = undefined;
    this._scaleSubscription = undefined;
    this._pixelOffset = undefined;
    this._pixelOffsetSubscription = undefined;
    this._eyeOffset = undefined;
    this._eyeOffsetSubscription = undefined;
    this._horizontalOrigin = undefined;
    this._horizontalOriginSubscription = undefined;
    this._verticalOrigin = undefined;
    this._verticalOriginSubscription = undefined;
    this._heightReference = undefined;
    this._heightReferenceSubscription = undefined;
    this._color = undefined;
    this._colorSubscription = undefined;
    this._rotation = undefined;
    this._rotationSubscription = undefined;
    this._alignedAxis = undefined;
    this._alignedAxisSubscription = undefined;
    this._sizeInMeters = undefined;
    this._sizeInMetersSubscription = undefined;
    this._width = undefined;
    this._widthSubscription = undefined;
    this._height = undefined;
    this._heightSubscription = undefined;
    this._scaleByDistance = undefined;
    this._scaleByDistanceSubscription = undefined;
    this._translucencyByDistance = undefined;
    this._translucencyByDistanceSubscription = undefined;
    this._pixelOffsetScaleByDistance = undefined;
    this._pixelOffsetScaleByDistanceSubscription = undefined;
    this._imageSubRegion = undefined;
    this._imageSubRegionSubscription = undefined;
    this._distanceDisplayCondition = undefined;
    this._distanceDisplayConditionSubscription = undefined;
    this._disableDepthTestDistance = undefined;
    this._disableDepthTestDistanceSubscription = undefined;

    this.merge(defaultValue(options, defaultValue.EMPTY_OBJECT));
  }

  Object.defineProperties(BillboardGraphics.prototype, {
    /**
     * Gets the event that is raised whenever a property or sub-property is changed or modified.
     * @memberof BillboardGraphics.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },

    /**
     * Gets or sets the boolean Property specifying the visibility of the billboard.
     * @memberof BillboardGraphics.prototype
     * @type {Property|undefined}
     * @default true
     */
    show: createPropertyDescriptor("show"),

    /**
     * Gets or sets the Property specifying the Image, URI, or Canvas to use for the billboard.
     * @memberof BillboardGraphics.prototype
     * @type {Property|undefined}
     */
    image: createPropertyDescriptor("image"),

    /**
     * Gets or sets the numeric Property specifying the uniform scale to apply to the image.
     * A scale greater than <code>1.0</code> enlarges the billboard while a scale less than <code>1.0</code> shrinks it.
     * <p>
     * <div align='center'>
     * <img src='Images/Billboard.setScale.png' width='400' height='300' /><br/>
     * From left to right in the above image, the scales are <code>0.5</code>, <code>1.0</code>, and <code>2.0</code>.
     * </div>
     * </p>
     * @memberof BillboardGraphics.prototype
     * @type {Property|undefined}
     * @default 1.0
     */
    scale: createPropertyDescriptor("scale"),

    /**
     * Gets or sets the {@link Cartesian2} Property specifying the billboard's pixel offset in screen space
     * from the origin of this billboard.  This is commonly used to align multiple billboards and labels at
     * the same position, e.g., an image and text.  The screen space origin is the top, left corner of the
     * canvas; <code>x</code> increases from left to right, and <code>y</code> increases from top to bottom.
     * <p>
     * <div align='center'>
     * <table border='0' cellpadding='5'><tr>
     * <td align='center'><code>default</code><br/><img src='Images/Billboard.setPixelOffset.default.png' width='250' height='188' /></td>
     * <td align='center'><code>b.pixeloffset = new Cartesian2(50, 25);</code><br/><img src='Images/Billboard.setPixelOffset.x50y-25.png' width='250' height='188' /></td>
     * </tr></table>
     * The billboard's origin is indicated by the yellow point.
     * </div>
     * </p>
     * @memberof BillboardGraphics.prototype
     * @type {Property|undefined}
     * @default Cartesian2.ZERO
     */
    pixelOffset: createPropertyDescriptor("pixelOffset"),

    /**
     * Gets or sets the {@link Cartesian3} Property specifying the billboard's offset in eye coordinates.
     * Eye coordinates is a left-handed coordinate system, where <code>x</code> points towards the viewer's
     * right, <code>y</code> points up, and <code>z</code> points into the screen.
     * <p>
     * An eye offset is commonly used to arrange multiple billboards or objects at the same position, e.g., to
     * arrange a billboard above its corresponding 3D model.
     * </p>
     * Below, the billboard is positioned at the center of the Earth but an eye offset makes it always
     * appear on top of the Earth regardless of the viewer's or Earth's orientation.
     * <p>
     * <div align='center'>
     * <table border='0' cellpadding='5'><tr>
     * <td align='center'><img src='Images/Billboard.setEyeOffset.one.png' width='250' height='188' /></td>
     * <td align='center'><img src='Images/Billboard.setEyeOffset.two.png' width='250' height='188' /></td>
     * </tr></table>
     * <code>b.eyeOffset = new Cartesian3(0.0, 8000000.0, 0.0);</code>
     * </div>
     * </p>
     * @memberof BillboardGraphics.prototype
     * @type {Property|undefined}
     * @default Cartesian3.ZERO
     */
    eyeOffset: createPropertyDescriptor("eyeOffset"),

    /**
     * Gets or sets the Property specifying the {@link HorizontalOrigin}.
     * @memberof BillboardGraphics.prototype
     * @type {Property|undefined}
     * @default HorizontalOrigin.CENTER
     */
    horizontalOrigin: createPropertyDescriptor("horizontalOrigin"),

    /**
     * Gets or sets the Property specifying the {@link VerticalOrigin}.
     * @memberof BillboardGraphics.prototype
     * @type {Property|undefined}
     * @default VerticalOrigin.CENTER
     */
    verticalOrigin: createPropertyDescriptor("verticalOrigin"),

    /**
     * Gets or sets the Property specifying the {@link HeightReference}.
     * @memberof BillboardGraphics.prototype
     * @type {Property|undefined}
     * @default HeightReference.NONE
     */
    heightReference: createPropertyDescriptor("heightReference"),

    /**
     * Gets or sets the Property specifying the {@link Color} that is multiplied with the <code>image</code>.
     * This has two common use cases.  First, the same white texture may be used by many different billboards,
     * each with a different color, to create colored billboards. Second, the color's alpha component can be
     * used to make the billboard translucent as shown below. An alpha of <code>0.0</code> makes the billboard
     * transparent, and <code>1.0</code> makes the billboard opaque.
     * <p>
     * <div align='center'>
     * <table border='0' cellpadding='5'><tr>
     * <td align='center'><code>default</code><br/><img src='Images/Billboard.setColor.Alpha255.png' width='250' height='188' /></td>
     * <td align='center'><code>alpha : 0.5</code><br/><img src='Images/Billboard.setColor.Alpha127.png' width='250' height='188' /></td>
     * </tr></table>
     * </div>
     * </p>
     * @memberof BillboardGraphics.prototype
     * @type {Property|undefined}
     * @default Color.WHITE
     */
    color: createPropertyDescriptor("color"),

    /**
     * Gets or sets the numeric Property specifying the rotation of the image
     * counter clockwise from the <code>alignedAxis</code>.
     * @memberof BillboardGraphics.prototype
     * @type {Property|undefined}
     * @default 0
     */
    rotation: createPropertyDescriptor("rotation"),

    /**
     * Gets or sets the {@link Cartesian3} Property specifying the unit vector axis of rotation
     * in the fixed frame. When set to Cartesian3.ZERO the rotation is from the top of the screen.
     * @memberof BillboardGraphics.prototype
     * @type {Property|undefined}
     * @default Cartesian3.ZERO
     */
    alignedAxis: createPropertyDescriptor("alignedAxis"),

    /**
     * Gets or sets the boolean Property specifying if this billboard's size will be measured in meters.
     * @memberof BillboardGraphics.prototype
     * @type {Property|undefined}
     * @default false
     */
    sizeInMeters: createPropertyDescriptor("sizeInMeters"),

    /**
     * Gets or sets the numeric Property specifying the width of the billboard in pixels.
     * When undefined, the native width is used.
     * @memberof BillboardGraphics.prototype
     * @type {Property|undefined}
     */
    width: createPropertyDescriptor("width"),

    /**
     * Gets or sets the numeric Property specifying the height of the billboard in pixels.
     * When undefined, the native height is used.
     * @memberof BillboardGraphics.prototype
     * @type {Property|undefined}
     */
    height: createPropertyDescriptor("height"),

    /**
     * Gets or sets {@link NearFarScalar} Property specifying the scale of the billboard based on the distance from the camera.
     * A billboard's scale will interpolate between the {@link NearFarScalar#nearValue} and
     * {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds
     * of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}.
     * Outside of these ranges the billboard's scale remains clamped to the nearest bound.
     * @memberof BillboardGraphics.prototype
     * @type {Property|undefined}
     */
    scaleByDistance: createPropertyDescriptor("scaleByDistance"),

    /**
     * Gets or sets {@link NearFarScalar} Property specifying the translucency of the billboard based on the distance from the camera.
     * A billboard's translucency will interpolate between the {@link NearFarScalar#nearValue} and
     * {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds
     * of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}.
     * Outside of these ranges the billboard's translucency remains clamped to the nearest bound.
     * @memberof BillboardGraphics.prototype
     * @type {Property|undefined}
     */
    translucencyByDistance: createPropertyDescriptor("translucencyByDistance"),

    /**
     * Gets or sets {@link NearFarScalar} Property specifying the pixel offset of the billboard based on the distance from the camera.
     * A billboard's pixel offset will interpolate between the {@link NearFarScalar#nearValue} and
     * {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds
     * of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}.
     * Outside of these ranges the billboard's pixel offset remains clamped to the nearest bound.
     * @memberof BillboardGraphics.prototype
     * @type {Property|undefined}
     */
    pixelOffsetScaleByDistance: createPropertyDescriptor(
      "pixelOffsetScaleByDistance"
    ),

    /**
     * Gets or sets the Property specifying a {@link BoundingRectangle} that defines a
     * sub-region of the <code>image</code> to use for the billboard, rather than the entire image,
     * measured in pixels from the bottom-left.
     * @memberof BillboardGraphics.prototype
     * @type {Property|undefined}
     */
    imageSubRegion: createPropertyDescriptor("imageSubRegion"),

    /**
     * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this billboard will be displayed.
     * @memberof BillboardGraphics.prototype
     * @type {Property|undefined}
     */
    distanceDisplayCondition: createPropertyDescriptor(
      "distanceDisplayCondition"
    ),

    /**
     * Gets or sets the distance from the camera at which to disable the depth test to, for example, prevent clipping against terrain.
     * When set to zero, the depth test is always applied. When set to Number.POSITIVE_INFINITY, the depth test is never applied.
     * @memberof BillboardGraphics.prototype
     * @type {Property|undefined}
     */
    disableDepthTestDistance: createPropertyDescriptor(
      "disableDepthTestDistance"
    ),
  });

  /**
   * Duplicates this instance.
   *
   * @param {BillboardGraphics} [result] The object onto which to store the result.
   * @returns {BillboardGraphics} The modified result parameter or a new instance if one was not provided.
   */
  BillboardGraphics.prototype.clone = function (result) {
    if (!defined(result)) {
      return new BillboardGraphics(this);
    }
    result.show = this._show;
    result.image = this._image;
    result.scale = this._scale;
    result.pixelOffset = this._pixelOffset;
    result.eyeOffset = this._eyeOffset;
    result.horizontalOrigin = this._horizontalOrigin;
    result.verticalOrigin = this._verticalOrigin;
    result.heightReference = this._heightReference;
    result.color = this._color;
    result.rotation = this._rotation;
    result.alignedAxis = this._alignedAxis;
    result.sizeInMeters = this._sizeInMeters;
    result.width = this._width;
    result.height = this._height;
    result.scaleByDistance = this._scaleByDistance;
    result.translucencyByDistance = this._translucencyByDistance;
    result.pixelOffsetScaleByDistance = this._pixelOffsetScaleByDistance;
    result.imageSubRegion = this._imageSubRegion;
    result.distanceDisplayCondition = this._distanceDisplayCondition;
    result.disableDepthTestDistance = this._disableDepthTestDistance;
    return result;
  };

  /**
   * Assigns each unassigned property on this object to the value
   * of the same property on the provided source object.
   *
   * @param {BillboardGraphics} source The object to be merged into this object.
   */
  BillboardGraphics.prototype.merge = function (source) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(source)) {
      throw new DeveloperError("source is required.");
    }
    //>>includeEnd('debug');

    this.show = defaultValue(this._show, source.show);
    this.image = defaultValue(this._image, source.image);
    this.scale = defaultValue(this._scale, source.scale);
    this.pixelOffset = defaultValue(this._pixelOffset, source.pixelOffset);
    this.eyeOffset = defaultValue(this._eyeOffset, source.eyeOffset);
    this.horizontalOrigin = defaultValue(
      this._horizontalOrigin,
      source.horizontalOrigin
    );
    this.verticalOrigin = defaultValue(
      this._verticalOrigin,
      source.verticalOrigin
    );
    this.heightReference = defaultValue(
      this._heightReference,
      source.heightReference
    );
    this.color = defaultValue(this._color, source.color);
    this.rotation = defaultValue(this._rotation, source.rotation);
    this.alignedAxis = defaultValue(this._alignedAxis, source.alignedAxis);
    this.sizeInMeters = defaultValue(this._sizeInMeters, source.sizeInMeters);
    this.width = defaultValue(this._width, source.width);
    this.height = defaultValue(this._height, source.height);
    this.scaleByDistance = defaultValue(
      this._scaleByDistance,
      source.scaleByDistance
    );
    this.translucencyByDistance = defaultValue(
      this._translucencyByDistance,
      source.translucencyByDistance
    );
    this.pixelOffsetScaleByDistance = defaultValue(
      this._pixelOffsetScaleByDistance,
      source.pixelOffsetScaleByDistance
    );
    this.imageSubRegion = defaultValue(
      this._imageSubRegion,
      source.imageSubRegion
    );
    this.distanceDisplayCondition = defaultValue(
      this._distanceDisplayCondition,
      source.distanceDisplayCondition
    );
    this.disableDepthTestDistance = defaultValue(
      this._disableDepthTestDistance,
      source.disableDepthTestDistance
    );
  };

  /**
   * Represents the position relative to the terrain.
   *
   * @enum {Number}
   */
  const HeightReference = {
    /**
     * The position is absolute.
     * @type {Number}
     * @constant
     */
    NONE: 0,

    /**
     * The position is clamped to the terrain.
     * @type {Number}
     * @constant
     */
    CLAMP_TO_GROUND: 1,

    /**
     * The position height is the height above the terrain.
     * @type {Number}
     * @constant
     */
    RELATIVE_TO_GROUND: 2,
  };
  var HeightReference$1 = Object.freeze(HeightReference);

  /**
   * The horizontal location of an origin relative to an object, e.g., a {@link Billboard}
   * or {@link Label}.  For example, setting the horizontal origin to <code>LEFT</code>
   * or <code>RIGHT</code> will display a billboard to the left or right (in screen space)
   * of the anchor position.
   * <br /><br />
   * <div align='center'>
   * <img src='Images/Billboard.setHorizontalOrigin.png' width='648' height='196' /><br />
   * </div>
   *
   * @enum {Number}
   *
   * @see Billboard#horizontalOrigin
   * @see Label#horizontalOrigin
   */
  const HorizontalOrigin = {
    /**
     * The origin is at the horizontal center of the object.
     *
     * @type {Number}
     * @constant
     */
    CENTER: 0,

    /**
     * The origin is on the left side of the object.
     *
     * @type {Number}
     * @constant
     */
    LEFT: 1,

    /**
     * The origin is on the right side of the object.
     *
     * @type {Number}
     * @constant
     */
    RIGHT: -1,
  };
  var HorizontalOrigin$1 = Object.freeze(HorizontalOrigin);

  /**
   * The vertical location of an origin relative to an object, e.g., a {@link Billboard}
   * or {@link Label}.  For example, setting the vertical origin to <code>TOP</code>
   * or <code>BOTTOM</code> will display a billboard above or below (in screen space)
   * the anchor position.
   * <br /><br />
   * <div align='center'>
   * <img src='Images/Billboard.setVerticalOrigin.png' width='695' height='175' /><br />
   * </div>
   *
   * @enum {Number}
   *
   * @see Billboard#verticalOrigin
   * @see Label#verticalOrigin
   */
  const VerticalOrigin = {
    /**
     * The origin is at the vertical center between <code>BASELINE</code> and <code>TOP</code>.
     *
     * @type {Number}
     * @constant
     */
    CENTER: 0,

    /**
     * The origin is at the bottom of the object.
     *
     * @type {Number}
     * @constant
     */
    BOTTOM: 1,

    /**
     * If the object contains text, the origin is at the baseline of the text, else the origin is at the bottom of the object.
     *
     * @type {Number}
     * @constant
     */
    BASELINE: 2,

    /**
     * The origin is at the top of the object.
     *
     * @type {Number}
     * @constant
     */
    TOP: -1,
  };
  var VerticalOrigin$1 = Object.freeze(VerticalOrigin);

  /**
   * The state of a BoundingSphere computation being performed by a {@link Visualizer}.
   * @enum {Number}
   * @private
   */
  const BoundingSphereState = {
    /**
     * The BoundingSphere has been computed.
     * @type BoundingSphereState
     * @constant
     */
    DONE: 0,
    /**
     * The BoundingSphere is still being computed.
     * @type BoundingSphereState
     * @constant
     */
    PENDING: 1,
    /**
     * The BoundingSphere does not exist.
     * @type BoundingSphereState
     * @constant
     */
    FAILED: 2,
  };
  var BoundingSphereState$1 = Object.freeze(BoundingSphereState);

  /**
   * The interface for all properties, which represent a value that can optionally vary over time.
   * This type defines an interface and cannot be instantiated directly.
   *
   * @alias Property
   * @constructor
   * @abstract
   *
   * @see CompositeProperty
   * @see ConstantProperty
   * @see SampledProperty
   * @see TimeIntervalCollectionProperty
   * @see MaterialProperty
   * @see PositionProperty
   * @see ReferenceProperty
   */
  function Property() {
    DeveloperError.throwInstantiationError();
  }

  Object.defineProperties(Property.prototype, {
    /**
     * Gets a value indicating if this property is constant.  A property is considered
     * constant if getValue always returns the same result for the current definition.
     * @memberof Property.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    isConstant: {
      get: DeveloperError.throwInstantiationError,
    },
    /**
     * Gets the event that is raised whenever the definition of this property changes.
     * The definition is considered to have changed if a call to getValue would return
     * a different result for the same time.
     * @memberof Property.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: DeveloperError.throwInstantiationError,
    },
  });

  /**
   * Gets the value of the property at the provided time.
   * @function
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {Object} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Object} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  Property.prototype.getValue = DeveloperError.throwInstantiationError;

  /**
   * Compares this property to the provided property and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   * @function
   *
   * @param {Property} [other] The other property.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  Property.prototype.equals = DeveloperError.throwInstantiationError;

  /**
   * @private
   */
  Property.equals = function (left, right) {
    return left === right || (defined(left) && left.equals(right));
  };

  /**
   * @private
   */
  Property.arrayEquals = function (left, right) {
    if (left === right) {
      return true;
    }
    if (!defined(left) || !defined(right) || left.length !== right.length) {
      return false;
    }
    const length = left.length;
    for (let i = 0; i < length; i++) {
      if (!Property.equals(left[i], right[i])) {
        return false;
      }
    }
    return true;
  };

  /**
   * @private
   */
  Property.isConstant = function (property) {
    return !defined(property) || property.isConstant;
  };

  /**
   * @private
   */
  Property.getValueOrUndefined = function (property, time, result) {
    return defined(property) ? property.getValue(time, result) : undefined;
  };

  /**
   * @private
   */
  Property.getValueOrDefault = function (property, time, valueDefault, result) {
    return defined(property)
      ? defaultValue(property.getValue(time, result), valueDefault)
      : valueDefault;
  };

  /**
   * @private
   */
  Property.getValueOrClonedDefault = function (
    property,
    time,
    valueDefault,
    result
  ) {
    let value;
    if (defined(property)) {
      value = property.getValue(time, result);
    }
    if (!defined(value)) {
      value = valueDefault.clone(value);
    }
    return value;
  };

  const defaultColor$8 = Color.WHITE;
  const defaultEyeOffset$1 = Cartesian3.ZERO;
  const defaultHeightReference$2 = HeightReference$1.NONE;
  const defaultPixelOffset$1 = Cartesian2.ZERO;
  const defaultScale$3 = 1.0;
  const defaultRotation = 0.0;
  const defaultAlignedAxis = Cartesian3.ZERO;
  const defaultHorizontalOrigin$1 = HorizontalOrigin$1.CENTER;
  const defaultVerticalOrigin$1 = VerticalOrigin$1.CENTER;
  const defaultSizeInMeters = false;

  const positionScratch$9 = new Cartesian3();
  const colorScratch$6 = new Color();
  const eyeOffsetScratch$1 = new Cartesian3();
  const pixelOffsetScratch$1 = new Cartesian2();
  const scaleByDistanceScratch$2 = new NearFarScalar();
  const translucencyByDistanceScratch$2 = new NearFarScalar();
  const pixelOffsetScaleByDistanceScratch$1 = new NearFarScalar();
  const boundingRectangleScratch = new BoundingRectangle();
  const distanceDisplayConditionScratch$8 = new DistanceDisplayCondition();

  function EntityData$3(entity) {
    this.entity = entity;
    this.billboard = undefined;
    this.textureValue = undefined;
  }

  /**
   * A {@link Visualizer} which maps {@link Entity#billboard} to a {@link Billboard}.
   * @alias BillboardVisualizer
   * @constructor
   *
   * @param {EntityCluster} entityCluster The entity cluster to manage the collection of billboards and optionally cluster with other entities.
   * @param {EntityCollection} entityCollection The entityCollection to visualize.
   */
  function BillboardVisualizer(entityCluster, entityCollection) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(entityCluster)) {
      throw new DeveloperError("entityCluster is required.");
    }
    if (!defined(entityCollection)) {
      throw new DeveloperError("entityCollection is required.");
    }
    //>>includeEnd('debug');

    entityCollection.collectionChanged.addEventListener(
      BillboardVisualizer.prototype._onCollectionChanged,
      this
    );

    this._cluster = entityCluster;
    this._entityCollection = entityCollection;
    this._items = new AssociativeArray();
    this._onCollectionChanged(entityCollection, entityCollection.values, [], []);
  }

  /**
   * Updates the primitives created by this visualizer to match their
   * Entity counterpart at the given time.
   *
   * @param {JulianDate} time The time to update to.
   * @returns {Boolean} This function always returns true.
   */
  BillboardVisualizer.prototype.update = function (time) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(time)) {
      throw new DeveloperError("time is required.");
    }
    //>>includeEnd('debug');

    const items = this._items.values;
    const cluster = this._cluster;

    for (let i = 0, len = items.length; i < len; i++) {
      const item = items[i];
      const entity = item.entity;
      const billboardGraphics = entity._billboard;
      let textureValue;
      let billboard = item.billboard;
      let show =
        entity.isShowing &&
        entity.isAvailable(time) &&
        Property.getValueOrDefault(billboardGraphics._show, time, true);
      let position;
      if (show) {
        position = Property.getValueOrUndefined(
          entity._position,
          time,
          positionScratch$9
        );
        textureValue = Property.getValueOrUndefined(
          billboardGraphics._image,
          time
        );
        show = defined(position) && defined(textureValue);
      }

      if (!show) {
        //don't bother creating or updating anything else
        returnPrimitive$2(item, entity, cluster);
        continue;
      }

      if (!Property.isConstant(entity._position)) {
        cluster._clusterDirty = true;
      }

      if (!defined(billboard)) {
        billboard = cluster.getBillboard(entity);
        billboard.id = entity;
        billboard.image = undefined;
        item.billboard = billboard;
      }

      billboard.show = show;
      if (!defined(billboard.image) || item.textureValue !== textureValue) {
        billboard.image = textureValue;
        item.textureValue = textureValue;
      }
      billboard.position = position;
      billboard.color = Property.getValueOrDefault(
        billboardGraphics._color,
        time,
        defaultColor$8,
        colorScratch$6
      );
      billboard.eyeOffset = Property.getValueOrDefault(
        billboardGraphics._eyeOffset,
        time,
        defaultEyeOffset$1,
        eyeOffsetScratch$1
      );
      billboard.heightReference = Property.getValueOrDefault(
        billboardGraphics._heightReference,
        time,
        defaultHeightReference$2
      );
      billboard.pixelOffset = Property.getValueOrDefault(
        billboardGraphics._pixelOffset,
        time,
        defaultPixelOffset$1,
        pixelOffsetScratch$1
      );
      billboard.scale = Property.getValueOrDefault(
        billboardGraphics._scale,
        time,
        defaultScale$3
      );
      billboard.rotation = Property.getValueOrDefault(
        billboardGraphics._rotation,
        time,
        defaultRotation
      );
      billboard.alignedAxis = Property.getValueOrDefault(
        billboardGraphics._alignedAxis,
        time,
        defaultAlignedAxis
      );
      billboard.horizontalOrigin = Property.getValueOrDefault(
        billboardGraphics._horizontalOrigin,
        time,
        defaultHorizontalOrigin$1
      );
      billboard.verticalOrigin = Property.getValueOrDefault(
        billboardGraphics._verticalOrigin,
        time,
        defaultVerticalOrigin$1
      );
      billboard.width = Property.getValueOrUndefined(
        billboardGraphics._width,
        time
      );
      billboard.height = Property.getValueOrUndefined(
        billboardGraphics._height,
        time
      );
      billboard.scaleByDistance = Property.getValueOrUndefined(
        billboardGraphics._scaleByDistance,
        time,
        scaleByDistanceScratch$2
      );
      billboard.translucencyByDistance = Property.getValueOrUndefined(
        billboardGraphics._translucencyByDistance,
        time,
        translucencyByDistanceScratch$2
      );
      billboard.pixelOffsetScaleByDistance = Property.getValueOrUndefined(
        billboardGraphics._pixelOffsetScaleByDistance,
        time,
        pixelOffsetScaleByDistanceScratch$1
      );
      billboard.sizeInMeters = Property.getValueOrDefault(
        billboardGraphics._sizeInMeters,
        time,
        defaultSizeInMeters
      );
      billboard.distanceDisplayCondition = Property.getValueOrUndefined(
        billboardGraphics._distanceDisplayCondition,
        time,
        distanceDisplayConditionScratch$8
      );
      billboard.disableDepthTestDistance = Property.getValueOrUndefined(
        billboardGraphics._disableDepthTestDistance,
        time
      );

      const subRegion = Property.getValueOrUndefined(
        billboardGraphics._imageSubRegion,
        time,
        boundingRectangleScratch
      );
      if (defined(subRegion)) {
        billboard.setImageSubRegion(billboard._imageId, subRegion);
      }
    }
    return true;
  };

  /**
   * Computes a bounding sphere which encloses the visualization produced for the specified entity.
   * The bounding sphere is in the fixed frame of the scene's globe.
   *
   * @param {Entity} entity The entity whose bounding sphere to compute.
   * @param {BoundingSphere} result The bounding sphere onto which to store the result.
   * @returns {BoundingSphereState} BoundingSphereState.DONE if the result contains the bounding sphere,
   *                       BoundingSphereState.PENDING if the result is still being computed, or
   *                       BoundingSphereState.FAILED if the entity has no visualization in the current scene.
   * @private
   */
  BillboardVisualizer.prototype.getBoundingSphere = function (entity, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(entity)) {
      throw new DeveloperError("entity is required.");
    }
    if (!defined(result)) {
      throw new DeveloperError("result is required.");
    }
    //>>includeEnd('debug');

    const item = this._items.get(entity.id);
    if (!defined(item) || !defined(item.billboard)) {
      return BoundingSphereState$1.FAILED;
    }

    const billboard = item.billboard;
    if (billboard.heightReference === HeightReference$1.NONE) {
      result.center = Cartesian3.clone(billboard.position, result.center);
    } else {
      if (!defined(billboard._clampedPosition)) {
        return BoundingSphereState$1.PENDING;
      }
      result.center = Cartesian3.clone(billboard._clampedPosition, result.center);
    }
    result.radius = 0;
    return BoundingSphereState$1.DONE;
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   *
   * @returns {Boolean} True if this object was destroyed; otherwise, false.
   */
  BillboardVisualizer.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Removes and destroys all primitives created by this instance.
   */
  BillboardVisualizer.prototype.destroy = function () {
    this._entityCollection.collectionChanged.removeEventListener(
      BillboardVisualizer.prototype._onCollectionChanged,
      this
    );
    const entities = this._entityCollection.values;
    for (let i = 0; i < entities.length; i++) {
      this._cluster.removeBillboard(entities[i]);
    }
    return destroyObject(this);
  };

  BillboardVisualizer.prototype._onCollectionChanged = function (
    entityCollection,
    added,
    removed,
    changed
  ) {
    let i;
    let entity;
    const items = this._items;
    const cluster = this._cluster;

    for (i = added.length - 1; i > -1; i--) {
      entity = added[i];
      if (defined(entity._billboard) && defined(entity._position)) {
        items.set(entity.id, new EntityData$3(entity));
      }
    }

    for (i = changed.length - 1; i > -1; i--) {
      entity = changed[i];
      if (defined(entity._billboard) && defined(entity._position)) {
        if (!items.contains(entity.id)) {
          items.set(entity.id, new EntityData$3(entity));
        }
      } else {
        returnPrimitive$2(items.get(entity.id), entity, cluster);
        items.remove(entity.id);
      }
    }

    for (i = removed.length - 1; i > -1; i--) {
      entity = removed[i];
      returnPrimitive$2(items.get(entity.id), entity, cluster);
      items.remove(entity.id);
    }
  };

  function returnPrimitive$2(item, entity, cluster) {
    if (defined(item)) {
      item.billboard = undefined;
      cluster.removeBillboard(entity);
    }
  }

  //This file is automatically rebuilt by the Cesium build process.
  var AllMaterialAppearanceFS = "varying vec3 v_positionEC;\n\
varying vec3 v_normalEC;\n\
varying vec3 v_tangentEC;\n\
varying vec3 v_bitangentEC;\n\
varying vec2 v_st;\n\
void main()\n\
{\n\
vec3 positionToEyeEC = -v_positionEC;\n\
mat3 tangentToEyeMatrix = czm_tangentToEyeSpaceMatrix(v_normalEC, v_tangentEC, v_bitangentEC);\n\
vec3 normalEC = normalize(v_normalEC);\n\
#ifdef FACE_FORWARD\n\
normalEC = faceforward(normalEC, vec3(0.0, 0.0, 1.0), -normalEC);\n\
#endif\n\
czm_materialInput materialInput;\n\
materialInput.normalEC = normalEC;\n\
materialInput.tangentToEyeMatrix = tangentToEyeMatrix;\n\
materialInput.positionToEyeEC = positionToEyeEC;\n\
materialInput.st = v_st;\n\
czm_material material = czm_getMaterial(materialInput);\n\
#ifdef FLAT\n\
gl_FragColor = vec4(material.diffuse + material.emission, material.alpha);\n\
#else\n\
gl_FragColor = czm_phong(normalize(positionToEyeEC), material, czm_lightDirectionEC);\n\
#endif\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var AllMaterialAppearanceVS = "attribute vec3 position3DHigh;\n\
attribute vec3 position3DLow;\n\
attribute vec3 normal;\n\
attribute vec3 tangent;\n\
attribute vec3 bitangent;\n\
attribute vec2 st;\n\
attribute float batchId;\n\
varying vec3 v_positionEC;\n\
varying vec3 v_normalEC;\n\
varying vec3 v_tangentEC;\n\
varying vec3 v_bitangentEC;\n\
varying vec2 v_st;\n\
void main()\n\
{\n\
vec4 p = czm_computePosition();\n\
v_positionEC = (czm_modelViewRelativeToEye * p).xyz;\n\
v_normalEC = czm_normal * normal;\n\
v_tangentEC = czm_normal * tangent;\n\
v_bitangentEC = czm_normal * bitangent;\n\
v_st = st;\n\
gl_Position = czm_modelViewProjectionRelativeToEye * p;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var BasicMaterialAppearanceFS = "varying vec3 v_positionEC;\n\
varying vec3 v_normalEC;\n\
void main()\n\
{\n\
vec3 positionToEyeEC = -v_positionEC;\n\
vec3 normalEC = normalize(v_normalEC);\n\
#ifdef FACE_FORWARD\n\
normalEC = faceforward(normalEC, vec3(0.0, 0.0, 1.0), -normalEC);\n\
#endif\n\
czm_materialInput materialInput;\n\
materialInput.normalEC = normalEC;\n\
materialInput.positionToEyeEC = positionToEyeEC;\n\
czm_material material = czm_getMaterial(materialInput);\n\
#ifdef FLAT\n\
gl_FragColor = vec4(material.diffuse + material.emission, material.alpha);\n\
#else\n\
gl_FragColor = czm_phong(normalize(positionToEyeEC), material, czm_lightDirectionEC);\n\
#endif\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var BasicMaterialAppearanceVS = "attribute vec3 position3DHigh;\n\
attribute vec3 position3DLow;\n\
attribute vec3 normal;\n\
attribute float batchId;\n\
varying vec3 v_positionEC;\n\
varying vec3 v_normalEC;\n\
void main()\n\
{\n\
vec4 p = czm_computePosition();\n\
v_positionEC = (czm_modelViewRelativeToEye * p).xyz;\n\
v_normalEC = czm_normal * normal;\n\
gl_Position = czm_modelViewProjectionRelativeToEye * p;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var TexturedMaterialAppearanceFS = "varying vec3 v_positionEC;\n\
varying vec3 v_normalEC;\n\
varying vec2 v_st;\n\
void main()\n\
{\n\
vec3 positionToEyeEC = -v_positionEC;\n\
vec3 normalEC = normalize(v_normalEC);\n\
#ifdef FACE_FORWARD\n\
normalEC = faceforward(normalEC, vec3(0.0, 0.0, 1.0), -normalEC);\n\
#endif\n\
czm_materialInput materialInput;\n\
materialInput.normalEC = normalEC;\n\
materialInput.positionToEyeEC = positionToEyeEC;\n\
materialInput.st = v_st;\n\
czm_material material = czm_getMaterial(materialInput);\n\
#ifdef FLAT\n\
gl_FragColor = vec4(material.diffuse + material.emission, material.alpha);\n\
#else\n\
gl_FragColor = czm_phong(normalize(positionToEyeEC), material, czm_lightDirectionEC);\n\
#endif\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var TexturedMaterialAppearanceVS = "attribute vec3 position3DHigh;\n\
attribute vec3 position3DLow;\n\
attribute vec3 normal;\n\
attribute vec2 st;\n\
attribute float batchId;\n\
varying vec3 v_positionEC;\n\
varying vec3 v_normalEC;\n\
varying vec2 v_st;\n\
void main()\n\
{\n\
vec4 p = czm_computePosition();\n\
v_positionEC = (czm_modelViewRelativeToEye * p).xyz;\n\
v_normalEC = czm_normal * normal;\n\
v_st = st;\n\
gl_Position = czm_modelViewProjectionRelativeToEye * p;\n\
}\n\
";

  /**
   * Determines how two pixels' values are combined.
   *
   * @enum {Number}
   */
  const BlendEquation = {
    /**
     * Pixel values are added componentwise.  This is used in additive blending for translucency.
     *
     * @type {Number}
     * @constant
     */
    ADD: WebGLConstants$1.FUNC_ADD,

    /**
     * Pixel values are subtracted componentwise (source - destination).  This is used in alpha blending for translucency.
     *
     * @type {Number}
     * @constant
     */
    SUBTRACT: WebGLConstants$1.FUNC_SUBTRACT,

    /**
     * Pixel values are subtracted componentwise (destination - source).
     *
     * @type {Number}
     * @constant
     */
    REVERSE_SUBTRACT: WebGLConstants$1.FUNC_REVERSE_SUBTRACT,

    /**
     * Pixel values are given to the minimum function (min(source, destination)).
     *
     * This equation operates on each pixel color component.
     *
     * @type {Number}
     * @constant
     */
    MIN: WebGLConstants$1.MIN,

    /**
     * Pixel values are given to the maximum function (max(source, destination)).
     *
     * This equation operates on each pixel color component.
     *
     * @type {Number}
     * @constant
     */
    MAX: WebGLConstants$1.MAX,
  };
  var BlendEquation$1 = Object.freeze(BlendEquation);

  /**
   * Determines how blending factors are computed.
   *
   * @enum {Number}
   */
  const BlendFunction = {
    /**
     * The blend factor is zero.
     *
     * @type {Number}
     * @constant
     */
    ZERO: WebGLConstants$1.ZERO,

    /**
     * The blend factor is one.
     *
     * @type {Number}
     * @constant
     */
    ONE: WebGLConstants$1.ONE,

    /**
     * The blend factor is the source color.
     *
     * @type {Number}
     * @constant
     */
    SOURCE_COLOR: WebGLConstants$1.SRC_COLOR,

    /**
     * The blend factor is one minus the source color.
     *
     * @type {Number}
     * @constant
     */
    ONE_MINUS_SOURCE_COLOR: WebGLConstants$1.ONE_MINUS_SRC_COLOR,

    /**
     * The blend factor is the destination color.
     *
     * @type {Number}
     * @constant
     */
    DESTINATION_COLOR: WebGLConstants$1.DST_COLOR,

    /**
     * The blend factor is one minus the destination color.
     *
     * @type {Number}
     * @constant
     */
    ONE_MINUS_DESTINATION_COLOR: WebGLConstants$1.ONE_MINUS_DST_COLOR,

    /**
     * The blend factor is the source alpha.
     *
     * @type {Number}
     * @constant
     */
    SOURCE_ALPHA: WebGLConstants$1.SRC_ALPHA,

    /**
     * The blend factor is one minus the source alpha.
     *
     * @type {Number}
     * @constant
     */
    ONE_MINUS_SOURCE_ALPHA: WebGLConstants$1.ONE_MINUS_SRC_ALPHA,

    /**
     * The blend factor is the destination alpha.
     *
     * @type {Number}
     * @constant
     */
    DESTINATION_ALPHA: WebGLConstants$1.DST_ALPHA,

    /**
     * The blend factor is one minus the destination alpha.
     *
     * @type {Number}
     * @constant
     */
    ONE_MINUS_DESTINATION_ALPHA: WebGLConstants$1.ONE_MINUS_DST_ALPHA,

    /**
     * The blend factor is the constant color.
     *
     * @type {Number}
     * @constant
     */
    CONSTANT_COLOR: WebGLConstants$1.CONSTANT_COLOR,

    /**
     * The blend factor is one minus the constant color.
     *
     * @type {Number}
     * @constant
     */
    ONE_MINUS_CONSTANT_COLOR: WebGLConstants$1.ONE_MINUS_CONSTANT_COLOR,

    /**
     * The blend factor is the constant alpha.
     *
     * @type {Number}
     * @constant
     */
    CONSTANT_ALPHA: WebGLConstants$1.CONSTANT_ALPHA,

    /**
     * The blend factor is one minus the constant alpha.
     *
     * @type {Number}
     * @constant
     */
    ONE_MINUS_CONSTANT_ALPHA: WebGLConstants$1.ONE_MINUS_CONSTANT_ALPHA,

    /**
     * The blend factor is the saturated source alpha.
     *
     * @type {Number}
     * @constant
     */
    SOURCE_ALPHA_SATURATE: WebGLConstants$1.SRC_ALPHA_SATURATE,
  };
  var BlendFunction$1 = Object.freeze(BlendFunction);

  /**
   * The blending state combines {@link BlendEquation} and {@link BlendFunction} and the
   * <code>enabled</code> flag to define the full blending state for combining source and
   * destination fragments when rendering.
   * <p>
   * This is a helper when using custom render states with {@link Appearance#renderState}.
   * </p>
   *
   * @namespace
   */
  const BlendingState = {
    /**
     * Blending is disabled.
     *
     * @type {Object}
     * @constant
     */
    DISABLED: Object.freeze({
      enabled: false,
    }),

    /**
     * Blending is enabled using alpha blending, <code>source(source.alpha) + destination(1 - source.alpha)</code>.
     *
     * @type {Object}
     * @constant
     */
    ALPHA_BLEND: Object.freeze({
      enabled: true,
      equationRgb: BlendEquation$1.ADD,
      equationAlpha: BlendEquation$1.ADD,
      functionSourceRgb: BlendFunction$1.SOURCE_ALPHA,
      functionSourceAlpha: BlendFunction$1.ONE,
      functionDestinationRgb: BlendFunction$1.ONE_MINUS_SOURCE_ALPHA,
      functionDestinationAlpha: BlendFunction$1.ONE_MINUS_SOURCE_ALPHA,
    }),

    /**
     * Blending is enabled using alpha blending with premultiplied alpha, <code>source + destination(1 - source.alpha)</code>.
     *
     * @type {Object}
     * @constant
     */
    PRE_MULTIPLIED_ALPHA_BLEND: Object.freeze({
      enabled: true,
      equationRgb: BlendEquation$1.ADD,
      equationAlpha: BlendEquation$1.ADD,
      functionSourceRgb: BlendFunction$1.ONE,
      functionSourceAlpha: BlendFunction$1.ONE,
      functionDestinationRgb: BlendFunction$1.ONE_MINUS_SOURCE_ALPHA,
      functionDestinationAlpha: BlendFunction$1.ONE_MINUS_SOURCE_ALPHA,
    }),

    /**
     * Blending is enabled using additive blending, <code>source(source.alpha) + destination</code>.
     *
     * @type {Object}
     * @constant
     */
    ADDITIVE_BLEND: Object.freeze({
      enabled: true,
      equationRgb: BlendEquation$1.ADD,
      equationAlpha: BlendEquation$1.ADD,
      functionSourceRgb: BlendFunction$1.SOURCE_ALPHA,
      functionSourceAlpha: BlendFunction$1.ONE,
      functionDestinationRgb: BlendFunction$1.ONE,
      functionDestinationAlpha: BlendFunction$1.ONE,
    }),
  };
  var BlendingState$1 = Object.freeze(BlendingState);

  /**
   * Determines which triangles, if any, are culled.
   *
   * @enum {Number}
   */
  const CullFace = {
    /**
     * Front-facing triangles are culled.
     *
     * @type {Number}
     * @constant
     */
    FRONT: WebGLConstants$1.FRONT,

    /**
     * Back-facing triangles are culled.
     *
     * @type {Number}
     * @constant
     */
    BACK: WebGLConstants$1.BACK,

    /**
     * Both front-facing and back-facing triangles are culled.
     *
     * @type {Number}
     * @constant
     */
    FRONT_AND_BACK: WebGLConstants$1.FRONT_AND_BACK,
  };
  var CullFace$1 = Object.freeze(CullFace);

  /**
   * An appearance defines the full GLSL vertex and fragment shaders and the
   * render state used to draw a {@link Primitive}.  All appearances implement
   * this base <code>Appearance</code> interface.
   *
   * @alias Appearance
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Boolean} [options.translucent=true] When <code>true</code>, the geometry is expected to appear translucent so {@link Appearance#renderState} has alpha blending enabled.
   * @param {Boolean} [options.closed=false] When <code>true</code>, the geometry is expected to be closed so {@link Appearance#renderState} has backface culling enabled.
   * @param {Material} [options.material=Material.ColorType] The material used to determine the fragment color.
   * @param {String} [options.vertexShaderSource] Optional GLSL vertex shader source to override the default vertex shader.
   * @param {String} [options.fragmentShaderSource] Optional GLSL fragment shader source to override the default fragment shader.
   * @param {Object} [options.renderState] Optional render state to override the default render state.
   *
   * @see MaterialAppearance
   * @see EllipsoidSurfaceAppearance
   * @see PerInstanceColorAppearance
   * @see DebugAppearance
   * @see PolylineColorAppearance
   * @see PolylineMaterialAppearance
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Geometry%20and%20Appearances.html|Geometry and Appearances Demo}
   */
  function Appearance(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    /**
     * The material used to determine the fragment color.  Unlike other {@link Appearance}
     * properties, this is not read-only, so an appearance's material can change on the fly.
     *
     * @type Material
     *
     * @see {@link https://github.com/CesiumGS/cesium/wiki/Fabric|Fabric}
     */
    this.material = options.material;

    /**
     * When <code>true</code>, the geometry is expected to appear translucent.
     *
     * @type {Boolean}
     *
     * @default true
     */
    this.translucent = defaultValue(options.translucent, true);

    this._vertexShaderSource = options.vertexShaderSource;
    this._fragmentShaderSource = options.fragmentShaderSource;
    this._renderState = options.renderState;
    this._closed = defaultValue(options.closed, false);
  }

  Object.defineProperties(Appearance.prototype, {
    /**
     * The GLSL source code for the vertex shader.
     *
     * @memberof Appearance.prototype
     *
     * @type {String}
     * @readonly
     */
    vertexShaderSource: {
      get: function () {
        return this._vertexShaderSource;
      },
    },

    /**
     * The GLSL source code for the fragment shader.  The full fragment shader
     * source is built procedurally taking into account the {@link Appearance#material}.
     * Use {@link Appearance#getFragmentShaderSource} to get the full source.
     *
     * @memberof Appearance.prototype
     *
     * @type {String}
     * @readonly
     */
    fragmentShaderSource: {
      get: function () {
        return this._fragmentShaderSource;
      },
    },

    /**
     * The WebGL fixed-function state to use when rendering the geometry.
     *
     * @memberof Appearance.prototype
     *
     * @type {Object}
     * @readonly
     */
    renderState: {
      get: function () {
        return this._renderState;
      },
    },

    /**
     * When <code>true</code>, the geometry is expected to be closed.
     *
     * @memberof Appearance.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default false
     */
    closed: {
      get: function () {
        return this._closed;
      },
    },
  });

  /**
   * Procedurally creates the full GLSL fragment shader source for this appearance
   * taking into account {@link Appearance#fragmentShaderSource} and {@link Appearance#material}.
   *
   * @returns {String} The full GLSL fragment shader source.
   */
  Appearance.prototype.getFragmentShaderSource = function () {
    const parts = [];
    if (this.flat) {
      parts.push("#define FLAT");
    }
    if (this.faceForward) {
      parts.push("#define FACE_FORWARD");
    }
    if (defined(this.material)) {
      parts.push(this.material.shaderSource);
    }
    parts.push(this.fragmentShaderSource);

    return parts.join("\n");
  };

  /**
   * Determines if the geometry is translucent based on {@link Appearance#translucent} and {@link Material#isTranslucent}.
   *
   * @returns {Boolean} <code>true</code> if the appearance is translucent.
   */
  Appearance.prototype.isTranslucent = function () {
    return (
      (defined(this.material) && this.material.isTranslucent()) ||
      (!defined(this.material) && this.translucent)
    );
  };

  /**
   * Creates a render state.  This is not the final render state instance; instead,
   * it can contain a subset of render state properties identical to the render state
   * created in the context.
   *
   * @returns {Object} The render state.
   */
  Appearance.prototype.getRenderState = function () {
    const translucent = this.isTranslucent();
    const rs = clone$1(this.renderState, false);
    if (translucent) {
      rs.depthMask = false;
      rs.blending = BlendingState$1.ALPHA_BLEND;
    } else {
      rs.depthMask = true;
    }
    return rs;
  };

  /**
   * @private
   */
  Appearance.getDefaultRenderState = function (translucent, closed, existing) {
    let rs = {
      depthTest: {
        enabled: true,
      },
    };

    if (translucent) {
      rs.depthMask = false;
      rs.blending = BlendingState$1.ALPHA_BLEND;
    }

    if (closed) {
      rs.cull = {
        enabled: true,
        face: CullFace$1.BACK,
      };
    }

    if (defined(existing)) {
      rs = combine$2(existing, rs, true);
    }

    return rs;
  };

  /**
   * @private
   */
  const ContextLimits = {
    _maximumCombinedTextureImageUnits: 0,
    _maximumCubeMapSize: 0,
    _maximumFragmentUniformVectors: 0,
    _maximumTextureImageUnits: 0,
    _maximumRenderbufferSize: 0,
    _maximumTextureSize: 0,
    _maximumVaryingVectors: 0,
    _maximumVertexAttributes: 0,
    _maximumVertexTextureImageUnits: 0,
    _maximumVertexUniformVectors: 0,
    _minimumAliasedLineWidth: 0,
    _maximumAliasedLineWidth: 0,
    _minimumAliasedPointSize: 0,
    _maximumAliasedPointSize: 0,
    _maximumViewportWidth: 0,
    _maximumViewportHeight: 0,
    _maximumTextureFilterAnisotropy: 0,
    _maximumDrawBuffers: 0,
    _maximumColorAttachments: 0,
    _maximumSamples: 0,
    _highpFloatSupported: false,
    _highpIntSupported: false,
  };

  Object.defineProperties(ContextLimits, {
    /**
     * The maximum number of texture units that can be used from the vertex and fragment
     * shader with this WebGL implementation.  The minimum is eight.  If both shaders access the
     * same texture unit, this counts as two texture units.
     * @memberof ContextLimits
     * @type {Number}
     * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with <code>MAX_COMBINED_TEXTURE_IMAGE_UNITS</code>.
     */
    maximumCombinedTextureImageUnits: {
      get: function () {
        return ContextLimits._maximumCombinedTextureImageUnits;
      },
    },

    /**
     * The approximate maximum cube mape width and height supported by this WebGL implementation.
     * The minimum is 16, but most desktop and laptop implementations will support much larger sizes like 8,192.
     * @memberof ContextLimits
     * @type {Number}
     * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with <code>MAX_CUBE_MAP_TEXTURE_SIZE</code>.
     */
    maximumCubeMapSize: {
      get: function () {
        return ContextLimits._maximumCubeMapSize;
      },
    },

    /**
     * The maximum number of <code>vec4</code>, <code>ivec4</code>, and <code>bvec4</code>
     * uniforms that can be used by a fragment shader with this WebGL implementation.  The minimum is 16.
     * @memberof ContextLimits
     * @type {Number}
     * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with <code>MAX_FRAGMENT_UNIFORM_VECTORS</code>.
     */
    maximumFragmentUniformVectors: {
      get: function () {
        return ContextLimits._maximumFragmentUniformVectors;
      },
    },

    /**
     * The maximum number of texture units that can be used from the fragment shader with this WebGL implementation.  The minimum is eight.
     * @memberof ContextLimits
     * @type {Number}
     * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with <code>MAX_TEXTURE_IMAGE_UNITS</code>.
     */
    maximumTextureImageUnits: {
      get: function () {
        return ContextLimits._maximumTextureImageUnits;
      },
    },

    /**
     * The maximum renderbuffer width and height supported by this WebGL implementation.
     * The minimum is 16, but most desktop and laptop implementations will support much larger sizes like 8,192.
     * @memberof ContextLimits
     * @type {Number}
     * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with <code>MAX_RENDERBUFFER_SIZE</code>.
     */
    maximumRenderbufferSize: {
      get: function () {
        return ContextLimits._maximumRenderbufferSize;
      },
    },

    /**
     * The approximate maximum texture width and height supported by this WebGL implementation.
     * The minimum is 64, but most desktop and laptop implementations will support much larger sizes like 8,192.
     * @memberof ContextLimits
     * @type {Number}
     * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with <code>MAX_TEXTURE_SIZE</code>.
     */
    maximumTextureSize: {
      get: function () {
        return ContextLimits._maximumTextureSize;
      },
    },

    /**
     * The maximum number of <code>vec4</code> varying variables supported by this WebGL implementation.
     * The minimum is eight.  Matrices and arrays count as multiple <code>vec4</code>s.
     * @memberof ContextLimits
     * @type {Number}
     * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with <code>MAX_VARYING_VECTORS</code>.
     */
    maximumVaryingVectors: {
      get: function () {
        return ContextLimits._maximumVaryingVectors;
      },
    },

    /**
     * The maximum number of <code>vec4</code> vertex attributes supported by this WebGL implementation.  The minimum is eight.
     * @memberof ContextLimits
     * @type {Number}
     * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with <code>MAX_VERTEX_ATTRIBS</code>.
     */
    maximumVertexAttributes: {
      get: function () {
        return ContextLimits._maximumVertexAttributes;
      },
    },

    /**
     * The maximum number of texture units that can be used from the vertex shader with this WebGL implementation.
     * The minimum is zero, which means the GL does not support vertex texture fetch.
     * @memberof ContextLimits
     * @type {Number}
     * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with <code>MAX_VERTEX_TEXTURE_IMAGE_UNITS</code>.
     */
    maximumVertexTextureImageUnits: {
      get: function () {
        return ContextLimits._maximumVertexTextureImageUnits;
      },
    },

    /**
     * The maximum number of <code>vec4</code>, <code>ivec4</code>, and <code>bvec4</code>
     * uniforms that can be used by a vertex shader with this WebGL implementation.  The minimum is 16.
     * @memberof ContextLimits
     * @type {Number}
     * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with <code>MAX_VERTEX_UNIFORM_VECTORS</code>.
     */
    maximumVertexUniformVectors: {
      get: function () {
        return ContextLimits._maximumVertexUniformVectors;
      },
    },

    /**
     * The minimum aliased line width, in pixels, supported by this WebGL implementation.  It will be at most one.
     * @memberof ContextLimits
     * @type {Number}
     * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with <code>ALIASED_LINE_WIDTH_RANGE</code>.
     */
    minimumAliasedLineWidth: {
      get: function () {
        return ContextLimits._minimumAliasedLineWidth;
      },
    },

    /**
     * The maximum aliased line width, in pixels, supported by this WebGL implementation.  It will be at least one.
     * @memberof ContextLimits
     * @type {Number}
     * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with <code>ALIASED_LINE_WIDTH_RANGE</code>.
     */
    maximumAliasedLineWidth: {
      get: function () {
        return ContextLimits._maximumAliasedLineWidth;
      },
    },

    /**
     * The minimum aliased point size, in pixels, supported by this WebGL implementation.  It will be at most one.
     * @memberof ContextLimits
     * @type {Number}
     * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with <code>ALIASED_POINT_SIZE_RANGE</code>.
     */
    minimumAliasedPointSize: {
      get: function () {
        return ContextLimits._minimumAliasedPointSize;
      },
    },

    /**
     * The maximum aliased point size, in pixels, supported by this WebGL implementation.  It will be at least one.
     * @memberof ContextLimits
     * @type {Number}
     * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with <code>ALIASED_POINT_SIZE_RANGE</code>.
     */
    maximumAliasedPointSize: {
      get: function () {
        return ContextLimits._maximumAliasedPointSize;
      },
    },

    /**
     * The maximum supported width of the viewport.  It will be at least as large as the visible width of the associated canvas.
     * @memberof ContextLimits
     * @type {Number}
     * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with <code>MAX_VIEWPORT_DIMS</code>.
     */
    maximumViewportWidth: {
      get: function () {
        return ContextLimits._maximumViewportWidth;
      },
    },

    /**
     * The maximum supported height of the viewport.  It will be at least as large as the visible height of the associated canvas.
     * @memberof ContextLimits
     * @type {Number}
     * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with <code>MAX_VIEWPORT_DIMS</code>.
     */
    maximumViewportHeight: {
      get: function () {
        return ContextLimits._maximumViewportHeight;
      },
    },

    /**
     * The maximum degree of anisotropy for texture filtering
     * @memberof ContextLimits
     * @type {Number}
     */
    maximumTextureFilterAnisotropy: {
      get: function () {
        return ContextLimits._maximumTextureFilterAnisotropy;
      },
    },

    /**
     * The maximum number of simultaneous outputs that may be written in a fragment shader.
     * @memberof ContextLimits
     * @type {Number}
     */
    maximumDrawBuffers: {
      get: function () {
        return ContextLimits._maximumDrawBuffers;
      },
    },

    /**
     * The maximum number of color attachments supported.
     * @memberof ContextLimits
     * @type {Number}
     */
    maximumColorAttachments: {
      get: function () {
        return ContextLimits._maximumColorAttachments;
      },
    },

    /**
     * The maximum number of samples supported for multisampling.
     * @memberof ContextLimits
     * @type {Number}
     */
    maximumSamples: {
      get: function () {
        return ContextLimits._maximumSamples;
      },
    },

    /**
     * High precision float supported (<code>highp</code>) in fragment shaders.
     * @memberof ContextLimits
     * @type {Boolean}
     */
    highpFloatSupported: {
      get: function () {
        return ContextLimits._highpFloatSupported;
      },
    },

    /**
     * High precision int supported (<code>highp</code>) in fragment shaders.
     * @memberof ContextLimits
     * @type {Boolean}
     */
    highpIntSupported: {
      get: function () {
        return ContextLimits._highpIntSupported;
      },
    },
  });

  /**
   * @private
   */
  function CubeMapFace(
    context,
    texture,
    textureTarget,
    targetFace,
    internalFormat,
    pixelFormat,
    pixelDatatype,
    size,
    preMultiplyAlpha,
    flipY,
    initialized
  ) {
    this._context = context;
    this._texture = texture;
    this._textureTarget = textureTarget;
    this._targetFace = targetFace;
    this._pixelDatatype = pixelDatatype;
    this._internalFormat = internalFormat;
    this._pixelFormat = pixelFormat;
    this._size = size;
    this._preMultiplyAlpha = preMultiplyAlpha;
    this._flipY = flipY;
    this._initialized = initialized;
  }

  Object.defineProperties(CubeMapFace.prototype, {
    pixelFormat: {
      get: function () {
        return this._pixelFormat;
      },
    },
    pixelDatatype: {
      get: function () {
        return this._pixelDatatype;
      },
    },
    _target: {
      get: function () {
        return this._targetFace;
      },
    },
  });

  /**
   * Copies texels from the source to the cubemap's face.
   * @param {Object} options Object with the following properties:
   * @param {Object} options.source The source {@link ImageData}, {@link HTMLImageElement}, {@link HTMLCanvasElement}, {@link HTMLVideoElement},
   *                              or an object with a width, height, and arrayBufferView properties.
   * @param {Number} [options.xOffset=0] An offset in the x direction in the cubemap where copying begins.
   * @param {Number} [options.yOffset=0] An offset in the y direction in the cubemap where copying begins.
   * @param {Boolean} [options.skipColorSpaceConversion=false] If true, any custom gamma or color profiles in the texture will be ignored.
   * @exception {DeveloperError} xOffset must be greater than or equal to zero.
   * @exception {DeveloperError} yOffset must be greater than or equal to zero.
   * @exception {DeveloperError} xOffset + source.width must be less than or equal to width.
   * @exception {DeveloperError} yOffset + source.height must be less than or equal to height.
   * @exception {DeveloperError} This CubeMap was destroyed, i.e., destroy() was called.
   *
   * @example
   * // Create a cubemap with 1x1 faces, and make the +x face red.
   * const cubeMap = new CubeMap({
   *   context : context
   *   width : 1,
   *   height : 1
   * });
   * cubeMap.positiveX.copyFrom({
   *   source: {
   *     width : 1,
   *     height : 1,
   *     arrayBufferView : new Uint8Array([255, 0, 0, 255])
   *   }
   * });
   */
  CubeMapFace.prototype.copyFrom = function (options) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("options", options);
    //>>includeEnd('debug');

    const xOffset = defaultValue(options.xOffset, 0);
    const yOffset = defaultValue(options.yOffset, 0);

    //>>includeStart('debug', pragmas.debug);
    Check.defined("options.source", options.source);
    Check.typeOf.number.greaterThanOrEquals("xOffset", xOffset, 0);
    Check.typeOf.number.greaterThanOrEquals("yOffset", yOffset, 0);
    if (xOffset + options.source.width > this._size) {
      throw new DeveloperError(
        "xOffset + options.source.width must be less than or equal to width."
      );
    }
    if (yOffset + options.source.height > this._size) {
      throw new DeveloperError(
        "yOffset + options.source.height must be less than or equal to height."
      );
    }
    //>>includeEnd('debug');

    const source = options.source;

    const gl = this._context._gl;
    const target = this._textureTarget;
    const targetFace = this._targetFace;

    gl.activeTexture(gl.TEXTURE0);
    gl.bindTexture(target, this._texture);

    const width = source.width;
    const height = source.height;
    let arrayBufferView = source.arrayBufferView;

    const size = this._size;
    const pixelFormat = this._pixelFormat;
    const internalFormat = this._internalFormat;
    const pixelDatatype = this._pixelDatatype;

    const preMultiplyAlpha = this._preMultiplyAlpha;
    const flipY = this._flipY;
    const skipColorSpaceConversion = defaultValue(
      options.skipColorSpaceConversion,
      false
    );

    let unpackAlignment = 4;
    if (defined(arrayBufferView)) {
      unpackAlignment = PixelFormat$1.alignmentInBytes(
        pixelFormat,
        pixelDatatype,
        width
      );
    }

    gl.pixelStorei(gl.UNPACK_ALIGNMENT, unpackAlignment);

    if (skipColorSpaceConversion) {
      gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE);
    } else {
      gl.pixelStorei(
        gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,
        gl.BROWSER_DEFAULT_WEBGL
      );
    }

    let uploaded = false;
    if (!this._initialized) {
      if (xOffset === 0 && yOffset === 0 && width === size && height === size) {
        // initialize the entire texture
        if (defined(arrayBufferView)) {
          gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
          gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);

          if (flipY) {
            arrayBufferView = PixelFormat$1.flipY(
              arrayBufferView,
              pixelFormat,
              pixelDatatype,
              size,
              size
            );
          }
          gl.texImage2D(
            targetFace,
            0,
            internalFormat,
            size,
            size,
            0,
            pixelFormat,
            PixelDatatype$1.toWebGLConstant(pixelDatatype, this._context),
            arrayBufferView
          );
        } else {
          // Only valid for DOM-Element uploads
          gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, preMultiplyAlpha);
          gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY);

          gl.texImage2D(
            targetFace,
            0,
            internalFormat,
            pixelFormat,
            PixelDatatype$1.toWebGLConstant(pixelDatatype, this._context),
            source
          );
        }
        uploaded = true;
      } else {
        gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);

        // initialize the entire texture to zero
        const bufferView = PixelFormat$1.createTypedArray(
          pixelFormat,
          pixelDatatype,
          size,
          size
        );
        gl.texImage2D(
          targetFace,
          0,
          internalFormat,
          size,
          size,
          0,
          pixelFormat,
          PixelDatatype$1.toWebGLConstant(pixelDatatype, this._context),
          bufferView
        );
      }
      this._initialized = true;
    }

    if (!uploaded) {
      if (defined(arrayBufferView)) {
        gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);

        if (flipY) {
          arrayBufferView = PixelFormat$1.flipY(
            arrayBufferView,
            pixelFormat,
            pixelDatatype,
            width,
            height
          );
        }
        gl.texSubImage2D(
          targetFace,
          0,
          xOffset,
          yOffset,
          width,
          height,
          pixelFormat,
          PixelDatatype$1.toWebGLConstant(pixelDatatype, this._context),
          arrayBufferView
        );
      } else {
        // Only valid for DOM-Element uploads
        gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, preMultiplyAlpha);
        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY);

        // Source: ImageData, HTMLImageElement, HTMLCanvasElement, or HTMLVideoElement
        gl.texSubImage2D(
          targetFace,
          0,
          xOffset,
          yOffset,
          pixelFormat,
          PixelDatatype$1.toWebGLConstant(pixelDatatype, this._context),
          source
        );
      }
    }

    gl.bindTexture(target, null);
  };

  /**
   * Copies texels from the framebuffer to the cubemap's face.
   *
   * @param {Number} [xOffset=0] An offset in the x direction in the cubemap where copying begins.
   * @param {Number} [yOffset=0] An offset in the y direction in the cubemap where copying begins.
   * @param {Number} [framebufferXOffset=0] An offset in the x direction in the framebuffer where copying begins from.
   * @param {Number} [framebufferYOffset=0] An offset in the y direction in the framebuffer where copying begins from.
   * @param {Number} [width=CubeMap's width] The width of the subimage to copy.
   * @param {Number} [height=CubeMap's height] The height of the subimage to copy.
   *
   * @exception {DeveloperError} Cannot call copyFromFramebuffer when the texture pixel data type is FLOAT.
   * @exception {DeveloperError} Cannot call copyFromFramebuffer when the texture pixel data type is HALF_FLOAT.
   * @exception {DeveloperError} This CubeMap was destroyed, i.e., destroy() was called.
   * @exception {DeveloperError} xOffset must be greater than or equal to zero.
   * @exception {DeveloperError} yOffset must be greater than or equal to zero.
   * @exception {DeveloperError} framebufferXOffset must be greater than or equal to zero.
   * @exception {DeveloperError} framebufferYOffset must be greater than or equal to zero.
   * @exception {DeveloperError} xOffset + source.width must be less than or equal to width.
   * @exception {DeveloperError} yOffset + source.height must be less than or equal to height.
   * @exception {DeveloperError} This CubeMap was destroyed, i.e., destroy() was called.
   *
   * @example
   * // Copy the framebuffer contents to the +x cube map face.
   * cubeMap.positiveX.copyFromFramebuffer();
   */
  CubeMapFace.prototype.copyFromFramebuffer = function (
    xOffset,
    yOffset,
    framebufferXOffset,
    framebufferYOffset,
    width,
    height
  ) {
    xOffset = defaultValue(xOffset, 0);
    yOffset = defaultValue(yOffset, 0);
    framebufferXOffset = defaultValue(framebufferXOffset, 0);
    framebufferYOffset = defaultValue(framebufferYOffset, 0);
    width = defaultValue(width, this._size);
    height = defaultValue(height, this._size);

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number.greaterThanOrEquals("xOffset", xOffset, 0);
    Check.typeOf.number.greaterThanOrEquals("yOffset", yOffset, 0);
    Check.typeOf.number.greaterThanOrEquals(
      "framebufferXOffset",
      framebufferXOffset,
      0
    );
    Check.typeOf.number.greaterThanOrEquals(
      "framebufferYOffset",
      framebufferYOffset,
      0
    );
    if (xOffset + width > this._size) {
      throw new DeveloperError(
        "xOffset + source.width must be less than or equal to width."
      );
    }
    if (yOffset + height > this._size) {
      throw new DeveloperError(
        "yOffset + source.height must be less than or equal to height."
      );
    }
    if (this._pixelDatatype === PixelDatatype$1.FLOAT) {
      throw new DeveloperError(
        "Cannot call copyFromFramebuffer when the texture pixel data type is FLOAT."
      );
    }
    if (this._pixelDatatype === PixelDatatype$1.HALF_FLOAT) {
      throw new DeveloperError(
        "Cannot call copyFromFramebuffer when the texture pixel data type is HALF_FLOAT."
      );
    }
    //>>includeEnd('debug');

    const gl = this._context._gl;
    const target = this._textureTarget;

    gl.activeTexture(gl.TEXTURE0);
    gl.bindTexture(target, this._texture);
    gl.copyTexSubImage2D(
      this._targetFace,
      0,
      xOffset,
      yOffset,
      framebufferXOffset,
      framebufferYOffset,
      width,
      height
    );
    gl.bindTexture(target, null);
    this._initialized = true;
  };

  /**
   * @private
   */
  const MipmapHint = {
    DONT_CARE: WebGLConstants$1.DONT_CARE,
    FASTEST: WebGLConstants$1.FASTEST,
    NICEST: WebGLConstants$1.NICEST,

    validate: function (mipmapHint) {
      return (
        mipmapHint === MipmapHint.DONT_CARE ||
        mipmapHint === MipmapHint.FASTEST ||
        mipmapHint === MipmapHint.NICEST
      );
    },
  };
  var MipmapHint$1 = Object.freeze(MipmapHint);

  /**
   * Enumerates all possible filters used when magnifying WebGL textures.
   *
   * @enum {Number}
   *
   * @see TextureMinificationFilter
   */
  const TextureMagnificationFilter = {
    /**
     * Samples the texture by returning the closest pixel.
     *
     * @type {Number}
     * @constant
     */
    NEAREST: WebGLConstants$1.NEAREST,
    /**
     * Samples the texture through bi-linear interpolation of the four nearest pixels. This produces smoother results than <code>NEAREST</code> filtering.
     *
     * @type {Number}
     * @constant
     */
    LINEAR: WebGLConstants$1.LINEAR,
  };

  /**
   * Validates the given <code>textureMinificationFilter</code> with respect to the possible enum values.
   * @param textureMagnificationFilter
   * @returns {Boolean} <code>true</code> if <code>textureMagnificationFilter</code> is valid.
   *
   * @private
   */
  TextureMagnificationFilter.validate = function (textureMagnificationFilter) {
    return (
      textureMagnificationFilter === TextureMagnificationFilter.NEAREST ||
      textureMagnificationFilter === TextureMagnificationFilter.LINEAR
    );
  };

  var TextureMagnificationFilter$1 = Object.freeze(TextureMagnificationFilter);

  /**
   * Enumerates all possible filters used when minifying WebGL textures.
   *
   * @enum {Number}
   *
   * @see TextureMagnificationFilter
   */
  const TextureMinificationFilter = {
    /**
     * Samples the texture by returning the closest pixel.
     *
     * @type {Number}
     * @constant
     */
    NEAREST: WebGLConstants$1.NEAREST,
    /**
     * Samples the texture through bi-linear interpolation of the four nearest pixels. This produces smoother results than <code>NEAREST</code> filtering.
     *
     * @type {Number}
     * @constant
     */
    LINEAR: WebGLConstants$1.LINEAR,
    /**
     * Selects the nearest mip level and applies nearest sampling within that level.
     * <p>
     * Requires that the texture has a mipmap. The mip level is chosen by the view angle and screen-space size of the texture.
     * </p>
     *
     * @type {Number}
     * @constant
     */
    NEAREST_MIPMAP_NEAREST: WebGLConstants$1.NEAREST_MIPMAP_NEAREST,
    /**
     * Selects the nearest mip level and applies linear sampling within that level.
     * <p>
     * Requires that the texture has a mipmap. The mip level is chosen by the view angle and screen-space size of the texture.
     * </p>
     *
     * @type {Number}
     * @constant
     */
    LINEAR_MIPMAP_NEAREST: WebGLConstants$1.LINEAR_MIPMAP_NEAREST,
    /**
     * Read texture values with nearest sampling from two adjacent mip levels and linearly interpolate the results.
     * <p>
     * This option provides a good balance of visual quality and speed when sampling from a mipmapped texture.
     * </p>
     * <p>
     * Requires that the texture has a mipmap. The mip level is chosen by the view angle and screen-space size of the texture.
     * </p>
     *
     * @type {Number}
     * @constant
     */
    NEAREST_MIPMAP_LINEAR: WebGLConstants$1.NEAREST_MIPMAP_LINEAR,
    /**
     * Read texture values with linear sampling from two adjacent mip levels and linearly interpolate the results.
     * <p>
     * This option provides a good balance of visual quality and speed when sampling from a mipmapped texture.
     * </p>
     * <p>
     * Requires that the texture has a mipmap. The mip level is chosen by the view angle and screen-space size of the texture.
     * </p>
     * @type {Number}
     * @constant
     */
    LINEAR_MIPMAP_LINEAR: WebGLConstants$1.LINEAR_MIPMAP_LINEAR,
  };

  /**
   * Validates the given <code>textureMinificationFilter</code> with respect to the possible enum values.
   *
   * @private
   *
   * @param textureMinificationFilter
   * @returns {Boolean} <code>true</code> if <code>textureMinificationFilter</code> is valid.
   */
  TextureMinificationFilter.validate = function (textureMinificationFilter) {
    return (
      textureMinificationFilter === TextureMinificationFilter.NEAREST ||
      textureMinificationFilter === TextureMinificationFilter.LINEAR ||
      textureMinificationFilter ===
        TextureMinificationFilter.NEAREST_MIPMAP_NEAREST ||
      textureMinificationFilter ===
        TextureMinificationFilter.LINEAR_MIPMAP_NEAREST ||
      textureMinificationFilter ===
        TextureMinificationFilter.NEAREST_MIPMAP_LINEAR ||
      textureMinificationFilter === TextureMinificationFilter.LINEAR_MIPMAP_LINEAR
    );
  };

  var TextureMinificationFilter$1 = Object.freeze(TextureMinificationFilter);

  /**
   * @private
   */
  const TextureWrap = {
    CLAMP_TO_EDGE: WebGLConstants$1.CLAMP_TO_EDGE,
    REPEAT: WebGLConstants$1.REPEAT,
    MIRRORED_REPEAT: WebGLConstants$1.MIRRORED_REPEAT,

    validate: function (textureWrap) {
      return (
        textureWrap === TextureWrap.CLAMP_TO_EDGE ||
        textureWrap === TextureWrap.REPEAT ||
        textureWrap === TextureWrap.MIRRORED_REPEAT
      );
    },
  };
  var TextureWrap$1 = Object.freeze(TextureWrap);

  /**
   * @private
   */
  function Sampler(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const wrapS = defaultValue(options.wrapS, TextureWrap$1.CLAMP_TO_EDGE);
    const wrapT = defaultValue(options.wrapT, TextureWrap$1.CLAMP_TO_EDGE);
    const minificationFilter = defaultValue(
      options.minificationFilter,
      TextureMinificationFilter$1.LINEAR
    );
    const magnificationFilter = defaultValue(
      options.magnificationFilter,
      TextureMagnificationFilter$1.LINEAR
    );
    const maximumAnisotropy = defined(options.maximumAnisotropy)
      ? options.maximumAnisotropy
      : 1.0;

    //>>includeStart('debug', pragmas.debug);
    if (!TextureWrap$1.validate(wrapS)) {
      throw new DeveloperError("Invalid sampler.wrapS.");
    }

    if (!TextureWrap$1.validate(wrapT)) {
      throw new DeveloperError("Invalid sampler.wrapT.");
    }

    if (!TextureMinificationFilter$1.validate(minificationFilter)) {
      throw new DeveloperError("Invalid sampler.minificationFilter.");
    }

    if (!TextureMagnificationFilter$1.validate(magnificationFilter)) {
      throw new DeveloperError("Invalid sampler.magnificationFilter.");
    }

    Check.typeOf.number.greaterThanOrEquals(
      "maximumAnisotropy",
      maximumAnisotropy,
      1.0
    );
    //>>includeEnd('debug');

    this._wrapS = wrapS;
    this._wrapT = wrapT;
    this._minificationFilter = minificationFilter;
    this._magnificationFilter = magnificationFilter;
    this._maximumAnisotropy = maximumAnisotropy;
  }

  Object.defineProperties(Sampler.prototype, {
    wrapS: {
      get: function () {
        return this._wrapS;
      },
    },
    wrapT: {
      get: function () {
        return this._wrapT;
      },
    },
    minificationFilter: {
      get: function () {
        return this._minificationFilter;
      },
    },
    magnificationFilter: {
      get: function () {
        return this._magnificationFilter;
      },
    },
    maximumAnisotropy: {
      get: function () {
        return this._maximumAnisotropy;
      },
    },
  });

  Sampler.equals = function (left, right) {
    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        left._wrapS === right._wrapS &&
        left._wrapT === right._wrapT &&
        left._minificationFilter === right._minificationFilter &&
        left._magnificationFilter === right._magnificationFilter &&
        left._maximumAnisotropy === right._maximumAnisotropy)
    );
  };

  Sampler.NEAREST = Object.freeze(
    new Sampler({
      wrapS: TextureWrap$1.CLAMP_TO_EDGE,
      wrapT: TextureWrap$1.CLAMP_TO_EDGE,
      minificationFilter: TextureMinificationFilter$1.NEAREST,
      magnificationFilter: TextureMagnificationFilter$1.NEAREST,
    })
  );

  /**
   * @private
   */
  function CubeMap(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    Check.defined("options.context", options.context);
    //>>includeEnd('debug');

    const context = options.context;
    const source = options.source;
    let width;
    let height;

    if (defined(source)) {
      const faces = [
        source.positiveX,
        source.negativeX,
        source.positiveY,
        source.negativeY,
        source.positiveZ,
        source.negativeZ,
      ];

      //>>includeStart('debug', pragmas.debug);
      if (
        !faces[0] ||
        !faces[1] ||
        !faces[2] ||
        !faces[3] ||
        !faces[4] ||
        !faces[5]
      ) {
        throw new DeveloperError(
          "options.source requires positiveX, negativeX, positiveY, negativeY, positiveZ, and negativeZ faces."
        );
      }
      //>>includeEnd('debug');

      width = faces[0].width;
      height = faces[0].height;

      //>>includeStart('debug', pragmas.debug);
      for (let i = 1; i < 6; ++i) {
        if (
          Number(faces[i].width) !== width ||
          Number(faces[i].height) !== height
        ) {
          throw new DeveloperError(
            "Each face in options.source must have the same width and height."
          );
        }
      }
      //>>includeEnd('debug');
    } else {
      width = options.width;
      height = options.height;
    }

    const size = width;
    const pixelDatatype = defaultValue(
      options.pixelDatatype,
      PixelDatatype$1.UNSIGNED_BYTE
    );
    const pixelFormat = defaultValue(options.pixelFormat, PixelFormat$1.RGBA);
    const internalFormat = PixelFormat$1.toInternalFormat(
      pixelFormat,
      pixelDatatype,
      context
    );

    //>>includeStart('debug', pragmas.debug);
    if (!defined(width) || !defined(height)) {
      throw new DeveloperError(
        "options requires a source field to create an initialized cube map or width and height fields to create a blank cube map."
      );
    }

    if (width !== height) {
      throw new DeveloperError("Width must equal height.");
    }

    if (size <= 0) {
      throw new DeveloperError("Width and height must be greater than zero.");
    }

    if (size > ContextLimits.maximumCubeMapSize) {
      throw new DeveloperError(
        `Width and height must be less than or equal to the maximum cube map size (${ContextLimits.maximumCubeMapSize}).  Check maximumCubeMapSize.`
      );
    }

    if (!PixelFormat$1.validate(pixelFormat)) {
      throw new DeveloperError("Invalid options.pixelFormat.");
    }

    if (PixelFormat$1.isDepthFormat(pixelFormat)) {
      throw new DeveloperError(
        "options.pixelFormat cannot be DEPTH_COMPONENT or DEPTH_STENCIL."
      );
    }

    if (!PixelDatatype$1.validate(pixelDatatype)) {
      throw new DeveloperError("Invalid options.pixelDatatype.");
    }

    if (pixelDatatype === PixelDatatype$1.FLOAT && !context.floatingPointTexture) {
      throw new DeveloperError(
        "When options.pixelDatatype is FLOAT, this WebGL implementation must support the OES_texture_float extension."
      );
    }

    if (
      pixelDatatype === PixelDatatype$1.HALF_FLOAT &&
      !context.halfFloatingPointTexture
    ) {
      throw new DeveloperError(
        "When options.pixelDatatype is HALF_FLOAT, this WebGL implementation must support the OES_texture_half_float extension."
      );
    }
    //>>includeEnd('debug');

    const sizeInBytes =
      PixelFormat$1.textureSizeInBytes(pixelFormat, pixelDatatype, size, size) * 6;

    // Use premultiplied alpha for opaque textures should perform better on Chrome:
    // http://media.tojicode.com/webglCamp4/#20
    const preMultiplyAlpha =
      options.preMultiplyAlpha ||
      pixelFormat === PixelFormat$1.RGB ||
      pixelFormat === PixelFormat$1.LUMINANCE;
    const flipY = defaultValue(options.flipY, true);
    const skipColorSpaceConversion = defaultValue(
      options.skipColorSpaceConversion,
      false
    );

    const gl = context._gl;
    const textureTarget = gl.TEXTURE_CUBE_MAP;
    const texture = gl.createTexture();

    gl.activeTexture(gl.TEXTURE0);
    gl.bindTexture(textureTarget, texture);

    function createFace(
      target,
      sourceFace,
      preMultiplyAlpha,
      flipY,
      skipColorSpaceConversion
    ) {
      let arrayBufferView = sourceFace.arrayBufferView;
      if (!defined(arrayBufferView)) {
        arrayBufferView = sourceFace.bufferView;
      }

      let unpackAlignment = 4;
      if (defined(arrayBufferView)) {
        unpackAlignment = PixelFormat$1.alignmentInBytes(
          pixelFormat,
          pixelDatatype,
          width
        );
      }

      gl.pixelStorei(gl.UNPACK_ALIGNMENT, unpackAlignment);

      if (skipColorSpaceConversion) {
        gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE);
      } else {
        gl.pixelStorei(
          gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,
          gl.BROWSER_DEFAULT_WEBGL
        );
      }

      if (defined(arrayBufferView)) {
        gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);

        if (flipY) {
          arrayBufferView = PixelFormat$1.flipY(
            arrayBufferView,
            pixelFormat,
            pixelDatatype,
            size,
            size
          );
        }
        gl.texImage2D(
          target,
          0,
          internalFormat,
          size,
          size,
          0,
          pixelFormat,
          PixelDatatype$1.toWebGLConstant(pixelDatatype, context),
          arrayBufferView
        );
      } else {
        // Only valid for DOM-Element uploads
        gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, preMultiplyAlpha);
        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY);

        // Source: ImageData, HTMLImageElement, HTMLCanvasElement, or HTMLVideoElement
        gl.texImage2D(
          target,
          0,
          internalFormat,
          pixelFormat,
          PixelDatatype$1.toWebGLConstant(pixelDatatype, context),
          sourceFace
        );
      }
    }

    if (defined(source)) {
      createFace(
        gl.TEXTURE_CUBE_MAP_POSITIVE_X,
        source.positiveX,
        preMultiplyAlpha,
        flipY,
        skipColorSpaceConversion
      );
      createFace(
        gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
        source.negativeX,
        preMultiplyAlpha,
        flipY,
        skipColorSpaceConversion
      );
      createFace(
        gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
        source.positiveY,
        preMultiplyAlpha,
        flipY,
        skipColorSpaceConversion
      );
      createFace(
        gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
        source.negativeY,
        preMultiplyAlpha,
        flipY,
        skipColorSpaceConversion
      );
      createFace(
        gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
        source.positiveZ,
        preMultiplyAlpha,
        flipY,
        skipColorSpaceConversion
      );
      createFace(
        gl.TEXTURE_CUBE_MAP_NEGATIVE_Z,
        source.negativeZ,
        preMultiplyAlpha,
        flipY,
        skipColorSpaceConversion
      );
    } else {
      gl.texImage2D(
        gl.TEXTURE_CUBE_MAP_POSITIVE_X,
        0,
        internalFormat,
        size,
        size,
        0,
        pixelFormat,
        PixelDatatype$1.toWebGLConstant(pixelDatatype, context),
        null
      );
      gl.texImage2D(
        gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
        0,
        internalFormat,
        size,
        size,
        0,
        pixelFormat,
        PixelDatatype$1.toWebGLConstant(pixelDatatype, context),
        null
      );
      gl.texImage2D(
        gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
        0,
        internalFormat,
        size,
        size,
        0,
        pixelFormat,
        PixelDatatype$1.toWebGLConstant(pixelDatatype, context),
        null
      );
      gl.texImage2D(
        gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
        0,
        internalFormat,
        size,
        size,
        0,
        pixelFormat,
        PixelDatatype$1.toWebGLConstant(pixelDatatype, context),
        null
      );
      gl.texImage2D(
        gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
        0,
        internalFormat,
        size,
        size,
        0,
        pixelFormat,
        PixelDatatype$1.toWebGLConstant(pixelDatatype, context),
        null
      );
      gl.texImage2D(
        gl.TEXTURE_CUBE_MAP_NEGATIVE_Z,
        0,
        internalFormat,
        size,
        size,
        0,
        pixelFormat,
        PixelDatatype$1.toWebGLConstant(pixelDatatype, context),
        null
      );
    }
    gl.bindTexture(textureTarget, null);

    this._context = context;
    this._textureFilterAnisotropic = context._textureFilterAnisotropic;
    this._textureTarget = textureTarget;
    this._texture = texture;
    this._pixelFormat = pixelFormat;
    this._pixelDatatype = pixelDatatype;
    this._size = size;
    this._hasMipmap = false;
    this._sizeInBytes = sizeInBytes;
    this._preMultiplyAlpha = preMultiplyAlpha;
    this._flipY = flipY;
    this._sampler = undefined;

    const initialized = defined(source);
    this._positiveX = new CubeMapFace(
      context,
      texture,
      textureTarget,
      gl.TEXTURE_CUBE_MAP_POSITIVE_X,
      internalFormat,
      pixelFormat,
      pixelDatatype,
      size,
      preMultiplyAlpha,
      flipY,
      initialized
    );
    this._negativeX = new CubeMapFace(
      context,
      texture,
      textureTarget,
      gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
      internalFormat,
      pixelFormat,
      pixelDatatype,
      size,
      preMultiplyAlpha,
      flipY,
      initialized
    );
    this._positiveY = new CubeMapFace(
      context,
      texture,
      textureTarget,
      gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
      internalFormat,
      pixelFormat,
      pixelDatatype,
      size,
      preMultiplyAlpha,
      flipY,
      initialized
    );
    this._negativeY = new CubeMapFace(
      context,
      texture,
      textureTarget,
      gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
      internalFormat,
      pixelFormat,
      pixelDatatype,
      size,
      preMultiplyAlpha,
      flipY,
      initialized
    );
    this._positiveZ = new CubeMapFace(
      context,
      texture,
      textureTarget,
      gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
      internalFormat,
      pixelFormat,
      pixelDatatype,
      size,
      preMultiplyAlpha,
      flipY,
      initialized
    );
    this._negativeZ = new CubeMapFace(
      context,
      texture,
      textureTarget,
      gl.TEXTURE_CUBE_MAP_NEGATIVE_Z,
      internalFormat,
      pixelFormat,
      pixelDatatype,
      size,
      preMultiplyAlpha,
      flipY,
      initialized
    );

    this.sampler = defined(options.sampler) ? options.sampler : new Sampler();
  }

  Object.defineProperties(CubeMap.prototype, {
    positiveX: {
      get: function () {
        return this._positiveX;
      },
    },
    negativeX: {
      get: function () {
        return this._negativeX;
      },
    },
    positiveY: {
      get: function () {
        return this._positiveY;
      },
    },
    negativeY: {
      get: function () {
        return this._negativeY;
      },
    },
    positiveZ: {
      get: function () {
        return this._positiveZ;
      },
    },
    negativeZ: {
      get: function () {
        return this._negativeZ;
      },
    },
    sampler: {
      get: function () {
        return this._sampler;
      },
      set: function (sampler) {
        let minificationFilter = sampler.minificationFilter;
        let magnificationFilter = sampler.magnificationFilter;

        const mipmap =
          minificationFilter ===
            TextureMinificationFilter$1.NEAREST_MIPMAP_NEAREST ||
          minificationFilter ===
            TextureMinificationFilter$1.NEAREST_MIPMAP_LINEAR ||
          minificationFilter ===
            TextureMinificationFilter$1.LINEAR_MIPMAP_NEAREST ||
          minificationFilter === TextureMinificationFilter$1.LINEAR_MIPMAP_LINEAR;

        const context = this._context;
        const pixelDatatype = this._pixelDatatype;

        // float textures only support nearest filtering unless the linear extensions are supported, so override the sampler's settings
        if (
          (pixelDatatype === PixelDatatype$1.FLOAT &&
            !context.textureFloatLinear) ||
          (pixelDatatype === PixelDatatype$1.HALF_FLOAT &&
            !context.textureHalfFloatLinear)
        ) {
          minificationFilter = mipmap
            ? TextureMinificationFilter$1.NEAREST_MIPMAP_NEAREST
            : TextureMinificationFilter$1.NEAREST;
          magnificationFilter = TextureMagnificationFilter$1.NEAREST;
        }

        const gl = context._gl;
        const target = this._textureTarget;

        gl.activeTexture(gl.TEXTURE0);
        gl.bindTexture(target, this._texture);
        gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, minificationFilter);
        gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, magnificationFilter);
        gl.texParameteri(target, gl.TEXTURE_WRAP_S, sampler.wrapS);
        gl.texParameteri(target, gl.TEXTURE_WRAP_T, sampler.wrapT);
        if (defined(this._textureFilterAnisotropic)) {
          gl.texParameteri(
            target,
            this._textureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,
            sampler.maximumAnisotropy
          );
        }
        gl.bindTexture(target, null);

        this._sampler = sampler;
      },
    },
    pixelFormat: {
      get: function () {
        return this._pixelFormat;
      },
    },
    pixelDatatype: {
      get: function () {
        return this._pixelDatatype;
      },
    },
    width: {
      get: function () {
        return this._size;
      },
    },
    height: {
      get: function () {
        return this._size;
      },
    },
    sizeInBytes: {
      get: function () {
        if (this._hasMipmap) {
          return Math.floor((this._sizeInBytes * 4) / 3);
        }
        return this._sizeInBytes;
      },
    },
    preMultiplyAlpha: {
      get: function () {
        return this._preMultiplyAlpha;
      },
    },
    flipY: {
      get: function () {
        return this._flipY;
      },
    },

    _target: {
      get: function () {
        return this._textureTarget;
      },
    },
  });

  /**
   * Generates a complete mipmap chain for each cubemap face.
   *
   * @param {MipmapHint} [hint=MipmapHint.DONT_CARE] A performance vs. quality hint.
   *
   * @exception {DeveloperError} hint is invalid.
   * @exception {DeveloperError} This CubeMap's width must be a power of two to call generateMipmap().
   * @exception {DeveloperError} This CubeMap's height must be a power of two to call generateMipmap().
   * @exception {DeveloperError} This CubeMap was destroyed, i.e., destroy() was called.
   *
   * @example
   * // Generate mipmaps, and then set the sampler so mipmaps are used for
   * // minification when the cube map is sampled.
   * cubeMap.generateMipmap();
   * cubeMap.sampler = new Sampler({
   *   minificationFilter : Cesium.TextureMinificationFilter.NEAREST_MIPMAP_LINEAR
   * });
   */
  CubeMap.prototype.generateMipmap = function (hint) {
    hint = defaultValue(hint, MipmapHint$1.DONT_CARE);

    //>>includeStart('debug', pragmas.debug);
    if (this._size > 1 && !CesiumMath.isPowerOfTwo(this._size)) {
      throw new DeveloperError(
        "width and height must be a power of two to call generateMipmap()."
      );
    }
    if (!MipmapHint$1.validate(hint)) {
      throw new DeveloperError("hint is invalid.");
    }
    //>>includeEnd('debug');

    this._hasMipmap = true;

    const gl = this._context._gl;
    const target = this._textureTarget;
    gl.hint(gl.GENERATE_MIPMAP_HINT, hint);
    gl.activeTexture(gl.TEXTURE0);
    gl.bindTexture(target, this._texture);
    gl.generateMipmap(target);
    gl.bindTexture(target, null);
  };

  CubeMap.prototype.isDestroyed = function () {
    return false;
  };

  CubeMap.prototype.destroy = function () {
    this._context._gl.deleteTexture(this._texture);
    this._positiveX = destroyObject(this._positiveX);
    this._negativeX = destroyObject(this._negativeX);
    this._positiveY = destroyObject(this._positiveY);
    this._negativeY = destroyObject(this._negativeY);
    this._positiveZ = destroyObject(this._positiveZ);
    this._negativeZ = destroyObject(this._negativeZ);
    return destroyObject(this);
  };

  /**
   * @private
   */
  function Texture(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    Check.defined("options.context", options.context);
    //>>includeEnd('debug');

    const context = options.context;
    let width = options.width;
    let height = options.height;
    const source = options.source;

    if (defined(source)) {
      if (!defined(width)) {
        width = defaultValue(source.videoWidth, source.width);
      }
      if (!defined(height)) {
        height = defaultValue(source.videoHeight, source.height);
      }
    }

    const pixelFormat = defaultValue(options.pixelFormat, PixelFormat$1.RGBA);
    const pixelDatatype = defaultValue(
      options.pixelDatatype,
      PixelDatatype$1.UNSIGNED_BYTE
    );
    const internalFormat = PixelFormat$1.toInternalFormat(
      pixelFormat,
      pixelDatatype,
      context
    );

    const isCompressed = PixelFormat$1.isCompressedFormat(internalFormat);

    //>>includeStart('debug', pragmas.debug);
    if (!defined(width) || !defined(height)) {
      throw new DeveloperError(
        "options requires a source field to create an initialized texture or width and height fields to create a blank texture."
      );
    }

    Check.typeOf.number.greaterThan("width", width, 0);

    if (width > ContextLimits.maximumTextureSize) {
      throw new DeveloperError(
        `Width must be less than or equal to the maximum texture size (${ContextLimits.maximumTextureSize}).  Check maximumTextureSize.`
      );
    }

    Check.typeOf.number.greaterThan("height", height, 0);

    if (height > ContextLimits.maximumTextureSize) {
      throw new DeveloperError(
        `Height must be less than or equal to the maximum texture size (${ContextLimits.maximumTextureSize}).  Check maximumTextureSize.`
      );
    }

    if (!PixelFormat$1.validate(pixelFormat)) {
      throw new DeveloperError("Invalid options.pixelFormat.");
    }

    if (!isCompressed && !PixelDatatype$1.validate(pixelDatatype)) {
      throw new DeveloperError("Invalid options.pixelDatatype.");
    }

    if (
      pixelFormat === PixelFormat$1.DEPTH_COMPONENT &&
      pixelDatatype !== PixelDatatype$1.UNSIGNED_SHORT &&
      pixelDatatype !== PixelDatatype$1.UNSIGNED_INT
    ) {
      throw new DeveloperError(
        "When options.pixelFormat is DEPTH_COMPONENT, options.pixelDatatype must be UNSIGNED_SHORT or UNSIGNED_INT."
      );
    }

    if (
      pixelFormat === PixelFormat$1.DEPTH_STENCIL &&
      pixelDatatype !== PixelDatatype$1.UNSIGNED_INT_24_8
    ) {
      throw new DeveloperError(
        "When options.pixelFormat is DEPTH_STENCIL, options.pixelDatatype must be UNSIGNED_INT_24_8."
      );
    }

    if (pixelDatatype === PixelDatatype$1.FLOAT && !context.floatingPointTexture) {
      throw new DeveloperError(
        "When options.pixelDatatype is FLOAT, this WebGL implementation must support the OES_texture_float extension.  Check context.floatingPointTexture."
      );
    }

    if (
      pixelDatatype === PixelDatatype$1.HALF_FLOAT &&
      !context.halfFloatingPointTexture
    ) {
      throw new DeveloperError(
        "When options.pixelDatatype is HALF_FLOAT, this WebGL implementation must support the OES_texture_half_float extension. Check context.halfFloatingPointTexture."
      );
    }

    if (PixelFormat$1.isDepthFormat(pixelFormat)) {
      if (defined(source)) {
        throw new DeveloperError(
          "When options.pixelFormat is DEPTH_COMPONENT or DEPTH_STENCIL, source cannot be provided."
        );
      }

      if (!context.depthTexture) {
        throw new DeveloperError(
          "When options.pixelFormat is DEPTH_COMPONENT or DEPTH_STENCIL, this WebGL implementation must support WEBGL_depth_texture.  Check context.depthTexture."
        );
      }
    }

    if (isCompressed) {
      if (!defined(source) || !defined(source.arrayBufferView)) {
        throw new DeveloperError(
          "When options.pixelFormat is compressed, options.source.arrayBufferView must be defined."
        );
      }

      if (PixelFormat$1.isDXTFormat(internalFormat) && !context.s3tc) {
        throw new DeveloperError(
          "When options.pixelFormat is S3TC compressed, this WebGL implementation must support the WEBGL_compressed_texture_s3tc extension. Check context.s3tc."
        );
      } else if (PixelFormat$1.isPVRTCFormat(internalFormat) && !context.pvrtc) {
        throw new DeveloperError(
          "When options.pixelFormat is PVRTC compressed, this WebGL implementation must support the WEBGL_compressed_texture_pvrtc extension. Check context.pvrtc."
        );
      } else if (PixelFormat$1.isASTCFormat(internalFormat) && !context.astc) {
        throw new DeveloperError(
          "When options.pixelFormat is ASTC compressed, this WebGL implementation must support the WEBGL_compressed_texture_astc extension. Check context.astc."
        );
      } else if (PixelFormat$1.isETC2Format(internalFormat) && !context.etc) {
        throw new DeveloperError(
          "When options.pixelFormat is ETC2 compressed, this WebGL implementation must support the WEBGL_compressed_texture_etc extension. Check context.etc."
        );
      } else if (PixelFormat$1.isETC1Format(internalFormat) && !context.etc1) {
        throw new DeveloperError(
          "When options.pixelFormat is ETC1 compressed, this WebGL implementation must support the WEBGL_compressed_texture_etc1 extension. Check context.etc1."
        );
      } else if (PixelFormat$1.isBC7Format(internalFormat) && !context.bc7) {
        throw new DeveloperError(
          "When options.pixelFormat is BC7 compressed, this WebGL implementation must support the EXT_texture_compression_bptc extension. Check context.bc7."
        );
      }

      if (
        PixelFormat$1.compressedTextureSizeInBytes(
          internalFormat,
          width,
          height
        ) !== source.arrayBufferView.byteLength
      ) {
        throw new DeveloperError(
          "The byte length of the array buffer is invalid for the compressed texture with the given width and height."
        );
      }
    }
    //>>includeEnd('debug');

    // Use premultiplied alpha for opaque textures should perform better on Chrome:
    // http://media.tojicode.com/webglCamp4/#20
    const preMultiplyAlpha =
      options.preMultiplyAlpha ||
      pixelFormat === PixelFormat$1.RGB ||
      pixelFormat === PixelFormat$1.LUMINANCE;
    const flipY = defaultValue(options.flipY, true);
    const skipColorSpaceConversion = defaultValue(
      options.skipColorSpaceConversion,
      false
    );

    let initialized = true;

    const gl = context._gl;
    const textureTarget = gl.TEXTURE_2D;
    const texture = gl.createTexture();

    gl.activeTexture(gl.TEXTURE0);
    gl.bindTexture(textureTarget, texture);

    let unpackAlignment = 4;
    if (defined(source) && defined(source.arrayBufferView) && !isCompressed) {
      unpackAlignment = PixelFormat$1.alignmentInBytes(
        pixelFormat,
        pixelDatatype,
        width
      );
    }

    gl.pixelStorei(gl.UNPACK_ALIGNMENT, unpackAlignment);

    if (skipColorSpaceConversion) {
      gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE);
    } else {
      gl.pixelStorei(
        gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,
        gl.BROWSER_DEFAULT_WEBGL
      );
    }

    if (defined(source)) {
      if (defined(source.arrayBufferView)) {
        gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);

        // Source: typed array
        let arrayBufferView = source.arrayBufferView;
        let i, mipWidth, mipHeight;
        if (isCompressed) {
          gl.compressedTexImage2D(
            textureTarget,
            0,
            internalFormat,
            width,
            height,
            0,
            arrayBufferView
          );
          if (defined(source.mipLevels)) {
            mipWidth = width;
            mipHeight = height;
            for (i = 0; i < source.mipLevels.length; ++i) {
              mipWidth = Math.floor(mipWidth / 2) | 0;
              if (mipWidth < 1) {
                mipWidth = 1;
              }
              mipHeight = Math.floor(mipHeight / 2) | 0;
              if (mipHeight < 1) {
                mipHeight = 1;
              }
              gl.compressedTexImage2D(
                textureTarget,
                i + 1,
                internalFormat,
                mipWidth,
                mipHeight,
                0,
                source.mipLevels[i]
              );
            }
          }
        } else {
          if (flipY) {
            arrayBufferView = PixelFormat$1.flipY(
              arrayBufferView,
              pixelFormat,
              pixelDatatype,
              width,
              height
            );
          }
          gl.texImage2D(
            textureTarget,
            0,
            internalFormat,
            width,
            height,
            0,
            pixelFormat,
            PixelDatatype$1.toWebGLConstant(pixelDatatype, context),
            arrayBufferView
          );

          if (defined(source.mipLevels)) {
            mipWidth = width;
            mipHeight = height;
            for (i = 0; i < source.mipLevels.length; ++i) {
              mipWidth = Math.floor(mipWidth / 2) | 0;
              if (mipWidth < 1) {
                mipWidth = 1;
              }
              mipHeight = Math.floor(mipHeight / 2) | 0;
              if (mipHeight < 1) {
                mipHeight = 1;
              }
              gl.texImage2D(
                textureTarget,
                i + 1,
                internalFormat,
                mipWidth,
                mipHeight,
                0,
                pixelFormat,
                PixelDatatype$1.toWebGLConstant(pixelDatatype, context),
                source.mipLevels[i]
              );
            }
          }
        }
      } else if (defined(source.framebuffer)) {
        gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);

        // Source: framebuffer
        if (source.framebuffer !== context.defaultFramebuffer) {
          source.framebuffer._bind();
        }

        gl.copyTexImage2D(
          textureTarget,
          0,
          internalFormat,
          source.xOffset,
          source.yOffset,
          width,
          height,
          0
        );

        if (source.framebuffer !== context.defaultFramebuffer) {
          source.framebuffer._unBind();
        }
      } else {
        // Only valid for DOM-Element uploads
        gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, preMultiplyAlpha);
        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY);

        // Source: ImageData, HTMLImageElement, HTMLCanvasElement, or HTMLVideoElement
        gl.texImage2D(
          textureTarget,
          0,
          internalFormat,
          pixelFormat,
          PixelDatatype$1.toWebGLConstant(pixelDatatype, context),
          source
        );
      }
    } else {
      gl.texImage2D(
        textureTarget,
        0,
        internalFormat,
        width,
        height,
        0,
        pixelFormat,
        PixelDatatype$1.toWebGLConstant(pixelDatatype, context),
        null
      );
      initialized = false;
    }
    gl.bindTexture(textureTarget, null);

    let sizeInBytes;
    if (isCompressed) {
      sizeInBytes = PixelFormat$1.compressedTextureSizeInBytes(
        pixelFormat,
        width,
        height
      );
    } else {
      sizeInBytes = PixelFormat$1.textureSizeInBytes(
        pixelFormat,
        pixelDatatype,
        width,
        height
      );
    }

    this._id = createGuid();
    this._context = context;
    this._textureFilterAnisotropic = context._textureFilterAnisotropic;
    this._textureTarget = textureTarget;
    this._texture = texture;
    this._internalFormat = internalFormat;
    this._pixelFormat = pixelFormat;
    this._pixelDatatype = pixelDatatype;
    this._width = width;
    this._height = height;
    this._dimensions = new Cartesian2(width, height);
    this._hasMipmap = false;
    this._sizeInBytes = sizeInBytes;
    this._preMultiplyAlpha = preMultiplyAlpha;
    this._flipY = flipY;
    this._initialized = initialized;
    this._sampler = undefined;

    this.sampler = defined(options.sampler) ? options.sampler : new Sampler();
  }

  /**
   * This function is identical to using the Texture constructor except that it can be
   * replaced with a mock/spy in tests.
   * @private
   */
  Texture.create = function (options) {
    return new Texture(options);
  };

  /**
   * Creates a texture, and copies a subimage of the framebuffer to it.  When called without arguments,
   * the texture is the same width and height as the framebuffer and contains its contents.
   *
   * @param {Object} options Object with the following properties:
   * @param {Context} options.context The context in which the Texture gets created.
   * @param {PixelFormat} [options.pixelFormat=PixelFormat.RGB] The texture's internal pixel format.
   * @param {Number} [options.framebufferXOffset=0] An offset in the x direction in the framebuffer where copying begins from.
   * @param {Number} [options.framebufferYOffset=0] An offset in the y direction in the framebuffer where copying begins from.
   * @param {Number} [options.width=canvas.clientWidth] The width of the texture in texels.
   * @param {Number} [options.height=canvas.clientHeight] The height of the texture in texels.
   * @param {Framebuffer} [options.framebuffer=defaultFramebuffer] The framebuffer from which to create the texture.  If this
   *        parameter is not specified, the default framebuffer is used.
   * @returns {Texture} A texture with contents from the framebuffer.
   *
   * @exception {DeveloperError} Invalid pixelFormat.
   * @exception {DeveloperError} pixelFormat cannot be DEPTH_COMPONENT, DEPTH_STENCIL or a compressed format.
   * @exception {DeveloperError} framebufferXOffset must be greater than or equal to zero.
   * @exception {DeveloperError} framebufferYOffset must be greater than or equal to zero.
   * @exception {DeveloperError} framebufferXOffset + width must be less than or equal to canvas.clientWidth.
   * @exception {DeveloperError} framebufferYOffset + height must be less than or equal to canvas.clientHeight.
   *
   *
   * @example
   * // Create a texture with the contents of the framebuffer.
   * const t = Texture.fromFramebuffer({
   *     context : context
   * });
   *
   * @see Sampler
   *
   * @private
   */
  Texture.fromFramebuffer = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    Check.defined("options.context", options.context);
    //>>includeEnd('debug');

    const context = options.context;
    const gl = context._gl;

    const pixelFormat = defaultValue(options.pixelFormat, PixelFormat$1.RGB);
    const framebufferXOffset = defaultValue(options.framebufferXOffset, 0);
    const framebufferYOffset = defaultValue(options.framebufferYOffset, 0);
    const width = defaultValue(options.width, gl.drawingBufferWidth);
    const height = defaultValue(options.height, gl.drawingBufferHeight);
    const framebuffer = options.framebuffer;

    //>>includeStart('debug', pragmas.debug);
    if (!PixelFormat$1.validate(pixelFormat)) {
      throw new DeveloperError("Invalid pixelFormat.");
    }
    if (
      PixelFormat$1.isDepthFormat(pixelFormat) ||
      PixelFormat$1.isCompressedFormat(pixelFormat)
    ) {
      throw new DeveloperError(
        "pixelFormat cannot be DEPTH_COMPONENT, DEPTH_STENCIL or a compressed format."
      );
    }
    Check.defined("options.context", options.context);
    Check.typeOf.number.greaterThanOrEquals(
      "framebufferXOffset",
      framebufferXOffset,
      0
    );
    Check.typeOf.number.greaterThanOrEquals(
      "framebufferYOffset",
      framebufferYOffset,
      0
    );
    if (framebufferXOffset + width > gl.drawingBufferWidth) {
      throw new DeveloperError(
        "framebufferXOffset + width must be less than or equal to drawingBufferWidth"
      );
    }
    if (framebufferYOffset + height > gl.drawingBufferHeight) {
      throw new DeveloperError(
        "framebufferYOffset + height must be less than or equal to drawingBufferHeight."
      );
    }
    //>>includeEnd('debug');

    const texture = new Texture({
      context: context,
      width: width,
      height: height,
      pixelFormat: pixelFormat,
      source: {
        framebuffer: defined(framebuffer)
          ? framebuffer
          : context.defaultFramebuffer,
        xOffset: framebufferXOffset,
        yOffset: framebufferYOffset,
        width: width,
        height: height,
      },
    });

    return texture;
  };

  Object.defineProperties(Texture.prototype, {
    /**
     * A unique id for the texture
     * @memberof Texture.prototype
     * @type {String}
     * @readonly
     * @private
     */
    id: {
      get: function () {
        return this._id;
      },
    },
    /**
     * The sampler to use when sampling this texture.
     * Create a sampler by calling {@link Sampler}.  If this
     * parameter is not specified, a default sampler is used.  The default sampler clamps texture
     * coordinates in both directions, uses linear filtering for both magnification and minification,
     * and uses a maximum anisotropy of 1.0.
     * @memberof Texture.prototype
     * @type {Object}
     */
    sampler: {
      get: function () {
        return this._sampler;
      },
      set: function (sampler) {
        let minificationFilter = sampler.minificationFilter;
        let magnificationFilter = sampler.magnificationFilter;
        const context = this._context;
        const pixelFormat = this._pixelFormat;
        const pixelDatatype = this._pixelDatatype;

        const mipmap =
          minificationFilter ===
            TextureMinificationFilter$1.NEAREST_MIPMAP_NEAREST ||
          minificationFilter ===
            TextureMinificationFilter$1.NEAREST_MIPMAP_LINEAR ||
          minificationFilter ===
            TextureMinificationFilter$1.LINEAR_MIPMAP_NEAREST ||
          minificationFilter === TextureMinificationFilter$1.LINEAR_MIPMAP_LINEAR;

        // float textures only support nearest filtering unless the linear extensions are supported, so override the sampler's settings
        if (
          (pixelDatatype === PixelDatatype$1.FLOAT &&
            !context.textureFloatLinear) ||
          (pixelDatatype === PixelDatatype$1.HALF_FLOAT &&
            !context.textureHalfFloatLinear)
        ) {
          minificationFilter = mipmap
            ? TextureMinificationFilter$1.NEAREST_MIPMAP_NEAREST
            : TextureMinificationFilter$1.NEAREST;
          magnificationFilter = TextureMagnificationFilter$1.NEAREST;
        }

        // WebGL 2 depth texture only support nearest filtering. See section 3.8.13 OpenGL ES 3 spec
        if (context.webgl2) {
          if (PixelFormat$1.isDepthFormat(pixelFormat)) {
            minificationFilter = TextureMinificationFilter$1.NEAREST;
            magnificationFilter = TextureMagnificationFilter$1.NEAREST;
          }
        }

        const gl = context._gl;
        const target = this._textureTarget;

        gl.activeTexture(gl.TEXTURE0);
        gl.bindTexture(target, this._texture);
        gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, minificationFilter);
        gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, magnificationFilter);
        gl.texParameteri(target, gl.TEXTURE_WRAP_S, sampler.wrapS);
        gl.texParameteri(target, gl.TEXTURE_WRAP_T, sampler.wrapT);
        if (defined(this._textureFilterAnisotropic)) {
          gl.texParameteri(
            target,
            this._textureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,
            sampler.maximumAnisotropy
          );
        }
        gl.bindTexture(target, null);

        this._sampler = sampler;
      },
    },
    pixelFormat: {
      get: function () {
        return this._pixelFormat;
      },
    },
    pixelDatatype: {
      get: function () {
        return this._pixelDatatype;
      },
    },
    dimensions: {
      get: function () {
        return this._dimensions;
      },
    },
    preMultiplyAlpha: {
      get: function () {
        return this._preMultiplyAlpha;
      },
    },
    flipY: {
      get: function () {
        return this._flipY;
      },
    },
    width: {
      get: function () {
        return this._width;
      },
    },
    height: {
      get: function () {
        return this._height;
      },
    },
    sizeInBytes: {
      get: function () {
        if (this._hasMipmap) {
          return Math.floor((this._sizeInBytes * 4) / 3);
        }
        return this._sizeInBytes;
      },
    },
    _target: {
      get: function () {
        return this._textureTarget;
      },
    },
  });

  /**
   * Copy new image data into this texture, from a source {@link ImageData}, {@link HTMLImageElement}, {@link HTMLCanvasElement}, or {@link HTMLVideoElement}.
   * or an object with width, height, and arrayBufferView properties.
   * @param {Object} options Object with the following properties:
   * @param {Object} options.source The source {@link ImageData}, {@link HTMLImageElement}, {@link HTMLCanvasElement}, or {@link HTMLVideoElement},
   *                        or an object with width, height, and arrayBufferView properties.
   * @param {Number} [options.xOffset=0] The offset in the x direction within the texture to copy into.
   * @param {Number} [options.yOffset=0] The offset in the y direction within the texture to copy into.
   * @param {Boolean} [options.skipColorSpaceConversion=false] If true, any custom gamma or color profiles in the texture will be ignored.
   *
   * @exception {DeveloperError} Cannot call copyFrom when the texture pixel format is DEPTH_COMPONENT or DEPTH_STENCIL.
   * @exception {DeveloperError} Cannot call copyFrom with a compressed texture pixel format.
   * @exception {DeveloperError} xOffset must be greater than or equal to zero.
   * @exception {DeveloperError} yOffset must be greater than or equal to zero.
   * @exception {DeveloperError} xOffset + source.width must be less than or equal to width.
   * @exception {DeveloperError} yOffset + source.height must be less than or equal to height.
   * @exception {DeveloperError} This texture was destroyed, i.e., destroy() was called.
   *
   * @example
   * texture.copyFrom({
   *  source: {
   *   width : 1,
   *   height : 1,
   *   arrayBufferView : new Uint8Array([255, 0, 0, 255])
   *  }
   * });
   */
  Texture.prototype.copyFrom = function (options) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("options", options);
    //>>includeEnd('debug');

    const xOffset = defaultValue(options.xOffset, 0);
    const yOffset = defaultValue(options.yOffset, 0);

    //>>includeStart('debug', pragmas.debug);
    Check.defined("options.source", options.source);
    if (PixelFormat$1.isDepthFormat(this._pixelFormat)) {
      throw new DeveloperError(
        "Cannot call copyFrom when the texture pixel format is DEPTH_COMPONENT or DEPTH_STENCIL."
      );
    }
    if (PixelFormat$1.isCompressedFormat(this._pixelFormat)) {
      throw new DeveloperError(
        "Cannot call copyFrom with a compressed texture pixel format."
      );
    }
    Check.typeOf.number.greaterThanOrEquals("xOffset", xOffset, 0);
    Check.typeOf.number.greaterThanOrEquals("yOffset", yOffset, 0);
    Check.typeOf.number.lessThanOrEquals(
      "xOffset + options.source.width",
      xOffset + options.source.width,
      this._width
    );
    Check.typeOf.number.lessThanOrEquals(
      "yOffset + options.source.height",
      yOffset + options.source.height,
      this._height
    );
    //>>includeEnd('debug');

    const source = options.source;

    const context = this._context;
    const gl = context._gl;
    const target = this._textureTarget;

    gl.activeTexture(gl.TEXTURE0);
    gl.bindTexture(target, this._texture);

    const width = source.width;
    const height = source.height;
    let arrayBufferView = source.arrayBufferView;

    const textureWidth = this._width;
    const textureHeight = this._height;
    const internalFormat = this._internalFormat;
    const pixelFormat = this._pixelFormat;
    const pixelDatatype = this._pixelDatatype;

    const preMultiplyAlpha = this._preMultiplyAlpha;
    const flipY = this._flipY;
    const skipColorSpaceConversion = defaultValue(
      options.skipColorSpaceConversion,
      false
    );

    let unpackAlignment = 4;
    if (defined(arrayBufferView)) {
      unpackAlignment = PixelFormat$1.alignmentInBytes(
        pixelFormat,
        pixelDatatype,
        width
      );
    }

    gl.pixelStorei(gl.UNPACK_ALIGNMENT, unpackAlignment);

    if (skipColorSpaceConversion) {
      gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE);
    } else {
      gl.pixelStorei(
        gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,
        gl.BROWSER_DEFAULT_WEBGL
      );
    }

    let uploaded = false;
    if (!this._initialized) {
      if (
        xOffset === 0 &&
        yOffset === 0 &&
        width === textureWidth &&
        height === textureHeight
      ) {
        // initialize the entire texture
        if (defined(arrayBufferView)) {
          gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
          gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);

          if (flipY) {
            arrayBufferView = PixelFormat$1.flipY(
              arrayBufferView,
              pixelFormat,
              pixelDatatype,
              textureWidth,
              textureHeight
            );
          }
          gl.texImage2D(
            target,
            0,
            internalFormat,
            textureWidth,
            textureHeight,
            0,
            pixelFormat,
            PixelDatatype$1.toWebGLConstant(pixelDatatype, context),
            arrayBufferView
          );
        } else {
          // Only valid for DOM-Element uploads
          gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, preMultiplyAlpha);
          gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY);

          gl.texImage2D(
            target,
            0,
            internalFormat,
            pixelFormat,
            PixelDatatype$1.toWebGLConstant(pixelDatatype, context),
            source
          );
        }
        uploaded = true;
      } else {
        gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);

        // initialize the entire texture to zero
        const bufferView = PixelFormat$1.createTypedArray(
          pixelFormat,
          pixelDatatype,
          textureWidth,
          textureHeight
        );
        gl.texImage2D(
          target,
          0,
          internalFormat,
          textureWidth,
          textureHeight,
          0,
          pixelFormat,
          PixelDatatype$1.toWebGLConstant(pixelDatatype, context),
          bufferView
        );
      }
      this._initialized = true;
    }

    if (!uploaded) {
      if (defined(arrayBufferView)) {
        gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);

        if (flipY) {
          arrayBufferView = PixelFormat$1.flipY(
            arrayBufferView,
            pixelFormat,
            pixelDatatype,
            width,
            height
          );
        }
        gl.texSubImage2D(
          target,
          0,
          xOffset,
          yOffset,
          width,
          height,
          pixelFormat,
          PixelDatatype$1.toWebGLConstant(pixelDatatype, context),
          arrayBufferView
        );
      } else {
        // Only valid for DOM-Element uploads
        gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, preMultiplyAlpha);
        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY);

        gl.texSubImage2D(
          target,
          0,
          xOffset,
          yOffset,
          pixelFormat,
          PixelDatatype$1.toWebGLConstant(pixelDatatype, context),
          source
        );
      }
    }

    gl.bindTexture(target, null);
  };

  /**
   * @param {Number} [xOffset=0] The offset in the x direction within the texture to copy into.
   * @param {Number} [yOffset=0] The offset in the y direction within the texture to copy into.
   * @param {Number} [framebufferXOffset=0] optional
   * @param {Number} [framebufferYOffset=0] optional
   * @param {Number} [width=width] optional
   * @param {Number} [height=height] optional
   *
   * @exception {DeveloperError} Cannot call copyFromFramebuffer when the texture pixel format is DEPTH_COMPONENT or DEPTH_STENCIL.
   * @exception {DeveloperError} Cannot call copyFromFramebuffer when the texture pixel data type is FLOAT.
   * @exception {DeveloperError} Cannot call copyFromFramebuffer when the texture pixel data type is HALF_FLOAT.
   * @exception {DeveloperError} Cannot call copyFrom with a compressed texture pixel format.
   * @exception {DeveloperError} This texture was destroyed, i.e., destroy() was called.
   * @exception {DeveloperError} xOffset must be greater than or equal to zero.
   * @exception {DeveloperError} yOffset must be greater than or equal to zero.
   * @exception {DeveloperError} framebufferXOffset must be greater than or equal to zero.
   * @exception {DeveloperError} framebufferYOffset must be greater than or equal to zero.
   * @exception {DeveloperError} xOffset + width must be less than or equal to width.
   * @exception {DeveloperError} yOffset + height must be less than or equal to height.
   */
  Texture.prototype.copyFromFramebuffer = function (
    xOffset,
    yOffset,
    framebufferXOffset,
    framebufferYOffset,
    width,
    height
  ) {
    xOffset = defaultValue(xOffset, 0);
    yOffset = defaultValue(yOffset, 0);
    framebufferXOffset = defaultValue(framebufferXOffset, 0);
    framebufferYOffset = defaultValue(framebufferYOffset, 0);
    width = defaultValue(width, this._width);
    height = defaultValue(height, this._height);

    //>>includeStart('debug', pragmas.debug);
    if (PixelFormat$1.isDepthFormat(this._pixelFormat)) {
      throw new DeveloperError(
        "Cannot call copyFromFramebuffer when the texture pixel format is DEPTH_COMPONENT or DEPTH_STENCIL."
      );
    }
    if (this._pixelDatatype === PixelDatatype$1.FLOAT) {
      throw new DeveloperError(
        "Cannot call copyFromFramebuffer when the texture pixel data type is FLOAT."
      );
    }
    if (this._pixelDatatype === PixelDatatype$1.HALF_FLOAT) {
      throw new DeveloperError(
        "Cannot call copyFromFramebuffer when the texture pixel data type is HALF_FLOAT."
      );
    }
    if (PixelFormat$1.isCompressedFormat(this._pixelFormat)) {
      throw new DeveloperError(
        "Cannot call copyFrom with a compressed texture pixel format."
      );
    }

    Check.typeOf.number.greaterThanOrEquals("xOffset", xOffset, 0);
    Check.typeOf.number.greaterThanOrEquals("yOffset", yOffset, 0);
    Check.typeOf.number.greaterThanOrEquals(
      "framebufferXOffset",
      framebufferXOffset,
      0
    );
    Check.typeOf.number.greaterThanOrEquals(
      "framebufferYOffset",
      framebufferYOffset,
      0
    );
    Check.typeOf.number.lessThanOrEquals(
      "xOffset + width",
      xOffset + width,
      this._width
    );
    Check.typeOf.number.lessThanOrEquals(
      "yOffset + height",
      yOffset + height,
      this._height
    );
    //>>includeEnd('debug');

    const gl = this._context._gl;
    const target = this._textureTarget;

    gl.activeTexture(gl.TEXTURE0);
    gl.bindTexture(target, this._texture);
    gl.copyTexSubImage2D(
      target,
      0,
      xOffset,
      yOffset,
      framebufferXOffset,
      framebufferYOffset,
      width,
      height
    );
    gl.bindTexture(target, null);
    this._initialized = true;
  };

  /**
   * @param {MipmapHint} [hint=MipmapHint.DONT_CARE] optional.
   *
   * @exception {DeveloperError} Cannot call generateMipmap when the texture pixel format is DEPTH_COMPONENT or DEPTH_STENCIL.
   * @exception {DeveloperError} Cannot call generateMipmap when the texture pixel format is a compressed format.
   * @exception {DeveloperError} hint is invalid.
   * @exception {DeveloperError} This texture's width must be a power of two to call generateMipmap() in a WebGL1 context.
   * @exception {DeveloperError} This texture's height must be a power of two to call generateMipmap() in a WebGL1 context.
   * @exception {DeveloperError} This texture was destroyed, i.e., destroy() was called.
   */
  Texture.prototype.generateMipmap = function (hint) {
    hint = defaultValue(hint, MipmapHint$1.DONT_CARE);

    //>>includeStart('debug', pragmas.debug);
    if (PixelFormat$1.isDepthFormat(this._pixelFormat)) {
      throw new DeveloperError(
        "Cannot call generateMipmap when the texture pixel format is DEPTH_COMPONENT or DEPTH_STENCIL."
      );
    }
    if (PixelFormat$1.isCompressedFormat(this._pixelFormat)) {
      throw new DeveloperError(
        "Cannot call generateMipmap with a compressed pixel format."
      );
    }
    if (!this._context.webgl2) {
      if (this._width > 1 && !CesiumMath.isPowerOfTwo(this._width)) {
        throw new DeveloperError(
          "width must be a power of two to call generateMipmap() in a WebGL1 context."
        );
      }
      if (this._height > 1 && !CesiumMath.isPowerOfTwo(this._height)) {
        throw new DeveloperError(
          "height must be a power of two to call generateMipmap() in a WebGL1 context."
        );
      }
    }
    if (!MipmapHint$1.validate(hint)) {
      throw new DeveloperError("hint is invalid.");
    }
    //>>includeEnd('debug');

    this._hasMipmap = true;

    const gl = this._context._gl;
    const target = this._textureTarget;

    gl.hint(gl.GENERATE_MIPMAP_HINT, hint);
    gl.activeTexture(gl.TEXTURE0);
    gl.bindTexture(target, this._texture);
    gl.generateMipmap(target);
    gl.bindTexture(target, null);
  };

  Texture.prototype.isDestroyed = function () {
    return false;
  };

  Texture.prototype.destroy = function () {
    this._context._gl.deleteTexture(this._texture);
    return destroyObject(this);
  };

  //This file is automatically rebuilt by the Cesium build process.
  var AspectRampMaterial = "uniform sampler2D image;\n\
czm_material czm_getMaterial(czm_materialInput materialInput)\n\
{\n\
czm_material material = czm_getDefaultMaterial(materialInput);\n\
vec4 rampColor = texture2D(image, vec2(materialInput.aspect / (2.0 * czm_pi), 0.5));\n\
rampColor = czm_gammaCorrect(rampColor);\n\
material.diffuse = rampColor.rgb;\n\
material.alpha = rampColor.a;\n\
return material;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var BumpMapMaterial = "uniform sampler2D image;\n\
uniform float strength;\n\
uniform vec2 repeat;\n\
czm_material czm_getMaterial(czm_materialInput materialInput)\n\
{\n\
czm_material material = czm_getDefaultMaterial(materialInput);\n\
vec2 st = materialInput.st;\n\
vec2 centerPixel = fract(repeat * st);\n\
float centerBump = texture2D(image, centerPixel).channel;\n\
float imageWidth = float(imageDimensions.x);\n\
vec2 rightPixel = fract(repeat * (st + vec2(1.0 / imageWidth, 0.0)));\n\
float rightBump = texture2D(image, rightPixel).channel;\n\
float imageHeight = float(imageDimensions.y);\n\
vec2 leftPixel = fract(repeat * (st + vec2(0.0, 1.0 / imageHeight)));\n\
float topBump = texture2D(image, leftPixel).channel;\n\
vec3 normalTangentSpace = normalize(vec3(centerBump - rightBump, centerBump - topBump, clamp(1.0 - strength, 0.1, 1.0)));\n\
vec3 normalEC = materialInput.tangentToEyeMatrix * normalTangentSpace;\n\
material.normal = normalEC;\n\
material.diffuse = vec3(0.01);\n\
return material;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var CheckerboardMaterial = "uniform vec4 lightColor;\n\
uniform vec4 darkColor;\n\
uniform vec2 repeat;\n\
czm_material czm_getMaterial(czm_materialInput materialInput)\n\
{\n\
czm_material material = czm_getDefaultMaterial(materialInput);\n\
vec2 st = materialInput.st;\n\
float b = mod(floor(repeat.s * st.s) + floor(repeat.t * st.t), 2.0);\n\
float scaledWidth = fract(repeat.s * st.s);\n\
scaledWidth = abs(scaledWidth - floor(scaledWidth + 0.5));\n\
float scaledHeight = fract(repeat.t * st.t);\n\
scaledHeight = abs(scaledHeight - floor(scaledHeight + 0.5));\n\
float value = min(scaledWidth, scaledHeight);\n\
vec4 currentColor = mix(lightColor, darkColor, b);\n\
vec4 color = czm_antialias(lightColor, darkColor, currentColor, value, 0.03);\n\
color = czm_gammaCorrect(color);\n\
material.diffuse = color.rgb;\n\
material.alpha = color.a;\n\
return material;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var DotMaterial = "uniform vec4 lightColor;\n\
uniform vec4 darkColor;\n\
uniform vec2 repeat;\n\
czm_material czm_getMaterial(czm_materialInput materialInput)\n\
{\n\
czm_material material = czm_getDefaultMaterial(materialInput);\n\
float b = smoothstep(0.3, 0.32, length(fract(repeat * materialInput.st) - 0.5));\n\
vec4 color = mix(lightColor, darkColor, b);\n\
color = czm_gammaCorrect(color);\n\
material.diffuse = color.rgb;\n\
material.alpha = color.a;\n\
return material;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var ElevationBandMaterial = "uniform sampler2D heights;\n\
uniform sampler2D colors;\n\
float getHeight(int idx, float invTexSize)\n\
{\n\
vec2 uv = vec2((float(idx) + 0.5) * invTexSize, 0.5);\n\
#ifdef OES_texture_float\n\
return texture2D(heights, uv).x;\n\
#else\n\
return czm_unpackFloat(texture2D(heights, uv));\n\
#endif\n\
}\n\
czm_material czm_getMaterial(czm_materialInput materialInput)\n\
{\n\
czm_material material = czm_getDefaultMaterial(materialInput);\n\
float height = materialInput.height;\n\
float invTexSize = 1.0 / float(heightsDimensions.x);\n\
float minHeight = getHeight(0, invTexSize);\n\
float maxHeight = getHeight(heightsDimensions.x - 1, invTexSize);\n\
if (height < minHeight || height > maxHeight) {\n\
material.diffuse = vec3(0.0);\n\
material.alpha = 0.0;\n\
return material;\n\
}\n\
int idxBelow = 0;\n\
int idxAbove = heightsDimensions.x;\n\
float heightBelow = minHeight;\n\
float heightAbove = maxHeight;\n\
const int maxIterations = 16;\n\
for (int i = 0; i < maxIterations; i++) {\n\
if (idxBelow >= idxAbove - 1) {\n\
break;\n\
}\n\
int idxMid = (idxBelow + idxAbove) / 2;\n\
float heightTex = getHeight(idxMid, invTexSize);\n\
if (height > heightTex) {\n\
idxBelow = idxMid;\n\
heightBelow = heightTex;\n\
} else {\n\
idxAbove = idxMid;\n\
heightAbove = heightTex;\n\
}\n\
}\n\
float lerper = heightBelow == heightAbove ? 1.0 : (height - heightBelow) / (heightAbove - heightBelow);\n\
vec2 colorUv = vec2(invTexSize * (float(idxBelow) + 0.5 + lerper), 0.5);\n\
vec4 color = texture2D(colors, colorUv);\n\
if (color.a > 0.0)\n\
{\n\
color.rgb /= color.a;\n\
}\n\
color.rgb = czm_gammaCorrect(color.rgb);\n\
material.diffuse = color.rgb;\n\
material.alpha = color.a;\n\
return material;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var ElevationContourMaterial = "#ifdef GL_OES_standard_derivatives\n\
#extension GL_OES_standard_derivatives : enable\n\
#endif\n\
uniform vec4 color;\n\
uniform float spacing;\n\
uniform float width;\n\
czm_material czm_getMaterial(czm_materialInput materialInput)\n\
{\n\
czm_material material = czm_getDefaultMaterial(materialInput);\n\
float distanceToContour = mod(materialInput.height, spacing);\n\
#ifdef GL_OES_standard_derivatives\n\
float dxc = abs(dFdx(materialInput.height));\n\
float dyc = abs(dFdy(materialInput.height));\n\
float dF = max(dxc, dyc) * czm_pixelRatio * width;\n\
float alpha = (distanceToContour < dF) ? 1.0 : 0.0;\n\
#else\n\
float alpha = (distanceToContour < (czm_pixelRatio * width)) ? 1.0 : 0.0;\n\
#endif\n\
vec4 outColor = czm_gammaCorrect(vec4(color.rgb, alpha * color.a));\n\
material.diffuse = outColor.rgb;\n\
material.alpha = outColor.a;\n\
return material;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var ElevationRampMaterial = "uniform sampler2D image;\n\
uniform float minimumHeight;\n\
uniform float maximumHeight;\n\
czm_material czm_getMaterial(czm_materialInput materialInput)\n\
{\n\
czm_material material = czm_getDefaultMaterial(materialInput);\n\
float scaledHeight = clamp((materialInput.height - minimumHeight) / (maximumHeight - minimumHeight), 0.0, 1.0);\n\
vec4 rampColor = texture2D(image, vec2(scaledHeight, 0.5));\n\
rampColor = czm_gammaCorrect(rampColor);\n\
material.diffuse = rampColor.rgb;\n\
material.alpha = rampColor.a;\n\
return material;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var FadeMaterial = "uniform vec4 fadeInColor;\n\
uniform vec4 fadeOutColor;\n\
uniform float maximumDistance;\n\
uniform bool repeat;\n\
uniform vec2 fadeDirection;\n\
uniform vec2 time;\n\
float getTime(float t, float coord)\n\
{\n\
float scalar = 1.0 / maximumDistance;\n\
float q  = distance(t, coord) * scalar;\n\
if (repeat)\n\
{\n\
float r = distance(t, coord + 1.0) * scalar;\n\
float s = distance(t, coord - 1.0) * scalar;\n\
q = min(min(r, s), q);\n\
}\n\
return clamp(q, 0.0, 1.0);\n\
}\n\
czm_material czm_getMaterial(czm_materialInput materialInput)\n\
{\n\
czm_material material = czm_getDefaultMaterial(materialInput);\n\
vec2 st = materialInput.st;\n\
float s = getTime(time.x, st.s) * fadeDirection.s;\n\
float t = getTime(time.y, st.t) * fadeDirection.t;\n\
float u = length(vec2(s, t));\n\
vec4 color = mix(fadeInColor, fadeOutColor, u);\n\
color = czm_gammaCorrect(color);\n\
material.emission = color.rgb;\n\
material.alpha = color.a;\n\
return material;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var GridMaterial = "#ifdef GL_OES_standard_derivatives\n\
#extension GL_OES_standard_derivatives : enable\n\
#endif\n\
uniform vec4 color;\n\
uniform float cellAlpha;\n\
uniform vec2 lineCount;\n\
uniform vec2 lineThickness;\n\
uniform vec2 lineOffset;\n\
czm_material czm_getMaterial(czm_materialInput materialInput)\n\
{\n\
czm_material material = czm_getDefaultMaterial(materialInput);\n\
vec2 st = materialInput.st;\n\
float scaledWidth = fract(lineCount.s * st.s - lineOffset.s);\n\
scaledWidth = abs(scaledWidth - floor(scaledWidth + 0.5));\n\
float scaledHeight = fract(lineCount.t * st.t - lineOffset.t);\n\
scaledHeight = abs(scaledHeight - floor(scaledHeight + 0.5));\n\
float value;\n\
#ifdef GL_OES_standard_derivatives\n\
const float fuzz = 1.2;\n\
vec2 thickness = (lineThickness * czm_pixelRatio) - 1.0;\n\
vec2 dx = abs(dFdx(st));\n\
vec2 dy = abs(dFdy(st));\n\
vec2 dF = vec2(max(dx.s, dy.s), max(dx.t, dy.t)) * lineCount;\n\
value = min(\n\
smoothstep(dF.s * thickness.s, dF.s * (fuzz + thickness.s), scaledWidth),\n\
smoothstep(dF.t * thickness.t, dF.t * (fuzz + thickness.t), scaledHeight));\n\
#else\n\
const float fuzz = 0.05;\n\
vec2 range = 0.5 - (lineThickness * 0.05);\n\
value = min(\n\
1.0 - smoothstep(range.s, range.s + fuzz, scaledWidth),\n\
1.0 - smoothstep(range.t, range.t + fuzz, scaledHeight));\n\
#endif\n\
float dRim = 1.0 - abs(dot(materialInput.normalEC, normalize(materialInput.positionToEyeEC)));\n\
float sRim = smoothstep(0.8, 1.0, dRim);\n\
value *= (1.0 - sRim);\n\
vec4 halfColor;\n\
halfColor.rgb = color.rgb * 0.5;\n\
halfColor.a = color.a * (1.0 - ((1.0 - cellAlpha) * value));\n\
halfColor = czm_gammaCorrect(halfColor);\n\
material.diffuse = halfColor.rgb;\n\
material.emission = halfColor.rgb;\n\
material.alpha = halfColor.a;\n\
return material;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var NormalMapMaterial = "uniform sampler2D image;\n\
uniform float strength;\n\
uniform vec2 repeat;\n\
czm_material czm_getMaterial(czm_materialInput materialInput)\n\
{\n\
czm_material material = czm_getDefaultMaterial(materialInput);\n\
vec4 textureValue = texture2D(image, fract(repeat * materialInput.st));\n\
vec3 normalTangentSpace = textureValue.channels;\n\
normalTangentSpace.xy = normalTangentSpace.xy * 2.0 - 1.0;\n\
normalTangentSpace.z = clamp(1.0 - strength, 0.1, 1.0);\n\
normalTangentSpace = normalize(normalTangentSpace);\n\
vec3 normalEC = materialInput.tangentToEyeMatrix * normalTangentSpace;\n\
material.normal = normalEC;\n\
return material;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var PolylineArrowMaterial = "#ifdef GL_OES_standard_derivatives\n\
#extension GL_OES_standard_derivatives : enable\n\
#endif\n\
uniform vec4 color;\n\
float getPointOnLine(vec2 p0, vec2 p1, float x)\n\
{\n\
float slope = (p0.y - p1.y) / (p0.x - p1.x);\n\
return slope * (x - p0.x) + p0.y;\n\
}\n\
czm_material czm_getMaterial(czm_materialInput materialInput)\n\
{\n\
czm_material material = czm_getDefaultMaterial(materialInput);\n\
vec2 st = materialInput.st;\n\
#ifdef GL_OES_standard_derivatives\n\
float base = 1.0 - abs(fwidth(st.s)) * 10.0 * czm_pixelRatio;\n\
#else\n\
float base = 0.975;\n\
#endif\n\
vec2 center = vec2(1.0, 0.5);\n\
float ptOnUpperLine = getPointOnLine(vec2(base, 1.0), center, st.s);\n\
float ptOnLowerLine = getPointOnLine(vec2(base, 0.0), center, st.s);\n\
float halfWidth = 0.15;\n\
float s = step(0.5 - halfWidth, st.t);\n\
s *= 1.0 - step(0.5 + halfWidth, st.t);\n\
s *= 1.0 - step(base, st.s);\n\
float t = step(base, materialInput.st.s);\n\
t *= 1.0 - step(ptOnUpperLine, st.t);\n\
t *= step(ptOnLowerLine, st.t);\n\
float dist;\n\
if (st.s < base)\n\
{\n\
float d1 = abs(st.t - (0.5 - halfWidth));\n\
float d2 = abs(st.t - (0.5 + halfWidth));\n\
dist = min(d1, d2);\n\
}\n\
else\n\
{\n\
float d1 = czm_infinity;\n\
if (st.t < 0.5 - halfWidth && st.t > 0.5 + halfWidth)\n\
{\n\
d1 = abs(st.s - base);\n\
}\n\
float d2 = abs(st.t - ptOnUpperLine);\n\
float d3 = abs(st.t - ptOnLowerLine);\n\
dist = min(min(d1, d2), d3);\n\
}\n\
vec4 outsideColor = vec4(0.0);\n\
vec4 currentColor = mix(outsideColor, color, clamp(s + t, 0.0, 1.0));\n\
vec4 outColor = czm_antialias(outsideColor, color, currentColor, dist);\n\
outColor = czm_gammaCorrect(outColor);\n\
material.diffuse = outColor.rgb;\n\
material.alpha = outColor.a;\n\
return material;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var PolylineDashMaterial = "uniform vec4 color;\n\
uniform vec4 gapColor;\n\
uniform float dashLength;\n\
uniform float dashPattern;\n\
varying float v_polylineAngle;\n\
const float maskLength = 16.0;\n\
mat2 rotate(float rad) {\n\
float c = cos(rad);\n\
float s = sin(rad);\n\
return mat2(\n\
c, s,\n\
-s, c\n\
);\n\
}\n\
czm_material czm_getMaterial(czm_materialInput materialInput)\n\
{\n\
czm_material material = czm_getDefaultMaterial(materialInput);\n\
vec2 pos = rotate(v_polylineAngle) * gl_FragCoord.xy;\n\
float dashPosition = fract(pos.x / (dashLength * czm_pixelRatio));\n\
float maskIndex = floor(dashPosition * maskLength);\n\
float maskTest = floor(dashPattern / pow(2.0, maskIndex));\n\
vec4 fragColor = (mod(maskTest, 2.0) < 1.0) ? gapColor : color;\n\
if (fragColor.a < 0.005) {\n\
discard;\n\
}\n\
fragColor = czm_gammaCorrect(fragColor);\n\
material.emission = fragColor.rgb;\n\
material.alpha = fragColor.a;\n\
return material;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var PolylineGlowMaterial = "uniform vec4 color;\n\
uniform float glowPower;\n\
uniform float taperPower;\n\
czm_material czm_getMaterial(czm_materialInput materialInput)\n\
{\n\
czm_material material = czm_getDefaultMaterial(materialInput);\n\
vec2 st = materialInput.st;\n\
float glow = glowPower / abs(st.t - 0.5) - (glowPower / 0.5);\n\
if (taperPower <= 0.99999) {\n\
glow *= min(1.0, taperPower / (0.5 - st.s * 0.5) - (taperPower / 0.5));\n\
}\n\
vec4 fragColor;\n\
fragColor.rgb = max(vec3(glow - 1.0 + color.rgb), color.rgb);\n\
fragColor.a = clamp(0.0, 1.0, glow) * color.a;\n\
fragColor = czm_gammaCorrect(fragColor);\n\
material.emission = fragColor.rgb;\n\
material.alpha = fragColor.a;\n\
return material;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var PolylineOutlineMaterial = "uniform vec4 color;\n\
uniform vec4 outlineColor;\n\
uniform float outlineWidth;\n\
varying float v_width;\n\
czm_material czm_getMaterial(czm_materialInput materialInput)\n\
{\n\
czm_material material = czm_getDefaultMaterial(materialInput);\n\
vec2 st = materialInput.st;\n\
float halfInteriorWidth =  0.5 * (v_width - outlineWidth) / v_width;\n\
float b = step(0.5 - halfInteriorWidth, st.t);\n\
b *= 1.0 - step(0.5 + halfInteriorWidth, st.t);\n\
float d1 = abs(st.t - (0.5 - halfInteriorWidth));\n\
float d2 = abs(st.t - (0.5 + halfInteriorWidth));\n\
float dist = min(d1, d2);\n\
vec4 currentColor = mix(outlineColor, color, b);\n\
vec4 outColor = czm_antialias(outlineColor, color, currentColor, dist);\n\
outColor = czm_gammaCorrect(outColor);\n\
material.diffuse = outColor.rgb;\n\
material.alpha = outColor.a;\n\
return material;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var RimLightingMaterial = "uniform vec4 color;\n\
uniform vec4 rimColor;\n\
uniform float width;\n\
czm_material czm_getMaterial(czm_materialInput materialInput)\n\
{\n\
czm_material material = czm_getDefaultMaterial(materialInput);\n\
float d = 1.0 - dot(materialInput.normalEC, normalize(materialInput.positionToEyeEC));\n\
float s = smoothstep(1.0 - width, 1.0, d);\n\
vec4 outColor = czm_gammaCorrect(color);\n\
vec4 outRimColor = czm_gammaCorrect(rimColor);\n\
material.diffuse = outColor.rgb;\n\
material.emission = outRimColor.rgb * s;\n\
material.alpha = mix(outColor.a, outRimColor.a, s);\n\
return material;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var SlopeRampMaterial = "uniform sampler2D image;\n\
czm_material czm_getMaterial(czm_materialInput materialInput)\n\
{\n\
czm_material material = czm_getDefaultMaterial(materialInput);\n\
vec4 rampColor = texture2D(image, vec2(materialInput.slope / (czm_pi / 2.0), 0.5));\n\
rampColor = czm_gammaCorrect(rampColor);\n\
material.diffuse = rampColor.rgb;\n\
material.alpha = rampColor.a;\n\
return material;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var StripeMaterial = "uniform vec4 evenColor;\n\
uniform vec4 oddColor;\n\
uniform float offset;\n\
uniform float repeat;\n\
uniform bool horizontal;\n\
czm_material czm_getMaterial(czm_materialInput materialInput)\n\
{\n\
czm_material material = czm_getDefaultMaterial(materialInput);\n\
float coord = mix(materialInput.st.s, materialInput.st.t, float(horizontal));\n\
float value = fract((coord - offset) * (repeat * 0.5));\n\
float dist = min(value, min(abs(value - 0.5), 1.0 - value));\n\
vec4 currentColor = mix(evenColor, oddColor, step(0.5, value));\n\
vec4 color = czm_antialias(evenColor, oddColor, currentColor, dist);\n\
color = czm_gammaCorrect(color);\n\
material.diffuse = color.rgb;\n\
material.alpha = color.a;\n\
return material;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var WaterMaterial = "uniform sampler2D specularMap;\n\
uniform sampler2D normalMap;\n\
uniform vec4 baseWaterColor;\n\
uniform vec4 blendColor;\n\
uniform float frequency;\n\
uniform float animationSpeed;\n\
uniform float amplitude;\n\
uniform float specularIntensity;\n\
uniform float fadeFactor;\n\
czm_material czm_getMaterial(czm_materialInput materialInput)\n\
{\n\
czm_material material = czm_getDefaultMaterial(materialInput);\n\
float time = czm_frameNumber * animationSpeed;\n\
float fade = max(1.0, (length(materialInput.positionToEyeEC) / 10000000000.0) * frequency * fadeFactor);\n\
float specularMapValue = texture2D(specularMap, materialInput.st).r;\n\
vec4 noise = czm_getWaterNoise(normalMap, materialInput.st * frequency, time, 0.0);\n\
vec3 normalTangentSpace = noise.xyz * vec3(1.0, 1.0, (1.0 / amplitude));\n\
normalTangentSpace.xy /= fade;\n\
normalTangentSpace = mix(vec3(0.0, 0.0, 50.0), normalTangentSpace, specularMapValue);\n\
normalTangentSpace = normalize(normalTangentSpace);\n\
float tsPerturbationRatio = clamp(dot(normalTangentSpace, vec3(0.0, 0.0, 1.0)), 0.0, 1.0);\n\
material.alpha = mix(blendColor.a, baseWaterColor.a, specularMapValue) * specularMapValue;\n\
material.diffuse = mix(blendColor.rgb, baseWaterColor.rgb, specularMapValue);\n\
material.diffuse += (0.1 * tsPerturbationRatio);\n\
material.diffuse = material.diffuse;\n\
material.normal = normalize(materialInput.tangentToEyeMatrix * normalTangentSpace);\n\
material.specular = specularIntensity;\n\
material.shininess = 10.0;\n\
return material;\n\
}\n\
";

  /**
   * A Material defines surface appearance through a combination of diffuse, specular,
   * normal, emission, and alpha components. These values are specified using a
   * JSON schema called Fabric which gets parsed and assembled into glsl shader code
   * behind-the-scenes. Check out the {@link https://github.com/CesiumGS/cesium/wiki/Fabric|wiki page}
   * for more details on Fabric.
   * <br /><br />
   * <style type="text/css">
   *  #materialDescriptions code {
   *      font-weight: normal;
   *      font-family: Consolas, 'Lucida Console', Monaco, monospace;
   *      color: #A35A00;
   *  }
   *  #materialDescriptions ul, #materialDescriptions ul ul {
   *      list-style-type: none;
   *  }
   *  #materialDescriptions ul ul {
   *      margin-bottom: 10px;
   *  }
   *  #materialDescriptions ul ul li {
   *      font-weight: normal;
   *      color: #000000;
   *      text-indent: -2em;
   *      margin-left: 2em;
   *  }
   *  #materialDescriptions ul li {
   *      font-weight: bold;
   *      color: #0053CF;
   *  }
   * </style>
   *
   * Base material types and their uniforms:
   * <div id='materialDescriptions'>
   * <ul>
   *  <li>Color</li>
   *  <ul>
   *      <li><code>color</code>:  rgba color object.</li>
   *  </ul>
   *  <li>Image</li>
   *  <ul>
   *      <li><code>image</code>:  path to image.</li>
   *      <li><code>repeat</code>:  Object with x and y values specifying the number of times to repeat the image.</li>
   *  </ul>
   *  <li>DiffuseMap</li>
   *  <ul>
   *      <li><code>image</code>:  path to image.</li>
   *      <li><code>channels</code>:  Three character string containing any combination of r, g, b, and a for selecting the desired image channels.</li>
   *      <li><code>repeat</code>:  Object with x and y values specifying the number of times to repeat the image.</li>
   *  </ul>
   *  <li>AlphaMap</li>
   *  <ul>
   *      <li><code>image</code>:  path to image.</li>
   *      <li><code>channel</code>:  One character string containing r, g, b, or a for selecting the desired image channel. </li>
   *      <li><code>repeat</code>:  Object with x and y values specifying the number of times to repeat the image.</li>
   *  </ul>
   *  <li>SpecularMap</li>
   *  <ul>
   *      <li><code>image</code>: path to image.</li>
   *      <li><code>channel</code>: One character string containing r, g, b, or a for selecting the desired image channel. </li>
   *      <li><code>repeat</code>: Object with x and y values specifying the number of times to repeat the image.</li>
   *  </ul>
   *  <li>EmissionMap</li>
   *  <ul>
   *      <li><code>image</code>:  path to image.</li>
   *      <li><code>channels</code>:  Three character string containing any combination of r, g, b, and a for selecting the desired image channels. </li>
   *      <li><code>repeat</code>:  Object with x and y values specifying the number of times to repeat the image.</li>
   *  </ul>
   *  <li>BumpMap</li>
   *  <ul>
   *      <li><code>image</code>:  path to image.</li>
   *      <li><code>channel</code>:  One character string containing r, g, b, or a for selecting the desired image channel. </li>
   *      <li><code>repeat</code>:  Object with x and y values specifying the number of times to repeat the image.</li>
   *      <li><code>strength</code>:  Bump strength value between 0.0 and 1.0 where 0.0 is small bumps and 1.0 is large bumps.</li>
   *  </ul>
   *  <li>NormalMap</li>
   *  <ul>
   *      <li><code>image</code>:  path to image.</li>
   *      <li><code>channels</code>:  Three character string containing any combination of r, g, b, and a for selecting the desired image channels. </li>
   *      <li><code>repeat</code>:  Object with x and y values specifying the number of times to repeat the image.</li>
   *      <li><code>strength</code>:  Bump strength value between 0.0 and 1.0 where 0.0 is small bumps and 1.0 is large bumps.</li>
   *  </ul>
   *  <li>Grid</li>
   *  <ul>
   *      <li><code>color</code>:  rgba color object for the whole material.</li>
   *      <li><code>cellAlpha</code>: Alpha value for the cells between grid lines.  This will be combined with color.alpha.</li>
   *      <li><code>lineCount</code>:  Object with x and y values specifying the number of columns and rows respectively.</li>
   *      <li><code>lineThickness</code>:  Object with x and y values specifying the thickness of grid lines (in pixels where available).</li>
   *      <li><code>lineOffset</code>:  Object with x and y values specifying the offset of grid lines (range is 0 to 1).</li>
   *  </ul>
   *  <li>Stripe</li>
   *  <ul>
   *      <li><code>horizontal</code>:  Boolean that determines if the stripes are horizontal or vertical.</li>
   *      <li><code>evenColor</code>:  rgba color object for the stripe's first color.</li>
   *      <li><code>oddColor</code>:  rgba color object for the stripe's second color.</li>
   *      <li><code>offset</code>:  Number that controls at which point into the pattern to begin drawing; with 0.0 being the beginning of the even color, 1.0 the beginning of the odd color, 2.0 being the even color again, and any multiple or fractional values being in between.</li>
   *      <li><code>repeat</code>:  Number that controls the total number of stripes, half light and half dark.</li>
   *  </ul>
   *  <li>Checkerboard</li>
   *  <ul>
   *      <li><code>lightColor</code>:  rgba color object for the checkerboard's light alternating color.</li>
   *      <li><code>darkColor</code>: rgba color object for the checkerboard's dark alternating color.</li>
   *      <li><code>repeat</code>:  Object with x and y values specifying the number of columns and rows respectively.</li>
   *  </ul>
   *  <li>Dot</li>
   *  <ul>
   *      <li><code>lightColor</code>:  rgba color object for the dot color.</li>
   *      <li><code>darkColor</code>:  rgba color object for the background color.</li>
   *      <li><code>repeat</code>:  Object with x and y values specifying the number of columns and rows of dots respectively.</li>
   *  </ul>
   *  <li>Water</li>
   *  <ul>
   *      <li><code>baseWaterColor</code>:  rgba color object base color of the water.</li>
   *      <li><code>blendColor</code>:  rgba color object used when blending from water to non-water areas.</li>
   *      <li><code>specularMap</code>:  Single channel texture used to indicate areas of water.</li>
   *      <li><code>normalMap</code>:  Normal map for water normal perturbation.</li>
   *      <li><code>frequency</code>:  Number that controls the number of waves.</li>
   *      <li><code>animationSpeed</code>:  Number that controls the animations speed of the water.</li>
   *      <li><code>amplitude</code>:  Number that controls the amplitude of water waves.</li>
   *      <li><code>specularIntensity</code>:  Number that controls the intensity of specular reflections.</li>
   *  </ul>
   *  <li>RimLighting</li>
   *  <ul>
   *      <li><code>color</code>:  diffuse color and alpha.</li>
   *      <li><code>rimColor</code>:  diffuse color and alpha of the rim.</li>
   *      <li><code>width</code>:  Number that determines the rim's width.</li>
   *  </ul>
   *  <li>Fade</li>
   *  <ul>
   *      <li><code>fadeInColor</code>: diffuse color and alpha at <code>time</code></li>
   *      <li><code>fadeOutColor</code>: diffuse color and alpha at <code>maximumDistance</code> from <code>time</code></li>
   *      <li><code>maximumDistance</code>: Number between 0.0 and 1.0 where the <code>fadeInColor</code> becomes the <code>fadeOutColor</code>. A value of 0.0 gives the entire material a color of <code>fadeOutColor</code> and a value of 1.0 gives the the entire material a color of <code>fadeInColor</code></li>
   *      <li><code>repeat</code>: true if the fade should wrap around the texture coodinates.</li>
   *      <li><code>fadeDirection</code>: Object with x and y values specifying if the fade should be in the x and y directions.</li>
   *      <li><code>time</code>: Object with x and y values between 0.0 and 1.0 of the <code>fadeInColor</code> position</li>
   *  </ul>
   *  <li>PolylineArrow</li>
   *  <ul>
   *      <li><code>color</code>: diffuse color and alpha.</li>
   *  </ul>
   *  <li>PolylineDash</li>
   *  <ul>
   *      <li><code>color</code>: color for the line.</li>
   *      <li><code>gapColor</code>: color for the gaps in the line.</li>
   *      <li><code>dashLength</code>: Dash length in pixels.</li>
   *      <li><code>dashPattern</code>: The 16 bit stipple pattern for the line..</li>
   *  </ul>
   *  <li>PolylineGlow</li>
   *  <ul>
   *      <li><code>color</code>: color and maximum alpha for the glow on the line.</li>
   *      <li><code>glowPower</code>: strength of the glow, as a percentage of the total line width (less than 1.0).</li>
   *      <li><code>taperPower</code>: strength of the tapering effect, as a percentage of the total line length.  If 1.0 or higher, no taper effect is used.</li>
   *  </ul>
   *  <li>PolylineOutline</li>
   *  <ul>
   *      <li><code>color</code>: diffuse color and alpha for the interior of the line.</li>
   *      <li><code>outlineColor</code>: diffuse color and alpha for the outline.</li>
   *      <li><code>outlineWidth</code>: width of the outline in pixels.</li>
   *  </ul>
   *  <li>ElevationContour</li>
   *  <ul>
   *      <li><code>color</code>: color and alpha for the contour line.</li>
   *      <li><code>spacing</code>: spacing for contour lines in meters.</li>
   *      <li><code>width</code>: Number specifying the width of the grid lines in pixels.</li>
   *  </ul>
   *  <li>ElevationRamp</li>
   *  <ul>
   *      <li><code>image</code>: color ramp image to use for coloring the terrain.</li>
   *      <li><code>minimumHeight</code>: minimum height for the ramp.</li>
   *      <li><code>maximumHeight</code>: maximum height for the ramp.</li>
   *  </ul>
   *  <li>SlopeRamp</li>
   *  <ul>
   *      <li><code>image</code>: color ramp image to use for coloring the terrain by slope.</li>
   *  </ul>
   *  <li>AspectRamp</li>
   *  <ul>
   *      <li><code>image</code>: color ramp image to use for color the terrain by aspect.</li>
   *  </ul>
   *  <li>ElevationBand</li>
   *  <ul>
   *      <li><code>heights</code>: image of heights sorted from lowest to highest.</li>
   *      <li><code>colors</code>: image of colors at the corresponding heights.</li>
   * </ul>
   * </ul>
   * </ul>
   * </div>
   *
   * @alias Material
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Boolean} [options.strict=false] Throws errors for issues that would normally be ignored, including unused uniforms or materials.
   * @param {Boolean|Function} [options.translucent=true] When <code>true</code> or a function that returns <code>true</code>, the geometry
   *                           with this material is expected to appear translucent.
   * @param {TextureMinificationFilter} [options.minificationFilter=TextureMinificationFilter.LINEAR] The {@link TextureMinificationFilter} to apply to this material's textures.
   * @param {TextureMagnificationFilter} [options.magnificationFilter=TextureMagnificationFilter.LINEAR] The {@link TextureMagnificationFilter} to apply to this material's textures.
   * @param {Object} options.fabric The fabric JSON used to generate the material.
   *
   * @constructor
   *
   * @exception {DeveloperError} fabric: uniform has invalid type.
   * @exception {DeveloperError} fabric: uniforms and materials cannot share the same property.
   * @exception {DeveloperError} fabric: cannot have source and components in the same section.
   * @exception {DeveloperError} fabric: property name is not valid. It should be 'type', 'materials', 'uniforms', 'components', or 'source'.
   * @exception {DeveloperError} fabric: property name is not valid. It should be 'diffuse', 'specular', 'shininess', 'normal', 'emission', or 'alpha'.
   * @exception {DeveloperError} strict: shader source does not use string.
   * @exception {DeveloperError} strict: shader source does not use uniform.
   * @exception {DeveloperError} strict: shader source does not use material.
   *
   * @see {@link https://github.com/CesiumGS/cesium/wiki/Fabric|Fabric wiki page} for a more detailed options of Fabric.
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Materials.html|Cesium Sandcastle Materials Demo}
   *
   * @example
   * // Create a color material with fromType:
   * polygon.material = Cesium.Material.fromType('Color');
   * polygon.material.uniforms.color = new Cesium.Color(1.0, 1.0, 0.0, 1.0);
   *
   * // Create the default material:
   * polygon.material = new Cesium.Material();
   *
   * // Create a color material with full Fabric notation:
   * polygon.material = new Cesium.Material({
   *     fabric : {
   *         type : 'Color',
   *         uniforms : {
   *             color : new Cesium.Color(1.0, 1.0, 0.0, 1.0)
   *         }
   *     }
   * });
   */
  function Material$4(options) {
    /**
     * The material type. Can be an existing type or a new type. If no type is specified in fabric, type is a GUID.
     * @type {String}
     * @default undefined
     */
    this.type = undefined;

    /**
     * The glsl shader source for this material.
     * @type {String}
     * @default undefined
     */
    this.shaderSource = undefined;

    /**
     * Maps sub-material names to Material objects.
     * @type {Object}
     * @default undefined
     */
    this.materials = undefined;

    /**
     * Maps uniform names to their values.
     * @type {Object}
     * @default undefined
     */
    this.uniforms = undefined;
    this._uniforms = undefined;

    /**
     * When <code>true</code> or a function that returns <code>true</code>,
     * the geometry is expected to appear translucent.
     * @type {Boolean|Function}
     * @default undefined
     */
    this.translucent = undefined;

    this._minificationFilter = defaultValue(
      options.minificationFilter,
      TextureMinificationFilter$1.LINEAR
    );
    this._magnificationFilter = defaultValue(
      options.magnificationFilter,
      TextureMagnificationFilter$1.LINEAR
    );

    this._strict = undefined;
    this._template = undefined;
    this._count = undefined;

    this._texturePaths = {};
    this._loadedImages = [];
    this._loadedCubeMaps = [];

    this._textures = {};

    this._updateFunctions = [];

    this._defaultTexture = undefined;

    initializeMaterial(options, this);
    Object.defineProperties(this, {
      type: {
        value: this.type,
        writable: false,
      },
    });

    if (!defined(Material$4._uniformList[this.type])) {
      Material$4._uniformList[this.type] = Object.keys(this._uniforms);
    }
  }

  // Cached list of combined uniform names indexed by type.
  // Used to get the list of uniforms in the same order.
  Material$4._uniformList = {};

  /**
   * Creates a new material using an existing material type.
   * <br /><br />
   * Shorthand for: new Material({fabric : {type : type}});
   *
   * @param {String} type The base material type.
   * @param {Object} [uniforms] Overrides for the default uniforms.
   * @returns {Material} New material object.
   *
   * @exception {DeveloperError} material with that type does not exist.
   *
   * @example
   * const material = Cesium.Material.fromType('Color', {
   *     color : new Cesium.Color(1.0, 0.0, 0.0, 1.0)
   * });
   */
  Material$4.fromType = function (type, uniforms) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(Material$4._materialCache.getMaterial(type))) {
      throw new DeveloperError(`material with type '${type}' does not exist.`);
    }
    //>>includeEnd('debug');

    const material = new Material$4({
      fabric: {
        type: type,
      },
    });

    if (defined(uniforms)) {
      for (const name in uniforms) {
        if (uniforms.hasOwnProperty(name)) {
          material.uniforms[name] = uniforms[name];
        }
      }
    }

    return material;
  };

  /**
   * Gets whether or not this material is translucent.
   * @returns {Boolean} <code>true</code> if this material is translucent, <code>false</code> otherwise.
   */
  Material$4.prototype.isTranslucent = function () {
    if (defined(this.translucent)) {
      if (typeof this.translucent === "function") {
        return this.translucent();
      }

      return this.translucent;
    }

    let translucent = true;
    const funcs = this._translucentFunctions;
    const length = funcs.length;
    for (let i = 0; i < length; ++i) {
      const func = funcs[i];
      if (typeof func === "function") {
        translucent = translucent && func();
      } else {
        translucent = translucent && func;
      }

      if (!translucent) {
        break;
      }
    }
    return translucent;
  };

  /**
   * @private
   */
  Material$4.prototype.update = function (context) {
    this._defaultTexture = context.defaultTexture;

    let i;
    let uniformId;

    const loadedImages = this._loadedImages;
    let length = loadedImages.length;
    for (i = 0; i < length; ++i) {
      const loadedImage = loadedImages[i];
      uniformId = loadedImage.id;
      let image = loadedImage.image;

      // Images transcoded from KTX2 can contain multiple mip levels:
      // https://github.khronos.org/KTX-Specification/#_mip_level_array
      let mipLevels;
      if (Array.isArray(image)) {
        // highest detail mip should be level 0
        mipLevels = image.slice(1, image.length).map(function (mipLevel) {
          return mipLevel.bufferView;
        });
        image = image[0];
      }

      const sampler = new Sampler({
        minificationFilter: this._minificationFilter,
        magnificationFilter: this._magnificationFilter,
      });

      let texture;
      if (defined(image.internalFormat)) {
        texture = new Texture({
          context: context,
          pixelFormat: image.internalFormat,
          width: image.width,
          height: image.height,
          source: {
            arrayBufferView: image.bufferView,
            mipLevels: mipLevels,
          },
          sampler: sampler,
        });
      } else {
        texture = new Texture({
          context: context,
          source: image,
          sampler: sampler,
        });
      }

      // The material destroys its old texture only after the new one has been loaded.
      // This will ensure a smooth swap of textures and prevent the default texture
      // from appearing for a few frames.
      const oldTexture = this._textures[uniformId];
      if (defined(oldTexture) && oldTexture !== this._defaultTexture) {
        oldTexture.destroy();
      }

      this._textures[uniformId] = texture;

      const uniformDimensionsName = `${uniformId}Dimensions`;
      if (this.uniforms.hasOwnProperty(uniformDimensionsName)) {
        const uniformDimensions = this.uniforms[uniformDimensionsName];
        uniformDimensions.x = texture._width;
        uniformDimensions.y = texture._height;
      }
    }

    loadedImages.length = 0;

    const loadedCubeMaps = this._loadedCubeMaps;
    length = loadedCubeMaps.length;

    for (i = 0; i < length; ++i) {
      const loadedCubeMap = loadedCubeMaps[i];
      uniformId = loadedCubeMap.id;
      const images = loadedCubeMap.images;

      const cubeMap = new CubeMap({
        context: context,
        source: {
          positiveX: images[0],
          negativeX: images[1],
          positiveY: images[2],
          negativeY: images[3],
          positiveZ: images[4],
          negativeZ: images[5],
        },
        sampler: new Sampler({
          minificationFilter: this._minificationFilter,
          magnificationFilter: this._magnificationFilter,
        }),
      });

      this._textures[uniformId] = cubeMap;
    }

    loadedCubeMaps.length = 0;

    const updateFunctions = this._updateFunctions;
    length = updateFunctions.length;
    for (i = 0; i < length; ++i) {
      updateFunctions[i](this, context);
    }

    const subMaterials = this.materials;
    for (const name in subMaterials) {
      if (subMaterials.hasOwnProperty(name)) {
        subMaterials[name].update(context);
      }
    }
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} True if this object was destroyed; otherwise, false.
   *
   * @see Material#destroy
   */
  Material$4.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * material = material && material.destroy();
   *
   * @see Material#isDestroyed
   */
  Material$4.prototype.destroy = function () {
    const textures = this._textures;
    for (const texture in textures) {
      if (textures.hasOwnProperty(texture)) {
        const instance = textures[texture];
        if (instance !== this._defaultTexture) {
          instance.destroy();
        }
      }
    }

    const materials = this.materials;
    for (const material in materials) {
      if (materials.hasOwnProperty(material)) {
        materials[material].destroy();
      }
    }
    return destroyObject(this);
  };

  function initializeMaterial(options, result) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    result._strict = defaultValue(options.strict, false);
    result._count = defaultValue(options.count, 0);
    result._template = clone$1(
      defaultValue(options.fabric, defaultValue.EMPTY_OBJECT)
    );
    result._template.uniforms = clone$1(
      defaultValue(result._template.uniforms, defaultValue.EMPTY_OBJECT)
    );
    result._template.materials = clone$1(
      defaultValue(result._template.materials, defaultValue.EMPTY_OBJECT)
    );

    result.type = defined(result._template.type)
      ? result._template.type
      : createGuid();

    result.shaderSource = "";
    result.materials = {};
    result.uniforms = {};
    result._uniforms = {};
    result._translucentFunctions = [];

    let translucent;

    // If the cache contains this material type, build the material template off of the stored template.
    const cachedMaterial = Material$4._materialCache.getMaterial(result.type);
    if (defined(cachedMaterial)) {
      const template = clone$1(cachedMaterial.fabric, true);
      result._template = combine$2(result._template, template, true);
      translucent = cachedMaterial.translucent;
    }

    // Make sure the template has no obvious errors. More error checking happens later.
    checkForTemplateErrors(result);

    // If the material has a new type, add it to the cache.
    if (!defined(cachedMaterial)) {
      Material$4._materialCache.addMaterial(result.type, result);
    }

    createMethodDefinition(result);
    createUniforms(result);
    createSubMaterials(result);

    const defaultTranslucent =
      result._translucentFunctions.length === 0 ? true : undefined;
    translucent = defaultValue(translucent, defaultTranslucent);
    translucent = defaultValue(options.translucent, translucent);

    if (defined(translucent)) {
      if (typeof translucent === "function") {
        const wrappedTranslucent = function () {
          return translucent(result);
        };
        result._translucentFunctions.push(wrappedTranslucent);
      } else {
        result._translucentFunctions.push(translucent);
      }
    }
  }

  function checkForValidProperties(object, properties, result, throwNotFound) {
    if (defined(object)) {
      for (const property in object) {
        if (object.hasOwnProperty(property)) {
          const hasProperty = properties.indexOf(property) !== -1;
          if (
            (throwNotFound && !hasProperty) ||
            (!throwNotFound && hasProperty)
          ) {
            result(property, properties);
          }
        }
      }
    }
  }

  function invalidNameError(property, properties) {
    //>>includeStart('debug', pragmas.debug);
    let errorString = `fabric: property name '${property}' is not valid. It should be `;
    for (let i = 0; i < properties.length; i++) {
      const propertyName = `'${properties[i]}'`;
      errorString +=
        i === properties.length - 1 ? `or ${propertyName}.` : `${propertyName}, `;
    }
    throw new DeveloperError(errorString);
    //>>includeEnd('debug');
  }

  function duplicateNameError(property, properties) {
    //>>includeStart('debug', pragmas.debug);
    const errorString = `fabric: uniforms and materials cannot share the same property '${property}'`;
    throw new DeveloperError(errorString);
    //>>includeEnd('debug');
  }

  const templateProperties = [
    "type",
    "materials",
    "uniforms",
    "components",
    "source",
  ];
  const componentProperties = [
    "diffuse",
    "specular",
    "shininess",
    "normal",
    "emission",
    "alpha",
  ];

  function checkForTemplateErrors(material) {
    const template = material._template;
    const uniforms = template.uniforms;
    const materials = template.materials;
    const components = template.components;

    // Make sure source and components do not exist in the same template.
    //>>includeStart('debug', pragmas.debug);
    if (defined(components) && defined(template.source)) {
      throw new DeveloperError(
        "fabric: cannot have source and components in the same template."
      );
    }
    //>>includeEnd('debug');

    // Make sure all template and components properties are valid.
    checkForValidProperties(template, templateProperties, invalidNameError, true);
    checkForValidProperties(
      components,
      componentProperties,
      invalidNameError,
      true
    );

    // Make sure uniforms and materials do not share any of the same names.
    const materialNames = [];
    for (const property in materials) {
      if (materials.hasOwnProperty(property)) {
        materialNames.push(property);
      }
    }
    checkForValidProperties(uniforms, materialNames, duplicateNameError, false);
  }

  function isMaterialFused(shaderComponent, material) {
    const materials = material._template.materials;
    for (const subMaterialId in materials) {
      if (materials.hasOwnProperty(subMaterialId)) {
        if (shaderComponent.indexOf(subMaterialId) > -1) {
          return true;
        }
      }
    }

    return false;
  }

  // Create the czm_getMaterial method body using source or components.
  function createMethodDefinition(material) {
    const components = material._template.components;
    const source = material._template.source;
    if (defined(source)) {
      material.shaderSource += `${source}\n`;
    } else {
      material.shaderSource +=
        "czm_material czm_getMaterial(czm_materialInput materialInput)\n{\n";
      material.shaderSource +=
        "czm_material material = czm_getDefaultMaterial(materialInput);\n";
      if (defined(components)) {
        const isMultiMaterial =
          Object.keys(material._template.materials).length > 0;
        for (const component in components) {
          if (components.hasOwnProperty(component)) {
            if (component === "diffuse" || component === "emission") {
              const isFusion =
                isMultiMaterial &&
                isMaterialFused(components[component], material);
              const componentSource = isFusion
                ? components[component]
                : `czm_gammaCorrect(${components[component]})`;
              material.shaderSource += `material.${component} = ${componentSource}; \n`;
            } else if (component === "alpha") {
              material.shaderSource += `material.alpha = ${components.alpha}; \n`;
            } else {
              material.shaderSource += `material.${component} = ${components[component]};\n`;
            }
          }
        }
      }
      material.shaderSource += "return material;\n}\n";
    }
  }

  const matrixMap = {
    mat2: Matrix2,
    mat3: Matrix3,
    mat4: Matrix4,
  };

  const ktx2Regex$3 = /\.ktx2$/i;

  function createTexture2DUpdateFunction(uniformId) {
    let oldUniformValue;
    return function (material, context) {
      const uniforms = material.uniforms;
      const uniformValue = uniforms[uniformId];
      const uniformChanged = oldUniformValue !== uniformValue;
      const uniformValueIsDefaultImage =
        !defined(uniformValue) || uniformValue === Material$4.DefaultImageId;
      oldUniformValue = uniformValue;

      let texture = material._textures[uniformId];
      let uniformDimensionsName;
      let uniformDimensions;

      if (uniformValue instanceof HTMLVideoElement) {
        // HTMLVideoElement.readyState >=2 means we have enough data for the current frame.
        // See: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/readyState
        if (uniformValue.readyState >= 2) {
          if (uniformChanged && defined(texture)) {
            if (texture !== context.defaultTexture) {
              texture.destroy();
            }
            texture = undefined;
          }

          if (!defined(texture) || texture === context.defaultTexture) {
            const sampler = new Sampler({
              minificationFilter: material._minificationFilter,
              magnificationFilter: material._magnificationFilter,
            });
            texture = new Texture({
              context: context,
              source: uniformValue,
              sampler: sampler,
            });
            material._textures[uniformId] = texture;
            return;
          }

          texture.copyFrom({
            source: uniformValue,
          });
        } else if (!defined(texture)) {
          material._textures[uniformId] = context.defaultTexture;
        }
        return;
      }

      if (uniformValue instanceof Texture && uniformValue !== texture) {
        material._texturePaths[uniformId] = undefined;
        const tmp = material._textures[uniformId];
        if (defined(tmp) && tmp !== material._defaultTexture) {
          tmp.destroy();
        }
        material._textures[uniformId] = uniformValue;

        uniformDimensionsName = `${uniformId}Dimensions`;
        if (uniforms.hasOwnProperty(uniformDimensionsName)) {
          uniformDimensions = uniforms[uniformDimensionsName];
          uniformDimensions.x = uniformValue._width;
          uniformDimensions.y = uniformValue._height;
        }

        return;
      }

      if (uniformChanged && defined(texture) && uniformValueIsDefaultImage) {
        // If the newly-assigned texture is the default texture,
        // we don't need to wait for a new image to load before destroying
        // the old texture.
        if (texture !== material._defaultTexture) {
          texture.destroy();
        }
        texture = undefined;
      }

      if (!defined(texture)) {
        material._texturePaths[uniformId] = undefined;
        texture = material._textures[uniformId] = material._defaultTexture;

        uniformDimensionsName = `${uniformId}Dimensions`;
        if (uniforms.hasOwnProperty(uniformDimensionsName)) {
          uniformDimensions = uniforms[uniformDimensionsName];
          uniformDimensions.x = texture._width;
          uniformDimensions.y = texture._height;
        }
      }

      if (uniformValueIsDefaultImage) {
        return;
      }

      // When using the entity layer, the Resource objects get recreated on getValue because
      //  they are clonable. That's why we check the url property for Resources
      //  because the instances aren't the same and we keep trying to load the same
      //  image if it fails to load.
      const isResource = uniformValue instanceof Resource;
      if (
        !defined(material._texturePaths[uniformId]) ||
        (isResource &&
          uniformValue.url !== material._texturePaths[uniformId].url) ||
        (!isResource && uniformValue !== material._texturePaths[uniformId])
      ) {
        if (typeof uniformValue === "string" || isResource) {
          const resource = isResource
            ? uniformValue
            : Resource.createIfNeeded(uniformValue);

          let promise;
          if (ktx2Regex$3.test(resource.url)) {
            promise = loadKTX2(resource.url);
          } else {
            promise = resource.fetchImage();
          }

          Promise.resolve(promise)
            .then(function (image) {
              material._loadedImages.push({
                id: uniformId,
                image: image,
              });
            })
            .catch(function () {
              if (defined(texture) && texture !== material._defaultTexture) {
                texture.destroy();
              }
              material._textures[uniformId] = material._defaultTexture;
            });
        } else if (
          uniformValue instanceof HTMLCanvasElement ||
          uniformValue instanceof HTMLImageElement
        ) {
          material._loadedImages.push({
            id: uniformId,
            image: uniformValue,
          });
        }

        material._texturePaths[uniformId] = uniformValue;
      }
    };
  }

  function createCubeMapUpdateFunction(uniformId) {
    return function (material, context) {
      const uniformValue = material.uniforms[uniformId];

      if (uniformValue instanceof CubeMap) {
        const tmp = material._textures[uniformId];
        if (tmp !== material._defaultTexture) {
          tmp.destroy();
        }
        material._texturePaths[uniformId] = undefined;
        material._textures[uniformId] = uniformValue;
        return;
      }

      if (!defined(material._textures[uniformId])) {
        material._texturePaths[uniformId] = undefined;
        material._textures[uniformId] = context.defaultCubeMap;
      }

      if (uniformValue === Material$4.DefaultCubeMapId) {
        return;
      }

      const path =
        uniformValue.positiveX +
        uniformValue.negativeX +
        uniformValue.positiveY +
        uniformValue.negativeY +
        uniformValue.positiveZ +
        uniformValue.negativeZ;

      if (path !== material._texturePaths[uniformId]) {
        const promises = [
          Resource.createIfNeeded(uniformValue.positiveX).fetchImage(),
          Resource.createIfNeeded(uniformValue.negativeX).fetchImage(),
          Resource.createIfNeeded(uniformValue.positiveY).fetchImage(),
          Resource.createIfNeeded(uniformValue.negativeY).fetchImage(),
          Resource.createIfNeeded(uniformValue.positiveZ).fetchImage(),
          Resource.createIfNeeded(uniformValue.negativeZ).fetchImage(),
        ];

        Promise.all(promises).then(function (images) {
          material._loadedCubeMaps.push({
            id: uniformId,
            images: images,
          });
        });

        material._texturePaths[uniformId] = path;
      }
    };
  }

  function createUniforms(material) {
    const uniforms = material._template.uniforms;
    for (const uniformId in uniforms) {
      if (uniforms.hasOwnProperty(uniformId)) {
        createUniform$1(material, uniformId);
      }
    }
  }

  // Writes uniform declarations to the shader file and connects uniform values with
  // corresponding material properties through the returnUniforms function.
  function createUniform$1(material, uniformId) {
    const strict = material._strict;
    const materialUniforms = material._template.uniforms;
    const uniformValue = materialUniforms[uniformId];
    const uniformType = getUniformType(uniformValue);

    //>>includeStart('debug', pragmas.debug);
    if (!defined(uniformType)) {
      throw new DeveloperError(
        `fabric: uniform '${uniformId}' has invalid type.`
      );
    }
    //>>includeEnd('debug');

    let replacedTokenCount;
    if (uniformType === "channels") {
      replacedTokenCount = replaceToken(material, uniformId, uniformValue, false);
      //>>includeStart('debug', pragmas.debug);
      if (replacedTokenCount === 0 && strict) {
        throw new DeveloperError(
          `strict: shader source does not use channels '${uniformId}'.`
        );
      }
      //>>includeEnd('debug');
    } else {
      // Since webgl doesn't allow texture dimension queries in glsl, create a uniform to do it.
      // Check if the shader source actually uses texture dimensions before creating the uniform.
      if (uniformType === "sampler2D") {
        const imageDimensionsUniformName = `${uniformId}Dimensions`;
        if (getNumberOfTokens(material, imageDimensionsUniformName) > 0) {
          materialUniforms[imageDimensionsUniformName] = {
            type: "ivec3",
            x: 1,
            y: 1,
          };
          createUniform$1(material, imageDimensionsUniformName);
        }
      }

      // Add uniform declaration to source code.
      const uniformDeclarationRegex = new RegExp(
        `uniform\\s+${uniformType}\\s+${uniformId}\\s*;`
      );
      if (!uniformDeclarationRegex.test(material.shaderSource)) {
        const uniformDeclaration = `uniform ${uniformType} ${uniformId};`;
        material.shaderSource = uniformDeclaration + material.shaderSource;
      }

      const newUniformId = `${uniformId}_${material._count++}`;
      replacedTokenCount = replaceToken(material, uniformId, newUniformId);
      //>>includeStart('debug', pragmas.debug);
      if (replacedTokenCount === 1 && strict) {
        throw new DeveloperError(
          `strict: shader source does not use uniform '${uniformId}'.`
        );
      }
      //>>includeEnd('debug');

      // Set uniform value
      material.uniforms[uniformId] = uniformValue;

      if (uniformType === "sampler2D") {
        material._uniforms[newUniformId] = function () {
          return material._textures[uniformId];
        };
        material._updateFunctions.push(createTexture2DUpdateFunction(uniformId));
      } else if (uniformType === "samplerCube") {
        material._uniforms[newUniformId] = function () {
          return material._textures[uniformId];
        };
        material._updateFunctions.push(createCubeMapUpdateFunction(uniformId));
      } else if (uniformType.indexOf("mat") !== -1) {
        const scratchMatrix = new matrixMap[uniformType]();
        material._uniforms[newUniformId] = function () {
          return matrixMap[uniformType].fromColumnMajorArray(
            material.uniforms[uniformId],
            scratchMatrix
          );
        };
      } else {
        material._uniforms[newUniformId] = function () {
          return material.uniforms[uniformId];
        };
      }
    }
  }

  // Determines the uniform type based on the uniform in the template.
  function getUniformType(uniformValue) {
    let uniformType = uniformValue.type;
    if (!defined(uniformType)) {
      const type = typeof uniformValue;
      if (type === "number") {
        uniformType = "float";
      } else if (type === "boolean") {
        uniformType = "bool";
      } else if (
        type === "string" ||
        uniformValue instanceof Resource ||
        uniformValue instanceof HTMLCanvasElement ||
        uniformValue instanceof HTMLImageElement
      ) {
        if (/^([rgba]){1,4}$/i.test(uniformValue)) {
          uniformType = "channels";
        } else if (uniformValue === Material$4.DefaultCubeMapId) {
          uniformType = "samplerCube";
        } else {
          uniformType = "sampler2D";
        }
      } else if (type === "object") {
        if (Array.isArray(uniformValue)) {
          if (
            uniformValue.length === 4 ||
            uniformValue.length === 9 ||
            uniformValue.length === 16
          ) {
            uniformType = `mat${Math.sqrt(uniformValue.length)}`;
          }
        } else {
          let numAttributes = 0;
          for (const attribute in uniformValue) {
            if (uniformValue.hasOwnProperty(attribute)) {
              numAttributes += 1;
            }
          }
          if (numAttributes >= 2 && numAttributes <= 4) {
            uniformType = `vec${numAttributes}`;
          } else if (numAttributes === 6) {
            uniformType = "samplerCube";
          }
        }
      }
    }
    return uniformType;
  }

  // Create all sub-materials by combining source and uniforms together.
  function createSubMaterials(material) {
    const strict = material._strict;
    const subMaterialTemplates = material._template.materials;
    for (const subMaterialId in subMaterialTemplates) {
      if (subMaterialTemplates.hasOwnProperty(subMaterialId)) {
        // Construct the sub-material.
        const subMaterial = new Material$4({
          strict: strict,
          fabric: subMaterialTemplates[subMaterialId],
          count: material._count,
        });

        material._count = subMaterial._count;
        material._uniforms = combine$2(
          material._uniforms,
          subMaterial._uniforms,
          true
        );
        material.materials[subMaterialId] = subMaterial;
        material._translucentFunctions = material._translucentFunctions.concat(
          subMaterial._translucentFunctions
        );

        // Make the material's czm_getMaterial unique by appending the sub-material type.
        const originalMethodName = "czm_getMaterial";
        const newMethodName = `${originalMethodName}_${material._count++}`;
        replaceToken(subMaterial, originalMethodName, newMethodName);
        material.shaderSource = subMaterial.shaderSource + material.shaderSource;

        // Replace each material id with an czm_getMaterial method call.
        const materialMethodCall = `${newMethodName}(materialInput)`;
        const tokensReplacedCount = replaceToken(
          material,
          subMaterialId,
          materialMethodCall
        );
        //>>includeStart('debug', pragmas.debug);
        if (tokensReplacedCount === 0 && strict) {
          throw new DeveloperError(
            `strict: shader source does not use material '${subMaterialId}'.`
          );
        }
        //>>includeEnd('debug');
      }
    }
  }

  // Used for searching or replacing a token in a material's shader source with something else.
  // If excludePeriod is true, do not accept tokens that are preceded by periods.
  // http://stackoverflow.com/questions/641407/javascript-negative-lookbehind-equivalent
  function replaceToken(material, token, newToken, excludePeriod) {
    excludePeriod = defaultValue(excludePeriod, true);
    let count = 0;
    const suffixChars = "([\\w])?";
    const prefixChars = `([\\w${excludePeriod ? "." : ""}])?`;
    const regExp = new RegExp(prefixChars + token + suffixChars, "g");
    material.shaderSource = material.shaderSource.replace(regExp, function (
      $0,
      $1,
      $2
    ) {
      if ($1 || $2) {
        return $0;
      }
      count += 1;
      return newToken;
    });
    return count;
  }

  function getNumberOfTokens(material, token, excludePeriod) {
    return replaceToken(material, token, token, excludePeriod);
  }

  Material$4._materialCache = {
    _materials: {},
    addMaterial: function (type, materialTemplate) {
      this._materials[type] = materialTemplate;
    },
    getMaterial: function (type) {
      return this._materials[type];
    },
  };

  /**
   * Gets or sets the default texture uniform value.
   * @type {String}
   */
  Material$4.DefaultImageId = "czm_defaultImage";

  /**
   * Gets or sets the default cube map texture uniform value.
   * @type {String}
   */
  Material$4.DefaultCubeMapId = "czm_defaultCubeMap";

  /**
   * Gets the name of the color material.
   * @type {String}
   * @readonly
   */
  Material$4.ColorType = "Color";
  Material$4._materialCache.addMaterial(Material$4.ColorType, {
    fabric: {
      type: Material$4.ColorType,
      uniforms: {
        color: new Color(1.0, 0.0, 0.0, 0.5),
      },
      components: {
        diffuse: "color.rgb",
        alpha: "color.a",
      },
    },
    translucent: function (material) {
      return material.uniforms.color.alpha < 1.0;
    },
  });

  /**
   * Gets the name of the image material.
   * @type {String}
   * @readonly
   */
  Material$4.ImageType = "Image";
  Material$4._materialCache.addMaterial(Material$4.ImageType, {
    fabric: {
      type: Material$4.ImageType,
      uniforms: {
        image: Material$4.DefaultImageId,
        repeat: new Cartesian2(1.0, 1.0),
        color: new Color(1.0, 1.0, 1.0, 1.0),
      },
      components: {
        diffuse:
          "texture2D(image, fract(repeat * materialInput.st)).rgb * color.rgb",
        alpha: "texture2D(image, fract(repeat * materialInput.st)).a * color.a",
      },
    },
    translucent: function (material) {
      return material.uniforms.color.alpha < 1.0;
    },
  });

  /**
   * Gets the name of the diffuce map material.
   * @type {String}
   * @readonly
   */
  Material$4.DiffuseMapType = "DiffuseMap";
  Material$4._materialCache.addMaterial(Material$4.DiffuseMapType, {
    fabric: {
      type: Material$4.DiffuseMapType,
      uniforms: {
        image: Material$4.DefaultImageId,
        channels: "rgb",
        repeat: new Cartesian2(1.0, 1.0),
      },
      components: {
        diffuse: "texture2D(image, fract(repeat * materialInput.st)).channels",
      },
    },
    translucent: false,
  });

  /**
   * Gets the name of the alpha map material.
   * @type {String}
   * @readonly
   */
  Material$4.AlphaMapType = "AlphaMap";
  Material$4._materialCache.addMaterial(Material$4.AlphaMapType, {
    fabric: {
      type: Material$4.AlphaMapType,
      uniforms: {
        image: Material$4.DefaultImageId,
        channel: "a",
        repeat: new Cartesian2(1.0, 1.0),
      },
      components: {
        alpha: "texture2D(image, fract(repeat * materialInput.st)).channel",
      },
    },
    translucent: true,
  });

  /**
   * Gets the name of the specular map material.
   * @type {String}
   * @readonly
   */
  Material$4.SpecularMapType = "SpecularMap";
  Material$4._materialCache.addMaterial(Material$4.SpecularMapType, {
    fabric: {
      type: Material$4.SpecularMapType,
      uniforms: {
        image: Material$4.DefaultImageId,
        channel: "r",
        repeat: new Cartesian2(1.0, 1.0),
      },
      components: {
        specular: "texture2D(image, fract(repeat * materialInput.st)).channel",
      },
    },
    translucent: false,
  });

  /**
   * Gets the name of the emmision map material.
   * @type {String}
   * @readonly
   */
  Material$4.EmissionMapType = "EmissionMap";
  Material$4._materialCache.addMaterial(Material$4.EmissionMapType, {
    fabric: {
      type: Material$4.EmissionMapType,
      uniforms: {
        image: Material$4.DefaultImageId,
        channels: "rgb",
        repeat: new Cartesian2(1.0, 1.0),
      },
      components: {
        emission: "texture2D(image, fract(repeat * materialInput.st)).channels",
      },
    },
    translucent: false,
  });

  /**
   * Gets the name of the bump map material.
   * @type {String}
   * @readonly
   */
  Material$4.BumpMapType = "BumpMap";
  Material$4._materialCache.addMaterial(Material$4.BumpMapType, {
    fabric: {
      type: Material$4.BumpMapType,
      uniforms: {
        image: Material$4.DefaultImageId,
        channel: "r",
        strength: 0.8,
        repeat: new Cartesian2(1.0, 1.0),
      },
      source: BumpMapMaterial,
    },
    translucent: false,
  });

  /**
   * Gets the name of the normal map material.
   * @type {String}
   * @readonly
   */
  Material$4.NormalMapType = "NormalMap";
  Material$4._materialCache.addMaterial(Material$4.NormalMapType, {
    fabric: {
      type: Material$4.NormalMapType,
      uniforms: {
        image: Material$4.DefaultImageId,
        channels: "rgb",
        strength: 0.8,
        repeat: new Cartesian2(1.0, 1.0),
      },
      source: NormalMapMaterial,
    },
    translucent: false,
  });

  /**
   * Gets the name of the grid material.
   * @type {String}
   * @readonly
   */
  Material$4.GridType = "Grid";
  Material$4._materialCache.addMaterial(Material$4.GridType, {
    fabric: {
      type: Material$4.GridType,
      uniforms: {
        color: new Color(0.0, 1.0, 0.0, 1.0),
        cellAlpha: 0.1,
        lineCount: new Cartesian2(8.0, 8.0),
        lineThickness: new Cartesian2(1.0, 1.0),
        lineOffset: new Cartesian2(0.0, 0.0),
      },
      source: GridMaterial,
    },
    translucent: function (material) {
      const uniforms = material.uniforms;
      return uniforms.color.alpha < 1.0 || uniforms.cellAlpha < 1.0;
    },
  });

  /**
   * Gets the name of the stripe material.
   * @type {String}
   * @readonly
   */
  Material$4.StripeType = "Stripe";
  Material$4._materialCache.addMaterial(Material$4.StripeType, {
    fabric: {
      type: Material$4.StripeType,
      uniforms: {
        horizontal: true,
        evenColor: new Color(1.0, 1.0, 1.0, 0.5),
        oddColor: new Color(0.0, 0.0, 1.0, 0.5),
        offset: 0.0,
        repeat: 5.0,
      },
      source: StripeMaterial,
    },
    translucent: function (material) {
      const uniforms = material.uniforms;
      return uniforms.evenColor.alpha < 1.0 || uniforms.oddColor.alpha < 1.0;
    },
  });

  /**
   * Gets the name of the checkerboard material.
   * @type {String}
   * @readonly
   */
  Material$4.CheckerboardType = "Checkerboard";
  Material$4._materialCache.addMaterial(Material$4.CheckerboardType, {
    fabric: {
      type: Material$4.CheckerboardType,
      uniforms: {
        lightColor: new Color(1.0, 1.0, 1.0, 0.5),
        darkColor: new Color(0.0, 0.0, 0.0, 0.5),
        repeat: new Cartesian2(5.0, 5.0),
      },
      source: CheckerboardMaterial,
    },
    translucent: function (material) {
      const uniforms = material.uniforms;
      return uniforms.lightColor.alpha < 1.0 || uniforms.darkColor.alpha < 1.0;
    },
  });

  /**
   * Gets the name of the dot material.
   * @type {String}
   * @readonly
   */
  Material$4.DotType = "Dot";
  Material$4._materialCache.addMaterial(Material$4.DotType, {
    fabric: {
      type: Material$4.DotType,
      uniforms: {
        lightColor: new Color(1.0, 1.0, 0.0, 0.75),
        darkColor: new Color(0.0, 1.0, 1.0, 0.75),
        repeat: new Cartesian2(5.0, 5.0),
      },
      source: DotMaterial,
    },
    translucent: function (material) {
      const uniforms = material.uniforms;
      return uniforms.lightColor.alpha < 1.0 || uniforms.darkColor.alpha < 1.0;
    },
  });

  /**
   * Gets the name of the water material.
   * @type {String}
   * @readonly
   */
  Material$4.WaterType = "Water";
  Material$4._materialCache.addMaterial(Material$4.WaterType, {
    fabric: {
      type: Material$4.WaterType,
      uniforms: {
        baseWaterColor: new Color(0.2, 0.3, 0.6, 1.0),
        blendColor: new Color(0.0, 1.0, 0.699, 1.0),
        specularMap: Material$4.DefaultImageId,
        normalMap: Material$4.DefaultImageId,
        frequency: 10.0,
        animationSpeed: 0.01,
        amplitude: 1.0,
        specularIntensity: 0.5,
        fadeFactor: 1.0,
      },
      source: WaterMaterial,
    },
    translucent: function (material) {
      const uniforms = material.uniforms;
      return (
        uniforms.baseWaterColor.alpha < 1.0 || uniforms.blendColor.alpha < 1.0
      );
    },
  });

  /**
   * Gets the name of the rim lighting material.
   * @type {String}
   * @readonly
   */
  Material$4.RimLightingType = "RimLighting";
  Material$4._materialCache.addMaterial(Material$4.RimLightingType, {
    fabric: {
      type: Material$4.RimLightingType,
      uniforms: {
        color: new Color(1.0, 0.0, 0.0, 0.7),
        rimColor: new Color(1.0, 1.0, 1.0, 0.4),
        width: 0.3,
      },
      source: RimLightingMaterial,
    },
    translucent: function (material) {
      const uniforms = material.uniforms;
      return uniforms.color.alpha < 1.0 || uniforms.rimColor.alpha < 1.0;
    },
  });

  /**
   * Gets the name of the fade material.
   * @type {String}
   * @readonly
   */
  Material$4.FadeType = "Fade";
  Material$4._materialCache.addMaterial(Material$4.FadeType, {
    fabric: {
      type: Material$4.FadeType,
      uniforms: {
        fadeInColor: new Color(1.0, 0.0, 0.0, 1.0),
        fadeOutColor: new Color(0.0, 0.0, 0.0, 0.0),
        maximumDistance: 0.5,
        repeat: true,
        fadeDirection: {
          x: true,
          y: true,
        },
        time: new Cartesian2(0.5, 0.5),
      },
      source: FadeMaterial,
    },
    translucent: function (material) {
      const uniforms = material.uniforms;
      return (
        uniforms.fadeInColor.alpha < 1.0 || uniforms.fadeOutColor.alpha < 1.0
      );
    },
  });

  /**
   * Gets the name of the polyline arrow material.
   * @type {String}
   * @readonly
   */
  Material$4.PolylineArrowType = "PolylineArrow";
  Material$4._materialCache.addMaterial(Material$4.PolylineArrowType, {
    fabric: {
      type: Material$4.PolylineArrowType,
      uniforms: {
        color: new Color(1.0, 1.0, 1.0, 1.0),
      },
      source: PolylineArrowMaterial,
    },
    translucent: true,
  });

  /**
   * Gets the name of the polyline glow material.
   * @type {String}
   * @readonly
   */
  Material$4.PolylineDashType = "PolylineDash";
  Material$4._materialCache.addMaterial(Material$4.PolylineDashType, {
    fabric: {
      type: Material$4.PolylineDashType,
      uniforms: {
        color: new Color(1.0, 0.0, 1.0, 1.0),
        gapColor: new Color(0.0, 0.0, 0.0, 0.0),
        dashLength: 16.0,
        dashPattern: 255.0,
      },
      source: PolylineDashMaterial,
    },
    translucent: true,
  });

  /**
   * Gets the name of the polyline glow material.
   * @type {String}
   * @readonly
   */
  Material$4.PolylineGlowType = "PolylineGlow";
  Material$4._materialCache.addMaterial(Material$4.PolylineGlowType, {
    fabric: {
      type: Material$4.PolylineGlowType,
      uniforms: {
        color: new Color(0.0, 0.5, 1.0, 1.0),
        glowPower: 0.25,
        taperPower: 1.0,
      },
      source: PolylineGlowMaterial,
    },
    translucent: true,
  });

  /**
   * Gets the name of the polyline outline material.
   * @type {String}
   * @readonly
   */
  Material$4.PolylineOutlineType = "PolylineOutline";
  Material$4._materialCache.addMaterial(Material$4.PolylineOutlineType, {
    fabric: {
      type: Material$4.PolylineOutlineType,
      uniforms: {
        color: new Color(1.0, 1.0, 1.0, 1.0),
        outlineColor: new Color(1.0, 0.0, 0.0, 1.0),
        outlineWidth: 1.0,
      },
      source: PolylineOutlineMaterial,
    },
    translucent: function (material) {
      const uniforms = material.uniforms;
      return uniforms.color.alpha < 1.0 || uniforms.outlineColor.alpha < 1.0;
    },
  });

  /**
   * Gets the name of the elevation contour material.
   * @type {String}
   * @readonly
   */
  Material$4.ElevationContourType = "ElevationContour";
  Material$4._materialCache.addMaterial(Material$4.ElevationContourType, {
    fabric: {
      type: Material$4.ElevationContourType,
      uniforms: {
        spacing: 100.0,
        color: new Color(1.0, 0.0, 0.0, 1.0),
        width: 1.0,
      },
      source: ElevationContourMaterial,
    },
    translucent: false,
  });

  /**
   * Gets the name of the elevation contour material.
   * @type {String}
   * @readonly
   */
  Material$4.ElevationRampType = "ElevationRamp";
  Material$4._materialCache.addMaterial(Material$4.ElevationRampType, {
    fabric: {
      type: Material$4.ElevationRampType,
      uniforms: {
        image: Material$4.DefaultImageId,
        minimumHeight: 0.0,
        maximumHeight: 10000.0,
      },
      source: ElevationRampMaterial,
    },
    translucent: false,
  });

  /**
   * Gets the name of the slope ramp material.
   * @type {String}
   * @readonly
   */
  Material$4.SlopeRampMaterialType = "SlopeRamp";
  Material$4._materialCache.addMaterial(Material$4.SlopeRampMaterialType, {
    fabric: {
      type: Material$4.SlopeRampMaterialType,
      uniforms: {
        image: Material$4.DefaultImageId,
      },
      source: SlopeRampMaterial,
    },
    translucent: false,
  });

  /**
   * Gets the name of the aspect ramp material.
   * @type {String}
   * @readonly
   */
  Material$4.AspectRampMaterialType = "AspectRamp";
  Material$4._materialCache.addMaterial(Material$4.AspectRampMaterialType, {
    fabric: {
      type: Material$4.AspectRampMaterialType,
      uniforms: {
        image: Material$4.DefaultImageId,
      },
      source: AspectRampMaterial,
    },
    translucent: false,
  });

  /**
   * Gets the name of the elevation band material.
   * @type {String}
   * @readonly
   */
  Material$4.ElevationBandType = "ElevationBand";
  Material$4._materialCache.addMaterial(Material$4.ElevationBandType, {
    fabric: {
      type: Material$4.ElevationBandType,
      uniforms: {
        heights: Material$4.DefaultImageId,
        colors: Material$4.DefaultImageId,
      },
      source: ElevationBandMaterial,
    },
    translucent: true,
  });

  /**
       * An appearance for arbitrary geometry (as opposed to {@link EllipsoidSurfaceAppearance}, for example)
       * that supports shading with materials.
       *
       * @alias MaterialAppearance
       * @constructor
       *
       * @param {Object} [options] Object with the following properties:
       * @param {Boolean} [options.flat=false] When <code>true</code>, flat shading is used in the fragment shader, which means lighting is not taking into account.
       * @param {Boolean} [options.faceForward=!options.closed] When <code>true</code>, the fragment shader flips the surface normal as needed to ensure that the normal faces the viewer to avoid dark spots.  This is useful when both sides of a geometry should be shaded like {@link WallGeometry}.
       * @param {Boolean} [options.translucent=true] When <code>true</code>, the geometry is expected to appear translucent so {@link MaterialAppearance#renderState} has alpha blending enabled.
       * @param {Boolean} [options.closed=false] When <code>true</code>, the geometry is expected to be closed so {@link MaterialAppearance#renderState} has backface culling enabled.
       * @param {MaterialAppearance.MaterialSupportType} [options.materialSupport=MaterialAppearance.MaterialSupport.TEXTURED] The type of materials that will be supported.
       * @param {Material} [options.material=Material.ColorType] The material used to determine the fragment color.
       * @param {String} [options.vertexShaderSource] Optional GLSL vertex shader source to override the default vertex shader.
       * @param {String} [options.fragmentShaderSource] Optional GLSL fragment shader source to override the default fragment shader.
       * @param {Object} [options.renderState] Optional render state to override the default render state.
       *
       * @see {@link https://github.com/CesiumGS/cesium/wiki/Fabric|Fabric}
       * @demo {@link https://sandcastle.cesium.com/index.html?src=Materials.html|Cesium Sandcastle Material Appearance Demo}
       *
       * @example
       * const primitive = new Cesium.Primitive({
       *   geometryInstances : new Cesium.GeometryInstance({
       *     geometry : new Cesium.WallGeometry({
              materialSupport :  Cesium.MaterialAppearance.MaterialSupport.BASIC.vertexFormat,
       *       // ...
       *     })
       *   }),
       *   appearance : new Cesium.MaterialAppearance({
       *     material : Cesium.Material.fromType('Color'),
       *     faceForward : true
       *   })
       *
       * });
       */
  function MaterialAppearance(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const translucent = defaultValue(options.translucent, true);
    const closed = defaultValue(options.closed, false);
    const materialSupport = defaultValue(
      options.materialSupport,
      MaterialAppearance.MaterialSupport.TEXTURED
    );

    /**
     * The material used to determine the fragment color.  Unlike other {@link MaterialAppearance}
     * properties, this is not read-only, so an appearance's material can change on the fly.
     *
     * @type Material
     *
     * @default {@link Material.ColorType}
     *
     * @see {@link https://github.com/CesiumGS/cesium/wiki/Fabric|Fabric}
     */
    this.material = defined(options.material)
      ? options.material
      : Material$4.fromType(Material$4.ColorType);

    /**
     * When <code>true</code>, the geometry is expected to appear translucent.
     *
     * @type {Boolean}
     *
     * @default true
     */
    this.translucent = translucent;

    this._vertexShaderSource = defaultValue(
      options.vertexShaderSource,
      materialSupport.vertexShaderSource
    );
    this._fragmentShaderSource = defaultValue(
      options.fragmentShaderSource,
      materialSupport.fragmentShaderSource
    );
    this._renderState = Appearance.getDefaultRenderState(
      translucent,
      closed,
      options.renderState
    );
    this._closed = closed;

    // Non-derived members

    this._materialSupport = materialSupport;
    this._vertexFormat = materialSupport.vertexFormat;
    this._flat = defaultValue(options.flat, false);
    this._faceForward = defaultValue(options.faceForward, !closed);
  }

  Object.defineProperties(MaterialAppearance.prototype, {
    /**
     * The GLSL source code for the vertex shader.
     *
     * @memberof MaterialAppearance.prototype
     *
     * @type {String}
     * @readonly
     */
    vertexShaderSource: {
      get: function () {
        return this._vertexShaderSource;
      },
    },

    /**
     * The GLSL source code for the fragment shader.  The full fragment shader
     * source is built procedurally taking into account {@link MaterialAppearance#material},
     * {@link MaterialAppearance#flat}, and {@link MaterialAppearance#faceForward}.
     * Use {@link MaterialAppearance#getFragmentShaderSource} to get the full source.
     *
     * @memberof MaterialAppearance.prototype
     *
     * @type {String}
     * @readonly
     */
    fragmentShaderSource: {
      get: function () {
        return this._fragmentShaderSource;
      },
    },

    /**
     * The WebGL fixed-function state to use when rendering the geometry.
     * <p>
     * The render state can be explicitly defined when constructing a {@link MaterialAppearance}
     * instance, or it is set implicitly via {@link MaterialAppearance#translucent}
     * and {@link MaterialAppearance#closed}.
     * </p>
     *
     * @memberof MaterialAppearance.prototype
     *
     * @type {Object}
     * @readonly
     */
    renderState: {
      get: function () {
        return this._renderState;
      },
    },

    /**
     * When <code>true</code>, the geometry is expected to be closed so
     * {@link MaterialAppearance#renderState} has backface culling enabled.
     * If the viewer enters the geometry, it will not be visible.
     *
     * @memberof MaterialAppearance.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default false
     */
    closed: {
      get: function () {
        return this._closed;
      },
    },

    /**
     * The type of materials supported by this instance.  This impacts the required
     * {@link VertexFormat} and the complexity of the vertex and fragment shaders.
     *
     * @memberof MaterialAppearance.prototype
     *
     * @type {MaterialAppearance.MaterialSupportType}
     * @readonly
     *
     * @default {@link MaterialAppearance.MaterialSupport.TEXTURED}
     */
    materialSupport: {
      get: function () {
        return this._materialSupport;
      },
    },

    /**
     * The {@link VertexFormat} that this appearance instance is compatible with.
     * A geometry can have more vertex attributes and still be compatible - at a
     * potential performance cost - but it can't have less.
     *
     * @memberof MaterialAppearance.prototype
     *
     * @type VertexFormat
     * @readonly
     *
     * @default {@link MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat}
     */
    vertexFormat: {
      get: function () {
        return this._vertexFormat;
      },
    },

    /**
     * When <code>true</code>, flat shading is used in the fragment shader,
     * which means lighting is not taking into account.
     *
     * @memberof MaterialAppearance.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default false
     */
    flat: {
      get: function () {
        return this._flat;
      },
    },

    /**
     * When <code>true</code>, the fragment shader flips the surface normal
     * as needed to ensure that the normal faces the viewer to avoid
     * dark spots.  This is useful when both sides of a geometry should be
     * shaded like {@link WallGeometry}.
     *
     * @memberof MaterialAppearance.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default true
     */
    faceForward: {
      get: function () {
        return this._faceForward;
      },
    },
  });

  /**
   * Procedurally creates the full GLSL fragment shader source.  For {@link MaterialAppearance},
   * this is derived from {@link MaterialAppearance#fragmentShaderSource}, {@link MaterialAppearance#material},
   * {@link MaterialAppearance#flat}, and {@link MaterialAppearance#faceForward}.
   *
   * @function
   *
   * @returns {String} The full GLSL fragment shader source.
   */
  MaterialAppearance.prototype.getFragmentShaderSource =
    Appearance.prototype.getFragmentShaderSource;

  /**
   * Determines if the geometry is translucent based on {@link MaterialAppearance#translucent} and {@link Material#isTranslucent}.
   *
   * @function
   *
   * @returns {Boolean} <code>true</code> if the appearance is translucent.
   */
  MaterialAppearance.prototype.isTranslucent = Appearance.prototype.isTranslucent;

  /**
   * Creates a render state.  This is not the final render state instance; instead,
   * it can contain a subset of render state properties identical to the render state
   * created in the context.
   *
   * @function
   *
   * @returns {Object} The render state.
   */
  MaterialAppearance.prototype.getRenderState =
    Appearance.prototype.getRenderState;

  /**
   * @typedef MaterialAppearance.MaterialSupportType
   * @type {Object}
   * @property {VertexFormat} vertexFormat
   * @property {String} vertexShaderSource
   * @property {String} fragmentShaderSource
   */

  /**
   * Determines the type of {@link Material} that is supported by a
   * {@link MaterialAppearance} instance.  This is a trade-off between
   * flexibility (a wide array of materials) and memory/performance
   * (required vertex format and GLSL shader complexity.
   * @namespace
   */
  MaterialAppearance.MaterialSupport = {
    /**
     * Only basic materials, which require just <code>position</code> and
     * <code>normal</code> vertex attributes, are supported.
     *
     * @type {MaterialAppearance.MaterialSupportType}
     * @constant
     */
    BASIC: Object.freeze({
      vertexFormat: VertexFormat.POSITION_AND_NORMAL,
      vertexShaderSource: BasicMaterialAppearanceVS,
      fragmentShaderSource: BasicMaterialAppearanceFS,
    }),
    /**
     * Materials with textures, which require <code>position</code>,
     * <code>normal</code>, and <code>st</code> vertex attributes,
     * are supported.  The vast majority of materials fall into this category.
     *
     * @type {MaterialAppearance.MaterialSupportType}
     * @constant
     */
    TEXTURED: Object.freeze({
      vertexFormat: VertexFormat.POSITION_NORMAL_AND_ST,
      vertexShaderSource: TexturedMaterialAppearanceVS,
      fragmentShaderSource: TexturedMaterialAppearanceFS,
    }),
    /**
     * All materials, including those that work in tangent space, are supported.
     * This requires <code>position</code>, <code>normal</code>, <code>st</code>,
     * <code>tangent</code>, and <code>bitangent</code> vertex attributes.
     *
     * @type {MaterialAppearance.MaterialSupportType}
     * @constant
     */
    ALL: Object.freeze({
      vertexFormat: VertexFormat.ALL,
      vertexShaderSource: AllMaterialAppearanceVS,
      fragmentShaderSource: AllMaterialAppearanceFS,
    }),
  };

  //This file is automatically rebuilt by the Cesium build process.
  var PerInstanceColorAppearanceFS = "varying vec3 v_positionEC;\n\
varying vec3 v_normalEC;\n\
varying vec4 v_color;\n\
void main()\n\
{\n\
vec3 positionToEyeEC = -v_positionEC;\n\
vec3 normalEC = normalize(v_normalEC);\n\
#ifdef FACE_FORWARD\n\
normalEC = faceforward(normalEC, vec3(0.0, 0.0, 1.0), -normalEC);\n\
#endif\n\
vec4 color = czm_gammaCorrect(v_color);\n\
czm_materialInput materialInput;\n\
materialInput.normalEC = normalEC;\n\
materialInput.positionToEyeEC = positionToEyeEC;\n\
czm_material material = czm_getDefaultMaterial(materialInput);\n\
material.diffuse = color.rgb;\n\
material.alpha = color.a;\n\
gl_FragColor = czm_phong(normalize(positionToEyeEC), material, czm_lightDirectionEC);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var PerInstanceColorAppearanceVS = "attribute vec3 position3DHigh;\n\
attribute vec3 position3DLow;\n\
attribute vec3 normal;\n\
attribute vec4 color;\n\
attribute float batchId;\n\
varying vec3 v_positionEC;\n\
varying vec3 v_normalEC;\n\
varying vec4 v_color;\n\
void main()\n\
{\n\
vec4 p = czm_computePosition();\n\
v_positionEC = (czm_modelViewRelativeToEye * p).xyz;\n\
v_normalEC = czm_normal * normal;\n\
v_color = color;\n\
gl_Position = czm_modelViewProjectionRelativeToEye * p;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var PerInstanceFlatColorAppearanceFS = "varying vec4 v_color;\n\
void main()\n\
{\n\
gl_FragColor = czm_gammaCorrect(v_color);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var PerInstanceFlatColorAppearanceVS = "attribute vec3 position3DHigh;\n\
attribute vec3 position3DLow;\n\
attribute vec4 color;\n\
attribute float batchId;\n\
varying vec4 v_color;\n\
void main()\n\
{\n\
vec4 p = czm_computePosition();\n\
v_color = color;\n\
gl_Position = czm_modelViewProjectionRelativeToEye * p;\n\
}\n\
";

  /**
   * An appearance for {@link GeometryInstance} instances with color attributes.
   * This allows several geometry instances, each with a different color, to
   * be drawn with the same {@link Primitive} as shown in the second example below.
   *
   * @alias PerInstanceColorAppearance
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Boolean} [options.flat=false] When <code>true</code>, flat shading is used in the fragment shader, which means lighting is not taking into account.
   * @param {Boolean} [options.faceForward=!options.closed] When <code>true</code>, the fragment shader flips the surface normal as needed to ensure that the normal faces the viewer to avoid dark spots.  This is useful when both sides of a geometry should be shaded like {@link WallGeometry}.
   * @param {Boolean} [options.translucent=true] When <code>true</code>, the geometry is expected to appear translucent so {@link PerInstanceColorAppearance#renderState} has alpha blending enabled.
   * @param {Boolean} [options.closed=false] When <code>true</code>, the geometry is expected to be closed so {@link PerInstanceColorAppearance#renderState} has backface culling enabled.
   * @param {String} [options.vertexShaderSource] Optional GLSL vertex shader source to override the default vertex shader.
   * @param {String} [options.fragmentShaderSource] Optional GLSL fragment shader source to override the default fragment shader.
   * @param {Object} [options.renderState] Optional render state to override the default render state.
   *
   * @example
   * // A solid white line segment
   * const primitive = new Cesium.Primitive({
   *   geometryInstances : new Cesium.GeometryInstance({
   *     geometry : new Cesium.SimplePolylineGeometry({
   *       positions : Cesium.Cartesian3.fromDegreesArray([
   *         0.0, 0.0,
   *         5.0, 0.0
   *       ])
   *     }),
   *     attributes : {
   *       color : Cesium.ColorGeometryInstanceAttribute.fromColor(new Cesium.Color(1.0, 1.0, 1.0, 1.0))
   *     }
   *   }),
   *   appearance : new Cesium.PerInstanceColorAppearance({
   *     flat : true,
   *     translucent : false
   *   })
   * });
   *
   * // Two rectangles in a primitive, each with a different color
   * const instance = new Cesium.GeometryInstance({
   *   geometry : new Cesium.RectangleGeometry({
   *     rectangle : Cesium.Rectangle.fromDegrees(0.0, 20.0, 10.0, 30.0)
   *   }),
   *   attributes : {
   *     color : new Cesium.ColorGeometryInstanceAttribute(1.0, 0.0, 0.0, 0.5)
   *   }
   * });
   *
   * const anotherInstance = new Cesium.GeometryInstance({
   *   geometry : new Cesium.RectangleGeometry({
   *     rectangle : Cesium.Rectangle.fromDegrees(0.0, 40.0, 10.0, 50.0)
   *   }),
   *   attributes : {
   *     color : new Cesium.ColorGeometryInstanceAttribute(0.0, 0.0, 1.0, 0.5)
   *   }
   * });
   *
   * const rectanglePrimitive = new Cesium.Primitive({
   *   geometryInstances : [instance, anotherInstance],
   *   appearance : new Cesium.PerInstanceColorAppearance()
   * });
   */
  function PerInstanceColorAppearance(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const translucent = defaultValue(options.translucent, true);
    const closed = defaultValue(options.closed, false);
    const flat = defaultValue(options.flat, false);
    const vs = flat
      ? PerInstanceFlatColorAppearanceVS
      : PerInstanceColorAppearanceVS;
    const fs = flat
      ? PerInstanceFlatColorAppearanceFS
      : PerInstanceColorAppearanceFS;
    const vertexFormat = flat
      ? PerInstanceColorAppearance.FLAT_VERTEX_FORMAT
      : PerInstanceColorAppearance.VERTEX_FORMAT;

    /**
     * This property is part of the {@link Appearance} interface, but is not
     * used by {@link PerInstanceColorAppearance} since a fully custom fragment shader is used.
     *
     * @type Material
     *
     * @default undefined
     */
    this.material = undefined;

    /**
     * When <code>true</code>, the geometry is expected to appear translucent so
     * {@link PerInstanceColorAppearance#renderState} has alpha blending enabled.
     *
     * @type {Boolean}
     *
     * @default true
     */
    this.translucent = translucent;

    this._vertexShaderSource = defaultValue(options.vertexShaderSource, vs);
    this._fragmentShaderSource = defaultValue(options.fragmentShaderSource, fs);
    this._renderState = Appearance.getDefaultRenderState(
      translucent,
      closed,
      options.renderState
    );
    this._closed = closed;

    // Non-derived members

    this._vertexFormat = vertexFormat;
    this._flat = flat;
    this._faceForward = defaultValue(options.faceForward, !closed);
  }

  Object.defineProperties(PerInstanceColorAppearance.prototype, {
    /**
     * The GLSL source code for the vertex shader.
     *
     * @memberof PerInstanceColorAppearance.prototype
     *
     * @type {String}
     * @readonly
     */
    vertexShaderSource: {
      get: function () {
        return this._vertexShaderSource;
      },
    },

    /**
     * The GLSL source code for the fragment shader.
     *
     * @memberof PerInstanceColorAppearance.prototype
     *
     * @type {String}
     * @readonly
     */
    fragmentShaderSource: {
      get: function () {
        return this._fragmentShaderSource;
      },
    },

    /**
     * The WebGL fixed-function state to use when rendering the geometry.
     * <p>
     * The render state can be explicitly defined when constructing a {@link PerInstanceColorAppearance}
     * instance, or it is set implicitly via {@link PerInstanceColorAppearance#translucent}
     * and {@link PerInstanceColorAppearance#closed}.
     * </p>
     *
     * @memberof PerInstanceColorAppearance.prototype
     *
     * @type {Object}
     * @readonly
     */
    renderState: {
      get: function () {
        return this._renderState;
      },
    },

    /**
     * When <code>true</code>, the geometry is expected to be closed so
     * {@link PerInstanceColorAppearance#renderState} has backface culling enabled.
     * If the viewer enters the geometry, it will not be visible.
     *
     * @memberof PerInstanceColorAppearance.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default false
     */
    closed: {
      get: function () {
        return this._closed;
      },
    },

    /**
     * The {@link VertexFormat} that this appearance instance is compatible with.
     * A geometry can have more vertex attributes and still be compatible - at a
     * potential performance cost - but it can't have less.
     *
     * @memberof PerInstanceColorAppearance.prototype
     *
     * @type VertexFormat
     * @readonly
     */
    vertexFormat: {
      get: function () {
        return this._vertexFormat;
      },
    },

    /**
     * When <code>true</code>, flat shading is used in the fragment shader,
     * which means lighting is not taking into account.
     *
     * @memberof PerInstanceColorAppearance.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default false
     */
    flat: {
      get: function () {
        return this._flat;
      },
    },

    /**
     * When <code>true</code>, the fragment shader flips the surface normal
     * as needed to ensure that the normal faces the viewer to avoid
     * dark spots.  This is useful when both sides of a geometry should be
     * shaded like {@link WallGeometry}.
     *
     * @memberof PerInstanceColorAppearance.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default true
     */
    faceForward: {
      get: function () {
        return this._faceForward;
      },
    },
  });

  /**
   * The {@link VertexFormat} that all {@link PerInstanceColorAppearance} instances
   * are compatible with.  This requires only <code>position</code> and <code>normal</code>
   * attributes.
   *
   * @type VertexFormat
   *
   * @constant
   */
  PerInstanceColorAppearance.VERTEX_FORMAT = VertexFormat.POSITION_AND_NORMAL;

  /**
   * The {@link VertexFormat} that all {@link PerInstanceColorAppearance} instances
   * are compatible with when {@link PerInstanceColorAppearance#flat} is <code>true</code>.
   * This requires only a <code>position</code> attribute.
   *
   * @type VertexFormat
   *
   * @constant
   */
  PerInstanceColorAppearance.FLAT_VERTEX_FORMAT = VertexFormat.POSITION_ONLY;

  /**
   * Procedurally creates the full GLSL fragment shader source.  For {@link PerInstanceColorAppearance},
   * this is derived from {@link PerInstanceColorAppearance#fragmentShaderSource}, {@link PerInstanceColorAppearance#flat},
   * and {@link PerInstanceColorAppearance#faceForward}.
   *
   * @function
   *
   * @returns {String} The full GLSL fragment shader source.
   */
  PerInstanceColorAppearance.prototype.getFragmentShaderSource =
    Appearance.prototype.getFragmentShaderSource;

  /**
   * Determines if the geometry is translucent based on {@link PerInstanceColorAppearance#translucent}.
   *
   * @function
   *
   * @returns {Boolean} <code>true</code> if the appearance is translucent.
   */
  PerInstanceColorAppearance.prototype.isTranslucent =
    Appearance.prototype.isTranslucent;

  /**
   * Creates a render state.  This is not the final render state instance; instead,
   * it can contain a subset of render state properties identical to the render state
   * created in the context.
   *
   * @function
   *
   * @returns {Object} The render state.
   */
  PerInstanceColorAppearance.prototype.getRenderState =
    Appearance.prototype.getRenderState;

  /**
   * A {@link MaterialProperty} that maps to solid color {@link Material} uniforms.
   *
   * @param {Property|Color} [color=Color.WHITE] The {@link Color} Property to be used.
   *
   * @alias ColorMaterialProperty
   * @constructor
   */
  function ColorMaterialProperty(color) {
    this._definitionChanged = new Event();
    this._color = undefined;
    this._colorSubscription = undefined;

    this.color = color;
  }

  Object.defineProperties(ColorMaterialProperty.prototype, {
    /**
     * Gets a value indicating if this property is constant.  A property is considered
     * constant if getValue always returns the same result for the current definition.
     * @memberof ColorMaterialProperty.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    isConstant: {
      get: function () {
        return Property.isConstant(this._color);
      },
    },

    /**
     * Gets the event that is raised whenever the definition of this property changes.
     * The definition is considered to have changed if a call to getValue would return
     * a different result for the same time.
     * @memberof ColorMaterialProperty.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },

    /**
     * Gets or sets the {@link Color} {@link Property}.
     * @memberof ColorMaterialProperty.prototype
     * @type {Property|undefined}
     * @default Color.WHITE
     */
    color: createPropertyDescriptor("color"),
  });

  /**
   * Gets the {@link Material} type at the provided time.
   *
   * @param {JulianDate} time The time for which to retrieve the type.
   * @returns {String} The type of material.
   */
  ColorMaterialProperty.prototype.getType = function (time) {
    return "Color";
  };

  /**
   * Gets the value of the property at the provided time.
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {Object} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Object} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  ColorMaterialProperty.prototype.getValue = function (time, result) {
    if (!defined(result)) {
      result = {};
    }
    result.color = Property.getValueOrClonedDefault(
      this._color,
      time,
      Color.WHITE,
      result.color
    );
    return result;
  };

  /**
   * Compares this property to the provided property and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Property} [other] The other property.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  ColorMaterialProperty.prototype.equals = function (other) {
    return (
      this === other || //
      (other instanceof ColorMaterialProperty && //
        Property.equals(this._color, other._color))
    );
  };

  const Flags = {
    CULL: 1,
    OCCLUDE: 2,
    EXECUTE_IN_CLOSEST_FRUSTUM: 4,
    DEBUG_SHOW_BOUNDING_VOLUME: 8,
    CAST_SHADOWS: 16,
    RECEIVE_SHADOWS: 32,
    PICK_ONLY: 64,
    DEPTH_FOR_TRANSLUCENT_CLASSIFICATION: 128,
  };

  /**
   * Represents a command to the renderer for drawing.
   *
   * @private
   */
  function DrawCommand(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    this._boundingVolume = options.boundingVolume;
    this._orientedBoundingBox = options.orientedBoundingBox;
    this._modelMatrix = options.modelMatrix;
    this._primitiveType = defaultValue(
      options.primitiveType,
      PrimitiveType$1.TRIANGLES
    );
    this._vertexArray = options.vertexArray;
    this._count = options.count;
    this._offset = defaultValue(options.offset, 0);
    this._instanceCount = defaultValue(options.instanceCount, 0);
    this._shaderProgram = options.shaderProgram;
    this._uniformMap = options.uniformMap;
    this._renderState = options.renderState;
    this._framebuffer = options.framebuffer;
    this._pass = options.pass;
    this._owner = options.owner;
    this._debugOverlappingFrustums = 0;
    this._pickId = options.pickId;

    // Set initial flags.
    this._flags = 0;
    this.cull = defaultValue(options.cull, true);
    this.occlude = defaultValue(options.occlude, true);
    this.executeInClosestFrustum = defaultValue(
      options.executeInClosestFrustum,
      false
    );
    this.debugShowBoundingVolume = defaultValue(
      options.debugShowBoundingVolume,
      false
    );
    this.castShadows = defaultValue(options.castShadows, false);
    this.receiveShadows = defaultValue(options.receiveShadows, false);
    this.pickOnly = defaultValue(options.pickOnly, false);
    this.depthForTranslucentClassification = defaultValue(
      options.depthForTranslucentClassification,
      false
    );

    this.dirty = true;
    this.lastDirtyTime = 0;

    /**
     * @private
     */
    this.derivedCommands = {};
  }

  function hasFlag(command, flag) {
    return (command._flags & flag) === flag;
  }

  function setFlag(command, flag, value) {
    if (value) {
      command._flags |= flag;
    } else {
      command._flags &= ~flag;
    }
  }

  Object.defineProperties(DrawCommand.prototype, {
    /**
     * The bounding volume of the geometry in world space.  This is used for culling and frustum selection.
     * <p>
     * For best rendering performance, use the tightest possible bounding volume.  Although
     * <code>undefined</code> is allowed, always try to provide a bounding volume to
     * allow the tightest possible near and far planes to be computed for the scene, and
     * minimize the number of frustums needed.
     * </p>
     *
     * @memberof DrawCommand.prototype
     * @type {Object}
     * @default undefined
     *
     * @see DrawCommand#debugShowBoundingVolume
     */
    boundingVolume: {
      get: function () {
        return this._boundingVolume;
      },
      set: function (value) {
        if (this._boundingVolume !== value) {
          this._boundingVolume = value;
          this.dirty = true;
        }
      },
    },

    /**
     * The oriented bounding box of the geometry in world space. If this is defined, it is used instead of
     * {@link DrawCommand#boundingVolume} for plane intersection testing.
     *
     * @memberof DrawCommand.prototype
     * @type {OrientedBoundingBox}
     * @default undefined
     *
     * @see DrawCommand#debugShowBoundingVolume
     */
    orientedBoundingBox: {
      get: function () {
        return this._orientedBoundingBox;
      },
      set: function (value) {
        if (this._orientedBoundingBox !== value) {
          this._orientedBoundingBox = value;
          this.dirty = true;
        }
      },
    },

    /**
     * When <code>true</code>, the renderer frustum and horizon culls the command based on its {@link DrawCommand#boundingVolume}.
     * If the command was already culled, set this to <code>false</code> for a performance improvement.
     *
     * @memberof DrawCommand.prototype
     * @type {Boolean}
     * @default true
     */
    cull: {
      get: function () {
        return hasFlag(this, Flags.CULL);
      },
      set: function (value) {
        if (hasFlag(this, Flags.CULL) !== value) {
          setFlag(this, Flags.CULL, value);
          this.dirty = true;
        }
      },
    },

    /**
     * When <code>true</code>, the horizon culls the command based on its {@link DrawCommand#boundingVolume}.
     * {@link DrawCommand#cull} must also be <code>true</code> in order for the command to be culled.
     *
     * @memberof DrawCommand.prototype
     * @type {Boolean}
     * @default true
     */
    occlude: {
      get: function () {
        return hasFlag(this, Flags.OCCLUDE);
      },
      set: function (value) {
        if (hasFlag(this, Flags.OCCLUDE) !== value) {
          setFlag(this, Flags.OCCLUDE, value);
          this.dirty = true;
        }
      },
    },

    /**
     * The transformation from the geometry in model space to world space.
     * <p>
     * When <code>undefined</code>, the geometry is assumed to be defined in world space.
     * </p>
     *
     * @memberof DrawCommand.prototype
     * @type {Matrix4}
     * @default undefined
     */
    modelMatrix: {
      get: function () {
        return this._modelMatrix;
      },
      set: function (value) {
        if (this._modelMatrix !== value) {
          this._modelMatrix = value;
          this.dirty = true;
        }
      },
    },

    /**
     * The type of geometry in the vertex array.
     *
     * @memberof DrawCommand.prototype
     * @type {PrimitiveType}
     * @default PrimitiveType.TRIANGLES
     */
    primitiveType: {
      get: function () {
        return this._primitiveType;
      },
      set: function (value) {
        if (this._primitiveType !== value) {
          this._primitiveType = value;
          this.dirty = true;
        }
      },
    },

    /**
     * The vertex array.
     *
     * @memberof DrawCommand.prototype
     * @type {VertexArray}
     * @default undefined
     */
    vertexArray: {
      get: function () {
        return this._vertexArray;
      },
      set: function (value) {
        if (this._vertexArray !== value) {
          this._vertexArray = value;
          this.dirty = true;
        }
      },
    },

    /**
     * The number of vertices to draw in the vertex array.
     *
     * @memberof DrawCommand.prototype
     * @type {Number}
     * @default undefined
     */
    count: {
      get: function () {
        return this._count;
      },
      set: function (value) {
        if (this._count !== value) {
          this._count = value;
          this.dirty = true;
        }
      },
    },

    /**
     * The offset to start drawing in the vertex array.
     *
     * @memberof DrawCommand.prototype
     * @type {Number}
     * @default 0
     */
    offset: {
      get: function () {
        return this._offset;
      },
      set: function (value) {
        if (this._offset !== value) {
          this._offset = value;
          this.dirty = true;
        }
      },
    },

    /**
     * The number of instances to draw.
     *
     * @memberof DrawCommand.prototype
     * @type {Number}
     * @default 0
     */
    instanceCount: {
      get: function () {
        return this._instanceCount;
      },
      set: function (value) {
        if (this._instanceCount !== value) {
          this._instanceCount = value;
          this.dirty = true;
        }
      },
    },

    /**
     * The shader program to apply.
     *
     * @memberof DrawCommand.prototype
     * @type {ShaderProgram}
     * @default undefined
     */
    shaderProgram: {
      get: function () {
        return this._shaderProgram;
      },
      set: function (value) {
        if (this._shaderProgram !== value) {
          this._shaderProgram = value;
          this.dirty = true;
        }
      },
    },

    /**
     * Whether this command should cast shadows when shadowing is enabled.
     *
     * @memberof DrawCommand.prototype
     * @type {Boolean}
     * @default false
     */
    castShadows: {
      get: function () {
        return hasFlag(this, Flags.CAST_SHADOWS);
      },
      set: function (value) {
        if (hasFlag(this, Flags.CAST_SHADOWS) !== value) {
          setFlag(this, Flags.CAST_SHADOWS, value);
          this.dirty = true;
        }
      },
    },

    /**
     * Whether this command should receive shadows when shadowing is enabled.
     *
     * @memberof DrawCommand.prototype
     * @type {Boolean}
     * @default false
     */
    receiveShadows: {
      get: function () {
        return hasFlag(this, Flags.RECEIVE_SHADOWS);
      },
      set: function (value) {
        if (hasFlag(this, Flags.RECEIVE_SHADOWS) !== value) {
          setFlag(this, Flags.RECEIVE_SHADOWS, value);
          this.dirty = true;
        }
      },
    },

    /**
     * An object with functions whose names match the uniforms in the shader program
     * and return values to set those uniforms.
     *
     * @memberof DrawCommand.prototype
     * @type {Object}
     * @default undefined
     */
    uniformMap: {
      get: function () {
        return this._uniformMap;
      },
      set: function (value) {
        if (this._uniformMap !== value) {
          this._uniformMap = value;
          this.dirty = true;
        }
      },
    },

    /**
     * The render state.
     *
     * @memberof DrawCommand.prototype
     * @type {RenderState}
     * @default undefined
     */
    renderState: {
      get: function () {
        return this._renderState;
      },
      set: function (value) {
        if (this._renderState !== value) {
          this._renderState = value;
          this.dirty = true;
        }
      },
    },

    /**
     * The framebuffer to draw to.
     *
     * @memberof DrawCommand.prototype
     * @type {Framebuffer}
     * @default undefined
     */
    framebuffer: {
      get: function () {
        return this._framebuffer;
      },
      set: function (value) {
        if (this._framebuffer !== value) {
          this._framebuffer = value;
          this.dirty = true;
        }
      },
    },

    /**
     * The pass when to render.
     *
     * @memberof DrawCommand.prototype
     * @type {Pass}
     * @default undefined
     */
    pass: {
      get: function () {
        return this._pass;
      },
      set: function (value) {
        if (this._pass !== value) {
          this._pass = value;
          this.dirty = true;
        }
      },
    },

    /**
     * Specifies if this command is only to be executed in the frustum closest
     * to the eye containing the bounding volume. Defaults to <code>false</code>.
     *
     * @memberof DrawCommand.prototype
     * @type {Boolean}
     * @default false
     */
    executeInClosestFrustum: {
      get: function () {
        return hasFlag(this, Flags.EXECUTE_IN_CLOSEST_FRUSTUM);
      },
      set: function (value) {
        if (hasFlag(this, Flags.EXECUTE_IN_CLOSEST_FRUSTUM) !== value) {
          setFlag(this, Flags.EXECUTE_IN_CLOSEST_FRUSTUM, value);
          this.dirty = true;
        }
      },
    },

    /**
     * The object who created this command.  This is useful for debugging command
     * execution; it allows us to see who created a command when we only have a
     * reference to the command, and can be used to selectively execute commands
     * with {@link Scene#debugCommandFilter}.
     *
     * @memberof DrawCommand.prototype
     * @type {Object}
     * @default undefined
     *
     * @see Scene#debugCommandFilter
     */
    owner: {
      get: function () {
        return this._owner;
      },
      set: function (value) {
        if (this._owner !== value) {
          this._owner = value;
          this.dirty = true;
        }
      },
    },

    /**
     * This property is for debugging only; it is not for production use nor is it optimized.
     * <p>
     * Draws the {@link DrawCommand#boundingVolume} for this command, assuming it is a sphere, when the command executes.
     * </p>
     *
     * @memberof DrawCommand.prototype
     * @type {Boolean}
     * @default false
     *
     * @see DrawCommand#boundingVolume
     */
    debugShowBoundingVolume: {
      get: function () {
        return hasFlag(this, Flags.DEBUG_SHOW_BOUNDING_VOLUME);
      },
      set: function (value) {
        if (hasFlag(this, Flags.DEBUG_SHOW_BOUNDING_VOLUME) !== value) {
          setFlag(this, Flags.DEBUG_SHOW_BOUNDING_VOLUME, value);
          this.dirty = true;
        }
      },
    },

    /**
     * Used to implement Scene.debugShowFrustums.
     * @private
     */
    debugOverlappingFrustums: {
      get: function () {
        return this._debugOverlappingFrustums;
      },
      set: function (value) {
        if (this._debugOverlappingFrustums !== value) {
          this._debugOverlappingFrustums = value;
          this.dirty = true;
        }
      },
    },
    /**
     * A GLSL string that will evaluate to a pick id. When <code>undefined</code>, the command will only draw depth
     * during the pick pass.
     *
     * @memberof DrawCommand.prototype
     * @type {String}
     * @default undefined
     */
    pickId: {
      get: function () {
        return this._pickId;
      },
      set: function (value) {
        if (this._pickId !== value) {
          this._pickId = value;
          this.dirty = true;
        }
      },
    },
    /**
     * Whether this command should be executed in the pick pass only.
     *
     * @memberof DrawCommand.prototype
     * @type {Boolean}
     * @default false
     */
    pickOnly: {
      get: function () {
        return hasFlag(this, Flags.PICK_ONLY);
      },
      set: function (value) {
        if (hasFlag(this, Flags.PICK_ONLY) !== value) {
          setFlag(this, Flags.PICK_ONLY, value);
          this.dirty = true;
        }
      },
    },
    /**
     * Whether this command should be derived to draw depth for classification of translucent primitives.
     *
     * @memberof DrawCommand.prototype
     * @type {Boolean}
     * @default false
     */
    depthForTranslucentClassification: {
      get: function () {
        return hasFlag(this, Flags.DEPTH_FOR_TRANSLUCENT_CLASSIFICATION);
      },
      set: function (value) {
        if (hasFlag(this, Flags.DEPTH_FOR_TRANSLUCENT_CLASSIFICATION) !== value) {
          setFlag(this, Flags.DEPTH_FOR_TRANSLUCENT_CLASSIFICATION, value);
          this.dirty = true;
        }
      },
    },
  });

  /**
   * @private
   */
  DrawCommand.shallowClone = function (command, result) {
    if (!defined(command)) {
      return undefined;
    }
    if (!defined(result)) {
      result = new DrawCommand();
    }

    result._boundingVolume = command._boundingVolume;
    result._orientedBoundingBox = command._orientedBoundingBox;
    result._modelMatrix = command._modelMatrix;
    result._primitiveType = command._primitiveType;
    result._vertexArray = command._vertexArray;
    result._count = command._count;
    result._offset = command._offset;
    result._instanceCount = command._instanceCount;
    result._shaderProgram = command._shaderProgram;
    result._uniformMap = command._uniformMap;
    result._renderState = command._renderState;
    result._framebuffer = command._framebuffer;
    result._pass = command._pass;
    result._owner = command._owner;
    result._debugOverlappingFrustums = command._debugOverlappingFrustums;
    result._pickId = command._pickId;
    result._flags = command._flags;

    result.dirty = true;
    result.lastDirtyTime = 0;

    return result;
  };

  /**
   * Executes the draw command.
   *
   * @param {Context} context The renderer context in which to draw.
   * @param {PassState} [passState] The state for the current render pass.
   */
  DrawCommand.prototype.execute = function (context, passState) {
    context.draw(this, passState);
  };

  /**
   * The render pass for a command.
   *
   * @private
   */
  const Pass = {
    // If you add/modify/remove Pass constants, also change the automatic GLSL constants
    // that start with 'czm_pass'
    //
    // Commands are executed in order by pass up to the translucent pass.
    // Translucent geometry needs special handling (sorting/OIT). The compute pass
    // is executed first and the overlay pass is executed last. Both are not sorted
    // by frustum.
    ENVIRONMENT: 0,
    COMPUTE: 1,
    GLOBE: 2,
    TERRAIN_CLASSIFICATION: 3,
    CESIUM_3D_TILE: 4,
    CESIUM_3D_TILE_CLASSIFICATION: 5,
    CESIUM_3D_TILE_CLASSIFICATION_IGNORE_SHOW: 6,
    OPAQUE: 7,
    TRANSLUCENT: 8,
    OVERLAY: 9,
    NUMBER_OF_PASSES: 10,
  };
  var Pass$1 = Object.freeze(Pass);

  /**
   * Returns frozen renderState as well as all of the object literal properties. This function is deep object freeze
   * function ignoring properties named "_applyFunctions".
   *
   * @private
   *
   * @param {Object} renderState
   * @returns {Object} Returns frozen renderState.
   *
   */
  function freezeRenderState(renderState) {
    if (typeof renderState !== "object" || renderState === null) {
      return renderState;
    }

    let propName;
    const propNames = Object.keys(renderState);

    for (let i = 0; i < propNames.length; i++) {
      propName = propNames[i];
      if (
        renderState.hasOwnProperty(propName) &&
        propName !== "_applyFunctions"
      ) {
        renderState[propName] = freezeRenderState(renderState[propName]);
      }
    }
    return Object.freeze(renderState);
  }

  function validateBlendEquation(blendEquation) {
    return (
      blendEquation === WebGLConstants$1.FUNC_ADD ||
      blendEquation === WebGLConstants$1.FUNC_SUBTRACT ||
      blendEquation === WebGLConstants$1.FUNC_REVERSE_SUBTRACT ||
      blendEquation === WebGLConstants$1.MIN ||
      blendEquation === WebGLConstants$1.MAX
    );
  }

  function validateBlendFunction(blendFunction) {
    return (
      blendFunction === WebGLConstants$1.ZERO ||
      blendFunction === WebGLConstants$1.ONE ||
      blendFunction === WebGLConstants$1.SRC_COLOR ||
      blendFunction === WebGLConstants$1.ONE_MINUS_SRC_COLOR ||
      blendFunction === WebGLConstants$1.DST_COLOR ||
      blendFunction === WebGLConstants$1.ONE_MINUS_DST_COLOR ||
      blendFunction === WebGLConstants$1.SRC_ALPHA ||
      blendFunction === WebGLConstants$1.ONE_MINUS_SRC_ALPHA ||
      blendFunction === WebGLConstants$1.DST_ALPHA ||
      blendFunction === WebGLConstants$1.ONE_MINUS_DST_ALPHA ||
      blendFunction === WebGLConstants$1.CONSTANT_COLOR ||
      blendFunction === WebGLConstants$1.ONE_MINUS_CONSTANT_COLOR ||
      blendFunction === WebGLConstants$1.CONSTANT_ALPHA ||
      blendFunction === WebGLConstants$1.ONE_MINUS_CONSTANT_ALPHA ||
      blendFunction === WebGLConstants$1.SRC_ALPHA_SATURATE
    );
  }

  function validateCullFace(cullFace) {
    return (
      cullFace === WebGLConstants$1.FRONT ||
      cullFace === WebGLConstants$1.BACK ||
      cullFace === WebGLConstants$1.FRONT_AND_BACK
    );
  }

  function validateDepthFunction(depthFunction) {
    return (
      depthFunction === WebGLConstants$1.NEVER ||
      depthFunction === WebGLConstants$1.LESS ||
      depthFunction === WebGLConstants$1.EQUAL ||
      depthFunction === WebGLConstants$1.LEQUAL ||
      depthFunction === WebGLConstants$1.GREATER ||
      depthFunction === WebGLConstants$1.NOTEQUAL ||
      depthFunction === WebGLConstants$1.GEQUAL ||
      depthFunction === WebGLConstants$1.ALWAYS
    );
  }

  function validateStencilFunction(stencilFunction) {
    return (
      stencilFunction === WebGLConstants$1.NEVER ||
      stencilFunction === WebGLConstants$1.LESS ||
      stencilFunction === WebGLConstants$1.EQUAL ||
      stencilFunction === WebGLConstants$1.LEQUAL ||
      stencilFunction === WebGLConstants$1.GREATER ||
      stencilFunction === WebGLConstants$1.NOTEQUAL ||
      stencilFunction === WebGLConstants$1.GEQUAL ||
      stencilFunction === WebGLConstants$1.ALWAYS
    );
  }

  function validateStencilOperation(stencilOperation) {
    return (
      stencilOperation === WebGLConstants$1.ZERO ||
      stencilOperation === WebGLConstants$1.KEEP ||
      stencilOperation === WebGLConstants$1.REPLACE ||
      stencilOperation === WebGLConstants$1.INCR ||
      stencilOperation === WebGLConstants$1.DECR ||
      stencilOperation === WebGLConstants$1.INVERT ||
      stencilOperation === WebGLConstants$1.INCR_WRAP ||
      stencilOperation === WebGLConstants$1.DECR_WRAP
    );
  }

  /**
   * @private
   */
  function RenderState(renderState) {
    const rs = defaultValue(renderState, defaultValue.EMPTY_OBJECT);
    const cull = defaultValue(rs.cull, defaultValue.EMPTY_OBJECT);
    const polygonOffset = defaultValue(
      rs.polygonOffset,
      defaultValue.EMPTY_OBJECT
    );
    const scissorTest = defaultValue(rs.scissorTest, defaultValue.EMPTY_OBJECT);
    const scissorTestRectangle = defaultValue(
      scissorTest.rectangle,
      defaultValue.EMPTY_OBJECT
    );
    const depthRange = defaultValue(rs.depthRange, defaultValue.EMPTY_OBJECT);
    const depthTest = defaultValue(rs.depthTest, defaultValue.EMPTY_OBJECT);
    const colorMask = defaultValue(rs.colorMask, defaultValue.EMPTY_OBJECT);
    const blending = defaultValue(rs.blending, defaultValue.EMPTY_OBJECT);
    const blendingColor = defaultValue(blending.color, defaultValue.EMPTY_OBJECT);
    const stencilTest = defaultValue(rs.stencilTest, defaultValue.EMPTY_OBJECT);
    const stencilTestFrontOperation = defaultValue(
      stencilTest.frontOperation,
      defaultValue.EMPTY_OBJECT
    );
    const stencilTestBackOperation = defaultValue(
      stencilTest.backOperation,
      defaultValue.EMPTY_OBJECT
    );
    const sampleCoverage = defaultValue(
      rs.sampleCoverage,
      defaultValue.EMPTY_OBJECT
    );
    const viewport = rs.viewport;

    this.frontFace = defaultValue(rs.frontFace, WindingOrder$1.COUNTER_CLOCKWISE);
    this.cull = {
      enabled: defaultValue(cull.enabled, false),
      face: defaultValue(cull.face, WebGLConstants$1.BACK),
    };
    this.lineWidth = defaultValue(rs.lineWidth, 1.0);
    this.polygonOffset = {
      enabled: defaultValue(polygonOffset.enabled, false),
      factor: defaultValue(polygonOffset.factor, 0),
      units: defaultValue(polygonOffset.units, 0),
    };
    this.scissorTest = {
      enabled: defaultValue(scissorTest.enabled, false),
      rectangle: BoundingRectangle.clone(scissorTestRectangle),
    };
    this.depthRange = {
      near: defaultValue(depthRange.near, 0),
      far: defaultValue(depthRange.far, 1),
    };
    this.depthTest = {
      enabled: defaultValue(depthTest.enabled, false),
      func: defaultValue(depthTest.func, WebGLConstants$1.LESS), // func, because function is a JavaScript keyword
    };
    this.colorMask = {
      red: defaultValue(colorMask.red, true),
      green: defaultValue(colorMask.green, true),
      blue: defaultValue(colorMask.blue, true),
      alpha: defaultValue(colorMask.alpha, true),
    };
    this.depthMask = defaultValue(rs.depthMask, true);
    this.stencilMask = defaultValue(rs.stencilMask, ~0);
    this.blending = {
      enabled: defaultValue(blending.enabled, false),
      color: new Color(
        defaultValue(blendingColor.red, 0.0),
        defaultValue(blendingColor.green, 0.0),
        defaultValue(blendingColor.blue, 0.0),
        defaultValue(blendingColor.alpha, 0.0)
      ),
      equationRgb: defaultValue(blending.equationRgb, WebGLConstants$1.FUNC_ADD),
      equationAlpha: defaultValue(
        blending.equationAlpha,
        WebGLConstants$1.FUNC_ADD
      ),
      functionSourceRgb: defaultValue(
        blending.functionSourceRgb,
        WebGLConstants$1.ONE
      ),
      functionSourceAlpha: defaultValue(
        blending.functionSourceAlpha,
        WebGLConstants$1.ONE
      ),
      functionDestinationRgb: defaultValue(
        blending.functionDestinationRgb,
        WebGLConstants$1.ZERO
      ),
      functionDestinationAlpha: defaultValue(
        blending.functionDestinationAlpha,
        WebGLConstants$1.ZERO
      ),
    };
    this.stencilTest = {
      enabled: defaultValue(stencilTest.enabled, false),
      frontFunction: defaultValue(
        stencilTest.frontFunction,
        WebGLConstants$1.ALWAYS
      ),
      backFunction: defaultValue(stencilTest.backFunction, WebGLConstants$1.ALWAYS),
      reference: defaultValue(stencilTest.reference, 0),
      mask: defaultValue(stencilTest.mask, ~0),
      frontOperation: {
        fail: defaultValue(stencilTestFrontOperation.fail, WebGLConstants$1.KEEP),
        zFail: defaultValue(stencilTestFrontOperation.zFail, WebGLConstants$1.KEEP),
        zPass: defaultValue(stencilTestFrontOperation.zPass, WebGLConstants$1.KEEP),
      },
      backOperation: {
        fail: defaultValue(stencilTestBackOperation.fail, WebGLConstants$1.KEEP),
        zFail: defaultValue(stencilTestBackOperation.zFail, WebGLConstants$1.KEEP),
        zPass: defaultValue(stencilTestBackOperation.zPass, WebGLConstants$1.KEEP),
      },
    };
    this.sampleCoverage = {
      enabled: defaultValue(sampleCoverage.enabled, false),
      value: defaultValue(sampleCoverage.value, 1.0),
      invert: defaultValue(sampleCoverage.invert, false),
    };
    this.viewport = defined(viewport)
      ? new BoundingRectangle(
          viewport.x,
          viewport.y,
          viewport.width,
          viewport.height
        )
      : undefined;

    //>>includeStart('debug', pragmas.debug);
    if (
      this.lineWidth < ContextLimits.minimumAliasedLineWidth ||
      this.lineWidth > ContextLimits.maximumAliasedLineWidth
    ) {
      throw new DeveloperError(
        "renderState.lineWidth is out of range.  Check minimumAliasedLineWidth and maximumAliasedLineWidth."
      );
    }
    if (!WindingOrder$1.validate(this.frontFace)) {
      throw new DeveloperError("Invalid renderState.frontFace.");
    }
    if (!validateCullFace(this.cull.face)) {
      throw new DeveloperError("Invalid renderState.cull.face.");
    }
    if (
      this.scissorTest.rectangle.width < 0 ||
      this.scissorTest.rectangle.height < 0
    ) {
      throw new DeveloperError(
        "renderState.scissorTest.rectangle.width and renderState.scissorTest.rectangle.height must be greater than or equal to zero."
      );
    }
    if (this.depthRange.near > this.depthRange.far) {
      // WebGL specific - not an error in GL ES
      throw new DeveloperError(
        "renderState.depthRange.near can not be greater than renderState.depthRange.far."
      );
    }
    if (this.depthRange.near < 0) {
      // Would be clamped by GL
      throw new DeveloperError(
        "renderState.depthRange.near must be greater than or equal to zero."
      );
    }
    if (this.depthRange.far > 1) {
      // Would be clamped by GL
      throw new DeveloperError(
        "renderState.depthRange.far must be less than or equal to one."
      );
    }
    if (!validateDepthFunction(this.depthTest.func)) {
      throw new DeveloperError("Invalid renderState.depthTest.func.");
    }
    if (
      this.blending.color.red < 0.0 ||
      this.blending.color.red > 1.0 ||
      this.blending.color.green < 0.0 ||
      this.blending.color.green > 1.0 ||
      this.blending.color.blue < 0.0 ||
      this.blending.color.blue > 1.0 ||
      this.blending.color.alpha < 0.0 ||
      this.blending.color.alpha > 1.0
    ) {
      // Would be clamped by GL
      throw new DeveloperError(
        "renderState.blending.color components must be greater than or equal to zero and less than or equal to one."
      );
    }
    if (!validateBlendEquation(this.blending.equationRgb)) {
      throw new DeveloperError("Invalid renderState.blending.equationRgb.");
    }
    if (!validateBlendEquation(this.blending.equationAlpha)) {
      throw new DeveloperError("Invalid renderState.blending.equationAlpha.");
    }
    if (!validateBlendFunction(this.blending.functionSourceRgb)) {
      throw new DeveloperError("Invalid renderState.blending.functionSourceRgb.");
    }
    if (!validateBlendFunction(this.blending.functionSourceAlpha)) {
      throw new DeveloperError(
        "Invalid renderState.blending.functionSourceAlpha."
      );
    }
    if (!validateBlendFunction(this.blending.functionDestinationRgb)) {
      throw new DeveloperError(
        "Invalid renderState.blending.functionDestinationRgb."
      );
    }
    if (!validateBlendFunction(this.blending.functionDestinationAlpha)) {
      throw new DeveloperError(
        "Invalid renderState.blending.functionDestinationAlpha."
      );
    }
    if (!validateStencilFunction(this.stencilTest.frontFunction)) {
      throw new DeveloperError("Invalid renderState.stencilTest.frontFunction.");
    }
    if (!validateStencilFunction(this.stencilTest.backFunction)) {
      throw new DeveloperError("Invalid renderState.stencilTest.backFunction.");
    }
    if (!validateStencilOperation(this.stencilTest.frontOperation.fail)) {
      throw new DeveloperError(
        "Invalid renderState.stencilTest.frontOperation.fail."
      );
    }
    if (!validateStencilOperation(this.stencilTest.frontOperation.zFail)) {
      throw new DeveloperError(
        "Invalid renderState.stencilTest.frontOperation.zFail."
      );
    }
    if (!validateStencilOperation(this.stencilTest.frontOperation.zPass)) {
      throw new DeveloperError(
        "Invalid renderState.stencilTest.frontOperation.zPass."
      );
    }
    if (!validateStencilOperation(this.stencilTest.backOperation.fail)) {
      throw new DeveloperError(
        "Invalid renderState.stencilTest.backOperation.fail."
      );
    }
    if (!validateStencilOperation(this.stencilTest.backOperation.zFail)) {
      throw new DeveloperError(
        "Invalid renderState.stencilTest.backOperation.zFail."
      );
    }
    if (!validateStencilOperation(this.stencilTest.backOperation.zPass)) {
      throw new DeveloperError(
        "Invalid renderState.stencilTest.backOperation.zPass."
      );
    }

    if (defined(this.viewport)) {
      if (this.viewport.width < 0) {
        throw new DeveloperError(
          "renderState.viewport.width must be greater than or equal to zero."
        );
      }
      if (this.viewport.height < 0) {
        throw new DeveloperError(
          "renderState.viewport.height must be greater than or equal to zero."
        );
      }

      if (this.viewport.width > ContextLimits.maximumViewportWidth) {
        throw new DeveloperError(
          `renderState.viewport.width must be less than or equal to the maximum viewport width (${ContextLimits.maximumViewportWidth.toString()}).  Check maximumViewportWidth.`
        );
      }
      if (this.viewport.height > ContextLimits.maximumViewportHeight) {
        throw new DeveloperError(
          `renderState.viewport.height must be less than or equal to the maximum viewport height (${ContextLimits.maximumViewportHeight.toString()}).  Check maximumViewportHeight.`
        );
      }
    }
    //>>includeEnd('debug');

    this.id = 0;
    this._applyFunctions = [];
  }

  let nextRenderStateId = 0;
  let renderStateCache = {};

  /**
   * Validates and then finds or creates an immutable render state, which defines the pipeline
   * state for a {@link DrawCommand} or {@link ClearCommand}.  All inputs states are optional.  Omitted states
   * use the defaults shown in the example below.
   *
   * @param {Object} [renderState] The states defining the render state as shown in the example below.
   *
   * @exception {RuntimeError} renderState.lineWidth is out of range.
   * @exception {DeveloperError} Invalid renderState.frontFace.
   * @exception {DeveloperError} Invalid renderState.cull.face.
   * @exception {DeveloperError} scissorTest.rectangle.width and scissorTest.rectangle.height must be greater than or equal to zero.
   * @exception {DeveloperError} renderState.depthRange.near can't be greater than renderState.depthRange.far.
   * @exception {DeveloperError} renderState.depthRange.near must be greater than or equal to zero.
   * @exception {DeveloperError} renderState.depthRange.far must be less than or equal to zero.
   * @exception {DeveloperError} Invalid renderState.depthTest.func.
   * @exception {DeveloperError} renderState.blending.color components must be greater than or equal to zero and less than or equal to one
   * @exception {DeveloperError} Invalid renderState.blending.equationRgb.
   * @exception {DeveloperError} Invalid renderState.blending.equationAlpha.
   * @exception {DeveloperError} Invalid renderState.blending.functionSourceRgb.
   * @exception {DeveloperError} Invalid renderState.blending.functionSourceAlpha.
   * @exception {DeveloperError} Invalid renderState.blending.functionDestinationRgb.
   * @exception {DeveloperError} Invalid renderState.blending.functionDestinationAlpha.
   * @exception {DeveloperError} Invalid renderState.stencilTest.frontFunction.
   * @exception {DeveloperError} Invalid renderState.stencilTest.backFunction.
   * @exception {DeveloperError} Invalid renderState.stencilTest.frontOperation.fail.
   * @exception {DeveloperError} Invalid renderState.stencilTest.frontOperation.zFail.
   * @exception {DeveloperError} Invalid renderState.stencilTest.frontOperation.zPass.
   * @exception {DeveloperError} Invalid renderState.stencilTest.backOperation.fail.
   * @exception {DeveloperError} Invalid renderState.stencilTest.backOperation.zFail.
   * @exception {DeveloperError} Invalid renderState.stencilTest.backOperation.zPass.
   * @exception {DeveloperError} renderState.viewport.width must be greater than or equal to zero.
   * @exception {DeveloperError} renderState.viewport.width must be less than or equal to the maximum viewport width.
   * @exception {DeveloperError} renderState.viewport.height must be greater than or equal to zero.
   * @exception {DeveloperError} renderState.viewport.height must be less than or equal to the maximum viewport height.
   *
   *
   * @example
   * const defaults = {
   *     frontFace : WindingOrder.COUNTER_CLOCKWISE,
   *     cull : {
   *         enabled : false,
   *         face : CullFace.BACK
   *     },
   *     lineWidth : 1,
   *     polygonOffset : {
   *         enabled : false,
   *         factor : 0,
   *         units : 0
   *     },
   *     scissorTest : {
   *         enabled : false,
   *         rectangle : {
   *             x : 0,
   *             y : 0,
   *             width : 0,
   *             height : 0
   *         }
   *     },
   *     depthRange : {
   *         near : 0,
   *         far : 1
   *     },
   *     depthTest : {
   *         enabled : false,
   *         func : DepthFunction.LESS
   *      },
   *     colorMask : {
   *         red : true,
   *         green : true,
   *         blue : true,
   *         alpha : true
   *     },
   *     depthMask : true,
   *     stencilMask : ~0,
   *     blending : {
   *         enabled : false,
   *         color : {
   *             red : 0.0,
   *             green : 0.0,
   *             blue : 0.0,
   *             alpha : 0.0
   *         },
   *         equationRgb : BlendEquation.ADD,
   *         equationAlpha : BlendEquation.ADD,
   *         functionSourceRgb : BlendFunction.ONE,
   *         functionSourceAlpha : BlendFunction.ONE,
   *         functionDestinationRgb : BlendFunction.ZERO,
   *         functionDestinationAlpha : BlendFunction.ZERO
   *     },
   *     stencilTest : {
   *         enabled : false,
   *         frontFunction : StencilFunction.ALWAYS,
   *         backFunction : StencilFunction.ALWAYS,
   *         reference : 0,
   *         mask : ~0,
   *         frontOperation : {
   *             fail : StencilOperation.KEEP,
   *             zFail : StencilOperation.KEEP,
   *             zPass : StencilOperation.KEEP
   *         },
   *         backOperation : {
   *             fail : StencilOperation.KEEP,
   *             zFail : StencilOperation.KEEP,
   *             zPass : StencilOperation.KEEP
   *         }
   *     },
   *     sampleCoverage : {
   *         enabled : false,
   *         value : 1.0,
   *         invert : false
   *      }
   * };
   *
   * const rs = RenderState.fromCache(defaults);
   *
   * @see DrawCommand
   * @see ClearCommand
   *
   * @private
   */
  RenderState.fromCache = function (renderState) {
    const partialKey = JSON.stringify(renderState);
    let cachedState = renderStateCache[partialKey];
    if (defined(cachedState)) {
      ++cachedState.referenceCount;
      return cachedState.state;
    }

    // Cache miss.  Fully define render state and try again.
    let states = new RenderState(renderState);
    const fullKey = JSON.stringify(states);
    cachedState = renderStateCache[fullKey];
    if (!defined(cachedState)) {
      states.id = nextRenderStateId++;
      //>>includeStart('debug', pragmas.debug);
      states = freezeRenderState(states);
      //>>includeEnd('debug');
      cachedState = {
        referenceCount: 0,
        state: states,
      };

      // Cache full render state.  Multiple partially defined render states may map to this.
      renderStateCache[fullKey] = cachedState;
    }

    ++cachedState.referenceCount;

    // Cache partial render state so we can skip validation on a cache hit for a partially defined render state
    renderStateCache[partialKey] = {
      referenceCount: 1,
      state: cachedState.state,
    };

    return cachedState.state;
  };

  /**
   * @private
   */
  RenderState.removeFromCache = function (renderState) {
    const states = new RenderState(renderState);
    const fullKey = JSON.stringify(states);
    const fullCachedState = renderStateCache[fullKey];

    // decrement partial key reference count
    const partialKey = JSON.stringify(renderState);
    const cachedState = renderStateCache[partialKey];
    if (defined(cachedState)) {
      --cachedState.referenceCount;

      if (cachedState.referenceCount === 0) {
        // remove partial key
        delete renderStateCache[partialKey];

        // decrement full key reference count
        if (defined(fullCachedState)) {
          --fullCachedState.referenceCount;
        }
      }
    }

    // remove full key if reference count is zero
    if (defined(fullCachedState) && fullCachedState.referenceCount === 0) {
      delete renderStateCache[fullKey];
    }
  };

  /**
   * This function is for testing purposes only.
   * @private
   */
  RenderState.getCache = function () {
    return renderStateCache;
  };

  /**
   * This function is for testing purposes only.
   * @private
   */
  RenderState.clearCache = function () {
    renderStateCache = {};
  };

  function enableOrDisable(gl, glEnum, enable) {
    if (enable) {
      gl.enable(glEnum);
    } else {
      gl.disable(glEnum);
    }
  }

  function applyFrontFace(gl, renderState) {
    gl.frontFace(renderState.frontFace);
  }

  function applyCull(gl, renderState) {
    const cull = renderState.cull;
    const enabled = cull.enabled;

    enableOrDisable(gl, gl.CULL_FACE, enabled);

    if (enabled) {
      gl.cullFace(cull.face);
    }
  }

  function applyLineWidth(gl, renderState) {
    gl.lineWidth(renderState.lineWidth);
  }

  function applyPolygonOffset(gl, renderState) {
    const polygonOffset = renderState.polygonOffset;
    const enabled = polygonOffset.enabled;

    enableOrDisable(gl, gl.POLYGON_OFFSET_FILL, enabled);

    if (enabled) {
      gl.polygonOffset(polygonOffset.factor, polygonOffset.units);
    }
  }

  function applyScissorTest(gl, renderState, passState) {
    const scissorTest = renderState.scissorTest;
    const enabled = defined(passState.scissorTest)
      ? passState.scissorTest.enabled
      : scissorTest.enabled;

    enableOrDisable(gl, gl.SCISSOR_TEST, enabled);

    if (enabled) {
      const rectangle = defined(passState.scissorTest)
        ? passState.scissorTest.rectangle
        : scissorTest.rectangle;
      gl.scissor(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
    }
  }

  function applyDepthRange(gl, renderState) {
    const depthRange = renderState.depthRange;
    gl.depthRange(depthRange.near, depthRange.far);
  }

  function applyDepthTest(gl, renderState) {
    const depthTest = renderState.depthTest;
    const enabled = depthTest.enabled;

    enableOrDisable(gl, gl.DEPTH_TEST, enabled);

    if (enabled) {
      gl.depthFunc(depthTest.func);
    }
  }

  function applyColorMask(gl, renderState) {
    const colorMask = renderState.colorMask;
    gl.colorMask(colorMask.red, colorMask.green, colorMask.blue, colorMask.alpha);
  }

  function applyDepthMask(gl, renderState) {
    gl.depthMask(renderState.depthMask);
  }

  function applyStencilMask(gl, renderState) {
    gl.stencilMask(renderState.stencilMask);
  }

  function applyBlendingColor(gl, color) {
    gl.blendColor(color.red, color.green, color.blue, color.alpha);
  }

  function applyBlending(gl, renderState, passState) {
    const blending = renderState.blending;
    const enabled = defined(passState.blendingEnabled)
      ? passState.blendingEnabled
      : blending.enabled;

    enableOrDisable(gl, gl.BLEND, enabled);

    if (enabled) {
      applyBlendingColor(gl, blending.color);
      gl.blendEquationSeparate(blending.equationRgb, blending.equationAlpha);
      gl.blendFuncSeparate(
        blending.functionSourceRgb,
        blending.functionDestinationRgb,
        blending.functionSourceAlpha,
        blending.functionDestinationAlpha
      );
    }
  }

  function applyStencilTest(gl, renderState) {
    const stencilTest = renderState.stencilTest;
    const enabled = stencilTest.enabled;

    enableOrDisable(gl, gl.STENCIL_TEST, enabled);

    if (enabled) {
      const frontFunction = stencilTest.frontFunction;
      const backFunction = stencilTest.backFunction;
      const reference = stencilTest.reference;
      const mask = stencilTest.mask;

      // Section 6.8 of the WebGL spec requires the reference and masks to be the same for
      // front- and back-face tests.  This call prevents invalid operation errors when calling
      // stencilFuncSeparate on Firefox.  Perhaps they should delay validation to avoid requiring this.
      gl.stencilFunc(frontFunction, reference, mask);
      gl.stencilFuncSeparate(gl.BACK, backFunction, reference, mask);
      gl.stencilFuncSeparate(gl.FRONT, frontFunction, reference, mask);

      const frontOperation = stencilTest.frontOperation;
      const frontOperationFail = frontOperation.fail;
      const frontOperationZFail = frontOperation.zFail;
      const frontOperationZPass = frontOperation.zPass;

      gl.stencilOpSeparate(
        gl.FRONT,
        frontOperationFail,
        frontOperationZFail,
        frontOperationZPass
      );

      const backOperation = stencilTest.backOperation;
      const backOperationFail = backOperation.fail;
      const backOperationZFail = backOperation.zFail;
      const backOperationZPass = backOperation.zPass;

      gl.stencilOpSeparate(
        gl.BACK,
        backOperationFail,
        backOperationZFail,
        backOperationZPass
      );
    }
  }

  function applySampleCoverage(gl, renderState) {
    const sampleCoverage = renderState.sampleCoverage;
    const enabled = sampleCoverage.enabled;

    enableOrDisable(gl, gl.SAMPLE_COVERAGE, enabled);

    if (enabled) {
      gl.sampleCoverage(sampleCoverage.value, sampleCoverage.invert);
    }
  }

  const scratchViewport$2 = new BoundingRectangle();

  function applyViewport(gl, renderState, passState) {
    let viewport = defaultValue(renderState.viewport, passState.viewport);
    if (!defined(viewport)) {
      viewport = scratchViewport$2;
      viewport.width = passState.context.drawingBufferWidth;
      viewport.height = passState.context.drawingBufferHeight;
    }

    passState.context.uniformState.viewport = viewport;
    gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height);
  }

  RenderState.apply = function (gl, renderState, passState) {
    applyFrontFace(gl, renderState);
    applyCull(gl, renderState);
    applyLineWidth(gl, renderState);
    applyPolygonOffset(gl, renderState);
    applyDepthRange(gl, renderState);
    applyDepthTest(gl, renderState);
    applyColorMask(gl, renderState);
    applyDepthMask(gl, renderState);
    applyStencilMask(gl, renderState);
    applyStencilTest(gl, renderState);
    applySampleCoverage(gl, renderState);
    applyScissorTest(gl, renderState, passState);
    applyBlending(gl, renderState, passState);
    applyViewport(gl, renderState, passState);
  };

  function createFuncs(previousState, nextState) {
    const funcs = [];

    if (previousState.frontFace !== nextState.frontFace) {
      funcs.push(applyFrontFace);
    }

    if (
      previousState.cull.enabled !== nextState.cull.enabled ||
      previousState.cull.face !== nextState.cull.face
    ) {
      funcs.push(applyCull);
    }

    if (previousState.lineWidth !== nextState.lineWidth) {
      funcs.push(applyLineWidth);
    }

    if (
      previousState.polygonOffset.enabled !== nextState.polygonOffset.enabled ||
      previousState.polygonOffset.factor !== nextState.polygonOffset.factor ||
      previousState.polygonOffset.units !== nextState.polygonOffset.units
    ) {
      funcs.push(applyPolygonOffset);
    }

    if (
      previousState.depthRange.near !== nextState.depthRange.near ||
      previousState.depthRange.far !== nextState.depthRange.far
    ) {
      funcs.push(applyDepthRange);
    }

    if (
      previousState.depthTest.enabled !== nextState.depthTest.enabled ||
      previousState.depthTest.func !== nextState.depthTest.func
    ) {
      funcs.push(applyDepthTest);
    }

    if (
      previousState.colorMask.red !== nextState.colorMask.red ||
      previousState.colorMask.green !== nextState.colorMask.green ||
      previousState.colorMask.blue !== nextState.colorMask.blue ||
      previousState.colorMask.alpha !== nextState.colorMask.alpha
    ) {
      funcs.push(applyColorMask);
    }

    if (previousState.depthMask !== nextState.depthMask) {
      funcs.push(applyDepthMask);
    }

    if (previousState.stencilMask !== nextState.stencilMask) {
      funcs.push(applyStencilMask);
    }

    if (
      previousState.stencilTest.enabled !== nextState.stencilTest.enabled ||
      previousState.stencilTest.frontFunction !==
        nextState.stencilTest.frontFunction ||
      previousState.stencilTest.backFunction !==
        nextState.stencilTest.backFunction ||
      previousState.stencilTest.reference !== nextState.stencilTest.reference ||
      previousState.stencilTest.mask !== nextState.stencilTest.mask ||
      previousState.stencilTest.frontOperation.fail !==
        nextState.stencilTest.frontOperation.fail ||
      previousState.stencilTest.frontOperation.zFail !==
        nextState.stencilTest.frontOperation.zFail ||
      previousState.stencilTest.backOperation.fail !==
        nextState.stencilTest.backOperation.fail ||
      previousState.stencilTest.backOperation.zFail !==
        nextState.stencilTest.backOperation.zFail ||
      previousState.stencilTest.backOperation.zPass !==
        nextState.stencilTest.backOperation.zPass
    ) {
      funcs.push(applyStencilTest);
    }

    if (
      previousState.sampleCoverage.enabled !== nextState.sampleCoverage.enabled ||
      previousState.sampleCoverage.value !== nextState.sampleCoverage.value ||
      previousState.sampleCoverage.invert !== nextState.sampleCoverage.invert
    ) {
      funcs.push(applySampleCoverage);
    }

    return funcs;
  }

  RenderState.partialApply = function (
    gl,
    previousRenderState,
    renderState,
    previousPassState,
    passState,
    clear
  ) {
    if (previousRenderState !== renderState) {
      // When a new render state is applied, instead of making WebGL calls for all the states or first
      // comparing the states one-by-one with the previous state (basically a linear search), we take
      // advantage of RenderState's immutability, and store a dynamically populated sparse data structure
      // containing functions that make the minimum number of WebGL calls when transitioning from one state
      // to the other.  In practice, this works well since state-to-state transitions generally only require a
      // few WebGL calls, especially if commands are stored by state.
      let funcs = renderState._applyFunctions[previousRenderState.id];
      if (!defined(funcs)) {
        funcs = createFuncs(previousRenderState, renderState);
        renderState._applyFunctions[previousRenderState.id] = funcs;
      }

      const len = funcs.length;
      for (let i = 0; i < len; ++i) {
        funcs[i](gl, renderState);
      }
    }

    const previousScissorTest = defined(previousPassState.scissorTest)
      ? previousPassState.scissorTest
      : previousRenderState.scissorTest;
    const scissorTest = defined(passState.scissorTest)
      ? passState.scissorTest
      : renderState.scissorTest;

    // Our scissor rectangle can get out of sync with the GL scissor rectangle on clears.
    // Seems to be a problem only on ANGLE. See https://github.com/CesiumGS/cesium/issues/2994
    if (previousScissorTest !== scissorTest || clear) {
      applyScissorTest(gl, renderState, passState);
    }

    const previousBlendingEnabled = defined(previousPassState.blendingEnabled)
      ? previousPassState.blendingEnabled
      : previousRenderState.blending.enabled;
    const blendingEnabled = defined(passState.blendingEnabled)
      ? passState.blendingEnabled
      : renderState.blending.enabled;
    if (
      previousBlendingEnabled !== blendingEnabled ||
      (blendingEnabled && previousRenderState.blending !== renderState.blending)
    ) {
      applyBlending(gl, renderState, passState);
    }

    if (
      previousRenderState !== renderState ||
      previousPassState !== passState ||
      previousPassState.context !== passState.context
    ) {
      applyViewport(gl, renderState, passState);
    }
  };

  RenderState.getState = function (renderState) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(renderState)) {
      throw new DeveloperError("renderState is required.");
    }
    //>>includeEnd('debug');

    return {
      frontFace: renderState.frontFace,
      cull: {
        enabled: renderState.cull.enabled,
        face: renderState.cull.face,
      },
      lineWidth: renderState.lineWidth,
      polygonOffset: {
        enabled: renderState.polygonOffset.enabled,
        factor: renderState.polygonOffset.factor,
        units: renderState.polygonOffset.units,
      },
      scissorTest: {
        enabled: renderState.scissorTest.enabled,
        rectangle: BoundingRectangle.clone(renderState.scissorTest.rectangle),
      },
      depthRange: {
        near: renderState.depthRange.near,
        far: renderState.depthRange.far,
      },
      depthTest: {
        enabled: renderState.depthTest.enabled,
        func: renderState.depthTest.func,
      },
      colorMask: {
        red: renderState.colorMask.red,
        green: renderState.colorMask.green,
        blue: renderState.colorMask.blue,
        alpha: renderState.colorMask.alpha,
      },
      depthMask: renderState.depthMask,
      stencilMask: renderState.stencilMask,
      blending: {
        enabled: renderState.blending.enabled,
        color: Color.clone(renderState.blending.color),
        equationRgb: renderState.blending.equationRgb,
        equationAlpha: renderState.blending.equationAlpha,
        functionSourceRgb: renderState.blending.functionSourceRgb,
        functionSourceAlpha: renderState.blending.functionSourceAlpha,
        functionDestinationRgb: renderState.blending.functionDestinationRgb,
        functionDestinationAlpha: renderState.blending.functionDestinationAlpha,
      },
      stencilTest: {
        enabled: renderState.stencilTest.enabled,
        frontFunction: renderState.stencilTest.frontFunction,
        backFunction: renderState.stencilTest.backFunction,
        reference: renderState.stencilTest.reference,
        mask: renderState.stencilTest.mask,
        frontOperation: {
          fail: renderState.stencilTest.frontOperation.fail,
          zFail: renderState.stencilTest.frontOperation.zFail,
          zPass: renderState.stencilTest.frontOperation.zPass,
        },
        backOperation: {
          fail: renderState.stencilTest.backOperation.fail,
          zFail: renderState.stencilTest.backOperation.zFail,
          zPass: renderState.stencilTest.backOperation.zPass,
        },
      },
      sampleCoverage: {
        enabled: renderState.sampleCoverage.enabled,
        value: renderState.sampleCoverage.value,
        invert: renderState.sampleCoverage.invert,
      },
      viewport: defined(renderState.viewport)
        ? BoundingRectangle.clone(renderState.viewport)
        : undefined,
    };
  };

  const viewerPositionWCScratch = new Cartesian3();

  function AutomaticUniform(options) {
    this._size = options.size;
    this._datatype = options.datatype;
    this.getValue = options.getValue;
  }

  const datatypeToGlsl = {};
  datatypeToGlsl[WebGLConstants$1.FLOAT] = "float";
  datatypeToGlsl[WebGLConstants$1.FLOAT_VEC2] = "vec2";
  datatypeToGlsl[WebGLConstants$1.FLOAT_VEC3] = "vec3";
  datatypeToGlsl[WebGLConstants$1.FLOAT_VEC4] = "vec4";
  datatypeToGlsl[WebGLConstants$1.INT] = "int";
  datatypeToGlsl[WebGLConstants$1.INT_VEC2] = "ivec2";
  datatypeToGlsl[WebGLConstants$1.INT_VEC3] = "ivec3";
  datatypeToGlsl[WebGLConstants$1.INT_VEC4] = "ivec4";
  datatypeToGlsl[WebGLConstants$1.BOOL] = "bool";
  datatypeToGlsl[WebGLConstants$1.BOOL_VEC2] = "bvec2";
  datatypeToGlsl[WebGLConstants$1.BOOL_VEC3] = "bvec3";
  datatypeToGlsl[WebGLConstants$1.BOOL_VEC4] = "bvec4";
  datatypeToGlsl[WebGLConstants$1.FLOAT_MAT2] = "mat2";
  datatypeToGlsl[WebGLConstants$1.FLOAT_MAT3] = "mat3";
  datatypeToGlsl[WebGLConstants$1.FLOAT_MAT4] = "mat4";
  datatypeToGlsl[WebGLConstants$1.SAMPLER_2D] = "sampler2D";
  datatypeToGlsl[WebGLConstants$1.SAMPLER_CUBE] = "samplerCube";

  AutomaticUniform.prototype.getDeclaration = function (name) {
    let declaration = `uniform ${datatypeToGlsl[this._datatype]} ${name}`;

    const size = this._size;
    if (size === 1) {
      declaration += ";";
    } else {
      declaration += `[${size.toString()}];`;
    }

    return declaration;
  };

  /**
   * @private
   */
  const AutomaticUniforms = {
    /**
     * An automatic GLSL uniform containing the viewport's <code>x</code>, <code>y</code>, <code>width</code>,
     * and <code>height</code> properties in an <code>vec4</code>'s <code>x</code>, <code>y</code>, <code>z</code>,
     * and <code>w</code> components, respectively.
     *
     * @example
     * // GLSL declaration
     * uniform vec4 czm_viewport;
     *
     * // Scale the window coordinate components to [0, 1] by dividing
     * // by the viewport's width and height.
     * vec2 v = gl_FragCoord.xy / czm_viewport.zw;
     *
     * @see Context#getViewport
     */
    czm_viewport: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_VEC4,
      getValue: function (uniformState) {
        return uniformState.viewportCartesian4;
      },
    }),

    /**
     * An automatic GLSL uniform representing a 4x4 orthographic projection matrix that
     * transforms window coordinates to clip coordinates.  Clip coordinates is the
     * coordinate system for a vertex shader's <code>gl_Position</code> output.
     * <br /><br />
     * This transform is useful when a vertex shader inputs or manipulates window coordinates
     * as done by {@link BillboardCollection}.
     * <br /><br />
     * Do not confuse {@link czm_viewportTransformation} with <code>czm_viewportOrthographic</code>.
     * The former transforms from normalized device coordinates to window coordinates; the later transforms
     * from window coordinates to clip coordinates, and is often used to assign to <code>gl_Position</code>.
     *
     * @example
     * // GLSL declaration
     * uniform mat4 czm_viewportOrthographic;
     *
     * // Example
     * gl_Position = czm_viewportOrthographic * vec4(windowPosition, 0.0, 1.0);
     *
     * @see UniformState#viewportOrthographic
     * @see czm_viewport
     * @see czm_viewportTransformation
     * @see BillboardCollection
     */
    czm_viewportOrthographic: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_MAT4,
      getValue: function (uniformState) {
        return uniformState.viewportOrthographic;
      },
    }),

    /**
     * An automatic GLSL uniform representing a 4x4 transformation matrix that
     * transforms normalized device coordinates to window coordinates.  The context's
     * full viewport is used, and the depth range is assumed to be <code>near = 0</code>
     * and <code>far = 1</code>.
     * <br /><br />
     * This transform is useful when there is a need to manipulate window coordinates
     * in a vertex shader as done by {@link BillboardCollection}.  In many cases,
     * this matrix will not be used directly; instead, {@link czm_modelToWindowCoordinates}
     * will be used to transform directly from model to window coordinates.
     * <br /><br />
     * Do not confuse <code>czm_viewportTransformation</code> with {@link czm_viewportOrthographic}.
     * The former transforms from normalized device coordinates to window coordinates; the later transforms
     * from window coordinates to clip coordinates, and is often used to assign to <code>gl_Position</code>.
     *
     * @example
     * // GLSL declaration
     * uniform mat4 czm_viewportTransformation;
     *
     * // Use czm_viewportTransformation as part of the
     * // transform from model to window coordinates.
     * vec4 q = czm_modelViewProjection * positionMC;               // model to clip coordinates
     * q.xyz /= q.w;                                                // clip to normalized device coordinates (ndc)
     * q.xyz = (czm_viewportTransformation * vec4(q.xyz, 1.0)).xyz; // ndc to window coordinates
     *
     * @see UniformState#viewportTransformation
     * @see czm_viewport
     * @see czm_viewportOrthographic
     * @see czm_modelToWindowCoordinates
     * @see BillboardCollection
     */
    czm_viewportTransformation: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_MAT4,
      getValue: function (uniformState) {
        return uniformState.viewportTransformation;
      },
    }),

    /**
     * An automatic GLSL uniform representing the depth of the scene
     * after the globe pass and then updated after the 3D Tiles pass.
     * The depth is packed into an RGBA texture.
     *
     * @example
     * // GLSL declaration
     * uniform sampler2D czm_globeDepthTexture;
     *
     * // Get the depth at the current fragment
     * vec2 coords = gl_FragCoord.xy / czm_viewport.zw;
     * float depth = czm_unpackDepth(texture2D(czm_globeDepthTexture, coords));
     */
    czm_globeDepthTexture: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.SAMPLER_2D,
      getValue: function (uniformState) {
        return uniformState.globeDepthTexture;
      },
    }),

    /**
     * An automatic GLSL uniform representing a 4x4 model transformation matrix that
     * transforms model coordinates to world coordinates.
     *
     * @example
     * // GLSL declaration
     * uniform mat4 czm_model;
     *
     * // Example
     * vec4 worldPosition = czm_model * modelPosition;
     *
     * @see UniformState#model
     * @see czm_inverseModel
     * @see czm_modelView
     * @see czm_modelViewProjection
     */
    czm_model: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_MAT4,
      getValue: function (uniformState) {
        return uniformState.model;
      },
    }),

    /**
     * An automatic GLSL uniform representing a 4x4 model transformation matrix that
     * transforms world coordinates to model coordinates.
     *
     * @example
     * // GLSL declaration
     * uniform mat4 czm_inverseModel;
     *
     * // Example
     * vec4 modelPosition = czm_inverseModel * worldPosition;
     *
     * @see UniformState#inverseModel
     * @see czm_model
     * @see czm_inverseModelView
     */
    czm_inverseModel: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_MAT4,
      getValue: function (uniformState) {
        return uniformState.inverseModel;
      },
    }),

    /**
     * An automatic GLSL uniform representing a 4x4 view transformation matrix that
     * transforms world coordinates to eye coordinates.
     *
     * @example
     * // GLSL declaration
     * uniform mat4 czm_view;
     *
     * // Example
     * vec4 eyePosition = czm_view * worldPosition;
     *
     * @see UniformState#view
     * @see czm_viewRotation
     * @see czm_modelView
     * @see czm_viewProjection
     * @see czm_modelViewProjection
     * @see czm_inverseView
     */
    czm_view: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_MAT4,
      getValue: function (uniformState) {
        return uniformState.view;
      },
    }),

    /**
     * An automatic GLSL uniform representing a 4x4 view transformation matrix that
     * transforms 3D world coordinates to eye coordinates.  In 3D mode, this is identical to
     * {@link czm_view}, but in 2D and Columbus View it represents the view matrix
     * as if the camera were at an equivalent location in 3D mode.  This is useful for lighting
     * 2D and Columbus View in the same way that 3D is lit.
     *
     * @example
     * // GLSL declaration
     * uniform mat4 czm_view3D;
     *
     * // Example
     * vec4 eyePosition3D = czm_view3D * worldPosition3D;
     *
     * @see UniformState#view3D
     * @see czm_view
     */
    czm_view3D: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_MAT4,
      getValue: function (uniformState) {
        return uniformState.view3D;
      },
    }),

    /**
     * An automatic GLSL uniform representing a 3x3 view rotation matrix that
     * transforms vectors in world coordinates to eye coordinates.
     *
     * @example
     * // GLSL declaration
     * uniform mat3 czm_viewRotation;
     *
     * // Example
     * vec3 eyeVector = czm_viewRotation * worldVector;
     *
     * @see UniformState#viewRotation
     * @see czm_view
     * @see czm_inverseView
     * @see czm_inverseViewRotation
     */
    czm_viewRotation: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_MAT3,
      getValue: function (uniformState) {
        return uniformState.viewRotation;
      },
    }),

    /**
     * An automatic GLSL uniform representing a 3x3 view rotation matrix that
     * transforms vectors in 3D world coordinates to eye coordinates.  In 3D mode, this is identical to
     * {@link czm_viewRotation}, but in 2D and Columbus View it represents the view matrix
     * as if the camera were at an equivalent location in 3D mode.  This is useful for lighting
     * 2D and Columbus View in the same way that 3D is lit.
     *
     * @example
     * // GLSL declaration
     * uniform mat3 czm_viewRotation3D;
     *
     * // Example
     * vec3 eyeVector = czm_viewRotation3D * worldVector;
     *
     * @see UniformState#viewRotation3D
     * @see czm_viewRotation
     */
    czm_viewRotation3D: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_MAT3,
      getValue: function (uniformState) {
        return uniformState.viewRotation3D;
      },
    }),

    /**
     * An automatic GLSL uniform representing a 4x4 transformation matrix that
     * transforms from eye coordinates to world coordinates.
     *
     * @example
     * // GLSL declaration
     * uniform mat4 czm_inverseView;
     *
     * // Example
     * vec4 worldPosition = czm_inverseView * eyePosition;
     *
     * @see UniformState#inverseView
     * @see czm_view
     * @see czm_inverseNormal
     */
    czm_inverseView: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_MAT4,
      getValue: function (uniformState) {
        return uniformState.inverseView;
      },
    }),

    /**
     * An automatic GLSL uniform representing a 4x4 transformation matrix that
     * transforms from 3D eye coordinates to world coordinates.  In 3D mode, this is identical to
     * {@link czm_inverseView}, but in 2D and Columbus View it represents the inverse view matrix
     * as if the camera were at an equivalent location in 3D mode.  This is useful for lighting
     * 2D and Columbus View in the same way that 3D is lit.
     *
     * @example
     * // GLSL declaration
     * uniform mat4 czm_inverseView3D;
     *
     * // Example
     * vec4 worldPosition = czm_inverseView3D * eyePosition;
     *
     * @see UniformState#inverseView3D
     * @see czm_inverseView
     */
    czm_inverseView3D: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_MAT4,
      getValue: function (uniformState) {
        return uniformState.inverseView3D;
      },
    }),

    /**
     * An automatic GLSL uniform representing a 3x3 rotation matrix that
     * transforms vectors from eye coordinates to world coordinates.
     *
     * @example
     * // GLSL declaration
     * uniform mat3 czm_inverseViewRotation;
     *
     * // Example
     * vec4 worldVector = czm_inverseViewRotation * eyeVector;
     *
     * @see UniformState#inverseView
     * @see czm_view
     * @see czm_viewRotation
     * @see czm_inverseViewRotation
     */
    czm_inverseViewRotation: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_MAT3,
      getValue: function (uniformState) {
        return uniformState.inverseViewRotation;
      },
    }),

    /**
     * An automatic GLSL uniform representing a 3x3 rotation matrix that
     * transforms vectors from 3D eye coordinates to world coordinates.  In 3D mode, this is identical to
     * {@link czm_inverseViewRotation}, but in 2D and Columbus View it represents the inverse view matrix
     * as if the camera were at an equivalent location in 3D mode.  This is useful for lighting
     * 2D and Columbus View in the same way that 3D is lit.
     *
     * @example
     * // GLSL declaration
     * uniform mat3 czm_inverseViewRotation3D;
     *
     * // Example
     * vec4 worldVector = czm_inverseViewRotation3D * eyeVector;
     *
     * @see UniformState#inverseView3D
     * @see czm_inverseViewRotation
     */
    czm_inverseViewRotation3D: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_MAT3,
      getValue: function (uniformState) {
        return uniformState.inverseViewRotation3D;
      },
    }),

    /**
     * An automatic GLSL uniform representing a 4x4 projection transformation matrix that
     * transforms eye coordinates to clip coordinates.  Clip coordinates is the
     * coordinate system for a vertex shader's <code>gl_Position</code> output.
     *
     * @example
     * // GLSL declaration
     * uniform mat4 czm_projection;
     *
     * // Example
     * gl_Position = czm_projection * eyePosition;
     *
     * @see UniformState#projection
     * @see czm_viewProjection
     * @see czm_modelViewProjection
     * @see czm_infiniteProjection
     */
    czm_projection: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_MAT4,
      getValue: function (uniformState) {
        return uniformState.projection;
      },
    }),

    /**
     * An automatic GLSL uniform representing a 4x4 inverse projection transformation matrix that
     * transforms from clip coordinates to eye coordinates. Clip coordinates is the
     * coordinate system for a vertex shader's <code>gl_Position</code> output.
     *
     * @example
     * // GLSL declaration
     * uniform mat4 czm_inverseProjection;
     *
     * // Example
     * vec4 eyePosition = czm_inverseProjection * clipPosition;
     *
     * @see UniformState#inverseProjection
     * @see czm_projection
     */
    czm_inverseProjection: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_MAT4,
      getValue: function (uniformState) {
        return uniformState.inverseProjection;
      },
    }),

    /**
     * An automatic GLSL uniform representing a 4x4 projection transformation matrix with the far plane at infinity,
     * that transforms eye coordinates to clip coordinates.  Clip coordinates is the
     * coordinate system for a vertex shader's <code>gl_Position</code> output.  An infinite far plane is used
     * in algorithms like shadow volumes and GPU ray casting with proxy geometry to ensure that triangles
     * are not clipped by the far plane.
     *
     * @example
     * // GLSL declaration
     * uniform mat4 czm_infiniteProjection;
     *
     * // Example
     * gl_Position = czm_infiniteProjection * eyePosition;
     *
     * @see UniformState#infiniteProjection
     * @see czm_projection
     * @see czm_modelViewInfiniteProjection
     */
    czm_infiniteProjection: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_MAT4,
      getValue: function (uniformState) {
        return uniformState.infiniteProjection;
      },
    }),

    /**
     * An automatic GLSL uniform representing a 4x4 model-view transformation matrix that
     * transforms model coordinates to eye coordinates.
     * <br /><br />
     * Positions should be transformed to eye coordinates using <code>czm_modelView</code> and
     * normals should be transformed using {@link czm_normal}.
     *
     * @example
     * // GLSL declaration
     * uniform mat4 czm_modelView;
     *
     * // Example
     * vec4 eyePosition = czm_modelView * modelPosition;
     *
     * // The above is equivalent to, but more efficient than:
     * vec4 eyePosition = czm_view * czm_model * modelPosition;
     *
     * @see UniformState#modelView
     * @see czm_model
     * @see czm_view
     * @see czm_modelViewProjection
     * @see czm_normal
     */
    czm_modelView: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_MAT4,
      getValue: function (uniformState) {
        return uniformState.modelView;
      },
    }),

    /**
     * An automatic GLSL uniform representing a 4x4 model-view transformation matrix that
     * transforms 3D model coordinates to eye coordinates.  In 3D mode, this is identical to
     * {@link czm_modelView}, but in 2D and Columbus View it represents the model-view matrix
     * as if the camera were at an equivalent location in 3D mode.  This is useful for lighting
     * 2D and Columbus View in the same way that 3D is lit.
     * <br /><br />
     * Positions should be transformed to eye coordinates using <code>czm_modelView3D</code> and
     * normals should be transformed using {@link czm_normal3D}.
     *
     * @example
     * // GLSL declaration
     * uniform mat4 czm_modelView3D;
     *
     * // Example
     * vec4 eyePosition = czm_modelView3D * modelPosition;
     *
     * // The above is equivalent to, but more efficient than:
     * vec4 eyePosition = czm_view3D * czm_model * modelPosition;
     *
     * @see UniformState#modelView3D
     * @see czm_modelView
     */
    czm_modelView3D: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_MAT4,
      getValue: function (uniformState) {
        return uniformState.modelView3D;
      },
    }),

    /**
     * An automatic GLSL uniform representing a 4x4 model-view transformation matrix that
     * transforms model coordinates, relative to the eye, to eye coordinates.  This is used
     * in conjunction with {@link czm_translateRelativeToEye}.
     *
     * @example
     * // GLSL declaration
     * uniform mat4 czm_modelViewRelativeToEye;
     *
     * // Example
     * attribute vec3 positionHigh;
     * attribute vec3 positionLow;
     *
     * void main()
     * {
     *   vec4 p = czm_translateRelativeToEye(positionHigh, positionLow);
     *   gl_Position = czm_projection * (czm_modelViewRelativeToEye * p);
     * }
     *
     * @see czm_modelViewProjectionRelativeToEye
     * @see czm_translateRelativeToEye
     * @see EncodedCartesian3
     */
    czm_modelViewRelativeToEye: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_MAT4,
      getValue: function (uniformState) {
        return uniformState.modelViewRelativeToEye;
      },
    }),

    /**
     * An automatic GLSL uniform representing a 4x4 transformation matrix that
     * transforms from eye coordinates to model coordinates.
     *
     * @example
     * // GLSL declaration
     * uniform mat4 czm_inverseModelView;
     *
     * // Example
     * vec4 modelPosition = czm_inverseModelView * eyePosition;
     *
     * @see UniformState#inverseModelView
     * @see czm_modelView
     */
    czm_inverseModelView: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_MAT4,
      getValue: function (uniformState) {
        return uniformState.inverseModelView;
      },
    }),

    /**
     * An automatic GLSL uniform representing a 4x4 transformation matrix that
     * transforms from eye coordinates to 3D model coordinates.  In 3D mode, this is identical to
     * {@link czm_inverseModelView}, but in 2D and Columbus View it represents the inverse model-view matrix
     * as if the camera were at an equivalent location in 3D mode.  This is useful for lighting
     * 2D and Columbus View in the same way that 3D is lit.
     *
     * @example
     * // GLSL declaration
     * uniform mat4 czm_inverseModelView3D;
     *
     * // Example
     * vec4 modelPosition = czm_inverseModelView3D * eyePosition;
     *
     * @see UniformState#inverseModelView
     * @see czm_inverseModelView
     * @see czm_modelView3D
     */
    czm_inverseModelView3D: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_MAT4,
      getValue: function (uniformState) {
        return uniformState.inverseModelView3D;
      },
    }),

    /**
     * An automatic GLSL uniform representing a 4x4 view-projection transformation matrix that
     * transforms world coordinates to clip coordinates.  Clip coordinates is the
     * coordinate system for a vertex shader's <code>gl_Position</code> output.
     *
     * @example
     * // GLSL declaration
     * uniform mat4 czm_viewProjection;
     *
     * // Example
     * vec4 gl_Position = czm_viewProjection * czm_model * modelPosition;
     *
     * // The above is equivalent to, but more efficient than:
     * gl_Position = czm_projection * czm_view * czm_model * modelPosition;
     *
     * @see UniformState#viewProjection
     * @see czm_view
     * @see czm_projection
     * @see czm_modelViewProjection
     * @see czm_inverseViewProjection
     */
    czm_viewProjection: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_MAT4,
      getValue: function (uniformState) {
        return uniformState.viewProjection;
      },
    }),

    /**
     * An automatic GLSL uniform representing a 4x4 view-projection transformation matrix that
     * transforms clip coordinates to world coordinates.  Clip coordinates is the
     * coordinate system for a vertex shader's <code>gl_Position</code> output.
     *
     * @example
     * // GLSL declaration
     * uniform mat4 czm_inverseViewProjection;
     *
     * // Example
     * vec4 worldPosition = czm_inverseViewProjection * clipPosition;
     *
     * @see UniformState#inverseViewProjection
     * @see czm_viewProjection
     */
    czm_inverseViewProjection: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_MAT4,
      getValue: function (uniformState) {
        return uniformState.inverseViewProjection;
      },
    }),

    /**
     * An automatic GLSL uniform representing a 4x4 model-view-projection transformation matrix that
     * transforms model coordinates to clip coordinates.  Clip coordinates is the
     * coordinate system for a vertex shader's <code>gl_Position</code> output.
     *
     * @example
     * // GLSL declaration
     * uniform mat4 czm_modelViewProjection;
     *
     * // Example
     * vec4 gl_Position = czm_modelViewProjection * modelPosition;
     *
     * // The above is equivalent to, but more efficient than:
     * gl_Position = czm_projection * czm_view * czm_model * modelPosition;
     *
     * @see UniformState#modelViewProjection
     * @see czm_model
     * @see czm_view
     * @see czm_projection
     * @see czm_modelView
     * @see czm_viewProjection
     * @see czm_modelViewInfiniteProjection
     * @see czm_inverseModelViewProjection
     */
    czm_modelViewProjection: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_MAT4,
      getValue: function (uniformState) {
        return uniformState.modelViewProjection;
      },
    }),

    /**
     * An automatic GLSL uniform representing a 4x4 inverse model-view-projection transformation matrix that
     * transforms clip coordinates to model coordinates.  Clip coordinates is the
     * coordinate system for a vertex shader's <code>gl_Position</code> output.
     *
     * @example
     * // GLSL declaration
     * uniform mat4 czm_inverseModelViewProjection;
     *
     * // Example
     * vec4 modelPosition = czm_inverseModelViewProjection * clipPosition;
     *
     * @see UniformState#modelViewProjection
     * @see czm_modelViewProjection
     */
    czm_inverseModelViewProjection: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_MAT4,
      getValue: function (uniformState) {
        return uniformState.inverseModelViewProjection;
      },
    }),

    /**
     * An automatic GLSL uniform representing a 4x4 model-view-projection transformation matrix that
     * transforms model coordinates, relative to the eye, to clip coordinates.  Clip coordinates is the
     * coordinate system for a vertex shader's <code>gl_Position</code> output.  This is used in
     * conjunction with {@link czm_translateRelativeToEye}.
     *
     * @example
     * // GLSL declaration
     * uniform mat4 czm_modelViewProjectionRelativeToEye;
     *
     * // Example
     * attribute vec3 positionHigh;
     * attribute vec3 positionLow;
     *
     * void main()
     * {
     *   vec4 p = czm_translateRelativeToEye(positionHigh, positionLow);
     *   gl_Position = czm_modelViewProjectionRelativeToEye * p;
     * }
     *
     * @see czm_modelViewRelativeToEye
     * @see czm_translateRelativeToEye
     * @see EncodedCartesian3
     */
    czm_modelViewProjectionRelativeToEye: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_MAT4,
      getValue: function (uniformState) {
        return uniformState.modelViewProjectionRelativeToEye;
      },
    }),

    /**
     * An automatic GLSL uniform representing a 4x4 model-view-projection transformation matrix that
     * transforms model coordinates to clip coordinates.  Clip coordinates is the
     * coordinate system for a vertex shader's <code>gl_Position</code> output.  The projection matrix places
     * the far plane at infinity.  This is useful in algorithms like shadow volumes and GPU ray casting with
     * proxy geometry to ensure that triangles are not clipped by the far plane.
     *
     * @example
     * // GLSL declaration
     * uniform mat4 czm_modelViewInfiniteProjection;
     *
     * // Example
     * vec4 gl_Position = czm_modelViewInfiniteProjection * modelPosition;
     *
     * // The above is equivalent to, but more efficient than:
     * gl_Position = czm_infiniteProjection * czm_view * czm_model * modelPosition;
     *
     * @see UniformState#modelViewInfiniteProjection
     * @see czm_model
     * @see czm_view
     * @see czm_infiniteProjection
     * @see czm_modelViewProjection
     */
    czm_modelViewInfiniteProjection: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_MAT4,
      getValue: function (uniformState) {
        return uniformState.modelViewInfiniteProjection;
      },
    }),

    /**
     * An automatic GLSL uniform that indicates if the current camera is orthographic in 3D.
     *
     * @see UniformState#orthographicIn3D
     */
    czm_orthographicIn3D: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT,
      getValue: function (uniformState) {
        return uniformState.orthographicIn3D ? 1 : 0;
      },
    }),

    /**
     * An automatic GLSL uniform representing a 3x3 normal transformation matrix that
     * transforms normal vectors in model coordinates to eye coordinates.
     * <br /><br />
     * Positions should be transformed to eye coordinates using {@link czm_modelView} and
     * normals should be transformed using <code>czm_normal</code>.
     *
     * @example
     * // GLSL declaration
     * uniform mat3 czm_normal;
     *
     * // Example
     * vec3 eyeNormal = czm_normal * normal;
     *
     * @see UniformState#normal
     * @see czm_inverseNormal
     * @see czm_modelView
     */
    czm_normal: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_MAT3,
      getValue: function (uniformState) {
        return uniformState.normal;
      },
    }),

    /**
     * An automatic GLSL uniform representing a 3x3 normal transformation matrix that
     * transforms normal vectors in 3D model coordinates to eye coordinates.
     * In 3D mode, this is identical to
     * {@link czm_normal}, but in 2D and Columbus View it represents the normal transformation
     * matrix as if the camera were at an equivalent location in 3D mode.  This is useful for lighting
     * 2D and Columbus View in the same way that 3D is lit.
     * <br /><br />
     * Positions should be transformed to eye coordinates using {@link czm_modelView3D} and
     * normals should be transformed using <code>czm_normal3D</code>.
     *
     * @example
     * // GLSL declaration
     * uniform mat3 czm_normal3D;
     *
     * // Example
     * vec3 eyeNormal = czm_normal3D * normal;
     *
     * @see UniformState#normal3D
     * @see czm_normal
     */
    czm_normal3D: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_MAT3,
      getValue: function (uniformState) {
        return uniformState.normal3D;
      },
    }),

    /**
     * An automatic GLSL uniform representing a 3x3 normal transformation matrix that
     * transforms normal vectors in eye coordinates to model coordinates.  This is
     * the opposite of the transform provided by {@link czm_normal}.
     *
     * @example
     * // GLSL declaration
     * uniform mat3 czm_inverseNormal;
     *
     * // Example
     * vec3 normalMC = czm_inverseNormal * normalEC;
     *
     * @see UniformState#inverseNormal
     * @see czm_normal
     * @see czm_modelView
     * @see czm_inverseView
     */
    czm_inverseNormal: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_MAT3,
      getValue: function (uniformState) {
        return uniformState.inverseNormal;
      },
    }),

    /**
     * An automatic GLSL uniform representing a 3x3 normal transformation matrix that
     * transforms normal vectors in eye coordinates to 3D model coordinates.  This is
     * the opposite of the transform provided by {@link czm_normal}.
     * In 3D mode, this is identical to
     * {@link czm_inverseNormal}, but in 2D and Columbus View it represents the inverse normal transformation
     * matrix as if the camera were at an equivalent location in 3D mode.  This is useful for lighting
     * 2D and Columbus View in the same way that 3D is lit.
     *
     * @example
     * // GLSL declaration
     * uniform mat3 czm_inverseNormal3D;
     *
     * // Example
     * vec3 normalMC = czm_inverseNormal3D * normalEC;
     *
     * @see UniformState#inverseNormal3D
     * @see czm_inverseNormal
     */
    czm_inverseNormal3D: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_MAT3,
      getValue: function (uniformState) {
        return uniformState.inverseNormal3D;
      },
    }),

    /**
     * An automatic GLSL uniform containing the height in meters of the
     * eye (camera) above or below the ellipsoid.
     *
     * @see UniformState#eyeHeight
     */
    czm_eyeHeight: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT,
      getValue: function (uniformState) {
        return uniformState.eyeHeight;
      },
    }),

    /**
     * An automatic GLSL uniform containing height (<code>x</code>) and height squared (<code>y</code>)
     * in meters of the eye (camera) above the 2D world plane. This uniform is only valid
     * when the {@link SceneMode} is <code>SCENE2D</code>.
     *
     * @see UniformState#eyeHeight2D
     */
    czm_eyeHeight2D: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_VEC2,
      getValue: function (uniformState) {
        return uniformState.eyeHeight2D;
      },
    }),

    /**
     * An automatic GLSL uniform containing the near distance (<code>x</code>) and the far distance (<code>y</code>)
     * of the frustum defined by the camera.  This is the largest possible frustum, not an individual
     * frustum used for multi-frustum rendering.
     *
     * @example
     * // GLSL declaration
     * uniform vec2 czm_entireFrustum;
     *
     * // Example
     * float frustumLength = czm_entireFrustum.y - czm_entireFrustum.x;
     *
     * @see UniformState#entireFrustum
     * @see czm_currentFrustum
     */
    czm_entireFrustum: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_VEC2,
      getValue: function (uniformState) {
        return uniformState.entireFrustum;
      },
    }),

    /**
     * An automatic GLSL uniform containing the near distance (<code>x</code>) and the far distance (<code>y</code>)
     * of the frustum defined by the camera.  This is the individual
     * frustum used for multi-frustum rendering.
     *
     * @example
     * // GLSL declaration
     * uniform vec2 czm_currentFrustum;
     *
     * // Example
     * float frustumLength = czm_currentFrustum.y - czm_currentFrustum.x;
     *
     * @see UniformState#currentFrustum
     * @see czm_entireFrustum
     */
    czm_currentFrustum: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_VEC2,
      getValue: function (uniformState) {
        return uniformState.currentFrustum;
      },
    }),

    /**
     * The distances to the frustum planes. The top, bottom, left and right distances are
     * the x, y, z, and w components, respectively.
     */
    czm_frustumPlanes: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_VEC4,
      getValue: function (uniformState) {
        return uniformState.frustumPlanes;
      },
    }),

    /**
     * Gets the far plane's distance from the near plane, plus 1.0.
     */
    czm_farDepthFromNearPlusOne: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT,
      getValue: function (uniformState) {
        return uniformState.farDepthFromNearPlusOne;
      },
    }),

    /**
     * Gets the log2 of {@link AutomaticUniforms#czm_farDepthFromNearPlusOne}.
     */
    czm_log2FarDepthFromNearPlusOne: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT,
      getValue: function (uniformState) {
        return uniformState.log2FarDepthFromNearPlusOne;
      },
    }),

    /**
     * Gets 1.0 divided by {@link AutomaticUniforms#czm_log2FarDepthFromNearPlusOne}.
     */
    czm_oneOverLog2FarDepthFromNearPlusOne: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT,
      getValue: function (uniformState) {
        return uniformState.oneOverLog2FarDepthFromNearPlusOne;
      },
    }),

    /**
     * An automatic GLSL uniform representing the sun position in world coordinates.
     *
     * @example
     * // GLSL declaration
     * uniform vec3 czm_sunPositionWC;
     *
     * @see UniformState#sunPositionWC
     * @see czm_sunPositionColumbusView
     * @see czm_sunDirectionWC
     */
    czm_sunPositionWC: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_VEC3,
      getValue: function (uniformState) {
        return uniformState.sunPositionWC;
      },
    }),

    /**
     * An automatic GLSL uniform representing the sun position in Columbus view world coordinates.
     *
     * @example
     * // GLSL declaration
     * uniform vec3 czm_sunPositionColumbusView;
     *
     * @see UniformState#sunPositionColumbusView
     * @see czm_sunPositionWC
     */
    czm_sunPositionColumbusView: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_VEC3,
      getValue: function (uniformState) {
        return uniformState.sunPositionColumbusView;
      },
    }),

    /**
     * An automatic GLSL uniform representing the normalized direction to the sun in eye coordinates.
     *
     * @example
     * // GLSL declaration
     * uniform vec3 czm_sunDirectionEC;
     *
     * // Example
     * float diffuse = max(dot(czm_sunDirectionEC, normalEC), 0.0);
     *
     * @see UniformState#sunDirectionEC
     * @see czm_moonDirectionEC
     * @see czm_sunDirectionWC
     */
    czm_sunDirectionEC: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_VEC3,
      getValue: function (uniformState) {
        return uniformState.sunDirectionEC;
      },
    }),

    /**
     * An automatic GLSL uniform representing the normalized direction to the sun in world coordinates.
     *
     * @example
     * // GLSL declaration
     * uniform vec3 czm_sunDirectionWC;
     *
     * // Example
     * float diffuse = max(dot(czm_sunDirectionWC, normalWC), 0.0);
     *
     * @see UniformState#sunDirectionWC
     * @see czm_sunPositionWC
     * @see czm_sunDirectionEC
     */
    czm_sunDirectionWC: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_VEC3,
      getValue: function (uniformState) {
        return uniformState.sunDirectionWC;
      },
    }),

    /**
     * An automatic GLSL uniform representing the normalized direction to the moon in eye coordinates.
     *
     * @example
     * // GLSL declaration
     * uniform vec3 czm_moonDirectionEC;
     *
     * // Example
     * float diffuse = max(dot(czm_moonDirectionEC, normalEC), 0.0);
     *
     * @see UniformState#moonDirectionEC
     * @see czm_sunDirectionEC
     */
    czm_moonDirectionEC: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_VEC3,
      getValue: function (uniformState) {
        return uniformState.moonDirectionEC;
      },
    }),

    /**
     * An automatic GLSL uniform representing the normalized direction to the scene's light source in eye coordinates.
     * This is commonly used for directional lighting computations.
     *
     * @example
     * // GLSL declaration
     * uniform vec3 czm_lightDirectionEC;
     *
     * // Example
     * float diffuse = max(dot(czm_lightDirectionEC, normalEC), 0.0);
     *
     * @see UniformState#lightDirectionEC
     * @see czm_lightDirectionWC
     */
    czm_lightDirectionEC: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_VEC3,
      getValue: function (uniformState) {
        return uniformState.lightDirectionEC;
      },
    }),

    /**
     * An automatic GLSL uniform representing the normalized direction to the scene's light source in world coordinates.
     * This is commonly used for directional lighting computations.
     *
     * @example
     * // GLSL declaration
     * uniform vec3 czm_lightDirectionWC;
     *
     * // Example
     * float diffuse = max(dot(czm_lightDirectionWC, normalWC), 0.0);
     *
     * @see UniformState#lightDirectionWC
     * @see czm_lightDirectionEC
     */
    czm_lightDirectionWC: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_VEC3,
      getValue: function (uniformState) {
        return uniformState.lightDirectionWC;
      },
    }),

    /**
     * An automatic GLSL uniform that represents the color of light emitted by the scene's light source. This
     * is equivalent to the light color multiplied by the light intensity limited to a maximum luminance of 1.0
     * suitable for non-HDR lighting.
     *
     * @example
     * // GLSL declaration
     * uniform vec3 czm_lightColor;
     *
     * // Example
     * vec3 diffuseColor = czm_lightColor * max(dot(czm_lightDirectionWC, normalWC), 0.0);
     *
     * @see UniformState#lightColor
     * @see czm_lightColorHdr
     */
    czm_lightColor: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_VEC3,
      getValue: function (uniformState) {
        return uniformState.lightColor;
      },
    }),

    /**
     * An automatic GLSL uniform that represents the high dynamic range color of light emitted by the scene's light
     * source. This is equivalent to the light color multiplied by the light intensity suitable for HDR lighting.
     *
     * @example
     * // GLSL declaration
     * uniform vec3 czm_lightColorHdr;
     *
     * // Example
     * vec3 diffuseColor = czm_lightColorHdr * max(dot(czm_lightDirectionWC, normalWC), 0.0);
     *
     * @see UniformState#lightColorHdr
     * @see czm_lightColor
     */
    czm_lightColorHdr: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_VEC3,
      getValue: function (uniformState) {
        return uniformState.lightColorHdr;
      },
    }),

    /**
     * An automatic GLSL uniform representing the high bits of the camera position in model
     * coordinates.  This is used for GPU RTE to eliminate jittering artifacts when rendering
     * as described in {@link http://help.agi.com/AGIComponents/html/BlogPrecisionsPrecisions.htm|Precisions, Precisions}.
     *
     * @example
     * // GLSL declaration
     * uniform vec3 czm_encodedCameraPositionMCHigh;
     *
     * @see czm_encodedCameraPositionMCLow
     * @see czm_modelViewRelativeToEye
     * @see czm_modelViewProjectionRelativeToEye
     */
    czm_encodedCameraPositionMCHigh: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_VEC3,
      getValue: function (uniformState) {
        return uniformState.encodedCameraPositionMCHigh;
      },
    }),

    /**
     * An automatic GLSL uniform representing the low bits of the camera position in model
     * coordinates.  This is used for GPU RTE to eliminate jittering artifacts when rendering
     * as described in {@linkhttp://help.agi.com/AGIComponents/html/BlogPrecisionsPrecisions.htm|Precisions, Precisions}.
     *
     * @example
     * // GLSL declaration
     * uniform vec3 czm_encodedCameraPositionMCLow;
     *
     * @see czm_encodedCameraPositionMCHigh
     * @see czm_modelViewRelativeToEye
     * @see czm_modelViewProjectionRelativeToEye
     */
    czm_encodedCameraPositionMCLow: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_VEC3,
      getValue: function (uniformState) {
        return uniformState.encodedCameraPositionMCLow;
      },
    }),

    /**
     * An automatic GLSL uniform representing the position of the viewer (camera) in world coordinates.
     *
     * @example
     * // GLSL declaration
     * uniform vec3 czm_viewerPositionWC;
     */
    czm_viewerPositionWC: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_VEC3,
      getValue: function (uniformState) {
        return Matrix4.getTranslation(
          uniformState.inverseView,
          viewerPositionWCScratch
        );
      },
    }),

    /**
     * An automatic GLSL uniform representing the frame number. This uniform is automatically incremented
     * every frame.
     *
     * @example
     * // GLSL declaration
     * uniform float czm_frameNumber;
     */
    czm_frameNumber: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT,
      getValue: function (uniformState) {
        return uniformState.frameState.frameNumber;
      },
    }),

    /**
     * An automatic GLSL uniform representing the current morph transition time between
     * 2D/Columbus View and 3D, with 0.0 being 2D or Columbus View and 1.0 being 3D.
     *
     * @example
     * // GLSL declaration
     * uniform float czm_morphTime;
     *
     * // Example
     * vec4 p = czm_columbusViewMorph(position2D, position3D, czm_morphTime);
     */
    czm_morphTime: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT,
      getValue: function (uniformState) {
        return uniformState.frameState.morphTime;
      },
    }),

    /**
     * An automatic GLSL uniform representing the current {@link SceneMode}, expressed
     * as a float.
     *
     * @example
     * // GLSL declaration
     * uniform float czm_sceneMode;
     *
     * // Example
     * if (czm_sceneMode == czm_sceneMode2D)
     * {
     *     eyeHeightSq = czm_eyeHeight2D.y;
     * }
     *
     * @see czm_sceneMode2D
     * @see czm_sceneModeColumbusView
     * @see czm_sceneMode3D
     * @see czm_sceneModeMorphing
     */
    czm_sceneMode: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT,
      getValue: function (uniformState) {
        return uniformState.frameState.mode;
      },
    }),

    /**
     * An automatic GLSL uniform representing the current rendering pass.
     *
     * @example
     * // GLSL declaration
     * uniform float czm_pass;
     *
     * // Example
     * if ((czm_pass == czm_passTranslucent) && isOpaque())
     * {
     *     gl_Position *= 0.0; // Cull opaque geometry in the translucent pass
     * }
     */
    czm_pass: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT,
      getValue: function (uniformState) {
        return uniformState.pass;
      },
    }),

    /**
     * An automatic GLSL uniform representing the current scene background color.
     *
     * @example
     * // GLSL declaration
     * uniform vec4 czm_backgroundColor;
     *
     * // Example: If the given color's RGB matches the background color, invert it.
     * vec4 adjustColorForContrast(vec4 color)
     * {
     *     if (czm_backgroundColor.rgb == color.rgb)
     *     {
     *         color.rgb = vec3(1.0) - color.rgb;
     *     }
     *
     *     return color;
     * }
     */
    czm_backgroundColor: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_VEC4,
      getValue: function (uniformState) {
        return uniformState.backgroundColor;
      },
    }),

    /**
     * An automatic GLSL uniform containing the BRDF look up texture used for image-based lighting computations.
     *
     * @example
     * // GLSL declaration
     * uniform sampler2D czm_brdfLut;
     *
     * // Example: For a given roughness and NdotV value, find the material's BRDF information in the red and green channels
     * float roughness = 0.5;
     * float NdotV = dot(normal, view);
     * vec2 brdfLut = texture2D(czm_brdfLut, vec2(NdotV, 1.0 - roughness)).rg;
     */
    czm_brdfLut: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.SAMPLER_2D,
      getValue: function (uniformState) {
        return uniformState.brdfLut;
      },
    }),

    /**
     * An automatic GLSL uniform containing the environment map used within the scene.
     *
     * @example
     * // GLSL declaration
     * uniform samplerCube czm_environmentMap;
     *
     * // Example: Create a perfect reflection of the environment map on a  model
     * float reflected = reflect(view, normal);
     * vec4 reflectedColor = textureCube(czm_environmentMap, reflected);
     */
    czm_environmentMap: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.SAMPLER_CUBE,
      getValue: function (uniformState) {
        return uniformState.environmentMap;
      },
    }),

    /**
     * An automatic GLSL uniform containing the specular environment map atlas used within the scene.
     *
     * @example
     * // GLSL declaration
     * uniform sampler2D czm_specularEnvironmentMaps;
     */
    czm_specularEnvironmentMaps: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.SAMPLER_2D,
      getValue: function (uniformState) {
        return uniformState.specularEnvironmentMaps;
      },
    }),

    /**
     * An automatic GLSL uniform containing the size of the specular environment map atlas used within the scene.
     *
     * @example
     * // GLSL declaration
     * uniform vec2 czm_specularEnvironmentMapSize;
     */
    czm_specularEnvironmentMapSize: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_VEC2,
      getValue: function (uniformState) {
        return uniformState.specularEnvironmentMapsDimensions;
      },
    }),

    /**
     * An automatic GLSL uniform containing the maximum level-of-detail of the specular environment map atlas used within the scene.
     *
     * @example
     * // GLSL declaration
     * uniform float czm_specularEnvironmentMapsMaximumLOD;
     */
    czm_specularEnvironmentMapsMaximumLOD: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT,
      getValue: function (uniformState) {
        return uniformState.specularEnvironmentMapsMaximumLOD;
      },
    }),

    /**
     * An automatic GLSL uniform containing the spherical harmonic coefficients used within the scene.
     *
     * @example
     * // GLSL declaration
     * uniform vec3[9] czm_sphericalHarmonicCoefficients;
     */
    czm_sphericalHarmonicCoefficients: new AutomaticUniform({
      size: 9,
      datatype: WebGLConstants$1.FLOAT_VEC3,
      getValue: function (uniformState) {
        return uniformState.sphericalHarmonicCoefficients;
      },
    }),

    /**
     * An automatic GLSL uniform representing a 3x3 rotation matrix that transforms
     * from True Equator Mean Equinox (TEME) axes to the pseudo-fixed axes at the current scene time.
     *
     * @example
     * // GLSL declaration
     * uniform mat3 czm_temeToPseudoFixed;
     *
     * // Example
     * vec3 pseudoFixed = czm_temeToPseudoFixed * teme;
     *
     * @see UniformState#temeToPseudoFixedMatrix
     * @see Transforms.computeTemeToPseudoFixedMatrix
     */
    czm_temeToPseudoFixed: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_MAT3,
      getValue: function (uniformState) {
        return uniformState.temeToPseudoFixedMatrix;
      },
    }),

    /**
     * An automatic GLSL uniform representing the ratio of canvas coordinate space to canvas pixel space.
     *
     * @example
     * uniform float czm_pixelRatio;
     */
    czm_pixelRatio: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT,
      getValue: function (uniformState) {
        return uniformState.pixelRatio;
      },
    }),

    /**
     * An automatic GLSL uniform scalar used to mix a color with the fog color based on the distance to the camera.
     *
     * @see czm_fog
     */
    czm_fogDensity: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT,
      getValue: function (uniformState) {
        return uniformState.fogDensity;
      },
    }),

    /**
     * An automatic GLSL uniform representing the splitter position to use when rendering with a splitter.
     * This will be in pixel coordinates relative to the canvas.
     *
     * @example
     * // GLSL declaration
     * uniform float czm_splitPosition;
     */
    czm_splitPosition: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT,
      getValue: function (uniformState) {
        return uniformState.splitPosition;
      },
    }),

    /**
     * An automatic GLSL uniform scalar representing the geometric tolerance per meter
     */
    czm_geometricToleranceOverMeter: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT,
      getValue: function (uniformState) {
        return uniformState.geometricToleranceOverMeter;
      },
    }),

    /**
     * An automatic GLSL uniform representing the distance from the camera at which to disable the depth test of billboards, labels and points
     * to, for example, prevent clipping against terrain. When set to zero, the depth test should always be applied. When less than zero,
     * the depth test should never be applied.
     */
    czm_minimumDisableDepthTestDistance: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT,
      getValue: function (uniformState) {
        return uniformState.minimumDisableDepthTestDistance;
      },
    }),

    /**
     * An automatic GLSL uniform that will be the highlight color of unclassified 3D Tiles.
     */
    czm_invertClassificationColor: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_VEC4,
      getValue: function (uniformState) {
        return uniformState.invertClassificationColor;
      },
    }),

    /**
     * An automatic GLSL uniform that is used for gamma correction.
     */
    czm_gamma: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT,
      getValue: function (uniformState) {
        return uniformState.gamma;
      },
    }),

    /**
     * An automatic GLSL uniform that stores the ellipsoid radii.
     */
    czm_ellipsoidRadii: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_VEC3,
      getValue: function (uniformState) {
        return uniformState.ellipsoid.radii;
      },
    }),

    /**
     * An automatic GLSL uniform that stores the ellipsoid inverse radii.
     */
    czm_ellipsoidInverseRadii: new AutomaticUniform({
      size: 1,
      datatype: WebGLConstants$1.FLOAT_VEC3,
      getValue: function (uniformState) {
        return uniformState.ellipsoid.oneOverRadii;
      },
    }),
  };

  /**
   * @private
   * @constructor
   */
  function createUniform(gl, activeUniform, uniformName, location) {
    switch (activeUniform.type) {
      case gl.FLOAT:
        return new UniformFloat(gl, activeUniform, uniformName, location);
      case gl.FLOAT_VEC2:
        return new UniformFloatVec2(gl, activeUniform, uniformName, location);
      case gl.FLOAT_VEC3:
        return new UniformFloatVec3(gl, activeUniform, uniformName, location);
      case gl.FLOAT_VEC4:
        return new UniformFloatVec4(gl, activeUniform, uniformName, location);
      case gl.SAMPLER_2D:
      case gl.SAMPLER_CUBE:
        return new UniformSampler(gl, activeUniform, uniformName, location);
      case gl.INT:
      case gl.BOOL:
        return new UniformInt(gl, activeUniform, uniformName, location);
      case gl.INT_VEC2:
      case gl.BOOL_VEC2:
        return new UniformIntVec2(gl, activeUniform, uniformName, location);
      case gl.INT_VEC3:
      case gl.BOOL_VEC3:
        return new UniformIntVec3(gl, activeUniform, uniformName, location);
      case gl.INT_VEC4:
      case gl.BOOL_VEC4:
        return new UniformIntVec4(gl, activeUniform, uniformName, location);
      case gl.FLOAT_MAT2:
        return new UniformMat2(gl, activeUniform, uniformName, location);
      case gl.FLOAT_MAT3:
        return new UniformMat3(gl, activeUniform, uniformName, location);
      case gl.FLOAT_MAT4:
        return new UniformMat4(gl, activeUniform, uniformName, location);
      default:
        throw new RuntimeError(
          `Unrecognized uniform type: ${activeUniform.type} for uniform "${uniformName}".`
        );
    }
  }

  /**
   * @private
   * @constructor
   */
  function UniformFloat(gl, activeUniform, uniformName, location) {
    /**
     * @type {String}
     * @readonly
     */
    this.name = uniformName;

    this.value = undefined;
    this._value = 0.0;

    this._gl = gl;
    this._location = location;
  }

  UniformFloat.prototype.set = function () {
    if (this.value !== this._value) {
      this._value = this.value;
      this._gl.uniform1f(this._location, this.value);
    }
  };

  ///////////////////////////////////////////////////////////////////////////

  /**
   * @private
   * @constructor
   */
  function UniformFloatVec2(gl, activeUniform, uniformName, location) {
    /**
     * @type {String}
     * @readonly
     */
    this.name = uniformName;

    this.value = undefined;
    this._value = new Cartesian2();

    this._gl = gl;
    this._location = location;
  }

  UniformFloatVec2.prototype.set = function () {
    const v = this.value;
    if (!Cartesian2.equals(v, this._value)) {
      Cartesian2.clone(v, this._value);
      this._gl.uniform2f(this._location, v.x, v.y);
    }
  };

  ///////////////////////////////////////////////////////////////////////////

  /**
   * @private
   * @constructor
   */
  function UniformFloatVec3(gl, activeUniform, uniformName, location) {
    /**
     * @type {String}
     * @readonly
     */
    this.name = uniformName;

    this.value = undefined;
    this._value = undefined;

    this._gl = gl;
    this._location = location;
  }

  UniformFloatVec3.prototype.set = function () {
    const v = this.value;

    if (defined(v.red)) {
      if (!Color.equals(v, this._value)) {
        this._value = Color.clone(v, this._value);
        this._gl.uniform3f(this._location, v.red, v.green, v.blue);
      }
    } else if (defined(v.x)) {
      if (!Cartesian3.equals(v, this._value)) {
        this._value = Cartesian3.clone(v, this._value);
        this._gl.uniform3f(this._location, v.x, v.y, v.z);
      }
    } else {
      //>>includeStart('debug', pragmas.debug);
      throw new DeveloperError(`Invalid vec3 value for uniform "${this.name}".`);
      //>>includeEnd('debug');
    }
  };

  ///////////////////////////////////////////////////////////////////////////

  /**
   * @private
   * @constructor
   */
  function UniformFloatVec4(gl, activeUniform, uniformName, location) {
    /**
     * @type {String}
     * @readonly
     */
    this.name = uniformName;

    this.value = undefined;
    this._value = undefined;

    this._gl = gl;
    this._location = location;
  }

  UniformFloatVec4.prototype.set = function () {
    const v = this.value;

    if (defined(v.red)) {
      if (!Color.equals(v, this._value)) {
        this._value = Color.clone(v, this._value);
        this._gl.uniform4f(this._location, v.red, v.green, v.blue, v.alpha);
      }
    } else if (defined(v.x)) {
      if (!Cartesian4.equals(v, this._value)) {
        this._value = Cartesian4.clone(v, this._value);
        this._gl.uniform4f(this._location, v.x, v.y, v.z, v.w);
      }
    } else {
      //>>includeStart('debug', pragmas.debug);
      throw new DeveloperError(`Invalid vec4 value for uniform "${this.name}".`);
      //>>includeEnd('debug');
    }
  };

  ///////////////////////////////////////////////////////////////////////////

  /**
   * @private
   * @constructor
   */
  function UniformSampler(gl, activeUniform, uniformName, location) {
    /**
     * @type {String}
     * @readonly
     */
    this.name = uniformName;

    this.value = undefined;

    this._gl = gl;
    this._location = location;

    this.textureUnitIndex = undefined;
  }

  UniformSampler.prototype.set = function () {
    const gl = this._gl;
    gl.activeTexture(gl.TEXTURE0 + this.textureUnitIndex);

    const v = this.value;
    gl.bindTexture(v._target, v._texture);
  };

  UniformSampler.prototype._setSampler = function (textureUnitIndex) {
    this.textureUnitIndex = textureUnitIndex;
    this._gl.uniform1i(this._location, textureUnitIndex);
    return textureUnitIndex + 1;
  };

  ///////////////////////////////////////////////////////////////////////////

  /**
   * @private
   * @constructor
   */
  function UniformInt(gl, activeUniform, uniformName, location) {
    /**
     * @type {String}
     * @readonly
     */
    this.name = uniformName;

    this.value = undefined;
    this._value = 0.0;

    this._gl = gl;
    this._location = location;
  }

  UniformInt.prototype.set = function () {
    if (this.value !== this._value) {
      this._value = this.value;
      this._gl.uniform1i(this._location, this.value);
    }
  };

  ///////////////////////////////////////////////////////////////////////////
  /**
   * @private
   * @constructor
   */
  function UniformIntVec2(gl, activeUniform, uniformName, location) {
    /**
     * @type {String}
     * @readonly
     */
    this.name = uniformName;

    this.value = undefined;
    this._value = new Cartesian2();

    this._gl = gl;
    this._location = location;
  }

  UniformIntVec2.prototype.set = function () {
    const v = this.value;
    if (!Cartesian2.equals(v, this._value)) {
      Cartesian2.clone(v, this._value);
      this._gl.uniform2i(this._location, v.x, v.y);
    }
  };

  ///////////////////////////////////////////////////////////////////////////
  /**
   * @private
   * @constructor
   */
  function UniformIntVec3(gl, activeUniform, uniformName, location) {
    /**
     * @type {String}
     * @readonly
     */
    this.name = uniformName;

    this.value = undefined;
    this._value = new Cartesian3();

    this._gl = gl;
    this._location = location;
  }

  UniformIntVec3.prototype.set = function () {
    const v = this.value;
    if (!Cartesian3.equals(v, this._value)) {
      Cartesian3.clone(v, this._value);
      this._gl.uniform3i(this._location, v.x, v.y, v.z);
    }
  };

  ///////////////////////////////////////////////////////////////////////////
  /**
   * @private
   * @constructor
   */
  function UniformIntVec4(gl, activeUniform, uniformName, location) {
    /**
     * @type {String}
     * @readonly
     */
    this.name = uniformName;

    this.value = undefined;
    this._value = new Cartesian4();

    this._gl = gl;
    this._location = location;
  }

  UniformIntVec4.prototype.set = function () {
    const v = this.value;
    if (!Cartesian4.equals(v, this._value)) {
      Cartesian4.clone(v, this._value);
      this._gl.uniform4i(this._location, v.x, v.y, v.z, v.w);
    }
  };

  ///////////////////////////////////////////////////////////////////////////

  const scratchUniformArray$1 = new Float32Array(4);
  /**
   * @private
   * @constructor
   */
  function UniformMat2(gl, activeUniform, uniformName, location) {
    /**
     * @type {String}
     * @readonly
     */
    this.name = uniformName;

    this.value = undefined;
    this._value = new Matrix2();

    this._gl = gl;
    this._location = location;
  }

  UniformMat2.prototype.set = function () {
    if (!Matrix2.equalsArray(this.value, this._value, 0)) {
      Matrix2.clone(this.value, this._value);

      const array = Matrix2.toArray(this.value, scratchUniformArray$1);
      this._gl.uniformMatrix2fv(this._location, false, array);
    }
  };

  ///////////////////////////////////////////////////////////////////////////

  const scratchMat3Array = new Float32Array(9);
  /**
   * @private
   * @constructor
   */
  function UniformMat3(gl, activeUniform, uniformName, location) {
    /**
     * @type {String}
     * @readonly
     */
    this.name = uniformName;

    this.value = undefined;
    this._value = new Matrix3();

    this._gl = gl;
    this._location = location;
  }

  UniformMat3.prototype.set = function () {
    if (!Matrix3.equalsArray(this.value, this._value, 0)) {
      Matrix3.clone(this.value, this._value);

      const array = Matrix3.toArray(this.value, scratchMat3Array);
      this._gl.uniformMatrix3fv(this._location, false, array);
    }
  };

  ///////////////////////////////////////////////////////////////////////////

  const scratchMat4Array = new Float32Array(16);
  /**
   * @private
   * @constructor
   */
  function UniformMat4(gl, activeUniform, uniformName, location) {
    /**
     * @type {String}
     * @readonly
     */
    this.name = uniformName;

    this.value = undefined;
    this._value = new Matrix4();

    this._gl = gl;
    this._location = location;
  }

  UniformMat4.prototype.set = function () {
    if (!Matrix4.equalsArray(this.value, this._value, 0)) {
      Matrix4.clone(this.value, this._value);

      const array = Matrix4.toArray(this.value, scratchMat4Array);
      this._gl.uniformMatrix4fv(this._location, false, array);
    }
  };

  /**
   * @private
   * @constructor
   */
  function createUniformArray(gl, activeUniform, uniformName, locations) {
    switch (activeUniform.type) {
      case gl.FLOAT:
        return new UniformArrayFloat(gl, activeUniform, uniformName, locations);
      case gl.FLOAT_VEC2:
        return new UniformArrayFloatVec2(
          gl,
          activeUniform,
          uniformName,
          locations
        );
      case gl.FLOAT_VEC3:
        return new UniformArrayFloatVec3(
          gl,
          activeUniform,
          uniformName,
          locations
        );
      case gl.FLOAT_VEC4:
        return new UniformArrayFloatVec4(
          gl,
          activeUniform,
          uniformName,
          locations
        );
      case gl.SAMPLER_2D:
      case gl.SAMPLER_CUBE:
        return new UniformArraySampler(gl, activeUniform, uniformName, locations);
      case gl.INT:
      case gl.BOOL:
        return new UniformArrayInt(gl, activeUniform, uniformName, locations);
      case gl.INT_VEC2:
      case gl.BOOL_VEC2:
        return new UniformArrayIntVec2(gl, activeUniform, uniformName, locations);
      case gl.INT_VEC3:
      case gl.BOOL_VEC3:
        return new UniformArrayIntVec3(gl, activeUniform, uniformName, locations);
      case gl.INT_VEC4:
      case gl.BOOL_VEC4:
        return new UniformArrayIntVec4(gl, activeUniform, uniformName, locations);
      case gl.FLOAT_MAT2:
        return new UniformArrayMat2(gl, activeUniform, uniformName, locations);
      case gl.FLOAT_MAT3:
        return new UniformArrayMat3(gl, activeUniform, uniformName, locations);
      case gl.FLOAT_MAT4:
        return new UniformArrayMat4(gl, activeUniform, uniformName, locations);
      default:
        throw new RuntimeError(
          `Unrecognized uniform type: ${activeUniform.type} for uniform "${uniformName}".`
        );
    }
  }

  /**
   * @private
   * @constructor
   */
  function UniformArrayFloat(gl, activeUniform, uniformName, locations) {
    const length = locations.length;

    /**
     * @type {String}
     * @readonly
     */
    this.name = uniformName;

    this.value = new Array(length);
    this._value = new Float32Array(length);

    this._gl = gl;
    this._location = locations[0];
  }

  UniformArrayFloat.prototype.set = function () {
    const value = this.value;
    const length = value.length;
    const arraybuffer = this._value;
    let changed = false;

    for (let i = 0; i < length; ++i) {
      const v = value[i];

      if (v !== arraybuffer[i]) {
        arraybuffer[i] = v;
        changed = true;
      }
    }

    if (changed) {
      this._gl.uniform1fv(this._location, arraybuffer);
    }
  };

  ///////////////////////////////////////////////////////////////////////////

  /**
   * @private
   * @constructor
   */
  function UniformArrayFloatVec2(gl, activeUniform, uniformName, locations) {
    const length = locations.length;

    /**
     * @type {String}
     * @readonly
     */
    this.name = uniformName;

    this.value = new Array(length);
    this._value = new Float32Array(length * 2);

    this._gl = gl;
    this._location = locations[0];
  }

  UniformArrayFloatVec2.prototype.set = function () {
    const value = this.value;
    const length = value.length;
    const arraybuffer = this._value;
    let changed = false;
    let j = 0;

    for (let i = 0; i < length; ++i) {
      const v = value[i];

      if (!Cartesian2.equalsArray(v, arraybuffer, j)) {
        Cartesian2.pack(v, arraybuffer, j);
        changed = true;
      }
      j += 2;
    }

    if (changed) {
      this._gl.uniform2fv(this._location, arraybuffer);
    }
  };

  ///////////////////////////////////////////////////////////////////////////

  /**
   * @private
   * @constructor
   */
  function UniformArrayFloatVec3(gl, activeUniform, uniformName, locations) {
    const length = locations.length;

    /**
     * @type {String}
     * @readonly
     */
    this.name = uniformName;

    this.value = new Array(length);
    this._value = new Float32Array(length * 3);

    this._gl = gl;
    this._location = locations[0];
  }

  UniformArrayFloatVec3.prototype.set = function () {
    const value = this.value;
    const length = value.length;
    const arraybuffer = this._value;
    let changed = false;
    let j = 0;

    for (let i = 0; i < length; ++i) {
      const v = value[i];

      if (defined(v.red)) {
        if (
          v.red !== arraybuffer[j] ||
          v.green !== arraybuffer[j + 1] ||
          v.blue !== arraybuffer[j + 2]
        ) {
          arraybuffer[j] = v.red;
          arraybuffer[j + 1] = v.green;
          arraybuffer[j + 2] = v.blue;
          changed = true;
        }
      } else if (defined(v.x)) {
        if (!Cartesian3.equalsArray(v, arraybuffer, j)) {
          Cartesian3.pack(v, arraybuffer, j);
          changed = true;
        }
      } else {
        //>>includeStart('debug', pragmas.debug);
        throw new DeveloperError("Invalid vec3 value.");
        //>>includeEnd('debug');
      }

      j += 3;
    }

    if (changed) {
      this._gl.uniform3fv(this._location, arraybuffer);
    }
  };

  ///////////////////////////////////////////////////////////////////////////

  /**
   * @private
   * @constructor
   */
  function UniformArrayFloatVec4(gl, activeUniform, uniformName, locations) {
    const length = locations.length;

    /**
     * @type {String}
     * @readonly
     */
    this.name = uniformName;

    this.value = new Array(length);
    this._value = new Float32Array(length * 4);

    this._gl = gl;
    this._location = locations[0];
  }

  UniformArrayFloatVec4.prototype.set = function () {
    // PERFORMANCE_IDEA: if it is a common case that only a few elements
    // in a uniform array change, we could use heuristics to determine
    // when it is better to call uniform4f for each element that changed
    // vs. call uniform4fv once to set the entire array.  This applies
    // to all uniform array types, not just vec4.  We might not care
    // once we have uniform buffers since that will be the fast path.

    // PERFORMANCE_IDEA: Micro-optimization (I bet it works though):
    // As soon as changed is true, break into a separate loop that
    // does the copy without the equals check.

    const value = this.value;
    const length = value.length;
    const arraybuffer = this._value;
    let changed = false;
    let j = 0;

    for (let i = 0; i < length; ++i) {
      const v = value[i];

      if (defined(v.red)) {
        if (!Color.equalsArray(v, arraybuffer, j)) {
          Color.pack(v, arraybuffer, j);
          changed = true;
        }
      } else if (defined(v.x)) {
        if (!Cartesian4.equalsArray(v, arraybuffer, j)) {
          Cartesian4.pack(v, arraybuffer, j);
          changed = true;
        }
      } else {
        //>>includeStart('debug', pragmas.debug);
        throw new DeveloperError("Invalid vec4 value.");
        //>>includeEnd('debug');
      }

      j += 4;
    }

    if (changed) {
      this._gl.uniform4fv(this._location, arraybuffer);
    }
  };

  ///////////////////////////////////////////////////////////////////////////

  /**
   * @private
   * @constructor
   */
  function UniformArraySampler(gl, activeUniform, uniformName, locations) {
    const length = locations.length;

    /**
     * @type {String}
     * @readonly
     */
    this.name = uniformName;

    this.value = new Array(length);
    this._value = new Float32Array(length);

    this._gl = gl;
    this._locations = locations;

    this.textureUnitIndex = undefined;
  }

  UniformArraySampler.prototype.set = function () {
    const gl = this._gl;
    const textureUnitIndex = gl.TEXTURE0 + this.textureUnitIndex;

    const value = this.value;
    const length = value.length;
    for (let i = 0; i < length; ++i) {
      const v = value[i];
      gl.activeTexture(textureUnitIndex + i);
      gl.bindTexture(v._target, v._texture);
    }
  };

  UniformArraySampler.prototype._setSampler = function (textureUnitIndex) {
    this.textureUnitIndex = textureUnitIndex;

    const locations = this._locations;
    const length = locations.length;
    for (let i = 0; i < length; ++i) {
      const index = textureUnitIndex + i;
      this._gl.uniform1i(locations[i], index);
    }

    return textureUnitIndex + length;
  };

  ///////////////////////////////////////////////////////////////////////////

  /**
   * @private
   * @constructor
   */
  function UniformArrayInt(gl, activeUniform, uniformName, locations) {
    const length = locations.length;

    /**
     * @type {String}
     * @readonly
     */
    this.name = uniformName;

    this.value = new Array(length);
    this._value = new Int32Array(length);

    this._gl = gl;
    this._location = locations[0];
  }

  UniformArrayInt.prototype.set = function () {
    const value = this.value;
    const length = value.length;
    const arraybuffer = this._value;
    let changed = false;

    for (let i = 0; i < length; ++i) {
      const v = value[i];

      if (v !== arraybuffer[i]) {
        arraybuffer[i] = v;
        changed = true;
      }
    }

    if (changed) {
      this._gl.uniform1iv(this._location, arraybuffer);
    }
  };

  ///////////////////////////////////////////////////////////////////////////

  /**
   * @private
   * @constructor
   */
  function UniformArrayIntVec2(gl, activeUniform, uniformName, locations) {
    const length = locations.length;

    /**
     * @type {String}
     * @readonly
     */
    this.name = uniformName;

    this.value = new Array(length);
    this._value = new Int32Array(length * 2);

    this._gl = gl;
    this._location = locations[0];
  }

  UniformArrayIntVec2.prototype.set = function () {
    const value = this.value;
    const length = value.length;
    const arraybuffer = this._value;
    let changed = false;
    let j = 0;

    for (let i = 0; i < length; ++i) {
      const v = value[i];

      if (!Cartesian2.equalsArray(v, arraybuffer, j)) {
        Cartesian2.pack(v, arraybuffer, j);
        changed = true;
      }
      j += 2;
    }

    if (changed) {
      this._gl.uniform2iv(this._location, arraybuffer);
    }
  };

  ///////////////////////////////////////////////////////////////////////////

  /**
   * @private
   * @constructor
   */
  function UniformArrayIntVec3(gl, activeUniform, uniformName, locations) {
    const length = locations.length;

    /**
     * @type {String}
     * @readonly
     */
    this.name = uniformName;

    this.value = new Array(length);
    this._value = new Int32Array(length * 3);

    this._gl = gl;
    this._location = locations[0];
  }

  UniformArrayIntVec3.prototype.set = function () {
    const value = this.value;
    const length = value.length;
    const arraybuffer = this._value;
    let changed = false;
    let j = 0;

    for (let i = 0; i < length; ++i) {
      const v = value[i];

      if (!Cartesian3.equalsArray(v, arraybuffer, j)) {
        Cartesian3.pack(v, arraybuffer, j);
        changed = true;
      }
      j += 3;
    }

    if (changed) {
      this._gl.uniform3iv(this._location, arraybuffer);
    }
  };

  ///////////////////////////////////////////////////////////////////////////

  /**
   * @private
   * @constructor
   */
  function UniformArrayIntVec4(gl, activeUniform, uniformName, locations) {
    const length = locations.length;

    /**
     * @type {String}
     * @readonly
     */
    this.name = uniformName;

    this.value = new Array(length);
    this._value = new Int32Array(length * 4);

    this._gl = gl;
    this._location = locations[0];
  }

  UniformArrayIntVec4.prototype.set = function () {
    const value = this.value;
    const length = value.length;
    const arraybuffer = this._value;
    let changed = false;
    let j = 0;

    for (let i = 0; i < length; ++i) {
      const v = value[i];

      if (!Cartesian4.equalsArray(v, arraybuffer, j)) {
        Cartesian4.pack(v, arraybuffer, j);
        changed = true;
      }
      j += 4;
    }

    if (changed) {
      this._gl.uniform4iv(this._location, arraybuffer);
    }
  };

  ///////////////////////////////////////////////////////////////////////////

  /**
   * @private
   * @constructor
   */
  function UniformArrayMat2(gl, activeUniform, uniformName, locations) {
    const length = locations.length;

    /**
     * @type {String}
     * @readonly
     */
    this.name = uniformName;

    this.value = new Array(length);
    this._value = new Float32Array(length * 4);

    this._gl = gl;
    this._location = locations[0];
  }

  UniformArrayMat2.prototype.set = function () {
    const value = this.value;
    const length = value.length;
    const arraybuffer = this._value;
    let changed = false;
    let j = 0;

    for (let i = 0; i < length; ++i) {
      const v = value[i];

      if (!Matrix2.equalsArray(v, arraybuffer, j)) {
        Matrix2.pack(v, arraybuffer, j);
        changed = true;
      }
      j += 4;
    }

    if (changed) {
      this._gl.uniformMatrix2fv(this._location, false, arraybuffer);
    }
  };

  ///////////////////////////////////////////////////////////////////////////

  /**
   * @private
   * @constructor
   */
  function UniformArrayMat3(gl, activeUniform, uniformName, locations) {
    const length = locations.length;

    /**
     * @type {String}
     * @readonly
     */
    this.name = uniformName;

    this.value = new Array(length);
    this._value = new Float32Array(length * 9);

    this._gl = gl;
    this._location = locations[0];
  }

  UniformArrayMat3.prototype.set = function () {
    const value = this.value;
    const length = value.length;
    const arraybuffer = this._value;
    let changed = false;
    let j = 0;

    for (let i = 0; i < length; ++i) {
      const v = value[i];

      if (!Matrix3.equalsArray(v, arraybuffer, j)) {
        Matrix3.pack(v, arraybuffer, j);
        changed = true;
      }
      j += 9;
    }

    if (changed) {
      this._gl.uniformMatrix3fv(this._location, false, arraybuffer);
    }
  };

  ///////////////////////////////////////////////////////////////////////////

  /**
   * @private
   * @constructor
   */
  function UniformArrayMat4(gl, activeUniform, uniformName, locations) {
    const length = locations.length;

    /**
     * @type {String}
     * @readonly
     */
    this.name = uniformName;

    this.value = new Array(length);
    this._value = new Float32Array(length * 16);

    this._gl = gl;
    this._location = locations[0];
  }

  UniformArrayMat4.prototype.set = function () {
    const value = this.value;
    const length = value.length;
    const arraybuffer = this._value;
    let changed = false;
    let j = 0;

    for (let i = 0; i < length; ++i) {
      const v = value[i];

      if (!Matrix4.equalsArray(v, arraybuffer, j)) {
        Matrix4.pack(v, arraybuffer, j);
        changed = true;
      }
      j += 16;
    }

    if (changed) {
      this._gl.uniformMatrix4fv(this._location, false, arraybuffer);
    }
  };

  let nextShaderProgramId = 0;

  /**
   * @private
   */
  function ShaderProgram(options) {
    let vertexShaderText = options.vertexShaderText;
    let fragmentShaderText = options.fragmentShaderText;

    if (typeof spector !== "undefined") {
      // The #line statements common in Cesium shaders interfere with the ability of the
      // SpectorJS to show errors on the correct line. So remove them when SpectorJS
      // is active.
      vertexShaderText = vertexShaderText.replace(/^#line/gm, "//#line");
      fragmentShaderText = fragmentShaderText.replace(/^#line/gm, "//#line");
    }

    const modifiedFS = handleUniformPrecisionMismatches(
      vertexShaderText,
      fragmentShaderText
    );

    this._gl = options.gl;
    this._logShaderCompilation = options.logShaderCompilation;
    this._debugShaders = options.debugShaders;
    this._attributeLocations = options.attributeLocations;

    this._program = undefined;
    this._numberOfVertexAttributes = undefined;
    this._vertexAttributes = undefined;
    this._uniformsByName = undefined;
    this._uniforms = undefined;
    this._automaticUniforms = undefined;
    this._manualUniforms = undefined;
    this._duplicateUniformNames = modifiedFS.duplicateUniformNames;
    this._cachedShader = undefined; // Used by ShaderCache

    /**
     * @private
     */
    this.maximumTextureUnitIndex = undefined;

    this._vertexShaderSource = options.vertexShaderSource;
    this._vertexShaderText = options.vertexShaderText;
    this._fragmentShaderSource = options.fragmentShaderSource;
    this._fragmentShaderText = modifiedFS.fragmentShaderText;

    /**
     * @private
     */
    this.id = nextShaderProgramId++;
  }

  ShaderProgram.fromCache = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    Check.defined("options.context", options.context);
    //>>includeEnd('debug');

    return options.context.shaderCache.getShaderProgram(options);
  };

  ShaderProgram.replaceCache = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    Check.defined("options.context", options.context);
    //>>includeEnd('debug');

    return options.context.shaderCache.replaceShaderProgram(options);
  };

  Object.defineProperties(ShaderProgram.prototype, {
    /**
     * GLSL source for the shader program's vertex shader.
     * @memberof ShaderProgram.prototype
     *
     * @type {ShaderSource}
     * @readonly
     */
    vertexShaderSource: {
      get: function () {
        return this._vertexShaderSource;
      },
    },
    /**
     * GLSL source for the shader program's fragment shader.
     * @memberof ShaderProgram.prototype
     *
     * @type {ShaderSource}
     * @readonly
     */
    fragmentShaderSource: {
      get: function () {
        return this._fragmentShaderSource;
      },
    },
    vertexAttributes: {
      get: function () {
        initialize$o(this);
        return this._vertexAttributes;
      },
    },
    numberOfVertexAttributes: {
      get: function () {
        initialize$o(this);
        return this._numberOfVertexAttributes;
      },
    },
    allUniforms: {
      get: function () {
        initialize$o(this);
        return this._uniformsByName;
      },
    },
  });

  function extractUniforms(shaderText) {
    const uniformNames = [];
    const uniformLines = shaderText.match(/uniform.*?(?![^{]*})(?=[=\[;])/g);
    if (defined(uniformLines)) {
      const len = uniformLines.length;
      for (let i = 0; i < len; i++) {
        const line = uniformLines[i].trim();
        const name = line.slice(line.lastIndexOf(" ") + 1);
        uniformNames.push(name);
      }
    }
    return uniformNames;
  }

  function handleUniformPrecisionMismatches(
    vertexShaderText,
    fragmentShaderText
  ) {
    // If a uniform exists in both the vertex and fragment shader but with different precision qualifiers,
    // give the fragment shader uniform a different name. This fixes shader compilation errors on devices
    // that only support mediump in the fragment shader.
    const duplicateUniformNames = {};

    if (!ContextLimits.highpFloatSupported || !ContextLimits.highpIntSupported) {
      let i, j;
      let uniformName;
      let duplicateName;
      const vertexShaderUniforms = extractUniforms(vertexShaderText);
      const fragmentShaderUniforms = extractUniforms(fragmentShaderText);
      const vertexUniformsCount = vertexShaderUniforms.length;
      const fragmentUniformsCount = fragmentShaderUniforms.length;

      for (i = 0; i < vertexUniformsCount; i++) {
        for (j = 0; j < fragmentUniformsCount; j++) {
          if (vertexShaderUniforms[i] === fragmentShaderUniforms[j]) {
            uniformName = vertexShaderUniforms[i];
            duplicateName = `czm_mediump_${uniformName}`;
            // Update fragmentShaderText with renamed uniforms
            const re = new RegExp(`${uniformName}\\b`, "g");
            fragmentShaderText = fragmentShaderText.replace(re, duplicateName);
            duplicateUniformNames[duplicateName] = uniformName;
          }
        }
      }
    }

    return {
      fragmentShaderText: fragmentShaderText,
      duplicateUniformNames: duplicateUniformNames,
    };
  }

  const consolePrefix = "[Cesium WebGL] ";

  function createAndLinkProgram(gl, shader) {
    const vsSource = shader._vertexShaderText;
    const fsSource = shader._fragmentShaderText;

    const vertexShader = gl.createShader(gl.VERTEX_SHADER);
    gl.shaderSource(vertexShader, vsSource);
    gl.compileShader(vertexShader);

    const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
    gl.shaderSource(fragmentShader, fsSource);
    gl.compileShader(fragmentShader);

    const program = gl.createProgram();
    gl.attachShader(program, vertexShader);
    gl.attachShader(program, fragmentShader);

    gl.deleteShader(vertexShader);
    gl.deleteShader(fragmentShader);

    const attributeLocations = shader._attributeLocations;
    if (defined(attributeLocations)) {
      for (const attribute in attributeLocations) {
        if (attributeLocations.hasOwnProperty(attribute)) {
          gl.bindAttribLocation(
            program,
            attributeLocations[attribute],
            attribute
          );
        }
      }
    }

    gl.linkProgram(program);

    let log;
    if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
      const debugShaders = shader._debugShaders;

      // For performance, only check compile errors if there is a linker error.
      if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
        log = gl.getShaderInfoLog(fragmentShader);
        console.error(`${consolePrefix}Fragment shader compile log: ${log}`);
        if (defined(debugShaders)) {
          const fragmentSourceTranslation = debugShaders.getTranslatedShaderSource(
            fragmentShader
          );
          if (fragmentSourceTranslation !== "") {
            console.error(
              `${consolePrefix}Translated fragment shader source:\n${fragmentSourceTranslation}`
            );
          } else {
            console.error(`${consolePrefix}Fragment shader translation failed.`);
          }
        }

        gl.deleteProgram(program);
        throw new RuntimeError(
          `Fragment shader failed to compile.  Compile log: ${log}`
        );
      }

      if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {
        log = gl.getShaderInfoLog(vertexShader);
        console.error(`${consolePrefix}Vertex shader compile log: ${log}`);
        if (defined(debugShaders)) {
          const vertexSourceTranslation = debugShaders.getTranslatedShaderSource(
            vertexShader
          );
          if (vertexSourceTranslation !== "") {
            console.error(
              `${consolePrefix}Translated vertex shader source:\n${vertexSourceTranslation}`
            );
          } else {
            console.error(`${consolePrefix}Vertex shader translation failed.`);
          }
        }

        gl.deleteProgram(program);
        throw new RuntimeError(
          `Vertex shader failed to compile.  Compile log: ${log}`
        );
      }

      log = gl.getProgramInfoLog(program);
      console.error(`${consolePrefix}Shader program link log: ${log}`);
      if (defined(debugShaders)) {
        console.error(
          `${consolePrefix}Translated vertex shader source:\n${debugShaders.getTranslatedShaderSource(
          vertexShader
        )}`
        );
        console.error(
          `${consolePrefix}Translated fragment shader source:\n${debugShaders.getTranslatedShaderSource(
          fragmentShader
        )}`
        );
      }

      gl.deleteProgram(program);
      throw new RuntimeError(`Program failed to link.  Link log: ${log}`);
    }

    const logShaderCompilation = shader._logShaderCompilation;

    if (logShaderCompilation) {
      log = gl.getShaderInfoLog(vertexShader);
      if (defined(log) && log.length > 0) {
        console.log(`${consolePrefix}Vertex shader compile log: ${log}`);
      }
    }

    if (logShaderCompilation) {
      log = gl.getShaderInfoLog(fragmentShader);
      if (defined(log) && log.length > 0) {
        console.log(`${consolePrefix}Fragment shader compile log: ${log}`);
      }
    }

    if (logShaderCompilation) {
      log = gl.getProgramInfoLog(program);
      if (defined(log) && log.length > 0) {
        console.log(`${consolePrefix}Shader program link log: ${log}`);
      }
    }

    return program;
  }

  function findVertexAttributes(gl, program, numberOfAttributes) {
    const attributes = {};
    for (let i = 0; i < numberOfAttributes; ++i) {
      const attr = gl.getActiveAttrib(program, i);
      const location = gl.getAttribLocation(program, attr.name);

      attributes[attr.name] = {
        name: attr.name,
        type: attr.type,
        index: location,
      };
    }

    return attributes;
  }

  function findUniforms(gl, program) {
    const uniformsByName = {};
    const uniforms = [];
    const samplerUniforms = [];

    const numberOfUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);

    for (let i = 0; i < numberOfUniforms; ++i) {
      const activeUniform = gl.getActiveUniform(program, i);
      const suffix = "[0]";
      const uniformName =
        activeUniform.name.indexOf(
          suffix,
          activeUniform.name.length - suffix.length
        ) !== -1
          ? activeUniform.name.slice(0, activeUniform.name.length - 3)
          : activeUniform.name;

      // Ignore GLSL built-in uniforms returned in Firefox.
      if (uniformName.indexOf("gl_") !== 0) {
        if (activeUniform.name.indexOf("[") < 0) {
          // Single uniform
          const location = gl.getUniformLocation(program, uniformName);

          // IE 11.0.9 needs this check since getUniformLocation can return null
          // if the uniform is not active (e.g., it is optimized out).  Looks like
          // getActiveUniform() above returns uniforms that are not actually active.
          if (location !== null) {
            const uniform = createUniform(
              gl,
              activeUniform,
              uniformName,
              location
            );

            uniformsByName[uniformName] = uniform;
            uniforms.push(uniform);

            if (uniform._setSampler) {
              samplerUniforms.push(uniform);
            }
          }
        } else {
          // Uniform array

          let uniformArray;
          let locations;
          let value;
          let loc;

          // On some platforms - Nexus 4 in Firefox for one - an array of sampler2D ends up being represented
          // as separate uniforms, one for each array element.  Check for and handle that case.
          const indexOfBracket = uniformName.indexOf("[");
          if (indexOfBracket >= 0) {
            // We're assuming the array elements show up in numerical order - it seems to be true.
            uniformArray = uniformsByName[uniformName.slice(0, indexOfBracket)];

            // Nexus 4 with Android 4.3 needs this check, because it reports a uniform
            // with the strange name webgl_3467e0265d05c3c1[1] in our globe surface shader.
            if (!defined(uniformArray)) {
              continue;
            }

            locations = uniformArray._locations;

            // On the Nexus 4 in Chrome, we get one uniform per sampler, just like in Firefox,
            // but the size is not 1 like it is in Firefox.  So if we push locations here,
            // we'll end up adding too many locations.
            if (locations.length <= 1) {
              value = uniformArray.value;
              loc = gl.getUniformLocation(program, uniformName);

              // Workaround for IE 11.0.9.  See above.
              if (loc !== null) {
                locations.push(loc);
                value.push(gl.getUniform(program, loc));
              }
            }
          } else {
            locations = [];
            for (let j = 0; j < activeUniform.size; ++j) {
              loc = gl.getUniformLocation(program, `${uniformName}[${j}]`);

              // Workaround for IE 11.0.9.  See above.
              if (loc !== null) {
                locations.push(loc);
              }
            }
            uniformArray = createUniformArray(
              gl,
              activeUniform,
              uniformName,
              locations
            );

            uniformsByName[uniformName] = uniformArray;
            uniforms.push(uniformArray);

            if (uniformArray._setSampler) {
              samplerUniforms.push(uniformArray);
            }
          }
        }
      }
    }

    return {
      uniformsByName: uniformsByName,
      uniforms: uniforms,
      samplerUniforms: samplerUniforms,
    };
  }

  function partitionUniforms(shader, uniforms) {
    const automaticUniforms = [];
    const manualUniforms = [];

    for (const uniform in uniforms) {
      if (uniforms.hasOwnProperty(uniform)) {
        const uniformObject = uniforms[uniform];
        let uniformName = uniform;
        // if it's a duplicate uniform, use its original name so it is updated correctly
        const duplicateUniform = shader._duplicateUniformNames[uniformName];
        if (defined(duplicateUniform)) {
          uniformObject.name = duplicateUniform;
          uniformName = duplicateUniform;
        }
        const automaticUniform = AutomaticUniforms[uniformName];
        if (defined(automaticUniform)) {
          automaticUniforms.push({
            uniform: uniformObject,
            automaticUniform: automaticUniform,
          });
        } else {
          manualUniforms.push(uniformObject);
        }
      }
    }

    return {
      automaticUniforms: automaticUniforms,
      manualUniforms: manualUniforms,
    };
  }

  function setSamplerUniforms(gl, program, samplerUniforms) {
    gl.useProgram(program);

    let textureUnitIndex = 0;
    const length = samplerUniforms.length;
    for (let i = 0; i < length; ++i) {
      textureUnitIndex = samplerUniforms[i]._setSampler(textureUnitIndex);
    }

    gl.useProgram(null);

    return textureUnitIndex;
  }

  function initialize$o(shader) {
    if (defined(shader._program)) {
      return;
    }

    reinitialize(shader);
  }

  function reinitialize(shader) {
    const oldProgram = shader._program;

    const gl = shader._gl;
    const program = createAndLinkProgram(gl, shader, shader._debugShaders);
    const numberOfVertexAttributes = gl.getProgramParameter(
      program,
      gl.ACTIVE_ATTRIBUTES
    );
    const uniforms = findUniforms(gl, program);
    const partitionedUniforms = partitionUniforms(
      shader,
      uniforms.uniformsByName
    );

    shader._program = program;
    shader._numberOfVertexAttributes = numberOfVertexAttributes;
    shader._vertexAttributes = findVertexAttributes(
      gl,
      program,
      numberOfVertexAttributes
    );
    shader._uniformsByName = uniforms.uniformsByName;
    shader._uniforms = uniforms.uniforms;
    shader._automaticUniforms = partitionedUniforms.automaticUniforms;
    shader._manualUniforms = partitionedUniforms.manualUniforms;

    shader.maximumTextureUnitIndex = setSamplerUniforms(
      gl,
      program,
      uniforms.samplerUniforms
    );

    if (oldProgram) {
      shader._gl.deleteProgram(oldProgram);
    }

    // If SpectorJS is active, add the hook to make the shader editor work.
    // https://github.com/BabylonJS/Spector.js/blob/master/documentation/extension.md#shader-editor
    if (typeof spector !== "undefined") {
      shader._program.__SPECTOR_rebuildProgram = function (
        vertexSourceCode, // The new vertex shader source
        fragmentSourceCode, // The new fragment shader source
        onCompiled, // Callback triggered by your engine when the compilation is successful. It needs to send back the new linked program.
        onError // Callback triggered by your engine in case of error. It needs to send the WebGL error to allow the editor to display the error in the gutter.
      ) {
        const originalVS = shader._vertexShaderText;
        const originalFS = shader._fragmentShaderText;

        // SpectorJS likes to replace `!=` with `! =` for unknown reasons,
        // and that causes glsl compile failures. So fix that up.
        const regex = / ! = /g;
        shader._vertexShaderText = vertexSourceCode.replace(regex, " != ");
        shader._fragmentShaderText = fragmentSourceCode.replace(regex, " != ");

        try {
          reinitialize(shader);
          onCompiled(shader._program);
        } catch (e) {
          shader._vertexShaderText = originalVS;
          shader._fragmentShaderText = originalFS;

          // Only pass on the WebGL error:
          const errorMatcher = /(?:Compile|Link) error: ([^]*)/;
          const match = errorMatcher.exec(e.message);
          if (match) {
            onError(match[1]);
          } else {
            onError(e.message);
          }
        }
      };
    }
  }

  ShaderProgram.prototype._bind = function () {
    initialize$o(this);
    this._gl.useProgram(this._program);
  };

  ShaderProgram.prototype._setUniforms = function (
    uniformMap,
    uniformState,
    validate
  ) {
    let len;
    let i;

    if (defined(uniformMap)) {
      const manualUniforms = this._manualUniforms;
      len = manualUniforms.length;
      for (i = 0; i < len; ++i) {
        const mu = manualUniforms[i];
        mu.value = uniformMap[mu.name]();
      }
    }

    const automaticUniforms = this._automaticUniforms;
    len = automaticUniforms.length;
    for (i = 0; i < len; ++i) {
      const au = automaticUniforms[i];
      au.uniform.value = au.automaticUniform.getValue(uniformState);
    }

    ///////////////////////////////////////////////////////////////////

    // It appears that assigning the uniform values above and then setting them here
    // (which makes the GL calls) is faster than removing this loop and making
    // the GL calls above.  I suspect this is because each GL call pollutes the
    // L2 cache making our JavaScript and the browser/driver ping-pong cache lines.
    const uniforms = this._uniforms;
    len = uniforms.length;
    for (i = 0; i < len; ++i) {
      uniforms[i].set();
    }

    if (validate) {
      const gl = this._gl;
      const program = this._program;

      gl.validateProgram(program);
      //>>includeStart('debug', pragmas.debug);
      if (!gl.getProgramParameter(program, gl.VALIDATE_STATUS)) {
        throw new DeveloperError(
          `Program validation failed.  Program info log: ${gl.getProgramInfoLog(
          program
        )}`
        );
      }
      //>>includeEnd('debug');
    }
  };

  ShaderProgram.prototype.isDestroyed = function () {
    return false;
  };

  ShaderProgram.prototype.destroy = function () {
    this._cachedShader.cache.releaseShaderProgram(this);
    return undefined;
  };

  ShaderProgram.prototype.finalDestroy = function () {
    this._gl.deleteProgram(this._program);
    return destroyObject(this);
  };

  /**
   * A function to port GLSL shaders from GLSL ES 1.00 to GLSL ES 3.00
   *
   * This function is nowhere near comprehensive or complete. It just
   * handles some common cases.
   *
   * Note that this function requires the presence of the
   * "#define OUTPUT_DECLARATION" line that is appended
   * by ShaderSource.
   *
   * @private
   */
  function modernizeShader(source, isFragmentShader) {
    const outputDeclarationRegex = /#define OUTPUT_DECLARATION/;
    const splitSource = source.split("\n");

    if (/#version 300 es/g.test(source)) {
      return source;
    }

    let outputDeclarationLine = -1;
    let i, line;
    for (i = 0; i < splitSource.length; ++i) {
      line = splitSource[i];
      if (outputDeclarationRegex.test(line)) {
        outputDeclarationLine = i;
        break;
      }
    }

    if (outputDeclarationLine === -1) {
      throw new DeveloperError("Could not find a #define OUTPUT_DECLARATION!");
    }

    const outputVariables = [];

    for (i = 0; i < 10; i++) {
      const fragDataString = `gl_FragData\\[${i}\\]`;
      const newOutput = `czm_out${i}`;
      const regex = new RegExp(fragDataString, "g");
      if (regex.test(source)) {
        setAdd(newOutput, outputVariables);
        replaceInSourceString(fragDataString, newOutput, splitSource);
        splitSource.splice(
          outputDeclarationLine,
          0,
          `layout(location = ${i}) out vec4 ${newOutput};`
        );
        outputDeclarationLine += 1;
      }
    }

    const czmFragColor = "czm_fragColor";
    if (findInSource("gl_FragColor", splitSource)) {
      setAdd(czmFragColor, outputVariables);
      replaceInSourceString("gl_FragColor", czmFragColor, splitSource);
      splitSource.splice(
        outputDeclarationLine,
        0,
        "layout(location = 0) out vec4 czm_fragColor;"
      );
      outputDeclarationLine += 1;
    }

    const variableMap = getVariablePreprocessorBranch(
      outputVariables,
      splitSource
    );
    const lineAdds = {};
    for (i = 0; i < splitSource.length; i++) {
      line = splitSource[i];
      for (const variable in variableMap) {
        if (variableMap.hasOwnProperty(variable)) {
          const matchVar = new RegExp(
            `(layout)[^]+(out)[^]+(${variable})[^]+`,
            "g"
          );
          if (matchVar.test(line)) {
            lineAdds[line] = variable;
          }
        }
      }
    }

    for (const layoutDeclaration in lineAdds) {
      if (lineAdds.hasOwnProperty(layoutDeclaration)) {
        const variableName = lineAdds[layoutDeclaration];
        let lineNumber = splitSource.indexOf(layoutDeclaration);
        const entry = variableMap[variableName];
        const depth = entry.length;
        for (let d = 0; d < depth; d++) {
          splitSource.splice(lineNumber, 0, entry[d]);
        }
        lineNumber += depth + 1;
        for (let d = depth - 1; d >= 0; d--) {
          splitSource.splice(lineNumber, 0, `#endif //${entry[d]}`);
        }
      }
    }

    const webgl2UniqueID = "WEBGL_2";
    const webgl2DefineMacro = `#define ${webgl2UniqueID}`;
    const versionThree = "#version 300 es";
    let foundVersion = false;
    for (i = 0; i < splitSource.length; i++) {
      if (/#version/.test(splitSource[i])) {
        splitSource[i] = versionThree;
        foundVersion = true;
        break;
      }
    }

    if (!foundVersion) {
      splitSource.splice(0, 0, versionThree);
    }

    splitSource.splice(1, 0, webgl2DefineMacro);

    removeExtension("EXT_draw_buffers", webgl2UniqueID, splitSource);
    removeExtension("EXT_frag_depth", webgl2UniqueID, splitSource);
    removeExtension("OES_standard_derivatives", webgl2UniqueID, splitSource);

    replaceInSourceString("texture2D", "texture", splitSource);
    replaceInSourceString("texture3D", "texture", splitSource);
    replaceInSourceString("textureCube", "texture", splitSource);
    replaceInSourceString("gl_FragDepthEXT", "gl_FragDepth", splitSource);

    if (isFragmentShader) {
      replaceInSourceString("varying", "in", splitSource);
    } else {
      replaceInSourceString("attribute", "in", splitSource);
      replaceInSourceString("varying", "out", splitSource);
    }

    return compileSource(splitSource);
  }

  // Note that this fails if your string looks like
  // searchString[singleCharacter]searchString
  function replaceInSourceString(str, replacement, splitSource) {
    const regexStr = `(^|[^\\w])(${str})($|[^\\w])`;
    const regex = new RegExp(regexStr, "g");

    const splitSourceLength = splitSource.length;
    for (let i = 0; i < splitSourceLength; ++i) {
      const line = splitSource[i];
      splitSource[i] = line.replace(regex, `$1${replacement}$3`);
    }
  }

  function replaceInSourceRegex(regex, replacement, splitSource) {
    const splitSourceLength = splitSource.length;
    for (let i = 0; i < splitSourceLength; ++i) {
      const line = splitSource[i];
      splitSource[i] = line.replace(regex, replacement);
    }
  }

  function findInSource(str, splitSource) {
    const regexStr = `(^|[^\\w])(${str})($|[^\\w])`;
    const regex = new RegExp(regexStr, "g");

    const splitSourceLength = splitSource.length;
    for (let i = 0; i < splitSourceLength; ++i) {
      const line = splitSource[i];
      if (regex.test(line)) {
        return true;
      }
    }
    return false;
  }

  function compileSource(splitSource) {
    let wholeSource = "";

    const splitSourceLength = splitSource.length;
    for (let i = 0; i < splitSourceLength; ++i) {
      wholeSource += `${splitSource[i]}\n`;
    }
    return wholeSource;
  }

  function setAdd(variable, set) {
    if (set.indexOf(variable) === -1) {
      set.push(variable);
    }
  }

  function getVariablePreprocessorBranch(layoutVariables, splitSource) {
    const variableMap = {};

    const numLayoutVariables = layoutVariables.length;

    const stack = [];
    for (let i = 0; i < splitSource.length; ++i) {
      const line = splitSource[i];
      const hasIF = /(#ifdef|#if)/g.test(line);
      const hasELSE = /#else/g.test(line);
      const hasENDIF = /#endif/g.test(line);

      if (hasIF) {
        stack.push(line);
      } else if (hasELSE) {
        const top = stack[stack.length - 1];
        let op = top.replace("ifdef", "ifndef");
        if (/if/g.test(op)) {
          op = op.replace(/(#if\s+)(\S*)([^]*)/, "$1!($2)$3");
        }
        stack.pop();
        stack.push(op);
      } else if (hasENDIF) {
        stack.pop();
      } else if (!/layout/g.test(line)) {
        for (let varIndex = 0; varIndex < numLayoutVariables; ++varIndex) {
          const varName = layoutVariables[varIndex];
          if (line.indexOf(varName) !== -1) {
            if (!defined(variableMap[varName])) {
              variableMap[varName] = stack.slice();
            } else {
              variableMap[varName] = variableMap[varName].filter(function (x) {
                return stack.indexOf(x) >= 0;
              });
            }
          }
        }
      }
    }

    return variableMap;
  }

  function removeExtension(name, webgl2UniqueID, splitSource) {
    const regex = `#extension\\s+GL_${name}\\s+:\\s+[a-zA-Z0-9]+\\s*$`;
    replaceInSourceRegex(new RegExp(regex, "g"), "", splitSource);

    // replace any possible directive #ifdef (GL_EXT_extension) with WEBGL_2 unique directive
    replaceInSourceString(`GL_${name}`, webgl2UniqueID, splitSource);
  }

  //This file is automatically rebuilt by the Cesium build process.
  var czm_degreesPerRadian = "const float czm_degreesPerRadian = 57.29577951308232;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_depthRange = "const czm_depthRangeStruct czm_depthRange = czm_depthRangeStruct(0.0, 1.0);\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_epsilon1 = "const float czm_epsilon1 = 0.1;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_epsilon2 = "const float czm_epsilon2 = 0.01;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_epsilon3 = "const float czm_epsilon3 = 0.001;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_epsilon4 = "const float czm_epsilon4 = 0.0001;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_epsilon5 = "const float czm_epsilon5 = 0.00001;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_epsilon6 = "const float czm_epsilon6 = 0.000001;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_epsilon7 = "const float czm_epsilon7 = 0.0000001;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_infinity = "const float czm_infinity = 5906376272000.0;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_oneOverPi = "const float czm_oneOverPi = 0.3183098861837907;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_oneOverTwoPi = "const float czm_oneOverTwoPi = 0.15915494309189535;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_passCesium3DTile = "const float czm_passCesium3DTile = 4.0;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_passCesium3DTileClassification = "const float czm_passCesium3DTileClassification = 5.0;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_passCesium3DTileClassificationIgnoreShow = "const float czm_passCesium3DTileClassificationIgnoreShow = 6.0;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_passClassification = "const float czm_passClassification = 7.0;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_passCompute = "const float czm_passCompute = 1.0;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_passEnvironment = "const float czm_passEnvironment = 0.0;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_passGlobe = "const float czm_passGlobe = 2.0;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_passOpaque = "const float czm_passOpaque = 7.0;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_passOverlay = "const float czm_passOverlay = 9.0;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_passTerrainClassification = "const float czm_passTerrainClassification = 3.0;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_passTranslucent = "const float czm_passTranslucent = 8.0;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_pi = "const float czm_pi = 3.141592653589793;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_piOverFour = "const float czm_piOverFour = 0.7853981633974483;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_piOverSix = "const float czm_piOverSix = 0.5235987755982988;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_piOverThree = "const float czm_piOverThree = 1.0471975511965976;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_piOverTwo = "const float czm_piOverTwo = 1.5707963267948966;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_radiansPerDegree = "const float czm_radiansPerDegree = 0.017453292519943295;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_sceneMode2D = "const float czm_sceneMode2D = 2.0;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_sceneMode3D = "const float czm_sceneMode3D = 3.0;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_sceneModeColumbusView = "const float czm_sceneModeColumbusView = 1.0;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_sceneModeMorphing = "const float czm_sceneModeMorphing = 0.0;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_solarRadius = "const float czm_solarRadius = 695500000.0;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_threePiOver2 = "const float czm_threePiOver2 = 4.71238898038469;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_twoPi = "const float czm_twoPi = 6.283185307179586;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_webMercatorMaxLatitude = "const float czm_webMercatorMaxLatitude = 1.4844222297453324;\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_depthRangeStruct = "struct czm_depthRangeStruct\n\
{\n\
float near;\n\
float far;\n\
};\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_material = "struct czm_material\n\
{\n\
vec3 diffuse;\n\
float specular;\n\
float shininess;\n\
vec3 normal;\n\
vec3 emission;\n\
float alpha;\n\
};\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_materialInput = "struct czm_materialInput\n\
{\n\
float s;\n\
vec2 st;\n\
vec3 str;\n\
vec3 normalEC;\n\
mat3 tangentToEyeMatrix;\n\
vec3 positionToEyeEC;\n\
float height;\n\
float slope;\n\
float aspect;\n\
};\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_modelMaterial = "struct czm_modelMaterial {\n\
vec3 diffuse;\n\
float alpha;\n\
vec3 specular;\n\
float roughness;\n\
vec3 normalEC;\n\
float occlusion;\n\
vec3 emissive;\n\
};\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_modelVertexOutput = "struct czm_modelVertexOutput {\n\
vec3 positionMC;\n\
float pointSize;\n\
};\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_pbrParameters = "struct czm_pbrParameters\n\
{\n\
vec3 diffuseColor;\n\
float roughness;\n\
vec3 f0;\n\
};\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_ray = "struct czm_ray\n\
{\n\
vec3 origin;\n\
vec3 direction;\n\
};\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_raySegment = "struct czm_raySegment\n\
{\n\
float start;\n\
float stop;\n\
};\n\
const czm_raySegment czm_emptyRaySegment = czm_raySegment(-czm_infinity, -czm_infinity);\n\
const czm_raySegment czm_fullRaySegment = czm_raySegment(0.0, czm_infinity);\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_shadowParameters = "struct czm_shadowParameters\n\
{\n\
#ifdef USE_CUBE_MAP_SHADOW\n\
vec3 texCoords;\n\
#else\n\
vec2 texCoords;\n\
#endif\n\
float depthBias;\n\
float depth;\n\
float nDotL;\n\
vec2 texelStepSize;\n\
float normalShadingSmooth;\n\
float darkness;\n\
};\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_HSBToRGB = "const vec4 K_HSB2RGB = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);\n\
vec3 czm_HSBToRGB(vec3 hsb)\n\
{\n\
vec3 p = abs(fract(hsb.xxx + K_HSB2RGB.xyz) * 6.0 - K_HSB2RGB.www);\n\
return hsb.z * mix(K_HSB2RGB.xxx, clamp(p - K_HSB2RGB.xxx, 0.0, 1.0), hsb.y);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_HSLToRGB = "vec3 hueToRGB(float hue)\n\
{\n\
float r = abs(hue * 6.0 - 3.0) - 1.0;\n\
float g = 2.0 - abs(hue * 6.0 - 2.0);\n\
float b = 2.0 - abs(hue * 6.0 - 4.0);\n\
return clamp(vec3(r, g, b), 0.0, 1.0);\n\
}\n\
vec3 czm_HSLToRGB(vec3 hsl)\n\
{\n\
vec3 rgb = hueToRGB(hsl.x);\n\
float c = (1.0 - abs(2.0 * hsl.z - 1.0)) * hsl.y;\n\
return (rgb - 0.5) * c + hsl.z;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_RGBToHSB = "const vec4 K_RGB2HSB = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);\n\
vec3 czm_RGBToHSB(vec3 rgb)\n\
{\n\
vec4 p = mix(vec4(rgb.bg, K_RGB2HSB.wz), vec4(rgb.gb, K_RGB2HSB.xy), step(rgb.b, rgb.g));\n\
vec4 q = mix(vec4(p.xyw, rgb.r), vec4(rgb.r, p.yzx), step(p.x, rgb.r));\n\
float d = q.x - min(q.w, q.y);\n\
return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + czm_epsilon7)), d / (q.x + czm_epsilon7), q.x);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_RGBToHSL = "vec3 RGBtoHCV(vec3 rgb)\n\
{\n\
vec4 p = (rgb.g < rgb.b) ? vec4(rgb.bg, -1.0, 2.0 / 3.0) : vec4(rgb.gb, 0.0, -1.0 / 3.0);\n\
vec4 q = (rgb.r < p.x) ? vec4(p.xyw, rgb.r) : vec4(rgb.r, p.yzx);\n\
float c = q.x - min(q.w, q.y);\n\
float h = abs((q.w - q.y) / (6.0 * c + czm_epsilon7) + q.z);\n\
return vec3(h, c, q.x);\n\
}\n\
vec3 czm_RGBToHSL(vec3 rgb)\n\
{\n\
vec3 hcv = RGBtoHCV(rgb);\n\
float l = hcv.z - hcv.y * 0.5;\n\
float s = hcv.y / (1.0 - abs(l * 2.0 - 1.0) + czm_epsilon7);\n\
return vec3(hcv.x, s, l);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_RGBToXYZ = "vec3 czm_RGBToXYZ(vec3 rgb)\n\
{\n\
const mat3 RGB2XYZ = mat3(0.4124, 0.2126, 0.0193,\n\
0.3576, 0.7152, 0.1192,\n\
0.1805, 0.0722, 0.9505);\n\
vec3 xyz = RGB2XYZ * rgb;\n\
vec3 Yxy;\n\
Yxy.r = xyz.g;\n\
float temp = dot(vec3(1.0), xyz);\n\
Yxy.gb = xyz.rg / temp;\n\
return Yxy;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_XYZToRGB = "vec3 czm_XYZToRGB(vec3 Yxy)\n\
{\n\
const mat3 XYZ2RGB = mat3( 3.2405, -0.9693,  0.0556,\n\
-1.5371,  1.8760, -0.2040,\n\
-0.4985,  0.0416,  1.0572);\n\
vec3 xyz;\n\
xyz.r = Yxy.r * Yxy.g / Yxy.b;\n\
xyz.g = Yxy.r;\n\
xyz.b = Yxy.r * (1.0 - Yxy.g - Yxy.b) / Yxy.b;\n\
return XYZ2RGB * xyz;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_acesTonemapping = "vec3 czm_acesTonemapping(vec3 color) {\n\
float g = 0.985;\n\
float a = 0.065;\n\
float b = 0.0001;\n\
float c = 0.433;\n\
float d = 0.238;\n\
color = (color * (color + a) - b) / (color * (g * color + c) + d);\n\
color = clamp(color, 0.0, 1.0);\n\
return color;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_alphaWeight = "float czm_alphaWeight(float a)\n\
{\n\
float z = (gl_FragCoord.z - czm_viewportTransformation[3][2]) / czm_viewportTransformation[2][2];\n\
return pow(a + 0.01, 4.0) + max(1e-2, min(3.0 * 1e3, 0.003 / (1e-5 + pow(abs(z) / 200.0, 4.0))));\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_antialias = "vec4 czm_antialias(vec4 color1, vec4 color2, vec4 currentColor, float dist, float fuzzFactor)\n\
{\n\
float val1 = clamp(dist / fuzzFactor, 0.0, 1.0);\n\
float val2 = clamp((dist - 0.5) / fuzzFactor, 0.0, 1.0);\n\
val1 = val1 * (1.0 - val2);\n\
val1 = val1 * val1 * (3.0 - (2.0 * val1));\n\
val1 = pow(val1, 0.5);\n\
vec4 midColor = (color1 + color2) * 0.5;\n\
return mix(midColor, currentColor, val1);\n\
}\n\
vec4 czm_antialias(vec4 color1, vec4 color2, vec4 currentColor, float dist)\n\
{\n\
return czm_antialias(color1, color2, currentColor, dist, 0.1);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_approximateSphericalCoordinates = "vec2 czm_approximateSphericalCoordinates(vec3 normal) {\n\
float latitudeApproximation = czm_fastApproximateAtan(sqrt(normal.x * normal.x + normal.y * normal.y), normal.z);\n\
float longitudeApproximation = czm_fastApproximateAtan(normal.x, normal.y);\n\
return vec2(latitudeApproximation, longitudeApproximation);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_backFacing = "bool czm_backFacing()\n\
{\n\
return gl_FrontFacing == false;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_branchFreeTernary = "float czm_branchFreeTernary(bool comparison, float a, float b) {\n\
float useA = float(comparison);\n\
return a * useA + b * (1.0 - useA);\n\
}\n\
vec2 czm_branchFreeTernary(bool comparison, vec2 a, vec2 b) {\n\
float useA = float(comparison);\n\
return a * useA + b * (1.0 - useA);\n\
}\n\
vec3 czm_branchFreeTernary(bool comparison, vec3 a, vec3 b) {\n\
float useA = float(comparison);\n\
return a * useA + b * (1.0 - useA);\n\
}\n\
vec4 czm_branchFreeTernary(bool comparison, vec4 a, vec4 b) {\n\
float useA = float(comparison);\n\
return a * useA + b * (1.0 - useA);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_cascadeColor = "vec4 czm_cascadeColor(vec4 weights)\n\
{\n\
return vec4(1.0, 0.0, 0.0, 1.0) * weights.x +\n\
vec4(0.0, 1.0, 0.0, 1.0) * weights.y +\n\
vec4(0.0, 0.0, 1.0, 1.0) * weights.z +\n\
vec4(1.0, 0.0, 1.0, 1.0) * weights.w;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_cascadeDistance = "uniform vec4 shadowMap_cascadeDistances;\n\
float czm_cascadeDistance(vec4 weights)\n\
{\n\
return dot(shadowMap_cascadeDistances, weights);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_cascadeMatrix = "uniform mat4 shadowMap_cascadeMatrices[4];\n\
mat4 czm_cascadeMatrix(vec4 weights)\n\
{\n\
return shadowMap_cascadeMatrices[0] * weights.x +\n\
shadowMap_cascadeMatrices[1] * weights.y +\n\
shadowMap_cascadeMatrices[2] * weights.z +\n\
shadowMap_cascadeMatrices[3] * weights.w;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_cascadeWeights = "uniform vec4 shadowMap_cascadeSplits[2];\n\
vec4 czm_cascadeWeights(float depthEye)\n\
{\n\
vec4 near = step(shadowMap_cascadeSplits[0], vec4(depthEye));\n\
vec4 far = step(depthEye, shadowMap_cascadeSplits[1]);\n\
return near * far;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_columbusViewMorph = "vec4 czm_columbusViewMorph(vec4 position2D, vec4 position3D, float time)\n\
{\n\
vec3 p = mix(position2D.xyz, position3D.xyz, time);\n\
return vec4(p, 1.0);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_computePosition = "vec4 czm_computePosition();\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_cosineAndSine = "vec2 cordic(float angle)\n\
{\n\
vec2 vector = vec2(6.0725293500888267e-1, 0.0);\n\
float sense = (angle < 0.0) ? -1.0 : 1.0;\n\
mat2 rotation = mat2(1.0, sense, -sense, 1.0);\n\
vector = rotation * vector;\n\
angle -= sense * 7.8539816339744828e-1;\n\
sense = (angle < 0.0) ? -1.0 : 1.0;\n\
float factor = sense * 5.0e-1;\n\
rotation[0][1] = factor;\n\
rotation[1][0] = -factor;\n\
vector = rotation * vector;\n\
angle -= sense * 4.6364760900080609e-1;\n\
sense = (angle < 0.0) ? -1.0 : 1.0;\n\
factor = sense * 2.5e-1;\n\
rotation[0][1] = factor;\n\
rotation[1][0] = -factor;\n\
vector = rotation * vector;\n\
angle -= sense * 2.4497866312686414e-1;\n\
sense = (angle < 0.0) ? -1.0 : 1.0;\n\
factor = sense * 1.25e-1;\n\
rotation[0][1] = factor;\n\
rotation[1][0] = -factor;\n\
vector = rotation * vector;\n\
angle -= sense * 1.2435499454676144e-1;\n\
sense = (angle < 0.0) ? -1.0 : 1.0;\n\
factor = sense * 6.25e-2;\n\
rotation[0][1] = factor;\n\
rotation[1][0] = -factor;\n\
vector = rotation * vector;\n\
angle -= sense * 6.2418809995957350e-2;\n\
sense = (angle < 0.0) ? -1.0 : 1.0;\n\
factor = sense * 3.125e-2;\n\
rotation[0][1] = factor;\n\
rotation[1][0] = -factor;\n\
vector = rotation * vector;\n\
angle -= sense * 3.1239833430268277e-2;\n\
sense = (angle < 0.0) ? -1.0 : 1.0;\n\
factor = sense * 1.5625e-2;\n\
rotation[0][1] = factor;\n\
rotation[1][0] = -factor;\n\
vector = rotation * vector;\n\
angle -= sense * 1.5623728620476831e-2;\n\
sense = (angle < 0.0) ? -1.0 : 1.0;\n\
factor = sense * 7.8125e-3;\n\
rotation[0][1] = factor;\n\
rotation[1][0] = -factor;\n\
vector = rotation * vector;\n\
angle -= sense * 7.8123410601011111e-3;\n\
sense = (angle < 0.0) ? -1.0 : 1.0;\n\
factor = sense * 3.90625e-3;\n\
rotation[0][1] = factor;\n\
rotation[1][0] = -factor;\n\
vector = rotation * vector;\n\
angle -= sense * 3.9062301319669718e-3;\n\
sense = (angle < 0.0) ? -1.0 : 1.0;\n\
factor = sense * 1.953125e-3;\n\
rotation[0][1] = factor;\n\
rotation[1][0] = -factor;\n\
vector = rotation * vector;\n\
angle -= sense * 1.9531225164788188e-3;\n\
sense = (angle < 0.0) ? -1.0 : 1.0;\n\
factor = sense * 9.765625e-4;\n\
rotation[0][1] = factor;\n\
rotation[1][0] = -factor;\n\
vector = rotation * vector;\n\
angle -= sense * 9.7656218955931946e-4;\n\
sense = (angle < 0.0) ? -1.0 : 1.0;\n\
factor = sense * 4.8828125e-4;\n\
rotation[0][1] = factor;\n\
rotation[1][0] = -factor;\n\
vector = rotation * vector;\n\
angle -= sense * 4.8828121119489829e-4;\n\
sense = (angle < 0.0) ? -1.0 : 1.0;\n\
factor = sense * 2.44140625e-4;\n\
rotation[0][1] = factor;\n\
rotation[1][0] = -factor;\n\
vector = rotation * vector;\n\
angle -= sense * 2.4414062014936177e-4;\n\
sense = (angle < 0.0) ? -1.0 : 1.0;\n\
factor = sense * 1.220703125e-4;\n\
rotation[0][1] = factor;\n\
rotation[1][0] = -factor;\n\
vector = rotation * vector;\n\
angle -= sense * 1.2207031189367021e-4;\n\
sense = (angle < 0.0) ? -1.0 : 1.0;\n\
factor = sense * 6.103515625e-5;\n\
rotation[0][1] = factor;\n\
rotation[1][0] = -factor;\n\
vector = rotation * vector;\n\
angle -= sense * 6.1035156174208773e-5;\n\
sense = (angle < 0.0) ? -1.0 : 1.0;\n\
factor = sense * 3.0517578125e-5;\n\
rotation[0][1] = factor;\n\
rotation[1][0] = -factor;\n\
vector = rotation * vector;\n\
angle -= sense * 3.0517578115526096e-5;\n\
sense = (angle < 0.0) ? -1.0 : 1.0;\n\
factor = sense * 1.52587890625e-5;\n\
rotation[0][1] = factor;\n\
rotation[1][0] = -factor;\n\
vector = rotation * vector;\n\
angle -= sense * 1.5258789061315762e-5;\n\
sense = (angle < 0.0) ? -1.0 : 1.0;\n\
factor = sense * 7.62939453125e-6;\n\
rotation[0][1] = factor;\n\
rotation[1][0] = -factor;\n\
vector = rotation * vector;\n\
angle -= sense * 7.6293945311019700e-6;\n\
sense = (angle < 0.0) ? -1.0 : 1.0;\n\
factor = sense * 3.814697265625e-6;\n\
rotation[0][1] = factor;\n\
rotation[1][0] = -factor;\n\
vector = rotation * vector;\n\
angle -= sense * 3.8146972656064961e-6;\n\
sense = (angle < 0.0) ? -1.0 : 1.0;\n\
factor = sense * 1.9073486328125e-6;\n\
rotation[0][1] = factor;\n\
rotation[1][0] = -factor;\n\
vector = rotation * vector;\n\
angle -= sense * 1.9073486328101870e-6;\n\
sense = (angle < 0.0) ? -1.0 : 1.0;\n\
factor = sense * 9.5367431640625e-7;\n\
rotation[0][1] = factor;\n\
rotation[1][0] = -factor;\n\
vector = rotation * vector;\n\
angle -= sense * 9.5367431640596084e-7;\n\
sense = (angle < 0.0) ? -1.0 : 1.0;\n\
factor = sense * 4.76837158203125e-7;\n\
rotation[0][1] = factor;\n\
rotation[1][0] = -factor;\n\
vector = rotation * vector;\n\
angle -= sense * 4.7683715820308884e-7;\n\
sense = (angle < 0.0) ? -1.0 : 1.0;\n\
factor = sense * 2.384185791015625e-7;\n\
rotation[0][1] = factor;\n\
rotation[1][0] = -factor;\n\
vector = rotation * vector;\n\
angle -= sense * 2.3841857910155797e-7;\n\
sense = (angle < 0.0) ? -1.0 : 1.0;\n\
factor = sense * 1.1920928955078125e-7;\n\
rotation[0][1] = factor;\n\
rotation[1][0] = -factor;\n\
vector = rotation * vector;\n\
return vector;\n\
}\n\
vec2 czm_cosineAndSine(float angle)\n\
{\n\
if (angle < -czm_piOverTwo || angle > czm_piOverTwo)\n\
{\n\
if (angle < 0.0)\n\
{\n\
return -cordic(angle + czm_pi);\n\
}\n\
else\n\
{\n\
return -cordic(angle - czm_pi);\n\
}\n\
}\n\
else\n\
{\n\
return cordic(angle);\n\
}\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_decompressTextureCoordinates = "vec2 czm_decompressTextureCoordinates(float encoded)\n\
{\n\
float temp = encoded / 4096.0;\n\
float xZeroTo4095 = floor(temp);\n\
float stx = xZeroTo4095 / 4095.0;\n\
float sty = (encoded - xZeroTo4095 * 4096.0) / 4095.0;\n\
return vec2(stx, sty);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_defaultPbrMaterial = "czm_pbrParameters czm_defaultPbrMaterial()\n\
{\n\
czm_pbrParameters results;\n\
results.diffuseColor = vec3(1.0);\n\
results.roughness = 1.0;\n\
const vec3 REFLECTANCE_DIELECTRIC = vec3(0.04);\n\
results.f0 = REFLECTANCE_DIELECTRIC;\n\
return results;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_depthClamp = "#if defined(GL_EXT_frag_depth) && !defined(LOG_DEPTH)\n\
varying float v_WindowZ;\n\
#endif\n\
vec4 czm_depthClamp(vec4 coords)\n\
{\n\
#ifndef LOG_DEPTH\n\
#ifdef GL_EXT_frag_depth\n\
v_WindowZ = (0.5 * (coords.z / coords.w) + 0.5) * coords.w;\n\
coords.z = 0.0;\n\
#else\n\
coords.z = min(coords.z, coords.w);\n\
#endif\n\
#endif\n\
return coords;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_eastNorthUpToEyeCoordinates = "mat3 czm_eastNorthUpToEyeCoordinates(vec3 positionMC, vec3 normalEC)\n\
{\n\
vec3 tangentMC = normalize(vec3(-positionMC.y, positionMC.x, 0.0));\n\
vec3 tangentEC = normalize(czm_normal3D * tangentMC);\n\
vec3 bitangentEC = normalize(cross(normalEC, tangentEC));\n\
return mat3(\n\
tangentEC.x,   tangentEC.y,   tangentEC.z,\n\
bitangentEC.x, bitangentEC.y, bitangentEC.z,\n\
normalEC.x,    normalEC.y,    normalEC.z);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_ellipsoidContainsPoint = "bool czm_ellipsoidContainsPoint(vec3 ellipsoid_inverseRadii, vec3 point)\n\
{\n\
vec3 scaled = ellipsoid_inverseRadii * (czm_inverseModelView * vec4(point, 1.0)).xyz;\n\
return (dot(scaled, scaled) <= 1.0);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_ellipsoidWgs84TextureCoordinates = "vec2 czm_ellipsoidWgs84TextureCoordinates(vec3 normal)\n\
{\n\
return vec2(atan(normal.y, normal.x) * czm_oneOverTwoPi + 0.5, asin(normal.z) * czm_oneOverPi + 0.5);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_equalsEpsilon = "bool czm_equalsEpsilon(vec4 left, vec4 right, float epsilon) {\n\
return all(lessThanEqual(abs(left - right), vec4(epsilon)));\n\
}\n\
bool czm_equalsEpsilon(vec3 left, vec3 right, float epsilon) {\n\
return all(lessThanEqual(abs(left - right), vec3(epsilon)));\n\
}\n\
bool czm_equalsEpsilon(vec2 left, vec2 right, float epsilon) {\n\
return all(lessThanEqual(abs(left - right), vec2(epsilon)));\n\
}\n\
bool czm_equalsEpsilon(float left, float right, float epsilon) {\n\
return (abs(left - right) <= epsilon);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_eyeOffset = "vec4 czm_eyeOffset(vec4 positionEC, vec3 eyeOffset)\n\
{\n\
vec4 p = positionEC;\n\
vec4 zEyeOffset = normalize(p) * eyeOffset.z;\n\
p.xy += eyeOffset.xy + zEyeOffset.xy;\n\
p.z += zEyeOffset.z;\n\
return p;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_eyeToWindowCoordinates = "vec4 czm_eyeToWindowCoordinates(vec4 positionEC)\n\
{\n\
vec4 q = czm_projection * positionEC;\n\
q.xyz /= q.w;\n\
q.xyz = (czm_viewportTransformation * vec4(q.xyz, 1.0)).xyz;\n\
return q;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_fastApproximateAtan = "float czm_fastApproximateAtan(float x) {\n\
return x * (-0.1784 * x - 0.0663 * x * x + 1.0301);\n\
}\n\
float czm_fastApproximateAtan(float x, float y) {\n\
float t = abs(x);\n\
float opposite = abs(y);\n\
float adjacent = max(t, opposite);\n\
opposite = min(t, opposite);\n\
t = czm_fastApproximateAtan(opposite / adjacent);\n\
t = czm_branchFreeTernary(abs(y) > abs(x), czm_piOverTwo - t, t);\n\
t = czm_branchFreeTernary(x < 0.0, czm_pi - t, t);\n\
t = czm_branchFreeTernary(y < 0.0, -t, t);\n\
return t;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_fog = "vec3 czm_fog(float distanceToCamera, vec3 color, vec3 fogColor)\n\
{\n\
float scalar = distanceToCamera * czm_fogDensity;\n\
float fog = 1.0 - exp(-(scalar * scalar));\n\
return mix(color, fogColor, fog);\n\
}\n\
vec3 czm_fog(float distanceToCamera, vec3 color, vec3 fogColor, float fogModifierConstant)\n\
{\n\
float scalar = distanceToCamera * czm_fogDensity;\n\
float fog = 1.0 - exp(-((fogModifierConstant * scalar + fogModifierConstant) * (scalar * (1.0 + fogModifierConstant))));\n\
return mix(color, fogColor, fog);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_gammaCorrect = "vec3 czm_gammaCorrect(vec3 color) {\n\
#ifdef HDR\n\
color = pow(color, vec3(czm_gamma));\n\
#endif\n\
return color;\n\
}\n\
vec4 czm_gammaCorrect(vec4 color) {\n\
#ifdef HDR\n\
color.rgb = pow(color.rgb, vec3(czm_gamma));\n\
#endif\n\
return color;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_geodeticSurfaceNormal = "vec3 czm_geodeticSurfaceNormal(vec3 positionOnEllipsoid, vec3 ellipsoidCenter, vec3 oneOverEllipsoidRadiiSquared)\n\
{\n\
return normalize((positionOnEllipsoid - ellipsoidCenter) * oneOverEllipsoidRadiiSquared);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_getDefaultMaterial = "czm_material czm_getDefaultMaterial(czm_materialInput materialInput)\n\
{\n\
czm_material material;\n\
material.diffuse = vec3(0.0);\n\
material.specular = 0.0;\n\
material.shininess = 1.0;\n\
material.normal = materialInput.normalEC;\n\
material.emission = vec3(0.0);\n\
material.alpha = 1.0;\n\
return material;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_getLambertDiffuse = "float czm_getLambertDiffuse(vec3 lightDirectionEC, vec3 normalEC)\n\
{\n\
return max(dot(lightDirectionEC, normalEC), 0.0);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_getSpecular = "float czm_getSpecular(vec3 lightDirectionEC, vec3 toEyeEC, vec3 normalEC, float shininess)\n\
{\n\
vec3 toReflectedLight = reflect(-lightDirectionEC, normalEC);\n\
float specular = max(dot(toReflectedLight, toEyeEC), 0.0);\n\
return pow(specular, max(shininess, czm_epsilon2));\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_getWaterNoise = "vec4 czm_getWaterNoise(sampler2D normalMap, vec2 uv, float time, float angleInRadians)\n\
{\n\
float cosAngle = cos(angleInRadians);\n\
float sinAngle = sin(angleInRadians);\n\
vec2 s0 = vec2(1.0/17.0, 0.0);\n\
vec2 s1 = vec2(-1.0/29.0, 0.0);\n\
vec2 s2 = vec2(1.0/101.0, 1.0/59.0);\n\
vec2 s3 = vec2(-1.0/109.0, -1.0/57.0);\n\
s0 = vec2((cosAngle * s0.x) - (sinAngle * s0.y), (sinAngle * s0.x) + (cosAngle * s0.y));\n\
s1 = vec2((cosAngle * s1.x) - (sinAngle * s1.y), (sinAngle * s1.x) + (cosAngle * s1.y));\n\
s2 = vec2((cosAngle * s2.x) - (sinAngle * s2.y), (sinAngle * s2.x) + (cosAngle * s2.y));\n\
s3 = vec2((cosAngle * s3.x) - (sinAngle * s3.y), (sinAngle * s3.x) + (cosAngle * s3.y));\n\
vec2 uv0 = (uv/103.0) + (time * s0);\n\
vec2 uv1 = uv/107.0 + (time * s1) + vec2(0.23);\n\
vec2 uv2 = uv/vec2(897.0, 983.0) + (time * s2) + vec2(0.51);\n\
vec2 uv3 = uv/vec2(991.0, 877.0) + (time * s3) + vec2(0.71);\n\
uv0 = fract(uv0);\n\
uv1 = fract(uv1);\n\
uv2 = fract(uv2);\n\
uv3 = fract(uv3);\n\
vec4 noise = (texture2D(normalMap, uv0)) +\n\
(texture2D(normalMap, uv1)) +\n\
(texture2D(normalMap, uv2)) +\n\
(texture2D(normalMap, uv3));\n\
return ((noise / 4.0) - 0.5) * 2.0;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_hue = "vec3 czm_hue(vec3 rgb, float adjustment)\n\
{\n\
const mat3 toYIQ = mat3(0.299,     0.587,     0.114,\n\
0.595716, -0.274453, -0.321263,\n\
0.211456, -0.522591,  0.311135);\n\
const mat3 toRGB = mat3(1.0,  0.9563,  0.6210,\n\
1.0, -0.2721, -0.6474,\n\
1.0, -1.107,   1.7046);\n\
vec3 yiq = toYIQ * rgb;\n\
float hue = atan(yiq.z, yiq.y) + adjustment;\n\
float chroma = sqrt(yiq.z * yiq.z + yiq.y * yiq.y);\n\
vec3 color = vec3(yiq.x, chroma * cos(hue), chroma * sin(hue));\n\
return toRGB * color;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_inverseGamma = "vec3 czm_inverseGamma(vec3 color) {\n\
return pow(color, vec3(1.0 / czm_gamma));\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_isEmpty = "bool czm_isEmpty(czm_raySegment interval)\n\
{\n\
return (interval.stop < 0.0);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_isFull = "bool czm_isFull(czm_raySegment interval)\n\
{\n\
return (interval.start == 0.0 && interval.stop == czm_infinity);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_latitudeToWebMercatorFraction = "float czm_latitudeToWebMercatorFraction(float latitude, float southMercatorY, float oneOverMercatorHeight)\n\
{\n\
float sinLatitude = sin(latitude);\n\
float mercatorY = 0.5 * log((1.0 + sinLatitude) / (1.0 - sinLatitude));\n\
return (mercatorY - southMercatorY) * oneOverMercatorHeight;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_lineDistance = "float czm_lineDistance(vec2 point1, vec2 point2, vec2 point) {\n\
return abs((point2.y - point1.y) * point.x - (point2.x - point1.x) * point.y + point2.x * point1.y - point2.y * point1.x) / distance(point2, point1);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_linearToSrgb = "vec3 czm_linearToSrgb(vec3 linearIn)\n\
{\n\
return pow(linearIn, vec3(1.0/2.2));\n\
}\n\
vec4 czm_linearToSrgb(vec4 linearIn)\n\
{\n\
vec3 srgbOut = pow(linearIn.rgb, vec3(1.0/2.2));\n\
return vec4(srgbOut, linearIn.a);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_luminance = "float czm_luminance(vec3 rgb)\n\
{\n\
const vec3 W = vec3(0.2125, 0.7154, 0.0721);\n\
return dot(rgb, W);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_metersPerPixel = "float czm_metersPerPixel(vec4 positionEC, float pixelRatio)\n\
{\n\
float width = czm_viewport.z;\n\
float height = czm_viewport.w;\n\
float pixelWidth;\n\
float pixelHeight;\n\
float top = czm_frustumPlanes.x;\n\
float bottom = czm_frustumPlanes.y;\n\
float left = czm_frustumPlanes.z;\n\
float right = czm_frustumPlanes.w;\n\
if (czm_sceneMode == czm_sceneMode2D || czm_orthographicIn3D == 1.0)\n\
{\n\
float frustumWidth = right - left;\n\
float frustumHeight = top - bottom;\n\
pixelWidth = frustumWidth / width;\n\
pixelHeight = frustumHeight / height;\n\
}\n\
else\n\
{\n\
float distanceToPixel = -positionEC.z;\n\
float inverseNear = 1.0 / czm_currentFrustum.x;\n\
float tanTheta = top * inverseNear;\n\
pixelHeight = 2.0 * distanceToPixel * tanTheta / height;\n\
tanTheta = right * inverseNear;\n\
pixelWidth = 2.0 * distanceToPixel * tanTheta / width;\n\
}\n\
return max(pixelWidth, pixelHeight) * pixelRatio;\n\
}\n\
float czm_metersPerPixel(vec4 positionEC)\n\
{\n\
return czm_metersPerPixel(positionEC, czm_pixelRatio);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_modelToWindowCoordinates = "vec4 czm_modelToWindowCoordinates(vec4 position)\n\
{\n\
vec4 q = czm_modelViewProjection * position;\n\
q.xyz /= q.w;\n\
q.xyz = (czm_viewportTransformation * vec4(q.xyz, 1.0)).xyz;\n\
return q;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_multiplyWithColorBalance = "vec3 czm_multiplyWithColorBalance(vec3 left, vec3 right)\n\
{\n\
const vec3 W = vec3(0.2125, 0.7154, 0.0721);\n\
vec3 target = left * right;\n\
float leftLuminance = dot(left, W);\n\
float rightLuminance = dot(right, W);\n\
float targetLuminance = dot(target, W);\n\
return ((leftLuminance + rightLuminance) / (2.0 * targetLuminance)) * target;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_nearFarScalar = "float czm_nearFarScalar(vec4 nearFarScalar, float cameraDistSq)\n\
{\n\
float valueAtMin = nearFarScalar.y;\n\
float valueAtMax = nearFarScalar.w;\n\
float nearDistanceSq = nearFarScalar.x * nearFarScalar.x;\n\
float farDistanceSq = nearFarScalar.z * nearFarScalar.z;\n\
float t = (cameraDistSq - nearDistanceSq) / (farDistanceSq - nearDistanceSq);\n\
t = pow(clamp(t, 0.0, 1.0), 0.2);\n\
return mix(valueAtMin, valueAtMax, t);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_octDecode = "vec3 czm_octDecode(vec2 encoded, float range)\n\
{\n\
if (encoded.x == 0.0 && encoded.y == 0.0) {\n\
return vec3(0.0, 0.0, 0.0);\n\
}\n\
encoded = encoded / range * 2.0 - 1.0;\n\
vec3 v = vec3(encoded.x, encoded.y, 1.0 - abs(encoded.x) - abs(encoded.y));\n\
if (v.z < 0.0)\n\
{\n\
v.xy = (1.0 - abs(v.yx)) * czm_signNotZero(v.xy);\n\
}\n\
return normalize(v);\n\
}\n\
vec3 czm_octDecode(vec2 encoded)\n\
{\n\
return czm_octDecode(encoded, 255.0);\n\
}\n\
vec3 czm_octDecode(float encoded)\n\
{\n\
float temp = encoded / 256.0;\n\
float x = floor(temp);\n\
float y = (temp - x) * 256.0;\n\
return czm_octDecode(vec2(x, y));\n\
}\n\
void czm_octDecode(vec2 encoded, out vec3 vector1, out vec3 vector2, out vec3 vector3)\n\
{\n\
float temp = encoded.x / 65536.0;\n\
float x = floor(temp);\n\
float encodedFloat1 = (temp - x) * 65536.0;\n\
temp = encoded.y / 65536.0;\n\
float y = floor(temp);\n\
float encodedFloat2 = (temp - y) * 65536.0;\n\
vector1 = czm_octDecode(encodedFloat1);\n\
vector2 = czm_octDecode(encodedFloat2);\n\
vector3 = czm_octDecode(vec2(x, y));\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_packDepth = "vec4 czm_packDepth(float depth)\n\
{\n\
vec4 enc = vec4(1.0, 255.0, 65025.0, 16581375.0) * depth;\n\
enc = fract(enc);\n\
enc -= enc.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);\n\
return enc;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_pbrLighting = "vec3 lambertianDiffuse(vec3 diffuseColor)\n\
{\n\
return diffuseColor / czm_pi;\n\
}\n\
vec3 fresnelSchlick2(vec3 f0, vec3 f90, float VdotH)\n\
{\n\
return f0 + (f90 - f0) * pow(clamp(1.0 - VdotH, 0.0, 1.0), 5.0);\n\
}\n\
float smithVisibilityG1(float NdotV, float roughness)\n\
{\n\
float k = (roughness + 1.0) * (roughness + 1.0) / 8.0;\n\
return NdotV / (NdotV * (1.0 - k) + k);\n\
}\n\
float smithVisibilityGGX(float roughness, float NdotL, float NdotV)\n\
{\n\
return (\n\
smithVisibilityG1(NdotL, roughness) *\n\
smithVisibilityG1(NdotV, roughness)\n\
);\n\
}\n\
float GGX(float roughness, float NdotH)\n\
{\n\
float roughnessSquared = roughness * roughness;\n\
float f = (NdotH * roughnessSquared - NdotH) * NdotH + 1.0;\n\
return roughnessSquared / (czm_pi * f * f);\n\
}\n\
vec3 czm_pbrLighting(\n\
vec3 positionEC,\n\
vec3 normalEC,\n\
vec3 lightDirectionEC,\n\
vec3 lightColorHdr,\n\
czm_pbrParameters pbrParameters\n\
)\n\
{\n\
vec3 v = -normalize(positionEC);\n\
vec3 l = normalize(lightDirectionEC);\n\
vec3 h = normalize(v + l);\n\
vec3 n = normalEC;\n\
float NdotL = clamp(dot(n, l), 0.001, 1.0);\n\
float NdotV = abs(dot(n, v)) + 0.001;\n\
float NdotH = clamp(dot(n, h), 0.0, 1.0);\n\
float LdotH = clamp(dot(l, h), 0.0, 1.0);\n\
float VdotH = clamp(dot(v, h), 0.0, 1.0);\n\
vec3 f0 = pbrParameters.f0;\n\
float reflectance = max(max(f0.r, f0.g), f0.b);\n\
vec3 f90 = vec3(clamp(reflectance * 25.0, 0.0, 1.0));\n\
vec3 F = fresnelSchlick2(f0, f90, VdotH);\n\
float alpha = pbrParameters.roughness;\n\
float G = smithVisibilityGGX(alpha, NdotL, NdotV);\n\
float D = GGX(alpha, NdotH);\n\
vec3 specularContribution = F * G * D / (4.0 * NdotL * NdotV);\n\
vec3 diffuseColor = pbrParameters.diffuseColor;\n\
vec3 diffuseContribution = (1.0 - F) * lambertianDiffuse(diffuseColor);\n\
return (diffuseContribution + specularContribution) * NdotL * lightColorHdr;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_pbrMetallicRoughnessMaterial = "czm_pbrParameters czm_pbrMetallicRoughnessMaterial(\n\
vec3 baseColor,\n\
float metallic,\n\
float roughness\n\
)\n\
{\n\
czm_pbrParameters results;\n\
roughness = clamp(roughness, 0.0, 1.0);\n\
results.roughness = roughness * roughness;\n\
metallic = clamp(metallic, 0.0, 1.0);\n\
const vec3 REFLECTANCE_DIELECTRIC = vec3(0.04);\n\
vec3 f0 = mix(REFLECTANCE_DIELECTRIC, baseColor, metallic);\n\
results.f0 = f0;\n\
results.diffuseColor = baseColor * (1.0 - f0) * (1.0 - metallic);\n\
return results;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_pbrSpecularGlossinessMaterial = "czm_pbrParameters czm_pbrSpecularGlossinessMaterial(\n\
vec3 diffuse,\n\
vec3 specular,\n\
float glossiness\n\
)\n\
{\n\
czm_pbrParameters results;\n\
float roughness = 1.0 - glossiness;\n\
results.roughness = roughness * roughness;\n\
results.diffuseColor = diffuse * (1.0 - max(max(specular.r, specular.g), specular.b));\n\
results.f0 = specular;\n\
return results;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_phong = "float czm_private_getLambertDiffuseOfMaterial(vec3 lightDirectionEC, czm_material material)\n\
{\n\
return czm_getLambertDiffuse(lightDirectionEC, material.normal);\n\
}\n\
float czm_private_getSpecularOfMaterial(vec3 lightDirectionEC, vec3 toEyeEC, czm_material material)\n\
{\n\
return czm_getSpecular(lightDirectionEC, toEyeEC, material.normal, material.shininess);\n\
}\n\
vec4 czm_phong(vec3 toEye, czm_material material, vec3 lightDirectionEC)\n\
{\n\
float diffuse = czm_private_getLambertDiffuseOfMaterial(vec3(0.0, 0.0, 1.0), material);\n\
if (czm_sceneMode == czm_sceneMode3D) {\n\
diffuse += czm_private_getLambertDiffuseOfMaterial(vec3(0.0, 1.0, 0.0), material);\n\
}\n\
float specular = czm_private_getSpecularOfMaterial(lightDirectionEC, toEye, material);\n\
vec3 materialDiffuse = material.diffuse * 0.5;\n\
vec3 ambient = materialDiffuse;\n\
vec3 color = ambient + material.emission;\n\
color += materialDiffuse * diffuse * czm_lightColor;\n\
color += material.specular * specular * czm_lightColor;\n\
return vec4(color, material.alpha);\n\
}\n\
vec4 czm_private_phong(vec3 toEye, czm_material material, vec3 lightDirectionEC)\n\
{\n\
float diffuse = czm_private_getLambertDiffuseOfMaterial(lightDirectionEC, material);\n\
float specular = czm_private_getSpecularOfMaterial(lightDirectionEC, toEye, material);\n\
vec3 ambient = vec3(0.0);\n\
vec3 color = ambient + material.emission;\n\
color += material.diffuse * diffuse * czm_lightColor;\n\
color += material.specular * specular * czm_lightColor;\n\
return vec4(color, material.alpha);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_planeDistance = "float czm_planeDistance(vec4 plane, vec3 point) {\n\
return (dot(plane.xyz, point) + plane.w);\n\
}\n\
float czm_planeDistance(vec3 planeNormal, float planeDistance, vec3 point) {\n\
return (dot(planeNormal, point) + planeDistance);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_pointAlongRay = "vec3 czm_pointAlongRay(czm_ray ray, float time)\n\
{\n\
return ray.origin + (time * ray.direction);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_rayEllipsoidIntersectionInterval = "czm_raySegment czm_rayEllipsoidIntersectionInterval(czm_ray ray, vec3 ellipsoid_center, vec3 ellipsoid_inverseRadii)\n\
{\n\
vec3 q = ellipsoid_inverseRadii * (czm_inverseModelView * vec4(ray.origin, 1.0)).xyz;\n\
vec3 w = ellipsoid_inverseRadii * (czm_inverseModelView * vec4(ray.direction, 0.0)).xyz;\n\
q = q - ellipsoid_inverseRadii * (czm_inverseModelView * vec4(ellipsoid_center, 1.0)).xyz;\n\
float q2 = dot(q, q);\n\
float qw = dot(q, w);\n\
if (q2 > 1.0)\n\
{\n\
if (qw >= 0.0)\n\
{\n\
return czm_emptyRaySegment;\n\
}\n\
else\n\
{\n\
float qw2 = qw * qw;\n\
float difference = q2 - 1.0;\n\
float w2 = dot(w, w);\n\
float product = w2 * difference;\n\
if (qw2 < product)\n\
{\n\
return czm_emptyRaySegment;\n\
}\n\
else if (qw2 > product)\n\
{\n\
float discriminant = qw * qw - product;\n\
float temp = -qw + sqrt(discriminant);\n\
float root0 = temp / w2;\n\
float root1 = difference / temp;\n\
if (root0 < root1)\n\
{\n\
czm_raySegment i = czm_raySegment(root0, root1);\n\
return i;\n\
}\n\
else\n\
{\n\
czm_raySegment i = czm_raySegment(root1, root0);\n\
return i;\n\
}\n\
}\n\
else\n\
{\n\
float root = sqrt(difference / w2);\n\
czm_raySegment i = czm_raySegment(root, root);\n\
return i;\n\
}\n\
}\n\
}\n\
else if (q2 < 1.0)\n\
{\n\
float difference = q2 - 1.0;\n\
float w2 = dot(w, w);\n\
float product = w2 * difference;\n\
float discriminant = qw * qw - product;\n\
float temp = -qw + sqrt(discriminant);\n\
czm_raySegment i = czm_raySegment(0.0, temp / w2);\n\
return i;\n\
}\n\
else\n\
{\n\
if (qw < 0.0)\n\
{\n\
float w2 = dot(w, w);\n\
czm_raySegment i = czm_raySegment(0.0, -qw / w2);\n\
return i;\n\
}\n\
else\n\
{\n\
return czm_emptyRaySegment;\n\
}\n\
}\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_raySphereIntersectionInterval = "czm_raySegment czm_raySphereIntersectionInterval(czm_ray ray, vec3 center, float radius)\n\
{\n\
vec3 o = ray.origin;\n\
vec3 d = ray.direction;\n\
vec3 oc = o - center;\n\
float a = dot(d, d);\n\
float b = 2.0 * dot(d, oc);\n\
float c = dot(oc, oc) - (radius * radius);\n\
float det = (b * b) - (4.0 * a * c);\n\
if (det < 0.0) {\n\
return czm_emptyRaySegment;\n\
}\n\
float sqrtDet = sqrt(det);\n\
float t0 = (-b - sqrtDet) / (2.0 * a);\n\
float t1 = (-b + sqrtDet) / (2.0 * a);\n\
czm_raySegment result = czm_raySegment(t0, t1);\n\
return result;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_readDepth = "float czm_readDepth(sampler2D depthTexture, vec2 texCoords)\n\
{\n\
return czm_reverseLogDepth(texture2D(depthTexture, texCoords).r);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_readNonPerspective = "float czm_readNonPerspective(float value, float oneOverW) {\n\
return value * oneOverW;\n\
}\n\
vec2 czm_readNonPerspective(vec2 value, float oneOverW) {\n\
return value * oneOverW;\n\
}\n\
vec3 czm_readNonPerspective(vec3 value, float oneOverW) {\n\
return value * oneOverW;\n\
}\n\
vec4 czm_readNonPerspective(vec4 value, float oneOverW) {\n\
return value * oneOverW;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_reverseLogDepth = "float czm_reverseLogDepth(float logZ)\n\
{\n\
#ifdef LOG_DEPTH\n\
float near = czm_currentFrustum.x;\n\
float far = czm_currentFrustum.y;\n\
float log2Depth = logZ * czm_log2FarDepthFromNearPlusOne;\n\
float depthFromNear = pow(2.0, log2Depth) - 1.0;\n\
return far * (1.0 - near / (depthFromNear + near)) / (far - near);\n\
#endif\n\
return logZ;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_round = "float czm_round(float value) {\n\
return floor(value + 0.5);\n\
}\n\
vec2 czm_round(vec2 value) {\n\
return floor(value + 0.5);\n\
}\n\
vec3 czm_round(vec3 value) {\n\
return floor(value + 0.5);\n\
}\n\
vec4 czm_round(vec4 value) {\n\
return floor(value + 0.5);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_sampleOctahedralProjection = "vec3 czm_sampleOctahedralProjectionWithFiltering(sampler2D projectedMap, vec2 textureSize, vec3 direction, float lod)\n\
{\n\
direction /= dot(vec3(1.0), abs(direction));\n\
vec2 rev = abs(direction.zx) - vec2(1.0);\n\
vec2 neg = vec2(direction.x < 0.0 ? rev.x : -rev.x,\n\
direction.z < 0.0 ? rev.y : -rev.y);\n\
vec2 uv = direction.y < 0.0 ? neg : direction.xz;\n\
vec2 coord = 0.5 * uv + vec2(0.5);\n\
vec2 pixel = 1.0 / textureSize;\n\
if (lod > 0.0)\n\
{\n\
float scale = 1.0 / pow(2.0, lod);\n\
float offset = ((textureSize.y + 1.0) / textureSize.x);\n\
coord.x *= offset;\n\
coord *= scale;\n\
coord.x += offset + pixel.x;\n\
coord.y += (1.0 - (1.0 / pow(2.0, lod - 1.0))) + pixel.y * (lod - 1.0) * 2.0;\n\
}\n\
else\n\
{\n\
coord.x *= (textureSize.y / textureSize.x);\n\
}\n\
#ifndef OES_texture_float_linear\n\
vec3 color1 = texture2D(projectedMap, coord + vec2(0.0, pixel.y)).rgb;\n\
vec3 color2 = texture2D(projectedMap, coord + vec2(pixel.x, 0.0)).rgb;\n\
vec3 color3 = texture2D(projectedMap, coord + pixel).rgb;\n\
vec3 color4 = texture2D(projectedMap, coord).rgb;\n\
vec2 texturePosition = coord * textureSize;\n\
float fu = fract(texturePosition.x);\n\
float fv = fract(texturePosition.y);\n\
vec3 average1 = mix(color4, color2, fu);\n\
vec3 average2 = mix(color1, color3, fu);\n\
vec3 color = mix(average1, average2, fv);\n\
#else\n\
vec3 color = texture2D(projectedMap, coord).rgb;\n\
#endif\n\
return color;\n\
}\n\
vec3 czm_sampleOctahedralProjection(sampler2D projectedMap, vec2 textureSize, vec3 direction, float lod, float maxLod) {\n\
float currentLod = floor(lod + 0.5);\n\
float nextLod = min(currentLod + 1.0, maxLod);\n\
vec3 colorCurrentLod = czm_sampleOctahedralProjectionWithFiltering(projectedMap, textureSize, direction, currentLod);\n\
vec3 colorNextLod = czm_sampleOctahedralProjectionWithFiltering(projectedMap, textureSize, direction, nextLod);\n\
return mix(colorNextLod, colorCurrentLod, nextLod - lod);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_saturation = "vec3 czm_saturation(vec3 rgb, float adjustment)\n\
{\n\
const vec3 W = vec3(0.2125, 0.7154, 0.0721);\n\
vec3 intensity = vec3(dot(rgb, W));\n\
return mix(intensity, rgb, adjustment);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_shadowDepthCompare = "float czm_sampleShadowMap(highp samplerCube shadowMap, vec3 d)\n\
{\n\
return czm_unpackDepth(textureCube(shadowMap, d));\n\
}\n\
float czm_sampleShadowMap(highp sampler2D shadowMap, vec2 uv)\n\
{\n\
#ifdef USE_SHADOW_DEPTH_TEXTURE\n\
return texture2D(shadowMap, uv).r;\n\
#else\n\
return czm_unpackDepth(texture2D(shadowMap, uv));\n\
#endif\n\
}\n\
float czm_shadowDepthCompare(samplerCube shadowMap, vec3 uv, float depth)\n\
{\n\
return step(depth, czm_sampleShadowMap(shadowMap, uv));\n\
}\n\
float czm_shadowDepthCompare(sampler2D shadowMap, vec2 uv, float depth)\n\
{\n\
return step(depth, czm_sampleShadowMap(shadowMap, uv));\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_shadowVisibility = "float czm_private_shadowVisibility(float visibility, float nDotL, float normalShadingSmooth, float darkness)\n\
{\n\
#ifdef USE_NORMAL_SHADING\n\
#ifdef USE_NORMAL_SHADING_SMOOTH\n\
float strength = clamp(nDotL / normalShadingSmooth, 0.0, 1.0);\n\
#else\n\
float strength = step(0.0, nDotL);\n\
#endif\n\
visibility *= strength;\n\
#endif\n\
visibility = max(visibility, darkness);\n\
return visibility;\n\
}\n\
#ifdef USE_CUBE_MAP_SHADOW\n\
float czm_shadowVisibility(samplerCube shadowMap, czm_shadowParameters shadowParameters)\n\
{\n\
float depthBias = shadowParameters.depthBias;\n\
float depth = shadowParameters.depth;\n\
float nDotL = shadowParameters.nDotL;\n\
float normalShadingSmooth = shadowParameters.normalShadingSmooth;\n\
float darkness = shadowParameters.darkness;\n\
vec3 uvw = shadowParameters.texCoords;\n\
depth -= depthBias;\n\
float visibility = czm_shadowDepthCompare(shadowMap, uvw, depth);\n\
return czm_private_shadowVisibility(visibility, nDotL, normalShadingSmooth, darkness);\n\
}\n\
#else\n\
float czm_shadowVisibility(sampler2D shadowMap, czm_shadowParameters shadowParameters)\n\
{\n\
float depthBias = shadowParameters.depthBias;\n\
float depth = shadowParameters.depth;\n\
float nDotL = shadowParameters.nDotL;\n\
float normalShadingSmooth = shadowParameters.normalShadingSmooth;\n\
float darkness = shadowParameters.darkness;\n\
vec2 uv = shadowParameters.texCoords;\n\
depth -= depthBias;\n\
#ifdef USE_SOFT_SHADOWS\n\
vec2 texelStepSize = shadowParameters.texelStepSize;\n\
float radius = 1.0;\n\
float dx0 = -texelStepSize.x * radius;\n\
float dy0 = -texelStepSize.y * radius;\n\
float dx1 = texelStepSize.x * radius;\n\
float dy1 = texelStepSize.y * radius;\n\
float visibility = (\n\
czm_shadowDepthCompare(shadowMap, uv, depth) +\n\
czm_shadowDepthCompare(shadowMap, uv + vec2(dx0, dy0), depth) +\n\
czm_shadowDepthCompare(shadowMap, uv + vec2(0.0, dy0), depth) +\n\
czm_shadowDepthCompare(shadowMap, uv + vec2(dx1, dy0), depth) +\n\
czm_shadowDepthCompare(shadowMap, uv + vec2(dx0, 0.0), depth) +\n\
czm_shadowDepthCompare(shadowMap, uv + vec2(dx1, 0.0), depth) +\n\
czm_shadowDepthCompare(shadowMap, uv + vec2(dx0, dy1), depth) +\n\
czm_shadowDepthCompare(shadowMap, uv + vec2(0.0, dy1), depth) +\n\
czm_shadowDepthCompare(shadowMap, uv + vec2(dx1, dy1), depth)\n\
) * (1.0 / 9.0);\n\
#else\n\
float visibility = czm_shadowDepthCompare(shadowMap, uv, depth);\n\
#endif\n\
return czm_private_shadowVisibility(visibility, nDotL, normalShadingSmooth, darkness);\n\
}\n\
#endif\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_signNotZero = "float czm_signNotZero(float value)\n\
{\n\
return value >= 0.0 ? 1.0 : -1.0;\n\
}\n\
vec2 czm_signNotZero(vec2 value)\n\
{\n\
return vec2(czm_signNotZero(value.x), czm_signNotZero(value.y));\n\
}\n\
vec3 czm_signNotZero(vec3 value)\n\
{\n\
return vec3(czm_signNotZero(value.x), czm_signNotZero(value.y), czm_signNotZero(value.z));\n\
}\n\
vec4 czm_signNotZero(vec4 value)\n\
{\n\
return vec4(czm_signNotZero(value.x), czm_signNotZero(value.y), czm_signNotZero(value.z), czm_signNotZero(value.w));\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_sphericalHarmonics = "vec3 czm_sphericalHarmonics(vec3 normal, vec3 coefficients[9])\n\
{\n\
vec3 L00 = coefficients[0];\n\
vec3 L1_1 = coefficients[1];\n\
vec3 L10 = coefficients[2];\n\
vec3 L11 = coefficients[3];\n\
vec3 L2_2 = coefficients[4];\n\
vec3 L2_1 = coefficients[5];\n\
vec3 L20 = coefficients[6];\n\
vec3 L21 = coefficients[7];\n\
vec3 L22 = coefficients[8];\n\
float x = normal.x;\n\
float y = normal.y;\n\
float z = normal.z;\n\
return\n\
L00\n\
+ L1_1 * y\n\
+ L10 * z\n\
+ L11 * x\n\
+ L2_2 * (y * x)\n\
+ L2_1 * (y * z)\n\
+ L20 * (3.0 * z * z - 1.0)\n\
+ L21 * (z * x)\n\
+ L22 * (x * x - y * y);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_srgbToLinear = "vec3 czm_srgbToLinear(vec3 srgbIn)\n\
{\n\
return pow(srgbIn, vec3(2.2));\n\
}\n\
vec4 czm_srgbToLinear(vec4 srgbIn)\n\
{\n\
vec3 linearOut = pow(srgbIn.rgb, vec3(2.2));\n\
return vec4(linearOut, srgbIn.a);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_tangentToEyeSpaceMatrix = "mat3 czm_tangentToEyeSpaceMatrix(vec3 normalEC, vec3 tangentEC, vec3 bitangentEC)\n\
{\n\
vec3 normal = normalize(normalEC);\n\
vec3 tangent = normalize(tangentEC);\n\
vec3 bitangent = normalize(bitangentEC);\n\
return mat3(tangent.x  , tangent.y  , tangent.z,\n\
bitangent.x, bitangent.y, bitangent.z,\n\
normal.x   , normal.y   , normal.z);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_transformPlane = "vec4 czm_transformPlane(vec4 plane, mat4 transform) {\n\
vec4 transformedPlane = transform * plane;\n\
float normalMagnitude = length(transformedPlane.xyz);\n\
return transformedPlane / normalMagnitude;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_translateRelativeToEye = "vec4 czm_translateRelativeToEye(vec3 high, vec3 low)\n\
{\n\
vec3 highDifference = high - czm_encodedCameraPositionMCHigh;\n\
vec3 lowDifference = low - czm_encodedCameraPositionMCLow;\n\
return vec4(highDifference + lowDifference, 1.0);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_translucentPhong = "vec4 czm_translucentPhong(vec3 toEye, czm_material material, vec3 lightDirectionEC)\n\
{\n\
float diffuse = czm_getLambertDiffuse(vec3(0.0, 0.0, 1.0), material.normal);\n\
if (czm_sceneMode == czm_sceneMode3D) {\n\
diffuse += czm_getLambertDiffuse(vec3(0.0, 1.0, 0.0), material.normal);\n\
}\n\
diffuse = clamp(diffuse, 0.0, 1.0);\n\
float specular = czm_getSpecular(lightDirectionEC, toEye, material.normal, material.shininess);\n\
vec3 materialDiffuse = material.diffuse * 0.5;\n\
vec3 ambient = materialDiffuse;\n\
vec3 color = ambient + material.emission;\n\
color += materialDiffuse * diffuse * czm_lightColor;\n\
color += material.specular * specular * czm_lightColor;\n\
return vec4(color, material.alpha);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_transpose = "mat2 czm_transpose(mat2 matrix)\n\
{\n\
return mat2(\n\
matrix[0][0], matrix[1][0],\n\
matrix[0][1], matrix[1][1]);\n\
}\n\
mat3 czm_transpose(mat3 matrix)\n\
{\n\
return mat3(\n\
matrix[0][0], matrix[1][0], matrix[2][0],\n\
matrix[0][1], matrix[1][1], matrix[2][1],\n\
matrix[0][2], matrix[1][2], matrix[2][2]);\n\
}\n\
mat4 czm_transpose(mat4 matrix)\n\
{\n\
return mat4(\n\
matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],\n\
matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],\n\
matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],\n\
matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_unpackDepth = "float czm_unpackDepth(vec4 packedDepth)\n\
{\n\
return dot(packedDepth, vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0));\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_unpackFloat = "float czm_unpackFloat(vec4 packedFloat)\n\
{\n\
packedFloat = floor(packedFloat * 255.0 + 0.5);\n\
float sign = 1.0 - step(128.0, packedFloat[3]) * 2.0;\n\
float exponent = 2.0 * mod(packedFloat[3], 128.0) + step(128.0, packedFloat[2]) - 127.0;\n\
if (exponent == -127.0)\n\
{\n\
return 0.0;\n\
}\n\
float mantissa = mod(packedFloat[2], 128.0) * 65536.0 + packedFloat[1] * 256.0 + packedFloat[0] + float(0x800000);\n\
float result = sign * exp2(exponent - 23.0) * mantissa;\n\
return result;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_unpackUint = "int czm_unpackUint(float packedValue) {\n\
float rounded = czm_round(packedValue * 255.0);\n\
return int(rounded);\n\
}\n\
int czm_unpackUint(vec2 packedValue) {\n\
vec2 rounded = czm_round(packedValue * 255.0);\n\
return int(dot(rounded, vec2(1.0, 256.0)));\n\
}\n\
int czm_unpackUint(vec3 packedValue) {\n\
vec3 rounded = czm_round(packedValue * 255.0);\n\
return int(dot(rounded, vec3(1.0, 256.0, 65536.0)));\n\
}\n\
int czm_unpackUint(vec4 packedValue) {\n\
vec4 rounded = czm_round(packedValue * 255.0);\n\
return int(dot(rounded, vec4(1.0, 256.0, 65536.0, 16777216.0)));\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_valueTransform = "float czm_valueTransform(float offset, float scale, float value) {\n\
return scale * value + offset;\n\
}\n\
vec2 czm_valueTransform(vec2 offset, vec2 scale, vec2 value) {\n\
return scale * value + offset;\n\
}\n\
vec3 czm_valueTransform(vec3 offset, vec3 scale, vec3 value) {\n\
return scale * value + offset;\n\
}\n\
vec4 czm_valueTransform(vec4 offset, vec4 scale, vec4 value) {\n\
return scale * value + offset;\n\
}\n\
mat2 czm_valueTransform(mat2 offset, mat2 scale, mat2 value) {\n\
return matrixCompMult(scale, value) + offset;\n\
}\n\
mat3 czm_valueTransform(mat3 offset, mat3 scale, mat3 value) {\n\
return matrixCompMult(scale, value) + offset;\n\
}\n\
mat4 czm_valueTransform(mat4 offset, mat4 scale, mat4 value) {\n\
return matrixCompMult(scale, value) + offset;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_vertexLogDepth = "#ifdef LOG_DEPTH\n\
varying float v_depthFromNearPlusOne;\n\
#ifdef SHADOW_MAP\n\
varying vec3 v_logPositionEC;\n\
#endif\n\
#endif\n\
vec4 czm_updatePositionDepth(vec4 coords) {\n\
#if defined(LOG_DEPTH)\n\
#ifdef SHADOW_MAP\n\
vec3 logPositionEC = (czm_inverseProjection * coords).xyz;\n\
v_logPositionEC = logPositionEC;\n\
#endif\n\
coords.z = clamp(coords.z / coords.w, -1.0, 1.0) * coords.w;\n\
#endif\n\
return coords;\n\
}\n\
void czm_vertexLogDepth()\n\
{\n\
#ifdef LOG_DEPTH\n\
v_depthFromNearPlusOne = (gl_Position.w - czm_currentFrustum.x) + 1.0;\n\
gl_Position = czm_updatePositionDepth(gl_Position);\n\
#endif\n\
}\n\
void czm_vertexLogDepth(vec4 clipCoords)\n\
{\n\
#ifdef LOG_DEPTH\n\
v_depthFromNearPlusOne = (clipCoords.w - czm_currentFrustum.x) + 1.0;\n\
czm_updatePositionDepth(clipCoords);\n\
#endif\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_windowToEyeCoordinates = "vec4 czm_windowToEyeCoordinates(vec4 fragmentCoordinate)\n\
{\n\
float x = 2.0 * (fragmentCoordinate.x - czm_viewport.x) / czm_viewport.z - 1.0;\n\
float y = 2.0 * (fragmentCoordinate.y - czm_viewport.y) / czm_viewport.w - 1.0;\n\
float z = (fragmentCoordinate.z - czm_viewportTransformation[3][2]) / czm_viewportTransformation[2][2];\n\
vec4 q = vec4(x, y, z, 1.0);\n\
q /= fragmentCoordinate.w;\n\
if (!(czm_inverseProjection == mat4(0.0)))\n\
{\n\
q = czm_inverseProjection * q;\n\
}\n\
else\n\
{\n\
float top = czm_frustumPlanes.x;\n\
float bottom = czm_frustumPlanes.y;\n\
float left = czm_frustumPlanes.z;\n\
float right = czm_frustumPlanes.w;\n\
float near = czm_currentFrustum.x;\n\
float far = czm_currentFrustum.y;\n\
q.x = (q.x * (right - left) + left + right) * 0.5;\n\
q.y = (q.y * (top - bottom) + bottom + top) * 0.5;\n\
q.z = (q.z * (near - far) - near - far) * 0.5;\n\
q.w = 1.0;\n\
}\n\
return q;\n\
}\n\
vec4 czm_windowToEyeCoordinates(vec2 fragmentCoordinateXY, float depthOrLogDepth)\n\
{\n\
#ifdef LOG_DEPTH\n\
float near = czm_currentFrustum.x;\n\
float far = czm_currentFrustum.y;\n\
float log2Depth = depthOrLogDepth * czm_log2FarDepthFromNearPlusOne;\n\
float depthFromNear = pow(2.0, log2Depth) - 1.0;\n\
float depthFromCamera = depthFromNear + near;\n\
vec4 windowCoord = vec4(fragmentCoordinateXY, far * (1.0 - near / depthFromCamera) / (far - near), 1.0);\n\
vec4 eyeCoordinate = czm_windowToEyeCoordinates(windowCoord);\n\
eyeCoordinate.w = 1.0 / depthFromCamera;\n\
return eyeCoordinate;\n\
#else\n\
vec4 windowCoord = vec4(fragmentCoordinateXY, depthOrLogDepth, 1.0);\n\
vec4 eyeCoordinate = czm_windowToEyeCoordinates(windowCoord);\n\
#endif\n\
return eyeCoordinate;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_writeDepthClamp = "#if defined(GL_EXT_frag_depth) && !defined(LOG_DEPTH)\n\
varying float v_WindowZ;\n\
#endif\n\
void czm_writeDepthClamp()\n\
{\n\
#if defined(GL_EXT_frag_depth) && !defined(LOG_DEPTH)\n\
gl_FragDepthEXT = clamp(v_WindowZ * gl_FragCoord.w, 0.0, 1.0);\n\
#endif\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_writeLogDepth = "#ifdef LOG_DEPTH\n\
varying float v_depthFromNearPlusOne;\n\
#ifdef POLYGON_OFFSET\n\
uniform vec2 u_polygonOffset;\n\
#endif\n\
#endif\n\
void czm_writeLogDepth(float depth)\n\
{\n\
#if defined(GL_EXT_frag_depth) && defined(LOG_DEPTH)\n\
if (depth <= 0.9999999 || depth > czm_farDepthFromNearPlusOne) {\n\
discard;\n\
}\n\
#ifdef POLYGON_OFFSET\n\
float factor = u_polygonOffset[0];\n\
float units = u_polygonOffset[1];\n\
#ifdef GL_OES_standard_derivatives\n\
float x = dFdx(depth);\n\
float y = dFdy(depth);\n\
float m = sqrt(x * x + y * y);\n\
depth += m * factor;\n\
#endif\n\
#endif\n\
gl_FragDepthEXT = log2(depth) * czm_oneOverLog2FarDepthFromNearPlusOne;\n\
#ifdef POLYGON_OFFSET\n\
gl_FragDepthEXT += czm_epsilon7 * units;\n\
#endif\n\
#endif\n\
}\n\
void czm_writeLogDepth() {\n\
#ifdef LOG_DEPTH\n\
czm_writeLogDepth(v_depthFromNearPlusOne);\n\
#endif\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var czm_writeNonPerspective = "float czm_writeNonPerspective(float value, float w) {\n\
return value * w;\n\
}\n\
vec2 czm_writeNonPerspective(vec2 value, float w) {\n\
return value * w;\n\
}\n\
vec3 czm_writeNonPerspective(vec3 value, float w) {\n\
return value * w;\n\
}\n\
vec4 czm_writeNonPerspective(vec4 value, float w) {\n\
return value * w;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.

  var CzmBuiltins = {
      czm_degreesPerRadian : czm_degreesPerRadian,
      czm_depthRange : czm_depthRange,
      czm_epsilon1 : czm_epsilon1,
      czm_epsilon2 : czm_epsilon2,
      czm_epsilon3 : czm_epsilon3,
      czm_epsilon4 : czm_epsilon4,
      czm_epsilon5 : czm_epsilon5,
      czm_epsilon6 : czm_epsilon6,
      czm_epsilon7 : czm_epsilon7,
      czm_infinity : czm_infinity,
      czm_oneOverPi : czm_oneOverPi,
      czm_oneOverTwoPi : czm_oneOverTwoPi,
      czm_passCesium3DTile : czm_passCesium3DTile,
      czm_passCesium3DTileClassification : czm_passCesium3DTileClassification,
      czm_passCesium3DTileClassificationIgnoreShow : czm_passCesium3DTileClassificationIgnoreShow,
      czm_passClassification : czm_passClassification,
      czm_passCompute : czm_passCompute,
      czm_passEnvironment : czm_passEnvironment,
      czm_passGlobe : czm_passGlobe,
      czm_passOpaque : czm_passOpaque,
      czm_passOverlay : czm_passOverlay,
      czm_passTerrainClassification : czm_passTerrainClassification,
      czm_passTranslucent : czm_passTranslucent,
      czm_pi : czm_pi,
      czm_piOverFour : czm_piOverFour,
      czm_piOverSix : czm_piOverSix,
      czm_piOverThree : czm_piOverThree,
      czm_piOverTwo : czm_piOverTwo,
      czm_radiansPerDegree : czm_radiansPerDegree,
      czm_sceneMode2D : czm_sceneMode2D,
      czm_sceneMode3D : czm_sceneMode3D,
      czm_sceneModeColumbusView : czm_sceneModeColumbusView,
      czm_sceneModeMorphing : czm_sceneModeMorphing,
      czm_solarRadius : czm_solarRadius,
      czm_threePiOver2 : czm_threePiOver2,
      czm_twoPi : czm_twoPi,
      czm_webMercatorMaxLatitude : czm_webMercatorMaxLatitude,
      czm_depthRangeStruct : czm_depthRangeStruct,
      czm_material : czm_material,
      czm_materialInput : czm_materialInput,
      czm_modelMaterial : czm_modelMaterial,
      czm_modelVertexOutput : czm_modelVertexOutput,
      czm_pbrParameters : czm_pbrParameters,
      czm_ray : czm_ray,
      czm_raySegment : czm_raySegment,
      czm_shadowParameters : czm_shadowParameters,
      czm_HSBToRGB : czm_HSBToRGB,
      czm_HSLToRGB : czm_HSLToRGB,
      czm_RGBToHSB : czm_RGBToHSB,
      czm_RGBToHSL : czm_RGBToHSL,
      czm_RGBToXYZ : czm_RGBToXYZ,
      czm_XYZToRGB : czm_XYZToRGB,
      czm_acesTonemapping : czm_acesTonemapping,
      czm_alphaWeight : czm_alphaWeight,
      czm_antialias : czm_antialias,
      czm_approximateSphericalCoordinates : czm_approximateSphericalCoordinates,
      czm_backFacing : czm_backFacing,
      czm_branchFreeTernary : czm_branchFreeTernary,
      czm_cascadeColor : czm_cascadeColor,
      czm_cascadeDistance : czm_cascadeDistance,
      czm_cascadeMatrix : czm_cascadeMatrix,
      czm_cascadeWeights : czm_cascadeWeights,
      czm_columbusViewMorph : czm_columbusViewMorph,
      czm_computePosition : czm_computePosition,
      czm_cosineAndSine : czm_cosineAndSine,
      czm_decompressTextureCoordinates : czm_decompressTextureCoordinates,
      czm_defaultPbrMaterial : czm_defaultPbrMaterial,
      czm_depthClamp : czm_depthClamp,
      czm_eastNorthUpToEyeCoordinates : czm_eastNorthUpToEyeCoordinates,
      czm_ellipsoidContainsPoint : czm_ellipsoidContainsPoint,
      czm_ellipsoidWgs84TextureCoordinates : czm_ellipsoidWgs84TextureCoordinates,
      czm_equalsEpsilon : czm_equalsEpsilon,
      czm_eyeOffset : czm_eyeOffset,
      czm_eyeToWindowCoordinates : czm_eyeToWindowCoordinates,
      czm_fastApproximateAtan : czm_fastApproximateAtan,
      czm_fog : czm_fog,
      czm_gammaCorrect : czm_gammaCorrect,
      czm_geodeticSurfaceNormal : czm_geodeticSurfaceNormal,
      czm_getDefaultMaterial : czm_getDefaultMaterial,
      czm_getLambertDiffuse : czm_getLambertDiffuse,
      czm_getSpecular : czm_getSpecular,
      czm_getWaterNoise : czm_getWaterNoise,
      czm_hue : czm_hue,
      czm_inverseGamma : czm_inverseGamma,
      czm_isEmpty : czm_isEmpty,
      czm_isFull : czm_isFull,
      czm_latitudeToWebMercatorFraction : czm_latitudeToWebMercatorFraction,
      czm_lineDistance : czm_lineDistance,
      czm_linearToSrgb : czm_linearToSrgb,
      czm_luminance : czm_luminance,
      czm_metersPerPixel : czm_metersPerPixel,
      czm_modelToWindowCoordinates : czm_modelToWindowCoordinates,
      czm_multiplyWithColorBalance : czm_multiplyWithColorBalance,
      czm_nearFarScalar : czm_nearFarScalar,
      czm_octDecode : czm_octDecode,
      czm_packDepth : czm_packDepth,
      czm_pbrLighting : czm_pbrLighting,
      czm_pbrMetallicRoughnessMaterial : czm_pbrMetallicRoughnessMaterial,
      czm_pbrSpecularGlossinessMaterial : czm_pbrSpecularGlossinessMaterial,
      czm_phong : czm_phong,
      czm_planeDistance : czm_planeDistance,
      czm_pointAlongRay : czm_pointAlongRay,
      czm_rayEllipsoidIntersectionInterval : czm_rayEllipsoidIntersectionInterval,
      czm_raySphereIntersectionInterval : czm_raySphereIntersectionInterval,
      czm_readDepth : czm_readDepth,
      czm_readNonPerspective : czm_readNonPerspective,
      czm_reverseLogDepth : czm_reverseLogDepth,
      czm_round : czm_round,
      czm_sampleOctahedralProjection : czm_sampleOctahedralProjection,
      czm_saturation : czm_saturation,
      czm_shadowDepthCompare : czm_shadowDepthCompare,
      czm_shadowVisibility : czm_shadowVisibility,
      czm_signNotZero : czm_signNotZero,
      czm_sphericalHarmonics : czm_sphericalHarmonics,
      czm_srgbToLinear : czm_srgbToLinear,
      czm_tangentToEyeSpaceMatrix : czm_tangentToEyeSpaceMatrix,
      czm_transformPlane : czm_transformPlane,
      czm_translateRelativeToEye : czm_translateRelativeToEye,
      czm_translucentPhong : czm_translucentPhong,
      czm_transpose : czm_transpose,
      czm_unpackDepth : czm_unpackDepth,
      czm_unpackFloat : czm_unpackFloat,
      czm_unpackUint : czm_unpackUint,
      czm_valueTransform : czm_valueTransform,
      czm_vertexLogDepth : czm_vertexLogDepth,
      czm_windowToEyeCoordinates : czm_windowToEyeCoordinates,
      czm_writeDepthClamp : czm_writeDepthClamp,
      czm_writeLogDepth : czm_writeLogDepth,
      czm_writeNonPerspective : czm_writeNonPerspective
  };

  function removeComments(source) {
    // remove inline comments
    source = source.replace(/\/\/.*/g, "");
    // remove multiline comment block
    return source.replace(/\/\*\*[\s\S]*?\*\//gm, function (match) {
      // preserve the number of lines in the comment block so the line numbers will be correct when debugging shaders
      const numberOfLines = match.match(/\n/gm).length;
      let replacement = "";
      for (let lineNumber = 0; lineNumber < numberOfLines; ++lineNumber) {
        replacement += "\n";
      }
      return replacement;
    });
  }

  function getDependencyNode(name, glslSource, nodes) {
    let dependencyNode;

    // check if already loaded
    for (let i = 0; i < nodes.length; ++i) {
      if (nodes[i].name === name) {
        dependencyNode = nodes[i];
      }
    }

    if (!defined(dependencyNode)) {
      // strip doc comments so we don't accidentally try to determine a dependency for something found
      // in a comment
      glslSource = removeComments(glslSource);

      // create new node
      dependencyNode = {
        name: name,
        glslSource: glslSource,
        dependsOn: [],
        requiredBy: [],
        evaluated: false,
      };
      nodes.push(dependencyNode);
    }

    return dependencyNode;
  }

  function generateDependencies(currentNode, dependencyNodes) {
    if (currentNode.evaluated) {
      return;
    }

    currentNode.evaluated = true;

    // identify all dependencies that are referenced from this glsl source code
    let czmMatches = currentNode.glslSource.match(/\bczm_[a-zA-Z0-9_]*/g);
    if (defined(czmMatches) && czmMatches !== null) {
      // remove duplicates
      czmMatches = czmMatches.filter(function (elem, pos) {
        return czmMatches.indexOf(elem) === pos;
      });

      czmMatches.forEach(function (element) {
        if (
          element !== currentNode.name &&
          ShaderSource._czmBuiltinsAndUniforms.hasOwnProperty(element)
        ) {
          const referencedNode = getDependencyNode(
            element,
            ShaderSource._czmBuiltinsAndUniforms[element],
            dependencyNodes
          );
          currentNode.dependsOn.push(referencedNode);
          referencedNode.requiredBy.push(currentNode);

          // recursive call to find any dependencies of the new node
          generateDependencies(referencedNode, dependencyNodes);
        }
      });
    }
  }

  function sortDependencies(dependencyNodes) {
    const nodesWithoutIncomingEdges = [];
    const allNodes = [];

    while (dependencyNodes.length > 0) {
      const node = dependencyNodes.pop();
      allNodes.push(node);

      if (node.requiredBy.length === 0) {
        nodesWithoutIncomingEdges.push(node);
      }
    }

    while (nodesWithoutIncomingEdges.length > 0) {
      const currentNode = nodesWithoutIncomingEdges.shift();

      dependencyNodes.push(currentNode);

      for (let i = 0; i < currentNode.dependsOn.length; ++i) {
        // remove the edge from the graph
        const referencedNode = currentNode.dependsOn[i];
        const index = referencedNode.requiredBy.indexOf(currentNode);
        referencedNode.requiredBy.splice(index, 1);

        // if referenced node has no more incoming edges, add to list
        if (referencedNode.requiredBy.length === 0) {
          nodesWithoutIncomingEdges.push(referencedNode);
        }
      }
    }

    // if there are any nodes left with incoming edges, then there was a circular dependency somewhere in the graph
    const badNodes = [];
    for (let j = 0; j < allNodes.length; ++j) {
      if (allNodes[j].requiredBy.length !== 0) {
        badNodes.push(allNodes[j]);
      }
    }

    //>>includeStart('debug', pragmas.debug);
    if (badNodes.length !== 0) {
      let message =
        "A circular dependency was found in the following built-in functions/structs/constants: \n";
      for (let k = 0; k < badNodes.length; ++k) {
        message = `${message + badNodes[k].name}\n`;
      }
      throw new DeveloperError(message);
    }
    //>>includeEnd('debug');
  }

  function getBuiltinsAndAutomaticUniforms(shaderSource) {
    // generate a dependency graph for builtin functions
    const dependencyNodes = [];
    const root = getDependencyNode("main", shaderSource, dependencyNodes);
    generateDependencies(root, dependencyNodes);
    sortDependencies(dependencyNodes);

    // Concatenate the source code for the function dependencies.
    // Iterate in reverse so that dependent items are declared before they are used.
    let builtinsSource = "";
    for (let i = dependencyNodes.length - 1; i >= 0; --i) {
      builtinsSource = `${builtinsSource + dependencyNodes[i].glslSource}\n`;
    }

    return builtinsSource.replace(root.glslSource, "");
  }

  function combineShader(shaderSource, isFragmentShader, context) {
    let i;
    let length;

    // Combine shader sources, generally for pseudo-polymorphism, e.g., czm_getMaterial.
    let combinedSources = "";
    const sources = shaderSource.sources;
    if (defined(sources)) {
      for (i = 0, length = sources.length; i < length; ++i) {
        // #line needs to be on its own line.
        combinedSources += `\n#line 0\n${sources[i]}`;
      }
    }

    combinedSources = removeComments(combinedSources);

    // Extract existing shader version from sources
    let version;
    combinedSources = combinedSources.replace(/#version\s+(.*?)\n/gm, function (
      match,
      group1
    ) {
      //>>includeStart('debug', pragmas.debug);
      if (defined(version) && version !== group1) {
        throw new DeveloperError(
          `inconsistent versions found: ${version} and ${group1}`
        );
      }
      //>>includeEnd('debug');

      // Extract #version to put at the top
      version = group1;

      // Replace original #version directive with a new line so the line numbers
      // are not off by one.  There can be only one #version directive
      // and it must appear at the top of the source, only preceded by
      // whitespace and comments.
      return "\n";
    });

    // Extract shader extensions from sources
    const extensions = [];
    combinedSources = combinedSources.replace(/#extension.*\n/gm, function (
      match
    ) {
      // Extract extension to put at the top
      extensions.push(match);

      // Replace original #extension directive with a new line so the line numbers
      // are not off by one.
      return "\n";
    });

    // Remove precision qualifier
    combinedSources = combinedSources.replace(
      /precision\s(lowp|mediump|highp)\s(float|int);/,
      ""
    );

    // Replace main() for picked if desired.
    const pickColorQualifier = shaderSource.pickColorQualifier;
    if (defined(pickColorQualifier)) {
      combinedSources = ShaderSource.createPickFragmentShaderSource(
        combinedSources,
        pickColorQualifier
      );
    }

    // combine into single string
    let result = "";

    // #version must be first
    // defaults to #version 100 if not specified
    if (defined(version)) {
      result = `#version ${version}\n`;
    }

    const extensionsLength = extensions.length;
    for (i = 0; i < extensionsLength; i++) {
      result += extensions[i];
    }

    if (isFragmentShader) {
      // If high precision isn't support replace occurrences of highp with mediump
      // The highp keyword is not always available on older mobile devices
      // See https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/WebGL_best_practices#In_WebGL_1_highp_float_support_is_optional_in_fragment_shaders
      result +=
        "\
#ifdef GL_FRAGMENT_PRECISION_HIGH\n\
    precision highp float;\n\
    precision highp int;\n\
#else\n\
    precision mediump float;\n\
    precision mediump int;\n\
    #define highp mediump\n\
#endif\n\n";
    }

    // Prepend #defines for uber-shaders
    const defines = shaderSource.defines;
    if (defined(defines)) {
      for (i = 0, length = defines.length; i < length; ++i) {
        const define = defines[i];
        if (define.length !== 0) {
          result += `#define ${define}\n`;
        }
      }
    }

    // GLSLModernizer inserts its own layout qualifiers
    // at this position in the source
    if (context.webgl2) {
      result += "#define OUTPUT_DECLARATION\n\n";
    }

    // Define a constant for the OES_texture_float_linear extension since WebGL does not.
    if (context.textureFloatLinear) {
      result += "#define OES_texture_float_linear\n\n";
    }

    // Define a constant for the OES_texture_float extension since WebGL does not.
    if (context.floatingPointTexture) {
      result += "#define OES_texture_float\n\n";
    }

    // append built-ins
    if (shaderSource.includeBuiltIns) {
      result += getBuiltinsAndAutomaticUniforms(combinedSources);
    }

    // reset line number
    result += "\n#line 0\n";

    // append actual source
    result += combinedSources;

    // modernize the source
    if (context.webgl2) {
      result = modernizeShader(result, isFragmentShader);
    }

    return result;
  }

  /**
   * An object containing various inputs that will be combined to form a final GLSL shader string.
   *
   * @param {Object} [options] Object with the following properties:
   * @param {String[]} [options.sources] An array of strings to combine containing GLSL code for the shader.
   * @param {String[]} [options.defines] An array of strings containing GLSL identifiers to <code>#define</code>.
   * @param {String} [options.pickColorQualifier] The GLSL qualifier, <code>uniform</code> or <code>varying</code>, for the input <code>czm_pickColor</code>.  When defined, a pick fragment shader is generated.
   * @param {Boolean} [options.includeBuiltIns=true] If true, referenced built-in functions will be included with the combined shader.  Set to false if this shader will become a source in another shader, to avoid duplicating functions.
   *
   * @exception {DeveloperError} options.pickColorQualifier must be 'uniform' or 'varying'.
   *
   * @example
   * // 1. Prepend #defines to a shader
   * const source = new Cesium.ShaderSource({
   *   defines : ['WHITE'],
   *   sources : ['void main() { \n#ifdef WHITE\n gl_FragColor = vec4(1.0); \n#else\n gl_FragColor = vec4(0.0); \n#endif\n }']
   * });
   *
   * // 2. Modify a fragment shader for picking
   * const source2 = new Cesium.ShaderSource({
   *   sources : ['void main() { gl_FragColor = vec4(1.0); }'],
   *   pickColorQualifier : 'uniform'
   * });
   *
   * @private
   */
  function ShaderSource(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const pickColorQualifier = options.pickColorQualifier;

    //>>includeStart('debug', pragmas.debug);
    if (
      defined(pickColorQualifier) &&
      pickColorQualifier !== "uniform" &&
      pickColorQualifier !== "varying"
    ) {
      throw new DeveloperError(
        "options.pickColorQualifier must be 'uniform' or 'varying'."
      );
    }
    //>>includeEnd('debug');

    this.defines = defined(options.defines) ? options.defines.slice(0) : [];
    this.sources = defined(options.sources) ? options.sources.slice(0) : [];
    this.pickColorQualifier = pickColorQualifier;
    this.includeBuiltIns = defaultValue(options.includeBuiltIns, true);
  }

  ShaderSource.prototype.clone = function () {
    return new ShaderSource({
      sources: this.sources,
      defines: this.defines,
      pickColorQualifier: this.pickColorQualifier,
      includeBuiltIns: this.includeBuiltIns,
    });
  };

  ShaderSource.replaceMain = function (source, renamedMain) {
    renamedMain = `void ${renamedMain}()`;
    return source.replace(/void\s+main\s*\(\s*(?:void)?\s*\)/g, renamedMain);
  };

  /**
   * Create a single string containing the full, combined vertex shader with all dependencies and defines.
   *
   * @param {Context} context The current rendering context
   *
   * @returns {String} The combined shader string.
   */
  ShaderSource.prototype.createCombinedVertexShader = function (context) {
    return combineShader(this, false, context);
  };

  /**
   * Create a single string containing the full, combined fragment shader with all dependencies and defines.
   *
   * @param {Context} context The current rendering context
   *
   * @returns {String} The combined shader string.
   */
  ShaderSource.prototype.createCombinedFragmentShader = function (context) {
    return combineShader(this, true, context);
  };

  /**
   * For ShaderProgram testing
   * @private
   */
  ShaderSource._czmBuiltinsAndUniforms = {};

  // combine automatic uniforms and Cesium built-ins
  for (const builtinName in CzmBuiltins) {
    if (CzmBuiltins.hasOwnProperty(builtinName)) {
      ShaderSource._czmBuiltinsAndUniforms[builtinName] =
        CzmBuiltins[builtinName];
    }
  }
  for (const uniformName in AutomaticUniforms) {
    if (AutomaticUniforms.hasOwnProperty(uniformName)) {
      const uniform = AutomaticUniforms[uniformName];
      if (typeof uniform.getDeclaration === "function") {
        ShaderSource._czmBuiltinsAndUniforms[
          uniformName
        ] = uniform.getDeclaration(uniformName);
      }
    }
  }

  ShaderSource.createPickVertexShaderSource = function (vertexShaderSource) {
    const renamedVS = ShaderSource.replaceMain(
      vertexShaderSource,
      "czm_old_main"
    );
    const pickMain =
      "attribute vec4 pickColor; \n" +
      "varying vec4 czm_pickColor; \n" +
      "void main() \n" +
      "{ \n" +
      "    czm_old_main(); \n" +
      "    czm_pickColor = pickColor; \n" +
      "}";

    return `${renamedVS}\n${pickMain}`;
  };

  ShaderSource.createPickFragmentShaderSource = function (
    fragmentShaderSource,
    pickColorQualifier
  ) {
    const renamedFS = ShaderSource.replaceMain(
      fragmentShaderSource,
      "czm_old_main"
    );
    const pickMain =
      `${pickColorQualifier} vec4 czm_pickColor; \n` +
      `void main() \n` +
      `{ \n` +
      `    czm_old_main(); \n` +
      `    if (gl_FragColor.a == 0.0) { \n` +
      `       discard; \n` +
      `    } \n` +
      `    gl_FragColor = czm_pickColor; \n` +
      `}`;

    return `${renamedFS}\n${pickMain}`;
  };

  function containsDefine(shaderSource, define) {
    const defines = shaderSource.defines;
    const definesLength = defines.length;
    for (let i = 0; i < definesLength; ++i) {
      if (defines[i] === define) {
        return true;
      }
    }
    return false;
  }

  function containsString(shaderSource, string) {
    const sources = shaderSource.sources;
    const sourcesLength = sources.length;
    for (let i = 0; i < sourcesLength; ++i) {
      if (sources[i].indexOf(string) !== -1) {
        return true;
      }
    }
    return false;
  }

  function findFirstString(shaderSource, strings) {
    const stringsLength = strings.length;
    for (let i = 0; i < stringsLength; ++i) {
      const string = strings[i];
      if (containsString(shaderSource, string)) {
        return string;
      }
    }
    return undefined;
  }

  const normalVaryingNames = ["v_normalEC", "v_normal"];

  ShaderSource.findNormalVarying = function (shaderSource) {
    // Fix for ModelExperimental: the shader text always has the word v_normalEC
    // wrapped in an #ifdef so instead of looking for v_normalEC look for the define
    if (containsString(shaderSource, "#ifdef HAS_NORMALS")) {
      if (containsDefine(shaderSource, "HAS_NORMALS")) {
        return "v_normalEC";
      }
      return undefined;
    }

    return findFirstString(shaderSource, normalVaryingNames);
  };

  const positionVaryingNames = ["v_positionEC"];

  ShaderSource.findPositionVarying = function (shaderSource) {
    return findFirstString(shaderSource, positionVaryingNames);
  };

  //This file is automatically rebuilt by the Cesium build process.
  var ShadowVolumeAppearanceVS = "attribute vec3 position3DHigh;\n\
attribute vec3 position3DLow;\n\
attribute float batchId;\n\
#ifdef EXTRUDED_GEOMETRY\n\
attribute vec3 extrudeDirection;\n\
uniform float u_globeMinimumAltitude;\n\
#endif // EXTRUDED_GEOMETRY\n\
#ifdef PER_INSTANCE_COLOR\n\
varying vec4 v_color;\n\
#endif // PER_INSTANCE_COLOR\n\
#ifdef TEXTURE_COORDINATES\n\
#ifdef SPHERICAL\n\
varying vec4 v_sphericalExtents;\n\
#else // SPHERICAL\n\
varying vec2 v_inversePlaneExtents;\n\
varying vec4 v_westPlane;\n\
varying vec4 v_southPlane;\n\
#endif // SPHERICAL\n\
varying vec3 v_uvMinAndSphericalLongitudeRotation;\n\
varying vec3 v_uMaxAndInverseDistance;\n\
varying vec3 v_vMaxAndInverseDistance;\n\
#endif // TEXTURE_COORDINATES\n\
void main()\n\
{\n\
vec4 position = czm_computePosition();\n\
#ifdef EXTRUDED_GEOMETRY\n\
float delta = min(u_globeMinimumAltitude, czm_geometricToleranceOverMeter * length(position.xyz));\n\
delta *= czm_sceneMode == czm_sceneMode3D ? 1.0 : 0.0;\n\
position = position + vec4(extrudeDirection * delta, 0.0);\n\
#endif\n\
#ifdef TEXTURE_COORDINATES\n\
#ifdef SPHERICAL\n\
v_sphericalExtents = czm_batchTable_sphericalExtents(batchId);\n\
v_uvMinAndSphericalLongitudeRotation.z = czm_batchTable_longitudeRotation(batchId);\n\
#else // SPHERICAL\n\
#ifdef COLUMBUS_VIEW_2D\n\
vec4 planes2D_high = czm_batchTable_planes2D_HIGH(batchId);\n\
vec4 planes2D_low = czm_batchTable_planes2D_LOW(batchId);\n\
vec2 idlSplitNewPlaneHiLow = vec2(EAST_MOST_X_HIGH - (WEST_MOST_X_HIGH - planes2D_high.w), EAST_MOST_X_LOW - (WEST_MOST_X_LOW - planes2D_low.w));\n\
bool idlSplit = planes2D_high.x > planes2D_high.w && position3DLow.y > 0.0;\n\
planes2D_high.w = czm_branchFreeTernary(idlSplit, idlSplitNewPlaneHiLow.x, planes2D_high.w);\n\
planes2D_low.w = czm_branchFreeTernary(idlSplit, idlSplitNewPlaneHiLow.y, planes2D_low.w);\n\
idlSplit = planes2D_high.x > planes2D_high.w && position3DLow.y < 0.0;\n\
idlSplitNewPlaneHiLow = vec2(WEST_MOST_X_HIGH - (EAST_MOST_X_HIGH - planes2D_high.x), WEST_MOST_X_LOW - (EAST_MOST_X_LOW - planes2D_low.x));\n\
planes2D_high.x = czm_branchFreeTernary(idlSplit, idlSplitNewPlaneHiLow.x, planes2D_high.x);\n\
planes2D_low.x = czm_branchFreeTernary(idlSplit, idlSplitNewPlaneHiLow.y, planes2D_low.x);\n\
vec3 southWestCorner = (czm_modelViewRelativeToEye * czm_translateRelativeToEye(vec3(0.0, planes2D_high.xy), vec3(0.0, planes2D_low.xy))).xyz;\n\
vec3 northWestCorner = (czm_modelViewRelativeToEye * czm_translateRelativeToEye(vec3(0.0, planes2D_high.x, planes2D_high.z), vec3(0.0, planes2D_low.x, planes2D_low.z))).xyz;\n\
vec3 southEastCorner = (czm_modelViewRelativeToEye * czm_translateRelativeToEye(vec3(0.0, planes2D_high.w, planes2D_high.y), vec3(0.0, planes2D_low.w, planes2D_low.y))).xyz;\n\
#else // COLUMBUS_VIEW_2D\n\
vec3 southWestCorner = (czm_modelViewRelativeToEye * czm_translateRelativeToEye(czm_batchTable_southWest_HIGH(batchId), czm_batchTable_southWest_LOW(batchId))).xyz;\n\
vec3 northWestCorner = czm_normal * czm_batchTable_northward(batchId) + southWestCorner;\n\
vec3 southEastCorner = czm_normal * czm_batchTable_eastward(batchId) + southWestCorner;\n\
#endif // COLUMBUS_VIEW_2D\n\
vec3 eastWard = southEastCorner - southWestCorner;\n\
float eastExtent = length(eastWard);\n\
eastWard /= eastExtent;\n\
vec3 northWard = northWestCorner - southWestCorner;\n\
float northExtent = length(northWard);\n\
northWard /= northExtent;\n\
v_westPlane = vec4(eastWard, -dot(eastWard, southWestCorner));\n\
v_southPlane = vec4(northWard, -dot(northWard, southWestCorner));\n\
v_inversePlaneExtents = vec2(1.0 / eastExtent, 1.0 / northExtent);\n\
#endif // SPHERICAL\n\
vec4 uvMinAndExtents = czm_batchTable_uvMinAndExtents(batchId);\n\
vec4 uMaxVmax = czm_batchTable_uMaxVmax(batchId);\n\
v_uMaxAndInverseDistance = vec3(uMaxVmax.xy, uvMinAndExtents.z);\n\
v_vMaxAndInverseDistance = vec3(uMaxVmax.zw, uvMinAndExtents.w);\n\
v_uvMinAndSphericalLongitudeRotation.xy = uvMinAndExtents.xy;\n\
#endif // TEXTURE_COORDINATES\n\
#ifdef PER_INSTANCE_COLOR\n\
v_color = czm_batchTable_color(batchId);\n\
#endif\n\
gl_Position = czm_depthClamp(czm_modelViewProjectionRelativeToEye * position);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var ShadowVolumeFS = "#ifdef GL_EXT_frag_depth\n\
#extension GL_EXT_frag_depth : enable\n\
#endif\n\
#ifdef VECTOR_TILE\n\
uniform vec4 u_highlightColor;\n\
#endif\n\
void main(void)\n\
{\n\
#ifdef VECTOR_TILE\n\
gl_FragColor = czm_gammaCorrect(u_highlightColor);\n\
#else\n\
gl_FragColor = vec4(1.0);\n\
#endif\n\
czm_writeDepthClamp();\n\
}\n\
";

  /**
   * Whether a classification affects terrain, 3D Tiles or both.
   *
   * @enum {Number}
   */
  const ClassificationType = {
    /**
     * Only terrain will be classified.
     *
     * @type {Number}
     * @constant
     */
    TERRAIN: 0,
    /**
     * Only 3D Tiles will be classified.
     *
     * @type {Number}
     * @constant
     */
    CESIUM_3D_TILE: 1,
    /**
     * Both terrain and 3D Tiles will be classified.
     *
     * @type {Number}
     * @constant
     */
    BOTH: 2,
  };

  /**
   * @private
   */
  ClassificationType.NUMBER_OF_CLASSIFICATION_TYPES = 3;

  var ClassificationType$1 = Object.freeze(ClassificationType);

  /**
   * Determines the function used to compare two depths for the depth test.
   *
   * @enum {Number}
   */
  const DepthFunction = {
    /**
     * The depth test never passes.
     *
     * @type {Number}
     * @constant
     */
    NEVER: WebGLConstants$1.NEVER,

    /**
     * The depth test passes if the incoming depth is less than the stored depth.
     *
     * @type {Number}
     * @constant
     */
    LESS: WebGLConstants$1.LESS,

    /**
     * The depth test passes if the incoming depth is equal to the stored depth.
     *
     * @type {Number}
     * @constant
     */
    EQUAL: WebGLConstants$1.EQUAL,

    /**
     * The depth test passes if the incoming depth is less than or equal to the stored depth.
     *
     * @type {Number}
     * @constant
     */
    LESS_OR_EQUAL: WebGLConstants$1.LEQUAL,

    /**
     * The depth test passes if the incoming depth is greater than the stored depth.
     *
     * @type {Number}
     * @constant
     */
    GREATER: WebGLConstants$1.GREATER,

    /**
     * The depth test passes if the incoming depth is not equal to the stored depth.
     *
     * @type {Number}
     * @constant
     */
    NOT_EQUAL: WebGLConstants$1.NOTEQUAL,

    /**
     * The depth test passes if the incoming depth is greater than or equal to the stored depth.
     *
     * @type {Number}
     * @constant
     */
    GREATER_OR_EQUAL: WebGLConstants$1.GEQUAL,

    /**
     * The depth test always passes.
     *
     * @type {Number}
     * @constant
     */
    ALWAYS: WebGLConstants$1.ALWAYS,
  };
  var DepthFunction$1 = Object.freeze(DepthFunction);

  /**
   * @private
   */
  const BufferUsage = {
    STREAM_DRAW: WebGLConstants$1.STREAM_DRAW,
    STATIC_DRAW: WebGLConstants$1.STATIC_DRAW,
    DYNAMIC_DRAW: WebGLConstants$1.DYNAMIC_DRAW,

    validate: function (bufferUsage) {
      return (
        bufferUsage === BufferUsage.STREAM_DRAW ||
        bufferUsage === BufferUsage.STATIC_DRAW ||
        bufferUsage === BufferUsage.DYNAMIC_DRAW
      );
    },
  };
  var BufferUsage$1 = Object.freeze(BufferUsage);

  /**
   * @private
   */
  function Buffer$1(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    Check.defined("options.context", options.context);

    if (!defined(options.typedArray) && !defined(options.sizeInBytes)) {
      throw new DeveloperError(
        "Either options.sizeInBytes or options.typedArray is required."
      );
    }

    if (defined(options.typedArray) && defined(options.sizeInBytes)) {
      throw new DeveloperError(
        "Cannot pass in both options.sizeInBytes and options.typedArray."
      );
    }

    if (defined(options.typedArray)) {
      Check.typeOf.object("options.typedArray", options.typedArray);
      Check.typeOf.number(
        "options.typedArray.byteLength",
        options.typedArray.byteLength
      );
    }

    if (!BufferUsage$1.validate(options.usage)) {
      throw new DeveloperError("usage is invalid.");
    }
    //>>includeEnd('debug');

    const gl = options.context._gl;
    const bufferTarget = options.bufferTarget;
    const typedArray = options.typedArray;
    let sizeInBytes = options.sizeInBytes;
    const usage = options.usage;
    const hasArray = defined(typedArray);

    if (hasArray) {
      sizeInBytes = typedArray.byteLength;
    }

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number.greaterThan("sizeInBytes", sizeInBytes, 0);
    //>>includeEnd('debug');

    const buffer = gl.createBuffer();
    gl.bindBuffer(bufferTarget, buffer);
    gl.bufferData(bufferTarget, hasArray ? typedArray : sizeInBytes, usage);
    gl.bindBuffer(bufferTarget, null);

    this._id = createGuid();
    this._gl = gl;
    this._webgl2 = options.context._webgl2;
    this._bufferTarget = bufferTarget;
    this._sizeInBytes = sizeInBytes;
    this._usage = usage;
    this._buffer = buffer;
    this.vertexArrayDestroyable = true;
  }

  /**
   * Creates a vertex buffer, which contains untyped vertex data in GPU-controlled memory.
   * <br /><br />
   * A vertex array defines the actual makeup of a vertex, e.g., positions, normals, texture coordinates,
   * etc., by interpreting the raw data in one or more vertex buffers.
   *
   * @param {Object} options An object containing the following properties:
   * @param {Context} options.context The context in which to create the buffer
   * @param {ArrayBufferView} [options.typedArray] A typed array containing the data to copy to the buffer.
   * @param {Number} [options.sizeInBytes] A <code>Number</code> defining the size of the buffer in bytes. Required if options.typedArray is not given.
   * @param {BufferUsage} options.usage Specifies the expected usage pattern of the buffer. On some GL implementations, this can significantly affect performance. See {@link BufferUsage}.
   * @returns {VertexBuffer} The vertex buffer, ready to be attached to a vertex array.
   *
   * @exception {DeveloperError} Must specify either <options.typedArray> or <options.sizeInBytes>, but not both.
   * @exception {DeveloperError} The buffer size must be greater than zero.
   * @exception {DeveloperError} Invalid <code>usage</code>.
   *
   *
   * @example
   * // Example 1. Create a dynamic vertex buffer 16 bytes in size.
   * const buffer = Buffer.createVertexBuffer({
   *     context : context,
   *     sizeInBytes : 16,
   *     usage : BufferUsage.DYNAMIC_DRAW
   * });
   *
   * @example
   * // Example 2. Create a dynamic vertex buffer from three floating-point values.
   * // The data copied to the vertex buffer is considered raw bytes until it is
   * // interpreted as vertices using a vertex array.
   * const positionBuffer = buffer.createVertexBuffer({
   *     context : context,
   *     typedArray : new Float32Array([0, 0, 0]),
   *     usage : BufferUsage.STATIC_DRAW
   * });
   *
   * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGenBuffer.xml|glGenBuffer}
   * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glBindBuffer.xml|glBindBuffer} with <code>ARRAY_BUFFER</code>
   * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glBufferData.xml|glBufferData} with <code>ARRAY_BUFFER</code>
   */
  Buffer$1.createVertexBuffer = function (options) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("options.context", options.context);
    //>>includeEnd('debug');

    return new Buffer$1({
      context: options.context,
      bufferTarget: WebGLConstants$1.ARRAY_BUFFER,
      typedArray: options.typedArray,
      sizeInBytes: options.sizeInBytes,
      usage: options.usage,
    });
  };

  /**
   * Creates an index buffer, which contains typed indices in GPU-controlled memory.
   * <br /><br />
   * An index buffer can be attached to a vertex array to select vertices for rendering.
   * <code>Context.draw</code> can render using the entire index buffer or a subset
   * of the index buffer defined by an offset and count.
   *
   * @param {Object} options An object containing the following properties:
   * @param {Context} options.context The context in which to create the buffer
   * @param {ArrayBufferView} [options.typedArray] A typed array containing the data to copy to the buffer.
   * @param {Number} [options.sizeInBytes] A <code>Number</code> defining the size of the buffer in bytes. Required if options.typedArray is not given.
   * @param {BufferUsage} options.usage Specifies the expected usage pattern of the buffer. On some GL implementations, this can significantly affect performance. See {@link BufferUsage}.
   * @param {IndexDatatype} options.indexDatatype The datatype of indices in the buffer.
   * @returns {IndexBuffer} The index buffer, ready to be attached to a vertex array.
   *
   * @exception {DeveloperError} Must specify either <options.typedArray> or <options.sizeInBytes>, but not both.
   * @exception {DeveloperError} IndexDatatype.UNSIGNED_INT requires OES_element_index_uint, which is not supported on this system. Check context.elementIndexUint.
   * @exception {DeveloperError} The size in bytes must be greater than zero.
   * @exception {DeveloperError} Invalid <code>usage</code>.
   * @exception {DeveloperError} Invalid <code>indexDatatype</code>.
   *
   *
   * @example
   * // Example 1. Create a stream index buffer of unsigned shorts that is
   * // 16 bytes in size.
   * const buffer = Buffer.createIndexBuffer({
   *     context : context,
   *     sizeInBytes : 16,
   *     usage : BufferUsage.STREAM_DRAW,
   *     indexDatatype : IndexDatatype.UNSIGNED_SHORT
   * });
   *
   * @example
   * // Example 2. Create a static index buffer containing three unsigned shorts.
   * const buffer = Buffer.createIndexBuffer({
   *     context : context,
   *     typedArray : new Uint16Array([0, 1, 2]),
   *     usage : BufferUsage.STATIC_DRAW,
   *     indexDatatype : IndexDatatype.UNSIGNED_SHORT
   * });
   *
   * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGenBuffer.xml|glGenBuffer}
   * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glBindBuffer.xml|glBindBuffer} with <code>ELEMENT_ARRAY_BUFFER</code>
   * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glBufferData.xml|glBufferData} with <code>ELEMENT_ARRAY_BUFFER</code>
   */
  Buffer$1.createIndexBuffer = function (options) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("options.context", options.context);

    if (!IndexDatatype$1.validate(options.indexDatatype)) {
      throw new DeveloperError("Invalid indexDatatype.");
    }

    if (
      options.indexDatatype === IndexDatatype$1.UNSIGNED_INT &&
      !options.context.elementIndexUint
    ) {
      throw new DeveloperError(
        "IndexDatatype.UNSIGNED_INT requires OES_element_index_uint, which is not supported on this system.  Check context.elementIndexUint."
      );
    }
    //>>includeEnd('debug');

    const context = options.context;
    const indexDatatype = options.indexDatatype;

    const bytesPerIndex = IndexDatatype$1.getSizeInBytes(indexDatatype);
    const buffer = new Buffer$1({
      context: context,
      bufferTarget: WebGLConstants$1.ELEMENT_ARRAY_BUFFER,
      typedArray: options.typedArray,
      sizeInBytes: options.sizeInBytes,
      usage: options.usage,
    });

    const numberOfIndices = buffer.sizeInBytes / bytesPerIndex;

    Object.defineProperties(buffer, {
      indexDatatype: {
        get: function () {
          return indexDatatype;
        },
      },
      bytesPerIndex: {
        get: function () {
          return bytesPerIndex;
        },
      },
      numberOfIndices: {
        get: function () {
          return numberOfIndices;
        },
      },
    });

    return buffer;
  };

  Object.defineProperties(Buffer$1.prototype, {
    sizeInBytes: {
      get: function () {
        return this._sizeInBytes;
      },
    },

    usage: {
      get: function () {
        return this._usage;
      },
    },
  });

  Buffer$1.prototype._getBuffer = function () {
    return this._buffer;
  };

  Buffer$1.prototype.copyFromArrayView = function (arrayView, offsetInBytes) {
    offsetInBytes = defaultValue(offsetInBytes, 0);

    //>>includeStart('debug', pragmas.debug);
    Check.defined("arrayView", arrayView);
    Check.typeOf.number.lessThanOrEquals(
      "offsetInBytes + arrayView.byteLength",
      offsetInBytes + arrayView.byteLength,
      this._sizeInBytes
    );
    //>>includeEnd('debug');

    const gl = this._gl;
    const target = this._bufferTarget;
    gl.bindBuffer(target, this._buffer);
    gl.bufferSubData(target, offsetInBytes, arrayView);
    gl.bindBuffer(target, null);
  };

  Buffer$1.prototype.copyFromBuffer = function (
    readBuffer,
    readOffset,
    writeOffset,
    sizeInBytes
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!this._webgl2) {
      throw new DeveloperError("A WebGL 2 context is required.");
    }
    if (!defined(readBuffer)) {
      throw new DeveloperError("readBuffer must be defined.");
    }
    if (!defined(sizeInBytes) || sizeInBytes <= 0) {
      throw new DeveloperError(
        "sizeInBytes must be defined and be greater than zero."
      );
    }
    if (
      !defined(readOffset) ||
      readOffset < 0 ||
      readOffset + sizeInBytes > readBuffer._sizeInBytes
    ) {
      throw new DeveloperError(
        "readOffset must be greater than or equal to zero and readOffset + sizeInBytes must be less than of equal to readBuffer.sizeInBytes."
      );
    }
    if (
      !defined(writeOffset) ||
      writeOffset < 0 ||
      writeOffset + sizeInBytes > this._sizeInBytes
    ) {
      throw new DeveloperError(
        "writeOffset must be greater than or equal to zero and writeOffset + sizeInBytes must be less than of equal to this.sizeInBytes."
      );
    }
    if (
      this._buffer === readBuffer._buffer &&
      ((writeOffset >= readOffset && writeOffset < readOffset + sizeInBytes) ||
        (readOffset > writeOffset && readOffset < writeOffset + sizeInBytes))
    ) {
      throw new DeveloperError(
        "When readBuffer is equal to this, the ranges [readOffset + sizeInBytes) and [writeOffset, writeOffset + sizeInBytes) must not overlap."
      );
    }
    if (
      (this._bufferTarget === WebGLConstants$1.ELEMENT_ARRAY_BUFFER &&
        readBuffer._bufferTarget !== WebGLConstants$1.ELEMENT_ARRAY_BUFFER) ||
      (this._bufferTarget !== WebGLConstants$1.ELEMENT_ARRAY_BUFFER &&
        readBuffer._bufferTarget === WebGLConstants$1.ELEMENT_ARRAY_BUFFER)
    ) {
      throw new DeveloperError(
        "Can not copy an index buffer into another buffer type."
      );
    }
    //>>includeEnd('debug');

    const readTarget = WebGLConstants$1.COPY_READ_BUFFER;
    const writeTarget = WebGLConstants$1.COPY_WRITE_BUFFER;

    const gl = this._gl;
    gl.bindBuffer(writeTarget, this._buffer);
    gl.bindBuffer(readTarget, readBuffer._buffer);
    gl.copyBufferSubData(
      readTarget,
      writeTarget,
      readOffset,
      writeOffset,
      sizeInBytes
    );
    gl.bindBuffer(writeTarget, null);
    gl.bindBuffer(readTarget, null);
  };

  Buffer$1.prototype.getBufferData = function (
    arrayView,
    sourceOffset,
    destinationOffset,
    length
  ) {
    sourceOffset = defaultValue(sourceOffset, 0);
    destinationOffset = defaultValue(destinationOffset, 0);

    //>>includeStart('debug', pragmas.debug);
    if (!this._webgl2) {
      throw new DeveloperError("A WebGL 2 context is required.");
    }
    if (!defined(arrayView)) {
      throw new DeveloperError("arrayView is required.");
    }

    let copyLength;
    let elementSize;
    let arrayLength = arrayView.byteLength;
    if (!defined(length)) {
      if (defined(arrayLength)) {
        copyLength = arrayLength - destinationOffset;
        elementSize = 1;
      } else {
        arrayLength = arrayView.length;
        copyLength = arrayLength - destinationOffset;
        elementSize = arrayView.BYTES_PER_ELEMENT;
      }
    } else {
      copyLength = length;
      if (defined(arrayLength)) {
        elementSize = 1;
      } else {
        arrayLength = arrayView.length;
        elementSize = arrayView.BYTES_PER_ELEMENT;
      }
    }

    if (destinationOffset < 0 || destinationOffset > arrayLength) {
      throw new DeveloperError(
        "destinationOffset must be greater than zero and less than the arrayView length."
      );
    }
    if (destinationOffset + copyLength > arrayLength) {
      throw new DeveloperError(
        "destinationOffset + length must be less than or equal to the arrayViewLength."
      );
    }
    if (sourceOffset < 0 || sourceOffset > this._sizeInBytes) {
      throw new DeveloperError(
        "sourceOffset must be greater than zero and less than the buffers size."
      );
    }
    if (sourceOffset + copyLength * elementSize > this._sizeInBytes) {
      throw new DeveloperError(
        "sourceOffset + length must be less than the buffers size."
      );
    }
    //>>includeEnd('debug');

    const gl = this._gl;
    const target = WebGLConstants$1.COPY_READ_BUFFER;
    gl.bindBuffer(target, this._buffer);
    gl.getBufferSubData(
      target,
      sourceOffset,
      arrayView,
      destinationOffset,
      length
    );
    gl.bindBuffer(target, null);
  };

  Buffer$1.prototype.isDestroyed = function () {
    return false;
  };

  Buffer$1.prototype.destroy = function () {
    this._gl.deleteBuffer(this._buffer);
    return destroyObject(this);
  };

  function addAttribute(attributes, attribute, index, context) {
    const hasVertexBuffer = defined(attribute.vertexBuffer);
    const hasValue = defined(attribute.value);
    const componentsPerAttribute = attribute.value
      ? attribute.value.length
      : attribute.componentsPerAttribute;

    //>>includeStart('debug', pragmas.debug);
    if (!hasVertexBuffer && !hasValue) {
      throw new DeveloperError("attribute must have a vertexBuffer or a value.");
    }
    if (hasVertexBuffer && hasValue) {
      throw new DeveloperError(
        "attribute cannot have both a vertexBuffer and a value.  It must have either a vertexBuffer property defining per-vertex data or a value property defining data for all vertices."
      );
    }
    if (
      componentsPerAttribute !== 1 &&
      componentsPerAttribute !== 2 &&
      componentsPerAttribute !== 3 &&
      componentsPerAttribute !== 4
    ) {
      if (hasValue) {
        throw new DeveloperError(
          "attribute.value.length must be in the range [1, 4]."
        );
      }

      throw new DeveloperError(
        "attribute.componentsPerAttribute must be in the range [1, 4]."
      );
    }
    if (
      defined(attribute.componentDatatype) &&
      !ComponentDatatype$1.validate(attribute.componentDatatype)
    ) {
      throw new DeveloperError(
        "attribute must have a valid componentDatatype or not specify it."
      );
    }
    if (defined(attribute.strideInBytes) && attribute.strideInBytes > 255) {
      // WebGL limit.  Not in GL ES.
      throw new DeveloperError(
        "attribute must have a strideInBytes less than or equal to 255 or not specify it."
      );
    }
    if (
      defined(attribute.instanceDivisor) &&
      attribute.instanceDivisor > 0 &&
      !context.instancedArrays
    ) {
      throw new DeveloperError("instanced arrays is not supported");
    }
    if (defined(attribute.instanceDivisor) && attribute.instanceDivisor < 0) {
      throw new DeveloperError(
        "attribute must have an instanceDivisor greater than or equal to zero"
      );
    }
    if (defined(attribute.instanceDivisor) && hasValue) {
      throw new DeveloperError(
        "attribute cannot have have an instanceDivisor if it is not backed by a buffer"
      );
    }
    if (
      defined(attribute.instanceDivisor) &&
      attribute.instanceDivisor > 0 &&
      attribute.index === 0
    ) {
      throw new DeveloperError(
        "attribute zero cannot have an instanceDivisor greater than 0"
      );
    }
    //>>includeEnd('debug');

    // Shallow copy the attribute; we do not want to copy the vertex buffer.
    const attr = {
      index: defaultValue(attribute.index, index),
      enabled: defaultValue(attribute.enabled, true),
      vertexBuffer: attribute.vertexBuffer,
      value: hasValue ? attribute.value.slice(0) : undefined,
      componentsPerAttribute: componentsPerAttribute,
      componentDatatype: defaultValue(
        attribute.componentDatatype,
        ComponentDatatype$1.FLOAT
      ),
      normalize: defaultValue(attribute.normalize, false),
      offsetInBytes: defaultValue(attribute.offsetInBytes, 0),
      strideInBytes: defaultValue(attribute.strideInBytes, 0),
      instanceDivisor: defaultValue(attribute.instanceDivisor, 0),
    };

    if (hasVertexBuffer) {
      // Common case: vertex buffer for per-vertex data
      attr.vertexAttrib = function (gl) {
        const index = this.index;
        gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer._getBuffer());
        gl.vertexAttribPointer(
          index,
          this.componentsPerAttribute,
          this.componentDatatype,
          this.normalize,
          this.strideInBytes,
          this.offsetInBytes
        );
        gl.enableVertexAttribArray(index);
        if (this.instanceDivisor > 0) {
          context.glVertexAttribDivisor(index, this.instanceDivisor);
          context._vertexAttribDivisors[index] = this.instanceDivisor;
          context._previousDrawInstanced = true;
        }
      };

      attr.disableVertexAttribArray = function (gl) {
        gl.disableVertexAttribArray(this.index);
        if (this.instanceDivisor > 0) {
          context.glVertexAttribDivisor(index, 0);
        }
      };
    } else {
      // Less common case: value array for the same data for each vertex
      switch (attr.componentsPerAttribute) {
        case 1:
          attr.vertexAttrib = function (gl) {
            gl.vertexAttrib1fv(this.index, this.value);
          };
          break;
        case 2:
          attr.vertexAttrib = function (gl) {
            gl.vertexAttrib2fv(this.index, this.value);
          };
          break;
        case 3:
          attr.vertexAttrib = function (gl) {
            gl.vertexAttrib3fv(this.index, this.value);
          };
          break;
        case 4:
          attr.vertexAttrib = function (gl) {
            gl.vertexAttrib4fv(this.index, this.value);
          };
          break;
      }

      attr.disableVertexAttribArray = function (gl) {};
    }

    attributes.push(attr);
  }

  function bind(gl, attributes, indexBuffer) {
    for (let i = 0; i < attributes.length; ++i) {
      const attribute = attributes[i];
      if (attribute.enabled) {
        attribute.vertexAttrib(gl);
      }
    }

    if (defined(indexBuffer)) {
      gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer._getBuffer());
    }
  }

  /**
   * Creates a vertex array, which defines the attributes making up a vertex, and contains an optional index buffer
   * to select vertices for rendering.  Attributes are defined using object literals as shown in Example 1 below.
   *
   * @param {Object} options Object with the following properties:
   * @param {Context} options.context The context in which the VertexArray gets created.
   * @param {Object[]} options.attributes An array of attributes.
   * @param {IndexBuffer} [options.indexBuffer] An optional index buffer.
   *
   * @returns {VertexArray} The vertex array, ready for use with drawing.
   *
   * @exception {DeveloperError} Attribute must have a <code>vertexBuffer</code>.
   * @exception {DeveloperError} Attribute must have a <code>componentsPerAttribute</code>.
   * @exception {DeveloperError} Attribute must have a valid <code>componentDatatype</code> or not specify it.
   * @exception {DeveloperError} Attribute must have a <code>strideInBytes</code> less than or equal to 255 or not specify it.
   * @exception {DeveloperError} Index n is used by more than one attribute.
   *
   *
   * @example
   * // Example 1. Create a vertex array with vertices made up of three floating point
   * // values, e.g., a position, from a single vertex buffer.  No index buffer is used.
   * const positionBuffer = Buffer.createVertexBuffer({
   *     context : context,
   *     sizeInBytes : 12,
   *     usage : BufferUsage.STATIC_DRAW
   * });
   * const attributes = [
   *     {
   *         index                  : 0,
   *         enabled                : true,
   *         vertexBuffer           : positionBuffer,
   *         componentsPerAttribute : 3,
   *         componentDatatype      : ComponentDatatype.FLOAT,
   *         normalize              : false,
   *         offsetInBytes          : 0,
   *         strideInBytes          : 0 // tightly packed
   *         instanceDivisor        : 0 // not instanced
   *     }
   * ];
   * const va = new VertexArray({
   *     context : context,
   *     attributes : attributes
   * });
   *
   * @example
   * // Example 2. Create a vertex array with vertices from two different vertex buffers.
   * // Each vertex has a three-component position and three-component normal.
   * const positionBuffer = Buffer.createVertexBuffer({
   *     context : context,
   *     sizeInBytes : 12,
   *     usage : BufferUsage.STATIC_DRAW
   * });
   * const normalBuffer = Buffer.createVertexBuffer({
   *     context : context,
   *     sizeInBytes : 12,
   *     usage : BufferUsage.STATIC_DRAW
   * });
   * const attributes = [
   *     {
   *         index                  : 0,
   *         vertexBuffer           : positionBuffer,
   *         componentsPerAttribute : 3,
   *         componentDatatype      : ComponentDatatype.FLOAT
   *     },
   *     {
   *         index                  : 1,
   *         vertexBuffer           : normalBuffer,
   *         componentsPerAttribute : 3,
   *         componentDatatype      : ComponentDatatype.FLOAT
   *     }
   * ];
   * const va = new VertexArray({
   *     context : context,
   *     attributes : attributes
   * });
   *
   * @example
   * // Example 3. Creates the same vertex layout as Example 2 using a single
   * // vertex buffer, instead of two.
   * const buffer = Buffer.createVertexBuffer({
   *     context : context,
   *     sizeInBytes : 24,
   *     usage : BufferUsage.STATIC_DRAW
   * });
   * const attributes = [
   *     {
   *         vertexBuffer           : buffer,
   *         componentsPerAttribute : 3,
   *         componentDatatype      : ComponentDatatype.FLOAT,
   *         offsetInBytes          : 0,
   *         strideInBytes          : 24
   *     },
   *     {
   *         vertexBuffer           : buffer,
   *         componentsPerAttribute : 3,
   *         componentDatatype      : ComponentDatatype.FLOAT,
   *         normalize              : true,
   *         offsetInBytes          : 12,
   *         strideInBytes          : 24
   *     }
   * ];
   * const va = new VertexArray({
   *     context : context,
   *     attributes : attributes
   * });
   *
   * @see Buffer#createVertexBuffer
   * @see Buffer#createIndexBuffer
   * @see Context#draw
   *
   * @private
   */
  function VertexArray(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    Check.defined("options.context", options.context);
    Check.defined("options.attributes", options.attributes);
    //>>includeEnd('debug');

    const context = options.context;
    const gl = context._gl;
    const attributes = options.attributes;
    const indexBuffer = options.indexBuffer;

    let i;
    const vaAttributes = [];
    let numberOfVertices = 1; // if every attribute is backed by a single value
    let hasInstancedAttributes = false;
    let hasConstantAttributes = false;

    let length = attributes.length;
    for (i = 0; i < length; ++i) {
      addAttribute(vaAttributes, attributes[i], i, context);
    }

    length = vaAttributes.length;
    for (i = 0; i < length; ++i) {
      const attribute = vaAttributes[i];

      if (defined(attribute.vertexBuffer) && attribute.instanceDivisor === 0) {
        // This assumes that each vertex buffer in the vertex array has the same number of vertices.
        const bytes =
          attribute.strideInBytes ||
          attribute.componentsPerAttribute *
            ComponentDatatype$1.getSizeInBytes(attribute.componentDatatype);
        numberOfVertices = attribute.vertexBuffer.sizeInBytes / bytes;
        break;
      }
    }

    for (i = 0; i < length; ++i) {
      if (vaAttributes[i].instanceDivisor > 0) {
        hasInstancedAttributes = true;
      }
      if (defined(vaAttributes[i].value)) {
        hasConstantAttributes = true;
      }
    }

    //>>includeStart('debug', pragmas.debug);
    // Verify all attribute names are unique
    const uniqueIndices = {};
    for (i = 0; i < length; ++i) {
      const index = vaAttributes[i].index;
      if (uniqueIndices[index]) {
        throw new DeveloperError(
          `Index ${index} is used by more than one attribute.`
        );
      }
      uniqueIndices[index] = true;
    }
    //>>includeEnd('debug');

    let vao;

    // Setup VAO if supported
    if (context.vertexArrayObject) {
      vao = context.glCreateVertexArray();
      context.glBindVertexArray(vao);
      bind(gl, vaAttributes, indexBuffer);
      context.glBindVertexArray(null);
    }

    this._numberOfVertices = numberOfVertices;
    this._hasInstancedAttributes = hasInstancedAttributes;
    this._hasConstantAttributes = hasConstantAttributes;
    this._context = context;
    this._gl = gl;
    this._vao = vao;
    this._attributes = vaAttributes;
    this._indexBuffer = indexBuffer;
  }

  function computeNumberOfVertices(attribute) {
    return attribute.values.length / attribute.componentsPerAttribute;
  }

  function computeAttributeSizeInBytes(attribute) {
    return (
      ComponentDatatype$1.getSizeInBytes(attribute.componentDatatype) *
      attribute.componentsPerAttribute
    );
  }

  function interleaveAttributes(attributes) {
    let j;
    let name;
    let attribute;

    // Extract attribute names.
    const names = [];
    for (name in attributes) {
      // Attribute needs to have per-vertex values; not a constant value for all vertices.
      if (
        attributes.hasOwnProperty(name) &&
        defined(attributes[name]) &&
        defined(attributes[name].values)
      ) {
        names.push(name);

        if (attributes[name].componentDatatype === ComponentDatatype$1.DOUBLE) {
          attributes[name].componentDatatype = ComponentDatatype$1.FLOAT;
          attributes[name].values = ComponentDatatype$1.createTypedArray(
            ComponentDatatype$1.FLOAT,
            attributes[name].values
          );
        }
      }
    }

    // Validation.  Compute number of vertices.
    let numberOfVertices;
    const namesLength = names.length;

    if (namesLength > 0) {
      numberOfVertices = computeNumberOfVertices(attributes[names[0]]);

      for (j = 1; j < namesLength; ++j) {
        const currentNumberOfVertices = computeNumberOfVertices(
          attributes[names[j]]
        );

        if (currentNumberOfVertices !== numberOfVertices) {
          throw new RuntimeError(
            `${
            "Each attribute list must have the same number of vertices.  " +
            "Attribute "
          }${names[j]} has a different number of vertices ` +
              `(${currentNumberOfVertices.toString()})` +
              ` than attribute ${names[0]} (${numberOfVertices.toString()}).`
          );
        }
      }
    }

    // Sort attributes by the size of their components.  From left to right, a vertex stores floats, shorts, and then bytes.
    names.sort(function (left, right) {
      return (
        ComponentDatatype$1.getSizeInBytes(attributes[right].componentDatatype) -
        ComponentDatatype$1.getSizeInBytes(attributes[left].componentDatatype)
      );
    });

    // Compute sizes and strides.
    let vertexSizeInBytes = 0;
    const offsetsInBytes = {};

    for (j = 0; j < namesLength; ++j) {
      name = names[j];
      attribute = attributes[name];

      offsetsInBytes[name] = vertexSizeInBytes;
      vertexSizeInBytes += computeAttributeSizeInBytes(attribute);
    }

    if (vertexSizeInBytes > 0) {
      // Pad each vertex to be a multiple of the largest component datatype so each
      // attribute can be addressed using typed arrays.
      const maxComponentSizeInBytes = ComponentDatatype$1.getSizeInBytes(
        attributes[names[0]].componentDatatype
      ); // Sorted large to small
      const remainder = vertexSizeInBytes % maxComponentSizeInBytes;
      if (remainder !== 0) {
        vertexSizeInBytes += maxComponentSizeInBytes - remainder;
      }

      // Total vertex buffer size in bytes, including per-vertex padding.
      const vertexBufferSizeInBytes = numberOfVertices * vertexSizeInBytes;

      // Create array for interleaved vertices.  Each attribute has a different view (pointer) into the array.
      const buffer = new ArrayBuffer(vertexBufferSizeInBytes);
      const views = {};

      for (j = 0; j < namesLength; ++j) {
        name = names[j];
        const sizeInBytes = ComponentDatatype$1.getSizeInBytes(
          attributes[name].componentDatatype
        );

        views[name] = {
          pointer: ComponentDatatype$1.createTypedArray(
            attributes[name].componentDatatype,
            buffer
          ),
          index: offsetsInBytes[name] / sizeInBytes, // Offset in ComponentType
          strideInComponentType: vertexSizeInBytes / sizeInBytes,
        };
      }

      // Copy attributes into one interleaved array.
      // PERFORMANCE_IDEA:  Can we optimize these loops?
      for (j = 0; j < numberOfVertices; ++j) {
        for (let n = 0; n < namesLength; ++n) {
          name = names[n];
          attribute = attributes[name];
          const values = attribute.values;
          const view = views[name];
          const pointer = view.pointer;

          const numberOfComponents = attribute.componentsPerAttribute;
          for (let k = 0; k < numberOfComponents; ++k) {
            pointer[view.index + k] = values[j * numberOfComponents + k];
          }

          view.index += view.strideInComponentType;
        }
      }

      return {
        buffer: buffer,
        offsetsInBytes: offsetsInBytes,
        vertexSizeInBytes: vertexSizeInBytes,
      };
    }

    // No attributes to interleave.
    return undefined;
  }

  /**
   * Creates a vertex array from a geometry.  A geometry contains vertex attributes and optional index data
   * in system memory, whereas a vertex array contains vertex buffers and an optional index buffer in WebGL
   * memory for use with rendering.
   * <br /><br />
   * The <code>geometry</code> argument should use the standard layout like the geometry returned by {@link BoxGeometry}.
   * <br /><br />
   * <code>options</code> can have four properties:
   * <ul>
   *   <li><code>geometry</code>:  The source geometry containing data used to create the vertex array.</li>
   *   <li><code>attributeLocations</code>:  An object that maps geometry attribute names to vertex shader attribute locations.</li>
   *   <li><code>bufferUsage</code>:  The expected usage pattern of the vertex array's buffers.  On some WebGL implementations, this can significantly affect performance.  See {@link BufferUsage}.  Default: <code>BufferUsage.DYNAMIC_DRAW</code>.</li>
   *   <li><code>interleave</code>:  Determines if all attributes are interleaved in a single vertex buffer or if each attribute is stored in a separate vertex buffer.  Default: <code>false</code>.</li>
   * </ul>
   * <br />
   * If <code>options</code> is not specified or the <code>geometry</code> contains no data, the returned vertex array is empty.
   *
   * @param {Object} options An object defining the geometry, attribute indices, buffer usage, and vertex layout used to create the vertex array.
   *
   * @exception {RuntimeError} Each attribute list must have the same number of vertices.
   * @exception {DeveloperError} The geometry must have zero or one index lists.
   * @exception {DeveloperError} Index n is used by more than one attribute.
   *
   *
   * @example
   * // Example 1. Creates a vertex array for rendering a box.  The default dynamic draw
   * // usage is used for the created vertex and index buffer.  The attributes are not
   * // interleaved by default.
   * const geometry = new BoxGeometry();
   * const va = VertexArray.fromGeometry({
   *     context            : context,
   *     geometry           : geometry,
   *     attributeLocations : GeometryPipeline.createAttributeLocations(geometry),
   * });
   *
   * @example
   * // Example 2. Creates a vertex array with interleaved attributes in a
   * // single vertex buffer.  The vertex and index buffer have static draw usage.
   * const va = VertexArray.fromGeometry({
   *     context            : context,
   *     geometry           : geometry,
   *     attributeLocations : GeometryPipeline.createAttributeLocations(geometry),
   *     bufferUsage        : BufferUsage.STATIC_DRAW,
   *     interleave         : true
   * });
   *
   * @example
   * // Example 3.  When the caller destroys the vertex array, it also destroys the
   * // attached vertex buffer(s) and index buffer.
   * va = va.destroy();
   *
   * @see Buffer#createVertexBuffer
   * @see Buffer#createIndexBuffer
   * @see GeometryPipeline.createAttributeLocations
   * @see ShaderProgram
   */
  VertexArray.fromGeometry = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    Check.defined("options.context", options.context);
    //>>includeEnd('debug');

    const context = options.context;
    const geometry = defaultValue(options.geometry, defaultValue.EMPTY_OBJECT);

    const bufferUsage = defaultValue(
      options.bufferUsage,
      BufferUsage$1.DYNAMIC_DRAW
    );

    const attributeLocations = defaultValue(
      options.attributeLocations,
      defaultValue.EMPTY_OBJECT
    );
    const interleave = defaultValue(options.interleave, false);
    const createdVAAttributes = options.vertexArrayAttributes;

    let name;
    let attribute;
    let vertexBuffer;
    const vaAttributes = defined(createdVAAttributes) ? createdVAAttributes : [];
    const attributes = geometry.attributes;

    if (interleave) {
      // Use a single vertex buffer with interleaved vertices.
      const interleavedAttributes = interleaveAttributes(attributes);
      if (defined(interleavedAttributes)) {
        vertexBuffer = Buffer$1.createVertexBuffer({
          context: context,
          typedArray: interleavedAttributes.buffer,
          usage: bufferUsage,
        });
        const offsetsInBytes = interleavedAttributes.offsetsInBytes;
        const strideInBytes = interleavedAttributes.vertexSizeInBytes;

        for (name in attributes) {
          if (attributes.hasOwnProperty(name) && defined(attributes[name])) {
            attribute = attributes[name];

            if (defined(attribute.values)) {
              // Common case: per-vertex attributes
              vaAttributes.push({
                index: attributeLocations[name],
                vertexBuffer: vertexBuffer,
                componentDatatype: attribute.componentDatatype,
                componentsPerAttribute: attribute.componentsPerAttribute,
                normalize: attribute.normalize,
                offsetInBytes: offsetsInBytes[name],
                strideInBytes: strideInBytes,
              });
            } else {
              // Constant attribute for all vertices
              vaAttributes.push({
                index: attributeLocations[name],
                value: attribute.value,
                componentDatatype: attribute.componentDatatype,
                normalize: attribute.normalize,
              });
            }
          }
        }
      }
    } else {
      // One vertex buffer per attribute.
      for (name in attributes) {
        if (attributes.hasOwnProperty(name) && defined(attributes[name])) {
          attribute = attributes[name];

          let componentDatatype = attribute.componentDatatype;
          if (componentDatatype === ComponentDatatype$1.DOUBLE) {
            componentDatatype = ComponentDatatype$1.FLOAT;
          }

          vertexBuffer = undefined;
          if (defined(attribute.values)) {
            vertexBuffer = Buffer$1.createVertexBuffer({
              context: context,
              typedArray: ComponentDatatype$1.createTypedArray(
                componentDatatype,
                attribute.values
              ),
              usage: bufferUsage,
            });
          }

          vaAttributes.push({
            index: attributeLocations[name],
            vertexBuffer: vertexBuffer,
            value: attribute.value,
            componentDatatype: componentDatatype,
            componentsPerAttribute: attribute.componentsPerAttribute,
            normalize: attribute.normalize,
          });
        }
      }
    }

    let indexBuffer;
    const indices = geometry.indices;
    if (defined(indices)) {
      if (
        Geometry.computeNumberOfVertices(geometry) >=
          CesiumMath.SIXTY_FOUR_KILOBYTES &&
        context.elementIndexUint
      ) {
        indexBuffer = Buffer$1.createIndexBuffer({
          context: context,
          typedArray: new Uint32Array(indices),
          usage: bufferUsage,
          indexDatatype: IndexDatatype$1.UNSIGNED_INT,
        });
      } else {
        indexBuffer = Buffer$1.createIndexBuffer({
          context: context,
          typedArray: new Uint16Array(indices),
          usage: bufferUsage,
          indexDatatype: IndexDatatype$1.UNSIGNED_SHORT,
        });
      }
    }

    return new VertexArray({
      context: context,
      attributes: vaAttributes,
      indexBuffer: indexBuffer,
    });
  };

  Object.defineProperties(VertexArray.prototype, {
    numberOfAttributes: {
      get: function () {
        return this._attributes.length;
      },
    },
    numberOfVertices: {
      get: function () {
        return this._numberOfVertices;
      },
    },
    indexBuffer: {
      get: function () {
        return this._indexBuffer;
      },
    },
  });

  /**
   * index is the location in the array of attributes, not the index property of an attribute.
   */
  VertexArray.prototype.getAttribute = function (index) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("index", index);
    //>>includeEnd('debug');

    return this._attributes[index];
  };

  // Workaround for ANGLE, where the attribute divisor seems to be part of the global state instead
  // of the VAO state. This function is called when the vao is bound, and should be removed
  // once the ANGLE issue is resolved. Setting the divisor should normally happen in vertexAttrib and
  // disableVertexAttribArray.
  function setVertexAttribDivisor(vertexArray) {
    const context = vertexArray._context;
    const hasInstancedAttributes = vertexArray._hasInstancedAttributes;
    if (!hasInstancedAttributes && !context._previousDrawInstanced) {
      return;
    }
    context._previousDrawInstanced = hasInstancedAttributes;

    const divisors = context._vertexAttribDivisors;
    const attributes = vertexArray._attributes;
    const maxAttributes = ContextLimits.maximumVertexAttributes;
    let i;

    if (hasInstancedAttributes) {
      const length = attributes.length;
      for (i = 0; i < length; ++i) {
        const attribute = attributes[i];
        if (attribute.enabled) {
          const divisor = attribute.instanceDivisor;
          const index = attribute.index;
          if (divisor !== divisors[index]) {
            context.glVertexAttribDivisor(index, divisor);
            divisors[index] = divisor;
          }
        }
      }
    } else {
      for (i = 0; i < maxAttributes; ++i) {
        if (divisors[i] > 0) {
          context.glVertexAttribDivisor(i, 0);
          divisors[i] = 0;
        }
      }
    }
  }

  // Vertex attributes backed by a constant value go through vertexAttrib[1234]f[v]
  // which is part of context state rather than VAO state.
  function setConstantAttributes(vertexArray, gl) {
    const attributes = vertexArray._attributes;
    const length = attributes.length;
    for (let i = 0; i < length; ++i) {
      const attribute = attributes[i];
      if (attribute.enabled && defined(attribute.value)) {
        attribute.vertexAttrib(gl);
      }
    }
  }

  VertexArray.prototype._bind = function () {
    if (defined(this._vao)) {
      this._context.glBindVertexArray(this._vao);
      if (this._context.instancedArrays) {
        setVertexAttribDivisor(this);
      }
      if (this._hasConstantAttributes) {
        setConstantAttributes(this, this._gl);
      }
    } else {
      bind(this._gl, this._attributes, this._indexBuffer);
    }
  };

  VertexArray.prototype._unBind = function () {
    if (defined(this._vao)) {
      this._context.glBindVertexArray(null);
    } else {
      const attributes = this._attributes;
      const gl = this._gl;

      for (let i = 0; i < attributes.length; ++i) {
        const attribute = attributes[i];
        if (attribute.enabled) {
          attribute.disableVertexAttribArray(gl);
        }
      }
      if (this._indexBuffer) {
        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
      }
    }
  };

  VertexArray.prototype.isDestroyed = function () {
    return false;
  };

  VertexArray.prototype.destroy = function () {
    const attributes = this._attributes;
    for (let i = 0; i < attributes.length; ++i) {
      const vertexBuffer = attributes[i].vertexBuffer;
      if (
        defined(vertexBuffer) &&
        !vertexBuffer.isDestroyed() &&
        vertexBuffer.vertexArrayDestroyable
      ) {
        vertexBuffer.destroy();
      }
    }

    const indexBuffer = this._indexBuffer;
    if (
      defined(indexBuffer) &&
      !indexBuffer.isDestroyed() &&
      indexBuffer.vertexArrayDestroyable
    ) {
      indexBuffer.destroy();
    }

    if (defined(this._vao)) {
      this._context.glDeleteVertexArray(this._vao);
    }

    return destroyObject(this);
  };

  /**
   * Creates a texture to look up per instance attributes for batched primitives. For example, store each primitive's pick color in the texture.
   *
   * @alias BatchTable
   * @constructor
   * @private
   *
   * @param {Context} context The context in which the batch table is created.
   * @param {Object[]} attributes An array of objects describing a per instance attribute. Each object contains a datatype, components per attributes, whether it is normalized and a function name
   *     to retrieve the value in the vertex shader.
   * @param {Number} numberOfInstances The number of instances in a batch table.
   *
   * @example
   * // create the batch table
   * const attributes = [{
   *     functionName : 'getShow',
   *     componentDatatype : ComponentDatatype.UNSIGNED_BYTE,
   *     componentsPerAttribute : 1
   * }, {
   *     functionName : 'getPickColor',
   *     componentDatatype : ComponentDatatype.UNSIGNED_BYTE,
   *     componentsPerAttribute : 4,
   *     normalize : true
   * }];
   * const batchTable = new BatchTable(context, attributes, 5);
   *
   * // when creating the draw commands, update the uniform map and the vertex shader
   * vertexShaderSource = batchTable.getVertexShaderCallback()(vertexShaderSource);
   * const shaderProgram = ShaderProgram.fromCache({
   *    // ...
   *    vertexShaderSource : vertexShaderSource,
   * });
   *
   * drawCommand.shaderProgram = shaderProgram;
   * drawCommand.uniformMap = batchTable.getUniformMapCallback()(uniformMap);
   *
   * // use the attribute function names in the shader to retrieve the instance values
   * // ...
   * attribute float batchId;
   *
   * void main() {
   *     // ...
   *     float show = getShow(batchId);
   *     vec3 pickColor = getPickColor(batchId);
   *     // ...
   * }
   */
  function BatchTable(context, attributes, numberOfInstances) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(context)) {
      throw new DeveloperError("context is required");
    }
    if (!defined(attributes)) {
      throw new DeveloperError("attributes is required");
    }
    if (!defined(numberOfInstances)) {
      throw new DeveloperError("numberOfInstances is required");
    }
    //>>includeEnd('debug');

    this._attributes = attributes;
    this._numberOfInstances = numberOfInstances;

    if (attributes.length === 0) {
      return;
    }

    // PERFORMANCE_IDEA: We may be able to arrange the attributes so they can be packing into fewer texels.
    // Right now, an attribute with one component uses an entire texel when 4 single component attributes can
    // be packed into a texel.
    //
    // Packing floats into unsigned byte textures makes the problem worse. A single component float attribute
    // will be packed into a single texel leaving 3 texels unused. 4 texels are reserved for each float attribute
    // regardless of how many components it has.
    const pixelDatatype = getDatatype(attributes);
    const textureFloatSupported = context.floatingPointTexture;
    const packFloats =
      pixelDatatype === PixelDatatype$1.FLOAT && !textureFloatSupported;
    const offsets = createOffsets(attributes, packFloats);

    const stride = getStride(offsets, attributes, packFloats);
    const maxNumberOfInstancesPerRow = Math.floor(
      ContextLimits.maximumTextureSize / stride
    );

    const instancesPerWidth = Math.min(
      numberOfInstances,
      maxNumberOfInstancesPerRow
    );
    const width = stride * instancesPerWidth;
    const height = Math.ceil(numberOfInstances / instancesPerWidth);

    const stepX = 1.0 / width;
    const centerX = stepX * 0.5;
    const stepY = 1.0 / height;
    const centerY = stepY * 0.5;

    this._textureDimensions = new Cartesian2(width, height);
    this._textureStep = new Cartesian4(stepX, centerX, stepY, centerY);
    this._pixelDatatype = !packFloats
      ? pixelDatatype
      : PixelDatatype$1.UNSIGNED_BYTE;
    this._packFloats = packFloats;
    this._offsets = offsets;
    this._stride = stride;
    this._texture = undefined;

    const batchLength = 4 * width * height;
    this._batchValues =
      pixelDatatype === PixelDatatype$1.FLOAT && !packFloats
        ? new Float32Array(batchLength)
        : new Uint8Array(batchLength);
    this._batchValuesDirty = false;
  }

  Object.defineProperties(BatchTable.prototype, {
    /**
     * The attribute descriptions.
     * @memberOf BatchTable.prototype
     * @type {Object[]}
     * @readonly
     */
    attributes: {
      get: function () {
        return this._attributes;
      },
    },
    /**
     * The number of instances.
     * @memberOf BatchTable.prototype
     * @type {Number}
     * @readonly
     */
    numberOfInstances: {
      get: function () {
        return this._numberOfInstances;
      },
    },
  });

  function getDatatype(attributes) {
    let foundFloatDatatype = false;
    const length = attributes.length;
    for (let i = 0; i < length; ++i) {
      if (attributes[i].componentDatatype !== ComponentDatatype$1.UNSIGNED_BYTE) {
        foundFloatDatatype = true;
        break;
      }
    }
    return foundFloatDatatype ? PixelDatatype$1.FLOAT : PixelDatatype$1.UNSIGNED_BYTE;
  }

  function getAttributeType(attributes, attributeIndex) {
    const componentsPerAttribute =
      attributes[attributeIndex].componentsPerAttribute;
    if (componentsPerAttribute === 2) {
      return Cartesian2;
    } else if (componentsPerAttribute === 3) {
      return Cartesian3;
    } else if (componentsPerAttribute === 4) {
      return Cartesian4;
    }
    return Number;
  }

  function createOffsets(attributes, packFloats) {
    const offsets = new Array(attributes.length);

    let currentOffset = 0;
    const attributesLength = attributes.length;
    for (let i = 0; i < attributesLength; ++i) {
      const attribute = attributes[i];
      const componentDatatype = attribute.componentDatatype;

      offsets[i] = currentOffset;

      if (componentDatatype !== ComponentDatatype$1.UNSIGNED_BYTE && packFloats) {
        currentOffset += 4;
      } else {
        ++currentOffset;
      }
    }

    return offsets;
  }

  function getStride(offsets, attributes, packFloats) {
    const length = offsets.length;
    const lastOffset = offsets[length - 1];
    const lastAttribute = attributes[length - 1];
    const componentDatatype = lastAttribute.componentDatatype;

    if (componentDatatype !== ComponentDatatype$1.UNSIGNED_BYTE && packFloats) {
      return lastOffset + 4;
    }
    return lastOffset + 1;
  }

  const scratchPackedFloatCartesian4 = new Cartesian4();

  function getPackedFloat(array, index, result) {
    let packed = Cartesian4.unpack(array, index, scratchPackedFloatCartesian4);
    const x = Cartesian4.unpackFloat(packed);

    packed = Cartesian4.unpack(array, index + 4, scratchPackedFloatCartesian4);
    const y = Cartesian4.unpackFloat(packed);

    packed = Cartesian4.unpack(array, index + 8, scratchPackedFloatCartesian4);
    const z = Cartesian4.unpackFloat(packed);

    packed = Cartesian4.unpack(array, index + 12, scratchPackedFloatCartesian4);
    const w = Cartesian4.unpackFloat(packed);

    return Cartesian4.fromElements(x, y, z, w, result);
  }

  function setPackedAttribute(value, array, index) {
    let packed = Cartesian4.packFloat(value.x, scratchPackedFloatCartesian4);
    Cartesian4.pack(packed, array, index);

    packed = Cartesian4.packFloat(value.y, packed);
    Cartesian4.pack(packed, array, index + 4);

    packed = Cartesian4.packFloat(value.z, packed);
    Cartesian4.pack(packed, array, index + 8);

    packed = Cartesian4.packFloat(value.w, packed);
    Cartesian4.pack(packed, array, index + 12);
  }

  const scratchGetAttributeCartesian4$1 = new Cartesian4();

  /**
   * Gets the value of an attribute in the table.
   *
   * @param {Number} instanceIndex The index of the instance.
   * @param {Number} attributeIndex The index of the attribute.
   * @param {undefined|Cartesian2|Cartesian3|Cartesian4} [result] The object onto which to store the result. The type is dependent on the attribute's number of components.
   * @returns {Number|Cartesian2|Cartesian3|Cartesian4} The attribute value stored for the instance.
   *
   * @exception {DeveloperError} instanceIndex is out of range.
   * @exception {DeveloperError} attributeIndex is out of range.
   */
  BatchTable.prototype.getBatchedAttribute = function (
    instanceIndex,
    attributeIndex,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (instanceIndex < 0 || instanceIndex >= this._numberOfInstances) {
      throw new DeveloperError("instanceIndex is out of range.");
    }
    if (attributeIndex < 0 || attributeIndex >= this._attributes.length) {
      throw new DeveloperError("attributeIndex is out of range");
    }
    //>>includeEnd('debug');

    const attributes = this._attributes;
    const offset = this._offsets[attributeIndex];
    const stride = this._stride;

    const index = 4 * stride * instanceIndex + 4 * offset;
    let value;

    if (
      this._packFloats &&
      attributes[attributeIndex].componentDatatype !== PixelDatatype$1.UNSIGNED_BYTE
    ) {
      value = getPackedFloat(
        this._batchValues,
        index,
        scratchGetAttributeCartesian4$1
      );
    } else {
      value = Cartesian4.unpack(
        this._batchValues,
        index,
        scratchGetAttributeCartesian4$1
      );
    }

    const attributeType = getAttributeType(attributes, attributeIndex);
    if (defined(attributeType.fromCartesian4)) {
      return attributeType.fromCartesian4(value, result);
    } else if (defined(attributeType.clone)) {
      return attributeType.clone(value, result);
    }

    return value.x;
  };

  const setAttributeScratchValues = [
    undefined,
    undefined,
    new Cartesian2(),
    new Cartesian3(),
    new Cartesian4(),
  ];
  const setAttributeScratchCartesian4 = new Cartesian4();

  /**
   * Sets the value of an attribute in the table.
   *
   * @param {Number} instanceIndex The index of the instance.
   * @param {Number} attributeIndex The index of the attribute.
   * @param {Number|Cartesian2|Cartesian3|Cartesian4} value The value to be stored in the table. The type of value will depend on the number of components of the attribute.
   *
   * @exception {DeveloperError} instanceIndex is out of range.
   * @exception {DeveloperError} attributeIndex is out of range.
   */
  BatchTable.prototype.setBatchedAttribute = function (
    instanceIndex,
    attributeIndex,
    value
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (instanceIndex < 0 || instanceIndex >= this._numberOfInstances) {
      throw new DeveloperError("instanceIndex is out of range.");
    }
    if (attributeIndex < 0 || attributeIndex >= this._attributes.length) {
      throw new DeveloperError("attributeIndex is out of range");
    }
    if (!defined(value)) {
      throw new DeveloperError("value is required.");
    }
    //>>includeEnd('debug');

    const attributes = this._attributes;
    const result =
      setAttributeScratchValues[
        attributes[attributeIndex].componentsPerAttribute
      ];
    const currentAttribute = this.getBatchedAttribute(
      instanceIndex,
      attributeIndex,
      result
    );
    const attributeType = getAttributeType(this._attributes, attributeIndex);
    const entriesEqual = defined(attributeType.equals)
      ? attributeType.equals(currentAttribute, value)
      : currentAttribute === value;
    if (entriesEqual) {
      return;
    }

    const attributeValue = setAttributeScratchCartesian4;
    attributeValue.x = defined(value.x) ? value.x : value;
    attributeValue.y = defined(value.y) ? value.y : 0.0;
    attributeValue.z = defined(value.z) ? value.z : 0.0;
    attributeValue.w = defined(value.w) ? value.w : 0.0;

    const offset = this._offsets[attributeIndex];
    const stride = this._stride;
    const index = 4 * stride * instanceIndex + 4 * offset;

    if (
      this._packFloats &&
      attributes[attributeIndex].componentDatatype !== PixelDatatype$1.UNSIGNED_BYTE
    ) {
      setPackedAttribute(attributeValue, this._batchValues, index);
    } else {
      Cartesian4.pack(attributeValue, this._batchValues, index);
    }

    this._batchValuesDirty = true;
  };

  function createTexture$5(batchTable, context) {
    const dimensions = batchTable._textureDimensions;
    batchTable._texture = new Texture({
      context: context,
      pixelFormat: PixelFormat$1.RGBA,
      pixelDatatype: batchTable._pixelDatatype,
      width: dimensions.x,
      height: dimensions.y,
      sampler: Sampler.NEAREST,
      flipY: false,
    });
  }

  function updateTexture(batchTable) {
    const dimensions = batchTable._textureDimensions;
    batchTable._texture.copyFrom({
      source: {
        width: dimensions.x,
        height: dimensions.y,
        arrayBufferView: batchTable._batchValues,
      },
    });
  }

  /**
   * Creates/updates the batch table texture.
   * @param {FrameState} frameState The frame state.
   *
   * @exception {RuntimeError} The floating point texture extension is required but not supported.
   */
  BatchTable.prototype.update = function (frameState) {
    if (
      (defined(this._texture) && !this._batchValuesDirty) ||
      this._attributes.length === 0
    ) {
      return;
    }

    this._batchValuesDirty = false;

    if (!defined(this._texture)) {
      createTexture$5(this, frameState.context);
    }
    updateTexture(this);
  };

  /**
   * Gets a function that will update a uniform map to contain values for looking up values in the batch table.
   *
   * @returns {BatchTable.updateUniformMapCallback} A callback for updating uniform maps.
   */
  BatchTable.prototype.getUniformMapCallback = function () {
    const that = this;
    return function (uniformMap) {
      if (that._attributes.length === 0) {
        return uniformMap;
      }

      const batchUniformMap = {
        batchTexture: function () {
          return that._texture;
        },
        batchTextureDimensions: function () {
          return that._textureDimensions;
        },
        batchTextureStep: function () {
          return that._textureStep;
        },
      };
      return combine$2(uniformMap, batchUniformMap);
    };
  };

  function getGlslComputeSt$1(batchTable) {
    const stride = batchTable._stride;

    // GLSL batchId is zero-based: [0, numberOfInstances - 1]
    if (batchTable._textureDimensions.y === 1) {
      return (
        `${
        "uniform vec4 batchTextureStep; \n" +
        "vec2 computeSt(float batchId) \n" +
        "{ \n" +
        "    float stepX = batchTextureStep.x; \n" +
        "    float centerX = batchTextureStep.y; \n" +
        "    float numberOfAttributes = float("
      }${stride}); \n` +
        `    return vec2(centerX + (batchId * numberOfAttributes * stepX), 0.5); \n` +
        `} \n`
      );
    }

    return (
      `${
      "uniform vec4 batchTextureStep; \n" +
      "uniform vec2 batchTextureDimensions; \n" +
      "vec2 computeSt(float batchId) \n" +
      "{ \n" +
      "    float stepX = batchTextureStep.x; \n" +
      "    float centerX = batchTextureStep.y; \n" +
      "    float stepY = batchTextureStep.z; \n" +
      "    float centerY = batchTextureStep.w; \n" +
      "    float numberOfAttributes = float("
    }${stride}); \n` +
      `    float xId = mod(batchId * numberOfAttributes, batchTextureDimensions.x); \n` +
      `    float yId = floor(batchId * numberOfAttributes / batchTextureDimensions.x); \n` +
      `    return vec2(centerX + (xId * stepX), centerY + (yId * stepY)); \n` +
      `} \n`
    );
  }

  function getComponentType(componentsPerAttribute) {
    if (componentsPerAttribute === 1) {
      return "float";
    }
    return `vec${componentsPerAttribute}`;
  }

  function getComponentSwizzle(componentsPerAttribute) {
    if (componentsPerAttribute === 1) {
      return ".x";
    } else if (componentsPerAttribute === 2) {
      return ".xy";
    } else if (componentsPerAttribute === 3) {
      return ".xyz";
    }
    return "";
  }

  function getGlslAttributeFunction(batchTable, attributeIndex) {
    const attributes = batchTable._attributes;
    const attribute = attributes[attributeIndex];
    const componentsPerAttribute = attribute.componentsPerAttribute;
    const functionName = attribute.functionName;
    const functionReturnType = getComponentType(componentsPerAttribute);
    const functionReturnValue = getComponentSwizzle(componentsPerAttribute);

    const offset = batchTable._offsets[attributeIndex];

    let glslFunction =
      `${functionReturnType} ${functionName}(float batchId) \n` +
      `{ \n` +
      `    vec2 st = computeSt(batchId); \n` +
      `    st.x += batchTextureStep.x * float(${offset}); \n`;

    if (
      batchTable._packFloats &&
      attribute.componentDatatype !== PixelDatatype$1.UNSIGNED_BYTE
    ) {
      glslFunction +=
        "vec4 textureValue; \n" +
        "textureValue.x = czm_unpackFloat(texture2D(batchTexture, st)); \n" +
        "textureValue.y = czm_unpackFloat(texture2D(batchTexture, st + vec2(batchTextureStep.x, 0.0))); \n" +
        "textureValue.z = czm_unpackFloat(texture2D(batchTexture, st + vec2(batchTextureStep.x * 2.0, 0.0))); \n" +
        "textureValue.w = czm_unpackFloat(texture2D(batchTexture, st + vec2(batchTextureStep.x * 3.0, 0.0))); \n";
    } else {
      glslFunction += "    vec4 textureValue = texture2D(batchTexture, st); \n";
    }

    glslFunction += `    ${functionReturnType} value = textureValue${functionReturnValue}; \n`;

    if (
      batchTable._pixelDatatype === PixelDatatype$1.UNSIGNED_BYTE &&
      attribute.componentDatatype === ComponentDatatype$1.UNSIGNED_BYTE &&
      !attribute.normalize
    ) {
      glslFunction += "value *= 255.0; \n";
    } else if (
      batchTable._pixelDatatype === PixelDatatype$1.FLOAT &&
      attribute.componentDatatype === ComponentDatatype$1.UNSIGNED_BYTE &&
      attribute.normalize
    ) {
      glslFunction += "value /= 255.0; \n";
    }

    glslFunction += "    return value; \n" + "} \n";
    return glslFunction;
  }

  /**
   * Gets a function that will update a vertex shader to contain functions for looking up values in the batch table.
   *
   * @returns {BatchTable.updateVertexShaderSourceCallback} A callback for updating a vertex shader source.
   */
  BatchTable.prototype.getVertexShaderCallback = function () {
    const attributes = this._attributes;
    if (attributes.length === 0) {
      return function (source) {
        return source;
      };
    }

    let batchTableShader = "uniform highp sampler2D batchTexture; \n";
    batchTableShader += `${getGlslComputeSt$1(this)}\n`;

    const length = attributes.length;
    for (let i = 0; i < length; ++i) {
      batchTableShader += getGlslAttributeFunction(this, i);
    }

    return function (source) {
      const mainIndex = source.indexOf("void main");
      const beforeMain = source.substring(0, mainIndex);
      const afterMain = source.substring(mainIndex);
      return `${beforeMain}\n${batchTableShader}\n${afterMain}`;
    };
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see BatchTable#destroy
   */
  BatchTable.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @see BatchTable#isDestroyed
   */
  BatchTable.prototype.destroy = function () {
    this._texture = this._texture && this._texture.destroy();
    return destroyObject(this);
  };

  function transformToWorldCoordinates(
    instances,
    primitiveModelMatrix,
    scene3DOnly
  ) {
    let toWorld = !scene3DOnly;
    const length = instances.length;
    let i;

    if (!toWorld && length > 1) {
      const modelMatrix = instances[0].modelMatrix;

      for (i = 1; i < length; ++i) {
        if (!Matrix4.equals(modelMatrix, instances[i].modelMatrix)) {
          toWorld = true;
          break;
        }
      }
    }

    if (toWorld) {
      for (i = 0; i < length; ++i) {
        if (defined(instances[i].geometry)) {
          GeometryPipeline.transformToWorldCoordinates(instances[i]);
        }
      }
    } else {
      // Leave geometry in local coordinate system; auto update model-matrix.
      Matrix4.multiplyTransformation(
        primitiveModelMatrix,
        instances[0].modelMatrix,
        primitiveModelMatrix
      );
    }
  }

  function addGeometryBatchId(geometry, batchId) {
    const attributes = geometry.attributes;
    const positionAttr = attributes.position;
    const numberOfComponents =
      positionAttr.values.length / positionAttr.componentsPerAttribute;

    attributes.batchId = new GeometryAttribute({
      componentDatatype: ComponentDatatype$1.FLOAT,
      componentsPerAttribute: 1,
      values: new Float32Array(numberOfComponents),
    });

    const values = attributes.batchId.values;
    for (let j = 0; j < numberOfComponents; ++j) {
      values[j] = batchId;
    }
  }

  function addBatchIds(instances) {
    const length = instances.length;

    for (let i = 0; i < length; ++i) {
      const instance = instances[i];
      if (defined(instance.geometry)) {
        addGeometryBatchId(instance.geometry, i);
      } else if (
        defined(instance.westHemisphereGeometry) &&
        defined(instance.eastHemisphereGeometry)
      ) {
        addGeometryBatchId(instance.westHemisphereGeometry, i);
        addGeometryBatchId(instance.eastHemisphereGeometry, i);
      }
    }
  }

  function geometryPipeline(parameters) {
    const instances = parameters.instances;
    const projection = parameters.projection;
    const uintIndexSupport = parameters.elementIndexUintSupported;
    const scene3DOnly = parameters.scene3DOnly;
    const vertexCacheOptimize = parameters.vertexCacheOptimize;
    const compressVertices = parameters.compressVertices;
    const modelMatrix = parameters.modelMatrix;

    let i;
    let geometry;
    let primitiveType;
    let length = instances.length;

    for (i = 0; i < length; ++i) {
      if (defined(instances[i].geometry)) {
        primitiveType = instances[i].geometry.primitiveType;
        break;
      }
    }

    //>>includeStart('debug', pragmas.debug);
    for (i = 1; i < length; ++i) {
      if (
        defined(instances[i].geometry) &&
        instances[i].geometry.primitiveType !== primitiveType
      ) {
        throw new DeveloperError(
          "All instance geometries must have the same primitiveType."
        );
      }
    }
    //>>includeEnd('debug');

    // Unify to world coordinates before combining.
    transformToWorldCoordinates(instances, modelMatrix, scene3DOnly);

    // Clip to IDL
    if (!scene3DOnly) {
      for (i = 0; i < length; ++i) {
        if (defined(instances[i].geometry)) {
          GeometryPipeline.splitLongitude(instances[i]);
        }
      }
    }

    addBatchIds(instances);

    // Optimize for vertex shader caches
    if (vertexCacheOptimize) {
      for (i = 0; i < length; ++i) {
        const instance = instances[i];
        if (defined(instance.geometry)) {
          GeometryPipeline.reorderForPostVertexCache(instance.geometry);
          GeometryPipeline.reorderForPreVertexCache(instance.geometry);
        } else if (
          defined(instance.westHemisphereGeometry) &&
          defined(instance.eastHemisphereGeometry)
        ) {
          GeometryPipeline.reorderForPostVertexCache(
            instance.westHemisphereGeometry
          );
          GeometryPipeline.reorderForPreVertexCache(
            instance.westHemisphereGeometry
          );

          GeometryPipeline.reorderForPostVertexCache(
            instance.eastHemisphereGeometry
          );
          GeometryPipeline.reorderForPreVertexCache(
            instance.eastHemisphereGeometry
          );
        }
      }
    }

    // Combine into single geometry for better rendering performance.
    let geometries = GeometryPipeline.combineInstances(instances);

    length = geometries.length;
    for (i = 0; i < length; ++i) {
      geometry = geometries[i];

      // Split positions for GPU RTE
      const attributes = geometry.attributes;
      if (!scene3DOnly) {
        for (const name in attributes) {
          if (
            attributes.hasOwnProperty(name) &&
            attributes[name].componentDatatype === ComponentDatatype$1.DOUBLE
          ) {
            const name3D = `${name}3D`;
            const name2D = `${name}2D`;

            // Compute 2D positions
            GeometryPipeline.projectTo2D(
              geometry,
              name,
              name3D,
              name2D,
              projection
            );
            if (defined(geometry.boundingSphere) && name === "position") {
              geometry.boundingSphereCV = BoundingSphere.fromVertices(
                geometry.attributes.position2D.values
              );
            }

            GeometryPipeline.encodeAttribute(
              geometry,
              name3D,
              `${name3D}High`,
              `${name3D}Low`
            );
            GeometryPipeline.encodeAttribute(
              geometry,
              name2D,
              `${name2D}High`,
              `${name2D}Low`
            );
          }
        }
      } else {
        for (const name in attributes) {
          if (
            attributes.hasOwnProperty(name) &&
            attributes[name].componentDatatype === ComponentDatatype$1.DOUBLE
          ) {
            GeometryPipeline.encodeAttribute(
              geometry,
              name,
              `${name}3DHigh`,
              `${name}3DLow`
            );
          }
        }
      }

      // oct encode and pack normals, compress texture coordinates
      if (compressVertices) {
        GeometryPipeline.compressVertices(geometry);
      }
    }

    if (!uintIndexSupport) {
      // Break into multiple geometries to fit within unsigned short indices if needed
      let splitGeometries = [];
      length = geometries.length;
      for (i = 0; i < length; ++i) {
        geometry = geometries[i];
        splitGeometries = splitGeometries.concat(
          GeometryPipeline.fitToUnsignedShortIndices(geometry)
        );
      }

      geometries = splitGeometries;
    }

    return geometries;
  }

  function createPickOffsets(instances, geometryName, geometries, pickOffsets) {
    let offset;
    let indexCount;
    let geometryIndex;

    const offsetIndex = pickOffsets.length - 1;
    if (offsetIndex >= 0) {
      const pickOffset = pickOffsets[offsetIndex];
      offset = pickOffset.offset + pickOffset.count;
      geometryIndex = pickOffset.index;
      indexCount = geometries[geometryIndex].indices.length;
    } else {
      offset = 0;
      geometryIndex = 0;
      indexCount = geometries[geometryIndex].indices.length;
    }

    const length = instances.length;
    for (let i = 0; i < length; ++i) {
      const instance = instances[i];
      const geometry = instance[geometryName];
      if (!defined(geometry)) {
        continue;
      }

      const count = geometry.indices.length;

      if (offset + count > indexCount) {
        offset = 0;
        indexCount = geometries[++geometryIndex].indices.length;
      }

      pickOffsets.push({
        index: geometryIndex,
        offset: offset,
        count: count,
      });
      offset += count;
    }
  }

  function createInstancePickOffsets(instances, geometries) {
    const pickOffsets = [];
    createPickOffsets(instances, "geometry", geometries, pickOffsets);
    createPickOffsets(
      instances,
      "westHemisphereGeometry",
      geometries,
      pickOffsets
    );
    createPickOffsets(
      instances,
      "eastHemisphereGeometry",
      geometries,
      pickOffsets
    );
    return pickOffsets;
  }

  /**
   * @private
   */
  const PrimitivePipeline = {};

  /**
   * @private
   */
  PrimitivePipeline.combineGeometry = function (parameters) {
    let geometries;
    let attributeLocations;
    const instances = parameters.instances;
    const length = instances.length;
    let pickOffsets;

    let offsetInstanceExtend;
    let hasOffset = false;
    if (length > 0) {
      geometries = geometryPipeline(parameters);
      if (geometries.length > 0) {
        attributeLocations = GeometryPipeline.createAttributeLocations(
          geometries[0]
        );
        if (parameters.createPickOffsets) {
          pickOffsets = createInstancePickOffsets(instances, geometries);
        }
      }
      if (
        defined(instances[0].attributes) &&
        defined(instances[0].attributes.offset)
      ) {
        offsetInstanceExtend = new Array(length);
        hasOffset = true;
      }
    }

    const boundingSpheres = new Array(length);
    const boundingSpheresCV = new Array(length);
    for (let i = 0; i < length; ++i) {
      const instance = instances[i];
      const geometry = instance.geometry;
      if (defined(geometry)) {
        boundingSpheres[i] = geometry.boundingSphere;
        boundingSpheresCV[i] = geometry.boundingSphereCV;
        if (hasOffset) {
          offsetInstanceExtend[i] = instance.geometry.offsetAttribute;
        }
      }

      const eastHemisphereGeometry = instance.eastHemisphereGeometry;
      const westHemisphereGeometry = instance.westHemisphereGeometry;
      if (defined(eastHemisphereGeometry) && defined(westHemisphereGeometry)) {
        if (
          defined(eastHemisphereGeometry.boundingSphere) &&
          defined(westHemisphereGeometry.boundingSphere)
        ) {
          boundingSpheres[i] = BoundingSphere.union(
            eastHemisphereGeometry.boundingSphere,
            westHemisphereGeometry.boundingSphere
          );
        }
        if (
          defined(eastHemisphereGeometry.boundingSphereCV) &&
          defined(westHemisphereGeometry.boundingSphereCV)
        ) {
          boundingSpheresCV[i] = BoundingSphere.union(
            eastHemisphereGeometry.boundingSphereCV,
            westHemisphereGeometry.boundingSphereCV
          );
        }
      }
    }

    return {
      geometries: geometries,
      modelMatrix: parameters.modelMatrix,
      attributeLocations: attributeLocations,
      pickOffsets: pickOffsets,
      offsetInstanceExtend: offsetInstanceExtend,
      boundingSpheres: boundingSpheres,
      boundingSpheresCV: boundingSpheresCV,
    };
  };

  function transferGeometry(geometry, transferableObjects) {
    const attributes = geometry.attributes;
    for (const name in attributes) {
      if (attributes.hasOwnProperty(name)) {
        const attribute = attributes[name];

        if (defined(attribute) && defined(attribute.values)) {
          transferableObjects.push(attribute.values.buffer);
        }
      }
    }

    if (defined(geometry.indices)) {
      transferableObjects.push(geometry.indices.buffer);
    }
  }

  function transferGeometries(geometries, transferableObjects) {
    const length = geometries.length;
    for (let i = 0; i < length; ++i) {
      transferGeometry(geometries[i], transferableObjects);
    }
  }

  // This function was created by simplifying packCreateGeometryResults into a count-only operation.
  function countCreateGeometryResults(items) {
    let count = 1;
    const length = items.length;
    for (let i = 0; i < length; i++) {
      const geometry = items[i];
      ++count;

      if (!defined(geometry)) {
        continue;
      }

      const attributes = geometry.attributes;

      count +=
        7 +
        2 * BoundingSphere.packedLength +
        (defined(geometry.indices) ? geometry.indices.length : 0);

      for (const property in attributes) {
        if (
          attributes.hasOwnProperty(property) &&
          defined(attributes[property])
        ) {
          const attribute = attributes[property];
          count += 5 + attribute.values.length;
        }
      }
    }

    return count;
  }

  /**
   * @private
   */
  PrimitivePipeline.packCreateGeometryResults = function (
    items,
    transferableObjects
  ) {
    const packedData = new Float64Array(countCreateGeometryResults(items));
    const stringTable = [];
    const stringHash = {};

    const length = items.length;
    let count = 0;
    packedData[count++] = length;
    for (let i = 0; i < length; i++) {
      const geometry = items[i];

      const validGeometry = defined(geometry);
      packedData[count++] = validGeometry ? 1.0 : 0.0;

      if (!validGeometry) {
        continue;
      }

      packedData[count++] = geometry.primitiveType;
      packedData[count++] = geometry.geometryType;
      packedData[count++] = defaultValue(geometry.offsetAttribute, -1);

      const validBoundingSphere = defined(geometry.boundingSphere) ? 1.0 : 0.0;
      packedData[count++] = validBoundingSphere;
      if (validBoundingSphere) {
        BoundingSphere.pack(geometry.boundingSphere, packedData, count);
      }

      count += BoundingSphere.packedLength;

      const validBoundingSphereCV = defined(geometry.boundingSphereCV)
        ? 1.0
        : 0.0;
      packedData[count++] = validBoundingSphereCV;
      if (validBoundingSphereCV) {
        BoundingSphere.pack(geometry.boundingSphereCV, packedData, count);
      }

      count += BoundingSphere.packedLength;

      const attributes = geometry.attributes;
      const attributesToWrite = [];
      for (const property in attributes) {
        if (
          attributes.hasOwnProperty(property) &&
          defined(attributes[property])
        ) {
          attributesToWrite.push(property);
          if (!defined(stringHash[property])) {
            stringHash[property] = stringTable.length;
            stringTable.push(property);
          }
        }
      }

      packedData[count++] = attributesToWrite.length;
      for (let q = 0; q < attributesToWrite.length; q++) {
        const name = attributesToWrite[q];
        const attribute = attributes[name];
        packedData[count++] = stringHash[name];
        packedData[count++] = attribute.componentDatatype;
        packedData[count++] = attribute.componentsPerAttribute;
        packedData[count++] = attribute.normalize ? 1 : 0;
        packedData[count++] = attribute.values.length;
        packedData.set(attribute.values, count);
        count += attribute.values.length;
      }

      const indicesLength = defined(geometry.indices)
        ? geometry.indices.length
        : 0;
      packedData[count++] = indicesLength;

      if (indicesLength > 0) {
        packedData.set(geometry.indices, count);
        count += indicesLength;
      }
    }

    transferableObjects.push(packedData.buffer);

    return {
      stringTable: stringTable,
      packedData: packedData,
    };
  };

  /**
   * @private
   */
  PrimitivePipeline.unpackCreateGeometryResults = function (
    createGeometryResult
  ) {
    const stringTable = createGeometryResult.stringTable;
    const packedGeometry = createGeometryResult.packedData;

    let i;
    const result = new Array(packedGeometry[0]);
    let resultIndex = 0;

    let packedGeometryIndex = 1;
    while (packedGeometryIndex < packedGeometry.length) {
      const valid = packedGeometry[packedGeometryIndex++] === 1.0;
      if (!valid) {
        result[resultIndex++] = undefined;
        continue;
      }

      const primitiveType = packedGeometry[packedGeometryIndex++];
      const geometryType = packedGeometry[packedGeometryIndex++];
      let offsetAttribute = packedGeometry[packedGeometryIndex++];
      if (offsetAttribute === -1) {
        offsetAttribute = undefined;
      }

      let boundingSphere;
      let boundingSphereCV;

      const validBoundingSphere = packedGeometry[packedGeometryIndex++] === 1.0;
      if (validBoundingSphere) {
        boundingSphere = BoundingSphere.unpack(
          packedGeometry,
          packedGeometryIndex
        );
      }

      packedGeometryIndex += BoundingSphere.packedLength;

      const validBoundingSphereCV = packedGeometry[packedGeometryIndex++] === 1.0;
      if (validBoundingSphereCV) {
        boundingSphereCV = BoundingSphere.unpack(
          packedGeometry,
          packedGeometryIndex
        );
      }

      packedGeometryIndex += BoundingSphere.packedLength;

      let length;
      let values;
      let componentsPerAttribute;
      const attributes = new GeometryAttributes();
      const numAttributes = packedGeometry[packedGeometryIndex++];
      for (i = 0; i < numAttributes; i++) {
        const name = stringTable[packedGeometry[packedGeometryIndex++]];
        const componentDatatype = packedGeometry[packedGeometryIndex++];
        componentsPerAttribute = packedGeometry[packedGeometryIndex++];
        const normalize = packedGeometry[packedGeometryIndex++] !== 0;

        length = packedGeometry[packedGeometryIndex++];
        values = ComponentDatatype$1.createTypedArray(componentDatatype, length);
        for (let valuesIndex = 0; valuesIndex < length; valuesIndex++) {
          values[valuesIndex] = packedGeometry[packedGeometryIndex++];
        }

        attributes[name] = new GeometryAttribute({
          componentDatatype: componentDatatype,
          componentsPerAttribute: componentsPerAttribute,
          normalize: normalize,
          values: values,
        });
      }

      let indices;
      length = packedGeometry[packedGeometryIndex++];

      if (length > 0) {
        const numberOfVertices = values.length / componentsPerAttribute;
        indices = IndexDatatype$1.createTypedArray(numberOfVertices, length);
        for (i = 0; i < length; i++) {
          indices[i] = packedGeometry[packedGeometryIndex++];
        }
      }

      result[resultIndex++] = new Geometry({
        primitiveType: primitiveType,
        geometryType: geometryType,
        boundingSphere: boundingSphere,
        boundingSphereCV: boundingSphereCV,
        indices: indices,
        attributes: attributes,
        offsetAttribute: offsetAttribute,
      });
    }

    return result;
  };

  function packInstancesForCombine(instances, transferableObjects) {
    const length = instances.length;
    const packedData = new Float64Array(1 + length * 19);
    let count = 0;
    packedData[count++] = length;
    for (let i = 0; i < length; i++) {
      const instance = instances[i];
      Matrix4.pack(instance.modelMatrix, packedData, count);
      count += Matrix4.packedLength;
      if (defined(instance.attributes) && defined(instance.attributes.offset)) {
        const values = instance.attributes.offset.value;
        packedData[count] = values[0];
        packedData[count + 1] = values[1];
        packedData[count + 2] = values[2];
      }
      count += 3;
    }
    transferableObjects.push(packedData.buffer);

    return packedData;
  }

  function unpackInstancesForCombine(data) {
    const packedInstances = data;
    const result = new Array(packedInstances[0]);
    let count = 0;

    let i = 1;
    while (i < packedInstances.length) {
      const modelMatrix = Matrix4.unpack(packedInstances, i);
      let attributes;
      i += Matrix4.packedLength;
      if (defined(packedInstances[i])) {
        attributes = {
          offset: new OffsetGeometryInstanceAttribute(
            packedInstances[i],
            packedInstances[i + 1],
            packedInstances[i + 2]
          ),
        };
      }
      i += 3;

      result[count++] = {
        modelMatrix: modelMatrix,
        attributes: attributes,
      };
    }

    return result;
  }

  /**
   * @private
   */
  PrimitivePipeline.packCombineGeometryParameters = function (
    parameters,
    transferableObjects
  ) {
    const createGeometryResults = parameters.createGeometryResults;
    const length = createGeometryResults.length;

    for (let i = 0; i < length; i++) {
      transferableObjects.push(createGeometryResults[i].packedData.buffer);
    }

    return {
      createGeometryResults: parameters.createGeometryResults,
      packedInstances: packInstancesForCombine(
        parameters.instances,
        transferableObjects
      ),
      ellipsoid: parameters.ellipsoid,
      isGeographic: parameters.projection instanceof GeographicProjection,
      elementIndexUintSupported: parameters.elementIndexUintSupported,
      scene3DOnly: parameters.scene3DOnly,
      vertexCacheOptimize: parameters.vertexCacheOptimize,
      compressVertices: parameters.compressVertices,
      modelMatrix: parameters.modelMatrix,
      createPickOffsets: parameters.createPickOffsets,
    };
  };

  /**
   * @private
   */
  PrimitivePipeline.unpackCombineGeometryParameters = function (
    packedParameters
  ) {
    const instances = unpackInstancesForCombine(packedParameters.packedInstances);
    const createGeometryResults = packedParameters.createGeometryResults;
    const length = createGeometryResults.length;
    let instanceIndex = 0;

    for (let resultIndex = 0; resultIndex < length; resultIndex++) {
      const geometries = PrimitivePipeline.unpackCreateGeometryResults(
        createGeometryResults[resultIndex]
      );
      const geometriesLength = geometries.length;
      for (
        let geometryIndex = 0;
        geometryIndex < geometriesLength;
        geometryIndex++
      ) {
        const geometry = geometries[geometryIndex];
        const instance = instances[instanceIndex];
        instance.geometry = geometry;
        ++instanceIndex;
      }
    }

    const ellipsoid = Ellipsoid.clone(packedParameters.ellipsoid);
    const projection = packedParameters.isGeographic
      ? new GeographicProjection(ellipsoid)
      : new WebMercatorProjection(ellipsoid);

    return {
      instances: instances,
      ellipsoid: ellipsoid,
      projection: projection,
      elementIndexUintSupported: packedParameters.elementIndexUintSupported,
      scene3DOnly: packedParameters.scene3DOnly,
      vertexCacheOptimize: packedParameters.vertexCacheOptimize,
      compressVertices: packedParameters.compressVertices,
      modelMatrix: Matrix4.clone(packedParameters.modelMatrix),
      createPickOffsets: packedParameters.createPickOffsets,
    };
  };

  function packBoundingSpheres(boundingSpheres) {
    const length = boundingSpheres.length;
    const bufferLength = 1 + (BoundingSphere.packedLength + 1) * length;
    const buffer = new Float32Array(bufferLength);

    let bufferIndex = 0;
    buffer[bufferIndex++] = length;

    for (let i = 0; i < length; ++i) {
      const bs = boundingSpheres[i];
      if (!defined(bs)) {
        buffer[bufferIndex++] = 0.0;
      } else {
        buffer[bufferIndex++] = 1.0;
        BoundingSphere.pack(boundingSpheres[i], buffer, bufferIndex);
      }
      bufferIndex += BoundingSphere.packedLength;
    }

    return buffer;
  }

  function unpackBoundingSpheres(buffer) {
    const result = new Array(buffer[0]);
    let count = 0;

    let i = 1;
    while (i < buffer.length) {
      if (buffer[i++] === 1.0) {
        result[count] = BoundingSphere.unpack(buffer, i);
      }
      ++count;
      i += BoundingSphere.packedLength;
    }

    return result;
  }

  /**
   * @private
   */
  PrimitivePipeline.packCombineGeometryResults = function (
    results,
    transferableObjects
  ) {
    if (defined(results.geometries)) {
      transferGeometries(results.geometries, transferableObjects);
    }

    const packedBoundingSpheres = packBoundingSpheres(results.boundingSpheres);
    const packedBoundingSpheresCV = packBoundingSpheres(
      results.boundingSpheresCV
    );
    transferableObjects.push(
      packedBoundingSpheres.buffer,
      packedBoundingSpheresCV.buffer
    );

    return {
      geometries: results.geometries,
      attributeLocations: results.attributeLocations,
      modelMatrix: results.modelMatrix,
      pickOffsets: results.pickOffsets,
      offsetInstanceExtend: results.offsetInstanceExtend,
      boundingSpheres: packedBoundingSpheres,
      boundingSpheresCV: packedBoundingSpheresCV,
    };
  };

  /**
   * @private
   */
  PrimitivePipeline.unpackCombineGeometryResults = function (packedResult) {
    return {
      geometries: packedResult.geometries,
      attributeLocations: packedResult.attributeLocations,
      modelMatrix: packedResult.modelMatrix,
      pickOffsets: packedResult.pickOffsets,
      offsetInstanceExtend: packedResult.offsetInstanceExtend,
      boundingSpheres: unpackBoundingSpheres(packedResult.boundingSpheres),
      boundingSpheresCV: unpackBoundingSpheres(packedResult.boundingSpheresCV),
    };
  };

  /**
   * @private
   */
  const PrimitiveState = {
    READY: 0,
    CREATING: 1,
    CREATED: 2,
    COMBINING: 3,
    COMBINED: 4,
    COMPLETE: 5,
    FAILED: 6,
  };
  var PrimitiveState$1 = Object.freeze(PrimitiveState);

  /**
   * Indicates if the scene is viewed in 3D, 2D, or 2.5D Columbus view.
   *
   * @enum {Number}
   * @see Scene#mode
   */
  const SceneMode = {
    /**
     * Morphing between mode, e.g., 3D to 2D.
     *
     * @type {Number}
     * @constant
     */
    MORPHING: 0,

    /**
     * Columbus View mode.  A 2.5D perspective view where the map is laid out
     * flat and objects with non-zero height are drawn above it.
     *
     * @type {Number}
     * @constant
     */
    COLUMBUS_VIEW: 1,

    /**
     * 2D mode.  The map is viewed top-down with an orthographic projection.
     *
     * @type {Number}
     * @constant
     */
    SCENE2D: 2,

    /**
     * 3D mode.  A traditional 3D perspective view of the globe.
     *
     * @type {Number}
     * @constant
     */
    SCENE3D: 3,
  };

  /**
   * Returns the morph time for the given scene mode.
   *
   * @param {SceneMode} value The scene mode
   * @returns {Number} The morph time
   */
  SceneMode.getMorphTime = function (value) {
    if (value === SceneMode.SCENE3D) {
      return 1.0;
    } else if (value === SceneMode.MORPHING) {
      return undefined;
    }
    return 0.0;
  };
  var SceneMode$1 = Object.freeze(SceneMode);

  /**
   * Specifies whether the object casts or receives shadows from light sources when
   * shadows are enabled.
   *
   * @enum {Number}
   */
  const ShadowMode = {
    /**
     * The object does not cast or receive shadows.
     *
     * @type {Number}
     * @constant
     */
    DISABLED: 0,

    /**
     * The object casts and receives shadows.
     *
     * @type {Number}
     * @constant
     */
    ENABLED: 1,

    /**
     * The object casts shadows only.
     *
     * @type {Number}
     * @constant
     */
    CAST_ONLY: 2,

    /**
     * The object receives shadows only.
     *
     * @type {Number}
     * @constant
     */
    RECEIVE_ONLY: 3,
  };

  /**
   * @private
   */
  ShadowMode.NUMBER_OF_SHADOW_MODES = 4;

  /**
   * @private
   */
  ShadowMode.castShadows = function (shadowMode) {
    return (
      shadowMode === ShadowMode.ENABLED || shadowMode === ShadowMode.CAST_ONLY
    );
  };

  /**
   * @private
   */
  ShadowMode.receiveShadows = function (shadowMode) {
    return (
      shadowMode === ShadowMode.ENABLED || shadowMode === ShadowMode.RECEIVE_ONLY
    );
  };

  /**
   * @private
   */
  ShadowMode.fromCastReceive = function (castShadows, receiveShadows) {
    if (castShadows && receiveShadows) {
      return ShadowMode.ENABLED;
    } else if (castShadows) {
      return ShadowMode.CAST_ONLY;
    } else if (receiveShadows) {
      return ShadowMode.RECEIVE_ONLY;
    }
    return ShadowMode.DISABLED;
  };

  var ShadowMode$1 = Object.freeze(ShadowMode);

  /**
   * A primitive represents geometry in the {@link Scene}.  The geometry can be from a single {@link GeometryInstance}
   * as shown in example 1 below, or from an array of instances, even if the geometry is from different
   * geometry types, e.g., an {@link RectangleGeometry} and an {@link EllipsoidGeometry} as shown in Code Example 2.
   * <p>
   * A primitive combines geometry instances with an {@link Appearance} that describes the full shading, including
   * {@link Material} and {@link RenderState}.  Roughly, the geometry instance defines the structure and placement,
   * and the appearance defines the visual characteristics.  Decoupling geometry and appearance allows us to mix
   * and match most of them and add a new geometry or appearance independently of each other.
   * </p>
   * <p>
   * Combining multiple instances into one primitive is called batching, and significantly improves performance for static data.
   * Instances can be individually picked; {@link Scene#pick} returns their {@link GeometryInstance#id}.  Using
   * per-instance appearances like {@link PerInstanceColorAppearance}, each instance can also have a unique color.
   * </p>
   * <p>
   * {@link Geometry} can either be created and batched on a web worker or the main thread. The first two examples
   * show geometry that will be created on a web worker by using the descriptions of the geometry. The third example
   * shows how to create the geometry on the main thread by explicitly calling the <code>createGeometry</code> method.
   * </p>
   *
   * @alias Primitive
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {GeometryInstance[]|GeometryInstance} [options.geometryInstances] The geometry instances - or a single geometry instance - to render.
   * @param {Appearance} [options.appearance] The appearance used to render the primitive.
   * @param {Appearance} [options.depthFailAppearance] The appearance used to shade this primitive when it fails the depth test.
   * @param {Boolean} [options.show=true] Determines if this primitive will be shown.
   * @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] The 4x4 transformation matrix that transforms the primitive (all geometry instances) from model to world coordinates.
   * @param {Boolean} [options.vertexCacheOptimize=false] When <code>true</code>, geometry vertices are optimized for the pre and post-vertex-shader caches.
   * @param {Boolean} [options.interleave=false] When <code>true</code>, geometry vertex attributes are interleaved, which can slightly improve rendering performance but increases load time.
   * @param {Boolean} [options.compressVertices=true] When <code>true</code>, the geometry vertices are compressed, which will save memory.
   * @param {Boolean} [options.releaseGeometryInstances=true] When <code>true</code>, the primitive does not keep a reference to the input <code>geometryInstances</code> to save memory.
   * @param {Boolean} [options.allowPicking=true] When <code>true</code>, each geometry instance will only be pickable with {@link Scene#pick}.  When <code>false</code>, GPU memory is saved.
   * @param {Boolean} [options.cull=true] When <code>true</code>, the renderer frustum culls and horizon culls the primitive's commands based on their bounding volume.  Set this to <code>false</code> for a small performance gain if you are manually culling the primitive.
   * @param {Boolean} [options.asynchronous=true] Determines if the primitive will be created asynchronously or block until ready.
   * @param {Boolean} [options.debugShowBoundingVolume=false] For debugging only. Determines if this primitive's commands' bounding spheres are shown.
   * @param {ShadowMode} [options.shadows=ShadowMode.DISABLED] Determines whether this primitive casts or receives shadows from light sources.
   *
   * @example
   * // 1. Draw a translucent ellipse on the surface with a checkerboard pattern
   * const instance = new Cesium.GeometryInstance({
   *   geometry : new Cesium.EllipseGeometry({
   *       center : Cesium.Cartesian3.fromDegrees(-100.0, 20.0),
   *       semiMinorAxis : 500000.0,
   *       semiMajorAxis : 1000000.0,
   *       rotation : Cesium.Math.PI_OVER_FOUR,
   *       vertexFormat : Cesium.VertexFormat.POSITION_AND_ST
   *   }),
   *   id : 'object returned when this instance is picked and to get/set per-instance attributes'
   * });
   * scene.primitives.add(new Cesium.Primitive({
   *   geometryInstances : instance,
   *   appearance : new Cesium.EllipsoidSurfaceAppearance({
   *     material : Cesium.Material.fromType('Checkerboard')
   *   })
   * }));
   *
   * @example
   * // 2. Draw different instances each with a unique color
   * const rectangleInstance = new Cesium.GeometryInstance({
   *   geometry : new Cesium.RectangleGeometry({
   *     rectangle : Cesium.Rectangle.fromDegrees(-140.0, 30.0, -100.0, 40.0),
   *     vertexFormat : Cesium.PerInstanceColorAppearance.VERTEX_FORMAT
   *   }),
   *   id : 'rectangle',
   *   attributes : {
   *     color : new Cesium.ColorGeometryInstanceAttribute(0.0, 1.0, 1.0, 0.5)
   *   }
   * });
   * const ellipsoidInstance = new Cesium.GeometryInstance({
   *   geometry : new Cesium.EllipsoidGeometry({
   *     radii : new Cesium.Cartesian3(500000.0, 500000.0, 1000000.0),
   *     vertexFormat : Cesium.VertexFormat.POSITION_AND_NORMAL
   *   }),
   *   modelMatrix : Cesium.Matrix4.multiplyByTranslation(Cesium.Transforms.eastNorthUpToFixedFrame(
   *     Cesium.Cartesian3.fromDegrees(-95.59777, 40.03883)), new Cesium.Cartesian3(0.0, 0.0, 500000.0), new Cesium.Matrix4()),
   *   id : 'ellipsoid',
   *   attributes : {
   *     color : Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.AQUA)
   *   }
   * });
   * scene.primitives.add(new Cesium.Primitive({
   *   geometryInstances : [rectangleInstance, ellipsoidInstance],
   *   appearance : new Cesium.PerInstanceColorAppearance()
   * }));
   *
   * @example
   * // 3. Create the geometry on the main thread.
   * scene.primitives.add(new Cesium.Primitive({
   *   geometryInstances : new Cesium.GeometryInstance({
   *     geometry : Cesium.EllipsoidGeometry.createGeometry(new Cesium.EllipsoidGeometry({
   *       radii : new Cesium.Cartesian3(500000.0, 500000.0, 1000000.0),
   *       vertexFormat : Cesium.VertexFormat.POSITION_AND_NORMAL
   *     })),
   *     modelMatrix : Cesium.Matrix4.multiplyByTranslation(Cesium.Transforms.eastNorthUpToFixedFrame(
   *       Cesium.Cartesian3.fromDegrees(-95.59777, 40.03883)), new Cesium.Cartesian3(0.0, 0.0, 500000.0), new Cesium.Matrix4()),
   *     id : 'ellipsoid',
   *     attributes : {
   *       color : Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.AQUA)
   *     }
   *   }),
   *   appearance : new Cesium.PerInstanceColorAppearance(),
   *   asynchronous : false
   * }));
   *
   * @see GeometryInstance
   * @see Appearance
   * @see ClassificationPrimitive
   * @see GroundPrimitive
   */
  function Primitive$3(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    /**
     * The geometry instances rendered with this primitive.  This may
     * be <code>undefined</code> if <code>options.releaseGeometryInstances</code>
     * is <code>true</code> when the primitive is constructed.
     * <p>
     * Changing this property after the primitive is rendered has no effect.
     * </p>
     *
     * @readonly
     * @type GeometryInstance[]|GeometryInstance
     *
     * @default undefined
     */
    this.geometryInstances = options.geometryInstances;

    /**
     * The {@link Appearance} used to shade this primitive. Each geometry
     * instance is shaded with the same appearance.  Some appearances, like
     * {@link PerInstanceColorAppearance} allow giving each instance unique
     * properties.
     *
     * @type Appearance
     *
     * @default undefined
     */
    this.appearance = options.appearance;
    this._appearance = undefined;
    this._material = undefined;

    /**
     * The {@link Appearance} used to shade this primitive when it fails the depth test. Each geometry
     * instance is shaded with the same appearance.  Some appearances, like
     * {@link PerInstanceColorAppearance} allow giving each instance unique
     * properties.
     *
     * <p>
     * When using an appearance that requires a color attribute, like PerInstanceColorAppearance,
     * add a depthFailColor per-instance attribute instead.
     * </p>
     *
     * <p>
     * Requires the EXT_frag_depth WebGL extension to render properly. If the extension is not supported,
     * there may be artifacts.
     * </p>
     * @type Appearance
     *
     * @default undefined
     */
    this.depthFailAppearance = options.depthFailAppearance;
    this._depthFailAppearance = undefined;
    this._depthFailMaterial = undefined;

    /**
     * The 4x4 transformation matrix that transforms the primitive (all geometry instances) from model to world coordinates.
     * When this is the identity matrix, the primitive is drawn in world coordinates, i.e., Earth's WGS84 coordinates.
     * Local reference frames can be used by providing a different transformation matrix, like that returned
     * by {@link Transforms.eastNorthUpToFixedFrame}.
     *
     * <p>
     * This property is only supported in 3D mode.
     * </p>
     *
     * @type Matrix4
     *
     * @default Matrix4.IDENTITY
     *
     * @example
     * const origin = Cesium.Cartesian3.fromDegrees(-95.0, 40.0, 200000.0);
     * p.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(origin);
     */
    this.modelMatrix = Matrix4.clone(
      defaultValue(options.modelMatrix, Matrix4.IDENTITY)
    );
    this._modelMatrix = new Matrix4();

    /**
     * Determines if the primitive will be shown.  This affects all geometry
     * instances in the primitive.
     *
     * @type Boolean
     *
     * @default true
     */
    this.show = defaultValue(options.show, true);

    this._vertexCacheOptimize = defaultValue(options.vertexCacheOptimize, false);
    this._interleave = defaultValue(options.interleave, false);
    this._releaseGeometryInstances = defaultValue(
      options.releaseGeometryInstances,
      true
    );
    this._allowPicking = defaultValue(options.allowPicking, true);
    this._asynchronous = defaultValue(options.asynchronous, true);
    this._compressVertices = defaultValue(options.compressVertices, true);

    /**
     * When <code>true</code>, the renderer frustum culls and horizon culls the primitive's commands
     * based on their bounding volume.  Set this to <code>false</code> for a small performance gain
     * if you are manually culling the primitive.
     *
     * @type {Boolean}
     *
     * @default true
     */
    this.cull = defaultValue(options.cull, true);

    /**
     * This property is for debugging only; it is not for production use nor is it optimized.
     * <p>
     * Draws the bounding sphere for each draw command in the primitive.
     * </p>
     *
     * @type {Boolean}
     *
     * @default false
     */
    this.debugShowBoundingVolume = defaultValue(
      options.debugShowBoundingVolume,
      false
    );

    /**
     * @private
     */
    this.rtcCenter = options.rtcCenter;

    //>>includeStart('debug', pragmas.debug);
    if (
      defined(this.rtcCenter) &&
      (!defined(this.geometryInstances) ||
        (Array.isArray(this.geometryInstances) &&
          this.geometryInstances.length !== 1))
    ) {
      throw new DeveloperError(
        "Relative-to-center rendering only supports one geometry instance."
      );
    }
    //>>includeEnd('debug');

    /**
     * Determines whether this primitive casts or receives shadows from light sources.
     *
     * @type {ShadowMode}
     *
     * @default ShadowMode.DISABLED
     */
    this.shadows = defaultValue(options.shadows, ShadowMode$1.DISABLED);

    this._translucent = undefined;

    this._state = PrimitiveState$1.READY;
    this._geometries = [];
    this._error = undefined;
    this._numberOfInstances = 0;

    this._boundingSpheres = [];
    this._boundingSphereWC = [];
    this._boundingSphereCV = [];
    this._boundingSphere2D = [];
    this._boundingSphereMorph = [];
    this._perInstanceAttributeCache = [];
    this._instanceIds = [];
    this._lastPerInstanceAttributeIndex = 0;

    this._va = [];
    this._attributeLocations = undefined;
    this._primitiveType = undefined;

    this._frontFaceRS = undefined;
    this._backFaceRS = undefined;
    this._sp = undefined;

    this._depthFailAppearance = undefined;
    this._spDepthFail = undefined;
    this._frontFaceDepthFailRS = undefined;
    this._backFaceDepthFailRS = undefined;

    this._pickIds = [];

    this._colorCommands = [];
    this._pickCommands = [];

    this._createBoundingVolumeFunction = options._createBoundingVolumeFunction;
    this._createRenderStatesFunction = options._createRenderStatesFunction;
    this._createShaderProgramFunction = options._createShaderProgramFunction;
    this._createCommandsFunction = options._createCommandsFunction;
    this._updateAndQueueCommandsFunction =
      options._updateAndQueueCommandsFunction;

    this._createPickOffsets = options._createPickOffsets;
    this._pickOffsets = undefined;

    this._createGeometryResults = undefined;
    this._ready = false;
    this._readyPromise = defer();

    this._batchTable = undefined;
    this._batchTableAttributeIndices = undefined;
    this._offsetInstanceExtend = undefined;
    this._batchTableOffsetAttribute2DIndex = undefined;
    this._batchTableOffsetsUpdated = false;
    this._instanceBoundingSpheres = undefined;
    this._instanceBoundingSpheresCV = undefined;
    this._tempBoundingSpheres = undefined;
    this._recomputeBoundingSpheres = false;
    this._batchTableBoundingSpheresUpdated = false;
    this._batchTableBoundingSphereAttributeIndices = undefined;
  }

  Object.defineProperties(Primitive$3.prototype, {
    /**
     * When <code>true</code>, geometry vertices are optimized for the pre and post-vertex-shader caches.
     *
     * @memberof Primitive.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default true
     */
    vertexCacheOptimize: {
      get: function () {
        return this._vertexCacheOptimize;
      },
    },

    /**
     * Determines if geometry vertex attributes are interleaved, which can slightly improve rendering performance.
     *
     * @memberof Primitive.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default false
     */
    interleave: {
      get: function () {
        return this._interleave;
      },
    },

    /**
     * When <code>true</code>, the primitive does not keep a reference to the input <code>geometryInstances</code> to save memory.
     *
     * @memberof Primitive.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default true
     */
    releaseGeometryInstances: {
      get: function () {
        return this._releaseGeometryInstances;
      },
    },

    /**
     * When <code>true</code>, each geometry instance will only be pickable with {@link Scene#pick}.  When <code>false</code>, GPU memory is saved.         *
     *
     * @memberof Primitive.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default true
     */
    allowPicking: {
      get: function () {
        return this._allowPicking;
      },
    },

    /**
     * Determines if the geometry instances will be created and batched on a web worker.
     *
     * @memberof Primitive.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default true
     */
    asynchronous: {
      get: function () {
        return this._asynchronous;
      },
    },

    /**
     * When <code>true</code>, geometry vertices are compressed, which will save memory.
     *
     * @memberof Primitive.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default true
     */
    compressVertices: {
      get: function () {
        return this._compressVertices;
      },
    },

    /**
     * Determines if the primitive is complete and ready to render.  If this property is
     * true, the primitive will be rendered the next time that {@link Primitive#update}
     * is called.
     *
     * @memberof Primitive.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    ready: {
      get: function () {
        return this._ready;
      },
    },

    /**
     * Gets a promise that resolves when the primitive is ready to render.
     * @memberof Primitive.prototype
     * @type {Promise.<Primitive>}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._readyPromise.promise;
      },
    },
  });

  function getCommonPerInstanceAttributeNames(instances) {
    const length = instances.length;

    const attributesInAllInstances = [];
    const attributes0 = instances[0].attributes;
    let name;

    for (name in attributes0) {
      if (attributes0.hasOwnProperty(name) && defined(attributes0[name])) {
        const attribute = attributes0[name];
        let inAllInstances = true;

        // Does this same attribute exist in all instances?
        for (let i = 1; i < length; ++i) {
          const otherAttribute = instances[i].attributes[name];

          if (
            !defined(otherAttribute) ||
            attribute.componentDatatype !== otherAttribute.componentDatatype ||
            attribute.componentsPerAttribute !==
              otherAttribute.componentsPerAttribute ||
            attribute.normalize !== otherAttribute.normalize
          ) {
            inAllInstances = false;
            break;
          }
        }

        if (inAllInstances) {
          attributesInAllInstances.push(name);
        }
      }
    }

    return attributesInAllInstances;
  }

  const scratchGetAttributeCartesian2 = new Cartesian2();
  const scratchGetAttributeCartesian3 = new Cartesian3();
  const scratchGetAttributeCartesian4 = new Cartesian4();

  function getAttributeValue(value) {
    const componentsPerAttribute = value.length;
    if (componentsPerAttribute === 1) {
      return value[0];
    } else if (componentsPerAttribute === 2) {
      return Cartesian2.unpack(value, 0, scratchGetAttributeCartesian2);
    } else if (componentsPerAttribute === 3) {
      return Cartesian3.unpack(value, 0, scratchGetAttributeCartesian3);
    } else if (componentsPerAttribute === 4) {
      return Cartesian4.unpack(value, 0, scratchGetAttributeCartesian4);
    }
  }

  function createBatchTable$1(primitive, context) {
    const geometryInstances = primitive.geometryInstances;
    const instances = Array.isArray(geometryInstances)
      ? geometryInstances
      : [geometryInstances];
    const numberOfInstances = instances.length;
    if (numberOfInstances === 0) {
      return;
    }

    const names = getCommonPerInstanceAttributeNames(instances);
    const length = names.length;

    const attributes = [];
    const attributeIndices = {};
    const boundingSphereAttributeIndices = {};
    let offset2DIndex;

    const firstInstance = instances[0];
    let instanceAttributes = firstInstance.attributes;

    let i;
    let name;
    let attribute;

    for (i = 0; i < length; ++i) {
      name = names[i];
      attribute = instanceAttributes[name];

      attributeIndices[name] = i;
      attributes.push({
        functionName: `czm_batchTable_${name}`,
        componentDatatype: attribute.componentDatatype,
        componentsPerAttribute: attribute.componentsPerAttribute,
        normalize: attribute.normalize,
      });
    }

    if (names.indexOf("distanceDisplayCondition") !== -1) {
      attributes.push(
        {
          functionName: "czm_batchTable_boundingSphereCenter3DHigh",
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 3,
        },
        {
          functionName: "czm_batchTable_boundingSphereCenter3DLow",
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 3,
        },
        {
          functionName: "czm_batchTable_boundingSphereCenter2DHigh",
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 3,
        },
        {
          functionName: "czm_batchTable_boundingSphereCenter2DLow",
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 3,
        },
        {
          functionName: "czm_batchTable_boundingSphereRadius",
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 1,
        }
      );
      boundingSphereAttributeIndices.center3DHigh = attributes.length - 5;
      boundingSphereAttributeIndices.center3DLow = attributes.length - 4;
      boundingSphereAttributeIndices.center2DHigh = attributes.length - 3;
      boundingSphereAttributeIndices.center2DLow = attributes.length - 2;
      boundingSphereAttributeIndices.radius = attributes.length - 1;
    }

    if (names.indexOf("offset") !== -1) {
      attributes.push({
        functionName: "czm_batchTable_offset2D",
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 3,
      });
      offset2DIndex = attributes.length - 1;
    }

    attributes.push({
      functionName: "czm_batchTable_pickColor",
      componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
      componentsPerAttribute: 4,
      normalize: true,
    });

    const attributesLength = attributes.length;
    const batchTable = new BatchTable(context, attributes, numberOfInstances);

    for (i = 0; i < numberOfInstances; ++i) {
      const instance = instances[i];
      instanceAttributes = instance.attributes;

      for (let j = 0; j < length; ++j) {
        name = names[j];
        attribute = instanceAttributes[name];
        const value = getAttributeValue(attribute.value);
        const attributeIndex = attributeIndices[name];
        batchTable.setBatchedAttribute(i, attributeIndex, value);
      }

      const pickObject = {
        primitive: defaultValue(instance.pickPrimitive, primitive),
      };

      if (defined(instance.id)) {
        pickObject.id = instance.id;
      }

      const pickId = context.createPickId(pickObject);
      primitive._pickIds.push(pickId);

      const pickColor = pickId.color;
      const color = scratchGetAttributeCartesian4;
      color.x = Color.floatToByte(pickColor.red);
      color.y = Color.floatToByte(pickColor.green);
      color.z = Color.floatToByte(pickColor.blue);
      color.w = Color.floatToByte(pickColor.alpha);

      batchTable.setBatchedAttribute(i, attributesLength - 1, color);
    }

    primitive._batchTable = batchTable;
    primitive._batchTableAttributeIndices = attributeIndices;
    primitive._batchTableBoundingSphereAttributeIndices = boundingSphereAttributeIndices;
    primitive._batchTableOffsetAttribute2DIndex = offset2DIndex;
  }

  function cloneAttribute(attribute) {
    let clonedValues;
    if (Array.isArray(attribute.values)) {
      clonedValues = attribute.values.slice(0);
    } else {
      clonedValues = new attribute.values.constructor(attribute.values);
    }
    return new GeometryAttribute({
      componentDatatype: attribute.componentDatatype,
      componentsPerAttribute: attribute.componentsPerAttribute,
      normalize: attribute.normalize,
      values: clonedValues,
    });
  }

  function cloneGeometry(geometry) {
    const attributes = geometry.attributes;
    const newAttributes = new GeometryAttributes();
    for (const property in attributes) {
      if (attributes.hasOwnProperty(property) && defined(attributes[property])) {
        newAttributes[property] = cloneAttribute(attributes[property]);
      }
    }

    let indices;
    if (defined(geometry.indices)) {
      const sourceValues = geometry.indices;
      if (Array.isArray(sourceValues)) {
        indices = sourceValues.slice(0);
      } else {
        indices = new sourceValues.constructor(sourceValues);
      }
    }

    return new Geometry({
      attributes: newAttributes,
      indices: indices,
      primitiveType: geometry.primitiveType,
      boundingSphere: BoundingSphere.clone(geometry.boundingSphere),
    });
  }

  function cloneInstance(instance, geometry) {
    return {
      geometry: geometry,
      attributes: instance.attributes,
      modelMatrix: Matrix4.clone(instance.modelMatrix),
      pickPrimitive: instance.pickPrimitive,
      id: instance.id,
    };
  }

  const positionRegex = /attribute\s+vec(?:3|4)\s+(.*)3DHigh;/g;

  Primitive$3._modifyShaderPosition = function (
    primitive,
    vertexShaderSource,
    scene3DOnly
  ) {
    let match;

    let forwardDecl = "";
    let attributes = "";
    let computeFunctions = "";

    while ((match = positionRegex.exec(vertexShaderSource)) !== null) {
      const name = match[1];

      const functionName = `vec4 czm_compute${name[0].toUpperCase()}${name.substr(
      1
    )}()`;

      // Don't forward-declare czm_computePosition because computePosition.glsl already does.
      if (functionName !== "vec4 czm_computePosition()") {
        forwardDecl += `${functionName};\n`;
      }

      if (!defined(primitive.rtcCenter)) {
        // Use GPU RTE
        if (!scene3DOnly) {
          attributes +=
            `attribute vec3 ${name}2DHigh;\n` + `attribute vec3 ${name}2DLow;\n`;

          computeFunctions +=
            `${functionName}\n` +
            `{\n` +
            `    vec4 p;\n` +
            `    if (czm_morphTime == 1.0)\n` +
            `    {\n` +
            `        p = czm_translateRelativeToEye(${name}3DHigh, ${name}3DLow);\n` +
            `    }\n` +
            `    else if (czm_morphTime == 0.0)\n` +
            `    {\n` +
            `        p = czm_translateRelativeToEye(${name}2DHigh.zxy, ${name}2DLow.zxy);\n` +
            `    }\n` +
            `    else\n` +
            `    {\n` +
            `        p = czm_columbusViewMorph(\n` +
            `                czm_translateRelativeToEye(${name}2DHigh.zxy, ${name}2DLow.zxy),\n` +
            `                czm_translateRelativeToEye(${name}3DHigh, ${name}3DLow),\n` +
            `                czm_morphTime);\n` +
            `    }\n` +
            `    return p;\n` +
            `}\n\n`;
        } else {
          computeFunctions +=
            `${functionName}\n` +
            `{\n` +
            `    return czm_translateRelativeToEye(${name}3DHigh, ${name}3DLow);\n` +
            `}\n\n`;
        }
      } else {
        // Use RTC
        vertexShaderSource = vertexShaderSource.replace(
          /attribute\s+vec(?:3|4)\s+position3DHigh;/g,
          ""
        );
        vertexShaderSource = vertexShaderSource.replace(
          /attribute\s+vec(?:3|4)\s+position3DLow;/g,
          ""
        );

        forwardDecl += "uniform mat4 u_modifiedModelView;\n";
        attributes += "attribute vec4 position;\n";

        computeFunctions +=
          `${functionName}\n` +
          `{\n` +
          `    return u_modifiedModelView * position;\n` +
          `}\n\n`;

        vertexShaderSource = vertexShaderSource.replace(
          /czm_modelViewRelativeToEye\s+\*\s+/g,
          ""
        );
        vertexShaderSource = vertexShaderSource.replace(
          /czm_modelViewProjectionRelativeToEye/g,
          "czm_projection"
        );
      }
    }

    return [forwardDecl, attributes, vertexShaderSource, computeFunctions].join(
      "\n"
    );
  };

  Primitive$3._appendShowToShader = function (primitive, vertexShaderSource) {
    if (!defined(primitive._batchTableAttributeIndices.show)) {
      return vertexShaderSource;
    }

    const renamedVS = ShaderSource.replaceMain(
      vertexShaderSource,
      "czm_non_show_main"
    );
    const showMain =
      "void main() \n" +
      "{ \n" +
      "    czm_non_show_main(); \n" +
      "    gl_Position *= czm_batchTable_show(batchId); \n" +
      "}";

    return `${renamedVS}\n${showMain}`;
  };

  Primitive$3._updateColorAttribute = function (
    primitive,
    vertexShaderSource,
    isDepthFail
  ) {
    // some appearances have a color attribute for per vertex color.
    // only remove if color is a per instance attribute.
    if (
      !defined(primitive._batchTableAttributeIndices.color) &&
      !defined(primitive._batchTableAttributeIndices.depthFailColor)
    ) {
      return vertexShaderSource;
    }

    if (vertexShaderSource.search(/attribute\s+vec4\s+color;/g) === -1) {
      return vertexShaderSource;
    }

    //>>includeStart('debug', pragmas.debug);
    if (
      isDepthFail &&
      !defined(primitive._batchTableAttributeIndices.depthFailColor)
    ) {
      throw new DeveloperError(
        "A depthFailColor per-instance attribute is required when using a depth fail appearance that uses a color attribute."
      );
    }
    //>>includeEnd('debug');

    let modifiedVS = vertexShaderSource;
    modifiedVS = modifiedVS.replace(/attribute\s+vec4\s+color;/g, "");
    if (!isDepthFail) {
      modifiedVS = modifiedVS.replace(
        /(\b)color(\b)/g,
        "$1czm_batchTable_color(batchId)$2"
      );
    } else {
      modifiedVS = modifiedVS.replace(
        /(\b)color(\b)/g,
        "$1czm_batchTable_depthFailColor(batchId)$2"
      );
    }
    return modifiedVS;
  };

  function appendPickToVertexShader(source) {
    const renamedVS = ShaderSource.replaceMain(source, "czm_non_pick_main");
    const pickMain =
      "varying vec4 v_pickColor; \n" +
      "void main() \n" +
      "{ \n" +
      "    czm_non_pick_main(); \n" +
      "    v_pickColor = czm_batchTable_pickColor(batchId); \n" +
      "}";

    return `${renamedVS}\n${pickMain}`;
  }

  function appendPickToFragmentShader(source) {
    return `varying vec4 v_pickColor;\n${source}`;
  }

  Primitive$3._updatePickColorAttribute = function (source) {
    let vsPick = source.replace(/attribute\s+vec4\s+pickColor;/g, "");
    vsPick = vsPick.replace(
      /(\b)pickColor(\b)/g,
      "$1czm_batchTable_pickColor(batchId)$2"
    );
    return vsPick;
  };

  Primitive$3._appendOffsetToShader = function (primitive, vertexShaderSource) {
    if (!defined(primitive._batchTableAttributeIndices.offset)) {
      return vertexShaderSource;
    }

    let attr = "attribute float batchId;\n";
    attr += "attribute float applyOffset;";
    let modifiedShader = vertexShaderSource.replace(
      /attribute\s+float\s+batchId;/g,
      attr
    );

    let str = "vec4 $1 = czm_computePosition();\n";
    str += "    if (czm_sceneMode == czm_sceneMode3D)\n";
    str += "    {\n";
    str +=
      "        $1 = $1 + vec4(czm_batchTable_offset(batchId) * applyOffset, 0.0);";
    str += "    }\n";
    str += "    else\n";
    str += "    {\n";
    str +=
      "        $1 = $1 + vec4(czm_batchTable_offset2D(batchId) * applyOffset, 0.0);";
    str += "    }\n";
    modifiedShader = modifiedShader.replace(
      /vec4\s+([A-Za-z0-9_]+)\s+=\s+czm_computePosition\(\);/g,
      str
    );
    return modifiedShader;
  };

  Primitive$3._appendDistanceDisplayConditionToShader = function (
    primitive,
    vertexShaderSource,
    scene3DOnly
  ) {
    if (
      !defined(primitive._batchTableAttributeIndices.distanceDisplayCondition)
    ) {
      return vertexShaderSource;
    }

    const renamedVS = ShaderSource.replaceMain(
      vertexShaderSource,
      "czm_non_distanceDisplayCondition_main"
    );
    let distanceDisplayConditionMain =
      "void main() \n" +
      "{ \n" +
      "    czm_non_distanceDisplayCondition_main(); \n" +
      "    vec2 distanceDisplayCondition = czm_batchTable_distanceDisplayCondition(batchId);\n" +
      "    vec3 boundingSphereCenter3DHigh = czm_batchTable_boundingSphereCenter3DHigh(batchId);\n" +
      "    vec3 boundingSphereCenter3DLow = czm_batchTable_boundingSphereCenter3DLow(batchId);\n" +
      "    float boundingSphereRadius = czm_batchTable_boundingSphereRadius(batchId);\n";

    if (!scene3DOnly) {
      distanceDisplayConditionMain +=
        "    vec3 boundingSphereCenter2DHigh = czm_batchTable_boundingSphereCenter2DHigh(batchId);\n" +
        "    vec3 boundingSphereCenter2DLow = czm_batchTable_boundingSphereCenter2DLow(batchId);\n" +
        "    vec4 centerRTE;\n" +
        "    if (czm_morphTime == 1.0)\n" +
        "    {\n" +
        "        centerRTE = czm_translateRelativeToEye(boundingSphereCenter3DHigh, boundingSphereCenter3DLow);\n" +
        "    }\n" +
        "    else if (czm_morphTime == 0.0)\n" +
        "    {\n" +
        "        centerRTE = czm_translateRelativeToEye(boundingSphereCenter2DHigh.zxy, boundingSphereCenter2DLow.zxy);\n" +
        "    }\n" +
        "    else\n" +
        "    {\n" +
        "        centerRTE = czm_columbusViewMorph(\n" +
        "                czm_translateRelativeToEye(boundingSphereCenter2DHigh.zxy, boundingSphereCenter2DLow.zxy),\n" +
        "                czm_translateRelativeToEye(boundingSphereCenter3DHigh, boundingSphereCenter3DLow),\n" +
        "                czm_morphTime);\n" +
        "    }\n";
    } else {
      distanceDisplayConditionMain +=
        "    vec4 centerRTE = czm_translateRelativeToEye(boundingSphereCenter3DHigh, boundingSphereCenter3DLow);\n";
    }

    distanceDisplayConditionMain +=
      "    float radiusSq = boundingSphereRadius * boundingSphereRadius; \n" +
      "    float distanceSq; \n" +
      "    if (czm_sceneMode == czm_sceneMode2D) \n" +
      "    { \n" +
      "        distanceSq = czm_eyeHeight2D.y - radiusSq; \n" +
      "    } \n" +
      "    else \n" +
      "    { \n" +
      "        distanceSq = dot(centerRTE.xyz, centerRTE.xyz) - radiusSq; \n" +
      "    } \n" +
      "    distanceSq = max(distanceSq, 0.0); \n" +
      "    float nearSq = distanceDisplayCondition.x * distanceDisplayCondition.x; \n" +
      "    float farSq = distanceDisplayCondition.y * distanceDisplayCondition.y; \n" +
      "    float show = (distanceSq >= nearSq && distanceSq <= farSq) ? 1.0 : 0.0; \n" +
      "    gl_Position *= show; \n" +
      "}";
    return `${renamedVS}\n${distanceDisplayConditionMain}`;
  };

  function modifyForEncodedNormals$1(primitive, vertexShaderSource) {
    if (!primitive.compressVertices) {
      return vertexShaderSource;
    }

    const containsNormal =
      vertexShaderSource.search(/attribute\s+vec3\s+normal;/g) !== -1;
    const containsSt =
      vertexShaderSource.search(/attribute\s+vec2\s+st;/g) !== -1;
    if (!containsNormal && !containsSt) {
      return vertexShaderSource;
    }

    const containsTangent =
      vertexShaderSource.search(/attribute\s+vec3\s+tangent;/g) !== -1;
    const containsBitangent =
      vertexShaderSource.search(/attribute\s+vec3\s+bitangent;/g) !== -1;

    let numComponents = containsSt && containsNormal ? 2.0 : 1.0;
    numComponents += containsTangent || containsBitangent ? 1 : 0;

    const type = numComponents > 1 ? `vec${numComponents}` : "float";

    const attributeName = "compressedAttributes";
    const attributeDecl = `attribute ${type} ${attributeName};`;

    let globalDecl = "";
    let decode = "";

    if (containsSt) {
      globalDecl += "vec2 st;\n";
      const stComponent =
        numComponents > 1 ? `${attributeName}.x` : attributeName;
      decode += `    st = czm_decompressTextureCoordinates(${stComponent});\n`;
    }

    if (containsNormal && containsTangent && containsBitangent) {
      globalDecl += "vec3 normal;\n" + "vec3 tangent;\n" + "vec3 bitangent;\n";
      decode += `    czm_octDecode(${attributeName}.${
      containsSt ? "yz" : "xy"
    }, normal, tangent, bitangent);\n`;
    } else {
      if (containsNormal) {
        globalDecl += "vec3 normal;\n";
        decode += `    normal = czm_octDecode(${attributeName}${
        numComponents > 1 ? `.${containsSt ? "y" : "x"}` : ""
      });\n`;
      }

      if (containsTangent) {
        globalDecl += "vec3 tangent;\n";
        decode += `    tangent = czm_octDecode(${attributeName}.${
        containsSt && containsNormal ? "z" : "y"
      });\n`;
      }

      if (containsBitangent) {
        globalDecl += "vec3 bitangent;\n";
        decode += `    bitangent = czm_octDecode(${attributeName}.${
        containsSt && containsNormal ? "z" : "y"
      });\n`;
      }
    }

    let modifiedVS = vertexShaderSource;
    modifiedVS = modifiedVS.replace(/attribute\s+vec3\s+normal;/g, "");
    modifiedVS = modifiedVS.replace(/attribute\s+vec2\s+st;/g, "");
    modifiedVS = modifiedVS.replace(/attribute\s+vec3\s+tangent;/g, "");
    modifiedVS = modifiedVS.replace(/attribute\s+vec3\s+bitangent;/g, "");
    modifiedVS = ShaderSource.replaceMain(modifiedVS, "czm_non_compressed_main");
    const compressedMain =
      `${"void main() \n" + "{ \n"}${decode}    czm_non_compressed_main(); \n` +
      `}`;

    return [attributeDecl, globalDecl, modifiedVS, compressedMain].join("\n");
  }

  function depthClampVS(vertexShaderSource) {
    let modifiedVS = ShaderSource.replaceMain(
      vertexShaderSource,
      "czm_non_depth_clamp_main"
    );
    modifiedVS +=
      "void main() {\n" +
      "    czm_non_depth_clamp_main();\n" +
      "    gl_Position = czm_depthClamp(gl_Position);" +
      "}\n";
    return modifiedVS;
  }

  function depthClampFS(fragmentShaderSource) {
    let modifiedFS = ShaderSource.replaceMain(
      fragmentShaderSource,
      "czm_non_depth_clamp_main"
    );
    modifiedFS +=
      "void main() {\n" +
      "    czm_non_depth_clamp_main();\n" +
      "#if defined(GL_EXT_frag_depth)\n" +
      "    #if defined(LOG_DEPTH)\n" +
      "        czm_writeLogDepth();\n" +
      "    #else\n" +
      "        czm_writeDepthClamp();\n" +
      "    #endif\n" +
      "#endif\n" +
      "}\n";
    modifiedFS = `${
    "#ifdef GL_EXT_frag_depth\n" +
    "#extension GL_EXT_frag_depth : enable\n" +
    "#endif\n"
  }${modifiedFS}`;
    return modifiedFS;
  }

  function validateShaderMatching(shaderProgram, attributeLocations) {
    // For a VAO and shader program to be compatible, the VAO must have
    // all active attribute in the shader program.  The VAO may have
    // extra attributes with the only concern being a potential
    // performance hit due to extra memory bandwidth and cache pollution.
    // The shader source could have extra attributes that are not used,
    // but there is no guarantee they will be optimized out.
    //
    // Here, we validate that the VAO has all attributes required
    // to match the shader program.
    const shaderAttributes = shaderProgram.vertexAttributes;

    //>>includeStart('debug', pragmas.debug);
    for (const name in shaderAttributes) {
      if (shaderAttributes.hasOwnProperty(name)) {
        if (!defined(attributeLocations[name])) {
          throw new DeveloperError(
            `Appearance/Geometry mismatch.  The appearance requires vertex shader attribute input '${name}', which was not computed as part of the Geometry.  Use the appearance's vertexFormat property when constructing the geometry.`
          );
        }
      }
    }
    //>>includeEnd('debug');
  }

  function getUniformFunction(uniforms, name) {
    return function () {
      return uniforms[name];
    };
  }

  const numberOfCreationWorkers = Math.max(
    FeatureDetection.hardwareConcurrency - 1,
    1
  );
  let createGeometryTaskProcessors;
  const combineGeometryTaskProcessor = new TaskProcessor("combineGeometry");

  function loadAsynchronous(primitive, frameState) {
    let instances;
    let geometry;
    let i;
    let j;

    const instanceIds = primitive._instanceIds;

    if (primitive._state === PrimitiveState$1.READY) {
      instances = Array.isArray(primitive.geometryInstances)
        ? primitive.geometryInstances
        : [primitive.geometryInstances];
      const length = (primitive._numberOfInstances = instances.length);

      const promises = [];
      let subTasks = [];
      for (i = 0; i < length; ++i) {
        geometry = instances[i].geometry;
        instanceIds.push(instances[i].id);

        //>>includeStart('debug', pragmas.debug);
        if (!defined(geometry._workerName)) {
          throw new DeveloperError(
            "_workerName must be defined for asynchronous geometry."
          );
        }
        //>>includeEnd('debug');

        subTasks.push({
          moduleName: geometry._workerName,
          geometry: geometry,
        });
      }

      if (!defined(createGeometryTaskProcessors)) {
        createGeometryTaskProcessors = new Array(numberOfCreationWorkers);
        for (i = 0; i < numberOfCreationWorkers; i++) {
          createGeometryTaskProcessors[i] = new TaskProcessor("createGeometry");
        }
      }

      let subTask;
      subTasks = subdivideArray(subTasks, numberOfCreationWorkers);

      for (i = 0; i < subTasks.length; i++) {
        let packedLength = 0;
        const workerSubTasks = subTasks[i];
        const workerSubTasksLength = workerSubTasks.length;
        for (j = 0; j < workerSubTasksLength; ++j) {
          subTask = workerSubTasks[j];
          geometry = subTask.geometry;
          if (defined(geometry.constructor.pack)) {
            subTask.offset = packedLength;
            packedLength += defaultValue(
              geometry.constructor.packedLength,
              geometry.packedLength
            );
          }
        }

        let subTaskTransferableObjects;

        if (packedLength > 0) {
          const array = new Float64Array(packedLength);
          subTaskTransferableObjects = [array.buffer];

          for (j = 0; j < workerSubTasksLength; ++j) {
            subTask = workerSubTasks[j];
            geometry = subTask.geometry;
            if (defined(geometry.constructor.pack)) {
              geometry.constructor.pack(geometry, array, subTask.offset);
              subTask.geometry = array;
            }
          }
        }

        promises.push(
          createGeometryTaskProcessors[i].scheduleTask(
            {
              subTasks: subTasks[i],
            },
            subTaskTransferableObjects
          )
        );
      }

      primitive._state = PrimitiveState$1.CREATING;

      Promise.all(promises)
        .then(function (results) {
          primitive._createGeometryResults = results;
          primitive._state = PrimitiveState$1.CREATED;
        })
        .catch(function (error) {
          setReady(primitive, frameState, PrimitiveState$1.FAILED, error);
        });
    } else if (primitive._state === PrimitiveState$1.CREATED) {
      const transferableObjects = [];
      instances = Array.isArray(primitive.geometryInstances)
        ? primitive.geometryInstances
        : [primitive.geometryInstances];

      const scene3DOnly = frameState.scene3DOnly;
      const projection = frameState.mapProjection;

      const promise = combineGeometryTaskProcessor.scheduleTask(
        PrimitivePipeline.packCombineGeometryParameters(
          {
            createGeometryResults: primitive._createGeometryResults,
            instances: instances,
            ellipsoid: projection.ellipsoid,
            projection: projection,
            elementIndexUintSupported: frameState.context.elementIndexUint,
            scene3DOnly: scene3DOnly,
            vertexCacheOptimize: primitive.vertexCacheOptimize,
            compressVertices: primitive.compressVertices,
            modelMatrix: primitive.modelMatrix,
            createPickOffsets: primitive._createPickOffsets,
          },
          transferableObjects
        ),
        transferableObjects
      );

      primitive._createGeometryResults = undefined;
      primitive._state = PrimitiveState$1.COMBINING;

      Promise.resolve(promise)
        .then(function (packedResult) {
          const result = PrimitivePipeline.unpackCombineGeometryResults(
            packedResult
          );
          primitive._geometries = result.geometries;
          primitive._attributeLocations = result.attributeLocations;
          primitive.modelMatrix = Matrix4.clone(
            result.modelMatrix,
            primitive.modelMatrix
          );
          primitive._pickOffsets = result.pickOffsets;
          primitive._offsetInstanceExtend = result.offsetInstanceExtend;
          primitive._instanceBoundingSpheres = result.boundingSpheres;
          primitive._instanceBoundingSpheresCV = result.boundingSpheresCV;

          if (
            defined(primitive._geometries) &&
            primitive._geometries.length > 0
          ) {
            primitive._recomputeBoundingSpheres = true;
            primitive._state = PrimitiveState$1.COMBINED;
          } else {
            setReady(primitive, frameState, PrimitiveState$1.FAILED, undefined);
          }
        })
        .catch(function (error) {
          setReady(primitive, frameState, PrimitiveState$1.FAILED, error);
        });
    }
  }

  function loadSynchronous(primitive, frameState) {
    const instances = Array.isArray(primitive.geometryInstances)
      ? primitive.geometryInstances
      : [primitive.geometryInstances];
    const length = (primitive._numberOfInstances = instances.length);
    const clonedInstances = new Array(length);
    const instanceIds = primitive._instanceIds;

    let instance;
    let i;

    let geometryIndex = 0;
    for (i = 0; i < length; i++) {
      instance = instances[i];
      const geometry = instance.geometry;

      let createdGeometry;
      if (defined(geometry.attributes) && defined(geometry.primitiveType)) {
        createdGeometry = cloneGeometry(geometry);
      } else {
        createdGeometry = geometry.constructor.createGeometry(geometry);
      }

      clonedInstances[geometryIndex++] = cloneInstance(instance, createdGeometry);
      instanceIds.push(instance.id);
    }

    clonedInstances.length = geometryIndex;

    const scene3DOnly = frameState.scene3DOnly;
    const projection = frameState.mapProjection;

    const result = PrimitivePipeline.combineGeometry({
      instances: clonedInstances,
      ellipsoid: projection.ellipsoid,
      projection: projection,
      elementIndexUintSupported: frameState.context.elementIndexUint,
      scene3DOnly: scene3DOnly,
      vertexCacheOptimize: primitive.vertexCacheOptimize,
      compressVertices: primitive.compressVertices,
      modelMatrix: primitive.modelMatrix,
      createPickOffsets: primitive._createPickOffsets,
    });

    primitive._geometries = result.geometries;
    primitive._attributeLocations = result.attributeLocations;
    primitive.modelMatrix = Matrix4.clone(
      result.modelMatrix,
      primitive.modelMatrix
    );
    primitive._pickOffsets = result.pickOffsets;
    primitive._offsetInstanceExtend = result.offsetInstanceExtend;
    primitive._instanceBoundingSpheres = result.boundingSpheres;
    primitive._instanceBoundingSpheresCV = result.boundingSpheresCV;

    if (defined(primitive._geometries) && primitive._geometries.length > 0) {
      primitive._recomputeBoundingSpheres = true;
      primitive._state = PrimitiveState$1.COMBINED;
    } else {
      setReady(primitive, frameState, PrimitiveState$1.FAILED, undefined);
    }
  }

  function recomputeBoundingSpheres(primitive, frameState) {
    const offsetIndex = primitive._batchTableAttributeIndices.offset;
    if (!primitive._recomputeBoundingSpheres || !defined(offsetIndex)) {
      primitive._recomputeBoundingSpheres = false;
      return;
    }

    let i;
    const offsetInstanceExtend = primitive._offsetInstanceExtend;
    const boundingSpheres = primitive._instanceBoundingSpheres;
    const length = boundingSpheres.length;
    let newBoundingSpheres = primitive._tempBoundingSpheres;
    if (!defined(newBoundingSpheres)) {
      newBoundingSpheres = new Array(length);
      for (i = 0; i < length; i++) {
        newBoundingSpheres[i] = new BoundingSphere();
      }
      primitive._tempBoundingSpheres = newBoundingSpheres;
    }
    for (i = 0; i < length; ++i) {
      let newBS = newBoundingSpheres[i];
      const offset = primitive._batchTable.getBatchedAttribute(
        i,
        offsetIndex,
        new Cartesian3()
      );
      newBS = boundingSpheres[i].clone(newBS);
      transformBoundingSphere(newBS, offset, offsetInstanceExtend[i]);
    }
    const combinedBS = [];
    const combinedWestBS = [];
    const combinedEastBS = [];

    for (i = 0; i < length; ++i) {
      const bs = newBoundingSpheres[i];

      const minX = bs.center.x - bs.radius;
      if (
        minX > 0 ||
        BoundingSphere.intersectPlane(bs, Plane.ORIGIN_ZX_PLANE) !==
          Intersect$1.INTERSECTING
      ) {
        combinedBS.push(bs);
      } else {
        combinedWestBS.push(bs);
        combinedEastBS.push(bs);
      }
    }

    let resultBS1 = combinedBS[0];
    let resultBS2 = combinedEastBS[0];
    let resultBS3 = combinedWestBS[0];

    for (i = 1; i < combinedBS.length; i++) {
      resultBS1 = BoundingSphere.union(resultBS1, combinedBS[i]);
    }
    for (i = 1; i < combinedEastBS.length; i++) {
      resultBS2 = BoundingSphere.union(resultBS2, combinedEastBS[i]);
    }
    for (i = 1; i < combinedWestBS.length; i++) {
      resultBS3 = BoundingSphere.union(resultBS3, combinedWestBS[i]);
    }
    const result = [];
    if (defined(resultBS1)) {
      result.push(resultBS1);
    }
    if (defined(resultBS2)) {
      result.push(resultBS2);
    }
    if (defined(resultBS3)) {
      result.push(resultBS3);
    }

    for (i = 0; i < result.length; i++) {
      const boundingSphere = result[i].clone(primitive._boundingSpheres[i]);
      primitive._boundingSpheres[i] = boundingSphere;
      primitive._boundingSphereCV[i] = BoundingSphere.projectTo2D(
        boundingSphere,
        frameState.mapProjection,
        primitive._boundingSphereCV[i]
      );
    }

    Primitive$3._updateBoundingVolumes(
      primitive,
      frameState,
      primitive.modelMatrix,
      true
    );
    primitive._recomputeBoundingSpheres = false;
  }

  const scratchBoundingSphereCenterEncoded = new EncodedCartesian3();
  const scratchBoundingSphereCartographic = new Cartographic();
  const scratchBoundingSphereCenter2D = new Cartesian3();
  const scratchBoundingSphere$3 = new BoundingSphere();

  function updateBatchTableBoundingSpheres(primitive, frameState) {
    const hasDistanceDisplayCondition = defined(
      primitive._batchTableAttributeIndices.distanceDisplayCondition
    );
    if (
      !hasDistanceDisplayCondition ||
      primitive._batchTableBoundingSpheresUpdated
    ) {
      return;
    }

    const indices = primitive._batchTableBoundingSphereAttributeIndices;
    const center3DHighIndex = indices.center3DHigh;
    const center3DLowIndex = indices.center3DLow;
    const center2DHighIndex = indices.center2DHigh;
    const center2DLowIndex = indices.center2DLow;
    const radiusIndex = indices.radius;

    const projection = frameState.mapProjection;
    const ellipsoid = projection.ellipsoid;

    const batchTable = primitive._batchTable;
    const boundingSpheres = primitive._instanceBoundingSpheres;
    const length = boundingSpheres.length;

    for (let i = 0; i < length; ++i) {
      let boundingSphere = boundingSpheres[i];
      if (!defined(boundingSphere)) {
        continue;
      }

      const modelMatrix = primitive.modelMatrix;
      if (defined(modelMatrix)) {
        boundingSphere = BoundingSphere.transform(
          boundingSphere,
          modelMatrix,
          scratchBoundingSphere$3
        );
      }

      const center = boundingSphere.center;
      const radius = boundingSphere.radius;

      let encodedCenter = EncodedCartesian3.fromCartesian(
        center,
        scratchBoundingSphereCenterEncoded
      );
      batchTable.setBatchedAttribute(i, center3DHighIndex, encodedCenter.high);
      batchTable.setBatchedAttribute(i, center3DLowIndex, encodedCenter.low);

      if (!frameState.scene3DOnly) {
        const cartographic = ellipsoid.cartesianToCartographic(
          center,
          scratchBoundingSphereCartographic
        );
        const center2D = projection.project(
          cartographic,
          scratchBoundingSphereCenter2D
        );
        encodedCenter = EncodedCartesian3.fromCartesian(
          center2D,
          scratchBoundingSphereCenterEncoded
        );
        batchTable.setBatchedAttribute(i, center2DHighIndex, encodedCenter.high);
        batchTable.setBatchedAttribute(i, center2DLowIndex, encodedCenter.low);
      }

      batchTable.setBatchedAttribute(i, radiusIndex, radius);
    }

    primitive._batchTableBoundingSpheresUpdated = true;
  }

  const offsetScratchCartesian = new Cartesian3();
  const offsetCenterScratch = new Cartesian3();
  function updateBatchTableOffsets(primitive, frameState) {
    const hasOffset = defined(primitive._batchTableAttributeIndices.offset);
    if (
      !hasOffset ||
      primitive._batchTableOffsetsUpdated ||
      frameState.scene3DOnly
    ) {
      return;
    }

    const index2D = primitive._batchTableOffsetAttribute2DIndex;

    const projection = frameState.mapProjection;
    const ellipsoid = projection.ellipsoid;

    const batchTable = primitive._batchTable;
    const boundingSpheres = primitive._instanceBoundingSpheres;
    const length = boundingSpheres.length;

    for (let i = 0; i < length; ++i) {
      let boundingSphere = boundingSpheres[i];
      if (!defined(boundingSphere)) {
        continue;
      }
      const offset = batchTable.getBatchedAttribute(
        i,
        primitive._batchTableAttributeIndices.offset
      );
      if (Cartesian3.equals(offset, Cartesian3.ZERO)) {
        batchTable.setBatchedAttribute(i, index2D, Cartesian3.ZERO);
        continue;
      }

      const modelMatrix = primitive.modelMatrix;
      if (defined(modelMatrix)) {
        boundingSphere = BoundingSphere.transform(
          boundingSphere,
          modelMatrix,
          scratchBoundingSphere$3
        );
      }

      let center = boundingSphere.center;
      center = ellipsoid.scaleToGeodeticSurface(center, offsetCenterScratch);
      let cartographic = ellipsoid.cartesianToCartographic(
        center,
        scratchBoundingSphereCartographic
      );
      const center2D = projection.project(
        cartographic,
        scratchBoundingSphereCenter2D
      );

      const newPoint = Cartesian3.add(offset, center, offsetScratchCartesian);
      cartographic = ellipsoid.cartesianToCartographic(newPoint, cartographic);

      const newPointProjected = projection.project(
        cartographic,
        offsetScratchCartesian
      );

      const newVector = Cartesian3.subtract(
        newPointProjected,
        center2D,
        offsetScratchCartesian
      );

      const x = newVector.x;
      newVector.x = newVector.z;
      newVector.z = newVector.y;
      newVector.y = x;

      batchTable.setBatchedAttribute(i, index2D, newVector);
    }

    primitive._batchTableOffsetsUpdated = true;
  }

  function createVertexArray$6(primitive, frameState) {
    const attributeLocations = primitive._attributeLocations;
    const geometries = primitive._geometries;
    const scene3DOnly = frameState.scene3DOnly;
    const context = frameState.context;

    const va = [];
    const length = geometries.length;
    for (let i = 0; i < length; ++i) {
      const geometry = geometries[i];

      va.push(
        VertexArray.fromGeometry({
          context: context,
          geometry: geometry,
          attributeLocations: attributeLocations,
          bufferUsage: BufferUsage$1.STATIC_DRAW,
          interleave: primitive._interleave,
        })
      );

      if (defined(primitive._createBoundingVolumeFunction)) {
        primitive._createBoundingVolumeFunction(frameState, geometry);
      } else {
        primitive._boundingSpheres.push(
          BoundingSphere.clone(geometry.boundingSphere)
        );
        primitive._boundingSphereWC.push(new BoundingSphere());

        if (!scene3DOnly) {
          const center = geometry.boundingSphereCV.center;
          const x = center.x;
          const y = center.y;
          const z = center.z;
          center.x = z;
          center.y = x;
          center.z = y;

          primitive._boundingSphereCV.push(
            BoundingSphere.clone(geometry.boundingSphereCV)
          );
          primitive._boundingSphere2D.push(new BoundingSphere());
          primitive._boundingSphereMorph.push(new BoundingSphere());
        }
      }
    }

    primitive._va = va;
    primitive._primitiveType = geometries[0].primitiveType;

    if (primitive.releaseGeometryInstances) {
      primitive.geometryInstances = undefined;
    }

    primitive._geometries = undefined;
    setReady(primitive, frameState, PrimitiveState$1.COMPLETE, undefined);
  }

  function createRenderStates$6(primitive, context, appearance, twoPasses) {
    let renderState = appearance.getRenderState();
    let rs;

    if (twoPasses) {
      rs = clone$1(renderState, false);
      rs.cull = {
        enabled: true,
        face: CullFace$1.BACK,
      };
      primitive._frontFaceRS = RenderState.fromCache(rs);

      rs.cull.face = CullFace$1.FRONT;
      primitive._backFaceRS = RenderState.fromCache(rs);
    } else {
      primitive._frontFaceRS = RenderState.fromCache(renderState);
      primitive._backFaceRS = primitive._frontFaceRS;
    }

    rs = clone$1(renderState, false);
    if (defined(primitive._depthFailAppearance)) {
      rs.depthTest.enabled = false;
    }

    if (defined(primitive._depthFailAppearance)) {
      renderState = primitive._depthFailAppearance.getRenderState();
      rs = clone$1(renderState, false);
      rs.depthTest.func = DepthFunction$1.GREATER;
      if (twoPasses) {
        rs.cull = {
          enabled: true,
          face: CullFace$1.BACK,
        };
        primitive._frontFaceDepthFailRS = RenderState.fromCache(rs);

        rs.cull.face = CullFace$1.FRONT;
        primitive._backFaceDepthFailRS = RenderState.fromCache(rs);
      } else {
        primitive._frontFaceDepthFailRS = RenderState.fromCache(rs);
        primitive._backFaceDepthFailRS = primitive._frontFaceRS;
      }
    }
  }

  function createShaderProgram$3(primitive, frameState, appearance) {
    const context = frameState.context;

    const attributeLocations = primitive._attributeLocations;

    let vs = primitive._batchTable.getVertexShaderCallback()(
      appearance.vertexShaderSource
    );
    vs = Primitive$3._appendOffsetToShader(primitive, vs);
    vs = Primitive$3._appendShowToShader(primitive, vs);
    vs = Primitive$3._appendDistanceDisplayConditionToShader(
      primitive,
      vs,
      frameState.scene3DOnly
    );
    vs = appendPickToVertexShader(vs);
    vs = Primitive$3._updateColorAttribute(primitive, vs, false);
    vs = modifyForEncodedNormals$1(primitive, vs);
    vs = Primitive$3._modifyShaderPosition(primitive, vs, frameState.scene3DOnly);
    let fs = appearance.getFragmentShaderSource();
    fs = appendPickToFragmentShader(fs);

    primitive._sp = ShaderProgram.replaceCache({
      context: context,
      shaderProgram: primitive._sp,
      vertexShaderSource: vs,
      fragmentShaderSource: fs,
      attributeLocations: attributeLocations,
    });
    validateShaderMatching(primitive._sp, attributeLocations);

    if (defined(primitive._depthFailAppearance)) {
      vs = primitive._batchTable.getVertexShaderCallback()(
        primitive._depthFailAppearance.vertexShaderSource
      );
      vs = Primitive$3._appendShowToShader(primitive, vs);
      vs = Primitive$3._appendDistanceDisplayConditionToShader(
        primitive,
        vs,
        frameState.scene3DOnly
      );
      vs = appendPickToVertexShader(vs);
      vs = Primitive$3._updateColorAttribute(primitive, vs, true);
      vs = modifyForEncodedNormals$1(primitive, vs);
      vs = Primitive$3._modifyShaderPosition(primitive, vs, frameState.scene3DOnly);
      vs = depthClampVS(vs);

      fs = primitive._depthFailAppearance.getFragmentShaderSource();
      fs = appendPickToFragmentShader(fs);
      fs = depthClampFS(fs);

      primitive._spDepthFail = ShaderProgram.replaceCache({
        context: context,
        shaderProgram: primitive._spDepthFail,
        vertexShaderSource: vs,
        fragmentShaderSource: fs,
        attributeLocations: attributeLocations,
      });
      validateShaderMatching(primitive._spDepthFail, attributeLocations);
    }
  }

  const modifiedModelViewScratch$4 = new Matrix4();
  const rtcScratch$4 = new Cartesian3();

  function getUniforms(primitive, appearance, material, frameState) {
    // Create uniform map by combining uniforms from the appearance and material if either have uniforms.
    const materialUniformMap = defined(material) ? material._uniforms : undefined;
    const appearanceUniformMap = {};
    const appearanceUniforms = appearance.uniforms;
    if (defined(appearanceUniforms)) {
      // Convert to uniform map of functions for the renderer
      for (const name in appearanceUniforms) {
        if (appearanceUniforms.hasOwnProperty(name)) {
          //>>includeStart('debug', pragmas.debug);
          if (defined(materialUniformMap) && defined(materialUniformMap[name])) {
            // Later, we could rename uniforms behind-the-scenes if needed.
            throw new DeveloperError(
              `Appearance and material have a uniform with the same name: ${name}`
            );
          }
          //>>includeEnd('debug');

          appearanceUniformMap[name] = getUniformFunction(
            appearanceUniforms,
            name
          );
        }
      }
    }
    let uniforms = combine$2(appearanceUniformMap, materialUniformMap);
    uniforms = primitive._batchTable.getUniformMapCallback()(uniforms);

    if (defined(primitive.rtcCenter)) {
      uniforms.u_modifiedModelView = function () {
        const viewMatrix = frameState.context.uniformState.view;
        Matrix4.multiply(
          viewMatrix,
          primitive._modelMatrix,
          modifiedModelViewScratch$4
        );
        Matrix4.multiplyByPoint(
          modifiedModelViewScratch$4,
          primitive.rtcCenter,
          rtcScratch$4
        );
        Matrix4.setTranslation(
          modifiedModelViewScratch$4,
          rtcScratch$4,
          modifiedModelViewScratch$4
        );
        return modifiedModelViewScratch$4;
      };
    }

    return uniforms;
  }

  function createCommands$5(
    primitive,
    appearance,
    material,
    translucent,
    twoPasses,
    colorCommands,
    pickCommands,
    frameState
  ) {
    const uniforms = getUniforms(primitive, appearance, material, frameState);

    let depthFailUniforms;
    if (defined(primitive._depthFailAppearance)) {
      depthFailUniforms = getUniforms(
        primitive,
        primitive._depthFailAppearance,
        primitive._depthFailAppearance.material,
        frameState
      );
    }

    const pass = translucent ? Pass$1.TRANSLUCENT : Pass$1.OPAQUE;

    let multiplier = twoPasses ? 2 : 1;
    multiplier *= defined(primitive._depthFailAppearance) ? 2 : 1;
    colorCommands.length = primitive._va.length * multiplier;

    const length = colorCommands.length;
    let vaIndex = 0;
    for (let i = 0; i < length; ++i) {
      let colorCommand;

      if (twoPasses) {
        colorCommand = colorCommands[i];
        if (!defined(colorCommand)) {
          colorCommand = colorCommands[i] = new DrawCommand({
            owner: primitive,
            primitiveType: primitive._primitiveType,
          });
        }
        colorCommand.vertexArray = primitive._va[vaIndex];
        colorCommand.renderState = primitive._backFaceRS;
        colorCommand.shaderProgram = primitive._sp;
        colorCommand.uniformMap = uniforms;
        colorCommand.pass = pass;

        ++i;
      }

      colorCommand = colorCommands[i];
      if (!defined(colorCommand)) {
        colorCommand = colorCommands[i] = new DrawCommand({
          owner: primitive,
          primitiveType: primitive._primitiveType,
        });
      }
      colorCommand.vertexArray = primitive._va[vaIndex];
      colorCommand.renderState = primitive._frontFaceRS;
      colorCommand.shaderProgram = primitive._sp;
      colorCommand.uniformMap = uniforms;
      colorCommand.pass = pass;

      if (defined(primitive._depthFailAppearance)) {
        if (twoPasses) {
          ++i;

          colorCommand = colorCommands[i];
          if (!defined(colorCommand)) {
            colorCommand = colorCommands[i] = new DrawCommand({
              owner: primitive,
              primitiveType: primitive._primitiveType,
            });
          }
          colorCommand.vertexArray = primitive._va[vaIndex];
          colorCommand.renderState = primitive._backFaceDepthFailRS;
          colorCommand.shaderProgram = primitive._spDepthFail;
          colorCommand.uniformMap = depthFailUniforms;
          colorCommand.pass = pass;
        }

        ++i;

        colorCommand = colorCommands[i];
        if (!defined(colorCommand)) {
          colorCommand = colorCommands[i] = new DrawCommand({
            owner: primitive,
            primitiveType: primitive._primitiveType,
          });
        }
        colorCommand.vertexArray = primitive._va[vaIndex];
        colorCommand.renderState = primitive._frontFaceDepthFailRS;
        colorCommand.shaderProgram = primitive._spDepthFail;
        colorCommand.uniformMap = depthFailUniforms;
        colorCommand.pass = pass;
      }

      ++vaIndex;
    }
  }

  Primitive$3._updateBoundingVolumes = function (
    primitive,
    frameState,
    modelMatrix,
    forceUpdate
  ) {
    let i;
    let length;
    let boundingSphere;

    if (forceUpdate || !Matrix4.equals(modelMatrix, primitive._modelMatrix)) {
      Matrix4.clone(modelMatrix, primitive._modelMatrix);
      length = primitive._boundingSpheres.length;
      for (i = 0; i < length; ++i) {
        boundingSphere = primitive._boundingSpheres[i];
        if (defined(boundingSphere)) {
          primitive._boundingSphereWC[i] = BoundingSphere.transform(
            boundingSphere,
            modelMatrix,
            primitive._boundingSphereWC[i]
          );
          if (!frameState.scene3DOnly) {
            primitive._boundingSphere2D[i] = BoundingSphere.clone(
              primitive._boundingSphereCV[i],
              primitive._boundingSphere2D[i]
            );
            primitive._boundingSphere2D[i].center.x = 0.0;
            primitive._boundingSphereMorph[i] = BoundingSphere.union(
              primitive._boundingSphereWC[i],
              primitive._boundingSphereCV[i]
            );
          }
        }
      }
    }

    // Update bounding volumes for primitives that are sized in pixels.
    // The pixel size in meters varies based on the distance from the camera.
    const pixelSize = primitive.appearance.pixelSize;
    if (defined(pixelSize)) {
      length = primitive._boundingSpheres.length;
      for (i = 0; i < length; ++i) {
        boundingSphere = primitive._boundingSpheres[i];
        const boundingSphereWC = primitive._boundingSphereWC[i];
        const pixelSizeInMeters = frameState.camera.getPixelSize(
          boundingSphere,
          frameState.context.drawingBufferWidth,
          frameState.context.drawingBufferHeight
        );
        const sizeInMeters = pixelSizeInMeters * pixelSize;
        boundingSphereWC.radius = boundingSphere.radius + sizeInMeters;
      }
    }
  };

  function updateAndQueueCommands$3(
    primitive,
    frameState,
    colorCommands,
    pickCommands,
    modelMatrix,
    cull,
    debugShowBoundingVolume,
    twoPasses
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (
      frameState.mode !== SceneMode$1.SCENE3D &&
      !Matrix4.equals(modelMatrix, Matrix4.IDENTITY)
    ) {
      throw new DeveloperError(
        "Primitive.modelMatrix is only supported in 3D mode."
      );
    }
    //>>includeEnd('debug');

    Primitive$3._updateBoundingVolumes(primitive, frameState, modelMatrix);

    let boundingSpheres;
    if (frameState.mode === SceneMode$1.SCENE3D) {
      boundingSpheres = primitive._boundingSphereWC;
    } else if (frameState.mode === SceneMode$1.COLUMBUS_VIEW) {
      boundingSpheres = primitive._boundingSphereCV;
    } else if (
      frameState.mode === SceneMode$1.SCENE2D &&
      defined(primitive._boundingSphere2D)
    ) {
      boundingSpheres = primitive._boundingSphere2D;
    } else if (defined(primitive._boundingSphereMorph)) {
      boundingSpheres = primitive._boundingSphereMorph;
    }

    const commandList = frameState.commandList;
    const passes = frameState.passes;
    if (passes.render || passes.pick) {
      const allowPicking = primitive.allowPicking;
      const castShadows = ShadowMode$1.castShadows(primitive.shadows);
      const receiveShadows = ShadowMode$1.receiveShadows(primitive.shadows);
      const colorLength = colorCommands.length;

      let factor = twoPasses ? 2 : 1;
      factor *= defined(primitive._depthFailAppearance) ? 2 : 1;

      for (let j = 0; j < colorLength; ++j) {
        const sphereIndex = Math.floor(j / factor);
        const colorCommand = colorCommands[j];
        colorCommand.modelMatrix = modelMatrix;
        colorCommand.boundingVolume = boundingSpheres[sphereIndex];
        colorCommand.cull = cull;
        colorCommand.debugShowBoundingVolume = debugShowBoundingVolume;
        colorCommand.castShadows = castShadows;
        colorCommand.receiveShadows = receiveShadows;

        if (allowPicking) {
          colorCommand.pickId = "v_pickColor";
        } else {
          colorCommand.pickId = undefined;
        }

        commandList.push(colorCommand);
      }
    }
  }

  /**
   * Called when {@link Viewer} or {@link CesiumWidget} render the scene to
   * get the draw commands needed to render this primitive.
   * <p>
   * Do not call this function directly.  This is documented just to
   * list the exceptions that may be propagated when the scene is rendered:
   * </p>
   *
   * @exception {DeveloperError} All instance geometries must have the same primitiveType.
   * @exception {DeveloperError} Appearance and material have a uniform with the same name.
   * @exception {DeveloperError} Primitive.modelMatrix is only supported in 3D mode.
   * @exception {RuntimeError} Vertex texture fetch support is required to render primitives with per-instance attributes. The maximum number of vertex texture image units must be greater than zero.
   */
  Primitive$3.prototype.update = function (frameState) {
    if (
      (!defined(this.geometryInstances) && this._va.length === 0) ||
      (defined(this.geometryInstances) &&
        Array.isArray(this.geometryInstances) &&
        this.geometryInstances.length === 0) ||
      !defined(this.appearance) ||
      (frameState.mode !== SceneMode$1.SCENE3D && frameState.scene3DOnly) ||
      (!frameState.passes.render && !frameState.passes.pick)
    ) {
      return;
    }

    if (defined(this._error)) {
      throw this._error;
    }

    //>>includeStart('debug', pragmas.debug);
    if (defined(this.rtcCenter) && !frameState.scene3DOnly) {
      throw new DeveloperError(
        "RTC rendering is only available for 3D only scenes."
      );
    }
    //>>includeEnd('debug');

    if (this._state === PrimitiveState$1.FAILED) {
      return;
    }

    const context = frameState.context;
    if (!defined(this._batchTable)) {
      createBatchTable$1(this, context);
    }
    if (this._batchTable.attributes.length > 0) {
      if (ContextLimits.maximumVertexTextureImageUnits === 0) {
        throw new RuntimeError(
          "Vertex texture fetch support is required to render primitives with per-instance attributes. The maximum number of vertex texture image units must be greater than zero."
        );
      }
      this._batchTable.update(frameState);
    }

    if (
      this._state !== PrimitiveState$1.COMPLETE &&
      this._state !== PrimitiveState$1.COMBINED
    ) {
      if (this.asynchronous) {
        loadAsynchronous(this, frameState);
      } else {
        loadSynchronous(this, frameState);
      }
    }

    if (this._state === PrimitiveState$1.COMBINED) {
      updateBatchTableBoundingSpheres(this, frameState);
      updateBatchTableOffsets(this, frameState);
      createVertexArray$6(this, frameState);
    }

    if (!this.show || this._state !== PrimitiveState$1.COMPLETE) {
      return;
    }

    if (!this._batchTableOffsetsUpdated) {
      updateBatchTableOffsets(this, frameState);
    }
    if (this._recomputeBoundingSpheres) {
      recomputeBoundingSpheres(this, frameState);
    }

    // Create or recreate render state and shader program if appearance/material changed
    const appearance = this.appearance;
    const material = appearance.material;
    let createRS = false;
    let createSP = false;

    if (this._appearance !== appearance) {
      this._appearance = appearance;
      this._material = material;
      createRS = true;
      createSP = true;
    } else if (this._material !== material) {
      this._material = material;
      createSP = true;
    }

    const depthFailAppearance = this.depthFailAppearance;
    const depthFailMaterial = defined(depthFailAppearance)
      ? depthFailAppearance.material
      : undefined;

    if (this._depthFailAppearance !== depthFailAppearance) {
      this._depthFailAppearance = depthFailAppearance;
      this._depthFailMaterial = depthFailMaterial;
      createRS = true;
      createSP = true;
    } else if (this._depthFailMaterial !== depthFailMaterial) {
      this._depthFailMaterial = depthFailMaterial;
      createSP = true;
    }

    const translucent = this._appearance.isTranslucent();
    if (this._translucent !== translucent) {
      this._translucent = translucent;
      createRS = true;
    }

    if (defined(this._material)) {
      this._material.update(context);
    }

    const twoPasses = appearance.closed && translucent;

    if (createRS) {
      const rsFunc = defaultValue(
        this._createRenderStatesFunction,
        createRenderStates$6
      );
      rsFunc(this, context, appearance, twoPasses);
    }

    if (createSP) {
      const spFunc = defaultValue(
        this._createShaderProgramFunction,
        createShaderProgram$3
      );
      spFunc(this, frameState, appearance);
    }

    if (createRS || createSP) {
      const commandFunc = defaultValue(
        this._createCommandsFunction,
        createCommands$5
      );
      commandFunc(
        this,
        appearance,
        material,
        translucent,
        twoPasses,
        this._colorCommands,
        this._pickCommands,
        frameState
      );
    }

    const updateAndQueueCommandsFunc = defaultValue(
      this._updateAndQueueCommandsFunction,
      updateAndQueueCommands$3
    );
    updateAndQueueCommandsFunc(
      this,
      frameState,
      this._colorCommands,
      this._pickCommands,
      this.modelMatrix,
      this.cull,
      this.debugShowBoundingVolume,
      twoPasses
    );
  };

  const offsetBoundingSphereScratch1 = new BoundingSphere();
  const offsetBoundingSphereScratch2 = new BoundingSphere();
  function transformBoundingSphere(boundingSphere, offset, offsetAttribute) {
    if (offsetAttribute === GeometryOffsetAttribute$1.TOP) {
      const origBS = BoundingSphere.clone(
        boundingSphere,
        offsetBoundingSphereScratch1
      );
      const offsetBS = BoundingSphere.clone(
        boundingSphere,
        offsetBoundingSphereScratch2
      );
      offsetBS.center = Cartesian3.add(offsetBS.center, offset, offsetBS.center);
      boundingSphere = BoundingSphere.union(origBS, offsetBS, boundingSphere);
    } else if (offsetAttribute === GeometryOffsetAttribute$1.ALL) {
      boundingSphere.center = Cartesian3.add(
        boundingSphere.center,
        offset,
        boundingSphere.center
      );
    }

    return boundingSphere;
  }

  function createGetFunction(batchTable, instanceIndex, attributeIndex) {
    return function () {
      const attributeValue = batchTable.getBatchedAttribute(
        instanceIndex,
        attributeIndex
      );
      const attribute = batchTable.attributes[attributeIndex];
      const componentsPerAttribute = attribute.componentsPerAttribute;
      const value = ComponentDatatype$1.createTypedArray(
        attribute.componentDatatype,
        componentsPerAttribute
      );
      if (defined(attributeValue.constructor.pack)) {
        attributeValue.constructor.pack(attributeValue, value, 0);
      } else {
        value[0] = attributeValue;
      }
      return value;
    };
  }

  function createSetFunction(
    batchTable,
    instanceIndex,
    attributeIndex,
    primitive,
    name
  ) {
    return function (value) {
      //>>includeStart('debug', pragmas.debug);
      if (
        !defined(value) ||
        !defined(value.length) ||
        value.length < 1 ||
        value.length > 4
      ) {
        throw new DeveloperError(
          "value must be and array with length between 1 and 4."
        );
      }
      //>>includeEnd('debug');
      const attributeValue = getAttributeValue(value);
      batchTable.setBatchedAttribute(
        instanceIndex,
        attributeIndex,
        attributeValue
      );
      if (name === "offset") {
        primitive._recomputeBoundingSpheres = true;
        primitive._batchTableOffsetsUpdated = false;
      }
    };
  }

  const offsetScratch$a = new Cartesian3();

  function createBoundingSphereProperties(primitive, properties, index) {
    properties.boundingSphere = {
      get: function () {
        let boundingSphere = primitive._instanceBoundingSpheres[index];
        if (defined(boundingSphere)) {
          boundingSphere = boundingSphere.clone();
          const modelMatrix = primitive.modelMatrix;
          const offset = properties.offset;
          if (defined(offset)) {
            transformBoundingSphere(
              boundingSphere,
              Cartesian3.fromArray(offset.get(), 0, offsetScratch$a),
              primitive._offsetInstanceExtend[index]
            );
          }
          if (defined(modelMatrix)) {
            boundingSphere = BoundingSphere.transform(
              boundingSphere,
              modelMatrix
            );
          }
        }

        return boundingSphere;
      },
    };
    properties.boundingSphereCV = {
      get: function () {
        return primitive._instanceBoundingSpheresCV[index];
      },
    };
  }

  function createPickIdProperty(primitive, properties, index) {
    properties.pickId = {
      get: function () {
        return primitive._pickIds[index];
      },
    };
  }

  /**
   * Returns the modifiable per-instance attributes for a {@link GeometryInstance}.
   *
   * @param {*} id The id of the {@link GeometryInstance}.
   * @returns {Object} The typed array in the attribute's format or undefined if the is no instance with id.
   *
   * @exception {DeveloperError} must call update before calling getGeometryInstanceAttributes.
   *
   * @example
   * const attributes = primitive.getGeometryInstanceAttributes('an id');
   * attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.AQUA);
   * attributes.show = Cesium.ShowGeometryInstanceAttribute.toValue(true);
   * attributes.distanceDisplayCondition = Cesium.DistanceDisplayConditionGeometryInstanceAttribute.toValue(100.0, 10000.0);
   * attributes.offset = Cesium.OffsetGeometryInstanceAttribute.toValue(Cartesian3.IDENTITY);
   */
  Primitive$3.prototype.getGeometryInstanceAttributes = function (id) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(id)) {
      throw new DeveloperError("id is required");
    }
    if (!defined(this._batchTable)) {
      throw new DeveloperError(
        "must call update before calling getGeometryInstanceAttributes"
      );
    }
    //>>includeEnd('debug');

    let index = -1;
    const lastIndex = this._lastPerInstanceAttributeIndex;
    const ids = this._instanceIds;
    const length = ids.length;
    for (let i = 0; i < length; ++i) {
      const curIndex = (lastIndex + i) % length;
      if (id === ids[curIndex]) {
        index = curIndex;
        break;
      }
    }

    if (index === -1) {
      return undefined;
    }

    let attributes = this._perInstanceAttributeCache[index];
    if (defined(attributes)) {
      return attributes;
    }

    const batchTable = this._batchTable;
    const perInstanceAttributeIndices = this._batchTableAttributeIndices;
    attributes = {};
    const properties = {};

    for (const name in perInstanceAttributeIndices) {
      if (perInstanceAttributeIndices.hasOwnProperty(name)) {
        const attributeIndex = perInstanceAttributeIndices[name];
        properties[name] = {
          get: createGetFunction(batchTable, index, attributeIndex),
          set: createSetFunction(batchTable, index, attributeIndex, this, name),
        };
      }
    }

    createBoundingSphereProperties(this, properties, index);
    createPickIdProperty(this, properties, index);
    Object.defineProperties(attributes, properties);

    this._lastPerInstanceAttributeIndex = index;
    this._perInstanceAttributeCache[index] = attributes;
    return attributes;
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <p>
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   * </p>
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see Primitive#destroy
   */
  Primitive$3.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <p>
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   * </p>
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * e = e && e.destroy();
   *
   * @see Primitive#isDestroyed
   */
  Primitive$3.prototype.destroy = function () {
    let length;
    let i;

    this._sp = this._sp && this._sp.destroy();
    this._spDepthFail = this._spDepthFail && this._spDepthFail.destroy();

    const va = this._va;
    length = va.length;
    for (i = 0; i < length; ++i) {
      va[i].destroy();
    }
    this._va = undefined;

    const pickIds = this._pickIds;
    length = pickIds.length;
    for (i = 0; i < length; ++i) {
      pickIds[i].destroy();
    }
    this._pickIds = undefined;

    this._batchTable = this._batchTable && this._batchTable.destroy();

    //These objects may be fairly large and reference other large objects (like Entities)
    //We explicitly set them to undefined here so that the memory can be freed
    //even if a reference to the destroyed Primitive has been kept around.
    this._instanceIds = undefined;
    this._perInstanceAttributeCache = undefined;
    this._attributeLocations = undefined;

    return destroyObject(this);
  };

  function setReady(primitive, frameState, state, error) {
    primitive._error = error;
    primitive._state = state;
    frameState.afterRender.push(function () {
      primitive._ready =
        primitive._state === PrimitiveState$1.COMPLETE ||
        primitive._state === PrimitiveState$1.FAILED;
      if (!defined(error)) {
        primitive._readyPromise.resolve(primitive);
      } else {
        primitive._readyPromise.reject(error);
      }
    });
  }

  //This file is automatically rebuilt by the Cesium build process.
  var ShadowVolumeAppearanceFS = "#ifdef GL_EXT_frag_depth\n\
#extension GL_EXT_frag_depth : enable\n\
#endif\n\
#ifdef TEXTURE_COORDINATES\n\
#ifdef SPHERICAL\n\
varying vec4 v_sphericalExtents;\n\
#else // SPHERICAL\n\
varying vec2 v_inversePlaneExtents;\n\
varying vec4 v_westPlane;\n\
varying vec4 v_southPlane;\n\
#endif // SPHERICAL\n\
varying vec3 v_uvMinAndSphericalLongitudeRotation;\n\
varying vec3 v_uMaxAndInverseDistance;\n\
varying vec3 v_vMaxAndInverseDistance;\n\
#endif // TEXTURE_COORDINATES\n\
#ifdef PER_INSTANCE_COLOR\n\
varying vec4 v_color;\n\
#endif\n\
#ifdef NORMAL_EC\n\
vec3 getEyeCoordinate3FromWindowCoordinate(vec2 fragCoord, float logDepthOrDepth) {\n\
vec4 eyeCoordinate = czm_windowToEyeCoordinates(fragCoord, logDepthOrDepth);\n\
return eyeCoordinate.xyz / eyeCoordinate.w;\n\
}\n\
vec3 vectorFromOffset(vec4 eyeCoordinate, vec2 positiveOffset) {\n\
vec2 glFragCoordXY = gl_FragCoord.xy;\n\
float upOrRightLogDepth = czm_unpackDepth(texture2D(czm_globeDepthTexture, (glFragCoordXY + positiveOffset) / czm_viewport.zw));\n\
float downOrLeftLogDepth = czm_unpackDepth(texture2D(czm_globeDepthTexture, (glFragCoordXY - positiveOffset) / czm_viewport.zw));\n\
bvec2 upOrRightInBounds = lessThan(glFragCoordXY + positiveOffset, czm_viewport.zw);\n\
float useUpOrRight = float(upOrRightLogDepth > 0.0 && upOrRightInBounds.x && upOrRightInBounds.y);\n\
float useDownOrLeft = float(useUpOrRight == 0.0);\n\
vec3 upOrRightEC = getEyeCoordinate3FromWindowCoordinate(glFragCoordXY + positiveOffset, upOrRightLogDepth);\n\
vec3 downOrLeftEC = getEyeCoordinate3FromWindowCoordinate(glFragCoordXY - positiveOffset, downOrLeftLogDepth);\n\
return (upOrRightEC - (eyeCoordinate.xyz / eyeCoordinate.w)) * useUpOrRight + ((eyeCoordinate.xyz / eyeCoordinate.w) - downOrLeftEC) * useDownOrLeft;\n\
}\n\
#endif // NORMAL_EC\n\
void main(void)\n\
{\n\
#ifdef REQUIRES_EC\n\
float logDepthOrDepth = czm_unpackDepth(texture2D(czm_globeDepthTexture, gl_FragCoord.xy / czm_viewport.zw));\n\
vec4 eyeCoordinate = czm_windowToEyeCoordinates(gl_FragCoord.xy, logDepthOrDepth);\n\
#endif\n\
#ifdef REQUIRES_WC\n\
vec4 worldCoordinate4 = czm_inverseView * eyeCoordinate;\n\
vec3 worldCoordinate = worldCoordinate4.xyz / worldCoordinate4.w;\n\
#endif\n\
#ifdef TEXTURE_COORDINATES\n\
vec2 uv;\n\
#ifdef SPHERICAL\n\
vec2 sphericalLatLong = czm_approximateSphericalCoordinates(worldCoordinate);\n\
sphericalLatLong.y += v_uvMinAndSphericalLongitudeRotation.z;\n\
sphericalLatLong.y = czm_branchFreeTernary(sphericalLatLong.y < czm_pi, sphericalLatLong.y, sphericalLatLong.y - czm_twoPi);\n\
uv.x = (sphericalLatLong.y - v_sphericalExtents.y) * v_sphericalExtents.w;\n\
uv.y = (sphericalLatLong.x - v_sphericalExtents.x) * v_sphericalExtents.z;\n\
#else // SPHERICAL\n\
uv.x = czm_planeDistance(v_westPlane, eyeCoordinate.xyz / eyeCoordinate.w) * v_inversePlaneExtents.x;\n\
uv.y = czm_planeDistance(v_southPlane, eyeCoordinate.xyz / eyeCoordinate.w) * v_inversePlaneExtents.y;\n\
#endif // SPHERICAL\n\
#endif // TEXTURE_COORDINATES\n\
#ifdef PICK\n\
#ifdef CULL_FRAGMENTS\n\
if (0.0 <= uv.x && uv.x <= 1.0 && 0.0 <= uv.y && uv.y <= 1.0 || logDepthOrDepth != 0.0) {\n\
gl_FragColor.a = 1.0;\n\
czm_writeDepthClamp();\n\
}\n\
#else // CULL_FRAGMENTS\n\
gl_FragColor.a = 1.0;\n\
#endif // CULL_FRAGMENTS\n\
#else // PICK\n\
#ifdef CULL_FRAGMENTS\n\
if (uv.x <= 0.0 || 1.0 <= uv.x || uv.y <= 0.0 || 1.0 <= uv.y || logDepthOrDepth == 0.0) {\n\
discard;\n\
}\n\
#endif\n\
#ifdef NORMAL_EC\n\
vec3 downUp = vectorFromOffset(eyeCoordinate, vec2(0.0, 1.0));\n\
vec3 leftRight = vectorFromOffset(eyeCoordinate, vec2(1.0, 0.0));\n\
vec3 normalEC = normalize(cross(leftRight, downUp));\n\
#endif\n\
#ifdef PER_INSTANCE_COLOR\n\
vec4 color = czm_gammaCorrect(v_color);\n\
#ifdef FLAT\n\
gl_FragColor = color;\n\
#else // FLAT\n\
czm_materialInput materialInput;\n\
materialInput.normalEC = normalEC;\n\
materialInput.positionToEyeEC = -eyeCoordinate.xyz;\n\
czm_material material = czm_getDefaultMaterial(materialInput);\n\
material.diffuse = color.rgb;\n\
material.alpha = color.a;\n\
gl_FragColor = czm_phong(normalize(-eyeCoordinate.xyz), material, czm_lightDirectionEC);\n\
#endif // FLAT\n\
gl_FragColor.rgb *= gl_FragColor.a;\n\
#else // PER_INSTANCE_COLOR\n\
czm_materialInput materialInput;\n\
#ifdef USES_NORMAL_EC\n\
materialInput.normalEC = normalEC;\n\
#endif\n\
#ifdef USES_POSITION_TO_EYE_EC\n\
materialInput.positionToEyeEC = -eyeCoordinate.xyz;\n\
#endif\n\
#ifdef USES_TANGENT_TO_EYE\n\
materialInput.tangentToEyeMatrix = czm_eastNorthUpToEyeCoordinates(worldCoordinate, normalEC);\n\
#endif\n\
#ifdef USES_ST\n\
materialInput.st.x = czm_lineDistance(v_uvMinAndSphericalLongitudeRotation.xy, v_uMaxAndInverseDistance.xy, uv) * v_uMaxAndInverseDistance.z;\n\
materialInput.st.y = czm_lineDistance(v_uvMinAndSphericalLongitudeRotation.xy, v_vMaxAndInverseDistance.xy, uv) * v_vMaxAndInverseDistance.z;\n\
#endif\n\
czm_material material = czm_getMaterial(materialInput);\n\
#ifdef FLAT\n\
gl_FragColor = vec4(material.diffuse + material.emission, material.alpha);\n\
#else // FLAT\n\
gl_FragColor = czm_phong(normalize(-eyeCoordinate.xyz), material, czm_lightDirectionEC);\n\
#endif // FLAT\n\
gl_FragColor.rgb *= gl_FragColor.a;\n\
#endif // PER_INSTANCE_COLOR\n\
czm_writeDepthClamp();\n\
#endif // PICK\n\
}\n\
";

  /**
   * Creates shaders for a ClassificationPrimitive to use a given Appearance, as well as for picking.
   *
   * @param {Boolean} extentsCulling Discard fragments outside the instance's texture coordinate extents.
   * @param {Boolean} planarExtents If true, texture coordinates will be computed using planes instead of spherical coordinates.
   * @param {Appearance} appearance An Appearance to be used with a ClassificationPrimitive via GroundPrimitive.
   * @private
   */
  function ShadowVolumeAppearance(extentsCulling, planarExtents, appearance) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.bool("extentsCulling", extentsCulling);
    Check.typeOf.bool("planarExtents", planarExtents);
    Check.typeOf.object("appearance", appearance);
    //>>includeEnd('debug');

    this._projectionExtentDefines = {
      eastMostYhighDefine: "",
      eastMostYlowDefine: "",
      westMostYhighDefine: "",
      westMostYlowDefine: "",
    };

    // Compute shader dependencies
    const colorShaderDependencies = new ShaderDependencies();
    colorShaderDependencies.requiresTextureCoordinates = extentsCulling;
    colorShaderDependencies.requiresEC = !appearance.flat;

    const pickShaderDependencies = new ShaderDependencies();
    pickShaderDependencies.requiresTextureCoordinates = extentsCulling;

    if (appearance instanceof PerInstanceColorAppearance) {
      // PerInstanceColorAppearance doesn't have material.shaderSource, instead it has its own vertex and fragment shaders
      colorShaderDependencies.requiresNormalEC = !appearance.flat;
    } else {
      // Scan material source for what hookups are needed. Assume czm_materialInput materialInput.
      const materialShaderSource = `${appearance.material.shaderSource}\n${appearance.fragmentShaderSource}`;

      colorShaderDependencies.normalEC =
        materialShaderSource.indexOf("materialInput.normalEC") !== -1 ||
        materialShaderSource.indexOf("czm_getDefaultMaterial") !== -1;
      colorShaderDependencies.positionToEyeEC =
        materialShaderSource.indexOf("materialInput.positionToEyeEC") !== -1;
      colorShaderDependencies.tangentToEyeMatrix =
        materialShaderSource.indexOf("materialInput.tangentToEyeMatrix") !== -1;
      colorShaderDependencies.st =
        materialShaderSource.indexOf("materialInput.st") !== -1;
    }

    this._colorShaderDependencies = colorShaderDependencies;
    this._pickShaderDependencies = pickShaderDependencies;
    this._appearance = appearance;
    this._extentsCulling = extentsCulling;
    this._planarExtents = planarExtents;
  }

  /**
   * Create the fragment shader for a ClassificationPrimitive's color pass when rendering for color.
   *
   * @param {Boolean} columbusView2D Whether the shader will be used for Columbus View or 2D.
   * @returns {ShaderSource} Shader source for the fragment shader.
   */
  ShadowVolumeAppearance.prototype.createFragmentShader = function (
    columbusView2D
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.bool("columbusView2D", columbusView2D);
    //>>includeEnd('debug');

    const appearance = this._appearance;
    const dependencies = this._colorShaderDependencies;

    const defines = [];
    if (!columbusView2D && !this._planarExtents) {
      defines.push("SPHERICAL");
    }
    if (dependencies.requiresEC) {
      defines.push("REQUIRES_EC");
    }
    if (dependencies.requiresWC) {
      defines.push("REQUIRES_WC");
    }
    if (dependencies.requiresTextureCoordinates) {
      defines.push("TEXTURE_COORDINATES");
    }
    if (this._extentsCulling) {
      defines.push("CULL_FRAGMENTS");
    }
    if (dependencies.requiresNormalEC) {
      defines.push("NORMAL_EC");
    }
    if (appearance instanceof PerInstanceColorAppearance) {
      defines.push("PER_INSTANCE_COLOR");
    }

    // Material inputs. Use of parameters in the material is different
    // from requirement of the parameters in the overall shader, for example,
    // texture coordinates may be used for fragment culling but not for the material itself.
    if (dependencies.normalEC) {
      defines.push("USES_NORMAL_EC");
    }
    if (dependencies.positionToEyeEC) {
      defines.push("USES_POSITION_TO_EYE_EC");
    }
    if (dependencies.tangentToEyeMatrix) {
      defines.push("USES_TANGENT_TO_EYE");
    }
    if (dependencies.st) {
      defines.push("USES_ST");
    }

    if (appearance.flat) {
      defines.push("FLAT");
    }

    let materialSource = "";
    if (!(appearance instanceof PerInstanceColorAppearance)) {
      materialSource = appearance.material.shaderSource;
    }

    return new ShaderSource({
      defines: defines,
      sources: [materialSource, ShadowVolumeAppearanceFS],
    });
  };

  ShadowVolumeAppearance.prototype.createPickFragmentShader = function (
    columbusView2D
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.bool("columbusView2D", columbusView2D);
    //>>includeEnd('debug');

    const dependencies = this._pickShaderDependencies;

    const defines = ["PICK"];
    if (!columbusView2D && !this._planarExtents) {
      defines.push("SPHERICAL");
    }
    if (dependencies.requiresEC) {
      defines.push("REQUIRES_EC");
    }
    if (dependencies.requiresWC) {
      defines.push("REQUIRES_WC");
    }
    if (dependencies.requiresTextureCoordinates) {
      defines.push("TEXTURE_COORDINATES");
    }
    if (this._extentsCulling) {
      defines.push("CULL_FRAGMENTS");
    }
    return new ShaderSource({
      defines: defines,
      sources: [ShadowVolumeAppearanceFS],
      pickColorQualifier: "varying",
    });
  };

  /**
   * Create the vertex shader for a ClassificationPrimitive's color pass on the final of 3 shadow volume passes
   *
   * @param {String[]} defines External defines to pass to the vertex shader.
   * @param {String} vertexShaderSource ShadowVolumeAppearanceVS with any required modifications for computing position.
   * @param {Boolean} columbusView2D Whether the shader will be used for Columbus View or 2D.
   * @param {MapProjection} mapProjection Current scene's map projection.
   * @returns {String} Shader source for the vertex shader.
   */
  ShadowVolumeAppearance.prototype.createVertexShader = function (
    defines,
    vertexShaderSource,
    columbusView2D,
    mapProjection
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("defines", defines);
    Check.typeOf.string("vertexShaderSource", vertexShaderSource);
    Check.typeOf.bool("columbusView2D", columbusView2D);
    Check.defined("mapProjection", mapProjection);
    //>>includeEnd('debug');
    return createShadowVolumeAppearanceVS(
      this._colorShaderDependencies,
      this._planarExtents,
      columbusView2D,
      defines,
      vertexShaderSource,
      this._appearance,
      mapProjection,
      this._projectionExtentDefines
    );
  };

  /**
   * Create the vertex shader for a ClassificationPrimitive's pick pass on the final of 3 shadow volume passes
   *
   * @param {String[]} defines External defines to pass to the vertex shader.
   * @param {String} vertexShaderSource ShadowVolumeAppearanceVS with any required modifications for computing position and picking.
   * @param {Boolean} columbusView2D Whether the shader will be used for Columbus View or 2D.
   * @param {MapProjection} mapProjection Current scene's map projection.
   * @returns {String} Shader source for the vertex shader.
   */
  ShadowVolumeAppearance.prototype.createPickVertexShader = function (
    defines,
    vertexShaderSource,
    columbusView2D,
    mapProjection
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("defines", defines);
    Check.typeOf.string("vertexShaderSource", vertexShaderSource);
    Check.typeOf.bool("columbusView2D", columbusView2D);
    Check.defined("mapProjection", mapProjection);
    //>>includeEnd('debug');
    return createShadowVolumeAppearanceVS(
      this._pickShaderDependencies,
      this._planarExtents,
      columbusView2D,
      defines,
      vertexShaderSource,
      undefined,
      mapProjection,
      this._projectionExtentDefines
    );
  };

  const longitudeExtentsCartesianScratch = new Cartesian3();
  const longitudeExtentsCartographicScratch = new Cartographic();
  const longitudeExtentsEncodeScratch = {
    high: 0.0,
    low: 0.0,
  };
  function createShadowVolumeAppearanceVS(
    shaderDependencies,
    planarExtents,
    columbusView2D,
    defines,
    vertexShaderSource,
    appearance,
    mapProjection,
    projectionExtentDefines
  ) {
    const allDefines = defines.slice();

    if (projectionExtentDefines.eastMostYhighDefine === "") {
      const eastMostCartographic = longitudeExtentsCartographicScratch;
      eastMostCartographic.longitude = CesiumMath.PI;
      eastMostCartographic.latitude = 0.0;
      eastMostCartographic.height = 0.0;
      const eastMostCartesian = mapProjection.project(
        eastMostCartographic,
        longitudeExtentsCartesianScratch
      );
      let encoded = EncodedCartesian3.encode(
        eastMostCartesian.x,
        longitudeExtentsEncodeScratch
      );
      projectionExtentDefines.eastMostYhighDefine = `EAST_MOST_X_HIGH ${encoded.high.toFixed(
      `${encoded.high}`.length + 1
    )}`;
      projectionExtentDefines.eastMostYlowDefine = `EAST_MOST_X_LOW ${encoded.low.toFixed(
      `${encoded.low}`.length + 1
    )}`;

      const westMostCartographic = longitudeExtentsCartographicScratch;
      westMostCartographic.longitude = -CesiumMath.PI;
      westMostCartographic.latitude = 0.0;
      westMostCartographic.height = 0.0;
      const westMostCartesian = mapProjection.project(
        westMostCartographic,
        longitudeExtentsCartesianScratch
      );
      encoded = EncodedCartesian3.encode(
        westMostCartesian.x,
        longitudeExtentsEncodeScratch
      );
      projectionExtentDefines.westMostYhighDefine = `WEST_MOST_X_HIGH ${encoded.high.toFixed(
      `${encoded.high}`.length + 1
    )}`;
      projectionExtentDefines.westMostYlowDefine = `WEST_MOST_X_LOW ${encoded.low.toFixed(
      `${encoded.low}`.length + 1
    )}`;
    }

    if (columbusView2D) {
      allDefines.push(projectionExtentDefines.eastMostYhighDefine);
      allDefines.push(projectionExtentDefines.eastMostYlowDefine);
      allDefines.push(projectionExtentDefines.westMostYhighDefine);
      allDefines.push(projectionExtentDefines.westMostYlowDefine);
    }

    if (defined(appearance) && appearance instanceof PerInstanceColorAppearance) {
      allDefines.push("PER_INSTANCE_COLOR");
    }
    if (shaderDependencies.requiresTextureCoordinates) {
      allDefines.push("TEXTURE_COORDINATES");
      if (!(planarExtents || columbusView2D)) {
        allDefines.push("SPHERICAL");
      }
      if (columbusView2D) {
        allDefines.push("COLUMBUS_VIEW_2D");
      }
    }

    return new ShaderSource({
      defines: allDefines,
      sources: [vertexShaderSource],
    });
  }

  /**
   * Tracks shader dependencies.
   * @private
   */
  function ShaderDependencies() {
    this._requiresEC = false;
    this._requiresWC = false; // depends on eye coordinates, needed for material and for phong
    this._requiresNormalEC = false; // depends on eye coordinates, needed for material
    this._requiresTextureCoordinates = false; // depends on world coordinates, needed for material and for culling

    this._usesNormalEC = false;
    this._usesPositionToEyeEC = false;
    this._usesTangentToEyeMat = false;
    this._usesSt = false;
  }

  Object.defineProperties(ShaderDependencies.prototype, {
    // Set when assessing final shading (flat vs. phong) and culling using computed texture coordinates
    requiresEC: {
      get: function () {
        return this._requiresEC;
      },
      set: function (value) {
        this._requiresEC = value || this._requiresEC;
      },
    },
    requiresWC: {
      get: function () {
        return this._requiresWC;
      },
      set: function (value) {
        this._requiresWC = value || this._requiresWC;
        this.requiresEC = this._requiresWC;
      },
    },
    requiresNormalEC: {
      get: function () {
        return this._requiresNormalEC;
      },
      set: function (value) {
        this._requiresNormalEC = value || this._requiresNormalEC;
        this.requiresEC = this._requiresNormalEC;
      },
    },
    requiresTextureCoordinates: {
      get: function () {
        return this._requiresTextureCoordinates;
      },
      set: function (value) {
        this._requiresTextureCoordinates =
          value || this._requiresTextureCoordinates;
        this.requiresWC = this._requiresTextureCoordinates;
      },
    },
    // Get/Set when assessing material hookups
    normalEC: {
      set: function (value) {
        this.requiresNormalEC = value;
        this._usesNormalEC = value;
      },
      get: function () {
        return this._usesNormalEC;
      },
    },
    tangentToEyeMatrix: {
      set: function (value) {
        this.requiresWC = value;
        this.requiresNormalEC = value;
        this._usesTangentToEyeMat = value;
      },
      get: function () {
        return this._usesTangentToEyeMat;
      },
    },
    positionToEyeEC: {
      set: function (value) {
        this.requiresEC = value;
        this._usesPositionToEyeEC = value;
      },
      get: function () {
        return this._usesPositionToEyeEC;
      },
    },
    st: {
      set: function (value) {
        this.requiresTextureCoordinates = value;
        this._usesSt = value;
      },
      get: function () {
        return this._usesSt;
      },
    },
  });

  function pointLineDistance(point1, point2, point) {
    return (
      Math.abs(
        (point2.y - point1.y) * point.x -
          (point2.x - point1.x) * point.y +
          point2.x * point1.y -
          point2.y * point1.x
      ) / Cartesian2.distance(point2, point1)
    );
  }

  const points2DScratch = [
    new Cartesian2(),
    new Cartesian2(),
    new Cartesian2(),
    new Cartesian2(),
  ];

  // textureCoordinateRotationPoints form 2 lines in the computed UV space that remap to desired texture coordinates.
  // This allows simulation of baked texture coordinates for EllipseGeometry, RectangleGeometry, and PolygonGeometry.
  function addTextureCoordinateRotationAttributes(
    attributes,
    textureCoordinateRotationPoints
  ) {
    const points2D = points2DScratch;

    const minXYCorner = Cartesian2.unpack(
      textureCoordinateRotationPoints,
      0,
      points2D[0]
    );
    const maxYCorner = Cartesian2.unpack(
      textureCoordinateRotationPoints,
      2,
      points2D[1]
    );
    const maxXCorner = Cartesian2.unpack(
      textureCoordinateRotationPoints,
      4,
      points2D[2]
    );

    attributes.uMaxVmax = new GeometryInstanceAttribute({
      componentDatatype: ComponentDatatype$1.FLOAT,
      componentsPerAttribute: 4,
      normalize: false,
      value: [maxYCorner.x, maxYCorner.y, maxXCorner.x, maxXCorner.y],
    });

    const inverseExtentX =
      1.0 / pointLineDistance(minXYCorner, maxYCorner, maxXCorner);
    const inverseExtentY =
      1.0 / pointLineDistance(minXYCorner, maxXCorner, maxYCorner);

    attributes.uvMinAndExtents = new GeometryInstanceAttribute({
      componentDatatype: ComponentDatatype$1.FLOAT,
      componentsPerAttribute: 4,
      normalize: false,
      value: [minXYCorner.x, minXYCorner.y, inverseExtentX, inverseExtentY],
    });
  }

  const cartographicScratch$3 = new Cartographic();
  const cornerScratch = new Cartesian3();
  const northWestScratch = new Cartesian3();
  const southEastScratch = new Cartesian3();
  const highLowScratch = { high: 0.0, low: 0.0 };
  function add2DTextureCoordinateAttributes(rectangle, projection, attributes) {
    // Compute corner positions in double precision
    const carto = cartographicScratch$3;
    carto.height = 0.0;

    carto.longitude = rectangle.west;
    carto.latitude = rectangle.south;

    const southWestCorner = projection.project(carto, cornerScratch);

    carto.latitude = rectangle.north;
    const northWest = projection.project(carto, northWestScratch);

    carto.longitude = rectangle.east;
    carto.latitude = rectangle.south;
    const southEast = projection.project(carto, southEastScratch);

    // Since these positions are all in the 2D plane, there's a lot of zeros
    // and a lot of repetition. So we only need to encode 4 values.
    // Encode:
    // x: x value for southWestCorner
    // y: y value for southWestCorner
    // z: y value for northWest
    // w: x value for southEast

    const valuesHigh = [0, 0, 0, 0];
    const valuesLow = [0, 0, 0, 0];
    let encoded = EncodedCartesian3.encode(southWestCorner.x, highLowScratch);
    valuesHigh[0] = encoded.high;
    valuesLow[0] = encoded.low;

    encoded = EncodedCartesian3.encode(southWestCorner.y, highLowScratch);
    valuesHigh[1] = encoded.high;
    valuesLow[1] = encoded.low;

    encoded = EncodedCartesian3.encode(northWest.y, highLowScratch);
    valuesHigh[2] = encoded.high;
    valuesLow[2] = encoded.low;

    encoded = EncodedCartesian3.encode(southEast.x, highLowScratch);
    valuesHigh[3] = encoded.high;
    valuesLow[3] = encoded.low;

    attributes.planes2D_HIGH = new GeometryInstanceAttribute({
      componentDatatype: ComponentDatatype$1.FLOAT,
      componentsPerAttribute: 4,
      normalize: false,
      value: valuesHigh,
    });

    attributes.planes2D_LOW = new GeometryInstanceAttribute({
      componentDatatype: ComponentDatatype$1.FLOAT,
      componentsPerAttribute: 4,
      normalize: false,
      value: valuesLow,
    });
  }

  const enuMatrixScratch = new Matrix4();
  const inverseEnuScratch = new Matrix4();
  const rectanglePointCartesianScratch = new Cartesian3();
  const rectangleCenterScratch$1 = new Cartographic();
  const pointsCartographicScratch = [
    new Cartographic(),
    new Cartographic(),
    new Cartographic(),
    new Cartographic(),
    new Cartographic(),
    new Cartographic(),
    new Cartographic(),
    new Cartographic(),
  ];
  /**
   * When computing planes to bound the rectangle,
   * need to factor in "bulge" and other distortion.
   * Flatten the ellipsoid-centered corners and edge-centers of the rectangle
   * into the plane of the local ENU system, compute bounds in 2D, and
   * project back to ellipsoid-centered.
   *
   * @private
   */
  function computeRectangleBounds(
    rectangle,
    ellipsoid,
    height,
    southWestCornerResult,
    eastVectorResult,
    northVectorResult
  ) {
    // Compute center of rectangle
    const centerCartographic = Rectangle.center(
      rectangle,
      rectangleCenterScratch$1
    );
    centerCartographic.height = height;
    const centerCartesian = Cartographic.toCartesian(
      centerCartographic,
      ellipsoid,
      rectanglePointCartesianScratch
    );
    const enuMatrix = Transforms.eastNorthUpToFixedFrame(
      centerCartesian,
      ellipsoid,
      enuMatrixScratch
    );
    const inverseEnu = Matrix4.inverse(enuMatrix, inverseEnuScratch);

    const west = rectangle.west;
    const east = rectangle.east;
    const north = rectangle.north;
    const south = rectangle.south;

    const cartographics = pointsCartographicScratch;
    cartographics[0].latitude = south;
    cartographics[0].longitude = west;
    cartographics[1].latitude = north;
    cartographics[1].longitude = west;
    cartographics[2].latitude = north;
    cartographics[2].longitude = east;
    cartographics[3].latitude = south;
    cartographics[3].longitude = east;

    const longitudeCenter = (west + east) * 0.5;
    const latitudeCenter = (north + south) * 0.5;

    cartographics[4].latitude = south;
    cartographics[4].longitude = longitudeCenter;
    cartographics[5].latitude = north;
    cartographics[5].longitude = longitudeCenter;
    cartographics[6].latitude = latitudeCenter;
    cartographics[6].longitude = west;
    cartographics[7].latitude = latitudeCenter;
    cartographics[7].longitude = east;

    let minX = Number.POSITIVE_INFINITY;
    let maxX = Number.NEGATIVE_INFINITY;
    let minY = Number.POSITIVE_INFINITY;
    let maxY = Number.NEGATIVE_INFINITY;
    for (let i = 0; i < 8; i++) {
      cartographics[i].height = height;
      const pointCartesian = Cartographic.toCartesian(
        cartographics[i],
        ellipsoid,
        rectanglePointCartesianScratch
      );
      Matrix4.multiplyByPoint(inverseEnu, pointCartesian, pointCartesian);
      pointCartesian.z = 0.0; // flatten into XY plane of ENU coordinate system
      minX = Math.min(minX, pointCartesian.x);
      maxX = Math.max(maxX, pointCartesian.x);
      minY = Math.min(minY, pointCartesian.y);
      maxY = Math.max(maxY, pointCartesian.y);
    }

    const southWestCorner = southWestCornerResult;
    southWestCorner.x = minX;
    southWestCorner.y = minY;
    southWestCorner.z = 0.0;
    Matrix4.multiplyByPoint(enuMatrix, southWestCorner, southWestCorner);

    const southEastCorner = eastVectorResult;
    southEastCorner.x = maxX;
    southEastCorner.y = minY;
    southEastCorner.z = 0.0;
    Matrix4.multiplyByPoint(enuMatrix, southEastCorner, southEastCorner);
    // make eastward vector
    Cartesian3.subtract(southEastCorner, southWestCorner, eastVectorResult);

    const northWestCorner = northVectorResult;
    northWestCorner.x = minX;
    northWestCorner.y = maxY;
    northWestCorner.z = 0.0;
    Matrix4.multiplyByPoint(enuMatrix, northWestCorner, northWestCorner);
    // make eastward vector
    Cartesian3.subtract(northWestCorner, southWestCorner, northVectorResult);
  }

  const eastwardScratch = new Cartesian3();
  const northwardScratch = new Cartesian3();
  const encodeScratch = new EncodedCartesian3();
  /**
   * Gets an attributes object containing:
   * - 3 high-precision points as 6 GeometryInstanceAttributes. These points are used to compute eye-space planes.
   * - 1 texture coordinate rotation GeometryInstanceAttributes
   * - 2 GeometryInstanceAttributes used to compute high-precision points in 2D and Columbus View.
   *   These points are used to compute eye-space planes like above.
   *
   * Used to compute texture coordinates for small-area ClassificationPrimitives with materials or multiple non-overlapping instances.
   *
   * @see ShadowVolumeAppearance
   * @private
   *
   * @param {Rectangle} boundingRectangle Rectangle object that the points will approximately bound
   * @param {Number[]} textureCoordinateRotationPoints Points in the computed texture coordinate system for remapping texture coordinates
   * @param {Ellipsoid} ellipsoid Ellipsoid for converting Rectangle points to world coordinates
   * @param {MapProjection} projection The MapProjection used for 2D and Columbus View.
   * @param {Number} [height=0] The maximum height for the shadow volume.
   * @returns {Object} An attributes dictionary containing planar texture coordinate attributes.
   */
  ShadowVolumeAppearance.getPlanarTextureCoordinateAttributes = function (
    boundingRectangle,
    textureCoordinateRotationPoints,
    ellipsoid,
    projection,
    height
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("boundingRectangle", boundingRectangle);
    Check.defined(
      "textureCoordinateRotationPoints",
      textureCoordinateRotationPoints
    );
    Check.typeOf.object("ellipsoid", ellipsoid);
    Check.typeOf.object("projection", projection);
    //>>includeEnd('debug');

    const corner = cornerScratch;
    const eastward = eastwardScratch;
    const northward = northwardScratch;
    computeRectangleBounds(
      boundingRectangle,
      ellipsoid,
      defaultValue(height, 0.0),
      corner,
      eastward,
      northward
    );

    const attributes = {};
    addTextureCoordinateRotationAttributes(
      attributes,
      textureCoordinateRotationPoints
    );

    const encoded = EncodedCartesian3.fromCartesian(corner, encodeScratch);

    attributes.southWest_HIGH = new GeometryInstanceAttribute({
      componentDatatype: ComponentDatatype$1.FLOAT,
      componentsPerAttribute: 3,
      normalize: false,
      value: Cartesian3.pack(encoded.high, [0, 0, 0]),
    });
    attributes.southWest_LOW = new GeometryInstanceAttribute({
      componentDatatype: ComponentDatatype$1.FLOAT,
      componentsPerAttribute: 3,
      normalize: false,
      value: Cartesian3.pack(encoded.low, [0, 0, 0]),
    });
    attributes.eastward = new GeometryInstanceAttribute({
      componentDatatype: ComponentDatatype$1.FLOAT,
      componentsPerAttribute: 3,
      normalize: false,
      value: Cartesian3.pack(eastward, [0, 0, 0]),
    });
    attributes.northward = new GeometryInstanceAttribute({
      componentDatatype: ComponentDatatype$1.FLOAT,
      componentsPerAttribute: 3,
      normalize: false,
      value: Cartesian3.pack(northward, [0, 0, 0]),
    });

    add2DTextureCoordinateAttributes(boundingRectangle, projection, attributes);
    return attributes;
  };

  const spherePointScratch = new Cartesian3();
  function latLongToSpherical(latitude, longitude, ellipsoid, result) {
    const cartographic = cartographicScratch$3;
    cartographic.latitude = latitude;
    cartographic.longitude = longitude;
    cartographic.height = 0.0;

    const spherePoint = Cartographic.toCartesian(
      cartographic,
      ellipsoid,
      spherePointScratch
    );

    // Project into plane with vertical for latitude
    const magXY = Math.sqrt(
      spherePoint.x * spherePoint.x + spherePoint.y * spherePoint.y
    );

    // Use fastApproximateAtan2 for alignment with shader
    const sphereLatitude = CesiumMath.fastApproximateAtan2(magXY, spherePoint.z);
    const sphereLongitude = CesiumMath.fastApproximateAtan2(
      spherePoint.x,
      spherePoint.y
    );

    result.x = sphereLatitude;
    result.y = sphereLongitude;

    return result;
  }

  const sphericalScratch = new Cartesian2();
  /**
   * Gets an attributes object containing:
   * - the southwest corner of a rectangular area in spherical coordinates, as well as the inverse of the latitude/longitude range.
   *   These are computed using the same atan2 approximation used in the shader.
   * - 1 texture coordinate rotation GeometryInstanceAttributes
   * - 2 GeometryInstanceAttributes used to compute high-precision points in 2D and Columbus View.
   *   These points are used to compute eye-space planes like above.
   *
   * Used when computing texture coordinates for large-area ClassificationPrimitives with materials or
   * multiple non-overlapping instances.
   * @see ShadowVolumeAppearance
   * @private
   *
   * @param {Rectangle} boundingRectangle Rectangle object that the spherical extents will approximately bound
   * @param {Number[]} textureCoordinateRotationPoints Points in the computed texture coordinate system for remapping texture coordinates
   * @param {Ellipsoid} ellipsoid Ellipsoid for converting Rectangle points to world coordinates
   * @param {MapProjection} projection The MapProjection used for 2D and Columbus View.
   * @returns {Object} An attributes dictionary containing spherical texture coordinate attributes.
   */
  ShadowVolumeAppearance.getSphericalExtentGeometryInstanceAttributes = function (
    boundingRectangle,
    textureCoordinateRotationPoints,
    ellipsoid,
    projection
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("boundingRectangle", boundingRectangle);
    Check.defined(
      "textureCoordinateRotationPoints",
      textureCoordinateRotationPoints
    );
    Check.typeOf.object("ellipsoid", ellipsoid);
    Check.typeOf.object("projection", projection);
    //>>includeEnd('debug');

    // rectangle cartographic coords !== spherical because it's on an ellipsoid
    const southWestExtents = latLongToSpherical(
      boundingRectangle.south,
      boundingRectangle.west,
      ellipsoid,
      sphericalScratch
    );

    let south = southWestExtents.x;
    let west = southWestExtents.y;

    const northEastExtents = latLongToSpherical(
      boundingRectangle.north,
      boundingRectangle.east,
      ellipsoid,
      sphericalScratch
    );
    let north = northEastExtents.x;
    let east = northEastExtents.y;

    // If the bounding rectangle crosses the IDL, rotate the spherical extents so the cross no longer happens.
    // This rotation must happen in the shader too.
    let rotationRadians = 0.0;
    if (west > east) {
      rotationRadians = CesiumMath.PI - west;
      west = -CesiumMath.PI;
      east += rotationRadians;
    }

    // Slightly pad extents to avoid floating point error when fragment culling at edges.
    south -= CesiumMath.EPSILON5;
    west -= CesiumMath.EPSILON5;
    north += CesiumMath.EPSILON5;
    east += CesiumMath.EPSILON5;

    const longitudeRangeInverse = 1.0 / (east - west);
    const latitudeRangeInverse = 1.0 / (north - south);

    const attributes = {
      sphericalExtents: new GeometryInstanceAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 4,
        normalize: false,
        value: [south, west, latitudeRangeInverse, longitudeRangeInverse],
      }),
      longitudeRotation: new GeometryInstanceAttribute({
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 1,
        normalize: false,
        value: [rotationRadians],
      }),
    };

    addTextureCoordinateRotationAttributes(
      attributes,
      textureCoordinateRotationPoints
    );
    add2DTextureCoordinateAttributes(boundingRectangle, projection, attributes);
    return attributes;
  };

  ShadowVolumeAppearance.hasAttributesForTextureCoordinatePlanes = function (
    attributes
  ) {
    return (
      defined(attributes.southWest_HIGH) &&
      defined(attributes.southWest_LOW) &&
      defined(attributes.northward) &&
      defined(attributes.eastward) &&
      defined(attributes.planes2D_HIGH) &&
      defined(attributes.planes2D_LOW) &&
      defined(attributes.uMaxVmax) &&
      defined(attributes.uvMinAndExtents)
    );
  };

  ShadowVolumeAppearance.hasAttributesForSphericalExtents = function (
    attributes
  ) {
    return (
      defined(attributes.sphericalExtents) &&
      defined(attributes.longitudeRotation) &&
      defined(attributes.planes2D_HIGH) &&
      defined(attributes.planes2D_LOW) &&
      defined(attributes.uMaxVmax) &&
      defined(attributes.uvMinAndExtents)
    );
  };

  function shouldUseSpherical(rectangle) {
    return (
      Math.max(rectangle.width, rectangle.height) >
      ShadowVolumeAppearance.MAX_WIDTH_FOR_PLANAR_EXTENTS
    );
  }

  /**
   * Computes whether the given rectangle is wide enough that texture coordinates
   * over its area should be computed using spherical extents instead of distance to planes.
   *
   * @param {Rectangle} rectangle A rectangle
   * @private
   */
  ShadowVolumeAppearance.shouldUseSphericalCoordinates = function (rectangle) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("rectangle", rectangle);
    //>>includeEnd('debug');

    return shouldUseSpherical(rectangle);
  };

  /**
   * Texture coordinates for ground primitives are computed either using spherical coordinates for large areas or
   * using distance from planes for small areas.
   *
   * @type {Number}
   * @constant
   * @private
   */
  ShadowVolumeAppearance.MAX_WIDTH_FOR_PLANAR_EXTENTS = CesiumMath.toRadians(1.0);

  /**
   * Determines the function used to compare stencil values for the stencil test.
   *
   * @enum {Number}
   */
  const StencilFunction = {
    /**
     * The stencil test never passes.
     *
     * @type {Number}
     * @constant
     */
    NEVER: WebGLConstants$1.NEVER,

    /**
     * The stencil test passes when the masked reference value is less than the masked stencil value.
     *
     * @type {Number}
     * @constant
     */
    LESS: WebGLConstants$1.LESS,

    /**
     * The stencil test passes when the masked reference value is equal to the masked stencil value.
     *
     * @type {Number}
     * @constant
     */
    EQUAL: WebGLConstants$1.EQUAL,

    /**
     * The stencil test passes when the masked reference value is less than or equal to the masked stencil value.
     *
     * @type {Number}
     * @constant
     */
    LESS_OR_EQUAL: WebGLConstants$1.LEQUAL,

    /**
     * The stencil test passes when the masked reference value is greater than the masked stencil value.
     *
     * @type {Number}
     * @constant
     */
    GREATER: WebGLConstants$1.GREATER,

    /**
     * The stencil test passes when the masked reference value is not equal to the masked stencil value.
     *
     * @type {Number}
     * @constant
     */
    NOT_EQUAL: WebGLConstants$1.NOTEQUAL,

    /**
     * The stencil test passes when the masked reference value is greater than or equal to the masked stencil value.
     *
     * @type {Number}
     * @constant
     */
    GREATER_OR_EQUAL: WebGLConstants$1.GEQUAL,

    /**
     * The stencil test always passes.
     *
     * @type {Number}
     * @constant
     */
    ALWAYS: WebGLConstants$1.ALWAYS,
  };
  var StencilFunction$1 = Object.freeze(StencilFunction);

  /**
   * Determines the action taken based on the result of the stencil test.
   *
   * @enum {Number}
   */
  const StencilOperation = {
    /**
     * Sets the stencil buffer value to zero.
     *
     * @type {Number}
     * @constant
     */
    ZERO: WebGLConstants$1.ZERO,

    /**
     * Does not change the stencil buffer.
     *
     * @type {Number}
     * @constant
     */
    KEEP: WebGLConstants$1.KEEP,

    /**
     * Replaces the stencil buffer value with the reference value.
     *
     * @type {Number}
     * @constant
     */
    REPLACE: WebGLConstants$1.REPLACE,

    /**
     * Increments the stencil buffer value, clamping to unsigned byte.
     *
     * @type {Number}
     * @constant
     */
    INCREMENT: WebGLConstants$1.INCR,

    /**
     * Decrements the stencil buffer value, clamping to zero.
     *
     * @type {Number}
     * @constant
     */
    DECREMENT: WebGLConstants$1.DECR,

    /**
     * Bitwise inverts the existing stencil buffer value.
     *
     * @type {Number}
     * @constant
     */
    INVERT: WebGLConstants$1.INVERT,

    /**
     * Increments the stencil buffer value, wrapping to zero when exceeding the unsigned byte range.
     *
     * @type {Number}
     * @constant
     */
    INCREMENT_WRAP: WebGLConstants$1.INCR_WRAP,

    /**
     * Decrements the stencil buffer value, wrapping to the maximum unsigned byte instead of going below zero.
     *
     * @type {Number}
     * @constant
     */
    DECREMENT_WRAP: WebGLConstants$1.DECR_WRAP,
  };
  var StencilOperation$1 = Object.freeze(StencilOperation);

  /**
   * The most significant bit is used to identify whether the pixel is 3D Tiles.
   * The next three bits store selection depth for the skip LODs optimization.
   * The last four bits are for increment/decrement shadow volume operations for classification.
   *
   * @private
   */
  const StencilConstants = {
    CESIUM_3D_TILE_MASK: 0x80,
    SKIP_LOD_MASK: 0x70,
    SKIP_LOD_BIT_SHIFT: 4,
    CLASSIFICATION_MASK: 0x0f,
  };

  StencilConstants.setCesium3DTileBit = function () {
    return {
      enabled: true,
      frontFunction: StencilFunction$1.ALWAYS,
      frontOperation: {
        fail: StencilOperation$1.KEEP,
        zFail: StencilOperation$1.KEEP,
        zPass: StencilOperation$1.REPLACE,
      },
      backFunction: StencilFunction$1.ALWAYS,
      backOperation: {
        fail: StencilOperation$1.KEEP,
        zFail: StencilOperation$1.KEEP,
        zPass: StencilOperation$1.REPLACE,
      },
      reference: StencilConstants.CESIUM_3D_TILE_MASK,
      mask: StencilConstants.CESIUM_3D_TILE_MASK,
    };
  };
  var StencilConstants$1 = Object.freeze(StencilConstants);

  /**
   * A classification primitive represents a volume enclosing geometry in the {@link Scene} to be highlighted.
   * <p>
   * A primitive combines geometry instances with an {@link Appearance} that describes the full shading, including
   * {@link Material} and {@link RenderState}.  Roughly, the geometry instance defines the structure and placement,
   * and the appearance defines the visual characteristics.  Decoupling geometry and appearance allows us to mix
   * and match most of them and add a new geometry or appearance independently of each other.
   * Only {@link PerInstanceColorAppearance} with the same color across all instances is supported at this time when using
   * ClassificationPrimitive directly.
   * For full {@link Appearance} support when classifying terrain or 3D Tiles use {@link GroundPrimitive} instead.
   * </p>
   * <p>
   * For correct rendering, this feature requires the EXT_frag_depth WebGL extension. For hardware that do not support this extension, there
   * will be rendering artifacts for some viewing angles.
   * </p>
   * <p>
   * Valid geometries are {@link BoxGeometry}, {@link CylinderGeometry}, {@link EllipsoidGeometry}, {@link PolylineVolumeGeometry}, and {@link SphereGeometry}.
   * </p>
   * <p>
   * Geometries that follow the surface of the ellipsoid, such as {@link CircleGeometry}, {@link CorridorGeometry}, {@link EllipseGeometry}, {@link PolygonGeometry}, and {@link RectangleGeometry},
   * are also valid if they are extruded volumes; otherwise, they will not be rendered.
   * </p>
   *
   * @alias ClassificationPrimitive
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Array|GeometryInstance} [options.geometryInstances] The geometry instances to render. This can either be a single instance or an array of length one.
   * @param {Appearance} [options.appearance] The appearance used to render the primitive. Defaults to PerInstanceColorAppearance when GeometryInstances have a color attribute.
   * @param {Boolean} [options.show=true] Determines if this primitive will be shown.
   * @param {Boolean} [options.vertexCacheOptimize=false] When <code>true</code>, geometry vertices are optimized for the pre and post-vertex-shader caches.
   * @param {Boolean} [options.interleave=false] When <code>true</code>, geometry vertex attributes are interleaved, which can slightly improve rendering performance but increases load time.
   * @param {Boolean} [options.compressVertices=true] When <code>true</code>, the geometry vertices are compressed, which will save memory.
   * @param {Boolean} [options.releaseGeometryInstances=true] When <code>true</code>, the primitive does not keep a reference to the input <code>geometryInstances</code> to save memory.
   * @param {Boolean} [options.allowPicking=true] When <code>true</code>, each geometry instance will only be pickable with {@link Scene#pick}.  When <code>false</code>, GPU memory is saved.
   * @param {Boolean} [options.asynchronous=true] Determines if the primitive will be created asynchronously or block until ready. If false initializeTerrainHeights() must be called first.
   * @param {ClassificationType} [options.classificationType=ClassificationType.BOTH] Determines whether terrain, 3D Tiles or both will be classified.
   * @param {Boolean} [options.debugShowBoundingVolume=false] For debugging only. Determines if this primitive's commands' bounding spheres are shown.
   * @param {Boolean} [options.debugShowShadowVolume=false] For debugging only. Determines if the shadow volume for each geometry in the primitive is drawn. Must be <code>true</code> on
   *                  creation for the volumes to be created before the geometry is released or options.releaseGeometryInstance must be <code>false</code>.
   *
   * @see Primitive
   * @see GroundPrimitive
   * @see GeometryInstance
   * @see Appearance
   */
  function ClassificationPrimitive(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const geometryInstances = options.geometryInstances;

    /**
     * The geometry instance rendered with this primitive.  This may
     * be <code>undefined</code> if <code>options.releaseGeometryInstances</code>
     * is <code>true</code> when the primitive is constructed.
     * <p>
     * Changing this property after the primitive is rendered has no effect.
     * </p>
     * <p>
     * Because of the rendering technique used, all geometry instances must be the same color.
     * If there is an instance with a differing color, a <code>DeveloperError</code> will be thrown
     * on the first attempt to render.
     * </p>
     *
     * @readonly
     * @type {Array|GeometryInstance}
     *
     * @default undefined
     */
    this.geometryInstances = geometryInstances;
    /**
     * Determines if the primitive will be shown.  This affects all geometry
     * instances in the primitive.
     *
     * @type {Boolean}
     *
     * @default true
     */
    this.show = defaultValue(options.show, true);
    /**
     * Determines whether terrain, 3D Tiles or both will be classified.
     *
     * @type {ClassificationType}
     *
     * @default ClassificationType.BOTH
     */
    this.classificationType = defaultValue(
      options.classificationType,
      ClassificationType$1.BOTH
    );
    /**
     * This property is for debugging only; it is not for production use nor is it optimized.
     * <p>
     * Draws the bounding sphere for each draw command in the primitive.
     * </p>
     *
     * @type {Boolean}
     *
     * @default false
     */
    this.debugShowBoundingVolume = defaultValue(
      options.debugShowBoundingVolume,
      false
    );
    /**
     * This property is for debugging only; it is not for production use nor is it optimized.
     * <p>
     * Draws the shadow volume for each geometry in the primitive.
     * </p>
     *
     * @type {Boolean}
     *
     * @default false
     */
    this.debugShowShadowVolume = defaultValue(
      options.debugShowShadowVolume,
      false
    );
    this._debugShowShadowVolume = false;

    // These are used by GroundPrimitive to augment the shader and uniform map.
    this._extruded = defaultValue(options._extruded, false);
    this._uniformMap = options._uniformMap;

    this._sp = undefined;
    this._spStencil = undefined;
    this._spPick = undefined;
    this._spColor = undefined;

    this._spPick2D = undefined; // only derived if necessary
    this._spColor2D = undefined; // only derived if necessary

    this._rsStencilDepthPass = undefined;
    this._rsStencilDepthPass3DTiles = undefined;
    this._rsColorPass = undefined;
    this._rsPickPass = undefined;

    this._commandsIgnoreShow = [];

    this._ready = false;
    this._readyPromise = defer();

    this._primitive = undefined;
    this._pickPrimitive = options._pickPrimitive;

    // Set in update
    this._hasSphericalExtentsAttribute = false;
    this._hasPlanarExtentsAttributes = false;
    this._hasPerColorAttribute = false;

    this.appearance = options.appearance;

    this._createBoundingVolumeFunction = options._createBoundingVolumeFunction;
    this._updateAndQueueCommandsFunction =
      options._updateAndQueueCommandsFunction;

    this._usePickOffsets = false;

    this._primitiveOptions = {
      geometryInstances: undefined,
      appearance: undefined,
      vertexCacheOptimize: defaultValue(options.vertexCacheOptimize, false),
      interleave: defaultValue(options.interleave, false),
      releaseGeometryInstances: defaultValue(
        options.releaseGeometryInstances,
        true
      ),
      allowPicking: defaultValue(options.allowPicking, true),
      asynchronous: defaultValue(options.asynchronous, true),
      compressVertices: defaultValue(options.compressVertices, true),
      _createBoundingVolumeFunction: undefined,
      _createRenderStatesFunction: undefined,
      _createShaderProgramFunction: undefined,
      _createCommandsFunction: undefined,
      _updateAndQueueCommandsFunction: undefined,
      _createPickOffsets: true,
    };
  }

  Object.defineProperties(ClassificationPrimitive.prototype, {
    /**
     * When <code>true</code>, geometry vertices are optimized for the pre and post-vertex-shader caches.
     *
     * @memberof ClassificationPrimitive.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default true
     */
    vertexCacheOptimize: {
      get: function () {
        return this._primitiveOptions.vertexCacheOptimize;
      },
    },

    /**
     * Determines if geometry vertex attributes are interleaved, which can slightly improve rendering performance.
     *
     * @memberof ClassificationPrimitive.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default false
     */
    interleave: {
      get: function () {
        return this._primitiveOptions.interleave;
      },
    },

    /**
     * When <code>true</code>, the primitive does not keep a reference to the input <code>geometryInstances</code> to save memory.
     *
     * @memberof ClassificationPrimitive.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default true
     */
    releaseGeometryInstances: {
      get: function () {
        return this._primitiveOptions.releaseGeometryInstances;
      },
    },

    /**
     * When <code>true</code>, each geometry instance will only be pickable with {@link Scene#pick}.  When <code>false</code>, GPU memory is saved.
     *
     * @memberof ClassificationPrimitive.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default true
     */
    allowPicking: {
      get: function () {
        return this._primitiveOptions.allowPicking;
      },
    },

    /**
     * Determines if the geometry instances will be created and batched on a web worker.
     *
     * @memberof ClassificationPrimitive.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default true
     */
    asynchronous: {
      get: function () {
        return this._primitiveOptions.asynchronous;
      },
    },

    /**
     * When <code>true</code>, geometry vertices are compressed, which will save memory.
     *
     * @memberof ClassificationPrimitive.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default true
     */
    compressVertices: {
      get: function () {
        return this._primitiveOptions.compressVertices;
      },
    },

    /**
     * Determines if the primitive is complete and ready to render.  If this property is
     * true, the primitive will be rendered the next time that {@link ClassificationPrimitive#update}
     * is called.
     *
     * @memberof ClassificationPrimitive.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    ready: {
      get: function () {
        return this._ready;
      },
    },

    /**
     * Gets a promise that resolves when the primitive is ready to render.
     * @memberof ClassificationPrimitive.prototype
     * @type {Promise.<ClassificationPrimitive>}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._readyPromise.promise;
      },
    },

    /**
     * Returns true if the ClassificationPrimitive needs a separate shader and commands for 2D.
     * This is because texture coordinates on ClassificationPrimitives are computed differently,
     * and are used for culling when multiple GeometryInstances are batched in one ClassificationPrimitive.
     * @memberof ClassificationPrimitive.prototype
     * @type {Boolean}
     * @readonly
     * @private
     */
    _needs2DShader: {
      get: function () {
        return (
          this._hasPlanarExtentsAttributes || this._hasSphericalExtentsAttribute
        );
      },
    },
  });

  /**
   * Determines if ClassificationPrimitive rendering is supported.
   *
   * @param {Scene} scene The scene.
   * @returns {Boolean} <code>true</code> if ClassificationPrimitives are supported; otherwise, returns <code>false</code>
   */
  ClassificationPrimitive.isSupported = function (scene) {
    return scene.context.stencilBuffer;
  };

  function getStencilDepthRenderState$1(enableStencil, mask3DTiles) {
    const stencilFunction = mask3DTiles
      ? StencilFunction$1.EQUAL
      : StencilFunction$1.ALWAYS;
    return {
      colorMask: {
        red: false,
        green: false,
        blue: false,
        alpha: false,
      },
      stencilTest: {
        enabled: enableStencil,
        frontFunction: stencilFunction,
        frontOperation: {
          fail: StencilOperation$1.KEEP,
          zFail: StencilOperation$1.DECREMENT_WRAP,
          zPass: StencilOperation$1.KEEP,
        },
        backFunction: stencilFunction,
        backOperation: {
          fail: StencilOperation$1.KEEP,
          zFail: StencilOperation$1.INCREMENT_WRAP,
          zPass: StencilOperation$1.KEEP,
        },
        reference: StencilConstants$1.CESIUM_3D_TILE_MASK,
        mask: StencilConstants$1.CESIUM_3D_TILE_MASK,
      },
      stencilMask: StencilConstants$1.CLASSIFICATION_MASK,
      depthTest: {
        enabled: true,
        func: DepthFunction$1.LESS_OR_EQUAL,
      },
      depthMask: false,
    };
  }

  function getColorRenderState(enableStencil) {
    return {
      stencilTest: {
        enabled: enableStencil,
        frontFunction: StencilFunction$1.NOT_EQUAL,
        frontOperation: {
          fail: StencilOperation$1.ZERO,
          zFail: StencilOperation$1.ZERO,
          zPass: StencilOperation$1.ZERO,
        },
        backFunction: StencilFunction$1.NOT_EQUAL,
        backOperation: {
          fail: StencilOperation$1.ZERO,
          zFail: StencilOperation$1.ZERO,
          zPass: StencilOperation$1.ZERO,
        },
        reference: 0,
        mask: StencilConstants$1.CLASSIFICATION_MASK,
      },
      stencilMask: StencilConstants$1.CLASSIFICATION_MASK,
      depthTest: {
        enabled: false,
      },
      depthMask: false,
      blending: BlendingState$1.PRE_MULTIPLIED_ALPHA_BLEND,
    };
  }

  const pickRenderState$1 = {
    stencilTest: {
      enabled: true,
      frontFunction: StencilFunction$1.NOT_EQUAL,
      frontOperation: {
        fail: StencilOperation$1.ZERO,
        zFail: StencilOperation$1.ZERO,
        zPass: StencilOperation$1.ZERO,
      },
      backFunction: StencilFunction$1.NOT_EQUAL,
      backOperation: {
        fail: StencilOperation$1.ZERO,
        zFail: StencilOperation$1.ZERO,
        zPass: StencilOperation$1.ZERO,
      },
      reference: 0,
      mask: StencilConstants$1.CLASSIFICATION_MASK,
    },
    stencilMask: StencilConstants$1.CLASSIFICATION_MASK,
    depthTest: {
      enabled: false,
    },
    depthMask: false,
  };

  function createRenderStates$5(
    classificationPrimitive,
    context,
    appearance,
    twoPasses
  ) {
    if (defined(classificationPrimitive._rsStencilDepthPass)) {
      return;
    }
    const stencilEnabled = !classificationPrimitive.debugShowShadowVolume;

    classificationPrimitive._rsStencilDepthPass = RenderState.fromCache(
      getStencilDepthRenderState$1(stencilEnabled, false)
    );
    classificationPrimitive._rsStencilDepthPass3DTiles = RenderState.fromCache(
      getStencilDepthRenderState$1(stencilEnabled, true)
    );
    classificationPrimitive._rsColorPass = RenderState.fromCache(
      getColorRenderState(stencilEnabled)
    );
    classificationPrimitive._rsPickPass = RenderState.fromCache(pickRenderState$1);
  }

  function modifyForEncodedNormals(primitive, vertexShaderSource) {
    if (!primitive.compressVertices) {
      return vertexShaderSource;
    }

    if (
      vertexShaderSource.search(/attribute\s+vec3\s+extrudeDirection;/g) !== -1
    ) {
      const attributeName = "compressedAttributes";

      //only shadow volumes use extrudeDirection, and shadow volumes use vertexFormat: POSITION_ONLY so we don't need to check other attributes
      const attributeDecl = `attribute vec2 ${attributeName};`;

      const globalDecl = "vec3 extrudeDirection;\n";
      const decode = `    extrudeDirection = czm_octDecode(${attributeName}, 65535.0);\n`;

      let modifiedVS = vertexShaderSource;
      modifiedVS = modifiedVS.replace(
        /attribute\s+vec3\s+extrudeDirection;/g,
        ""
      );
      modifiedVS = ShaderSource.replaceMain(
        modifiedVS,
        "czm_non_compressed_main"
      );
      const compressedMain =
        `${"void main() \n" + "{ \n"}${decode}    czm_non_compressed_main(); \n` +
        `}`;

      return [attributeDecl, globalDecl, modifiedVS, compressedMain].join("\n");
    }
  }

  function createShaderProgram$2(classificationPrimitive, frameState) {
    const context = frameState.context;
    const primitive = classificationPrimitive._primitive;
    let vs = ShadowVolumeAppearanceVS;
    vs = classificationPrimitive._primitive._batchTable.getVertexShaderCallback()(
      vs
    );
    vs = Primitive$3._appendDistanceDisplayConditionToShader(primitive, vs);
    vs = Primitive$3._modifyShaderPosition(
      classificationPrimitive,
      vs,
      frameState.scene3DOnly
    );
    vs = Primitive$3._updateColorAttribute(primitive, vs);

    const planarExtents = classificationPrimitive._hasPlanarExtentsAttributes;
    const cullFragmentsUsingExtents =
      planarExtents || classificationPrimitive._hasSphericalExtentsAttribute;

    if (classificationPrimitive._extruded) {
      vs = modifyForEncodedNormals(primitive, vs);
    }

    const extrudedDefine = classificationPrimitive._extruded
      ? "EXTRUDED_GEOMETRY"
      : "";

    let vsSource = new ShaderSource({
      defines: [extrudedDefine],
      sources: [vs],
    });
    const fsSource = new ShaderSource({
      sources: [ShadowVolumeFS],
    });
    const attributeLocations =
      classificationPrimitive._primitive._attributeLocations;

    const shadowVolumeAppearance = new ShadowVolumeAppearance(
      cullFragmentsUsingExtents,
      planarExtents,
      classificationPrimitive.appearance
    );

    classificationPrimitive._spStencil = ShaderProgram.replaceCache({
      context: context,
      shaderProgram: classificationPrimitive._spStencil,
      vertexShaderSource: vsSource,
      fragmentShaderSource: fsSource,
      attributeLocations: attributeLocations,
    });

    if (classificationPrimitive._primitive.allowPicking) {
      let vsPick = ShaderSource.createPickVertexShaderSource(vs);
      vsPick = Primitive$3._appendShowToShader(primitive, vsPick);
      vsPick = Primitive$3._updatePickColorAttribute(vsPick);

      const pickFS3D = shadowVolumeAppearance.createPickFragmentShader(false);
      const pickVS3D = shadowVolumeAppearance.createPickVertexShader(
        [extrudedDefine],
        vsPick,
        false,
        frameState.mapProjection
      );

      classificationPrimitive._spPick = ShaderProgram.replaceCache({
        context: context,
        shaderProgram: classificationPrimitive._spPick,
        vertexShaderSource: pickVS3D,
        fragmentShaderSource: pickFS3D,
        attributeLocations: attributeLocations,
      });

      // Derive a 2D pick shader if the primitive uses texture coordinate-based fragment culling,
      // since texture coordinates are computed differently in 2D.
      if (cullFragmentsUsingExtents) {
        let pickProgram2D = context.shaderCache.getDerivedShaderProgram(
          classificationPrimitive._spPick,
          "2dPick"
        );
        if (!defined(pickProgram2D)) {
          const pickFS2D = shadowVolumeAppearance.createPickFragmentShader(true);
          const pickVS2D = shadowVolumeAppearance.createPickVertexShader(
            [extrudedDefine],
            vsPick,
            true,
            frameState.mapProjection
          );

          pickProgram2D = context.shaderCache.createDerivedShaderProgram(
            classificationPrimitive._spPick,
            "2dPick",
            {
              vertexShaderSource: pickVS2D,
              fragmentShaderSource: pickFS2D,
              attributeLocations: attributeLocations,
            }
          );
        }
        classificationPrimitive._spPick2D = pickProgram2D;
      }
    } else {
      classificationPrimitive._spPick = ShaderProgram.fromCache({
        context: context,
        vertexShaderSource: vsSource,
        fragmentShaderSource: fsSource,
        attributeLocations: attributeLocations,
      });
    }

    vs = Primitive$3._appendShowToShader(primitive, vs);
    vsSource = new ShaderSource({
      defines: [extrudedDefine],
      sources: [vs],
    });

    classificationPrimitive._sp = ShaderProgram.replaceCache({
      context: context,
      shaderProgram: classificationPrimitive._sp,
      vertexShaderSource: vsSource,
      fragmentShaderSource: fsSource,
      attributeLocations: attributeLocations,
    });

    // Create a fragment shader that computes only required material hookups using screen space techniques
    const fsColorSource = shadowVolumeAppearance.createFragmentShader(false);
    const vsColorSource = shadowVolumeAppearance.createVertexShader(
      [extrudedDefine],
      vs,
      false,
      frameState.mapProjection
    );

    classificationPrimitive._spColor = ShaderProgram.replaceCache({
      context: context,
      shaderProgram: classificationPrimitive._spColor,
      vertexShaderSource: vsColorSource,
      fragmentShaderSource: fsColorSource,
      attributeLocations: attributeLocations,
    });

    // Derive a 2D shader if the primitive uses texture coordinate-based fragment culling,
    // since texture coordinates are computed differently in 2D.
    // Any material that uses texture coordinates will also equip texture coordinate-based fragment culling.
    if (cullFragmentsUsingExtents) {
      let colorProgram2D = context.shaderCache.getDerivedShaderProgram(
        classificationPrimitive._spColor,
        "2dColor"
      );
      if (!defined(colorProgram2D)) {
        const fsColorSource2D = shadowVolumeAppearance.createFragmentShader(true);
        const vsColorSource2D = shadowVolumeAppearance.createVertexShader(
          [extrudedDefine],
          vs,
          true,
          frameState.mapProjection
        );

        colorProgram2D = context.shaderCache.createDerivedShaderProgram(
          classificationPrimitive._spColor,
          "2dColor",
          {
            vertexShaderSource: vsColorSource2D,
            fragmentShaderSource: fsColorSource2D,
            attributeLocations: attributeLocations,
          }
        );
      }
      classificationPrimitive._spColor2D = colorProgram2D;
    }
  }

  function createColorCommands$1(classificationPrimitive, colorCommands) {
    const primitive = classificationPrimitive._primitive;
    let length = primitive._va.length * 2; // each geometry (pack of vertex attributes) needs 2 commands: front/back stencils and fill
    colorCommands.length = length;

    let i;
    let command;
    let derivedCommand;
    let vaIndex = 0;
    let uniformMap = primitive._batchTable.getUniformMapCallback()(
      classificationPrimitive._uniformMap
    );

    const needs2DShader = classificationPrimitive._needs2DShader;

    for (i = 0; i < length; i += 2) {
      const vertexArray = primitive._va[vaIndex++];

      // Stencil depth command
      command = colorCommands[i];
      if (!defined(command)) {
        command = colorCommands[i] = new DrawCommand({
          owner: classificationPrimitive,
          primitiveType: primitive._primitiveType,
        });
      }

      command.vertexArray = vertexArray;
      command.renderState = classificationPrimitive._rsStencilDepthPass;
      command.shaderProgram = classificationPrimitive._sp;
      command.uniformMap = uniformMap;
      command.pass = Pass$1.TERRAIN_CLASSIFICATION;

      derivedCommand = DrawCommand.shallowClone(
        command,
        command.derivedCommands.tileset
      );
      derivedCommand.renderState =
        classificationPrimitive._rsStencilDepthPass3DTiles;
      derivedCommand.pass = Pass$1.CESIUM_3D_TILE_CLASSIFICATION;
      command.derivedCommands.tileset = derivedCommand;

      // Color command
      command = colorCommands[i + 1];
      if (!defined(command)) {
        command = colorCommands[i + 1] = new DrawCommand({
          owner: classificationPrimitive,
          primitiveType: primitive._primitiveType,
        });
      }

      command.vertexArray = vertexArray;
      command.renderState = classificationPrimitive._rsColorPass;
      command.shaderProgram = classificationPrimitive._spColor;
      command.pass = Pass$1.TERRAIN_CLASSIFICATION;

      const appearance = classificationPrimitive.appearance;
      const material = appearance.material;
      if (defined(material)) {
        uniformMap = combine$2(uniformMap, material._uniforms);
      }

      command.uniformMap = uniformMap;

      derivedCommand = DrawCommand.shallowClone(
        command,
        command.derivedCommands.tileset
      );
      derivedCommand.pass = Pass$1.CESIUM_3D_TILE_CLASSIFICATION;
      command.derivedCommands.tileset = derivedCommand;

      // Derive for 2D if texture coordinates are ever computed
      if (needs2DShader) {
        // First derive from the terrain command
        let derived2DCommand = DrawCommand.shallowClone(
          command,
          command.derivedCommands.appearance2D
        );
        derived2DCommand.shaderProgram = classificationPrimitive._spColor2D;
        command.derivedCommands.appearance2D = derived2DCommand;

        // Then derive from the 3D Tiles command
        derived2DCommand = DrawCommand.shallowClone(
          derivedCommand,
          derivedCommand.derivedCommands.appearance2D
        );
        derived2DCommand.shaderProgram = classificationPrimitive._spColor2D;
        derivedCommand.derivedCommands.appearance2D = derived2DCommand;
      }
    }

    const commandsIgnoreShow = classificationPrimitive._commandsIgnoreShow;
    const spStencil = classificationPrimitive._spStencil;

    let commandIndex = 0;
    length = commandsIgnoreShow.length = length / 2;

    for (let j = 0; j < length; ++j) {
      const commandIgnoreShow = (commandsIgnoreShow[j] = DrawCommand.shallowClone(
        colorCommands[commandIndex],
        commandsIgnoreShow[j]
      ));
      commandIgnoreShow.shaderProgram = spStencil;
      commandIgnoreShow.pass = Pass$1.CESIUM_3D_TILE_CLASSIFICATION_IGNORE_SHOW;

      commandIndex += 2;
    }
  }

  function createPickCommands$1(classificationPrimitive, pickCommands) {
    const usePickOffsets = classificationPrimitive._usePickOffsets;

    const primitive = classificationPrimitive._primitive;
    let length = primitive._va.length * 2; // each geometry (pack of vertex attributes) needs 2 commands: front/back stencils and fill

    // Fallback for batching same-color geometry instances
    let pickOffsets;
    let pickIndex = 0;
    let pickOffset;
    if (usePickOffsets) {
      pickOffsets = primitive._pickOffsets;
      length = pickOffsets.length * 2;
    }

    pickCommands.length = length;

    let j;
    let command;
    let derivedCommand;
    let vaIndex = 0;
    const uniformMap = primitive._batchTable.getUniformMapCallback()(
      classificationPrimitive._uniformMap
    );

    const needs2DShader = classificationPrimitive._needs2DShader;

    for (j = 0; j < length; j += 2) {
      let vertexArray = primitive._va[vaIndex++];
      if (usePickOffsets) {
        pickOffset = pickOffsets[pickIndex++];
        vertexArray = primitive._va[pickOffset.index];
      }

      // Stencil depth command
      command = pickCommands[j];
      if (!defined(command)) {
        command = pickCommands[j] = new DrawCommand({
          owner: classificationPrimitive,
          primitiveType: primitive._primitiveType,
          pickOnly: true,
        });
      }

      command.vertexArray = vertexArray;
      command.renderState = classificationPrimitive._rsStencilDepthPass;
      command.shaderProgram = classificationPrimitive._sp;
      command.uniformMap = uniformMap;
      command.pass = Pass$1.TERRAIN_CLASSIFICATION;
      if (usePickOffsets) {
        command.offset = pickOffset.offset;
        command.count = pickOffset.count;
      }

      // Derive for 3D Tiles classification
      derivedCommand = DrawCommand.shallowClone(
        command,
        command.derivedCommands.tileset
      );
      derivedCommand.renderState =
        classificationPrimitive._rsStencilDepthPass3DTiles;
      derivedCommand.pass = Pass$1.CESIUM_3D_TILE_CLASSIFICATION;
      command.derivedCommands.tileset = derivedCommand;

      // Pick color command
      command = pickCommands[j + 1];
      if (!defined(command)) {
        command = pickCommands[j + 1] = new DrawCommand({
          owner: classificationPrimitive,
          primitiveType: primitive._primitiveType,
          pickOnly: true,
        });
      }

      command.vertexArray = vertexArray;
      command.renderState = classificationPrimitive._rsPickPass;
      command.shaderProgram = classificationPrimitive._spPick;
      command.uniformMap = uniformMap;
      command.pass = Pass$1.TERRAIN_CLASSIFICATION;
      if (usePickOffsets) {
        command.offset = pickOffset.offset;
        command.count = pickOffset.count;
      }

      derivedCommand = DrawCommand.shallowClone(
        command,
        command.derivedCommands.tileset
      );
      derivedCommand.pass = Pass$1.CESIUM_3D_TILE_CLASSIFICATION;
      command.derivedCommands.tileset = derivedCommand;

      // Derive for 2D if texture coordinates are ever computed
      if (needs2DShader) {
        // First derive from the terrain command
        let derived2DCommand = DrawCommand.shallowClone(
          command,
          command.derivedCommands.pick2D
        );
        derived2DCommand.shaderProgram = classificationPrimitive._spPick2D;
        command.derivedCommands.pick2D = derived2DCommand;

        // Then derive from the 3D Tiles command
        derived2DCommand = DrawCommand.shallowClone(
          derivedCommand,
          derivedCommand.derivedCommands.pick2D
        );
        derived2DCommand.shaderProgram = classificationPrimitive._spPick2D;
        derivedCommand.derivedCommands.pick2D = derived2DCommand;
      }
    }
  }

  function createCommands$4(
    classificationPrimitive,
    appearance,
    material,
    translucent,
    twoPasses,
    colorCommands,
    pickCommands
  ) {
    createColorCommands$1(classificationPrimitive, colorCommands);
    createPickCommands$1(classificationPrimitive, pickCommands);
  }

  function boundingVolumeIndex$1(commandIndex, length) {
    return Math.floor((commandIndex % length) / 2);
  }

  function updateAndQueueRenderCommand$1(
    command,
    frameState,
    modelMatrix,
    cull,
    boundingVolume,
    debugShowBoundingVolume
  ) {
    command.modelMatrix = modelMatrix;
    command.boundingVolume = boundingVolume;
    command.cull = cull;
    command.debugShowBoundingVolume = debugShowBoundingVolume;

    frameState.commandList.push(command);
  }

  function updateAndQueuePickCommand$1(
    command,
    frameState,
    modelMatrix,
    cull,
    boundingVolume
  ) {
    command.modelMatrix = modelMatrix;
    command.boundingVolume = boundingVolume;
    command.cull = cull;

    frameState.commandList.push(command);
  }

  function updateAndQueueCommands$2(
    classificationPrimitive,
    frameState,
    colorCommands,
    pickCommands,
    modelMatrix,
    cull,
    debugShowBoundingVolume,
    twoPasses
  ) {
    const primitive = classificationPrimitive._primitive;
    Primitive$3._updateBoundingVolumes(primitive, frameState, modelMatrix);

    let boundingVolumes;
    if (frameState.mode === SceneMode$1.SCENE3D) {
      boundingVolumes = primitive._boundingSphereWC;
    } else if (frameState.mode === SceneMode$1.COLUMBUS_VIEW) {
      boundingVolumes = primitive._boundingSphereCV;
    } else if (
      frameState.mode === SceneMode$1.SCENE2D &&
      defined(primitive._boundingSphere2D)
    ) {
      boundingVolumes = primitive._boundingSphere2D;
    } else if (defined(primitive._boundingSphereMorph)) {
      boundingVolumes = primitive._boundingSphereMorph;
    }

    const classificationType = classificationPrimitive.classificationType;
    const queueTerrainCommands =
      classificationType !== ClassificationType$1.CESIUM_3D_TILE;
    const queue3DTilesCommands =
      classificationType !== ClassificationType$1.TERRAIN;

    const passes = frameState.passes;

    let i;
    let boundingVolume;
    let command;

    if (passes.render) {
      const colorLength = colorCommands.length;
      for (i = 0; i < colorLength; ++i) {
        boundingVolume = boundingVolumes[boundingVolumeIndex$1(i, colorLength)];
        if (queueTerrainCommands) {
          command = colorCommands[i];
          updateAndQueueRenderCommand$1(
            command,
            frameState,
            modelMatrix,
            cull,
            boundingVolume,
            debugShowBoundingVolume
          );
        }
        if (queue3DTilesCommands) {
          command = colorCommands[i].derivedCommands.tileset;
          updateAndQueueRenderCommand$1(
            command,
            frameState,
            modelMatrix,
            cull,
            boundingVolume,
            debugShowBoundingVolume
          );
        }
      }

      if (frameState.invertClassification) {
        const ignoreShowCommands = classificationPrimitive._commandsIgnoreShow;
        const ignoreShowCommandsLength = ignoreShowCommands.length;
        for (i = 0; i < ignoreShowCommandsLength; ++i) {
          boundingVolume = boundingVolumes[i];
          command = ignoreShowCommands[i];
          updateAndQueueRenderCommand$1(
            command,
            frameState,
            modelMatrix,
            cull,
            boundingVolume,
            debugShowBoundingVolume
          );
        }
      }
    }

    if (passes.pick) {
      const pickLength = pickCommands.length;
      const pickOffsets = primitive._pickOffsets;
      for (i = 0; i < pickLength; ++i) {
        const pickOffset = pickOffsets[boundingVolumeIndex$1(i, pickLength)];
        boundingVolume = boundingVolumes[pickOffset.index];
        if (queueTerrainCommands) {
          command = pickCommands[i];
          updateAndQueuePickCommand$1(
            command,
            frameState,
            modelMatrix,
            cull,
            boundingVolume
          );
        }
        if (queue3DTilesCommands) {
          command = pickCommands[i].derivedCommands.tileset;
          updateAndQueuePickCommand$1(
            command,
            frameState,
            modelMatrix,
            cull,
            boundingVolume
          );
        }
      }
    }
  }

  /**
   * Called when {@link Viewer} or {@link CesiumWidget} render the scene to
   * get the draw commands needed to render this primitive.
   * <p>
   * Do not call this function directly.  This is documented just to
   * list the exceptions that may be propagated when the scene is rendered:
   * </p>
   *
   * @exception {DeveloperError} All instance geometries must have the same primitiveType.
   * @exception {DeveloperError} Appearance and material have a uniform with the same name.
   * @exception {DeveloperError} Not all of the geometry instances have the same color attribute.
   */
  ClassificationPrimitive.prototype.update = function (frameState) {
    if (!defined(this._primitive) && !defined(this.geometryInstances)) {
      return;
    }

    let appearance = this.appearance;
    if (defined(appearance) && defined(appearance.material)) {
      appearance.material.update(frameState.context);
    }

    const that = this;
    const primitiveOptions = this._primitiveOptions;

    if (!defined(this._primitive)) {
      const instances = Array.isArray(this.geometryInstances)
        ? this.geometryInstances
        : [this.geometryInstances];
      const length = instances.length;

      let i;
      let instance;
      let attributes;

      let hasPerColorAttribute = false;
      let allColorsSame = true;
      let firstColor;
      let hasSphericalExtentsAttribute = false;
      let hasPlanarExtentsAttributes = false;

      if (length > 0) {
        attributes = instances[0].attributes;
        // Not expecting these to be set by users, should only be set via GroundPrimitive.
        // So don't check for mismatch.
        hasSphericalExtentsAttribute = ShadowVolumeAppearance.hasAttributesForSphericalExtents(
          attributes
        );
        hasPlanarExtentsAttributes = ShadowVolumeAppearance.hasAttributesForTextureCoordinatePlanes(
          attributes
        );
        firstColor = attributes.color;
      }

      for (i = 0; i < length; i++) {
        instance = instances[i];
        const color = instance.attributes.color;
        if (defined(color)) {
          hasPerColorAttribute = true;
        }
        //>>includeStart('debug', pragmas.debug);
        else if (hasPerColorAttribute) {
          throw new DeveloperError(
            "All GeometryInstances must have color attributes to use per-instance color."
          );
        }
        //>>includeEnd('debug');

        allColorsSame =
          allColorsSame &&
          defined(color) &&
          ColorGeometryInstanceAttribute.equals(firstColor, color);
      }

      // If no attributes exist for computing spherical extents or fragment culling,
      // throw if the colors aren't all the same.
      if (
        !allColorsSame &&
        !hasSphericalExtentsAttribute &&
        !hasPlanarExtentsAttributes
      ) {
        throw new DeveloperError(
          "All GeometryInstances must have the same color attribute except via GroundPrimitives"
        );
      }

      // default to a color appearance
      if (hasPerColorAttribute && !defined(appearance)) {
        appearance = new PerInstanceColorAppearance({
          flat: true,
        });
        this.appearance = appearance;
      }

      //>>includeStart('debug', pragmas.debug);
      if (
        !hasPerColorAttribute &&
        appearance instanceof PerInstanceColorAppearance
      ) {
        throw new DeveloperError(
          "PerInstanceColorAppearance requires color GeometryInstanceAttributes on all GeometryInstances"
        );
      }
      if (
        defined(appearance.material) &&
        !hasSphericalExtentsAttribute &&
        !hasPlanarExtentsAttributes
      ) {
        throw new DeveloperError(
          "Materials on ClassificationPrimitives are not supported except via GroundPrimitives"
        );
      }
      //>>includeEnd('debug');

      this._usePickOffsets =
        !hasSphericalExtentsAttribute && !hasPlanarExtentsAttributes;
      this._hasSphericalExtentsAttribute = hasSphericalExtentsAttribute;
      this._hasPlanarExtentsAttributes = hasPlanarExtentsAttributes;
      this._hasPerColorAttribute = hasPerColorAttribute;

      const geometryInstances = new Array(length);
      for (i = 0; i < length; ++i) {
        instance = instances[i];
        geometryInstances[i] = new GeometryInstance({
          geometry: instance.geometry,
          attributes: instance.attributes,
          modelMatrix: instance.modelMatrix,
          id: instance.id,
          pickPrimitive: defaultValue(this._pickPrimitive, that),
        });
      }

      primitiveOptions.appearance = appearance;
      primitiveOptions.geometryInstances = geometryInstances;

      if (defined(this._createBoundingVolumeFunction)) {
        primitiveOptions._createBoundingVolumeFunction = function (
          frameState,
          geometry
        ) {
          that._createBoundingVolumeFunction(frameState, geometry);
        };
      }

      primitiveOptions._createRenderStatesFunction = function (
        primitive,
        context,
        appearance,
        twoPasses
      ) {
        createRenderStates$5(that);
      };
      primitiveOptions._createShaderProgramFunction = function (
        primitive,
        frameState,
        appearance
      ) {
        createShaderProgram$2(that, frameState);
      };
      primitiveOptions._createCommandsFunction = function (
        primitive,
        appearance,
        material,
        translucent,
        twoPasses,
        colorCommands,
        pickCommands
      ) {
        createCommands$4(
          that,
          undefined,
          undefined,
          true,
          false,
          colorCommands,
          pickCommands
        );
      };

      if (defined(this._updateAndQueueCommandsFunction)) {
        primitiveOptions._updateAndQueueCommandsFunction = function (
          primitive,
          frameState,
          colorCommands,
          pickCommands,
          modelMatrix,
          cull,
          debugShowBoundingVolume,
          twoPasses
        ) {
          that._updateAndQueueCommandsFunction(
            primitive,
            frameState,
            colorCommands,
            pickCommands,
            modelMatrix,
            cull,
            debugShowBoundingVolume,
            twoPasses
          );
        };
      } else {
        primitiveOptions._updateAndQueueCommandsFunction = function (
          primitive,
          frameState,
          colorCommands,
          pickCommands,
          modelMatrix,
          cull,
          debugShowBoundingVolume,
          twoPasses
        ) {
          updateAndQueueCommands$2(
            that,
            frameState,
            colorCommands,
            pickCommands,
            modelMatrix,
            cull,
            debugShowBoundingVolume);
        };
      }

      this._primitive = new Primitive$3(primitiveOptions);
      this._primitive.readyPromise.then(function (primitive) {
        that._ready = true;

        if (that.releaseGeometryInstances) {
          that.geometryInstances = undefined;
        }

        const error = primitive._error;
        if (!defined(error)) {
          that._readyPromise.resolve(that);
        } else {
          that._readyPromise.reject(error);
        }
      });
    }

    if (
      this.debugShowShadowVolume &&
      !this._debugShowShadowVolume &&
      this._ready
    ) {
      this._debugShowShadowVolume = true;
      this._rsStencilDepthPass = RenderState.fromCache(
        getStencilDepthRenderState$1(false, false)
      );
      this._rsStencilDepthPass3DTiles = RenderState.fromCache(
        getStencilDepthRenderState$1(false, true)
      );
      this._rsColorPass = RenderState.fromCache(getColorRenderState(false));
    } else if (!this.debugShowShadowVolume && this._debugShowShadowVolume) {
      this._debugShowShadowVolume = false;
      this._rsStencilDepthPass = RenderState.fromCache(
        getStencilDepthRenderState$1(true, false)
      );
      this._rsStencilDepthPass3DTiles = RenderState.fromCache(
        getStencilDepthRenderState$1(true, true)
      );
      this._rsColorPass = RenderState.fromCache(getColorRenderState(true));
    }
    // Update primitive appearance
    if (this._primitive.appearance !== appearance) {
      //>>includeStart('debug', pragmas.debug);
      // Check if the appearance is supported by the geometry attributes
      if (
        !this._hasSphericalExtentsAttribute &&
        !this._hasPlanarExtentsAttributes &&
        defined(appearance.material)
      ) {
        throw new DeveloperError(
          "Materials on ClassificationPrimitives are not supported except via GroundPrimitive"
        );
      }
      if (
        !this._hasPerColorAttribute &&
        appearance instanceof PerInstanceColorAppearance
      ) {
        throw new DeveloperError(
          "PerInstanceColorAppearance requires color GeometryInstanceAttribute"
        );
      }
      //>>includeEnd('debug');
      this._primitive.appearance = appearance;
    }

    this._primitive.show = this.show;
    this._primitive.debugShowBoundingVolume = this.debugShowBoundingVolume;
    this._primitive.update(frameState);
  };

  /**
   * Returns the modifiable per-instance attributes for a {@link GeometryInstance}.
   *
   * @param {*} id The id of the {@link GeometryInstance}.
   * @returns {Object} The typed array in the attribute's format or undefined if the is no instance with id.
   *
   * @exception {DeveloperError} must call update before calling getGeometryInstanceAttributes.
   *
   * @example
   * const attributes = primitive.getGeometryInstanceAttributes('an id');
   * attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.AQUA);
   * attributes.show = Cesium.ShowGeometryInstanceAttribute.toValue(true);
   */
  ClassificationPrimitive.prototype.getGeometryInstanceAttributes = function (
    id
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(this._primitive)) {
      throw new DeveloperError(
        "must call update before calling getGeometryInstanceAttributes"
      );
    }
    //>>includeEnd('debug');
    return this._primitive.getGeometryInstanceAttributes(id);
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <p>
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   * </p>
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see ClassificationPrimitive#destroy
   */
  ClassificationPrimitive.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <p>
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   * </p>
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @example
   * e = e && e.destroy();
   *
   * @see ClassificationPrimitive#isDestroyed
   */
  ClassificationPrimitive.prototype.destroy = function () {
    this._primitive = this._primitive && this._primitive.destroy();
    this._sp = this._sp && this._sp.destroy();
    this._spPick = this._spPick && this._spPick.destroy();
    this._spColor = this._spColor && this._spColor.destroy();

    // Derived programs, destroyed above if they existed.
    this._spPick2D = undefined;
    this._spColor2D = undefined;
    return destroyObject(this);
  };

  const GroundPrimitiveUniformMap = {
    u_globeMinimumAltitude: function () {
      return 55000.0;
    },
  };

  /**
   * A ground primitive represents geometry draped over terrain or 3D Tiles in the {@link Scene}.
   * <p>
   * A primitive combines geometry instances with an {@link Appearance} that describes the full shading, including
   * {@link Material} and {@link RenderState}.  Roughly, the geometry instance defines the structure and placement,
   * and the appearance defines the visual characteristics.  Decoupling geometry and appearance allows us to mix
   * and match most of them and add a new geometry or appearance independently of each other.
   * </p>
   * <p>
   * Support for the WEBGL_depth_texture extension is required to use GeometryInstances with different PerInstanceColors
   * or materials besides PerInstanceColorAppearance.
   * </p>
   * <p>
   * Textured GroundPrimitives were designed for notional patterns and are not meant for precisely mapping
   * textures to terrain - for that use case, use {@link SingleTileImageryProvider}.
   * </p>
   * <p>
   * For correct rendering, this feature requires the EXT_frag_depth WebGL extension. For hardware that do not support this extension, there
   * will be rendering artifacts for some viewing angles.
   * </p>
   * <p>
   * Valid geometries are {@link CircleGeometry}, {@link CorridorGeometry}, {@link EllipseGeometry}, {@link PolygonGeometry}, and {@link RectangleGeometry}.
   * </p>
   *
   * @alias GroundPrimitive
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Array|GeometryInstance} [options.geometryInstances] The geometry instances to render.
   * @param {Appearance} [options.appearance] The appearance used to render the primitive. Defaults to a flat PerInstanceColorAppearance when GeometryInstances have a color attribute.
   * @param {Boolean} [options.show=true] Determines if this primitive will be shown.
   * @param {Boolean} [options.vertexCacheOptimize=false] When <code>true</code>, geometry vertices are optimized for the pre and post-vertex-shader caches.
   * @param {Boolean} [options.interleave=false] When <code>true</code>, geometry vertex attributes are interleaved, which can slightly improve rendering performance but increases load time.
   * @param {Boolean} [options.compressVertices=true] When <code>true</code>, the geometry vertices are compressed, which will save memory.
   * @param {Boolean} [options.releaseGeometryInstances=true] When <code>true</code>, the primitive does not keep a reference to the input <code>geometryInstances</code> to save memory.
   * @param {Boolean} [options.allowPicking=true] When <code>true</code>, each geometry instance will only be pickable with {@link Scene#pick}.  When <code>false</code>, GPU memory is saved.
   * @param {Boolean} [options.asynchronous=true] Determines if the primitive will be created asynchronously or block until ready. If false initializeTerrainHeights() must be called first.
   * @param {ClassificationType} [options.classificationType=ClassificationType.BOTH] Determines whether terrain, 3D Tiles or both will be classified.
   * @param {Boolean} [options.debugShowBoundingVolume=false] For debugging only. Determines if this primitive's commands' bounding spheres are shown.
   * @param {Boolean} [options.debugShowShadowVolume=false] For debugging only. Determines if the shadow volume for each geometry in the primitive is drawn. Must be <code>true</code> on
   *                  creation for the volumes to be created before the geometry is released or options.releaseGeometryInstance must be <code>false</code>.
   *
   * @example
   * // Example 1: Create primitive with a single instance
   * const rectangleInstance = new Cesium.GeometryInstance({
   *   geometry : new Cesium.RectangleGeometry({
   *     rectangle : Cesium.Rectangle.fromDegrees(-140.0, 30.0, -100.0, 40.0)
   *   }),
   *   id : 'rectangle',
   *   attributes : {
   *     color : new Cesium.ColorGeometryInstanceAttribute(0.0, 1.0, 1.0, 0.5)
   *   }
   * });
   * scene.primitives.add(new Cesium.GroundPrimitive({
   *   geometryInstances : rectangleInstance
   * }));
   *
   * // Example 2: Batch instances
   * const color = new Cesium.ColorGeometryInstanceAttribute(0.0, 1.0, 1.0, 0.5); // Both instances must have the same color.
   * const rectangleInstance = new Cesium.GeometryInstance({
   *   geometry : new Cesium.RectangleGeometry({
   *     rectangle : Cesium.Rectangle.fromDegrees(-140.0, 30.0, -100.0, 40.0)
   *   }),
   *   id : 'rectangle',
   *   attributes : {
   *     color : color
   *   }
   * });
   * const ellipseInstance = new Cesium.GeometryInstance({
   *     geometry : new Cesium.EllipseGeometry({
   *         center : Cesium.Cartesian3.fromDegrees(-105.0, 40.0),
   *         semiMinorAxis : 300000.0,
   *         semiMajorAxis : 400000.0
   *     }),
   *     id : 'ellipse',
   *     attributes : {
   *         color : color
   *     }
   * });
   * scene.primitives.add(new Cesium.GroundPrimitive({
   *   geometryInstances : [rectangleInstance, ellipseInstance]
   * }));
   *
   * @see Primitive
   * @see ClassificationPrimitive
   * @see GeometryInstance
   * @see Appearance
   */
  function GroundPrimitive(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    let appearance = options.appearance;
    const geometryInstances = options.geometryInstances;
    if (!defined(appearance) && defined(geometryInstances)) {
      const geometryInstancesArray = Array.isArray(geometryInstances)
        ? geometryInstances
        : [geometryInstances];
      const geometryInstanceCount = geometryInstancesArray.length;
      for (let i = 0; i < geometryInstanceCount; i++) {
        const attributes = geometryInstancesArray[i].attributes;
        if (defined(attributes) && defined(attributes.color)) {
          appearance = new PerInstanceColorAppearance({
            flat: true,
          });
          break;
        }
      }
    }
    /**
     * The {@link Appearance} used to shade this primitive. Each geometry
     * instance is shaded with the same appearance.  Some appearances, like
     * {@link PerInstanceColorAppearance} allow giving each instance unique
     * properties.
     *
     * @type Appearance
     *
     * @default undefined
     */
    this.appearance = appearance;

    /**
     * The geometry instances rendered with this primitive.  This may
     * be <code>undefined</code> if <code>options.releaseGeometryInstances</code>
     * is <code>true</code> when the primitive is constructed.
     * <p>
     * Changing this property after the primitive is rendered has no effect.
     * </p>
     *
     * @readonly
     * @type {Array|GeometryInstance}
     *
     * @default undefined
     */
    this.geometryInstances = options.geometryInstances;
    /**
     * Determines if the primitive will be shown.  This affects all geometry
     * instances in the primitive.
     *
     * @type {Boolean}
     *
     * @default true
     */
    this.show = defaultValue(options.show, true);
    /**
     * Determines whether terrain, 3D Tiles or both will be classified.
     *
     * @type {ClassificationType}
     *
     * @default ClassificationType.BOTH
     */
    this.classificationType = defaultValue(
      options.classificationType,
      ClassificationType$1.BOTH
    );
    /**
     * This property is for debugging only; it is not for production use nor is it optimized.
     * <p>
     * Draws the bounding sphere for each draw command in the primitive.
     * </p>
     *
     * @type {Boolean}
     *
     * @default false
     */
    this.debugShowBoundingVolume = defaultValue(
      options.debugShowBoundingVolume,
      false
    );

    /**
     * This property is for debugging only; it is not for production use nor is it optimized.
     * <p>
     * Draws the shadow volume for each geometry in the primitive.
     * </p>
     *
     * @type {Boolean}
     *
     * @default false
     */
    this.debugShowShadowVolume = defaultValue(
      options.debugShowShadowVolume,
      false
    );

    this._boundingVolumes = [];
    this._boundingVolumes2D = [];

    this._ready = false;
    this._readyPromise = defer();

    this._primitive = undefined;

    this._maxHeight = undefined;
    this._minHeight = undefined;

    this._maxTerrainHeight = ApproximateTerrainHeights._defaultMaxTerrainHeight;
    this._minTerrainHeight = ApproximateTerrainHeights._defaultMinTerrainHeight;

    this._boundingSpheresKeys = [];
    this._boundingSpheres = [];

    this._useFragmentCulling = false;
    // Used when inserting in an OrderedPrimitiveCollection
    this._zIndex = undefined;

    const that = this;
    this._classificationPrimitiveOptions = {
      geometryInstances: undefined,
      appearance: undefined,
      vertexCacheOptimize: defaultValue(options.vertexCacheOptimize, false),
      interleave: defaultValue(options.interleave, false),
      releaseGeometryInstances: defaultValue(
        options.releaseGeometryInstances,
        true
      ),
      allowPicking: defaultValue(options.allowPicking, true),
      asynchronous: defaultValue(options.asynchronous, true),
      compressVertices: defaultValue(options.compressVertices, true),
      _createBoundingVolumeFunction: undefined,
      _updateAndQueueCommandsFunction: undefined,
      _pickPrimitive: that,
      _extruded: true,
      _uniformMap: GroundPrimitiveUniformMap,
    };
  }

  Object.defineProperties(GroundPrimitive.prototype, {
    /**
     * When <code>true</code>, geometry vertices are optimized for the pre and post-vertex-shader caches.
     *
     * @memberof GroundPrimitive.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default true
     */
    vertexCacheOptimize: {
      get: function () {
        return this._classificationPrimitiveOptions.vertexCacheOptimize;
      },
    },

    /**
     * Determines if geometry vertex attributes are interleaved, which can slightly improve rendering performance.
     *
     * @memberof GroundPrimitive.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default false
     */
    interleave: {
      get: function () {
        return this._classificationPrimitiveOptions.interleave;
      },
    },

    /**
     * When <code>true</code>, the primitive does not keep a reference to the input <code>geometryInstances</code> to save memory.
     *
     * @memberof GroundPrimitive.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default true
     */
    releaseGeometryInstances: {
      get: function () {
        return this._classificationPrimitiveOptions.releaseGeometryInstances;
      },
    },

    /**
     * When <code>true</code>, each geometry instance will only be pickable with {@link Scene#pick}.  When <code>false</code>, GPU memory is saved.
     *
     * @memberof GroundPrimitive.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default true
     */
    allowPicking: {
      get: function () {
        return this._classificationPrimitiveOptions.allowPicking;
      },
    },

    /**
     * Determines if the geometry instances will be created and batched on a web worker.
     *
     * @memberof GroundPrimitive.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default true
     */
    asynchronous: {
      get: function () {
        return this._classificationPrimitiveOptions.asynchronous;
      },
    },

    /**
     * When <code>true</code>, geometry vertices are compressed, which will save memory.
     *
     * @memberof GroundPrimitive.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default true
     */
    compressVertices: {
      get: function () {
        return this._classificationPrimitiveOptions.compressVertices;
      },
    },

    /**
     * Determines if the primitive is complete and ready to render.  If this property is
     * true, the primitive will be rendered the next time that {@link GroundPrimitive#update}
     * is called.
     *
     * @memberof GroundPrimitive.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    ready: {
      get: function () {
        return this._ready;
      },
    },

    /**
     * Gets a promise that resolves when the primitive is ready to render.
     * @memberof GroundPrimitive.prototype
     * @type {Promise.<GroundPrimitive>}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._readyPromise.promise;
      },
    },
  });

  /**
   * Determines if GroundPrimitive rendering is supported.
   *
   * @function
   * @param {Scene} scene The scene.
   * @returns {Boolean} <code>true</code> if GroundPrimitives are supported; otherwise, returns <code>false</code>
   */
  GroundPrimitive.isSupported = ClassificationPrimitive.isSupported;

  function getComputeMaximumHeightFunction(primitive) {
    return function (granularity, ellipsoid) {
      const r = ellipsoid.maximumRadius;
      const delta = r / Math.cos(granularity * 0.5) - r;
      return primitive._maxHeight + delta;
    };
  }

  function getComputeMinimumHeightFunction(primitive) {
    return function (granularity, ellipsoid) {
      return primitive._minHeight;
    };
  }

  const scratchBVCartesianHigh = new Cartesian3();
  const scratchBVCartesianLow = new Cartesian3();
  const scratchBVCartesian = new Cartesian3();
  const scratchBVCartographic = new Cartographic();
  const scratchBVRectangle = new Rectangle();

  function getRectangle(frameState, geometry) {
    const ellipsoid = frameState.mapProjection.ellipsoid;

    if (
      !defined(geometry.attributes) ||
      !defined(geometry.attributes.position3DHigh)
    ) {
      if (defined(geometry.rectangle)) {
        return geometry.rectangle;
      }

      return undefined;
    }

    const highPositions = geometry.attributes.position3DHigh.values;
    const lowPositions = geometry.attributes.position3DLow.values;
    const length = highPositions.length;

    let minLat = Number.POSITIVE_INFINITY;
    let minLon = Number.POSITIVE_INFINITY;
    let maxLat = Number.NEGATIVE_INFINITY;
    let maxLon = Number.NEGATIVE_INFINITY;

    for (let i = 0; i < length; i += 3) {
      const highPosition = Cartesian3.unpack(
        highPositions,
        i,
        scratchBVCartesianHigh
      );
      const lowPosition = Cartesian3.unpack(
        lowPositions,
        i,
        scratchBVCartesianLow
      );

      const position = Cartesian3.add(
        highPosition,
        lowPosition,
        scratchBVCartesian
      );
      const cartographic = ellipsoid.cartesianToCartographic(
        position,
        scratchBVCartographic
      );

      const latitude = cartographic.latitude;
      const longitude = cartographic.longitude;

      minLat = Math.min(minLat, latitude);
      minLon = Math.min(minLon, longitude);
      maxLat = Math.max(maxLat, latitude);
      maxLon = Math.max(maxLon, longitude);
    }

    const rectangle = scratchBVRectangle;
    rectangle.north = maxLat;
    rectangle.south = minLat;
    rectangle.east = maxLon;
    rectangle.west = minLon;

    return rectangle;
  }

  function setMinMaxTerrainHeights(primitive, rectangle, ellipsoid) {
    const result = ApproximateTerrainHeights.getMinimumMaximumHeights(
      rectangle,
      ellipsoid
    );

    primitive._minTerrainHeight = result.minimumTerrainHeight;
    primitive._maxTerrainHeight = result.maximumTerrainHeight;
  }

  function createBoundingVolume(groundPrimitive, frameState, geometry) {
    const ellipsoid = frameState.mapProjection.ellipsoid;
    const rectangle = getRectangle(frameState, geometry);

    const obb = OrientedBoundingBox.fromRectangle(
      rectangle,
      groundPrimitive._minHeight,
      groundPrimitive._maxHeight,
      ellipsoid
    );
    groundPrimitive._boundingVolumes.push(obb);

    if (!frameState.scene3DOnly) {
      const projection = frameState.mapProjection;
      const boundingVolume = BoundingSphere.fromRectangleWithHeights2D(
        rectangle,
        projection,
        groundPrimitive._maxHeight,
        groundPrimitive._minHeight
      );
      Cartesian3.fromElements(
        boundingVolume.center.z,
        boundingVolume.center.x,
        boundingVolume.center.y,
        boundingVolume.center
      );

      groundPrimitive._boundingVolumes2D.push(boundingVolume);
    }
  }

  function boundingVolumeIndex(commandIndex, length) {
    return Math.floor((commandIndex % length) / 2);
  }

  function updateAndQueueRenderCommand(
    groundPrimitive,
    command,
    frameState,
    modelMatrix,
    cull,
    boundingVolume,
    debugShowBoundingVolume
  ) {
    // Use derived appearance command for 2D if needed
    const classificationPrimitive = groundPrimitive._primitive;
    if (
      frameState.mode !== SceneMode$1.SCENE3D &&
      command.shaderProgram === classificationPrimitive._spColor &&
      classificationPrimitive._needs2DShader
    ) {
      command = command.derivedCommands.appearance2D;
    }

    command.owner = groundPrimitive;
    command.modelMatrix = modelMatrix;
    command.boundingVolume = boundingVolume;
    command.cull = cull;
    command.debugShowBoundingVolume = debugShowBoundingVolume;

    frameState.commandList.push(command);
  }

  function updateAndQueuePickCommand(
    groundPrimitive,
    command,
    frameState,
    modelMatrix,
    cull,
    boundingVolume
  ) {
    // Use derived pick command for 2D if needed
    const classificationPrimitive = groundPrimitive._primitive;
    if (
      frameState.mode !== SceneMode$1.SCENE3D &&
      command.shaderProgram === classificationPrimitive._spPick &&
      classificationPrimitive._needs2DShader
    ) {
      command = command.derivedCommands.pick2D;
    }

    command.owner = groundPrimitive;
    command.modelMatrix = modelMatrix;
    command.boundingVolume = boundingVolume;
    command.cull = cull;

    frameState.commandList.push(command);
  }

  function updateAndQueueCommands$1(
    groundPrimitive,
    frameState,
    colorCommands,
    pickCommands,
    modelMatrix,
    cull,
    debugShowBoundingVolume,
    twoPasses
  ) {
    let boundingVolumes;
    if (frameState.mode === SceneMode$1.SCENE3D) {
      boundingVolumes = groundPrimitive._boundingVolumes;
    } else {
      boundingVolumes = groundPrimitive._boundingVolumes2D;
    }

    const classificationType = groundPrimitive.classificationType;
    const queueTerrainCommands =
      classificationType !== ClassificationType$1.CESIUM_3D_TILE;
    const queue3DTilesCommands =
      classificationType !== ClassificationType$1.TERRAIN;

    const passes = frameState.passes;
    const classificationPrimitive = groundPrimitive._primitive;

    let i;
    let boundingVolume;
    let command;

    if (passes.render) {
      const colorLength = colorCommands.length;

      for (i = 0; i < colorLength; ++i) {
        boundingVolume = boundingVolumes[boundingVolumeIndex(i, colorLength)];
        if (queueTerrainCommands) {
          command = colorCommands[i];
          updateAndQueueRenderCommand(
            groundPrimitive,
            command,
            frameState,
            modelMatrix,
            cull,
            boundingVolume,
            debugShowBoundingVolume
          );
        }
        if (queue3DTilesCommands) {
          command = colorCommands[i].derivedCommands.tileset;
          updateAndQueueRenderCommand(
            groundPrimitive,
            command,
            frameState,
            modelMatrix,
            cull,
            boundingVolume,
            debugShowBoundingVolume
          );
        }
      }

      if (frameState.invertClassification) {
        const ignoreShowCommands = classificationPrimitive._commandsIgnoreShow;
        const ignoreShowCommandsLength = ignoreShowCommands.length;
        for (i = 0; i < ignoreShowCommandsLength; ++i) {
          boundingVolume = boundingVolumes[i];
          command = ignoreShowCommands[i];
          updateAndQueueRenderCommand(
            groundPrimitive,
            command,
            frameState,
            modelMatrix,
            cull,
            boundingVolume,
            debugShowBoundingVolume
          );
        }
      }
    }

    if (passes.pick) {
      const pickLength = pickCommands.length;

      let pickOffsets;
      if (!groundPrimitive._useFragmentCulling) {
        // Must be using pick offsets
        pickOffsets = classificationPrimitive._primitive._pickOffsets;
      }
      for (i = 0; i < pickLength; ++i) {
        boundingVolume = boundingVolumes[boundingVolumeIndex(i, pickLength)];
        if (!groundPrimitive._useFragmentCulling) {
          const pickOffset = pickOffsets[boundingVolumeIndex(i, pickLength)];
          boundingVolume = boundingVolumes[pickOffset.index];
        }
        if (queueTerrainCommands) {
          command = pickCommands[i];
          updateAndQueuePickCommand(
            groundPrimitive,
            command,
            frameState,
            modelMatrix,
            cull,
            boundingVolume
          );
        }
        if (queue3DTilesCommands) {
          command = pickCommands[i].derivedCommands.tileset;
          updateAndQueuePickCommand(
            groundPrimitive,
            command,
            frameState,
            modelMatrix,
            cull,
            boundingVolume
          );
        }
      }
    }
  }

  /**
   * Initializes the minimum and maximum terrain heights. This only needs to be called if you are creating the
   * GroundPrimitive synchronously.
   *
   * @returns {Promise<void>} A promise that will resolve once the terrain heights have been loaded.
   *
   */
  GroundPrimitive.initializeTerrainHeights = function () {
    return ApproximateTerrainHeights.initialize();
  };

  /**
   * Called when {@link Viewer} or {@link CesiumWidget} render the scene to
   * get the draw commands needed to render this primitive.
   * <p>
   * Do not call this function directly.  This is documented just to
   * list the exceptions that may be propagated when the scene is rendered:
   * </p>
   *
   * @exception {DeveloperError} For synchronous GroundPrimitive, you must call GroundPrimitive.initializeTerrainHeights() and wait for the returned promise to resolve.
   * @exception {DeveloperError} All instance geometries must have the same primitiveType.
   * @exception {DeveloperError} Appearance and material have a uniform with the same name.
   */
  GroundPrimitive.prototype.update = function (frameState) {
    if (!defined(this._primitive) && !defined(this.geometryInstances)) {
      return;
    }

    if (!ApproximateTerrainHeights.initialized) {
      //>>includeStart('debug', pragmas.debug);
      if (!this.asynchronous) {
        throw new DeveloperError(
          "For synchronous GroundPrimitives, you must call GroundPrimitive.initializeTerrainHeights() and wait for the returned promise to resolve."
        );
      }
      //>>includeEnd('debug');

      GroundPrimitive.initializeTerrainHeights();
      return;
    }

    const that = this;
    const primitiveOptions = this._classificationPrimitiveOptions;

    if (!defined(this._primitive)) {
      const ellipsoid = frameState.mapProjection.ellipsoid;

      let instance;
      let geometry;
      let instanceType;

      const instances = Array.isArray(this.geometryInstances)
        ? this.geometryInstances
        : [this.geometryInstances];
      const length = instances.length;
      const groundInstances = new Array(length);

      let i;
      let rectangle;
      for (i = 0; i < length; ++i) {
        instance = instances[i];
        geometry = instance.geometry;
        const instanceRectangle = getRectangle(frameState, geometry);
        if (!defined(rectangle)) {
          rectangle = Rectangle.clone(instanceRectangle);
        } else if (defined(instanceRectangle)) {
          Rectangle.union(rectangle, instanceRectangle, rectangle);
        }

        const id = instance.id;
        if (defined(id) && defined(instanceRectangle)) {
          const boundingSphere = ApproximateTerrainHeights.getBoundingSphere(
            instanceRectangle,
            ellipsoid
          );
          this._boundingSpheresKeys.push(id);
          this._boundingSpheres.push(boundingSphere);
        }

        instanceType = geometry.constructor;
        if (!defined(instanceType) || !defined(instanceType.createShadowVolume)) {
          //>>includeStart('debug', pragmas.debug);
          throw new DeveloperError(
            "Not all of the geometry instances have GroundPrimitive support."
          );
          //>>includeEnd('debug');
        }
      }

      // Now compute the min/max heights for the primitive
      setMinMaxTerrainHeights(this, rectangle, ellipsoid);
      const exaggeration = frameState.terrainExaggeration;
      const exaggerationRelativeHeight =
        frameState.terrainExaggerationRelativeHeight;
      this._minHeight = TerrainExaggeration.getHeight(
        this._minTerrainHeight,
        exaggeration,
        exaggerationRelativeHeight
      );
      this._maxHeight = TerrainExaggeration.getHeight(
        this._maxTerrainHeight,
        exaggeration,
        exaggerationRelativeHeight
      );

      const useFragmentCulling = GroundPrimitive._supportsMaterials(
        frameState.context
      );
      this._useFragmentCulling = useFragmentCulling;

      if (useFragmentCulling) {
        // Determine whether to add spherical or planar extent attributes for computing texture coordinates.
        // This depends on the size of the GeometryInstances.
        let attributes;
        let usePlanarExtents = true;
        for (i = 0; i < length; ++i) {
          instance = instances[i];
          geometry = instance.geometry;
          rectangle = getRectangle(frameState, geometry);
          if (ShadowVolumeAppearance.shouldUseSphericalCoordinates(rectangle)) {
            usePlanarExtents = false;
            break;
          }
        }

        for (i = 0; i < length; ++i) {
          instance = instances[i];
          geometry = instance.geometry;
          instanceType = geometry.constructor;

          const boundingRectangle = getRectangle(frameState, geometry);
          const textureCoordinateRotationPoints =
            geometry.textureCoordinateRotationPoints;

          if (usePlanarExtents) {
            attributes = ShadowVolumeAppearance.getPlanarTextureCoordinateAttributes(
              boundingRectangle,
              textureCoordinateRotationPoints,
              ellipsoid,
              frameState.mapProjection,
              this._maxHeight
            );
          } else {
            attributes = ShadowVolumeAppearance.getSphericalExtentGeometryInstanceAttributes(
              boundingRectangle,
              textureCoordinateRotationPoints,
              ellipsoid,
              frameState.mapProjection
            );
          }

          const instanceAttributes = instance.attributes;
          for (const attributeKey in instanceAttributes) {
            if (instanceAttributes.hasOwnProperty(attributeKey)) {
              attributes[attributeKey] = instanceAttributes[attributeKey];
            }
          }

          groundInstances[i] = new GeometryInstance({
            geometry: instanceType.createShadowVolume(
              geometry,
              getComputeMinimumHeightFunction(this),
              getComputeMaximumHeightFunction(this)
            ),
            attributes: attributes,
            id: instance.id,
          });
        }
      } else {
        // ClassificationPrimitive will check if the colors are all the same if it detects lack of fragment culling attributes
        for (i = 0; i < length; ++i) {
          instance = instances[i];
          geometry = instance.geometry;
          instanceType = geometry.constructor;
          groundInstances[i] = new GeometryInstance({
            geometry: instanceType.createShadowVolume(
              geometry,
              getComputeMinimumHeightFunction(this),
              getComputeMaximumHeightFunction(this)
            ),
            attributes: instance.attributes,
            id: instance.id,
          });
        }
      }

      primitiveOptions.geometryInstances = groundInstances;
      primitiveOptions.appearance = this.appearance;

      primitiveOptions._createBoundingVolumeFunction = function (
        frameState,
        geometry
      ) {
        createBoundingVolume(that, frameState, geometry);
      };
      primitiveOptions._updateAndQueueCommandsFunction = function (
        primitive,
        frameState,
        colorCommands,
        pickCommands,
        modelMatrix,
        cull,
        debugShowBoundingVolume,
        twoPasses
      ) {
        updateAndQueueCommands$1(
          that,
          frameState,
          colorCommands,
          pickCommands,
          modelMatrix,
          cull,
          debugShowBoundingVolume);
      };

      this._primitive = new ClassificationPrimitive(primitiveOptions);
      this._primitive.readyPromise.then(function (primitive) {
        that._ready = true;

        if (that.releaseGeometryInstances) {
          that.geometryInstances = undefined;
        }

        const error = primitive._error;
        if (!defined(error)) {
          that._readyPromise.resolve(that);
        } else {
          that._readyPromise.reject(error);
        }
      });
    }

    this._primitive.appearance = this.appearance;
    this._primitive.show = this.show;
    this._primitive.debugShowShadowVolume = this.debugShowShadowVolume;
    this._primitive.debugShowBoundingVolume = this.debugShowBoundingVolume;
    this._primitive.update(frameState);
  };

  /**
   * @private
   */
  GroundPrimitive.prototype.getBoundingSphere = function (id) {
    const index = this._boundingSpheresKeys.indexOf(id);
    if (index !== -1) {
      return this._boundingSpheres[index];
    }

    return undefined;
  };

  /**
   * Returns the modifiable per-instance attributes for a {@link GeometryInstance}.
   *
   * @param {*} id The id of the {@link GeometryInstance}.
   * @returns {Object} The typed array in the attribute's format or undefined if the is no instance with id.
   *
   * @exception {DeveloperError} must call update before calling getGeometryInstanceAttributes.
   *
   * @example
   * const attributes = primitive.getGeometryInstanceAttributes('an id');
   * attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.AQUA);
   * attributes.show = Cesium.ShowGeometryInstanceAttribute.toValue(true);
   */
  GroundPrimitive.prototype.getGeometryInstanceAttributes = function (id) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(this._primitive)) {
      throw new DeveloperError(
        "must call update before calling getGeometryInstanceAttributes"
      );
    }
    //>>includeEnd('debug');
    return this._primitive.getGeometryInstanceAttributes(id);
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <p>
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   * </p>
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see GroundPrimitive#destroy
   */
  GroundPrimitive.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <p>
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   * </p>
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @example
   * e = e && e.destroy();
   *
   * @see GroundPrimitive#isDestroyed
   */
  GroundPrimitive.prototype.destroy = function () {
    this._primitive = this._primitive && this._primitive.destroy();
    return destroyObject(this);
  };

  /**
   * Exposed for testing.
   *
   * @param {Context} context Rendering context
   * @returns {Boolean} Whether or not the current context supports materials on GroundPrimitives.
   * @private
   */
  GroundPrimitive._supportsMaterials = function (context) {
    return context.depthTexture;
  };

  /**
   * Checks if the given Scene supports materials on GroundPrimitives.
   * Materials on GroundPrimitives require support for the WEBGL_depth_texture extension.
   *
   * @param {Scene} scene The current scene.
   * @returns {Boolean} Whether or not the current scene supports materials on GroundPrimitives.
   */
  GroundPrimitive.supportsMaterials = function (scene) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("scene", scene);
    //>>includeEnd('debug');

    return GroundPrimitive._supportsMaterials(scene.frameState.context);
  };

  /**
   * The interface for all {@link Property} objects that represent {@link Material} uniforms.
   * This type defines an interface and cannot be instantiated directly.
   *
   * @alias MaterialProperty
   * @constructor
   * @abstract
   *
   * @see ColorMaterialProperty
   * @see CompositeMaterialProperty
   * @see GridMaterialProperty
   * @see ImageMaterialProperty
   * @see PolylineGlowMaterialProperty
   * @see PolylineOutlineMaterialProperty
   * @see StripeMaterialProperty
   */
  function MaterialProperty() {
    DeveloperError.throwInstantiationError();
  }

  Object.defineProperties(MaterialProperty.prototype, {
    /**
     * Gets a value indicating if this property is constant.  A property is considered
     * constant if getValue always returns the same result for the current definition.
     * @memberof MaterialProperty.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    isConstant: {
      get: DeveloperError.throwInstantiationError,
    },
    /**
     * Gets the event that is raised whenever the definition of this property changes.
     * The definition is considered to have changed if a call to getValue would return
     * a different result for the same time.
     * @memberof MaterialProperty.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: DeveloperError.throwInstantiationError,
    },
  });

  /**
   * Gets the {@link Material} type at the provided time.
   * @function
   *
   * @param {JulianDate} time The time for which to retrieve the type.
   * @returns {String} The type of material.
   */
  MaterialProperty.prototype.getType = DeveloperError.throwInstantiationError;

  /**
   * Gets the value of the property at the provided time.
   * @function
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {Object} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Object} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  MaterialProperty.prototype.getValue = DeveloperError.throwInstantiationError;

  /**
   * Compares this property to the provided property and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   * @function
   *
   * @param {Property} [other] The other property.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  MaterialProperty.prototype.equals = DeveloperError.throwInstantiationError;

  /**
   * @private
   */
  MaterialProperty.getValue = function (time, materialProperty, material) {
    let type;

    if (defined(materialProperty)) {
      type = materialProperty.getType(time);
      if (defined(type)) {
        if (!defined(material) || material.type !== type) {
          material = Material$4.fromType(type);
        }
        materialProperty.getValue(time, material.uniforms);
        return material;
      }
    }

    if (!defined(material) || material.type !== Material$4.ColorType) {
      material = Material$4.fromType(Material$4.ColorType);
    }
    Color.clone(Color.WHITE, material.uniforms.color);

    return material;
  };

  /**
   * Defines the interface for a dynamic geometry updater.  A DynamicGeometryUpdater
   * is responsible for handling visualization of a specific type of geometry
   * that needs to be recomputed based on simulation time.
   * This object is never used directly by client code, but is instead created by
   * {@link GeometryUpdater} implementations which contain dynamic geometry.
   *
   * This type defines an interface and cannot be instantiated directly.
   *
   * @alias DynamicGeometryUpdater
   * @constructor
   * @private
   * @abstract
   */
  function DynamicGeometryUpdater$1(
    geometryUpdater,
    primitives,
    orderedGroundPrimitives
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("geometryUpdater", geometryUpdater);
    Check.defined("primitives", primitives);
    Check.defined("orderedGroundPrimitives", orderedGroundPrimitives);
    //>>includeEnd('debug');

    this._primitives = primitives;
    this._orderedGroundPrimitives = orderedGroundPrimitives;
    this._primitive = undefined;
    this._outlinePrimitive = undefined;
    this._geometryUpdater = geometryUpdater;
    this._options = geometryUpdater._options;
    this._entity = geometryUpdater._entity;
    this._material = undefined;
  }

  DynamicGeometryUpdater$1.prototype._isHidden = function (entity, geometry, time) {
    return (
      !entity.isShowing ||
      !entity.isAvailable(time) ||
      !Property.getValueOrDefault(geometry.show, time, true)
    );
  };

  DynamicGeometryUpdater$1.prototype._setOptions =
    DeveloperError.throwInstantiationError;

  /**
   * Updates the geometry to the specified time.
   * @memberof DynamicGeometryUpdater
   * @function
   *
   * @param {JulianDate} time The current time.
   */
  DynamicGeometryUpdater$1.prototype.update = function (time) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("time", time);
    //>>includeEnd('debug');

    const geometryUpdater = this._geometryUpdater;
    const onTerrain = geometryUpdater._onTerrain;

    const primitives = this._primitives;
    const orderedGroundPrimitives = this._orderedGroundPrimitives;
    if (onTerrain) {
      orderedGroundPrimitives.remove(this._primitive);
    } else {
      primitives.removeAndDestroy(this._primitive);
      primitives.removeAndDestroy(this._outlinePrimitive);
      this._outlinePrimitive = undefined;
    }
    this._primitive = undefined;

    const entity = this._entity;
    const geometry = entity[this._geometryUpdater._geometryPropertyName];
    this._setOptions(entity, geometry, time);
    if (this._isHidden(entity, geometry, time)) {
      return;
    }

    const shadows = this._geometryUpdater.shadowsProperty.getValue(time);
    const options = this._options;
    if (!defined(geometry.fill) || geometry.fill.getValue(time)) {
      const fillMaterialProperty = geometryUpdater.fillMaterialProperty;
      const isColorAppearance =
        fillMaterialProperty instanceof ColorMaterialProperty;
      let appearance;
      const closed = geometryUpdater._getIsClosed(options);
      if (isColorAppearance) {
        appearance = new PerInstanceColorAppearance({
          closed: closed,
          flat:
            onTerrain && !geometryUpdater._supportsMaterialsforEntitiesOnTerrain,
        });
      } else {
        const material = MaterialProperty.getValue(
          time,
          fillMaterialProperty,
          this._material
        );
        this._material = material;
        appearance = new MaterialAppearance({
          material: material,
          translucent: material.isTranslucent(),
          closed: closed,
        });
      }

      if (onTerrain) {
        options.vertexFormat = PerInstanceColorAppearance.VERTEX_FORMAT;
        this._primitive = orderedGroundPrimitives.add(
          new GroundPrimitive({
            geometryInstances: this._geometryUpdater.createFillGeometryInstance(
              time
            ),
            appearance: appearance,
            asynchronous: false,
            shadows: shadows,
            classificationType: this._geometryUpdater.classificationTypeProperty.getValue(
              time
            ),
          }),
          Property.getValueOrUndefined(this._geometryUpdater.zIndex, time)
        );
      } else {
        options.vertexFormat = appearance.vertexFormat;

        const fillInstance = this._geometryUpdater.createFillGeometryInstance(
          time
        );

        if (isColorAppearance) {
          appearance.translucent = fillInstance.attributes.color.value[3] !== 255;
        }

        this._primitive = primitives.add(
          new Primitive$3({
            geometryInstances: fillInstance,
            appearance: appearance,
            asynchronous: false,
            shadows: shadows,
          })
        );
      }
    }

    if (
      !onTerrain &&
      defined(geometry.outline) &&
      geometry.outline.getValue(time)
    ) {
      const outlineInstance = this._geometryUpdater.createOutlineGeometryInstance(
        time
      );
      const outlineWidth = Property.getValueOrDefault(
        geometry.outlineWidth,
        time,
        1.0
      );

      this._outlinePrimitive = primitives.add(
        new Primitive$3({
          geometryInstances: outlineInstance,
          appearance: new PerInstanceColorAppearance({
            flat: true,
            translucent: outlineInstance.attributes.color.value[3] !== 255,
            renderState: {
              lineWidth: geometryUpdater._scene.clampLineWidth(outlineWidth),
            },
          }),
          asynchronous: false,
          shadows: shadows,
        })
      );
    }
  };

  /**
   * Computes a bounding sphere which encloses the visualization produced for the specified entity.
   * The bounding sphere is in the fixed frame of the scene's globe.
   * @function
   *
   * @param {BoundingSphere} result The bounding sphere onto which to store the result.
   * @returns {BoundingSphereState} BoundingSphereState.DONE if the result contains the bounding sphere,
   *                       BoundingSphereState.PENDING if the result is still being computed, or
   *                       BoundingSphereState.FAILED if the entity has no visualization in the current scene.
   * @private
   */
  DynamicGeometryUpdater$1.prototype.getBoundingSphere = function (result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(result)) {
      throw new DeveloperError("result is required.");
    }
    //>>includeEnd('debug');
    const entity = this._entity;
    const primitive = this._primitive;
    const outlinePrimitive = this._outlinePrimitive;

    let attributes;

    //Outline and Fill geometries have the same bounding sphere, so just use whichever one is defined and ready
    if (defined(primitive) && primitive.show && primitive.ready) {
      attributes = primitive.getGeometryInstanceAttributes(entity);
      if (defined(attributes) && defined(attributes.boundingSphere)) {
        BoundingSphere.clone(attributes.boundingSphere, result);
        return BoundingSphereState$1.DONE;
      }
    }

    if (
      defined(outlinePrimitive) &&
      outlinePrimitive.show &&
      outlinePrimitive.ready
    ) {
      attributes = outlinePrimitive.getGeometryInstanceAttributes(entity);
      if (defined(attributes) && defined(attributes.boundingSphere)) {
        BoundingSphere.clone(attributes.boundingSphere, result);
        return BoundingSphereState$1.DONE;
      }
    }

    if (
      (defined(primitive) && !primitive.ready) ||
      (defined(outlinePrimitive) && !outlinePrimitive.ready)
    ) {
      return BoundingSphereState$1.PENDING;
    }

    return BoundingSphereState$1.FAILED;
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * @memberof DynamicGeometryUpdater
   * @function
   *
   * @returns {Boolean} True if this object was destroyed; otherwise, false.
   */
  DynamicGeometryUpdater$1.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys and resources used by the object.  Once an object is destroyed, it should not be used.
   * @memberof DynamicGeometryUpdater
   * @function
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   */
  DynamicGeometryUpdater$1.prototype.destroy = function () {
    const primitives = this._primitives;
    const orderedGroundPrimitives = this._orderedGroundPrimitives;
    if (this._geometryUpdater._onTerrain) {
      orderedGroundPrimitives.remove(this._primitive);
    } else {
      primitives.removeAndDestroy(this._primitive);
    }
    primitives.removeAndDestroy(this._outlinePrimitive);
    destroyObject(this);
  };

  //This file is automatically rebuilt by the Cesium build process.
  var PolylineShadowVolumeFS = "#ifdef GL_EXT_frag_depth\n\
#extension GL_EXT_frag_depth : enable\n\
#endif\n\
varying vec4 v_startPlaneNormalEcAndHalfWidth;\n\
varying vec4 v_endPlaneNormalEcAndBatchId;\n\
varying vec4 v_rightPlaneEC;\n\
varying vec4 v_endEcAndStartEcX;\n\
varying vec4 v_texcoordNormalizationAndStartEcYZ;\n\
#ifdef PER_INSTANCE_COLOR\n\
varying vec4 v_color;\n\
#endif\n\
void main(void)\n\
{\n\
float logDepthOrDepth = czm_branchFreeTernary(czm_sceneMode == czm_sceneMode2D, gl_FragCoord.z, czm_unpackDepth(texture2D(czm_globeDepthTexture, gl_FragCoord.xy / czm_viewport.zw)));\n\
vec3 ecStart = vec3(v_endEcAndStartEcX.w, v_texcoordNormalizationAndStartEcYZ.zw);\n\
if (logDepthOrDepth == 0.0) {\n\
#ifdef DEBUG_SHOW_VOLUME\n\
gl_FragColor = vec4(1.0, 0.0, 0.0, 0.5);\n\
return;\n\
#else // DEBUG_SHOW_VOLUME\n\
discard;\n\
#endif // DEBUG_SHOW_VOLUME\n\
}\n\
vec4 eyeCoordinate = czm_windowToEyeCoordinates(gl_FragCoord.xy, logDepthOrDepth);\n\
eyeCoordinate /= eyeCoordinate.w;\n\
float halfMaxWidth = v_startPlaneNormalEcAndHalfWidth.w * czm_metersPerPixel(eyeCoordinate);\n\
float widthwiseDistance = czm_planeDistance(v_rightPlaneEC, eyeCoordinate.xyz);\n\
float distanceFromStart = czm_planeDistance(v_startPlaneNormalEcAndHalfWidth.xyz, -dot(ecStart, v_startPlaneNormalEcAndHalfWidth.xyz), eyeCoordinate.xyz);\n\
float distanceFromEnd = czm_planeDistance(v_endPlaneNormalEcAndBatchId.xyz, -dot(v_endEcAndStartEcX.xyz, v_endPlaneNormalEcAndBatchId.xyz), eyeCoordinate.xyz);\n\
if (abs(widthwiseDistance) > halfMaxWidth || distanceFromStart < 0.0 || distanceFromEnd < 0.0) {\n\
#ifdef DEBUG_SHOW_VOLUME\n\
gl_FragColor = vec4(1.0, 0.0, 0.0, 0.5);\n\
return;\n\
#else // DEBUG_SHOW_VOLUME\n\
discard;\n\
#endif // DEBUG_SHOW_VOLUME\n\
}\n\
vec3 alignedPlaneNormal;\n\
alignedPlaneNormal = cross(v_rightPlaneEC.xyz, v_startPlaneNormalEcAndHalfWidth.xyz);\n\
alignedPlaneNormal = normalize(cross(alignedPlaneNormal, v_rightPlaneEC.xyz));\n\
distanceFromStart = czm_planeDistance(alignedPlaneNormal, -dot(alignedPlaneNormal, ecStart), eyeCoordinate.xyz);\n\
alignedPlaneNormal = cross(v_rightPlaneEC.xyz, v_endPlaneNormalEcAndBatchId.xyz);\n\
alignedPlaneNormal = normalize(cross(alignedPlaneNormal, v_rightPlaneEC.xyz));\n\
distanceFromEnd = czm_planeDistance(alignedPlaneNormal, -dot(alignedPlaneNormal, v_endEcAndStartEcX.xyz), eyeCoordinate.xyz);\n\
#ifdef PER_INSTANCE_COLOR\n\
gl_FragColor = czm_gammaCorrect(v_color);\n\
#else // PER_INSTANCE_COLOR\n\
float s = clamp(distanceFromStart / (distanceFromStart + distanceFromEnd), 0.0, 1.0);\n\
s = (s * v_texcoordNormalizationAndStartEcYZ.x) + v_texcoordNormalizationAndStartEcYZ.y;\n\
float t = (widthwiseDistance + halfMaxWidth) / (2.0 * halfMaxWidth);\n\
czm_materialInput materialInput;\n\
materialInput.s = s;\n\
materialInput.st = vec2(s, t);\n\
materialInput.str = vec3(s, t, 0.0);\n\
czm_material material = czm_getMaterial(materialInput);\n\
gl_FragColor = vec4(material.diffuse + material.emission, material.alpha);\n\
#endif // PER_INSTANCE_COLOR\n\
gl_FragColor.rgb *= gl_FragColor.a;\n\
czm_writeDepthClamp();\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var PolylineShadowVolumeMorphFS = "varying vec3 v_forwardDirectionEC;\n\
varying vec3 v_texcoordNormalizationAndHalfWidth;\n\
varying float v_batchId;\n\
#ifdef PER_INSTANCE_COLOR\n\
varying vec4 v_color;\n\
#else\n\
varying vec2 v_alignedPlaneDistances;\n\
varying float v_texcoordT;\n\
#endif\n\
float rayPlaneDistanceUnsafe(vec3 origin, vec3 direction, vec3 planeNormal, float planeDistance) {\n\
return (-planeDistance - dot(planeNormal, origin)) / dot(planeNormal, direction);\n\
}\n\
void main(void)\n\
{\n\
vec4 eyeCoordinate = gl_FragCoord;\n\
eyeCoordinate /= eyeCoordinate.w;\n\
#ifdef PER_INSTANCE_COLOR\n\
gl_FragColor = czm_gammaCorrect(v_color);\n\
#else // PER_INSTANCE_COLOR\n\
float distanceFromStart = rayPlaneDistanceUnsafe(eyeCoordinate.xyz, -v_forwardDirectionEC, v_forwardDirectionEC.xyz, v_alignedPlaneDistances.x);\n\
float distanceFromEnd = rayPlaneDistanceUnsafe(eyeCoordinate.xyz, v_forwardDirectionEC, -v_forwardDirectionEC.xyz, v_alignedPlaneDistances.y);\n\
distanceFromStart = max(0.0, distanceFromStart);\n\
distanceFromEnd = max(0.0, distanceFromEnd);\n\
float s = distanceFromStart / (distanceFromStart + distanceFromEnd);\n\
s = (s * v_texcoordNormalizationAndHalfWidth.x) + v_texcoordNormalizationAndHalfWidth.y;\n\
czm_materialInput materialInput;\n\
materialInput.s = s;\n\
materialInput.st = vec2(s, v_texcoordT);\n\
materialInput.str = vec3(s, v_texcoordT, 0.0);\n\
czm_material material = czm_getMaterial(materialInput);\n\
gl_FragColor = vec4(material.diffuse + material.emission, material.alpha);\n\
#endif // PER_INSTANCE_COLOR\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var PolylineShadowVolumeMorphVS = "attribute vec3 position3DHigh;\n\
attribute vec3 position3DLow;\n\
attribute vec4 startHiAndForwardOffsetX;\n\
attribute vec4 startLoAndForwardOffsetY;\n\
attribute vec4 startNormalAndForwardOffsetZ;\n\
attribute vec4 endNormalAndTextureCoordinateNormalizationX;\n\
attribute vec4 rightNormalAndTextureCoordinateNormalizationY;\n\
attribute vec4 startHiLo2D;\n\
attribute vec4 offsetAndRight2D;\n\
attribute vec4 startEndNormals2D;\n\
attribute vec2 texcoordNormalization2D;\n\
attribute float batchId;\n\
varying vec3 v_forwardDirectionEC;\n\
varying vec3 v_texcoordNormalizationAndHalfWidth;\n\
varying float v_batchId;\n\
#ifdef WIDTH_VARYING\n\
varying float v_width;\n\
#endif\n\
#ifdef ANGLE_VARYING\n\
varying float v_polylineAngle;\n\
#endif\n\
#ifdef PER_INSTANCE_COLOR\n\
varying vec4 v_color;\n\
#else\n\
varying vec2 v_alignedPlaneDistances;\n\
varying float v_texcoordT;\n\
#endif\n\
void main()\n\
{\n\
v_batchId = batchId;\n\
vec4 posRelativeToEye2D = czm_translateRelativeToEye(vec3(0.0, startHiLo2D.xy), vec3(0.0, startHiLo2D.zw));\n\
vec4 posRelativeToEye3D = czm_translateRelativeToEye(startHiAndForwardOffsetX.xyz, startLoAndForwardOffsetY.xyz);\n\
vec4 posRelativeToEye = czm_columbusViewMorph(posRelativeToEye2D, posRelativeToEye3D, czm_morphTime);\n\
vec3 posEc2D = (czm_modelViewRelativeToEye * posRelativeToEye2D).xyz;\n\
vec3 posEc3D = (czm_modelViewRelativeToEye * posRelativeToEye3D).xyz;\n\
vec3 startEC = (czm_modelViewRelativeToEye * posRelativeToEye).xyz;\n\
vec4 startPlane2D;\n\
vec4 startPlane3D;\n\
startPlane2D.xyz = czm_normal * vec3(0.0, startEndNormals2D.xy);\n\
startPlane3D.xyz = czm_normal * startNormalAndForwardOffsetZ.xyz;\n\
startPlane2D.w = -dot(startPlane2D.xyz, posEc2D);\n\
startPlane3D.w = -dot(startPlane3D.xyz, posEc3D);\n\
vec4 rightPlane2D;\n\
vec4 rightPlane3D;\n\
rightPlane2D.xyz = czm_normal * vec3(0.0, offsetAndRight2D.zw);\n\
rightPlane3D.xyz = czm_normal * rightNormalAndTextureCoordinateNormalizationY.xyz;\n\
rightPlane2D.w = -dot(rightPlane2D.xyz, posEc2D);\n\
rightPlane3D.w = -dot(rightPlane3D.xyz, posEc3D);\n\
posRelativeToEye2D = posRelativeToEye2D + vec4(0.0, offsetAndRight2D.xy, 0.0);\n\
posRelativeToEye3D = posRelativeToEye3D + vec4(startHiAndForwardOffsetX.w, startLoAndForwardOffsetY.w, startNormalAndForwardOffsetZ.w, 0.0);\n\
posRelativeToEye = czm_columbusViewMorph(posRelativeToEye2D, posRelativeToEye3D, czm_morphTime);\n\
posEc2D = (czm_modelViewRelativeToEye * posRelativeToEye2D).xyz;\n\
posEc3D = (czm_modelViewRelativeToEye * posRelativeToEye3D).xyz;\n\
vec3 endEC = (czm_modelViewRelativeToEye * posRelativeToEye).xyz;\n\
vec3 forwardEc3D = czm_normal * normalize(vec3(startHiAndForwardOffsetX.w, startLoAndForwardOffsetY.w, startNormalAndForwardOffsetZ.w));\n\
vec3 forwardEc2D = czm_normal * normalize(vec3(0.0, offsetAndRight2D.xy));\n\
vec4 endPlane2D;\n\
vec4 endPlane3D;\n\
endPlane2D.xyz = czm_normal * vec3(0.0, startEndNormals2D.zw);\n\
endPlane3D.xyz = czm_normal * endNormalAndTextureCoordinateNormalizationX.xyz;\n\
endPlane2D.w = -dot(endPlane2D.xyz, posEc2D);\n\
endPlane3D.w = -dot(endPlane3D.xyz, posEc3D);\n\
v_forwardDirectionEC = normalize(endEC - startEC);\n\
vec2 cleanTexcoordNormalization2D;\n\
cleanTexcoordNormalization2D.x = abs(texcoordNormalization2D.x);\n\
cleanTexcoordNormalization2D.y = czm_branchFreeTernary(texcoordNormalization2D.y > 1.0, 0.0, abs(texcoordNormalization2D.y));\n\
vec2 cleanTexcoordNormalization3D;\n\
cleanTexcoordNormalization3D.x = abs(endNormalAndTextureCoordinateNormalizationX.w);\n\
cleanTexcoordNormalization3D.y = rightNormalAndTextureCoordinateNormalizationY.w;\n\
cleanTexcoordNormalization3D.y = czm_branchFreeTernary(cleanTexcoordNormalization3D.y > 1.0, 0.0, abs(cleanTexcoordNormalization3D.y));\n\
v_texcoordNormalizationAndHalfWidth.xy = mix(cleanTexcoordNormalization2D, cleanTexcoordNormalization3D, czm_morphTime);\n\
#ifdef PER_INSTANCE_COLOR\n\
v_color = czm_batchTable_color(batchId);\n\
#else // PER_INSTANCE_COLOR\n\
v_alignedPlaneDistances.x = -dot(v_forwardDirectionEC, startEC);\n\
v_alignedPlaneDistances.y = -dot(-v_forwardDirectionEC, endEC);\n\
#endif // PER_INSTANCE_COLOR\n\
#ifdef WIDTH_VARYING\n\
float width = czm_batchTable_width(batchId);\n\
float halfWidth = width * 0.5;\n\
v_width = width;\n\
v_texcoordNormalizationAndHalfWidth.z = halfWidth;\n\
#else\n\
float halfWidth = 0.5 * czm_batchTable_width(batchId);\n\
v_texcoordNormalizationAndHalfWidth.z = halfWidth;\n\
#endif\n\
vec4 positionEc3D = czm_modelViewRelativeToEye * czm_translateRelativeToEye(position3DHigh, position3DLow);\n\
float absStartPlaneDistance = abs(czm_planeDistance(startPlane3D, positionEc3D.xyz));\n\
float absEndPlaneDistance = abs(czm_planeDistance(endPlane3D, positionEc3D.xyz));\n\
vec3 planeDirection = czm_branchFreeTernary(absStartPlaneDistance < absEndPlaneDistance, startPlane3D.xyz, endPlane3D.xyz);\n\
vec3 upOrDown = normalize(cross(rightPlane3D.xyz, planeDirection));\n\
vec3 normalEC = normalize(cross(planeDirection, upOrDown));\n\
vec3 geodeticSurfaceNormal = normalize(cross(normalEC, forwardEc3D));\n\
geodeticSurfaceNormal *= float(0.0 <= rightNormalAndTextureCoordinateNormalizationY.w && rightNormalAndTextureCoordinateNormalizationY.w <= 1.0);\n\
geodeticSurfaceNormal *= MAX_TERRAIN_HEIGHT;\n\
positionEc3D.xyz += geodeticSurfaceNormal;\n\
normalEC *= sign(endNormalAndTextureCoordinateNormalizationX.w);\n\
positionEc3D.xyz += halfWidth * max(0.0, czm_metersPerPixel(positionEc3D)) * normalEC;\n\
vec4 positionEc2D = czm_modelViewRelativeToEye * czm_translateRelativeToEye(position2DHigh.zxy, position2DLow.zxy);\n\
absStartPlaneDistance = abs(czm_planeDistance(startPlane2D, positionEc2D.xyz));\n\
absEndPlaneDistance = abs(czm_planeDistance(endPlane2D, positionEc2D.xyz));\n\
planeDirection = czm_branchFreeTernary(absStartPlaneDistance < absEndPlaneDistance, startPlane2D.xyz, endPlane2D.xyz);\n\
upOrDown = normalize(cross(rightPlane2D.xyz, planeDirection));\n\
normalEC = normalize(cross(planeDirection, upOrDown));\n\
geodeticSurfaceNormal = normalize(cross(normalEC, forwardEc2D));\n\
geodeticSurfaceNormal *= float(0.0 <= texcoordNormalization2D.y && texcoordNormalization2D.y <= 1.0);\n\
geodeticSurfaceNormal *= MAX_TERRAIN_HEIGHT;\n\
positionEc2D.xyz += geodeticSurfaceNormal;\n\
normalEC *= sign(texcoordNormalization2D.x);\n\
#ifndef PER_INSTANCE_COLOR\n\
v_texcoordT = clamp(sign(texcoordNormalization2D.x), 0.0, 1.0);\n\
#endif\n\
positionEc2D.xyz += halfWidth * max(0.0, czm_metersPerPixel(positionEc2D)) * normalEC;\n\
gl_Position = czm_projection * mix(positionEc2D, positionEc3D, czm_morphTime);\n\
#ifdef ANGLE_VARYING\n\
vec2 approxLineDirection = normalize(vec2(v_forwardDirectionEC.x, -v_forwardDirectionEC.y));\n\
approxLineDirection.y = czm_branchFreeTernary(approxLineDirection.x == 0.0 && approxLineDirection.y == 0.0, -1.0, approxLineDirection.y);\n\
v_polylineAngle = czm_fastApproximateAtan(approxLineDirection.x, approxLineDirection.y);\n\
#endif\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var PolylineShadowVolumeVS = "attribute vec3 position3DHigh;\n\
attribute vec3 position3DLow;\n\
#ifndef COLUMBUS_VIEW_2D\n\
attribute vec4 startHiAndForwardOffsetX;\n\
attribute vec4 startLoAndForwardOffsetY;\n\
attribute vec4 startNormalAndForwardOffsetZ;\n\
attribute vec4 endNormalAndTextureCoordinateNormalizationX;\n\
attribute vec4 rightNormalAndTextureCoordinateNormalizationY;\n\
#else\n\
attribute vec4 startHiLo2D;\n\
attribute vec4 offsetAndRight2D;\n\
attribute vec4 startEndNormals2D;\n\
attribute vec2 texcoordNormalization2D;\n\
#endif\n\
attribute float batchId;\n\
varying vec4 v_startPlaneNormalEcAndHalfWidth;\n\
varying vec4 v_endPlaneNormalEcAndBatchId;\n\
varying vec4 v_rightPlaneEC;\n\
varying vec4 v_endEcAndStartEcX;\n\
varying vec4 v_texcoordNormalizationAndStartEcYZ;\n\
#ifdef WIDTH_VARYING\n\
varying float v_width;\n\
#endif\n\
#ifdef ANGLE_VARYING\n\
varying float v_polylineAngle;\n\
#endif\n\
#ifdef PER_INSTANCE_COLOR\n\
varying vec4 v_color;\n\
#endif\n\
void main()\n\
{\n\
#ifdef COLUMBUS_VIEW_2D\n\
vec3 ecStart = (czm_modelViewRelativeToEye * czm_translateRelativeToEye(vec3(0.0, startHiLo2D.xy), vec3(0.0, startHiLo2D.zw))).xyz;\n\
vec3 forwardDirectionEC = czm_normal * vec3(0.0, offsetAndRight2D.xy);\n\
vec3 ecEnd = forwardDirectionEC + ecStart;\n\
forwardDirectionEC = normalize(forwardDirectionEC);\n\
v_rightPlaneEC.xyz = czm_normal * vec3(0.0, offsetAndRight2D.zw);\n\
v_rightPlaneEC.w = -dot(v_rightPlaneEC.xyz, ecStart);\n\
vec4 startPlaneEC;\n\
startPlaneEC.xyz =  czm_normal * vec3(0.0, startEndNormals2D.xy);\n\
startPlaneEC.w = -dot(startPlaneEC.xyz, ecStart);\n\
vec4 endPlaneEC;\n\
endPlaneEC.xyz =  czm_normal * vec3(0.0, startEndNormals2D.zw);\n\
endPlaneEC.w = -dot(endPlaneEC.xyz, ecEnd);\n\
v_texcoordNormalizationAndStartEcYZ.x = abs(texcoordNormalization2D.x);\n\
v_texcoordNormalizationAndStartEcYZ.y = texcoordNormalization2D.y;\n\
#else // COLUMBUS_VIEW_2D\n\
vec3 ecStart = (czm_modelViewRelativeToEye * czm_translateRelativeToEye(startHiAndForwardOffsetX.xyz, startLoAndForwardOffsetY.xyz)).xyz;\n\
vec3 offset = czm_normal * vec3(startHiAndForwardOffsetX.w, startLoAndForwardOffsetY.w, startNormalAndForwardOffsetZ.w);\n\
vec3 ecEnd = ecStart + offset;\n\
vec3 forwardDirectionEC = normalize(offset);\n\
vec4 startPlaneEC;\n\
startPlaneEC.xyz = czm_normal * startNormalAndForwardOffsetZ.xyz;\n\
startPlaneEC.w = -dot(startPlaneEC.xyz, ecStart);\n\
vec4 endPlaneEC;\n\
endPlaneEC.xyz = czm_normal * endNormalAndTextureCoordinateNormalizationX.xyz;\n\
endPlaneEC.w = -dot(endPlaneEC.xyz, ecEnd);\n\
v_rightPlaneEC.xyz = czm_normal * rightNormalAndTextureCoordinateNormalizationY.xyz;\n\
v_rightPlaneEC.w = -dot(v_rightPlaneEC.xyz, ecStart);\n\
v_texcoordNormalizationAndStartEcYZ.x = abs(endNormalAndTextureCoordinateNormalizationX.w);\n\
v_texcoordNormalizationAndStartEcYZ.y = rightNormalAndTextureCoordinateNormalizationY.w;\n\
#endif // COLUMBUS_VIEW_2D\n\
v_endEcAndStartEcX.xyz = ecEnd;\n\
v_endEcAndStartEcX.w = ecStart.x;\n\
v_texcoordNormalizationAndStartEcYZ.zw = ecStart.yz;\n\
#ifdef PER_INSTANCE_COLOR\n\
v_color = czm_batchTable_color(batchId);\n\
#endif // PER_INSTANCE_COLOR\n\
vec4 positionRelativeToEye = czm_computePosition();\n\
vec4 positionEC = czm_modelViewRelativeToEye * positionRelativeToEye;\n\
float absStartPlaneDistance = abs(czm_planeDistance(startPlaneEC, positionEC.xyz));\n\
float absEndPlaneDistance = abs(czm_planeDistance(endPlaneEC, positionEC.xyz));\n\
vec3 planeDirection = czm_branchFreeTernary(absStartPlaneDistance < absEndPlaneDistance, startPlaneEC.xyz, endPlaneEC.xyz);\n\
vec3 upOrDown = normalize(cross(v_rightPlaneEC.xyz, planeDirection));\n\
vec3 normalEC = normalize(cross(planeDirection, upOrDown));\n\
upOrDown = cross(forwardDirectionEC, normalEC);\n\
upOrDown = float(czm_sceneMode == czm_sceneMode3D) * upOrDown;\n\
upOrDown = float(v_texcoordNormalizationAndStartEcYZ.y > 1.0 || v_texcoordNormalizationAndStartEcYZ.y < 0.0) * upOrDown;\n\
upOrDown = min(GLOBE_MINIMUM_ALTITUDE, czm_geometricToleranceOverMeter * length(positionRelativeToEye.xyz)) * upOrDown;\n\
positionEC.xyz += upOrDown;\n\
v_texcoordNormalizationAndStartEcYZ.y = czm_branchFreeTernary(v_texcoordNormalizationAndStartEcYZ.y > 1.0, 0.0, abs(v_texcoordNormalizationAndStartEcYZ.y));\n\
float width = czm_batchTable_width(batchId);\n\
#ifdef WIDTH_VARYING\n\
v_width = width;\n\
#endif\n\
v_startPlaneNormalEcAndHalfWidth.xyz = startPlaneEC.xyz;\n\
v_startPlaneNormalEcAndHalfWidth.w = width * 0.5;\n\
v_endPlaneNormalEcAndBatchId.xyz = endPlaneEC.xyz;\n\
v_endPlaneNormalEcAndBatchId.w = batchId;\n\
width = width * max(0.0, czm_metersPerPixel(positionEC));\n\
width = width / dot(normalEC, v_rightPlaneEC.xyz);\n\
#ifdef COLUMBUS_VIEW_2D\n\
normalEC *= sign(texcoordNormalization2D.x);\n\
#else\n\
normalEC *= sign(endNormalAndTextureCoordinateNormalizationX.w);\n\
#endif\n\
positionEC.xyz += width * normalEC;\n\
gl_Position = czm_depthClamp(czm_projection * positionEC);\n\
#ifdef ANGLE_VARYING\n\
vec2 approxLineDirection = normalize(vec2(forwardDirectionEC.x, -forwardDirectionEC.y));\n\
approxLineDirection.y = czm_branchFreeTernary(approxLineDirection.x == 0.0 && approxLineDirection.y == 0.0, -1.0, approxLineDirection.y);\n\
v_polylineAngle = czm_fastApproximateAtan(approxLineDirection.x, approxLineDirection.y);\n\
#endif\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var PolylineColorAppearanceVS = "attribute vec3 position3DHigh;\n\
attribute vec3 position3DLow;\n\
attribute vec3 prevPosition3DHigh;\n\
attribute vec3 prevPosition3DLow;\n\
attribute vec3 nextPosition3DHigh;\n\
attribute vec3 nextPosition3DLow;\n\
attribute vec2 expandAndWidth;\n\
attribute vec4 color;\n\
attribute float batchId;\n\
varying vec4 v_color;\n\
void main()\n\
{\n\
float expandDir = expandAndWidth.x;\n\
float width = abs(expandAndWidth.y) + 0.5;\n\
bool usePrev = expandAndWidth.y < 0.0;\n\
vec4 p = czm_computePosition();\n\
vec4 prev = czm_computePrevPosition();\n\
vec4 next = czm_computeNextPosition();\n\
float angle;\n\
vec4 positionWC = getPolylineWindowCoordinates(p, prev, next, expandDir, width, usePrev, angle);\n\
gl_Position = czm_viewportOrthographic * positionWC;\n\
v_color = color;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var PolylineCommon = "void clipLineSegmentToNearPlane(\n\
vec3 p0,\n\
vec3 p1,\n\
out vec4 positionWC,\n\
out bool clipped,\n\
out bool culledByNearPlane,\n\
out vec4 clippedPositionEC)\n\
{\n\
culledByNearPlane = false;\n\
clipped = false;\n\
vec3 p0ToP1 = p1 - p0;\n\
float magnitude = length(p0ToP1);\n\
vec3 direction = normalize(p0ToP1);\n\
float endPoint0Distance =  czm_currentFrustum.x + p0.z;\n\
float denominator = -direction.z;\n\
if (endPoint0Distance > 0.0 && abs(denominator) < czm_epsilon7)\n\
{\n\
culledByNearPlane = true;\n\
}\n\
else if (endPoint0Distance > 0.0)\n\
{\n\
float t = endPoint0Distance / denominator;\n\
if (t < 0.0 || t > magnitude)\n\
{\n\
culledByNearPlane = true;\n\
}\n\
else\n\
{\n\
p0 = p0 + t * direction;\n\
p0.z = min(p0.z, -czm_currentFrustum.x);\n\
clipped = true;\n\
}\n\
}\n\
clippedPositionEC = vec4(p0, 1.0);\n\
positionWC = czm_eyeToWindowCoordinates(clippedPositionEC);\n\
}\n\
vec4 getPolylineWindowCoordinatesEC(vec4 positionEC, vec4 prevEC, vec4 nextEC, float expandDirection, float width, bool usePrevious, out float angle)\n\
{\n\
#ifdef POLYLINE_DASH\n\
vec4 positionWindow = czm_eyeToWindowCoordinates(positionEC);\n\
vec4 previousWindow = czm_eyeToWindowCoordinates(prevEC);\n\
vec4 nextWindow = czm_eyeToWindowCoordinates(nextEC);\n\
vec2 lineDir;\n\
if (usePrevious) {\n\
lineDir = normalize(positionWindow.xy - previousWindow.xy);\n\
}\n\
else {\n\
lineDir = normalize(nextWindow.xy - positionWindow.xy);\n\
}\n\
angle = atan(lineDir.x, lineDir.y) - 1.570796327;\n\
angle = floor(angle / czm_piOverFour + 0.5) * czm_piOverFour;\n\
#endif\n\
vec4 clippedPrevWC, clippedPrevEC;\n\
bool prevSegmentClipped, prevSegmentCulled;\n\
clipLineSegmentToNearPlane(prevEC.xyz, positionEC.xyz, clippedPrevWC, prevSegmentClipped, prevSegmentCulled, clippedPrevEC);\n\
vec4 clippedNextWC, clippedNextEC;\n\
bool nextSegmentClipped, nextSegmentCulled;\n\
clipLineSegmentToNearPlane(nextEC.xyz, positionEC.xyz, clippedNextWC, nextSegmentClipped, nextSegmentCulled, clippedNextEC);\n\
bool segmentClipped, segmentCulled;\n\
vec4 clippedPositionWC, clippedPositionEC;\n\
clipLineSegmentToNearPlane(positionEC.xyz, usePrevious ? prevEC.xyz : nextEC.xyz, clippedPositionWC, segmentClipped, segmentCulled, clippedPositionEC);\n\
if (segmentCulled)\n\
{\n\
return vec4(0.0, 0.0, 0.0, 1.0);\n\
}\n\
vec2 directionToPrevWC = normalize(clippedPrevWC.xy - clippedPositionWC.xy);\n\
vec2 directionToNextWC = normalize(clippedNextWC.xy - clippedPositionWC.xy);\n\
if (prevSegmentCulled)\n\
{\n\
directionToPrevWC = -directionToNextWC;\n\
}\n\
else if (nextSegmentCulled)\n\
{\n\
directionToNextWC = -directionToPrevWC;\n\
}\n\
vec2 thisSegmentForwardWC, otherSegmentForwardWC;\n\
if (usePrevious)\n\
{\n\
thisSegmentForwardWC = -directionToPrevWC;\n\
otherSegmentForwardWC = directionToNextWC;\n\
}\n\
else\n\
{\n\
thisSegmentForwardWC = directionToNextWC;\n\
otherSegmentForwardWC =  -directionToPrevWC;\n\
}\n\
vec2 thisSegmentLeftWC = vec2(-thisSegmentForwardWC.y, thisSegmentForwardWC.x);\n\
vec2 leftWC = thisSegmentLeftWC;\n\
float expandWidth = width * 0.5;\n\
if (!czm_equalsEpsilon(prevEC.xyz - positionEC.xyz, vec3(0.0), czm_epsilon1) && !czm_equalsEpsilon(nextEC.xyz - positionEC.xyz, vec3(0.0), czm_epsilon1))\n\
{\n\
vec2 otherSegmentLeftWC = vec2(-otherSegmentForwardWC.y, otherSegmentForwardWC.x);\n\
vec2 leftSumWC = thisSegmentLeftWC + otherSegmentLeftWC;\n\
float leftSumLength = length(leftSumWC);\n\
leftWC = leftSumLength < czm_epsilon6 ? thisSegmentLeftWC : (leftSumWC / leftSumLength);\n\
vec2 u = -thisSegmentForwardWC;\n\
vec2 v = leftWC;\n\
float sinAngle = abs(u.x * v.y - u.y * v.x);\n\
expandWidth = clamp(expandWidth / sinAngle, 0.0, width * 2.0);\n\
}\n\
vec2 offset = leftWC * expandDirection * expandWidth * czm_pixelRatio;\n\
return vec4(clippedPositionWC.xy + offset, -clippedPositionWC.z, 1.0) * (czm_projection * clippedPositionEC).w;\n\
}\n\
vec4 getPolylineWindowCoordinates(vec4 position, vec4 previous, vec4 next, float expandDirection, float width, bool usePrevious, out float angle)\n\
{\n\
vec4 positionEC = czm_modelViewRelativeToEye * position;\n\
vec4 prevEC = czm_modelViewRelativeToEye * previous;\n\
vec4 nextEC = czm_modelViewRelativeToEye * next;\n\
return getPolylineWindowCoordinatesEC(positionEC, prevEC, nextEC, expandDirection, width, usePrevious, angle);\n\
}\n\
";

  let defaultVertexShaderSource$1 = `${PolylineCommon}\n${PolylineColorAppearanceVS}`;
  const defaultFragmentShaderSource$1 = PerInstanceFlatColorAppearanceFS;

  if (!FeatureDetection.isInternetExplorer()) {
    defaultVertexShaderSource$1 = `#define CLIP_POLYLINE \n${defaultVertexShaderSource$1}`;
  }

  /**
   * An appearance for {@link GeometryInstance} instances with color attributes and
   * {@link PolylineGeometry} or {@link GroundPolylineGeometry}.
   * This allows several geometry instances, each with a different color, to
   * be drawn with the same {@link Primitive}.
   *
   * @alias PolylineColorAppearance
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Boolean} [options.translucent=true] When <code>true</code>, the geometry is expected to appear translucent so {@link PolylineColorAppearance#renderState} has alpha blending enabled.
   * @param {String} [options.vertexShaderSource] Optional GLSL vertex shader source to override the default vertex shader.
   * @param {String} [options.fragmentShaderSource] Optional GLSL fragment shader source to override the default fragment shader.
   * @param {Object} [options.renderState] Optional render state to override the default render state.
   *
   * @example
   * // A solid white line segment
   * const primitive = new Cesium.Primitive({
   *   geometryInstances : new Cesium.GeometryInstance({
   *     geometry : new Cesium.PolylineGeometry({
   *       positions : Cesium.Cartesian3.fromDegreesArray([
   *         0.0, 0.0,
   *         5.0, 0.0
   *       ]),
   *       width : 10.0,
   *       vertexFormat : Cesium.PolylineColorAppearance.VERTEX_FORMAT
   *     }),
   *     attributes : {
   *       color : Cesium.ColorGeometryInstanceAttribute.fromColor(new Cesium.Color(1.0, 1.0, 1.0, 1.0))
   *     }
   *   }),
   *   appearance : new Cesium.PolylineColorAppearance({
   *     translucent : false
   *   })
   * });
   */
  function PolylineColorAppearance(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const translucent = defaultValue(options.translucent, true);
    const closed = false;
    const vertexFormat = PolylineColorAppearance.VERTEX_FORMAT;

    /**
     * This property is part of the {@link Appearance} interface, but is not
     * used by {@link PolylineColorAppearance} since a fully custom fragment shader is used.
     *
     * @type Material
     *
     * @default undefined
     */
    this.material = undefined;

    /**
     * When <code>true</code>, the geometry is expected to appear translucent so
     * {@link PolylineColorAppearance#renderState} has alpha blending enabled.
     *
     * @type {Boolean}
     *
     * @default true
     */
    this.translucent = translucent;

    this._vertexShaderSource = defaultValue(
      options.vertexShaderSource,
      defaultVertexShaderSource$1
    );
    this._fragmentShaderSource = defaultValue(
      options.fragmentShaderSource,
      defaultFragmentShaderSource$1
    );
    this._renderState = Appearance.getDefaultRenderState(
      translucent,
      closed,
      options.renderState
    );
    this._closed = closed;

    // Non-derived members

    this._vertexFormat = vertexFormat;
  }

  Object.defineProperties(PolylineColorAppearance.prototype, {
    /**
     * The GLSL source code for the vertex shader.
     *
     * @memberof PolylineColorAppearance.prototype
     *
     * @type {String}
     * @readonly
     */
    vertexShaderSource: {
      get: function () {
        return this._vertexShaderSource;
      },
    },

    /**
     * The GLSL source code for the fragment shader.
     *
     * @memberof PolylineColorAppearance.prototype
     *
     * @type {String}
     * @readonly
     */
    fragmentShaderSource: {
      get: function () {
        return this._fragmentShaderSource;
      },
    },

    /**
     * The WebGL fixed-function state to use when rendering the geometry.
     * <p>
     * The render state can be explicitly defined when constructing a {@link PolylineColorAppearance}
     * instance, or it is set implicitly via {@link PolylineColorAppearance#translucent}.
     * </p>
     *
     * @memberof PolylineColorAppearance.prototype
     *
     * @type {Object}
     * @readonly
     */
    renderState: {
      get: function () {
        return this._renderState;
      },
    },

    /**
     * When <code>true</code>, the geometry is expected to be closed so
     * {@link PolylineColorAppearance#renderState} has backface culling enabled.
     * This is always <code>false</code> for <code>PolylineColorAppearance</code>.
     *
     * @memberof PolylineColorAppearance.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default false
     */
    closed: {
      get: function () {
        return this._closed;
      },
    },

    /**
     * The {@link VertexFormat} that this appearance instance is compatible with.
     * A geometry can have more vertex attributes and still be compatible - at a
     * potential performance cost - but it can't have less.
     *
     * @memberof PolylineColorAppearance.prototype
     *
     * @type VertexFormat
     * @readonly
     *
     * @default {@link PolylineColorAppearance.VERTEX_FORMAT}
     */
    vertexFormat: {
      get: function () {
        return this._vertexFormat;
      },
    },
  });

  /**
   * The {@link VertexFormat} that all {@link PolylineColorAppearance} instances
   * are compatible with. This requires only a <code>position</code> attribute.
   *
   * @type VertexFormat
   *
   * @constant
   */
  PolylineColorAppearance.VERTEX_FORMAT = VertexFormat.POSITION_ONLY;

  /**
   * Procedurally creates the full GLSL fragment shader source.
   *
   * @function
   *
   * @returns {String} The full GLSL fragment shader source.
   */
  PolylineColorAppearance.prototype.getFragmentShaderSource =
    Appearance.prototype.getFragmentShaderSource;

  /**
   * Determines if the geometry is translucent based on {@link PolylineColorAppearance#translucent}.
   *
   * @function
   *
   * @returns {Boolean} <code>true</code> if the appearance is translucent.
   */
  PolylineColorAppearance.prototype.isTranslucent =
    Appearance.prototype.isTranslucent;

  /**
   * Creates a render state.  This is not the final render state instance; instead,
   * it can contain a subset of render state properties identical to the render state
   * created in the context.
   *
   * @function
   *
   * @returns {Object} The render state.
   */
  PolylineColorAppearance.prototype.getRenderState =
    Appearance.prototype.getRenderState;

  //This file is automatically rebuilt by the Cesium build process.
  var PolylineMaterialAppearanceVS = "attribute vec3 position3DHigh;\n\
attribute vec3 position3DLow;\n\
attribute vec3 prevPosition3DHigh;\n\
attribute vec3 prevPosition3DLow;\n\
attribute vec3 nextPosition3DHigh;\n\
attribute vec3 nextPosition3DLow;\n\
attribute vec2 expandAndWidth;\n\
attribute vec2 st;\n\
attribute float batchId;\n\
varying float v_width;\n\
varying vec2 v_st;\n\
varying float v_polylineAngle;\n\
void main()\n\
{\n\
float expandDir = expandAndWidth.x;\n\
float width = abs(expandAndWidth.y) + 0.5;\n\
bool usePrev = expandAndWidth.y < 0.0;\n\
vec4 p = czm_computePosition();\n\
vec4 prev = czm_computePrevPosition();\n\
vec4 next = czm_computeNextPosition();\n\
float angle;\n\
vec4 positionWC = getPolylineWindowCoordinates(p, prev, next, expandDir, width, usePrev, angle);\n\
gl_Position = czm_viewportOrthographic * positionWC;\n\
v_width = width;\n\
v_st.s = st.s;\n\
v_st.t = czm_writeNonPerspective(st.t, gl_Position.w);\n\
v_polylineAngle = angle;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var PolylineFS$1 = "#ifdef VECTOR_TILE\n\
uniform vec4 u_highlightColor;\n\
#endif\n\
varying vec2 v_st;\n\
void main()\n\
{\n\
czm_materialInput materialInput;\n\
vec2 st = v_st;\n\
st.t = czm_readNonPerspective(st.t, gl_FragCoord.w);\n\
materialInput.s = st.s;\n\
materialInput.st = st;\n\
materialInput.str = vec3(st, 0.0);\n\
czm_material material = czm_getMaterial(materialInput);\n\
gl_FragColor = vec4(material.diffuse + material.emission, material.alpha);\n\
#ifdef VECTOR_TILE\n\
gl_FragColor *= u_highlightColor;\n\
#endif\n\
czm_writeLogDepth();\n\
}\n\
";

  let defaultVertexShaderSource = `${PolylineCommon}\n${PolylineMaterialAppearanceVS}`;
  const defaultFragmentShaderSource = PolylineFS$1;

  if (!FeatureDetection.isInternetExplorer()) {
    defaultVertexShaderSource = `#define CLIP_POLYLINE \n${defaultVertexShaderSource}`;
  }

  /**
   * An appearance for {@link PolylineGeometry} that supports shading with materials.
   *
   * @alias PolylineMaterialAppearance
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Boolean} [options.translucent=true] When <code>true</code>, the geometry is expected to appear translucent so {@link PolylineMaterialAppearance#renderState} has alpha blending enabled.
   * @param {Material} [options.material=Material.ColorType] The material used to determine the fragment color.
   * @param {String} [options.vertexShaderSource] Optional GLSL vertex shader source to override the default vertex shader.
   * @param {String} [options.fragmentShaderSource] Optional GLSL fragment shader source to override the default fragment shader.
   * @param {Object} [options.renderState] Optional render state to override the default render state.
   *
   * @see {@link https://github.com/CesiumGS/cesium/wiki/Fabric|Fabric}
   *
   * @example
   * const primitive = new Cesium.Primitive({
   *   geometryInstances : new Cesium.GeometryInstance({
   *     geometry : new Cesium.PolylineGeometry({
   *       positions : Cesium.Cartesian3.fromDegreesArray([
   *         0.0, 0.0,
   *         5.0, 0.0
   *       ]),
   *       width : 10.0,
   *       vertexFormat : Cesium.PolylineMaterialAppearance.VERTEX_FORMAT
   *     })
   *   }),
   *   appearance : new Cesium.PolylineMaterialAppearance({
   *     material : Cesium.Material.fromType('Color')
   *   })
   * });
   */
  function PolylineMaterialAppearance(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const translucent = defaultValue(options.translucent, true);
    const closed = false;
    const vertexFormat = PolylineMaterialAppearance.VERTEX_FORMAT;

    /**
     * The material used to determine the fragment color.  Unlike other {@link PolylineMaterialAppearance}
     * properties, this is not read-only, so an appearance's material can change on the fly.
     *
     * @type Material
     *
     * @default {@link Material.ColorType}
     *
     * @see {@link https://github.com/CesiumGS/cesium/wiki/Fabric|Fabric}
     */
    this.material = defined(options.material)
      ? options.material
      : Material$4.fromType(Material$4.ColorType);

    /**
     * When <code>true</code>, the geometry is expected to appear translucent so
     * {@link PolylineMaterialAppearance#renderState} has alpha blending enabled.
     *
     * @type {Boolean}
     *
     * @default true
     */
    this.translucent = translucent;

    this._vertexShaderSource = defaultValue(
      options.vertexShaderSource,
      defaultVertexShaderSource
    );
    this._fragmentShaderSource = defaultValue(
      options.fragmentShaderSource,
      defaultFragmentShaderSource
    );
    this._renderState = Appearance.getDefaultRenderState(
      translucent,
      closed,
      options.renderState
    );
    this._closed = closed;

    // Non-derived members

    this._vertexFormat = vertexFormat;
  }

  Object.defineProperties(PolylineMaterialAppearance.prototype, {
    /**
     * The GLSL source code for the vertex shader.
     *
     * @memberof PolylineMaterialAppearance.prototype
     *
     * @type {String}
     * @readonly
     */
    vertexShaderSource: {
      get: function () {
        let vs = this._vertexShaderSource;
        if (
          this.material.shaderSource.search(
            /varying\s+float\s+v_polylineAngle;/g
          ) !== -1
        ) {
          vs = `#define POLYLINE_DASH\n${vs}`;
        }
        return vs;
      },
    },

    /**
     * The GLSL source code for the fragment shader.
     *
     * @memberof PolylineMaterialAppearance.prototype
     *
     * @type {String}
     * @readonly
     */
    fragmentShaderSource: {
      get: function () {
        return this._fragmentShaderSource;
      },
    },

    /**
     * The WebGL fixed-function state to use when rendering the geometry.
     * <p>
     * The render state can be explicitly defined when constructing a {@link PolylineMaterialAppearance}
     * instance, or it is set implicitly via {@link PolylineMaterialAppearance#translucent}
     * and {@link PolylineMaterialAppearance#closed}.
     * </p>
     *
     * @memberof PolylineMaterialAppearance.prototype
     *
     * @type {Object}
     * @readonly
     */
    renderState: {
      get: function () {
        return this._renderState;
      },
    },

    /**
     * When <code>true</code>, the geometry is expected to be closed so
     * {@link PolylineMaterialAppearance#renderState} has backface culling enabled.
     * This is always <code>false</code> for <code>PolylineMaterialAppearance</code>.
     *
     * @memberof PolylineMaterialAppearance.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default false
     */
    closed: {
      get: function () {
        return this._closed;
      },
    },

    /**
     * The {@link VertexFormat} that this appearance instance is compatible with.
     * A geometry can have more vertex attributes and still be compatible - at a
     * potential performance cost - but it can't have less.
     *
     * @memberof PolylineMaterialAppearance.prototype
     *
     * @type VertexFormat
     * @readonly
     *
     * @default {@link PolylineMaterialAppearance.VERTEX_FORMAT}
     */
    vertexFormat: {
      get: function () {
        return this._vertexFormat;
      },
    },
  });

  /**
   * The {@link VertexFormat} that all {@link PolylineMaterialAppearance} instances
   * are compatible with. This requires <code>position</code> and <code>st</code> attributes.
   *
   * @type VertexFormat
   *
   * @constant
   */
  PolylineMaterialAppearance.VERTEX_FORMAT = VertexFormat.POSITION_AND_ST;

  /**
   * Procedurally creates the full GLSL fragment shader source.  For {@link PolylineMaterialAppearance},
   * this is derived from {@link PolylineMaterialAppearance#fragmentShaderSource} and {@link PolylineMaterialAppearance#material}.
   *
   * @function
   *
   * @returns {String} The full GLSL fragment shader source.
   */
  PolylineMaterialAppearance.prototype.getFragmentShaderSource =
    Appearance.prototype.getFragmentShaderSource;

  /**
   * Determines if the geometry is translucent based on {@link PolylineMaterialAppearance#translucent} and {@link Material#isTranslucent}.
   *
   * @function
   *
   * @returns {Boolean} <code>true</code> if the appearance is translucent.
   */
  PolylineMaterialAppearance.prototype.isTranslucent =
    Appearance.prototype.isTranslucent;

  /**
   * Creates a render state.  This is not the final render state instance; instead,
   * it can contain a subset of render state properties identical to the render state
   * created in the context.
   *
   * @function
   *
   * @returns {Object} The render state.
   */
  PolylineMaterialAppearance.prototype.getRenderState =
    Appearance.prototype.getRenderState;

  /**
   * A GroundPolylinePrimitive represents a polyline draped over the terrain or 3D Tiles in the {@link Scene}.
   * <p>
   * Only to be used with GeometryInstances containing {@link GroundPolylineGeometry}.
   * </p>
   *
   * @alias GroundPolylinePrimitive
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Array|GeometryInstance} [options.geometryInstances] GeometryInstances containing GroundPolylineGeometry
   * @param {Appearance} [options.appearance] The Appearance used to render the polyline. Defaults to a white color {@link Material} on a {@link PolylineMaterialAppearance}.
   * @param {Boolean} [options.show=true] Determines if this primitive will be shown.
   * @param {Boolean} [options.interleave=false] When <code>true</code>, geometry vertex attributes are interleaved, which can slightly improve rendering performance but increases load time.
   * @param {Boolean} [options.releaseGeometryInstances=true] When <code>true</code>, the primitive does not keep a reference to the input <code>geometryInstances</code> to save memory.
   * @param {Boolean} [options.allowPicking=true] When <code>true</code>, each geometry instance will only be pickable with {@link Scene#pick}.  When <code>false</code>, GPU memory is saved.
   * @param {Boolean} [options.asynchronous=true] Determines if the primitive will be created asynchronously or block until ready. If false initializeTerrainHeights() must be called first.
   * @param {ClassificationType} [options.classificationType=ClassificationType.BOTH] Determines whether terrain, 3D Tiles or both will be classified.
   * @param {Boolean} [options.debugShowBoundingVolume=false] For debugging only. Determines if this primitive's commands' bounding spheres are shown.
   * @param {Boolean} [options.debugShowShadowVolume=false] For debugging only. Determines if the shadow volume for each geometry in the primitive is drawn. Must be <code>true</code> on creation to have effect.
   *
   * @example
   * // 1. Draw a polyline on terrain with a basic color material
   *
   * const instance = new Cesium.GeometryInstance({
   *   geometry : new Cesium.GroundPolylineGeometry({
   *      positions : Cesium.Cartesian3.fromDegreesArray([
   *          -112.1340164450331, 36.05494287836128,
   *          -112.08821010582645, 36.097804071380715
   *      ]),
   *      width : 4.0
   *   }),
   *   id : 'object returned when this instance is picked and to get/set per-instance attributes'
   * });
   *
   * scene.groundPrimitives.add(new Cesium.GroundPolylinePrimitive({
   *   geometryInstances : instance,
   *   appearance : new Cesium.PolylineMaterialAppearance()
   * }));
   *
   * // 2. Draw a looped polyline on terrain with per-instance color and a distance display condition.
   * // Distance display conditions for polylines on terrain are based on an approximate terrain height
   * // instead of true terrain height.
   *
   * const instance2 = new Cesium.GeometryInstance({
   *   geometry : new Cesium.GroundPolylineGeometry({
   *      positions : Cesium.Cartesian3.fromDegreesArray([
   *          -112.1340164450331, 36.05494287836128,
   *          -112.08821010582645, 36.097804071380715,
   *          -112.13296079730024, 36.168769146801104
   *      ]),
   *      loop : true,
   *      width : 4.0
   *   }),
   *   attributes : {
   *      color : Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.fromCssColorString('green').withAlpha(0.7)),
   *      distanceDisplayCondition : new Cesium.DistanceDisplayConditionGeometryInstanceAttribute(1000, 30000)
   *   },
   *   id : 'object returned when this instance is picked and to get/set per-instance attributes'
   * });
   *
   * scene.groundPrimitives.add(new Cesium.GroundPolylinePrimitive({
   *   geometryInstances : instance2,
   *   appearance : new Cesium.PolylineColorAppearance()
   * }));
   */
  function GroundPolylinePrimitive(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    /**
     * The geometry instances rendered with this primitive. This may
     * be <code>undefined</code> if <code>options.releaseGeometryInstances</code>
     * is <code>true</code> when the primitive is constructed.
     * <p>
     * Changing this property after the primitive is rendered has no effect.
     * </p>
     *
     * @readonly
     * @type {Array|GeometryInstance}
     *
     * @default undefined
     */
    this.geometryInstances = options.geometryInstances;
    this._hasPerInstanceColors = true;

    let appearance = options.appearance;
    if (!defined(appearance)) {
      appearance = new PolylineMaterialAppearance();
    }
    /**
     * The {@link Appearance} used to shade this primitive. Each geometry
     * instance is shaded with the same appearance.  Some appearances, like
     * {@link PolylineColorAppearance} allow giving each instance unique
     * properties.
     *
     * @type Appearance
     *
     * @default undefined
     */
    this.appearance = appearance;

    /**
     * Determines if the primitive will be shown.  This affects all geometry
     * instances in the primitive.
     *
     * @type {Boolean}
     *
     * @default true
     */
    this.show = defaultValue(options.show, true);

    /**
     * Determines whether terrain, 3D Tiles or both will be classified.
     *
     * @type {ClassificationType}
     *
     * @default ClassificationType.BOTH
     */
    this.classificationType = defaultValue(
      options.classificationType,
      ClassificationType$1.BOTH
    );

    /**
     * This property is for debugging only; it is not for production use nor is it optimized.
     * <p>
     * Draws the bounding sphere for each draw command in the primitive.
     * </p>
     *
     * @type {Boolean}
     *
     * @default false
     */
    this.debugShowBoundingVolume = defaultValue(
      options.debugShowBoundingVolume,
      false
    );

    // Shadow volume is shown by removing a discard in the shader, so this isn't toggleable.
    this._debugShowShadowVolume = defaultValue(
      options.debugShowShadowVolume,
      false
    );

    this._primitiveOptions = {
      geometryInstances: undefined,
      appearance: undefined,
      vertexCacheOptimize: false,
      interleave: defaultValue(options.interleave, false),
      releaseGeometryInstances: defaultValue(
        options.releaseGeometryInstances,
        true
      ),
      allowPicking: defaultValue(options.allowPicking, true),
      asynchronous: defaultValue(options.asynchronous, true),
      compressVertices: false,
      _createShaderProgramFunction: undefined,
      _createCommandsFunction: undefined,
      _updateAndQueueCommandsFunction: undefined,
    };

    // Used when inserting in an OrderedPrimitiveCollection
    this._zIndex = undefined;

    this._ready = false;
    this._readyPromise = defer();

    this._primitive = undefined;

    this._sp = undefined;
    this._sp2D = undefined;
    this._spMorph = undefined;

    this._renderState = getRenderState$1(false);
    this._renderState3DTiles = getRenderState$1(true);

    this._renderStateMorph = RenderState.fromCache({
      cull: {
        enabled: true,
        face: CullFace$1.FRONT, // Geometry is "inverted," so cull front when materials on volume instead of on terrain (morph)
      },
      depthTest: {
        enabled: true,
      },
      blending: BlendingState$1.PRE_MULTIPLIED_ALPHA_BLEND,
      depthMask: false,
    });
  }

  Object.defineProperties(GroundPolylinePrimitive.prototype, {
    /**
     * Determines if geometry vertex attributes are interleaved, which can slightly improve rendering performance.
     *
     * @memberof GroundPolylinePrimitive.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default false
     */
    interleave: {
      get: function () {
        return this._primitiveOptions.interleave;
      },
    },

    /**
     * When <code>true</code>, the primitive does not keep a reference to the input <code>geometryInstances</code> to save memory.
     *
     * @memberof GroundPolylinePrimitive.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default true
     */
    releaseGeometryInstances: {
      get: function () {
        return this._primitiveOptions.releaseGeometryInstances;
      },
    },

    /**
     * When <code>true</code>, each geometry instance will only be pickable with {@link Scene#pick}.  When <code>false</code>, GPU memory is saved.
     *
     * @memberof GroundPolylinePrimitive.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default true
     */
    allowPicking: {
      get: function () {
        return this._primitiveOptions.allowPicking;
      },
    },

    /**
     * Determines if the geometry instances will be created and batched on a web worker.
     *
     * @memberof GroundPolylinePrimitive.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default true
     */
    asynchronous: {
      get: function () {
        return this._primitiveOptions.asynchronous;
      },
    },

    /**
     * Determines if the primitive is complete and ready to render.  If this property is
     * true, the primitive will be rendered the next time that {@link GroundPolylinePrimitive#update}
     * is called.
     *
     * @memberof GroundPolylinePrimitive.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    ready: {
      get: function () {
        return this._ready;
      },
    },

    /**
     * Gets a promise that resolves when the primitive is ready to render.
     * @memberof GroundPolylinePrimitive.prototype
     * @type {Promise.<GroundPolylinePrimitive>}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._readyPromise.promise;
      },
    },

    /**
     * This property is for debugging only; it is not for production use nor is it optimized.
     * <p>
     * If true, draws the shadow volume for each geometry in the primitive.
     * </p>
     *
     * @memberof GroundPolylinePrimitive.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default false
     */
    debugShowShadowVolume: {
      get: function () {
        return this._debugShowShadowVolume;
      },
    },
  });

  /**
   * Initializes the minimum and maximum terrain heights. This only needs to be called if you are creating the
   * GroundPolylinePrimitive synchronously.
   *
   * @returns {Promise<void>} A promise that will resolve once the terrain heights have been loaded.
   */
  GroundPolylinePrimitive.initializeTerrainHeights = function () {
    return ApproximateTerrainHeights.initialize();
  };

  function createShaderProgram$1(groundPolylinePrimitive, frameState, appearance) {
    const context = frameState.context;
    const primitive = groundPolylinePrimitive._primitive;
    const attributeLocations = primitive._attributeLocations;

    let vs = primitive._batchTable.getVertexShaderCallback()(
      PolylineShadowVolumeVS
    );
    vs = Primitive$3._appendShowToShader(primitive, vs);
    vs = Primitive$3._appendDistanceDisplayConditionToShader(primitive, vs);
    vs = Primitive$3._modifyShaderPosition(
      groundPolylinePrimitive,
      vs,
      frameState.scene3DOnly
    );

    let vsMorph = primitive._batchTable.getVertexShaderCallback()(
      PolylineShadowVolumeMorphVS
    );
    vsMorph = Primitive$3._appendShowToShader(primitive, vsMorph);
    vsMorph = Primitive$3._appendDistanceDisplayConditionToShader(
      primitive,
      vsMorph
    );
    vsMorph = Primitive$3._modifyShaderPosition(
      groundPolylinePrimitive,
      vsMorph,
      frameState.scene3DOnly
    );

    // Access pick color from fragment shader.
    // Helps with varying budget.
    let fs = primitive._batchTable.getVertexShaderCallback()(
      PolylineShadowVolumeFS
    );

    const vsDefines = [
      `GLOBE_MINIMUM_ALTITUDE ${frameState.mapProjection.ellipsoid.minimumRadius.toFixed(
      1
    )}`,
    ];
    let colorDefine = "";
    let materialShaderSource = "";
    if (defined(appearance.material)) {
      materialShaderSource = defined(appearance.material)
        ? appearance.material.shaderSource
        : "";

      // Check for use of v_width and v_polylineAngle in material shader
      // to determine whether these varyings should be active in the vertex shader.
      if (
        materialShaderSource.search(/varying\s+float\s+v_polylineAngle;/g) !== -1
      ) {
        vsDefines.push("ANGLE_VARYING");
      }
      if (materialShaderSource.search(/varying\s+float\s+v_width;/g) !== -1) {
        vsDefines.push("WIDTH_VARYING");
      }
    } else {
      colorDefine = "PER_INSTANCE_COLOR";
    }

    vsDefines.push(colorDefine);
    const fsDefines = groundPolylinePrimitive.debugShowShadowVolume
      ? ["DEBUG_SHOW_VOLUME", colorDefine]
      : [colorDefine];

    const vsColor3D = new ShaderSource({
      defines: vsDefines,
      sources: [vs],
    });
    const fsColor3D = new ShaderSource({
      defines: fsDefines,
      sources: [materialShaderSource, fs],
    });
    groundPolylinePrimitive._sp = ShaderProgram.replaceCache({
      context: context,
      shaderProgram: primitive._sp,
      vertexShaderSource: vsColor3D,
      fragmentShaderSource: fsColor3D,
      attributeLocations: attributeLocations,
    });

    // Derive 2D/CV
    let colorProgram2D = context.shaderCache.getDerivedShaderProgram(
      groundPolylinePrimitive._sp,
      "2dColor"
    );
    if (!defined(colorProgram2D)) {
      const vsColor2D = new ShaderSource({
        defines: vsDefines.concat(["COLUMBUS_VIEW_2D"]),
        sources: [vs],
      });
      colorProgram2D = context.shaderCache.createDerivedShaderProgram(
        groundPolylinePrimitive._sp,
        "2dColor",
        {
          context: context,
          shaderProgram: groundPolylinePrimitive._sp2D,
          vertexShaderSource: vsColor2D,
          fragmentShaderSource: fsColor3D,
          attributeLocations: attributeLocations,
        }
      );
    }
    groundPolylinePrimitive._sp2D = colorProgram2D;

    // Derive Morph
    let colorProgramMorph = context.shaderCache.getDerivedShaderProgram(
      groundPolylinePrimitive._sp,
      "MorphColor"
    );
    if (!defined(colorProgramMorph)) {
      const vsColorMorph = new ShaderSource({
        defines: vsDefines.concat([
          `MAX_TERRAIN_HEIGHT ${ApproximateTerrainHeights._defaultMaxTerrainHeight.toFixed(
          1
        )}`,
        ]),
        sources: [vsMorph],
      });

      fs = primitive._batchTable.getVertexShaderCallback()(
        PolylineShadowVolumeMorphFS
      );
      const fsColorMorph = new ShaderSource({
        defines: fsDefines,
        sources: [materialShaderSource, fs],
      });
      colorProgramMorph = context.shaderCache.createDerivedShaderProgram(
        groundPolylinePrimitive._sp,
        "MorphColor",
        {
          context: context,
          shaderProgram: groundPolylinePrimitive._spMorph,
          vertexShaderSource: vsColorMorph,
          fragmentShaderSource: fsColorMorph,
          attributeLocations: attributeLocations,
        }
      );
    }
    groundPolylinePrimitive._spMorph = colorProgramMorph;
  }

  function getRenderState$1(mask3DTiles) {
    return RenderState.fromCache({
      cull: {
        enabled: true, // prevent double-draw. Geometry is "inverted" (reversed winding order) so we're drawing backfaces.
      },
      blending: BlendingState$1.PRE_MULTIPLIED_ALPHA_BLEND,
      depthMask: false,
      stencilTest: {
        enabled: mask3DTiles,
        frontFunction: StencilFunction$1.EQUAL,
        frontOperation: {
          fail: StencilOperation$1.KEEP,
          zFail: StencilOperation$1.KEEP,
          zPass: StencilOperation$1.KEEP,
        },
        backFunction: StencilFunction$1.EQUAL,
        backOperation: {
          fail: StencilOperation$1.KEEP,
          zFail: StencilOperation$1.KEEP,
          zPass: StencilOperation$1.KEEP,
        },
        reference: StencilConstants$1.CESIUM_3D_TILE_MASK,
        mask: StencilConstants$1.CESIUM_3D_TILE_MASK,
      },
    });
  }

  function createCommands$3(
    groundPolylinePrimitive,
    appearance,
    material,
    translucent,
    colorCommands,
    pickCommands
  ) {
    const primitive = groundPolylinePrimitive._primitive;
    const length = primitive._va.length;
    colorCommands.length = length;
    pickCommands.length = length;

    const isPolylineColorAppearance =
      appearance instanceof PolylineColorAppearance;

    const materialUniforms = isPolylineColorAppearance ? {} : material._uniforms;
    const uniformMap = primitive._batchTable.getUniformMapCallback()(
      materialUniforms
    );

    for (let i = 0; i < length; i++) {
      const vertexArray = primitive._va[i];

      let command = colorCommands[i];
      if (!defined(command)) {
        command = colorCommands[i] = new DrawCommand({
          owner: groundPolylinePrimitive,
          primitiveType: primitive._primitiveType,
        });
      }

      command.vertexArray = vertexArray;
      command.renderState = groundPolylinePrimitive._renderState;
      command.shaderProgram = groundPolylinePrimitive._sp;
      command.uniformMap = uniformMap;
      command.pass = Pass$1.TERRAIN_CLASSIFICATION;
      command.pickId = "czm_batchTable_pickColor(v_endPlaneNormalEcAndBatchId.w)";

      const derivedTilesetCommand = DrawCommand.shallowClone(
        command,
        command.derivedCommands.tileset
      );
      derivedTilesetCommand.renderState =
        groundPolylinePrimitive._renderState3DTiles;
      derivedTilesetCommand.pass = Pass$1.CESIUM_3D_TILE_CLASSIFICATION;
      command.derivedCommands.tileset = derivedTilesetCommand;

      // derive for 2D
      const derived2DCommand = DrawCommand.shallowClone(
        command,
        command.derivedCommands.color2D
      );
      derived2DCommand.shaderProgram = groundPolylinePrimitive._sp2D;
      command.derivedCommands.color2D = derived2DCommand;

      const derived2DTilesetCommand = DrawCommand.shallowClone(
        derivedTilesetCommand,
        derivedTilesetCommand.derivedCommands.color2D
      );
      derived2DTilesetCommand.shaderProgram = groundPolylinePrimitive._sp2D;
      derivedTilesetCommand.derivedCommands.color2D = derived2DTilesetCommand;

      // derive for Morph
      const derivedMorphCommand = DrawCommand.shallowClone(
        command,
        command.derivedCommands.colorMorph
      );
      derivedMorphCommand.renderState = groundPolylinePrimitive._renderStateMorph;
      derivedMorphCommand.shaderProgram = groundPolylinePrimitive._spMorph;
      derivedMorphCommand.pickId = "czm_batchTable_pickColor(v_batchId)";
      command.derivedCommands.colorMorph = derivedMorphCommand;
    }
  }

  function updateAndQueueCommand(
    groundPolylinePrimitive,
    command,
    frameState,
    modelMatrix,
    cull,
    boundingVolume,
    debugShowBoundingVolume
  ) {
    // Use derived appearance command for morph and 2D
    if (frameState.mode === SceneMode$1.MORPHING) {
      command = command.derivedCommands.colorMorph;
    } else if (frameState.mode !== SceneMode$1.SCENE3D) {
      command = command.derivedCommands.color2D;
    }
    command.modelMatrix = modelMatrix;
    command.boundingVolume = boundingVolume;
    command.cull = cull;
    command.debugShowBoundingVolume = debugShowBoundingVolume;

    frameState.commandList.push(command);
  }

  function updateAndQueueCommands(
    groundPolylinePrimitive,
    frameState,
    colorCommands,
    pickCommands,
    modelMatrix,
    cull,
    debugShowBoundingVolume
  ) {
    const primitive = groundPolylinePrimitive._primitive;

    Primitive$3._updateBoundingVolumes(primitive, frameState, modelMatrix); // Expected to be identity - GroundPrimitives don't support other model matrices

    let boundingSpheres;
    if (frameState.mode === SceneMode$1.SCENE3D) {
      boundingSpheres = primitive._boundingSphereWC;
    } else if (frameState.mode === SceneMode$1.COLUMBUS_VIEW) {
      boundingSpheres = primitive._boundingSphereCV;
    } else if (
      frameState.mode === SceneMode$1.SCENE2D &&
      defined(primitive._boundingSphere2D)
    ) {
      boundingSpheres = primitive._boundingSphere2D;
    } else if (defined(primitive._boundingSphereMorph)) {
      boundingSpheres = primitive._boundingSphereMorph;
    }

    const morphing = frameState.mode === SceneMode$1.MORPHING;
    const classificationType = groundPolylinePrimitive.classificationType;
    const queueTerrainCommands =
      classificationType !== ClassificationType$1.CESIUM_3D_TILE;
    const queue3DTilesCommands =
      classificationType !== ClassificationType$1.TERRAIN && !morphing;

    let command;
    const passes = frameState.passes;
    if (passes.render || (passes.pick && primitive.allowPicking)) {
      const colorLength = colorCommands.length;
      for (let j = 0; j < colorLength; ++j) {
        const boundingVolume = boundingSpheres[j];
        if (queueTerrainCommands) {
          command = colorCommands[j];
          updateAndQueueCommand(
            groundPolylinePrimitive,
            command,
            frameState,
            modelMatrix,
            cull,
            boundingVolume,
            debugShowBoundingVolume
          );
        }
        if (queue3DTilesCommands) {
          command = colorCommands[j].derivedCommands.tileset;
          updateAndQueueCommand(
            groundPolylinePrimitive,
            command,
            frameState,
            modelMatrix,
            cull,
            boundingVolume,
            debugShowBoundingVolume
          );
        }
      }
    }
  }

  /**
   * Called when {@link Viewer} or {@link CesiumWidget} render the scene to
   * get the draw commands needed to render this primitive.
   * <p>
   * Do not call this function directly.  This is documented just to
   * list the exceptions that may be propagated when the scene is rendered:
   * </p>
   *
   * @exception {DeveloperError} For synchronous GroundPolylinePrimitives, you must call GroundPolylinePrimitives.initializeTerrainHeights() and wait for the returned promise to resolve.
   * @exception {DeveloperError} All GeometryInstances must have color attributes to use PolylineColorAppearance with GroundPolylinePrimitive.
   */
  GroundPolylinePrimitive.prototype.update = function (frameState) {
    if (!defined(this._primitive) && !defined(this.geometryInstances)) {
      return;
    }

    if (!ApproximateTerrainHeights.initialized) {
      //>>includeStart('debug', pragmas.debug);
      if (!this.asynchronous) {
        throw new DeveloperError(
          "For synchronous GroundPolylinePrimitives, you must call GroundPolylinePrimitives.initializeTerrainHeights() and wait for the returned promise to resolve."
        );
      }
      //>>includeEnd('debug');

      GroundPolylinePrimitive.initializeTerrainHeights();
      return;
    }

    let i;

    const that = this;
    const primitiveOptions = this._primitiveOptions;
    if (!defined(this._primitive)) {
      const geometryInstances = Array.isArray(this.geometryInstances)
        ? this.geometryInstances
        : [this.geometryInstances];
      const geometryInstancesLength = geometryInstances.length;
      const groundInstances = new Array(geometryInstancesLength);

      let attributes;

      // Check if each instance has a color attribute.
      for (i = 0; i < geometryInstancesLength; ++i) {
        attributes = geometryInstances[i].attributes;
        if (!defined(attributes) || !defined(attributes.color)) {
          this._hasPerInstanceColors = false;
          break;
        }
      }

      for (i = 0; i < geometryInstancesLength; ++i) {
        const geometryInstance = geometryInstances[i];
        attributes = {};
        const instanceAttributes = geometryInstance.attributes;
        for (const attributeKey in instanceAttributes) {
          if (instanceAttributes.hasOwnProperty(attributeKey)) {
            attributes[attributeKey] = instanceAttributes[attributeKey];
          }
        }

        // Automatically create line width attribute if not already given
        if (!defined(attributes.width)) {
          attributes.width = new GeometryInstanceAttribute({
            componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
            componentsPerAttribute: 1.0,
            value: [geometryInstance.geometry.width],
          });
        }

        // Update each geometry for framestate.scene3DOnly = true and projection
        geometryInstance.geometry._scene3DOnly = frameState.scene3DOnly;
        GroundPolylineGeometry.setProjectionAndEllipsoid(
          geometryInstance.geometry,
          frameState.mapProjection
        );

        groundInstances[i] = new GeometryInstance({
          geometry: geometryInstance.geometry,
          attributes: attributes,
          id: geometryInstance.id,
          pickPrimitive: that,
        });
      }

      primitiveOptions.geometryInstances = groundInstances;
      primitiveOptions.appearance = this.appearance;

      primitiveOptions._createShaderProgramFunction = function (
        primitive,
        frameState,
        appearance
      ) {
        createShaderProgram$1(that, frameState, appearance);
      };
      primitiveOptions._createCommandsFunction = function (
        primitive,
        appearance,
        material,
        translucent,
        twoPasses,
        colorCommands,
        pickCommands
      ) {
        createCommands$3(
          that,
          appearance,
          material,
          translucent,
          colorCommands,
          pickCommands
        );
      };
      primitiveOptions._updateAndQueueCommandsFunction = function (
        primitive,
        frameState,
        colorCommands,
        pickCommands,
        modelMatrix,
        cull,
        debugShowBoundingVolume,
        twoPasses
      ) {
        updateAndQueueCommands(
          that,
          frameState,
          colorCommands,
          pickCommands,
          modelMatrix,
          cull,
          debugShowBoundingVolume
        );
      };

      this._primitive = new Primitive$3(primitiveOptions);
      this._primitive.readyPromise.then(function (primitive) {
        that._ready = true;

        if (that.releaseGeometryInstances) {
          that.geometryInstances = undefined;
        }

        const error = primitive._error;
        if (!defined(error)) {
          that._readyPromise.resolve(that);
        } else {
          that._readyPromise.reject(error);
        }
      });
    }

    if (
      this.appearance instanceof PolylineColorAppearance &&
      !this._hasPerInstanceColors
    ) {
      throw new DeveloperError(
        "All GeometryInstances must have color attributes to use PolylineColorAppearance with GroundPolylinePrimitive."
      );
    }

    this._primitive.appearance = this.appearance;
    this._primitive.show = this.show;
    this._primitive.debugShowBoundingVolume = this.debugShowBoundingVolume;
    this._primitive.update(frameState);
  };

  /**
   * Returns the modifiable per-instance attributes for a {@link GeometryInstance}.
   *
   * @param {*} id The id of the {@link GeometryInstance}.
   * @returns {Object} The typed array in the attribute's format or undefined if the is no instance with id.
   *
   * @exception {DeveloperError} must call update before calling getGeometryInstanceAttributes.
   *
   * @example
   * const attributes = primitive.getGeometryInstanceAttributes('an id');
   * attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.AQUA);
   * attributes.show = Cesium.ShowGeometryInstanceAttribute.toValue(true);
   */
  GroundPolylinePrimitive.prototype.getGeometryInstanceAttributes = function (
    id
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(this._primitive)) {
      throw new DeveloperError(
        "must call update before calling getGeometryInstanceAttributes"
      );
    }
    //>>includeEnd('debug');
    return this._primitive.getGeometryInstanceAttributes(id);
  };

  /**
   * Checks if the given Scene supports GroundPolylinePrimitives.
   * GroundPolylinePrimitives require support for the WEBGL_depth_texture extension.
   *
   * @param {Scene} scene The current scene.
   * @returns {Boolean} Whether or not the current scene supports GroundPolylinePrimitives.
   */
  GroundPolylinePrimitive.isSupported = function (scene) {
    return scene.frameState.context.depthTexture;
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <p>
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   * </p>
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see GroundPolylinePrimitive#destroy
   */
  GroundPolylinePrimitive.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <p>
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   * </p>
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @example
   * e = e && e.destroy();
   *
   * @see GroundPolylinePrimitive#isDestroyed
   */
  GroundPolylinePrimitive.prototype.destroy = function () {
    this._primitive = this._primitive && this._primitive.destroy();
    this._sp = this._sp && this._sp.destroy();

    // Derived programs, destroyed above if they existed.
    this._sp2D = undefined;
    this._spMorph = undefined;

    return destroyObject(this);
  };

  const defaultRepeat$2 = new Cartesian2(1, 1);
  const defaultTransparent = false;
  const defaultColor$7 = Color.WHITE;

  /**
   * A {@link MaterialProperty} that maps to image {@link Material} uniforms.
   * @alias ImageMaterialProperty
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Property|String|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement} [options.image] A Property specifying the Image, URL, Canvas, or Video.
   * @param {Property|Cartesian2} [options.repeat=new Cartesian2(1.0, 1.0)] A {@link Cartesian2} Property specifying the number of times the image repeats in each direction.
   * @param {Property|Color} [options.color=Color.WHITE] The color applied to the image
   * @param {Property|Boolean} [options.transparent=false] Set to true when the image has transparency (for example, when a png has transparent sections)
   */
  function ImageMaterialProperty(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    this._definitionChanged = new Event();
    this._image = undefined;
    this._imageSubscription = undefined;
    this._repeat = undefined;
    this._repeatSubscription = undefined;
    this._color = undefined;
    this._colorSubscription = undefined;
    this._transparent = undefined;
    this._transparentSubscription = undefined;

    this.image = options.image;
    this.repeat = options.repeat;
    this.color = options.color;
    this.transparent = options.transparent;
  }

  Object.defineProperties(ImageMaterialProperty.prototype, {
    /**
     * Gets a value indicating if this property is constant.  A property is considered
     * constant if getValue always returns the same result for the current definition.
     * @memberof ImageMaterialProperty.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    isConstant: {
      get: function () {
        return (
          Property.isConstant(this._image) && Property.isConstant(this._repeat)
        );
      },
    },

    /**
     * Gets the event that is raised whenever the definition of this property changes.
     * The definition is considered to have changed if a call to getValue would return
     * a different result for the same time.
     * @memberof ImageMaterialProperty.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },

    /**
     * Gets or sets the Property specifying Image, URL, Canvas, or Video to use.
     * @memberof ImageMaterialProperty.prototype
     * @type {Property|undefined}
     */
    image: createPropertyDescriptor("image"),

    /**
     * Gets or sets the {@link Cartesian2} Property specifying the number of times the image repeats in each direction.
     * @memberof ImageMaterialProperty.prototype
     * @type {Property|undefined}
     * @default new Cartesian2(1, 1)
     */
    repeat: createPropertyDescriptor("repeat"),

    /**
     * Gets or sets the Color Property specifying the desired color applied to the image.
     * @memberof ImageMaterialProperty.prototype
     * @type {Property|undefined}
     * @default 1.0
     */
    color: createPropertyDescriptor("color"),

    /**
     * Gets or sets the Boolean Property specifying whether the image has transparency
     * @memberof ImageMaterialProperty.prototype
     * @type {Property|undefined}
     * @default 1.0
     */
    transparent: createPropertyDescriptor("transparent"),
  });

  /**
   * Gets the {@link Material} type at the provided time.
   *
   * @param {JulianDate} time The time for which to retrieve the type.
   * @returns {String} The type of material.
   */
  ImageMaterialProperty.prototype.getType = function (time) {
    return "Image";
  };

  /**
   * Gets the value of the property at the provided time.
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {Object} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Object} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  ImageMaterialProperty.prototype.getValue = function (time, result) {
    if (!defined(result)) {
      result = {};
    }

    result.image = Property.getValueOrUndefined(this._image, time);
    result.repeat = Property.getValueOrClonedDefault(
      this._repeat,
      time,
      defaultRepeat$2,
      result.repeat
    );
    result.color = Property.getValueOrClonedDefault(
      this._color,
      time,
      defaultColor$7,
      result.color
    );
    if (Property.getValueOrDefault(this._transparent, time, defaultTransparent)) {
      result.color.alpha = Math.min(0.99, result.color.alpha);
    }

    return result;
  };

  /**
   * Compares this property to the provided property and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Property} [other] The other property.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  ImageMaterialProperty.prototype.equals = function (other) {
    return (
      this === other ||
      (other instanceof ImageMaterialProperty &&
        Property.equals(this._image, other._image) &&
        Property.equals(this._repeat, other._repeat) &&
        Property.equals(this._color, other._color) &&
        Property.equals(this._transparent, other._transparent))
    );
  };

  function createMaterialProperty(value) {
    if (value instanceof Color) {
      return new ColorMaterialProperty(value);
    }

    if (
      typeof value === "string" ||
      value instanceof Resource ||
      value instanceof HTMLCanvasElement ||
      value instanceof HTMLVideoElement
    ) {
      const result = new ImageMaterialProperty();
      result.image = value;
      return result;
    }

    //>>includeStart('debug', pragmas.debug);
    throw new DeveloperError(`Unable to infer material type: ${value}`);
    //>>includeEnd('debug');
  }

  /**
   * @private
   */
  function createMaterialPropertyDescriptor(name, configurable) {
    return createPropertyDescriptor(name, configurable, createMaterialProperty);
  }

  /**
   * @typedef {Object} BoxGraphics.ConstructorOptions
   *
   * Initialization options for the BoxGraphics constructor
   *
   * @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the box.
   * @property {Property | Cartesian3} [dimensions] A {@link Cartesian3} Property specifying the length, width, and height of the box.
   * @property {Property | HeightReference} [heightReference=HeightReference.NONE] A Property specifying what the height from the entity position is relative to.
   * @property {Property | boolean} [fill=true] A boolean Property specifying whether the box is filled with the provided material.
   * @property {MaterialProperty | Color} [material=Color.WHITE] A Property specifying the material used to fill the box.
   * @property {Property | boolean} [outline=false] A boolean Property specifying whether the box is outlined.
   * @property {Property | Color} [outlineColor=Color.BLACK] A Property specifying the {@link Color} of the outline.
   * @property {Property | number} [outlineWidth=1.0] A numeric Property specifying the width of the outline.
   * @property {Property | ShadowMode} [shadows=ShadowMode.DISABLED] An enum Property specifying whether the box casts or receives shadows from light sources.
   * @property {Property | DistanceDisplayCondition} [distanceDisplayCondition] A Property specifying at what distance from the camera that this box will be displayed.
   *
   */

  /**
   * Describes a box. The center position and orientation are determined by the containing {@link Entity}.
   *
   * @alias BoxGraphics
   * @constructor
   *
   * @param {BoxGraphics.ConstructorOptions} [options] Object describing initialization options
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Box.html|Cesium Sandcastle Box Demo}
   */
  function BoxGraphics(options) {
    this._definitionChanged = new Event();
    this._show = undefined;
    this._showSubscription = undefined;
    this._dimensions = undefined;
    this._dimensionsSubscription = undefined;
    this._heightReference = undefined;
    this._heightReferenceSubscription = undefined;
    this._fill = undefined;
    this._fillSubscription = undefined;
    this._material = undefined;
    this._materialSubscription = undefined;
    this._outline = undefined;
    this._outlineSubscription = undefined;
    this._outlineColor = undefined;
    this._outlineColorSubscription = undefined;
    this._outlineWidth = undefined;
    this._outlineWidthSubscription = undefined;
    this._shadows = undefined;
    this._shadowsSubscription = undefined;
    this._distanceDisplayCondition = undefined;
    this._distanceDisplayConditionSubscription = undefined;

    this.merge(defaultValue(options, defaultValue.EMPTY_OBJECT));
  }

  Object.defineProperties(BoxGraphics.prototype, {
    /**
     * Gets the event that is raised whenever a property or sub-property is changed or modified.
     * @memberof BoxGraphics.prototype
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },

    /**
     * Gets or sets the boolean Property specifying the visibility of the box.
     * @memberof BoxGraphics.prototype
     * @type {Property|undefined}
     * @default true
     */
    show: createPropertyDescriptor("show"),

    /**
     * Gets or sets {@link Cartesian3} Property property specifying the length, width, and height of the box.
     * @memberof BoxGraphics.prototype
     * @type {Property|undefined}
     */
    dimensions: createPropertyDescriptor("dimensions"),

    /**
     * Gets or sets the Property specifying the {@link HeightReference}.
     * @memberof BoxGraphics.prototype
     * @type {Property|undefined}
     * @default HeightReference.NONE
     */
    heightReference: createPropertyDescriptor("heightReference"),

    /**
     * Gets or sets the boolean Property specifying whether the box is filled with the provided material.
     * @memberof BoxGraphics.prototype
     * @type {Property|undefined}
     * @default true
     */
    fill: createPropertyDescriptor("fill"),

    /**
     * Gets or sets the material used to fill the box.
     * @memberof BoxGraphics.prototype
     * @type {MaterialProperty|undefined}
     * @default Color.WHITE
     */
    material: createMaterialPropertyDescriptor("material"),

    /**
     * Gets or sets the Property specifying whether the box is outlined.
     * @memberof BoxGraphics.prototype
     * @type {Property|undefined}
     * @default false
     */
    outline: createPropertyDescriptor("outline"),

    /**
     * Gets or sets the Property specifying the {@link Color} of the outline.
     * @memberof BoxGraphics.prototype
     * @type {Property|undefined}
     * @default Color.BLACK
     */
    outlineColor: createPropertyDescriptor("outlineColor"),

    /**
     * Gets or sets the numeric Property specifying the width of the outline.
     * <p>
     * Note: This property will be ignored on all major browsers on Windows platforms. For details, see (@link https://github.com/CesiumGS/cesium/issues/40}.
     * </p>
     * @memberof BoxGraphics.prototype
     * @type {Property|undefined}
     * @default 1.0
     */
    outlineWidth: createPropertyDescriptor("outlineWidth"),

    /**
     * Get or sets the enum Property specifying whether the box
     * casts or receives shadows from light sources.
     * @memberof BoxGraphics.prototype
     * @type {Property|undefined}
     * @default ShadowMode.DISABLED
     */
    shadows: createPropertyDescriptor("shadows"),

    /**
     * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this box will be displayed.
     * @memberof BoxGraphics.prototype
     * @type {Property|undefined}
     */
    distanceDisplayCondition: createPropertyDescriptor(
      "distanceDisplayCondition"
    ),
  });

  /**
   * Duplicates this instance.
   *
   * @param {BoxGraphics} [result] The object onto which to store the result.
   * @returns {BoxGraphics} The modified result parameter or a new instance if one was not provided.
   */
  BoxGraphics.prototype.clone = function (result) {
    if (!defined(result)) {
      return new BoxGraphics(this);
    }
    result.show = this.show;
    result.dimensions = this.dimensions;
    result.heightReference = this.heightReference;
    result.fill = this.fill;
    result.material = this.material;
    result.outline = this.outline;
    result.outlineColor = this.outlineColor;
    result.outlineWidth = this.outlineWidth;
    result.shadows = this.shadows;
    result.distanceDisplayCondition = this.distanceDisplayCondition;
    return result;
  };

  /**
   * Assigns each unassigned property on this object to the value
   * of the same property on the provided source object.
   *
   * @param {BoxGraphics} source The object to be merged into this object.
   */
  BoxGraphics.prototype.merge = function (source) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(source)) {
      throw new DeveloperError("source is required.");
    }
    //>>includeEnd('debug');

    this.show = defaultValue(this.show, source.show);
    this.dimensions = defaultValue(this.dimensions, source.dimensions);
    this.heightReference = defaultValue(
      this.heightReference,
      source.heightReference
    );
    this.fill = defaultValue(this.fill, source.fill);
    this.material = defaultValue(this.material, source.material);
    this.outline = defaultValue(this.outline, source.outline);
    this.outlineColor = defaultValue(this.outlineColor, source.outlineColor);
    this.outlineWidth = defaultValue(this.outlineWidth, source.outlineWidth);
    this.shadows = defaultValue(this.shadows, source.shadows);
    this.distanceDisplayCondition = defaultValue(
      this.distanceDisplayCondition,
      source.distanceDisplayCondition
    );
  };

  /**
   * The interface for all {@link Property} objects that define a world
   * location as a {@link Cartesian3} with an associated {@link ReferenceFrame}.
   * This type defines an interface and cannot be instantiated directly.
   *
   * @alias PositionProperty
   * @constructor
   * @abstract
   *
   * @see CompositePositionProperty
   * @see ConstantPositionProperty
   * @see SampledPositionProperty
   * @see TimeIntervalCollectionPositionProperty
   */
  function PositionProperty() {
    DeveloperError.throwInstantiationError();
  }

  Object.defineProperties(PositionProperty.prototype, {
    /**
     * Gets a value indicating if this property is constant.  A property is considered
     * constant if getValue always returns the same result for the current definition.
     * @memberof PositionProperty.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    isConstant: {
      get: DeveloperError.throwInstantiationError,
    },
    /**
     * Gets the event that is raised whenever the definition of this property changes.
     * The definition is considered to have changed if a call to getValue would return
     * a different result for the same time.
     * @memberof PositionProperty.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: DeveloperError.throwInstantiationError,
    },
    /**
     * Gets the reference frame that the position is defined in.
     * @memberof PositionProperty.prototype
     * @type {ReferenceFrame}
     */
    referenceFrame: {
      get: DeveloperError.throwInstantiationError,
    },
  });

  /**
   * Gets the value of the property at the provided time in the fixed frame.
   * @function
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {Cartesian3} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Cartesian3 | undefined} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  PositionProperty.prototype.getValue = DeveloperError.throwInstantiationError;

  /**
   * Gets the value of the property at the provided time and in the provided reference frame.
   * @function
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {ReferenceFrame} referenceFrame The desired referenceFrame of the result.
   * @param {Cartesian3} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Cartesian3 | undefined} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  PositionProperty.prototype.getValueInReferenceFrame =
    DeveloperError.throwInstantiationError;

  /**
   * Compares this property to the provided property and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   * @function
   *
   * @param {Property} [other] The other property.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  PositionProperty.prototype.equals = DeveloperError.throwInstantiationError;

  const scratchMatrix3$2 = new Matrix3();

  /**
   * @private
   */
  PositionProperty.convertToReferenceFrame = function (
    time,
    value,
    inputFrame,
    outputFrame,
    result
  ) {
    if (!defined(value)) {
      return value;
    }
    if (!defined(result)) {
      result = new Cartesian3();
    }

    if (inputFrame === outputFrame) {
      return Cartesian3.clone(value, result);
    }

    let icrfToFixed = Transforms.computeIcrfToFixedMatrix(time, scratchMatrix3$2);
    if (!defined(icrfToFixed)) {
      icrfToFixed = Transforms.computeTemeToPseudoFixedMatrix(
        time,
        scratchMatrix3$2
      );
    }
    if (inputFrame === ReferenceFrame$1.INERTIAL) {
      return Matrix3.multiplyByVector(icrfToFixed, value, result);
    }
    if (inputFrame === ReferenceFrame$1.FIXED) {
      return Matrix3.multiplyByVector(
        Matrix3.transpose(icrfToFixed, scratchMatrix3$2),
        value,
        result
      );
    }
  };

  /**
   * A {@link PositionProperty} whose value does not change in respect to the
   * {@link ReferenceFrame} in which is it defined.
   *
   * @alias ConstantPositionProperty
   * @constructor
   *
   * @param {Cartesian3} [value] The property value.
   * @param {ReferenceFrame} [referenceFrame=ReferenceFrame.FIXED] The reference frame in which the position is defined.
   */
  function ConstantPositionProperty(value, referenceFrame) {
    this._definitionChanged = new Event();
    this._value = Cartesian3.clone(value);
    this._referenceFrame = defaultValue(referenceFrame, ReferenceFrame$1.FIXED);
  }

  Object.defineProperties(ConstantPositionProperty.prototype, {
    /**
     * Gets a value indicating if this property is constant.  A property is considered
     * constant if getValue always returns the same result for the current definition.
     * @memberof ConstantPositionProperty.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    isConstant: {
      get: function () {
        return (
          !defined(this._value) || this._referenceFrame === ReferenceFrame$1.FIXED
        );
      },
    },
    /**
     * Gets the event that is raised whenever the definition of this property changes.
     * The definition is considered to have changed if a call to getValue would return
     * a different result for the same time.
     * @memberof ConstantPositionProperty.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },
    /**
     * Gets the reference frame in which the position is defined.
     * @memberof ConstantPositionProperty.prototype
     * @type {ReferenceFrame}
     * @default ReferenceFrame.FIXED;
     */
    referenceFrame: {
      get: function () {
        return this._referenceFrame;
      },
    },
  });

  /**
   * Gets the value of the property at the provided time in the fixed frame.
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {Object} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Object} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  ConstantPositionProperty.prototype.getValue = function (time, result) {
    return this.getValueInReferenceFrame(time, ReferenceFrame$1.FIXED, result);
  };

  /**
   * Sets the value of the property.
   *
   * @param {Cartesian3} value The property value.
   * @param {ReferenceFrame} [referenceFrame=this.referenceFrame] The reference frame in which the position is defined.
   */
  ConstantPositionProperty.prototype.setValue = function (value, referenceFrame) {
    let definitionChanged = false;
    if (!Cartesian3.equals(this._value, value)) {
      definitionChanged = true;
      this._value = Cartesian3.clone(value);
    }
    if (defined(referenceFrame) && this._referenceFrame !== referenceFrame) {
      definitionChanged = true;
      this._referenceFrame = referenceFrame;
    }
    if (definitionChanged) {
      this._definitionChanged.raiseEvent(this);
    }
  };

  /**
   * Gets the value of the property at the provided time and in the provided reference frame.
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {ReferenceFrame} referenceFrame The desired referenceFrame of the result.
   * @param {Cartesian3} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Cartesian3} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  ConstantPositionProperty.prototype.getValueInReferenceFrame = function (
    time,
    referenceFrame,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(time)) {
      throw new DeveloperError("time is required.");
    }
    if (!defined(referenceFrame)) {
      throw new DeveloperError("referenceFrame is required.");
    }
    //>>includeEnd('debug');

    return PositionProperty.convertToReferenceFrame(
      time,
      this._value,
      this._referenceFrame,
      referenceFrame,
      result
    );
  };

  /**
   * Compares this property to the provided property and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Property} [other] The other property.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  ConstantPositionProperty.prototype.equals = function (other) {
    return (
      this === other ||
      (other instanceof ConstantPositionProperty &&
        Cartesian3.equals(this._value, other._value) &&
        this._referenceFrame === other._referenceFrame)
    );
  };

  /**
   * @typedef {Object} CorridorGraphics.ConstructorOptions
   *
   * Initialization options for the CorridorGraphics constructor
   *
   * @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the corridor.
   * @property {Property | Cartesian3[]} [positions] A Property specifying the array of {@link Cartesian3} positions that define the centerline of the corridor.
   * @property {Property | number} [width] A numeric Property specifying the distance between the edges of the corridor.
   * @property {Property | number} [height=0] A numeric Property specifying the altitude of the corridor relative to the ellipsoid surface.
   * @property {Property | HeightReference} [heightReference=HeightReference.NONE] A Property specifying what the height is relative to.
   * @property {Property | number} [extrudedHeight] A numeric Property specifying the altitude of the corridor's extruded face relative to the ellipsoid surface.
   * @property {Property | HeightReference} [extrudedHeightReference=HeightReference.NONE] A Property specifying what the extrudedHeight is relative to.
   * @property {Property | CornerType} [cornerType=CornerType.ROUNDED] A {@link CornerType} Property specifying the style of the corners.
   * @property {Property | number} [granularity=Cesium.Math.RADIANS_PER_DEGREE] A numeric Property specifying the distance between each latitude and longitude.
   * @property {Property | boolean} [fill=true] A boolean Property specifying whether the corridor is filled with the provided material.
   * @property {MaterialProperty | Color} [material=Color.WHITE] A Property specifying the material used to fill the corridor.
   * @property {Property | boolean} [outline=false] A boolean Property specifying whether the corridor is outlined.
   * @property {Property | Color} [outlineColor=Color.BLACK] A Property specifying the {@link Color} of the outline.
   * @property {Property | number} [outlineWidth=1.0] A numeric Property specifying the width of the outline.
   * @property {Property | ShadowMode} [shadows=ShadowMode.DISABLED] An enum Property specifying whether the corridor casts or receives shadows from light sources.
   * @property {Property | DistanceDisplayCondition} [distanceDisplayCondition] A Property specifying at what distance from the camera that this corridor will be displayed.
   * @property {Property | ClassificationType} [classificationType=ClassificationType.BOTH] An enum Property specifying whether this corridor will classify terrain, 3D Tiles, or both when on the ground.
   * @property {ConstantProperty | number} [zIndex] A Property specifying the zIndex of the corridor, used for ordering.  Only has an effect if height and extrudedHeight are undefined, and if the corridor is static.
   */

  /**
   * Describes a corridor, which is a shape defined by a centerline and width that
   * conforms to the curvature of the globe. It can be placed on the surface or at altitude
   * and can optionally be extruded into a volume.
   *
   * @alias CorridorGraphics
   * @constructor
   *
   * @param {CorridorGraphics.ConstructorOptions} [options] Object describing initialization options
   *
   * @see Entity
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Corridor.html|Cesium Sandcastle Corridor Demo}
   */
  function CorridorGraphics(options) {
    this._definitionChanged = new Event();
    this._show = undefined;
    this._showSubscription = undefined;
    this._positions = undefined;
    this._positionsSubscription = undefined;
    this._width = undefined;
    this._widthSubscription = undefined;
    this._height = undefined;
    this._heightSubscription = undefined;
    this._heightReference = undefined;
    this._heightReferenceSubscription = undefined;
    this._extrudedHeight = undefined;
    this._extrudedHeightSubscription = undefined;
    this._extrudedHeightReference = undefined;
    this._extrudedHeightReferenceSubscription = undefined;
    this._cornerType = undefined;
    this._cornerTypeSubscription = undefined;
    this._granularity = undefined;
    this._granularitySubscription = undefined;
    this._fill = undefined;
    this._fillSubscription = undefined;
    this._material = undefined;
    this._materialSubscription = undefined;
    this._outline = undefined;
    this._outlineSubscription = undefined;
    this._outlineColor = undefined;
    this._outlineColorSubscription = undefined;
    this._outlineWidth = undefined;
    this._outlineWidthSubscription = undefined;
    this._shadows = undefined;
    this._shadowsSubscription = undefined;
    this._distanceDisplayCondition = undefined;
    this._distanceDisplayConditionSubscription = undefined;
    this._classificationType = undefined;
    this._classificationTypeSubscription = undefined;
    this._zIndex = undefined;
    this._zIndexSubscription = undefined;

    this.merge(defaultValue(options, defaultValue.EMPTY_OBJECT));
  }

  Object.defineProperties(CorridorGraphics.prototype, {
    /**
     * Gets the event that is raised whenever a property or sub-property is changed or modified.
     * @memberof CorridorGraphics.prototype
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },

    /**
     * Gets or sets the boolean Property specifying the visibility of the corridor.
     * @memberof CorridorGraphics.prototype
     * @type {Property|undefined}
     * @default true
     */
    show: createPropertyDescriptor("show"),

    /**
     * Gets or sets a Property specifying the array of {@link Cartesian3} positions that define the centerline of the corridor.
     * @memberof CorridorGraphics.prototype
     * @type {Property|undefined}
     */
    positions: createPropertyDescriptor("positions"),

    /**
     * Gets or sets the numeric Property specifying the width of the outline.
     * @memberof CorridorGraphics.prototype
     * @type {Property|undefined}
     */
    width: createPropertyDescriptor("width"),

    /**
     * Gets or sets the numeric Property specifying the altitude of the corridor.
     * @memberof CorridorGraphics.prototype
     * @type {Property|undefined}
     * @default 0.0
     */
    height: createPropertyDescriptor("height"),

    /**
     * Gets or sets the Property specifying the {@link HeightReference}.
     * @memberof CorridorGraphics.prototype
     * @type {Property|undefined}
     * @default HeightReference.NONE
     */
    heightReference: createPropertyDescriptor("heightReference"),

    /**
     * Gets or sets the numeric Property specifying the altitude of the corridor extrusion.
     * Setting this property creates a corridor shaped volume starting at height and ending
     * at this altitude.
     * @memberof CorridorGraphics.prototype
     * @type {Property|undefined}
     */
    extrudedHeight: createPropertyDescriptor("extrudedHeight"),

    /**
     * Gets or sets the Property specifying the extruded {@link HeightReference}.
     * @memberof CorridorGraphics.prototype
     * @type {Property|undefined}
     * @default HeightReference.NONE
     */
    extrudedHeightReference: createPropertyDescriptor("extrudedHeightReference"),

    /**
     * Gets or sets the {@link CornerType} Property specifying how corners are styled.
     * @memberof CorridorGraphics.prototype
     * @type {Property|undefined}
     * @default CornerType.ROUNDED
     */
    cornerType: createPropertyDescriptor("cornerType"),

    /**
     * Gets or sets the numeric Property specifying the sampling distance between each latitude and longitude point.
     * @memberof CorridorGraphics.prototype
     * @type {Property|undefined}
     * @default {CesiumMath.RADIANS_PER_DEGREE}
     */
    granularity: createPropertyDescriptor("granularity"),

    /**
     * Gets or sets the boolean Property specifying whether the corridor is filled with the provided material.
     * @memberof CorridorGraphics.prototype
     * @type {Property|undefined}
     * @default true
     */
    fill: createPropertyDescriptor("fill"),

    /**
     * Gets or sets the Property specifying the material used to fill the corridor.
     * @memberof CorridorGraphics.prototype
     * @type {MaterialProperty|undefined}
     * @default Color.WHITE
     */
    material: createMaterialPropertyDescriptor("material"),

    /**
     * Gets or sets the Property specifying whether the corridor is outlined.
     * @memberof CorridorGraphics.prototype
     * @type {Property|undefined}
     * @default false
     */
    outline: createPropertyDescriptor("outline"),

    /**
     * Gets or sets the Property specifying the {@link Color} of the outline.
     * @memberof CorridorGraphics.prototype
     * @type {Property|undefined}
     * @default Color.BLACK
     */
    outlineColor: createPropertyDescriptor("outlineColor"),

    /**
     * Gets or sets the numeric Property specifying the width of the outline.
     * <p>
     * Note: This property will be ignored on all major browsers on Windows platforms. For details, see (@link https://github.com/CesiumGS/cesium/issues/40}.
     * </p>
     * @memberof CorridorGraphics.prototype
     * @type {Property|undefined}
     * @default 1.0
     */
    outlineWidth: createPropertyDescriptor("outlineWidth"),

    /**
     * Get or sets the enum Property specifying whether the corridor
     * casts or receives shadows from light sources.
     * @memberof CorridorGraphics.prototype
     * @type {Property|undefined}
     * @default ShadowMode.DISABLED
     */
    shadows: createPropertyDescriptor("shadows"),

    /**
     * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this corridor will be displayed.
     * @memberof CorridorGraphics.prototype
     * @type {Property|undefined}
     */
    distanceDisplayCondition: createPropertyDescriptor(
      "distanceDisplayCondition"
    ),

    /**
     * Gets or sets the {@link ClassificationType} Property specifying whether this corridor will classify terrain, 3D Tiles, or both when on the ground.
     * @memberof CorridorGraphics.prototype
     * @type {Property|undefined}
     * @default ClassificationType.BOTH
     */
    classificationType: createPropertyDescriptor("classificationType"),

    /**
     * Gets or sets the zIndex Property specifying the ordering of the corridor.  Only has an effect if the coridor is static and neither height or exturdedHeight are specified.
     * @memberof CorridorGraphics.prototype
     * @type {ConstantProperty|undefined}
     * @default 0
     */
    zIndex: createPropertyDescriptor("zIndex"),
  });

  /**
   * Duplicates this instance.
   *
   * @param {CorridorGraphics} [result] The object onto which to store the result.
   * @returns {CorridorGraphics} The modified result parameter or a new instance if one was not provided.
   */
  CorridorGraphics.prototype.clone = function (result) {
    if (!defined(result)) {
      return new CorridorGraphics(this);
    }
    result.show = this.show;
    result.positions = this.positions;
    result.width = this.width;
    result.height = this.height;
    result.heightReference = this.heightReference;
    result.extrudedHeight = this.extrudedHeight;
    result.extrudedHeightReference = this.extrudedHeightReference;
    result.cornerType = this.cornerType;
    result.granularity = this.granularity;
    result.fill = this.fill;
    result.material = this.material;
    result.outline = this.outline;
    result.outlineColor = this.outlineColor;
    result.outlineWidth = this.outlineWidth;
    result.shadows = this.shadows;
    result.distanceDisplayCondition = this.distanceDisplayCondition;
    result.classificationType = this.classificationType;
    result.zIndex = this.zIndex;
    return result;
  };

  /**
   * Assigns each unassigned property on this object to the value
   * of the same property on the provided source object.
   *
   * @param {CorridorGraphics} source The object to be merged into this object.
   */
  CorridorGraphics.prototype.merge = function (source) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(source)) {
      throw new DeveloperError("source is required.");
    }
    //>>includeEnd('debug');

    this.show = defaultValue(this.show, source.show);
    this.positions = defaultValue(this.positions, source.positions);
    this.width = defaultValue(this.width, source.width);
    this.height = defaultValue(this.height, source.height);
    this.heightReference = defaultValue(
      this.heightReference,
      source.heightReference
    );
    this.extrudedHeight = defaultValue(
      this.extrudedHeight,
      source.extrudedHeight
    );
    this.extrudedHeightReference = defaultValue(
      this.extrudedHeightReference,
      source.extrudedHeightReference
    );
    this.cornerType = defaultValue(this.cornerType, source.cornerType);
    this.granularity = defaultValue(this.granularity, source.granularity);
    this.fill = defaultValue(this.fill, source.fill);
    this.material = defaultValue(this.material, source.material);
    this.outline = defaultValue(this.outline, source.outline);
    this.outlineColor = defaultValue(this.outlineColor, source.outlineColor);
    this.outlineWidth = defaultValue(this.outlineWidth, source.outlineWidth);
    this.shadows = defaultValue(this.shadows, source.shadows);
    this.distanceDisplayCondition = defaultValue(
      this.distanceDisplayCondition,
      source.distanceDisplayCondition
    );
    this.classificationType = defaultValue(
      this.classificationType,
      source.classificationType
    );
    this.zIndex = defaultValue(this.zIndex, source.zIndex);
  };

  function createRawProperty(value) {
    return value;
  }

  /**
   * @private
   */
  function createRawPropertyDescriptor(name, configurable) {
    return createPropertyDescriptor(name, configurable, createRawProperty);
  }

  /**
   * @typedef {Object} CylinderGraphics.ConstructorOptions
   *
   * Initialization options for the CylinderGraphics constructor
   *
   * @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the cylinder.
   * @property {Property | number} [length] A numeric Property specifying the length of the cylinder.
   * @property {Property | number} [topRadius] A numeric Property specifying the radius of the top of the cylinder.
   * @property {Property | number} [bottomRadius] A numeric Property specifying the radius of the bottom of the cylinder.
   * @property {Property | HeightReference} [heightReference=HeightReference.NONE] A Property specifying what the height from the entity position is relative to.
   * @property {Property | boolean} [fill=true] A boolean Property specifying whether the cylinder is filled with the provided material.
   * @property {MaterialProperty | Color} [material=Color.WHITE] A Property specifying the material used to fill the cylinder.
   * @property {Property | boolean} [outline=false] A boolean Property specifying whether the cylinder is outlined.
   * @property {Property | Color} [outlineColor=Color.BLACK] A Property specifying the {@link Color} of the outline.
   * @property {Property | number} [outlineWidth=1.0] A numeric Property specifying the width of the outline.
   * @property {Property | number} [numberOfVerticalLines=16] A numeric Property specifying the number of vertical lines to draw along the perimeter for the outline.
   * @property {Property | number} [slices=128] The number of edges around the perimeter of the cylinder.
   * @property {Property | ShadowMode} [shadows=ShadowMode.DISABLED] An enum Property specifying whether the cylinder casts or receives shadows from light sources.
   * @property {Property | DistanceDisplayCondition} [distanceDisplayCondition] A Property specifying at what distance from the camera that this cylinder will be displayed.
   */

  /**
   * Describes a cylinder, truncated cone, or cone defined by a length, top radius, and bottom radius.
   * The center position and orientation are determined by the containing {@link Entity}.
   *
   * @alias CylinderGraphics
   * @constructor
   *
   * @param {CylinderGraphics.ConstructorOptions} [options] Object describing initialization options
   */
  function CylinderGraphics(options) {
    this._definitionChanged = new Event();
    this._show = undefined;
    this._showSubscription = undefined;
    this._length = undefined;
    this._lengthSubscription = undefined;
    this._topRadius = undefined;
    this._topRadiusSubscription = undefined;
    this._bottomRadius = undefined;
    this._bottomRadiusSubscription = undefined;
    this._heightReference = undefined;
    this._heightReferenceSubscription = undefined;
    this._fill = undefined;
    this._fillSubscription = undefined;
    this._material = undefined;
    this._materialSubscription = undefined;
    this._outline = undefined;
    this._outlineSubscription = undefined;
    this._outlineColor = undefined;
    this._outlineColorSubscription = undefined;
    this._outlineWidth = undefined;
    this._outlineWidthSubscription = undefined;
    this._numberOfVerticalLines = undefined;
    this._numberOfVerticalLinesSubscription = undefined;
    this._slices = undefined;
    this._slicesSubscription = undefined;
    this._shadows = undefined;
    this._shadowsSubscription = undefined;
    this._distanceDisplayCondition = undefined;
    this._distanceDisplayConditionSubscription = undefined;

    this.merge(defaultValue(options, defaultValue.EMPTY_OBJECT));
  }

  Object.defineProperties(CylinderGraphics.prototype, {
    /**
     * Gets the event that is raised whenever a property or sub-property is changed or modified.
     * @memberof CylinderGraphics.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },

    /**
     * Gets or sets the boolean Property specifying the visibility of the cylinder.
     * @memberof CylinderGraphics.prototype
     * @type {Property|undefined}
     * @default true
     */
    show: createPropertyDescriptor("show"),

    /**
     * Gets or sets the numeric Property specifying the length of the cylinder.
     * @memberof CylinderGraphics.prototype
     * @type {Property|undefined}
     */
    length: createPropertyDescriptor("length"),

    /**
     * Gets or sets the numeric Property specifying the radius of the top of the cylinder.
     * @memberof CylinderGraphics.prototype
     * @type {Property|undefined}
     */
    topRadius: createPropertyDescriptor("topRadius"),

    /**
     * Gets or sets the numeric Property specifying the radius of the bottom of the cylinder.
     * @memberof CylinderGraphics.prototype
     * @type {Property|undefined}
     */
    bottomRadius: createPropertyDescriptor("bottomRadius"),

    /**
     * Gets or sets the Property specifying the {@link HeightReference}.
     * @memberof CylinderGraphics.prototype
     * @type {Property|undefined}
     * @default HeightReference.NONE
     */
    heightReference: createPropertyDescriptor("heightReference"),

    /**
     * Gets or sets the boolean Property specifying whether the cylinder is filled with the provided material.
     * @memberof CylinderGraphics.prototype
     * @type {Property|undefined}
     * @default true
     */
    fill: createPropertyDescriptor("fill"),

    /**
     * Gets or sets the Property specifying the material used to fill the cylinder.
     * @memberof CylinderGraphics.prototype
     * @type {MaterialProperty|undefined}
     * @default Color.WHITE
     */
    material: createMaterialPropertyDescriptor("material"),

    /**
     * Gets or sets the boolean Property specifying whether the cylinder is outlined.
     * @memberof CylinderGraphics.prototype
     * @type {Property|undefined}
     * @default false
     */
    outline: createPropertyDescriptor("outline"),

    /**
     * Gets or sets the Property specifying the {@link Color} of the outline.
     * @memberof CylinderGraphics.prototype
     * @type {Property|undefined}
     * @default Color.BLACK
     */
    outlineColor: createPropertyDescriptor("outlineColor"),

    /**
     * Gets or sets the numeric Property specifying the width of the outline.
     * <p>
     * Note: This property will be ignored on all major browsers on Windows platforms. For details, see (@link https://github.com/CesiumGS/cesium/issues/40}.
     * </p>
     * @memberof CylinderGraphics.prototype
     * @type {Property|undefined}
     * @default 1.0
     */
    outlineWidth: createPropertyDescriptor("outlineWidth"),

    /**
     * Gets or sets the Property specifying the number of vertical lines to draw along the perimeter for the outline.
     * @memberof CylinderGraphics.prototype
     * @type {Property|undefined}
     * @default 16
     */
    numberOfVerticalLines: createPropertyDescriptor("numberOfVerticalLines"),

    /**
     * Gets or sets the Property specifying the number of edges around the perimeter of the cylinder.
     * @memberof CylinderGraphics.prototype
     * @type {Property|undefined}
     * @default 128
     */
    slices: createPropertyDescriptor("slices"),

    /**
     * Get or sets the enum Property specifying whether the cylinder
     * casts or receives shadows from light sources.
     * @memberof CylinderGraphics.prototype
     * @type {Property|undefined}
     * @default ShadowMode.DISABLED
     */
    shadows: createPropertyDescriptor("shadows"),

    /**
     * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this cylinder will be displayed.
     * @memberof CylinderGraphics.prototype
     * @type {Property|undefined}
     */
    distanceDisplayCondition: createPropertyDescriptor(
      "distanceDisplayCondition"
    ),
  });

  /**
   * Duplicates this instance.
   *
   * @param {CylinderGraphics} [result] The object onto which to store the result.
   * @returns {CylinderGraphics} The modified result parameter or a new instance if one was not provided.
   */
  CylinderGraphics.prototype.clone = function (result) {
    if (!defined(result)) {
      return new CylinderGraphics(this);
    }
    result.show = this.show;
    result.length = this.length;
    result.topRadius = this.topRadius;
    result.bottomRadius = this.bottomRadius;
    result.heightReference = this.heightReference;
    result.fill = this.fill;
    result.material = this.material;
    result.outline = this.outline;
    result.outlineColor = this.outlineColor;
    result.outlineWidth = this.outlineWidth;
    result.numberOfVerticalLines = this.numberOfVerticalLines;
    result.slices = this.slices;
    result.shadows = this.shadows;
    result.distanceDisplayCondition = this.distanceDisplayCondition;
    return result;
  };

  /**
   * Assigns each unassigned property on this object to the value
   * of the same property on the provided source object.
   *
   * @param {CylinderGraphics} source The object to be merged into this object.
   */
  CylinderGraphics.prototype.merge = function (source) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(source)) {
      throw new DeveloperError("source is required.");
    }
    //>>includeEnd('debug');

    this.show = defaultValue(this.show, source.show);
    this.length = defaultValue(this.length, source.length);
    this.topRadius = defaultValue(this.topRadius, source.topRadius);
    this.bottomRadius = defaultValue(this.bottomRadius, source.bottomRadius);
    this.heightReference = defaultValue(
      this.heightReference,
      source.heightReference
    );
    this.fill = defaultValue(this.fill, source.fill);
    this.material = defaultValue(this.material, source.material);
    this.outline = defaultValue(this.outline, source.outline);
    this.outlineColor = defaultValue(this.outlineColor, source.outlineColor);
    this.outlineWidth = defaultValue(this.outlineWidth, source.outlineWidth);
    this.numberOfVerticalLines = defaultValue(
      this.numberOfVerticalLines,
      source.numberOfVerticalLines
    );
    this.slices = defaultValue(this.slices, source.slices);
    this.shadows = defaultValue(this.shadows, source.shadows);
    this.distanceDisplayCondition = defaultValue(
      this.distanceDisplayCondition,
      source.distanceDisplayCondition
    );
  };

  /**
   * @typedef {Object} EllipseGraphics.ConstructorOptions
   *
   * Initialization options for the EllipseGraphics constructor
   *
   * @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the ellipse.
   * @property {Property | number} [semiMajorAxis] The numeric Property specifying the semi-major axis.
   * @property {Property | number} [semiMinorAxis] The numeric Property specifying the semi-minor axis.
   * @property {Property | number} [height=0] A numeric Property specifying the altitude of the ellipse relative to the ellipsoid surface.
   * @property {Property | HeightReference} [heightReference=HeightReference.NONE] A Property specifying what the height is relative to.
   * @property {Property | number} [extrudedHeight] A numeric Property specifying the altitude of the ellipse's extruded face relative to the ellipsoid surface.
   * @property {Property | HeightReference} [extrudedHeightReference=HeightReference.NONE] A Property specifying what the extrudedHeight is relative to.
   * @property {Property | number} [rotation=0.0] A numeric property specifying the rotation of the ellipse counter-clockwise from north.
   * @property {Property | number} [stRotation=0.0] A numeric property specifying the rotation of the ellipse texture counter-clockwise from north.
   * @property {Property | number} [granularity=Cesium.Math.RADIANS_PER_DEGREE] A numeric Property specifying the angular distance between points on the ellipse.
   * @property {Property | boolean} [fill=true] A boolean Property specifying whether the ellipse is filled with the provided material.
   * @property {MaterialProperty | Color} [material=Color.WHITE] A Property specifying the material used to fill the ellipse.
   * @property {Property | boolean} [outline=false] A boolean Property specifying whether the ellipse is outlined.
   * @property {Property | Color} [outlineColor=Color.BLACK] A Property specifying the {@link Color} of the outline.
   * @property {Property | number} [outlineWidth=1.0] A numeric Property specifying the width of the outline.
   * @property {Property | number} [numberOfVerticalLines=16] A numeric Property specifying the number of vertical lines to draw along the perimeter for the outline.
   * @property {Property | ShadowMode} [shadows=ShadowMode.DISABLED] An enum Property specifying whether the ellipse casts or receives shadows from light sources.
   * @property {Property | DistanceDisplayCondition} [distanceDisplayCondition] A Property specifying at what distance from the camera that this ellipse will be displayed.
   * @property {Property | ClassificationType} [classificationType=ClassificationType.BOTH] An enum Property specifying whether this ellipse will classify terrain, 3D Tiles, or both when on the ground.
   * @property {ConstantProperty | number} [zIndex=0] A property specifying the zIndex of the Ellipse.  Used for ordering ground geometry.  Only has an effect if the ellipse is constant and neither height or exturdedHeight are specified.
   */

  /**
   * Describes an ellipse defined by a center point and semi-major and semi-minor axes.
   * The ellipse conforms to the curvature of the globe and can be placed on the surface or
   * at altitude and can optionally be extruded into a volume.
   * The center point is determined by the containing {@link Entity}.
   *
   * @alias EllipseGraphics
   * @constructor
   *
   * @param {EllipseGraphics.ConstructorOptions} [options] Object describing initialization options
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Circles and Ellipses.html|Cesium Sandcastle Circles and Ellipses Demo}
   */
  function EllipseGraphics(options) {
    this._definitionChanged = new Event();
    this._show = undefined;
    this._showSubscription = undefined;
    this._semiMajorAxis = undefined;
    this._semiMajorAxisSubscription = undefined;
    this._semiMinorAxis = undefined;
    this._semiMinorAxisSubscription = undefined;
    this._height = undefined;
    this._heightSubscription = undefined;
    this._heightReference = undefined;
    this._heightReferenceSubscription = undefined;
    this._extrudedHeight = undefined;
    this._extrudedHeightSubscription = undefined;
    this._extrudedHeightReference = undefined;
    this._extrudedHeightReferenceSubscription = undefined;
    this._rotation = undefined;
    this._rotationSubscription = undefined;
    this._stRotation = undefined;
    this._stRotationSubscription = undefined;
    this._granularity = undefined;
    this._granularitySubscription = undefined;
    this._fill = undefined;
    this._fillSubscription = undefined;
    this._material = undefined;
    this._materialSubscription = undefined;
    this._outline = undefined;
    this._outlineSubscription = undefined;
    this._outlineColor = undefined;
    this._outlineColorSubscription = undefined;
    this._outlineWidth = undefined;
    this._outlineWidthSubscription = undefined;
    this._numberOfVerticalLines = undefined;
    this._numberOfVerticalLinesSubscription = undefined;
    this._shadows = undefined;
    this._shadowsSubscription = undefined;
    this._distanceDisplayCondition = undefined;
    this._distanceDisplayConditionSubscription = undefined;
    this._classificationType = undefined;
    this._classificationTypeSubscription = undefined;
    this._zIndex = undefined;
    this._zIndexSubscription = undefined;

    this.merge(defaultValue(options, defaultValue.EMPTY_OBJECT));
  }

  Object.defineProperties(EllipseGraphics.prototype, {
    /**
     * Gets the event that is raised whenever a property or sub-property is changed or modified.
     * @memberof EllipseGraphics.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },

    /**
     * Gets or sets the boolean Property specifying the visibility of the ellipse.
     * @memberof EllipseGraphics.prototype
     * @type {Property|undefined}
     * @default true
     */
    show: createPropertyDescriptor("show"),

    /**
     * Gets or sets the numeric Property specifying the semi-major axis.
     * @memberof EllipseGraphics.prototype
     * @type {Property|undefined}
     */
    semiMajorAxis: createPropertyDescriptor("semiMajorAxis"),

    /**
     * Gets or sets the numeric Property specifying the semi-minor axis.
     * @memberof EllipseGraphics.prototype
     * @type {Property|undefined}
     */
    semiMinorAxis: createPropertyDescriptor("semiMinorAxis"),

    /**
     * Gets or sets the numeric Property specifying the altitude of the ellipse.
     * @memberof EllipseGraphics.prototype
     * @type {Property|undefined}
     * @default 0.0
     */
    height: createPropertyDescriptor("height"),

    /**
     * Gets or sets the Property specifying the {@link HeightReference}.
     * @memberof EllipseGraphics.prototype
     * @type {Property|undefined}
     * @default HeightReference.NONE
     */
    heightReference: createPropertyDescriptor("heightReference"),

    /**
     * Gets or sets the numeric Property specifying the altitude of the ellipse extrusion.
     * Setting this property creates volume starting at height and ending at this altitude.
     * @memberof EllipseGraphics.prototype
     * @type {Property|undefined}
     */
    extrudedHeight: createPropertyDescriptor("extrudedHeight"),

    /**
     * Gets or sets the Property specifying the extruded {@link HeightReference}.
     * @memberof EllipseGraphics.prototype
     * @type {Property|undefined}
     * @default HeightReference.NONE
     */
    extrudedHeightReference: createPropertyDescriptor("extrudedHeightReference"),

    /**
     * Gets or sets the numeric property specifying the rotation of the ellipse counter-clockwise from north.
     * @memberof EllipseGraphics.prototype
     * @type {Property|undefined}
     * @default 0
     */
    rotation: createPropertyDescriptor("rotation"),

    /**
     * Gets or sets the numeric property specifying the rotation of the ellipse texture counter-clockwise from north.
     * @memberof EllipseGraphics.prototype
     * @type {Property|undefined}
     * @default 0
     */
    stRotation: createPropertyDescriptor("stRotation"),

    /**
     * Gets or sets the numeric Property specifying the angular distance between points on the ellipse.
     * @memberof EllipseGraphics.prototype
     * @type {Property|undefined}
     * @default {CesiumMath.RADIANS_PER_DEGREE}
     */
    granularity: createPropertyDescriptor("granularity"),

    /**
     * Gets or sets the boolean Property specifying whether the ellipse is filled with the provided material.
     * @memberof EllipseGraphics.prototype
     * @type {Property|undefined}
     * @default true
     */
    fill: createPropertyDescriptor("fill"),

    /**
     * Gets or sets the Property specifying the material used to fill the ellipse.
     * @memberof EllipseGraphics.prototype
     * @type {MaterialProperty|undefined}
     * @default Color.WHITE
     */
    material: createMaterialPropertyDescriptor("material"),

    /**
     * Gets or sets the Property specifying whether the ellipse is outlined.
     * @memberof EllipseGraphics.prototype
     * @type {Property|undefined}
     * @default false
     */
    outline: createPropertyDescriptor("outline"),

    /**
     * Gets or sets the Property specifying the {@link Color} of the outline.
     * @memberof EllipseGraphics.prototype
     * @type {Property|undefined}
     * @default Color.BLACK
     */
    outlineColor: createPropertyDescriptor("outlineColor"),

    /**
     * Gets or sets the numeric Property specifying the width of the outline.
     * <p>
     * Note: This property will be ignored on all major browsers on Windows platforms. For details, see (@link https://github.com/CesiumGS/cesium/issues/40}.
     * </p>
     * @memberof EllipseGraphics.prototype
     * @type {Property|undefined}
     * @default 1.0
     */
    outlineWidth: createPropertyDescriptor("outlineWidth"),

    /**
     * Gets or sets the numeric Property specifying the number of vertical lines to draw along the perimeter for the outline.
     * @memberof EllipseGraphics.prototype
     * @type {Property|undefined}
     * @default 16
     */
    numberOfVerticalLines: createPropertyDescriptor("numberOfVerticalLines"),

    /**
     * Get or sets the enum Property specifying whether the ellipse
     * casts or receives shadows from light sources.
     * @memberof EllipseGraphics.prototype
     * @type {Property|undefined}
     * @default ShadowMode.DISABLED
     */
    shadows: createPropertyDescriptor("shadows"),

    /**
     * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this ellipse will be displayed.
     * @memberof EllipseGraphics.prototype
     * @type {Property|undefined}
     */
    distanceDisplayCondition: createPropertyDescriptor(
      "distanceDisplayCondition"
    ),

    /**
     * Gets or sets the {@link ClassificationType} Property specifying whether this ellipse will classify terrain, 3D Tiles, or both when on the ground.
     * @memberof EllipseGraphics.prototype
     * @type {Property|undefined}
     * @default ClassificationType.BOTH
     */
    classificationType: createPropertyDescriptor("classificationType"),

    /**
     * Gets or sets the zIndex Property specifying the ellipse ordering.  Only has an effect if the ellipse is constant and neither height or extrudedHeight are specified
     * @memberof EllipseGraphics.prototype
     * @type {ConstantProperty|undefined}
     * @default 0
     */
    zIndex: createPropertyDescriptor("zIndex"),
  });

  /**
   * Duplicates this instance.
   *
   * @param {EllipseGraphics} [result] The object onto which to store the result.
   * @returns {EllipseGraphics} The modified result parameter or a new instance if one was not provided.
   */
  EllipseGraphics.prototype.clone = function (result) {
    if (!defined(result)) {
      return new EllipseGraphics(this);
    }
    result.show = this.show;
    result.semiMajorAxis = this.semiMajorAxis;
    result.semiMinorAxis = this.semiMinorAxis;
    result.height = this.height;
    result.heightReference = this.heightReference;
    result.extrudedHeight = this.extrudedHeight;
    result.extrudedHeightReference = this.extrudedHeightReference;
    result.rotation = this.rotation;
    result.stRotation = this.stRotation;
    result.granularity = this.granularity;
    result.fill = this.fill;
    result.material = this.material;
    result.outline = this.outline;
    result.outlineColor = this.outlineColor;
    result.outlineWidth = this.outlineWidth;
    result.numberOfVerticalLines = this.numberOfVerticalLines;
    result.shadows = this.shadows;
    result.distanceDisplayCondition = this.distanceDisplayCondition;
    result.classificationType = this.classificationType;
    result.zIndex = this.zIndex;
    return result;
  };

  /**
   * Assigns each unassigned property on this object to the value
   * of the same property on the provided source object.
   *
   * @param {EllipseGraphics} source The object to be merged into this object.
   */
  EllipseGraphics.prototype.merge = function (source) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(source)) {
      throw new DeveloperError("source is required.");
    }
    //>>includeEnd('debug');

    this.show = defaultValue(this.show, source.show);
    this.semiMajorAxis = defaultValue(this.semiMajorAxis, source.semiMajorAxis);
    this.semiMinorAxis = defaultValue(this.semiMinorAxis, source.semiMinorAxis);
    this.height = defaultValue(this.height, source.height);
    this.heightReference = defaultValue(
      this.heightReference,
      source.heightReference
    );
    this.extrudedHeight = defaultValue(
      this.extrudedHeight,
      source.extrudedHeight
    );
    this.extrudedHeightReference = defaultValue(
      this.extrudedHeightReference,
      source.extrudedHeightReference
    );
    this.rotation = defaultValue(this.rotation, source.rotation);
    this.stRotation = defaultValue(this.stRotation, source.stRotation);
    this.granularity = defaultValue(this.granularity, source.granularity);
    this.fill = defaultValue(this.fill, source.fill);
    this.material = defaultValue(this.material, source.material);
    this.outline = defaultValue(this.outline, source.outline);
    this.outlineColor = defaultValue(this.outlineColor, source.outlineColor);
    this.outlineWidth = defaultValue(this.outlineWidth, source.outlineWidth);
    this.numberOfVerticalLines = defaultValue(
      this.numberOfVerticalLines,
      source.numberOfVerticalLines
    );
    this.shadows = defaultValue(this.shadows, source.shadows);
    this.distanceDisplayCondition = defaultValue(
      this.distanceDisplayCondition,
      source.distanceDisplayCondition
    );
    this.classificationType = defaultValue(
      this.classificationType,
      source.classificationType
    );
    this.zIndex = defaultValue(this.zIndex, source.zIndex);
  };

  /**
   * @typedef {Object} EllipsoidGraphics.ConstructorOptions
   *
   * Initialization options for the EllipsoidGraphics constructor
   *
   * @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the ellipsoid.
   * @property {Property | Cartesian3} [radii] A {@link Cartesian3} Property specifying the radii of the ellipsoid.
   * @property {Property | Cartesian3} [innerRadii] A {@link Cartesian3} Property specifying the inner radii of the ellipsoid.
   * @property {Property | number} [minimumClock=0.0] A Property specifying the minimum clock angle of the ellipsoid.
   * @property {Property | number} [maximumClock=2*PI] A Property specifying the maximum clock angle of the ellipsoid.
   * @property {Property | number} [minimumCone=0.0] A Property specifying the minimum cone angle of the ellipsoid.
   * @property {Property | number} [maximumCone=PI] A Property specifying the maximum cone angle of the ellipsoid.
   * @property {Property | HeightReference} [heightReference=HeightReference.NONE] A Property specifying what the height from the entity position is relative to.
   * @property {Property | boolean} [fill=true] A boolean Property specifying whether the ellipsoid is filled with the provided material.
   * @property {MaterialProperty | Color} [material=Color.WHITE] A Property specifying the material used to fill the ellipsoid.
   * @property {Property | boolean} [outline=false] A boolean Property specifying whether the ellipsoid is outlined.
   * @property {Property | Color} [outlineColor=Color.BLACK] A Property specifying the {@link Color} of the outline.
   * @property {Property | number} [outlineWidth=1.0] A numeric Property specifying the width of the outline.
   * @property {Property | number} [stackPartitions=64] A Property specifying the number of stacks.
   * @property {Property | number} [slicePartitions=64] A Property specifying the number of radial slices.
   * @property {Property | number} [subdivisions=128] A Property specifying the number of samples per outline ring, determining the granularity of the curvature.
   * @property {Property | ShadowMode} [shadows=ShadowMode.DISABLED] An enum Property specifying whether the ellipsoid casts or receives shadows from light sources.
   * @property {Property | DistanceDisplayCondition} [distanceDisplayCondition] A Property specifying at what distance from the camera that this ellipsoid will be displayed.
   */

  /**
   * Describe an ellipsoid or sphere.  The center position and orientation are determined by the containing {@link Entity}.
   *
   * @alias EllipsoidGraphics
   * @constructor
   *
   * @param {EllipsoidGraphics.ConstructorOptions} [options] Object describing initialization options
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Spheres%20and%20Ellipsoids.html|Cesium Sandcastle Spheres and Ellipsoids Demo}
   */
  function EllipsoidGraphics(options) {
    this._definitionChanged = new Event();
    this._show = undefined;
    this._showSubscription = undefined;
    this._radii = undefined;
    this._radiiSubscription = undefined;
    this._innerRadii = undefined;
    this._innerRadiiSubscription = undefined;
    this._minimumClock = undefined;
    this._minimumClockSubscription = undefined;
    this._maximumClock = undefined;
    this._maximumClockSubscription = undefined;
    this._minimumCone = undefined;
    this._minimumConeSubscription = undefined;
    this._maximumCone = undefined;
    this._maximumConeSubscription = undefined;
    this._heightReference = undefined;
    this._heightReferenceSubscription = undefined;
    this._fill = undefined;
    this._fillSubscription = undefined;
    this._material = undefined;
    this._materialSubscription = undefined;
    this._outline = undefined;
    this._outlineSubscription = undefined;
    this._outlineColor = undefined;
    this._outlineColorSubscription = undefined;
    this._outlineWidth = undefined;
    this._outlineWidthSubscription = undefined;
    this._stackPartitions = undefined;
    this._stackPartitionsSubscription = undefined;
    this._slicePartitions = undefined;
    this._slicePartitionsSubscription = undefined;
    this._subdivisions = undefined;
    this._subdivisionsSubscription = undefined;
    this._shadows = undefined;
    this._shadowsSubscription = undefined;
    this._distanceDisplayCondition = undefined;
    this._distanceDisplayConditionSubscription = undefined;

    this.merge(defaultValue(options, defaultValue.EMPTY_OBJECT));
  }

  Object.defineProperties(EllipsoidGraphics.prototype, {
    /**
     * Gets the event that is raised whenever a property or sub-property is changed or modified.
     * @memberof EllipsoidGraphics.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },

    /**
     * Gets or sets the boolean Property specifying the visibility of the ellipsoid.
     * @memberof EllipsoidGraphics.prototype
     * @type {Property|undefined}
     * @default true
     */
    show: createPropertyDescriptor("show"),

    /**
     * Gets or sets the {@link Cartesian3} {@link Property} specifying the radii of the ellipsoid.
     * @memberof EllipsoidGraphics.prototype
     * @type {Property|undefined}
     */
    radii: createPropertyDescriptor("radii"),

    /**
     * Gets or sets the {@link Cartesian3} {@link Property} specifying the inner radii of the ellipsoid.
     * @memberof EllipsoidGraphics.prototype
     * @type {Property|undefined}
     * @default radii
     */
    innerRadii: createPropertyDescriptor("innerRadii"),

    /**
     * Gets or sets the Property specifying the minimum clock angle of the ellipsoid.
     * @memberof EllipsoidGraphics.prototype
     * @type {Property|undefined}
     * @default 0.0
     */
    minimumClock: createPropertyDescriptor("minimumClock"),

    /**
     * Gets or sets the Property specifying the maximum clock angle of the ellipsoid.
     * @memberof EllipsoidGraphics.prototype
     * @type {Property|undefined}
     * @default 2*PI
     */
    maximumClock: createPropertyDescriptor("maximumClock"),

    /**
     * Gets or sets the Property specifying the minimum cone angle of the ellipsoid.
     * @memberof EllipsoidGraphics.prototype
     * @type {Property|undefined}
     * @default 0.0
     */
    minimumCone: createPropertyDescriptor("minimumCone"),

    /**
     * Gets or sets the Property specifying the maximum cone angle of the ellipsoid.
     * @memberof EllipsoidGraphics.prototype
     * @type {Property|undefined}
     * @default PI
     */
    maximumCone: createPropertyDescriptor("maximumCone"),

    /**
     * Gets or sets the Property specifying the {@link HeightReference}.
     * @memberof EllipsoidGraphics.prototype
     * @type {Property|undefined}
     * @default HeightReference.NONE
     */
    heightReference: createPropertyDescriptor("heightReference"),

    /**
     * Gets or sets the boolean Property specifying whether the ellipsoid is filled with the provided material.
     * @memberof EllipsoidGraphics.prototype
     * @type {Property|undefined}
     * @default true
     */
    fill: createPropertyDescriptor("fill"),

    /**
     * Gets or sets the Property specifying the material used to fill the ellipsoid.
     * @memberof EllipsoidGraphics.prototype
     * @type {MaterialProperty}
     * @default Color.WHITE
     */
    material: createMaterialPropertyDescriptor("material"),

    /**
     * Gets or sets the Property specifying whether the ellipsoid is outlined.
     * @memberof EllipsoidGraphics.prototype
     * @type {Property|undefined}
     * @default false
     */
    outline: createPropertyDescriptor("outline"),

    /**
     * Gets or sets the Property specifying the {@link Color} of the outline.
     * @memberof EllipsoidGraphics.prototype
     * @type {Property|undefined}
     * @default Color.BLACK
     */
    outlineColor: createPropertyDescriptor("outlineColor"),

    /**
     * Gets or sets the numeric Property specifying the width of the outline.
     * <p>
     * Note: This property will be ignored on all major browsers on Windows platforms. For details, see (@link https://github.com/CesiumGS/cesium/issues/40}.
     * </p>
     * @memberof EllipsoidGraphics.prototype
     * @type {Property|undefined}
     * @default 1.0
     */
    outlineWidth: createPropertyDescriptor("outlineWidth"),

    /**
     * Gets or sets the Property specifying the number of stacks.
     * @memberof EllipsoidGraphics.prototype
     * @type {Property|undefined}
     * @default 64
     */
    stackPartitions: createPropertyDescriptor("stackPartitions"),

    /**
     * Gets or sets the Property specifying the number of radial slices per 360 degrees.
     * @memberof EllipsoidGraphics.prototype
     * @type {Property|undefined}
     * @default 64
     */
    slicePartitions: createPropertyDescriptor("slicePartitions"),

    /**
     * Gets or sets the Property specifying the number of samples per outline ring, determining the granularity of the curvature.
     * @memberof EllipsoidGraphics.prototype
     * @type {Property|undefined}
     * @default 128
     */
    subdivisions: createPropertyDescriptor("subdivisions"),

    /**
     * Get or sets the enum Property specifying whether the ellipsoid
     * casts or receives shadows from light sources.
     * @memberof EllipsoidGraphics.prototype
     * @type {Property|undefined}
     * @default ShadowMode.DISABLED
     */
    shadows: createPropertyDescriptor("shadows"),

    /**
     * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this ellipsoid will be displayed.
     * @memberof EllipsoidGraphics.prototype
     * @type {Property|undefined}
     */
    distanceDisplayCondition: createPropertyDescriptor(
      "distanceDisplayCondition"
    ),
  });

  /**
   * Duplicates this instance.
   *
   * @param {EllipsoidGraphics} [result] The object onto which to store the result.
   * @returns {EllipsoidGraphics} The modified result parameter or a new instance if one was not provided.
   */
  EllipsoidGraphics.prototype.clone = function (result) {
    if (!defined(result)) {
      return new EllipsoidGraphics(this);
    }
    result.show = this.show;
    result.radii = this.radii;
    result.innerRadii = this.innerRadii;
    result.minimumClock = this.minimumClock;
    result.maximumClock = this.maximumClock;
    result.minimumCone = this.minimumCone;
    result.maximumCone = this.maximumCone;
    result.heightReference = this.heightReference;
    result.fill = this.fill;
    result.material = this.material;
    result.outline = this.outline;
    result.outlineColor = this.outlineColor;
    result.outlineWidth = this.outlineWidth;
    result.stackPartitions = this.stackPartitions;
    result.slicePartitions = this.slicePartitions;
    result.subdivisions = this.subdivisions;
    result.shadows = this.shadows;
    result.distanceDisplayCondition = this.distanceDisplayCondition;
    return result;
  };

  /**
   * Assigns each unassigned property on this object to the value
   * of the same property on the provided source object.
   *
   * @param {EllipsoidGraphics} source The object to be merged into this object.
   */
  EllipsoidGraphics.prototype.merge = function (source) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(source)) {
      throw new DeveloperError("source is required.");
    }
    //>>includeEnd('debug');

    this.show = defaultValue(this.show, source.show);
    this.radii = defaultValue(this.radii, source.radii);
    this.innerRadii = defaultValue(this.innerRadii, source.innerRadii);
    this.minimumClock = defaultValue(this.minimumClock, source.minimumClock);
    this.maximumClock = defaultValue(this.maximumClock, source.maximumClock);
    this.minimumCone = defaultValue(this.minimumCone, source.minimumCone);
    this.maximumCone = defaultValue(this.maximumCone, source.maximumCone);
    this.heightReference = defaultValue(
      this.heightReference,
      source.heightReference
    );
    this.fill = defaultValue(this.fill, source.fill);
    this.material = defaultValue(this.material, source.material);
    this.outline = defaultValue(this.outline, source.outline);
    this.outlineColor = defaultValue(this.outlineColor, source.outlineColor);
    this.outlineWidth = defaultValue(this.outlineWidth, source.outlineWidth);
    this.stackPartitions = defaultValue(
      this.stackPartitions,
      source.stackPartitions
    );
    this.slicePartitions = defaultValue(
      this.slicePartitions,
      source.slicePartitions
    );
    this.subdivisions = defaultValue(this.subdivisions, source.subdivisions);
    this.shadows = defaultValue(this.shadows, source.shadows);
    this.distanceDisplayCondition = defaultValue(
      this.distanceDisplayCondition,
      source.distanceDisplayCondition
    );
  };

  /**
   * @typedef {Object} LabelGraphics.ConstructorOptions
   *
   * Initialization options for the LabelGraphics constructor
   *
   * @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the label.
   * @property {Property | string} [text] A Property specifying the text. Explicit newlines '\n' are supported.
   * @property {Property | string} [font='30px sans-serif'] A Property specifying the CSS font.
   * @property {Property | LabelStyle} [style=LabelStyle.FILL] A Property specifying the {@link LabelStyle}.
   * @property {Property | number} [scale=1.0] A numeric Property specifying the scale to apply to the text.
   * @property {Property | boolean} [showBackground=false] A boolean Property specifying the visibility of the background behind the label.
   * @property {Property | Color} [backgroundColor=new Color(0.165, 0.165, 0.165, 0.8)] A Property specifying the background {@link Color}.
   * @property {Property | Cartesian2} [backgroundPadding=new Cartesian2(7, 5)] A {@link Cartesian2} Property specifying the horizontal and vertical background padding in pixels.
   * @property {Property | Cartesian2} [pixelOffset=Cartesian2.ZERO] A {@link Cartesian2} Property specifying the pixel offset.
   * @property {Property | Cartesian3} [eyeOffset=Cartesian3.ZERO] A {@link Cartesian3} Property specifying the eye offset.
   * @property {Property | HorizontalOrigin} [horizontalOrigin=HorizontalOrigin.CENTER] A Property specifying the {@link HorizontalOrigin}.
   * @property {Property | VerticalOrigin} [verticalOrigin=VerticalOrigin.CENTER] A Property specifying the {@link VerticalOrigin}.
   * @property {Property | HeightReference} [heightReference=HeightReference.NONE] A Property specifying what the height is relative to.
   * @property {Property | Color} [fillColor=Color.WHITE] A Property specifying the fill {@link Color}.
   * @property {Property | Color} [outlineColor=Color.BLACK] A Property specifying the outline {@link Color}.
   * @property {Property | number} [outlineWidth=1.0] A numeric Property specifying the outline width.
   * @property {Property | NearFarScalar} [translucencyByDistance] A {@link NearFarScalar} Property used to set translucency based on distance from the camera.
   * @property {Property | NearFarScalar} [pixelOffsetScaleByDistance] A {@link NearFarScalar} Property used to set pixelOffset based on distance from the camera.
   * @property {Property | NearFarScalar} [scaleByDistance] A {@link NearFarScalar} Property used to set scale based on distance from the camera.
   * @property {Property | DistanceDisplayCondition} [distanceDisplayCondition] A Property specifying at what distance from the camera that this label will be displayed.
   * @property {Property | number} [disableDepthTestDistance] A Property specifying the distance from the camera at which to disable the depth test to.
   */

  /**
   * Describes a two dimensional label located at the position of the containing {@link Entity}.
   * <p>
   * <div align='center'>
   * <img src='Images/Label.png' width='400' height='300' /><br />
   * Example labels
   * </div>
   * </p>
   *
   * @alias LabelGraphics
   * @constructor
   *
   * @param {LabelGraphics.ConstructorOptions} [options] Object describing initialization options
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Labels.html|Cesium Sandcastle Labels Demo}
   */
  function LabelGraphics(options) {
    this._definitionChanged = new Event();
    this._show = undefined;
    this._showSubscription = undefined;
    this._text = undefined;
    this._textSubscription = undefined;
    this._font = undefined;
    this._fontSubscription = undefined;
    this._style = undefined;
    this._styleSubscription = undefined;
    this._scale = undefined;
    this._scaleSubscription = undefined;
    this._showBackground = undefined;
    this._showBackgroundSubscription = undefined;
    this._backgroundColor = undefined;
    this._backgroundColorSubscription = undefined;
    this._backgroundPadding = undefined;
    this._backgroundPaddingSubscription = undefined;
    this._pixelOffset = undefined;
    this._pixelOffsetSubscription = undefined;
    this._eyeOffset = undefined;
    this._eyeOffsetSubscription = undefined;
    this._horizontalOrigin = undefined;
    this._horizontalOriginSubscription = undefined;
    this._verticalOrigin = undefined;
    this._verticalOriginSubscription = undefined;
    this._heightReference = undefined;
    this._heightReferenceSubscription = undefined;
    this._fillColor = undefined;
    this._fillColorSubscription = undefined;
    this._outlineColor = undefined;
    this._outlineColorSubscription = undefined;
    this._outlineWidth = undefined;
    this._outlineWidthSubscription = undefined;
    this._translucencyByDistance = undefined;
    this._translucencyByDistanceSubscription = undefined;
    this._pixelOffsetScaleByDistance = undefined;
    this._pixelOffsetScaleByDistanceSubscription = undefined;
    this._scaleByDistance = undefined;
    this._scaleByDistanceSubscription = undefined;
    this._distanceDisplayCondition = undefined;
    this._distanceDisplayConditionSubscription = undefined;
    this._disableDepthTestDistance = undefined;
    this._disableDepthTestDistanceSubscription = undefined;

    this.merge(defaultValue(options, defaultValue.EMPTY_OBJECT));
  }

  Object.defineProperties(LabelGraphics.prototype, {
    /**
     * Gets the event that is raised whenever a property or sub-property is changed or modified.
     * @memberof LabelGraphics.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },

    /**
     * Gets or sets the boolean Property specifying the visibility of the label.
     * @memberof LabelGraphics.prototype
     * @type {Property|undefined}
     */
    show: createPropertyDescriptor("show"),

    /**
     * Gets or sets the string Property specifying the text of the label.
     * Explicit newlines '\n' are supported.
     * @memberof LabelGraphics.prototype
     * @type {Property|undefined}
     */
    text: createPropertyDescriptor("text"),

    /**
     * Gets or sets the string Property specifying the font in CSS syntax.
     * @memberof LabelGraphics.prototype
     * @type {Property|undefined}
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/CSS/font|CSS font on MDN}
     */
    font: createPropertyDescriptor("font"),

    /**
     * Gets or sets the Property specifying the {@link LabelStyle}.
     * @memberof LabelGraphics.prototype
     * @type {Property|undefined}
     */
    style: createPropertyDescriptor("style"),

    /**
     * Gets or sets the numeric Property specifying the uniform scale to apply to the image.
     * A scale greater than <code>1.0</code> enlarges the label while a scale less than <code>1.0</code> shrinks it.
     * <p>
     * <div align='center'>
     * <img src='Images/Label.setScale.png' width='400' height='300' /><br/>
     * From left to right in the above image, the scales are <code>0.5</code>, <code>1.0</code>,
     * and <code>2.0</code>.
     * </div>
     * </p>
     * @memberof LabelGraphics.prototype
     * @type {Property|undefined}
     * @default 1.0
     */
    scale: createPropertyDescriptor("scale"),

    /**
     * Gets or sets the boolean Property specifying the visibility of the background behind the label.
     * @memberof LabelGraphics.prototype
     * @type {Property|undefined}
     * @default false
     */
    showBackground: createPropertyDescriptor("showBackground"),

    /**
     * Gets or sets the Property specifying the background {@link Color}.
     * @memberof LabelGraphics.prototype
     * @type {Property|undefined}
     * @default new Color(0.165, 0.165, 0.165, 0.8)
     */
    backgroundColor: createPropertyDescriptor("backgroundColor"),

    /**
     * Gets or sets the {@link Cartesian2} Property specifying the label's horizontal and vertical
     * background padding in pixels.
     * @memberof LabelGraphics.prototype
     * @type {Property|undefined}
     * @default new Cartesian2(7, 5)
     */
    backgroundPadding: createPropertyDescriptor("backgroundPadding"),

    /**
     * Gets or sets the {@link Cartesian2} Property specifying the label's pixel offset in screen space
     * from the origin of this label.  This is commonly used to align multiple labels and labels at
     * the same position, e.g., an image and text.  The screen space origin is the top, left corner of the
     * canvas; <code>x</code> increases from left to right, and <code>y</code> increases from top to bottom.
     * <p>
     * <div align='center'>
     * <table border='0' cellpadding='5'><tr>
     * <td align='center'><code>default</code><br/><img src='Images/Label.setPixelOffset.default.png' width='250' height='188' /></td>
     * <td align='center'><code>l.pixeloffset = new Cartesian2(25, 75);</code><br/><img src='Images/Label.setPixelOffset.x50y-25.png' width='250' height='188' /></td>
     * </tr></table>
     * The label's origin is indicated by the yellow point.
     * </div>
     * </p>
     * @memberof LabelGraphics.prototype
     * @type {Property|undefined}
     * @default Cartesian2.ZERO
     */
    pixelOffset: createPropertyDescriptor("pixelOffset"),

    /**
     * Gets or sets the {@link Cartesian3} Property specifying the label's offset in eye coordinates.
     * Eye coordinates is a left-handed coordinate system, where <code>x</code> points towards the viewer's
     * right, <code>y</code> points up, and <code>z</code> points into the screen.
     * <p>
     * An eye offset is commonly used to arrange multiple labels or objects at the same position, e.g., to
     * arrange a label above its corresponding 3D model.
     * </p>
     * Below, the label is positioned at the center of the Earth but an eye offset makes it always
     * appear on top of the Earth regardless of the viewer's or Earth's orientation.
     * <p>
     * <div align='center'>
     * <table border='0' cellpadding='5'><tr>
     * <td align='center'><img src='Images/Billboard.setEyeOffset.one.png' width='250' height='188' /></td>
     * <td align='center'><img src='Images/Billboard.setEyeOffset.two.png' width='250' height='188' /></td>
     * </tr></table>
     * <code>l.eyeOffset = new Cartesian3(0.0, 8000000.0, 0.0);</code><br /><br />
     * </div>
     * </p>
     * @memberof LabelGraphics.prototype
     * @type {Property|undefined}
     * @default Cartesian3.ZERO
     */
    eyeOffset: createPropertyDescriptor("eyeOffset"),

    /**
     * Gets or sets the Property specifying the {@link HorizontalOrigin}.
     * @memberof LabelGraphics.prototype
     * @type {Property|undefined}
     */
    horizontalOrigin: createPropertyDescriptor("horizontalOrigin"),

    /**
     * Gets or sets the Property specifying the {@link VerticalOrigin}.
     * @memberof LabelGraphics.prototype
     * @type {Property|undefined}
     */
    verticalOrigin: createPropertyDescriptor("verticalOrigin"),

    /**
     * Gets or sets the Property specifying the {@link HeightReference}.
     * @memberof LabelGraphics.prototype
     * @type {Property|undefined}
     * @default HeightReference.NONE
     */
    heightReference: createPropertyDescriptor("heightReference"),

    /**
     * Gets or sets the Property specifying the fill {@link Color}.
     * @memberof LabelGraphics.prototype
     * @type {Property|undefined}
     */
    fillColor: createPropertyDescriptor("fillColor"),

    /**
     * Gets or sets the Property specifying the outline {@link Color}.
     * @memberof LabelGraphics.prototype
     * @type {Property|undefined}
     */
    outlineColor: createPropertyDescriptor("outlineColor"),

    /**
     * Gets or sets the numeric Property specifying the outline width.
     * @memberof LabelGraphics.prototype
     * @type {Property|undefined}
     */
    outlineWidth: createPropertyDescriptor("outlineWidth"),

    /**
     * Gets or sets {@link NearFarScalar} Property specifying the translucency of the label based on the distance from the camera.
     * A label's translucency will interpolate between the {@link NearFarScalar#nearValue} and
     * {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds
     * of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}.
     * Outside of these ranges the label's translucency remains clamped to the nearest bound.
     * @memberof LabelGraphics.prototype
     * @type {Property|undefined}
     */
    translucencyByDistance: createPropertyDescriptor("translucencyByDistance"),

    /**
     * Gets or sets {@link NearFarScalar} Property specifying the pixel offset of the label based on the distance from the camera.
     * A label's pixel offset will interpolate between the {@link NearFarScalar#nearValue} and
     * {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds
     * of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}.
     * Outside of these ranges the label's pixel offset remains clamped to the nearest bound.
     * @memberof LabelGraphics.prototype
     * @type {Property|undefined}
     */
    pixelOffsetScaleByDistance: createPropertyDescriptor(
      "pixelOffsetScaleByDistance"
    ),

    /**
     * Gets or sets near and far scaling properties of a Label based on the label's distance from the camera.
     * A label's scale will interpolate between the {@link NearFarScalar#nearValue} and
     * {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds
     * of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}.
     * Outside of these ranges the label's scale remains clamped to the nearest bound.  If undefined,
     * scaleByDistance will be disabled.
     * @memberof LabelGraphics.prototype
     * @type {Property|undefined}
     */
    scaleByDistance: createPropertyDescriptor("scaleByDistance"),

    /**
     * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this label will be displayed.
     * @memberof LabelGraphics.prototype
     * @type {Property|undefined}
     */
    distanceDisplayCondition: createPropertyDescriptor(
      "distanceDisplayCondition"
    ),

    /**
     * Gets or sets the distance from the camera at which to disable the depth test to, for example, prevent clipping against terrain.
     * When set to zero, the depth test is always applied. When set to Number.POSITIVE_INFINITY, the depth test is never applied.
     * @memberof LabelGraphics.prototype
     * @type {Property|undefined}
     */
    disableDepthTestDistance: createPropertyDescriptor(
      "disableDepthTestDistance"
    ),
  });

  /**
   * Duplicates this instance.
   *
   * @param {LabelGraphics} [result] The object onto which to store the result.
   * @returns {LabelGraphics} The modified result parameter or a new instance if one was not provided.
   */
  LabelGraphics.prototype.clone = function (result) {
    if (!defined(result)) {
      return new LabelGraphics(this);
    }
    result.show = this.show;
    result.text = this.text;
    result.font = this.font;
    result.style = this.style;
    result.scale = this.scale;
    result.showBackground = this.showBackground;
    result.backgroundColor = this.backgroundColor;
    result.backgroundPadding = this.backgroundPadding;
    result.pixelOffset = this.pixelOffset;
    result.eyeOffset = this.eyeOffset;
    result.horizontalOrigin = this.horizontalOrigin;
    result.verticalOrigin = this.verticalOrigin;
    result.heightReference = this.heightReference;
    result.fillColor = this.fillColor;
    result.outlineColor = this.outlineColor;
    result.outlineWidth = this.outlineWidth;
    result.translucencyByDistance = this.translucencyByDistance;
    result.pixelOffsetScaleByDistance = this.pixelOffsetScaleByDistance;
    result.scaleByDistance = this.scaleByDistance;
    result.distanceDisplayCondition = this.distanceDisplayCondition;
    result.disableDepthTestDistance = this.disableDepthTestDistance;
    return result;
  };

  /**
   * Assigns each unassigned property on this object to the value
   * of the same property on the provided source object.
   *
   * @param {LabelGraphics} source The object to be merged into this object.
   */
  LabelGraphics.prototype.merge = function (source) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(source)) {
      throw new DeveloperError("source is required.");
    }
    //>>includeEnd('debug');

    this.show = defaultValue(this.show, source.show);
    this.text = defaultValue(this.text, source.text);
    this.font = defaultValue(this.font, source.font);
    this.style = defaultValue(this.style, source.style);
    this.scale = defaultValue(this.scale, source.scale);
    this.showBackground = defaultValue(
      this.showBackground,
      source.showBackground
    );
    this.backgroundColor = defaultValue(
      this.backgroundColor,
      source.backgroundColor
    );
    this.backgroundPadding = defaultValue(
      this.backgroundPadding,
      source.backgroundPadding
    );
    this.pixelOffset = defaultValue(this.pixelOffset, source.pixelOffset);
    this.eyeOffset = defaultValue(this.eyeOffset, source.eyeOffset);
    this.horizontalOrigin = defaultValue(
      this.horizontalOrigin,
      source.horizontalOrigin
    );
    this.verticalOrigin = defaultValue(
      this.verticalOrigin,
      source.verticalOrigin
    );
    this.heightReference = defaultValue(
      this.heightReference,
      source.heightReference
    );
    this.fillColor = defaultValue(this.fillColor, source.fillColor);
    this.outlineColor = defaultValue(this.outlineColor, source.outlineColor);
    this.outlineWidth = defaultValue(this.outlineWidth, source.outlineWidth);
    this.translucencyByDistance = defaultValue(
      this.translucencyByDistance,
      source.translucencyByDistance
    );
    this.pixelOffsetScaleByDistance = defaultValue(
      this.pixelOffsetScaleByDistance,
      source.pixelOffsetScaleByDistance
    );
    this.scaleByDistance = defaultValue(
      this.scaleByDistance,
      source.scaleByDistance
    );
    this.distanceDisplayCondition = defaultValue(
      this.distanceDisplayCondition,
      source.distanceDisplayCondition
    );
    this.disableDepthTestDistance = defaultValue(
      this.disableDepthTestDistance,
      source.disableDepthTestDistance
    );
  };

  const defaultNodeTransformation = new TranslationRotationScale();

  /**
   * A {@link Property} that produces {@link TranslationRotationScale} data.
   * @alias NodeTransformationProperty
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Property|Cartesian3} [options.translation=Cartesian3.ZERO] A {@link Cartesian3} Property specifying the (x, y, z) translation to apply to the node.
   * @param {Property|Quaternion} [options.rotation=Quaternion.IDENTITY] A {@link Quaternion} Property specifying the (x, y, z, w) rotation to apply to the node.
   * @param {Property|Cartesian3} [options.scale=new Cartesian3(1.0, 1.0, 1.0)] A {@link Cartesian3} Property specifying the (x, y, z) scaling to apply to the node.
   */
  function NodeTransformationProperty(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    this._definitionChanged = new Event();
    this._translation = undefined;
    this._translationSubscription = undefined;
    this._rotation = undefined;
    this._rotationSubscription = undefined;
    this._scale = undefined;
    this._scaleSubscription = undefined;

    this.translation = options.translation;
    this.rotation = options.rotation;
    this.scale = options.scale;
  }

  Object.defineProperties(NodeTransformationProperty.prototype, {
    /**
     * Gets a value indicating if this property is constant.  A property is considered
     * constant if getValue always returns the same result for the current definition.
     * @memberof NodeTransformationProperty.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    isConstant: {
      get: function () {
        return (
          Property.isConstant(this._translation) &&
          Property.isConstant(this._rotation) &&
          Property.isConstant(this._scale)
        );
      },
    },

    /**
     * Gets the event that is raised whenever the definition of this property changes.
     * The definition is considered to have changed if a call to getValue would return
     * a different result for the same time.
     * @memberof NodeTransformationProperty.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },

    /**
     * Gets or sets the {@link Cartesian3} Property specifying the (x, y, z) translation to apply to the node.
     * @memberof NodeTransformationProperty.prototype
     * @type {Property|undefined}
     * @default Cartesian3.ZERO
     */
    translation: createPropertyDescriptor("translation"),

    /**
     * Gets or sets the {@link Quaternion} Property specifying the (x, y, z, w) rotation to apply to the node.
     * @memberof NodeTransformationProperty.prototype
     * @type {Property|undefined}
     * @default Quaternion.IDENTITY
     */
    rotation: createPropertyDescriptor("rotation"),

    /**
     * Gets or sets the {@link Cartesian3} Property specifying the (x, y, z) scaling to apply to the node.
     * @memberof NodeTransformationProperty.prototype
     * @type {Property|undefined}
     * @default new Cartesian3(1.0, 1.0, 1.0)
     */
    scale: createPropertyDescriptor("scale"),
  });

  /**
   * Gets the value of the property at the provided time.
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {TranslationRotationScale} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {TranslationRotationScale} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  NodeTransformationProperty.prototype.getValue = function (time, result) {
    if (!defined(result)) {
      result = new TranslationRotationScale();
    }

    result.translation = Property.getValueOrClonedDefault(
      this._translation,
      time,
      defaultNodeTransformation.translation,
      result.translation
    );
    result.rotation = Property.getValueOrClonedDefault(
      this._rotation,
      time,
      defaultNodeTransformation.rotation,
      result.rotation
    );
    result.scale = Property.getValueOrClonedDefault(
      this._scale,
      time,
      defaultNodeTransformation.scale,
      result.scale
    );
    return result;
  };

  /**
   * Compares this property to the provided property and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Property} [other] The other property.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  NodeTransformationProperty.prototype.equals = function (other) {
    return (
      this === other ||
      (other instanceof NodeTransformationProperty &&
        Property.equals(this._translation, other._translation) &&
        Property.equals(this._rotation, other._rotation) &&
        Property.equals(this._scale, other._scale))
    );
  };

  /**
   * A {@link Property} whose value is a key-value mapping of property names to the computed value of other properties.
   *
   * @alias PropertyBag
   * @implements Record<string, any>
   * @constructor
   *
   * @param {Object} [value] An object, containing key-value mapping of property names to properties.
   * @param {Function} [createPropertyCallback] A function that will be called when the value of any of the properties in value are not a Property.
   */
  function PropertyBag(value, createPropertyCallback) {
    this._propertyNames = [];
    this._definitionChanged = new Event();

    if (defined(value)) {
      this.merge(value, createPropertyCallback);
    }
  }

  Object.defineProperties(PropertyBag.prototype, {
    /**
     * Gets the names of all properties registered on this instance.
     * @memberof PropertyBag.prototype
     * @type {Array}
     */
    propertyNames: {
      get: function () {
        return this._propertyNames;
      },
    },
    /**
     * Gets a value indicating if this property is constant.  This property
     * is considered constant if all property items in this object are constant.
     * @memberof PropertyBag.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    isConstant: {
      get: function () {
        const propertyNames = this._propertyNames;
        for (let i = 0, len = propertyNames.length; i < len; i++) {
          if (!Property.isConstant(this[propertyNames[i]])) {
            return false;
          }
        }
        return true;
      },
    },
    /**
     * Gets the event that is raised whenever the set of properties contained in this
     * object changes, or one of the properties itself changes.
     *
     * @memberof PropertyBag.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },
  });

  /**
   * Determines if this object has defined a property with the given name.
   *
   * @param {String} propertyName The name of the property to check for.
   *
   * @returns {Boolean} True if this object has defined a property with the given name, false otherwise.
   */
  PropertyBag.prototype.hasProperty = function (propertyName) {
    return this._propertyNames.indexOf(propertyName) !== -1;
  };

  function createConstantProperty(value) {
    return new ConstantProperty(value);
  }

  /**
   * Adds a property to this object.
   *
   * @param {String} propertyName The name of the property to add.
   * @param {*} [value] The value of the new property, if provided.
   * @param {Function} [createPropertyCallback] A function that will be called when the value of this new property is set to a value that is not a Property.
   *
   * @exception {DeveloperError} "propertyName" is already a registered property.
   */
  PropertyBag.prototype.addProperty = function (
    propertyName,
    value,
    createPropertyCallback
  ) {
    const propertyNames = this._propertyNames;

    //>>includeStart('debug', pragmas.debug);
    if (!defined(propertyName)) {
      throw new DeveloperError("propertyName is required.");
    }
    if (propertyNames.indexOf(propertyName) !== -1) {
      throw new DeveloperError(
        `${propertyName} is already a registered property.`
      );
    }
    //>>includeEnd('debug');

    propertyNames.push(propertyName);
    Object.defineProperty(
      this,
      propertyName,
      createPropertyDescriptor(
        propertyName,
        true,
        defaultValue(createPropertyCallback, createConstantProperty)
      )
    );

    if (defined(value)) {
      this[propertyName] = value;
    }

    this._definitionChanged.raiseEvent(this);
  };

  /**
   * Removed a property previously added with addProperty.
   *
   * @param {String} propertyName The name of the property to remove.
   *
   * @exception {DeveloperError} "propertyName" is not a registered property.
   */
  PropertyBag.prototype.removeProperty = function (propertyName) {
    const propertyNames = this._propertyNames;
    const index = propertyNames.indexOf(propertyName);

    //>>includeStart('debug', pragmas.debug);
    if (!defined(propertyName)) {
      throw new DeveloperError("propertyName is required.");
    }
    if (index === -1) {
      throw new DeveloperError(`${propertyName} is not a registered property.`);
    }
    //>>includeEnd('debug');

    this._propertyNames.splice(index, 1);
    delete this[propertyName];

    this._definitionChanged.raiseEvent(this);
  };

  /**
   * Gets the value of this property.  Each contained property will be evaluated at the given time, and the overall
   * result will be an object, mapping property names to those values.
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {Object} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * Note that any properties in result which are not part of this PropertyBag will be left as-is.
   * @returns {Object} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  PropertyBag.prototype.getValue = function (time, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(time)) {
      throw new DeveloperError("time is required.");
    }
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = {};
    }

    const propertyNames = this._propertyNames;
    for (let i = 0, len = propertyNames.length; i < len; i++) {
      const propertyName = propertyNames[i];
      result[propertyName] = Property.getValueOrUndefined(
        this[propertyName],
        time,
        result[propertyName]
      );
    }
    return result;
  };

  /**
   * Assigns each unassigned property on this object to the value
   * of the same property on the provided source object.
   *
   * @param {Object} source The object to be merged into this object.
   * @param {Function} [createPropertyCallback] A function that will be called when the value of any of the properties in value are not a Property.
   */
  PropertyBag.prototype.merge = function (source, createPropertyCallback) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(source)) {
      throw new DeveloperError("source is required.");
    }
    //>>includeEnd('debug');

    const propertyNames = this._propertyNames;
    const sourcePropertyNames = defined(source._propertyNames)
      ? source._propertyNames
      : Object.keys(source);
    for (let i = 0, len = sourcePropertyNames.length; i < len; i++) {
      const name = sourcePropertyNames[i];

      const targetProperty = this[name];
      const sourceProperty = source[name];

      //Custom properties that are registered on the source must also be added to this.
      if (targetProperty === undefined && propertyNames.indexOf(name) === -1) {
        this.addProperty(name, undefined, createPropertyCallback);
      }

      if (sourceProperty !== undefined) {
        if (targetProperty !== undefined) {
          if (defined(targetProperty) && defined(targetProperty.merge)) {
            targetProperty.merge(sourceProperty);
          }
        } else if (
          defined(sourceProperty) &&
          defined(sourceProperty.merge) &&
          defined(sourceProperty.clone)
        ) {
          this[name] = sourceProperty.clone();
        } else {
          this[name] = sourceProperty;
        }
      }
    }
  };

  function propertiesEqual(a, b) {
    const aPropertyNames = a._propertyNames;
    const bPropertyNames = b._propertyNames;

    const len = aPropertyNames.length;
    if (len !== bPropertyNames.length) {
      return false;
    }

    for (let aIndex = 0; aIndex < len; ++aIndex) {
      const name = aPropertyNames[aIndex];
      const bIndex = bPropertyNames.indexOf(name);
      if (bIndex === -1) {
        return false;
      }
      if (!Property.equals(a[name], b[name])) {
        return false;
      }
    }
    return true;
  }

  /**
   * Compares this property to the provided property and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Property} [other] The other property.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  PropertyBag.prototype.equals = function (other) {
    return (
      this === other || //
      (other instanceof PropertyBag && //
        propertiesEqual(this, other))
    );
  };

  function createNodeTransformationProperty(value) {
    return new NodeTransformationProperty(value);
  }

  function createNodeTransformationPropertyBag(value) {
    return new PropertyBag(value, createNodeTransformationProperty);
  }

  function createArticulationStagePropertyBag(value) {
    return new PropertyBag(value);
  }

  /**
   * @typedef {Object} ModelGraphics.ConstructorOptions
   *
   * Initialization options for the ModelGraphics constructor
   *
   * @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the model.
   * @property {Property | string | Resource} [uri] A string or Resource Property specifying the URI of the glTF asset.
   * @property {Property | number} [scale=1.0] A numeric Property specifying a uniform linear scale.
   * @property {Property | number} [minimumPixelSize=0.0] A numeric Property specifying the approximate minimum pixel size of the model regardless of zoom.
   * @property {Property | number} [maximumScale] The maximum scale size of a model. An upper limit for minimumPixelSize.
   * @property {Property | boolean} [incrementallyLoadTextures=true] Determine if textures may continue to stream in after the model is loaded.
   * @property {Property | boolean} [runAnimations=true] A boolean Property specifying if glTF animations specified in the model should be started.
   * @property {Property | boolean} [clampAnimations=true] A boolean Property specifying if glTF animations should hold the last pose for time durations with no keyframes.
   * @property {Property | ShadowMode} [shadows=ShadowMode.ENABLED] An enum Property specifying whether the model casts or receives shadows from light sources.
   * @property {Property | HeightReference} [heightReference=HeightReference.NONE] A Property specifying what the height is relative to.
   * @property {Property | Color} [silhouetteColor=Color.RED] A Property specifying the {@link Color} of the silhouette.
   * @property {Property | number} [silhouetteSize=0.0] A numeric Property specifying the size of the silhouette in pixels.
   * @property {Property | Color} [color=Color.WHITE] A Property specifying the {@link Color} that blends with the model's rendered color.
   * @property {Property | ColorBlendMode} [colorBlendMode=ColorBlendMode.HIGHLIGHT] An enum Property specifying how the color blends with the model.
   * @property {Property | number} [colorBlendAmount=0.5] A numeric Property specifying the color strength when the <code>colorBlendMode</code> is <code>MIX</code>. A value of 0.0 results in the model's rendered color while a value of 1.0 results in a solid color, with any value in-between resulting in a mix of the two.
   * @property {Property | Cartesian2} [imageBasedLightingFactor=new Cartesian2(1.0, 1.0)] A property specifying the contribution from diffuse and specular image-based lighting.
   * @property {Property | Color} [lightColor] A property specifying the light color when shading the model. When <code>undefined</code> the scene's light color is used instead.
   * @property {Property | DistanceDisplayCondition} [distanceDisplayCondition] A Property specifying at what distance from the camera that this model will be displayed.
   * @property {PropertyBag | Object.<string, TranslationRotationScale>} [nodeTransformations] An object, where keys are names of nodes, and values are {@link TranslationRotationScale} Properties describing the transformation to apply to that node. The transformation is applied after the node's existing transformation as specified in the glTF, and does not replace the node's existing transformation.
   * @property {PropertyBag | Object.<string, number>} [articulations] An object, where keys are composed of an articulation name, a single space, and a stage name, and the values are numeric properties.
   * @property {Property | ClippingPlaneCollection} [clippingPlanes] A property specifying the {@link ClippingPlaneCollection} used to selectively disable rendering the model.
   */

  /**
   * A 3D model based on {@link https://github.com/KhronosGroup/glTF|glTF}, the runtime asset format for WebGL, OpenGL ES, and OpenGL.
   * The position and orientation of the model is determined by the containing {@link Entity}.
   * <p>
   * Cesium includes support for glTF geometry, materials, animations, and skinning.
   * Cameras and lights are not currently supported.
   * </p>
   *
   * @alias ModelGraphics
   * @constructor
   *
   * @param {ModelGraphics.ConstructorOptions} [options] Object describing initialization options
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=3D%20Models.html|Cesium Sandcastle 3D Models Demo}
   */
  function ModelGraphics(options) {
    this._definitionChanged = new Event();
    this._show = undefined;
    this._showSubscription = undefined;
    this._uri = undefined;
    this._uriSubscription = undefined;
    this._scale = undefined;
    this._scaleSubscription = undefined;
    this._minimumPixelSize = undefined;
    this._minimumPixelSizeSubscription = undefined;
    this._maximumScale = undefined;
    this._maximumScaleSubscription = undefined;
    this._incrementallyLoadTextures = undefined;
    this._incrementallyLoadTexturesSubscription = undefined;
    this._runAnimations = undefined;
    this._runAnimationsSubscription = undefined;
    this._clampAnimations = undefined;
    this._clampAnimationsSubscription = undefined;
    this._shadows = undefined;
    this._shadowsSubscription = undefined;
    this._heightReference = undefined;
    this._heightReferenceSubscription = undefined;
    this._silhouetteColor = undefined;
    this._silhouetteColorSubscription = undefined;
    this._silhouetteSize = undefined;
    this._silhouetteSizeSubscription = undefined;
    this._color = undefined;
    this._colorSubscription = undefined;
    this._colorBlendMode = undefined;
    this._colorBlendModeSubscription = undefined;
    this._colorBlendAmount = undefined;
    this._colorBlendAmountSubscription = undefined;
    this._imageBasedLightingFactor = undefined;
    this._imageBasedLightingFactorSubscription = undefined;
    this._lightColor = undefined;
    this._lightColorSubscription = undefined;
    this._distanceDisplayCondition = undefined;
    this._distanceDisplayConditionSubscription = undefined;
    this._nodeTransformations = undefined;
    this._nodeTransformationsSubscription = undefined;
    this._articulations = undefined;
    this._articulationsSubscription = undefined;
    this._clippingPlanes = undefined;
    this._clippingPlanesSubscription = undefined;

    this.merge(defaultValue(options, defaultValue.EMPTY_OBJECT));
  }

  Object.defineProperties(ModelGraphics.prototype, {
    /**
     * Gets the event that is raised whenever a property or sub-property is changed or modified.
     * @memberof ModelGraphics.prototype
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },

    /**
     * Gets or sets the boolean Property specifying the visibility of the model.
     * @memberof ModelGraphics.prototype
     * @type {Property|undefined}
     * @default true
     */
    show: createPropertyDescriptor("show"),

    /**
     * Gets or sets the string Property specifying the URI of the glTF asset.
     * @memberof ModelGraphics.prototype
     * @type {Property|undefined}
     */
    uri: createPropertyDescriptor("uri"),

    /**
     * Gets or sets the numeric Property specifying a uniform linear scale
     * for this model. Values greater than 1.0 increase the size of the model while
     * values less than 1.0 decrease it.
     * @memberof ModelGraphics.prototype
     * @type {Property|undefined}
     * @default 1.0
     */
    scale: createPropertyDescriptor("scale"),

    /**
     * Gets or sets the numeric Property specifying the approximate minimum
     * pixel size of the model regardless of zoom. This can be used to ensure that
     * a model is visible even when the viewer zooms out.  When <code>0.0</code>,
     * no minimum size is enforced.
     * @memberof ModelGraphics.prototype
     * @type {Property|undefined}
     * @default 0.0
     */
    minimumPixelSize: createPropertyDescriptor("minimumPixelSize"),

    /**
     * Gets or sets the numeric Property specifying the maximum scale
     * size of a model. This property is used as an upper limit for
     * {@link ModelGraphics#minimumPixelSize}.
     * @memberof ModelGraphics.prototype
     * @type {Property|undefined}
     */
    maximumScale: createPropertyDescriptor("maximumScale"),

    /**
     * Get or sets the boolean Property specifying whether textures
     * may continue to stream in after the model is loaded.
     * @memberof ModelGraphics.prototype
     * @type {Property|undefined}
     */
    incrementallyLoadTextures: createPropertyDescriptor(
      "incrementallyLoadTextures"
    ),

    /**
     * Gets or sets the boolean Property specifying if glTF animations should be run.
     * @memberof ModelGraphics.prototype
     * @type {Property|undefined}
     * @default true
     */
    runAnimations: createPropertyDescriptor("runAnimations"),

    /**
     * Gets or sets the boolean Property specifying if glTF animations should hold the last pose for time durations with no keyframes.
     * @memberof ModelGraphics.prototype
     * @type {Property|undefined}
     * @default true
     */
    clampAnimations: createPropertyDescriptor("clampAnimations"),

    /**
     * Get or sets the enum Property specifying whether the model
     * casts or receives shadows from light sources.
     * @memberof ModelGraphics.prototype
     * @type {Property|undefined}
     * @default ShadowMode.ENABLED
     */
    shadows: createPropertyDescriptor("shadows"),

    /**
     * Gets or sets the Property specifying the {@link HeightReference}.
     * @memberof ModelGraphics.prototype
     * @type {Property|undefined}
     * @default HeightReference.NONE
     */
    heightReference: createPropertyDescriptor("heightReference"),

    /**
     * Gets or sets the Property specifying the {@link Color} of the silhouette.
     * @memberof ModelGraphics.prototype
     * @type {Property|undefined}
     * @default Color.RED
     */
    silhouetteColor: createPropertyDescriptor("silhouetteColor"),

    /**
     * Gets or sets the numeric Property specifying the size of the silhouette in pixels.
     * @memberof ModelGraphics.prototype
     * @type {Property|undefined}
     * @default 0.0
     */
    silhouetteSize: createPropertyDescriptor("silhouetteSize"),

    /**
     * Gets or sets the Property specifying the {@link Color} that blends with the model's rendered color.
     * @memberof ModelGraphics.prototype
     * @type {Property|undefined}
     * @default Color.WHITE
     */
    color: createPropertyDescriptor("color"),

    /**
     * Gets or sets the enum Property specifying how the color blends with the model.
     * @memberof ModelGraphics.prototype
     * @type {Property|undefined}
     * @default ColorBlendMode.HIGHLIGHT
     */
    colorBlendMode: createPropertyDescriptor("colorBlendMode"),

    /**
     * A numeric Property specifying the color strength when the <code>colorBlendMode</code> is MIX.
     * A value of 0.0 results in the model's rendered color while a value of 1.0 results in a solid color, with
     * any value in-between resulting in a mix of the two.
     * @memberof ModelGraphics.prototype
     * @type {Property|undefined}
     * @default 0.5
     */
    colorBlendAmount: createPropertyDescriptor("colorBlendAmount"),

    /**
     * A property specifying the {@link Cartesian2} used to scale the diffuse and specular image-based lighting contribution to the final color.
     * @memberof ModelGraphics.prototype
     * @type {Property|undefined}
     */
    imageBasedLightingFactor: createPropertyDescriptor(
      "imageBasedLightingFactor"
    ),

    /**
     * A property specifying the {@link Cartesian3} light color when shading the model. When <code>undefined</code> the scene's light color is used instead.
     * @memberOf ModelGraphics.prototype
     * @type {Property|undefined}
     */
    lightColor: createPropertyDescriptor("lightColor"),

    /**
     * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this model will be displayed.
     * @memberof ModelGraphics.prototype
     * @type {Property|undefined}
     */
    distanceDisplayCondition: createPropertyDescriptor(
      "distanceDisplayCondition"
    ),

    /**
     * Gets or sets the set of node transformations to apply to this model.  This is represented as an {@link PropertyBag}, where keys are
     * names of nodes, and values are {@link TranslationRotationScale} Properties describing the transformation to apply to that node.
     * The transformation is applied after the node's existing transformation as specified in the glTF, and does not replace the node's existing transformation.
     * @memberof ModelGraphics.prototype
     * @type {PropertyBag}
     */
    nodeTransformations: createPropertyDescriptor(
      "nodeTransformations",
      undefined,
      createNodeTransformationPropertyBag
    ),

    /**
     * Gets or sets the set of articulation values to apply to this model.  This is represented as an {@link PropertyBag}, where keys are
     * composed as the name of the articulation, a single space, and the name of the stage.
     * @memberof ModelGraphics.prototype
     * @type {PropertyBag}
     */
    articulations: createPropertyDescriptor(
      "articulations",
      undefined,
      createArticulationStagePropertyBag
    ),

    /**
     * A property specifying the {@link ClippingPlaneCollection} used to selectively disable rendering the model.
     * @memberof ModelGraphics.prototype
     * @type {Property|undefined}
     */
    clippingPlanes: createPropertyDescriptor("clippingPlanes"),
  });

  /**
   * Duplicates this instance.
   *
   * @param {ModelGraphics} [result] The object onto which to store the result.
   * @returns {ModelGraphics} The modified result parameter or a new instance if one was not provided.
   */
  ModelGraphics.prototype.clone = function (result) {
    if (!defined(result)) {
      return new ModelGraphics(this);
    }
    result.show = this.show;
    result.uri = this.uri;
    result.scale = this.scale;
    result.minimumPixelSize = this.minimumPixelSize;
    result.maximumScale = this.maximumScale;
    result.incrementallyLoadTextures = this.incrementallyLoadTextures;
    result.runAnimations = this.runAnimations;
    result.clampAnimations = this.clampAnimations;
    result.heightReference = this._heightReference;
    result.silhouetteColor = this.silhouetteColor;
    result.silhouetteSize = this.silhouetteSize;
    result.color = this.color;
    result.colorBlendMode = this.colorBlendMode;
    result.colorBlendAmount = this.colorBlendAmount;
    result.imageBasedLightingFactor = this.imageBasedLightingFactor;
    result.lightColor = this.lightColor;
    result.distanceDisplayCondition = this.distanceDisplayCondition;
    result.nodeTransformations = this.nodeTransformations;
    result.articulations = this.articulations;
    result.clippingPlanes = this.clippingPlanes;
    return result;
  };

  /**
   * Assigns each unassigned property on this object to the value
   * of the same property on the provided source object.
   *
   * @param {ModelGraphics} source The object to be merged into this object.
   */
  ModelGraphics.prototype.merge = function (source) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(source)) {
      throw new DeveloperError("source is required.");
    }
    //>>includeEnd('debug');

    this.show = defaultValue(this.show, source.show);
    this.uri = defaultValue(this.uri, source.uri);
    this.scale = defaultValue(this.scale, source.scale);
    this.minimumPixelSize = defaultValue(
      this.minimumPixelSize,
      source.minimumPixelSize
    );
    this.maximumScale = defaultValue(this.maximumScale, source.maximumScale);
    this.incrementallyLoadTextures = defaultValue(
      this.incrementallyLoadTextures,
      source.incrementallyLoadTextures
    );
    this.runAnimations = defaultValue(this.runAnimations, source.runAnimations);
    this.clampAnimations = defaultValue(
      this.clampAnimations,
      source.clampAnimations
    );
    this.shadows = defaultValue(this.shadows, source.shadows);
    this.heightReference = defaultValue(
      this.heightReference,
      source.heightReference
    );
    this.silhouetteColor = defaultValue(
      this.silhouetteColor,
      source.silhouetteColor
    );
    this.silhouetteSize = defaultValue(
      this.silhouetteSize,
      source.silhouetteSize
    );
    this.color = defaultValue(this.color, source.color);
    this.colorBlendMode = defaultValue(
      this.colorBlendMode,
      source.colorBlendMode
    );
    this.colorBlendAmount = defaultValue(
      this.colorBlendAmount,
      source.colorBlendAmount
    );
    this.imageBasedLightingFactor = defaultValue(
      this.imageBasedLightingFactor,
      source.imageBasedLightingFactor
    );
    this.lightColor = defaultValue(this.lightColor, source.lightColor);
    this.distanceDisplayCondition = defaultValue(
      this.distanceDisplayCondition,
      source.distanceDisplayCondition
    );
    this.clippingPlanes = defaultValue(
      this.clippingPlanes,
      source.clippingPlanes
    );

    const sourceNodeTransformations = source.nodeTransformations;
    if (defined(sourceNodeTransformations)) {
      const targetNodeTransformations = this.nodeTransformations;
      if (defined(targetNodeTransformations)) {
        targetNodeTransformations.merge(sourceNodeTransformations);
      } else {
        this.nodeTransformations = new PropertyBag(
          sourceNodeTransformations,
          createNodeTransformationProperty
        );
      }
    }

    const sourceArticulations = source.articulations;
    if (defined(sourceArticulations)) {
      const targetArticulations = this.articulations;
      if (defined(targetArticulations)) {
        targetArticulations.merge(sourceArticulations);
      } else {
        this.articulations = new PropertyBag(sourceArticulations);
      }
    }
  };

  /**
   * @typedef {Object} Cesium3DTilesetGraphics.ConstructorOptions
   *
   * Initialization options for the Cesium3DTilesetGraphics constructor
   *
   * @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the tileset.
   * @property {Property | string | Resource} [uri] A string or Resource Property specifying the URI of the tileset.
   * @property {Property | number} [maximumScreenSpaceError] A number or Property specifying the maximum screen space error used to drive level of detail refinement.
   */

  /**
   * A 3D Tiles tileset represented by an {@link Entity}.
   * The tileset modelMatrix is determined by the containing Entity position and orientation
   * or is left unset if position is undefined.
   *
   * @alias Cesium3DTilesetGraphics
   * @constructor
   *
   * @param {Cesium3DTilesetGraphics.ConstructorOptions} [options] Object describing initialization options
   */
  function Cesium3DTilesetGraphics(options) {
    this._definitionChanged = new Event();
    this._show = undefined;
    this._showSubscription = undefined;
    this._uri = undefined;
    this._uriSubscription = undefined;
    this._maximumScreenSpaceError = undefined;
    this._maximumScreenSpaceErrorSubscription = undefined;

    this.merge(defaultValue(options, defaultValue.EMPTY_OBJECT));
  }

  Object.defineProperties(Cesium3DTilesetGraphics.prototype, {
    /**
     * Gets the event that is raised whenever a property or sub-property is changed or modified.
     * @memberof Cesium3DTilesetGraphics.prototype
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },

    /**
     * Gets or sets the boolean Property specifying the visibility of the model.
     * @memberof Cesium3DTilesetGraphics.prototype
     * @type {Property|undefined}
     * @default true
     */
    show: createPropertyDescriptor("show"),

    /**
     * Gets or sets the string Property specifying the URI of the glTF asset.
     * @memberof Cesium3DTilesetGraphics.prototype
     * @type {Property|undefined}
     */
    uri: createPropertyDescriptor("uri"),

    /**
     * Gets or sets the maximum screen space error used to drive level of detail refinement.
     * @memberof Cesium3DTilesetGraphics.prototype
     * @type {Property|undefined}
     */
    maximumScreenSpaceError: createPropertyDescriptor("maximumScreenSpaceError"),
  });

  /**
   * Duplicates this instance.
   *
   * @param {Cesium3DTilesetGraphics} [result] The object onto which to store the result.
   * @returns {Cesium3DTilesetGraphics} The modified result parameter or a new instance if one was not provided.
   */
  Cesium3DTilesetGraphics.prototype.clone = function (result) {
    if (!defined(result)) {
      return new Cesium3DTilesetGraphics(this);
    }
    result.show = this.show;
    result.uri = this.uri;
    result.maximumScreenSpaceError = this.maximumScreenSpaceError;

    return result;
  };

  /**
   * Assigns each unassigned property on this object to the value
   * of the same property on the provided source object.
   *
   * @param {Cesium3DTilesetGraphics} source The object to be merged into this object.
   */
  Cesium3DTilesetGraphics.prototype.merge = function (source) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(source)) {
      throw new DeveloperError("source is required.");
    }
    //>>includeEnd('debug');

    this.show = defaultValue(this.show, source.show);
    this.uri = defaultValue(this.uri, source.uri);
    this.maximumScreenSpaceError = defaultValue(
      this.maximumScreenSpaceError,
      source.maximumScreenSpaceError
    );
  };

  /**
   * @typedef {Object} PathGraphics.ConstructorOptions
   *
   * Initialization options for the PathGraphics constructor
   *
   * @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the path.
   * @property {Property | number} [leadTime] A Property specifying the number of seconds in front the object to show.
   * @property {Property | number} [trailTime] A Property specifying the number of seconds behind of the object to show.
   * @property {Property | number} [width=1.0] A numeric Property specifying the width in pixels.
   * @property {Property | number} [resolution=60] A numeric Property specifying the maximum number of seconds to step when sampling the position.
   * @property {MaterialProperty | Color} [material=Color.WHITE] A Property specifying the material used to draw the path.
   * @property {Property | DistanceDisplayCondition} [distanceDisplayCondition] A Property specifying at what distance from the camera that this path will be displayed.
   */

  /**
   * Describes a polyline defined as the path made by an {@link Entity} as it moves over time.
   *
   * @alias PathGraphics
   * @constructor
   *
   * @param {PathGraphics.ConstructorOptions} [options] Object describing initialization options
   */
  function PathGraphics(options) {
    this._definitionChanged = new Event();
    this._show = undefined;
    this._showSubscription = undefined;
    this._leadTime = undefined;
    this._leadTimeSubscription = undefined;
    this._trailTime = undefined;
    this._trailTimeSubscription = undefined;
    this._width = undefined;
    this._widthSubscription = undefined;
    this._resolution = undefined;
    this._resolutionSubscription = undefined;
    this._material = undefined;
    this._materialSubscription = undefined;
    this._distanceDisplayCondition = undefined;
    this._distanceDisplayConditionSubscription = undefined;

    this.merge(defaultValue(options, defaultValue.EMPTY_OBJECT));
  }

  Object.defineProperties(PathGraphics.prototype, {
    /**
     * Gets the event that is raised whenever a property or sub-property is changed or modified.
     * @memberof PathGraphics.prototype
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },

    /**
     * Gets or sets the boolean Property specifying the visibility of the path.
     * @memberof PathGraphics.prototype
     * @type {Property|undefined}
     * @default true
     */
    show: createPropertyDescriptor("show"),

    /**
     * Gets or sets the Property specifying the number of seconds in front of the object to show.
     * @memberof PathGraphics.prototype
     * @type {Property|undefined}
     */
    leadTime: createPropertyDescriptor("leadTime"),

    /**
     * Gets or sets the Property specifying the number of seconds behind the object to show.
     * @memberof PathGraphics.prototype
     * @type {Property|undefined}
     */
    trailTime: createPropertyDescriptor("trailTime"),

    /**
     * Gets or sets the numeric Property specifying the width in pixels.
     * @memberof PathGraphics.prototype
     * @type {Property|undefined}
     * @default 1.0
     */
    width: createPropertyDescriptor("width"),

    /**
     * Gets or sets the Property specifying the maximum number of seconds to step when sampling the position.
     * @memberof PathGraphics.prototype
     * @type {Property|undefined}
     * @default 60
     */
    resolution: createPropertyDescriptor("resolution"),

    /**
     * Gets or sets the Property specifying the material used to draw the path.
     * @memberof PathGraphics.prototype
     * @type {MaterialProperty}
     * @default Color.WHITE
     */
    material: createMaterialPropertyDescriptor("material"),

    /**
     * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this path will be displayed.
     * @memberof PathGraphics.prototype
     * @type {Property|undefined}
     */
    distanceDisplayCondition: createPropertyDescriptor(
      "distanceDisplayCondition"
    ),
  });

  /**
   * Duplicates this instance.
   *
   * @param {PathGraphics} [result] The object onto which to store the result.
   * @returns {PathGraphics} The modified result parameter or a new instance if one was not provided.
   */
  PathGraphics.prototype.clone = function (result) {
    if (!defined(result)) {
      return new PathGraphics(this);
    }
    result.show = this.show;
    result.leadTime = this.leadTime;
    result.trailTime = this.trailTime;
    result.width = this.width;
    result.resolution = this.resolution;
    result.material = this.material;
    result.distanceDisplayCondition = this.distanceDisplayCondition;
    return result;
  };

  /**
   * Assigns each unassigned property on this object to the value
   * of the same property on the provided source object.
   *
   * @param {PathGraphics} source The object to be merged into this object.
   */
  PathGraphics.prototype.merge = function (source) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(source)) {
      throw new DeveloperError("source is required.");
    }
    //>>includeEnd('debug');

    this.show = defaultValue(this.show, source.show);
    this.leadTime = defaultValue(this.leadTime, source.leadTime);
    this.trailTime = defaultValue(this.trailTime, source.trailTime);
    this.width = defaultValue(this.width, source.width);
    this.resolution = defaultValue(this.resolution, source.resolution);
    this.material = defaultValue(this.material, source.material);
    this.distanceDisplayCondition = defaultValue(
      this.distanceDisplayCondition,
      source.distanceDisplayCondition
    );
  };

  /**
   * @typedef {Object} PlaneGraphics.ConstructorOptions
   *
   * Initialization options for the PlaneGraphics constructor
   *
   * @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the plane.
   * @property {Property | Plane} [plane] A {@link Plane} Property specifying the normal and distance for the plane.
   * @property {Property | Cartesian2} [dimensions] A {@link Cartesian2} Property specifying the width and height of the plane.
   * @property {Property | boolean} [fill=true] A boolean Property specifying whether the plane is filled with the provided material.
   * @property {MaterialProperty | Color} [material=Color.WHITE] A Property specifying the material used to fill the plane.
   * @property {Property | boolean} [outline=false] A boolean Property specifying whether the plane is outlined.
   * @property {Property | Color} [outlineColor=Color.BLACK] A Property specifying the {@link Color} of the outline.
   * @property {Property | number} [outlineWidth=1.0] A numeric Property specifying the width of the outline.
   * @property {Property | ShadowMode} [shadows=ShadowMode.DISABLED] An enum Property specifying whether the plane casts or receives shadows from light sources.
   * @property {Property | DistanceDisplayCondition} [distanceDisplayCondition] A Property specifying at what distance from the camera that this plane will be displayed.
   */

  /**
   * Describes a plane. The center position and orientation are determined by the containing {@link Entity}.
   *
   * @alias PlaneGraphics
   * @constructor
   *
   * @param {PlaneGraphics.ConstructorOptions} [options] Object describing initialization options
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Plane.html|Cesium Sandcastle Plane Demo}
   */
  function PlaneGraphics(options) {
    this._definitionChanged = new Event();
    this._show = undefined;
    this._showSubscription = undefined;
    this._plane = undefined;
    this._planeSubscription = undefined;
    this._dimensions = undefined;
    this._dimensionsSubscription = undefined;
    this._fill = undefined;
    this._fillSubscription = undefined;
    this._material = undefined;
    this._materialSubscription = undefined;
    this._outline = undefined;
    this._outlineSubscription = undefined;
    this._outlineColor = undefined;
    this._outlineColorSubscription = undefined;
    this._outlineWidth = undefined;
    this._outlineWidthSubscription = undefined;
    this._shadows = undefined;
    this._shadowsSubscription = undefined;
    this._distanceDisplayCondition = undefined;
    this._distanceDisplayConditionSubscription = undefined;

    this.merge(defaultValue(options, defaultValue.EMPTY_OBJECT));
  }

  Object.defineProperties(PlaneGraphics.prototype, {
    /**
     * Gets the event that is raised whenever a property or sub-property is changed or modified.
     * @memberof PlaneGraphics.prototype
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },

    /**
     * Gets or sets the boolean Property specifying the visibility of the plane.
     * @memberof PlaneGraphics.prototype
     * @type {Property|undefined}
     * @default true
     */
    show: createPropertyDescriptor("show"),

    /**
     * Gets or sets the {@link Plane} Property specifying the normal and distance of the plane.
     *
     * @memberof PlaneGraphics.prototype
     * @type {Property|undefined}
     */
    plane: createPropertyDescriptor("plane"),

    /**
     * Gets or sets the {@link Cartesian2} Property specifying the width and height of the plane.
     *
     * @memberof PlaneGraphics.prototype
     * @type {Property|undefined}
     */
    dimensions: createPropertyDescriptor("dimensions"),

    /**
     * Gets or sets the boolean Property specifying whether the plane is filled with the provided material.
     * @memberof PlaneGraphics.prototype
     * @type {Property|undefined}
     * @default true
     */
    fill: createPropertyDescriptor("fill"),

    /**
     * Gets or sets the material used to fill the plane.
     * @memberof PlaneGraphics.prototype
     * @type {MaterialProperty}
     * @default Color.WHITE
     */
    material: createMaterialPropertyDescriptor("material"),

    /**
     * Gets or sets the Property specifying whether the plane is outlined.
     * @memberof PlaneGraphics.prototype
     * @type {Property|undefined}
     * @default false
     */
    outline: createPropertyDescriptor("outline"),

    /**
     * Gets or sets the Property specifying the {@link Color} of the outline.
     * @memberof PlaneGraphics.prototype
     * @type {Property|undefined}
     * @default Color.BLACK
     */
    outlineColor: createPropertyDescriptor("outlineColor"),

    /**
     * Gets or sets the numeric Property specifying the width of the outline.
     * <p>
     * Note: This property will be ignored on all major browsers on Windows platforms. For details, see (@link https://github.com/CesiumGS/cesium/issues/40}.
     * </p>
     * @memberof PlaneGraphics.prototype
     * @type {Property|undefined}
     * @default 1.0
     */
    outlineWidth: createPropertyDescriptor("outlineWidth"),

    /**
     * Get or sets the enum Property specifying whether the plane
     * casts or receives shadows from light sources.
     * @memberof PlaneGraphics.prototype
     * @type {Property|undefined}
     * @default ShadowMode.DISABLED
     */
    shadows: createPropertyDescriptor("shadows"),

    /**
     * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this plane will be displayed.
     * @memberof PlaneGraphics.prototype
     * @type {Property|undefined}
     */
    distanceDisplayCondition: createPropertyDescriptor(
      "distanceDisplayCondition"
    ),
  });

  /**
   * Duplicates this instance.
   *
   * @param {PlaneGraphics} [result] The object onto which to store the result.
   * @returns {PlaneGraphics} The modified result parameter or a new instance if one was not provided.
   */
  PlaneGraphics.prototype.clone = function (result) {
    if (!defined(result)) {
      return new PlaneGraphics(this);
    }
    result.show = this.show;
    result.plane = this.plane;
    result.dimensions = this.dimensions;
    result.fill = this.fill;
    result.material = this.material;
    result.outline = this.outline;
    result.outlineColor = this.outlineColor;
    result.outlineWidth = this.outlineWidth;
    result.shadows = this.shadows;
    result.distanceDisplayCondition = this.distanceDisplayCondition;
    return result;
  };

  /**
   * Assigns each unassigned property on this object to the value
   * of the same property on the provided source object.
   *
   * @param {PlaneGraphics} source The object to be merged into this object.
   */
  PlaneGraphics.prototype.merge = function (source) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(source)) {
      throw new DeveloperError("source is required.");
    }
    //>>includeEnd('debug');

    this.show = defaultValue(this.show, source.show);
    this.plane = defaultValue(this.plane, source.plane);
    this.dimensions = defaultValue(this.dimensions, source.dimensions);
    this.fill = defaultValue(this.fill, source.fill);
    this.material = defaultValue(this.material, source.material);
    this.outline = defaultValue(this.outline, source.outline);
    this.outlineColor = defaultValue(this.outlineColor, source.outlineColor);
    this.outlineWidth = defaultValue(this.outlineWidth, source.outlineWidth);
    this.shadows = defaultValue(this.shadows, source.shadows);
    this.distanceDisplayCondition = defaultValue(
      this.distanceDisplayCondition,
      source.distanceDisplayCondition
    );
  };

  /**
   * @typedef {Object} PointGraphics.ConstructorOptions
   *
   * Initialization options for the PointGraphics constructor
   *
   * @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the point.
   * @property {Property | number} [pixelSize=1] A numeric Property specifying the size in pixels.
   * @property {Property | HeightReference} [heightReference=HeightReference.NONE] A Property specifying what the height is relative to.
   * @property {Property | Color} [color=Color.WHITE] A Property specifying the {@link Color} of the point.
   * @property {Property | Color} [outlineColor=Color.BLACK] A Property specifying the {@link Color} of the outline.
   * @property {Property | number} [outlineWidth=0] A numeric Property specifying the the outline width in pixels.
   * @property {Property | NearFarScalar} [scaleByDistance] A {@link NearFarScalar} Property used to scale the point based on distance.
   * @property {Property | NearFarScalar} [translucencyByDistance] A {@link NearFarScalar} Property used to set translucency based on distance from the camera.
   * @property {Property | DistanceDisplayCondition} [distanceDisplayCondition] A Property specifying at what distance from the camera that this point will be displayed.
   * @property {Property | number} [disableDepthTestDistance] A Property specifying the distance from the camera at which to disable the depth test to.
   */

  /**
   * Describes a graphical point located at the position of the containing {@link Entity}.
   *
   * @alias PointGraphics
   * @constructor
   *
   * @param {PointGraphics.ConstructorOptions} [options] Object describing initialization options
   */
  function PointGraphics(options) {
    this._definitionChanged = new Event();
    this._show = undefined;
    this._showSubscription = undefined;
    this._pixelSize = undefined;
    this._pixelSizeSubscription = undefined;
    this._heightReference = undefined;
    this._heightReferenceSubscription = undefined;
    this._color = undefined;
    this._colorSubscription = undefined;
    this._outlineColor = undefined;
    this._outlineColorSubscription = undefined;
    this._outlineWidth = undefined;
    this._outlineWidthSubscription = undefined;
    this._scaleByDistance = undefined;
    this._scaleByDistanceSubscription = undefined;
    this._translucencyByDistance = undefined;
    this._translucencyByDistanceSubscription = undefined;
    this._distanceDisplayCondition = undefined;
    this._distanceDisplayConditionSubscription = undefined;
    this._disableDepthTestDistance = undefined;
    this._disableDepthTestDistanceSubscription = undefined;

    this.merge(defaultValue(options, defaultValue.EMPTY_OBJECT));
  }

  Object.defineProperties(PointGraphics.prototype, {
    /**
     * Gets the event that is raised whenever a property or sub-property is changed or modified.
     * @memberof PointGraphics.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },

    /**
     * Gets or sets the boolean Property specifying the visibility of the point.
     * @memberof PointGraphics.prototype
     * @type {Property|undefined}
     * @default true
     */
    show: createPropertyDescriptor("show"),

    /**
     * Gets or sets the numeric Property specifying the size in pixels.
     * @memberof PointGraphics.prototype
     * @type {Property|undefined}
     * @default 1
     */
    pixelSize: createPropertyDescriptor("pixelSize"),

    /**
     * Gets or sets the Property specifying the {@link HeightReference}.
     * @memberof PointGraphics.prototype
     * @type {Property|undefined}
     * @default HeightReference.NONE
     */
    heightReference: createPropertyDescriptor("heightReference"),

    /**
     * Gets or sets the Property specifying the {@link Color} of the point.
     * @memberof PointGraphics.prototype
     * @type {Property|undefined}
     * @default Color.WHITE
     */
    color: createPropertyDescriptor("color"),

    /**
     * Gets or sets the Property specifying the {@link Color} of the outline.
     * @memberof PointGraphics.prototype
     * @type {Property|undefined}
     * @default Color.BLACK
     */
    outlineColor: createPropertyDescriptor("outlineColor"),

    /**
     * Gets or sets the numeric Property specifying the the outline width in pixels.
     * @memberof PointGraphics.prototype
     * @type {Property|undefined}
     * @default 0
     */
    outlineWidth: createPropertyDescriptor("outlineWidth"),

    /**
     * Gets or sets the {@link NearFarScalar} Property used to scale the point based on distance.
     * If undefined, a constant size is used.
     * @memberof PointGraphics.prototype
     * @type {Property|undefined}
     */
    scaleByDistance: createPropertyDescriptor("scaleByDistance"),

    /**
     * Gets or sets {@link NearFarScalar} Property specifying the translucency of the point based on the distance from the camera.
     * A point's translucency will interpolate between the {@link NearFarScalar#nearValue} and
     * {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds
     * of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}.
     * Outside of these ranges the points's translucency remains clamped to the nearest bound.
     * @memberof PointGraphics.prototype
     * @type {Property|undefined}
     */
    translucencyByDistance: createPropertyDescriptor("translucencyByDistance"),

    /**
     * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this point will be displayed.
     * @memberof PointGraphics.prototype
     * @type {Property|undefined}
     */
    distanceDisplayCondition: createPropertyDescriptor(
      "distanceDisplayCondition"
    ),

    /**
     * Gets or sets the distance from the camera at which to disable the depth test to, for example, prevent clipping against terrain.
     * When set to zero, the depth test is always applied. When set to Number.POSITIVE_INFINITY, the depth test is never applied.
     * @memberof PointGraphics.prototype
     * @type {Property|undefined}
     */
    disableDepthTestDistance: createPropertyDescriptor(
      "disableDepthTestDistance"
    ),
  });

  /**
   * Duplicates this instance.
   *
   * @param {PointGraphics} [result] The object onto which to store the result.
   * @returns {PointGraphics} The modified result parameter or a new instance if one was not provided.
   */
  PointGraphics.prototype.clone = function (result) {
    if (!defined(result)) {
      return new PointGraphics(this);
    }
    result.show = this.show;
    result.pixelSize = this.pixelSize;
    result.heightReference = this.heightReference;
    result.color = this.color;
    result.outlineColor = this.outlineColor;
    result.outlineWidth = this.outlineWidth;
    result.scaleByDistance = this.scaleByDistance;
    result.translucencyByDistance = this._translucencyByDistance;
    result.distanceDisplayCondition = this.distanceDisplayCondition;
    result.disableDepthTestDistance = this.disableDepthTestDistance;
    return result;
  };

  /**
   * Assigns each unassigned property on this object to the value
   * of the same property on the provided source object.
   *
   * @param {PointGraphics} source The object to be merged into this object.
   */
  PointGraphics.prototype.merge = function (source) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(source)) {
      throw new DeveloperError("source is required.");
    }
    //>>includeEnd('debug');

    this.show = defaultValue(this.show, source.show);
    this.pixelSize = defaultValue(this.pixelSize, source.pixelSize);
    this.heightReference = defaultValue(
      this.heightReference,
      source.heightReference
    );
    this.color = defaultValue(this.color, source.color);
    this.outlineColor = defaultValue(this.outlineColor, source.outlineColor);
    this.outlineWidth = defaultValue(this.outlineWidth, source.outlineWidth);
    this.scaleByDistance = defaultValue(
      this.scaleByDistance,
      source.scaleByDistance
    );
    this.translucencyByDistance = defaultValue(
      this._translucencyByDistance,
      source.translucencyByDistance
    );
    this.distanceDisplayCondition = defaultValue(
      this.distanceDisplayCondition,
      source.distanceDisplayCondition
    );
    this.disableDepthTestDistance = defaultValue(
      this.disableDepthTestDistance,
      source.disableDepthTestDistance
    );
  };

  function createPolygonHierarchyProperty(value) {
    if (Array.isArray(value)) {
      // convert array of positions to PolygonHierarchy object
      value = new PolygonHierarchy(value);
    }
    return new ConstantProperty(value);
  }

  /**
   * @typedef {Object} PolygonGraphics.ConstructorOptions
   *
   * Initialization options for the PolygonGraphics constructor
   *
   * @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the polygon.
   * @property {Property | PolygonHierarchy} [hierarchy] A Property specifying the {@link PolygonHierarchy}.
   * @property {Property | number} [height=0] A numeric Property specifying the altitude of the polygon relative to the ellipsoid surface.
   * @property {Property | HeightReference} [heightReference=HeightReference.NONE] A Property specifying what the height is relative to.
   * @property {Property | number} [extrudedHeight] A numeric Property specifying the altitude of the polygon's extruded face relative to the ellipsoid surface.
   * @property {Property | HeightReference} [extrudedHeightReference=HeightReference.NONE] A Property specifying what the extrudedHeight is relative to.
   * @property {Property | number} [stRotation=0.0] A numeric property specifying the rotation of the polygon texture counter-clockwise from north. Only has an effect if textureCoordinates is not defined.
   * @property {Property | number} [granularity=Cesium.Math.RADIANS_PER_DEGREE] A numeric Property specifying the angular distance between each latitude and longitude point.
   * @property {Property | boolean} [fill=true] A boolean Property specifying whether the polygon is filled with the provided material.
   * @property {MaterialProperty | Color} [material=Color.WHITE] A Property specifying the material used to fill the polygon.
   * @property {Property | boolean} [outline=false] A boolean Property specifying whether the polygon is outlined.
   * @property {Property | Color} [outlineColor=Color.BLACK] A Property specifying the {@link Color} of the outline.
   * @property {Property | number} [outlineWidth=1.0] A numeric Property specifying the width of the outline.
   * @property {Property | boolean} [perPositionHeight=false] A boolean specifying whether or not the height of each position is used.
   * @property {Boolean | boolean} [closeTop=true] When false, leaves off the top of an extruded polygon open.
   * @property {Boolean | boolean} [closeBottom=true] When false, leaves off the bottom of an extruded polygon open.
   * @property {Property | ArcType} [arcType=ArcType.GEODESIC] The type of line the polygon edges must follow.
   * @property {Property | ShadowMode} [shadows=ShadowMode.DISABLED] An enum Property specifying whether the polygon casts or receives shadows from light sources.
   * @property {Property | DistanceDisplayCondition} [distanceDisplayCondition] A Property specifying at what distance from the camera that this polygon will be displayed.
   * @property {Property | ClassificationType} [classificationType=ClassificationType.BOTH] An enum Property specifying whether this polygon will classify terrain, 3D Tiles, or both when on the ground.
   * @property {ConstantProperty | number} [zIndex=0] A property specifying the zIndex used for ordering ground geometry.  Only has an effect if the polygon is constant and neither height or extrudedHeight are specified.
   * @property {Property | PolygonHierarchy} [textureCoordinates] A Property specifying texture coordinates as a {@link PolygonHierarchy} of {@link Cartesian2} points. Has no effect for ground primitives.
   */

  /**
   * Describes a polygon defined by an hierarchy of linear rings which make up the outer shape and any nested holes.
   * The polygon conforms to the curvature of the globe and can be placed on the surface or
   * at altitude and can optionally be extruded into a volume.
   *
   * @alias PolygonGraphics
   * @constructor
   *
   * @param {PolygonGraphics.ConstructorOptions} [options] Object describing initialization options
   *
   * @see Entity
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Polygon.html|Cesium Sandcastle Polygon Demo}
   */
  function PolygonGraphics(options) {
    this._definitionChanged = new Event();
    this._show = undefined;
    this._showSubscription = undefined;
    this._hierarchy = undefined;
    this._hierarchySubscription = undefined;
    this._height = undefined;
    this._heightSubscription = undefined;
    this._heightReference = undefined;
    this._heightReferenceSubscription = undefined;
    this._extrudedHeight = undefined;
    this._extrudedHeightSubscription = undefined;
    this._extrudedHeightReference = undefined;
    this._extrudedHeightReferenceSubscription = undefined;
    this._stRotation = undefined;
    this._stRotationSubscription = undefined;
    this._granularity = undefined;
    this._granularitySubscription = undefined;
    this._fill = undefined;
    this._fillSubscription = undefined;
    this._material = undefined;
    this._materialSubscription = undefined;
    this._outline = undefined;
    this._outlineSubscription = undefined;
    this._outlineColor = undefined;
    this._outlineColorSubscription = undefined;
    this._outlineWidth = undefined;
    this._outlineWidthSubscription = undefined;
    this._perPositionHeight = undefined;
    this._perPositionHeightSubscription = undefined;
    this._closeTop = undefined;
    this._closeTopSubscription = undefined;
    this._closeBottom = undefined;
    this._closeBottomSubscription = undefined;
    this._arcType = undefined;
    this._arcTypeSubscription = undefined;
    this._shadows = undefined;
    this._shadowsSubscription = undefined;
    this._distanceDisplayCondition = undefined;
    this._distanceDisplayConditionSubscription = undefined;
    this._classificationType = undefined;
    this._classificationTypeSubscription = undefined;
    this._zIndex = undefined;
    this._zIndexSubscription = undefined;
    this._textureCoordinates = undefined;
    this._textureCoordinatesSubscription = undefined;

    this.merge(defaultValue(options, defaultValue.EMPTY_OBJECT));
  }

  Object.defineProperties(PolygonGraphics.prototype, {
    /**
     * Gets the event that is raised whenever a property or sub-property is changed or modified.
     * @memberof PolygonGraphics.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },

    /**
     * Gets or sets the boolean Property specifying the visibility of the polygon.
     * @memberof PolygonGraphics.prototype
     * @type {Property|undefined}
     * @default true
     */
    show: createPropertyDescriptor("show"),

    /**
     * Gets or sets the Property specifying the {@link PolygonHierarchy}.
     * @memberof PolygonGraphics.prototype
     * @type {Property|undefined}
     */
    hierarchy: createPropertyDescriptor(
      "hierarchy",
      undefined,
      createPolygonHierarchyProperty
    ),

    /**
     * Gets or sets the numeric Property specifying the constant altitude of the polygon.
     * @memberof PolygonGraphics.prototype
     * @type {Property|undefined}
     * @default 0.0
     */
    height: createPropertyDescriptor("height"),

    /**
     * Gets or sets the Property specifying the {@link HeightReference}.
     * @memberof PolygonGraphics.prototype
     * @type {Property|undefined}
     * @default HeightReference.NONE
     */
    heightReference: createPropertyDescriptor("heightReference"),

    /**
     * Gets or sets the numeric Property specifying the altitude of the polygon extrusion.
     * If {@link PolygonGraphics#perPositionHeight} is false, the volume starts at {@link PolygonGraphics#height} and ends at this altitude.
     * If {@link PolygonGraphics#perPositionHeight} is true, the volume starts at the height of each {@link PolygonGraphics#hierarchy} position and ends at this altitude.
     * @memberof PolygonGraphics.prototype
     * @type {Property|undefined}
     */
    extrudedHeight: createPropertyDescriptor("extrudedHeight"),

    /**
     * Gets or sets the Property specifying the extruded {@link HeightReference}.
     * @memberof PolygonGraphics.prototype
     * @type {Property|undefined}
     * @default HeightReference.NONE
     */
    extrudedHeightReference: createPropertyDescriptor("extrudedHeightReference"),

    /**
     * Gets or sets the numeric property specifying the rotation of the polygon texture counter-clockwise from north. Only has an effect if textureCoordinates is not defined.
     * @memberof PolygonGraphics.prototype
     * @type {Property|undefined}
     * @default 0
     */
    stRotation: createPropertyDescriptor("stRotation"),

    /**
     * Gets or sets the numeric Property specifying the angular distance between points on the polygon.
     * @memberof PolygonGraphics.prototype
     * @type {Property|undefined}
     * @default {CesiumMath.RADIANS_PER_DEGREE}
     */
    granularity: createPropertyDescriptor("granularity"),

    /**
     * Gets or sets the boolean Property specifying whether the polygon is filled with the provided material.
     * @memberof PolygonGraphics.prototype
     * @type {Property|undefined}
     * @default true
     */
    fill: createPropertyDescriptor("fill"),

    /**
     * Gets or sets the Property specifying the material used to fill the polygon.
     * @memberof PolygonGraphics.prototype
     * @type {MaterialProperty}
     * @default Color.WHITE
     */
    material: createMaterialPropertyDescriptor("material"),

    /**
     * Gets or sets the Property specifying whether the polygon is outlined.
     * @memberof PolygonGraphics.prototype
     * @type {Property|undefined}
     * @default false
     */
    outline: createPropertyDescriptor("outline"),

    /**
     * Gets or sets the Property specifying the {@link Color} of the outline.
     * @memberof PolygonGraphics.prototype
     * @type {Property|undefined}
     * @default Color.BLACK
     */
    outlineColor: createPropertyDescriptor("outlineColor"),

    /**
     * Gets or sets the numeric Property specifying the width of the outline.
     * <p>
     * Note: This property will be ignored on all major browsers on Windows platforms. For details, see (@link https://github.com/CesiumGS/cesium/issues/40}.
     * </p>
     * @memberof PolygonGraphics.prototype
     * @type {Property|undefined}
     * @default 1.0
     */
    outlineWidth: createPropertyDescriptor("outlineWidth"),

    /**
     * Gets or sets the boolean specifying whether or not the the height of each position is used.
     * If true, the shape will have non-uniform altitude defined by the height of each {@link PolygonGraphics#hierarchy} position.
     * If false, the shape will have a constant altitude as specified by {@link PolygonGraphics#height}.
     * @memberof PolygonGraphics.prototype
     * @type {Property|undefined}
     */
    perPositionHeight: createPropertyDescriptor("perPositionHeight"),

    /**
     * Gets or sets a boolean specifying whether or not the top of an extruded polygon is included.
     * @memberof PolygonGraphics.prototype
     * @type {Property|undefined}
     */
    closeTop: createPropertyDescriptor("closeTop"),

    /**
     * Gets or sets a boolean specifying whether or not the bottom of an extruded polygon is included.
     * @memberof PolygonGraphics.prototype
     * @type {Property|undefined}
     */
    closeBottom: createPropertyDescriptor("closeBottom"),

    /**
     * Gets or sets the {@link ArcType} Property specifying the type of lines the polygon edges use.
     * @memberof PolygonGraphics.prototype
     * @type {Property|undefined}
     * @default ArcType.GEODESIC
     */
    arcType: createPropertyDescriptor("arcType"),

    /**
     * Get or sets the enum Property specifying whether the polygon
     * casts or receives shadows from light sources.
     * @memberof PolygonGraphics.prototype
     * @type {Property|undefined}
     * @default ShadowMode.DISABLED
     */
    shadows: createPropertyDescriptor("shadows"),

    /**
     * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this polygon will be displayed.
     * @memberof PolygonGraphics.prototype
     * @type {Property|undefined}
     */
    distanceDisplayCondition: createPropertyDescriptor(
      "distanceDisplayCondition"
    ),

    /**
     * Gets or sets the {@link ClassificationType} Property specifying whether this polygon will classify terrain, 3D Tiles, or both when on the ground.
     * @memberof PolygonGraphics.prototype
     * @type {Property|undefined}
     * @default ClassificationType.BOTH
     */
    classificationType: createPropertyDescriptor("classificationType"),

    /**
     * Gets or sets the zIndex Prperty specifying the ordering of ground geometry.  Only has an effect if the polygon is constant and neither height or extrudedHeight are specified.
     * @memberof PolygonGraphics.prototype
     * @type {ConstantProperty|undefined}
     * @default 0
     */
    zIndex: createPropertyDescriptor("zIndex"),

    /**
     *  A Property specifying texture coordinates as a {@link PolygonHierarchy} of {@link Cartesian2} points. Has no effect for ground primitives.
     * @memberof PolygonGraphics.prototype
     * @type {Property|undefined}
     */
    textureCoordinates: createPropertyDescriptor("textureCoordinates"),
  });

  /**
   * Duplicates this instance.
   *
   * @param {PolygonGraphics} [result] The object onto which to store the result.
   * @returns {PolygonGraphics} The modified result parameter or a new instance if one was not provided.
   */
  PolygonGraphics.prototype.clone = function (result) {
    if (!defined(result)) {
      return new PolygonGraphics(this);
    }
    result.show = this.show;
    result.hierarchy = this.hierarchy;
    result.height = this.height;
    result.heightReference = this.heightReference;
    result.extrudedHeight = this.extrudedHeight;
    result.extrudedHeightReference = this.extrudedHeightReference;
    result.stRotation = this.stRotation;
    result.granularity = this.granularity;
    result.fill = this.fill;
    result.material = this.material;
    result.outline = this.outline;
    result.outlineColor = this.outlineColor;
    result.outlineWidth = this.outlineWidth;
    result.perPositionHeight = this.perPositionHeight;
    result.closeTop = this.closeTop;
    result.closeBottom = this.closeBottom;
    result.arcType = this.arcType;
    result.shadows = this.shadows;
    result.distanceDisplayCondition = this.distanceDisplayCondition;
    result.classificationType = this.classificationType;
    result.zIndex = this.zIndex;
    result.textureCoordinates = this.textureCoordinates;
    return result;
  };

  /**
   * Assigns each unassigned property on this object to the value
   * of the same property on the provided source object.
   *
   * @param {PolygonGraphics} source The object to be merged into this object.
   */
  PolygonGraphics.prototype.merge = function (source) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(source)) {
      throw new DeveloperError("source is required.");
    }
    //>>includeEnd('debug');

    this.show = defaultValue(this.show, source.show);
    this.hierarchy = defaultValue(this.hierarchy, source.hierarchy);
    this.height = defaultValue(this.height, source.height);
    this.heightReference = defaultValue(
      this.heightReference,
      source.heightReference
    );
    this.extrudedHeight = defaultValue(
      this.extrudedHeight,
      source.extrudedHeight
    );
    this.extrudedHeightReference = defaultValue(
      this.extrudedHeightReference,
      source.extrudedHeightReference
    );
    this.stRotation = defaultValue(this.stRotation, source.stRotation);
    this.granularity = defaultValue(this.granularity, source.granularity);
    this.fill = defaultValue(this.fill, source.fill);
    this.material = defaultValue(this.material, source.material);
    this.outline = defaultValue(this.outline, source.outline);
    this.outlineColor = defaultValue(this.outlineColor, source.outlineColor);
    this.outlineWidth = defaultValue(this.outlineWidth, source.outlineWidth);
    this.perPositionHeight = defaultValue(
      this.perPositionHeight,
      source.perPositionHeight
    );
    this.closeTop = defaultValue(this.closeTop, source.closeTop);
    this.closeBottom = defaultValue(this.closeBottom, source.closeBottom);
    this.arcType = defaultValue(this.arcType, source.arcType);
    this.shadows = defaultValue(this.shadows, source.shadows);
    this.distanceDisplayCondition = defaultValue(
      this.distanceDisplayCondition,
      source.distanceDisplayCondition
    );
    this.classificationType = defaultValue(
      this.classificationType,
      source.classificationType
    );
    this.zIndex = defaultValue(this.zIndex, source.zIndex);
    this.textureCoordinates = defaultValue(
      this.textureCoordinates,
      source.textureCoordinates
    );
  };

  /**
   * @typedef {Object} PolylineGraphics.ConstructorOptions
   *
   * Initialization options for the PolylineGraphics constructor
   *
   * @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the polyline.
   * @property {Property | Array<Cartesian3>} [positions] A Property specifying the array of {@link Cartesian3} positions that define the line strip.
   * @property {Property | number} [width=1.0] A numeric Property specifying the width in pixels.
   * @property {Property | number} [granularity=Cesium.Math.RADIANS_PER_DEGREE] A numeric Property specifying the angular distance between each latitude and longitude if arcType is not ArcType.NONE.
   * @property {MaterialProperty | Color} [material=Color.WHITE] A Property specifying the material used to draw the polyline.
   * @property {MaterialProperty | Color} [depthFailMaterial] A property specifying the material used to draw the polyline when it is below the terrain.
   * @property {Property | ArcType} [arcType=ArcType.GEODESIC] The type of line the polyline segments must follow.
   * @property {Property | boolean} [clampToGround=false] A boolean Property specifying whether the Polyline should be clamped to the ground.
   * @property {Property | ShadowMode} [shadows=ShadowMode.DISABLED] An enum Property specifying whether the polyline casts or receives shadows from light sources.
   * @property {Property | DistanceDisplayCondition} [distanceDisplayCondition] A Property specifying at what distance from the camera that this polyline will be displayed.
   * @property {Property | ClassificationType} [classificationType=ClassificationType.BOTH] An enum Property specifying whether this polyline will classify terrain, 3D Tiles, or both when on the ground.
   * @property {Property | number} [zIndex=0] A Property specifying the zIndex used for ordering ground geometry. Only has an effect if `clampToGround` is true and polylines on terrain is supported.
   */

  /**
   * Describes a polyline. The first two positions define a line segment,
   * and each additional position defines a line segment from the previous position. The segments
   * can be linear connected points, great arcs, or clamped to terrain.
   *
   * @alias PolylineGraphics
   * @constructor
   *
   * @param {PolylineGraphics.ConstructorOptions} [options] Object describing initialization options
   *
   * @see Entity
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Polyline.html|Cesium Sandcastle Polyline Demo}
   */
  function PolylineGraphics(options) {
    this._definitionChanged = new Event();
    this._show = undefined;
    this._showSubscription = undefined;
    this._positions = undefined;
    this._positionsSubscription = undefined;
    this._width = undefined;
    this._widthSubscription = undefined;
    this._granularity = undefined;
    this._granularitySubscription = undefined;
    this._material = undefined;
    this._materialSubscription = undefined;
    this._depthFailMaterial = undefined;
    this._depthFailMaterialSubscription = undefined;
    this._arcType = undefined;
    this._arcTypeSubscription = undefined;
    this._clampToGround = undefined;
    this._clampToGroundSubscription = undefined;
    this._shadows = undefined;
    this._shadowsSubscription = undefined;
    this._distanceDisplayCondition = undefined;
    this._distanceDisplayConditionSubscription = undefined;
    this._classificationType = undefined;
    this._classificationTypeSubscription = undefined;
    this._zIndex = undefined;
    this._zIndexSubscription = undefined;

    this.merge(defaultValue(options, defaultValue.EMPTY_OBJECT));
  }

  Object.defineProperties(PolylineGraphics.prototype, {
    /**
     * Gets the event that is raised whenever a property or sub-property is changed or modified.
     * @memberof PolylineGraphics.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },

    /**
     * Gets or sets the boolean Property specifying the visibility of the polyline.
     * @memberof PolylineGraphics.prototype
     * @type {Property|undefined}
     * @default true
     */
    show: createPropertyDescriptor("show"),

    /**
     * Gets or sets the Property specifying the array of {@link Cartesian3}
     * positions that define the line strip.
     * @memberof PolylineGraphics.prototype
     * @type {Property|undefined}
     */
    positions: createPropertyDescriptor("positions"),

    /**
     * Gets or sets the numeric Property specifying the width in pixels.
     * @memberof PolylineGraphics.prototype
     * @type {Property|undefined}
     * @default 1.0
     */
    width: createPropertyDescriptor("width"),

    /**
     * Gets or sets the numeric Property specifying the angular distance between each latitude and longitude if arcType is not ArcType.NONE and clampToGround is false.
     * @memberof PolylineGraphics.prototype
     * @type {Property|undefined}
     * @default Cesium.Math.RADIANS_PER_DEGREE
     */
    granularity: createPropertyDescriptor("granularity"),

    /**
     * Gets or sets the Property specifying the material used to draw the polyline.
     * @memberof PolylineGraphics.prototype
     * @type {MaterialProperty}
     * @default Color.WHITE
     */
    material: createMaterialPropertyDescriptor("material"),

    /**
     * Gets or sets the Property specifying the material used to draw the polyline when it fails the depth test.
     * <p>
     * Requires the EXT_frag_depth WebGL extension to render properly. If the extension is not supported,
     * there may be artifacts.
     * </p>
     * @memberof PolylineGraphics.prototype
     * @type {MaterialProperty}
     * @default undefined
     */
    depthFailMaterial: createMaterialPropertyDescriptor("depthFailMaterial"),

    /**
     * Gets or sets the {@link ArcType} Property specifying whether the line segments should be great arcs, rhumb lines or linearly connected.
     * @memberof PolylineGraphics.prototype
     * @type {Property|undefined}
     * @default ArcType.GEODESIC
     */
    arcType: createPropertyDescriptor("arcType"),

    /**
     * Gets or sets the boolean Property specifying whether the polyline
     * should be clamped to the ground.
     * @memberof PolylineGraphics.prototype
     * @type {Property|undefined}
     * @default false
     */
    clampToGround: createPropertyDescriptor("clampToGround"),

    /**
     * Get or sets the enum Property specifying whether the polyline
     * casts or receives shadows from light sources.
     * @memberof PolylineGraphics.prototype
     * @type {Property|undefined}
     * @default ShadowMode.DISABLED
     */
    shadows: createPropertyDescriptor("shadows"),

    /**
     * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this polyline will be displayed.
     * @memberof PolylineGraphics.prototype
     * @type {Property|undefined}
     */
    distanceDisplayCondition: createPropertyDescriptor(
      "distanceDisplayCondition"
    ),

    /**
     * Gets or sets the {@link ClassificationType} Property specifying whether this polyline will classify terrain, 3D Tiles, or both when on the ground.
     * @memberof PolylineGraphics.prototype
     * @type {Property|undefined}
     * @default ClassificationType.BOTH
     */
    classificationType: createPropertyDescriptor("classificationType"),

    /**
     * Gets or sets the zIndex Property specifying the ordering of the polyline. Only has an effect if `clampToGround` is true and polylines on terrain is supported.
     * @memberof PolylineGraphics.prototype
     * @type {ConstantProperty|undefined}
     * @default 0
     */
    zIndex: createPropertyDescriptor("zIndex"),
  });

  /**
   * Duplicates this instance.
   *
   * @param {PolylineGraphics} [result] The object onto which to store the result.
   * @returns {PolylineGraphics} The modified result parameter or a new instance if one was not provided.
   */
  PolylineGraphics.prototype.clone = function (result) {
    if (!defined(result)) {
      return new PolylineGraphics(this);
    }
    result.show = this.show;
    result.positions = this.positions;
    result.width = this.width;
    result.granularity = this.granularity;
    result.material = this.material;
    result.depthFailMaterial = this.depthFailMaterial;
    result.arcType = this.arcType;
    result.clampToGround = this.clampToGround;
    result.shadows = this.shadows;
    result.distanceDisplayCondition = this.distanceDisplayCondition;
    result.classificationType = this.classificationType;
    result.zIndex = this.zIndex;
    return result;
  };

  /**
   * Assigns each unassigned property on this object to the value
   * of the same property on the provided source object.
   *
   * @param {PolylineGraphics} source The object to be merged into this object.
   */
  PolylineGraphics.prototype.merge = function (source) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(source)) {
      throw new DeveloperError("source is required.");
    }
    //>>includeEnd('debug');

    this.show = defaultValue(this.show, source.show);
    this.positions = defaultValue(this.positions, source.positions);
    this.width = defaultValue(this.width, source.width);
    this.granularity = defaultValue(this.granularity, source.granularity);
    this.material = defaultValue(this.material, source.material);
    this.depthFailMaterial = defaultValue(
      this.depthFailMaterial,
      source.depthFailMaterial
    );
    this.arcType = defaultValue(this.arcType, source.arcType);
    this.clampToGround = defaultValue(this.clampToGround, source.clampToGround);
    this.shadows = defaultValue(this.shadows, source.shadows);
    this.distanceDisplayCondition = defaultValue(
      this.distanceDisplayCondition,
      source.distanceDisplayCondition
    );
    this.classificationType = defaultValue(
      this.classificationType,
      source.classificationType
    );
    this.zIndex = defaultValue(this.zIndex, source.zIndex);
  };

  /**
   * @typedef {Object} PolylineVolumeGraphics.ConstructorOptions
   *
   * Initialization options for the PolylineVolumeGraphics constructor
   *
   * @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the volume.
   * @property {Property | Array<Cartesian3>} [positions] A Property specifying the array of {@link Cartesian3} positions which define the line strip.
   * @property {Property | Array<Cartesian2>} [shape] A Property specifying the array of {@link Cartesian2} positions which define the shape to be extruded.
   * @property {Property | CornerType} [cornerType=CornerType.ROUNDED] A {@link CornerType} Property specifying the style of the corners.
   * @property {Property | number} [granularity=Cesium.Math.RADIANS_PER_DEGREE] A numeric Property specifying the angular distance between each latitude and longitude point.
   * @property {Property | boolean} [fill=true] A boolean Property specifying whether the volume is filled with the provided material.
   * @property {MaterialProperty | Color} [material=Color.WHITE] A Property specifying the material used to fill the volume.
   * @property {Property | boolean} [outline=false] A boolean Property specifying whether the volume is outlined.
   * @property {Property | Color} [outlineColor=Color.BLACK] A Property specifying the {@link Color} of the outline.
   * @property {Property | number} [outlineWidth=1.0] A numeric Property specifying the width of the outline.
   * @property {Property | ShadowMode} [shadows=ShadowMode.DISABLED] An enum Property specifying whether the volume casts or receives shadows from light sources.
   * @property {Property | DistanceDisplayCondition} [distanceDisplayCondition] A Property specifying at what distance from the camera that this volume will be displayed.
   */

  /**
   * Describes a polyline volume defined as a line strip and corresponding two dimensional shape which is extruded along it.
   * The resulting volume conforms to the curvature of the globe.
   *
   * @alias PolylineVolumeGraphics
   * @constructor
   *
   * @param {PolylineVolumeGraphics.ConstructorOptions} [options] Object describing initialization options
   *
   * @see Entity
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Polyline%20Volume.html|Cesium Sandcastle Polyline Volume Demo}
   */
  function PolylineVolumeGraphics(options) {
    this._definitionChanged = new Event();
    this._show = undefined;
    this._showSubscription = undefined;
    this._positions = undefined;
    this._positionsSubscription = undefined;
    this._shape = undefined;
    this._shapeSubscription = undefined;
    this._cornerType = undefined;
    this._cornerTypeSubscription = undefined;
    this._granularity = undefined;
    this._granularitySubscription = undefined;
    this._fill = undefined;
    this._fillSubscription = undefined;
    this._material = undefined;
    this._materialSubscription = undefined;
    this._outline = undefined;
    this._outlineSubscription = undefined;
    this._outlineColor = undefined;
    this._outlineColorSubscription = undefined;
    this._outlineWidth = undefined;
    this._outlineWidthSubscription = undefined;
    this._shadows = undefined;
    this._shadowsSubscription = undefined;
    this._distanceDisplayCondition = undefined;
    this._distanceDisplayConditionSubsription = undefined;

    this.merge(defaultValue(options, defaultValue.EMPTY_OBJECT));
  }

  Object.defineProperties(PolylineVolumeGraphics.prototype, {
    /**
     * Gets the event that is raised whenever a property or sub-property is changed or modified.
     * @memberof PolylineVolumeGraphics.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },

    /**
     * Gets or sets the boolean Property specifying the visibility of the volume.
     * @memberof PolylineVolumeGraphics.prototype
     * @type {Property|undefined}
     * @default true
     */
    show: createPropertyDescriptor("show"),

    /**
     * Gets or sets the Property specifying the array of {@link Cartesian3} positions which define the line strip.
     * @memberof PolylineVolumeGraphics.prototype
     * @type {Property|undefined}
     */
    positions: createPropertyDescriptor("positions"),

    /**
     * Gets or sets the Property specifying the array of {@link Cartesian2} positions which define the shape to be extruded.
     * @memberof PolylineVolumeGraphics.prototype
     * @type {Property|undefined}
     */
    shape: createPropertyDescriptor("shape"),

    /**
     * Gets or sets the {@link CornerType} Property specifying the style of the corners.
     * @memberof PolylineVolumeGraphics.prototype
     * @type {Property|undefined}
     * @default CornerType.ROUNDED
     */
    cornerType: createPropertyDescriptor("cornerType"),

    /**
     * Gets or sets the numeric Property specifying the angular distance between points on the volume.
     * @memberof PolylineVolumeGraphics.prototype
     * @type {Property|undefined}
     * @default {CesiumMath.RADIANS_PER_DEGREE}
     */
    granularity: createPropertyDescriptor("granularity"),

    /**
     * Gets or sets the boolean Property specifying whether the volume is filled with the provided material.
     * @memberof PolylineVolumeGraphics.prototype
     * @type {Property|undefined}
     * @default true
     */
    fill: createPropertyDescriptor("fill"),

    /**
     * Gets or sets the Property specifying the material used to fill the volume.
     * @memberof PolylineVolumeGraphics.prototype
     * @type {MaterialProperty}
     * @default Color.WHITE
     */
    material: createMaterialPropertyDescriptor("material"),

    /**
     * Gets or sets the Property specifying whether the volume is outlined.
     * @memberof PolylineVolumeGraphics.prototype
     * @type {Property|undefined}
     * @default false
     */
    outline: createPropertyDescriptor("outline"),

    /**
     * Gets or sets the Property specifying the {@link Color} of the outline.
     * @memberof PolylineVolumeGraphics.prototype
     * @type {Property|undefined}
     * @default Color.BLACK
     */
    outlineColor: createPropertyDescriptor("outlineColor"),

    /**
     * Gets or sets the numeric Property specifying the width of the outline.
     * <p>
     * Note: This property will be ignored on all major browsers on Windows platforms. For details, see (@link https://github.com/CesiumGS/cesium/issues/40}.
     * </p>
     * @memberof PolylineVolumeGraphics.prototype
     * @type {Property|undefined}
     * @default 1.0
     */
    outlineWidth: createPropertyDescriptor("outlineWidth"),

    /**
     * Get or sets the enum Property specifying whether the volume
     * casts or receives shadows from light sources.
     * @memberof PolylineVolumeGraphics.prototype
     * @type {Property|undefined}
     * @default ShadowMode.DISABLED
     */
    shadows: createPropertyDescriptor("shadows"),

    /**
     * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this volume will be displayed.
     * @memberof PolylineVolumeGraphics.prototype
     * @type {Property|undefined}
     */
    distanceDisplayCondition: createPropertyDescriptor(
      "distanceDisplayCondition"
    ),
  });

  /**
   * Duplicates this instance.
   *
   * @param {PolylineVolumeGraphics} [result] The object onto which to store the result.
   * @returns {PolylineVolumeGraphics} The modified result parameter or a new instance if one was not provided.
   */
  PolylineVolumeGraphics.prototype.clone = function (result) {
    if (!defined(result)) {
      return new PolylineVolumeGraphics(this);
    }
    result.show = this.show;
    result.positions = this.positions;
    result.shape = this.shape;
    result.cornerType = this.cornerType;
    result.granularity = this.granularity;
    result.fill = this.fill;
    result.material = this.material;
    result.outline = this.outline;
    result.outlineColor = this.outlineColor;
    result.outlineWidth = this.outlineWidth;
    result.shadows = this.shadows;
    result.distanceDisplayCondition = this.distanceDisplayCondition;
    return result;
  };

  /**
   * Assigns each unassigned property on this object to the value
   * of the same property on the provided source object.
   *
   * @param {PolylineVolumeGraphics} source The object to be merged into this object.
   */
  PolylineVolumeGraphics.prototype.merge = function (source) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(source)) {
      throw new DeveloperError("source is required.");
    }
    //>>includeEnd('debug');

    this.show = defaultValue(this.show, source.show);
    this.positions = defaultValue(this.positions, source.positions);
    this.shape = defaultValue(this.shape, source.shape);
    this.cornerType = defaultValue(this.cornerType, source.cornerType);
    this.granularity = defaultValue(this.granularity, source.granularity);
    this.fill = defaultValue(this.fill, source.fill);
    this.material = defaultValue(this.material, source.material);
    this.outline = defaultValue(this.outline, source.outline);
    this.outlineColor = defaultValue(this.outlineColor, source.outlineColor);
    this.outlineWidth = defaultValue(this.outlineWidth, source.outlineWidth);
    this.shadows = defaultValue(this.shadows, source.shadows);
    this.distanceDisplayCondition = defaultValue(
      this.distanceDisplayCondition,
      source.distanceDisplayCondition
    );
  };

  /**
   * @typedef {Object} RectangleGraphics.ConstructorOptions
   *
   * Initialization options for the RectangleGraphics constructor
   *
   * @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the rectangle.
   * @property {Property | Rectangle} [coordinates] The Property specifying the {@link Rectangle}.
   * @property {Property | number} [height=0] A numeric Property specifying the altitude of the rectangle relative to the ellipsoid surface.
   * @property {Property | HeightReference} [heightReference=HeightReference.NONE] A Property specifying what the height is relative to.
   * @property {Property | number} [extrudedHeight] A numeric Property specifying the altitude of the rectangle's extruded face relative to the ellipsoid surface.
   * @property {Property | HeightReference} [extrudedHeightReference=HeightReference.NONE] A Property specifying what the extrudedHeight is relative to.
   * @property {Property | number} [rotation=0.0] A numeric property specifying the rotation of the rectangle clockwise from north.
   * @property {Property | number} [stRotation=0.0] A numeric property specifying the rotation of the rectangle texture counter-clockwise from north.
   * @property {Property | number} [granularity=Cesium.Math.RADIANS_PER_DEGREE] A numeric Property specifying the angular distance between points on the rectangle.
   * @property {Property | boolean} [fill=true] A boolean Property specifying whether the rectangle is filled with the provided material.
   * @property {MaterialProperty | Color} [material=Color.WHITE] A Property specifying the material used to fill the rectangle.
   * @property {Property | boolean} [outline=false] A boolean Property specifying whether the rectangle is outlined.
   * @property {Property | Color} [outlineColor=Color.BLACK] A Property specifying the {@link Color} of the outline.
   * @property {Property | number} [outlineWidth=1.0] A numeric Property specifying the width of the outline.
   * @property {Property | ShadowMode} [shadows=ShadowMode.DISABLED] An enum Property specifying whether the rectangle casts or receives shadows from light sources.
   * @property {Property | DistanceDisplayCondition} [distanceDisplayCondition] A Property specifying at what distance from the camera that this rectangle will be displayed.
   * @property {Property | ClassificationType} [classificationType=ClassificationType.BOTH] An enum Property specifying whether this rectangle will classify terrain, 3D Tiles, or both when on the ground.
   * @property {Property | number} [zIndex=0] A Property specifying the zIndex used for ordering ground geometry.  Only has an effect if the rectangle is constant and neither height or extrudedHeight are specified.
   */

  /**
   * Describes graphics for a {@link Rectangle}.
   * The rectangle conforms to the curvature of the globe and can be placed on the surface or
   * at altitude and can optionally be extruded into a volume.
   *
   * @alias RectangleGraphics
   * @constructor
   *
   * @param {RectangleGraphics.ConstructorOptions} [options] Object describing initialization options
   *
   * @see Entity
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Rectangle.html|Cesium Sandcastle Rectangle Demo}
   */
  function RectangleGraphics(options) {
    this._definitionChanged = new Event();
    this._show = undefined;
    this._showSubscription = undefined;
    this._coordinates = undefined;
    this._coordinatesSubscription = undefined;
    this._height = undefined;
    this._heightSubscription = undefined;
    this._heightReference = undefined;
    this._heightReferenceSubscription = undefined;
    this._extrudedHeight = undefined;
    this._extrudedHeightSubscription = undefined;
    this._extrudedHeightReference = undefined;
    this._extrudedHeightReferenceSubscription = undefined;
    this._rotation = undefined;
    this._rotationSubscription = undefined;
    this._stRotation = undefined;
    this._stRotationSubscription = undefined;
    this._granularity = undefined;
    this._granularitySubscription = undefined;
    this._fill = undefined;
    this._fillSubscription = undefined;
    this._material = undefined;
    this._materialSubscription = undefined;
    this._outline = undefined;
    this._outlineSubscription = undefined;
    this._outlineColor = undefined;
    this._outlineColorSubscription = undefined;
    this._outlineWidth = undefined;
    this._outlineWidthSubscription = undefined;
    this._shadows = undefined;
    this._shadowsSubscription = undefined;
    this._distanceDisplayCondition = undefined;
    this._distancedisplayConditionSubscription = undefined;
    this._classificationType = undefined;
    this._classificationTypeSubscription = undefined;
    this._zIndex = undefined;
    this._zIndexSubscription = undefined;

    this.merge(defaultValue(options, defaultValue.EMPTY_OBJECT));
  }

  Object.defineProperties(RectangleGraphics.prototype, {
    /**
     * Gets the event that is raised whenever a property or sub-property is changed or modified.
     * @memberof RectangleGraphics.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },

    /**
     * Gets or sets the boolean Property specifying the visibility of the rectangle.
     * @memberof RectangleGraphics.prototype
     * @type {Property|undefined}
     * @default true
     */
    show: createPropertyDescriptor("show"),

    /**
     * Gets or sets the Property specifying the {@link Rectangle}.
     * @memberof RectangleGraphics.prototype
     * @type {Property|undefined}
     */
    coordinates: createPropertyDescriptor("coordinates"),

    /**
     * Gets or sets the numeric Property specifying the altitude of the rectangle.
     * @memberof RectangleGraphics.prototype
     * @type {Property|undefined}
     * @default 0.0
     */
    height: createPropertyDescriptor("height"),

    /**
     * Gets or sets the Property specifying the {@link HeightReference}.
     * @memberof RectangleGraphics.prototype
     * @type {Property|undefined}
     * @default HeightReference.NONE
     */
    heightReference: createPropertyDescriptor("heightReference"),

    /**
     * Gets or sets the numeric Property specifying the altitude of the rectangle extrusion.
     * Setting this property creates volume starting at height and ending at this altitude.
     * @memberof RectangleGraphics.prototype
     * @type {Property|undefined}
     */
    extrudedHeight: createPropertyDescriptor("extrudedHeight"),

    /**
     * Gets or sets the Property specifying the extruded {@link HeightReference}.
     * @memberof RectangleGraphics.prototype
     * @type {Property|undefined}
     * @default HeightReference.NONE
     */
    extrudedHeightReference: createPropertyDescriptor("extrudedHeightReference"),

    /**
     * Gets or sets the numeric property specifying the rotation of the rectangle clockwise from north.
     * @memberof RectangleGraphics.prototype
     * @type {Property|undefined}
     * @default 0
     */
    rotation: createPropertyDescriptor("rotation"),

    /**
     * Gets or sets the numeric property specifying the rotation of the rectangle texture counter-clockwise from north.
     * @memberof RectangleGraphics.prototype
     * @type {Property|undefined}
     * @default 0
     */
    stRotation: createPropertyDescriptor("stRotation"),

    /**
     * Gets or sets the numeric Property specifying the angular distance between points on the rectangle.
     * @memberof RectangleGraphics.prototype
     * @type {Property|undefined}
     * @default {CesiumMath.RADIANS_PER_DEGREE}
     */
    granularity: createPropertyDescriptor("granularity"),

    /**
     * Gets or sets the boolean Property specifying whether the rectangle is filled with the provided material.
     * @memberof RectangleGraphics.prototype
     * @type {Property|undefined}
     * @default true
     */
    fill: createPropertyDescriptor("fill"),

    /**
     * Gets or sets the Property specifying the material used to fill the rectangle.
     * @memberof RectangleGraphics.prototype
     * @type {MaterialProperty}
     * @default Color.WHITE
     */
    material: createMaterialPropertyDescriptor("material"),

    /**
     * Gets or sets the Property specifying whether the rectangle is outlined.
     * @memberof RectangleGraphics.prototype
     * @type {Property|undefined}
     * @default false
     */
    outline: createPropertyDescriptor("outline"),

    /**
     * Gets or sets the Property specifying the {@link Color} of the outline.
     * @memberof RectangleGraphics.prototype
     * @type {Property|undefined}
     * @default Color.BLACK
     */
    outlineColor: createPropertyDescriptor("outlineColor"),

    /**
     * Gets or sets the numeric Property specifying the width of the outline.
     * <p>
     * Note: This property will be ignored on all major browsers on Windows platforms. For details, see (@link https://github.com/CesiumGS/cesium/issues/40}.
     * </p>
     * @memberof RectangleGraphics.prototype
     * @type {Property|undefined}
     * @default 1.0
     */
    outlineWidth: createPropertyDescriptor("outlineWidth"),

    /**
     * Get or sets the enum Property specifying whether the rectangle
     * casts or receives shadows from light sources.
     * @memberof RectangleGraphics.prototype
     * @type {Property|undefined}
     * @default ShadowMode.DISABLED
     */
    shadows: createPropertyDescriptor("shadows"),

    /**
     * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this rectangle will be displayed.
     * @memberof RectangleGraphics.prototype
     * @type {Property|undefined}
     */
    distanceDisplayCondition: createPropertyDescriptor(
      "distanceDisplayCondition"
    ),

    /**
     * Gets or sets the {@link ClassificationType} Property specifying whether this rectangle will classify terrain, 3D Tiles, or both when on the ground.
     * @memberof RectangleGraphics.prototype
     * @type {Property|undefined}
     * @default ClassificationType.BOTH
     */
    classificationType: createPropertyDescriptor("classificationType"),

    /**
     * Gets or sets the zIndex Property specifying the ordering of the rectangle.  Only has an effect if the rectangle is constant and neither height or extrudedHeight are specified.
     * @memberof RectangleGraphics.prototype
     * @type {ConstantProperty|undefined}
     * @default 0
     */
    zIndex: createPropertyDescriptor("zIndex"),
  });

  /**
   * Duplicates this instance.
   *
   * @param {RectangleGraphics} [result] The object onto which to store the result.
   * @returns {RectangleGraphics} The modified result parameter or a new instance if one was not provided.
   */
  RectangleGraphics.prototype.clone = function (result) {
    if (!defined(result)) {
      return new RectangleGraphics(this);
    }
    result.show = this.show;
    result.coordinates = this.coordinates;
    result.height = this.height;
    result.heightReference = this.heightReference;
    result.extrudedHeight = this.extrudedHeight;
    result.extrudedHeightReference = this.extrudedHeightReference;
    result.rotation = this.rotation;
    result.stRotation = this.stRotation;
    result.granularity = this.granularity;
    result.fill = this.fill;
    result.material = this.material;
    result.outline = this.outline;
    result.outlineColor = this.outlineColor;
    result.outlineWidth = this.outlineWidth;
    result.shadows = this.shadows;
    result.distanceDisplayCondition = this.distanceDisplayCondition;
    result.classificationType = this.classificationType;
    result.zIndex = this.zIndex;
    return result;
  };

  /**
   * Assigns each unassigned property on this object to the value
   * of the same property on the provided source object.
   *
   * @param {RectangleGraphics} source The object to be merged into this object.
   */
  RectangleGraphics.prototype.merge = function (source) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(source)) {
      throw new DeveloperError("source is required.");
    }
    //>>includeEnd('debug');

    this.show = defaultValue(this.show, source.show);
    this.coordinates = defaultValue(this.coordinates, source.coordinates);
    this.height = defaultValue(this.height, source.height);
    this.heightReference = defaultValue(
      this.heightReference,
      source.heightReference
    );
    this.extrudedHeight = defaultValue(
      this.extrudedHeight,
      source.extrudedHeight
    );
    this.extrudedHeightReference = defaultValue(
      this.extrudedHeightReference,
      source.extrudedHeightReference
    );
    this.rotation = defaultValue(this.rotation, source.rotation);
    this.stRotation = defaultValue(this.stRotation, source.stRotation);
    this.granularity = defaultValue(this.granularity, source.granularity);
    this.fill = defaultValue(this.fill, source.fill);
    this.material = defaultValue(this.material, source.material);
    this.outline = defaultValue(this.outline, source.outline);
    this.outlineColor = defaultValue(this.outlineColor, source.outlineColor);
    this.outlineWidth = defaultValue(this.outlineWidth, source.outlineWidth);
    this.shadows = defaultValue(this.shadows, source.shadows);
    this.distanceDisplayCondition = defaultValue(
      this.distanceDisplayCondition,
      source.distanceDisplayCondition
    );
    this.classificationType = defaultValue(
      this.classificationType,
      source.classificationType
    );
    this.zIndex = defaultValue(this.zIndex, source.zIndex);
  };

  /**
   * @typedef {Object} WallGraphics.ConstructorOptions
   *
   * Initialization options for the WallGraphics constructor
   *
   * @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the wall.
   * @property {Property | Array<Cartesian3>} [positions] A Property specifying the array of {@link Cartesian3} positions which define the top of the wall.
   * @property {Property | Array<number>} [minimumHeights] A Property specifying an array of heights to be used for the bottom of the wall instead of the globe surface.
   * @property {Property | Array<number>} [maximumHeights] A Property specifying an array of heights to be used for the top of the wall instead of the height of each position.
   * @property {Property | number} [granularity=Cesium.Math.RADIANS_PER_DEGREE] A numeric Property specifying the angular distance between each latitude and longitude point.
   * @property {Property | boolean} [fill=true] A boolean Property specifying whether the wall is filled with the provided material.
   * @property {MaterialProperty | Color} [material=Color.WHITE] A Property specifying the material used to fill the wall.
   * @property {Property | boolean} [outline=false] A boolean Property specifying whether the wall is outlined.
   * @property {Property | Color} [outlineColor=Color.BLACK] A Property specifying the {@link Color} of the outline.
   * @property {Property | number} [outlineWidth=1.0] A numeric Property specifying the width of the outline.
   * @property {Property | ShadowMode} [shadows=ShadowMode.DISABLED] An enum Property specifying whether the wall casts or receives shadows from light sources.
   * @property {Property | DistanceDisplayCondition} [distanceDisplayCondition] A Property specifying at what distance from the camera that this wall will be displayed.
   */

  /**
   * Describes a two dimensional wall defined as a line strip and optional maximum and minimum heights.
   * The wall conforms to the curvature of the globe and can be placed along the surface or at altitude.
   *
   * @alias WallGraphics
   * @constructor
   *
   * @param {WallGraphics.ConstructorOptions} [options] Object describing initialization options
   *
   * @see Entity
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Wall.html|Cesium Sandcastle Wall Demo}
   */
  function WallGraphics(options) {
    this._definitionChanged = new Event();
    this._show = undefined;
    this._showSubscription = undefined;
    this._positions = undefined;
    this._positionsSubscription = undefined;
    this._minimumHeights = undefined;
    this._minimumHeightsSubscription = undefined;
    this._maximumHeights = undefined;
    this._maximumHeightsSubscription = undefined;
    this._granularity = undefined;
    this._granularitySubscription = undefined;
    this._fill = undefined;
    this._fillSubscription = undefined;
    this._material = undefined;
    this._materialSubscription = undefined;
    this._outline = undefined;
    this._outlineSubscription = undefined;
    this._outlineColor = undefined;
    this._outlineColorSubscription = undefined;
    this._outlineWidth = undefined;
    this._outlineWidthSubscription = undefined;
    this._shadows = undefined;
    this._shadowsSubscription = undefined;
    this._distanceDisplayCondition = undefined;
    this._distanceDisplayConditionSubscription = undefined;

    this.merge(defaultValue(options, defaultValue.EMPTY_OBJECT));
  }

  Object.defineProperties(WallGraphics.prototype, {
    /**
     * Gets the event that is raised whenever a property or sub-property is changed or modified.
     * @memberof WallGraphics.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },

    /**
     * Gets or sets the boolean Property specifying the visibility of the wall.
     * @memberof WallGraphics.prototype
     * @type {Property|undefined}
     * @default true
     */
    show: createPropertyDescriptor("show"),

    /**
     * Gets or sets the Property specifying the array of {@link Cartesian3} positions which define the top of the wall.
     * @memberof WallGraphics.prototype
     * @type {Property|undefined}
     */
    positions: createPropertyDescriptor("positions"),

    /**
     * Gets or sets the Property specifying an array of heights to be used for the bottom of the wall instead of the surface of the globe.
     * If defined, the array must be the same length as {@link Wall#positions}.
     * @memberof WallGraphics.prototype
     * @type {Property|undefined}
     */
    minimumHeights: createPropertyDescriptor("minimumHeights"),

    /**
     * Gets or sets the Property specifying an array of heights to be used for the top of the wall instead of the height of each position.
     * If defined, the array must be the same length as {@link Wall#positions}.
     * @memberof WallGraphics.prototype
     * @type {Property|undefined}
     */
    maximumHeights: createPropertyDescriptor("maximumHeights"),

    /**
     * Gets or sets the numeric Property specifying the angular distance between points on the wall.
     * @memberof WallGraphics.prototype
     * @type {Property|undefined}
     * @default {CesiumMath.RADIANS_PER_DEGREE}
     */
    granularity: createPropertyDescriptor("granularity"),

    /**
     * Gets or sets the boolean Property specifying whether the wall is filled with the provided material.
     * @memberof WallGraphics.prototype
     * @type {Property|undefined}
     * @default true
     */
    fill: createPropertyDescriptor("fill"),

    /**
     * Gets or sets the Property specifying the material used to fill the wall.
     * @memberof WallGraphics.prototype
     * @type {MaterialProperty}
     * @default Color.WHITE
     */
    material: createMaterialPropertyDescriptor("material"),

    /**
     * Gets or sets the Property specifying whether the wall is outlined.
     * @memberof WallGraphics.prototype
     * @type {Property|undefined}
     * @default false
     */
    outline: createPropertyDescriptor("outline"),

    /**
     * Gets or sets the Property specifying the {@link Color} of the outline.
     * @memberof WallGraphics.prototype
     * @type {Property|undefined}
     * @default Color.BLACK
     */
    outlineColor: createPropertyDescriptor("outlineColor"),

    /**
     * Gets or sets the numeric Property specifying the width of the outline.
     * <p>
     * Note: This property will be ignored on all major browsers on Windows platforms. For details, see (@link https://github.com/CesiumGS/cesium/issues/40}.
     * </p>
     * @memberof WallGraphics.prototype
     * @type {Property|undefined}
     * @default 1.0
     */
    outlineWidth: createPropertyDescriptor("outlineWidth"),

    /**
     * Get or sets the enum Property specifying whether the wall
     * casts or receives shadows from light sources.
     * @memberof WallGraphics.prototype
     * @type {Property|undefined}
     * @default ShadowMode.DISABLED
     */
    shadows: createPropertyDescriptor("shadows"),

    /**
     * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this wall will be displayed.
     * @memberof WallGraphics.prototype
     * @type {Property|undefined}
     */
    distanceDisplayCondition: createPropertyDescriptor(
      "distanceDisplayCondition"
    ),
  });

  /**
   * Duplicates this instance.
   *
   * @param {WallGraphics} [result] The object onto which to store the result.
   * @returns {WallGraphics} The modified result parameter or a new instance if one was not provided.
   */
  WallGraphics.prototype.clone = function (result) {
    if (!defined(result)) {
      return new WallGraphics(this);
    }
    result.show = this.show;
    result.positions = this.positions;
    result.minimumHeights = this.minimumHeights;
    result.maximumHeights = this.maximumHeights;
    result.granularity = this.granularity;
    result.fill = this.fill;
    result.material = this.material;
    result.outline = this.outline;
    result.outlineColor = this.outlineColor;
    result.outlineWidth = this.outlineWidth;
    result.shadows = this.shadows;
    result.distanceDisplayCondition = this.distanceDisplayCondition;
    return result;
  };

  /**
   * Assigns each unassigned property on this object to the value
   * of the same property on the provided source object.
   *
   * @param {WallGraphics} source The object to be merged into this object.
   */
  WallGraphics.prototype.merge = function (source) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(source)) {
      throw new DeveloperError("source is required.");
    }
    //>>includeEnd('debug');

    this.show = defaultValue(this.show, source.show);
    this.positions = defaultValue(this.positions, source.positions);
    this.minimumHeights = defaultValue(
      this.minimumHeights,
      source.minimumHeights
    );
    this.maximumHeights = defaultValue(
      this.maximumHeights,
      source.maximumHeights
    );
    this.granularity = defaultValue(this.granularity, source.granularity);
    this.fill = defaultValue(this.fill, source.fill);
    this.material = defaultValue(this.material, source.material);
    this.outline = defaultValue(this.outline, source.outline);
    this.outlineColor = defaultValue(this.outlineColor, source.outlineColor);
    this.outlineWidth = defaultValue(this.outlineWidth, source.outlineWidth);
    this.shadows = defaultValue(this.shadows, source.shadows);
    this.distanceDisplayCondition = defaultValue(
      this.distanceDisplayCondition,
      source.distanceDisplayCondition
    );
  };

  const cartoScratch$1 = new Cartographic();

  function createConstantPositionProperty(value) {
    return new ConstantPositionProperty(value);
  }

  function createPositionPropertyDescriptor(name) {
    return createPropertyDescriptor(
      name,
      undefined,
      createConstantPositionProperty
    );
  }

  function createPropertyTypeDescriptor(name, Type) {
    return createPropertyDescriptor(name, undefined, function (value) {
      if (value instanceof Type) {
        return value;
      }
      return new Type(value);
    });
  }

  /**
   * @typedef {Object} Entity.ConstructorOptions
   *
   * Initialization options for the Entity constructor
   *
   * @property {String} [id] A unique identifier for this object. If none is provided, a GUID is generated.
   * @property {String} [name] A human readable name to display to users. It does not have to be unique.
   * @property {TimeIntervalCollection} [availability] The availability, if any, associated with this object.
   * @property {Boolean} [show] A boolean value indicating if the entity and its children are displayed.
   * @property {Property | string} [description] A string Property specifying an HTML description for this entity.
   * @property {PositionProperty | Cartesian3} [position] A Property specifying the entity position.
   * @property {Property} [orientation] A Property specifying the entity orientation.
   * @property {Property} [viewFrom] A suggested initial offset for viewing this object.
   * @property {Entity} [parent] A parent entity to associate with this entity.
   * @property {BillboardGraphics | BillboardGraphics.ConstructorOptions} [billboard] A billboard to associate with this entity.
   * @property {BoxGraphics | BoxGraphics.ConstructorOptions} [box] A box to associate with this entity.
   * @property {CorridorGraphics | CorridorGraphics.ConstructorOptions} [corridor] A corridor to associate with this entity.
   * @property {CylinderGraphics | CylinderGraphics.ConstructorOptions} [cylinder] A cylinder to associate with this entity.
   * @property {EllipseGraphics | EllipseGraphics.ConstructorOptions} [ellipse] A ellipse to associate with this entity.
   * @property {EllipsoidGraphics | EllipsoidGraphics.ConstructorOptions} [ellipsoid] A ellipsoid to associate with this entity.
   * @property {LabelGraphics | LabelGraphics.ConstructorOptions} [label] A options.label to associate with this entity.
   * @property {ModelGraphics | ModelGraphics.ConstructorOptions} [model] A model to associate with this entity.
   * @property {Cesium3DTilesetGraphics | Cesium3DTilesetGraphics.ConstructorOptions} [tileset] A 3D Tiles tileset to associate with this entity.
   * @property {PathGraphics | PathGraphics.ConstructorOptions} [path] A path to associate with this entity.
   * @property {PlaneGraphics | PlaneGraphics.ConstructorOptions} [plane] A plane to associate with this entity.
   * @property {PointGraphics | PointGraphics.ConstructorOptions} [point] A point to associate with this entity.
   * @property {PolygonGraphics | PolygonGraphics.ConstructorOptions} [polygon] A polygon to associate with this entity.
   * @property {PolylineGraphics | PolylineGraphics.ConstructorOptions} [polyline] A polyline to associate with this entity.
   * @property {PropertyBag | Object.<string,*>} [properties] Arbitrary properties to associate with this entity.
   * @property {PolylineVolumeGraphics | PolylineVolumeGraphics.ConstructorOptions} [polylineVolume] A polylineVolume to associate with this entity.
   * @property {RectangleGraphics | RectangleGraphics.ConstructorOptions} [rectangle] A rectangle to associate with this entity.
   * @property {WallGraphics | WallGraphics.ConstructorOptions} [wall] A wall to associate with this entity.
   */

  /**
   * Entity instances aggregate multiple forms of visualization into a single high-level object.
   * They can be created manually and added to {@link Viewer#entities} or be produced by
   * data sources, such as {@link CzmlDataSource} and {@link GeoJsonDataSource}.
   * @alias Entity
   * @constructor
   *
   * @param {Entity.ConstructorOptions} [options] Object describing initialization options
   *
   * @see {@link https://cesium.com/learn/cesiumjs-learn/cesiumjs-creating-entities/|Creating Entities}
   */
  function Entity(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    let id = options.id;
    if (!defined(id)) {
      id = createGuid();
    }

    this._availability = undefined;
    this._id = id;
    this._definitionChanged = new Event();
    this._name = options.name;
    this._show = defaultValue(options.show, true);
    this._parent = undefined;
    this._propertyNames = [
      "billboard",
      "box",
      "corridor",
      "cylinder",
      "description",
      "ellipse", //
      "ellipsoid",
      "label",
      "model",
      "tileset",
      "orientation",
      "path",
      "plane",
      "point",
      "polygon", //
      "polyline",
      "polylineVolume",
      "position",
      "properties",
      "rectangle",
      "viewFrom",
      "wall",
    ];

    this._billboard = undefined;
    this._billboardSubscription = undefined;
    this._box = undefined;
    this._boxSubscription = undefined;
    this._corridor = undefined;
    this._corridorSubscription = undefined;
    this._cylinder = undefined;
    this._cylinderSubscription = undefined;
    this._description = undefined;
    this._descriptionSubscription = undefined;
    this._ellipse = undefined;
    this._ellipseSubscription = undefined;
    this._ellipsoid = undefined;
    this._ellipsoidSubscription = undefined;
    this._label = undefined;
    this._labelSubscription = undefined;
    this._model = undefined;
    this._modelSubscription = undefined;
    this._tileset = undefined;
    this._tilesetSubscription = undefined;
    this._orientation = undefined;
    this._orientationSubscription = undefined;
    this._path = undefined;
    this._pathSubscription = undefined;
    this._plane = undefined;
    this._planeSubscription = undefined;
    this._point = undefined;
    this._pointSubscription = undefined;
    this._polygon = undefined;
    this._polygonSubscription = undefined;
    this._polyline = undefined;
    this._polylineSubscription = undefined;
    this._polylineVolume = undefined;
    this._polylineVolumeSubscription = undefined;
    this._position = undefined;
    this._positionSubscription = undefined;
    this._properties = undefined;
    this._propertiesSubscription = undefined;
    this._rectangle = undefined;
    this._rectangleSubscription = undefined;
    this._viewFrom = undefined;
    this._viewFromSubscription = undefined;
    this._wall = undefined;
    this._wallSubscription = undefined;
    this._children = [];

    /**
     * Gets or sets the entity collection that this entity belongs to.
     * @type {EntityCollection}
     */
    this.entityCollection = undefined;

    this.parent = options.parent;
    this.merge(options);
  }

  function updateShow(entity, children, isShowing) {
    const length = children.length;
    for (let i = 0; i < length; i++) {
      const child = children[i];
      const childShow = child._show;
      const oldValue = !isShowing && childShow;
      const newValue = isShowing && childShow;
      if (oldValue !== newValue) {
        updateShow(child, child._children, isShowing);
      }
    }
    entity._definitionChanged.raiseEvent(
      entity,
      "isShowing",
      isShowing,
      !isShowing
    );
  }

  Object.defineProperties(Entity.prototype, {
    /**
     * The availability, if any, associated with this object.
     * If availability is undefined, it is assumed that this object's
     * other properties will return valid data for any provided time.
     * If availability exists, the objects other properties will only
     * provide valid data if queried within the given interval.
     * @memberof Entity.prototype
     * @type {TimeIntervalCollection|undefined}
     */
    availability: createRawPropertyDescriptor("availability"),
    /**
     * Gets the unique ID associated with this object.
     * @memberof Entity.prototype
     * @type {String}
     */
    id: {
      get: function () {
        return this._id;
      },
    },
    /**
     * Gets the event that is raised whenever a property or sub-property is changed or modified.
     * @memberof Entity.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },
    /**
     * Gets or sets the name of the object.  The name is intended for end-user
     * consumption and does not need to be unique.
     * @memberof Entity.prototype
     * @type {String|undefined}
     */
    name: createRawPropertyDescriptor("name"),
    /**
     * Gets or sets whether this entity should be displayed. When set to true,
     * the entity is only displayed if the parent entity's show property is also true.
     * @memberof Entity.prototype
     * @type {Boolean}
     */
    show: {
      get: function () {
        return this._show;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        if (value === this._show) {
          return;
        }

        const wasShowing = this.isShowing;
        this._show = value;
        const isShowing = this.isShowing;

        if (wasShowing !== isShowing) {
          updateShow(this, this._children, isShowing);
        }

        this._definitionChanged.raiseEvent(this, "show", value, !value);
      },
    },
    /**
     * Gets whether this entity is being displayed, taking into account
     * the visibility of any ancestor entities.
     * @memberof Entity.prototype
     * @type {Boolean}
     */
    isShowing: {
      get: function () {
        return (
          this._show &&
          (!defined(this.entityCollection) || this.entityCollection.show) &&
          (!defined(this._parent) || this._parent.isShowing)
        );
      },
    },
    /**
     * Gets or sets the parent object.
     * @memberof Entity.prototype
     * @type {Entity|undefined}
     */
    parent: {
      get: function () {
        return this._parent;
      },
      set: function (value) {
        const oldValue = this._parent;

        if (oldValue === value) {
          return;
        }

        const wasShowing = this.isShowing;
        if (defined(oldValue)) {
          const index = oldValue._children.indexOf(this);
          oldValue._children.splice(index, 1);
        }

        this._parent = value;
        if (defined(value)) {
          value._children.push(this);
        }

        const isShowing = this.isShowing;

        if (wasShowing !== isShowing) {
          updateShow(this, this._children, isShowing);
        }

        this._definitionChanged.raiseEvent(this, "parent", value, oldValue);
      },
    },
    /**
     * Gets the names of all properties registered on this instance.
     * @memberof Entity.prototype
     * @type {string[]}
     */
    propertyNames: {
      get: function () {
        return this._propertyNames;
      },
    },
    /**
     * Gets or sets the billboard.
     * @memberof Entity.prototype
     * @type {BillboardGraphics|undefined}
     */
    billboard: createPropertyTypeDescriptor("billboard", BillboardGraphics),
    /**
     * Gets or sets the box.
     * @memberof Entity.prototype
     * @type {BoxGraphics|undefined}
     */
    box: createPropertyTypeDescriptor("box", BoxGraphics),
    /**
     * Gets or sets the corridor.
     * @memberof Entity.prototype
     * @type {CorridorGraphics|undefined}
     */
    corridor: createPropertyTypeDescriptor("corridor", CorridorGraphics),
    /**
     * Gets or sets the cylinder.
     * @memberof Entity.prototype
     * @type {CylinderGraphics|undefined}
     */
    cylinder: createPropertyTypeDescriptor("cylinder", CylinderGraphics),
    /**
     * Gets or sets the description.
     * @memberof Entity.prototype
     * @type {Property|undefined}
     */
    description: createPropertyDescriptor("description"),
    /**
     * Gets or sets the ellipse.
     * @memberof Entity.prototype
     * @type {EllipseGraphics|undefined}
     */
    ellipse: createPropertyTypeDescriptor("ellipse", EllipseGraphics),
    /**
     * Gets or sets the ellipsoid.
     * @memberof Entity.prototype
     * @type {EllipsoidGraphics|undefined}
     */
    ellipsoid: createPropertyTypeDescriptor("ellipsoid", EllipsoidGraphics),
    /**
     * Gets or sets the label.
     * @memberof Entity.prototype
     * @type {LabelGraphics|undefined}
     */
    label: createPropertyTypeDescriptor("label", LabelGraphics),
    /**
     * Gets or sets the model.
     * @memberof Entity.prototype
     * @type {ModelGraphics|undefined}
     */
    model: createPropertyTypeDescriptor("model", ModelGraphics),
    /**
     * Gets or sets the tileset.
     * @memberof Entity.prototype
     * @type {Cesium3DTilesetGraphics|undefined}
     */
    tileset: createPropertyTypeDescriptor("tileset", Cesium3DTilesetGraphics),
    /**
     * Gets or sets the orientation.
     * @memberof Entity.prototype
     * @type {Property|undefined}
     */
    orientation: createPropertyDescriptor("orientation"),
    /**
     * Gets or sets the path.
     * @memberof Entity.prototype
     * @type {PathGraphics|undefined}
     */
    path: createPropertyTypeDescriptor("path", PathGraphics),
    /**
     * Gets or sets the plane.
     * @memberof Entity.prototype
     * @type {PlaneGraphics|undefined}
     */
    plane: createPropertyTypeDescriptor("plane", PlaneGraphics),
    /**
     * Gets or sets the point graphic.
     * @memberof Entity.prototype
     * @type {PointGraphics|undefined}
     */
    point: createPropertyTypeDescriptor("point", PointGraphics),
    /**
     * Gets or sets the polygon.
     * @memberof Entity.prototype
     * @type {PolygonGraphics|undefined}
     */
    polygon: createPropertyTypeDescriptor("polygon", PolygonGraphics),
    /**
     * Gets or sets the polyline.
     * @memberof Entity.prototype
     * @type {PolylineGraphics|undefined}
     */
    polyline: createPropertyTypeDescriptor("polyline", PolylineGraphics),
    /**
     * Gets or sets the polyline volume.
     * @memberof Entity.prototype
     * @type {PolylineVolumeGraphics|undefined}
     */
    polylineVolume: createPropertyTypeDescriptor(
      "polylineVolume",
      PolylineVolumeGraphics
    ),
    /**
     * Gets or sets the bag of arbitrary properties associated with this entity.
     * @memberof Entity.prototype
     * @type {PropertyBag|undefined}
     */
    properties: createPropertyTypeDescriptor("properties", PropertyBag),
    /**
     * Gets or sets the position.
     * @memberof Entity.prototype
     * @type {PositionProperty|undefined}
     */
    position: createPositionPropertyDescriptor("position"),
    /**
     * Gets or sets the rectangle.
     * @memberof Entity.prototype
     * @type {RectangleGraphics|undefined}
     */
    rectangle: createPropertyTypeDescriptor("rectangle", RectangleGraphics),
    /**
     * Gets or sets the suggested initial offset when tracking this object.
     * The offset is typically defined in the east-north-up reference frame,
     * but may be another frame depending on the object's velocity.
     * @memberof Entity.prototype
     * @type {Property|undefined}
     */
    viewFrom: createPropertyDescriptor("viewFrom"),
    /**
     * Gets or sets the wall.
     * @memberof Entity.prototype
     * @type {WallGraphics|undefined}
     */
    wall: createPropertyTypeDescriptor("wall", WallGraphics),
  });

  /**
   * Given a time, returns true if this object should have data during that time.
   *
   * @param {JulianDate} time The time to check availability for.
   * @returns {Boolean} true if the object should have data during the provided time, false otherwise.
   */
  Entity.prototype.isAvailable = function (time) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(time)) {
      throw new DeveloperError("time is required.");
    }
    //>>includeEnd('debug');

    const availability = this._availability;
    return !defined(availability) || availability.contains(time);
  };

  /**
   * Adds a property to this object.  Once a property is added, it can be
   * observed with {@link Entity#definitionChanged} and composited
   * with {@link CompositeEntityCollection}
   *
   * @param {String} propertyName The name of the property to add.
   *
   * @exception {DeveloperError} "propertyName" is a reserved property name.
   * @exception {DeveloperError} "propertyName" is already a registered property.
   */
  Entity.prototype.addProperty = function (propertyName) {
    const propertyNames = this._propertyNames;

    //>>includeStart('debug', pragmas.debug);
    if (!defined(propertyName)) {
      throw new DeveloperError("propertyName is required.");
    }
    if (propertyNames.indexOf(propertyName) !== -1) {
      throw new DeveloperError(
        `${propertyName} is already a registered property.`
      );
    }
    if (propertyName in this) {
      throw new DeveloperError(`${propertyName} is a reserved property name.`);
    }
    //>>includeEnd('debug');

    propertyNames.push(propertyName);
    Object.defineProperty(
      this,
      propertyName,
      createRawPropertyDescriptor(propertyName, true)
    );
  };

  /**
   * Removed a property previously added with addProperty.
   *
   * @param {String} propertyName The name of the property to remove.
   *
   * @exception {DeveloperError} "propertyName" is a reserved property name.
   * @exception {DeveloperError} "propertyName" is not a registered property.
   */
  Entity.prototype.removeProperty = function (propertyName) {
    const propertyNames = this._propertyNames;
    const index = propertyNames.indexOf(propertyName);

    //>>includeStart('debug', pragmas.debug);
    if (!defined(propertyName)) {
      throw new DeveloperError("propertyName is required.");
    }
    if (index === -1) {
      throw new DeveloperError(`${propertyName} is not a registered property.`);
    }
    //>>includeEnd('debug');

    this._propertyNames.splice(index, 1);
    delete this[propertyName];
  };

  /**
   * Assigns each unassigned property on this object to the value
   * of the same property on the provided source object.
   *
   * @param {Entity} source The object to be merged into this object.
   */
  Entity.prototype.merge = function (source) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(source)) {
      throw new DeveloperError("source is required.");
    }
    //>>includeEnd('debug');

    //Name, show, and availability are not Property objects and are currently handled differently.
    //source.show is intentionally ignored because this.show always has a value.
    this.name = defaultValue(this.name, source.name);
    this.availability = defaultValue(this.availability, source.availability);

    const propertyNames = this._propertyNames;
    const sourcePropertyNames = defined(source._propertyNames)
      ? source._propertyNames
      : Object.keys(source);
    const propertyNamesLength = sourcePropertyNames.length;
    for (let i = 0; i < propertyNamesLength; i++) {
      const name = sourcePropertyNames[i];

      //While source is required by the API to be an Entity, we internally call this method from the
      //constructor with an options object to configure initial custom properties.
      //So we need to ignore reserved-non-property.
      if (name === "parent" || name === "name" || name === "availability") {
        continue;
      }

      const targetProperty = this[name];
      const sourceProperty = source[name];

      //Custom properties that are registered on the source entity must also
      //get registered on this entity.
      if (!defined(targetProperty) && propertyNames.indexOf(name) === -1) {
        this.addProperty(name);
      }

      if (defined(sourceProperty)) {
        if (defined(targetProperty)) {
          if (defined(targetProperty.merge)) {
            targetProperty.merge(sourceProperty);
          }
        } else if (
          defined(sourceProperty.merge) &&
          defined(sourceProperty.clone)
        ) {
          this[name] = sourceProperty.clone();
        } else {
          this[name] = sourceProperty;
        }
      }
    }
  };

  const matrix3Scratch = new Matrix3();
  const positionScratch$8 = new Cartesian3();
  const orientationScratch = new Quaternion();

  /**
   * Computes the model matrix for the entity's transform at specified time. Returns undefined if orientation or position
   * are undefined.
   *
   * @param {JulianDate} time The time to retrieve model matrix for.
   * @param {Matrix4} [result] The object onto which to store the result.
   *
   * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided. Result is undefined if position or orientation are undefined.
   */
  Entity.prototype.computeModelMatrix = function (time, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("time", time);
    //>>includeEnd('debug');
    const position = Property.getValueOrUndefined(
      this._position,
      time,
      positionScratch$8
    );
    if (!defined(position)) {
      return undefined;
    }

    const orientation = Property.getValueOrUndefined(
      this._orientation,
      time,
      orientationScratch
    );
    if (!defined(orientation)) {
      result = Transforms.eastNorthUpToFixedFrame(position, undefined, result);
    } else {
      result = Matrix4.fromRotationTranslation(
        Matrix3.fromQuaternion(orientation, matrix3Scratch),
        position,
        result
      );
    }
    return result;
  };

  /**
   * @private
   */
  Entity.prototype.computeModelMatrixForHeightReference = function (
    time,
    heightReferenceProperty,
    heightOffset,
    ellipsoid,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("time", time);
    //>>includeEnd('debug');
    const heightReference = Property.getValueOrDefault(
      heightReferenceProperty,
      time,
      HeightReference$1.NONE
    );
    let position = Property.getValueOrUndefined(
      this._position,
      time,
      positionScratch$8
    );
    if (
      heightReference === HeightReference$1.NONE ||
      !defined(position) ||
      Cartesian3.equalsEpsilon(position, Cartesian3.ZERO, CesiumMath.EPSILON8)
    ) {
      return this.computeModelMatrix(time, result);
    }

    const carto = ellipsoid.cartesianToCartographic(position, cartoScratch$1);
    if (heightReference === HeightReference$1.CLAMP_TO_GROUND) {
      carto.height = heightOffset;
    } else {
      carto.height += heightOffset;
    }
    position = ellipsoid.cartographicToCartesian(carto, position);

    const orientation = Property.getValueOrUndefined(
      this._orientation,
      time,
      orientationScratch
    );
    if (!defined(orientation)) {
      result = Transforms.eastNorthUpToFixedFrame(position, undefined, result);
    } else {
      result = Matrix4.fromRotationTranslation(
        Matrix3.fromQuaternion(orientation, matrix3Scratch),
        position,
        result
      );
    }
    return result;
  };

  /**
   * Checks if the given Scene supports materials besides Color on Entities draped on terrain or 3D Tiles.
   * If this feature is not supported, Entities with non-color materials but no `height` will
   * instead be rendered as if height is 0.
   *
   * @param {Scene} scene The current scene.
   * @returns {Boolean} Whether or not the current scene supports materials for entities on terrain.
   */
  Entity.supportsMaterialsforEntitiesOnTerrain = function (scene) {
    return GroundPrimitive.supportsMaterials(scene);
  };

  /**
   * Checks if the given Scene supports polylines clamped to terrain or 3D Tiles.
   * If this feature is not supported, Entities with PolylineGraphics will be rendered with vertices at
   * the provided heights and using the `arcType` parameter instead of clamped to the ground.
   *
   * @param {Scene} scene The current scene.
   * @returns {Boolean} Whether or not the current scene supports polylines on terrain or 3D TIles.
   */
  Entity.supportsPolylinesOnTerrain = function (scene) {
    return GroundPolylinePrimitive.isSupported(scene);
  };

  const defaultMaterial$2 = new ColorMaterialProperty(Color.WHITE);
  const defaultShow$1 = new ConstantProperty(true);
  const defaultFill$1 = new ConstantProperty(true);
  const defaultOutline = new ConstantProperty(false);
  const defaultOutlineColor$3 = new ConstantProperty(Color.BLACK);
  const defaultShadows$2 = new ConstantProperty(ShadowMode$1.DISABLED);
  const defaultDistanceDisplayCondition$7 = new ConstantProperty(
    new DistanceDisplayCondition()
  );
  const defaultClassificationType$1 = new ConstantProperty(ClassificationType$1.BOTH);

  /**
   * An abstract class for updating geometry entities.
   * @alias GeometryUpdater
   * @constructor
   *
   * @param {Object} options An object with the following properties:
   * @param {Entity} options.entity The entity containing the geometry to be visualized.
   * @param {Scene} options.scene The scene where visualization is taking place.
   * @param {Object} options.geometryOptions Options for the geometry
   * @param {String} options.geometryPropertyName The geometry property name
   * @param {String[]} options.observedPropertyNames The entity properties this geometry cares about
   */
  function GeometryUpdater(options) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("options.entity", options.entity);
    Check.defined("options.scene", options.scene);
    Check.defined("options.geometryOptions", options.geometryOptions);
    Check.defined("options.geometryPropertyName", options.geometryPropertyName);
    Check.defined("options.observedPropertyNames", options.observedPropertyNames);
    //>>includeEnd('debug');

    const entity = options.entity;
    const geometryPropertyName = options.geometryPropertyName;

    this._entity = entity;
    this._scene = options.scene;
    this._fillEnabled = false;
    this._isClosed = false;
    this._onTerrain = false;
    this._dynamic = false;
    this._outlineEnabled = false;
    this._geometryChanged = new Event();
    this._showProperty = undefined;
    this._materialProperty = undefined;
    this._showOutlineProperty = undefined;
    this._outlineColorProperty = undefined;
    this._outlineWidth = 1.0;
    this._shadowsProperty = undefined;
    this._distanceDisplayConditionProperty = undefined;
    this._classificationTypeProperty = undefined;
    this._options = options.geometryOptions;
    this._geometryPropertyName = geometryPropertyName;
    this._id = `${geometryPropertyName}-${entity.id}`;
    this._observedPropertyNames = options.observedPropertyNames;
    this._supportsMaterialsforEntitiesOnTerrain = Entity.supportsMaterialsforEntitiesOnTerrain(
      options.scene
    );
  }

  Object.defineProperties(GeometryUpdater.prototype, {
    /**
     * Gets the unique ID associated with this updater
     * @memberof GeometryUpdater.prototype
     * @type {String}
     * @readonly
     */
    id: {
      get: function () {
        return this._id;
      },
    },
    /**
     * Gets the entity associated with this geometry.
     * @memberof GeometryUpdater.prototype
     *
     * @type {Entity}
     * @readonly
     */
    entity: {
      get: function () {
        return this._entity;
      },
    },
    /**
     * Gets a value indicating if the geometry has a fill component.
     * @memberof GeometryUpdater.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    fillEnabled: {
      get: function () {
        return this._fillEnabled;
      },
    },
    /**
     * Gets a value indicating if fill visibility varies with simulation time.
     * @memberof GeometryUpdater.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    hasConstantFill: {
      get: function () {
        return (
          !this._fillEnabled ||
          (!defined(this._entity.availability) &&
            Property.isConstant(this._showProperty) &&
            Property.isConstant(this._fillProperty))
        );
      },
    },
    /**
     * Gets the material property used to fill the geometry.
     * @memberof GeometryUpdater.prototype
     *
     * @type {MaterialProperty}
     * @readonly
     */
    fillMaterialProperty: {
      get: function () {
        return this._materialProperty;
      },
    },
    /**
     * Gets a value indicating if the geometry has an outline component.
     * @memberof GeometryUpdater.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    outlineEnabled: {
      get: function () {
        return this._outlineEnabled;
      },
    },
    /**
     * Gets a value indicating if the geometry has an outline component.
     * @memberof GeometryUpdater.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    hasConstantOutline: {
      get: function () {
        return (
          !this._outlineEnabled ||
          (!defined(this._entity.availability) &&
            Property.isConstant(this._showProperty) &&
            Property.isConstant(this._showOutlineProperty))
        );
      },
    },
    /**
     * Gets the {@link Color} property for the geometry outline.
     * @memberof GeometryUpdater.prototype
     *
     * @type {Property}
     * @readonly
     */
    outlineColorProperty: {
      get: function () {
        return this._outlineColorProperty;
      },
    },
    /**
     * Gets the constant with of the geometry outline, in pixels.
     * This value is only valid if isDynamic is false.
     * @memberof GeometryUpdater.prototype
     *
     * @type {Number}
     * @readonly
     */
    outlineWidth: {
      get: function () {
        return this._outlineWidth;
      },
    },
    /**
     * Gets the property specifying whether the geometry
     * casts or receives shadows from light sources.
     * @memberof GeometryUpdater.prototype
     *
     * @type {Property}
     * @readonly
     */
    shadowsProperty: {
      get: function () {
        return this._shadowsProperty;
      },
    },
    /**
     * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this geometry will be displayed.
     * @memberof GeometryUpdater.prototype
     *
     * @type {Property}
     * @readonly
     */
    distanceDisplayConditionProperty: {
      get: function () {
        return this._distanceDisplayConditionProperty;
      },
    },
    /**
     * Gets or sets the {@link ClassificationType} Property specifying if this geometry will classify terrain, 3D Tiles, or both when on the ground.
     * @memberof GeometryUpdater.prototype
     *
     * @type {Property}
     * @readonly
     */
    classificationTypeProperty: {
      get: function () {
        return this._classificationTypeProperty;
      },
    },
    /**
     * Gets a value indicating if the geometry is time-varying.
     * If true, all visualization is delegated to a DynamicGeometryUpdater
     * returned by GeometryUpdater#createDynamicUpdater.
     * @memberof GeometryUpdater.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    isDynamic: {
      get: function () {
        return this._dynamic;
      },
    },
    /**
     * Gets a value indicating if the geometry is closed.
     * This property is only valid for static geometry.
     * @memberof GeometryUpdater.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    isClosed: {
      get: function () {
        return this._isClosed;
      },
    },
    /**
     * Gets a value indicating if the geometry should be drawn on terrain.
     * @memberof EllipseGeometryUpdater.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    onTerrain: {
      get: function () {
        return this._onTerrain;
      },
    },
    /**
     * Gets an event that is raised whenever the public properties
     * of this updater change.
     * @memberof GeometryUpdater.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    geometryChanged: {
      get: function () {
        return this._geometryChanged;
      },
    },
  });

  /**
   * Checks if the geometry is outlined at the provided time.
   *
   * @param {JulianDate} time The time for which to retrieve visibility.
   * @returns {Boolean} true if geometry is outlined at the provided time, false otherwise.
   */
  GeometryUpdater.prototype.isOutlineVisible = function (time) {
    const entity = this._entity;
    const visible =
      this._outlineEnabled &&
      entity.isAvailable(time) &&
      this._showProperty.getValue(time) &&
      this._showOutlineProperty.getValue(time);
    return defaultValue(visible, false);
  };

  /**
   * Checks if the geometry is filled at the provided time.
   *
   * @param {JulianDate} time The time for which to retrieve visibility.
   * @returns {Boolean} true if geometry is filled at the provided time, false otherwise.
   */
  GeometryUpdater.prototype.isFilled = function (time) {
    const entity = this._entity;
    const visible =
      this._fillEnabled &&
      entity.isAvailable(time) &&
      this._showProperty.getValue(time) &&
      this._fillProperty.getValue(time);
    return defaultValue(visible, false);
  };

  /**
   * Creates the geometry instance which represents the fill of the geometry.
   *
   * @function
   * @param {JulianDate} time The time to use when retrieving initial attribute values.
   * @returns {GeometryInstance} The geometry instance representing the filled portion of the geometry.
   *
   * @exception {DeveloperError} This instance does not represent a filled geometry.
   */
  GeometryUpdater.prototype.createFillGeometryInstance =
    DeveloperError.throwInstantiationError;

  /**
   * Creates the geometry instance which represents the outline of the geometry.
   *
   * @function
   * @param {JulianDate} time The time to use when retrieving initial attribute values.
   * @returns {GeometryInstance} The geometry instance representing the outline portion of the geometry.
   *
   * @exception {DeveloperError} This instance does not represent an outlined geometry.
   */
  GeometryUpdater.prototype.createOutlineGeometryInstance =
    DeveloperError.throwInstantiationError;

  /**
   * Returns true if this object was destroyed; otherwise, false.
   *
   * @returns {Boolean} True if this object was destroyed; otherwise, false.
   */
  GeometryUpdater.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys and resources used by the object.  Once an object is destroyed, it should not be used.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   */
  GeometryUpdater.prototype.destroy = function () {
    destroyObject(this);
  };
  /**
   * @param {Entity} entity
   * @param {Object} geometry
   * @private
   */
  GeometryUpdater.prototype._isHidden = function (entity, geometry) {
    const show = geometry.show;
    return (
      defined(show) && show.isConstant && !show.getValue(Iso8601.MINIMUM_VALUE)
    );
  };

  /**
   * @param {Entity} entity
   * @param {Object} geometry
   * @private
   */
  GeometryUpdater.prototype._isOnTerrain = function (entity, geometry) {
    return false;
  };

  /**
   * @param {GeometryOptions} options
   * @private
   */
  GeometryUpdater.prototype._getIsClosed = function (options) {
    return true;
  };

  /**
   * @param {Entity} entity
   * @param {Object} geometry
   * @private
   */
  GeometryUpdater.prototype._isDynamic = DeveloperError.throwInstantiationError;

  /**
   * @param {Entity} entity
   * @param {Object} geometry
   * @private
   */
  GeometryUpdater.prototype._setStaticOptions =
    DeveloperError.throwInstantiationError;

  /**
   * @param {Entity} entity
   * @param {String} propertyName
   * @param {*} newValue
   * @param {*} oldValue
   * @private
   */
  GeometryUpdater.prototype._onEntityPropertyChanged = function (
    entity,
    propertyName,
    newValue,
    oldValue
  ) {
    if (this._observedPropertyNames.indexOf(propertyName) === -1) {
      return;
    }

    const geometry = this._entity[this._geometryPropertyName];

    if (!defined(geometry)) {
      if (this._fillEnabled || this._outlineEnabled) {
        this._fillEnabled = false;
        this._outlineEnabled = false;
        this._geometryChanged.raiseEvent(this);
      }
      return;
    }

    const fillProperty = geometry.fill;
    const fillEnabled =
      defined(fillProperty) && fillProperty.isConstant
        ? fillProperty.getValue(Iso8601.MINIMUM_VALUE)
        : true;

    const outlineProperty = geometry.outline;
    let outlineEnabled = defined(outlineProperty);
    if (outlineEnabled && outlineProperty.isConstant) {
      outlineEnabled = outlineProperty.getValue(Iso8601.MINIMUM_VALUE);
    }

    if (!fillEnabled && !outlineEnabled) {
      if (this._fillEnabled || this._outlineEnabled) {
        this._fillEnabled = false;
        this._outlineEnabled = false;
        this._geometryChanged.raiseEvent(this);
      }
      return;
    }

    const show = geometry.show;
    if (this._isHidden(entity, geometry)) {
      if (this._fillEnabled || this._outlineEnabled) {
        this._fillEnabled = false;
        this._outlineEnabled = false;
        this._geometryChanged.raiseEvent(this);
      }
      return;
    }

    this._materialProperty = defaultValue(geometry.material, defaultMaterial$2);
    this._fillProperty = defaultValue(fillProperty, defaultFill$1);
    this._showProperty = defaultValue(show, defaultShow$1);
    this._showOutlineProperty = defaultValue(geometry.outline, defaultOutline);
    this._outlineColorProperty = outlineEnabled
      ? defaultValue(geometry.outlineColor, defaultOutlineColor$3)
      : undefined;
    this._shadowsProperty = defaultValue(geometry.shadows, defaultShadows$2);
    this._distanceDisplayConditionProperty = defaultValue(
      geometry.distanceDisplayCondition,
      defaultDistanceDisplayCondition$7
    );
    this._classificationTypeProperty = defaultValue(
      geometry.classificationType,
      defaultClassificationType$1
    );

    this._fillEnabled = fillEnabled;

    const onTerrain =
      this._isOnTerrain(entity, geometry) &&
      (this._supportsMaterialsforEntitiesOnTerrain ||
        this._materialProperty instanceof ColorMaterialProperty);

    if (outlineEnabled && onTerrain) {
      oneTimeWarning(oneTimeWarning.geometryOutlines);
      outlineEnabled = false;
    }

    this._onTerrain = onTerrain;
    this._outlineEnabled = outlineEnabled;

    if (this._isDynamic(entity, geometry)) {
      if (!this._dynamic) {
        this._dynamic = true;
        this._geometryChanged.raiseEvent(this);
      }
    } else {
      this._setStaticOptions(entity, geometry);
      this._isClosed = this._getIsClosed(this._options);
      const outlineWidth = geometry.outlineWidth;
      this._outlineWidth = defined(outlineWidth)
        ? outlineWidth.getValue(Iso8601.MINIMUM_VALUE)
        : 1.0;
      this._dynamic = false;
      this._geometryChanged.raiseEvent(this);
    }
  };

  /**
   * Creates the dynamic updater to be used when GeometryUpdater#isDynamic is true.
   *
   * @param {PrimitiveCollection} primitives The primitive collection to use.
   * @param {PrimitiveCollection} [groundPrimitives] The primitive collection to use for ground primitives.
   *
   * @returns {DynamicGeometryUpdater} The dynamic updater used to update the geometry each frame.
   *
   * @exception {DeveloperError} This instance does not represent dynamic geometry.
   * @private
   */
  GeometryUpdater.prototype.createDynamicUpdater = function (
    primitives,
    groundPrimitives
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("primitives", primitives);
    Check.defined("groundPrimitives", groundPrimitives);

    if (!this._dynamic) {
      throw new DeveloperError(
        "This instance does not represent dynamic geometry."
      );
    }
    //>>includeEnd('debug');

    return new this.constructor.DynamicGeometryUpdater(
      this,
      primitives,
      groundPrimitives
    );
  };

  /**
   * A {@link Property} whose value is lazily evaluated by a callback function.
   *
   * @alias CallbackProperty
   * @constructor
   *
   * @param {CallbackProperty.Callback} callback The function to be called when the property is evaluated.
   * @param {Boolean} isConstant <code>true</code> when the callback function returns the same value every time, <code>false</code> if the value will change.
   */
  function CallbackProperty(callback, isConstant) {
    this._callback = undefined;
    this._isConstant = undefined;
    this._definitionChanged = new Event();
    this.setCallback(callback, isConstant);
  }

  Object.defineProperties(CallbackProperty.prototype, {
    /**
     * Gets a value indicating if this property is constant.
     * @memberof CallbackProperty.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    isConstant: {
      get: function () {
        return this._isConstant;
      },
    },
    /**
     * Gets the event that is raised whenever the definition of this property changes.
     * The definition is changed whenever setCallback is called.
     * @memberof CallbackProperty.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },
  });

  /**
   * Gets the value of the property.
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {Object} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Object} The modified result parameter or a new instance if the result parameter was not supplied or is unsupported.
   */
  CallbackProperty.prototype.getValue = function (time, result) {
    return this._callback(time, result);
  };

  /**
   * Sets the callback to be used.
   *
   * @param {CallbackProperty.Callback} callback The function to be called when the property is evaluated.
   * @param {Boolean} isConstant <code>true</code> when the callback function returns the same value every time, <code>false</code> if the value will change.
   */
  CallbackProperty.prototype.setCallback = function (callback, isConstant) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(callback)) {
      throw new DeveloperError("callback is required.");
    }
    if (!defined(isConstant)) {
      throw new DeveloperError("isConstant is required.");
    }
    //>>includeEnd('debug');

    const changed =
      this._callback !== callback || this._isConstant !== isConstant;

    this._callback = callback;
    this._isConstant = isConstant;

    if (changed) {
      this._definitionChanged.raiseEvent(this);
    }
  };

  /**
   * Compares this property to the provided property and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Property} [other] The other property.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  CallbackProperty.prototype.equals = function (other) {
    return (
      this === other ||
      (other instanceof CallbackProperty &&
        this._callback === other._callback &&
        this._isConstant === other._isConstant)
    );
  };

  const scratchPosition$a = new Cartesian3();
  const scratchCarto$1 = new Cartographic();

  /**
   * @private
   */
  function TerrainOffsetProperty(
    scene,
    positionProperty,
    heightReferenceProperty,
    extrudedHeightReferenceProperty
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("scene", scene);
    Check.defined("positionProperty", positionProperty);
    //>>includeEnd('debug');

    this._scene = scene;
    this._heightReference = heightReferenceProperty;
    this._extrudedHeightReference = extrudedHeightReferenceProperty;
    this._positionProperty = positionProperty;

    this._position = new Cartesian3();
    this._cartographicPosition = new Cartographic();
    this._normal = new Cartesian3();

    this._definitionChanged = new Event();
    this._terrainHeight = 0;
    this._removeCallbackFunc = undefined;
    this._removeEventListener = undefined;
    this._removeModeListener = undefined;

    const that = this;
    if (defined(scene.globe)) {
      this._removeEventListener = scene.terrainProviderChanged.addEventListener(
        function () {
          that._updateClamping();
        }
      );
      this._removeModeListener = scene.morphComplete.addEventListener(
        function () {
          that._updateClamping();
        }
      );
    }

    if (positionProperty.isConstant) {
      const position = positionProperty.getValue(
        Iso8601.MINIMUM_VALUE,
        scratchPosition$a
      );
      if (
        !defined(position) ||
        Cartesian3.equals(position, Cartesian3.ZERO) ||
        !defined(scene.globe)
      ) {
        return;
      }
      this._position = Cartesian3.clone(position, this._position);

      this._updateClamping();

      this._normal = scene.globe.ellipsoid.geodeticSurfaceNormal(
        position,
        this._normal
      );
    }
  }

  Object.defineProperties(TerrainOffsetProperty.prototype, {
    /**
     * Gets a value indicating if this property is constant.
     * @memberof TerrainOffsetProperty.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    isConstant: {
      get: function () {
        return false;
      },
    },
    /**
     * Gets the event that is raised whenever the definition of this property changes.
     * @memberof TerrainOffsetProperty.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },
  });

  /**
   * @private
   */
  TerrainOffsetProperty.prototype._updateClamping = function () {
    if (defined(this._removeCallbackFunc)) {
      this._removeCallbackFunc();
    }

    const scene = this._scene;
    const globe = scene.globe;
    const position = this._position;

    if (!defined(globe) || Cartesian3.equals(position, Cartesian3.ZERO)) {
      this._terrainHeight = 0;
      return;
    }
    const ellipsoid = globe.ellipsoid;
    const surface = globe._surface;

    const that = this;
    const cartographicPosition = ellipsoid.cartesianToCartographic(
      position,
      this._cartographicPosition
    );
    const height = globe.getHeight(cartographicPosition);
    if (defined(height)) {
      this._terrainHeight = height;
    } else {
      this._terrainHeight = 0;
    }

    function updateFunction(clampedPosition) {
      if (scene.mode === SceneMode$1.SCENE3D) {
        const carto = ellipsoid.cartesianToCartographic(
          clampedPosition,
          scratchCarto$1
        );
        that._terrainHeight = carto.height;
      } else {
        that._terrainHeight = clampedPosition.x;
      }
      that.definitionChanged.raiseEvent();
    }
    this._removeCallbackFunc = surface.updateHeight(
      cartographicPosition,
      updateFunction
    );
  };

  /**
   * Gets the height relative to the terrain based on the positions.
   *
   * @returns {Cartesian3} The offset
   */
  TerrainOffsetProperty.prototype.getValue = function (time, result) {
    const heightReference = Property.getValueOrDefault(
      this._heightReference,
      time,
      HeightReference$1.NONE
    );
    const extrudedHeightReference = Property.getValueOrDefault(
      this._extrudedHeightReference,
      time,
      HeightReference$1.NONE
    );

    if (
      heightReference === HeightReference$1.NONE &&
      extrudedHeightReference !== HeightReference$1.RELATIVE_TO_GROUND
    ) {
      this._position = Cartesian3.clone(Cartesian3.ZERO, this._position);
      return Cartesian3.clone(Cartesian3.ZERO, result);
    }

    if (this._positionProperty.isConstant) {
      return Cartesian3.multiplyByScalar(
        this._normal,
        this._terrainHeight,
        result
      );
    }

    const scene = this._scene;
    const position = this._positionProperty.getValue(time, scratchPosition$a);
    if (
      !defined(position) ||
      Cartesian3.equals(position, Cartesian3.ZERO) ||
      !defined(scene.globe)
    ) {
      return Cartesian3.clone(Cartesian3.ZERO, result);
    }

    if (
      Cartesian3.equalsEpsilon(this._position, position, CesiumMath.EPSILON10)
    ) {
      return Cartesian3.multiplyByScalar(
        this._normal,
        this._terrainHeight,
        result
      );
    }

    this._position = Cartesian3.clone(position, this._position);

    this._updateClamping();

    const normal = scene.globe.ellipsoid.geodeticSurfaceNormal(
      position,
      this._normal
    );
    return Cartesian3.multiplyByScalar(normal, this._terrainHeight, result);
  };

  TerrainOffsetProperty.prototype.isDestroyed = function () {
    return false;
  };

  TerrainOffsetProperty.prototype.destroy = function () {
    if (defined(this._removeEventListener)) {
      this._removeEventListener();
    }
    if (defined(this._removeModeListener)) {
      this._removeModeListener();
    }
    if (defined(this._removeCallbackFunc)) {
      this._removeCallbackFunc();
    }
    return destroyObject(this);
  };

  function heightReferenceOnEntityPropertyChanged(
    entity,
    propertyName,
    newValue,
    oldValue
  ) {
    GeometryUpdater.prototype._onEntityPropertyChanged.call(
      this,
      entity,
      propertyName,
      newValue,
      oldValue
    );
    if (this._observedPropertyNames.indexOf(propertyName) === -1) {
      return;
    }

    const geometry = this._entity[this._geometryPropertyName];
    if (!defined(geometry)) {
      return;
    }

    if (defined(this._terrainOffsetProperty)) {
      this._terrainOffsetProperty.destroy();
      this._terrainOffsetProperty = undefined;
    }

    const heightReferenceProperty = geometry.heightReference;

    if (defined(heightReferenceProperty)) {
      const centerPosition = new CallbackProperty(
        this._computeCenter.bind(this),
        !this._dynamic
      );
      this._terrainOffsetProperty = new TerrainOffsetProperty(
        this._scene,
        centerPosition,
        heightReferenceProperty
      );
    }
  }

  const defaultOffset$a = Cartesian3.ZERO;

  const offsetScratch$9 = new Cartesian3();
  const positionScratch$7 = new Cartesian3();
  const scratchColor$o = new Color();

  function BoxGeometryOptions(entity) {
    this.id = entity;
    this.vertexFormat = undefined;
    this.dimensions = undefined;
    this.offsetAttribute = undefined;
  }

  /**
   * A {@link GeometryUpdater} for boxes.
   * Clients do not normally create this class directly, but instead rely on {@link DataSourceDisplay}.
   * @alias BoxGeometryUpdater
   * @constructor
   *
   * @param {Entity} entity The entity containing the geometry to be visualized.
   * @param {Scene} scene The scene where visualization is taking place.
   */
  function BoxGeometryUpdater(entity, scene) {
    GeometryUpdater.call(this, {
      entity: entity,
      scene: scene,
      geometryOptions: new BoxGeometryOptions(entity),
      geometryPropertyName: "box",
      observedPropertyNames: ["availability", "position", "orientation", "box"],
    });

    this._onEntityPropertyChanged(entity, "box", entity.box, undefined);
  }

  if (defined(Object.create)) {
    BoxGeometryUpdater.prototype = Object.create(GeometryUpdater.prototype);
    BoxGeometryUpdater.prototype.constructor = BoxGeometryUpdater;
  }

  Object.defineProperties(BoxGeometryUpdater.prototype, {
    /**
     * Gets the terrain offset property
     * @type {TerrainOffsetProperty}
     * @memberof BoxGeometryUpdater.prototype
     * @readonly
     * @private
     */
    terrainOffsetProperty: {
      get: function () {
        return this._terrainOffsetProperty;
      },
    },
  });

  /**
   * Creates the geometry instance which represents the fill of the geometry.
   *
   * @param {JulianDate} time The time to use when retrieving initial attribute values.
   * @returns {GeometryInstance} The geometry instance representing the filled portion of the geometry.
   *
   * @exception {DeveloperError} This instance does not represent a filled geometry.
   */
  BoxGeometryUpdater.prototype.createFillGeometryInstance = function (time) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("time", time);

    if (!this._fillEnabled) {
      throw new DeveloperError(
        "This instance does not represent a filled geometry."
      );
    }
    //>>includeEnd('debug');

    const entity = this._entity;
    const isAvailable = entity.isAvailable(time);

    const show = new ShowGeometryInstanceAttribute(
      isAvailable &&
        entity.isShowing &&
        this._showProperty.getValue(time) &&
        this._fillProperty.getValue(time)
    );
    const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
      time
    );
    const distanceDisplayConditionAttribute = DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
      distanceDisplayCondition
    );

    const attributes = {
      show: show,
      distanceDisplayCondition: distanceDisplayConditionAttribute,
      color: undefined,
      offset: undefined,
    };
    if (this._materialProperty instanceof ColorMaterialProperty) {
      let currentColor;
      if (
        defined(this._materialProperty.color) &&
        (this._materialProperty.color.isConstant || isAvailable)
      ) {
        currentColor = this._materialProperty.color.getValue(time, scratchColor$o);
      }
      if (!defined(currentColor)) {
        currentColor = Color.WHITE;
      }
      attributes.color = ColorGeometryInstanceAttribute.fromColor(currentColor);
    }
    if (defined(this._options.offsetAttribute)) {
      attributes.offset = OffsetGeometryInstanceAttribute.fromCartesian3(
        Property.getValueOrDefault(
          this._terrainOffsetProperty,
          time,
          defaultOffset$a,
          offsetScratch$9
        )
      );
    }

    return new GeometryInstance({
      id: entity,
      geometry: BoxGeometry.fromDimensions(this._options),
      modelMatrix: entity.computeModelMatrixForHeightReference(
        time,
        entity.box.heightReference,
        this._options.dimensions.z * 0.5,
        this._scene.mapProjection.ellipsoid
      ),
      attributes: attributes,
    });
  };

  /**
   * Creates the geometry instance which represents the outline of the geometry.
   *
   * @param {JulianDate} time The time to use when retrieving initial attribute values.
   * @returns {GeometryInstance} The geometry instance representing the outline portion of the geometry.
   *
   * @exception {DeveloperError} This instance does not represent an outlined geometry.
   */
  BoxGeometryUpdater.prototype.createOutlineGeometryInstance = function (time) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("time", time);

    if (!this._outlineEnabled) {
      throw new DeveloperError(
        "This instance does not represent an outlined geometry."
      );
    }
    //>>includeEnd('debug');

    const entity = this._entity;
    const isAvailable = entity.isAvailable(time);
    const outlineColor = Property.getValueOrDefault(
      this._outlineColorProperty,
      time,
      Color.BLACK,
      scratchColor$o
    );
    const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
      time
    );

    const attributes = {
      show: new ShowGeometryInstanceAttribute(
        isAvailable &&
          entity.isShowing &&
          this._showProperty.getValue(time) &&
          this._showOutlineProperty.getValue(time)
      ),
      color: ColorGeometryInstanceAttribute.fromColor(outlineColor),
      distanceDisplayCondition: DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
        distanceDisplayCondition
      ),
      offset: undefined,
    };
    if (defined(this._options.offsetAttribute)) {
      attributes.offset = OffsetGeometryInstanceAttribute.fromCartesian3(
        Property.getValueOrDefault(
          this._terrainOffsetProperty,
          time,
          defaultOffset$a,
          offsetScratch$9
        )
      );
    }

    return new GeometryInstance({
      id: entity,
      geometry: BoxOutlineGeometry.fromDimensions(this._options),
      modelMatrix: entity.computeModelMatrixForHeightReference(
        time,
        entity.box.heightReference,
        this._options.dimensions.z * 0.5,
        this._scene.mapProjection.ellipsoid
      ),
      attributes: attributes,
    });
  };

  BoxGeometryUpdater.prototype._computeCenter = function (time, result) {
    return Property.getValueOrUndefined(this._entity.position, time, result);
  };

  BoxGeometryUpdater.prototype._isHidden = function (entity, box) {
    return (
      !defined(box.dimensions) ||
      !defined(entity.position) ||
      GeometryUpdater.prototype._isHidden.call(this, entity, box)
    );
  };

  BoxGeometryUpdater.prototype._isDynamic = function (entity, box) {
    return (
      !entity.position.isConstant ||
      !Property.isConstant(entity.orientation) ||
      !box.dimensions.isConstant ||
      !Property.isConstant(box.outlineWidth)
    );
  };

  BoxGeometryUpdater.prototype._setStaticOptions = function (entity, box) {
    const heightReference = Property.getValueOrDefault(
      box.heightReference,
      Iso8601.MINIMUM_VALUE,
      HeightReference$1.NONE
    );

    const options = this._options;
    options.vertexFormat =
      this._materialProperty instanceof ColorMaterialProperty
        ? PerInstanceColorAppearance.VERTEX_FORMAT
        : MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat;
    options.dimensions = box.dimensions.getValue(
      Iso8601.MINIMUM_VALUE,
      options.dimensions
    );
    options.offsetAttribute =
      heightReference !== HeightReference$1.NONE
        ? GeometryOffsetAttribute$1.ALL
        : undefined;
  };

  BoxGeometryUpdater.prototype._onEntityPropertyChanged = heightReferenceOnEntityPropertyChanged;

  BoxGeometryUpdater.DynamicGeometryUpdater = DynamicBoxGeometryUpdater;

  /**
   * @private
   */
  function DynamicBoxGeometryUpdater(
    geometryUpdater,
    primitives,
    groundPrimitives
  ) {
    DynamicGeometryUpdater$1.call(
      this,
      geometryUpdater,
      primitives,
      groundPrimitives
    );
  }

  if (defined(Object.create)) {
    DynamicBoxGeometryUpdater.prototype = Object.create(
      DynamicGeometryUpdater$1.prototype
    );
    DynamicBoxGeometryUpdater.prototype.constructor = DynamicBoxGeometryUpdater;
  }

  DynamicBoxGeometryUpdater.prototype._isHidden = function (entity, box, time) {
    const position = Property.getValueOrUndefined(
      entity.position,
      time,
      positionScratch$7
    );
    const dimensions = this._options.dimensions;
    return (
      !defined(position) ||
      !defined(dimensions) ||
      DynamicGeometryUpdater$1.prototype._isHidden.call(this, entity, box, time)
    );
  };

  DynamicBoxGeometryUpdater.prototype._setOptions = function (entity, box, time) {
    const heightReference = Property.getValueOrDefault(
      box.heightReference,
      time,
      HeightReference$1.NONE
    );
    const options = this._options;
    options.dimensions = Property.getValueOrUndefined(
      box.dimensions,
      time,
      options.dimensions
    );
    options.offsetAttribute =
      heightReference !== HeightReference$1.NONE
        ? GeometryOffsetAttribute$1.ALL
        : undefined;
  };

  /**
   * Represents a command to the renderer for GPU Compute (using old-school GPGPU).
   *
   * @private
   * @constructor
   */
  function ComputeCommand(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    /**
     * The vertex array. If none is provided, a viewport quad will be used.
     *
     * @type {VertexArray}
     * @default undefined
     */
    this.vertexArray = options.vertexArray;

    /**
     * The fragment shader source. The default vertex shader is ViewportQuadVS.
     *
     * @type {ShaderSource}
     * @default undefined
     */
    this.fragmentShaderSource = options.fragmentShaderSource;

    /**
     * The shader program to apply.
     *
     * @type {ShaderProgram}
     * @default undefined
     */
    this.shaderProgram = options.shaderProgram;

    /**
     * An object with functions whose names match the uniforms in the shader program
     * and return values to set those uniforms.
     *
     * @type {Object}
     * @default undefined
     */
    this.uniformMap = options.uniformMap;

    /**
     * Texture to use for offscreen rendering.
     *
     * @type {Texture}
     * @default undefined
     */
    this.outputTexture = options.outputTexture;

    /**
     * Function that is called immediately before the ComputeCommand is executed. Used to
     * update any renderer resources. Takes the ComputeCommand as its single argument.
     *
     * @type {Function}
     * @default undefined
     */
    this.preExecute = options.preExecute;

    /**
     * Function that is called after the ComputeCommand is executed. Takes the output
     * texture as its single argument.
     *
     * @type {Function}
     * @default undefined
     */
    this.postExecute = options.postExecute;

    /**
     * Function that is called when the command is canceled
     *
     * @type {Function}
     * @default undefined
     */
    this.canceled = options.canceled;

    /**
     * Whether the renderer resources will persist beyond this call. If not, they
     * will be destroyed after completion.
     *
     * @type {Boolean}
     * @default false
     */
    this.persists = defaultValue(options.persists, false);

    /**
     * The pass when to render. Always compute pass.
     *
     * @type {Pass}
     * @default Pass.COMPUTE;
     */
    this.pass = Pass$1.COMPUTE;

    /**
     * The object who created this command.  This is useful for debugging command
     * execution; it allows us to see who created a command when we only have a
     * reference to the command, and can be used to selectively execute commands
     * with {@link Scene#debugCommandFilter}.
     *
     * @type {Object}
     * @default undefined
     *
     * @see Scene#debugCommandFilter
     */
    this.owner = options.owner;
  }

  /**
   * Executes the compute command.
   *
   * @param {ComputeEngine} computeEngine The context that processes the compute command.
   */
  ComputeCommand.prototype.execute = function (computeEngine) {
    computeEngine.execute(this);
  };

  //This file is automatically rebuilt by the Cesium build process.
  var OctahedralProjectionAtlasFS = "varying vec2 v_textureCoordinates;\n\
uniform float originalSize;\n\
uniform sampler2D texture0;\n\
uniform sampler2D texture1;\n\
uniform sampler2D texture2;\n\
uniform sampler2D texture3;\n\
uniform sampler2D texture4;\n\
uniform sampler2D texture5;\n\
const float yMipLevel1 = 1.0 - (1.0 / pow(2.0, 1.0));\n\
const float yMipLevel2 = 1.0 - (1.0 / pow(2.0, 2.0));\n\
const float yMipLevel3 = 1.0 - (1.0 / pow(2.0, 3.0));\n\
const float yMipLevel4 = 1.0 - (1.0 / pow(2.0, 4.0));\n\
void main()\n\
{\n\
vec2 uv = v_textureCoordinates;\n\
vec2 textureSize = vec2(originalSize * 1.5 + 2.0, originalSize);\n\
vec2 pixel = 1.0 / textureSize;\n\
float mipLevel = 0.0;\n\
if (uv.x - pixel.x > (textureSize.y / textureSize.x))\n\
{\n\
mipLevel = 1.0;\n\
if (uv.y - pixel.y > yMipLevel1)\n\
{\n\
mipLevel = 2.0;\n\
if (uv.y - pixel.y * 3.0 > yMipLevel2)\n\
{\n\
mipLevel = 3.0;\n\
if (uv.y - pixel.y * 5.0 > yMipLevel3)\n\
{\n\
mipLevel = 4.0;\n\
if (uv.y - pixel.y * 7.0 > yMipLevel4)\n\
{\n\
mipLevel = 5.0;\n\
}\n\
}\n\
}\n\
}\n\
}\n\
if (mipLevel > 0.0)\n\
{\n\
float scale = pow(2.0, mipLevel);\n\
uv.y -= (pixel.y * (mipLevel - 1.0) * 2.0);\n\
uv.x *= ((textureSize.x - 2.0) / textureSize.y);\n\
uv.x -= 1.0 + pixel.x;\n\
uv.y -= (1.0 - (1.0 / pow(2.0, mipLevel - 1.0)));\n\
uv *= scale;\n\
}\n\
else\n\
{\n\
uv.x *= (textureSize.x / textureSize.y);\n\
}\n\
if(mipLevel == 0.0)\n\
{\n\
gl_FragColor = texture2D(texture0, uv);\n\
}\n\
else if(mipLevel == 1.0)\n\
{\n\
gl_FragColor = texture2D(texture1, uv);\n\
}\n\
else if(mipLevel == 2.0)\n\
{\n\
gl_FragColor = texture2D(texture2, uv);\n\
}\n\
else if(mipLevel == 3.0)\n\
{\n\
gl_FragColor = texture2D(texture3, uv);\n\
}\n\
else if(mipLevel == 4.0)\n\
{\n\
gl_FragColor = texture2D(texture4, uv);\n\
}\n\
else if(mipLevel == 5.0)\n\
{\n\
gl_FragColor = texture2D(texture5, uv);\n\
}\n\
else\n\
{\n\
gl_FragColor = vec4(0.0);\n\
}\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var OctahedralProjectionFS = "varying vec3 v_cubeMapCoordinates;\n\
uniform samplerCube cubeMap;\n\
void main()\n\
{\n\
vec4 rgba = textureCube(cubeMap, v_cubeMapCoordinates);\n\
#ifdef RGBA_NORMALIZED\n\
gl_FragColor = vec4(rgba.rgb, 1.0);\n\
#else\n\
float m = rgba.a * 16.0;\n\
vec3 r = rgba.rgb * m;\n\
gl_FragColor = vec4(r * r, 1.0);\n\
#endif\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var OctahedralProjectionVS = "attribute vec4 position;\n\
attribute vec3 cubeMapCoordinates;\n\
varying vec3 v_cubeMapCoordinates;\n\
void main()\n\
{\n\
gl_Position = position;\n\
v_cubeMapCoordinates = cubeMapCoordinates;\n\
}\n\
";

  /**
   * Packs all mip levels of a cube map into a 2D texture atlas.
   *
   * Octahedral projection is a way of putting the cube maps onto a 2D texture
   * with minimal distortion and easy look up.
   * See Chapter 16 of WebGL Insights "HDR Image-Based Lighting on the Web" by Jeff Russell
   * and "Octahedron Environment Maps" for reference.
   *
   * @private
   */
  function OctahedralProjectedCubeMap(url) {
    this._url = url;

    this._cubeMapBuffers = undefined;
    this._cubeMaps = undefined;
    this._texture = undefined;
    this._mipTextures = undefined;
    this._va = undefined;
    this._sp = undefined;

    this._maximumMipmapLevel = undefined;

    this._loading = false;
    this._ready = false;
    this._readyPromise = defer();
  }

  Object.defineProperties(OctahedralProjectedCubeMap.prototype, {
    /**
     * The url to the KTX2 file containing the specular environment map and convoluted mipmaps.
     * @memberof OctahedralProjectedCubeMap.prototype
     * @type {String}
     * @readonly
     */
    url: {
      get: function () {
        return this._url;
      },
    },
    /**
     * A texture containing all the packed convolutions.
     * @memberof OctahedralProjectedCubeMap.prototype
     * @type {Texture}
     * @readonly
     */
    texture: {
      get: function () {
        return this._texture;
      },
    },
    /**
     * The maximum number of mip levels.
     * @memberOf OctahedralProjectedCubeMap.prototype
     * @type {Number}
     * @readonly
     */
    maximumMipmapLevel: {
      get: function () {
        return this._maximumMipmapLevel;
      },
    },
    /**
     * Determines if the texture atlas is complete and ready to use.
     * @memberof OctahedralProjectedCubeMap.prototype
     * @type {Boolean}
     * @readonly
     */
    ready: {
      get: function () {
        return this._ready;
      },
    },
    /**
     * Gets a promise that resolves when the texture atlas is ready to use.
     * @memberof OctahedralProjectedCubeMap.prototype
     * @type {Promise<void>}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._readyPromise.promise;
      },
    },
  });

  OctahedralProjectedCubeMap.isSupported = function (context) {
    return (
      (context.colorBufferHalfFloat && context.halfFloatingPointTexture) ||
      (context.floatingPointTexture && context.colorBufferFloat)
    );
  };

  // These vertices are based on figure 1 from "Octahedron Environment Maps".
  const v1 = new Cartesian3(1.0, 0.0, 0.0);
  const v2 = new Cartesian3(0.0, 0.0, 1.0);
  const v3 = new Cartesian3(-1.0, 0.0, 0.0);
  const v4 = new Cartesian3(0.0, 0.0, -1.0);
  const v5 = new Cartesian3(0.0, 1.0, 0.0);
  const v6 = new Cartesian3(0.0, -1.0, 0.0);

  // top left, left, top, center, right, top right, bottom, bottom left, bottom right
  const cubeMapCoordinates = [v5, v3, v2, v6, v1, v5, v4, v5, v5];
  const length$1 = cubeMapCoordinates.length;
  const flatCubeMapCoordinates = new Float32Array(length$1 * 3);

  let offset = 0;
  for (let i = 0; i < length$1; ++i, offset += 3) {
    Cartesian3.pack(cubeMapCoordinates[i], flatCubeMapCoordinates, offset);
  }

  const flatPositions = new Float32Array([
    -1.0,
    1.0, // top left
    -1.0,
    0.0, // left
    0.0,
    1.0, // top
    0.0,
    0.0, // center
    1.0,
    0.0, // right
    1.0,
    1.0, // top right
    0.0,
    -1.0, // bottom
    -1.0,
    -1.0, // bottom left
    1.0,
    -1.0, // bottom right
  ]);
  const indices = new Uint16Array([
    0,
    1,
    2, // top left, left, top,
    2,
    3,
    1, // top, center, left,
    7,
    6,
    1, // bottom left, bottom, left,
    3,
    6,
    1, // center, bottom, left,
    2,
    5,
    4, // top, top right, right,
    3,
    4,
    2, // center, right, top,
    4,
    8,
    6, // right, bottom right, bottom,
    3,
    4,
    6, //center, right, bottom
  ]);

  function createVertexArray$5(context) {
    const positionBuffer = Buffer$1.createVertexBuffer({
      context: context,
      typedArray: flatPositions,
      usage: BufferUsage$1.STATIC_DRAW,
    });
    const cubeMapCoordinatesBuffer = Buffer$1.createVertexBuffer({
      context: context,
      typedArray: flatCubeMapCoordinates,
      usage: BufferUsage$1.STATIC_DRAW,
    });
    const indexBuffer = Buffer$1.createIndexBuffer({
      context: context,
      typedArray: indices,
      usage: BufferUsage$1.STATIC_DRAW,
      indexDatatype: IndexDatatype$1.UNSIGNED_SHORT,
    });

    const attributes = [
      {
        index: 0,
        vertexBuffer: positionBuffer,
        componentsPerAttribute: 2,
        componentDatatype: ComponentDatatype$1.FLOAT,
      },
      {
        index: 1,
        vertexBuffer: cubeMapCoordinatesBuffer,
        componentsPerAttribute: 3,
        componentDatatype: ComponentDatatype$1.FLOAT,
      },
    ];
    return new VertexArray({
      context: context,
      attributes: attributes,
      indexBuffer: indexBuffer,
    });
  }

  function createUniformTexture(texture) {
    return function () {
      return texture;
    };
  }

  function cleanupResources(map) {
    map._va = map._va && map._va.destroy();
    map._sp = map._sp && map._sp.destroy();

    let i;
    let length;

    const cubeMaps = map._cubeMaps;
    if (defined(cubeMaps)) {
      length = cubeMaps.length;
      for (i = 0; i < length; ++i) {
        cubeMaps[i].destroy();
      }
    }
    const mipTextures = map._mipTextures;
    if (defined(mipTextures)) {
      length = mipTextures.length;
      for (i = 0; i < length; ++i) {
        mipTextures[i].destroy();
      }
    }

    map._va = undefined;
    map._sp = undefined;
    map._cubeMaps = undefined;
    map._cubeMapBuffers = undefined;
    map._mipTextures = undefined;
  }

  /**
   * Creates compute commands to generate octahedral projections of each cube map
   * and then renders them to an atlas.
   * <p>
   * Only needs to be called twice. The first call queues the compute commands to generate the atlas.
   * The second call cleans up unused resources. Every call afterwards is a no-op.
   * </p>
   *
   * @param {FrameState} frameState The frame state.
   *
   * @private
   */
  OctahedralProjectedCubeMap.prototype.update = function (frameState) {
    const context = frameState.context;

    if (!OctahedralProjectedCubeMap.isSupported(context)) {
      return;
    }

    if (defined(this._texture) && defined(this._va)) {
      cleanupResources(this);
    }
    if (defined(this._texture)) {
      return;
    }

    if (!defined(this._texture) && !this._loading) {
      const cachedTexture = context.textureCache.getTexture(this._url);
      if (defined(cachedTexture)) {
        cleanupResources(this);
        this._texture = cachedTexture;
        this._maximumMipmapLevel = this._texture.maximumMipmapLevel;
        this._ready = true;
        this._readyPromise.resolve();
        return;
      }
    }

    const cubeMapBuffers = this._cubeMapBuffers;
    if (!defined(cubeMapBuffers) && !this._loading) {
      const that = this;
      loadKTX2(this._url)
        .then(function (buffers) {
          that._cubeMapBuffers = buffers;
          that._loading = false;
        })
        .catch(function (e) {
          that._readyPromise.reject(e);
        });
      this._loading = true;
    }
    if (!defined(this._cubeMapBuffers)) {
      return;
    }

    const defines = [];
    // Datatype is defined if it is a normalized type (i.e. ..._UNORM, ..._SFLOAT)
    let pixelDatatype = cubeMapBuffers[0].positiveX.pixelDatatype;
    if (!defined(pixelDatatype)) {
      pixelDatatype = context.halfFloatingPointTexture
        ? PixelDatatype$1.HALF_FLOAT
        : PixelDatatype$1.FLOAT;
    } else {
      defines.push("RGBA_NORMALIZED");
    }
    const pixelFormat = PixelFormat$1.RGBA;

    const fs = new ShaderSource({
      defines: defines,
      sources: [OctahedralProjectionFS],
    });

    this._va = createVertexArray$5(context);
    this._sp = ShaderProgram.fromCache({
      context: context,
      vertexShaderSource: OctahedralProjectionVS,
      fragmentShaderSource: fs,
      attributeLocations: {
        position: 0,
        cubeMapCoordinates: 1,
      },
    });

    // We only need up to 6 mip levels to avoid artifacts.
    const length = Math.min(cubeMapBuffers.length, 6);
    this._maximumMipmapLevel = length - 1;
    const cubeMaps = (this._cubeMaps = new Array(length));
    const mipTextures = (this._mipTextures = new Array(length));
    const originalSize = cubeMapBuffers[0].positiveX.width * 2.0;
    const uniformMap = {
      originalSize: function () {
        return originalSize;
      },
    };

    // First we project each cubemap onto a flat octahedron, and write that to a texture.
    for (let i = 0; i < length; ++i) {
      // Swap +Y/-Y faces since the octahedral projection expects this order.
      const positiveY = cubeMapBuffers[i].positiveY;
      cubeMapBuffers[i].positiveY = cubeMapBuffers[i].negativeY;
      cubeMapBuffers[i].negativeY = positiveY;

      const cubeMap = (cubeMaps[i] = new CubeMap({
        context: context,
        source: cubeMapBuffers[i],
        pixelDatatype: pixelDatatype,
      }));
      const size = cubeMaps[i].width * 2;

      const mipTexture = (mipTextures[i] = new Texture({
        context: context,
        width: size,
        height: size,
        pixelDatatype: pixelDatatype,
        pixelFormat: pixelFormat,
      }));

      const command = new ComputeCommand({
        vertexArray: this._va,
        shaderProgram: this._sp,
        uniformMap: {
          cubeMap: createUniformTexture(cubeMap),
        },
        outputTexture: mipTexture,
        persists: true,
        owner: this,
      });
      frameState.commandList.push(command);

      uniformMap[`texture${i}`] = createUniformTexture(mipTexture);
    }

    this._texture = new Texture({
      context: context,
      width: originalSize * 1.5 + 2.0, // We add a 1 pixel border to avoid linear sampling artifacts.
      height: originalSize,
      pixelDatatype: pixelDatatype,
      pixelFormat: pixelFormat,
    });

    this._texture.maximumMipmapLevel = this._maximumMipmapLevel;
    context.textureCache.addTexture(this._url, this._texture);

    const atlasCommand = new ComputeCommand({
      fragmentShaderSource: OctahedralProjectionAtlasFS,
      uniformMap: uniformMap,
      outputTexture: this._texture,
      persists: false,
      owner: this,
    });
    frameState.commandList.push(atlasCommand);

    this._ready = true;
    this._readyPromise.resolve();
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <p>
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   * </p>
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see OctahedralProjectedCubeMap#destroy
   */
  OctahedralProjectedCubeMap.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <p>
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   * </p>
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @see OctahedralProjectedCubeMap#isDestroyed
   */
  OctahedralProjectedCubeMap.prototype.destroy = function () {
    cleanupResources(this);
    this._texture = this._texture && this._texture.destroy();
    return destroyObject(this);
  };

  /**
   * Properties for managing image-based lighting on tilesets and models.
   * Also manages the necessary resources and textures.
   * <p>
   * If specular environment maps are used, {@link ImageBasedLighting#destroy} must be called
   * when the image-based lighting is no longer needed to clean up GPU resources properly.
   * If a model or tileset creates an instance of ImageBasedLighting, it will handle this.
   * Otherwise, the application is responsible for calling destroy().
   *</p>
   *
   * @alias ImageBasedLighting
   * @constructor
   *
   * @param {Cartesian2} [options.imageBasedLightingFactor=Cartesian2(1.0, 1.0)] Scales diffuse and specular image-based lighting from the earth, sky, atmosphere and star skybox.
   * @param {Number} [options.luminanceAtZenith=0.2] The sun's luminance at the zenith in kilo candela per meter squared to use for this model's procedural environment map.
   * @param {Cartesian3[]} [options.sphericalHarmonicCoefficients] The third order spherical harmonic coefficients used for the diffuse color of image-based lighting.
   * @param {String} [options.specularEnvironmentMaps] A URL to a KTX2 file that contains a cube map of the specular lighting and the convoluted specular mipmaps.
   */
  function ImageBasedLighting(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const imageBasedLightingFactor = defined(options.imageBasedLightingFactor)
      ? Cartesian2.clone(options.imageBasedLightingFactor)
      : new Cartesian2(1.0, 1.0);

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object(
      "options.imageBasedLightingFactor",
      imageBasedLightingFactor
    );
    Check.typeOf.number.greaterThanOrEquals(
      "options.imageBasedLightingFactor.x",
      imageBasedLightingFactor.x,
      0.0
    );
    Check.typeOf.number.lessThanOrEquals(
      "options.imageBasedLightingFactor.x",
      imageBasedLightingFactor.x,
      1.0
    );
    Check.typeOf.number.greaterThanOrEquals(
      "options.imageBasedLightingFactor.y",
      imageBasedLightingFactor.y,
      0.0
    );
    Check.typeOf.number.lessThanOrEquals(
      "options.imageBasedLightingFactor.y",
      imageBasedLightingFactor.y,
      1.0
    );
    //>>includeEnd('debug');

    this._imageBasedLightingFactor = imageBasedLightingFactor;

    const luminanceAtZenith = defaultValue(options.luminanceAtZenith, 0.2);

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("options.luminanceAtZenith", luminanceAtZenith);
    //>>includeEnd('debug');

    this._luminanceAtZenith = luminanceAtZenith;

    const sphericalHarmonicCoefficients = options.sphericalHarmonicCoefficients;

    //>>includeStart('debug', pragmas.debug);
    if (
      defined(sphericalHarmonicCoefficients) &&
      (!Array.isArray(sphericalHarmonicCoefficients) ||
        sphericalHarmonicCoefficients.length !== 9)
    ) {
      throw new DeveloperError(
        "options.sphericalHarmonicCoefficients must be an array of 9 Cartesian3 values."
      );
    }
    //>>includeEnd('debug');
    this._sphericalHarmonicCoefficients = sphericalHarmonicCoefficients;

    // The specular environment map texture is created in update();
    this._specularEnvironmentMaps = options.specularEnvironmentMaps;
    this._specularEnvironmentMapAtlas = undefined;
    this._specularEnvironmentMapAtlasDirty = true;
    this._specularEnvironmentMapLoaded = false;
    this._previousSpecularEnvironmentMapLoaded = false;

    this._useDefaultSpecularMaps = false;
    this._useDefaultSphericalHarmonics = false;
    this._shouldRegenerateShaders = false;

    // Store the previous frame number to prevent redundant update calls
    this._previousFrameNumber = undefined;

    // Keeps track of the last values for use during update logic
    this._previousImageBasedLightingFactor = Cartesian2.clone(
      imageBasedLightingFactor
    );
    this._previousLuminanceAtZenith = luminanceAtZenith;
    this._previousSphericalHarmonicCoefficients = sphericalHarmonicCoefficients;
  }

  Object.defineProperties(ImageBasedLighting.prototype, {
    /**
     * Cesium adds lighting from the earth, sky, atmosphere, and star skybox.
     * This cartesian is used to scale the final diffuse and specular lighting
     * contribution from those sources to the final color. A value of 0.0 will
     * disable those light sources.
     *
     * @memberof ImageBasedLighting.prototype
     *
     * @type {Cartesian2}
     * @default Cartesian2(1.0, 1.0)
     */
    imageBasedLightingFactor: {
      get: function () {
        return this._imageBasedLightingFactor;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.object("imageBasedLightingFactor", value);
        Check.typeOf.number.greaterThanOrEquals(
          "imageBasedLightingFactor.x",
          value.x,
          0.0
        );
        Check.typeOf.number.lessThanOrEquals(
          "imageBasedLightingFactor.x",
          value.x,
          1.0
        );
        Check.typeOf.number.greaterThanOrEquals(
          "imageBasedLightingFactor.y",
          value.y,
          0.0
        );
        Check.typeOf.number.lessThanOrEquals(
          "imageBasedLightingFactor.y",
          value.y,
          1.0
        );
        //>>includeEnd('debug');
        this._previousImageBasedLightingFactor = Cartesian2.clone(
          this._imageBasedLightingFactor,
          this._previousImageBasedLightingFactor
        );
        this._imageBasedLightingFactor = Cartesian2.clone(
          value,
          this._imageBasedLightingFactor
        );
      },
    },

    /**
     * The sun's luminance at the zenith in kilo candela per meter squared
     * to use for this model's procedural environment map. This is used when
     * {@link ImageBasedLighting#specularEnvironmentMaps} and {@link ImageBasedLighting#sphericalHarmonicCoefficients}
     * are not defined.
     *
     * @memberof ImageBasedLighting.prototype
     *
     * @type {Number}
     * @default 0.2
     */
    luminanceAtZenith: {
      get: function () {
        return this._luminanceAtZenith;
      },
      set: function (value) {
        this._previousLuminanceAtZenith = this._luminanceAtZenith;
        this._luminanceAtZenith = value;
      },
    },

    /**
     * The third order spherical harmonic coefficients used for the diffuse color of image-based lighting. When <code>undefined</code>, a diffuse irradiance
     * computed from the atmosphere color is used.
     * <p>
     * There are nine <code>Cartesian3</code> coefficients.
     * The order of the coefficients is: L<sub>0,0</sub>, L<sub>1,-1</sub>, L<sub>1,0</sub>, L<sub>1,1</sub>, L<sub>2,-2</sub>, L<sub>2,-1</sub>, L<sub>2,0</sub>, L<sub>2,1</sub>, L<sub>2,2</sub>
     * </p>
     *
     * These values can be obtained by preprocessing the environment map using the <code>cmgen</code> tool of
     * {@link https://github.com/google/filament/releases|Google's Filament project}. This will also generate a KTX file that can be
     * supplied to {@link Model#specularEnvironmentMaps}.
     *
     * @memberof ImageBasedLighting.prototype
     *
     * @type {Cartesian3[]}
     * @demo {@link https://sandcastle.cesium.com/index.html?src=Image-Based Lighting.html|Sandcastle Image Based Lighting Demo}
     * @see {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf|An Efficient Representation for Irradiance Environment Maps}
     */
    sphericalHarmonicCoefficients: {
      get: function () {
        return this._sphericalHarmonicCoefficients;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (defined(value) && (!Array.isArray(value) || value.length !== 9)) {
          throw new DeveloperError(
            "sphericalHarmonicCoefficients must be an array of 9 Cartesian3 values."
          );
        }
        //>>includeEnd('debug');
        this._previousSphericalHarmonicCoefficients = this._sphericalHarmonicCoefficients;
        this._sphericalHarmonicCoefficients = value;
      },
    },

    /**
     * A URL to a KTX2 file that contains a cube map of the specular lighting and the convoluted specular mipmaps.
     *
     * @memberof ImageBasedLighting.prototype
     * @demo {@link https://sandcastle.cesium.com/index.html?src=Image-Based Lighting.html|Sandcastle Image Based Lighting Demo}
     * @type {String}
     * @see ImageBasedLighting#sphericalHarmonicCoefficients
     */
    specularEnvironmentMaps: {
      get: function () {
        return this._specularEnvironmentMaps;
      },
      set: function (value) {
        if (value !== this._specularEnvironmentMaps) {
          this._specularEnvironmentMapAtlasDirty =
            this._specularEnvironmentMapAtlasDirty ||
            value !== this._specularEnvironmentMaps;
          this._specularEnvironmentMapLoaded = false;
        }
        this._specularEnvironmentMaps = value;
      },
    },

    /**
     * Whether or not image-based lighting is enabled.
     *
     * @memberof ImageBasedLighting.prototype
     * @type {Boolean}
     *
     * @private
     */
    enabled: {
      get: function () {
        return (
          this._imageBasedLightingFactor.x > 0.0 ||
          this._imageBasedLightingFactor.y > 0.0
        );
      },
    },

    /**
     * Whether or not the models that use this lighting should regenerate their shaders,
     * based on the properties and resources have changed.
     *
     * @memberof ImageBasedLighting.prototype
     * @type {Boolean}
     *
     * @private
     */
    shouldRegenerateShaders: {
      get: function () {
        return this._shouldRegenerateShaders;
      },
    },

    /**
     * Whether or not to use the default spherical harmonic coefficients.
     *
     * @memberof ImageBasedLighting.prototype
     * @type {Boolean}
     *
     * @private
     */
    useDefaultSphericalHarmonics: {
      get: function () {
        return this._useDefaultSphericalHarmonics;
      },
    },

    /**
     * Whether or not the image-based lighting settings use spherical harmonic coefficients.
     *
     * @memberof ImageBasedLighting.prototype
     * @type {Boolean}
     *
     * @private
     */
    useSphericalHarmonicCoefficients: {
      get: function () {
        return (
          defined(this._sphericalHarmonicCoefficients) ||
          this._useDefaultSphericalHarmonics
        );
      },
    },

    /**
     * The texture atlas for the specular environment maps.
     *
     * @memberof ImageBasedLighting.prototype
     * @type {OctahedralProjectedCubeMap}
     *
     * @private
     */
    specularEnvironmentMapAtlas: {
      get: function () {
        return this._specularEnvironmentMapAtlas;
      },
    },

    /**
     * Whether or not to use the default specular environment maps.
     *
     * @memberof ImageBasedLighting.prototype
     * @type {Boolean}
     *
     * @private
     */
    useDefaultSpecularMaps: {
      get: function () {
        return this._useDefaultSpecularMaps;
      },
    },

    /**
     * Whether or not the image-based lighting settings use specular environment maps.
     *
     * @memberof ImageBasedLighting.prototype
     * @type {Boolean}
     *
     * @private
     */
    useSpecularEnvironmentMaps: {
      get: function () {
        return (
          (defined(this._specularEnvironmentMapAtlas) &&
            this._specularEnvironmentMapAtlas.ready) ||
          this._useDefaultSpecularMaps
        );
      },
    },
  });

  function createSpecularEnvironmentMapAtlas(imageBasedLighting, context) {
    if (!OctahedralProjectedCubeMap.isSupported(context)) {
      return;
    }

    imageBasedLighting._specularEnvironmentMapAtlas =
      imageBasedLighting._specularEnvironmentMapAtlas &&
      imageBasedLighting._specularEnvironmentMapAtlas.destroy();

    if (defined(imageBasedLighting._specularEnvironmentMaps)) {
      const atlas = new OctahedralProjectedCubeMap(
        imageBasedLighting._specularEnvironmentMaps
      );
      imageBasedLighting._specularEnvironmentMapAtlas = atlas;

      atlas.readyPromise
        .then(function () {
          imageBasedLighting._specularEnvironmentMapLoaded = true;
        })
        .catch(function (error) {
          console.error(`Error loading specularEnvironmentMaps: ${error}`);
        });
    }

    // Regenerate shaders so they do not use an environment map.
    // Will be set to true again if there was a new environment map and it is ready.
    imageBasedLighting._shouldRegenerateShaders = true;
  }

  ImageBasedLighting.prototype.update = function (frameState) {
    if (frameState.frameNumber === this._previousFrameNumber) {
      return;
    }

    this._previousFrameNumber = frameState.frameNumber;
    const context = frameState.context;

    frameState.brdfLutGenerator.update(frameState);
    this._shouldRegenerateShaders = false;

    const iblFactor = this._imageBasedLightingFactor;
    const previousIBLFactor = this._previousImageBasedLightingFactor;
    if (!Cartesian2.equals(iblFactor, previousIBLFactor)) {
      this._shouldRegenerateShaders =
        (iblFactor.x > 0.0 && previousIBLFactor.x === 0.0) ||
        (iblFactor.x === 0.0 && previousIBLFactor.x > 0.0);
      this._shouldRegenerateShaders =
        this._shouldRegenerateShaders ||
        (iblFactor.y > 0.0 && previousIBLFactor.y === 0.0) ||
        (iblFactor.y === 0.0 && previousIBLFactor.y > 0.0);

      this._previousImageBasedLightingFactor = Cartesian2.clone(
        this._imageBasedLightingFactor,
        this._previousImageBasedLightingFactor
      );
    }

    if (this._luminanceAtZenith !== this._previousLuminanceAtZenith) {
      this._shouldRegenerateShaders =
        this._shouldRegenerateShaders ||
        defined(this._luminanceAtZenith) !==
          defined(this._previousLuminanceAtZenith);

      this._previousLuminanceAtZenith = this._luminanceAtZenith;
    }

    if (
      this._previousSphericalHarmonicCoefficients !==
      this._sphericalHarmonicCoefficients
    ) {
      this._shouldRegenerateShaders =
        this._shouldRegenerateShaders ||
        defined(this._previousSphericalHarmonicCoefficients) !==
          defined(this._sphericalHarmonicCoefficients);

      this._previousSphericalHarmonicCoefficients = this._sphericalHarmonicCoefficients;
    }

    this._shouldRegenerateShaders =
      this._shouldRegenerateShaders ||
      this._previousSpecularEnvironmentMapLoaded !==
        this._specularEnvironmentMapLoaded;

    this._previousSpecularEnvironmentMapLoaded = this._specularEnvironmentMapLoaded;

    if (this._specularEnvironmentMapAtlasDirty) {
      createSpecularEnvironmentMapAtlas(this, context);
      this._specularEnvironmentMapAtlasDirty = false;
    }

    if (defined(this._specularEnvironmentMapAtlas)) {
      this._specularEnvironmentMapAtlas.update(frameState);
    }

    const recompileWithDefaultAtlas =
      !defined(this._specularEnvironmentMapAtlas) &&
      defined(frameState.specularEnvironmentMaps) &&
      !this._useDefaultSpecularMaps;
    const recompileWithoutDefaultAtlas =
      !defined(frameState.specularEnvironmentMaps) &&
      this._useDefaultSpecularMaps;

    const recompileWithDefaultSHCoeffs =
      !defined(this._sphericalHarmonicCoefficients) &&
      defined(frameState.sphericalHarmonicCoefficients) &&
      !this._useDefaultSphericalHarmonics;
    const recompileWithoutDefaultSHCoeffs =
      !defined(frameState.sphericalHarmonicCoefficients) &&
      this._useDefaultSphericalHarmonics;

    this._shouldRegenerateShaders =
      this._shouldRegenerateShaders ||
      recompileWithDefaultAtlas ||
      recompileWithoutDefaultAtlas ||
      recompileWithDefaultSHCoeffs ||
      recompileWithoutDefaultSHCoeffs;

    this._useDefaultSpecularMaps =
      !defined(this._specularEnvironmentMapAtlas) &&
      defined(frameState.specularEnvironmentMaps);
    this._useDefaultSphericalHarmonics =
      !defined(this._sphericalHarmonicCoefficients) &&
      defined(frameState.sphericalHarmonicCoefficients);
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} True if this object was destroyed; otherwise, false.
   *
   * @see ImageBasedLighting#destroy
   * @private
   */
  ImageBasedLighting.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @example
   * imageBasedLighting = imageBasedLighting && imageBasedLighting.destroy();
   *
   * @see ImageBasedLighting#isDestroyed
   * @private
   */
  ImageBasedLighting.prototype.destroy = function () {
    this._specularEnvironmentMapAtlas =
      this._specularEnvironmentMapAtlas &&
      this._specularEnvironmentMapAtlas.destroy();
    return destroyObject(this);
  };

  /**
   * Represents a command to the renderer for clearing a framebuffer.
   *
   * @private
   * @constructor
   */
  function ClearCommand(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    /**
     * The value to clear the color buffer to.  When <code>undefined</code>, the color buffer is not cleared.
     *
     * @type {Color}
     *
     * @default undefined
     */
    this.color = options.color;

    /**
     * The value to clear the depth buffer to.  When <code>undefined</code>, the depth buffer is not cleared.
     *
     * @type {Number}
     *
     * @default undefined
     */
    this.depth = options.depth;

    /**
     * The value to clear the stencil buffer to.  When <code>undefined</code>, the stencil buffer is not cleared.
     *
     * @type {Number}
     *
     * @default undefined
     */
    this.stencil = options.stencil;

    /**
     * The render state to apply when executing the clear command.  The following states affect clearing:
     * scissor test, color mask, depth mask, and stencil mask.  When the render state is
     * <code>undefined</code>, the default render state is used.
     *
     * @type {RenderState}
     *
     * @default undefined
     */
    this.renderState = options.renderState;

    /**
     * The framebuffer to clear.
     *
     * @type {Framebuffer}
     *
     * @default undefined
     */
    this.framebuffer = options.framebuffer;

    /**
     * The object who created this command.  This is useful for debugging command
     * execution; it allows you to see who created a command when you only have a
     * reference to the command, and can be used to selectively execute commands
     * with {@link Scene#debugCommandFilter}.
     *
     * @type {Object}
     *
     * @default undefined
     *
     * @see Scene#debugCommandFilter
     */
    this.owner = options.owner;

    /**
     * The pass in which to run this command.
     *
     * @type {Pass}
     *
     * @default undefined
     */
    this.pass = options.pass;
  }

  /**
   * Clears color to (0.0, 0.0, 0.0, 0.0); depth to 1.0; and stencil to 0.
   *
   * @type {ClearCommand}
   *
   * @constant
   */
  ClearCommand.ALL = Object.freeze(
    new ClearCommand({
      color: new Color(0.0, 0.0, 0.0, 0.0),
      depth: 1.0,
      stencil: 0.0,
    })
  );

  ClearCommand.prototype.execute = function (context, passState) {
    context.clear(this, passState);
  };

  /**
   * An enum describing the x, y, and z axes and helper conversion functions.
   *
   * @enum {Number}
   */
  const Axis = {
    /**
     * Denotes the x-axis.
     *
     * @type {Number}
     * @constant
     */
    X: 0,

    /**
     * Denotes the y-axis.
     *
     * @type {Number}
     * @constant
     */
    Y: 1,

    /**
     * Denotes the z-axis.
     *
     * @type {Number}
     * @constant
     */
    Z: 2,
  };

  /**
   * Matrix used to convert from y-up to z-up
   *
   * @type {Matrix4}
   * @constant
   */
  Axis.Y_UP_TO_Z_UP = Matrix4.fromRotationTranslation(
    Matrix3.fromRotationX(CesiumMath.PI_OVER_TWO)
  );

  /**
   * Matrix used to convert from z-up to y-up
   *
   * @type {Matrix4}
   * @constant
   */
  Axis.Z_UP_TO_Y_UP = Matrix4.fromRotationTranslation(
    Matrix3.fromRotationX(-CesiumMath.PI_OVER_TWO)
  );

  /**
   * Matrix used to convert from x-up to z-up
   *
   * @type {Matrix4}
   * @constant
   */
  Axis.X_UP_TO_Z_UP = Matrix4.fromRotationTranslation(
    Matrix3.fromRotationY(-CesiumMath.PI_OVER_TWO)
  );

  /**
   * Matrix used to convert from z-up to x-up
   *
   * @type {Matrix4}
   * @constant
   */
  Axis.Z_UP_TO_X_UP = Matrix4.fromRotationTranslation(
    Matrix3.fromRotationY(CesiumMath.PI_OVER_TWO)
  );

  /**
   * Matrix used to convert from x-up to y-up
   *
   * @type {Matrix4}
   * @constant
   */
  Axis.X_UP_TO_Y_UP = Matrix4.fromRotationTranslation(
    Matrix3.fromRotationZ(CesiumMath.PI_OVER_TWO)
  );

  /**
   * Matrix used to convert from y-up to x-up
   *
   * @type {Matrix4}
   * @constant
   */
  Axis.Y_UP_TO_X_UP = Matrix4.fromRotationTranslation(
    Matrix3.fromRotationZ(-CesiumMath.PI_OVER_TWO)
  );

  /**
   * Gets the axis by name
   *
   * @param {String} name The name of the axis.
   * @returns {Number} The axis enum.
   */
  Axis.fromName = function (name) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("name", name);
    //>>includeEnd('debug');

    return Axis[name];
  };

  var Axis$1 = Object.freeze(Axis);

  /**
   * Simple abstraction for a group. This class exists to make the metadata API
   * more consistent, i.e. metadata can be accessed via
   * <code>content.group.metadata</code> much like tile metadata is accessed as
   * <code>tile.metadata</code>.
   *
   * @param {Object} options Object with the following properties:
   * @param {GroupMetadata} options.metadata The metadata associated with this group.
   *
   * @alias Cesium3DContentGroup
   * @constructor
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function Cesium3DContentGroup(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.metadata", options.metadata);
    //>>includeEnd('debug');

    this._metadata = options.metadata;
  }

  Object.defineProperties(Cesium3DContentGroup.prototype, {
    /**
     * Get the metadata for this group
     *
     * @memberof Cesium3DContentGroup.prototype
     *
     * @type {GroupMetadata}
     *
     * @readonly
     */
    metadata: {
      get: function () {
        return this._metadata;
      },
    },
  });

  /**
   * Handles parsing of a Batched 3D Model.
   *
   * @namespace B3dmParser
   * @private
   */
  const B3dmParser = {};
  B3dmParser._deprecationWarning = deprecationWarning;

  const sizeOfUint32$6 = Uint32Array.BYTES_PER_ELEMENT;

  /**
   * Parses the contents of a {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/TileFormats/Batched3DModel|Batched 3D Model}.
   *
   * @private
   *
   * @param {ArrayBuffer} arrayBuffer The array buffer containing the b3dm.
   * @param {Number} [byteOffset=0] The byte offset of the beginning of the b3dm in the array buffer.
   * @returns {Object} Returns an object with the batch length, feature table (binary and json), batch table (binary and json) and glTF parts of the b3dm.
   */
  B3dmParser.parse = function (arrayBuffer, byteOffset) {
    const byteStart = defaultValue(byteOffset, 0);
    //>>includeStart('debug', pragmas.debug);
    Check.defined("arrayBuffer", arrayBuffer);
    //>>includeEnd('debug');

    byteOffset = byteStart;

    const uint8Array = new Uint8Array(arrayBuffer);
    const view = new DataView(arrayBuffer);
    byteOffset += sizeOfUint32$6; // Skip magic

    const version = view.getUint32(byteOffset, true);
    if (version !== 1) {
      throw new RuntimeError(
        `Only Batched 3D Model version 1 is supported.  Version ${version} is not.`
      );
    }
    byteOffset += sizeOfUint32$6;

    const byteLength = view.getUint32(byteOffset, true);
    byteOffset += sizeOfUint32$6;

    let featureTableJsonByteLength = view.getUint32(byteOffset, true);
    byteOffset += sizeOfUint32$6;

    let featureTableBinaryByteLength = view.getUint32(byteOffset, true);
    byteOffset += sizeOfUint32$6;

    let batchTableJsonByteLength = view.getUint32(byteOffset, true);
    byteOffset += sizeOfUint32$6;

    let batchTableBinaryByteLength = view.getUint32(byteOffset, true);
    byteOffset += sizeOfUint32$6;

    let batchLength;

    // Legacy header #1: [batchLength] [batchTableByteLength]
    // Legacy header #2: [batchTableJsonByteLength] [batchTableBinaryByteLength] [batchLength]
    // Current header: [featureTableJsonByteLength] [featureTableBinaryByteLength] [batchTableJsonByteLength] [batchTableBinaryByteLength]
    // If the header is in the first legacy format 'batchTableJsonByteLength' will be the start of the JSON string (a quotation mark) or the glTF magic.
    // Accordingly its first byte will be either 0x22 or 0x67, and so the minimum uint32 expected is 0x22000000 = 570425344 = 570MB. It is unlikely that the feature table JSON will exceed this length.
    // The check for the second legacy format is similar, except it checks 'batchTableBinaryByteLength' instead
    if (batchTableJsonByteLength >= 570425344) {
      // First legacy check
      byteOffset -= sizeOfUint32$6 * 2;
      batchLength = featureTableJsonByteLength;
      batchTableJsonByteLength = featureTableBinaryByteLength;
      batchTableBinaryByteLength = 0;
      featureTableJsonByteLength = 0;
      featureTableBinaryByteLength = 0;
      B3dmParser._deprecationWarning(
        "b3dm-legacy-header",
        "This b3dm header is using the legacy format [batchLength] [batchTableByteLength]. The new format is [featureTableJsonByteLength] [featureTableBinaryByteLength] [batchTableJsonByteLength] [batchTableBinaryByteLength] from https://github.com/CesiumGS/3d-tiles/tree/main/specification/TileFormats/Batched3DModel."
      );
    } else if (batchTableBinaryByteLength >= 570425344) {
      // Second legacy check
      byteOffset -= sizeOfUint32$6;
      batchLength = batchTableJsonByteLength;
      batchTableJsonByteLength = featureTableJsonByteLength;
      batchTableBinaryByteLength = featureTableBinaryByteLength;
      featureTableJsonByteLength = 0;
      featureTableBinaryByteLength = 0;
      B3dmParser._deprecationWarning(
        "b3dm-legacy-header",
        "This b3dm header is using the legacy format [batchTableJsonByteLength] [batchTableBinaryByteLength] [batchLength]. The new format is [featureTableJsonByteLength] [featureTableBinaryByteLength] [batchTableJsonByteLength] [batchTableBinaryByteLength] from https://github.com/CesiumGS/3d-tiles/tree/main/specification/TileFormats/Batched3DModel."
      );
    }

    let featureTableJson;
    if (featureTableJsonByteLength === 0) {
      featureTableJson = {
        BATCH_LENGTH: defaultValue(batchLength, 0),
      };
    } else {
      featureTableJson = getJsonFromTypedArray(
        uint8Array,
        byteOffset,
        featureTableJsonByteLength
      );
      byteOffset += featureTableJsonByteLength;
    }

    const featureTableBinary = new Uint8Array(
      arrayBuffer,
      byteOffset,
      featureTableBinaryByteLength
    );
    byteOffset += featureTableBinaryByteLength;

    let batchTableJson;
    let batchTableBinary;
    if (batchTableJsonByteLength > 0) {
      // PERFORMANCE_IDEA: is it possible to allocate this on-demand?  Perhaps keep the
      // arraybuffer/string compressed in memory and then decompress it when it is first accessed.
      //
      // We could also make another request for it, but that would make the property set/get
      // API async, and would double the number of numbers in some cases.
      batchTableJson = getJsonFromTypedArray(
        uint8Array,
        byteOffset,
        batchTableJsonByteLength
      );
      byteOffset += batchTableJsonByteLength;

      if (batchTableBinaryByteLength > 0) {
        // Has a batch table binary
        batchTableBinary = new Uint8Array(
          arrayBuffer,
          byteOffset,
          batchTableBinaryByteLength
        );
        // Copy the batchTableBinary section and let the underlying ArrayBuffer be freed
        batchTableBinary = new Uint8Array(batchTableBinary);
        byteOffset += batchTableBinaryByteLength;
      }
    }

    const gltfByteLength = byteStart + byteLength - byteOffset;
    if (gltfByteLength === 0) {
      throw new RuntimeError("glTF byte length must be greater than 0.");
    }

    let gltfView;
    if (byteOffset % 4 === 0) {
      gltfView = new Uint8Array(arrayBuffer, byteOffset, gltfByteLength);
    } else {
      // Create a copy of the glb so that it is 4-byte aligned
      B3dmParser._deprecationWarning(
        "b3dm-glb-unaligned",
        "The embedded glb is not aligned to a 4-byte boundary."
      );
      gltfView = new Uint8Array(
        uint8Array.subarray(byteOffset, byteOffset + gltfByteLength)
      );
    }

    return {
      batchLength: batchLength,
      featureTableJson: featureTableJson,
      featureTableBinary: featureTableBinary,
      batchTableJson: batchTableJson,
      batchTableBinary: batchTableBinary,
      gltf: gltfView,
    };
  };

  /**
   * An object that manages color, show/hide and picking textures for a batch
   * table or feature table.
   *
   * @param {Object} options Object with the following properties:
   * @param {Number} featuresLength The number of features in the batch table or feature table
   * @param {Cesium3DTileContent|ModelFeatureTable} owner The owner of this batch texture. For 3D Tiles, this will be a {@link Cesium3DTileContent}. For glTF models, this will be a {@link ModelFeatureTable}.
   * @param {Object} [statistics] The statistics object to update with information about the batch texture.
   * @param {Function} [colorChangedCallback] A callback function that is called whenever the color of a feature changes.
   *
   * @alias BatchTexture
   * @constructor
   *
   * @private
   */
  function BatchTexture(options) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("options.featuresLength", options.featuresLength);
    Check.typeOf.object("options.owner", options.owner);
    //>>includeEnd('debug');

    const featuresLength = options.featuresLength;

    // PERFORMANCE_IDEA: These parallel arrays probably generate cache misses in get/set color/show
    // and use A LOT of memory.  How can we use less memory?
    this._showAlphaProperties = undefined; // [Show (0 or 255), Alpha (0 to 255)] property for each feature
    this._batchValues = undefined; // Per-feature RGBA (A is based on the color's alpha and feature's show property)

    this._batchValuesDirty = false;
    this._batchTexture = undefined;
    this._defaultTexture = undefined;

    this._pickTexture = undefined;
    this._pickIds = [];

    // Dimensions for batch and pick textures
    let textureDimensions;
    let textureStep;

    if (featuresLength > 0) {
      // PERFORMANCE_IDEA: this can waste memory in the last row in the uncommon case
      // when more than one row is needed (e.g., > 16K features in one tile)
      const width = Math.min(featuresLength, ContextLimits.maximumTextureSize);
      const height = Math.ceil(featuresLength / ContextLimits.maximumTextureSize);
      const stepX = 1.0 / width;
      const centerX = stepX * 0.5;
      const stepY = 1.0 / height;
      const centerY = stepY * 0.5;

      textureDimensions = new Cartesian2(width, height);
      textureStep = new Cartesian4(stepX, centerX, stepY, centerY);
    }

    this._translucentFeaturesLength = 0;
    this._featuresLength = featuresLength;
    this._textureDimensions = textureDimensions;
    this._textureStep = textureStep;
    this._owner = options.owner;
    this._statistics = options.statistics;
    this._colorChangedCallback = options.colorChangedCallback;
  }

  Object.defineProperties(BatchTexture.prototype, {
    /**
     * Number of features that are translucent
     *
     * @memberof BatchTexture.prototype
     * @type {Number}
     * @readonly
     * @private
     */
    translucentFeaturesLength: {
      get: function () {
        return this._translucentFeaturesLength;
      },
    },

    /**
     * Total size of all GPU resources used by this batch texture.
     *
     * @memberof BatchTexture.prototype
     * @type {Number}
     * @readonly
     * @private
     */
    byteLength: {
      get: function () {
        let memory = 0;
        if (defined(this._pickTexture)) {
          memory += this._pickTexture.sizeInBytes;
        }
        if (defined(this._batchTexture)) {
          memory += this._batchTexture.sizeInBytes;
        }
        return memory;
      },
    },

    /**
     * Dimensions of the underlying batch texture.
     *
     * @memberof BatchTexture.prototype
     * @type {Cartesian2}
     * @readonly
     * @private
     */
    textureDimensions: {
      get: function () {
        return this._textureDimensions;
      },
    },

    /**
     * Size of each texture and distance from side to center of a texel in
     * each direction. Stored as (stepX, centerX, stepY, centerY)
     *
     * @memberof BatchTexture.prototype
     * @type {Cartesian4}
     * @readonly
     * @private
     */
    textureStep: {
      get: function () {
        return this._textureStep;
      },
    },

    /**
     * The underlying texture used for styling. The texels are accessed
     * by batch ID, and the value is the color of this feature after accounting
     * for show/hide settings.
     *
     * @memberof BatchTexture.prototype
     * @type {Texture}
     * @readonly
     * @private
     */
    batchTexture: {
      get: function () {
        return this._batchTexture;
      },
    },

    /**
     * The default texture to use when there are no batch values
     *
     * @memberof BatchTexture.prototype
     * @type {Texture}
     * @readonly
     * @private
     */
    defaultTexture: {
      get: function () {
        return this._defaultTexture;
      },
    },

    /**
     * The underlying texture used for picking. The texels are accessed by
     * batch ID, and the value is the pick color.
     *
     * @memberof BatchTexture.prototype
     * @type {Texture}
     * @readonly
     * @private
     */
    pickTexture: {
      get: function () {
        return this._pickTexture;
      },
    },
  });

  BatchTexture.DEFAULT_COLOR_VALUE = Color.WHITE;
  BatchTexture.DEFAULT_SHOW_VALUE = true;

  function getByteLength(batchTexture) {
    const dimensions = batchTexture._textureDimensions;
    return dimensions.x * dimensions.y * 4;
  }

  function getBatchValues(batchTexture) {
    if (!defined(batchTexture._batchValues)) {
      // Default batch texture to RGBA = 255: white highlight (RGB) and show/alpha = true/255 (A).
      const byteLength = getByteLength(batchTexture);
      const bytes = new Uint8Array(byteLength).fill(255);
      batchTexture._batchValues = bytes;
    }

    return batchTexture._batchValues;
  }

  function getShowAlphaProperties(batchTexture) {
    if (!defined(batchTexture._showAlphaProperties)) {
      const byteLength = 2 * batchTexture._featuresLength;
      const bytes = new Uint8Array(byteLength).fill(255);
      // [Show = true, Alpha = 255]
      batchTexture._showAlphaProperties = bytes;
    }
    return batchTexture._showAlphaProperties;
  }

  function checkBatchId$1(batchId, featuresLength) {
    if (!defined(batchId) || batchId < 0 || batchId >= featuresLength) {
      throw new DeveloperError(
        `batchId is required and between zero and featuresLength - 1 (${featuresLength}` -
          +")."
      );
    }
  }

  /**
   * Set whether a feature is visible.
   *
   * @param {Number} batchId the ID of the feature
   * @param {Boolean} show <code>true</code> if the feature should be shown, <code>false</code> otherwise
   * @private
   */
  BatchTexture.prototype.setShow = function (batchId, show) {
    //>>includeStart('debug', pragmas.debug);
    checkBatchId$1(batchId, this._featuresLength);
    Check.typeOf.bool("show", show);
    //>>includeEnd('debug');

    if (show && !defined(this._showAlphaProperties)) {
      // Avoid allocating since the default is show = true
      return;
    }

    const showAlphaProperties = getShowAlphaProperties(this);
    const propertyOffset = batchId * 2;

    const newShow = show ? 255 : 0;
    if (showAlphaProperties[propertyOffset] !== newShow) {
      showAlphaProperties[propertyOffset] = newShow;

      const batchValues = getBatchValues(this);

      // Compute alpha used in the shader based on show and color.alpha properties
      const offset = batchId * 4 + 3;
      batchValues[offset] = show ? showAlphaProperties[propertyOffset + 1] : 0;

      this._batchValuesDirty = true;
    }
  };

  /**
   * Set the show for all features at once.
   *
   * @param {Boolean} show <code>true</code> if the feature should be shown, <code>false</code> otherwise
   * @private
   */
  BatchTexture.prototype.setAllShow = function (show) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.bool("show", show);
    //>>includeEnd('debug');

    const featuresLength = this._featuresLength;
    for (let i = 0; i < featuresLength; ++i) {
      this.setShow(i, show);
    }
  };

  /**
   * Check the current show value for a feature
   *
   * @param {Number} batchId the ID of the feature
   * @return {Boolean} <code>true</code> if the feature is shown, or <code>false</code> otherwise
   * @private
   */
  BatchTexture.prototype.getShow = function (batchId) {
    //>>includeStart('debug', pragmas.debug);
    checkBatchId$1(batchId, this._featuresLength);
    //>>includeEnd('debug');

    if (!defined(this._showAlphaProperties)) {
      // Avoid allocating since the default is show = true
      return true;
    }

    const offset = batchId * 2;
    return this._showAlphaProperties[offset] === 255;
  };

  const scratchColorBytes$1 = new Array(4);

  /**
   * Set the styling color of a feature
   *
   * @param {Number} batchId the ID of the feature
   * @param {Color} color the color to assign to this feature.
   *
   * @private
   */
  BatchTexture.prototype.setColor = function (batchId, color) {
    //>>includeStart('debug', pragmas.debug);
    checkBatchId$1(batchId, this._featuresLength);
    Check.typeOf.object("color", color);
    //>>includeEnd('debug');

    if (
      Color.equals(color, BatchTexture.DEFAULT_COLOR_VALUE) &&
      !defined(this._batchValues)
    ) {
      // Avoid allocating since the default is white
      return;
    }

    const newColor = color.toBytes(scratchColorBytes$1);
    const newAlpha = newColor[3];

    const batchValues = getBatchValues(this);
    const offset = batchId * 4;

    const showAlphaProperties = getShowAlphaProperties(this);
    const propertyOffset = batchId * 2;

    if (
      batchValues[offset] !== newColor[0] ||
      batchValues[offset + 1] !== newColor[1] ||
      batchValues[offset + 2] !== newColor[2] ||
      showAlphaProperties[propertyOffset + 1] !== newAlpha
    ) {
      batchValues[offset] = newColor[0];
      batchValues[offset + 1] = newColor[1];
      batchValues[offset + 2] = newColor[2];

      const wasTranslucent = showAlphaProperties[propertyOffset + 1] !== 255;

      // Compute alpha used in the shader based on show and color.alpha properties
      const show = showAlphaProperties[propertyOffset] !== 0;
      batchValues[offset + 3] = show ? newAlpha : 0;
      showAlphaProperties[propertyOffset + 1] = newAlpha;

      // Track number of translucent features so we know if this tile needs
      // opaque commands, translucent commands, or both for rendering.
      const isTranslucent = newAlpha !== 255;
      if (isTranslucent && !wasTranslucent) {
        ++this._translucentFeaturesLength;
      } else if (!isTranslucent && wasTranslucent) {
        --this._translucentFeaturesLength;
      }

      this._batchValuesDirty = true;

      if (defined(this._colorChangedCallback)) {
        this._colorChangedCallback(batchId, color);
      }
    }
  };

  /**
   * Set the styling color for all features at once
   *
   * @param {Color} color the color to assign to all features.
   *
   * @private
   */
  BatchTexture.prototype.setAllColor = function (color) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("color", color);
    //>>includeEnd('debug');

    const featuresLength = this._featuresLength;
    for (let i = 0; i < featuresLength; ++i) {
      this.setColor(i, color);
    }
  };

  /**
   * Get the current color of a feature
   *
   * @param {Number} batchId The ID of the feature
   * @param {Color} result A color object where the result will be stored.
   * @return {Color} The color assigned to the selected feature
   *
   * @private
   */
  BatchTexture.prototype.getColor = function (batchId, result) {
    //>>includeStart('debug', pragmas.debug);
    checkBatchId$1(batchId, this._featuresLength);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    if (!defined(this._batchValues)) {
      return Color.clone(BatchTexture.DEFAULT_COLOR_VALUE, result);
    }

    const batchValues = this._batchValues;
    const offset = batchId * 4;

    const showAlphaProperties = this._showAlphaProperties;
    const propertyOffset = batchId * 2;

    return Color.fromBytes(
      batchValues[offset],
      batchValues[offset + 1],
      batchValues[offset + 2],
      showAlphaProperties[propertyOffset + 1],
      result
    );
  };

  /**
   * Get the pick color of a feature. This feature is an RGBA encoding of the
   * pick ID.
   *
   * @param {Number} batchId The ID of the feature
   * @return {PickId} The picking color assigned to this feature
   *
   * @private
   */
  BatchTexture.prototype.getPickColor = function (batchId) {
    //>>includeStart('debug', pragmas.debug);
    checkBatchId$1(batchId, this._featuresLength);
    //>>includeEnd('debug');
    return this._pickIds[batchId];
  };

  function createTexture$4(batchTexture, context, bytes) {
    const dimensions = batchTexture._textureDimensions;
    return new Texture({
      context: context,
      pixelFormat: PixelFormat$1.RGBA,
      pixelDatatype: PixelDatatype$1.UNSIGNED_BYTE,
      source: {
        width: dimensions.x,
        height: dimensions.y,
        arrayBufferView: bytes,
      },
      flipY: false,
      sampler: Sampler.NEAREST,
    });
  }

  function createPickTexture(batchTexture, context) {
    const featuresLength = batchTexture._featuresLength;
    if (!defined(batchTexture._pickTexture) && featuresLength > 0) {
      const pickIds = batchTexture._pickIds;
      const byteLength = getByteLength(batchTexture);
      const bytes = new Uint8Array(byteLength);
      const owner = batchTexture._owner;
      const statistics = batchTexture._statistics;

      // PERFORMANCE_IDEA: we could skip the pick texture completely by allocating
      // a continuous range of pickIds and then converting the base pickId + batchId
      // to RGBA in the shader.  The only consider is precision issues, which might
      // not be an issue in WebGL 2.
      for (let i = 0; i < featuresLength; ++i) {
        const pickId = context.createPickId(owner.getFeature(i));
        pickIds.push(pickId);

        const pickColor = pickId.color;
        const offset = i * 4;
        bytes[offset] = Color.floatToByte(pickColor.red);
        bytes[offset + 1] = Color.floatToByte(pickColor.green);
        bytes[offset + 2] = Color.floatToByte(pickColor.blue);
        bytes[offset + 3] = Color.floatToByte(pickColor.alpha);
      }

      batchTexture._pickTexture = createTexture$4(batchTexture, context, bytes);

      // Make sure the tileset statistics are updated the frame when the pick
      // texture is created.
      if (defined(statistics)) {
        statistics.batchTableByteLength += batchTexture._pickTexture.sizeInBytes;
      }
    }
  }

  function updateBatchTexture(batchTexture) {
    const dimensions = batchTexture._textureDimensions;
    // PERFORMANCE_IDEA: Instead of rewriting the entire texture, use fine-grained
    // texture updates when less than, for example, 10%, of the values changed.  Or
    // even just optimize the common case when one feature show/color changed.
    batchTexture._batchTexture.copyFrom({
      source: {
        width: dimensions.x,
        height: dimensions.y,
        arrayBufferView: batchTexture._batchValues,
      },
    });
  }

  BatchTexture.prototype.update = function (tileset, frameState) {
    const context = frameState.context;
    this._defaultTexture = context.defaultTexture;

    const passes = frameState.passes;
    if (passes.pick || passes.postProcess) {
      createPickTexture(this, context);
    }

    if (this._batchValuesDirty) {
      this._batchValuesDirty = false;

      // Create batch texture on-demand
      if (!defined(this._batchTexture)) {
        this._batchTexture = createTexture$4(this, context, this._batchValues);

        // Make sure the tileset statistics are updated the frame when the
        // batch texture is created.
        if (defined(this._statistics)) {
          this._statistics.batchTableByteLength += this._batchTexture.sizeInBytes;
        }
      }

      updateBatchTexture(this); // Apply per-feature show/color updates
    }
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <p>
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   * </p>
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see BatchTexture#destroy
   * @private
   */
  BatchTexture.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <p>
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   * </p>
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @example
   * e = e && e.destroy();
   *
   * @see BatchTexture#isDestroyed
   * @private
   */
  BatchTexture.prototype.destroy = function () {
    this._batchTexture = this._batchTexture && this._batchTexture.destroy();
    this._pickTexture = this._pickTexture && this._pickTexture.destroy();

    const pickIds = this._pickIds;
    const length = pickIds.length;
    for (let i = 0; i < length; ++i) {
      pickIds[i].destroy();
    }

    return destroyObject(this);
  };

  const ComponentsPerAttribute = {
    SCALAR: 1,
    VEC2: 2,
    VEC3: 3,
    VEC4: 4,
    MAT2: 4,
    MAT3: 9,
    MAT4: 16,
  };

  const ClassPerType = {
    SCALAR: undefined,
    VEC2: Cartesian2,
    VEC3: Cartesian3,
    VEC4: Cartesian4,
    MAT2: Matrix2,
    MAT3: Matrix3,
    MAT4: Matrix4,
  };

  /**
   * @private
   */
  function getBinaryAccessor(accessor) {
    const componentType = accessor.componentType;
    let componentDatatype;
    if (typeof componentType === "string") {
      componentDatatype = ComponentDatatype$1.fromName(componentType);
    } else {
      componentDatatype = componentType;
    }

    const componentsPerAttribute = ComponentsPerAttribute[accessor.type];
    const classType = ClassPerType[accessor.type];
    return {
      componentsPerAttribute: componentsPerAttribute,
      classType: classType,
      createArrayBufferView: function (buffer, byteOffset, length) {
        return ComponentDatatype$1.createArrayBufferView(
          componentDatatype,
          buffer,
          byteOffset,
          componentsPerAttribute * length
        );
      },
    };
  }

  /**
   * Object for handling the <code>3DTILES_batch_table_hierarchy</code> extension
   *
   * @param {Object} options Object with the following properties:
   * @param {Object} options.extension The <code>3DTILES_batch_table_hierarchy</code> extension object.
   * @param {Uint8Array} [options.binaryBody] The binary body of the batch table
   *
   * @alias BatchTableHierarchy
   * @constructor
   *
   * @private
   */
  function BatchTableHierarchy(options) {
    this._classes = undefined;
    this._classIds = undefined;
    this._classIndexes = undefined;
    this._parentCounts = undefined;
    this._parentIndexes = undefined;
    this._parentIds = undefined;

    // Total memory used by the typed arrays
    this._byteLength = 0;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.extension", options.extension);
    //>>includeEnd('debug');

    initialize$n(this, options.extension, options.binaryBody);

    //>>includeStart('debug', pragmas.debug);
    validateHierarchy(this);
    //>>includeEnd('debug');
  }

  Object.defineProperties(BatchTableHierarchy.prototype, {
    byteLength: {
      get: function () {
        return this._byteLength;
      },
    },
  });

  /**
   * Parse the batch table hierarchy from the
   * <code>3DTILES_batch_table_hierarchy</code> extension.
   *
   * @param {BatchTableHierarchy} hierarchy The hierarchy instance
   * @param {Object} hierarchyJson The JSON of the extension
   * @param {Uint8Array} [binaryBody] The binary body of the batch table for accessing binary properties
   * @private
   */
  function initialize$n(hierarchy, hierarchyJson, binaryBody) {
    let i;
    let classId;
    let binaryAccessor;

    const instancesLength = hierarchyJson.instancesLength;
    const classes = hierarchyJson.classes;
    let classIds = hierarchyJson.classIds;
    let parentCounts = hierarchyJson.parentCounts;
    let parentIds = hierarchyJson.parentIds;
    let parentIdsLength = instancesLength;
    let byteLength = 0;

    if (defined(classIds.byteOffset)) {
      classIds.componentType = defaultValue(
        classIds.componentType,
        ComponentDatatype$1.UNSIGNED_SHORT
      );
      classIds.type = AttributeType$1.SCALAR;
      binaryAccessor = getBinaryAccessor(classIds);
      classIds = binaryAccessor.createArrayBufferView(
        binaryBody.buffer,
        binaryBody.byteOffset + classIds.byteOffset,
        instancesLength
      );
      byteLength += classIds.byteLength;
    }

    let parentIndexes;
    if (defined(parentCounts)) {
      if (defined(parentCounts.byteOffset)) {
        parentCounts.componentType = defaultValue(
          parentCounts.componentType,
          ComponentDatatype$1.UNSIGNED_SHORT
        );
        parentCounts.type = AttributeType$1.SCALAR;
        binaryAccessor = getBinaryAccessor(parentCounts);
        parentCounts = binaryAccessor.createArrayBufferView(
          binaryBody.buffer,
          binaryBody.byteOffset + parentCounts.byteOffset,
          instancesLength
        );
        byteLength += parentCounts.byteLength;
      }
      parentIndexes = new Uint16Array(instancesLength);
      parentIdsLength = 0;
      for (i = 0; i < instancesLength; ++i) {
        parentIndexes[i] = parentIdsLength;
        parentIdsLength += parentCounts[i];
      }

      byteLength += parentIndexes.byteLength;
    }

    if (defined(parentIds) && defined(parentIds.byteOffset)) {
      parentIds.componentType = defaultValue(
        parentIds.componentType,
        ComponentDatatype$1.UNSIGNED_SHORT
      );
      parentIds.type = AttributeType$1.SCALAR;
      binaryAccessor = getBinaryAccessor(parentIds);
      parentIds = binaryAccessor.createArrayBufferView(
        binaryBody.buffer,
        binaryBody.byteOffset + parentIds.byteOffset,
        parentIdsLength
      );

      byteLength += parentIds.byteLength;
    }

    const classesLength = classes.length;
    for (i = 0; i < classesLength; ++i) {
      const classInstancesLength = classes[i].length;
      const properties = classes[i].instances;
      const binaryProperties = getBinaryProperties$1(
        classInstancesLength,
        properties,
        binaryBody
      );
      byteLength += countBinaryPropertyMemory$1(binaryProperties);
      classes[i].instances = combine$2(binaryProperties, properties);
    }

    const classCounts = new Array(classesLength).fill(0);
    const classIndexes = new Uint16Array(instancesLength);
    for (i = 0; i < instancesLength; ++i) {
      classId = classIds[i];
      classIndexes[i] = classCounts[classId];
      ++classCounts[classId];
    }
    byteLength += classIndexes.byteLength;

    hierarchy._classes = classes;
    hierarchy._classIds = classIds;
    hierarchy._classIndexes = classIndexes;
    hierarchy._parentCounts = parentCounts;
    hierarchy._parentIndexes = parentIndexes;
    hierarchy._parentIds = parentIds;
    hierarchy._byteLength = byteLength;
  }

  function getBinaryProperties$1(featuresLength, properties, binaryBody) {
    let binaryProperties;
    for (const name in properties) {
      if (properties.hasOwnProperty(name)) {
        const property = properties[name];
        const byteOffset = property.byteOffset;
        if (defined(byteOffset)) {
          // This is a binary property
          const componentType = property.componentType;
          const type = property.type;
          if (!defined(componentType)) {
            throw new RuntimeError("componentType is required.");
          }
          if (!defined(type)) {
            throw new RuntimeError("type is required.");
          }
          if (!defined(binaryBody)) {
            throw new RuntimeError(
              `Property ${name} requires a batch table binary.`
            );
          }

          const binaryAccessor = getBinaryAccessor(property);
          const componentCount = binaryAccessor.componentsPerAttribute;
          const classType = binaryAccessor.classType;
          const typedArray = binaryAccessor.createArrayBufferView(
            binaryBody.buffer,
            binaryBody.byteOffset + byteOffset,
            featuresLength
          );

          if (!defined(binaryProperties)) {
            binaryProperties = {};
          }

          // Store any information needed to access the binary data, including the typed array,
          // componentCount (e.g. a VEC4 would be 4), and the type used to pack and unpack (e.g. Cartesian4).
          binaryProperties[name] = {
            typedArray: typedArray,
            componentCount: componentCount,
            type: classType,
          };
        }
      }
    }
    return binaryProperties;
  }

  function countBinaryPropertyMemory$1(binaryProperties) {
    let byteLength = 0;
    for (const name in binaryProperties) {
      if (binaryProperties.hasOwnProperty(name)) {
        byteLength += binaryProperties[name].typedArray.byteLength;
      }
    }
    return byteLength;
  }

  //>>includeStart('debug', pragmas.debug);
  const scratchValidateStack = [];
  function validateHierarchy(hierarchy) {
    const stack = scratchValidateStack;
    stack.length = 0;

    const classIds = hierarchy._classIds;
    const instancesLength = classIds.length;

    for (let i = 0; i < instancesLength; ++i) {
      validateInstance(hierarchy, i, stack);
    }
  }

  function validateInstance(hierarchy, instanceIndex, stack) {
    const parentCounts = hierarchy._parentCounts;
    const parentIds = hierarchy._parentIds;
    const parentIndexes = hierarchy._parentIndexes;
    const classIds = hierarchy._classIds;
    const instancesLength = classIds.length;

    if (!defined(parentIds)) {
      // No need to validate if there are no parents
      return;
    }

    if (instanceIndex >= instancesLength) {
      throw new DeveloperError(
        `Parent index ${instanceIndex} exceeds the total number of instances: ${instancesLength}`
      );
    }
    if (stack.indexOf(instanceIndex) > -1) {
      throw new DeveloperError(
        "Circular dependency detected in the batch table hierarchy."
      );
    }

    stack.push(instanceIndex);
    const parentCount = defined(parentCounts) ? parentCounts[instanceIndex] : 1;
    const parentIndex = defined(parentCounts)
      ? parentIndexes[instanceIndex]
      : instanceIndex;
    for (let i = 0; i < parentCount; ++i) {
      const parentId = parentIds[parentIndex + i];
      // Stop the traversal when the instance has no parent (its parentId equals itself), else continue the traversal.
      if (parentId !== instanceIndex) {
        validateInstance(hierarchy, parentId, stack);
      }
    }
    stack.pop(instanceIndex);
  }
  //>>includeEnd('debug');

  // The size of this array equals the maximum instance count among all loaded tiles, which has the potential to be large.
  const scratchVisited = [];
  const scratchStack$1 = [];
  let marker = 0;
  function traverseHierarchyMultipleParents(
    hierarchy,
    instanceIndex,
    endConditionCallback
  ) {
    const classIds = hierarchy._classIds;
    const parentCounts = hierarchy._parentCounts;
    const parentIds = hierarchy._parentIds;
    const parentIndexes = hierarchy._parentIndexes;
    const instancesLength = classIds.length;

    // Ignore instances that have already been visited. This occurs in diamond inheritance situations.
    // Use a marker value to indicate that an instance has been visited, which increments with each run.
    // This is more efficient than clearing the visited array every time.
    const visited = scratchVisited;
    visited.length = Math.max(visited.length, instancesLength);
    const visitedMarker = ++marker;

    const stack = scratchStack$1;
    stack.length = 0;
    stack.push(instanceIndex);

    while (stack.length > 0) {
      instanceIndex = stack.pop();
      if (visited[instanceIndex] === visitedMarker) {
        // This instance has already been visited, stop traversal
        continue;
      }
      visited[instanceIndex] = visitedMarker;
      const result = endConditionCallback(hierarchy, instanceIndex);
      if (defined(result)) {
        // The end condition was met, stop the traversal and return the result
        return result;
      }
      const parentCount = parentCounts[instanceIndex];
      const parentIndex = parentIndexes[instanceIndex];
      for (let i = 0; i < parentCount; ++i) {
        const parentId = parentIds[parentIndex + i];
        // Stop the traversal when the instance has no parent (its parentId equals itself)
        // else add the parent to the stack to continue the traversal.
        if (parentId !== instanceIndex) {
          stack.push(parentId);
        }
      }
    }
  }

  function traverseHierarchySingleParent(
    hierarchy,
    instanceIndex,
    endConditionCallback
  ) {
    let hasParent = true;
    while (hasParent) {
      const result = endConditionCallback(hierarchy, instanceIndex);
      if (defined(result)) {
        // The end condition was met, stop the traversal and return the result
        return result;
      }
      const parentId = hierarchy._parentIds[instanceIndex];
      hasParent = parentId !== instanceIndex;
      instanceIndex = parentId;
    }
  }

  function traverseHierarchy(hierarchy, instanceIndex, endConditionCallback) {
    // Traverse over the hierarchy and process each instance with the endConditionCallback.
    // When the endConditionCallback returns a value, the traversal stops and that value is returned.
    const parentCounts = hierarchy._parentCounts;
    const parentIds = hierarchy._parentIds;
    if (!defined(parentIds)) {
      return endConditionCallback(hierarchy, instanceIndex);
    } else if (defined(parentCounts)) {
      return traverseHierarchyMultipleParents(
        hierarchy,
        instanceIndex,
        endConditionCallback
      );
    }
    return traverseHierarchySingleParent(
      hierarchy,
      instanceIndex,
      endConditionCallback
    );
  }

  /**
   * Returns whether the feature has this property.
   *
   * @param {Number} batchId the batch ID of the feature
   * @param {String} propertyId The case-sensitive ID of the property.
   * @returns {Boolean} Whether the feature has this property.
   * @private
   */
  BatchTableHierarchy.prototype.hasProperty = function (batchId, propertyId) {
    const result = traverseHierarchy(this, batchId, function (
      hierarchy,
      instanceIndex
    ) {
      const classId = hierarchy._classIds[instanceIndex];
      const instances = hierarchy._classes[classId].instances;
      if (defined(instances[propertyId])) {
        return true;
      }
    });
    return defined(result);
  };

  /**
   * Returns whether any feature has this property.
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @returns {Boolean} Whether any feature has this property.
   * @private
   */
  BatchTableHierarchy.prototype.propertyExists = function (propertyId) {
    const classes = this._classes;
    const classesLength = classes.length;
    for (let i = 0; i < classesLength; ++i) {
      const instances = classes[i].instances;
      if (defined(instances[propertyId])) {
        return true;
      }
    }
    return false;
  };

  /**
   * Returns an array of property IDs.
   *
   * @param {Number} batchId the batch ID of the feature
   * @param {Number} index The index of the entity.
   * @param {String[]} [results] An array into which to store the results.
   * @returns {String[]} The property IDs.
   * @private
   */
  BatchTableHierarchy.prototype.getPropertyIds = function (batchId, results) {
    results = defined(results) ? results : [];
    results.length = 0;

    traverseHierarchy(this, batchId, function (hierarchy, instanceIndex) {
      const classId = hierarchy._classIds[instanceIndex];
      const instances = hierarchy._classes[classId].instances;
      for (const name in instances) {
        if (instances.hasOwnProperty(name)) {
          if (results.indexOf(name) === -1) {
            results.push(name);
          }
        }
      }
    });

    return results;
  };

  /**
   * Returns a copy of the value of the property with the given ID.
   *
   * @param {Number} batchId the batch ID of the feature
   * @param {String} propertyId The case-sensitive ID of the property.
   * @returns {*} The value of the property or <code>undefined</code> if the feature does not have this property.
   * @private
   */
  BatchTableHierarchy.prototype.getProperty = function (batchId, propertyId) {
    return traverseHierarchy(this, batchId, function (hierarchy, instanceIndex) {
      const classId = hierarchy._classIds[instanceIndex];
      const instanceClass = hierarchy._classes[classId];
      const indexInClass = hierarchy._classIndexes[instanceIndex];
      const propertyValues = instanceClass.instances[propertyId];
      if (defined(propertyValues)) {
        if (defined(propertyValues.typedArray)) {
          return getBinaryProperty$1(propertyValues, indexInClass);
        }
        return clone$1(propertyValues[indexInClass], true);
      }
    });
  };

  function getBinaryProperty$1(binaryProperty, index) {
    const typedArray = binaryProperty.typedArray;
    const componentCount = binaryProperty.componentCount;
    if (componentCount === 1) {
      return typedArray[index];
    }
    return binaryProperty.type.unpack(typedArray, index * componentCount);
  }

  /**
   * Sets the value of the property with the given ID. Only properties of the
   * instance may be set; parent properties may not be set.
   *
   * @param {Number} batchId The batchId of the feature
   * @param {String} propertyId The case-sensitive ID of the property.
   * @param {*} value The value of the property that will be copied.
   * @returns {Boolean} <code>true</code> if the property was set, <code>false</code> otherwise.
   *
   * @exception {DeveloperError} when setting an inherited property
   * @private
   */
  BatchTableHierarchy.prototype.setProperty = function (
    batchId,
    propertyId,
    value
  ) {
    const result = traverseHierarchy(this, batchId, function (
      hierarchy,
      instanceIndex
    ) {
      const classId = hierarchy._classIds[instanceIndex];
      const instanceClass = hierarchy._classes[classId];
      const indexInClass = hierarchy._classIndexes[instanceIndex];
      const propertyValues = instanceClass.instances[propertyId];
      if (defined(propertyValues)) {
        //>>includeStart('debug', pragmas.debug);
        if (instanceIndex !== batchId) {
          throw new DeveloperError(
            `Inherited property "${propertyId}" is read-only.`
          );
        }
        //>>includeEnd('debug');
        if (defined(propertyValues.typedArray)) {
          setBinaryProperty$1(propertyValues, indexInClass, value);
        } else {
          propertyValues[indexInClass] = clone$1(value, true);
        }
        return true;
      }
    });
    return defined(result);
  };

  function setBinaryProperty$1(binaryProperty, index, value) {
    const typedArray = binaryProperty.typedArray;
    const componentCount = binaryProperty.componentCount;
    if (componentCount === 1) {
      typedArray[index] = value;
    } else {
      binaryProperty.type.pack(value, typedArray, index * componentCount);
    }
  }

  /**
   * Check if a feature belongs to a class with the given name
   *
   * @param {Number} batchId The batch ID of the feature
   * @param {String} className The name of the class
   * @return {Boolean} <code>true</code> if the feature belongs to the class given by className, or <code>false</code> otherwise
   * @private
   */
  BatchTableHierarchy.prototype.isClass = function (batchId, className) {
    // PERFORMANCE_IDEA : cache results in the ancestor classes to speed up this check if this area becomes a hotspot
    // PERFORMANCE_IDEA : treat class names as integers for faster comparisons
    const result = traverseHierarchy(this, batchId, function (
      hierarchy,
      instanceIndex
    ) {
      const classId = hierarchy._classIds[instanceIndex];
      const instanceClass = hierarchy._classes[classId];
      if (instanceClass.name === className) {
        return true;
      }
    });
    return defined(result);
  };

  /**
   * Get the name of the class a given feature belongs to
   *
   * @param {Number} batchId The batch ID of the feature
   * @return {String} The name of the class this feature belongs to
   */
  BatchTableHierarchy.prototype.getClassName = function (batchId) {
    const classId = this._classIds[batchId];
    const instanceClass = this._classes[classId];
    return instanceClass.name;
  };

  /**
   * Defines how per-feature colors set from the Cesium API or declarative styling blend with the source colors from
   * the original feature, e.g. glTF material or per-point color in the tile.
   * <p>
   * When <code>REPLACE</code> or <code>MIX</code> are used and the source color is a glTF material, the technique must assign the
   * <code>_3DTILESDIFFUSE</code> semantic to the diffuse color parameter. Otherwise only <code>HIGHLIGHT</code> is supported.
   * </p>
   * <p>
   * A feature whose color evaluates to white (1.0, 1.0, 1.0) is always rendered without color blending, regardless of the
   * tileset's color blend mode.
   * </p>
   * <pre><code>
   * "techniques": {
   *   "technique0": {
   *     "parameters": {
   *       "diffuse": {
   *         "semantic": "_3DTILESDIFFUSE",
   *         "type": 35666
   *       }
   *     }
   *   }
   * }
   * </code></pre>
   *
   * @enum {Number}
   */
  const Cesium3DTileColorBlendMode = {
    /**
     * Multiplies the source color by the feature color.
     *
     * @type {Number}
     * @constant
     */
    HIGHLIGHT: 0,

    /**
     * Replaces the source color with the feature color.
     *
     * @type {Number}
     * @constant
     */
    REPLACE: 1,

    /**
     * Blends the source color and feature color together.
     *
     * @type {Number}
     * @constant
     */
    MIX: 2,
  };
  var Cesium3DTileColorBlendMode$1 = Object.freeze(Cesium3DTileColorBlendMode);

  const DEFAULT_COLOR_VALUE$3 = BatchTexture.DEFAULT_COLOR_VALUE;
  const DEFAULT_SHOW_VALUE$3 = BatchTexture.DEFAULT_SHOW_VALUE;

  /**
   * @private
   * @constructor
   */
  function Cesium3DTileBatchTable(
    content,
    featuresLength,
    batchTableJson,
    batchTableBinary,
    colorChangedCallback
  ) {
    /**
     * @readonly
     */
    this.featuresLength = featuresLength;

    let extensions;
    if (defined(batchTableJson)) {
      extensions = batchTableJson.extensions;
    }
    this._extensions = defaultValue(extensions, {});

    const properties = initializeProperties(batchTableJson);
    this._properties = properties;

    this._batchTableHierarchy = initializeHierarchy$1(
      this,
      batchTableJson,
      batchTableBinary
    );

    const binaryProperties = getBinaryProperties(
      featuresLength,
      properties,
      batchTableBinary
    );
    this._binaryPropertiesByteLength = countBinaryPropertyMemory(
      binaryProperties
    );
    this._batchTableBinaryProperties = binaryProperties;

    this._content = content;

    this._batchTexture = new BatchTexture({
      featuresLength: featuresLength,
      colorChangedCallback: colorChangedCallback,
      owner: content,
      statistics: content.tileset.statistics,
    });
  }

  // This can be overridden for testing purposes
  Cesium3DTileBatchTable._deprecationWarning = deprecationWarning;

  Object.defineProperties(Cesium3DTileBatchTable.prototype, {
    /**
     * Size of the batch table, including the batch table hierarchy's binary
     * buffers and any binary properties. JSON data is not counted.
     *
     * @memberof Cesium3DTileBatchTable.prototype
     * @type {Number}
     * @readonly
     * @private
     */
    batchTableByteLength: {
      get: function () {
        let totalByteLength = this._binaryPropertiesByteLength;

        if (defined(this._batchTableHierarchy)) {
          totalByteLength += this._batchTableHierarchy.byteLength;
        }

        totalByteLength += this._batchTexture.byteLength;

        return totalByteLength;
      },
    },
  });

  function initializeProperties(jsonHeader) {
    const properties = {};

    if (!defined(jsonHeader)) {
      return properties;
    }

    for (const propertyName in jsonHeader) {
      if (
        jsonHeader.hasOwnProperty(propertyName) &&
        propertyName !== "HIERARCHY" && // Deprecated HIERARCHY property
        propertyName !== "extensions" &&
        propertyName !== "extras"
      ) {
        properties[propertyName] = clone$1(jsonHeader[propertyName], true);
      }
    }

    return properties;
  }

  function initializeHierarchy$1(batchTable, jsonHeader, binaryBody) {
    if (!defined(jsonHeader)) {
      return;
    }

    let hierarchy = batchTable._extensions["3DTILES_batch_table_hierarchy"];

    const legacyHierarchy = jsonHeader.HIERARCHY;
    if (defined(legacyHierarchy)) {
      Cesium3DTileBatchTable._deprecationWarning(
        "batchTableHierarchyExtension",
        "The batch table HIERARCHY property has been moved to an extension. Use extensions.3DTILES_batch_table_hierarchy instead."
      );
      batchTable._extensions["3DTILES_batch_table_hierarchy"] = legacyHierarchy;
      hierarchy = legacyHierarchy;
    }

    if (!defined(hierarchy)) {
      return;
    }

    return new BatchTableHierarchy({
      extension: hierarchy,
      binaryBody: binaryBody,
    });
  }

  function getBinaryProperties(featuresLength, properties, binaryBody) {
    let binaryProperties;
    for (const name in properties) {
      if (properties.hasOwnProperty(name)) {
        const property = properties[name];
        const byteOffset = property.byteOffset;
        if (defined(byteOffset)) {
          // This is a binary property
          const componentType = property.componentType;
          const type = property.type;
          if (!defined(componentType)) {
            throw new RuntimeError("componentType is required.");
          }
          if (!defined(type)) {
            throw new RuntimeError("type is required.");
          }
          if (!defined(binaryBody)) {
            throw new RuntimeError(
              `Property ${name} requires a batch table binary.`
            );
          }

          const binaryAccessor = getBinaryAccessor(property);
          const componentCount = binaryAccessor.componentsPerAttribute;
          const classType = binaryAccessor.classType;
          const typedArray = binaryAccessor.createArrayBufferView(
            binaryBody.buffer,
            binaryBody.byteOffset + byteOffset,
            featuresLength
          );

          if (!defined(binaryProperties)) {
            binaryProperties = {};
          }

          // Store any information needed to access the binary data, including the typed array,
          // componentCount (e.g. a VEC4 would be 4), and the type used to pack and unpack (e.g. Cartesian4).
          binaryProperties[name] = {
            typedArray: typedArray,
            componentCount: componentCount,
            type: classType,
          };
        }
      }
    }
    return binaryProperties;
  }

  function countBinaryPropertyMemory(binaryProperties) {
    if (!defined(binaryProperties)) {
      return 0;
    }

    let byteLength = 0;
    for (const name in binaryProperties) {
      if (binaryProperties.hasOwnProperty(name)) {
        byteLength += binaryProperties[name].typedArray.byteLength;
      }
    }
    return byteLength;
  }

  Cesium3DTileBatchTable.getBinaryProperties = function (
    featuresLength,
    batchTableJson,
    batchTableBinary
  ) {
    return getBinaryProperties(featuresLength, batchTableJson, batchTableBinary);
  };

  Cesium3DTileBatchTable.prototype.setShow = function (batchId, show) {
    this._batchTexture.setShow(batchId, show);
  };

  Cesium3DTileBatchTable.prototype.setAllShow = function (show) {
    this._batchTexture.setAllShow(show);
  };

  Cesium3DTileBatchTable.prototype.getShow = function (batchId) {
    return this._batchTexture.getShow(batchId);
  };

  Cesium3DTileBatchTable.prototype.setColor = function (batchId, color) {
    this._batchTexture.setColor(batchId, color);
  };

  Cesium3DTileBatchTable.prototype.setAllColor = function (color) {
    this._batchTexture.setAllColor(color);
  };

  Cesium3DTileBatchTable.prototype.getColor = function (batchId, result) {
    return this._batchTexture.getColor(batchId, result);
  };

  Cesium3DTileBatchTable.prototype.getPickColor = function (batchId) {
    return this._batchTexture.getPickColor(batchId);
  };

  const scratchColor$n = new Color();

  Cesium3DTileBatchTable.prototype.applyStyle = function (style) {
    if (!defined(style)) {
      this.setAllColor(DEFAULT_COLOR_VALUE$3);
      this.setAllShow(DEFAULT_SHOW_VALUE$3);
      return;
    }

    const content = this._content;
    const length = this.featuresLength;
    for (let i = 0; i < length; ++i) {
      const feature = content.getFeature(i);
      const color = defined(style.color)
        ? defaultValue(
            style.color.evaluateColor(feature, scratchColor$n),
            DEFAULT_COLOR_VALUE$3
          )
        : DEFAULT_COLOR_VALUE$3;
      const show = defined(style.show)
        ? defaultValue(style.show.evaluate(feature), DEFAULT_SHOW_VALUE$3)
        : DEFAULT_SHOW_VALUE$3;
      this.setColor(i, color);
      this.setShow(i, show);
    }
  };

  function getBinaryProperty(binaryProperty, index) {
    const typedArray = binaryProperty.typedArray;
    const componentCount = binaryProperty.componentCount;
    if (componentCount === 1) {
      return typedArray[index];
    }
    return binaryProperty.type.unpack(typedArray, index * componentCount);
  }

  function setBinaryProperty(binaryProperty, index, value) {
    const typedArray = binaryProperty.typedArray;
    const componentCount = binaryProperty.componentCount;
    if (componentCount === 1) {
      typedArray[index] = value;
    } else {
      binaryProperty.type.pack(value, typedArray, index * componentCount);
    }
  }

  function checkBatchId(batchId, featuresLength) {
    if (!defined(batchId) || batchId < 0 || batchId >= featuresLength) {
      throw new DeveloperError(
        `batchId is required and between zero and featuresLength - 1 (${featuresLength}` -
          +")."
      );
    }
  }

  Cesium3DTileBatchTable.prototype.isClass = function (batchId, className) {
    //>>includeStart('debug', pragmas.debug);
    checkBatchId(batchId, this.featuresLength);
    Check.typeOf.string("className", className);
    //>>includeEnd('debug');

    const hierarchy = this._batchTableHierarchy;
    if (!defined(hierarchy)) {
      return false;
    }

    return hierarchy.isClass(batchId, className);
  };

  Cesium3DTileBatchTable.prototype.isExactClass = function (batchId, className) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("className", className);
    //>>includeEnd('debug');

    return this.getExactClassName(batchId) === className;
  };

  Cesium3DTileBatchTable.prototype.getExactClassName = function (batchId) {
    //>>includeStart('debug', pragmas.debug);
    checkBatchId(batchId, this.featuresLength);
    //>>includeEnd('debug');

    const hierarchy = this._batchTableHierarchy;
    if (!defined(hierarchy)) {
      return undefined;
    }

    return hierarchy.getClassName(batchId);
  };

  Cesium3DTileBatchTable.prototype.hasProperty = function (batchId, name) {
    //>>includeStart('debug', pragmas.debug);
    checkBatchId(batchId, this.featuresLength);
    Check.typeOf.string("name", name);
    //>>includeEnd('debug');

    return (
      defined(this._properties[name]) ||
      (defined(this._batchTableHierarchy) &&
        this._batchTableHierarchy.hasProperty(batchId, name))
    );
  };

  /**
   * @private
   */
  Cesium3DTileBatchTable.prototype.hasPropertyBySemantic = function () {
    // Cesium 3D Tiles 1.0 formats do not have semantics
    return false;
  };

  Cesium3DTileBatchTable.prototype.getPropertyIds = function (batchId, results) {
    //>>includeStart('debug', pragmas.debug);
    checkBatchId(batchId, this.featuresLength);
    //>>includeEnd('debug');

    results = defined(results) ? results : [];
    results.length = 0;

    const scratchPropertyIds = Object.keys(this._properties);
    results.push.apply(results, scratchPropertyIds);

    if (defined(this._batchTableHierarchy)) {
      results.push.apply(
        results,
        this._batchTableHierarchy.getPropertyIds(batchId, scratchPropertyIds)
      );
    }

    return results;
  };

  /**
   * @private
   */
  Cesium3DTileBatchTable.prototype.getPropertyBySemantic = function (
    batchId,
    name
  ) {
    // Cesium 3D Tiles 1.0 formats do not have semantics
    return undefined;
  };

  Cesium3DTileBatchTable.prototype.getProperty = function (batchId, name) {
    //>>includeStart('debug', pragmas.debug);
    checkBatchId(batchId, this.featuresLength);
    Check.typeOf.string("name", name);
    //>>includeEnd('debug');

    if (defined(this._batchTableBinaryProperties)) {
      const binaryProperty = this._batchTableBinaryProperties[name];
      if (defined(binaryProperty)) {
        return getBinaryProperty(binaryProperty, batchId);
      }
    }

    const propertyValues = this._properties[name];
    if (defined(propertyValues)) {
      return clone$1(propertyValues[batchId], true);
    }

    if (defined(this._batchTableHierarchy)) {
      const hierarchyProperty = this._batchTableHierarchy.getProperty(
        batchId,
        name
      );
      if (defined(hierarchyProperty)) {
        return hierarchyProperty;
      }
    }

    return undefined;
  };

  Cesium3DTileBatchTable.prototype.setProperty = function (batchId, name, value) {
    const featuresLength = this.featuresLength;
    //>>includeStart('debug', pragmas.debug);
    checkBatchId(batchId, featuresLength);
    Check.typeOf.string("name", name);
    //>>includeEnd('debug');

    if (defined(this._batchTableBinaryProperties)) {
      const binaryProperty = this._batchTableBinaryProperties[name];
      if (defined(binaryProperty)) {
        setBinaryProperty(binaryProperty, batchId, value);
        return;
      }
    }

    if (defined(this._batchTableHierarchy)) {
      if (this._batchTableHierarchy.setProperty(batchId, name, value)) {
        return;
      }
    }

    let propertyValues = this._properties[name];
    if (!defined(propertyValues)) {
      // Property does not exist. Create it.
      this._properties[name] = new Array(featuresLength);
      propertyValues = this._properties[name];
    }

    propertyValues[batchId] = clone$1(value, true);
  };

  function getGlslComputeSt(batchTable) {
    // GLSL batchId is zero-based: [0, featuresLength - 1]
    if (batchTable._batchTexture.textureDimensions.y === 1) {
      return (
        "uniform vec4 tile_textureStep; \n" +
        "vec2 computeSt(float batchId) \n" +
        "{ \n" +
        "    float stepX = tile_textureStep.x; \n" +
        "    float centerX = tile_textureStep.y; \n" +
        "    return vec2(centerX + (batchId * stepX), 0.5); \n" +
        "} \n"
      );
    }

    return (
      "uniform vec4 tile_textureStep; \n" +
      "uniform vec2 tile_textureDimensions; \n" +
      "vec2 computeSt(float batchId) \n" +
      "{ \n" +
      "    float stepX = tile_textureStep.x; \n" +
      "    float centerX = tile_textureStep.y; \n" +
      "    float stepY = tile_textureStep.z; \n" +
      "    float centerY = tile_textureStep.w; \n" +
      "    float xId = mod(batchId, tile_textureDimensions.x); \n" +
      "    float yId = floor(batchId / tile_textureDimensions.x); \n" +
      "    return vec2(centerX + (xId * stepX), centerY + (yId * stepY)); \n" +
      "} \n"
    );
  }

  Cesium3DTileBatchTable.prototype.getVertexShaderCallback = function (
    handleTranslucent,
    batchIdAttributeName,
    diffuseAttributeOrUniformName
  ) {
    if (this.featuresLength === 0) {
      return;
    }

    const that = this;
    return function (source) {
      // If the color blend mode is HIGHLIGHT, the highlight color will always be applied in the fragment shader.
      // No need to apply the highlight color in the vertex shader as well.
      const renamedSource = modifyDiffuse(
        source,
        diffuseAttributeOrUniformName,
        false
      );
      let newMain;

      if (ContextLimits.maximumVertexTextureImageUnits > 0) {
        // When VTF is supported, perform per-feature show/hide in the vertex shader
        newMain = "";
        if (handleTranslucent) {
          newMain += "uniform bool tile_translucentCommand; \n";
        }
        newMain +=
          `${
          "uniform sampler2D tile_batchTexture; \n" +
          "varying vec4 tile_featureColor; \n" +
          "varying vec2 tile_featureSt; \n" +
          "void main() \n" +
          "{ \n" +
          "    vec2 st = computeSt("
        }${batchIdAttributeName}); \n` +
          `    vec4 featureProperties = texture2D(tile_batchTexture, st); \n` +
          `    tile_color(featureProperties); \n` +
          `    float show = ceil(featureProperties.a); \n` + // 0 - false, non-zeo - true
          `    gl_Position *= show; \n`; // Per-feature show/hide
        if (handleTranslucent) {
          newMain +=
            "    bool isStyleTranslucent = (featureProperties.a != 1.0); \n" +
            "    if (czm_pass == czm_passTranslucent) \n" +
            "    { \n" +
            "        if (!isStyleTranslucent && !tile_translucentCommand) \n" + // Do not render opaque features in the translucent pass
            "        { \n" +
            "            gl_Position *= 0.0; \n" +
            "        } \n" +
            "    } \n" +
            "    else \n" +
            "    { \n" +
            "        if (isStyleTranslucent) \n" + // Do not render translucent features in the opaque pass
            "        { \n" +
            "            gl_Position *= 0.0; \n" +
            "        } \n" +
            "    } \n";
        }
        newMain +=
          "    tile_featureColor = featureProperties; \n" +
          "    tile_featureSt = st; \n" +
          "}";
      } else {
        // When VTF is not supported, color blend mode MIX will look incorrect due to the feature's color not being available in the vertex shader
        newMain =
          `${
          "varying vec2 tile_featureSt; \n" +
          "void main() \n" +
          "{ \n" +
          "    tile_color(vec4(1.0)); \n" +
          "    tile_featureSt = computeSt("
        }${batchIdAttributeName}); \n` + `}`;
      }

      return `${renamedSource}\n${getGlslComputeSt(that)}${newMain}`;
    };
  };

  function getDefaultShader(source, applyHighlight) {
    source = ShaderSource.replaceMain(source, "tile_main");

    if (!applyHighlight) {
      return (
        `${source}void tile_color(vec4 tile_featureColor) \n` +
        `{ \n` +
        `    tile_main(); \n` +
        `} \n`
      );
    }

    // The color blend mode is intended for the RGB channels so alpha is always just multiplied.
    // gl_FragColor is multiplied by the tile color only when tile_colorBlend is 0.0 (highlight)
    return (
      `${source}uniform float tile_colorBlend; \n` +
      `void tile_color(vec4 tile_featureColor) \n` +
      `{ \n` +
      `    tile_main(); \n` +
      `    tile_featureColor = czm_gammaCorrect(tile_featureColor); \n` +
      `    gl_FragColor.a *= tile_featureColor.a; \n` +
      `    float highlight = ceil(tile_colorBlend); \n` +
      `    gl_FragColor.rgb *= mix(tile_featureColor.rgb, vec3(1.0), highlight); \n` +
      `} \n`
    );
  }

  function replaceDiffuseTextureCalls(source, diffuseAttributeOrUniformName) {
    const functionCall = `texture2D(${diffuseAttributeOrUniformName}`;

    let fromIndex = 0;
    let startIndex = source.indexOf(functionCall, fromIndex);
    let endIndex;

    while (startIndex > -1) {
      let nestedLevel = 0;
      for (let i = startIndex; i < source.length; ++i) {
        const character = source.charAt(i);
        if (character === "(") {
          ++nestedLevel;
        } else if (character === ")") {
          --nestedLevel;
          if (nestedLevel === 0) {
            endIndex = i + 1;
            break;
          }
        }
      }
      const extractedFunction = source.slice(startIndex, endIndex);
      const replacedFunction = `tile_diffuse_final(${extractedFunction}, tile_diffuse)`;

      source =
        source.slice(0, startIndex) + replacedFunction + source.slice(endIndex);
      fromIndex = startIndex + replacedFunction.length;
      startIndex = source.indexOf(functionCall, fromIndex);
    }

    return source;
  }

  function modifyDiffuse(source, diffuseAttributeOrUniformName, applyHighlight) {
    // If the glTF does not specify the _3DTILESDIFFUSE semantic, return the default shader.
    // Otherwise if _3DTILESDIFFUSE is defined prefer the shader below that can switch the color mode at runtime.
    if (!defined(diffuseAttributeOrUniformName)) {
      return getDefaultShader(source, applyHighlight);
    }

    // Find the diffuse uniform. Examples matches:
    //   uniform vec3 u_diffuseColor;
    //   uniform sampler2D diffuseTexture;
    let regex = new RegExp(
      `(uniform|attribute|in)\\s+(vec[34]|sampler2D)\\s+${diffuseAttributeOrUniformName};`
    );
    const uniformMatch = source.match(regex);

    if (!defined(uniformMatch)) {
      // Could not find uniform declaration of type vec3, vec4, or sampler2D
      return getDefaultShader(source, applyHighlight);
    }

    const declaration = uniformMatch[0];
    const type = uniformMatch[2];

    source = ShaderSource.replaceMain(source, "tile_main");
    source = source.replace(declaration, ""); // Remove uniform declaration for now so the replace below doesn't affect it

    // If the tile color is white, use the source color. This implies the feature has not been styled.
    // Highlight: tile_colorBlend is 0.0 and the source color is used
    // Replace: tile_colorBlend is 1.0 and the tile color is used
    // Mix: tile_colorBlend is between 0.0 and 1.0, causing the source color and tile color to mix
    const finalDiffuseFunction =
      "bool isWhite(vec3 color) \n" +
      "{ \n" +
      "    return all(greaterThan(color, vec3(1.0 - czm_epsilon3))); \n" +
      "} \n" +
      "vec4 tile_diffuse_final(vec4 sourceDiffuse, vec4 tileDiffuse) \n" +
      "{ \n" +
      "    vec4 blendDiffuse = mix(sourceDiffuse, tileDiffuse, tile_colorBlend); \n" +
      "    vec4 diffuse = isWhite(tileDiffuse.rgb) ? sourceDiffuse : blendDiffuse; \n" +
      "    return vec4(diffuse.rgb, sourceDiffuse.a); \n" +
      "} \n";

    // The color blend mode is intended for the RGB channels so alpha is always just multiplied.
    // gl_FragColor is multiplied by the tile color only when tile_colorBlend is 0.0 (highlight)
    const highlight =
      "    tile_featureColor = czm_gammaCorrect(tile_featureColor); \n" +
      "    gl_FragColor.a *= tile_featureColor.a; \n" +
      "    float highlight = ceil(tile_colorBlend); \n" +
      "    gl_FragColor.rgb *= mix(tile_featureColor.rgb, vec3(1.0), highlight); \n";

    let setColor;
    if (type === "vec3" || type === "vec4") {
      const sourceDiffuse =
        type === "vec3"
          ? `vec4(${diffuseAttributeOrUniformName}, 1.0)`
          : diffuseAttributeOrUniformName;
      const replaceDiffuse =
        type === "vec3" ? "tile_diffuse.xyz" : "tile_diffuse";
      regex = new RegExp(diffuseAttributeOrUniformName, "g");
      source = source.replace(regex, replaceDiffuse);
      setColor =
        `    vec4 source = ${sourceDiffuse}; \n` +
        `    tile_diffuse = tile_diffuse_final(source, tile_featureColor); \n` +
        `    tile_main(); \n`;
    } else if (type === "sampler2D") {
      // Handles any number of nested parentheses
      // E.g. texture2D(u_diffuse, uv)
      // E.g. texture2D(u_diffuse, computeUV(index))
      source = replaceDiffuseTextureCalls(source, diffuseAttributeOrUniformName);
      setColor =
        "    tile_diffuse = tile_featureColor; \n" + "    tile_main(); \n";
    }

    source =
      `${
      "uniform float tile_colorBlend; \n" + "vec4 tile_diffuse = vec4(1.0); \n"
    }${finalDiffuseFunction}${declaration}\n${source}\n` +
      `void tile_color(vec4 tile_featureColor) \n` +
      `{ \n${setColor}`;

    if (applyHighlight) {
      source += highlight;
    }

    source += "} \n";
    return source;
  }

  Cesium3DTileBatchTable.prototype.getFragmentShaderCallback = function (
    handleTranslucent,
    diffuseAttributeOrUniformName,
    hasPremultipliedAlpha
  ) {
    if (this.featuresLength === 0) {
      return;
    }
    return function (source) {
      source = modifyDiffuse(source, diffuseAttributeOrUniformName, true);
      if (ContextLimits.maximumVertexTextureImageUnits > 0) {
        // When VTF is supported, per-feature show/hide already happened in the fragment shader
        source +=
          "uniform sampler2D tile_pickTexture; \n" +
          "varying vec2 tile_featureSt; \n" +
          "varying vec4 tile_featureColor; \n" +
          "void main() \n" +
          "{ \n" +
          "    tile_color(tile_featureColor); \n";

        if (hasPremultipliedAlpha) {
          source += "    gl_FragColor.rgb *= gl_FragColor.a; \n";
        }

        source += "}";
      } else {
        if (handleTranslucent) {
          source += "uniform bool tile_translucentCommand; \n";
        }
        source +=
          "uniform sampler2D tile_pickTexture; \n" +
          "uniform sampler2D tile_batchTexture; \n" +
          "varying vec2 tile_featureSt; \n" +
          "void main() \n" +
          "{ \n" +
          "    vec4 featureProperties = texture2D(tile_batchTexture, tile_featureSt); \n" +
          "    if (featureProperties.a == 0.0) { \n" + // show: alpha == 0 - false, non-zeo - true
          "        discard; \n" +
          "    } \n";

        if (handleTranslucent) {
          source +=
            "    bool isStyleTranslucent = (featureProperties.a != 1.0); \n" +
            "    if (czm_pass == czm_passTranslucent) \n" +
            "    { \n" +
            "        if (!isStyleTranslucent && !tile_translucentCommand) \n" + // Do not render opaque features in the translucent pass
            "        { \n" +
            "            discard; \n" +
            "        } \n" +
            "    } \n" +
            "    else \n" +
            "    { \n" +
            "        if (isStyleTranslucent) \n" + // Do not render translucent features in the opaque pass
            "        { \n" +
            "            discard; \n" +
            "        } \n" +
            "    } \n";
        }

        source += "    tile_color(featureProperties); \n";

        if (hasPremultipliedAlpha) {
          source += "    gl_FragColor.rgb *= gl_FragColor.a; \n";
        }

        source += "} \n";
      }
      return source;
    };
  };

  Cesium3DTileBatchTable.prototype.getClassificationFragmentShaderCallback = function () {
    if (this.featuresLength === 0) {
      return;
    }
    return function (source) {
      source = ShaderSource.replaceMain(source, "tile_main");
      if (ContextLimits.maximumVertexTextureImageUnits > 0) {
        // When VTF is supported, per-feature show/hide already happened in the fragment shader
        source +=
          "uniform sampler2D tile_pickTexture;\n" +
          "varying vec2 tile_featureSt; \n" +
          "varying vec4 tile_featureColor; \n" +
          "void main() \n" +
          "{ \n" +
          "    tile_main(); \n" +
          "    gl_FragColor = tile_featureColor; \n" +
          "    gl_FragColor.rgb *= gl_FragColor.a; \n" +
          "}";
      } else {
        source +=
          "uniform sampler2D tile_batchTexture; \n" +
          "uniform sampler2D tile_pickTexture;\n" +
          "varying vec2 tile_featureSt; \n" +
          "void main() \n" +
          "{ \n" +
          "    tile_main(); \n" +
          "    vec4 featureProperties = texture2D(tile_batchTexture, tile_featureSt); \n" +
          "    if (featureProperties.a == 0.0) { \n" + // show: alpha == 0 - false, non-zeo - true
          "        discard; \n" +
          "    } \n" +
          "    gl_FragColor = featureProperties; \n" +
          "    gl_FragColor.rgb *= gl_FragColor.a; \n" +
          "} \n";
      }
      return source;
    };
  };

  function getColorBlend(batchTable) {
    const tileset = batchTable._content.tileset;
    const colorBlendMode = tileset.colorBlendMode;
    const colorBlendAmount = tileset.colorBlendAmount;
    if (colorBlendMode === Cesium3DTileColorBlendMode$1.HIGHLIGHT) {
      return 0.0;
    }
    if (colorBlendMode === Cesium3DTileColorBlendMode$1.REPLACE) {
      return 1.0;
    }
    if (colorBlendMode === Cesium3DTileColorBlendMode$1.MIX) {
      // The value 0.0 is reserved for highlight, so clamp to just above 0.0.
      return CesiumMath.clamp(colorBlendAmount, CesiumMath.EPSILON4, 1.0);
    }
    //>>includeStart('debug', pragmas.debug);
    throw new DeveloperError(`Invalid color blend mode "${colorBlendMode}".`);
    //>>includeEnd('debug');
  }

  Cesium3DTileBatchTable.prototype.getUniformMapCallback = function () {
    if (this.featuresLength === 0) {
      return;
    }

    const that = this;
    return function (uniformMap) {
      const batchUniformMap = {
        tile_batchTexture: function () {
          // PERFORMANCE_IDEA: we could also use a custom shader that avoids the texture read.
          return defaultValue(
            that._batchTexture.batchTexture,
            that._batchTexture.defaultTexture
          );
        },
        tile_textureDimensions: function () {
          return that._batchTexture.textureDimensions;
        },
        tile_textureStep: function () {
          return that._batchTexture.textureStep;
        },
        tile_colorBlend: function () {
          return getColorBlend(that);
        },
        tile_pickTexture: function () {
          return that._batchTexture.pickTexture;
        },
      };

      return combine$2(uniformMap, batchUniformMap);
    };
  };

  Cesium3DTileBatchTable.prototype.getPickId = function () {
    return "texture2D(tile_pickTexture, tile_featureSt)";
  };

  ///////////////////////////////////////////////////////////////////////////

  const StyleCommandsNeeded$2 = {
    ALL_OPAQUE: 0,
    ALL_TRANSLUCENT: 1,
    OPAQUE_AND_TRANSLUCENT: 2,
  };

  Cesium3DTileBatchTable.prototype.addDerivedCommands = function (
    frameState,
    commandStart
  ) {
    const commandList = frameState.commandList;
    const commandEnd = commandList.length;
    const tile = this._content._tile;
    const finalResolution = tile._finalResolution;
    const tileset = tile.tileset;
    const bivariateVisibilityTest =
      tileset._skipLevelOfDetail &&
      tileset._hasMixedContent &&
      frameState.context.stencilBuffer;
    const styleCommandsNeeded = getStyleCommandsNeeded(this);

    for (let i = commandStart; i < commandEnd; ++i) {
      const command = commandList[i];
      if (command.pass === Pass$1.COMPUTE) {
        continue;
      }

      let derivedCommands = command.derivedCommands.tileset;
      if (!defined(derivedCommands) || command.dirty) {
        derivedCommands = {};
        command.derivedCommands.tileset = derivedCommands;
        derivedCommands.originalCommand = deriveCommand(command);
        command.dirty = false;
      }
      const originalCommand = derivedCommands.originalCommand;

      if (
        styleCommandsNeeded !== StyleCommandsNeeded$2.ALL_OPAQUE &&
        command.pass !== Pass$1.TRANSLUCENT
      ) {
        if (!defined(derivedCommands.translucent)) {
          derivedCommands.translucent = deriveTranslucentCommand$2(originalCommand);
        }
      }

      if (
        styleCommandsNeeded !== StyleCommandsNeeded$2.ALL_TRANSLUCENT &&
        command.pass !== Pass$1.TRANSLUCENT
      ) {
        if (!defined(derivedCommands.opaque)) {
          derivedCommands.opaque = deriveOpaqueCommand(originalCommand);
        }

        if (bivariateVisibilityTest) {
          if (!finalResolution) {
            if (!defined(derivedCommands.zback)) {
              derivedCommands.zback = deriveZBackfaceCommand(
                frameState.context,
                originalCommand
              );
            }
            tileset._backfaceCommands.push(derivedCommands.zback);
          }
          if (
            !defined(derivedCommands.stencil) ||
            tile._selectionDepth !==
              getLastSelectionDepth(derivedCommands.stencil)
          ) {
            if (command.renderState.depthMask) {
              derivedCommands.stencil = deriveStencilCommand(
                originalCommand,
                tile._selectionDepth
              );
            } else {
              // Ignore if tile does not write depth
              derivedCommands.stencil = derivedCommands.opaque;
            }
          }
        }
      }

      const opaqueCommand = bivariateVisibilityTest
        ? derivedCommands.stencil
        : derivedCommands.opaque;
      const translucentCommand = derivedCommands.translucent;

      // If the command was originally opaque:
      //    * If the styling applied to the tile is all opaque, use the opaque command
      //      (with one additional uniform needed for the shader).
      //    * If the styling is all translucent, use new (cached) derived commands (front
      //      and back faces) with a translucent render state.
      //    * If the styling causes both opaque and translucent features in this tile,
      //      then use both sets of commands.
      if (command.pass !== Pass$1.TRANSLUCENT) {
        if (styleCommandsNeeded === StyleCommandsNeeded$2.ALL_OPAQUE) {
          commandList[i] = opaqueCommand;
        }
        if (styleCommandsNeeded === StyleCommandsNeeded$2.ALL_TRANSLUCENT) {
          commandList[i] = translucentCommand;
        }
        if (styleCommandsNeeded === StyleCommandsNeeded$2.OPAQUE_AND_TRANSLUCENT) {
          // PERFORMANCE_IDEA: if the tile has multiple commands, we do not know what features are in what
          // commands so this case may be overkill.
          commandList[i] = opaqueCommand;
          commandList.push(translucentCommand);
        }
      } else {
        // Command was originally translucent so no need to derive new commands;
        // as of now, a style can't change an originally translucent feature to
        // opaque since the style's alpha is modulated, not a replacement.  When
        // this changes, we need to derive new opaque commands here.
        commandList[i] = originalCommand;
      }
    }
  };

  function getStyleCommandsNeeded(batchTable) {
    const translucentFeaturesLength =
      batchTable._batchTexture.translucentFeaturesLength;

    if (translucentFeaturesLength === 0) {
      return StyleCommandsNeeded$2.ALL_OPAQUE;
    } else if (translucentFeaturesLength === batchTable.featuresLength) {
      return StyleCommandsNeeded$2.ALL_TRANSLUCENT;
    }

    return StyleCommandsNeeded$2.OPAQUE_AND_TRANSLUCENT;
  }

  function deriveCommand(command) {
    const derivedCommand = DrawCommand.shallowClone(command);

    // Add a uniform to indicate if the original command was translucent so
    // the shader knows not to cull vertices that were originally transparent
    // even though their style is opaque.
    const translucentCommand = derivedCommand.pass === Pass$1.TRANSLUCENT;

    derivedCommand.uniformMap = defined(derivedCommand.uniformMap)
      ? derivedCommand.uniformMap
      : {};
    derivedCommand.uniformMap.tile_translucentCommand = function () {
      return translucentCommand;
    };

    return derivedCommand;
  }

  function deriveTranslucentCommand$2(command) {
    const derivedCommand = DrawCommand.shallowClone(command);
    derivedCommand.pass = Pass$1.TRANSLUCENT;
    derivedCommand.renderState = getTranslucentRenderState$2(command.renderState);
    return derivedCommand;
  }

  function deriveOpaqueCommand(command) {
    const derivedCommand = DrawCommand.shallowClone(command);
    derivedCommand.renderState = getOpaqueRenderState(command.renderState);
    return derivedCommand;
  }

  function getLogDepthPolygonOffsetFragmentShaderProgram(context, shaderProgram) {
    let shader = context.shaderCache.getDerivedShaderProgram(
      shaderProgram,
      "zBackfaceLogDepth"
    );
    if (!defined(shader)) {
      const fs = shaderProgram.fragmentShaderSource.clone();
      fs.defines = defined(fs.defines) ? fs.defines.slice(0) : [];
      fs.defines.push("POLYGON_OFFSET");

      fs.sources.unshift(
        "#ifdef GL_OES_standard_derivatives\n#extension GL_OES_standard_derivatives : enable\n#endif\n"
      );
      shader = context.shaderCache.createDerivedShaderProgram(
        shaderProgram,
        "zBackfaceLogDepth",
        {
          vertexShaderSource: shaderProgram.vertexShaderSource,
          fragmentShaderSource: fs,
          attributeLocations: shaderProgram._attributeLocations,
        }
      );
    }

    return shader;
  }

  function deriveZBackfaceCommand(context, command) {
    // Write just backface depth of unresolved tiles so resolved stenciled tiles do not appear in front
    const derivedCommand = DrawCommand.shallowClone(command);
    const rs = clone$1(derivedCommand.renderState, true);
    rs.cull.enabled = true;
    rs.cull.face = CullFace$1.FRONT;
    // Back faces do not need to write color.
    rs.colorMask = {
      red: false,
      green: false,
      blue: false,
      alpha: false,
    };
    // Push back face depth away from the camera so it is less likely that back faces and front faces of the same tile
    // intersect and overlap. This helps avoid flickering for very thin double-sided walls.
    rs.polygonOffset = {
      enabled: true,
      factor: 5.0,
      units: 5.0,
    };
    // Set the 3D Tiles bit
    rs.stencilTest = StencilConstants$1.setCesium3DTileBit();
    rs.stencilMask = StencilConstants$1.CESIUM_3D_TILE_MASK;

    derivedCommand.renderState = RenderState.fromCache(rs);
    derivedCommand.castShadows = false;
    derivedCommand.receiveShadows = false;
    derivedCommand.uniformMap = clone$1(command.uniformMap);

    const polygonOffset = new Cartesian2(5.0, 5.0);
    derivedCommand.uniformMap.u_polygonOffset = function () {
      return polygonOffset;
    };

    // Make the log depth depth fragment write account for the polygon offset, too.
    // Otherwise, the back face commands will cause the higher resolution
    // tiles to disappear.
    derivedCommand.shaderProgram = getLogDepthPolygonOffsetFragmentShaderProgram(
      context,
      command.shaderProgram
    );
    return derivedCommand;
  }

  function deriveStencilCommand(command, reference) {
    // Tiles only draw if their selection depth is >= the tile drawn already. They write their
    // selection depth to the stencil buffer to prevent ancestor tiles from drawing on top
    const derivedCommand = DrawCommand.shallowClone(command);
    const rs = clone$1(derivedCommand.renderState, true);
    // Stencil test is masked to the most significant 3 bits so the reference is shifted. Writes 0 for the terrain bit
    rs.stencilTest.enabled = true;
    rs.stencilTest.mask = StencilConstants$1.SKIP_LOD_MASK;
    rs.stencilTest.reference =
      StencilConstants$1.CESIUM_3D_TILE_MASK |
      (reference << StencilConstants$1.SKIP_LOD_BIT_SHIFT);
    rs.stencilTest.frontFunction = StencilFunction$1.GREATER_OR_EQUAL;
    rs.stencilTest.frontOperation.zPass = StencilOperation$1.REPLACE;
    rs.stencilTest.backFunction = StencilFunction$1.GREATER_OR_EQUAL;
    rs.stencilTest.backOperation.zPass = StencilOperation$1.REPLACE;
    rs.stencilMask =
      StencilConstants$1.CESIUM_3D_TILE_MASK | StencilConstants$1.SKIP_LOD_MASK;
    derivedCommand.renderState = RenderState.fromCache(rs);
    return derivedCommand;
  }

  function getLastSelectionDepth(stencilCommand) {
    // Isolate the selection depth from the stencil reference.
    const reference = stencilCommand.renderState.stencilTest.reference;
    return (
      (reference & StencilConstants$1.SKIP_LOD_MASK) >>>
      StencilConstants$1.SKIP_LOD_BIT_SHIFT
    );
  }

  function getTranslucentRenderState$2(renderState) {
    const rs = clone$1(renderState, true);
    rs.cull.enabled = false;
    rs.depthTest.enabled = true;
    rs.depthMask = false;
    rs.blending = BlendingState$1.ALPHA_BLEND;
    rs.stencilTest = StencilConstants$1.setCesium3DTileBit();
    rs.stencilMask = StencilConstants$1.CESIUM_3D_TILE_MASK;

    return RenderState.fromCache(rs);
  }

  function getOpaqueRenderState(renderState) {
    const rs = clone$1(renderState, true);
    rs.stencilTest = StencilConstants$1.setCesium3DTileBit();
    rs.stencilMask = StencilConstants$1.CESIUM_3D_TILE_MASK;

    return RenderState.fromCache(rs);
  }

  Cesium3DTileBatchTable.prototype.update = function (tileset, frameState) {
    this._batchTexture.update(tileset, frameState);
  };

  Cesium3DTileBatchTable.prototype.isDestroyed = function () {
    return false;
  };

  Cesium3DTileBatchTable.prototype.destroy = function () {
    this._batchTexture = this._batchTexture && this._batchTexture.destroy();
    return destroyObject(this);
  };

  /**
   * A feature of a {@link Cesium3DTileset}.
   * <p>
   * Provides access to a feature's properties stored in the tile's batch table, as well
   * as the ability to show/hide a feature and change its highlight color via
   * {@link Cesium3DTileFeature#show} and {@link Cesium3DTileFeature#color}, respectively.
   * </p>
   * <p>
   * Modifications to a <code>Cesium3DTileFeature</code> object have the lifetime of the tile's
   * content.  If the tile's content is unloaded, e.g., due to it going out of view and needing
   * to free space in the cache for visible tiles, listen to the {@link Cesium3DTileset#tileUnload} event to save any
   * modifications. Also listen to the {@link Cesium3DTileset#tileVisible} event to reapply any modifications.
   * </p>
   * <p>
   * Do not construct this directly.  Access it through {@link Cesium3DTileContent#getFeature}
   * or picking using {@link Scene#pick}.
   * </p>
   *
   * @alias Cesium3DTileFeature
   * @constructor
   *
   * @example
   * // On mouse over, display all the properties for a feature in the console log.
   * handler.setInputAction(function(movement) {
   *     const feature = scene.pick(movement.endPosition);
   *     if (feature instanceof Cesium.Cesium3DTileFeature) {
   *         const propertyIds = feature.getPropertyIds();
   *         const length = propertyIds.length;
   *         for (let i = 0; i < length; ++i) {
   *             const propertyId = propertyIds[i];
   *             console.log(`{propertyId}: ${feature.getProperty(propertyId)}`);
   *         }
   *     }
   * }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
   */
  function Cesium3DTileFeature(content, batchId) {
    this._content = content;
    this._batchId = batchId;
    this._color = undefined; // for calling getColor
  }

  Object.defineProperties(Cesium3DTileFeature.prototype, {
    /**
     * Gets or sets if the feature will be shown. This is set for all features
     * when a style's show is evaluated.
     *
     * @memberof Cesium3DTileFeature.prototype
     *
     * @type {Boolean}
     *
     * @default true
     */
    show: {
      get: function () {
        return this._content.batchTable.getShow(this._batchId);
      },
      set: function (value) {
        this._content.batchTable.setShow(this._batchId, value);
      },
    },

    /**
     * Gets or sets the highlight color multiplied with the feature's color.  When
     * this is white, the feature's color is not changed. This is set for all features
     * when a style's color is evaluated.
     *
     * @memberof Cesium3DTileFeature.prototype
     *
     * @type {Color}
     *
     * @default {@link Color.WHITE}
     */
    color: {
      get: function () {
        if (!defined(this._color)) {
          this._color = new Color();
        }
        return this._content.batchTable.getColor(this._batchId, this._color);
      },
      set: function (value) {
        this._content.batchTable.setColor(this._batchId, value);
      },
    },

    /**
     * Gets a typed array containing the ECEF positions of the polyline.
     * Returns undefined if {@link Cesium3DTileset#vectorKeepDecodedPositions} is false
     * or the feature is not a polyline in a vector tile.
     *
     * @memberof Cesium3DTileFeature.prototype
     *
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     *
     * @type {Float64Array}
     */
    polylinePositions: {
      get: function () {
        if (!defined(this._content.getPolylinePositions)) {
          return undefined;
        }

        return this._content.getPolylinePositions(this._batchId);
      },
    },

    /**
     * Gets the content of the tile containing the feature.
     *
     * @memberof Cesium3DTileFeature.prototype
     *
     * @type {Cesium3DTileContent}
     *
     * @readonly
     * @private
     */
    content: {
      get: function () {
        return this._content;
      },
    },

    /**
     * Gets the tileset containing the feature.
     *
     * @memberof Cesium3DTileFeature.prototype
     *
     * @type {Cesium3DTileset}
     *
     * @readonly
     */
    tileset: {
      get: function () {
        return this._content.tileset;
      },
    },

    /**
     * All objects returned by {@link Scene#pick} have a <code>primitive</code> property. This returns
     * the tileset containing the feature.
     *
     * @memberof Cesium3DTileFeature.prototype
     *
     * @type {Cesium3DTileset}
     *
     * @readonly
     */
    primitive: {
      get: function () {
        return this._content.tileset;
      },
    },

    /**
     * Get the feature ID associated with this feature. For 3D Tiles 1.0, the
     * batch ID is returned. For EXT_mesh_features, this is the feature ID from
     * the selected feature ID set.
     *
     * @memberof Cesium3DTileFeature.prototype
     *
     * @type {Number}
     *
     * @readonly
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     */
    featureId: {
      get: function () {
        return this._batchId;
      },
    },

    /**
     * @private
     */
    pickId: {
      get: function () {
        return this._content.batchTable.getPickColor(this._batchId);
      },
    },
  });

  /**
   * Returns whether the feature contains this property. This includes properties from this feature's
   * class and inherited classes when using a batch table hierarchy.
   *
   * @see {@link https://github.com/CesiumGS/3d-tiles/tree/main/extensions/3DTILES_batch_table_hierarchy}
   *
   * @param {String} name The case-sensitive name of the property.
   * @returns {Boolean} Whether the feature contains this property.
   */
  Cesium3DTileFeature.prototype.hasProperty = function (name) {
    return this._content.batchTable.hasProperty(this._batchId, name);
  };

  /**
   * Returns an array of property names for the feature. This includes properties from this feature's
   * class and inherited classes when using a batch table hierarchy.
   *
   * @see {@link https://github.com/CesiumGS/3d-tiles/tree/main/extensions/3DTILES_batch_table_hierarchy}
   *
   * @deprecated
   *
   * @param {String[]} [results] An array into which to store the results.
   * @returns {String[]} The names of the feature's properties.
   */
  Cesium3DTileFeature.prototype.getPropertyNames = function (results) {
    deprecationWarning(
      "Cesium3DTileFeature.getPropertyNames",
      "Cesium3DTileFeature.getPropertyNames was deprecated in CesiumJS 1.95 and will be removed in 1.98. Use Cesium3DTileFeature.getPropertyIds instead"
    );
    return this._content.batchTable.getPropertyIds(this._batchId, results);
  };

  /**
   * Returns an array of property IDs for the feature. This includes properties from this feature's
   * class and inherited classes when using a batch table hierarchy.
   *
   * @see {@link https://github.com/CesiumGS/3d-tiles/tree/main/extensions/3DTILES_batch_table_hierarchy}
   *
   * @param {String[]} [results] An array into which to store the results.
   * @returns {String[]} The IDs of the feature's properties.
   */
  Cesium3DTileFeature.prototype.getPropertyIds = function (results) {
    return this._content.batchTable.getPropertyIds(this._batchId, results);
  };

  /**
   * Returns a copy of the value of the feature's property with the given name. This includes properties from this feature's
   * class and inherited classes when using a batch table hierarchy.
   *
   * @see {@link https://github.com/CesiumGS/3d-tiles/tree/main/extensions/3DTILES_batch_table_hierarchy}
   *
   * @param {String} name The case-sensitive name of the property.
   * @returns {*} The value of the property or <code>undefined</code> if the feature does not have this property.
   *
   * @example
   * // Display all the properties for a feature in the console log.
   * const propertyIds = feature.getPropertyIds();
   * const length = propertyIds.length;
   * for (let i = 0; i < length; ++i) {
   *     const propertyId = propertyIds[i];
   *     console.log(`{propertyId}: ${feature.getProperty(propertyId)}`);
   * }
   */
  Cesium3DTileFeature.prototype.getProperty = function (name) {
    return this._content.batchTable.getProperty(this._batchId, name);
  };

  /**
   * Returns a copy of the feature's property with the given name, examining all
   * the metadata from 3D Tiles 1.0 formats, the EXT_structural_metadata and legacy
   * EXT_feature_metadata glTF extensions, and the metadata present either in the
   * tileset JSON (3D Tiles 1.1) or in the 3DTILES_metadata 3D Tiles extension.
   * Metadata is checked against name from most specific to most general and the
   * first match is returned. Metadata is checked in this order:
   *
   * <ol>
   *   <li>Batch table (structural metadata) property by semantic</li>
   *   <li>Batch table (structural metadata) property by property ID</li>
   *   <li>Content metadata property by semantic</li>
   *   <li>Content metadata property by property</li>
   *   <li>Tile metadata property by semantic</li>
   *   <li>Tile metadata property by property ID</li>
   *   <li>Subtree metadata property by semantic</li>
   *   <li>Subtree metadata property by property ID</li>
   *   <li>Group metadata property by semantic</li>
   *   <li>Group metadata property by property ID</li>
   *   <li>Tileset metadata property by semantic</li>
   *   <li>Tileset metadata property by property ID</li>
   *   <li>Otherwise, return undefined</li>
   * </ol>
   * <p>
   * For 3D Tiles Next details, see the {@link https://github.com/CesiumGS/3d-tiles/tree/main/extensions/3DTILES_metadata|3DTILES_metadata Extension}
   * for 3D Tiles, as well as the {@link https://github.com/CesiumGS/glTF/tree/3d-tiles-next/extensions/2.0/Vendor/EXT_structural_metadata|EXT_structural_metadata Extension}
   * for glTF. For the legacy glTF extension, see {@link https://github.com/CesiumGS/glTF/tree/3d-tiles-next/extensions/2.0/Vendor/EXT_feature_metadata|EXT_feature_metadata Extension}
   * </p>
   *
   * @param {Cesium3DTileContent} content The content for accessing the metadata
   * @param {Number} batchId The batch ID (or feature ID) of the feature to get a property for
   * @param {String} name The semantic or property ID of the feature. Semantics are checked before property IDs in each granularity of metadata.
   * @return {*} The value of the property or <code>undefined</code> if the feature does not have this property.
   *
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  Cesium3DTileFeature.getPropertyInherited = function (content, batchId, name) {
    const batchTable = content.batchTable;
    if (defined(batchTable)) {
      if (batchTable.hasPropertyBySemantic(batchId, name)) {
        return batchTable.getPropertyBySemantic(batchId, name);
      }

      if (batchTable.hasProperty(batchId, name)) {
        return batchTable.getProperty(batchId, name);
      }
    }

    const contentMetadata = content.metadata;
    if (defined(contentMetadata)) {
      if (contentMetadata.hasPropertyBySemantic(name)) {
        return contentMetadata.getPropertyBySemantic(name);
      }

      if (contentMetadata.hasProperty(name)) {
        return contentMetadata.getProperty(name);
      }
    }

    const tile = content.tile;
    const tileMetadata = tile.metadata;
    if (defined(tileMetadata)) {
      if (tileMetadata.hasPropertyBySemantic(name)) {
        return tileMetadata.getPropertyBySemantic(name);
      }

      if (tileMetadata.hasProperty(name)) {
        return tileMetadata.getProperty(name);
      }
    }

    let subtreeMetadata;
    if (defined(tile.implicitSubtree)) {
      subtreeMetadata = tile.implicitSubtree.metadata;
    }

    if (defined(subtreeMetadata)) {
      if (subtreeMetadata.hasPropertyBySemantic(name)) {
        return subtreeMetadata.getPropertyBySemantic(name);
      }

      if (subtreeMetadata.hasProperty(name)) {
        return subtreeMetadata.getProperty(name);
      }
    }

    const groupMetadata = defined(content.group)
      ? content.group.metadata
      : undefined;
    if (defined(groupMetadata)) {
      if (groupMetadata.hasPropertyBySemantic(name)) {
        return groupMetadata.getPropertyBySemantic(name);
      }

      if (groupMetadata.hasProperty(name)) {
        return groupMetadata.getProperty(name);
      }
    }

    const tilesetMetadata = content.tileset.metadata;
    if (defined(tilesetMetadata)) {
      if (tilesetMetadata.hasPropertyBySemantic(name)) {
        return tilesetMetadata.getPropertyBySemantic(name);
      }

      if (tilesetMetadata.hasProperty(name)) {
        return tilesetMetadata.getProperty(name);
      }
    }

    return undefined;
  };

  /**
   * Returns a copy of the value of the feature's property with the given name.
   * If the feature is contained within a tileset that has metadata (3D Tiles 1.1)
   * or uses the <code>3DTILES_metadata</code> extension, tileset, group and tile
   * metadata is inherited.
   * <p>
   * To resolve name conflicts, this method resolves names from most specific to
   * least specific by metadata granularity in the order: feature, tile, group,
   * tileset. Within each granularity, semantics are resolved first, then other
   * properties.
   * </p>
   * @param {String} name The case-sensitive name of the property.
   * @returns {*} The value of the property or <code>undefined</code> if the feature does not have this property.
   * @private
   */
  Cesium3DTileFeature.prototype.getPropertyInherited = function (name) {
    return Cesium3DTileFeature.getPropertyInherited(
      this._content,
      this._batchId,
      name
    );
  };

  /**
   * Sets the value of the feature's property with the given name.
   * <p>
   * If a property with the given name doesn't exist, it is created.
   * </p>
   *
   * @param {String} name The case-sensitive name of the property.
   * @param {*} value The value of the property that will be copied.
   *
   * @exception {DeveloperError} Inherited batch table hierarchy property is read only.
   *
   * @example
   * const height = feature.getProperty('Height'); // e.g., the height of a building
   *
   * @example
   * const name = 'clicked';
   * if (feature.getProperty(name)) {
   *     console.log('already clicked');
   * } else {
   *     feature.setProperty(name, true);
   *     console.log('first click');
   * }
   */
  Cesium3DTileFeature.prototype.setProperty = function (name, value) {
    this._content.batchTable.setProperty(this._batchId, name, value);

    // PERFORMANCE_IDEA: Probably overkill, but maybe only mark the tile dirty if the
    // property is in one of the style's expressions or - if it can be done quickly -
    // if the new property value changed the result of an expression.
    this._content.featurePropertiesDirty = true;
  };

  /**
   * Returns whether the feature's class name equals <code>className</code>. Unlike {@link Cesium3DTileFeature#isClass}
   * this function only checks the feature's exact class and not inherited classes.
   * <p>
   * This function returns <code>false</code> if no batch table hierarchy is present.
   * </p>
   *
   * @param {String} className The name to check against.
   * @returns {Boolean} Whether the feature's class name equals <code>className</code>
   *
   * @private
   */
  Cesium3DTileFeature.prototype.isExactClass = function (className) {
    return this._content.batchTable.isExactClass(this._batchId, className);
  };

  /**
   * Returns whether the feature's class or any inherited classes are named <code>className</code>.
   * <p>
   * This function returns <code>false</code> if no batch table hierarchy is present.
   * </p>
   *
   * @param {String} className The name to check against.
   * @returns {Boolean} Whether the feature's class or inherited classes are named <code>className</code>
   *
   * @private
   */
  Cesium3DTileFeature.prototype.isClass = function (className) {
    return this._content.batchTable.isClass(this._batchId, className);
  };

  /**
   * Returns the feature's class name.
   * <p>
   * This function returns <code>undefined</code> if no batch table hierarchy is present.
   * </p>
   *
   * @returns {String} The feature's class name.
   *
   * @private
   */
  Cesium3DTileFeature.prototype.getExactClassName = function () {
    return this._content.batchTable.getExactClassName(this._batchId);
  };

  /**
   * @private
   */
  function Cesium3DTileFeatureTable(featureTableJson, featureTableBinary) {
    this.json = featureTableJson;
    this.buffer = featureTableBinary;
    this._cachedTypedArrays = {};
    this.featuresLength = 0;
  }

  function getTypedArrayFromBinary(
    featureTable,
    semantic,
    componentType,
    componentLength,
    count,
    byteOffset
  ) {
    const cachedTypedArrays = featureTable._cachedTypedArrays;
    let typedArray = cachedTypedArrays[semantic];
    if (!defined(typedArray)) {
      typedArray = ComponentDatatype$1.createArrayBufferView(
        componentType,
        featureTable.buffer.buffer,
        featureTable.buffer.byteOffset + byteOffset,
        count * componentLength
      );
      cachedTypedArrays[semantic] = typedArray;
    }
    return typedArray;
  }

  function getTypedArrayFromArray(featureTable, semantic, componentType, array) {
    const cachedTypedArrays = featureTable._cachedTypedArrays;
    let typedArray = cachedTypedArrays[semantic];
    if (!defined(typedArray)) {
      typedArray = ComponentDatatype$1.createTypedArray(componentType, array);
      cachedTypedArrays[semantic] = typedArray;
    }
    return typedArray;
  }

  Cesium3DTileFeatureTable.prototype.getGlobalProperty = function (
    semantic,
    componentType,
    componentLength
  ) {
    const jsonValue = this.json[semantic];
    if (!defined(jsonValue)) {
      return undefined;
    }

    if (defined(jsonValue.byteOffset)) {
      componentType = defaultValue(componentType, ComponentDatatype$1.UNSIGNED_INT);
      componentLength = defaultValue(componentLength, 1);
      return getTypedArrayFromBinary(
        this,
        semantic,
        componentType,
        componentLength,
        1,
        jsonValue.byteOffset
      );
    }

    return jsonValue;
  };

  Cesium3DTileFeatureTable.prototype.hasProperty = function (semantic) {
    return defined(this.json[semantic]);
  };

  Cesium3DTileFeatureTable.prototype.getPropertyArray = function (
    semantic,
    componentType,
    componentLength
  ) {
    const jsonValue = this.json[semantic];
    if (!defined(jsonValue)) {
      return undefined;
    }

    if (defined(jsonValue.byteOffset)) {
      if (defined(jsonValue.componentType)) {
        componentType = ComponentDatatype$1.fromName(jsonValue.componentType);
      }
      return getTypedArrayFromBinary(
        this,
        semantic,
        componentType,
        componentLength,
        this.featuresLength,
        jsonValue.byteOffset
      );
    }

    return getTypedArrayFromArray(this, semantic, componentType, jsonValue);
  };

  Cesium3DTileFeatureTable.prototype.getProperty = function (
    semantic,
    componentType,
    componentLength,
    featureId,
    result
  ) {
    const jsonValue = this.json[semantic];
    if (!defined(jsonValue)) {
      return undefined;
    }

    const typedArray = this.getPropertyArray(
      semantic,
      componentType,
      componentLength
    );

    if (componentLength === 1) {
      return typedArray[featureId];
    }

    for (let i = 0; i < componentLength; ++i) {
      result[i] = typedArray[componentLength * featureId + i];
    }

    return result;
  };

  /**
   * Adds an element to an array and returns the element's index.
   *
   * @param {Array} array The array to add to.
   * @param {Object} element The element to add.
   * @param {Boolean} [checkDuplicates=false] When <code>true</code>, if a duplicate element is found its index is returned and <code>element</code> is not added to the array.
   *
   * @private
   */
  function addToArray(array, element, checkDuplicates) {
    checkDuplicates = defaultValue(checkDuplicates, false);
    if (checkDuplicates) {
      const index = array.indexOf(element);
      if (index > -1) {
        return index;
      }
    }

    array.push(element);
    return array.length - 1;
  }

  /**
   * Checks whether the glTF uses the given extension.
   *
   * @param {Object} gltf A javascript object containing a glTF asset.
   * @param {String} extension The name of the extension.
   * @returns {Boolean} Whether the glTF uses the given extension.
   *
   * @private
   */
  function usesExtension(gltf, extension) {
    return (
      defined(gltf.extensionsUsed) && gltf.extensionsUsed.indexOf(extension) >= 0
    );
  }

  /**
   * Contains traversal functions for processing elements of the glTF hierarchy.
   * @constructor
   *
   * @private
   */
  function ForEach() {}

  /**
   * Fallback for glTF 1.0
   * @private
   */
  ForEach.objectLegacy = function (objects, handler) {
    if (defined(objects)) {
      for (const objectId in objects) {
        if (Object.prototype.hasOwnProperty.call(objects, objectId)) {
          const object = objects[objectId];
          const value = handler(object, objectId);

          if (defined(value)) {
            return value;
          }
        }
      }
    }
  };

  /**
   * @private
   */
  ForEach.object = function (arrayOfObjects, handler) {
    if (defined(arrayOfObjects)) {
      const length = arrayOfObjects.length;
      for (let i = 0; i < length; i++) {
        const object = arrayOfObjects[i];
        const value = handler(object, i);

        if (defined(value)) {
          return value;
        }
      }
    }
  };

  /**
   * Supports glTF 1.0 and 2.0
   * @private
   */
  ForEach.topLevel = function (gltf, name, handler) {
    const gltfProperty = gltf[name];
    if (defined(gltfProperty) && !Array.isArray(gltfProperty)) {
      return ForEach.objectLegacy(gltfProperty, handler);
    }

    return ForEach.object(gltfProperty, handler);
  };

  ForEach.accessor = function (gltf, handler) {
    return ForEach.topLevel(gltf, "accessors", handler);
  };

  ForEach.accessorWithSemantic = function (gltf, semantic, handler) {
    const visited = {};
    return ForEach.mesh(gltf, function (mesh) {
      return ForEach.meshPrimitive(mesh, function (primitive) {
        const valueForEach = ForEach.meshPrimitiveAttribute(
          primitive,
          function (accessorId, attributeSemantic) {
            if (
              attributeSemantic.indexOf(semantic) === 0 &&
              !defined(visited[accessorId])
            ) {
              visited[accessorId] = true;
              const value = handler(accessorId);

              if (defined(value)) {
                return value;
              }
            }
          }
        );

        if (defined(valueForEach)) {
          return valueForEach;
        }

        return ForEach.meshPrimitiveTarget(primitive, function (target) {
          return ForEach.meshPrimitiveTargetAttribute(
            target,
            function (accessorId, attributeSemantic) {
              if (
                attributeSemantic.indexOf(semantic) === 0 &&
                !defined(visited[accessorId])
              ) {
                visited[accessorId] = true;
                const value = handler(accessorId);

                if (defined(value)) {
                  return value;
                }
              }
            }
          );
        });
      });
    });
  };

  ForEach.accessorContainingVertexAttributeData = function (gltf, handler) {
    const visited = {};
    return ForEach.mesh(gltf, function (mesh) {
      return ForEach.meshPrimitive(mesh, function (primitive) {
        const valueForEach = ForEach.meshPrimitiveAttribute(
          primitive,
          function (accessorId) {
            if (!defined(visited[accessorId])) {
              visited[accessorId] = true;
              const value = handler(accessorId);

              if (defined(value)) {
                return value;
              }
            }
          }
        );

        if (defined(valueForEach)) {
          return valueForEach;
        }

        return ForEach.meshPrimitiveTarget(primitive, function (target) {
          return ForEach.meshPrimitiveTargetAttribute(
            target,
            function (accessorId) {
              if (!defined(visited[accessorId])) {
                visited[accessorId] = true;
                const value = handler(accessorId);

                if (defined(value)) {
                  return value;
                }
              }
            }
          );
        });
      });
    });
  };

  ForEach.accessorContainingIndexData = function (gltf, handler) {
    const visited = {};
    return ForEach.mesh(gltf, function (mesh) {
      return ForEach.meshPrimitive(mesh, function (primitive) {
        const indices = primitive.indices;
        if (defined(indices) && !defined(visited[indices])) {
          visited[indices] = true;
          const value = handler(indices);

          if (defined(value)) {
            return value;
          }
        }
      });
    });
  };

  ForEach.animation = function (gltf, handler) {
    return ForEach.topLevel(gltf, "animations", handler);
  };

  ForEach.animationChannel = function (animation, handler) {
    const channels = animation.channels;
    return ForEach.object(channels, handler);
  };

  ForEach.animationSampler = function (animation, handler) {
    const samplers = animation.samplers;
    return ForEach.object(samplers, handler);
  };

  ForEach.buffer = function (gltf, handler) {
    return ForEach.topLevel(gltf, "buffers", handler);
  };

  ForEach.bufferView = function (gltf, handler) {
    return ForEach.topLevel(gltf, "bufferViews", handler);
  };

  ForEach.camera = function (gltf, handler) {
    return ForEach.topLevel(gltf, "cameras", handler);
  };

  ForEach.image = function (gltf, handler) {
    return ForEach.topLevel(gltf, "images", handler);
  };

  ForEach.material = function (gltf, handler) {
    return ForEach.topLevel(gltf, "materials", handler);
  };

  ForEach.materialValue = function (material, handler) {
    let values = material.values;
    if (
      defined(material.extensions) &&
      defined(material.extensions.KHR_techniques_webgl)
    ) {
      values = material.extensions.KHR_techniques_webgl.values;
    }

    for (const name in values) {
      if (Object.prototype.hasOwnProperty.call(values, name)) {
        const value = handler(values[name], name);

        if (defined(value)) {
          return value;
        }
      }
    }
  };

  ForEach.mesh = function (gltf, handler) {
    return ForEach.topLevel(gltf, "meshes", handler);
  };

  ForEach.meshPrimitive = function (mesh, handler) {
    const primitives = mesh.primitives;
    if (defined(primitives)) {
      const primitivesLength = primitives.length;
      for (let i = 0; i < primitivesLength; i++) {
        const primitive = primitives[i];
        const value = handler(primitive, i);

        if (defined(value)) {
          return value;
        }
      }
    }
  };

  ForEach.meshPrimitiveAttribute = function (primitive, handler) {
    const attributes = primitive.attributes;
    for (const semantic in attributes) {
      if (Object.prototype.hasOwnProperty.call(attributes, semantic)) {
        const value = handler(attributes[semantic], semantic);

        if (defined(value)) {
          return value;
        }
      }
    }
  };

  ForEach.meshPrimitiveTarget = function (primitive, handler) {
    const targets = primitive.targets;
    if (defined(targets)) {
      const length = targets.length;
      for (let i = 0; i < length; ++i) {
        const value = handler(targets[i], i);

        if (defined(value)) {
          return value;
        }
      }
    }
  };

  ForEach.meshPrimitiveTargetAttribute = function (target, handler) {
    for (const semantic in target) {
      if (Object.prototype.hasOwnProperty.call(target, semantic)) {
        const accessorId = target[semantic];
        const value = handler(accessorId, semantic);

        if (defined(value)) {
          return value;
        }
      }
    }
  };

  ForEach.node = function (gltf, handler) {
    return ForEach.topLevel(gltf, "nodes", handler);
  };

  ForEach.nodeInTree = function (gltf, nodeIds, handler) {
    const nodes = gltf.nodes;
    if (defined(nodes)) {
      const length = nodeIds.length;
      for (let i = 0; i < length; i++) {
        const nodeId = nodeIds[i];
        const node = nodes[nodeId];
        if (defined(node)) {
          let value = handler(node, nodeId);

          if (defined(value)) {
            return value;
          }

          const children = node.children;
          if (defined(children)) {
            value = ForEach.nodeInTree(gltf, children, handler);

            if (defined(value)) {
              return value;
            }
          }
        }
      }
    }
  };

  ForEach.nodeInScene = function (gltf, scene, handler) {
    const sceneNodeIds = scene.nodes;
    if (defined(sceneNodeIds)) {
      return ForEach.nodeInTree(gltf, sceneNodeIds, handler);
    }
  };

  ForEach.program = function (gltf, handler) {
    if (usesExtension(gltf, "KHR_techniques_webgl")) {
      return ForEach.object(
        gltf.extensions.KHR_techniques_webgl.programs,
        handler
      );
    }

    return ForEach.topLevel(gltf, "programs", handler);
  };

  ForEach.sampler = function (gltf, handler) {
    return ForEach.topLevel(gltf, "samplers", handler);
  };

  ForEach.scene = function (gltf, handler) {
    return ForEach.topLevel(gltf, "scenes", handler);
  };

  ForEach.shader = function (gltf, handler) {
    if (usesExtension(gltf, "KHR_techniques_webgl")) {
      return ForEach.object(
        gltf.extensions.KHR_techniques_webgl.shaders,
        handler
      );
    }

    return ForEach.topLevel(gltf, "shaders", handler);
  };

  ForEach.skin = function (gltf, handler) {
    return ForEach.topLevel(gltf, "skins", handler);
  };

  ForEach.skinJoint = function (skin, handler) {
    const joints = skin.joints;
    if (defined(joints)) {
      const jointsLength = joints.length;
      for (let i = 0; i < jointsLength; i++) {
        const joint = joints[i];
        const value = handler(joint);

        if (defined(value)) {
          return value;
        }
      }
    }
  };

  ForEach.techniqueAttribute = function (technique, handler) {
    const attributes = technique.attributes;
    for (const attributeName in attributes) {
      if (Object.prototype.hasOwnProperty.call(attributes, attributeName)) {
        const value = handler(attributes[attributeName], attributeName);

        if (defined(value)) {
          return value;
        }
      }
    }
  };

  ForEach.techniqueUniform = function (technique, handler) {
    const uniforms = technique.uniforms;
    for (const uniformName in uniforms) {
      if (Object.prototype.hasOwnProperty.call(uniforms, uniformName)) {
        const value = handler(uniforms[uniformName], uniformName);

        if (defined(value)) {
          return value;
        }
      }
    }
  };

  ForEach.techniqueParameter = function (technique, handler) {
    const parameters = technique.parameters;
    for (const parameterName in parameters) {
      if (Object.prototype.hasOwnProperty.call(parameters, parameterName)) {
        const value = handler(parameters[parameterName], parameterName);

        if (defined(value)) {
          return value;
        }
      }
    }
  };

  ForEach.technique = function (gltf, handler) {
    if (usesExtension(gltf, "KHR_techniques_webgl")) {
      return ForEach.object(
        gltf.extensions.KHR_techniques_webgl.techniques,
        handler
      );
    }

    return ForEach.topLevel(gltf, "techniques", handler);
  };

  ForEach.texture = function (gltf, handler) {
    return ForEach.topLevel(gltf, "textures", handler);
  };

  /**
   * Utility function for retrieving the number of components in a given type.
   *
   * @param {String} type glTF type
   * @returns {Number} The number of components in that type.
   *
   * @private
   */
  function numberOfComponentsForType(type) {
    switch (type) {
      case "SCALAR":
        return 1;
      case "VEC2":
        return 2;
      case "VEC3":
        return 3;
      case "VEC4":
      case "MAT2":
        return 4;
      case "MAT3":
        return 9;
      case "MAT4":
        return 16;
    }
  }

  /**
   * Returns the byte stride of the provided accessor.
   * If the byteStride is 0, it is calculated based on type and componentType
   *
   * @param {Object} gltf A javascript object containing a glTF asset.
   * @param {Object} accessor The accessor.
   * @returns {Number} The byte stride of the accessor.
   *
   * @private
   */
  function getAccessorByteStride(gltf, accessor) {
    const bufferViewId = accessor.bufferView;
    if (defined(bufferViewId)) {
      const bufferView = gltf.bufferViews[bufferViewId];
      if (defined(bufferView.byteStride) && bufferView.byteStride > 0) {
        return bufferView.byteStride;
      }
    }
    return (
      ComponentDatatype$1.getSizeInBytes(accessor.componentType) *
      numberOfComponentsForType(accessor.type)
    );
  }

  /**
   * Adds default glTF values if they don't exist.
   *
   * @param {Object} gltf A javascript object containing a glTF asset.
   * @returns {Object} The modified glTF.
   *
   * @private
   */
  function addDefaults(gltf) {
    ForEach.accessor(gltf, function (accessor) {
      if (defined(accessor.bufferView)) {
        accessor.byteOffset = defaultValue(accessor.byteOffset, 0);
      }
    });

    ForEach.bufferView(gltf, function (bufferView) {
      if (defined(bufferView.buffer)) {
        bufferView.byteOffset = defaultValue(bufferView.byteOffset, 0);
      }
    });

    ForEach.mesh(gltf, function (mesh) {
      ForEach.meshPrimitive(mesh, function (primitive) {
        primitive.mode = defaultValue(primitive.mode, WebGLConstants$1.TRIANGLES);
        if (!defined(primitive.material)) {
          if (!defined(gltf.materials)) {
            gltf.materials = [];
          }
          const defaultMaterial = {
            name: "default",
          };
          primitive.material = addToArray(gltf.materials, defaultMaterial);
        }
      });
    });

    ForEach.accessorContainingVertexAttributeData(gltf, function (accessorId) {
      const accessor = gltf.accessors[accessorId];
      const bufferViewId = accessor.bufferView;
      accessor.normalized = defaultValue(accessor.normalized, false);
      if (defined(bufferViewId)) {
        const bufferView = gltf.bufferViews[bufferViewId];
        bufferView.byteStride = getAccessorByteStride(gltf, accessor);
        bufferView.target = WebGLConstants$1.ARRAY_BUFFER;
      }
    });

    ForEach.accessorContainingIndexData(gltf, function (accessorId) {
      const accessor = gltf.accessors[accessorId];
      const bufferViewId = accessor.bufferView;
      if (defined(bufferViewId)) {
        const bufferView = gltf.bufferViews[bufferViewId];
        bufferView.target = WebGLConstants$1.ELEMENT_ARRAY_BUFFER;
      }
    });

    ForEach.material(gltf, function (material) {
      const extensions = defaultValue(
        material.extensions,
        defaultValue.EMPTY_OBJECT
      );
      const materialsCommon = extensions.KHR_materials_common;
      if (defined(materialsCommon)) {
        const technique = materialsCommon.technique;
        const values = defined(materialsCommon.values)
          ? materialsCommon.values
          : {};
        materialsCommon.values = values;

        values.ambient = defined(values.ambient)
          ? values.ambient
          : [0.0, 0.0, 0.0, 1.0];
        values.emission = defined(values.emission)
          ? values.emission
          : [0.0, 0.0, 0.0, 1.0];

        values.transparency = defaultValue(values.transparency, 1.0);
        values.transparent = defaultValue(values.transparent, false);
        values.doubleSided = defaultValue(values.doubleSided, false);

        if (technique !== "CONSTANT") {
          values.diffuse = defined(values.diffuse)
            ? values.diffuse
            : [0.0, 0.0, 0.0, 1.0];
          if (technique !== "LAMBERT") {
            values.specular = defined(values.specular)
              ? values.specular
              : [0.0, 0.0, 0.0, 1.0];
            values.shininess = defaultValue(values.shininess, 0.0);
          }
        }
        return;
      }

      material.emissiveFactor = defaultValue(
        material.emissiveFactor,
        [0.0, 0.0, 0.0]
      );
      material.alphaMode = defaultValue(material.alphaMode, "OPAQUE");
      material.doubleSided = defaultValue(material.doubleSided, false);

      if (material.alphaMode === "MASK") {
        material.alphaCutoff = defaultValue(material.alphaCutoff, 0.5);
      }

      const techniquesExtension = extensions.KHR_techniques_webgl;
      if (defined(techniquesExtension)) {
        ForEach.materialValue(material, function (materialValue) {
          // Check if material value is a TextureInfo object
          if (defined(materialValue.index)) {
            addTextureDefaults(materialValue);
          }
        });
      }

      addTextureDefaults(material.emissiveTexture);
      addTextureDefaults(material.normalTexture);
      addTextureDefaults(material.occlusionTexture);

      const pbrMetallicRoughness = material.pbrMetallicRoughness;
      if (defined(pbrMetallicRoughness)) {
        pbrMetallicRoughness.baseColorFactor = defaultValue(
          pbrMetallicRoughness.baseColorFactor,
          [1.0, 1.0, 1.0, 1.0]
        );
        pbrMetallicRoughness.metallicFactor = defaultValue(
          pbrMetallicRoughness.metallicFactor,
          1.0
        );
        pbrMetallicRoughness.roughnessFactor = defaultValue(
          pbrMetallicRoughness.roughnessFactor,
          1.0
        );
        addTextureDefaults(pbrMetallicRoughness.baseColorTexture);
        addTextureDefaults(pbrMetallicRoughness.metallicRoughnessTexture);
      }

      const pbrSpecularGlossiness =
        extensions.KHR_materials_pbrSpecularGlossiness;
      if (defined(pbrSpecularGlossiness)) {
        pbrSpecularGlossiness.diffuseFactor = defaultValue(
          pbrSpecularGlossiness.diffuseFactor,
          [1.0, 1.0, 1.0, 1.0]
        );
        pbrSpecularGlossiness.specularFactor = defaultValue(
          pbrSpecularGlossiness.specularFactor,
          [1.0, 1.0, 1.0]
        );
        pbrSpecularGlossiness.glossinessFactor = defaultValue(
          pbrSpecularGlossiness.glossinessFactor,
          1.0
        );
        addTextureDefaults(pbrSpecularGlossiness.specularGlossinessTexture);
      }
    });

    ForEach.animation(gltf, function (animation) {
      ForEach.animationSampler(animation, function (sampler) {
        sampler.interpolation = defaultValue(sampler.interpolation, "LINEAR");
      });
    });

    const animatedNodes = getAnimatedNodes(gltf);
    ForEach.node(gltf, function (node, id) {
      const animated = defined(animatedNodes[id]);
      if (
        animated ||
        defined(node.translation) ||
        defined(node.rotation) ||
        defined(node.scale)
      ) {
        node.translation = defaultValue(node.translation, [0.0, 0.0, 0.0]);
        node.rotation = defaultValue(node.rotation, [0.0, 0.0, 0.0, 1.0]);
        node.scale = defaultValue(node.scale, [1.0, 1.0, 1.0]);
      } else {
        node.matrix = defaultValue(
          node.matrix,
          [
            1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0,
            0.0, 1.0,
          ]
        );
      }
    });

    ForEach.sampler(gltf, function (sampler) {
      sampler.wrapS = defaultValue(sampler.wrapS, WebGLConstants$1.REPEAT);
      sampler.wrapT = defaultValue(sampler.wrapT, WebGLConstants$1.REPEAT);
    });

    if (defined(gltf.scenes) && !defined(gltf.scene)) {
      gltf.scene = 0;
    }

    return gltf;
  }

  function getAnimatedNodes(gltf) {
    const nodes = {};
    ForEach.animation(gltf, function (animation) {
      ForEach.animationChannel(animation, function (channel) {
        const target = channel.target;
        const nodeId = target.node;
        const path = target.path;
        // Ignore animations that target 'weights'
        if (path === "translation" || path === "rotation" || path === "scale") {
          nodes[nodeId] = true;
        }
      });
    });
    return nodes;
  }

  function addTextureDefaults(texture) {
    if (defined(texture)) {
      texture.texCoord = defaultValue(texture.texCoord, 0);
    }
  }

  /**
   * Adds extras._pipeline to each object that can have extras in the glTF asset.
   * This stage runs before updateVersion and handles both glTF 1.0 and glTF 2.0 assets.
   *
   * @param {Object} gltf A javascript object containing a glTF asset.
   * @returns {Object} The glTF asset with the added pipeline extras.
   *
   * @private
   */
  function addPipelineExtras(gltf) {
    ForEach.shader(gltf, function (shader) {
      addExtras(shader);
    });
    ForEach.buffer(gltf, function (buffer) {
      addExtras(buffer);
    });
    ForEach.image(gltf, function (image) {
      addExtras(image);
    });

    addExtras(gltf);

    return gltf;
  }

  function addExtras(object) {
    object.extras = defined(object.extras) ? object.extras : {};
    object.extras._pipeline = defined(object.extras._pipeline)
      ? object.extras._pipeline
      : {};
  }

  /**
   * Removes an extension from gltf.extensionsRequired if it is present.
   *
   * @param {Object} gltf A javascript object containing a glTF asset.
   * @param {String} extension The extension to remove.
   *
   * @private
   */
  function removeExtensionsRequired(gltf, extension) {
    const extensionsRequired = gltf.extensionsRequired;
    if (defined(extensionsRequired)) {
      const index = extensionsRequired.indexOf(extension);
      if (index >= 0) {
        extensionsRequired.splice(index, 1);
      }
      if (extensionsRequired.length === 0) {
        delete gltf.extensionsRequired;
      }
    }
  }

  /**
   * Removes an extension from gltf.extensionsUsed and gltf.extensionsRequired if it is present.
   *
   * @param {Object} gltf A javascript object containing a glTF asset.
   * @param {String} extension The extension to remove.
   *
   * @private
   */
  function removeExtensionsUsed(gltf, extension) {
    const extensionsUsed = gltf.extensionsUsed;
    if (defined(extensionsUsed)) {
      const index = extensionsUsed.indexOf(extension);
      if (index >= 0) {
        extensionsUsed.splice(index, 1);
      }
      removeExtensionsRequired(gltf, extension);
      if (extensionsUsed.length === 0) {
        delete gltf.extensionsUsed;
      }
    }
  }

  const sizeOfUint32$5 = 4;

  /**
   * Convert a binary glTF to glTF.
   *
   * The returned glTF has pipeline extras included. The embedded binary data is stored in gltf.buffers[0].extras._pipeline.source.
   *
   * @param {Buffer} glb The glb data to parse.
   * @returns {Object} A javascript object containing a glTF asset with pipeline extras included.
   *
   * @private
   */
  function parseGlb(glb) {
    // Check that the magic string is present
    const magic = getMagic(glb);
    if (magic !== "glTF") {
      throw new RuntimeError("File is not valid binary glTF");
    }

    const header = readHeader(glb, 0, 5);
    const version = header[1];
    if (version !== 1 && version !== 2) {
      throw new RuntimeError("Binary glTF version is not 1 or 2");
    }

    if (version === 1) {
      return parseGlbVersion1(glb, header);
    }

    return parseGlbVersion2(glb, header);
  }

  function readHeader(glb, byteOffset, count) {
    const dataView = new DataView(glb.buffer);
    const header = new Array(count);
    for (let i = 0; i < count; ++i) {
      header[i] = dataView.getUint32(
        glb.byteOffset + byteOffset + i * sizeOfUint32$5,
        true
      );
    }
    return header;
  }

  function parseGlbVersion1(glb, header) {
    const length = header[2];
    const contentLength = header[3];
    const contentFormat = header[4];

    // Check that the content format is 0, indicating that it is JSON
    if (contentFormat !== 0) {
      throw new RuntimeError("Binary glTF scene format is not JSON");
    }

    const jsonStart = 20;
    const binaryStart = jsonStart + contentLength;

    const contentString = getStringFromTypedArray(glb, jsonStart, contentLength);
    const gltf = JSON.parse(contentString);
    addPipelineExtras(gltf);

    const binaryBuffer = glb.subarray(binaryStart, length);

    const buffers = gltf.buffers;
    if (defined(buffers) && Object.keys(buffers).length > 0) {
      // In some older models, the binary glTF buffer is named KHR_binary_glTF
      const binaryGltfBuffer = defaultValue(
        buffers.binary_glTF,
        buffers.KHR_binary_glTF
      );
      if (defined(binaryGltfBuffer)) {
        binaryGltfBuffer.extras._pipeline.source = binaryBuffer;
        delete binaryGltfBuffer.uri;
      }
    }
    // Remove the KHR_binary_glTF extension
    removeExtensionsUsed(gltf, "KHR_binary_glTF");
    return gltf;
  }

  function parseGlbVersion2(glb, header) {
    const length = header[2];
    let byteOffset = 12;
    let gltf;
    let binaryBuffer;
    while (byteOffset < length) {
      const chunkHeader = readHeader(glb, byteOffset, 2);
      const chunkLength = chunkHeader[0];
      const chunkType = chunkHeader[1];
      byteOffset += 8;
      const chunkBuffer = glb.subarray(byteOffset, byteOffset + chunkLength);
      byteOffset += chunkLength;
      // Load JSON chunk
      if (chunkType === 0x4e4f534a) {
        const jsonString = getStringFromTypedArray(chunkBuffer);
        gltf = JSON.parse(jsonString);
        addPipelineExtras(gltf);
      }
      // Load Binary chunk
      else if (chunkType === 0x004e4942) {
        binaryBuffer = chunkBuffer;
      }
    }
    if (defined(gltf) && defined(binaryBuffer)) {
      const buffers = gltf.buffers;
      if (defined(buffers) && buffers.length > 0) {
        const buffer = buffers[0];
        buffer.extras._pipeline.source = binaryBuffer;
      }
    }
    return gltf;
  }

  /**
   * Adds an extension to gltf.extensionsUsed if it does not already exist.
   * Initializes extensionsUsed if it is not defined.
   *
   * @param {Object} gltf A javascript object containing a glTF asset.
   * @param {String} extension The extension to add.
   *
   * @private
   */
  function addExtensionsUsed(gltf, extension) {
    let extensionsUsed = gltf.extensionsUsed;
    if (!defined(extensionsUsed)) {
      extensionsUsed = [];
      gltf.extensionsUsed = extensionsUsed;
    }
    addToArray(extensionsUsed, extension, true);
  }

  /**
   * Returns a function to read and convert data from a DataView into an array.
   *
   * @param {Number} componentType Type to convert the data to.
   * @returns {ComponentReader} Function that reads and converts data.
   *
   * @private
   */
  function getComponentReader(componentType) {
    switch (componentType) {
      case ComponentDatatype$1.BYTE:
        return function (
          dataView,
          byteOffset,
          numberOfComponents,
          componentTypeByteLength,
          result
        ) {
          for (let i = 0; i < numberOfComponents; ++i) {
            result[i] = dataView.getInt8(
              byteOffset + i * componentTypeByteLength
            );
          }
        };
      case ComponentDatatype$1.UNSIGNED_BYTE:
        return function (
          dataView,
          byteOffset,
          numberOfComponents,
          componentTypeByteLength,
          result
        ) {
          for (let i = 0; i < numberOfComponents; ++i) {
            result[i] = dataView.getUint8(
              byteOffset + i * componentTypeByteLength
            );
          }
        };
      case ComponentDatatype$1.SHORT:
        return function (
          dataView,
          byteOffset,
          numberOfComponents,
          componentTypeByteLength,
          result
        ) {
          for (let i = 0; i < numberOfComponents; ++i) {
            result[i] = dataView.getInt16(
              byteOffset + i * componentTypeByteLength,
              true
            );
          }
        };
      case ComponentDatatype$1.UNSIGNED_SHORT:
        return function (
          dataView,
          byteOffset,
          numberOfComponents,
          componentTypeByteLength,
          result
        ) {
          for (let i = 0; i < numberOfComponents; ++i) {
            result[i] = dataView.getUint16(
              byteOffset + i * componentTypeByteLength,
              true
            );
          }
        };
      case ComponentDatatype$1.INT:
        return function (
          dataView,
          byteOffset,
          numberOfComponents,
          componentTypeByteLength,
          result
        ) {
          for (let i = 0; i < numberOfComponents; ++i) {
            result[i] = dataView.getInt32(
              byteOffset + i * componentTypeByteLength,
              true
            );
          }
        };
      case ComponentDatatype$1.UNSIGNED_INT:
        return function (
          dataView,
          byteOffset,
          numberOfComponents,
          componentTypeByteLength,
          result
        ) {
          for (let i = 0; i < numberOfComponents; ++i) {
            result[i] = dataView.getUint32(
              byteOffset + i * componentTypeByteLength,
              true
            );
          }
        };
      case ComponentDatatype$1.FLOAT:
        return function (
          dataView,
          byteOffset,
          numberOfComponents,
          componentTypeByteLength,
          result
        ) {
          for (let i = 0; i < numberOfComponents; ++i) {
            result[i] = dataView.getFloat32(
              byteOffset + i * componentTypeByteLength,
              true
            );
          }
        };
      case ComponentDatatype$1.DOUBLE:
        return function (
          dataView,
          byteOffset,
          numberOfComponents,
          componentTypeByteLength,
          result
        ) {
          for (let i = 0; i < numberOfComponents; ++i) {
            result[i] = dataView.getFloat64(
              byteOffset + i * componentTypeByteLength,
              true
            );
          }
        };
    }
  }

  /**
   * Finds the min and max values of the accessor.
   *
   * @param {Object} gltf A javascript object containing a glTF asset.
   * @param {Object} accessor The accessor object from the glTF asset to read.
   * @returns {{min: Array, max: Array}} min holding the array of minimum values and max holding the array of maximum values.
   *
   * @private
   */
  function findAccessorMinMax(gltf, accessor) {
    const bufferViews = gltf.bufferViews;
    const buffers = gltf.buffers;
    const bufferViewId = accessor.bufferView;
    const numberOfComponents = numberOfComponentsForType(accessor.type);

    // According to the spec, when bufferView is not defined, accessor must be initialized with zeros
    if (!defined(accessor.bufferView)) {
      return {
        min: new Array(numberOfComponents).fill(0.0),
        max: new Array(numberOfComponents).fill(0.0),
      };
    }

    const min = new Array(numberOfComponents).fill(Number.POSITIVE_INFINITY);
    const max = new Array(numberOfComponents).fill(Number.NEGATIVE_INFINITY);

    const bufferView = bufferViews[bufferViewId];
    const bufferId = bufferView.buffer;
    const buffer = buffers[bufferId];
    const source = buffer.extras._pipeline.source;

    const count = accessor.count;
    const byteStride = getAccessorByteStride(gltf, accessor);
    let byteOffset =
      accessor.byteOffset + bufferView.byteOffset + source.byteOffset;
    const componentType = accessor.componentType;
    const componentTypeByteLength =
      ComponentDatatype$1.getSizeInBytes(componentType);
    const dataView = new DataView(source.buffer);
    const components = new Array(numberOfComponents);
    const componentReader = getComponentReader(componentType);

    for (let i = 0; i < count; i++) {
      componentReader(
        dataView,
        byteOffset,
        numberOfComponents,
        componentTypeByteLength,
        components
      );
      for (let j = 0; j < numberOfComponents; j++) {
        const value = components[j];
        min[j] = Math.min(min[j], value);
        max[j] = Math.max(max[j], value);
      }
      byteOffset += byteStride;
    }

    return {
      min: min,
      max: max,
    };
  }

  const defaultBlendEquation = [WebGLConstants$1.FUNC_ADD, WebGLConstants$1.FUNC_ADD];

  const defaultBlendFactors = [
    WebGLConstants$1.ONE,
    WebGLConstants$1.ZERO,
    WebGLConstants$1.ONE,
    WebGLConstants$1.ZERO,
  ];

  function isStateEnabled(renderStates, state) {
    const enabled = renderStates.enable;
    if (!defined(enabled)) {
      return false;
    }

    return enabled.indexOf(state) > -1;
  }

  const supportedBlendFactors = [
    WebGLConstants$1.ZERO,
    WebGLConstants$1.ONE,
    WebGLConstants$1.SRC_COLOR,
    WebGLConstants$1.ONE_MINUS_SRC_COLOR,
    WebGLConstants$1.SRC_ALPHA,
    WebGLConstants$1.ONE_MINUS_SRC_ALPHA,
    WebGLConstants$1.DST_ALPHA,
    WebGLConstants$1.ONE_MINUS_DST_ALPHA,
    WebGLConstants$1.DST_COLOR,
    WebGLConstants$1.ONE_MINUS_DST_COLOR,
  ];

  // If any of the blend factors are not supported, return the default
  function getSupportedBlendFactors(value, defaultValue) {
    if (!defined(value)) {
      return defaultValue;
    }

    for (let i = 0; i < 4; i++) {
      if (supportedBlendFactors.indexOf(value[i]) === -1) {
        return defaultValue;
      }
    }

    return value;
  }

  /**
   * Move glTF 1.0 technique render states to glTF 2.0 materials properties and KHR_blend extension.
   *
   * @param {Object} gltf A javascript object containing a glTF asset.
   * @returns {Object} The updated glTF asset.
   *
   * @private
   */
  function moveTechniqueRenderStates(gltf) {
    const blendingForTechnique = {};
    const materialPropertiesForTechnique = {};
    const techniquesLegacy = gltf.techniques;
    if (!defined(techniquesLegacy)) {
      return gltf;
    }

    ForEach.technique(gltf, function (techniqueLegacy, techniqueIndex) {
      const renderStates = techniqueLegacy.states;
      if (defined(renderStates)) {
        const materialProperties = (materialPropertiesForTechnique[
          techniqueIndex
        ] = {});

        // If BLEND is enabled, the material should have alpha mode BLEND
        if (isStateEnabled(renderStates, WebGLConstants$1.BLEND)) {
          materialProperties.alphaMode = "BLEND";

          const blendFunctions = renderStates.functions;
          if (
            defined(blendFunctions) &&
            (defined(blendFunctions.blendEquationSeparate) ||
              defined(blendFunctions.blendFuncSeparate))
          ) {
            blendingForTechnique[techniqueIndex] = {
              blendEquation: defaultValue(
                blendFunctions.blendEquationSeparate,
                defaultBlendEquation
              ),
              blendFactors: getSupportedBlendFactors(
                blendFunctions.blendFuncSeparate,
                defaultBlendFactors
              ),
            };
          }
        }

        // If CULL_FACE is not enabled, the material should be doubleSided
        if (!isStateEnabled(renderStates, WebGLConstants$1.CULL_FACE)) {
          materialProperties.doubleSided = true;
        }

        delete techniqueLegacy.states;
      }
    });

    if (Object.keys(blendingForTechnique).length > 0) {
      if (!defined(gltf.extensions)) {
        gltf.extensions = {};
      }

      addExtensionsUsed(gltf, "KHR_blend");
    }

    ForEach.material(gltf, function (material) {
      if (defined(material.technique)) {
        const materialProperties =
          materialPropertiesForTechnique[material.technique];
        ForEach.objectLegacy(materialProperties, function (value, property) {
          material[property] = value;
        });

        const blending = blendingForTechnique[material.technique];
        if (defined(blending)) {
          if (!defined(material.extensions)) {
            material.extensions = {};
          }

          material.extensions.KHR_blend = blending;
        }
      }
    });

    return gltf;
  }

  /**
   * Adds an extension to gltf.extensionsRequired if it does not already exist.
   * Initializes extensionsRequired if it is not defined.
   *
   * @param {Object} gltf A javascript object containing a glTF asset.
   * @param {String} extension The extension to add.
   *
   * @private
   */
  function addExtensionsRequired(gltf, extension) {
    let extensionsRequired = gltf.extensionsRequired;
    if (!defined(extensionsRequired)) {
      extensionsRequired = [];
      gltf.extensionsRequired = extensionsRequired;
    }
    addToArray(extensionsRequired, extension, true);
    addExtensionsUsed(gltf, extension);
  }

  /**
   * Move glTF 1.0 material techniques to glTF 2.0 KHR_techniques_webgl extension.
   *
   * @param {Object} gltf A javascript object containing a glTF asset.
   * @returns {Object} The updated glTF asset.
   *
   * @private
   */
  function moveTechniquesToExtension(gltf) {
    const techniquesLegacy = gltf.techniques;
    const mappedUniforms = {};
    const updatedTechniqueIndices = {};
    const seenPrograms = {};
    if (defined(techniquesLegacy)) {
      const extension = {
        programs: [],
        shaders: [],
        techniques: [],
      };

      // Some 1.1 models have a glExtensionsUsed property that can be transferred to program.glExtensions
      const glExtensions = gltf.glExtensionsUsed;
      delete gltf.glExtensionsUsed;

      ForEach.technique(gltf, function (techniqueLegacy, techniqueId) {
        const technique = {
          name: techniqueLegacy.name,
          program: undefined,
          attributes: {},
          uniforms: {},
        };

        let parameterLegacy;
        ForEach.techniqueAttribute(
          techniqueLegacy,
          function (parameterName, attributeName) {
            parameterLegacy = techniqueLegacy.parameters[parameterName];
            technique.attributes[attributeName] = {
              semantic: parameterLegacy.semantic,
            };
          }
        );

        ForEach.techniqueUniform(
          techniqueLegacy,
          function (parameterName, uniformName) {
            parameterLegacy = techniqueLegacy.parameters[parameterName];
            technique.uniforms[uniformName] = {
              count: parameterLegacy.count,
              node: parameterLegacy.node,
              type: parameterLegacy.type,
              semantic: parameterLegacy.semantic,
              value: parameterLegacy.value,
            };

            // Store the name of the uniform to update material values.
            if (!defined(mappedUniforms[techniqueId])) {
              mappedUniforms[techniqueId] = {};
            }
            mappedUniforms[techniqueId][parameterName] = uniformName;
          }
        );

        if (!defined(seenPrograms[techniqueLegacy.program])) {
          const programLegacy = gltf.programs[techniqueLegacy.program];

          const program = {
            name: programLegacy.name,
            fragmentShader: undefined,
            vertexShader: undefined,
            glExtensions: glExtensions,
          };

          const fs = gltf.shaders[programLegacy.fragmentShader];
          program.fragmentShader = addToArray(extension.shaders, fs, true);

          const vs = gltf.shaders[programLegacy.vertexShader];
          program.vertexShader = addToArray(extension.shaders, vs, true);

          technique.program = addToArray(extension.programs, program);
          seenPrograms[techniqueLegacy.program] = technique.program;
        } else {
          technique.program = seenPrograms[techniqueLegacy.program];
        }

        // Store the index of the new technique to reference instead.
        updatedTechniqueIndices[techniqueId] = addToArray(
          extension.techniques,
          technique
        );
      });

      if (extension.techniques.length > 0) {
        if (!defined(gltf.extensions)) {
          gltf.extensions = {};
        }

        gltf.extensions.KHR_techniques_webgl = extension;
        addExtensionsUsed(gltf, "KHR_techniques_webgl");
        addExtensionsRequired(gltf, "KHR_techniques_webgl");
      }
    }

    ForEach.material(gltf, function (material) {
      if (defined(material.technique)) {
        const materialExtension = {
          technique: updatedTechniqueIndices[material.technique],
        };

        ForEach.objectLegacy(material.values, function (value, parameterName) {
          if (!defined(materialExtension.values)) {
            materialExtension.values = {};
          }

          const uniformName = mappedUniforms[material.technique][parameterName];
          materialExtension.values[uniformName] = value;
        });

        if (!defined(material.extensions)) {
          material.extensions = {};
        }

        material.extensions.KHR_techniques_webgl = materialExtension;
      }

      delete material.technique;
      delete material.values;
    });

    delete gltf.techniques;
    delete gltf.programs;
    delete gltf.shaders;

    return gltf;
  }

  /**
   * Calls the provider handler function on each texture used by the material.
   * Mimics the behavior of functions in gltf-pipeline ForEach.
   * @param {Object} material The glTF material.
   * @param {forEachTextureInMaterial~handler} handler Function that is called for each texture in the material.
   *
   * @private
   */
  function forEachTextureInMaterial(material, handler) {
    Check.typeOf.object("material", material);
    Check.defined("handler", handler);

    // Metallic roughness
    const pbrMetallicRoughness = material.pbrMetallicRoughness;
    if (defined(pbrMetallicRoughness)) {
      if (defined(pbrMetallicRoughness.baseColorTexture)) {
        const textureInfo = pbrMetallicRoughness.baseColorTexture;
        const value = handler(textureInfo.index, textureInfo);
        if (defined(value)) {
          return value;
        }
      }
      if (defined(pbrMetallicRoughness.metallicRoughnessTexture)) {
        const textureInfo = pbrMetallicRoughness.metallicRoughnessTexture;
        const value = handler(textureInfo.index, textureInfo);
        if (defined(value)) {
          return value;
        }
      }
    }

    if (defined(material.extensions)) {
      // Spec gloss extension
      const pbrSpecularGlossiness =
        material.extensions.KHR_materials_pbrSpecularGlossiness;
      if (defined(pbrSpecularGlossiness)) {
        if (defined(pbrSpecularGlossiness.diffuseTexture)) {
          const textureInfo = pbrSpecularGlossiness.diffuseTexture;
          const value = handler(textureInfo.index, textureInfo);
          if (defined(value)) {
            return value;
          }
        }
        if (defined(pbrSpecularGlossiness.specularGlossinessTexture)) {
          const textureInfo = pbrSpecularGlossiness.specularGlossinessTexture;
          const value = handler(textureInfo.index, textureInfo);
          if (defined(value)) {
            return value;
          }
        }
      }

      // Materials common extension (may be present in models converted from glTF 1.0)
      const materialsCommon = material.extensions.KHR_materials_common;
      if (defined(materialsCommon)) {
        const diffuse = materialsCommon.values.diffuse;
        const ambient = materialsCommon.values.ambient;
        const emission = materialsCommon.values.emission;
        const specular = materialsCommon.values.specular;
        if (defined(diffuse) && defined(diffuse.index)) {
          const value = handler(diffuse.index, diffuse);
          if (defined(value)) {
            return value;
          }
        }
        if (defined(ambient) && defined(ambient.index)) {
          const value = handler(ambient.index, ambient);
          if (defined(value)) {
            return value;
          }
        }
        if (defined(emission) && defined(emission.index)) {
          const value = handler(emission.index, emission);
          if (defined(value)) {
            return value;
          }
        }
        if (defined(specular) && defined(specular.index)) {
          const value = handler(specular.index, specular);
          if (defined(value)) {
            return value;
          }
        }
      }
    }

    // KHR_techniques_webgl extension
    const value = ForEach.materialValue(material, function (materialValue) {
      if (defined(materialValue.index)) {
        const value = handler(materialValue.index, materialValue);
        if (defined(value)) {
          return value;
        }
      }
    });
    if (defined(value)) {
      return value;
    }

    // Top level textures
    if (defined(material.emissiveTexture)) {
      const textureInfo = material.emissiveTexture;
      const value = handler(textureInfo.index, textureInfo);
      if (defined(value)) {
        return value;
      }
    }

    if (defined(material.normalTexture)) {
      const textureInfo = material.normalTexture;
      const value = handler(textureInfo.index, textureInfo);
      if (defined(value)) {
        return value;
      }
    }

    if (defined(material.occlusionTexture)) {
      const textureInfo = material.occlusionTexture;
      const value = handler(textureInfo.index, textureInfo);
      if (defined(value)) {
        return value;
      }
    }
  }

  const allElementTypes = [
    "mesh",
    "node",
    "material",
    "accessor",
    "bufferView",
    "buffer",
    "texture",
    "sampler",
    "image",
  ];

  /**
   * Removes unused elements from gltf.
   *
   * @param {Object} gltf A javascript object containing a glTF asset.
   * @param {String[]} [elementTypes=['mesh', 'node', 'material', 'accessor', 'bufferView', 'buffer']] Element types to be removed. Needs to be a subset of ['mesh', 'node', 'material', 'accessor', 'bufferView', 'buffer'], other items will be ignored.
   *
   * @private
   */
  function removeUnusedElements(gltf, elementTypes) {
    elementTypes = defaultValue(elementTypes, allElementTypes);
    allElementTypes.forEach(function (type) {
      if (elementTypes.indexOf(type) > -1) {
        removeUnusedElementsByType(gltf, type);
      }
    });
    return gltf;
  }

  const TypeToGltfElementName = {
    accessor: "accessors",
    buffer: "buffers",
    bufferView: "bufferViews",
    image: "images",
    node: "nodes",
    material: "materials",
    mesh: "meshes",
    sampler: "samplers",
    texture: "textures",
  };

  function removeUnusedElementsByType(gltf, type) {
    const name = TypeToGltfElementName[type];
    const arrayOfObjects = gltf[name];

    if (defined(arrayOfObjects)) {
      let removed = 0;
      const usedIds = getListOfElementsIdsInUse[type](gltf);
      const length = arrayOfObjects.length;

      for (let i = 0; i < length; ++i) {
        if (!usedIds[i]) {
          Remove[type](gltf, i - removed);
          removed++;
        }
      }
    }
  }

  /**
   * Contains functions for removing elements from a glTF hierarchy.
   * Since top-level glTF elements are arrays, when something is removed, referring
   * indices need to be updated.
   * @constructor
   *
   * @private
   */
  function Remove() {}

  Remove.accessor = function (gltf, accessorId) {
    const accessors = gltf.accessors;

    accessors.splice(accessorId, 1);

    ForEach.mesh(gltf, function (mesh) {
      ForEach.meshPrimitive(mesh, function (primitive) {
        // Update accessor ids for the primitives.
        ForEach.meshPrimitiveAttribute(
          primitive,
          function (attributeAccessorId, semantic) {
            if (attributeAccessorId > accessorId) {
              primitive.attributes[semantic]--;
            }
          }
        );

        // Update accessor ids for the targets.
        ForEach.meshPrimitiveTarget(primitive, function (target) {
          ForEach.meshPrimitiveTargetAttribute(
            target,
            function (attributeAccessorId, semantic) {
              if (attributeAccessorId > accessorId) {
                target[semantic]--;
              }
            }
          );
        });
        const indices = primitive.indices;
        if (defined(indices) && indices > accessorId) {
          primitive.indices--;
        }
      });
    });

    ForEach.skin(gltf, function (skin) {
      if (
        defined(skin.inverseBindMatrices) &&
        skin.inverseBindMatrices > accessorId
      ) {
        skin.inverseBindMatrices--;
      }
    });

    ForEach.animation(gltf, function (animation) {
      ForEach.animationSampler(animation, function (sampler) {
        if (defined(sampler.input) && sampler.input > accessorId) {
          sampler.input--;
        }
        if (defined(sampler.output) && sampler.output > accessorId) {
          sampler.output--;
        }
      });
    });
  };

  Remove.buffer = function (gltf, bufferId) {
    const buffers = gltf.buffers;

    buffers.splice(bufferId, 1);

    ForEach.bufferView(gltf, function (bufferView) {
      if (defined(bufferView.buffer) && bufferView.buffer > bufferId) {
        bufferView.buffer--;
      }

      if (
        defined(bufferView.extensions) &&
        defined(bufferView.extensions.EXT_meshopt_compression)
      ) {
        bufferView.extensions.EXT_meshopt_compression.buffer--;
      }
    });
  };

  Remove.bufferView = function (gltf, bufferViewId) {
    const bufferViews = gltf.bufferViews;

    bufferViews.splice(bufferViewId, 1);

    ForEach.accessor(gltf, function (accessor) {
      if (defined(accessor.bufferView) && accessor.bufferView > bufferViewId) {
        accessor.bufferView--;
      }
    });

    ForEach.shader(gltf, function (shader) {
      if (defined(shader.bufferView) && shader.bufferView > bufferViewId) {
        shader.bufferView--;
      }
    });

    ForEach.image(gltf, function (image) {
      if (defined(image.bufferView) && image.bufferView > bufferViewId) {
        image.bufferView--;
      }
    });

    if (usesExtension(gltf, "KHR_draco_mesh_compression")) {
      ForEach.mesh(gltf, function (mesh) {
        ForEach.meshPrimitive(mesh, function (primitive) {
          if (
            defined(primitive.extensions) &&
            defined(primitive.extensions.KHR_draco_mesh_compression)
          ) {
            if (
              primitive.extensions.KHR_draco_mesh_compression.bufferView >
              bufferViewId
            ) {
              primitive.extensions.KHR_draco_mesh_compression.bufferView--;
            }
          }
        });
      });
    }

    if (usesExtension(gltf, "EXT_feature_metadata")) {
      const extension = gltf.extensions.EXT_feature_metadata;
      const featureTables = extension.featureTables;
      for (const featureTableId in featureTables) {
        if (featureTables.hasOwnProperty(featureTableId)) {
          const featureTable = featureTables[featureTableId];
          const properties = featureTable.properties;
          if (defined(properties)) {
            for (const propertyId in properties) {
              if (properties.hasOwnProperty(propertyId)) {
                const property = properties[propertyId];
                if (
                  defined(property.bufferView) &&
                  property.bufferView > bufferViewId
                ) {
                  property.bufferView--;
                }
                if (
                  defined(property.arrayOffsetBufferView) &&
                  property.arrayOffsetBufferView > bufferViewId
                ) {
                  property.arrayOffsetBufferView--;
                }
                if (
                  defined(property.stringOffsetBufferView) &&
                  property.stringOffsetBufferView > bufferViewId
                ) {
                  property.stringOffsetBufferView--;
                }
              }
            }
          }
        }
      }
    }
  };

  Remove.image = function (gltf, imageId) {
    const images = gltf.images;
    images.splice(imageId, 1);

    ForEach.texture(gltf, function (texture) {
      if (defined(texture.source)) {
        if (texture.source > imageId) {
          --texture.source;
        }
      }
      const ext = texture.extensions;
      if (
        defined(ext) &&
        defined(ext.EXT_texture_webp) &&
        ext.EXT_texture_webp.source > imageId
      ) {
        --texture.extensions.EXT_texture_webp.source;
      } else if (
        defined(ext) &&
        defined(ext.KHR_texture_basisu) &&
        ext.KHR_texture_basisu.source > imageId
      ) {
        --texture.extensions.KHR_texture_basisu.source;
      }
    });
  };

  Remove.mesh = function (gltf, meshId) {
    const meshes = gltf.meshes;
    meshes.splice(meshId, 1);

    ForEach.node(gltf, function (node) {
      if (defined(node.mesh)) {
        if (node.mesh > meshId) {
          node.mesh--;
        } else if (node.mesh === meshId) {
          // Remove reference to deleted mesh
          delete node.mesh;
        }
      }
    });
  };

  Remove.node = function (gltf, nodeId) {
    const nodes = gltf.nodes;
    nodes.splice(nodeId, 1);

    // Shift all node references
    ForEach.skin(gltf, function (skin) {
      if (defined(skin.skeleton) && skin.skeleton > nodeId) {
        skin.skeleton--;
      }

      skin.joints = skin.joints.map(function (x) {
        return x > nodeId ? x - 1 : x;
      });
    });
    ForEach.animation(gltf, function (animation) {
      ForEach.animationChannel(animation, function (channel) {
        if (
          defined(channel.target) &&
          defined(channel.target.node) &&
          channel.target.node > nodeId
        ) {
          channel.target.node--;
        }
      });
    });
    ForEach.technique(gltf, function (technique) {
      ForEach.techniqueUniform(technique, function (uniform) {
        if (defined(uniform.node) && uniform.node > nodeId) {
          uniform.node--;
        }
      });
    });
    ForEach.node(gltf, function (node) {
      if (!defined(node.children)) {
        return;
      }

      node.children = node.children
        .filter(function (x) {
          return x !== nodeId; // Remove
        })
        .map(function (x) {
          return x > nodeId ? x - 1 : x; // Shift indices
        });
    });
    ForEach.scene(gltf, function (scene) {
      scene.nodes = scene.nodes
        .filter(function (x) {
          return x !== nodeId; // Remove
        })
        .map(function (x) {
          return x > nodeId ? x - 1 : x; // Shift indices
        });
    });
  };

  Remove.material = function (gltf, materialId) {
    const materials = gltf.materials;
    materials.splice(materialId, 1);

    // Shift other material ids
    ForEach.mesh(gltf, function (mesh) {
      ForEach.meshPrimitive(mesh, function (primitive) {
        if (defined(primitive.material) && primitive.material > materialId) {
          primitive.material--;
        }
      });
    });
  };

  Remove.sampler = function (gltf, samplerId) {
    const samplers = gltf.samplers;
    samplers.splice(samplerId, 1);

    ForEach.texture(gltf, function (texture) {
      if (defined(texture.sampler)) {
        if (texture.sampler > samplerId) {
          --texture.sampler;
        }
      }
    });
  };

  Remove.texture = function (gltf, textureId) {
    const textures = gltf.textures;
    textures.splice(textureId, 1);

    ForEach.material(gltf, function (material) {
      forEachTextureInMaterial(material, function (textureIndex, textureInfo) {
        if (textureInfo.index > textureId) {
          --textureInfo.index;
        }
      });
    });

    if (usesExtension(gltf, "EXT_feature_metadata")) {
      ForEach.mesh(gltf, function (mesh) {
        ForEach.meshPrimitive(mesh, function (primitive) {
          const extensions = primitive.extensions;
          if (defined(extensions) && defined(extensions.EXT_feature_metadata)) {
            const extension = extensions.EXT_feature_metadata;
            const featureIdTextures = extension.featureIdTextures;
            if (defined(featureIdTextures)) {
              const featureIdTexturesLength = featureIdTextures.length;
              for (let i = 0; i < featureIdTexturesLength; ++i) {
                const featureIdTexture = featureIdTextures[i];
                const textureInfo = featureIdTexture.featureIds.texture;
                if (textureInfo.index > textureId) {
                  --textureInfo.index;
                }
              }
            }
          }
        });
      });

      const extension = gltf.extensions.EXT_feature_metadata;
      const featureTextures = extension.featureTextures;
      for (const featureTextureId in featureTextures) {
        if (featureTextures.hasOwnProperty(featureTextureId)) {
          const featureTexture = featureTextures[featureTextureId];
          const properties = featureTexture.properties;
          if (defined(properties)) {
            for (const propertyId in properties) {
              if (properties.hasOwnProperty(propertyId)) {
                const property = properties[propertyId];
                const textureInfo = property.texture;
                if (textureInfo.index > textureId) {
                  --textureInfo.index;
                }
              }
            }
          }
        }
      }
    }
  };

  /**
   * Contains functions for getting a list of element ids in use by the glTF asset.
   * @constructor
   *
   * @private
   */
  function getListOfElementsIdsInUse() {}

  getListOfElementsIdsInUse.accessor = function (gltf) {
    // Calculate accessor's that are currently in use.
    const usedAccessorIds = {};

    ForEach.mesh(gltf, function (mesh) {
      ForEach.meshPrimitive(mesh, function (primitive) {
        ForEach.meshPrimitiveAttribute(primitive, function (accessorId) {
          usedAccessorIds[accessorId] = true;
        });
        ForEach.meshPrimitiveTarget(primitive, function (target) {
          ForEach.meshPrimitiveTargetAttribute(target, function (accessorId) {
            usedAccessorIds[accessorId] = true;
          });
        });
        const indices = primitive.indices;
        if (defined(indices)) {
          usedAccessorIds[indices] = true;
        }
      });
    });

    ForEach.skin(gltf, function (skin) {
      if (defined(skin.inverseBindMatrices)) {
        usedAccessorIds[skin.inverseBindMatrices] = true;
      }
    });

    ForEach.animation(gltf, function (animation) {
      ForEach.animationSampler(animation, function (sampler) {
        if (defined(sampler.input)) {
          usedAccessorIds[sampler.input] = true;
        }
        if (defined(sampler.output)) {
          usedAccessorIds[sampler.output] = true;
        }
      });
    });

    if (usesExtension(gltf, "EXT_mesh_gpu_instancing")) {
      ForEach.node(gltf, function (node) {
        if (
          defined(node.extensions) &&
          defined(node.extensions.EXT_mesh_gpu_instancing)
        ) {
          Object.keys(node.extensions.EXT_mesh_gpu_instancing.attributes).forEach(
            function (key) {
              const attributeAccessorId =
                node.extensions.EXT_mesh_gpu_instancing.attributes[key];
              usedAccessorIds[attributeAccessorId] = true;
            }
          );
        }
      });
    }

    return usedAccessorIds;
  };

  getListOfElementsIdsInUse.buffer = function (gltf) {
    // Calculate buffer's that are currently in use.
    const usedBufferIds = {};

    ForEach.bufferView(gltf, function (bufferView) {
      if (defined(bufferView.buffer)) {
        usedBufferIds[bufferView.buffer] = true;
      }
      if (
        defined(bufferView.extensions) &&
        defined(bufferView.extensions.EXT_meshopt_compression)
      ) {
        usedBufferIds[
          bufferView.extensions.EXT_meshopt_compression.buffer
        ] = true;
      }
    });

    return usedBufferIds;
  };

  getListOfElementsIdsInUse.bufferView = function (gltf) {
    // Calculate bufferView's that are currently in use.
    const usedBufferViewIds = {};

    ForEach.accessor(gltf, function (accessor) {
      if (defined(accessor.bufferView)) {
        usedBufferViewIds[accessor.bufferView] = true;
      }
    });

    ForEach.shader(gltf, function (shader) {
      if (defined(shader.bufferView)) {
        usedBufferViewIds[shader.bufferView] = true;
      }
    });

    ForEach.image(gltf, function (image) {
      if (defined(image.bufferView)) {
        usedBufferViewIds[image.bufferView] = true;
      }
    });

    if (usesExtension(gltf, "KHR_draco_mesh_compression")) {
      ForEach.mesh(gltf, function (mesh) {
        ForEach.meshPrimitive(mesh, function (primitive) {
          if (
            defined(primitive.extensions) &&
            defined(primitive.extensions.KHR_draco_mesh_compression)
          ) {
            usedBufferViewIds[
              primitive.extensions.KHR_draco_mesh_compression.bufferView
            ] = true;
          }
        });
      });
    }

    if (usesExtension(gltf, "EXT_feature_metadata")) {
      const extension = gltf.extensions.EXT_feature_metadata;
      const featureTables = extension.featureTables;
      for (const featureTableId in featureTables) {
        if (featureTables.hasOwnProperty(featureTableId)) {
          const featureTable = featureTables[featureTableId];
          const properties = featureTable.properties;
          if (defined(properties)) {
            for (const propertyId in properties) {
              if (properties.hasOwnProperty(propertyId)) {
                const property = properties[propertyId];
                if (defined(property.bufferView)) {
                  usedBufferViewIds[property.bufferView] = true;
                }
                if (defined(property.arrayOffsetBufferView)) {
                  usedBufferViewIds[property.arrayOffsetBufferView] = true;
                }
                if (defined(property.stringOffsetBufferView)) {
                  usedBufferViewIds[property.stringOffsetBufferView] = true;
                }
              }
            }
          }
        }
      }
    }

    return usedBufferViewIds;
  };

  getListOfElementsIdsInUse.image = function (gltf) {
    const usedImageIds = {};

    ForEach.texture(gltf, function (texture) {
      if (defined(texture.source)) {
        usedImageIds[texture.source] = true;
      }

      if (
        defined(texture.extensions) &&
        defined(texture.extensions.EXT_texture_webp)
      ) {
        usedImageIds[texture.extensions.EXT_texture_webp.source] = true;
      } else if (
        defined(texture.extensions) &&
        defined(texture.extensions.KHR_texture_basisu)
      ) {
        usedImageIds[texture.extensions.KHR_texture_basisu.source] = true;
      }
    });
    return usedImageIds;
  };

  getListOfElementsIdsInUse.mesh = function (gltf) {
    const usedMeshIds = {};
    ForEach.node(gltf, function (node) {
      if (defined(node.mesh && defined(gltf.meshes))) {
        const mesh = gltf.meshes[node.mesh];
        if (
          defined(mesh) &&
          defined(mesh.primitives) &&
          mesh.primitives.length > 0
        ) {
          usedMeshIds[node.mesh] = true;
        }
      }
    });

    return usedMeshIds;
  };

  // Check if node is empty. It is considered empty if neither referencing
  // mesh, camera, extensions and has no children
  function nodeIsEmpty(gltf, nodeId, usedNodeIds) {
    const node = gltf.nodes[nodeId];
    if (
      defined(node.mesh) ||
      defined(node.camera) ||
      defined(node.skin) ||
      defined(node.weights) ||
      defined(node.extras) ||
      (defined(node.extensions) && Object.keys(node.extensions).length !== 0) ||
      defined(usedNodeIds[nodeId])
    ) {
      return false;
    }

    // Empty if no children or children are all empty nodes
    return (
      !defined(node.children) ||
      node.children.filter(function (n) {
        return !nodeIsEmpty(gltf, n, usedNodeIds);
      }).length === 0
    );
  }

  getListOfElementsIdsInUse.node = function (gltf) {
    const usedNodeIds = {};
    ForEach.skin(gltf, function (skin) {
      if (defined(skin.skeleton)) {
        usedNodeIds[skin.skeleton] = true;
      }

      ForEach.skinJoint(skin, function (joint) {
        usedNodeIds[joint] = true;
      });
    });
    ForEach.animation(gltf, function (animation) {
      ForEach.animationChannel(animation, function (channel) {
        if (defined(channel.target) && defined(channel.target.node)) {
          usedNodeIds[channel.target.node] = true;
        }
      });
    });
    ForEach.technique(gltf, function (technique) {
      ForEach.techniqueUniform(technique, function (uniform) {
        if (defined(uniform.node)) {
          usedNodeIds[uniform.node] = true;
        }
      });
    });
    ForEach.node(gltf, function (node, nodeId) {
      if (!nodeIsEmpty(gltf, nodeId, usedNodeIds)) {
        usedNodeIds[nodeId] = true;
      }
    });

    return usedNodeIds;
  };

  getListOfElementsIdsInUse.material = function (gltf) {
    const usedMaterialIds = {};

    ForEach.mesh(gltf, function (mesh) {
      ForEach.meshPrimitive(mesh, function (primitive) {
        if (defined(primitive.material)) {
          usedMaterialIds[primitive.material] = true;
        }
      });
    });

    return usedMaterialIds;
  };

  getListOfElementsIdsInUse.texture = function (gltf) {
    const usedTextureIds = {};

    ForEach.material(gltf, function (material) {
      forEachTextureInMaterial(material, function (textureId) {
        usedTextureIds[textureId] = true;
      });
    });

    if (usesExtension(gltf, "EXT_feature_metadata")) {
      ForEach.mesh(gltf, function (mesh) {
        ForEach.meshPrimitive(mesh, function (primitive) {
          const extensions = primitive.extensions;
          if (defined(extensions) && defined(extensions.EXT_feature_metadata)) {
            const extension = extensions.EXT_feature_metadata;
            const featureIdTextures = extension.featureIdTextures;
            if (defined(featureIdTextures)) {
              const featureIdTexturesLength = featureIdTextures.length;
              for (let i = 0; i < featureIdTexturesLength; ++i) {
                const featureIdTexture = featureIdTextures[i];
                const textureInfo = featureIdTexture.featureIds.texture;
                usedTextureIds[textureInfo.index] = true;
              }
            }
          }
        });
      });

      const extension = gltf.extensions.EXT_feature_metadata;
      const featureTextures = extension.featureTextures;
      for (const featureTextureId in featureTextures) {
        if (featureTextures.hasOwnProperty(featureTextureId)) {
          const featureTexture = featureTextures[featureTextureId];
          const properties = featureTexture.properties;
          if (defined(properties)) {
            for (const propertyId in properties) {
              if (properties.hasOwnProperty(propertyId)) {
                const property = properties[propertyId];
                const textureInfo = property.texture;
                usedTextureIds[textureInfo.index] = true;
              }
            }
          }
        }
      }
    }

    return usedTextureIds;
  };

  getListOfElementsIdsInUse.sampler = function (gltf) {
    const usedSamplerIds = {};

    ForEach.texture(gltf, function (texture) {
      if (defined(texture.sampler)) {
        usedSamplerIds[texture.sampler] = true;
      }
    });

    return usedSamplerIds;
  };

  /**
   * Adds buffer to gltf.
   *
   * @param {Object} gltf A javascript object containing a glTF asset.
   * @param {Buffer} buffer A Buffer object which will be added to gltf.buffers.
   * @returns {Number} The bufferView id of the newly added bufferView.
   *
   * @private
   */
  function addBuffer(gltf, buffer) {
    const newBuffer = {
      byteLength: buffer.length,
      extras: {
        _pipeline: {
          source: buffer,
        },
      },
    };
    const bufferId = addToArray(gltf.buffers, newBuffer);
    const bufferView = {
      buffer: bufferId,
      byteOffset: 0,
      byteLength: buffer.length,
    };
    return addToArray(gltf.bufferViews, bufferView);
  }

  /**
   * Returns the accessor data in a contiguous array.
   *
   * @param {Object} gltf A javascript object containing a glTF asset.
   * @param {Object} accessor The accessor.
   * @returns {Array} The accessor values in a contiguous array.
   *
   * @private
   */
  function readAccessorPacked(gltf, accessor) {
    const byteStride = getAccessorByteStride(gltf, accessor);
    const componentTypeByteLength = ComponentDatatype$1.getSizeInBytes(
      accessor.componentType
    );
    const numberOfComponents = numberOfComponentsForType(accessor.type);
    const count = accessor.count;
    const values = new Array(numberOfComponents * count);

    if (!defined(accessor.bufferView)) {
      return values.fill(0)
    }

    const bufferView = gltf.bufferViews[accessor.bufferView];
    const source = gltf.buffers[bufferView.buffer].extras._pipeline.source;
    let byteOffset =
      accessor.byteOffset + bufferView.byteOffset + source.byteOffset;

    const dataView = new DataView(source.buffer);
    const components = new Array(numberOfComponents);
    const componentReader = getComponentReader(accessor.componentType);

    for (let i = 0; i < count; ++i) {
      componentReader(
        dataView,
        byteOffset,
        numberOfComponents,
        componentTypeByteLength,
        components
      );
      for (let j = 0; j < numberOfComponents; ++j) {
        values[i * numberOfComponents + j] = components[j];
      }
      byteOffset += byteStride;
    }
    return values;
  }

  /**
   * Update accessors referenced by JOINTS_0 and WEIGHTS_0 attributes to use correct component types.
   *
   * @param {Object} gltf A javascript object containing a glTF asset.
   * @returns {Object} The glTF asset with compressed meshes.
   *
   * @private
   */
  function updateAccessorComponentTypes(gltf) {
    let componentType;
    ForEach.accessorWithSemantic(gltf, "JOINTS_0", function (accessorId) {
      const accessor = gltf.accessors[accessorId];
      componentType = accessor.componentType;
      if (componentType === WebGLConstants$1.BYTE) {
        convertType(gltf, accessor, ComponentDatatype$1.UNSIGNED_BYTE);
      } else if (
        componentType !== WebGLConstants$1.UNSIGNED_BYTE &&
        componentType !== WebGLConstants$1.UNSIGNED_SHORT
      ) {
        convertType(gltf, accessor, ComponentDatatype$1.UNSIGNED_SHORT);
      }
    });
    ForEach.accessorWithSemantic(gltf, "WEIGHTS_0", function (accessorId) {
      const accessor = gltf.accessors[accessorId];
      componentType = accessor.componentType;
      if (componentType === WebGLConstants$1.BYTE) {
        convertType(gltf, accessor, ComponentDatatype$1.UNSIGNED_BYTE);
      } else if (componentType === WebGLConstants$1.SHORT) {
        convertType(gltf, accessor, ComponentDatatype$1.UNSIGNED_SHORT);
      }
    });

    return gltf;
  }

  function convertType(gltf, accessor, updatedComponentType) {
    const typedArray = ComponentDatatype$1.createTypedArray(
      updatedComponentType,
      readAccessorPacked(gltf, accessor)
    );
    const newBuffer = new Uint8Array(typedArray.buffer);
    accessor.bufferView = addBuffer(gltf, newBuffer);
    accessor.componentType = updatedComponentType;
    accessor.byteOffset = 0;
  }

  const updateFunctions = {
    0.8: glTF08to10,
    "1.0": glTF10to20,
    "2.0": undefined,
  };

  /**
   * Update the glTF version to the latest version (2.0), or targetVersion if specified.
   * Applies changes made to the glTF spec between revisions so that the core library
   * only has to handle the latest version.
   *
   * @param {Object} gltf A javascript object containing a glTF asset.
   * @param {Object} [options] Options for updating the glTF.
   * @param {String} [options.targetVersion] The glTF will be upgraded until it hits the specified version.
   * @returns {Object} The updated glTF asset.
   *
   * @private
   */
  function updateVersion(gltf, options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const targetVersion = options.targetVersion;
    let version = gltf.version;

    gltf.asset = defaultValue(gltf.asset, {
      version: "1.0",
    });

    gltf.asset.version = defaultValue(gltf.asset.version, "1.0");
    version = defaultValue(version, gltf.asset.version).toString();

    // Invalid version
    if (!Object.prototype.hasOwnProperty.call(updateFunctions, version)) {
      // Try truncating trailing version numbers, could be a number as well if it is 0.8
      if (defined(version)) {
        version = version.substring(0, 3);
      }
      // Default to 1.0 if it cannot be determined
      if (!Object.prototype.hasOwnProperty.call(updateFunctions, version)) {
        version = "1.0";
      }
    }

    let updateFunction = updateFunctions[version];

    while (defined(updateFunction)) {
      if (version === targetVersion) {
        break;
      }
      updateFunction(gltf, options);
      version = gltf.asset.version;
      updateFunction = updateFunctions[version];
    }
    return gltf;
  }

  function updateInstanceTechniques(gltf) {
    const materials = gltf.materials;
    for (const materialId in materials) {
      if (Object.prototype.hasOwnProperty.call(materials, materialId)) {
        const material = materials[materialId];
        const instanceTechnique = material.instanceTechnique;
        if (defined(instanceTechnique)) {
          material.technique = instanceTechnique.technique;
          material.values = instanceTechnique.values;
          delete material.instanceTechnique;
        }
      }
    }
  }

  function setPrimitiveModes(gltf) {
    const meshes = gltf.meshes;
    for (const meshId in meshes) {
      if (Object.prototype.hasOwnProperty.call(meshes, meshId)) {
        const mesh = meshes[meshId];
        const primitives = mesh.primitives;
        if (defined(primitives)) {
          const primitivesLength = primitives.length;
          for (let i = 0; i < primitivesLength; ++i) {
            const primitive = primitives[i];
            const defaultMode = defaultValue(
              primitive.primitive,
              WebGLConstants$1.TRIANGLES
            );
            primitive.mode = defaultValue(primitive.mode, defaultMode);
            delete primitive.primitive;
          }
        }
      }
    }
  }

  function updateNodes(gltf) {
    const nodes = gltf.nodes;
    const axis = new Cartesian3();
    const quat = new Quaternion();
    for (const nodeId in nodes) {
      if (Object.prototype.hasOwnProperty.call(nodes, nodeId)) {
        const node = nodes[nodeId];
        if (defined(node.rotation)) {
          const rotation = node.rotation;
          Cartesian3.fromArray(rotation, 0, axis);
          Quaternion.fromAxisAngle(axis, rotation[3], quat);
          node.rotation = [quat.x, quat.y, quat.z, quat.w];
        }
        const instanceSkin = node.instanceSkin;
        if (defined(instanceSkin)) {
          node.skeletons = instanceSkin.skeletons;
          node.skin = instanceSkin.skin;
          node.meshes = instanceSkin.meshes;
          delete node.instanceSkin;
        }
      }
    }
  }

  function updateAnimations(gltf) {
    const animations = gltf.animations;
    const accessors = gltf.accessors;
    const bufferViews = gltf.bufferViews;
    const buffers = gltf.buffers;
    const updatedAccessors = {};
    const axis = new Cartesian3();
    const quat = new Quaternion();
    for (const animationId in animations) {
      if (Object.prototype.hasOwnProperty.call(animations, animationId)) {
        const animation = animations[animationId];
        const channels = animation.channels;
        const parameters = animation.parameters;
        const samplers = animation.samplers;
        if (defined(channels)) {
          const channelsLength = channels.length;
          for (let i = 0; i < channelsLength; ++i) {
            const channel = channels[i];
            if (channel.target.path === "rotation") {
              const accessorId = parameters[samplers[channel.sampler].output];
              if (defined(updatedAccessors[accessorId])) {
                continue;
              }
              updatedAccessors[accessorId] = true;
              const accessor = accessors[accessorId];
              const bufferView = bufferViews[accessor.bufferView];
              const buffer = buffers[bufferView.buffer];
              const source = buffer.extras._pipeline.source;
              const byteOffset =
                source.byteOffset + bufferView.byteOffset + accessor.byteOffset;
              const componentType = accessor.componentType;
              const count = accessor.count;
              const componentsLength = numberOfComponentsForType(accessor.type);
              const length = accessor.count * componentsLength;
              const typedArray = ComponentDatatype$1.createArrayBufferView(
                componentType,
                source.buffer,
                byteOffset,
                length
              );

              for (let j = 0; j < count; j++) {
                const offset = j * componentsLength;
                Cartesian3.unpack(typedArray, offset, axis);
                const angle = typedArray[offset + 3];
                Quaternion.fromAxisAngle(axis, angle, quat);
                Quaternion.pack(quat, typedArray, offset);
              }
            }
          }
        }
      }
    }
  }

  function removeTechniquePasses(gltf) {
    const techniques = gltf.techniques;
    for (const techniqueId in techniques) {
      if (Object.prototype.hasOwnProperty.call(techniques, techniqueId)) {
        const technique = techniques[techniqueId];
        const passes = technique.passes;
        if (defined(passes)) {
          const passName = defaultValue(technique.pass, "defaultPass");
          if (Object.prototype.hasOwnProperty.call(passes, passName)) {
            const pass = passes[passName];
            const instanceProgram = pass.instanceProgram;
            technique.attributes = defaultValue(
              technique.attributes,
              instanceProgram.attributes
            );
            technique.program = defaultValue(
              technique.program,
              instanceProgram.program
            );
            technique.uniforms = defaultValue(
              technique.uniforms,
              instanceProgram.uniforms
            );
            technique.states = defaultValue(technique.states, pass.states);
          }
          delete technique.passes;
          delete technique.pass;
        }
      }
    }
  }

  function glTF08to10(gltf) {
    if (!defined(gltf.asset)) {
      gltf.asset = {};
    }
    const asset = gltf.asset;
    asset.version = "1.0";
    // Profile should be an object, not a string
    if (typeof asset.profile === "string") {
      const split = asset.profile.split(" ");
      asset.profile = {
        api: split[0],
        version: split[1],
      };
    } else {
      asset.profile = {};
    }

    // Version property should be in asset, not on the root element
    if (defined(gltf.version)) {
      delete gltf.version;
    }
    // material.instanceTechnique properties should be directly on the material
    updateInstanceTechniques(gltf);
    // primitive.primitive should be primitive.mode
    setPrimitiveModes(gltf);
    // Node rotation should be quaternion, not axis-angle
    // node.instanceSkin is deprecated
    updateNodes(gltf);
    // Animations that target rotations should be quaternion, not axis-angle
    updateAnimations(gltf);
    // technique.pass and techniques.passes are deprecated
    removeTechniquePasses(gltf);
    // gltf.allExtensions -> extensionsUsed
    if (defined(gltf.allExtensions)) {
      gltf.extensionsUsed = gltf.allExtensions;
      delete gltf.allExtensions;
    }
    // gltf.lights -> khrMaterialsCommon.lights
    if (defined(gltf.lights)) {
      const extensions = defaultValue(gltf.extensions, {});
      gltf.extensions = extensions;
      const materialsCommon = defaultValue(extensions.KHR_materials_common, {});
      extensions.KHR_materials_common = materialsCommon;
      materialsCommon.lights = gltf.lights;
      delete gltf.lights;
      addExtensionsUsed(gltf, "KHR_materials_common");
    }
  }

  function removeAnimationSamplersIndirection(gltf) {
    const animations = gltf.animations;
    for (const animationId in animations) {
      if (Object.prototype.hasOwnProperty.call(animations, animationId)) {
        const animation = animations[animationId];
        const parameters = animation.parameters;
        if (defined(parameters)) {
          const samplers = animation.samplers;
          for (const samplerId in samplers) {
            if (Object.prototype.hasOwnProperty.call(samplers, samplerId)) {
              const sampler = samplers[samplerId];
              sampler.input = parameters[sampler.input];
              sampler.output = parameters[sampler.output];
            }
          }
          delete animation.parameters;
        }
      }
    }
  }

  function objectToArray(object, mapping) {
    const array = [];
    for (const id in object) {
      if (Object.prototype.hasOwnProperty.call(object, id)) {
        const value = object[id];
        mapping[id] = array.length;
        array.push(value);
        if (!defined(value.name)) {
          value.name = id;
        }
      }
    }
    return array;
  }

  function objectsToArrays(gltf) {
    let i;
    const globalMapping = {
      accessors: {},
      animations: {},
      buffers: {},
      bufferViews: {},
      cameras: {},
      images: {},
      materials: {},
      meshes: {},
      nodes: {},
      programs: {},
      samplers: {},
      scenes: {},
      shaders: {},
      skins: {},
      textures: {},
      techniques: {},
    };

    // Map joint names to id names
    let jointName;
    const jointNameToId = {};
    const nodes = gltf.nodes;
    for (const id in nodes) {
      if (Object.prototype.hasOwnProperty.call(nodes, id)) {
        jointName = nodes[id].jointName;
        if (defined(jointName)) {
          jointNameToId[jointName] = id;
        }
      }
    }

    // Convert top level objects to arrays
    for (const topLevelId in gltf) {
      if (
        Object.prototype.hasOwnProperty.call(gltf, topLevelId) &&
        defined(globalMapping[topLevelId])
      ) {
        const objectMapping = {};
        const object = gltf[topLevelId];
        gltf[topLevelId] = objectToArray(object, objectMapping);
        globalMapping[topLevelId] = objectMapping;
      }
    }

    // Remap joint names to array indexes
    for (jointName in jointNameToId) {
      if (Object.prototype.hasOwnProperty.call(jointNameToId, jointName)) {
        jointNameToId[jointName] = globalMapping.nodes[jointNameToId[jointName]];
      }
    }

    // Fix references
    if (defined(gltf.scene)) {
      gltf.scene = globalMapping.scenes[gltf.scene];
    }
    ForEach.bufferView(gltf, function (bufferView) {
      if (defined(bufferView.buffer)) {
        bufferView.buffer = globalMapping.buffers[bufferView.buffer];
      }
    });
    ForEach.accessor(gltf, function (accessor) {
      if (defined(accessor.bufferView)) {
        accessor.bufferView = globalMapping.bufferViews[accessor.bufferView];
      }
    });
    ForEach.shader(gltf, function (shader) {
      const extensions = shader.extensions;
      if (defined(extensions)) {
        const binaryGltf = extensions.KHR_binary_glTF;
        if (defined(binaryGltf)) {
          shader.bufferView = globalMapping.bufferViews[binaryGltf.bufferView];
          delete extensions.KHR_binary_glTF;
        }
        if (Object.keys(extensions).length === 0) {
          delete shader.extensions;
        }
      }
    });
    ForEach.program(gltf, function (program) {
      if (defined(program.vertexShader)) {
        program.vertexShader = globalMapping.shaders[program.vertexShader];
      }
      if (defined(program.fragmentShader)) {
        program.fragmentShader = globalMapping.shaders[program.fragmentShader];
      }
    });
    ForEach.technique(gltf, function (technique) {
      if (defined(technique.program)) {
        technique.program = globalMapping.programs[technique.program];
      }
      ForEach.techniqueParameter(technique, function (parameter) {
        if (defined(parameter.node)) {
          parameter.node = globalMapping.nodes[parameter.node];
        }
        const value = parameter.value;
        if (typeof value === "string") {
          parameter.value = {
            index: globalMapping.textures[value],
          };
        }
      });
    });
    ForEach.mesh(gltf, function (mesh) {
      ForEach.meshPrimitive(mesh, function (primitive) {
        if (defined(primitive.indices)) {
          primitive.indices = globalMapping.accessors[primitive.indices];
        }
        ForEach.meshPrimitiveAttribute(
          primitive,
          function (accessorId, semantic) {
            primitive.attributes[semantic] = globalMapping.accessors[accessorId];
          }
        );
        if (defined(primitive.material)) {
          primitive.material = globalMapping.materials[primitive.material];
        }
      });
    });
    ForEach.node(gltf, function (node) {
      let children = node.children;
      if (defined(children)) {
        const childrenLength = children.length;
        for (i = 0; i < childrenLength; ++i) {
          children[i] = globalMapping.nodes[children[i]];
        }
      }
      if (defined(node.meshes)) {
        // Split out meshes on nodes
        const meshes = node.meshes;
        const meshesLength = meshes.length;
        if (meshesLength > 0) {
          node.mesh = globalMapping.meshes[meshes[0]];
          for (i = 1; i < meshesLength; ++i) {
            const meshNode = {
              mesh: globalMapping.meshes[meshes[i]],
            };
            const meshNodeId = addToArray(gltf.nodes, meshNode);
            if (!defined(children)) {
              children = [];
              node.children = children;
            }
            children.push(meshNodeId);
          }
        }
        delete node.meshes;
      }
      if (defined(node.camera)) {
        node.camera = globalMapping.cameras[node.camera];
      }
      if (defined(node.skin)) {
        node.skin = globalMapping.skins[node.skin];
      }
      if (defined(node.skeletons)) {
        // Assign skeletons to skins
        const skeletons = node.skeletons;
        const skeletonsLength = skeletons.length;
        if (skeletonsLength > 0 && defined(node.skin)) {
          const skin = gltf.skins[node.skin];
          skin.skeleton = globalMapping.nodes[skeletons[0]];
        }
        delete node.skeletons;
      }
      if (defined(node.jointName)) {
        delete node.jointName;
      }
    });
    ForEach.skin(gltf, function (skin) {
      if (defined(skin.inverseBindMatrices)) {
        skin.inverseBindMatrices =
          globalMapping.accessors[skin.inverseBindMatrices];
      }
      const jointNames = skin.jointNames;
      if (defined(jointNames)) {
        const joints = [];
        const jointNamesLength = jointNames.length;
        for (i = 0; i < jointNamesLength; ++i) {
          joints[i] = jointNameToId[jointNames[i]];
        }
        skin.joints = joints;
        delete skin.jointNames;
      }
    });
    ForEach.scene(gltf, function (scene) {
      const sceneNodes = scene.nodes;
      if (defined(sceneNodes)) {
        const sceneNodesLength = sceneNodes.length;
        for (i = 0; i < sceneNodesLength; ++i) {
          sceneNodes[i] = globalMapping.nodes[sceneNodes[i]];
        }
      }
    });
    ForEach.animation(gltf, function (animation) {
      const samplerMapping = {};
      animation.samplers = objectToArray(animation.samplers, samplerMapping);
      ForEach.animationSampler(animation, function (sampler) {
        sampler.input = globalMapping.accessors[sampler.input];
        sampler.output = globalMapping.accessors[sampler.output];
      });
      ForEach.animationChannel(animation, function (channel) {
        channel.sampler = samplerMapping[channel.sampler];
        const target = channel.target;
        if (defined(target)) {
          target.node = globalMapping.nodes[target.id];
          delete target.id;
        }
      });
    });
    ForEach.material(gltf, function (material) {
      if (defined(material.technique)) {
        material.technique = globalMapping.techniques[material.technique];
      }
      ForEach.materialValue(material, function (value, name) {
        if (typeof value === "string") {
          material.values[name] = {
            index: globalMapping.textures[value],
          };
        }
      });
      const extensions = material.extensions;
      if (defined(extensions)) {
        const materialsCommon = extensions.KHR_materials_common;
        if (defined(materialsCommon)) {
          ForEach.materialValue(materialsCommon, function (value, name) {
            if (typeof value === "string") {
              materialsCommon.values[name] = {
                index: globalMapping.textures[value],
              };
            }
          });
        }
      }
    });
    ForEach.image(gltf, function (image) {
      const extensions = image.extensions;
      if (defined(extensions)) {
        const binaryGltf = extensions.KHR_binary_glTF;
        if (defined(binaryGltf)) {
          image.bufferView = globalMapping.bufferViews[binaryGltf.bufferView];
          image.mimeType = binaryGltf.mimeType;
          delete extensions.KHR_binary_glTF;
        }
        if (Object.keys(extensions).length === 0) {
          delete image.extensions;
        }
      }
    });
    ForEach.texture(gltf, function (texture) {
      if (defined(texture.sampler)) {
        texture.sampler = globalMapping.samplers[texture.sampler];
      }
      if (defined(texture.source)) {
        texture.source = globalMapping.images[texture.source];
      }
    });
  }

  function removeAnimationSamplerNames(gltf) {
    ForEach.animation(gltf, function (animation) {
      ForEach.animationSampler(animation, function (sampler) {
        delete sampler.name;
      });
    });
  }

  function removeEmptyArrays(gltf) {
    for (const topLevelId in gltf) {
      if (Object.prototype.hasOwnProperty.call(gltf, topLevelId)) {
        const array = gltf[topLevelId];
        if (Array.isArray(array) && array.length === 0) {
          delete gltf[topLevelId];
        }
      }
    }
    ForEach.node(gltf, function (node) {
      if (defined(node.children) && node.children.length === 0) {
        delete node.children;
      }
    });
  }

  function stripAsset(gltf) {
    const asset = gltf.asset;
    delete asset.profile;
    delete asset.premultipliedAlpha;
  }

  const knownExtensions = {
    CESIUM_RTC: true,
    KHR_materials_common: true,
    WEB3D_quantized_attributes: true,
  };
  function requireKnownExtensions(gltf) {
    const extensionsUsed = gltf.extensionsUsed;
    gltf.extensionsRequired = defaultValue(gltf.extensionsRequired, []);
    if (defined(extensionsUsed)) {
      const extensionsUsedLength = extensionsUsed.length;
      for (let i = 0; i < extensionsUsedLength; ++i) {
        const extension = extensionsUsed[i];
        if (defined(knownExtensions[extension])) {
          gltf.extensionsRequired.push(extension);
        }
      }
    }
  }

  function removeBufferType(gltf) {
    ForEach.buffer(gltf, function (buffer) {
      delete buffer.type;
    });
  }

  function removeTextureProperties(gltf) {
    ForEach.texture(gltf, function (texture) {
      delete texture.format;
      delete texture.internalFormat;
      delete texture.target;
      delete texture.type;
    });
  }

  function requireAttributeSetIndex(gltf) {
    ForEach.mesh(gltf, function (mesh) {
      ForEach.meshPrimitive(mesh, function (primitive) {
        ForEach.meshPrimitiveAttribute(
          primitive,
          function (accessorId, semantic) {
            if (semantic === "TEXCOORD") {
              primitive.attributes.TEXCOORD_0 = accessorId;
            } else if (semantic === "COLOR") {
              primitive.attributes.COLOR_0 = accessorId;
            }
          }
        );
        delete primitive.attributes.TEXCOORD;
        delete primitive.attributes.COLOR;
      });
    });
    ForEach.technique(gltf, function (technique) {
      ForEach.techniqueParameter(technique, function (parameter) {
        const semantic = parameter.semantic;
        if (defined(semantic)) {
          if (semantic === "TEXCOORD") {
            parameter.semantic = "TEXCOORD_0";
          } else if (semantic === "COLOR") {
            parameter.semantic = "COLOR_0";
          }
        }
      });
    });
  }

  const knownSemantics = {
    POSITION: true,
    NORMAL: true,
    TANGENT: true,
  };
  const indexedSemantics = {
    COLOR: "COLOR",
    JOINT: "JOINTS",
    JOINTS: "JOINTS",
    TEXCOORD: "TEXCOORD",
    WEIGHT: "WEIGHTS",
    WEIGHTS: "WEIGHTS",
  };
  function underscoreApplicationSpecificSemantics(gltf) {
    const mappedSemantics = {};
    ForEach.mesh(gltf, function (mesh) {
      ForEach.meshPrimitive(mesh, function (primitive) {
        /*eslint-disable no-unused-vars*/
        ForEach.meshPrimitiveAttribute(
          primitive,
          function (accessorId, semantic) {
            if (semantic.charAt(0) !== "_") {
              const setIndex = semantic.search(/_[0-9]+/g);
              let strippedSemantic = semantic;
              let suffix = "_0";
              if (setIndex >= 0) {
                strippedSemantic = semantic.substring(0, setIndex);
                suffix = semantic.substring(setIndex);
              }
              let newSemantic;
              const indexedSemantic = indexedSemantics[strippedSemantic];
              if (defined(indexedSemantic)) {
                newSemantic = indexedSemantic + suffix;
                mappedSemantics[semantic] = newSemantic;
              } else if (!defined(knownSemantics[strippedSemantic])) {
                newSemantic = "_" + semantic;
                mappedSemantics[semantic] = newSemantic;
              }
            }
          }
        );
        for (const semantic in mappedSemantics) {
          if (Object.prototype.hasOwnProperty.call(mappedSemantics, semantic)) {
            const mappedSemantic = mappedSemantics[semantic];
            const accessorId = primitive.attributes[semantic];
            if (defined(accessorId)) {
              delete primitive.attributes[semantic];
              primitive.attributes[mappedSemantic] = accessorId;
            }
          }
        }
      });
    });
    ForEach.technique(gltf, function (technique) {
      ForEach.techniqueParameter(technique, function (parameter) {
        const mappedSemantic = mappedSemantics[parameter.semantic];
        if (defined(mappedSemantic)) {
          parameter.semantic = mappedSemantic;
        }
      });
    });
  }

  function clampCameraParameters(gltf) {
    ForEach.camera(gltf, function (camera) {
      const perspective = camera.perspective;
      if (defined(perspective)) {
        const aspectRatio = perspective.aspectRatio;
        if (defined(aspectRatio) && aspectRatio === 0.0) {
          delete perspective.aspectRatio;
        }
        const yfov = perspective.yfov;
        if (defined(yfov) && yfov === 0.0) {
          perspective.yfov = 1.0;
        }
      }
    });
  }

  function computeAccessorByteStride(gltf, accessor) {
    return defined(accessor.byteStride) && accessor.byteStride !== 0
      ? accessor.byteStride
      : getAccessorByteStride(gltf, accessor);
  }

  function requireByteLength(gltf) {
    ForEach.buffer(gltf, function (buffer) {
      if (!defined(buffer.byteLength)) {
        buffer.byteLength = buffer.extras._pipeline.source.length;
      }
    });
    ForEach.accessor(gltf, function (accessor) {
      const bufferViewId = accessor.bufferView;
      if (defined(bufferViewId)) {
        const bufferView = gltf.bufferViews[bufferViewId];
        const accessorByteStride = computeAccessorByteStride(gltf, accessor);
        const accessorByteEnd =
          accessor.byteOffset + accessor.count * accessorByteStride;
        bufferView.byteLength = Math.max(
          defaultValue(bufferView.byteLength, 0),
          accessorByteEnd
        );
      }
    });
  }

  function moveByteStrideToBufferView(gltf) {
    let i;
    let j;
    let bufferView;
    const bufferViews = gltf.bufferViews;

    const bufferViewHasVertexAttributes = {};
    ForEach.accessorContainingVertexAttributeData(gltf, function (accessorId) {
      const accessor = gltf.accessors[accessorId];
      if (defined(accessor.bufferView)) {
        bufferViewHasVertexAttributes[accessor.bufferView] = true;
      }
    });

    // Map buffer views to a list of accessors
    const bufferViewMap = {};
    ForEach.accessor(gltf, function (accessor) {
      if (defined(accessor.bufferView)) {
        bufferViewMap[accessor.bufferView] = defaultValue(
          bufferViewMap[accessor.bufferView],
          []
        );
        bufferViewMap[accessor.bufferView].push(accessor);
      }
    });

    // Split accessors with different byte strides
    for (const bufferViewId in bufferViewMap) {
      if (Object.prototype.hasOwnProperty.call(bufferViewMap, bufferViewId)) {
        bufferView = bufferViews[bufferViewId];
        const accessors = bufferViewMap[bufferViewId];
        accessors.sort(function (a, b) {
          return a.byteOffset - b.byteOffset;
        });
        let currentByteOffset = 0;
        let currentIndex = 0;
        const accessorsLength = accessors.length;
        for (i = 0; i < accessorsLength; ++i) {
          let accessor = accessors[i];
          const accessorByteStride = computeAccessorByteStride(gltf, accessor);
          const accessorByteOffset = accessor.byteOffset;
          const accessorByteLength = accessor.count * accessorByteStride;
          delete accessor.byteStride;

          const hasNextAccessor = i < accessorsLength - 1;
          const nextAccessorByteStride = hasNextAccessor
            ? computeAccessorByteStride(gltf, accessors[i + 1])
            : undefined;
          if (accessorByteStride !== nextAccessorByteStride) {
            const newBufferView = clone$1(bufferView, true);
            if (bufferViewHasVertexAttributes[bufferViewId]) {
              newBufferView.byteStride = accessorByteStride;
            }
            newBufferView.byteOffset += currentByteOffset;
            newBufferView.byteLength =
              accessorByteOffset + accessorByteLength - currentByteOffset;
            const newBufferViewId = addToArray(bufferViews, newBufferView);
            for (j = currentIndex; j <= i; ++j) {
              accessor = accessors[j];
              accessor.bufferView = newBufferViewId;
              accessor.byteOffset = accessor.byteOffset - currentByteOffset;
            }
            // Set current byte offset to next accessor's byte offset
            currentByteOffset = hasNextAccessor
              ? accessors[i + 1].byteOffset
              : undefined;
            currentIndex = i + 1;
          }
        }
      }
    }

    // Remove unused buffer views
    removeUnusedElements(gltf, ["accessor", "bufferView", "buffer"]);
  }

  function requirePositionAccessorMinMax(gltf) {
    ForEach.accessorWithSemantic(gltf, "POSITION", function (accessorId) {
      const accessor = gltf.accessors[accessorId];
      if (!defined(accessor.min) || !defined(accessor.max)) {
        const minMax = findAccessorMinMax(gltf, accessor);
        accessor.min = minMax.min;
        accessor.max = minMax.max;
      }
    });
  }

  function isNodeEmpty(node) {
    return (
      (!defined(node.children) || node.children.length === 0) &&
      (!defined(node.meshes) || node.meshes.length === 0) &&
      !defined(node.camera) &&
      !defined(node.skin) &&
      !defined(node.skeletons) &&
      !defined(node.jointName) &&
      (!defined(node.translation) ||
        Cartesian3.fromArray(node.translation).equals(Cartesian3.ZERO)) &&
      (!defined(node.scale) ||
        Cartesian3.fromArray(node.scale).equals(new Cartesian3(1.0, 1.0, 1.0))) &&
      (!defined(node.rotation) ||
        Cartesian4.fromArray(node.rotation).equals(
          new Cartesian4(0.0, 0.0, 0.0, 1.0)
        )) &&
      (!defined(node.matrix) ||
        Matrix4.fromColumnMajorArray(node.matrix).equals(Matrix4.IDENTITY)) &&
      !defined(node.extensions) &&
      !defined(node.extras)
    );
  }

  function deleteNode(gltf, nodeId) {
    // Remove from list of nodes in scene
    ForEach.scene(gltf, function (scene) {
      const sceneNodes = scene.nodes;
      if (defined(sceneNodes)) {
        const sceneNodesLength = sceneNodes.length;
        for (let i = sceneNodesLength; i >= 0; --i) {
          if (sceneNodes[i] === nodeId) {
            sceneNodes.splice(i, 1);
            return;
          }
        }
      }
    });

    // Remove parent node's reference to this node, and delete the parent if also empty
    ForEach.node(gltf, function (parentNode, parentNodeId) {
      if (defined(parentNode.children)) {
        const index = parentNode.children.indexOf(nodeId);
        if (index > -1) {
          parentNode.children.splice(index, 1);

          if (isNodeEmpty(parentNode)) {
            deleteNode(gltf, parentNodeId);
          }
        }
      }
    });

    delete gltf.nodes[nodeId];
  }

  function removeEmptyNodes(gltf) {
    ForEach.node(gltf, function (node, nodeId) {
      if (isNodeEmpty(node)) {
        deleteNode(gltf, nodeId);
      }
    });

    return gltf;
  }

  function requireAnimationAccessorMinMax(gltf) {
    ForEach.animation(gltf, function (animation) {
      ForEach.animationSampler(animation, function (sampler) {
        const accessor = gltf.accessors[sampler.input];
        if (!defined(accessor.min) || !defined(accessor.max)) {
          const minMax = findAccessorMinMax(gltf, accessor);
          accessor.min = minMax.min;
          accessor.max = minMax.max;
        }
      });
    });
  }

  function glTF10to20(gltf) {
    gltf.asset = defaultValue(gltf.asset, {});
    gltf.asset.version = "2.0";
    // material.instanceTechnique properties should be directly on the material. instanceTechnique is a gltf 0.8 property but is seen in some 1.0 models.
    updateInstanceTechniques(gltf);
    // animation.samplers now refers directly to accessors and animation.parameters should be removed
    removeAnimationSamplersIndirection(gltf);
    // Remove empty nodes and re-assign referencing indices
    removeEmptyNodes(gltf);
    // Top-level objects are now arrays referenced by index instead of id
    objectsToArrays(gltf);
    // Animation.sampler objects cannot have names
    removeAnimationSamplerNames(gltf);
    // asset.profile no longer exists
    stripAsset(gltf);
    // Move known extensions from extensionsUsed to extensionsRequired
    requireKnownExtensions(gltf);
    // bufferView.byteLength and buffer.byteLength are required
    requireByteLength(gltf);
    // byteStride moved from accessor to bufferView
    moveByteStrideToBufferView(gltf);
    // accessor.min and accessor.max must be defined for accessors containing POSITION attributes
    requirePositionAccessorMinMax(gltf);
    // An animation sampler's input accessor must have min and max properties defined
    requireAnimationAccessorMinMax(gltf);
    // buffer.type is unnecessary and should be removed
    removeBufferType(gltf);
    // Remove format, internalFormat, target, and type
    removeTextureProperties(gltf);
    // TEXCOORD and COLOR attributes must be written with a set index (TEXCOORD_#)
    requireAttributeSetIndex(gltf);
    // Add underscores to application-specific parameters
    underscoreApplicationSpecificSemantics(gltf);
    // Accessors referenced by JOINTS_0 and WEIGHTS_0 attributes must have correct component types
    updateAccessorComponentTypes(gltf);
    // Clamp camera parameters
    clampCameraParameters(gltf);
    // Move legacy technique render states to material properties and add KHR_blend extension blending functions
    moveTechniqueRenderStates(gltf);
    // Add material techniques to KHR_techniques_webgl extension, removing shaders, programs, and techniques
    moveTechniquesToExtension(gltf);
    // Remove empty arrays
    removeEmptyArrays(gltf);
  }

  /**
   * @private
   */
  function ModelLoadResources() {
    this.initialized = false;
    this.resourcesParsed = false;

    this.vertexBuffersToCreate = new Queue();
    this.indexBuffersToCreate = new Queue();
    this.buffers = {};
    this.pendingBufferLoads = 0;

    this.programsToCreate = new Queue();
    this.shaders = {};
    this.pendingShaderLoads = 0;

    this.texturesToCreate = new Queue();
    this.pendingTextureLoads = 0;

    this.texturesToCreateFromBufferView = new Queue();
    this.pendingBufferViewToImage = 0;

    this.createSamplers = true;
    this.createSkins = true;
    this.createRuntimeAnimations = true;
    this.createVertexArrays = true;
    this.createRenderStates = true;
    this.createUniformMaps = true;
    this.createRuntimeNodes = true;

    this.createdBufferViews = {};
    this.primitivesToDecode = new Queue();
    this.activeDecodingTasks = 0;
    this.pendingDecodingCache = false;

    this.skinnedNodesIds = [];
  }

  /**
   * This function differs from the normal subarray function
   * because it takes offset and length, rather than begin and end.
   * @private
   */
  function getSubarray(array, offset, length) {
    return array.subarray(offset, offset + length);
  }

  ModelLoadResources.prototype.getBuffer = function (bufferView) {
    return getSubarray(
      this.buffers[bufferView.buffer],
      bufferView.byteOffset,
      bufferView.byteLength
    );
  };

  ModelLoadResources.prototype.finishedPendingBufferLoads = function () {
    return this.pendingBufferLoads === 0;
  };

  ModelLoadResources.prototype.finishedBuffersCreation = function () {
    return (
      this.pendingBufferLoads === 0 &&
      this.vertexBuffersToCreate.length === 0 &&
      this.indexBuffersToCreate.length === 0
    );
  };

  ModelLoadResources.prototype.finishedProgramCreation = function () {
    return this.pendingShaderLoads === 0 && this.programsToCreate.length === 0;
  };

  ModelLoadResources.prototype.finishedTextureCreation = function () {
    const finishedPendingLoads = this.pendingTextureLoads === 0;
    const finishedResourceCreation =
      this.texturesToCreate.length === 0 &&
      this.texturesToCreateFromBufferView.length === 0;

    return finishedPendingLoads && finishedResourceCreation;
  };

  ModelLoadResources.prototype.finishedEverythingButTextureCreation = function () {
    const finishedPendingLoads =
      this.pendingBufferLoads === 0 && this.pendingShaderLoads === 0;
    const finishedResourceCreation =
      this.vertexBuffersToCreate.length === 0 &&
      this.indexBuffersToCreate.length === 0 &&
      this.programsToCreate.length === 0 &&
      this.pendingBufferViewToImage === 0;

    return (
      this.finishedDecoding() && finishedPendingLoads && finishedResourceCreation
    );
  };

  ModelLoadResources.prototype.finishedDecoding = function () {
    return (
      this.primitivesToDecode.length === 0 &&
      this.activeDecodingTasks === 0 &&
      !this.pendingDecodingCache
    );
  };

  ModelLoadResources.prototype.finished = function () {
    return (
      this.finishedDecoding() &&
      this.finishedTextureCreation() &&
      this.finishedEverythingButTextureCreation()
    );
  };

  /**
   * @private
   */
  const ModelUtility = {};

  /**
   * Updates the model's forward axis if the model is not a 2.0 model.
   *
   * @param {Object} model The model to update.
   */
  ModelUtility.updateForwardAxis = function (model) {
    const cachedSourceVersion = model.gltfInternal.extras.sourceVersion;

    if (
      (defined(cachedSourceVersion) && cachedSourceVersion !== "2.0") ||
      ModelUtility.getAssetVersion(model.gltfInternal) !== "2.0"
    ) {
      model._gltfForwardAxis = Axis$1.X;
    }
  };

  /**
   *  Gets the string representing the glTF asset version.
   *
   *  @param {Object} gltf A javascript object containing a glTF asset.
   *  @returns {String} The glTF asset version string.
   */
  ModelUtility.getAssetVersion = function (gltf) {
    // In glTF 1.0 it was valid to omit the version number.
    if (!defined(gltf.asset) || !defined(gltf.asset.version)) {
      return "1.0";
    }

    return gltf.asset.version;
  };

  /**
   * Splits primitive materials with values incompatible for generating techniques.
   *
   * @param {Object} gltf A javascript object containing a glTF asset.
   * @returns {Object} The glTF asset with modified materials.
   */
  ModelUtility.splitIncompatibleMaterials = function (gltf) {
    const accessors = gltf.accessors;
    const materials = gltf.materials;
    const primitiveInfoByMaterial = {};
    ForEach.mesh(gltf, function (mesh) {
      ForEach.meshPrimitive(mesh, function (primitive) {
        let materialIndex = primitive.material;
        const material = materials[materialIndex];

        const jointAccessorId = primitive.attributes.JOINTS_0;
        let componentType;
        let accessorType;
        if (defined(jointAccessorId)) {
          const jointAccessor = accessors[jointAccessorId];
          componentType = jointAccessor.componentType;
          accessorType = jointAccessor.type;
        }
        const isSkinned = defined(jointAccessorId) && accessorType === "VEC4";
        const hasVertexColors = defined(primitive.attributes.COLOR_0);
        const hasMorphTargets = defined(primitive.targets);
        const hasNormals = defined(primitive.attributes.NORMAL);
        const hasTangents = defined(primitive.attributes.TANGENT);
        const hasTexCoords = defined(primitive.attributes.TEXCOORD_0);
        const hasTexCoord1 =
          hasTexCoords && defined(primitive.attributes.TEXCOORD_1);
        const hasOutline =
          defined(primitive.extensions) &&
          defined(primitive.extensions.CESIUM_primitive_outline);

        const primitiveInfo = primitiveInfoByMaterial[materialIndex];
        if (!defined(primitiveInfo)) {
          primitiveInfoByMaterial[materialIndex] = {
            skinning: {
              skinned: isSkinned,
              componentType: componentType,
            },
            hasVertexColors: hasVertexColors,
            hasMorphTargets: hasMorphTargets,
            hasNormals: hasNormals,
            hasTangents: hasTangents,
            hasTexCoords: hasTexCoords,
            hasTexCoord1: hasTexCoord1,
            hasOutline: hasOutline,
          };
        } else if (
          primitiveInfo.skinning.skinned !== isSkinned ||
          primitiveInfo.hasVertexColors !== hasVertexColors ||
          primitiveInfo.hasMorphTargets !== hasMorphTargets ||
          primitiveInfo.hasNormals !== hasNormals ||
          primitiveInfo.hasTangents !== hasTangents ||
          primitiveInfo.hasTexCoords !== hasTexCoords ||
          primitiveInfo.hasTexCoord1 !== hasTexCoord1 ||
          primitiveInfo.hasOutline !== hasOutline
        ) {
          // This primitive uses the same material as another one that either:
          // * Isn't skinned
          // * Uses a different type to store joints and weights
          // * Doesn't have vertex colors, morph targets, normals, tangents, or texCoords
          // * Doesn't have a CESIUM_primitive_outline extension.
          const clonedMaterial = clone$1(material, true);
          // Split this off as a separate material
          materialIndex = addToArray(materials, clonedMaterial);
          primitive.material = materialIndex;
          primitiveInfoByMaterial[materialIndex] = {
            skinning: {
              skinned: isSkinned,
              componentType: componentType,
            },
            hasVertexColors: hasVertexColors,
            hasMorphTargets: hasMorphTargets,
            hasNormals: hasNormals,
            hasTangents: hasTangents,
            hasTexCoords: hasTexCoords,
            hasTexCoord1: hasTexCoord1,
            hasOutline: hasOutline,
          };
        }
      });
    });

    return primitiveInfoByMaterial;
  };

  ModelUtility.getShaderVariable = function (type) {
    if (type === "SCALAR") {
      return "float";
    }
    return type.toLowerCase();
  };

  ModelUtility.ModelState = {
    NEEDS_LOAD: 0,
    LOADING: 1,
    LOADED: 2, // Renderable, but textures can still be pending when incrementallyLoadTextures is true.
    FAILED: 3,
  };

  ModelUtility.getFailedLoadFunction = function (model, type, path) {
    return function (error) {
      model._state = ModelUtility.ModelState.FAILED;
      let message = `Failed to load ${type}: ${path}`;
      if (defined(error)) {
        message += `\n${error.message}`;
      }
      model._readyPromise.reject(new RuntimeError(message));
    };
  };

  ModelUtility.parseBuffers = function (model, bufferLoad) {
    const loadResources = model._loadResources;

    ForEach.buffer(model.gltfInternal, function (buffer, bufferViewId) {
      if (defined(buffer.extras._pipeline.source)) {
        loadResources.buffers[bufferViewId] = buffer.extras._pipeline.source;
      } else if (defined(bufferLoad)) {
        const bufferResource = model._resource.getDerivedResource({
          url: buffer.uri,
        });
        ++loadResources.pendingBufferLoads;
        bufferResource
          .fetchArrayBuffer()
          .then(bufferLoad(model, bufferViewId))
          .catch(
            ModelUtility.getFailedLoadFunction(
              model,
              "buffer",
              bufferResource.url
            )
          );
      }
    });
  };

  const aMinScratch = new Cartesian3();
  const aMaxScratch = new Cartesian3();

  ModelUtility.computeBoundingSphere = function (model) {
    const gltf = model.gltfInternal;
    const gltfNodes = gltf.nodes;
    const gltfMeshes = gltf.meshes;
    const rootNodes = gltf.scenes[gltf.scene].nodes;
    const rootNodesLength = rootNodes.length;

    const nodeStack = [];

    const min = new Cartesian3(
      Number.MAX_VALUE,
      Number.MAX_VALUE,
      Number.MAX_VALUE
    );
    const max = new Cartesian3(
      -Number.MAX_VALUE,
      -Number.MAX_VALUE,
      -Number.MAX_VALUE
    );

    for (let i = 0; i < rootNodesLength; ++i) {
      let n = gltfNodes[rootNodes[i]];
      n._transformToRoot = ModelUtility.getTransform(n);
      nodeStack.push(n);

      while (nodeStack.length > 0) {
        n = nodeStack.pop();
        const transformToRoot = n._transformToRoot;

        const meshId = n.mesh;
        if (defined(meshId)) {
          const mesh = gltfMeshes[meshId];
          const primitives = mesh.primitives;
          const primitivesLength = primitives.length;
          for (let m = 0; m < primitivesLength; ++m) {
            const positionAccessor = primitives[m].attributes.POSITION;
            if (defined(positionAccessor)) {
              const minMax = ModelUtility.getAccessorMinMax(
                gltf,
                positionAccessor
              );
              if (defined(minMax.min) && defined(minMax.max)) {
                const aMin = Cartesian3.fromArray(minMax.min, 0, aMinScratch);
                const aMax = Cartesian3.fromArray(minMax.max, 0, aMaxScratch);

                Matrix4.multiplyByPoint(transformToRoot, aMin, aMin);
                Matrix4.multiplyByPoint(transformToRoot, aMax, aMax);
                Cartesian3.minimumByComponent(min, aMin, min);
                Cartesian3.maximumByComponent(max, aMax, max);
              }
            }
          }
        }

        const children = n.children;
        if (defined(children)) {
          const childrenLength = children.length;
          for (let k = 0; k < childrenLength; ++k) {
            const child = gltfNodes[children[k]];
            child._transformToRoot = ModelUtility.getTransform(child);
            Matrix4.multiplyTransformation(
              transformToRoot,
              child._transformToRoot,
              child._transformToRoot
            );
            nodeStack.push(child);
          }
        }
        delete n._transformToRoot;
      }
    }

    const boundingSphere = BoundingSphere.fromCornerPoints(min, max);
    if (model.forwardAxis === Axis$1.Z) {
      // glTF 2.0 has a Z-forward convention that must be adapted here to X-forward.
      BoundingSphere.transformWithoutScale(
        boundingSphere,
        Axis$1.Z_UP_TO_X_UP,
        boundingSphere
      );
    }
    if (model._upAxis === Axis$1.Y) {
      BoundingSphere.transformWithoutScale(
        boundingSphere,
        Axis$1.Y_UP_TO_Z_UP,
        boundingSphere
      );
    } else if (model._upAxis === Axis$1.X) {
      BoundingSphere.transformWithoutScale(
        boundingSphere,
        Axis$1.X_UP_TO_Z_UP,
        boundingSphere
      );
    }
    return boundingSphere;
  };

  function techniqueAttributeForSemantic(technique, semantic) {
    return ForEach.techniqueAttribute(technique, function (
      attribute,
      attributeName
    ) {
      if (attribute.semantic === semantic) {
        return attributeName;
      }
    });
  }

  function ensureSemanticExistenceForPrimitive(gltf, primitive) {
    const accessors = gltf.accessors;
    const materials = gltf.materials;
    const techniquesWebgl = gltf.extensions.KHR_techniques_webgl;

    const techniques = techniquesWebgl.techniques;
    const programs = techniquesWebgl.programs;
    const shaders = techniquesWebgl.shaders;
    const targets = primitive.targets;

    const attributes = primitive.attributes;
    for (const target in targets) {
      if (targets.hasOwnProperty(target)) {
        const targetAttributes = targets[target];
        for (const attribute in targetAttributes) {
          if (attribute !== "extras") {
            attributes[`${attribute}_${target}`] = targetAttributes[attribute];
          }
        }
      }
    }

    const material = materials[primitive.material];
    const technique =
      techniques[material.extensions.KHR_techniques_webgl.technique];
    const program = programs[technique.program];
    const vertexShader = shaders[program.vertexShader];

    for (const semantic in attributes) {
      if (attributes.hasOwnProperty(semantic)) {
        if (!defined(techniqueAttributeForSemantic(technique, semantic))) {
          const accessorId = attributes[semantic];
          const accessor = accessors[accessorId];
          let lowerCase = semantic.toLowerCase();
          if (lowerCase.charAt(0) === "_") {
            lowerCase = lowerCase.slice(1);
          }
          const attributeName = `a_${lowerCase}`;
          technique.attributes[attributeName] = {
            semantic: semantic,
            type: accessor.componentType,
          };
          const pipelineExtras = vertexShader.extras._pipeline;
          let shaderText = pipelineExtras.source;
          shaderText = `attribute ${ModelUtility.getShaderVariable(
          accessor.type
        )} ${attributeName};\n${shaderText}`;
          pipelineExtras.source = shaderText;
        }
      }
    }
  }

  /**
   * Ensures all attributes present on the primitive are present in the technique and
   * vertex shader.
   *
   * @param {Object} gltf A javascript object containing a glTF asset.
   * @returns {Object} The glTF asset, including any additional attributes.
   */
  ModelUtility.ensureSemanticExistence = function (gltf) {
    ForEach.mesh(gltf, function (mesh) {
      ForEach.meshPrimitive(mesh, function (primitive) {
        ensureSemanticExistenceForPrimitive(gltf, primitive);
      });
    });

    return gltf;
  };

  /**
   * Creates attribute location for all attributes required by a technique.
   *
   * @param {Object} technique A glTF KHR_techniques_webgl technique object.
   * @param {Object} precreatedAttributes A dictionary object of pre-created attributes for which to also create locations.
   * @returns {Object} A dictionary object containing attribute names and their locations.
   */
  ModelUtility.createAttributeLocations = function (
    technique,
    precreatedAttributes
  ) {
    const attributeLocations = {};
    let hasIndex0 = false;
    let i = 1;

    ForEach.techniqueAttribute(technique, function (attribute, attributeName) {
      // Set the position attribute to the 0th index. In some WebGL implementations the shader
      // will not work correctly if the 0th attribute is not active. For example, some glTF models
      // list the normal attribute first but derived shaders like the cast-shadows shader do not use
      // the normal attribute.
      if (/pos/i.test(attributeName) && !hasIndex0) {
        attributeLocations[attributeName] = 0;
        hasIndex0 = true;
      } else {
        attributeLocations[attributeName] = i++;
      }
    });

    if (defined(precreatedAttributes)) {
      for (const attributeName in precreatedAttributes) {
        if (precreatedAttributes.hasOwnProperty(attributeName)) {
          attributeLocations[attributeName] = i++;
        }
      }
    }

    return attributeLocations;
  };

  ModelUtility.getAccessorMinMax = function (gltf, accessorId) {
    const accessor = gltf.accessors[accessorId];
    const extensions = accessor.extensions;
    let accessorMin = accessor.min;
    let accessorMax = accessor.max;
    // If this accessor is quantized, we should use the decoded min and max
    if (defined(extensions)) {
      const quantizedAttributes = extensions.WEB3D_quantized_attributes;
      if (defined(quantizedAttributes)) {
        accessorMin = quantizedAttributes.decodedMin;
        accessorMax = quantizedAttributes.decodedMax;
      }
    }
    return {
      min: accessorMin,
      max: accessorMax,
    };
  };

  function getTechniqueAttributeOrUniformFunction(
    gltf,
    technique,
    semantic,
    ignoreNodes
  ) {
    if (usesExtension(gltf, "KHR_techniques_webgl")) {
      return function (attributeOrUniform, attributeOrUniformName) {
        if (
          attributeOrUniform.semantic === semantic &&
          (!ignoreNodes || !defined(attributeOrUniform.node))
        ) {
          return attributeOrUniformName;
        }
      };
    }

    return function (parameterName, attributeOrUniformName) {
      const attributeOrUniform = technique.parameters[parameterName];
      if (
        attributeOrUniform.semantic === semantic &&
        (!ignoreNodes || !defined(attributeOrUniform.node))
      ) {
        return attributeOrUniformName;
      }
    };
  }

  ModelUtility.getAttributeOrUniformBySemantic = function (
    gltf,
    semantic,
    programId,
    ignoreNodes
  ) {
    return ForEach.technique(gltf, function (technique) {
      if (defined(programId) && technique.program !== programId) {
        return;
      }

      const value = ForEach.techniqueAttribute(
        technique,
        getTechniqueAttributeOrUniformFunction(
          gltf,
          technique,
          semantic,
          ignoreNodes
        )
      );

      if (defined(value)) {
        return value;
      }

      return ForEach.techniqueUniform(
        technique,
        getTechniqueAttributeOrUniformFunction(
          gltf,
          technique,
          semantic,
          ignoreNodes
        )
      );
    });
  };

  ModelUtility.getDiffuseAttributeOrUniform = function (gltf, programId) {
    let diffuseUniformName = ModelUtility.getAttributeOrUniformBySemantic(
      gltf,
      "COLOR_0",
      programId
    );
    if (!defined(diffuseUniformName)) {
      diffuseUniformName = ModelUtility.getAttributeOrUniformBySemantic(
        gltf,
        "_3DTILESDIFFUSE",
        programId
      );
    }
    return diffuseUniformName;
  };

  const nodeTranslationScratch = new Cartesian3();
  const nodeQuaternionScratch = new Quaternion();
  const nodeScaleScratch = new Cartesian3();

  ModelUtility.getTransform = function (node, result) {
    if (defined(node.matrix)) {
      return Matrix4.fromColumnMajorArray(node.matrix, result);
    }

    return Matrix4.fromTranslationQuaternionRotationScale(
      Cartesian3.fromArray(node.translation, 0, nodeTranslationScratch),
      Quaternion.unpack(node.rotation, 0, nodeQuaternionScratch),
      Cartesian3.fromArray(node.scale, 0, nodeScaleScratch),
      result
    );
  };

  ModelUtility.getUsedExtensions = function (gltf) {
    const extensionsUsed = gltf.extensionsUsed;
    const cachedExtensionsUsed = {};

    if (defined(extensionsUsed)) {
      const extensionsUsedLength = extensionsUsed.length;
      for (let i = 0; i < extensionsUsedLength; i++) {
        const extension = extensionsUsed[i];
        cachedExtensionsUsed[extension] = true;
      }
    }
    return cachedExtensionsUsed;
  };

  ModelUtility.getRequiredExtensions = function (gltf) {
    const extensionsRequired = gltf.extensionsRequired;
    const cachedExtensionsRequired = {};

    if (defined(extensionsRequired)) {
      const extensionsRequiredLength = extensionsRequired.length;
      for (let i = 0; i < extensionsRequiredLength; i++) {
        const extension = extensionsRequired[i];
        cachedExtensionsRequired[extension] = true;
      }
    }

    return cachedExtensionsRequired;
  };

  ModelUtility.supportedExtensions = {
    AGI_articulations: true,
    CESIUM_RTC: true,
    EXT_texture_webp: true,
    KHR_blend: true,
    KHR_binary_glTF: true,
    KHR_texture_basisu: true,
    KHR_draco_mesh_compression: true,
    KHR_materials_common: true,
    KHR_techniques_webgl: true,
    KHR_materials_unlit: true,
    KHR_materials_pbrSpecularGlossiness: true,
    KHR_texture_transform: true,
    WEB3D_quantized_attributes: true,
  };

  ModelUtility.checkSupportedExtensions = function (
    extensionsRequired,
    browserSupportsWebp
  ) {
    for (const extension in extensionsRequired) {
      if (extensionsRequired.hasOwnProperty(extension)) {
        if (!ModelUtility.supportedExtensions[extension]) {
          throw new RuntimeError(`Unsupported glTF Extension: ${extension}`);
        }

        if (extension === "EXT_texture_webp" && browserSupportsWebp === false) {
          throw new RuntimeError(
            "Loaded model requires WebP but browser does not support it."
          );
        }
      }
    }
  };

  ModelUtility.checkSupportedGlExtensions = function (extensionsUsed, context) {
    if (defined(extensionsUsed)) {
      const glExtensionsUsedLength = extensionsUsed.length;
      for (let i = 0; i < glExtensionsUsedLength; i++) {
        const extension = extensionsUsed[i];
        if (extension !== "OES_element_index_uint") {
          throw new RuntimeError(`Unsupported WebGL Extension: ${extension}`);
        } else if (!context.elementIndexUint) {
          throw new RuntimeError(
            "OES_element_index_uint WebGL extension is not enabled."
          );
        }
      }
    }
  };

  function replaceAllButFirstInString(string, find, replace) {
    // Limit search to strings that are not a subset of other tokens.
    find += "(?!\\w)";
    find = new RegExp(find, "g");

    const index = string.search(find);
    return string.replace(find, function (match, offset) {
      return index === offset ? match : replace;
    });
  }

  function getQuantizedAttributes(gltf, accessorId) {
    const accessor = gltf.accessors[accessorId];
    const extensions = accessor.extensions;
    if (defined(extensions)) {
      return extensions.WEB3D_quantized_attributes;
    }
    return undefined;
  }

  function getAttributeVariableName(gltf, primitive, attributeSemantic) {
    const materialId = primitive.material;
    const material = gltf.materials[materialId];

    if (
      !usesExtension(gltf, "KHR_techniques_webgl") ||
      !defined(material.extensions) ||
      !defined(material.extensions.KHR_techniques_webgl)
    ) {
      return;
    }

    const techniqueId = material.extensions.KHR_techniques_webgl.technique;
    const techniquesWebgl = gltf.extensions.KHR_techniques_webgl;
    const technique = techniquesWebgl.techniques[techniqueId];
    return ForEach.techniqueAttribute(technique, function (
      attribute,
      attributeName
    ) {
      const semantic = attribute.semantic;
      if (semantic === attributeSemantic) {
        return attributeName;
      }
    });
  }

  ModelUtility.modifyShaderForDracoQuantizedAttributes = function (
    gltf,
    primitive,
    shader,
    decodedAttributes
  ) {
    const quantizedUniforms = {};
    for (let attributeSemantic in decodedAttributes) {
      if (decodedAttributes.hasOwnProperty(attributeSemantic)) {
        const attribute = decodedAttributes[attributeSemantic];
        const quantization = attribute.quantization;
        if (!defined(quantization)) {
          continue;
        }

        const attributeVarName = getAttributeVariableName(
          gltf,
          primitive,
          attributeSemantic
        );

        if (attributeSemantic.charAt(0) === "_") {
          attributeSemantic = attributeSemantic.substring(1);
        }
        const decodeUniformVarName = `gltf_u_dec_${attributeSemantic.toLowerCase()}`;

        if (!defined(quantizedUniforms[decodeUniformVarName])) {
          const newMain = `gltf_decoded_${attributeSemantic}`;
          const decodedAttributeVarName = attributeVarName.replace(
            "a_",
            "gltf_a_dec_"
          );
          const size = attribute.componentsPerAttribute;

          // replace usages of the original attribute with the decoded version, but not the declaration
          shader = replaceAllButFirstInString(
            shader,
            attributeVarName,
            decodedAttributeVarName
          );

          // declare decoded attribute
          let variableType;
          if (quantization.octEncoded) {
            variableType = "vec3";
          } else if (size > 1) {
            variableType = `vec${size}`;
          } else {
            variableType = "float";
          }
          shader = `${variableType} ${decodedAttributeVarName};\n${shader}`;

          // The gltf 2.0 COLOR_0 vertex attribute can be VEC4 or VEC3
          const vec3Color = size === 3 && attributeSemantic === "COLOR_0";
          if (vec3Color) {
            shader = replaceAllButFirstInString(
              shader,
              decodedAttributeVarName,
              `vec4(${decodedAttributeVarName}, 1.0)`
            );
          }

          // splice decode function into the shader
          let decode = "";
          if (quantization.octEncoded) {
            const decodeUniformVarNameRangeConstant = `${decodeUniformVarName}_rangeConstant`;
            shader = `uniform float ${decodeUniformVarNameRangeConstant};\n${shader}`;
            decode =
              `${
              "\n" +
              "void main() {\n" +
              // Draco oct-encoding decodes to zxy order
              "    "
            }${decodedAttributeVarName} = czm_octDecode(${attributeVarName}.xy, ${decodeUniformVarNameRangeConstant}).zxy;\n` +
              `    ${newMain}();\n` +
              `}\n`;
          } else {
            const decodeUniformVarNameNormConstant = `${decodeUniformVarName}_normConstant`;
            const decodeUniformVarNameMin = `${decodeUniformVarName}_min`;
            shader =
              `uniform float ${decodeUniformVarNameNormConstant};\n` +
              `uniform ${variableType} ${decodeUniformVarNameMin};\n${shader}`;
            const attributeVarAccess = vec3Color ? ".xyz" : "";
            decode =
              `${
              "\n" + "void main() {\n" + "    "
            }${decodedAttributeVarName} = ${decodeUniformVarNameMin} + ${attributeVarName}${attributeVarAccess} * ${decodeUniformVarNameNormConstant};\n` +
              `    ${newMain}();\n` +
              `}\n`;
          }

          shader = ShaderSource.replaceMain(shader, newMain);
          shader += decode;
        }
      }
    }
    return {
      shader: shader,
    };
  };

  ModelUtility.modifyShaderForQuantizedAttributes = function (
    gltf,
    primitive,
    shader
  ) {
    const quantizedUniforms = {};
    const attributes = primitive.attributes;
    for (let attributeSemantic in attributes) {
      if (attributes.hasOwnProperty(attributeSemantic)) {
        const attributeVarName = getAttributeVariableName(
          gltf,
          primitive,
          attributeSemantic
        );
        const accessorId = primitive.attributes[attributeSemantic];

        if (attributeSemantic.charAt(0) === "_") {
          attributeSemantic = attributeSemantic.substring(1);
        }
        const decodeUniformVarName = `gltf_u_dec_${attributeSemantic.toLowerCase()}`;

        const decodeUniformVarNameScale = `${decodeUniformVarName}_scale`;
        const decodeUniformVarNameTranslate = `${decodeUniformVarName}_translate`;
        if (
          !defined(quantizedUniforms[decodeUniformVarName]) &&
          !defined(quantizedUniforms[decodeUniformVarNameScale])
        ) {
          const quantizedAttributes = getQuantizedAttributes(gltf, accessorId);
          if (defined(quantizedAttributes)) {
            const decodeMatrix = quantizedAttributes.decodeMatrix;
            const newMain = `gltf_decoded_${attributeSemantic}`;
            const decodedAttributeVarName = attributeVarName.replace(
              "a_",
              "gltf_a_dec_"
            );
            const size = Math.floor(Math.sqrt(decodeMatrix.length));

            // replace usages of the original attribute with the decoded version, but not the declaration
            shader = replaceAllButFirstInString(
              shader,
              attributeVarName,
              decodedAttributeVarName
            );
            // declare decoded attribute
            let variableType;
            if (size > 2) {
              variableType = `vec${size - 1}`;
            } else {
              variableType = "float";
            }
            shader = `${variableType} ${decodedAttributeVarName};\n${shader}`;
            // splice decode function into the shader - attributes are pre-multiplied with the decode matrix
            // uniform in the shader (32-bit floating point)
            let decode = "";
            if (size === 5) {
              // separate scale and translate since glsl doesn't have mat5
              shader = `uniform mat4 ${decodeUniformVarNameScale};\n${shader}`;
              shader = `uniform vec4 ${decodeUniformVarNameTranslate};\n${shader}`;
              decode =
                `${
                "\n" + "void main() {\n" + "    "
              }${decodedAttributeVarName} = ${decodeUniformVarNameScale} * ${attributeVarName} + ${decodeUniformVarNameTranslate};\n` +
                `    ${newMain}();\n` +
                `}\n`;

              quantizedUniforms[decodeUniformVarNameScale] = { mat: 4 };
              quantizedUniforms[decodeUniformVarNameTranslate] = { vec: 4 };
            } else {
              shader = `uniform mat${size} ${decodeUniformVarName};\n${shader}`;
              decode =
                `${
                "\n" + "void main() {\n" + "    "
              }${decodedAttributeVarName} = ${variableType}(${decodeUniformVarName} * vec${size}(${attributeVarName},1.0));\n` +
                `    ${newMain}();\n` +
                `}\n`;

              quantizedUniforms[decodeUniformVarName] = { mat: size };
            }
            shader = ShaderSource.replaceMain(shader, newMain);
            shader += decode;
          }
        }
      }
    }
    return {
      shader: shader,
      uniforms: quantizedUniforms,
    };
  };

  function getScalarUniformFunction(value) {
    const that = {
      value: value,
      clone: function (source, result) {
        return source;
      },
      func: function () {
        return that.value;
      },
    };
    return that;
  }

  function getVec2UniformFunction(value) {
    const that = {
      value: Cartesian2.fromArray(value),
      clone: Cartesian2.clone,
      func: function () {
        return that.value;
      },
    };
    return that;
  }

  function getVec3UniformFunction(value) {
    const that = {
      value: Cartesian3.fromArray(value),
      clone: Cartesian3.clone,
      func: function () {
        return that.value;
      },
    };
    return that;
  }

  function getVec4UniformFunction(value) {
    const that = {
      value: Cartesian4.fromArray(value),
      clone: Cartesian4.clone,
      func: function () {
        return that.value;
      },
    };
    return that;
  }

  function getMat2UniformFunction(value) {
    const that = {
      value: Matrix2.fromColumnMajorArray(value),
      clone: Matrix2.clone,
      func: function () {
        return that.value;
      },
    };
    return that;
  }

  function getMat3UniformFunction(value) {
    const that = {
      value: Matrix3.fromColumnMajorArray(value),
      clone: Matrix3.clone,
      func: function () {
        return that.value;
      },
    };
    return that;
  }

  function getMat4UniformFunction(value) {
    const that = {
      value: Matrix4.fromColumnMajorArray(value),
      clone: Matrix4.clone,
      func: function () {
        return that.value;
      },
    };
    return that;
  }

  ///////////////////////////////////////////////////////////////////////////

  function DelayLoadedTextureUniform(value, textures, defaultTexture) {
    this._value = undefined;
    this._textureId = value.index;
    this._textures = textures;
    this._defaultTexture = defaultTexture;
  }

  Object.defineProperties(DelayLoadedTextureUniform.prototype, {
    value: {
      get: function () {
        // Use the default texture (1x1 white) until the model's texture is loaded
        if (!defined(this._value)) {
          const texture = this._textures[this._textureId];
          if (defined(texture)) {
            this._value = texture;
          } else {
            return this._defaultTexture;
          }
        }

        return this._value;
      },
      set: function (value) {
        this._value = value;
      },
    },
  });

  DelayLoadedTextureUniform.prototype.clone = function (source) {
    return source;
  };

  DelayLoadedTextureUniform.prototype.func = undefined;

  ///////////////////////////////////////////////////////////////////////////

  function getTextureUniformFunction(value, textures, defaultTexture) {
    const uniform = new DelayLoadedTextureUniform(
      value,
      textures,
      defaultTexture
    );
    // Define function here to access closure since 'this' can't be
    // used when the Renderer sets uniforms.
    uniform.func = function () {
      return uniform.value;
    };
    return uniform;
  }

  const gltfUniformFunctions = {};
  gltfUniformFunctions[WebGLConstants$1.FLOAT] = getScalarUniformFunction;
  gltfUniformFunctions[WebGLConstants$1.FLOAT_VEC2] = getVec2UniformFunction;
  gltfUniformFunctions[WebGLConstants$1.FLOAT_VEC3] = getVec3UniformFunction;
  gltfUniformFunctions[WebGLConstants$1.FLOAT_VEC4] = getVec4UniformFunction;
  gltfUniformFunctions[WebGLConstants$1.INT] = getScalarUniformFunction;
  gltfUniformFunctions[WebGLConstants$1.INT_VEC2] = getVec2UniformFunction;
  gltfUniformFunctions[WebGLConstants$1.INT_VEC3] = getVec3UniformFunction;
  gltfUniformFunctions[WebGLConstants$1.INT_VEC4] = getVec4UniformFunction;
  gltfUniformFunctions[WebGLConstants$1.BOOL] = getScalarUniformFunction;
  gltfUniformFunctions[WebGLConstants$1.BOOL_VEC2] = getVec2UniformFunction;
  gltfUniformFunctions[WebGLConstants$1.BOOL_VEC3] = getVec3UniformFunction;
  gltfUniformFunctions[WebGLConstants$1.BOOL_VEC4] = getVec4UniformFunction;
  gltfUniformFunctions[WebGLConstants$1.FLOAT_MAT2] = getMat2UniformFunction;
  gltfUniformFunctions[WebGLConstants$1.FLOAT_MAT3] = getMat3UniformFunction;
  gltfUniformFunctions[WebGLConstants$1.FLOAT_MAT4] = getMat4UniformFunction;
  gltfUniformFunctions[WebGLConstants$1.SAMPLER_2D] = getTextureUniformFunction;
  // GLTF_SPEC: Support SAMPLER_CUBE. https://github.com/KhronosGroup/glTF/issues/40

  ModelUtility.createUniformFunction = function (
    type,
    value,
    textures,
    defaultTexture
  ) {
    return gltfUniformFunctions[type](value, textures, defaultTexture);
  };

  function scaleFromMatrix5Array(matrix) {
    return [
      matrix[0],
      matrix[1],
      matrix[2],
      matrix[3],
      matrix[5],
      matrix[6],
      matrix[7],
      matrix[8],
      matrix[10],
      matrix[11],
      matrix[12],
      matrix[13],
      matrix[15],
      matrix[16],
      matrix[17],
      matrix[18],
    ];
  }

  function translateFromMatrix5Array(matrix) {
    return [matrix[20], matrix[21], matrix[22], matrix[23]];
  }

  ModelUtility.createUniformsForDracoQuantizedAttributes = function (
    decodedAttributes
  ) {
    const uniformMap = {};
    for (let attribute in decodedAttributes) {
      if (decodedAttributes.hasOwnProperty(attribute)) {
        const decodedData = decodedAttributes[attribute];
        const quantization = decodedData.quantization;

        if (!defined(quantization)) {
          continue;
        }

        if (attribute.charAt(0) === "_") {
          attribute = attribute.substring(1);
        }

        const uniformVarName = `gltf_u_dec_${attribute.toLowerCase()}`;

        if (quantization.octEncoded) {
          const uniformVarNameRangeConstant = `${uniformVarName}_rangeConstant`;
          const rangeConstant = (1 << quantization.quantizationBits) - 1.0;
          uniformMap[uniformVarNameRangeConstant] = getScalarUniformFunction(
            rangeConstant
          ).func;
          continue;
        }

        const uniformVarNameNormConstant = `${uniformVarName}_normConstant`;
        const normConstant =
          quantization.range / (1 << quantization.quantizationBits);
        uniformMap[uniformVarNameNormConstant] = getScalarUniformFunction(
          normConstant
        ).func;

        const uniformVarNameMin = `${uniformVarName}_min`;
        switch (decodedData.componentsPerAttribute) {
          case 1:
            uniformMap[uniformVarNameMin] = getScalarUniformFunction(
              quantization.minValues
            ).func;
            break;
          case 2:
            uniformMap[uniformVarNameMin] = getVec2UniformFunction(
              quantization.minValues
            ).func;
            break;
          case 3:
            uniformMap[uniformVarNameMin] = getVec3UniformFunction(
              quantization.minValues
            ).func;
            break;
          case 4:
            uniformMap[uniformVarNameMin] = getVec4UniformFunction(
              quantization.minValues
            ).func;
            break;
        }
      }
    }

    return uniformMap;
  };

  ModelUtility.createUniformsForQuantizedAttributes = function (
    gltf,
    primitive,
    quantizedUniforms
  ) {
    const accessors = gltf.accessors;
    const setUniforms = {};
    const uniformMap = {};

    const attributes = primitive.attributes;
    for (let attribute in attributes) {
      if (attributes.hasOwnProperty(attribute)) {
        const accessorId = attributes[attribute];
        const a = accessors[accessorId];
        const extensions = a.extensions;

        if (attribute.charAt(0) === "_") {
          attribute = attribute.substring(1);
        }

        if (defined(extensions)) {
          const quantizedAttributes = extensions.WEB3D_quantized_attributes;
          if (defined(quantizedAttributes)) {
            const decodeMatrix = quantizedAttributes.decodeMatrix;
            const uniformVariable = `gltf_u_dec_${attribute.toLowerCase()}`;
            let uniformVariableScale;
            let uniformVariableTranslate;
            switch (a.type) {
              case AttributeType$1.SCALAR:
                uniformMap[uniformVariable] = getMat2UniformFunction(
                  decodeMatrix
                ).func;
                setUniforms[uniformVariable] = true;
                break;
              case AttributeType$1.VEC2:
                uniformMap[uniformVariable] = getMat3UniformFunction(
                  decodeMatrix
                ).func;
                setUniforms[uniformVariable] = true;
                break;
              case AttributeType$1.VEC3:
                uniformMap[uniformVariable] = getMat4UniformFunction(
                  decodeMatrix
                ).func;
                setUniforms[uniformVariable] = true;
                break;
              case AttributeType$1.VEC4:
                // VEC4 attributes are split into scale and translate because there is no mat5 in GLSL
                uniformVariableScale = `${uniformVariable}_scale`;
                uniformVariableTranslate = `${uniformVariable}_translate`;
                uniformMap[uniformVariableScale] = getMat4UniformFunction(
                  scaleFromMatrix5Array(decodeMatrix)
                ).func;
                uniformMap[uniformVariableTranslate] = getVec4UniformFunction(
                  translateFromMatrix5Array(decodeMatrix)
                ).func;
                setUniforms[uniformVariableScale] = true;
                setUniforms[uniformVariableTranslate] = true;
                break;
            }
          }
        }
      }
    }

    // If there are any unset quantized uniforms in this program, they should be set to the identity
    for (const quantizedUniform in quantizedUniforms) {
      if (quantizedUniforms.hasOwnProperty(quantizedUniform)) {
        if (!setUniforms[quantizedUniform]) {
          const properties = quantizedUniforms[quantizedUniform];
          if (defined(properties.mat)) {
            if (properties.mat === 2) {
              uniformMap[quantizedUniform] = getMat2UniformFunction(
                Matrix2.IDENTITY
              ).func;
            } else if (properties.mat === 3) {
              uniformMap[quantizedUniform] = getMat3UniformFunction(
                Matrix3.IDENTITY
              ).func;
            } else if (properties.mat === 4) {
              uniformMap[quantizedUniform] = getMat4UniformFunction(
                Matrix4.IDENTITY
              ).func;
            }
          }
          if (defined(properties.vec)) {
            if (properties.vec === 4) {
              uniformMap[quantizedUniform] = getVec4UniformFunction([
                0,
                0,
                0,
                0,
              ]).func;
            }
          }
        }
      }
    }
    return uniformMap;
  };

  // This doesn't support LOCAL, which we could add if it is ever used.
  const scratchTranslationRtc = new Cartesian3();
  const gltfSemanticUniforms$1 = {
    MODEL: function (uniformState, model) {
      return function () {
        return uniformState.model;
      };
    },
    VIEW: function (uniformState, model) {
      return function () {
        return uniformState.view;
      };
    },
    PROJECTION: function (uniformState, model) {
      return function () {
        return uniformState.projection;
      };
    },
    MODELVIEW: function (uniformState, model) {
      return function () {
        return uniformState.modelView;
      };
    },
    CESIUM_RTC_MODELVIEW: function (uniformState, model) {
      // CESIUM_RTC extension
      const mvRtc = new Matrix4();
      return function () {
        if (defined(model._rtcCenter)) {
          Matrix4.getTranslation(uniformState.model, scratchTranslationRtc);
          Cartesian3.add(
            scratchTranslationRtc,
            model._rtcCenter,
            scratchTranslationRtc
          );
          Matrix4.multiplyByPoint(
            uniformState.view,
            scratchTranslationRtc,
            scratchTranslationRtc
          );
          return Matrix4.setTranslation(
            uniformState.modelView,
            scratchTranslationRtc,
            mvRtc
          );
        }
        return uniformState.modelView;
      };
    },
    MODELVIEWPROJECTION: function (uniformState, model) {
      return function () {
        return uniformState.modelViewProjection;
      };
    },
    MODELINVERSE: function (uniformState, model) {
      return function () {
        return uniformState.inverseModel;
      };
    },
    VIEWINVERSE: function (uniformState, model) {
      return function () {
        return uniformState.inverseView;
      };
    },
    PROJECTIONINVERSE: function (uniformState, model) {
      return function () {
        return uniformState.inverseProjection;
      };
    },
    MODELVIEWINVERSE: function (uniformState, model) {
      return function () {
        return uniformState.inverseModelView;
      };
    },
    MODELVIEWPROJECTIONINVERSE: function (uniformState, model) {
      return function () {
        return uniformState.inverseModelViewProjection;
      };
    },
    MODELINVERSETRANSPOSE: function (uniformState, model) {
      return function () {
        return uniformState.inverseTransposeModel;
      };
    },
    MODELVIEWINVERSETRANSPOSE: function (uniformState, model) {
      return function () {
        return uniformState.normal;
      };
    },
    VIEWPORT: function (uniformState, model) {
      return function () {
        return uniformState.viewportCartesian4;
      };
    },
    // JOINTMATRIX created in createCommand()
  };

  ModelUtility.getGltfSemanticUniforms = function () {
    return gltfSemanticUniforms$1;
  };

  /**
   * @private
   */
  function processModelMaterialsCommon(gltf, options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    if (!defined(gltf)) {
      return;
    }

    if (!usesExtension(gltf, "KHR_materials_common")) {
      return;
    }

    if (!usesExtension(gltf, "KHR_techniques_webgl")) {
      if (!defined(gltf.extensions)) {
        gltf.extensions = {};
      }

      gltf.extensions.KHR_techniques_webgl = {
        programs: [],
        shaders: [],
        techniques: [],
      };
      gltf.extensionsUsed.push("KHR_techniques_webgl");
      gltf.extensionsRequired.push("KHR_techniques_webgl");
    }

    const techniquesWebgl = gltf.extensions.KHR_techniques_webgl;

    lightDefaults(gltf);

    const lightParameters = generateLightParameters(gltf);

    const primitiveByMaterial = ModelUtility.splitIncompatibleMaterials(gltf);

    const techniques = {};
    let generatedTechniques = false;
    ForEach.material(gltf, function (material, materialIndex) {
      if (
        defined(material.extensions) &&
        defined(material.extensions.KHR_materials_common)
      ) {
        const khrMaterialsCommon = material.extensions.KHR_materials_common;
        const primitiveInfo = primitiveByMaterial[materialIndex];

        const techniqueKey = getTechniqueKey(khrMaterialsCommon, primitiveInfo);
        let technique = techniques[techniqueKey];

        if (!defined(technique)) {
          technique = generateTechnique$1(
            gltf,
            techniquesWebgl,
            primitiveInfo,
            khrMaterialsCommon,
            lightParameters,
            options.addBatchIdToGeneratedShaders
          );
          techniques[techniqueKey] = technique;
          generatedTechniques = true;
        }

        const materialValues = {};
        const values = khrMaterialsCommon.values;
        let uniformName;
        for (const valueName in values) {
          if (
            values.hasOwnProperty(valueName) &&
            valueName !== "transparent" &&
            valueName !== "doubleSided"
          ) {
            uniformName = `u_${valueName.toLowerCase()}`;
            materialValues[uniformName] = values[valueName];
          }
        }

        material.extensions.KHR_techniques_webgl = {
          technique: technique,
          values: materialValues,
        };

        material.alphaMode = "OPAQUE";
        if (khrMaterialsCommon.transparent) {
          material.alphaMode = "BLEND";
        }

        if (khrMaterialsCommon.doubleSided) {
          material.doubleSided = true;
        }
      }
    });

    if (!generatedTechniques) {
      return gltf;
    }

    // If any primitives have semantics that aren't declared in the generated
    // shaders, we want to preserve them.
    ModelUtility.ensureSemanticExistence(gltf);

    return gltf;
  }

  function generateLightParameters(gltf) {
    const result = {};

    let lights;
    if (
      defined(gltf.extensions) &&
      defined(gltf.extensions.KHR_materials_common)
    ) {
      lights = gltf.extensions.KHR_materials_common.lights;
    }

    if (defined(lights)) {
      // Figure out which node references the light
      const nodes = gltf.nodes;
      for (const nodeName in nodes) {
        if (nodes.hasOwnProperty(nodeName)) {
          const node = nodes[nodeName];
          if (
            defined(node.extensions) &&
            defined(node.extensions.KHR_materials_common)
          ) {
            const nodeLightId = node.extensions.KHR_materials_common.light;
            if (defined(nodeLightId) && defined(lights[nodeLightId])) {
              lights[nodeLightId].node = nodeName;
            }
            delete node.extensions.KHR_materials_common;
          }
        }
      }

      // Add light parameters to result
      let lightCount = 0;
      for (const lightName in lights) {
        if (lights.hasOwnProperty(lightName)) {
          const light = lights[lightName];
          const lightType = light.type;
          if (lightType !== "ambient" && !defined(light.node)) {
            delete lights[lightName];
            continue;
          }
          const lightBaseName = `light${lightCount.toString()}`;
          light.baseName = lightBaseName;
          let ambient;
          let directional;
          let point;
          let spot;
          switch (lightType) {
            case "ambient":
              ambient = light.ambient;
              result[`${lightBaseName}Color`] = {
                type: WebGLConstants$1.FLOAT_VEC3,
                value: ambient.color,
              };
              break;
            case "directional":
              directional = light.directional;
              result[`${lightBaseName}Color`] = {
                type: WebGLConstants$1.FLOAT_VEC3,
                value: directional.color,
              };
              if (defined(light.node)) {
                result[`${lightBaseName}Transform`] = {
                  node: light.node,
                  semantic: "MODELVIEW",
                  type: WebGLConstants$1.FLOAT_MAT4,
                };
              }
              break;
            case "point":
              point = light.point;
              result[`${lightBaseName}Color`] = {
                type: WebGLConstants$1.FLOAT_VEC3,
                value: point.color,
              };
              if (defined(light.node)) {
                result[`${lightBaseName}Transform`] = {
                  node: light.node,
                  semantic: "MODELVIEW",
                  type: WebGLConstants$1.FLOAT_MAT4,
                };
              }
              result[`${lightBaseName}Attenuation`] = {
                type: WebGLConstants$1.FLOAT_VEC3,
                value: [
                  point.constantAttenuation,
                  point.linearAttenuation,
                  point.quadraticAttenuation,
                ],
              };
              break;
            case "spot":
              spot = light.spot;
              result[`${lightBaseName}Color`] = {
                type: WebGLConstants$1.FLOAT_VEC3,
                value: spot.color,
              };
              if (defined(light.node)) {
                result[`${lightBaseName}Transform`] = {
                  node: light.node,
                  semantic: "MODELVIEW",
                  type: WebGLConstants$1.FLOAT_MAT4,
                };
                result[`${lightBaseName}InverseTransform`] = {
                  node: light.node,
                  semantic: "MODELVIEWINVERSE",
                  type: WebGLConstants$1.FLOAT_MAT4,
                  useInFragment: true,
                };
              }
              result[`${lightBaseName}Attenuation`] = {
                type: WebGLConstants$1.FLOAT_VEC3,
                value: [
                  spot.constantAttenuation,
                  spot.linearAttenuation,
                  spot.quadraticAttenuation,
                ],
              };

              result[`${lightBaseName}FallOff`] = {
                type: WebGLConstants$1.FLOAT_VEC2,
                value: [spot.fallOffAngle, spot.fallOffExponent],
              };
              break;
          }
          ++lightCount;
        }
      }
    }

    return result;
  }

  function generateTechnique$1(
    gltf,
    techniquesWebgl,
    primitiveInfo,
    khrMaterialsCommon,
    lightParameters,
    addBatchIdToGeneratedShaders
  ) {
    if (!defined(khrMaterialsCommon)) {
      khrMaterialsCommon = {};
    }

    addBatchIdToGeneratedShaders = defaultValue(
      addBatchIdToGeneratedShaders,
      false
    );

    const techniques = techniquesWebgl.techniques;
    const shaders = techniquesWebgl.shaders;
    const programs = techniquesWebgl.programs;
    const lightingModel = khrMaterialsCommon.technique.toUpperCase();
    let lights;
    if (
      defined(gltf.extensions) &&
      defined(gltf.extensions.KHR_materials_common)
    ) {
      lights = gltf.extensions.KHR_materials_common.lights;
    }

    const parameterValues = khrMaterialsCommon.values;
    const jointCount = defaultValue(khrMaterialsCommon.jointCount, 0);

    let skinningInfo;
    let hasSkinning = false;
    let hasVertexColors = false;

    if (defined(primitiveInfo)) {
      skinningInfo = primitiveInfo.skinning;
      hasSkinning = skinningInfo.skinned;
      hasVertexColors = primitiveInfo.hasVertexColors;
    }

    let vertexShader = "precision highp float;\n";
    let fragmentShader = "precision highp float;\n";

    const hasNormals = lightingModel !== "CONSTANT";

    // Add techniques
    const techniqueUniforms = {
      u_modelViewMatrix: {
        semantic: usesExtension(gltf, "CESIUM_RTC")
          ? "CESIUM_RTC_MODELVIEW"
          : "MODELVIEW",
        type: WebGLConstants$1.FLOAT_MAT4,
      },
      u_projectionMatrix: {
        semantic: "PROJECTION",
        type: WebGLConstants$1.FLOAT_MAT4,
      },
    };

    if (hasNormals) {
      techniqueUniforms.u_normalMatrix = {
        semantic: "MODELVIEWINVERSETRANSPOSE",
        type: WebGLConstants$1.FLOAT_MAT3,
      };
    }

    if (hasSkinning) {
      techniqueUniforms.u_jointMatrix = {
        count: jointCount,
        semantic: "JOINTMATRIX",
        type: WebGLConstants$1.FLOAT_MAT4,
      };
    }

    // Add material values
    let uniformName;
    let hasTexCoords = false;
    for (const name in parameterValues) {
      //generate shader parameters for KHR_materials_common attributes
      //(including a check, because some boolean flags should not be used as shader parameters)
      if (
        parameterValues.hasOwnProperty(name) &&
        name !== "transparent" &&
        name !== "doubleSided"
      ) {
        const uniformType = getKHRMaterialsCommonValueType(
          name,
          parameterValues[name]
        );
        uniformName = `u_${name.toLowerCase()}`;
        if (!hasTexCoords && uniformType === WebGLConstants$1.SAMPLER_2D) {
          hasTexCoords = true;
        }

        techniqueUniforms[uniformName] = {
          type: uniformType,
        };
      }
    }

    // Give the diffuse uniform a semantic to support color replacement in 3D Tiles
    if (defined(techniqueUniforms.u_diffuse)) {
      techniqueUniforms.u_diffuse.semantic = "_3DTILESDIFFUSE";
    }

    // Copy light parameters into technique parameters
    if (defined(lightParameters)) {
      for (const lightParamName in lightParameters) {
        if (lightParameters.hasOwnProperty(lightParamName)) {
          uniformName = `u_${lightParamName}`;
          techniqueUniforms[uniformName] = lightParameters[lightParamName];
        }
      }
    }

    // Add uniforms to shaders
    for (uniformName in techniqueUniforms) {
      if (techniqueUniforms.hasOwnProperty(uniformName)) {
        const uniform = techniqueUniforms[uniformName];
        const arraySize = defined(uniform.count) ? `[${uniform.count}]` : "";
        if (
          (uniform.type !== WebGLConstants$1.FLOAT_MAT3 &&
            uniform.type !== WebGLConstants$1.FLOAT_MAT4) ||
          uniform.useInFragment
        ) {
          fragmentShader += `uniform ${webGLConstantToGlslType(
          uniform.type
        )} ${uniformName}${arraySize};\n`;
          delete uniform.useInFragment;
        } else {
          vertexShader += `uniform ${webGLConstantToGlslType(
          uniform.type
        )} ${uniformName}${arraySize};\n`;
        }
      }
    }

    // Add attributes with semantics
    let vertexShaderMain = "";
    if (hasSkinning) {
      vertexShaderMain +=
        "    mat4 skinMatrix =\n" +
        "        a_weight.x * u_jointMatrix[int(a_joint.x)] +\n" +
        "        a_weight.y * u_jointMatrix[int(a_joint.y)] +\n" +
        "        a_weight.z * u_jointMatrix[int(a_joint.z)] +\n" +
        "        a_weight.w * u_jointMatrix[int(a_joint.w)];\n";
    }

    // Add position always
    const techniqueAttributes = {
      a_position: {
        semantic: "POSITION",
      },
    };
    vertexShader += "attribute vec3 a_position;\n";
    vertexShader += "varying vec3 v_positionEC;\n";
    if (hasSkinning) {
      vertexShaderMain +=
        "  vec4 pos = u_modelViewMatrix * skinMatrix * vec4(a_position,1.0);\n";
    } else {
      vertexShaderMain +=
        "  vec4 pos = u_modelViewMatrix * vec4(a_position,1.0);\n";
    }
    vertexShaderMain += "  v_positionEC = pos.xyz;\n";
    vertexShaderMain += "  gl_Position = u_projectionMatrix * pos;\n";
    fragmentShader += "varying vec3 v_positionEC;\n";

    // Add normal if we don't have constant lighting
    if (hasNormals) {
      techniqueAttributes.a_normal = {
        semantic: "NORMAL",
      };
      vertexShader += "attribute vec3 a_normal;\n";
      vertexShader += "varying vec3 v_normal;\n";
      if (hasSkinning) {
        vertexShaderMain +=
          "  v_normal = u_normalMatrix * mat3(skinMatrix) * a_normal;\n";
      } else {
        vertexShaderMain += "  v_normal = u_normalMatrix * a_normal;\n";
      }

      fragmentShader += "varying vec3 v_normal;\n";
    }

    // Add texture coordinates if the material uses them
    let v_texcoord;
    if (hasTexCoords) {
      techniqueAttributes.a_texcoord_0 = {
        semantic: "TEXCOORD_0",
      };

      v_texcoord = "v_texcoord_0";
      vertexShader += "attribute vec2 a_texcoord_0;\n";
      vertexShader += `varying vec2 ${v_texcoord};\n`;
      vertexShaderMain += `  ${v_texcoord} = a_texcoord_0;\n`;

      fragmentShader += `varying vec2 ${v_texcoord};\n`;
    }

    if (hasSkinning) {
      techniqueAttributes.a_joint = {
        semantic: "JOINTS_0",
      };
      techniqueAttributes.a_weight = {
        semantic: "WEIGHTS_0",
      };

      vertexShader += "attribute vec4 a_joint;\n";
      vertexShader += "attribute vec4 a_weight;\n";
    }

    if (hasVertexColors) {
      techniqueAttributes.a_vertexColor = {
        semantic: "COLOR_0",
      };
      vertexShader += "attribute vec4 a_vertexColor;\n";
      vertexShader += "varying vec4 v_vertexColor;\n";
      vertexShaderMain += "  v_vertexColor = a_vertexColor;\n";
      fragmentShader += "varying vec4 v_vertexColor;\n";
    }

    if (addBatchIdToGeneratedShaders) {
      techniqueAttributes.a_batchId = {
        semantic: "_BATCHID",
      };
      vertexShader += "attribute float a_batchId;\n";
    }

    const hasSpecular =
      hasNormals &&
      (lightingModel === "BLINN" || lightingModel === "PHONG") &&
      defined(techniqueUniforms.u_specular) &&
      defined(techniqueUniforms.u_shininess) &&
      techniqueUniforms.u_shininess > 0.0;

    // Generate lighting code blocks
    let hasNonAmbientLights = false;
    let hasAmbientLights = false;
    let fragmentLightingBlock = "";
    for (const lightName in lights) {
      if (lights.hasOwnProperty(lightName)) {
        const light = lights[lightName];
        const lightType = light.type.toLowerCase();
        const lightBaseName = light.baseName;
        fragmentLightingBlock += "  {\n";
        const lightColorName = `u_${lightBaseName}Color`;
        if (lightType === "ambient") {
          hasAmbientLights = true;
          fragmentLightingBlock += `    ambientLight += ${lightColorName};\n`;
        } else if (hasNormals) {
          hasNonAmbientLights = true;
          const varyingDirectionName = `v_${lightBaseName}Direction`;
          const varyingPositionName = `v_${lightBaseName}Position`;

          if (lightType !== "point") {
            vertexShader += `varying vec3 ${varyingDirectionName};\n`;
            fragmentShader += `varying vec3 ${varyingDirectionName};\n`;

            vertexShaderMain += `  ${varyingDirectionName} = mat3(u_${lightBaseName}Transform) * vec3(0.,0.,1.);\n`;
            if (lightType === "directional") {
              fragmentLightingBlock += `    vec3 l = normalize(${varyingDirectionName});\n`;
            }
          }

          if (lightType !== "directional") {
            vertexShader += `varying vec3 ${varyingPositionName};\n`;
            fragmentShader += `varying vec3 ${varyingPositionName};\n`;

            vertexShaderMain += `  ${varyingPositionName} = u_${lightBaseName}Transform[3].xyz;\n`;
            fragmentLightingBlock += `    vec3 VP = ${varyingPositionName} - v_positionEC;\n`;
            fragmentLightingBlock += "    vec3 l = normalize(VP);\n";
            fragmentLightingBlock += "    float range = length(VP);\n";
            fragmentLightingBlock += `    float attenuation = 1.0 / (u_${lightBaseName}Attenuation.x + `;
            fragmentLightingBlock += `(u_${lightBaseName}Attenuation.y * range) + `;
            fragmentLightingBlock += `(u_${lightBaseName}Attenuation.z * range * range));\n`;
          } else {
            fragmentLightingBlock += "    float attenuation = 1.0;\n";
          }

          if (lightType === "spot") {
            fragmentLightingBlock += `    float spotDot = dot(l, normalize(${varyingDirectionName}));\n`;
            fragmentLightingBlock += `    if (spotDot < cos(u_${lightBaseName}FallOff.x * 0.5))\n`;
            fragmentLightingBlock += "    {\n";
            fragmentLightingBlock += "      attenuation = 0.0;\n";
            fragmentLightingBlock += "    }\n";
            fragmentLightingBlock += "    else\n";
            fragmentLightingBlock += "    {\n";
            fragmentLightingBlock += `        attenuation *= max(0.0, pow(spotDot, u_${lightBaseName}FallOff.y));\n`;
            fragmentLightingBlock += "    }\n";
          }

          fragmentLightingBlock += `    diffuseLight += ${lightColorName}* max(dot(normal,l), 0.) * attenuation;\n`;

          if (hasSpecular) {
            if (lightingModel === "BLINN") {
              fragmentLightingBlock += "    vec3 h = normalize(l + viewDir);\n";
              fragmentLightingBlock +=
                "    float specularIntensity = max(0., pow(max(dot(normal, h), 0.), u_shininess)) * attenuation;\n";
            } else {
              // PHONG
              fragmentLightingBlock +=
                "    vec3 reflectDir = reflect(-l, normal);\n";
              fragmentLightingBlock +=
                "    float specularIntensity = max(0., pow(max(dot(reflectDir, viewDir), 0.), u_shininess)) * attenuation;\n";
            }
            fragmentLightingBlock += `    specularLight += ${lightColorName} * specularIntensity;\n`;
          }
        }
        fragmentLightingBlock += "  }\n";
      }
    }

    if (!hasAmbientLights) {
      // Add an ambient light if we don't have one
      fragmentLightingBlock += "  ambientLight += vec3(0.2, 0.2, 0.2);\n";
    }

    if (!hasNonAmbientLights && lightingModel !== "CONSTANT") {
      fragmentShader += "#ifdef USE_CUSTOM_LIGHT_COLOR \n";
      fragmentShader += "uniform vec3 gltf_lightColor; \n";
      fragmentShader += "#endif \n";

      fragmentLightingBlock += "#ifndef USE_CUSTOM_LIGHT_COLOR \n";
      fragmentLightingBlock += "    vec3 lightColor = czm_lightColor;\n";
      fragmentLightingBlock += "#else \n";
      fragmentLightingBlock += "    vec3 lightColor = gltf_lightColor;\n";
      fragmentLightingBlock += "#endif \n";

      fragmentLightingBlock += "  vec3 l = normalize(czm_lightDirectionEC);\n";
      const minimumLighting = "0.2"; // Use strings instead of values as 0.0 -> 0 when stringified
      fragmentLightingBlock += `  diffuseLight += lightColor * max(dot(normal,l), ${minimumLighting});\n`;

      if (hasSpecular) {
        if (lightingModel === "BLINN") {
          fragmentLightingBlock += "  vec3 h = normalize(l + viewDir);\n";
          fragmentLightingBlock +=
            "  float specularIntensity = max(0., pow(max(dot(normal, h), 0.), u_shininess));\n";
        } else {
          // PHONG
          fragmentLightingBlock += "  vec3 reflectDir = reflect(-l, normal);\n";
          fragmentLightingBlock +=
            "  float specularIntensity = max(0., pow(max(dot(reflectDir, viewDir), 0.), u_shininess));\n";
        }

        fragmentLightingBlock +=
          "  specularLight += lightColor * specularIntensity;\n";
      }
    }

    vertexShader += "void main(void) {\n";
    vertexShader += vertexShaderMain;
    vertexShader += "}\n";

    fragmentShader += "void main(void) {\n";
    let colorCreationBlock = "  vec3 color = vec3(0.0, 0.0, 0.0);\n";
    if (hasNormals) {
      fragmentShader += "  vec3 normal = normalize(v_normal);\n";
      if (khrMaterialsCommon.doubleSided) {
        fragmentShader += "  if (czm_backFacing())\n";
        fragmentShader += "  {\n";
        fragmentShader += "    normal = -normal;\n";
        fragmentShader += "  }\n";
      }
    }

    let finalColorComputation;
    if (lightingModel !== "CONSTANT") {
      if (defined(techniqueUniforms.u_diffuse)) {
        if (techniqueUniforms.u_diffuse.type === WebGLConstants$1.SAMPLER_2D) {
          fragmentShader += `  vec4 diffuse = texture2D(u_diffuse, ${v_texcoord});\n`;
        } else {
          fragmentShader += "  vec4 diffuse = u_diffuse;\n";
        }
        fragmentShader += "  vec3 diffuseLight = vec3(0.0, 0.0, 0.0);\n";
        colorCreationBlock += "  color += diffuse.rgb * diffuseLight;\n";
      }

      if (hasSpecular) {
        if (techniqueUniforms.u_specular.type === WebGLConstants$1.SAMPLER_2D) {
          fragmentShader += `  vec3 specular = texture2D(u_specular, ${v_texcoord}).rgb;\n`;
        } else {
          fragmentShader += "  vec3 specular = u_specular.rgb;\n";
        }
        fragmentShader += "  vec3 specularLight = vec3(0.0, 0.0, 0.0);\n";
        colorCreationBlock += "  color += specular * specularLight;\n";
      }

      if (defined(techniqueUniforms.u_transparency)) {
        finalColorComputation =
          "  gl_FragColor = vec4(color * diffuse.a * u_transparency, diffuse.a * u_transparency);\n";
      } else {
        finalColorComputation =
          "  gl_FragColor = vec4(color * diffuse.a, diffuse.a);\n";
      }
    } else if (defined(techniqueUniforms.u_transparency)) {
      finalColorComputation =
        "  gl_FragColor = vec4(color * u_transparency, u_transparency);\n";
    } else {
      finalColorComputation = "  gl_FragColor = vec4(color, 1.0);\n";
    }

    if (hasVertexColors) {
      colorCreationBlock += "  color *= v_vertexColor.rgb;\n";
    }

    if (defined(techniqueUniforms.u_emission)) {
      if (techniqueUniforms.u_emission.type === WebGLConstants$1.SAMPLER_2D) {
        fragmentShader += `  vec3 emission = texture2D(u_emission, ${v_texcoord}).rgb;\n`;
      } else {
        fragmentShader += "  vec3 emission = u_emission.rgb;\n";
      }
      colorCreationBlock += "  color += emission;\n";
    }

    if (defined(techniqueUniforms.u_ambient) || lightingModel !== "CONSTANT") {
      if (defined(techniqueUniforms.u_ambient)) {
        if (techniqueUniforms.u_ambient.type === WebGLConstants$1.SAMPLER_2D) {
          fragmentShader += `  vec3 ambient = texture2D(u_ambient, ${v_texcoord}).rgb;\n`;
        } else {
          fragmentShader += "  vec3 ambient = u_ambient.rgb;\n";
        }
      } else {
        fragmentShader += "  vec3 ambient = diffuse.rgb;\n";
      }
      colorCreationBlock += "  color += ambient * ambientLight;\n";
    }
    fragmentShader += "  vec3 viewDir = -normalize(v_positionEC);\n";
    fragmentShader += "  vec3 ambientLight = vec3(0.0, 0.0, 0.0);\n";

    // Add in light computations
    fragmentShader += fragmentLightingBlock;

    fragmentShader += colorCreationBlock;
    fragmentShader += finalColorComputation;
    fragmentShader += "}\n";

    // Add shaders
    const vertexShaderId = addToArray(shaders, {
      type: WebGLConstants$1.VERTEX_SHADER,
      extras: {
        _pipeline: {
          source: vertexShader,
          extension: ".glsl",
        },
      },
    });

    const fragmentShaderId = addToArray(shaders, {
      type: WebGLConstants$1.FRAGMENT_SHADER,
      extras: {
        _pipeline: {
          source: fragmentShader,
          extension: ".glsl",
        },
      },
    });

    // Add program
    const programId = addToArray(programs, {
      fragmentShader: fragmentShaderId,
      vertexShader: vertexShaderId,
    });

    const techniqueId = addToArray(techniques, {
      attributes: techniqueAttributes,
      program: programId,
      uniforms: techniqueUniforms,
    });

    return techniqueId;
  }

  function getKHRMaterialsCommonValueType(paramName, paramValue) {
    let value;

    // Backwards compatibility for COLLADA2GLTF v1.0-draft when it encoding
    // materials using KHR_materials_common with explicit type/value members
    if (defined(paramValue.value)) {
      value = paramValue.value;
    } else if (defined(paramValue.index)) {
      value = [paramValue.index];
    } else {
      value = paramValue;
    }

    switch (paramName) {
      case "ambient":
        return value.length === 1
          ? WebGLConstants$1.SAMPLER_2D
          : WebGLConstants$1.FLOAT_VEC4;
      case "diffuse":
        return value.length === 1
          ? WebGLConstants$1.SAMPLER_2D
          : WebGLConstants$1.FLOAT_VEC4;
      case "emission":
        return value.length === 1
          ? WebGLConstants$1.SAMPLER_2D
          : WebGLConstants$1.FLOAT_VEC4;
      case "specular":
        return value.length === 1
          ? WebGLConstants$1.SAMPLER_2D
          : WebGLConstants$1.FLOAT_VEC4;
      case "shininess":
        return WebGLConstants$1.FLOAT;
      case "transparency":
        return WebGLConstants$1.FLOAT;

      // these two are usually not used directly within shaders,
      // they are just added here for completeness
      case "transparent":
        return WebGLConstants$1.BOOL;
      case "doubleSided":
        return WebGLConstants$1.BOOL;
    }
  }

  function getTechniqueKey(khrMaterialsCommon, primitiveInfo) {
    let techniqueKey = "";
    techniqueKey += `technique:${khrMaterialsCommon.technique};`;

    const values = khrMaterialsCommon.values;
    const keys = Object.keys(values).sort();
    const keysCount = keys.length;
    for (let i = 0; i < keysCount; ++i) {
      const name = keys[i];
      if (values.hasOwnProperty(name)) {
        techniqueKey += `${name}:${getKHRMaterialsCommonValueType(
        name,
        values[name]
      )}`;
        techniqueKey += ";";
      }
    }

    const jointCount = defaultValue(khrMaterialsCommon.jointCount, 0);
    techniqueKey += `${jointCount.toString()};`;
    if (defined(primitiveInfo)) {
      const skinningInfo = primitiveInfo.skinning;
      if (jointCount > 0) {
        techniqueKey += `${skinningInfo.type};`;
      }
      techniqueKey += primitiveInfo.hasVertexColors;
    }

    return techniqueKey;
  }

  function lightDefaults(gltf) {
    const khrMaterialsCommon = gltf.extensions.KHR_materials_common;
    if (!defined(khrMaterialsCommon) || !defined(khrMaterialsCommon.lights)) {
      return;
    }

    const lights = khrMaterialsCommon.lights;

    const lightsLength = lights.length;
    for (let lightId = 0; lightId < lightsLength; lightId++) {
      const light = lights[lightId];
      if (light.type === "ambient") {
        if (!defined(light.ambient)) {
          light.ambient = {};
        }
        const ambientLight = light.ambient;

        if (!defined(ambientLight.color)) {
          ambientLight.color = [1.0, 1.0, 1.0];
        }
      } else if (light.type === "directional") {
        if (!defined(light.directional)) {
          light.directional = {};
        }
        const directionalLight = light.directional;

        if (!defined(directionalLight.color)) {
          directionalLight.color = [1.0, 1.0, 1.0];
        }
      } else if (light.type === "point") {
        if (!defined(light.point)) {
          light.point = {};
        }
        const pointLight = light.point;

        if (!defined(pointLight.color)) {
          pointLight.color = [1.0, 1.0, 1.0];
        }

        pointLight.constantAttenuation = defaultValue(
          pointLight.constantAttenuation,
          1.0
        );
        pointLight.linearAttenuation = defaultValue(
          pointLight.linearAttenuation,
          0.0
        );
        pointLight.quadraticAttenuation = defaultValue(
          pointLight.quadraticAttenuation,
          0.0
        );
      } else if (light.type === "spot") {
        if (!defined(light.spot)) {
          light.spot = {};
        }
        const spotLight = light.spot;

        if (!defined(spotLight.color)) {
          spotLight.color = [1.0, 1.0, 1.0];
        }

        spotLight.constantAttenuation = defaultValue(
          spotLight.constantAttenuation,
          1.0
        );
        spotLight.fallOffAngle = defaultValue(spotLight.fallOffAngle, 3.14159265);
        spotLight.fallOffExponent = defaultValue(spotLight.fallOffExponent, 0.0);
        spotLight.linearAttenuation = defaultValue(
          spotLight.linearAttenuation,
          0.0
        );
        spotLight.quadraticAttenuation = defaultValue(
          spotLight.quadraticAttenuation,
          0.0
        );
      }
    }
  }

  /**
   * @private
   */
  function processPbrMaterials(gltf, options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    // No need to create new techniques if they already exist,
    // the shader should handle these values
    if (usesExtension(gltf, "KHR_techniques_webgl")) {
      return gltf;
    }

    // All materials in glTF are PBR by default,
    // so we should apply PBR unless no materials are found.
    if (!defined(gltf.materials) || gltf.materials.length === 0) {
      return gltf;
    }

    if (!defined(gltf.extensions)) {
      gltf.extensions = {};
    }

    if (!defined(gltf.extensionsUsed)) {
      gltf.extensionsUsed = [];
    }

    if (!defined(gltf.extensionsRequired)) {
      gltf.extensionsRequired = [];
    }

    gltf.extensions.KHR_techniques_webgl = {
      programs: [],
      shaders: [],
      techniques: [],
    };

    gltf.extensionsUsed.push("KHR_techniques_webgl");
    gltf.extensionsRequired.push("KHR_techniques_webgl");

    const primitiveByMaterial = ModelUtility.splitIncompatibleMaterials(gltf);

    ForEach.material(gltf, function (material, materialIndex) {
      const generatedMaterialValues = {};
      const technique = generateTechnique(
        gltf,
        material,
        materialIndex,
        generatedMaterialValues,
        primitiveByMaterial,
        options
      );

      if (!defined(material.extensions)) {
        material.extensions = {};
      }

      material.extensions.KHR_techniques_webgl = {
        values: generatedMaterialValues,
        technique: technique,
      };
    });

    // If any primitives have semantics that aren't declared in the generated
    // shaders, we want to preserve them.
    ModelUtility.ensureSemanticExistence(gltf);

    return gltf;
  }

  function isSpecularGlossinessMaterial(material) {
    return (
      defined(material.extensions) &&
      defined(material.extensions.KHR_materials_pbrSpecularGlossiness)
    );
  }

  function addTextureCoordinates(
    gltf,
    textureName,
    generatedMaterialValues,
    defaultTexCoord,
    result
  ) {
    let texCoord;
    const texInfo = generatedMaterialValues[textureName];
    if (defined(texInfo) && defined(texInfo.texCoord) && texInfo.texCoord === 1) {
      defaultTexCoord = defaultTexCoord.replace("0", "1");
    }
    if (defined(generatedMaterialValues[`${textureName}Offset`])) {
      texCoord = `${textureName}Coord`;
      result.fragmentShaderMain += `    vec2 ${texCoord} = computeTexCoord(${defaultTexCoord}, ${textureName}Offset, ${textureName}Rotation, ${textureName}Scale);\n`;
    } else {
      texCoord = defaultTexCoord;
    }
    return texCoord;
  }

  const DEFAULT_TEXTURE_OFFSET = [0.0, 0.0];
  const DEFAULT_TEXTURE_ROTATION = [0.0];
  const DEFAULT_TEXTURE_SCALE = [1.0, 1.0];

  function handleKHRTextureTransform(
    parameterName,
    value,
    generatedMaterialValues
  ) {
    if (
      parameterName.indexOf("Texture") === -1 ||
      !defined(value.extensions) ||
      !defined(value.extensions.KHR_texture_transform)
    ) {
      return;
    }

    const uniformName = `u_${parameterName}`;
    const extension = value.extensions.KHR_texture_transform;
    generatedMaterialValues[`${uniformName}Offset`] = defaultValue(
      extension.offset,
      DEFAULT_TEXTURE_OFFSET
    );
    generatedMaterialValues[`${uniformName}Rotation`] = defaultValue(
      extension.rotation,
      DEFAULT_TEXTURE_ROTATION
    );
    generatedMaterialValues[`${uniformName}Scale`] = defaultValue(
      extension.scale,
      DEFAULT_TEXTURE_SCALE
    );

    if (defined(value.texCoord) && defined(extension.texCoord)) {
      generatedMaterialValues[uniformName].texCoord = extension.texCoord;
    }
  }

  function generateTechnique(
    gltf,
    material,
    materialIndex,
    generatedMaterialValues,
    primitiveByMaterial,
    options
  ) {
    const addBatchIdToGeneratedShaders = defaultValue(
      options.addBatchIdToGeneratedShaders,
      false
    );

    const techniquesWebgl = gltf.extensions.KHR_techniques_webgl;
    const techniques = techniquesWebgl.techniques;
    const shaders = techniquesWebgl.shaders;
    const programs = techniquesWebgl.programs;

    const useSpecGloss = isSpecularGlossinessMaterial(material);

    let uniformName;
    let parameterName;
    let value;
    if (!useSpecGloss) {
      const pbrMetallicRoughness = material.pbrMetallicRoughness;
      if (defined(pbrMetallicRoughness)) {
        for (parameterName in pbrMetallicRoughness) {
          if (pbrMetallicRoughness.hasOwnProperty(parameterName)) {
            value = pbrMetallicRoughness[parameterName];
            uniformName = `u_${parameterName}`;
            generatedMaterialValues[uniformName] = value;
            handleKHRTextureTransform(
              parameterName,
              value,
              generatedMaterialValues
            );
          }
        }
      } else {
        // Add a uniform for baseColorFactor and set the default value. Otherwise
        // glTFs without a pbrMetallicRoughness object will not be styled correctly
        // when using Cesium3DTileColorBlendMode.REPLACE.
        generatedMaterialValues["u_baseColorFactor"] = [1.0, 1.0, 1.0, 1.0];
      }
    }

    if (useSpecGloss) {
      const pbrSpecularGlossiness =
        material.extensions.KHR_materials_pbrSpecularGlossiness;
      for (parameterName in pbrSpecularGlossiness) {
        if (pbrSpecularGlossiness.hasOwnProperty(parameterName)) {
          value = pbrSpecularGlossiness[parameterName];
          uniformName = `u_${parameterName}`;
          generatedMaterialValues[uniformName] = value;
          handleKHRTextureTransform(
            parameterName,
            value,
            generatedMaterialValues
          );
        }
      }
    }

    for (const additional in material) {
      if (
        material.hasOwnProperty(additional) &&
        (additional.indexOf("Texture") >= 0 || additional.indexOf("Factor") >= 0)
      ) {
        value = material[additional];
        uniformName = `u_${additional}`;
        generatedMaterialValues[uniformName] = value;
        handleKHRTextureTransform(additional, value, generatedMaterialValues);
      }
    }

    let vertexShader = "precision highp float;\n";
    let fragmentShader = "precision highp float;\n";

    let skin;
    if (defined(gltf.skins)) {
      skin = gltf.skins[0];
    }
    const joints = defined(skin) ? skin.joints : [];
    const jointCount = joints.length;

    const primitiveInfo = primitiveByMaterial[materialIndex];

    let skinningInfo;
    let hasSkinning = false;
    let hasVertexColors = false;
    let hasMorphTargets = false;
    let hasNormals = false;
    let hasTangents = false;
    let hasTexCoords = false;
    let hasTexCoord1 = false;
    let hasOutline = false;
    let isUnlit = false;

    if (defined(primitiveInfo)) {
      skinningInfo = primitiveInfo.skinning;
      hasSkinning = skinningInfo.skinned && joints.length > 0;
      hasVertexColors = primitiveInfo.hasVertexColors;
      hasMorphTargets = primitiveInfo.hasMorphTargets;
      hasNormals = primitiveInfo.hasNormals;
      hasTangents = primitiveInfo.hasTangents;
      hasTexCoords = primitiveInfo.hasTexCoords;
      hasTexCoord1 = primitiveInfo.hasTexCoord1;
      hasOutline = primitiveInfo.hasOutline;
    }

    let morphTargets;
    if (hasMorphTargets) {
      ForEach.mesh(gltf, function (mesh) {
        ForEach.meshPrimitive(mesh, function (primitive) {
          if (primitive.material === materialIndex) {
            const targets = primitive.targets;
            if (defined(targets)) {
              morphTargets = targets;
            }
          }
        });
      });
    }

    // Add techniques
    const techniqueUniforms = {
      // Add matrices
      u_modelViewMatrix: {
        semantic: usesExtension(gltf, "CESIUM_RTC")
          ? "CESIUM_RTC_MODELVIEW"
          : "MODELVIEW",
        type: WebGLConstants$1.FLOAT_MAT4,
      },
      u_projectionMatrix: {
        semantic: "PROJECTION",
        type: WebGLConstants$1.FLOAT_MAT4,
      },
    };

    if (
      defined(material.extensions) &&
      defined(material.extensions.KHR_materials_unlit)
    ) {
      isUnlit = true;
    }

    if (hasNormals) {
      techniqueUniforms.u_normalMatrix = {
        semantic: "MODELVIEWINVERSETRANSPOSE",
        type: WebGLConstants$1.FLOAT_MAT3,
      };
    }

    if (hasSkinning) {
      techniqueUniforms.u_jointMatrix = {
        count: jointCount,
        semantic: "JOINTMATRIX",
        type: WebGLConstants$1.FLOAT_MAT4,
      };
    }

    if (hasMorphTargets) {
      techniqueUniforms.u_morphWeights = {
        count: morphTargets.length,
        semantic: "MORPHWEIGHTS",
        type: WebGLConstants$1.FLOAT,
      };
    }

    const alphaMode = material.alphaMode;
    if (defined(alphaMode) && alphaMode === "MASK") {
      techniqueUniforms.u_alphaCutoff = {
        semantic: "ALPHACUTOFF",
        type: WebGLConstants$1.FLOAT,
      };
    }

    // Add material values
    for (uniformName in generatedMaterialValues) {
      if (generatedMaterialValues.hasOwnProperty(uniformName)) {
        techniqueUniforms[uniformName] = {
          type: getPBRValueType(uniformName),
        };
      }
    }

    const baseColorUniform = defaultValue(
      techniqueUniforms.u_baseColorTexture,
      techniqueUniforms.u_baseColorFactor
    );
    if (defined(baseColorUniform)) {
      baseColorUniform.semantic = "_3DTILESDIFFUSE";
    }

    // Add uniforms to shaders
    for (uniformName in techniqueUniforms) {
      if (techniqueUniforms.hasOwnProperty(uniformName)) {
        const uniform = techniqueUniforms[uniformName];
        const arraySize = defined(uniform.count) ? `[${uniform.count}]` : "";
        if (
          (uniform.type !== WebGLConstants$1.FLOAT_MAT3 &&
            uniform.type !== WebGLConstants$1.FLOAT_MAT4 &&
            uniformName !== "u_morphWeights") ||
          uniform.useInFragment
        ) {
          fragmentShader += `uniform ${webGLConstantToGlslType(
          uniform.type
        )} ${uniformName}${arraySize};\n`;
          delete uniform.useInFragment;
        } else {
          vertexShader += `uniform ${webGLConstantToGlslType(
          uniform.type
        )} ${uniformName}${arraySize};\n`;
        }
      }
    }

    if (hasOutline) {
      fragmentShader += "uniform sampler2D u_outlineTexture;\n";
    }

    // Add attributes with semantics
    let vertexShaderMain = "";
    if (hasSkinning) {
      vertexShaderMain +=
        "    mat4 skinMatrix =\n" +
        "        a_weight.x * u_jointMatrix[int(a_joint.x)] +\n" +
        "        a_weight.y * u_jointMatrix[int(a_joint.y)] +\n" +
        "        a_weight.z * u_jointMatrix[int(a_joint.z)] +\n" +
        "        a_weight.w * u_jointMatrix[int(a_joint.w)];\n";
    }

    // Add position always
    const techniqueAttributes = {
      a_position: {
        semantic: "POSITION",
      },
    };

    if (hasOutline) {
      techniqueAttributes.a_outlineCoordinates = {
        semantic: "_OUTLINE_COORDINATES",
      };
    }

    vertexShader += "attribute vec3 a_position;\n";
    if (hasNormals) {
      vertexShader += "varying vec3 v_positionEC;\n";
    }
    if (hasOutline) {
      vertexShader += "attribute vec3 a_outlineCoordinates;\n";
      vertexShader += "varying vec3 v_outlineCoordinates;\n";
    }

    // Morph Target Weighting
    vertexShaderMain += "    vec3 weightedPosition = a_position;\n";
    if (hasNormals) {
      vertexShaderMain += "    vec3 weightedNormal = a_normal;\n";
    }
    if (hasTangents) {
      vertexShaderMain += "    vec4 weightedTangent = a_tangent;\n";
    }
    if (hasMorphTargets) {
      for (let k = 0; k < morphTargets.length; k++) {
        const targetAttributes = morphTargets[k];
        for (const targetAttribute in targetAttributes) {
          if (
            targetAttributes.hasOwnProperty(targetAttribute) &&
            targetAttribute !== "extras"
          ) {
            const attributeName = `a_${targetAttribute}_${k}`;
            techniqueAttributes[attributeName] = {
              semantic: `${targetAttribute}_${k}`,
            };
            vertexShader += `attribute vec3 ${attributeName};\n`;
            if (targetAttribute === "POSITION") {
              vertexShaderMain += `    weightedPosition += u_morphWeights[${k}] * ${attributeName};\n`;
            } else if (targetAttribute === "NORMAL") {
              vertexShaderMain += `    weightedNormal += u_morphWeights[${k}] * ${attributeName};\n`;
            } else if (hasTangents && targetAttribute === "TANGENT") {
              vertexShaderMain += `    weightedTangent.xyz += u_morphWeights[${k}] * ${attributeName};\n`;
            }
          }
        }
      }
    }

    // Final position computation
    if (hasSkinning) {
      vertexShaderMain +=
        "    vec4 position = skinMatrix * vec4(weightedPosition, 1.0);\n";
    } else {
      vertexShaderMain += "    vec4 position = vec4(weightedPosition, 1.0);\n";
    }
    vertexShaderMain += "    position = u_modelViewMatrix * position;\n";
    if (hasNormals) {
      vertexShaderMain += "    v_positionEC = position.xyz;\n";
    }
    vertexShaderMain += "    gl_Position = u_projectionMatrix * position;\n";

    if (hasOutline) {
      vertexShaderMain += "    v_outlineCoordinates = a_outlineCoordinates;\n";
    }

    // Final normal computation
    if (hasNormals) {
      techniqueAttributes.a_normal = {
        semantic: "NORMAL",
      };
      vertexShader += "attribute vec3 a_normal;\n";
      if (!isUnlit) {
        vertexShader += "varying vec3 v_normal;\n";
        if (hasSkinning) {
          vertexShaderMain +=
            "    v_normal = u_normalMatrix * mat3(skinMatrix) * weightedNormal;\n";
        } else {
          vertexShaderMain += "    v_normal = u_normalMatrix * weightedNormal;\n";
        }
        fragmentShader += "varying vec3 v_normal;\n";
      }
      fragmentShader += "varying vec3 v_positionEC;\n";
    }

    // Read tangents if available
    if (hasTangents) {
      techniqueAttributes.a_tangent = {
        semantic: "TANGENT",
      };
      vertexShader += "attribute vec4 a_tangent;\n";
      vertexShader += "varying vec4 v_tangent;\n";
      vertexShaderMain +=
        "    v_tangent.xyz = u_normalMatrix * weightedTangent.xyz;\n";
      vertexShaderMain += "    v_tangent.w = weightedTangent.w;\n";

      fragmentShader += "varying vec4 v_tangent;\n";
    }

    if (hasOutline) {
      fragmentShader += "varying vec3 v_outlineCoordinates;\n";
    }

    let fragmentShaderMain = "";

    // Add texture coordinates if the material uses them
    let v_texCoord;
    let normalTexCoord;
    let baseColorTexCoord;
    let specularGlossinessTexCoord;
    let diffuseTexCoord;
    let metallicRoughnessTexCoord;
    let occlusionTexCoord;
    let emissiveTexCoord;

    if (hasTexCoords) {
      techniqueAttributes.a_texcoord_0 = {
        semantic: "TEXCOORD_0",
      };

      v_texCoord = "v_texcoord_0";
      vertexShader += "attribute vec2 a_texcoord_0;\n";
      vertexShader += `varying vec2 ${v_texCoord};\n`;
      vertexShaderMain += `    ${v_texCoord} = a_texcoord_0;\n`;

      fragmentShader += `varying vec2 ${v_texCoord};\n`;

      if (hasTexCoord1) {
        techniqueAttributes.a_texcoord_1 = {
          semantic: "TEXCOORD_1",
        };

        const v_texCoord1 = v_texCoord.replace("0", "1");
        vertexShader += "attribute vec2 a_texcoord_1;\n";
        vertexShader += `varying vec2 ${v_texCoord1};\n`;
        vertexShaderMain += `    ${v_texCoord1} = a_texcoord_1;\n`;

        fragmentShader += `varying vec2 ${v_texCoord1};\n`;
      }

      const result = {
        fragmentShaderMain: fragmentShaderMain,
      };
      normalTexCoord = addTextureCoordinates(
        gltf,
        "u_normalTexture",
        generatedMaterialValues,
        v_texCoord,
        result
      );
      baseColorTexCoord = addTextureCoordinates(
        gltf,
        "u_baseColorTexture",
        generatedMaterialValues,
        v_texCoord,
        result
      );
      specularGlossinessTexCoord = addTextureCoordinates(
        gltf,
        "u_specularGlossinessTexture",
        generatedMaterialValues,
        v_texCoord,
        result
      );
      diffuseTexCoord = addTextureCoordinates(
        gltf,
        "u_diffuseTexture",
        generatedMaterialValues,
        v_texCoord,
        result
      );
      metallicRoughnessTexCoord = addTextureCoordinates(
        gltf,
        "u_metallicRoughnessTexture",
        generatedMaterialValues,
        v_texCoord,
        result
      );
      occlusionTexCoord = addTextureCoordinates(
        gltf,
        "u_occlusionTexture",
        generatedMaterialValues,
        v_texCoord,
        result
      );
      emissiveTexCoord = addTextureCoordinates(
        gltf,
        "u_emissiveTexture",
        generatedMaterialValues,
        v_texCoord,
        result
      );

      fragmentShaderMain = result.fragmentShaderMain;
    }

    // Add skinning information if available
    if (hasSkinning) {
      techniqueAttributes.a_joint = {
        semantic: "JOINTS_0",
      };
      techniqueAttributes.a_weight = {
        semantic: "WEIGHTS_0",
      };

      vertexShader += "attribute vec4 a_joint;\n";
      vertexShader += "attribute vec4 a_weight;\n";
    }

    if (hasVertexColors) {
      techniqueAttributes.a_vertexColor = {
        semantic: "COLOR_0",
      };
      vertexShader += "attribute vec4 a_vertexColor;\n";
      vertexShader += "varying vec4 v_vertexColor;\n";
      vertexShaderMain += "  v_vertexColor = a_vertexColor;\n";
      fragmentShader += "varying vec4 v_vertexColor;\n";
    }

    if (addBatchIdToGeneratedShaders) {
      techniqueAttributes.a_batchId = {
        semantic: "_BATCHID",
      };
      vertexShader += "attribute float a_batchId;\n";
    }

    vertexShader += "void main(void) \n{\n";
    vertexShader += vertexShaderMain;
    vertexShader += "}\n";

    // Fragment shader lighting
    if (hasNormals && !isUnlit) {
      fragmentShader += "const float M_PI = 3.141592653589793;\n";

      fragmentShader +=
        "vec3 lambertianDiffuse(vec3 diffuseColor) \n" +
        "{\n" +
        "    return diffuseColor / M_PI;\n" +
        "}\n\n";

      fragmentShader +=
        "vec3 fresnelSchlick2(vec3 f0, vec3 f90, float VdotH) \n" +
        "{\n" +
        "    return f0 + (f90 - f0) * pow(clamp(1.0 - VdotH, 0.0, 1.0), 5.0);\n" +
        "}\n\n";

      fragmentShader +=
        "vec3 fresnelSchlick(float metalness, float VdotH) \n" +
        "{\n" +
        "    return metalness + (vec3(1.0) - metalness) * pow(1.0 - VdotH, 5.0);\n" +
        "}\n\n";

      fragmentShader +=
        "float smithVisibilityG1(float NdotV, float roughness) \n" +
        "{\n" +
        "    float k = (roughness + 1.0) * (roughness + 1.0) / 8.0;\n" +
        "    return NdotV / (NdotV * (1.0 - k) + k);\n" +
        "}\n\n";

      fragmentShader +=
        "float smithVisibilityGGX(float roughness, float NdotL, float NdotV) \n" +
        "{\n" +
        "    return smithVisibilityG1(NdotL, roughness) * smithVisibilityG1(NdotV, roughness);\n" +
        "}\n\n";

      fragmentShader +=
        "float GGX(float roughness, float NdotH) \n" +
        "{\n" +
        "    float roughnessSquared = roughness * roughness;\n" +
        "    float f = (NdotH * roughnessSquared - NdotH) * NdotH + 1.0;\n" +
        "    return roughnessSquared / (M_PI * f * f);\n" +
        "}\n\n";
    }

    fragmentShader +=
      "vec3 SRGBtoLINEAR3(vec3 srgbIn) \n" +
      "{\n" +
      "    return pow(srgbIn, vec3(2.2));\n" +
      "}\n\n";

    fragmentShader +=
      "vec4 SRGBtoLINEAR4(vec4 srgbIn) \n" +
      "{\n" +
      "    vec3 linearOut = pow(srgbIn.rgb, vec3(2.2));\n" +
      "    return vec4(linearOut, srgbIn.a);\n" +
      "}\n\n";

    fragmentShader +=
      "vec3 applyTonemapping(vec3 linearIn) \n" +
      "{\n" +
      "#ifndef HDR \n" +
      "    return czm_acesTonemapping(linearIn);\n" +
      "#else \n" +
      "    return linearIn;\n" +
      "#endif \n" +
      "}\n\n";

    fragmentShader +=
      "vec3 LINEARtoSRGB(vec3 linearIn) \n" +
      "{\n" +
      "#ifndef HDR \n" +
      "    return pow(linearIn, vec3(1.0/2.2));\n" +
      "#else \n" +
      "    return linearIn;\n" +
      "#endif \n" +
      "}\n\n";

    fragmentShader +=
      "vec2 computeTexCoord(vec2 texCoords, vec2 offset, float rotation, vec2 scale) \n" +
      "{\n" +
      "    rotation = -rotation; \n" +
      "    mat3 transform = mat3(\n" +
      "        cos(rotation) * scale.x, sin(rotation) * scale.x, 0.0, \n" +
      "       -sin(rotation) * scale.y, cos(rotation) * scale.y, 0.0, \n" +
      "        offset.x, offset.y, 1.0); \n" +
      "    vec2 transformedTexCoords = (transform * vec3(fract(texCoords), 1.0)).xy; \n" +
      "    return transformedTexCoords; \n" +
      "}\n\n";

    fragmentShader += "#ifdef USE_IBL_LIGHTING \n";
    fragmentShader += "uniform vec2 gltf_iblFactor; \n";
    fragmentShader += "#endif \n";
    fragmentShader += "#ifdef USE_CUSTOM_LIGHT_COLOR \n";
    fragmentShader += "uniform vec3 gltf_lightColor; \n";
    fragmentShader += "#endif \n";

    fragmentShader += "void main(void) \n{\n";
    fragmentShader += fragmentShaderMain;

    // Add normal mapping to fragment shader
    if (hasNormals && !isUnlit) {
      fragmentShader += "    vec3 ng = normalize(v_normal);\n";
      fragmentShader +=
        "    vec3 positionWC = vec3(czm_inverseView * vec4(v_positionEC, 1.0));\n";
      if (defined(generatedMaterialValues.u_normalTexture)) {
        if (hasTangents) {
          // Read tangents from varying
          fragmentShader += "    vec3 t = normalize(v_tangent.xyz);\n";
          fragmentShader +=
            "    vec3 b = normalize(cross(ng, t) * v_tangent.w);\n";
          fragmentShader += "    mat3 tbn = mat3(t, b, ng);\n";
          fragmentShader += `    vec3 n = texture2D(u_normalTexture, ${normalTexCoord}).rgb;\n`;
          fragmentShader += "    n = normalize(tbn * (2.0 * n - 1.0));\n";
        } else {
          // Add standard derivatives extension
          fragmentShader = `${
          "#ifdef GL_OES_standard_derivatives\n" +
          "#extension GL_OES_standard_derivatives : enable\n" +
          "#endif\n"
        }${fragmentShader}`;
          // Compute tangents
          fragmentShader += "#ifdef GL_OES_standard_derivatives\n";
          fragmentShader += "    vec3 pos_dx = dFdx(v_positionEC);\n";
          fragmentShader += "    vec3 pos_dy = dFdy(v_positionEC);\n";
          fragmentShader += `    vec3 tex_dx = dFdx(vec3(${normalTexCoord},0.0));\n`;
          fragmentShader += `    vec3 tex_dy = dFdy(vec3(${normalTexCoord},0.0));\n`;
          fragmentShader +=
            "    vec3 t = (tex_dy.t * pos_dx - tex_dx.t * pos_dy) / (tex_dx.s * tex_dy.t - tex_dy.s * tex_dx.t);\n";
          fragmentShader += "    t = normalize(t - ng * dot(ng, t));\n";
          fragmentShader += "    vec3 b = normalize(cross(ng, t));\n";
          fragmentShader += "    mat3 tbn = mat3(t, b, ng);\n";
          fragmentShader += `    vec3 n = texture2D(u_normalTexture, ${normalTexCoord}).rgb;\n`;
          fragmentShader += "    n = normalize(tbn * (2.0 * n - 1.0));\n";
          fragmentShader += "#else\n";
          fragmentShader += "    vec3 n = ng;\n";
          fragmentShader += "#endif\n";
        }
      } else {
        fragmentShader += "    vec3 n = ng;\n";
      }
      if (material.doubleSided) {
        fragmentShader += "    if (czm_backFacing())\n";
        fragmentShader += "    {\n";
        fragmentShader += "        n = -n;\n";
        fragmentShader += "    }\n";
      }
    }

    // Add base color to fragment shader
    if (defined(generatedMaterialValues.u_baseColorTexture)) {
      fragmentShader += `    vec4 baseColorWithAlpha = SRGBtoLINEAR4(texture2D(u_baseColorTexture, ${baseColorTexCoord}));\n`;
      if (defined(generatedMaterialValues.u_baseColorFactor)) {
        fragmentShader += "    baseColorWithAlpha *= u_baseColorFactor;\n";
      }
    } else if (defined(generatedMaterialValues.u_baseColorFactor)) {
      fragmentShader += "    vec4 baseColorWithAlpha = u_baseColorFactor;\n";
    } else {
      fragmentShader += "    vec4 baseColorWithAlpha = vec4(1.0);\n";
    }

    if (hasVertexColors) {
      fragmentShader += "    baseColorWithAlpha *= v_vertexColor;\n";
    }

    fragmentShader += "    vec3 baseColor = baseColorWithAlpha.rgb;\n";

    if (hasNormals && !isUnlit) {
      if (useSpecGloss) {
        if (defined(generatedMaterialValues.u_specularGlossinessTexture)) {
          fragmentShader += `    vec4 specularGlossiness = SRGBtoLINEAR4(texture2D(u_specularGlossinessTexture, ${specularGlossinessTexCoord}));\n`;
          fragmentShader += "    vec3 specular = specularGlossiness.rgb;\n";
          fragmentShader += "    float glossiness = specularGlossiness.a;\n";
          if (defined(generatedMaterialValues.u_specularFactor)) {
            fragmentShader += "    specular *= u_specularFactor;\n";
          }
          if (defined(generatedMaterialValues.u_glossinessFactor)) {
            fragmentShader += "    glossiness *= u_glossinessFactor;\n";
          }
        } else {
          if (defined(generatedMaterialValues.u_specularFactor)) {
            fragmentShader +=
              "    vec3 specular = clamp(u_specularFactor, vec3(0.0), vec3(1.0));\n";
          } else {
            fragmentShader += "    vec3 specular = vec3(1.0);\n";
          }
          if (defined(generatedMaterialValues.u_glossinessFactor)) {
            fragmentShader +=
              "    float glossiness = clamp(u_glossinessFactor, 0.0, 1.0);\n";
          } else {
            fragmentShader += "    float glossiness = 1.0;\n";
          }
        }
        if (defined(generatedMaterialValues.u_diffuseTexture)) {
          fragmentShader += `    vec4 diffuse = SRGBtoLINEAR4(texture2D(u_diffuseTexture, ${diffuseTexCoord}));\n`;
          if (defined(generatedMaterialValues.u_diffuseFactor)) {
            fragmentShader += "    diffuse *= u_diffuseFactor;\n";
          }
        } else if (defined(generatedMaterialValues.u_diffuseFactor)) {
          fragmentShader +=
            "    vec4 diffuse = clamp(u_diffuseFactor, vec4(0.0), vec4(1.0));\n";
        } else {
          fragmentShader += "    vec4 diffuse = vec4(1.0);\n";
        }

        // the specular glossiness extension's alpha takes precedence over
        // the base color alpha.
        fragmentShader += "    baseColorWithAlpha.a = diffuse.a;\n";
      } else if (defined(generatedMaterialValues.u_metallicRoughnessTexture)) {
        fragmentShader += `    vec3 metallicRoughness = texture2D(u_metallicRoughnessTexture, ${metallicRoughnessTexCoord}).rgb;\n`;
        fragmentShader +=
          "    float metalness = clamp(metallicRoughness.b, 0.0, 1.0);\n";
        fragmentShader +=
          "    float roughness = clamp(metallicRoughness.g, 0.04, 1.0);\n";
        if (defined(generatedMaterialValues.u_metallicFactor)) {
          fragmentShader += "    metalness *= u_metallicFactor;\n";
        }
        if (defined(generatedMaterialValues.u_roughnessFactor)) {
          fragmentShader += "    roughness *= u_roughnessFactor;\n";
        }
      } else {
        if (defined(generatedMaterialValues.u_metallicFactor)) {
          fragmentShader +=
            "    float metalness = clamp(u_metallicFactor, 0.0, 1.0);\n";
        } else {
          fragmentShader += "    float metalness = 1.0;\n";
        }
        if (defined(generatedMaterialValues.u_roughnessFactor)) {
          fragmentShader +=
            "    float roughness = clamp(u_roughnessFactor, 0.04, 1.0);\n";
        } else {
          fragmentShader += "    float roughness = 1.0;\n";
        }
      }

      fragmentShader += "    vec3 v = -normalize(v_positionEC);\n";

      // Generate fragment shader's lighting block
      fragmentShader += "#ifndef USE_CUSTOM_LIGHT_COLOR \n";
      fragmentShader += "    vec3 lightColorHdr = czm_lightColorHdr;\n";
      fragmentShader += "#else \n";
      fragmentShader += "    vec3 lightColorHdr = gltf_lightColor;\n";
      fragmentShader += "#endif \n";
      fragmentShader += "    vec3 l = normalize(czm_lightDirectionEC);\n";
      fragmentShader += "    vec3 h = normalize(v + l);\n";
      fragmentShader += "    float NdotL = clamp(dot(n, l), 0.001, 1.0);\n";
      fragmentShader += "    float NdotV = abs(dot(n, v)) + 0.001;\n";
      fragmentShader += "    float NdotH = clamp(dot(n, h), 0.0, 1.0);\n";
      fragmentShader += "    float LdotH = clamp(dot(l, h), 0.0, 1.0);\n";
      fragmentShader += "    float VdotH = clamp(dot(v, h), 0.0, 1.0);\n";
      fragmentShader += "    vec3 f0 = vec3(0.04);\n";
      // Whether the material uses metallic-roughness or specular-glossiness changes how the BRDF inputs are computed.
      // It does not change the implementation of the BRDF itself.
      if (useSpecGloss) {
        fragmentShader += "    float roughness = 1.0 - glossiness;\n";
        fragmentShader +=
          "    vec3 diffuseColor = diffuse.rgb * (1.0 - max(max(specular.r, specular.g), specular.b));\n";
        fragmentShader += "    vec3 specularColor = specular;\n";
      } else {
        fragmentShader +=
          "    vec3 diffuseColor = baseColor * (1.0 - metalness) * (1.0 - f0);\n";
        fragmentShader +=
          "    vec3 specularColor = mix(f0, baseColor, metalness);\n";
      }

      fragmentShader += "    float alpha = roughness * roughness;\n";
      fragmentShader +=
        "    float reflectance = max(max(specularColor.r, specularColor.g), specularColor.b);\n";
      fragmentShader +=
        "    vec3 r90 = vec3(clamp(reflectance * 25.0, 0.0, 1.0));\n";
      fragmentShader += "    vec3 r0 = specularColor.rgb;\n";

      fragmentShader += "    vec3 F = fresnelSchlick2(r0, r90, VdotH);\n";
      fragmentShader +=
        "    float G = smithVisibilityGGX(alpha, NdotL, NdotV);\n";
      fragmentShader += "    float D = GGX(alpha, NdotH);\n";

      fragmentShader +=
        "    vec3 diffuseContribution = (1.0 - F) * lambertianDiffuse(diffuseColor);\n";
      fragmentShader +=
        "    vec3 specularContribution = F * G * D / (4.0 * NdotL * NdotV);\n";
      fragmentShader +=
        "    vec3 color = NdotL * lightColorHdr * (diffuseContribution + specularContribution);\n";

      // Use the procedural IBL if there are no environment maps
      fragmentShader +=
        "#if defined(USE_IBL_LIGHTING) && !defined(DIFFUSE_IBL) && !defined(SPECULAR_IBL) \n";

      fragmentShader +=
        "    vec3 r = normalize(czm_inverseViewRotation * normalize(reflect(v, n)));\n";
      // Figure out if the reflection vector hits the ellipsoid
      fragmentShader += "    float vertexRadius = length(positionWC);\n";
      fragmentShader +=
        "    float horizonDotNadir = 1.0 - min(1.0, czm_ellipsoidRadii.x / vertexRadius);\n";
      fragmentShader +=
        "    float reflectionDotNadir = dot(r, normalize(positionWC));\n";
      // Flipping the X vector is a cheap way to get the inverse of czm_temeToPseudoFixed, since that's a rotation about Z.
      fragmentShader += "    r.x = -r.x;\n";
      fragmentShader += "    r = -normalize(czm_temeToPseudoFixed * r);\n";
      fragmentShader += "    r.x = -r.x;\n";

      fragmentShader += "    float inverseRoughness = 1.04 - roughness;\n";
      fragmentShader += "    inverseRoughness *= inverseRoughness;\n";
      fragmentShader +=
        "    vec3 sceneSkyBox = textureCube(czm_environmentMap, r).rgb * inverseRoughness;\n";

      fragmentShader += "    float atmosphereHeight = 0.05;\n";
      fragmentShader +=
        "    float blendRegionSize = 0.1 * ((1.0 - inverseRoughness) * 8.0 + 1.1 - horizonDotNadir);\n";
      fragmentShader += "    float blendRegionOffset = roughness * -1.0;\n";
      fragmentShader +=
        "    float farAboveHorizon = clamp(horizonDotNadir - blendRegionSize * 0.5 + blendRegionOffset, 1.0e-10 - blendRegionSize, 0.99999);\n";
      fragmentShader +=
        "    float aroundHorizon = clamp(horizonDotNadir + blendRegionSize * 0.5, 1.0e-10 - blendRegionSize, 0.99999);\n";
      fragmentShader +=
        "    float farBelowHorizon = clamp(horizonDotNadir + blendRegionSize * 1.5, 1.0e-10 - blendRegionSize, 0.99999);\n";
      fragmentShader +=
        "    float smoothstepHeight = smoothstep(0.0, atmosphereHeight, horizonDotNadir);\n";

      fragmentShader +=
        "    vec3 belowHorizonColor = mix(vec3(0.1, 0.15, 0.25), vec3(0.4, 0.7, 0.9), smoothstepHeight);\n";
      fragmentShader += "    vec3 nadirColor = belowHorizonColor * 0.5;\n";
      fragmentShader +=
        "    vec3 aboveHorizonColor = mix(vec3(0.9, 1.0, 1.2), belowHorizonColor, roughness * 0.5);\n";
      fragmentShader +=
        "    vec3 blueSkyColor = mix(vec3(0.18, 0.26, 0.48), aboveHorizonColor, reflectionDotNadir * inverseRoughness * 0.5 + 0.75);\n";
      fragmentShader +=
        "    vec3 zenithColor = mix(blueSkyColor, sceneSkyBox, smoothstepHeight);\n";

      fragmentShader += "    vec3 blueSkyDiffuseColor = vec3(0.7, 0.85, 0.9);\n";
      fragmentShader +=
        "    float diffuseIrradianceFromEarth = (1.0 - horizonDotNadir) * (reflectionDotNadir * 0.25 + 0.75) * smoothstepHeight;\n";
      fragmentShader +=
        "    float diffuseIrradianceFromSky = (1.0 - smoothstepHeight) * (1.0 - (reflectionDotNadir * 0.25 + 0.25));\n";
      fragmentShader +=
        "    vec3 diffuseIrradiance = blueSkyDiffuseColor * clamp(diffuseIrradianceFromEarth + diffuseIrradianceFromSky, 0.0, 1.0);\n";

      fragmentShader +=
        "    float notDistantRough = (1.0 - horizonDotNadir * roughness * 0.8);\n";
      fragmentShader +=
        "    vec3 specularIrradiance = mix(zenithColor, aboveHorizonColor, smoothstep(farAboveHorizon, aroundHorizon, reflectionDotNadir) * notDistantRough);\n";
      fragmentShader +=
        "    specularIrradiance = mix(specularIrradiance, belowHorizonColor, smoothstep(aroundHorizon, farBelowHorizon, reflectionDotNadir) * inverseRoughness);\n";
      fragmentShader +=
        "    specularIrradiance = mix(specularIrradiance, nadirColor, smoothstep(farBelowHorizon, 1.0, reflectionDotNadir) * inverseRoughness);\n";

      // Luminance model from page 40 of http://silviojemma.com/public/papers/lighting/spherical-harmonic-lighting.pdf
      fragmentShader += "#ifdef USE_SUN_LUMINANCE \n";
      // Angle between sun and zenith
      fragmentShader +=
        "    float LdotZenith = clamp(dot(normalize(czm_inverseViewRotation * l), normalize(positionWC * -1.0)), 0.001, 1.0);\n";
      fragmentShader += "    float S = acos(LdotZenith);\n";
      // Angle between zenith and current pixel
      fragmentShader +=
        "    float NdotZenith = clamp(dot(normalize(czm_inverseViewRotation * n), normalize(positionWC * -1.0)), 0.001, 1.0);\n";
      // Angle between sun and current pixel
      fragmentShader += "    float gamma = acos(NdotL);\n";
      fragmentShader +=
        "    float numerator = ((0.91 + 10.0 * exp(-3.0 * gamma) + 0.45 * pow(NdotL, 2.0)) * (1.0 - exp(-0.32 / NdotZenith)));\n";
      fragmentShader +=
        "    float denominator = (0.91 + 10.0 * exp(-3.0 * S) + 0.45 * pow(LdotZenith,2.0)) * (1.0 - exp(-0.32));\n";
      fragmentShader +=
        "    float luminance = gltf_luminanceAtZenith * (numerator / denominator);\n";
      fragmentShader += "#endif \n";

      fragmentShader +=
        "    vec2 brdfLut = texture2D(czm_brdfLut, vec2(NdotV, roughness)).rg;\n";
      fragmentShader +=
        "    vec3 IBLColor = (diffuseIrradiance * diffuseColor * gltf_iblFactor.x) + (specularIrradiance * SRGBtoLINEAR3(specularColor * brdfLut.x + brdfLut.y) * gltf_iblFactor.y);\n";

      fragmentShader +=
        "    float maximumComponent = max(max(lightColorHdr.x, lightColorHdr.y), lightColorHdr.z);\n";
      fragmentShader +=
        "    vec3 lightColor = lightColorHdr / max(maximumComponent, 1.0);\n";
      fragmentShader += "    IBLColor *= lightColor;\n";

      fragmentShader += "#ifdef USE_SUN_LUMINANCE \n";
      fragmentShader += "    color += IBLColor * luminance;\n";
      fragmentShader += "#else \n";
      fragmentShader += "    color += IBLColor; \n";
      fragmentShader += "#endif \n";

      // Environment maps were provided, use them for IBL
      fragmentShader += "#elif defined(DIFFUSE_IBL) || defined(SPECULAR_IBL) \n";
      fragmentShader +=
        "    const mat3 yUpToZUp = mat3(-1.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 1.0, 0.0); \n";
      fragmentShader +=
        "    vec3 cubeDir = normalize(yUpToZUp * gltf_iblReferenceFrameMatrix * normalize(reflect(-v, n))); \n";

      fragmentShader += "#ifdef DIFFUSE_IBL \n";
      fragmentShader += "#ifdef CUSTOM_SPHERICAL_HARMONICS \n";
      fragmentShader +=
        "    vec3 diffuseIrradiance = czm_sphericalHarmonics(cubeDir, gltf_sphericalHarmonicCoefficients); \n";
      fragmentShader += "#else \n";
      fragmentShader +=
        "    vec3 diffuseIrradiance = czm_sphericalHarmonics(cubeDir, czm_sphericalHarmonicCoefficients); \n";
      fragmentShader += "#endif \n";
      fragmentShader += "#else \n";
      fragmentShader += "    vec3 diffuseIrradiance = vec3(0.0); \n";
      fragmentShader += "#endif \n";

      fragmentShader += "#ifdef SPECULAR_IBL \n";
      fragmentShader +=
        "    vec2 brdfLut = texture2D(czm_brdfLut, vec2(NdotV, roughness)).rg;\n";
      fragmentShader += "#ifdef CUSTOM_SPECULAR_IBL \n";
      fragmentShader +=
        "    vec3 specularIBL = czm_sampleOctahedralProjection(gltf_specularMap, gltf_specularMapSize, cubeDir,  roughness * gltf_maxSpecularLOD, gltf_maxSpecularLOD);\n";
      fragmentShader += "#else \n";
      fragmentShader +=
        "    vec3 specularIBL = czm_sampleOctahedralProjection(czm_specularEnvironmentMaps, czm_specularEnvironmentMapSize, cubeDir,  roughness * czm_specularEnvironmentMapsMaximumLOD, czm_specularEnvironmentMapsMaximumLOD);\n";
      fragmentShader += "#endif \n";
      fragmentShader += "    specularIBL *= F * brdfLut.x + brdfLut.y;\n";
      fragmentShader += "#else \n";
      fragmentShader += "    vec3 specularIBL = vec3(0.0); \n";
      fragmentShader += "#endif \n";

      fragmentShader +=
        "    color += diffuseIrradiance * diffuseColor + specularColor * specularIBL;\n";

      fragmentShader += "#endif \n";
    } else {
      fragmentShader += "    vec3 color = baseColor;\n";
    }

    // Ignore occlusion and emissive when unlit
    if (!isUnlit) {
      if (defined(generatedMaterialValues.u_occlusionTexture)) {
        fragmentShader += `    color *= texture2D(u_occlusionTexture, ${occlusionTexCoord}).r;\n`;
      }
      if (defined(generatedMaterialValues.u_emissiveTexture)) {
        fragmentShader += `    vec3 emissive = SRGBtoLINEAR3(texture2D(u_emissiveTexture, ${emissiveTexCoord}).rgb);\n`;
        if (defined(generatedMaterialValues.u_emissiveFactor)) {
          fragmentShader += "    emissive *= u_emissiveFactor;\n";
        }
        fragmentShader += "    color += emissive;\n";
      } else if (defined(generatedMaterialValues.u_emissiveFactor)) {
        fragmentShader += "    color += u_emissiveFactor;\n";
      }
    }

    if (!isUnlit) {
      fragmentShader += "    color = applyTonemapping(color);\n";
    }

    fragmentShader += "    color = LINEARtoSRGB(color);\n";

    if (hasOutline) {
      fragmentShader += "    float outlineness = max(\n";
      fragmentShader +=
        "        texture2D(u_outlineTexture, vec2(v_outlineCoordinates.x, 0.5)).r,\n";
      fragmentShader += "        max(\n";
      fragmentShader +=
        "          texture2D(u_outlineTexture, vec2(v_outlineCoordinates.y, 0.5)).r,\n";
      fragmentShader +=
        "          texture2D(u_outlineTexture, vec2(v_outlineCoordinates.z, 0.5)).r));\n";
      fragmentShader +=
        "    color = mix(color, vec3(0.0, 0.0, 0.0), outlineness);\n";
    }

    if (defined(alphaMode)) {
      if (alphaMode === "MASK") {
        fragmentShader += "    if (baseColorWithAlpha.a < u_alphaCutoff) {\n";
        fragmentShader += "        discard;\n";
        fragmentShader += "    }\n";
        fragmentShader += "    gl_FragColor = vec4(color, 1.0);\n";
      } else if (alphaMode === "BLEND") {
        fragmentShader +=
          "    gl_FragColor = vec4(color, baseColorWithAlpha.a);\n";
      } else {
        fragmentShader += "    gl_FragColor = vec4(color, 1.0);\n";
      }
    } else {
      fragmentShader += "    gl_FragColor = vec4(color, 1.0);\n";
    }

    fragmentShader += "}\n";

    // Add shaders
    const vertexShaderId = addToArray(shaders, {
      type: WebGLConstants$1.VERTEX_SHADER,
      extras: {
        _pipeline: {
          source: vertexShader,
          extension: ".glsl",
        },
      },
    });

    const fragmentShaderId = addToArray(shaders, {
      type: WebGLConstants$1.FRAGMENT_SHADER,
      extras: {
        _pipeline: {
          source: fragmentShader,
          extension: ".glsl",
        },
      },
    });

    // Add program
    const programId = addToArray(programs, {
      fragmentShader: fragmentShaderId,
      vertexShader: vertexShaderId,
    });

    const techniqueId = addToArray(techniques, {
      attributes: techniqueAttributes,
      program: programId,
      uniforms: techniqueUniforms,
    });

    return techniqueId;
  }

  function getPBRValueType(paramName) {
    if (paramName.indexOf("Offset") !== -1) {
      return WebGLConstants$1.FLOAT_VEC2;
    } else if (paramName.indexOf("Rotation") !== -1) {
      return WebGLConstants$1.FLOAT;
    } else if (paramName.indexOf("Scale") !== -1) {
      return WebGLConstants$1.FLOAT_VEC2;
    } else if (paramName.indexOf("Texture") !== -1) {
      return WebGLConstants$1.SAMPLER_2D;
    }

    switch (paramName) {
      case "u_baseColorFactor":
        return WebGLConstants$1.FLOAT_VEC4;
      case "u_metallicFactor":
        return WebGLConstants$1.FLOAT;
      case "u_roughnessFactor":
        return WebGLConstants$1.FLOAT;
      case "u_emissiveFactor":
        return WebGLConstants$1.FLOAT_VEC3;
      // Specular Glossiness Types
      case "u_diffuseFactor":
        return WebGLConstants$1.FLOAT_VEC4;
      case "u_specularFactor":
        return WebGLConstants$1.FLOAT_VEC3;
      case "u_glossinessFactor":
        return WebGLConstants$1.FLOAT;
    }
  }

  /**
   * Describes a renderable batch of geometry.
   *
   * @alias Vector3DTileBatch
   * @constructor
   *
   * @param {Object} options An object with the following properties:
   * @param {Number} options.offset The offset of the batch into the indices buffer.
   * @param {Number} options.count The number of indices in the batch.
   * @param {Color} options.color The color of the geometry in the batch.
   * @param {Number[]} options.batchIds An array where each element is the batch id of the geometry in the batch.
   *
   * @private
   */
  function Vector3DTileBatch(options) {
    /**
     * The offset of the batch into the indices buffer.
     * @type {Number}
     */
    this.offset = options.offset;
    /**
     * The number of indices in the batch.
     * @type {Number}
     */
    this.count = options.count;
    /**
     * The color of the geometry in the batch.
     * @type {Color}
     */
    this.color = options.color;
    /**
     * An array where each element is the batch id of the geometry in the batch.
     * @type {Number[]}
     */
    this.batchIds = options.batchIds;
  }

  //This file is automatically rebuilt by the Cesium build process.
  var VectorTileVS = "attribute vec3 position;\n\
attribute float a_batchId;\n\
uniform mat4 u_modifiedModelViewProjection;\n\
void main()\n\
{\n\
gl_Position = czm_depthClamp(u_modifiedModelViewProjection * vec4(position, 1.0));\n\
}\n\
";

  /* This file is automatically rebuilt by the Cesium build process. */

  var jsep = createCommonjsModule(function (module, exports) {
  //     JavaScript Expression Parser (JSEP) 0.3.5
  //     JSEP may be freely distributed under the MIT License
  //     https://ericsmekens.github.io/jsep/

  /*global module: true, exports: true, console: true */
  (function (root) {
  	// Node Types
  	// ----------

  	// This is the full set of types that any JSEP node can be.
  	// Store them here to save space when minified
  	var COMPOUND = 'Compound',
  		IDENTIFIER = 'Identifier',
  		MEMBER_EXP = 'MemberExpression',
  		LITERAL = 'Literal',
  		THIS_EXP = 'ThisExpression',
  		CALL_EXP = 'CallExpression',
  		UNARY_EXP = 'UnaryExpression',
  		BINARY_EXP = 'BinaryExpression',
  		LOGICAL_EXP = 'LogicalExpression',
  		CONDITIONAL_EXP = 'ConditionalExpression',
  		ARRAY_EXP = 'ArrayExpression',

  		PERIOD_CODE = 46, // '.'
  		COMMA_CODE  = 44, // ','
  		SQUOTE_CODE = 39, // single quote
  		DQUOTE_CODE = 34, // double quotes
  		OPAREN_CODE = 40, // (
  		CPAREN_CODE = 41, // )
  		OBRACK_CODE = 91, // [
  		CBRACK_CODE = 93, // ]
  		QUMARK_CODE = 63, // ?
  		SEMCOL_CODE = 59, // ;
  		COLON_CODE  = 58, // :

  		throwError = function(message, index) {
  			var error = new Error(message + ' at character ' + index);
  			error.index = index;
  			error.description = message;
  			throw error;
  		},

  	// Operations
  	// ----------

  	// Set `t` to `true` to save space (when minified, not gzipped)
  		t = true,
  	// Use a quickly-accessible map to store all of the unary operators
  	// Values are set to `true` (it really doesn't matter)
  		unary_ops = {'-': t, '!': t, '~': t, '+': t},
  	// Also use a map for the binary operations but set their values to their
  	// binary precedence for quick reference:
  	// see [Order of operations](http://en.wikipedia.org/wiki/Order_of_operations#Programming_language)
  		binary_ops = {
  			'||': 1, '&&': 2, '|': 3,  '^': 4,  '&': 5,
  			'==': 6, '!=': 6, '===': 6, '!==': 6,
  			'<': 7,  '>': 7,  '<=': 7,  '>=': 7,
  			'<<':8,  '>>': 8, '>>>': 8,
  			'+': 9, '-': 9,
  			'*': 10, '/': 10, '%': 10
  		},
  	// Get return the longest key length of any object
  		getMaxKeyLen = function(obj) {
  			var max_len = 0, len;
  			for(var key in obj) {
  				if((len = key.length) > max_len && obj.hasOwnProperty(key)) {
  					max_len = len;
  				}
  			}
  			return max_len;
  		},
  		max_unop_len = getMaxKeyLen(unary_ops),
  		max_binop_len = getMaxKeyLen(binary_ops),
  	// Literals
  	// ----------
  	// Store the values to return for the various literals we may encounter
  		literals = {
  			'true': true,
  			'false': false,
  			'null': null
  		},
  	// Except for `this`, which is special. This could be changed to something like `'self'` as well
  		this_str = 'this',
  	// Returns the precedence of a binary operator or `0` if it isn't a binary operator
  		binaryPrecedence = function(op_val) {
  			return binary_ops[op_val] || 0;
  		},
  	// Utility function (gets called from multiple places)
  	// Also note that `a && b` and `a || b` are *logical* expressions, not binary expressions
  		createBinaryExpression = function (operator, left, right) {
  			var type = (operator === '||' || operator === '&&') ? LOGICAL_EXP : BINARY_EXP;
  			return {
  				type: type,
  				operator: operator,
  				left: left,
  				right: right
  			};
  		},
  		// `ch` is a character code in the next three functions
  		isDecimalDigit = function(ch) {
  			return (ch >= 48 && ch <= 57); // 0...9
  		},
  		isIdentifierStart = function(ch) {
  			return (ch === 36) || (ch === 95) || // `$` and `_`
  					(ch >= 65 && ch <= 90) || // A...Z
  					(ch >= 97 && ch <= 122) || // a...z
                      (ch >= 128 && !binary_ops[String.fromCharCode(ch)]); // any non-ASCII that is not an operator
  		},
  		isIdentifierPart = function(ch) {
  			return (ch === 36) || (ch === 95) || // `$` and `_`
  					(ch >= 65 && ch <= 90) || // A...Z
  					(ch >= 97 && ch <= 122) || // a...z
  					(ch >= 48 && ch <= 57) || // 0...9
                      (ch >= 128 && !binary_ops[String.fromCharCode(ch)]); // any non-ASCII that is not an operator
  		},

  		// Parsing
  		// -------
  		// `expr` is a string with the passed in expression
  		jsep = function(expr) {
  			// `index` stores the character number we are currently at while `length` is a constant
  			// All of the gobbles below will modify `index` as we move along
  			var index = 0,
  				charAtFunc = expr.charAt,
  				charCodeAtFunc = expr.charCodeAt,
  				exprI = function(i) { return charAtFunc.call(expr, i); },
  				exprICode = function(i) { return charCodeAtFunc.call(expr, i); },
  				length = expr.length,

  				// Push `index` up to the next non-space character
  				gobbleSpaces = function() {
  					var ch = exprICode(index);
  					// space or tab
  					while(ch === 32 || ch === 9 || ch === 10 || ch === 13) {
  						ch = exprICode(++index);
  					}
  				},

  				// The main parsing function. Much of this code is dedicated to ternary expressions
  				gobbleExpression = function() {
  					var test = gobbleBinaryExpression(),
  						consequent, alternate;
  					gobbleSpaces();
  					if(exprICode(index) === QUMARK_CODE) {
  						// Ternary expression: test ? consequent : alternate
  						index++;
  						consequent = gobbleExpression();
  						if(!consequent) {
  							throwError('Expected expression', index);
  						}
  						gobbleSpaces();
  						if(exprICode(index) === COLON_CODE) {
  							index++;
  							alternate = gobbleExpression();
  							if(!alternate) {
  								throwError('Expected expression', index);
  							}
  							return {
  								type: CONDITIONAL_EXP,
  								test: test,
  								consequent: consequent,
  								alternate: alternate
  							};
  						} else {
  							throwError('Expected :', index);
  						}
  					} else {
  						return test;
  					}
  				},

  				// Search for the operation portion of the string (e.g. `+`, `===`)
  				// Start by taking the longest possible binary operations (3 characters: `===`, `!==`, `>>>`)
  				// and move down from 3 to 2 to 1 character until a matching binary operation is found
  				// then, return that binary operation
  				gobbleBinaryOp = function() {
  					gobbleSpaces();
  					var to_check = expr.substr(index, max_binop_len), tc_len = to_check.length;
  					while(tc_len > 0) {
  						// Don't accept a binary op when it is an identifier.
  						// Binary ops that start with a identifier-valid character must be followed
  						// by a non identifier-part valid character
  						if(binary_ops.hasOwnProperty(to_check) && (
  							!isIdentifierStart(exprICode(index)) ||
  							(index+to_check.length< expr.length && !isIdentifierPart(exprICode(index+to_check.length)))
  						)) {
  							index += tc_len;
  							return to_check;
  						}
  						to_check = to_check.substr(0, --tc_len);
  					}
  					return false;
  				},

  				// This function is responsible for gobbling an individual expression,
  				// e.g. `1`, `1+2`, `a+(b*2)-Math.sqrt(2)`
  				gobbleBinaryExpression = function() {
  					var node, biop, prec, stack, biop_info, left, right, i, cur_biop;

  					// First, try to get the leftmost thing
  					// Then, check to see if there's a binary operator operating on that leftmost thing
  					left = gobbleToken();
  					biop = gobbleBinaryOp();

  					// If there wasn't a binary operator, just return the leftmost node
  					if(!biop) {
  						return left;
  					}

  					// Otherwise, we need to start a stack to properly place the binary operations in their
  					// precedence structure
  					biop_info = { value: biop, prec: binaryPrecedence(biop)};

  					right = gobbleToken();
  					if(!right) {
  						throwError("Expected expression after " + biop, index);
  					}
  					stack = [left, biop_info, right];

  					// Properly deal with precedence using [recursive descent](http://www.engr.mun.ca/~theo/Misc/exp_parsing.htm)
  					while((biop = gobbleBinaryOp())) {
  						prec = binaryPrecedence(biop);

  						if(prec === 0) {
  							break;
  						}
  						biop_info = { value: biop, prec: prec };

  						cur_biop = biop;
  						// Reduce: make a binary expression from the three topmost entries.
  						while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) {
  							right = stack.pop();
  							biop = stack.pop().value;
  							left = stack.pop();
  							node = createBinaryExpression(biop, left, right);
  							stack.push(node);
  						}

  						node = gobbleToken();
  						if(!node) {
  							throwError("Expected expression after " + cur_biop, index);
  						}
  						stack.push(biop_info, node);
  					}

  					i = stack.length - 1;
  					node = stack[i];
  					while(i > 1) {
  						node = createBinaryExpression(stack[i - 1].value, stack[i - 2], node);
  						i -= 2;
  					}
  					return node;
  				},

  				// An individual part of a binary expression:
  				// e.g. `foo.bar(baz)`, `1`, `"abc"`, `(a % 2)` (because it's in parenthesis)
  				gobbleToken = function() {
  					var ch, to_check, tc_len;

  					gobbleSpaces();
  					ch = exprICode(index);

  					if(isDecimalDigit(ch) || ch === PERIOD_CODE) {
  						// Char code 46 is a dot `.` which can start off a numeric literal
  						return gobbleNumericLiteral();
  					} else if(ch === SQUOTE_CODE || ch === DQUOTE_CODE) {
  						// Single or double quotes
  						return gobbleStringLiteral();
  					} else if (ch === OBRACK_CODE) {
  						return gobbleArray();
  					} else {
  						to_check = expr.substr(index, max_unop_len);
  						tc_len = to_check.length;
  						while(tc_len > 0) {
  						// Don't accept an unary op when it is an identifier.
  						// Unary ops that start with a identifier-valid character must be followed
  						// by a non identifier-part valid character
  							if(unary_ops.hasOwnProperty(to_check) && (
  								!isIdentifierStart(exprICode(index)) ||
  								(index+to_check.length < expr.length && !isIdentifierPart(exprICode(index+to_check.length)))
  							)) {
  								index += tc_len;
  								return {
  									type: UNARY_EXP,
  									operator: to_check,
  									argument: gobbleToken(),
  									prefix: true
  								};
  							}
  							to_check = to_check.substr(0, --tc_len);
  						}

  						if (isIdentifierStart(ch) || ch === OPAREN_CODE) { // open parenthesis
  							// `foo`, `bar.baz`
  							return gobbleVariable();
  						}
  					}

  					return false;
  				},
  				// Parse simple numeric literals: `12`, `3.4`, `.5`. Do this by using a string to
  				// keep track of everything in the numeric literal and then calling `parseFloat` on that string
  				gobbleNumericLiteral = function() {
  					var number = '', ch, chCode;
  					while(isDecimalDigit(exprICode(index))) {
  						number += exprI(index++);
  					}

  					if(exprICode(index) === PERIOD_CODE) { // can start with a decimal marker
  						number += exprI(index++);

  						while(isDecimalDigit(exprICode(index))) {
  							number += exprI(index++);
  						}
  					}

  					ch = exprI(index);
  					if(ch === 'e' || ch === 'E') { // exponent marker
  						number += exprI(index++);
  						ch = exprI(index);
  						if(ch === '+' || ch === '-') { // exponent sign
  							number += exprI(index++);
  						}
  						while(isDecimalDigit(exprICode(index))) { //exponent itself
  							number += exprI(index++);
  						}
  						if(!isDecimalDigit(exprICode(index-1)) ) {
  							throwError('Expected exponent (' + number + exprI(index) + ')', index);
  						}
  					}


  					chCode = exprICode(index);
  					// Check to make sure this isn't a variable name that start with a number (123abc)
  					if(isIdentifierStart(chCode)) {
  						throwError('Variable names cannot start with a number (' +
  									number + exprI(index) + ')', index);
  					} else if(chCode === PERIOD_CODE) {
  						throwError('Unexpected period', index);
  					}

  					return {
  						type: LITERAL,
  						value: parseFloat(number),
  						raw: number
  					};
  				},

  				// Parses a string literal, staring with single or double quotes with basic support for escape codes
  				// e.g. `"hello world"`, `'this is\nJSEP'`
  				gobbleStringLiteral = function() {
  					var str = '', quote = exprI(index++), closed = false, ch;

  					while(index < length) {
  						ch = exprI(index++);
  						if(ch === quote) {
  							closed = true;
  							break;
  						} else if(ch === '\\') {
  							// Check for all of the common escape codes
  							ch = exprI(index++);
  							switch(ch) {
  								case 'n': str += '\n'; break;
  								case 'r': str += '\r'; break;
  								case 't': str += '\t'; break;
  								case 'b': str += '\b'; break;
  								case 'f': str += '\f'; break;
  								case 'v': str += '\x0B'; break;
  								default : str += ch;
  							}
  						} else {
  							str += ch;
  						}
  					}

  					if(!closed) {
  						throwError('Unclosed quote after "'+str+'"', index);
  					}

  					return {
  						type: LITERAL,
  						value: str,
  						raw: quote + str + quote
  					};
  				},

  				// Gobbles only identifiers
  				// e.g.: `foo`, `_value`, `$x1`
  				// Also, this function checks if that identifier is a literal:
  				// (e.g. `true`, `false`, `null`) or `this`
  				gobbleIdentifier = function() {
  					var ch = exprICode(index), start = index, identifier;

  					if(isIdentifierStart(ch)) {
  						index++;
  					} else {
  						throwError('Unexpected ' + exprI(index), index);
  					}

  					while(index < length) {
  						ch = exprICode(index);
  						if(isIdentifierPart(ch)) {
  							index++;
  						} else {
  							break;
  						}
  					}
  					identifier = expr.slice(start, index);

  					if(literals.hasOwnProperty(identifier)) {
  						return {
  							type: LITERAL,
  							value: literals[identifier],
  							raw: identifier
  						};
  					} else if(identifier === this_str) {
  						return { type: THIS_EXP };
  					} else {
  						return {
  							type: IDENTIFIER,
  							name: identifier
  						};
  					}
  				},

  				// Gobbles a list of arguments within the context of a function call
  				// or array literal. This function also assumes that the opening character
  				// `(` or `[` has already been gobbled, and gobbles expressions and commas
  				// until the terminator character `)` or `]` is encountered.
  				// e.g. `foo(bar, baz)`, `my_func()`, or `[bar, baz]`
  				gobbleArguments = function(termination) {
  					var ch_i, args = [], node, closed = false;
  					var separator_count = 0;
  					while(index < length) {
  						gobbleSpaces();
  						ch_i = exprICode(index);
  						if(ch_i === termination) { // done parsing
  							closed = true;
  							index++;
  							if(termination === CPAREN_CODE && separator_count && separator_count >= args.length){
  								throwError('Unexpected token ' + String.fromCharCode(termination), index);
  							}
  							break;
  						} else if (ch_i === COMMA_CODE) { // between expressions
  							index++;
  							separator_count++;
  							if(separator_count !== args.length) { // missing argument
  								if(termination === CPAREN_CODE) {
  									throwError('Unexpected token ,', index);
  								}
  								else if(termination === CBRACK_CODE) {
  									for(var arg = args.length; arg< separator_count; arg++) {
  										args.push(null);
  									}
  								}
  							}
  						} else {
  							node = gobbleExpression();
  							if(!node || node.type === COMPOUND) {
  								throwError('Expected comma', index);
  							}
  							args.push(node);
  						}
  					}
  					if (!closed) {
  						throwError('Expected ' + String.fromCharCode(termination), index);
  					}
  					return args;
  				},

  				// Gobble a non-literal variable name. This variable name may include properties
  				// e.g. `foo`, `bar.baz`, `foo['bar'].baz`
  				// It also gobbles function calls:
  				// e.g. `Math.acos(obj.angle)`
  				gobbleVariable = function() {
  					var ch_i, node;
  					ch_i = exprICode(index);

  					if(ch_i === OPAREN_CODE) {
  						node = gobbleGroup();
  					} else {
  						node = gobbleIdentifier();
  					}
  					gobbleSpaces();
  					ch_i = exprICode(index);
  					while(ch_i === PERIOD_CODE || ch_i === OBRACK_CODE || ch_i === OPAREN_CODE) {
  						index++;
  						if(ch_i === PERIOD_CODE) {
  							gobbleSpaces();
  							node = {
  								type: MEMBER_EXP,
  								computed: false,
  								object: node,
  								property: gobbleIdentifier()
  							};
  						} else if(ch_i === OBRACK_CODE) {
  							node = {
  								type: MEMBER_EXP,
  								computed: true,
  								object: node,
  								property: gobbleExpression()
  							};
  							gobbleSpaces();
  							ch_i = exprICode(index);
  							if(ch_i !== CBRACK_CODE) {
  								throwError('Unclosed [', index);
  							}
  							index++;
  						} else if(ch_i === OPAREN_CODE) {
  							// A function call is being made; gobble all the arguments
  							node = {
  								type: CALL_EXP,
  								'arguments': gobbleArguments(CPAREN_CODE),
  								callee: node
  							};
  						}
  						gobbleSpaces();
  						ch_i = exprICode(index);
  					}
  					return node;
  				},

  				// Responsible for parsing a group of things within parentheses `()`
  				// This function assumes that it needs to gobble the opening parenthesis
  				// and then tries to gobble everything within that parenthesis, assuming
  				// that the next thing it should see is the close parenthesis. If not,
  				// then the expression probably doesn't have a `)`
  				gobbleGroup = function() {
  					index++;
  					var node = gobbleExpression();
  					gobbleSpaces();
  					if(exprICode(index) === CPAREN_CODE) {
  						index++;
  						return node;
  					} else {
  						throwError('Unclosed (', index);
  					}
  				},

  				// Responsible for parsing Array literals `[1, 2, 3]`
  				// This function assumes that it needs to gobble the opening bracket
  				// and then tries to gobble the expressions as arguments.
  				gobbleArray = function() {
  					index++;
  					return {
  						type: ARRAY_EXP,
  						elements: gobbleArguments(CBRACK_CODE)
  					};
  				},

  				nodes = [], ch_i, node;

  			while(index < length) {
  				ch_i = exprICode(index);

  				// Expressions can be separated by semicolons, commas, or just inferred without any
  				// separators
  				if(ch_i === SEMCOL_CODE || ch_i === COMMA_CODE) {
  					index++; // ignore separators
  				} else {
  					// Try to gobble each expression individually
  					if((node = gobbleExpression())) {
  						nodes.push(node);
  					// If we weren't able to find a binary expression and are out of room, then
  					// the expression passed in probably has too much
  					} else if(index < length) {
  						throwError('Unexpected "' + exprI(index) + '"', index);
  					}
  				}
  			}

  			// If there's only one expression just try returning the expression
  			if(nodes.length === 1) {
  				return nodes[0];
  			} else {
  				return {
  					type: COMPOUND,
  					body: nodes
  				};
  			}
  		};

  	// To be filled in by the template
  	jsep.version = '0.3.5';
  	jsep.toString = function() { return 'JavaScript Expression Parser (JSEP) v' + jsep.version; };

  	/**
  	 * @method jsep.addUnaryOp
  	 * @param {string} op_name The name of the unary op to add
  	 * @return jsep
  	 */
  	jsep.addUnaryOp = function(op_name) {
  		max_unop_len = Math.max(op_name.length, max_unop_len);
  		unary_ops[op_name] = t; return this;
  	};

  	/**
  	 * @method jsep.addBinaryOp
  	 * @param {string} op_name The name of the binary op to add
  	 * @param {number} precedence The precedence of the binary op (can be a float)
  	 * @return jsep
  	 */
  	jsep.addBinaryOp = function(op_name, precedence) {
  		max_binop_len = Math.max(op_name.length, max_binop_len);
  		binary_ops[op_name] = precedence;
  		return this;
  	};

  	/**
  	 * @method jsep.addLiteral
  	 * @param {string} literal_name The name of the literal to add
  	 * @param {*} literal_value The value of the literal
  	 * @return jsep
  	 */
  	jsep.addLiteral = function(literal_name, literal_value) {
  		literals[literal_name] = literal_value;
  		return this;
  	};

  	/**
  	 * @method jsep.removeUnaryOp
  	 * @param {string} op_name The name of the unary op to remove
  	 * @return jsep
  	 */
  	jsep.removeUnaryOp = function(op_name) {
  		delete unary_ops[op_name];
  		if(op_name.length === max_unop_len) {
  			max_unop_len = getMaxKeyLen(unary_ops);
  		}
  		return this;
  	};

  	/**
  	 * @method jsep.removeAllUnaryOps
  	 * @return jsep
  	 */
  	jsep.removeAllUnaryOps = function() {
  		unary_ops = {};
  		max_unop_len = 0;

  		return this;
  	};

  	/**
  	 * @method jsep.removeBinaryOp
  	 * @param {string} op_name The name of the binary op to remove
  	 * @return jsep
  	 */
  	jsep.removeBinaryOp = function(op_name) {
  		delete binary_ops[op_name];
  		if(op_name.length === max_binop_len) {
  			max_binop_len = getMaxKeyLen(binary_ops);
  		}
  		return this;
  	};

  	/**
  	 * @method jsep.removeAllBinaryOps
  	 * @return jsep
  	 */
  	jsep.removeAllBinaryOps = function() {
  		binary_ops = {};
  		max_binop_len = 0;

  		return this;
  	};

  	/**
  	 * @method jsep.removeLiteral
  	 * @param {string} literal_name The name of the literal to remove
  	 * @return jsep
  	 */
  	jsep.removeLiteral = function(literal_name) {
  		delete literals[literal_name];
  		return this;
  	};

  	/**
  	 * @method jsep.removeAllLiterals
  	 * @return jsep
  	 */
  	jsep.removeAllLiterals = function() {
  		literals = {};

  		return this;
  	};

  	// In desktop environments, have a way to restore the old value for `jsep`
  	{
  		// In Node.JS environments
  		if (module.exports) {
  			exports = module.exports = jsep;
  		} else {
  			exports.parse = jsep;
  		}
  	}
  }());
  });

  /**
   * @private
   */
  const ExpressionNodeType = {
    VARIABLE: 0,
    UNARY: 1,
    BINARY: 2,
    TERNARY: 3,
    CONDITIONAL: 4,
    MEMBER: 5,
    FUNCTION_CALL: 6,
    ARRAY: 7,
    REGEX: 8,
    VARIABLE_IN_STRING: 9,
    LITERAL_NULL: 10,
    LITERAL_BOOLEAN: 11,
    LITERAL_NUMBER: 12,
    LITERAL_STRING: 13,
    LITERAL_COLOR: 14,
    LITERAL_VECTOR: 15,
    LITERAL_REGEX: 16,
    LITERAL_UNDEFINED: 17,
    BUILTIN_VARIABLE: 18,
  };
  var ExpressionNodeType$1 = Object.freeze(ExpressionNodeType);

  /**
   * An expression for a style applied to a {@link Cesium3DTileset}.
   * <p>
   * Evaluates an expression defined using the
   * {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/Styling|3D Tiles Styling language}.
   * </p>
   * <p>
   * Implements the {@link StyleExpression} interface.
   * </p>
   *
   * @alias Expression
   * @constructor
   *
   * @param {String} [expression] The expression defined using the 3D Tiles Styling language.
   * @param {Object} [defines] Defines in the style.
   *
   * @example
   * const expression = new Cesium.Expression('(regExp("^Chest").test(${County})) && (${YearBuilt} >= 1970)');
   * expression.evaluate(feature); // returns true or false depending on the feature's properties
   *
   * @example
   * const expression = new Cesium.Expression('(${Temperature} > 90) ? color("red") : color("white")');
   * expression.evaluateColor(feature, result); // returns a Cesium.Color object
   */
  function Expression(expression, defines) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("expression", expression);
    //>>includeEnd('debug');

    this._expression = expression;
    expression = replaceDefines(expression, defines);
    expression = replaceVariables(removeBackslashes(expression));

    // customize jsep operators
    jsep.addBinaryOp("=~", 0);
    jsep.addBinaryOp("!~", 0);

    let ast;
    try {
      ast = jsep(expression);
    } catch (e) {
      throw new RuntimeError(e);
    }

    this._runtimeAst = createRuntimeAst(this, ast);
  }

  Object.defineProperties(Expression.prototype, {
    /**
     * Gets the expression defined in the 3D Tiles Styling language.
     *
     * @memberof Expression.prototype
     *
     * @type {String}
     * @readonly
     *
     * @default undefined
     */
    expression: {
      get: function () {
        return this._expression;
      },
    },
  });

  // Scratch storage manager while evaluating deep expressions.
  // For example, an expression like dot(vec4(${red}), vec4(${green}) * vec4(${blue}) requires 3 scratch Cartesian4's
  const scratchStorage = {
    arrayIndex: 0,
    arrayArray: [[]],
    cartesian2Index: 0,
    cartesian3Index: 0,
    cartesian4Index: 0,
    cartesian2Array: [new Cartesian2()],
    cartesian3Array: [new Cartesian3()],
    cartesian4Array: [new Cartesian4()],
    reset: function () {
      this.arrayIndex = 0;
      this.cartesian2Index = 0;
      this.cartesian3Index = 0;
      this.cartesian4Index = 0;
    },
    getArray: function () {
      if (this.arrayIndex >= this.arrayArray.length) {
        this.arrayArray.push([]);
      }
      const array = this.arrayArray[this.arrayIndex++];
      array.length = 0;
      return array;
    },
    getCartesian2: function () {
      if (this.cartesian2Index >= this.cartesian2Array.length) {
        this.cartesian2Array.push(new Cartesian2());
      }
      return this.cartesian2Array[this.cartesian2Index++];
    },
    getCartesian3: function () {
      if (this.cartesian3Index >= this.cartesian3Array.length) {
        this.cartesian3Array.push(new Cartesian3());
      }
      return this.cartesian3Array[this.cartesian3Index++];
    },
    getCartesian4: function () {
      if (this.cartesian4Index >= this.cartesian4Array.length) {
        this.cartesian4Array.push(new Cartesian4());
      }
      return this.cartesian4Array[this.cartesian4Index++];
    },
  };

  /**
   * Evaluates the result of an expression, optionally using the provided feature's properties. If the result of
   * the expression in the
   * {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/Styling|3D Tiles Styling language}
   * is of type <code>Boolean</code>, <code>Number</code>, or <code>String</code>, the corresponding JavaScript
   * primitive type will be returned. If the result is a <code>RegExp</code>, a Javascript <code>RegExp</code>
   * object will be returned. If the result is a <code>Cartesian2</code>, <code>Cartesian3</code>, or <code>Cartesian4</code>,
   * a {@link Cartesian2}, {@link Cartesian3}, or {@link Cartesian4} object will be returned. If the <code>result</code> argument is
   * a {@link Color}, the {@link Cartesian4} value is converted to a {@link Color} and then returned.
   *
   * @param {Cesium3DTileFeature} feature The feature whose properties may be used as variables in the expression.
   * @param {Object} [result] The object onto which to store the result.
   * @returns {Boolean|Number|String|RegExp|Cartesian2|Cartesian3|Cartesian4|Color} The result of evaluating the expression.
   */
  Expression.prototype.evaluate = function (feature, result) {
    scratchStorage.reset();
    const value = this._runtimeAst.evaluate(feature);
    if (result instanceof Color && value instanceof Cartesian4) {
      return Color.fromCartesian4(value, result);
    }
    if (
      value instanceof Cartesian2 ||
      value instanceof Cartesian3 ||
      value instanceof Cartesian4
    ) {
      return value.clone(result);
    }
    return value;
  };

  /**
   * Evaluates the result of a Color expression, optionally using the provided feature's properties.
   * <p>
   * This is equivalent to {@link Expression#evaluate} but always returns a {@link Color} object.
   * </p>
   *
   * @param {Cesium3DTileFeature} feature The feature whose properties may be used as variables in the expression.
   * @param {Color} [result] The object in which to store the result
   * @returns {Color} The modified result parameter or a new Color instance if one was not provided.
   */
  Expression.prototype.evaluateColor = function (feature, result) {
    scratchStorage.reset();
    const color = this._runtimeAst.evaluate(feature);
    return Color.fromCartesian4(color, result);
  };

  /**
   * Gets the shader function for this expression.
   * Returns undefined if the shader function can't be generated from this expression.
   *
   * @param {String} functionSignature Signature of the generated function.
   * @param {Object} variableSubstitutionMap Maps variable names to shader variable names.
   * @param {Object} shaderState Stores information about the generated shader function, including whether it is translucent.
   * @param {String} returnType The return type of the generated function.
   *
   * @returns {String} The shader function.
   *
   * @private
   */
  Expression.prototype.getShaderFunction = function (
    functionSignature,
    variableSubstitutionMap,
    shaderState,
    returnType
  ) {
    let shaderExpression = this.getShaderExpression(
      variableSubstitutionMap,
      shaderState
    );

    shaderExpression =
      `${returnType} ${functionSignature}\n` +
      `{\n` +
      `    return ${shaderExpression};\n` +
      `}\n`;

    return shaderExpression;
  };

  /**
   * Gets the shader expression for this expression.
   * Returns undefined if the shader expression can't be generated from this expression.
   *
   * @param {Object} variableSubstitutionMap Maps variable names to shader variable names.
   * @param {Object} shaderState Stores information about the generated shader function, including whether it is translucent.
   *
   * @returns {String} The shader expression.
   *
   * @private
   */
  Expression.prototype.getShaderExpression = function (
    variableSubstitutionMap,
    shaderState
  ) {
    return this._runtimeAst.getShaderExpression(
      variableSubstitutionMap,
      shaderState
    );
  };

  /**
   * Gets the variables used by the expression.
   *
   * @returns {String[]} The variables used by the expression.
   *
   * @private
   */
  Expression.prototype.getVariables = function () {
    let variables = [];

    this._runtimeAst.getVariables(variables);

    // Remove duplicates
    variables = variables.filter(function (variable, index, variables) {
      return variables.indexOf(variable) === index;
    });

    return variables;
  };

  const unaryOperators = ["!", "-", "+"];
  const binaryOperators = [
    "+",
    "-",
    "*",
    "/",
    "%",
    "===",
    "!==",
    ">",
    ">=",
    "<",
    "<=",
    "&&",
    "||",
    "!~",
    "=~",
  ];

  const variableRegex = /\${(.*?)}/g; // Matches ${variable_name}
  const backslashRegex = /\\/g;
  const backslashReplacement = "@#%";
  const replacementRegex = /@#%/g;

  const scratchColor$m = new Color();

  const unaryFunctions = {
    abs: getEvaluateUnaryComponentwise(Math.abs),
    sqrt: getEvaluateUnaryComponentwise(Math.sqrt),
    cos: getEvaluateUnaryComponentwise(Math.cos),
    sin: getEvaluateUnaryComponentwise(Math.sin),
    tan: getEvaluateUnaryComponentwise(Math.tan),
    acos: getEvaluateUnaryComponentwise(Math.acos),
    asin: getEvaluateUnaryComponentwise(Math.asin),
    atan: getEvaluateUnaryComponentwise(Math.atan),
    radians: getEvaluateUnaryComponentwise(CesiumMath.toRadians),
    degrees: getEvaluateUnaryComponentwise(CesiumMath.toDegrees),
    sign: getEvaluateUnaryComponentwise(CesiumMath.sign),
    floor: getEvaluateUnaryComponentwise(Math.floor),
    ceil: getEvaluateUnaryComponentwise(Math.ceil),
    round: getEvaluateUnaryComponentwise(Math.round),
    exp: getEvaluateUnaryComponentwise(Math.exp),
    exp2: getEvaluateUnaryComponentwise(exp2),
    log: getEvaluateUnaryComponentwise(Math.log),
    log2: getEvaluateUnaryComponentwise(log2),
    fract: getEvaluateUnaryComponentwise(fract),
    length: length,
    normalize: normalize,
  };

  const binaryFunctions = {
    atan2: getEvaluateBinaryComponentwise(Math.atan2, false),
    pow: getEvaluateBinaryComponentwise(Math.pow, false),
    min: getEvaluateBinaryComponentwise(Math.min, true),
    max: getEvaluateBinaryComponentwise(Math.max, true),
    distance: distance,
    dot: dot,
    cross: cross,
  };

  const ternaryFunctions = {
    clamp: getEvaluateTernaryComponentwise(CesiumMath.clamp, true),
    mix: getEvaluateTernaryComponentwise(CesiumMath.lerp, true),
  };

  function fract(number) {
    return number - Math.floor(number);
  }

  function exp2(exponent) {
    return Math.pow(2.0, exponent);
  }

  function log2(number) {
    return CesiumMath.log2(number);
  }

  function getEvaluateUnaryComponentwise(operation) {
    return function (call, left) {
      if (typeof left === "number") {
        return operation(left);
      } else if (left instanceof Cartesian2) {
        return Cartesian2.fromElements(
          operation(left.x),
          operation(left.y),
          scratchStorage.getCartesian2()
        );
      } else if (left instanceof Cartesian3) {
        return Cartesian3.fromElements(
          operation(left.x),
          operation(left.y),
          operation(left.z),
          scratchStorage.getCartesian3()
        );
      } else if (left instanceof Cartesian4) {
        return Cartesian4.fromElements(
          operation(left.x),
          operation(left.y),
          operation(left.z),
          operation(left.w),
          scratchStorage.getCartesian4()
        );
      }
      throw new RuntimeError(
        `Function "${call}" requires a vector or number argument. Argument is ${left}.`
      );
    };
  }

  function getEvaluateBinaryComponentwise(operation, allowScalar) {
    return function (call, left, right) {
      if (allowScalar && typeof right === "number") {
        if (typeof left === "number") {
          return operation(left, right);
        } else if (left instanceof Cartesian2) {
          return Cartesian2.fromElements(
            operation(left.x, right),
            operation(left.y, right),
            scratchStorage.getCartesian2()
          );
        } else if (left instanceof Cartesian3) {
          return Cartesian3.fromElements(
            operation(left.x, right),
            operation(left.y, right),
            operation(left.z, right),
            scratchStorage.getCartesian3()
          );
        } else if (left instanceof Cartesian4) {
          return Cartesian4.fromElements(
            operation(left.x, right),
            operation(left.y, right),
            operation(left.z, right),
            operation(left.w, right),
            scratchStorage.getCartesian4()
          );
        }
      }

      if (typeof left === "number" && typeof right === "number") {
        return operation(left, right);
      } else if (left instanceof Cartesian2 && right instanceof Cartesian2) {
        return Cartesian2.fromElements(
          operation(left.x, right.x),
          operation(left.y, right.y),
          scratchStorage.getCartesian2()
        );
      } else if (left instanceof Cartesian3 && right instanceof Cartesian3) {
        return Cartesian3.fromElements(
          operation(left.x, right.x),
          operation(left.y, right.y),
          operation(left.z, right.z),
          scratchStorage.getCartesian3()
        );
      } else if (left instanceof Cartesian4 && right instanceof Cartesian4) {
        return Cartesian4.fromElements(
          operation(left.x, right.x),
          operation(left.y, right.y),
          operation(left.z, right.z),
          operation(left.w, right.w),
          scratchStorage.getCartesian4()
        );
      }

      throw new RuntimeError(
        `Function "${call}" requires vector or number arguments of matching types. Arguments are ${left} and ${right}.`
      );
    };
  }

  function getEvaluateTernaryComponentwise(operation, allowScalar) {
    return function (call, left, right, test) {
      if (allowScalar && typeof test === "number") {
        if (typeof left === "number" && typeof right === "number") {
          return operation(left, right, test);
        } else if (left instanceof Cartesian2 && right instanceof Cartesian2) {
          return Cartesian2.fromElements(
            operation(left.x, right.x, test),
            operation(left.y, right.y, test),
            scratchStorage.getCartesian2()
          );
        } else if (left instanceof Cartesian3 && right instanceof Cartesian3) {
          return Cartesian3.fromElements(
            operation(left.x, right.x, test),
            operation(left.y, right.y, test),
            operation(left.z, right.z, test),
            scratchStorage.getCartesian3()
          );
        } else if (left instanceof Cartesian4 && right instanceof Cartesian4) {
          return Cartesian4.fromElements(
            operation(left.x, right.x, test),
            operation(left.y, right.y, test),
            operation(left.z, right.z, test),
            operation(left.w, right.w, test),
            scratchStorage.getCartesian4()
          );
        }
      }

      if (
        typeof left === "number" &&
        typeof right === "number" &&
        typeof test === "number"
      ) {
        return operation(left, right, test);
      } else if (
        left instanceof Cartesian2 &&
        right instanceof Cartesian2 &&
        test instanceof Cartesian2
      ) {
        return Cartesian2.fromElements(
          operation(left.x, right.x, test.x),
          operation(left.y, right.y, test.y),
          scratchStorage.getCartesian2()
        );
      } else if (
        left instanceof Cartesian3 &&
        right instanceof Cartesian3 &&
        test instanceof Cartesian3
      ) {
        return Cartesian3.fromElements(
          operation(left.x, right.x, test.x),
          operation(left.y, right.y, test.y),
          operation(left.z, right.z, test.z),
          scratchStorage.getCartesian3()
        );
      } else if (
        left instanceof Cartesian4 &&
        right instanceof Cartesian4 &&
        test instanceof Cartesian4
      ) {
        return Cartesian4.fromElements(
          operation(left.x, right.x, test.x),
          operation(left.y, right.y, test.y),
          operation(left.z, right.z, test.z),
          operation(left.w, right.w, test.w),
          scratchStorage.getCartesian4()
        );
      }

      throw new RuntimeError(
        `Function "${call}" requires vector or number arguments of matching types. Arguments are ${left}, ${right}, and ${test}.`
      );
    };
  }

  function length(call, left) {
    if (typeof left === "number") {
      return Math.abs(left);
    } else if (left instanceof Cartesian2) {
      return Cartesian2.magnitude(left);
    } else if (left instanceof Cartesian3) {
      return Cartesian3.magnitude(left);
    } else if (left instanceof Cartesian4) {
      return Cartesian4.magnitude(left);
    }

    throw new RuntimeError(
      `Function "${call}" requires a vector or number argument. Argument is ${left}.`
    );
  }

  function normalize(call, left) {
    if (typeof left === "number") {
      return 1.0;
    } else if (left instanceof Cartesian2) {
      return Cartesian2.normalize(left, scratchStorage.getCartesian2());
    } else if (left instanceof Cartesian3) {
      return Cartesian3.normalize(left, scratchStorage.getCartesian3());
    } else if (left instanceof Cartesian4) {
      return Cartesian4.normalize(left, scratchStorage.getCartesian4());
    }

    throw new RuntimeError(
      `Function "${call}" requires a vector or number argument. Argument is ${left}.`
    );
  }

  function distance(call, left, right) {
    if (typeof left === "number" && typeof right === "number") {
      return Math.abs(left - right);
    } else if (left instanceof Cartesian2 && right instanceof Cartesian2) {
      return Cartesian2.distance(left, right);
    } else if (left instanceof Cartesian3 && right instanceof Cartesian3) {
      return Cartesian3.distance(left, right);
    } else if (left instanceof Cartesian4 && right instanceof Cartesian4) {
      return Cartesian4.distance(left, right);
    }

    throw new RuntimeError(
      `Function "${call}" requires vector or number arguments of matching types. Arguments are ${left} and ${right}.`
    );
  }

  function dot(call, left, right) {
    if (typeof left === "number" && typeof right === "number") {
      return left * right;
    } else if (left instanceof Cartesian2 && right instanceof Cartesian2) {
      return Cartesian2.dot(left, right);
    } else if (left instanceof Cartesian3 && right instanceof Cartesian3) {
      return Cartesian3.dot(left, right);
    } else if (left instanceof Cartesian4 && right instanceof Cartesian4) {
      return Cartesian4.dot(left, right);
    }

    throw new RuntimeError(
      `Function "${call}" requires vector or number arguments of matching types. Arguments are ${left} and ${right}.`
    );
  }

  function cross(call, left, right) {
    if (left instanceof Cartesian3 && right instanceof Cartesian3) {
      return Cartesian3.cross(left, right, scratchStorage.getCartesian3());
    }

    throw new RuntimeError(
      `Function "${call}" requires vec3 arguments. Arguments are ${left} and ${right}.`
    );
  }

  function Node$4(type, value, left, right, test) {
    this._type = type;
    this._value = value;
    this._left = left;
    this._right = right;
    this._test = test;
    this.evaluate = undefined;

    setEvaluateFunction(this);
  }

  function replaceDefines(expression, defines) {
    if (!defined(defines)) {
      return expression;
    }
    for (const key in defines) {
      if (defines.hasOwnProperty(key)) {
        const definePlaceholder = new RegExp(`\\$\\{${key}\\}`, "g");
        const defineReplace = `(${defines[key]})`;
        if (defined(defineReplace)) {
          expression = expression.replace(definePlaceholder, defineReplace);
        }
      }
    }
    return expression;
  }

  function removeBackslashes(expression) {
    return expression.replace(backslashRegex, backslashReplacement);
  }

  function replaceBackslashes(expression) {
    return expression.replace(replacementRegex, "\\");
  }

  function replaceVariables(expression) {
    let exp = expression;
    let result = "";
    let i = exp.indexOf("${");
    while (i >= 0) {
      // Check if string is inside quotes
      const openSingleQuote = exp.indexOf("'");
      const openDoubleQuote = exp.indexOf('"');
      let closeQuote;
      if (openSingleQuote >= 0 && openSingleQuote < i) {
        closeQuote = exp.indexOf("'", openSingleQuote + 1);
        result += exp.substr(0, closeQuote + 1);
        exp = exp.substr(closeQuote + 1);
        i = exp.indexOf("${");
      } else if (openDoubleQuote >= 0 && openDoubleQuote < i) {
        closeQuote = exp.indexOf('"', openDoubleQuote + 1);
        result += exp.substr(0, closeQuote + 1);
        exp = exp.substr(closeQuote + 1);
        i = exp.indexOf("${");
      } else {
        result += exp.substr(0, i);
        const j = exp.indexOf("}");
        if (j < 0) {
          throw new RuntimeError("Unmatched {.");
        }
        result += `czm_${exp.substr(i + 2, j - (i + 2))}`;
        exp = exp.substr(j + 1);
        i = exp.indexOf("${");
      }
    }
    result += exp;
    return result;
  }

  function parseLiteral(ast) {
    const type = typeof ast.value;
    if (ast.value === null) {
      return new Node$4(ExpressionNodeType$1.LITERAL_NULL, null);
    } else if (type === "boolean") {
      return new Node$4(ExpressionNodeType$1.LITERAL_BOOLEAN, ast.value);
    } else if (type === "number") {
      return new Node$4(ExpressionNodeType$1.LITERAL_NUMBER, ast.value);
    } else if (type === "string") {
      if (ast.value.indexOf("${") >= 0) {
        return new Node$4(ExpressionNodeType$1.VARIABLE_IN_STRING, ast.value);
      }
      return new Node$4(
        ExpressionNodeType$1.LITERAL_STRING,
        replaceBackslashes(ast.value)
      );
    }
  }

  function parseCall(expression, ast) {
    const args = ast.arguments;
    const argsLength = args.length;
    let call;
    let val, left, right;

    // Member function calls
    if (ast.callee.type === "MemberExpression") {
      call = ast.callee.property.name;
      const object = ast.callee.object;
      if (call === "test" || call === "exec") {
        // Make sure this is called on a valid type
        if (object.callee.name !== "regExp") {
          throw new RuntimeError(`${call} is not a function.`);
        }
        if (argsLength === 0) {
          if (call === "test") {
            return new Node$4(ExpressionNodeType$1.LITERAL_BOOLEAN, false);
          }
          return new Node$4(ExpressionNodeType$1.LITERAL_NULL, null);
        }
        left = createRuntimeAst(expression, object);
        right = createRuntimeAst(expression, args[0]);
        return new Node$4(ExpressionNodeType$1.FUNCTION_CALL, call, left, right);
      } else if (call === "toString") {
        val = createRuntimeAst(expression, object);
        return new Node$4(ExpressionNodeType$1.FUNCTION_CALL, call, val);
      }

      throw new RuntimeError(`Unexpected function call "${call}".`);
    }

    // Non-member function calls
    call = ast.callee.name;
    if (call === "color") {
      if (argsLength === 0) {
        return new Node$4(ExpressionNodeType$1.LITERAL_COLOR, call);
      }
      val = createRuntimeAst(expression, args[0]);
      if (defined(args[1])) {
        const alpha = createRuntimeAst(expression, args[1]);
        return new Node$4(ExpressionNodeType$1.LITERAL_COLOR, call, [val, alpha]);
      }
      return new Node$4(ExpressionNodeType$1.LITERAL_COLOR, call, [val]);
    } else if (call === "rgb" || call === "hsl") {
      if (argsLength < 3) {
        throw new RuntimeError(`${call} requires three arguments.`);
      }
      val = [
        createRuntimeAst(expression, args[0]),
        createRuntimeAst(expression, args[1]),
        createRuntimeAst(expression, args[2]),
      ];
      return new Node$4(ExpressionNodeType$1.LITERAL_COLOR, call, val);
    } else if (call === "rgba" || call === "hsla") {
      if (argsLength < 4) {
        throw new RuntimeError(`${call} requires four arguments.`);
      }
      val = [
        createRuntimeAst(expression, args[0]),
        createRuntimeAst(expression, args[1]),
        createRuntimeAst(expression, args[2]),
        createRuntimeAst(expression, args[3]),
      ];
      return new Node$4(ExpressionNodeType$1.LITERAL_COLOR, call, val);
    } else if (call === "vec2" || call === "vec3" || call === "vec4") {
      // Check for invalid constructors at evaluation time
      val = new Array(argsLength);
      for (let i = 0; i < argsLength; ++i) {
        val[i] = createRuntimeAst(expression, args[i]);
      }
      return new Node$4(ExpressionNodeType$1.LITERAL_VECTOR, call, val);
    } else if (call === "isNaN" || call === "isFinite") {
      if (argsLength === 0) {
        if (call === "isNaN") {
          return new Node$4(ExpressionNodeType$1.LITERAL_BOOLEAN, true);
        }
        return new Node$4(ExpressionNodeType$1.LITERAL_BOOLEAN, false);
      }
      val = createRuntimeAst(expression, args[0]);
      return new Node$4(ExpressionNodeType$1.UNARY, call, val);
    } else if (call === "isExactClass" || call === "isClass") {
      if (argsLength < 1 || argsLength > 1) {
        throw new RuntimeError(`${call} requires exactly one argument.`);
      }
      val = createRuntimeAst(expression, args[0]);
      return new Node$4(ExpressionNodeType$1.UNARY, call, val);
    } else if (call === "getExactClassName") {
      if (argsLength > 0) {
        throw new RuntimeError(`${call} does not take any argument.`);
      }
      return new Node$4(ExpressionNodeType$1.UNARY, call);
    } else if (defined(unaryFunctions[call])) {
      if (argsLength !== 1) {
        throw new RuntimeError(`${call} requires exactly one argument.`);
      }
      val = createRuntimeAst(expression, args[0]);
      return new Node$4(ExpressionNodeType$1.UNARY, call, val);
    } else if (defined(binaryFunctions[call])) {
      if (argsLength !== 2) {
        throw new RuntimeError(`${call} requires exactly two arguments.`);
      }
      left = createRuntimeAst(expression, args[0]);
      right = createRuntimeAst(expression, args[1]);
      return new Node$4(ExpressionNodeType$1.BINARY, call, left, right);
    } else if (defined(ternaryFunctions[call])) {
      if (argsLength !== 3) {
        throw new RuntimeError(`${call} requires exactly three arguments.`);
      }
      left = createRuntimeAst(expression, args[0]);
      right = createRuntimeAst(expression, args[1]);
      const test = createRuntimeAst(expression, args[2]);
      return new Node$4(ExpressionNodeType$1.TERNARY, call, left, right, test);
    } else if (call === "Boolean") {
      if (argsLength === 0) {
        return new Node$4(ExpressionNodeType$1.LITERAL_BOOLEAN, false);
      }
      val = createRuntimeAst(expression, args[0]);
      return new Node$4(ExpressionNodeType$1.UNARY, call, val);
    } else if (call === "Number") {
      if (argsLength === 0) {
        return new Node$4(ExpressionNodeType$1.LITERAL_NUMBER, 0);
      }
      val = createRuntimeAst(expression, args[0]);
      return new Node$4(ExpressionNodeType$1.UNARY, call, val);
    } else if (call === "String") {
      if (argsLength === 0) {
        return new Node$4(ExpressionNodeType$1.LITERAL_STRING, "");
      }
      val = createRuntimeAst(expression, args[0]);
      return new Node$4(ExpressionNodeType$1.UNARY, call, val);
    } else if (call === "regExp") {
      return parseRegex(expression, ast);
    }

    throw new RuntimeError(`Unexpected function call "${call}".`);
  }

  function parseRegex(expression, ast) {
    const args = ast.arguments;
    // no arguments, return default regex
    if (args.length === 0) {
      return new Node$4(ExpressionNodeType$1.LITERAL_REGEX, new RegExp());
    }

    const pattern = createRuntimeAst(expression, args[0]);
    let exp;

    // optional flag argument supplied
    if (args.length > 1) {
      const flags = createRuntimeAst(expression, args[1]);
      if (isLiteralType(pattern) && isLiteralType(flags)) {
        try {
          exp = new RegExp(
            replaceBackslashes(String(pattern._value)),
            flags._value
          );
        } catch (e) {
          throw new RuntimeError(e);
        }
        return new Node$4(ExpressionNodeType$1.LITERAL_REGEX, exp);
      }
      return new Node$4(ExpressionNodeType$1.REGEX, pattern, flags);
    }

    // only pattern argument supplied
    if (isLiteralType(pattern)) {
      try {
        exp = new RegExp(replaceBackslashes(String(pattern._value)));
      } catch (e) {
        throw new RuntimeError(e);
      }
      return new Node$4(ExpressionNodeType$1.LITERAL_REGEX, exp);
    }
    return new Node$4(ExpressionNodeType$1.REGEX, pattern);
  }

  function parseKeywordsAndVariables(ast) {
    if (isVariable(ast.name)) {
      const name = getPropertyName(ast.name);
      if (name.substr(0, 8) === "tiles3d_") {
        return new Node$4(ExpressionNodeType$1.BUILTIN_VARIABLE, name);
      }
      return new Node$4(ExpressionNodeType$1.VARIABLE, name);
    } else if (ast.name === "NaN") {
      return new Node$4(ExpressionNodeType$1.LITERAL_NUMBER, NaN);
    } else if (ast.name === "Infinity") {
      return new Node$4(ExpressionNodeType$1.LITERAL_NUMBER, Infinity);
    } else if (ast.name === "undefined") {
      return new Node$4(ExpressionNodeType$1.LITERAL_UNDEFINED, undefined);
    }

    throw new RuntimeError(`${ast.name} is not defined.`);
  }

  function parseMathConstant(ast) {
    const name = ast.property.name;
    if (name === "PI") {
      return new Node$4(ExpressionNodeType$1.LITERAL_NUMBER, Math.PI);
    } else if (name === "E") {
      return new Node$4(ExpressionNodeType$1.LITERAL_NUMBER, Math.E);
    }
  }

  function parseNumberConstant(ast) {
    const name = ast.property.name;
    if (name === "POSITIVE_INFINITY") {
      return new Node$4(
        ExpressionNodeType$1.LITERAL_NUMBER,
        Number.POSITIVE_INFINITY
      );
    }
  }

  function parseMemberExpression(expression, ast) {
    if (ast.object.name === "Math") {
      return parseMathConstant(ast);
    } else if (ast.object.name === "Number") {
      return parseNumberConstant(ast);
    }

    let val;
    const obj = createRuntimeAst(expression, ast.object);
    if (ast.computed) {
      val = createRuntimeAst(expression, ast.property);
      return new Node$4(ExpressionNodeType$1.MEMBER, "brackets", obj, val);
    }

    val = new Node$4(ExpressionNodeType$1.LITERAL_STRING, ast.property.name);
    return new Node$4(ExpressionNodeType$1.MEMBER, "dot", obj, val);
  }

  function isLiteralType(node) {
    return node._type >= ExpressionNodeType$1.LITERAL_NULL;
  }

  function isVariable(name) {
    return name.substr(0, 4) === "czm_";
  }

  function getPropertyName(variable) {
    return variable.substr(4);
  }

  function createRuntimeAst(expression, ast) {
    let node;
    let op;
    let left;
    let right;

    if (ast.type === "Literal") {
      node = parseLiteral(ast);
    } else if (ast.type === "CallExpression") {
      node = parseCall(expression, ast);
    } else if (ast.type === "Identifier") {
      node = parseKeywordsAndVariables(ast);
    } else if (ast.type === "UnaryExpression") {
      op = ast.operator;
      const child = createRuntimeAst(expression, ast.argument);
      if (unaryOperators.indexOf(op) > -1) {
        node = new Node$4(ExpressionNodeType$1.UNARY, op, child);
      } else {
        throw new RuntimeError(`Unexpected operator "${op}".`);
      }
    } else if (ast.type === "BinaryExpression") {
      op = ast.operator;
      left = createRuntimeAst(expression, ast.left);
      right = createRuntimeAst(expression, ast.right);
      if (binaryOperators.indexOf(op) > -1) {
        node = new Node$4(ExpressionNodeType$1.BINARY, op, left, right);
      } else {
        throw new RuntimeError(`Unexpected operator "${op}".`);
      }
    } else if (ast.type === "LogicalExpression") {
      op = ast.operator;
      left = createRuntimeAst(expression, ast.left);
      right = createRuntimeAst(expression, ast.right);
      if (binaryOperators.indexOf(op) > -1) {
        node = new Node$4(ExpressionNodeType$1.BINARY, op, left, right);
      }
    } else if (ast.type === "ConditionalExpression") {
      const test = createRuntimeAst(expression, ast.test);
      left = createRuntimeAst(expression, ast.consequent);
      right = createRuntimeAst(expression, ast.alternate);
      node = new Node$4(ExpressionNodeType$1.CONDITIONAL, "?", left, right, test);
    } else if (ast.type === "MemberExpression") {
      node = parseMemberExpression(expression, ast);
    } else if (ast.type === "ArrayExpression") {
      const val = [];
      for (let i = 0; i < ast.elements.length; i++) {
        val[i] = createRuntimeAst(expression, ast.elements[i]);
      }
      node = new Node$4(ExpressionNodeType$1.ARRAY, val);
    } else if (ast.type === "Compound") {
      // empty expression or multiple expressions
      throw new RuntimeError("Provide exactly one expression.");
    } else {
      throw new RuntimeError("Cannot parse expression.");
    }

    return node;
  }

  function setEvaluateFunction(node) {
    if (node._type === ExpressionNodeType$1.CONDITIONAL) {
      node.evaluate = node._evaluateConditional;
    } else if (node._type === ExpressionNodeType$1.FUNCTION_CALL) {
      if (node._value === "test") {
        node.evaluate = node._evaluateRegExpTest;
      } else if (node._value === "exec") {
        node.evaluate = node._evaluateRegExpExec;
      } else if (node._value === "toString") {
        node.evaluate = node._evaluateToString;
      }
    } else if (node._type === ExpressionNodeType$1.UNARY) {
      if (node._value === "!") {
        node.evaluate = node._evaluateNot;
      } else if (node._value === "-") {
        node.evaluate = node._evaluateNegative;
      } else if (node._value === "+") {
        node.evaluate = node._evaluatePositive;
      } else if (node._value === "isNaN") {
        node.evaluate = node._evaluateNaN;
      } else if (node._value === "isFinite") {
        node.evaluate = node._evaluateIsFinite;
      } else if (node._value === "isExactClass") {
        node.evaluate = node._evaluateIsExactClass;
      } else if (node._value === "isClass") {
        node.evaluate = node._evaluateIsClass;
      } else if (node._value === "getExactClassName") {
        node.evaluate = node._evaluateGetExactClassName;
      } else if (node._value === "Boolean") {
        node.evaluate = node._evaluateBooleanConversion;
      } else if (node._value === "Number") {
        node.evaluate = node._evaluateNumberConversion;
      } else if (node._value === "String") {
        node.evaluate = node._evaluateStringConversion;
      } else if (defined(unaryFunctions[node._value])) {
        node.evaluate = getEvaluateUnaryFunction(node._value);
      }
    } else if (node._type === ExpressionNodeType$1.BINARY) {
      if (node._value === "+") {
        node.evaluate = node._evaluatePlus;
      } else if (node._value === "-") {
        node.evaluate = node._evaluateMinus;
      } else if (node._value === "*") {
        node.evaluate = node._evaluateTimes;
      } else if (node._value === "/") {
        node.evaluate = node._evaluateDivide;
      } else if (node._value === "%") {
        node.evaluate = node._evaluateMod;
      } else if (node._value === "===") {
        node.evaluate = node._evaluateEqualsStrict;
      } else if (node._value === "!==") {
        node.evaluate = node._evaluateNotEqualsStrict;
      } else if (node._value === "<") {
        node.evaluate = node._evaluateLessThan;
      } else if (node._value === "<=") {
        node.evaluate = node._evaluateLessThanOrEquals;
      } else if (node._value === ">") {
        node.evaluate = node._evaluateGreaterThan;
      } else if (node._value === ">=") {
        node.evaluate = node._evaluateGreaterThanOrEquals;
      } else if (node._value === "&&") {
        node.evaluate = node._evaluateAnd;
      } else if (node._value === "||") {
        node.evaluate = node._evaluateOr;
      } else if (node._value === "=~") {
        node.evaluate = node._evaluateRegExpMatch;
      } else if (node._value === "!~") {
        node.evaluate = node._evaluateRegExpNotMatch;
      } else if (defined(binaryFunctions[node._value])) {
        node.evaluate = getEvaluateBinaryFunction(node._value);
      }
    } else if (node._type === ExpressionNodeType$1.TERNARY) {
      node.evaluate = getEvaluateTernaryFunction(node._value);
    } else if (node._type === ExpressionNodeType$1.MEMBER) {
      if (node._value === "brackets") {
        node.evaluate = node._evaluateMemberBrackets;
      } else {
        node.evaluate = node._evaluateMemberDot;
      }
    } else if (node._type === ExpressionNodeType$1.ARRAY) {
      node.evaluate = node._evaluateArray;
    } else if (node._type === ExpressionNodeType$1.VARIABLE) {
      node.evaluate = node._evaluateVariable;
    } else if (node._type === ExpressionNodeType$1.VARIABLE_IN_STRING) {
      node.evaluate = node._evaluateVariableString;
    } else if (node._type === ExpressionNodeType$1.LITERAL_COLOR) {
      node.evaluate = node._evaluateLiteralColor;
    } else if (node._type === ExpressionNodeType$1.LITERAL_VECTOR) {
      node.evaluate = node._evaluateLiteralVector;
    } else if (node._type === ExpressionNodeType$1.LITERAL_STRING) {
      node.evaluate = node._evaluateLiteralString;
    } else if (node._type === ExpressionNodeType$1.REGEX) {
      node.evaluate = node._evaluateRegExp;
    } else if (node._type === ExpressionNodeType$1.BUILTIN_VARIABLE) {
      if (node._value === "tiles3d_tileset_time") {
        node.evaluate = evaluateTilesetTime;
      }
    } else {
      node.evaluate = node._evaluateLiteral;
    }
  }

  function evaluateTilesetTime(feature) {
    if (!defined(feature)) {
      return 0.0;
    }
    return feature.content.tileset.timeSinceLoad;
  }

  function getEvaluateUnaryFunction(call) {
    const evaluate = unaryFunctions[call];
    return function (feature) {
      const left = this._left.evaluate(feature);
      return evaluate(call, left);
    };
  }

  function getEvaluateBinaryFunction(call) {
    const evaluate = binaryFunctions[call];
    return function (feature) {
      const left = this._left.evaluate(feature);
      const right = this._right.evaluate(feature);
      return evaluate(call, left, right);
    };
  }

  function getEvaluateTernaryFunction(call) {
    const evaluate = ternaryFunctions[call];
    return function (feature) {
      const left = this._left.evaluate(feature);
      const right = this._right.evaluate(feature);
      const test = this._test.evaluate(feature);
      return evaluate(call, left, right, test);
    };
  }

  function getFeatureProperty(feature, name) {
    // Returns undefined if the feature is not defined or the property name is not defined for that feature
    if (defined(feature)) {
      return feature.getPropertyInherited(name);
    }
  }

  Node$4.prototype._evaluateLiteral = function () {
    return this._value;
  };

  Node$4.prototype._evaluateLiteralColor = function (feature) {
    const color = scratchColor$m;
    const args = this._left;
    if (this._value === "color") {
      if (!defined(args)) {
        Color.fromBytes(255, 255, 255, 255, color);
      } else if (args.length > 1) {
        Color.fromCssColorString(args[0].evaluate(feature), color);
        color.alpha = args[1].evaluate(feature);
      } else {
        Color.fromCssColorString(args[0].evaluate(feature), color);
      }
    } else if (this._value === "rgb") {
      Color.fromBytes(
        args[0].evaluate(feature),
        args[1].evaluate(feature),
        args[2].evaluate(feature),
        255,
        color
      );
    } else if (this._value === "rgba") {
      // convert between css alpha (0 to 1) and cesium alpha (0 to 255)
      const a = args[3].evaluate(feature) * 255;
      Color.fromBytes(
        args[0].evaluate(feature),
        args[1].evaluate(feature),
        args[2].evaluate(feature),
        a,
        color
      );
    } else if (this._value === "hsl") {
      Color.fromHsl(
        args[0].evaluate(feature),
        args[1].evaluate(feature),
        args[2].evaluate(feature),
        1.0,
        color
      );
    } else if (this._value === "hsla") {
      Color.fromHsl(
        args[0].evaluate(feature),
        args[1].evaluate(feature),
        args[2].evaluate(feature),
        args[3].evaluate(feature),
        color
      );
    }
    return Cartesian4.fromColor(color, scratchStorage.getCartesian4());
  };

  Node$4.prototype._evaluateLiteralVector = function (feature) {
    // Gather the components that make up the vector, which includes components from interior vectors.
    // For example vec3(1, 2, 3) or vec3(vec2(1, 2), 3) are both valid.
    //
    // If the number of components does not equal the vector's size, then a RuntimeError is thrown - with two exceptions:
    // 1. A vector may be constructed from a larger vector and drop the extra components.
    // 2. A vector may be constructed from a single component - vec3(1) will become vec3(1, 1, 1).
    //
    // Examples of invalid constructors include:
    // vec4(1, 2)        // not enough components
    // vec3(vec2(1, 2))  // not enough components
    // vec3(1, 2, 3, 4)  // too many components
    // vec2(vec4(1), 1)  // too many components

    const components = scratchStorage.getArray();
    const call = this._value;
    const args = this._left;
    const argsLength = args.length;
    for (let i = 0; i < argsLength; ++i) {
      const value = args[i].evaluate(feature);
      if (typeof value === "number") {
        components.push(value);
      } else if (value instanceof Cartesian2) {
        components.push(value.x, value.y);
      } else if (value instanceof Cartesian3) {
        components.push(value.x, value.y, value.z);
      } else if (value instanceof Cartesian4) {
        components.push(value.x, value.y, value.z, value.w);
      } else {
        throw new RuntimeError(
          `${call} argument must be a vector or number. Argument is ${value}.`
        );
      }
    }

    const componentsLength = components.length;
    const vectorLength = parseInt(call.charAt(3));

    if (componentsLength === 0) {
      throw new RuntimeError(`Invalid ${call} constructor. No valid arguments.`);
    } else if (componentsLength < vectorLength && componentsLength > 1) {
      throw new RuntimeError(
        `Invalid ${call} constructor. Not enough arguments.`
      );
    } else if (componentsLength > vectorLength && argsLength > 1) {
      throw new RuntimeError(`Invalid ${call} constructor. Too many arguments.`);
    }

    if (componentsLength === 1) {
      // Add the same component 3 more times
      const component = components[0];
      components.push(component, component, component);
    }

    if (call === "vec2") {
      return Cartesian2.fromArray(components, 0, scratchStorage.getCartesian2());
    } else if (call === "vec3") {
      return Cartesian3.fromArray(components, 0, scratchStorage.getCartesian3());
    } else if (call === "vec4") {
      return Cartesian4.fromArray(components, 0, scratchStorage.getCartesian4());
    }
  };

  Node$4.prototype._evaluateLiteralString = function () {
    return this._value;
  };

  Node$4.prototype._evaluateVariableString = function (feature) {
    let result = this._value;
    let match = variableRegex.exec(result);
    while (match !== null) {
      const placeholder = match[0];
      const variableName = match[1];
      let property = getFeatureProperty(feature, variableName);
      if (!defined(property)) {
        property = "";
      }
      result = result.replace(placeholder, property);
      match = variableRegex.exec(result);
    }
    return result;
  };

  Node$4.prototype._evaluateVariable = function (feature) {
    // evaluates to undefined if the property name is not defined for that feature
    return getFeatureProperty(feature, this._value);
  };

  function checkFeature(ast) {
    return ast._value === "feature";
  }

  // PERFORMANCE_IDEA: Determine if parent property needs to be computed before runtime
  Node$4.prototype._evaluateMemberDot = function (feature) {
    if (checkFeature(this._left)) {
      return getFeatureProperty(feature, this._right.evaluate(feature));
    }
    const property = this._left.evaluate(feature);
    if (!defined(property)) {
      return undefined;
    }

    const member = this._right.evaluate(feature);
    if (
      property instanceof Cartesian2 ||
      property instanceof Cartesian3 ||
      property instanceof Cartesian4
    ) {
      // Vector components may be accessed with .r, .g, .b, .a and implicitly with .x, .y, .z, .w
      if (member === "r") {
        return property.x;
      } else if (member === "g") {
        return property.y;
      } else if (member === "b") {
        return property.z;
      } else if (member === "a") {
        return property.w;
      }
    }
    return property[member];
  };

  Node$4.prototype._evaluateMemberBrackets = function (feature) {
    if (checkFeature(this._left)) {
      return getFeatureProperty(feature, this._right.evaluate(feature));
    }
    const property = this._left.evaluate(feature);
    if (!defined(property)) {
      return undefined;
    }

    const member = this._right.evaluate(feature);
    if (
      property instanceof Cartesian2 ||
      property instanceof Cartesian3 ||
      property instanceof Cartesian4
    ) {
      // Vector components may be accessed with [0][1][2][3], ['r']['g']['b']['a'] and implicitly with ['x']['y']['z']['w']
      // For Cartesian2 and Cartesian3 out-of-range components will just return undefined
      if (member === 0 || member === "r") {
        return property.x;
      } else if (member === 1 || member === "g") {
        return property.y;
      } else if (member === 2 || member === "b") {
        return property.z;
      } else if (member === 3 || member === "a") {
        return property.w;
      }
    }
    return property[member];
  };

  Node$4.prototype._evaluateArray = function (feature) {
    const array = [];
    for (let i = 0; i < this._value.length; i++) {
      array[i] = this._value[i].evaluate(feature);
    }
    return array;
  };

  // PERFORMANCE_IDEA: Have "fast path" functions that deal only with specific types
  // that we can assign if we know the types before runtime

  Node$4.prototype._evaluateNot = function (feature) {
    const left = this._left.evaluate(feature);
    if (typeof left !== "boolean") {
      throw new RuntimeError(
        `Operator "!" requires a boolean argument. Argument is ${left}.`
      );
    }
    return !left;
  };

  Node$4.prototype._evaluateNegative = function (feature) {
    const left = this._left.evaluate(feature);
    if (left instanceof Cartesian2) {
      return Cartesian2.negate(left, scratchStorage.getCartesian2());
    } else if (left instanceof Cartesian3) {
      return Cartesian3.negate(left, scratchStorage.getCartesian3());
    } else if (left instanceof Cartesian4) {
      return Cartesian4.negate(left, scratchStorage.getCartesian4());
    } else if (typeof left === "number") {
      return -left;
    }

    throw new RuntimeError(
      `Operator "-" requires a vector or number argument. Argument is ${left}.`
    );
  };

  Node$4.prototype._evaluatePositive = function (feature) {
    const left = this._left.evaluate(feature);

    if (
      !(
        left instanceof Cartesian2 ||
        left instanceof Cartesian3 ||
        left instanceof Cartesian4 ||
        typeof left === "number"
      )
    ) {
      throw new RuntimeError(
        `Operator "+" requires a vector or number argument. Argument is ${left}.`
      );
    }

    return left;
  };

  Node$4.prototype._evaluateLessThan = function (feature) {
    const left = this._left.evaluate(feature);
    const right = this._right.evaluate(feature);

    if (typeof left !== "number" || typeof right !== "number") {
      throw new RuntimeError(
        `Operator "<" requires number arguments. Arguments are ${left} and ${right}.`
      );
    }

    return left < right;
  };

  Node$4.prototype._evaluateLessThanOrEquals = function (feature) {
    const left = this._left.evaluate(feature);
    const right = this._right.evaluate(feature);

    if (typeof left !== "number" || typeof right !== "number") {
      throw new RuntimeError(
        `Operator "<=" requires number arguments. Arguments are ${left} and ${right}.`
      );
    }

    return left <= right;
  };

  Node$4.prototype._evaluateGreaterThan = function (feature) {
    const left = this._left.evaluate(feature);
    const right = this._right.evaluate(feature);

    if (typeof left !== "number" || typeof right !== "number") {
      throw new RuntimeError(
        `Operator ">" requires number arguments. Arguments are ${left} and ${right}.`
      );
    }

    return left > right;
  };

  Node$4.prototype._evaluateGreaterThanOrEquals = function (feature) {
    const left = this._left.evaluate(feature);
    const right = this._right.evaluate(feature);

    if (typeof left !== "number" || typeof right !== "number") {
      throw new RuntimeError(
        `Operator ">=" requires number arguments. Arguments are ${left} and ${right}.`
      );
    }

    return left >= right;
  };

  Node$4.prototype._evaluateOr = function (feature) {
    const left = this._left.evaluate(feature);
    if (typeof left !== "boolean") {
      throw new RuntimeError(
        `Operator "||" requires boolean arguments. First argument is ${left}.`
      );
    }

    // short circuit the expression
    if (left) {
      return true;
    }

    const right = this._right.evaluate(feature);
    if (typeof right !== "boolean") {
      throw new RuntimeError(
        `Operator "||" requires boolean arguments. Second argument is ${right}.`
      );
    }

    return left || right;
  };

  Node$4.prototype._evaluateAnd = function (feature) {
    const left = this._left.evaluate(feature);
    if (typeof left !== "boolean") {
      throw new RuntimeError(
        `Operator "&&" requires boolean arguments. First argument is ${left}.`
      );
    }

    // short circuit the expression
    if (!left) {
      return false;
    }

    const right = this._right.evaluate(feature);
    if (typeof right !== "boolean") {
      throw new RuntimeError(
        `Operator "&&" requires boolean arguments. Second argument is ${right}.`
      );
    }

    return left && right;
  };

  Node$4.prototype._evaluatePlus = function (feature) {
    const left = this._left.evaluate(feature);
    const right = this._right.evaluate(feature);
    if (right instanceof Cartesian2 && left instanceof Cartesian2) {
      return Cartesian2.add(left, right, scratchStorage.getCartesian2());
    } else if (right instanceof Cartesian3 && left instanceof Cartesian3) {
      return Cartesian3.add(left, right, scratchStorage.getCartesian3());
    } else if (right instanceof Cartesian4 && left instanceof Cartesian4) {
      return Cartesian4.add(left, right, scratchStorage.getCartesian4());
    } else if (typeof left === "string" || typeof right === "string") {
      // If only one argument is a string the other argument calls its toString function.
      return left + right;
    } else if (typeof left === "number" && typeof right === "number") {
      return left + right;
    }

    throw new RuntimeError(
      `Operator "+" requires vector or number arguments of matching types, or at least one string argument. Arguments are ${left} and ${right}.`
    );
  };

  Node$4.prototype._evaluateMinus = function (feature) {
    const left = this._left.evaluate(feature);
    const right = this._right.evaluate(feature);
    if (right instanceof Cartesian2 && left instanceof Cartesian2) {
      return Cartesian2.subtract(left, right, scratchStorage.getCartesian2());
    } else if (right instanceof Cartesian3 && left instanceof Cartesian3) {
      return Cartesian3.subtract(left, right, scratchStorage.getCartesian3());
    } else if (right instanceof Cartesian4 && left instanceof Cartesian4) {
      return Cartesian4.subtract(left, right, scratchStorage.getCartesian4());
    } else if (typeof left === "number" && typeof right === "number") {
      return left - right;
    }

    throw new RuntimeError(
      `Operator "-" requires vector or number arguments of matching types. Arguments are ${left} and ${right}.`
    );
  };

  Node$4.prototype._evaluateTimes = function (feature) {
    const left = this._left.evaluate(feature);
    const right = this._right.evaluate(feature);
    if (right instanceof Cartesian2 && left instanceof Cartesian2) {
      return Cartesian2.multiplyComponents(
        left,
        right,
        scratchStorage.getCartesian2()
      );
    } else if (right instanceof Cartesian2 && typeof left === "number") {
      return Cartesian2.multiplyByScalar(
        right,
        left,
        scratchStorage.getCartesian2()
      );
    } else if (left instanceof Cartesian2 && typeof right === "number") {
      return Cartesian2.multiplyByScalar(
        left,
        right,
        scratchStorage.getCartesian2()
      );
    } else if (right instanceof Cartesian3 && left instanceof Cartesian3) {
      return Cartesian3.multiplyComponents(
        left,
        right,
        scratchStorage.getCartesian3()
      );
    } else if (right instanceof Cartesian3 && typeof left === "number") {
      return Cartesian3.multiplyByScalar(
        right,
        left,
        scratchStorage.getCartesian3()
      );
    } else if (left instanceof Cartesian3 && typeof right === "number") {
      return Cartesian3.multiplyByScalar(
        left,
        right,
        scratchStorage.getCartesian3()
      );
    } else if (right instanceof Cartesian4 && left instanceof Cartesian4) {
      return Cartesian4.multiplyComponents(
        left,
        right,
        scratchStorage.getCartesian4()
      );
    } else if (right instanceof Cartesian4 && typeof left === "number") {
      return Cartesian4.multiplyByScalar(
        right,
        left,
        scratchStorage.getCartesian4()
      );
    } else if (left instanceof Cartesian4 && typeof right === "number") {
      return Cartesian4.multiplyByScalar(
        left,
        right,
        scratchStorage.getCartesian4()
      );
    } else if (typeof left === "number" && typeof right === "number") {
      return left * right;
    }

    throw new RuntimeError(
      `Operator "*" requires vector or number arguments. If both arguments are vectors they must be matching types. Arguments are ${left} and ${right}.`
    );
  };

  Node$4.prototype._evaluateDivide = function (feature) {
    const left = this._left.evaluate(feature);
    const right = this._right.evaluate(feature);
    if (right instanceof Cartesian2 && left instanceof Cartesian2) {
      return Cartesian2.divideComponents(
        left,
        right,
        scratchStorage.getCartesian2()
      );
    } else if (left instanceof Cartesian2 && typeof right === "number") {
      return Cartesian2.divideByScalar(
        left,
        right,
        scratchStorage.getCartesian2()
      );
    } else if (right instanceof Cartesian3 && left instanceof Cartesian3) {
      return Cartesian3.divideComponents(
        left,
        right,
        scratchStorage.getCartesian3()
      );
    } else if (left instanceof Cartesian3 && typeof right === "number") {
      return Cartesian3.divideByScalar(
        left,
        right,
        scratchStorage.getCartesian3()
      );
    } else if (right instanceof Cartesian4 && left instanceof Cartesian4) {
      return Cartesian4.divideComponents(
        left,
        right,
        scratchStorage.getCartesian4()
      );
    } else if (left instanceof Cartesian4 && typeof right === "number") {
      return Cartesian4.divideByScalar(
        left,
        right,
        scratchStorage.getCartesian4()
      );
    } else if (typeof left === "number" && typeof right === "number") {
      return left / right;
    }

    throw new RuntimeError(
      `Operator "/" requires vector or number arguments of matching types, or a number as the second argument. Arguments are ${left} and ${right}.`
    );
  };

  Node$4.prototype._evaluateMod = function (feature) {
    const left = this._left.evaluate(feature);
    const right = this._right.evaluate(feature);
    if (right instanceof Cartesian2 && left instanceof Cartesian2) {
      return Cartesian2.fromElements(
        left.x % right.x,
        left.y % right.y,
        scratchStorage.getCartesian2()
      );
    } else if (right instanceof Cartesian3 && left instanceof Cartesian3) {
      return Cartesian3.fromElements(
        left.x % right.x,
        left.y % right.y,
        left.z % right.z,
        scratchStorage.getCartesian3()
      );
    } else if (right instanceof Cartesian4 && left instanceof Cartesian4) {
      return Cartesian4.fromElements(
        left.x % right.x,
        left.y % right.y,
        left.z % right.z,
        left.w % right.w,
        scratchStorage.getCartesian4()
      );
    } else if (typeof left === "number" && typeof right === "number") {
      return left % right;
    }

    throw new RuntimeError(
      `Operator "%" requires vector or number arguments of matching types. Arguments are ${left} and ${right}.`
    );
  };

  Node$4.prototype._evaluateEqualsStrict = function (feature) {
    const left = this._left.evaluate(feature);
    const right = this._right.evaluate(feature);
    if (
      (right instanceof Cartesian2 && left instanceof Cartesian2) ||
      (right instanceof Cartesian3 && left instanceof Cartesian3) ||
      (right instanceof Cartesian4 && left instanceof Cartesian4)
    ) {
      return left.equals(right);
    }
    return left === right;
  };

  Node$4.prototype._evaluateNotEqualsStrict = function (feature) {
    const left = this._left.evaluate(feature);
    const right = this._right.evaluate(feature);
    if (
      (right instanceof Cartesian2 && left instanceof Cartesian2) ||
      (right instanceof Cartesian3 && left instanceof Cartesian3) ||
      (right instanceof Cartesian4 && left instanceof Cartesian4)
    ) {
      return !left.equals(right);
    }
    return left !== right;
  };

  Node$4.prototype._evaluateConditional = function (feature) {
    const test = this._test.evaluate(feature);

    if (typeof test !== "boolean") {
      throw new RuntimeError(
        `Conditional argument of conditional expression must be a boolean. Argument is ${test}.`
      );
    }

    if (test) {
      return this._left.evaluate(feature);
    }
    return this._right.evaluate(feature);
  };

  Node$4.prototype._evaluateNaN = function (feature) {
    return isNaN(this._left.evaluate(feature));
  };

  Node$4.prototype._evaluateIsFinite = function (feature) {
    return isFinite(this._left.evaluate(feature));
  };

  Node$4.prototype._evaluateIsExactClass = function (feature) {
    if (defined(feature)) {
      return feature.isExactClass(this._left.evaluate(feature));
    }
    return false;
  };

  Node$4.prototype._evaluateIsClass = function (feature) {
    if (defined(feature)) {
      return feature.isClass(this._left.evaluate(feature));
    }
    return false;
  };

  Node$4.prototype._evaluateGetExactClassName = function (feature) {
    if (defined(feature)) {
      return feature.getExactClassName();
    }
  };

  Node$4.prototype._evaluateBooleanConversion = function (feature) {
    return Boolean(this._left.evaluate(feature));
  };

  Node$4.prototype._evaluateNumberConversion = function (feature) {
    return Number(this._left.evaluate(feature));
  };

  Node$4.prototype._evaluateStringConversion = function (feature) {
    return String(this._left.evaluate(feature));
  };

  Node$4.prototype._evaluateRegExp = function (feature) {
    const pattern = this._value.evaluate(feature);
    let flags = "";

    if (defined(this._left)) {
      flags = this._left.evaluate(feature);
    }

    let exp;
    try {
      exp = new RegExp(pattern, flags);
    } catch (e) {
      throw new RuntimeError(e);
    }
    return exp;
  };

  Node$4.prototype._evaluateRegExpTest = function (feature) {
    const left = this._left.evaluate(feature);
    const right = this._right.evaluate(feature);

    if (!(left instanceof RegExp && typeof right === "string")) {
      throw new RuntimeError(
        `RegExp.test requires the first argument to be a RegExp and the second argument to be a string. Arguments are ${left} and ${right}.`
      );
    }

    return left.test(right);
  };

  Node$4.prototype._evaluateRegExpMatch = function (feature) {
    const left = this._left.evaluate(feature);
    const right = this._right.evaluate(feature);

    if (left instanceof RegExp && typeof right === "string") {
      return left.test(right);
    } else if (right instanceof RegExp && typeof left === "string") {
      return right.test(left);
    }

    throw new RuntimeError(
      `Operator "=~" requires one RegExp argument and one string argument. Arguments are ${left} and ${right}.`
    );
  };

  Node$4.prototype._evaluateRegExpNotMatch = function (feature) {
    const left = this._left.evaluate(feature);
    const right = this._right.evaluate(feature);

    if (left instanceof RegExp && typeof right === "string") {
      return !left.test(right);
    } else if (right instanceof RegExp && typeof left === "string") {
      return !right.test(left);
    }

    throw new RuntimeError(
      `Operator "!~" requires one RegExp argument and one string argument. Arguments are ${left} and ${right}.`
    );
  };

  Node$4.prototype._evaluateRegExpExec = function (feature) {
    const left = this._left.evaluate(feature);
    const right = this._right.evaluate(feature);

    if (!(left instanceof RegExp && typeof right === "string")) {
      throw new RuntimeError(
        `RegExp.exec requires the first argument to be a RegExp and the second argument to be a string. Arguments are ${left} and ${right}.`
      );
    }

    const exec = left.exec(right);
    if (!defined(exec)) {
      return null;
    }
    return exec[1];
  };

  Node$4.prototype._evaluateToString = function (feature) {
    const left = this._left.evaluate(feature);
    if (
      left instanceof RegExp ||
      left instanceof Cartesian2 ||
      left instanceof Cartesian3 ||
      left instanceof Cartesian4
    ) {
      return String(left);
    }

    throw new RuntimeError(`Unexpected function call "${this._value}".`);
  };

  function convertHSLToRGB(ast) {
    // Check if the color contains any nested expressions to see if the color can be converted here.
    // E.g. "hsl(0.9, 0.6, 0.7)" is able to convert directly to rgb, "hsl(0.9, 0.6, ${Height})" is not.
    const channels = ast._left;
    const length = channels.length;
    for (let i = 0; i < length; ++i) {
      if (channels[i]._type !== ExpressionNodeType$1.LITERAL_NUMBER) {
        return undefined;
      }
    }
    const h = channels[0]._value;
    const s = channels[1]._value;
    const l = channels[2]._value;
    const a = length === 4 ? channels[3]._value : 1.0;
    return Color.fromHsl(h, s, l, a, scratchColor$m);
  }

  function convertRGBToColor(ast) {
    // Check if the color contains any nested expressions to see if the color can be converted here.
    // E.g. "rgb(255, 255, 255)" is able to convert directly to Color, "rgb(255, 255, ${Height})" is not.
    const channels = ast._left;
    const length = channels.length;
    for (let i = 0; i < length; ++i) {
      if (channels[i]._type !== ExpressionNodeType$1.LITERAL_NUMBER) {
        return undefined;
      }
    }
    const color = scratchColor$m;
    color.red = channels[0]._value / 255.0;
    color.green = channels[1]._value / 255.0;
    color.blue = channels[2]._value / 255.0;
    color.alpha = length === 4 ? channels[3]._value : 1.0;
    return color;
  }

  function numberToString(number) {
    if (number % 1 === 0) {
      // Add a .0 to whole numbers
      return number.toFixed(1);
    }

    return number.toString();
  }

  function colorToVec3(color) {
    const r = numberToString(color.red);
    const g = numberToString(color.green);
    const b = numberToString(color.blue);
    return `vec3(${r}, ${g}, ${b})`;
  }

  function colorToVec4(color) {
    const r = numberToString(color.red);
    const g = numberToString(color.green);
    const b = numberToString(color.blue);
    const a = numberToString(color.alpha);
    return `vec4(${r}, ${g}, ${b}, ${a})`;
  }

  function getExpressionArray(
    array,
    variableSubstitutionMap,
    shaderState,
    parent
  ) {
    const length = array.length;
    const expressions = new Array(length);
    for (let i = 0; i < length; ++i) {
      expressions[i] = array[i].getShaderExpression(
        variableSubstitutionMap,
        shaderState,
        parent
      );
    }
    return expressions;
  }

  function getVariableName(variableName, variableSubstitutionMap) {
    if (!defined(variableSubstitutionMap[variableName])) {
      return Expression.NULL_SENTINEL;
    }

    return variableSubstitutionMap[variableName];
  }

  /**
   * @private
   */
  Expression.NULL_SENTINEL = "czm_infinity"; // null just needs to be some sentinel value that will cause "[expression] === null" to be false in nearly all cases. GLSL doesn't have a NaN constant so use czm_infinity.

  Node$4.prototype.getShaderExpression = function (
    variableSubstitutionMap,
    shaderState,
    parent
  ) {
    let color;
    let left;
    let right;
    let test;

    const type = this._type;
    let value = this._value;

    if (defined(this._left)) {
      if (Array.isArray(this._left)) {
        // Left can be an array if the type is LITERAL_COLOR or LITERAL_VECTOR
        left = getExpressionArray(
          this._left,
          variableSubstitutionMap,
          shaderState,
          this
        );
      } else {
        left = this._left.getShaderExpression(
          variableSubstitutionMap,
          shaderState,
          this
        );
      }
    }

    if (defined(this._right)) {
      right = this._right.getShaderExpression(
        variableSubstitutionMap,
        shaderState,
        this
      );
    }

    if (defined(this._test)) {
      test = this._test.getShaderExpression(
        variableSubstitutionMap,
        shaderState,
        this
      );
    }

    if (Array.isArray(this._value)) {
      // For ARRAY type
      value = getExpressionArray(
        this._value,
        variableSubstitutionMap,
        shaderState,
        this
      );
    }

    let args;
    let length;
    let vectorExpression;
    switch (type) {
      case ExpressionNodeType$1.VARIABLE:
        if (checkFeature(this)) {
          return undefined;
        }
        return getVariableName(value, variableSubstitutionMap);
      case ExpressionNodeType$1.UNARY:
        // Supported types: +, -, !, Boolean, Number
        if (value === "Boolean") {
          return `bool(${left})`;
        } else if (value === "Number") {
          return `float(${left})`;
        } else if (value === "round") {
          return `floor(${left} + 0.5)`;
        } else if (defined(unaryFunctions[value])) {
          return `${value}(${left})`;
        } else if (value === "isNaN") {
          // In GLSL 2.0 use isnan instead
          return `(${left} != ${left})`;
        } else if (value === "isFinite") {
          // In GLSL 2.0 use isinf instead. GLSL doesn't have an infinity constant so use czm_infinity which is an arbitrarily big enough number.
          return `(abs(${left}) < czm_infinity)`;
        } else if (
          value === "String" ||
          value === "isExactClass" ||
          value === "isClass" ||
          value === "getExactClassName"
        ) {
          throw new RuntimeError(
            `Error generating style shader: "${value}" is not supported.`
          );
        }
        return value + left;
      case ExpressionNodeType$1.BINARY:
        // Supported types: ||, &&, ===, !==, <, >, <=, >=, +, -, *, /, %
        if (value === "%") {
          return `mod(${left}, ${right})`;
        } else if (value === "===") {
          return `(${left} == ${right})`;
        } else if (value === "!==") {
          return `(${left} != ${right})`;
        } else if (value === "atan2") {
          return `atan(${left}, ${right})`;
        } else if (defined(binaryFunctions[value])) {
          return `${value}(${left}, ${right})`;
        }
        return `(${left} ${value} ${right})`;
      case ExpressionNodeType$1.TERNARY:
        if (defined(ternaryFunctions[value])) {
          return `${value}(${left}, ${right}, ${test})`;
        }
        break;
      case ExpressionNodeType$1.CONDITIONAL:
        return `(${test} ? ${left} : ${right})`;
      case ExpressionNodeType$1.MEMBER:
        if (checkFeature(this._left)) {
          return getVariableName(right, variableSubstitutionMap);
        }
        // This is intended for accessing the components of vector properties. String members aren't supported.
        // Check for 0.0 rather than 0 because all numbers are previously converted to decimals.
        if (right === "r" || right === "x" || right === "0.0") {
          return `${left}[0]`;
        } else if (right === "g" || right === "y" || right === "1.0") {
          return `${left}[1]`;
        } else if (right === "b" || right === "z" || right === "2.0") {
          return `${left}[2]`;
        } else if (right === "a" || right === "w" || right === "3.0") {
          return `${left}[3]`;
        }
        return `${left}[int(${right})]`;
      case ExpressionNodeType$1.FUNCTION_CALL:
        throw new RuntimeError(
          `Error generating style shader: "${value}" is not supported.`
        );
      case ExpressionNodeType$1.ARRAY:
        if (value.length === 4) {
          return `vec4(${value[0]}, ${value[1]}, ${value[2]}, ${value[3]})`;
        } else if (value.length === 3) {
          return `vec3(${value[0]}, ${value[1]}, ${value[2]})`;
        } else if (value.length === 2) {
          return `vec2(${value[0]}, ${value[1]})`;
        }
        throw new RuntimeError(
          "Error generating style shader: Invalid array length. Array length should be 2, 3, or 4."
        );
      case ExpressionNodeType$1.REGEX:
        throw new RuntimeError(
          "Error generating style shader: Regular expressions are not supported."
        );
      case ExpressionNodeType$1.VARIABLE_IN_STRING:
        throw new RuntimeError(
          "Error generating style shader: Converting a variable to a string is not supported."
        );
      case ExpressionNodeType$1.LITERAL_NULL:
        return Expression.NULL_SENTINEL;
      case ExpressionNodeType$1.LITERAL_BOOLEAN:
        return value ? "true" : "false";
      case ExpressionNodeType$1.LITERAL_NUMBER:
        return numberToString(value);
      case ExpressionNodeType$1.LITERAL_STRING:
        if (defined(parent) && parent._type === ExpressionNodeType$1.MEMBER) {
          if (
            value === "r" ||
            value === "g" ||
            value === "b" ||
            value === "a" ||
            value === "x" ||
            value === "y" ||
            value === "z" ||
            value === "w" ||
            checkFeature(parent._left)
          ) {
            return value;
          }
        }
        // Check for css color strings
        color = Color.fromCssColorString(value, scratchColor$m);
        if (defined(color)) {
          return colorToVec3(color);
        }
        throw new RuntimeError(
          "Error generating style shader: String literals are not supported."
        );
      case ExpressionNodeType$1.LITERAL_COLOR:
        args = left;
        if (value === "color") {
          if (!defined(args)) {
            return "vec4(1.0)";
          } else if (args.length > 1) {
            const rgb = args[0];
            const alpha = args[1];
            if (alpha !== "1.0") {
              shaderState.translucent = true;
            }
            return `vec4(${rgb}, ${alpha})`;
          }
          return `vec4(${args[0]}, 1.0)`;
        } else if (value === "rgb") {
          color = convertRGBToColor(this);
          if (defined(color)) {
            return colorToVec4(color);
          }
          return `vec4(${args[0]} / 255.0, ${args[1]} / 255.0, ${args[2]} / 255.0, 1.0)`;
        } else if (value === "rgba") {
          if (args[3] !== "1.0") {
            shaderState.translucent = true;
          }
          color = convertRGBToColor(this);
          if (defined(color)) {
            return colorToVec4(color);
          }
          return `vec4(${args[0]} / 255.0, ${args[1]} / 255.0, ${args[2]} / 255.0, ${args[3]})`;
        } else if (value === "hsl") {
          color = convertHSLToRGB(this);
          if (defined(color)) {
            return colorToVec4(color);
          }
          return `vec4(czm_HSLToRGB(vec3(${args[0]}, ${args[1]}, ${args[2]})), 1.0)`;
        } else if (value === "hsla") {
          color = convertHSLToRGB(this);
          if (defined(color)) {
            if (color.alpha !== 1.0) {
              shaderState.translucent = true;
            }
            return colorToVec4(color);
          }
          if (args[3] !== "1.0") {
            shaderState.translucent = true;
          }
          return `vec4(czm_HSLToRGB(vec3(${args[0]}, ${args[1]}, ${args[2]})), ${args[3]})`;
        }
        break;
      case ExpressionNodeType$1.LITERAL_VECTOR:
        //>>includeStart('debug', pragmas.debug);
        if (!defined(left)) {
          throw new DeveloperError(
            "left should always be defined for type ExpressionNodeType.LITERAL_VECTOR"
          );
        }
        //>>includeEnd('debug');
        length = left.length;
        vectorExpression = `${value}(`;
        for (let i = 0; i < length; ++i) {
          vectorExpression += left[i];
          if (i < length - 1) {
            vectorExpression += ", ";
          }
        }
        vectorExpression += ")";
        return vectorExpression;
      case ExpressionNodeType$1.LITERAL_REGEX:
        throw new RuntimeError(
          "Error generating style shader: Regular expressions are not supported."
        );
      case ExpressionNodeType$1.LITERAL_UNDEFINED:
        return Expression.NULL_SENTINEL;
      case ExpressionNodeType$1.BUILTIN_VARIABLE:
        if (value === "tiles3d_tileset_time") {
          return "u_time";
        }
    }
  };

  Node$4.prototype.getVariables = function (variables, parent) {
    let array;
    let length;
    let i;

    const type = this._type;
    const value = this._value;

    if (defined(this._left)) {
      if (Array.isArray(this._left)) {
        // Left can be an array if the type is LITERAL_COLOR or LITERAL_VECTOR
        array = this._left;
        length = array.length;
        for (i = 0; i < length; ++i) {
          array[i].getVariables(variables, this);
        }
      } else {
        this._left.getVariables(variables, this);
      }
    }

    if (defined(this._right)) {
      this._right.getVariables(variables, this);
    }

    if (defined(this._test)) {
      this._test.getVariables(variables, this);
    }

    if (Array.isArray(this._value)) {
      // For ARRAY type
      array = this._value;
      length = array.length;
      for (i = 0; i < length; ++i) {
        array[i].getVariables(variables, this);
      }
    }

    let match;
    switch (type) {
      case ExpressionNodeType$1.VARIABLE:
        if (!checkFeature(this)) {
          variables.push(value);
        }
        break;
      case ExpressionNodeType$1.VARIABLE_IN_STRING:
        match = variableRegex.exec(value);
        while (match !== null) {
          variables.push(match[1]);
          match = variableRegex.exec(value);
        }
        break;
      case ExpressionNodeType$1.LITERAL_STRING:
        if (
          defined(parent) &&
          parent._type === ExpressionNodeType$1.MEMBER &&
          checkFeature(parent._left)
        ) {
          variables.push(value);
        }
        break;
    }
  };

  /**
   * Creates a batch of classification meshes.
   *
   * @alias Vector3DTilePrimitive
   * @constructor
   *
   * @param {Object} options An object with following properties:
   * @param {Float32Array} options.positions The positions of the meshes.
   * @param {Uint16Array|Uint32Array} options.indices The indices of the triangulated meshes. The indices must be contiguous so that
   * the indices for mesh n are in [i, i + indexCounts[n]] where i = sum{indexCounts[0], indexCounts[n - 1]}.
   * @param {Uint32Array} options.indexCounts The number of indices for each mesh.
   * @param {Uint32Array} options.indexOffsets The offset into the index buffer for each mesh.
   * @param {Vector3DTileBatch[]} options.batchedIndices The index offset and count for each batch with the same color.
   * @param {Cartesian3} [options.center=Cartesian3.ZERO] The RTC center.
   * @param {Cesium3DTileBatchTable} options.batchTable The batch table for the tile containing the batched meshes.
   * @param {Uint16Array} options.batchIds The batch ids for each mesh.
   * @param {Uint16Array} options.vertexBatchIds The batch id for each vertex.
   * @param {BoundingSphere} options.boundingVolume The bounding volume for the entire batch of meshes.
   * @param {BoundingSphere[]} options.boundingVolumes The bounding volume for each mesh.
   * @param {ClassificationType} [options.classificationType] What this tile will classify.
   *
   * @private
   */
  function Vector3DTilePrimitive(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    this._batchTable = options.batchTable;
    this._batchIds = options.batchIds;

    // These arrays are released after VAO creation.
    this._positions = options.positions;
    this._vertexBatchIds = options.vertexBatchIds;

    // These arrays are kept for re-batching indices based on colors.
    // If WebGL 2 is supported, indices will be released and re-batching uses buffer-to-buffer copies.
    this._indices = options.indices;
    this._indexCounts = options.indexCounts;
    this._indexOffsets = options.indexOffsets;
    this._batchedIndices = options.batchedIndices;

    this._boundingVolume = options.boundingVolume;
    this._boundingVolumes = options.boundingVolumes;

    this._center = defaultValue(options.center, Cartesian3.ZERO);

    this._va = undefined;
    this._sp = undefined;
    this._spStencil = undefined;
    this._spPick = undefined;
    this._uniformMap = undefined;

    // Only used with WebGL 2 to ping-pong ibos after copy.
    this._vaSwap = undefined;

    this._rsStencilDepthPass = undefined;
    this._rsStencilDepthPass3DTiles = undefined;
    this._rsColorPass = undefined;
    this._rsPickPass = undefined;
    this._rsWireframe = undefined;

    this._commands = [];
    this._commandsIgnoreShow = [];
    this._pickCommands = [];

    this._constantColor = Color.clone(Color.WHITE);
    this._highlightColor = this._constantColor;

    this._batchDirty = true;
    this._pickCommandsDirty = true;
    this._framesSinceLastRebatch = 0;

    this._updatingAllCommands = false;

    this._trianglesLength = this._indices.length / 3;
    this._geometryByteLength =
      this._indices.byteLength +
      this._positions.byteLength +
      this._vertexBatchIds.byteLength;

    /**
     * Draw the wireframe of the classification meshes.
     * @type {Boolean}
     * @default false
     */
    this.debugWireframe = false;
    this._debugWireframe = this.debugWireframe;
    this._wireframeDirty = false;

    /**
     * Forces a re-batch instead of waiting after a number of frames have been rendered. For testing only.
     * @type {Boolean}
     * @default false
     */
    this.forceRebatch = false;

    /**
     * What this tile will classify.
     * @type {ClassificationType}
     * @default ClassificationType.BOTH
     */
    this.classificationType = defaultValue(
      options.classificationType,
      ClassificationType$1.BOTH
    );

    // Hidden options
    this._vertexShaderSource = options._vertexShaderSource;
    this._fragmentShaderSource = options._fragmentShaderSource;
    this._attributeLocations = options._attributeLocations;
    this._uniformMap = options._uniformMap;
    this._pickId = options._pickId;
    this._modelMatrix = options._modelMatrix;
    this._boundingSphere = options._boundingSphere;

    this._batchIdLookUp = {};

    const length = this._batchIds.length;
    for (let i = 0; i < length; ++i) {
      const batchId = this._batchIds[i];
      this._batchIdLookUp[batchId] = i;
    }
  }

  Object.defineProperties(Vector3DTilePrimitive.prototype, {
    /**
     * Gets the number of triangles.
     *
     * @memberof Vector3DTilePrimitive.prototype
     *
     * @type {Number}
     * @readonly
     */
    trianglesLength: {
      get: function () {
        return this._trianglesLength;
      },
    },

    /**
     * Gets the geometry memory in bytes.
     *
     * @memberof Vector3DTilePrimitive.prototype
     *
     * @type {Number}
     * @readonly
     */
    geometryByteLength: {
      get: function () {
        return this._geometryByteLength;
      },
    },
  });

  const defaultAttributeLocations = {
    position: 0,
    a_batchId: 1,
  };

  function createVertexArray$4(primitive, context) {
    if (defined(primitive._va)) {
      return;
    }

    const positionBuffer = Buffer$1.createVertexBuffer({
      context: context,
      typedArray: primitive._positions,
      usage: BufferUsage$1.STATIC_DRAW,
    });
    const idBuffer = Buffer$1.createVertexBuffer({
      context: context,
      typedArray: primitive._vertexBatchIds,
      usage: BufferUsage$1.STATIC_DRAW,
    });
    const indexBuffer = Buffer$1.createIndexBuffer({
      context: context,
      typedArray: primitive._indices,
      usage: BufferUsage$1.DYNAMIC_DRAW,
      indexDatatype:
        primitive._indices.BYTES_PER_ELEMENT === 2
          ? IndexDatatype$1.UNSIGNED_SHORT
          : IndexDatatype$1.UNSIGNED_INT,
    });

    const vertexAttributes = [
      {
        index: 0,
        vertexBuffer: positionBuffer,
        componentDatatype: ComponentDatatype$1.fromTypedArray(primitive._positions),
        componentsPerAttribute: 3,
      },
      {
        index: 1,
        vertexBuffer: idBuffer,
        componentDatatype: ComponentDatatype$1.fromTypedArray(
          primitive._vertexBatchIds
        ),
        componentsPerAttribute: 1,
      },
    ];

    primitive._va = new VertexArray({
      context: context,
      attributes: vertexAttributes,
      indexBuffer: indexBuffer,
    });

    if (context.webgl2) {
      primitive._vaSwap = new VertexArray({
        context: context,
        attributes: vertexAttributes,
        indexBuffer: Buffer$1.createIndexBuffer({
          context: context,
          sizeInBytes: indexBuffer.sizeInBytes,
          usage: BufferUsage$1.DYNAMIC_DRAW,
          indexDatatype: indexBuffer.indexDatatype,
        }),
      });
    }

    primitive._batchedPositions = undefined;
    primitive._transferrableBatchIds = undefined;
    primitive._vertexBatchIds = undefined;
    primitive._verticesPromise = undefined;
  }

  function createShaders$3(primitive, context) {
    if (defined(primitive._sp)) {
      return;
    }

    const batchTable = primitive._batchTable;
    const attributeLocations = defaultValue(
      primitive._attributeLocations,
      defaultAttributeLocations
    );

    let pickId = primitive._pickId;
    const vertexShaderSource = primitive._vertexShaderSource;
    let fragmentShaderSource = primitive._fragmentShaderSource;
    if (defined(vertexShaderSource)) {
      primitive._sp = ShaderProgram.fromCache({
        context: context,
        vertexShaderSource: vertexShaderSource,
        fragmentShaderSource: fragmentShaderSource,
        attributeLocations: attributeLocations,
      });
      primitive._spStencil = primitive._sp;

      fragmentShaderSource = ShaderSource.replaceMain(
        fragmentShaderSource,
        "czm_non_pick_main"
      );
      fragmentShaderSource =
        `${fragmentShaderSource}void main() \n` +
        `{ \n` +
        `    czm_non_pick_main(); \n` +
        `    gl_FragColor = ${pickId}; \n` +
        `} \n`;
      primitive._spPick = ShaderProgram.fromCache({
        context: context,
        vertexShaderSource: vertexShaderSource,
        fragmentShaderSource: fragmentShaderSource,
        attributeLocations: attributeLocations,
      });
      return;
    }

    const vsSource = batchTable.getVertexShaderCallback(
      false,
      "a_batchId",
      undefined
    )(VectorTileVS);
    let fsSource = batchTable.getFragmentShaderCallback(
      false,
      undefined,
      true
    )(ShadowVolumeFS);

    pickId = batchTable.getPickId();

    let vs = new ShaderSource({
      sources: [vsSource],
    });
    let fs = new ShaderSource({
      defines: ["VECTOR_TILE"],
      sources: [fsSource],
    });

    primitive._sp = ShaderProgram.fromCache({
      context: context,
      vertexShaderSource: vs,
      fragmentShaderSource: fs,
      attributeLocations: attributeLocations,
    });

    vs = new ShaderSource({
      sources: [VectorTileVS],
    });
    fs = new ShaderSource({
      defines: ["VECTOR_TILE"],
      sources: [ShadowVolumeFS],
    });

    primitive._spStencil = ShaderProgram.fromCache({
      context: context,
      vertexShaderSource: vs,
      fragmentShaderSource: fs,
      attributeLocations: attributeLocations,
    });

    fsSource = ShaderSource.replaceMain(fsSource, "czm_non_pick_main");
    fsSource =
      `${fsSource}\n` +
      `void main() \n` +
      `{ \n` +
      `    czm_non_pick_main(); \n` +
      `    gl_FragColor = ${pickId}; \n` +
      `} \n`;

    const pickVS = new ShaderSource({
      sources: [vsSource],
    });
    const pickFS = new ShaderSource({
      defines: ["VECTOR_TILE"],
      sources: [fsSource],
    });
    primitive._spPick = ShaderProgram.fromCache({
      context: context,
      vertexShaderSource: pickVS,
      fragmentShaderSource: pickFS,
      attributeLocations: attributeLocations,
    });
  }

  function getStencilDepthRenderState(mask3DTiles) {
    const stencilFunction = mask3DTiles
      ? StencilFunction$1.EQUAL
      : StencilFunction$1.ALWAYS;
    return {
      colorMask: {
        red: false,
        green: false,
        blue: false,
        alpha: false,
      },
      stencilTest: {
        enabled: true,
        frontFunction: stencilFunction,
        frontOperation: {
          fail: StencilOperation$1.KEEP,
          zFail: StencilOperation$1.DECREMENT_WRAP,
          zPass: StencilOperation$1.KEEP,
        },
        backFunction: stencilFunction,
        backOperation: {
          fail: StencilOperation$1.KEEP,
          zFail: StencilOperation$1.INCREMENT_WRAP,
          zPass: StencilOperation$1.KEEP,
        },
        reference: StencilConstants$1.CESIUM_3D_TILE_MASK,
        mask: StencilConstants$1.CESIUM_3D_TILE_MASK,
      },
      stencilMask: StencilConstants$1.CLASSIFICATION_MASK,
      depthTest: {
        enabled: true,
        func: DepthFunction$1.LESS_OR_EQUAL,
      },
      depthMask: false,
    };
  }

  const colorRenderState = {
    stencilTest: {
      enabled: true,
      frontFunction: StencilFunction$1.NOT_EQUAL,
      frontOperation: {
        fail: StencilOperation$1.ZERO,
        zFail: StencilOperation$1.ZERO,
        zPass: StencilOperation$1.ZERO,
      },
      backFunction: StencilFunction$1.NOT_EQUAL,
      backOperation: {
        fail: StencilOperation$1.ZERO,
        zFail: StencilOperation$1.ZERO,
        zPass: StencilOperation$1.ZERO,
      },
      reference: 0,
      mask: StencilConstants$1.CLASSIFICATION_MASK,
    },
    stencilMask: StencilConstants$1.CLASSIFICATION_MASK,
    depthTest: {
      enabled: false,
    },
    depthMask: false,
    blending: BlendingState$1.PRE_MULTIPLIED_ALPHA_BLEND,
  };

  const pickRenderState = {
    stencilTest: {
      enabled: true,
      frontFunction: StencilFunction$1.NOT_EQUAL,
      frontOperation: {
        fail: StencilOperation$1.ZERO,
        zFail: StencilOperation$1.ZERO,
        zPass: StencilOperation$1.ZERO,
      },
      backFunction: StencilFunction$1.NOT_EQUAL,
      backOperation: {
        fail: StencilOperation$1.ZERO,
        zFail: StencilOperation$1.ZERO,
        zPass: StencilOperation$1.ZERO,
      },
      reference: 0,
      mask: StencilConstants$1.CLASSIFICATION_MASK,
    },
    stencilMask: StencilConstants$1.CLASSIFICATION_MASK,
    depthTest: {
      enabled: false,
    },
    depthMask: false,
  };

  function createRenderStates$4(primitive) {
    if (defined(primitive._rsStencilDepthPass)) {
      return;
    }

    primitive._rsStencilDepthPass = RenderState.fromCache(
      getStencilDepthRenderState(false)
    );
    primitive._rsStencilDepthPass3DTiles = RenderState.fromCache(
      getStencilDepthRenderState(true)
    );
    primitive._rsColorPass = RenderState.fromCache(colorRenderState);
    primitive._rsPickPass = RenderState.fromCache(pickRenderState);
  }

  const modifiedModelViewScratch$3 = new Matrix4();
  const rtcScratch$3 = new Cartesian3();

  function createUniformMap$6(primitive, context) {
    if (defined(primitive._uniformMap)) {
      return;
    }

    const uniformMap = {
      u_modifiedModelViewProjection: function () {
        const viewMatrix = context.uniformState.view;
        const projectionMatrix = context.uniformState.projection;
        Matrix4.clone(viewMatrix, modifiedModelViewScratch$3);
        Matrix4.multiplyByPoint(
          modifiedModelViewScratch$3,
          primitive._center,
          rtcScratch$3
        );
        Matrix4.setTranslation(
          modifiedModelViewScratch$3,
          rtcScratch$3,
          modifiedModelViewScratch$3
        );
        Matrix4.multiply(
          projectionMatrix,
          modifiedModelViewScratch$3,
          modifiedModelViewScratch$3
        );
        return modifiedModelViewScratch$3;
      },
      u_highlightColor: function () {
        return primitive._highlightColor;
      },
    };

    primitive._uniformMap = primitive._batchTable.getUniformMapCallback()(
      uniformMap
    );
  }

  function copyIndicesCPU(
    indices,
    newIndices,
    currentOffset,
    offsets,
    counts,
    batchIds,
    batchIdLookUp
  ) {
    const sizeInBytes = indices.constructor.BYTES_PER_ELEMENT;

    const batchedIdsLength = batchIds.length;
    for (let j = 0; j < batchedIdsLength; ++j) {
      const batchedId = batchIds[j];
      const index = batchIdLookUp[batchedId];
      const offset = offsets[index];
      const count = counts[index];

      const subarray = new indices.constructor(
        indices.buffer,
        sizeInBytes * offset,
        count
      );
      newIndices.set(subarray, currentOffset);

      offsets[index] = currentOffset;
      currentOffset += count;
    }

    return currentOffset;
  }

  function rebatchCPU(primitive, batchedIndices) {
    const indices = primitive._indices;
    const indexOffsets = primitive._indexOffsets;
    const indexCounts = primitive._indexCounts;
    const batchIdLookUp = primitive._batchIdLookUp;

    const newIndices = new indices.constructor(indices.length);

    let current = batchedIndices.pop();
    const newBatchedIndices = [current];

    let currentOffset = copyIndicesCPU(
      indices,
      newIndices,
      0,
      indexOffsets,
      indexCounts,
      current.batchIds,
      batchIdLookUp
    );

    current.offset = 0;
    current.count = currentOffset;

    while (batchedIndices.length > 0) {
      const next = batchedIndices.pop();
      if (Color.equals(next.color, current.color)) {
        currentOffset = copyIndicesCPU(
          indices,
          newIndices,
          currentOffset,
          indexOffsets,
          indexCounts,
          next.batchIds,
          batchIdLookUp
        );
        current.batchIds = current.batchIds.concat(next.batchIds);
        current.count = currentOffset - current.offset;
      } else {
        const offset = currentOffset;
        currentOffset = copyIndicesCPU(
          indices,
          newIndices,
          currentOffset,
          indexOffsets,
          indexCounts,
          next.batchIds,
          batchIdLookUp
        );

        next.offset = offset;
        next.count = currentOffset - offset;
        newBatchedIndices.push(next);
        current = next;
      }
    }

    primitive._va.indexBuffer.copyFromArrayView(newIndices);

    primitive._indices = newIndices;
    primitive._batchedIndices = newBatchedIndices;
  }

  function copyIndicesGPU(
    readBuffer,
    writeBuffer,
    currentOffset,
    offsets,
    counts,
    batchIds,
    batchIdLookUp
  ) {
    const sizeInBytes = readBuffer.bytesPerIndex;

    const batchedIdsLength = batchIds.length;
    for (let j = 0; j < batchedIdsLength; ++j) {
      const batchedId = batchIds[j];
      const index = batchIdLookUp[batchedId];
      const offset = offsets[index];
      const count = counts[index];

      writeBuffer.copyFromBuffer(
        readBuffer,
        offset * sizeInBytes,
        currentOffset * sizeInBytes,
        count * sizeInBytes
      );

      offsets[index] = currentOffset;
      currentOffset += count;
    }

    return currentOffset;
  }

  function rebatchGPU(primitive, batchedIndices) {
    const indexOffsets = primitive._indexOffsets;
    const indexCounts = primitive._indexCounts;
    const batchIdLookUp = primitive._batchIdLookUp;

    let current = batchedIndices.pop();
    const newBatchedIndices = [current];

    const readBuffer = primitive._va.indexBuffer;
    const writeBuffer = primitive._vaSwap.indexBuffer;

    let currentOffset = copyIndicesGPU(
      readBuffer,
      writeBuffer,
      0,
      indexOffsets,
      indexCounts,
      current.batchIds,
      batchIdLookUp
    );

    current.offset = 0;
    current.count = currentOffset;

    while (batchedIndices.length > 0) {
      const next = batchedIndices.pop();
      if (Color.equals(next.color, current.color)) {
        currentOffset = copyIndicesGPU(
          readBuffer,
          writeBuffer,
          currentOffset,
          indexOffsets,
          indexCounts,
          next.batchIds,
          batchIdLookUp
        );
        current.batchIds = current.batchIds.concat(next.batchIds);
        current.count = currentOffset - current.offset;
      } else {
        const offset = currentOffset;
        currentOffset = copyIndicesGPU(
          readBuffer,
          writeBuffer,
          currentOffset,
          indexOffsets,
          indexCounts,
          next.batchIds,
          batchIdLookUp
        );
        next.offset = offset;
        next.count = currentOffset - offset;
        newBatchedIndices.push(next);
        current = next;
      }
    }

    const temp = primitive._va;
    primitive._va = primitive._vaSwap;
    primitive._vaSwap = temp;

    primitive._batchedIndices = newBatchedIndices;
  }

  function compareColors(a, b) {
    return b.color.toRgba() - a.color.toRgba();
  }

  // PERFORMANCE_IDEA: For WebGL 2, we can use copyBufferSubData for buffer-to-buffer copies.
  // PERFORMANCE_IDEA: Not supported, but we could use glMultiDrawElements here.
  function rebatchCommands(primitive, context) {
    if (!primitive._batchDirty) {
      return false;
    }

    const batchedIndices = primitive._batchedIndices;
    const length = batchedIndices.length;

    let needToRebatch = false;
    const colorCounts = {};

    for (let i = 0; i < length; ++i) {
      const color = batchedIndices[i].color;
      const rgba = color.toRgba();
      if (defined(colorCounts[rgba])) {
        needToRebatch = true;
        break;
      } else {
        colorCounts[rgba] = true;
      }
    }

    if (!needToRebatch) {
      primitive._batchDirty = false;
      return false;
    }

    if (
      needToRebatch &&
      !primitive.forceRebatch &&
      primitive._framesSinceLastRebatch < 120
    ) {
      ++primitive._framesSinceLastRebatch;
      return;
    }

    batchedIndices.sort(compareColors);

    if (context.webgl2) {
      rebatchGPU(primitive, batchedIndices);
    } else {
      rebatchCPU(primitive, batchedIndices);
    }

    primitive._framesSinceLastRebatch = 0;
    primitive._batchDirty = false;
    primitive._pickCommandsDirty = true;
    primitive._wireframeDirty = true;
    return true;
  }

  function createColorCommands(primitive, context) {
    const needsRebatch = rebatchCommands(primitive, context);

    const commands = primitive._commands;
    const batchedIndices = primitive._batchedIndices;
    const length = batchedIndices.length;
    const commandsLength = length * 2;

    if (
      defined(commands) &&
      !needsRebatch &&
      commands.length === commandsLength
    ) {
      return;
    }

    commands.length = commandsLength;

    const vertexArray = primitive._va;
    const sp = primitive._sp;
    const modelMatrix = defaultValue(primitive._modelMatrix, Matrix4.IDENTITY);
    const uniformMap = primitive._uniformMap;
    const bv = primitive._boundingVolume;

    for (let j = 0; j < length; ++j) {
      const offset = batchedIndices[j].offset;
      const count = batchedIndices[j].count;

      let stencilDepthCommand = commands[j * 2];
      if (!defined(stencilDepthCommand)) {
        stencilDepthCommand = commands[j * 2] = new DrawCommand({
          owner: primitive,
        });
      }

      stencilDepthCommand.vertexArray = vertexArray;
      stencilDepthCommand.modelMatrix = modelMatrix;
      stencilDepthCommand.offset = offset;
      stencilDepthCommand.count = count;
      stencilDepthCommand.renderState = primitive._rsStencilDepthPass;
      stencilDepthCommand.shaderProgram = sp;
      stencilDepthCommand.uniformMap = uniformMap;
      stencilDepthCommand.boundingVolume = bv;
      stencilDepthCommand.cull = false;
      stencilDepthCommand.pass = Pass$1.TERRAIN_CLASSIFICATION;

      const stencilDepthDerivedCommand = DrawCommand.shallowClone(
        stencilDepthCommand,
        stencilDepthCommand.derivedCommands.tileset
      );
      stencilDepthDerivedCommand.renderState =
        primitive._rsStencilDepthPass3DTiles;
      stencilDepthDerivedCommand.pass = Pass$1.CESIUM_3D_TILE_CLASSIFICATION;
      stencilDepthCommand.derivedCommands.tileset = stencilDepthDerivedCommand;

      let colorCommand = commands[j * 2 + 1];
      if (!defined(colorCommand)) {
        colorCommand = commands[j * 2 + 1] = new DrawCommand({
          owner: primitive,
        });
      }

      colorCommand.vertexArray = vertexArray;
      colorCommand.modelMatrix = modelMatrix;
      colorCommand.offset = offset;
      colorCommand.count = count;
      colorCommand.renderState = primitive._rsColorPass;
      colorCommand.shaderProgram = sp;
      colorCommand.uniformMap = uniformMap;
      colorCommand.boundingVolume = bv;
      colorCommand.cull = false;
      colorCommand.pass = Pass$1.TERRAIN_CLASSIFICATION;

      const colorDerivedCommand = DrawCommand.shallowClone(
        colorCommand,
        colorCommand.derivedCommands.tileset
      );
      colorDerivedCommand.pass = Pass$1.CESIUM_3D_TILE_CLASSIFICATION;
      colorCommand.derivedCommands.tileset = colorDerivedCommand;
    }

    primitive._commandsDirty = true;
  }

  function createColorCommandsIgnoreShow(primitive, frameState) {
    if (
      primitive.classificationType === ClassificationType$1.TERRAIN ||
      !frameState.invertClassification ||
      (defined(primitive._commandsIgnoreShow) && !primitive._commandsDirty)
    ) {
      return;
    }

    const commands = primitive._commands;
    const commandsIgnoreShow = primitive._commandsIgnoreShow;
    const spStencil = primitive._spStencil;

    const commandsLength = commands.length;
    const length = (commandsIgnoreShow.length = commandsLength / 2);

    let commandIndex = 0;
    for (let j = 0; j < length; ++j) {
      const commandIgnoreShow = (commandsIgnoreShow[j] = DrawCommand.shallowClone(
        commands[commandIndex],
        commandsIgnoreShow[j]
      ));
      commandIgnoreShow.shaderProgram = spStencil;
      commandIgnoreShow.pass = Pass$1.CESIUM_3D_TILE_CLASSIFICATION_IGNORE_SHOW;

      commandIndex += 2;
    }

    primitive._commandsDirty = false;
  }

  function createPickCommands(primitive) {
    if (!primitive._pickCommandsDirty) {
      return;
    }

    const length = primitive._indexOffsets.length;
    const pickCommands = primitive._pickCommands;
    pickCommands.length = length * 2;

    const vertexArray = primitive._va;
    const spStencil = primitive._spStencil;
    const spPick = primitive._spPick;
    const modelMatrix = defaultValue(primitive._modelMatrix, Matrix4.IDENTITY);
    const uniformMap = primitive._uniformMap;

    for (let j = 0; j < length; ++j) {
      const offset = primitive._indexOffsets[j];
      const count = primitive._indexCounts[j];
      const bv = defined(primitive._boundingVolumes)
        ? primitive._boundingVolumes[j]
        : primitive.boundingVolume;

      let stencilDepthCommand = pickCommands[j * 2];
      if (!defined(stencilDepthCommand)) {
        stencilDepthCommand = pickCommands[j * 2] = new DrawCommand({
          owner: primitive,
          pickOnly: true,
        });
      }

      stencilDepthCommand.vertexArray = vertexArray;
      stencilDepthCommand.modelMatrix = modelMatrix;
      stencilDepthCommand.offset = offset;
      stencilDepthCommand.count = count;
      stencilDepthCommand.renderState = primitive._rsStencilDepthPass;
      stencilDepthCommand.shaderProgram = spStencil;
      stencilDepthCommand.uniformMap = uniformMap;
      stencilDepthCommand.boundingVolume = bv;
      stencilDepthCommand.pass = Pass$1.TERRAIN_CLASSIFICATION;

      const stencilDepthDerivedCommand = DrawCommand.shallowClone(
        stencilDepthCommand,
        stencilDepthCommand.derivedCommands.tileset
      );
      stencilDepthDerivedCommand.renderState =
        primitive._rsStencilDepthPass3DTiles;
      stencilDepthDerivedCommand.pass = Pass$1.CESIUM_3D_TILE_CLASSIFICATION;
      stencilDepthCommand.derivedCommands.tileset = stencilDepthDerivedCommand;

      let colorCommand = pickCommands[j * 2 + 1];
      if (!defined(colorCommand)) {
        colorCommand = pickCommands[j * 2 + 1] = new DrawCommand({
          owner: primitive,
          pickOnly: true,
        });
      }

      colorCommand.vertexArray = vertexArray;
      colorCommand.modelMatrix = modelMatrix;
      colorCommand.offset = offset;
      colorCommand.count = count;
      colorCommand.renderState = primitive._rsPickPass;
      colorCommand.shaderProgram = spPick;
      colorCommand.uniformMap = uniformMap;
      colorCommand.boundingVolume = bv;
      colorCommand.pass = Pass$1.TERRAIN_CLASSIFICATION;

      const colorDerivedCommand = DrawCommand.shallowClone(
        colorCommand,
        colorCommand.derivedCommands.tileset
      );
      colorDerivedCommand.pass = Pass$1.CESIUM_3D_TILE_CLASSIFICATION;
      colorCommand.derivedCommands.tileset = colorDerivedCommand;
    }

    primitive._pickCommandsDirty = false;
  }

  /**
   * Creates features for each mesh and places it at the batch id index of features.
   *
   * @param {Vector3DTileContent} content The vector tile content.
   * @param {Cesium3DTileFeature[]} features An array of features where the polygon features will be placed.
   */
  Vector3DTilePrimitive.prototype.createFeatures = function (content, features) {
    const batchIds = this._batchIds;
    const length = batchIds.length;
    for (let i = 0; i < length; ++i) {
      const batchId = batchIds[i];
      features[batchId] = new Cesium3DTileFeature(content, batchId);
    }
  };

  /**
   * Colors the entire tile when enabled is true. The resulting color will be (mesh batch table color * color).
   *
   * @param {Boolean} enabled Whether to enable debug coloring.
   * @param {Color} color The debug color.
   */
  Vector3DTilePrimitive.prototype.applyDebugSettings = function (enabled, color) {
    this._highlightColor = enabled ? color : this._constantColor;
  };

  function clearStyle$3(polygons, features) {
    polygons._updatingAllCommands = true;

    const batchIds = polygons._batchIds;
    let length = batchIds.length;
    let i;

    for (i = 0; i < length; ++i) {
      const batchId = batchIds[i];
      const feature = features[batchId];

      feature.show = true;
      feature.color = Color.WHITE;
    }

    const batchedIndices = polygons._batchedIndices;
    length = batchedIndices.length;

    for (i = 0; i < length; ++i) {
      batchedIndices[i].color = Color.clone(Color.WHITE);
    }

    polygons._updatingAllCommands = false;
    polygons._batchDirty = true;
  }

  const scratchColor$l = new Color();

  const DEFAULT_COLOR_VALUE$2 = Color.WHITE;
  const DEFAULT_SHOW_VALUE$2 = true;

  const complexExpressionReg = /\$/;

  /**
   * Apply a style to the content.
   *
   * @param {Cesium3DTileStyle} style The style.
   * @param {Cesium3DTileFeature[]} features The array of features.
   */
  Vector3DTilePrimitive.prototype.applyStyle = function (style, features) {
    if (!defined(style)) {
      clearStyle$3(this, features);
      return;
    }

    const colorExpression = style.color;
    const isSimpleStyle =
      colorExpression instanceof Expression &&
      !complexExpressionReg.test(colorExpression.expression);
    this._updatingAllCommands = isSimpleStyle;

    const batchIds = this._batchIds;
    let length = batchIds.length;
    let i;

    for (i = 0; i < length; ++i) {
      const batchId = batchIds[i];
      const feature = features[batchId];

      feature.color = defined(style.color)
        ? style.color.evaluateColor(feature, scratchColor$l)
        : DEFAULT_COLOR_VALUE$2;
      feature.show = defined(style.show)
        ? style.show.evaluate(feature)
        : DEFAULT_SHOW_VALUE$2;
    }

    if (isSimpleStyle) {
      const batchedIndices = this._batchedIndices;
      length = batchedIndices.length;

      for (i = 0; i < length; ++i) {
        batchedIndices[i].color = Color.clone(Color.WHITE);
      }

      this._updatingAllCommands = false;
      this._batchDirty = true;
    }
  };

  /**
   * Call when updating the color of a mesh with batchId changes color. The meshes will need to be re-batched
   * on the next update.
   *
   * @param {Number} batchId The batch id of the meshes whose color has changed.
   * @param {Color} color The new polygon color.
   */
  Vector3DTilePrimitive.prototype.updateCommands = function (batchId, color) {
    if (this._updatingAllCommands) {
      return;
    }

    const batchIdLookUp = this._batchIdLookUp;
    const index = batchIdLookUp[batchId];
    if (!defined(index)) {
      return;
    }

    const indexOffsets = this._indexOffsets;
    const indexCounts = this._indexCounts;

    const offset = indexOffsets[index];
    const count = indexCounts[index];

    const batchedIndices = this._batchedIndices;
    const length = batchedIndices.length;

    let i;
    for (i = 0; i < length; ++i) {
      const batchedOffset = batchedIndices[i].offset;
      const batchedCount = batchedIndices[i].count;

      if (offset >= batchedOffset && offset < batchedOffset + batchedCount) {
        break;
      }
    }

    batchedIndices.push(
      new Vector3DTileBatch({
        color: Color.clone(color),
        offset: offset,
        count: count,
        batchIds: [batchId],
      })
    );

    const startIds = [];
    const endIds = [];

    const batchIds = batchedIndices[i].batchIds;
    const batchIdsLength = batchIds.length;

    for (let j = 0; j < batchIdsLength; ++j) {
      const id = batchIds[j];
      if (id === batchId) {
        continue;
      }

      const offsetIndex = batchIdLookUp[id];
      if (indexOffsets[offsetIndex] < offset) {
        startIds.push(id);
      } else {
        endIds.push(id);
      }
    }

    if (endIds.length !== 0) {
      batchedIndices.push(
        new Vector3DTileBatch({
          color: Color.clone(batchedIndices[i].color),
          offset: offset + count,
          count:
            batchedIndices[i].offset + batchedIndices[i].count - (offset + count),
          batchIds: endIds,
        })
      );
    }

    if (startIds.length !== 0) {
      batchedIndices[i].count = offset - batchedIndices[i].offset;
      batchedIndices[i].batchIds = startIds;
    } else {
      batchedIndices.splice(i, 1);
    }

    this._batchDirty = true;
  };

  function queueCommands$2(primitive, frameState, commands, commandsIgnoreShow) {
    const classificationType = primitive.classificationType;
    const queueTerrainCommands =
      classificationType !== ClassificationType$1.CESIUM_3D_TILE;
    const queue3DTilesCommands =
      classificationType !== ClassificationType$1.TERRAIN;

    const commandList = frameState.commandList;
    let commandLength = commands.length;
    let command;
    let i;
    for (i = 0; i < commandLength; ++i) {
      if (queueTerrainCommands) {
        command = commands[i];
        command.pass = Pass$1.TERRAIN_CLASSIFICATION;
        commandList.push(command);
      }
      if (queue3DTilesCommands) {
        command = commands[i].derivedCommands.tileset;
        command.pass = Pass$1.CESIUM_3D_TILE_CLASSIFICATION;
        commandList.push(command);
      }
    }

    if (!frameState.invertClassification || !defined(commandsIgnoreShow)) {
      return;
    }

    commandLength = commandsIgnoreShow.length;
    for (i = 0; i < commandLength; ++i) {
      commandList.push(commandsIgnoreShow[i]);
    }
  }

  function queueWireframeCommands(frameState, commands) {
    const commandList = frameState.commandList;
    const commandLength = commands.length;
    for (let i = 0; i < commandLength; i += 2) {
      const command = commands[i + 1];
      command.pass = Pass$1.OPAQUE;
      commandList.push(command);
    }
  }

  function updateWireframe$2(primitive) {
    let earlyExit = primitive.debugWireframe === primitive._debugWireframe;
    earlyExit =
      earlyExit && !(primitive.debugWireframe && primitive._wireframeDirty);
    if (earlyExit) {
      return;
    }

    if (!defined(primitive._rsWireframe)) {
      primitive._rsWireframe = RenderState.fromCache({});
    }

    let rs;
    let type;

    if (primitive.debugWireframe) {
      rs = primitive._rsWireframe;
      type = PrimitiveType$1.LINES;
    } else {
      rs = primitive._rsColorPass;
      type = PrimitiveType$1.TRIANGLES;
    }

    const commands = primitive._commands;
    const commandLength = commands.length;
    for (let i = 0; i < commandLength; i += 2) {
      const command = commands[i + 1];
      command.renderState = rs;
      command.primitiveType = type;
    }

    primitive._debugWireframe = primitive.debugWireframe;
    primitive._wireframeDirty = false;
  }

  /**
   * Updates the batches and queues the commands for rendering.
   *
   * @param {FrameState} frameState The current frame state.
   */
  Vector3DTilePrimitive.prototype.update = function (frameState) {
    const context = frameState.context;

    createVertexArray$4(this, context);
    createShaders$3(this, context);
    createRenderStates$4(this);
    createUniformMap$6(this, context);

    const passes = frameState.passes;
    if (passes.render) {
      createColorCommands(this, context);
      createColorCommandsIgnoreShow(this, frameState);
      updateWireframe$2(this);

      if (this._debugWireframe) {
        queueWireframeCommands(frameState, this._commands);
      } else {
        queueCommands$2(this, frameState, this._commands, this._commandsIgnoreShow);
      }
    }

    if (passes.pick) {
      createPickCommands(this);
      queueCommands$2(this, frameState, this._pickCommands);
    }
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <p>
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   * </p>
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   */
  Vector3DTilePrimitive.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <p>
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   * </p>
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   */
  Vector3DTilePrimitive.prototype.destroy = function () {
    this._va = this._va && this._va.destroy();
    this._sp = this._sp && this._sp.destroy();
    this._spPick = this._spPick && this._spPick.destroy();
    this._vaSwap = this._vaSwap && this._vaSwap.destroy();
    return destroyObject(this);
  };

  const boundingSphereCartesian3Scratch$1 = new Cartesian3();

  const ModelState$1 = ModelUtility.ModelState;

  ///////////////////////////////////////////////////////////////////////////

  /**
   * A 3D model for classifying other 3D assets based on glTF, the runtime 3D asset format.
   * This is a special case when a model of a 3D tileset becomes a classifier when setting {@link Cesium3DTileset#classificationType}.
   *
   * @alias ClassificationModel
   * @constructor
   *
   * @private
   *
   * @param {Object} options Object with the following properties:
   * @param {ArrayBuffer|Uint8Array} options.gltf A binary glTF buffer.
   * @param {Boolean} [options.show=true] Determines if the model primitive will be shown.
   * @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] The 4x4 transformation matrix that transforms the model from model to world coordinates.
   * @param {Boolean} [options.debugShowBoundingVolume=false] For debugging only. Draws the bounding sphere for each draw command in the model.
   * @param {Boolean} [options.debugWireframe=false] For debugging only. Draws the model in wireframe.
   * @param {ClassificationType} [options.classificationType] What this model will classify.
   *
   * @exception {RuntimeError} Only binary glTF is supported.
   * @exception {RuntimeError} Buffer data must be embedded in the binary glTF.
   * @exception {RuntimeError} Only one node is supported for classification and it must have a mesh.
   * @exception {RuntimeError} Only one mesh is supported when using b3dm for classification.
   * @exception {RuntimeError} Only one primitive per mesh is supported when using b3dm for classification.
   * @exception {RuntimeError} The mesh must have a position attribute.
   * @exception {RuntimeError} The mesh must have a batch id attribute.
   */
  function ClassificationModel(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    let gltf = options.gltf;
    if (gltf instanceof ArrayBuffer) {
      gltf = new Uint8Array(gltf);
    }

    if (gltf instanceof Uint8Array) {
      // Parse and update binary glTF
      gltf = parseGlb(gltf);
      updateVersion(gltf);
      addDefaults(gltf);
      processModelMaterialsCommon(gltf);
      processPbrMaterials(gltf);
    } else {
      throw new RuntimeError("Only binary glTF is supported as a classifier.");
    }

    ForEach.buffer(gltf, function (buffer) {
      if (!defined(buffer.extras._pipeline.source)) {
        throw new RuntimeError(
          "Buffer data must be embedded in the binary gltf."
        );
      }
    });

    const gltfNodes = gltf.nodes;
    const gltfMeshes = gltf.meshes;

    const gltfNode = gltfNodes[0];
    const meshId = gltfNode.mesh;
    if (gltfNodes.length !== 1 || !defined(meshId)) {
      throw new RuntimeError(
        "Only one node is supported for classification and it must have a mesh."
      );
    }

    if (gltfMeshes.length !== 1) {
      throw new RuntimeError(
        "Only one mesh is supported when using b3dm for classification."
      );
    }

    const gltfPrimitives = gltfMeshes[0].primitives;
    if (gltfPrimitives.length !== 1) {
      throw new RuntimeError(
        "Only one primitive per mesh is supported when using b3dm for classification."
      );
    }

    const gltfPositionAttribute = gltfPrimitives[0].attributes.POSITION;
    if (!defined(gltfPositionAttribute)) {
      throw new RuntimeError("The mesh must have a position attribute.");
    }

    const gltfBatchIdAttribute = gltfPrimitives[0].attributes._BATCHID;
    if (!defined(gltfBatchIdAttribute)) {
      throw new RuntimeError("The mesh must have a batch id attribute.");
    }

    this._gltf = gltf;

    /**
     * Determines if the model primitive will be shown.
     *
     * @type {Boolean}
     *
     * @default true
     */
    this.show = defaultValue(options.show, true);

    /**
     * The 4x4 transformation matrix that transforms the model from model to world coordinates.
     * When this is the identity matrix, the model is drawn in world coordinates, i.e., Earth's WGS84 coordinates.
     * Local reference frames can be used by providing a different transformation matrix, like that returned
     * by {@link Transforms.eastNorthUpToFixedFrame}.
     *
     * @type {Matrix4}
     *
     * @default {@link Matrix4.IDENTITY}
     *
     * @example
     * const origin = Cesium.Cartesian3.fromDegrees(-95.0, 40.0, 200000.0);
     * m.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(origin);
     */
    this.modelMatrix = Matrix4.clone(
      defaultValue(options.modelMatrix, Matrix4.IDENTITY)
    );
    this._modelMatrix = Matrix4.clone(this.modelMatrix);

    this._ready = false;
    this._readyPromise = defer();

    /**
     * This property is for debugging only; it is not for production use nor is it optimized.
     * <p>
     * Draws the bounding sphere for each draw command in the model.  A glTF primitive corresponds
     * to one draw command.  A glTF mesh has an array of primitives, often of length one.
     * </p>
     *
     * @type {Boolean}
     *
     * @default false
     */
    this.debugShowBoundingVolume = defaultValue(
      options.debugShowBoundingVolume,
      false
    );
    this._debugShowBoundingVolume = false;

    /**
     * This property is for debugging only; it is not for production use nor is it optimized.
     * <p>
     * Draws the model in wireframe.
     * </p>
     *
     * @type {Boolean}
     *
     * @default false
     */
    this.debugWireframe = defaultValue(options.debugWireframe, false);
    this._debugWireframe = false;

    this._classificationType = options.classificationType;

    // Undocumented options
    this._vertexShaderLoaded = options.vertexShaderLoaded;
    this._classificationShaderLoaded = options.classificationShaderLoaded;
    this._uniformMapLoaded = options.uniformMapLoaded;
    this._pickIdLoaded = options.pickIdLoaded;
    this._ignoreCommands = defaultValue(options.ignoreCommands, false);
    this._upAxis = defaultValue(options.upAxis, Axis$1.Y);
    this._batchTable = options.batchTable;

    this._computedModelMatrix = new Matrix4(); // Derived from modelMatrix and axis
    this._initialRadius = undefined; // Radius without model's scale property, model-matrix scale, animations, or skins
    this._boundingSphere = undefined;
    this._scaledBoundingSphere = new BoundingSphere();
    this._state = ModelState$1.NEEDS_LOAD;
    this._loadResources = undefined;

    this._mode = undefined;
    this._dirty = false; // true when the model was transformed this frame

    this._nodeMatrix = new Matrix4();
    this._primitive = undefined;

    this._extensionsUsed = undefined; // Cached used glTF extensions
    this._extensionsRequired = undefined; // Cached required glTF extensions
    this._quantizedUniforms = undefined; // Quantized uniforms for WEB3D_quantized_attributes

    this._buffers = {};
    this._vertexArray = undefined;
    this._shaderProgram = undefined;
    this._uniformMap = undefined;

    this._geometryByteLength = 0;
    this._trianglesLength = 0;

    // CESIUM_RTC extension
    this._rtcCenter = undefined; // reference to either 3D or 2D
    this._rtcCenterEye = undefined; // in eye coordinates
    this._rtcCenter3D = undefined; // in world coordinates
    this._rtcCenter2D = undefined; // in projected world coordinates
  }

  Object.defineProperties(ClassificationModel.prototype, {
    /**
     * The object for the glTF JSON, including properties with default values omitted
     * from the JSON provided to this model.
     *
     * @memberof ClassificationModel.prototype
     *
     * @type {Object}
     * @readonly
     *
     * @default undefined
     */
    gltf: {
      get: function () {
        return this._gltf;
      },
    },

    /**
     * For compatibility with Model which now uses gltfInternal to avoid
     * deprecation noise.
     *
     * @private
     */
    gltfInternal: {
      get: function () {
        return this._gltf;
      },
    },

    /**
     * The model's bounding sphere in its local coordinate system.
     *
     * @memberof ClassificationModel.prototype
     *
     * @type {BoundingSphere}
     * @readonly
     *
     * @default undefined
     *
     * @exception {DeveloperError} The model is not loaded.  Use ClassificationModel.readyPromise or wait for ClassificationModel.ready to be true.
     *
     * @example
     * // Center in WGS84 coordinates
     * const center = Cesium.Matrix4.multiplyByPoint(model.modelMatrix, model.boundingSphere.center, new Cesium.Cartesian3());
     */
    boundingSphere: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (this._state !== ModelState$1.LOADED) {
          throw new DeveloperError(
            "The model is not loaded.  Use ClassificationModel.readyPromise or wait for ClassificationModel.ready to be true."
          );
        }
        //>>includeEnd('debug');

        const modelMatrix = this.modelMatrix;
        const nonUniformScale = Matrix4.getScale(
          modelMatrix,
          boundingSphereCartesian3Scratch$1
        );

        const scaledBoundingSphere = this._scaledBoundingSphere;
        scaledBoundingSphere.center = Cartesian3.multiplyComponents(
          this._boundingSphere.center,
          nonUniformScale,
          scaledBoundingSphere.center
        );
        scaledBoundingSphere.radius =
          Cartesian3.maximumComponent(nonUniformScale) * this._initialRadius;

        if (defined(this._rtcCenter)) {
          Cartesian3.add(
            this._rtcCenter,
            scaledBoundingSphere.center,
            scaledBoundingSphere.center
          );
        }

        return scaledBoundingSphere;
      },
    },

    /**
     * When <code>true</code>, this model is ready to render, i.e., the external binary, image,
     * and shader files were downloaded and the WebGL resources were created.  This is set to
     * <code>true</code> right before {@link ClassificationModel#readyPromise} is resolved.
     *
     * @memberof ClassificationModel.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default false
     */
    ready: {
      get: function () {
        return this._ready;
      },
    },

    /**
     * Gets the promise that will be resolved when this model is ready to render, i.e., when the external binary, image,
     * and shader files were downloaded and the WebGL resources were created.
     * <p>
     * This promise is resolved at the end of the frame before the first frame the model is rendered in.
     * </p>
     *
     * @memberof ClassificationModel.prototype
     * @type {Promise.<ClassificationModel>}
     * @readonly
     *
     * @see ClassificationModel#ready
     */
    readyPromise: {
      get: function () {
        return this._readyPromise.promise;
      },
    },

    /**
     * Returns true if the model was transformed this frame
     *
     * @memberof ClassificationModel.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @private
     */
    dirty: {
      get: function () {
        return this._dirty;
      },
    },

    /**
     * Returns an object with all of the glTF extensions used.
     *
     * @memberof ClassificationModel.prototype
     *
     * @type {Object}
     * @readonly
     */
    extensionsUsed: {
      get: function () {
        if (!defined(this._extensionsUsed)) {
          this._extensionsUsed = ModelUtility.getUsedExtensions(this.gltf);
        }
        return this._extensionsUsed;
      },
    },

    /**
     * Returns an object with all of the glTF extensions required.
     *
     * @memberof ClassificationModel.prototype
     *
     * @type {Object}
     * @readonly
     */
    extensionsRequired: {
      get: function () {
        if (!defined(this._extensionsRequired)) {
          this._extensionsRequired = ModelUtility.getRequiredExtensions(
            this.gltf
          );
        }
        return this._extensionsRequired;
      },
    },

    /**
     * Gets the model's up-axis.
     * By default models are y-up according to the glTF spec, however geo-referenced models will typically be z-up.
     *
     * @memberof ClassificationModel.prototype
     *
     * @type {Number}
     * @default Axis.Y
     * @readonly
     *
     * @private
     */
    upAxis: {
      get: function () {
        return this._upAxis;
      },
    },

    /**
     * Gets the model's triangle count.
     *
     * @private
     */
    trianglesLength: {
      get: function () {
        return this._trianglesLength;
      },
    },

    /**
     * Gets the model's geometry memory in bytes. This includes all vertex and index buffers.
     *
     * @private
     */
    geometryByteLength: {
      get: function () {
        return this._geometryByteLength;
      },
    },

    /**
     * Gets the model's texture memory in bytes.
     *
     * @private
     */
    texturesByteLength: {
      get: function () {
        return 0;
      },
    },

    /**
     * Gets the model's classification type.
     * @memberof ClassificationModel.prototype
     * @type {ClassificationType}
     */
    classificationType: {
      get: function () {
        return this._classificationType;
      },
    },
  });

  ///////////////////////////////////////////////////////////////////////////

  function addBuffersToLoadResources$1(model) {
    const gltf = model.gltf;
    const loadResources = model._loadResources;
    ForEach.buffer(gltf, function (buffer, id) {
      loadResources.buffers[id] = buffer.extras._pipeline.source;
    });
  }

  function parseBufferViews$1(model) {
    const bufferViews = model.gltf.bufferViews;

    const vertexBuffersToCreate = model._loadResources.vertexBuffersToCreate;

    // Only ARRAY_BUFFER here.  ELEMENT_ARRAY_BUFFER created below.
    ForEach.bufferView(model.gltf, function (bufferView, id) {
      if (bufferView.target === WebGLConstants$1.ARRAY_BUFFER) {
        vertexBuffersToCreate.enqueue(id);
      }
    });

    const indexBuffersToCreate = model._loadResources.indexBuffersToCreate;
    const indexBufferIds = {};

    // The Cesium Renderer requires knowing the datatype for an index buffer
    // at creation type, which is not part of the glTF bufferview so loop
    // through glTF accessors to create the bufferview's index buffer.
    ForEach.accessor(model.gltf, function (accessor) {
      const bufferViewId = accessor.bufferView;
      const bufferView = bufferViews[bufferViewId];

      if (
        bufferView.target === WebGLConstants$1.ELEMENT_ARRAY_BUFFER &&
        !defined(indexBufferIds[bufferViewId])
      ) {
        indexBufferIds[bufferViewId] = true;
        indexBuffersToCreate.enqueue({
          id: bufferViewId,
          componentType: accessor.componentType,
        });
      }
    });
  }

  function createVertexBuffer$4(bufferViewId, model) {
    const loadResources = model._loadResources;
    const bufferViews = model.gltf.bufferViews;
    const bufferView = bufferViews[bufferViewId];
    const vertexBuffer = loadResources.getBuffer(bufferView);
    model._buffers[bufferViewId] = vertexBuffer;
    model._geometryByteLength += vertexBuffer.byteLength;
  }

  function createIndexBuffer$2(bufferViewId, componentType, model) {
    const loadResources = model._loadResources;
    const bufferViews = model.gltf.bufferViews;
    const bufferView = bufferViews[bufferViewId];
    const indexBuffer = {
      typedArray: loadResources.getBuffer(bufferView),
      indexDatatype: componentType,
    };
    model._buffers[bufferViewId] = indexBuffer;
    model._geometryByteLength += indexBuffer.typedArray.byteLength;
  }

  function createBuffers$1(model) {
    const loadResources = model._loadResources;

    if (loadResources.pendingBufferLoads !== 0) {
      return;
    }

    const vertexBuffersToCreate = loadResources.vertexBuffersToCreate;
    const indexBuffersToCreate = loadResources.indexBuffersToCreate;

    while (vertexBuffersToCreate.length > 0) {
      createVertexBuffer$4(vertexBuffersToCreate.dequeue(), model);
    }

    while (indexBuffersToCreate.length > 0) {
      const i = indexBuffersToCreate.dequeue();
      createIndexBuffer$2(i.id, i.componentType, model);
    }
  }

  function modifyShaderForQuantizedAttributes$1(shader, model) {
    const primitive = model.gltf.meshes[0].primitives[0];
    const result = ModelUtility.modifyShaderForQuantizedAttributes(
      model.gltf,
      primitive,
      shader
    );
    model._quantizedUniforms = result.uniforms;
    return result.shader;
  }

  function modifyShader$1(shader, callback) {
    if (defined(callback)) {
      shader = callback(shader);
    }
    return shader;
  }

  function createProgram$1(model) {
    const gltf = model.gltf;

    const positionName = ModelUtility.getAttributeOrUniformBySemantic(
      gltf,
      "POSITION"
    );
    const batchIdName = ModelUtility.getAttributeOrUniformBySemantic(
      gltf,
      "_BATCHID"
    );

    const attributeLocations = {};
    attributeLocations[positionName] = 0;
    attributeLocations[batchIdName] = 1;

    const modelViewProjectionName = ModelUtility.getAttributeOrUniformBySemantic(
      gltf,
      "MODELVIEWPROJECTION"
    );

    let uniformDecl;
    let toClip;

    if (!defined(modelViewProjectionName)) {
      const projectionName = ModelUtility.getAttributeOrUniformBySemantic(
        gltf,
        "PROJECTION"
      );
      let modelViewName = ModelUtility.getAttributeOrUniformBySemantic(
        gltf,
        "MODELVIEW"
      );
      if (!defined(modelViewName)) {
        modelViewName = ModelUtility.getAttributeOrUniformBySemantic(
          gltf,
          "CESIUM_RTC_MODELVIEW"
        );
      }

      uniformDecl =
        `uniform mat4 ${modelViewName};\n` + `uniform mat4 ${projectionName};\n`;
      toClip = `${projectionName} * ${modelViewName} * vec4(${positionName}, 1.0)`;
    } else {
      uniformDecl = `uniform mat4 ${modelViewProjectionName};\n`;
      toClip = `${modelViewProjectionName} * vec4(${positionName}, 1.0)`;
    }

    const computePosition = `    vec4 positionInClipCoords = ${toClip};\n`;

    let vs =
      `attribute vec3 ${positionName};\n` +
      `attribute float ${batchIdName};\n${uniformDecl}void main() {\n${computePosition}    gl_Position = czm_depthClamp(positionInClipCoords);\n` +
      `}\n`;
    const fs =
      "#ifdef GL_EXT_frag_depth\n" +
      "#extension GL_EXT_frag_depth : enable\n" +
      "#endif\n" +
      "void main() \n" +
      "{ \n" +
      "    gl_FragColor = vec4(1.0); \n" +
      "    czm_writeDepthClamp();\n" +
      "}\n";

    if (model.extensionsUsed.WEB3D_quantized_attributes) {
      vs = modifyShaderForQuantizedAttributes$1(vs, model);
    }

    const drawVS = modifyShader$1(vs, model._vertexShaderLoaded);
    const drawFS = modifyShader$1(fs, model._classificationShaderLoaded);

    model._shaderProgram = {
      vertexShaderSource: drawVS,
      fragmentShaderSource: drawFS,
      attributeLocations: attributeLocations,
    };
  }

  function getAttributeLocations$2() {
    return {
      POSITION: 0,
      _BATCHID: 1,
    };
  }

  function createVertexArray$3(model) {
    const loadResources = model._loadResources;
    if (!loadResources.finishedBuffersCreation() || defined(model._vertexArray)) {
      return;
    }

    const rendererBuffers = model._buffers;
    const gltf = model.gltf;
    const accessors = gltf.accessors;
    const meshes = gltf.meshes;
    const primitives = meshes[0].primitives;

    const primitive = primitives[0];
    const attributeLocations = getAttributeLocations$2();
    const attributes = {};
    ForEach.meshPrimitiveAttribute(primitive, function (
      accessorId,
      attributeName
    ) {
      // Skip if the attribute is not used by the material, e.g., because the asset
      // was exported with an attribute that wasn't used and the asset wasn't optimized.
      const attributeLocation = attributeLocations[attributeName];
      if (defined(attributeLocation)) {
        const a = accessors[accessorId];
        attributes[attributeName] = {
          index: attributeLocation,
          vertexBuffer: rendererBuffers[a.bufferView],
          componentsPerAttribute: numberOfComponentsForType(a.type),
          componentDatatype: a.componentType,
          offsetInBytes: a.byteOffset,
          strideInBytes: getAccessorByteStride(gltf, a),
        };
      }
    });

    let indexBuffer;
    if (defined(primitive.indices)) {
      const accessor = accessors[primitive.indices];
      indexBuffer = rendererBuffers[accessor.bufferView];
    }
    model._vertexArray = {
      attributes: attributes,
      indexBuffer: indexBuffer,
    };
  }

  const gltfSemanticUniforms = {
    PROJECTION: function (uniformState, model) {
      return ModelUtility.getGltfSemanticUniforms().PROJECTION(
        uniformState,
        model
      );
    },
    MODELVIEW: function (uniformState, model) {
      return ModelUtility.getGltfSemanticUniforms().MODELVIEW(
        uniformState,
        model
      );
    },
    CESIUM_RTC_MODELVIEW: function (uniformState, model) {
      return ModelUtility.getGltfSemanticUniforms().CESIUM_RTC_MODELVIEW(
        uniformState,
        model
      );
    },
    MODELVIEWPROJECTION: function (uniformState, model) {
      return ModelUtility.getGltfSemanticUniforms().MODELVIEWPROJECTION(
        uniformState,
        model
      );
    },
  };

  function createUniformMap$5(model, context) {
    if (defined(model._uniformMap)) {
      return;
    }

    const uniformMap = {};
    ForEach.technique(model.gltf, function (technique) {
      ForEach.techniqueUniform(technique, function (uniform, uniformName) {
        if (
          !defined(uniform.semantic) ||
          !defined(gltfSemanticUniforms[uniform.semantic])
        ) {
          return;
        }

        uniformMap[uniformName] = gltfSemanticUniforms[uniform.semantic](
          context.uniformState,
          model
        );
      });
    });

    model._uniformMap = uniformMap;
  }

  function createUniformsForQuantizedAttributes$1(model, primitive) {
    return ModelUtility.createUniformsForQuantizedAttributes(
      model.gltf,
      primitive,
      model._quantizedUniforms
    );
  }

  function triangleCountFromPrimitiveIndices$1(primitive, indicesCount) {
    switch (primitive.mode) {
      case PrimitiveType$1.TRIANGLES:
        return indicesCount / 3;
      case PrimitiveType$1.TRIANGLE_STRIP:
      case PrimitiveType$1.TRIANGLE_FAN:
        return Math.max(indicesCount - 2, 0);
      default:
        return 0;
    }
  }

  function createPrimitive$2(model) {
    const batchTable = model._batchTable;

    let uniformMap = model._uniformMap;
    const vertexArray = model._vertexArray;

    const gltf = model.gltf;
    const accessors = gltf.accessors;
    const gltfMeshes = gltf.meshes;
    const primitive = gltfMeshes[0].primitives[0];
    const ix = accessors[primitive.indices];

    const positionAccessor = primitive.attributes.POSITION;
    const minMax = ModelUtility.getAccessorMinMax(gltf, positionAccessor);
    const boundingSphere = BoundingSphere.fromCornerPoints(
      Cartesian3.fromArray(minMax.min),
      Cartesian3.fromArray(minMax.max)
    );

    let offset;
    let count;
    if (defined(ix)) {
      count = ix.count;
      offset = ix.byteOffset / IndexDatatype$1.getSizeInBytes(ix.componentType); // glTF has offset in bytes.  Cesium has offsets in indices
    } else {
      const positions = accessors[primitive.attributes.POSITION];
      count = positions.count;
      offset = 0;
    }

    // Update model triangle count using number of indices
    model._trianglesLength += triangleCountFromPrimitiveIndices$1(primitive, count);

    // Allow callback to modify the uniformMap
    if (defined(model._uniformMapLoaded)) {
      uniformMap = model._uniformMapLoaded(uniformMap);
    }

    // Add uniforms for decoding quantized attributes if used
    if (model.extensionsUsed.WEB3D_quantized_attributes) {
      const quantizedUniformMap = createUniformsForQuantizedAttributes$1(
        model,
        primitive
      );
      uniformMap = combine$2(uniformMap, quantizedUniformMap);
    }

    let attribute = vertexArray.attributes.POSITION;
    let componentDatatype = attribute.componentDatatype;
    let typedArray = attribute.vertexBuffer;
    let byteOffset = typedArray.byteOffset;
    let bufferLength =
      typedArray.byteLength / ComponentDatatype$1.getSizeInBytes(componentDatatype);
    let positionsBuffer = ComponentDatatype$1.createArrayBufferView(
      componentDatatype,
      typedArray.buffer,
      byteOffset,
      bufferLength
    );

    attribute = vertexArray.attributes._BATCHID;
    componentDatatype = attribute.componentDatatype;
    typedArray = attribute.vertexBuffer;
    byteOffset = typedArray.byteOffset;
    bufferLength =
      typedArray.byteLength / ComponentDatatype$1.getSizeInBytes(componentDatatype);
    let vertexBatchIds = ComponentDatatype$1.createArrayBufferView(
      componentDatatype,
      typedArray.buffer,
      byteOffset,
      bufferLength
    );

    const buffer = vertexArray.indexBuffer.typedArray;
    let indices;
    if (vertexArray.indexBuffer.indexDatatype === IndexDatatype$1.UNSIGNED_SHORT) {
      indices = new Uint16Array(
        buffer.buffer,
        buffer.byteOffset,
        buffer.byteLength / Uint16Array.BYTES_PER_ELEMENT
      );
    } else {
      indices = new Uint32Array(
        buffer.buffer,
        buffer.byteOffset,
        buffer.byteLength / Uint32Array.BYTES_PER_ELEMENT
      );
    }

    positionsBuffer = positionsBuffer.slice();
    vertexBatchIds = vertexBatchIds.slice();
    indices = indices.slice(offset, offset + count);

    const batchIds = [];
    const indexCounts = [];
    const indexOffsets = [];
    const batchedIndices = [];

    let currentId = vertexBatchIds[indices[0]];
    batchIds.push(currentId);
    indexOffsets.push(0);

    let batchId;
    let indexOffset;
    let indexCount;
    const indicesLength = indices.length;
    for (let j = 1; j < indicesLength; ++j) {
      batchId = vertexBatchIds[indices[j]];
      if (batchId !== currentId) {
        indexOffset = indexOffsets[indexOffsets.length - 1];
        indexCount = j - indexOffset;

        batchIds.push(batchId);
        indexCounts.push(indexCount);
        indexOffsets.push(j);

        batchedIndices.push(
          new Vector3DTileBatch({
            offset: indexOffset,
            count: indexCount,
            batchIds: [currentId],
            color: Color.WHITE,
          })
        );

        currentId = batchId;
      }
    }

    indexOffset = indexOffsets[indexOffsets.length - 1];
    indexCount = indicesLength - indexOffset;

    indexCounts.push(indexCount);
    batchedIndices.push(
      new Vector3DTileBatch({
        offset: indexOffset,
        count: indexCount,
        batchIds: [currentId],
        color: Color.WHITE,
      })
    );

    const shader = model._shaderProgram;
    const vertexShaderSource = shader.vertexShaderSource;
    const fragmentShaderSource = shader.fragmentShaderSource;
    const attributeLocations = shader.attributeLocations;
    const pickId = defined(model._pickIdLoaded)
      ? model._pickIdLoaded()
      : undefined;

    model._primitive = new Vector3DTilePrimitive({
      classificationType: model._classificationType,
      positions: positionsBuffer,
      indices: indices,
      indexOffsets: indexOffsets,
      indexCounts: indexCounts,
      batchIds: batchIds,
      vertexBatchIds: vertexBatchIds,
      batchedIndices: batchedIndices,
      batchTable: batchTable,
      boundingVolume: new BoundingSphere(), // updated in update()
      _vertexShaderSource: vertexShaderSource,
      _fragmentShaderSource: fragmentShaderSource,
      _attributeLocations: attributeLocations,
      _uniformMap: uniformMap,
      _pickId: pickId,
      _modelMatrix: new Matrix4(), // updated in update()
      _boundingSphere: boundingSphere, // used to update boundingVolume
    });

    // Release CPU resources
    model._buffers = undefined;
    model._vertexArray = undefined;
    model._shaderProgram = undefined;
    model._uniformMap = undefined;
  }

  function createRuntimeNodes$1(model) {
    const loadResources = model._loadResources;
    if (!loadResources.finished()) {
      return;
    }

    if (defined(model._primitive)) {
      return;
    }

    const gltf = model.gltf;
    const nodes = gltf.nodes;
    const gltfNode = nodes[0];
    model._nodeMatrix = ModelUtility.getTransform(gltfNode, model._nodeMatrix);

    createPrimitive$2(model);
  }

  function createResources$5(model, frameState) {
    const context = frameState.context;

    ModelUtility.checkSupportedGlExtensions(model.gltf.glExtensionsUsed, context);
    createBuffers$1(model); // using glTF bufferViews
    createProgram$1(model);
    createVertexArray$3(model); // using glTF meshes
    createUniformMap$5(model, context); // using glTF materials/techniques
    createRuntimeNodes$1(model); // using glTF scene
  }

  ///////////////////////////////////////////////////////////////////////////

  const scratchComputedTranslation$3 = new Cartesian4();
  const scratchComputedMatrixIn2D$1 = new Matrix4();

  function updateNodeModelMatrix(
    model,
    modelTransformChanged,
    justLoaded,
    projection
  ) {
    let computedModelMatrix = model._computedModelMatrix;

    if (model._mode !== SceneMode$1.SCENE3D && !model._ignoreCommands) {
      const translation = Matrix4.getColumn(
        computedModelMatrix,
        3,
        scratchComputedTranslation$3
      );
      if (!Cartesian4.equals(translation, Cartesian4.UNIT_W)) {
        computedModelMatrix = Transforms.basisTo2D(
          projection,
          computedModelMatrix,
          scratchComputedMatrixIn2D$1
        );
        model._rtcCenter = model._rtcCenter3D;
      } else {
        const center = model.boundingSphereInternal.center;
        const to2D = Transforms.wgs84To2DModelMatrix(
          projection,
          center,
          scratchComputedMatrixIn2D$1
        );
        computedModelMatrix = Matrix4.multiply(
          to2D,
          computedModelMatrix,
          scratchComputedMatrixIn2D$1
        );

        if (defined(model._rtcCenter)) {
          Matrix4.setTranslation(
            computedModelMatrix,
            Cartesian4.UNIT_W,
            computedModelMatrix
          );
          model._rtcCenter = model._rtcCenter2D;
        }
      }
    }

    const primitive = model._primitive;

    if (modelTransformChanged || justLoaded) {
      Matrix4.multiplyTransformation(
        computedModelMatrix,
        model._nodeMatrix,
        primitive._modelMatrix
      );
      BoundingSphere.transform(
        primitive._boundingSphere,
        primitive._modelMatrix,
        primitive._boundingVolume
      );

      if (defined(model._rtcCenter)) {
        Cartesian3.add(
          model._rtcCenter,
          primitive._boundingVolume.center,
          primitive._boundingVolume.center
        );
      }
    }
  }

  ///////////////////////////////////////////////////////////////////////////

  ClassificationModel.prototype.updateCommands = function (batchId, color) {
    this._primitive.updateCommands(batchId, color);
  };

  ClassificationModel.prototype.update = function (frameState) {
    if (frameState.mode === SceneMode$1.MORPHING) {
      return;
    }

    if (!FeatureDetection.supportsWebP.initialized) {
      FeatureDetection.supportsWebP.initialize();
      return;
    }
    const supportsWebP = FeatureDetection.supportsWebP();

    if (this._state === ModelState$1.NEEDS_LOAD && defined(this.gltf)) {
      this._state = ModelState$1.LOADING;
      if (this._state !== ModelState$1.FAILED) {
        const extensions = this.gltf.extensions;
        if (defined(extensions) && defined(extensions.CESIUM_RTC)) {
          const center = Cartesian3.fromArray(extensions.CESIUM_RTC.center);
          if (!Cartesian3.equals(center, Cartesian3.ZERO)) {
            this._rtcCenter3D = center;

            const projection = frameState.mapProjection;
            const ellipsoid = projection.ellipsoid;
            const cartographic = ellipsoid.cartesianToCartographic(
              this._rtcCenter3D
            );
            const projectedCart = projection.project(cartographic);
            Cartesian3.fromElements(
              projectedCart.z,
              projectedCart.x,
              projectedCart.y,
              projectedCart
            );
            this._rtcCenter2D = projectedCart;

            this._rtcCenterEye = new Cartesian3();
            this._rtcCenter = this._rtcCenter3D;
          }
        }

        this._loadResources = new ModelLoadResources();
        ModelUtility.parseBuffers(this);
      }
    }

    const loadResources = this._loadResources;
    let justLoaded = false;

    if (this._state === ModelState$1.LOADING) {
      // Transition from LOADING -> LOADED once resources are downloaded and created.
      // Textures may continue to stream in while in the LOADED state.
      if (loadResources.pendingBufferLoads === 0) {
        ModelUtility.checkSupportedExtensions(
          this.extensionsRequired,
          supportsWebP
        );

        addBuffersToLoadResources$1(this);
        parseBufferViews$1(this);

        this._boundingSphere = ModelUtility.computeBoundingSphere(this);
        this._initialRadius = this._boundingSphere.radius;
        createResources$5(this, frameState);
      }
      if (loadResources.finished()) {
        this._state = ModelState$1.LOADED;
        justLoaded = true;
      }
    }

    if (defined(loadResources) && this._state === ModelState$1.LOADED) {
      if (!justLoaded) {
        createResources$5(this, frameState);
      }

      if (loadResources.finished()) {
        this._loadResources = undefined; // Clear CPU memory since WebGL resources were created.
      }
    }

    const show = this.show;

    if ((show && this._state === ModelState$1.LOADED) || justLoaded) {
      this._dirty = false;
      const modelMatrix = this.modelMatrix;

      const modeChanged = frameState.mode !== this._mode;
      this._mode = frameState.mode;

      // ClassificationModel's model matrix needs to be updated
      const modelTransformChanged =
        !Matrix4.equals(this._modelMatrix, modelMatrix) || modeChanged;

      if (modelTransformChanged || justLoaded) {
        Matrix4.clone(modelMatrix, this._modelMatrix);

        const computedModelMatrix = this._computedModelMatrix;
        Matrix4.clone(modelMatrix, computedModelMatrix);
        if (this._upAxis === Axis$1.Y) {
          Matrix4.multiplyTransformation(
            computedModelMatrix,
            Axis$1.Y_UP_TO_Z_UP,
            computedModelMatrix
          );
        } else if (this._upAxis === Axis$1.X) {
          Matrix4.multiplyTransformation(
            computedModelMatrix,
            Axis$1.X_UP_TO_Z_UP,
            computedModelMatrix
          );
        }
      }

      // Update modelMatrix throughout the graph as needed
      if (modelTransformChanged || justLoaded) {
        updateNodeModelMatrix(
          this,
          modelTransformChanged,
          justLoaded,
          frameState.mapProjection
        );
        this._dirty = true;
      }
    }

    if (justLoaded) {
      // Called after modelMatrix update.
      const model = this;
      frameState.afterRender.push(function () {
        model._ready = true;
        model._readyPromise.resolve(model);
      });
      return;
    }

    if (show && !this._ignoreCommands) {
      this._primitive.debugShowBoundingVolume = this.debugShowBoundingVolume;
      this._primitive.debugWireframe = this.debugWireframe;
      this._primitive.update(frameState);
    }
  };

  ClassificationModel.prototype.isDestroyed = function () {
    return false;
  };

  ClassificationModel.prototype.destroy = function () {
    this._primitive = this._primitive && this._primitive.destroy();
    return destroyObject(this);
  };

  /**
   * A Plane in Hessian Normal form to be used with {@link ClippingPlaneCollection}.
   * Compatible with mathematics functions in {@link Plane}
   *
   * @alias ClippingPlane
   * @constructor
   *
   * @param {Cartesian3} normal The plane's normal (normalized).
   * @param {Number} distance The shortest distance from the origin to the plane.  The sign of
   * <code>distance</code> determines which side of the plane the origin
   * is on.  If <code>distance</code> is positive, the origin is in the half-space
   * in the direction of the normal; if negative, the origin is in the half-space
   * opposite to the normal; if zero, the plane passes through the origin.
   */
  function ClippingPlane(normal, distance) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("normal", normal);
    Check.typeOf.number("distance", distance);
    //>>includeEnd('debug');

    this._distance = distance;
    this._normal = new UpdateChangedCartesian3(normal, this);
    this.onChangeCallback = undefined;
    this.index = -1; // to be set by ClippingPlaneCollection
  }

  Object.defineProperties(ClippingPlane.prototype, {
    /**
     * The shortest distance from the origin to the plane.  The sign of
     * <code>distance</code> determines which side of the plane the origin
     * is on.  If <code>distance</code> is positive, the origin is in the half-space
     * in the direction of the normal; if negative, the origin is in the half-space
     * opposite to the normal; if zero, the plane passes through the origin.
     *
     * @type {Number}
     * @memberof ClippingPlane.prototype
     */
    distance: {
      get: function () {
        return this._distance;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number("value", value);
        //>>includeEnd('debug');
        if (defined(this.onChangeCallback) && value !== this._distance) {
          this.onChangeCallback(this.index);
        }
        this._distance = value;
      },
    },
    /**
     * The plane's normal.
     *
     * @type {Cartesian3}
     * @memberof ClippingPlane.prototype
     */
    normal: {
      get: function () {
        return this._normal;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.object("value", value);
        //>>includeEnd('debug');
        if (
          defined(this.onChangeCallback) &&
          !Cartesian3.equals(this._normal._cartesian3, value)
        ) {
          this.onChangeCallback(this.index);
        }
        // Set without firing callback again
        Cartesian3.clone(value, this._normal._cartesian3);
      },
    },
  });

  /**
   * Create a ClippingPlane from a Plane object.
   *
   * @param {Plane} plane The plane containing parameters to copy
   * @param {ClippingPlane} [result] The object on which to store the result
   * @returns {ClippingPlane} The ClippingPlane generated from the plane's parameters.
   */
  ClippingPlane.fromPlane = function (plane, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("plane", plane);
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new ClippingPlane(plane.normal, plane.distance);
    } else {
      result.normal = plane.normal;
      result.distance = plane.distance;
    }
    return result;
  };

  /**
   * Clones the ClippingPlane without setting its ownership.
   * @param {ClippingPlane} clippingPlane The ClippingPlane to be cloned
   * @param {ClippingPlane} [result] The object on which to store the cloned parameters.
   * @returns {ClippingPlane} a clone of the input ClippingPlane
   */
  ClippingPlane.clone = function (clippingPlane, result) {
    if (!defined(result)) {
      return new ClippingPlane(clippingPlane.normal, clippingPlane.distance);
    }
    result.normal = clippingPlane.normal;
    result.distance = clippingPlane.distance;
    return result;
  };

  /**
   * Wrapper on Cartesian3 that allows detection of Plane changes from "members of members," for example:
   *
   * const clippingPlane = new ClippingPlane(...);
   * clippingPlane.normal.z = -1.0;
   *
   * @private
   */
  function UpdateChangedCartesian3(normal, clippingPlane) {
    this._clippingPlane = clippingPlane;
    this._cartesian3 = Cartesian3.clone(normal);
  }

  Object.defineProperties(UpdateChangedCartesian3.prototype, {
    x: {
      get: function () {
        return this._cartesian3.x;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number("value", value);
        //>>includeEnd('debug');
        if (
          defined(this._clippingPlane.onChangeCallback) &&
          value !== this._cartesian3.x
        ) {
          this._clippingPlane.onChangeCallback(this._clippingPlane.index);
        }
        this._cartesian3.x = value;
      },
    },
    y: {
      get: function () {
        return this._cartesian3.y;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number("value", value);
        //>>includeEnd('debug');
        if (
          defined(this._clippingPlane.onChangeCallback) &&
          value !== this._cartesian3.y
        ) {
          this._clippingPlane.onChangeCallback(this._clippingPlane.index);
        }
        this._cartesian3.y = value;
      },
    },
    z: {
      get: function () {
        return this._cartesian3.z;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number("value", value);
        //>>includeEnd('debug');
        if (
          defined(this._clippingPlane.onChangeCallback) &&
          value !== this._cartesian3.z
        ) {
          this._clippingPlane.onChangeCallback(this._clippingPlane.index);
        }
        this._cartesian3.z = value;
      },
    },
  });

  /**
   * Specifies a set of clipping planes. Clipping planes selectively disable rendering in a region on the
   * outside of the specified list of {@link ClippingPlane} objects for a single gltf model, 3D Tileset, or the globe.
   * <p>
   * In general the clipping planes' coordinates are relative to the object they're attached to, so a plane with distance set to 0 will clip
   * through the center of the object.
   * </p>
   * <p>
   * For 3D Tiles, the root tile's transform is used to position the clipping planes. If a transform is not defined, the root tile's {@link Cesium3DTile#boundingSphere} is used instead.
   * </p>
   *
   * @alias ClippingPlaneCollection
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {ClippingPlane[]} [options.planes=[]] An array of {@link ClippingPlane} objects used to selectively disable rendering on the outside of each plane.
   * @param {Boolean} [options.enabled=true] Determines whether the clipping planes are active.
   * @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] The 4x4 transformation matrix specifying an additional transform relative to the clipping planes original coordinate system.
   * @param {Boolean} [options.unionClippingRegions=false] If true, a region will be clipped if it is on the outside of any plane in the collection. Otherwise, a region will only be clipped if it is on the outside of every plane.
   * @param {Color} [options.edgeColor=Color.WHITE] The color applied to highlight the edge along which an object is clipped.
   * @param {Number} [options.edgeWidth=0.0] The width, in pixels, of the highlight applied to the edge along which an object is clipped.
   *
   * @demo {@link https://sandcastle.cesium.com/?src=3D%20Tiles%20Clipping%20Planes.html|Clipping 3D Tiles and glTF models.}
   * @demo {@link https://sandcastle.cesium.com/?src=Terrain%20Clipping%20Planes.html|Clipping the Globe.}
   *
   * @example
   * // This clipping plane's distance is positive, which means its normal
   * // is facing the origin. This will clip everything that is behind
   * // the plane, which is anything with y coordinate < -5.
   * const clippingPlanes = new Cesium.ClippingPlaneCollection({
   *     planes : [
   *         new Cesium.ClippingPlane(new Cesium.Cartesian3(0.0, 1.0, 0.0), 5.0)
   *     ],
   * });
   * // Create an entity and attach the ClippingPlaneCollection to the model.
   * const entity = viewer.entities.add({
   *     position : Cesium.Cartesian3.fromDegrees(-123.0744619, 44.0503706, 10000),
   *     model : {
   *         uri : 'model.gltf',
   *         minimumPixelSize : 128,
   *         maximumScale : 20000,
   *         clippingPlanes : clippingPlanes
   *     }
   * });
   * viewer.zoomTo(entity);
   */
  function ClippingPlaneCollection(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    this._planes = [];

    // Do partial texture updates if just one plane is dirty.
    // If many planes are dirty, refresh the entire texture.
    this._dirtyIndex = -1;
    this._multipleDirtyPlanes = false;

    this._enabled = defaultValue(options.enabled, true);

    /**
     * The 4x4 transformation matrix specifying an additional transform relative to the clipping planes
     * original coordinate system.
     *
     * @type {Matrix4}
     * @default Matrix4.IDENTITY
     */
    this.modelMatrix = Matrix4.clone(
      defaultValue(options.modelMatrix, Matrix4.IDENTITY)
    );

    /**
     * The color applied to highlight the edge along which an object is clipped.
     *
     * @type {Color}
     * @default Color.WHITE
     */
    this.edgeColor = Color.clone(defaultValue(options.edgeColor, Color.WHITE));

    /**
     * The width, in pixels, of the highlight applied to the edge along which an object is clipped.
     *
     * @type {Number}
     * @default 0.0
     */
    this.edgeWidth = defaultValue(options.edgeWidth, 0.0);

    /**
     * An event triggered when a new clipping plane is added to the collection.  Event handlers
     * are passed the new plane and the index at which it was added.
     * @type {Event}
     * @default Event()
     */
    this.planeAdded = new Event();

    /**
     * An event triggered when a new clipping plane is removed from the collection.  Event handlers
     * are passed the new plane and the index from which it was removed.
     * @type {Event}
     * @default Event()
     */
    this.planeRemoved = new Event();

    // If this ClippingPlaneCollection has an owner, only its owner should update or destroy it.
    // This is because in a Cesium3DTileset multiple models may reference the tileset's ClippingPlaneCollection.
    this._owner = undefined;

    const unionClippingRegions = defaultValue(
      options.unionClippingRegions,
      false
    );
    this._unionClippingRegions = unionClippingRegions;
    this._testIntersection = unionClippingRegions
      ? unionIntersectFunction
      : defaultIntersectFunction;

    this._uint8View = undefined;
    this._float32View = undefined;

    this._clippingPlanesTexture = undefined;

    // Add each ClippingPlane object.
    const planes = options.planes;
    if (defined(planes)) {
      const planesLength = planes.length;
      for (let i = 0; i < planesLength; ++i) {
        this.add(planes[i]);
      }
    }
  }

  function unionIntersectFunction(value) {
    return value === Intersect$1.OUTSIDE;
  }

  function defaultIntersectFunction(value) {
    return value === Intersect$1.INSIDE;
  }

  Object.defineProperties(ClippingPlaneCollection.prototype, {
    /**
     * Returns the number of planes in this collection.  This is commonly used with
     * {@link ClippingPlaneCollection#get} to iterate over all the planes
     * in the collection.
     *
     * @memberof ClippingPlaneCollection.prototype
     * @type {Number}
     * @readonly
     */
    length: {
      get: function () {
        return this._planes.length;
      },
    },

    /**
     * If true, a region will be clipped if it is on the outside of any plane in the
     * collection. Otherwise, a region will only be clipped if it is on the
     * outside of every plane.
     *
     * @memberof ClippingPlaneCollection.prototype
     * @type {Boolean}
     * @default false
     */
    unionClippingRegions: {
      get: function () {
        return this._unionClippingRegions;
      },
      set: function (value) {
        if (this._unionClippingRegions === value) {
          return;
        }
        this._unionClippingRegions = value;
        this._testIntersection = value
          ? unionIntersectFunction
          : defaultIntersectFunction;
      },
    },

    /**
     * If true, clipping will be enabled.
     *
     * @memberof ClippingPlaneCollection.prototype
     * @type {Boolean}
     * @default true
     */
    enabled: {
      get: function () {
        return this._enabled;
      },
      set: function (value) {
        if (this._enabled === value) {
          return;
        }
        this._enabled = value;
      },
    },

    /**
     * Returns a texture containing packed, untransformed clipping planes.
     *
     * @memberof ClippingPlaneCollection.prototype
     * @type {Texture}
     * @readonly
     * @private
     */
    texture: {
      get: function () {
        return this._clippingPlanesTexture;
      },
    },

    /**
     * A reference to the ClippingPlaneCollection's owner, if any.
     *
     * @memberof ClippingPlaneCollection.prototype
     * @readonly
     * @private
     */
    owner: {
      get: function () {
        return this._owner;
      },
    },

    /**
     * Returns a Number encapsulating the state for this ClippingPlaneCollection.
     *
     * Clipping mode is encoded in the sign of the number, which is just the plane count.
     * If this value changes, then shader regeneration is necessary.
     *
     * @memberof ClippingPlaneCollection.prototype
     * @returns {Number} A Number that describes the ClippingPlaneCollection's state.
     * @readonly
     * @private
     */
    clippingPlanesState: {
      get: function () {
        return this._unionClippingRegions
          ? this._planes.length
          : -this._planes.length;
      },
    },
  });

  function setIndexDirty(collection, index) {
    // If there's already a different _dirtyIndex set, more than one plane has changed since update.
    // Entire texture must be reloaded
    collection._multipleDirtyPlanes =
      collection._multipleDirtyPlanes ||
      (collection._dirtyIndex !== -1 && collection._dirtyIndex !== index);
    collection._dirtyIndex = index;
  }

  /**
   * Adds the specified {@link ClippingPlane} to the collection to be used to selectively disable rendering
   * on the outside of each plane. Use {@link ClippingPlaneCollection#unionClippingRegions} to modify
   * how modify the clipping behavior of multiple planes.
   *
   * @param {ClippingPlane} plane The ClippingPlane to add to the collection.
   *
   * @see ClippingPlaneCollection#unionClippingRegions
   * @see ClippingPlaneCollection#remove
   * @see ClippingPlaneCollection#removeAll
   */
  ClippingPlaneCollection.prototype.add = function (plane) {
    const newPlaneIndex = this._planes.length;

    const that = this;
    plane.onChangeCallback = function (index) {
      setIndexDirty(that, index);
    };
    plane.index = newPlaneIndex;

    setIndexDirty(this, newPlaneIndex);
    this._planes.push(plane);
    this.planeAdded.raiseEvent(plane, newPlaneIndex);
  };

  /**
   * Returns the plane in the collection at the specified index.  Indices are zero-based
   * and increase as planes are added.  Removing a plane shifts all planes after
   * it to the left, changing their indices.  This function is commonly used with
   * {@link ClippingPlaneCollection#length} to iterate over all the planes
   * in the collection.
   *
   * @param {Number} index The zero-based index of the plane.
   * @returns {ClippingPlane} The ClippingPlane at the specified index.
   *
   * @see ClippingPlaneCollection#length
   */
  ClippingPlaneCollection.prototype.get = function (index) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("index", index);
    //>>includeEnd('debug');

    return this._planes[index];
  };

  function indexOf$1(planes, plane) {
    const length = planes.length;
    for (let i = 0; i < length; ++i) {
      if (Plane.equals(planes[i], plane)) {
        return i;
      }
    }

    return -1;
  }

  /**
   * Checks whether this collection contains a ClippingPlane equal to the given ClippingPlane.
   *
   * @param {ClippingPlane} [clippingPlane] The ClippingPlane to check for.
   * @returns {Boolean} true if this collection contains the ClippingPlane, false otherwise.
   *
   * @see ClippingPlaneCollection#get
   */
  ClippingPlaneCollection.prototype.contains = function (clippingPlane) {
    return indexOf$1(this._planes, clippingPlane) !== -1;
  };

  /**
   * Removes the first occurrence of the given ClippingPlane from the collection.
   *
   * @param {ClippingPlane} clippingPlane
   * @returns {Boolean} <code>true</code> if the plane was removed; <code>false</code> if the plane was not found in the collection.
   *
   * @see ClippingPlaneCollection#add
   * @see ClippingPlaneCollection#contains
   * @see ClippingPlaneCollection#removeAll
   */
  ClippingPlaneCollection.prototype.remove = function (clippingPlane) {
    const planes = this._planes;
    const index = indexOf$1(planes, clippingPlane);

    if (index === -1) {
      return false;
    }

    // Unlink this ClippingPlaneCollection from the ClippingPlane
    if (clippingPlane instanceof ClippingPlane) {
      clippingPlane.onChangeCallback = undefined;
      clippingPlane.index = -1;
    }

    // Shift and update indices
    const length = planes.length - 1;
    for (let i = index; i < length; ++i) {
      const planeToKeep = planes[i + 1];
      planes[i] = planeToKeep;
      if (planeToKeep instanceof ClippingPlane) {
        planeToKeep.index = i;
      }
    }

    // Indicate planes texture is dirty
    this._multipleDirtyPlanes = true;
    planes.length = length;

    this.planeRemoved.raiseEvent(clippingPlane, index);

    return true;
  };

  /**
   * Removes all planes from the collection.
   *
   * @see ClippingPlaneCollection#add
   * @see ClippingPlaneCollection#remove
   */
  ClippingPlaneCollection.prototype.removeAll = function () {
    // Dereference this ClippingPlaneCollection from all ClippingPlanes
    const planes = this._planes;
    const planesCount = planes.length;
    for (let i = 0; i < planesCount; ++i) {
      const plane = planes[i];
      if (plane instanceof ClippingPlane) {
        plane.onChangeCallback = undefined;
        plane.index = -1;
      }
      this.planeRemoved.raiseEvent(plane, i);
    }
    this._multipleDirtyPlanes = true;
    this._planes = [];
  };

  const distanceEncodeScratch = new Cartesian4();
  const oct32EncodeScratch = new Cartesian4();
  function packPlanesAsUint8(clippingPlaneCollection, startIndex, endIndex) {
    const uint8View = clippingPlaneCollection._uint8View;
    const planes = clippingPlaneCollection._planes;
    let byteIndex = 0;
    for (let i = startIndex; i < endIndex; ++i) {
      const plane = planes[i];

      const oct32Normal = AttributeCompression.octEncodeToCartesian4(
        plane.normal,
        oct32EncodeScratch
      );
      uint8View[byteIndex] = oct32Normal.x;
      uint8View[byteIndex + 1] = oct32Normal.y;
      uint8View[byteIndex + 2] = oct32Normal.z;
      uint8View[byteIndex + 3] = oct32Normal.w;

      const encodedDistance = Cartesian4.packFloat(
        plane.distance,
        distanceEncodeScratch
      );
      uint8View[byteIndex + 4] = encodedDistance.x;
      uint8View[byteIndex + 5] = encodedDistance.y;
      uint8View[byteIndex + 6] = encodedDistance.z;
      uint8View[byteIndex + 7] = encodedDistance.w;

      byteIndex += 8;
    }
  }

  // Pack starting at the beginning of the buffer to allow partial update
  function packPlanesAsFloats(clippingPlaneCollection, startIndex, endIndex) {
    const float32View = clippingPlaneCollection._float32View;
    const planes = clippingPlaneCollection._planes;

    let floatIndex = 0;
    for (let i = startIndex; i < endIndex; ++i) {
      const plane = planes[i];
      const normal = plane.normal;

      float32View[floatIndex] = normal.x;
      float32View[floatIndex + 1] = normal.y;
      float32View[floatIndex + 2] = normal.z;
      float32View[floatIndex + 3] = plane.distance;

      floatIndex += 4; // each plane is 4 floats
    }
  }

  function computeTextureResolution(pixelsNeeded, result) {
    const maxSize = ContextLimits.maximumTextureSize;
    result.x = Math.min(pixelsNeeded, maxSize);
    result.y = Math.ceil(pixelsNeeded / result.x);
    return result;
  }

  const textureResolutionScratch$2 = new Cartesian2();
  /**
   * Called when {@link Viewer} or {@link CesiumWidget} render the scene to
   * build the resources for clipping planes.
   * <p>
   * Do not call this function directly.
   * </p>
   */
  ClippingPlaneCollection.prototype.update = function (frameState) {
    let clippingPlanesTexture = this._clippingPlanesTexture;
    const context = frameState.context;
    const useFloatTexture = ClippingPlaneCollection.useFloatTexture(context);

    // Compute texture requirements for current planes
    // In RGBA FLOAT, A plane is 4 floats packed to a RGBA.
    // In RGBA UNSIGNED_BYTE, A plane is a float in [0, 1) packed to RGBA and an Oct32 quantized normal,
    // so 8 bits or 2 pixels in RGBA.
    const pixelsNeeded = useFloatTexture ? this.length : this.length * 2;

    if (defined(clippingPlanesTexture)) {
      const currentPixelCount =
        clippingPlanesTexture.width * clippingPlanesTexture.height;
      // Recreate the texture to double current requirement if it isn't big enough or is 4 times larger than it needs to be.
      // Optimization note: this isn't exactly the classic resizeable array algorithm
      // * not necessarily checking for resize after each add/remove operation
      // * random-access deletes instead of just pops
      // * alloc ops likely more expensive than demonstrable via big-O analysis
      if (
        currentPixelCount < pixelsNeeded ||
        pixelsNeeded < 0.25 * currentPixelCount
      ) {
        clippingPlanesTexture.destroy();
        clippingPlanesTexture = undefined;
        this._clippingPlanesTexture = undefined;
      }
    }

    // If there are no clipping planes, there's nothing to update.
    if (this.length === 0) {
      return;
    }

    if (!defined(clippingPlanesTexture)) {
      const requiredResolution = computeTextureResolution(
        pixelsNeeded,
        textureResolutionScratch$2
      );
      // Allocate twice as much space as needed to avoid frequent texture reallocation.
      // Allocate in the Y direction, since texture may be as wide as context texture support.
      requiredResolution.y *= 2;

      if (useFloatTexture) {
        clippingPlanesTexture = new Texture({
          context: context,
          width: requiredResolution.x,
          height: requiredResolution.y,
          pixelFormat: PixelFormat$1.RGBA,
          pixelDatatype: PixelDatatype$1.FLOAT,
          sampler: Sampler.NEAREST,
          flipY: false,
        });
        this._float32View = new Float32Array(
          requiredResolution.x * requiredResolution.y * 4
        );
      } else {
        clippingPlanesTexture = new Texture({
          context: context,
          width: requiredResolution.x,
          height: requiredResolution.y,
          pixelFormat: PixelFormat$1.RGBA,
          pixelDatatype: PixelDatatype$1.UNSIGNED_BYTE,
          sampler: Sampler.NEAREST,
          flipY: false,
        });
        this._uint8View = new Uint8Array(
          requiredResolution.x * requiredResolution.y * 4
        );
      }

      this._clippingPlanesTexture = clippingPlanesTexture;
      this._multipleDirtyPlanes = true;
    }

    const dirtyIndex = this._dirtyIndex;
    if (!this._multipleDirtyPlanes && dirtyIndex === -1) {
      return;
    }
    if (!this._multipleDirtyPlanes) {
      // partial updates possible
      let offsetX = 0;
      let offsetY = 0;
      if (useFloatTexture) {
        offsetY = Math.floor(dirtyIndex / clippingPlanesTexture.width);
        offsetX = Math.floor(dirtyIndex - offsetY * clippingPlanesTexture.width);

        packPlanesAsFloats(this, dirtyIndex, dirtyIndex + 1);
        clippingPlanesTexture.copyFrom({
          source: {
            width: 1,
            height: 1,
            arrayBufferView: this._float32View,
          },
          xOffset: offsetX,
          yOffset: offsetY,
        });
      } else {
        offsetY = Math.floor((dirtyIndex * 2) / clippingPlanesTexture.width);
        offsetX = Math.floor(
          dirtyIndex * 2 - offsetY * clippingPlanesTexture.width
        );
        packPlanesAsUint8(this, dirtyIndex, dirtyIndex + 1);
        clippingPlanesTexture.copyFrom({
          source: {
            width: 2,
            height: 1,
            arrayBufferView: this._uint8View,
          },
          xOffset: offsetX,
          yOffset: offsetY,
        });
      }
    } else if (useFloatTexture) {
      packPlanesAsFloats(this, 0, this._planes.length);
      clippingPlanesTexture.copyFrom({
        source: {
          width: clippingPlanesTexture.width,
          height: clippingPlanesTexture.height,
          arrayBufferView: this._float32View,
        },
      });
    } else {
      packPlanesAsUint8(this, 0, this._planes.length);
      clippingPlanesTexture.copyFrom({
        source: {
          width: clippingPlanesTexture.width,
          height: clippingPlanesTexture.height,
          arrayBufferView: this._uint8View,
        },
      });
    }

    this._multipleDirtyPlanes = false;
    this._dirtyIndex = -1;
  };

  const scratchMatrix$4 = new Matrix4();
  const scratchPlane = new Plane(Cartesian3.UNIT_X, 0.0);
  /**
   * Determines the type intersection with the planes of this ClippingPlaneCollection instance and the specified {@link TileBoundingVolume}.
   * @private
   *
   * @param {Object} tileBoundingVolume The volume to determine the intersection with the planes.
   * @param {Matrix4} [transform] An optional, additional matrix to transform the plane to world coordinates.
   * @returns {Intersect} {@link Intersect.INSIDE} if the entire volume is on the side of the planes
   *                      the normal is pointing and should be entirely rendered, {@link Intersect.OUTSIDE}
   *                      if the entire volume is on the opposite side and should be clipped, and
   *                      {@link Intersect.INTERSECTING} if the volume intersects the planes.
   */
  ClippingPlaneCollection.prototype.computeIntersectionWithBoundingVolume = function (
    tileBoundingVolume,
    transform
  ) {
    const planes = this._planes;
    const length = planes.length;

    let modelMatrix = this.modelMatrix;
    if (defined(transform)) {
      modelMatrix = Matrix4.multiply(transform, modelMatrix, scratchMatrix$4);
    }

    // If the collection is not set to union the clipping regions, the volume must be outside of all planes to be
    // considered completely clipped. If the collection is set to union the clipping regions, if the volume can be
    // outside any the planes, it is considered completely clipped.
    // Lastly, if not completely clipped, if any plane is intersecting, more calculations must be performed.
    let intersection = Intersect$1.INSIDE;
    if (!this.unionClippingRegions && length > 0) {
      intersection = Intersect$1.OUTSIDE;
    }

    for (let i = 0; i < length; ++i) {
      const plane = planes[i];

      Plane.transform(plane, modelMatrix, scratchPlane); // ClippingPlane can be used for Plane math

      const value = tileBoundingVolume.intersectPlane(scratchPlane);
      if (value === Intersect$1.INTERSECTING) {
        intersection = value;
      } else if (this._testIntersection(value)) {
        return value;
      }
    }

    return intersection;
  };

  /**
   * Sets the owner for the input ClippingPlaneCollection if there wasn't another owner.
   * Destroys the owner's previous ClippingPlaneCollection if setting is successful.
   *
   * @param {ClippingPlaneCollection} [clippingPlaneCollection] A ClippingPlaneCollection (or undefined) being attached to an object
   * @param {Object} owner An Object that should receive the new ClippingPlaneCollection
   * @param {String} key The Key for the Object to reference the ClippingPlaneCollection
   * @private
   */
  ClippingPlaneCollection.setOwner = function (
    clippingPlaneCollection,
    owner,
    key
  ) {
    // Don't destroy the ClippingPlaneCollection if it is already owned by newOwner
    if (clippingPlaneCollection === owner[key]) {
      return;
    }
    // Destroy the existing ClippingPlaneCollection, if any
    owner[key] = owner[key] && owner[key].destroy();
    if (defined(clippingPlaneCollection)) {
      //>>includeStart('debug', pragmas.debug);
      if (defined(clippingPlaneCollection._owner)) {
        throw new DeveloperError(
          "ClippingPlaneCollection should only be assigned to one object"
        );
      }
      //>>includeEnd('debug');
      clippingPlaneCollection._owner = owner;
      owner[key] = clippingPlaneCollection;
    }
  };

  /**
   * Function for checking if the context will allow clipping planes with floating point textures.
   *
   * @param {Context} context The Context that will contain clipped objects and clipping textures.
   * @returns {Boolean} <code>true</code> if floating point textures can be used for clipping planes.
   * @private
   */
  ClippingPlaneCollection.useFloatTexture = function (context) {
    return context.floatingPointTexture;
  };

  /**
   * Function for getting the clipping plane collection's texture resolution.
   * If the ClippingPlaneCollection hasn't been updated, returns the resolution that will be
   * allocated based on the current plane count.
   *
   * @param {ClippingPlaneCollection} clippingPlaneCollection The clipping plane collection
   * @param {Context} context The rendering context
   * @param {Cartesian2} result A Cartesian2 for the result.
   * @returns {Cartesian2} The required resolution.
   * @private
   */
  ClippingPlaneCollection.getTextureResolution = function (
    clippingPlaneCollection,
    context,
    result
  ) {
    const texture = clippingPlaneCollection.texture;
    if (defined(texture)) {
      result.x = texture.width;
      result.y = texture.height;
      return result;
    }

    const pixelsNeeded = ClippingPlaneCollection.useFloatTexture(context)
      ? clippingPlaneCollection.length
      : clippingPlaneCollection.length * 2;
    const requiredResolution = computeTextureResolution(pixelsNeeded, result);

    // Allocate twice as much space as needed to avoid frequent texture reallocation.
    requiredResolution.y *= 2;
    return requiredResolution;
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see ClippingPlaneCollection#destroy
   */
  ClippingPlaneCollection.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * clippingPlanes = clippingPlanes && clippingPlanes.destroy();
   *
   * @see ClippingPlaneCollection#isDestroyed
   */
  ClippingPlaneCollection.prototype.destroy = function () {
    this._clippingPlanesTexture =
      this._clippingPlanesTexture && this._clippingPlanesTexture.destroy();
    return destroyObject(this);
  };

  /**
   * Defines different modes for blending between a target color and a primitive's source color.
   *
   * HIGHLIGHT multiplies the source color by the target color
   * REPLACE replaces the source color with the target color
   * MIX blends the source color and target color together
   *
   * @enum {Number}
   *
   * @see Model.colorBlendMode
   */
  const ColorBlendMode = {
    HIGHLIGHT: 0,
    REPLACE: 1,
    MIX: 2,
  };

  /**
   * @private
   */
  ColorBlendMode.getColorBlend = function (colorBlendMode, colorBlendAmount) {
    if (colorBlendMode === ColorBlendMode.HIGHLIGHT) {
      return 0.0;
    } else if (colorBlendMode === ColorBlendMode.REPLACE) {
      return 1.0;
    } else if (colorBlendMode === ColorBlendMode.MIX) {
      // The value 0.0 is reserved for highlight, so clamp to just above 0.0.
      return CesiumMath.clamp(colorBlendAmount, CesiumMath.EPSILON4, 1.0);
    }
  };
  var ColorBlendMode$1 = Object.freeze(ColorBlendMode);

  /**
   * @private
   */
  function DracoLoader() {}

  // Maximum concurrency to use when decoding draco models
  DracoLoader._maxDecodingConcurrency = Math.max(
    FeatureDetection.hardwareConcurrency - 1,
    1
  );

  // Exposed for testing purposes
  DracoLoader._decoderTaskProcessor = undefined;
  DracoLoader._taskProcessorReady = false;
  DracoLoader._getDecoderTaskProcessor = function () {
    if (!defined(DracoLoader._decoderTaskProcessor)) {
      const processor = new TaskProcessor(
        "decodeDraco",
        DracoLoader._maxDecodingConcurrency
      );
      processor
        .initWebAssemblyModule({
          modulePath: "ThirdParty/Workers/draco_decoder_nodejs.js",
          wasmBinaryFile: "ThirdParty/draco_decoder.wasm",
        })
        .then(function () {
          DracoLoader._taskProcessorReady = true;
        });
      DracoLoader._decoderTaskProcessor = processor;
    }

    return DracoLoader._decoderTaskProcessor;
  };

  /**
   * Returns true if the model uses or requires KHR_draco_mesh_compression.
   *
   * @private
   */
  DracoLoader.hasExtension = function (model) {
    return (
      defined(model.extensionsRequired.KHR_draco_mesh_compression) ||
      defined(model.extensionsUsed.KHR_draco_mesh_compression)
    );
  };

  function addBufferToLoadResources(loadResources, typedArray) {
    // Create a new id to differentiate from original glTF bufferViews
    const bufferViewId = `runtime.${
    Object.keys(loadResources.createdBufferViews).length
  }`;

    const loadResourceBuffers = loadResources.buffers;
    const id = Object.keys(loadResourceBuffers).length;
    loadResourceBuffers[id] = typedArray;
    loadResources.createdBufferViews[bufferViewId] = {
      buffer: id,
      byteOffset: 0,
      byteLength: typedArray.byteLength,
    };

    return bufferViewId;
  }

  function addNewVertexBuffer(typedArray, model, context) {
    const loadResources = model._loadResources;
    const id = addBufferToLoadResources(loadResources, typedArray);
    loadResources.vertexBuffersToCreate.enqueue(id);
    return id;
  }

  function addNewIndexBuffer(indexArray, model, context) {
    const typedArray = indexArray.typedArray;
    const loadResources = model._loadResources;
    const id = addBufferToLoadResources(loadResources, typedArray);
    loadResources.indexBuffersToCreate.enqueue({
      id: id,
      componentType: ComponentDatatype$1.fromTypedArray(typedArray),
    });

    return {
      bufferViewId: id,
      numberOfIndices: indexArray.numberOfIndices,
    };
  }

  function scheduleDecodingTask(
    decoderTaskProcessor,
    model,
    loadResources,
    context
  ) {
    if (!DracoLoader._taskProcessorReady) {
      // The task processor is not ready to schedule tasks
      return;
    }

    const taskData = loadResources.primitivesToDecode.peek();
    if (!defined(taskData)) {
      // All primitives are processing
      return;
    }

    const promise = decoderTaskProcessor.scheduleTask(taskData, [
      taskData.array.buffer,
    ]);
    if (!defined(promise)) {
      // Cannot schedule another task this frame
      return;
    }

    loadResources.activeDecodingTasks++;
    loadResources.primitivesToDecode.dequeue();
    return promise.then(function (result) {
      loadResources.activeDecodingTasks--;

      const decodedIndexBuffer = addNewIndexBuffer(
        result.indexArray,
        model);

      const attributes = {};
      const decodedAttributeData = result.attributeData;
      for (const attributeName in decodedAttributeData) {
        if (decodedAttributeData.hasOwnProperty(attributeName)) {
          const attribute = decodedAttributeData[attributeName];
          const vertexArray = attribute.array;
          const vertexBufferView = addNewVertexBuffer(
            vertexArray,
            model);

          const data = attribute.data;
          data.bufferView = vertexBufferView;

          attributes[attributeName] = data;
        }
      }

      model._decodedData[`${taskData.mesh}.primitive.${taskData.primitive}`] = {
        bufferView: decodedIndexBuffer.bufferViewId,
        numberOfIndices: decodedIndexBuffer.numberOfIndices,
        attributes: attributes,
      };
    });
  }

  DracoLoader._decodedModelResourceCache = undefined;

  /**
   * Parses draco extension on model primitives and
   * adds the decoding data to the model's load resources.
   *
   * @private
   */
  DracoLoader.parse = function (model, context) {
    if (!DracoLoader.hasExtension(model)) {
      return;
    }

    const loadResources = model._loadResources;
    const cacheKey = model.cacheKey;
    if (defined(cacheKey)) {
      if (!defined(DracoLoader._decodedModelResourceCache)) {
        if (!defined(context.cache.modelDecodingCache)) {
          context.cache.modelDecodingCache = {};
        }

        DracoLoader._decodedModelResourceCache = context.cache.modelDecodingCache;
      }

      // Decoded data for model will be loaded from cache
      const cachedData = DracoLoader._decodedModelResourceCache[cacheKey];
      if (defined(cachedData)) {
        cachedData.count++;
        loadResources.pendingDecodingCache = true;
        return;
      }
    }

    const dequantizeInShader = model._dequantizeInShader;
    const gltf = model.gltfInternal;
    ForEach.mesh(gltf, function (mesh, meshId) {
      ForEach.meshPrimitive(mesh, function (primitive, primitiveId) {
        if (!defined(primitive.extensions)) {
          return;
        }

        const compressionData = primitive.extensions.KHR_draco_mesh_compression;
        if (!defined(compressionData)) {
          return;
        }

        const bufferView = gltf.bufferViews[compressionData.bufferView];
        const arraySource =
          gltf.buffers[bufferView.buffer].extras._pipeline.source;
        const typedArray = arraySource.slice(
          bufferView.byteOffset,
          bufferView.byteOffset + bufferView.byteLength
        );
        loadResources.primitivesToDecode.enqueue({
          mesh: meshId,
          primitive: primitiveId,
          array: typedArray,
          bufferView: bufferView,
          compressedAttributes: compressionData.attributes,
          dequantizeInShader: dequantizeInShader,
        });
      });
    });
  };

  /**
   * Schedules decoding tasks available this frame.
   * @private
   */
  DracoLoader.decodeModel = function (model, context) {
    if (!DracoLoader.hasExtension(model)) {
      return Promise.resolve();
    }

    const loadResources = model._loadResources;
    const cacheKey = model.cacheKey;
    if (defined(cacheKey) && defined(DracoLoader._decodedModelResourceCache)) {
      const cachedData = DracoLoader._decodedModelResourceCache[cacheKey];
      // Load decoded data for model when cache is ready
      if (defined(cachedData) && loadResources.pendingDecodingCache) {
        return Promise.resolve(cachedData.ready).then(function () {
          model._decodedData = cachedData.data;
          loadResources.pendingDecodingCache = false;
        });
      }

      // Decoded data for model should be cached when ready
      DracoLoader._decodedModelResourceCache[cacheKey] = {
        ready: false,
        count: 1,
        data: undefined,
      };
    }

    if (loadResources.primitivesToDecode.length === 0) {
      // No more tasks to schedule
      return Promise.resolve();
    }

    const decoderTaskProcessor = DracoLoader._getDecoderTaskProcessor();
    const decodingPromises = [];

    let promise = scheduleDecodingTask(
      decoderTaskProcessor,
      model,
      loadResources);
    while (defined(promise)) {
      decodingPromises.push(promise);
      promise = scheduleDecodingTask(
        decoderTaskProcessor,
        model,
        loadResources);
    }

    return Promise.all(decodingPromises);
  };

  /**
   * Decodes a compressed point cloud. Returns undefined if the task cannot be scheduled.
   * @private
   */
  DracoLoader.decodePointCloud = function (parameters) {
    const decoderTaskProcessor = DracoLoader._getDecoderTaskProcessor();
    if (!DracoLoader._taskProcessorReady) {
      // The task processor is not ready to schedule tasks
      return;
    }
    return decoderTaskProcessor.scheduleTask(parameters, [
      parameters.buffer.buffer,
    ]);
  };

  /**
   * Decodes a buffer view. Returns undefined if the task cannot be scheduled.
   *
   * @param {Object} options Object with the following properties:
   * @param {Uint8Array} options.array The typed array containing the buffer view data.
   * @param {Object} options.bufferView The glTF buffer view object.
   * @param {Object.<String, Number>} options.compressedAttributes The compressed attributes.
   * @param {Boolean} options.dequantizeInShader Whether POSITION and NORMAL attributes should be dequantized on the GPU.
   *
   * @returns {Promise} A promise that resolves to the decoded indices and attributes.
   * @private
   */
  DracoLoader.decodeBufferView = function (options) {
    const decoderTaskProcessor = DracoLoader._getDecoderTaskProcessor();
    if (!DracoLoader._taskProcessorReady) {
      // The task processor is not ready to schedule tasks
      return;
    }

    return decoderTaskProcessor.scheduleTask(options, [options.array.buffer]);
  };

  /**
   * Caches a models decoded data so it doesn't need to decode more than once.
   * @private
   */
  DracoLoader.cacheDataForModel = function (model) {
    const cacheKey = model.cacheKey;
    if (defined(cacheKey) && defined(DracoLoader._decodedModelResourceCache)) {
      const cachedData = DracoLoader._decodedModelResourceCache[cacheKey];
      if (defined(cachedData)) {
        cachedData.ready = true;
        cachedData.data = model._decodedData;
      }
    }
  };

  /**
   * Destroys the cached data that this model references if it is no longer in use.
   * @private
   */
  DracoLoader.destroyCachedDataForModel = function (model) {
    const cacheKey = model.cacheKey;
    if (defined(cacheKey) && defined(DracoLoader._decodedModelResourceCache)) {
      const cachedData = DracoLoader._decodedModelResourceCache[cacheKey];
      if (defined(cachedData) && --cachedData.count === 0) {
        delete DracoLoader._decodedModelResourceCache[cacheKey];
      }
    }
  };

  /**
   * Gets a GLSL snippet that clips a fragment using the `clip` function from {@link getClippingFunction} and styles it.
   *
   * @param {String} samplerUniformName Name of the uniform for the clipping planes texture sampler.
   * @param {String} matrixUniformName Name of the uniform for the clipping planes matrix.
   * @param {String} styleUniformName Name of the uniform for the clipping planes style, a vec4.
   * @returns {String} A string containing GLSL that clips and styles the current fragment.
   * @private
   */
  function getClipAndStyleCode(
    samplerUniformName,
    matrixUniformName,
    styleUniformName
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("samplerUniformName", samplerUniformName);
    Check.typeOf.string("matrixUniformName", matrixUniformName);
    Check.typeOf.string("styleUniformName", styleUniformName);
    //>>includeEnd('debug');

    const shaderCode =
      `    float clipDistance = clip(gl_FragCoord, ${samplerUniformName}, ${matrixUniformName}); \n` +
      `    vec4 clippingPlanesEdgeColor = vec4(1.0); \n` +
      `    clippingPlanesEdgeColor.rgb = ${styleUniformName}.rgb; \n` +
      `    float clippingPlanesEdgeWidth = ${styleUniformName}.a; \n` +
      `    if (clipDistance > 0.0 && clipDistance < clippingPlanesEdgeWidth) \n` +
      `    { \n` +
      `        gl_FragColor = clippingPlanesEdgeColor;\n` +
      `    } \n`;
    return shaderCode;
  }

  const textureResolutionScratch$1 = new Cartesian2();
  /**
   * Gets the GLSL functions needed to retrieve clipping planes from a ClippingPlaneCollection's texture.
   *
   * @param {ClippingPlaneCollection} clippingPlaneCollection ClippingPlaneCollection with a defined texture.
   * @param {Context} context The current rendering context.
   * @returns {String} A string containing GLSL functions for retrieving clipping planes.
   * @private
   */
  function getClippingFunction(clippingPlaneCollection, context) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("clippingPlaneCollection", clippingPlaneCollection);
    Check.typeOf.object("context", context);
    //>>includeEnd('debug');
    const unionClippingRegions = clippingPlaneCollection.unionClippingRegions;
    const clippingPlanesLength = clippingPlaneCollection.length;
    const usingFloatTexture = ClippingPlaneCollection.useFloatTexture(context);
    const textureResolution = ClippingPlaneCollection.getTextureResolution(
      clippingPlaneCollection,
      context,
      textureResolutionScratch$1
    );
    const width = textureResolution.x;
    const height = textureResolution.y;

    let functions = usingFloatTexture
      ? getClippingPlaneFloat(width, height)
      : getClippingPlaneUint8(width, height);
    functions += "\n";
    functions += unionClippingRegions
      ? clippingFunctionUnion(clippingPlanesLength)
      : clippingFunctionIntersect(clippingPlanesLength);
    return functions;
  }

  function clippingFunctionUnion(clippingPlanesLength) {
    const functionString =
      `${
      "float clip(vec4 fragCoord, sampler2D clippingPlanes, mat4 clippingPlanesMatrix)\n" +
      "{\n" +
      "    vec4 position = czm_windowToEyeCoordinates(fragCoord);\n" +
      "    vec3 clipNormal = vec3(0.0);\n" +
      "    vec3 clipPosition = vec3(0.0);\n" +
      "    float clipAmount;\n" + // For union planes, we want to get the min distance. So we set the initial value to the first plane distance in the loop below.
      "    float pixelWidth = czm_metersPerPixel(position);\n" +
      "    bool breakAndDiscard = false;\n" +
      "    for (int i = 0; i < "
    }${clippingPlanesLength}; ++i)\n` +
      `    {\n` +
      `        vec4 clippingPlane = getClippingPlane(clippingPlanes, i, clippingPlanesMatrix);\n` +
      `        clipNormal = clippingPlane.xyz;\n` +
      `        clipPosition = -clippingPlane.w * clipNormal;\n` +
      `        float amount = dot(clipNormal, (position.xyz - clipPosition)) / pixelWidth;\n` +
      `        clipAmount = czm_branchFreeTernary(i == 0, amount, min(amount, clipAmount));\n` +
      `        if (amount <= 0.0)\n` +
      `        {\n` +
      `           breakAndDiscard = true;\n` +
      `           break;\n` + // HLSL compiler bug if we discard here: https://bugs.chromium.org/p/angleproject/issues/detail?id=1945#c6
      `        }\n` +
      `    }\n` +
      `    if (breakAndDiscard) {\n` +
      `        discard;\n` +
      `    }\n` +
      `    return clipAmount;\n` +
      `}\n`;
    return functionString;
  }

  function clippingFunctionIntersect(clippingPlanesLength) {
    const functionString =
      `${
      "float clip(vec4 fragCoord, sampler2D clippingPlanes, mat4 clippingPlanesMatrix)\n" +
      "{\n" +
      "    bool clipped = true;\n" +
      "    vec4 position = czm_windowToEyeCoordinates(fragCoord);\n" +
      "    vec3 clipNormal = vec3(0.0);\n" +
      "    vec3 clipPosition = vec3(0.0);\n" +
      "    float clipAmount = 0.0;\n" +
      "    float pixelWidth = czm_metersPerPixel(position);\n" +
      "    for (int i = 0; i < "
    }${clippingPlanesLength}; ++i)\n` +
      `    {\n` +
      `        vec4 clippingPlane = getClippingPlane(clippingPlanes, i, clippingPlanesMatrix);\n` +
      `        clipNormal = clippingPlane.xyz;\n` +
      `        clipPosition = -clippingPlane.w * clipNormal;\n` +
      `        float amount = dot(clipNormal, (position.xyz - clipPosition)) / pixelWidth;\n` +
      `        clipAmount = max(amount, clipAmount);\n` +
      `        clipped = clipped && (amount <= 0.0);\n` +
      `    }\n` +
      `    if (clipped)\n` +
      `    {\n` +
      `        discard;\n` +
      `    }\n` +
      `    return clipAmount;\n` +
      `}\n`;
    return functionString;
  }

  function getClippingPlaneFloat(width, height) {
    const pixelWidth = 1.0 / width;
    const pixelHeight = 1.0 / height;

    let pixelWidthString = `${pixelWidth}`;
    if (pixelWidthString.indexOf(".") === -1) {
      pixelWidthString += ".0";
    }
    let pixelHeightString = `${pixelHeight}`;
    if (pixelHeightString.indexOf(".") === -1) {
      pixelHeightString += ".0";
    }

    const functionString =
      `${
      "vec4 getClippingPlane(highp sampler2D packedClippingPlanes, int clippingPlaneNumber, mat4 transform)\n" +
      "{\n" +
      "    int pixY = clippingPlaneNumber / "
    }${width};\n` +
      `    int pixX = clippingPlaneNumber - (pixY * ${width});\n` +
      `    float u = (float(pixX) + 0.5) * ${pixelWidthString};\n` + // sample from center of pixel
      `    float v = (float(pixY) + 0.5) * ${pixelHeightString};\n` +
      `    vec4 plane = texture2D(packedClippingPlanes, vec2(u, v));\n` +
      `    return czm_transformPlane(plane, transform);\n` +
      `}\n`;
    return functionString;
  }

  function getClippingPlaneUint8(width, height) {
    const pixelWidth = 1.0 / width;
    const pixelHeight = 1.0 / height;

    let pixelWidthString = `${pixelWidth}`;
    if (pixelWidthString.indexOf(".") === -1) {
      pixelWidthString += ".0";
    }
    let pixelHeightString = `${pixelHeight}`;
    if (pixelHeightString.indexOf(".") === -1) {
      pixelHeightString += ".0";
    }

    const functionString =
      `${
      "vec4 getClippingPlane(highp sampler2D packedClippingPlanes, int clippingPlaneNumber, mat4 transform)\n" +
      "{\n" +
      "    int clippingPlaneStartIndex = clippingPlaneNumber * 2;\n" + // clipping planes are two pixels each
      "    int pixY = clippingPlaneStartIndex / "
    }${width};\n` +
      `    int pixX = clippingPlaneStartIndex - (pixY * ${width});\n` +
      `    float u = (float(pixX) + 0.5) * ${pixelWidthString};\n` + // sample from center of pixel
      `    float v = (float(pixY) + 0.5) * ${pixelHeightString};\n` +
      `    vec4 oct32 = texture2D(packedClippingPlanes, vec2(u, v)) * 255.0;\n` +
      `    vec2 oct = vec2(oct32.x * 256.0 + oct32.y, oct32.z * 256.0 + oct32.w);\n` +
      `    vec4 plane;\n` +
      `    plane.xyz = czm_octDecode(oct, 65535.0);\n` +
      `    plane.w = czm_unpackFloat(texture2D(packedClippingPlanes, vec2(u + ${pixelWidthString}, v)));\n` +
      `    return czm_transformPlane(plane, transform);\n` +
      `}\n`;
    return functionString;
  }

  /**
   * @private
   */
  const JobType = {
    TEXTURE: 0,
    PROGRAM: 1,
    BUFFER: 2,
    NUMBER_OF_JOB_TYPES: 3,
  };
  var JobType$1 = Object.freeze(JobType);

  /**
   * @private
   */
  function ModelAnimationCache() {}

  const dataUriRegex = /^data\:/i;

  function getAccessorKey(model, accessor) {
    const gltf = model.gltfInternal;
    const buffers = gltf.buffers;
    const bufferViews = gltf.bufferViews;

    const bufferView = bufferViews[accessor.bufferView];
    const buffer = buffers[bufferView.buffer];

    const byteOffset = bufferView.byteOffset + accessor.byteOffset;
    const byteLength = accessor.count * numberOfComponentsForType(accessor.type);

    const uriKey = dataUriRegex.test(buffer.uri) ? "" : buffer.uri;
    return `${model.cacheKey}//${uriKey}/${byteOffset}/${byteLength}`;
  }

  const cachedAnimationParameters = {};

  ModelAnimationCache.getAnimationParameterValues = function (model, accessor) {
    const key = getAccessorKey(model, accessor);
    let values = cachedAnimationParameters[key];

    if (!defined(values)) {
      // Cache miss
      const gltf = model.gltfInternal;

      const buffers = gltf.buffers;
      const bufferViews = gltf.bufferViews;

      const bufferView = bufferViews[accessor.bufferView];
      const bufferId = bufferView.buffer;
      const buffer = buffers[bufferId];
      const source = buffer.extras._pipeline.source;

      const componentType = accessor.componentType;
      const type = accessor.type;
      const numberOfComponents = numberOfComponentsForType(type);
      const count = accessor.count;
      const byteStride = getAccessorByteStride(gltf, accessor);

      values = new Array(count);
      const accessorByteOffset = defaultValue(accessor.byteOffset, 0);
      let byteOffset = bufferView.byteOffset + accessorByteOffset;
      for (let i = 0; i < count; i++) {
        const typedArrayView = ComponentDatatype$1.createArrayBufferView(
          componentType,
          source.buffer,
          source.byteOffset + byteOffset,
          numberOfComponents
        );
        if (type === "SCALAR") {
          values[i] = typedArrayView[0];
        } else if (type === "VEC3") {
          values[i] = Cartesian3.fromArray(typedArrayView);
        } else if (type === "VEC4") {
          values[i] = Quaternion.unpack(typedArrayView);
        }
        byteOffset += byteStride;
      }
      // GLTF_SPEC: Support more parameter types when glTF supports targeting materials. https://github.com/KhronosGroup/glTF/issues/142

      if (defined(model.cacheKey)) {
        // Only cache when we can create a unique id
        cachedAnimationParameters[key] = values;
      }
    }

    return values;
  };

  const cachedAnimationSplines = {};

  function getAnimationSplineKey(model, animationName, samplerName) {
    return `${model.cacheKey}//${animationName}/${samplerName}`;
  }

  function SteppedSpline(backingSpline) {
    this._spline = backingSpline;
    this._lastTimeIndex = 0;
  }
  SteppedSpline.prototype.findTimeInterval = Spline.prototype.findTimeInterval;
  SteppedSpline.prototype.evaluate = function (time, result) {
    const i = (this._lastTimeIndex = this.findTimeInterval(
      time,
      this._lastTimeIndex
    ));
    const times = this._spline.times;
    const steppedTime = time >= times[i + 1] ? times[i + 1] : times[i];
    return this._spline.evaluate(steppedTime, result);
  };
  Object.defineProperties(SteppedSpline.prototype, {
    times: {
      get: function () {
        return this._spline.times;
      },
    },
  });
  SteppedSpline.prototype.wrapTime = function (time) {
    return this._spline.wrapTime(time);
  };
  SteppedSpline.prototype.clampTime = function (time) {
    return this._spline.clampTime(time);
  };

  ModelAnimationCache.getAnimationSpline = function (
    model,
    animationName,
    animation,
    samplerName,
    sampler,
    input,
    path,
    output
  ) {
    const key = getAnimationSplineKey(model, animationName, samplerName);
    let spline = cachedAnimationSplines[key];

    if (!defined(spline)) {
      const times = input;
      const controlPoints = output;

      if (times.length === 1 && controlPoints.length === 1) {
        spline = new ConstantSpline(controlPoints[0]);
      } else if (
        sampler.interpolation === "LINEAR" ||
        sampler.interpolation === "STEP"
      ) {
        if (path === "translation" || path === "scale") {
          spline = new LinearSpline({
            times: times,
            points: controlPoints,
          });
        } else if (path === "rotation") {
          spline = new QuaternionSpline({
            times: times,
            points: controlPoints,
          });
        } else if (path === "weights") {
          spline = new MorphWeightSpline({
            times: times,
            weights: controlPoints,
          });
        }

        if (defined(spline) && sampler.interpolation === "STEP") {
          spline = new SteppedSpline(spline);
        }
      }

      if (defined(model.cacheKey)) {
        // Only cache when we can create a unique id
        cachedAnimationSplines[key] = spline;
      }
    }

    return spline;
  };

  const cachedSkinInverseBindMatrices = {};

  ModelAnimationCache.getSkinInverseBindMatrices = function (model, accessor) {
    const key = getAccessorKey(model, accessor);
    let matrices = cachedSkinInverseBindMatrices[key];

    if (!defined(matrices)) {
      // Cache miss
      const gltf = model.gltfInternal;
      const buffers = gltf.buffers;
      const bufferViews = gltf.bufferViews;

      const bufferViewId = accessor.bufferView;
      const bufferView = bufferViews[bufferViewId];
      const bufferId = bufferView.buffer;
      const buffer = buffers[bufferId];
      const source = buffer.extras._pipeline.source;

      const componentType = accessor.componentType;
      const type = accessor.type;
      const count = accessor.count;
      const byteStride = getAccessorByteStride(gltf, accessor);
      let byteOffset = bufferView.byteOffset + accessor.byteOffset;
      const numberOfComponents = numberOfComponentsForType(type);

      matrices = new Array(count);

      if (componentType === WebGLConstants$1.FLOAT && type === AttributeType$1.MAT4) {
        for (let i = 0; i < count; ++i) {
          const typedArrayView = ComponentDatatype$1.createArrayBufferView(
            componentType,
            source.buffer,
            source.byteOffset + byteOffset,
            numberOfComponents
          );
          matrices[i] = Matrix4.fromArray(typedArrayView);
          byteOffset += byteStride;
        }
      }

      cachedSkinInverseBindMatrices[key] = matrices;
    }

    return matrices;
  };

  /**
   * Determines if and how a glTF animation is looped.
   *
   * @enum {Number}
   *
   * @see ModelAnimationCollection#add
   */
  const ModelAnimationLoop = {
    /**
     * Play the animation once; do not loop it.
     *
     * @type {Number}
     * @constant
     */
    NONE: 0,

    /**
     * Loop the animation playing it from the start immediately after it stops.
     *
     * @type {Number}
     * @constant
     */
    REPEAT: 1,

    /**
     * Loop the animation.  First, playing it forward, then in reverse, then forward, and so on.
     *
     * @type {Number}
     * @constant
     */
    MIRRORED_REPEAT: 2,
  };
  var ModelAnimationLoop$1 = Object.freeze(ModelAnimationLoop);

  /**
   * @private
   */
  var ModelAnimationState = Object.freeze({
    STOPPED: 0,
    ANIMATING: 1,
  });

  /**
   * An active glTF animation.  A glTF asset can contain animations.  An active animation
   * is an animation that is currently playing or scheduled to be played because it was
   * added to a model's {@link ModelAnimationCollection}.  An active animation is an
   * instance of an animation; for example, there can be multiple active animations
   * for the same glTF animation, each with a different start time.
   * <p>
   * Create this by calling {@link ModelAnimationCollection#add}.
   * </p>
   *
   * @alias ModelAnimation
   * @internalConstructor
   * @class
   *
   * @see ModelAnimationCollection#add
   */
  function ModelAnimation(options, model, runtimeAnimation) {
    this._name = runtimeAnimation.name;
    this._startTime = JulianDate.clone(options.startTime);
    this._delay = defaultValue(options.delay, 0.0); // in seconds
    this._stopTime = options.stopTime;

    /**
     * When <code>true</code>, the animation is removed after it stops playing.
     * This is slightly more efficient that not removing it, but if, for example,
     * time is reversed, the animation is not played again.
     *
     * @type {Boolean}
     * @default false
     */
    this.removeOnStop = defaultValue(options.removeOnStop, false);
    this._multiplier = defaultValue(options.multiplier, 1.0);
    this._reverse = defaultValue(options.reverse, false);
    this._loop = defaultValue(options.loop, ModelAnimationLoop$1.NONE);
    this._animationTime = options.animationTime;
    this._prevAnimationDelta = undefined;

    /**
     * The event fired when this animation is started.  This can be used, for
     * example, to play a sound or start a particle system, when the animation starts.
     * <p>
     * This event is fired at the end of the frame after the scene is rendered.
     * </p>
     *
     * @type {Event}
     * @default new Event()
     *
     * @example
     * animation.start.addEventListener(function(model, animation) {
     *   console.log(`Animation started: ${animation.name}`);
     * });
     */
    this.start = new Event();

    /**
     * The event fired when on each frame when this animation is updated.  The
     * current time of the animation, relative to the glTF animation time span, is
     * passed to the event, which allows, for example, starting new animations at a
     * specific time relative to a playing animation.
     * <p>
     * This event is fired at the end of the frame after the scene is rendered.
     * </p>
     *
     * @type {Event}
     * @default new Event()
     *
     * @example
     * animation.update.addEventListener(function(model, animation, time) {
     *   console.log(`Animation updated: ${animation.name}. glTF animation time: ${time}`);
     * });
     */
    this.update = new Event();

    /**
     * The event fired when this animation is stopped.  This can be used, for
     * example, to play a sound or start a particle system, when the animation stops.
     * <p>
     * This event is fired at the end of the frame after the scene is rendered.
     * </p>
     *
     * @type {Event}
     * @default new Event()
     *
     * @example
     * animation.stop.addEventListener(function(model, animation) {
     *   console.log(`Animation stopped: ${animation.name}`);
     * });
     */
    this.stop = new Event();

    this._state = ModelAnimationState.STOPPED;
    this._runtimeAnimation = runtimeAnimation;

    // Set during animation update
    this._computedStartTime = undefined;
    this._duration = undefined;

    // To avoid allocations in ModelAnimationCollection.update
    const that = this;
    this._raiseStartEvent = function () {
      that.start.raiseEvent(model, that);
    };
    this._updateEventTime = 0.0;
    this._raiseUpdateEvent = function () {
      that.update.raiseEvent(model, that, that._updateEventTime);
    };
    this._raiseStopEvent = function () {
      that.stop.raiseEvent(model, that);
    };
  }

  Object.defineProperties(ModelAnimation.prototype, {
    /**
     * The glTF animation name that identifies this animation.
     *
     * @memberof ModelAnimation.prototype
     *
     * @type {String}
     * @readonly
     */
    name: {
      get: function () {
        return this._name;
      },
    },

    /**
     * The scene time to start playing this animation.  When this is <code>undefined</code>,
     * the animation starts at the next frame.
     *
     * @memberof ModelAnimation.prototype
     *
     * @type {JulianDate}
     * @readonly
     *
     * @default undefined
     */
    startTime: {
      get: function () {
        return this._startTime;
      },
    },

    /**
     * The delay, in seconds, from {@link ModelAnimation#startTime} to start playing.
     *
     * @memberof ModelAnimation.prototype
     *
     * @type {Number}
     * @readonly
     *
     * @default undefined
     */
    delay: {
      get: function () {
        return this._delay;
      },
    },

    /**
     * The scene time to stop playing this animation.  When this is <code>undefined</code>,
     * the animation is played for its full duration and perhaps repeated depending on
     * {@link ModelAnimation#loop}.
     *
     * @memberof ModelAnimation.prototype
     *
     * @type {JulianDate}
     * @readonly
     *
     * @default undefined
     */
    stopTime: {
      get: function () {
        return this._stopTime;
      },
    },
    /**
     * Values greater than <code>1.0</code> increase the speed that the animation is played relative
     * to the scene clock speed; values less than <code>1.0</code> decrease the speed.  A value of
     * <code>1.0</code> plays the animation at the speed in the glTF animation mapped to the scene
     * clock speed.  For example, if the scene is played at 2x real-time, a two-second glTF animation
     * will play in one second even if <code>multiplier</code> is <code>1.0</code>.
     *
     * @memberof ModelAnimation.prototype
     *
     * @type {Number}
     * @readonly
     *
     * @default 1.0
     */
    multiplier: {
      get: function () {
        return this._multiplier;
      },
    },

    /**
     * When <code>true</code>, the animation is played in reverse.
     *
     * @memberof ModelAnimation.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default false
     */
    reverse: {
      get: function () {
        return this._reverse;
      },
    },

    /**
     * Determines if and how the animation is looped.
     *
     * @memberof ModelAnimation.prototype
     *
     * @type {ModelAnimationLoop}
     * @readonly
     *
     * @default {@link ModelAnimationLoop.NONE}
     */
    loop: {
      get: function () {
        return this._loop;
      },
    },

    /**
     * If this is defined, it will be used to compute the local animation time
     * instead of the scene's time.
     *
     * @memberof ModelAnimation.prototype
     *
     * @type {ModelAnimation.AnimationTimeCallback}
     * @default undefined
     */
    animationTime: {
      get: function () {
        return this._animationTime;
      },
    },
  });

  /**
   * A collection of active model animations.  Access this using {@link Model#activeAnimations}.
   *
   * @alias ModelAnimationCollection
   * @internalConstructor
   * @class
   *
   * @see Model#activeAnimations
   */
  function ModelAnimationCollection(model) {
    /**
     * The event fired when an animation is added to the collection.  This can be used, for
     * example, to keep a UI in sync.
     *
     * @type {Event}
     * @default new Event()
     *
     * @example
     * model.activeAnimations.animationAdded.addEventListener(function(model, animation) {
     *   console.log(`Animation added: ${animation.name}`);
     * });
     */
    this.animationAdded = new Event();

    /**
     * The event fired when an animation is removed from the collection.  This can be used, for
     * example, to keep a UI in sync.
     *
     * @type {Event}
     * @default new Event()
     *
     * @example
     * model.activeAnimations.animationRemoved.addEventListener(function(model, animation) {
     *   console.log(`Animation removed: ${animation.name}`);
     * });
     */
    this.animationRemoved = new Event();

    /**
     * When true, the animation will play even when the scene time is paused. However,
     * whether animation takes place will depend on the animationTime functions assigned
     * to the model's animations. By default, this is based on scene time, so models using
     * the default will not animate regardless of this setting.
     *
     * @type {Boolean}
     * @default false
     */
    this.animateWhilePaused = false;

    this._model = model;
    this._scheduledAnimations = [];
    this._previousTime = undefined;
  }

  Object.defineProperties(ModelAnimationCollection.prototype, {
    /**
     * The number of animations in the collection.
     *
     * @memberof ModelAnimationCollection.prototype
     *
     * @type {Number}
     * @readonly
     */
    length: {
      get: function () {
        return this._scheduledAnimations.length;
      },
    },
  });

  function add(collection, index, options) {
    const model = collection._model;
    const animations = model._runtime.animations;
    const animation = animations[index];
    const scheduledAnimation = new ModelAnimation(options, model, animation);
    collection._scheduledAnimations.push(scheduledAnimation);
    collection.animationAdded.raiseEvent(model, scheduledAnimation);
    return scheduledAnimation;
  }

  /**
   * Creates and adds an animation with the specified initial properties to the collection.
   * <p>
   * This raises the {@link ModelAnimationCollection#animationAdded} event so, for example, a UI can stay in sync.
   * </p>
   *
   * @param {Object} options Object with the following properties:
   * @param {String} [options.name] The glTF animation name that identifies the animation. Must be defined if <code>options.index</code> is <code>undefined</code>.
   * @param {Number} [options.index] The glTF animation index that identifies the animation. Must be defined if <code>options.name</code> is <code>undefined</code>.
   * @param {JulianDate} [options.startTime] The scene time to start playing the animation.  When this is <code>undefined</code>, the animation starts at the next frame.
   * @param {Number} [options.delay=0.0] The delay, in seconds, from <code>startTime</code> to start playing.
   * @param {JulianDate} [options.stopTime] The scene time to stop playing the animation.  When this is <code>undefined</code>, the animation is played for its full duration.
   * @param {Boolean} [options.removeOnStop=false] When <code>true</code>, the animation is removed after it stops playing.
   * @param {Number} [options.multiplier=1.0] Values greater than <code>1.0</code> increase the speed that the animation is played relative to the scene clock speed; values less than <code>1.0</code> decrease the speed.
   * @param {Boolean} [options.reverse=false] When <code>true</code>, the animation is played in reverse.
   * @param {ModelAnimationLoop} [options.loop=ModelAnimationLoop.NONE] Determines if and how the animation is looped.
   * @param {ModelAnimation.AnimationTimeCallback} [options.animationTime=undefined] If defined, computes the local animation time for this animation.
   * @returns {ModelAnimation} The animation that was added to the collection.
   *
   * @exception {DeveloperError} Animations are not loaded.  Wait for the {@link Model#readyPromise} to resolve.
   * @exception {DeveloperError} options.name must be a valid animation name.
   * @exception {DeveloperError} options.index must be a valid animation index.
   * @exception {DeveloperError} Either options.name or options.index must be defined.
   * @exception {DeveloperError} options.multiplier must be greater than zero.
   *
   * @example
   * // Example 1. Add an animation by name
   * model.activeAnimations.add({
   *   name : 'animation name'
   * });
   *
   * // Example 2. Add an animation by index
   * model.activeAnimations.add({
   *   index : 0
   * });
   *
   * @example
   * // Example 3. Add an animation and provide all properties and events
   * const startTime = Cesium.JulianDate.now();
   *
   * const animation = model.activeAnimations.add({
   *   name : 'another animation name',
   *   startTime : startTime,
   *   delay : 0.0,                          // Play at startTime (default)
   *   stopTime : Cesium.JulianDate.addSeconds(startTime, 4.0, new Cesium.JulianDate()),
   *   removeOnStop : false,                 // Do not remove when animation stops (default)
   *   multiplier : 2.0,                        // Play at double speed
   *   reverse : true,                       // Play in reverse
   *   loop : Cesium.ModelAnimationLoop.REPEAT      // Loop the animation
   * });
   *
   * animation.start.addEventListener(function(model, animation) {
   *   console.log(`Animation started: ${animation.name}`);
   * });
   * animation.update.addEventListener(function(model, animation, time) {
   *   console.log(`Animation updated:  ${animation.name}. glTF animation time: ${time}`);
   * });
   * animation.stop.addEventListener(function(model, animation) {
   *   console.log(`Animation stopped: ${animation.name}`);
   * });
   */
  ModelAnimationCollection.prototype.add = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const model = this._model;
    const animations = model._runtime.animations;

    //>>includeStart('debug', pragmas.debug);
    if (!defined(animations)) {
      throw new DeveloperError(
        "Animations are not loaded.  Wait for Model.readyPromise to resolve."
      );
    }
    if (!defined(options.name) && !defined(options.index)) {
      throw new DeveloperError(
        "Either options.name or options.index must be defined."
      );
    }

    if (defined(options.multiplier) && options.multiplier <= 0.0) {
      throw new DeveloperError("options.multiplier must be greater than zero.");
    }
    if (
      defined(options.index) &&
      (options.index >= animations.length || options.index < 0)
    ) {
      throw new DeveloperError("options.index must be a valid animation index.");
    }
    //>>includeEnd('debug');

    if (defined(options.index)) {
      return add(this, options.index, options);
    }

    // Find the index of the animation with the given name
    let index;
    const length = animations.length;
    for (let i = 0; i < length; ++i) {
      if (animations[i].name === options.name) {
        index = i;
        break;
      }
    }

    //>>includeStart('debug', pragmas.debug);
    if (!defined(index)) {
      throw new DeveloperError("options.name must be a valid animation name.");
    }
    //>>includeEnd('debug');

    return add(this, index, options);
  };

  /**
   * Creates and adds an animation with the specified initial properties to the collection
   * for each animation in the model.
   * <p>
   * This raises the {@link ModelAnimationCollection#animationAdded} event for each model so, for example, a UI can stay in sync.
   * </p>
   *
   * @param {Object} [options] Object with the following properties:
   * @param {JulianDate} [options.startTime] The scene time to start playing the animations.  When this is <code>undefined</code>, the animations starts at the next frame.
   * @param {Number} [options.delay=0.0] The delay, in seconds, from <code>startTime</code> to start playing.
   * @param {JulianDate} [options.stopTime] The scene time to stop playing the animations.  When this is <code>undefined</code>, the animations are played for its full duration.
   * @param {Boolean} [options.removeOnStop=false] When <code>true</code>, the animations are removed after they stop playing.
   * @param {Number} [options.multiplier=1.0] Values greater than <code>1.0</code> increase the speed that the animations play relative to the scene clock speed; values less than <code>1.0</code> decrease the speed.
   * @param {Boolean} [options.reverse=false] When <code>true</code>, the animations are played in reverse.
   * @param {ModelAnimationLoop} [options.loop=ModelAnimationLoop.NONE] Determines if and how the animations are looped.
   * @param {ModelAnimation.AnimationTimeCallback} [options.animationTime=undefined] If defined, computes the local animation time for all of the animations.
   * @returns {ModelAnimation[]} An array of {@link ModelAnimation} objects, one for each animation added to the collection.  If there are no glTF animations, the array is empty.
   *
   * @exception {DeveloperError} Animations are not loaded.  Wait for the {@link Model#readyPromise} to resolve.
   * @exception {DeveloperError} options.multiplier must be greater than zero.
   *
   * @example
   * model.activeAnimations.addAll({
   *   multiplier : 0.5,                        // Play at half-speed
   *   loop : Cesium.ModelAnimationLoop.REPEAT      // Loop the animations
   * });
   */
  ModelAnimationCollection.prototype.addAll = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    if (!defined(this._model._runtime.animations)) {
      throw new DeveloperError(
        "Animations are not loaded.  Wait for Model.readyPromise to resolve."
      );
    }

    if (defined(options.multiplier) && options.multiplier <= 0.0) {
      throw new DeveloperError("options.multiplier must be greater than zero.");
    }
    //>>includeEnd('debug');

    const scheduledAnimations = [];
    const model = this._model;
    const animations = model._runtime.animations;
    const length = animations.length;
    for (let i = 0; i < length; ++i) {
      scheduledAnimations.push(add(this, i, options));
    }
    return scheduledAnimations;
  };

  /**
   * Removes an animation from the collection.
   * <p>
   * This raises the {@link ModelAnimationCollection#animationRemoved} event so, for example, a UI can stay in sync.
   * </p>
   * <p>
   * An animation can also be implicitly removed from the collection by setting {@link ModelAnimation#removeOnStop} to
   * <code>true</code>.  The {@link ModelAnimationCollection#animationRemoved} event is still fired when the animation is removed.
   * </p>
   *
   * @param {ModelAnimation} animation The animation to remove.
   * @returns {Boolean} <code>true</code> if the animation was removed; <code>false</code> if the animation was not found in the collection.
   *
   * @example
   * const a = model.activeAnimations.add({
   *   name : 'animation name'
   * });
   * model.activeAnimations.remove(a); // Returns true
   */
  ModelAnimationCollection.prototype.remove = function (animation) {
    if (defined(animation)) {
      const animations = this._scheduledAnimations;
      const i = animations.indexOf(animation);
      if (i !== -1) {
        animations.splice(i, 1);
        this.animationRemoved.raiseEvent(this._model, animation);
        return true;
      }
    }

    return false;
  };

  /**
   * Removes all animations from the collection.
   * <p>
   * This raises the {@link ModelAnimationCollection#animationRemoved} event for each
   * animation so, for example, a UI can stay in sync.
   * </p>
   */
  ModelAnimationCollection.prototype.removeAll = function () {
    const model = this._model;
    const animations = this._scheduledAnimations;
    const length = animations.length;

    this._scheduledAnimations = [];

    for (let i = 0; i < length; ++i) {
      this.animationRemoved.raiseEvent(model, animations[i]);
    }
  };

  /**
   * Determines whether this collection contains a given animation.
   *
   * @param {ModelAnimation} animation The animation to check for.
   * @returns {Boolean} <code>true</code> if this collection contains the animation, <code>false</code> otherwise.
   */
  ModelAnimationCollection.prototype.contains = function (animation) {
    if (defined(animation)) {
      return this._scheduledAnimations.indexOf(animation) !== -1;
    }

    return false;
  };

  /**
   * Returns the animation in the collection at the specified index.  Indices are zero-based
   * and increase as animations are added.  Removing an animation shifts all animations after
   * it to the left, changing their indices.  This function is commonly used to iterate over
   * all the animations in the collection.
   *
   * @param {Number} index The zero-based index of the animation.
   * @returns {ModelAnimation} The animation at the specified index.
   *
   * @example
   * // Output the names of all the animations in the collection.
   * const animations = model.activeAnimations;
   * const length = animations.length;
   * for (let i = 0; i < length; ++i) {
   *   console.log(animations.get(i).name);
   * }
   */
  ModelAnimationCollection.prototype.get = function (index) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(index)) {
      throw new DeveloperError("index is required.");
    }
    //>>includeEnd('debug');

    return this._scheduledAnimations[index];
  };

  function animateChannels(runtimeAnimation, localAnimationTime) {
    const channelEvaluators = runtimeAnimation.channelEvaluators;
    const length = channelEvaluators.length;
    for (let i = 0; i < length; ++i) {
      channelEvaluators[i](localAnimationTime);
    }
  }

  const animationsToRemove$1 = [];

  function createAnimationRemovedFunction$1(
    modelAnimationCollection,
    model,
    animation
  ) {
    return function () {
      modelAnimationCollection.animationRemoved.raiseEvent(model, animation);
    };
  }

  /**
   * @private
   */
  ModelAnimationCollection.prototype.update = function (frameState) {
    const scheduledAnimations = this._scheduledAnimations;
    let length = scheduledAnimations.length;

    if (length === 0) {
      // No animations - quick return for performance
      this._previousTime = undefined;
      return false;
    }

    if (
      !this.animateWhilePaused &&
      JulianDate.equals(frameState.time, this._previousTime)
    ) {
      return false;
    }
    this._previousTime = JulianDate.clone(frameState.time, this._previousTime);

    let animationOccured = false;
    const sceneTime = frameState.time;
    const model = this._model;

    for (let i = 0; i < length; ++i) {
      const scheduledAnimation = scheduledAnimations[i];
      const runtimeAnimation = scheduledAnimation._runtimeAnimation;

      if (!defined(scheduledAnimation._computedStartTime)) {
        scheduledAnimation._computedStartTime = JulianDate.addSeconds(
          defaultValue(scheduledAnimation.startTime, sceneTime),
          scheduledAnimation.delay,
          new JulianDate()
        );
      }

      if (!defined(scheduledAnimation._duration)) {
        scheduledAnimation._duration =
          runtimeAnimation.stopTime * (1.0 / scheduledAnimation.multiplier);
      }

      const startTime = scheduledAnimation._computedStartTime;
      const duration = scheduledAnimation._duration;
      const stopTime = scheduledAnimation.stopTime;

      const pastStartTime = JulianDate.lessThanOrEquals(startTime, sceneTime);
      const pastStopTime =
        defined(stopTime) && JulianDate.greaterThan(sceneTime, stopTime);

      // [0.0, 1.0] normalized local animation time
      let delta = 0.0;
      if (duration !== 0.0) {
        const seconds = JulianDate.secondsDifference(
          pastStopTime ? stopTime : sceneTime,
          startTime
        );
        delta = defined(scheduledAnimation._animationTime)
          ? scheduledAnimation._animationTime(duration, seconds)
          : seconds / duration;
      }

      // Play animation if
      // * we are after the start time or the animation is being repeated, and
      // * before the end of the animation's duration or the animation is being repeated, and
      // * we did not reach a user-provided stop time.

      const repeat =
        scheduledAnimation.loop === ModelAnimationLoop$1.REPEAT ||
        scheduledAnimation.loop === ModelAnimationLoop$1.MIRRORED_REPEAT;

      const play =
        (pastStartTime || (repeat && !defined(scheduledAnimation.startTime))) &&
        (delta <= 1.0 || repeat) &&
        !pastStopTime;

      if (delta === scheduledAnimation._prevAnimationDelta) {
        const animationStopped =
          scheduledAnimation._state === ModelAnimationState.STOPPED;
        // no change to delta, and no change to the animation state means we can
        // skip the update this time around.
        if (play !== animationStopped) {
          continue;
        }
      }
      scheduledAnimation._prevAnimationDelta = delta;

      // If it IS, or WAS, animating...
      if (play || scheduledAnimation._state === ModelAnimationState.ANIMATING) {
        // STOPPED -> ANIMATING state transition?
        if (play && scheduledAnimation._state === ModelAnimationState.STOPPED) {
          scheduledAnimation._state = ModelAnimationState.ANIMATING;
          if (scheduledAnimation.start.numberOfListeners > 0) {
            frameState.afterRender.push(scheduledAnimation._raiseStartEvent);
          }
        }

        // Truncate to [0.0, 1.0] for repeating animations
        if (scheduledAnimation.loop === ModelAnimationLoop$1.REPEAT) {
          delta = delta - Math.floor(delta);
        } else if (
          scheduledAnimation.loop === ModelAnimationLoop$1.MIRRORED_REPEAT
        ) {
          const floor = Math.floor(delta);
          const fract = delta - floor;
          // When odd use (1.0 - fract) to mirror repeat
          delta = floor % 2 === 1.0 ? 1.0 - fract : fract;
        }

        if (scheduledAnimation.reverse) {
          delta = 1.0 - delta;
        }

        let localAnimationTime = delta * duration * scheduledAnimation.multiplier;
        // Clamp in case floating-point roundoff goes outside the animation's first or last keyframe
        localAnimationTime = CesiumMath.clamp(
          localAnimationTime,
          runtimeAnimation.startTime,
          runtimeAnimation.stopTime
        );

        animateChannels(runtimeAnimation, localAnimationTime);

        if (scheduledAnimation.update.numberOfListeners > 0) {
          scheduledAnimation._updateEventTime = localAnimationTime;
          frameState.afterRender.push(scheduledAnimation._raiseUpdateEvent);
        }
        animationOccured = true;

        if (!play) {
          // ANIMATING -> STOPPED state transition?
          scheduledAnimation._state = ModelAnimationState.STOPPED;
          if (scheduledAnimation.stop.numberOfListeners > 0) {
            frameState.afterRender.push(scheduledAnimation._raiseStopEvent);
          }

          if (scheduledAnimation.removeOnStop) {
            animationsToRemove$1.push(scheduledAnimation);
          }
        }
      }
    }

    // Remove animations that stopped
    length = animationsToRemove$1.length;
    for (let j = 0; j < length; ++j) {
      const animationToRemove = animationsToRemove$1[j];
      scheduledAnimations.splice(
        scheduledAnimations.indexOf(animationToRemove),
        1
      );
      frameState.afterRender.push(
        createAnimationRemovedFunction$1(this, model, animationToRemove)
      );
    }
    animationsToRemove$1.length = 0;

    return animationOccured;
  };

  /**
   * A model's material with modifiable parameters.  A glTF material
   * contains parameters defined by the material's technique with values
   * defined by the technique and potentially overridden by the material.
   * This class allows changing these values at runtime.
   * <p>
   * Use {@link Model#getMaterial} to create an instance.
   * </p>
   *
   * @alias ModelMaterial
   * @internalConstructor
   * @class
   *
   * @see Model#getMaterial
   */
  function ModelMaterial(model, material, id) {
    this._name = material.name;
    this._id = id;
    this._uniformMap = model._uniformMaps[id];

    this._technique = undefined;
    this._program = undefined;
    this._values = undefined;
  }

  Object.defineProperties(ModelMaterial.prototype, {
    /**
     * The value of the <code>name</code> property of this material.
     *
     * @memberof ModelMaterial.prototype
     *
     * @type {String}
     * @readonly
     */
    name: {
      get: function () {
        return this._name;
      },
    },

    /**
     * The index of the material.
     *
     * @memberof ModelMaterial.prototype
     *
     * @type {String}
     * @readonly
     */
    id: {
      get: function () {
        return this._id;
      },
    },
  });

  /**
   * Assigns a value to a material parameter.  The type for <code>value</code>
   * depends on the glTF type of the parameter.  It will be a floating-point
   * number, Cartesian, or matrix.
   *
   * @param {String} name The name of the parameter.
   * @param {*} [value] The value to assign to the parameter.
   *
   * @exception {DeveloperError} name must match a parameter name in the material's technique that is targetable and not optimized out.
   *
   * @example
   * material.setValue('diffuse', new Cesium.Cartesian4(1.0, 0.0, 0.0, 1.0));  // vec4
   * material.setValue('shininess', 256.0); // scalar
   */
  ModelMaterial.prototype.setValue = function (name, value) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(name)) {
      throw new DeveloperError("name is required.");
    }
    //>>includeEnd('debug');

    const uniformName = `u_${name}`;
    const v = this._uniformMap.values[uniformName];

    //>>includeStart('debug', pragmas.debug);
    if (!defined(v)) {
      throw new DeveloperError(
        "name must match a parameter name in the material's technique that is targetable and not optimized out."
      );
    }
    //>>includeEnd('debug');

    v.value = v.clone(value, v.value);
  };

  /**
   * Returns the value of the parameter with the given <code>name</code>.  The type of the
   * returned object depends on the glTF type of the parameter.  It will be a floating-point
   * number, Cartesian, or matrix.
   *
   * @param {String} name The name of the parameter.
   * @returns {*} The value of the parameter or <code>undefined</code> if the parameter does not exist.
   */
  ModelMaterial.prototype.getValue = function (name) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(name)) {
      throw new DeveloperError("name is required.");
    }
    //>>includeEnd('debug');

    const uniformName = `u_${name}`;
    const v = this._uniformMap.values[uniformName];

    if (!defined(v)) {
      return undefined;
    }

    return v.value;
  };

  /**
   * A model's mesh and its materials.
   * <p>
   * Use {@link Model#getMesh} to create an instance.
   * </p>
   *
   * @alias ModelMesh
   * @internalConstructor
   * @class
   *
   * @see Model#getMesh
   */
  function ModelMesh(mesh, runtimeMaterialsById, id) {
    const materials = [];
    const primitives = mesh.primitives;
    const length = primitives.length;
    for (let i = 0; i < length; ++i) {
      const p = primitives[i];
      materials[i] = runtimeMaterialsById[p.material];
    }

    this._name = mesh.name;
    this._materials = materials;
    this._id = id;
  }

  Object.defineProperties(ModelMesh.prototype, {
    /**
     * The value of the <code>name</code> property of this mesh.
     *
     * @memberof ModelMesh.prototype
     *
     * @type {String}
     * @readonly
     */
    name: {
      get: function () {
        return this._name;
      },
    },

    /**
     * The index of the mesh.
     *
     * @memberof ModelMesh.prototype
     *
     * @type {String}
     * @readonly
     */
    id: {
      get: function () {
        return this._id;
      },
    },

    /**
     * An array of {@link ModelMaterial} instances indexed by the mesh's
     * primitive indices.
     *
     * @memberof ModelMesh.prototype
     *
     * @type {ModelMaterial[]}
     * @readonly
     */
    materials: {
      get: function () {
        return this._materials;
      },
    },
  });

  /**
   * A model node with a transform for user-defined animations.  A glTF asset can
   * contain animations that target a node's transform.  This class allows
   * changing a node's transform externally so animation can be driven by another
   * source, not just an animation in the glTF asset.
   * <p>
   * Use {@link Model#getNode} to create an instance.
   * </p>
   *
   * @alias ModelNode
   * @internalConstructor
   * @class
   *
   * @example
   * const node = model.getNode('LOD3sp');
   * node.matrix = Cesium.Matrix4.fromScale(new Cesium.Cartesian3(5.0, 1.0, 1.0), node.matrix);
   *
   * @see Model#getNode
   */
  function ModelNode(model, node, runtimeNode, id, matrix) {
    this._model = model;
    this._runtimeNode = runtimeNode;
    this._name = node.name;
    this._id = id;

    /**
     * @private
     */
    this.useMatrix = false;

    this._show = true;
    this._matrix = Matrix4.clone(matrix);
    this._originalMatrix = Matrix4.clone(matrix);
  }

  Object.defineProperties(ModelNode.prototype, {
    /**
     * The value of the <code>name</code> property of this node.
     *
     * @memberof ModelNode.prototype
     *
     * @type {String}
     * @readonly
     */
    name: {
      get: function () {
        return this._name;
      },
    },

    /**
     * The index of the node.
     *
     * @memberof ModelNode.prototype
     *
     * @type {String}
     * @readonly
     */
    id: {
      get: function () {
        return this._id;
      },
    },

    /**
     * Determines if this node and its children will be shown.
     *
     * @memberof ModelNode.prototype
     * @type {Boolean}
     *
     * @default true
     */
    show: {
      get: function () {
        return this._show;
      },
      set: function (value) {
        if (this._show !== value) {
          this._show = value;
          this._model._perNodeShowDirty = true;
        }
      },
    },

    /**
     * The node's 4x4 matrix transform from its local coordinates to
     * its parent's.
     * <p>
     * For changes to take effect, this property must be assigned to;
     * setting individual elements of the matrix will not work.
     * </p>
     *
     * @memberof ModelNode.prototype
     * @type {Matrix4}
     */
    matrix: {
      get: function () {
        return this._matrix;
      },
      set: function (value) {
        this._matrix = Matrix4.clone(value, this._matrix);
        this.useMatrix = true;

        const model = this._model;
        model._cesiumAnimationsDirty = true;
        this._runtimeNode.dirtyNumber = model._maxDirtyNumber;
      },
    },

    /**
     * Gets the node's original 4x4 matrix transform from its local coordinates to
     * its parent's, without any node transformations or articulations applied.
     *
     * @memberof ModelNode.prototype
     * @type {Matrix4}
     */
    originalMatrix: {
      get: function () {
        return this._originalMatrix;
      },
    },
  });

  /**
   * @private
   */
  ModelNode.prototype.setMatrix = function (matrix) {
    // Update matrix but do not set the dirty flag since this is used internally
    // to keep the matrix in-sync during a glTF animation.
    Matrix4.clone(matrix, this._matrix);
  };

  // glTF does not allow an index value of 65535 because this is the primitive
  // restart value in some APIs.
  const MAX_GLTF_UINT16_INDEX = 65534;

  /**
   * Creates face outlines for glTF primitives with the `CESIUM_primitive_outline` extension.
   * @private
   */
  function ModelOutlineLoader() {}

  /**
   * Returns true if the model uses or requires CESIUM_primitive_outline.
   * @private
   */
  ModelOutlineLoader.hasExtension = function (model) {
    return (
      defined(model.extensionsRequired.CESIUM_primitive_outline) ||
      defined(model.extensionsUsed.CESIUM_primitive_outline)
    );
  };

  /**
   * Arranges to outline any primitives with the CESIUM_primitive_outline extension.
   * It is expected that all buffer data is loaded and available in
   * `extras._pipeline.source` before this function is called, and that vertex
   * and index WebGL buffers are not yet created.
   * @private
   */
  ModelOutlineLoader.outlinePrimitives = function (model) {
    if (!ModelOutlineLoader.hasExtension(model)) {
      return;
    }

    const gltf = model.gltfInternal;

    // Assumption: A single bufferView contains a single zero-indexed range of vertices.
    // No trickery with using large accessor byteOffsets to store multiple zero-based
    // ranges of vertices in a single bufferView. Use separate bufferViews for that,
    // you monster.
    // Note that interleaved vertex attributes (e.g. position0, normal0, uv0,
    // position1, normal1, uv1, ...) _are_ supported and should not be confused with
    // the above.

    const vertexNumberingScopes = [];

    ForEach.mesh(gltf, function (mesh, meshId) {
      ForEach.meshPrimitive(mesh, function (primitive, primitiveId) {
        if (!defined(primitive.extensions)) {
          return;
        }

        const outlineData = primitive.extensions.CESIUM_primitive_outline;
        if (!defined(outlineData)) {
          return;
        }

        const vertexNumberingScope = getVertexNumberingScope(model, primitive);
        if (vertexNumberingScope === undefined) {
          return;
        }

        if (vertexNumberingScopes.indexOf(vertexNumberingScope) < 0) {
          vertexNumberingScopes.push(vertexNumberingScope);
        }

        // Add the outline to this primitive
        addOutline(
          model,
          meshId,
          primitiveId,
          outlineData.indices,
          vertexNumberingScope
        );
      });
    });

    // Update all relevant bufferViews to include the duplicate vertices that are
    // needed for outlining.
    for (let i = 0; i < vertexNumberingScopes.length; ++i) {
      updateBufferViewsWithNewVertices(
        model,
        vertexNumberingScopes[i].bufferViews
      );
    }

    // Remove data not referenced by any bufferViews anymore.
    compactBuffers(model);
  };

  ModelOutlineLoader.createTexture = function (model, context) {
    let cache = context.cache.modelOutliningCache;
    if (!defined(cache)) {
      cache = context.cache.modelOutliningCache = {};
    }

    if (defined(cache.outlineTexture)) {
      return cache.outlineTexture;
    }

    const maxSize = Math.min(4096, ContextLimits.maximumTextureSize);

    let size = maxSize;
    const levelZero = createTexture$3(size);

    const mipLevels = [];

    while (size > 1) {
      size >>= 1;
      mipLevels.push(createTexture$3(size));
    }

    const texture = new Texture({
      context: context,
      source: {
        arrayBufferView: levelZero,
        mipLevels: mipLevels,
      },
      width: maxSize,
      height: 1,
      pixelFormat: PixelFormat$1.LUMINANCE,
      sampler: new Sampler({
        wrapS: TextureWrap$1.CLAMP_TO_EDGE,
        wrapT: TextureWrap$1.CLAMP_TO_EDGE,
        minificationFilter: TextureMinificationFilter$1.LINEAR_MIPMAP_LINEAR,
        magnificationFilter: TextureMagnificationFilter$1.LINEAR,
      }),
    });

    cache.outlineTexture = texture;

    return texture;
  };

  function addOutline(
    model,
    meshId,
    primitiveId,
    edgeIndicesAccessorId,
    vertexNumberingScope
  ) {
    const vertexCopies = vertexNumberingScope.vertexCopies;
    const extraVertices = vertexNumberingScope.extraVertices;
    const outlineCoordinates = vertexNumberingScope.outlineCoordinates;

    const gltf = model.gltfInternal;
    const mesh = gltf.meshes[meshId];
    const primitive = mesh.primitives[primitiveId];
    const accessors = gltf.accessors;
    const bufferViews = gltf.bufferViews;

    // Find the number of vertices in this primitive by looking at
    // the first attribute. Others are required to be the same.
    let numVertices;
    for (const semantic in primitive.attributes) {
      if (primitive.attributes.hasOwnProperty(semantic)) {
        const attributeId = primitive.attributes[semantic];
        const accessor = accessors[attributeId];
        if (defined(accessor)) {
          numVertices = accessor.count;
          break;
        }
      }
    }

    if (!defined(numVertices)) {
      return undefined;
    }

    const triangleIndexAccessorGltf = accessors[primitive.indices];
    const triangleIndexBufferViewGltf =
      bufferViews[triangleIndexAccessorGltf.bufferView];
    const edgeIndexAccessorGltf = accessors[edgeIndicesAccessorId];
    const edgeIndexBufferViewGltf = bufferViews[edgeIndexAccessorGltf.bufferView];

    const loadResources = model._loadResources;
    const triangleIndexBufferView = loadResources.getBuffer(
      triangleIndexBufferViewGltf
    );
    const edgeIndexBufferView = loadResources.getBuffer(edgeIndexBufferViewGltf);

    let triangleIndices =
      triangleIndexAccessorGltf.componentType === 5123
        ? new Uint16Array(
            triangleIndexBufferView.buffer,
            triangleIndexBufferView.byteOffset +
              triangleIndexAccessorGltf.byteOffset,
            triangleIndexAccessorGltf.count
          )
        : new Uint32Array(
            triangleIndexBufferView.buffer,
            triangleIndexBufferView.byteOffset +
              triangleIndexAccessorGltf.byteOffset,
            triangleIndexAccessorGltf.count
          );
    const edgeIndices =
      edgeIndexAccessorGltf.componentType === 5123
        ? new Uint16Array(
            edgeIndexBufferView.buffer,
            edgeIndexBufferView.byteOffset + edgeIndexAccessorGltf.byteOffset,
            edgeIndexAccessorGltf.count
          )
        : new Uint32Array(
            edgeIndexBufferView.buffer,
            edgeIndexBufferView.byteOffset + edgeIndexAccessorGltf.byteOffset,
            edgeIndexAccessorGltf.count
          );

    // Make a hash table for quick lookups of whether an edge exists between two
    // vertices. The hash is a sparse array indexed by
    //   `smallerVertexIndex * totalNumberOfVertices + biggerVertexIndex`
    // A value of 1 indicates an edge exists between the two vertex indices; any
    // other value indicates that it does not. We store the
    // `edgeSmallMultipler` - that is, the number of vertices in the equation
    // above - at index 0 for easy access to it later.

    const edgeSmallMultiplier = numVertices;

    const edges = [edgeSmallMultiplier];
    let i;
    for (i = 0; i < edgeIndices.length; i += 2) {
      const a = edgeIndices[i];
      const b = edgeIndices[i + 1];
      const small = Math.min(a, b);
      const big = Math.max(a, b);
      edges[small * edgeSmallMultiplier + big] = 1;
    }

    // For each triangle, adjust vertex data so that the correct edges are outlined.
    for (i = 0; i < triangleIndices.length; i += 3) {
      let i0 = triangleIndices[i];
      let i1 = triangleIndices[i + 1];
      let i2 = triangleIndices[i + 2];
      const has01 = isHighlighted(edges, i0, i1);
      const has12 = isHighlighted(edges, i1, i2);
      const has20 = isHighlighted(edges, i2, i0);

      let unmatchableVertexIndex = matchAndStoreCoordinates(
        outlineCoordinates,
        i0,
        i1,
        i2,
        has01,
        has12,
        has20
      );
      while (unmatchableVertexIndex >= 0) {
        // Copy the unmatchable index and try again.
        let copy;
        if (unmatchableVertexIndex === i0) {
          copy = vertexCopies[i0];
        } else if (unmatchableVertexIndex === i1) {
          copy = vertexCopies[i1];
        } else {
          copy = vertexCopies[i2];
        }

        if (copy === undefined) {
          copy = numVertices + extraVertices.length;

          let original = unmatchableVertexIndex;
          while (original >= numVertices) {
            original = extraVertices[original - numVertices];
          }
          extraVertices.push(original);
          vertexCopies[unmatchableVertexIndex] = copy;
        }

        if (
          copy > MAX_GLTF_UINT16_INDEX &&
          triangleIndices instanceof Uint16Array
        ) {
          // We outgrew a 16-bit index buffer, switch to 32-bit.
          triangleIndices = new Uint32Array(triangleIndices);
          triangleIndexAccessorGltf.componentType = 5125; // UNSIGNED_INT
          triangleIndexBufferViewGltf.buffer =
            gltf.buffers.push({
              byteLength: triangleIndices.byteLength,
              extras: {
                _pipeline: {
                  source: triangleIndices.buffer,
                },
              },
            }) - 1;
          triangleIndexBufferViewGltf.byteLength = triangleIndices.byteLength;
          triangleIndexBufferViewGltf.byteOffset = 0;
          model._loadResources.buffers[
            triangleIndexBufferViewGltf.buffer
          ] = new Uint8Array(
            triangleIndices.buffer,
            0,
            triangleIndices.byteLength
          );

          // The index componentType is also squirreled away in ModelLoadResources.
          // Hackily update it, or else we'll end up creating the wrong type
          // of index buffer later.
          loadResources.indexBuffersToCreate._array.forEach(function (toCreate) {
            if (toCreate.id === triangleIndexAccessorGltf.bufferView) {
              toCreate.componentType = triangleIndexAccessorGltf.componentType;
            }
          });
        }

        if (unmatchableVertexIndex === i0) {
          i0 = copy;
          triangleIndices[i] = copy;
        } else if (unmatchableVertexIndex === i1) {
          i1 = copy;
          triangleIndices[i + 1] = copy;
        } else {
          i2 = copy;
          triangleIndices[i + 2] = copy;
        }

        if (defined(triangleIndexAccessorGltf.max)) {
          triangleIndexAccessorGltf.max[0] = Math.max(
            triangleIndexAccessorGltf.max[0],
            copy
          );
        }

        unmatchableVertexIndex = matchAndStoreCoordinates(
          outlineCoordinates,
          i0,
          i1,
          i2,
          has01,
          has12,
          has20
        );
      }
    }
  }

  // Each vertex has three coordinates, a, b, and c.
  // a is the coordinate that applies to edge 2-0 for the vertex.
  // b is the coordinate that applies to edge 0-1 for the vertex.
  // c is the coordinate that applies to edge 1-2 for the vertex.

  // A single triangle with all edges highlighted:
  //
  //                 | a | b | c |
  //                 | 1 | 1 | 0 |
  //                       0
  //                      / \
  //                     /   \
  //           edge 0-1 /     \ edge 2-0
  //                   /       \
  //                  /         \
  // | a | b | c |   1-----------2   | a | b | c |
  // | 0 | 1 | 1 |     edge 1-2      | 1 | 0 | 1 |
  //
  // There are 6 possible orderings of coordinates a, b, and c:
  // 0 - abc
  // 1 - acb
  // 2 - bac
  // 3 - bca
  // 4 - cab
  // 5 - cba

  // All vertices must use the _same ordering_ for the edges to be rendered
  // correctly. So we compute a bitmask for each vertex, where the bit at
  // each position indicates whether that ordering works (i.e. doesn't
  // conflict with already-assigned coordinates) for that vertex.

  // Then we can find an ordering that works for all three vertices with a
  // bitwise AND.

  function computeOrderMask(outlineCoordinates, vertexIndex, a, b, c) {
    const startIndex = vertexIndex * 3;
    const first = outlineCoordinates[startIndex];
    const second = outlineCoordinates[startIndex + 1];
    const third = outlineCoordinates[startIndex + 2];

    if (first === undefined) {
      // If one coordinate is undefined, they all are, and all orderings are fine.
      return 63; // 0b111111;
    }

    return (
      ((first === a && second === b && third === c) << 0) +
      ((first === a && second === c && third === b) << 1) +
      ((first === b && second === a && third === c) << 2) +
      ((first === b && second === c && third === a) << 3) +
      ((first === c && second === a && third === b) << 4) +
      ((first === c && second === b && third === a) << 5)
    );
  }

  // popcount for integers 0-63, inclusive.
  // i.e. how many 1s are in the binary representation of the integer.
  function popcount0to63(value) {
    return (
      (value & 1) +
      ((value >> 1) & 1) +
      ((value >> 2) & 1) +
      ((value >> 3) & 1) +
      ((value >> 4) & 1) +
      ((value >> 5) & 1)
    );
  }

  function matchAndStoreCoordinates(
    outlineCoordinates,
    i0,
    i1,
    i2,
    has01,
    has12,
    has20
  ) {
    const a0 = has20 ? 1.0 : 0.0;
    const b0 = has01 ? 1.0 : 0.0;
    const c0 = 0.0;

    const i0Mask = computeOrderMask(outlineCoordinates, i0, a0, b0, c0);
    if (i0Mask === 0) {
      return i0;
    }

    const a1 = 0.0;
    const b1 = has01 ? 1.0 : 0.0;
    const c1 = has12 ? 1.0 : 0.0;

    const i1Mask = computeOrderMask(outlineCoordinates, i1, a1, b1, c1);
    if (i1Mask === 0) {
      return i1;
    }

    const a2 = has20 ? 1.0 : 0.0;
    const b2 = 0.0;
    const c2 = has12 ? 1.0 : 0.0;

    const i2Mask = computeOrderMask(outlineCoordinates, i2, a2, b2, c2);
    if (i2Mask === 0) {
      return i2;
    }

    const workingOrders = i0Mask & i1Mask & i2Mask;

    let a, b, c;

    if (workingOrders & (1 << 0)) {
      // 0 - abc
      a = 0;
      b = 1;
      c = 2;
    } else if (workingOrders & (1 << 1)) {
      // 1 - acb
      a = 0;
      c = 1;
      b = 2;
    } else if (workingOrders & (1 << 2)) {
      // 2 - bac
      b = 0;
      a = 1;
      c = 2;
    } else if (workingOrders & (1 << 3)) {
      // 3 - bca
      b = 0;
      c = 1;
      a = 2;
    } else if (workingOrders & (1 << 4)) {
      // 4 - cab
      c = 0;
      a = 1;
      b = 2;
    } else if (workingOrders & (1 << 5)) {
      // 5 - cba
      c = 0;
      b = 1;
      a = 2;
    } else {
      // No ordering works.
      // Report the most constrained vertex as unmatched so we copy that one.
      const i0Popcount = popcount0to63(i0Mask);
      const i1Popcount = popcount0to63(i1Mask);
      const i2Popcount = popcount0to63(i2Mask);
      if (i0Popcount < i1Popcount && i0Popcount < i2Popcount) {
        return i0;
      } else if (i1Popcount < i2Popcount) {
        return i1;
      }
      return i2;
    }

    const i0Start = i0 * 3;
    outlineCoordinates[i0Start + a] = a0;
    outlineCoordinates[i0Start + b] = b0;
    outlineCoordinates[i0Start + c] = c0;

    const i1Start = i1 * 3;
    outlineCoordinates[i1Start + a] = a1;
    outlineCoordinates[i1Start + b] = b1;
    outlineCoordinates[i1Start + c] = c1;

    const i2Start = i2 * 3;
    outlineCoordinates[i2Start + a] = a2;
    outlineCoordinates[i2Start + b] = b2;
    outlineCoordinates[i2Start + c] = c2;

    return -1;
  }

  function isHighlighted(edges, i0, i1) {
    const edgeSmallMultiplier = edges[0];
    const index = Math.min(i0, i1) * edgeSmallMultiplier + Math.max(i0, i1);

    // If i0 and i1 are both 0, then our index will be 0 and we'll end up
    // accessing the edgeSmallMultiplier that we've sneakily squirreled away
    // in index 0. But it makes no sense to have an edge between vertex 0 and
    // itself, so for any edgeSmallMultiplier other than 1 we'll return the
    // correct answer: false. If edgeSmallMultiplier is 1, that means there is
    // only a single vertex, so no danger of forming a meaningful triangle
    // with that.
    return edges[index] === 1;
  }

  function createTexture$3(size) {
    const texture = new Uint8Array(size);
    texture[size - 1] = 192;
    if (size === 8) {
      texture[size - 1] = 96;
    } else if (size === 4) {
      texture[size - 1] = 48;
    } else if (size === 2) {
      texture[size - 1] = 24;
    } else if (size === 1) {
      texture[size - 1] = 12;
    }
    return texture;
  }

  function updateBufferViewsWithNewVertices(model, bufferViews) {
    const gltf = model.gltfInternal;
    const loadResources = model._loadResources;

    let i, j;
    for (i = 0; i < bufferViews.length; ++i) {
      const bufferView = bufferViews[i];
      const vertexNumberingScope =
        bufferView.extras._pipeline.vertexNumberingScope;

      // Let the temporary data be garbage collected.
      bufferView.extras._pipeline.vertexNumberingScope = undefined;

      const newVertices = vertexNumberingScope.extraVertices;

      const sourceData = loadResources.getBuffer(bufferView);
      const byteStride = bufferView.byteStride || 4;
      const newVerticesLength = newVertices.length;
      const destData = new Uint8Array(
        sourceData.byteLength + newVerticesLength * byteStride
      );

      // Copy the original vertices
      destData.set(sourceData);

      // Copy the vertices added for outlining
      for (j = 0; j < newVerticesLength; ++j) {
        const sourceIndex = newVertices[j] * byteStride;
        const destIndex = sourceData.length + j * byteStride;
        for (let k = 0; k < byteStride; ++k) {
          destData[destIndex + k] = destData[sourceIndex + k];
        }
      }

      // This bufferView is an independent buffer now. Update the model accordingly.
      bufferView.byteOffset = 0;
      bufferView.byteLength = destData.byteLength;

      const bufferId =
        gltf.buffers.push({
          byteLength: destData.byteLength,
          extras: {
            _pipeline: {
              source: destData.buffer,
            },
          },
        }) - 1;

      bufferView.buffer = bufferId;
      loadResources.buffers[bufferId] = destData;

      // Update the accessors to reflect the added vertices.
      const accessors = vertexNumberingScope.accessors;
      for (j = 0; j < accessors.length; ++j) {
        const accessorId = accessors[j];
        gltf.accessors[accessorId].count += newVerticesLength;
      }

      if (!vertexNumberingScope.createdOutlines) {
        // Create the buffers, views, and accessors for the outline texture coordinates.
        const outlineCoordinates = vertexNumberingScope.outlineCoordinates;
        const outlineCoordinateBuffer = new Float32Array(outlineCoordinates);
        const bufferIndex =
          model.gltfInternal.buffers.push({
            byteLength: outlineCoordinateBuffer.byteLength,
            extras: {
              _pipeline: {
                source: outlineCoordinateBuffer.buffer,
              },
            },
          }) - 1;
        loadResources.buffers[bufferIndex] = new Uint8Array(
          outlineCoordinateBuffer.buffer,
          0,
          outlineCoordinateBuffer.byteLength
        );

        const bufferViewIndex =
          model.gltfInternal.bufferViews.push({
            buffer: bufferIndex,
            byteLength: outlineCoordinateBuffer.byteLength,
            byteOffset: 0,
            byteStride: 3 * Float32Array.BYTES_PER_ELEMENT,
            target: 34962,
          }) - 1;

        const accessorIndex =
          model.gltfInternal.accessors.push({
            bufferView: bufferViewIndex,
            byteOffset: 0,
            componentType: 5126,
            count: outlineCoordinateBuffer.length / 3,
            type: "VEC3",
            min: [0.0, 0.0, 0.0],
            max: [1.0, 1.0, 1.0],
          }) - 1;

        const primitives = vertexNumberingScope.primitives;
        for (j = 0; j < primitives.length; ++j) {
          primitives[j].attributes._OUTLINE_COORDINATES = accessorIndex;
        }

        loadResources.vertexBuffersToCreate.enqueue(bufferViewIndex);

        vertexNumberingScope.createdOutlines = true;
      }
    }
  }

  function compactBuffers(model) {
    const gltf = model.gltfInternal;
    const loadResources = model._loadResources;

    let i;
    for (i = 0; i < gltf.buffers.length; ++i) {
      const buffer = gltf.buffers[i];
      const bufferViewsUsingThisBuffer = gltf.bufferViews.filter(
        usesBuffer.bind(undefined, i)
      );
      const newLength = bufferViewsUsingThisBuffer.reduce(function (
        previous,
        current
      ) {
        return previous + current.byteLength;
      },
      0);
      if (newLength === buffer.byteLength) {
        continue;
      }

      const newBuffer = new Uint8Array(newLength);
      let offset = 0;
      for (let j = 0; j < bufferViewsUsingThisBuffer.length; ++j) {
        const bufferView = bufferViewsUsingThisBuffer[j];
        const sourceData = loadResources.getBuffer(bufferView);
        newBuffer.set(sourceData, offset);

        bufferView.byteOffset = offset;
        offset += sourceData.byteLength;
      }

      loadResources.buffers[i] = newBuffer;
      buffer.extras._pipeline.source = newBuffer.buffer;
      buffer.byteLength = newLength;
    }
  }

  function usesBuffer(bufferId, bufferView) {
    return bufferView.buffer === bufferId;
  }

  function getVertexNumberingScope(model, primitive) {
    const attributes = primitive.attributes;
    if (attributes === undefined) {
      return undefined;
    }

    const gltf = model.gltfInternal;

    let vertexNumberingScope;

    // Initialize common details for all bufferViews used by this primitive's vertices.
    // All bufferViews used by this primitive must use a common vertex numbering scheme.
    for (const semantic in attributes) {
      if (!attributes.hasOwnProperty(semantic)) {
        continue;
      }

      const accessorId = attributes[semantic];
      const accessor = gltf.accessors[accessorId];
      const bufferViewId = accessor.bufferView;
      const bufferView = gltf.bufferViews[bufferViewId];

      if (!defined(bufferView.extras)) {
        bufferView.extras = {};
      }
      if (!defined(bufferView.extras._pipeline)) {
        bufferView.extras._pipeline = {};
      }

      if (!defined(bufferView.extras._pipeline.vertexNumberingScope)) {
        bufferView.extras._pipeline.vertexNumberingScope = vertexNumberingScope || {
          // Each element in this array is:
          // a) undefined, if the vertex at this index has no copies
          // b) the index of the copy.
          vertexCopies: [],

          // Extra vertices appended after the ones originally included in the model.
          // Each element is the index of the vertex that this one is a copy of.
          extraVertices: [],

          // The texture coordinates used for outlining, three floats per vertex.
          outlineCoordinates: [],

          // The IDs of accessors that use this vertex numbering.
          accessors: [],

          // The IDs of bufferViews that use this vertex numbering.
          bufferViews: [],

          // The primitives that use this vertex numbering.
          primitives: [],

          // True if the buffer for the outlines has already been created.
          createdOutlines: false,
        };
      } else if (
        vertexNumberingScope !== undefined &&
        bufferView.extras._pipeline.vertexNumberingScope !== vertexNumberingScope
      ) {
        // Conflicting vertex numbering, let's give up.
        return undefined;
      }

      vertexNumberingScope = bufferView.extras._pipeline.vertexNumberingScope;

      if (vertexNumberingScope.bufferViews.indexOf(bufferView) < 0) {
        vertexNumberingScope.bufferViews.push(bufferView);
      }

      if (vertexNumberingScope.accessors.indexOf(accessorId) < 0) {
        vertexNumberingScope.accessors.push(accessorId);
      }
    }

    vertexNumberingScope.primitives.push(primitive);

    return vertexNumberingScope;
  }

  /**
   * The direction to display a primitive or ImageryLayer relative to the {@link Scene#splitPosition}.
   *
   * @enum {Number}
   *
   * @see ImageryLayer#splitDirection
   * @see Cesium3DTileset#splitDirection
   */
  const SplitDirection = {
    /**
     * Display the primitive or ImageryLayer to the left of the {@link Scene#splitPosition}.
     *
     * @type {Number}
     * @constant
     */
    LEFT: -1.0,

    /**
     *  Always display the primitive or ImageryLayer.
     *
     * @type {Number}
     * @constant
     */
    NONE: 0.0,

    /**
     * Display the primitive or ImageryLayer to the right of the {@link Scene#splitPosition}.
     *
     * @type {Number}
     * @constant
     */
    RIGHT: 1.0,
  };
  var SplitDirection$1 = Object.freeze(SplitDirection);

  /**
   * Support for rendering things on only one side of the screen.
   *
   * @private
   */
  const Splitter = {
    /**
     * Given a fragment shader string, returns a modified version of it that
     * only renders on one side of the screen or the other. Fragments on the
     * other side are discarded. The screen side is given by a uniform called
     * `czm_splitDirection`, which can be added by calling
     * {@link Splitter#addUniforms}, and the split position is given by an
     * automatic uniform called `czm_splitPosition`.
     */
    modifyFragmentShader: function modifyFragmentShader(shader) {
      shader = ShaderSource.replaceMain(shader, "czm_splitter_main");
      shader +=
        // czm_splitPosition is not declared because it is an automatic uniform.
        "uniform float czm_splitDirection; \n" +
        "void main() \n" +
        "{ \n" +
        // Don't split when rendering the shadow map, because it is rendered from
        // the perspective of a totally different camera.
        "#ifndef SHADOW_MAP\n" +
        "    if (czm_splitDirection < 0.0 && gl_FragCoord.x > czm_splitPosition) discard; \n" +
        "    if (czm_splitDirection > 0.0 && gl_FragCoord.x < czm_splitPosition) discard; \n" +
        "#endif\n" +
        "    czm_splitter_main(); \n" +
        "} \n";

      return shader;
    },

    /**
     * Add `czm_splitDirection` to the given uniform map.
     *
     * @param {Object} object The object on which the `splitDirection` property may be found.
     * @param {Object} uniformMap The uniform map.
     */
    addUniforms: function addUniforms(object, uniformMap) {
      uniformMap.czm_splitDirection = function () {
        return object.splitDirection;
      };
    },
  };

  const boundingSphereCartesian3Scratch = new Cartesian3();

  const ModelState = ModelUtility.ModelState;

  // glTF MIME types discussed in https://github.com/KhronosGroup/glTF/issues/412 and https://github.com/KhronosGroup/glTF/issues/943
  const defaultModelAccept =
    "model/gltf-binary,model/gltf+json;q=0.8,application/json;q=0.2,*/*;q=0.01";

  const articulationEpsilon$1 = CesiumMath.EPSILON16;

  ///////////////////////////////////////////////////////////////////////////

  function setCachedGltf(model, cachedGltf) {
    model._cachedGltf = cachedGltf;
  }

  // glTF JSON can be big given embedded geometry, textures, and animations, so we
  // cache it across all models using the same url/cache-key.  This also reduces the
  // slight overhead in assigning defaults to missing values.
  //
  // Note that this is a global cache, compared to renderer resources, which
  // are cached per context.
  function CachedGltf(options) {
    this._gltf = options.gltf;
    this.ready = options.ready;
    this.modelsToLoad = [];
    this.count = 0;
  }

  Object.defineProperties(CachedGltf.prototype, {
    gltf: {
      set: function (value) {
        this._gltf = value;
      },

      get: function () {
        return this._gltf;
      },
    },
  });

  CachedGltf.prototype.makeReady = function (gltfJson) {
    this.gltf = gltfJson;

    const models = this.modelsToLoad;
    const length = models.length;
    for (let i = 0; i < length; ++i) {
      const m = models[i];
      if (!m.isDestroyed()) {
        setCachedGltf(m, this);
      }
    }
    this.modelsToLoad = undefined;
    this.ready = true;
  };

  const gltfCache = {};
  const uriToGuid = {};
  ///////////////////////////////////////////////////////////////////////////

  /**
   * A 3D model based on glTF, the runtime asset format for WebGL, OpenGL ES, and OpenGL.
   * <p>
   * Cesium includes support for geometry and materials, glTF animations, and glTF skinning.
   * In addition, individual glTF nodes are pickable with {@link Scene#pick} and animatable
   * with {@link Model#getNode}.  glTF cameras and lights are not currently supported.
   * </p>
   * <p>
   * An external glTF asset is created with {@link Model.fromGltf}.  glTF JSON can also be
   * created at runtime and passed to this constructor function.  In either case, the
   * {@link Model#readyPromise} is resolved when the model is ready to render, i.e.,
   * when the external binary, image, and shader files are downloaded and the WebGL
   * resources are created.
   * </p>
   * <p>
   * Cesium supports glTF assets with the following extensions:
   * <ul>
   * <li>
   * {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/1.0/Khronos/KHR_binary_glTF/README.md|KHR_binary_glTF (glTF 1.0)}
   * </li><li>
   * {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/1.0/Khronos/KHR_materials_common/README.md|KHR_materials_common (glTF 1.0)}
   * </li><li>
   * {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/1.0/Vendor/WEB3D_quantized_attributes/README.md|WEB3D_quantized_attributes (glTF 1.0)}
   * </li><li>
   * {@link https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/AGI_articulations/README.md|AGI_articulations}
   * </li><li>
   * {@link https://github.com/KhronosGroup/glTF/pull/1302|KHR_blend (draft)}
   * </li><li>
   * {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_draco_mesh_compression/README.md|KHR_draco_mesh_compression}
   * </li><li>
   * {@link https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness/README.md|KHR_materials_pbrSpecularGlossiness}
   * </li><li>
   * {@link https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit/README.md|KHR_materials_unlit}
   * </li><li>
   * {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_techniques_webgl/README.md|KHR_techniques_webgl}
   * </li><li>
   * {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_texture_transform/README.md|KHR_texture_transform}
   * </li><li>
   * {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_texture_basisu|KHR_texture_basisu}
   * </li>
   * </ul>
   * </p>
   * <p>
   * Note: for models with compressed textures using the KHR_texture_basisu extension, we recommend power of 2 textures in both dimensions
   * for maximum compatibility. This is because some samplers require power of 2 textures ({@link https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL|Using textures in WebGL})
   * and KHR_texture_basisu requires multiple of 4 dimensions ({@link https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_texture_basisu/README.md#additional-requirements|KHR_texture_basisu additional requirements}).
   * </p>
   * <p>
   * For high-precision rendering, Cesium supports the {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/1.0/Vendor/CESIUM_RTC/README.md|CESIUM_RTC} extension, which introduces the
   * CESIUM_RTC_MODELVIEW parameter semantic that says the node is in WGS84 coordinates translated
   * relative to a local origin.
   * </p>
   *
   * @alias Model
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Object|ArrayBuffer|Uint8Array} [options.gltf] A glTF JSON object, or a binary glTF buffer.
   * @param {Resource|String} [options.basePath=''] The base path that paths in the glTF JSON are relative to.
   * @param {Boolean} [options.show=true] Determines if the model primitive will be shown.
   * @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] The 4x4 transformation matrix that transforms the model from model to world coordinates.
   * @param {Number} [options.scale=1.0] A uniform scale applied to this model.
   * @param {Number} [options.minimumPixelSize=0.0] The approximate minimum pixel size of the model regardless of zoom.
   * @param {Number} [options.maximumScale] The maximum scale size of a model. An upper limit for minimumPixelSize.
   * @param {Object} [options.id] A user-defined object to return when the model is picked with {@link Scene#pick}.
   * @param {Boolean} [options.allowPicking=true] When <code>true</code>, each glTF mesh and primitive is pickable with {@link Scene#pick}.
   * @param {Boolean} [options.incrementallyLoadTextures=true] Determine if textures may continue to stream in after the model is loaded.
   * @param {Boolean} [options.asynchronous=true] Determines if model WebGL resource creation will be spread out over several frames or block until completion once all glTF files are loaded.
   * @param {Boolean} [options.clampAnimations=true] Determines if the model's animations should hold a pose over frames where no keyframes are specified.
   * @param {ShadowMode} [options.shadows=ShadowMode.ENABLED] Determines whether the model casts or receives shadows from light sources.
   * @param {Boolean} [options.debugShowBoundingVolume=false] For debugging only. Draws the bounding sphere for each draw command in the model.
   * @param {Boolean} [options.debugWireframe=false] For debugging only. Draws the model in wireframe.
   * @param {HeightReference} [options.heightReference=HeightReference.NONE] Determines how the model is drawn relative to terrain.
   * @param {Scene} [options.scene] Must be passed in for models that use the height reference property.
   * @param {DistanceDisplayCondition} [options.distanceDisplayCondition] The condition specifying at what distance from the camera that this model will be displayed.
   * @param {Color} [options.color=Color.WHITE] A color that blends with the model's rendered color.
   * @param {ColorBlendMode} [options.colorBlendMode=ColorBlendMode.HIGHLIGHT] Defines how the color blends with the model.
   * @param {Number} [options.colorBlendAmount=0.5] Value used to determine the color strength when the <code>colorBlendMode</code> is <code>MIX</code>. A value of 0.0 results in the model's rendered color while a value of 1.0 results in a solid color, with any value in-between resulting in a mix of the two.
   * @param {Color} [options.silhouetteColor=Color.RED] The silhouette color. If more than 256 models have silhouettes enabled, there is a small chance that overlapping models will have minor artifacts.
   * @param {Number} [options.silhouetteSize=0.0] The size of the silhouette in pixels.
   * @param {ClippingPlaneCollection} [options.clippingPlanes] The {@link ClippingPlaneCollection} used to selectively disable rendering the model.
   * @param {Boolean} [options.dequantizeInShader=true] Determines if a {@link https://github.com/google/draco|Draco} encoded model is dequantized on the GPU. This decreases total memory usage for encoded models. Deprecated in CesiumJS 1.94, will be removed in CesiumJS 1.96.
   * @param {Cartesian3} [options.lightColor] The light color when shading the model. When <code>undefined</code> the scene's light color is used instead.
   * @param {ImageBasedLighting} [options.imageBasedLighting] The properties for managing image-based lighting on this model.
   * @param {Credit|String} [options.credit] A credit for the data source, which is displayed on the canvas.
   * @param {Boolean} [options.showCreditsOnScreen=false] Whether to display the credits of this model on screen.
   * @param {Boolean} [options.backFaceCulling=true] Whether to cull back-facing geometry. When true, back face culling is determined by the material's doubleSided property; when false, back face culling is disabled. Back faces are not culled if {@link Model#color} is translucent or {@link Model#silhouetteSize} is greater than 0.0.
   * @param {Boolean} [options.showOutline=true] Whether to display the outline for models using the {@link https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/CESIUM_primitive_outline|CESIUM_primitive_outline} extension. When true, outlines are displayed. When false, outlines are not displayed.
   * @param {SplitDirection} [options.splitDirection=SplitDirection.NONE] The {@link SplitDirection} split to apply to this model.
   *
   *
   * @see Model.fromGltf
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=3D%20Models.html|Cesium Sandcastle Models Demo}
   */
  function Model(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const cacheKey = options.cacheKey;
    this._cacheKey = cacheKey;
    this._cachedGltf = undefined;
    this._releaseGltfJson = defaultValue(options.releaseGltfJson, false);

    let cachedGltf;
    if (
      defined(cacheKey) &&
      defined(gltfCache[cacheKey]) &&
      gltfCache[cacheKey].ready
    ) {
      // glTF JSON is in cache and ready
      cachedGltf = gltfCache[cacheKey];
      ++cachedGltf.count;
    } else {
      // glTF was explicitly provided, e.g., when a user uses the Model constructor directly
      let gltf = options.gltf;

      if (defined(gltf)) {
        if (gltf instanceof ArrayBuffer) {
          gltf = new Uint8Array(gltf);
        }

        if (gltf instanceof Uint8Array) {
          // Binary glTF
          const parsedGltf = parseGlb(gltf);

          cachedGltf = new CachedGltf({
            gltf: parsedGltf,
            ready: true,
          });
        } else {
          // Normal glTF (JSON)
          cachedGltf = new CachedGltf({
            gltf: options.gltf,
            ready: true,
          });
        }

        cachedGltf.count = 1;

        if (defined(cacheKey)) {
          gltfCache[cacheKey] = cachedGltf;
        }
      }
    }
    setCachedGltf(this, cachedGltf);

    const basePath = defaultValue(options.basePath, "");
    this._resource = Resource.createIfNeeded(basePath);

    // User specified credit
    let credit = options.credit;
    if (typeof credit === "string") {
      credit = new Credit(credit);
    }

    this._credit = credit;

    // List of credits to be added from the Resource if it is an IonResource
    this._resourceCredits = [];

    // List of credits to be added from the glTF
    this._gltfCredits = [];

    this._showCreditsOnScreen = defaultValue(options.showCreditsOnScreen, false);

    /**
     * Determines if the model primitive will be shown.
     *
     * @type {Boolean}
     *
     * @default true
     */
    this.show = defaultValue(options.show, true);

    /**
     * The silhouette color.
     *
     * @type {Color}
     *
     * @default Color.RED
     */
    this.silhouetteColor = defaultValue(options.silhouetteColor, Color.RED);
    this._silhouetteColor = new Color();
    this._silhouetteColorPreviousAlpha = 1.0;
    this._normalAttributeName = undefined;

    /**
     * The size of the silhouette in pixels.
     *
     * @type {Number}
     *
     * @default 0.0
     */
    this.silhouetteSize = defaultValue(options.silhouetteSize, 0.0);

    /**
     * The 4x4 transformation matrix that transforms the model from model to world coordinates.
     * When this is the identity matrix, the model is drawn in world coordinates, i.e., Earth's WGS84 coordinates.
     * Local reference frames can be used by providing a different transformation matrix, like that returned
     * by {@link Transforms.eastNorthUpToFixedFrame}.
     *
     * @type {Matrix4}
     *
     * @default {@link Matrix4.IDENTITY}
     *
     * @example
     * const origin = Cesium.Cartesian3.fromDegrees(-95.0, 40.0, 200000.0);
     * m.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(origin);
     */
    this.modelMatrix = Matrix4.clone(
      defaultValue(options.modelMatrix, Matrix4.IDENTITY)
    );
    this._modelMatrix = Matrix4.clone(this.modelMatrix);
    this._clampedModelMatrix = undefined;

    /**
     * A uniform scale applied to this model before the {@link Model#modelMatrix}.
     * Values greater than <code>1.0</code> increase the size of the model; values
     * less than <code>1.0</code> decrease.
     *
     * @type {Number}
     *
     * @default 1.0
     */
    this.scale = defaultValue(options.scale, 1.0);
    this._scale = this.scale;

    /**
     * The approximate minimum pixel size of the model regardless of zoom.
     * This can be used to ensure that a model is visible even when the viewer
     * zooms out.  When <code>0.0</code>, no minimum size is enforced.
     *
     * @type {Number}
     *
     * @default 0.0
     */
    this.minimumPixelSize = defaultValue(options.minimumPixelSize, 0.0);
    this._minimumPixelSize = this.minimumPixelSize;

    /**
     * The maximum scale size for a model. This can be used to give
     * an upper limit to the {@link Model#minimumPixelSize}, ensuring that the model
     * is never an unreasonable scale.
     *
     * @type {Number}
     */
    this.maximumScale = options.maximumScale;
    this._maximumScale = this.maximumScale;

    /**
     * User-defined object returned when the model is picked.
     *
     * @type Object
     *
     * @default undefined
     *
     * @see Scene#pick
     */
    this.id = options.id;
    this._id = options.id;

    /**
     * Returns the height reference of the model
     *
     * @type {HeightReference}
     *
     * @default HeightReference.NONE
     */
    this.heightReference = defaultValue(
      options.heightReference,
      HeightReference$1.NONE
    );
    this._heightReference = this.heightReference;
    this._heightChanged = false;
    this._removeUpdateHeightCallback = undefined;
    const scene = options.scene;
    this._scene = scene;
    if (defined(scene) && defined(scene.terrainProviderChanged)) {
      this._terrainProviderChangedCallback = scene.terrainProviderChanged.addEventListener(
        function () {
          this._heightChanged = true;
        },
        this
      );
    }

    /**
     * Used for picking primitives that wrap a model.
     *
     * @private
     */
    this._pickObject = options.pickObject;
    this._allowPicking = defaultValue(options.allowPicking, true);

    this._ready = false;
    this._readyPromise = defer();

    /**
     * The currently playing glTF animations.
     *
     * @type {ModelAnimationCollection}
     */
    this.activeAnimations = new ModelAnimationCollection(this);

    /**
     * Determines if the model's animations should hold a pose over frames where no keyframes are specified.
     *
     * @type {Boolean}
     */
    this.clampAnimations = defaultValue(options.clampAnimations, true);

    this._defaultTexture = undefined;
    this._incrementallyLoadTextures = defaultValue(
      options.incrementallyLoadTextures,
      true
    );
    this._asynchronous = defaultValue(options.asynchronous, true);

    /**
     * Determines whether the model casts or receives shadows from light sources.
     *
     * @type {ShadowMode}
     *
     * @default ShadowMode.ENABLED
     */
    this.shadows = defaultValue(options.shadows, ShadowMode$1.ENABLED);
    this._shadows = this.shadows;

    /**
     * A color that blends with the model's rendered color.
     *
     * @type {Color}
     *
     * @default Color.WHITE
     */
    this.color = Color.clone(defaultValue(options.color, Color.WHITE));
    this._colorPreviousAlpha = 1.0;

    /**
     * Defines how the color blends with the model.
     *
     * @type {ColorBlendMode}
     *
     * @default ColorBlendMode.HIGHLIGHT
     */
    this.colorBlendMode = defaultValue(
      options.colorBlendMode,
      ColorBlendMode$1.HIGHLIGHT
    );

    /**
     * Value used to determine the color strength when the <code>colorBlendMode</code> is <code>MIX</code>.
     * A value of 0.0 results in the model's rendered color while a value of 1.0 results in a solid color, with
     * any value in-between resulting in a mix of the two.
     *
     * @type {Number}
     *
     * @default 0.5
     */
    this.colorBlendAmount = defaultValue(options.colorBlendAmount, 0.5);

    this._colorShadingEnabled = false;

    this._clippingPlanes = undefined;
    this.clippingPlanes = options.clippingPlanes;
    // Used for checking if shaders need to be regenerated due to clipping plane changes.
    this._clippingPlanesState = 0;

    // If defined, use this matrix to transform miscellaneous properties like
    // clipping planes and IBL instead of the modelMatrix. This is so that when
    // models are part of a tileset these properties get transformed relative to
    // a common reference (such as the root).
    this.referenceMatrix = undefined;

    /**
     * Whether to cull back-facing geometry. When true, back face culling is
     * determined by the material's doubleSided property; when false, back face
     * culling is disabled. Back faces are not culled if {@link Model#color} is
     * translucent or {@link Model#silhouetteSize} is greater than 0.0.
     *
     * @type {Boolean}
     *
     * @default true
     */
    this.backFaceCulling = defaultValue(options.backFaceCulling, true);

    /**
     * Whether to display the outline for models using the
     * {@link https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/CESIUM_primitive_outline|CESIUM_primitive_outline} extension.
     * When true, outlines are displayed. When false, outlines are not displayed.
     *
     * @type {Boolean}
     * @readonly
     *
     * @default true
     */
    this.showOutline = defaultValue(options.showOutline, true);

    /**
     * The {@link SplitDirection} to apply to this model.
     *
     * @type {SplitDirection}
     * @default {@link SplitDirection.NONE}
     */
    this.splitDirection = defaultValue(
      options.splitDirection,
      SplitDirection$1.NONE
    );
    this._splittingEnabled = false;

    /**
     * This property is for debugging only; it is not for production use nor is it optimized.
     * <p>
     * Draws the bounding sphere for each draw command in the model.  A glTF primitive corresponds
     * to one draw command.  A glTF mesh has an array of primitives, often of length one.
     * </p>
     *
     * @type {Boolean}
     *
     * @default false
     */
    this.debugShowBoundingVolume = defaultValue(
      options.debugShowBoundingVolume,
      false
    );
    this._debugShowBoundingVolume = false;

    /**
     * This property is for debugging only; it is not for production use nor is it optimized.
     * <p>
     * Draws the model in wireframe.
     * </p>
     *
     * @type {Boolean}
     *
     * @default false
     */
    this.debugWireframe = defaultValue(options.debugWireframe, false);
    this._debugWireframe = false;

    this._distanceDisplayCondition = options.distanceDisplayCondition;

    // Undocumented options
    this._addBatchIdToGeneratedShaders = options.addBatchIdToGeneratedShaders;
    this._precreatedAttributes = options.precreatedAttributes;
    this._vertexShaderLoaded = options.vertexShaderLoaded;
    this._fragmentShaderLoaded = options.fragmentShaderLoaded;
    this._uniformMapLoaded = options.uniformMapLoaded;
    this._pickIdLoaded = options.pickIdLoaded;
    this._ignoreCommands = defaultValue(options.ignoreCommands, false);
    this._requestType = options.requestType;
    this._upAxis = defaultValue(options.upAxis, Axis$1.Y);
    this._gltfForwardAxis = Axis$1.Z;
    this._forwardAxis = options.forwardAxis;

    /**
     * @private
     * @readonly
     */
    this.cull = defaultValue(options.cull, true);

    /**
     * @private
     * @readonly
     */
    this.opaquePass = defaultValue(options.opaquePass, Pass$1.OPAQUE);

    this._computedModelMatrix = new Matrix4(); // Derived from modelMatrix and scale
    this._clippingPlanesMatrix = Matrix4.clone(Matrix4.IDENTITY); // Derived from reference matrix and the current view matrix
    this._iblReferenceFrameMatrix = Matrix3.clone(Matrix3.IDENTITY); // Derived from reference matrix and the current view matrix
    this._initialRadius = undefined; // Radius without model's scale property, model-matrix scale, animations, or skins
    this._boundingSphere = undefined;
    this._scaledBoundingSphere = new BoundingSphere();
    this._state = ModelState.NEEDS_LOAD;
    this._loadResources = undefined;

    this._mode = undefined;

    this._perNodeShowDirty = false; // true when the Cesium API was used to change a node's show property
    this._cesiumAnimationsDirty = false; // true when the Cesium API, not a glTF animation, changed a node transform
    this._dirty = false; // true when the model was transformed this frame
    this._maxDirtyNumber = 0; // Used in place of a dirty boolean flag to avoid an extra graph traversal

    this._runtime = {
      animations: undefined,
      articulationsByName: undefined,
      articulationsByStageKey: undefined,
      stagesByKey: undefined,
      rootNodes: undefined,
      nodes: undefined, // Indexed with the node's index
      nodesByName: undefined, // Indexed with name property in the node
      skinnedNodes: undefined,
      meshesByName: undefined, // Indexed with the name property in the mesh
      materialsByName: undefined, // Indexed with the name property in the material
      materialsById: undefined, // Indexed with the material's index
    };

    this._uniformMaps = {}; // Not cached since it can be targeted by glTF animation
    this._extensionsUsed = undefined; // Cached used glTF extensions
    this._extensionsRequired = undefined; // Cached required glTF extensions
    this._quantizedUniforms = {}; // Quantized uniforms for each program for WEB3D_quantized_attributes
    this._programPrimitives = {};
    this._rendererResources = {
      // Cached between models with the same url/cache-key
      buffers: {},
      vertexArrays: {},
      programs: {},
      sourceShaders: {},
      silhouettePrograms: {},
      textures: {},
      samplers: {},
      renderStates: {},
    };
    this._cachedRendererResources = undefined;
    this._loadRendererResourcesFromCache = false;

    if (options.dequantizeInShader) {
      deprecationWarning(
        "Model.dequantizeInShader",
        "The Model dequantizeInShader constructor parameter was deprecated in CesiumJS 1.94 and will be removed in 1.96"
      );
    }

    this._dequantizeInShader = defaultValue(options.dequantizeInShader, true);
    this._decodedData = {};

    this._cachedGeometryByteLength = 0;
    this._cachedTexturesByteLength = 0;
    this._geometryByteLength = 0;
    this._texturesByteLength = 0;
    this._trianglesLength = 0;
    this._pointsLength = 0;

    // Hold references for shader reconstruction.
    // Hold these separately because _cachedGltf may get released (this.releaseGltfJson)
    this._sourceTechniques = {};
    this._sourcePrograms = {};
    this._quantizedVertexShaders = {};

    this._nodeCommands = [];
    this._pickIds = [];

    // CESIUM_RTC extension
    this._rtcCenter = undefined; // reference to either 3D or 2D
    this._rtcCenterEye = undefined; // in eye coordinates
    this._rtcCenter3D = undefined; // in world coordinates
    this._rtcCenter2D = undefined; // in projected world coordinates

    this._sourceVersion = undefined;
    this._sourceKHRTechniquesWebGL = undefined;

    this._lightColor = Cartesian3.clone(options.lightColor);

    if (defined(options.imageBasedLighting)) {
      this._imageBasedLighting = options.imageBasedLighting;
      this._shouldDestroyImageBasedLighting = false;
    } else {
      this._imageBasedLighting = new ImageBasedLighting();
      this._shouldDestroyImageBasedLighting = true;
    }

    this._shouldRegenerateShaders = false;
  }

  Object.defineProperties(Model.prototype, {
    /**
     * The object for the glTF JSON, including properties with default values omitted
     * from the JSON provided to this model.
     *
     * @deprecated
     *
     * @memberof Model.prototype
     *
     * @type {Object}
     * @readonly
     *
     * @default undefined
     */
    gltf: {
      get: function () {
        deprecationWarning(
          "Model.gltf",
          "Model.gltf getter was deprecated in CesiumJS 1.94 and will be removed in 1.96"
        );

        return this.gltfInternal;
      },
    },

    /**
     * See https://github.com/CesiumGS/cesium/pull/10415#issuecomment-1143600984
     * @private
     */
    gltfInternal: {
      get: function () {
        return defined(this._cachedGltf) ? this._cachedGltf.gltf : undefined;
      },
    },

    /**
     * When <code>true</code>, the glTF JSON is not stored with the model once the model is
     * loaded (when {@link Model#ready} is <code>true</code>).  This saves memory when
     * geometry, textures, and animations are embedded in the .gltf file.
     * This is especially useful for cases like 3D buildings, where each .gltf model is unique
     * and caching the glTF JSON is not effective.
     *
     * @memberof Model.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default false
     *
     * @private
     */
    releaseGltfJson: {
      get: function () {
        return this._releaseGltfJson;
      },
    },

    /**
     * The key identifying this model in the model cache for glTF JSON, renderer resources, and animations.
     * Caching saves memory and improves loading speed when several models with the same url are created.
     * <p>
     * This key is automatically generated when the model is created with {@link Model.fromGltf}.  If the model
     * is created directly from glTF JSON using the {@link Model} constructor, this key can be manually
     * provided; otherwise, the model will not be changed.
     * </p>
     *
     * @memberof Model.prototype
     *
     * @type {String}
     * @readonly
     *
     * @private
     */
    cacheKey: {
      get: function () {
        return this._cacheKey;
      },
    },

    /**
     * The base path that paths in the glTF JSON are relative to.  The base
     * path is the same path as the path containing the .gltf file
     * minus the .gltf file, when binary, image, and shader files are
     * in the same directory as the .gltf.  When this is <code>''</code>,
     * the app's base path is used.
     *
     * @deprecated
     *
     * @memberof Model.prototype
     *
     * @type {String}
     * @readonly
     *
     * @default ''
     */
    basePath: {
      get: function () {
        deprecationWarning(
          "model.basePath",
          "Model.basePath getter is deprecated in CesiumJS 1.94. It will be removed in CesiumJS 1.96"
        );
        return this.basePathInternal;
      },
    },

    /**
     * See https://github.com/CesiumGS/cesium/pull/10415#issuecomment-1143600984
     * @private
     */
    basePathInternal: {
      get: function () {
        return this._resource.url;
      },
    },

    /**
     * The model's bounding sphere in its local coordinate system.  This does not take into
     * account glTF animations and skins nor does it take into account {@link Model#minimumPixelSize}.
     *
     * @memberof Model.prototype
     *
     * @type {BoundingSphere}
     * @readonly
     *
     * @default undefined
     *
     * @exception {DeveloperError} The model is not loaded.  Use Model.readyPromise or wait for Model.ready to be true.
     *
     * @example
     * // Center in WGS84 coordinates
     * const center = Cesium.Matrix4.multiplyByPoint(model.modelMatrix, model.boundingSphere.center, new Cesium.Cartesian3());
     */
    boundingSphere: {
      get: function () {
        deprecationWarning(
          "model.boundingSphere",
          "Model.boundingSphere currently returns results in model space. In CesiumJS 1.96, model.boundingSphere will be changed to return results in world space. The calling code will no longer need to multiply the bounding sphere by the model matrix"
        );
        return this.boundingSphereInternal;
      },
    },

    /*
     * See https://github.com/CesiumGS/cesium/pull/10415#issuecomment-1143600984
     * @private
     */
    boundingSphereInternal: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (this._state !== ModelState.LOADED) {
          throw new DeveloperError(
            "The model is not loaded.  Use Model.readyPromise or wait for Model.ready to be true."
          );
        }
        //>>includeEnd('debug');

        let modelMatrix = this.modelMatrix;
        if (
          this.heightReference !== HeightReference$1.NONE &&
          this._clampedModelMatrix
        ) {
          modelMatrix = this._clampedModelMatrix;
        }

        const nonUniformScale = Matrix4.getScale(
          modelMatrix,
          boundingSphereCartesian3Scratch
        );
        const scale = defined(this.maximumScale)
          ? Math.min(this.maximumScale, this.scale)
          : this.scale;
        Cartesian3.multiplyByScalar(nonUniformScale, scale, nonUniformScale);

        const scaledBoundingSphere = this._scaledBoundingSphere;
        scaledBoundingSphere.center = Cartesian3.multiplyComponents(
          this._boundingSphere.center,
          nonUniformScale,
          scaledBoundingSphere.center
        );
        scaledBoundingSphere.radius =
          Cartesian3.maximumComponent(nonUniformScale) * this._initialRadius;

        if (defined(this._rtcCenter)) {
          Cartesian3.add(
            this._rtcCenter,
            scaledBoundingSphere.center,
            scaledBoundingSphere.center
          );
        }

        return scaledBoundingSphere;
      },
    },

    /**
     * When <code>true</code>, this model is ready to render, i.e., the external binary, image,
     * and shader files were downloaded and the WebGL resources were created.  This is set to
     * <code>true</code> right before {@link Model#readyPromise} is resolved.
     *
     * @memberof Model.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default false
     */
    ready: {
      get: function () {
        return this._ready;
      },
    },

    /**
     * Gets the promise that will be resolved when this model is ready to render, i.e., when the external binary, image,
     * and shader files were downloaded and the WebGL resources were created.
     * <p>
     * This promise is resolved at the end of the frame before the first frame the model is rendered in.
     * </p>
     *
     * @memberof Model.prototype
     * @type {Promise.<Model>}
     * @readonly
     *
     * @example
     * // Play all animations at half-speed when the model is ready to render
     * Promise.resolve(model.readyPromise).then(function(model) {
     *   model.activeAnimations.addAll({
     *     multiplier : 0.5
     *   });
     * }).catch(function(error){
     *   window.alert(error);
     * });
     *
     * @see Model#ready
     */
    readyPromise: {
      get: function () {
        return this._readyPromise.promise;
      },
    },

    /**
     * Determines if model WebGL resource creation will be spread out over several frames or
     * block until completion once all glTF files are loaded.
     *
     * @memberof Model.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default true
     */
    asynchronous: {
      get: function () {
        return this._asynchronous;
      },
    },

    /**
     * When <code>true</code>, each glTF mesh and primitive is pickable with {@link Scene#pick}.  When <code>false</code>, GPU memory is saved.
     *
     * @memberof Model.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default true
     */
    allowPicking: {
      get: function () {
        return this._allowPicking;
      },
    },

    /**
     * Determine if textures may continue to stream in after the model is loaded.
     *
     * @memberof Model.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default true
     */
    incrementallyLoadTextures: {
      get: function () {
        return this._incrementallyLoadTextures;
      },
    },

    /**
     * Return the number of pending texture loads.
     *
     * @deprecated
     *
     * @memberof Model.prototype
     *
     * @type {Number}
     * @readonly
     */
    pendingTextureLoads: {
      get: function () {
        deprecationWarning(
          "Model.pendingTextureLoads",
          "The Model.pendingTextureLoads getter was deprecated in CesiumJS 1.94 and will be removed in CesiumJS 1.96"
        );

        return this.pendingTextureLoadsInternal;
      },
    },

    /**
     * See https://github.com/CesiumGS/cesium/pull/10415#issuecomment-1143600984
     * @private
     */
    pendingTextureLoadsInternal: {
      get: function () {
        return defined(this._loadResources)
          ? this._loadResources.pendingTextureLoads
          : 0;
      },
    },

    /**
     * Returns true if the model was transformed this frame
     *
     * @memberof Model.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @private
     */
    dirty: {
      get: function () {
        return this._dirty;
      },
    },

    /**
     * Gets or sets the condition specifying at what distance from the camera that this model will be displayed.
     * @memberof Model.prototype
     * @type {DistanceDisplayCondition}
     * @default undefined
     */
    distanceDisplayCondition: {
      get: function () {
        return this._distanceDisplayCondition;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (defined(value) && value.far <= value.near) {
          throw new DeveloperError("far must be greater than near");
        }
        //>>includeEnd('debug');
        this._distanceDisplayCondition = DistanceDisplayCondition.clone(
          value,
          this._distanceDisplayCondition
        );
      },
    },

    extensionsUsed: {
      get: function () {
        if (!defined(this._extensionsUsed)) {
          this._extensionsUsed = ModelUtility.getUsedExtensions(
            this.gltfInternal
          );
        }
        return this._extensionsUsed;
      },
    },

    extensionsRequired: {
      get: function () {
        if (!defined(this._extensionsRequired)) {
          this._extensionsRequired = ModelUtility.getRequiredExtensions(
            this.gltfInternal
          );
        }
        return this._extensionsRequired;
      },
    },

    /**
     * Gets the model's up-axis.
     * By default models are y-up according to the glTF spec, however geo-referenced models will typically be z-up.
     *
     * @memberof Model.prototype
     *
     * @type {Number}
     * @default Axis.Y
     * @readonly
     *
     * @private
     */
    upAxis: {
      get: function () {
        return this._upAxis;
      },
    },

    /**
     * Gets the model's forward axis.
     * By default, glTF 2.0 models are z-forward according to the glTF spec, however older
     * glTF (1.0, 0.8) models used x-forward.  Note that only Axis.X and Axis.Z are supported.
     *
     * @memberof Model.prototype
     *
     * @type {Number}
     * @default Axis.Z
     * @readonly
     *
     * @private
     */
    forwardAxis: {
      get: function () {
        if (defined(this._forwardAxis)) {
          return this._forwardAxis;
        }
        return this._gltfForwardAxis;
      },
    },

    /**
     * Gets the model's triangle count.
     *
     * @private
     */
    trianglesLength: {
      get: function () {
        return this._trianglesLength;
      },
    },

    /**
     * Gets the model's point count.
     *
     * @private
     */
    pointsLength: {
      get: function () {
        return this._pointsLength;
      },
    },

    /**
     * Gets the model's geometry memory in bytes. This includes all vertex and index buffers.
     *
     * @private
     */
    geometryByteLength: {
      get: function () {
        return this._geometryByteLength;
      },
    },

    /**
     * Gets the model's texture memory in bytes.
     *
     * @private
     */
    texturesByteLength: {
      get: function () {
        return this._texturesByteLength;
      },
    },

    /**
     * Gets the model's cached geometry memory in bytes. This includes all vertex and index buffers.
     *
     * @private
     */
    cachedGeometryByteLength: {
      get: function () {
        return this._cachedGeometryByteLength;
      },
    },

    /**
     * Gets the model's cached texture memory in bytes.
     *
     * @private
     */
    cachedTexturesByteLength: {
      get: function () {
        return this._cachedTexturesByteLength;
      },
    },

    /**
     * The {@link ClippingPlaneCollection} used to selectively disable rendering the model.
     *
     * @memberof Model.prototype
     *
     * @type {ClippingPlaneCollection}
     */
    clippingPlanes: {
      get: function () {
        return this._clippingPlanes;
      },
      set: function (value) {
        if (value === this._clippingPlanes) {
          return;
        }
        // Handle destroying, checking of unknown, checking for existing ownership
        ClippingPlaneCollection.setOwner(value, this, "_clippingPlanes");
      },
    },

    /**
     * @private
     */
    pickIds: {
      get: function () {
        return this._pickIds;
      },
    },

    /**
     * The light color when shading the model. When <code>undefined</code> the scene's light color is used instead.
     * <p>
     * For example, disabling additional light sources by setting
     * <code>model.imageBasedLighting.imageBasedLightingFactor = new Cesium.Cartesian2(0.0, 0.0)</code>
     * will make the model much darker. Here, increasing the intensity of the light source will make the model brighter.
     * </p>
     *
     * @memberof Model.prototype
     *
     * @type {Cartesian3}
     * @default undefined
     */
    lightColor: {
      get: function () {
        return this._lightColor;
      },
      set: function (value) {
        const lightColor = this._lightColor;
        if (value === lightColor || Cartesian3.equals(value, lightColor)) {
          return;
        }
        this._shouldRegenerateShaders =
          this._shouldRegenerateShaders ||
          (defined(lightColor) && !defined(value)) ||
          (defined(value) && !defined(lightColor));
        this._lightColor = Cartesian3.clone(value, lightColor);
      },
    },

    /**
     * The properties for managing image-based lighting on this model.
     *
     * @memberof Model.prototype
     *
     * @type {ImageBasedLighting}
     */
    imageBasedLighting: {
      get: function () {
        return this._imageBasedLighting;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.object("imageBasedLighting", this._imageBasedLighting);
        //>>includeEnd('debug');

        if (value !== this._imageBasedLighting) {
          if (
            this._shouldDestroyImageBasedLighting &&
            !this._imageBasedLighting.isDestroyed()
          ) {
            this._imageBasedLighting.destroy();
          }
          this._imageBasedLighting = value;
          this._shouldDestroyImageBasedLighting = false;
          this._shouldRegenerateShaders = true;
        }
      },
    },

    /**
     * Gets the credit that will be displayed for the model
     * @memberof Model.prototype
     * @type {Credit}
     */
    credit: {
      get: function () {
        return this._credit;
      },
    },

    /**
     * Gets or sets whether the credits of the model will be displayed on the screen
     * @memberof Model.prototype
     * @type {Boolean}
     */
    showCreditsOnScreen: {
      get: function () {
        return this._showCreditsOnScreen;
      },
      set: function (value) {
        if (this._showCreditsOnScreen !== value) {
          if (defined(this._credit)) {
            this._credit.showOnScreen = value;
          }

          const resourceCreditsLength = this._resourceCredits.length;
          for (let i = 0; i < resourceCreditsLength; i++) {
            this._resourceCredits[i].showOnScreen = value;
          }

          const gltfCreditsLength = this._gltfCredits.length;
          for (let i = 0; i < gltfCreditsLength; i++) {
            this._gltfCredits[i].showOnScreen = value;
          }
        }

        this._showCreditsOnScreen = value;
      },
    },
  });

  function silhouetteSupported(context) {
    return context.stencilBuffer;
  }

  function isColorShadingEnabled(model) {
    return (
      !Color.equals(model.color, Color.WHITE) ||
      model.colorBlendMode !== ColorBlendMode$1.HIGHLIGHT
    );
  }

  function isClippingEnabled(model) {
    const clippingPlanes = model._clippingPlanes;
    return (
      defined(clippingPlanes) &&
      clippingPlanes.enabled &&
      clippingPlanes.length !== 0
    );
  }

  /**
   * Determines if silhouettes are supported.
   *
   * @param {Scene} scene The scene.
   * @returns {Boolean} <code>true</code> if silhouettes are supported; otherwise, returns <code>false</code>
   */
  Model.silhouetteSupported = function (scene) {
    return silhouetteSupported(scene.context);
  };

  function containsGltfMagic(uint8Array) {
    const magic = getMagic(uint8Array);
    return magic === "glTF";
  }

  /**
   * <p>
   * Creates a model from a glTF asset.  When the model is ready to render, i.e., when the external binary, image,
   * and shader files are downloaded and the WebGL resources are created, the {@link Model#readyPromise} is resolved.
   * </p>
   * <p>
   * The model can be a traditional glTF asset with a .gltf extension or a Binary glTF using the .glb extension.
   * </p>
   * <p>
   * Cesium supports glTF assets with the following extensions:
   * <ul>
   * <li>
   * {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/1.0/Khronos/KHR_binary_glTF/README.md|KHR_binary_glTF (glTF 1.0)}
   * </li><li>
   * {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/1.0/Khronos/KHR_materials_common/README.md|KHR_materials_common (glTF 1.0)}
   * </li><li>
   * {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/1.0/Vendor/WEB3D_quantized_attributes/README.md|WEB3D_quantized_attributes (glTF 1.0)}
   * </li><li>
   * {@link https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/AGI_articulations/README.md|AGI_articulations}
   * </li><li>
   * {@link https://github.com/KhronosGroup/glTF/pull/1302|KHR_blend (draft)}
   * </li><li>
   * {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_draco_mesh_compression/README.md|KHR_draco_mesh_compression}
   * </li><li>
   * {@link https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness/README.md|KHR_materials_pbrSpecularGlossiness}
   * </li><li>
   * {@link https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit/README.md|KHR_materials_unlit}
   * </li><li>
   * {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_techniques_webgl/README.md|KHR_techniques_webgl}
   * </li><li>
   * {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_texture_transform/README.md|KHR_texture_transform}
   * </li><li>
   * {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_texture_basisu/README.md|KHR_texture_basisu}
   * </li>
   * </ul>
   * </p>
   * <p>
   * For high-precision rendering, Cesium supports the {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/1.0/Vendor/CESIUM_RTC/README.md|CESIUM_RTC} extension, which introduces the
   * CESIUM_RTC_MODELVIEW parameter semantic that says the node is in WGS84 coordinates translated
   * relative to a local origin.
   * </p>
   *
   * @param {Object} options Object with the following properties:
   * @param {Resource|String} options.url The url to the .gltf file.
   * @param {Resource|String} [options.basePath] The base path that paths in the glTF JSON are relative to.
   * @param {Boolean} [options.show=true] Determines if the model primitive will be shown.
   * @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] The 4x4 transformation matrix that transforms the model from model to world coordinates.
   * @param {Number} [options.scale=1.0] A uniform scale applied to this model.
   * @param {Number} [options.minimumPixelSize=0.0] The approximate minimum pixel size of the model regardless of zoom.
   * @param {Number} [options.maximumScale] The maximum scale for the model.
   * @param {Object} [options.id] A user-defined object to return when the model is picked with {@link Scene#pick}.
   * @param {Boolean} [options.allowPicking=true] When <code>true</code>, each glTF mesh and primitive is pickable with {@link Scene#pick}.
   * @param {Boolean} [options.incrementallyLoadTextures=true] Determine if textures may continue to stream in after the model is loaded.
   * @param {Boolean} [options.asynchronous=true] Determines if model WebGL resource creation will be spread out over several frames or block until completion once all glTF files are loaded.
   * @param {Boolean} [options.clampAnimations=true] Determines if the model's animations should hold a pose over frames where no keyframes are specified.
   * @param {ShadowMode} [options.shadows=ShadowMode.ENABLED] Determines whether the model casts or receives shadows from light sources.
   * @param {Boolean} [options.debugShowBoundingVolume=false] For debugging only. Draws the bounding sphere for each draw command in the model.
   * @param {Boolean} [options.debugWireframe=false] For debugging only. Draws the model in wireframe.
   * @param {HeightReference} [options.heightReference=HeightReference.NONE] Determines how the model is drawn relative to terrain.
   * @param {Scene} [options.scene] Must be passed in for models that use the height reference property.
   * @param {DistanceDisplayCondition} [options.distanceDisplayCondition] The condition specifying at what distance from the camera that this model will be displayed.
   * @param {Color} [options.color=Color.WHITE] A color that blends with the model's rendered color.
   * @param {ColorBlendMode} [options.colorBlendMode=ColorBlendMode.HIGHLIGHT] Defines how the color blends with the model.
   * @param {Number} [options.colorBlendAmount=0.5] Value used to determine the color strength when the <code>colorBlendMode</code> is <code>MIX</code>. A value of 0.0 results in the model's rendered color while a value of 1.0 results in a solid color, with any value in-between resulting in a mix of the two.
   * @param {Color} [options.silhouetteColor=Color.RED] The silhouette color. If more than 256 models have silhouettes enabled, there is a small chance that overlapping models will have minor artifacts.
   * @param {Number} [options.silhouetteSize=0.0] The size of the silhouette in pixels.
   * @param {ClippingPlaneCollection} [options.clippingPlanes] The {@link ClippingPlaneCollection} used to selectively disable rendering the model.
   * @param {Boolean} [options.dequantizeInShader=true] Determines if a {@link https://github.com/google/draco|Draco} encoded model is dequantized on the GPU. This decreases total memory usage for encoded models. Deprecated in CesiumJS 1.94, will be removed in CesiumJS 1.96.
   * @param {Cartesian3} [options.lightColor] The light color when shading the model. When <code>undefined</code> the scene's light color is used instead.
   * @param {ImageBasedLighting} [options.imageBasedLighting] The properties for managing image-based lighting for this tileset.
   * @param {Credit|String} [options.credit] A credit for the model, which is displayed on the canvas.
   * @param {Boolean} [options.showCreditsOnScreen=false] Whether to display the credits of this model on screen.
   * @param {Boolean} [options.backFaceCulling=true] Whether to cull back-facing geometry. When true, back face culling is determined by the material's doubleSided property; when false, back face culling is disabled. Back faces are not culled if {@link Model#color} is translucent or {@link Model#silhouetteSize} is greater than 0.0.
   * @param {Boolean} [options.showOutline=true] Whether to display the outline for models using the {@link https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/CESIUM_primitive_outline|CESIUM_primitive_outline} extension. When true, outlines are displayed. When false, outlines are not displayed.
   * @returns {Model} The newly created model.
   *
   * @example
   * // Example 1. Create a model from a glTF asset
   * const model = scene.primitives.add(Cesium.Model.fromGltf({
   *   url : './duck/duck.gltf'
   * }));
   *
   * @example
   * // Example 2. Create model and provide all properties and events
   * const origin = Cesium.Cartesian3.fromDegrees(-95.0, 40.0, 200000.0);
   * const modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(origin);
   *
   * const model = scene.primitives.add(Cesium.Model.fromGltf({
   *   url : './duck/duck.gltf',
   *   show : true,                     // default
   *   modelMatrix : modelMatrix,
   *   scale : 2.0,                     // double size
   *   minimumPixelSize : 128,          // never smaller than 128 pixels
   *   maximumScale: 20000,             // never larger than 20000 * model size (overrides minimumPixelSize)
   *   allowPicking : false,            // not pickable
   *   debugShowBoundingVolume : false, // default
   *   debugWireframe : false
   * }));
   *
   * model.readyPromise.then(function(model) {
   *   // Play all animations when the model is ready to render
   *   model.activeAnimations.addAll();
   * });
   */
  Model.fromGltf = function (options) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(options) || !defined(options.url)) {
      throw new DeveloperError("options.url is required");
    }
    //>>includeEnd('debug');

    const url = options.url;
    options = clone$1(options);

    // Create resource for the model file
    const modelResource = Resource.createIfNeeded(url);

    // Setup basePath to get dependent files
    const basePath = defaultValue(options.basePath, modelResource.clone());
    const resource = Resource.createIfNeeded(basePath);

    // If no cache key is provided, use a GUID.
    // Check using a URI to GUID dictionary that we have not already added this model.
    let cacheKey = defaultValue(
      options.cacheKey,
      uriToGuid[getAbsoluteUri(modelResource.url)]
    );
    if (!defined(cacheKey)) {
      cacheKey = createGuid();
      uriToGuid[getAbsoluteUri(modelResource.url)] = cacheKey;
    }

    if (defined(options.basePath) && !defined(options.cacheKey)) {
      cacheKey += resource.url;
    }
    options.cacheKey = cacheKey;
    options.basePath = resource;

    const model = new Model(options);

    let cachedGltf = gltfCache[cacheKey];
    if (!defined(cachedGltf)) {
      cachedGltf = new CachedGltf({
        ready: false,
      });
      cachedGltf.count = 1;
      cachedGltf.modelsToLoad.push(model);
      setCachedGltf(model, cachedGltf);
      gltfCache[cacheKey] = cachedGltf;

      // Add Accept header if we need it
      if (!defined(modelResource.headers.Accept)) {
        modelResource.headers.Accept = defaultModelAccept;
      }

      modelResource
        .fetchArrayBuffer()
        .then(function (arrayBuffer) {
          const array = new Uint8Array(arrayBuffer);
          if (containsGltfMagic(array)) {
            // Load binary glTF
            const parsedGltf = parseGlb(array);
            cachedGltf.makeReady(parsedGltf);
          } else {
            // Load text (JSON) glTF
            const json = getJsonFromTypedArray(array);
            cachedGltf.makeReady(json);
          }

          const resourceCredits = model._resourceCredits;
          const credits = modelResource.credits;
          if (defined(credits)) {
            const length = credits.length;
            for (let i = 0; i < length; i++) {
              resourceCredits.push(credits[i]);
            }
          }
        })
        .catch(
          ModelUtility.getFailedLoadFunction(model, "model", modelResource.url)
        );
    } else if (!cachedGltf.ready) {
      // Cache hit but the fetchArrayBuffer() or fetchText() request is still pending
      ++cachedGltf.count;
      cachedGltf.modelsToLoad.push(model);
    }
    // else if the cached glTF is defined and ready, the
    // model constructor will pick it up using the cache key.

    return model;
  };

  /**
   * For the unit tests to verify model caching.
   *
   * @private
   */
  Model._gltfCache = gltfCache;

  function getRuntime(model, runtimeName, name) {
    //>>includeStart('debug', pragmas.debug);
    if (model._state !== ModelState.LOADED) {
      throw new DeveloperError(
        "The model is not loaded.  Use Model.readyPromise or wait for Model.ready to be true."
      );
    }

    if (!defined(name)) {
      throw new DeveloperError("name is required.");
    }
    //>>includeEnd('debug');

    return model._runtime[runtimeName][name];
  }

  /**
   * Returns the glTF node with the given <code>name</code> property.  This is used to
   * modify a node's transform for animation outside of glTF animations.
   *
   * @param {String} name The glTF name of the node.
   * @returns {ModelNode} The node or <code>undefined</code> if no node with <code>name</code> exists.
   *
   * @exception {DeveloperError} The model is not loaded.  Use Model.readyPromise or wait for Model.ready to be true.
   *
   * @example
   * // Apply non-uniform scale to node LOD3sp
   * const node = model.getNode('LOD3sp');
   * node.matrix = Cesium.Matrix4.fromScale(new Cesium.Cartesian3(5.0, 1.0, 1.0), node.matrix);
   */
  Model.prototype.getNode = function (name) {
    const node = getRuntime(this, "nodesByName", name);
    return defined(node) ? node.publicNode : undefined;
  };

  /**
   * Returns the glTF mesh with the given <code>name</code> property.
   *
   * @param {String} name The glTF name of the mesh.
   *
   * @returns {ModelMesh} The mesh or <code>undefined</code> if no mesh with <code>name</code> exists.
   *
   * @exception {DeveloperError} The model is not loaded.  Use Model.readyPromise or wait for Model.ready to be true.
   */
  Model.prototype.getMesh = function (name) {
    return getRuntime(this, "meshesByName", name);
  };

  /**
   * Returns the glTF material with the given <code>name</code> property.
   *
   * @param {String} name The glTF name of the material.
   * @returns {ModelMaterial} The material or <code>undefined</code> if no material with <code>name</code> exists.
   *
   * @exception {DeveloperError} The model is not loaded.  Use Model.readyPromise or wait for Model.ready to be true.
   */
  Model.prototype.getMaterial = function (name) {
    return getRuntime(this, "materialsByName", name);
  };

  /**
   * Sets the current value of an articulation stage.  After setting one or multiple stage values, call
   * Model.applyArticulations() to cause the node matrices to be recalculated.
   *
   * @param {String} articulationStageKey The name of the articulation, a space, and the name of the stage.
   * @param {Number} value The numeric value of this stage of the articulation.
   *
   * @exception {DeveloperError} The model is not loaded.  Use Model.readyPromise or wait for Model.ready to be true.
   *
   * @see Model#applyArticulations
   */
  Model.prototype.setArticulationStage = function (articulationStageKey, value) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("value", value);
    //>>includeEnd('debug');

    const stage = getRuntime(this, "stagesByKey", articulationStageKey);
    const articulation = getRuntime(
      this,
      "articulationsByStageKey",
      articulationStageKey
    );
    if (defined(stage) && defined(articulation)) {
      value = CesiumMath.clamp(value, stage.minimumValue, stage.maximumValue);
      if (
        !CesiumMath.equalsEpsilon(stage.currentValue, value, articulationEpsilon$1)
      ) {
        stage.currentValue = value;
        articulation.isDirty = true;
      }
    }
  };

  const scratchArticulationCartesian$1 = new Cartesian3();
  const scratchArticulationRotation$1 = new Matrix3();

  /**
   * Modifies a Matrix4 by applying a transformation for a given value of a stage.  Note this is different usage
   * from the typical <code>result</code> parameter, in that the incoming value of <code>result</code> is
   * meaningful.  Various stages of an articulation can be multiplied together, so their
   * transformations are all merged into a composite Matrix4 representing them all.
   *
   * @param {object} stage The stage of an articulation that is being evaluated.
   * @param {Matrix4} result The matrix to be modified.
   * @returns {Matrix4} A matrix transformed as requested by the articulation stage.
   *
   * @private
   */
  function applyArticulationStageMatrix(stage, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("stage", stage);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const value = stage.currentValue;
    const cartesian = scratchArticulationCartesian$1;
    let rotation;
    switch (stage.type) {
      case "xRotate":
        rotation = Matrix3.fromRotationX(
          CesiumMath.toRadians(value),
          scratchArticulationRotation$1
        );
        Matrix4.multiplyByMatrix3(result, rotation, result);
        break;
      case "yRotate":
        rotation = Matrix3.fromRotationY(
          CesiumMath.toRadians(value),
          scratchArticulationRotation$1
        );
        Matrix4.multiplyByMatrix3(result, rotation, result);
        break;
      case "zRotate":
        rotation = Matrix3.fromRotationZ(
          CesiumMath.toRadians(value),
          scratchArticulationRotation$1
        );
        Matrix4.multiplyByMatrix3(result, rotation, result);
        break;
      case "xTranslate":
        cartesian.x = value;
        cartesian.y = 0.0;
        cartesian.z = 0.0;
        Matrix4.multiplyByTranslation(result, cartesian, result);
        break;
      case "yTranslate":
        cartesian.x = 0.0;
        cartesian.y = value;
        cartesian.z = 0.0;
        Matrix4.multiplyByTranslation(result, cartesian, result);
        break;
      case "zTranslate":
        cartesian.x = 0.0;
        cartesian.y = 0.0;
        cartesian.z = value;
        Matrix4.multiplyByTranslation(result, cartesian, result);
        break;
      case "xScale":
        cartesian.x = value;
        cartesian.y = 1.0;
        cartesian.z = 1.0;
        Matrix4.multiplyByScale(result, cartesian, result);
        break;
      case "yScale":
        cartesian.x = 1.0;
        cartesian.y = value;
        cartesian.z = 1.0;
        Matrix4.multiplyByScale(result, cartesian, result);
        break;
      case "zScale":
        cartesian.x = 1.0;
        cartesian.y = 1.0;
        cartesian.z = value;
        Matrix4.multiplyByScale(result, cartesian, result);
        break;
      case "uniformScale":
        Matrix4.multiplyByUniformScale(result, value, result);
        break;
    }
    return result;
  }

  const scratchApplyArticulationTransform = new Matrix4();

  /**
   * Applies any modified articulation stages to the matrix of each node that participates
   * in any articulation.  Note that this will overwrite any nodeTransformations on participating nodes.
   *
   * @exception {DeveloperError} The model is not loaded.  Use Model.readyPromise or wait for Model.ready to be true.
   */
  Model.prototype.applyArticulations = function () {
    const articulationsByName = this._runtime.articulationsByName;
    for (const articulationName in articulationsByName) {
      if (articulationsByName.hasOwnProperty(articulationName)) {
        const articulation = articulationsByName[articulationName];
        if (articulation.isDirty) {
          articulation.isDirty = false;
          const numNodes = articulation.nodes.length;
          for (let n = 0; n < numNodes; ++n) {
            const node = articulation.nodes[n];
            let transform = Matrix4.clone(
              node.originalMatrix,
              scratchApplyArticulationTransform
            );

            const numStages = articulation.stages.length;
            for (let s = 0; s < numStages; ++s) {
              const stage = articulation.stages[s];
              transform = applyArticulationStageMatrix(stage, transform);
            }
            node.matrix = transform;
          }
        }
      }
    }
  };

  ///////////////////////////////////////////////////////////////////////////

  function addBuffersToLoadResources(model) {
    const gltf = model.gltfInternal;
    const loadResources = model._loadResources;
    ForEach.buffer(gltf, function (buffer, id) {
      loadResources.buffers[id] = buffer.extras._pipeline.source;
    });
  }

  function bufferLoad(model, id) {
    return function (arrayBuffer) {
      const loadResources = model._loadResources;
      const buffer = new Uint8Array(arrayBuffer);
      --loadResources.pendingBufferLoads;
      model.gltfInternal.buffers[id].extras._pipeline.source = buffer;
    };
  }

  function parseBufferViews(model) {
    const bufferViews = model.gltfInternal.bufferViews;
    const vertexBuffersToCreate = model._loadResources.vertexBuffersToCreate;

    // Only ARRAY_BUFFER here.  ELEMENT_ARRAY_BUFFER created below.
    ForEach.bufferView(model.gltfInternal, function (bufferView, id) {
      if (bufferView.target === WebGLConstants$1.ARRAY_BUFFER) {
        vertexBuffersToCreate.enqueue(id);
      }
    });

    const indexBuffersToCreate = model._loadResources.indexBuffersToCreate;
    const indexBufferIds = {};

    // The Cesium Renderer requires knowing the datatype for an index buffer
    // at creation type, which is not part of the glTF bufferview so loop
    // through glTF accessors to create the bufferview's index buffer.
    ForEach.accessor(model.gltfInternal, function (accessor) {
      const bufferViewId = accessor.bufferView;
      if (!defined(bufferViewId)) {
        return;
      }

      const bufferView = bufferViews[bufferViewId];
      if (
        bufferView.target === WebGLConstants$1.ELEMENT_ARRAY_BUFFER &&
        !defined(indexBufferIds[bufferViewId])
      ) {
        indexBufferIds[bufferViewId] = true;
        indexBuffersToCreate.enqueue({
          id: bufferViewId,
          componentType: accessor.componentType,
        });
      }
    });
  }

  function parseTechniques(model) {
    // retain references to gltf techniques
    const gltf = model.gltfInternal;
    if (!usesExtension(gltf, "KHR_techniques_webgl")) {
      return;
    }

    const sourcePrograms = model._sourcePrograms;
    const sourceTechniques = model._sourceTechniques;
    const programs = gltf.extensions.KHR_techniques_webgl.programs;

    ForEach.technique(gltf, function (technique, techniqueId) {
      sourceTechniques[techniqueId] = clone$1(technique);

      const programId = technique.program;
      if (!defined(sourcePrograms[programId])) {
        sourcePrograms[programId] = clone$1(programs[programId]);
      }
    });
  }

  function shaderLoad(model, type, id) {
    return function (source) {
      const loadResources = model._loadResources;
      loadResources.shaders[id] = {
        source: source,
        type: type,
        bufferView: undefined,
      };
      --loadResources.pendingShaderLoads;
      model._rendererResources.sourceShaders[id] = source;
    };
  }

  function parseShaders(model) {
    const gltf = model.gltfInternal;
    const buffers = gltf.buffers;
    const bufferViews = gltf.bufferViews;
    const sourceShaders = model._rendererResources.sourceShaders;
    ForEach.shader(gltf, function (shader, id) {
      // Shader references either uri (external or base64-encoded) or bufferView
      if (defined(shader.bufferView)) {
        const bufferViewId = shader.bufferView;
        const bufferView = bufferViews[bufferViewId];
        const bufferId = bufferView.buffer;
        const buffer = buffers[bufferId];
        const source = getStringFromTypedArray(
          buffer.extras._pipeline.source,
          bufferView.byteOffset,
          bufferView.byteLength
        );
        sourceShaders[id] = source;
      } else if (defined(shader.extras._pipeline.source)) {
        sourceShaders[id] = shader.extras._pipeline.source;
      } else {
        ++model._loadResources.pendingShaderLoads;

        const shaderResource = model._resource.getDerivedResource({
          url: shader.uri,
        });

        shaderResource
          .fetchText()
          .then(shaderLoad(model, shader.type, id))
          .catch(
            ModelUtility.getFailedLoadFunction(
              model,
              "shader",
              shaderResource.url
            )
          );
      }
    });
  }

  function parsePrograms(model) {
    const sourceTechniques = model._sourceTechniques;
    for (const techniqueId in sourceTechniques) {
      if (sourceTechniques.hasOwnProperty(techniqueId)) {
        const technique = sourceTechniques[techniqueId];
        model._loadResources.programsToCreate.enqueue({
          programId: technique.program,
          techniqueId: techniqueId,
        });
      }
    }
  }

  function parseArticulations(model) {
    const articulationsByName = {};
    const articulationsByStageKey = {};
    const runtimeStagesByKey = {};

    model._runtime.articulationsByName = articulationsByName;
    model._runtime.articulationsByStageKey = articulationsByStageKey;
    model._runtime.stagesByKey = runtimeStagesByKey;

    const gltf = model.gltfInternal;
    if (
      !usesExtension(gltf, "AGI_articulations") ||
      !defined(gltf.extensions) ||
      !defined(gltf.extensions.AGI_articulations)
    ) {
      return;
    }

    const gltfArticulations = gltf.extensions.AGI_articulations.articulations;
    if (!defined(gltfArticulations)) {
      return;
    }

    const numArticulations = gltfArticulations.length;
    for (let i = 0; i < numArticulations; ++i) {
      const articulation = clone$1(gltfArticulations[i]);
      articulation.nodes = [];
      articulation.isDirty = true;
      articulationsByName[articulation.name] = articulation;

      const numStages = articulation.stages.length;
      for (let s = 0; s < numStages; ++s) {
        const stage = articulation.stages[s];
        stage.currentValue = stage.initialValue;

        const stageKey = `${articulation.name} ${stage.name}`;
        articulationsByStageKey[stageKey] = articulation;
        runtimeStagesByKey[stageKey] = stage;
      }
    }
  }

  function imageLoad(model, textureId) {
    return function (image) {
      const loadResources = model._loadResources;
      --loadResources.pendingTextureLoads;

      // Images transcoded from KTX2 can contain multiple mip levels:
      // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu
      let mipLevels;
      if (Array.isArray(image)) {
        // highest detail mip should be level 0
        mipLevels = image.slice(1, image.length).map(function (mipLevel) {
          return mipLevel.bufferView;
        });
        image = image[0];
      }

      loadResources.texturesToCreate.enqueue({
        id: textureId,
        image: image,
        bufferView: image.bufferView,
        width: image.width,
        height: image.height,
        internalFormat: image.internalFormat,
        mipLevels: mipLevels,
      });
    };
  }

  const ktx2Regex$2 = /(^data:image\/ktx2)|(\.ktx2$)/i;

  function parseTextures(model, context, supportsWebP) {
    const gltf = model.gltfInternal;
    const images = gltf.images;
    let uri;
    ForEach.texture(gltf, function (texture, id) {
      let imageId = texture.source;

      if (
        defined(texture.extensions) &&
        defined(texture.extensions.EXT_texture_webp) &&
        supportsWebP
      ) {
        imageId = texture.extensions.EXT_texture_webp.source;
      } else if (
        defined(texture.extensions) &&
        defined(texture.extensions.KHR_texture_basisu) &&
        context.supportsBasis
      ) {
        imageId = texture.extensions.KHR_texture_basisu.source;
      }

      const gltfImage = images[imageId];

      const bufferViewId = gltfImage.bufferView;
      const mimeType = gltfImage.mimeType;
      uri = gltfImage.uri;

      // Image references either uri (external or base64-encoded) or bufferView
      if (defined(bufferViewId)) {
        model._loadResources.texturesToCreateFromBufferView.enqueue({
          id: id,
          image: undefined,
          bufferView: bufferViewId,
          mimeType: mimeType,
        });
      } else {
        ++model._loadResources.pendingTextureLoads;

        const imageResource = model._resource.getDerivedResource({
          url: uri,
        });

        let promise;
        if (ktx2Regex$2.test(uri)) {
          promise = loadKTX2(imageResource);
        } else {
          promise = imageResource.fetchImage({
            skipColorSpaceConversion: true,
            preferImageBitmap: true,
          });
        }
        promise
          .then(imageLoad(model, id))
          .catch(
            ModelUtility.getFailedLoadFunction(model, "image", imageResource.url)
          );
      }
    });
  }

  const scratchArticulationStageInitialTransform = new Matrix4();

  function parseNodes(model) {
    const runtimeNodes = {};
    const runtimeNodesByName = {};
    const skinnedNodes = [];

    const skinnedNodesIds = model._loadResources.skinnedNodesIds;
    const articulationsByName = model._runtime.articulationsByName;

    ForEach.node(model.gltfInternal, function (node, id) {
      const runtimeNode = {
        // Animation targets
        matrix: undefined,
        translation: undefined,
        rotation: undefined,
        scale: undefined,

        // Per-node show inherited from parent
        computedShow: true,

        // Computed transforms
        transformToRoot: new Matrix4(),
        computedMatrix: new Matrix4(),
        dirtyNumber: 0, // The frame this node was made dirty by an animation; for graph traversal

        // Rendering
        commands: [], // empty for transform, light, and camera nodes

        // Skinned node
        inverseBindMatrices: undefined, // undefined when node is not skinned
        bindShapeMatrix: undefined, // undefined when node is not skinned or identity
        joints: [], // empty when node is not skinned
        computedJointMatrices: [], // empty when node is not skinned

        // Joint node
        jointName: node.jointName, // undefined when node is not a joint

        weights: [],

        // Graph pointers
        children: [], // empty for leaf nodes
        parents: [], // empty for root nodes

        // Publicly-accessible ModelNode instance to modify animation targets
        publicNode: undefined,
      };
      runtimeNode.publicNode = new ModelNode(
        model,
        node,
        runtimeNode,
        id,
        ModelUtility.getTransform(node)
      );

      runtimeNodes[id] = runtimeNode;
      runtimeNodesByName[node.name] = runtimeNode;

      if (defined(node.skin)) {
        skinnedNodesIds.push(id);
        skinnedNodes.push(runtimeNode);
      }

      if (
        defined(node.extensions) &&
        defined(node.extensions.AGI_articulations)
      ) {
        const articulationName =
          node.extensions.AGI_articulations.articulationName;
        if (defined(articulationName)) {
          let transform = Matrix4.clone(
            runtimeNode.publicNode.originalMatrix,
            scratchArticulationStageInitialTransform
          );
          const articulation = articulationsByName[articulationName];
          articulation.nodes.push(runtimeNode.publicNode);

          const numStages = articulation.stages.length;
          for (let s = 0; s < numStages; ++s) {
            const stage = articulation.stages[s];
            transform = applyArticulationStageMatrix(stage, transform);
          }
          runtimeNode.publicNode.matrix = transform;
        }
      }
    });

    model._runtime.nodes = runtimeNodes;
    model._runtime.nodesByName = runtimeNodesByName;
    model._runtime.skinnedNodes = skinnedNodes;
  }

  function parseMaterials(model) {
    const gltf = model.gltfInternal;
    const techniques = model._sourceTechniques;

    const runtimeMaterialsByName = {};
    const runtimeMaterialsById = {};
    const uniformMaps = model._uniformMaps;

    ForEach.material(gltf, function (material, materialId) {
      // Allocated now so ModelMaterial can keep a reference to it.
      uniformMaps[materialId] = {
        uniformMap: undefined,
        values: undefined,
        jointMatrixUniformName: undefined,
        morphWeightsUniformName: undefined,
      };

      const modelMaterial = new ModelMaterial(model, material, materialId);

      if (
        defined(material.extensions) &&
        defined(material.extensions.KHR_techniques_webgl)
      ) {
        const techniqueId = material.extensions.KHR_techniques_webgl.technique;
        modelMaterial._technique = techniqueId;
        modelMaterial._program = techniques[techniqueId].program;

        ForEach.materialValue(material, function (value, uniformName) {
          if (!defined(modelMaterial._values)) {
            modelMaterial._values = {};
          }

          modelMaterial._values[uniformName] = clone$1(value);
        });
      }

      runtimeMaterialsByName[material.name] = modelMaterial;
      runtimeMaterialsById[materialId] = modelMaterial;
    });

    model._runtime.materialsByName = runtimeMaterialsByName;
    model._runtime.materialsById = runtimeMaterialsById;
  }

  function parseMeshes(model) {
    const runtimeMeshesByName = {};
    const runtimeMaterialsById = model._runtime.materialsById;

    ForEach.mesh(model.gltfInternal, function (mesh, meshId) {
      runtimeMeshesByName[mesh.name] = new ModelMesh(
        mesh,
        runtimeMaterialsById,
        meshId
      );
      if (
        defined(model.extensionsUsed.WEB3D_quantized_attributes) ||
        model._dequantizeInShader
      ) {
        // Cache primitives according to their program
        ForEach.meshPrimitive(mesh, function (primitive, primitiveId) {
          const programId = getProgramForPrimitive(model, primitive);
          let programPrimitives = model._programPrimitives[programId];
          if (!defined(programPrimitives)) {
            programPrimitives = {};
            model._programPrimitives[programId] = programPrimitives;
          }
          programPrimitives[`${meshId}.primitive.${primitiveId}`] = primitive;
        });
      }
    });

    model._runtime.meshesByName = runtimeMeshesByName;
  }

  function parseCredits(model) {
    const asset = model.gltfInternal.asset;
    const copyright = asset.copyright;
    if (!defined(copyright)) {
      return;
    }

    const showOnScreen = model._showCreditsOnScreen;
    const credits = copyright.split(";").map(function (string) {
      return new Credit(string.trim(), showOnScreen);
    });

    model._gltfCredits = credits;
  }

  ///////////////////////////////////////////////////////////////////////////

  const CreateVertexBufferJob$1 = function () {
    this.id = undefined;
    this.model = undefined;
    this.context = undefined;
  };

  CreateVertexBufferJob$1.prototype.set = function (id, model, context) {
    this.id = id;
    this.model = model;
    this.context = context;
  };

  CreateVertexBufferJob$1.prototype.execute = function () {
    createVertexBuffer$3(this.id, this.model, this.context);
  };

  ///////////////////////////////////////////////////////////////////////////

  function createVertexBuffer$3(bufferViewId, model, context) {
    const loadResources = model._loadResources;
    const bufferViews = model.gltfInternal.bufferViews;
    let bufferView = bufferViews[bufferViewId];

    // Use bufferView created at runtime
    if (!defined(bufferView)) {
      bufferView = loadResources.createdBufferViews[bufferViewId];
    }

    const vertexBuffer = Buffer$1.createVertexBuffer({
      context: context,
      typedArray: loadResources.getBuffer(bufferView),
      usage: BufferUsage$1.STATIC_DRAW,
    });
    vertexBuffer.vertexArrayDestroyable = false;
    model._rendererResources.buffers[bufferViewId] = vertexBuffer;
    model._geometryByteLength += vertexBuffer.sizeInBytes;
  }

  ///////////////////////////////////////////////////////////////////////////

  const CreateIndexBufferJob$1 = function () {
    this.id = undefined;
    this.componentType = undefined;
    this.model = undefined;
    this.context = undefined;
  };

  CreateIndexBufferJob$1.prototype.set = function (
    id,
    componentType,
    model,
    context
  ) {
    this.id = id;
    this.componentType = componentType;
    this.model = model;
    this.context = context;
  };

  CreateIndexBufferJob$1.prototype.execute = function () {
    createIndexBuffer$1(this.id, this.componentType, this.model, this.context);
  };

  ///////////////////////////////////////////////////////////////////////////

  function createIndexBuffer$1(bufferViewId, componentType, model, context) {
    const loadResources = model._loadResources;
    const bufferViews = model.gltfInternal.bufferViews;
    let bufferView = bufferViews[bufferViewId];

    // Use bufferView created at runtime
    if (!defined(bufferView)) {
      bufferView = loadResources.createdBufferViews[bufferViewId];
    }

    const indexBuffer = Buffer$1.createIndexBuffer({
      context: context,
      typedArray: loadResources.getBuffer(bufferView),
      usage: BufferUsage$1.STATIC_DRAW,
      indexDatatype: componentType,
    });
    indexBuffer.vertexArrayDestroyable = false;
    model._rendererResources.buffers[bufferViewId] = indexBuffer;
    model._geometryByteLength += indexBuffer.sizeInBytes;
  }

  const scratchVertexBufferJob = new CreateVertexBufferJob$1();
  const scratchIndexBufferJob$1 = new CreateIndexBufferJob$1();

  function createBuffers(model, frameState) {
    const loadResources = model._loadResources;

    if (loadResources.pendingBufferLoads !== 0) {
      return;
    }

    const context = frameState.context;
    const vertexBuffersToCreate = loadResources.vertexBuffersToCreate;
    const indexBuffersToCreate = loadResources.indexBuffersToCreate;
    let i;

    if (model.asynchronous) {
      while (vertexBuffersToCreate.length > 0) {
        scratchVertexBufferJob.set(vertexBuffersToCreate.peek(), model, context);
        if (
          !frameState.jobScheduler.execute(scratchVertexBufferJob, JobType$1.BUFFER)
        ) {
          break;
        }
        vertexBuffersToCreate.dequeue();
      }

      while (indexBuffersToCreate.length > 0) {
        i = indexBuffersToCreate.peek();
        scratchIndexBufferJob$1.set(i.id, i.componentType, model, context);
        if (
          !frameState.jobScheduler.execute(scratchIndexBufferJob$1, JobType$1.BUFFER)
        ) {
          break;
        }
        indexBuffersToCreate.dequeue();
      }
    } else {
      while (vertexBuffersToCreate.length > 0) {
        createVertexBuffer$3(vertexBuffersToCreate.dequeue(), model, context);
      }

      while (indexBuffersToCreate.length > 0) {
        i = indexBuffersToCreate.dequeue();
        createIndexBuffer$1(i.id, i.componentType, model, context);
      }
    }
  }

  function getProgramForPrimitive(model, primitive) {
    const material = model._runtime.materialsById[primitive.material];
    if (!defined(material)) {
      return;
    }

    return material._program;
  }

  function modifyShaderForQuantizedAttributes(shader, programName, model) {
    let primitive;
    const primitives = model._programPrimitives[programName];

    // If no primitives were cached for this program, there's no need to modify the shader
    if (!defined(primitives)) {
      return shader;
    }

    let primitiveId;
    for (primitiveId in primitives) {
      if (primitives.hasOwnProperty(primitiveId)) {
        primitive = primitives[primitiveId];
        if (getProgramForPrimitive(model, primitive) === programName) {
          break;
        }
      }
    }

    // This is not needed after the program is processed, free the memory
    model._programPrimitives[programName] = undefined;

    let result;
    if (model.extensionsUsed.WEB3D_quantized_attributes) {
      result = ModelUtility.modifyShaderForQuantizedAttributes(
        model.gltfInternal,
        primitive,
        shader
      );
      model._quantizedUniforms[programName] = result.uniforms;
    } else {
      const decodedData = model._decodedData[primitiveId];
      if (defined(decodedData)) {
        result = ModelUtility.modifyShaderForDracoQuantizedAttributes(
          model.gltfInternal,
          primitive,
          shader,
          decodedData.attributes
        );
      } else {
        return shader;
      }
    }

    return result.shader;
  }

  function modifyShaderForColor(shader) {
    shader = ShaderSource.replaceMain(shader, "gltf_blend_main");
    shader +=
      "uniform vec4 gltf_color; \n" +
      "uniform float gltf_colorBlend; \n" +
      "void main() \n" +
      "{ \n" +
      "    gltf_blend_main(); \n" +
      "    gl_FragColor.rgb = mix(gl_FragColor.rgb, gltf_color.rgb, gltf_colorBlend); \n" +
      "    float highlight = ceil(gltf_colorBlend); \n" +
      "    gl_FragColor.rgb *= mix(gltf_color.rgb, vec3(1.0), highlight); \n" +
      "    gl_FragColor.a *= gltf_color.a; \n" +
      "} \n";

    return shader;
  }

  function modifyShader(shader, programName, callback) {
    if (defined(callback)) {
      shader = callback(shader, programName);
    }
    return shader;
  }

  const CreateProgramJob = function () {
    this.programToCreate = undefined;
    this.model = undefined;
    this.context = undefined;
  };

  CreateProgramJob.prototype.set = function (programToCreate, model, context) {
    this.programToCreate = programToCreate;
    this.model = model;
    this.context = context;
  };

  CreateProgramJob.prototype.execute = function () {
    createProgram(this.programToCreate, this.model, this.context);
  };

  ///////////////////////////////////////////////////////////////////////////

  // When building programs for the first time, do not include modifiers for clipping planes and color
  // since this is the version of the program that will be cached for use with other Models.
  function createProgram(programToCreate, model, context) {
    const programId = programToCreate.programId;
    const techniqueId = programToCreate.techniqueId;
    const program = model._sourcePrograms[programId];
    const shaders = model._rendererResources.sourceShaders;

    let vs = shaders[program.vertexShader];
    const fs = shaders[program.fragmentShader];

    const quantizedVertexShaders = model._quantizedVertexShaders;

    if (
      model.extensionsUsed.WEB3D_quantized_attributes ||
      model._dequantizeInShader
    ) {
      let quantizedVS = quantizedVertexShaders[programId];
      if (!defined(quantizedVS)) {
        quantizedVS = modifyShaderForQuantizedAttributes(vs, programId, model);
        quantizedVertexShaders[programId] = quantizedVS;
      }
      vs = quantizedVS;
    }

    const drawVS = modifyShader(vs, programId, model._vertexShaderLoaded);
    let drawFS = modifyShader(fs, programId, model._fragmentShaderLoaded);

    if (!defined(model._uniformMapLoaded)) {
      drawFS = `uniform vec4 czm_pickColor;\n${drawFS}`;
    }

    const imageBasedLighting = model._imageBasedLighting;
    const useIBL = imageBasedLighting.enabled;
    if (useIBL) {
      drawFS = `#define USE_IBL_LIGHTING \n\n${drawFS}`;
    }

    if (defined(model._lightColor)) {
      drawFS = `#define USE_CUSTOM_LIGHT_COLOR \n\n${drawFS}`;
    }

    if (model._sourceVersion !== "2.0" || model._sourceKHRTechniquesWebGL) {
      drawFS = ShaderSource.replaceMain(drawFS, "non_gamma_corrected_main");
      drawFS =
        `${drawFS}\n` +
        `void main() { \n` +
        `    non_gamma_corrected_main(); \n` +
        `    gl_FragColor = czm_gammaCorrect(gl_FragColor); \n` +
        `} \n`;
    }

    if (OctahedralProjectedCubeMap.isSupported(context)) {
      const useSHC = imageBasedLighting.useSphericalHarmonicCoefficients;
      const useSEM = imageBasedLighting.useSpecularEnvironmentMaps;
      const addMatrix = useSHC || useSEM || useIBL;
      if (addMatrix) {
        drawFS = `uniform mat3 gltf_iblReferenceFrameMatrix; \n${drawFS}`;
      }

      if (defined(imageBasedLighting.sphericalHarmonicCoefficients)) {
        drawFS = `${
        "#define DIFFUSE_IBL \n" +
        "#define CUSTOM_SPHERICAL_HARMONICS \n" +
        "uniform vec3 gltf_sphericalHarmonicCoefficients[9]; \n"
      }${drawFS}`;
      } else if (imageBasedLighting.useDefaultSphericalHarmonics) {
        drawFS = `#define DIFFUSE_IBL \n${drawFS}`;
      }

      if (
        defined(imageBasedLighting.specularEnvironmentMapAtlas) &&
        imageBasedLighting.specularEnvironmentMapAtlas.ready
      ) {
        drawFS = `${
        "#define SPECULAR_IBL \n" +
        "#define CUSTOM_SPECULAR_IBL \n" +
        "uniform sampler2D gltf_specularMap; \n" +
        "uniform vec2 gltf_specularMapSize; \n" +
        "uniform float gltf_maxSpecularLOD; \n"
      }${drawFS}`;
      } else if (imageBasedLighting.useDefaultSpecularMaps) {
        drawFS = `#define SPECULAR_IBL \n${drawFS}`;
      }
    }

    if (defined(imageBasedLighting.luminanceAtZenith)) {
      drawFS = `${
      "#define USE_SUN_LUMINANCE \n" + "uniform float gltf_luminanceAtZenith;\n"
    }${drawFS}`;
    }

    createAttributesAndProgram(
      programId,
      techniqueId,
      drawFS,
      drawVS,
      model,
      context
    );
  }

  function recreateProgram(programToCreate, model, context) {
    const programId = programToCreate.programId;
    const techniqueId = programToCreate.techniqueId;
    const program = model._sourcePrograms[programId];
    const shaders = model._rendererResources.sourceShaders;

    const quantizedVertexShaders = model._quantizedVertexShaders;

    const clippingPlaneCollection = model.clippingPlanes;
    const addClippingPlaneCode = isClippingEnabled(model);

    let vs = shaders[program.vertexShader];
    const fs = shaders[program.fragmentShader];

    if (
      model.extensionsUsed.WEB3D_quantized_attributes ||
      model._dequantizeInShader
    ) {
      vs = quantizedVertexShaders[programId];
    }

    let finalFS = fs;
    if (isColorShadingEnabled(model)) {
      finalFS = Model._modifyShaderForColor(finalFS);
    }
    if (addClippingPlaneCode) {
      finalFS = modifyShaderForClippingPlanes(
        finalFS,
        clippingPlaneCollection,
        context
      );
    }

    if (model.splitDirection !== SplitDirection$1.NONE) {
      finalFS = Splitter.modifyFragmentShader(finalFS);
    }

    const drawVS = modifyShader(vs, programId, model._vertexShaderLoaded);
    let drawFS = modifyShader(finalFS, programId, model._fragmentShaderLoaded);

    if (!defined(model._uniformMapLoaded)) {
      drawFS = `uniform vec4 czm_pickColor;\n${drawFS}`;
    }

    const imageBasedLighting = model._imageBasedLighting;
    const useIBL = imageBasedLighting.enabled;
    if (useIBL) {
      drawFS = `#define USE_IBL_LIGHTING \n\n${drawFS}`;
    }

    if (defined(model._lightColor)) {
      drawFS = `#define USE_CUSTOM_LIGHT_COLOR \n\n${drawFS}`;
    }

    if (model._sourceVersion !== "2.0" || model._sourceKHRTechniquesWebGL) {
      drawFS = ShaderSource.replaceMain(drawFS, "non_gamma_corrected_main");
      drawFS =
        `${drawFS}\n` +
        `void main() { \n` +
        `    non_gamma_corrected_main(); \n` +
        `    gl_FragColor = czm_gammaCorrect(gl_FragColor); \n` +
        `} \n`;
    }

    if (OctahedralProjectedCubeMap.isSupported(context)) {
      const useSHC = imageBasedLighting.useSphericalHarmonicCoefficients;
      const useSEM = imageBasedLighting.useSpecularEnvironmentMaps;
      const addMatrix = useSHC || useSEM || useIBL;
      if (addMatrix) {
        drawFS = `uniform mat3 gltf_iblReferenceFrameMatrix; \n${drawFS}`;
      }

      if (defined(imageBasedLighting.sphericalHarmonicCoefficients)) {
        drawFS = `${
        "#define DIFFUSE_IBL \n" +
        "#define CUSTOM_SPHERICAL_HARMONICS \n" +
        "uniform vec3 gltf_sphericalHarmonicCoefficients[9]; \n"
      }${drawFS}`;
      } else if (imageBasedLighting.useDefaultSphericalHarmonics) {
        drawFS = `#define DIFFUSE_IBL \n${drawFS}`;
      }

      if (
        defined(imageBasedLighting.specularEnvironmentMapAtlas) &&
        imageBasedLighting.specularEnvironmentMapAtlas.ready
      ) {
        drawFS = `${
        "#define SPECULAR_IBL \n" +
        "#define CUSTOM_SPECULAR_IBL \n" +
        "uniform sampler2D gltf_specularMap; \n" +
        "uniform vec2 gltf_specularMapSize; \n" +
        "uniform float gltf_maxSpecularLOD; \n"
      }${drawFS}`;
      } else if (imageBasedLighting.useDefaultSpecularMaps) {
        drawFS = `#define SPECULAR_IBL \n${drawFS}`;
      }
    }

    if (defined(imageBasedLighting.luminanceAtZenith)) {
      drawFS = `${
      "#define USE_SUN_LUMINANCE \n" + "uniform float gltf_luminanceAtZenith;\n"
    }${drawFS}`;
    }

    createAttributesAndProgram(
      programId,
      techniqueId,
      drawFS,
      drawVS,
      model,
      context
    );
  }

  function createAttributesAndProgram(
    programId,
    techniqueId,
    drawFS,
    drawVS,
    model,
    context
  ) {
    const technique = model._sourceTechniques[techniqueId];
    const attributeLocations = ModelUtility.createAttributeLocations(
      technique,
      model._precreatedAttributes
    );

    model._rendererResources.programs[programId] = ShaderProgram.fromCache({
      context: context,
      vertexShaderSource: drawVS,
      fragmentShaderSource: drawFS,
      attributeLocations: attributeLocations,
    });
  }

  const scratchCreateProgramJob = new CreateProgramJob();

  function createPrograms(model, frameState) {
    const loadResources = model._loadResources;
    const programsToCreate = loadResources.programsToCreate;

    if (loadResources.pendingShaderLoads !== 0) {
      return;
    }

    // PERFORMANCE_IDEA: this could be more fine-grained by looking
    // at the shader's bufferView's to determine the buffer dependencies.
    if (loadResources.pendingBufferLoads !== 0) {
      return;
    }

    const context = frameState.context;

    if (model.asynchronous) {
      while (programsToCreate.length > 0) {
        scratchCreateProgramJob.set(programsToCreate.peek(), model, context);
        if (
          !frameState.jobScheduler.execute(
            scratchCreateProgramJob,
            JobType$1.PROGRAM
          )
        ) {
          break;
        }
        programsToCreate.dequeue();
      }
    } else {
      // Create all loaded programs this frame
      while (programsToCreate.length > 0) {
        createProgram(programsToCreate.dequeue(), model, context);
      }
    }
  }

  function getOnImageCreatedFromTypedArray(loadResources, gltfTexture) {
    return function (image) {
      loadResources.texturesToCreate.enqueue({
        id: gltfTexture.id,
        image: image,
        bufferView: undefined,
      });

      --loadResources.pendingBufferViewToImage;
    };
  }

  function loadTexturesFromBufferViews(model) {
    const loadResources = model._loadResources;

    if (loadResources.pendingBufferLoads !== 0) {
      return;
    }

    while (loadResources.texturesToCreateFromBufferView.length > 0) {
      const gltfTexture = loadResources.texturesToCreateFromBufferView.dequeue();

      const gltf = model.gltfInternal;
      const bufferView = gltf.bufferViews[gltfTexture.bufferView];
      gltf.textures[gltfTexture.id].source;

      const onerror = ModelUtility.getFailedLoadFunction(
        model,
        "image",
        `id: ${gltfTexture.id}, bufferView: ${gltfTexture.bufferView}`
      );

      if (gltfTexture.mimeType === "image/ktx2") {
        // Need to make a copy of the embedded KTX2 buffer otherwise the underlying
        // ArrayBuffer may be accessed on both the worker and the main thread and
        // throw an error like "Cannot perform Construct on a detached ArrayBuffer".
        // Look into SharedArrayBuffer at some point to get around this.
        const ktxBuffer = new Uint8Array(loadResources.getBuffer(bufferView));
        loadKTX2(ktxBuffer)
          .then(imageLoad(model, gltfTexture.id))
          .catch(onerror);
        ++model._loadResources.pendingTextureLoads;
      } else {
        const onload = getOnImageCreatedFromTypedArray(
          loadResources,
          gltfTexture
        );
        loadImageFromTypedArray({
          uint8Array: loadResources.getBuffer(bufferView),
          format: gltfTexture.mimeType,
          flipY: false,
          skipColorSpaceConversion: true,
        })
          .then(onload)
          .catch(onerror);
        ++loadResources.pendingBufferViewToImage;
      }
    }
  }

  function createSamplers(model) {
    const loadResources = model._loadResources;
    if (loadResources.createSamplers) {
      loadResources.createSamplers = false;

      const rendererSamplers = model._rendererResources.samplers;
      ForEach.sampler(model.gltfInternal, function (sampler, samplerId) {
        rendererSamplers[samplerId] = new Sampler({
          wrapS: sampler.wrapS,
          wrapT: sampler.wrapT,
          minificationFilter: sampler.minFilter,
          magnificationFilter: sampler.magFilter,
        });
      });
    }
  }

  ///////////////////////////////////////////////////////////////////////////

  const CreateTextureJob$1 = function () {
    this.gltfTexture = undefined;
    this.model = undefined;
    this.context = undefined;
  };

  CreateTextureJob$1.prototype.set = function (gltfTexture, model, context) {
    this.gltfTexture = gltfTexture;
    this.model = model;
    this.context = context;
  };

  CreateTextureJob$1.prototype.execute = function () {
    createTexture$2(this.gltfTexture, this.model, this.context);
  };

  ///////////////////////////////////////////////////////////////////////////

  function createTexture$2(gltfTexture, model, context) {
    const textures = model.gltfInternal.textures;
    const texture = textures[gltfTexture.id];

    const rendererSamplers = model._rendererResources.samplers;
    let sampler = rendererSamplers[texture.sampler];
    if (!defined(sampler)) {
      sampler = new Sampler({
        wrapS: TextureWrap$1.REPEAT,
        wrapT: TextureWrap$1.REPEAT,
      });
    }

    let usesTextureTransform = false;
    const materials = model.gltfInternal.materials;
    const materialsLength = materials.length;
    for (let i = 0; i < materialsLength; ++i) {
      const material = materials[i];
      if (
        defined(material.extensions) &&
        defined(material.extensions.KHR_techniques_webgl)
      ) {
        const values = material.extensions.KHR_techniques_webgl.values;
        for (const valueName in values) {
          if (
            values.hasOwnProperty(valueName) &&
            valueName.indexOf("Texture") !== -1
          ) {
            const value = values[valueName];
            if (
              value.index === gltfTexture.id &&
              defined(value.extensions) &&
              defined(value.extensions.KHR_texture_transform)
            ) {
              usesTextureTransform = true;
              break;
            }
          }
        }
      }
      if (usesTextureTransform) {
        break;
      }
    }

    const wrapS = sampler.wrapS;
    const wrapT = sampler.wrapT;
    let minFilter = sampler.minificationFilter;

    if (
      usesTextureTransform &&
      minFilter !== TextureMinificationFilter$1.LINEAR &&
      minFilter !== TextureMinificationFilter$1.NEAREST
    ) {
      if (
        minFilter === TextureMinificationFilter$1.NEAREST_MIPMAP_NEAREST ||
        minFilter === TextureMinificationFilter$1.NEAREST_MIPMAP_LINEAR
      ) {
        minFilter = TextureMinificationFilter$1.NEAREST;
      } else {
        minFilter = TextureMinificationFilter$1.LINEAR;
      }

      sampler = new Sampler({
        wrapS: sampler.wrapS,
        wrapT: sampler.wrapT,
        minificationFilter: minFilter,
        magnificationFilter: sampler.magnificationFilter,
      });
    }

    const internalFormat = gltfTexture.internalFormat;

    const mipmap =
      !(
        defined(internalFormat) && PixelFormat$1.isCompressedFormat(internalFormat)
      ) &&
      (minFilter === TextureMinificationFilter$1.NEAREST_MIPMAP_NEAREST ||
        minFilter === TextureMinificationFilter$1.NEAREST_MIPMAP_LINEAR ||
        minFilter === TextureMinificationFilter$1.LINEAR_MIPMAP_NEAREST ||
        minFilter === TextureMinificationFilter$1.LINEAR_MIPMAP_LINEAR);
    const requiresNpot =
      mipmap ||
      wrapS === TextureWrap$1.REPEAT ||
      wrapS === TextureWrap$1.MIRRORED_REPEAT ||
      wrapT === TextureWrap$1.REPEAT ||
      wrapT === TextureWrap$1.MIRRORED_REPEAT;
    let npot;
    let tx;
    let source = gltfTexture.image;

    if (defined(internalFormat)) {
      npot =
        !CesiumMath.isPowerOfTwo(gltfTexture.width) ||
        !CesiumMath.isPowerOfTwo(gltfTexture.height);

      // Warning to encourage power of 2 texture dimensions with KHR_texture_basisu
      if (
        !context.webgl2 &&
        PixelFormat$1.isCompressedFormat(internalFormat) &&
        npot &&
        requiresNpot
      ) {
        console.warn(
          "Compressed texture uses REPEAT or MIRRORED_REPEAT texture wrap mode and dimensions are not powers of two. The texture may be rendered incorrectly. See the Model.js constructor documentation for more information."
        );
      }

      let minificationFilter = sampler.minificationFilter;
      if (
        !defined(gltfTexture.mipLevels) &&
        (minFilter === TextureMinificationFilter$1.NEAREST_MIPMAP_NEAREST ||
          minFilter === TextureMinificationFilter$1.NEAREST_MIPMAP_LINEAR)
      ) {
        minificationFilter = TextureMinificationFilter$1.NEAREST;
      } else if (
        !defined(gltfTexture.mipLevels) &&
        (minFilter === TextureMinificationFilter$1.LINEAR_MIPMAP_NEAREST ||
          minFilter === TextureMinificationFilter$1.LINEAR_MIPMAP_LINEAR)
      ) {
        minificationFilter = TextureMinificationFilter$1.LINEAR;
      }
      sampler = new Sampler({
        wrapS: sampler.wrapS,
        wrapT: sampler.wrapT,
        minificationFilter: minificationFilter,
        magnificationFilter: sampler.magnificationFilter,
      });

      tx = new Texture({
        context: context,
        source: {
          arrayBufferView: gltfTexture.bufferView,
          mipLevels: gltfTexture.mipLevels,
        },
        width: gltfTexture.width,
        height: gltfTexture.height,
        pixelFormat: internalFormat,
        sampler: sampler,
      });
    } else if (defined(source)) {
      npot =
        !CesiumMath.isPowerOfTwo(source.width) ||
        !CesiumMath.isPowerOfTwo(source.height);
      if (requiresNpot && npot) {
        // WebGL requires power-of-two texture dimensions for mipmapping and REPEAT/MIRRORED_REPEAT wrap modes.
        const canvas = document.createElement("canvas");
        canvas.width = CesiumMath.nextPowerOfTwo(source.width);
        canvas.height = CesiumMath.nextPowerOfTwo(source.height);
        const canvasContext = canvas.getContext("2d");
        canvasContext.drawImage(
          source,
          0,
          0,
          source.width,
          source.height,
          0,
          0,
          canvas.width,
          canvas.height
        );
        source = canvas;
      }

      tx = new Texture({
        context: context,
        source: source,
        pixelFormat: texture.internalFormat,
        pixelDatatype: texture.type,
        sampler: sampler,
        flipY: false,
        skipColorSpaceConversion: true,
      });
      // GLTF_SPEC: Support TEXTURE_CUBE_MAP.  https://github.com/KhronosGroup/glTF/issues/40
      if (mipmap) {
        tx.generateMipmap();
      }
    }
    if (defined(tx)) {
      model._rendererResources.textures[gltfTexture.id] = tx;
      model._texturesByteLength += tx.sizeInBytes;
    }
  }

  const scratchCreateTextureJob = new CreateTextureJob$1();

  function createTextures(model, frameState) {
    const context = frameState.context;
    const texturesToCreate = model._loadResources.texturesToCreate;

    if (model.asynchronous) {
      while (texturesToCreate.length > 0) {
        scratchCreateTextureJob.set(texturesToCreate.peek(), model, context);
        if (
          !frameState.jobScheduler.execute(
            scratchCreateTextureJob,
            JobType$1.TEXTURE
          )
        ) {
          break;
        }
        texturesToCreate.dequeue();
      }
    } else {
      // Create all loaded textures this frame
      while (texturesToCreate.length > 0) {
        createTexture$2(texturesToCreate.dequeue(), model, context);
      }
    }
  }

  function getAttributeLocations$1(model, primitive) {
    const techniques = model._sourceTechniques;

    // Retrieve the compiled shader program to assign index values to attributes
    const attributeLocations = {};

    let location;
    let index;
    const material = model._runtime.materialsById[primitive.material];
    if (!defined(material)) {
      return attributeLocations;
    }

    const technique = techniques[material._technique];
    if (!defined(technique)) {
      return attributeLocations;
    }

    const attributes = technique.attributes;
    const program = model._rendererResources.programs[technique.program];
    const programAttributeLocations = program._attributeLocations;

    for (location in programAttributeLocations) {
      if (programAttributeLocations.hasOwnProperty(location)) {
        const attribute = attributes[location];
        if (defined(attribute)) {
          index = programAttributeLocations[location];
          attributeLocations[attribute.semantic] = index;
        }
      }
    }

    // Add pre-created attributes.
    const precreatedAttributes = model._precreatedAttributes;
    if (defined(precreatedAttributes)) {
      for (location in precreatedAttributes) {
        if (precreatedAttributes.hasOwnProperty(location)) {
          index = programAttributeLocations[location];
          attributeLocations[location] = index;
        }
      }
    }

    return attributeLocations;
  }

  function createJoints(model, runtimeSkins) {
    const gltf = model.gltfInternal;
    const skins = gltf.skins;
    const nodes = gltf.nodes;
    const runtimeNodes = model._runtime.nodes;

    const skinnedNodesIds = model._loadResources.skinnedNodesIds;
    const length = skinnedNodesIds.length;
    for (let j = 0; j < length; ++j) {
      const id = skinnedNodesIds[j];
      const skinnedNode = runtimeNodes[id];
      const node = nodes[id];

      const runtimeSkin = runtimeSkins[node.skin];
      skinnedNode.inverseBindMatrices = runtimeSkin.inverseBindMatrices;
      skinnedNode.bindShapeMatrix = runtimeSkin.bindShapeMatrix;

      const gltfJoints = skins[node.skin].joints;
      const jointsLength = gltfJoints.length;
      for (let i = 0; i < jointsLength; ++i) {
        const nodeId = gltfJoints[i];
        const jointNode = runtimeNodes[nodeId];
        skinnedNode.joints.push(jointNode);
      }
    }
  }

  function createSkins(model) {
    const loadResources = model._loadResources;

    if (loadResources.pendingBufferLoads !== 0) {
      return;
    }

    if (!loadResources.createSkins) {
      return;
    }
    loadResources.createSkins = false;

    const gltf = model.gltfInternal;
    const accessors = gltf.accessors;
    const runtimeSkins = {};

    ForEach.skin(gltf, function (skin, id) {
      const accessor = accessors[skin.inverseBindMatrices];

      let bindShapeMatrix;
      if (!Matrix4.equals(skin.bindShapeMatrix, Matrix4.IDENTITY)) {
        bindShapeMatrix = Matrix4.clone(skin.bindShapeMatrix);
      }

      runtimeSkins[id] = {
        inverseBindMatrices: ModelAnimationCache.getSkinInverseBindMatrices(
          model,
          accessor
        ),
        bindShapeMatrix: bindShapeMatrix, // not used when undefined
      };
    });

    createJoints(model, runtimeSkins);
  }

  function getChannelEvaluator(model, runtimeNode, targetPath, spline) {
    return function (localAnimationTime) {
      if (defined(spline)) {
        localAnimationTime = model.clampAnimations
          ? spline.clampTime(localAnimationTime)
          : spline.wrapTime(localAnimationTime);
        runtimeNode[targetPath] = spline.evaluate(
          localAnimationTime,
          runtimeNode[targetPath]
        );
        runtimeNode.dirtyNumber = model._maxDirtyNumber;
      }
    };
  }

  function createRuntimeAnimations(model) {
    const loadResources = model._loadResources;

    if (!loadResources.finishedPendingBufferLoads()) {
      return;
    }

    if (!loadResources.createRuntimeAnimations) {
      return;
    }
    loadResources.createRuntimeAnimations = false;

    model._runtime.animations = [];

    const runtimeNodes = model._runtime.nodes;
    const accessors = model.gltfInternal.accessors;

    ForEach.animation(model.gltfInternal, function (animation, i) {
      const channels = animation.channels;
      const samplers = animation.samplers;

      // Find start and stop time for the entire animation
      let startTime = Number.MAX_VALUE;
      let stopTime = -Number.MAX_VALUE;

      const channelsLength = channels.length;
      const channelEvaluators = new Array(channelsLength);

      for (let j = 0; j < channelsLength; ++j) {
        const channel = channels[j];
        const target = channel.target;
        const path = target.path;
        const sampler = samplers[channel.sampler];
        const input = ModelAnimationCache.getAnimationParameterValues(
          model,
          accessors[sampler.input]
        );
        const output = ModelAnimationCache.getAnimationParameterValues(
          model,
          accessors[sampler.output]
        );

        startTime = Math.min(startTime, input[0]);
        stopTime = Math.max(stopTime, input[input.length - 1]);

        const spline = ModelAnimationCache.getAnimationSpline(
          model,
          i,
          animation,
          channel.sampler,
          sampler,
          input,
          path,
          output
        );

        channelEvaluators[j] = getChannelEvaluator(
          model,
          runtimeNodes[target.node],
          target.path,
          spline
        );
      }

      model._runtime.animations[i] = {
        name: animation.name,
        startTime: startTime,
        stopTime: stopTime,
        channelEvaluators: channelEvaluators,
      };
    });
  }

  function createVertexArrays$1(model, context) {
    const loadResources = model._loadResources;
    if (
      !loadResources.finishedBuffersCreation() ||
      !loadResources.finishedProgramCreation() ||
      !loadResources.createVertexArrays
    ) {
      return;
    }
    loadResources.createVertexArrays = false;

    const rendererBuffers = model._rendererResources.buffers;
    const rendererVertexArrays = model._rendererResources.vertexArrays;
    const gltf = model.gltfInternal;
    const accessors = gltf.accessors;
    ForEach.mesh(gltf, function (mesh, meshId) {
      ForEach.meshPrimitive(mesh, function (primitive, primitiveId) {
        const attributes = [];
        let attributeLocation;
        const attributeLocations = getAttributeLocations$1(model, primitive);
        const decodedData =
          model._decodedData[`${meshId}.primitive.${primitiveId}`];
        ForEach.meshPrimitiveAttribute(primitive, function (
          accessorId,
          attributeName
        ) {
          // Skip if the attribute is not used by the material, e.g., because the asset
          // was exported with an attribute that wasn't used and the asset wasn't optimized.
          attributeLocation = attributeLocations[attributeName];
          if (defined(attributeLocation)) {
            // Use attributes of previously decoded draco geometry
            if (defined(decodedData)) {
              const decodedAttributes = decodedData.attributes;
              if (decodedAttributes.hasOwnProperty(attributeName)) {
                const decodedAttribute = decodedAttributes[attributeName];
                attributes.push({
                  index: attributeLocation,
                  vertexBuffer: rendererBuffers[decodedAttribute.bufferView],
                  componentsPerAttribute: decodedAttribute.componentsPerAttribute,
                  componentDatatype: decodedAttribute.componentDatatype,
                  normalize: decodedAttribute.normalized,
                  offsetInBytes: decodedAttribute.byteOffset,
                  strideInBytes: decodedAttribute.byteStride,
                });

                return;
              }
            }

            const a = accessors[accessorId];
            const normalize = defined(a.normalized) && a.normalized;
            attributes.push({
              index: attributeLocation,
              vertexBuffer: rendererBuffers[a.bufferView],
              componentsPerAttribute: numberOfComponentsForType(a.type),
              componentDatatype: a.componentType,
              normalize: normalize,
              offsetInBytes: a.byteOffset,
              strideInBytes: getAccessorByteStride(gltf, a),
            });
          }
        });

        // Add pre-created attributes
        let attribute;
        let attributeName;
        const precreatedAttributes = model._precreatedAttributes;
        if (defined(precreatedAttributes)) {
          for (attributeName in precreatedAttributes) {
            if (precreatedAttributes.hasOwnProperty(attributeName)) {
              attributeLocation = attributeLocations[attributeName];
              if (defined(attributeLocation)) {
                attribute = precreatedAttributes[attributeName];
                attribute.index = attributeLocation;
                attributes.push(attribute);
              }
            }
          }
        }

        let indexBuffer;
        if (defined(primitive.indices)) {
          const accessor = accessors[primitive.indices];
          let bufferView = accessor.bufferView;

          // Use buffer of previously decoded draco geometry
          if (defined(decodedData)) {
            bufferView = decodedData.bufferView;
          }

          indexBuffer = rendererBuffers[bufferView];
        }
        rendererVertexArrays[
          `${meshId}.primitive.${primitiveId}`
        ] = new VertexArray({
          context: context,
          attributes: attributes,
          indexBuffer: indexBuffer,
        });
      });
    });
  }

  function createRenderStates$3(model) {
    const loadResources = model._loadResources;
    if (loadResources.createRenderStates) {
      loadResources.createRenderStates = false;

      ForEach.material(model.gltfInternal, function (material, materialId) {
        createRenderStateForMaterial(model, material, materialId);
      });
    }
  }

  function createRenderStateForMaterial(model, material, materialId) {
    const rendererRenderStates = model._rendererResources.renderStates;

    let blendEquationSeparate = [
      WebGLConstants$1.FUNC_ADD,
      WebGLConstants$1.FUNC_ADD,
    ];
    let blendFuncSeparate = [
      WebGLConstants$1.ONE,
      WebGLConstants$1.ONE_MINUS_SRC_ALPHA,
      WebGLConstants$1.ONE,
      WebGLConstants$1.ONE_MINUS_SRC_ALPHA,
    ];

    if (defined(material.extensions) && defined(material.extensions.KHR_blend)) {
      blendEquationSeparate = material.extensions.KHR_blend.blendEquation;
      blendFuncSeparate = material.extensions.KHR_blend.blendFactors;
    }

    const enableCulling = !material.doubleSided;
    const blendingEnabled = material.alphaMode === "BLEND";
    rendererRenderStates[materialId] = RenderState.fromCache({
      cull: {
        enabled: enableCulling,
      },
      depthTest: {
        enabled: true,
        func: DepthFunction$1.LESS_OR_EQUAL,
      },
      depthMask: !blendingEnabled,
      blending: {
        enabled: blendingEnabled,
        equationRgb: blendEquationSeparate[0],
        equationAlpha: blendEquationSeparate[1],
        functionSourceRgb: blendFuncSeparate[0],
        functionDestinationRgb: blendFuncSeparate[1],
        functionSourceAlpha: blendFuncSeparate[2],
        functionDestinationAlpha: blendFuncSeparate[3],
      },
    });
  }

  ///////////////////////////////////////////////////////////////////////////

  const gltfUniformsFromNode = {
    MODEL: function (uniformState, model, runtimeNode) {
      return function () {
        return runtimeNode.computedMatrix;
      };
    },
    VIEW: function (uniformState, model, runtimeNode) {
      return function () {
        return uniformState.view;
      };
    },
    PROJECTION: function (uniformState, model, runtimeNode) {
      return function () {
        return uniformState.projection;
      };
    },
    MODELVIEW: function (uniformState, model, runtimeNode) {
      const mv = new Matrix4();
      return function () {
        return Matrix4.multiplyTransformation(
          uniformState.view,
          runtimeNode.computedMatrix,
          mv
        );
      };
    },
    CESIUM_RTC_MODELVIEW: function (uniformState, model, runtimeNode) {
      // CESIUM_RTC extension
      const mvRtc = new Matrix4();
      return function () {
        Matrix4.multiplyTransformation(
          uniformState.view,
          runtimeNode.computedMatrix,
          mvRtc
        );
        return Matrix4.setTranslation(mvRtc, model._rtcCenterEye, mvRtc);
      };
    },
    MODELVIEWPROJECTION: function (uniformState, model, runtimeNode) {
      const mvp = new Matrix4();
      return function () {
        Matrix4.multiplyTransformation(
          uniformState.view,
          runtimeNode.computedMatrix,
          mvp
        );
        return Matrix4.multiply(uniformState._projection, mvp, mvp);
      };
    },
    MODELINVERSE: function (uniformState, model, runtimeNode) {
      const mInverse = new Matrix4();
      return function () {
        return Matrix4.inverse(runtimeNode.computedMatrix, mInverse);
      };
    },
    VIEWINVERSE: function (uniformState, model) {
      return function () {
        return uniformState.inverseView;
      };
    },
    PROJECTIONINVERSE: function (uniformState, model, runtimeNode) {
      return function () {
        return uniformState.inverseProjection;
      };
    },
    MODELVIEWINVERSE: function (uniformState, model, runtimeNode) {
      const mv = new Matrix4();
      const mvInverse = new Matrix4();
      return function () {
        Matrix4.multiplyTransformation(
          uniformState.view,
          runtimeNode.computedMatrix,
          mv
        );
        return Matrix4.inverse(mv, mvInverse);
      };
    },
    MODELVIEWPROJECTIONINVERSE: function (uniformState, model, runtimeNode) {
      const mvp = new Matrix4();
      const mvpInverse = new Matrix4();
      return function () {
        Matrix4.multiplyTransformation(
          uniformState.view,
          runtimeNode.computedMatrix,
          mvp
        );
        Matrix4.multiply(uniformState._projection, mvp, mvp);
        return Matrix4.inverse(mvp, mvpInverse);
      };
    },
    MODELINVERSETRANSPOSE: function (uniformState, model, runtimeNode) {
      const mInverse = new Matrix4();
      const mInverseTranspose = new Matrix3();
      return function () {
        Matrix4.inverse(runtimeNode.computedMatrix, mInverse);
        Matrix4.getMatrix3(mInverse, mInverseTranspose);
        return Matrix3.transpose(mInverseTranspose, mInverseTranspose);
      };
    },
    MODELVIEWINVERSETRANSPOSE: function (uniformState, model, runtimeNode) {
      const mv = new Matrix4();
      const mvInverse = new Matrix4();
      const mvInverseTranspose = new Matrix3();
      return function () {
        Matrix4.multiplyTransformation(
          uniformState.view,
          runtimeNode.computedMatrix,
          mv
        );
        Matrix4.inverse(mv, mvInverse);
        Matrix4.getMatrix3(mvInverse, mvInverseTranspose);
        return Matrix3.transpose(mvInverseTranspose, mvInverseTranspose);
      };
    },
    VIEWPORT: function (uniformState, model, runtimeNode) {
      return function () {
        return uniformState.viewportCartesian4;
      };
    },
  };

  function getUniformFunctionFromSource(source, model, semantic, uniformState) {
    const runtimeNode = model._runtime.nodes[source];
    return gltfUniformsFromNode[semantic](uniformState, model, runtimeNode);
  }

  function createUniformsForMaterial(
    model,
    material,
    technique,
    instanceValues,
    context,
    textures,
    defaultTexture
  ) {
    const uniformMap = {};
    const uniformValues = {};
    let jointMatrixUniformName;
    let morphWeightsUniformName;

    ForEach.techniqueUniform(technique, function (uniform, uniformName) {
      // GLTF_SPEC: This does not take into account uniform arrays,
      // indicated by uniforms with a count property.
      //
      // https://github.com/KhronosGroup/glTF/issues/258

      // GLTF_SPEC: In this implementation, material parameters with a
      // semantic or targeted via a source (for animation) are not
      // targetable for material animations.  Is this too strict?
      //
      // https://github.com/KhronosGroup/glTF/issues/142

      let uv;
      if (defined(instanceValues) && defined(instanceValues[uniformName])) {
        // Parameter overrides by the instance technique
        uv = ModelUtility.createUniformFunction(
          uniform.type,
          instanceValues[uniformName],
          textures,
          defaultTexture
        );
        uniformMap[uniformName] = uv.func;
        uniformValues[uniformName] = uv;
      } else if (defined(uniform.node)) {
        uniformMap[uniformName] = getUniformFunctionFromSource(
          uniform.node,
          model,
          uniform.semantic,
          context.uniformState
        );
      } else if (defined(uniform.semantic)) {
        if (uniform.semantic === "JOINTMATRIX") {
          jointMatrixUniformName = uniformName;
        } else if (uniform.semantic === "MORPHWEIGHTS") {
          morphWeightsUniformName = uniformName;
        } else if (uniform.semantic === "ALPHACUTOFF") {
          // The material's alphaCutoff value uses a uniform with semantic ALPHACUTOFF.
          // A uniform with this semantic will ignore the instance or default values.
          const alphaMode = material.alphaMode;
          if (defined(alphaMode) && alphaMode === "MASK") {
            const alphaCutoffValue = defaultValue(material.alphaCutoff, 0.5);
            uv = ModelUtility.createUniformFunction(
              uniform.type,
              alphaCutoffValue,
              textures,
              defaultTexture
            );
            uniformMap[uniformName] = uv.func;
            uniformValues[uniformName] = uv;
          }
        } else {
          // Map glTF semantic to Cesium automatic uniform
          uniformMap[uniformName] = ModelUtility.getGltfSemanticUniforms()[
            uniform.semantic
          ](context.uniformState, model);
        }
      } else if (defined(uniform.value)) {
        // Technique value that isn't overridden by a material
        const uv2 = ModelUtility.createUniformFunction(
          uniform.type,
          uniform.value,
          textures,
          defaultTexture
        );
        uniformMap[uniformName] = uv2.func;
        uniformValues[uniformName] = uv2;
      }
    });

    return {
      map: uniformMap,
      values: uniformValues,
      jointMatrixUniformName: jointMatrixUniformName,
      morphWeightsUniformName: morphWeightsUniformName,
    };
  }

  function createUniformMaps(model, context) {
    const loadResources = model._loadResources;

    if (!loadResources.finishedProgramCreation()) {
      return;
    }

    if (!loadResources.createUniformMaps) {
      return;
    }
    loadResources.createUniformMaps = false;

    const gltf = model.gltfInternal;
    const techniques = model._sourceTechniques;
    const uniformMaps = model._uniformMaps;

    const textures = model._rendererResources.textures;
    const defaultTexture = model._defaultTexture;

    ForEach.material(gltf, function (material, materialId) {
      const modelMaterial = model._runtime.materialsById[materialId];
      const technique = techniques[modelMaterial._technique];
      const instanceValues = modelMaterial._values;

      const uniforms = createUniformsForMaterial(
        model,
        material,
        technique,
        instanceValues,
        context,
        textures,
        defaultTexture
      );

      const u = uniformMaps[materialId];
      u.uniformMap = uniforms.map; // uniform name -> function for the renderer
      u.values = uniforms.values; // material parameter name -> ModelMaterial for modifying the parameter at runtime
      u.jointMatrixUniformName = uniforms.jointMatrixUniformName;
      u.morphWeightsUniformName = uniforms.morphWeightsUniformName;

      if (defined(technique.attributes.a_outlineCoordinates)) {
        const outlineTexture = ModelOutlineLoader.createTexture(model, context);
        u.uniformMap.u_outlineTexture = function () {
          return outlineTexture;
        };
      }
    });
  }

  function createUniformsForDracoQuantizedAttributes(decodedData) {
    return ModelUtility.createUniformsForDracoQuantizedAttributes(
      decodedData.attributes
    );
  }

  function createUniformsForQuantizedAttributes(model, primitive) {
    const programId = getProgramForPrimitive(model, primitive);
    const quantizedUniforms = model._quantizedUniforms[programId];
    return ModelUtility.createUniformsForQuantizedAttributes(
      model.gltfInternal,
      primitive,
      quantizedUniforms
    );
  }

  function createPickColorFunction$1(color) {
    return function () {
      return color;
    };
  }

  function createJointMatricesFunction(runtimeNode) {
    return function () {
      return runtimeNode.computedJointMatrices;
    };
  }

  function createMorphWeightsFunction(runtimeNode) {
    return function () {
      return runtimeNode.weights;
    };
  }

  function createSilhouetteColorFunction(model) {
    return function () {
      return model.silhouetteColor;
    };
  }

  function createSilhouetteSizeFunction(model) {
    return function () {
      return model.silhouetteSize;
    };
  }

  function createColorFunction(model) {
    return function () {
      return model.color;
    };
  }

  function createClippingPlanesMatrixFunction(model) {
    return function () {
      return model._clippingPlanesMatrix;
    };
  }

  function createIBLReferenceFrameMatrixFunction(model) {
    return function () {
      return model._iblReferenceFrameMatrix;
    };
  }

  function createClippingPlanesFunction(model) {
    return function () {
      const clippingPlanes = model.clippingPlanes;
      return !defined(clippingPlanes) || !clippingPlanes.enabled
        ? model._defaultTexture
        : clippingPlanes.texture;
    };
  }

  function createClippingPlanesEdgeStyleFunction(model) {
    return function () {
      const clippingPlanes = model.clippingPlanes;
      if (!defined(clippingPlanes)) {
        return Color.WHITE.withAlpha(0.0);
      }

      const style = Color.clone(clippingPlanes.edgeColor);
      style.alpha = clippingPlanes.edgeWidth;
      return style;
    };
  }

  function createColorBlendFunction(model) {
    return function () {
      return ColorBlendMode$1.getColorBlend(
        model.colorBlendMode,
        model.colorBlendAmount
      );
    };
  }

  function createIBLFactorFunction(model) {
    return function () {
      return model._imageBasedLighting.imageBasedLightingFactor;
    };
  }

  function createLightColorFunction(model) {
    return function () {
      return model._lightColor;
    };
  }

  function createLuminanceAtZenithFunction(model) {
    return function () {
      return model._imageBasedLighting.luminanceAtZenith;
    };
  }

  function createSphericalHarmonicCoefficientsFunction(model) {
    return function () {
      return model._imageBasedLighting.sphericalHarmonicCoefficients;
    };
  }

  function createSpecularEnvironmentMapFunction(model) {
    return function () {
      return model._imageBasedLighting.specularEnvironmentMapAtlas.texture;
    };
  }

  function createSpecularEnvironmentMapSizeFunction(model) {
    return function () {
      return model._imageBasedLighting.specularEnvironmentMapAtlas.texture
        .dimensions;
    };
  }

  function createSpecularEnvironmentMapLOD(model) {
    return function () {
      return model._imageBasedLighting.specularEnvironmentMapAtlas
        .maximumMipmapLevel;
    };
  }

  function triangleCountFromPrimitiveIndices(primitive, indicesCount) {
    switch (primitive.mode) {
      case PrimitiveType$1.TRIANGLES:
        return indicesCount / 3;
      case PrimitiveType$1.TRIANGLE_STRIP:
      case PrimitiveType$1.TRIANGLE_FAN:
        return Math.max(indicesCount - 2, 0);
      default:
        return 0;
    }
  }

  function createCommand$2(model, gltfNode, runtimeNode, context, scene3DOnly) {
    const nodeCommands = model._nodeCommands;
    const pickIds = model._pickIds;
    const allowPicking = model.allowPicking;
    const runtimeMeshesByName = model._runtime.meshesByName;

    const resources = model._rendererResources;
    const rendererVertexArrays = resources.vertexArrays;
    const rendererPrograms = resources.programs;
    const rendererRenderStates = resources.renderStates;
    const uniformMaps = model._uniformMaps;

    const gltf = model.gltfInternal;
    const accessors = gltf.accessors;
    const gltfMeshes = gltf.meshes;

    const id = gltfNode.mesh;
    const mesh = gltfMeshes[id];

    const primitives = mesh.primitives;
    const length = primitives.length;

    // The glTF node hierarchy is a DAG so a node can have more than one
    // parent, so a node may already have commands.  If so, append more
    // since they will have a different model matrix.

    for (let i = 0; i < length; ++i) {
      const primitive = primitives[i];
      const ix = accessors[primitive.indices];
      const material = model._runtime.materialsById[primitive.material];
      const programId = material._program;
      const decodedData = model._decodedData[`${id}.primitive.${i}`];

      let boundingSphere;
      const positionAccessor = primitive.attributes.POSITION;
      if (defined(positionAccessor)) {
        const minMax = ModelUtility.getAccessorMinMax(gltf, positionAccessor);
        boundingSphere = BoundingSphere.fromCornerPoints(
          Cartesian3.fromArray(minMax.min),
          Cartesian3.fromArray(minMax.max)
        );
      }

      const vertexArray = rendererVertexArrays[`${id}.primitive.${i}`];
      let offset;
      let count;

      // Use indices of the previously decoded Draco geometry.
      if (defined(decodedData)) {
        count = decodedData.numberOfIndices;
        offset = 0;
      } else if (defined(ix)) {
        count = ix.count;
        offset = ix.byteOffset / IndexDatatype$1.getSizeInBytes(ix.componentType); // glTF has offset in bytes.  Cesium has offsets in indices
      } else {
        const positions = accessors[primitive.attributes.POSITION];
        count = positions.count;
        offset = 0;
      }

      // Update model triangle count using number of indices
      model._trianglesLength += triangleCountFromPrimitiveIndices(
        primitive,
        count
      );

      if (primitive.mode === PrimitiveType$1.POINTS) {
        model._pointsLength += count;
      }

      const um = uniformMaps[primitive.material];
      let uniformMap = um.uniformMap;
      if (defined(um.jointMatrixUniformName)) {
        const jointUniformMap = {};
        jointUniformMap[um.jointMatrixUniformName] = createJointMatricesFunction(
          runtimeNode
        );

        uniformMap = combine$2(uniformMap, jointUniformMap);
      }
      if (defined(um.morphWeightsUniformName)) {
        const morphWeightsUniformMap = {};
        morphWeightsUniformMap[
          um.morphWeightsUniformName
        ] = createMorphWeightsFunction(runtimeNode);

        uniformMap = combine$2(uniformMap, morphWeightsUniformMap);
      }

      uniformMap = combine$2(uniformMap, {
        gltf_color: createColorFunction(model),
        gltf_colorBlend: createColorBlendFunction(model),
        gltf_clippingPlanes: createClippingPlanesFunction(model),
        gltf_clippingPlanesEdgeStyle: createClippingPlanesEdgeStyleFunction(
          model
        ),
        gltf_clippingPlanesMatrix: createClippingPlanesMatrixFunction(model),
        gltf_iblReferenceFrameMatrix: createIBLReferenceFrameMatrixFunction(
          model
        ),
        gltf_iblFactor: createIBLFactorFunction(model),
        gltf_lightColor: createLightColorFunction(model),
        gltf_sphericalHarmonicCoefficients: createSphericalHarmonicCoefficientsFunction(
          model
        ),
        gltf_specularMap: createSpecularEnvironmentMapFunction(model),
        gltf_specularMapSize: createSpecularEnvironmentMapSizeFunction(model),
        gltf_maxSpecularLOD: createSpecularEnvironmentMapLOD(model),
        gltf_luminanceAtZenith: createLuminanceAtZenithFunction(model),
      });

      Splitter.addUniforms(model, uniformMap);

      // Allow callback to modify the uniformMap
      if (defined(model._uniformMapLoaded)) {
        uniformMap = model._uniformMapLoaded(uniformMap, programId, runtimeNode);
      }

      // Add uniforms for decoding quantized attributes if used
      let quantizedUniformMap = {};
      if (model.extensionsUsed.WEB3D_quantized_attributes) {
        quantizedUniformMap = createUniformsForQuantizedAttributes(
          model,
          primitive
        );
      } else if (model._dequantizeInShader && defined(decodedData)) {
        quantizedUniformMap = createUniformsForDracoQuantizedAttributes(
          decodedData
        );
      }
      uniformMap = combine$2(uniformMap, quantizedUniformMap);

      const rs = rendererRenderStates[primitive.material];
      const isTranslucent = rs.blending.enabled;

      let owner = model._pickObject;
      if (!defined(owner)) {
        owner = {
          primitive: model,
          id: model.id,
          node: runtimeNode.publicNode,
          mesh: runtimeMeshesByName[mesh.name],
        };
      }

      const castShadows = ShadowMode$1.castShadows(model._shadows);
      const receiveShadows = ShadowMode$1.receiveShadows(model._shadows);

      let pickId;
      if (allowPicking && !defined(model._uniformMapLoaded)) {
        pickId = context.createPickId(owner);
        pickIds.push(pickId);
        const pickUniforms = {
          czm_pickColor: createPickColorFunction$1(pickId.color),
        };
        uniformMap = combine$2(uniformMap, pickUniforms);
      }

      if (allowPicking) {
        if (defined(model._pickIdLoaded) && defined(model._uniformMapLoaded)) {
          pickId = model._pickIdLoaded();
        } else {
          pickId = "czm_pickColor";
        }
      }

      const command = new DrawCommand({
        boundingVolume: new BoundingSphere(), // updated in update()
        cull: model.cull,
        modelMatrix: new Matrix4(), // computed in update()
        primitiveType: primitive.mode,
        vertexArray: vertexArray,
        count: count,
        offset: offset,
        shaderProgram: rendererPrograms[programId],
        castShadows: castShadows,
        receiveShadows: receiveShadows,
        uniformMap: uniformMap,
        renderState: rs,
        owner: owner,
        pass: isTranslucent ? Pass$1.TRANSLUCENT : model.opaquePass,
        pickId: pickId,
      });

      let command2D;
      if (!scene3DOnly) {
        command2D = DrawCommand.shallowClone(command);
        command2D.boundingVolume = new BoundingSphere(); // updated in update()
        command2D.modelMatrix = new Matrix4(); // updated in update()
      }

      const nodeCommand = {
        show: true,
        boundingSphere: boundingSphere,
        command: command,
        command2D: command2D,
        // Generated on demand when silhouette size is greater than 0.0 and silhouette alpha is greater than 0.0
        silhouetteModelCommand: undefined,
        silhouetteModelCommand2D: undefined,
        silhouetteColorCommand: undefined,
        silhouetteColorCommand2D: undefined,
        // Generated on demand when color alpha is less than 1.0
        translucentCommand: undefined,
        translucentCommand2D: undefined,
        // Generated on demand when back face culling is false
        disableCullingCommand: undefined,
        disableCullingCommand2D: undefined,
        // For updating node commands on shader reconstruction
        programId: programId,
      };
      runtimeNode.commands.push(nodeCommand);
      nodeCommands.push(nodeCommand);
    }
  }

  function createRuntimeNodes(model, context, scene3DOnly) {
    const loadResources = model._loadResources;

    if (!loadResources.finishedEverythingButTextureCreation()) {
      return;
    }

    if (!loadResources.createRuntimeNodes) {
      return;
    }
    loadResources.createRuntimeNodes = false;

    const rootNodes = [];
    const runtimeNodes = model._runtime.nodes;

    const gltf = model.gltfInternal;
    const nodes = gltf.nodes;

    const scene = gltf.scenes[gltf.scene];
    const sceneNodes = scene.nodes;
    const length = sceneNodes.length;

    const stack = [];
    const seen = {};

    for (let i = 0; i < length; ++i) {
      stack.push({
        parentRuntimeNode: undefined,
        gltfNode: nodes[sceneNodes[i]],
        id: sceneNodes[i],
      });

      while (stack.length > 0) {
        const n = stack.pop();
        seen[n.id] = true;
        const parentRuntimeNode = n.parentRuntimeNode;
        const gltfNode = n.gltfNode;

        // Node hierarchy is a DAG so a node can have more than one parent so it may already exist
        const runtimeNode = runtimeNodes[n.id];
        if (runtimeNode.parents.length === 0) {
          if (defined(gltfNode.matrix)) {
            runtimeNode.matrix = Matrix4.fromColumnMajorArray(gltfNode.matrix);
          } else {
            // TRS converted to Cesium types
            const rotation = gltfNode.rotation;
            runtimeNode.translation = Cartesian3.fromArray(gltfNode.translation);
            runtimeNode.rotation = Quaternion.unpack(rotation);
            runtimeNode.scale = Cartesian3.fromArray(gltfNode.scale);
          }
        }

        if (defined(parentRuntimeNode)) {
          parentRuntimeNode.children.push(runtimeNode);
          runtimeNode.parents.push(parentRuntimeNode);
        } else {
          rootNodes.push(runtimeNode);
        }

        if (defined(gltfNode.mesh)) {
          createCommand$2(model, gltfNode, runtimeNode, context, scene3DOnly);
        }

        const children = gltfNode.children;
        if (defined(children)) {
          const childrenLength = children.length;
          for (let j = 0; j < childrenLength; j++) {
            const childId = children[j];
            if (!seen[childId]) {
              stack.push({
                parentRuntimeNode: runtimeNode,
                gltfNode: nodes[childId],
                id: children[j],
              });
            }
          }
        }
      }
    }

    model._runtime.rootNodes = rootNodes;
    model._runtime.nodes = runtimeNodes;
  }

  function getGeometryByteLength(buffers) {
    let memory = 0;
    for (const id in buffers) {
      if (buffers.hasOwnProperty(id)) {
        memory += buffers[id].sizeInBytes;
      }
    }
    return memory;
  }

  function getTexturesByteLength(textures) {
    let memory = 0;
    for (const id in textures) {
      if (textures.hasOwnProperty(id)) {
        memory += textures[id].sizeInBytes;
      }
    }
    return memory;
  }

  function createResources$4(model, frameState) {
    const context = frameState.context;
    const scene3DOnly = frameState.scene3DOnly;
    const quantizedVertexShaders = model._quantizedVertexShaders;
    const techniques = model._sourceTechniques;
    const programs = model._sourcePrograms;

    const resources = model._rendererResources;
    let shaders = resources.sourceShaders;
    if (model._loadRendererResourcesFromCache) {
      shaders = resources.sourceShaders =
        model._cachedRendererResources.sourceShaders;
    }

    for (const techniqueId in techniques) {
      if (techniques.hasOwnProperty(techniqueId)) {
        const programId = techniques[techniqueId].program;
        const program = programs[programId];
        let shader = shaders[program.vertexShader];

        ModelUtility.checkSupportedGlExtensions(program.glExtensions, context);

        if (
          model.extensionsUsed.WEB3D_quantized_attributes ||
          model._dequantizeInShader
        ) {
          let quantizedVS = quantizedVertexShaders[programId];
          if (!defined(quantizedVS)) {
            quantizedVS = modifyShaderForQuantizedAttributes(
              shader,
              programId,
              model
            );
            quantizedVertexShaders[programId] = quantizedVS;
          }
          shader = quantizedVS;
        }

        shader = modifyShader(shader, programId, model._vertexShaderLoaded);
      }
    }

    if (model._loadRendererResourcesFromCache) {
      const cachedResources = model._cachedRendererResources;

      resources.buffers = cachedResources.buffers;
      resources.vertexArrays = cachedResources.vertexArrays;
      resources.programs = cachedResources.programs;
      resources.silhouettePrograms = cachedResources.silhouettePrograms;
      resources.textures = cachedResources.textures;
      resources.samplers = cachedResources.samplers;
      resources.renderStates = cachedResources.renderStates;

      // Vertex arrays are unique to this model, create instead of using the cache.
      if (defined(model._precreatedAttributes)) {
        createVertexArrays$1(model, context);
      }

      model._cachedGeometryByteLength += getGeometryByteLength(
        cachedResources.buffers
      );
      model._cachedTexturesByteLength += getTexturesByteLength(
        cachedResources.textures
      );
    } else {
      createBuffers(model, frameState); // using glTF bufferViews
      createPrograms(model, frameState);
      createSamplers(model);
      loadTexturesFromBufferViews(model);
      createTextures(model, frameState);
    }

    createSkins(model);
    createRuntimeAnimations(model);

    if (!model._loadRendererResourcesFromCache) {
      createVertexArrays$1(model, context); // using glTF meshes
      createRenderStates$3(model); // using glTF materials/techniques/states
      // Long-term, we might not cache render states if they could change
      // due to an animation, e.g., a uniform going from opaque to transparent.
      // Could use copy-on-write if it is worth it.  Probably overkill.
    }

    createUniformMaps(model, context); // using glTF materials/techniques
    createRuntimeNodes(model, context, scene3DOnly); // using glTF scene
  }

  ///////////////////////////////////////////////////////////////////////////

  function getNodeMatrix(node, result) {
    const publicNode = node.publicNode;
    const publicMatrix = publicNode.matrix;

    if (publicNode.useMatrix && defined(publicMatrix)) {
      // Public matrix overrides original glTF matrix and glTF animations
      Matrix4.clone(publicMatrix, result);
    } else if (defined(node.matrix)) {
      Matrix4.clone(node.matrix, result);
    } else {
      Matrix4.fromTranslationQuaternionRotationScale(
        node.translation,
        node.rotation,
        node.scale,
        result
      );
      // Keep matrix returned by the node in-sync if the node is targeted by an animation.  Only TRS nodes can be targeted.
      publicNode.setMatrix(result);
    }
  }

  const scratchNodeStack = [];
  const scratchComputedTranslation$2 = new Cartesian4();
  const scratchComputedMatrixIn2D = new Matrix4();

  function updateNodeHierarchyModelMatrix(
    model,
    modelTransformChanged,
    justLoaded,
    projection
  ) {
    const maxDirtyNumber = model._maxDirtyNumber;

    const rootNodes = model._runtime.rootNodes;
    const length = rootNodes.length;

    const nodeStack = scratchNodeStack;
    let computedModelMatrix = model._computedModelMatrix;

    if (model._mode !== SceneMode$1.SCENE3D && !model._ignoreCommands) {
      const translation = Matrix4.getColumn(
        computedModelMatrix,
        3,
        scratchComputedTranslation$2
      );
      if (!Cartesian4.equals(translation, Cartesian4.UNIT_W)) {
        computedModelMatrix = Transforms.basisTo2D(
          projection,
          computedModelMatrix,
          scratchComputedMatrixIn2D
        );
        model._rtcCenter = model._rtcCenter3D;
      } else {
        const center = model.boundingSphereInternal.center;
        const to2D = Transforms.wgs84To2DModelMatrix(
          projection,
          center,
          scratchComputedMatrixIn2D
        );
        computedModelMatrix = Matrix4.multiply(
          to2D,
          computedModelMatrix,
          scratchComputedMatrixIn2D
        );

        if (defined(model._rtcCenter)) {
          Matrix4.setTranslation(
            computedModelMatrix,
            Cartesian4.UNIT_W,
            computedModelMatrix
          );
          model._rtcCenter = model._rtcCenter2D;
        }
      }
    }

    for (let i = 0; i < length; ++i) {
      let n = rootNodes[i];

      getNodeMatrix(n, n.transformToRoot);
      nodeStack.push(n);

      while (nodeStack.length > 0) {
        n = nodeStack.pop();
        const transformToRoot = n.transformToRoot;
        const commands = n.commands;

        if (
          n.dirtyNumber === maxDirtyNumber ||
          modelTransformChanged ||
          justLoaded
        ) {
          const nodeMatrix = Matrix4.multiplyTransformation(
            computedModelMatrix,
            transformToRoot,
            n.computedMatrix
          );
          const commandsLength = commands.length;
          if (commandsLength > 0) {
            // Node has meshes, which has primitives.  Update their commands.
            for (let j = 0; j < commandsLength; ++j) {
              const primitiveCommand = commands[j];
              let command = primitiveCommand.command;
              Matrix4.clone(nodeMatrix, command.modelMatrix);

              // PERFORMANCE_IDEA: Can use transformWithoutScale if no node up to the root has scale (including animation)
              BoundingSphere.transform(
                primitiveCommand.boundingSphere,
                command.modelMatrix,
                command.boundingVolume
              );

              if (defined(model._rtcCenter)) {
                Cartesian3.add(
                  model._rtcCenter,
                  command.boundingVolume.center,
                  command.boundingVolume.center
                );
              }

              // If the model crosses the IDL in 2D, it will be drawn in one viewport, but part of it
              // will be clipped by the viewport. We create a second command that translates the model
              // model matrix to the opposite side of the map so the part that was clipped in one viewport
              // is drawn in the other.
              command = primitiveCommand.command2D;
              if (defined(command) && model._mode === SceneMode$1.SCENE2D) {
                Matrix4.clone(nodeMatrix, command.modelMatrix);
                command.modelMatrix[13] -=
                  CesiumMath.sign(command.modelMatrix[13]) *
                  2.0 *
                  CesiumMath.PI *
                  projection.ellipsoid.maximumRadius;
                BoundingSphere.transform(
                  primitiveCommand.boundingSphere,
                  command.modelMatrix,
                  command.boundingVolume
                );
              }
            }
          }
        }

        const children = n.children;
        if (defined(children)) {
          const childrenLength = children.length;
          for (let k = 0; k < childrenLength; ++k) {
            const child = children[k];

            // A node's transform needs to be updated if
            // - It was targeted for animation this frame, or
            // - Any of its ancestors were targeted for animation this frame

            // PERFORMANCE_IDEA: if a child has multiple parents and only one of the parents
            // is dirty, all the subtrees for each child instance will be dirty; we probably
            // won't see this in the wild often.
            child.dirtyNumber = Math.max(child.dirtyNumber, n.dirtyNumber);

            if (child.dirtyNumber === maxDirtyNumber || justLoaded) {
              // Don't check for modelTransformChanged since if only the model's model matrix changed,
              // we do not need to rebuild the local transform-to-root, only the final
              // [model's-model-matrix][transform-to-root] above.
              getNodeMatrix(child, child.transformToRoot);
              Matrix4.multiplyTransformation(
                transformToRoot,
                child.transformToRoot,
                child.transformToRoot
              );
            }

            nodeStack.push(child);
          }
        }
      }
    }

    ++model._maxDirtyNumber;
  }

  let scratchObjectSpace = new Matrix4();

  function applySkins(model) {
    const skinnedNodes = model._runtime.skinnedNodes;
    const length = skinnedNodes.length;

    for (let i = 0; i < length; ++i) {
      const node = skinnedNodes[i];

      scratchObjectSpace = Matrix4.inverseTransformation(
        node.transformToRoot,
        scratchObjectSpace
      );

      const computedJointMatrices = node.computedJointMatrices;
      const joints = node.joints;
      const bindShapeMatrix = node.bindShapeMatrix;
      const inverseBindMatrices = node.inverseBindMatrices;
      const inverseBindMatricesLength = inverseBindMatrices.length;

      for (let m = 0; m < inverseBindMatricesLength; ++m) {
        // [joint-matrix] = [node-to-root^-1][joint-to-root][inverse-bind][bind-shape]
        if (!defined(computedJointMatrices[m])) {
          computedJointMatrices[m] = new Matrix4();
        }
        computedJointMatrices[m] = Matrix4.multiplyTransformation(
          scratchObjectSpace,
          joints[m].transformToRoot,
          computedJointMatrices[m]
        );
        computedJointMatrices[m] = Matrix4.multiplyTransformation(
          computedJointMatrices[m],
          inverseBindMatrices[m],
          computedJointMatrices[m]
        );
        if (defined(bindShapeMatrix)) {
          // NOTE: bindShapeMatrix is glTF 1.0 only, removed in glTF 2.0.
          computedJointMatrices[m] = Matrix4.multiplyTransformation(
            computedJointMatrices[m],
            bindShapeMatrix,
            computedJointMatrices[m]
          );
        }
      }
    }
  }

  function updatePerNodeShow(model) {
    // Totally not worth it, but we could optimize this:
    // http://help.agi.com/AGIComponents/html/BlogDeletionInBoundingVolumeHierarchies.htm

    const rootNodes = model._runtime.rootNodes;
    const length = rootNodes.length;

    const nodeStack = scratchNodeStack;

    for (let i = 0; i < length; ++i) {
      let n = rootNodes[i];
      n.computedShow = n.publicNode.show;
      nodeStack.push(n);

      while (nodeStack.length > 0) {
        n = nodeStack.pop();
        const show = n.computedShow;

        const nodeCommands = n.commands;
        const nodeCommandsLength = nodeCommands.length;
        for (let j = 0; j < nodeCommandsLength; ++j) {
          nodeCommands[j].show = show;
        }
        // if commandsLength is zero, the node has a light or camera

        const children = n.children;
        if (defined(children)) {
          const childrenLength = children.length;
          for (let k = 0; k < childrenLength; ++k) {
            const child = children[k];
            // Parent needs to be shown for child to be shown.
            child.computedShow = show && child.publicNode.show;
            nodeStack.push(child);
          }
        }
      }
    }
  }

  function updatePickIds$1(model, context) {
    const id = model.id;
    if (model._id !== id) {
      model._id = id;

      const pickIds = model._pickIds;
      const length = pickIds.length;
      for (let i = 0; i < length; ++i) {
        pickIds[i].object.id = id;
      }
    }
  }

  function updateWireframe$1(model) {
    if (model._debugWireframe !== model.debugWireframe) {
      model._debugWireframe = model.debugWireframe;

      // This assumes the original primitive was TRIANGLES and that the triangles
      // are connected for the wireframe to look perfect.
      const primitiveType = model.debugWireframe
        ? PrimitiveType$1.LINES
        : PrimitiveType$1.TRIANGLES;
      const nodeCommands = model._nodeCommands;
      const length = nodeCommands.length;

      for (let i = 0; i < length; ++i) {
        nodeCommands[i].command.primitiveType = primitiveType;
      }
    }
  }

  function updateShowBoundingVolume$2(model) {
    if (model.debugShowBoundingVolume !== model._debugShowBoundingVolume) {
      model._debugShowBoundingVolume = model.debugShowBoundingVolume;

      const debugShowBoundingVolume = model.debugShowBoundingVolume;
      const nodeCommands = model._nodeCommands;
      const length = nodeCommands.length;

      for (let i = 0; i < length; ++i) {
        nodeCommands[i].command.debugShowBoundingVolume = debugShowBoundingVolume;
      }
    }
  }

  function updateShadows$2(model) {
    if (model.shadows !== model._shadows) {
      model._shadows = model.shadows;

      const castShadows = ShadowMode$1.castShadows(model.shadows);
      const receiveShadows = ShadowMode$1.receiveShadows(model.shadows);
      const nodeCommands = model._nodeCommands;
      const length = nodeCommands.length;

      for (let i = 0; i < length; i++) {
        const nodeCommand = nodeCommands[i];
        nodeCommand.command.castShadows = castShadows;
        nodeCommand.command.receiveShadows = receiveShadows;
      }
    }
  }

  function getTranslucentRenderState$1(model, renderState) {
    const rs = clone$1(renderState, true);
    rs.cull.enabled = false;
    rs.depthTest.enabled = true;
    rs.depthMask = false;
    rs.blending = BlendingState$1.ALPHA_BLEND;

    if (model.opaquePass === Pass$1.CESIUM_3D_TILE) {
      rs.stencilTest = StencilConstants$1.setCesium3DTileBit();
      rs.stencilMask = StencilConstants$1.CESIUM_3D_TILE_MASK;
    }

    return RenderState.fromCache(rs);
  }

  function deriveTranslucentCommand$1(model, command) {
    const translucentCommand = DrawCommand.shallowClone(command);
    translucentCommand.pass = Pass$1.TRANSLUCENT;
    translucentCommand.renderState = getTranslucentRenderState$1(
      model,
      command.renderState
    );
    return translucentCommand;
  }

  function updateColor(model, frameState, forceDerive) {
    // Generate translucent commands when the blend color has an alpha in the range (0.0, 1.0) exclusive
    const scene3DOnly = frameState.scene3DOnly;
    const alpha = model.color.alpha;
    if (alpha > 0.0 && alpha < 1.0) {
      const nodeCommands = model._nodeCommands;
      const length = nodeCommands.length;
      if (
        length > 0 &&
        (!defined(nodeCommands[0].translucentCommand) || forceDerive)
      ) {
        for (let i = 0; i < length; ++i) {
          const nodeCommand = nodeCommands[i];
          const command = nodeCommand.command;
          nodeCommand.translucentCommand = deriveTranslucentCommand$1(
            model,
            command
          );
          if (!scene3DOnly) {
            const command2D = nodeCommand.command2D;
            nodeCommand.translucentCommand2D = deriveTranslucentCommand$1(
              model,
              command2D
            );
          }
        }
      }
    }
  }

  function getDisableCullingRenderState$1(renderState) {
    const rs = clone$1(renderState, true);
    rs.cull.enabled = false;
    return RenderState.fromCache(rs);
  }

  function deriveDisableCullingCommand(command) {
    const disableCullingCommand = DrawCommand.shallowClone(command);
    disableCullingCommand.renderState = getDisableCullingRenderState$1(
      command.renderState
    );
    return disableCullingCommand;
  }

  function updateBackFaceCulling$2(model, frameState, forceDerive) {
    const scene3DOnly = frameState.scene3DOnly;
    const backFaceCulling = model.backFaceCulling;
    if (!backFaceCulling) {
      const nodeCommands = model._nodeCommands;
      const length = nodeCommands.length;
      if (
        length > 0 &&
        (!defined(nodeCommands[0].disableCullingCommand) || forceDerive)
      ) {
        for (let i = 0; i < length; ++i) {
          const nodeCommand = nodeCommands[i];
          const command = nodeCommand.command;
          nodeCommand.disableCullingCommand = deriveDisableCullingCommand(
            command
          );
          if (!scene3DOnly) {
            const command2D = nodeCommand.command2D;
            nodeCommand.disableCullingCommand2D = deriveDisableCullingCommand(
              command2D
            );
          }
        }
      }
    }
  }

  function getProgramId(model, program) {
    const programs = model._rendererResources.programs;
    for (const id in programs) {
      if (programs.hasOwnProperty(id)) {
        if (programs[id] === program) {
          return id;
        }
      }
    }
  }

  function createSilhouetteProgram(model, program, frameState) {
    let vs = program.vertexShaderSource.sources[0];
    const attributeLocations = program._attributeLocations;
    const normalAttributeName = model._normalAttributeName;

    // Modified from http://forum.unity3d.com/threads/toon-outline-but-with-diffuse-surface.24668/
    vs = ShaderSource.replaceMain(vs, "gltf_silhouette_main");
    vs +=
      `${
      "uniform float gltf_silhouetteSize; \n" +
      "void main() \n" +
      "{ \n" +
      "    gltf_silhouette_main(); \n" +
      "    vec3 n = normalize(czm_normal3D * "
    }${normalAttributeName}); \n` +
      `    n.x *= czm_projection[0][0]; \n` +
      `    n.y *= czm_projection[1][1]; \n` +
      `    vec4 clip = gl_Position; \n` +
      `    clip.xy += n.xy * clip.w * gltf_silhouetteSize * czm_pixelRatio / czm_viewport.z; \n` +
      `    gl_Position = clip; \n` +
      `}`;

    const fs =
      "uniform vec4 gltf_silhouetteColor; \n" +
      "void main() \n" +
      "{ \n" +
      "    gl_FragColor = czm_gammaCorrect(gltf_silhouetteColor); \n" +
      "}";

    return ShaderProgram.fromCache({
      context: frameState.context,
      vertexShaderSource: vs,
      fragmentShaderSource: fs,
      attributeLocations: attributeLocations,
    });
  }

  function hasSilhouette(model, frameState) {
    return (
      silhouetteSupported(frameState.context) &&
      model.silhouetteSize > 0.0 &&
      model.silhouetteColor.alpha > 0.0 &&
      defined(model._normalAttributeName)
    );
  }

  function hasTranslucentCommands(model) {
    const nodeCommands = model._nodeCommands;
    const length = nodeCommands.length;
    for (let i = 0; i < length; ++i) {
      const nodeCommand = nodeCommands[i];
      const command = nodeCommand.command;
      if (command.pass === Pass$1.TRANSLUCENT) {
        return true;
      }
    }
    return false;
  }

  function isTranslucent(model) {
    return model.color.alpha > 0.0 && model.color.alpha < 1.0;
  }

  function isInvisible(model) {
    return model.color.alpha === 0.0;
  }

  function alphaDirty(currAlpha, prevAlpha) {
    // Returns whether the alpha state has changed between invisible, translucent, or opaque
    return (
      Math.floor(currAlpha) !== Math.floor(prevAlpha) ||
      Math.ceil(currAlpha) !== Math.ceil(prevAlpha)
    );
  }

  let silhouettesLength = 0;

  function createSilhouetteCommands(model, frameState) {
    // Wrap around after exceeding the 8-bit stencil limit.
    // The reference is unique to each model until this point.
    const stencilReference = ++silhouettesLength % 255;

    // If the model is translucent the silhouette needs to be in the translucent pass.
    // Otherwise the silhouette would be rendered before the model.
    const silhouetteTranslucent =
      hasTranslucentCommands(model) ||
      isTranslucent(model) ||
      model.silhouetteColor.alpha < 1.0;
    const silhouettePrograms = model._rendererResources.silhouettePrograms;
    const scene3DOnly = frameState.scene3DOnly;
    const nodeCommands = model._nodeCommands;
    const length = nodeCommands.length;
    for (let i = 0; i < length; ++i) {
      const nodeCommand = nodeCommands[i];
      const command = nodeCommand.command;

      // Create model command
      const modelCommand = isTranslucent(model)
        ? nodeCommand.translucentCommand
        : command;
      const silhouetteModelCommand = DrawCommand.shallowClone(modelCommand);
      let renderState = clone$1(modelCommand.renderState);

      // Write the reference value into the stencil buffer.
      renderState.stencilTest = {
        enabled: true,
        frontFunction: WebGLConstants$1.ALWAYS,
        backFunction: WebGLConstants$1.ALWAYS,
        reference: stencilReference,
        mask: ~0,
        frontOperation: {
          fail: WebGLConstants$1.KEEP,
          zFail: WebGLConstants$1.KEEP,
          zPass: WebGLConstants$1.REPLACE,
        },
        backOperation: {
          fail: WebGLConstants$1.KEEP,
          zFail: WebGLConstants$1.KEEP,
          zPass: WebGLConstants$1.REPLACE,
        },
      };

      if (isInvisible(model)) {
        // When the model is invisible disable color and depth writes but still write into the stencil buffer
        renderState.colorMask = {
          red: false,
          green: false,
          blue: false,
          alpha: false,
        };
        renderState.depthMask = false;
      }
      renderState = RenderState.fromCache(renderState);
      silhouetteModelCommand.renderState = renderState;
      nodeCommand.silhouetteModelCommand = silhouetteModelCommand;

      // Create color command
      const silhouetteColorCommand = DrawCommand.shallowClone(command);
      renderState = clone$1(command.renderState, true);
      renderState.depthTest.enabled = true;
      renderState.cull.enabled = false;
      if (silhouetteTranslucent) {
        silhouetteColorCommand.pass = Pass$1.TRANSLUCENT;
        renderState.depthMask = false;
        renderState.blending = BlendingState$1.ALPHA_BLEND;
      }

      // Only render silhouette if the value in the stencil buffer equals the reference
      renderState.stencilTest = {
        enabled: true,
        frontFunction: WebGLConstants$1.NOTEQUAL,
        backFunction: WebGLConstants$1.NOTEQUAL,
        reference: stencilReference,
        mask: ~0,
        frontOperation: {
          fail: WebGLConstants$1.KEEP,
          zFail: WebGLConstants$1.KEEP,
          zPass: WebGLConstants$1.KEEP,
        },
        backOperation: {
          fail: WebGLConstants$1.KEEP,
          zFail: WebGLConstants$1.KEEP,
          zPass: WebGLConstants$1.KEEP,
        },
      };
      renderState = RenderState.fromCache(renderState);

      // If the silhouette program has already been cached use it
      const program = command.shaderProgram;
      const id = getProgramId(model, program);
      let silhouetteProgram = silhouettePrograms[id];
      if (!defined(silhouetteProgram)) {
        silhouetteProgram = createSilhouetteProgram(model, program, frameState);
        silhouettePrograms[id] = silhouetteProgram;
      }

      const silhouetteUniformMap = combine$2(command.uniformMap, {
        gltf_silhouetteColor: createSilhouetteColorFunction(model),
        gltf_silhouetteSize: createSilhouetteSizeFunction(model),
      });

      silhouetteColorCommand.renderState = renderState;
      silhouetteColorCommand.shaderProgram = silhouetteProgram;
      silhouetteColorCommand.uniformMap = silhouetteUniformMap;
      silhouetteColorCommand.castShadows = false;
      silhouetteColorCommand.receiveShadows = false;
      nodeCommand.silhouetteColorCommand = silhouetteColorCommand;

      if (!scene3DOnly) {
        const command2D = nodeCommand.command2D;
        const silhouetteModelCommand2D = DrawCommand.shallowClone(
          silhouetteModelCommand
        );
        silhouetteModelCommand2D.boundingVolume = command2D.boundingVolume;
        silhouetteModelCommand2D.modelMatrix = command2D.modelMatrix;
        nodeCommand.silhouetteModelCommand2D = silhouetteModelCommand2D;

        const silhouetteColorCommand2D = DrawCommand.shallowClone(
          silhouetteColorCommand
        );
        silhouetteModelCommand2D.boundingVolume = command2D.boundingVolume;
        silhouetteModelCommand2D.modelMatrix = command2D.modelMatrix;
        nodeCommand.silhouetteColorCommand2D = silhouetteColorCommand2D;
      }
    }
  }

  function modifyShaderForClippingPlanes(
    shader,
    clippingPlaneCollection,
    context
  ) {
    shader = ShaderSource.replaceMain(shader, "gltf_clip_main");
    shader += `${Model._getClippingFunction(clippingPlaneCollection, context)}\n`;
    shader += `${
    "uniform highp sampler2D gltf_clippingPlanes; \n" +
    "uniform mat4 gltf_clippingPlanesMatrix; \n" +
    "uniform vec4 gltf_clippingPlanesEdgeStyle; \n" +
    "void main() \n" +
    "{ \n" +
    "    gltf_clip_main(); \n"
  }${getClipAndStyleCode(
    "gltf_clippingPlanes",
    "gltf_clippingPlanesMatrix",
    "gltf_clippingPlanesEdgeStyle"
  )}} \n`;
    return shader;
  }

  function updateSilhouette$1(model, frameState, force) {
    // Generate silhouette commands when the silhouette size is greater than 0.0 and the alpha is greater than 0.0
    // There are two silhouette commands:
    //     1. silhouetteModelCommand : render model normally while enabling stencil mask
    //     2. silhouetteColorCommand : render enlarged model with a solid color while enabling stencil tests
    if (!hasSilhouette(model, frameState)) {
      return;
    }

    const nodeCommands = model._nodeCommands;
    const dirty =
      nodeCommands.length > 0 &&
      (alphaDirty(model.color.alpha, model._colorPreviousAlpha) ||
        alphaDirty(
          model.silhouetteColor.alpha,
          model._silhouetteColorPreviousAlpha
        ) ||
        !defined(nodeCommands[0].silhouetteModelCommand));

    model._colorPreviousAlpha = model.color.alpha;
    model._silhouetteColorPreviousAlpha = model.silhouetteColor.alpha;

    if (dirty || force) {
      createSilhouetteCommands(model, frameState);
    }
  }

  function updateClippingPlanes$2(model, frameState) {
    const clippingPlanes = model._clippingPlanes;
    if (defined(clippingPlanes) && clippingPlanes.owner === model) {
      if (clippingPlanes.enabled) {
        clippingPlanes.update(frameState);
      }
    }
  }

  const scratchBoundingSphere$2 = new BoundingSphere();

  function scaleInPixels$1(positionWC, radius, frameState) {
    scratchBoundingSphere$2.center = positionWC;
    scratchBoundingSphere$2.radius = radius;
    return frameState.camera.getPixelSize(
      scratchBoundingSphere$2,
      frameState.context.drawingBufferWidth,
      frameState.context.drawingBufferHeight
    );
  }

  const scratchPosition$9 = new Cartesian3();
  const scratchCartographic$e = new Cartographic();

  function getScale$1(model, frameState) {
    let scale = model.scale;

    if (model.minimumPixelSize !== 0.0) {
      // Compute size of bounding sphere in pixels
      const context = frameState.context;
      const maxPixelSize = Math.max(
        context.drawingBufferWidth,
        context.drawingBufferHeight
      );
      const m = defined(model._clampedModelMatrix)
        ? model._clampedModelMatrix
        : model.modelMatrix;
      scratchPosition$9.x = m[12];
      scratchPosition$9.y = m[13];
      scratchPosition$9.z = m[14];

      if (defined(model._rtcCenter)) {
        Cartesian3.add(model._rtcCenter, scratchPosition$9, scratchPosition$9);
      }

      if (model._mode !== SceneMode$1.SCENE3D) {
        const projection = frameState.mapProjection;
        const cartographic = projection.ellipsoid.cartesianToCartographic(
          scratchPosition$9,
          scratchCartographic$e
        );
        projection.project(cartographic, scratchPosition$9);
        Cartesian3.fromElements(
          scratchPosition$9.z,
          scratchPosition$9.x,
          scratchPosition$9.y,
          scratchPosition$9
        );
      }

      const radius = model.boundingSphereInternal.radius;
      const metersPerPixel = scaleInPixels$1(scratchPosition$9, radius, frameState);

      // metersPerPixel is always > 0.0
      const pixelsPerMeter = 1.0 / metersPerPixel;
      const diameterInPixels = Math.min(
        pixelsPerMeter * (2.0 * radius),
        maxPixelSize
      );

      // Maintain model's minimum pixel size
      if (diameterInPixels < model.minimumPixelSize) {
        scale =
          (model.minimumPixelSize * metersPerPixel) /
          (2.0 * model._initialRadius);
      }
    }

    return defined(model.maximumScale)
      ? Math.min(model.maximumScale, scale)
      : scale;
  }

  function releaseCachedGltf(model) {
    if (
      defined(model._cacheKey) &&
      defined(model._cachedGltf) &&
      --model._cachedGltf.count === 0
    ) {
      delete gltfCache[model._cacheKey];
    }
    model._cachedGltf = undefined;
  }

  ///////////////////////////////////////////////////////////////////////////

  function CachedRendererResources(context, cacheKey) {
    this.buffers = undefined;
    this.vertexArrays = undefined;
    this.programs = undefined;
    this.sourceShaders = undefined;
    this.silhouettePrograms = undefined;
    this.textures = undefined;
    this.samplers = undefined;
    this.renderStates = undefined;
    this.ready = false;

    this.context = context;
    this.cacheKey = cacheKey;
    this.count = 0;
  }

  function destroy(property) {
    for (const name in property) {
      if (property.hasOwnProperty(name)) {
        property[name].destroy();
      }
    }
  }

  function destroyCachedRendererResources(resources) {
    destroy(resources.buffers);
    destroy(resources.vertexArrays);
    destroy(resources.programs);
    destroy(resources.silhouettePrograms);
    destroy(resources.textures);
  }

  CachedRendererResources.prototype.release = function () {
    if (--this.count === 0) {
      if (defined(this.cacheKey)) {
        // Remove if this was cached
        delete this.context.cache.modelRendererResourceCache[this.cacheKey];
      }
      destroyCachedRendererResources(this);
      return destroyObject(this);
    }

    return undefined;
  };

  ///////////////////////////////////////////////////////////////////////////

  function getUpdateHeightCallback$1(model, ellipsoid, cartoPosition) {
    return function (clampedPosition) {
      if (model.heightReference === HeightReference$1.RELATIVE_TO_GROUND) {
        const clampedCart = ellipsoid.cartesianToCartographic(
          clampedPosition,
          scratchCartographic$e
        );
        clampedCart.height += cartoPosition.height;
        ellipsoid.cartographicToCartesian(clampedCart, clampedPosition);
      }

      const clampedModelMatrix = model._clampedModelMatrix;

      // Modify clamped model matrix to use new height
      Matrix4.clone(model.modelMatrix, clampedModelMatrix);
      clampedModelMatrix[12] = clampedPosition.x;
      clampedModelMatrix[13] = clampedPosition.y;
      clampedModelMatrix[14] = clampedPosition.z;

      model._heightChanged = true;
    };
  }

  function updateClamping$1(model) {
    if (defined(model._removeUpdateHeightCallback)) {
      model._removeUpdateHeightCallback();
      model._removeUpdateHeightCallback = undefined;
    }

    const scene = model._scene;
    if (
      !defined(scene) ||
      !defined(scene.globe) ||
      model.heightReference === HeightReference$1.NONE
    ) {
      //>>includeStart('debug', pragmas.debug);
      if (model.heightReference !== HeightReference$1.NONE) {
        throw new DeveloperError(
          "Height reference is not supported without a scene and globe."
        );
      }
      //>>includeEnd('debug');
      model._clampedModelMatrix = undefined;
      return;
    }

    const globe = scene.globe;
    const ellipsoid = globe.ellipsoid;

    // Compute cartographic position so we don't recompute every update
    const modelMatrix = model.modelMatrix;
    scratchPosition$9.x = modelMatrix[12];
    scratchPosition$9.y = modelMatrix[13];
    scratchPosition$9.z = modelMatrix[14];
    const cartoPosition = ellipsoid.cartesianToCartographic(scratchPosition$9);

    if (!defined(model._clampedModelMatrix)) {
      model._clampedModelMatrix = Matrix4.clone(modelMatrix, new Matrix4());
    }

    // Install callback to handle updating of terrain tiles
    const surface = globe._surface;
    model._removeUpdateHeightCallback = surface.updateHeight(
      cartoPosition,
      getUpdateHeightCallback$1(model, ellipsoid, cartoPosition)
    );

    // Set the correct height now
    const height = globe.getHeight(cartoPosition);
    if (defined(height)) {
      // Get callback with cartoPosition being the non-clamped position
      const cb = getUpdateHeightCallback$1(model, ellipsoid, cartoPosition);

      // Compute the clamped cartesian and call updateHeight callback
      Cartographic.clone(cartoPosition, scratchCartographic$e);
      scratchCartographic$e.height = height;
      ellipsoid.cartographicToCartesian(scratchCartographic$e, scratchPosition$9);
      cb(scratchPosition$9);
    }
  }

  const scratchDisplayConditionCartesian$1 = new Cartesian3();
  const scratchDistanceDisplayConditionCartographic = new Cartographic();

  function distanceDisplayConditionVisible(model, frameState) {
    let distance2;
    const ddc = model.distanceDisplayCondition;
    const nearSquared = ddc.near * ddc.near;
    const farSquared = ddc.far * ddc.far;

    if (frameState.mode === SceneMode$1.SCENE2D) {
      const frustum2DWidth =
        frameState.camera.frustum.right - frameState.camera.frustum.left;
      distance2 = frustum2DWidth * 0.5;
      distance2 = distance2 * distance2;
    } else {
      // Distance to center of primitive's reference frame
      let position = Matrix4.getTranslation(
        model.modelMatrix,
        scratchDisplayConditionCartesian$1
      );
      if (frameState.mode === SceneMode$1.COLUMBUS_VIEW) {
        const projection = frameState.mapProjection;
        const ellipsoid = projection.ellipsoid;
        const cartographic = ellipsoid.cartesianToCartographic(
          position,
          scratchDistanceDisplayConditionCartographic
        );
        position = projection.project(cartographic, position);
        Cartesian3.fromElements(position.z, position.x, position.y, position);
      }
      distance2 = Cartesian3.distanceSquared(
        position,
        frameState.camera.positionWC
      );
    }

    return distance2 >= nearSquared && distance2 <= farSquared;
  }

  const scratchIBLReferenceFrameMatrix4$1 = new Matrix4();
  const scratchIBLReferenceFrameMatrix3$1 = new Matrix3();
  const scratchClippingPlanesMatrix$3 = new Matrix4();

  /**
   * Called when {@link Viewer} or {@link CesiumWidget} render the scene to
   * get the draw commands needed to render this primitive.
   * <p>
   * Do not call this function directly.  This is documented just to
   * list the exceptions that may be propagated when the scene is rendered:
   * </p>
   *
   * @exception {RuntimeError} Failed to load external reference.
   */
  Model.prototype.update = function (frameState) {
    if (frameState.mode === SceneMode$1.MORPHING) {
      return;
    }

    if (!FeatureDetection.supportsWebP.initialized) {
      FeatureDetection.supportsWebP.initialize();
      return;
    }

    const context = frameState.context;
    this._defaultTexture = context.defaultTexture;

    const supportsWebP = FeatureDetection.supportsWebP();

    if (this._state === ModelState.NEEDS_LOAD && defined(this.gltfInternal)) {
      // Use renderer resources from cache instead of loading/creating them?
      let cachedRendererResources;
      const cacheKey = this.cacheKey;
      if (defined(cacheKey)) {
        // cache key given? this model will pull from or contribute to context level cache
        context.cache.modelRendererResourceCache = defaultValue(
          context.cache.modelRendererResourceCache,
          {}
        );
        const modelCaches = context.cache.modelRendererResourceCache;

        cachedRendererResources = modelCaches[this.cacheKey];
        if (defined(cachedRendererResources)) {
          if (!cachedRendererResources.ready) {
            // Cached resources for the model are not loaded yet.  We'll
            // try again every frame until they are.
            return;
          }

          ++cachedRendererResources.count;
          this._loadRendererResourcesFromCache = true;
        } else {
          cachedRendererResources = new CachedRendererResources(
            context,
            cacheKey
          );
          cachedRendererResources.count = 1;
          modelCaches[this.cacheKey] = cachedRendererResources;
        }
        this._cachedRendererResources = cachedRendererResources;
      } else {
        // cache key not given? this model doesn't care about context level cache at all. Cache is here to simplify freeing on destroy.
        cachedRendererResources = new CachedRendererResources(context);
        cachedRendererResources.count = 1;
        this._cachedRendererResources = cachedRendererResources;
      }

      this._state = ModelState.LOADING;
      if (this._state !== ModelState.FAILED) {
        const extensions = this.gltfInternal.extensions;
        if (defined(extensions) && defined(extensions.CESIUM_RTC)) {
          const center = Cartesian3.fromArray(extensions.CESIUM_RTC.center);
          if (!Cartesian3.equals(center, Cartesian3.ZERO)) {
            this._rtcCenter3D = center;

            const projection = frameState.mapProjection;
            const ellipsoid = projection.ellipsoid;
            const cartographic = ellipsoid.cartesianToCartographic(
              this._rtcCenter3D
            );
            const projectedCart = projection.project(cartographic);
            Cartesian3.fromElements(
              projectedCart.z,
              projectedCart.x,
              projectedCart.y,
              projectedCart
            );
            this._rtcCenter2D = projectedCart;

            this._rtcCenterEye = new Cartesian3();
            this._rtcCenter = this._rtcCenter3D;
          }
        }

        addPipelineExtras(this.gltfInternal);

        this._loadResources = new ModelLoadResources();
        if (!this._loadRendererResourcesFromCache) {
          // Buffers are required to updateVersion
          ModelUtility.parseBuffers(this, bufferLoad);
        }
      }
    }

    const loadResources = this._loadResources;
    const incrementallyLoadTextures = this._incrementallyLoadTextures;
    let justLoaded = false;

    if (this._state === ModelState.LOADING) {
      // Transition from LOADING -> LOADED once resources are downloaded and created.
      // Textures may continue to stream in while in the LOADED state.
      if (loadResources.pendingBufferLoads === 0) {
        if (!loadResources.initialized) {
          frameState.brdfLutGenerator.update(frameState);

          ModelUtility.checkSupportedExtensions(
            this.extensionsRequired,
            supportsWebP
          );
          ModelUtility.updateForwardAxis(this);

          // glTF pipeline updates, not needed if loading from cache
          if (!defined(this.gltfInternal.extras.sourceVersion)) {
            const gltf = this.gltfInternal;
            // Add the original version so it remains cached
            const sourceVersion = ModelUtility.getAssetVersion(gltf);
            const sourceKHRTechniquesWebGL = defined(
              ModelUtility.getUsedExtensions(gltf).KHR_techniques_webgl
            );

            if (sourceVersion !== "2.0") {
              deprecationWarning(
                "gltf-1.0",
                "glTF 1.0 assets were deprecated in CesiumJS 1.94. They will be removed in 1.96. Please convert any glTF 1.0 assets to glTF 2.0."
              );
            }

            if (sourceKHRTechniquesWebGL) {
              deprecationWarning(
                "KHR_techniques_webgl",
                "Support for glTF 1.0 techniques and the KHR_techniques_webgl glTF extension were deprecated in CesiumJS 1.94. It will be removed in 1.96. If custom GLSL shaders are needed, use CustomShader instead."
              );
            }

            gltf.extras.sourceVersion = sourceVersion;
            gltf.extras.sourceKHRTechniquesWebGL = sourceKHRTechniquesWebGL;

            this._sourceVersion = sourceVersion;
            this._sourceKHRTechniquesWebGL = sourceKHRTechniquesWebGL;

            updateVersion(gltf);
            addDefaults(gltf);

            const options = {
              addBatchIdToGeneratedShaders: this._addBatchIdToGeneratedShaders,
            };

            processModelMaterialsCommon(gltf, options);
            processPbrMaterials(gltf, options);
          }

          this._sourceVersion = this.gltfInternal.extras.sourceVersion;
          this._sourceKHRTechniquesWebGL = this.gltfInternal.extras.sourceKHRTechniquesWebGL;

          // Skip dequantizing in the shader if not encoded
          this._dequantizeInShader =
            this._dequantizeInShader && DracoLoader.hasExtension(this);

          // We do this after to make sure that the ids don't change
          addBuffersToLoadResources(this);
          parseArticulations(this);
          parseTechniques(this);
          if (!this._loadRendererResourcesFromCache) {
            parseBufferViews(this);
            parseShaders(this);
            parsePrograms(this);
            parseTextures(this, context, supportsWebP);
          }
          parseMaterials(this);
          parseMeshes(this);
          parseNodes(this);
          parseCredits(this);

          // Start draco decoding
          DracoLoader.parse(this, context);

          loadResources.initialized = true;
        }

        if (!loadResources.finishedDecoding()) {
          DracoLoader.decodeModel(this, context).catch(
            ModelUtility.getFailedLoadFunction(
              this,
              "model",
              this.basePathInternal
            )
          );
        }

        if (loadResources.finishedDecoding() && !loadResources.resourcesParsed) {
          this._boundingSphere = ModelUtility.computeBoundingSphere(this);
          this._initialRadius = this._boundingSphere.radius;

          DracoLoader.cacheDataForModel(this);

          loadResources.resourcesParsed = true;
        }

        if (
          loadResources.resourcesParsed &&
          loadResources.pendingShaderLoads === 0
        ) {
          if (this.showOutline) {
            ModelOutlineLoader.outlinePrimitives(this);
          }
          createResources$4(this, frameState);
        }
      }

      if (
        loadResources.finished() ||
        (incrementallyLoadTextures &&
          loadResources.finishedEverythingButTextureCreation())
      ) {
        this._state = ModelState.LOADED;
        justLoaded = true;
      }
    }

    // Incrementally stream textures.
    if (defined(loadResources) && this._state === ModelState.LOADED) {
      if (incrementallyLoadTextures && !justLoaded) {
        createResources$4(this, frameState);
      }

      if (loadResources.finished()) {
        this._loadResources = undefined; // Clear CPU memory since WebGL resources were created.

        const resources = this._rendererResources;
        const cachedResources = this._cachedRendererResources;

        cachedResources.buffers = resources.buffers;
        cachedResources.vertexArrays = resources.vertexArrays;
        cachedResources.programs = resources.programs;
        cachedResources.sourceShaders = resources.sourceShaders;
        cachedResources.silhouettePrograms = resources.silhouettePrograms;
        cachedResources.textures = resources.textures;
        cachedResources.samplers = resources.samplers;
        cachedResources.renderStates = resources.renderStates;
        cachedResources.ready = true;

        // The normal attribute name is required for silhouettes, so get it before the gltf JSON is released
        this._normalAttributeName = ModelUtility.getAttributeOrUniformBySemantic(
          this.gltfInternal,
          "NORMAL"
        );

        // Vertex arrays are unique to this model, do not store in cache.
        if (defined(this._precreatedAttributes)) {
          cachedResources.vertexArrays = {};
        }

        if (this.releaseGltfJson) {
          releaseCachedGltf(this);
        }
      }
    }

    const silhouette = hasSilhouette(this, frameState);
    const translucent = isTranslucent(this);
    const invisible = isInvisible(this);
    const backFaceCulling = this.backFaceCulling;
    const displayConditionPassed = defined(this.distanceDisplayCondition)
      ? distanceDisplayConditionVisible(this, frameState)
      : true;
    const show =
      this.show &&
      displayConditionPassed &&
      this.scale !== 0.0 &&
      (!invisible || silhouette);

    this._imageBasedLighting.update(frameState);

    if ((show && this._state === ModelState.LOADED) || justLoaded) {
      const animated =
        this.activeAnimations.update(frameState) || this._cesiumAnimationsDirty;
      this._cesiumAnimationsDirty = false;
      this._dirty = false;
      let modelMatrix = this.modelMatrix;

      const modeChanged = frameState.mode !== this._mode;
      this._mode = frameState.mode;

      // Model's model matrix needs to be updated
      const modelTransformChanged =
        !Matrix4.equals(this._modelMatrix, modelMatrix) ||
        this._scale !== this.scale ||
        this._minimumPixelSize !== this.minimumPixelSize ||
        this.minimumPixelSize !== 0.0 || // Minimum pixel size changed or is enabled
        this._maximumScale !== this.maximumScale ||
        this._heightReference !== this.heightReference ||
        this._heightChanged ||
        modeChanged;

      if (modelTransformChanged || justLoaded) {
        Matrix4.clone(modelMatrix, this._modelMatrix);

        updateClamping$1(this);

        if (defined(this._clampedModelMatrix)) {
          modelMatrix = this._clampedModelMatrix;
        }

        this._scale = this.scale;
        this._minimumPixelSize = this.minimumPixelSize;
        this._maximumScale = this.maximumScale;
        this._heightReference = this.heightReference;
        this._heightChanged = false;

        const scale = getScale$1(this, frameState);
        const computedModelMatrix = this._computedModelMatrix;
        Matrix4.multiplyByUniformScale(modelMatrix, scale, computedModelMatrix);
        if (this._upAxis === Axis$1.Y) {
          Matrix4.multiplyTransformation(
            computedModelMatrix,
            Axis$1.Y_UP_TO_Z_UP,
            computedModelMatrix
          );
        } else if (this._upAxis === Axis$1.X) {
          Matrix4.multiplyTransformation(
            computedModelMatrix,
            Axis$1.X_UP_TO_Z_UP,
            computedModelMatrix
          );
        }
        if (this.forwardAxis === Axis$1.Z) {
          // glTF 2.0 has a Z-forward convention that must be adapted here to X-forward.
          Matrix4.multiplyTransformation(
            computedModelMatrix,
            Axis$1.Z_UP_TO_X_UP,
            computedModelMatrix
          );
        }
      }

      // Update modelMatrix throughout the graph as needed
      if (animated || modelTransformChanged || justLoaded) {
        updateNodeHierarchyModelMatrix(
          this,
          modelTransformChanged,
          justLoaded,
          frameState.mapProjection
        );
        this._dirty = true;

        if (animated || justLoaded) {
          // Apply skins if animation changed any node transforms
          applySkins(this);
        }
      }

      if (this._perNodeShowDirty) {
        this._perNodeShowDirty = false;
        updatePerNodeShow(this);
      }
      updatePickIds$1(this);
      updateWireframe$1(this);
      updateShowBoundingVolume$2(this);
      updateShadows$2(this);
      updateClippingPlanes$2(this, frameState);

      // Regenerate shaders if ClippingPlaneCollection state changed or it was removed
      const clippingPlanes = this._clippingPlanes;
      let currentClippingPlanesState = 0;

      // If defined, use the reference matrix to transform miscellaneous properties like
      // clipping planes and IBL instead of the modelMatrix. This is so that when
      // models are part of a tileset these properties get transformed relative to
      // a common reference (such as the root).
      const referenceMatrix = defaultValue(this.referenceMatrix, modelMatrix);

      if (
        this._imageBasedLighting.useSphericalHarmonicCoefficients ||
        this._imageBasedLighting.useSpecularEnvironmentMaps
      ) {
        let iblReferenceFrameMatrix3 = scratchIBLReferenceFrameMatrix3$1;
        let iblReferenceFrameMatrix4 = scratchIBLReferenceFrameMatrix4$1;

        iblReferenceFrameMatrix4 = Matrix4.multiply(
          context.uniformState.view3D,
          referenceMatrix,
          iblReferenceFrameMatrix4
        );
        iblReferenceFrameMatrix3 = Matrix4.getMatrix3(
          iblReferenceFrameMatrix4,
          iblReferenceFrameMatrix3
        );
        iblReferenceFrameMatrix3 = Matrix3.getRotation(
          iblReferenceFrameMatrix3,
          iblReferenceFrameMatrix3
        );
        this._iblReferenceFrameMatrix = Matrix3.transpose(
          iblReferenceFrameMatrix3,
          this._iblReferenceFrameMatrix
        );
      }

      this._shouldRegenerateShaders =
        this._shouldRegenerateShaders ||
        this._imageBasedLighting.shouldRegenerateShaders;

      if (isClippingEnabled(this)) {
        let clippingPlanesMatrix = scratchClippingPlanesMatrix$3;
        clippingPlanesMatrix = Matrix4.multiply(
          context.uniformState.view3D,
          referenceMatrix,
          clippingPlanesMatrix
        );
        clippingPlanesMatrix = Matrix4.multiply(
          clippingPlanesMatrix,
          clippingPlanes.modelMatrix,
          clippingPlanesMatrix
        );
        this._clippingPlanesMatrix = Matrix4.inverseTranspose(
          clippingPlanesMatrix,
          this._clippingPlanesMatrix
        );
        currentClippingPlanesState = clippingPlanes.clippingPlanesState;
      }

      this._shouldRegenerateShaders =
        this._shouldRegenerateShaders ||
        this._clippingPlanesState !== currentClippingPlanesState;
      this._clippingPlanesState = currentClippingPlanesState;

      // Regenerate shaders if color shading changed from last update
      const currentlyColorShadingEnabled = isColorShadingEnabled(this);
      if (currentlyColorShadingEnabled !== this._colorShadingEnabled) {
        this._colorShadingEnabled = currentlyColorShadingEnabled;
        this._shouldRegenerateShaders = true;
      }

      // Regenerate shaders if splitting was enabled/disabled from last update
      const splittingEnabled = this.splitDirection !== SplitDirection$1.NONE;
      if (this._splittingEnabled !== splittingEnabled) {
        this._splittingEnabled = splittingEnabled;
        this._shouldRegenerateShaders = true;
      }

      if (this._shouldRegenerateShaders) {
        regenerateShaders(this, frameState);
      } else {
        updateColor(this, frameState, false);
        updateBackFaceCulling$2(this, frameState, false);
        updateSilhouette$1(this, frameState, false);
      }
    }

    if (justLoaded) {
      // Called after modelMatrix update.
      const model = this;
      frameState.afterRender.push(function () {
        model._ready = true;
        model._readyPromise.resolve(model);
      });
      return;
    }

    // We don't check show at the top of the function since we
    // want to be able to progressively load models when they are not shown,
    // and then have them visible immediately when show is set to true.
    if (show && !this._ignoreCommands) {
      // PERFORMANCE_IDEA: This is terrible
      const commandList = frameState.commandList;
      const passes = frameState.passes;
      const nodeCommands = this._nodeCommands;
      const length = nodeCommands.length;
      let i;
      let nc;

      const idl2D =
        frameState.mapProjection.ellipsoid.maximumRadius * CesiumMath.PI;
      let boundingVolume;

      if (passes.render || (passes.pick && this.allowPicking)) {
        for (i = 0; i < length; ++i) {
          nc = nodeCommands[i];
          if (nc.show) {
            let command = nc.command;
            if (silhouette) {
              command = nc.silhouetteModelCommand;
            } else if (translucent) {
              command = nc.translucentCommand;
            } else if (!backFaceCulling) {
              command = nc.disableCullingCommand;
            }
            commandList.push(command);
            boundingVolume = nc.command.boundingVolume;
            const left = boundingVolume.center.y - boundingVolume.radius;
            const right = boundingVolume.center.y + boundingVolume.radius;
            const overIdl =
              (left < idl2D && right > idl2D) ||
              (left < -idl2D && right > -idl2D);
            if (frameState.mode === SceneMode$1.SCENE2D && overIdl) {
              let command2D = nc.command2D;
              if (silhouette) {
                command2D = nc.silhouetteModelCommand2D;
              } else if (translucent) {
                command2D = nc.translucentCommand2D;
              } else if (!backFaceCulling) {
                command2D = nc.disableCullingCommand2D;
              }
              commandList.push(command2D);
            }
          }
        }

        if (silhouette && !passes.pick) {
          // Render second silhouette pass
          for (i = 0; i < length; ++i) {
            nc = nodeCommands[i];
            if (nc.show) {
              commandList.push(nc.silhouetteColorCommand);
              boundingVolume = nc.command.boundingVolume;
              const left = boundingVolume.center.y - boundingVolume.radius;
              const right = boundingVolume.center.y + boundingVolume.radius;
              const overIdl =
                (left < idl2D && right > idl2D) ||
                (left < -idl2D && right > -idl2D);
              if (frameState.mode === SceneMode$1.SCENE2D && overIdl) {
                commandList.push(nc.silhouetteColorCommand2D);
              }
            }
          }
        }
      }
    }

    const credit = this._credit;
    if (defined(credit)) {
      frameState.creditDisplay.addCredit(credit);
    }

    const resourceCredits = this._resourceCredits;
    const resourceCreditsLength = resourceCredits.length;
    for (let c = 0; c < resourceCreditsLength; c++) {
      frameState.creditDisplay.addCredit(resourceCredits[c]);
    }

    const gltfCredits = this._gltfCredits;
    const gltfCreditsLength = gltfCredits.length;
    for (let c = 0; c < gltfCreditsLength; c++) {
      frameState.creditDisplay.addCredit(gltfCredits[c]);
    }
  };

  function destroyIfNotCached(rendererResources, cachedRendererResources) {
    if (rendererResources.programs !== cachedRendererResources.programs) {
      destroy(rendererResources.programs);
    }
    if (
      rendererResources.silhouettePrograms !==
      cachedRendererResources.silhouettePrograms
    ) {
      destroy(rendererResources.silhouettePrograms);
    }
  }

  // Run from update iff:
  // - everything is loaded
  // - clipping planes state change OR color state set
  // Run this from destructor after removing color state and clipping plane state
  function regenerateShaders(model, frameState) {
    // In regards to _cachedRendererResources:
    // Fair to assume that this is data that should just never get modified due to clipping planes, model color, or splitting.
    // So if clipping planes, model color, or splitting are active:
    // - delink _rendererResources.*programs and create new dictionaries.
    // - do NOT destroy any programs - might be used by copies of the model or by might be needed in the future if clipping planes/model color is deactivated

    // If clipping planes, model color, and splitting inactive:
    // - destroy _rendererResources.*programs
    // - relink _rendererResources.*programs to _cachedRendererResources

    // In both cases, need to mark commands as dirty, re-run derived commands (elsewhere)

    const rendererResources = model._rendererResources;
    const cachedRendererResources = model._cachedRendererResources;
    destroyIfNotCached(rendererResources, cachedRendererResources);

    let programId;
    if (
      isClippingEnabled(model) ||
      isColorShadingEnabled(model) ||
      model.splitDirection !== SplitDirection$1.NONE ||
      model._shouldRegenerateShaders
    ) {
      model._shouldRegenerateShaders = false;

      rendererResources.programs = {};
      rendererResources.silhouettePrograms = {};

      const visitedPrograms = {};
      const techniques = model._sourceTechniques;
      let technique;

      for (const techniqueId in techniques) {
        if (techniques.hasOwnProperty(techniqueId)) {
          technique = techniques[techniqueId];
          programId = technique.program;
          if (!visitedPrograms[programId]) {
            visitedPrograms[programId] = true;
            recreateProgram(
              {
                programId: programId,
                techniqueId: techniqueId,
              },
              model,
              frameState.context
            );
          }
        }
      }
    } else {
      rendererResources.programs = cachedRendererResources.programs;
      rendererResources.silhouettePrograms =
        cachedRendererResources.silhouettePrograms;
    }

    // Fix all the commands, marking them as dirty so everything that derives will re-derive
    const rendererPrograms = rendererResources.programs;

    const nodeCommands = model._nodeCommands;
    const commandCount = nodeCommands.length;
    for (let i = 0; i < commandCount; ++i) {
      const nodeCommand = nodeCommands[i];
      programId = nodeCommand.programId;

      const renderProgram = rendererPrograms[programId];
      nodeCommand.command.shaderProgram = renderProgram;
      if (defined(nodeCommand.command2D)) {
        nodeCommand.command2D.shaderProgram = renderProgram;
      }
    }

    // Force update silhouette commands/shaders
    updateColor(model, frameState, true);
    updateBackFaceCulling$2(model, frameState, true);
    updateSilhouette$1(model, frameState, true);
  }

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see Model#destroy
   */
  Model.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * model = model && model.destroy();
   *
   * @see Model#isDestroyed
   */
  Model.prototype.destroy = function () {
    // Vertex arrays are unique to this model, destroy here.
    if (defined(this._precreatedAttributes)) {
      destroy(this._rendererResources.vertexArrays);
    }

    if (defined(this._removeUpdateHeightCallback)) {
      this._removeUpdateHeightCallback();
      this._removeUpdateHeightCallback = undefined;
    }

    if (defined(this._terrainProviderChangedCallback)) {
      this._terrainProviderChangedCallback();
      this._terrainProviderChangedCallback = undefined;
    }

    // Shaders modified for clipping and for color don't get cached, so destroy these manually
    if (defined(this._cachedRendererResources)) {
      destroyIfNotCached(this._rendererResources, this._cachedRendererResources);
    }

    this._rendererResources = undefined;
    this._cachedRendererResources =
      this._cachedRendererResources && this._cachedRendererResources.release();
    DracoLoader.destroyCachedDataForModel(this);

    const pickIds = this._pickIds;
    const length = pickIds.length;
    for (let i = 0; i < length; ++i) {
      pickIds[i].destroy();
    }

    releaseCachedGltf(this);
    this._quantizedVertexShaders = undefined;

    // Only destroy the ClippingPlaneCollection if this is the owner - if this model is part of a Cesium3DTileset,
    // _clippingPlanes references a ClippingPlaneCollection that this model does not own.
    const clippingPlaneCollection = this._clippingPlanes;
    if (
      defined(clippingPlaneCollection) &&
      !clippingPlaneCollection.isDestroyed() &&
      clippingPlaneCollection.owner === this
    ) {
      clippingPlaneCollection.destroy();
    }
    this._clippingPlanes = undefined;

    if (
      this._shouldDestroyImageBasedLighting &&
      !this._imageBasedLighting.isDestroyed()
    ) {
      this._imageBasedLighting.destroy();
    }

    this._imageBasedLighting = undefined;

    return destroyObject(this);
  };

  // exposed for testing
  Model._getClippingFunction = getClippingFunction;
  Model._modifyShaderForColor = modifyShaderForColor;

  /**
   * Represents the contents of a
   * {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/TileFormats/Batched3DModel|Batched 3D Model}
   * tile in a {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification|3D Tiles} tileset.
   * <p>
   * Implements the {@link Cesium3DTileContent} interface.
   * </p>
   *
   * @alias Batched3DModel3DTileContent
   * @constructor
   *
   * @private
   */
  function Batched3DModel3DTileContent(
    tileset,
    tile,
    resource,
    arrayBuffer,
    byteOffset
  ) {
    this._tileset = tileset;
    this._tile = tile;
    this._resource = resource;
    this._model = undefined;
    this._batchTable = undefined;
    this._features = undefined;

    this._classificationType = tileset.vectorClassificationOnly
      ? undefined
      : tileset.classificationType;

    this._metadata = undefined;

    // Populate from gltf when available
    this._batchIdAttributeName = undefined;
    this._diffuseAttributeOrUniformName = {};

    this._rtcCenterTransform = undefined;
    this._contentModelMatrix = undefined;

    this.featurePropertiesDirty = false;
    this._group = undefined;

    initialize$m(this, arrayBuffer, byteOffset);
  }

  // This can be overridden for testing purposes
  Batched3DModel3DTileContent._deprecationWarning = deprecationWarning;

  Object.defineProperties(Batched3DModel3DTileContent.prototype, {
    featuresLength: {
      get: function () {
        return this.batchTable.featuresLength;
      },
    },

    pointsLength: {
      get: function () {
        return this._model.pointsLength;
      },
    },

    trianglesLength: {
      get: function () {
        return this._model.trianglesLength;
      },
    },

    geometryByteLength: {
      get: function () {
        return this._model.geometryByteLength;
      },
    },

    texturesByteLength: {
      get: function () {
        return this._model.texturesByteLength;
      },
    },

    batchTableByteLength: {
      get: function () {
        return this.batchTable.batchTableByteLength;
      },
    },

    innerContents: {
      get: function () {
        return undefined;
      },
    },

    readyPromise: {
      get: function () {
        return this._model.readyPromise;
      },
    },

    tileset: {
      get: function () {
        return this._tileset;
      },
    },

    tile: {
      get: function () {
        return this._tile;
      },
    },

    url: {
      get: function () {
        return this._resource.getUrlComponent(true);
      },
    },

    metadata: {
      get: function () {
        return this._metadata;
      },
      set: function (value) {
        this._metadata = value;
      },
    },

    batchTable: {
      get: function () {
        return this._batchTable;
      },
    },

    group: {
      get: function () {
        return this._group;
      },
      set: function (value) {
        this._group = value;
      },
    },
  });

  function getBatchIdAttributeName(gltf) {
    let batchIdAttributeName = ModelUtility.getAttributeOrUniformBySemantic(
      gltf,
      "_BATCHID"
    );
    if (!defined(batchIdAttributeName)) {
      batchIdAttributeName = ModelUtility.getAttributeOrUniformBySemantic(
        gltf,
        "BATCHID"
      );
      if (defined(batchIdAttributeName)) {
        Batched3DModel3DTileContent._deprecationWarning(
          "b3dm-legacy-batchid",
          "The glTF in this b3dm uses the semantic `BATCHID`. Application-specific semantics should be prefixed with an underscore: `_BATCHID`."
        );
      }
    }
    return batchIdAttributeName;
  }

  function getVertexShaderCallback$1(content) {
    return function (vs, programId) {
      const batchTable = content._batchTable;
      const handleTranslucent = !defined(content._classificationType);

      const gltf = content._model.gltfInternal;
      if (defined(gltf)) {
        content._batchIdAttributeName = getBatchIdAttributeName(gltf);
        content._diffuseAttributeOrUniformName[
          programId
        ] = ModelUtility.getDiffuseAttributeOrUniform(gltf, programId);
      }

      const callback = batchTable.getVertexShaderCallback(
        handleTranslucent,
        content._batchIdAttributeName,
        content._diffuseAttributeOrUniformName[programId]
      );
      return defined(callback) ? callback(vs) : vs;
    };
  }

  function getFragmentShaderCallback$1(content) {
    return function (fs, programId) {
      const batchTable = content._batchTable;
      const handleTranslucent = !defined(content._classificationType);

      const gltf = content._model.gltfInternal;
      if (defined(gltf)) {
        content._diffuseAttributeOrUniformName[
          programId
        ] = ModelUtility.getDiffuseAttributeOrUniform(gltf, programId);
      }
      const callback = batchTable.getFragmentShaderCallback(
        handleTranslucent,
        content._diffuseAttributeOrUniformName[programId],
        false
      );
      return defined(callback) ? callback(fs) : fs;
    };
  }

  function getPickIdCallback$1(content) {
    return function () {
      return content._batchTable.getPickId();
    };
  }

  function getClassificationFragmentShaderCallback(content) {
    return function (fs) {
      const batchTable = content._batchTable;
      const callback = batchTable.getClassificationFragmentShaderCallback();
      return defined(callback) ? callback(fs) : fs;
    };
  }

  function createColorChangedCallback$2(content) {
    return function (batchId, color) {
      content._model.updateCommands(batchId, color);
    };
  }

  function initialize$m(content, arrayBuffer, byteOffset) {
    const tileset = content._tileset;
    const tile = content._tile;
    const resource = content._resource;

    const b3dm = B3dmParser.parse(arrayBuffer, byteOffset);

    let batchLength = b3dm.batchLength;

    const featureTableJson = b3dm.featureTableJson;
    const featureTableBinary = b3dm.featureTableBinary;
    const featureTable = new Cesium3DTileFeatureTable(
      featureTableJson,
      featureTableBinary
    );

    batchLength = featureTable.getGlobalProperty("BATCH_LENGTH");
    featureTable.featuresLength = batchLength;

    const batchTableJson = b3dm.batchTableJson;
    const batchTableBinary = b3dm.batchTableBinary;

    let colorChangedCallback;
    if (defined(content._classificationType)) {
      colorChangedCallback = createColorChangedCallback$2(content);
    }

    const batchTable = new Cesium3DTileBatchTable(
      content,
      batchLength,
      batchTableJson,
      batchTableBinary,
      colorChangedCallback
    );
    content._batchTable = batchTable;

    const gltfView = b3dm.gltf;

    const pickObject = {
      content: content,
      primitive: tileset,
    };

    content._rtcCenterTransform = Matrix4.IDENTITY;
    const rtcCenter = featureTable.getGlobalProperty(
      "RTC_CENTER",
      ComponentDatatype$1.FLOAT,
      3
    );
    if (defined(rtcCenter)) {
      content._rtcCenterTransform = Matrix4.fromTranslation(
        Cartesian3.fromArray(rtcCenter)
      );
    }

    content._contentModelMatrix = Matrix4.multiply(
      tile.computedTransform,
      content._rtcCenterTransform,
      new Matrix4()
    );

    if (!defined(content._classificationType)) {
      // PERFORMANCE_IDEA: patch the shader on demand, e.g., the first time show/color changes.
      // The pick shader still needs to be patched.
      content._model = new Model({
        gltf: gltfView,
        cull: false, // The model is already culled by 3D Tiles
        releaseGltfJson: true, // Models are unique and will not benefit from caching so save memory
        opaquePass: Pass$1.CESIUM_3D_TILE, // Draw opaque portions of the model during the 3D Tiles pass
        basePath: resource,
        requestType: RequestType$1.TILES3D,
        modelMatrix: content._contentModelMatrix,
        upAxis: tileset._modelUpAxis,
        forwardAxis: tileset._modelForwardAxis,
        shadows: tileset.shadows,
        debugWireframe: tileset.debugWireframe,
        incrementallyLoadTextures: false,
        vertexShaderLoaded: getVertexShaderCallback$1(content),
        fragmentShaderLoaded: getFragmentShaderCallback$1(content),
        uniformMapLoaded: batchTable.getUniformMapCallback(),
        pickIdLoaded: getPickIdCallback$1(content),
        addBatchIdToGeneratedShaders: batchLength > 0, // If the batch table has values in it, generated shaders will need a batchId attribute
        pickObject: pickObject,
        lightColor: tileset.lightColor,
        imageBasedLighting: tileset.imageBasedLighting,
        backFaceCulling: tileset.backFaceCulling,
        showOutline: tileset.showOutline,
        showCreditsOnScreen: tileset.showCreditsOnScreen,
      });
      content._model.readyPromise.then(function (model) {
        model.activeAnimations.addAll({
          loop: ModelAnimationLoop$1.REPEAT,
        });
      });
    } else {
      // This transcodes glTF to an internal representation for geometry so we can take advantage of the re-batching of vector data.
      // For a list of limitations on the input glTF, see the documentation for classificationType of Cesium3DTileset.
      content._model = new ClassificationModel({
        gltf: gltfView,
        cull: false, // The model is already culled by 3D Tiles
        basePath: resource,
        requestType: RequestType$1.TILES3D,
        modelMatrix: content._contentModelMatrix,
        upAxis: tileset._modelUpAxis,
        forwardAxis: tileset._modelForwardAxis,
        debugWireframe: tileset.debugWireframe,
        vertexShaderLoaded: getVertexShaderCallback$1(content),
        classificationShaderLoaded: getClassificationFragmentShaderCallback(
          content
        ),
        uniformMapLoaded: batchTable.getUniformMapCallback(),
        pickIdLoaded: getPickIdCallback$1(content),
        classificationType: content._classificationType,
        batchTable: batchTable,
      });
    }
  }

  function createFeatures$4(content) {
    const featuresLength = content.featuresLength;
    if (!defined(content._features) && featuresLength > 0) {
      const features = new Array(featuresLength);
      for (let i = 0; i < featuresLength; ++i) {
        features[i] = new Cesium3DTileFeature(content, i);
      }
      content._features = features;
    }
  }

  Batched3DModel3DTileContent.prototype.hasProperty = function (batchId, name) {
    return this._batchTable.hasProperty(batchId, name);
  };

  Batched3DModel3DTileContent.prototype.getFeature = function (batchId) {
    //>>includeStart('debug', pragmas.debug);
    const featuresLength = this.featuresLength;
    if (!defined(batchId) || batchId < 0 || batchId >= featuresLength) {
      throw new DeveloperError(
        `batchId is required and between zero and featuresLength - 1 (${
        featuresLength - 1
      }).`
      );
    }
    //>>includeEnd('debug');

    createFeatures$4(this);
    return this._features[batchId];
  };

  Batched3DModel3DTileContent.prototype.applyDebugSettings = function (
    enabled,
    color
  ) {
    color = enabled ? color : Color.WHITE;
    if (this.featuresLength === 0) {
      this._model.color = color;
    } else {
      this._batchTable.setAllColor(color);
    }
  };

  Batched3DModel3DTileContent.prototype.applyStyle = function (style) {
    if (this.featuresLength === 0) {
      const hasColorStyle = defined(style) && defined(style.color);
      const hasShowStyle = defined(style) && defined(style.show);
      this._model.color = hasColorStyle
        ? style.color.evaluateColor(undefined, this._model.color)
        : Color.clone(Color.WHITE, this._model.color);
      this._model.show = hasShowStyle ? style.show.evaluate(undefined) : true;
    } else {
      this._batchTable.applyStyle(style);
    }
  };

  Batched3DModel3DTileContent.prototype.update = function (tileset, frameState) {
    const commandStart = frameState.commandList.length;

    const model = this._model;
    const tile = this._tile;
    const batchTable = this._batchTable;

    // In the PROCESSING state we may be calling update() to move forward
    // the content's resource loading.  In the READY state, it will
    // actually generate commands.
    batchTable.update(tileset, frameState);

    this._contentModelMatrix = Matrix4.multiply(
      tile.computedTransform,
      this._rtcCenterTransform,
      this._contentModelMatrix
    );
    model.modelMatrix = this._contentModelMatrix;

    model.shadows = tileset.shadows;
    model.lightColor = tileset.lightColor;
    model.imageBasedLighting = tileset.imageBasedLighting;
    model.backFaceCulling = tileset.backFaceCulling;
    model.debugWireframe = tileset.debugWireframe;
    model.showCreditsOnScreen = tileset.showCreditsOnScreen;
    model.splitDirection = tileset.splitDirection;

    // Update clipping planes
    const tilesetClippingPlanes = tileset.clippingPlanes;
    model.referenceMatrix = tileset.clippingPlanesOriginMatrix;
    if (defined(tilesetClippingPlanes) && tile.clippingPlanesDirty) {
      // Dereference the clipping planes from the model if they are irrelevant.
      // Link/Dereference directly to avoid ownership checks.
      // This will also trigger synchronous shader regeneration to remove or add the clipping plane and color blending code.
      model._clippingPlanes =
        tilesetClippingPlanes.enabled && tile._isClipped
          ? tilesetClippingPlanes
          : undefined;
    }

    // If the model references a different ClippingPlaneCollection due to the tileset's collection being replaced with a
    // ClippingPlaneCollection that gives this tile the same clipping status, update the model to use the new ClippingPlaneCollection.
    if (
      defined(tilesetClippingPlanes) &&
      defined(model._clippingPlanes) &&
      model._clippingPlanes !== tilesetClippingPlanes
    ) {
      model._clippingPlanes = tilesetClippingPlanes;
    }

    model.update(frameState);

    // If any commands were pushed, add derived commands
    const commandEnd = frameState.commandList.length;
    if (
      commandStart < commandEnd &&
      (frameState.passes.render || frameState.passes.pick) &&
      !defined(this._classificationType)
    ) {
      batchTable.addDerivedCommands(frameState, commandStart);
    }
  };

  Batched3DModel3DTileContent.prototype.isDestroyed = function () {
    return false;
  };

  Batched3DModel3DTileContent.prototype.destroy = function () {
    this._model = this._model && this._model.destroy();
    this._batchTable = this._batchTable && this._batchTable.destroy();
    return destroyObject(this);
  };

  /**
   * Represents the contents of a
   * {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/TileFormats/Composite|Composite}
   * tile in a {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification|3D Tiles} tileset.
   * <p>
   * Implements the {@link Cesium3DTileContent} interface.
   * </p>
   *
   * @alias Composite3DTileContent
   * @constructor
   *
   * @private
   */
  function Composite3DTileContent(
    tileset,
    tile,
    resource,
    arrayBuffer,
    byteOffset,
    factory
  ) {
    this._tileset = tileset;
    this._tile = tile;
    this._resource = resource;
    this._contents = [];

    this._metadata = undefined;
    this._group = undefined;

    this._readyPromise = initialize$l(this, arrayBuffer, byteOffset, factory);
  }

  Object.defineProperties(Composite3DTileContent.prototype, {
    featurePropertiesDirty: {
      get: function () {
        const contents = this._contents;
        const length = contents.length;
        for (let i = 0; i < length; ++i) {
          if (contents[i].featurePropertiesDirty) {
            return true;
          }
        }

        return false;
      },
      set: function (value) {
        const contents = this._contents;
        const length = contents.length;
        for (let i = 0; i < length; ++i) {
          contents[i].featurePropertiesDirty = value;
        }
      },
    },

    /**
     * Part of the {@link Cesium3DTileContent} interface.  <code>Composite3DTileContent</code>
     * always returns <code>0</code>.  Instead call <code>featuresLength</code> for a tile in the composite.
     * @memberof Composite3DTileContent.prototype
     */
    featuresLength: {
      get: function () {
        return 0;
      },
    },

    /**
     * Part of the {@link Cesium3DTileContent} interface.  <code>Composite3DTileContent</code>
     * always returns <code>0</code>.  Instead call <code>pointsLength</code> for a tile in the composite.
     * @memberof Composite3DTileContent.prototype
     */
    pointsLength: {
      get: function () {
        return 0;
      },
    },

    /**
     * Part of the {@link Cesium3DTileContent} interface.  <code>Composite3DTileContent</code>
     * always returns <code>0</code>.  Instead call <code>trianglesLength</code> for a tile in the composite.
     * @memberof Composite3DTileContent.prototype
     */
    trianglesLength: {
      get: function () {
        return 0;
      },
    },

    /**
     * Part of the {@link Cesium3DTileContent} interface.  <code>Composite3DTileContent</code>
     * always returns <code>0</code>.  Instead call <code>geometryByteLength</code> for a tile in the composite.
     * @memberof Composite3DTileContent.prototype
     */
    geometryByteLength: {
      get: function () {
        return 0;
      },
    },

    /**
     * Part of the {@link Cesium3DTileContent} interface.   <code>Composite3DTileContent</code>
     * always returns <code>0</code>.  Instead call <code>texturesByteLength</code> for a tile in the composite.
     * @memberof Composite3DTileContent.prototype
     */
    texturesByteLength: {
      get: function () {
        return 0;
      },
    },

    /**
     * Part of the {@link Cesium3DTileContent} interface.  <code>Composite3DTileContent</code>
     * always returns <code>0</code>.  Instead call <code>batchTableByteLength</code> for a tile in the composite.
     * @memberof Composite3DTileContent.prototype
     */
    batchTableByteLength: {
      get: function () {
        return 0;
      },
    },

    innerContents: {
      get: function () {
        return this._contents;
      },
    },

    readyPromise: {
      get: function () {
        return this._readyPromise;
      },
    },

    tileset: {
      get: function () {
        return this._tileset;
      },
    },

    tile: {
      get: function () {
        return this._tile;
      },
    },

    url: {
      get: function () {
        return this._resource.getUrlComponent(true);
      },
    },

    /**
     * Part of the {@link Cesium3DTileContent} interface. <code>Composite3DTileContent</code>
     * both stores the content metadata and propagates the content metadata to all of its children.
     * @memberof Composite3DTileContent.prototype
     * @private
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     */
    metadata: {
      get: function () {
        return this._metadata;
      },
      set: function (value) {
        this._metadata = value;
        const contents = this._contents;
        const length = contents.length;
        for (let i = 0; i < length; ++i) {
          contents[i].metadata = value;
        }
      },
    },

    /**
     * Part of the {@link Cesium3DTileContent} interface. <code>Composite3DTileContent</code>
     * always returns <code>undefined</code>.  Instead call <code>batchTable</code> for a tile in the composite.
     * @memberof Composite3DTileContent.prototype
     */
    batchTable: {
      get: function () {
        return undefined;
      },
    },

    /**
     * Part of the {@link Cesium3DTileContent} interface. <code>Composite3DTileContent</code>
     * both stores the group metadata and propagates the group metadata to all of its children.
     * @memberof Composite3DTileContent.prototype
     * @private
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     */
    group: {
      get: function () {
        return this._group;
      },
      set: function (value) {
        this._group = value;
        const contents = this._contents;
        const length = contents.length;
        for (let i = 0; i < length; ++i) {
          contents[i].group = value;
        }
      },
    },
  });

  const sizeOfUint32$4 = Uint32Array.BYTES_PER_ELEMENT;

  function initialize$l(content, arrayBuffer, byteOffset, factory) {
    byteOffset = defaultValue(byteOffset, 0);

    const uint8Array = new Uint8Array(arrayBuffer);
    const view = new DataView(arrayBuffer);
    byteOffset += sizeOfUint32$4; // Skip magic

    const version = view.getUint32(byteOffset, true);
    if (version !== 1) {
      throw new RuntimeError(
        `Only Composite Tile version 1 is supported. Version ${version} is not.`
      );
    }
    byteOffset += sizeOfUint32$4;

    // Skip byteLength
    byteOffset += sizeOfUint32$4;

    const tilesLength = view.getUint32(byteOffset, true);
    byteOffset += sizeOfUint32$4;

    const contentPromises = [];

    for (let i = 0; i < tilesLength; ++i) {
      const tileType = getMagic(uint8Array, byteOffset);

      // Tile byte length is stored after magic and version
      const tileByteLength = view.getUint32(byteOffset + sizeOfUint32$4 * 2, true);

      const contentFactory = factory[tileType];

      if (defined(contentFactory)) {
        const innerContent = contentFactory(
          content._tileset,
          content._tile,
          content._resource,
          arrayBuffer,
          byteOffset
        );
        content._contents.push(innerContent);
        contentPromises.push(innerContent.readyPromise);
      } else {
        throw new RuntimeError(
          `Unknown tile content type, ${tileType}, inside Composite tile`
        );
      }

      byteOffset += tileByteLength;
    }

    return Promise.all(contentPromises).then(function () {
      return content;
    });
  }

  /**
   * Part of the {@link Cesium3DTileContent} interface.  <code>Composite3DTileContent</code>
   * always returns <code>false</code>.  Instead call <code>hasProperty</code> for a tile in the composite.
   */
  Composite3DTileContent.prototype.hasProperty = function (batchId, name) {
    return false;
  };

  /**
   * Part of the {@link Cesium3DTileContent} interface.  <code>Composite3DTileContent</code>
   * always returns <code>undefined</code>.  Instead call <code>getFeature</code> for a tile in the composite.
   */
  Composite3DTileContent.prototype.getFeature = function (batchId) {
    return undefined;
  };

  Composite3DTileContent.prototype.applyDebugSettings = function (
    enabled,
    color
  ) {
    const contents = this._contents;
    const length = contents.length;
    for (let i = 0; i < length; ++i) {
      contents[i].applyDebugSettings(enabled, color);
    }
  };

  Composite3DTileContent.prototype.applyStyle = function (style) {
    const contents = this._contents;
    const length = contents.length;
    for (let i = 0; i < length; ++i) {
      contents[i].applyStyle(style);
    }
  };

  Composite3DTileContent.prototype.update = function (tileset, frameState) {
    const contents = this._contents;
    const length = contents.length;
    for (let i = 0; i < length; ++i) {
      contents[i].update(tileset, frameState);
    }
  };

  Composite3DTileContent.prototype.isDestroyed = function () {
    return false;
  };

  Composite3DTileContent.prototype.destroy = function () {
    const contents = this._contents;
    const length = contents.length;
    for (let i = 0; i < length; ++i) {
      contents[i].destroy();
    }
    return destroyObject(this);
  };

  /**
   * Creates a batch of box, cylinder, ellipsoid and/or sphere geometries intersecting terrain or 3D Tiles.
   *
   * @alias Vector3DTileGeometry
   * @constructor
   *
   * @param {Object} options An object with following properties:
   * @param {Float32Array} [options.boxes] The boxes in the tile.
   * @param {Uint16Array} [options.boxBatchIds] The batch ids for each box.
   * @param {Float32Array} [options.cylinders] The cylinders in the tile.
   * @param {Uint16Array} [options.cylinderBatchIds] The batch ids for each cylinder.
   * @param {Float32Array} [options.ellipsoids] The ellipsoids in the tile.
   * @param {Uint16Array} [options.ellipsoidBatchIds] The batch ids for each ellipsoid.
   * @param {Float32Array} [options.spheres] The spheres in the tile.
   * @param {Uint16Array} [options.sphereBatchIds] The batch ids for each sphere.
   * @param {Cartesian3} options.center The RTC center of all geometries.
   * @param {Matrix4} options.modelMatrix The model matrix of all geometries. Applied after the individual geometry model matrices.
   * @param {Cesium3DTileBatchTable} options.batchTable The batch table.
   * @param {BoundingSphere} options.boundingVolume The bounding volume containing all of the geometry in the tile.
   *
   * @private
   */
  function Vector3DTileGeometry(options) {
    // these will all be released after the primitive is created
    this._boxes = options.boxes;
    this._boxBatchIds = options.boxBatchIds;
    this._cylinders = options.cylinders;
    this._cylinderBatchIds = options.cylinderBatchIds;
    this._ellipsoids = options.ellipsoids;
    this._ellipsoidBatchIds = options.ellipsoidBatchIds;
    this._spheres = options.spheres;
    this._sphereBatchIds = options.sphereBatchIds;
    this._modelMatrix = options.modelMatrix;
    this._batchTable = options.batchTable;
    this._boundingVolume = options.boundingVolume;

    this._center = options.center;
    if (!defined(this._center)) {
      if (defined(this._boundingVolume)) {
        this._center = Cartesian3.clone(this._boundingVolume.center);
      } else {
        this._center = Cartesian3.clone(Cartesian3.ZERO);
      }
    }

    this._boundingVolumes = undefined;
    this._batchedIndices = undefined;

    this._indices = undefined;
    this._indexOffsets = undefined;
    this._indexCounts = undefined;

    this._positions = undefined;
    this._vertexBatchIds = undefined;

    this._batchIds = undefined;

    this._batchTableColors = undefined;
    this._packedBuffer = undefined;

    this._ready = false;
    this._update = function (geometries, frameState) {};
    this._readyPromise = initialize$k(this);

    this._verticesPromise = undefined;

    this._primitive = undefined;

    /**
     * Draws the wireframe of the classification geometries.
     * @type {Boolean}
     * @default false
     */
    this.debugWireframe = false;

    /**
     * Forces a re-batch instead of waiting after a number of frames have been rendered. For testing only.
     * @type {Boolean}
     * @default false
     */
    this.forceRebatch = false;

    /**
     * What this tile will classify.
     * @type {ClassificationType}
     * @default ClassificationType.BOTH
     */
    this.classificationType = ClassificationType$1.BOTH;
  }

  Object.defineProperties(Vector3DTileGeometry.prototype, {
    /**
     * Gets the number of triangles.
     *
     * @memberof Vector3DTileGeometry.prototype
     *
     * @type {Number}
     * @readonly
     */
    trianglesLength: {
      get: function () {
        if (defined(this._primitive)) {
          return this._primitive.trianglesLength;
        }
        return 0;
      },
    },

    /**
     * Gets the geometry memory in bytes.
     *
     * @memberof Vector3DTileGeometry.prototype
     *
     * @type {Number}
     * @readonly
     */
    geometryByteLength: {
      get: function () {
        if (defined(this._primitive)) {
          return this._primitive.geometryByteLength;
        }
        return 0;
      },
    },

    /**
     * Gets a promise that resolves when the primitive is ready to render.
     * @memberof Vector3DTileGeometry.prototype
     * @type {Promise<void>}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._readyPromise;
      },
    },
  });

  Vector3DTileGeometry.packedBoxLength =
    Matrix4.packedLength + Cartesian3.packedLength;
  Vector3DTileGeometry.packedCylinderLength = Matrix4.packedLength + 2;
  Vector3DTileGeometry.packedEllipsoidLength =
    Matrix4.packedLength + Cartesian3.packedLength;
  Vector3DTileGeometry.packedSphereLength = Cartesian3.packedLength + 1;

  function packBuffer$4(geometries) {
    const packedBuffer = new Float64Array(
      Matrix4.packedLength + Cartesian3.packedLength
    );

    let offset = 0;
    Cartesian3.pack(geometries._center, packedBuffer, offset);
    offset += Cartesian3.packedLength;
    Matrix4.pack(geometries._modelMatrix, packedBuffer, offset);

    return packedBuffer;
  }

  function unpackBuffer$1(geometries, packedBuffer) {
    let offset = 0;

    const indicesBytesPerElement = packedBuffer[offset++];
    const numBVS = packedBuffer[offset++];
    const bvs = (geometries._boundingVolumes = new Array(numBVS));

    for (let i = 0; i < numBVS; ++i) {
      bvs[i] = BoundingSphere.unpack(packedBuffer, offset);
      offset += BoundingSphere.packedLength;
    }

    const numBatchedIndices = packedBuffer[offset++];
    const bis = (geometries._batchedIndices = new Array(numBatchedIndices));

    for (let j = 0; j < numBatchedIndices; ++j) {
      const color = Color.unpack(packedBuffer, offset);
      offset += Color.packedLength;

      const indexOffset = packedBuffer[offset++];
      const count = packedBuffer[offset++];

      const length = packedBuffer[offset++];
      const batchIds = new Array(length);

      for (let k = 0; k < length; ++k) {
        batchIds[k] = packedBuffer[offset++];
      }

      bis[j] = new Vector3DTileBatch({
        color: color,
        offset: indexOffset,
        count: count,
        batchIds: batchIds,
      });
    }

    return indicesBytesPerElement;
  }

  const createVerticesTaskProcessor$4 = new TaskProcessor(
    "createVectorTileGeometries",
    5
  );
  const scratchColor$k = new Color();

  function createPrimitive$1(geometries) {
    if (defined(geometries._primitive)) {
      return;
    }

    if (!defined(geometries._verticesPromise)) {
      let boxes = geometries._boxes;
      let boxBatchIds = geometries._boxBatchIds;
      let cylinders = geometries._cylinders;
      let cylinderBatchIds = geometries._cylinderBatchIds;
      let ellipsoids = geometries._ellipsoids;
      let ellipsoidBatchIds = geometries._ellipsoidBatchIds;
      let spheres = geometries._spheres;
      let sphereBatchIds = geometries._sphereBatchIds;

      let batchTableColors = geometries._batchTableColors;
      let packedBuffer = geometries._packedBuffer;

      if (!defined(batchTableColors)) {
        // Copy because they may be the views on the same buffer.
        let length = 0;
        if (defined(geometries._boxes)) {
          boxes = geometries._boxes = boxes.slice();
          boxBatchIds = geometries._boxBatchIds = boxBatchIds.slice();
          length += boxBatchIds.length;
        }
        if (defined(geometries._cylinders)) {
          cylinders = geometries._cylinders = cylinders.slice();
          cylinderBatchIds = geometries._cylinderBatchIds = cylinderBatchIds.slice();
          length += cylinderBatchIds.length;
        }
        if (defined(geometries._ellipsoids)) {
          ellipsoids = geometries._ellipsoids = ellipsoids.slice();
          ellipsoidBatchIds = geometries._ellipsoidBatchIds = ellipsoidBatchIds.slice();
          length += ellipsoidBatchIds.length;
        }
        if (defined(geometries._spheres)) {
          spheres = geometries._sphere = spheres.slice();
          sphereBatchIds = geometries._sphereBatchIds = sphereBatchIds.slice();
          length += sphereBatchIds.length;
        }

        batchTableColors = geometries._batchTableColors = new Uint32Array(length);
        const batchTable = geometries._batchTable;

        for (let i = 0; i < length; ++i) {
          const color = batchTable.getColor(i, scratchColor$k);
          batchTableColors[i] = color.toRgba();
        }

        packedBuffer = geometries._packedBuffer = packBuffer$4(geometries);
      }

      const transferrableObjects = [];
      if (defined(boxes)) {
        transferrableObjects.push(boxes.buffer, boxBatchIds.buffer);
      }
      if (defined(cylinders)) {
        transferrableObjects.push(cylinders.buffer, cylinderBatchIds.buffer);
      }
      if (defined(ellipsoids)) {
        transferrableObjects.push(ellipsoids.buffer, ellipsoidBatchIds.buffer);
      }
      if (defined(spheres)) {
        transferrableObjects.push(spheres.buffer, sphereBatchIds.buffer);
      }
      transferrableObjects.push(batchTableColors.buffer, packedBuffer.buffer);

      const parameters = {
        boxes: defined(boxes) ? boxes.buffer : undefined,
        boxBatchIds: defined(boxes) ? boxBatchIds.buffer : undefined,
        cylinders: defined(cylinders) ? cylinders.buffer : undefined,
        cylinderBatchIds: defined(cylinders)
          ? cylinderBatchIds.buffer
          : undefined,
        ellipsoids: defined(ellipsoids) ? ellipsoids.buffer : undefined,
        ellipsoidBatchIds: defined(ellipsoids)
          ? ellipsoidBatchIds.buffer
          : undefined,
        spheres: defined(spheres) ? spheres.buffer : undefined,
        sphereBatchIds: defined(spheres) ? sphereBatchIds.buffer : undefined,
        batchTableColors: batchTableColors.buffer,
        packedBuffer: packedBuffer.buffer,
      };

      const verticesPromise = (geometries._verticesPromise = createVerticesTaskProcessor$4.scheduleTask(
        parameters,
        transferrableObjects
      ));
      if (!defined(verticesPromise)) {
        // Postponed
        return;
      }

      return verticesPromise.then(function (result) {
        const packedBuffer = new Float64Array(result.packedBuffer);
        const indicesBytesPerElement = unpackBuffer$1(geometries, packedBuffer);

        if (indicesBytesPerElement === 2) {
          geometries._indices = new Uint16Array(result.indices);
        } else {
          geometries._indices = new Uint32Array(result.indices);
        }

        geometries._indexOffsets = new Uint32Array(result.indexOffsets);
        geometries._indexCounts = new Uint32Array(result.indexCounts);

        geometries._positions = new Float32Array(result.positions);
        geometries._vertexBatchIds = new Uint16Array(result.vertexBatchIds);

        geometries._batchIds = new Uint16Array(result.batchIds);

        geometries._ready = true;
      });
    }
  }

  function finishPrimitive$1(geometries) {
    if (geometries._ready && !defined(geometries._primitive)) {
      geometries._primitive = new Vector3DTilePrimitive({
        batchTable: geometries._batchTable,
        positions: geometries._positions,
        batchIds: geometries._batchIds,
        vertexBatchIds: geometries._vertexBatchIds,
        indices: geometries._indices,
        indexOffsets: geometries._indexOffsets,
        indexCounts: geometries._indexCounts,
        batchedIndices: geometries._batchedIndices,
        boundingVolume: geometries._boundingVolume,
        boundingVolumes: geometries._boundingVolumes,
        center: geometries._center,
        pickObject: defaultValue(geometries._pickObject, geometries),
      });

      geometries._boxes = undefined;
      geometries._boxBatchIds = undefined;
      geometries._cylinders = undefined;
      geometries._cylinderBatchIds = undefined;
      geometries._ellipsoids = undefined;
      geometries._ellipsoidBatchIds = undefined;
      geometries._spheres = undefined;
      geometries._sphereBatchIds = undefined;
      geometries._center = undefined;
      geometries._modelMatrix = undefined;
      geometries._batchTable = undefined;
      geometries._boundingVolume = undefined;

      geometries._boundingVolumes = undefined;
      geometries._batchedIndices = undefined;

      geometries._indices = undefined;
      geometries._indexOffsets = undefined;
      geometries._indexCounts = undefined;

      geometries._positions = undefined;
      geometries._vertexBatchIds = undefined;

      geometries._batchIds = undefined;

      geometries._batchTableColors = undefined;
      geometries._packedBuffer = undefined;

      geometries._verticesPromise = undefined;
    }
  }

  /**
   * Creates features for each geometry and places it at the batch id index of features.
   *
   * @param {Vector3DTileContent} content The vector tile content.
   * @param {Cesium3DTileFeature[]} features An array of features where the polygon features will be placed.
   */
  Vector3DTileGeometry.prototype.createFeatures = function (content, features) {
    this._primitive.createFeatures(content, features);
  };

  /**
   * Colors the entire tile when enabled is true. The resulting color will be (geometry batch table color * color).
   *
   * @param {Boolean} enabled Whether to enable debug coloring.
   * @param {Color} color The debug color.
   */
  Vector3DTileGeometry.prototype.applyDebugSettings = function (enabled, color) {
    this._primitive.applyDebugSettings(enabled, color);
  };

  /**
   * Apply a style to the content.
   *
   * @param {Cesium3DTileStyle} style The style.
   * @param {Cesium3DTileFeature[]} features The array of features.
   */
  Vector3DTileGeometry.prototype.applyStyle = function (style, features) {
    this._primitive.applyStyle(style, features);
  };

  /**
   * Call when updating the color of a geometry with batchId changes color. The geometries will need to be re-batched
   * on the next update.
   *
   * @param {Number} batchId The batch id of the geometries whose color has changed.
   * @param {Color} color The new polygon color.
   */
  Vector3DTileGeometry.prototype.updateCommands = function (batchId, color) {
    this._primitive.updateCommands(batchId, color);
  };

  function initialize$k(geometries) {
    return new Promise(function (resolve, reject) {
      geometries._update = function (geometries, frameState) {
        const promise = createPrimitive$1(geometries);

        if (geometries._ready) {
          geometries._primitive.debugWireframe = geometries.debugWireframe;
          geometries._primitive.forceRebatch = geometries.forceRebatch;
          geometries._primitive.classificationType =
            geometries.classificationType;
          geometries._primitive.update(frameState);
        }

        if (!defined(promise)) {
          return;
        }

        promise
          .then(function () {
            finishPrimitive$1(geometries);
            resolve(geometries);
          })
          .catch(function (e) {
            reject(e);
          });
      };
    });
  }

  /**
   * Updates the batches and queues the commands for rendering.
   *
   * @param {FrameState} frameState The current frame state.
   */
  Vector3DTileGeometry.prototype.update = function (frameState) {
    this._update(this, frameState);
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <p>
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   * </p>
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   */
  Vector3DTileGeometry.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <p>
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   * </p>
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   */
  Vector3DTileGeometry.prototype.destroy = function () {
    this._primitive = this._primitive && this._primitive.destroy();
    return destroyObject(this);
  };

  /**
   * <p>
   * Implements the {@link Cesium3DTileContent} interface.
   * </p>
   *
   * @alias Geometry3DTileContent
   * @constructor
   *
   * @private
   */
  function Geometry3DTileContent(
    tileset,
    tile,
    resource,
    arrayBuffer,
    byteOffset
  ) {
    this._tileset = tileset;
    this._tile = tile;
    this._resource = resource;
    this._geometries = undefined;

    this._metadata = undefined;

    this._batchTable = undefined;
    this._features = undefined;

    /**
     * Part of the {@link Cesium3DTileContent} interface.
     */
    this.featurePropertiesDirty = false;
    this._group = undefined;

    this._readyPromise = initialize$j(this, arrayBuffer, byteOffset);
  }

  Object.defineProperties(Geometry3DTileContent.prototype, {
    featuresLength: {
      get: function () {
        return defined(this._batchTable) ? this._batchTable.featuresLength : 0;
      },
    },

    pointsLength: {
      get: function () {
        return 0;
      },
    },

    trianglesLength: {
      get: function () {
        if (defined(this._geometries)) {
          return this._geometries.trianglesLength;
        }
        return 0;
      },
    },

    geometryByteLength: {
      get: function () {
        if (defined(this._geometries)) {
          return this._geometries.geometryByteLength;
        }
        return 0;
      },
    },

    texturesByteLength: {
      get: function () {
        return 0;
      },
    },

    batchTableByteLength: {
      get: function () {
        return defined(this._batchTable)
          ? this._batchTable.batchTableByteLength
          : 0;
      },
    },

    innerContents: {
      get: function () {
        return undefined;
      },
    },

    readyPromise: {
      get: function () {
        return this._readyPromise;
      },
    },

    tileset: {
      get: function () {
        return this._tileset;
      },
    },

    tile: {
      get: function () {
        return this._tile;
      },
    },

    url: {
      get: function () {
        return this._resource.getUrlComponent(true);
      },
    },

    metadata: {
      get: function () {
        return this._metadata;
      },
      set: function (value) {
        this._metadata = value;
      },
    },

    batchTable: {
      get: function () {
        return this._batchTable;
      },
    },

    group: {
      get: function () {
        return this._group;
      },
      set: function (value) {
        this._group = value;
      },
    },
  });

  function createColorChangedCallback$1(content) {
    return function (batchId, color) {
      if (defined(content._geometries)) {
        content._geometries.updateCommands(batchId, color);
      }
    };
  }

  function getBatchIds$1(featureTableJson, featureTableBinary) {
    let boxBatchIds;
    let cylinderBatchIds;
    let ellipsoidBatchIds;
    let sphereBatchIds;
    let i;

    const numberOfBoxes = defaultValue(featureTableJson.BOXES_LENGTH, 0);
    const numberOfCylinders = defaultValue(featureTableJson.CYLINDERS_LENGTH, 0);
    const numberOfEllipsoids = defaultValue(
      featureTableJson.ELLIPSOIDS_LENGTH,
      0
    );
    const numberOfSpheres = defaultValue(featureTableJson.SPHERES_LENGTH, 0);

    if (numberOfBoxes > 0 && defined(featureTableJson.BOX_BATCH_IDS)) {
      const boxBatchIdsByteOffset =
        featureTableBinary.byteOffset + featureTableJson.BOX_BATCH_IDS.byteOffset;
      boxBatchIds = new Uint16Array(
        featureTableBinary.buffer,
        boxBatchIdsByteOffset,
        numberOfBoxes
      );
    }

    if (numberOfCylinders > 0 && defined(featureTableJson.CYLINDER_BATCH_IDS)) {
      const cylinderBatchIdsByteOffset =
        featureTableBinary.byteOffset +
        featureTableJson.CYLINDER_BATCH_IDS.byteOffset;
      cylinderBatchIds = new Uint16Array(
        featureTableBinary.buffer,
        cylinderBatchIdsByteOffset,
        numberOfCylinders
      );
    }

    if (numberOfEllipsoids > 0 && defined(featureTableJson.ELLIPSOID_BATCH_IDS)) {
      const ellipsoidBatchIdsByteOffset =
        featureTableBinary.byteOffset +
        featureTableJson.ELLIPSOID_BATCH_IDS.byteOffset;
      ellipsoidBatchIds = new Uint16Array(
        featureTableBinary.buffer,
        ellipsoidBatchIdsByteOffset,
        numberOfEllipsoids
      );
    }

    if (numberOfSpheres > 0 && defined(featureTableJson.SPHERE_BATCH_IDS)) {
      const sphereBatchIdsByteOffset =
        featureTableBinary.byteOffset +
        featureTableJson.SPHERE_BATCH_IDS.byteOffset;
      sphereBatchIds = new Uint16Array(
        featureTableBinary.buffer,
        sphereBatchIdsByteOffset,
        numberOfSpheres
      );
    }

    const atLeastOneDefined =
      defined(boxBatchIds) ||
      defined(cylinderBatchIds) ||
      defined(ellipsoidBatchIds) ||
      defined(sphereBatchIds);
    const atLeastOneUndefined =
      (numberOfBoxes > 0 && !defined(boxBatchIds)) ||
      (numberOfCylinders > 0 && !defined(cylinderBatchIds)) ||
      (numberOfEllipsoids > 0 && !defined(ellipsoidBatchIds)) ||
      (numberOfSpheres > 0 && !defined(sphereBatchIds));

    if (atLeastOneDefined && atLeastOneUndefined) {
      throw new RuntimeError(
        "If one group of batch ids is defined, then all batch ids must be defined."
      );
    }

    const allUndefinedBatchIds =
      !defined(boxBatchIds) &&
      !defined(cylinderBatchIds) &&
      !defined(ellipsoidBatchIds) &&
      !defined(sphereBatchIds);
    if (allUndefinedBatchIds) {
      let id = 0;
      if (!defined(boxBatchIds) && numberOfBoxes > 0) {
        boxBatchIds = new Uint16Array(numberOfBoxes);
        for (i = 0; i < numberOfBoxes; ++i) {
          boxBatchIds[i] = id++;
        }
      }
      if (!defined(cylinderBatchIds) && numberOfCylinders > 0) {
        cylinderBatchIds = new Uint16Array(numberOfCylinders);
        for (i = 0; i < numberOfCylinders; ++i) {
          cylinderBatchIds[i] = id++;
        }
      }
      if (!defined(ellipsoidBatchIds) && numberOfEllipsoids > 0) {
        ellipsoidBatchIds = new Uint16Array(numberOfEllipsoids);
        for (i = 0; i < numberOfEllipsoids; ++i) {
          ellipsoidBatchIds[i] = id++;
        }
      }
      if (!defined(sphereBatchIds) && numberOfSpheres > 0) {
        sphereBatchIds = new Uint16Array(numberOfSpheres);
        for (i = 0; i < numberOfSpheres; ++i) {
          sphereBatchIds[i] = id++;
        }
      }
    }

    return {
      boxes: boxBatchIds,
      cylinders: cylinderBatchIds,
      ellipsoids: ellipsoidBatchIds,
      spheres: sphereBatchIds,
    };
  }

  const sizeOfUint32$3 = Uint32Array.BYTES_PER_ELEMENT;

  function initialize$j(content, arrayBuffer, byteOffset) {
    byteOffset = defaultValue(byteOffset, 0);

    const uint8Array = new Uint8Array(arrayBuffer);
    const view = new DataView(arrayBuffer);
    byteOffset += sizeOfUint32$3; // Skip magic number

    const version = view.getUint32(byteOffset, true);
    if (version !== 1) {
      throw new RuntimeError(
        `Only Geometry tile version 1 is supported.  Version ${version} is not.`
      );
    }
    byteOffset += sizeOfUint32$3;

    const byteLength = view.getUint32(byteOffset, true);
    byteOffset += sizeOfUint32$3;

    if (byteLength === 0) {
      content._readyPromise.resolve(content);
      return;
    }

    const featureTableJSONByteLength = view.getUint32(byteOffset, true);
    byteOffset += sizeOfUint32$3;

    if (featureTableJSONByteLength === 0) {
      throw new RuntimeError(
        "Feature table must have a byte length greater than zero"
      );
    }

    const featureTableBinaryByteLength = view.getUint32(byteOffset, true);
    byteOffset += sizeOfUint32$3;
    const batchTableJSONByteLength = view.getUint32(byteOffset, true);
    byteOffset += sizeOfUint32$3;
    const batchTableBinaryByteLength = view.getUint32(byteOffset, true);
    byteOffset += sizeOfUint32$3;

    const featureTableJson = getJsonFromTypedArray(
      uint8Array,
      byteOffset,
      featureTableJSONByteLength
    );
    byteOffset += featureTableJSONByteLength;

    const featureTableBinary = new Uint8Array(
      arrayBuffer,
      byteOffset,
      featureTableBinaryByteLength
    );
    byteOffset += featureTableBinaryByteLength;

    let batchTableJson;
    let batchTableBinary;
    if (batchTableJSONByteLength > 0) {
      // PERFORMANCE_IDEA: is it possible to allocate this on-demand?  Perhaps keep the
      // arraybuffer/string compressed in memory and then decompress it when it is first accessed.
      //
      // We could also make another request for it, but that would make the property set/get
      // API async, and would double the number of numbers in some cases.
      batchTableJson = getJsonFromTypedArray(
        uint8Array,
        byteOffset,
        batchTableJSONByteLength
      );
      byteOffset += batchTableJSONByteLength;

      if (batchTableBinaryByteLength > 0) {
        // Has a batch table binary
        batchTableBinary = new Uint8Array(
          arrayBuffer,
          byteOffset,
          batchTableBinaryByteLength
        );
        // Copy the batchTableBinary section and let the underlying ArrayBuffer be freed
        batchTableBinary = new Uint8Array(batchTableBinary);
      }
    }

    const numberOfBoxes = defaultValue(featureTableJson.BOXES_LENGTH, 0);
    const numberOfCylinders = defaultValue(featureTableJson.CYLINDERS_LENGTH, 0);
    const numberOfEllipsoids = defaultValue(
      featureTableJson.ELLIPSOIDS_LENGTH,
      0
    );
    const numberOfSpheres = defaultValue(featureTableJson.SPHERES_LENGTH, 0);

    const totalPrimitives =
      numberOfBoxes + numberOfCylinders + numberOfEllipsoids + numberOfSpheres;

    const batchTable = new Cesium3DTileBatchTable(
      content,
      totalPrimitives,
      batchTableJson,
      batchTableBinary,
      createColorChangedCallback$1(content)
    );
    content._batchTable = batchTable;

    if (totalPrimitives === 0) {
      return;
    }

    const modelMatrix = content.tile.computedTransform;

    let center;
    if (defined(featureTableJson.RTC_CENTER)) {
      center = Cartesian3.unpack(featureTableJson.RTC_CENTER);
      Matrix4.multiplyByPoint(modelMatrix, center, center);
    }

    const batchIds = getBatchIds$1(featureTableJson, featureTableBinary);

    if (
      numberOfBoxes > 0 ||
      numberOfCylinders > 0 ||
      numberOfEllipsoids > 0 ||
      numberOfSpheres > 0
    ) {
      let boxes;
      let cylinders;
      let ellipsoids;
      let spheres;

      if (numberOfBoxes > 0) {
        const boxesByteOffset =
          featureTableBinary.byteOffset + featureTableJson.BOXES.byteOffset;
        boxes = new Float32Array(
          featureTableBinary.buffer,
          boxesByteOffset,
          Vector3DTileGeometry.packedBoxLength * numberOfBoxes
        );
      }

      if (numberOfCylinders > 0) {
        const cylindersByteOffset =
          featureTableBinary.byteOffset + featureTableJson.CYLINDERS.byteOffset;
        cylinders = new Float32Array(
          featureTableBinary.buffer,
          cylindersByteOffset,
          Vector3DTileGeometry.packedCylinderLength * numberOfCylinders
        );
      }

      if (numberOfEllipsoids > 0) {
        const ellipsoidsByteOffset =
          featureTableBinary.byteOffset + featureTableJson.ELLIPSOIDS.byteOffset;
        ellipsoids = new Float32Array(
          featureTableBinary.buffer,
          ellipsoidsByteOffset,
          Vector3DTileGeometry.packedEllipsoidLength * numberOfEllipsoids
        );
      }

      if (numberOfSpheres > 0) {
        const spheresByteOffset =
          featureTableBinary.byteOffset + featureTableJson.SPHERES.byteOffset;
        spheres = new Float32Array(
          featureTableBinary.buffer,
          spheresByteOffset,
          Vector3DTileGeometry.packedSphereLength * numberOfSpheres
        );
      }

      content._geometries = new Vector3DTileGeometry({
        boxes: boxes,
        boxBatchIds: batchIds.boxes,
        cylinders: cylinders,
        cylinderBatchIds: batchIds.cylinders,
        ellipsoids: ellipsoids,
        ellipsoidBatchIds: batchIds.ellipsoids,
        spheres: spheres,
        sphereBatchIds: batchIds.spheres,
        center: center,
        modelMatrix: modelMatrix,
        batchTable: batchTable,
        boundingVolume: content.tile.boundingVolume.boundingVolume,
      });

      return content._geometries.readyPromise.then(function () {
        return content;
      });
    }

    return Promise.resolve(content);
  }

  function createFeatures$3(content) {
    const featuresLength = content.featuresLength;
    if (!defined(content._features) && featuresLength > 0) {
      const features = new Array(featuresLength);
      if (defined(content._geometries)) {
        content._geometries.createFeatures(content, features);
      }
      content._features = features;
    }
  }

  Geometry3DTileContent.prototype.hasProperty = function (batchId, name) {
    return this._batchTable.hasProperty(batchId, name);
  };

  Geometry3DTileContent.prototype.getFeature = function (batchId) {
    //>>includeStart('debug', pragmas.debug);
    const featuresLength = this.featuresLength;
    if (!defined(batchId) || batchId < 0 || batchId >= featuresLength) {
      throw new DeveloperError(
        `batchId is required and between zero and featuresLength - 1 (${
        featuresLength - 1
      }).`
      );
    }
    //>>includeEnd('debug');

    createFeatures$3(this);
    return this._features[batchId];
  };

  Geometry3DTileContent.prototype.applyDebugSettings = function (enabled, color) {
    if (defined(this._geometries)) {
      this._geometries.applyDebugSettings(enabled, color);
    }
  };

  Geometry3DTileContent.prototype.applyStyle = function (style) {
    createFeatures$3(this);
    if (defined(this._geometries)) {
      this._geometries.applyStyle(style, this._features);
    }
  };

  Geometry3DTileContent.prototype.update = function (tileset, frameState) {
    if (defined(this._geometries)) {
      this._geometries.classificationType = this._tileset.classificationType;
      this._geometries.debugWireframe = this._tileset.debugWireframe;
      this._geometries.update(frameState);
    }
    if (defined(this._batchTable) && this._geometries._ready) {
      this._batchTable.update(tileset, frameState);
    }
  };

  Geometry3DTileContent.prototype.isDestroyed = function () {
    return false;
  };

  Geometry3DTileContent.prototype.destroy = function () {
    this._geometries = this._geometries && this._geometries.destroy();
    this._batchTable = this._batchTable && this._batchTable.destroy();
    return destroyObject(this);
  };

  /**
   * Check if a specific extension is present on a JSON object. This can be used
   * for either 3D Tiles extensions or glTF extensions
   * @param {Object} json The JSON object
   * @param {String} extensionName The name of the extension, e.g. '3DTILES_implicit_tiling'
   * @returns {Boolean} True if the extension is present
   * @private
   */
  function hasExtension(json, extensionName) {
    return (
      defined(json) &&
      defined(json.extensions) &&
      defined(json.extensions[extensionName])
    );
  }

  /**
   * An availability bitstream for use in an {@link ImplicitSubtree}. This handles
   * both Uint8Array bitstreams and constant values.
   *
   * @alias ImplicitAvailabilityBitstream
   * @constructor
   *
   * @param {Object} options An object with the following properties:
   * @param {Number} options.lengthBits The length of the bitstream in bits
   * @param {Boolean} [options.constant] A single boolean value indicating the value of all the bits in the bitstream if they are all the same
   * @param {Uint8Array} [options.bitstream] An array of bytes storing the bitstream in binary
   * @param {Number} [options.availableCount] A number indicating how many 1 bits are found in the bitstream
   * @param {Boolean} [options.computeAvailableCountEnabled=false] If true, and options.availableCount is undefined, the availableCount will be computed from the bitstream.
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function ImplicitAvailabilityBitstream(options) {
    const lengthBits = options.lengthBits;
    let availableCount = options.availableCount;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("options.lengthBits", lengthBits);
    //>>includeEnd('debug');

    const constant = options.constant;
    const bitstream = options.bitstream;

    if (defined(constant)) {
      // if defined, constant must be 1 which means all tiles are available
      availableCount = lengthBits;
    } else {
      const expectedLength = Math.ceil(lengthBits / 8);
      if (bitstream.length !== expectedLength) {
        throw new RuntimeError(
          `Availability bitstream must be exactly ${expectedLength} bytes long to store ${lengthBits} bits. Actual bitstream was ${bitstream.length} bytes long.`
        );
      }

      // Only compute the available count if requested, as this involves looping
      // over the bitstream.
      const computeAvailableCountEnabled = defaultValue(
        options.computeAvailableCountEnabled,
        false
      );
      if (!defined(availableCount) && computeAvailableCountEnabled) {
        availableCount = count1Bits(bitstream, lengthBits);
      }
    }

    this._lengthBits = lengthBits;
    this._availableCount = availableCount;
    this._constant = constant;
    this._bitstream = bitstream;
  }

  /**
   * Count the number of bits with value 1 in the bitstream. This is used for
   * computing availableCount if not precomputed
   *
   * @param {Uint8Array} bitstream The bitstream typed array
   * @param {Number} lengthBits How many bits are in the bitstream
   * @private
   */
  function count1Bits(bitstream, lengthBits) {
    let count = 0;
    for (let i = 0; i < lengthBits; i++) {
      const byteIndex = i >> 3;
      const bitIndex = i % 8;
      count += (bitstream[byteIndex] >> bitIndex) & 1;
    }
    return count;
  }

  Object.defineProperties(ImplicitAvailabilityBitstream.prototype, {
    /**
     * The length of the bitstream in bits.
     *
     * @memberof ImplicitAvailabilityBitstream.prototype
     *
     * @type {Number}
     * @readonly
     * @private
     */
    lengthBits: {
      get: function () {
        return this._lengthBits;
      },
    },
    /**
     * The number of bits in the bitstream with value <code>1</code>.
     *
     * @memberof ImplicitAvailabilityBitstream.prototype
     *
     * @type {Number}
     * @readonly
     * @private
     */
    availableCount: {
      get: function () {
        return this._availableCount;
      },
    },
  });

  /**
   * Get a bit from the availability bitstream as a Boolean. If the bitstream
   * is a constant, the constant value is returned instead.
   *
   * @param {Number} index The integer index of the bit.
   * @returns {Boolean} The value of the bit
   * @private
   */
  ImplicitAvailabilityBitstream.prototype.getBit = function (index) {
    //>>includeStart('debug', pragmas.debug);
    if (index < 0 || index >= this._lengthBits) {
      throw new DeveloperError("Bit index out of bounds.");
    }
    //>>includeEnd('debug');

    if (defined(this._constant)) {
      return this._constant;
    }

    // byteIndex is floor(index / 8)
    const byteIndex = index >> 3;
    const bitIndex = index % 8;

    return ((this._bitstream[byteIndex] >> bitIndex) & 1) === 1;
  };

  /**
   * This class represents a single entity in the <code>MetadataTable</code> owned by an implicit subtree. The entity is specified by the entityId.
   * <p>
   * See the {@link https://github.com/CesiumGS/3d-tiles/tree/main/extensions/3DTILES_metadata|3DTILES_metadata Extension} for 3D Tiles
   * </p>
   *
   * @param {MetadataTable} options.metadataTable The metadata table.
   * @param {MetadataClass} options.class The class that the metadata conforms to.
   * @param {Number} options.entityId The ID of the entity the metadata belongs to.
   * @param {Object} options.propertyTableJson The JSON that contains the property table of the entity.
   *
   * @alias ImplicitMetadataView
   * @constructor
   *
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function ImplicitMetadataView(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const metadataTable = options.metadataTable;
    const metadataClass = options.class;
    const entityId = options.entityId;
    const propertyTableJson = options.propertyTableJson;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.metadataTable", metadataTable);
    Check.typeOf.object("options.class", metadataClass);
    Check.typeOf.number("options.entityId", entityId);
    Check.typeOf.object("options.propertyTableJson", propertyTableJson);

    //>>includeEnd('debug');

    this._class = metadataClass;
    this._metadataTable = metadataTable;
    this._entityId = entityId;

    this._extensions = propertyTableJson.extensions;
    this._extras = propertyTableJson.extras;
  }

  Object.defineProperties(ImplicitMetadataView.prototype, {
    /**
     * The class that properties conform to.
     *
     * @memberof ImplicitMetadataView.prototype
     * @type {MetadataClass}
     * @readonly
     */
    class: {
      get: function () {
        return this._class;
      },
    },

    /**
     * Extras in the JSON object.
     *
     * @memberof ImplicitMetadataView.prototype
     * @type {Object}
     * @readonly
     */
    extras: {
      get: function () {
        return this._extras;
      },
    },

    /**
     * Extensions in the JSON object.
     *
     * @memberof ImplicitMetadataView.prototype
     * @type {Object}
     * @readonly
     */
    extensions: {
      get: function () {
        return this._extensions;
      },
    },
  });

  /**
   * Returns whether the metadata contains this property.
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @returns {Boolean} Whether the tile has this property.
   * @private
   */
  ImplicitMetadataView.prototype.hasProperty = function (propertyId) {
    return this._metadataTable.hasProperty(propertyId);
  };

  /**
   * Returns whether the metadata contains a property with the given semantic.
   *
   * @param {String} semantic The case-sensitive semantic of the property.
   * @returns {Boolean} Whether the tile has a property with the given semantic.
   * @private
   */
  ImplicitMetadataView.prototype.hasPropertyBySemantic = function (semantic) {
    return this._metadataTable.hasPropertyBySemantic(semantic);
  };

  /**
   * Returns an array of property IDs in the metadata table.
   *
   * @param {String[]} [results] An array into which to store the results.
   * @returns {String[]} The property IDs.
   * @private
   */
  ImplicitMetadataView.prototype.getPropertyIds = function (results) {
    return this._metadataTable.getPropertyIds(results);
  };

  /**
   * Returns a copy of the value of the property with the given ID.
   * <p>
   * If the property is normalized the normalized value is returned.
   * </p>
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @returns {*} The value of the property or <code>undefined</code> if the tile does not have this property.
   * @private
   */
  ImplicitMetadataView.prototype.getProperty = function (propertyId) {
    return this._metadataTable.getProperty(this._entityId, propertyId);
  };

  /**
   * Sets the value of the property with the given ID in the metadata table.
   * <p>
   * If the property is normalized a normalized value must be provided to this function.
   * </p>
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @param {*} value The value of the property that will be copied.
   * @returns {Boolean} <code>true</code> if the property was set, <code>false</code> otherwise.
   * @private
   */
  ImplicitMetadataView.prototype.setProperty = function (propertyId, value) {
    return this._metadataTable.setProperty(this._entityId, propertyId, value);
  };

  /**
   * Returns a copy of the value of the property with the given semantic in the metadata table.
   *
   * @param {String} semantic The case-sensitive semantic of the property.
   * @returns {*} The value of the property or <code>undefined</code> if the tile does not have this semantic.
   * @private
   */
  ImplicitMetadataView.prototype.getPropertyBySemantic = function (semantic) {
    return this._metadataTable.getPropertyBySemantic(this._entityId, semantic);
  };

  /**
   * Sets the value of the property with the given semantic in the metadata table.
   *
   * @param {String} semantic The case-sensitive semantic of the property.
   * @param {*} value The value of the property that will be copied.
   * @returns {Boolean} <code>true</code> if the property was set, <code>false</code> otherwise.
   * @private
   */

  ImplicitMetadataView.prototype.setPropertyBySemantic = function (
    semantic,
    value
  ) {
    return this._metadataTable.setPropertyBySemantic(
      this._entityId,
      semantic,
      value
    );
  };

  /**
   * The subdivision scheme for an implicit tileset.
   *
   * @enum {String}
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  const ImplicitSubdivisionScheme = {
    /**
     * A quadtree divides a parent tile into four children, split at the midpoint
     * of the x and y dimensions of the bounding box
     * @type {String}
     * @constant
     * @private
     */
    QUADTREE: "QUADTREE",
    /**
     * An octree divides a parent tile into eight children, split at the midpoint
     * of the x, y, and z dimensions of the bounding box.
     * @type {String}
     * @constant
     * @private
     */
    OCTREE: "OCTREE",
  };

  /**
   * Get the branching factor for the given subdivision scheme
   * @param {ImplicitSubdivisionScheme} subdivisionScheme The subdivision scheme
   * @returns {Number} The branching factor, either 4 for QUADTREE or 8 for OCTREE
   * @private
   */
  ImplicitSubdivisionScheme.getBranchingFactor = function (subdivisionScheme) {
    switch (subdivisionScheme) {
      case ImplicitSubdivisionScheme.OCTREE:
        return 8;
      case ImplicitSubdivisionScheme.QUADTREE:
        return 4;
      //>>includeStart('debug', pragmas.debug);
      default:
        throw new DeveloperError("subdivisionScheme is not a valid value.");
      //>>includeEnd('debug');
    }
  };

  var ImplicitSubdivisionScheme$1 = Object.freeze(ImplicitSubdivisionScheme);

  /**
   * An entity containing metadata.
   * <p>
   * This type describes an interface and is not intended to be instantiated directly.
   * </p>
   * <p>
   * See the {@link https://github.com/CesiumGS/3d-tiles/tree/main/extensions/3DTILES_metadata|3DTILES_metadata Extension} for 3D Tiles
   * </p>
   *
   * @alias MetadataEntity
   * @constructor
   *
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function MetadataEntity() {}

  Object.defineProperties(MetadataEntity.prototype, {
    /**
     * The class that properties conform to.
     *
     * @memberof MetadataEntity.prototype
     * @type {MetadataClass}
     * @readonly
     * @private
     */
    class: {
      // eslint-disable-next-line getter-return
      get: function () {
        DeveloperError.throwInstantiationError();
      },
    },
  });

  /**
   * Returns whether the entity has this property.
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @returns {Boolean} Whether the entity has this property.
   * @private
   */
  MetadataEntity.prototype.hasProperty = function (propertyId) {
    DeveloperError.throwInstantiationError();
  };

  /**
   * Returns whether the entity has a property with the given semantic.
   *
   * @param {String} semantic The case-sensitive semantic of the property.
   * @returns {Boolean} Whether the entity has a property with the given semantic.
   * @private
   */
  MetadataEntity.prototype.hasPropertyBySemantic = function (semantic) {
    DeveloperError.throwInstantiationError();
  };

  /**
   * Returns an array of property IDs.
   *
   * @param {String[]} [results] An array into which to store the results.
   * @returns {String[]} The property IDs.
   * @private
   */
  MetadataEntity.prototype.getPropertyIds = function (results) {
    DeveloperError.throwInstantiationError();
  };

  /**
   * Returns a copy of the value of the property with the given ID.
   * <p>
   * If the property is normalized the normalized value is returned.
   * </p>
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @returns {*} The value of the property or <code>undefined</code> if the entity does not have this property.
   * @private
   */
  MetadataEntity.prototype.getProperty = function (propertyId) {
    DeveloperError.throwInstantiationError();
  };

  /**
   * Sets the value of the property with the given ID.
   * <p>
   * If the property is normalized a normalized value must be provided to this function.
   * </p>
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @param {*} value The value of the property that will be copied.
   * @returns {Boolean} <code>true</code> if the property was set, <code>false</code> otherwise.
   * @private
   */
  MetadataEntity.prototype.setProperty = function (propertyId, value) {
    DeveloperError.throwInstantiationError();
  };

  /**
   * Returns a copy of the value of the property with the given semantic.
   *
   * @param {String} semantic The case-sensitive semantic of the property.
   * @returns {*} The value of the property or <code>undefined</code> if the entity does not have this property.
   * @private
   */
  MetadataEntity.prototype.getPropertyBySemantic = function (semantic) {
    DeveloperError.throwInstantiationError();
  };

  /**
   * Sets the value of the property with the given semantic.
   *
   * @param {String} semantic The case-sensitive semantic of the property.
   * @param {*} value The value of the property that will be copied.
   * @returns {Boolean} <code>true</code> if the property was set, <code>false</code> otherwise.
   * @private
   */
  MetadataEntity.prototype.setPropertyBySemantic = function (semantic, value) {
    DeveloperError.throwInstantiationError();
  };

  /**
   * Returns whether the entity has this property.
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @param {Object} properties The dictionary containing properties.
   * @param {MetadataClass} classDefinition The class.
   * @returns {Boolean} Whether the entity has this property.
   *
   * @private
   */
  MetadataEntity.hasProperty = function (
    propertyId,
    properties,
    classDefinition
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("propertyId", propertyId);
    Check.typeOf.object("properties", properties);
    Check.typeOf.object("classDefinition", classDefinition);
    //>>includeEnd('debug');

    if (defined(properties[propertyId])) {
      return true;
    }

    const classProperties = classDefinition.properties;
    if (!defined(classProperties)) {
      return false;
    }

    const classProperty = classProperties[propertyId];
    if (defined(classProperty) && defined(classProperty.default)) {
      return true;
    }

    return false;
  };

  /**
   * Returns whether the entity has a property with the given semantic.
   *
   * @param {String} semantic The case-sensitive semantic of the property.
   * @param {Object} properties The dictionary containing properties.
   * @param {MetadataClass} classDefinition The class.
   * @returns {Boolean} Whether the entity has a property with the given semantic.
   *
   * @private
   */
  MetadataEntity.hasPropertyBySemantic = function (
    semantic,
    properties,
    classDefinition
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("semantic", semantic);
    Check.typeOf.object("properties", properties);
    Check.typeOf.object("classDefinition", classDefinition);
    //>>includeEnd('debug');

    const propertiesBySemantic = classDefinition.propertiesBySemantic;
    if (!defined(propertiesBySemantic)) {
      return false;
    }

    const property = propertiesBySemantic[semantic];
    return defined(property);
  };

  /**
   * Returns an array of property IDs.
   *
   * @param {Object} properties The dictionary containing properties.
   * @param {MetadataClass} classDefinition The class.
   * @param {String[]} [results] An array into which to store the results.
   * @returns {String[]} The property IDs.
   *
   * @private
   */
  MetadataEntity.getPropertyIds = function (
    properties,
    classDefinition,
    results
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("properties", properties);
    Check.typeOf.object("classDefinition", classDefinition);
    //>>includeEnd('debug');

    results = defined(results) ? results : [];
    results.length = 0;

    // Add entity properties
    for (const propertyId in properties) {
      if (
        properties.hasOwnProperty(propertyId) &&
        defined(properties[propertyId])
      ) {
        results.push(propertyId);
      }
    }

    // Add default properties
    const classProperties = classDefinition.properties;
    if (defined(classProperties)) {
      for (const classPropertyId in classProperties) {
        if (
          classProperties.hasOwnProperty(classPropertyId) &&
          !defined(properties[classPropertyId]) &&
          defined(classProperties[classPropertyId].default)
        ) {
          results.push(classPropertyId);
        }
      }
    }

    return results;
  };

  /**
   * Returns a copy of the value of the property with the given ID.
   * <p>
   * If the property is normalized the normalized value is returned.
   * </p>
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @param {Object} properties The dictionary containing properties.
   * @param {MetadataClass} classDefinition The class.
   * @returns {*} The value of the property or <code>undefined</code> if the entity does not have this property.
   *
   * @private
   */
  MetadataEntity.getProperty = function (
    propertyId,
    properties,
    classDefinition
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("propertyId", propertyId);
    Check.typeOf.object("properties", properties);
    Check.typeOf.object("classDefinition", classDefinition);

    if (!defined(classDefinition.properties[propertyId])) {
      throw new DeveloperError(`Class definition missing property ${propertyId}`);
    }
    //>>includeEnd('debug');

    const classProperty = classDefinition.properties[propertyId];
    let value = properties[propertyId];

    // Clone array values
    if (Array.isArray(value)) {
      value = value.slice();
    }

    // Arrays of vectors are represented as nested arrays in JSON
    const enableNestedArrays = true;

    // Handle noData and default
    value = classProperty.handleNoData(value);
    if (!defined(value) && defined(classProperty.default)) {
      value = clone$1(classProperty.default, true);
      return classProperty.unpackVectorAndMatrixTypes(value, enableNestedArrays);
    }

    if (!defined(value)) {
      return undefined;
    }

    value = classProperty.normalize(value);
    value = classProperty.applyValueTransform(value);
    return classProperty.unpackVectorAndMatrixTypes(value, enableNestedArrays);
  };

  /**
   * Sets the value of the property with the given ID.
   * <p>
   * If the property is normalized a normalized value must be provided to this function.
   * </p>
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @param {*} value The value of the property that will be copied.
   * @param {Object} properties The dictionary containing properties.
   * @param {MetadataClass} classDefinition The class.
   * @returns {Boolean} <code>true</code> if the property was set, <code>false</code> otherwise.
   *
   * @private
   */
  MetadataEntity.setProperty = function (
    propertyId,
    value,
    properties,
    classDefinition
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("propertyId", propertyId);
    Check.defined("value", value);
    Check.typeOf.object("properties", properties);
    Check.typeOf.object("classDefinition", classDefinition);
    //>>includeEnd('debug');

    if (!defined(properties[propertyId])) {
      return false;
    }

    if (Array.isArray(value)) {
      value = value.slice(); // clone
    }

    let classProperty;
    const classProperties = classDefinition.properties;
    if (defined(classProperties)) {
      classProperty = classProperties[propertyId];
    }

    // arrays of vectors are represented as nested arrays in JSON
    const enableNestedArrays = true;
    if (defined(classProperty)) {
      value = classProperty.packVectorAndMatrixTypes(value, enableNestedArrays);
      value = classProperty.unapplyValueTransform(value);
      value = classProperty.unnormalize(value);
    }

    properties[propertyId] = value;
    return true;
  };

  /**
   * Returns a copy of the value of the property with the given semantic.
   *
   * @param {String} semantic The case-sensitive semantic of the property.
   * @param {Object} properties The dictionary containing properties.
   * @param {MetadataClass} classDefinition The class.
   * @returns {*} The value of the property or <code>undefined</code> if the entity does not have this property.
   *
   * @private
   */
  MetadataEntity.getPropertyBySemantic = function (
    semantic,
    properties,
    classDefinition
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("semantic", semantic);
    Check.typeOf.object("properties", properties);
    Check.typeOf.object("classDefinition", classDefinition);
    //>>includeEnd('debug');

    const propertiesBySemantic = classDefinition.propertiesBySemantic;
    if (!defined(propertiesBySemantic)) {
      return undefined;
    }

    const property = propertiesBySemantic[semantic];
    if (defined(property)) {
      return MetadataEntity.getProperty(property.id, properties, classDefinition);
    }
    return undefined;
  };

  /**
   * Sets the value of the property with the given semantic.
   *
   * @param {String} semantic The case-sensitive semantic of the property.
   * @param {*} value The value of the property that will be copied.
   * @param {Object} properties The dictionary containing properties.
   * @param {MetadataClass} classDefinition The class.
   * @returns {Boolean} <code>true</code> if the property was set, <code>false</code> otherwise.
   * @private
   */
  MetadataEntity.setPropertyBySemantic = function (
    semantic,
    value,
    properties,
    classDefinition
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("semantic", semantic);
    Check.defined("value", value);
    Check.typeOf.object("properties", properties);
    Check.typeOf.object("classDefinition", classDefinition);
    //>>includeEnd('debug');

    const propertiesBySemantic = classDefinition.propertiesBySemantic;
    if (!defined(propertiesBySemantic)) {
      return false;
    }

    const property = classDefinition.propertiesBySemantic[semantic];
    if (defined(property)) {
      return MetadataEntity.setProperty(
        property.id,
        value,
        properties,
        classDefinition
      );
    }

    return false;
  };

  /**
   * Metadata about an implicit subtree.
   * <p>
   * See the {@link https://github.com/CesiumGS/3d-tiles/tree/main/extensions/3DTILES_metadata|3DTILES_metadata Extension} for 3D Tiles
   * </p>
   *
   * @param {Object} options Object with the following properties:
   * @param {Object} options.subtreeMetadata The subtree metadata JSON object.
   * @param {MetadataClass} options.class The class that subtree metadata conforms to.
   *
   * @alias ImplicitSubtreeMetadata
   * @constructor
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function ImplicitSubtreeMetadata(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const subtreeMetadata = options.subtreeMetadata;
    const metadataClass = options.class;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.subtreeMetadata", subtreeMetadata);
    Check.typeOf.object("options.class", metadataClass);
    //>>includeEnd('debug');

    const properties = defined(subtreeMetadata.properties)
      ? subtreeMetadata.properties
      : {};

    this._class = metadataClass;
    this._properties = properties;
    this._extras = subtreeMetadata.extras;
    this._extensions = subtreeMetadata.extensions;
  }

  Object.defineProperties(ImplicitSubtreeMetadata.prototype, {
    /**
     * The class that properties conform to.
     *
     * @memberof ImplicitSubtreeMetadata.prototype
     * @type {MetadataClass}
     * @readonly
     * @private
     */
    class: {
      get: function () {
        return this._class;
      },
    },

    /**
     * Extras in the JSON object.
     *
     * @memberof ImplicitSubtreeMetadata.prototype
     * @type {Object}
     * @readonly
     * @private
     */
    extras: {
      get: function () {
        return this._extras;
      },
    },

    /**
     * Extensions in the JSON object.
     *
     * @memberof ImplicitSubtreeMetadata.prototype
     * @type {Object}
     * @readonly
     * @private
     */
    extensions: {
      get: function () {
        return this._extensions;
      },
    },
  });

  /**
   * Returns whether the subtree has this property.
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @returns {Boolean} Whether the subtree has this property.
   * @private
   */
  ImplicitSubtreeMetadata.prototype.hasProperty = function (propertyId) {
    return MetadataEntity.hasProperty(propertyId, this._properties, this._class);
  };

  /**
   * Returns whether the subtree has a property with the given semantic.
   *
   * @param {String} semantic The case-sensitive semantic of the property.
   * @returns {Boolean} Whether the subtree has a property with the given semantic.
   * @private
   */
  ImplicitSubtreeMetadata.prototype.hasPropertyBySemantic = function (semantic) {
    return MetadataEntity.hasPropertyBySemantic(
      semantic,
      this._properties,
      this._class
    );
  };

  /**
   * Returns an array of property IDs.
   *
   * @param {String[]} [results] An array into which to store the results.
   * @returns {String[]} The property IDs.
   * @private
   */
  ImplicitSubtreeMetadata.prototype.getPropertyIds = function (results) {
    return MetadataEntity.getPropertyIds(this._properties, this._class, results);
  };

  /**
   * Returns a copy of the value of the property with the given ID.
   * <p>
   * If the property is normalized the normalized value is returned.
   * </p>
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @returns {*} The value of the property or <code>undefined</code> if the subtree does not have this property.
   * @private
   */
  ImplicitSubtreeMetadata.prototype.getProperty = function (propertyId) {
    return MetadataEntity.getProperty(propertyId, this._properties, this._class);
  };

  /**
   * Sets the value of the property with the given ID.
   * <p>
   * If the property is normalized a normalized value must be provided to this function.
   * </p>
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @param {*} value The value of the property that will be copied.
   * @returns {Boolean} <code>true</code> if the property was set, <code>false</code> otherwise.
   * @private
   */
  ImplicitSubtreeMetadata.prototype.setProperty = function (propertyId, value) {
    return MetadataEntity.setProperty(
      propertyId,
      value,
      this._properties,
      this._class
    );
  };

  /**
   * Returns a copy of the value of the property with the given semantic.
   *
   * @param {String} semantic The case-sensitive semantic of the property.
   * @returns {*} The value of the property or <code>undefined</code> if the subtree does not have this semantic.
   * @private
   */
  ImplicitSubtreeMetadata.prototype.getPropertyBySemantic = function (semantic) {
    return MetadataEntity.getPropertyBySemantic(
      semantic,
      this._properties,
      this._class
    );
  };

  /**
   * Sets the value of the property with the given semantic.
   *
   * @param {String} semantic The case-sensitive semantic of the property.
   * @param {*} value The value of the property that will be copied.
   * @returns {Boolean} <code>true</code> if the property was set, <code>false</code> otherwise.
   * @private
   */
  ImplicitSubtreeMetadata.prototype.setPropertyBySemantic = function (
    semantic,
    value
  ) {
    return MetadataEntity.setPropertyBySemantic(
      semantic,
      value,
      this._properties,
      this._class
    );
  };

  /**
   * An enum of metadata component types.
   *
   * @enum MetadataComponentType
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  const MetadataComponentType = {
    /**
     * An 8-bit signed integer
     *
     * @type {String}
     * @constant
     * @private
     */
    INT8: "INT8",
    /**
     * An 8-bit unsigned integer
     *
     * @type {String}
     * @constant
     * @private
     */
    UINT8: "UINT8",
    /**
     * A 16-bit signed integer
     *
     * @type {String}
     * @constant
     * @private
     */
    INT16: "INT16",
    /**
     * A 16-bit unsigned integer
     *
     * @type {String}
     * @constant
     * @private
     */
    UINT16: "UINT16",
    /**
     * A 32-bit signed integer
     *
     * @type {String}
     * @constant
     * @private
     */
    INT32: "INT32",
    /**
     * A 32-bit unsigned integer
     *
     * @type {String}
     * @constant
     * @private
     */
    UINT32: "UINT32",
    /**
     * A 64-bit signed integer. This type requires BigInt support.
     *
     * @see FeatureDetection.supportsBigInt
     *
     * @type {String}
     * @constant
     * @private
     */
    INT64: "INT64",
    /**
     * A 64-bit signed integer. This type requires BigInt support
     *
     * @see FeatureDetection.supportsBigInt
     *
     * @type {String}
     * @constant
     * @private
     */
    UINT64: "UINT64",
    /**
     * A 32-bit (single precision) floating point number
     *
     * @type {String}
     * @constant
     * @private
     */
    FLOAT32: "FLOAT32",
    /**
     * A 64-bit (double precision) floating point number
     *
     * @type {String}
     * @constant
     * @private
     */
    FLOAT64: "FLOAT64",
  };

  /**
   * Gets the minimum value for the numeric type.
   * <p>
   * Returns a BigInt for the INT64 and UINT64 types if BigInt is supported on this platform.
   * Otherwise an approximate number is returned.
   * </p>
   *
   * @param {MetadataComponentType} type The type.
   * @returns {Number|BigInt} The minimum value.
   *
   * @exception {DeveloperError} type must be a numeric type
   *
   * @private
   */
  MetadataComponentType.getMinimum = function (type) {
    //>>includeStart('debug', pragmas.debug);
    if (!MetadataComponentType.isNumericType(type)) {
      throw new DeveloperError("type must be a numeric type");
    }
    //>>includeEnd('debug');

    switch (type) {
      case MetadataComponentType.INT8:
        return -128;
      case MetadataComponentType.UINT8:
        return 0;
      case MetadataComponentType.INT16:
        return -32768;
      case MetadataComponentType.UINT16:
        return 0;
      case MetadataComponentType.INT32:
        return -2147483648;
      case MetadataComponentType.UINT32:
        return 0;
      case MetadataComponentType.INT64:
        if (FeatureDetection.supportsBigInt()) {
          return BigInt("-9223372036854775808"); // eslint-disable-line
        }
        return -Math.pow(2, 63);
      case MetadataComponentType.UINT64:
        if (FeatureDetection.supportsBigInt()) {
          return BigInt(0); // eslint-disable-line
        }
        return 0;
      case MetadataComponentType.FLOAT32:
        // Maximum 32-bit floating point number. This value will be converted to the nearest 64-bit Number
        return -340282346638528859811704183484516925440.0;
      case MetadataComponentType.FLOAT64:
        return -Number.MAX_VALUE;
    }
  };

  /**
   * Gets the maximum value for the numeric type.
   * <p>
   * Returns a BigInt for the INT64 and UINT64 types if BigInt is supported on this platform.
   * Otherwise an approximate number is returned.
   * </p>
   *
   * @param {MetadataComponentType} type The type.
   * @returns {Number|BigInt} The maximum value.
   *
   * @exception {DeveloperError} type must be a numeric type
   *
   * @private
   */
  MetadataComponentType.getMaximum = function (type) {
    //>>includeStart('debug', pragmas.debug);
    if (!MetadataComponentType.isNumericType(type)) {
      throw new DeveloperError("type must be a numeric type");
    }
    //>>includeEnd('debug');

    switch (type) {
      case MetadataComponentType.INT8:
        return 127;
      case MetadataComponentType.UINT8:
        return 255;
      case MetadataComponentType.INT16:
        return 32767;
      case MetadataComponentType.UINT16:
        return 65535;
      case MetadataComponentType.INT32:
        return 2147483647;
      case MetadataComponentType.UINT32:
        return 4294967295;
      case MetadataComponentType.INT64:
        if (FeatureDetection.supportsBigInt()) {
          // Need to initialize with a string otherwise the value will be 9223372036854775808
          return BigInt("9223372036854775807"); // eslint-disable-line
        }
        return Math.pow(2, 63) - 1;
      case MetadataComponentType.UINT64:
        if (FeatureDetection.supportsBigInt()) {
          // Need to initialize with a string otherwise the value will be 18446744073709551616
          return BigInt("18446744073709551615"); // eslint-disable-line
        }
        return Math.pow(2, 64) - 1;
      case MetadataComponentType.FLOAT32:
        // Maximum 32-bit floating point number
        return 340282346638528859811704183484516925440.0;
      case MetadataComponentType.FLOAT64:
        return Number.MAX_VALUE;
    }
  };

  /**
   * Returns whether the type is a numeric type.
   *
   * @param {MetadataComponentType} type The type.
   * @returns {Boolean} Whether the type is a numeric type.
   *
   * @private
   */
  MetadataComponentType.isNumericType = function (type) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("type", type);
    //>>includeEnd('debug');

    switch (type) {
      case MetadataComponentType.INT8:
      case MetadataComponentType.UINT8:
      case MetadataComponentType.INT16:
      case MetadataComponentType.UINT16:
      case MetadataComponentType.INT32:
      case MetadataComponentType.UINT32:
      case MetadataComponentType.INT64:
      case MetadataComponentType.UINT64:
      case MetadataComponentType.FLOAT32:
      case MetadataComponentType.FLOAT64:
        return true;
      default:
        return false;
    }
  };

  /**
   * Returns whether the type is an integer type.
   *
   * @param {MetadataComponentType} type The type.
   * @returns {Boolean} Whether the type is an integer type.
   *
   * @private
   */
  MetadataComponentType.isIntegerType = function (type) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("type", type);
    //>>includeEnd('debug');

    switch (type) {
      case MetadataComponentType.INT8:
      case MetadataComponentType.UINT8:
      case MetadataComponentType.INT16:
      case MetadataComponentType.UINT16:
      case MetadataComponentType.INT32:
      case MetadataComponentType.UINT32:
      case MetadataComponentType.INT64:
      case MetadataComponentType.UINT64:
        return true;
      default:
        return false;
    }
  };

  /**
   * Returns whether the type is an unsigned integer type.
   *
   * @param {MetadataComponentType} type The type.
   * @returns {Boolean} Whether the type is an unsigned integer type.
   *
   * @private
   */
  MetadataComponentType.isUnsignedIntegerType = function (type) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("type", type);
    //>>includeEnd('debug');

    switch (type) {
      case MetadataComponentType.UINT8:
      case MetadataComponentType.UINT16:
      case MetadataComponentType.UINT32:
      case MetadataComponentType.UINT64:
        return true;
      default:
        return false;
    }
  };

  /**
   * Returns whether a type can be used in a vector, i.e. the {@link Cartesian2},
   * {@link Cartesian3}, or {@link Cartesian4} classes. This includes all numeric
   * types except for types requiring 64-bit integers
   * @param {MetadataComponentType} type The type to check
   * @return {Boolean} <code>true</code> if the type can be encoded as a vector type, or <code>false</code> otherwise
   * @private
   */
  MetadataComponentType.isVectorCompatible = function (type) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("type", type);
    //>>includeEnd('debug');

    switch (type) {
      case MetadataComponentType.INT8:
      case MetadataComponentType.UINT8:
      case MetadataComponentType.INT16:
      case MetadataComponentType.UINT16:
      case MetadataComponentType.INT32:
      case MetadataComponentType.UINT32:
      case MetadataComponentType.FLOAT32:
      case MetadataComponentType.FLOAT64:
        return true;
      default:
        return false;
    }
  };

  /**
   * Normalizes signed integers to the range [-1.0, 1.0] and unsigned integers to
   * the range [0.0, 1.0].
   * <p>
   * The value may be a BigInt for the INT64 and UINT64 types. The value is converted
   * to a 64-bit floating point number during normalization which may result in
   * small precision differences.
   * </p>
   *
   * @param {Number|BigInt} value The integer value.
   * @param {MetadataComponentType} type The type.
   * @returns {Number} The normalized value.
   *
   * @exception {DeveloperError} value must be a number or a BigInt
   * @exception {DeveloperError} type must be an integer type
   *
   * @private
   */
  MetadataComponentType.normalize = function (value, type) {
    //>>includeStart('debug', pragmas.debug);
    if (typeof value !== "number" && typeof value !== "bigint") {
      throw new DeveloperError("value must be a number or a BigInt");
    }
    if (!MetadataComponentType.isIntegerType(type)) {
      throw new DeveloperError("type must be an integer type");
    }
    //>>includeEnd('debug');

    return Math.max(
      Number(value) / Number(MetadataComponentType.getMaximum(type)),
      -1.0
    );
  };

  /**
   * Unnormalizes signed numbers in the range [-1.0, 1.0] to signed integers and
   * unsigned numbers in the range [0.0, 1.0] to unsigned integers. Values outside
   * the range are clamped to the range.
   * <p>
   * Returns a BigInt for the INT64 and UINT64 types if BigInt is supported on this platform.
   * </p>
   *
   * @param {Number} value The normalized value.
   * @param {MetadataComponentType} type The type.
   * @returns {Number|BigInt} The integer value.
   *
   * @exception {DeveloperError} type must be an integer type
   *
   * @private
   */
  MetadataComponentType.unnormalize = function (value, type) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("value", value);
    if (!MetadataComponentType.isIntegerType(type)) {
      throw new DeveloperError("type must be an integer type");
    }
    //>>includeEnd('debug');

    const max = MetadataComponentType.getMaximum(type);
    const min = MetadataComponentType.isUnsignedIntegerType(type) ? 0 : -max;

    value = CesiumMath.sign(value) * Math.round(Math.abs(value) * Number(max));

    if (
      (type === MetadataComponentType.INT64 ||
        type === MetadataComponentType.UINT64) &&
      FeatureDetection.supportsBigInt()
    ) {
      value = BigInt(value); // eslint-disable-line
    }

    if (value > max) {
      return max;
    }

    if (value < min) {
      return min;
    }

    return value;
  };

  MetadataComponentType.applyValueTransform = function (value, offset, scale) {
    return scale * value + offset;
  };

  MetadataComponentType.unapplyValueTransform = function (value, offset, scale) {
    // if the scale is 0, avoid a divide by zero error. The result can be any
    // finite number, so 0.0 will do nicely.
    if (scale === 0) {
      return 0.0;
    }

    return (value - offset) / scale;
  };

  /**
   * Gets the size in bytes for the numeric type.
   *
   * @param {MetadataComponentType} type The type.
   * @returns {Number} The size in bytes.
   *
   * @exception {DeveloperError} type must be a numeric type
   *
   * @private
   */
  MetadataComponentType.getSizeInBytes = function (type) {
    //>>includeStart('debug', pragmas.debug);
    if (!MetadataComponentType.isNumericType(type)) {
      throw new DeveloperError("type must be a numeric type");
    }
    //>>includeEnd('debug');
    switch (type) {
      case MetadataComponentType.INT8:
      case MetadataComponentType.UINT8:
        return 1;
      case MetadataComponentType.INT16:
      case MetadataComponentType.UINT16:
        return 2;
      case MetadataComponentType.INT32:
      case MetadataComponentType.UINT32:
        return 4;
      case MetadataComponentType.INT64:
      case MetadataComponentType.UINT64:
        return 8;
      case MetadataComponentType.FLOAT32:
        return 4;
      case MetadataComponentType.FLOAT64:
        return 8;
    }
  };

  var MetadataComponentType$1 = Object.freeze(MetadataComponentType);

  /**
   * An enum of metadata types. These metadata types are containers containing
   * one or more components of type {@link MetadataComponentType}
   *
   * @enum MetadataType
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  const MetadataType = {
    /**
     * A single component
     *
     * @type {String}
     * @constant
     * @private
     */
    SCALAR: "SCALAR",
    /**
     * A vector with two components
     *
     * @type {String}
     * @constant
     * @private
     */
    VEC2: "VEC2",
    /**
     * A vector with three components
     *
     * @type {String}
     * @constant
     * @private
     */
    VEC3: "VEC3",
    /**
     * A vector with four components
     *
     * @type {String}
     * @constant
     * @private
     */
    VEC4: "VEC4",
    /**
     * A 2x2 matrix, stored in column-major format.
     *
     * @type {String}
     * @constant
     * @private
     */
    MAT2: "MAT2",
    /**
     * A 2x2 matrix, stored in column-major format.
     *
     * @type {String}
     * @constant
     * @private
     */
    MAT3: "MAT3",
    /**
     * A 2x2 matrix, stored in column-major format.
     *
     * @type {String}
     * @constant
     * @private
     */
    MAT4: "MAT4",
    /**
     * A boolean (true/false) value
     *
     * @type {String}
     * @constant
     * @private
     */
    BOOLEAN: "BOOLEAN",
    /**
     * A UTF-8 encoded string value
     *
     * @type {String}
     * @constant
     * @private
     */
    STRING: "STRING",
    /**
     * An enumerated value. This type is used in conjunction with a {@link MetadataEnum} to describe the valid values.
     *
     * @see MetadataEnum
     *
     * @type {String}
     * @constant
     * @private
     */
    ENUM: "ENUM",
  };

  /**
   * Check if a type is VEC2, VEC3 or VEC4
   *
   * @param {MetadataType} type The type
   * @return {Boolean} <code>true</code> if the type is a vector, <code>false</code> otherwise
   */
  MetadataType.isVectorType = function (type) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("type", type);
    //>>includeEnd('debug');

    switch (type) {
      case MetadataType.VEC2:
      case MetadataType.VEC3:
      case MetadataType.VEC4:
        return true;
      default:
        return false;
    }
  };

  /**
   * Check if a type is MAT2, MAT3 or MAT4
   *
   * @param {MetadataType} type The type
   * @return {Boolean} <code>true</code> if the type is a matrix, <code>false</code> otherwise
   */
  MetadataType.isMatrixType = function (type) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("type", type);
    //>>includeEnd('debug');

    switch (type) {
      case MetadataType.MAT2:
      case MetadataType.MAT3:
      case MetadataType.MAT4:
        return true;
      default:
        return false;
    }
  };

  /**
   * Get the number of components for a vector or matrix type. e.g.
   * a VECN returns N, and a MATN returns N*N. All other types return 1.
   *
   * @param {MetadataType} type The type to get the component count for
   * @return {Number} The number of components
   */
  MetadataType.getComponentCount = function (type) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("type", type);
    //>>includeEnd('debug');

    switch (type) {
      case MetadataType.SCALAR:
      case MetadataType.STRING:
      case MetadataType.ENUM:
      case MetadataType.BOOLEAN:
        return 1;
      case MetadataType.VEC2:
        return 2;
      case MetadataType.VEC3:
        return 3;
      case MetadataType.VEC4:
        return 4;
      case MetadataType.MAT2:
        return 4;
      case MetadataType.MAT3:
        return 9;
      case MetadataType.MAT4:
        return 16;
      //>>includeStart('debug', pragmas.debug);
      default:
        throw new DeveloperError(`Invalid metadata type ${type}`);
      //>>includeEnd('debug');
    }
  };

  /**
   * Get the corresponding vector or matrix class. This is used to simplify
   * packing and unpacking code.
   * @param {MetadataType} type The metadata type
   * @return {Object} The appropriate CartesianN class for vector types, MatrixN class for matrix types, or undefined otherwise.
   * @private
   */
  MetadataType.getMathType = function (type) {
    switch (type) {
      case MetadataType.VEC2:
        return Cartesian2;
      case MetadataType.VEC3:
        return Cartesian3;
      case MetadataType.VEC4:
        return Cartesian4;
      case MetadataType.MAT2:
        return Matrix2;
      case MetadataType.MAT3:
        return Matrix3;
      case MetadataType.MAT4:
        return Matrix4;
      default:
        return undefined;
    }
  };

  var MetadataType$1 = Object.freeze(MetadataType);

  /**
   * A metadata property, as part of a {@link MetadataClass}
   *
   * @param {Object} options Object with the following properties:
   * @param {String} options.id The ID of the property.
   * @param {Object} options.property The property JSON object.
   * @param {Object.<String, MetadataEnum>} [options.enums] A dictionary of enums.
   *
   * @alias MetadataClassProperty
   * @constructor
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function MetadataClassProperty(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const id = options.id;
    const property = options.property;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("options.id", id);
    Check.typeOf.object("options.property", property);
    Check.typeOf.string("options.property.type", property.type);
    //>>includeEnd('debug');

    // Try to determine if this is the legacy extension. This is not
    // always possible, as there are some types that are valid in both
    // extensions.
    const isLegacyExtension = isLegacy(property);
    const parsedType = parseType(property, options.enums);
    const componentType = parsedType.componentType;

    const normalized =
      defined(componentType) &&
      MetadataComponentType$1.isIntegerType(componentType) &&
      defaultValue(property.normalized, false);

    // Basic information about this property
    this._id = id;
    this._name = property.name;
    this._description = property.description;
    this._semantic = property.semantic;
    this._isLegacyExtension = isLegacyExtension;

    // Details about basic types
    this._type = parsedType.type;
    this._componentType = componentType;
    this._enumType = parsedType.enumType;
    this._valueType = parsedType.valueType;

    // Details about arrays
    this._isArray = parsedType.isArray;
    this._isVariableLengthArray = parsedType.isVariableLengthArray;
    this._arrayLength = parsedType.arrayLength;

    // min and max allowed values
    this._min = property.min;
    this._max = property.max;

    // properties that adjust the range of metadata values
    this._normalized = normalized;

    let offset = property.offset;
    let scale = property.scale;
    const hasValueTransform = defined(offset) || defined(scale);

    const enableNestedArrays = true;
    if (!defined(offset)) {
      offset = this.expandConstant(0, enableNestedArrays);
    }

    if (!defined(scale)) {
      scale = this.expandConstant(1, enableNestedArrays);
    }

    this._offset = offset;
    this._scale = scale;
    this._hasValueTransform = hasValueTransform;

    // sentinel value for missing data, and a default value to use
    // in its place if needed.
    this._noData = property.noData;
    // For vector and array types, this is stored as an array of values.
    this._default = property.default;

    // EXT_feature_metadata had an optional flag, while EXT_structural_metadata
    // has a required flag. The defaults are not the same, and there's some cases
    // like {type: BOOLEAN} that are ambiguous. Coalesce this into a single
    // required flag
    let required;
    if (!defined(isLegacyExtension)) {
      // Impossible to tell which extension was used, so don't require
      // the property
      required = false;
    } else if (isLegacyExtension) {
      required = defined(property.optional) ? !property.optional : true;
    } else {
      required = defaultValue(property.required, false);
    }
    this._required = required;

    // extras and extensions
    this._extras = property.extras;
    this._extensions = property.extensions;
  }

  Object.defineProperties(MetadataClassProperty.prototype, {
    /**
     * The ID of the property.
     *
     * @memberof MetadataClassProperty.prototype
     * @type {String}
     * @readonly
     * @private
     */
    id: {
      get: function () {
        return this._id;
      },
    },

    /**
     * The name of the property.
     *
     * @memberof MetadataClassProperty.prototype
     * @type {String}
     * @readonly
     * @private
     */
    name: {
      get: function () {
        return this._name;
      },
    },

    /**
     * The description of the property.
     *
     * @memberof MetadataClassProperty.prototype
     * @type {String}
     * @readonly
     * @private
     */
    description: {
      get: function () {
        return this._description;
      },
    },

    /**
     * The type of the property such as SCALAR, VEC2, VEC3
     *
     *
     * @memberof MetadataClassProperty.prototype
     * @type {MetadataType}
     * @readonly
     * @private
     */
    type: {
      get: function () {
        return this._type;
      },
    },

    /**
     * The enum type of the property. Only defined when type is ENUM.
     *
     * @memberof MetadataClassProperty.prototype
     * @type {MetadataEnum}
     * @readonly
     * @private
     */
    enumType: {
      get: function () {
        return this._enumType;
      },
    },

    /**
     * The component type of the property. This includes integer
     * (e.g. INT8 or UINT16), and floating point (FLOAT32 and FLOAT64) values
     *
     * @memberof MetadataClassProperty.prototype
     * @type {MetadataComponentType}
     * @readonly
     * @private
     */
    componentType: {
      get: function () {
        return this._componentType;
      },
    },

    /**
     * The datatype used for storing each component of the property. This
     * is usually the same as componentType except for ENUM, where this
     * returns an integer type
     *
     * @memberof MetadataClassProperty.prototype
     * @type {MetadataComponentType}
     * @readonly
     * @private
     */
    valueType: {
      get: function () {
        return this._valueType;
      },
    },

    /**
     * True if a property is an array (either fixed length or variable length),
     * false otherwise.
     *
     * @memberof MetadataClassProperty.prototype
     * @type {Boolean}
     * @readonly
     * @private
     */
    isArray: {
      get: function () {
        return this._isArray;
      },
    },

    /**
     * True if a property is a variable length array, false otherwise.
     *
     * @memberof MetadataClassProperty.prototype
     * @type {Boolean}
     * @readonly
     * @private
     */
    isVariableLengthArray: {
      get: function () {
        return this._isVariableLengthArray;
      },
    },

    /**
     * The number of array elements. Only defined for fixed-size
     * arrays.
     *
     * @memberof MetadataClassProperty.prototype
     * @type {Number}
     * @readonly
     * @private
     */
    arrayLength: {
      get: function () {
        return this._arrayLength;
      },
    },

    /**
     * Whether the property is normalized.
     *
     * @memberof MetadataClassProperty.prototype
     * @type {Boolean}
     * @readonly
     * @private
     */
    normalized: {
      get: function () {
        return this._normalized;
      },
    },

    /**
     * A number or an array of numbers storing the maximum allowable value of this property. Only defined when type or componentType is a numeric type.
     *
     * @memberof MetadataClassProperty.prototype
     * @type {Number|Number[]}
     * @readonly
     * @private
     */
    max: {
      get: function () {
        return this._max;
      },
    },

    /**
     * A number or an array of numbers storing the minimum allowable value of this property. Only defined when type or componentType is a numeric type.
     *
     * @memberof MetadataClassProperty.prototype
     * @type {Number|Number[]}
     * @readonly
     * @private
     */
    min: {
      get: function () {
        return this._min;
      },
    },

    /**
     * The no-data sentinel value that represents null values
     *
     * @memberof MetadataClassProperty.prototype
     * @type {Boolean|Number|String|Array}
     * @readonly
     * @private
     */
    noData: {
      get: function () {
        return this._noData;
      },
    },

    /**
     * A default value to use when an entity's property value is not defined.
     *
     * @memberof MetadataClassProperty.prototype
     * @type {Boolean|Number|String|Array}
     * @readonly
     * @private
     */
    default: {
      get: function () {
        return this._default;
      },
    },

    /**
     * Whether the property is required.
     *
     * @memberof MetadataClassProperty.prototype
     * @type {Boolean}
     * @readonly
     * @private
     */
    required: {
      get: function () {
        return this._required;
      },
    },

    /**
     * An identifier that describes how this property should be interpreted.
     *
     * @memberof MetadataClassProperty.prototype
     * @type {String}
     * @readonly
     * @private
     */
    semantic: {
      get: function () {
        return this._semantic;
      },
    },

    /**
     * True if offset/scale should be applied. If both offset/scale were
     * undefined, they default to identity so this property is set false
     *
     * @memberof MetadataClassProperty.prototype
     * @type {Boolean}
     * @readonly
     * @private
     */
    hasValueTransform: {
      get: function () {
        return this._hasValueTransform;
      },
    },

    /**
     * The offset to be added to property values as part of the value transform.
     *
     * @memberof MetadataClassProperty.prototype
     * @type {Number|Number[]|Number[][]}
     * @readonly
     * @private
     */
    offset: {
      get: function () {
        return this._offset;
      },
    },

    /**
     * The scale to be multiplied to property values as part of the value transform.
     *
     * @memberof MetadataClassProperty.prototype
     * @type {Number|Number[]|Number[][]}
     * @readonly
     * @private
     */
    scale: {
      get: function () {
        return this._scale;
      },
    },

    /**
     * Extras in the JSON object.
     *
     * @memberof MetadataClassProperty.prototype
     * @type {*}
     * @readonly
     * @private
     */
    extras: {
      get: function () {
        return this._extras;
      },
    },

    /**
     * Extensions in the JSON object.
     *
     * @memberof MetadataClassProperty.prototype
     * @type {Object}
     * @readonly
     * @private
     */
    extensions: {
      get: function () {
        return this._extensions;
      },
    },
  });

  function isLegacy(property) {
    if (property.type === "ARRAY") {
      return true;
    }

    // New property types in EXT_structural_metadata
    const type = property.type;
    if (
      type === MetadataType$1.SCALAR ||
      MetadataType$1.isMatrixType(type) ||
      MetadataType$1.isVectorType(type)
    ) {
      return false;
    }

    // EXT_feature_metadata allowed numeric types as a type. Now they are
    // represented as {type: SINGLE, componentType: type}
    if (MetadataComponentType$1.isNumericType(type)) {
      return true;
    }

    // New properties in EXT_structural_metadata
    if (
      defined(property.noData) ||
      defined(property.scale) ||
      defined(property.offset) ||
      defined(property.required) ||
      defined(property.count) ||
      defined(property.array)
    ) {
      return false;
    }

    // Properties that only exist in EXT_feature_metadata
    if (defined(property.optional)) {
      return false;
    }

    // impossible to tell, give up.
    return undefined;
  }

  function parseType(property, enums) {
    const type = property.type;
    const componentType = property.componentType;

    // EXT_feature_metadata had an ARRAY type. This is now handled
    // with array + count, so some details need to be transcoded
    const isLegacyArray = type === "ARRAY";
    let isArray;
    let arrayLength;
    let isVariableLengthArray;
    if (isLegacyArray) {
      // definitely EXT_feature_metadata
      isArray = true;
      arrayLength = property.componentCount;
      isVariableLengthArray = !defined(arrayLength);
    } else if (property.array) {
      isArray = true;
      arrayLength = property.count;
      isVariableLengthArray = !defined(property.count);
    } else {
      // Could be either extension. Some cases are impossible to distinguish
      // Default to a single value
      isArray = false;
      arrayLength = undefined;
      isVariableLengthArray = false;
    }

    let enumType;
    if (defined(property.enumType)) {
      enumType = enums[property.enumType];
    }

    // In both EXT_feature_metadata and EXT_structural_metadata, ENUM appears
    // as a type.
    if (type === MetadataType$1.ENUM) {
      return {
        type: type,
        componentType: undefined,
        enumType: enumType,
        valueType: enumType.valueType,
        isArray: isArray,
        isVariableLengthArray: isVariableLengthArray,
        arrayLength: arrayLength,
      };
    }

    // In EXT_feature_metadata, ENUM also appears as an ARRAY componentType
    if (isLegacyArray && componentType === MetadataType$1.ENUM) {
      return {
        type: componentType,
        componentType: undefined,
        enumType: enumType,
        valueType: enumType.valueType,
        isArray: isArray,
        isVariableLengthArray: isVariableLengthArray,
        arrayLength: arrayLength,
      };
    }

    // EXT_structural_metadata only: SCALAR, VECN and MATN
    if (
      type === MetadataType$1.SCALAR ||
      MetadataType$1.isMatrixType(type) ||
      MetadataType$1.isVectorType(type)
    ) {
      return {
        type: type,
        componentType: componentType,
        enumType: undefined,
        valueType: componentType,
        isArray: isArray,
        isVariableLengthArray: isVariableLengthArray,
        arrayLength: arrayLength,
      };
    }

    // In both EXT_structural_metadata and EXT_feature_metadata,
    // BOOLEAN and STRING appear as types
    if (type === MetadataType$1.BOOLEAN || type === MetadataType$1.STRING) {
      return {
        type: type,
        componentType: undefined,
        enumType: undefined,
        valueType: undefined,
        isArray: isArray,
        isVariableLengthArray: isVariableLengthArray,
        arrayLength: arrayLength,
      };
    }

    // EXT_feature_metadata also allows BOOLEAN and STRING as an ARRAY
    // componentType
    if (
      isLegacyArray &&
      (componentType === MetadataType$1.BOOLEAN ||
        componentType === MetadataType$1.STRING)
    ) {
      return {
        type: componentType,
        componentType: undefined,
        enumType: undefined,
        valueType: undefined,
        isArray: isArray,
        isVariableLengthArray: isVariableLengthArray,
        arrayLength: arrayLength,
      };
    }

    // Both EXT_feature_metadata and EXT_structural_metadata allow numeric types like
    // INT32 or FLOAT64 as a componentType.
    if (
      defined(componentType) &&
      MetadataComponentType$1.isNumericType(componentType)
    ) {
      return {
        type: MetadataType$1.SCALAR,
        componentType: componentType,
        enumType: undefined,
        valueType: componentType,
        isArray: isArray,
        isVariableLengthArray: isVariableLengthArray,
        arrayLength: arrayLength,
      };
    }

    // EXT_feature_metadata: integer and float types were allowed as types,
    // but now these are expressed as {type: SCALAR, componentType: type}
    if (MetadataComponentType$1.isNumericType(type)) {
      return {
        type: MetadataType$1.SCALAR,
        componentType: type,
        enumType: undefined,
        valueType: type,
        isArray: isArray,
        isVariableLengthArray: isVariableLengthArray,
        arrayLength: arrayLength,
      };
    }

    //>>includeStart('debug', pragmas.debug);
    throw new DeveloperError(
      `unknown metadata type {type: ${type}, componentType: ${componentType})`
    );
    //>>includeEnd('debug');
  }

  /**
   * Normalizes integer property values. If the property is not normalized
   * the value is returned unmodified.
   * <p>
   * Given the way normalization is defined in {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/Metadata#normalized-values|the 3D Metadata Specification},
   * normalize and unnormalize are almost, but not quite inverses. In particular,
   * the smallest signed integer value will be off by one after normalizing and
   * unnormalizing. See
   * {@link https://www.desmos.com/calculator/nledg1evut|this Desmos graph} for
   * an example using INT8.
   * </p>
   * <p>
   * Furthermore, for 64-bit integer types, there may be a loss of precision
   * due to conversion to Number
   * </p>
   *
   * @param {*} value The integer value or array of integer values.
   * @returns {*} The normalized value or array of normalized values.
   *
   * @private
   */
  MetadataClassProperty.prototype.normalize = function (value) {
    if (!this._normalized) {
      return value;
    }

    return normalizeInPlace(
      value,
      this._valueType,
      MetadataComponentType$1.normalize
    );
  };

  /**
   * Unnormalizes integer property values. If the property is not normalized
   * the value is returned unmodified.
   * <p>
   * Given the way normalization is defined in {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/Metadata#normalized-values|the 3D Metadata Specification},
   * normalize and unnormalize are almost, but not quite inverses. In particular,
   * the smallest signed integer value will be off by one after normalizing and
   * unnormalizing. See
   * {@link https://www.desmos.com/calculator/nledg1evut|this Desmos graph} for
   * an example using INT8.
   * </p>
   * <p>
   * Furthermore, for 64-bit integer types, there may be a loss of precision
   * due to conversion to Number
   * </p>
   *
   * @param {*} value The normalized value or array of normalized values.
   * @returns {*} The integer value or array of integer values.
   *
   * @private
   */
  MetadataClassProperty.prototype.unnormalize = function (value) {
    if (!this._normalized) {
      return value;
    }

    return normalizeInPlace(
      value,
      this._valueType,
      MetadataComponentType$1.unnormalize
    );
  };

  MetadataClassProperty.prototype.applyValueTransform = function (value) {
    // variable length arrays do not have a well-defined offset/scale so this
    // is forbidden by the spec
    if (!this._hasValueTransform || this._isVariableLengthArray) {
      return value;
    }

    return MetadataClassProperty.valueTransformInPlace(
      value,
      this._offset,
      this._scale,
      MetadataComponentType$1.applyValueTransform
    );
  };

  MetadataClassProperty.prototype.unapplyValueTransform = function (value) {
    // variable length arrays do not have a well-defined offset/scale so this
    // is forbidden by the spec
    if (!this._hasValueTransform || this._isVariableLengthArray) {
      return value;
    }

    return MetadataClassProperty.valueTransformInPlace(
      value,
      this._offset,
      this._scale,
      MetadataComponentType$1.unapplyValueTransform
    );
  };

  MetadataClassProperty.prototype.expandConstant = function (
    constant,
    enableNestedArrays
  ) {
    enableNestedArrays = defaultValue(enableNestedArrays, false);
    const isArray = this._isArray;
    const arrayLength = this._arrayLength;
    const componentCount = MetadataType$1.getComponentCount(this._type);
    const isNested = isArray && componentCount > 1;

    // scalar values can be returned directly
    if (!isArray && componentCount === 1) {
      return constant;
    }

    // vector and matrix values
    if (!isArray) {
      return new Array(componentCount).fill(constant);
    }

    // arrays of scalars
    if (!isNested) {
      return new Array(arrayLength).fill(constant);
    }

    // arrays of vectors/matrices: flattened
    if (!enableNestedArrays) {
      return new Array(this._arrayLength * componentCount).fill(constant);
    }

    // array of vectors/matrices: nested
    const innerConstant = new Array(componentCount).fill(constant);
    // This array fill duplicates the pointer to the inner arrays. Since this is
    // intended for use with constants, no need to clone the array.
    return new Array(this._arrayLength).fill(innerConstant);
  };

  /**
   * If the value is the noData sentinel, return undefined. Otherwise, return
   * the value.
   * @param {*} value The raw value
   * @returns {*} Either the value or undefined if the value was a no data value.
   *
   * @private
   */
  MetadataClassProperty.prototype.handleNoData = function (value) {
    const sentinel = this._noData;
    if (!defined(sentinel)) {
      return value;
    }

    if (arrayEquals(value, sentinel)) {
      return undefined;
    }

    return value;
  };

  function arrayEquals(left, right) {
    if (!Array.isArray(left)) {
      return left === right;
    }

    if (!Array.isArray(right)) {
      return false;
    }

    if (left.length !== right.length) {
      return false;
    }

    for (let i = 0; i < left.length; i++) {
      if (!arrayEquals(left[i], right[i])) {
        return false;
      }
    }

    return true;
  }

  /**
   * Unpack VECN values into {@link Cartesian2}, {@link Cartesian3}, or
   * {@link Cartesian4} and MATN values into {@link Matrix2}, {@link Matrix3}, or
   * {@link Matrix4} depending on N. All other values (including arrays of
   * other sizes) are passed through unaltered.
   *
   * @param {*} value the original, normalized values.
   * @param {Boolean} [enableNestedArrays=false] If true, arrays of vectors are represented as nested arrays. This is used for JSON encoding but not binary encoding
   * @returns {*} The appropriate vector or matrix type if the value is a vector or matrix type, respectively. If the property is an array of vectors or matrices, an array of the appropriate vector or matrix type is returned. Otherwise, the value is returned unaltered.
   * @private
   */
  MetadataClassProperty.prototype.unpackVectorAndMatrixTypes = function (
    value,
    enableNestedArrays
  ) {
    enableNestedArrays = defaultValue(enableNestedArrays, false);
    const MathType = MetadataType$1.getMathType(this._type);
    const isArray = this._isArray;
    const componentCount = MetadataType$1.getComponentCount(this._type);
    const isNested = isArray && componentCount > 1;

    if (!defined(MathType)) {
      return value;
    }

    if (enableNestedArrays && isNested) {
      return value.map(function (x) {
        return MathType.unpack(x);
      });
    }

    if (isArray) {
      return MathType.unpackArray(value);
    }

    return MathType.unpack(value);
  };

  /**
   * Pack a {@link Cartesian2}, {@link Cartesian3}, or {@link Cartesian4} into an
   * array if this property is an <code>VECN</code>.
   * Pack a {@link Matrix2}, {@link Matrix3}, or {@link Matrix4} into an
   * array if this property is an <code>MATN</code>.
   * All other values (including arrays of other sizes) are passed through unaltered.
   *
   * @param {*} value The value of this property
   * @param {Boolean} [enableNestedArrays=false] If true, arrays of vectors are represented as nested arrays. This is used for JSON encoding but not binary encoding
   * @returns {*} An array of the appropriate length if the property is a vector or matrix type. Otherwise, the value is returned unaltered.
   * @private
   */
  MetadataClassProperty.prototype.packVectorAndMatrixTypes = function (
    value,
    enableNestedArrays
  ) {
    enableNestedArrays = defaultValue(enableNestedArrays, false);
    const MathType = MetadataType$1.getMathType(this._type);
    const isArray = this._isArray;
    const componentCount = MetadataType$1.getComponentCount(this._type);
    const isNested = isArray && componentCount > 1;

    if (!defined(MathType)) {
      return value;
    }

    if (enableNestedArrays && isNested) {
      return value.map(function (x) {
        return MathType.pack(x, []);
      });
    }

    if (isArray) {
      return MathType.packArray(value, []);
    }

    return MathType.pack(value, []);
  };

  /**
   * Validates whether the given value conforms to the property.
   *
   * @param {*} value The value.
   * @returns {String|undefined} An error message if the value does not conform to the property, otherwise undefined.
   * @private
   */
  MetadataClassProperty.prototype.validate = function (value) {
    if (!defined(value) && defined(this._default)) {
      // no value, but we have a default to use.
      return undefined;
    }

    if (this._required && !defined(value)) {
      return `required property must have a value`;
    }

    if (this._isArray) {
      return validateArray(this, value);
    }

    return validateSingleValue(this, value);
  };

  function validateArray(classProperty, value) {
    if (!Array.isArray(value)) {
      return `value ${value} must be an array`;
    }

    const length = value.length;
    if (
      !classProperty._isVariableLengthArray &&
      length !== classProperty._arrayLength
    ) {
      return "Array length does not match property.arrayLength";
    }

    for (let i = 0; i < length; i++) {
      const message = validateSingleValue(classProperty, value[i]);
      if (defined(message)) {
        return message;
      }
    }
  }

  function validateSingleValue(classProperty, value) {
    const type = classProperty._type;
    const componentType = classProperty._componentType;
    const enumType = classProperty._enumType;
    const normalized = classProperty._normalized;

    if (MetadataType$1.isVectorType(type)) {
      return validateVector(value, type, componentType);
    } else if (MetadataType$1.isMatrixType(type)) {
      return validateMatrix(value, type, componentType);
    } else if (type === MetadataType$1.STRING) {
      return validateString(value);
    } else if (type === MetadataType$1.BOOLEAN) {
      return validateBoolean(value);
    } else if (type === MetadataType$1.ENUM) {
      return validateEnum(value, enumType);
    }

    return validateScalar(value, componentType, normalized);
  }

  function validateVector(value, type, componentType) {
    if (!MetadataComponentType$1.isVectorCompatible(componentType)) {
      return `componentType ${componentType} is incompatible with vector type ${type}`;
    }

    if (type === MetadataType$1.VEC2 && !(value instanceof Cartesian2)) {
      return `vector value ${value} must be a Cartesian2`;
    }

    if (type === MetadataType$1.VEC3 && !(value instanceof Cartesian3)) {
      return `vector value ${value} must be a Cartesian3`;
    }

    if (type === MetadataType$1.VEC4 && !(value instanceof Cartesian4)) {
      return `vector value ${value} must be a Cartesian4`;
    }
  }

  function validateMatrix(value, type, componentType) {
    if (!MetadataComponentType$1.isVectorCompatible(componentType)) {
      return `componentType ${componentType} is incompatible with matrix type ${type}`;
    }

    if (type === MetadataType$1.MAT2 && !(value instanceof Matrix2)) {
      return `matrix value ${value} must be a Matrix2`;
    }

    if (type === MetadataType$1.MAT3 && !(value instanceof Matrix3)) {
      return `matrix value ${value} must be a Matrix3`;
    }

    if (type === MetadataType$1.MAT4 && !(value instanceof Matrix4)) {
      return `matrix value ${value} must be a Matrix4`;
    }
  }

  function validateString(value) {
    if (typeof value !== "string") {
      return getTypeErrorMessage(value, MetadataType$1.STRING);
    }
  }

  function validateBoolean(value) {
    if (typeof value !== "boolean") {
      return getTypeErrorMessage(value, MetadataType$1.BOOLEAN);
    }
  }

  function validateEnum(value, enumType) {
    const javascriptType = typeof value;
    if (defined(enumType)) {
      if (javascriptType !== "string" || !defined(enumType.valuesByName[value])) {
        return `value ${value} is not a valid enum name for ${enumType.id}`;
      }
      return;
    }
  }

  function validateScalar(value, componentType, normalized) {
    const javascriptType = typeof value;

    switch (componentType) {
      case MetadataComponentType$1.INT8:
      case MetadataComponentType$1.UINT8:
      case MetadataComponentType$1.INT16:
      case MetadataComponentType$1.UINT16:
      case MetadataComponentType$1.INT32:
      case MetadataComponentType$1.UINT32:
      case MetadataComponentType$1.FLOAT32:
      case MetadataComponentType$1.FLOAT64:
        if (javascriptType !== "number") {
          return getTypeErrorMessage(value, componentType);
        }
        if (!isFinite(value)) {
          return getNonFiniteErrorMessage(value, componentType);
        }
        return checkInRange(value, componentType, normalized);
      case MetadataComponentType$1.INT64:
      case MetadataComponentType$1.UINT64:
        if (javascriptType !== "number" && javascriptType !== "bigint") {
          return getTypeErrorMessage(value, componentType);
        }
        if (javascriptType === "number" && !isFinite(value)) {
          return getNonFiniteErrorMessage(value, componentType);
        }
        return checkInRange(value, componentType, normalized);
    }
  }

  function getTypeErrorMessage(value, type) {
    return `value ${value} does not match type ${type}`;
  }

  function getOutOfRangeErrorMessage(value, type, normalized) {
    let errorMessage = `value ${value} is out of range for type ${type}`;
    if (normalized) {
      errorMessage += " (normalized)";
    }
    return errorMessage;
  }

  function checkInRange(value, componentType, normalized) {
    if (normalized) {
      const min = MetadataComponentType$1.isUnsignedIntegerType(componentType)
        ? 0.0
        : -1.0;
      const max = 1.0;
      if (value < min || value > max) {
        return getOutOfRangeErrorMessage(value, componentType, normalized);
      }
      return;
    }

    if (
      value < MetadataComponentType$1.getMinimum(componentType) ||
      value > MetadataComponentType$1.getMaximum(componentType)
    ) {
      return getOutOfRangeErrorMessage(value, componentType, normalized);
    }
  }

  function getNonFiniteErrorMessage(value, type) {
    return `value ${value} of type ${type} must be finite`;
  }

  function normalizeInPlace(values, valueType, normalizeFunction) {
    if (!Array.isArray(values)) {
      return normalizeFunction(values, valueType);
    }

    for (let i = 0; i < values.length; i++) {
      values[i] = normalizeInPlace(values[i], valueType, normalizeFunction);
    }

    return values;
  }

  MetadataClassProperty.valueTransformInPlace = function (
    values,
    offsets,
    scales,
    transformationFunction
  ) {
    if (!Array.isArray(values)) {
      // transform a single value
      return transformationFunction(values, offsets, scales);
    }

    for (let i = 0; i < values.length; i++) {
      // offsets and scales must be the same array shape as values.
      values[i] = MetadataClassProperty.valueTransformInPlace(
        values[i],
        offsets[i],
        scales[i],
        transformationFunction
      );
    }

    return values;
  };

  /**
   * A binary property in a {@MetadataTable}
   * <p>
   * For 3D Tiles Next details, see the {@link https://github.com/CesiumGS/3d-tiles/tree/main/extensions/3DTILES_metadata|3DTILES_metadata Extension}
   * for 3D Tiles, as well as the {@link https://github.com/CesiumGS/glTF/tree/3d-tiles-next/extensions/2.0/Vendor/EXT_structural_metadata|EXT_structural_metadata Extension}
   * for glTF. For the legacy glTF extension, see {@link https://github.com/CesiumGS/glTF/tree/3d-tiles-next/extensions/2.0/Vendor/EXT_feature_metadata|EXT_feature_metadata Extension}
   * </p>
   *
   * @param {Object} options Object with the following properties:
   * @param {Number} options.count The number of elements in each property array.
   * @param {Object} options.property The property JSON object.
   * @param {MetadataClassProperty} options.classProperty The class property.
   * @param {Object.<String, Uint8Array>} options.bufferViews An object mapping bufferView IDs to Uint8Array objects.
   *
   * @alias MetadataTableProperty
   * @constructor
   *
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function MetadataTableProperty(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const count = options.count;
    const property = options.property;
    const classProperty = options.classProperty;
    const bufferViews = options.bufferViews;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number.greaterThan("options.count", count, 0);
    Check.typeOf.object("options.property", property);
    Check.typeOf.object("options.classProperty", classProperty);
    Check.typeOf.object("options.bufferViews", bufferViews);
    //>>includeEnd('debug');

    const type = classProperty.type;
    const isArray = classProperty.isArray;
    const isVariableLengthArray = classProperty.isVariableLengthArray;

    let valueType = classProperty.valueType;
    const enumType = classProperty.enumType;

    const hasStrings = type === MetadataType$1.STRING;
    const hasBooleans = type === MetadataType$1.BOOLEAN;

    let byteLength = 0;

    let arrayOffsets;
    if (isVariableLengthArray) {
      // EXT_structural_metadata uses arrayOffsetType.
      // EXT_feature_metadata uses offsetType for both arrays and strings
      let arrayOffsetType = defaultValue(
        property.arrayOffsetType,
        property.offsetType
      );
      arrayOffsetType = defaultValue(
        MetadataComponentType$1[arrayOffsetType],
        MetadataComponentType$1.UINT32
      );

      // EXT_structural_metadata uses arrayOffsets.
      // EXT_feature_metadata uses arrayOffsetBufferView
      const arrayOffsetBufferView = defaultValue(
        property.arrayOffsets,
        property.arrayOffsetBufferView
      );
      arrayOffsets = new BufferView(
        bufferViews[arrayOffsetBufferView],
        arrayOffsetType,
        count + 1
      );

      byteLength += arrayOffsets.typedArray.byteLength;
    }

    const vectorComponentCount = MetadataType$1.getComponentCount(type);

    let arrayComponentCount;
    if (isVariableLengthArray) {
      arrayComponentCount = arrayOffsets.get(count) - arrayOffsets.get(0);
    } else if (isArray) {
      arrayComponentCount = count * classProperty.arrayLength;
    } else {
      arrayComponentCount = count;
    }

    const componentCount = vectorComponentCount * arrayComponentCount;

    let stringOffsets;
    if (hasStrings) {
      // EXT_structural_metadata uses stringOffsetType, EXT_feature_metadata uses offsetType for both arrays and strings
      let stringOffsetType = defaultValue(
        property.stringOffsetType,
        property.offsetType
      );
      stringOffsetType = defaultValue(
        MetadataComponentType$1[stringOffsetType],
        MetadataComponentType$1.UINT32
      );

      // EXT_structural_metadata uses stringOffsets.
      // EXT_feature_metadata uses stringOffsetBufferView
      const stringOffsetBufferView = defaultValue(
        property.stringOffsets,
        property.stringOffsetBufferView
      );
      stringOffsets = new BufferView(
        bufferViews[stringOffsetBufferView],
        stringOffsetType,
        componentCount + 1
      );

      byteLength += stringOffsets.typedArray.byteLength;
    }

    if (hasStrings || hasBooleans) {
      // STRING and BOOLEAN types need to be parsed differently than other types
      valueType = MetadataComponentType$1.UINT8;
    }

    let valueCount;
    if (hasStrings) {
      valueCount = stringOffsets.get(componentCount) - stringOffsets.get(0);
    } else if (hasBooleans) {
      valueCount = Math.ceil(componentCount / 8);
    } else {
      valueCount = componentCount;
    }

    // EXT_structural_metadata uses values
    // EXT_feature_metadata uses bufferView
    const valuesBufferView = defaultValue(property.values, property.bufferView);
    const values = new BufferView(
      bufferViews[valuesBufferView],
      valueType,
      valueCount
    );
    byteLength += values.typedArray.byteLength;

    let offset = property.offset;
    let scale = property.scale;

    // This needs to be set before handling default values
    const hasValueTransform =
      classProperty.hasValueTransform || defined(offset) || defined(scale);

    // If the table does not define an offset/scale, it inherits from the
    // class property. The class property handles setting the default of identity:
    // (offset 0, scale 1) with the same array shape as the property's type
    // information.
    offset = defaultValue(offset, classProperty.offset);
    scale = defaultValue(scale, classProperty.scale);

    // Since metadata table properties are stored as packed typed
    // arrays, flatten the offset/scale to make it easier to apply the
    // transformation by iteration.
    offset = flatten(offset);
    scale = flatten(scale);

    let getValueFunction;
    let setValueFunction;
    const that = this;
    if (hasStrings) {
      getValueFunction = function (index) {
        return getString(index, that._values, that._stringOffsets);
      };
    } else if (hasBooleans) {
      getValueFunction = function (index) {
        return getBoolean(index, that._values);
      };
      setValueFunction = function (index, value) {
        setBoolean(index, that._values, value);
      };
    } else if (defined(enumType)) {
      getValueFunction = function (index) {
        const integer = that._values.get(index);
        return enumType.namesByValue[integer];
      };
      setValueFunction = function (index, value) {
        const integer = enumType.valuesByName[value];
        that._values.set(index, integer);
      };
    } else {
      getValueFunction = function (index) {
        return that._values.get(index);
      };
      setValueFunction = function (index, value) {
        that._values.set(index, value);
      };
    }

    this._arrayOffsets = arrayOffsets;
    this._stringOffsets = stringOffsets;
    this._values = values;
    this._classProperty = classProperty;
    this._count = count;
    this._vectorComponentCount = vectorComponentCount;
    this._min = property.min;
    this._max = property.max;
    this._offset = offset;
    this._scale = scale;
    this._hasValueTransform = hasValueTransform;
    this._getValue = getValueFunction;
    this._setValue = setValueFunction;
    this._unpackedValues = undefined;
    this._extras = property.extras;
    this._extensions = property.extensions;
    this._byteLength = byteLength;
  }

  Object.defineProperties(MetadataTableProperty.prototype, {
    /**
     * True if offset/scale should be applied. If both offset/scale were
     * undefined, they default to identity so this property is set false
     *
     * @memberof MetadataClassProperty.prototype
     * @type {Boolean}
     * @readonly
     * @private
     */
    hasValueTransform: {
      get: function () {
        return this._hasValueTransform;
      },
    },

    /**
     * The offset to be added to property values as part of the value transform.
     *
     * @memberof MetadataClassProperty.prototype
     * @type {Number|Number[]|Number[][]}
     * @readonly
     * @private
     */
    offset: {
      get: function () {
        return this._offset;
      },
    },

    /**
     * The scale to be multiplied to property values as part of the value transform.
     *
     * @memberof MetadataClassProperty.prototype
     * @type {Number|Number[]|Number[][]}
     * @readonly
     * @private
     */
    scale: {
      get: function () {
        return this._scale;
      },
    },

    /**
     * Extras in the JSON object.
     *
     * @memberof MetadataTableProperty.prototype
     * @type {*}
     * @readonly
     * @private
     */
    extras: {
      get: function () {
        return this._extras;
      },
    },

    /**
     * Extensions in the JSON object.
     *
     * @memberof MetadataTableProperty.prototype
     * @type {*}
     * @readonly
     * @private
     */
    extensions: {
      get: function () {
        return this._extensions;
      },
    },

    /**
     * Size of all typed arrays used by this table property
     *
     * @memberof MetadataTableProperty.prototype
     * @type {Normal}
     * @readonly
     * @private
     */
    byteLength: {
      get: function () {
        return this._byteLength;
      },
    },
  });

  /**
   * Returns a copy of the value at the given index.
   *
   * @param {Number} index The index.
   * @returns {*} The value of the property.
   *
   * @private
   */
  MetadataTableProperty.prototype.get = function (index) {
    //>>includeStart('debug', pragmas.debug);
    checkIndex(this, index);
    //>>includeEnd('debug');

    let value = get(this, index);

    // handle noData and default
    value = this._classProperty.handleNoData(value);
    if (!defined(value)) {
      value = this._classProperty.default;
      return this._classProperty.unpackVectorAndMatrixTypes(value);
    }

    value = this._classProperty.normalize(value);
    value = applyValueTransform(this, value);
    return this._classProperty.unpackVectorAndMatrixTypes(value);
  };

  /**
   * Sets the value at the given index.
   *
   * @param {Number} index The index.
   * @param {*} value The value of the property.
   *
   * @private
   */
  MetadataTableProperty.prototype.set = function (index, value) {
    const classProperty = this._classProperty;

    //>>includeStart('debug', pragmas.debug);
    Check.defined("value", value);
    checkIndex(this, index);
    const errorMessage = classProperty.validate(value);
    if (defined(errorMessage)) {
      throw new DeveloperError(errorMessage);
    }
    //>>includeEnd('debug');

    value = classProperty.packVectorAndMatrixTypes(value);
    value = unapplyValueTransform(this, value);
    value = classProperty.unnormalize(value);

    set(this, index, value);
  };

  /**
   * Returns a typed array containing the property values.
   *
   * @returns {*} The typed array containing the property values or <code>undefined</code> if the property values are not stored in a typed array.
   *
   * @private
   */
  MetadataTableProperty.prototype.getTypedArray = function () {
    // Note: depending on the class definition some properties are unpacked to
    // JS arrays when first accessed and values will be undefined. Generally not
    // a concern for fixed-length arrays of numbers.
    if (defined(this._values)) {
      return this._values.typedArray;
    }

    return undefined;
  };

  function flatten(values) {
    if (!Array.isArray(values)) {
      return values;
    }

    const result = [];
    for (let i = 0; i < values.length; i++) {
      const value = values[i];
      if (Array.isArray(value)) {
        result.push.apply(result, value);
      } else {
        result.push(value);
      }
    }

    return result;
  }

  function checkIndex(table, index) {
    const count = table._count;
    if (!defined(index) || index < 0 || index >= count) {
      const maximumIndex = count - 1;
      throw new DeveloperError(
        `index is required and between zero and count - 1. Actual value: ${maximumIndex}`
      );
    }
  }

  function get(property, index) {
    if (requiresUnpackForGet(property)) {
      unpackProperty(property);
    }

    const classProperty = property._classProperty;
    const isArray = classProperty.isArray;
    const type = classProperty.type;
    const componentCount = MetadataType$1.getComponentCount(type);

    if (defined(property._unpackedValues)) {
      const value = property._unpackedValues[index];
      if (isArray) {
        return clone$1(value, true);
      }
      return value;
    }

    // handle single values
    if (!isArray && componentCount === 1) {
      return property._getValue(index);
    }

    return getArrayValues(property, classProperty, index);
  }

  function getArrayValues(property, classProperty, index) {
    let offset;
    let length;
    if (classProperty.isVariableLengthArray) {
      offset = property._arrayOffsets.get(index);
      length = property._arrayOffsets.get(index + 1) - offset;

      // for vectors and matrices, the offset and length need to be multiplied
      // by the component count
      const componentCount = MetadataType$1.getComponentCount(classProperty.type);
      offset *= componentCount;
      length *= componentCount;
    } else {
      const arrayLength = defaultValue(classProperty.arrayLength, 1);
      const componentCount = arrayLength * property._vectorComponentCount;
      offset = index * componentCount;
      length = componentCount;
    }

    const values = new Array(length);
    for (let i = 0; i < length; i++) {
      values[i] = property._getValue(offset + i);
    }

    return values;
  }

  function set(property, index, value) {
    if (requiresUnpackForSet(property, index, value)) {
      unpackProperty(property);
    }

    const classProperty = property._classProperty;
    const isArray = classProperty.isArray;
    const type = classProperty.type;
    const componentCount = MetadataType$1.getComponentCount(type);

    if (defined(property._unpackedValues)) {
      if (classProperty.isArray) {
        value = clone$1(value, true);
      }
      property._unpackedValues[index] = value;
      return;
    }

    // Values are unpacked if the length of a variable-size array changes or the
    // property has strings. No need to handle these cases below.

    // Handle single values
    if (!isArray && componentCount === 1) {
      property._setValue(index, value);
      return;
    }

    let offset;
    let length;
    if (classProperty.isVariableLengthArray) {
      offset = property._arrayOffsets.get(index);
      length = property._arrayOffsets.get(index + 1) - offset;
    } else {
      const arrayLength = defaultValue(classProperty.arrayLength, 1);
      const componentCount = arrayLength * property._vectorComponentCount;
      offset = index * componentCount;
      length = componentCount;
    }

    for (let i = 0; i < length; ++i) {
      property._setValue(offset + i, value[i]);
    }
  }

  function getString(index, values, stringOffsets) {
    const stringByteOffset = stringOffsets.get(index);
    const stringByteLength = stringOffsets.get(index + 1) - stringByteOffset;
    return getStringFromTypedArray(
      values.typedArray,
      stringByteOffset,
      stringByteLength
    );
  }

  function getBoolean(index, values) {
    // byteIndex is floor(index / 8)
    const byteIndex = index >> 3;
    const bitIndex = index % 8;
    return ((values.typedArray[byteIndex] >> bitIndex) & 1) === 1;
  }

  function setBoolean(index, values, value) {
    // byteIndex is floor(index / 8)
    const byteIndex = index >> 3;
    const bitIndex = index % 8;

    if (value) {
      values.typedArray[byteIndex] |= 1 << bitIndex;
    } else {
      values.typedArray[byteIndex] &= ~(1 << bitIndex);
    }
  }

  function getInt64NumberFallback(index, values) {
    const dataView = values.dataView;
    const byteOffset = index * 8;
    let value = 0;
    const isNegative = (dataView.getUint8(byteOffset + 7) & 0x80) > 0;
    let carrying = true;
    for (let i = 0; i < 8; ++i) {
      let byte = dataView.getUint8(byteOffset + i);
      if (isNegative) {
        if (carrying) {
          if (byte !== 0x00) {
            byte = ~(byte - 1) & 0xff;
            carrying = false;
          }
        } else {
          byte = ~byte & 0xff;
        }
      }
      value += byte * Math.pow(256, i);
    }
    if (isNegative) {
      value = -value;
    }
    return value;
  }

  function getInt64BigIntFallback(index, values) {
    const dataView = values.dataView;
    const byteOffset = index * 8;
    // eslint-disable-next-line no-undef
    let value = BigInt(0);
    const isNegative = (dataView.getUint8(byteOffset + 7) & 0x80) > 0;
    let carrying = true;
    for (let i = 0; i < 8; ++i) {
      let byte = dataView.getUint8(byteOffset + i);
      if (isNegative) {
        if (carrying) {
          if (byte !== 0x00) {
            byte = ~(byte - 1) & 0xff;
            carrying = false;
          }
        } else {
          byte = ~byte & 0xff;
        }
      }
      value += BigInt(byte) * (BigInt(1) << BigInt(i * 8)); // eslint-disable-line
    }
    if (isNegative) {
      value = -value;
    }
    return value;
  }

  function getUint64NumberFallback(index, values) {
    const dataView = values.dataView;
    const byteOffset = index * 8;

    // Split 64-bit number into two 32-bit (4-byte) parts
    const left = dataView.getUint32(byteOffset, true);
    const right = dataView.getUint32(byteOffset + 4, true);

    // Combine the two 32-bit values
    const value = left + 4294967296 * right;

    return value;
  }

  function getUint64BigIntFallback(index, values) {
    const dataView = values.dataView;
    const byteOffset = index * 8;

    // Split 64-bit number into two 32-bit (4-byte) parts
    // eslint-disable-next-line no-undef
    const left = BigInt(dataView.getUint32(byteOffset, true));

    // eslint-disable-next-line no-undef
    const right = BigInt(dataView.getUint32(byteOffset + 4, true));

    // Combine the two 32-bit values
    // eslint-disable-next-line no-undef
    const value = left + BigInt(4294967296) * right;

    return value;
  }

  function getComponentDatatype(componentType) {
    switch (componentType) {
      case MetadataComponentType$1.INT8:
        return ComponentDatatype$1.BYTE;
      case MetadataComponentType$1.UINT8:
        return ComponentDatatype$1.UNSIGNED_BYTE;
      case MetadataComponentType$1.INT16:
        return ComponentDatatype$1.SHORT;
      case MetadataComponentType$1.UINT16:
        return ComponentDatatype$1.UNSIGNED_SHORT;
      case MetadataComponentType$1.INT32:
        return ComponentDatatype$1.INT;
      case MetadataComponentType$1.UINT32:
        return ComponentDatatype$1.UNSIGNED_INT;
      case MetadataComponentType$1.FLOAT32:
        return ComponentDatatype$1.FLOAT;
      case MetadataComponentType$1.FLOAT64:
        return ComponentDatatype$1.DOUBLE;
    }
  }

  function requiresUnpackForGet(property) {
    if (defined(property._unpackedValues)) {
      return false;
    }

    const classProperty = property._classProperty;
    const type = classProperty.type;
    const valueType = classProperty.valueType;

    if (type === MetadataType$1.STRING) {
      // Unpack since UTF-8 decoding is expensive
      return true;
    }

    if (
      valueType === MetadataComponentType$1.INT64 &&
      !FeatureDetection.supportsBigInt64Array()
    ) {
      // Unpack since the fallback INT64 getters are expensive
      return true;
    }

    if (
      valueType === MetadataComponentType$1.UINT64 &&
      !FeatureDetection.supportsBigUint64Array()
    ) {
      // Unpack since the fallback UINT64 getters are expensive
      return true;
    }

    return false;
  }

  function requiresUnpackForSet(property, index, value) {
    if (requiresUnpackForGet(property)) {
      return true;
    }

    const arrayOffsets = property._arrayOffsets;
    if (defined(arrayOffsets)) {
      // Unpacking is required if a variable-size array changes length since it
      // would be expensive to repack the binary data
      const oldLength = arrayOffsets.get(index + 1) - arrayOffsets.get(index);
      const newLength = value.length;
      if (oldLength !== newLength) {
        return true;
      }
    }

    return false;
  }

  function unpackProperty(property) {
    property._unpackedValues = unpackValues(property);

    // Free memory
    property._arrayOffsets = undefined;
    property._stringOffsets = undefined;
    property._values = undefined;
  }

  function unpackValues(property) {
    const count = property._count;
    const unpackedValues = new Array(count);

    const classProperty = property._classProperty;
    const isArray = classProperty.isArray;
    const type = classProperty.type;
    const componentCount = MetadataType$1.getComponentCount(type);

    // Handle single values
    if (!isArray && componentCount === 1) {
      for (let i = 0; i < count; ++i) {
        unpackedValues[i] = property._getValue(i);
      }
      return unpackedValues;
    }

    for (let i = 0; i < count; i++) {
      unpackedValues[i] = getArrayValues(property, classProperty, i);
    }
    return unpackedValues;
  }

  function applyValueTransform(property, value) {
    const classProperty = property._classProperty;
    const isVariableLengthArray = classProperty.isVariableLengthArray;
    if (!property._hasValueTransform || isVariableLengthArray) {
      return value;
    }

    return MetadataClassProperty.valueTransformInPlace(
      value,
      property._offset,
      property._scale,
      MetadataComponentType$1.applyValueTransform
    );
  }

  function unapplyValueTransform(property, value) {
    const classProperty = property._classProperty;
    const isVariableLengthArray = classProperty.isVariableLengthArray;
    if (!property._hasValueTransform || isVariableLengthArray) {
      return value;
    }

    return MetadataClassProperty.valueTransformInPlace(
      value,
      property._offset,
      property._scale,
      MetadataComponentType$1.unapplyValueTransform
    );
  }

  function BufferView(bufferView, componentType, length) {
    const that = this;

    let typedArray;
    let getFunction;
    let setFunction;

    if (componentType === MetadataComponentType$1.INT64) {
      if (!FeatureDetection.supportsBigInt()) {
        oneTimeWarning(
          "INT64 type is not fully supported on this platform. Values greater than 2^53 - 1 or less than -(2^53 - 1) may lose precision when read."
        );
        typedArray = new Uint8Array(
          bufferView.buffer,
          bufferView.byteOffset,
          length * 8
        );
        getFunction = function (index) {
          return getInt64NumberFallback(index, that);
        };
      } else if (!FeatureDetection.supportsBigInt64Array()) {
        typedArray = new Uint8Array(
          bufferView.buffer,
          bufferView.byteOffset,
          length * 8
        );
        getFunction = function (index) {
          return getInt64BigIntFallback(index, that);
        };
      } else {
        // eslint-disable-next-line
        typedArray = new BigInt64Array(
          bufferView.buffer,
          bufferView.byteOffset,
          length
        );
        setFunction = function (index, value) {
          // Convert the number to a BigInt before setting the value in the typed array
          that.typedArray[index] = BigInt(value); // eslint-disable-line
        };
      }
    } else if (componentType === MetadataComponentType$1.UINT64) {
      if (!FeatureDetection.supportsBigInt()) {
        oneTimeWarning(
          "UINT64 type is not fully supported on this platform. Values greater than 2^53 - 1 may lose precision when read."
        );
        typedArray = new Uint8Array(
          bufferView.buffer,
          bufferView.byteOffset,
          length * 8
        );
        getFunction = function (index) {
          return getUint64NumberFallback(index, that);
        };
      } else if (!FeatureDetection.supportsBigUint64Array()) {
        typedArray = new Uint8Array(
          bufferView.buffer,
          bufferView.byteOffset,
          length * 8
        );
        getFunction = function (index) {
          return getUint64BigIntFallback(index, that);
        };
      } else {
        // eslint-disable-next-line
        typedArray = new BigUint64Array(
          bufferView.buffer,
          bufferView.byteOffset,
          length
        );
        setFunction = function (index, value) {
          // Convert the number to a BigInt before setting the value in the typed array
          that.typedArray[index] = BigInt(value); // eslint-disable-line
        };
      }
    } else {
      const componentDatatype = getComponentDatatype(componentType);
      typedArray = ComponentDatatype$1.createArrayBufferView(
        componentDatatype,
        bufferView.buffer,
        bufferView.byteOffset,
        length
      );
      setFunction = function (index, value) {
        that.typedArray[index] = value;
      };
    }

    if (!defined(getFunction)) {
      getFunction = function (index) {
        return that.typedArray[index];
      };
    }

    this.typedArray = typedArray;
    this.dataView = new DataView(typedArray.buffer, typedArray.byteOffset);
    this.get = getFunction;
    this.set = setFunction;

    // for unit testing
    this._componentType = componentType;
  }

  /**
   * A table containing binary metadata for a collection of entities. This is
   * used for representing binary properties of a batch table, as well as binary
   * metadata in 3D Tiles next extensions.
   * <p>
   * For 3D Tiles Next details, see the {@link https://github.com/CesiumGS/3d-tiles/tree/main/extensions/3DTILES_metadata|3DTILES_metadata Extension} for 3D Tiles, as well as the {@link https://github.com/CesiumGS/glTF/tree/3d-tiles-next/extensions/2.0/Vendor/EXT_feature_metadata|EXT_feature_metadata Extension} for glTF.
   * </p>
   *
   * @param {Object} options Object with the following properties:
   * @param {Number} options.count The number of entities in the table.
   * @param {Object} [options.properties] A dictionary containing properties.
   * @param {MetadataClass} options.class The class that properties conform to.
   * @param {Object.<String, Uint8Array>} [options.bufferViews] An object mapping bufferView IDs to Uint8Array objects.
   *
   * @alias MetadataTable
   * @constructor
   *
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function MetadataTable(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const count = options.count;
    const metadataClass = options.class;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number.greaterThan("options.count", count, 0);
    Check.typeOf.object("options.class", metadataClass);
    //>>includeEnd('debug');

    let byteLength = 0;
    const properties = {};
    if (defined(options.properties)) {
      for (const propertyId in options.properties) {
        if (options.properties.hasOwnProperty(propertyId)) {
          const property = new MetadataTableProperty({
            count: count,
            property: options.properties[propertyId],
            classProperty: metadataClass.properties[propertyId],
            bufferViews: options.bufferViews,
          });
          properties[propertyId] = property;
          byteLength += property.byteLength;
        }
      }
    }

    this._count = count;
    this._class = metadataClass;
    this._properties = properties;
    this._byteLength = byteLength;
  }

  Object.defineProperties(MetadataTable.prototype, {
    /**
     * The number of entities in the table.
     *
     * @memberof MetadataTable.prototype
     * @type {Number}
     * @readonly
     * @private
     */
    count: {
      get: function () {
        return this._count;
      },
    },

    /**
     * The class that properties conform to.
     *
     * @memberof MetadataTable.prototype
     * @type {MetadataClass}
     * @readonly
     * @private
     */
    class: {
      get: function () {
        return this._class;
      },
    },

    /**
     * The size of all typed arrays used in this table.
     *
     * @memberof MetadataTable.prototype
     * @type {Number}
     * @readonly
     * @private
     */
    byteLength: {
      get: function () {
        return this._byteLength;
      },
    },
  });

  /**
   * Returns whether the table has this property.
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @returns {Boolean} Whether the table has this property.
   * @private
   */
  MetadataTable.prototype.hasProperty = function (propertyId) {
    return MetadataEntity.hasProperty(propertyId, this._properties, this._class);
  };

  /**
   * Returns whether the table has a property with the given semantic.
   *
   * @param {String} semantic The case-sensitive semantic of the property.
   * @returns {Boolean} Whether the table has a property with the given semantic.
   * @private
   */
  MetadataTable.prototype.hasPropertyBySemantic = function (semantic) {
    return MetadataEntity.hasPropertyBySemantic(
      semantic,
      this._properties,
      this._class
    );
  };

  /**
   * Returns an array of property IDs.
   *
   * @param {String[]} [results] An array into which to store the results.
   * @returns {String[]} The property IDs.
   * @private
   */
  MetadataTable.prototype.getPropertyIds = function (results) {
    return MetadataEntity.getPropertyIds(this._properties, this._class, results);
  };

  /**
   * Returns a copy of the value of the property with the given ID.
   * <p>
   * If the property is an enum the name of the enum is returned.
   * </p>
   * <p>
   * If the property is normalized the normalized value is returned. The value is
   * in the range [-1.0, 1.0] for signed integer types and [0.0, 1.0] for unsigned
   * integer types.
   * </p>
   * <p>
   * If the property is not normalized and type or componentType is INT64 or
   * UINT64 a BigInt will be returned. On platforms that don't support BigInt a
   * number will be returned instead. Note that numbers only support up to 52 bits
   * of integer precision. Values greater than 2^53 - 1 or less than -(2^53 - 1)
   * may lose precision when read.
   * </p>
   *
   * @param {Number} index The index of the entity.
   * @param {String} propertyId The case-sensitive ID of the property.
   * @returns {*} The value of the property or <code>undefined</code> if the entity does not have this property.
   *
   * @exception {DeveloperError} index is required and between zero and count - 1
   * @private
   */
  MetadataTable.prototype.getProperty = function (index, propertyId) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("propertyId", propertyId);
    //>>includeEnd('debug');

    const property = this._properties[propertyId];

    let value;
    if (defined(property)) {
      value = property.get(index);
    } else {
      value = getDefault$1(this._class, propertyId);
    }

    return value;
  };

  /**
   * Sets the value of the property with the given ID.
   * <p>
   * If the property is an enum the name of the enum must be provided, not the
   * integer value.
   * </p>
   * <p>
   * If the property is normalized a normalized value must be provided to this
   * function. The value must be in the range [-1.0, 1.0] for signed integer
   * types and [0.0, 1.0] for unsigned integer types.
   * </p>
   * <p>
   * If the property is not normalized and type or componentType is INT64 or
   * UINT64 a BigInt may be provided. On platforms that don't support BigInt a
   * number may be provided instead. Note that numbers only support up to 52 bits
   * of integer precision. Values greater than 2^53 - 1 or less than -(2^53 - 1)
   * may lose precision when set."
   * </p>
   *
   * @param {Number} index The index of the entity.
   * @param {String} propertyId The case-sensitive ID of the property.
   * @param {*} value The value of the property that will be copied.
   * @returns {Boolean} <code>true</code> if the property was set, <code>false</code> otherwise.
   *
   * @exception {DeveloperError} index is required and between zero and count - 1
   * @exception {DeveloperError} value does not match type
   * @exception {DeveloperError} value is out of range for type
   * @exception {DeveloperError} Array length does not match componentCount
   * @private
   */
  MetadataTable.prototype.setProperty = function (index, propertyId, value) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("propertyId", propertyId);
    //>>includeEnd('debug');

    const property = this._properties[propertyId];
    if (defined(property)) {
      property.set(index, value);
      return true;
    }

    return false;
  };

  /**
   * Returns a copy of the value of the property with the given semantic.
   *
   * @param {Number} index The index of the entity.
   * @param {String} semantic The case-sensitive semantic of the property.
   * @returns {*} The value of the property or <code>undefined</code> if the entity does not have this semantic.
   *
   * @exception {DeveloperError} index is required and between zero and count - 1
   * @private
   */
  MetadataTable.prototype.getPropertyBySemantic = function (index, semantic) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("semantic", semantic);
    //>>includeEnd('debug');

    let property;
    const propertiesBySemantic = this._class.propertiesBySemantic;
    if (defined(propertiesBySemantic)) {
      property = propertiesBySemantic[semantic];
    }

    if (defined(property)) {
      return this.getProperty(index, property.id);
    }

    return undefined;
  };

  /**
   * Sets the value of the property with the given semantic.
   *
   * @param {Number} index The index of the entity.
   * @param {String} semantic The case-sensitive semantic of the property.
   * @param {*} value The value of the property that will be copied.
   * @returns {Boolean} <code>true</code> if the property was set, <code>false</code> otherwise.
   *
   * @exception {DeveloperError} index is required and between zero and count - 1
   * @exception {DeveloperError} value does not match type
   * @exception {DeveloperError} value is out of range for type
   * @exception {DeveloperError} Array length does not match componentCount
   * @private
   */
  MetadataTable.prototype.setPropertyBySemantic = function (
    index,
    semantic,
    value
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("semantic", semantic);
    //>>includeEnd('debug');

    let property;
    const propertiesBySemantic = this._class.propertiesBySemantic;
    if (defined(propertiesBySemantic)) {
      property = propertiesBySemantic[semantic];
    }

    if (defined(property)) {
      return this.setProperty(index, property.id, value);
    }

    return false;
  };

  /**
   * Returns a typed array containing the property values for a given propertyId.
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @returns {*} The typed array containing the property values or <code>undefined</code> if the property values are not stored in a typed array.
   *
   * @private
   */
  MetadataTable.prototype.getPropertyTypedArray = function (propertyId) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("propertyId", propertyId);
    //>>includeEnd('debug');

    const property = this._properties[propertyId];

    if (defined(property)) {
      return property.getTypedArray();
    }

    return undefined;
  };

  /**
   * Returns a typed array containing the property values for the property with the given semantic.
   *
   * @param {String} semantic The case-sensitive semantic of the property.
   * @returns {*} The typed array containing the property values or <code>undefined</code> if the property values are not stored in a typed array.
   *
   * @private
   */
  MetadataTable.prototype.getPropertyTypedArrayBySemantic = function (semantic) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("semantic", semantic);
    //>>includeEnd('debug');

    let property;
    const propertiesBySemantic = this._class.propertiesBySemantic;
    if (defined(propertiesBySemantic)) {
      property = propertiesBySemantic[semantic];
    }

    if (defined(property)) {
      return this.getPropertyTypedArray(property.id);
    }

    return undefined;
  };

  function getDefault$1(classDefinition, propertyId) {
    const classProperties = classDefinition.properties;
    if (!defined(classProperties)) {
      return undefined;
    }

    const classProperty = classProperties[propertyId];
    if (defined(classProperty) && defined(classProperty.default)) {
      let value = classProperty.default;
      if (classProperty.isArray) {
        value = clone$1(value, true);
      }
      value = classProperty.normalize(value);
      return classProperty.unpackVectorAndMatrixTypes(value);
    }
  }

  /**
   * A cache resource.
   * <p>
   * This type describes an interface and is not intended to be instantiated directly.
   * </p>
   *
   * @alias ResourceLoader
   * @constructor
   *
   * @see ResourceCache
   *
   * @private
   */
  function ResourceLoader() {}

  Object.defineProperties(ResourceLoader.prototype, {
    /**
     * A promise that resolves to the resource when the resource is ready, or undefined if the resource hasn't started loading.
     *
     * @memberof ResourceLoader.prototype
     *
     * @type {Promise.<ResourceLoader>|undefined}
     * @readonly
     * @private
     */
    promise: {
      // eslint-disable-next-line getter-return
      get: function () {
        DeveloperError.throwInstantiationError();
      },
    },
    /**
     * The cache key of the resource.
     *
     * @memberof ResourceLoader.prototype
     *
     * @type {String}
     * @readonly
     * @private
     */
    cacheKey: {
      // eslint-disable-next-line getter-return
      get: function () {
        DeveloperError.throwInstantiationError();
      },
    },
  });

  /**
   * Loads the resource.
   * @returns {Promise.<ResourceLoader>} A promise which resolves to the loader when the resource loading is completed.
   * @private
   */
  ResourceLoader.prototype.load = function () {
    DeveloperError.throwInstantiationError();
  };

  /**
   * Unloads the resource.
   * @private
   */
  ResourceLoader.prototype.unload = function () {};

  /**
   * Processes the resource until it becomes ready.
   *
   * @param {FrameState} frameState The frame state.
   * @private
   */
  ResourceLoader.prototype.process = function (frameState) {};

  /**
   * Constructs a {@link RuntimeError} from an errorMessage and an error.
   *
   * @param {String} errorMessage The error message.
   * @param {Error} [error] The error.
   *
   * @returns {RuntimeError} The runtime error.
   * @private
   */
  ResourceLoader.prototype.getError = function (errorMessage, error) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("errorMessage", errorMessage);
    //>>includeEnd('debug');

    if (defined(error)) {
      errorMessage += `\n${error.message}`;
    }
    return new RuntimeError(errorMessage);
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see ResourceLoader#destroy
   * @private
   */
  ResourceLoader.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the loaded resource.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @example
   * resourceLoader = resourceLoader && resourceLoader.destroy();
   *
   * @see ResourceLoader#isDestroyed
   * @private
   */
  ResourceLoader.prototype.destroy = function () {
    this.unload();
    return destroyObject(this);
  };

  /**
   * The {@link ResourceLoader} state.
   *
   * @private
   */
  const ResourceLoaderState = {
    /**
     * The resource has not yet been loaded.
     *
     * @type {Number}
     * @constant
     * @private
     */
    UNLOADED: 0,
    /**
     * The resource is loading. In this state, external resources are fetched as needed.
     *
     * @type {Number}
     * @constant
     * @private
     */
    LOADING: 1,
    /**
     * The resource has finished loading, but requires further processing. GPU resources are allocated in this state as needed.
     *
     * @type {Number}
     * @constant
     * @private
     */
    PROCESSING: 2,
    /**
     * The resource has finished loading and processing; the results are ready to be used.
     *
     * @type {Number}
     * @constant
     * @private
     */
    READY: 3,
    /**
     * The resource loading or processing has failed due to an error.
     *
     * @type {Number}
     * @constant
     * @private
     */
    FAILED: 4,
  };
  var ResourceLoaderState$1 = Object.freeze(ResourceLoaderState);

  /**
   * Loads an embedded or external buffer.
   * <p>
   * Implements the {@link ResourceLoader} interface.
   * </p>
   *
   * @alias BufferLoader
   * @constructor
   * @augments ResourceLoader
   *
   * @param {Object} options Object with the following properties:
   * @param {Uint8Array} [options.typedArray] The typed array containing the embedded buffer contents. Mutually exclusive with options.resource.
   * @param {Resource} [options.resource] The {@link Resource} pointing to the external buffer. Mutually exclusive with options.typedArray.
   * @param {String} [options.cacheKey] The cache key of the resource.
   *
   * @exception {DeveloperError} One of options.typedArray and options.resource must be defined.
   *
   * @private
   */
  function BufferLoader(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const typedArray = options.typedArray;
    const resource = options.resource;
    const cacheKey = options.cacheKey;

    //>>includeStart('debug', pragmas.debug);
    if (defined(typedArray) === defined(resource)) {
      throw new DeveloperError(
        "One of options.typedArray and options.resource must be defined."
      );
    }
    //>>includeEnd('debug');

    this._typedArray = typedArray;
    this._resource = resource;
    this._cacheKey = cacheKey;
    this._state = ResourceLoaderState$1.UNLOADED;
    this._promise = undefined;
  }

  if (defined(Object.create)) {
    BufferLoader.prototype = Object.create(ResourceLoader.prototype);
    BufferLoader.prototype.constructor = BufferLoader;
  }

  Object.defineProperties(BufferLoader.prototype, {
    /**
     * A promise that resolves to the resource when the resource is ready, or undefined if the resource hasn't started loading.
     *
     * @memberof BufferLoader.prototype
     *
     * @type {Promise.<BufferLoader>|undefined}
     * @readonly
     */
    promise: {
      get: function () {
        return this._promise;
      },
    },
    /**
     * The cache key of the resource.
     *
     * @memberof BufferLoader.prototype
     *
     * @type {String}
     * @readonly
     */
    cacheKey: {
      get: function () {
        return this._cacheKey;
      },
    },
    /**
     * The typed array containing the embedded buffer contents.
     *
     * @memberof BufferLoader.prototype
     *
     * @type {Uint8Array}
     * @readonly
     */
    typedArray: {
      get: function () {
        return this._typedArray;
      },
    },
  });

  /**
   * Loads the resource.
   * @returns {Promise.<BufferLoader>} A promise which resolves to the loader when the resource loading is completed.
   * @private
   */
  BufferLoader.prototype.load = function () {
    if (defined(this._typedArray)) {
      this._promise = Promise.resolve(this);
    } else {
      this._promise = loadExternalBuffer(this);
    }
    return this._promise;
  };

  function loadExternalBuffer(bufferLoader) {
    const resource = bufferLoader._resource;
    bufferLoader._state = ResourceLoaderState$1.LOADING;
    return BufferLoader._fetchArrayBuffer(resource)
      .then(function (arrayBuffer) {
        if (bufferLoader.isDestroyed()) {
          return;
        }
        bufferLoader._typedArray = new Uint8Array(arrayBuffer);
        bufferLoader._state = ResourceLoaderState$1.READY;
        return bufferLoader;
      })
      .catch(function (error) {
        if (bufferLoader.isDestroyed()) {
          return;
        }
        bufferLoader._state = ResourceLoaderState$1.FAILED;
        const errorMessage = `Failed to load external buffer: ${resource.url}`;
        return Promise.reject(bufferLoader.getError(errorMessage, error));
      });
  }

  /**
   * Exposed for testing
   * @private
   */
  BufferLoader._fetchArrayBuffer = function (resource) {
    return resource.fetchArrayBuffer();
  };

  /**
   * Unloads the resource.
   * @private
   */
  BufferLoader.prototype.unload = function () {
    this._typedArray = undefined;
  };

  /* This file is automatically rebuilt by the Cesium build process. */
  // This file is part of meshoptimizer library and is distributed under the terms of MIT License.
  // Copyright (C) 2016-2021, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)
  ((function() {

  	// Built with clang version 11.0.0 (https://github.com/llvm/llvm-project 176249bd6732a8044d457092ed932768724a6f06)
  	// Built from meshoptimizer 0.16
  	var wasm = " ";

  	// Used to unpack wasm
  	var wasmpack = new Uint8Array([32,0,65,2,1,106,34,33,3,128,11,4,13,64,6,253,10,7,15,116,127,5,8,12,40,16,19,54,20,9,27,255,113,17,42,67,24,23,146,148,18,14,22,45,70,69,56,114,101,21,25,63,75,136,108,28,118,29,73,115]);

  	if (typeof WebAssembly !== 'object') {
  		// This module requires WebAssembly to function
  		return {
  			supported: false,
  		};
  	}

  	var instance;

  	var promise =
  		WebAssembly.instantiate(unpack(wasm), {})
  		.then(function(result) {
  			instance = result.instance;
  			instance.exports.__wasm_call_ctors();
  			instance.exports.meshopt_encodeVertexVersion(0);
  			instance.exports.meshopt_encodeIndexVersion(1);
  		});

  	function unpack(data) {
  		var result = new Uint8Array(data.length);
  		for (var i = 0; i < data.length; ++i) {
  			var ch = data.charCodeAt(i);
  			result[i] = ch > 96 ? ch - 71 : ch > 64 ? ch - 65 : ch > 47 ? ch + 4 : ch > 46 ? 63 : 62;
  		}
  		var write = 0;
  		for (var i = 0; i < data.length; ++i) {
  			result[write++] = (result[i] < 60) ? wasmpack[result[i]] : (result[i] - 60) * 64 + result[++i];
  		}
  		return result.buffer.slice(0, write);
  	}

  	function assert(cond) {
  		if (!cond) {
  			throw new Error("Assertion failed");
  		}
  	}

  	function reorder(indices, vertices, optf) {
  		var sbrk = instance.exports.sbrk;
  		var ip = sbrk(indices.length * 4);
  		var rp = sbrk(vertices * 4);
  		var heap = new Uint8Array(instance.exports.memory.buffer);
  		var indices8 = new Uint8Array(indices.buffer, indices.byteOffset, indices.byteLength);
  		heap.set(indices8, ip);
  		if (optf) {
  			optf(ip, ip, indices.length, vertices);
  		}
  		var unique = instance.exports.meshopt_optimizeVertexFetchRemap(rp, ip, indices.length, vertices);
  		// heap may have grown
  		heap = new Uint8Array(instance.exports.memory.buffer);
  		var remap = new Uint32Array(vertices);
  		new Uint8Array(remap.buffer).set(heap.subarray(rp, rp + vertices * 4));
  		indices8.set(heap.subarray(ip, ip + indices.length * 4));
  		sbrk(ip - sbrk(0));

  		for (var i = 0; i < indices.length; ++i)
  			indices[i] = remap[indices[i]];

  		return [remap, unique];
  	}

  	function encode(fun, bound, source, count, size) {
  		var sbrk = instance.exports.sbrk;
  		var tp = sbrk(bound);
  		var sp = sbrk(count * size);
  		var heap = new Uint8Array(instance.exports.memory.buffer);
  		heap.set(new Uint8Array(source.buffer, source.byteOffset, source.byteLength), sp);
  		var res = fun(tp, bound, sp, count, size);
  		var target = new Uint8Array(res);
  		target.set(heap.subarray(tp, tp + res));
  		sbrk(tp - sbrk(0));
  		return target;
  	}

  	function maxindex(source) {
  		var result = 0;
  		for (var i = 0; i < source.length; ++i) {
  			var index = source[i];
  			result = result < index ? index : result;
  		}
  		return result;
  	}

  	function index32(source, size) {
  		assert(size == 2 || size == 4);
  		if (size == 4) {
  			return new Uint32Array(source.buffer, source.byteOffset, source.byteLength / 4);
  		} else {
  			var view = new Uint16Array(source.buffer, source.byteOffset, source.byteLength / 2);
  			return new Uint32Array(view); // copies each element
  		}
  	}

  	function filter(fun, source, count, stride, bits, insize) {
  		var sbrk = instance.exports.sbrk;
  		var tp = sbrk(count * stride);
  		var sp = sbrk(count * insize);
  		var heap = new Uint8Array(instance.exports.memory.buffer);
  		heap.set(new Uint8Array(source.buffer, source.byteOffset, source.byteLength), sp);
  		fun(tp, count, stride, bits, sp);
  		var target = new Uint8Array(count * stride);
  		target.set(heap.subarray(tp, tp + count * stride));
  		sbrk(tp - sbrk(0));
  		return target;
  	}

  	return {
  		ready: promise,
  		supported: true,
  		reorderMesh: function(indices, triangles, optsize) {
  			var optf = triangles ? (optsize ? instance.exports.meshopt_optimizeVertexCacheStrip : instance.exports.meshopt_optimizeVertexCache) : undefined;
  			return reorder(indices, maxindex(indices) + 1, optf);
  		},
  		encodeVertexBuffer: function(source, count, size) {
  			assert(size > 0 && size <= 256);
  			assert(size % 4 == 0);
  			var bound = instance.exports.meshopt_encodeVertexBufferBound(count, size);
  			return encode(instance.exports.meshopt_encodeVertexBuffer, bound, source, count, size);
  		},
  		encodeIndexBuffer: function(source, count, size) {
  			assert(size == 2 || size == 4);
  			assert(count % 3 == 0);
  			var indices = index32(source, size);
  			var bound = instance.exports.meshopt_encodeIndexBufferBound(count, maxindex(indices) + 1);
  			return encode(instance.exports.meshopt_encodeIndexBuffer, bound, indices, count, 4);
  		},
  		encodeIndexSequence: function(source, count, size) {
  			assert(size == 2 || size == 4);
  			var indices = index32(source, size);
  			var bound = instance.exports.meshopt_encodeIndexSequenceBound(count, maxindex(indices) + 1);
  			return encode(instance.exports.meshopt_encodeIndexSequence, bound, indices, count, 4);
  		},
  		encodeGltfBuffer: function(source, count, size, mode) {
  			var table = {
  				ATTRIBUTES: this.encodeVertexBuffer,
  				TRIANGLES: this.encodeIndexBuffer,
  				INDICES: this.encodeIndexSequence,
  			};
  			assert(table[mode]);
  			return table[mode](source, count, size);
  		},
  		encodeFilterOct: function(source, count, stride, bits) {
  			assert(stride == 4 || stride == 8);
  			assert(bits >= 1 && bits <= 16);
  			return filter(instance.exports.meshopt_encodeFilterOct, source, count, stride, bits, 4);
  		},
  		encodeFilterQuat: function(source, count, stride, bits) {
  			assert(stride == 8);
  			assert(bits >= 4 && bits <= 16);
  			return filter(instance.exports.meshopt_encodeFilterQuat, source, count, stride, bits, 4);
  		},
  		encodeFilterExp: function(source, count, stride, bits) {
  			assert(stride > 0 && stride % 4 == 0);
  			assert(bits >= 1 && bits <= 24);
  			return filter(instance.exports.meshopt_encodeFilterExp, source, count, stride, bits, stride/4);
  		},
  	};
  }))();

  // This file is part of meshoptimizer library and is distributed under the terms of MIT License.
  // Copyright (C) 2016-2021, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)
  var MeshoptDecoder = (function() {

  	// Built with clang version 11.0.0 (https://github.com/llvm/llvm-project 176249bd6732a8044d457092ed932768724a6f06)
  	// Built from meshoptimizer 0.16
  	var wasm_base = " ";
  	var wasm_simd = " ";

  	// Uses bulk-memory and simd extensions
  	var detector = new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,3,2,0,0,5,3,1,0,1,12,1,0,10,22,2,12,0,65,0,65,0,65,0,252,10,0,0,11,7,0,65,0,253,15,26,11]);

  	// Used to unpack wasm
  	var wasmpack = new Uint8Array([32,0,65,2,1,106,34,33,3,128,11,4,13,64,6,253,10,7,15,116,127,5,8,12,40,16,19,54,20,9,27,255,113,17,42,67,24,23,146,148,18,14,22,45,70,69,56,114,101,21,25,63,75,136,108,28,118,29,73,115]);

  	if (typeof WebAssembly !== 'object') {
  		// This module requires WebAssembly to function
  		return {
  			supported: false,
  		};
  	}

  	var wasm = wasm_base;

  	if (WebAssembly.validate(detector)) {
  		wasm = wasm_simd;
  	}

  	var instance;

  	var promise =
  		WebAssembly.instantiate(unpack(wasm), {})
  		.then(function(result) {
  			instance = result.instance;
  			instance.exports.__wasm_call_ctors();
  		});

  	function unpack(data) {
  		var result = new Uint8Array(data.length);
  		for (var i = 0; i < data.length; ++i) {
  			var ch = data.charCodeAt(i);
  			result[i] = ch > 96 ? ch - 71 : ch > 64 ? ch - 65 : ch > 47 ? ch + 4 : ch > 46 ? 63 : 62;
  		}
  		var write = 0;
  		for (var i = 0; i < data.length; ++i) {
  			result[write++] = (result[i] < 60) ? wasmpack[result[i]] : (result[i] - 60) * 64 + result[++i];
  		}
  		return result.buffer.slice(0, write);
  	}

  	function decode(fun, target, count, size, source, filter) {
  		var sbrk = instance.exports.sbrk;
  		var count4 = (count + 3) & ~3; // pad for SIMD filter
  		var tp = sbrk(count4 * size);
  		var sp = sbrk(source.length);
  		var heap = new Uint8Array(instance.exports.memory.buffer);
  		heap.set(source, sp);
  		var res = fun(tp, count, size, sp, source.length);
  		if (res == 0 && filter) {
  			filter(tp, count4, size);
  		}
  		target.set(heap.subarray(tp, tp + count * size));
  		sbrk(tp - sbrk(0));
  		if (res != 0) {
  			throw new Error("Malformed buffer data: " + res);
  		}
  	}
  	var filters = {
  		// legacy index-based enums for glTF
  		0: "",
  		1: "meshopt_decodeFilterOct",
  		2: "meshopt_decodeFilterQuat",
  		3: "meshopt_decodeFilterExp",
  		// string-based enums for glTF
  		NONE: "",
  		OCTAHEDRAL: "meshopt_decodeFilterOct",
  		QUATERNION: "meshopt_decodeFilterQuat",
  		EXPONENTIAL: "meshopt_decodeFilterExp",
  	};

  	var decoders = {
  		// legacy index-based enums for glTF
  		0: "meshopt_decodeVertexBuffer",
  		1: "meshopt_decodeIndexBuffer",
  		2: "meshopt_decodeIndexSequence",
  		// string-based enums for glTF
  		ATTRIBUTES: "meshopt_decodeVertexBuffer",
  		TRIANGLES: "meshopt_decodeIndexBuffer",
  		INDICES: "meshopt_decodeIndexSequence",
  	};

  	return {
  		ready: promise,
  		supported: true,
  		decodeVertexBuffer: function(target, count, size, source, filter) {
  			decode(instance.exports.meshopt_decodeVertexBuffer, target, count, size, source, instance.exports[filters[filter]]);
  		},
  		decodeIndexBuffer: function(target, count, size, source) {
  			decode(instance.exports.meshopt_decodeIndexBuffer, target, count, size, source);
  		},
  		decodeIndexSequence: function(target, count, size, source) {
  			decode(instance.exports.meshopt_decodeIndexSequence, target, count, size, source);
  		},
  		decodeGltfBuffer: function(target, count, size, source, mode, filter) {
  			decode(instance.exports[decoders[mode]], target, count, size, source, instance.exports[filters[filter]]);
  		}
  	};
  })();

  /**
   * Loads a glTF buffer view.
   * <p>
   * Implements the {@link ResourceLoader} interface.
   * </p>
   *
   * @alias GltfBufferViewLoader
   * @constructor
   * @augments ResourceLoader
   *
   * @param {Object} options Object with the following properties:
   * @param {ResourceCache} options.resourceCache The {@link ResourceCache} (to avoid circular dependencies).
   * @param {Object} options.gltf The glTF JSON.
   * @param {Number} options.bufferViewId The buffer view ID.
   * @param {Resource} options.gltfResource The {@link Resource} containing the glTF.
   * @param {Resource} options.baseResource The {@link Resource} that paths in the glTF JSON are relative to.
   * @param {String} [options.cacheKey] The cache key of the resource.
   *
   * @private
   */
  function GltfBufferViewLoader(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const resourceCache = options.resourceCache;
    const gltf = options.gltf;
    const bufferViewId = options.bufferViewId;
    const gltfResource = options.gltfResource;
    const baseResource = options.baseResource;
    const cacheKey = options.cacheKey;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.func("options.resourceCache", resourceCache);
    Check.typeOf.object("options.gltf", gltf);
    Check.typeOf.number("options.bufferViewId", bufferViewId);
    Check.typeOf.object("options.gltfResource", gltfResource);
    Check.typeOf.object("options.baseResource", baseResource);
    //>>includeEnd('debug');

    const bufferView = gltf.bufferViews[bufferViewId];
    let bufferId = bufferView.buffer;
    let byteOffset = bufferView.byteOffset;
    let byteLength = bufferView.byteLength;

    let hasMeshopt = false;
    let meshoptByteStride;
    let meshoptCount;
    let meshoptMode;
    let meshoptFilter;

    if (hasExtension(bufferView, "EXT_meshopt_compression")) {
      const meshopt = bufferView.extensions.EXT_meshopt_compression;
      bufferId = meshopt.buffer;
      byteOffset = defaultValue(meshopt.byteOffset, 0);
      byteLength = meshopt.byteLength;

      hasMeshopt = true;
      meshoptByteStride = meshopt.byteStride;
      meshoptCount = meshopt.count;
      meshoptMode = meshopt.mode;
      meshoptFilter = defaultValue(meshopt.filter, "NONE");
    }

    const buffer = gltf.buffers[bufferId];

    this._hasMeshopt = hasMeshopt;
    this._meshoptByteStride = meshoptByteStride;
    this._meshoptCount = meshoptCount;
    this._meshoptMode = meshoptMode;
    this._meshoptFilter = meshoptFilter;

    this._resourceCache = resourceCache;
    this._gltfResource = gltfResource;
    this._baseResource = baseResource;
    this._buffer = buffer;
    this._bufferId = bufferId;
    this._byteOffset = byteOffset;
    this._byteLength = byteLength;
    this._cacheKey = cacheKey;
    this._bufferLoader = undefined;
    this._typedArray = undefined;
    this._state = ResourceLoaderState$1.UNLOADED;
    this._promise = undefined;
    this._process = function (loader, frameState) {};
  }

  if (defined(Object.create)) {
    GltfBufferViewLoader.prototype = Object.create(ResourceLoader.prototype);
    GltfBufferViewLoader.prototype.constructor = GltfBufferViewLoader;
  }

  Object.defineProperties(GltfBufferViewLoader.prototype, {
    /**
     * A promise that resolves to the resource when the resource is ready, or undefined if the resource hasn't started loading.
     *
     * @memberof GltfBufferViewLoader.prototype
     *
     * @type {Promise.<GltfBufferViewLoader>|undefined}
     * @readonly
     * @private
     */
    promise: {
      get: function () {
        return this._promise;
      },
    },
    /**
     * The cache key of the resource.
     *
     * @memberof GltfBufferViewLoader.prototype
     *
     * @type {String}
     * @readonly
     * @private
     */
    cacheKey: {
      get: function () {
        return this._cacheKey;
      },
    },
    /**
     * The typed array containing buffer view data.
     *
     * @memberof GltfBufferViewLoader.prototype
     *
     * @type {Uint8Array}
     * @readonly
     * @private
     */
    typedArray: {
      get: function () {
        return this._typedArray;
      },
    },
  });

  /**
   * Loads the resource.
   * @returns {Promise.<GltfBufferViewLoader>} A promise which resolves to the loader when the resource loading is completed.
   * @private
   */
  GltfBufferViewLoader.prototype.load = function () {
    const bufferLoader = getBufferLoader(this);
    this._bufferLoader = bufferLoader;
    this._state = ResourceLoaderState$1.LOADING;

    const that = this;
    const bufferViewPromise = new Promise(function (resolve) {
      that._process = function (loader, frameState) {
        if (!loader._hasMeshopt) {
          return;
        }

        if (!defined(loader._typedArray)) {
          return;
        }

        if (loader._state !== ResourceLoaderState$1.PROCESSING) {
          return;
        }

        const count = loader._meshoptCount;
        const byteStride = loader._meshoptByteStride;
        const result = new Uint8Array(count * byteStride);
        MeshoptDecoder.decodeGltfBuffer(
          result,
          count,
          byteStride,
          loader._typedArray,
          loader._meshoptMode,
          loader._meshoptFilter
        );

        loader._typedArray = result;
        loader._state = ResourceLoaderState$1.READY;
        resolve(loader);
      };
    });

    this._promise = bufferLoader.promise
      .then(function () {
        if (that.isDestroyed()) {
          return;
        }
        const bufferTypedArray = bufferLoader.typedArray;
        const bufferViewTypedArray = new Uint8Array(
          bufferTypedArray.buffer,
          bufferTypedArray.byteOffset + that._byteOffset,
          that._byteLength
        );

        // Unload the buffer
        that.unload();

        that._typedArray = bufferViewTypedArray;
        if (that._hasMeshopt) {
          that._state = ResourceLoaderState$1.PROCESSING;
          return bufferViewPromise;
        }

        that._state = ResourceLoaderState$1.READY;
        return that;
      })
      .catch(function (error) {
        if (that.isDestroyed()) {
          return;
        }
        that.unload();
        that._state = ResourceLoaderState$1.FAILED;
        const errorMessage = "Failed to load buffer view";
        return Promise.reject(that.getError(errorMessage, error));
      });

    return this._promise;
  };

  function getBufferLoader(bufferViewLoader) {
    const resourceCache = bufferViewLoader._resourceCache;
    const buffer = bufferViewLoader._buffer;
    if (defined(buffer.uri)) {
      const baseResource = bufferViewLoader._baseResource;
      const resource = baseResource.getDerivedResource({
        url: buffer.uri,
      });
      return resourceCache.loadExternalBuffer({
        resource: resource,
      });
    }
    return resourceCache.loadEmbeddedBuffer({
      parentResource: bufferViewLoader._gltfResource,
      bufferId: bufferViewLoader._bufferId,
    });
  }

  /**
   * Processes the resources. For a BufferView that does not have the EXT_meshopt_compression extension, there
   * is no processing that needs to happen, so this function returns immediately.
   *
   * @param {FrameState} frameState The frame state.
   */
  GltfBufferViewLoader.prototype.process = function (frameState) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("frameState", frameState);
    //>>includeEnd('debug');

    return this._process(this, frameState);
  };

  /**
   * Unloads the resource.
   * @private
   */
  GltfBufferViewLoader.prototype.unload = function () {
    if (defined(this._bufferLoader)) {
      this._resourceCache.unload(this._bufferLoader);
    }

    this._bufferLoader = undefined;
    this._typedArray = undefined;
  };

  /**
   * Load a draco buffer from a glTF.
   * <p>
   * Implements the {@link ResourceLoader} interface.
   * </p>
   *
   * @alias GltfDracoLoader
   * @constructor
   * @augments ResourceLoader
   *
   * @param {Object} options Object with the following properties:
   * @param {ResourceCache} options.resourceCache The {@link ResourceCache} (to avoid circular dependencies).
   * @param {Object} options.gltf The glTF JSON.
   * @param {Object} options.draco The Draco extension object.
   * @param {Resource} options.gltfResource The {@link Resource} containing the glTF.
   * @param {Resource} options.baseResource The {@link Resource} that paths in the glTF JSON are relative to.
   * @param {String} [options.cacheKey] The cache key of the resource.
   *
   * @private
   */
  function GltfDracoLoader(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const resourceCache = options.resourceCache;
    const gltf = options.gltf;
    const draco = options.draco;
    const gltfResource = options.gltfResource;
    const baseResource = options.baseResource;
    const cacheKey = options.cacheKey;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.func("options.resourceCache", resourceCache);
    Check.typeOf.object("options.gltf", gltf);
    Check.typeOf.object("options.draco", draco);
    Check.typeOf.object("options.gltfResource", gltfResource);
    Check.typeOf.object("options.baseResource", baseResource);
    //>>includeEnd('debug');

    this._resourceCache = resourceCache;
    this._gltfResource = gltfResource;
    this._baseResource = baseResource;
    this._gltf = gltf;
    this._draco = draco;
    this._cacheKey = cacheKey;
    this._bufferViewLoader = undefined;
    this._bufferViewTypedArray = undefined;
    this._decodePromise = undefined;
    this._decodedData = undefined;
    this._state = ResourceLoaderState$1.UNLOADED;
    this._promise = undefined;
    this._process = function (loader, frameState) {};
  }

  if (defined(Object.create)) {
    GltfDracoLoader.prototype = Object.create(ResourceLoader.prototype);
    GltfDracoLoader.prototype.constructor = GltfDracoLoader;
  }

  Object.defineProperties(GltfDracoLoader.prototype, {
    /**
     * A promise that resolves to the resource when the resource is ready.
     *
     * @memberof GltfDracoLoader.prototype
     *
     * @type {Promise.<GltfDracoLoader>}
     * @readonly
     * @private
     */
    promise: {
      get: function () {
        return this._promise;
      },
    },
    /**
     * The cache key of the resource.
     *
     * @memberof GltfDracoLoader.prototype
     *
     * @type {String}
     * @readonly
     * @private
     */
    cacheKey: {
      get: function () {
        return this._cacheKey;
      },
    },
    /**
     * The decoded data.
     *
     * @memberof GltfDracoLoader.prototype
     *
     * @type {Object}
     * @readonly
     * @private
     */
    decodedData: {
      get: function () {
        return this._decodedData;
      },
    },
  });

  /**
   * Loads the resource.
   * @returns {Promise.<GltfDracoLoader>} A promise which resolves to the loader when the resource loading is completed.
   * @private
   */
  GltfDracoLoader.prototype.load = function () {
    const resourceCache = this._resourceCache;
    const bufferViewLoader = resourceCache.loadBufferView({
      gltf: this._gltf,
      bufferViewId: this._draco.bufferView,
      gltfResource: this._gltfResource,
      baseResource: this._baseResource,
    });

    this._bufferViewLoader = bufferViewLoader;
    this._state = ResourceLoaderState$1.LOADING;
    const that = this;
    const dracoPromise = new Promise(function (resolve, reject) {
      that._process = function (loader, frameState) {
        if (!defined(loader._bufferViewTypedArray)) {
          // Not ready to decode the Draco buffer
          return;
        }

        if (defined(loader._decodePromise)) {
          // Currently decoding
          return;
        }

        const draco = loader._draco;
        const gltf = loader._gltf;
        const bufferViews = gltf.bufferViews;
        const bufferViewId = draco.bufferView;
        const bufferView = bufferViews[bufferViewId];
        const compressedAttributes = draco.attributes;

        const decodeOptions = {
          // Need to make a copy of the typed array otherwise the underlying
          // ArrayBuffer may be accessed on both the worker and the main thread. This
          // leads to errors such as "ArrayBuffer at index 0 is already detached".
          // PERFORMANCE_IDEA: Look into SharedArrayBuffer to get around this.
          array: new Uint8Array(loader._bufferViewTypedArray),
          bufferView: bufferView,
          compressedAttributes: compressedAttributes,
          dequantizeInShader: true,
        };

        const decodePromise = DracoLoader.decodeBufferView(decodeOptions);

        if (!defined(decodePromise)) {
          // Cannot schedule task this frame
          return;
        }

        loader._decodePromise = decodePromise
          .then(function (results) {
            if (loader.isDestroyed()) {
              resolve();
              return;
            }

            // Unload everything except the decoded data
            loader.unload();

            loader._decodedData = {
              indices: results.indexArray,
              vertexAttributes: results.attributeData,
            };
            loader._state = ResourceLoaderState$1.READY;
            resolve(loader);
          })
          .catch(function (e) {
            if (loader.isDestroyed()) {
              resolve();
              return;
            }

            reject(e);
          });
      };
    });

    this._promise = bufferViewLoader.promise
      .then(function () {
        if (that.isDestroyed()) {
          return;
        }
        // Now wait for process() to run to finish loading
        that._bufferViewTypedArray = bufferViewLoader.typedArray;
        that._state = ResourceLoaderState$1.PROCESSING;

        return dracoPromise;
      })
      .catch(function (error) {
        if (that.isDestroyed()) {
          return;
        }

        return handleError$7(that, error);
      });

    return this._promise;
  };

  function handleError$7(dracoLoader, error) {
    dracoLoader.unload();
    dracoLoader._state = ResourceLoaderState$1.FAILED;
    const errorMessage = "Failed to load Draco";
    return Promise.reject(dracoLoader.getError(errorMessage, error));
  }

  /**
   * Processes the resource until it becomes ready.
   *
   * @param {FrameState} frameState The frame state.
   * @private
   */
  GltfDracoLoader.prototype.process = function (frameState) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("frameState", frameState);
    //>>includeEnd('debug');

    return this._process(this, frameState);
  };

  /**
   * Unloads the resource.
   * @private
   */
  GltfDracoLoader.prototype.unload = function () {
    if (defined(this._bufferViewLoader)) {
      this._resourceCache.unload(this._bufferViewLoader);
    }

    this._bufferViewLoader = undefined;
    this._bufferViewTypedArray = undefined;
    this._decodedData = undefined;
    this._gltf = undefined;
  };

  /**
   * Loads a glTF image.
   * <p>
   * Implements the {@link ResourceLoader} interface.
   * </p>
   *
   * @alias GltfImageLoader
   * @constructor
   * @augments ResourceLoader
   *
   * @param {Object} options Object with the following properties:
   * @param {ResourceCache} options.resourceCache The {@link ResourceCache} (to avoid circular dependencies).
   * @param {Object} options.gltf The glTF JSON.
   * @param {Number} options.imageId The image ID.
   * @param {Resource} options.gltfResource The {@link Resource} containing the glTF.
   * @param {Resource} options.baseResource The {@link Resource} that paths in the glTF JSON are relative to.
   * @param {String} [options.cacheKey] The cache key of the resource.
   *
   * @private
   */
  function GltfImageLoader(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const resourceCache = options.resourceCache;
    const gltf = options.gltf;
    const imageId = options.imageId;
    const gltfResource = options.gltfResource;
    const baseResource = options.baseResource;
    const cacheKey = options.cacheKey;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.func("options.resourceCache", resourceCache);
    Check.typeOf.object("options.gltf", gltf);
    Check.typeOf.number("options.imageId", imageId);
    Check.typeOf.object("options.gltfResource", gltfResource);
    Check.typeOf.object("options.baseResource", baseResource);
    //>>includeEnd('debug');

    const image = gltf.images[imageId];
    const bufferViewId = image.bufferView;
    const uri = image.uri;

    this._resourceCache = resourceCache;
    this._gltfResource = gltfResource;
    this._baseResource = baseResource;
    this._gltf = gltf;
    this._bufferViewId = bufferViewId;
    this._uri = uri;
    this._cacheKey = cacheKey;
    this._bufferViewLoader = undefined;
    this._image = undefined;
    this._mipLevels = undefined;
    this._state = ResourceLoaderState$1.UNLOADED;
    this._promise = undefined;
  }

  if (defined(Object.create)) {
    GltfImageLoader.prototype = Object.create(ResourceLoader.prototype);
    GltfImageLoader.prototype.constructor = GltfImageLoader;
  }

  Object.defineProperties(GltfImageLoader.prototype, {
    /**
     * A promise that resolves to the resource when the resource is ready, or undefined if the resource hasn't started loading.
     *
     * @memberof GltfImageLoader.prototype
     *
     * @type {Promise.<GltfImageLoader>|undefined}
     * @readonly
     * @private
     */
    promise: {
      get: function () {
        return this._promise;
      },
    },
    /**
     * The cache key of the resource.
     *
     * @memberof GltfImageLoader.prototype
     *
     * @type {String}
     * @readonly
     * @private
     */
    cacheKey: {
      get: function () {
        return this._cacheKey;
      },
    },
    /**
     * The image.
     *
     * @memberof GltfImageLoader.prototype
     *
     * @type {Image|ImageBitmap|CompressedTextureBuffer}
     * @readonly
     * @private
     */
    image: {
      get: function () {
        return this._image;
      },
    },
    /**
     * The mip levels. Only defined for KTX2 files containing mip levels.
     *
     * @memberof GltfImageLoader.prototype
     *
     * @type {Uint8Array[]}
     * @readonly
     * @private
     */
    mipLevels: {
      get: function () {
        return this._mipLevels;
      },
    },
  });

  /**
   * Loads the resource.
   * @returns {Promise.<GltfImageLoader>} A promise which resolves to the loader when the resource loading is completed.
   * @private
   */
  GltfImageLoader.prototype.load = function () {
    if (defined(this._bufferViewId)) {
      this._promise = loadFromBufferView$2(this);
      return this._promise;
    }

    this._promise = loadFromUri$1(this);
    return this._promise;
  };

  function getImageAndMipLevels(image) {
    // Images transcoded from KTX2 can contain multiple mip levels:
    // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu
    let mipLevels;
    if (Array.isArray(image)) {
      // highest detail mip should be level 0
      mipLevels = image.slice(1, image.length).map(function (mipLevel) {
        return mipLevel.bufferView;
      });
      image = image[0];
    }
    return {
      image: image,
      mipLevels: mipLevels,
    };
  }

  function loadFromBufferView$2(imageLoader) {
    const resourceCache = imageLoader._resourceCache;
    const bufferViewLoader = resourceCache.loadBufferView({
      gltf: imageLoader._gltf,
      bufferViewId: imageLoader._bufferViewId,
      gltfResource: imageLoader._gltfResource,
      baseResource: imageLoader._baseResource,
    });

    imageLoader._bufferViewLoader = bufferViewLoader;
    imageLoader._state = ResourceLoaderState$1.LOADING;

    return bufferViewLoader.promise
      .then(function () {
        if (imageLoader.isDestroyed()) {
          return;
        }

        const typedArray = bufferViewLoader.typedArray;
        return loadImageFromBufferTypedArray(typedArray).then(function (image) {
          if (imageLoader.isDestroyed()) {
            return;
          }

          const imageAndMipLevels = getImageAndMipLevels(image);

          // Unload everything except the image
          imageLoader.unload();

          imageLoader._image = imageAndMipLevels.image;
          imageLoader._mipLevels = imageAndMipLevels.mipLevels;
          imageLoader._state = ResourceLoaderState$1.READY;
          return imageLoader;
        });
      })
      .catch(function (error) {
        if (imageLoader.isDestroyed()) {
          return;
        }
        return handleError$6(imageLoader, error, "Failed to load embedded image");
      });
  }

  function loadFromUri$1(imageLoader) {
    const baseResource = imageLoader._baseResource;
    const uri = imageLoader._uri;
    const resource = baseResource.getDerivedResource({
      url: uri,
    });
    imageLoader._state = ResourceLoaderState$1.LOADING;
    return loadImageFromUri(resource)
      .then(function (image) {
        if (imageLoader.isDestroyed()) {
          return;
        }

        const imageAndMipLevels = getImageAndMipLevels(image);

        // Unload everything except the image
        imageLoader.unload();

        imageLoader._image = imageAndMipLevels.image;
        imageLoader._mipLevels = imageAndMipLevels.mipLevels;
        imageLoader._state = ResourceLoaderState$1.READY;
        return imageLoader;
      })
      .catch(function (error) {
        if (imageLoader.isDestroyed()) {
          return;
        }
        return handleError$6(imageLoader, error, `Failed to load image: ${uri}`);
      });
  }

  function handleError$6(imageLoader, error, errorMessage) {
    imageLoader.unload();
    imageLoader._state = ResourceLoaderState$1.FAILED;
    return Promise.reject(imageLoader.getError(errorMessage, error));
  }

  function getMimeTypeFromTypedArray(typedArray) {
    const header = typedArray.subarray(0, 2);
    const webpHeaderRIFFChars = typedArray.subarray(0, 4);
    const webpHeaderWEBPChars = typedArray.subarray(8, 12);

    if (header[0] === 0xff && header[1] === 0xd8) {
      // See https://en.wikipedia.org/wiki/JPEG_File_Interchange_Format
      return "image/jpeg";
    } else if (header[0] === 0x89 && header[1] === 0x50) {
      // See http://www.libpng.org/pub/png/spec/1.2/PNG-Structure.html
      return "image/png";
    } else if (header[0] === 0xab && header[1] === 0x4b) {
      // See http://github.khronos.org/KTX-Specification/#_identifier
      return "image/ktx2";
    } else if (
      // See https://developers.google.com/speed/webp/docs/riff_container#webp_file_header
      webpHeaderRIFFChars[0] === 0x52 &&
      webpHeaderRIFFChars[1] === 0x49 &&
      webpHeaderRIFFChars[2] === 0x46 &&
      webpHeaderRIFFChars[3] === 0x46 &&
      webpHeaderWEBPChars[0] === 0x57 &&
      webpHeaderWEBPChars[1] === 0x45 &&
      webpHeaderWEBPChars[2] === 0x42 &&
      webpHeaderWEBPChars[3] === 0x50
    ) {
      return "image/webp";
    }

    throw new RuntimeError("Image format is not recognized");
  }

  function loadImageFromBufferTypedArray(typedArray) {
    const mimeType = getMimeTypeFromTypedArray(typedArray);
    if (mimeType === "image/ktx2") {
      // Need to make a copy of the embedded KTX2 buffer otherwise the underlying
      // ArrayBuffer may be accessed on both the worker and the main thread and
      // throw an error like "Cannot perform Construct on a detached ArrayBuffer".
      // Look into SharedArrayBuffer at some point to get around this.
      const ktxBuffer = new Uint8Array(typedArray);

      // Resolves to a CompressedTextureBuffer
      return loadKTX2(ktxBuffer);
    }
    // Resolves to an Image or ImageBitmap
    return GltfImageLoader._loadImageFromTypedArray({
      uint8Array: typedArray,
      format: mimeType,
      flipY: false,
      skipColorSpaceConversion: true,
    });
  }

  const ktx2Regex$1 = /(^data:image\/ktx2)|(\.ktx2$)/i;

  function loadImageFromUri(resource) {
    const uri = resource.url;
    if (ktx2Regex$1.test(uri)) {
      // Resolves to a CompressedTextureBuffer
      return loadKTX2(resource);
    }
    // Resolves to an ImageBitmap or Image
    return resource.fetchImage({
      skipColorSpaceConversion: true,
      preferImageBitmap: true,
    });
  }

  /**
   * Unloads the resource.
   * @private
   */
  GltfImageLoader.prototype.unload = function () {
    if (defined(this._bufferViewLoader)) {
      this._resourceCache.unload(this._bufferViewLoader);
    }

    this._bufferViewLoader = undefined;
    this._uri = undefined; // Free in case the uri is a data uri
    this._image = undefined;
    this._mipLevels = undefined;
    this._gltf = undefined;
  };

  // Exposed for testing
  GltfImageLoader._loadImageFromTypedArray = loadImageFromTypedArray;

  /**
   * Loads an index buffer from a glTF accessor.
   * <p>
   * Implements the {@link ResourceLoader} interface.
   * </p>
   *
   * @alias GltfIndexBufferLoader
   * @constructor
   * @augments ResourceLoader
   *
   * @param {Object} options Object with the following properties:
   * @param {ResourceCache} options.resourceCache The {@link ResourceCache} (to avoid circular dependencies).
   * @param {Object} options.gltf The glTF JSON.
   * @param {Number} options.accessorId The accessor ID corresponding to the index buffer.
   * @param {Resource} options.gltfResource The {@link Resource} containing the glTF.
   * @param {Resource} options.baseResource The {@link Resource} that paths in the glTF JSON are relative to.
   * @param {Object} [options.draco] The Draco extension object.
   * @param {String} [options.cacheKey] The cache key of the resource.
   * @param {Boolean} [options.asynchronous=true] Determines if WebGL resource creation will be spread out over several frames or block until all WebGL resources are created.
   * @param {Boolean} [options.loadBuffer=false] Load the index buffer as a GPU index buffer.
   * @param {Boolean} [options.loadTypedArray=false] Load the index buffer as a typed array.
   * @private
   */
  function GltfIndexBufferLoader(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const resourceCache = options.resourceCache;
    const gltf = options.gltf;
    const accessorId = options.accessorId;
    const gltfResource = options.gltfResource;
    const baseResource = options.baseResource;
    const draco = options.draco;
    const cacheKey = options.cacheKey;
    const asynchronous = defaultValue(options.asynchronous, true);
    const loadBuffer = defaultValue(options.loadBuffer, false);
    const loadTypedArray = defaultValue(options.loadTypedArray, false);

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.func("options.resourceCache", resourceCache);
    Check.typeOf.object("options.gltf", gltf);
    Check.typeOf.number("options.accessorId", accessorId);
    Check.typeOf.object("options.gltfResource", gltfResource);
    Check.typeOf.object("options.baseResource", baseResource);
    if (!loadBuffer && !loadTypedArray) {
      throw new DeveloperError(
        "At least one of loadBuffer and loadTypedArray must be true."
      );
    }
    //>>includeEnd('debug');

    const indexDatatype = gltf.accessors[accessorId].componentType;

    this._resourceCache = resourceCache;
    this._gltfResource = gltfResource;
    this._baseResource = baseResource;
    this._gltf = gltf;
    this._accessorId = accessorId;
    this._indexDatatype = indexDatatype;
    this._draco = draco;
    this._cacheKey = cacheKey;
    this._asynchronous = asynchronous;
    this._loadBuffer = loadBuffer;
    this._loadTypedArray = loadTypedArray;
    this._bufferViewLoader = undefined;
    this._dracoLoader = undefined;
    this._typedArray = undefined;
    this._buffer = undefined;
    this._state = ResourceLoaderState$1.UNLOADED;
    this._promise = undefined;
    this._process = function (loader, frameState) {};
  }

  if (defined(Object.create)) {
    GltfIndexBufferLoader.prototype = Object.create(ResourceLoader.prototype);
    GltfIndexBufferLoader.prototype.constructor = GltfIndexBufferLoader;
  }

  Object.defineProperties(GltfIndexBufferLoader.prototype, {
    /**
     * A promise that resolves to the resource when the resource is ready, or undefined if the resource has not yet started loading.
     *
     * @memberof GltfIndexBufferLoader.prototype
     *
     * @type {Promise.<GltfIndexBufferLoader>|undefined}
     * @readonly
     * @private
     */
    promise: {
      get: function () {
        return this._promise;
      },
    },
    /**
     * The cache key of the resource.
     *
     * @memberof GltfIndexBufferLoader.prototype
     *
     * @type {String}
     * @readonly
     * @private
     */
    cacheKey: {
      get: function () {
        return this._cacheKey;
      },
    },
    /**
     * The index buffer. This is only defined when <code>loadBuffer</code> is true.
     *
     * @memberof GltfIndexBufferLoader.prototype
     *
     * @type {Buffer}
     * @readonly
     * @private
     */
    buffer: {
      get: function () {
        return this._buffer;
      },
    },
    /**
     * The typed array containing indices. This is only defined when <code>loadTypedArray</code> is true.
     *
     * @memberof GltfIndexBufferLoader.prototype
     *
     * @type {Uint8Array|Uint16Array|Uint32Array}
     * @readonly
     * @private
     */
    typedArray: {
      get: function () {
        return this._typedArray;
      },
    },

    /**
     * The index datatype after decode.
     *
     * @memberof GltfIndexBufferLoader.prototype
     *
     * @type {IndexDatatype}
     * @readonly
     * @private
     */
    indexDatatype: {
      get: function () {
        return this._indexDatatype;
      },
    },
  });

  const scratchIndexBufferJob = new CreateIndexBufferJob();

  /**
   * Loads the resource.
   * @returns {Promise.<GltfIndexBufferLoader>} A promise which resolves to the loader when the resource loading is completed.
   * @private
   */
  GltfIndexBufferLoader.prototype.load = function () {
    let promise;

    if (defined(this._draco)) {
      promise = loadFromDraco$1(this);
    } else {
      promise = loadFromBufferView$1(this);
    }

    const that = this;
    const processPromise = new Promise(function (resolve) {
      that._process = function (loader, frameState) {
        if (loader._state === ResourceLoaderState$1.READY) {
          return;
        }

        const typedArray = loader._typedArray;
        const indexDatatype = loader._indexDatatype;

        if (defined(loader._dracoLoader)) {
          loader._dracoLoader.process(frameState);
        }

        if (defined(loader._bufferViewLoader)) {
          loader._bufferViewLoader.process(frameState);
        }

        if (!defined(typedArray)) {
          // Buffer view hasn't been loaded yet
          return;
        }

        let buffer;
        if (loader._loadBuffer && loader._asynchronous) {
          const indexBufferJob = scratchIndexBufferJob;
          indexBufferJob.set(typedArray, indexDatatype, frameState.context);
          const jobScheduler = frameState.jobScheduler;
          if (!jobScheduler.execute(indexBufferJob, JobType$1.BUFFER)) {
            // Job scheduler is full. Try again next frame.
            return;
          }
          buffer = indexBufferJob.buffer;
        } else if (loader._loadBuffer) {
          buffer = createIndexBuffer(
            typedArray,
            indexDatatype,
            frameState.context
          );
        }

        // Unload everything except the index buffer and/or typed array.
        loader.unload();

        loader._buffer = buffer;
        loader._typedArray = loader._loadTypedArray ? typedArray : undefined;
        loader._state = ResourceLoaderState$1.READY;
        resolve(loader);
      };
    });

    this._promise = promise
      .then(function () {
        if (that.isDestroyed()) {
          return;
        }

        return processPromise;
      })
      .catch(function (error) {
        if (that.isDestroyed()) {
          return;
        }

        return handleError$5(that, error);
      });

    return this._promise;
  };

  function loadFromDraco$1(indexBufferLoader) {
    const resourceCache = indexBufferLoader._resourceCache;
    const dracoLoader = resourceCache.loadDraco({
      gltf: indexBufferLoader._gltf,
      draco: indexBufferLoader._draco,
      gltfResource: indexBufferLoader._gltfResource,
      baseResource: indexBufferLoader._baseResource,
    });

    indexBufferLoader._dracoLoader = dracoLoader;
    indexBufferLoader._state = ResourceLoaderState$1.LOADING;

    return dracoLoader.promise.then(function () {
      if (indexBufferLoader.isDestroyed()) {
        return;
      }
      // Now wait for process() to run to finish loading
      const typedArray = dracoLoader.decodedData.indices.typedArray;
      indexBufferLoader._typedArray = typedArray;
      // The index datatype may be a smaller datatype after draco decode
      indexBufferLoader._indexDatatype = ComponentDatatype$1.fromTypedArray(
        typedArray
      );
      indexBufferLoader._state = ResourceLoaderState$1.PROCESSING;
      return indexBufferLoader;
    });
  }

  function loadFromBufferView$1(indexBufferLoader) {
    const gltf = indexBufferLoader._gltf;
    const accessorId = indexBufferLoader._accessorId;
    const accessor = gltf.accessors[accessorId];
    const bufferViewId = accessor.bufferView;

    const resourceCache = indexBufferLoader._resourceCache;
    const bufferViewLoader = resourceCache.loadBufferView({
      gltf: gltf,
      bufferViewId: bufferViewId,
      gltfResource: indexBufferLoader._gltfResource,
      baseResource: indexBufferLoader._baseResource,
    });
    indexBufferLoader._state = ResourceLoaderState$1.LOADING;
    indexBufferLoader._bufferViewLoader = bufferViewLoader;

    return bufferViewLoader.promise.then(function () {
      if (indexBufferLoader.isDestroyed()) {
        return;
      }

      // Now wait for process() to run to finish loading
      const bufferViewTypedArray = bufferViewLoader.typedArray;
      indexBufferLoader._typedArray = createIndicesTypedArray(
        indexBufferLoader,
        bufferViewTypedArray
      );
      indexBufferLoader._state = ResourceLoaderState$1.PROCESSING;
      return indexBufferLoader;
    });
  }

  function createIndicesTypedArray(indexBufferLoader, bufferViewTypedArray) {
    const gltf = indexBufferLoader._gltf;
    const accessorId = indexBufferLoader._accessorId;
    const accessor = gltf.accessors[accessorId];
    const count = accessor.count;
    const indexDatatype = accessor.componentType;

    const arrayBuffer = bufferViewTypedArray.buffer;
    const byteOffset = bufferViewTypedArray.byteOffset + accessor.byteOffset;

    let typedArray;
    if (indexDatatype === IndexDatatype$1.UNSIGNED_BYTE) {
      typedArray = new Uint8Array(arrayBuffer, byteOffset, count);
    } else if (indexDatatype === IndexDatatype$1.UNSIGNED_SHORT) {
      typedArray = new Uint16Array(arrayBuffer, byteOffset, count);
    } else if (indexDatatype === IndexDatatype$1.UNSIGNED_INT) {
      typedArray = new Uint32Array(arrayBuffer, byteOffset, count);
    }

    return typedArray;
  }

  function handleError$5(indexBufferLoader, error) {
    indexBufferLoader.unload();
    indexBufferLoader._state = ResourceLoaderState$1.FAILED;
    const errorMessage = "Failed to load index buffer";
    error = indexBufferLoader.getError(errorMessage, error);
    return Promise.reject(error);
  }

  function CreateIndexBufferJob() {
    this.typedArray = undefined;
    this.indexDatatype = undefined;
    this.context = undefined;
    this.buffer = undefined;
  }

  CreateIndexBufferJob.prototype.set = function (
    typedArray,
    indexDatatype,
    context
  ) {
    this.typedArray = typedArray;
    this.indexDatatype = indexDatatype;
    this.context = context;
  };

  CreateIndexBufferJob.prototype.execute = function () {
    this.buffer = createIndexBuffer(
      this.typedArray,
      this.indexDatatype,
      this.context
    );
  };

  function createIndexBuffer(typedArray, indexDatatype, context) {
    const buffer = Buffer$1.createIndexBuffer({
      typedArray: typedArray,
      context: context,
      usage: BufferUsage$1.STATIC_DRAW,
      indexDatatype: indexDatatype,
    });
    buffer.vertexArrayDestroyable = false;
    return buffer;
  }

  /**
   * Processes the resource until it becomes ready.
   *
   * @param {FrameState} frameState The frame state.
   * @private
   */
  GltfIndexBufferLoader.prototype.process = function (frameState) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("frameState", frameState);
    //>>includeEnd('debug');

    return this._process(this, frameState);
  };

  /**
   * Unloads the resource.
   * @private
   */
  GltfIndexBufferLoader.prototype.unload = function () {
    if (defined(this._buffer)) {
      this._buffer.destroy();
    }

    const resourceCache = this._resourceCache;

    if (defined(this._bufferViewLoader)) {
      resourceCache.unload(this._bufferViewLoader);
    }

    if (defined(this._dracoLoader)) {
      resourceCache.unload(this._dracoLoader);
    }

    this._bufferViewLoader = undefined;
    this._dracoLoader = undefined;
    this._typedArray = undefined;
    this._buffer = undefined;
    this._gltf = undefined;
  };

  /**
   * Iterate through the objects within the glTF and delete their pipeline extras object.
   *
   * @param {Object} gltf A javascript object containing a glTF asset.
   * @returns {Object} glTF with no pipeline extras.
   *
   * @private
   */
  function removePipelineExtras(gltf) {
    ForEach.shader(gltf, function (shader) {
      removeExtras(shader);
    });
    ForEach.buffer(gltf, function (buffer) {
      removeExtras(buffer);
    });
    ForEach.image(gltf, function (image) {
      removeExtras(image);
    });

    removeExtras(gltf);

    return gltf;
  }

  function removeExtras(object) {
    if (!defined(object.extras)) {
      return;
    }

    if (defined(object.extras._pipeline)) {
      delete object.extras._pipeline;
    }

    if (Object.keys(object.extras).length === 0) {
      delete object.extras;
    }
  }

  /**
   * Loads a glTF JSON from a glTF or glb.
   * <p>
   * Implements the {@link ResourceLoader} interface.
   * </p>
   *
   * @alias GltfJsonLoader
   * @constructor
   * @augments ResourceLoader
   *
   * @param {Object} options Object with the following properties:
   * @param {ResourceCache} options.resourceCache The {@link ResourceCache} (to avoid circular dependencies).
   * @param {Resource} options.gltfResource The {@link Resource} containing the glTF.
   * @param {Resource} options.baseResource The {@link Resource} that paths in the glTF JSON are relative to.
   * @param {Uint8Array} [options.typedArray] The typed array containing the glTF contents.
   * @param {Object} [options.gltfJson] The parsed glTF JSON contents.
   * @param {String} [options.cacheKey] The cache key of the resource.
   *
   * @private
   */
  function GltfJsonLoader(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const resourceCache = options.resourceCache;
    const gltfResource = options.gltfResource;
    const baseResource = options.baseResource;
    const typedArray = options.typedArray;
    const gltfJson = options.gltfJson;
    const cacheKey = options.cacheKey;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.func("options.resourceCache", resourceCache);
    Check.typeOf.object("options.gltfResource", gltfResource);
    Check.typeOf.object("options.baseResource", baseResource);
    //>>includeEnd('debug');

    this._resourceCache = resourceCache;
    this._gltfResource = gltfResource;
    this._baseResource = baseResource;
    this._typedArray = typedArray;
    this._gltfJson = gltfJson;
    this._cacheKey = cacheKey;
    this._gltf = undefined;
    this._bufferLoaders = [];
    this._state = ResourceLoaderState$1.UNLOADED;
    this._promise = undefined;
  }

  if (defined(Object.create)) {
    GltfJsonLoader.prototype = Object.create(ResourceLoader.prototype);
    GltfJsonLoader.prototype.constructor = GltfJsonLoader;
  }

  Object.defineProperties(GltfJsonLoader.prototype, {
    /**
     * A promise that resolves to the resource when the resource is ready, or undefined if the resource hasn't started loading.
     *
     * @memberof GltfJsonLoader.prototype
     *
     * @type {Promise.<GltfJsonLoader>|undefined}
     * @readonly
     * @private
     */
    promise: {
      get: function () {
        return this._promise;
      },
    },
    /**
     * The cache key of the resource.
     *
     * @memberof GltfJsonLoader.prototype
     *
     * @type {String}
     * @readonly
     * @private
     */
    cacheKey: {
      get: function () {
        return this._cacheKey;
      },
    },
    /**
     * The glTF JSON.
     *
     * @memberof GltfJsonLoader.prototype
     *
     * @type {Object}
     * @readonly
     * @private
     */
    gltf: {
      get: function () {
        return this._gltf;
      },
    },
  });

  /**
   * Loads the resource.
   * @returns {Promise.<GltfJsonLoader>} A promise which resolves to the loader when the resource loading is completed.
   * @private
   */
  GltfJsonLoader.prototype.load = function () {
    this._state = ResourceLoaderState$1.LOADING;

    let processPromise;
    if (defined(this._gltfJson)) {
      processPromise = processGltfJson(this, this._gltfJson);
    } else if (defined(this._typedArray)) {
      processPromise = processGltfTypedArray(this, this._typedArray);
    } else {
      processPromise = loadFromUri(this);
    }

    const that = this;
    this._promise = processPromise
      .then(function (gltf) {
        if (that.isDestroyed()) {
          return;
        }
        that._gltf = gltf;
        that._state = ResourceLoaderState$1.READY;
        return that;
      })
      .catch(function (error) {
        if (that.isDestroyed()) {
          return;
        }
        return handleError$4(that, error);
      });

    return this._promise;
  };

  function loadFromUri(gltfJsonLoader) {
    return gltfJsonLoader._fetchGltf().then(function (arrayBuffer) {
      if (gltfJsonLoader.isDestroyed()) {
        return;
      }
      const typedArray = new Uint8Array(arrayBuffer);
      return processGltfTypedArray(gltfJsonLoader, typedArray);
    });
  }

  function handleError$4(gltfJsonLoader, error) {
    gltfJsonLoader.unload();
    gltfJsonLoader._state = ResourceLoaderState$1.FAILED;
    const errorMessage = `Failed to load glTF: ${gltfJsonLoader._gltfResource.url}`;
    return Promise.reject(gltfJsonLoader.getError(errorMessage, error));
  }

  function upgradeVersion(gltfJsonLoader, gltf) {
    if (gltf.asset.version === "2.0") {
      return Promise.resolve();
    }

    // Load all buffers into memory. updateVersion will read and in some cases modify
    // the buffer data, which it accesses from buffer.extras._pipeline.source
    const promises = [];
    ForEach.buffer(gltf, function (buffer) {
      if (
        !defined(buffer.extras._pipeline.source) && // Ignore uri if this buffer uses the glTF 1.0 KHR_binary_glTF extension
        defined(buffer.uri)
      ) {
        const resource = gltfJsonLoader._baseResource.getDerivedResource({
          url: buffer.uri,
        });
        const resourceCache = gltfJsonLoader._resourceCache;
        const bufferLoader = resourceCache.loadExternalBuffer({
          resource: resource,
        });

        gltfJsonLoader._bufferLoaders.push(bufferLoader);

        promises.push(
          bufferLoader.promise.then(function (bufferLoader) {
            buffer.extras._pipeline.source = bufferLoader.typedArray;
          })
        );
      }
    });

    return Promise.all(promises).then(function () {
      updateVersion(gltf);
    });
  }

  function decodeDataUris(gltf) {
    const promises = [];
    ForEach.buffer(gltf, function (buffer) {
      const bufferUri = buffer.uri;
      if (
        !defined(buffer.extras._pipeline.source) && // Ignore uri if this buffer uses the glTF 1.0 KHR_binary_glTF extension
        defined(bufferUri) &&
        isDataUri(bufferUri)
      ) {
        delete buffer.uri; // Delete the data URI to keep the cached glTF JSON small
        promises.push(
          Resource.fetchArrayBuffer(bufferUri).then(function (arrayBuffer) {
            buffer.extras._pipeline.source = new Uint8Array(arrayBuffer);
          })
        );
      }
    });
    return Promise.all(promises);
  }

  function loadEmbeddedBuffers(gltfJsonLoader, gltf) {
    const promises = [];
    ForEach.buffer(gltf, function (buffer, bufferId) {
      const source = buffer.extras._pipeline.source;
      if (defined(source) && !defined(buffer.uri)) {
        const resourceCache = gltfJsonLoader._resourceCache;
        const bufferLoader = resourceCache.loadEmbeddedBuffer({
          parentResource: gltfJsonLoader._gltfResource,
          bufferId: bufferId,
          typedArray: source,
        });

        gltfJsonLoader._bufferLoaders.push(bufferLoader);
        promises.push(bufferLoader.promise);
      }
    });
    return Promise.all(promises);
  }

  function processGltfJson(gltfJsonLoader, gltf) {
    addPipelineExtras(gltf);

    return decodeDataUris(gltf)
      .then(function () {
        return upgradeVersion(gltfJsonLoader, gltf);
      })
      .then(function () {
        addDefaults(gltf);
        return loadEmbeddedBuffers(gltfJsonLoader, gltf);
      })
      .then(function () {
        removePipelineExtras(gltf);
        return gltf;
      });
  }

  function processGltfTypedArray(gltfJsonLoader, typedArray) {
    let gltf;
    if (getMagic(typedArray) === "glTF") {
      gltf = parseGlb(typedArray);
    } else {
      gltf = getJsonFromTypedArray(typedArray);
    }

    return processGltfJson(gltfJsonLoader, gltf);
  }

  /**
   * Unloads the resource.
   * @private
   */
  GltfJsonLoader.prototype.unload = function () {
    const bufferLoaders = this._bufferLoaders;
    const bufferLoadersLength = bufferLoaders.length;
    for (let i = 0; i < bufferLoadersLength; ++i) {
      this._resourceCache.unload(bufferLoaders[i]);
    }
    this._bufferLoaders.length = 0;

    this._gltf = undefined;
  };

  /**
   * Exposed for testing
   *
   * @private
   */
  GltfJsonLoader.prototype._fetchGltf = function () {
    return this._gltfResource.fetchArrayBuffer();
  };

  /**
   * The alpha rendering mode of the material.
   *
   * @enum {String}
   * @private
   */
  const AlphaMode = {
    /**
     * The alpha value is ignored and the rendered output is fully opaque.
     *
     * @type {String}
     * @constant
     */
    OPAQUE: "OPAQUE",

    /**
     * The rendered output is either fully opaque or fully transparent depending on the alpha value and the specified alpha cutoff value.
     *
     * @type {String}
     * @constant
     */
    MASK: "MASK",

    /**
     * The rendered output is composited onto the destination with alpha blending.
     *
     * @type {String}
     * @constant
     */
    BLEND: "BLEND",
  };

  var AlphaMode$1 = Object.freeze(AlphaMode);

  /**
   * Components for building models.
   *
   * @namespace ModelComponents
   *
   * @private
   */
  const ModelComponents = {};

  /**
   * Information about the quantized attribute.
   *
   * @alias ModelComponents.Quantization
   * @constructor
   *
   * @private
   */
  function Quantization$1() {
    /**
     * Whether the quantized attribute is oct-encoded.
     *
     * @type {Boolean}
     * @private
     */
    this.octEncoded = false;

    /**
     * Whether the oct-encoded values are stored as ZXY instead of XYZ. This is true when decoding from Draco.
     *
     * @type {Boolean}
     */
    this.octEncodedZXY = false;

    /**
     * The range used to convert buffer values to normalized values [0.0, 1.0]
     * This is typically computed as (1 << quantizationBits) - 1.
     * For oct-encoded values this value is a single Number.
     *
     * @type {Number|Cartesian2|Cartesian3|Cartesian4|Matrix2|Matrix3|Matrix4}
     * @private
     */
    this.normalizationRange = undefined;

    /**
     * The bottom-left corner of the quantization volume. Not applicable for oct encoded attributes.
     * The type should match the attribute type - e.g. if the attribute type
     * is AttributeType.VEC4 the offset should be a Cartesian4.
     *
     * @type {Number|Cartesian2|Cartesian3|Cartesian4|Matrix2|Matrix3|Matrix4}
     * @private
     */
    this.quantizedVolumeOffset = undefined;

    /**
     * The dimensions of the quantization volume. Not applicable for oct encoded attributes.
     * The type should match the attribute type - e.g. if the attribute type
     * is AttributeType.VEC4 the dimensions should be a Cartesian4.
     *
     * @type {Number|Cartesian2|Cartesian3|Cartesian4|Matrix2|Matrix3|Matrix4}
     * @private
     */
    this.quantizedVolumeDimensions = undefined;

    /**
     * The step size of the quantization volume, equal to
     * quantizedVolumeDimensions / normalizationRange (component-wise).
     * Not applicable for oct encoded attributes.
     * The type should match the attribute type - e.g. if the attribute type
     * is AttributeType.VEC4 the dimensions should be a Cartesian4.
     *
     * @type {Number|Cartesian2|Cartesian3|Cartesian4|Matrix2|Matrix3|Matrix4}
     * @private
     */
    this.quantizedVolumeStepSize = undefined;

    /**
     * The component data type of the quantized attribute, e.g. ComponentDatatype.UNSIGNED_SHORT.
     *
     * <p>
     * The following component datatypes are not supported:
     * <ul>
     *   <li>ComponentDatatype.INT</li>
     *   <li>ComponentDatatype.UNSIGNED_INT</li>
     *   <li>ComponentDatatype.DOUBLE</li>
     * </ul>
     * </p>
     *
     * @type {ComponentDatatype}
     * @private
     */
    this.componentDatatype = undefined;

    /**
     * The type of the quantized attribute, e.g. AttributeType.VEC2 for oct-encoded normals.
     *
     * @type {AttributeType}
     * @private
     */
    this.type = undefined;
  }

  /**
   * A per-vertex or per-instance attribute.
   *
   * @alias ModelComponents.Attribute
   * @constructor
   *
   * @private
   */
  function Attribute$3() {
    /**
     * The attribute name. Must be unique within the attributes array.
     *
     * @type {String}
     * @private
     */
    this.name = undefined;

    /**
     * The attribute semantic. The combination of semantic and setIndex must be
     * unique within the attributes array.
     *
     * @type {VertexAttributeSemantic|InstanceAttributeSemantic}
     * @private
     */
    this.semantic = undefined;

    /**
     * The set index of the attribute. Only applicable when the attribute has one
     * of the following semantics:
     *
     * <ul>
     *   <li>{@link VertexAttributeSemantic.TEXCOORD}</li>
     *   <li>{@link VertexAttributeSemantic.COLOR}</li>
     *   <li>{@link VertexAttributeSemantic.JOINTS}</li>
     *   <li>{@link VertexAttributeSemantic.WEIGHTS}</li>
     *   <li>{@link VertexAttributeSemantic.FEATURE_ID}</li>
     *   <li>{@link InstanceAttributeSemantic.FEATURE_ID}</li>
     * </ul>
     */
    this.setIndex = undefined;

    /**
     * The component data type of the attribute.
     * <p>
     * When the data is quantized the componentDatatype should match the
     * dequantized data, which is typically ComponentDatatype.FLOAT.
     * </p>
     * <p>
     * The following component datatypes are not supported:
     * <ul>
     *   <li>ComponentDatatype.INT</li>
     *   <li>ComponentDatatype.UNSIGNED_INT</li>
     *   <li>ComponentDatatype.DOUBLE</li>
     * </ul>
     * </p>
     *
     * @type {ComponentDatatype}
     * @private
     */
    this.componentDatatype = undefined;

    /**
     * The type of the attribute.
     * <p>
     * When the data is oct-encoded the type should match the decoded data, which
     * is typically AttributeType.VEC3.
     * </p>
     *
     * @type {AttributeType}
     * @private
     */
    this.type = undefined;

    /**
     * Whether the attribute is normalized.
     *
     * @type {Boolean}
     * @default false
     * @private
     */
    this.normalized = false;

    /**
     * The number of elements.
     *
     * @type {Number}
     * @private
     */
    this.count = undefined;

    /**
     * Minimum value of each component in the attribute.
     * <p>
     * When the data is quantized the min should match the dequantized data.
     * The normalized property has no effect on these values.
     * </p>
     * <p>
     * Must be defined for POSITION attributes.
     * </p>
     *
     * @type {Number|Cartesian2|Cartesian3|Cartesian4|Matrix2|Matrix3|Matrix4}
     * @private
     */
    this.min = undefined;

    /**
     * Maximum value of each component in the attribute.
     * <p>
     * When the data is quantized the max should match the dequantized data.
     * The normalized property has no effect on these values.
     * </p>
     * <p>
     * Must be defined for POSITION attributes.
     * </p>
     *
     * @type {Number|Cartesian2|Cartesian3|Cartesian4|Matrix2|Matrix3|Matrix4}
     * @private
     */
    this.max = undefined;

    /**
     * A constant value used for all elements when typed array and buffer are undefined.
     *
     * @type {Number|Cartesian2|Cartesian3|Cartesian4|Matrix2|Matrix3|Matrix4}
     * @private
     */
    this.constant = undefined;

    /**
     * Information about the quantized attribute.
     *
     * @type {ModelComponents.Quantization}
     * @private
     */
    this.quantization = undefined;

    /**
     * A typed array containing tightly-packed attribute values, as they appear
     * in the model file.
     *
     * @type {Uint8Array|Int8Array|Uint16Array|Int16Array|Uint32Array|Int32Array|Float32Array}
     * @private
     */
    this.packedTypedArray = undefined;

    /**
     * A vertex buffer. Attribute values are accessed using byteOffset and byteStride.
     *
     * @type {Buffer}
     * @private
     */
    this.buffer = undefined;

    /**
     * A typed array containing a CPU copy of the vertex buffer for further
     * processing. Since GPU buffers may have padding, attribute values are
     * accessed using byteOffset and byteStride.
     *
     * @type {Uint8Array}
     * @private
     */
    this.typedArray = undefined;

    /**
     * The byte offset of elements in the buffer.
     *
     * @type {Number}
     * @default 0
     * @private
     */
    this.byteOffset = 0;

    /**
     * The byte stride of elements in the buffer. When undefined the elements are tightly packed.
     *
     * @type {Number}
     * @private
     */
    this.byteStride = undefined;
  }

  /**
   * Indices used to select vertices for rendering.
   *
   * @alias ModelComponents.Indices
   * @constructor
   *
   * @private
   */
  function Indices$1() {
    /**
     * The index data type of the attribute, e.g. IndexDatatype.UNSIGNED_SHORT.
     *
     * @type {IndexDatatype}
     * @private
     */
    this.indexDatatype = undefined;

    /**
     * The number of indices.
     *
     * @type {Number}
     * @private
     */
    this.count = undefined;

    /**
     * An index buffer containing indices.
     *
     * @type {Buffer}
     * @private
     */
    this.buffer = undefined;

    /**
     * A typed array containing indices.
     *
     * @type {Uint8Array|Uint16Array|Uint32Array}
     * @private
     */
    this.typedArray = undefined;
  }

  /**
   * Maps per-vertex or per-instance feature IDs to a property table. Feature
   * IDs are stored in an accessor.
   *
   * @alias ModelComponents.FeatureIdAttribute
   * @constructor
   *
   * @private
   */
  function FeatureIdAttribute$4() {
    /**
     * How many unique features are defined in this set of feature IDs
     *
     * @type {Number}
     * @private
     */
    this.featureCount = undefined;

    /**
     * This value indicates that no feature is indicated with this vertex
     *
     * @type {Number}
     * @private
     */
    this.nullFeatureId = undefined;

    /**
     * The ID of the property table that feature IDs index into. If undefined,
     * feature IDs are used for classification, but no metadata is associated.
     *
     *
     * @type {Number}
     * @private
     */
    this.propertyTableId = undefined;

    /**
     * The set index of feature ID attribute containing feature IDs.
     *
     * @type {Number}
     * @private
     */
    this.setIndex = undefined;

    /**
     * The label to identify this set of feature IDs. This is used in picking,
     * styling and shaders.
     *
     * @type {String}
     * @private
     */
    this.label = undefined;

    /**
     * Label to identify this set of feature IDs by its position in the array.
     * This will always be either "featureId_N" for primitives or
     * "instanceFeatureId_N" for instances.
     *
     * @type {String}
     * @private
     */
    this.positionalLabel = undefined;
  }

  /**
   * Defines a range of implicitly-defined feature IDs, one for each vertex or
   * instance. Such feature IDs may optionally be associated with a property table
   * storing metadata
   *
   * @alias ModelComponents.FeatureIdImplicitRange
   * @constructor
   *
   * @private
   */
  function FeatureIdImplicitRange$1() {
    /**
     * How many unique features are defined in this set of feature IDs
     *
     * @type {Number}
     * @private
     */
    this.featureCount = undefined;

    /**
     * This value indicates that no feature is indicated with this vertex
     *
     * @type {Number}
     * @private
     */
    this.nullFeatureId = undefined;

    /**
     * The ID of the property table that feature IDs index into. If undefined,
     * feature IDs are used for classification, but no metadata is associated.
     *
     * @type {Number}
     * @private
     */
    this.propertyTableId = undefined;

    /**
     * The first feature ID to use when setIndex is undefined
     *
     * @type {Number}
     * @default 0
     * @private
     */
    this.offset = 0;

    /**
     * Number of times each feature ID is repeated before being incremented.
     *
     * @type {Number}
     * @private
     */
    this.repeat = undefined;

    /**
     * The label to identify this set of feature IDs. This is used in picking,
     * styling and shaders.
     *
     * @type {String}
     * @private
     */
    this.label = undefined;

    /**
     * Label to identify this set of feature IDs by its position in the array.
     * This will always be either "featureId_N" for primitives or
     * "instanceFeatureId_N" for instances.
     *
     * @type {String}
     * @private
     */
    this.positionalLabel = undefined;
  }

  /**
   * A texture that contains per-texel feature IDs that index into a property table.
   *
   * @alias ModelComponents.FeatureIdTexture
   * @constructor
   *
   * @private
   */
  function FeatureIdTexture$1() {
    /**
     * How many unique features are defined in this set of feature IDs
     *
     * @type {Number}
     * @private
     */
    this.featureCount = undefined;

    /**
     * This value indicates that no feature is indicated with this texel
     *
     * @type {Number}
     * @private
     */
    this.nullFeatureId = undefined;

    /**
     * The ID of the property table that feature IDs index into. If undefined,
     * feature IDs are used for classification, but no metadata is associated.
     *
     * @type {String}
     * @private
     */
    this.propertyTableId = undefined;

    /**
     * The texture reader containing feature IDs.
     *
     * @type {ModelComponents.TextureReader}
     * @private
     */
    this.textureReader = undefined;

    /**
     * The label to identify this set of feature IDs. This is used in picking,
     * styling and shaders.
     *
     * @type {String}
     * @private
     */
    this.label = undefined;

    /**
     * Label to identify this set of feature IDs by its position in the array.
     * This will always be either "featureId_N" for primitives or
     * "instanceFeatureId_N" for instances.
     *
     * @type {String}
     * @private
     */
    this.positionalLabel = undefined;
  }

  /**
   * A morph target where each attribute contains attribute displacement data.
   *
   * @alias ModelComponents.MorphTarget
   * @constructor
   *
   * @private
   */
  function MorphTarget$1() {
    /**
     * Attributes that are part of the morph target, e.g. positions, normals, and tangents.
     *
     * @type {ModelComponents.Attribute[]}
     * @private
     */
    this.attributes = [];
  }

  /**
   * Geometry to be rendered with a material.
   *
   * @alias ModelComponents.Primitive
   * @constructor
   *
   * @private
   */
  function Primitive$2() {
    /**
     * The vertex attributes, e.g. positions, normals, etc.
     *
     * @type {ModelComponents.Attribute[]}
     * @private
     */
    this.attributes = [];

    /**
     * The morph targets.
     *
     * @type {ModelComponents.MorphTarget[]}
     * @private
     */
    this.morphTargets = [];

    /**
     * The indices.
     *
     * @type {ModelComponents.Indices}
     * @private
     */
    this.indices = undefined;

    /**
     * The material.
     *
     * @type {ModelComponents.Material}
     * @private
     */
    this.material = undefined;

    /**
     * The primitive type, e.g. PrimitiveType.TRIANGLES.
     *
     * @type {PrimitiveType}
     * @private
     */
    this.primitiveType = undefined;

    /**
     * The feature IDs associated with this primitive. Feature ID types may
     * be interleaved
     *
     * @type {Array.<ModelComponents.FeatureIdAttribute|ModelComponents.FeatureIdImplicitRange|ModelComponents.FeatureIdTexture>}
     * @private
     */
    this.featureIds = [];

    /**
     * The property texture IDs. These indices correspond to the array of
     * property textures.
     *
     * @type {Number[]}
     * @private
     */
    this.propertyTextureIds = [];

    /**
     * The property attribute IDs. These indices correspond to the array of
     * property attributes in the EXT_structural_metadata extension.
     *
     * @type {Number[]}
     * @private
     */
    this.propertyAttributeIds = [];
  }

  /**
   * Position and metadata information for instances of a node.
   *
   * @alias ModelComponents.Primitive
   * @constructor
   *
   * @private
   */
  function Instances$2() {
    /**
     * The instance attributes, e.g. translation, rotation, scale, feature id, etc.
     *
     * @type {ModelComponents.Attribute[]}
     * @private
     */
    this.attributes = [];

    /**
     * The feature ID attributes associated with this set of instances.
     * Feature ID attribute types may be interleaved.
     *
     * @type {Array.<ModelComponents.FeatureIdAttribute|ModelComponents.FeatureIdImplicitRange>}
     * @private
     */
    this.featureIds = [];

    /**
     * Whether the instancing transforms are applied in world space. For glTF models that
     * use EXT_mesh_gpu_instancing, the transform is applied in object space. For i3dm files,
     * the instance transform is in world space.
     *
     * @type {Boolean}
     * @private
     */
    this.transformInWorldSpace = false;
  }

  /**
   * Joints and matrices defining a skin.
   *
   * @alias ModelComponents.Skin
   * @constructor
   *
   * @private
   */
  function Skin$1() {
    /**
     * The index of the skin in the glTF. This is useful for finding the skin
     * that applies to a node after the skin is instantiated at runtime.
     *
     * @type {Number}
     * @private
     */
    this.index = undefined;

    /**
     * The joints.
     *
     * @type {ModelComponents.Node[]}
     * @private
     */
    this.joints = [];

    /**
     * The inverse bind matrices of the joints.
     *
     * @type {Matrix4[]}
     * @private
     */
    this.inverseBindMatrices = [];
  }

  /**
   * A node in the node hierarchy.
   *
   * @alias ModelComponents.Node
   * @constructor
   *
   * @private
   */
  function Node$3() {
    /**
     * The name of the node.
     *
     * @type {String}
     * @private
     */
    this.name = undefined;

    /**
     * The index of the node in the glTF. This is useful for finding the nodes
     * that belong to a skin after they have been instantiated at runtime.
     *
     * @type {Number}
     * @private
     */
    this.index = undefined;

    /**
     * The children nodes.
     *
     * @type {ModelComponents.Node[]}
     * @private
     */
    this.children = [];

    /**
     * The mesh primitives.
     *
     * @type {ModelComponents.Primitive[]}
     * @private
     */
    this.primitives = [];

    /**
     * Instances of this node.
     *
     * @type {ModelComponents.Instances}
     * @private
     */
    this.instances = undefined;

    /**
     * The skin.
     *
     * @type {ModelComponents.Skin}
     * @private
     */
    this.skin = undefined;

    /**
     * The local transformation matrix. When matrix is defined translation,
     * rotation, and scale must be undefined. When matrix is undefined
     * translation, rotation, and scale must all be defined.
     *
     * @type {Matrix4}
     * @private
     */
    this.matrix = undefined;

    /**
     * The local translation.
     *
     * @type {Cartesian3}
     * @private
     */
    this.translation = undefined;

    /**
     * The local rotation.
     *
     * @type {Quaternion}
     * @private
     */
    this.rotation = undefined;

    /**
     * The local scale.
     *
     * @type {Cartesian3}
     * @private
     */
    this.scale = undefined;

    /**
     * An array of weights to be applied to the primitives' morph targets.
     * These are supplied by either the node or its mesh.
     *
     * @type {Number[]}
     * @private
     */
    this.morphWeights = [];

    /**
     * The name of the articulation affecting this node, as defined by the
     * AGI_articulations extension.
     *
     * @type {String}
     * @private
     */
    this.articulationName = undefined;
  }

  /**
   * A scene containing nodes.
   *
   * @alias ModelComponents.Scene
   * @constructor
   *
   * @private
   */
  function Scene$3() {
    /**
     * The nodes belonging to the scene.
     *
     * @type {ModelComponents.Node[]}
     * @private
     */
    this.nodes = [];
  }

  /**
   * The property of the node that is targeted by an animation. The values of
   * this enum are used to look up the appropriate property on the runtime node.
   *
   * @alias {ModelComponents.AnimatedPropertyType}
   * @enum {String}
   *
   * @private
   */
  const AnimatedPropertyType$2 = {
    TRANSLATION: "translation",
    ROTATION: "rotation",
    SCALE: "scale",
    WEIGHTS: "weights",
  };

  /**
   * An animation sampler that describes the sources of animated keyframe data
   * and their interpolation.
   *
   * @alias {ModelComponents.AnimationSampler}
   * @constructor
   *
   * @private
   */
  function AnimationSampler$1() {
    /**
     * The timesteps of the animation.
     *
     * @type {Number[]}
     * @private
     */
    this.input = [];

    /**
     * The method used to interpolate between the animation's keyframe data.
     *
     * @type {InterpolationType}
     * @private
     */
    this.interpolation = undefined;

    /**
     * The keyframe data of the animation.
     *
     * @type {Number[]|Cartesian3[]|Quaternion[]}
     * @private
     */
    this.output = [];
  }

  /**
   * An animation target, which specifies the node and property to animate.
   *
   * @alias {ModelComponents.AnimationTarget}
   * @constructor
   *
   * @private
   */
  function AnimationTarget$1() {
    /**
     * The node that will be affected by the animation.
     *
     * @type {ModelComponents.Node}
     * @private
     */
    this.node = undefined;

    /**
     * The property of the node to be animated.
     *
     * @type {ModelComponents.AnimatedPropertyType}
     * @private
     */
    this.path = undefined;
  }

  /**
   * An animation channel linking an animation sampler and the target it animates.
   *
   * @alias {ModelComponents.AnimationChannel}
   * @constructor
   *
   * @private
   */
  function AnimationChannel$1() {
    /**
     * The sampler used as the source of the animation data.
     *
     * @type {ModelComponents.AnimationSampler}
     * @private
     */
    this.sampler = undefined;

    /**
     * The target of the animation.
     *
     * @type {ModelComponents.AnimationTarget}
     * @private
     */
    this.target = undefined;
  }

  /**
   * An animation in the model.
   *
   * @alias {ModelComponents.Animation}
   * @constructor
   *
   * @private
   */
  function Animation$2() {
    /**
     * The name of the animation.
     *
     * @type {String}
     * @private
     */
    this.name = undefined;

    /**
     * The samplers used in this animation.
     *
     * @type {ModelComponents.AnimationSampler[]}
     * @private
     */
    this.samplers = [];

    /**
     * The channels used in this animation.
     *
     * @type {ModelComponents.AnimationChannel[]}
     * @private
     */
    this.channels = [];
  }

  /**
   * An articulation stage belonging to an articulation from the
   * AGI_articulations extension.
   *
   * @alias {ModelComponents.ArticulationStage}
   * @constructor
   *
   * @private
   */
  function ArticulationStage$1() {
    /**
     * The name of the articulation stage.
     *
     * @type {String}
     * @private
     */
    this.name = undefined;

    /**
     * The type of the articulation stage, defined by the type of motion it modifies.
     *
     * @type {ArticulationStageType}
     * @private
     */
    this.type = undefined;

    /**
     * The minimum value for the range of motion of this articulation stage.
     *
     * @type {Number}
     * @private
     */
    this.minimumValue = undefined;

    /**
     * The maximum value for the range of motion of this articulation stage.
     *
     * @type {Number}
     * @private
     */
    this.maximumValue = undefined;

    /**
     * The initial value for this articulation stage.
     *
     * @type {Number}
     * @private
     */
    this.initialValue = undefined;
  }

  /**
   * An articulation for the model, as defined by the AGI_articulations extension.
   *
   * @alias {ModelComponents.Articulation}
   * @constructor
   *
   * @private
   */
  function Articulation$1() {
    /**
     * The name of the articulation.
     *
     * @type {String}
     * @private
     */
    this.name = undefined;

    /**
     * The stages belonging to this articulation. The stages are applied to
     * the model in order of appearance.
     *
     * @type {ModelComponents.ArticulationStage[]}
     * @private
     */
    this.stages = [];
  }

  /**
   * The asset of the model.
   *
   * @alias {ModelComponents.Asset}
   * @constructor
   *
   * @private
   */
  function Asset$1() {
    /**
     * The credits of the model.
     *
     * @type {Credit[]}
     * @private
     */
    this.credits = [];
  }

  /**
   * The components that make up a model.
   *
   * @alias ModelComponents.Components
   * @constructor
   *
   * @private
   */
  function Components$2() {
    /**
     * The asset of the model.
     *
     * @type {ModelComponents.Asset}
     * @private
     */
    this.asset = new Asset$1();

    /**
     * The default scene.
     *
     * @type {ModelComponents.Scene}
     * @private
     */
    this.scene = undefined;

    /**
     * All nodes in the model.
     *
     * @type {ModelComponents.Node[]}
     */
    this.nodes = [];

    /**
     * All skins in the model.
     *
     * @type {ModelComponents.Skin[]}
     */
    this.skins = [];

    /**
     * All animations in the model.
     *
     * @type {ModelComponents.Animation[]}
     */
    this.animations = [];

    /**
     * All articulations in the model as defined by the AGI_articulations extension.
     *
     * @type {ModelComponents.Articulation[]}
     */
    this.articulations = [];

    /**
     * Structural metadata containing the schema, property tables, property
     * textures and property mappings
     *
     * @type {StructuralMetadata}
     * @private
     */
    this.structuralMetadata = undefined;

    /**
     * The model's up axis.
     *
     * @type {Axis}
     * @private
     */
    this.upAxis = undefined;

    /**
     * The model's forward axis.
     *
     * @type {Axis}
     * @private
     */
    this.forwardAxis = undefined;

    /**
     * A world-space transform to apply to the primitives.
     *
     * @type {Matrix4}
     * @private
     */
    this.transform = Matrix4.clone(Matrix4.IDENTITY);
  }

  /**
   * Information about a GPU texture, including the texture itself
   *
   * @alias ModelComponents.TextureReader
   * @constructor
   *
   * @private
   */
  function TextureReader() {
    /**
     * The underlying GPU texture. The {@link Texture} contains the sampler.
     *
     * @type {Texture}
     * @private
     */
    this.texture = undefined;

    /**
     * The index of the texture in the glTF. This is useful for determining
     * when textures are shared to avoid attaching a texture in multiple uniform
     * slots in the shader.
     *
     * @type {Number}
     * @private
     */
    this.index = undefined;

    /**
     * The texture coordinate set.
     *
     * @type {Number}
     * @default 0
     * @private
     */
    this.texCoord = 0;

    /**
     * Transformation matrix to apply to texture coordinates.
     *
     * @type {Matrix3}
     * @default Matrix3.IDENTITY
     */
    this.transform = Matrix3.clone(Matrix3.IDENTITY);

    /**
     * The texture channels to read from. When undefined all channels are read.
     *
     * @type {String}
     */
    this.channels = undefined;
  }

  /**
   * Material properties for the PBR metallic roughness shading model.
   *
   * @alias ModelComponents.MetallicRoughness
   * @constructor
   *
   * @private
   */
  function MetallicRoughness$3() {
    /**
     * The base color texture reader.
     *
     * @type {ModelComponents.TextureReader}
     * @private
     */
    this.baseColorTexture = undefined;

    /**
     * The metallic roughness texture reader.
     *
     * @type {ModelComponents.TextureReader}
     * @private
     */
    this.metallicRoughnessTexture = undefined;

    /**
     * The base color factor.
     *
     * @type {Cartesian4}
     * @default new Cartesian4(1.0, 1.0, 1.0, 1.0)
     * @private
     */
    this.baseColorFactor = Cartesian4.clone(
      MetallicRoughness$3.DEFAULT_BASE_COLOR_FACTOR
    );

    /**
     * The metallic factor.
     *
     * @type {Number}
     * @default 1.0
     * @private
     */
    this.metallicFactor = MetallicRoughness$3.DEFAULT_METALLIC_FACTOR;

    /**
     * The roughness factor.
     *
     * @type {Number}
     * @default 1.0
     * @private
     */
    this.roughnessFactor = MetallicRoughness$3.DEFAULT_ROUGHNESS_FACTOR;
  }

  /**
   * @private
   */
  MetallicRoughness$3.DEFAULT_BASE_COLOR_FACTOR = Cartesian4.ONE;

  /**
   * @private
   */
  MetallicRoughness$3.DEFAULT_METALLIC_FACTOR = 1.0;

  /**
   * @private
   */
  MetallicRoughness$3.DEFAULT_ROUGHNESS_FACTOR = 1.0;

  /**
   * Material properties for the PBR specular glossiness shading model.
   *
   * @alias ModelComponents.function SpecularGlossiness
   * @constructor
   *
   * @private
   */
  function SpecularGlossiness$2() {
    /**
     * The diffuse texture reader.
     *
     * @type {ModelComponents.TextureReader}
     * @private
     */
    this.diffuseTexture = undefined;

    /**
     * The specular glossiness texture reader.
     *
     * @type {ModelComponents.TextureReader}
     * @private
     */
    this.specularGlossinessTexture = undefined;

    /**
     * The diffuse factor.
     *
     * @type {Cartesian4}
     * @default new Cartesian4(1.0, 1.0, 1.0, 1.0)
     * @private
     */
    this.diffuseFactor = Cartesian4.clone(
      SpecularGlossiness$2.DEFAULT_DIFFUSE_FACTOR
    );

    /**
     * The specular factor.
     *
     * @type {Cartesian3}
     * @default new Cartesian3(1.0, 1.0, 1.0)
     * @private
     */
    this.specularFactor = Cartesian3.clone(
      SpecularGlossiness$2.DEFAULT_SPECULAR_FACTOR
    );

    /**
     * The glossiness factor.
     *
     * @type {Number}
     * @default 1.0
     * @private
     */
    this.glossinessFactor = SpecularGlossiness$2.DEFAULT_GLOSSINESS_FACTOR;
  }

  /**
   * @private
   */
  SpecularGlossiness$2.DEFAULT_DIFFUSE_FACTOR = Cartesian4.ONE;

  /**
   * @private
   */
  SpecularGlossiness$2.DEFAULT_SPECULAR_FACTOR = Cartesian3.ONE;

  /**
   * @private
   */
  SpecularGlossiness$2.DEFAULT_GLOSSINESS_FACTOR = 1.0;

  /**
   * The material appearance of a primitive.
   *
   * @alias ModelComponent.Material
   * @constructor
   *
   * @private
   */
  function Material$3() {
    /**
     * Material properties for the PBR metallic roughness shading model.
     *
     * @type {ModelComponents.MetallicRoughness}
     * @private
     */
    this.metallicRoughness = new MetallicRoughness$3();

    /**
     * Material properties for the PBR specular glossiness shading model.
     *
     * @type {ModelComponents.SpecularGlossiness}
     * @private
     */
    this.specularGlossiness = undefined;

    /**
     * The emissive texture reader.
     *
     * @type {ModelComponents.TextureReader}
     * @private
     */
    this.emissiveTexture = undefined;

    /**
     * The normal texture reader.
     *
     * @type {ModelComponents.TextureReader}
     * @private
     */
    this.normalTexture = undefined;

    /**
     * The occlusion texture reader.
     *
     * @type {ModelComponents.TextureReader}
     * @private
     */
    this.occlusionTexture = undefined;

    /**
     * The emissive factor.
     *
     * @type {Cartesian3}
     * @default Cartesian3.ZERO
     * @private
     */
    this.emissiveFactor = Cartesian3.clone(Material$3.DEFAULT_EMISSIVE_FACTOR);

    /**
     * The alpha mode.
     *
     * @type {AlphaMode}
     * @default AlphaMode.OPAQUE
     * @private
     */
    this.alphaMode = AlphaMode$1.OPAQUE;

    /**
     * The alpha cutoff value of the material for the MASK alpha mode.
     *
     * @type {Number}
     * @default 0.5
     * @private
     */
    this.alphaCutoff = 0.5;

    /**
     * Specifies whether the material is double sided.
     *
     * @type {Boolean}
     * @default false
     * @private
     */
    this.doubleSided = false;

    /**
     * Specifies whether the material is unlit.
     *
     * @type {Boolean}
     * @default false
     * @private
     */
    this.unlit = false;
  }

  /**
   * @private
   */
  Material$3.DEFAULT_EMISSIVE_FACTOR = Cartesian3.ZERO;

  ModelComponents.Quantization = Quantization$1;
  ModelComponents.Attribute = Attribute$3;
  ModelComponents.Indices = Indices$1;
  ModelComponents.FeatureIdAttribute = FeatureIdAttribute$4;
  ModelComponents.FeatureIdTexture = FeatureIdTexture$1;
  ModelComponents.FeatureIdImplicitRange = FeatureIdImplicitRange$1;
  ModelComponents.MorphTarget = MorphTarget$1;
  ModelComponents.Primitive = Primitive$2;
  ModelComponents.Instances = Instances$2;
  ModelComponents.Skin = Skin$1;
  ModelComponents.Node = Node$3;
  ModelComponents.Scene = Scene$3;
  ModelComponents.AnimatedPropertyType = Object.freeze(AnimatedPropertyType$2);
  ModelComponents.AnimationSampler = AnimationSampler$1;
  ModelComponents.AnimationTarget = AnimationTarget$1;
  ModelComponents.AnimationChannel = AnimationChannel$1;
  ModelComponents.Animation = Animation$2;
  ModelComponents.ArticulationStage = ArticulationStage$1;
  ModelComponents.Articulation = Articulation$1;
  ModelComponents.Asset = Asset$1;
  ModelComponents.Components = Components$2;
  ModelComponents.TextureReader = TextureReader;
  ModelComponents.MetallicRoughness = MetallicRoughness$3;
  ModelComponents.SpecularGlossiness = SpecularGlossiness$2;
  ModelComponents.Material = Material$3;

  /**
   * glTF loading utilities.
   *
   * @namespace GltfLoaderUtil
   *
   * @private
   */
  const GltfLoaderUtil = {};

  /**
   * Get the image ID referenced by a texture.
   * <p>
   * When the texture has the EXT_texture_webp extension and the browser supports
   * WebP images the WebP image ID is returned.
   * </p>
   *
   * @param {Object} options Object with the following properties:
   * @param {Object} options.gltf The glTF JSON.
   * @param {Number} options.textureId The texture ID.
   * @param {SupportedImageFormats} options.supportedImageFormats The supported image formats.
   *
   * @returns {Number} The image ID.
   * @private
   */
  GltfLoaderUtil.getImageIdFromTexture = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const gltf = options.gltf;
    const textureId = options.textureId;
    const supportedImageFormats = options.supportedImageFormats;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.gltf", gltf);
    Check.typeOf.number("options.textureId", textureId);
    Check.typeOf.object("options.supportedImageFormats", supportedImageFormats);
    //>>includeEnd('debug');

    const texture = gltf.textures[textureId];
    const extensions = texture.extensions;
    if (defined(extensions)) {
      if (supportedImageFormats.webp && defined(extensions.EXT_texture_webp)) {
        return extensions.EXT_texture_webp.source;
      } else if (
        supportedImageFormats.basis &&
        defined(extensions.KHR_texture_basisu)
      ) {
        return extensions.KHR_texture_basisu.source;
      }
    }
    return texture.source;
  };

  /**
   * Create a sampler for a texture.
   *
   * @param {Object} options Object with the following properties:
   * @param {Object} options.gltf The glTF JSON.
   * @param {Object} options.textureInfo The texture info object.
   * @param {Boolean} [options.compressedTextureNoMipmap=false] True when the texture is compressed and does not have an embedded mipmap.
   *
   * @returns {Sampler} The sampler.
   * @private
   */
  GltfLoaderUtil.createSampler = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const gltf = options.gltf;
    const textureInfo = options.textureInfo;
    const compressedTextureNoMipmap = defaultValue(
      options.compressedTextureNoMipmap,
      false
    );

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.gltf", gltf);
    Check.typeOf.object("options.textureInfo", textureInfo);
    //>>includeEnd('debug');

    // Default sampler properties
    let wrapS = TextureWrap$1.REPEAT;
    let wrapT = TextureWrap$1.REPEAT;
    let minFilter = TextureMinificationFilter$1.LINEAR;
    let magFilter = TextureMagnificationFilter$1.LINEAR;

    const textureId = textureInfo.index;
    const texture = gltf.textures[textureId];
    const samplerId = texture.sampler;

    if (defined(samplerId)) {
      const sampler = gltf.samplers[samplerId];
      wrapS = defaultValue(sampler.wrapS, wrapS);
      wrapT = defaultValue(sampler.wrapT, wrapT);
      minFilter = defaultValue(sampler.minFilter, minFilter);
      magFilter = defaultValue(sampler.magFilter, magFilter);
    }

    let usesTextureTransform = false;
    const extensions = textureInfo.extensions;
    if (defined(extensions) && defined(extensions.KHR_texture_transform)) {
      usesTextureTransform = true;
    }

    if (
      (compressedTextureNoMipmap || usesTextureTransform) &&
      minFilter !== TextureMinificationFilter$1.LINEAR &&
      minFilter !== TextureMinificationFilter$1.NEAREST
    ) {
      if (
        minFilter === TextureMinificationFilter$1.NEAREST_MIPMAP_NEAREST ||
        minFilter === TextureMinificationFilter$1.NEAREST_MIPMAP_LINEAR
      ) {
        minFilter = TextureMinificationFilter$1.NEAREST;
      } else {
        minFilter = TextureMinificationFilter$1.LINEAR;
      }
    }

    return new Sampler({
      wrapS: wrapS,
      wrapT: wrapT,
      minificationFilter: minFilter,
      magnificationFilter: magFilter,
    });
  };

  const defaultScale$2 = new Cartesian2(1.0, 1.0);

  /**
   * Create a model texture reader.
   *
   * @param {Object} options Object with the following properties:
   * @param {Object} options.textureInfo The texture info JSON.
   * @param {String} [options.channels] The texture channels to read from.
   * @param {Texture} [options.texture] The texture object.
   *
   * @returns {ModelComponents.TextureReader} The texture reader for this model.
   */
  GltfLoaderUtil.createModelTextureReader = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const textureInfo = options.textureInfo;
    const channels = options.channels;
    const texture = options.texture;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.textureInfo", textureInfo);
    //>>includeEnd('debug');

    let texCoord = defaultValue(textureInfo.texCoord, 0);
    let transform;

    const textureTransform = defaultValue(
      textureInfo.extensions,
      defaultValue.EMPTY_OBJECT
    ).KHR_texture_transform;

    if (defined(textureTransform)) {
      texCoord = defaultValue(textureTransform.texCoord, texCoord);

      const offset = defined(textureTransform.offset)
        ? Cartesian2.unpack(textureTransform.offset)
        : Cartesian2.ZERO;
      let rotation = defaultValue(textureTransform.rotation, 0.0);
      const scale = defined(textureTransform.scale)
        ? Cartesian2.unpack(textureTransform.scale)
        : defaultScale$2;

      // glTF assumes UV coordinates start with (0, 0) in the top left corner
      // (y-down) unlike WebGL which puts (0, 0) in the bottom left corner (y-up).
      // This means rotations are reversed since the angle from x to y is now
      // clockwise instead of CCW. Translations and scales are not impacted by
      // this.
      rotation = -rotation;

      // prettier-ignore
      transform = new Matrix3(
          Math.cos(rotation) * scale.x, -Math.sin(rotation) * scale.y, offset.x,
          Math.sin(rotation) * scale.x, Math.cos(rotation) * scale.y, offset.y,
          0.0, 0.0, 1.0
        );
    }

    const modelTextureReader = new ModelComponents.TextureReader();
    modelTextureReader.index = textureInfo.index;
    modelTextureReader.texture = texture;
    modelTextureReader.texCoord = texCoord;
    modelTextureReader.transform = transform;
    modelTextureReader.channels = channels;

    return modelTextureReader;
  };

  /**
   * Loads a glTF texture.
   * <p>
   * Implements the {@link ResourceLoader} interface.
   * </p>
   *
   * @alias GltfTextureLoader
   * @constructor
   * @augments ResourceLoader
   *
   * @param {Object} options Object with the following properties:
   * @param {ResourceCache} options.resourceCache The {@link ResourceCache} (to avoid circular dependencies).
   * @param {Object} options.gltf The glTF JSON.
   * @param {Object} options.textureInfo The texture info object.
   * @param {Resource} options.gltfResource The {@link Resource} containing the glTF.
   * @param {Resource} options.baseResource The {@link Resource} that paths in the glTF JSON are relative to.
   * @param {SupportedImageFormats} options.supportedImageFormats The supported image formats.
   * @param {String} [options.cacheKey] The cache key of the resource.
   * @param {Boolean} [options.asynchronous=true] Determines if WebGL resource creation will be spread out over several frames or block until all WebGL resources are created.
   *
   * @private
   */
  function GltfTextureLoader(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const resourceCache = options.resourceCache;
    const gltf = options.gltf;
    const textureInfo = options.textureInfo;
    const gltfResource = options.gltfResource;
    const baseResource = options.baseResource;
    const supportedImageFormats = options.supportedImageFormats;
    const cacheKey = options.cacheKey;
    const asynchronous = defaultValue(options.asynchronous, true);

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.func("options.resourceCache", resourceCache);
    Check.typeOf.object("options.gltf", gltf);
    Check.typeOf.object("options.textureInfo", textureInfo);
    Check.typeOf.object("options.gltfResource", gltfResource);
    Check.typeOf.object("options.baseResource", baseResource);
    Check.typeOf.object("options.supportedImageFormats", supportedImageFormats);
    //>>includeEnd('debug');

    const textureId = textureInfo.index;

    // imageId is guaranteed to be defined otherwise the GltfTextureLoader
    // wouldn't have been created
    const imageId = GltfLoaderUtil.getImageIdFromTexture({
      gltf: gltf,
      textureId: textureId,
      supportedImageFormats: supportedImageFormats,
    });

    this._resourceCache = resourceCache;
    this._gltf = gltf;
    this._textureInfo = textureInfo;
    this._imageId = imageId;
    this._gltfResource = gltfResource;
    this._baseResource = baseResource;
    this._cacheKey = cacheKey;
    this._asynchronous = asynchronous;
    this._imageLoader = undefined;
    this._image = undefined;
    this._mipLevels = undefined;
    this._texture = undefined;
    this._state = ResourceLoaderState$1.UNLOADED;
    this._promise = undefined;
    this._process = function (loader, frameState) {};
  }

  if (defined(Object.create)) {
    GltfTextureLoader.prototype = Object.create(ResourceLoader.prototype);
    GltfTextureLoader.prototype.constructor = GltfTextureLoader;
  }

  Object.defineProperties(GltfTextureLoader.prototype, {
    /**
     * A promise that resolves to the resource when the resource is ready, or undefined if the resource hasn't started loading.
     *
     * @memberof GltfTextureLoader.prototype
     *
     * @type {Promise.<GltfTextureLoader>|undefined}
     * @readonly
     * @private
     */
    promise: {
      get: function () {
        return this._promise;
      },
    },
    /**
     * The cache key of the resource.
     *
     * @memberof GltfTextureLoader.prototype
     *
     * @type {String}
     * @readonly
     * @private
     */
    cacheKey: {
      get: function () {
        return this._cacheKey;
      },
    },
    /**
     * The texture.
     *
     * @memberof GltfTextureLoader.prototype
     *
     * @type {Texture}
     * @readonly
     * @private
     */
    texture: {
      get: function () {
        return this._texture;
      },
    },
  });

  const scratchTextureJob = new CreateTextureJob();

  /**
   * Loads the resource.
   * @returns {Promise.<GltfDracoLoader>} A promise which resolves to the loader when the resource loading is completed.
   * @private
   */
  GltfTextureLoader.prototype.load = function () {
    const resourceCache = this._resourceCache;
    const imageLoader = resourceCache.loadImage({
      gltf: this._gltf,
      imageId: this._imageId,
      gltfResource: this._gltfResource,
      baseResource: this._baseResource,
    });

    this._imageLoader = imageLoader;
    this._state = ResourceLoaderState$1.LOADING;
    const that = this;
    const processPromise = new Promise(function (resolve) {
      that._process = function (loader, frameState) {
        if (defined(loader._texture)) {
          // Already created texture
          return;
        }

        if (!defined(loader._image)) {
          // Not ready to create texture
          return;
        }

        let texture;

        if (loader._asynchronous) {
          const textureJob = scratchTextureJob;
          textureJob.set(
            loader._gltf,
            loader._textureInfo,
            loader._image,
            loader._mipLevels,
            frameState.context
          );
          const jobScheduler = frameState.jobScheduler;
          if (!jobScheduler.execute(textureJob, JobType$1.TEXTURE)) {
            // Job scheduler is full. Try again next frame.
            return;
          }
          texture = textureJob.texture;
        } else {
          texture = createTexture$1(
            loader._gltf,
            loader._textureInfo,
            loader._image,
            loader._mipLevels,
            frameState.context
          );
        }

        // Unload everything except the texture
        loader.unload();

        loader._texture = texture;
        loader._state = ResourceLoaderState$1.READY;
        resolve(loader);
      };
    });

    this._promise = imageLoader.promise
      .then(function () {
        if (that.isDestroyed()) {
          return;
        }
        // Now wait for process() to run to finish loading
        that._image = imageLoader.image;
        that._mipLevels = imageLoader.mipLevels;
        that._state = ResourceLoaderState$1.PROCESSING;
        return processPromise;
      })
      .catch(function (error) {
        if (that.isDestroyed()) {
          return;
        }
        that.unload();
        that._state = ResourceLoaderState$1.FAILED;
        const errorMessage = "Failed to load texture";
        return Promise.reject(that.getError(errorMessage, error));
      });

    return this._promise;
  };

  function CreateTextureJob() {
    this.gltf = undefined;
    this.textureInfo = undefined;
    this.image = undefined;
    this.context = undefined;
    this.texture = undefined;
  }

  CreateTextureJob.prototype.set = function (
    gltf,
    textureInfo,
    image,
    mipLevels,
    context
  ) {
    this.gltf = gltf;
    this.textureInfo = textureInfo;
    this.image = image;
    this.mipLevels = mipLevels;
    this.context = context;
  };

  CreateTextureJob.prototype.execute = function () {
    this.texture = createTexture$1(
      this.gltf,
      this.textureInfo,
      this.image,
      this.mipLevels,
      this.context
    );
  };

  function createTexture$1(gltf, textureInfo, image, mipLevels, context) {
    // internalFormat is only defined for CompressedTextureBuffer
    const internalFormat = image.internalFormat;

    let compressedTextureNoMipmap = false;
    if (PixelFormat$1.isCompressedFormat(internalFormat) && !defined(mipLevels)) {
      compressedTextureNoMipmap = true;
    }

    const sampler = GltfLoaderUtil.createSampler({
      gltf: gltf,
      textureInfo: textureInfo,
      compressedTextureNoMipmap: compressedTextureNoMipmap,
    });

    const minFilter = sampler.minificationFilter;
    const wrapS = sampler.wrapS;
    const wrapT = sampler.wrapT;

    const samplerRequiresMipmap =
      minFilter === TextureMinificationFilter$1.NEAREST_MIPMAP_NEAREST ||
      minFilter === TextureMinificationFilter$1.NEAREST_MIPMAP_LINEAR ||
      minFilter === TextureMinificationFilter$1.LINEAR_MIPMAP_NEAREST ||
      minFilter === TextureMinificationFilter$1.LINEAR_MIPMAP_LINEAR;

    // generateMipmap is disallowed for compressed textures. Compressed textures
    // can have mipmaps but they must come with the KTX2 instead of generated by
    // WebGL. Also note from the KHR_texture_basisu spec:
    //
    //   When a texture refers to a sampler with mipmap minification or when the
    //   sampler is undefined, the KTX2 image SHOULD contain a full mip pyramid.
    //
    const generateMipmap = !defined(internalFormat) && samplerRequiresMipmap;

    // WebGL 1 requires power-of-two texture dimensions for mipmapping and REPEAT/MIRRORED_REPEAT wrap modes.
    const requiresPowerOfTwo =
      generateMipmap ||
      wrapS === TextureWrap$1.REPEAT ||
      wrapS === TextureWrap$1.MIRRORED_REPEAT ||
      wrapT === TextureWrap$1.REPEAT ||
      wrapT === TextureWrap$1.MIRRORED_REPEAT;

    const nonPowerOfTwo =
      !CesiumMath.isPowerOfTwo(image.width) ||
      !CesiumMath.isPowerOfTwo(image.height);

    const requiresResize = requiresPowerOfTwo && nonPowerOfTwo;

    let texture;
    if (defined(internalFormat)) {
      if (
        !context.webgl2 &&
        PixelFormat$1.isCompressedFormat(internalFormat) &&
        nonPowerOfTwo &&
        requiresPowerOfTwo
      ) {
        console.warn(
          "Compressed texture uses REPEAT or MIRRORED_REPEAT texture wrap mode and dimensions are not powers of two. The texture may be rendered incorrectly."
        );
      }

      texture = Texture.create({
        context: context,
        source: {
          arrayBufferView: image.bufferView, // Only defined for CompressedTextureBuffer
          mipLevels: mipLevels,
        },
        width: image.width,
        height: image.height,
        pixelFormat: image.internalFormat, // Only defined for CompressedTextureBuffer
        sampler: sampler,
      });
    } else {
      if (requiresResize) {
        image = resizeImageToNextPowerOfTwo(image);
      }
      texture = Texture.create({
        context: context,
        source: image,
        sampler: sampler,
        flipY: false,
        skipColorSpaceConversion: true,
      });
    }

    if (generateMipmap) {
      texture.generateMipmap();
    }

    return texture;
  }

  /**
   * Processes the resource until it becomes ready.
   *
   * @param {FrameState} frameState The frame state.
   * @private
   */
  GltfTextureLoader.prototype.process = function (frameState) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("frameState", frameState);
    //>>includeEnd('debug');

    return this._process(this, frameState);
  };

  /**
   * Unloads the resource.
   * @private
   */
  GltfTextureLoader.prototype.unload = function () {
    if (defined(this._texture)) {
      this._texture.destroy();
    }

    if (defined(this._imageLoader)) {
      this._resourceCache.unload(this._imageLoader);
    }

    this._imageLoader = undefined;
    this._image = undefined;
    this._mipLevels = undefined;
    this._texture = undefined;
    this._gltf = undefined;
  };

  /**
   * Loads a vertex buffer from a glTF buffer view.
   * <p>
   * Implements the {@link ResourceLoader} interface.
   * </p>
   *
   * @alias GltfVertexBufferLoader
   * @constructor
   * @augments ResourceLoader
   *
   * @param {Object} options Object with the following properties:
   * @param {ResourceCache} options.resourceCache The {@link ResourceCache} (to avoid circular dependencies).
   * @param {Object} options.gltf The glTF JSON.
   * @param {Resource} options.gltfResource The {@link Resource} containing the glTF.
   * @param {Resource} options.baseResource The {@link Resource} that paths in the glTF JSON are relative to.
   * @param {Number} [options.bufferViewId] The bufferView ID corresponding to the vertex buffer.
   * @param {Object} [options.draco] The Draco extension object.
   * @param {String} [options.attributeSemantic] The attribute semantic, e.g. POSITION or NORMAL.
   * @param {Number} [options.accessorId] The accessor id.
   * @param {String} [options.cacheKey] The cache key of the resource.
   * @param {Boolean} [options.asynchronous=true] Determines if WebGL resource creation will be spread out over several frames or block until all WebGL resources are created.
   * @param {Boolean} [options.dequantize=false] Determines whether or not the vertex buffer will be dequantized on the CPU.
   * @param {Boolean} [options.loadBuffer=false] Load vertex buffer as a GPU vertex buffer.
   * @param {Boolean} [options.loadTypedArray=false] Load vertex buffer as a typed array.
   *
   * @exception {DeveloperError} One of options.bufferViewId and options.draco must be defined.
   * @exception {DeveloperError} When options.draco is defined options.attributeSemantic must also be defined.
   * @exception {DeveloperError} When options.draco is defined options.accessorId must also be defined.
   *
   * @private
   */
  function GltfVertexBufferLoader(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const resourceCache = options.resourceCache;
    const gltf = options.gltf;
    const gltfResource = options.gltfResource;
    const baseResource = options.baseResource;
    const bufferViewId = options.bufferViewId;
    const draco = options.draco;
    const attributeSemantic = options.attributeSemantic;
    const accessorId = options.accessorId;
    const cacheKey = options.cacheKey;
    const asynchronous = defaultValue(options.asynchronous, true);
    const dequantize = defaultValue(options.dequantize, false);
    const loadBuffer = defaultValue(options.loadBuffer, false);
    const loadTypedArray = defaultValue(options.loadTypedArray, false);

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.func("options.resourceCache", resourceCache);
    Check.typeOf.object("options.gltf", gltf);
    Check.typeOf.object("options.gltfResource", gltfResource);
    Check.typeOf.object("options.baseResource", baseResource);
    if (!loadBuffer && !loadTypedArray) {
      throw new DeveloperError(
        "At least one of loadBuffer and loadTypedArray must be true."
      );
    }

    const hasBufferViewId = defined(bufferViewId);
    const hasDraco = defined(draco);
    const hasAttributeSemantic = defined(attributeSemantic);
    const hasAccessorId = defined(accessorId);

    if (hasBufferViewId === hasDraco) {
      throw new DeveloperError(
        "One of options.bufferViewId and options.draco must be defined."
      );
    }

    if (hasDraco && !hasAttributeSemantic) {
      throw new DeveloperError(
        "When options.draco is defined options.attributeSemantic must also be defined."
      );
    }

    if (hasDraco && !hasAccessorId) {
      throw new DeveloperError(
        "When options.draco is defined options.accessorId must also be defined."
      );
    }

    if (hasDraco) {
      Check.typeOf.object("options.draco", draco);
      Check.typeOf.string("options.attributeSemantic", attributeSemantic);
      Check.typeOf.number("options.accessorId", accessorId);
    }
    //>>includeEnd('debug');

    this._resourceCache = resourceCache;
    this._gltfResource = gltfResource;
    this._baseResource = baseResource;
    this._gltf = gltf;
    this._bufferViewId = bufferViewId;
    this._draco = draco;
    this._attributeSemantic = attributeSemantic;
    this._accessorId = accessorId;
    this._cacheKey = cacheKey;
    this._asynchronous = asynchronous;
    this._dequantize = dequantize;
    this._loadBuffer = loadBuffer;
    this._loadTypedArray = loadTypedArray;
    this._bufferViewLoader = undefined;
    this._dracoLoader = undefined;
    this._quantization = undefined;
    this._typedArray = undefined;
    this._buffer = undefined;
    this._state = ResourceLoaderState$1.UNLOADED;
    this._promise = undefined;
    this._process = function (loader, frameState) {};
  }

  if (defined(Object.create)) {
    GltfVertexBufferLoader.prototype = Object.create(ResourceLoader.prototype);
    GltfVertexBufferLoader.prototype.constructor = GltfVertexBufferLoader;
  }

  Object.defineProperties(GltfVertexBufferLoader.prototype, {
    /**
     * A promise that resolves to the resource when the resource is ready, or undefined if the resource hasn't started loading.
     *
     * @memberof GltfVertexBufferLoader.prototype
     *
     * @type {Promise.<GltfVertexBufferLoader>|undefined}
     * @readonly
     * @private
     */
    promise: {
      get: function () {
        return this._promise;
      },
    },
    /**
     * The cache key of the resource.
     *
     * @memberof GltfVertexBufferLoader.prototype
     *
     * @type {String}
     * @readonly
     * @private
     */
    cacheKey: {
      get: function () {
        return this._cacheKey;
      },
    },
    /**
     * The vertex buffer. This is only defined when <code>loadAsTypedArray</code> is false.
     *
     * @memberof GltfVertexBufferLoader.prototype
     *
     * @type {Buffer}
     * @readonly
     * @private
     */
    buffer: {
      get: function () {
        return this._buffer;
      },
    },
    /**
     * The typed array containing vertex buffer data. This is only defined when <code>loadAsTypedArray</code> is true.
     *
     * @memberof GltfVertexBufferLoader.prototype
     *
     * @type {Uint8Array}
     * @readonly
     * @private
     */
    typedArray: {
      get: function () {
        return this._typedArray;
      },
    },
    /**
     * Information about the quantized vertex attribute after Draco decode.
     *
     * @memberof GltfVertexBufferLoader.prototype
     *
     * @type {ModelComponents.Quantization}
     * @readonly
     * @private
     */
    quantization: {
      get: function () {
        return this._quantization;
      },
    },
  });

  /**
   * Loads the resource.
   * @returns {Promise.<GltfVertexBufferLoader>} A promise which resolves to the loader when the resource loading is completed.
   * @private
   */
  GltfVertexBufferLoader.prototype.load = function () {
    let promise;

    if (defined(this._draco)) {
      promise = loadFromDraco(this);
    } else {
      promise = loadFromBufferView(this);
    }

    const that = this;
    const scratchVertexBufferJob = new CreateVertexBufferJob();
    const processPromise = new Promise(function (resolve) {
      that._process = function (loader, frameState) {
        if (loader._state === ResourceLoaderState$1.READY) {
          return;
        }

        const typedArray = loader._typedArray;
        const dequantize = loader._dequantize;

        if (defined(loader._dracoLoader)) {
          loader._dracoLoader.process(frameState);
        }

        if (defined(loader._bufferViewLoader)) {
          loader._bufferViewLoader.process(frameState);
        }

        if (!defined(typedArray)) {
          // Buffer view hasn't been loaded yet
          return;
        }

        const accessor = loader._gltf.accessors[loader._accessorId];

        let buffer;
        if (loader._loadBuffer && loader._asynchronous) {
          const vertexBufferJob = scratchVertexBufferJob;
          vertexBufferJob.set(
            typedArray,
            dequantize,
            accessor.componentType,
            accessor.type,
            accessor.count,
            frameState.context
          );
          const jobScheduler = frameState.jobScheduler;
          if (!jobScheduler.execute(vertexBufferJob, JobType$1.BUFFER)) {
            // Job scheduler is full. Try again next frame.
            return;
          }
          buffer = vertexBufferJob.buffer;
        } else if (loader._loadBuffer) {
          buffer = createVertexBuffer$2(
            typedArray,
            dequantize,
            accessor.componentType,
            accessor.type,
            accessor.count,
            frameState.context
          );
        }

        // Unload everything except the vertex buffer
        loader.unload();

        loader._buffer = buffer;
        loader._typedArray = loader._loadTypedArray ? typedArray : undefined;
        loader._state = ResourceLoaderState$1.READY;
        resolve(loader);
      };
    });

    this._promise = promise
      .then(function () {
        if (that.isDestroyed()) {
          return;
        }

        return processPromise;
      })
      .catch(function (error) {
        if (that.isDestroyed()) {
          return;
        }

        return handleError$3(that, error);
      });
    return this._promise;
  };

  function getQuantizationInformation(
    dracoQuantization,
    componentDatatype,
    componentCount,
    type
  ) {
    const quantizationBits = dracoQuantization.quantizationBits;
    const normalizationRange = (1 << quantizationBits) - 1;
    const normalizationDivisor = 1.0 / normalizationRange;

    const quantization = new ModelComponents.Quantization();
    quantization.componentDatatype = componentDatatype;
    quantization.octEncoded = dracoQuantization.octEncoded;
    quantization.octEncodedZXY = true;
    quantization.type = type;

    if (quantization.octEncoded) {
      quantization.type = AttributeType$1.VEC2;
      quantization.normalizationRange = normalizationRange;
    } else {
      const MathType = AttributeType$1.getMathType(type);
      if (MathType === Number) {
        const dimensions = dracoQuantization.range;
        quantization.quantizedVolumeOffset = dracoQuantization.minValues[0];
        quantization.quantizedVolumeDimensions = dimensions;
        quantization.normalizationRange = normalizationRange;
        quantization.quantizedVolumeStepSize = dimensions * normalizationDivisor;
      } else {
        quantization.quantizedVolumeOffset = MathType.unpack(
          dracoQuantization.minValues
        );
        quantization.normalizationRange = MathType.unpack(
          new Array(componentCount).fill(normalizationRange)
        );
        const packedDimensions = new Array(componentCount).fill(
          dracoQuantization.range
        );
        quantization.quantizedVolumeDimensions = MathType.unpack(
          packedDimensions
        );

        // Computing the step size
        const packedSteps = packedDimensions.map(function (dimension) {
          return dimension * normalizationDivisor;
        });
        quantization.quantizedVolumeStepSize = MathType.unpack(packedSteps);
      }
    }

    return quantization;
  }

  function loadFromDraco(vertexBufferLoader) {
    const resourceCache = vertexBufferLoader._resourceCache;
    const dracoLoader = resourceCache.loadDraco({
      gltf: vertexBufferLoader._gltf,
      draco: vertexBufferLoader._draco,
      gltfResource: vertexBufferLoader._gltfResource,
      baseResource: vertexBufferLoader._baseResource,
    });

    vertexBufferLoader._dracoLoader = dracoLoader;
    vertexBufferLoader._state = ResourceLoaderState$1.LOADING;

    return dracoLoader.promise.then(function () {
      if (vertexBufferLoader.isDestroyed()) {
        return;
      }
      // Get the typed array and quantization information
      const decodedVertexAttributes = dracoLoader.decodedData.vertexAttributes;
      const attributeSemantic = vertexBufferLoader._attributeSemantic;
      const dracoAttribute = decodedVertexAttributes[attributeSemantic];
      const accessorId = vertexBufferLoader._accessorId;
      const accessor = vertexBufferLoader._gltf.accessors[accessorId];
      const type = accessor.type;
      const typedArray = dracoAttribute.array;
      const dracoQuantization = dracoAttribute.data.quantization;
      if (defined(dracoQuantization)) {
        vertexBufferLoader._quantization = getQuantizationInformation(
          dracoQuantization,
          dracoAttribute.data.componentDatatype,
          dracoAttribute.data.componentsPerAttribute,
          type
        );
      }

      // Now wait for process() to run to finish loading
      vertexBufferLoader._typedArray = typedArray;
      vertexBufferLoader._state = ResourceLoaderState$1.PROCESSING;
      return vertexBufferLoader;
    });
  }

  function loadFromBufferView(vertexBufferLoader) {
    const resourceCache = vertexBufferLoader._resourceCache;
    const bufferViewLoader = resourceCache.loadBufferView({
      gltf: vertexBufferLoader._gltf,
      bufferViewId: vertexBufferLoader._bufferViewId,
      gltfResource: vertexBufferLoader._gltfResource,
      baseResource: vertexBufferLoader._baseResource,
    });
    vertexBufferLoader._state = ResourceLoaderState$1.LOADING;
    vertexBufferLoader._bufferViewLoader = bufferViewLoader;

    return bufferViewLoader.promise.then(function () {
      if (vertexBufferLoader.isDestroyed()) {
        return;
      }
      // Now wait for process() to run to finish loading
      vertexBufferLoader._typedArray = bufferViewLoader.typedArray;
      vertexBufferLoader._state = ResourceLoaderState$1.PROCESSING;
      return vertexBufferLoader;
    });
  }

  function handleError$3(vertexBufferLoader, error) {
    vertexBufferLoader.unload();
    vertexBufferLoader._state = ResourceLoaderState$1.FAILED;
    const errorMessage = "Failed to load vertex buffer";
    error = vertexBufferLoader.getError(errorMessage, error);
    return Promise.reject(error);
  }

  function CreateVertexBufferJob() {
    this.typedArray = undefined;
    this.dequantize = undefined;
    this.componentType = undefined;
    this.type = undefined;
    this.count = undefined;
    this.context = undefined;
    this.buffer = undefined;
  }

  CreateVertexBufferJob.prototype.set = function (
    typedArray,
    dequantize,
    componentType,
    type,
    count,
    context
  ) {
    this.typedArray = typedArray;
    this.dequantize = dequantize;
    this.componentType = componentType;
    this.type = type;
    this.count = count;
    this.context = context;
  };

  CreateVertexBufferJob.prototype.execute = function () {
    this.buffer = createVertexBuffer$2(
      this.typedArray,
      this.dequantize,
      this.componentType,
      this.type,
      this.count,
      this.context
    );
  };

  function createVertexBuffer$2(
    typedArray,
    dequantize,
    componentType,
    type,
    count,
    context
  ) {
    if (dequantize && componentType !== ComponentDatatype$1.FLOAT) {
      typedArray = AttributeCompression.dequantize(
        typedArray,
        componentType,
        type,
        count
      );
    }

    const buffer = Buffer$1.createVertexBuffer({
      typedArray: typedArray,
      context: context,
      usage: BufferUsage$1.STATIC_DRAW,
    });
    buffer.vertexArrayDestroyable = false;
    return buffer;
  }

  /**
   * Processes the resource until it becomes ready.
   *
   * @param {FrameState} frameState The frame state.
   * @private
   */
  GltfVertexBufferLoader.prototype.process = function (frameState) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("frameState", frameState);
    //>>includeEnd('debug');

    return this._process(this, frameState);
  };

  /**
   * Unloads the resource.
   * @private
   */
  GltfVertexBufferLoader.prototype.unload = function () {
    if (defined(this._buffer)) {
      this._buffer.destroy();
    }

    const resourceCache = this._resourceCache;

    if (defined(this._bufferViewLoader)) {
      resourceCache.unload(this._bufferViewLoader);
    }

    if (defined(this._dracoLoader)) {
      resourceCache.unload(this._dracoLoader);
    }

    this._bufferViewLoader = undefined;
    this._dracoLoader = undefined;
    this._typedArray = undefined;
    this._buffer = undefined;
    this._gltf = undefined;
  };

  /**
   * A metadata class.
   *
   * <p>
   * See the {@link https://github.com/CesiumGS/3d-tiles/tree/main/extensions/3DTILES_metadata|3DTILES_metadata Extension} for 3D Tiles
   * </p>
   *
   * @param {Object} options Object with the following properties:
   * @param {String} options.id The ID of the class.
   * @param {Object} options.class The class JSON object.
   * @param {Object.<String, MetadataEnum>} [options.enums] A dictionary of enums.
   *
   * @alias MetadataClass
   * @constructor
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function MetadataClass(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const id = options.id;
    const classDefinition = options.class;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("options.id", id);
    Check.typeOf.object("options.class", classDefinition);
    //>>includeEnd('debug');

    const properties = {};
    const propertiesBySemantic = {};
    for (const propertyId in classDefinition.properties) {
      if (classDefinition.properties.hasOwnProperty(propertyId)) {
        const property = new MetadataClassProperty({
          id: propertyId,
          property: classDefinition.properties[propertyId],
          enums: options.enums,
        });
        properties[propertyId] = property;
        if (defined(property.semantic)) {
          propertiesBySemantic[property.semantic] = property;
        }
      }
    }

    this._properties = properties;
    this._propertiesBySemantic = propertiesBySemantic;
    this._id = id;
    this._name = classDefinition.name;
    this._description = classDefinition.description;
    this._extras = classDefinition.extras;
    this._extensions = classDefinition.extensions;
  }

  Object.defineProperties(MetadataClass.prototype, {
    /**
     * The class properties.
     *
     * @memberof MetadataClass.prototype
     * @type {Object.<String, MetadataClassProperty>}
     * @readonly
     * @private
     */
    properties: {
      get: function () {
        return this._properties;
      },
    },

    /**
     * A dictionary mapping semantics to class properties.
     *
     * @memberof MetadataClass.prototype
     * @type {Object.<String, MetadataClassProperty>}
     * @readonly
     *
     * @private
     */
    propertiesBySemantic: {
      get: function () {
        return this._propertiesBySemantic;
      },
    },

    /**
     * The ID of the class.
     *
     * @memberof MetadataClass.prototype
     * @type {String}
     * @readonly
     * @private
     */
    id: {
      get: function () {
        return this._id;
      },
    },

    /**
     * The name of the class.
     *
     * @memberof MetadataClass.prototype
     * @type {String}
     * @readonly
     * @private
     */
    name: {
      get: function () {
        return this._name;
      },
    },

    /**
     * The description of the class.
     *
     * @memberof MetadataClass.prototype
     * @type {String}
     * @readonly
     * @private
     */
    description: {
      get: function () {
        return this._description;
      },
    },

    /**
     * Extras in the JSON object.
     *
     * @memberof MetadataClass.prototype
     * @type {*}
     * @readonly
     * @private
     */
    extras: {
      get: function () {
        return this._extras;
      },
    },

    /**
     * Extensions in the JSON object.
     *
     * @memberof MetadataClass.prototype
     * @type {Object}
     * @readonly
     * @private
     */
    extensions: {
      get: function () {
        return this._extensions;
      },
    },
  });

  /**
   * The class name given to the metadata class when a batch
   * table is loaded from 3D Tiles 1.0 formats.
   *
   * @private
   */
  MetadataClass.BATCH_TABLE_CLASS_NAME = "_batchTable";

  /**
   * A metadata enum value.
   *
   * @param {Object} value The enum value JSON object.
   *
   * @alias MetadataEnumValue
   * @constructor
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function MetadataEnumValue(value) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("value", value);
    //>>includeEnd('debug');

    this._value = value.value;
    this._name = value.name;
    this._description = value.description;
    this._extras = value.extras;
    this._extensions = value.extensions;
  }

  Object.defineProperties(MetadataEnumValue.prototype, {
    /**
     * The integer value.
     *
     * @memberof MetadataEnumValue.prototype
     * @type {Number}
     * @readonly
     * @private
     */
    value: {
      get: function () {
        return this._value;
      },
    },

    /**
     * The name of the enum value.
     *
     * @memberof MetadataEnumValue.prototype
     * @type {String}
     * @readonly
     * @private
     */
    name: {
      get: function () {
        return this._name;
      },
    },

    /**
     * The description of the enum value.
     *
     * @memberof MetadataEnumValue.prototype
     * @type {String}
     * @readonly
     * @private
     */
    description: {
      get: function () {
        return this._description;
      },
    },

    /**
     * Extras in the JSON object.
     *
     * @memberof MetadataEnumValue.prototype
     * @type {*}
     * @readonly
     * @private
     */
    extras: {
      get: function () {
        return this._extras;
      },
    },

    /**
     * Extensions in the JSON object.
     *
     * @memberof MetadataEnumValue.prototype
     * @type {Object}
     * @readonly
     * @private
     */
    extensions: {
      get: function () {
        return this._extensions;
      },
    },
  });

  /**
   * A metadata enum.
   * <p>
   * See the {@link https://github.com/CesiumGS/3d-tiles/tree/main/extensions/3DTILES_metadata|3DTILES_metadata Extension} for 3D Tiles
   * </p>
   *
   * @param {Object} options Object with the following properties:
   * @param {String} options.id The ID of the enum.
   * @param {Object} options.enum The enum JSON object.
   *
   * @alias MetadataEnum
   * @constructor
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function MetadataEnum(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const id = options.id;
    const enumDefinition = options.enum;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("options.id", id);
    Check.typeOf.object("options.enum", enumDefinition);
    //>>includeEnd('debug');

    const namesByValue = {};
    const valuesByName = {};
    const values = enumDefinition.values.map(function (value) {
      namesByValue[value.value] = value.name;
      valuesByName[value.name] = value.value;
      return new MetadataEnumValue(value);
    });

    const valueType = defaultValue(
      MetadataComponentType$1[enumDefinition.valueType],
      MetadataComponentType$1.UINT16
    );

    this._values = values;
    this._namesByValue = namesByValue;
    this._valuesByName = valuesByName;
    this._valueType = valueType;
    this._id = id;
    this._name = enumDefinition.name;
    this._description = enumDefinition.description;
    this._extras = enumDefinition.extras;
    this._extensions = enumDefinition.extensions;
  }

  Object.defineProperties(MetadataEnum.prototype, {
    /**
     * The enum values.
     *
     * @memberof MetadataEnum.prototype
     * @type {MetadataEnumValue[]}
     * @readonly
     * @private
     */
    values: {
      get: function () {
        return this._values;
      },
    },

    /**
     * A dictionary mapping enum integer values to names.
     *
     * @memberof MetadataEnum.prototype
     * @type {Object.<Number, String>}
     * @readonly
     *
     * @private
     */
    namesByValue: {
      get: function () {
        return this._namesByValue;
      },
    },

    /**
     * A dictionary mapping enum names to integer values.
     *
     * @memberof MetadataEnum.prototype
     * @type {Object.<String, Number>}
     * @readonly
     *
     * @private
     */
    valuesByName: {
      get: function () {
        return this._valuesByName;
      },
    },

    /**
     * The enum value type.
     *
     * @memberof MetadataEnum.prototype
     * @type {MetadataComponentType}
     * @readonly
     *
     * @private
     */
    valueType: {
      get: function () {
        return this._valueType;
      },
    },

    /**
     * The ID of the enum.
     *
     * @memberof MetadataEnum.prototype
     * @type {String}
     * @readonly
     * @private
     */
    id: {
      get: function () {
        return this._id;
      },
    },

    /**
     * The name of the enum.
     *
     * @memberof MetadataEnum.prototype
     * @type {String}
     * @readonly
     * @private
     */
    name: {
      get: function () {
        return this._name;
      },
    },

    /**
     * The description of the enum.
     *
     * @memberof MetadataEnum.prototype
     * @type {String}
     * @readonly
     * @private
     */
    description: {
      get: function () {
        return this._description;
      },
    },

    /**
     * Extras in the JSON object.
     *
     * @memberof MetadataEnum.prototype
     * @type {*}
     * @readonly
     * @private
     */
    extras: {
      get: function () {
        return this._extras;
      },
    },

    /**
     * Extensions in the JSON object.
     *
     * @memberof MetadataEnum.prototype
     * @type {Object}
     * @readonly
     * @private
     */
    extensions: {
      get: function () {
        return this._extensions;
      },
    },
  });

  /**
   * A schema containing classes and enums.
   * <p>
   * See the {@link https://github.com/CesiumGS/3d-tiles/tree/main/extensions/3DTILES_metadata|3DTILES_metadata Extension} for 3D Tiles
   * </p>
   *
   * @param {Object} schema The schema JSON object.
   *
   * @alias MetadataSchema
   * @constructor
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function MetadataSchema(schema) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("schema", schema);
    //>>includeEnd('debug');

    const enums = {};
    if (defined(schema.enums)) {
      for (const enumId in schema.enums) {
        if (schema.enums.hasOwnProperty(enumId)) {
          enums[enumId] = new MetadataEnum({
            id: enumId,
            enum: schema.enums[enumId],
          });
        }
      }
    }

    const classes = {};
    if (defined(schema.classes)) {
      for (const classId in schema.classes) {
        if (schema.classes.hasOwnProperty(classId)) {
          classes[classId] = new MetadataClass({
            id: classId,
            class: schema.classes[classId],
            enums: enums,
          });
        }
      }
    }

    this._classes = classes;
    this._enums = enums;
    this._id = schema.id;
    this._name = schema.name;
    this._description = schema.description;
    this._version = schema.version;
    this._extras = schema.extras;
    this._extensions = schema.extensions;
  }

  Object.defineProperties(MetadataSchema.prototype, {
    /**
     * Classes defined in the schema.
     *
     * @memberof MetadataSchema.prototype
     * @type {Object.<String, MetadataClass>}
     * @readonly
     * @private
     */
    classes: {
      get: function () {
        return this._classes;
      },
    },

    /**
     * Enums defined in the schema.
     *
     * @memberof MetadataSchema.prototype
     * @type {Object.<String, MetadataEnum>}
     * @readonly
     * @private
     */
    enums: {
      get: function () {
        return this._enums;
      },
    },

    /**
     * The ID of the schema.
     *
     * @memberof MetadataSchema.prototype
     * @type {String}
     * @readonly
     * @private
     */
    id: {
      get: function () {
        return this._id;
      },
    },

    /**
     * The name of the schema.
     *
     * @memberof MetadataSchema.prototype
     * @type {String}
     * @readonly
     * @private
     */
    name: {
      get: function () {
        return this._name;
      },
    },

    /**
     * The description of the schema.
     *
     * @memberof MetadataSchema.prototype
     * @type {String}
     * @readonly
     * @private
     */
    description: {
      get: function () {
        return this._description;
      },
    },

    /**
     * The application-specific version of the schema.
     *
     * @memberof MetadataSchema.prototype
     * @type {String}
     * @readonly
     * @private
     */
    version: {
      get: function () {
        return this._version;
      },
    },

    /**
     * Extras in the JSON object.
     *
     * @memberof MetadataSchema.prototype
     * @type {*}
     * @readonly
     * @private
     */
    extras: {
      get: function () {
        return this._extras;
      },
    },

    /**
     * Extensions in the JSON object.
     *
     * @memberof MetadataSchema.prototype
     * @type {Object}
     * @readonly
     * @private
     */
    extensions: {
      get: function () {
        return this._extensions;
      },
    },
  });

  /**
   * A {@link MetadataSchema} loader.
   * <p>
   * Implements the {@link ResourceLoader} interface.
   * </p>
   *
   * @alias MetadataSchemaLoader
   * @constructor
   * @augments ResourceLoader
   *
   * @param {Object} options Object with the following properties:
   * @param {Object} [options.schema] An object that explicitly defines a schema JSON. Mutually exclusive with options.resource.
   * @param {Resource} [options.resource] The {@link Resource} pointing to the schema JSON. Mutually exclusive with options.schema.
   * @param {String} [options.cacheKey] The cache key of the resource.
   *
   * @exception {DeveloperError} One of options.schema and options.resource must be defined.
   *
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function MetadataSchemaLoader(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const schema = options.schema;
    const resource = options.resource;
    const cacheKey = options.cacheKey;

    //>>includeStart('debug', pragmas.debug);
    if (defined(schema) === defined(resource)) {
      throw new DeveloperError(
        "One of options.schema and options.resource must be defined."
      );
    }
    //>>includeEnd('debug');

    this._schema = defined(schema) ? new MetadataSchema(schema) : undefined;
    this._resource = resource;
    this._cacheKey = cacheKey;
    this._state = ResourceLoaderState$1.UNLOADED;
    this._promise = undefined;
  }

  if (defined(Object.create)) {
    MetadataSchemaLoader.prototype = Object.create(ResourceLoader.prototype);
    MetadataSchemaLoader.prototype.constructor = MetadataSchemaLoader;
  }

  Object.defineProperties(MetadataSchemaLoader.prototype, {
    /**
     * A promise that resolves to the resource when the resource is ready, or undefined if the resource hasn't started loading.
     *
     * @memberof MetadataSchemaLoader.prototype
     *
     * @type {Promise.<MetadataSchemaLoader>|undefined}
     * @readonly
     * @private
     */
    promise: {
      get: function () {
        return this._promise;
      },
    },
    /**
     * The cache key of the resource.
     *
     * @memberof MetadataSchemaLoader.prototype
     *
     * @type {String}
     * @readonly
     * @private
     */
    cacheKey: {
      get: function () {
        return this._cacheKey;
      },
    },
    /**
     * The metadata schema object.
     *
     * @memberof MetadataSchemaLoader.prototype
     *
     * @type {MetadataSchema}
     * @readonly
     * @private
     */
    schema: {
      get: function () {
        return this._schema;
      },
    },
  });

  /**
   * Loads the resource.
   * @returns {Promise.<MetadataSchemaLoader>} A promise which resolves to the loader when the resource loading is completed.
   * @private
   */
  MetadataSchemaLoader.prototype.load = function () {
    if (defined(this._schema)) {
      this._promise = Promise.resolve(this);
    } else {
      this._promise = loadExternalSchema(this);
    }

    return this._promise;
  };

  function loadExternalSchema(schemaLoader) {
    const resource = schemaLoader._resource;
    schemaLoader._state = ResourceLoaderState$1.LOADING;
    return resource
      .fetchJson()
      .then(function (json) {
        if (schemaLoader.isDestroyed()) {
          return;
        }
        schemaLoader._schema = new MetadataSchema(json);
        schemaLoader._state = ResourceLoaderState$1.READY;
        return schemaLoader;
      })
      .catch(function (error) {
        if (schemaLoader.isDestroyed()) {
          return;
        }
        schemaLoader._state = ResourceLoaderState$1.FAILED;
        const errorMessage = `Failed to load schema: ${resource.url}`;
        return Promise.reject(schemaLoader.getError(errorMessage, error));
      });
  }

  /**
   * Unloads the resource.
   * @private
   */
  MetadataSchemaLoader.prototype.unload = function () {
    this._schema = undefined;
  };

  /**
   * Compute cache keys for resources in {@link ResourceCache}.
   *
   * @namespace ResourceCacheKey
   *
   * @private
   */
  const ResourceCacheKey = {};

  function getExternalResourceCacheKey(resource) {
    return getAbsoluteUri(resource.url);
  }

  function getBufferViewCacheKey(bufferView) {
    let byteOffset = bufferView.byteOffset;
    let byteLength = bufferView.byteLength;

    if (hasExtension(bufferView, "EXT_meshopt_compression")) {
      const meshopt = bufferView.extensions.EXT_meshopt_compression;
      byteOffset = defaultValue(meshopt.byteOffset, 0);
      byteLength = meshopt.byteLength;
    }

    return `${byteOffset}-${byteOffset + byteLength}`;
  }

  function getAccessorCacheKey(accessor, bufferView) {
    const byteOffset = bufferView.byteOffset + accessor.byteOffset;
    const componentType = accessor.componentType;
    const type = accessor.type;
    const count = accessor.count;
    return `${byteOffset}-${componentType}-${type}-${count}`;
  }

  function getExternalBufferCacheKey(resource) {
    return getExternalResourceCacheKey(resource);
  }

  function getEmbeddedBufferCacheKey(parentResource, bufferId) {
    const parentCacheKey = getExternalResourceCacheKey(parentResource);
    return `${parentCacheKey}-buffer-id-${bufferId}`;
  }

  function getBufferCacheKey(buffer, bufferId, gltfResource, baseResource) {
    if (defined(buffer.uri)) {
      const resource = baseResource.getDerivedResource({
        url: buffer.uri,
      });
      return getExternalBufferCacheKey(resource);
    }

    return getEmbeddedBufferCacheKey(gltfResource, bufferId);
  }

  function getDracoCacheKey(gltf, draco, gltfResource, baseResource) {
    const bufferViewId = draco.bufferView;
    const bufferView = gltf.bufferViews[bufferViewId];
    const bufferId = bufferView.buffer;
    const buffer = gltf.buffers[bufferId];

    const bufferCacheKey = getBufferCacheKey(
      buffer,
      bufferId,
      gltfResource,
      baseResource
    );

    const bufferViewCacheKey = getBufferViewCacheKey(bufferView);

    return `${bufferCacheKey}-range-${bufferViewCacheKey}`;
  }

  function getImageCacheKey(gltf, imageId, gltfResource, baseResource) {
    const image = gltf.images[imageId];
    const bufferViewId = image.bufferView;
    const uri = image.uri;

    if (defined(uri)) {
      const resource = baseResource.getDerivedResource({
        url: uri,
      });
      return getExternalResourceCacheKey(resource);
    }

    const bufferView = gltf.bufferViews[bufferViewId];
    const bufferId = bufferView.buffer;
    const buffer = gltf.buffers[bufferId];

    const bufferCacheKey = getBufferCacheKey(
      buffer,
      bufferId,
      gltfResource,
      baseResource
    );

    const bufferViewCacheKey = getBufferViewCacheKey(bufferView);

    return `${bufferCacheKey}-range-${bufferViewCacheKey}`;
  }

  function getSamplerCacheKey(gltf, textureInfo) {
    const sampler = GltfLoaderUtil.createSampler({
      gltf: gltf,
      textureInfo: textureInfo,
    });

    return `${sampler.wrapS}-${sampler.wrapT}-${sampler.minificationFilter}-${sampler.magnificationFilter}`;
  }

  /**
   * Gets the schema cache key.
   *
   * @param {Object} options Object with the following properties:
   * @param {Object} [options.schema] An object that explicitly defines a schema JSON. Mutually exclusive with options.resource.
   * @param {Resource} [options.resource] The {@link Resource} pointing to the schema JSON. Mutually exclusive with options.schema.
   *
   * @returns {String} The schema cache key.
   *
   * @exception {DeveloperError} One of options.schema and options.resource must be defined.
   * @private
   */
  ResourceCacheKey.getSchemaCacheKey = function (options) {
    const schema = options.schema;
    const resource = options.resource;

    //>>includeStart('debug', pragmas.debug);
    if (defined(schema) === defined(resource)) {
      throw new DeveloperError(
        "One of options.schema and options.resource must be defined."
      );
    }
    //>>includeEnd('debug');

    if (defined(schema)) {
      return `embedded-schema:${JSON.stringify(schema)}`;
    }

    return `external-schema:${getExternalResourceCacheKey(resource)}`;
  };

  /**
   * Gets the external buffer cache key.
   *
   * @param {Object} options Object with the following properties:
   * @param {Resource} options.resource The {@link Resource} pointing to the external buffer.
   *
   * @returns {String} The external buffer cache key.
   * @private
   */
  ResourceCacheKey.getExternalBufferCacheKey = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const resource = options.resource;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.resource", resource);
    //>>includeEnd('debug');

    return `external-buffer:${getExternalBufferCacheKey(resource)}`;
  };

  /**
   * Gets the embedded buffer cache key.
   *
   * @param {Object} options Object with the following properties:
   * @param {Resource} options.parentResource The {@link Resource} containing the embedded buffer.
   * @param {Number} options.bufferId A unique identifier of the embedded buffer within the parent resource.
   *
   * @returns {String} The embedded buffer cache key.
   * @private
   */
  ResourceCacheKey.getEmbeddedBufferCacheKey = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const parentResource = options.parentResource;
    const bufferId = options.bufferId;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.parentResource", parentResource);
    Check.typeOf.number("options.bufferId", bufferId);
    //>>includeEnd('debug');

    return `embedded-buffer:${getEmbeddedBufferCacheKey(
    parentResource,
    bufferId
  )}`;
  };

  /**
   * Gets the glTF cache key.
   *
   * @param {Object} options Object with the following properties:
   * @param {Resource} options.gltfResource The {@link Resource} containing the glTF.
   *
   * @returns {String} The glTF cache key.
   * @private
   */
  ResourceCacheKey.getGltfCacheKey = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const gltfResource = options.gltfResource;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.gltfResource", gltfResource);
    //>>includeEnd('debug');

    return `gltf:${getExternalResourceCacheKey(gltfResource)}`;
  };

  /**
   * Gets the buffer view cache key.
   *
   * @param {Object} options Object with the following properties:
   * @param {Object} options.gltf The glTF JSON.
   * @param {Number} options.bufferViewId The bufferView ID.
   * @param {Resource} options.gltfResource The {@link Resource} containing the glTF.
   * @param {Resource} options.baseResource The {@link Resource} that paths in the glTF JSON are relative to.
   *
   * @returns {String} The buffer view cache key.
   * @private
   */
  ResourceCacheKey.getBufferViewCacheKey = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const gltf = options.gltf;
    const bufferViewId = options.bufferViewId;
    const gltfResource = options.gltfResource;
    const baseResource = options.baseResource;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.gltf", gltf);
    Check.typeOf.number("options.bufferViewId", bufferViewId);
    Check.typeOf.object("options.gltfResource", gltfResource);
    Check.typeOf.object("options.baseResource", baseResource);
    //>>includeEnd('debug');

    const bufferView = gltf.bufferViews[bufferViewId];
    let bufferId = bufferView.buffer;
    const buffer = gltf.buffers[bufferId];
    if (hasExtension(bufferView, "EXT_meshopt_compression")) {
      const meshopt = bufferView.extensions.EXT_meshopt_compression;
      bufferId = meshopt.buffer;
    }

    const bufferCacheKey = getBufferCacheKey(
      buffer,
      bufferId,
      gltfResource,
      baseResource
    );

    const bufferViewCacheKey = getBufferViewCacheKey(bufferView);

    return `buffer-view:${bufferCacheKey}-range-${bufferViewCacheKey}`;
  };

  /**
   * Gets the Draco cache key.
   *
   * @param {Object} options Object with the following properties:
   * @param {Object} options.gltf The glTF JSON.
   * @param {Object} options.draco The Draco extension object.
   * @param {Resource} options.gltfResource The {@link Resource} containing the glTF.
   * @param {Resource} options.baseResource The {@link Resource} that paths in the glTF JSON are relative to.
   *
   * @returns {String} The Draco cache key.
   * @private
   */
  ResourceCacheKey.getDracoCacheKey = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const gltf = options.gltf;
    const draco = options.draco;
    const gltfResource = options.gltfResource;
    const baseResource = options.baseResource;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.gltf", gltf);
    Check.typeOf.object("options.draco", draco);
    Check.typeOf.object("options.gltfResource", gltfResource);
    Check.typeOf.object("options.baseResource", baseResource);
    //>>includeEnd('debug');

    return `draco:${getDracoCacheKey(gltf, draco, gltfResource, baseResource)}`;
  };

  /**
   * Gets the vertex buffer cache key.
   *
   * @param {Object} options Object with the following properties:
   * @param {Object} options.gltf The glTF JSON.
   * @param {Resource} options.gltfResource The {@link Resource} containing the glTF.
   * @param {Resource} options.baseResource The {@link Resource} that paths in the glTF JSON are relative to.
   * @param {Number} [options.bufferViewId] The bufferView ID corresponding to the vertex buffer.
   * @param {Object} [options.draco] The Draco extension object.
   * @param {String} [options.attributeSemantic] The attribute semantic, e.g. POSITION or NORMAL.
   * @param {Boolean} [options.dequantize=false] Determines whether or not the vertex buffer will be dequantized on the CPU.
   * @param {Boolean} [options.loadBuffer=false] Load vertex buffer as a GPU vertex buffer.
   * @param {Boolean} [options.loadTypedArray=false] Load vertex buffer as a typed array.
   * @exception {DeveloperError} One of options.bufferViewId and options.draco must be defined.
   * @exception {DeveloperError} When options.draco is defined options.attributeSemantic must also be defined.
   *
   * @returns {String} The vertex buffer cache key.
   * @private
   */
  ResourceCacheKey.getVertexBufferCacheKey = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const gltf = options.gltf;
    const gltfResource = options.gltfResource;
    const baseResource = options.baseResource;
    const bufferViewId = options.bufferViewId;
    const draco = options.draco;
    const attributeSemantic = options.attributeSemantic;
    const dequantize = defaultValue(options.dequantize, false);
    const loadBuffer = defaultValue(options.loadBuffer, false);
    const loadTypedArray = defaultValue(options.loadTypedArray, false);

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.gltf", gltf);
    Check.typeOf.object("options.gltfResource", gltfResource);
    Check.typeOf.object("options.baseResource", baseResource);

    const hasBufferViewId = defined(bufferViewId);
    const hasDraco = defined(draco);
    const hasAttributeSemantic = defined(attributeSemantic);

    if (hasBufferViewId === hasDraco) {
      throw new DeveloperError(
        "One of options.bufferViewId and options.draco must be defined."
      );
    }

    if (hasDraco && !hasAttributeSemantic) {
      throw new DeveloperError(
        "When options.draco is defined options.attributeSemantic must also be defined."
      );
    }

    if (hasDraco) {
      Check.typeOf.object("options.draco", draco);
      Check.typeOf.string("options.attributeSemantic", attributeSemantic);
    }

    if (!loadBuffer && !loadTypedArray) {
      throw new DeveloperError(
        "At least one of loadBuffer and loadTypedArray must be true."
      );
    }
    //>>includeEnd('debug');

    let cacheKeySuffix = "";
    if (dequantize) {
      cacheKeySuffix += "-dequantize";
    }

    if (loadBuffer) {
      cacheKeySuffix += "-buffer";
    }

    if (loadTypedArray) {
      cacheKeySuffix += "-typed-array";
    }

    if (defined(draco)) {
      const dracoCacheKey = getDracoCacheKey(
        gltf,
        draco,
        gltfResource,
        baseResource
      );
      return `vertex-buffer:${dracoCacheKey}-draco-${attributeSemantic}${cacheKeySuffix}`;
    }

    const bufferView = gltf.bufferViews[bufferViewId];
    const bufferId = bufferView.buffer;
    const buffer = gltf.buffers[bufferId];

    const bufferCacheKey = getBufferCacheKey(
      buffer,
      bufferId,
      gltfResource,
      baseResource
    );

    const bufferViewCacheKey = getBufferViewCacheKey(bufferView);

    return `vertex-buffer:${bufferCacheKey}-range-${bufferViewCacheKey}${cacheKeySuffix}`;
  };

  /**
   * Gets the index buffer cache key.
   *
   * @param {Object} options Object with the following properties:
   * @param {Object} options.gltf The glTF JSON.
   * @param {Number} options.accessorId The accessor ID corresponding to the index buffer.
   * @param {Resource} options.gltfResource The {@link Resource} containing the glTF.
   * @param {Resource} options.baseResource The {@link Resource} that paths in the glTF JSON are relative to.
   * @param {Object} [options.draco] The Draco extension object.
   * @param {Boolean} [options.loadBuffer=false] Load index buffer as a GPU index buffer.
   * @param {Boolean} [options.loadTypedArray=false] Load index buffer as a typed array.
   *
   * @returns {String} The index buffer cache key.
   * @private
   */
  ResourceCacheKey.getIndexBufferCacheKey = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const gltf = options.gltf;
    const accessorId = options.accessorId;
    const gltfResource = options.gltfResource;
    const baseResource = options.baseResource;
    const draco = options.draco;
    const loadBuffer = defaultValue(options.loadBuffer, false);
    const loadTypedArray = defaultValue(options.loadTypedArray, false);

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.gltf", gltf);
    Check.typeOf.number("options.accessorId", accessorId);
    Check.typeOf.object("options.gltfResource", gltfResource);
    Check.typeOf.object("options.baseResource", baseResource);
    if (!loadBuffer && !loadTypedArray) {
      throw new DeveloperError(
        "At least one of loadBuffer and loadTypedArray must be true."
      );
    }
    //>>includeEnd('debug');

    let cacheKeySuffix = "";
    if (loadBuffer) {
      cacheKeySuffix += "-buffer";
    }

    if (loadTypedArray) {
      cacheKeySuffix += "-typed-array";
    }

    if (defined(draco)) {
      const dracoCacheKey = getDracoCacheKey(
        gltf,
        draco,
        gltfResource,
        baseResource
      );
      return `index-buffer:${dracoCacheKey}-draco${cacheKeySuffix}`;
    }

    const accessor = gltf.accessors[accessorId];
    const bufferViewId = accessor.bufferView;
    const bufferView = gltf.bufferViews[bufferViewId];
    const bufferId = bufferView.buffer;
    const buffer = gltf.buffers[bufferId];

    const bufferCacheKey = getBufferCacheKey(
      buffer,
      bufferId,
      gltfResource,
      baseResource
    );

    const accessorCacheKey = getAccessorCacheKey(accessor, bufferView);

    return `index-buffer:${bufferCacheKey}-accessor-${accessorCacheKey}${cacheKeySuffix}`;
  };

  /**
   * Gets the image cache key.
   *
   * @param {Object} options Object with the following properties:
   * @param {Object} options.gltf The glTF JSON.
   * @param {Number} options.imageId The image ID.
   * @param {Resource} options.gltfResource The {@link Resource} containing the glTF.
   * @param {Resource} options.baseResource The {@link Resource} that paths in the glTF JSON are relative to.
   *
   * @returns {String} The image cache key.
   * @private
   */
  ResourceCacheKey.getImageCacheKey = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const gltf = options.gltf;
    const imageId = options.imageId;
    const gltfResource = options.gltfResource;
    const baseResource = options.baseResource;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.gltf", gltf);
    Check.typeOf.number("options.imageId", imageId);
    Check.typeOf.object("options.gltfResource", gltfResource);
    Check.typeOf.object("options.baseResource", baseResource);
    //>>includeEnd('debug');

    const imageCacheKey = getImageCacheKey(
      gltf,
      imageId,
      gltfResource,
      baseResource
    );

    return `image:${imageCacheKey}`;
  };

  /**
   * Gets the texture cache key.
   *
   * @param {Object} options Object with the following properties:
   * @param {Object} options.gltf The glTF JSON.
   * @param {Object} options.textureInfo The texture info object.
   * @param {Resource} options.gltfResource The {@link Resource} containing the glTF.
   * @param {Resource} options.baseResource The {@link Resource} that paths in the glTF JSON are relative to.
   * @param {SupportedImageFormats} options.supportedImageFormats The supported image formats.
   *
   * @returns {String} The texture cache key.
   * @private
   */
  ResourceCacheKey.getTextureCacheKey = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const gltf = options.gltf;
    const textureInfo = options.textureInfo;
    const gltfResource = options.gltfResource;
    const baseResource = options.baseResource;
    const supportedImageFormats = options.supportedImageFormats;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.gltf", gltf);
    Check.typeOf.object("options.textureInfo", textureInfo);
    Check.typeOf.object("options.gltfResource", gltfResource);
    Check.typeOf.object("options.baseResource", baseResource);
    Check.typeOf.object("options.supportedImageFormats", supportedImageFormats);
    //>>includeEnd('debug');

    const textureId = textureInfo.index;

    const imageId = GltfLoaderUtil.getImageIdFromTexture({
      gltf: gltf,
      textureId: textureId,
      supportedImageFormats: supportedImageFormats,
    });

    const imageCacheKey = getImageCacheKey(
      gltf,
      imageId,
      gltfResource,
      baseResource
    );

    // Include the sampler cache key in the texture cache key since textures and
    // samplers are coupled in WebGL 1. When upgrading to WebGL 2 consider
    // removing the sampleCacheKey here.
    const samplerCacheKey = getSamplerCacheKey(gltf, textureInfo);

    return `texture:${imageCacheKey}-sampler-${samplerCacheKey}`;
  };

  /**
   * Statistics for the GPU and CPU memory used by the models loaded through the
   * {@link ResourceCache}.
   *
   * @alias ResourceCacheStatistics
   * @constructor
   *
   * @private
   */
  function ResourceCacheStatistics() {
    /**
     * The size of vertex buffers and index buffers loaded in the cache in bytes.
     *
     * @type {Number}
     * @private
     */
    this.geometryByteLength = 0;

    /**
     * The size of all textures loaded in the cache in bytes
     *
     * @type {Number}
     * @private
     */
    this.texturesByteLength = 0;

    // Track the sizes of resources by cache key. This is important so
    // removeLoader() can decrement the counts correctly.
    this._geometrySizes = {};
    this._textureSizes = {};
  }

  /**
   * Reset the memory counts
   *
   * @private
   */
  ResourceCacheStatistics.prototype.clear = function () {
    this.geometryByteLength = 0;
    this.texturesByteLength = 0;

    this._geometrySizes = {};
    this._textureSizes = {};
  };

  /**
   * Track the resources for a vertex or index buffer loader. This is implemented
   * asynchronously since resources may not be immediately available to count.
   * This method handles the following cases gracefully:
   * <ul>
   *   <li>If the loader is added twice, its resources will not be double-counted</li>
   *   <li>If the geometry has a CPU copy of the GPU buffer, it will be added to the count</li>
   *   <li>If the resource loading failed, its resources will not be counted</li>
   *   <li>If removeLoader() was called before the loader promise resolves, its resources will not be counted</li>
   * </ul>
   * @param {GltfVertexBufferLoader|GltfIndexBufferLoader} loader The geometry buffer with resources to track
   * @returns {Promise} A promise that resolves once the count is updated.
   *
   * @private
   */
  ResourceCacheStatistics.prototype.addGeometryLoader = function (loader) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("loader", loader);
    //>>includeEnd('debug');

    const cacheKey = loader.cacheKey;

    // Don't double count the same resource.
    if (this._geometrySizes.hasOwnProperty(cacheKey)) {
      return;
    }

    this._geometrySizes[cacheKey] = 0;

    const that = this;
    return loader.promise
      .then(function (loader) {
        // loader was unloaded before its promise resolved
        if (!that._geometrySizes.hasOwnProperty(cacheKey)) {
          return;
        }

        const buffer = loader.buffer;
        const typedArray = loader.typedArray;

        let totalSize = 0;

        if (defined(buffer)) {
          totalSize += buffer.sizeInBytes;
        }

        if (defined(typedArray)) {
          totalSize += typedArray.byteLength;
        }

        that.geometryByteLength += totalSize;
        that._geometrySizes[cacheKey] = totalSize;
      })
      .catch(function () {
        // If the resource failed to load, remove it from the cache
        delete that._geometrySizes[cacheKey];
      });
  };

  /**
   * Track the resources for a texture loader. This is implemented
   * asynchronously since resources may not be immediately available to count.
   * This method handles the following cases gracefully:
   * <ul>
   *   <li>If the loader is added twice, its resources will not be double-counted</li>
   *   <li>If the resource loading failed, its resources will not be counted</li>
   *   <li>If removeLoader() was called before the loader promise resolves, its resources will not be counted</li>
   * </ul>
   * @param {GltfTextureLoader} loader The texture loader with resources to track
   * @returns {Promise} A promise that resolves once the count is updated.
   *
   * @private
   */
  ResourceCacheStatistics.prototype.addTextureLoader = function (loader) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("loader", loader);
    //>>includeEnd('debug');

    const cacheKey = loader.cacheKey;

    // Don't double count the same resource.
    if (this._textureSizes.hasOwnProperty(cacheKey)) {
      return;
    }

    this._textureSizes[cacheKey] = 0;

    const that = this;
    return loader.promise
      .then(function (loader) {
        // loader was unloaded before its promise resolved
        if (!that._textureSizes.hasOwnProperty(cacheKey)) {
          return;
        }

        const totalSize = loader.texture.sizeInBytes;
        that.texturesByteLength += loader.texture.sizeInBytes;
        that._textureSizes[cacheKey] = totalSize;
      })
      .catch(function () {
        delete that._textureSizes[cacheKey];
      });
  };

  /**
   * Remove a loader's resources from the memory count. The loader's cache key
   * is used to determine information about the resource, so this method can
   * be used both for geometry and textures. If the loader does not have any
   * tracked resources, this is a no-op.
   * @param {ResourceLoader} loader The resource loader to remove from the cache
   *
   * @private
   */
  ResourceCacheStatistics.prototype.removeLoader = function (loader) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("loader", loader);
    //>>includeEnd('debug');

    const cacheKey = loader.cacheKey;
    const geometrySize = this._geometrySizes[cacheKey];
    delete this._geometrySizes[cacheKey];

    if (defined(geometrySize)) {
      this.geometryByteLength -= geometrySize;
    }

    const textureSize = this._textureSizes[cacheKey];
    delete this._textureSizes[cacheKey];

    if (defined(textureSize)) {
      this.texturesByteLength -= textureSize;
    }
  };

  /**
   * Cache for resources shared across 3D Tiles and glTF.
   *
   * @namespace ResourceCache
   *
   * @private
   */
  function ResourceCache() {}

  ResourceCache.cacheEntries = {};

  // Statistics about binary data stored in the resource cache
  ResourceCache.statistics = new ResourceCacheStatistics();

  /**
   * A reference-counted cache entry.
   *
   * @param {ResourceLoader} resourceLoader The resource.
   *
   * @alias CacheEntry
   * @constructor
   *
   * @private
   */
  function CacheEntry(resourceLoader) {
    this.referenceCount = 1;
    this.resourceLoader = resourceLoader;

    // For unit testing only
    this._statisticsPromise = undefined;
  }

  /**
   * Gets a resource from the cache. If the resource exists its reference count is
   * incremented. Otherwise, if no resource loader exists, undefined is returned.
   *
   * @param {String} cacheKey The cache key of the resource.
   *
   * @returns {ResourceLoader|undefined} The resource.
   * @private
   */
  ResourceCache.get = function (cacheKey) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("cacheKey", cacheKey);
    //>>includeEnd('debug');

    const cacheEntry = ResourceCache.cacheEntries[cacheKey];
    if (defined(cacheEntry)) {
      ++cacheEntry.referenceCount;
      return cacheEntry.resourceLoader;
    }
    return undefined;
  };

  /**
   * Loads a resource and adds it to the cache.
   *
   * @param {Object} options Object with the following properties:
   * @param {ResourceLoader} options.resourceLoader The resource.
   *
   * @exception {DeveloperError} Resource with this cacheKey is already in the cach
   * @private
   */
  ResourceCache.load = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const resourceLoader = options.resourceLoader;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.resourceLoader", resourceLoader);
    //>>includeEnd('debug');

    const cacheKey = resourceLoader.cacheKey;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("options.resourceLoader.cacheKey", cacheKey);

    if (defined(ResourceCache.cacheEntries[cacheKey])) {
      throw new DeveloperError(
        `Resource with this cacheKey is already in the cache: ${cacheKey}`
      );
    }
    //>>includeEnd('debug');

    ResourceCache.cacheEntries[cacheKey] = new CacheEntry(resourceLoader);

    resourceLoader.load();
  };

  /**
   * Unloads a resource from the cache. When the reference count hits zero the
   * resource is destroyed.
   *
   * @param {ResourceLoader} resourceLoader The resource.
   *
   * @exception {DeveloperError} Resource is not in the cache.
   * @exception {DeveloperError} Cannot unload resource that has no references.
   * @private
   */
  ResourceCache.unload = function (resourceLoader) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("resourceLoader", resourceLoader);
    //>>includeEnd('debug');

    const cacheKey = resourceLoader.cacheKey;
    const cacheEntry = ResourceCache.cacheEntries[cacheKey];

    //>>includeStart('debug', pragmas.debug);
    if (!defined(cacheEntry)) {
      throw new DeveloperError(`Resource is not in the cache: ${cacheKey}`);
    }
    //>>includeEnd('debug');

    --cacheEntry.referenceCount;

    if (cacheEntry.referenceCount === 0) {
      ResourceCache.statistics.removeLoader(resourceLoader);
      resourceLoader.destroy();
      delete ResourceCache.cacheEntries[cacheKey];
    }
  };

  /**
   * Loads a schema from the cache.
   *
   * @param {Object} options Object with the following properties:
   * @param {Object} [options.schema] An object that explicitly defines a schema JSON. Mutually exclusive with options.resource.
   * @param {Resource} [options.resource] The {@link Resource} pointing to the schema JSON. Mutually exclusive with options.schema.
   *
   * @returns {MetadataSchemaLoader} The schema resource.
   *
   * @exception {DeveloperError} One of options.schema and options.resource must be defined.
   * @private
   */
  ResourceCache.loadSchema = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const schema = options.schema;
    const resource = options.resource;

    //>>includeStart('debug', pragmas.debug);
    if (defined(schema) === defined(resource)) {
      throw new DeveloperError(
        "One of options.schema and options.resource must be defined."
      );
    }
    //>>includeEnd('debug');

    const cacheKey = ResourceCacheKey.getSchemaCacheKey({
      schema: schema,
      resource: resource,
    });

    let schemaLoader = ResourceCache.get(cacheKey);
    if (defined(schemaLoader)) {
      return schemaLoader;
    }

    schemaLoader = new MetadataSchemaLoader({
      schema: schema,
      resource: resource,
      cacheKey: cacheKey,
    });

    ResourceCache.load({
      resourceLoader: schemaLoader,
    });

    return schemaLoader;
  };

  /**
   * Load an embedded buffer from the cache.
   *
   * @param {Object} options Object with the following properties:
   * @param {Resource} options.parentResource The {@link Resource} containing the embedded buffer.
   * @param {Number} options.bufferId A unique identifier of the embedded buffer within the parent resource.
   * @param {Uint8Array} [options.typedArray] The typed array containing the embedded buffer contents.
   *
   * @returns {BufferLoader} The buffer loader.
   * @private
   */
  ResourceCache.loadEmbeddedBuffer = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const parentResource = options.parentResource;
    const bufferId = options.bufferId;
    const typedArray = options.typedArray;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.parentResource", parentResource);
    Check.typeOf.number("options.bufferId", bufferId);
    //>>includeEnd('debug');

    const cacheKey = ResourceCacheKey.getEmbeddedBufferCacheKey({
      parentResource: parentResource,
      bufferId: bufferId,
    });

    let bufferLoader = ResourceCache.get(cacheKey);
    if (defined(bufferLoader)) {
      return bufferLoader;
    }

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.typedArray", typedArray);
    //>>includeEnd('debug');

    bufferLoader = new BufferLoader({
      typedArray: typedArray,
      cacheKey: cacheKey,
    });

    ResourceCache.load({
      resourceLoader: bufferLoader,
    });

    return bufferLoader;
  };

  /**
   * Loads an external buffer from the cache.
   *
   * @param {Object} options Object with the following properties:
   * @param {Resource} options.resource The {@link Resource} pointing to the external buffer.
   *
   * @returns {BufferLoader} The buffer loader.
   * @private
   */
  ResourceCache.loadExternalBuffer = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const resource = options.resource;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.resource", resource);
    //>>includeEnd('debug');

    const cacheKey = ResourceCacheKey.getExternalBufferCacheKey({
      resource: resource,
    });

    let bufferLoader = ResourceCache.get(cacheKey);
    if (defined(bufferLoader)) {
      return bufferLoader;
    }

    bufferLoader = new BufferLoader({
      resource: resource,
      cacheKey: cacheKey,
    });

    ResourceCache.load({
      resourceLoader: bufferLoader,
    });

    return bufferLoader;
  };

  /**
   * Loads a glTF JSON from the cache.
   *
   * @param {Object} options Object with the following properties:
   * @param {Resource} options.gltfResource The {@link Resource} containing the glTF.
   * @param {Resource} options.baseResource The {@link Resource} that paths in the glTF JSON are relative to.
   * @param {Uint8Array} [options.typedArray] The typed array containing the glTF contents.
   * @param {Object} [options.gltfJson] The parsed glTF JSON contents.
   *
   * @returns {GltfJsonLoader} The glTF JSON.
   * @private
   */
  ResourceCache.loadGltfJson = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const gltfResource = options.gltfResource;
    const baseResource = options.baseResource;
    const typedArray = options.typedArray;
    const gltfJson = options.gltfJson;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.gltfResource", gltfResource);
    Check.typeOf.object("options.baseResource", baseResource);
    //>>includeEnd('debug');

    const cacheKey = ResourceCacheKey.getGltfCacheKey({
      gltfResource: gltfResource,
    });

    let gltfJsonLoader = ResourceCache.get(cacheKey);
    if (defined(gltfJsonLoader)) {
      return gltfJsonLoader;
    }

    gltfJsonLoader = new GltfJsonLoader({
      resourceCache: ResourceCache,
      gltfResource: gltfResource,
      baseResource: baseResource,
      typedArray: typedArray,
      gltfJson: gltfJson,
      cacheKey: cacheKey,
    });

    ResourceCache.load({
      resourceLoader: gltfJsonLoader,
    });

    return gltfJsonLoader;
  };

  /**
   * Loads a glTF buffer view from the cache.
   *
   * @param {Object} options Object with the following properties:
   * @param {Object} options.gltf The glTF JSON.
   * @param {Number} options.bufferViewId The bufferView ID.
   * @param {Resource} options.gltfResource The {@link Resource} containing the glTF.
   * @param {Resource} options.baseResource The {@link Resource} that paths in the glTF JSON are relative to.
   *
   * @returns {GltfBufferViewLoader} The buffer view loader.
   * @private
   */
  ResourceCache.loadBufferView = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const gltf = options.gltf;
    const bufferViewId = options.bufferViewId;
    const gltfResource = options.gltfResource;
    const baseResource = options.baseResource;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.gltf", gltf);
    Check.typeOf.number("options.bufferViewId", bufferViewId);
    Check.typeOf.object("options.gltfResource", gltfResource);
    Check.typeOf.object("options.baseResource", baseResource);
    //>>includeEnd('debug');

    const cacheKey = ResourceCacheKey.getBufferViewCacheKey({
      gltf: gltf,
      bufferViewId: bufferViewId,
      gltfResource: gltfResource,
      baseResource: baseResource,
    });

    let bufferViewLoader = ResourceCache.get(cacheKey);
    if (defined(bufferViewLoader)) {
      return bufferViewLoader;
    }

    bufferViewLoader = new GltfBufferViewLoader({
      resourceCache: ResourceCache,
      gltf: gltf,
      bufferViewId: bufferViewId,
      gltfResource: gltfResource,
      baseResource: baseResource,
      cacheKey: cacheKey,
    });

    ResourceCache.load({
      resourceLoader: bufferViewLoader,
    });

    return bufferViewLoader;
  };

  /**
   * Loads Draco data from the cache.
   *
   * @param {Object} options Object with the following properties:
   * @param {Object} options.gltf The glTF JSON.
   * @param {Object} options.draco The Draco extension object.
   * @param {Resource} options.gltfResource The {@link Resource} containing the glTF.
   * @param {Resource} options.baseResource The {@link Resource} that paths in the glTF JSON are relative to.
   *
   * @returns {GltfDracoLoader} The Draco loader.
   * @private
   */
  ResourceCache.loadDraco = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const gltf = options.gltf;
    const draco = options.draco;
    const gltfResource = options.gltfResource;
    const baseResource = options.baseResource;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.gltf", gltf);
    Check.typeOf.object("options.draco", draco);
    Check.typeOf.object("options.gltfResource", gltfResource);
    Check.typeOf.object("options.baseResource", baseResource);
    //>>includeEnd('debug');

    const cacheKey = ResourceCacheKey.getDracoCacheKey({
      gltf: gltf,
      draco: draco,
      gltfResource: gltfResource,
      baseResource: baseResource,
    });

    let dracoLoader = ResourceCache.get(cacheKey);
    if (defined(dracoLoader)) {
      return dracoLoader;
    }

    dracoLoader = new GltfDracoLoader({
      resourceCache: ResourceCache,
      gltf: gltf,
      draco: draco,
      gltfResource: gltfResource,
      baseResource: baseResource,
      cacheKey: cacheKey,
    });

    ResourceCache.load({
      resourceLoader: dracoLoader,
    });

    return dracoLoader;
  };

  /**
   * Loads a glTF vertex buffer from the cache.
   *
   * @param {Object} options Object with the following properties:
   * @param {Object} options.gltf The glTF JSON.
   * @param {Resource} options.gltfResource The {@link Resource} containing the glTF.
   * @param {Resource} options.baseResource The {@link Resource} that paths in the glTF JSON are relative to.
   * @param {Number} [options.bufferViewId] The bufferView ID corresponding to the vertex buffer.
   * @param {Object} [options.draco] The Draco extension object.
   * @param {String} [options.attributeSemantic] The attribute semantic, e.g. POSITION or NORMAL.
   * @param {Number} [options.accessorId] The accessor ID.
   * @param {Boolean} [options.asynchronous=true] Determines if WebGL resource creation will be spread out over several frames or block until all WebGL resources are created.
   * @param {Boolean} [options.dequantize=false] Determines whether or not the vertex buffer will be dequantized on the CPU.
   * @param {Boolean} [options.loadBuffer=false] Load vertex buffer as a GPU vertex buffer.
   * @param {Boolean} [options.loadTypedArray=false] Load vertex buffer as a typed array.
   * @exception {DeveloperError} One of options.bufferViewId and options.draco must be defined.
   * @exception {DeveloperError} When options.draco is defined options.attributeSemantic must also be defined.
   * @exception {DeveloperError} When options.draco is defined options.accessorId must also be defined.
   *
   * @returns {GltfVertexBufferLoader} The vertex buffer loader.
   * @private
   */
  ResourceCache.loadVertexBuffer = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const gltf = options.gltf;
    const gltfResource = options.gltfResource;
    const baseResource = options.baseResource;
    const bufferViewId = options.bufferViewId;
    const draco = options.draco;
    const attributeSemantic = options.attributeSemantic;
    const accessorId = options.accessorId;
    const asynchronous = defaultValue(options.asynchronous, true);
    const dequantize = defaultValue(options.dequantize, false);
    const loadBuffer = defaultValue(options.loadBuffer, false);
    const loadTypedArray = defaultValue(options.loadTypedArray, false);

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.gltf", gltf);
    Check.typeOf.object("options.gltfResource", gltfResource);
    Check.typeOf.object("options.baseResource", baseResource);
    if (!loadBuffer && !loadTypedArray) {
      throw new DeveloperError(
        "At least one of loadBuffer and loadTypedArray must be true."
      );
    }

    const hasBufferViewId = defined(bufferViewId);
    const hasDraco = defined(draco);
    const hasAttributeSemantic = defined(attributeSemantic);
    const hasAccessorId = defined(accessorId);

    if (hasBufferViewId === hasDraco) {
      throw new DeveloperError(
        "One of options.bufferViewId and options.draco must be defined."
      );
    }

    if (hasDraco && !hasAttributeSemantic) {
      throw new DeveloperError(
        "When options.draco is defined options.attributeSemantic must also be defined."
      );
    }

    if (hasDraco && !hasAccessorId) {
      throw new DeveloperError(
        "When options.draco is defined options.haAccessorId must also be defined."
      );
    }

    if (hasDraco) {
      Check.typeOf.object("options.draco", draco);
      Check.typeOf.string("options.attributeSemantic", attributeSemantic);
      Check.typeOf.number("options.accessorId", accessorId);
    }
    //>>includeEnd('debug');

    const cacheKey = ResourceCacheKey.getVertexBufferCacheKey({
      gltf: gltf,
      gltfResource: gltfResource,
      baseResource: baseResource,
      bufferViewId: bufferViewId,
      draco: draco,
      attributeSemantic: attributeSemantic,
      dequantize: dequantize,
      loadBuffer: loadBuffer,
      loadTypedArray: loadTypedArray,
    });

    let vertexBufferLoader = ResourceCache.get(cacheKey);
    if (defined(vertexBufferLoader)) {
      return vertexBufferLoader;
    }

    vertexBufferLoader = new GltfVertexBufferLoader({
      resourceCache: ResourceCache,
      gltf: gltf,
      gltfResource: gltfResource,
      baseResource: baseResource,
      bufferViewId: bufferViewId,
      draco: draco,
      attributeSemantic: attributeSemantic,
      accessorId: accessorId,
      cacheKey: cacheKey,
      asynchronous: asynchronous,
      dequantize: dequantize,
      loadBuffer: loadBuffer,
      loadTypedArray: loadTypedArray,
    });

    ResourceCache.load({
      resourceLoader: vertexBufferLoader,
    });

    const promise = ResourceCache.statistics.addGeometryLoader(
      vertexBufferLoader
    );

    // Needed for unit testing
    ResourceCache.cacheEntries[cacheKey]._statisticsPromise = promise;

    return vertexBufferLoader;
  };

  /**
   * Loads a glTF index buffer from the cache.
   *
   * @param {Object} options Object with the following properties:
   * @param {Object} options.gltf The glTF JSON.
   * @param {Number} options.accessorId The accessor ID corresponding to the index buffer.
   * @param {Resource} options.gltfResource The {@link Resource} containing the glTF.
   * @param {Resource} options.baseResource The {@link Resource} that paths in the glTF JSON are relative to.
   * @param {Object} [options.draco] The Draco extension object.
   * @param {Boolean} [options.asynchronous=true] Determines if WebGL resource creation will be spread out over several frames or block until all WebGL resources are created.
   * @param {Boolean} [options.loadBuffer=false] Load index buffer as a GPU index buffer.
   * @param {Boolean} [options.loadTypedArray=false] Load index buffer as a typed array.
   * @returns {GltfIndexBufferLoader} The index buffer loader.
   * @private
   */
  ResourceCache.loadIndexBuffer = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const gltf = options.gltf;
    const accessorId = options.accessorId;
    const gltfResource = options.gltfResource;
    const baseResource = options.baseResource;
    const draco = options.draco;
    const asynchronous = defaultValue(options.asynchronous, true);
    const loadBuffer = defaultValue(options.loadBuffer, false);
    const loadTypedArray = defaultValue(options.loadTypedArray, false);

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.gltf", gltf);
    Check.typeOf.number("options.accessorId", accessorId);
    Check.typeOf.object("options.gltfResource", gltfResource);
    Check.typeOf.object("options.baseResource", baseResource);
    if (!loadBuffer && !loadTypedArray) {
      throw new DeveloperError(
        "At least one of loadBuffer and loadTypedArray must be true."
      );
    }
    //>>includeEnd('debug');

    const cacheKey = ResourceCacheKey.getIndexBufferCacheKey({
      gltf: gltf,
      accessorId: accessorId,
      gltfResource: gltfResource,
      baseResource: baseResource,
      draco: draco,
      loadBuffer: loadBuffer,
      loadTypedArray: loadTypedArray,
    });

    let indexBufferLoader = ResourceCache.get(cacheKey);
    if (defined(indexBufferLoader)) {
      return indexBufferLoader;
    }

    indexBufferLoader = new GltfIndexBufferLoader({
      resourceCache: ResourceCache,
      gltf: gltf,
      accessorId: accessorId,
      gltfResource: gltfResource,
      baseResource: baseResource,
      draco: draco,
      cacheKey: cacheKey,
      asynchronous: asynchronous,
      loadBuffer: loadBuffer,
      loadTypedArray: loadTypedArray,
    });

    ResourceCache.load({
      resourceLoader: indexBufferLoader,
    });
    const promise = ResourceCache.statistics.addGeometryLoader(indexBufferLoader);

    // Needed for unit testing
    ResourceCache.cacheEntries[cacheKey]._statisticsPromise = promise;

    return indexBufferLoader;
  };

  /**
   * Loads a glTF image from the cache.
   *
   * @param {Object} options Object with the following properties:
   * @param {Object} options.gltf The glTF JSON.
   * @param {Number} options.imageId The image ID.
   * @param {Resource} options.gltfResource The {@link Resource} containing the glTF.
   * @param {Resource} options.baseResource The {@link Resource} that paths in the glTF JSON are relative to.
   *
   * @returns {GltfImageLoader} The image loader.
   * @private
   */
  ResourceCache.loadImage = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const gltf = options.gltf;
    const imageId = options.imageId;
    const gltfResource = options.gltfResource;
    const baseResource = options.baseResource;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.gltf", gltf);
    Check.typeOf.number("options.imageId", imageId);
    Check.typeOf.object("options.gltfResource", gltfResource);
    Check.typeOf.object("options.baseResource", baseResource);
    //>>includeEnd('debug');

    const cacheKey = ResourceCacheKey.getImageCacheKey({
      gltf: gltf,
      imageId: imageId,
      gltfResource: gltfResource,
      baseResource: baseResource,
    });

    let imageLoader = ResourceCache.get(cacheKey);
    if (defined(imageLoader)) {
      return imageLoader;
    }

    imageLoader = new GltfImageLoader({
      resourceCache: ResourceCache,
      gltf: gltf,
      imageId: imageId,
      gltfResource: gltfResource,
      baseResource: baseResource,
      cacheKey: cacheKey,
    });

    ResourceCache.load({
      resourceLoader: imageLoader,
    });

    return imageLoader;
  };

  /**
   * Loads a glTF texture from the cache.
   *
   * @param {Object} options Object with the following properties:
   * @param {Object} options.gltf The glTF JSON.
   * @param {Object} options.textureInfo The texture info object.
   * @param {Resource} options.gltfResource The {@link Resource} containing the glTF.
   * @param {Resource} options.baseResource The {@link Resource} that paths in the glTF JSON are relative to.
   * @param {SupportedImageFormats} options.supportedImageFormats The supported image formats.
   * @param {Boolean} [options.asynchronous=true] Determines if WebGL resource creation will be spread out over several frames or block until all WebGL resources are created.
   *
   * @returns {GltfTextureLoader} The texture loader.
   * @private
   */
  ResourceCache.loadTexture = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const gltf = options.gltf;
    const textureInfo = options.textureInfo;
    const gltfResource = options.gltfResource;
    const baseResource = options.baseResource;
    const supportedImageFormats = options.supportedImageFormats;
    const asynchronous = defaultValue(options.asynchronous, true);

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.gltf", gltf);
    Check.typeOf.object("options.textureInfo", textureInfo);
    Check.typeOf.object("options.gltfResource", gltfResource);
    Check.typeOf.object("options.baseResource", baseResource);
    //>>includeEnd('debug');

    const cacheKey = ResourceCacheKey.getTextureCacheKey({
      gltf: gltf,
      textureInfo: textureInfo,
      gltfResource: gltfResource,
      baseResource: baseResource,
      supportedImageFormats: supportedImageFormats,
    });

    let textureLoader = ResourceCache.get(cacheKey);
    if (defined(textureLoader)) {
      return textureLoader;
    }

    textureLoader = new GltfTextureLoader({
      resourceCache: ResourceCache,
      gltf: gltf,
      textureInfo: textureInfo,
      gltfResource: gltfResource,
      baseResource: baseResource,
      supportedImageFormats: supportedImageFormats,
      cacheKey: cacheKey,
      asynchronous: asynchronous,
    });

    ResourceCache.load({
      resourceLoader: textureLoader,
    });
    const promise = ResourceCache.statistics.addTextureLoader(textureLoader);

    // Needed for unit testing
    ResourceCache.cacheEntries[cacheKey]._statisticsPromise = promise;

    return textureLoader;
  };

  /**
   * Unload everything from the cache. This is used for unit testing.
   *
   * @private
   */
  ResourceCache.clearForSpecs = function () {
    // Unload in the order below. This prevents an unload function from unloading
    // a resource that has already been unloaded.
    const precedence = [
      GltfVertexBufferLoader,
      GltfIndexBufferLoader,
      GltfDracoLoader,
      GltfTextureLoader,
      GltfImageLoader,
      GltfBufferViewLoader,
      BufferLoader,
      MetadataSchemaLoader,
      GltfJsonLoader,
    ];

    let cacheKey;
    const cacheEntries = ResourceCache.cacheEntries;

    const cacheEntriesSorted = [];
    for (cacheKey in cacheEntries) {
      if (cacheEntries.hasOwnProperty(cacheKey)) {
        cacheEntriesSorted.push(cacheEntries[cacheKey]);
      }
    }

    cacheEntriesSorted.sort(function (a, b) {
      const indexA = precedence.indexOf(a.resourceLoader.constructor);
      const indexB = precedence.indexOf(b.resourceLoader.constructor);
      return indexA - indexB;
    });

    const cacheEntriesLength = cacheEntriesSorted.length;
    for (let i = 0; i < cacheEntriesLength; ++i) {
      const cacheEntry = cacheEntriesSorted[i];
      cacheKey = cacheEntry.resourceLoader.cacheKey;
      if (defined(cacheEntries[cacheKey])) {
        cacheEntry.resourceLoader.destroy();
        delete cacheEntries[cacheKey];
      }
    }

    ResourceCache.statistics.clear();
  };

  /**
   * An object representing a single subtree in an implicit tileset
   * including availability.
   * <p>
   * Subtrees handle tile metadata, defined in the subtree JSON in either
   * tileMetadata (3D Tiles 1.1) or the <code>3DTILES_metadata</code> extension.
   * Subtrees also handle content metadata and metadata about the subtree itself.
   * </p>
   *
   * @see {@link https://github.com/CesiumGS/3d-tiles/tree/main/extensions/3DTILES_metadata#implicit-tile-properties|Implicit Tile Properties in the 3DTILES_metadata specification}
   *
   * @alias ImplicitSubtree
   * @constructor
   *
   * @param {Resource} resource The resource for this subtree. This is used for fetching external buffers as needed.
   * @param {Object} [json] The JSON object for this subtree. Mutually exclusive with subtreeView.
   * @param {Uint8Array} [subtreeView] The contents of a subtree binary in a Uint8Array. Mutually exclusive with json.
   * @param {ImplicitTileset} implicitTileset The implicit tileset. This includes information about the size of subtrees
   * @param {ImplicitTileCoordinates} implicitCoordinates The coordinates of the subtree's root tile.
   *
   * @exception {DeveloperError} One of json and subtreeView must be defined.
   *
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function ImplicitSubtree(
    resource,
    json,
    subtreeView,
    implicitTileset,
    implicitCoordinates
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("resource", resource);
    if (defined(json) === defined(subtreeView)) {
      throw new DeveloperError("One of json and subtreeView must be defined.");
    }
    Check.typeOf.object("implicitTileset", implicitTileset);
    Check.typeOf.object("implicitCoordinates", implicitCoordinates);
    //>>includeEnd('debug');

    this._resource = resource;
    this._subtreeJson = undefined;
    this._bufferLoader = undefined;
    this._tileAvailability = undefined;
    this._contentAvailabilityBitstreams = [];
    this._childSubtreeAvailability = undefined;
    this._implicitCoordinates = implicitCoordinates;
    this._subtreeLevels = implicitTileset.subtreeLevels;
    this._subdivisionScheme = implicitTileset.subdivisionScheme;
    this._branchingFactor = implicitTileset.branchingFactor;

    // properties for metadata
    this._metadata = undefined;
    this._tileMetadataTable = undefined;
    this._tilePropertyTableJson = undefined;

    this._contentMetadataTables = [];
    this._contentPropertyTableJsons = [];

    // Jump buffers are maps of availability bit index to entity ID
    this._tileJumpBuffer = undefined;
    this._contentJumpBuffers = [];

    this._readyPromise = initialize$i(this, json, subtreeView, implicitTileset);
  }

  Object.defineProperties(ImplicitSubtree.prototype, {
    /**
     * A promise that resolves once all necessary availability buffers
     * are loaded.
     *
     * @type {Promise}
     * @readonly
     * @private
     */
    readyPromise: {
      get: function () {
        return this._readyPromise;
      },
    },

    /**
     * When subtree metadata is present (3D Tiles 1.1), this property stores an {@link ImplicitSubtreeMetadata} instance
     *
     * @type {ImplicitSubtreeMetadata}
     * @readonly
     * @private
     */
    metadata: {
      get: function () {
        return this._metadata;
      },
    },

    /**
     * When tile metadata is present (3D Tiles 1.1) or the <code>3DTILES_metadata</code> extension is used,
     * this property stores a {@link MetadataTable} instance for the tiles in the subtree.
     *
     * @type {MetadataTable}
     * @readonly
     * @private
     */
    tileMetadataTable: {
      get: function () {
        return this._tileMetadataTable;
      },
    },

    /**
     * When tile metadata is present (3D Tiles 1.1) or the <code>3DTILES_metadata</code> extension is used,
     * this property stores the JSON from the extension. This is used by {@link TileMetadata}
     * to get the extras and extensions for the tiles in the subtree.
     *
     * @type {Object}
     * @readonly
     * @private
     */
    tilePropertyTableJson: {
      get: function () {
        return this._tilePropertyTableJson;
      },
    },

    /**
     * When content metadata is present (3D Tiles 1.1), this property stores
     * an array of {@link MetadataTable} instances for the contents in the subtree.
     *
     * @type {Array}
     * @readonly
     * @private
     */
    contentMetadataTables: {
      get: function () {
        return this._contentMetadataTables;
      },
    },

    /**
     * When content metadata is present (3D Tiles 1.1), this property
     * an array of the JSONs from the extension. This is used to get the extras
     * and extensions for the contents in the subtree.
     *
     * @type {Array}
     * @readonly
     * @private
     */
    contentPropertyTableJsons: {
      get: function () {
        return this._contentPropertyTableJsons;
      },
    },

    /**
     * Gets the implicit tile coordinates for the root of the subtree.
     *
     * @type {ImplicitTileCoordinates}
     * @readonly
     * @private
     */
    implicitCoordinates: {
      get: function () {
        return this._implicitCoordinates;
      },
    },
  });

  /**
   * Check if a specific tile is available at an index of the tile availability bitstream
   *
   * @param {Number} index The index of the desired tile
   * @returns {Boolean} The value of the i-th bit
   * @private
   */
  ImplicitSubtree.prototype.tileIsAvailableAtIndex = function (index) {
    return this._tileAvailability.getBit(index);
  };

  /**
   * Check if a specific tile is available at an implicit tile coordinate
   *
   * @param {ImplicitTileCoordinates} implicitCoordinates The global coordinates of a tile
   * @returns {Boolean} The value of the i-th bit
   * @private
   */
  ImplicitSubtree.prototype.tileIsAvailableAtCoordinates = function (
    implicitCoordinates
  ) {
    const index = this.getTileIndex(implicitCoordinates);
    return this.tileIsAvailableAtIndex(index);
  };

  /**
   * Check if a specific tile's content is available at an index of the content availability bitstream
   *
   * @param {Number} index The index of the desired tile
   * @param {Number} [contentIndex=0] The index of the desired content when multiple contents are used.
   * @returns {Boolean} The value of the i-th bit
   * @private
   */
  ImplicitSubtree.prototype.contentIsAvailableAtIndex = function (
    index,
    contentIndex
  ) {
    contentIndex = defaultValue(contentIndex, 0);
    //>>includeStart('debug', pragmas.debug);
    if (
      contentIndex < 0 ||
      contentIndex >= this._contentAvailabilityBitstreams.length
    ) {
      throw new DeveloperError("contentIndex out of bounds.");
    }
    //>>includeEnd('debug');

    return this._contentAvailabilityBitstreams[contentIndex].getBit(index);
  };

  /**
   * Check if a specific tile's content is available at an implicit tile coordinate
   *
   * @param {ImplicitTileCoordinates} implicitCoordinates The global coordinates of a tile
   * @param {Number} [contentIndex=0] The index of the desired content when the <code>3DTILES_multiple_contents</code> extension is used.
   * @returns {Boolean} The value of the i-th bit
   * @private
   */
  ImplicitSubtree.prototype.contentIsAvailableAtCoordinates = function (
    implicitCoordinates,
    contentIndex
  ) {
    const index = this.getTileIndex(implicitCoordinates);
    return this.contentIsAvailableAtIndex(index, contentIndex);
  };

  /**
   * Check if a child subtree is available at an index of the child subtree availability bitstream
   *
   * @param {Number} index The index of the desired child subtree
   * @returns {Boolean} The value of the i-th bit
   * @private
   */
  ImplicitSubtree.prototype.childSubtreeIsAvailableAtIndex = function (index) {
    return this._childSubtreeAvailability.getBit(index);
  };

  /**
   * Check if a specific child subtree is available at an implicit tile coordinate
   *
   * @param {ImplicitTileCoordinates} implicitCoordinates The global coordinates of a child subtree
   * @returns {Boolean} The value of the i-th bit
   * @private
   */
  ImplicitSubtree.prototype.childSubtreeIsAvailableAtCoordinates = function (
    implicitCoordinates
  ) {
    const index = this.getChildSubtreeIndex(implicitCoordinates);
    return this.childSubtreeIsAvailableAtIndex(index);
  };

  /**
   * Get the index of the first node at the given level within this subtree.
   * e.g. for a quadtree:
   * <ul>
   * <li>Level 0 starts at index 0</li>
   * <li>Level 1 starts at index 1</li>
   * <li>Level 2 starts at index 5</li>
   * </ul>
   *
   * @param {Number} level The 0-indexed level number relative to the root of the subtree
   * @returns {Number} The first index at the desired level
   * @private
   */
  ImplicitSubtree.prototype.getLevelOffset = function (level) {
    const branchingFactor = this._branchingFactor;
    return (Math.pow(branchingFactor, level) - 1) / (branchingFactor - 1);
  };

  /**
   * Get the morton index of a tile's parent. This is equivalent to
   * chopping off the last 2 (quadtree) or 3 (octree) bits of the morton
   * index.
   *
   * @param {Number} childIndex The morton index of the child tile relative to its parent
   * @returns {Number} The index of the child's parent node
   * @private
   */
  ImplicitSubtree.prototype.getParentMortonIndex = function (mortonIndex) {
    let bitsPerLevel = 2;
    if (this._subdivisionScheme === ImplicitSubdivisionScheme$1.OCTREE) {
      bitsPerLevel = 3;
    }

    return mortonIndex >> bitsPerLevel;
  };

  /**
   * Parse all relevant information out of the subtree. This fetches any
   * external buffers that are used by the implicit tileset. When finished,
   * it resolves/rejects subtree.readyPromise.
   *
   * @param {ImplicitSubtree} subtree The subtree
   * @param {Object} [json] The JSON object for this subtree. If parsing from a binary subtree file, this will be undefined.
   * @param {Uint8Array} [subtreeView] The contents of the subtree binary
   * @param {ImplicitTileset} implicitTileset The implicit tileset this subtree belongs to.
   * @private
   */
  function initialize$i(subtree, json, subtreeView, implicitTileset) {
    let chunks;
    if (defined(json)) {
      chunks = {
        json: json,
        binary: undefined,
      };
    } else {
      chunks = parseSubtreeChunks(subtreeView);
    }

    const subtreeJson = chunks.json;
    subtree._subtreeJson = subtreeJson;

    let tilePropertyTableJson;
    if (hasExtension(subtreeJson, "3DTILES_metadata")) {
      tilePropertyTableJson = subtreeJson.extensions["3DTILES_metadata"];
    } else if (defined(subtreeJson.tileMetadata)) {
      const propertyTableIndex = subtreeJson.tileMetadata;
      tilePropertyTableJson = subtreeJson.propertyTables[propertyTableIndex];
    }

    const contentPropertyTableJsons = [];
    if (defined(subtreeJson.contentMetadata)) {
      const length = subtreeJson.contentMetadata.length;
      for (let i = 0; i < length; i++) {
        const propertyTableIndex = subtreeJson.contentMetadata[i];
        contentPropertyTableJsons.push(
          subtreeJson.propertyTables[propertyTableIndex]
        );
      }
    }

    let metadata;
    const schema = implicitTileset.metadataSchema;
    const subtreeMetadata = subtreeJson.subtreeMetadata;
    if (defined(subtreeMetadata)) {
      const metadataClass = subtreeMetadata.class;
      const subtreeMetadataClass = schema.classes[metadataClass];
      metadata = new ImplicitSubtreeMetadata({
        subtreeMetadata: subtreeMetadata,
        class: subtreeMetadataClass,
      });
    }

    subtree._metadata = metadata;
    subtree._tilePropertyTableJson = tilePropertyTableJson;
    subtree._contentPropertyTableJsons = contentPropertyTableJsons;

    // if no contentAvailability is specified, no tile in the subtree has
    // content
    const defaultContentAvailability = {
      constant: 0,
    };

    // In 3D Tiles 1.1, content availability is provided in an array in the subtree JSON
    // regardless of whether or not it contains multiple contents. This differs from previous
    // schemas, where content availability is either a single object in the subtree JSON or
    // as an array in the 3DTILES_multiple_contents extension.
    //
    // After identifying how availability is stored, put the results in this new array for consistent processing later
    subtreeJson.contentAvailabilityHeaders = [];
    if (hasExtension(subtreeJson, "3DTILES_multiple_contents")) {
      subtreeJson.contentAvailabilityHeaders =
        subtreeJson.extensions["3DTILES_multiple_contents"].contentAvailability;
    } else if (Array.isArray(subtreeJson.contentAvailability)) {
      subtreeJson.contentAvailabilityHeaders = subtreeJson.contentAvailability;
    } else {
      subtreeJson.contentAvailabilityHeaders.push(
        defaultValue(subtreeJson.contentAvailability, defaultContentAvailability)
      );
    }

    const bufferHeaders = preprocessBuffers(subtreeJson.buffers);
    const bufferViewHeaders = preprocessBufferViews(
      subtreeJson.bufferViews,
      bufferHeaders
    );

    // Buffers and buffer views are inactive until explicitly marked active.
    // This way we can avoid fetching buffers that will not be used.
    markActiveBufferViews(subtreeJson, bufferViewHeaders);
    if (defined(tilePropertyTableJson)) {
      markActiveMetadataBufferViews(tilePropertyTableJson, bufferViewHeaders);
    }

    for (let i = 0; i < contentPropertyTableJsons.length; i++) {
      const contentPropertyTableJson = contentPropertyTableJsons[i];
      markActiveMetadataBufferViews(contentPropertyTableJson, bufferViewHeaders);
    }

    return requestActiveBuffers(subtree, bufferHeaders, chunks.binary).then(
      function (buffersU8) {
        const bufferViewsU8 = parseActiveBufferViews(
          bufferViewHeaders,
          buffersU8
        );
        parseAvailability(subtree, subtreeJson, implicitTileset, bufferViewsU8);

        if (defined(tilePropertyTableJson)) {
          parseTileMetadataTable(subtree, implicitTileset, bufferViewsU8);
          makeTileJumpBuffer(subtree);
        }

        parseContentMetadataTables(subtree, implicitTileset, bufferViewsU8);
        makeContentJumpBuffers(subtree);

        return subtree;
      }
    );
  }

  /**
   * A helper object for storing the two parts of the subtree binary
   *
   * @typedef {Object} SubtreeChunks
   * @property {Object} json The json chunk of the subtree
   * @property {Uint8Array} binary The binary chunk of the subtree. This represents the internal buffer.
   * @private
   */

  /**
   * Given the binary contents of a subtree, split into JSON and binary chunks
   *
   * @param {Uint8Array} subtreeView The subtree binary
   * @returns {SubtreeChunks} An object containing the JSON and binary chunks.
   * @private
   */
  function parseSubtreeChunks(subtreeView) {
    // Parse the header
    const littleEndian = true;
    const subtreeReader = new DataView(
      subtreeView.buffer,
      subtreeView.byteOffset
    );
    // Skip to the chunk lengths
    let byteOffset = 8;

    // Read the bottom 32 bits of the 64-bit byte length. This is ok for now because:
    // 1) not all browsers have native 64-bit operations
    // 2) the data is well under 4GB
    const jsonByteLength = subtreeReader.getUint32(byteOffset, littleEndian);
    byteOffset += 8;
    const binaryByteLength = subtreeReader.getUint32(byteOffset, littleEndian);
    byteOffset += 8;

    const subtreeJson = getJsonFromTypedArray(
      subtreeView,
      byteOffset,
      jsonByteLength
    );
    byteOffset += jsonByteLength;
    const subtreeBinary = subtreeView.subarray(
      byteOffset,
      byteOffset + binaryByteLength
    );

    return {
      json: subtreeJson,
      binary: subtreeBinary,
    };
  }

  /**
   * A buffer header is the JSON header from the subtree JSON chunk plus
   * a couple extra boolean flags for easy reference.
   *
   * Buffers are assumed inactive until explicitly marked active. This is used
   * to avoid fetching unneeded buffers.
   *
   * @typedef {Object} BufferHeader
   * @property {Boolean} isExternal True if this is an external buffer
   * @property {Boolean} isActive Whether this buffer is currently used.
   * @property {String} [uri] The URI of the buffer (external buffers only)
   * @property {Number} byteLength The byte length of the buffer, including any padding contained within.
   * @private
   */

  /**
   * Iterate over the list of buffers from the subtree JSON and add the
   * isExternal and isActive fields for easier parsing later. This modifies
   * the objects in place.
   *
   * @param {Object[]} [bufferHeaders=[]] The JSON from subtreeJson.buffers.
   * @returns {BufferHeader[]} The same array of headers with additional fields.
   * @private
   */
  function preprocessBuffers(bufferHeaders) {
    bufferHeaders = defined(bufferHeaders) ? bufferHeaders : [];
    for (let i = 0; i < bufferHeaders.length; i++) {
      const bufferHeader = bufferHeaders[i];
      bufferHeader.isExternal = defined(bufferHeader.uri);
      bufferHeader.isActive = false;
    }

    return bufferHeaders;
  }

  /**
   * A buffer header is the JSON header from the subtree JSON chunk plus
   * the isActive flag and a reference to the header for the underlying buffer
   *
   * @typedef {Object} BufferViewHeader
   * @property {BufferHeader} bufferHeader A reference to the header for the underlying buffer
   * @property {Boolean} isActive Whether this bufferView is currently used.
   * @property {Number} buffer The index of the underlying buffer.
   * @property {Number} byteOffset The start byte of the bufferView within the buffer.
   * @property {Number} byteLength The length of the bufferView. No padding is included in this length.
   * @private
   */

  /**
   * Iterate the list of buffer views from the subtree JSON and add the
   * isActive flag. Also save a reference to the bufferHeader
   *
   * @param {Object[]} [bufferViewHeaders=[]] The JSON from subtree.bufferViews
   * @param {BufferHeader[]} bufferHeaders The preprocessed buffer headers
   * @returns {BufferViewHeader[]} The same array of bufferView headers with additional fields
   * @private
   */
  function preprocessBufferViews(bufferViewHeaders, bufferHeaders) {
    bufferViewHeaders = defined(bufferViewHeaders) ? bufferViewHeaders : [];
    for (let i = 0; i < bufferViewHeaders.length; i++) {
      const bufferViewHeader = bufferViewHeaders[i];
      const bufferHeader = bufferHeaders[bufferViewHeader.buffer];
      bufferViewHeader.bufferHeader = bufferHeader;
      bufferViewHeader.isActive = false;
    }
    return bufferViewHeaders;
  }

  /**
   * Determine which buffer views need to be loaded into memory. This includes:
   *
   * <ul>
   * <li>The tile availability bitstream (if a bitstream is defined)</li>
   * <li>The content availability bitstream(s) (if a bitstream is defined)</li>
   * <li>The child subtree availability bitstream (if a bitstream is defined)</li>
   * </ul>
   *
   * <p>
   * This function modifies the buffer view headers' isActive flags in place.
   * </p>
   *
   * @param {Object[]} subtreeJson The JSON chunk from the subtree
   * @param {BufferViewHeader[]} bufferViewHeaders The preprocessed buffer view headers
   * @private
   */
  function markActiveBufferViews(subtreeJson, bufferViewHeaders) {
    let header;
    const tileAvailabilityHeader = subtreeJson.tileAvailability;

    // Check for bitstream first, which is part of the current schema.
    // bufferView is the name of the bitstream from an older schema.
    if (defined(tileAvailabilityHeader.bitstream)) {
      header = bufferViewHeaders[tileAvailabilityHeader.bitstream];
    } else if (defined(tileAvailabilityHeader.bufferView)) {
      header = bufferViewHeaders[tileAvailabilityHeader.bufferView];
    }

    if (defined(header)) {
      header.isActive = true;
      header.bufferHeader.isActive = true;
    }

    const contentAvailabilityHeaders = subtreeJson.contentAvailabilityHeaders;
    for (let i = 0; i < contentAvailabilityHeaders.length; i++) {
      header = undefined;
      if (defined(contentAvailabilityHeaders[i].bitstream)) {
        header = bufferViewHeaders[contentAvailabilityHeaders[i].bitstream];
      } else if (defined(contentAvailabilityHeaders[i].bufferView)) {
        header = bufferViewHeaders[contentAvailabilityHeaders[i].bufferView];
      }

      if (defined(header)) {
        header.isActive = true;
        header.bufferHeader.isActive = true;
      }
    }

    header = undefined;
    const childSubtreeAvailabilityHeader = subtreeJson.childSubtreeAvailability;
    if (defined(childSubtreeAvailabilityHeader.bitstream)) {
      header = bufferViewHeaders[childSubtreeAvailabilityHeader.bitstream];
    } else if (defined(childSubtreeAvailabilityHeader.bufferView)) {
      header = bufferViewHeaders[childSubtreeAvailabilityHeader.bufferView];
    }

    if (defined(header)) {
      header.isActive = true;
      header.bufferHeader.isActive = true;
    }
  }

  /**
   * For handling metadata, look over the tile and content metadata buffers
   * <p>
   * This always loads all of the metadata immediately. Future iterations may
   * allow filtering this to avoid downloading unneeded buffers.
   * </p>
   *
   * @param {Object} propertyTableJson The property table JSON for either a tile or some content
   * @param {BufferViewHeader[]} bufferViewHeaders The preprocessed buffer view headers
   * @private
   */
  function markActiveMetadataBufferViews(propertyTableJson, bufferViewHeaders) {
    const properties = propertyTableJson.properties;
    let header;
    for (const key in properties) {
      if (properties.hasOwnProperty(key)) {
        const metadataHeader = properties[key];

        // An older spec used bufferView
        const valuesBufferView = defaultValue(
          metadataHeader.values,
          metadataHeader.bufferView
        );
        header = bufferViewHeaders[valuesBufferView];
        header.isActive = true;
        header.bufferHeader.isActive = true;

        // An older spec used stringOffsetBufferView
        const stringOffsetBufferView = defaultValue(
          metadataHeader.stringOffsets,
          metadataHeader.stringOffsetBufferView
        );
        if (defined(stringOffsetBufferView)) {
          header = bufferViewHeaders[stringOffsetBufferView];
          header.isActive = true;
          header.bufferHeader.isActive = true;
        }

        // an older spec used arrayOffsetBufferView
        const arrayOffsetBufferView = defaultValue(
          metadataHeader.arrayOffsets,
          metadataHeader.arrayOffsetBufferView
        );
        if (defined(arrayOffsetBufferView)) {
          header = bufferViewHeaders[arrayOffsetBufferView];
          header.isActive = true;
          header.bufferHeader.isActive = true;
        }
      }
    }
  }

  /**
   * Go through the list of buffers and gather all the active ones into a
   * a dictionary. Since external buffers are allowed, this sometimes involves
   * fetching separate binary files. Consequently, this method returns a promise.
   * <p>
   * The results are put into a dictionary object. The keys are indices of
   * buffers, and the values are Uint8Arrays of the contents. Only buffers
   * marked with the isActive flag are fetched.
   * </p>
   * <p>
   * The internal buffer (the subtree's binary chunk) is also stored in this
   * dictionary if it is marked active.
   * </p>
   * @param {ImplicitSubtree} subtree The subtree
   * @param {BufferHeader[]} bufferHeaders The preprocessed buffer headers
   * @param {Uint8Array} internalBuffer The binary chunk of the subtree file
   * @returns {Promise<Object>} A promise resolving to the dictionary of active buffers
   * @private
   */
  function requestActiveBuffers(subtree, bufferHeaders, internalBuffer) {
    const promises = [];
    for (let i = 0; i < bufferHeaders.length; i++) {
      const bufferHeader = bufferHeaders[i];
      if (!bufferHeader.isActive) {
        promises.push(Promise.resolve(undefined));
      } else if (bufferHeader.isExternal) {
        const promise = requestExternalBuffer(subtree, bufferHeader);
        promises.push(promise);
      } else {
        promises.push(Promise.resolve(internalBuffer));
      }
    }
    return Promise.all(promises).then(function (bufferResults) {
      const buffersU8 = {};
      for (let i = 0; i < bufferResults.length; i++) {
        const result = bufferResults[i];
        if (defined(result)) {
          buffersU8[i] = result;
        }
      }
      return buffersU8;
    });
  }

  function requestExternalBuffer(subtree, bufferHeader) {
    const baseResource = subtree._resource;
    const bufferResource = baseResource.getDerivedResource({
      url: bufferHeader.uri,
    });

    const bufferLoader = ResourceCache.loadExternalBuffer({
      resource: bufferResource,
    });
    subtree._bufferLoader = bufferLoader;

    return bufferLoader.promise.then(function (bufferLoader) {
      return bufferLoader.typedArray;
    });
  }

  /**
   * Go through the list of buffer views, and if they are marked as active,
   * extract a subarray from one of the active buffers.
   *
   * @param {BufferViewHeader[]} bufferViewHeaders
   * @param {Object} buffersU8 A dictionary of buffer index to a Uint8Array of its contents.
   * @returns {Object} A dictionary of buffer view index to a Uint8Array of its contents.
   * @private
   */
  function parseActiveBufferViews(bufferViewHeaders, buffersU8) {
    const bufferViewsU8 = {};
    for (let i = 0; i < bufferViewHeaders.length; i++) {
      const bufferViewHeader = bufferViewHeaders[i];

      if (!bufferViewHeader.isActive) {
        continue;
      }

      const start = bufferViewHeader.byteOffset;
      const end = start + bufferViewHeader.byteLength;
      const buffer = buffersU8[bufferViewHeader.buffer];
      const bufferView = buffer.subarray(start, end);
      bufferViewsU8[i] = bufferView;
    }
    return bufferViewsU8;
  }

  /**
   * Parse the three availability bitstreams and store them in the subtree
   *
   * @param {ImplicitSubtree} subtree The subtree to modify
   * @param {Object} subtreeJson The subtree JSON
   * @param {ImplicitTileset} implicitTileset The implicit tileset this subtree belongs to
   * @param {Object} bufferViewsU8 A dictionary of buffer view index to a Uint8Array of its contents.
   * @private
   */
  function parseAvailability(
    subtree,
    subtreeJson,
    implicitTileset,
    bufferViewsU8
  ) {
    const branchingFactor = implicitTileset.branchingFactor;
    const subtreeLevels = implicitTileset.subtreeLevels;
    const tileAvailabilityBits =
      (Math.pow(branchingFactor, subtreeLevels) - 1) / (branchingFactor - 1);
    const childSubtreeBits = Math.pow(branchingFactor, subtreeLevels);

    // availableCount is only needed for the metadata jump buffer, which
    // corresponds to the tile availability bitstream.
    const hasMetadataExtension = hasExtension(subtreeJson, "3DTILES_metadata");
    const hasTileMetadata = defined(subtree._tilePropertyTableJson);
    let computeAvailableCountEnabled = hasMetadataExtension || hasTileMetadata;

    subtree._tileAvailability = parseAvailabilityBitstream(
      subtreeJson.tileAvailability,
      bufferViewsU8,
      tileAvailabilityBits,
      computeAvailableCountEnabled
    );

    const hasContentMetadata = subtree._contentPropertyTableJsons.length > 0;
    computeAvailableCountEnabled =
      computeAvailableCountEnabled || hasContentMetadata;

    for (let i = 0; i < subtreeJson.contentAvailabilityHeaders.length; i++) {
      const bitstream = parseAvailabilityBitstream(
        subtreeJson.contentAvailabilityHeaders[i],
        bufferViewsU8,
        // content availability has the same length as tile availability.
        tileAvailabilityBits,
        computeAvailableCountEnabled
      );
      subtree._contentAvailabilityBitstreams.push(bitstream);
    }

    subtree._childSubtreeAvailability = parseAvailabilityBitstream(
      subtreeJson.childSubtreeAvailability,
      bufferViewsU8,
      childSubtreeBits
    );
  }

  /**
   * Given the JSON describing an availability bitstream, turn it into an
   * in-memory representation using an {@link ImplicitAvailabilityBitstream}
   * object. This handles both constants and bitstreams from a bufferView.
   *
   * @param {Object} availabilityJson A JSON object representing the availability
   * @param {Object} bufferViewsU8 A dictionary of bufferView index to its Uint8Array contents.
   * @param {Number} lengthBits The length of the availability bitstream in bits
   * @param {Boolean} [computeAvailableCountEnabled] If true and availabilityJson.availableCount is undefined, the availableCount will be computed.
   * @returns {ImplicitAvailabilityBitstream} The parsed bitstream object
   * @private
   */
  function parseAvailabilityBitstream(
    availabilityJson,
    bufferViewsU8,
    lengthBits,
    computeAvailableCountEnabled
  ) {
    if (defined(availabilityJson.constant)) {
      return new ImplicitAvailabilityBitstream({
        constant: Boolean(availabilityJson.constant),
        lengthBits: lengthBits,
        availableCount: availabilityJson.availableCount,
      });
    }

    let bufferView;

    // Check for bitstream first, which is part of the current schema.
    // bufferView is the name of the bitstream from an older schema.
    if (defined(availabilityJson.bitstream)) {
      bufferView = bufferViewsU8[availabilityJson.bitstream];
    } else if (defined(availabilityJson.bufferView)) {
      bufferView = bufferViewsU8[availabilityJson.bufferView];
    }

    return new ImplicitAvailabilityBitstream({
      bitstream: bufferView,
      lengthBits: lengthBits,
      availableCount: availabilityJson.availableCount,
      computeAvailableCountEnabled: computeAvailableCountEnabled,
    });
  }

  /**
   * Parse the metadata table for the tile metadata, storing a {@link MetadataTable}
   * in the subtree.
   *
   * @param {ImplicitSubtree} subtree The subtree
   * @param {ImplicitTileset} implicitTileset The implicit tileset this subtree belongs to.
   * @param {Object} bufferViewsU8 A dictionary of bufferView index to its Uint8Array contents.
   * @private
   */
  function parseTileMetadataTable(subtree, implicitTileset, bufferViewsU8) {
    const tilePropertyTableJson = subtree._tilePropertyTableJson;
    const tileCount = subtree._tileAvailability.availableCount;
    const metadataSchema = implicitTileset.metadataSchema;

    const tileMetadataClassName = tilePropertyTableJson.class;
    const tileMetadataClass = metadataSchema.classes[tileMetadataClassName];

    subtree._tileMetadataTable = new MetadataTable({
      class: tileMetadataClass,
      count: tileCount,
      properties: tilePropertyTableJson.properties,
      bufferViews: bufferViewsU8,
    });
  }

  /**
   * Parse the metadata tables for the content metadata, storing an array of
   * {@link MetadataTable}s in the subtree.
   *
   * @param {ImplicitSubtree} subtree The subtree
   * @param {ImplicitTileset} implicitTileset The implicit tileset this subtree belongs to.
   * @param {Object} bufferViewsU8 A dictionary of bufferView index to its Uint8Array contents.
   * @private
   */
  function parseContentMetadataTables(subtree, implicitTileset, bufferViewsU8) {
    const contentPropertyTableJsons = subtree._contentPropertyTableJsons;
    const contentAvailabilityBitstreams = subtree._contentAvailabilityBitstreams;
    const metadataSchema = implicitTileset.metadataSchema;

    const contentMetadataTables = subtree._contentMetadataTables;
    for (let i = 0; i < contentPropertyTableJsons.length; i++) {
      const contentPropertyTableJson = contentPropertyTableJsons[i];
      const contentAvailabilityBitsteam = contentAvailabilityBitstreams[i];

      const contentCount = contentAvailabilityBitsteam.availableCount;
      const contentMetadataClassName = contentPropertyTableJson.class;
      const contentMetadataClass =
        metadataSchema.classes[contentMetadataClassName];

      const metadataTable = new MetadataTable({
        class: contentMetadataClass,
        count: contentCount,
        properties: contentPropertyTableJson.properties,
        bufferViews: bufferViewsU8,
      });

      contentMetadataTables.push(metadataTable);
    }
  }

  /**
   * Make a jump buffer, i.e. a map of a bit index to the metadata entity ID.
   * <p>
   * For unavailable tiles and content, the jump buffer entries will be uninitialized.
   * Use the tile and content availability to determine whether a jump buffer value is valid.
   * </p>
   *
   * @param {ImplicitAvailabilityBitstream} availability The availability bitstream to create the jump buffer from.
   * @returns {Array} The resulting jump buffer.
   * @private
   */
  function makeJumpBuffer(availability) {
    let entityId = 0;
    const bufferLength = availability.lengthBits;
    const availableCount = availability.availableCount;

    let jumpBuffer;
    if (availableCount < 256) {
      jumpBuffer = new Uint8Array(bufferLength);
    } else if (availableCount < 65536) {
      jumpBuffer = new Uint16Array(bufferLength);
    } else {
      jumpBuffer = new Uint32Array(bufferLength);
    }

    for (let i = 0; i < availability.lengthBits; i++) {
      if (availability.getBit(i)) {
        jumpBuffer[i] = entityId;
        entityId++;
      }
    }

    return jumpBuffer;
  }

  /**
   * Make the jump buffer, i.e. a map of a bit index to the metadata entity ID,
   * for the content metadata. This is stored in the subtree.
   *
   * @param {ImplicitSubtree} subtree The subtree
   * @private
   */
  function makeTileJumpBuffer(subtree) {
    const tileJumpBuffer = makeJumpBuffer(subtree._tileAvailability);
    subtree._tileJumpBuffer = tileJumpBuffer;
  }

  /**
   * Make the jump buffers, i.e. maps of bit indices to the metadata entity IDs,
   * for the content metadata. This is stored in the subtree.
   *
   * @param {ImplicitSubtree} subtree The subtree
   * @private
   */
  function makeContentJumpBuffers(subtree) {
    const contentJumpBuffers = subtree._contentJumpBuffers;
    const contentAvailabilityBitstreams = subtree._contentAvailabilityBitstreams;
    for (let i = 0; i < contentAvailabilityBitstreams.length; i++) {
      const contentAvailability = contentAvailabilityBitstreams[i];
      const contentJumpBuffer = makeJumpBuffer(contentAvailability);
      contentJumpBuffers.push(contentJumpBuffer);
    }
  }

  /**
   * Given the implicit tiling coordinates for a tile, get the index within the
   * subtree's tile availability bitstream.
   * @param {ImplicitTileCoordinates} implicitCoordinates The global coordinates of a tile
   * @return {Number} The tile's index within the subtree.
   * @private
   */
  ImplicitSubtree.prototype.getTileIndex = function (implicitCoordinates) {
    const localLevel =
      implicitCoordinates.level - this._implicitCoordinates.level;
    if (localLevel < 0 || this._subtreeLevels <= localLevel) {
      throw new RuntimeError("level is out of bounds for this subtree");
    }

    const subtreeCoordinates = implicitCoordinates.getSubtreeCoordinates();
    const offsetCoordinates = subtreeCoordinates.getOffsetCoordinates(
      implicitCoordinates
    );
    const index = offsetCoordinates.tileIndex;
    return index;
  };

  /**
   * Given the implicit tiling coordinates for a child subtree, get the index within the
   * subtree's child subtree availability bitstream.
   * @param {ImplicitTileCoordinates} implicitCoordinates The global coordinates of a child subtree
   * @return {Number} The child subtree's index within the subtree's child subtree availability bitstream.
   * @private
   */
  ImplicitSubtree.prototype.getChildSubtreeIndex = function (
    implicitCoordinates
  ) {
    const localLevel =
      implicitCoordinates.level - this._implicitCoordinates.level;
    if (localLevel !== this._implicitCoordinates.subtreeLevels) {
      throw new RuntimeError("level is out of bounds for this subtree");
    }

    // Call getParentSubtreeCoordinates instead of getSubtreeCoordinates because the
    // child subtree is by definition the root of its own subtree, so we need to find
    // the parent subtree.
    const parentSubtreeCoordinates = implicitCoordinates.getParentSubtreeCoordinates();
    const offsetCoordinates = parentSubtreeCoordinates.getOffsetCoordinates(
      implicitCoordinates
    );
    const index = offsetCoordinates.mortonIndex;
    return index;
  };

  /**
   * Get the entity ID for a tile within this subtree.
   * @param {ImplicitSubtree} subtree The subtree
   * @param {ImplicitTileCoordinates} implicitCoordinates The global coordinates of a tile
   * @return {Number} The entity ID for this tile for accessing tile metadata, or <code>undefined</code> if not applicable.
   *
   * @private
   */
  function getTileEntityId(subtree, implicitCoordinates) {
    if (!defined(subtree._tileMetadataTable)) {
      return undefined;
    }

    const tileIndex = subtree.getTileIndex(implicitCoordinates);
    if (subtree._tileAvailability.getBit(tileIndex)) {
      return subtree._tileJumpBuffer[tileIndex];
    }

    return undefined;
  }

  /**
   * Get the entity ID for a content within this subtree.
   * @param {ImplicitSubtree} subtree The subtree
   * @param {ImplicitTileCoordinates} implicitCoordinates The global coordinates of a content
   * @param {Number} contentIndex The content index, for distinguishing between multiple contents.
   * @return {Number} The entity ID for this content for accessing content metadata, or <code>undefined</code> if not applicable.
   *
   * @private
   */
  function getContentEntityId(subtree, implicitCoordinates, contentIndex) {
    const metadataTables = subtree._contentMetadataTables;
    if (!defined(metadataTables)) {
      return undefined;
    }

    const metadataTable = metadataTables[contentIndex];
    if (!defined(metadataTable)) {
      return undefined;
    }

    const availability = subtree._contentAvailabilityBitstreams[contentIndex];
    const tileIndex = subtree.getTileIndex(implicitCoordinates);
    if (availability.getBit(tileIndex)) {
      const contentJumpBuffer = subtree._contentJumpBuffers[contentIndex];
      return contentJumpBuffer[tileIndex];
    }

    return undefined;
  }

  /**
   * Create and return a metadata table view for a tile within this subtree.
   * @param {ImplicitTileCoordinates} implicitCoordinates The global coordinates of a tile
   * @return {ImplicitMetadataView} The metadata view for this tile, or <code>undefined</code> if not applicable.
   *
   * @private
   */
  ImplicitSubtree.prototype.getTileMetadataView = function (implicitCoordinates) {
    const entityId = getTileEntityId(this, implicitCoordinates);
    if (!defined(entityId)) {
      return undefined;
    }

    const metadataTable = this._tileMetadataTable;
    return new ImplicitMetadataView({
      class: metadataTable.class,
      metadataTable: metadataTable,
      entityId: entityId,
      propertyTableJson: this._tilePropertyTableJson,
    });
  };

  /**
   * Create and return a metadata table view for a content within this subtree.
   * @param {ImplicitTileCoordinates} implicitCoordinates The global coordinates of a content
   * @param {Number} contentIndex The index of the content used to distinguish between multiple contents
   * @return {ImplicitMetadataView} The metadata view for this content, or <code>undefined</code> if not applicable.
   *
   * @private
   */
  ImplicitSubtree.prototype.getContentMetadataView = function (
    implicitCoordinates,
    contentIndex
  ) {
    const entityId = getContentEntityId(this, implicitCoordinates, contentIndex);
    if (!defined(entityId)) {
      return undefined;
    }

    const metadataTable = this._contentMetadataTables[contentIndex];
    const propertyTableJson = this._contentPropertyTableJsons[contentIndex];
    return new ImplicitMetadataView({
      class: metadataTable.class,
      metadataTable: metadataTable,
      entityId: entityId,
      contentIndex: contentIndex,
      propertyTableJson: propertyTableJson,
    });
  };

  /**
   * @private
   */
  ImplicitSubtree.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * @private
   */
  ImplicitSubtree.prototype.destroy = function () {
    if (defined(this._bufferLoader)) {
      ResourceCache.unload(this._bufferLoader);
    }

    return destroyObject(this);
  };

  /**
   * An enum of built-in semantics.
   *
   * @enum MetadataSemantic
   *
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   * @see {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/Metadata/Semantics|3D Metadata Semantic Reference}
   */
  const MetadataSemantic = {
    /**
     * A unique identifier, stored as a <code>STRING</code>.
     *
     * @type {String}
     * @constant
     * @private
     */
    ID: "ID",
    /**
     * A name, stored as a <code>STRING</code>. This does not have to be unique.
     *
     * @type {String}
     * @constant
     * @private
     */
    NAME: "NAME",
    /**
     * A description, stored as a <code>STRING</code>.
     *
     * @type {String}
     * @constant
     * @private
     */
    DESCRIPTION: "DESCRIPTION",
    /**
     * A bounding box for a tile, stored as an array of 12 <code>FLOAT32</code> or <code>FLOAT64</code> components. The components are the same format as for <code>boundingVolume.box</code> in 3D Tiles 1.0. This semantic is used to provide a tighter bounding volume than the one implicitly calculated in implicit tiling.
     *
     * @type {String}
     * @constant
     * @private
     */
    TILE_BOUNDING_BOX: "TILE_BOUNDING_BOX",
    /**
     * A bounding region for a tile, stored as an array of 6 <code>FLOAT64</code> components. The components are <code>[west, south, east, north, minimumHeight, maximumHeight]</code>. This semantic is used to provide a tighter bounding volume than the one implicitly calculated in implicit tiling.
     *
     * @type {String}
     * @constant
     * @private
     */
    TILE_BOUNDING_REGION: "TILE_BOUNDING_REGION",
    /**
     * A bounding sphere for a tile, stored as an array of 4 <code>FLOAT32</code> or <code>FLOAT64</code> components. The components are <code>[centerX, centerY, centerZ, radius]</code>. This semantic is used to provide a tighter bounding volume than the one implicitly calculated in implicit tiling.
     *
     * @type {String}
     * @constant
     * @private
     */
    TILE_BOUNDING_SPHERE: "TILE_BOUNDING_SPHERE",
    /**
     * The minimum height of a tile above (or below) the WGS84 ellipsoid, stored as a <code>FLOAT32</code> or a <code>FLOAT64</code>. This semantic is used to tighten bounding regions implicitly calculated in implicit tiling.
     *
     * @type {String}
     * @constant
     * @private
     */
    TILE_MINIMUM_HEIGHT: "TILE_MINIMUM_HEIGHT",
    /**
     * The maximum height of a tile above (or below) the WGS84 ellipsoid, stored as a <code>FLOAT32</code> or a <code>FLOAT64</code>. This semantic is used to tighten bounding regions implicitly calculated in implicit tiling.
     *
     * @type {String}
     * @constant
     * @private
     */
    TILE_MAXIMUM_HEIGHT: "TILE_MAXIMUM_HEIGHT",
    /**
     * The horizon occlusion point for a tile, stored as an <code>VEC3</code> of <code>FLOAT32</code> or <code>FLOAT64</code> components.
     *
     * @see {@link https://cesium.com/blog/2013/04/25/horizon-culling/|Horizon Culling}
     *
     * @type {String}
     * @constant
     * @private
     */
    TILE_HORIZON_OCCLUSION_POINT: "TILE_HORIZON_OCCLUSION_POINT",
    /**
     * The geometric error for a tile, stored as a <code>FLOAT32</code> or a <code>FLOAT64</code>. This semantic is used to override the geometric error implicitly calculated in implicit tiling.
     *
     * @type {String}
     * @constant
     * @private
     */
    TILE_GEOMETRIC_ERROR: "TILE_GEOMETRIC_ERROR",
    /**
     * A bounding box for the content of a tile, stored as an array of 12 <code>FLOAT32</code> or <code>FLOAT64</code> components. The components are the same format as for <code>boundingVolume.box</code> in 3D Tiles 1.0. This semantic is used to provide a tighter bounding volume than the one implicitly calculated in implicit tiling.
     *
     * @type {String}
     * @constant
     * @private
     */
    CONTENT_BOUNDING_BOX: "CONTENT_BOUNDING_BOX",
    /**
     * A bounding region for the content of a tile, stored as an array of 6 <code>FLOAT64</code> components. The components are <code>[west, south, east, north, minimumHeight, maximumHeight]</code>. This semantic is used to provide a tighter bounding volume than the one implicitly calculated in implicit tiling.
     *
     * @type {String}
     * @constant
     * @private
     */
    CONTENT_BOUNDING_REGION: "CONTENT_BOUNDING_REGION",
    /**
     * A bounding sphere for the content of a tile, stored as an array of 4 <code>FLOAT32</code> or <code>FLOAT64</code> components. The components are <code>[centerX, centerY, centerZ, radius]</code>. This semantic is used to provide a tighter bounding volume than the one implicitly calculated in implicit tiling.
     *
     * @type {String}
     * @constant
     * @private
     */
    CONTENT_BOUNDING_SPHERE: "CONTENT_BOUNDING_SPHERE",
    /**
     * The minimum height of the content of a tile above (or below) the WGS84 ellipsoid, stored as a <code>FLOAT32</code> or a <code>FLOAT64</code>
     *
     * @type {String}
     * @constant
     * @private
     */
    CONTENT_MINIMUM_HEIGHT: "CONTENT_MINIMUM_HEIGHT",
    /**
     * The maximum height of the content of a tile above (or below) the WGS84 ellipsoid, stored as a <code>FLOAT32</code> or a <code>FLOAT64</code>
     *
     * @type {String}
     * @constant
     * @private
     */
    CONTENT_MAXIMUM_HEIGHT: "CONTENT_MAXIMUM_HEIGHT",
    /**
     * The horizon occlusion point for the content of a tile, stored as an <code>VEC3</code> of <code>FLOAT32</code> or <code>FLOAT64</code> components.
     *
     * @see {@link https://cesium.com/blog/2013/04/25/horizon-culling/|Horizon Culling}
     *
     * @type {String}
     * @constant
     * @private
     */
    CONTENT_HORIZON_OCCLUSION_POINT: "CONTENT_HORIZON_OCCLUSION_POINT",
  };

  var MetadataSemantic$1 = Object.freeze(MetadataSemantic);

  /**
   * Parse the bounding volume-related semantics such as
   * <code>TILE_BOUNDING_BOX</code> and <code>CONTENT_BOUNDING_REGION</code> from
   * implicit tile metadata. Results are returned as a JSON object for use when
   * transcoding tiles (see {@link Implicit3DTileContent}).
   * <p>
   * Bounding volumes are checked in the order box, region, then sphere. Only
   * the first valid bounding volume is returned.
   * </p>
   *
   * @see {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/Metadata/Semantics|3D Metadata Semantic Reference} for the various bounding volumes and minimum/maximum heights.
   *
   * @param {TileMetadata} tileMetadata The metadata object for looking up values by semantic. In practice, this will typically be a {@link ImplicitMetadataView}
   * @return {Object} An object containing a <code>tile</code> property and a <code>content</code> property. These contain the bounding volume, and any minimum or maximum height.
   *
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function parseBoundingVolumeSemantics(tileMetadata) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("tileMetadata", tileMetadata);
    //>>includeEnd('debug');

    return {
      tile: {
        boundingVolume: parseBoundingVolume("TILE", tileMetadata),
        minimumHeight: parseMinimumHeight("TILE", tileMetadata),
        maximumHeight: parseMaximumHeight("TILE", tileMetadata),
      },
      content: {
        boundingVolume: parseBoundingVolume("CONTENT", tileMetadata),
        minimumHeight: parseMinimumHeight("CONTENT", tileMetadata),
        maximumHeight: parseMaximumHeight("CONTENT", tileMetadata),
      },
    };
  }

  /**
   * Parse the bounding volume from a tile metadata. If the metadata specify
   * multiple bounding volumes, only the first one is returned. Bounding volumes
   * are checked in the order box, region, then sphere.
   *
   * This handles both tile and content bounding volumes, as the only difference
   * is the prefix. e.g. <code>TILE_BOUNDING_BOX</code> and
   * <code>CONTENT_BOUNDING_BOX</code> have the same memory layout.
   *
   * @param {String} prefix Either "TILE" or "CONTENT"
   * @param {TileMetadata} tileMetadata The tileMetadata for looking up values
   * @return {Object} An object representing the JSON description of the tile metadata
   * @private
   */
  function parseBoundingVolume(prefix, tileMetadata) {
    const boundingBoxSemantic = `${prefix}_BOUNDING_BOX`;
    const boundingBox = tileMetadata.getPropertyBySemantic(boundingBoxSemantic);

    if (defined(boundingBox)) {
      return {
        box: boundingBox,
      };
    }

    const boundingRegionSemantic = `${prefix}_BOUNDING_REGION`;
    const boundingRegion = tileMetadata.getPropertyBySemantic(
      boundingRegionSemantic
    );

    if (defined(boundingRegion)) {
      return {
        region: boundingRegion,
      };
    }

    const boundingSphereSemantic = `${prefix}_BOUNDING_SPHERE`;
    const boundingSphere = tileMetadata.getPropertyBySemantic(
      boundingSphereSemantic
    );

    if (defined(boundingSphere)) {
      // ARRAY with 4 elements is automatically converted to a Cartesian4
      return {
        sphere: boundingSphere,
      };
    }

    return undefined;
  }

  /**
   * Parse the minimum height from tile metadata. This is used for making tighter
   * quadtree bounds for implicit tiling. This works for both
   * <code>TILE_MINIMUM_HEIGHT</code> and <code>CONTENT_MINIMUM_HEIGHT</code>
   *
   * @param {String} prefix Either "TILE" or "CONTENT"
   * @param {TileMetadata} tileMetadata The tileMetadata for looking up values
   * @return {Number} The minimum height
   * @private
   */
  function parseMinimumHeight(prefix, tileMetadata) {
    const minimumHeightSemantic = `${prefix}_MINIMUM_HEIGHT`;
    return tileMetadata.getPropertyBySemantic(minimumHeightSemantic);
  }

  /**
   * Parse the maximum height from tile metadata. This is used for making tighter
   * quadtree bounds for implicit tiling. This works for both
   * <code>TILE_MAXIMUM_HEIGHT</code> and <code>CONTENT_MAXIMUM_HEIGHT</code>
   *
   * @param {String} prefix Either "TILE" or "CONTENT"
   * @param {TileMetadata} tileMetadata The tileMetadata for looking up values
   * @return {Number} The maximum height
   * @private
   */
  function parseMaximumHeight(prefix, tileMetadata) {
    const maximumHeightSemantic = `${prefix}_MAXIMUM_HEIGHT`;
    return tileMetadata.getPropertyBySemantic(maximumHeightSemantic);
  }

  /**
   * A specialized {@link Cesium3DTileContent} that lazily evaluates an implicit
   * tileset. It is somewhat similar in operation to a
   * {@link Tileset3DTileContent} in that once the content is constructed, it
   * updates the tileset tree with more tiles. However, unlike external tilesets,
   * child subtrees are represented as additional placeholder nodes with
   * Implicit3DTileContent.
   * <p>
   * Implements the {@link Cesium3DTileContent} interface.
   * </p>
   *
   * @alias Implicit3DTileContent
   * @constructor
   *
   * @param {Cesium3DTileset} tileset The tileset this content belongs to
   * @param {Cesium3DTile} tile The tile this content belongs to.
   * @param {Resource} resource The resource for the tileset
   * @param {Object} [json] The JSON object containing the subtree. Mutually exclusive with arrayBuffer.
   * @param {ArrayBuffer} [arrayBuffer] The array buffer that stores the content payload. Mutually exclusive with json.
   * @param {Number} [byteOffset=0] The offset into the array buffer, if one was provided
   *
   * @exception {DeveloperError} One of json and arrayBuffer must be defined.
   *
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function Implicit3DTileContent(
    tileset,
    tile,
    resource,
    json,
    arrayBuffer,
    byteOffset
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("tile.implicitTileset", tile.implicitTileset);
    Check.defined("tile.implicitCoordinates", tile.implicitCoordinates);
    if (defined(json) === defined(arrayBuffer)) {
      throw new DeveloperError("One of json and arrayBuffer must be defined.");
    }
    //>>includeEnd('debug');

    const implicitTileset = tile.implicitTileset;
    const implicitCoordinates = tile.implicitCoordinates;

    this._implicitTileset = implicitTileset;
    this._implicitCoordinates = implicitCoordinates;
    this._implicitSubtree = undefined;
    this._tileset = tileset;
    this._tile = tile;
    this._resource = resource;

    this._metadata = undefined;

    this.featurePropertiesDirty = false;
    this._group = undefined;

    const templateValues = implicitCoordinates.getTemplateValues();
    const subtreeResource = implicitTileset.subtreeUriTemplate.getDerivedResource(
      {
        templateValues: templateValues,
      }
    );
    this._url = subtreeResource.getUrlComponent(true);

    this._readyPromise = initialize$h(this, json, arrayBuffer, byteOffset);
  }

  Object.defineProperties(Implicit3DTileContent.prototype, {
    featuresLength: {
      get: function () {
        return 0;
      },
    },

    pointsLength: {
      get: function () {
        return 0;
      },
    },

    trianglesLength: {
      get: function () {
        return 0;
      },
    },

    geometryByteLength: {
      get: function () {
        return 0;
      },
    },

    texturesByteLength: {
      get: function () {
        return 0;
      },
    },

    batchTableByteLength: {
      get: function () {
        return 0;
      },
    },

    innerContents: {
      get: function () {
        return undefined;
      },
    },

    readyPromise: {
      get: function () {
        return this._readyPromise;
      },
    },

    tileset: {
      get: function () {
        return this._tileset;
      },
    },

    tile: {
      get: function () {
        return this._tile;
      },
    },

    url: {
      get: function () {
        return this._url;
      },
    },

    /**
     * Part of the {@link Cesium3DTileContent} interface. <code>Implicit3DTileContent</code>
     * always returns <code>undefined</code>. Only transcoded tiles have content metadata.
     * @memberof Implicit3DTileContent.prototype
     * @private
     */
    metadata: {
      get: function () {
        return undefined;
      },
      set: function () {
        //>>includeStart('debug', pragmas.debug);
        throw new DeveloperError("Implicit3DTileContent cannot have metadata");
        //>>includeEnd('debug');
      },
    },

    batchTable: {
      get: function () {
        return undefined;
      },
    },

    group: {
      get: function () {
        return this._group;
      },
      set: function (value) {
        this._group = value;
      },
    },
  });

  /**
   * Initialize the implicit content by parsing the subtree resource and setting
   * up a promise chain to expand the immediate subtree.
   *
   * @param {Implicit3DTileContent} content The implicit content
   * @param {Object} [json] The JSON containing the subtree. Mutually exclusive with arrayBuffer.
   * @param {ArrayBuffer} [arrayBuffer] The ArrayBuffer containing a subtree binary. Mutually exclusive with json.
   * @param {Number} [byteOffset=0] The byte offset into the arrayBuffer
   * @private
   */
  function initialize$h(content, json, arrayBuffer, byteOffset) {
    byteOffset = defaultValue(byteOffset, 0);
    let uint8Array;
    if (defined(arrayBuffer)) {
      uint8Array = new Uint8Array(arrayBuffer, byteOffset);
    }

    const subtree = new ImplicitSubtree(
      content._resource,
      json,
      uint8Array,
      content._implicitTileset,
      content._implicitCoordinates
    );

    content._implicitSubtree = subtree;
    return subtree.readyPromise.then(function () {
      expandSubtree(content, subtree);
      return content;
    });
  }

  /**
   * Expand a single subtree placeholder tile. This transcodes the subtree into
   * a tree of {@link Cesium3DTile}. The root of this tree is stored in
   * the placeholder tile's children array. This method also creates placeholder
   * tiles for the child subtrees to be lazily expanded as needed.
   *
   * @param {Implicit3DTileContent} content The content
   * @param {ImplicitSubtree} subtree The parsed subtree
   * @private
   */
  function expandSubtree(content, subtree) {
    const placeholderTile = content._tile;

    // Parse the tiles inside this immediate subtree
    const childIndex = content._implicitCoordinates.childIndex;
    const results = transcodeSubtreeTiles(
      content,
      subtree,
      placeholderTile,
      childIndex
    );

    // Link the new subtree to the existing placeholder tile.
    placeholderTile.children.push(results.rootTile);

    // for each child subtree, make new placeholder tiles
    const childSubtrees = listChildSubtrees(content, subtree, results.bottomRow);
    for (let i = 0; i < childSubtrees.length; i++) {
      const subtreeLocator = childSubtrees[i];
      const leafTile = subtreeLocator.tile;
      const implicitChildTile = makePlaceholderChildSubtree(
        content,
        leafTile,
        subtreeLocator.childIndex
      );
      leafTile.children.push(implicitChildTile);
    }
  }

  /**
   * A pair of (tile, childIndex) used for finding child subtrees.
   *
   * @typedef {Object} ChildSubtreeLocator
   * @property {Cesium3DTile} tile One of the tiles in the bottommost row of the subtree.
   * @property {Number} childIndex The morton index of the child tile relative to its parent
   * @private
   */

  /**
   * Determine what child subtrees exist and return a list of information
   *
   * @param {Implicit3DTileContent} content The implicit content
   * @param {ImplicitSubtree} subtree The subtree for looking up availability
   * @param {Array<Cesium3DTile|undefined>} bottomRow The bottom row of tiles in a transcoded subtree
   * @returns {ChildSubtreeLocator[]} A list of identifiers for the child subtrees.
   * @private
   */
  function listChildSubtrees(content, subtree, bottomRow) {
    const results = [];
    const branchingFactor = content._implicitTileset.branchingFactor;
    for (let i = 0; i < bottomRow.length; i++) {
      const leafTile = bottomRow[i];
      if (!defined(leafTile)) {
        continue;
      }

      for (let j = 0; j < branchingFactor; j++) {
        const index = i * branchingFactor + j;
        if (subtree.childSubtreeIsAvailableAtIndex(index)) {
          results.push({
            tile: leafTile,
            childIndex: j,
          });
        }
      }
    }
    return results;
  }

  /**
   * Results of transcodeSubtreeTiles, containing the root tile of the
   * subtree and the bottom row of nodes for further processing.
   *
   * @typedef {Object} TranscodedSubtree
   * @property {Cesium3DTile} rootTile The transcoded root tile of the subtree
   * @property {Array<Cesium3DTile|undefined>} bottomRow The bottom row of transcoded tiles. This is helpful for processing child subtrees
   * @private
   */

  /**
   * Transcode the implicitly-defined tiles within this subtree and generate
   * explicit {@link Cesium3DTile} objects. This function only transcode tiles,
   * child subtrees are handled separately.
   *
   * @param {Implicit3DTileContent} content The implicit content
   * @param {ImplicitSubtree} subtree The subtree to get availability information
   * @param {Cesium3DTile} placeholderTile The placeholder tile, used for constructing the subtree root tile
   * @param {Number} childIndex The Morton index of the root tile relative to parentOfRootTile
   * @returns {TranscodedSubtree} The newly created subtree of tiles
   * @private
   */
  function transcodeSubtreeTiles(content, subtree, placeholderTile, childIndex) {
    const rootBitIndex = 0;
    const rootParentIsPlaceholder = true;
    const rootTile = deriveChildTile(
      content,
      subtree,
      placeholderTile,
      childIndex,
      rootBitIndex,
      rootParentIsPlaceholder
    );

    // Sliding window over the levels of the tree.
    // Each row is branchingFactor * length of previous row
    // Tiles within a row are ordered by Morton index.
    let parentRow = [rootTile];
    let currentRow = [];

    const implicitTileset = content._implicitTileset;
    for (let level = 1; level < implicitTileset.subtreeLevels; level++) {
      const levelOffset = subtree.getLevelOffset(level);
      const numberOfChildren = implicitTileset.branchingFactor * parentRow.length;
      for (
        let childMortonIndex = 0;
        childMortonIndex < numberOfChildren;
        childMortonIndex++
      ) {
        const childBitIndex = levelOffset + childMortonIndex;

        if (!subtree.tileIsAvailableAtIndex(childBitIndex)) {
          currentRow.push(undefined);
          continue;
        }

        const parentMortonIndex = subtree.getParentMortonIndex(childMortonIndex);
        const parentTile = parentRow[parentMortonIndex];
        const childChildIndex =
          childMortonIndex % implicitTileset.branchingFactor;
        const childTile = deriveChildTile(
          content,
          subtree,
          parentTile,
          childChildIndex,
          childBitIndex
        );
        parentTile.children.push(childTile);
        currentRow.push(childTile);
      }

      parentRow = currentRow;
      currentRow = [];
    }

    return {
      rootTile: rootTile,
      // At the end of the last loop, bottomRow was moved to parentRow
      bottomRow: parentRow,
    };
  }

  function getGeometricError$3(tileMetadata, implicitTileset, implicitCoordinates) {
    const semantic = MetadataSemantic$1.TILE_GEOMETRIC_ERROR;

    if (defined(tileMetadata) && tileMetadata.hasPropertyBySemantic(semantic)) {
      return tileMetadata.getPropertyBySemantic(semantic);
    }

    return (
      implicitTileset.geometricError / Math.pow(2, implicitCoordinates.level)
    );
  }

  /**
   * Given a parent tile and information about which child to create, derive
   * the properties of the child tile implicitly.
   * <p>
   * This creates a real tile for rendering, not a placeholder tile like some of
   * the other methods of ImplicitTileset.
   * </p>
   *
   * @param {Implicit3DTileContent} implicitContent The implicit content
   * @param {ImplicitSubtree} subtree The subtree the child tile belongs to
   * @param {Cesium3DTile} parentTile The parent of the new child tile
   * @param {Number} childIndex The morton index of the child tile relative to its parent
   * @param {Number} childBitIndex The index of the child tile within the tile's availability information.
   * @param {Boolean} [parentIsPlaceholderTile=false] True if parentTile is a placeholder tile. This is true for the root of each subtree.
   * @returns {Cesium3DTile} The new child tile.
   * @private
   */
  function deriveChildTile(
    implicitContent,
    subtree,
    parentTile,
    childIndex,
    childBitIndex,
    parentIsPlaceholderTile
  ) {
    const implicitTileset = implicitContent._implicitTileset;
    let implicitCoordinates;
    if (defaultValue(parentIsPlaceholderTile, false)) {
      implicitCoordinates = parentTile.implicitCoordinates;
    } else {
      implicitCoordinates = parentTile.implicitCoordinates.getChildCoordinates(
        childIndex
      );
    }

    // Parse metadata and bounding volume semantics at the beginning
    // as the bounding volumes are needed below.
    let tileMetadata;
    let tileBounds;
    let contentBounds;
    if (defined(subtree.tilePropertyTableJson)) {
      tileMetadata = subtree.getTileMetadataView(implicitCoordinates);

      const boundingVolumeSemantics = parseBoundingVolumeSemantics(tileMetadata);
      tileBounds = boundingVolumeSemantics.tile;
      contentBounds = boundingVolumeSemantics.content;
    }

    // Content is not loaded at this point, so this flag is set for future reference.
    const contentPropertyTableJsons = subtree.contentPropertyTableJsons;
    const length = contentPropertyTableJsons.length;
    let hasImplicitContentMetadata = false;
    for (let i = 0; i < length; i++) {
      if (subtree.contentIsAvailableAtCoordinates(implicitCoordinates, i)) {
        hasImplicitContentMetadata = true;
        break;
      }
    }

    const boundingVolume = getTileBoundingVolume(
      implicitTileset,
      implicitCoordinates,
      childIndex,
      parentIsPlaceholderTile,
      parentTile,
      tileBounds
    );

    const contentJsons = [];
    for (let i = 0; i < implicitTileset.contentCount; i++) {
      if (!subtree.contentIsAvailableAtIndex(childBitIndex, i)) {
        continue;
      }
      const childContentTemplate = implicitTileset.contentUriTemplates[i];
      const childContentUri = childContentTemplate.getDerivedResource({
        templateValues: implicitCoordinates.getTemplateValues(),
      }).url;
      const contentJson = {
        uri: childContentUri,
      };

      const contentBoundingVolume = getContentBoundingVolume$1(
        boundingVolume,
        contentBounds
      );

      if (defined(contentBoundingVolume)) {
        contentJson.boundingVolume = contentBoundingVolume;
      }

      // combine() is used to pass through any additional properties the
      // user specified such as extras or extensions
      contentJsons.push(combine$2(contentJson, implicitTileset.contentHeaders[i]));
    }

    const childGeometricError = getGeometricError$3(
      tileMetadata,
      implicitTileset,
      implicitCoordinates
    );

    const tileJson = {
      boundingVolume: boundingVolume,
      geometricError: childGeometricError,
      refine: implicitTileset.refine,
      contents: contentJsons,
    };

    // combine() is used to pass through any additional properties the
    // user specified such as extras or extensions.
    const deep = true;
    const rootHeader = clone$1(implicitTileset.tileHeader, deep);
    delete rootHeader.boundingVolume;
    delete rootHeader.transform;
    const combinedTileJson = combine$2(tileJson, rootHeader, deep);

    const childTile = makeTile$1(
      implicitContent,
      implicitTileset.baseResource,
      combinedTileJson,
      parentTile
    );

    childTile.implicitCoordinates = implicitCoordinates;
    childTile.implicitSubtree = subtree;
    childTile.metadata = tileMetadata;
    childTile.hasImplicitContentMetadata = hasImplicitContentMetadata;

    return childTile;
  }

  /**
   * Checks whether the bounding volume's heights can be updated.
   * Returns true if the minimumHeight/maximumHeight parameter
   * is defined and the bounding volume is a region or S2 cell.
   *
   * @param {Object} [boundingVolume] The bounding volume
   * @param {Object} [tileBounds] The tile bounds
   * @param {Number} [tileBounds.minimumHeight] The minimum height
   * @param {Number} [tileBounds.maximumHeight] The maximum height
   * @returns {Boolean} Whether the bounding volume's heights can be updated
   * @private
   */
  function canUpdateHeights(boundingVolume, tileBounds) {
    return (
      defined(boundingVolume) &&
      defined(tileBounds) &&
      (defined(tileBounds.minimumHeight) || defined(tileBounds.maximumHeight)) &&
      (hasExtension(boundingVolume, "3DTILES_bounding_volume_S2") ||
        defined(boundingVolume.region))
    );
  }

  /**
   * Update the minimum and maximum height of the bounding volume.
   * This is typically used to tighten a bounding volume using the
   * <code>TILE_MINIMUM_HEIGHT</code> and <code>TILE_MAXIMUM_HEIGHT</code>
   * semantics. Heights are only updated if the respective
   * minimumHeight/maximumHeight parameter is defined and the
   * bounding volume is a region or S2 cell.
   *
   * @param {Object} boundingVolume The bounding volume
   * @param {Object} [tileBounds] The tile bounds
   * @param {Number} [tileBounds.minimumHeight] The new minimum height
   * @param {Number} [tileBounds.maximumHeight] The new maximum height
   * @private
   */
  function updateHeights$1(boundingVolume, tileBounds) {
    if (!defined(tileBounds)) {
      return;
    }

    if (hasExtension(boundingVolume, "3DTILES_bounding_volume_S2")) {
      updateS2CellHeights(
        boundingVolume.extensions["3DTILES_bounding_volume_S2"],
        tileBounds.minimumHeight,
        tileBounds.maximumHeight
      );
    } else if (defined(boundingVolume.region)) {
      updateRegionHeights(
        boundingVolume.region,
        tileBounds.minimumHeight,
        tileBounds.maximumHeight
      );
    }
  }

  /**
   * For a bounding region, update the minimum and maximum height. This
   * is typically used to tighten a bounding volume using the
   * <code>TILE_MINIMUM_HEIGHT</code> and <code>TILE_MAXIMUM_HEIGHT</code>
   * semantics. Heights are only updated if the respective
   * minimumHeight/maximumHeight parameter is defined.
   *
   * @param {Array} region A 6-element array describing the bounding region
   * @param {Number} [minimumHeight] The new minimum height
   * @param {Number} [maximumHeight] The new maximum height
   * @private
   */
  function updateRegionHeights(region, minimumHeight, maximumHeight) {
    if (defined(minimumHeight)) {
      region[4] = minimumHeight;
    }

    if (defined(maximumHeight)) {
      region[5] = maximumHeight;
    }
  }

  /**
   * For a bounding S2 cell, update the minimum and maximum height. This
   * is typically used to tighten a bounding volume using the
   * <code>TILE_MINIMUM_HEIGHT</code> and <code>TILE_MAXIMUM_HEIGHT</code>
   * semantics. Heights are only updated if the respective
   * minimumHeight/maximumHeight parameter is defined.
   *
   * @param {Object} s2CellVolume An object describing the S2 cell
   * @param {Number} [minimumHeight] The new minimum height
   * @param {Number} [maximumHeight] The new maximum height
   * @private
   */
  function updateS2CellHeights(s2CellVolume, minimumHeight, maximumHeight) {
    if (defined(minimumHeight)) {
      s2CellVolume.minimumHeight = minimumHeight;
    }

    if (defined(maximumHeight)) {
      s2CellVolume.maximumHeight = maximumHeight;
    }
  }

  /**
   * Gets the tile's bounding volume, which may be specified via
   * metadata semantics such as TILE_BOUNDING_BOX or implicitly
   * derived from the implicit root tile's bounding volume.
   * <p>
   * Priority of bounding volume types:
   * <ol>
   * <li>Explicit min/max height
   *   <ol>
   *     <li>With explicit region</li>
   *     <li>With implicit S2</li>
   *     <li>With implicit region</li>
   *   </ol>
   * </li>
   * <li>Explicit box</li>
   * <li>Explicit region</li>
   * <li>Explicit sphere</li>
   * <li>Implicit S2</li>
   * <li>Implicit box</li>
   * <li>Implicit region</li>
   * </ol>
   * </p>
   *
   * @param {ImplicitTileset} implicitTileset The implicit tileset struct which holds the root bounding volume
   * @param {ImplicitTileCoordinates} implicitCoordinates The coordinates of the child tile
   * @param {Number} childIndex The morton index of the child tile relative to its parent
   * @param {Boolean} parentIsPlaceholderTile True if parentTile is a placeholder tile. This is true for the root of each subtree.
   * @param {Cesium3DTile} parentTile The parent of the new child tile
   * @param {Object} [tileBounds] The tile bounds
   * @returns {Object} An object containing the JSON for a bounding volume
   * @private
   */
  function getTileBoundingVolume(
    implicitTileset,
    implicitCoordinates,
    childIndex,
    parentIsPlaceholderTile,
    parentTile,
    tileBounds
  ) {
    let boundingVolume;

    if (
      !defined(tileBounds) ||
      !defined(tileBounds.boundingVolume) ||
      (!canUpdateHeights(tileBounds.boundingVolume, tileBounds) &&
        canUpdateHeights(implicitTileset.boundingVolume, tileBounds))
    ) {
      boundingVolume = deriveBoundingVolume(
        implicitTileset,
        implicitCoordinates,
        childIndex,
        defaultValue(parentIsPlaceholderTile, false),
        parentTile
      );
    } else {
      boundingVolume = tileBounds.boundingVolume;
    }

    // The TILE_MINIMUM_HEIGHT and TILE_MAXIMUM_HEIGHT metadata semantics
    // can be used to tighten the bounding volume
    updateHeights$1(boundingVolume, tileBounds);

    return boundingVolume;
  }

  /**
   * Gets the content bounding volume, which may be specified via
   * metadata semantics such as CONTENT_BOUNDING_BOX.
   * <p>
   * Priority of bounding volume types:
   * <ol>
   * <li>Explicit min/max height
   *   <ol>
   *     <li>With explicit region</li>
   *     <li>With tile bounding volume (S2 or region)</li>
   *   </ol>
   * </li>
   * <li>Explicit box</li>
   * <li>Explicit region</li>
   * <li>Explicit sphere</li>
   * <li>Tile bounding volume (when content.boundingVolume is undefined)</li>
   * </ol>
   * </p>
   *
   * @param {Object} tileBoundingVolume An object containing the JSON for the tile's bounding volume
   * @param {Object} [contentBounds] The content bounds
   * @returns {Object|undefined} An object containing the JSON for a bounding volume, or <code>undefined</code> if there is no bounding volume
   * @private
   */
  function getContentBoundingVolume$1(tileBoundingVolume, contentBounds) {
    // content bounding volumes can only be specified via
    // metadata semantics such as CONTENT_BOUNDING_BOX
    let contentBoundingVolume;
    if (defined(contentBounds)) {
      contentBoundingVolume = contentBounds.boundingVolume;
    }

    // The CONTENT_MINIMUM_HEIGHT and CONTENT_MAXIMUM_HEIGHT metadata semantics
    // can be used to tighten the bounding volume
    if (canUpdateHeights(contentBoundingVolume, contentBounds)) {
      updateHeights$1(contentBoundingVolume, contentBounds);
    } else if (canUpdateHeights(tileBoundingVolume, contentBounds)) {
      contentBoundingVolume = clone$1(tileBoundingVolume, true);
      updateHeights$1(contentBoundingVolume, contentBounds);
    }

    return contentBoundingVolume;
  }

  /**
   * Given the coordinates of a tile, derive its bounding volume from the root.
   *
   * @param {ImplicitTileset} implicitTileset The implicit tileset struct which holds the root bounding volume
   * @param {ImplicitTileCoordinates} implicitCoordinates The coordinates of the child tile
   * @param {Number} childIndex The morton index of the child tile relative to its parent
   * @param {Boolean} parentIsPlaceholderTile True if parentTile is a placeholder tile. This is true for the root of each subtree.
   * @param {Cesium3DTile} parentTile The parent of the new child tile
   * @returns {Object} An object containing the JSON for a bounding volume
   * @private
   */
  function deriveBoundingVolume(
    implicitTileset,
    implicitCoordinates,
    childIndex,
    parentIsPlaceholderTile,
    parentTile
  ) {
    const rootBoundingVolume = implicitTileset.boundingVolume;

    if (hasExtension(rootBoundingVolume, "3DTILES_bounding_volume_S2")) {
      return deriveBoundingVolumeS2(
        parentIsPlaceholderTile,
        parentTile,
        childIndex,
        implicitCoordinates.level,
        implicitCoordinates.x,
        implicitCoordinates.y,
        implicitCoordinates.z
      );
    }

    if (defined(rootBoundingVolume.region)) {
      const childRegion = deriveBoundingRegion(
        rootBoundingVolume.region,
        implicitCoordinates.level,
        implicitCoordinates.x,
        implicitCoordinates.y,
        implicitCoordinates.z
      );

      return {
        region: childRegion,
      };
    }

    const childBox = deriveBoundingBox(
      rootBoundingVolume.box,
      implicitCoordinates.level,
      implicitCoordinates.x,
      implicitCoordinates.y,
      implicitCoordinates.z
    );

    return {
      box: childBox,
    };
  }

  /**
   * Derive a bounding volume for a descendant tile (child, grandchild, etc.),
   * assuming a quadtree or octree implicit tiling scheme. The (level, x, y, [z])
   * coordinates are given to select the descendant tile and compute its position
   * and dimensions.
   * <p>
   * If z is present, octree subdivision is used. Otherwise, quadtree subdivision
   * is used. Quadtrees are always divided at the midpoint of the the horizontal
   * dimensions, i.e. (x, y), leaving the z axis unchanged.
   * </p>
   *
   * @param {Boolean} parentIsPlaceholderTile True if parentTile is a placeholder tile. This is true for the root of each subtree.
   * @param {Cesium3DTile} parentTile The parent of the new child tile
   * @param {Number} childIndex The morton index of the child tile relative to its parent
   * @param {Number} level The level of the descendant tile relative to the root implicit tile
   * @param {Number} x The x coordinate of the descendant tile
   * @param {Number} y The y coordinate of the descendant tile
   * @param {Number} [z] The z coordinate of the descendant tile (octree only)
   * @returns {Object} An object with the 3DTILES_bounding_volume_S2 extension.
   * @private
   */
  function deriveBoundingVolumeS2(
    parentIsPlaceholderTile,
    parentTile,
    childIndex,
    level,
    x,
    y,
    z
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.bool("parentIsPlaceholderTile", parentIsPlaceholderTile);
    Check.typeOf.object("parentTile", parentTile);
    Check.typeOf.number("childIndex", childIndex);
    Check.typeOf.number("level", level);
    Check.typeOf.number("x", x);
    Check.typeOf.number("y", y);
    if (defined(z)) {
      Check.typeOf.number("z", z);
    }
    //>>includeEnd('debug');

    const boundingVolumeS2 = parentTile._boundingVolume;

    // Handle the placeholder tile case, where we just duplicate the placeholder's bounding volume.
    if (parentIsPlaceholderTile) {
      return {
        extensions: {
          "3DTILES_bounding_volume_S2": {
            token: S2Cell.getTokenFromId(boundingVolumeS2.s2Cell._cellId),
            minimumHeight: boundingVolumeS2.minimumHeight,
            maximumHeight: boundingVolumeS2.maximumHeight,
          },
        },
      };
    }

    // Extract the first 3 face bits from the 64-bit S2 cell ID.
    // eslint-disable-next-line no-undef
    const face = Number(parentTile._boundingVolume.s2Cell._cellId >> BigInt(61));
    // The Hilbert curve is rotated for the "odd" faces on the S2 Earthcube.
    // See http://s2geometry.io/devguide/img/s2cell_global.jpg
    const position =
      face % 2 === 0
        ? HilbertOrder.encode2D(level, x, y)
        : HilbertOrder.encode2D(level, y, x);
    // eslint-disable-next-line no-undef
    const cell = S2Cell.fromFacePositionLevel(face, BigInt(position), level);

    let minHeight, maxHeight;
    if (defined(z)) {
      const midpointHeight =
        (boundingVolumeS2.maximumHeight + boundingVolumeS2.minimumHeight) / 2;
      minHeight =
        childIndex < 4 ? boundingVolumeS2.minimumHeight : midpointHeight;
      maxHeight =
        childIndex < 4 ? midpointHeight : boundingVolumeS2.maximumHeight;
    } else {
      minHeight = boundingVolumeS2.minimumHeight;
      maxHeight = boundingVolumeS2.maximumHeight;
    }

    return {
      extensions: {
        "3DTILES_bounding_volume_S2": {
          token: S2Cell.getTokenFromId(cell._cellId),
          minimumHeight: minHeight,
          maximumHeight: maxHeight,
        },
      },
    };
  }

  const scratchScaleFactors = new Cartesian3();
  const scratchRootCenter = new Cartesian3();
  const scratchCenter$5 = new Cartesian3();
  const scratchHalfAxes$1 = new Matrix3();
  /**
   * Derive a bounding volume for a descendant tile (child, grandchild, etc.),
   * assuming a quadtree or octree implicit tiling scheme. The (level, x, y, [z])
   * coordinates are given to select the descendant tile and compute its position
   * and dimensions.
   * <p>
   * If z is present, octree subdivision is used. Otherwise, quadtree subdivision
   * is used. Quadtrees are always divided at the midpoint of the the horizontal
   * dimensions, i.e. (x, y), leaving the z axis unchanged.
   * </p>
   * <p>
   * This computes the child volume directly from the root bounding volume rather
   * than recursively subdividing to minimize floating point error.
   * </p>
   *
   * @param {Number[]} rootBox An array of 12 numbers representing the bounding box of the root tile
   * @param {Number} level The level of the descendant tile relative to the root implicit tile
   * @param {Number} x The x coordinate of the descendant tile
   * @param {Number} y The y coordinate of the descendant tile
   * @param {Number} [z] The z coordinate of the descendant tile (octree only)
   * @returns {Number[]} An array of 12 numbers representing the bounding box of the descendant tile.
   * @private
   */
  function deriveBoundingBox(rootBox, level, x, y, z) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("rootBox", rootBox);
    Check.typeOf.number("level", level);
    Check.typeOf.number("x", x);
    Check.typeOf.number("y", y);
    if (defined(z)) {
      Check.typeOf.number("z", z);
    }
    //>>includeEnd('debug');

    if (level === 0) {
      return rootBox;
    }

    const rootCenter = Cartesian3.unpack(rootBox, 0, scratchRootCenter);
    const rootHalfAxes = Matrix3.unpack(rootBox, 3, scratchHalfAxes$1);

    const tileScale = Math.pow(2, -level);
    const modelSpaceX = -1 + (2 * x + 1) * tileScale;
    const modelSpaceY = -1 + (2 * y + 1) * tileScale;

    let modelSpaceZ = 0;
    const scaleFactors = Cartesian3.fromElements(
      tileScale,
      tileScale,
      1,
      scratchScaleFactors
    );

    if (defined(z)) {
      modelSpaceZ = -1 + (2 * z + 1) * tileScale;
      scaleFactors.z = tileScale;
    }

    let center = Cartesian3.fromElements(
      modelSpaceX,
      modelSpaceY,
      modelSpaceZ,
      scratchCenter$5
    );
    center = Matrix3.multiplyByVector(rootHalfAxes, center, scratchCenter$5);
    center = Cartesian3.add(center, rootCenter, scratchCenter$5);

    let halfAxes = Matrix3.clone(rootHalfAxes);
    halfAxes = Matrix3.multiplyByScale(halfAxes, scaleFactors, halfAxes);

    const childBox = new Array(12);
    Cartesian3.pack(center, childBox);
    Matrix3.pack(halfAxes, childBox, 3);
    return childBox;
  }

  const scratchRectangle$6 = new Rectangle();
  /**
   * Derive a bounding volume for a descendant tile (child, grandchild, etc.),
   * assuming a quadtree or octree implicit tiling scheme. The (level, x, y, [z])
   * coordinates are given to select the descendant tile and compute its position
   * and dimensions.
   * <p>
   * If z is present, octree subdivision is used. Otherwise, quadtree subdivision
   * is used. Quadtrees are always divided at the midpoint of the the horizontal
   * dimensions, i.e. (mid_longitude, mid_latitude), leaving the height values
   * unchanged.
   * </p>
   * <p>
   * This computes the child volume directly from the root bounding volume rather
   * than recursively subdividing to minimize floating point error.
   * </p>
   * @param {Number[]} rootRegion An array of 6 numbers representing the root implicit tile
   * @param {Number} level The level of the descendant tile relative to the root implicit tile
   * @param {Number} x The x coordinate of the descendant tile
   * @param {Number} y The x coordinate of the descendant tile
   * @param {Number} [z] The z coordinate of the descendant tile (octree only)
   * @returns {Number[]} An array of 6 numbers representing the bounding region of the descendant tile
   * @private
   */
  function deriveBoundingRegion(rootRegion, level, x, y, z) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("rootRegion", rootRegion);
    Check.typeOf.number("level", level);
    Check.typeOf.number("x", x);
    Check.typeOf.number("y", y);
    if (defined(z)) {
      Check.typeOf.number("z", z);
    }
    //>>includeEnd('debug');

    if (level === 0) {
      return rootRegion.slice();
    }

    const rectangle = Rectangle.unpack(rootRegion, 0, scratchRectangle$6);
    const rootMinimumHeight = rootRegion[4];
    const rootMaximumHeight = rootRegion[5];
    const tileScale = Math.pow(2, -level);

    const childWidth = tileScale * rectangle.width;
    const west = CesiumMath.negativePiToPi(rectangle.west + x * childWidth);
    const east = CesiumMath.negativePiToPi(west + childWidth);

    const childHeight = tileScale * rectangle.height;
    const south = CesiumMath.negativePiToPi(rectangle.south + y * childHeight);
    const north = CesiumMath.negativePiToPi(south + childHeight);

    // Height is only subdivided for octrees; It remains constant for quadtrees.
    let minimumHeight = rootMinimumHeight;
    let maximumHeight = rootMaximumHeight;
    if (defined(z)) {
      const childThickness = tileScale * (rootMaximumHeight - rootMinimumHeight);
      minimumHeight += z * childThickness;
      maximumHeight = minimumHeight + childThickness;
    }

    return [west, south, east, north, minimumHeight, maximumHeight];
  }

  /**
   * Create a placeholder 3D Tile whose content will be an Implicit3DTileContent
   * for lazy evaluation of a child subtree.
   *
   * @param {Implicit3DTileContent} content The content object.
   * @param {Cesium3DTile} parentTile The parent of the new child subtree.
   * @param {Number} childIndex The morton index of the child tile relative to its parent
   * @returns {Cesium3DTile} The new placeholder tile
   * @private
   */
  function makePlaceholderChildSubtree(content, parentTile, childIndex) {
    const implicitTileset = content._implicitTileset;
    const implicitCoordinates = parentTile.implicitCoordinates.getChildCoordinates(
      childIndex
    );

    const childBoundingVolume = deriveBoundingVolume(
      implicitTileset,
      implicitCoordinates,
      childIndex,
      false,
      parentTile
    );

    // Ignore tile metadata when computing geometric error for the placeholder tile
    // since the child subtree's metadata hasn't been loaded yet.
    // The actual geometric error will be computed in deriveChildTile.
    const childGeometricError = getGeometricError$3(
      undefined,
      implicitTileset,
      implicitCoordinates
    );

    const childContentUri = implicitTileset.subtreeUriTemplate.getDerivedResource(
      {
        templateValues: implicitCoordinates.getTemplateValues(),
      }
    ).url;
    const tileJson = {
      boundingVolume: childBoundingVolume,
      geometricError: childGeometricError,
      refine: implicitTileset.refine,
      contents: [
        {
          uri: childContentUri,
        },
      ],
    };

    const tile = makeTile$1(
      content,
      implicitTileset.baseResource,
      tileJson,
      parentTile
    );
    tile.implicitTileset = implicitTileset;
    tile.implicitCoordinates = implicitCoordinates;
    return tile;
  }

  /**
   * Make a {@link Cesium3DTile}. This uses the content's tile's constructor instead
   * of importing Cesium3DTile. This is to avoid a circular dependency between
   * this file and Cesium3DTile.js
   * @param {Implicit3DTileContent} content The implicit content
   * @param {Resource} baseResource The base resource for the tileset
   * @param {Object} tileJson The JSON header for the tile
   * @param {Cesium3DTile} parentTile The parent of the new tile
   * @returns {Cesium3DTile} The newly created tile.
   * @private
   */
  function makeTile$1(content, baseResource, tileJson, parentTile) {
    const Cesium3DTile = content._tile.constructor;
    return new Cesium3DTile(content._tileset, baseResource, tileJson, parentTile);
  }

  /**
   * Part of the {@link Cesium3DTileContent} interface.  <code>Implicit3DTileContent</code>
   * always returns <code>false</code> since a tile of this type does not have any features.
   * @private
   */
  Implicit3DTileContent.prototype.hasProperty = function (batchId, name) {
    return false;
  };

  /**
   * Part of the {@link Cesium3DTileContent} interface.  <code>Implicit3DTileContent</code>
   * always returns <code>undefined</code> since a tile of this type does not have any features.
   * @private
   */
  Implicit3DTileContent.prototype.getFeature = function (batchId) {
    return undefined;
  };

  Implicit3DTileContent.prototype.applyDebugSettings = function (
    enabled,
    color
  ) {};

  Implicit3DTileContent.prototype.applyStyle = function (style) {};

  Implicit3DTileContent.prototype.update = function (tileset, frameState) {};

  Implicit3DTileContent.prototype.isDestroyed = function () {
    return false;
  };

  Implicit3DTileContent.prototype.destroy = function () {
    this._implicitSubtree =
      this._implicitSubtree && this._implicitSubtree.destroy();
    return destroyObject(this);
  };

  // Exposed for testing
  Implicit3DTileContent._deriveBoundingBox = deriveBoundingBox;
  Implicit3DTileContent._deriveBoundingRegion = deriveBoundingRegion;
  Implicit3DTileContent._deriveBoundingVolumeS2 = deriveBoundingVolumeS2;

  /**
   * Handles parsing of an Instanced 3D Model.
   *
   * @namespace I3dmParser
   * @private
   */
  const I3dmParser = {};
  I3dmParser._deprecationWarning = deprecationWarning;

  const sizeOfUint32$2 = Uint32Array.BYTES_PER_ELEMENT;

  /**
   * Parses the contents of a {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/TileFormats/Instanced3DModel|Instanced 3D Model}.
   *
   * @private
   *
   * @param {ArrayBuffer} arrayBuffer The array buffer containing the i3dm.
   * @param {Number} [byteOffset=0] The byte offset of the beginning of the i3dm in the array buffer.
   * @returns {Object} Returns an object with the glTF format, feature table (binary and json), batch table (binary and json) and glTF parts of the i3dm.
   */
  I3dmParser.parse = function (arrayBuffer, byteOffset) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("arrayBuffer", arrayBuffer);
    //>>includeEnd('debug');

    const byteStart = defaultValue(byteOffset, 0);
    byteOffset = byteStart;

    const uint8Array = new Uint8Array(arrayBuffer);
    const view = new DataView(arrayBuffer);
    byteOffset += sizeOfUint32$2; // Skip magic

    const version = view.getUint32(byteOffset, true);
    if (version !== 1) {
      throw new RuntimeError(
        `Only Instanced 3D Model version 1 is supported. Version ${version} is not.`
      );
    }
    byteOffset += sizeOfUint32$2;

    const byteLength = view.getUint32(byteOffset, true);
    byteOffset += sizeOfUint32$2;

    const featureTableJsonByteLength = view.getUint32(byteOffset, true);
    if (featureTableJsonByteLength === 0) {
      throw new RuntimeError(
        "featureTableJsonByteLength is zero, the feature table must be defined."
      );
    }
    byteOffset += sizeOfUint32$2;

    const featureTableBinaryByteLength = view.getUint32(byteOffset, true);
    byteOffset += sizeOfUint32$2;

    const batchTableJsonByteLength = view.getUint32(byteOffset, true);
    byteOffset += sizeOfUint32$2;

    const batchTableBinaryByteLength = view.getUint32(byteOffset, true);
    byteOffset += sizeOfUint32$2;

    const gltfFormat = view.getUint32(byteOffset, true);
    if (gltfFormat !== 1 && gltfFormat !== 0) {
      throw new RuntimeError(
        `Only glTF format 0 (uri) or 1 (embedded) are supported. Format ${gltfFormat} is not.`
      );
    }
    byteOffset += sizeOfUint32$2;

    const featureTableJson = getJsonFromTypedArray(
      uint8Array,
      byteOffset,
      featureTableJsonByteLength
    );
    byteOffset += featureTableJsonByteLength;

    const featureTableBinary = new Uint8Array(
      arrayBuffer,
      byteOffset,
      featureTableBinaryByteLength
    );
    byteOffset += featureTableBinaryByteLength;

    let batchTableJson;
    let batchTableBinary;
    if (batchTableJsonByteLength > 0) {
      batchTableJson = getJsonFromTypedArray(
        uint8Array,
        byteOffset,
        batchTableJsonByteLength
      );
      byteOffset += batchTableJsonByteLength;

      if (batchTableBinaryByteLength > 0) {
        // Has a batch table binary
        batchTableBinary = new Uint8Array(
          arrayBuffer,
          byteOffset,
          batchTableBinaryByteLength
        );
        // Copy the batchTableBinary section and let the underlying ArrayBuffer be freed
        batchTableBinary = new Uint8Array(batchTableBinary);
        byteOffset += batchTableBinaryByteLength;
      }
    }

    const gltfByteLength = byteStart + byteLength - byteOffset;
    if (gltfByteLength === 0) {
      throw new RuntimeError("glTF byte length must be greater than 0.");
    }

    let gltfView;
    if (byteOffset % 4 === 0) {
      gltfView = new Uint8Array(arrayBuffer, byteOffset, gltfByteLength);
    } else {
      // Create a copy of the glb so that it is 4-byte aligned
      I3dmParser._deprecationWarning(
        "i3dm-glb-unaligned",
        "The embedded glb is not aligned to a 4-byte boundary."
      );
      gltfView = new Uint8Array(
        uint8Array.subarray(byteOffset, byteOffset + gltfByteLength)
      );
    }

    return {
      gltfFormat: gltfFormat,
      featureTableJson: featureTableJson,
      featureTableBinary: featureTableBinary,
      batchTableJson: batchTableJson,
      batchTableBinary: batchTableBinary,
      gltf: gltfView,
    };
  };

  /**
   * @private
   */
  function ModelInstance(collection, modelMatrix, instanceId) {
    this.primitive = collection;
    this._modelMatrix = Matrix4.clone(modelMatrix);
    this._instanceId = instanceId;
  }

  Object.defineProperties(ModelInstance.prototype, {
    instanceId: {
      get: function () {
        return this._instanceId;
      },
    },
    model: {
      get: function () {
        return this.primitive._model;
      },
    },
    modelMatrix: {
      get: function () {
        return Matrix4.clone(this._modelMatrix);
      },
      set: function (value) {
        Matrix4.clone(value, this._modelMatrix);
        this.primitive.expandBoundingSphere(this._modelMatrix);
        this.primitive._dirty = true;
      },
    },
  });

  const LoadState = {
    NEEDS_LOAD: 0,
    LOADING: 1,
    LOADED: 2,
    FAILED: 3,
  };

  /**
   * A 3D model instance collection. All instances reference the same underlying model, but have unique
   * per-instance properties like model matrix, pick id, etc.
   *
   * Instances are rendered relative-to-center and for best results instances should be positioned close to one another.
   * Otherwise there may be precision issues if, for example, instances are placed on opposite sides of the globe.
   *
   * @alias ModelInstanceCollection
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Object[]} [options.instances] An array of instances, where each instance contains a modelMatrix and optional batchId when options.batchTable is defined.
   * @param {Cesium3DTileBatchTable} [options.batchTable] The batch table of the instanced 3D Tile.
   * @param {Resource|String} [options.url] The url to the .gltf file.
   * @param {Object} [options.requestType] The request type, used for request prioritization
   * @param {Object|ArrayBuffer|Uint8Array} [options.gltf] A glTF JSON object, or a binary glTF buffer.
   * @param {Resource|String} [options.basePath=''] The base path that paths in the glTF JSON are relative to.
   * @param {Boolean} [options.dynamic=false] Hint if instance model matrices will be updated frequently.
   * @param {Boolean} [options.show=true] Determines if the collection will be shown.
   * @param {Boolean} [options.allowPicking=true] When <code>true</code>, each instance is pickable with {@link Scene#pick}.
   * @param {Boolean} [options.asynchronous=true] Determines if model WebGL resource creation will be spread out over several frames or block until completion once all glTF files are loaded.
   * @param {Boolean} [options.incrementallyLoadTextures=true] Determine if textures may continue to stream in after the model is loaded.
   * @param {ShadowMode} [options.shadows=ShadowMode.ENABLED] Determines whether the collection casts or receives shadows from light sources.
   * @param {Cartesian3} [options.lightColor] The light color when shading models. When <code>undefined</code> the scene's light color is used instead.
   * @param {ImageBasedLighting} [options.imageBasedLighting] The properties for managing image-based lighting for this tileset.
   * @param {Boolean} [options.backFaceCulling=true] Whether to cull back-facing geometry. When true, back face culling is determined by the glTF material's doubleSided property; when false, back face culling is disabled.
   * @param {Boolean} [options.showCreditsOnScreen=false] Whether to display the credits of this model on screen.
   * @param {SplitDirection} [options.splitDirection=SplitDirection.NONE] The {@link SplitDirection} split to apply to this collection.
   * @param {Boolean} [options.debugShowBoundingVolume=false] For debugging only. Draws the bounding sphere for the collection.
   * @param {Boolean} [options.debugWireframe=false] For debugging only. Draws the instances in wireframe.
   * @exception {DeveloperError} Must specify either <options.gltf> or <options.url>, but not both.
   * @exception {DeveloperError} Shader program cannot be optimized for instancing. Parameters cannot have any of the following semantics: MODEL, MODELINVERSE, MODELVIEWINVERSE, MODELVIEWPROJECTIONINVERSE, MODELINVERSETRANSPOSE.
   *
   * @private
   */
  function ModelInstanceCollection(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    if (!defined(options.gltf) && !defined(options.url)) {
      throw new DeveloperError("Either options.gltf or options.url is required.");
    }

    if (defined(options.gltf) && defined(options.url)) {
      throw new DeveloperError(
        "Cannot pass in both options.gltf and options.url."
      );
    }
    //>>includeEnd('debug');

    this.show = defaultValue(options.show, true);

    this._instancingSupported = false;
    this._dynamic = defaultValue(options.dynamic, false);
    this._allowPicking = defaultValue(options.allowPicking, true);
    this._ready = false;
    this._readyPromise = defer();
    this._state = LoadState.NEEDS_LOAD;
    this._dirty = false;

    // Undocumented options
    this._cull = defaultValue(options.cull, true);
    this._opaquePass = defaultValue(options.opaquePass, Pass$1.OPAQUE);

    this._instances = createInstances$1(this, options.instances);

    // When the model instance collection is backed by an i3dm tile,
    // use its batch table resources to modify the shaders, attributes, and uniform maps.
    this._batchTable = options.batchTable;

    this._model = undefined;
    this._vertexBufferTypedArray = undefined; // Hold onto the vertex buffer contents when dynamic is true
    this._vertexBuffer = undefined;
    this._batchIdBuffer = undefined;
    this._instancedUniformsByProgram = undefined;

    this._drawCommands = [];
    this._modelCommands = undefined;

    this._renderStates = undefined;
    this._disableCullingRenderStates = undefined;

    this._boundingSphere = createBoundingSphere(this);
    this._center = Cartesian3.clone(this._boundingSphere.center);
    this._rtcTransform = new Matrix4();
    this._rtcModelView = new Matrix4(); // Holds onto uniform

    this._mode = undefined;

    this.modelMatrix = Matrix4.clone(Matrix4.IDENTITY);
    this._modelMatrix = Matrix4.clone(this.modelMatrix);

    // Passed on to Model
    this._url = Resource.createIfNeeded(options.url);
    this._requestType = options.requestType;
    this._gltf = options.gltf;
    this._basePath = Resource.createIfNeeded(options.basePath);
    this._asynchronous = options.asynchronous;
    this._incrementallyLoadTextures = options.incrementallyLoadTextures;
    this._upAxis = options.upAxis; // Undocumented option
    this._forwardAxis = options.forwardAxis; // Undocumented option

    this.shadows = defaultValue(options.shadows, ShadowMode$1.ENABLED);
    this._shadows = this.shadows;

    this._pickIdLoaded = options.pickIdLoaded;

    /**
     * The {@link SplitDirection} to apply to this collection.
     *
     * @type {SplitDirection}
     * @default {@link SplitDirection.NONE}
     */
    this.splitDirection = defaultValue(
      options.splitDirection,
      SplitDirection$1.NONE
    );

    this.debugShowBoundingVolume = defaultValue(
      options.debugShowBoundingVolume,
      false
    );
    this._debugShowBoundingVolume = false;

    this.debugWireframe = defaultValue(options.debugWireframe, false);
    this._debugWireframe = false;

    if (defined(options.imageBasedLighting)) {
      this._imageBasedLighting = options.imageBasedLighting;
      this._shouldDestroyImageBasedLighting = false;
    } else {
      this._imageBasedLighting = new ImageBasedLighting();
      this._shouldDestroyImageBasedLighting = true;
    }

    this.backFaceCulling = defaultValue(options.backFaceCulling, true);
    this._backFaceCulling = this.backFaceCulling;
    this.showCreditsOnScreen = defaultValue(options.showCreditsOnScreen, false);
  }

  Object.defineProperties(ModelInstanceCollection.prototype, {
    allowPicking: {
      get: function () {
        return this._allowPicking;
      },
    },
    length: {
      get: function () {
        return this._instances.length;
      },
    },
    activeAnimations: {
      get: function () {
        return this._model.activeAnimations;
      },
    },
    ready: {
      get: function () {
        return this._ready;
      },
    },
    readyPromise: {
      get: function () {
        return this._readyPromise.promise;
      },
    },
    imageBasedLighting: {
      get: function () {
        return this._imageBasedLighting;
      },
      set: function (value) {
        if (value !== this._imageBasedLighting) {
          if (
            this._shouldDestroyImageBasedLighting &&
            !this._imageBasedLighting.isDestroyed()
          ) {
            this._imageBasedLighting.destroy();
          }
          this._imageBasedLighting = value;
          this._shouldDestroyImageBasedLighting = false;
        }
      },
    },
  });

  function createInstances$1(collection, instancesOptions) {
    instancesOptions = defaultValue(instancesOptions, []);
    const length = instancesOptions.length;
    const instances = new Array(length);
    for (let i = 0; i < length; ++i) {
      const instanceOptions = instancesOptions[i];
      const modelMatrix = instanceOptions.modelMatrix;
      const instanceId = defaultValue(instanceOptions.batchId, i);
      instances[i] = new ModelInstance(collection, modelMatrix, instanceId);
    }
    return instances;
  }

  function createBoundingSphere(collection) {
    const instancesLength = collection.length;
    const points = new Array(instancesLength);
    for (let i = 0; i < instancesLength; ++i) {
      points[i] = Matrix4.getTranslation(
        collection._instances[i]._modelMatrix,
        new Cartesian3()
      );
    }

    return BoundingSphere.fromPoints(points);
  }

  const scratchCartesian$8 = new Cartesian3();
  const scratchMatrix$3 = new Matrix4();

  ModelInstanceCollection.prototype.expandBoundingSphere = function (
    instanceModelMatrix
  ) {
    const translation = Matrix4.getTranslation(
      instanceModelMatrix,
      scratchCartesian$8
    );
    BoundingSphere.expand(
      this._boundingSphere,
      translation,
      this._boundingSphere
    );
  };

  function getCheckUniformSemanticFunction(
    modelSemantics,
    supportedSemantics,
    programId,
    uniformMap
  ) {
    return function (uniform, uniformName) {
      const semantic = uniform.semantic;
      if (defined(semantic) && modelSemantics.indexOf(semantic) > -1) {
        if (supportedSemantics.indexOf(semantic) > -1) {
          uniformMap[uniformName] = semantic;
        } else {
          throw new RuntimeError(
            `${
            "Shader program cannot be optimized for instancing. " + 'Uniform "'
          }${uniformName}" in program "${programId}" uses unsupported semantic "${semantic}"`
          );
        }
      }
    };
  }

  function getInstancedUniforms(collection, programId) {
    if (defined(collection._instancedUniformsByProgram)) {
      return collection._instancedUniformsByProgram[programId];
    }

    const instancedUniformsByProgram = {};
    collection._instancedUniformsByProgram = instancedUniformsByProgram;

    // When using CESIUM_RTC_MODELVIEW the CESIUM_RTC center is ignored. Instances are always rendered relative-to-center.
    const modelSemantics = [
      "MODEL",
      "MODELVIEW",
      "CESIUM_RTC_MODELVIEW",
      "MODELVIEWPROJECTION",
      "MODELINVERSE",
      "MODELVIEWINVERSE",
      "MODELVIEWPROJECTIONINVERSE",
      "MODELINVERSETRANSPOSE",
      "MODELVIEWINVERSETRANSPOSE",
    ];
    const supportedSemantics = [
      "MODELVIEW",
      "CESIUM_RTC_MODELVIEW",
      "MODELVIEWPROJECTION",
      "MODELVIEWINVERSETRANSPOSE",
    ];

    const techniques = collection._model._sourceTechniques;
    for (const techniqueId in techniques) {
      if (techniques.hasOwnProperty(techniqueId)) {
        const technique = techniques[techniqueId];
        const program = technique.program;

        // Different techniques may share the same program, skip if already processed.
        // This assumes techniques that share a program do not declare different semantics for the same uniforms.
        if (!defined(instancedUniformsByProgram[program])) {
          const uniformMap = {};
          instancedUniformsByProgram[program] = uniformMap;
          ForEach.techniqueUniform(
            technique,
            getCheckUniformSemanticFunction(
              modelSemantics,
              supportedSemantics,
              programId,
              uniformMap
            )
          );
        }
      }
    }

    return instancedUniformsByProgram[programId];
  }

  function getVertexShaderCallback(collection) {
    return function (vs, programId) {
      const instancedUniforms = getInstancedUniforms(collection, programId);
      const usesBatchTable = defined(collection._batchTable);

      let renamedSource = ShaderSource.replaceMain(vs, "czm_instancing_main");

      let globalVarsHeader = "";
      let globalVarsMain = "";
      for (const uniform in instancedUniforms) {
        if (instancedUniforms.hasOwnProperty(uniform)) {
          const semantic = instancedUniforms[uniform];
          let varName;
          if (semantic === "MODELVIEW" || semantic === "CESIUM_RTC_MODELVIEW") {
            varName = "czm_instanced_modelView";
          } else if (semantic === "MODELVIEWPROJECTION") {
            varName = "czm_instanced_modelViewProjection";
            globalVarsHeader += "mat4 czm_instanced_modelViewProjection;\n";
            globalVarsMain +=
              "czm_instanced_modelViewProjection = czm_projection * czm_instanced_modelView;\n";
          } else if (semantic === "MODELVIEWINVERSETRANSPOSE") {
            varName = "czm_instanced_modelViewInverseTranspose";
            globalVarsHeader += "mat3 czm_instanced_modelViewInverseTranspose;\n";
            globalVarsMain +=
              "czm_instanced_modelViewInverseTranspose = mat3(czm_instanced_modelView);\n";
          }

          // Remove the uniform declaration
          let regex = new RegExp(`uniform.*${uniform}.*`);
          renamedSource = renamedSource.replace(regex, "");

          // Replace all occurrences of the uniform with the global variable
          regex = new RegExp(`${uniform}\\b`, "g");
          renamedSource = renamedSource.replace(regex, varName);
        }
      }

      // czm_instanced_model is the model matrix of the instance relative to center
      // czm_instanced_modifiedModelView is the transform from the center to view
      // czm_instanced_nodeTransform is the local offset of the node within the model
      const uniforms =
        "uniform mat4 czm_instanced_modifiedModelView;\n" +
        "uniform mat4 czm_instanced_nodeTransform;\n";

      let batchIdAttribute;
      let pickAttribute;
      let pickVarying;

      if (usesBatchTable) {
        batchIdAttribute = "attribute float a_batchId;\n";
        pickAttribute = "";
        pickVarying = "";
      } else {
        batchIdAttribute = "";
        pickAttribute =
          "attribute vec4 pickColor;\n" + "varying vec4 v_pickColor;\n";
        pickVarying = "    v_pickColor = pickColor;\n";
      }

      let instancedSource =
        `${uniforms + globalVarsHeader}mat4 czm_instanced_modelView;\n` +
        `attribute vec4 czm_modelMatrixRow0;\n` +
        `attribute vec4 czm_modelMatrixRow1;\n` +
        `attribute vec4 czm_modelMatrixRow2;\n${batchIdAttribute}${pickAttribute}${renamedSource}void main()\n` +
        `{\n` +
        `    mat4 czm_instanced_model = mat4(czm_modelMatrixRow0.x, czm_modelMatrixRow1.x, czm_modelMatrixRow2.x, 0.0, czm_modelMatrixRow0.y, czm_modelMatrixRow1.y, czm_modelMatrixRow2.y, 0.0, czm_modelMatrixRow0.z, czm_modelMatrixRow1.z, czm_modelMatrixRow2.z, 0.0, czm_modelMatrixRow0.w, czm_modelMatrixRow1.w, czm_modelMatrixRow2.w, 1.0);\n` +
        `    czm_instanced_modelView = czm_instanced_modifiedModelView * czm_instanced_model * czm_instanced_nodeTransform;\n${globalVarsMain}    czm_instancing_main();\n${pickVarying}}\n`;

      if (usesBatchTable) {
        const gltf = collection._model.gltfInternal;
        const diffuseAttributeOrUniformName = ModelUtility.getDiffuseAttributeOrUniform(
          gltf,
          programId
        );
        instancedSource = collection._batchTable.getVertexShaderCallback(
          true,
          "a_batchId",
          diffuseAttributeOrUniformName
        )(instancedSource);
      }

      return instancedSource;
    };
  }

  function getFragmentShaderCallback(collection) {
    return function (fs, programId) {
      const batchTable = collection._batchTable;
      if (defined(batchTable)) {
        const gltf = collection._model.gltfInternal;
        const diffuseAttributeOrUniformName = ModelUtility.getDiffuseAttributeOrUniform(
          gltf,
          programId
        );
        fs = batchTable.getFragmentShaderCallback(
          true,
          diffuseAttributeOrUniformName,
          false
        )(fs);
      } else {
        fs = `varying vec4 v_pickColor;\n${fs}`;
      }
      return fs;
    };
  }

  function createModifiedModelView(collection, context) {
    return function () {
      return Matrix4.multiply(
        context.uniformState.view,
        collection._rtcTransform,
        collection._rtcModelView
      );
    };
  }

  function createNodeTransformFunction(node) {
    return function () {
      return node.computedMatrix;
    };
  }

  function getUniformMapCallback(collection, context) {
    return function (uniformMap, programId, node) {
      uniformMap = clone$1(uniformMap);
      uniformMap.czm_instanced_modifiedModelView = createModifiedModelView(
        collection,
        context
      );
      uniformMap.czm_instanced_nodeTransform = createNodeTransformFunction(node);

      // Remove instanced uniforms from the uniform map
      const instancedUniforms = getInstancedUniforms(collection, programId);
      for (const uniform in instancedUniforms) {
        if (instancedUniforms.hasOwnProperty(uniform)) {
          delete uniformMap[uniform];
        }
      }

      if (defined(collection._batchTable)) {
        uniformMap = collection._batchTable.getUniformMapCallback()(uniformMap);
      }

      return uniformMap;
    };
  }

  function getVertexShaderNonInstancedCallback(collection) {
    return function (vs, programId) {
      if (defined(collection._batchTable)) {
        const gltf = collection._model.gltfInternal;
        const diffuseAttributeOrUniformName = ModelUtility.getDiffuseAttributeOrUniform(
          gltf,
          programId
        );
        vs = collection._batchTable.getVertexShaderCallback(
          true,
          "a_batchId",
          diffuseAttributeOrUniformName
        )(vs);
        // Treat a_batchId as a uniform rather than a vertex attribute
        vs = `uniform float a_batchId\n;${vs}`;
      }
      return vs;
    };
  }

  function getFragmentShaderNonInstancedCallback(collection) {
    return function (fs, programId) {
      const batchTable = collection._batchTable;
      if (defined(batchTable)) {
        const gltf = collection._model.gltfInternal;
        const diffuseAttributeOrUniformName = ModelUtility.getDiffuseAttributeOrUniform(
          gltf,
          programId
        );
        fs = batchTable.getFragmentShaderCallback(
          true,
          diffuseAttributeOrUniformName,
          false
        )(fs);
      } else {
        fs = `uniform vec4 czm_pickColor;\n${fs}`;
      }
      return fs;
    };
  }

  function getUniformMapNonInstancedCallback(collection) {
    return function (uniformMap) {
      if (defined(collection._batchTable)) {
        uniformMap = collection._batchTable.getUniformMapCallback()(uniformMap);
      }

      return uniformMap;
    };
  }

  function getVertexBufferTypedArray(collection) {
    const instances = collection._instances;
    const instancesLength = collection.length;
    const collectionCenter = collection._center;
    const vertexSizeInFloats = 12;

    let bufferData = collection._vertexBufferTypedArray;
    if (!defined(bufferData)) {
      bufferData = new Float32Array(instancesLength * vertexSizeInFloats);
    }
    if (collection._dynamic) {
      // Hold onto the buffer data so we don't have to allocate new memory every frame.
      collection._vertexBufferTypedArray = bufferData;
    }

    for (let i = 0; i < instancesLength; ++i) {
      const modelMatrix = instances[i]._modelMatrix;

      // Instance matrix is relative to center
      const instanceMatrix = Matrix4.clone(modelMatrix, scratchMatrix$3);
      instanceMatrix[12] -= collectionCenter.x;
      instanceMatrix[13] -= collectionCenter.y;
      instanceMatrix[14] -= collectionCenter.z;

      const offset = i * vertexSizeInFloats;

      // First three rows of the model matrix
      bufferData[offset + 0] = instanceMatrix[0];
      bufferData[offset + 1] = instanceMatrix[4];
      bufferData[offset + 2] = instanceMatrix[8];
      bufferData[offset + 3] = instanceMatrix[12];
      bufferData[offset + 4] = instanceMatrix[1];
      bufferData[offset + 5] = instanceMatrix[5];
      bufferData[offset + 6] = instanceMatrix[9];
      bufferData[offset + 7] = instanceMatrix[13];
      bufferData[offset + 8] = instanceMatrix[2];
      bufferData[offset + 9] = instanceMatrix[6];
      bufferData[offset + 10] = instanceMatrix[10];
      bufferData[offset + 11] = instanceMatrix[14];
    }

    return bufferData;
  }

  function createVertexBuffer$1(collection, context) {
    let i;
    const instances = collection._instances;
    const instancesLength = collection.length;
    const dynamic = collection._dynamic;
    const usesBatchTable = defined(collection._batchTable);

    if (usesBatchTable) {
      const batchIdBufferData = new Uint16Array(instancesLength);
      for (i = 0; i < instancesLength; ++i) {
        batchIdBufferData[i] = instances[i]._instanceId;
      }
      collection._batchIdBuffer = Buffer$1.createVertexBuffer({
        context: context,
        typedArray: batchIdBufferData,
        usage: BufferUsage$1.STATIC_DRAW,
      });
    }

    if (!usesBatchTable) {
      const pickIdBuffer = new Uint8Array(instancesLength * 4);
      for (i = 0; i < instancesLength; ++i) {
        const pickId = collection._pickIds[i];
        const pickColor = pickId.color;
        const offset = i * 4;
        pickIdBuffer[offset] = Color.floatToByte(pickColor.red);
        pickIdBuffer[offset + 1] = Color.floatToByte(pickColor.green);
        pickIdBuffer[offset + 2] = Color.floatToByte(pickColor.blue);
        pickIdBuffer[offset + 3] = Color.floatToByte(pickColor.alpha);
      }
      collection._pickIdBuffer = Buffer$1.createVertexBuffer({
        context: context,
        typedArray: pickIdBuffer,
        usage: BufferUsage$1.STATIC_DRAW,
      });
    }

    const vertexBufferTypedArray = getVertexBufferTypedArray(collection);
    collection._vertexBuffer = Buffer$1.createVertexBuffer({
      context: context,
      typedArray: vertexBufferTypedArray,
      usage: dynamic ? BufferUsage$1.STREAM_DRAW : BufferUsage$1.STATIC_DRAW,
    });
  }

  function updateVertexBuffer(collection) {
    const vertexBufferTypedArray = getVertexBufferTypedArray(collection);
    collection._vertexBuffer.copyFromArrayView(vertexBufferTypedArray);
  }

  function createPickIds(collection, context) {
    // PERFORMANCE_IDEA: we could skip the pick buffer completely by allocating
    // a continuous range of pickIds and then converting the base pickId + batchId
    // to RGBA in the shader.  The only consider is precision issues, which might
    // not be an issue in WebGL 2.
    const instances = collection._instances;
    const instancesLength = instances.length;
    const pickIds = new Array(instancesLength);
    for (let i = 0; i < instancesLength; ++i) {
      pickIds[i] = context.createPickId(instances[i]);
    }
    return pickIds;
  }

  function createModel$1(collection, context) {
    const instancingSupported = collection._instancingSupported;
    const usesBatchTable = defined(collection._batchTable);
    const allowPicking = collection._allowPicking;

    const modelOptions = {
      url: collection._url,
      requestType: collection._requestType,
      gltf: collection._gltf,
      basePath: collection._basePath,
      shadows: collection._shadows,
      cacheKey: undefined,
      asynchronous: collection._asynchronous,
      allowPicking: allowPicking,
      incrementallyLoadTextures: collection._incrementallyLoadTextures,
      upAxis: collection._upAxis,
      forwardAxis: collection._forwardAxis,
      precreatedAttributes: undefined,
      vertexShaderLoaded: undefined,
      fragmentShaderLoaded: undefined,
      uniformMapLoaded: undefined,
      pickIdLoaded: collection._pickIdLoaded,
      ignoreCommands: true,
      opaquePass: collection._opaquePass,
      imageBasedLighting: collection._imageBasedLighting,
      showOutline: collection.showOutline,
      showCreditsOnScreen: collection.showCreditsOnScreen,
    };

    if (!usesBatchTable) {
      collection._pickIds = createPickIds(collection, context);
    }

    if (instancingSupported) {
      createVertexBuffer$1(collection, context);

      const vertexSizeInFloats = 12;
      const componentSizeInBytes = ComponentDatatype$1.getSizeInBytes(
        ComponentDatatype$1.FLOAT
      );

      const instancedAttributes = {
        czm_modelMatrixRow0: {
          index: 0, // updated in Model
          vertexBuffer: collection._vertexBuffer,
          componentsPerAttribute: 4,
          componentDatatype: ComponentDatatype$1.FLOAT,
          normalize: false,
          offsetInBytes: 0,
          strideInBytes: componentSizeInBytes * vertexSizeInFloats,
          instanceDivisor: 1,
        },
        czm_modelMatrixRow1: {
          index: 0, // updated in Model
          vertexBuffer: collection._vertexBuffer,
          componentsPerAttribute: 4,
          componentDatatype: ComponentDatatype$1.FLOAT,
          normalize: false,
          offsetInBytes: componentSizeInBytes * 4,
          strideInBytes: componentSizeInBytes * vertexSizeInFloats,
          instanceDivisor: 1,
        },
        czm_modelMatrixRow2: {
          index: 0, // updated in Model
          vertexBuffer: collection._vertexBuffer,
          componentsPerAttribute: 4,
          componentDatatype: ComponentDatatype$1.FLOAT,
          normalize: false,
          offsetInBytes: componentSizeInBytes * 8,
          strideInBytes: componentSizeInBytes * vertexSizeInFloats,
          instanceDivisor: 1,
        },
      };

      // When using a batch table, add a batch id attribute
      if (usesBatchTable) {
        instancedAttributes.a_batchId = {
          index: 0, // updated in Model
          vertexBuffer: collection._batchIdBuffer,
          componentsPerAttribute: 1,
          componentDatatype: ComponentDatatype$1.UNSIGNED_SHORT,
          normalize: false,
          offsetInBytes: 0,
          strideInBytes: 0,
          instanceDivisor: 1,
        };
      }

      if (!usesBatchTable) {
        instancedAttributes.pickColor = {
          index: 0, // updated in Model
          vertexBuffer: collection._pickIdBuffer,
          componentsPerAttribute: 4,
          componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
          normalize: true,
          offsetInBytes: 0,
          strideInBytes: 0,
          instanceDivisor: 1,
        };
      }

      modelOptions.precreatedAttributes = instancedAttributes;
      modelOptions.vertexShaderLoaded = getVertexShaderCallback(collection);
      modelOptions.fragmentShaderLoaded = getFragmentShaderCallback(collection);
      modelOptions.uniformMapLoaded = getUniformMapCallback(collection, context);

      if (defined(collection._url)) {
        modelOptions.cacheKey = `${collection._url.getUrlComponent()}#instanced`;
      }
    } else {
      modelOptions.vertexShaderLoaded = getVertexShaderNonInstancedCallback(
        collection
      );
      modelOptions.fragmentShaderLoaded = getFragmentShaderNonInstancedCallback(
        collection
      );
      modelOptions.uniformMapLoaded = getUniformMapNonInstancedCallback(
        collection);
    }

    if (defined(collection._url)) {
      collection._model = Model.fromGltf(modelOptions);
    } else {
      collection._model = new Model(modelOptions);
    }
  }

  function updateWireframe(collection, force) {
    if (collection._debugWireframe !== collection.debugWireframe || force) {
      collection._debugWireframe = collection.debugWireframe;

      // This assumes the original primitive was TRIANGLES and that the triangles
      // are connected for the wireframe to look perfect.
      const primitiveType = collection.debugWireframe
        ? PrimitiveType$1.LINES
        : PrimitiveType$1.TRIANGLES;
      const commands = collection._drawCommands;
      const length = commands.length;
      for (let i = 0; i < length; ++i) {
        commands[i].primitiveType = primitiveType;
      }
    }
  }

  function getDisableCullingRenderState(renderState) {
    const rs = clone$1(renderState, true);
    rs.cull.enabled = false;
    return RenderState.fromCache(rs);
  }

  function updateBackFaceCulling$1(collection, force) {
    if (collection._backFaceCulling !== collection.backFaceCulling || force) {
      collection._backFaceCulling = collection.backFaceCulling;

      const commands = collection._drawCommands;
      const length = commands.length;
      let i;

      if (!defined(collection._disableCullingRenderStates)) {
        collection._disableCullingRenderStates = new Array(length);
        collection._renderStates = new Array(length);
        for (i = 0; i < length; ++i) {
          const renderState = commands[i].renderState;
          const derivedRenderState = getDisableCullingRenderState(renderState);
          collection._disableCullingRenderStates[i] = derivedRenderState;
          collection._renderStates[i] = renderState;
        }
      }

      for (i = 0; i < length; ++i) {
        commands[i].renderState = collection._backFaceCulling
          ? collection._renderStates[i]
          : collection._disableCullingRenderStates[i];
      }
    }
  }

  function updateShowBoundingVolume$1(collection, force) {
    if (
      collection.debugShowBoundingVolume !==
        collection._debugShowBoundingVolume ||
      force
    ) {
      collection._debugShowBoundingVolume = collection.debugShowBoundingVolume;

      const commands = collection._drawCommands;
      const length = commands.length;
      for (let i = 0; i < length; ++i) {
        commands[i].debugShowBoundingVolume = collection.debugShowBoundingVolume;
      }
    }
  }

  function createCommands$2(collection, drawCommands) {
    const commandsLength = drawCommands.length;
    const instancesLength = collection.length;
    const boundingSphere = collection._boundingSphere;
    const cull = collection._cull;

    for (let i = 0; i < commandsLength; ++i) {
      const drawCommand = DrawCommand.shallowClone(drawCommands[i]);
      drawCommand.instanceCount = instancesLength;
      drawCommand.boundingVolume = boundingSphere;
      drawCommand.cull = cull;
      if (defined(collection._batchTable)) {
        drawCommand.pickId = collection._batchTable.getPickId();
      } else {
        drawCommand.pickId = "v_pickColor";
      }
      collection._drawCommands.push(drawCommand);
    }
  }

  function createBatchIdFunction(batchId) {
    return function () {
      return batchId;
    };
  }

  function createPickColorFunction(color) {
    return function () {
      return color;
    };
  }

  function createCommandsNonInstanced(collection, drawCommands) {
    // When instancing is disabled, create commands for every instance.
    const instances = collection._instances;
    const commandsLength = drawCommands.length;
    const instancesLength = collection.length;
    const batchTable = collection._batchTable;
    const usesBatchTable = defined(batchTable);
    const cull = collection._cull;

    for (let i = 0; i < commandsLength; ++i) {
      for (let j = 0; j < instancesLength; ++j) {
        const drawCommand = DrawCommand.shallowClone(drawCommands[i]);
        drawCommand.modelMatrix = new Matrix4(); // Updated in updateCommandsNonInstanced
        drawCommand.boundingVolume = new BoundingSphere(); // Updated in updateCommandsNonInstanced
        drawCommand.cull = cull;
        drawCommand.uniformMap = clone$1(drawCommand.uniformMap);
        if (usesBatchTable) {
          drawCommand.uniformMap.a_batchId = createBatchIdFunction(
            instances[j]._instanceId
          );
        } else {
          const pickId = collection._pickIds[j];
          drawCommand.uniformMap.czm_pickColor = createPickColorFunction(
            pickId.color
          );
        }
        collection._drawCommands.push(drawCommand);
      }
    }
  }

  function updateCommandsNonInstanced(collection) {
    const modelCommands = collection._modelCommands;
    const commandsLength = modelCommands.length;
    const instancesLength = collection.length;
    const collectionTransform = collection._rtcTransform;
    const collectionCenter = collection._center;

    for (let i = 0; i < commandsLength; ++i) {
      const modelCommand = modelCommands[i];
      for (let j = 0; j < instancesLength; ++j) {
        const commandIndex = i * instancesLength + j;
        const drawCommand = collection._drawCommands[commandIndex];
        let instanceMatrix = Matrix4.clone(
          collection._instances[j]._modelMatrix,
          scratchMatrix$3
        );
        instanceMatrix[12] -= collectionCenter.x;
        instanceMatrix[13] -= collectionCenter.y;
        instanceMatrix[14] -= collectionCenter.z;
        instanceMatrix = Matrix4.multiply(
          collectionTransform,
          instanceMatrix,
          scratchMatrix$3
        );
        const nodeMatrix = modelCommand.modelMatrix;
        const modelMatrix = drawCommand.modelMatrix;
        Matrix4.multiply(instanceMatrix, nodeMatrix, modelMatrix);

        const nodeBoundingSphere = modelCommand.boundingVolume;
        const boundingSphere = drawCommand.boundingVolume;
        BoundingSphere.transform(
          nodeBoundingSphere,
          instanceMatrix,
          boundingSphere
        );
      }
    }
  }

  function getModelCommands(model) {
    const nodeCommands = model._nodeCommands;
    const length = nodeCommands.length;

    const drawCommands = [];

    for (let i = 0; i < length; ++i) {
      const nc = nodeCommands[i];
      if (nc.show) {
        drawCommands.push(nc.command);
      }
    }

    return drawCommands;
  }

  function commandsDirty(model) {
    const nodeCommands = model._nodeCommands;
    const length = nodeCommands.length;

    let commandsDirty = false;

    for (let i = 0; i < length; i++) {
      const nc = nodeCommands[i];
      if (nc.command.dirty) {
        nc.command.dirty = false;
        commandsDirty = true;
      }
    }
    return commandsDirty;
  }

  function generateModelCommands(modelInstanceCollection, instancingSupported) {
    modelInstanceCollection._drawCommands = [];

    const modelCommands = getModelCommands(modelInstanceCollection._model);
    if (instancingSupported) {
      createCommands$2(modelInstanceCollection, modelCommands);
    } else {
      createCommandsNonInstanced(modelInstanceCollection, modelCommands);
      updateCommandsNonInstanced(modelInstanceCollection);
    }
  }

  function updateShadows$1(collection, force) {
    if (collection.shadows !== collection._shadows || force) {
      collection._shadows = collection.shadows;

      const castShadows = ShadowMode$1.castShadows(collection.shadows);
      const receiveShadows = ShadowMode$1.receiveShadows(collection.shadows);

      const drawCommands = collection._drawCommands;
      const length = drawCommands.length;
      for (let i = 0; i < length; ++i) {
        const drawCommand = drawCommands[i];
        drawCommand.castShadows = castShadows;
        drawCommand.receiveShadows = receiveShadows;
      }
    }
  }

  ModelInstanceCollection.prototype.update = function (frameState) {
    if (frameState.mode === SceneMode$1.MORPHING) {
      return;
    }

    if (!this.show) {
      return;
    }

    if (this.length === 0) {
      return;
    }

    const context = frameState.context;

    if (this._state === LoadState.NEEDS_LOAD) {
      this._state = LoadState.LOADING;
      this._instancingSupported = context.instancedArrays;
      createModel$1(this, context);
      const that = this;
      this._model.readyPromise.catch(function (error) {
        that._state = LoadState.FAILED;
        that._readyPromise.reject(error);
      });
    }

    const instancingSupported = this._instancingSupported;
    const model = this._model;

    model.imageBasedLighting = this._imageBasedLighting;
    model.showCreditsOnScreen = this.showCreditsOnScreen;
    model.splitDirection = this.splitDirection;

    model.update(frameState);

    if (model.ready && this._state === LoadState.LOADING) {
      this._state = LoadState.LOADED;
      this._ready = true;

      // Expand bounding volume to fit the radius of the loaded model including the model's offset from the center
      const modelRadius =
        model.boundingSphereInternal.radius +
        Cartesian3.magnitude(model.boundingSphereInternal.center);
      this._boundingSphere.radius += modelRadius;
      this._modelCommands = getModelCommands(model);

      generateModelCommands(this, instancingSupported);

      this._readyPromise.resolve(this);
      return;
    }

    if (this._state !== LoadState.LOADED) {
      return;
    }

    const modeChanged = frameState.mode !== this._mode;
    const modelMatrix = this.modelMatrix;
    const modelMatrixChanged = !Matrix4.equals(this._modelMatrix, modelMatrix);

    if (modeChanged || modelMatrixChanged) {
      this._mode = frameState.mode;
      Matrix4.clone(modelMatrix, this._modelMatrix);
      let rtcTransform = Matrix4.multiplyByTranslation(
        this._modelMatrix,
        this._center,
        this._rtcTransform
      );
      if (this._mode !== SceneMode$1.SCENE3D) {
        rtcTransform = Transforms.basisTo2D(
          frameState.mapProjection,
          rtcTransform,
          rtcTransform
        );
      }
      Matrix4.getTranslation(rtcTransform, this._boundingSphere.center);
    }

    if (instancingSupported && this._dirty) {
      // If at least one instance has moved assume the collection is now dynamic
      this._dynamic = true;
      this._dirty = false;

      // PERFORMANCE_IDEA: only update dirty sub-sections instead of the whole collection
      updateVertexBuffer(this);
    }

    // If the model was set to rebuild shaders during update, rebuild instanced commands.
    const modelCommandsDirty = commandsDirty(model);
    if (modelCommandsDirty) {
      generateModelCommands(this, instancingSupported);
    }

    // If any node changes due to an animation, update the commands. This could be inefficient if the model is
    // composed of many nodes and only one changes, however it is probably fine in the general use case.
    // Only applies when instancing is disabled. The instanced shader automatically handles node transformations.
    if (
      !instancingSupported &&
      (model.dirty || this._dirty || modeChanged || modelMatrixChanged)
    ) {
      updateCommandsNonInstanced(this);
    }

    updateShadows$1(this, modelCommandsDirty);
    updateWireframe(this, modelCommandsDirty);
    updateBackFaceCulling$1(this, modelCommandsDirty);
    updateShowBoundingVolume$1(this, modelCommandsDirty);

    const passes = frameState.passes;
    if (!passes.render && !passes.pick) {
      return;
    }

    const commandList = frameState.commandList;
    const commands = this._drawCommands;
    const commandsLength = commands.length;

    for (let i = 0; i < commandsLength; ++i) {
      commandList.push(commands[i]);
    }
  };

  ModelInstanceCollection.prototype.isDestroyed = function () {
    return false;
  };

  ModelInstanceCollection.prototype.destroy = function () {
    this._model = this._model && this._model.destroy();

    const pickIds = this._pickIds;
    if (defined(pickIds)) {
      const length = pickIds.length;
      for (let i = 0; i < length; ++i) {
        pickIds[i].destroy();
      }
    }

    if (
      this._shouldDestroyImageBasedLighting &&
      !this._imageBasedLighting.isDestroyed()
    ) {
      this._imageBasedLighting.destroy();
    }
    this._imageBasedLighting = undefined;

    return destroyObject(this);
  };

  /**
   * Represents the contents of a
   * {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/TileFormats/Instanced3DModel|Instanced 3D Model}
   * tile in a {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification|3D Tiles} tileset.
   * <p>
   * Implements the {@link Cesium3DTileContent} interface.
   * </p>
   *
   * @alias Instanced3DModel3DTileContent
   * @constructor
   *
   * @private
   */
  function Instanced3DModel3DTileContent(
    tileset,
    tile,
    resource,
    arrayBuffer,
    byteOffset
  ) {
    this._tileset = tileset;
    this._tile = tile;
    this._resource = resource;
    this._modelInstanceCollection = undefined;

    this._metadata = undefined;

    this._batchTable = undefined;
    this._features = undefined;

    this.featurePropertiesDirty = false;
    this._group = undefined;

    initialize$g(this, arrayBuffer, byteOffset);
  }

  // This can be overridden for testing purposes
  Instanced3DModel3DTileContent._deprecationWarning = deprecationWarning;

  Object.defineProperties(Instanced3DModel3DTileContent.prototype, {
    featuresLength: {
      get: function () {
        return this._batchTable.featuresLength;
      },
    },

    pointsLength: {
      get: function () {
        return 0;
      },
    },

    trianglesLength: {
      get: function () {
        const model = this._modelInstanceCollection._model;
        if (defined(model)) {
          return model.trianglesLength;
        }
        return 0;
      },
    },

    geometryByteLength: {
      get: function () {
        const model = this._modelInstanceCollection._model;
        if (defined(model)) {
          return model.geometryByteLength;
        }
        return 0;
      },
    },

    texturesByteLength: {
      get: function () {
        const model = this._modelInstanceCollection._model;
        if (defined(model)) {
          return model.texturesByteLength;
        }
        return 0;
      },
    },

    batchTableByteLength: {
      get: function () {
        return this._batchTable.batchTableByteLength;
      },
    },

    innerContents: {
      get: function () {
        return undefined;
      },
    },

    readyPromise: {
      get: function () {
        return this._modelInstanceCollection.readyPromise;
      },
    },

    tileset: {
      get: function () {
        return this._tileset;
      },
    },

    tile: {
      get: function () {
        return this._tile;
      },
    },

    url: {
      get: function () {
        return this._resource.getUrlComponent(true);
      },
    },

    metadata: {
      get: function () {
        return this._metadata;
      },
      set: function (value) {
        this._metadata = value;
      },
    },

    batchTable: {
      get: function () {
        return this._batchTable;
      },
    },

    group: {
      get: function () {
        return this._group;
      },
      set: function (value) {
        this._group = value;
      },
    },
  });

  function getPickIdCallback(content) {
    return function () {
      return content._batchTable.getPickId();
    };
  }

  const propertyScratch1$1 = new Array(4);
  const propertyScratch2$1 = new Array(4);

  function initialize$g(content, arrayBuffer, byteOffset) {
    const i3dm = I3dmParser.parse(arrayBuffer, byteOffset);

    const gltfFormat = i3dm.gltfFormat;
    const gltfView = i3dm.gltf;
    const featureTableJson = i3dm.featureTableJson;
    const featureTableBinary = i3dm.featureTableBinary;
    const batchTableJson = i3dm.batchTableJson;
    const batchTableBinary = i3dm.batchTableBinary;

    const featureTable = new Cesium3DTileFeatureTable(
      featureTableJson,
      featureTableBinary
    );
    const instancesLength = featureTable.getGlobalProperty("INSTANCES_LENGTH");
    featureTable.featuresLength = instancesLength;

    if (!defined(instancesLength)) {
      throw new RuntimeError(
        "Feature table global property: INSTANCES_LENGTH must be defined"
      );
    }

    content._batchTable = new Cesium3DTileBatchTable(
      content,
      instancesLength,
      batchTableJson,
      batchTableBinary
    );

    const tileset = content._tileset;

    // Create model instance collection
    const collectionOptions = {
      instances: new Array(instancesLength),
      batchTable: content._batchTable,
      cull: false, // Already culled by 3D Tiles
      url: undefined,
      requestType: RequestType$1.TILES3D,
      gltf: undefined,
      basePath: undefined,
      incrementallyLoadTextures: false,
      upAxis: tileset._modelUpAxis,
      forwardAxis: tileset._modelForwardAxis,
      opaquePass: Pass$1.CESIUM_3D_TILE, // Draw opaque portions during the 3D Tiles pass
      pickIdLoaded: getPickIdCallback(content),
      imageBasedLighting: tileset.imageBasedLighting,
      backFaceCulling: tileset.backFaceCulling,
      showOutline: tileset.showOutline,
      showCreditsOnScreen: tileset.showCreditsOnScreen,
    };

    if (gltfFormat === 0) {
      let gltfUrl = getStringFromTypedArray(gltfView);

      // We need to remove padding from the end of the model URL in case this tile was part of a composite tile.
      // This removes all white space and null characters from the end of the string.
      gltfUrl = gltfUrl.replace(/[\s\0]+$/, "");
      collectionOptions.url = content._resource.getDerivedResource({
        url: gltfUrl,
      });
    } else {
      collectionOptions.gltf = gltfView;
      collectionOptions.basePath = content._resource.clone();
    }

    const eastNorthUp = featureTable.getGlobalProperty("EAST_NORTH_UP");

    let rtcCenter;
    const rtcCenterArray = featureTable.getGlobalProperty(
      "RTC_CENTER",
      ComponentDatatype$1.FLOAT,
      3
    );
    if (defined(rtcCenterArray)) {
      rtcCenter = Cartesian3.unpack(rtcCenterArray);
    }

    const instances = collectionOptions.instances;
    const instancePosition = new Cartesian3();
    const instancePositionArray = new Array(3);
    const instanceNormalRight = new Cartesian3();
    const instanceNormalUp = new Cartesian3();
    const instanceNormalForward = new Cartesian3();
    const instanceRotation = new Matrix3();
    const instanceQuaternion = new Quaternion();
    let instanceScale = new Cartesian3();
    const instanceTranslationRotationScale = new TranslationRotationScale();
    const instanceTransform = new Matrix4();
    for (let i = 0; i < instancesLength; i++) {
      // Get the instance position
      let position = featureTable.getProperty(
        "POSITION",
        ComponentDatatype$1.FLOAT,
        3,
        i,
        propertyScratch1$1
      );
      if (!defined(position)) {
        position = instancePositionArray;
        const positionQuantized = featureTable.getProperty(
          "POSITION_QUANTIZED",
          ComponentDatatype$1.UNSIGNED_SHORT,
          3,
          i,
          propertyScratch1$1
        );
        if (!defined(positionQuantized)) {
          throw new RuntimeError(
            "Either POSITION or POSITION_QUANTIZED must be defined for each instance."
          );
        }
        const quantizedVolumeOffset = featureTable.getGlobalProperty(
          "QUANTIZED_VOLUME_OFFSET",
          ComponentDatatype$1.FLOAT,
          3
        );
        if (!defined(quantizedVolumeOffset)) {
          throw new RuntimeError(
            "Global property: QUANTIZED_VOLUME_OFFSET must be defined for quantized positions."
          );
        }
        const quantizedVolumeScale = featureTable.getGlobalProperty(
          "QUANTIZED_VOLUME_SCALE",
          ComponentDatatype$1.FLOAT,
          3
        );
        if (!defined(quantizedVolumeScale)) {
          throw new RuntimeError(
            "Global property: QUANTIZED_VOLUME_SCALE must be defined for quantized positions."
          );
        }
        for (let j = 0; j < 3; j++) {
          position[j] =
            (positionQuantized[j] / 65535.0) * quantizedVolumeScale[j] +
            quantizedVolumeOffset[j];
        }
      }
      Cartesian3.unpack(position, 0, instancePosition);
      if (defined(rtcCenter)) {
        Cartesian3.add(instancePosition, rtcCenter, instancePosition);
      }
      instanceTranslationRotationScale.translation = instancePosition;

      // Get the instance rotation
      const normalUp = featureTable.getProperty(
        "NORMAL_UP",
        ComponentDatatype$1.FLOAT,
        3,
        i,
        propertyScratch1$1
      );
      const normalRight = featureTable.getProperty(
        "NORMAL_RIGHT",
        ComponentDatatype$1.FLOAT,
        3,
        i,
        propertyScratch2$1
      );
      let hasCustomOrientation = false;
      if (defined(normalUp)) {
        if (!defined(normalRight)) {
          throw new RuntimeError(
            "To define a custom orientation, both NORMAL_UP and NORMAL_RIGHT must be defined."
          );
        }
        Cartesian3.unpack(normalUp, 0, instanceNormalUp);
        Cartesian3.unpack(normalRight, 0, instanceNormalRight);
        hasCustomOrientation = true;
      } else {
        const octNormalUp = featureTable.getProperty(
          "NORMAL_UP_OCT32P",
          ComponentDatatype$1.UNSIGNED_SHORT,
          2,
          i,
          propertyScratch1$1
        );
        const octNormalRight = featureTable.getProperty(
          "NORMAL_RIGHT_OCT32P",
          ComponentDatatype$1.UNSIGNED_SHORT,
          2,
          i,
          propertyScratch2$1
        );
        if (defined(octNormalUp)) {
          if (!defined(octNormalRight)) {
            throw new RuntimeError(
              "To define a custom orientation with oct-encoded vectors, both NORMAL_UP_OCT32P and NORMAL_RIGHT_OCT32P must be defined."
            );
          }
          AttributeCompression.octDecodeInRange(
            octNormalUp[0],
            octNormalUp[1],
            65535,
            instanceNormalUp
          );
          AttributeCompression.octDecodeInRange(
            octNormalRight[0],
            octNormalRight[1],
            65535,
            instanceNormalRight
          );
          hasCustomOrientation = true;
        } else if (eastNorthUp) {
          Transforms.eastNorthUpToFixedFrame(
            instancePosition,
            Ellipsoid.WGS84,
            instanceTransform
          );
          Matrix4.getMatrix3(instanceTransform, instanceRotation);
        } else {
          Matrix3.clone(Matrix3.IDENTITY, instanceRotation);
        }
      }
      if (hasCustomOrientation) {
        Cartesian3.cross(
          instanceNormalRight,
          instanceNormalUp,
          instanceNormalForward
        );
        Cartesian3.normalize(instanceNormalForward, instanceNormalForward);
        Matrix3.setColumn(
          instanceRotation,
          0,
          instanceNormalRight,
          instanceRotation
        );
        Matrix3.setColumn(
          instanceRotation,
          1,
          instanceNormalUp,
          instanceRotation
        );
        Matrix3.setColumn(
          instanceRotation,
          2,
          instanceNormalForward,
          instanceRotation
        );
      }
      Quaternion.fromRotationMatrix(instanceRotation, instanceQuaternion);
      instanceTranslationRotationScale.rotation = instanceQuaternion;

      // Get the instance scale
      instanceScale = Cartesian3.fromElements(1.0, 1.0, 1.0, instanceScale);
      const scale = featureTable.getProperty(
        "SCALE",
        ComponentDatatype$1.FLOAT,
        1,
        i
      );
      if (defined(scale)) {
        Cartesian3.multiplyByScalar(instanceScale, scale, instanceScale);
      }
      const nonUniformScale = featureTable.getProperty(
        "SCALE_NON_UNIFORM",
        ComponentDatatype$1.FLOAT,
        3,
        i,
        propertyScratch1$1
      );
      if (defined(nonUniformScale)) {
        instanceScale.x *= nonUniformScale[0];
        instanceScale.y *= nonUniformScale[1];
        instanceScale.z *= nonUniformScale[2];
      }
      instanceTranslationRotationScale.scale = instanceScale;

      // Get the batchId
      let batchId = featureTable.getProperty(
        "BATCH_ID",
        ComponentDatatype$1.UNSIGNED_SHORT,
        1,
        i
      );
      if (!defined(batchId)) {
        // If BATCH_ID semantic is undefined, batchId is just the instance number
        batchId = i;
      }

      // Create the model matrix and the instance
      Matrix4.fromTranslationRotationScale(
        instanceTranslationRotationScale,
        instanceTransform
      );
      const modelMatrix = instanceTransform.clone();
      instances[i] = {
        modelMatrix: modelMatrix,
        batchId: batchId,
      };
    }

    content._modelInstanceCollection = new ModelInstanceCollection(
      collectionOptions
    );
    content._modelInstanceCollection.readyPromise
      .catch(function () {
        // Any readyPromise failure is handled in modelInstanceCollection
      })
      .then(function (collection) {
        if (content._modelInstanceCollection.ready) {
          collection.activeAnimations.addAll({
            loop: ModelAnimationLoop$1.REPEAT,
          });
        }
      });
  }

  function createFeatures$2(content) {
    const featuresLength = content.featuresLength;
    if (!defined(content._features) && featuresLength > 0) {
      const features = new Array(featuresLength);
      for (let i = 0; i < featuresLength; ++i) {
        features[i] = new Cesium3DTileFeature(content, i);
      }
      content._features = features;
    }
  }

  Instanced3DModel3DTileContent.prototype.hasProperty = function (batchId, name) {
    return this._batchTable.hasProperty(batchId, name);
  };

  Instanced3DModel3DTileContent.prototype.getFeature = function (batchId) {
    const featuresLength = this.featuresLength;
    //>>includeStart('debug', pragmas.debug);
    if (!defined(batchId) || batchId < 0 || batchId >= featuresLength) {
      throw new DeveloperError(
        `batchId is required and between zero and featuresLength - 1 (${
        featuresLength - 1
      }).`
      );
    }
    //>>includeEnd('debug');

    createFeatures$2(this);
    return this._features[batchId];
  };

  Instanced3DModel3DTileContent.prototype.applyDebugSettings = function (
    enabled,
    color
  ) {
    color = enabled ? color : Color.WHITE;
    this._batchTable.setAllColor(color);
  };

  Instanced3DModel3DTileContent.prototype.applyStyle = function (style) {
    this._batchTable.applyStyle(style);
  };

  Instanced3DModel3DTileContent.prototype.update = function (
    tileset,
    frameState
  ) {
    const commandStart = frameState.commandList.length;

    // In the PROCESSING state we may be calling update() to move forward
    // the content's resource loading.  In the READY state, it will
    // actually generate commands.
    this._batchTable.update(tileset, frameState);
    this._modelInstanceCollection.modelMatrix = this._tile.computedTransform;
    this._modelInstanceCollection.shadows = this._tileset.shadows;
    this._modelInstanceCollection.lightColor = this._tileset.lightColor;
    this._modelInstanceCollection.imageBasedLighting = this._tileset.imageBasedLighting;
    this._modelInstanceCollection.backFaceCulling = this._tileset.backFaceCulling;
    this._modelInstanceCollection.debugWireframe = this._tileset.debugWireframe;
    this._modelInstanceCollection.showCreditsOnScreen = this._tileset.showCreditsOnScreen;
    this._modelInstanceCollection.splitDirection = this._tileset.splitDirection;

    const model = this._modelInstanceCollection._model;

    if (defined(model)) {
      // Update for clipping planes
      const tilesetClippingPlanes = this._tileset.clippingPlanes;
      model.referenceMatrix = this._tileset.clippingPlanesOriginMatrix;
      if (defined(tilesetClippingPlanes) && this._tile.clippingPlanesDirty) {
        // Dereference the clipping planes from the model if they are irrelevant - saves on shading
        // Link/Dereference directly to avoid ownership checks.
        model._clippingPlanes =
          tilesetClippingPlanes.enabled && this._tile._isClipped
            ? tilesetClippingPlanes
            : undefined;
      }

      // If the model references a different ClippingPlaneCollection due to the tileset's collection being replaced with a
      // ClippingPlaneCollection that gives this tile the same clipping status, update the model to use the new ClippingPlaneCollection.
      if (
        defined(tilesetClippingPlanes) &&
        defined(model._clippingPlanes) &&
        model._clippingPlanes !== tilesetClippingPlanes
      ) {
        model._clippingPlanes = tilesetClippingPlanes;
      }
    }

    this._modelInstanceCollection.update(frameState);

    // If any commands were pushed, add derived commands
    const commandEnd = frameState.commandList.length;
    if (
      commandStart < commandEnd &&
      (frameState.passes.render || frameState.passes.pick)
    ) {
      this._batchTable.addDerivedCommands(frameState, commandStart, false);
    }
  };

  Instanced3DModel3DTileContent.prototype.isDestroyed = function () {
    return false;
  };

  Instanced3DModel3DTileContent.prototype.destroy = function () {
    this._modelInstanceCollection =
      this._modelInstanceCollection && this._modelInstanceCollection.destroy();
    this._batchTable = this._batchTable && this._batchTable.destroy();

    return destroyObject(this);
  };

  /**
   * The refinement approach for a tile.
   * <p>
   * See the {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification#refinement|Refinement}
   * in the 3D Tiles spec.
   * </p>
   *
   * @enum {Number}
   *
   * @private
   */
  const Cesium3DTileRefine = {
    /**
     * Render this tile and, if it doesn't meet the screen space error, also refine to its children.
     *
     * @type {Number}
     * @constant
     */
    ADD: 0,

    /**
     * Render this tile or, if it doesn't meet the screen space error, refine to its descendants instead.
     *
     * @type {Number}
     * @constant
     */
    REPLACE: 1,
  };
  var Cesium3DTileRefine$1 = Object.freeze(Cesium3DTileRefine);

  /**
   * An enum describing the built-in vertex attribute semantics.
   *
   * @enum {String}
   *
   * @private
   */
  const VertexAttributeSemantic = {
    /**
     * Per-vertex position.
     *
     * @type {String}
     * @constant
     */
    POSITION: "POSITION",

    /**
     * Per-vertex normal.
     *
     * @type {String}
     * @constant
     */
    NORMAL: "NORMAL",

    /**
     * Per-vertex tangent.
     *
     * @type {String}
     * @constant
     */
    TANGENT: "TANGENT",

    /**
     * Per-vertex texture coordinates.
     *
     * @type {String}
     * @constant
     */
    TEXCOORD: "TEXCOORD",

    /**
     * Per-vertex color.
     *
     * @type {String}
     * @constant
     */
    COLOR: "COLOR",

    /**
     * Per-vertex joint IDs for skinning.
     *
     * @type {String}
     * @constant
     */
    JOINTS: "JOINTS",

    /**
     * Per-vertex joint weights for skinning.
     *
     * @type {String}
     * @constant
     */
    WEIGHTS: "WEIGHTS",

    /**
     * Per-vertex feature ID.
     *
     * @type {String}
     * @constant
     */
    FEATURE_ID: "_FEATURE_ID",
  };

  function semanticToVariableName(semantic) {
    switch (semantic) {
      case VertexAttributeSemantic.POSITION:
        return "positionMC";
      case VertexAttributeSemantic.NORMAL:
        return "normalMC";
      case VertexAttributeSemantic.TANGENT:
        return "tangentMC";
      case VertexAttributeSemantic.TEXCOORD:
        return "texCoord";
      case VertexAttributeSemantic.COLOR:
        return "color";
      case VertexAttributeSemantic.JOINTS:
        return "joints";
      case VertexAttributeSemantic.WEIGHTS:
        return "weights";
      case VertexAttributeSemantic.FEATURE_ID:
        return "featureId";
      //>>includeStart('debug', pragmas.debug);
      default:
        throw new DeveloperError("semantic is not a valid value.");
      //>>includeEnd('debug');
    }
  }

  /**
   * Returns whether the vertex attribute semantic can have a set index.
   *
   * @param {VertexAttributeSemantic} semantic The semantic.
   *
   * @returns {Boolean} Whether the semantic can have a set index.
   *
   * @private
   */
  VertexAttributeSemantic.hasSetIndex = function (semantic) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("semantic", semantic);
    //>>includeEnd('debug');

    switch (semantic) {
      case VertexAttributeSemantic.POSITION:
      case VertexAttributeSemantic.NORMAL:
      case VertexAttributeSemantic.TANGENT:
        return false;
      case VertexAttributeSemantic.TEXCOORD:
      case VertexAttributeSemantic.COLOR:
      case VertexAttributeSemantic.JOINTS:
      case VertexAttributeSemantic.WEIGHTS:
      case VertexAttributeSemantic.FEATURE_ID:
        return true;
      //>>includeStart('debug', pragmas.debug);
      default:
        throw new DeveloperError("semantic is not a valid value.");
      //>>includeEnd('debug');
    }
  };

  /**
   * Gets the vertex attribute semantic matching the glTF semantic.
   *
   * @param {String} gltfSemantic The glTF semantic.
   *
   * @returns {VertexAttributeSemantic|undefined} The vertex attribute semantic, or undefined if there is no match.
   *
   * @private
   */
  VertexAttributeSemantic.fromGltfSemantic = function (gltfSemantic) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("gltfSemantic", gltfSemantic);
    //>>includeEnd('debug');

    let semantic = gltfSemantic;

    // Strip the set index from the semantic
    const setIndexRegex = /^(\w+)_\d+$/;
    const setIndexMatch = setIndexRegex.exec(gltfSemantic);
    if (setIndexMatch !== null) {
      semantic = setIndexMatch[1];
    }

    switch (semantic) {
      case "POSITION":
        return VertexAttributeSemantic.POSITION;
      case "NORMAL":
        return VertexAttributeSemantic.NORMAL;
      case "TANGENT":
        return VertexAttributeSemantic.TANGENT;
      case "TEXCOORD":
        return VertexAttributeSemantic.TEXCOORD;
      case "COLOR":
        return VertexAttributeSemantic.COLOR;
      case "JOINTS":
        return VertexAttributeSemantic.JOINTS;
      case "WEIGHTS":
        return VertexAttributeSemantic.WEIGHTS;
      case "_FEATURE_ID":
        return VertexAttributeSemantic.FEATURE_ID;
    }

    return undefined;
  };

  /**
   * Gets the vertex attribute semantic matching the pnts semantic.
   *
   * @param {String} pntsSemantic The pnts semantic.
   *
   * @returns {VertexAttributeSemantic|undefined} The vertex attribute semantic, or undefined if there is no match.
   *
   * @private
   */
  VertexAttributeSemantic.fromPntsSemantic = function (pntsSemantic) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("pntsSemantic", pntsSemantic);
    //>>includeEnd('debug');

    switch (pntsSemantic) {
      case "POSITION":
      case "POSITION_QUANTIZED":
        return VertexAttributeSemantic.POSITION;
      case "RGBA":
      case "RGB":
      case "RGB565":
        return VertexAttributeSemantic.COLOR;
      case "NORMAL":
      case "NORMAL_OCT16P":
        return VertexAttributeSemantic.NORMAL;
      case "BATCH_ID":
        return VertexAttributeSemantic.FEATURE_ID;
      //>>includeStart('debug', pragmas.debug);
      default:
        throw new DeveloperError("pntsSemantic is not a valid value.");
      //>>includeEnd('debug');
    }
  };

  /**
   * Gets the GLSL type (such as <code>vec3</code> or <code>int</code>) for the
   * given vertex attribute.
   *
   * @param {VertexAttributeSemantic} semantic The semantic.
   *
   * @returns {String} The shader type.
   *
   * @private
   */
  VertexAttributeSemantic.getGlslType = function (semantic) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("semantic", semantic);
    //>>includeEnd('debug');

    switch (semantic) {
      case VertexAttributeSemantic.POSITION:
      case VertexAttributeSemantic.NORMAL:
      case VertexAttributeSemantic.TANGENT:
        return "vec3";
      case VertexAttributeSemantic.TEXCOORD:
        return "vec2";
      case VertexAttributeSemantic.COLOR:
        return "vec4";
      case VertexAttributeSemantic.JOINTS:
        return "ivec4";
      case VertexAttributeSemantic.WEIGHTS:
        return "vec4";
      case VertexAttributeSemantic.FEATURE_ID:
        return "int";
      //>>includeStart('debug', pragmas.debug);
      default:
        throw new DeveloperError("semantic is not a valid value.");
      //>>includeEnd('debug');
    }
  };

  /**
   * Gets the variable name for the given semantic and set index.
   *
   * @param {VertexAttributeSemantic} semantic The semantic.
   * @param {Number} [setIndex] The set index.
   *
   * @returns {String} The variable name.
   *
   * @private
   */
  VertexAttributeSemantic.getVariableName = function (semantic, setIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("semantic", semantic);
    //>>includeEnd('debug');

    let variableName = semanticToVariableName(semantic);
    if (defined(setIndex)) {
      variableName += `_${setIndex}`;
    }
    return variableName;
  };

  var VertexAttributeSemantic$1 = Object.freeze(VertexAttributeSemantic);

  /**
   * Handles parsing of a Point Cloud
   *
   * @namespace PntsParser
   * @private
   */
  const PntsParser = {};

  const sizeOfUint32$1 = Uint32Array.BYTES_PER_ELEMENT;

  /**
   * Parses the contents of a {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/TileFormats/PointCloud|Point Cloud}.
   *
   * @private
   *
   * @param {*} arrayBuffer The array buffer containing the pnts
   * @param {*} [byteOffset=0] The byte offset of the beginning of the pnts in the array buffer
   * @returns {Object} An object containing a parsed representation of the point cloud
   */
  PntsParser.parse = function (arrayBuffer, byteOffset) {
    byteOffset = defaultValue(byteOffset, 0);
    //>>includeStart('debug', pragmas.debug);
    Check.defined("arrayBuffer", arrayBuffer);
    //>>includeEnd('debug');

    const uint8Array = new Uint8Array(arrayBuffer);
    const view = new DataView(arrayBuffer);
    byteOffset += sizeOfUint32$1; // Skip magic

    const version = view.getUint32(byteOffset, true);
    if (version !== 1) {
      throw new RuntimeError(
        `Only Point Cloud tile version 1 is supported.  Version ${version} is not.`
      );
    }
    byteOffset += sizeOfUint32$1;

    // Skip byteLength
    byteOffset += sizeOfUint32$1;

    const featureTableJsonByteLength = view.getUint32(byteOffset, true);
    if (featureTableJsonByteLength === 0) {
      throw new RuntimeError(
        "Feature table must have a byte length greater than zero"
      );
    }
    byteOffset += sizeOfUint32$1;

    const featureTableBinaryByteLength = view.getUint32(byteOffset, true);
    byteOffset += sizeOfUint32$1;

    const batchTableJsonByteLength = view.getUint32(byteOffset, true);
    byteOffset += sizeOfUint32$1;
    const batchTableBinaryByteLength = view.getUint32(byteOffset, true);
    byteOffset += sizeOfUint32$1;

    const featureTableJson = getJsonFromTypedArray(
      uint8Array,
      byteOffset,
      featureTableJsonByteLength
    );
    byteOffset += featureTableJsonByteLength;

    const featureTableBinary = new Uint8Array(
      arrayBuffer,
      byteOffset,
      featureTableBinaryByteLength
    );
    byteOffset += featureTableBinaryByteLength;

    // Get the batch table JSON and binary
    let batchTableJson;
    let batchTableBinary;
    if (batchTableJsonByteLength > 0) {
      // Has a batch table JSON
      batchTableJson = getJsonFromTypedArray(
        uint8Array,
        byteOffset,
        batchTableJsonByteLength
      );
      byteOffset += batchTableJsonByteLength;

      if (batchTableBinaryByteLength > 0) {
        // Has a batch table binary
        batchTableBinary = new Uint8Array(
          arrayBuffer,
          byteOffset,
          batchTableBinaryByteLength
        );
        byteOffset += batchTableBinaryByteLength;
      }
    }

    const featureTable = new Cesium3DTileFeatureTable(
      featureTableJson,
      featureTableBinary
    );

    const pointsLength = featureTable.getGlobalProperty("POINTS_LENGTH");
    featureTable.featuresLength = pointsLength;

    if (!defined(pointsLength)) {
      throw new RuntimeError(
        "Feature table global property: POINTS_LENGTH must be defined"
      );
    }

    let rtcCenter = featureTable.getGlobalProperty(
      "RTC_CENTER",
      ComponentDatatype$1.FLOAT,
      3
    );
    if (defined(rtcCenter)) {
      rtcCenter = Cartesian3.unpack(rtcCenter);
    }

    // Start with the draco compressed properties and add in uncompressed
    // properties.
    const parsedContent = parseDracoProperties(featureTable, batchTableJson);
    parsedContent.rtcCenter = rtcCenter;
    parsedContent.pointsLength = pointsLength;

    if (!parsedContent.hasPositions) {
      const positions = parsePositions(featureTable);
      parsedContent.positions = positions;
      parsedContent.hasPositions =
        parsedContent.hasPositions || defined(positions);
    }

    if (!parsedContent.hasPositions) {
      throw new RuntimeError(
        "Either POSITION or POSITION_QUANTIZED must be defined."
      );
    }

    if (!parsedContent.hasNormals) {
      const normals = parseNormals(featureTable);
      parsedContent.normals = normals;
      parsedContent.hasNormals = parsedContent.hasNormals || defined(normals);
    }

    if (!parsedContent.hasColors) {
      const colors = parseColors(featureTable);
      parsedContent.colors = colors;
      parsedContent.hasColors = parsedContent.hasColors || defined(colors);
      parsedContent.hasConstantColor = defined(parsedContent.constantColor);
      parsedContent.isTranslucent = defined(colors) && colors.isTranslucent;
    }

    if (!parsedContent.hasBatchIds) {
      const batchIds = parseBatchIds(featureTable);
      parsedContent.batchIds = batchIds;
      parsedContent.hasBatchIds = parsedContent.hasBatchIds || defined(batchIds);
    }

    if (parsedContent.hasBatchIds) {
      const batchLength = featureTable.getGlobalProperty("BATCH_LENGTH");
      if (!defined(batchLength)) {
        throw new RuntimeError(
          "Global property: BATCH_LENGTH must be defined when BATCH_ID is defined."
        );
      }
      parsedContent.batchLength = batchLength;
    }

    if (defined(batchTableBinary)) {
      // Copy the batchTableBinary section and let the underlying ArrayBuffer be freed
      batchTableBinary = new Uint8Array(batchTableBinary);
      parsedContent.batchTableJson = batchTableJson;
      parsedContent.batchTableBinary = batchTableBinary;
    }

    return parsedContent;
  };

  function parseDracoProperties(featureTable, batchTableJson) {
    const featureTableJson = featureTable.json;
    let dracoBuffer;
    let dracoFeatureTableProperties;
    let dracoBatchTableProperties;

    const featureTableDraco = defined(featureTableJson.extensions)
      ? featureTableJson.extensions["3DTILES_draco_point_compression"]
      : undefined;
    const batchTableDraco =
      defined(batchTableJson) && defined(batchTableJson.extensions)
        ? batchTableJson.extensions["3DTILES_draco_point_compression"]
        : undefined;

    if (defined(batchTableDraco)) {
      dracoBatchTableProperties = batchTableDraco.properties;
    }

    let hasPositions;
    let hasColors;
    let hasNormals;
    let hasBatchIds;
    let isTranslucent;
    if (defined(featureTableDraco)) {
      dracoFeatureTableProperties = featureTableDraco.properties;
      const dracoByteOffset = featureTableDraco.byteOffset;
      const dracoByteLength = featureTableDraco.byteLength;
      if (
        !defined(dracoFeatureTableProperties) ||
        !defined(dracoByteOffset) ||
        !defined(dracoByteLength)
      ) {
        throw new RuntimeError(
          "Draco properties, byteOffset, and byteLength must be defined"
        );
      }
      dracoBuffer = featureTable.buffer.slice(
        dracoByteOffset,
        dracoByteOffset + dracoByteLength
      );
      hasPositions = defined(dracoFeatureTableProperties.POSITION);
      hasColors =
        defined(dracoFeatureTableProperties.RGB) ||
        defined(dracoFeatureTableProperties.RGBA);
      hasNormals = defined(dracoFeatureTableProperties.NORMAL);
      hasBatchIds = defined(dracoFeatureTableProperties.BATCH_ID);
      isTranslucent = defined(dracoFeatureTableProperties.RGBA);
    }

    let draco;
    if (defined(dracoBuffer)) {
      draco = {
        buffer: dracoBuffer,
        featureTableProperties: dracoFeatureTableProperties,
        batchTableProperties: dracoBatchTableProperties,
        properties: combine$2(
          dracoFeatureTableProperties,
          dracoBatchTableProperties
        ),
        dequantizeInShader: true,
      };
    }

    return {
      draco: draco,
      hasPositions: hasPositions,
      hasColors: hasColors,
      isTranslucent: isTranslucent,
      hasNormals: hasNormals,
      hasBatchIds: hasBatchIds,
    };
  }

  function parsePositions(featureTable) {
    const featureTableJson = featureTable.json;

    let positions;
    if (defined(featureTableJson.POSITION)) {
      positions = featureTable.getPropertyArray(
        "POSITION",
        ComponentDatatype$1.FLOAT,
        3
      );

      return {
        name: VertexAttributeSemantic$1.POSITION,
        semantic: VertexAttributeSemantic$1.POSITION,
        typedArray: positions,
        isQuantized: false,
        componentDatatype: ComponentDatatype$1.FLOAT,
        type: AttributeType$1.VEC3,
      };
    } else if (defined(featureTableJson.POSITION_QUANTIZED)) {
      positions = featureTable.getPropertyArray(
        "POSITION_QUANTIZED",
        ComponentDatatype$1.UNSIGNED_SHORT,
        3
      );

      const quantizedVolumeScale = featureTable.getGlobalProperty(
        "QUANTIZED_VOLUME_SCALE",
        ComponentDatatype$1.FLOAT,
        3
      );
      if (!defined(quantizedVolumeScale)) {
        throw new RuntimeError(
          "Global property: QUANTIZED_VOLUME_SCALE must be defined for quantized positions."
        );
      }
      const quantizedRange = (1 << 16) - 1;

      const quantizedVolumeOffset = featureTable.getGlobalProperty(
        "QUANTIZED_VOLUME_OFFSET",
        ComponentDatatype$1.FLOAT,
        3
      );
      if (!defined(quantizedVolumeOffset)) {
        throw new RuntimeError(
          "Global property: QUANTIZED_VOLUME_OFFSET must be defined for quantized positions."
        );
      }

      return {
        name: VertexAttributeSemantic$1.POSITION,
        semantic: VertexAttributeSemantic$1.POSITION,
        typedArray: positions,
        isQuantized: true,
        componentDatatype: ComponentDatatype$1.FLOAT,
        type: AttributeType$1.VEC3,
        quantizedRange: quantizedRange,
        quantizedVolumeOffset: Cartesian3.unpack(quantizedVolumeOffset),
        quantizedVolumeScale: Cartesian3.unpack(quantizedVolumeScale),
        quantizedComponentDatatype: ComponentDatatype$1.UNSIGNED_SHORT,
        quantizedType: AttributeType$1.VEC3,
      };
    }
  }

  function parseColors(featureTable) {
    const featureTableJson = featureTable.json;

    let colors;
    if (defined(featureTableJson.RGBA)) {
      colors = featureTable.getPropertyArray(
        "RGBA",
        ComponentDatatype$1.UNSIGNED_BYTE,
        4
      );
      return {
        name: VertexAttributeSemantic$1.COLOR,
        semantic: VertexAttributeSemantic$1.COLOR,
        setIndex: 0,
        typedArray: colors,
        componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
        type: AttributeType$1.VEC4,
        normalized: true,
        isRGB565: false,
        isTranslucent: true,
      };
    } else if (defined(featureTableJson.RGB)) {
      colors = featureTable.getPropertyArray(
        "RGB",
        ComponentDatatype$1.UNSIGNED_BYTE,
        3
      );
      return {
        name: "COLOR",
        semantic: VertexAttributeSemantic$1.COLOR,
        setIndex: 0,
        typedArray: colors,
        componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
        type: AttributeType$1.VEC3,
        normalized: true,
        isRGB565: false,
        isTranslucent: false,
      };
    } else if (defined(featureTableJson.RGB565)) {
      colors = featureTable.getPropertyArray(
        "RGB565",
        ComponentDatatype$1.UNSIGNED_SHORT,
        1
      );
      return {
        name: "COLOR",
        semantic: VertexAttributeSemantic$1.COLOR,
        setIndex: 0,
        typedArray: colors,
        // These settings are for the ModelExperimental implementation
        // which decodes on the CPU and uploads a VEC3 of float colors.
        // PointCloud does the decoding on the GPU so uploads a
        // UNSIGNED_SHORT instead.
        componentDatatype: ComponentDatatype$1.FLOAT,
        type: AttributeType$1.VEC3,
        normalized: false,
        isRGB565: true,
        isTranslucent: false,
      };
    } else if (defined(featureTableJson.CONSTANT_RGBA)) {
      const constantRGBA = featureTable.getGlobalProperty(
        "CONSTANT_RGBA",
        ComponentDatatype$1.UNSIGNED_BYTE,
        4
      );

      const alpha = constantRGBA[3];
      const constantColor = Color.fromBytes(
        constantRGBA[0],
        constantRGBA[1],
        constantRGBA[2],
        alpha
      );

      const isTranslucent = alpha < 255;
      return {
        name: VertexAttributeSemantic$1.COLOR,
        semantic: VertexAttributeSemantic$1.COLOR,
        setIndex: 0,
        constantColor: constantColor,
        componentDatatype: ComponentDatatype$1.FLOAT,
        type: AttributeType$1.VEC4,
        isQuantized: false,
        isTranslucent: isTranslucent,
      };
    }

    return undefined;
  }

  function parseNormals(featureTable) {
    const featureTableJson = featureTable.json;
    let normals;
    if (defined(featureTableJson.NORMAL)) {
      normals = featureTable.getPropertyArray(
        "NORMAL",
        ComponentDatatype$1.FLOAT,
        3
      );
      return {
        name: VertexAttributeSemantic$1.NORMAL,
        semantic: VertexAttributeSemantic$1.NORMAL,
        typedArray: normals,
        octEncoded: false,
        octEncodedZXY: false,
        componentDatatype: ComponentDatatype$1.FLOAT,
        type: AttributeType$1.VEC3,
      };
    } else if (defined(featureTableJson.NORMAL_OCT16P)) {
      normals = featureTable.getPropertyArray(
        "NORMAL_OCT16P",
        ComponentDatatype$1.UNSIGNED_BYTE,
        2
      );
      const quantizationBits = 8;
      return {
        name: VertexAttributeSemantic$1.NORMAL,
        semantic: VertexAttributeSemantic$1.NORMAL,
        typedArray: normals,
        octEncoded: true,
        octEncodedZXY: false,
        quantizedRange: (1 << quantizationBits) - 1,
        quantizedType: AttributeType$1.VEC2,
        quantizedComponentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
        componentDatatype: ComponentDatatype$1.FLOAT,
        type: AttributeType$1.VEC3,
      };
    }

    return undefined;
  }

  function parseBatchIds(featureTable) {
    const featureTableJson = featureTable.json;
    if (defined(featureTableJson.BATCH_ID)) {
      const batchIds = featureTable.getPropertyArray(
        "BATCH_ID",
        ComponentDatatype$1.UNSIGNED_SHORT,
        1
      );
      return {
        name: VertexAttributeSemantic$1.FEATURE_ID,
        semantic: VertexAttributeSemantic$1.FEATURE_ID,
        setIndex: 0,
        typedArray: batchIds,
        componentDatatype: ComponentDatatype$1.fromTypedArray(batchIds),
        type: AttributeType$1.SCALAR,
      };
    }

    return undefined;
  }

  const DecodingState = {
    NEEDS_DECODE: 0,
    DECODING: 1,
    READY: 2,
    FAILED: 3,
  };

  /**
   * Represents the contents of a
   * {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/TileFormats/PointCloud|Point Cloud}
   * tile. Used internally by {@link PointCloud3DTileContent} and {@link TimeDynamicPointCloud}.
   *
   * @alias PointCloud
   * @constructor
   *
   * @see PointCloud3DTileContent
   * @see TimeDynamicPointCloud
   *
   * @private
   */
  function PointCloud(options) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options", options);
    Check.typeOf.object("options.arrayBuffer", options.arrayBuffer);
    //>>includeEnd('debug');

    // Hold onto the payload until the render resources are created
    this._parsedContent = undefined;

    this._drawCommand = undefined;
    this._isTranslucent = false;
    this._styleTranslucent = false;
    this._constantColor = Color.clone(Color.DARKGRAY);
    this._highlightColor = Color.clone(Color.WHITE);
    this._pointSize = 1.0;

    this._rtcCenter = undefined;
    this._quantizedVolumeScale = undefined;
    this._quantizedVolumeOffset = undefined;

    // These values are used to regenerate the shader when the style changes
    this._styleableShaderAttributes = undefined;
    this._isQuantized = false;
    this._isOctEncoded16P = false;
    this._isRGB565 = false;
    this._hasColors = false;
    this._hasNormals = false;
    this._hasBatchIds = false;

    // Draco
    this._decodingState = DecodingState.READY;
    this._dequantizeInShader = true;
    this._isQuantizedDraco = false;
    this._isOctEncodedDraco = false;
    this._quantizedRange = 0.0;
    this._octEncodedRange = 0.0;

    // Use per-point normals to hide back-facing points.
    this.backFaceCulling = false;
    this._backFaceCulling = false;

    // Whether to enable normal shading
    this.normalShading = true;
    this._normalShading = true;

    this._opaqueRenderState = undefined;
    this._translucentRenderState = undefined;

    this._mode = undefined;

    this._ready = false;
    this._pointsLength = 0;
    this._geometryByteLength = 0;

    this._vertexShaderLoaded = options.vertexShaderLoaded;
    this._fragmentShaderLoaded = options.fragmentShaderLoaded;
    this._uniformMapLoaded = options.uniformMapLoaded;
    this._batchTableLoaded = options.batchTableLoaded;
    this._pickIdLoaded = options.pickIdLoaded;
    this._opaquePass = defaultValue(options.opaquePass, Pass$1.OPAQUE);
    this._cull = defaultValue(options.cull, true);

    this.style = undefined;
    this._style = undefined;
    this.styleDirty = false;

    this.modelMatrix = Matrix4.clone(Matrix4.IDENTITY);
    this._modelMatrix = Matrix4.clone(Matrix4.IDENTITY);

    this.time = 0.0; // For styling
    this.shadows = ShadowMode$1.ENABLED;
    this._boundingSphere = undefined;

    this.clippingPlanes = undefined;
    this.isClipped = false;
    this.clippingPlanesDirty = false;
    // If defined, use this matrix to position the clipping planes instead of the modelMatrix.
    // This is so that when point clouds are part of a tileset they all get clipped relative
    // to the root tile.
    this.clippingPlanesOriginMatrix = undefined;

    this.attenuation = false;
    this._attenuation = false;

    // Options for geometric error based attenuation
    this.geometricError = 0.0;
    this.geometricErrorScale = 1.0;
    this.maximumAttenuation = this._pointSize;

    /**
     * The {@link SplitDirection} to apply to this point cloud.
     *
     * @type {SplitDirection}
     * @default {@link SplitDirection.NONE}
     */
    this.splitDirection = defaultValue(
      options.splitDirection,
      SplitDirection$1.NONE
    );
    this._splittingEnabled = false;

    this._resolveReadyPromise = undefined;
    this._rejectReadyPromise = undefined;
    this._readyPromise = initialize$f(this, options);
  }

  Object.defineProperties(PointCloud.prototype, {
    pointsLength: {
      get: function () {
        return this._pointsLength;
      },
    },

    geometryByteLength: {
      get: function () {
        return this._geometryByteLength;
      },
    },

    ready: {
      get: function () {
        return this._ready;
      },
    },

    readyPromise: {
      get: function () {
        return this._readyPromise;
      },
    },

    color: {
      get: function () {
        return Color.clone(this._highlightColor);
      },
      set: function (value) {
        this._highlightColor = Color.clone(value, this._highlightColor);
      },
    },

    boundingSphere: {
      get: function () {
        if (defined(this._drawCommand)) {
          return this._drawCommand.boundingVolume;
        }
        return undefined;
      },
      set: function (value) {
        this._boundingSphere = BoundingSphere.clone(value, this._boundingSphere);
      },
    },
  });

  function initialize$f(pointCloud, options) {
    const parsedContent = PntsParser.parse(
      options.arrayBuffer,
      options.byteOffset
    );
    pointCloud._parsedContent = parsedContent;
    pointCloud._rtcCenter = parsedContent.rtcCenter;
    pointCloud._hasNormals = parsedContent.hasNormals;
    pointCloud._hasColors = parsedContent.hasColors;
    pointCloud._hasBatchIds = parsedContent.hasBatchIds;
    pointCloud._isTranslucent = parsedContent.isTranslucent;

    // If points are not batched and there are per-point properties, use the
    // properties as metadata for styling purposes.
    if (!parsedContent.hasBatchIds && defined(parsedContent.batchTableBinary)) {
      parsedContent.styleableProperties = Cesium3DTileBatchTable.getBinaryProperties(
        parsedContent.pointsLength,
        parsedContent.batchTableJson,
        parsedContent.batchTableBinary
      );
    }

    if (defined(parsedContent.draco)) {
      const draco = parsedContent.draco;
      pointCloud._decodingState = DecodingState.NEEDS_DECODE;
      draco.dequantizeInShader = pointCloud._dequantizeInShader;
    }

    const positions = parsedContent.positions;
    if (defined(positions)) {
      pointCloud._isQuantized = positions.isQuantized;
      pointCloud._quantizedVolumeScale = positions.quantizedVolumeScale;
      pointCloud._quantizedVolumeOffset = positions.quantizedVolumeOffset;
      pointCloud._quantizedRange = positions.quantizedRange;
    }

    const normals = parsedContent.normals;
    if (defined(normals)) {
      pointCloud._isOctEncoded16P = normals.octEncoded;
    }

    const colors = parsedContent.colors;
    if (defined(colors)) {
      if (defined(colors.constantColor)) {
        pointCloud._constantColor = Color.clone(
          colors.constantColor,
          pointCloud._constantColor
        );

        // Constant colors are handled as a uniform rather than a vertex
        // attribute.
        pointCloud._hasColors = false;
      }
      pointCloud._isRGB565 = colors.isRGB565;
    }

    // PntsParser parses BATCH_ID as _FEATURE_ID_0 for EXT_mesh_features.
    // These properties aren't used but rename them to BATCH_ID to avoid
    // confusion when debugging.
    const batchIds = parsedContent.batchIds;
    if (defined(parsedContent.batchIds)) {
      batchIds.name = "BATCH_ID";
      batchIds.semantic = "BATCH_ID";
      batchIds.setIndex = undefined;
    }

    if (parsedContent.hasBatchIds) {
      pointCloud._batchTableLoaded(
        parsedContent.batchLength,
        parsedContent.batchTableJson,
        parsedContent.batchTableBinary
      );
    }

    pointCloud._pointsLength = parsedContent.pointsLength;

    return new Promise(function (resolve, reject) {
      pointCloud._resolveReadyPromise = function () {
        pointCloud._ready = true;
        resolve(pointCloud);
      };
      pointCloud._rejectReadyPromise = reject;
    });
  }

  const scratchMin$2 = new Cartesian3();
  const scratchMax$2 = new Cartesian3();
  const scratchPosition$8 = new Cartesian3();

  // Use MersenneTwister directly to avoid interfering with CesiumMath.nextRandomNumber()
  // See https://github.com/CesiumGS/cesium/issues/9730
  let randomNumberGenerator$1;
  let randomValues$1;

  function getRandomValues$2(samplesLength) {
    // Use same random values across all runs
    if (!defined(randomValues$1)) {
      // Use MersenneTwister directly to avoid interfering with CesiumMath.nextRandomNumber()
      // See https://github.com/CesiumGS/cesium/issues/9730
      randomNumberGenerator$1 = new mersenneTwister(0);
      randomValues$1 = new Array(samplesLength);
      for (let i = 0; i < samplesLength; ++i) {
        randomValues$1[i] = randomNumberGenerator$1.random();
      }
    }
    return randomValues$1;
  }

  function computeApproximateBoundingSphereFromPositions(positions) {
    const maximumSamplesLength = 20;
    const pointsLength = positions.length / 3;
    const samplesLength = Math.min(pointsLength, maximumSamplesLength);
    const randomValues = getRandomValues$2(maximumSamplesLength);
    const maxValue = Number.MAX_VALUE;
    const minValue = -Number.MAX_VALUE;
    const min = Cartesian3.fromElements(maxValue, maxValue, maxValue, scratchMin$2);
    const max = Cartesian3.fromElements(minValue, minValue, minValue, scratchMax$2);
    for (let i = 0; i < samplesLength; ++i) {
      const index = Math.floor(randomValues[i] * pointsLength);
      const position = Cartesian3.unpack(positions, index * 3, scratchPosition$8);
      Cartesian3.minimumByComponent(min, position, min);
      Cartesian3.maximumByComponent(max, position, max);
    }

    const boundingSphere = BoundingSphere.fromCornerPoints(min, max);
    boundingSphere.radius += CesiumMath.EPSILON2; // To avoid radius of zero
    return boundingSphere;
  }

  function prepareVertexAttribute(typedArray, name) {
    // WebGL does not support UNSIGNED_INT, INT, or DOUBLE vertex attributes. Convert these to FLOAT.
    const componentDatatype = ComponentDatatype$1.fromTypedArray(typedArray);
    if (
      componentDatatype === ComponentDatatype$1.INT ||
      componentDatatype === ComponentDatatype$1.UNSIGNED_INT ||
      componentDatatype === ComponentDatatype$1.DOUBLE
    ) {
      oneTimeWarning(
        "Cast pnts property to floats",
        `Point cloud property "${name}" will be casted to a float array because INT, UNSIGNED_INT, and DOUBLE are not valid WebGL vertex attribute types. Some precision may be lost.`
      );
      return new Float32Array(typedArray);
    }
    return typedArray;
  }

  const scratchPointSizeAndTimeAndGeometricErrorAndDepthMultiplier = new Cartesian4();
  const scratchQuantizedVolumeScaleAndOctEncodedRange = new Cartesian4();
  const scratchColor$j = new Color();

  const positionLocation = 0;
  const colorLocation = 1;
  const normalLocation = 2;
  const batchIdLocation = 3;
  const numberOfAttributes = 4;

  const scratchClippingPlanesMatrix$2 = new Matrix4();
  const scratchInverseTransposeClippingPlanesMatrix$1 = new Matrix4();

  function createResources$3(pointCloud, frameState) {
    const context = frameState.context;
    const parsedContent = pointCloud._parsedContent;
    const pointsLength = pointCloud._pointsLength;
    const positions = parsedContent.positions;
    const colors = parsedContent.colors;
    const normals = parsedContent.normals;
    const batchIds = parsedContent.batchIds;
    const styleableProperties = parsedContent.styleableProperties;
    const hasStyleableProperties = defined(styleableProperties);
    const isQuantized = pointCloud._isQuantized;
    const isQuantizedDraco = pointCloud._isQuantizedDraco;
    const isOctEncoded16P = pointCloud._isOctEncoded16P;
    const isOctEncodedDraco = pointCloud._isOctEncodedDraco;
    const quantizedRange = pointCloud._quantizedRange;
    const octEncodedRange = pointCloud._octEncodedRange;
    const isRGB565 = pointCloud._isRGB565;
    const isTranslucent = pointCloud._isTranslucent;
    const hasColors = pointCloud._hasColors;
    const hasNormals = pointCloud._hasNormals;
    const hasBatchIds = pointCloud._hasBatchIds;

    let componentsPerAttribute;
    let componentDatatype;

    const styleableVertexAttributes = [];
    const styleableShaderAttributes = {};
    pointCloud._styleableShaderAttributes = styleableShaderAttributes;

    if (hasStyleableProperties) {
      let attributeLocation = numberOfAttributes;

      for (const name in styleableProperties) {
        if (styleableProperties.hasOwnProperty(name)) {
          const property = styleableProperties[name];
          const typedArray = prepareVertexAttribute(property.typedArray, name);
          componentsPerAttribute = property.componentCount;
          componentDatatype = ComponentDatatype$1.fromTypedArray(typedArray);

          const vertexBuffer = Buffer$1.createVertexBuffer({
            context: context,
            typedArray: typedArray,
            usage: BufferUsage$1.STATIC_DRAW,
          });

          pointCloud._geometryByteLength += vertexBuffer.sizeInBytes;

          const vertexAttribute = {
            index: attributeLocation,
            vertexBuffer: vertexBuffer,
            componentsPerAttribute: componentsPerAttribute,
            componentDatatype: componentDatatype,
            normalize: false,
            offsetInBytes: 0,
            strideInBytes: 0,
          };

          styleableVertexAttributes.push(vertexAttribute);
          styleableShaderAttributes[name] = {
            location: attributeLocation,
            componentCount: componentsPerAttribute,
          };
          ++attributeLocation;
        }
      }
    }

    const positionsVertexBuffer = Buffer$1.createVertexBuffer({
      context: context,
      typedArray: positions.typedArray,
      usage: BufferUsage$1.STATIC_DRAW,
    });
    pointCloud._geometryByteLength += positionsVertexBuffer.sizeInBytes;

    let colorsVertexBuffer;
    if (hasColors) {
      colorsVertexBuffer = Buffer$1.createVertexBuffer({
        context: context,
        typedArray: colors.typedArray,
        usage: BufferUsage$1.STATIC_DRAW,
      });
      pointCloud._geometryByteLength += colorsVertexBuffer.sizeInBytes;
    }

    let normalsVertexBuffer;
    if (hasNormals) {
      normalsVertexBuffer = Buffer$1.createVertexBuffer({
        context: context,
        typedArray: normals.typedArray,
        usage: BufferUsage$1.STATIC_DRAW,
      });
      pointCloud._geometryByteLength += normalsVertexBuffer.sizeInBytes;
    }

    let batchIdsVertexBuffer;
    if (hasBatchIds) {
      batchIds.typedArray = prepareVertexAttribute(
        batchIds.typedArray,
        "batchIds"
      );
      batchIdsVertexBuffer = Buffer$1.createVertexBuffer({
        context: context,
        typedArray: batchIds.typedArray,
        usage: BufferUsage$1.STATIC_DRAW,
      });
      pointCloud._geometryByteLength += batchIdsVertexBuffer.sizeInBytes;
    }

    let attributes = [];

    if (isQuantized) {
      componentDatatype = ComponentDatatype$1.UNSIGNED_SHORT;
    } else if (isQuantizedDraco) {
      componentDatatype =
        quantizedRange <= 255
          ? ComponentDatatype$1.UNSIGNED_BYTE
          : ComponentDatatype$1.UNSIGNED_SHORT;
    } else {
      componentDatatype = ComponentDatatype$1.FLOAT;
    }

    attributes.push({
      index: positionLocation,
      vertexBuffer: positionsVertexBuffer,
      componentsPerAttribute: 3,
      componentDatatype: componentDatatype,
      normalize: false,
      offsetInBytes: 0,
      strideInBytes: 0,
    });

    if (pointCloud._cull) {
      if (isQuantized || isQuantizedDraco) {
        pointCloud._boundingSphere = BoundingSphere.fromCornerPoints(
          Cartesian3.ZERO,
          pointCloud._quantizedVolumeScale
        );
      } else {
        pointCloud._boundingSphere = computeApproximateBoundingSphereFromPositions(
          positions.typedArray
        );
      }
    }

    if (hasColors) {
      if (isRGB565) {
        attributes.push({
          index: colorLocation,
          vertexBuffer: colorsVertexBuffer,
          componentsPerAttribute: 1,
          componentDatatype: ComponentDatatype$1.UNSIGNED_SHORT,
          normalize: false,
          offsetInBytes: 0,
          strideInBytes: 0,
        });
      } else {
        const colorComponentsPerAttribute = isTranslucent ? 4 : 3;
        attributes.push({
          index: colorLocation,
          vertexBuffer: colorsVertexBuffer,
          componentsPerAttribute: colorComponentsPerAttribute,
          componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
          normalize: true,
          offsetInBytes: 0,
          strideInBytes: 0,
        });
      }
    }

    if (hasNormals) {
      if (isOctEncoded16P) {
        componentsPerAttribute = 2;
        componentDatatype = ComponentDatatype$1.UNSIGNED_BYTE;
      } else if (isOctEncodedDraco) {
        componentsPerAttribute = 2;
        componentDatatype =
          octEncodedRange <= 255
            ? ComponentDatatype$1.UNSIGNED_BYTE
            : ComponentDatatype$1.UNSIGNED_SHORT;
      } else {
        componentsPerAttribute = 3;
        componentDatatype = ComponentDatatype$1.FLOAT;
      }
      attributes.push({
        index: normalLocation,
        vertexBuffer: normalsVertexBuffer,
        componentsPerAttribute: componentsPerAttribute,
        componentDatatype: componentDatatype,
        normalize: false,
        offsetInBytes: 0,
        strideInBytes: 0,
      });
    }

    if (hasBatchIds) {
      attributes.push({
        index: batchIdLocation,
        vertexBuffer: batchIdsVertexBuffer,
        componentsPerAttribute: 1,
        componentDatatype: ComponentDatatype$1.fromTypedArray(batchIds.typedArray),
        normalize: false,
        offsetInBytes: 0,
        strideInBytes: 0,
      });
    }

    if (hasStyleableProperties) {
      attributes = attributes.concat(styleableVertexAttributes);
    }

    const vertexArray = new VertexArray({
      context: context,
      attributes: attributes,
    });

    const opaqueRenderState = {
      depthTest: {
        enabled: true,
      },
    };

    const translucentRenderState = {
      depthTest: {
        enabled: true,
      },
      depthMask: false,
      blending: BlendingState$1.ALPHA_BLEND,
    };

    if (pointCloud._opaquePass === Pass$1.CESIUM_3D_TILE) {
      opaqueRenderState.stencilTest = StencilConstants$1.setCesium3DTileBit();
      opaqueRenderState.stencilMask = StencilConstants$1.CESIUM_3D_TILE_MASK;
      translucentRenderState.stencilTest = StencilConstants$1.setCesium3DTileBit();
      translucentRenderState.stencilMask = StencilConstants$1.CESIUM_3D_TILE_MASK;
    }

    pointCloud._opaqueRenderState = RenderState.fromCache(opaqueRenderState);
    pointCloud._translucentRenderState = RenderState.fromCache(
      translucentRenderState
    );

    pointCloud._drawCommand = new DrawCommand({
      boundingVolume: new BoundingSphere(),
      cull: pointCloud._cull,
      modelMatrix: new Matrix4(),
      primitiveType: PrimitiveType$1.POINTS,
      vertexArray: vertexArray,
      count: pointsLength,
      shaderProgram: undefined, // Updated in createShaders
      uniformMap: undefined, // Updated in createShaders
      renderState: isTranslucent
        ? pointCloud._translucentRenderState
        : pointCloud._opaqueRenderState,
      pass: isTranslucent ? Pass$1.TRANSLUCENT : pointCloud._opaquePass,
      owner: pointCloud,
      castShadows: false,
      receiveShadows: false,
      pickId: pointCloud._pickIdLoaded(),
    });
  }

  function createUniformMap$4(pointCloud, frameState) {
    const context = frameState.context;
    const isQuantized = pointCloud._isQuantized;
    const isQuantizedDraco = pointCloud._isQuantizedDraco;
    const isOctEncodedDraco = pointCloud._isOctEncodedDraco;

    let uniformMap = {
      u_pointSizeAndTimeAndGeometricErrorAndDepthMultiplier: function () {
        const scratch = scratchPointSizeAndTimeAndGeometricErrorAndDepthMultiplier;
        scratch.x = pointCloud._attenuation
          ? pointCloud.maximumAttenuation
          : pointCloud._pointSize;
        scratch.x *= frameState.pixelRatio;

        scratch.y = pointCloud.time;

        if (pointCloud._attenuation) {
          const frustum = frameState.camera.frustum;
          let depthMultiplier;
          // Attenuation is maximumAttenuation in 2D/ortho
          if (
            frameState.mode === SceneMode$1.SCENE2D ||
            frustum instanceof OrthographicFrustum
          ) {
            depthMultiplier = Number.POSITIVE_INFINITY;
          } else {
            depthMultiplier =
              context.drawingBufferHeight /
              frameState.camera.frustum.sseDenominator;
          }

          scratch.z = pointCloud.geometricError * pointCloud.geometricErrorScale;
          scratch.w = depthMultiplier;
        }

        return scratch;
      },
      u_highlightColor: function () {
        return pointCloud._highlightColor;
      },
      u_constantColor: function () {
        return pointCloud._constantColor;
      },
      u_clippingPlanes: function () {
        const clippingPlanes = pointCloud.clippingPlanes;
        const isClipped = pointCloud.isClipped;
        return isClipped ? clippingPlanes.texture : context.defaultTexture;
      },
      u_clippingPlanesEdgeStyle: function () {
        const clippingPlanes = pointCloud.clippingPlanes;
        if (!defined(clippingPlanes)) {
          return Color.TRANSPARENT;
        }

        const style = Color.clone(clippingPlanes.edgeColor, scratchColor$j);
        style.alpha = clippingPlanes.edgeWidth;
        return style;
      },
      u_clippingPlanesMatrix: function () {
        const clippingPlanes = pointCloud.clippingPlanes;
        if (!defined(clippingPlanes)) {
          return Matrix4.IDENTITY;
        }

        const clippingPlanesOriginMatrix = defaultValue(
          pointCloud.clippingPlanesOriginMatrix,
          pointCloud._modelMatrix
        );
        Matrix4.multiply(
          context.uniformState.view3D,
          clippingPlanesOriginMatrix,
          scratchClippingPlanesMatrix$2
        );
        const transform = Matrix4.multiply(
          scratchClippingPlanesMatrix$2,
          clippingPlanes.modelMatrix,
          scratchClippingPlanesMatrix$2
        );

        return Matrix4.inverseTranspose(
          transform,
          scratchInverseTransposeClippingPlanesMatrix$1
        );
      },
    };

    Splitter.addUniforms(pointCloud, uniformMap);

    if (isQuantized || isQuantizedDraco || isOctEncodedDraco) {
      uniformMap = combine$2(uniformMap, {
        u_quantizedVolumeScaleAndOctEncodedRange: function () {
          const scratch = scratchQuantizedVolumeScaleAndOctEncodedRange;
          if (defined(pointCloud._quantizedVolumeScale)) {
            const scale = Cartesian3.clone(
              pointCloud._quantizedVolumeScale,
              scratch
            );
            Cartesian3.divideByScalar(scale, pointCloud._quantizedRange, scratch);
          }
          scratch.w = pointCloud._octEncodedRange;
          return scratch;
        },
      });
    }

    if (defined(pointCloud._uniformMapLoaded)) {
      uniformMap = pointCloud._uniformMapLoaded(uniformMap);
    }

    pointCloud._drawCommand.uniformMap = uniformMap;
  }

  function getStyleablePropertyIds(source, propertyIds) {
    // Get all the property IDs used by this style
    const regex = /czm_3dtiles_property_(\d+)/g;
    let matches = regex.exec(source);
    while (matches !== null) {
      const id = parseInt(matches[1]);
      if (propertyIds.indexOf(id) === -1) {
        propertyIds.push(id);
      }
      matches = regex.exec(source);
    }
  }

  function getBuiltinPropertyNames(source, propertyNames) {
    // Get all the builtin property names used by this style, ignoring the function signature
    source = source.slice(source.indexOf("\n"));
    const regex = /czm_3dtiles_builtin_property_(\w+)/g;
    let matches = regex.exec(source);
    while (matches !== null) {
      const name = matches[1];
      if (propertyNames.indexOf(name) === -1) {
        propertyNames.push(name);
      }
      matches = regex.exec(source);
    }
  }

  function getVertexAttribute(vertexArray, index) {
    const numberOfAttributes = vertexArray.numberOfAttributes;
    for (let i = 0; i < numberOfAttributes; ++i) {
      const attribute = vertexArray.getAttribute(i);
      if (attribute.index === index) {
        return attribute;
      }
    }
  }

  const builtinVariableSubstitutionMap = {
    POSITION: "czm_3dtiles_builtin_property_POSITION",
    POSITION_ABSOLUTE: "czm_3dtiles_builtin_property_POSITION_ABSOLUTE",
    COLOR: "czm_3dtiles_builtin_property_COLOR",
    NORMAL: "czm_3dtiles_builtin_property_NORMAL",
  };

  function createShaders$2(pointCloud, frameState, style) {
    let i;
    let name;
    let attribute;

    const context = frameState.context;
    const hasStyle = defined(style);
    const isQuantized = pointCloud._isQuantized;
    const isQuantizedDraco = pointCloud._isQuantizedDraco;
    const isOctEncoded16P = pointCloud._isOctEncoded16P;
    const isOctEncodedDraco = pointCloud._isOctEncodedDraco;
    const isRGB565 = pointCloud._isRGB565;
    const isTranslucent = pointCloud._isTranslucent;
    const hasColors = pointCloud._hasColors;
    const hasNormals = pointCloud._hasNormals;
    const hasBatchIds = pointCloud._hasBatchIds;
    const backFaceCulling = pointCloud._backFaceCulling;
    const normalShading = pointCloud._normalShading;
    const vertexArray = pointCloud._drawCommand.vertexArray;
    const clippingPlanes = pointCloud.clippingPlanes;
    const attenuation = pointCloud._attenuation;

    let colorStyleFunction;
    let showStyleFunction;
    let pointSizeStyleFunction;
    let styleTranslucent = isTranslucent;

    const variableSubstitutionMap = clone$1(builtinVariableSubstitutionMap);
    const propertyIdToAttributeMap = {};
    const styleableShaderAttributes = pointCloud._styleableShaderAttributes;
    for (name in styleableShaderAttributes) {
      if (styleableShaderAttributes.hasOwnProperty(name)) {
        attribute = styleableShaderAttributes[name];
        variableSubstitutionMap[
          name
        ] = `czm_3dtiles_property_${attribute.location}`;
        propertyIdToAttributeMap[attribute.location] = attribute;
      }
    }

    if (hasStyle) {
      const shaderState = {
        translucent: false,
      };
      const parameterList =
        "(" +
        "vec3 czm_3dtiles_builtin_property_POSITION, " +
        "vec3 czm_3dtiles_builtin_property_POSITION_ABSOLUTE, " +
        "vec4 czm_3dtiles_builtin_property_COLOR, " +
        "vec3 czm_3dtiles_builtin_property_NORMAL" +
        ")";
      colorStyleFunction = style.getColorShaderFunction(
        `getColorFromStyle${parameterList}`,
        variableSubstitutionMap,
        shaderState
      );
      showStyleFunction = style.getShowShaderFunction(
        `getShowFromStyle${parameterList}`,
        variableSubstitutionMap,
        shaderState
      );
      pointSizeStyleFunction = style.getPointSizeShaderFunction(
        `getPointSizeFromStyle${parameterList}`,
        variableSubstitutionMap,
        shaderState
      );
      if (defined(colorStyleFunction) && shaderState.translucent) {
        styleTranslucent = true;
      }
    }

    pointCloud._styleTranslucent = styleTranslucent;

    const hasColorStyle = defined(colorStyleFunction);
    const hasShowStyle = defined(showStyleFunction);
    const hasPointSizeStyle = defined(pointSizeStyleFunction);
    const hasClippedContent = pointCloud.isClipped;

    // Get the properties in use by the style
    const styleablePropertyIds = [];
    const builtinPropertyNames = [];

    if (hasColorStyle) {
      getStyleablePropertyIds(colorStyleFunction, styleablePropertyIds);
      getBuiltinPropertyNames(colorStyleFunction, builtinPropertyNames);
    }
    if (hasShowStyle) {
      getStyleablePropertyIds(showStyleFunction, styleablePropertyIds);
      getBuiltinPropertyNames(showStyleFunction, builtinPropertyNames);
    }
    if (hasPointSizeStyle) {
      getStyleablePropertyIds(pointSizeStyleFunction, styleablePropertyIds);
      getBuiltinPropertyNames(pointSizeStyleFunction, builtinPropertyNames);
    }

    const usesColorSemantic = builtinPropertyNames.indexOf("COLOR") >= 0;
    const usesNormalSemantic = builtinPropertyNames.indexOf("NORMAL") >= 0;

    if (usesNormalSemantic && !hasNormals) {
      throw new RuntimeError(
        "Style references the NORMAL semantic but the point cloud does not have normals"
      );
    }

    // Disable vertex attributes that aren't used in the style, enable attributes that are
    for (name in styleableShaderAttributes) {
      if (styleableShaderAttributes.hasOwnProperty(name)) {
        attribute = styleableShaderAttributes[name];
        const enabled = styleablePropertyIds.indexOf(attribute.location) >= 0;
        const vertexAttribute = getVertexAttribute(
          vertexArray,
          attribute.location
        );
        vertexAttribute.enabled = enabled;
      }
    }

    const usesColors = hasColors && (!hasColorStyle || usesColorSemantic);
    if (hasColors) {
      // Disable the color vertex attribute if the color style does not reference the color semantic
      const colorVertexAttribute = getVertexAttribute(vertexArray, colorLocation);
      colorVertexAttribute.enabled = usesColors;
    }

    const usesNormals =
      hasNormals && (normalShading || backFaceCulling || usesNormalSemantic);
    if (hasNormals) {
      // Disable the normal vertex attribute if normals are not used
      const normalVertexAttribute = getVertexAttribute(
        vertexArray,
        normalLocation
      );
      normalVertexAttribute.enabled = usesNormals;
    }

    const attributeLocations = {
      a_position: positionLocation,
    };
    if (usesColors) {
      attributeLocations.a_color = colorLocation;
    }
    if (usesNormals) {
      attributeLocations.a_normal = normalLocation;
    }
    if (hasBatchIds) {
      attributeLocations.a_batchId = batchIdLocation;
    }

    let attributeDeclarations = "";

    const length = styleablePropertyIds.length;
    for (i = 0; i < length; ++i) {
      const propertyId = styleablePropertyIds[i];
      attribute = propertyIdToAttributeMap[propertyId];
      const componentCount = attribute.componentCount;
      const attributeName = `czm_3dtiles_property_${propertyId}`;
      let attributeType;
      if (componentCount === 1) {
        attributeType = "float";
      } else {
        attributeType = `vec${componentCount}`;
      }

      attributeDeclarations += `attribute ${attributeType} ${attributeName}; \n`;
      attributeLocations[attributeName] = attribute.location;
    }

    createUniformMap$4(pointCloud, frameState);

    let vs =
      "attribute vec3 a_position; \n" +
      "varying vec4 v_color; \n" +
      "uniform vec4 u_pointSizeAndTimeAndGeometricErrorAndDepthMultiplier; \n" +
      "uniform vec4 u_constantColor; \n" +
      "uniform vec4 u_highlightColor; \n";
    vs += "float u_pointSize; \n" + "float u_time; \n";

    if (attenuation) {
      vs += "float u_geometricError; \n" + "float u_depthMultiplier; \n";
    }

    vs += attributeDeclarations;

    if (usesColors) {
      if (isTranslucent) {
        vs += "attribute vec4 a_color; \n";
      } else if (isRGB565) {
        vs +=
          "attribute float a_color; \n" +
          "const float SHIFT_RIGHT_11 = 1.0 / 2048.0; \n" +
          "const float SHIFT_RIGHT_5 = 1.0 / 32.0; \n" +
          "const float SHIFT_LEFT_11 = 2048.0; \n" +
          "const float SHIFT_LEFT_5 = 32.0; \n" +
          "const float NORMALIZE_6 = 1.0 / 64.0; \n" +
          "const float NORMALIZE_5 = 1.0 / 32.0; \n";
      } else {
        vs += "attribute vec3 a_color; \n";
      }
    }
    if (usesNormals) {
      if (isOctEncoded16P || isOctEncodedDraco) {
        vs += "attribute vec2 a_normal; \n";
      } else {
        vs += "attribute vec3 a_normal; \n";
      }
    }

    if (hasBatchIds) {
      vs += "attribute float a_batchId; \n";
    }

    if (isQuantized || isQuantizedDraco || isOctEncodedDraco) {
      vs += "uniform vec4 u_quantizedVolumeScaleAndOctEncodedRange; \n";
    }

    if (hasColorStyle) {
      vs += colorStyleFunction;
    }

    if (hasShowStyle) {
      vs += showStyleFunction;
    }

    if (hasPointSizeStyle) {
      vs += pointSizeStyleFunction;
    }

    vs +=
      "void main() \n" +
      "{ \n" +
      "    u_pointSize = u_pointSizeAndTimeAndGeometricErrorAndDepthMultiplier.x; \n" +
      "    u_time = u_pointSizeAndTimeAndGeometricErrorAndDepthMultiplier.y; \n";

    if (attenuation) {
      vs +=
        "    u_geometricError = u_pointSizeAndTimeAndGeometricErrorAndDepthMultiplier.z; \n" +
        "    u_depthMultiplier = u_pointSizeAndTimeAndGeometricErrorAndDepthMultiplier.w; \n";
    }

    if (usesColors) {
      if (isTranslucent) {
        vs += "    vec4 color = a_color; \n";
      } else if (isRGB565) {
        vs +=
          "    float compressed = a_color; \n" +
          "    float r = floor(compressed * SHIFT_RIGHT_11); \n" +
          "    compressed -= r * SHIFT_LEFT_11; \n" +
          "    float g = floor(compressed * SHIFT_RIGHT_5); \n" +
          "    compressed -= g * SHIFT_LEFT_5; \n" +
          "    float b = compressed; \n" +
          "    vec3 rgb = vec3(r * NORMALIZE_5, g * NORMALIZE_6, b * NORMALIZE_5); \n" +
          "    vec4 color = vec4(rgb, 1.0); \n";
      } else {
        vs += "    vec4 color = vec4(a_color, 1.0); \n";
      }
    } else {
      vs += "    vec4 color = u_constantColor; \n";
    }

    if (isQuantized || isQuantizedDraco) {
      vs +=
        "    vec3 position = a_position * u_quantizedVolumeScaleAndOctEncodedRange.xyz; \n";
    } else {
      vs += "    vec3 position = a_position; \n";
    }
    vs +=
      "    vec3 position_absolute = vec3(czm_model * vec4(position, 1.0)); \n";

    if (usesNormals) {
      if (isOctEncoded16P) {
        vs += "    vec3 normal = czm_octDecode(a_normal); \n";
      } else if (isOctEncodedDraco) {
        // Draco oct-encoding decodes to zxy order
        vs +=
          "    vec3 normal = czm_octDecode(a_normal, u_quantizedVolumeScaleAndOctEncodedRange.w).zxy; \n";
      } else {
        vs += "    vec3 normal = a_normal; \n";
      }
      vs += "    vec3 normalEC = czm_normal * normal; \n";
    } else {
      vs += "    vec3 normal = vec3(1.0); \n";
    }

    if (hasColorStyle) {
      vs +=
        "    color = getColorFromStyle(position, position_absolute, color, normal); \n";
    }

    if (hasShowStyle) {
      vs +=
        "    float show = float(getShowFromStyle(position, position_absolute, color, normal)); \n";
    }

    if (hasPointSizeStyle) {
      vs +=
        "    gl_PointSize = getPointSizeFromStyle(position, position_absolute, color, normal) * czm_pixelRatio; \n";
    } else if (attenuation) {
      vs +=
        "    vec4 positionEC = czm_modelView * vec4(position, 1.0); \n" +
        "    float depth = -positionEC.z; \n" +
        // compute SSE for this point
        "    gl_PointSize = min((u_geometricError / depth) * u_depthMultiplier, u_pointSize); \n";
    } else {
      vs += "    gl_PointSize = u_pointSize; \n";
    }

    vs += "    color = color * u_highlightColor; \n";

    if (usesNormals && normalShading) {
      vs +=
        "    float diffuseStrength = czm_getLambertDiffuse(czm_lightDirectionEC, normalEC); \n" +
        "    diffuseStrength = max(diffuseStrength, 0.4); \n" + // Apply some ambient lighting
        "    color.xyz *= diffuseStrength * czm_lightColor; \n";
    }

    vs +=
      "    v_color = color; \n" +
      "    gl_Position = czm_modelViewProjection * vec4(position, 1.0); \n";

    if (usesNormals && backFaceCulling) {
      vs +=
        "    float visible = step(-normalEC.z, 0.0); \n" +
        "    gl_Position *= visible; \n" +
        "    gl_PointSize *= visible; \n";
    }

    if (hasShowStyle) {
      vs +=
        "    gl_Position.w *= float(show); \n" +
        "    gl_PointSize *= float(show); \n";
    }

    vs += "} \n";

    let fs = "varying vec4 v_color; \n";

    if (hasClippedContent) {
      fs +=
        "uniform highp sampler2D u_clippingPlanes; \n" +
        "uniform mat4 u_clippingPlanesMatrix; \n" +
        "uniform vec4 u_clippingPlanesEdgeStyle; \n";
      fs += "\n";
      fs += getClippingFunction(clippingPlanes, context);
      fs += "\n";
    }

    fs +=
      "void main() \n" +
      "{ \n" +
      "    gl_FragColor = czm_gammaCorrect(v_color); \n";

    if (hasClippedContent) {
      fs += getClipAndStyleCode(
        "u_clippingPlanes",
        "u_clippingPlanesMatrix",
        "u_clippingPlanesEdgeStyle"
      );
    }

    fs += "} \n";

    if (pointCloud.splitDirection !== SplitDirection$1.NONE) {
      fs = Splitter.modifyFragmentShader(fs);
    }

    if (defined(pointCloud._vertexShaderLoaded)) {
      vs = pointCloud._vertexShaderLoaded(vs);
    }

    if (defined(pointCloud._fragmentShaderLoaded)) {
      fs = pointCloud._fragmentShaderLoaded(fs);
    }

    const drawCommand = pointCloud._drawCommand;
    if (defined(drawCommand.shaderProgram)) {
      // Destroy the old shader
      drawCommand.shaderProgram.destroy();
    }
    drawCommand.shaderProgram = ShaderProgram.fromCache({
      context: context,
      vertexShaderSource: vs,
      fragmentShaderSource: fs,
      attributeLocations: attributeLocations,
    });

    try {
      // Check if the shader compiles correctly. If not there is likely a syntax error with the style.
      drawCommand.shaderProgram._bind();
    } catch (error) {
      // Rephrase the error.
      throw new RuntimeError(
        "Error generating style shader: this may be caused by a type mismatch, index out-of-bounds, or other syntax error."
      );
    }
  }

  function decodeDraco$1(pointCloud, context) {
    if (pointCloud._decodingState === DecodingState.READY) {
      return false;
    }
    if (pointCloud._decodingState === DecodingState.NEEDS_DECODE) {
      const parsedContent = pointCloud._parsedContent;
      const draco = parsedContent.draco;
      const decodePromise = DracoLoader.decodePointCloud(draco, context);
      if (defined(decodePromise)) {
        pointCloud._decodingState = DecodingState.DECODING;
        decodePromise
          .then(function (result) {
            pointCloud._decodingState = DecodingState.READY;
            const decodedPositions = defined(result.POSITION)
              ? result.POSITION.array
              : undefined;
            const decodedRgb = defined(result.RGB) ? result.RGB.array : undefined;
            const decodedRgba = defined(result.RGBA)
              ? result.RGBA.array
              : undefined;
            const decodedNormals = defined(result.NORMAL)
              ? result.NORMAL.array
              : undefined;
            const decodedBatchIds = defined(result.BATCH_ID)
              ? result.BATCH_ID.array
              : undefined;
            const isQuantizedDraco =
              defined(decodedPositions) &&
              defined(result.POSITION.data.quantization);
            const isOctEncodedDraco =
              defined(decodedNormals) && defined(result.NORMAL.data.quantization);
            if (isQuantizedDraco) {
              // Draco quantization range == quantized volume scale - size in meters of the quantized volume
              // Internal quantized range is the range of values of the quantized data, e.g. 255 for 8-bit, 1023 for 10-bit, etc
              const quantization = result.POSITION.data.quantization;
              const range = quantization.range;
              pointCloud._quantizedVolumeScale = Cartesian3.fromElements(
                range,
                range,
                range
              );
              pointCloud._quantizedVolumeOffset = Cartesian3.unpack(
                quantization.minValues
              );
              pointCloud._quantizedRange =
                (1 << quantization.quantizationBits) - 1.0;
              pointCloud._isQuantizedDraco = true;
            }
            if (isOctEncodedDraco) {
              pointCloud._octEncodedRange =
                (1 << result.NORMAL.data.quantization.quantizationBits) - 1.0;
              pointCloud._isOctEncodedDraco = true;
            }
            let styleableProperties = parsedContent.styleableProperties;
            const batchTableProperties = draco.batchTableProperties;
            for (const name in batchTableProperties) {
              if (batchTableProperties.hasOwnProperty(name)) {
                const property = result[name];
                if (!defined(styleableProperties)) {
                  styleableProperties = {};
                }
                styleableProperties[name] = {
                  typedArray: property.array,
                  componentCount: property.data.componentsPerAttribute,
                };
              }
            }

            if (defined(decodedPositions)) {
              parsedContent.positions = {
                typedArray: decodedPositions,
              };
            }

            const decodedColors = defaultValue(decodedRgba, decodedRgb);
            if (defined(decodedColors)) {
              parsedContent.colors = {
                typedArray: decodedColors,
              };
            }

            if (defined(decodedNormals)) {
              parsedContent.normals = {
                typedArray: decodedNormals,
              };
            }

            if (defined(decodedBatchIds)) {
              parsedContent.batchIds = {
                typedArray: decodedBatchIds,
              };
            }

            parsedContent.styleableProperties = styleableProperties;
          })
          .catch(function (error) {
            pointCloud._decodingState = DecodingState.FAILED;
            pointCloud._rejectReadyPromise(error);
          });
      }
    }
    return true;
  }

  const scratchComputedTranslation$1 = new Cartesian4();
  const scratchScale$3 = new Cartesian3();

  PointCloud.prototype.update = function (frameState) {
    const context = frameState.context;
    const decoding = decodeDraco$1(this, context);
    if (decoding) {
      return;
    }

    let shadersDirty = false;
    let modelMatrixDirty = !Matrix4.equals(this._modelMatrix, this.modelMatrix);

    if (this._mode !== frameState.mode) {
      this._mode = frameState.mode;
      modelMatrixDirty = true;
    }

    if (!defined(this._drawCommand)) {
      createResources$3(this, frameState);
      modelMatrixDirty = true;
      shadersDirty = true;
      this._resolveReadyPromise();
      this._parsedContent = undefined; // Unload
    }

    if (modelMatrixDirty) {
      Matrix4.clone(this.modelMatrix, this._modelMatrix);
      const modelMatrix = this._drawCommand.modelMatrix;
      Matrix4.clone(this._modelMatrix, modelMatrix);

      if (defined(this._rtcCenter)) {
        Matrix4.multiplyByTranslation(modelMatrix, this._rtcCenter, modelMatrix);
      }
      if (defined(this._quantizedVolumeOffset)) {
        Matrix4.multiplyByTranslation(
          modelMatrix,
          this._quantizedVolumeOffset,
          modelMatrix
        );
      }

      if (frameState.mode !== SceneMode$1.SCENE3D) {
        const projection = frameState.mapProjection;
        const translation = Matrix4.getColumn(
          modelMatrix,
          3,
          scratchComputedTranslation$1
        );
        if (!Cartesian4.equals(translation, Cartesian4.UNIT_W)) {
          Transforms.basisTo2D(projection, modelMatrix, modelMatrix);
        }
      }

      const boundingSphere = this._drawCommand.boundingVolume;
      BoundingSphere.clone(this._boundingSphere, boundingSphere);

      if (this._cull) {
        const center = boundingSphere.center;
        Matrix4.multiplyByPoint(modelMatrix, center, center);
        const scale = Matrix4.getScale(modelMatrix, scratchScale$3);
        boundingSphere.radius *= Cartesian3.maximumComponent(scale);
      }
    }

    if (this.clippingPlanesDirty) {
      this.clippingPlanesDirty = false;
      shadersDirty = true;
    }

    if (this._attenuation !== this.attenuation) {
      this._attenuation = this.attenuation;
      shadersDirty = true;
    }

    if (this.backFaceCulling !== this._backFaceCulling) {
      this._backFaceCulling = this.backFaceCulling;
      shadersDirty = true;
    }

    if (this.normalShading !== this._normalShading) {
      this._normalShading = this.normalShading;
      shadersDirty = true;
    }

    if (this._style !== this.style || this.styleDirty) {
      this._style = this.style;
      this.styleDirty = false;
      shadersDirty = true;
    }

    const splittingEnabled = this.splitDirection !== SplitDirection$1.NONE;
    if (this._splittingEnabled !== splittingEnabled) {
      this._splittingEnabled = splittingEnabled;
      shadersDirty = true;
    }

    if (shadersDirty) {
      createShaders$2(this, frameState, this._style);
    }

    this._drawCommand.castShadows = ShadowMode$1.castShadows(this.shadows);
    this._drawCommand.receiveShadows = ShadowMode$1.receiveShadows(this.shadows);

    // Update the render state
    const isTranslucent =
      this._highlightColor.alpha < 1.0 ||
      this._constantColor.alpha < 1.0 ||
      this._styleTranslucent;
    this._drawCommand.renderState = isTranslucent
      ? this._translucentRenderState
      : this._opaqueRenderState;
    this._drawCommand.pass = isTranslucent ? Pass$1.TRANSLUCENT : this._opaquePass;

    const commandList = frameState.commandList;

    const passes = frameState.passes;
    if (passes.render || passes.pick) {
      commandList.push(this._drawCommand);
    }
  };

  PointCloud.prototype.isDestroyed = function () {
    return false;
  };

  PointCloud.prototype.destroy = function () {
    const command = this._drawCommand;
    if (defined(command)) {
      command.vertexArray = command.vertexArray && command.vertexArray.destroy();
      command.shaderProgram =
        command.shaderProgram && command.shaderProgram.destroy();
    }
    return destroyObject(this);
  };

  function attachTexture(framebuffer, attachment, texture) {
    const gl = framebuffer._gl;
    gl.framebufferTexture2D(
      gl.FRAMEBUFFER,
      attachment,
      texture._target,
      texture._texture,
      0
    );
  }

  function attachRenderbuffer(framebuffer, attachment, renderbuffer) {
    const gl = framebuffer._gl;
    gl.framebufferRenderbuffer(
      gl.FRAMEBUFFER,
      attachment,
      gl.RENDERBUFFER,
      renderbuffer._getRenderbuffer()
    );
  }

  /**
   * Creates a framebuffer with optional initial color, depth, and stencil attachments.
   * Framebuffers are used for render-to-texture effects; they allow us to render to
   * textures in one pass, and read from it in a later pass.
   *
   * @param {Object} options The initial framebuffer attachments as shown in the example below. <code>context</code> is required. The possible properties are <code>colorTextures</code>, <code>colorRenderbuffers</code>, <code>depthTexture</code>, <code>depthRenderbuffer</code>, <code>stencilRenderbuffer</code>, <code>depthStencilTexture</code>, <code>depthStencilRenderbuffer</code>, and <code>destroyAttachments</code>.
   *
   * @exception {DeveloperError} Cannot have both color texture and color renderbuffer attachments.
   * @exception {DeveloperError} Cannot have both a depth texture and depth renderbuffer attachment.
   * @exception {DeveloperError} Cannot have both a depth-stencil texture and depth-stencil renderbuffer attachment.
   * @exception {DeveloperError} Cannot have both a depth and depth-stencil renderbuffer.
   * @exception {DeveloperError} Cannot have both a stencil and depth-stencil renderbuffer.
   * @exception {DeveloperError} Cannot have both a depth and stencil renderbuffer.
   * @exception {DeveloperError} The color-texture pixel-format must be a color format.
   * @exception {DeveloperError} The depth-texture pixel-format must be DEPTH_COMPONENT.
   * @exception {DeveloperError} The depth-stencil-texture pixel-format must be DEPTH_STENCIL.
   * @exception {DeveloperError} The number of color attachments exceeds the number supported.
   * @exception {DeveloperError} The color-texture pixel datatype is HALF_FLOAT and the WebGL implementation does not support the EXT_color_buffer_half_float extension.
   * @exception {DeveloperError} The color-texture pixel datatype is FLOAT and the WebGL implementation does not support the EXT_color_buffer_float or WEBGL_color_buffer_float extensions.
   *
   * @example
   * // Create a framebuffer with color and depth texture attachments.
   * const width = context.canvas.clientWidth;
   * const height = context.canvas.clientHeight;
   * const framebuffer = new Framebuffer({
   *   context : context,
   *   colorTextures : [new Texture({
   *     context : context,
   *     width : width,
   *     height : height,
   *     pixelFormat : PixelFormat.RGBA
   *   })],
   *   depthTexture : new Texture({
   *     context : context,
   *     width : width,
   *     height : height,
   *     pixelFormat : PixelFormat.DEPTH_COMPONENT,
   *     pixelDatatype : PixelDatatype.UNSIGNED_SHORT
   *   })
   * });
   *
   * @private
   * @constructor
   */
  function Framebuffer(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const context = options.context;
    //>>includeStart('debug', pragmas.debug);
    Check.defined("options.context", context);
    //>>includeEnd('debug');

    const gl = context._gl;
    const maximumColorAttachments = ContextLimits.maximumColorAttachments;

    this._gl = gl;
    this._framebuffer = gl.createFramebuffer();

    this._colorTextures = [];
    this._colorRenderbuffers = [];
    this._activeColorAttachments = [];

    this._depthTexture = undefined;
    this._depthRenderbuffer = undefined;
    this._stencilRenderbuffer = undefined;
    this._depthStencilTexture = undefined;
    this._depthStencilRenderbuffer = undefined;

    /**
     * When true, the framebuffer owns its attachments so they will be destroyed when
     * {@link Framebuffer#destroy} is called or when a new attachment is assigned
     * to an attachment point.
     *
     * @type {Boolean}
     * @default true
     *
     * @see Framebuffer#destroy
     */
    this.destroyAttachments = defaultValue(options.destroyAttachments, true);

    // Throw if a texture and renderbuffer are attached to the same point.  This won't
    // cause a WebGL error (because only one will be attached), but is likely a developer error.

    //>>includeStart('debug', pragmas.debug);
    if (defined(options.colorTextures) && defined(options.colorRenderbuffers)) {
      throw new DeveloperError(
        "Cannot have both color texture and color renderbuffer attachments."
      );
    }
    if (defined(options.depthTexture) && defined(options.depthRenderbuffer)) {
      throw new DeveloperError(
        "Cannot have both a depth texture and depth renderbuffer attachment."
      );
    }
    if (
      defined(options.depthStencilTexture) &&
      defined(options.depthStencilRenderbuffer)
    ) {
      throw new DeveloperError(
        "Cannot have both a depth-stencil texture and depth-stencil renderbuffer attachment."
      );
    }
    //>>includeEnd('debug');

    // Avoid errors defined in Section 6.5 of the WebGL spec
    const depthAttachment =
      defined(options.depthTexture) || defined(options.depthRenderbuffer);
    const depthStencilAttachment =
      defined(options.depthStencilTexture) ||
      defined(options.depthStencilRenderbuffer);

    //>>includeStart('debug', pragmas.debug);
    if (depthAttachment && depthStencilAttachment) {
      throw new DeveloperError(
        "Cannot have both a depth and depth-stencil attachment."
      );
    }
    if (defined(options.stencilRenderbuffer) && depthStencilAttachment) {
      throw new DeveloperError(
        "Cannot have both a stencil and depth-stencil attachment."
      );
    }
    if (depthAttachment && defined(options.stencilRenderbuffer)) {
      throw new DeveloperError(
        "Cannot have both a depth and stencil attachment."
      );
    }
    //>>includeEnd('debug');

    ///////////////////////////////////////////////////////////////////

    this._bind();

    let texture;
    let renderbuffer;
    let i;
    let length;
    let attachmentEnum;

    if (defined(options.colorTextures)) {
      const textures = options.colorTextures;
      length = this._colorTextures.length = this._activeColorAttachments.length =
        textures.length;

      //>>includeStart('debug', pragmas.debug);
      if (length > maximumColorAttachments) {
        throw new DeveloperError(
          "The number of color attachments exceeds the number supported."
        );
      }
      //>>includeEnd('debug');

      for (i = 0; i < length; ++i) {
        texture = textures[i];

        //>>includeStart('debug', pragmas.debug);
        if (!PixelFormat$1.isColorFormat(texture.pixelFormat)) {
          throw new DeveloperError(
            "The color-texture pixel-format must be a color format."
          );
        }
        if (
          texture.pixelDatatype === PixelDatatype$1.FLOAT &&
          !context.colorBufferFloat
        ) {
          throw new DeveloperError(
            "The color texture pixel datatype is FLOAT and the WebGL implementation does not support the EXT_color_buffer_float or WEBGL_color_buffer_float extensions. See Context.colorBufferFloat."
          );
        }
        if (
          texture.pixelDatatype === PixelDatatype$1.HALF_FLOAT &&
          !context.colorBufferHalfFloat
        ) {
          throw new DeveloperError(
            "The color texture pixel datatype is HALF_FLOAT and the WebGL implementation does not support the EXT_color_buffer_half_float extension. See Context.colorBufferHalfFloat."
          );
        }
        //>>includeEnd('debug');

        attachmentEnum = this._gl.COLOR_ATTACHMENT0 + i;
        attachTexture(this, attachmentEnum, texture);
        this._activeColorAttachments[i] = attachmentEnum;
        this._colorTextures[i] = texture;
      }
    }

    if (defined(options.colorRenderbuffers)) {
      const renderbuffers = options.colorRenderbuffers;
      length = this._colorRenderbuffers.length = this._activeColorAttachments.length =
        renderbuffers.length;

      //>>includeStart('debug', pragmas.debug);
      if (length > maximumColorAttachments) {
        throw new DeveloperError(
          "The number of color attachments exceeds the number supported."
        );
      }
      //>>includeEnd('debug');

      for (i = 0; i < length; ++i) {
        renderbuffer = renderbuffers[i];
        attachmentEnum = this._gl.COLOR_ATTACHMENT0 + i;
        attachRenderbuffer(this, attachmentEnum, renderbuffer);
        this._activeColorAttachments[i] = attachmentEnum;
        this._colorRenderbuffers[i] = renderbuffer;
      }
    }

    if (defined(options.depthTexture)) {
      texture = options.depthTexture;

      //>>includeStart('debug', pragmas.debug);
      if (texture.pixelFormat !== PixelFormat$1.DEPTH_COMPONENT) {
        throw new DeveloperError(
          "The depth-texture pixel-format must be DEPTH_COMPONENT."
        );
      }
      //>>includeEnd('debug');

      attachTexture(this, this._gl.DEPTH_ATTACHMENT, texture);
      this._depthTexture = texture;
    }

    if (defined(options.depthRenderbuffer)) {
      renderbuffer = options.depthRenderbuffer;
      attachRenderbuffer(this, this._gl.DEPTH_ATTACHMENT, renderbuffer);
      this._depthRenderbuffer = renderbuffer;
    }

    if (defined(options.stencilRenderbuffer)) {
      renderbuffer = options.stencilRenderbuffer;
      attachRenderbuffer(this, this._gl.STENCIL_ATTACHMENT, renderbuffer);
      this._stencilRenderbuffer = renderbuffer;
    }

    if (defined(options.depthStencilTexture)) {
      texture = options.depthStencilTexture;

      //>>includeStart('debug', pragmas.debug);
      if (texture.pixelFormat !== PixelFormat$1.DEPTH_STENCIL) {
        throw new DeveloperError(
          "The depth-stencil pixel-format must be DEPTH_STENCIL."
        );
      }
      //>>includeEnd('debug');

      attachTexture(this, this._gl.DEPTH_STENCIL_ATTACHMENT, texture);
      this._depthStencilTexture = texture;
    }

    if (defined(options.depthStencilRenderbuffer)) {
      renderbuffer = options.depthStencilRenderbuffer;
      attachRenderbuffer(this, this._gl.DEPTH_STENCIL_ATTACHMENT, renderbuffer);
      this._depthStencilRenderbuffer = renderbuffer;
    }

    this._unBind();
  }

  Object.defineProperties(Framebuffer.prototype, {
    /**
     * The status of the framebuffer. If the status is not WebGLConstants.FRAMEBUFFER_COMPLETE,
     * a {@link DeveloperError} will be thrown when attempting to render to the framebuffer.
     * @memberof Framebuffer.prototype
     * @type {Number}
     */
    status: {
      get: function () {
        this._bind();
        const status = this._gl.checkFramebufferStatus(this._gl.FRAMEBUFFER);
        this._unBind();
        return status;
      },
    },
    numberOfColorAttachments: {
      get: function () {
        return this._activeColorAttachments.length;
      },
    },
    depthTexture: {
      get: function () {
        return this._depthTexture;
      },
    },
    depthRenderbuffer: {
      get: function () {
        return this._depthRenderbuffer;
      },
    },
    stencilRenderbuffer: {
      get: function () {
        return this._stencilRenderbuffer;
      },
    },
    depthStencilTexture: {
      get: function () {
        return this._depthStencilTexture;
      },
    },
    depthStencilRenderbuffer: {
      get: function () {
        return this._depthStencilRenderbuffer;
      },
    },

    /**
     * True if the framebuffer has a depth attachment.  Depth attachments include
     * depth and depth-stencil textures, and depth and depth-stencil renderbuffers.  When
     * rendering to a framebuffer, a depth attachment is required for the depth test to have effect.
     * @memberof Framebuffer.prototype
     * @type {Boolean}
     */
    hasDepthAttachment: {
      get: function () {
        return !!(
          this.depthTexture ||
          this.depthRenderbuffer ||
          this.depthStencilTexture ||
          this.depthStencilRenderbuffer
        );
      },
    },
  });

  Framebuffer.prototype._bind = function () {
    const gl = this._gl;
    gl.bindFramebuffer(gl.FRAMEBUFFER, this._framebuffer);
  };

  Framebuffer.prototype._unBind = function () {
    const gl = this._gl;
    gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  };

  Framebuffer.prototype.bindDraw = function () {
    const gl = this._gl;
    gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, this._framebuffer);
  };

  Framebuffer.prototype.bindRead = function () {
    const gl = this._gl;
    gl.bindFramebuffer(gl.READ_FRAMEBUFFER, this._framebuffer);
  };

  Framebuffer.prototype._getActiveColorAttachments = function () {
    return this._activeColorAttachments;
  };

  Framebuffer.prototype.getColorTexture = function (index) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(index) || index < 0 || index >= this._colorTextures.length) {
      throw new DeveloperError(
        "index is required, must be greater than or equal to zero and must be less than the number of color attachments."
      );
    }
    //>>includeEnd('debug');

    return this._colorTextures[index];
  };

  Framebuffer.prototype.getColorRenderbuffer = function (index) {
    //>>includeStart('debug', pragmas.debug);
    if (
      !defined(index) ||
      index < 0 ||
      index >= this._colorRenderbuffers.length
    ) {
      throw new DeveloperError(
        "index is required, must be greater than or equal to zero and must be less than the number of color attachments."
      );
    }
    //>>includeEnd('debug');

    return this._colorRenderbuffers[index];
  };

  Framebuffer.prototype.isDestroyed = function () {
    return false;
  };

  Framebuffer.prototype.destroy = function () {
    if (this.destroyAttachments) {
      // If the color texture is a cube map face, it is owned by the cube map, and will not be destroyed.
      let i = 0;
      const textures = this._colorTextures;
      let length = textures.length;
      for (; i < length; ++i) {
        const texture = textures[i];
        if (defined(texture)) {
          texture.destroy();
        }
      }

      const renderbuffers = this._colorRenderbuffers;
      length = renderbuffers.length;
      for (i = 0; i < length; ++i) {
        const renderbuffer = renderbuffers[i];
        if (defined(renderbuffer)) {
          renderbuffer.destroy();
        }
      }

      this._depthTexture = this._depthTexture && this._depthTexture.destroy();
      this._depthRenderbuffer =
        this._depthRenderbuffer && this._depthRenderbuffer.destroy();
      this._stencilRenderbuffer =
        this._stencilRenderbuffer && this._stencilRenderbuffer.destroy();
      this._depthStencilTexture =
        this._depthStencilTexture && this._depthStencilTexture.destroy();
      this._depthStencilRenderbuffer =
        this._depthStencilRenderbuffer &&
        this._depthStencilRenderbuffer.destroy();
    }

    this._gl.deleteFramebuffer(this._framebuffer);
    return destroyObject(this);
  };

  /**
   * Creates a multisampling wrapper around two framebuffers with optional initial
   * color and depth-stencil attachments. The first framebuffer has multisampled
   * renderbuffer attachments and is bound to READ_FRAMEBUFFER during the blit. The
   * second is bound to DRAW_FRAMEBUFFER during the blit, and has texture attachments
   * to store the copied pixels.
   *
   * @param {Object} options The initial framebuffer attachments. <code>context</code>, <code>width</code>, and <code>height</code> are required. The possible properties are <code>colorTextures</code>, <code>colorRenderbuffers</code>, <code>depthStencilTexture</code>, <code>depthStencilRenderbuffer</code>, and <code>destroyAttachments</code>.
   *
   * @exception {DeveloperError} Both color renderbuffer and texture attachments must be provided.
   * @exception {DeveloperError} Both depth-stencil renderbuffer and texture attachments must be provided.
   *
   * @private
   * @constructor
   */
  function MultisampleFramebuffer(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const context = options.context;
    const width = options.width;
    const height = options.height;
    //>>includeStart('debug', pragmas.debug);
    Check.defined("options.context", context);
    Check.defined("options.width", width);
    Check.defined("options.height", height);
    //>>includeEnd('debug');
    this._width = width;
    this._height = height;

    const colorRenderbuffers = options.colorRenderbuffers;
    const colorTextures = options.colorTextures;
    if (defined(colorRenderbuffers) !== defined(colorTextures)) {
      throw new DeveloperError(
        "Both color renderbuffer and texture attachments must be provided."
      );
    }

    const depthStencilRenderbuffer = options.depthStencilRenderbuffer;
    const depthStencilTexture = options.depthStencilTexture;
    if (defined(depthStencilRenderbuffer) !== defined(depthStencilTexture)) {
      throw new DeveloperError(
        "Both depth-stencil renderbuffer and texture attachments must be provided."
      );
    }

    this._renderFramebuffer = new Framebuffer({
      context: context,
      colorRenderbuffers: colorRenderbuffers,
      depthStencilRenderbuffer: depthStencilRenderbuffer,
      destroyAttachments: options.destroyAttachments,
    });
    this._colorFramebuffer = new Framebuffer({
      context: context,
      colorTextures: colorTextures,
      depthStencilTexture: depthStencilTexture,
      destroyAttachments: options.destroyAttachments,
    });
  }

  MultisampleFramebuffer.prototype.getRenderFramebuffer = function () {
    return this._renderFramebuffer;
  };

  MultisampleFramebuffer.prototype.getColorFramebuffer = function () {
    return this._colorFramebuffer;
  };

  MultisampleFramebuffer.prototype.blitFramebuffers = function (
    context,
    blitStencil
  ) {
    this._renderFramebuffer.bindRead();
    this._colorFramebuffer.bindDraw();
    const gl = context._gl;
    let mask = 0;
    if (this._colorFramebuffer._colorTextures.length > 0) {
      mask |= gl.COLOR_BUFFER_BIT;
    }
    if (defined(this._colorFramebuffer.depthStencilTexture)) {
      mask |= gl.DEPTH_BUFFER_BIT | (blitStencil ? gl.STENCIL_BUFFER_BIT : 0);
    }
    gl.blitFramebuffer(
      0,
      0,
      this._width,
      this._height,
      0,
      0,
      this._width,
      this._height,
      mask,
      gl.NEAREST
    );
    gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
    gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
  };

  MultisampleFramebuffer.prototype.isDestroyed = function () {
    return false;
  };

  MultisampleFramebuffer.prototype.destroy = function () {
    this._renderFramebuffer.destroy();
    this._colorFramebuffer.destroy();
    return destroyObject(this);
  };

  /**
   * @private
   */
  const RenderbufferFormat = {
    RGBA4: WebGLConstants$1.RGBA4,
    RGBA8: WebGLConstants$1.RGBA8,
    RGBA16F: WebGLConstants$1.RGBA16F,
    RGBA32F: WebGLConstants$1.RGBA32F,
    RGB5_A1: WebGLConstants$1.RGB5_A1,
    RGB565: WebGLConstants$1.RGB565,
    DEPTH_COMPONENT16: WebGLConstants$1.DEPTH_COMPONENT16,
    STENCIL_INDEX8: WebGLConstants$1.STENCIL_INDEX8,
    DEPTH_STENCIL: WebGLConstants$1.DEPTH_STENCIL,
    DEPTH24_STENCIL8: WebGLConstants$1.DEPTH24_STENCIL8,

    validate: function (renderbufferFormat) {
      return (
        renderbufferFormat === RenderbufferFormat.RGBA4 ||
        renderbufferFormat === RenderbufferFormat.RGBA8 ||
        renderbufferFormat === RenderbufferFormat.RGBA16F ||
        renderbufferFormat === RenderbufferFormat.RGBA32F ||
        renderbufferFormat === RenderbufferFormat.RGB5_A1 ||
        renderbufferFormat === RenderbufferFormat.RGB565 ||
        renderbufferFormat === RenderbufferFormat.DEPTH_COMPONENT16 ||
        renderbufferFormat === RenderbufferFormat.STENCIL_INDEX8 ||
        renderbufferFormat === RenderbufferFormat.DEPTH_STENCIL ||
        renderbufferFormat === RenderbufferFormat.DEPTH24_STENCIL8
      );
    },

    getColorFormat: function (datatype) {
      if (datatype === WebGLConstants$1.FLOAT) {
        return RenderbufferFormat.RGBA32F;
      } else if (datatype === WebGLConstants$1.HALF_FLOAT_OES) {
        return RenderbufferFormat.RGBA16F;
      }
      return RenderbufferFormat.RGBA8;
    },
  };
  var RenderbufferFormat$1 = Object.freeze(RenderbufferFormat);

  /**
   * @private
   */
  function Renderbuffer(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    Check.defined("options.context", options.context);
    //>>includeEnd('debug');

    const context = options.context;
    const gl = context._gl;
    const maximumRenderbufferSize = ContextLimits.maximumRenderbufferSize;

    const format = defaultValue(options.format, RenderbufferFormat$1.RGBA4);
    const width = defined(options.width) ? options.width : gl.drawingBufferWidth;
    const height = defined(options.height)
      ? options.height
      : gl.drawingBufferHeight;
    const numSamples = defaultValue(options.numSamples, 1);

    //>>includeStart('debug', pragmas.debug);
    if (!RenderbufferFormat$1.validate(format)) {
      throw new DeveloperError("Invalid format.");
    }

    Check.typeOf.number.greaterThan("width", width, 0);

    if (width > maximumRenderbufferSize) {
      throw new DeveloperError(
        `Width must be less than or equal to the maximum renderbuffer size (${maximumRenderbufferSize}).  Check maximumRenderbufferSize.`
      );
    }

    Check.typeOf.number.greaterThan("height", height, 0);

    if (height > maximumRenderbufferSize) {
      throw new DeveloperError(
        `Height must be less than or equal to the maximum renderbuffer size (${maximumRenderbufferSize}).  Check maximumRenderbufferSize.`
      );
    }
    //>>includeEnd('debug');

    this._gl = gl;
    this._format = format;
    this._width = width;
    this._height = height;
    this._renderbuffer = this._gl.createRenderbuffer();

    gl.bindRenderbuffer(gl.RENDERBUFFER, this._renderbuffer);
    if (numSamples > 1) {
      gl.renderbufferStorageMultisample(
        gl.RENDERBUFFER,
        numSamples,
        format,
        width,
        height
      );
    } else {
      gl.renderbufferStorage(gl.RENDERBUFFER, format, width, height);
    }
    gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  }

  Object.defineProperties(Renderbuffer.prototype, {
    format: {
      get: function () {
        return this._format;
      },
    },
    width: {
      get: function () {
        return this._width;
      },
    },
    height: {
      get: function () {
        return this._height;
      },
    },
  });

  Renderbuffer.prototype._getRenderbuffer = function () {
    return this._renderbuffer;
  };

  Renderbuffer.prototype.isDestroyed = function () {
    return false;
  };

  Renderbuffer.prototype.destroy = function () {
    this._gl.deleteRenderbuffer(this._renderbuffer);
    return destroyObject(this);
  };

  /**
   * Creates a wrapper object around a framebuffer and its resources.
   *
   * @param {Object} options Object with the following properties:
   * @param {Number} [options.numSamples=1] The multisampling rate of the render targets. Requires a WebGL2 context.
   * @param {Number} [options.colorAttachmentsLength=1] The number of color attachments this FramebufferManager will create.
   * @param {Boolean} [options.color=true] Whether the FramebufferManager will use color attachments.
   * @param {Boolean} [options.depth=false] Whether the FramebufferManager will use depth attachments.
   * @param {Boolean} [options.depthStencil=false] Whether the FramebufferManager will use depth-stencil attachments.
   * @param {Boolean} [options.supportsDepthTexture=false] Whether the FramebufferManager will create a depth texture when the extension is supported.
   * @param {Boolean} [options.createColorAttachments=true] Whether the FramebufferManager will construct its own color attachments.
   * @param {Boolean} [options.createDepthAttachments=true] Whether the FramebufferManager will construct its own depth attachments.
   * @param {PixelDatatype} [options.pixelDatatype=undefined] The default pixel datatype to use when creating color attachments.
   * @param {PixelFormat} [options.pixelFormat=undefined] The default pixel format to use when creating color attachments.
   *
   * @exception {DeveloperError} Must enable at least one type of framebuffer attachment.
   * @exception {DeveloperError} Cannot have both a depth and depth-stencil attachment.
   *
   * @private
   * @constructor
   */
  function FramebufferManager(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    this._numSamples = defaultValue(options.numSamples, 1);
    this._colorAttachmentsLength = defaultValue(
      options.colorAttachmentsLength,
      1
    );

    this._color = defaultValue(options.color, true);
    this._depth = defaultValue(options.depth, false);
    this._depthStencil = defaultValue(options.depthStencil, false);
    this._supportsDepthTexture = defaultValue(
      options.supportsDepthTexture,
      false
    );
    //>>includeStart('debug', pragmas.debug);
    if (!this._color && !this._depth && !this._depthStencil) {
      throw new DeveloperError(
        "Must enable at least one type of framebuffer attachment."
      );
    }
    if (this._depth && this._depthStencil) {
      throw new DeveloperError(
        "Cannot have both a depth and depth-stencil attachment."
      );
    }
    //>>includeEnd('debug');

    this._createColorAttachments = defaultValue(
      options.createColorAttachments,
      true
    );
    this._createDepthAttachments = defaultValue(
      options.createDepthAttachments,
      true
    );

    this._pixelDatatype = options.pixelDatatype;
    this._pixelFormat = options.pixelFormat;

    this._width = undefined;
    this._height = undefined;

    this._framebuffer = undefined;
    this._multisampleFramebuffer = undefined;
    this._colorTextures = undefined;
    if (this._color) {
      this._colorTextures = new Array(this._colorAttachmentsLength);
      this._colorRenderbuffers = new Array(this._colorAttachmentsLength);
    }
    this._colorRenderbuffer = undefined;
    this._depthStencilRenderbuffer = undefined;
    this._depthStencilTexture = undefined;
    this._depthRenderbuffer = undefined;
    this._depthTexture = undefined;

    this._attachmentsDirty = false;
  }

  Object.defineProperties(FramebufferManager.prototype, {
    framebuffer: {
      get: function () {
        if (this._numSamples > 1) {
          return this._multisampleFramebuffer.getRenderFramebuffer();
        }
        return this._framebuffer;
      },
    },
    numSamples: {
      get: function () {
        return this._numSamples;
      },
    },
    status: {
      get: function () {
        return this.framebuffer.status;
      },
    },
  });

  FramebufferManager.prototype.isDirty = function (
    width,
    height,
    numSamples,
    pixelDatatype,
    pixelFormat
  ) {
    numSamples = defaultValue(numSamples, 1);
    const dimensionChanged = this._width !== width || this._height !== height;
    const samplesChanged = this._numSamples !== numSamples;
    const pixelChanged =
      (defined(pixelDatatype) && this._pixelDatatype !== pixelDatatype) ||
      (defined(pixelFormat) && this._pixelFormat !== pixelFormat);
    const framebufferDefined =
      numSamples === 1
        ? defined(this._framebuffer)
        : defined(this._multisampleFramebuffer);

    return (
      this._attachmentsDirty ||
      dimensionChanged ||
      samplesChanged ||
      pixelChanged ||
      !framebufferDefined ||
      (this._color && !defined(this._colorTextures[0]))
    );
  };

  FramebufferManager.prototype.update = function (
    context,
    width,
    height,
    numSamples,
    pixelDatatype,
    pixelFormat
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(width) || !defined(height)) {
      throw new DeveloperError("width and height must be defined.");
    }
    //>>includeEnd('debug');
    numSamples = context.msaa ? defaultValue(numSamples, 1) : 1;
    pixelDatatype = defaultValue(
      pixelDatatype,
      this._color
        ? defaultValue(this._pixelDatatype, PixelDatatype$1.UNSIGNED_BYTE)
        : undefined
    );
    pixelFormat = defaultValue(
      pixelFormat,
      this._color ? defaultValue(this._pixelFormat, PixelFormat$1.RGBA) : undefined
    );

    if (this.isDirty(width, height, numSamples, pixelDatatype, pixelFormat)) {
      this.destroy();
      this._width = width;
      this._height = height;
      this._numSamples = numSamples;
      this._pixelDatatype = pixelDatatype;
      this._pixelFormat = pixelFormat;
      this._attachmentsDirty = false;

      // Create color texture
      if (this._color && this._createColorAttachments) {
        for (let i = 0; i < this._colorAttachmentsLength; ++i) {
          this._colorTextures[i] = new Texture({
            context: context,
            width: width,
            height: height,
            pixelFormat: pixelFormat,
            pixelDatatype: pixelDatatype,
            sampler: Sampler.NEAREST,
          });
          if (this._numSamples > 1) {
            const format = RenderbufferFormat$1.getColorFormat(pixelDatatype);
            this._colorRenderbuffers[i] = new Renderbuffer({
              context: context,
              width: width,
              height: height,
              format: format,
              numSamples: this._numSamples,
            });
          }
        }
      }

      // Create depth stencil texture or renderbuffer
      if (this._depthStencil && this._createDepthAttachments) {
        if (this._supportsDepthTexture && context.depthTexture) {
          this._depthStencilTexture = new Texture({
            context: context,
            width: width,
            height: height,
            pixelFormat: PixelFormat$1.DEPTH_STENCIL,
            pixelDatatype: PixelDatatype$1.UNSIGNED_INT_24_8,
            sampler: Sampler.NEAREST,
          });
          if (this._numSamples > 1) {
            this._depthStencilRenderbuffer = new Renderbuffer({
              context: context,
              width: width,
              height: height,
              format: RenderbufferFormat$1.DEPTH24_STENCIL8,
              numSamples: this._numSamples,
            });
          }
        } else {
          this._depthStencilRenderbuffer = new Renderbuffer({
            context: context,
            width: width,
            height: height,
            format: RenderbufferFormat$1.DEPTH_STENCIL,
          });
        }
      }

      // Create depth texture
      if (this._depth && this._createDepthAttachments) {
        if (this._supportsDepthTexture && context.depthTexture) {
          this._depthTexture = new Texture({
            context: context,
            width: width,
            height: height,
            pixelFormat: PixelFormat$1.DEPTH_COMPONENT,
            pixelDatatype: PixelDatatype$1.UNSIGNED_INT,
            sampler: Sampler.NEAREST,
          });
        } else {
          this._depthRenderbuffer = new Renderbuffer({
            context: context,
            width: width,
            height: height,
            format: RenderbufferFormat$1.DEPTH_COMPONENT16,
          });
        }
      }

      if (this._numSamples > 1) {
        this._multisampleFramebuffer = new MultisampleFramebuffer({
          context: context,
          width: this._width,
          height: this._height,
          colorTextures: this._colorTextures,
          colorRenderbuffers: this._colorRenderbuffers,
          depthStencilTexture: this._depthStencilTexture,
          depthStencilRenderbuffer: this._depthStencilRenderbuffer,
          destroyAttachments: false,
        });
      } else {
        this._framebuffer = new Framebuffer({
          context: context,
          colorTextures: this._colorTextures,
          depthTexture: this._depthTexture,
          depthRenderbuffer: this._depthRenderbuffer,
          depthStencilTexture: this._depthStencilTexture,
          depthStencilRenderbuffer: this._depthStencilRenderbuffer,
          destroyAttachments: false,
        });
      }
    }
  };

  FramebufferManager.prototype.getColorTexture = function (index) {
    index = defaultValue(index, 0);
    //>>includeStart('debug', pragmas.debug);
    if (index >= this._colorAttachmentsLength) {
      throw new DeveloperError(
        "index must be smaller than total number of color attachments."
      );
    }
    //>>includeEnd('debug');
    return this._colorTextures[index];
  };

  FramebufferManager.prototype.setColorTexture = function (texture, index) {
    index = defaultValue(index, 0);
    //>>includeStart('debug', pragmas.debug);
    if (this._createColorAttachments) {
      throw new DeveloperError(
        "createColorAttachments must be false if setColorTexture is called."
      );
    }
    if (index >= this._colorAttachmentsLength) {
      throw new DeveloperError(
        "index must be smaller than total number of color attachments."
      );
    }
    //>>includeEnd('debug');
    this._attachmentsDirty = texture !== this._colorTextures[index];
    this._colorTextures[index] = texture;
  };

  FramebufferManager.prototype.getColorRenderbuffer = function (index) {
    index = defaultValue(index, 0);
    //>>includeStart('debug', pragmas.debug);
    if (index >= this._colorAttachmentsLength) {
      throw new DeveloperError(
        "index must be smaller than total number of color attachments."
      );
    }
    //>>includeEnd('debug');
    return this._colorRenderbuffers[index];
  };

  FramebufferManager.prototype.setColorRenderbuffer = function (
    renderbuffer,
    index
  ) {
    index = defaultValue(index, 0);
    //>>includeStart('debug', pragmas.debug);
    if (this._createColorAttachments) {
      throw new DeveloperError(
        "createColorAttachments must be false if setColorRenderbuffer is called."
      );
    }
    if (index >= this._colorAttachmentsLength) {
      throw new DeveloperError(
        "index must be smaller than total number of color attachments."
      );
    }
    //>>includeEnd('debug');
    this._attachmentsDirty = renderbuffer !== this._colorRenderbuffers[index];
    this._colorRenderbuffers[index] = renderbuffer;
  };

  FramebufferManager.prototype.getDepthRenderbuffer = function () {
    return this._depthRenderbuffer;
  };

  FramebufferManager.prototype.setDepthRenderbuffer = function (renderbuffer) {
    //>>includeStart('debug', pragmas.debug);
    if (this._createDepthAttachments) {
      throw new DeveloperError(
        "createDepthAttachments must be false if setDepthRenderbuffer is called."
      );
    }
    //>>includeEnd('debug');
    this._attachmentsDirty = renderbuffer !== this._depthRenderbuffer;
    this._depthRenderbuffer = renderbuffer;
  };

  FramebufferManager.prototype.getDepthTexture = function () {
    return this._depthTexture;
  };

  FramebufferManager.prototype.setDepthTexture = function (texture) {
    //>>includeStart('debug', pragmas.debug);
    if (this._createDepthAttachments) {
      throw new DeveloperError(
        "createDepthAttachments must be false if setDepthTexture is called."
      );
    }
    //>>includeEnd('debug');
    this._attachmentsDirty = texture !== this._depthTexture;
    this._depthTexture = texture;
  };

  FramebufferManager.prototype.getDepthStencilRenderbuffer = function () {
    return this._depthStencilRenderbuffer;
  };

  FramebufferManager.prototype.setDepthStencilRenderbuffer = function (
    renderbuffer
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (this._createDepthAttachments) {
      throw new DeveloperError(
        "createDepthAttachments must be false if setDepthStencilRenderbuffer is called."
      );
    }
    //>>includeEnd('debug');
    this._attachmentsDirty = renderbuffer !== this._depthStencilRenderbuffer;
    this._depthStencilRenderbuffer = renderbuffer;
  };

  FramebufferManager.prototype.getDepthStencilTexture = function () {
    return this._depthStencilTexture;
  };

  FramebufferManager.prototype.setDepthStencilTexture = function (texture) {
    //>>includeStart('debug', pragmas.debug);
    if (this._createDepthAttachments) {
      throw new DeveloperError(
        "createDepthAttachments must be false if setDepthStencilTexture is called."
      );
    }
    //>>includeEnd('debug');
    this._attachmentsDirty = texture !== this._depthStencilTexture;
    this._depthStencilTexture = texture;
  };

  FramebufferManager.prototype.prepareTextures = function (context, blitStencil) {
    if (this._numSamples > 1) {
      this._multisampleFramebuffer.blitFramebuffers(context, blitStencil);
    }
  };

  FramebufferManager.prototype.clear = function (
    context,
    clearCommand,
    passState
  ) {
    const framebuffer = clearCommand.framebuffer;
    clearCommand.framebuffer = this.framebuffer;
    clearCommand.execute(context, passState);
    clearCommand.framebuffer = framebuffer;
  };

  FramebufferManager.prototype.destroyFramebuffer = function () {
    this._framebuffer = this._framebuffer && this._framebuffer.destroy();
    this._multisampleFramebuffer =
      this._multisampleFramebuffer && this._multisampleFramebuffer.destroy();
  };

  FramebufferManager.prototype.destroy = function () {
    if (this._color) {
      let i;
      const length = this._colorTextures.length;
      for (i = 0; i < length; ++i) {
        const texture = this._colorTextures[i];
        if (this._createColorAttachments) {
          if (defined(texture) && !texture.isDestroyed()) {
            this._colorTextures[i].destroy();
            this._colorTextures[i] = undefined;
          }
        }
        if (defined(texture) && texture.isDestroyed()) {
          this._colorTextures[i] = undefined;
        }
        const renderbuffer = this._colorRenderbuffers[i];
        if (this._createColorAttachments) {
          if (defined(renderbuffer) && !renderbuffer.isDestroyed()) {
            this._colorRenderbuffers[i].destroy();
            this._colorRenderbuffers[i] = undefined;
          }
        }
        if (defined(renderbuffer) && renderbuffer.isDestroyed()) {
          this._colorRenderbuffers[i] = undefined;
        }
      }
    }

    if (this._depthStencil) {
      if (this._createDepthAttachments) {
        this._depthStencilTexture =
          this._depthStencilTexture && this._depthStencilTexture.destroy();
        this._depthStencilRenderbuffer =
          this._depthStencilRenderbuffer &&
          this._depthStencilRenderbuffer.destroy();
      }
      if (
        defined(this._depthStencilTexture) &&
        this._depthStencilTexture.isDestroyed()
      ) {
        this._depthStencilTexture = undefined;
      }
      if (
        defined(this._depthStencilRenderbuffer) &&
        this._depthStencilRenderbuffer.isDestroyed()
      ) {
        this._depthStencilRenderbuffer = undefined;
      }
    }

    if (this._depth) {
      if (this._createDepthAttachments) {
        this._depthTexture = this._depthTexture && this._depthTexture.destroy();
        this._depthRenderbuffer =
          this._depthRenderbuffer && this._depthRenderbuffer.destroy();
      }
      if (defined(this._depthTexture) && this._depthTexture.isDestroyed()) {
        this._depthTexture = undefined;
      }
      if (
        defined(this._depthRenderbuffer) &&
        this._depthRenderbuffer.isDestroyed()
      ) {
        this._depthRenderbuffer = undefined;
      }
    }

    this.destroyFramebuffer();
  };

  //This file is automatically rebuilt by the Cesium build process.
  var PointCloudEyeDomeLightingShader = "#extension GL_EXT_frag_depth : enable\n\
uniform sampler2D u_pointCloud_colorGBuffer;\n\
uniform sampler2D u_pointCloud_depthGBuffer;\n\
uniform vec2 u_distanceAndEdlStrength;\n\
varying vec2 v_textureCoordinates;\n\
vec2 neighborContribution(float log2Depth, vec2 offset)\n\
{\n\
float dist = u_distanceAndEdlStrength.x;\n\
vec2 texCoordOrig = v_textureCoordinates + offset * dist;\n\
vec2 texCoord0 = v_textureCoordinates + offset * floor(dist);\n\
vec2 texCoord1 = v_textureCoordinates + offset * ceil(dist);\n\
float depthOrLogDepth0 = czm_unpackDepth(texture2D(u_pointCloud_depthGBuffer, texCoord0));\n\
float depthOrLogDepth1 = czm_unpackDepth(texture2D(u_pointCloud_depthGBuffer, texCoord1));\n\
if (depthOrLogDepth0 == 0.0 || depthOrLogDepth1 == 0.0) {\n\
return vec2(0.0);\n\
}\n\
float depthMix = mix(depthOrLogDepth0, depthOrLogDepth1, fract(dist));\n\
vec4 eyeCoordinate = czm_windowToEyeCoordinates(texCoordOrig, depthMix);\n\
return vec2(max(0.0, log2Depth - log2(-eyeCoordinate.z / eyeCoordinate.w)), 1.0);\n\
}\n\
void main()\n\
{\n\
float depthOrLogDepth = czm_unpackDepth(texture2D(u_pointCloud_depthGBuffer, v_textureCoordinates));\n\
vec4 eyeCoordinate = czm_windowToEyeCoordinates(gl_FragCoord.xy, depthOrLogDepth);\n\
eyeCoordinate /= eyeCoordinate.w;\n\
float log2Depth = log2(-eyeCoordinate.z);\n\
if (depthOrLogDepth == 0.0)\n\
{\n\
discard;\n\
}\n\
vec4 color = texture2D(u_pointCloud_colorGBuffer, v_textureCoordinates);\n\
vec2 texelSize = 1.0 / czm_viewport.zw;\n\
vec2 responseAndCount = vec2(0.0);\n\
responseAndCount += neighborContribution(log2Depth, vec2(-texelSize.x, 0.0));\n\
responseAndCount += neighborContribution(log2Depth, vec2(+texelSize.x, 0.0));\n\
responseAndCount += neighborContribution(log2Depth, vec2(0.0, -texelSize.y));\n\
responseAndCount += neighborContribution(log2Depth, vec2(0.0, +texelSize.y));\n\
float response = responseAndCount.x / responseAndCount.y;\n\
float strength = u_distanceAndEdlStrength.y;\n\
float shade = exp(-response * 300.0 * strength);\n\
color.rgb *= shade;\n\
gl_FragColor = vec4(color);\n\
gl_FragDepthEXT = depthOrLogDepth;\n\
}\n\
";

  /**
   * Eye dome lighting. Does not support points with per-point translucency, but does allow translucent styling against the globe.
   * Requires support for EXT_frag_depth and WEBGL_draw_buffers extensions in WebGL 1.0.
   *
   * @private
   */
  function PointCloudEyeDomeLighting() {
    this._framebuffer = new FramebufferManager({
      colorAttachmentsLength: 2,
      depth: true,
      supportsDepthTexture: true,
    });

    this._drawCommand = undefined;
    this._clearCommand = undefined;

    this._strength = 1.0;
    this._radius = 1.0;
  }

  Object.defineProperties(PointCloudEyeDomeLighting.prototype, {
    framebuffer: {
      get: function () {
        return this._framebuffer.framebuffer;
      },
    },
    colorGBuffer: {
      get: function () {
        return this._framebuffer.getColorTexture(0);
      },
    },
    depthGBuffer: {
      get: function () {
        return this._framebuffer.getColorTexture(1);
      },
    },
  });

  function destroyFramebuffer$1(processor) {
    processor._framebuffer.destroy();
    processor._drawCommand = undefined;
    processor._clearCommand = undefined;
  }

  const distanceAndEdlStrengthScratch = new Cartesian2();

  function createCommands$1(processor, context) {
    const blendFS = new ShaderSource({
      defines: ["LOG_DEPTH_WRITE"],
      sources: [PointCloudEyeDomeLightingShader],
    });

    const blendUniformMap = {
      u_pointCloud_colorGBuffer: function () {
        return processor.colorGBuffer;
      },
      u_pointCloud_depthGBuffer: function () {
        return processor.depthGBuffer;
      },
      u_distanceAndEdlStrength: function () {
        distanceAndEdlStrengthScratch.x = processor._radius;
        distanceAndEdlStrengthScratch.y = processor._strength;
        return distanceAndEdlStrengthScratch;
      },
    };

    const blendRenderState = RenderState.fromCache({
      blending: BlendingState$1.ALPHA_BLEND,
      depthMask: true,
      depthTest: {
        enabled: true,
      },
      stencilTest: StencilConstants$1.setCesium3DTileBit(),
      stencilMask: StencilConstants$1.CESIUM_3D_TILE_MASK,
    });

    processor._drawCommand = context.createViewportQuadCommand(blendFS, {
      uniformMap: blendUniformMap,
      renderState: blendRenderState,
      pass: Pass$1.CESIUM_3D_TILE,
      owner: processor,
    });

    processor._clearCommand = new ClearCommand({
      framebuffer: processor.framebuffer,
      color: new Color(0.0, 0.0, 0.0, 0.0),
      depth: 1.0,
      renderState: RenderState.fromCache(),
      pass: Pass$1.CESIUM_3D_TILE,
      owner: processor,
    });
  }

  function createResources$2(processor, context) {
    const width = context.drawingBufferWidth;
    const height = context.drawingBufferHeight;
    processor._framebuffer.update(context, width, height);
    createCommands$1(processor, context);
  }

  function isSupported(context) {
    return context.drawBuffers && context.fragmentDepth;
  }

  PointCloudEyeDomeLighting.isSupported = isSupported;

  function getECShaderProgram(context, shaderProgram) {
    let shader = context.shaderCache.getDerivedShaderProgram(shaderProgram, "EC");
    if (!defined(shader)) {
      const attributeLocations = shaderProgram._attributeLocations;

      const fs = shaderProgram.fragmentShaderSource.clone();

      fs.sources = fs.sources.map(function (source) {
        source = ShaderSource.replaceMain(
          source,
          "czm_point_cloud_post_process_main"
        );
        source = source.replace(/gl_FragColor/g, "gl_FragData[0]");
        return source;
      });

      fs.sources.unshift("#extension GL_EXT_draw_buffers : enable \n");
      fs.sources.push(
        "void main() \n" +
          "{ \n" +
          "    czm_point_cloud_post_process_main(); \n" +
          "#ifdef LOG_DEPTH\n" +
          "    czm_writeLogDepth();\n" +
          "    gl_FragData[1] = czm_packDepth(gl_FragDepthEXT); \n" +
          "#else\n" +
          "    gl_FragData[1] = czm_packDepth(gl_FragCoord.z);\n" +
          "#endif\n" +
          "}"
      );

      shader = context.shaderCache.createDerivedShaderProgram(
        shaderProgram,
        "EC",
        {
          vertexShaderSource: shaderProgram.vertexShaderSource,
          fragmentShaderSource: fs,
          attributeLocations: attributeLocations,
        }
      );
    }

    return shader;
  }

  PointCloudEyeDomeLighting.prototype.update = function (
    frameState,
    commandStart,
    pointCloudShading,
    boundingVolume
  ) {
    if (!isSupported(frameState.context)) {
      return;
    }

    this._strength = pointCloudShading.eyeDomeLightingStrength;
    this._radius =
      pointCloudShading.eyeDomeLightingRadius * frameState.pixelRatio;

    createResources$2(this, frameState.context);

    // Hijack existing point commands to render into an offscreen FBO.
    let i;
    const commandList = frameState.commandList;
    const commandEnd = commandList.length;

    for (i = commandStart; i < commandEnd; ++i) {
      const command = commandList[i];
      if (
        command.primitiveType !== PrimitiveType$1.POINTS ||
        command.pass === Pass$1.TRANSLUCENT
      ) {
        continue;
      }

      let derivedCommand;
      let originalShaderProgram;

      let derivedCommandObject = command.derivedCommands.pointCloudProcessor;
      if (defined(derivedCommandObject)) {
        derivedCommand = derivedCommandObject.command;
        originalShaderProgram = derivedCommandObject.originalShaderProgram;
      }

      if (
        !defined(derivedCommand) ||
        command.dirty ||
        originalShaderProgram !== command.shaderProgram ||
        derivedCommand.framebuffer !== this.framebuffer
      ) {
        // Prevent crash when tiles out-of-view come in-view during context size change or
        // when the underlying shader changes while EDL is disabled
        derivedCommand = DrawCommand.shallowClone(command, derivedCommand);
        derivedCommand.framebuffer = this.framebuffer;
        derivedCommand.shaderProgram = getECShaderProgram(
          frameState.context,
          command.shaderProgram
        );
        derivedCommand.castShadows = false;
        derivedCommand.receiveShadows = false;

        if (!defined(derivedCommandObject)) {
          derivedCommandObject = {
            command: derivedCommand,
            originalShaderProgram: command.shaderProgram,
          };
          command.derivedCommands.pointCloudProcessor = derivedCommandObject;
        }

        derivedCommandObject.originalShaderProgram = command.shaderProgram;
      }

      commandList[i] = derivedCommand;
    }

    const clearCommand = this._clearCommand;
    const blendCommand = this._drawCommand;

    blendCommand.boundingVolume = boundingVolume;

    // Blend EDL into the main FBO
    commandList.push(blendCommand);
    commandList.push(clearCommand);
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see PointCloudEyeDomeLighting#destroy
   */
  PointCloudEyeDomeLighting.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @example
   * processor = processor && processor.destroy();
   *
   * @see PointCloudEyeDomeLighting#isDestroyed
   */
  PointCloudEyeDomeLighting.prototype.destroy = function () {
    destroyFramebuffer$1(this);
    return destroyObject(this);
  };

  /**
   * Options for performing point attenuation based on geometric error when rendering
   * point clouds using 3D Tiles.
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Boolean} [options.attenuation=false] Perform point attenuation based on geometric error.
   * @param {Number} [options.geometricErrorScale=1.0] Scale to be applied to each tile's geometric error.
   * @param {Number} [options.maximumAttenuation] Maximum attenuation in pixels. Defaults to the Cesium3DTileset's maximumScreenSpaceError.
   * @param {Number} [options.baseResolution] Average base resolution for the dataset in meters. Substitute for Geometric Error when not available.
   * @param {Boolean} [options.eyeDomeLighting=true] When true, use eye dome lighting when drawing with point attenuation.
   * @param {Number} [options.eyeDomeLightingStrength=1.0] Increasing this value increases contrast on slopes and edges.
   * @param {Number} [options.eyeDomeLightingRadius=1.0] Increase the thickness of contours from eye dome lighting.
   * @param {Boolean} [options.backFaceCulling=false] Determines whether back-facing points are hidden. This option works only if data has normals included.
   * @param {Boolean} [options.normalShading=true] Determines whether a point cloud that contains normals is shaded by the scene's light source.
   *
   * @alias PointCloudShading
   * @constructor
   */
  function PointCloudShading(options) {
    const pointCloudShading = defaultValue(options, {});

    /**
     * Perform point attenuation based on geometric error.
     * @type {Boolean}
     * @default false
     */
    this.attenuation = defaultValue(pointCloudShading.attenuation, false);

    /**
     * Scale to be applied to the geometric error before computing attenuation.
     * @type {Number}
     * @default 1.0
     */
    this.geometricErrorScale = defaultValue(
      pointCloudShading.geometricErrorScale,
      1.0
    );

    /**
     * Maximum point attenuation in pixels. If undefined, the Cesium3DTileset's maximumScreenSpaceError will be used.
     * @type {Number}
     */
    this.maximumAttenuation = pointCloudShading.maximumAttenuation;

    /**
     * Average base resolution for the dataset in meters.
     * Used in place of geometric error when geometric error is 0.
     * If undefined, an approximation will be computed for each tile that has geometric error of 0.
     * @type {Number}
     */
    this.baseResolution = pointCloudShading.baseResolution;

    /**
     * Use eye dome lighting when drawing with point attenuation
     * Requires support for EXT_frag_depth, OES_texture_float, and WEBGL_draw_buffers extensions in WebGL 1.0,
     * otherwise eye dome lighting is ignored.
     *
     * @type {Boolean}
     * @default true
     */
    this.eyeDomeLighting = defaultValue(pointCloudShading.eyeDomeLighting, true);

    /**
     * Eye dome lighting strength (apparent contrast)
     * @type {Number}
     * @default 1.0
     */
    this.eyeDomeLightingStrength = defaultValue(
      pointCloudShading.eyeDomeLightingStrength,
      1.0
    );

    /**
     * Thickness of contours from eye dome lighting
     * @type {Number}
     * @default 1.0
     */
    this.eyeDomeLightingRadius = defaultValue(
      pointCloudShading.eyeDomeLightingRadius,
      1.0
    );

    /**
     * Determines whether back-facing points are hidden.
     * This option works only if data has normals included.
     *
     * @type {Boolean}
     * @default false
     */
    this.backFaceCulling = defaultValue(pointCloudShading.backFaceCulling, false);

    /**
     * Determines whether a point cloud that contains normals is shaded by the scene's light source.
     *
     * @type {Boolean}
     * @default true
     */
    this.normalShading = defaultValue(pointCloudShading.normalShading, true);
  }

  /**
   * Determines if point cloud shading is supported.
   *
   * @param {Scene} scene The scene.
   * @returns {Boolean} <code>true</code> if point cloud shading is supported; otherwise, returns <code>false</code>
   */
  PointCloudShading.isSupported = function (scene) {
    return PointCloudEyeDomeLighting.isSupported(scene.context);
  };

  /**
   * Represents the contents of a
   * {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/TileFormats/PointCloud|Point Cloud}
   * tile in a {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification|3D Tiles} tileset.
   * <p>
   * Implements the {@link Cesium3DTileContent} interface.
   * </p>
   *
   * @alias PointCloud3DTileContent
   * @constructor
   *
   * @private
   */
  function PointCloud3DTileContent(
    tileset,
    tile,
    resource,
    arrayBuffer,
    byteOffset
  ) {
    this._tileset = tileset;
    this._tile = tile;
    this._resource = resource;

    this._metadata = undefined;

    this._pickId = undefined; // Only defined when batchTable is undefined
    this._batchTable = undefined; // Used when feature table contains BATCH_ID semantic
    this._styleDirty = false;
    this._features = undefined;
    this.featurePropertiesDirty = false;
    this._group = undefined;

    this._pointCloud = new PointCloud({
      arrayBuffer: arrayBuffer,
      byteOffset: byteOffset,
      cull: false,
      opaquePass: Pass$1.CESIUM_3D_TILE,
      vertexShaderLoaded: getVertexShaderLoaded(this),
      fragmentShaderLoaded: getFragmentShaderLoaded$1(this),
      uniformMapLoaded: getUniformMapLoaded$1(this),
      batchTableLoaded: getBatchTableLoaded(this),
      pickIdLoaded: getPickIdLoaded$1(this),
    });
  }

  Object.defineProperties(PointCloud3DTileContent.prototype, {
    featuresLength: {
      get: function () {
        if (defined(this._batchTable)) {
          return this._batchTable.featuresLength;
        }
        return 0;
      },
    },

    pointsLength: {
      get: function () {
        return this._pointCloud.pointsLength;
      },
    },

    trianglesLength: {
      get: function () {
        return 0;
      },
    },

    geometryByteLength: {
      get: function () {
        return this._pointCloud.geometryByteLength;
      },
    },

    texturesByteLength: {
      get: function () {
        return 0;
      },
    },

    batchTableByteLength: {
      get: function () {
        if (defined(this._batchTable)) {
          return this._batchTable.batchTableByteLength;
        }
        return 0;
      },
    },

    innerContents: {
      get: function () {
        return undefined;
      },
    },

    readyPromise: {
      get: function () {
        return this._pointCloud.readyPromise;
      },
    },

    tileset: {
      get: function () {
        return this._tileset;
      },
    },

    tile: {
      get: function () {
        return this._tile;
      },
    },

    url: {
      get: function () {
        return this._resource.getUrlComponent(true);
      },
    },

    metadata: {
      get: function () {
        return this._metadata;
      },
      set: function (value) {
        this._metadata = value;
      },
    },

    batchTable: {
      get: function () {
        return this._batchTable;
      },
    },

    group: {
      get: function () {
        return this._group;
      },
      set: function (value) {
        this._group = value;
      },
    },
  });

  function getVertexShaderLoaded(content) {
    return function (vs) {
      if (defined(content._batchTable)) {
        return content._batchTable.getVertexShaderCallback(
          false,
          "a_batchId",
          undefined
        )(vs);
      }
      return vs;
    };
  }

  function getFragmentShaderLoaded$1(content) {
    return function (fs) {
      if (defined(content._batchTable)) {
        return content._batchTable.getFragmentShaderCallback(
          false,
          undefined,
          false
        )(fs);
      }
      return `uniform vec4 czm_pickColor;\n${fs}`;
    };
  }

  function getUniformMapLoaded$1(content) {
    return function (uniformMap) {
      if (defined(content._batchTable)) {
        return content._batchTable.getUniformMapCallback()(uniformMap);
      }
      return combine$2(uniformMap, {
        czm_pickColor: function () {
          return content._pickId.color;
        },
      });
    };
  }

  function getBatchTableLoaded(content) {
    return function (batchLength, batchTableJson, batchTableBinary) {
      content._batchTable = new Cesium3DTileBatchTable(
        content,
        batchLength,
        batchTableJson,
        batchTableBinary
      );
    };
  }

  function getPickIdLoaded$1(content) {
    return function () {
      return defined(content._batchTable)
        ? content._batchTable.getPickId()
        : "czm_pickColor";
    };
  }

  function getGeometricError$2(content) {
    const pointCloudShading = content._tileset.pointCloudShading;
    const sphereVolume = content._tile.contentBoundingVolume.boundingSphere.volume();
    const baseResolutionApproximation = CesiumMath.cbrt(
      sphereVolume / content.pointsLength
    );

    let geometricError = content._tile.geometricError;
    if (geometricError === 0) {
      if (
        defined(pointCloudShading) &&
        defined(pointCloudShading.baseResolution)
      ) {
        geometricError = pointCloudShading.baseResolution;
      } else {
        geometricError = baseResolutionApproximation;
      }
    }
    return geometricError;
  }

  function createFeatures$1(content) {
    const featuresLength = content.featuresLength;
    if (!defined(content._features) && featuresLength > 0) {
      const features = new Array(featuresLength);
      for (let i = 0; i < featuresLength; ++i) {
        features[i] = new Cesium3DTileFeature(content, i);
      }
      content._features = features;
    }
  }

  PointCloud3DTileContent.prototype.hasProperty = function (batchId, name) {
    if (defined(this._batchTable)) {
      return this._batchTable.hasProperty(batchId, name);
    }
    return false;
  };

  /**
   * Part of the {@link Cesium3DTileContent} interface.
   *
   * In this context a feature refers to a group of points that share the same BATCH_ID.
   * For example all the points that represent a door in a house point cloud would be a feature.
   *
   * Features are backed by a batch table and can be colored, shown/hidden, picked, etc like features
   * in b3dm and i3dm.
   *
   * When the BATCH_ID semantic is omitted and the point cloud stores per-point properties, they
   * are not accessible by getFeature. They are only used for dynamic styling.
   */
  PointCloud3DTileContent.prototype.getFeature = function (batchId) {
    if (!defined(this._batchTable)) {
      return undefined;
    }
    const featuresLength = this.featuresLength;
    //>>includeStart('debug', pragmas.debug);
    if (!defined(batchId) || batchId < 0 || batchId >= featuresLength) {
      throw new DeveloperError(
        `batchId is required and between zero and featuresLength - 1 (${
        featuresLength - 1
      }).`
      );
    }
    //>>includeEnd('debug');
    createFeatures$1(this);
    return this._features[batchId];
  };

  PointCloud3DTileContent.prototype.applyDebugSettings = function (
    enabled,
    color
  ) {
    this._pointCloud.color = enabled ? color : Color.WHITE;
  };

  PointCloud3DTileContent.prototype.applyStyle = function (style) {
    if (defined(this._batchTable)) {
      this._batchTable.applyStyle(style);
    } else {
      this._styleDirty = true;
    }
  };

  const defaultShading$1 = new PointCloudShading();

  PointCloud3DTileContent.prototype.update = function (tileset, frameState) {
    const pointCloud = this._pointCloud;
    const pointCloudShading = defaultValue(
      tileset.pointCloudShading,
      defaultShading$1
    );
    const tile = this._tile;
    const batchTable = this._batchTable;
    const mode = frameState.mode;
    const clippingPlanes = tileset.clippingPlanes;

    if (!defined(this._pickId) && !defined(batchTable)) {
      this._pickId = frameState.context.createPickId({
        primitive: tileset,
        content: this,
      });
    }

    if (defined(batchTable)) {
      batchTable.update(tileset, frameState);
    }

    let boundingSphere;
    if (defined(tile._contentBoundingVolume)) {
      boundingSphere =
        mode === SceneMode$1.SCENE3D
          ? tile._contentBoundingVolume.boundingSphere
          : tile._contentBoundingVolume2D.boundingSphere;
    } else {
      boundingSphere =
        mode === SceneMode$1.SCENE3D
          ? tile._boundingVolume.boundingSphere
          : tile._boundingVolume2D.boundingSphere;
    }

    const styleDirty = this._styleDirty;
    this._styleDirty = false;

    pointCloud.clippingPlanesOriginMatrix = tileset.clippingPlanesOriginMatrix;
    pointCloud.style = defined(batchTable) ? undefined : tileset.style;
    pointCloud.styleDirty = styleDirty;
    pointCloud.modelMatrix = tile.computedTransform;
    pointCloud.time = tileset.timeSinceLoad;
    pointCloud.shadows = tileset.shadows;
    pointCloud.boundingSphere = boundingSphere;
    pointCloud.clippingPlanes = clippingPlanes;
    pointCloud.isClipped =
      defined(clippingPlanes) && clippingPlanes.enabled && tile._isClipped;
    pointCloud.clippingPlanesDirty = tile.clippingPlanesDirty;
    pointCloud.attenuation = pointCloudShading.attenuation;
    pointCloud.backFaceCulling = pointCloudShading.backFaceCulling;
    pointCloud.normalShading = pointCloudShading.normalShading;
    pointCloud.geometricError = getGeometricError$2(this);
    pointCloud.geometricErrorScale = pointCloudShading.geometricErrorScale;
    pointCloud.splitDirection = tileset.splitDirection;
    if (
      defined(pointCloudShading) &&
      defined(pointCloudShading.maximumAttenuation)
    ) {
      pointCloud.maximumAttenuation = pointCloudShading.maximumAttenuation;
    } else if (tile.refine === Cesium3DTileRefine$1.ADD) {
      pointCloud.maximumAttenuation = 5.0;
    } else {
      pointCloud.maximumAttenuation = tileset.maximumScreenSpaceError;
    }

    pointCloud.update(frameState);
  };

  PointCloud3DTileContent.prototype.isDestroyed = function () {
    return false;
  };

  PointCloud3DTileContent.prototype.destroy = function () {
    this._pickId = this._pickId && this._pickId.destroy();
    this._pointCloud = this._pointCloud && this._pointCloud.destroy();
    this._batchTable = this._batchTable && this._batchTable.destroy();
    return destroyObject(this);
  };

  /**
   * Represents content for a tile in a
   * {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification|3D Tiles} tileset whose
   * content points to another 3D Tiles tileset.
   * <p>
   * Implements the {@link Cesium3DTileContent} interface.
   * </p>
   *
   * @alias Tileset3DTileContent
   * @constructor
   *
   * @private
   */
  function Tileset3DTileContent(tileset, tile, resource, json) {
    this._tileset = tileset;
    this._tile = tile;
    this._resource = resource;

    this.featurePropertiesDirty = false;

    this._metadata = undefined;
    this._group = undefined;

    this._readyPromise = initialize$e(this, json);
  }

  Object.defineProperties(Tileset3DTileContent.prototype, {
    featuresLength: {
      get: function () {
        return 0;
      },
    },

    pointsLength: {
      get: function () {
        return 0;
      },
    },

    trianglesLength: {
      get: function () {
        return 0;
      },
    },

    geometryByteLength: {
      get: function () {
        return 0;
      },
    },

    texturesByteLength: {
      get: function () {
        return 0;
      },
    },

    batchTableByteLength: {
      get: function () {
        return 0;
      },
    },

    innerContents: {
      get: function () {
        return undefined;
      },
    },

    readyPromise: {
      get: function () {
        return this._readyPromise;
      },
    },

    tileset: {
      get: function () {
        return this._tileset;
      },
    },

    tile: {
      get: function () {
        return this._tile;
      },
    },

    url: {
      get: function () {
        return this._resource.getUrlComponent(true);
      },
    },

    batchTable: {
      get: function () {
        return undefined;
      },
    },

    metadata: {
      get: function () {
        return this._metadata;
      },
      set: function (value) {
        this._metadata = value;
      },
    },

    group: {
      get: function () {
        return this._group;
      },
      set: function (value) {
        this._group = value;
      },
    },
  });

  function initialize$e(content, json) {
    content._tileset.loadTileset(content._resource, json, content._tile);
    return Promise.resolve(content);
  }

  /**
   * Part of the {@link Cesium3DTileContent} interface.  <code>Tileset3DTileContent</code>
   * always returns <code>false</code> since a tile of this type does not have any features.
   */
  Tileset3DTileContent.prototype.hasProperty = function (batchId, name) {
    return false;
  };

  /**
   * Part of the {@link Cesium3DTileContent} interface.  <code>Tileset3DTileContent</code>
   * always returns <code>undefined</code> since a tile of this type does not have any features.
   */
  Tileset3DTileContent.prototype.getFeature = function (batchId) {
    return undefined;
  };

  Tileset3DTileContent.prototype.applyDebugSettings = function (
    enabled,
    color
  ) {};

  Tileset3DTileContent.prototype.applyStyle = function (style) {};

  Tileset3DTileContent.prototype.update = function (tileset, frameState) {};

  Tileset3DTileContent.prototype.isDestroyed = function () {
    return false;
  };

  Tileset3DTileContent.prototype.destroy = function () {
    return destroyObject(this);
  };

  /**
   * @private
   */
  function VertexArrayFacade(context, attributes, sizeInVertices, instanced) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("context", context);
    if (!attributes || attributes.length === 0) {
      throw new DeveloperError("At least one attribute is required.");
    }
    //>>includeEnd('debug');

    const attrs = VertexArrayFacade._verifyAttributes(attributes);
    sizeInVertices = defaultValue(sizeInVertices, 0);
    const precreatedAttributes = [];
    const attributesByUsage = {};
    let attributesForUsage;
    let usage;

    // Bucket the attributes by usage.
    const length = attrs.length;
    for (let i = 0; i < length; ++i) {
      const attribute = attrs[i];

      // If the attribute already has a vertex buffer, we do not need
      // to manage a vertex buffer or typed array for it.
      if (attribute.vertexBuffer) {
        precreatedAttributes.push(attribute);
        continue;
      }

      usage = attribute.usage;
      attributesForUsage = attributesByUsage[usage];
      if (!defined(attributesForUsage)) {
        attributesForUsage = attributesByUsage[usage] = [];
      }

      attributesForUsage.push(attribute);
    }

    // A function to sort attributes by the size of their components.  From left to right, a vertex
    // stores floats, shorts, and then bytes.
    function compare(left, right) {
      return (
        ComponentDatatype$1.getSizeInBytes(right.componentDatatype) -
        ComponentDatatype$1.getSizeInBytes(left.componentDatatype)
      );
    }

    this._allBuffers = [];

    for (usage in attributesByUsage) {
      if (attributesByUsage.hasOwnProperty(usage)) {
        attributesForUsage = attributesByUsage[usage];

        attributesForUsage.sort(compare);
        const vertexSizeInBytes = VertexArrayFacade._vertexSizeInBytes(
          attributesForUsage
        );

        const bufferUsage = attributesForUsage[0].usage;

        const buffer = {
          vertexSizeInBytes: vertexSizeInBytes,
          vertexBuffer: undefined,
          usage: bufferUsage,
          needsCommit: false,
          arrayBuffer: undefined,
          arrayViews: VertexArrayFacade._createArrayViews(
            attributesForUsage,
            vertexSizeInBytes
          ),
        };

        this._allBuffers.push(buffer);
      }
    }

    this._size = 0;
    this._instanced = defaultValue(instanced, false);

    this._precreated = precreatedAttributes;
    this._context = context;

    this.writers = undefined;
    this.va = undefined;

    this.resize(sizeInVertices);
  }
  VertexArrayFacade._verifyAttributes = function (attributes) {
    const attrs = [];

    for (let i = 0; i < attributes.length; ++i) {
      const attribute = attributes[i];

      const attr = {
        index: defaultValue(attribute.index, i),
        enabled: defaultValue(attribute.enabled, true),
        componentsPerAttribute: attribute.componentsPerAttribute,
        componentDatatype: defaultValue(
          attribute.componentDatatype,
          ComponentDatatype$1.FLOAT
        ),
        normalize: defaultValue(attribute.normalize, false),

        // There will be either a vertexBuffer or an [optional] usage.
        vertexBuffer: attribute.vertexBuffer,
        usage: defaultValue(attribute.usage, BufferUsage$1.STATIC_DRAW),
      };
      attrs.push(attr);

      //>>includeStart('debug', pragmas.debug);
      if (
        attr.componentsPerAttribute !== 1 &&
        attr.componentsPerAttribute !== 2 &&
        attr.componentsPerAttribute !== 3 &&
        attr.componentsPerAttribute !== 4
      ) {
        throw new DeveloperError(
          "attribute.componentsPerAttribute must be in the range [1, 4]."
        );
      }

      const datatype = attr.componentDatatype;
      if (!ComponentDatatype$1.validate(datatype)) {
        throw new DeveloperError(
          "Attribute must have a valid componentDatatype or not specify it."
        );
      }

      if (!BufferUsage$1.validate(attr.usage)) {
        throw new DeveloperError(
          "Attribute must have a valid usage or not specify it."
        );
      }
      //>>includeEnd('debug');
    }

    // Verify all attribute names are unique.
    const uniqueIndices = new Array(attrs.length);
    for (let j = 0; j < attrs.length; ++j) {
      const currentAttr = attrs[j];
      const index = currentAttr.index;
      //>>includeStart('debug', pragmas.debug);
      if (uniqueIndices[index]) {
        throw new DeveloperError(
          `Index ${index} is used by more than one attribute.`
        );
      }
      //>>includeEnd('debug');
      uniqueIndices[index] = true;
    }

    return attrs;
  };

  VertexArrayFacade._vertexSizeInBytes = function (attributes) {
    let sizeInBytes = 0;

    const length = attributes.length;
    for (let i = 0; i < length; ++i) {
      const attribute = attributes[i];
      sizeInBytes +=
        attribute.componentsPerAttribute *
        ComponentDatatype$1.getSizeInBytes(attribute.componentDatatype);
    }

    const maxComponentSizeInBytes =
      length > 0
        ? ComponentDatatype$1.getSizeInBytes(attributes[0].componentDatatype)
        : 0; // Sorted by size
    const remainder =
      maxComponentSizeInBytes > 0 ? sizeInBytes % maxComponentSizeInBytes : 0;
    const padding = remainder === 0 ? 0 : maxComponentSizeInBytes - remainder;
    sizeInBytes += padding;

    return sizeInBytes;
  };

  VertexArrayFacade._createArrayViews = function (attributes, vertexSizeInBytes) {
    const views = [];
    let offsetInBytes = 0;

    const length = attributes.length;
    for (let i = 0; i < length; ++i) {
      const attribute = attributes[i];
      const componentDatatype = attribute.componentDatatype;

      views.push({
        index: attribute.index,
        enabled: attribute.enabled,
        componentsPerAttribute: attribute.componentsPerAttribute,
        componentDatatype: componentDatatype,
        normalize: attribute.normalize,

        offsetInBytes: offsetInBytes,
        vertexSizeInComponentType:
          vertexSizeInBytes / ComponentDatatype$1.getSizeInBytes(componentDatatype),

        view: undefined,
      });

      offsetInBytes +=
        attribute.componentsPerAttribute *
        ComponentDatatype$1.getSizeInBytes(componentDatatype);
    }

    return views;
  };

  /**
   * Invalidates writers.  Can't render again until commit is called.
   */
  VertexArrayFacade.prototype.resize = function (sizeInVertices) {
    this._size = sizeInVertices;

    const allBuffers = this._allBuffers;
    this.writers = [];

    for (let i = 0, len = allBuffers.length; i < len; ++i) {
      const buffer = allBuffers[i];

      VertexArrayFacade._resize(buffer, this._size);

      // Reserving invalidates the writers, so if client's cache them, they need to invalidate their cache.
      VertexArrayFacade._appendWriters(this.writers, buffer);
    }

    // VAs are recreated next time commit is called.
    destroyVA(this);
  };

  VertexArrayFacade._resize = function (buffer, size) {
    if (buffer.vertexSizeInBytes > 0) {
      // Create larger array buffer
      const arrayBuffer = new ArrayBuffer(size * buffer.vertexSizeInBytes);

      // Copy contents from previous array buffer
      if (defined(buffer.arrayBuffer)) {
        const destView = new Uint8Array(arrayBuffer);
        const sourceView = new Uint8Array(buffer.arrayBuffer);
        const sourceLength = sourceView.length;
        for (let j = 0; j < sourceLength; ++j) {
          destView[j] = sourceView[j];
        }
      }

      // Create typed views into the new array buffer
      const views = buffer.arrayViews;
      const length = views.length;
      for (let i = 0; i < length; ++i) {
        const view = views[i];
        view.view = ComponentDatatype$1.createArrayBufferView(
          view.componentDatatype,
          arrayBuffer,
          view.offsetInBytes
        );
      }

      buffer.arrayBuffer = arrayBuffer;
    }
  };

  const createWriters = [
    // 1 component per attribute
    function (buffer, view, vertexSizeInComponentType) {
      return function (index, attribute) {
        view[index * vertexSizeInComponentType] = attribute;
        buffer.needsCommit = true;
      };
    },

    // 2 component per attribute
    function (buffer, view, vertexSizeInComponentType) {
      return function (index, component0, component1) {
        const i = index * vertexSizeInComponentType;
        view[i] = component0;
        view[i + 1] = component1;
        buffer.needsCommit = true;
      };
    },

    // 3 component per attribute
    function (buffer, view, vertexSizeInComponentType) {
      return function (index, component0, component1, component2) {
        const i = index * vertexSizeInComponentType;
        view[i] = component0;
        view[i + 1] = component1;
        view[i + 2] = component2;
        buffer.needsCommit = true;
      };
    },

    // 4 component per attribute
    function (buffer, view, vertexSizeInComponentType) {
      return function (index, component0, component1, component2, component3) {
        const i = index * vertexSizeInComponentType;
        view[i] = component0;
        view[i + 1] = component1;
        view[i + 2] = component2;
        view[i + 3] = component3;
        buffer.needsCommit = true;
      };
    },
  ];

  VertexArrayFacade._appendWriters = function (writers, buffer) {
    const arrayViews = buffer.arrayViews;
    const length = arrayViews.length;
    for (let i = 0; i < length; ++i) {
      const arrayView = arrayViews[i];
      writers[arrayView.index] = createWriters[
        arrayView.componentsPerAttribute - 1
      ](buffer, arrayView.view, arrayView.vertexSizeInComponentType);
    }
  };

  VertexArrayFacade.prototype.commit = function (indexBuffer) {
    let recreateVA = false;

    const allBuffers = this._allBuffers;
    let buffer;
    let i;
    let length;

    for (i = 0, length = allBuffers.length; i < length; ++i) {
      buffer = allBuffers[i];
      recreateVA = commit(this, buffer) || recreateVA;
    }

    ///////////////////////////////////////////////////////////////////////

    if (recreateVA || !defined(this.va)) {
      destroyVA(this);
      const va = (this.va = []);

      const chunkSize = CesiumMath.SIXTY_FOUR_KILOBYTES - 4; // The 65535 index is reserved for primitive restart. Reserve the last 4 indices so that billboard quads are not broken up.
      const numberOfVertexArrays =
        defined(indexBuffer) && !this._instanced
          ? Math.ceil(this._size / chunkSize)
          : 1;
      for (let k = 0; k < numberOfVertexArrays; ++k) {
        let attributes = [];
        for (i = 0, length = allBuffers.length; i < length; ++i) {
          buffer = allBuffers[i];
          const offset = k * (buffer.vertexSizeInBytes * chunkSize);
          VertexArrayFacade._appendAttributes(
            attributes,
            buffer,
            offset,
            this._instanced
          );
        }

        attributes = attributes.concat(this._precreated);

        va.push({
          va: new VertexArray({
            context: this._context,
            attributes: attributes,
            indexBuffer: indexBuffer,
          }),
          indicesCount:
            1.5 *
            (k !== numberOfVertexArrays - 1 ? chunkSize : this._size % chunkSize),
          // TODO: not hardcode 1.5, this assumes 6 indices per 4 vertices (as for Billboard quads).
        });
      }
    }
  };

  function commit(vertexArrayFacade, buffer) {
    if (buffer.needsCommit && buffer.vertexSizeInBytes > 0) {
      buffer.needsCommit = false;

      const vertexBuffer = buffer.vertexBuffer;
      const vertexBufferSizeInBytes =
        vertexArrayFacade._size * buffer.vertexSizeInBytes;
      const vertexBufferDefined = defined(vertexBuffer);
      if (
        !vertexBufferDefined ||
        vertexBuffer.sizeInBytes < vertexBufferSizeInBytes
      ) {
        if (vertexBufferDefined) {
          vertexBuffer.destroy();
        }
        buffer.vertexBuffer = Buffer$1.createVertexBuffer({
          context: vertexArrayFacade._context,
          typedArray: buffer.arrayBuffer,
          usage: buffer.usage,
        });
        buffer.vertexBuffer.vertexArrayDestroyable = false;

        return true; // Created new vertex buffer
      }

      buffer.vertexBuffer.copyFromArrayView(buffer.arrayBuffer);
    }

    return false; // Did not create new vertex buffer
  }

  VertexArrayFacade._appendAttributes = function (
    attributes,
    buffer,
    vertexBufferOffset,
    instanced
  ) {
    const arrayViews = buffer.arrayViews;
    const length = arrayViews.length;
    for (let i = 0; i < length; ++i) {
      const view = arrayViews[i];

      attributes.push({
        index: view.index,
        enabled: view.enabled,
        componentsPerAttribute: view.componentsPerAttribute,
        componentDatatype: view.componentDatatype,
        normalize: view.normalize,
        vertexBuffer: buffer.vertexBuffer,
        offsetInBytes: vertexBufferOffset + view.offsetInBytes,
        strideInBytes: buffer.vertexSizeInBytes,
        instanceDivisor: instanced ? 1 : 0,
      });
    }
  };

  VertexArrayFacade.prototype.subCommit = function (
    offsetInVertices,
    lengthInVertices
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (offsetInVertices < 0 || offsetInVertices >= this._size) {
      throw new DeveloperError(
        "offsetInVertices must be greater than or equal to zero and less than the vertex array size."
      );
    }
    if (offsetInVertices + lengthInVertices > this._size) {
      throw new DeveloperError(
        "offsetInVertices + lengthInVertices cannot exceed the vertex array size."
      );
    }
    //>>includeEnd('debug');

    const allBuffers = this._allBuffers;
    for (let i = 0, len = allBuffers.length; i < len; ++i) {
      subCommit(allBuffers[i], offsetInVertices, lengthInVertices);
    }
  };

  function subCommit(buffer, offsetInVertices, lengthInVertices) {
    if (buffer.needsCommit && buffer.vertexSizeInBytes > 0) {
      const byteOffset = buffer.vertexSizeInBytes * offsetInVertices;
      const byteLength = buffer.vertexSizeInBytes * lengthInVertices;

      // PERFORMANCE_IDEA: If we want to get really crazy, we could consider updating
      // individual attributes instead of the entire (sub-)vertex.
      //
      // PERFORMANCE_IDEA: Does creating the typed view add too much GC overhead?
      buffer.vertexBuffer.copyFromArrayView(
        new Uint8Array(buffer.arrayBuffer, byteOffset, byteLength),
        byteOffset
      );
    }
  }

  VertexArrayFacade.prototype.endSubCommits = function () {
    const allBuffers = this._allBuffers;

    for (let i = 0, len = allBuffers.length; i < len; ++i) {
      allBuffers[i].needsCommit = false;
    }
  };

  function destroyVA(vertexArrayFacade) {
    const va = vertexArrayFacade.va;
    if (!defined(va)) {
      return;
    }

    const length = va.length;
    for (let i = 0; i < length; ++i) {
      va[i].va.destroy();
    }

    vertexArrayFacade.va = undefined;
  }

  VertexArrayFacade.prototype.isDestroyed = function () {
    return false;
  };

  VertexArrayFacade.prototype.destroy = function () {
    const allBuffers = this._allBuffers;
    for (let i = 0, len = allBuffers.length; i < len; ++i) {
      const buffer = allBuffers[i];
      buffer.vertexBuffer = buffer.vertexBuffer && buffer.vertexBuffer.destroy();
    }

    destroyVA(this);

    return destroyObject(this);
  };

  //This file is automatically rebuilt by the Cesium build process.
  var BillboardCollectionFS = "#ifdef GL_OES_standard_derivatives\n\
#extension GL_OES_standard_derivatives : enable\n\
#endif\n\
uniform sampler2D u_atlas;\n\
#ifdef VECTOR_TILE\n\
uniform vec4 u_highlightColor;\n\
#endif\n\
varying vec2 v_textureCoordinates;\n\
varying vec4 v_pickColor;\n\
varying vec4 v_color;\n\
#ifdef SDF\n\
varying vec4 v_outlineColor;\n\
varying float v_outlineWidth;\n\
#endif\n\
#ifdef FRAGMENT_DEPTH_CHECK\n\
varying vec4 v_textureCoordinateBounds;\n\
varying vec4 v_originTextureCoordinateAndTranslate;\n\
varying vec4 v_compressed;\n\
varying mat2 v_rotationMatrix;\n\
const float SHIFT_LEFT12 = 4096.0;\n\
const float SHIFT_LEFT1 = 2.0;\n\
const float SHIFT_RIGHT12 = 1.0 / 4096.0;\n\
const float SHIFT_RIGHT1 = 1.0 / 2.0;\n\
float getGlobeDepth(vec2 adjustedST, vec2 depthLookupST, bool applyTranslate, vec2 dimensions, vec2 imageSize)\n\
{\n\
vec2 lookupVector = imageSize * (depthLookupST - adjustedST);\n\
lookupVector = v_rotationMatrix * lookupVector;\n\
vec2 labelOffset = (dimensions - imageSize) * (depthLookupST - vec2(0.0, v_originTextureCoordinateAndTranslate.y));\n\
vec2 translation = v_originTextureCoordinateAndTranslate.zw;\n\
if (applyTranslate)\n\
{\n\
translation += (dimensions * v_originTextureCoordinateAndTranslate.xy * vec2(1.0, 0.0));\n\
}\n\
vec2 st = ((lookupVector - translation + labelOffset) + gl_FragCoord.xy) / czm_viewport.zw;\n\
float logDepthOrDepth = czm_unpackDepth(texture2D(czm_globeDepthTexture, st));\n\
if (logDepthOrDepth == 0.0)\n\
{\n\
return 0.0;\n\
}\n\
vec4 eyeCoordinate = czm_windowToEyeCoordinates(gl_FragCoord.xy, logDepthOrDepth);\n\
return eyeCoordinate.z / eyeCoordinate.w;\n\
}\n\
#endif\n\
#ifdef SDF\n\
float getDistance(vec2 position)\n\
{\n\
return texture2D(u_atlas, position).r;\n\
}\n\
vec4 getSDFColor(vec2 position, float outlineWidth, vec4 outlineColor, float smoothing)\n\
{\n\
float distance = getDistance(position);\n\
if (outlineWidth > 0.0)\n\
{\n\
float outlineEdge = clamp(SDF_EDGE - outlineWidth, 0.0, SDF_EDGE);\n\
float outlineFactor = smoothstep(SDF_EDGE - smoothing, SDF_EDGE + smoothing, distance);\n\
vec4 sdfColor = mix(outlineColor, v_color, outlineFactor);\n\
float alpha = smoothstep(outlineEdge - smoothing, outlineEdge + smoothing, distance);\n\
return vec4(sdfColor.rgb, sdfColor.a * alpha);\n\
}\n\
else\n\
{\n\
float alpha = smoothstep(SDF_EDGE - smoothing, SDF_EDGE + smoothing, distance);\n\
return vec4(v_color.rgb, v_color.a * alpha);\n\
}\n\
}\n\
#endif\n\
void main()\n\
{\n\
vec4 color = texture2D(u_atlas, v_textureCoordinates);\n\
#ifdef SDF\n\
float outlineWidth = v_outlineWidth;\n\
vec4 outlineColor = v_outlineColor;\n\
float distance = getDistance(v_textureCoordinates);\n\
#ifdef GL_OES_standard_derivatives\n\
float smoothing = fwidth(distance);\n\
vec2 sampleOffset = 0.354 * vec2(dFdx(v_textureCoordinates) + dFdy(v_textureCoordinates));\n\
vec4 center = getSDFColor(v_textureCoordinates, outlineWidth, outlineColor, smoothing);\n\
vec4 color1 = getSDFColor(v_textureCoordinates + vec2(sampleOffset.x, sampleOffset.y), outlineWidth, outlineColor, smoothing);\n\
vec4 color2 = getSDFColor(v_textureCoordinates + vec2(-sampleOffset.x, sampleOffset.y), outlineWidth, outlineColor, smoothing);\n\
vec4 color3 = getSDFColor(v_textureCoordinates + vec2(-sampleOffset.x, -sampleOffset.y), outlineWidth, outlineColor, smoothing);\n\
vec4 color4 = getSDFColor(v_textureCoordinates + vec2(sampleOffset.x, -sampleOffset.y), outlineWidth, outlineColor, smoothing);\n\
color = (center + color1 + color2 + color3 + color4)/5.0;\n\
#else\n\
float smoothing = 1.0/32.0;\n\
color = getSDFColor(v_textureCoordinates, outlineWidth, outlineColor, smoothing);\n\
#endif\n\
color = czm_gammaCorrect(color);\n\
#else\n\
color = czm_gammaCorrect(color);\n\
color *= czm_gammaCorrect(v_color);\n\
#endif\n\
#if !defined(OPAQUE) && !defined(TRANSLUCENT)\n\
if (color.a < 0.005)\n\
{\n\
discard;\n\
}\n\
#else\n\
#ifdef OPAQUE\n\
if (color.a < 0.995)\n\
{\n\
discard;\n\
}\n\
#else\n\
if (color.a >= 0.995)\n\
{\n\
discard;\n\
}\n\
#endif\n\
#endif\n\
#ifdef VECTOR_TILE\n\
color *= u_highlightColor;\n\
#endif\n\
gl_FragColor = color;\n\
#ifdef LOG_DEPTH\n\
czm_writeLogDepth();\n\
#endif\n\
#ifdef FRAGMENT_DEPTH_CHECK\n\
float temp = v_compressed.y;\n\
temp = temp * SHIFT_RIGHT1;\n\
float temp2 = (temp - floor(temp)) * SHIFT_LEFT1;\n\
bool enableDepthTest = temp2 != 0.0;\n\
bool applyTranslate = floor(temp) != 0.0;\n\
if (enableDepthTest) {\n\
temp = v_compressed.z;\n\
temp = temp * SHIFT_RIGHT12;\n\
vec2 dimensions;\n\
dimensions.y = (temp - floor(temp)) * SHIFT_LEFT12;\n\
dimensions.x = floor(temp);\n\
temp = v_compressed.w;\n\
temp = temp * SHIFT_RIGHT12;\n\
vec2 imageSize;\n\
imageSize.y = (temp - floor(temp)) * SHIFT_LEFT12;\n\
imageSize.x = floor(temp);\n\
vec2 adjustedST = v_textureCoordinates - v_textureCoordinateBounds.xy;\n\
adjustedST = adjustedST / vec2(v_textureCoordinateBounds.z - v_textureCoordinateBounds.x, v_textureCoordinateBounds.w - v_textureCoordinateBounds.y);\n\
float epsilonEyeDepth = v_compressed.x + czm_epsilon1;\n\
float globeDepth1 = getGlobeDepth(adjustedST, v_originTextureCoordinateAndTranslate.xy, applyTranslate, dimensions, imageSize);\n\
if (globeDepth1 != 0.0 && globeDepth1 > epsilonEyeDepth)\n\
{\n\
float globeDepth2 = getGlobeDepth(adjustedST, vec2(0.0, 1.0), applyTranslate, dimensions, imageSize);\n\
if (globeDepth2 != 0.0 && globeDepth2 > epsilonEyeDepth)\n\
{\n\
float globeDepth3 = getGlobeDepth(adjustedST, vec2(1.0, 1.0), applyTranslate, dimensions, imageSize);\n\
if (globeDepth3 != 0.0 && globeDepth3 > epsilonEyeDepth)\n\
{\n\
discard;\n\
}\n\
}\n\
}\n\
}\n\
#endif\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var BillboardCollectionVS = "#ifdef INSTANCED\n\
attribute vec2 direction;\n\
#endif\n\
attribute vec4 positionHighAndScale;\n\
attribute vec4 positionLowAndRotation;\n\
attribute vec4 compressedAttribute0;\n\
attribute vec4 compressedAttribute1;\n\
attribute vec4 compressedAttribute2;\n\
attribute vec4 eyeOffset;\n\
attribute vec4 scaleByDistance;\n\
attribute vec4 pixelOffsetScaleByDistance;\n\
attribute vec4 compressedAttribute3;\n\
attribute vec2 sdf;\n\
#if defined(VERTEX_DEPTH_CHECK) || defined(FRAGMENT_DEPTH_CHECK)\n\
attribute vec4 textureCoordinateBoundsOrLabelTranslate;\n\
#endif\n\
#ifdef VECTOR_TILE\n\
attribute float a_batchId;\n\
#endif\n\
varying vec2 v_textureCoordinates;\n\
#ifdef FRAGMENT_DEPTH_CHECK\n\
varying vec4 v_textureCoordinateBounds;\n\
varying vec4 v_originTextureCoordinateAndTranslate;\n\
varying vec4 v_compressed;\n\
varying mat2 v_rotationMatrix;\n\
#endif\n\
varying vec4 v_pickColor;\n\
varying vec4 v_color;\n\
#ifdef SDF\n\
varying vec4 v_outlineColor;\n\
varying float v_outlineWidth;\n\
#endif\n\
const float UPPER_BOUND = 32768.0;\n\
const float SHIFT_LEFT16 = 65536.0;\n\
const float SHIFT_LEFT12 = 4096.0;\n\
const float SHIFT_LEFT8 = 256.0;\n\
const float SHIFT_LEFT7 = 128.0;\n\
const float SHIFT_LEFT5 = 32.0;\n\
const float SHIFT_LEFT3 = 8.0;\n\
const float SHIFT_LEFT2 = 4.0;\n\
const float SHIFT_LEFT1 = 2.0;\n\
const float SHIFT_RIGHT12 = 1.0 / 4096.0;\n\
const float SHIFT_RIGHT8 = 1.0 / 256.0;\n\
const float SHIFT_RIGHT7 = 1.0 / 128.0;\n\
const float SHIFT_RIGHT5 = 1.0 / 32.0;\n\
const float SHIFT_RIGHT3 = 1.0 / 8.0;\n\
const float SHIFT_RIGHT2 = 1.0 / 4.0;\n\
const float SHIFT_RIGHT1 = 1.0 / 2.0;\n\
vec4 addScreenSpaceOffset(vec4 positionEC, vec2 imageSize, float scale, vec2 direction, vec2 origin, vec2 translate, vec2 pixelOffset, vec3 alignedAxis, bool validAlignedAxis, float rotation, bool sizeInMeters, out mat2 rotationMatrix, out float mpp)\n\
{\n\
vec2 halfSize = imageSize * scale * 0.5;\n\
halfSize *= ((direction * 2.0) - 1.0);\n\
vec2 originTranslate = origin * abs(halfSize);\n\
#if defined(ROTATION) || defined(ALIGNED_AXIS)\n\
if (validAlignedAxis || rotation != 0.0)\n\
{\n\
float angle = rotation;\n\
if (validAlignedAxis)\n\
{\n\
vec4 projectedAlignedAxis = czm_modelViewProjection * vec4(alignedAxis, 0.0);\n\
angle += sign(-projectedAlignedAxis.x) * acos(sign(projectedAlignedAxis.y) * (projectedAlignedAxis.y * projectedAlignedAxis.y) /\n\
(projectedAlignedAxis.x * projectedAlignedAxis.x + projectedAlignedAxis.y * projectedAlignedAxis.y));\n\
}\n\
float cosTheta = cos(angle);\n\
float sinTheta = sin(angle);\n\
rotationMatrix = mat2(cosTheta, sinTheta, -sinTheta, cosTheta);\n\
halfSize = rotationMatrix * halfSize;\n\
}\n\
else\n\
{\n\
rotationMatrix = mat2(1.0, 0.0, 0.0, 1.0);\n\
}\n\
#endif\n\
mpp = czm_metersPerPixel(positionEC);\n\
positionEC.xy += (originTranslate + halfSize) * czm_branchFreeTernary(sizeInMeters, 1.0, mpp);\n\
positionEC.xy += (translate + pixelOffset) * mpp;\n\
return positionEC;\n\
}\n\
#ifdef VERTEX_DEPTH_CHECK\n\
float getGlobeDepth(vec4 positionEC)\n\
{\n\
vec4 posWC = czm_eyeToWindowCoordinates(positionEC);\n\
float globeDepth = czm_unpackDepth(texture2D(czm_globeDepthTexture, posWC.xy / czm_viewport.zw));\n\
if (globeDepth == 0.0)\n\
{\n\
return 0.0;\n\
}\n\
vec4 eyeCoordinate = czm_windowToEyeCoordinates(posWC.xy, globeDepth);\n\
return eyeCoordinate.z / eyeCoordinate.w;\n\
}\n\
#endif\n\
void main()\n\
{\n\
vec3 positionHigh = positionHighAndScale.xyz;\n\
vec3 positionLow = positionLowAndRotation.xyz;\n\
float scale = positionHighAndScale.w;\n\
#if defined(ROTATION) || defined(ALIGNED_AXIS)\n\
float rotation = positionLowAndRotation.w;\n\
#else\n\
float rotation = 0.0;\n\
#endif\n\
float compressed = compressedAttribute0.x;\n\
vec2 pixelOffset;\n\
pixelOffset.x = floor(compressed * SHIFT_RIGHT7);\n\
compressed -= pixelOffset.x * SHIFT_LEFT7;\n\
pixelOffset.x -= UPPER_BOUND;\n\
vec2 origin;\n\
origin.x = floor(compressed * SHIFT_RIGHT5);\n\
compressed -= origin.x * SHIFT_LEFT5;\n\
origin.y = floor(compressed * SHIFT_RIGHT3);\n\
compressed -= origin.y * SHIFT_LEFT3;\n\
#ifdef FRAGMENT_DEPTH_CHECK\n\
vec2 depthOrigin = origin.xy;\n\
#endif\n\
origin -= vec2(1.0);\n\
float show = floor(compressed * SHIFT_RIGHT2);\n\
compressed -= show * SHIFT_LEFT2;\n\
#ifdef INSTANCED\n\
vec2 textureCoordinatesBottomLeft = czm_decompressTextureCoordinates(compressedAttribute0.w);\n\
vec2 textureCoordinatesRange = czm_decompressTextureCoordinates(eyeOffset.w);\n\
vec2 textureCoordinates = textureCoordinatesBottomLeft + direction * textureCoordinatesRange;\n\
#else\n\
vec2 direction;\n\
direction.x = floor(compressed * SHIFT_RIGHT1);\n\
direction.y = compressed - direction.x * SHIFT_LEFT1;\n\
vec2 textureCoordinates = czm_decompressTextureCoordinates(compressedAttribute0.w);\n\
#endif\n\
float temp = compressedAttribute0.y  * SHIFT_RIGHT8;\n\
pixelOffset.y = -(floor(temp) - UPPER_BOUND);\n\
vec2 translate;\n\
translate.y = (temp - floor(temp)) * SHIFT_LEFT16;\n\
temp = compressedAttribute0.z * SHIFT_RIGHT8;\n\
translate.x = floor(temp) - UPPER_BOUND;\n\
translate.y += (temp - floor(temp)) * SHIFT_LEFT8;\n\
translate.y -= UPPER_BOUND;\n\
temp = compressedAttribute1.x * SHIFT_RIGHT8;\n\
float temp2 = floor(compressedAttribute2.w * SHIFT_RIGHT2);\n\
vec2 imageSize = vec2(floor(temp), temp2);\n\
#ifdef FRAGMENT_DEPTH_CHECK\n\
float labelHorizontalOrigin = floor(compressedAttribute2.w - (temp2 * SHIFT_LEFT2));\n\
float applyTranslate = 0.0;\n\
if (labelHorizontalOrigin != 0.0)\n\
{\n\
applyTranslate = 1.0;\n\
labelHorizontalOrigin -= 2.0;\n\
depthOrigin.x = labelHorizontalOrigin + 1.0;\n\
}\n\
depthOrigin = vec2(1.0) - (depthOrigin * 0.5);\n\
#endif\n\
#ifdef EYE_DISTANCE_TRANSLUCENCY\n\
vec4 translucencyByDistance;\n\
translucencyByDistance.x = compressedAttribute1.z;\n\
translucencyByDistance.z = compressedAttribute1.w;\n\
translucencyByDistance.y = ((temp - floor(temp)) * SHIFT_LEFT8) / 255.0;\n\
temp = compressedAttribute1.y * SHIFT_RIGHT8;\n\
translucencyByDistance.w = ((temp - floor(temp)) * SHIFT_LEFT8) / 255.0;\n\
#endif\n\
#if defined(VERTEX_DEPTH_CHECK) || defined(FRAGMENT_DEPTH_CHECK)\n\
temp = compressedAttribute3.w;\n\
temp = temp * SHIFT_RIGHT12;\n\
vec2 dimensions;\n\
dimensions.y = (temp - floor(temp)) * SHIFT_LEFT12;\n\
dimensions.x = floor(temp);\n\
#endif\n\
#ifdef ALIGNED_AXIS\n\
vec3 alignedAxis = czm_octDecode(floor(compressedAttribute1.y * SHIFT_RIGHT8));\n\
temp = compressedAttribute2.z * SHIFT_RIGHT5;\n\
bool validAlignedAxis = (temp - floor(temp)) * SHIFT_LEFT1 > 0.0;\n\
#else\n\
vec3 alignedAxis = vec3(0.0);\n\
bool validAlignedAxis = false;\n\
#endif\n\
vec4 pickColor;\n\
vec4 color;\n\
temp = compressedAttribute2.y;\n\
temp = temp * SHIFT_RIGHT8;\n\
pickColor.b = (temp - floor(temp)) * SHIFT_LEFT8;\n\
temp = floor(temp) * SHIFT_RIGHT8;\n\
pickColor.g = (temp - floor(temp)) * SHIFT_LEFT8;\n\
pickColor.r = floor(temp);\n\
temp = compressedAttribute2.x;\n\
temp = temp * SHIFT_RIGHT8;\n\
color.b = (temp - floor(temp)) * SHIFT_LEFT8;\n\
temp = floor(temp) * SHIFT_RIGHT8;\n\
color.g = (temp - floor(temp)) * SHIFT_LEFT8;\n\
color.r = floor(temp);\n\
temp = compressedAttribute2.z * SHIFT_RIGHT8;\n\
bool sizeInMeters = floor((temp - floor(temp)) * SHIFT_LEFT7) > 0.0;\n\
temp = floor(temp) * SHIFT_RIGHT8;\n\
pickColor.a = (temp - floor(temp)) * SHIFT_LEFT8;\n\
pickColor /= 255.0;\n\
color.a = floor(temp);\n\
color /= 255.0;\n\
vec4 p = czm_translateRelativeToEye(positionHigh, positionLow);\n\
vec4 positionEC = czm_modelViewRelativeToEye * p;\n\
#if defined(FRAGMENT_DEPTH_CHECK) || defined(VERTEX_DEPTH_CHECK)\n\
float eyeDepth = positionEC.z;\n\
#endif\n\
positionEC = czm_eyeOffset(positionEC, eyeOffset.xyz);\n\
positionEC.xyz *= show;\n\
#if defined(EYE_DISTANCE_SCALING) || defined(EYE_DISTANCE_TRANSLUCENCY) || defined(EYE_DISTANCE_PIXEL_OFFSET) || defined(DISTANCE_DISPLAY_CONDITION) || defined(DISABLE_DEPTH_DISTANCE)\n\
float lengthSq;\n\
if (czm_sceneMode == czm_sceneMode2D)\n\
{\n\
lengthSq = czm_eyeHeight2D.y;\n\
}\n\
else\n\
{\n\
lengthSq = dot(positionEC.xyz, positionEC.xyz);\n\
}\n\
#endif\n\
#ifdef EYE_DISTANCE_SCALING\n\
float distanceScale = czm_nearFarScalar(scaleByDistance, lengthSq);\n\
scale *= distanceScale;\n\
translate *= distanceScale;\n\
if (scale == 0.0)\n\
{\n\
positionEC.xyz = vec3(0.0);\n\
}\n\
#endif\n\
float translucency = 1.0;\n\
#ifdef EYE_DISTANCE_TRANSLUCENCY\n\
translucency = czm_nearFarScalar(translucencyByDistance, lengthSq);\n\
if (translucency == 0.0)\n\
{\n\
positionEC.xyz = vec3(0.0);\n\
}\n\
#endif\n\
#ifdef EYE_DISTANCE_PIXEL_OFFSET\n\
float pixelOffsetScale = czm_nearFarScalar(pixelOffsetScaleByDistance, lengthSq);\n\
pixelOffset *= pixelOffsetScale;\n\
#endif\n\
#ifdef DISTANCE_DISPLAY_CONDITION\n\
float nearSq = compressedAttribute3.x;\n\
float farSq = compressedAttribute3.y;\n\
if (lengthSq < nearSq || lengthSq > farSq)\n\
{\n\
positionEC.xyz = vec3(0.0);\n\
}\n\
#endif\n\
mat2 rotationMatrix;\n\
float mpp;\n\
#ifdef DISABLE_DEPTH_DISTANCE\n\
float disableDepthTestDistance = compressedAttribute3.z;\n\
#endif\n\
#ifdef VERTEX_DEPTH_CHECK\n\
if (lengthSq < disableDepthTestDistance) {\n\
float depthsilon = 10.0;\n\
vec2 labelTranslate = textureCoordinateBoundsOrLabelTranslate.xy;\n\
vec4 pEC1 = addScreenSpaceOffset(positionEC, dimensions, scale, vec2(0.0), origin, labelTranslate, pixelOffset, alignedAxis, validAlignedAxis, rotation, sizeInMeters, rotationMatrix, mpp);\n\
float globeDepth1 = getGlobeDepth(pEC1);\n\
if (globeDepth1 != 0.0 && pEC1.z + depthsilon < globeDepth1)\n\
{\n\
vec4 pEC2 = addScreenSpaceOffset(positionEC, dimensions, scale, vec2(0.0, 1.0), origin, labelTranslate, pixelOffset, alignedAxis, validAlignedAxis, rotation, sizeInMeters, rotationMatrix, mpp);\n\
float globeDepth2 = getGlobeDepth(pEC2);\n\
if (globeDepth2 != 0.0 && pEC2.z + depthsilon < globeDepth2)\n\
{\n\
vec4 pEC3 = addScreenSpaceOffset(positionEC, dimensions, scale, vec2(1.0), origin, labelTranslate, pixelOffset, alignedAxis, validAlignedAxis, rotation, sizeInMeters, rotationMatrix, mpp);\n\
float globeDepth3 = getGlobeDepth(pEC3);\n\
if (globeDepth3 != 0.0 && pEC3.z + depthsilon < globeDepth3)\n\
{\n\
positionEC.xyz = vec3(0.0);\n\
}\n\
}\n\
}\n\
}\n\
#endif\n\
positionEC = addScreenSpaceOffset(positionEC, imageSize, scale, direction, origin, translate, pixelOffset, alignedAxis, validAlignedAxis, rotation, sizeInMeters, rotationMatrix, mpp);\n\
gl_Position = czm_projection * positionEC;\n\
v_textureCoordinates = textureCoordinates;\n\
#ifdef LOG_DEPTH\n\
czm_vertexLogDepth();\n\
#endif\n\
#ifdef DISABLE_DEPTH_DISTANCE\n\
if (disableDepthTestDistance == 0.0 && czm_minimumDisableDepthTestDistance != 0.0)\n\
{\n\
disableDepthTestDistance = czm_minimumDisableDepthTestDistance;\n\
}\n\
if (disableDepthTestDistance != 0.0)\n\
{\n\
float zclip = gl_Position.z / gl_Position.w;\n\
bool clipped = (zclip < -1.0 || zclip > 1.0);\n\
if (!clipped && (disableDepthTestDistance < 0.0 || (lengthSq > 0.0 && lengthSq < disableDepthTestDistance)))\n\
{\n\
gl_Position.z = -gl_Position.w;\n\
#ifdef LOG_DEPTH\n\
v_depthFromNearPlusOne = 1.0;\n\
#endif\n\
}\n\
}\n\
#endif\n\
#ifdef FRAGMENT_DEPTH_CHECK\n\
if (sizeInMeters) {\n\
translate /= mpp;\n\
dimensions /= mpp;\n\
imageSize /= mpp;\n\
}\n\
#if defined(ROTATION) || defined(ALIGNED_AXIS)\n\
v_rotationMatrix = rotationMatrix;\n\
#else\n\
v_rotationMatrix = mat2(1.0, 0.0, 0.0, 1.0);\n\
#endif\n\
float enableDepthCheck = 0.0;\n\
if (lengthSq < disableDepthTestDistance)\n\
{\n\
enableDepthCheck = 1.0;\n\
}\n\
float dw = floor(clamp(dimensions.x, 0.0, SHIFT_LEFT12));\n\
float dh = floor(clamp(dimensions.y, 0.0, SHIFT_LEFT12));\n\
float iw = floor(clamp(imageSize.x, 0.0, SHIFT_LEFT12));\n\
float ih = floor(clamp(imageSize.y, 0.0, SHIFT_LEFT12));\n\
v_compressed.x = eyeDepth;\n\
v_compressed.y = applyTranslate * SHIFT_LEFT1 + enableDepthCheck;\n\
v_compressed.z = dw * SHIFT_LEFT12 + dh;\n\
v_compressed.w = iw * SHIFT_LEFT12 + ih;\n\
v_originTextureCoordinateAndTranslate.xy = depthOrigin;\n\
v_originTextureCoordinateAndTranslate.zw = translate;\n\
v_textureCoordinateBounds = textureCoordinateBoundsOrLabelTranslate;\n\
#endif\n\
#ifdef SDF\n\
vec4 outlineColor;\n\
float outlineWidth;\n\
temp = sdf.x;\n\
temp = temp * SHIFT_RIGHT8;\n\
outlineColor.b = (temp - floor(temp)) * SHIFT_LEFT8;\n\
temp = floor(temp) * SHIFT_RIGHT8;\n\
outlineColor.g = (temp - floor(temp)) * SHIFT_LEFT8;\n\
outlineColor.r = floor(temp);\n\
temp = sdf.y;\n\
temp = temp * SHIFT_RIGHT8;\n\
float temp3 = (temp - floor(temp)) * SHIFT_LEFT8;\n\
temp = floor(temp) * SHIFT_RIGHT8;\n\
outlineWidth = (temp - floor(temp)) * SHIFT_LEFT8;\n\
outlineColor.a = floor(temp);\n\
outlineColor /= 255.0;\n\
v_outlineWidth = outlineWidth / 255.0;\n\
v_outlineColor = outlineColor;\n\
v_outlineColor.a *= translucency;\n\
#endif\n\
v_pickColor = pickColor;\n\
v_color = color;\n\
v_color.a *= translucency;\n\
}\n\
";

  /**
   * Functions that do scene-dependent transforms between rendering-related coordinate systems.
   *
   * @namespace SceneTransforms
   */
  const SceneTransforms = {};

  const actualPositionScratch = new Cartesian4(0, 0, 0, 1);
  let positionCC = new Cartesian4();
  const scratchViewport$1 = new BoundingRectangle();

  const scratchWindowCoord0 = new Cartesian2();
  const scratchWindowCoord1 = new Cartesian2();

  /**
   * Transforms a position in WGS84 coordinates to window coordinates.  This is commonly used to place an
   * HTML element at the same screen position as an object in the scene.
   *
   * @param {Scene} scene The scene.
   * @param {Cartesian3} position The position in WGS84 (world) coordinates.
   * @param {Cartesian2} [result] An optional object to return the input position transformed to window coordinates.
   * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.  This may be <code>undefined</code> if the input position is near the center of the ellipsoid.
   *
   * @example
   * // Output the window position of longitude/latitude (0, 0) every time the mouse moves.
   * const scene = widget.scene;
   * const ellipsoid = scene.globe.ellipsoid;
   * const position = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
   * const handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
   * handler.setInputAction(function(movement) {
   *     console.log(Cesium.SceneTransforms.wgs84ToWindowCoordinates(scene, position));
   * }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
   */
  SceneTransforms.wgs84ToWindowCoordinates = function (scene, position, result) {
    return SceneTransforms.wgs84WithEyeOffsetToWindowCoordinates(
      scene,
      position,
      Cartesian3.ZERO,
      result
    );
  };

  const scratchCartesian4$3 = new Cartesian4();
  const scratchEyeOffset = new Cartesian3();

  function worldToClip(position, eyeOffset, camera, result) {
    const viewMatrix = camera.viewMatrix;

    const positionEC = Matrix4.multiplyByVector(
      viewMatrix,
      Cartesian4.fromElements(
        position.x,
        position.y,
        position.z,
        1,
        scratchCartesian4$3
      ),
      scratchCartesian4$3
    );

    const zEyeOffset = Cartesian3.multiplyComponents(
      eyeOffset,
      Cartesian3.normalize(positionEC, scratchEyeOffset),
      scratchEyeOffset
    );
    positionEC.x += eyeOffset.x + zEyeOffset.x;
    positionEC.y += eyeOffset.y + zEyeOffset.y;
    positionEC.z += zEyeOffset.z;

    return Matrix4.multiplyByVector(
      camera.frustum.projectionMatrix,
      positionEC,
      result
    );
  }

  const scratchMaxCartographic = new Cartographic(
    Math.PI,
    CesiumMath.PI_OVER_TWO
  );
  const scratchProjectedCartesian = new Cartesian3();
  const scratchCameraPosition$1 = new Cartesian3();

  /**
   * @private
   */
  SceneTransforms.wgs84WithEyeOffsetToWindowCoordinates = function (
    scene,
    position,
    eyeOffset,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(scene)) {
      throw new DeveloperError("scene is required.");
    }
    if (!defined(position)) {
      throw new DeveloperError("position is required.");
    }
    //>>includeEnd('debug');

    // Transform for 3D, 2D, or Columbus view
    const frameState = scene.frameState;
    const actualPosition = SceneTransforms.computeActualWgs84Position(
      frameState,
      position,
      actualPositionScratch
    );

    if (!defined(actualPosition)) {
      return undefined;
    }

    // Assuming viewport takes up the entire canvas...
    const canvas = scene.canvas;
    const viewport = scratchViewport$1;
    viewport.x = 0;
    viewport.y = 0;
    viewport.width = canvas.clientWidth;
    viewport.height = canvas.clientHeight;

    const camera = scene.camera;
    let cameraCentered = false;

    if (frameState.mode === SceneMode$1.SCENE2D) {
      const projection = scene.mapProjection;
      const maxCartographic = scratchMaxCartographic;
      const maxCoord = projection.project(
        maxCartographic,
        scratchProjectedCartesian
      );

      const cameraPosition = Cartesian3.clone(
        camera.position,
        scratchCameraPosition$1
      );
      const frustum = camera.frustum.clone();

      const viewportTransformation = Matrix4.computeViewportTransformation(
        viewport,
        0.0,
        1.0,
        new Matrix4()
      );
      const projectionMatrix = camera.frustum.projectionMatrix;

      const x = camera.positionWC.y;
      const eyePoint = Cartesian3.fromElements(
        CesiumMath.sign(x) * maxCoord.x - x,
        0.0,
        -camera.positionWC.x
      );
      const windowCoordinates = Transforms.pointToGLWindowCoordinates(
        projectionMatrix,
        viewportTransformation,
        eyePoint
      );

      if (
        x === 0.0 ||
        windowCoordinates.x <= 0.0 ||
        windowCoordinates.x >= canvas.clientWidth
      ) {
        cameraCentered = true;
      } else {
        if (windowCoordinates.x > canvas.clientWidth * 0.5) {
          viewport.width = windowCoordinates.x;

          camera.frustum.right = maxCoord.x - x;

          positionCC = worldToClip(actualPosition, eyeOffset, camera, positionCC);
          SceneTransforms.clipToGLWindowCoordinates(
            viewport,
            positionCC,
            scratchWindowCoord0
          );

          viewport.x += windowCoordinates.x;

          camera.position.x = -camera.position.x;

          const right = camera.frustum.right;
          camera.frustum.right = -camera.frustum.left;
          camera.frustum.left = -right;

          positionCC = worldToClip(actualPosition, eyeOffset, camera, positionCC);
          SceneTransforms.clipToGLWindowCoordinates(
            viewport,
            positionCC,
            scratchWindowCoord1
          );
        } else {
          viewport.x += windowCoordinates.x;
          viewport.width -= windowCoordinates.x;

          camera.frustum.left = -maxCoord.x - x;

          positionCC = worldToClip(actualPosition, eyeOffset, camera, positionCC);
          SceneTransforms.clipToGLWindowCoordinates(
            viewport,
            positionCC,
            scratchWindowCoord0
          );

          viewport.x = viewport.x - viewport.width;

          camera.position.x = -camera.position.x;

          const left = camera.frustum.left;
          camera.frustum.left = -camera.frustum.right;
          camera.frustum.right = -left;

          positionCC = worldToClip(actualPosition, eyeOffset, camera, positionCC);
          SceneTransforms.clipToGLWindowCoordinates(
            viewport,
            positionCC,
            scratchWindowCoord1
          );
        }

        Cartesian3.clone(cameraPosition, camera.position);
        camera.frustum = frustum.clone();

        result = Cartesian2.clone(scratchWindowCoord0, result);
        if (result.x < 0.0 || result.x > canvas.clientWidth) {
          result.x = scratchWindowCoord1.x;
        }
      }
    }

    if (frameState.mode !== SceneMode$1.SCENE2D || cameraCentered) {
      // View-projection matrix to transform from world coordinates to clip coordinates
      positionCC = worldToClip(actualPosition, eyeOffset, camera, positionCC);
      if (
        positionCC.z < 0 &&
        !(camera.frustum instanceof OrthographicFrustum) &&
        !(camera.frustum instanceof OrthographicOffCenterFrustum)
      ) {
        return undefined;
      }

      result = SceneTransforms.clipToGLWindowCoordinates(
        viewport,
        positionCC,
        result
      );
    }

    result.y = canvas.clientHeight - result.y;
    return result;
  };

  /**
   * Transforms a position in WGS84 coordinates to drawing buffer coordinates.  This may produce different
   * results from SceneTransforms.wgs84ToWindowCoordinates when the browser zoom is not 100%, or on high-DPI displays.
   *
   * @param {Scene} scene The scene.
   * @param {Cartesian3} position The position in WGS84 (world) coordinates.
   * @param {Cartesian2} [result] An optional object to return the input position transformed to window coordinates.
   * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.  This may be <code>undefined</code> if the input position is near the center of the ellipsoid.
   *
   * @example
   * // Output the window position of longitude/latitude (0, 0) every time the mouse moves.
   * const scene = widget.scene;
   * const ellipsoid = scene.globe.ellipsoid;
   * const position = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
   * const handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
   * handler.setInputAction(function(movement) {
   *     console.log(Cesium.SceneTransforms.wgs84ToWindowCoordinates(scene, position));
   * }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
   */
  SceneTransforms.wgs84ToDrawingBufferCoordinates = function (
    scene,
    position,
    result
  ) {
    result = SceneTransforms.wgs84ToWindowCoordinates(scene, position, result);
    if (!defined(result)) {
      return undefined;
    }

    return SceneTransforms.transformWindowToDrawingBuffer(scene, result, result);
  };

  const projectedPosition = new Cartesian3();
  const positionInCartographic = new Cartographic();

  /**
   * @private
   */
  SceneTransforms.computeActualWgs84Position = function (
    frameState,
    position,
    result
  ) {
    const mode = frameState.mode;

    if (mode === SceneMode$1.SCENE3D) {
      return Cartesian3.clone(position, result);
    }

    const projection = frameState.mapProjection;
    const cartographic = projection.ellipsoid.cartesianToCartographic(
      position,
      positionInCartographic
    );
    if (!defined(cartographic)) {
      return undefined;
    }

    projection.project(cartographic, projectedPosition);

    if (mode === SceneMode$1.COLUMBUS_VIEW) {
      return Cartesian3.fromElements(
        projectedPosition.z,
        projectedPosition.x,
        projectedPosition.y,
        result
      );
    }

    if (mode === SceneMode$1.SCENE2D) {
      return Cartesian3.fromElements(
        0.0,
        projectedPosition.x,
        projectedPosition.y,
        result
      );
    }

    // mode === SceneMode.MORPHING
    const morphTime = frameState.morphTime;
    return Cartesian3.fromElements(
      CesiumMath.lerp(projectedPosition.z, position.x, morphTime),
      CesiumMath.lerp(projectedPosition.x, position.y, morphTime),
      CesiumMath.lerp(projectedPosition.y, position.z, morphTime),
      result
    );
  };

  const positionNDC = new Cartesian3();
  const positionWC = new Cartesian3();
  const viewportTransform = new Matrix4();

  /**
   * @private
   */
  SceneTransforms.clipToGLWindowCoordinates = function (
    viewport,
    position,
    result
  ) {
    // Perspective divide to transform from clip coordinates to normalized device coordinates
    Cartesian3.divideByScalar(position, position.w, positionNDC);

    // Viewport transform to transform from clip coordinates to window coordinates
    Matrix4.computeViewportTransformation(viewport, 0.0, 1.0, viewportTransform);
    Matrix4.multiplyByPoint(viewportTransform, positionNDC, positionWC);

    return Cartesian2.fromCartesian3(positionWC, result);
  };

  /**
   * @private
   */
  SceneTransforms.transformWindowToDrawingBuffer = function (
    scene,
    windowPosition,
    result
  ) {
    const canvas = scene.canvas;
    const xScale = scene.drawingBufferWidth / canvas.clientWidth;
    const yScale = scene.drawingBufferHeight / canvas.clientHeight;
    return Cartesian2.fromElements(
      windowPosition.x * xScale,
      windowPosition.y * yScale,
      result
    );
  };

  const scratchNDC = new Cartesian4();
  const scratchWorldCoords = new Cartesian4();

  /**
   * @private
   */
  SceneTransforms.drawingBufferToWgs84Coordinates = function (
    scene,
    drawingBufferPosition,
    depth,
    result
  ) {
    const context = scene.context;
    const uniformState = context.uniformState;

    const currentFrustum = uniformState.currentFrustum;
    const near = currentFrustum.x;
    const far = currentFrustum.y;

    if (scene.frameState.useLogDepth) {
      // transforming logarithmic depth of form
      // log2(z + 1) / log2( far + 1);
      // to perspective form
      // (far - far * near / z) / (far - near)
      const log2Depth = depth * uniformState.log2FarDepthFromNearPlusOne;
      const depthFromNear = Math.pow(2.0, log2Depth) - 1.0;
      depth = (far * (1.0 - near / (depthFromNear + near))) / (far - near);
    }

    const viewport = scene.view.passState.viewport;
    const ndc = Cartesian4.clone(Cartesian4.UNIT_W, scratchNDC);
    ndc.x = ((drawingBufferPosition.x - viewport.x) / viewport.width) * 2.0 - 1.0;
    ndc.y =
      ((drawingBufferPosition.y - viewport.y) / viewport.height) * 2.0 - 1.0;
    ndc.z = depth * 2.0 - 1.0;
    ndc.w = 1.0;

    let worldCoords;
    let frustum = scene.camera.frustum;
    if (!defined(frustum.fovy)) {
      if (defined(frustum._offCenterFrustum)) {
        frustum = frustum._offCenterFrustum;
      }
      worldCoords = scratchWorldCoords;
      worldCoords.x =
        (ndc.x * (frustum.right - frustum.left) + frustum.left + frustum.right) *
        0.5;
      worldCoords.y =
        (ndc.y * (frustum.top - frustum.bottom) + frustum.bottom + frustum.top) *
        0.5;
      worldCoords.z = (ndc.z * (near - far) - near - far) * 0.5;
      worldCoords.w = 1.0;

      worldCoords = Matrix4.multiplyByVector(
        uniformState.inverseView,
        worldCoords,
        worldCoords
      );
    } else {
      worldCoords = Matrix4.multiplyByVector(
        uniformState.inverseViewProjection,
        ndc,
        scratchWorldCoords
      );

      // Reverse perspective divide
      const w = 1.0 / worldCoords.w;
      Cartesian3.multiplyByScalar(worldCoords, w, worldCoords);
    }
    return Cartesian3.fromCartesian4(worldCoords, result);
  };

  /**
   * A viewport-aligned image positioned in the 3D scene, that is created
   * and rendered using a {@link BillboardCollection}.  A billboard is created and its initial
   * properties are set by calling {@link BillboardCollection#add}.
   * <br /><br />
   * <div align='center'>
   * <img src='Images/Billboard.png' width='400' height='300' /><br />
   * Example billboards
   * </div>
   *
   * @alias Billboard
   *
   * @performance Reading a property, e.g., {@link Billboard#show}, is constant time.
   * Assigning to a property is constant time but results in
   * CPU to GPU traffic when {@link BillboardCollection#update} is called.  The per-billboard traffic is
   * the same regardless of how many properties were updated.  If most billboards in a collection need to be
   * updated, it may be more efficient to clear the collection with {@link BillboardCollection#removeAll}
   * and add new billboards instead of modifying each one.
   *
   * @exception {DeveloperError} scaleByDistance.far must be greater than scaleByDistance.near
   * @exception {DeveloperError} translucencyByDistance.far must be greater than translucencyByDistance.near
   * @exception {DeveloperError} pixelOffsetScaleByDistance.far must be greater than pixelOffsetScaleByDistance.near
   * @exception {DeveloperError} distanceDisplayCondition.far must be greater than distanceDisplayCondition.near
   *
   * @see BillboardCollection
   * @see BillboardCollection#add
   * @see Label
   *
   * @internalConstructor
   * @class
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Billboards.html|Cesium Sandcastle Billboard Demo}
   */
  function Billboard(options, billboardCollection) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    if (
      defined(options.disableDepthTestDistance) &&
      options.disableDepthTestDistance < 0.0
    ) {
      throw new DeveloperError(
        "disableDepthTestDistance must be greater than or equal to 0.0."
      );
    }
    //>>includeEnd('debug');

    let translucencyByDistance = options.translucencyByDistance;
    let pixelOffsetScaleByDistance = options.pixelOffsetScaleByDistance;
    let scaleByDistance = options.scaleByDistance;
    let distanceDisplayCondition = options.distanceDisplayCondition;
    if (defined(translucencyByDistance)) {
      //>>includeStart('debug', pragmas.debug);
      if (translucencyByDistance.far <= translucencyByDistance.near) {
        throw new DeveloperError(
          "translucencyByDistance.far must be greater than translucencyByDistance.near."
        );
      }
      //>>includeEnd('debug');
      translucencyByDistance = NearFarScalar.clone(translucencyByDistance);
    }
    if (defined(pixelOffsetScaleByDistance)) {
      //>>includeStart('debug', pragmas.debug);
      if (pixelOffsetScaleByDistance.far <= pixelOffsetScaleByDistance.near) {
        throw new DeveloperError(
          "pixelOffsetScaleByDistance.far must be greater than pixelOffsetScaleByDistance.near."
        );
      }
      //>>includeEnd('debug');
      pixelOffsetScaleByDistance = NearFarScalar.clone(
        pixelOffsetScaleByDistance
      );
    }
    if (defined(scaleByDistance)) {
      //>>includeStart('debug', pragmas.debug);
      if (scaleByDistance.far <= scaleByDistance.near) {
        throw new DeveloperError(
          "scaleByDistance.far must be greater than scaleByDistance.near."
        );
      }
      //>>includeEnd('debug');
      scaleByDistance = NearFarScalar.clone(scaleByDistance);
    }
    if (defined(distanceDisplayCondition)) {
      //>>includeStart('debug', pragmas.debug);
      if (distanceDisplayCondition.far <= distanceDisplayCondition.near) {
        throw new DeveloperError(
          "distanceDisplayCondition.far must be greater than distanceDisplayCondition.near."
        );
      }
      //>>includeEnd('debug');
      distanceDisplayCondition = DistanceDisplayCondition.clone(
        distanceDisplayCondition
      );
    }

    this._show = defaultValue(options.show, true);
    this._position = Cartesian3.clone(
      defaultValue(options.position, Cartesian3.ZERO)
    );
    this._actualPosition = Cartesian3.clone(this._position); // For columbus view and 2D
    this._pixelOffset = Cartesian2.clone(
      defaultValue(options.pixelOffset, Cartesian2.ZERO)
    );
    this._translate = new Cartesian2(0.0, 0.0); // used by labels for glyph vertex translation
    this._eyeOffset = Cartesian3.clone(
      defaultValue(options.eyeOffset, Cartesian3.ZERO)
    );
    this._heightReference = defaultValue(
      options.heightReference,
      HeightReference$1.NONE
    );
    this._verticalOrigin = defaultValue(
      options.verticalOrigin,
      VerticalOrigin$1.CENTER
    );
    this._horizontalOrigin = defaultValue(
      options.horizontalOrigin,
      HorizontalOrigin$1.CENTER
    );
    this._scale = defaultValue(options.scale, 1.0);
    this._color = Color.clone(defaultValue(options.color, Color.WHITE));
    this._rotation = defaultValue(options.rotation, 0.0);
    this._alignedAxis = Cartesian3.clone(
      defaultValue(options.alignedAxis, Cartesian3.ZERO)
    );
    this._width = options.width;
    this._height = options.height;
    this._scaleByDistance = scaleByDistance;
    this._translucencyByDistance = translucencyByDistance;
    this._pixelOffsetScaleByDistance = pixelOffsetScaleByDistance;
    this._sizeInMeters = defaultValue(options.sizeInMeters, false);
    this._distanceDisplayCondition = distanceDisplayCondition;
    this._disableDepthTestDistance = options.disableDepthTestDistance;
    this._id = options.id;
    this._collection = defaultValue(options.collection, billboardCollection);

    this._pickId = undefined;
    this._pickPrimitive = defaultValue(options._pickPrimitive, this);
    this._billboardCollection = billboardCollection;
    this._dirty = false;
    this._index = -1; //Used only by BillboardCollection
    this._batchIndex = undefined; // Used only by Vector3DTilePoints and BillboardCollection

    this._imageIndex = -1;
    this._imageIndexPromise = undefined;
    this._imageId = undefined;
    this._image = undefined;
    this._imageSubRegion = undefined;
    this._imageWidth = undefined;
    this._imageHeight = undefined;

    this._labelDimensions = undefined;
    this._labelHorizontalOrigin = undefined;
    this._labelTranslate = undefined;

    const image = options.image;
    let imageId = options.imageId;
    if (defined(image)) {
      if (!defined(imageId)) {
        if (typeof image === "string") {
          imageId = image;
        } else if (defined(image.src)) {
          imageId = image.src;
        } else {
          imageId = createGuid();
        }
      }

      this._imageId = imageId;
      this._image = image;
    }

    if (defined(options.imageSubRegion)) {
      this._imageId = imageId;
      this._imageSubRegion = options.imageSubRegion;
    }

    if (defined(this._billboardCollection._textureAtlas)) {
      this._loadImage();
    }

    this._actualClampedPosition = undefined;
    this._removeCallbackFunc = undefined;
    this._mode = SceneMode$1.SCENE3D;

    this._clusterShow = true;
    this._outlineColor = Color.clone(
      defaultValue(options.outlineColor, Color.BLACK)
    );
    this._outlineWidth = defaultValue(options.outlineWidth, 0.0);

    this._updateClamping();
  }

  const SHOW_INDEX$7 = (Billboard.SHOW_INDEX = 0);
  const POSITION_INDEX$7 = (Billboard.POSITION_INDEX = 1);
  const PIXEL_OFFSET_INDEX$1 = (Billboard.PIXEL_OFFSET_INDEX = 2);
  const EYE_OFFSET_INDEX$1 = (Billboard.EYE_OFFSET_INDEX = 3);
  const HORIZONTAL_ORIGIN_INDEX$1 = (Billboard.HORIZONTAL_ORIGIN_INDEX = 4);
  const VERTICAL_ORIGIN_INDEX$1 = (Billboard.VERTICAL_ORIGIN_INDEX = 5);
  const SCALE_INDEX$3 = (Billboard.SCALE_INDEX = 6);
  const IMAGE_INDEX_INDEX$1 = (Billboard.IMAGE_INDEX_INDEX = 7);
  const COLOR_INDEX$5 = (Billboard.COLOR_INDEX = 8);
  const ROTATION_INDEX$1 = (Billboard.ROTATION_INDEX = 9);
  const ALIGNED_AXIS_INDEX$1 = (Billboard.ALIGNED_AXIS_INDEX = 10);
  const SCALE_BY_DISTANCE_INDEX$3 = (Billboard.SCALE_BY_DISTANCE_INDEX = 11);
  const TRANSLUCENCY_BY_DISTANCE_INDEX$3 = (Billboard.TRANSLUCENCY_BY_DISTANCE_INDEX = 12);
  const PIXEL_OFFSET_SCALE_BY_DISTANCE_INDEX$1 = (Billboard.PIXEL_OFFSET_SCALE_BY_DISTANCE_INDEX = 13);
  const DISTANCE_DISPLAY_CONDITION$2 = (Billboard.DISTANCE_DISPLAY_CONDITION = 14);
  const DISABLE_DEPTH_DISTANCE$1 = (Billboard.DISABLE_DEPTH_DISTANCE = 15);
  Billboard.TEXTURE_COORDINATE_BOUNDS = 16;
  const SDF_INDEX$1 = (Billboard.SDF_INDEX = 17);
  Billboard.NUMBER_OF_PROPERTIES = 18;

  function makeDirty$3(billboard, propertyChanged) {
    const billboardCollection = billboard._billboardCollection;
    if (defined(billboardCollection)) {
      billboardCollection._updateBillboard(billboard, propertyChanged);
      billboard._dirty = true;
    }
  }

  Object.defineProperties(Billboard.prototype, {
    /**
     * Determines if this billboard will be shown.  Use this to hide or show a billboard, instead
     * of removing it and re-adding it to the collection.
     * @memberof Billboard.prototype
     * @type {Boolean}
     * @default true
     */
    show: {
      get: function () {
        return this._show;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.bool("value", value);
        //>>includeEnd('debug');

        if (this._show !== value) {
          this._show = value;
          makeDirty$3(this, SHOW_INDEX$7);
        }
      },
    },

    /**
     * Gets or sets the Cartesian position of this billboard.
     * @memberof Billboard.prototype
     * @type {Cartesian3}
     */
    position: {
      get: function () {
        return this._position;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug)
        Check.typeOf.object("value", value);
        //>>includeEnd('debug');

        const position = this._position;
        if (!Cartesian3.equals(position, value)) {
          Cartesian3.clone(value, position);
          Cartesian3.clone(value, this._actualPosition);
          this._updateClamping();
          makeDirty$3(this, POSITION_INDEX$7);
        }
      },
    },

    /**
     * Gets or sets the height reference of this billboard.
     * @memberof Billboard.prototype
     * @type {HeightReference}
     * @default HeightReference.NONE
     */
    heightReference: {
      get: function () {
        return this._heightReference;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug)
        Check.typeOf.number("value", value);
        //>>includeEnd('debug');

        const heightReference = this._heightReference;
        if (value !== heightReference) {
          this._heightReference = value;
          this._updateClamping();
          makeDirty$3(this, POSITION_INDEX$7);
        }
      },
    },

    /**
     * Gets or sets the pixel offset in screen space from the origin of this billboard.  This is commonly used
     * to align multiple billboards and labels at the same position, e.g., an image and text.  The
     * screen space origin is the top, left corner of the canvas; <code>x</code> increases from
     * left to right, and <code>y</code> increases from top to bottom.
     * <br /><br />
     * <div align='center'>
     * <table border='0' cellpadding='5'><tr>
     * <td align='center'><code>default</code><br/><img src='Images/Billboard.setPixelOffset.default.png' width='250' height='188' /></td>
     * <td align='center'><code>b.pixeloffset = new Cartesian2(50, 25);</code><br/><img src='Images/Billboard.setPixelOffset.x50y-25.png' width='250' height='188' /></td>
     * </tr></table>
     * The billboard's origin is indicated by the yellow point.
     * </div>
     * @memberof Billboard.prototype
     * @type {Cartesian2}
     */
    pixelOffset: {
      get: function () {
        return this._pixelOffset;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.object("value", value);
        //>>includeEnd('debug');

        const pixelOffset = this._pixelOffset;
        if (!Cartesian2.equals(pixelOffset, value)) {
          Cartesian2.clone(value, pixelOffset);
          makeDirty$3(this, PIXEL_OFFSET_INDEX$1);
        }
      },
    },

    /**
     * Gets or sets near and far scaling properties of a Billboard based on the billboard's distance from the camera.
     * A billboard's scale will interpolate between the {@link NearFarScalar#nearValue} and
     * {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds
     * of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}.
     * Outside of these ranges the billboard's scale remains clamped to the nearest bound.  If undefined,
     * scaleByDistance will be disabled.
     * @memberof Billboard.prototype
     * @type {NearFarScalar}
     *
     * @example
     * // Example 1.
     * // Set a billboard's scaleByDistance to scale by 1.5 when the
     * // camera is 1500 meters from the billboard and disappear as
     * // the camera distance approaches 8.0e6 meters.
     * b.scaleByDistance = new Cesium.NearFarScalar(1.5e2, 1.5, 8.0e6, 0.0);
     *
     * @example
     * // Example 2.
     * // disable scaling by distance
     * b.scaleByDistance = undefined;
     */
    scaleByDistance: {
      get: function () {
        return this._scaleByDistance;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (defined(value)) {
          Check.typeOf.object("value", value);
          if (value.far <= value.near) {
            throw new DeveloperError(
              "far distance must be greater than near distance."
            );
          }
        }
        //>>includeEnd('debug');

        const scaleByDistance = this._scaleByDistance;
        if (!NearFarScalar.equals(scaleByDistance, value)) {
          this._scaleByDistance = NearFarScalar.clone(value, scaleByDistance);
          makeDirty$3(this, SCALE_BY_DISTANCE_INDEX$3);
        }
      },
    },

    /**
     * Gets or sets near and far translucency properties of a Billboard based on the billboard's distance from the camera.
     * A billboard's translucency will interpolate between the {@link NearFarScalar#nearValue} and
     * {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds
     * of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}.
     * Outside of these ranges the billboard's translucency remains clamped to the nearest bound.  If undefined,
     * translucencyByDistance will be disabled.
     * @memberof Billboard.prototype
     * @type {NearFarScalar}
     *
     * @example
     * // Example 1.
     * // Set a billboard's translucency to 1.0 when the
     * // camera is 1500 meters from the billboard and disappear as
     * // the camera distance approaches 8.0e6 meters.
     * b.translucencyByDistance = new Cesium.NearFarScalar(1.5e2, 1.0, 8.0e6, 0.0);
     *
     * @example
     * // Example 2.
     * // disable translucency by distance
     * b.translucencyByDistance = undefined;
     */
    translucencyByDistance: {
      get: function () {
        return this._translucencyByDistance;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (defined(value)) {
          Check.typeOf.object("value", value);
          if (value.far <= value.near) {
            throw new DeveloperError(
              "far distance must be greater than near distance."
            );
          }
        }
        //>>includeEnd('debug');

        const translucencyByDistance = this._translucencyByDistance;
        if (!NearFarScalar.equals(translucencyByDistance, value)) {
          this._translucencyByDistance = NearFarScalar.clone(
            value,
            translucencyByDistance
          );
          makeDirty$3(this, TRANSLUCENCY_BY_DISTANCE_INDEX$3);
        }
      },
    },

    /**
     * Gets or sets near and far pixel offset scaling properties of a Billboard based on the billboard's distance from the camera.
     * A billboard's pixel offset will be scaled between the {@link NearFarScalar#nearValue} and
     * {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds
     * of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}.
     * Outside of these ranges the billboard's pixel offset scale remains clamped to the nearest bound.  If undefined,
     * pixelOffsetScaleByDistance will be disabled.
     * @memberof Billboard.prototype
     * @type {NearFarScalar}
     *
     * @example
     * // Example 1.
     * // Set a billboard's pixel offset scale to 0.0 when the
     * // camera is 1500 meters from the billboard and scale pixel offset to 10.0 pixels
     * // in the y direction the camera distance approaches 8.0e6 meters.
     * b.pixelOffset = new Cesium.Cartesian2(0.0, 1.0);
     * b.pixelOffsetScaleByDistance = new Cesium.NearFarScalar(1.5e2, 0.0, 8.0e6, 10.0);
     *
     * @example
     * // Example 2.
     * // disable pixel offset by distance
     * b.pixelOffsetScaleByDistance = undefined;
     */
    pixelOffsetScaleByDistance: {
      get: function () {
        return this._pixelOffsetScaleByDistance;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (defined(value)) {
          Check.typeOf.object("value", value);
          if (value.far <= value.near) {
            throw new DeveloperError(
              "far distance must be greater than near distance."
            );
          }
        }
        //>>includeEnd('debug');

        const pixelOffsetScaleByDistance = this._pixelOffsetScaleByDistance;
        if (!NearFarScalar.equals(pixelOffsetScaleByDistance, value)) {
          this._pixelOffsetScaleByDistance = NearFarScalar.clone(
            value,
            pixelOffsetScaleByDistance
          );
          makeDirty$3(this, PIXEL_OFFSET_SCALE_BY_DISTANCE_INDEX$1);
        }
      },
    },

    /**
     * Gets or sets the 3D Cartesian offset applied to this billboard in eye coordinates.  Eye coordinates is a left-handed
     * coordinate system, where <code>x</code> points towards the viewer's right, <code>y</code> points up, and
     * <code>z</code> points into the screen.  Eye coordinates use the same scale as world and model coordinates,
     * which is typically meters.
     * <br /><br />
     * An eye offset is commonly used to arrange multiple billboards or objects at the same position, e.g., to
     * arrange a billboard above its corresponding 3D model.
     * <br /><br />
     * Below, the billboard is positioned at the center of the Earth but an eye offset makes it always
     * appear on top of the Earth regardless of the viewer's or Earth's orientation.
     * <br /><br />
     * <div align='center'>
     * <table border='0' cellpadding='5'><tr>
     * <td align='center'><img src='Images/Billboard.setEyeOffset.one.png' width='250' height='188' /></td>
     * <td align='center'><img src='Images/Billboard.setEyeOffset.two.png' width='250' height='188' /></td>
     * </tr></table>
     * <code>b.eyeOffset = new Cartesian3(0.0, 8000000.0, 0.0);</code><br /><br />
     * </div>
     * @memberof Billboard.prototype
     * @type {Cartesian3}
     */
    eyeOffset: {
      get: function () {
        return this._eyeOffset;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.object("value", value);
        //>>includeEnd('debug');

        const eyeOffset = this._eyeOffset;
        if (!Cartesian3.equals(eyeOffset, value)) {
          Cartesian3.clone(value, eyeOffset);
          makeDirty$3(this, EYE_OFFSET_INDEX$1);
        }
      },
    },

    /**
     * Gets or sets the horizontal origin of this billboard, which determines if the billboard is
     * to the left, center, or right of its anchor position.
     * <br /><br />
     * <div align='center'>
     * <img src='Images/Billboard.setHorizontalOrigin.png' width='648' height='196' /><br />
     * </div>
     * @memberof Billboard.prototype
     * @type {HorizontalOrigin}
     * @example
     * // Use a bottom, left origin
     * b.horizontalOrigin = Cesium.HorizontalOrigin.LEFT;
     * b.verticalOrigin = Cesium.VerticalOrigin.BOTTOM;
     */
    horizontalOrigin: {
      get: function () {
        return this._horizontalOrigin;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number("value", value);
        //>>includeEnd('debug');

        if (this._horizontalOrigin !== value) {
          this._horizontalOrigin = value;
          makeDirty$3(this, HORIZONTAL_ORIGIN_INDEX$1);
        }
      },
    },

    /**
     * Gets or sets the vertical origin of this billboard, which determines if the billboard is
     * to the above, below, or at the center of its anchor position.
     * <br /><br />
     * <div align='center'>
     * <img src='Images/Billboard.setVerticalOrigin.png' width='695' height='175' /><br />
     * </div>
     * @memberof Billboard.prototype
     * @type {VerticalOrigin}
     * @example
     * // Use a bottom, left origin
     * b.horizontalOrigin = Cesium.HorizontalOrigin.LEFT;
     * b.verticalOrigin = Cesium.VerticalOrigin.BOTTOM;
     */
    verticalOrigin: {
      get: function () {
        return this._verticalOrigin;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number("value", value);
        //>>includeEnd('debug');

        if (this._verticalOrigin !== value) {
          this._verticalOrigin = value;
          makeDirty$3(this, VERTICAL_ORIGIN_INDEX$1);
        }
      },
    },

    /**
     * Gets or sets the uniform scale that is multiplied with the billboard's image size in pixels.
     * A scale of <code>1.0</code> does not change the size of the billboard; a scale greater than
     * <code>1.0</code> enlarges the billboard; a positive scale less than <code>1.0</code> shrinks
     * the billboard.
     * <br /><br />
     * <div align='center'>
     * <img src='Images/Billboard.setScale.png' width='400' height='300' /><br/>
     * From left to right in the above image, the scales are <code>0.5</code>, <code>1.0</code>,
     * and <code>2.0</code>.
     * </div>
     * @memberof Billboard.prototype
     * @type {Number}
     */
    scale: {
      get: function () {
        return this._scale;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number("value", value);
        //>>includeEnd('debug');

        if (this._scale !== value) {
          this._scale = value;
          makeDirty$3(this, SCALE_INDEX$3);
        }
      },
    },

    /**
     * Gets or sets the color that is multiplied with the billboard's texture.  This has two common use cases.  First,
     * the same white texture may be used by many different billboards, each with a different color, to create
     * colored billboards.  Second, the color's alpha component can be used to make the billboard translucent as shown below.
     * An alpha of <code>0.0</code> makes the billboard transparent, and <code>1.0</code> makes the billboard opaque.
     * <br /><br />
     * <div align='center'>
     * <table border='0' cellpadding='5'><tr>
     * <td align='center'><code>default</code><br/><img src='Images/Billboard.setColor.Alpha255.png' width='250' height='188' /></td>
     * <td align='center'><code>alpha : 0.5</code><br/><img src='Images/Billboard.setColor.Alpha127.png' width='250' height='188' /></td>
     * </tr></table>
     * </div>
     * <br />
     * The red, green, blue, and alpha values are indicated by <code>value</code>'s <code>red</code>, <code>green</code>,
     * <code>blue</code>, and <code>alpha</code> properties as shown in Example 1.  These components range from <code>0.0</code>
     * (no intensity) to <code>1.0</code> (full intensity).
     * @memberof Billboard.prototype
     * @type {Color}
     *
     * @example
     * // Example 1. Assign yellow.
     * b.color = Cesium.Color.YELLOW;
     *
     * @example
     * // Example 2. Make a billboard 50% translucent.
     * b.color = new Cesium.Color(1.0, 1.0, 1.0, 0.5);
     */
    color: {
      get: function () {
        return this._color;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.object("value", value);
        //>>includeEnd('debug');

        const color = this._color;
        if (!Color.equals(color, value)) {
          Color.clone(value, color);
          makeDirty$3(this, COLOR_INDEX$5);
        }
      },
    },

    /**
     * Gets or sets the rotation angle in radians.
     * @memberof Billboard.prototype
     * @type {Number}
     */
    rotation: {
      get: function () {
        return this._rotation;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number("value", value);
        //>>includeEnd('debug');

        if (this._rotation !== value) {
          this._rotation = value;
          makeDirty$3(this, ROTATION_INDEX$1);
        }
      },
    },

    /**
     * Gets or sets the aligned axis in world space. The aligned axis is the unit vector that the billboard up vector points towards.
     * The default is the zero vector, which means the billboard is aligned to the screen up vector.
     * @memberof Billboard.prototype
     * @type {Cartesian3}
     * @example
     * // Example 1.
     * // Have the billboard up vector point north
     * billboard.alignedAxis = Cesium.Cartesian3.UNIT_Z;
     *
     * @example
     * // Example 2.
     * // Have the billboard point east.
     * billboard.alignedAxis = Cesium.Cartesian3.UNIT_Z;
     * billboard.rotation = -Cesium.Math.PI_OVER_TWO;
     *
     * @example
     * // Example 3.
     * // Reset the aligned axis
     * billboard.alignedAxis = Cesium.Cartesian3.ZERO;
     */
    alignedAxis: {
      get: function () {
        return this._alignedAxis;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.object("value", value);
        //>>includeEnd('debug');

        const alignedAxis = this._alignedAxis;
        if (!Cartesian3.equals(alignedAxis, value)) {
          Cartesian3.clone(value, alignedAxis);
          makeDirty$3(this, ALIGNED_AXIS_INDEX$1);
        }
      },
    },

    /**
     * Gets or sets a width for the billboard. If undefined, the image width will be used.
     * @memberof Billboard.prototype
     * @type {Number}
     */
    width: {
      get: function () {
        return defaultValue(this._width, this._imageWidth);
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (defined(value)) {
          Check.typeOf.number("value", value);
        }
        //>>includeEnd('debug');
        if (this._width !== value) {
          this._width = value;
          makeDirty$3(this, IMAGE_INDEX_INDEX$1);
        }
      },
    },

    /**
     * Gets or sets a height for the billboard. If undefined, the image height will be used.
     * @memberof Billboard.prototype
     * @type {Number}
     */
    height: {
      get: function () {
        return defaultValue(this._height, this._imageHeight);
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (defined(value)) {
          Check.typeOf.number("value", value);
        }
        //>>includeEnd('debug');
        if (this._height !== value) {
          this._height = value;
          makeDirty$3(this, IMAGE_INDEX_INDEX$1);
        }
      },
    },

    /**
     * Gets or sets if the billboard size is in meters or pixels. <code>true</code> to size the billboard in meters;
     * otherwise, the size is in pixels.
     * @memberof Billboard.prototype
     * @type {Boolean}
     * @default false
     */
    sizeInMeters: {
      get: function () {
        return this._sizeInMeters;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.bool("value", value);
        //>>includeEnd('debug');
        if (this._sizeInMeters !== value) {
          this._sizeInMeters = value;
          makeDirty$3(this, COLOR_INDEX$5);
        }
      },
    },

    /**
     * Gets or sets the condition specifying at what distance from the camera that this billboard will be displayed.
     * @memberof Billboard.prototype
     * @type {DistanceDisplayCondition}
     * @default undefined
     */
    distanceDisplayCondition: {
      get: function () {
        return this._distanceDisplayCondition;
      },
      set: function (value) {
        if (
          !DistanceDisplayCondition.equals(value, this._distanceDisplayCondition)
        ) {
          //>>includeStart('debug', pragmas.debug);
          if (defined(value)) {
            Check.typeOf.object("value", value);
            if (value.far <= value.near) {
              throw new DeveloperError(
                "far distance must be greater than near distance."
              );
            }
          }
          //>>includeEnd('debug');
          this._distanceDisplayCondition = DistanceDisplayCondition.clone(
            value,
            this._distanceDisplayCondition
          );
          makeDirty$3(this, DISTANCE_DISPLAY_CONDITION$2);
        }
      },
    },

    /**
     * Gets or sets the distance from the camera at which to disable the depth test to, for example, prevent clipping against terrain.
     * When set to zero, the depth test is always applied. When set to Number.POSITIVE_INFINITY, the depth test is never applied.
     * @memberof Billboard.prototype
     * @type {Number}
     */
    disableDepthTestDistance: {
      get: function () {
        return this._disableDepthTestDistance;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (defined(value)) {
          Check.typeOf.number("value", value);
          if (value < 0.0) {
            throw new DeveloperError(
              "disableDepthTestDistance must be greater than or equal to 0.0."
            );
          }
        }
        //>>includeEnd('debug');
        if (this._disableDepthTestDistance !== value) {
          this._disableDepthTestDistance = value;
          makeDirty$3(this, DISABLE_DEPTH_DISTANCE$1);
        }
      },
    },

    /**
     * Gets or sets the user-defined object returned when the billboard is picked.
     * @memberof Billboard.prototype
     * @type {Object}
     */
    id: {
      get: function () {
        return this._id;
      },
      set: function (value) {
        this._id = value;
        if (defined(this._pickId)) {
          this._pickId.object.id = value;
        }
      },
    },

    /**
     * The primitive to return when picking this billboard.
     * @memberof Billboard.prototype
     * @private
     */
    pickPrimitive: {
      get: function () {
        return this._pickPrimitive;
      },
      set: function (value) {
        this._pickPrimitive = value;
        if (defined(this._pickId)) {
          this._pickId.object.primitive = value;
        }
      },
    },

    /**
     * @private
     */
    pickId: {
      get: function () {
        return this._pickId;
      },
    },

    /**
     * <p>
     * Gets or sets the image to be used for this billboard.  If a texture has already been created for the
     * given image, the existing texture is used.
     * </p>
     * <p>
     * This property can be set to a loaded Image, a URL which will be loaded as an Image automatically,
     * a canvas, or another billboard's image property (from the same billboard collection).
     * </p>
     *
     * @memberof Billboard.prototype
     * @type {String}
     * @example
     * // load an image from a URL
     * b.image = 'some/image/url.png';
     *
     * // assuming b1 and b2 are billboards in the same billboard collection,
     * // use the same image for both billboards.
     * b2.image = b1.image;
     */
    image: {
      get: function () {
        return this._imageId;
      },
      set: function (value) {
        if (!defined(value)) {
          this._imageIndex = -1;
          this._imageSubRegion = undefined;
          this._imageId = undefined;
          this._image = undefined;
          this._imageIndexPromise = undefined;
          makeDirty$3(this, IMAGE_INDEX_INDEX$1);
        } else if (typeof value === "string") {
          this.setImage(value, value);
        } else if (value instanceof Resource) {
          this.setImage(value.url, value);
        } else if (defined(value.src)) {
          this.setImage(value.src, value);
        } else {
          this.setImage(createGuid(), value);
        }
      },
    },

    /**
     * When <code>true</code>, this billboard is ready to render, i.e., the image
     * has been downloaded and the WebGL resources are created.
     *
     * @memberof Billboard.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default false
     */
    ready: {
      get: function () {
        return this._imageIndex !== -1;
      },
    },

    /**
     * Keeps track of the position of the billboard based on the height reference.
     * @memberof Billboard.prototype
     * @type {Cartesian3}
     * @private
     */
    _clampedPosition: {
      get: function () {
        return this._actualClampedPosition;
      },
      set: function (value) {
        this._actualClampedPosition = Cartesian3.clone(
          value,
          this._actualClampedPosition
        );
        makeDirty$3(this, POSITION_INDEX$7);
      },
    },

    /**
     * Determines whether or not this billboard will be shown or hidden because it was clustered.
     * @memberof Billboard.prototype
     * @type {Boolean}
     * @private
     */
    clusterShow: {
      get: function () {
        return this._clusterShow;
      },
      set: function (value) {
        if (this._clusterShow !== value) {
          this._clusterShow = value;
          makeDirty$3(this, SHOW_INDEX$7);
        }
      },
    },

    /**
     * The outline color of this Billboard.  Effective only for SDF billboards like Label glyphs.
     * @memberof Billboard.prototype
     * @type {Color}
     * @private
     */
    outlineColor: {
      get: function () {
        return this._outlineColor;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        const outlineColor = this._outlineColor;
        if (!Color.equals(outlineColor, value)) {
          Color.clone(value, outlineColor);
          makeDirty$3(this, SDF_INDEX$1);
        }
      },
    },

    /**
     * The outline width of this Billboard in pixels.  Effective only for SDF billboards like Label glyphs.
     * @memberof Billboard.prototype
     * @type {Number}
     * @private
     */
    outlineWidth: {
      get: function () {
        return this._outlineWidth;
      },
      set: function (value) {
        if (this._outlineWidth !== value) {
          this._outlineWidth = value;
          makeDirty$3(this, SDF_INDEX$1);
        }
      },
    },
  });

  Billboard.prototype.getPickId = function (context) {
    if (!defined(this._pickId)) {
      this._pickId = context.createPickId({
        primitive: this._pickPrimitive,
        collection: this._collection,
        id: this._id,
      });
    }

    return this._pickId;
  };

  Billboard.prototype._updateClamping = function () {
    Billboard._updateClamping(this._billboardCollection, this);
  };

  const scratchCartographic$d = new Cartographic();
  const scratchPosition$7 = new Cartesian3();

  Billboard._updateClamping = function (collection, owner) {
    const scene = collection._scene;
    if (!defined(scene) || !defined(scene.globe)) {
      //>>includeStart('debug', pragmas.debug);
      if (owner._heightReference !== HeightReference$1.NONE) {
        throw new DeveloperError(
          "Height reference is not supported without a scene and globe."
        );
      }
      //>>includeEnd('debug');
      return;
    }

    const globe = scene.globe;
    const ellipsoid = globe.ellipsoid;
    const surface = globe._surface;

    const mode = scene.frameState.mode;

    const modeChanged = mode !== owner._mode;
    owner._mode = mode;

    if (
      (owner._heightReference === HeightReference$1.NONE || modeChanged) &&
      defined(owner._removeCallbackFunc)
    ) {
      owner._removeCallbackFunc();
      owner._removeCallbackFunc = undefined;
      owner._clampedPosition = undefined;
    }

    if (
      owner._heightReference === HeightReference$1.NONE ||
      !defined(owner._position)
    ) {
      return;
    }

    const position = ellipsoid.cartesianToCartographic(owner._position);
    if (!defined(position)) {
      owner._actualClampedPosition = undefined;
      return;
    }

    if (defined(owner._removeCallbackFunc)) {
      owner._removeCallbackFunc();
    }

    function updateFunction(clampedPosition) {
      if (owner._heightReference === HeightReference$1.RELATIVE_TO_GROUND) {
        if (owner._mode === SceneMode$1.SCENE3D) {
          const clampedCart = ellipsoid.cartesianToCartographic(
            clampedPosition,
            scratchCartographic$d
          );
          clampedCart.height += position.height;
          ellipsoid.cartographicToCartesian(clampedCart, clampedPosition);
        } else {
          clampedPosition.x += position.height;
        }
      }
      owner._clampedPosition = Cartesian3.clone(
        clampedPosition,
        owner._clampedPosition
      );
    }
    owner._removeCallbackFunc = surface.updateHeight(position, updateFunction);

    Cartographic.clone(position, scratchCartographic$d);
    const height = globe.getHeight(position);
    if (defined(height)) {
      scratchCartographic$d.height = height;
    }

    ellipsoid.cartographicToCartesian(scratchCartographic$d, scratchPosition$7);

    updateFunction(scratchPosition$7);
  };

  Billboard.prototype._loadImage = function () {
    const atlas = this._billboardCollection._textureAtlas;

    const imageId = this._imageId;
    const image = this._image;
    const imageSubRegion = this._imageSubRegion;
    let imageIndexPromise;

    const that = this;
    function completeImageLoad(index) {
      if (
        that._imageId !== imageId ||
        that._image !== image ||
        !BoundingRectangle.equals(that._imageSubRegion, imageSubRegion)
      ) {
        // another load occurred before this one finished, ignore the index
        return;
      }

      // fill in imageWidth and imageHeight
      const textureCoordinates = atlas.textureCoordinates[index];
      that._imageWidth = atlas.texture.width * textureCoordinates.width;
      that._imageHeight = atlas.texture.height * textureCoordinates.height;

      that._imageIndex = index;
      that._ready = true;
      that._image = undefined;
      that._imageIndexPromise = undefined;
      makeDirty$3(that, IMAGE_INDEX_INDEX$1);
    }

    if (defined(image)) {
      // No need to wait on imageIndexPromise since these have already been added to the atlas
      const index = atlas.getImageIndex(imageId);
      if (defined(index)) {
        completeImageLoad(index);
        return;
      }

      imageIndexPromise = atlas.addImage(imageId, image);
    }
    if (defined(imageSubRegion)) {
      imageIndexPromise = atlas.addSubRegion(imageId, imageSubRegion);
    }

    this._imageIndexPromise = imageIndexPromise;

    if (!defined(imageIndexPromise)) {
      return;
    }

    imageIndexPromise.then(completeImageLoad).catch(function (error) {
      console.error(`Error loading image for billboard: ${error}`);
      that._imageIndexPromise = undefined;
    });
  };

  /**
   * <p>
   * Sets the image to be used for this billboard.  If a texture has already been created for the
   * given id, the existing texture is used.
   * </p>
   * <p>
   * This function is useful for dynamically creating textures that are shared across many billboards.
   * Only the first billboard will actually call the function and create the texture, while subsequent
   * billboards created with the same id will simply re-use the existing texture.
   * </p>
   * <p>
   * To load an image from a URL, setting the {@link Billboard#image} property is more convenient.
   * </p>
   *
   * @param {String} id The id of the image.  This can be any string that uniquely identifies the image.
   * @param {HTMLImageElement|HTMLCanvasElement|String|Resource|Billboard.CreateImageCallback} image The image to load.  This parameter
   *        can either be a loaded Image or Canvas, a URL which will be loaded as an Image automatically,
   *        or a function which will be called to create the image if it hasn't been loaded already.
   * @example
   * // create a billboard image dynamically
   * function drawImage(id) {
   *   // create and draw an image using a canvas
   *   const canvas = document.createElement('canvas');
   *   const context2D = canvas.getContext('2d');
   *   // ... draw image
   *   return canvas;
   * }
   * // drawImage will be called to create the texture
   * b.setImage('myImage', drawImage);
   *
   * // subsequent billboards created in the same collection using the same id will use the existing
   * // texture, without the need to create the canvas or draw the image
   * b2.setImage('myImage', drawImage);
   */
  Billboard.prototype.setImage = function (id, image) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(id)) {
      throw new DeveloperError("id is required.");
    }
    if (!defined(image)) {
      throw new DeveloperError("image is required.");
    }
    //>>includeEnd('debug');

    if (this._imageId === id) {
      return;
    }

    this._imageIndex = -1;
    this._imageSubRegion = undefined;
    this._imageId = id;
    this._image = image;

    if (defined(this._billboardCollection._textureAtlas)) {
      this._loadImage();
    }
  };

  /**
   * Uses a sub-region of the image with the given id as the image for this billboard,
   * measured in pixels from the bottom-left.
   *
   * @param {String} id The id of the image to use.
   * @param {BoundingRectangle} subRegion The sub-region of the image.
   *
   * @exception {RuntimeError} image with id must be in the atlas
   */
  Billboard.prototype.setImageSubRegion = function (id, subRegion) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(id)) {
      throw new DeveloperError("id is required.");
    }
    if (!defined(subRegion)) {
      throw new DeveloperError("subRegion is required.");
    }
    //>>includeEnd('debug');

    if (
      this._imageId === id &&
      BoundingRectangle.equals(this._imageSubRegion, subRegion)
    ) {
      return;
    }

    this._imageIndex = -1;
    this._imageId = id;
    this._imageSubRegion = BoundingRectangle.clone(subRegion);

    if (defined(this._billboardCollection._textureAtlas)) {
      this._loadImage();
    }
  };

  Billboard.prototype._setTranslate = function (value) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(value)) {
      throw new DeveloperError("value is required.");
    }
    //>>includeEnd('debug');

    const translate = this._translate;
    if (!Cartesian2.equals(translate, value)) {
      Cartesian2.clone(value, translate);
      makeDirty$3(this, PIXEL_OFFSET_INDEX$1);
    }
  };

  Billboard.prototype._getActualPosition = function () {
    return defined(this._clampedPosition)
      ? this._clampedPosition
      : this._actualPosition;
  };

  Billboard.prototype._setActualPosition = function (value) {
    if (!defined(this._clampedPosition)) {
      Cartesian3.clone(value, this._actualPosition);
    }
    makeDirty$3(this, POSITION_INDEX$7);
  };

  const tempCartesian3$1 = new Cartesian4();
  Billboard._computeActualPosition = function (
    billboard,
    position,
    frameState,
    modelMatrix
  ) {
    if (defined(billboard._clampedPosition)) {
      if (frameState.mode !== billboard._mode) {
        billboard._updateClamping();
      }
      return billboard._clampedPosition;
    } else if (frameState.mode === SceneMode$1.SCENE3D) {
      return position;
    }

    Matrix4.multiplyByPoint(modelMatrix, position, tempCartesian3$1);
    return SceneTransforms.computeActualWgs84Position(frameState, tempCartesian3$1);
  };

  const scratchCartesian3$4 = new Cartesian3();

  // This function is basically a stripped-down JavaScript version of BillboardCollectionVS.glsl
  Billboard._computeScreenSpacePosition = function (
    modelMatrix,
    position,
    eyeOffset,
    pixelOffset,
    scene,
    result
  ) {
    // Model to world coordinates
    const positionWorld = Matrix4.multiplyByPoint(
      modelMatrix,
      position,
      scratchCartesian3$4
    );

    // World to window coordinates
    const positionWC = SceneTransforms.wgs84WithEyeOffsetToWindowCoordinates(
      scene,
      positionWorld,
      eyeOffset,
      result
    );
    if (!defined(positionWC)) {
      return undefined;
    }

    // Apply pixel offset
    Cartesian2.add(positionWC, pixelOffset, positionWC);

    return positionWC;
  };

  const scratchPixelOffset = new Cartesian2(0.0, 0.0);

  /**
   * Computes the screen-space position of the billboard's origin, taking into account eye and pixel offsets.
   * The screen space origin is the top, left corner of the canvas; <code>x</code> increases from
   * left to right, and <code>y</code> increases from top to bottom.
   *
   * @param {Scene} scene The scene.
   * @param {Cartesian2} [result] The object onto which to store the result.
   * @returns {Cartesian2} The screen-space position of the billboard.
   *
   * @exception {DeveloperError} Billboard must be in a collection.
   *
   * @example
   * console.log(b.computeScreenSpacePosition(scene).toString());
   *
   * @see Billboard#eyeOffset
   * @see Billboard#pixelOffset
   */
  Billboard.prototype.computeScreenSpacePosition = function (scene, result) {
    const billboardCollection = this._billboardCollection;
    if (!defined(result)) {
      result = new Cartesian2();
    }

    //>>includeStart('debug', pragmas.debug);
    if (!defined(billboardCollection)) {
      throw new DeveloperError(
        "Billboard must be in a collection.  Was it removed?"
      );
    }
    if (!defined(scene)) {
      throw new DeveloperError("scene is required.");
    }
    //>>includeEnd('debug');

    // pixel offset for screen space computation is the pixelOffset + screen space translate
    Cartesian2.clone(this._pixelOffset, scratchPixelOffset);
    Cartesian2.add(scratchPixelOffset, this._translate, scratchPixelOffset);

    let modelMatrix = billboardCollection.modelMatrix;
    let position = this._position;
    if (defined(this._clampedPosition)) {
      position = this._clampedPosition;
      if (scene.mode !== SceneMode$1.SCENE3D) {
        // position needs to be in world coordinates
        const projection = scene.mapProjection;
        const ellipsoid = projection.ellipsoid;
        const cart = projection.unproject(position, scratchCartographic$d);
        position = ellipsoid.cartographicToCartesian(cart, scratchCartesian3$4);
        modelMatrix = Matrix4.IDENTITY;
      }
    }

    const windowCoordinates = Billboard._computeScreenSpacePosition(
      modelMatrix,
      position,
      this._eyeOffset,
      scratchPixelOffset,
      scene,
      result
    );
    return windowCoordinates;
  };

  /**
   * Gets a billboard's screen space bounding box centered around screenSpacePosition.
   * @param {Billboard} billboard The billboard to get the screen space bounding box for.
   * @param {Cartesian2} screenSpacePosition The screen space center of the label.
   * @param {BoundingRectangle} [result] The object onto which to store the result.
   * @returns {BoundingRectangle} The screen space bounding box.
   *
   * @private
   */
  Billboard.getScreenSpaceBoundingBox = function (
    billboard,
    screenSpacePosition,
    result
  ) {
    let width = billboard.width;
    let height = billboard.height;

    const scale = billboard.scale;
    width *= scale;
    height *= scale;

    let x = screenSpacePosition.x;
    if (billboard.horizontalOrigin === HorizontalOrigin$1.RIGHT) {
      x -= width;
    } else if (billboard.horizontalOrigin === HorizontalOrigin$1.CENTER) {
      x -= width * 0.5;
    }

    let y = screenSpacePosition.y;
    if (
      billboard.verticalOrigin === VerticalOrigin$1.BOTTOM ||
      billboard.verticalOrigin === VerticalOrigin$1.BASELINE
    ) {
      y -= height;
    } else if (billboard.verticalOrigin === VerticalOrigin$1.CENTER) {
      y -= height * 0.5;
    }

    if (!defined(result)) {
      result = new BoundingRectangle();
    }

    result.x = x;
    result.y = y;
    result.width = width;
    result.height = height;

    return result;
  };

  /**
   * Determines if this billboard equals another billboard.  Billboards are equal if all their properties
   * are equal.  Billboards in different collections can be equal.
   *
   * @param {Billboard} other The billboard to compare for equality.
   * @returns {Boolean} <code>true</code> if the billboards are equal; otherwise, <code>false</code>.
   */
  Billboard.prototype.equals = function (other) {
    return (
      this === other ||
      (defined(other) &&
        this._id === other._id &&
        Cartesian3.equals(this._position, other._position) &&
        this._imageId === other._imageId &&
        this._show === other._show &&
        this._scale === other._scale &&
        this._verticalOrigin === other._verticalOrigin &&
        this._horizontalOrigin === other._horizontalOrigin &&
        this._heightReference === other._heightReference &&
        BoundingRectangle.equals(this._imageSubRegion, other._imageSubRegion) &&
        Color.equals(this._color, other._color) &&
        Cartesian2.equals(this._pixelOffset, other._pixelOffset) &&
        Cartesian2.equals(this._translate, other._translate) &&
        Cartesian3.equals(this._eyeOffset, other._eyeOffset) &&
        NearFarScalar.equals(this._scaleByDistance, other._scaleByDistance) &&
        NearFarScalar.equals(
          this._translucencyByDistance,
          other._translucencyByDistance
        ) &&
        NearFarScalar.equals(
          this._pixelOffsetScaleByDistance,
          other._pixelOffsetScaleByDistance
        ) &&
        DistanceDisplayCondition.equals(
          this._distanceDisplayCondition,
          other._distanceDisplayCondition
        ) &&
        this._disableDepthTestDistance === other._disableDepthTestDistance)
    );
  };

  Billboard.prototype._destroy = function () {
    if (defined(this._customData)) {
      this._billboardCollection._scene.globe._surface.removeTileCustomData(
        this._customData
      );
      this._customData = undefined;
    }

    if (defined(this._removeCallbackFunc)) {
      this._removeCallbackFunc();
      this._removeCallbackFunc = undefined;
    }

    this.image = undefined;
    this._pickId = this._pickId && this._pickId.destroy();
    this._billboardCollection = undefined;
  };

  /**
   * Determines how opaque and translucent parts of billboards, points, and labels are blended with the scene.
   *
   * @enum {Number}
   */
  const BlendOption = {
    /**
     * The billboards, points, or labels in the collection are completely opaque.
     * @type {Number}
     * @constant
     */
    OPAQUE: 0,

    /**
     * The billboards, points, or labels in the collection are completely translucent.
     * @type {Number}
     * @constant
     */
    TRANSLUCENT: 1,

    /**
     * The billboards, points, or labels in the collection are both opaque and translucent.
     * @type {Number}
     * @constant
     */
    OPAQUE_AND_TRANSLUCENT: 2,
  };
  var BlendOption$1 = Object.freeze(BlendOption);

  /**
   * Settings for the generation of signed distance field glyphs
   *
   * @private
   */
  const SDFSettings = {
    /**
     * The font size in pixels
     *
     * @type {Number}
     * @constant
     */
    FONT_SIZE: 48.0,

    /**
     * Whitespace padding around glyphs.
     *
     * @type {Number}
     * @constant
     */
    PADDING: 10.0,

    /**
     * How many pixels around the glyph shape to use for encoding distance
     *
     * @type {Number}
     * @constant
     */
    RADIUS: 8.0,

    /**
     * How much of the radius (relative) is used for the inside part the glyph.
     *
     * @type {Number}
     * @constant
     */
    CUTOFF: 0.25,
  };
  var SDFSettings$1 = Object.freeze(SDFSettings);

  // The atlas is made up of regions of space called nodes that contain images or child nodes.
  function TextureAtlasNode(
    bottomLeft,
    topRight,
    childNode1,
    childNode2,
    imageIndex
  ) {
    this.bottomLeft = defaultValue(bottomLeft, Cartesian2.ZERO);
    this.topRight = defaultValue(topRight, Cartesian2.ZERO);
    this.childNode1 = childNode1;
    this.childNode2 = childNode2;
    this.imageIndex = imageIndex;
  }

  const defaultInitialSize = new Cartesian2(16.0, 16.0);

  /**
   * A TextureAtlas stores multiple images in one square texture and keeps
   * track of the texture coordinates for each image. TextureAtlas is dynamic,
   * meaning new images can be added at any point in time.
   * Texture coordinates are subject to change if the texture atlas resizes, so it is
   * important to check {@link TextureAtlas#getGUID} before using old values.
   *
   * @alias TextureAtlas
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Scene} options.context The context in which the texture gets created.
   * @param {PixelFormat} [options.pixelFormat=PixelFormat.RGBA] The pixel format of the texture.
   * @param {Number} [options.borderWidthInPixels=1] The amount of spacing between adjacent images in pixels.
   * @param {Cartesian2} [options.initialSize=new Cartesian2(16.0, 16.0)] The initial side lengths of the texture.
   *
   * @exception {DeveloperError} borderWidthInPixels must be greater than or equal to zero.
   * @exception {DeveloperError} initialSize must be greater than zero.
   *
   * @private
   */
  function TextureAtlas(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const borderWidthInPixels = defaultValue(options.borderWidthInPixels, 1.0);
    const initialSize = defaultValue(options.initialSize, defaultInitialSize);

    //>>includeStart('debug', pragmas.debug);
    if (!defined(options.context)) {
      throw new DeveloperError("context is required.");
    }
    if (borderWidthInPixels < 0) {
      throw new DeveloperError(
        "borderWidthInPixels must be greater than or equal to zero."
      );
    }
    if (initialSize.x < 1 || initialSize.y < 1) {
      throw new DeveloperError("initialSize must be greater than zero.");
    }
    //>>includeEnd('debug');

    this._context = options.context;
    this._pixelFormat = defaultValue(options.pixelFormat, PixelFormat$1.RGBA);
    this._borderWidthInPixels = borderWidthInPixels;
    this._textureCoordinates = [];
    this._guid = createGuid();
    this._idHash = {};
    this._indexHash = {};
    this._initialSize = initialSize;

    this._root = undefined;
  }

  Object.defineProperties(TextureAtlas.prototype, {
    /**
     * The amount of spacing between adjacent images in pixels.
     * @memberof TextureAtlas.prototype
     * @type {Number}
     */
    borderWidthInPixels: {
      get: function () {
        return this._borderWidthInPixels;
      },
    },

    /**
     * An array of {@link BoundingRectangle} texture coordinate regions for all the images in the texture atlas.
     * The x and y values of the rectangle correspond to the bottom-left corner of the texture coordinate.
     * The coordinates are in the order that the corresponding images were added to the atlas.
     * @memberof TextureAtlas.prototype
     * @type {BoundingRectangle[]}
     */
    textureCoordinates: {
      get: function () {
        return this._textureCoordinates;
      },
    },

    /**
     * The texture that all of the images are being written to.
     * @memberof TextureAtlas.prototype
     * @type {Texture}
     */
    texture: {
      get: function () {
        if (!defined(this._texture)) {
          this._texture = new Texture({
            context: this._context,
            width: this._initialSize.x,
            height: this._initialSize.y,
            pixelFormat: this._pixelFormat,
          });
        }
        return this._texture;
      },
    },

    /**
     * The number of images in the texture atlas. This value increases
     * every time addImage or addImages is called.
     * Texture coordinates are subject to change if the texture atlas resizes, so it is
     * important to check {@link TextureAtlas#getGUID} before using old values.
     * @memberof TextureAtlas.prototype
     * @type {Number}
     */
    numberOfImages: {
      get: function () {
        return this._textureCoordinates.length;
      },
    },

    /**
     * The atlas' globally unique identifier (GUID).
     * The GUID changes whenever the texture atlas is modified.
     * Classes that use a texture atlas should check if the GUID
     * has changed before processing the atlas data.
     * @memberof TextureAtlas.prototype
     * @type {String}
     */
    guid: {
      get: function () {
        return this._guid;
      },
    },
  });

  // Builds a larger texture and copies the old texture into the new one.
  function resizeAtlas(textureAtlas, image) {
    const context = textureAtlas._context;
    const numImages = textureAtlas.numberOfImages;
    const scalingFactor = 2.0;
    const borderWidthInPixels = textureAtlas._borderWidthInPixels;
    if (numImages > 0) {
      const oldAtlasWidth = textureAtlas._texture.width;
      const oldAtlasHeight = textureAtlas._texture.height;
      const atlasWidth =
        scalingFactor * (oldAtlasWidth + image.width + borderWidthInPixels);
      const atlasHeight =
        scalingFactor * (oldAtlasHeight + image.height + borderWidthInPixels);
      const widthRatio = oldAtlasWidth / atlasWidth;
      const heightRatio = oldAtlasHeight / atlasHeight;

      // Create new node structure, putting the old root node in the bottom left.
      const nodeBottomRight = new TextureAtlasNode(
        new Cartesian2(oldAtlasWidth + borderWidthInPixels, borderWidthInPixels),
        new Cartesian2(atlasWidth, oldAtlasHeight)
      );
      const nodeBottomHalf = new TextureAtlasNode(
        new Cartesian2(),
        new Cartesian2(atlasWidth, oldAtlasHeight),
        textureAtlas._root,
        nodeBottomRight
      );
      const nodeTopHalf = new TextureAtlasNode(
        new Cartesian2(borderWidthInPixels, oldAtlasHeight + borderWidthInPixels),
        new Cartesian2(atlasWidth, atlasHeight)
      );
      const nodeMain = new TextureAtlasNode(
        new Cartesian2(),
        new Cartesian2(atlasWidth, atlasHeight),
        nodeBottomHalf,
        nodeTopHalf
      );

      // Resize texture coordinates.
      for (let i = 0; i < textureAtlas._textureCoordinates.length; i++) {
        const texCoord = textureAtlas._textureCoordinates[i];
        if (defined(texCoord)) {
          texCoord.x *= widthRatio;
          texCoord.y *= heightRatio;
          texCoord.width *= widthRatio;
          texCoord.height *= heightRatio;
        }
      }

      // Copy larger texture.
      const newTexture = new Texture({
        context: textureAtlas._context,
        width: atlasWidth,
        height: atlasHeight,
        pixelFormat: textureAtlas._pixelFormat,
      });

      const framebuffer = new Framebuffer({
        context: context,
        colorTextures: [textureAtlas._texture],
        destroyAttachments: false,
      });

      framebuffer._bind();
      newTexture.copyFromFramebuffer(0, 0, 0, 0, atlasWidth, atlasHeight);
      framebuffer._unBind();
      framebuffer.destroy();
      textureAtlas._texture =
        textureAtlas._texture && textureAtlas._texture.destroy();
      textureAtlas._texture = newTexture;
      textureAtlas._root = nodeMain;
    } else {
      // First image exceeds initialSize
      let initialWidth = scalingFactor * (image.width + 2 * borderWidthInPixels);
      let initialHeight =
        scalingFactor * (image.height + 2 * borderWidthInPixels);
      if (initialWidth < textureAtlas._initialSize.x) {
        initialWidth = textureAtlas._initialSize.x;
      }
      if (initialHeight < textureAtlas._initialSize.y) {
        initialHeight = textureAtlas._initialSize.y;
      }
      textureAtlas._texture =
        textureAtlas._texture && textureAtlas._texture.destroy();
      textureAtlas._texture = new Texture({
        context: textureAtlas._context,
        width: initialWidth,
        height: initialHeight,
        pixelFormat: textureAtlas._pixelFormat,
      });
      textureAtlas._root = new TextureAtlasNode(
        new Cartesian2(borderWidthInPixels, borderWidthInPixels),
        new Cartesian2(initialWidth, initialHeight)
      );
    }
  }

  // A recursive function that finds the best place to insert
  // a new image based on existing image 'nodes'.
  // Inspired by: http://blackpawn.com/texts/lightmaps/default.html
  function findNode(textureAtlas, node, image) {
    if (!defined(node)) {
      return undefined;
    }

    // If a leaf node
    if (!defined(node.childNode1) && !defined(node.childNode2)) {
      // Node already contains an image, don't add to it.
      if (defined(node.imageIndex)) {
        return undefined;
      }

      const nodeWidth = node.topRight.x - node.bottomLeft.x;
      const nodeHeight = node.topRight.y - node.bottomLeft.y;
      const widthDifference = nodeWidth - image.width;
      const heightDifference = nodeHeight - image.height;

      // Node is smaller than the image.
      if (widthDifference < 0 || heightDifference < 0) {
        return undefined;
      }

      // If the node is the same size as the image, return the node
      if (widthDifference === 0 && heightDifference === 0) {
        return node;
      }

      // Vertical split (childNode1 = left half, childNode2 = right half).
      if (widthDifference > heightDifference) {
        node.childNode1 = new TextureAtlasNode(
          new Cartesian2(node.bottomLeft.x, node.bottomLeft.y),
          new Cartesian2(node.bottomLeft.x + image.width, node.topRight.y)
        );
        // Only make a second child if the border gives enough space.
        const childNode2BottomLeftX =
          node.bottomLeft.x + image.width + textureAtlas._borderWidthInPixels;
        if (childNode2BottomLeftX < node.topRight.x) {
          node.childNode2 = new TextureAtlasNode(
            new Cartesian2(childNode2BottomLeftX, node.bottomLeft.y),
            new Cartesian2(node.topRight.x, node.topRight.y)
          );
        }
      }
      // Horizontal split (childNode1 = bottom half, childNode2 = top half).
      else {
        node.childNode1 = new TextureAtlasNode(
          new Cartesian2(node.bottomLeft.x, node.bottomLeft.y),
          new Cartesian2(node.topRight.x, node.bottomLeft.y + image.height)
        );
        // Only make a second child if the border gives enough space.
        const childNode2BottomLeftY =
          node.bottomLeft.y + image.height + textureAtlas._borderWidthInPixels;
        if (childNode2BottomLeftY < node.topRight.y) {
          node.childNode2 = new TextureAtlasNode(
            new Cartesian2(node.bottomLeft.x, childNode2BottomLeftY),
            new Cartesian2(node.topRight.x, node.topRight.y)
          );
        }
      }
      return findNode(textureAtlas, node.childNode1, image);
    }

    // If not a leaf node
    return (
      findNode(textureAtlas, node.childNode1, image) ||
      findNode(textureAtlas, node.childNode2, image)
    );
  }

  // Adds image of given index to the texture atlas. Called from addImage and addImages.
  function addImage(textureAtlas, image, index) {
    const node = findNode(textureAtlas, textureAtlas._root, image);
    if (defined(node)) {
      // Found a node that can hold the image.
      node.imageIndex = index;

      // Add texture coordinate and write to texture
      const atlasWidth = textureAtlas._texture.width;
      const atlasHeight = textureAtlas._texture.height;
      const nodeWidth = node.topRight.x - node.bottomLeft.x;
      const nodeHeight = node.topRight.y - node.bottomLeft.y;
      const x = node.bottomLeft.x / atlasWidth;
      const y = node.bottomLeft.y / atlasHeight;
      const w = nodeWidth / atlasWidth;
      const h = nodeHeight / atlasHeight;
      textureAtlas._textureCoordinates[index] = new BoundingRectangle(x, y, w, h);
      textureAtlas._texture.copyFrom({
        source: image,
        xOffset: node.bottomLeft.x,
        yOffset: node.bottomLeft.y,
      });
    } else {
      // No node found, must resize the texture atlas.
      resizeAtlas(textureAtlas, image);
      addImage(textureAtlas, image, index);
    }

    textureAtlas._guid = createGuid();
  }

  function getIndex$1(atlas, image) {
    if (!defined(atlas) || atlas.isDestroyed()) {
      return -1;
    }

    const index = atlas.numberOfImages;

    addImage(atlas, image, index);

    return index;
  }

  /**
   * If the image is already in the atlas, the existing index is returned. Otherwise, the result is undefined.
   *
   * @param {String} id An identifier to detect whether the image already exists in the atlas.
   * @returns {Number|undefined} The image index, or undefined if the image does not exist in the atlas.
   */
  TextureAtlas.prototype.getImageIndex = function (id) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(id)) {
      throw new DeveloperError("id is required.");
    }
    //>>includeEnd('debug');

    return this._indexHash[id];
  };

  /**
   * Adds an image to the atlas synchronously.  If the image is already in the atlas, the atlas is unchanged and
   * the existing index is used.
   *
   * @param {String} id An identifier to detect whether the image already exists in the atlas.
   * @param {HTMLImageElement|HTMLCanvasElement} image An image or canvas to add to the texture atlas.
   * @returns {Number} The image index.
   */
  TextureAtlas.prototype.addImageSync = function (id, image) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(id)) {
      throw new DeveloperError("id is required.");
    }
    if (!defined(image)) {
      throw new DeveloperError("image is required.");
    }
    //>>includeEnd('debug');

    let index = this._indexHash[id];
    if (defined(index)) {
      // we're already aware of this source
      return index;
    }

    index = getIndex$1(this, image);
    // store the promise
    this._idHash[id] = Promise.resolve(index);
    this._indexHash[id] = index;
    // but return the value synchronously
    return index;
  };

  /**
   * Adds an image to the atlas.  If the image is already in the atlas, the atlas is unchanged and
   * the existing index is used.
   *
   * @param {String} id An identifier to detect whether the image already exists in the atlas.
   * @param {HTMLImageElement|HTMLCanvasElement|String|Resource|Promise|TextureAtlas.CreateImageCallback} image An image or canvas to add to the texture atlas,
   *        or a URL to an Image, or a Promise for an image, or a function that creates an image.
   * @returns {Promise.<Number>} A Promise for the image index.
   */
  TextureAtlas.prototype.addImage = function (id, image) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(id)) {
      throw new DeveloperError("id is required.");
    }
    if (!defined(image)) {
      throw new DeveloperError("image is required.");
    }
    //>>includeEnd('debug');

    let indexPromise = this._idHash[id];
    if (defined(indexPromise)) {
      // we're already aware of this source
      return indexPromise;
    }

    // not in atlas, create the promise for the index

    if (typeof image === "function") {
      // if image is a function, call it
      image = image(id);
      //>>includeStart('debug', pragmas.debug);
      if (!defined(image)) {
        throw new DeveloperError("image is required.");
      }
      //>>includeEnd('debug');
    } else if (typeof image === "string" || image instanceof Resource) {
      // Get a resource
      const resource = Resource.createIfNeeded(image);
      image = resource.fetchImage();
    }

    const that = this;
    indexPromise = Promise.resolve(image).then(function (image) {
      const index = getIndex$1(that, image);
      that._indexHash[id] = index;
      return index;
    });

    // store the promise
    this._idHash[id] = indexPromise;

    return indexPromise;
  };

  /**
   * Add a sub-region of an existing atlas image as additional image indices.
   *
   * @param {String} id The identifier of the existing image.
   * @param {BoundingRectangle} subRegion An {@link BoundingRectangle} sub-region measured in pixels from the bottom-left.
   *
   * @returns {Promise.<Number>} A Promise for the image index.
   */
  TextureAtlas.prototype.addSubRegion = function (id, subRegion) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(id)) {
      throw new DeveloperError("id is required.");
    }
    if (!defined(subRegion)) {
      throw new DeveloperError("subRegion is required.");
    }
    //>>includeEnd('debug');

    const indexPromise = this._idHash[id];
    if (!defined(indexPromise)) {
      throw new RuntimeError(`image with id "${id}" not found in the atlas.`);
    }

    const that = this;
    return Promise.resolve(indexPromise).then(function (index) {
      if (index === -1) {
        // the atlas is destroyed
        return -1;
      }
      const atlasWidth = that._texture.width;
      const atlasHeight = that._texture.height;
      const numImages = that.numberOfImages;

      const baseRegion = that._textureCoordinates[index];
      const x = baseRegion.x + subRegion.x / atlasWidth;
      const y = baseRegion.y + subRegion.y / atlasHeight;
      const w = subRegion.width / atlasWidth;
      const h = subRegion.height / atlasHeight;
      that._textureCoordinates.push(new BoundingRectangle(x, y, w, h));
      that._guid = createGuid();

      return numImages;
    });
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} True if this object was destroyed; otherwise, false.
   *
   * @see TextureAtlas#destroy
   */
  TextureAtlas.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * atlas = atlas && atlas.destroy();
   *
   * @see TextureAtlas#isDestroyed
   */
  TextureAtlas.prototype.destroy = function () {
    this._texture = this._texture && this._texture.destroy();
    return destroyObject(this);
  };

  const SHOW_INDEX$6 = Billboard.SHOW_INDEX;
  const POSITION_INDEX$6 = Billboard.POSITION_INDEX;
  const PIXEL_OFFSET_INDEX = Billboard.PIXEL_OFFSET_INDEX;
  const EYE_OFFSET_INDEX = Billboard.EYE_OFFSET_INDEX;
  const HORIZONTAL_ORIGIN_INDEX = Billboard.HORIZONTAL_ORIGIN_INDEX;
  const VERTICAL_ORIGIN_INDEX = Billboard.VERTICAL_ORIGIN_INDEX;
  const SCALE_INDEX$2 = Billboard.SCALE_INDEX;
  const IMAGE_INDEX_INDEX = Billboard.IMAGE_INDEX_INDEX;
  const COLOR_INDEX$4 = Billboard.COLOR_INDEX;
  const ROTATION_INDEX = Billboard.ROTATION_INDEX;
  const ALIGNED_AXIS_INDEX = Billboard.ALIGNED_AXIS_INDEX;
  const SCALE_BY_DISTANCE_INDEX$2 = Billboard.SCALE_BY_DISTANCE_INDEX;
  const TRANSLUCENCY_BY_DISTANCE_INDEX$2 = Billboard.TRANSLUCENCY_BY_DISTANCE_INDEX;
  const PIXEL_OFFSET_SCALE_BY_DISTANCE_INDEX =
    Billboard.PIXEL_OFFSET_SCALE_BY_DISTANCE_INDEX;
  const DISTANCE_DISPLAY_CONDITION_INDEX$2 = Billboard.DISTANCE_DISPLAY_CONDITION;
  const DISABLE_DEPTH_DISTANCE = Billboard.DISABLE_DEPTH_DISTANCE;
  const TEXTURE_COORDINATE_BOUNDS = Billboard.TEXTURE_COORDINATE_BOUNDS;
  const SDF_INDEX = Billboard.SDF_INDEX;
  const NUMBER_OF_PROPERTIES$4 = Billboard.NUMBER_OF_PROPERTIES;

  let attributeLocations$6;

  const attributeLocationsBatched$1 = {
    positionHighAndScale: 0,
    positionLowAndRotation: 1,
    compressedAttribute0: 2, // pixel offset, translate, horizontal origin, vertical origin, show, direction, texture coordinates
    compressedAttribute1: 3, // aligned axis, translucency by distance, image width
    compressedAttribute2: 4, // image height, color, pick color, size in meters, valid aligned axis, 13 bits free
    eyeOffset: 5, // 4 bytes free
    scaleByDistance: 6,
    pixelOffsetScaleByDistance: 7,
    compressedAttribute3: 8,
    textureCoordinateBoundsOrLabelTranslate: 9,
    a_batchId: 10,
    sdf: 11,
  };

  const attributeLocationsInstanced$1 = {
    direction: 0,
    positionHighAndScale: 1,
    positionLowAndRotation: 2, // texture offset in w
    compressedAttribute0: 3,
    compressedAttribute1: 4,
    compressedAttribute2: 5,
    eyeOffset: 6, // texture range in w
    scaleByDistance: 7,
    pixelOffsetScaleByDistance: 8,
    compressedAttribute3: 9,
    textureCoordinateBoundsOrLabelTranslate: 10,
    a_batchId: 11,
    sdf: 12,
  };

  /**
   * A renderable collection of billboards.  Billboards are viewport-aligned
   * images positioned in the 3D scene.
   * <br /><br />
   * <div align='center'>
   * <img src='Images/Billboard.png' width='400' height='300' /><br />
   * Example billboards
   * </div>
   * <br /><br />
   * Billboards are added and removed from the collection using {@link BillboardCollection#add}
   * and {@link BillboardCollection#remove}.  Billboards in a collection automatically share textures
   * for images with the same identifier.
   *
   * @alias BillboardCollection
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] The 4x4 transformation matrix that transforms each billboard from model to world coordinates.
   * @param {Boolean} [options.debugShowBoundingVolume=false] For debugging only. Determines if this primitive's commands' bounding spheres are shown.
   * @param {Scene} [options.scene] Must be passed in for billboards that use the height reference property or will be depth tested against the globe.
   * @param {BlendOption} [options.blendOption=BlendOption.OPAQUE_AND_TRANSLUCENT] The billboard blending option. The default
   * is used for rendering both opaque and translucent billboards. However, if either all of the billboards are completely opaque or all are completely translucent,
   * setting the technique to BlendOption.OPAQUE or BlendOption.TRANSLUCENT can improve performance by up to 2x.
   * @param {Boolean} [options.show=true] Determines if the billboards in the collection will be shown.
   *
   * @performance For best performance, prefer a few collections, each with many billboards, to
   * many collections with only a few billboards each.  Organize collections so that billboards
   * with the same update frequency are in the same collection, i.e., billboards that do not
   * change should be in one collection; billboards that change every frame should be in another
   * collection; and so on.
   *
   * @see BillboardCollection#add
   * @see BillboardCollection#remove
   * @see Billboard
   * @see LabelCollection
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Billboards.html|Cesium Sandcastle Billboard Demo}
   *
   * @example
   * // Create a billboard collection with two billboards
   * const billboards = scene.primitives.add(new Cesium.BillboardCollection());
   * billboards.add({
   *   position : new Cesium.Cartesian3(1.0, 2.0, 3.0),
   *   image : 'url/to/image'
   * });
   * billboards.add({
   *   position : new Cesium.Cartesian3(4.0, 5.0, 6.0),
   *   image : 'url/to/another/image'
   * });
   */
  function BillboardCollection(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    this._scene = options.scene;
    this._batchTable = options.batchTable;

    this._textureAtlas = undefined;
    this._textureAtlasGUID = undefined;
    this._destroyTextureAtlas = true;
    this._sp = undefined;
    this._spTranslucent = undefined;
    this._rsOpaque = undefined;
    this._rsTranslucent = undefined;
    this._vaf = undefined;

    this._billboards = [];
    this._billboardsToUpdate = [];
    this._billboardsToUpdateIndex = 0;
    this._billboardsRemoved = false;
    this._createVertexArray = false;

    this._shaderRotation = false;
    this._compiledShaderRotation = false;

    this._shaderAlignedAxis = false;
    this._compiledShaderAlignedAxis = false;

    this._shaderScaleByDistance = false;
    this._compiledShaderScaleByDistance = false;

    this._shaderTranslucencyByDistance = false;
    this._compiledShaderTranslucencyByDistance = false;

    this._shaderPixelOffsetScaleByDistance = false;
    this._compiledShaderPixelOffsetScaleByDistance = false;

    this._shaderDistanceDisplayCondition = false;
    this._compiledShaderDistanceDisplayCondition = false;

    this._shaderDisableDepthDistance = false;
    this._compiledShaderDisableDepthDistance = false;

    this._shaderClampToGround = false;
    this._compiledShaderClampToGround = false;

    this._propertiesChanged = new Uint32Array(NUMBER_OF_PROPERTIES$4);

    this._maxSize = 0.0;
    this._maxEyeOffset = 0.0;
    this._maxScale = 1.0;
    this._maxPixelOffset = 0.0;
    this._allHorizontalCenter = true;
    this._allVerticalCenter = true;
    this._allSizedInMeters = true;

    this._baseVolume = new BoundingSphere();
    this._baseVolumeWC = new BoundingSphere();
    this._baseVolume2D = new BoundingSphere();
    this._boundingVolume = new BoundingSphere();
    this._boundingVolumeDirty = false;

    this._colorCommands = [];

    /**
     * Determines if billboards in this collection will be shown.
     *
     * @type {Boolean}
     * @default true
     */
    this.show = defaultValue(options.show, true);

    /**
     * The 4x4 transformation matrix that transforms each billboard in this collection from model to world coordinates.
     * When this is the identity matrix, the billboards are drawn in world coordinates, i.e., Earth's WGS84 coordinates.
     * Local reference frames can be used by providing a different transformation matrix, like that returned
     * by {@link Transforms.eastNorthUpToFixedFrame}.
     *
     * @type {Matrix4}
     * @default {@link Matrix4.IDENTITY}
     *
     *
     * @example
     * const center = Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883);
     * billboards.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(center);
     * billboards.add({
     *   image : 'url/to/image',
     *   position : new Cesium.Cartesian3(0.0, 0.0, 0.0) // center
     * });
     * billboards.add({
     *   image : 'url/to/image',
     *   position : new Cesium.Cartesian3(1000000.0, 0.0, 0.0) // east
     * });
     * billboards.add({
     *   image : 'url/to/image',
     *   position : new Cesium.Cartesian3(0.0, 1000000.0, 0.0) // north
     * });
     * billboards.add({
     *   image : 'url/to/image',
     *   position : new Cesium.Cartesian3(0.0, 0.0, 1000000.0) // up
     * });
     *
     * @see Transforms.eastNorthUpToFixedFrame
     */
    this.modelMatrix = Matrix4.clone(
      defaultValue(options.modelMatrix, Matrix4.IDENTITY)
    );
    this._modelMatrix = Matrix4.clone(Matrix4.IDENTITY);

    /**
     * This property is for debugging only; it is not for production use nor is it optimized.
     * <p>
     * Draws the bounding sphere for each draw command in the primitive.
     * </p>
     *
     * @type {Boolean}
     *
     * @default false
     */
    this.debugShowBoundingVolume = defaultValue(
      options.debugShowBoundingVolume,
      false
    );

    /**
     * This property is for debugging only; it is not for production use nor is it optimized.
     * <p>
     * Draws the texture atlas for this BillboardCollection as a fullscreen quad.
     * </p>
     *
     * @type {Boolean}
     *
     * @default false
     */
    this.debugShowTextureAtlas = defaultValue(
      options.debugShowTextureAtlas,
      false
    );

    /**
     * The billboard blending option. The default is used for rendering both opaque and translucent billboards.
     * However, if either all of the billboards are completely opaque or all are completely translucent,
     * setting the technique to BlendOption.OPAQUE or BlendOption.TRANSLUCENT can improve
     * performance by up to 2x.
     * @type {BlendOption}
     * @default BlendOption.OPAQUE_AND_TRANSLUCENT
     */
    this.blendOption = defaultValue(
      options.blendOption,
      BlendOption$1.OPAQUE_AND_TRANSLUCENT
    );
    this._blendOption = undefined;

    this._mode = SceneMode$1.SCENE3D;

    // The buffer usage for each attribute is determined based on the usage of the attribute over time.
    this._buffersUsage = [
      BufferUsage$1.STATIC_DRAW, // SHOW_INDEX
      BufferUsage$1.STATIC_DRAW, // POSITION_INDEX
      BufferUsage$1.STATIC_DRAW, // PIXEL_OFFSET_INDEX
      BufferUsage$1.STATIC_DRAW, // EYE_OFFSET_INDEX
      BufferUsage$1.STATIC_DRAW, // HORIZONTAL_ORIGIN_INDEX
      BufferUsage$1.STATIC_DRAW, // VERTICAL_ORIGIN_INDEX
      BufferUsage$1.STATIC_DRAW, // SCALE_INDEX
      BufferUsage$1.STATIC_DRAW, // IMAGE_INDEX_INDEX
      BufferUsage$1.STATIC_DRAW, // COLOR_INDEX
      BufferUsage$1.STATIC_DRAW, // ROTATION_INDEX
      BufferUsage$1.STATIC_DRAW, // ALIGNED_AXIS_INDEX
      BufferUsage$1.STATIC_DRAW, // SCALE_BY_DISTANCE_INDEX
      BufferUsage$1.STATIC_DRAW, // TRANSLUCENCY_BY_DISTANCE_INDEX
      BufferUsage$1.STATIC_DRAW, // PIXEL_OFFSET_SCALE_BY_DISTANCE_INDEX
      BufferUsage$1.STATIC_DRAW, // DISTANCE_DISPLAY_CONDITION_INDEX
      BufferUsage$1.STATIC_DRAW, // TEXTURE_COORDINATE_BOUNDS
    ];

    this._highlightColor = Color.clone(Color.WHITE); // Only used by Vector3DTilePoints

    const that = this;
    this._uniforms = {
      u_atlas: function () {
        return that._textureAtlas.texture;
      },
      u_highlightColor: function () {
        return that._highlightColor;
      },
    };

    const scene = this._scene;
    if (defined(scene) && defined(scene.terrainProviderChanged)) {
      this._removeCallbackFunc = scene.terrainProviderChanged.addEventListener(
        function () {
          const billboards = this._billboards;
          const length = billboards.length;
          for (let i = 0; i < length; ++i) {
            if (defined(billboards[i])) {
              billboards[i]._updateClamping();
            }
          }
        },
        this
      );
    }
  }

  Object.defineProperties(BillboardCollection.prototype, {
    /**
     * Returns the number of billboards in this collection.  This is commonly used with
     * {@link BillboardCollection#get} to iterate over all the billboards
     * in the collection.
     * @memberof BillboardCollection.prototype
     * @type {Number}
     */
    length: {
      get: function () {
        removeBillboards(this);
        return this._billboards.length;
      },
    },

    /**
     * Gets or sets the textureAtlas.
     * @memberof BillboardCollection.prototype
     * @type {TextureAtlas}
     * @private
     */
    textureAtlas: {
      get: function () {
        return this._textureAtlas;
      },
      set: function (value) {
        if (this._textureAtlas !== value) {
          this._textureAtlas =
            this._destroyTextureAtlas &&
            this._textureAtlas &&
            this._textureAtlas.destroy();
          this._textureAtlas = value;
          this._createVertexArray = true; // New per-billboard texture coordinates
        }
      },
    },

    /**
     * Gets or sets a value which determines if the texture atlas is
     * destroyed when the collection is destroyed.
     *
     * If the texture atlas is used by more than one collection, set this to <code>false</code>,
     * and explicitly destroy the atlas to avoid attempting to destroy it multiple times.
     *
     * @memberof BillboardCollection.prototype
     * @type {Boolean}
     * @private
     *
     * @example
     * // Set destroyTextureAtlas
     * // Destroy a billboard collection but not its texture atlas.
     *
     * const atlas = new TextureAtlas({
     *   scene : scene,
     *   images : images
     * });
     * billboards.textureAtlas = atlas;
     * billboards.destroyTextureAtlas = false;
     * billboards = billboards.destroy();
     * console.log(atlas.isDestroyed()); // False
     */
    destroyTextureAtlas: {
      get: function () {
        return this._destroyTextureAtlas;
      },
      set: function (value) {
        this._destroyTextureAtlas = value;
      },
    },
  });

  function destroyBillboards(billboards) {
    const length = billboards.length;
    for (let i = 0; i < length; ++i) {
      if (billboards[i]) {
        billboards[i]._destroy();
      }
    }
  }

  /**
   * Creates and adds a billboard with the specified initial properties to the collection.
   * The added billboard is returned so it can be modified or removed from the collection later.
   *
   * @param {Object}[options] A template describing the billboard's properties as shown in Example 1.
   * @returns {Billboard} The billboard that was added to the collection.
   *
   * @performance Calling <code>add</code> is expected constant time.  However, the collection's vertex buffer
   * is rewritten - an <code>O(n)</code> operation that also incurs CPU to GPU overhead.  For
   * best performance, add as many billboards as possible before calling <code>update</code>.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * // Example 1:  Add a billboard, specifying all the default values.
   * const b = billboards.add({
   *   show : true,
   *   position : Cesium.Cartesian3.ZERO,
   *   pixelOffset : Cesium.Cartesian2.ZERO,
   *   eyeOffset : Cesium.Cartesian3.ZERO,
   *   heightReference : Cesium.HeightReference.NONE,
   *   horizontalOrigin : Cesium.HorizontalOrigin.CENTER,
   *   verticalOrigin : Cesium.VerticalOrigin.CENTER,
   *   scale : 1.0,
   *   image : 'url/to/image',
   *   imageSubRegion : undefined,
   *   color : Cesium.Color.WHITE,
   *   id : undefined,
   *   rotation : 0.0,
   *   alignedAxis : Cesium.Cartesian3.ZERO,
   *   width : undefined,
   *   height : undefined,
   *   scaleByDistance : undefined,
   *   translucencyByDistance : undefined,
   *   pixelOffsetScaleByDistance : undefined,
   *   sizeInMeters : false,
   *   distanceDisplayCondition : undefined
   * });
   *
   * @example
   * // Example 2:  Specify only the billboard's cartographic position.
   * const b = billboards.add({
   *   position : Cesium.Cartesian3.fromDegrees(longitude, latitude, height)
   * });
   *
   * @see BillboardCollection#remove
   * @see BillboardCollection#removeAll
   */
  BillboardCollection.prototype.add = function (options) {
    const billboard = new Billboard(options, this);
    billboard._index = this._billboards.length;

    this._billboards.push(billboard);
    this._createVertexArray = true;

    return billboard;
  };

  /**
   * Removes a billboard from the collection.
   *
   * @param {Billboard} billboard The billboard to remove.
   * @returns {Boolean} <code>true</code> if the billboard was removed; <code>false</code> if the billboard was not found in the collection.
   *
   * @performance Calling <code>remove</code> is expected constant time.  However, the collection's vertex buffer
   * is rewritten - an <code>O(n)</code> operation that also incurs CPU to GPU overhead.  For
   * best performance, remove as many billboards as possible before calling <code>update</code>.
   * If you intend to temporarily hide a billboard, it is usually more efficient to call
   * {@link Billboard#show} instead of removing and re-adding the billboard.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * const b = billboards.add(...);
   * billboards.remove(b);  // Returns true
   *
   * @see BillboardCollection#add
   * @see BillboardCollection#removeAll
   * @see Billboard#show
   */
  BillboardCollection.prototype.remove = function (billboard) {
    if (this.contains(billboard)) {
      this._billboards[billboard._index] = undefined; // Removed later
      this._billboardsRemoved = true;
      this._createVertexArray = true;
      billboard._destroy();
      return true;
    }

    return false;
  };

  /**
   * Removes all billboards from the collection.
   *
   * @performance <code>O(n)</code>.  It is more efficient to remove all the billboards
   * from a collection and then add new ones than to create a new collection entirely.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * billboards.add(...);
   * billboards.add(...);
   * billboards.removeAll();
   *
   * @see BillboardCollection#add
   * @see BillboardCollection#remove
   */
  BillboardCollection.prototype.removeAll = function () {
    destroyBillboards(this._billboards);
    this._billboards = [];
    this._billboardsToUpdate = [];
    this._billboardsToUpdateIndex = 0;
    this._billboardsRemoved = false;

    this._createVertexArray = true;
  };

  function removeBillboards(billboardCollection) {
    if (billboardCollection._billboardsRemoved) {
      billboardCollection._billboardsRemoved = false;

      const newBillboards = [];
      const billboards = billboardCollection._billboards;
      const length = billboards.length;
      for (let i = 0, j = 0; i < length; ++i) {
        const billboard = billboards[i];
        if (defined(billboard)) {
          billboard._index = j++;
          newBillboards.push(billboard);
        }
      }

      billboardCollection._billboards = newBillboards;
    }
  }

  BillboardCollection.prototype._updateBillboard = function (
    billboard,
    propertyChanged
  ) {
    if (!billboard._dirty) {
      this._billboardsToUpdate[this._billboardsToUpdateIndex++] = billboard;
    }

    ++this._propertiesChanged[propertyChanged];
  };

  /**
   * Check whether this collection contains a given billboard.
   *
   * @param {Billboard} [billboard] The billboard to check for.
   * @returns {Boolean} true if this collection contains the billboard, false otherwise.
   *
   * @see BillboardCollection#get
   */
  BillboardCollection.prototype.contains = function (billboard) {
    return defined(billboard) && billboard._billboardCollection === this;
  };

  /**
   * Returns the billboard in the collection at the specified index.  Indices are zero-based
   * and increase as billboards are added.  Removing a billboard shifts all billboards after
   * it to the left, changing their indices.  This function is commonly used with
   * {@link BillboardCollection#length} to iterate over all the billboards
   * in the collection.
   *
   * @param {Number} index The zero-based index of the billboard.
   * @returns {Billboard} The billboard at the specified index.
   *
   * @performance Expected constant time.  If billboards were removed from the collection and
   * {@link BillboardCollection#update} was not called, an implicit <code>O(n)</code>
   * operation is performed.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * // Toggle the show property of every billboard in the collection
   * const len = billboards.length;
   * for (let i = 0; i < len; ++i) {
   *   const b = billboards.get(i);
   *   b.show = !b.show;
   * }
   *
   * @see BillboardCollection#length
   */
  BillboardCollection.prototype.get = function (index) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("index", index);
    //>>includeEnd('debug');

    removeBillboards(this);
    return this._billboards[index];
  };

  let getIndexBuffer$2;

  function getIndexBufferBatched$1(context) {
    const sixteenK = 16 * 1024;

    let indexBuffer = context.cache.billboardCollection_indexBufferBatched;
    if (defined(indexBuffer)) {
      return indexBuffer;
    }

    // Subtract 6 because the last index is reserverd for primitive restart.
    // https://www.khronos.org/registry/webgl/specs/latest/2.0/#5.18
    const length = sixteenK * 6 - 6;
    const indices = new Uint16Array(length);
    for (let i = 0, j = 0; i < length; i += 6, j += 4) {
      indices[i] = j;
      indices[i + 1] = j + 1;
      indices[i + 2] = j + 2;

      indices[i + 3] = j + 0;
      indices[i + 4] = j + 2;
      indices[i + 5] = j + 3;
    }

    // PERFORMANCE_IDEA:  Should we reference count billboard collections, and eventually delete this?
    // Is this too much memory to allocate up front?  Should we dynamically grow it?
    indexBuffer = Buffer$1.createIndexBuffer({
      context: context,
      typedArray: indices,
      usage: BufferUsage$1.STATIC_DRAW,
      indexDatatype: IndexDatatype$1.UNSIGNED_SHORT,
    });
    indexBuffer.vertexArrayDestroyable = false;
    context.cache.billboardCollection_indexBufferBatched = indexBuffer;
    return indexBuffer;
  }

  function getIndexBufferInstanced$1(context) {
    let indexBuffer = context.cache.billboardCollection_indexBufferInstanced;
    if (defined(indexBuffer)) {
      return indexBuffer;
    }

    indexBuffer = Buffer$1.createIndexBuffer({
      context: context,
      typedArray: new Uint16Array([0, 1, 2, 0, 2, 3]),
      usage: BufferUsage$1.STATIC_DRAW,
      indexDatatype: IndexDatatype$1.UNSIGNED_SHORT,
    });

    indexBuffer.vertexArrayDestroyable = false;
    context.cache.billboardCollection_indexBufferInstanced = indexBuffer;
    return indexBuffer;
  }

  function getVertexBufferInstanced$1(context) {
    let vertexBuffer = context.cache.billboardCollection_vertexBufferInstanced;
    if (defined(vertexBuffer)) {
      return vertexBuffer;
    }

    vertexBuffer = Buffer$1.createVertexBuffer({
      context: context,
      typedArray: new Float32Array([0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0]),
      usage: BufferUsage$1.STATIC_DRAW,
    });

    vertexBuffer.vertexArrayDestroyable = false;
    context.cache.billboardCollection_vertexBufferInstanced = vertexBuffer;
    return vertexBuffer;
  }

  BillboardCollection.prototype.computeNewBuffersUsage = function () {
    const buffersUsage = this._buffersUsage;
    let usageChanged = false;

    const properties = this._propertiesChanged;
    for (let k = 0; k < NUMBER_OF_PROPERTIES$4; ++k) {
      const newUsage =
        properties[k] === 0 ? BufferUsage$1.STATIC_DRAW : BufferUsage$1.STREAM_DRAW;
      usageChanged = usageChanged || buffersUsage[k] !== newUsage;
      buffersUsage[k] = newUsage;
    }

    return usageChanged;
  };

  function createVAF$2(
    context,
    numberOfBillboards,
    buffersUsage,
    instanced,
    batchTable,
    sdf
  ) {
    const attributes = [
      {
        index: attributeLocations$6.positionHighAndScale,
        componentsPerAttribute: 4,
        componentDatatype: ComponentDatatype$1.FLOAT,
        usage: buffersUsage[POSITION_INDEX$6],
      },
      {
        index: attributeLocations$6.positionLowAndRotation,
        componentsPerAttribute: 4,
        componentDatatype: ComponentDatatype$1.FLOAT,
        usage: buffersUsage[POSITION_INDEX$6],
      },
      {
        index: attributeLocations$6.compressedAttribute0,
        componentsPerAttribute: 4,
        componentDatatype: ComponentDatatype$1.FLOAT,
        usage: buffersUsage[PIXEL_OFFSET_INDEX],
      },
      {
        index: attributeLocations$6.compressedAttribute1,
        componentsPerAttribute: 4,
        componentDatatype: ComponentDatatype$1.FLOAT,
        usage: buffersUsage[TRANSLUCENCY_BY_DISTANCE_INDEX$2],
      },
      {
        index: attributeLocations$6.compressedAttribute2,
        componentsPerAttribute: 4,
        componentDatatype: ComponentDatatype$1.FLOAT,
        usage: buffersUsage[COLOR_INDEX$4],
      },
      {
        index: attributeLocations$6.eyeOffset,
        componentsPerAttribute: 4,
        componentDatatype: ComponentDatatype$1.FLOAT,
        usage: buffersUsage[EYE_OFFSET_INDEX],
      },
      {
        index: attributeLocations$6.scaleByDistance,
        componentsPerAttribute: 4,
        componentDatatype: ComponentDatatype$1.FLOAT,
        usage: buffersUsage[SCALE_BY_DISTANCE_INDEX$2],
      },
      {
        index: attributeLocations$6.pixelOffsetScaleByDistance,
        componentsPerAttribute: 4,
        componentDatatype: ComponentDatatype$1.FLOAT,
        usage: buffersUsage[PIXEL_OFFSET_SCALE_BY_DISTANCE_INDEX],
      },
      {
        index: attributeLocations$6.compressedAttribute3,
        componentsPerAttribute: 4,
        componentDatatype: ComponentDatatype$1.FLOAT,
        usage: buffersUsage[DISTANCE_DISPLAY_CONDITION_INDEX$2],
      },
      {
        index: attributeLocations$6.textureCoordinateBoundsOrLabelTranslate,
        componentsPerAttribute: 4,
        componentDatatype: ComponentDatatype$1.FLOAT,
        usage: buffersUsage[TEXTURE_COORDINATE_BOUNDS],
      },
    ];

    // Instancing requires one non-instanced attribute.
    if (instanced) {
      attributes.push({
        index: attributeLocations$6.direction,
        componentsPerAttribute: 2,
        componentDatatype: ComponentDatatype$1.FLOAT,
        vertexBuffer: getVertexBufferInstanced$1(context),
      });
    }

    if (defined(batchTable)) {
      attributes.push({
        index: attributeLocations$6.a_batchId,
        componentsPerAttribute: 1,
        componentDatatype: ComponentDatatype$1.FLOAT,
        bufferUsage: BufferUsage$1.STATIC_DRAW,
      });
    }

    if (sdf) {
      attributes.push({
        index: attributeLocations$6.sdf,
        componentsPerAttribute: 2,
        componentDatatype: ComponentDatatype$1.FLOAT,
        usage: buffersUsage[SDF_INDEX],
      });
    }

    // When instancing is enabled, only one vertex is needed for each billboard.
    const sizeInVertices = instanced
      ? numberOfBillboards
      : 4 * numberOfBillboards;
    return new VertexArrayFacade(context, attributes, sizeInVertices, instanced);
  }

  ///////////////////////////////////////////////////////////////////////////

  // Four vertices per billboard.  Each has the same position, etc., but a different screen-space direction vector.

  // PERFORMANCE_IDEA:  Save memory if a property is the same for all billboards, use a latched attribute state,
  // instead of storing it in a vertex buffer.

  const writePositionScratch$2 = new EncodedCartesian3();

  function writePositionScaleAndRotation(
    billboardCollection,
    frameState,
    textureAtlasCoordinates,
    vafWriters,
    billboard
  ) {
    let i;
    const positionHighWriter =
      vafWriters[attributeLocations$6.positionHighAndScale];
    const positionLowWriter =
      vafWriters[attributeLocations$6.positionLowAndRotation];
    const position = billboard._getActualPosition();

    if (billboardCollection._mode === SceneMode$1.SCENE3D) {
      BoundingSphere.expand(
        billboardCollection._baseVolume,
        position,
        billboardCollection._baseVolume
      );
      billboardCollection._boundingVolumeDirty = true;
    }

    EncodedCartesian3.fromCartesian(position, writePositionScratch$2);
    const scale = billboard.scale;
    const rotation = billboard.rotation;

    if (rotation !== 0.0) {
      billboardCollection._shaderRotation = true;
    }

    billboardCollection._maxScale = Math.max(
      billboardCollection._maxScale,
      scale
    );

    const high = writePositionScratch$2.high;
    const low = writePositionScratch$2.low;

    if (billboardCollection._instanced) {
      i = billboard._index;
      positionHighWriter(i, high.x, high.y, high.z, scale);
      positionLowWriter(i, low.x, low.y, low.z, rotation);
    } else {
      i = billboard._index * 4;
      positionHighWriter(i + 0, high.x, high.y, high.z, scale);
      positionHighWriter(i + 1, high.x, high.y, high.z, scale);
      positionHighWriter(i + 2, high.x, high.y, high.z, scale);
      positionHighWriter(i + 3, high.x, high.y, high.z, scale);

      positionLowWriter(i + 0, low.x, low.y, low.z, rotation);
      positionLowWriter(i + 1, low.x, low.y, low.z, rotation);
      positionLowWriter(i + 2, low.x, low.y, low.z, rotation);
      positionLowWriter(i + 3, low.x, low.y, low.z, rotation);
    }
  }

  const scratchCartesian2$3 = new Cartesian2();

  const UPPER_BOUND = 32768.0; // 2^15

  const LEFT_SHIFT16$1 = 65536.0; // 2^16
  const LEFT_SHIFT12 = 4096.0; // 2^12
  const LEFT_SHIFT8$1 = 256.0; // 2^8
  const LEFT_SHIFT7 = 128.0;
  const LEFT_SHIFT5 = 32.0;
  const LEFT_SHIFT3 = 8.0;
  const LEFT_SHIFT2 = 4.0;

  const RIGHT_SHIFT8 = 1.0 / 256.0;

  const LOWER_LEFT = 0.0;
  const LOWER_RIGHT = 2.0;
  const UPPER_RIGHT = 3.0;
  const UPPER_LEFT = 1.0;

  function writeCompressedAttrib0$1(
    billboardCollection,
    frameState,
    textureAtlasCoordinates,
    vafWriters,
    billboard
  ) {
    let i;
    const writer = vafWriters[attributeLocations$6.compressedAttribute0];
    const pixelOffset = billboard.pixelOffset;
    const pixelOffsetX = pixelOffset.x;
    const pixelOffsetY = pixelOffset.y;

    const translate = billboard._translate;
    const translateX = translate.x;
    const translateY = translate.y;

    billboardCollection._maxPixelOffset = Math.max(
      billboardCollection._maxPixelOffset,
      Math.abs(pixelOffsetX + translateX),
      Math.abs(-pixelOffsetY + translateY)
    );

    const horizontalOrigin = billboard.horizontalOrigin;
    let verticalOrigin = billboard._verticalOrigin;
    let show = billboard.show && billboard.clusterShow;

    // If the color alpha is zero, do not show this billboard.  This lets us avoid providing
    // color during the pick pass and also eliminates a discard in the fragment shader.
    if (billboard.color.alpha === 0.0) {
      show = false;
    }

    // Raw billboards don't distinguish between BASELINE and BOTTOM, only LabelCollection does that.
    if (verticalOrigin === VerticalOrigin$1.BASELINE) {
      verticalOrigin = VerticalOrigin$1.BOTTOM;
    }

    billboardCollection._allHorizontalCenter =
      billboardCollection._allHorizontalCenter &&
      horizontalOrigin === HorizontalOrigin$1.CENTER;
    billboardCollection._allVerticalCenter =
      billboardCollection._allVerticalCenter &&
      verticalOrigin === VerticalOrigin$1.CENTER;

    let bottomLeftX = 0;
    let bottomLeftY = 0;
    let width = 0;
    let height = 0;
    const index = billboard._imageIndex;
    if (index !== -1) {
      const imageRectangle = textureAtlasCoordinates[index];

      //>>includeStart('debug', pragmas.debug);
      if (!defined(imageRectangle)) {
        throw new DeveloperError(`Invalid billboard image index: ${index}`);
      }
      //>>includeEnd('debug');

      bottomLeftX = imageRectangle.x;
      bottomLeftY = imageRectangle.y;
      width = imageRectangle.width;
      height = imageRectangle.height;
    }
    const topRightX = bottomLeftX + width;
    const topRightY = bottomLeftY + height;

    let compressed0 =
      Math.floor(
        CesiumMath.clamp(pixelOffsetX, -UPPER_BOUND, UPPER_BOUND) + UPPER_BOUND
      ) * LEFT_SHIFT7;
    compressed0 += (horizontalOrigin + 1.0) * LEFT_SHIFT5;
    compressed0 += (verticalOrigin + 1.0) * LEFT_SHIFT3;
    compressed0 += (show ? 1.0 : 0.0) * LEFT_SHIFT2;

    let compressed1 =
      Math.floor(
        CesiumMath.clamp(pixelOffsetY, -UPPER_BOUND, UPPER_BOUND) + UPPER_BOUND
      ) * LEFT_SHIFT8$1;
    let compressed2 =
      Math.floor(
        CesiumMath.clamp(translateX, -UPPER_BOUND, UPPER_BOUND) + UPPER_BOUND
      ) * LEFT_SHIFT8$1;

    const tempTanslateY =
      (CesiumMath.clamp(translateY, -UPPER_BOUND, UPPER_BOUND) + UPPER_BOUND) *
      RIGHT_SHIFT8;
    const upperTranslateY = Math.floor(tempTanslateY);
    const lowerTranslateY = Math.floor(
      (tempTanslateY - upperTranslateY) * LEFT_SHIFT8$1
    );

    compressed1 += upperTranslateY;
    compressed2 += lowerTranslateY;

    scratchCartesian2$3.x = bottomLeftX;
    scratchCartesian2$3.y = bottomLeftY;
    const compressedTexCoordsLL = AttributeCompression.compressTextureCoordinates(
      scratchCartesian2$3
    );
    scratchCartesian2$3.x = topRightX;
    const compressedTexCoordsLR = AttributeCompression.compressTextureCoordinates(
      scratchCartesian2$3
    );
    scratchCartesian2$3.y = topRightY;
    const compressedTexCoordsUR = AttributeCompression.compressTextureCoordinates(
      scratchCartesian2$3
    );
    scratchCartesian2$3.x = bottomLeftX;
    const compressedTexCoordsUL = AttributeCompression.compressTextureCoordinates(
      scratchCartesian2$3
    );

    if (billboardCollection._instanced) {
      i = billboard._index;
      writer(i, compressed0, compressed1, compressed2, compressedTexCoordsLL);
    } else {
      i = billboard._index * 4;
      writer(
        i + 0,
        compressed0 + LOWER_LEFT,
        compressed1,
        compressed2,
        compressedTexCoordsLL
      );
      writer(
        i + 1,
        compressed0 + LOWER_RIGHT,
        compressed1,
        compressed2,
        compressedTexCoordsLR
      );
      writer(
        i + 2,
        compressed0 + UPPER_RIGHT,
        compressed1,
        compressed2,
        compressedTexCoordsUR
      );
      writer(
        i + 3,
        compressed0 + UPPER_LEFT,
        compressed1,
        compressed2,
        compressedTexCoordsUL
      );
    }
  }

  function writeCompressedAttrib1$1(
    billboardCollection,
    frameState,
    textureAtlasCoordinates,
    vafWriters,
    billboard
  ) {
    let i;
    const writer = vafWriters[attributeLocations$6.compressedAttribute1];
    const alignedAxis = billboard.alignedAxis;
    if (!Cartesian3.equals(alignedAxis, Cartesian3.ZERO)) {
      billboardCollection._shaderAlignedAxis = true;
    }

    let near = 0.0;
    let nearValue = 1.0;
    let far = 1.0;
    let farValue = 1.0;

    const translucency = billboard.translucencyByDistance;
    if (defined(translucency)) {
      near = translucency.near;
      nearValue = translucency.nearValue;
      far = translucency.far;
      farValue = translucency.farValue;

      if (nearValue !== 1.0 || farValue !== 1.0) {
        // translucency by distance calculation in shader need not be enabled
        // until a billboard with near and far !== 1.0 is found
        billboardCollection._shaderTranslucencyByDistance = true;
      }
    }

    let width = 0;
    const index = billboard._imageIndex;
    if (index !== -1) {
      const imageRectangle = textureAtlasCoordinates[index];

      //>>includeStart('debug', pragmas.debug);
      if (!defined(imageRectangle)) {
        throw new DeveloperError(`Invalid billboard image index: ${index}`);
      }
      //>>includeEnd('debug');

      width = imageRectangle.width;
    }

    const textureWidth = billboardCollection._textureAtlas.texture.width;
    const imageWidth = Math.round(
      defaultValue(billboard.width, textureWidth * width)
    );
    billboardCollection._maxSize = Math.max(
      billboardCollection._maxSize,
      imageWidth
    );

    let compressed0 = CesiumMath.clamp(imageWidth, 0.0, LEFT_SHIFT16$1);
    let compressed1 = 0.0;

    if (
      Math.abs(Cartesian3.magnitudeSquared(alignedAxis) - 1.0) <
      CesiumMath.EPSILON6
    ) {
      compressed1 = AttributeCompression.octEncodeFloat(alignedAxis);
    }

    nearValue = CesiumMath.clamp(nearValue, 0.0, 1.0);
    nearValue = nearValue === 1.0 ? 255.0 : (nearValue * 255.0) | 0;
    compressed0 = compressed0 * LEFT_SHIFT8$1 + nearValue;

    farValue = CesiumMath.clamp(farValue, 0.0, 1.0);
    farValue = farValue === 1.0 ? 255.0 : (farValue * 255.0) | 0;
    compressed1 = compressed1 * LEFT_SHIFT8$1 + farValue;

    if (billboardCollection._instanced) {
      i = billboard._index;
      writer(i, compressed0, compressed1, near, far);
    } else {
      i = billboard._index * 4;
      writer(i + 0, compressed0, compressed1, near, far);
      writer(i + 1, compressed0, compressed1, near, far);
      writer(i + 2, compressed0, compressed1, near, far);
      writer(i + 3, compressed0, compressed1, near, far);
    }
  }

  function writeCompressedAttrib2(
    billboardCollection,
    frameState,
    textureAtlasCoordinates,
    vafWriters,
    billboard
  ) {
    let i;
    const writer = vafWriters[attributeLocations$6.compressedAttribute2];
    const color = billboard.color;
    const pickColor = !defined(billboardCollection._batchTable)
      ? billboard.getPickId(frameState.context).color
      : Color.WHITE;
    const sizeInMeters = billboard.sizeInMeters ? 1.0 : 0.0;
    const validAlignedAxis =
      Math.abs(Cartesian3.magnitudeSquared(billboard.alignedAxis) - 1.0) <
      CesiumMath.EPSILON6
        ? 1.0
        : 0.0;

    billboardCollection._allSizedInMeters =
      billboardCollection._allSizedInMeters && sizeInMeters === 1.0;

    let height = 0;
    const index = billboard._imageIndex;
    if (index !== -1) {
      const imageRectangle = textureAtlasCoordinates[index];

      //>>includeStart('debug', pragmas.debug);
      if (!defined(imageRectangle)) {
        throw new DeveloperError(`Invalid billboard image index: ${index}`);
      }
      //>>includeEnd('debug');

      height = imageRectangle.height;
    }

    const dimensions = billboardCollection._textureAtlas.texture.dimensions;
    const imageHeight = Math.round(
      defaultValue(billboard.height, dimensions.y * height)
    );
    billboardCollection._maxSize = Math.max(
      billboardCollection._maxSize,
      imageHeight
    );
    let labelHorizontalOrigin = defaultValue(
      billboard._labelHorizontalOrigin,
      -2
    );
    labelHorizontalOrigin += 2;
    const compressed3 = imageHeight * LEFT_SHIFT2 + labelHorizontalOrigin;

    let red = Color.floatToByte(color.red);
    let green = Color.floatToByte(color.green);
    let blue = Color.floatToByte(color.blue);
    const compressed0 = red * LEFT_SHIFT16$1 + green * LEFT_SHIFT8$1 + blue;

    red = Color.floatToByte(pickColor.red);
    green = Color.floatToByte(pickColor.green);
    blue = Color.floatToByte(pickColor.blue);
    const compressed1 = red * LEFT_SHIFT16$1 + green * LEFT_SHIFT8$1 + blue;

    let compressed2 =
      Color.floatToByte(color.alpha) * LEFT_SHIFT16$1 +
      Color.floatToByte(pickColor.alpha) * LEFT_SHIFT8$1;
    compressed2 += sizeInMeters * 2.0 + validAlignedAxis;

    if (billboardCollection._instanced) {
      i = billboard._index;
      writer(i, compressed0, compressed1, compressed2, compressed3);
    } else {
      i = billboard._index * 4;
      writer(i + 0, compressed0, compressed1, compressed2, compressed3);
      writer(i + 1, compressed0, compressed1, compressed2, compressed3);
      writer(i + 2, compressed0, compressed1, compressed2, compressed3);
      writer(i + 3, compressed0, compressed1, compressed2, compressed3);
    }
  }

  function writeEyeOffset(
    billboardCollection,
    frameState,
    textureAtlasCoordinates,
    vafWriters,
    billboard
  ) {
    let i;
    const writer = vafWriters[attributeLocations$6.eyeOffset];
    const eyeOffset = billboard.eyeOffset;

    // For billboards that are clamped to ground, move it slightly closer to the camera
    let eyeOffsetZ = eyeOffset.z;
    if (billboard._heightReference !== HeightReference$1.NONE) {
      eyeOffsetZ *= 1.005;
    }
    billboardCollection._maxEyeOffset = Math.max(
      billboardCollection._maxEyeOffset,
      Math.abs(eyeOffset.x),
      Math.abs(eyeOffset.y),
      Math.abs(eyeOffsetZ)
    );

    if (billboardCollection._instanced) {
      let width = 0;
      let height = 0;
      const index = billboard._imageIndex;
      if (index !== -1) {
        const imageRectangle = textureAtlasCoordinates[index];

        //>>includeStart('debug', pragmas.debug);
        if (!defined(imageRectangle)) {
          throw new DeveloperError(`Invalid billboard image index: ${index}`);
        }
        //>>includeEnd('debug');

        width = imageRectangle.width;
        height = imageRectangle.height;
      }

      scratchCartesian2$3.x = width;
      scratchCartesian2$3.y = height;
      const compressedTexCoordsRange = AttributeCompression.compressTextureCoordinates(
        scratchCartesian2$3
      );

      i = billboard._index;
      writer(i, eyeOffset.x, eyeOffset.y, eyeOffsetZ, compressedTexCoordsRange);
    } else {
      i = billboard._index * 4;
      writer(i + 0, eyeOffset.x, eyeOffset.y, eyeOffsetZ, 0.0);
      writer(i + 1, eyeOffset.x, eyeOffset.y, eyeOffsetZ, 0.0);
      writer(i + 2, eyeOffset.x, eyeOffset.y, eyeOffsetZ, 0.0);
      writer(i + 3, eyeOffset.x, eyeOffset.y, eyeOffsetZ, 0.0);
    }
  }

  function writeScaleByDistance$1(
    billboardCollection,
    frameState,
    textureAtlasCoordinates,
    vafWriters,
    billboard
  ) {
    let i;
    const writer = vafWriters[attributeLocations$6.scaleByDistance];
    let near = 0.0;
    let nearValue = 1.0;
    let far = 1.0;
    let farValue = 1.0;

    const scale = billboard.scaleByDistance;
    if (defined(scale)) {
      near = scale.near;
      nearValue = scale.nearValue;
      far = scale.far;
      farValue = scale.farValue;

      if (nearValue !== 1.0 || farValue !== 1.0) {
        // scale by distance calculation in shader need not be enabled
        // until a billboard with near and far !== 1.0 is found
        billboardCollection._shaderScaleByDistance = true;
      }
    }

    if (billboardCollection._instanced) {
      i = billboard._index;
      writer(i, near, nearValue, far, farValue);
    } else {
      i = billboard._index * 4;
      writer(i + 0, near, nearValue, far, farValue);
      writer(i + 1, near, nearValue, far, farValue);
      writer(i + 2, near, nearValue, far, farValue);
      writer(i + 3, near, nearValue, far, farValue);
    }
  }

  function writePixelOffsetScaleByDistance(
    billboardCollection,
    frameState,
    textureAtlasCoordinates,
    vafWriters,
    billboard
  ) {
    let i;
    const writer = vafWriters[attributeLocations$6.pixelOffsetScaleByDistance];
    let near = 0.0;
    let nearValue = 1.0;
    let far = 1.0;
    let farValue = 1.0;

    const pixelOffsetScale = billboard.pixelOffsetScaleByDistance;
    if (defined(pixelOffsetScale)) {
      near = pixelOffsetScale.near;
      nearValue = pixelOffsetScale.nearValue;
      far = pixelOffsetScale.far;
      farValue = pixelOffsetScale.farValue;

      if (nearValue !== 1.0 || farValue !== 1.0) {
        // pixelOffsetScale by distance calculation in shader need not be enabled
        // until a billboard with near and far !== 1.0 is found
        billboardCollection._shaderPixelOffsetScaleByDistance = true;
      }
    }

    if (billboardCollection._instanced) {
      i = billboard._index;
      writer(i, near, nearValue, far, farValue);
    } else {
      i = billboard._index * 4;
      writer(i + 0, near, nearValue, far, farValue);
      writer(i + 1, near, nearValue, far, farValue);
      writer(i + 2, near, nearValue, far, farValue);
      writer(i + 3, near, nearValue, far, farValue);
    }
  }

  function writeCompressedAttribute3(
    billboardCollection,
    frameState,
    textureAtlasCoordinates,
    vafWriters,
    billboard
  ) {
    let i;
    const writer = vafWriters[attributeLocations$6.compressedAttribute3];
    let near = 0.0;
    let far = Number.MAX_VALUE;

    const distanceDisplayCondition = billboard.distanceDisplayCondition;
    if (defined(distanceDisplayCondition)) {
      near = distanceDisplayCondition.near;
      far = distanceDisplayCondition.far;

      near *= near;
      far *= far;

      billboardCollection._shaderDistanceDisplayCondition = true;
    }

    let disableDepthTestDistance = billboard.disableDepthTestDistance;
    const clampToGround =
      billboard.heightReference === HeightReference$1.CLAMP_TO_GROUND &&
      frameState.context.depthTexture;
    if (!defined(disableDepthTestDistance)) {
      disableDepthTestDistance = clampToGround ? 5000.0 : 0.0;
    }

    disableDepthTestDistance *= disableDepthTestDistance;
    if (clampToGround || disableDepthTestDistance > 0.0) {
      billboardCollection._shaderDisableDepthDistance = true;
      if (disableDepthTestDistance === Number.POSITIVE_INFINITY) {
        disableDepthTestDistance = -1.0;
      }
    }

    let imageHeight;
    let imageWidth;

    if (!defined(billboard._labelDimensions)) {
      let height = 0;
      let width = 0;
      const index = billboard._imageIndex;
      if (index !== -1) {
        const imageRectangle = textureAtlasCoordinates[index];

        //>>includeStart('debug', pragmas.debug);
        if (!defined(imageRectangle)) {
          throw new DeveloperError(`Invalid billboard image index: ${index}`);
        }
        //>>includeEnd('debug');

        height = imageRectangle.height;
        width = imageRectangle.width;
      }

      imageHeight = Math.round(
        defaultValue(
          billboard.height,
          billboardCollection._textureAtlas.texture.dimensions.y * height
        )
      );

      const textureWidth = billboardCollection._textureAtlas.texture.width;
      imageWidth = Math.round(
        defaultValue(billboard.width, textureWidth * width)
      );
    } else {
      imageWidth = billboard._labelDimensions.x;
      imageHeight = billboard._labelDimensions.y;
    }

    const w = Math.floor(CesiumMath.clamp(imageWidth, 0.0, LEFT_SHIFT12));
    const h = Math.floor(CesiumMath.clamp(imageHeight, 0.0, LEFT_SHIFT12));
    const dimensions = w * LEFT_SHIFT12 + h;

    if (billboardCollection._instanced) {
      i = billboard._index;
      writer(i, near, far, disableDepthTestDistance, dimensions);
    } else {
      i = billboard._index * 4;
      writer(i + 0, near, far, disableDepthTestDistance, dimensions);
      writer(i + 1, near, far, disableDepthTestDistance, dimensions);
      writer(i + 2, near, far, disableDepthTestDistance, dimensions);
      writer(i + 3, near, far, disableDepthTestDistance, dimensions);
    }
  }

  function writeTextureCoordinateBoundsOrLabelTranslate(
    billboardCollection,
    frameState,
    textureAtlasCoordinates,
    vafWriters,
    billboard
  ) {
    if (billboard.heightReference === HeightReference$1.CLAMP_TO_GROUND) {
      const scene = billboardCollection._scene;
      const context = frameState.context;
      const globeTranslucent = frameState.globeTranslucencyState.translucent;
      const depthTestAgainstTerrain =
        defined(scene.globe) && scene.globe.depthTestAgainstTerrain;

      // Only do manual depth test if the globe is opaque and writes depth
      billboardCollection._shaderClampToGround =
        context.depthTexture && !globeTranslucent && depthTestAgainstTerrain;
    }
    let i;
    const writer =
      vafWriters[attributeLocations$6.textureCoordinateBoundsOrLabelTranslate];

    if (ContextLimits.maximumVertexTextureImageUnits > 0) {
      //write _labelTranslate, used by depth testing in the vertex shader
      let translateX = 0;
      let translateY = 0;
      if (defined(billboard._labelTranslate)) {
        translateX = billboard._labelTranslate.x;
        translateY = billboard._labelTranslate.y;
      }
      if (billboardCollection._instanced) {
        i = billboard._index;
        writer(i, translateX, translateY, 0.0, 0.0);
      } else {
        i = billboard._index * 4;
        writer(i + 0, translateX, translateY, 0.0, 0.0);
        writer(i + 1, translateX, translateY, 0.0, 0.0);
        writer(i + 2, translateX, translateY, 0.0, 0.0);
        writer(i + 3, translateX, translateY, 0.0, 0.0);
      }
      return;
    }

    //write texture coordinate bounds, used by depth testing in fragment shader
    let minX = 0;
    let minY = 0;
    let width = 0;
    let height = 0;
    const index = billboard._imageIndex;
    if (index !== -1) {
      const imageRectangle = textureAtlasCoordinates[index];

      //>>includeStart('debug', pragmas.debug);
      if (!defined(imageRectangle)) {
        throw new DeveloperError(`Invalid billboard image index: ${index}`);
      }
      //>>includeEnd('debug');

      minX = imageRectangle.x;
      minY = imageRectangle.y;
      width = imageRectangle.width;
      height = imageRectangle.height;
    }
    const maxX = minX + width;
    const maxY = minY + height;

    if (billboardCollection._instanced) {
      i = billboard._index;
      writer(i, minX, minY, maxX, maxY);
    } else {
      i = billboard._index * 4;
      writer(i + 0, minX, minY, maxX, maxY);
      writer(i + 1, minX, minY, maxX, maxY);
      writer(i + 2, minX, minY, maxX, maxY);
      writer(i + 3, minX, minY, maxX, maxY);
    }
  }

  function writeBatchId(
    billboardCollection,
    frameState,
    textureAtlasCoordinates,
    vafWriters,
    billboard
  ) {
    if (!defined(billboardCollection._batchTable)) {
      return;
    }

    const writer = vafWriters[attributeLocations$6.a_batchId];
    const id = billboard._batchIndex;

    let i;
    if (billboardCollection._instanced) {
      i = billboard._index;
      writer(i, id);
    } else {
      i = billboard._index * 4;
      writer(i + 0, id);
      writer(i + 1, id);
      writer(i + 2, id);
      writer(i + 3, id);
    }
  }

  function writeSDF(
    billboardCollection,
    frameState,
    textureAtlasCoordinates,
    vafWriters,
    billboard
  ) {
    if (!billboardCollection._sdf) {
      return;
    }

    let i;
    const writer = vafWriters[attributeLocations$6.sdf];

    const outlineColor = billboard.outlineColor;
    const outlineWidth = billboard.outlineWidth;

    const red = Color.floatToByte(outlineColor.red);
    const green = Color.floatToByte(outlineColor.green);
    const blue = Color.floatToByte(outlineColor.blue);
    const compressed0 = red * LEFT_SHIFT16$1 + green * LEFT_SHIFT8$1 + blue;

    // Compute the relative outline distance
    const outlineDistance = outlineWidth / SDFSettings$1.RADIUS;
    const compressed1 =
      Color.floatToByte(outlineColor.alpha) * LEFT_SHIFT16$1 +
      Color.floatToByte(outlineDistance) * LEFT_SHIFT8$1;

    if (billboardCollection._instanced) {
      i = billboard._index;
      writer(i, compressed0, compressed1);
    } else {
      i = billboard._index * 4;
      writer(i + 0, compressed0 + LOWER_LEFT, compressed1);
      writer(i + 1, compressed0 + LOWER_RIGHT, compressed1);
      writer(i + 2, compressed0 + UPPER_RIGHT, compressed1);
      writer(i + 3, compressed0 + UPPER_LEFT, compressed1);
    }
  }

  function writeBillboard(
    billboardCollection,
    frameState,
    textureAtlasCoordinates,
    vafWriters,
    billboard
  ) {
    writePositionScaleAndRotation(
      billboardCollection,
      frameState,
      textureAtlasCoordinates,
      vafWriters,
      billboard
    );
    writeCompressedAttrib0$1(
      billboardCollection,
      frameState,
      textureAtlasCoordinates,
      vafWriters,
      billboard
    );
    writeCompressedAttrib1$1(
      billboardCollection,
      frameState,
      textureAtlasCoordinates,
      vafWriters,
      billboard
    );
    writeCompressedAttrib2(
      billboardCollection,
      frameState,
      textureAtlasCoordinates,
      vafWriters,
      billboard
    );
    writeEyeOffset(
      billboardCollection,
      frameState,
      textureAtlasCoordinates,
      vafWriters,
      billboard
    );
    writeScaleByDistance$1(
      billboardCollection,
      frameState,
      textureAtlasCoordinates,
      vafWriters,
      billboard
    );
    writePixelOffsetScaleByDistance(
      billboardCollection,
      frameState,
      textureAtlasCoordinates,
      vafWriters,
      billboard
    );
    writeCompressedAttribute3(
      billboardCollection,
      frameState,
      textureAtlasCoordinates,
      vafWriters,
      billboard
    );
    writeTextureCoordinateBoundsOrLabelTranslate(
      billboardCollection,
      frameState,
      textureAtlasCoordinates,
      vafWriters,
      billboard
    );
    writeBatchId(
      billboardCollection,
      frameState,
      textureAtlasCoordinates,
      vafWriters,
      billboard
    );
    writeSDF(
      billboardCollection,
      frameState,
      textureAtlasCoordinates,
      vafWriters,
      billboard
    );
  }

  function recomputeActualPositions$1(
    billboardCollection,
    billboards,
    length,
    frameState,
    modelMatrix,
    recomputeBoundingVolume
  ) {
    let boundingVolume;
    if (frameState.mode === SceneMode$1.SCENE3D) {
      boundingVolume = billboardCollection._baseVolume;
      billboardCollection._boundingVolumeDirty = true;
    } else {
      boundingVolume = billboardCollection._baseVolume2D;
    }

    const positions = [];
    for (let i = 0; i < length; ++i) {
      const billboard = billboards[i];
      const position = billboard.position;
      const actualPosition = Billboard._computeActualPosition(
        billboard,
        position,
        frameState,
        modelMatrix
      );
      if (defined(actualPosition)) {
        billboard._setActualPosition(actualPosition);

        if (recomputeBoundingVolume) {
          positions.push(actualPosition);
        } else {
          BoundingSphere.expand(boundingVolume, actualPosition, boundingVolume);
        }
      }
    }

    if (recomputeBoundingVolume) {
      BoundingSphere.fromPoints(positions, boundingVolume);
    }
  }

  function updateMode$2(billboardCollection, frameState) {
    const mode = frameState.mode;

    const billboards = billboardCollection._billboards;
    const billboardsToUpdate = billboardCollection._billboardsToUpdate;
    const modelMatrix = billboardCollection._modelMatrix;

    if (
      billboardCollection._createVertexArray ||
      billboardCollection._mode !== mode ||
      (mode !== SceneMode$1.SCENE3D &&
        !Matrix4.equals(modelMatrix, billboardCollection.modelMatrix))
    ) {
      billboardCollection._mode = mode;
      Matrix4.clone(billboardCollection.modelMatrix, modelMatrix);
      billboardCollection._createVertexArray = true;

      if (
        mode === SceneMode$1.SCENE3D ||
        mode === SceneMode$1.SCENE2D ||
        mode === SceneMode$1.COLUMBUS_VIEW
      ) {
        recomputeActualPositions$1(
          billboardCollection,
          billboards,
          billboards.length,
          frameState,
          modelMatrix,
          true
        );
      }
    } else if (mode === SceneMode$1.MORPHING) {
      recomputeActualPositions$1(
        billboardCollection,
        billboards,
        billboards.length,
        frameState,
        modelMatrix,
        true
      );
    } else if (mode === SceneMode$1.SCENE2D || mode === SceneMode$1.COLUMBUS_VIEW) {
      recomputeActualPositions$1(
        billboardCollection,
        billboardsToUpdate,
        billboardCollection._billboardsToUpdateIndex,
        frameState,
        modelMatrix,
        false
      );
    }
  }

  function updateBoundingVolume$1(collection, frameState, boundingVolume) {
    let pixelScale = 1.0;
    if (!collection._allSizedInMeters || collection._maxPixelOffset !== 0.0) {
      pixelScale = frameState.camera.getPixelSize(
        boundingVolume,
        frameState.context.drawingBufferWidth,
        frameState.context.drawingBufferHeight
      );
    }

    let size = pixelScale * collection._maxScale * collection._maxSize * 2.0;
    if (collection._allHorizontalCenter && collection._allVerticalCenter) {
      size *= 0.5;
    }

    const offset =
      pixelScale * collection._maxPixelOffset + collection._maxEyeOffset;
    boundingVolume.radius += size + offset;
  }

  function createDebugCommand(billboardCollection, context) {
    const fs =
      "uniform sampler2D billboard_texture; \n" +
      "varying vec2 v_textureCoordinates; \n" +
      "void main() \n" +
      "{ \n" +
      "    gl_FragColor = texture2D(billboard_texture, v_textureCoordinates); \n" +
      "} \n";

    const drawCommand = context.createViewportQuadCommand(fs, {
      uniformMap: {
        billboard_texture: function () {
          return billboardCollection._textureAtlas.texture;
        },
      },
    });
    drawCommand.pass = Pass$1.OVERLAY;
    return drawCommand;
  }

  const scratchWriterArray$2 = [];

  /**
   * Called when {@link Viewer} or {@link CesiumWidget} render the scene to
   * get the draw commands needed to render this primitive.
   * <p>
   * Do not call this function directly.  This is documented just to
   * list the exceptions that may be propagated when the scene is rendered:
   * </p>
   *
   * @exception {RuntimeError} image with id must be in the atlas.
   */
  BillboardCollection.prototype.update = function (frameState) {
    removeBillboards(this);

    if (!this.show) {
      return;
    }

    let billboards = this._billboards;
    let billboardsLength = billboards.length;

    const context = frameState.context;
    this._instanced = context.instancedArrays;
    attributeLocations$6 = this._instanced
      ? attributeLocationsInstanced$1
      : attributeLocationsBatched$1;
    getIndexBuffer$2 = this._instanced
      ? getIndexBufferInstanced$1
      : getIndexBufferBatched$1;

    let textureAtlas = this._textureAtlas;
    if (!defined(textureAtlas)) {
      textureAtlas = this._textureAtlas = new TextureAtlas({
        context: context,
      });

      for (let ii = 0; ii < billboardsLength; ++ii) {
        billboards[ii]._loadImage();
      }
    }

    const textureAtlasCoordinates = textureAtlas.textureCoordinates;
    if (textureAtlasCoordinates.length === 0) {
      // Can't write billboard vertices until we have texture coordinates
      // provided by a texture atlas
      return;
    }

    updateMode$2(this, frameState);

    billboards = this._billboards;
    billboardsLength = billboards.length;
    const billboardsToUpdate = this._billboardsToUpdate;
    const billboardsToUpdateLength = this._billboardsToUpdateIndex;

    const properties = this._propertiesChanged;

    const textureAtlasGUID = textureAtlas.guid;
    const createVertexArray =
      this._createVertexArray || this._textureAtlasGUID !== textureAtlasGUID;
    this._textureAtlasGUID = textureAtlasGUID;

    let vafWriters;
    const pass = frameState.passes;
    const picking = pass.pick;

    // PERFORMANCE_IDEA: Round robin multiple buffers.
    if (createVertexArray || (!picking && this.computeNewBuffersUsage())) {
      this._createVertexArray = false;

      for (let k = 0; k < NUMBER_OF_PROPERTIES$4; ++k) {
        properties[k] = 0;
      }

      this._vaf = this._vaf && this._vaf.destroy();

      if (billboardsLength > 0) {
        // PERFORMANCE_IDEA:  Instead of creating a new one, resize like std::vector.
        this._vaf = createVAF$2(
          context,
          billboardsLength,
          this._buffersUsage,
          this._instanced,
          this._batchTable,
          this._sdf
        );
        vafWriters = this._vaf.writers;

        // Rewrite entire buffer if billboards were added or removed.
        for (let i = 0; i < billboardsLength; ++i) {
          const billboard = this._billboards[i];
          billboard._dirty = false; // In case it needed an update.
          writeBillboard(
            this,
            frameState,
            textureAtlasCoordinates,
            vafWriters,
            billboard
          );
        }

        // Different billboard collections share the same index buffer.
        this._vaf.commit(getIndexBuffer$2(context));
      }

      this._billboardsToUpdateIndex = 0;
    } else if (billboardsToUpdateLength > 0) {
      // Billboards were modified, but none were added or removed.
      const writers = scratchWriterArray$2;
      writers.length = 0;

      if (
        properties[POSITION_INDEX$6] ||
        properties[ROTATION_INDEX] ||
        properties[SCALE_INDEX$2]
      ) {
        writers.push(writePositionScaleAndRotation);
      }

      if (
        properties[IMAGE_INDEX_INDEX] ||
        properties[PIXEL_OFFSET_INDEX] ||
        properties[HORIZONTAL_ORIGIN_INDEX] ||
        properties[VERTICAL_ORIGIN_INDEX] ||
        properties[SHOW_INDEX$6]
      ) {
        writers.push(writeCompressedAttrib0$1);
        if (this._instanced) {
          writers.push(writeEyeOffset);
        }
      }

      if (
        properties[IMAGE_INDEX_INDEX] ||
        properties[ALIGNED_AXIS_INDEX] ||
        properties[TRANSLUCENCY_BY_DISTANCE_INDEX$2]
      ) {
        writers.push(writeCompressedAttrib1$1);
        writers.push(writeCompressedAttrib2);
      }

      if (properties[IMAGE_INDEX_INDEX] || properties[COLOR_INDEX$4]) {
        writers.push(writeCompressedAttrib2);
      }

      if (properties[EYE_OFFSET_INDEX]) {
        writers.push(writeEyeOffset);
      }

      if (properties[SCALE_BY_DISTANCE_INDEX$2]) {
        writers.push(writeScaleByDistance$1);
      }

      if (properties[PIXEL_OFFSET_SCALE_BY_DISTANCE_INDEX]) {
        writers.push(writePixelOffsetScaleByDistance);
      }

      if (
        properties[DISTANCE_DISPLAY_CONDITION_INDEX$2] ||
        properties[DISABLE_DEPTH_DISTANCE] ||
        properties[IMAGE_INDEX_INDEX] ||
        properties[POSITION_INDEX$6]
      ) {
        writers.push(writeCompressedAttribute3);
      }

      if (properties[IMAGE_INDEX_INDEX] || properties[POSITION_INDEX$6]) {
        writers.push(writeTextureCoordinateBoundsOrLabelTranslate);
      }

      if (properties[SDF_INDEX]) {
        writers.push(writeSDF);
      }

      const numWriters = writers.length;
      vafWriters = this._vaf.writers;

      if (billboardsToUpdateLength / billboardsLength > 0.1) {
        // If more than 10% of billboard change, rewrite the entire buffer.

        // PERFORMANCE_IDEA:  I totally made up 10% :).

        for (let m = 0; m < billboardsToUpdateLength; ++m) {
          const b = billboardsToUpdate[m];
          b._dirty = false;

          for (let n = 0; n < numWriters; ++n) {
            writers[n](this, frameState, textureAtlasCoordinates, vafWriters, b);
          }
        }
        this._vaf.commit(getIndexBuffer$2(context));
      } else {
        for (let h = 0; h < billboardsToUpdateLength; ++h) {
          const bb = billboardsToUpdate[h];
          bb._dirty = false;

          for (let o = 0; o < numWriters; ++o) {
            writers[o](this, frameState, textureAtlasCoordinates, vafWriters, bb);
          }

          if (this._instanced) {
            this._vaf.subCommit(bb._index, 1);
          } else {
            this._vaf.subCommit(bb._index * 4, 4);
          }
        }
        this._vaf.endSubCommits();
      }

      this._billboardsToUpdateIndex = 0;
    }

    // If the number of total billboards ever shrinks considerably
    // Truncate billboardsToUpdate so that we free memory that we're
    // not going to be using.
    if (billboardsToUpdateLength > billboardsLength * 1.5) {
      billboardsToUpdate.length = billboardsLength;
    }

    if (!defined(this._vaf) || !defined(this._vaf.va)) {
      return;
    }

    if (this._boundingVolumeDirty) {
      this._boundingVolumeDirty = false;
      BoundingSphere.transform(
        this._baseVolume,
        this.modelMatrix,
        this._baseVolumeWC
      );
    }

    let boundingVolume;
    let modelMatrix = Matrix4.IDENTITY;
    if (frameState.mode === SceneMode$1.SCENE3D) {
      modelMatrix = this.modelMatrix;
      boundingVolume = BoundingSphere.clone(
        this._baseVolumeWC,
        this._boundingVolume
      );
    } else {
      boundingVolume = BoundingSphere.clone(
        this._baseVolume2D,
        this._boundingVolume
      );
    }
    updateBoundingVolume$1(this, frameState, boundingVolume);

    const blendOptionChanged = this._blendOption !== this.blendOption;
    this._blendOption = this.blendOption;

    if (blendOptionChanged) {
      if (
        this._blendOption === BlendOption$1.OPAQUE ||
        this._blendOption === BlendOption$1.OPAQUE_AND_TRANSLUCENT
      ) {
        this._rsOpaque = RenderState.fromCache({
          depthTest: {
            enabled: true,
            func: WebGLConstants$1.LESS,
          },
          depthMask: true,
        });
      } else {
        this._rsOpaque = undefined;
      }

      // If OPAQUE_AND_TRANSLUCENT is in use, only the opaque pass gets the benefit of the depth buffer,
      // not the translucent pass.  Otherwise, if the TRANSLUCENT pass is on its own, it turns on
      // a depthMask in lieu of full depth sorting (because it has opaque-ish fragments that look bad in OIT).
      // When the TRANSLUCENT depth mask is in use, label backgrounds require the depth func to be LEQUAL.
      const useTranslucentDepthMask =
        this._blendOption === BlendOption$1.TRANSLUCENT;

      if (
        this._blendOption === BlendOption$1.TRANSLUCENT ||
        this._blendOption === BlendOption$1.OPAQUE_AND_TRANSLUCENT
      ) {
        this._rsTranslucent = RenderState.fromCache({
          depthTest: {
            enabled: true,
            func: useTranslucentDepthMask
              ? WebGLConstants$1.LEQUAL
              : WebGLConstants$1.LESS,
          },
          depthMask: useTranslucentDepthMask,
          blending: BlendingState$1.ALPHA_BLEND,
        });
      } else {
        this._rsTranslucent = undefined;
      }
    }

    this._shaderDisableDepthDistance =
      this._shaderDisableDepthDistance ||
      frameState.minimumDisableDepthTestDistance !== 0.0;

    let vsSource;
    let fsSource;
    let vs;
    let fs;
    let vertDefines;

    const supportVSTextureReads =
      ContextLimits.maximumVertexTextureImageUnits > 0;

    if (
      blendOptionChanged ||
      this._shaderRotation !== this._compiledShaderRotation ||
      this._shaderAlignedAxis !== this._compiledShaderAlignedAxis ||
      this._shaderScaleByDistance !== this._compiledShaderScaleByDistance ||
      this._shaderTranslucencyByDistance !==
        this._compiledShaderTranslucencyByDistance ||
      this._shaderPixelOffsetScaleByDistance !==
        this._compiledShaderPixelOffsetScaleByDistance ||
      this._shaderDistanceDisplayCondition !==
        this._compiledShaderDistanceDisplayCondition ||
      this._shaderDisableDepthDistance !==
        this._compiledShaderDisableDepthDistance ||
      this._shaderClampToGround !== this._compiledShaderClampToGround ||
      this._sdf !== this._compiledSDF
    ) {
      vsSource = BillboardCollectionVS;
      fsSource = BillboardCollectionFS;

      vertDefines = [];
      if (defined(this._batchTable)) {
        vertDefines.push("VECTOR_TILE");
        vsSource = this._batchTable.getVertexShaderCallback(
          false,
          "a_batchId",
          undefined
        )(vsSource);
        fsSource = this._batchTable.getFragmentShaderCallback(
          false,
          undefined
        )(fsSource);
      }

      vs = new ShaderSource({
        defines: vertDefines,
        sources: [vsSource],
      });
      if (this._instanced) {
        vs.defines.push("INSTANCED");
      }
      if (this._shaderRotation) {
        vs.defines.push("ROTATION");
      }
      if (this._shaderAlignedAxis) {
        vs.defines.push("ALIGNED_AXIS");
      }
      if (this._shaderScaleByDistance) {
        vs.defines.push("EYE_DISTANCE_SCALING");
      }
      if (this._shaderTranslucencyByDistance) {
        vs.defines.push("EYE_DISTANCE_TRANSLUCENCY");
      }
      if (this._shaderPixelOffsetScaleByDistance) {
        vs.defines.push("EYE_DISTANCE_PIXEL_OFFSET");
      }
      if (this._shaderDistanceDisplayCondition) {
        vs.defines.push("DISTANCE_DISPLAY_CONDITION");
      }
      if (this._shaderDisableDepthDistance) {
        vs.defines.push("DISABLE_DEPTH_DISTANCE");
      }
      if (this._shaderClampToGround) {
        if (supportVSTextureReads) {
          vs.defines.push("VERTEX_DEPTH_CHECK");
        } else {
          vs.defines.push("FRAGMENT_DEPTH_CHECK");
        }
      }

      const sdfEdge = 1.0 - SDFSettings$1.CUTOFF;

      if (this._sdf) {
        vs.defines.push("SDF");
      }

      const vectorFragDefine = defined(this._batchTable) ? "VECTOR_TILE" : "";

      if (this._blendOption === BlendOption$1.OPAQUE_AND_TRANSLUCENT) {
        fs = new ShaderSource({
          defines: ["OPAQUE", vectorFragDefine],
          sources: [fsSource],
        });
        if (this._shaderClampToGround) {
          if (supportVSTextureReads) {
            fs.defines.push("VERTEX_DEPTH_CHECK");
          } else {
            fs.defines.push("FRAGMENT_DEPTH_CHECK");
          }
        }

        if (this._sdf) {
          fs.defines.push("SDF");
          fs.defines.push(`SDF_EDGE ${sdfEdge}`);
        }

        this._sp = ShaderProgram.replaceCache({
          context: context,
          shaderProgram: this._sp,
          vertexShaderSource: vs,
          fragmentShaderSource: fs,
          attributeLocations: attributeLocations$6,
        });

        fs = new ShaderSource({
          defines: ["TRANSLUCENT", vectorFragDefine],
          sources: [fsSource],
        });
        if (this._shaderClampToGround) {
          if (supportVSTextureReads) {
            fs.defines.push("VERTEX_DEPTH_CHECK");
          } else {
            fs.defines.push("FRAGMENT_DEPTH_CHECK");
          }
        }
        if (this._sdf) {
          fs.defines.push("SDF");
          fs.defines.push(`SDF_EDGE ${sdfEdge}`);
        }
        this._spTranslucent = ShaderProgram.replaceCache({
          context: context,
          shaderProgram: this._spTranslucent,
          vertexShaderSource: vs,
          fragmentShaderSource: fs,
          attributeLocations: attributeLocations$6,
        });
      }

      if (this._blendOption === BlendOption$1.OPAQUE) {
        fs = new ShaderSource({
          defines: [vectorFragDefine],
          sources: [fsSource],
        });
        if (this._shaderClampToGround) {
          if (supportVSTextureReads) {
            fs.defines.push("VERTEX_DEPTH_CHECK");
          } else {
            fs.defines.push("FRAGMENT_DEPTH_CHECK");
          }
        }
        if (this._sdf) {
          fs.defines.push("SDF");
          fs.defines.push(`SDF_EDGE ${sdfEdge}`);
        }
        this._sp = ShaderProgram.replaceCache({
          context: context,
          shaderProgram: this._sp,
          vertexShaderSource: vs,
          fragmentShaderSource: fs,
          attributeLocations: attributeLocations$6,
        });
      }

      if (this._blendOption === BlendOption$1.TRANSLUCENT) {
        fs = new ShaderSource({
          defines: [vectorFragDefine],
          sources: [fsSource],
        });
        if (this._shaderClampToGround) {
          if (supportVSTextureReads) {
            fs.defines.push("VERTEX_DEPTH_CHECK");
          } else {
            fs.defines.push("FRAGMENT_DEPTH_CHECK");
          }
        }
        if (this._sdf) {
          fs.defines.push("SDF");
          fs.defines.push(`SDF_EDGE ${sdfEdge}`);
        }
        this._spTranslucent = ShaderProgram.replaceCache({
          context: context,
          shaderProgram: this._spTranslucent,
          vertexShaderSource: vs,
          fragmentShaderSource: fs,
          attributeLocations: attributeLocations$6,
        });
      }

      this._compiledShaderRotation = this._shaderRotation;
      this._compiledShaderAlignedAxis = this._shaderAlignedAxis;
      this._compiledShaderScaleByDistance = this._shaderScaleByDistance;
      this._compiledShaderTranslucencyByDistance = this._shaderTranslucencyByDistance;
      this._compiledShaderPixelOffsetScaleByDistance = this._shaderPixelOffsetScaleByDistance;
      this._compiledShaderDistanceDisplayCondition = this._shaderDistanceDisplayCondition;
      this._compiledShaderDisableDepthDistance = this._shaderDisableDepthDistance;
      this._compiledShaderClampToGround = this._shaderClampToGround;
      this._compiledSDF = this._sdf;
    }

    const commandList = frameState.commandList;

    if (pass.render || pass.pick) {
      const colorList = this._colorCommands;

      const opaque = this._blendOption === BlendOption$1.OPAQUE;
      const opaqueAndTranslucent =
        this._blendOption === BlendOption$1.OPAQUE_AND_TRANSLUCENT;

      const va = this._vaf.va;
      const vaLength = va.length;

      let uniforms = this._uniforms;
      let pickId;
      if (defined(this._batchTable)) {
        uniforms = this._batchTable.getUniformMapCallback()(uniforms);
        pickId = this._batchTable.getPickId();
      } else {
        pickId = "v_pickColor";
      }

      colorList.length = vaLength;
      const totalLength = opaqueAndTranslucent ? vaLength * 2 : vaLength;
      for (let j = 0; j < totalLength; ++j) {
        let command = colorList[j];
        if (!defined(command)) {
          command = colorList[j] = new DrawCommand();
        }

        const opaqueCommand = opaque || (opaqueAndTranslucent && j % 2 === 0);

        command.pass =
          opaqueCommand || !opaqueAndTranslucent ? Pass$1.OPAQUE : Pass$1.TRANSLUCENT;
        command.owner = this;

        const index = opaqueAndTranslucent ? Math.floor(j / 2.0) : j;
        command.boundingVolume = boundingVolume;
        command.modelMatrix = modelMatrix;
        command.count = va[index].indicesCount;
        command.shaderProgram = opaqueCommand ? this._sp : this._spTranslucent;
        command.uniformMap = uniforms;
        command.vertexArray = va[index].va;
        command.renderState = opaqueCommand
          ? this._rsOpaque
          : this._rsTranslucent;
        command.debugShowBoundingVolume = this.debugShowBoundingVolume;
        command.pickId = pickId;

        if (this._instanced) {
          command.count = 6;
          command.instanceCount = billboardsLength;
        }

        commandList.push(command);
      }

      if (this.debugShowTextureAtlas) {
        if (!defined(this.debugCommand)) {
          this.debugCommand = createDebugCommand(this, frameState.context);
        }

        commandList.push(this.debugCommand);
      }
    }
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see BillboardCollection#destroy
   */
  BillboardCollection.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * billboards = billboards && billboards.destroy();
   *
   * @see BillboardCollection#isDestroyed
   */
  BillboardCollection.prototype.destroy = function () {
    if (defined(this._removeCallbackFunc)) {
      this._removeCallbackFunc();
      this._removeCallbackFunc = undefined;
    }

    this._textureAtlas =
      this._destroyTextureAtlas &&
      this._textureAtlas &&
      this._textureAtlas.destroy();
    this._sp = this._sp && this._sp.destroy();
    this._spTranslucent = this._spTranslucent && this._spTranslucent.destroy();
    this._vaf = this._vaf && this._vaf.destroy();
    destroyBillboards(this._billboards);

    return destroyObject(this);
  };

  /**
   * Creates a {@link createBillboardPointCallback.CanvasFunction} that will create a canvas with a point.
   *
   * @param {Number} centerAlpha The alpha of the center of the point. The value must be in the range [0.0, 1.0].
   * @param {String} cssColor The CSS color string.
   * @param {String} cssOutlineColor The CSS color of the point outline.
   * @param {Number} cssOutlineWidth The width of the outline in pixels.
   * @param {Number} pixelSize The size of the point in pixels.
   * @return {createBillboardPointCallback.CanvasFunction} The function that will return a canvas with the point drawn on it.
   *
   * @private
   */
  function createBillboardPointCallback(
    centerAlpha,
    cssColor,
    cssOutlineColor,
    cssOutlineWidth,
    pixelSize
  ) {
    return function () {
      const canvas = document.createElement("canvas");

      const length = pixelSize + 2 * cssOutlineWidth;
      canvas.height = canvas.width = length;

      const context2D = canvas.getContext("2d");
      context2D.clearRect(0, 0, length, length);

      if (cssOutlineWidth !== 0) {
        context2D.beginPath();
        context2D.arc(length / 2, length / 2, length / 2, 0, 2 * Math.PI, true);
        context2D.closePath();
        context2D.fillStyle = cssOutlineColor;
        context2D.fill();
        // Punch a hole in the center if needed.
        if (centerAlpha < 1.0) {
          context2D.save();
          context2D.globalCompositeOperation = "destination-out";
          context2D.beginPath();
          context2D.arc(
            length / 2,
            length / 2,
            pixelSize / 2,
            0,
            2 * Math.PI,
            true
          );
          context2D.closePath();
          context2D.fillStyle = "black";
          context2D.fill();
          context2D.restore();
        }
      }

      context2D.beginPath();
      context2D.arc(length / 2, length / 2, pixelSize / 2, 0, 2 * Math.PI, true);
      context2D.closePath();
      context2D.fillStyle = cssColor;
      context2D.fill();

      return canvas;
    };
  }

  /**
   * A point feature of a {@link Cesium3DTileset}.
   * <p>
   * Provides access to a feature's properties stored in the tile's batch table, as well
   * as the ability to show/hide a feature and change its point properties
   * </p>
   * <p>
   * Modifications to a <code>Cesium3DTilePointFeature</code> object have the lifetime of the tile's
   * content.  If the tile's content is unloaded, e.g., due to it going out of view and needing
   * to free space in the cache for visible tiles, listen to the {@link Cesium3DTileset#tileUnload} event to save any
   * modifications. Also listen to the {@link Cesium3DTileset#tileVisible} event to reapply any modifications.
   * </p>
   * <p>
   * Do not construct this directly.  Access it through {@link Cesium3DTileContent#getFeature}
   * or picking using {@link Scene#pick} and {@link Scene#pickPosition}.
   * </p>
   *
   * @alias Cesium3DTilePointFeature
   * @constructor
   *
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   *
   * @example
   * // On mouse over, display all the properties for a feature in the console log.
   * handler.setInputAction(function(movement) {
   *     const feature = scene.pick(movement.endPosition);
   *     if (feature instanceof Cesium.Cesium3DTilePointFeature) {
   *         const propertyIds = feature.getPropertyIds();
   *         const length = propertyIds.length;
   *         for (let i = 0; i < length; ++i) {
   *             const propertyId = propertyIds[i];
   *             console.log(`{propertyId}: ${feature.getProperty(propertyId)}`);
   *         }
   *     }
   * }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
   */
  function Cesium3DTilePointFeature(
    content,
    batchId,
    billboard,
    label,
    polyline
  ) {
    this._content = content;
    this._billboard = billboard;
    this._label = label;
    this._polyline = polyline;

    this._batchId = batchId;
    this._billboardImage = undefined;
    this._billboardColor = undefined;
    this._billboardOutlineColor = undefined;
    this._billboardOutlineWidth = undefined;
    this._billboardSize = undefined;
    this._pointSize = undefined;
    this._color = undefined;
    this._pointSize = undefined;
    this._pointOutlineColor = undefined;
    this._pointOutlineWidth = undefined;
    this._heightOffset = undefined;

    this._pickIds = new Array(3);

    setBillboardImage(this);
  }

  const scratchCartographic$c = new Cartographic();

  Object.defineProperties(Cesium3DTilePointFeature.prototype, {
    /**
     * Gets or sets if the feature will be shown. This is set for all features
     * when a style's show is evaluated.
     *
     * @memberof Cesium3DTilePointFeature.prototype
     *
     * @type {Boolean}
     *
     * @default true
     */
    show: {
      get: function () {
        return this._label.show;
      },
      set: function (value) {
        this._label.show = value;
        this._billboard.show = value;
        this._polyline.show = value;
      },
    },

    /**
     * Gets or sets the color of the point of this feature.
     * <p>
     * Only applied when <code>image</code> is <code>undefined</code>.
     * </p>
     *
     * @memberof Cesium3DTilePointFeature.prototype
     *
     * @type {Color}
     */
    color: {
      get: function () {
        return this._color;
      },
      set: function (value) {
        this._color = Color.clone(value, this._color);
        setBillboardImage(this);
      },
    },

    /**
     * Gets or sets the point size of this feature.
     * <p>
     * Only applied when <code>image</code> is <code>undefined</code>.
     * </p>
     *
     * @memberof Cesium3DTilePointFeature.prototype
     *
     * @type {Number}
     */
    pointSize: {
      get: function () {
        return this._pointSize;
      },
      set: function (value) {
        this._pointSize = value;
        setBillboardImage(this);
      },
    },

    /**
     * Gets or sets the point outline color of this feature.
     * <p>
     * Only applied when <code>image</code> is <code>undefined</code>.
     * </p>
     *
     * @memberof Cesium3DTilePointFeature.prototype
     *
     * @type {Color}
     */
    pointOutlineColor: {
      get: function () {
        return this._pointOutlineColor;
      },
      set: function (value) {
        this._pointOutlineColor = Color.clone(value, this._pointOutlineColor);
        setBillboardImage(this);
      },
    },

    /**
     * Gets or sets the point outline width in pixels of this feature.
     * <p>
     * Only applied when <code>image</code> is <code>undefined</code>.
     * </p>
     *
     * @memberof Cesium3DTilePointFeature.prototype
     *
     * @type {Number}
     */
    pointOutlineWidth: {
      get: function () {
        return this._pointOutlineWidth;
      },
      set: function (value) {
        this._pointOutlineWidth = value;
        setBillboardImage(this);
      },
    },

    /**
     * Gets or sets the label color of this feature.
     * <p>
     * The color will be applied to the label if <code>labelText</code> is defined.
     * </p>
     *
     * @memberof Cesium3DTilePointFeature.prototype
     *
     * @type {Color}
     */
    labelColor: {
      get: function () {
        return this._label.fillColor;
      },
      set: function (value) {
        this._label.fillColor = value;
        this._polyline.show = this._label.show && value.alpha > 0.0;
      },
    },

    /**
     * Gets or sets the label outline color of this feature.
     * <p>
     * The outline color will be applied to the label if <code>labelText</code> is defined.
     * </p>
     *
     * @memberof Cesium3DTilePointFeature.prototype
     *
     * @type {Color}
     */
    labelOutlineColor: {
      get: function () {
        return this._label.outlineColor;
      },
      set: function (value) {
        this._label.outlineColor = value;
      },
    },

    /**
     * Gets or sets the outline width in pixels of this feature.
     * <p>
     * The outline width will be applied to the point if <code>labelText</code> is defined.
     * </p>
     *
     * @memberof Cesium3DTilePointFeature.prototype
     *
     * @type {Number}
     */
    labelOutlineWidth: {
      get: function () {
        return this._label.outlineWidth;
      },
      set: function (value) {
        this._label.outlineWidth = value;
      },
    },

    /**
     * Gets or sets the font of this feature.
     * <p>
     * Only applied when the <code>labelText</code> is defined.
     * </p>
     *
     * @memberof Cesium3DTilePointFeature.prototype
     *
     * @type {String}
     */
    font: {
      get: function () {
        return this._label.font;
      },
      set: function (value) {
        this._label.font = value;
      },
    },

    /**
     * Gets or sets the fill and outline style of this feature.
     * <p>
     * Only applied when <code>labelText</code> is defined.
     * </p>
     *
     * @memberof Cesium3DTilePointFeature.prototype
     *
     * @type {LabelStyle}
     */
    labelStyle: {
      get: function () {
        return this._label.style;
      },
      set: function (value) {
        this._label.style = value;
      },
    },

    /**
     * Gets or sets the text for this feature.
     *
     * @memberof Cesium3DTilePointFeature.prototype
     *
     * @type {String}
     */
    labelText: {
      get: function () {
        return this._label.text;
      },
      set: function (value) {
        if (!defined(value)) {
          value = "";
        }
        this._label.text = value;
      },
    },

    /**
     * Gets or sets the background color of the text for this feature.
     * <p>
     * Only applied when <code>labelText</code> is defined.
     * </p>
     *
     * @memberof Cesium3DTilePointFeature.prototype
     *
     * @type {Color}
     */
    backgroundColor: {
      get: function () {
        return this._label.backgroundColor;
      },
      set: function (value) {
        this._label.backgroundColor = value;
      },
    },

    /**
     * Gets or sets the background padding of the text for this feature.
     * <p>
     * Only applied when <code>labelText</code> is defined.
     * </p>
     *
     * @memberof Cesium3DTilePointFeature.prototype
     *
     * @type {Cartesian2}
     */
    backgroundPadding: {
      get: function () {
        return this._label.backgroundPadding;
      },
      set: function (value) {
        this._label.backgroundPadding = value;
      },
    },

    /**
     * Gets or sets whether to display the background of the text for this feature.
     * <p>
     * Only applied when <code>labelText</code> is defined.
     * </p>
     *
     * @memberof Cesium3DTilePointFeature.prototype
     *
     * @type {Boolean}
     */
    backgroundEnabled: {
      get: function () {
        return this._label.showBackground;
      },
      set: function (value) {
        this._label.showBackground = value;
      },
    },

    /**
     * Gets or sets the near and far scaling properties for this feature.
     *
     * @memberof Cesium3DTilePointFeature.prototype
     *
     * @type {NearFarScalar}
     */
    scaleByDistance: {
      get: function () {
        return this._label.scaleByDistance;
      },
      set: function (value) {
        this._label.scaleByDistance = value;
        this._billboard.scaleByDistance = value;
      },
    },

    /**
     * Gets or sets the near and far translucency properties for this feature.
     *
     * @memberof Cesium3DTilePointFeature.prototype
     *
     * @type {NearFarScalar}
     */
    translucencyByDistance: {
      get: function () {
        return this._label.translucencyByDistance;
      },
      set: function (value) {
        this._label.translucencyByDistance = value;
        this._billboard.translucencyByDistance = value;
      },
    },

    /**
     * Gets or sets the condition specifying at what distance from the camera that this feature will be displayed.
     *
     * @memberof Cesium3DTilePointFeature.prototype
     *
     * @type {DistanceDisplayCondition}
     */
    distanceDisplayCondition: {
      get: function () {
        return this._label.distanceDisplayCondition;
      },
      set: function (value) {
        this._label.distanceDisplayCondition = value;
        this._polyline.distanceDisplayCondition = value;
        this._billboard.distanceDisplayCondition = value;
      },
    },

    /**
     * Gets or sets the height offset in meters of this feature.
     *
     * @memberof Cesium3DTilePointFeature.prototype
     *
     * @type {Number}
     */
    heightOffset: {
      get: function () {
        return this._heightOffset;
      },
      set: function (value) {
        const offset = defaultValue(this._heightOffset, 0.0);

        const ellipsoid = this._content.tileset.ellipsoid;
        const cart = ellipsoid.cartesianToCartographic(
          this._billboard.position,
          scratchCartographic$c
        );
        cart.height = cart.height - offset + value;
        const newPosition = ellipsoid.cartographicToCartesian(cart);

        this._billboard.position = newPosition;
        this._label.position = this._billboard.position;
        this._polyline.positions = [this._polyline.positions[0], newPosition];

        this._heightOffset = value;
      },
    },

    /**
     * Gets or sets whether the anchor line is displayed.
     * <p>
     * Only applied when <code>heightOffset</code> is defined.
     * </p>
     *
     * @memberof Cesium3DTilePointFeature.prototype
     *
     * @type {Boolean}
     */
    anchorLineEnabled: {
      get: function () {
        return this._polyline.show;
      },
      set: function (value) {
        this._polyline.show = value;
      },
    },

    /**
     * Gets or sets the color for the anchor line.
     * <p>
     * Only applied when <code>heightOffset</code> is defined.
     * </p>
     *
     * @memberof Cesium3DTilePointFeature.prototype
     *
     * @type {Color}
     */
    anchorLineColor: {
      get: function () {
        return this._polyline.material.uniforms.color;
      },
      set: function (value) {
        this._polyline.material.uniforms.color = Color.clone(
          value,
          this._polyline.material.uniforms.color
        );
      },
    },

    /**
     * Gets or sets the image of this feature.
     *
     * @memberof Cesium3DTilePointFeature.prototype
     *
     * @type {String}
     */
    image: {
      get: function () {
        return this._billboardImage;
      },
      set: function (value) {
        const imageChanged = this._billboardImage !== value;
        this._billboardImage = value;
        if (imageChanged) {
          setBillboardImage(this);
        }
      },
    },

    /**
     * Gets or sets the distance where depth testing will be disabled.
     *
     * @memberof Cesium3DTilePointFeature.prototype
     *
     * @type {Number}
     */
    disableDepthTestDistance: {
      get: function () {
        return this._label.disableDepthTestDistance;
      },
      set: function (value) {
        this._label.disableDepthTestDistance = value;
        this._billboard.disableDepthTestDistance = value;
      },
    },

    /**
     * Gets or sets the horizontal origin of this point, which determines if the point is
     * to the left, center, or right of its anchor position.
     *
     * @memberof Cesium3DTilePointFeature.prototype
     *
     * @type {HorizontalOrigin}
     */
    horizontalOrigin: {
      get: function () {
        return this._billboard.horizontalOrigin;
      },
      set: function (value) {
        this._billboard.horizontalOrigin = value;
      },
    },

    /**
     * Gets or sets the vertical origin of this point, which determines if the point is
     * to the bottom, center, or top of its anchor position.
     *
     * @memberof Cesium3DTilePointFeature.prototype
     *
     * @type {VerticalOrigin}
     */
    verticalOrigin: {
      get: function () {
        return this._billboard.verticalOrigin;
      },
      set: function (value) {
        this._billboard.verticalOrigin = value;
      },
    },

    /**
     * Gets or sets the horizontal origin of this point's text, which determines if the point's text is
     * to the left, center, or right of its anchor position.
     *
     * @memberof Cesium3DTilePointFeature.prototype
     *
     * @type {HorizontalOrigin}
     */
    labelHorizontalOrigin: {
      get: function () {
        return this._label.horizontalOrigin;
      },
      set: function (value) {
        this._label.horizontalOrigin = value;
      },
    },

    /**
     * Get or sets the vertical origin of this point's text, which determines if the point's text is
     * to the bottom, center, top, or baseline of it's anchor point.
     *
     * @memberof Cesium3DTilePointFeature.prototype
     *
     * @type {VerticalOrigin}
     */
    labelVerticalOrigin: {
      get: function () {
        return this._label.verticalOrigin;
      },
      set: function (value) {
        this._label.verticalOrigin = value;
      },
    },

    /**
     * Gets the content of the tile containing the feature.
     *
     * @memberof Cesium3DTilePointFeature.prototype
     *
     * @type {Cesium3DTileContent}
     *
     * @readonly
     * @private
     */
    content: {
      get: function () {
        return this._content;
      },
    },

    /**
     * Gets the tileset containing the feature.
     *
     * @memberof Cesium3DTilePointFeature.prototype
     *
     * @type {Cesium3DTileset}
     *
     * @readonly
     */
    tileset: {
      get: function () {
        return this._content.tileset;
      },
    },

    /**
     * All objects returned by {@link Scene#pick} have a <code>primitive</code> property. This returns
     * the tileset containing the feature.
     *
     * @memberof Cesium3DTilePointFeature.prototype
     *
     * @type {Cesium3DTileset}
     *
     * @readonly
     */
    primitive: {
      get: function () {
        return this._content.tileset;
      },
    },

    /**
     * @private
     */
    pickIds: {
      get: function () {
        const ids = this._pickIds;
        ids[0] = this._billboard.pickId;
        ids[1] = this._label.pickId;
        ids[2] = this._polyline.pickId;
        return ids;
      },
    },
  });

  Cesium3DTilePointFeature.defaultColor = Color.WHITE;
  Cesium3DTilePointFeature.defaultPointOutlineColor = Color.BLACK;
  Cesium3DTilePointFeature.defaultPointOutlineWidth = 0.0;
  Cesium3DTilePointFeature.defaultPointSize = 8.0;

  function setBillboardImage(feature) {
    const b = feature._billboard;
    if (defined(feature._billboardImage) && feature._billboardImage !== b.image) {
      b.image = feature._billboardImage;
      return;
    }

    if (defined(feature._billboardImage)) {
      return;
    }

    const newColor = defaultValue(
      feature._color,
      Cesium3DTilePointFeature.defaultColor
    );
    const newOutlineColor = defaultValue(
      feature._pointOutlineColor,
      Cesium3DTilePointFeature.defaultPointOutlineColor
    );
    const newOutlineWidth = defaultValue(
      feature._pointOutlineWidth,
      Cesium3DTilePointFeature.defaultPointOutlineWidth
    );
    const newPointSize = defaultValue(
      feature._pointSize,
      Cesium3DTilePointFeature.defaultPointSize
    );

    const currentColor = feature._billboardColor;
    const currentOutlineColor = feature._billboardOutlineColor;
    const currentOutlineWidth = feature._billboardOutlineWidth;
    const currentPointSize = feature._billboardSize;

    if (
      Color.equals(newColor, currentColor) &&
      Color.equals(newOutlineColor, currentOutlineColor) &&
      newOutlineWidth === currentOutlineWidth &&
      newPointSize === currentPointSize
    ) {
      return;
    }

    feature._billboardColor = Color.clone(newColor, feature._billboardColor);
    feature._billboardOutlineColor = Color.clone(
      newOutlineColor,
      feature._billboardOutlineColor
    );
    feature._billboardOutlineWidth = newOutlineWidth;
    feature._billboardSize = newPointSize;

    const centerAlpha = newColor.alpha;
    const cssColor = newColor.toCssColorString();
    const cssOutlineColor = newOutlineColor.toCssColorString();
    const textureId = JSON.stringify([
      cssColor,
      newPointSize,
      cssOutlineColor,
      newOutlineWidth,
    ]);

    b.setImage(
      textureId,
      createBillboardPointCallback(
        centerAlpha,
        cssColor,
        cssOutlineColor,
        newOutlineWidth,
        newPointSize
      )
    );
  }

  /**
   * Returns whether the feature contains this property. This includes properties from this feature's
   * class and inherited classes when using a batch table hierarchy.
   *
   * @see {@link https://github.com/CesiumGS/3d-tiles/tree/main/extensions/3DTILES_batch_table_hierarchy}
   *
   * @param {String} name The case-sensitive name of the property.
   * @returns {Boolean} Whether the feature contains this property.
   */
  Cesium3DTilePointFeature.prototype.hasProperty = function (name) {
    return this._content.batchTable.hasProperty(this._batchId, name);
  };

  /**
   * Returns an array of property names for the feature. This includes properties from this feature's
   * class and inherited classes when using a batch table hierarchy.
   *
   * @see {@link https://github.com/CesiumGS/3d-tiles/tree/main/extensions/3DTILES_batch_table_hierarchy}
   *
   * @deprecated
   *
   * @param {String[]} [results] An array into which to store the results.
   * @returns {String[]} The names of the feature's properties.
   */
  Cesium3DTilePointFeature.prototype.getPropertyNames = function (results) {
    deprecationWarning(
      "Cesium3DTilePointFeature.getPropertyNames",
      "Cesium3DTilePointFeature.getPropertyNames is deprecated in CesiumJS 1.95, and will be removed in 1.98. Use Cesium3DTilePointFeature.getPropertyIds instead"
    );
    return this._content.batchTable.getPropertyIds(this._batchId, results);
  };

  /**
   * Returns an array of property IDs for the feature. This includes properties from this feature's
   * class and inherited classes when using a batch table hierarchy.
   *
   * @see {@link https://github.com/CesiumGS/3d-tiles/tree/main/extensions/3DTILES_batch_table_hierarchy}
   *
   * @param {String[]} [results] An array into which to store the results.
   * @returns {String[]} The IDs of the feature's properties.
   */
  Cesium3DTilePointFeature.prototype.getPropertyIds = function (results) {
    return this._content.batchTable.getPropertyIds(this._batchId, results);
  };

  /**
   * Returns a copy of the value of the feature's property with the given name. This includes properties from this feature's
   * class and inherited classes when using a batch table hierarchy.
   *
   * @see {@link https://github.com/CesiumGS/3d-tiles/tree/main/extensions/3DTILES_batch_table_hierarchy}
   *
   * @param {String} name The case-sensitive name of the property.
   * @returns {*} The value of the property or <code>undefined</code> if the feature does not have this property.
   *
   * @example
   * // Display all the properties for a feature in the console log.
   * const propertyIds = feature.getPropertyIds();
   * const length = propertyIds.length;
   * for (let i = 0; i < length; ++i) {
   *     const propertyId = propertyIds[i];
   *     console.log(`{propertyId} : ${feature.getProperty(propertyId)}`);
   * }
   */
  Cesium3DTilePointFeature.prototype.getProperty = function (name) {
    return this._content.batchTable.getProperty(this._batchId, name);
  };

  /**
   * Returns a copy of the value of the feature's property with the given name.
   * If the feature is contained within a tileset that has metadata (3D Tiles 1.1)
   * or uses the <code>3DTILES_metadata</code> extension, tileset, group and tile metadata is
   * inherited.
   * <p>
   * To resolve name conflicts, this method resolves names from most specific to
   * least specific by metadata granularity in the order: feature, tile, group,
   * tileset. Within each granularity, semantics are resolved first, then other
   * properties.
   * </p>
   * @param {String} name The case-sensitive name of the property.
   * @returns {*} The value of the property or <code>undefined</code> if the feature does not have this property.
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  Cesium3DTilePointFeature.prototype.getPropertyInherited = function (name) {
    return Cesium3DTileFeature.getPropertyInherited(
      this._content,
      this._batchId,
      name
    );
  };

  /**
   * Sets the value of the feature's property with the given name.
   * <p>
   * If a property with the given name doesn't exist, it is created.
   * </p>
   *
   * @param {String} name The case-sensitive name of the property.
   * @param {*} value The value of the property that will be copied.
   *
   * @exception {DeveloperError} Inherited batch table hierarchy property is read only.
   *
   * @example
   * const height = feature.getProperty('Height'); // e.g., the height of a building
   *
   * @example
   * const name = 'clicked';
   * if (feature.getProperty(name)) {
   *     console.log('already clicked');
   * } else {
   *     feature.setProperty(name, true);
   *     console.log('first click');
   * }
   */
  Cesium3DTilePointFeature.prototype.setProperty = function (name, value) {
    this._content.batchTable.setProperty(this._batchId, name, value);

    // PERFORMANCE_IDEA: Probably overkill, but maybe only mark the tile dirty if the
    // property is in one of the style's expressions or - if it can be done quickly -
    // if the new property value changed the result of an expression.
    this._content.featurePropertiesDirty = true;
  };

  /**
   * Returns whether the feature's class name equals <code>className</code>. Unlike {@link Cesium3DTilePointFeature#isClass}
   * this function only checks the feature's exact class and not inherited classes.
   * <p>
   * This function returns <code>false</code> if no batch table hierarchy is present.
   * </p>
   *
   * @param {String} className The name to check against.
   * @returns {Boolean} Whether the feature's class name equals <code>className</code>
   *
   * @private
   */
  Cesium3DTilePointFeature.prototype.isExactClass = function (className) {
    return this._content.batchTable.isExactClass(this._batchId, className);
  };

  /**
   * Returns whether the feature's class or any inherited classes are named <code>className</code>.
   * <p>
   * This function returns <code>false</code> if no batch table hierarchy is present.
   * </p>
   *
   * @param {String} className The name to check against.
   * @returns {Boolean} Whether the feature's class or inherited classes are named <code>className</code>
   *
   * @private
   */
  Cesium3DTilePointFeature.prototype.isClass = function (className) {
    return this._content.batchTable.isClass(this._batchId, className);
  };

  /**
   * Returns the feature's class name.
   * <p>
   * This function returns <code>undefined</code> if no batch table hierarchy is present.
   * </p>
   *
   * @returns {String} The feature's class name.
   *
   * @private
   */
  Cesium3DTilePointFeature.prototype.getExactClassName = function () {
    return this._content.batchTable.getExactClassName(this._batchId);
  };

  /* This file is automatically rebuilt by the Cesium build process. */
  var bitmapSdf = calcSDF;

  var INF = 1e20;

  function calcSDF(src, options) {
      if (!options) options = {};

      var cutoff = options.cutoff == null ? 0.25 : options.cutoff;
      var radius = options.radius == null ? 8 : options.radius;
      var channel = options.channel || 0;
      var w, h, size, data, intData, stride, ctx, canvas, imgData, i, l;

      // handle image container
      if (ArrayBuffer.isView(src) || Array.isArray(src)) {
          if (!options.width || !options.height) throw Error('For raw data width and height should be provided by options')
          w = options.width, h = options.height;
          data = src;

          if (!options.stride) stride = Math.floor(src.length / w / h);
          else stride = options.stride;
      }
      else {
          if (window.HTMLCanvasElement && src instanceof window.HTMLCanvasElement) {
              canvas = src;
              ctx = canvas.getContext('2d');
              w = canvas.width, h = canvas.height;
              imgData = ctx.getImageData(0, 0, w, h);
              data = imgData.data;
              stride = 4;
          }
          else if (window.CanvasRenderingContext2D && src instanceof window.CanvasRenderingContext2D) {
              canvas = src.canvas;
              ctx = src;
              w = canvas.width, h = canvas.height;
              imgData = ctx.getImageData(0, 0, w, h);
              data = imgData.data;
              stride = 4;
          }
          else if (window.ImageData && src instanceof window.ImageData) {
              imgData = src;
              w = src.width, h = src.height;
              data = imgData.data;
              stride = 4;
          }
      }

      size = Math.max(w, h);

      //convert int data to floats
      if ((window.Uint8ClampedArray && data instanceof window.Uint8ClampedArray) || (window.Uint8Array && data instanceof window.Uint8Array)) {
          intData = data;
          data = Array(w*h);

          for (i = 0, l = Math.floor(intData.length / stride); i < l; i++) {
              data[i] = intData[i*stride + channel] / 255;
          }
      }
      else {
          if (stride !== 1) throw Error('Raw data can have only 1 value per pixel')
      }

      // temporary arrays for the distance transform
      var gridOuter = Array(w * h);
      var gridInner = Array(w * h);
      var f = Array(size);
      var d = Array(size);
      var z = Array(size + 1);
      var v = Array(size);

      for (i = 0, l = w * h; i < l; i++) {
          var a = data[i];
          gridOuter[i] = a === 1 ? 0 : a === 0 ? INF : Math.pow(Math.max(0, 0.5 - a), 2);
          gridInner[i] = a === 1 ? INF : a === 0 ? 0 : Math.pow(Math.max(0, a - 0.5), 2);
      }

      edt(gridOuter, w, h, f, d, v, z);
      edt(gridInner, w, h, f, d, v, z);

      var dist = window.Float32Array ? new Float32Array(w * h) : new Array(w * h);

      for (i = 0, l = w*h; i < l; i++) {
          dist[i] = Math.min(Math.max(1 - ( (gridOuter[i] - gridInner[i]) / radius + cutoff), 0), 1);
      }

      return dist
  }

  // 2D Euclidean distance transform by Felzenszwalb & Huttenlocher https://cs.brown.edu/~pff/dt/
  function edt(data, width, height, f, d, v, z) {
      for (var x = 0; x < width; x++) {
          for (var y = 0; y < height; y++) {
              f[y] = data[y * width + x];
          }
          edt1d(f, d, v, z, height);
          for (y = 0; y < height; y++) {
              data[y * width + x] = d[y];
          }
      }
      for (y = 0; y < height; y++) {
          for (x = 0; x < width; x++) {
              f[x] = data[y * width + x];
          }
          edt1d(f, d, v, z, width);
          for (x = 0; x < width; x++) {
              data[y * width + x] = Math.sqrt(d[x]);
          }
      }
  }

  // 1D squared distance transform
  function edt1d(f, d, v, z, n) {
      v[0] = 0;
      z[0] = -INF;
      z[1] = +INF;

      for (var q = 1, k = 0; q < n; q++) {
          var s = ((f[q] + q * q) - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]);
          while (s <= z[k]) {
              k--;
              s = ((f[q] + q * q) - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]);
          }
          k++;
          v[k] = q;
          z[k] = s;
          z[k + 1] = +INF;
      }

      for (q = 0, k = 0; q < n; q++) {
          while (z[k + 1] < q) k++;
          d[q] = (q - v[k]) * (q - v[k]) + f[v[k]];
      }
  }

  /**
   * Describes how to draw a label.
   *
   * @enum {Number}
   *
   * @see Label#style
   */
  const LabelStyle = {
    /**
     * Fill the text of the label, but do not outline.
     *
     * @type {Number}
     * @constant
     */
    FILL: 0,

    /**
     * Outline the text of the label, but do not fill.
     *
     * @type {Number}
     * @constant
     */
    OUTLINE: 1,

    /**
     * Fill and outline the text of the label.
     *
     * @type {Number}
     * @constant
     */
    FILL_AND_OUTLINE: 2,
  };
  var LabelStyle$1 = Object.freeze(LabelStyle);

  const fontInfoCache = {};
  let fontInfoCacheLength = 0;
  const fontInfoCacheMaxSize = 256;
  const defaultBackgroundColor$2 = new Color(0.165, 0.165, 0.165, 0.8);
  const defaultBackgroundPadding$1 = new Cartesian2(7, 5);

  const textTypes = Object.freeze({
    LTR: 0,
    RTL: 1,
    WEAK: 2,
    BRACKETS: 3,
  });

  function rebindAllGlyphs$1(label) {
    if (!label._rebindAllGlyphs && !label._repositionAllGlyphs) {
      // only push label if it's not already been marked dirty
      label._labelCollection._labelsToUpdate.push(label);
    }
    label._rebindAllGlyphs = true;
  }

  function repositionAllGlyphs$1(label) {
    if (!label._rebindAllGlyphs && !label._repositionAllGlyphs) {
      // only push label if it's not already been marked dirty
      label._labelCollection._labelsToUpdate.push(label);
    }
    label._repositionAllGlyphs = true;
  }

  function getCSSValue(element, property) {
    return document.defaultView
      .getComputedStyle(element, null)
      .getPropertyValue(property);
  }

  function parseFont(label) {
    let fontInfo = fontInfoCache[label._font];
    if (!defined(fontInfo)) {
      const div = document.createElement("div");
      div.style.position = "absolute";
      div.style.opacity = 0;
      div.style.font = label._font;
      document.body.appendChild(div);

      let lineHeight = parseFloat(getCSSValue(div, "line-height"));
      if (isNaN(lineHeight)) {
        // line-height isn't a number, i.e. 'normal'; apply default line-spacing
        lineHeight = undefined;
      }

      fontInfo = {
        family: getCSSValue(div, "font-family"),
        size: getCSSValue(div, "font-size").replace("px", ""),
        style: getCSSValue(div, "font-style"),
        weight: getCSSValue(div, "font-weight"),
        lineHeight: lineHeight,
      };

      document.body.removeChild(div);
      if (fontInfoCacheLength < fontInfoCacheMaxSize) {
        fontInfoCache[label._font] = fontInfo;
        fontInfoCacheLength++;
      }
    }
    label._fontFamily = fontInfo.family;
    label._fontSize = fontInfo.size;
    label._fontStyle = fontInfo.style;
    label._fontWeight = fontInfo.weight;
    label._lineHeight = fontInfo.lineHeight;
  }

  /**
   * A Label draws viewport-aligned text positioned in the 3D scene.  This constructor
   * should not be used directly, instead create labels by calling {@link LabelCollection#add}.
   *
   * @alias Label
   * @internalConstructor
   * @class
   *
   * @exception {DeveloperError} translucencyByDistance.far must be greater than translucencyByDistance.near
   * @exception {DeveloperError} pixelOffsetScaleByDistance.far must be greater than pixelOffsetScaleByDistance.near
   * @exception {DeveloperError} distanceDisplayCondition.far must be greater than distanceDisplayCondition.near
   *
   * @see LabelCollection
   * @see LabelCollection#add
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Labels.html|Cesium Sandcastle Labels Demo}
   */
  function Label(options, labelCollection) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    if (
      defined(options.disableDepthTestDistance) &&
      options.disableDepthTestDistance < 0.0
    ) {
      throw new DeveloperError(
        "disableDepthTestDistance must be greater than 0.0."
      );
    }
    //>>includeEnd('debug');

    let translucencyByDistance = options.translucencyByDistance;
    let pixelOffsetScaleByDistance = options.pixelOffsetScaleByDistance;
    let scaleByDistance = options.scaleByDistance;
    let distanceDisplayCondition = options.distanceDisplayCondition;
    if (defined(translucencyByDistance)) {
      //>>includeStart('debug', pragmas.debug);
      if (translucencyByDistance.far <= translucencyByDistance.near) {
        throw new DeveloperError(
          "translucencyByDistance.far must be greater than translucencyByDistance.near."
        );
      }
      //>>includeEnd('debug');
      translucencyByDistance = NearFarScalar.clone(translucencyByDistance);
    }
    if (defined(pixelOffsetScaleByDistance)) {
      //>>includeStart('debug', pragmas.debug);
      if (pixelOffsetScaleByDistance.far <= pixelOffsetScaleByDistance.near) {
        throw new DeveloperError(
          "pixelOffsetScaleByDistance.far must be greater than pixelOffsetScaleByDistance.near."
        );
      }
      //>>includeEnd('debug');
      pixelOffsetScaleByDistance = NearFarScalar.clone(
        pixelOffsetScaleByDistance
      );
    }
    if (defined(scaleByDistance)) {
      //>>includeStart('debug', pragmas.debug);
      if (scaleByDistance.far <= scaleByDistance.near) {
        throw new DeveloperError(
          "scaleByDistance.far must be greater than scaleByDistance.near."
        );
      }
      //>>includeEnd('debug');
      scaleByDistance = NearFarScalar.clone(scaleByDistance);
    }
    if (defined(distanceDisplayCondition)) {
      //>>includeStart('debug', pragmas.debug);
      if (distanceDisplayCondition.far <= distanceDisplayCondition.near) {
        throw new DeveloperError(
          "distanceDisplayCondition.far must be greater than distanceDisplayCondition.near."
        );
      }
      //>>includeEnd('debug');
      distanceDisplayCondition = DistanceDisplayCondition.clone(
        distanceDisplayCondition
      );
    }

    this._renderedText = undefined;
    this._text = undefined;
    this._show = defaultValue(options.show, true);
    this._font = defaultValue(options.font, "30px sans-serif");
    this._fillColor = Color.clone(defaultValue(options.fillColor, Color.WHITE));
    this._outlineColor = Color.clone(
      defaultValue(options.outlineColor, Color.BLACK)
    );
    this._outlineWidth = defaultValue(options.outlineWidth, 1.0);
    this._showBackground = defaultValue(options.showBackground, false);
    this._backgroundColor = Color.clone(
      defaultValue(options.backgroundColor, defaultBackgroundColor$2)
    );
    this._backgroundPadding = Cartesian2.clone(
      defaultValue(options.backgroundPadding, defaultBackgroundPadding$1)
    );
    this._style = defaultValue(options.style, LabelStyle$1.FILL);
    this._verticalOrigin = defaultValue(
      options.verticalOrigin,
      VerticalOrigin$1.BASELINE
    );
    this._horizontalOrigin = defaultValue(
      options.horizontalOrigin,
      HorizontalOrigin$1.LEFT
    );
    this._pixelOffset = Cartesian2.clone(
      defaultValue(options.pixelOffset, Cartesian2.ZERO)
    );
    this._eyeOffset = Cartesian3.clone(
      defaultValue(options.eyeOffset, Cartesian3.ZERO)
    );
    this._position = Cartesian3.clone(
      defaultValue(options.position, Cartesian3.ZERO)
    );
    this._scale = defaultValue(options.scale, 1.0);
    this._id = options.id;
    this._translucencyByDistance = translucencyByDistance;
    this._pixelOffsetScaleByDistance = pixelOffsetScaleByDistance;
    this._scaleByDistance = scaleByDistance;
    this._heightReference = defaultValue(
      options.heightReference,
      HeightReference$1.NONE
    );
    this._distanceDisplayCondition = distanceDisplayCondition;
    this._disableDepthTestDistance = options.disableDepthTestDistance;

    this._labelCollection = labelCollection;
    this._glyphs = [];
    this._backgroundBillboard = undefined;
    this._batchIndex = undefined; // Used only by Vector3DTilePoints and BillboardCollection

    this._rebindAllGlyphs = true;
    this._repositionAllGlyphs = true;

    this._actualClampedPosition = undefined;
    this._removeCallbackFunc = undefined;
    this._mode = undefined;

    this._clusterShow = true;

    this.text = defaultValue(options.text, "");

    this._relativeSize = 1.0;

    parseFont(this);

    this._updateClamping();
  }

  Object.defineProperties(Label.prototype, {
    /**
     * Determines if this label will be shown.  Use this to hide or show a label, instead
     * of removing it and re-adding it to the collection.
     * @memberof Label.prototype
     * @type {Boolean}
     * @default true
     */
    show: {
      get: function () {
        return this._show;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        if (this._show !== value) {
          this._show = value;

          const glyphs = this._glyphs;
          for (let i = 0, len = glyphs.length; i < len; i++) {
            const billboard = glyphs[i].billboard;
            if (defined(billboard)) {
              billboard.show = value;
            }
          }
          const backgroundBillboard = this._backgroundBillboard;
          if (defined(backgroundBillboard)) {
            backgroundBillboard.show = value;
          }
        }
      },
    },

    /**
     * Gets or sets the Cartesian position of this label.
     * @memberof Label.prototype
     * @type {Cartesian3}
     */
    position: {
      get: function () {
        return this._position;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        const position = this._position;
        if (!Cartesian3.equals(position, value)) {
          Cartesian3.clone(value, position);

          const glyphs = this._glyphs;
          for (let i = 0, len = glyphs.length; i < len; i++) {
            const billboard = glyphs[i].billboard;
            if (defined(billboard)) {
              billboard.position = value;
            }
          }
          const backgroundBillboard = this._backgroundBillboard;
          if (defined(backgroundBillboard)) {
            backgroundBillboard.position = value;
          }

          this._updateClamping();
        }
      },
    },

    /**
     * Gets or sets the height reference of this billboard.
     * @memberof Label.prototype
     * @type {HeightReference}
     * @default HeightReference.NONE
     */
    heightReference: {
      get: function () {
        return this._heightReference;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        if (value !== this._heightReference) {
          this._heightReference = value;

          const glyphs = this._glyphs;
          for (let i = 0, len = glyphs.length; i < len; i++) {
            const billboard = glyphs[i].billboard;
            if (defined(billboard)) {
              billboard.heightReference = value;
            }
          }
          const backgroundBillboard = this._backgroundBillboard;
          if (defined(backgroundBillboard)) {
            backgroundBillboard.heightReference = value;
          }

          repositionAllGlyphs$1(this);

          this._updateClamping();
        }
      },
    },

    /**
     * Gets or sets the text of this label.
     * @memberof Label.prototype
     * @type {String}
     */
    text: {
      get: function () {
        return this._text;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        if (this._text !== value) {
          this._text = value;

          // Strip soft-hyphen (auto-wrap) characters from input string
          const renderedValue = value.replace(/\u00ad/g, "");
          this._renderedText = Label.enableRightToLeftDetection
            ? reverseRtl(renderedValue)
            : renderedValue;
          rebindAllGlyphs$1(this);
        }
      },
    },

    /**
     * Gets or sets the font used to draw this label. Fonts are specified using the same syntax as the CSS 'font' property.
     * @memberof Label.prototype
     * @type {String}
     * @default '30px sans-serif'
     * @see {@link http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#text-styles|HTML canvas 2D context text styles}
     */
    font: {
      get: function () {
        return this._font;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        if (this._font !== value) {
          this._font = value;
          rebindAllGlyphs$1(this);
          parseFont(this);
        }
      },
    },

    /**
     * Gets or sets the fill color of this label.
     * @memberof Label.prototype
     * @type {Color}
     * @default Color.WHITE
     * @see {@link http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#fill-and-stroke-styles|HTML canvas 2D context fill and stroke styles}
     */
    fillColor: {
      get: function () {
        return this._fillColor;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        const fillColor = this._fillColor;
        if (!Color.equals(fillColor, value)) {
          Color.clone(value, fillColor);
          rebindAllGlyphs$1(this);
        }
      },
    },

    /**
     * Gets or sets the outline color of this label.
     * @memberof Label.prototype
     * @type {Color}
     * @default Color.BLACK
     * @see {@link http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#fill-and-stroke-styles|HTML canvas 2D context fill and stroke styles}
     */
    outlineColor: {
      get: function () {
        return this._outlineColor;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        const outlineColor = this._outlineColor;
        if (!Color.equals(outlineColor, value)) {
          Color.clone(value, outlineColor);
          rebindAllGlyphs$1(this);
        }
      },
    },

    /**
     * Gets or sets the outline width of this label.
     * @memberof Label.prototype
     * @type {Number}
     * @default 1.0
     * @see {@link http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#fill-and-stroke-styles|HTML canvas 2D context fill and stroke styles}
     */
    outlineWidth: {
      get: function () {
        return this._outlineWidth;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        if (this._outlineWidth !== value) {
          this._outlineWidth = value;
          rebindAllGlyphs$1(this);
        }
      },
    },

    /**
     * Determines if a background behind this label will be shown.
     * @memberof Label.prototype
     * @default false
     * @type {Boolean}
     */
    showBackground: {
      get: function () {
        return this._showBackground;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        if (this._showBackground !== value) {
          this._showBackground = value;
          rebindAllGlyphs$1(this);
        }
      },
    },

    /**
     * Gets or sets the background color of this label.
     * @memberof Label.prototype
     * @type {Color}
     * @default new Color(0.165, 0.165, 0.165, 0.8)
     */
    backgroundColor: {
      get: function () {
        return this._backgroundColor;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        const backgroundColor = this._backgroundColor;
        if (!Color.equals(backgroundColor, value)) {
          Color.clone(value, backgroundColor);

          const backgroundBillboard = this._backgroundBillboard;
          if (defined(backgroundBillboard)) {
            backgroundBillboard.color = backgroundColor;
          }
        }
      },
    },

    /**
     * Gets or sets the background padding, in pixels, of this label.  The <code>x</code> value
     * controls horizontal padding, and the <code>y</code> value controls vertical padding.
     * @memberof Label.prototype
     * @type {Cartesian2}
     * @default new Cartesian2(7, 5)
     */
    backgroundPadding: {
      get: function () {
        return this._backgroundPadding;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        const backgroundPadding = this._backgroundPadding;
        if (!Cartesian2.equals(backgroundPadding, value)) {
          Cartesian2.clone(value, backgroundPadding);
          repositionAllGlyphs$1(this);
        }
      },
    },

    /**
     * Gets or sets the style of this label.
     * @memberof Label.prototype
     * @type {LabelStyle}
     * @default LabelStyle.FILL
     */
    style: {
      get: function () {
        return this._style;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        if (this._style !== value) {
          this._style = value;
          rebindAllGlyphs$1(this);
        }
      },
    },

    /**
     * Gets or sets the pixel offset in screen space from the origin of this label.  This is commonly used
     * to align multiple labels and billboards at the same position, e.g., an image and text.  The
     * screen space origin is the top, left corner of the canvas; <code>x</code> increases from
     * left to right, and <code>y</code> increases from top to bottom.
     * <br /><br />
     * <div align='center'>
     * <table border='0' cellpadding='5'><tr>
     * <td align='center'><code>default</code><br/><img src='Images/Label.setPixelOffset.default.png' width='250' height='188' /></td>
     * <td align='center'><code>l.pixeloffset = new Cartesian2(25, 75);</code><br/><img src='Images/Label.setPixelOffset.x50y-25.png' width='250' height='188' /></td>
     * </tr></table>
     * The label's origin is indicated by the yellow point.
     * </div>
     * @memberof Label.prototype
     * @type {Cartesian2}
     * @default Cartesian2.ZERO
     */
    pixelOffset: {
      get: function () {
        return this._pixelOffset;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        const pixelOffset = this._pixelOffset;
        if (!Cartesian2.equals(pixelOffset, value)) {
          Cartesian2.clone(value, pixelOffset);

          const glyphs = this._glyphs;
          for (let i = 0, len = glyphs.length; i < len; i++) {
            const glyph = glyphs[i];
            if (defined(glyph.billboard)) {
              glyph.billboard.pixelOffset = value;
            }
          }
          const backgroundBillboard = this._backgroundBillboard;
          if (defined(backgroundBillboard)) {
            backgroundBillboard.pixelOffset = value;
          }
        }
      },
    },

    /**
     * Gets or sets near and far translucency properties of a Label based on the Label's distance from the camera.
     * A label's translucency will interpolate between the {@link NearFarScalar#nearValue} and
     * {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds
     * of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}.
     * Outside of these ranges the label's translucency remains clamped to the nearest bound.  If undefined,
     * translucencyByDistance will be disabled.
     * @memberof Label.prototype
     * @type {NearFarScalar}
     *
     * @example
     * // Example 1.
     * // Set a label's translucencyByDistance to 1.0 when the
     * // camera is 1500 meters from the label and disappear as
     * // the camera distance approaches 8.0e6 meters.
     * text.translucencyByDistance = new Cesium.NearFarScalar(1.5e2, 1.0, 8.0e6, 0.0);
     *
     * @example
     * // Example 2.
     * // disable translucency by distance
     * text.translucencyByDistance = undefined;
     */
    translucencyByDistance: {
      get: function () {
        return this._translucencyByDistance;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (defined(value) && value.far <= value.near) {
          throw new DeveloperError(
            "far distance must be greater than near distance."
          );
        }
        //>>includeEnd('debug');

        const translucencyByDistance = this._translucencyByDistance;
        if (!NearFarScalar.equals(translucencyByDistance, value)) {
          this._translucencyByDistance = NearFarScalar.clone(
            value,
            translucencyByDistance
          );

          const glyphs = this._glyphs;
          for (let i = 0, len = glyphs.length; i < len; i++) {
            const glyph = glyphs[i];
            if (defined(glyph.billboard)) {
              glyph.billboard.translucencyByDistance = value;
            }
          }
          const backgroundBillboard = this._backgroundBillboard;
          if (defined(backgroundBillboard)) {
            backgroundBillboard.translucencyByDistance = value;
          }
        }
      },
    },

    /**
     * Gets or sets near and far pixel offset scaling properties of a Label based on the Label's distance from the camera.
     * A label's pixel offset will be scaled between the {@link NearFarScalar#nearValue} and
     * {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds
     * of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}.
     * Outside of these ranges the label's pixel offset scaling remains clamped to the nearest bound.  If undefined,
     * pixelOffsetScaleByDistance will be disabled.
     * @memberof Label.prototype
     * @type {NearFarScalar}
     *
     * @example
     * // Example 1.
     * // Set a label's pixel offset scale to 0.0 when the
     * // camera is 1500 meters from the label and scale pixel offset to 10.0 pixels
     * // in the y direction the camera distance approaches 8.0e6 meters.
     * text.pixelOffset = new Cesium.Cartesian2(0.0, 1.0);
     * text.pixelOffsetScaleByDistance = new Cesium.NearFarScalar(1.5e2, 0.0, 8.0e6, 10.0);
     *
     * @example
     * // Example 2.
     * // disable pixel offset by distance
     * text.pixelOffsetScaleByDistance = undefined;
     */
    pixelOffsetScaleByDistance: {
      get: function () {
        return this._pixelOffsetScaleByDistance;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (defined(value) && value.far <= value.near) {
          throw new DeveloperError(
            "far distance must be greater than near distance."
          );
        }
        //>>includeEnd('debug');

        const pixelOffsetScaleByDistance = this._pixelOffsetScaleByDistance;
        if (!NearFarScalar.equals(pixelOffsetScaleByDistance, value)) {
          this._pixelOffsetScaleByDistance = NearFarScalar.clone(
            value,
            pixelOffsetScaleByDistance
          );

          const glyphs = this._glyphs;
          for (let i = 0, len = glyphs.length; i < len; i++) {
            const glyph = glyphs[i];
            if (defined(glyph.billboard)) {
              glyph.billboard.pixelOffsetScaleByDistance = value;
            }
          }
          const backgroundBillboard = this._backgroundBillboard;
          if (defined(backgroundBillboard)) {
            backgroundBillboard.pixelOffsetScaleByDistance = value;
          }
        }
      },
    },

    /**
     * Gets or sets near and far scaling properties of a Label based on the label's distance from the camera.
     * A label's scale will interpolate between the {@link NearFarScalar#nearValue} and
     * {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds
     * of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}.
     * Outside of these ranges the label's scale remains clamped to the nearest bound.  If undefined,
     * scaleByDistance will be disabled.
     * @memberof Label.prototype
     * @type {NearFarScalar}
     *
     * @example
     * // Example 1.
     * // Set a label's scaleByDistance to scale by 1.5 when the
     * // camera is 1500 meters from the label and disappear as
     * // the camera distance approaches 8.0e6 meters.
     * label.scaleByDistance = new Cesium.NearFarScalar(1.5e2, 1.5, 8.0e6, 0.0);
     *
     * @example
     * // Example 2.
     * // disable scaling by distance
     * label.scaleByDistance = undefined;
     */
    scaleByDistance: {
      get: function () {
        return this._scaleByDistance;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (defined(value) && value.far <= value.near) {
          throw new DeveloperError(
            "far distance must be greater than near distance."
          );
        }
        //>>includeEnd('debug');

        const scaleByDistance = this._scaleByDistance;
        if (!NearFarScalar.equals(scaleByDistance, value)) {
          this._scaleByDistance = NearFarScalar.clone(value, scaleByDistance);

          const glyphs = this._glyphs;
          for (let i = 0, len = glyphs.length; i < len; i++) {
            const glyph = glyphs[i];
            if (defined(glyph.billboard)) {
              glyph.billboard.scaleByDistance = value;
            }
          }
          const backgroundBillboard = this._backgroundBillboard;
          if (defined(backgroundBillboard)) {
            backgroundBillboard.scaleByDistance = value;
          }
        }
      },
    },

    /**
     * Gets and sets the 3D Cartesian offset applied to this label in eye coordinates.  Eye coordinates is a left-handed
     * coordinate system, where <code>x</code> points towards the viewer's right, <code>y</code> points up, and
     * <code>z</code> points into the screen.  Eye coordinates use the same scale as world and model coordinates,
     * which is typically meters.
     * <br /><br />
     * An eye offset is commonly used to arrange multiple label or objects at the same position, e.g., to
     * arrange a label above its corresponding 3D model.
     * <br /><br />
     * Below, the label is positioned at the center of the Earth but an eye offset makes it always
     * appear on top of the Earth regardless of the viewer's or Earth's orientation.
     * <br /><br />
     * <div align='center'>
     * <table border='0' cellpadding='5'><tr>
     * <td align='center'><img src='Images/Billboard.setEyeOffset.one.png' width='250' height='188' /></td>
     * <td align='center'><img src='Images/Billboard.setEyeOffset.two.png' width='250' height='188' /></td>
     * </tr></table>
     * <code>l.eyeOffset = new Cartesian3(0.0, 8000000.0, 0.0);</code><br /><br />
     * </div>
     * @memberof Label.prototype
     * @type {Cartesian3}
     * @default Cartesian3.ZERO
     */
    eyeOffset: {
      get: function () {
        return this._eyeOffset;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        const eyeOffset = this._eyeOffset;
        if (!Cartesian3.equals(eyeOffset, value)) {
          Cartesian3.clone(value, eyeOffset);

          const glyphs = this._glyphs;
          for (let i = 0, len = glyphs.length; i < len; i++) {
            const glyph = glyphs[i];
            if (defined(glyph.billboard)) {
              glyph.billboard.eyeOffset = value;
            }
          }
          const backgroundBillboard = this._backgroundBillboard;
          if (defined(backgroundBillboard)) {
            backgroundBillboard.eyeOffset = value;
          }
        }
      },
    },

    /**
     * Gets or sets the horizontal origin of this label, which determines if the label is drawn
     * to the left, center, or right of its anchor position.
     * <br /><br />
     * <div align='center'>
     * <img src='Images/Billboard.setHorizontalOrigin.png' width='648' height='196' /><br />
     * </div>
     * @memberof Label.prototype
     * @type {HorizontalOrigin}
     * @default HorizontalOrigin.LEFT
     * @example
     * // Use a top, right origin
     * l.horizontalOrigin = Cesium.HorizontalOrigin.RIGHT;
     * l.verticalOrigin = Cesium.VerticalOrigin.TOP;
     */
    horizontalOrigin: {
      get: function () {
        return this._horizontalOrigin;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        if (this._horizontalOrigin !== value) {
          this._horizontalOrigin = value;
          repositionAllGlyphs$1(this);
        }
      },
    },

    /**
     * Gets or sets the vertical origin of this label, which determines if the label is
     * to the above, below, or at the center of its anchor position.
     * <br /><br />
     * <div align='center'>
     * <img src='Images/Billboard.setVerticalOrigin.png' width='695' height='175' /><br />
     * </div>
     * @memberof Label.prototype
     * @type {VerticalOrigin}
     * @default VerticalOrigin.BASELINE
     * @example
     * // Use a top, right origin
     * l.horizontalOrigin = Cesium.HorizontalOrigin.RIGHT;
     * l.verticalOrigin = Cesium.VerticalOrigin.TOP;
     */
    verticalOrigin: {
      get: function () {
        return this._verticalOrigin;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        if (this._verticalOrigin !== value) {
          this._verticalOrigin = value;

          const glyphs = this._glyphs;
          for (let i = 0, len = glyphs.length; i < len; i++) {
            const glyph = glyphs[i];
            if (defined(glyph.billboard)) {
              glyph.billboard.verticalOrigin = value;
            }
          }
          const backgroundBillboard = this._backgroundBillboard;
          if (defined(backgroundBillboard)) {
            backgroundBillboard.verticalOrigin = value;
          }

          repositionAllGlyphs$1(this);
        }
      },
    },

    /**
     * Gets or sets the uniform scale that is multiplied with the label's size in pixels.
     * A scale of <code>1.0</code> does not change the size of the label; a scale greater than
     * <code>1.0</code> enlarges the label; a positive scale less than <code>1.0</code> shrinks
     * the label.
     * <br /><br />
     * Applying a large scale value may pixelate the label.  To make text larger without pixelation,
     * use a larger font size when calling {@link Label#font} instead.
     * <br /><br />
     * <div align='center'>
     * <img src='Images/Label.setScale.png' width='400' height='300' /><br/>
     * From left to right in the above image, the scales are <code>0.5</code>, <code>1.0</code>,
     * and <code>2.0</code>.
     * </div>
     * @memberof Label.prototype
     * @type {Number}
     * @default 1.0
     */
    scale: {
      get: function () {
        return this._scale;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        if (this._scale !== value) {
          this._scale = value;

          const glyphs = this._glyphs;
          for (let i = 0, len = glyphs.length; i < len; i++) {
            const glyph = glyphs[i];
            if (defined(glyph.billboard)) {
              glyph.billboard.scale = value * this._relativeSize;
            }
          }
          const backgroundBillboard = this._backgroundBillboard;
          if (defined(backgroundBillboard)) {
            backgroundBillboard.scale = value * this._relativeSize;
          }

          repositionAllGlyphs$1(this);
        }
      },
    },

    /**
     * Gets the total scale of the label, which is the label's scale multiplied by the computed relative size
     * of the desired font compared to the generated glyph size.
     * @memberof Label.prototype
     * @type {Number}
     * @default 1.0
     */
    totalScale: {
      get: function () {
        return this._scale * this._relativeSize;
      },
    },

    /**
     * Gets or sets the condition specifying at what distance from the camera that this label will be displayed.
     * @memberof Label.prototype
     * @type {DistanceDisplayCondition}
     * @default undefined
     */
    distanceDisplayCondition: {
      get: function () {
        return this._distanceDisplayCondition;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (defined(value) && value.far <= value.near) {
          throw new DeveloperError("far must be greater than near");
        }
        //>>includeEnd('debug');
        if (
          !DistanceDisplayCondition.equals(value, this._distanceDisplayCondition)
        ) {
          this._distanceDisplayCondition = DistanceDisplayCondition.clone(
            value,
            this._distanceDisplayCondition
          );

          const glyphs = this._glyphs;
          for (let i = 0, len = glyphs.length; i < len; i++) {
            const glyph = glyphs[i];
            if (defined(glyph.billboard)) {
              glyph.billboard.distanceDisplayCondition = value;
            }
          }
          const backgroundBillboard = this._backgroundBillboard;
          if (defined(backgroundBillboard)) {
            backgroundBillboard.distanceDisplayCondition = value;
          }
        }
      },
    },

    /**
     * Gets or sets the distance from the camera at which to disable the depth test to, for example, prevent clipping against terrain.
     * When set to zero, the depth test is always applied. When set to Number.POSITIVE_INFINITY, the depth test is never applied.
     * @memberof Label.prototype
     * @type {Number}
     */
    disableDepthTestDistance: {
      get: function () {
        return this._disableDepthTestDistance;
      },
      set: function (value) {
        if (this._disableDepthTestDistance !== value) {
          //>>includeStart('debug', pragmas.debug);
          if (defined(value) && value < 0.0) {
            throw new DeveloperError(
              "disableDepthTestDistance must be greater than 0.0."
            );
          }
          //>>includeEnd('debug');
          this._disableDepthTestDistance = value;

          const glyphs = this._glyphs;
          for (let i = 0, len = glyphs.length; i < len; i++) {
            const glyph = glyphs[i];
            if (defined(glyph.billboard)) {
              glyph.billboard.disableDepthTestDistance = value;
            }
          }
          const backgroundBillboard = this._backgroundBillboard;
          if (defined(backgroundBillboard)) {
            backgroundBillboard.disableDepthTestDistance = value;
          }
        }
      },
    },

    /**
     * Gets or sets the user-defined value returned when the label is picked.
     * @memberof Label.prototype
     * @type {*}
     */
    id: {
      get: function () {
        return this._id;
      },
      set: function (value) {
        if (this._id !== value) {
          this._id = value;

          const glyphs = this._glyphs;
          for (let i = 0, len = glyphs.length; i < len; i++) {
            const glyph = glyphs[i];
            if (defined(glyph.billboard)) {
              glyph.billboard.id = value;
            }
          }
          const backgroundBillboard = this._backgroundBillboard;
          if (defined(backgroundBillboard)) {
            backgroundBillboard.id = value;
          }
        }
      },
    },

    /**
     * @private
     */
    pickId: {
      get: function () {
        if (this._glyphs.length === 0 || !defined(this._glyphs[0].billboard)) {
          return undefined;
        }
        return this._glyphs[0].billboard.pickId;
      },
    },

    /**
     * Keeps track of the position of the label based on the height reference.
     * @memberof Label.prototype
     * @type {Cartesian3}
     * @private
     */
    _clampedPosition: {
      get: function () {
        return this._actualClampedPosition;
      },
      set: function (value) {
        this._actualClampedPosition = Cartesian3.clone(
          value,
          this._actualClampedPosition
        );

        const glyphs = this._glyphs;
        for (let i = 0, len = glyphs.length; i < len; i++) {
          const glyph = glyphs[i];
          if (defined(glyph.billboard)) {
            // Set all the private values here, because we already clamped to ground
            //  so we don't want to do it again for every glyph
            glyph.billboard._clampedPosition = value;
          }
        }
        const backgroundBillboard = this._backgroundBillboard;
        if (defined(backgroundBillboard)) {
          backgroundBillboard._clampedPosition = value;
        }
      },
    },

    /**
     * Determines whether or not this label will be shown or hidden because it was clustered.
     * @memberof Label.prototype
     * @type {Boolean}
     * @default true
     * @private
     */
    clusterShow: {
      get: function () {
        return this._clusterShow;
      },
      set: function (value) {
        if (this._clusterShow !== value) {
          this._clusterShow = value;

          const glyphs = this._glyphs;
          for (let i = 0, len = glyphs.length; i < len; i++) {
            const glyph = glyphs[i];
            if (defined(glyph.billboard)) {
              glyph.billboard.clusterShow = value;
            }
          }
          const backgroundBillboard = this._backgroundBillboard;
          if (defined(backgroundBillboard)) {
            backgroundBillboard.clusterShow = value;
          }
        }
      },
    },
  });

  Label.prototype._updateClamping = function () {
    Billboard._updateClamping(this._labelCollection, this);
  };

  /**
   * Computes the screen-space position of the label's origin, taking into account eye and pixel offsets.
   * The screen space origin is the top, left corner of the canvas; <code>x</code> increases from
   * left to right, and <code>y</code> increases from top to bottom.
   *
   * @param {Scene} scene The scene the label is in.
   * @param {Cartesian2} [result] The object onto which to store the result.
   * @returns {Cartesian2} The screen-space position of the label.
   *
   *
   * @example
   * console.log(l.computeScreenSpacePosition(scene).toString());
   *
   * @see Label#eyeOffset
   * @see Label#pixelOffset
   */
  Label.prototype.computeScreenSpacePosition = function (scene, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(scene)) {
      throw new DeveloperError("scene is required.");
    }
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Cartesian2();
    }

    const labelCollection = this._labelCollection;
    const modelMatrix = labelCollection.modelMatrix;
    const actualPosition = defined(this._actualClampedPosition)
      ? this._actualClampedPosition
      : this._position;

    const windowCoordinates = Billboard._computeScreenSpacePosition(
      modelMatrix,
      actualPosition,
      this._eyeOffset,
      this._pixelOffset,
      scene,
      result
    );
    return windowCoordinates;
  };

  /**
   * Gets a label's screen space bounding box centered around screenSpacePosition.
   * @param {Label} label The label to get the screen space bounding box for.
   * @param {Cartesian2} screenSpacePosition The screen space center of the label.
   * @param {BoundingRectangle} [result] The object onto which to store the result.
   * @returns {BoundingRectangle} The screen space bounding box.
   *
   * @private
   */
  Label.getScreenSpaceBoundingBox = function (
    label,
    screenSpacePosition,
    result
  ) {
    let x = 0;
    let y = 0;
    let width = 0;
    let height = 0;
    const scale = label.totalScale;

    const backgroundBillboard = label._backgroundBillboard;
    if (defined(backgroundBillboard)) {
      x = screenSpacePosition.x + backgroundBillboard._translate.x;
      y = screenSpacePosition.y - backgroundBillboard._translate.y;
      width = backgroundBillboard.width * scale;
      height = backgroundBillboard.height * scale;

      if (
        label.verticalOrigin === VerticalOrigin$1.BOTTOM ||
        label.verticalOrigin === VerticalOrigin$1.BASELINE
      ) {
        y -= height;
      } else if (label.verticalOrigin === VerticalOrigin$1.CENTER) {
        y -= height * 0.5;
      }
    } else {
      x = Number.POSITIVE_INFINITY;
      y = Number.POSITIVE_INFINITY;
      let maxX = 0;
      let maxY = 0;
      const glyphs = label._glyphs;
      const length = glyphs.length;
      for (let i = 0; i < length; ++i) {
        const glyph = glyphs[i];
        const billboard = glyph.billboard;
        if (!defined(billboard)) {
          continue;
        }

        const glyphX = screenSpacePosition.x + billboard._translate.x;
        let glyphY = screenSpacePosition.y - billboard._translate.y;
        const glyphWidth = glyph.dimensions.width * scale;
        const glyphHeight = glyph.dimensions.height * scale;

        if (
          label.verticalOrigin === VerticalOrigin$1.BOTTOM ||
          label.verticalOrigin === VerticalOrigin$1.BASELINE
        ) {
          glyphY -= glyphHeight;
        } else if (label.verticalOrigin === VerticalOrigin$1.CENTER) {
          glyphY -= glyphHeight * 0.5;
        }

        if (label._verticalOrigin === VerticalOrigin$1.TOP) {
          glyphY += SDFSettings$1.PADDING * scale;
        } else if (
          label._verticalOrigin === VerticalOrigin$1.BOTTOM ||
          label._verticalOrigin === VerticalOrigin$1.BASELINE
        ) {
          glyphY -= SDFSettings$1.PADDING * scale;
        }

        x = Math.min(x, glyphX);
        y = Math.min(y, glyphY);
        maxX = Math.max(maxX, glyphX + glyphWidth);
        maxY = Math.max(maxY, glyphY + glyphHeight);
      }

      width = maxX - x;
      height = maxY - y;
    }

    if (!defined(result)) {
      result = new BoundingRectangle();
    }

    result.x = x;
    result.y = y;
    result.width = width;
    result.height = height;

    return result;
  };

  /**
   * Determines if this label equals another label.  Labels are equal if all their properties
   * are equal.  Labels in different collections can be equal.
   *
   * @param {Label} other The label to compare for equality.
   * @returns {Boolean} <code>true</code> if the labels are equal; otherwise, <code>false</code>.
   */
  Label.prototype.equals = function (other) {
    return (
      this === other ||
      (defined(other) &&
        this._show === other._show &&
        this._scale === other._scale &&
        this._outlineWidth === other._outlineWidth &&
        this._showBackground === other._showBackground &&
        this._style === other._style &&
        this._verticalOrigin === other._verticalOrigin &&
        this._horizontalOrigin === other._horizontalOrigin &&
        this._heightReference === other._heightReference &&
        this._renderedText === other._renderedText &&
        this._font === other._font &&
        Cartesian3.equals(this._position, other._position) &&
        Color.equals(this._fillColor, other._fillColor) &&
        Color.equals(this._outlineColor, other._outlineColor) &&
        Color.equals(this._backgroundColor, other._backgroundColor) &&
        Cartesian2.equals(this._backgroundPadding, other._backgroundPadding) &&
        Cartesian2.equals(this._pixelOffset, other._pixelOffset) &&
        Cartesian3.equals(this._eyeOffset, other._eyeOffset) &&
        NearFarScalar.equals(
          this._translucencyByDistance,
          other._translucencyByDistance
        ) &&
        NearFarScalar.equals(
          this._pixelOffsetScaleByDistance,
          other._pixelOffsetScaleByDistance
        ) &&
        NearFarScalar.equals(this._scaleByDistance, other._scaleByDistance) &&
        DistanceDisplayCondition.equals(
          this._distanceDisplayCondition,
          other._distanceDisplayCondition
        ) &&
        this._disableDepthTestDistance === other._disableDepthTestDistance &&
        this._id === other._id)
    );
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} True if this object was destroyed; otherwise, false.
   */
  Label.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Determines whether or not run the algorithm, that match the text of the label to right-to-left languages
   * @memberof Label
   * @type {Boolean}
   * @default false
   *
   * @example
   * // Example 1.
   * // Set a label's rightToLeft before init
   * Cesium.Label.enableRightToLeftDetection = true;
   * const myLabelEntity = viewer.entities.add({
   *   label: {
   *     id: 'my label',
   *     text: 'זה טקסט בעברית \n ועכשיו יורדים שורה',
   *   }
   * });
   *
   * @example
   * // Example 2.
   * const myLabelEntity = viewer.entities.add({
   *   label: {
   *     id: 'my label',
   *     text: 'English text'
   *   }
   * });
   * // Set a label's rightToLeft after init
   * Cesium.Label.enableRightToLeftDetection = true;
   * myLabelEntity.text = 'טקסט חדש';
   */
  Label.enableRightToLeftDetection = false;

  function convertTextToTypes(text, rtlChars) {
    const ltrChars = /[a-zA-Z0-9]/;
    const bracketsChars = /[()[\]{}<>]/;
    const parsedText = [];
    let word = "";
    let lastType = textTypes.LTR;
    let currentType = "";
    const textLength = text.length;
    for (let textIndex = 0; textIndex < textLength; ++textIndex) {
      const character = text.charAt(textIndex);
      if (rtlChars.test(character)) {
        currentType = textTypes.RTL;
      } else if (ltrChars.test(character)) {
        currentType = textTypes.LTR;
      } else if (bracketsChars.test(character)) {
        currentType = textTypes.BRACKETS;
      } else {
        currentType = textTypes.WEAK;
      }

      if (textIndex === 0) {
        lastType = currentType;
      }

      if (lastType === currentType && currentType !== textTypes.BRACKETS) {
        word += character;
      } else {
        if (word !== "") {
          parsedText.push({ Type: lastType, Word: word });
        }
        lastType = currentType;
        word = character;
      }
    }
    parsedText.push({ Type: currentType, Word: word });
    return parsedText;
  }

  function reverseWord(word) {
    return word.split("").reverse().join("");
  }

  function spliceWord(result, pointer, word) {
    return result.slice(0, pointer) + word + result.slice(pointer);
  }

  function reverseBrackets(bracket) {
    switch (bracket) {
      case "(":
        return ")";
      case ")":
        return "(";
      case "[":
        return "]";
      case "]":
        return "[";
      case "{":
        return "}";
      case "}":
        return "{";
      case "<":
        return ">";
      case ">":
        return "<";
    }
  }

  //To add another language, simply add its Unicode block range(s) to the below regex.
  const hebrew = "\u05D0-\u05EA";
  const arabic = "\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF";
  const rtlChars = new RegExp(`[${hebrew}${arabic}]`);

  /**
   *
   * @param {String} value the text to parse and reorder
   * @returns {String} the text as rightToLeft direction
   * @private
   */
  function reverseRtl(value) {
    const texts = value.split("\n");
    let result = "";
    for (let i = 0; i < texts.length; i++) {
      const text = texts[i];
      // first character of the line is a RTL character, so need to manage different cases
      const rtlDir = rtlChars.test(text.charAt(0));
      const parsedText = convertTextToTypes(text, rtlChars);

      let splicePointer = 0;
      let line = "";
      for (let wordIndex = 0; wordIndex < parsedText.length; ++wordIndex) {
        const subText = parsedText[wordIndex];
        const reverse =
          subText.Type === textTypes.BRACKETS
            ? reverseBrackets(subText.Word)
            : reverseWord(subText.Word);
        if (rtlDir) {
          if (subText.Type === textTypes.RTL) {
            line = reverse + line;
            splicePointer = 0;
          } else if (subText.Type === textTypes.LTR) {
            line = spliceWord(line, splicePointer, subText.Word);
            splicePointer += subText.Word.length;
          } else if (
            subText.Type === textTypes.WEAK ||
            subText.Type === textTypes.BRACKETS
          ) {
            // current word is weak, last one was bracket
            if (
              subText.Type === textTypes.WEAK &&
              parsedText[wordIndex - 1].Type === textTypes.BRACKETS
            ) {
              line = reverse + line;
            }
            // current word is weak or bracket, last one was rtl
            else if (parsedText[wordIndex - 1].Type === textTypes.RTL) {
              line = reverse + line;
              splicePointer = 0;
            }
            // current word is weak or bracket, there is at least one more word
            else if (parsedText.length > wordIndex + 1) {
              // next word is rtl
              if (parsedText[wordIndex + 1].Type === textTypes.RTL) {
                line = reverse + line;
                splicePointer = 0;
              } else {
                line = spliceWord(line, splicePointer, subText.Word);
                splicePointer += subText.Word.length;
              }
            }
            // current word is weak or bracket, and it the last in this line
            else {
              line = spliceWord(line, 0, reverse);
            }
          }
        }
        // ltr line, rtl word
        else if (subText.Type === textTypes.RTL) {
          line = spliceWord(line, splicePointer, reverse);
        }
        // ltr line, ltr word
        else if (subText.Type === textTypes.LTR) {
          line += subText.Word;
          splicePointer = line.length;
        }
        // ltr line, weak or bracket word
        else if (
          subText.Type === textTypes.WEAK ||
          subText.Type === textTypes.BRACKETS
        ) {
          // not first word in line
          if (wordIndex > 0) {
            // last word was rtl
            if (parsedText[wordIndex - 1].Type === textTypes.RTL) {
              // there is at least one more word
              if (parsedText.length > wordIndex + 1) {
                // next word is rtl
                if (parsedText[wordIndex + 1].Type === textTypes.RTL) {
                  line = spliceWord(line, splicePointer, reverse);
                } else {
                  line += subText.Word;
                  splicePointer = line.length;
                }
              } else {
                line += subText.Word;
              }
            } else {
              line += subText.Word;
              splicePointer = line.length;
            }
          } else {
            line += subText.Word;
            splicePointer = line.length;
          }
        }
      }

      result += line;
      if (i < texts.length - 1) {
        result += "\n";
      }
    }
    return result;
  }

  /* This file is automatically rebuilt by the Cesium build process. */

  var graphemeSplitter = createCommonjsModule(function (module) {
  /*
  Breaks a Javascript string into individual user-perceived "characters" 
  called extended grapheme clusters by implementing the Unicode UAX-29 standard, version 10.0.0

  Usage:
  var splitter = new GraphemeSplitter();
  //returns an array of strings, one string for each grapheme cluster
  var graphemes = splitter.splitGraphemes(string); 

  */
  function GraphemeSplitter(){
  	var CR = 0,
  		LF = 1,
  		Control = 2,
  		Extend = 3,
  		Regional_Indicator = 4,
  		SpacingMark = 5,
  		L = 6,
  		V = 7,
  		T = 8,
  		LV = 9,
  		LVT = 10,
  		Other = 11,
  		Prepend = 12,
  		E_Base = 13,
  		E_Modifier = 14,
  		ZWJ = 15,
  		Glue_After_Zwj = 16,
  		E_Base_GAZ = 17;
  		
  	// BreakTypes
  	var NotBreak = 0,
  		BreakStart = 1,
  		Break = 2,
  		BreakLastRegional = 3,
  		BreakPenultimateRegional = 4;
  		
  	function isSurrogate(str, pos) {
  		return  0xd800 <= str.charCodeAt(pos) && str.charCodeAt(pos) <= 0xdbff && 
  				0xdc00 <= str.charCodeAt(pos + 1) && str.charCodeAt(pos + 1) <= 0xdfff;
  	}
  		
  	// Private function, gets a Unicode code point from a JavaScript UTF-16 string
  	// handling surrogate pairs appropriately
  	function codePointAt(str, idx){
  		if(idx === undefined){
  			idx = 0;
  		}
  		var code = str.charCodeAt(idx);

  		// if a high surrogate
  		if (0xD800 <= code && code <= 0xDBFF && 
  			idx < str.length - 1){
  			var hi = code;
  			var low = str.charCodeAt(idx + 1);
  			if (0xDC00 <= low && low <= 0xDFFF){
  				return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;
  			}
  			return hi;
  		}
  		
  		// if a low surrogate
  		if (0xDC00 <= code && code <= 0xDFFF &&
  			idx >= 1){
  			var hi = str.charCodeAt(idx - 1);
  			var low = code;
  			if (0xD800 <= hi && hi <= 0xDBFF){
  				return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;
  			}
  			return low;
  		}
  		
  		//just return the char if an unmatched surrogate half or a 
  		//single-char codepoint
  		return code;
  	}
  	
  	// Private function, returns whether a break is allowed between the 
  	// two given grapheme breaking classes
  	function shouldBreak(start, mid, end){
  		var all = [start].concat(mid).concat([end]);
  		var previous = all[all.length - 2];
  		var next = end;
  		
  		// Lookahead termintor for:
  		// GB10. (E_Base | EBG) Extend* ?	E_Modifier
  		var eModifierIndex = all.lastIndexOf(E_Modifier);
  		if(eModifierIndex > 1 &&
  			all.slice(1, eModifierIndex).every(function(c){return c == Extend}) &&
  			[Extend, E_Base, E_Base_GAZ].indexOf(start) == -1){
  			return Break
  		}

  		// Lookahead termintor for:
  		// GB12. ^ (RI RI)* RI	?	RI
  		// GB13. [^RI] (RI RI)* RI	?	RI
  		var rIIndex = all.lastIndexOf(Regional_Indicator);
  		if(rIIndex > 0 &&
  			all.slice(1, rIIndex).every(function(c){return c == Regional_Indicator}) &&
  			[Prepend, Regional_Indicator].indexOf(previous) == -1) { 
  			if(all.filter(function(c){return c == Regional_Indicator}).length % 2 == 1) {
  				return BreakLastRegional
  			}
  			else {
  				return BreakPenultimateRegional
  			}
  		}
  		
  		// GB3. CR X LF
  		if(previous == CR && next == LF){
  			return NotBreak;
  		}
  		// GB4. (Control|CR|LF) ÷
  		else if(previous == Control || previous == CR || previous == LF){
  			if(next == E_Modifier && mid.every(function(c){return c == Extend})){
  				return Break
  			}
  			else {
  				return BreakStart
  			}
  		}
  		// GB5. ÷ (Control|CR|LF)
  		else if(next == Control || next == CR || next == LF){
  			return BreakStart;
  		}
  		// GB6. L X (L|V|LV|LVT)
  		else if(previous == L && 
  			(next == L || next == V || next == LV || next == LVT)){
  			return NotBreak;
  		}
  		// GB7. (LV|V) X (V|T)
  		else if((previous == LV || previous == V) && 
  			(next == V || next == T)){
  			return NotBreak;
  		}
  		// GB8. (LVT|T) X (T)
  		else if((previous == LVT || previous == T) && 
  			next == T){
  			return NotBreak;
  		}
  		// GB9. X (Extend|ZWJ)
  		else if (next == Extend || next == ZWJ){
  			return NotBreak;
  		}
  		// GB9a. X SpacingMark
  		else if(next == SpacingMark){
  			return NotBreak;
  		}
  		// GB9b. Prepend X
  		else if (previous == Prepend){
  			return NotBreak;
  		}
  		
  		// GB10. (E_Base | EBG) Extend* ?	E_Modifier
  		var previousNonExtendIndex = all.indexOf(Extend) != -1 ? all.lastIndexOf(Extend) - 1 : all.length - 2;
  		if([E_Base, E_Base_GAZ].indexOf(all[previousNonExtendIndex]) != -1 &&
  			all.slice(previousNonExtendIndex + 1, -1).every(function(c){return c == Extend}) &&
  			next == E_Modifier){
  			return NotBreak;
  		}
  		
  		// GB11. ZWJ ? (Glue_After_Zwj | EBG)
  		if(previous == ZWJ && [Glue_After_Zwj, E_Base_GAZ].indexOf(next) != -1) {
  			return NotBreak;
  		}

  		// GB12. ^ (RI RI)* RI ? RI
  		// GB13. [^RI] (RI RI)* RI ? RI
  		if(mid.indexOf(Regional_Indicator) != -1) { 
  			return Break;
  		}
  		if(previous == Regional_Indicator && next == Regional_Indicator) {
  			return NotBreak;
  		}

  		// GB999. Any ? Any
  		return BreakStart;
  	}
  	
  	// Returns the next grapheme break in the string after the given index
  	this.nextBreak = function(string, index){
  		if(index === undefined){
  			index = 0;
  		}
  		if(index < 0){
  			return 0;
  		}
  		if(index >= string.length - 1){
  			return string.length;
  		}
  		var prev = getGraphemeBreakProperty(codePointAt(string, index));
  		var mid = [];
  		for (var i = index + 1; i < string.length; i++) {
  			// check for already processed low surrogates
  			if(isSurrogate(string, i - 1)){
  				continue;
  			}
  		
  			var next = getGraphemeBreakProperty(codePointAt(string, i));
  			if(shouldBreak(prev, mid, next)){
  				return i;
  			}
  			
  			mid.push(next);
  		}
  		return string.length;
  	};
  	
  	// Breaks the given string into an array of grapheme cluster strings
  	this.splitGraphemes = function(str){
  		var res = [];
  		var index = 0;
  		var brk;
  		while((brk = this.nextBreak(str, index)) < str.length){
  			res.push(str.slice(index, brk));
  			index = brk;
  		}
  		if(index < str.length){
  			res.push(str.slice(index));
  		}
  		return res;
  	};

  	// Returns the iterator of grapheme clusters there are in the given string
  	this.iterateGraphemes = function(str) {
  		var index = 0;
  		var res = {
  			next: (function() {
  				var value;
  				var brk;
  				if ((brk = this.nextBreak(str, index)) < str.length) {
  					value = str.slice(index, brk);
  					index = brk;
  					return { value: value, done: false };
  				}
  				if (index < str.length) {
  					value = str.slice(index);
  					index = str.length;
  					return { value: value, done: false };
  				}
  				return { value: undefined, done: true };
  			}).bind(this)
  		};
  		// ES2015 @@iterator method (iterable) for spread syntax and for...of statement
  		if (typeof Symbol !== 'undefined' && Symbol.iterator) {
  			res[Symbol.iterator] = function() {return res};
  		}
  		return res;
  	};

  	// Returns the number of grapheme clusters there are in the given string
  	this.countGraphemes = function(str){
  		var count = 0;
  		var index = 0;
  		var brk;
  		while((brk = this.nextBreak(str, index)) < str.length){
  			index = brk;
  			count++;
  		}
  		if(index < str.length){
  			count++;
  		}
  		return count;
  	};
  	
  	//given a Unicode code point, determines this symbol's grapheme break property
  	function getGraphemeBreakProperty(code){
  		
  		//grapheme break property for Unicode 10.0.0, 
  		//taken from http://www.unicode.org/Public/10.0.0/ucd/auxiliary/GraphemeBreakProperty.txt
  		//and adapted to JavaScript rules
  		
  		if(		
  		(0x0600 <= code && code <= 0x0605) || // Cf   [6] ARABIC NUMBER SIGN..ARABIC NUMBER MARK ABOVE
  		0x06DD == code || // Cf       ARABIC END OF AYAH
  		0x070F == code || // Cf       SYRIAC ABBREVIATION MARK
  		0x08E2 == code || // Cf       ARABIC DISPUTED END OF AYAH
  		0x0D4E == code || // Lo       MALAYALAM LETTER DOT REPH
  		0x110BD == code || // Cf       KAITHI NUMBER SIGN
  		(0x111C2 <= code && code <= 0x111C3) || // Lo   [2] SHARADA SIGN JIHVAMULIYA..SHARADA SIGN UPADHMANIYA
  		0x11A3A == code || // Lo       ZANABAZAR SQUARE CLUSTER-INITIAL LETTER RA
  		(0x11A86 <= code && code <= 0x11A89) || // Lo   [4] SOYOMBO CLUSTER-INITIAL LETTER RA..SOYOMBO CLUSTER-INITIAL LETTER SA
  		0x11D46 == code // Lo       MASARAM GONDI REPHA
  		){
  			return Prepend;
  		}
  		if(
  		0x000D == code // Cc       <control-000D>
  		){
  			return CR;
  		}
  		
  		if(
  		0x000A == code // Cc       <control-000A>
  		){
  			return LF;
  		}
  		
  		
  		if(
  		(0x0000 <= code && code <= 0x0009) || // Cc  [10] <control-0000>..<control-0009>
  		(0x000B <= code && code <= 0x000C) || // Cc   [2] <control-000B>..<control-000C>
  		(0x000E <= code && code <= 0x001F) || // Cc  [18] <control-000E>..<control-001F>
  		(0x007F <= code && code <= 0x009F) || // Cc  [33] <control-007F>..<control-009F>
  		0x00AD == code || // Cf       SOFT HYPHEN
  		0x061C == code || // Cf       ARABIC LETTER MARK
  	
  		0x180E == code || // Cf       MONGOLIAN VOWEL SEPARATOR
  		0x200B == code || // Cf       ZERO WIDTH SPACE
  		(0x200E <= code && code <= 0x200F) || // Cf   [2] LEFT-TO-RIGHT MARK..RIGHT-TO-LEFT MARK
  		0x2028 == code || // Zl       LINE SEPARATOR
  		0x2029 == code || // Zp       PARAGRAPH SEPARATOR
  		(0x202A <= code && code <= 0x202E) || // Cf   [5] LEFT-TO-RIGHT EMBEDDING..RIGHT-TO-LEFT OVERRIDE
  		(0x2060 <= code && code <= 0x2064) || // Cf   [5] WORD JOINER..INVISIBLE PLUS
  		0x2065 == code || // Cn       <reserved-2065>
  		(0x2066 <= code && code <= 0x206F) || // Cf  [10] LEFT-TO-RIGHT ISOLATE..NOMINAL DIGIT SHAPES
  		(0xD800 <= code && code <= 0xDFFF) || // Cs [2048] <surrogate-D800>..<surrogate-DFFF>
  		0xFEFF == code || // Cf       ZERO WIDTH NO-BREAK SPACE
  		(0xFFF0 <= code && code <= 0xFFF8) || // Cn   [9] <reserved-FFF0>..<reserved-FFF8>
  		(0xFFF9 <= code && code <= 0xFFFB) || // Cf   [3] INTERLINEAR ANNOTATION ANCHOR..INTERLINEAR ANNOTATION TERMINATOR
  		(0x1BCA0 <= code && code <= 0x1BCA3) || // Cf   [4] SHORTHAND FORMAT LETTER OVERLAP..SHORTHAND FORMAT UP STEP
  		(0x1D173 <= code && code <= 0x1D17A) || // Cf   [8] MUSICAL SYMBOL BEGIN BEAM..MUSICAL SYMBOL END PHRASE
  		0xE0000 == code || // Cn       <reserved-E0000>
  		0xE0001 == code || // Cf       LANGUAGE TAG
  		(0xE0002 <= code && code <= 0xE001F) || // Cn  [30] <reserved-E0002>..<reserved-E001F>
  		(0xE0080 <= code && code <= 0xE00FF) || // Cn [128] <reserved-E0080>..<reserved-E00FF>
  		(0xE01F0 <= code && code <= 0xE0FFF) // Cn [3600] <reserved-E01F0>..<reserved-E0FFF>
  		){
  			return Control;
  		}
  		
  		
  		if(
  		(0x0300 <= code && code <= 0x036F) || // Mn [112] COMBINING GRAVE ACCENT..COMBINING LATIN SMALL LETTER X
  		(0x0483 <= code && code <= 0x0487) || // Mn   [5] COMBINING CYRILLIC TITLO..COMBINING CYRILLIC POKRYTIE
  		(0x0488 <= code && code <= 0x0489) || // Me   [2] COMBINING CYRILLIC HUNDRED THOUSANDS SIGN..COMBINING CYRILLIC MILLIONS SIGN
  		(0x0591 <= code && code <= 0x05BD) || // Mn  [45] HEBREW ACCENT ETNAHTA..HEBREW POINT METEG
  		0x05BF == code || // Mn       HEBREW POINT RAFE
  		(0x05C1 <= code && code <= 0x05C2) || // Mn   [2] HEBREW POINT SHIN DOT..HEBREW POINT SIN DOT
  		(0x05C4 <= code && code <= 0x05C5) || // Mn   [2] HEBREW MARK UPPER DOT..HEBREW MARK LOWER DOT
  		0x05C7 == code || // Mn       HEBREW POINT QAMATS QATAN
  		(0x0610 <= code && code <= 0x061A) || // Mn  [11] ARABIC SIGN SALLALLAHOU ALAYHE WASSALLAM..ARABIC SMALL KASRA
  		(0x064B <= code && code <= 0x065F) || // Mn  [21] ARABIC FATHATAN..ARABIC WAVY HAMZA BELOW
  		0x0670 == code || // Mn       ARABIC LETTER SUPERSCRIPT ALEF
  		(0x06D6 <= code && code <= 0x06DC) || // Mn   [7] ARABIC SMALL HIGH LIGATURE SAD WITH LAM WITH ALEF MAKSURA..ARABIC SMALL HIGH SEEN
  		(0x06DF <= code && code <= 0x06E4) || // Mn   [6] ARABIC SMALL HIGH ROUNDED ZERO..ARABIC SMALL HIGH MADDA
  		(0x06E7 <= code && code <= 0x06E8) || // Mn   [2] ARABIC SMALL HIGH YEH..ARABIC SMALL HIGH NOON
  		(0x06EA <= code && code <= 0x06ED) || // Mn   [4] ARABIC EMPTY CENTRE LOW STOP..ARABIC SMALL LOW MEEM
  		0x0711 == code || // Mn       SYRIAC LETTER SUPERSCRIPT ALAPH
  		(0x0730 <= code && code <= 0x074A) || // Mn  [27] SYRIAC PTHAHA ABOVE..SYRIAC BARREKH
  		(0x07A6 <= code && code <= 0x07B0) || // Mn  [11] THAANA ABAFILI..THAANA SUKUN
  		(0x07EB <= code && code <= 0x07F3) || // Mn   [9] NKO COMBINING SHORT HIGH TONE..NKO COMBINING DOUBLE DOT ABOVE
  		(0x0816 <= code && code <= 0x0819) || // Mn   [4] SAMARITAN MARK IN..SAMARITAN MARK DAGESH
  		(0x081B <= code && code <= 0x0823) || // Mn   [9] SAMARITAN MARK EPENTHETIC YUT..SAMARITAN VOWEL SIGN A
  		(0x0825 <= code && code <= 0x0827) || // Mn   [3] SAMARITAN VOWEL SIGN SHORT A..SAMARITAN VOWEL SIGN U
  		(0x0829 <= code && code <= 0x082D) || // Mn   [5] SAMARITAN VOWEL SIGN LONG I..SAMARITAN MARK NEQUDAA
  		(0x0859 <= code && code <= 0x085B) || // Mn   [3] MANDAIC AFFRICATION MARK..MANDAIC GEMINATION MARK
  		(0x08D4 <= code && code <= 0x08E1) || // Mn  [14] ARABIC SMALL HIGH WORD AR-RUB..ARABIC SMALL HIGH SIGN SAFHA
  		(0x08E3 <= code && code <= 0x0902) || // Mn  [32] ARABIC TURNED DAMMA BELOW..DEVANAGARI SIGN ANUSVARA
  		0x093A == code || // Mn       DEVANAGARI VOWEL SIGN OE
  		0x093C == code || // Mn       DEVANAGARI SIGN NUKTA
  		(0x0941 <= code && code <= 0x0948) || // Mn   [8] DEVANAGARI VOWEL SIGN U..DEVANAGARI VOWEL SIGN AI
  		0x094D == code || // Mn       DEVANAGARI SIGN VIRAMA
  		(0x0951 <= code && code <= 0x0957) || // Mn   [7] DEVANAGARI STRESS SIGN UDATTA..DEVANAGARI VOWEL SIGN UUE
  		(0x0962 <= code && code <= 0x0963) || // Mn   [2] DEVANAGARI VOWEL SIGN VOCALIC L..DEVANAGARI VOWEL SIGN VOCALIC LL
  		0x0981 == code || // Mn       BENGALI SIGN CANDRABINDU
  		0x09BC == code || // Mn       BENGALI SIGN NUKTA
  		0x09BE == code || // Mc       BENGALI VOWEL SIGN AA
  		(0x09C1 <= code && code <= 0x09C4) || // Mn   [4] BENGALI VOWEL SIGN U..BENGALI VOWEL SIGN VOCALIC RR
  		0x09CD == code || // Mn       BENGALI SIGN VIRAMA
  		0x09D7 == code || // Mc       BENGALI AU LENGTH MARK
  		(0x09E2 <= code && code <= 0x09E3) || // Mn   [2] BENGALI VOWEL SIGN VOCALIC L..BENGALI VOWEL SIGN VOCALIC LL
  		(0x0A01 <= code && code <= 0x0A02) || // Mn   [2] GURMUKHI SIGN ADAK BINDI..GURMUKHI SIGN BINDI
  		0x0A3C == code || // Mn       GURMUKHI SIGN NUKTA
  		(0x0A41 <= code && code <= 0x0A42) || // Mn   [2] GURMUKHI VOWEL SIGN U..GURMUKHI VOWEL SIGN UU
  		(0x0A47 <= code && code <= 0x0A48) || // Mn   [2] GURMUKHI VOWEL SIGN EE..GURMUKHI VOWEL SIGN AI
  		(0x0A4B <= code && code <= 0x0A4D) || // Mn   [3] GURMUKHI VOWEL SIGN OO..GURMUKHI SIGN VIRAMA
  		0x0A51 == code || // Mn       GURMUKHI SIGN UDAAT
  		(0x0A70 <= code && code <= 0x0A71) || // Mn   [2] GURMUKHI TIPPI..GURMUKHI ADDAK
  		0x0A75 == code || // Mn       GURMUKHI SIGN YAKASH
  		(0x0A81 <= code && code <= 0x0A82) || // Mn   [2] GUJARATI SIGN CANDRABINDU..GUJARATI SIGN ANUSVARA
  		0x0ABC == code || // Mn       GUJARATI SIGN NUKTA
  		(0x0AC1 <= code && code <= 0x0AC5) || // Mn   [5] GUJARATI VOWEL SIGN U..GUJARATI VOWEL SIGN CANDRA E
  		(0x0AC7 <= code && code <= 0x0AC8) || // Mn   [2] GUJARATI VOWEL SIGN E..GUJARATI VOWEL SIGN AI
  		0x0ACD == code || // Mn       GUJARATI SIGN VIRAMA
  		(0x0AE2 <= code && code <= 0x0AE3) || // Mn   [2] GUJARATI VOWEL SIGN VOCALIC L..GUJARATI VOWEL SIGN VOCALIC LL
  		(0x0AFA <= code && code <= 0x0AFF) || // Mn   [6] GUJARATI SIGN SUKUN..GUJARATI SIGN TWO-CIRCLE NUKTA ABOVE
  		0x0B01 == code || // Mn       ORIYA SIGN CANDRABINDU
  		0x0B3C == code || // Mn       ORIYA SIGN NUKTA
  		0x0B3E == code || // Mc       ORIYA VOWEL SIGN AA
  		0x0B3F == code || // Mn       ORIYA VOWEL SIGN I
  		(0x0B41 <= code && code <= 0x0B44) || // Mn   [4] ORIYA VOWEL SIGN U..ORIYA VOWEL SIGN VOCALIC RR
  		0x0B4D == code || // Mn       ORIYA SIGN VIRAMA
  		0x0B56 == code || // Mn       ORIYA AI LENGTH MARK
  		0x0B57 == code || // Mc       ORIYA AU LENGTH MARK
  		(0x0B62 <= code && code <= 0x0B63) || // Mn   [2] ORIYA VOWEL SIGN VOCALIC L..ORIYA VOWEL SIGN VOCALIC LL
  		0x0B82 == code || // Mn       TAMIL SIGN ANUSVARA
  		0x0BBE == code || // Mc       TAMIL VOWEL SIGN AA
  		0x0BC0 == code || // Mn       TAMIL VOWEL SIGN II
  		0x0BCD == code || // Mn       TAMIL SIGN VIRAMA
  		0x0BD7 == code || // Mc       TAMIL AU LENGTH MARK
  		0x0C00 == code || // Mn       TELUGU SIGN COMBINING CANDRABINDU ABOVE
  		(0x0C3E <= code && code <= 0x0C40) || // Mn   [3] TELUGU VOWEL SIGN AA..TELUGU VOWEL SIGN II
  		(0x0C46 <= code && code <= 0x0C48) || // Mn   [3] TELUGU VOWEL SIGN E..TELUGU VOWEL SIGN AI
  		(0x0C4A <= code && code <= 0x0C4D) || // Mn   [4] TELUGU VOWEL SIGN O..TELUGU SIGN VIRAMA
  		(0x0C55 <= code && code <= 0x0C56) || // Mn   [2] TELUGU LENGTH MARK..TELUGU AI LENGTH MARK
  		(0x0C62 <= code && code <= 0x0C63) || // Mn   [2] TELUGU VOWEL SIGN VOCALIC L..TELUGU VOWEL SIGN VOCALIC LL
  		0x0C81 == code || // Mn       KANNADA SIGN CANDRABINDU
  		0x0CBC == code || // Mn       KANNADA SIGN NUKTA
  		0x0CBF == code || // Mn       KANNADA VOWEL SIGN I
  		0x0CC2 == code || // Mc       KANNADA VOWEL SIGN UU
  		0x0CC6 == code || // Mn       KANNADA VOWEL SIGN E
  		(0x0CCC <= code && code <= 0x0CCD) || // Mn   [2] KANNADA VOWEL SIGN AU..KANNADA SIGN VIRAMA
  		(0x0CD5 <= code && code <= 0x0CD6) || // Mc   [2] KANNADA LENGTH MARK..KANNADA AI LENGTH MARK
  		(0x0CE2 <= code && code <= 0x0CE3) || // Mn   [2] KANNADA VOWEL SIGN VOCALIC L..KANNADA VOWEL SIGN VOCALIC LL
  		(0x0D00 <= code && code <= 0x0D01) || // Mn   [2] MALAYALAM SIGN COMBINING ANUSVARA ABOVE..MALAYALAM SIGN CANDRABINDU
  		(0x0D3B <= code && code <= 0x0D3C) || // Mn   [2] MALAYALAM SIGN VERTICAL BAR VIRAMA..MALAYALAM SIGN CIRCULAR VIRAMA
  		0x0D3E == code || // Mc       MALAYALAM VOWEL SIGN AA
  		(0x0D41 <= code && code <= 0x0D44) || // Mn   [4] MALAYALAM VOWEL SIGN U..MALAYALAM VOWEL SIGN VOCALIC RR
  		0x0D4D == code || // Mn       MALAYALAM SIGN VIRAMA
  		0x0D57 == code || // Mc       MALAYALAM AU LENGTH MARK
  		(0x0D62 <= code && code <= 0x0D63) || // Mn   [2] MALAYALAM VOWEL SIGN VOCALIC L..MALAYALAM VOWEL SIGN VOCALIC LL
  		0x0DCA == code || // Mn       SINHALA SIGN AL-LAKUNA
  		0x0DCF == code || // Mc       SINHALA VOWEL SIGN AELA-PILLA
  		(0x0DD2 <= code && code <= 0x0DD4) || // Mn   [3] SINHALA VOWEL SIGN KETTI IS-PILLA..SINHALA VOWEL SIGN KETTI PAA-PILLA
  		0x0DD6 == code || // Mn       SINHALA VOWEL SIGN DIGA PAA-PILLA
  		0x0DDF == code || // Mc       SINHALA VOWEL SIGN GAYANUKITTA
  		0x0E31 == code || // Mn       THAI CHARACTER MAI HAN-AKAT
  		(0x0E34 <= code && code <= 0x0E3A) || // Mn   [7] THAI CHARACTER SARA I..THAI CHARACTER PHINTHU
  		(0x0E47 <= code && code <= 0x0E4E) || // Mn   [8] THAI CHARACTER MAITAIKHU..THAI CHARACTER YAMAKKAN
  		0x0EB1 == code || // Mn       LAO VOWEL SIGN MAI KAN
  		(0x0EB4 <= code && code <= 0x0EB9) || // Mn   [6] LAO VOWEL SIGN I..LAO VOWEL SIGN UU
  		(0x0EBB <= code && code <= 0x0EBC) || // Mn   [2] LAO VOWEL SIGN MAI KON..LAO SEMIVOWEL SIGN LO
  		(0x0EC8 <= code && code <= 0x0ECD) || // Mn   [6] LAO TONE MAI EK..LAO NIGGAHITA
  		(0x0F18 <= code && code <= 0x0F19) || // Mn   [2] TIBETAN ASTROLOGICAL SIGN -KHYUD PA..TIBETAN ASTROLOGICAL SIGN SDONG TSHUGS
  		0x0F35 == code || // Mn       TIBETAN MARK NGAS BZUNG NYI ZLA
  		0x0F37 == code || // Mn       TIBETAN MARK NGAS BZUNG SGOR RTAGS
  		0x0F39 == code || // Mn       TIBETAN MARK TSA -PHRU
  		(0x0F71 <= code && code <= 0x0F7E) || // Mn  [14] TIBETAN VOWEL SIGN AA..TIBETAN SIGN RJES SU NGA RO
  		(0x0F80 <= code && code <= 0x0F84) || // Mn   [5] TIBETAN VOWEL SIGN REVERSED I..TIBETAN MARK HALANTA
  		(0x0F86 <= code && code <= 0x0F87) || // Mn   [2] TIBETAN SIGN LCI RTAGS..TIBETAN SIGN YANG RTAGS
  		(0x0F8D <= code && code <= 0x0F97) || // Mn  [11] TIBETAN SUBJOINED SIGN LCE TSA CAN..TIBETAN SUBJOINED LETTER JA
  		(0x0F99 <= code && code <= 0x0FBC) || // Mn  [36] TIBETAN SUBJOINED LETTER NYA..TIBETAN SUBJOINED LETTER FIXED-FORM RA
  		0x0FC6 == code || // Mn       TIBETAN SYMBOL PADMA GDAN
  		(0x102D <= code && code <= 0x1030) || // Mn   [4] MYANMAR VOWEL SIGN I..MYANMAR VOWEL SIGN UU
  		(0x1032 <= code && code <= 0x1037) || // Mn   [6] MYANMAR VOWEL SIGN AI..MYANMAR SIGN DOT BELOW
  		(0x1039 <= code && code <= 0x103A) || // Mn   [2] MYANMAR SIGN VIRAMA..MYANMAR SIGN ASAT
  		(0x103D <= code && code <= 0x103E) || // Mn   [2] MYANMAR CONSONANT SIGN MEDIAL WA..MYANMAR CONSONANT SIGN MEDIAL HA
  		(0x1058 <= code && code <= 0x1059) || // Mn   [2] MYANMAR VOWEL SIGN VOCALIC L..MYANMAR VOWEL SIGN VOCALIC LL
  		(0x105E <= code && code <= 0x1060) || // Mn   [3] MYANMAR CONSONANT SIGN MON MEDIAL NA..MYANMAR CONSONANT SIGN MON MEDIAL LA
  		(0x1071 <= code && code <= 0x1074) || // Mn   [4] MYANMAR VOWEL SIGN GEBA KAREN I..MYANMAR VOWEL SIGN KAYAH EE
  		0x1082 == code || // Mn       MYANMAR CONSONANT SIGN SHAN MEDIAL WA
  		(0x1085 <= code && code <= 0x1086) || // Mn   [2] MYANMAR VOWEL SIGN SHAN E ABOVE..MYANMAR VOWEL SIGN SHAN FINAL Y
  		0x108D == code || // Mn       MYANMAR SIGN SHAN COUNCIL EMPHATIC TONE
  		0x109D == code || // Mn       MYANMAR VOWEL SIGN AITON AI
  		(0x135D <= code && code <= 0x135F) || // Mn   [3] ETHIOPIC COMBINING GEMINATION AND VOWEL LENGTH MARK..ETHIOPIC COMBINING GEMINATION MARK
  		(0x1712 <= code && code <= 0x1714) || // Mn   [3] TAGALOG VOWEL SIGN I..TAGALOG SIGN VIRAMA
  		(0x1732 <= code && code <= 0x1734) || // Mn   [3] HANUNOO VOWEL SIGN I..HANUNOO SIGN PAMUDPOD
  		(0x1752 <= code && code <= 0x1753) || // Mn   [2] BUHID VOWEL SIGN I..BUHID VOWEL SIGN U
  		(0x1772 <= code && code <= 0x1773) || // Mn   [2] TAGBANWA VOWEL SIGN I..TAGBANWA VOWEL SIGN U
  		(0x17B4 <= code && code <= 0x17B5) || // Mn   [2] KHMER VOWEL INHERENT AQ..KHMER VOWEL INHERENT AA
  		(0x17B7 <= code && code <= 0x17BD) || // Mn   [7] KHMER VOWEL SIGN I..KHMER VOWEL SIGN UA
  		0x17C6 == code || // Mn       KHMER SIGN NIKAHIT
  		(0x17C9 <= code && code <= 0x17D3) || // Mn  [11] KHMER SIGN MUUSIKATOAN..KHMER SIGN BATHAMASAT
  		0x17DD == code || // Mn       KHMER SIGN ATTHACAN
  		(0x180B <= code && code <= 0x180D) || // Mn   [3] MONGOLIAN FREE VARIATION SELECTOR ONE..MONGOLIAN FREE VARIATION SELECTOR THREE
  		(0x1885 <= code && code <= 0x1886) || // Mn   [2] MONGOLIAN LETTER ALI GALI BALUDA..MONGOLIAN LETTER ALI GALI THREE BALUDA
  		0x18A9 == code || // Mn       MONGOLIAN LETTER ALI GALI DAGALGA
  		(0x1920 <= code && code <= 0x1922) || // Mn   [3] LIMBU VOWEL SIGN A..LIMBU VOWEL SIGN U
  		(0x1927 <= code && code <= 0x1928) || // Mn   [2] LIMBU VOWEL SIGN E..LIMBU VOWEL SIGN O
  		0x1932 == code || // Mn       LIMBU SMALL LETTER ANUSVARA
  		(0x1939 <= code && code <= 0x193B) || // Mn   [3] LIMBU SIGN MUKPHRENG..LIMBU SIGN SA-I
  		(0x1A17 <= code && code <= 0x1A18) || // Mn   [2] BUGINESE VOWEL SIGN I..BUGINESE VOWEL SIGN U
  		0x1A1B == code || // Mn       BUGINESE VOWEL SIGN AE
  		0x1A56 == code || // Mn       TAI THAM CONSONANT SIGN MEDIAL LA
  		(0x1A58 <= code && code <= 0x1A5E) || // Mn   [7] TAI THAM SIGN MAI KANG LAI..TAI THAM CONSONANT SIGN SA
  		0x1A60 == code || // Mn       TAI THAM SIGN SAKOT
  		0x1A62 == code || // Mn       TAI THAM VOWEL SIGN MAI SAT
  		(0x1A65 <= code && code <= 0x1A6C) || // Mn   [8] TAI THAM VOWEL SIGN I..TAI THAM VOWEL SIGN OA BELOW
  		(0x1A73 <= code && code <= 0x1A7C) || // Mn  [10] TAI THAM VOWEL SIGN OA ABOVE..TAI THAM SIGN KHUEN-LUE KARAN
  		0x1A7F == code || // Mn       TAI THAM COMBINING CRYPTOGRAMMIC DOT
  		(0x1AB0 <= code && code <= 0x1ABD) || // Mn  [14] COMBINING DOUBLED CIRCUMFLEX ACCENT..COMBINING PARENTHESES BELOW
  		0x1ABE == code || // Me       COMBINING PARENTHESES OVERLAY
  		(0x1B00 <= code && code <= 0x1B03) || // Mn   [4] BALINESE SIGN ULU RICEM..BALINESE SIGN SURANG
  		0x1B34 == code || // Mn       BALINESE SIGN REREKAN
  		(0x1B36 <= code && code <= 0x1B3A) || // Mn   [5] BALINESE VOWEL SIGN ULU..BALINESE VOWEL SIGN RA REPA
  		0x1B3C == code || // Mn       BALINESE VOWEL SIGN LA LENGA
  		0x1B42 == code || // Mn       BALINESE VOWEL SIGN PEPET
  		(0x1B6B <= code && code <= 0x1B73) || // Mn   [9] BALINESE MUSICAL SYMBOL COMBINING TEGEH..BALINESE MUSICAL SYMBOL COMBINING GONG
  		(0x1B80 <= code && code <= 0x1B81) || // Mn   [2] SUNDANESE SIGN PANYECEK..SUNDANESE SIGN PANGLAYAR
  		(0x1BA2 <= code && code <= 0x1BA5) || // Mn   [4] SUNDANESE CONSONANT SIGN PANYAKRA..SUNDANESE VOWEL SIGN PANYUKU
  		(0x1BA8 <= code && code <= 0x1BA9) || // Mn   [2] SUNDANESE VOWEL SIGN PAMEPET..SUNDANESE VOWEL SIGN PANEULEUNG
  		(0x1BAB <= code && code <= 0x1BAD) || // Mn   [3] SUNDANESE SIGN VIRAMA..SUNDANESE CONSONANT SIGN PASANGAN WA
  		0x1BE6 == code || // Mn       BATAK SIGN TOMPI
  		(0x1BE8 <= code && code <= 0x1BE9) || // Mn   [2] BATAK VOWEL SIGN PAKPAK E..BATAK VOWEL SIGN EE
  		0x1BED == code || // Mn       BATAK VOWEL SIGN KARO O
  		(0x1BEF <= code && code <= 0x1BF1) || // Mn   [3] BATAK VOWEL SIGN U FOR SIMALUNGUN SA..BATAK CONSONANT SIGN H
  		(0x1C2C <= code && code <= 0x1C33) || // Mn   [8] LEPCHA VOWEL SIGN E..LEPCHA CONSONANT SIGN T
  		(0x1C36 <= code && code <= 0x1C37) || // Mn   [2] LEPCHA SIGN RAN..LEPCHA SIGN NUKTA
  		(0x1CD0 <= code && code <= 0x1CD2) || // Mn   [3] VEDIC TONE KARSHANA..VEDIC TONE PRENKHA
  		(0x1CD4 <= code && code <= 0x1CE0) || // Mn  [13] VEDIC SIGN YAJURVEDIC MIDLINE SVARITA..VEDIC TONE RIGVEDIC KASHMIRI INDEPENDENT SVARITA
  		(0x1CE2 <= code && code <= 0x1CE8) || // Mn   [7] VEDIC SIGN VISARGA SVARITA..VEDIC SIGN VISARGA ANUDATTA WITH TAIL
  		0x1CED == code || // Mn       VEDIC SIGN TIRYAK
  		0x1CF4 == code || // Mn       VEDIC TONE CANDRA ABOVE
  		(0x1CF8 <= code && code <= 0x1CF9) || // Mn   [2] VEDIC TONE RING ABOVE..VEDIC TONE DOUBLE RING ABOVE
  		(0x1DC0 <= code && code <= 0x1DF9) || // Mn  [58] COMBINING DOTTED GRAVE ACCENT..COMBINING WIDE INVERTED BRIDGE BELOW
  		(0x1DFB <= code && code <= 0x1DFF) || // Mn   [5] COMBINING DELETION MARK..COMBINING RIGHT ARROWHEAD AND DOWN ARROWHEAD BELOW
  		0x200C == code || // Cf       ZERO WIDTH NON-JOINER
  		(0x20D0 <= code && code <= 0x20DC) || // Mn  [13] COMBINING LEFT HARPOON ABOVE..COMBINING FOUR DOTS ABOVE
  		(0x20DD <= code && code <= 0x20E0) || // Me   [4] COMBINING ENCLOSING CIRCLE..COMBINING ENCLOSING CIRCLE BACKSLASH
  		0x20E1 == code || // Mn       COMBINING LEFT RIGHT ARROW ABOVE
  		(0x20E2 <= code && code <= 0x20E4) || // Me   [3] COMBINING ENCLOSING SCREEN..COMBINING ENCLOSING UPWARD POINTING TRIANGLE
  		(0x20E5 <= code && code <= 0x20F0) || // Mn  [12] COMBINING REVERSE SOLIDUS OVERLAY..COMBINING ASTERISK ABOVE
  		(0x2CEF <= code && code <= 0x2CF1) || // Mn   [3] COPTIC COMBINING NI ABOVE..COPTIC COMBINING SPIRITUS LENIS
  		0x2D7F == code || // Mn       TIFINAGH CONSONANT JOINER
  		(0x2DE0 <= code && code <= 0x2DFF) || // Mn  [32] COMBINING CYRILLIC LETTER BE..COMBINING CYRILLIC LETTER IOTIFIED BIG YUS
  		(0x302A <= code && code <= 0x302D) || // Mn   [4] IDEOGRAPHIC LEVEL TONE MARK..IDEOGRAPHIC ENTERING TONE MARK
  		(0x302E <= code && code <= 0x302F) || // Mc   [2] HANGUL SINGLE DOT TONE MARK..HANGUL DOUBLE DOT TONE MARK
  		(0x3099 <= code && code <= 0x309A) || // Mn   [2] COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK..COMBINING KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK
  		0xA66F == code || // Mn       COMBINING CYRILLIC VZMET
  		(0xA670 <= code && code <= 0xA672) || // Me   [3] COMBINING CYRILLIC TEN MILLIONS SIGN..COMBINING CYRILLIC THOUSAND MILLIONS SIGN
  		(0xA674 <= code && code <= 0xA67D) || // Mn  [10] COMBINING CYRILLIC LETTER UKRAINIAN IE..COMBINING CYRILLIC PAYEROK
  		(0xA69E <= code && code <= 0xA69F) || // Mn   [2] COMBINING CYRILLIC LETTER EF..COMBINING CYRILLIC LETTER IOTIFIED E
  		(0xA6F0 <= code && code <= 0xA6F1) || // Mn   [2] BAMUM COMBINING MARK KOQNDON..BAMUM COMBINING MARK TUKWENTIS
  		0xA802 == code || // Mn       SYLOTI NAGRI SIGN DVISVARA
  		0xA806 == code || // Mn       SYLOTI NAGRI SIGN HASANTA
  		0xA80B == code || // Mn       SYLOTI NAGRI SIGN ANUSVARA
  		(0xA825 <= code && code <= 0xA826) || // Mn   [2] SYLOTI NAGRI VOWEL SIGN U..SYLOTI NAGRI VOWEL SIGN E
  		(0xA8C4 <= code && code <= 0xA8C5) || // Mn   [2] SAURASHTRA SIGN VIRAMA..SAURASHTRA SIGN CANDRABINDU
  		(0xA8E0 <= code && code <= 0xA8F1) || // Mn  [18] COMBINING DEVANAGARI DIGIT ZERO..COMBINING DEVANAGARI SIGN AVAGRAHA
  		(0xA926 <= code && code <= 0xA92D) || // Mn   [8] KAYAH LI VOWEL UE..KAYAH LI TONE CALYA PLOPHU
  		(0xA947 <= code && code <= 0xA951) || // Mn  [11] REJANG VOWEL SIGN I..REJANG CONSONANT SIGN R
  		(0xA980 <= code && code <= 0xA982) || // Mn   [3] JAVANESE SIGN PANYANGGA..JAVANESE SIGN LAYAR
  		0xA9B3 == code || // Mn       JAVANESE SIGN CECAK TELU
  		(0xA9B6 <= code && code <= 0xA9B9) || // Mn   [4] JAVANESE VOWEL SIGN WULU..JAVANESE VOWEL SIGN SUKU MENDUT
  		0xA9BC == code || // Mn       JAVANESE VOWEL SIGN PEPET
  		0xA9E5 == code || // Mn       MYANMAR SIGN SHAN SAW
  		(0xAA29 <= code && code <= 0xAA2E) || // Mn   [6] CHAM VOWEL SIGN AA..CHAM VOWEL SIGN OE
  		(0xAA31 <= code && code <= 0xAA32) || // Mn   [2] CHAM VOWEL SIGN AU..CHAM VOWEL SIGN UE
  		(0xAA35 <= code && code <= 0xAA36) || // Mn   [2] CHAM CONSONANT SIGN LA..CHAM CONSONANT SIGN WA
  		0xAA43 == code || // Mn       CHAM CONSONANT SIGN FINAL NG
  		0xAA4C == code || // Mn       CHAM CONSONANT SIGN FINAL M
  		0xAA7C == code || // Mn       MYANMAR SIGN TAI LAING TONE-2
  		0xAAB0 == code || // Mn       TAI VIET MAI KANG
  		(0xAAB2 <= code && code <= 0xAAB4) || // Mn   [3] TAI VIET VOWEL I..TAI VIET VOWEL U
  		(0xAAB7 <= code && code <= 0xAAB8) || // Mn   [2] TAI VIET MAI KHIT..TAI VIET VOWEL IA
  		(0xAABE <= code && code <= 0xAABF) || // Mn   [2] TAI VIET VOWEL AM..TAI VIET TONE MAI EK
  		0xAAC1 == code || // Mn       TAI VIET TONE MAI THO
  		(0xAAEC <= code && code <= 0xAAED) || // Mn   [2] MEETEI MAYEK VOWEL SIGN UU..MEETEI MAYEK VOWEL SIGN AAI
  		0xAAF6 == code || // Mn       MEETEI MAYEK VIRAMA
  		0xABE5 == code || // Mn       MEETEI MAYEK VOWEL SIGN ANAP
  		0xABE8 == code || // Mn       MEETEI MAYEK VOWEL SIGN UNAP
  		0xABED == code || // Mn       MEETEI MAYEK APUN IYEK
  		0xFB1E == code || // Mn       HEBREW POINT JUDEO-SPANISH VARIKA
  		(0xFE00 <= code && code <= 0xFE0F) || // Mn  [16] VARIATION SELECTOR-1..VARIATION SELECTOR-16
  		(0xFE20 <= code && code <= 0xFE2F) || // Mn  [16] COMBINING LIGATURE LEFT HALF..COMBINING CYRILLIC TITLO RIGHT HALF
  		(0xFF9E <= code && code <= 0xFF9F) || // Lm   [2] HALFWIDTH KATAKANA VOICED SOUND MARK..HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK
  		0x101FD == code || // Mn       PHAISTOS DISC SIGN COMBINING OBLIQUE STROKE
  		0x102E0 == code || // Mn       COPTIC EPACT THOUSANDS MARK
  		(0x10376 <= code && code <= 0x1037A) || // Mn   [5] COMBINING OLD PERMIC LETTER AN..COMBINING OLD PERMIC LETTER SII
  		(0x10A01 <= code && code <= 0x10A03) || // Mn   [3] KHAROSHTHI VOWEL SIGN I..KHAROSHTHI VOWEL SIGN VOCALIC R
  		(0x10A05 <= code && code <= 0x10A06) || // Mn   [2] KHAROSHTHI VOWEL SIGN E..KHAROSHTHI VOWEL SIGN O
  		(0x10A0C <= code && code <= 0x10A0F) || // Mn   [4] KHAROSHTHI VOWEL LENGTH MARK..KHAROSHTHI SIGN VISARGA
  		(0x10A38 <= code && code <= 0x10A3A) || // Mn   [3] KHAROSHTHI SIGN BAR ABOVE..KHAROSHTHI SIGN DOT BELOW
  		0x10A3F == code || // Mn       KHAROSHTHI VIRAMA
  		(0x10AE5 <= code && code <= 0x10AE6) || // Mn   [2] MANICHAEAN ABBREVIATION MARK ABOVE..MANICHAEAN ABBREVIATION MARK BELOW
  		0x11001 == code || // Mn       BRAHMI SIGN ANUSVARA
  		(0x11038 <= code && code <= 0x11046) || // Mn  [15] BRAHMI VOWEL SIGN AA..BRAHMI VIRAMA
  		(0x1107F <= code && code <= 0x11081) || // Mn   [3] BRAHMI NUMBER JOINER..KAITHI SIGN ANUSVARA
  		(0x110B3 <= code && code <= 0x110B6) || // Mn   [4] KAITHI VOWEL SIGN U..KAITHI VOWEL SIGN AI
  		(0x110B9 <= code && code <= 0x110BA) || // Mn   [2] KAITHI SIGN VIRAMA..KAITHI SIGN NUKTA
  		(0x11100 <= code && code <= 0x11102) || // Mn   [3] CHAKMA SIGN CANDRABINDU..CHAKMA SIGN VISARGA
  		(0x11127 <= code && code <= 0x1112B) || // Mn   [5] CHAKMA VOWEL SIGN A..CHAKMA VOWEL SIGN UU
  		(0x1112D <= code && code <= 0x11134) || // Mn   [8] CHAKMA VOWEL SIGN AI..CHAKMA MAAYYAA
  		0x11173 == code || // Mn       MAHAJANI SIGN NUKTA
  		(0x11180 <= code && code <= 0x11181) || // Mn   [2] SHARADA SIGN CANDRABINDU..SHARADA SIGN ANUSVARA
  		(0x111B6 <= code && code <= 0x111BE) || // Mn   [9] SHARADA VOWEL SIGN U..SHARADA VOWEL SIGN O
  		(0x111CA <= code && code <= 0x111CC) || // Mn   [3] SHARADA SIGN NUKTA..SHARADA EXTRA SHORT VOWEL MARK
  		(0x1122F <= code && code <= 0x11231) || // Mn   [3] KHOJKI VOWEL SIGN U..KHOJKI VOWEL SIGN AI
  		0x11234 == code || // Mn       KHOJKI SIGN ANUSVARA
  		(0x11236 <= code && code <= 0x11237) || // Mn   [2] KHOJKI SIGN NUKTA..KHOJKI SIGN SHADDA
  		0x1123E == code || // Mn       KHOJKI SIGN SUKUN
  		0x112DF == code || // Mn       KHUDAWADI SIGN ANUSVARA
  		(0x112E3 <= code && code <= 0x112EA) || // Mn   [8] KHUDAWADI VOWEL SIGN U..KHUDAWADI SIGN VIRAMA
  		(0x11300 <= code && code <= 0x11301) || // Mn   [2] GRANTHA SIGN COMBINING ANUSVARA ABOVE..GRANTHA SIGN CANDRABINDU
  		0x1133C == code || // Mn       GRANTHA SIGN NUKTA
  		0x1133E == code || // Mc       GRANTHA VOWEL SIGN AA
  		0x11340 == code || // Mn       GRANTHA VOWEL SIGN II
  		0x11357 == code || // Mc       GRANTHA AU LENGTH MARK
  		(0x11366 <= code && code <= 0x1136C) || // Mn   [7] COMBINING GRANTHA DIGIT ZERO..COMBINING GRANTHA DIGIT SIX
  		(0x11370 <= code && code <= 0x11374) || // Mn   [5] COMBINING GRANTHA LETTER A..COMBINING GRANTHA LETTER PA
  		(0x11438 <= code && code <= 0x1143F) || // Mn   [8] NEWA VOWEL SIGN U..NEWA VOWEL SIGN AI
  		(0x11442 <= code && code <= 0x11444) || // Mn   [3] NEWA SIGN VIRAMA..NEWA SIGN ANUSVARA
  		0x11446 == code || // Mn       NEWA SIGN NUKTA
  		0x114B0 == code || // Mc       TIRHUTA VOWEL SIGN AA
  		(0x114B3 <= code && code <= 0x114B8) || // Mn   [6] TIRHUTA VOWEL SIGN U..TIRHUTA VOWEL SIGN VOCALIC LL
  		0x114BA == code || // Mn       TIRHUTA VOWEL SIGN SHORT E
  		0x114BD == code || // Mc       TIRHUTA VOWEL SIGN SHORT O
  		(0x114BF <= code && code <= 0x114C0) || // Mn   [2] TIRHUTA SIGN CANDRABINDU..TIRHUTA SIGN ANUSVARA
  		(0x114C2 <= code && code <= 0x114C3) || // Mn   [2] TIRHUTA SIGN VIRAMA..TIRHUTA SIGN NUKTA
  		0x115AF == code || // Mc       SIDDHAM VOWEL SIGN AA
  		(0x115B2 <= code && code <= 0x115B5) || // Mn   [4] SIDDHAM VOWEL SIGN U..SIDDHAM VOWEL SIGN VOCALIC RR
  		(0x115BC <= code && code <= 0x115BD) || // Mn   [2] SIDDHAM SIGN CANDRABINDU..SIDDHAM SIGN ANUSVARA
  		(0x115BF <= code && code <= 0x115C0) || // Mn   [2] SIDDHAM SIGN VIRAMA..SIDDHAM SIGN NUKTA
  		(0x115DC <= code && code <= 0x115DD) || // Mn   [2] SIDDHAM VOWEL SIGN ALTERNATE U..SIDDHAM VOWEL SIGN ALTERNATE UU
  		(0x11633 <= code && code <= 0x1163A) || // Mn   [8] MODI VOWEL SIGN U..MODI VOWEL SIGN AI
  		0x1163D == code || // Mn       MODI SIGN ANUSVARA
  		(0x1163F <= code && code <= 0x11640) || // Mn   [2] MODI SIGN VIRAMA..MODI SIGN ARDHACANDRA
  		0x116AB == code || // Mn       TAKRI SIGN ANUSVARA
  		0x116AD == code || // Mn       TAKRI VOWEL SIGN AA
  		(0x116B0 <= code && code <= 0x116B5) || // Mn   [6] TAKRI VOWEL SIGN U..TAKRI VOWEL SIGN AU
  		0x116B7 == code || // Mn       TAKRI SIGN NUKTA
  		(0x1171D <= code && code <= 0x1171F) || // Mn   [3] AHOM CONSONANT SIGN MEDIAL LA..AHOM CONSONANT SIGN MEDIAL LIGATING RA
  		(0x11722 <= code && code <= 0x11725) || // Mn   [4] AHOM VOWEL SIGN I..AHOM VOWEL SIGN UU
  		(0x11727 <= code && code <= 0x1172B) || // Mn   [5] AHOM VOWEL SIGN AW..AHOM SIGN KILLER
  		(0x11A01 <= code && code <= 0x11A06) || // Mn   [6] ZANABAZAR SQUARE VOWEL SIGN I..ZANABAZAR SQUARE VOWEL SIGN O
  		(0x11A09 <= code && code <= 0x11A0A) || // Mn   [2] ZANABAZAR SQUARE VOWEL SIGN REVERSED I..ZANABAZAR SQUARE VOWEL LENGTH MARK
  		(0x11A33 <= code && code <= 0x11A38) || // Mn   [6] ZANABAZAR SQUARE FINAL CONSONANT MARK..ZANABAZAR SQUARE SIGN ANUSVARA
  		(0x11A3B <= code && code <= 0x11A3E) || // Mn   [4] ZANABAZAR SQUARE CLUSTER-FINAL LETTER YA..ZANABAZAR SQUARE CLUSTER-FINAL LETTER VA
  		0x11A47 == code || // Mn       ZANABAZAR SQUARE SUBJOINER
  		(0x11A51 <= code && code <= 0x11A56) || // Mn   [6] SOYOMBO VOWEL SIGN I..SOYOMBO VOWEL SIGN OE
  		(0x11A59 <= code && code <= 0x11A5B) || // Mn   [3] SOYOMBO VOWEL SIGN VOCALIC R..SOYOMBO VOWEL LENGTH MARK
  		(0x11A8A <= code && code <= 0x11A96) || // Mn  [13] SOYOMBO FINAL CONSONANT SIGN G..SOYOMBO SIGN ANUSVARA
  		(0x11A98 <= code && code <= 0x11A99) || // Mn   [2] SOYOMBO GEMINATION MARK..SOYOMBO SUBJOINER
  		(0x11C30 <= code && code <= 0x11C36) || // Mn   [7] BHAIKSUKI VOWEL SIGN I..BHAIKSUKI VOWEL SIGN VOCALIC L
  		(0x11C38 <= code && code <= 0x11C3D) || // Mn   [6] BHAIKSUKI VOWEL SIGN E..BHAIKSUKI SIGN ANUSVARA
  		0x11C3F == code || // Mn       BHAIKSUKI SIGN VIRAMA
  		(0x11C92 <= code && code <= 0x11CA7) || // Mn  [22] MARCHEN SUBJOINED LETTER KA..MARCHEN SUBJOINED LETTER ZA
  		(0x11CAA <= code && code <= 0x11CB0) || // Mn   [7] MARCHEN SUBJOINED LETTER RA..MARCHEN VOWEL SIGN AA
  		(0x11CB2 <= code && code <= 0x11CB3) || // Mn   [2] MARCHEN VOWEL SIGN U..MARCHEN VOWEL SIGN E
  		(0x11CB5 <= code && code <= 0x11CB6) || // Mn   [2] MARCHEN SIGN ANUSVARA..MARCHEN SIGN CANDRABINDU
  		(0x11D31 <= code && code <= 0x11D36) || // Mn   [6] MASARAM GONDI VOWEL SIGN AA..MASARAM GONDI VOWEL SIGN VOCALIC R
  		0x11D3A == code || // Mn       MASARAM GONDI VOWEL SIGN E
  		(0x11D3C <= code && code <= 0x11D3D) || // Mn   [2] MASARAM GONDI VOWEL SIGN AI..MASARAM GONDI VOWEL SIGN O
  		(0x11D3F <= code && code <= 0x11D45) || // Mn   [7] MASARAM GONDI VOWEL SIGN AU..MASARAM GONDI VIRAMA
  		0x11D47 == code || // Mn       MASARAM GONDI RA-KARA
  		(0x16AF0 <= code && code <= 0x16AF4) || // Mn   [5] BASSA VAH COMBINING HIGH TONE..BASSA VAH COMBINING HIGH-LOW TONE
  		(0x16B30 <= code && code <= 0x16B36) || // Mn   [7] PAHAWH HMONG MARK CIM TUB..PAHAWH HMONG MARK CIM TAUM
  		(0x16F8F <= code && code <= 0x16F92) || // Mn   [4] MIAO TONE RIGHT..MIAO TONE BELOW
  		(0x1BC9D <= code && code <= 0x1BC9E) || // Mn   [2] DUPLOYAN THICK LETTER SELECTOR..DUPLOYAN DOUBLE MARK
  		0x1D165 == code || // Mc       MUSICAL SYMBOL COMBINING STEM
  		(0x1D167 <= code && code <= 0x1D169) || // Mn   [3] MUSICAL SYMBOL COMBINING TREMOLO-1..MUSICAL SYMBOL COMBINING TREMOLO-3
  		(0x1D16E <= code && code <= 0x1D172) || // Mc   [5] MUSICAL SYMBOL COMBINING FLAG-1..MUSICAL SYMBOL COMBINING FLAG-5
  		(0x1D17B <= code && code <= 0x1D182) || // Mn   [8] MUSICAL SYMBOL COMBINING ACCENT..MUSICAL SYMBOL COMBINING LOURE
  		(0x1D185 <= code && code <= 0x1D18B) || // Mn   [7] MUSICAL SYMBOL COMBINING DOIT..MUSICAL SYMBOL COMBINING TRIPLE TONGUE
  		(0x1D1AA <= code && code <= 0x1D1AD) || // Mn   [4] MUSICAL SYMBOL COMBINING DOWN BOW..MUSICAL SYMBOL COMBINING SNAP PIZZICATO
  		(0x1D242 <= code && code <= 0x1D244) || // Mn   [3] COMBINING GREEK MUSICAL TRISEME..COMBINING GREEK MUSICAL PENTASEME
  		(0x1DA00 <= code && code <= 0x1DA36) || // Mn  [55] SIGNWRITING HEAD RIM..SIGNWRITING AIR SUCKING IN
  		(0x1DA3B <= code && code <= 0x1DA6C) || // Mn  [50] SIGNWRITING MOUTH CLOSED NEUTRAL..SIGNWRITING EXCITEMENT
  		0x1DA75 == code || // Mn       SIGNWRITING UPPER BODY TILTING FROM HIP JOINTS
  		0x1DA84 == code || // Mn       SIGNWRITING LOCATION HEAD NECK
  		(0x1DA9B <= code && code <= 0x1DA9F) || // Mn   [5] SIGNWRITING FILL MODIFIER-2..SIGNWRITING FILL MODIFIER-6
  		(0x1DAA1 <= code && code <= 0x1DAAF) || // Mn  [15] SIGNWRITING ROTATION MODIFIER-2..SIGNWRITING ROTATION MODIFIER-16
  		(0x1E000 <= code && code <= 0x1E006) || // Mn   [7] COMBINING GLAGOLITIC LETTER AZU..COMBINING GLAGOLITIC LETTER ZHIVETE
  		(0x1E008 <= code && code <= 0x1E018) || // Mn  [17] COMBINING GLAGOLITIC LETTER ZEMLJA..COMBINING GLAGOLITIC LETTER HERU
  		(0x1E01B <= code && code <= 0x1E021) || // Mn   [7] COMBINING GLAGOLITIC LETTER SHTA..COMBINING GLAGOLITIC LETTER YATI
  		(0x1E023 <= code && code <= 0x1E024) || // Mn   [2] COMBINING GLAGOLITIC LETTER YU..COMBINING GLAGOLITIC LETTER SMALL YUS
  		(0x1E026 <= code && code <= 0x1E02A) || // Mn   [5] COMBINING GLAGOLITIC LETTER YO..COMBINING GLAGOLITIC LETTER FITA
  		(0x1E8D0 <= code && code <= 0x1E8D6) || // Mn   [7] MENDE KIKAKUI COMBINING NUMBER TEENS..MENDE KIKAKUI COMBINING NUMBER MILLIONS
  		(0x1E944 <= code && code <= 0x1E94A) || // Mn   [7] ADLAM ALIF LENGTHENER..ADLAM NUKTA
  		(0xE0020 <= code && code <= 0xE007F) || // Cf  [96] TAG SPACE..CANCEL TAG
  		(0xE0100 <= code && code <= 0xE01EF) // Mn [240] VARIATION SELECTOR-17..VARIATION SELECTOR-256
  		){
  			return Extend;
  		}
  		
  		
  		if(
  		(0x1F1E6 <= code && code <= 0x1F1FF) // So  [26] REGIONAL INDICATOR SYMBOL LETTER A..REGIONAL INDICATOR SYMBOL LETTER Z
  		){
  			return Regional_Indicator;
  		}
  		
  		if(
  		0x0903 == code || // Mc       DEVANAGARI SIGN VISARGA
  		0x093B == code || // Mc       DEVANAGARI VOWEL SIGN OOE
  		(0x093E <= code && code <= 0x0940) || // Mc   [3] DEVANAGARI VOWEL SIGN AA..DEVANAGARI VOWEL SIGN II
  		(0x0949 <= code && code <= 0x094C) || // Mc   [4] DEVANAGARI VOWEL SIGN CANDRA O..DEVANAGARI VOWEL SIGN AU
  		(0x094E <= code && code <= 0x094F) || // Mc   [2] DEVANAGARI VOWEL SIGN PRISHTHAMATRA E..DEVANAGARI VOWEL SIGN AW
  		(0x0982 <= code && code <= 0x0983) || // Mc   [2] BENGALI SIGN ANUSVARA..BENGALI SIGN VISARGA
  		(0x09BF <= code && code <= 0x09C0) || // Mc   [2] BENGALI VOWEL SIGN I..BENGALI VOWEL SIGN II
  		(0x09C7 <= code && code <= 0x09C8) || // Mc   [2] BENGALI VOWEL SIGN E..BENGALI VOWEL SIGN AI
  		(0x09CB <= code && code <= 0x09CC) || // Mc   [2] BENGALI VOWEL SIGN O..BENGALI VOWEL SIGN AU
  		0x0A03 == code || // Mc       GURMUKHI SIGN VISARGA
  		(0x0A3E <= code && code <= 0x0A40) || // Mc   [3] GURMUKHI VOWEL SIGN AA..GURMUKHI VOWEL SIGN II
  		0x0A83 == code || // Mc       GUJARATI SIGN VISARGA
  		(0x0ABE <= code && code <= 0x0AC0) || // Mc   [3] GUJARATI VOWEL SIGN AA..GUJARATI VOWEL SIGN II
  		0x0AC9 == code || // Mc       GUJARATI VOWEL SIGN CANDRA O
  		(0x0ACB <= code && code <= 0x0ACC) || // Mc   [2] GUJARATI VOWEL SIGN O..GUJARATI VOWEL SIGN AU
  		(0x0B02 <= code && code <= 0x0B03) || // Mc   [2] ORIYA SIGN ANUSVARA..ORIYA SIGN VISARGA
  		0x0B40 == code || // Mc       ORIYA VOWEL SIGN II
  		(0x0B47 <= code && code <= 0x0B48) || // Mc   [2] ORIYA VOWEL SIGN E..ORIYA VOWEL SIGN AI
  		(0x0B4B <= code && code <= 0x0B4C) || // Mc   [2] ORIYA VOWEL SIGN O..ORIYA VOWEL SIGN AU
  		0x0BBF == code || // Mc       TAMIL VOWEL SIGN I
  		(0x0BC1 <= code && code <= 0x0BC2) || // Mc   [2] TAMIL VOWEL SIGN U..TAMIL VOWEL SIGN UU
  		(0x0BC6 <= code && code <= 0x0BC8) || // Mc   [3] TAMIL VOWEL SIGN E..TAMIL VOWEL SIGN AI
  		(0x0BCA <= code && code <= 0x0BCC) || // Mc   [3] TAMIL VOWEL SIGN O..TAMIL VOWEL SIGN AU
  		(0x0C01 <= code && code <= 0x0C03) || // Mc   [3] TELUGU SIGN CANDRABINDU..TELUGU SIGN VISARGA
  		(0x0C41 <= code && code <= 0x0C44) || // Mc   [4] TELUGU VOWEL SIGN U..TELUGU VOWEL SIGN VOCALIC RR
  		(0x0C82 <= code && code <= 0x0C83) || // Mc   [2] KANNADA SIGN ANUSVARA..KANNADA SIGN VISARGA
  		0x0CBE == code || // Mc       KANNADA VOWEL SIGN AA
  		(0x0CC0 <= code && code <= 0x0CC1) || // Mc   [2] KANNADA VOWEL SIGN II..KANNADA VOWEL SIGN U
  		(0x0CC3 <= code && code <= 0x0CC4) || // Mc   [2] KANNADA VOWEL SIGN VOCALIC R..KANNADA VOWEL SIGN VOCALIC RR
  		(0x0CC7 <= code && code <= 0x0CC8) || // Mc   [2] KANNADA VOWEL SIGN EE..KANNADA VOWEL SIGN AI
  		(0x0CCA <= code && code <= 0x0CCB) || // Mc   [2] KANNADA VOWEL SIGN O..KANNADA VOWEL SIGN OO
  		(0x0D02 <= code && code <= 0x0D03) || // Mc   [2] MALAYALAM SIGN ANUSVARA..MALAYALAM SIGN VISARGA
  		(0x0D3F <= code && code <= 0x0D40) || // Mc   [2] MALAYALAM VOWEL SIGN I..MALAYALAM VOWEL SIGN II
  		(0x0D46 <= code && code <= 0x0D48) || // Mc   [3] MALAYALAM VOWEL SIGN E..MALAYALAM VOWEL SIGN AI
  		(0x0D4A <= code && code <= 0x0D4C) || // Mc   [3] MALAYALAM VOWEL SIGN O..MALAYALAM VOWEL SIGN AU
  		(0x0D82 <= code && code <= 0x0D83) || // Mc   [2] SINHALA SIGN ANUSVARAYA..SINHALA SIGN VISARGAYA
  		(0x0DD0 <= code && code <= 0x0DD1) || // Mc   [2] SINHALA VOWEL SIGN KETTI AEDA-PILLA..SINHALA VOWEL SIGN DIGA AEDA-PILLA
  		(0x0DD8 <= code && code <= 0x0DDE) || // Mc   [7] SINHALA VOWEL SIGN GAETTA-PILLA..SINHALA VOWEL SIGN KOMBUVA HAA GAYANUKITTA
  		(0x0DF2 <= code && code <= 0x0DF3) || // Mc   [2] SINHALA VOWEL SIGN DIGA GAETTA-PILLA..SINHALA VOWEL SIGN DIGA GAYANUKITTA
  		0x0E33 == code || // Lo       THAI CHARACTER SARA AM
  		0x0EB3 == code || // Lo       LAO VOWEL SIGN AM
  		(0x0F3E <= code && code <= 0x0F3F) || // Mc   [2] TIBETAN SIGN YAR TSHES..TIBETAN SIGN MAR TSHES
  		0x0F7F == code || // Mc       TIBETAN SIGN RNAM BCAD
  		0x1031 == code || // Mc       MYANMAR VOWEL SIGN E
  		(0x103B <= code && code <= 0x103C) || // Mc   [2] MYANMAR CONSONANT SIGN MEDIAL YA..MYANMAR CONSONANT SIGN MEDIAL RA
  		(0x1056 <= code && code <= 0x1057) || // Mc   [2] MYANMAR VOWEL SIGN VOCALIC R..MYANMAR VOWEL SIGN VOCALIC RR
  		0x1084 == code || // Mc       MYANMAR VOWEL SIGN SHAN E
  		0x17B6 == code || // Mc       KHMER VOWEL SIGN AA
  		(0x17BE <= code && code <= 0x17C5) || // Mc   [8] KHMER VOWEL SIGN OE..KHMER VOWEL SIGN AU
  		(0x17C7 <= code && code <= 0x17C8) || // Mc   [2] KHMER SIGN REAHMUK..KHMER SIGN YUUKALEAPINTU
  		(0x1923 <= code && code <= 0x1926) || // Mc   [4] LIMBU VOWEL SIGN EE..LIMBU VOWEL SIGN AU
  		(0x1929 <= code && code <= 0x192B) || // Mc   [3] LIMBU SUBJOINED LETTER YA..LIMBU SUBJOINED LETTER WA
  		(0x1930 <= code && code <= 0x1931) || // Mc   [2] LIMBU SMALL LETTER KA..LIMBU SMALL LETTER NGA
  		(0x1933 <= code && code <= 0x1938) || // Mc   [6] LIMBU SMALL LETTER TA..LIMBU SMALL LETTER LA
  		(0x1A19 <= code && code <= 0x1A1A) || // Mc   [2] BUGINESE VOWEL SIGN E..BUGINESE VOWEL SIGN O
  		0x1A55 == code || // Mc       TAI THAM CONSONANT SIGN MEDIAL RA
  		0x1A57 == code || // Mc       TAI THAM CONSONANT SIGN LA TANG LAI
  		(0x1A6D <= code && code <= 0x1A72) || // Mc   [6] TAI THAM VOWEL SIGN OY..TAI THAM VOWEL SIGN THAM AI
  		0x1B04 == code || // Mc       BALINESE SIGN BISAH
  		0x1B35 == code || // Mc       BALINESE VOWEL SIGN TEDUNG
  		0x1B3B == code || // Mc       BALINESE VOWEL SIGN RA REPA TEDUNG
  		(0x1B3D <= code && code <= 0x1B41) || // Mc   [5] BALINESE VOWEL SIGN LA LENGA TEDUNG..BALINESE VOWEL SIGN TALING REPA TEDUNG
  		(0x1B43 <= code && code <= 0x1B44) || // Mc   [2] BALINESE VOWEL SIGN PEPET TEDUNG..BALINESE ADEG ADEG
  		0x1B82 == code || // Mc       SUNDANESE SIGN PANGWISAD
  		0x1BA1 == code || // Mc       SUNDANESE CONSONANT SIGN PAMINGKAL
  		(0x1BA6 <= code && code <= 0x1BA7) || // Mc   [2] SUNDANESE VOWEL SIGN PANAELAENG..SUNDANESE VOWEL SIGN PANOLONG
  		0x1BAA == code || // Mc       SUNDANESE SIGN PAMAAEH
  		0x1BE7 == code || // Mc       BATAK VOWEL SIGN E
  		(0x1BEA <= code && code <= 0x1BEC) || // Mc   [3] BATAK VOWEL SIGN I..BATAK VOWEL SIGN O
  		0x1BEE == code || // Mc       BATAK VOWEL SIGN U
  		(0x1BF2 <= code && code <= 0x1BF3) || // Mc   [2] BATAK PANGOLAT..BATAK PANONGONAN
  		(0x1C24 <= code && code <= 0x1C2B) || // Mc   [8] LEPCHA SUBJOINED LETTER YA..LEPCHA VOWEL SIGN UU
  		(0x1C34 <= code && code <= 0x1C35) || // Mc   [2] LEPCHA CONSONANT SIGN NYIN-DO..LEPCHA CONSONANT SIGN KANG
  		0x1CE1 == code || // Mc       VEDIC TONE ATHARVAVEDIC INDEPENDENT SVARITA
  		(0x1CF2 <= code && code <= 0x1CF3) || // Mc   [2] VEDIC SIGN ARDHAVISARGA..VEDIC SIGN ROTATED ARDHAVISARGA
  		0x1CF7 == code || // Mc       VEDIC SIGN ATIKRAMA
  		(0xA823 <= code && code <= 0xA824) || // Mc   [2] SYLOTI NAGRI VOWEL SIGN A..SYLOTI NAGRI VOWEL SIGN I
  		0xA827 == code || // Mc       SYLOTI NAGRI VOWEL SIGN OO
  		(0xA880 <= code && code <= 0xA881) || // Mc   [2] SAURASHTRA SIGN ANUSVARA..SAURASHTRA SIGN VISARGA
  		(0xA8B4 <= code && code <= 0xA8C3) || // Mc  [16] SAURASHTRA CONSONANT SIGN HAARU..SAURASHTRA VOWEL SIGN AU
  		(0xA952 <= code && code <= 0xA953) || // Mc   [2] REJANG CONSONANT SIGN H..REJANG VIRAMA
  		0xA983 == code || // Mc       JAVANESE SIGN WIGNYAN
  		(0xA9B4 <= code && code <= 0xA9B5) || // Mc   [2] JAVANESE VOWEL SIGN TARUNG..JAVANESE VOWEL SIGN TOLONG
  		(0xA9BA <= code && code <= 0xA9BB) || // Mc   [2] JAVANESE VOWEL SIGN TALING..JAVANESE VOWEL SIGN DIRGA MURE
  		(0xA9BD <= code && code <= 0xA9C0) || // Mc   [4] JAVANESE CONSONANT SIGN KERET..JAVANESE PANGKON
  		(0xAA2F <= code && code <= 0xAA30) || // Mc   [2] CHAM VOWEL SIGN O..CHAM VOWEL SIGN AI
  		(0xAA33 <= code && code <= 0xAA34) || // Mc   [2] CHAM CONSONANT SIGN YA..CHAM CONSONANT SIGN RA
  		0xAA4D == code || // Mc       CHAM CONSONANT SIGN FINAL H
  		0xAAEB == code || // Mc       MEETEI MAYEK VOWEL SIGN II
  		(0xAAEE <= code && code <= 0xAAEF) || // Mc   [2] MEETEI MAYEK VOWEL SIGN AU..MEETEI MAYEK VOWEL SIGN AAU
  		0xAAF5 == code || // Mc       MEETEI MAYEK VOWEL SIGN VISARGA
  		(0xABE3 <= code && code <= 0xABE4) || // Mc   [2] MEETEI MAYEK VOWEL SIGN ONAP..MEETEI MAYEK VOWEL SIGN INAP
  		(0xABE6 <= code && code <= 0xABE7) || // Mc   [2] MEETEI MAYEK VOWEL SIGN YENAP..MEETEI MAYEK VOWEL SIGN SOUNAP
  		(0xABE9 <= code && code <= 0xABEA) || // Mc   [2] MEETEI MAYEK VOWEL SIGN CHEINAP..MEETEI MAYEK VOWEL SIGN NUNG
  		0xABEC == code || // Mc       MEETEI MAYEK LUM IYEK
  		0x11000 == code || // Mc       BRAHMI SIGN CANDRABINDU
  		0x11002 == code || // Mc       BRAHMI SIGN VISARGA
  		0x11082 == code || // Mc       KAITHI SIGN VISARGA
  		(0x110B0 <= code && code <= 0x110B2) || // Mc   [3] KAITHI VOWEL SIGN AA..KAITHI VOWEL SIGN II
  		(0x110B7 <= code && code <= 0x110B8) || // Mc   [2] KAITHI VOWEL SIGN O..KAITHI VOWEL SIGN AU
  		0x1112C == code || // Mc       CHAKMA VOWEL SIGN E
  		0x11182 == code || // Mc       SHARADA SIGN VISARGA
  		(0x111B3 <= code && code <= 0x111B5) || // Mc   [3] SHARADA VOWEL SIGN AA..SHARADA VOWEL SIGN II
  		(0x111BF <= code && code <= 0x111C0) || // Mc   [2] SHARADA VOWEL SIGN AU..SHARADA SIGN VIRAMA
  		(0x1122C <= code && code <= 0x1122E) || // Mc   [3] KHOJKI VOWEL SIGN AA..KHOJKI VOWEL SIGN II
  		(0x11232 <= code && code <= 0x11233) || // Mc   [2] KHOJKI VOWEL SIGN O..KHOJKI VOWEL SIGN AU
  		0x11235 == code || // Mc       KHOJKI SIGN VIRAMA
  		(0x112E0 <= code && code <= 0x112E2) || // Mc   [3] KHUDAWADI VOWEL SIGN AA..KHUDAWADI VOWEL SIGN II
  		(0x11302 <= code && code <= 0x11303) || // Mc   [2] GRANTHA SIGN ANUSVARA..GRANTHA SIGN VISARGA
  		0x1133F == code || // Mc       GRANTHA VOWEL SIGN I
  		(0x11341 <= code && code <= 0x11344) || // Mc   [4] GRANTHA VOWEL SIGN U..GRANTHA VOWEL SIGN VOCALIC RR
  		(0x11347 <= code && code <= 0x11348) || // Mc   [2] GRANTHA VOWEL SIGN EE..GRANTHA VOWEL SIGN AI
  		(0x1134B <= code && code <= 0x1134D) || // Mc   [3] GRANTHA VOWEL SIGN OO..GRANTHA SIGN VIRAMA
  		(0x11362 <= code && code <= 0x11363) || // Mc   [2] GRANTHA VOWEL SIGN VOCALIC L..GRANTHA VOWEL SIGN VOCALIC LL
  		(0x11435 <= code && code <= 0x11437) || // Mc   [3] NEWA VOWEL SIGN AA..NEWA VOWEL SIGN II
  		(0x11440 <= code && code <= 0x11441) || // Mc   [2] NEWA VOWEL SIGN O..NEWA VOWEL SIGN AU
  		0x11445 == code || // Mc       NEWA SIGN VISARGA
  		(0x114B1 <= code && code <= 0x114B2) || // Mc   [2] TIRHUTA VOWEL SIGN I..TIRHUTA VOWEL SIGN II
  		0x114B9 == code || // Mc       TIRHUTA VOWEL SIGN E
  		(0x114BB <= code && code <= 0x114BC) || // Mc   [2] TIRHUTA VOWEL SIGN AI..TIRHUTA VOWEL SIGN O
  		0x114BE == code || // Mc       TIRHUTA VOWEL SIGN AU
  		0x114C1 == code || // Mc       TIRHUTA SIGN VISARGA
  		(0x115B0 <= code && code <= 0x115B1) || // Mc   [2] SIDDHAM VOWEL SIGN I..SIDDHAM VOWEL SIGN II
  		(0x115B8 <= code && code <= 0x115BB) || // Mc   [4] SIDDHAM VOWEL SIGN E..SIDDHAM VOWEL SIGN AU
  		0x115BE == code || // Mc       SIDDHAM SIGN VISARGA
  		(0x11630 <= code && code <= 0x11632) || // Mc   [3] MODI VOWEL SIGN AA..MODI VOWEL SIGN II
  		(0x1163B <= code && code <= 0x1163C) || // Mc   [2] MODI VOWEL SIGN O..MODI VOWEL SIGN AU
  		0x1163E == code || // Mc       MODI SIGN VISARGA
  		0x116AC == code || // Mc       TAKRI SIGN VISARGA
  		(0x116AE <= code && code <= 0x116AF) || // Mc   [2] TAKRI VOWEL SIGN I..TAKRI VOWEL SIGN II
  		0x116B6 == code || // Mc       TAKRI SIGN VIRAMA
  		(0x11720 <= code && code <= 0x11721) || // Mc   [2] AHOM VOWEL SIGN A..AHOM VOWEL SIGN AA
  		0x11726 == code || // Mc       AHOM VOWEL SIGN E
  		(0x11A07 <= code && code <= 0x11A08) || // Mc   [2] ZANABAZAR SQUARE VOWEL SIGN AI..ZANABAZAR SQUARE VOWEL SIGN AU
  		0x11A39 == code || // Mc       ZANABAZAR SQUARE SIGN VISARGA
  		(0x11A57 <= code && code <= 0x11A58) || // Mc   [2] SOYOMBO VOWEL SIGN AI..SOYOMBO VOWEL SIGN AU
  		0x11A97 == code || // Mc       SOYOMBO SIGN VISARGA
  		0x11C2F == code || // Mc       BHAIKSUKI VOWEL SIGN AA
  		0x11C3E == code || // Mc       BHAIKSUKI SIGN VISARGA
  		0x11CA9 == code || // Mc       MARCHEN SUBJOINED LETTER YA
  		0x11CB1 == code || // Mc       MARCHEN VOWEL SIGN I
  		0x11CB4 == code || // Mc       MARCHEN VOWEL SIGN O
  		(0x16F51 <= code && code <= 0x16F7E) || // Mc  [46] MIAO SIGN ASPIRATION..MIAO VOWEL SIGN NG
  		0x1D166 == code || // Mc       MUSICAL SYMBOL COMBINING SPRECHGESANG STEM
  		0x1D16D == code // Mc       MUSICAL SYMBOL COMBINING AUGMENTATION DOT
  		){
  			return SpacingMark;
  		}
  		
  		
  		if(
  		(0x1100 <= code && code <= 0x115F) || // Lo  [96] HANGUL CHOSEONG KIYEOK..HANGUL CHOSEONG FILLER
  		(0xA960 <= code && code <= 0xA97C) // Lo  [29] HANGUL CHOSEONG TIKEUT-MIEUM..HANGUL CHOSEONG SSANGYEORINHIEUH
  		){
  			return L;
  		}
  		
  		if(
  		(0x1160 <= code && code <= 0x11A7) || // Lo  [72] HANGUL JUNGSEONG FILLER..HANGUL JUNGSEONG O-YAE
  		(0xD7B0 <= code && code <= 0xD7C6) // Lo  [23] HANGUL JUNGSEONG O-YEO..HANGUL JUNGSEONG ARAEA-E
  		){
  			return V;
  		}
  		
  		
  		if(
  		(0x11A8 <= code && code <= 0x11FF) || // Lo  [88] HANGUL JONGSEONG KIYEOK..HANGUL JONGSEONG SSANGNIEUN
  		(0xD7CB <= code && code <= 0xD7FB) // Lo  [49] HANGUL JONGSEONG NIEUN-RIEUL..HANGUL JONGSEONG PHIEUPH-THIEUTH
  		){
  			return T;
  		}
  		
  		if(
  		0xAC00 == code || // Lo       HANGUL SYLLABLE GA
  		0xAC1C == code || // Lo       HANGUL SYLLABLE GAE
  		0xAC38 == code || // Lo       HANGUL SYLLABLE GYA
  		0xAC54 == code || // Lo       HANGUL SYLLABLE GYAE
  		0xAC70 == code || // Lo       HANGUL SYLLABLE GEO
  		0xAC8C == code || // Lo       HANGUL SYLLABLE GE
  		0xACA8 == code || // Lo       HANGUL SYLLABLE GYEO
  		0xACC4 == code || // Lo       HANGUL SYLLABLE GYE
  		0xACE0 == code || // Lo       HANGUL SYLLABLE GO
  		0xACFC == code || // Lo       HANGUL SYLLABLE GWA
  		0xAD18 == code || // Lo       HANGUL SYLLABLE GWAE
  		0xAD34 == code || // Lo       HANGUL SYLLABLE GOE
  		0xAD50 == code || // Lo       HANGUL SYLLABLE GYO
  		0xAD6C == code || // Lo       HANGUL SYLLABLE GU
  		0xAD88 == code || // Lo       HANGUL SYLLABLE GWEO
  		0xADA4 == code || // Lo       HANGUL SYLLABLE GWE
  		0xADC0 == code || // Lo       HANGUL SYLLABLE GWI
  		0xADDC == code || // Lo       HANGUL SYLLABLE GYU
  		0xADF8 == code || // Lo       HANGUL SYLLABLE GEU
  		0xAE14 == code || // Lo       HANGUL SYLLABLE GYI
  		0xAE30 == code || // Lo       HANGUL SYLLABLE GI
  		0xAE4C == code || // Lo       HANGUL SYLLABLE GGA
  		0xAE68 == code || // Lo       HANGUL SYLLABLE GGAE
  		0xAE84 == code || // Lo       HANGUL SYLLABLE GGYA
  		0xAEA0 == code || // Lo       HANGUL SYLLABLE GGYAE
  		0xAEBC == code || // Lo       HANGUL SYLLABLE GGEO
  		0xAED8 == code || // Lo       HANGUL SYLLABLE GGE
  		0xAEF4 == code || // Lo       HANGUL SYLLABLE GGYEO
  		0xAF10 == code || // Lo       HANGUL SYLLABLE GGYE
  		0xAF2C == code || // Lo       HANGUL SYLLABLE GGO
  		0xAF48 == code || // Lo       HANGUL SYLLABLE GGWA
  		0xAF64 == code || // Lo       HANGUL SYLLABLE GGWAE
  		0xAF80 == code || // Lo       HANGUL SYLLABLE GGOE
  		0xAF9C == code || // Lo       HANGUL SYLLABLE GGYO
  		0xAFB8 == code || // Lo       HANGUL SYLLABLE GGU
  		0xAFD4 == code || // Lo       HANGUL SYLLABLE GGWEO
  		0xAFF0 == code || // Lo       HANGUL SYLLABLE GGWE
  		0xB00C == code || // Lo       HANGUL SYLLABLE GGWI
  		0xB028 == code || // Lo       HANGUL SYLLABLE GGYU
  		0xB044 == code || // Lo       HANGUL SYLLABLE GGEU
  		0xB060 == code || // Lo       HANGUL SYLLABLE GGYI
  		0xB07C == code || // Lo       HANGUL SYLLABLE GGI
  		0xB098 == code || // Lo       HANGUL SYLLABLE NA
  		0xB0B4 == code || // Lo       HANGUL SYLLABLE NAE
  		0xB0D0 == code || // Lo       HANGUL SYLLABLE NYA
  		0xB0EC == code || // Lo       HANGUL SYLLABLE NYAE
  		0xB108 == code || // Lo       HANGUL SYLLABLE NEO
  		0xB124 == code || // Lo       HANGUL SYLLABLE NE
  		0xB140 == code || // Lo       HANGUL SYLLABLE NYEO
  		0xB15C == code || // Lo       HANGUL SYLLABLE NYE
  		0xB178 == code || // Lo       HANGUL SYLLABLE NO
  		0xB194 == code || // Lo       HANGUL SYLLABLE NWA
  		0xB1B0 == code || // Lo       HANGUL SYLLABLE NWAE
  		0xB1CC == code || // Lo       HANGUL SYLLABLE NOE
  		0xB1E8 == code || // Lo       HANGUL SYLLABLE NYO
  		0xB204 == code || // Lo       HANGUL SYLLABLE NU
  		0xB220 == code || // Lo       HANGUL SYLLABLE NWEO
  		0xB23C == code || // Lo       HANGUL SYLLABLE NWE
  		0xB258 == code || // Lo       HANGUL SYLLABLE NWI
  		0xB274 == code || // Lo       HANGUL SYLLABLE NYU
  		0xB290 == code || // Lo       HANGUL SYLLABLE NEU
  		0xB2AC == code || // Lo       HANGUL SYLLABLE NYI
  		0xB2C8 == code || // Lo       HANGUL SYLLABLE NI
  		0xB2E4 == code || // Lo       HANGUL SYLLABLE DA
  		0xB300 == code || // Lo       HANGUL SYLLABLE DAE
  		0xB31C == code || // Lo       HANGUL SYLLABLE DYA
  		0xB338 == code || // Lo       HANGUL SYLLABLE DYAE
  		0xB354 == code || // Lo       HANGUL SYLLABLE DEO
  		0xB370 == code || // Lo       HANGUL SYLLABLE DE
  		0xB38C == code || // Lo       HANGUL SYLLABLE DYEO
  		0xB3A8 == code || // Lo       HANGUL SYLLABLE DYE
  		0xB3C4 == code || // Lo       HANGUL SYLLABLE DO
  		0xB3E0 == code || // Lo       HANGUL SYLLABLE DWA
  		0xB3FC == code || // Lo       HANGUL SYLLABLE DWAE
  		0xB418 == code || // Lo       HANGUL SYLLABLE DOE
  		0xB434 == code || // Lo       HANGUL SYLLABLE DYO
  		0xB450 == code || // Lo       HANGUL SYLLABLE DU
  		0xB46C == code || // Lo       HANGUL SYLLABLE DWEO
  		0xB488 == code || // Lo       HANGUL SYLLABLE DWE
  		0xB4A4 == code || // Lo       HANGUL SYLLABLE DWI
  		0xB4C0 == code || // Lo       HANGUL SYLLABLE DYU
  		0xB4DC == code || // Lo       HANGUL SYLLABLE DEU
  		0xB4F8 == code || // Lo       HANGUL SYLLABLE DYI
  		0xB514 == code || // Lo       HANGUL SYLLABLE DI
  		0xB530 == code || // Lo       HANGUL SYLLABLE DDA
  		0xB54C == code || // Lo       HANGUL SYLLABLE DDAE
  		0xB568 == code || // Lo       HANGUL SYLLABLE DDYA
  		0xB584 == code || // Lo       HANGUL SYLLABLE DDYAE
  		0xB5A0 == code || // Lo       HANGUL SYLLABLE DDEO
  		0xB5BC == code || // Lo       HANGUL SYLLABLE DDE
  		0xB5D8 == code || // Lo       HANGUL SYLLABLE DDYEO
  		0xB5F4 == code || // Lo       HANGUL SYLLABLE DDYE
  		0xB610 == code || // Lo       HANGUL SYLLABLE DDO
  		0xB62C == code || // Lo       HANGUL SYLLABLE DDWA
  		0xB648 == code || // Lo       HANGUL SYLLABLE DDWAE
  		0xB664 == code || // Lo       HANGUL SYLLABLE DDOE
  		0xB680 == code || // Lo       HANGUL SYLLABLE DDYO
  		0xB69C == code || // Lo       HANGUL SYLLABLE DDU
  		0xB6B8 == code || // Lo       HANGUL SYLLABLE DDWEO
  		0xB6D4 == code || // Lo       HANGUL SYLLABLE DDWE
  		0xB6F0 == code || // Lo       HANGUL SYLLABLE DDWI
  		0xB70C == code || // Lo       HANGUL SYLLABLE DDYU
  		0xB728 == code || // Lo       HANGUL SYLLABLE DDEU
  		0xB744 == code || // Lo       HANGUL SYLLABLE DDYI
  		0xB760 == code || // Lo       HANGUL SYLLABLE DDI
  		0xB77C == code || // Lo       HANGUL SYLLABLE RA
  		0xB798 == code || // Lo       HANGUL SYLLABLE RAE
  		0xB7B4 == code || // Lo       HANGUL SYLLABLE RYA
  		0xB7D0 == code || // Lo       HANGUL SYLLABLE RYAE
  		0xB7EC == code || // Lo       HANGUL SYLLABLE REO
  		0xB808 == code || // Lo       HANGUL SYLLABLE RE
  		0xB824 == code || // Lo       HANGUL SYLLABLE RYEO
  		0xB840 == code || // Lo       HANGUL SYLLABLE RYE
  		0xB85C == code || // Lo       HANGUL SYLLABLE RO
  		0xB878 == code || // Lo       HANGUL SYLLABLE RWA
  		0xB894 == code || // Lo       HANGUL SYLLABLE RWAE
  		0xB8B0 == code || // Lo       HANGUL SYLLABLE ROE
  		0xB8CC == code || // Lo       HANGUL SYLLABLE RYO
  		0xB8E8 == code || // Lo       HANGUL SYLLABLE RU
  		0xB904 == code || // Lo       HANGUL SYLLABLE RWEO
  		0xB920 == code || // Lo       HANGUL SYLLABLE RWE
  		0xB93C == code || // Lo       HANGUL SYLLABLE RWI
  		0xB958 == code || // Lo       HANGUL SYLLABLE RYU
  		0xB974 == code || // Lo       HANGUL SYLLABLE REU
  		0xB990 == code || // Lo       HANGUL SYLLABLE RYI
  		0xB9AC == code || // Lo       HANGUL SYLLABLE RI
  		0xB9C8 == code || // Lo       HANGUL SYLLABLE MA
  		0xB9E4 == code || // Lo       HANGUL SYLLABLE MAE
  		0xBA00 == code || // Lo       HANGUL SYLLABLE MYA
  		0xBA1C == code || // Lo       HANGUL SYLLABLE MYAE
  		0xBA38 == code || // Lo       HANGUL SYLLABLE MEO
  		0xBA54 == code || // Lo       HANGUL SYLLABLE ME
  		0xBA70 == code || // Lo       HANGUL SYLLABLE MYEO
  		0xBA8C == code || // Lo       HANGUL SYLLABLE MYE
  		0xBAA8 == code || // Lo       HANGUL SYLLABLE MO
  		0xBAC4 == code || // Lo       HANGUL SYLLABLE MWA
  		0xBAE0 == code || // Lo       HANGUL SYLLABLE MWAE
  		0xBAFC == code || // Lo       HANGUL SYLLABLE MOE
  		0xBB18 == code || // Lo       HANGUL SYLLABLE MYO
  		0xBB34 == code || // Lo       HANGUL SYLLABLE MU
  		0xBB50 == code || // Lo       HANGUL SYLLABLE MWEO
  		0xBB6C == code || // Lo       HANGUL SYLLABLE MWE
  		0xBB88 == code || // Lo       HANGUL SYLLABLE MWI
  		0xBBA4 == code || // Lo       HANGUL SYLLABLE MYU
  		0xBBC0 == code || // Lo       HANGUL SYLLABLE MEU
  		0xBBDC == code || // Lo       HANGUL SYLLABLE MYI
  		0xBBF8 == code || // Lo       HANGUL SYLLABLE MI
  		0xBC14 == code || // Lo       HANGUL SYLLABLE BA
  		0xBC30 == code || // Lo       HANGUL SYLLABLE BAE
  		0xBC4C == code || // Lo       HANGUL SYLLABLE BYA
  		0xBC68 == code || // Lo       HANGUL SYLLABLE BYAE
  		0xBC84 == code || // Lo       HANGUL SYLLABLE BEO
  		0xBCA0 == code || // Lo       HANGUL SYLLABLE BE
  		0xBCBC == code || // Lo       HANGUL SYLLABLE BYEO
  		0xBCD8 == code || // Lo       HANGUL SYLLABLE BYE
  		0xBCF4 == code || // Lo       HANGUL SYLLABLE BO
  		0xBD10 == code || // Lo       HANGUL SYLLABLE BWA
  		0xBD2C == code || // Lo       HANGUL SYLLABLE BWAE
  		0xBD48 == code || // Lo       HANGUL SYLLABLE BOE
  		0xBD64 == code || // Lo       HANGUL SYLLABLE BYO
  		0xBD80 == code || // Lo       HANGUL SYLLABLE BU
  		0xBD9C == code || // Lo       HANGUL SYLLABLE BWEO
  		0xBDB8 == code || // Lo       HANGUL SYLLABLE BWE
  		0xBDD4 == code || // Lo       HANGUL SYLLABLE BWI
  		0xBDF0 == code || // Lo       HANGUL SYLLABLE BYU
  		0xBE0C == code || // Lo       HANGUL SYLLABLE BEU
  		0xBE28 == code || // Lo       HANGUL SYLLABLE BYI
  		0xBE44 == code || // Lo       HANGUL SYLLABLE BI
  		0xBE60 == code || // Lo       HANGUL SYLLABLE BBA
  		0xBE7C == code || // Lo       HANGUL SYLLABLE BBAE
  		0xBE98 == code || // Lo       HANGUL SYLLABLE BBYA
  		0xBEB4 == code || // Lo       HANGUL SYLLABLE BBYAE
  		0xBED0 == code || // Lo       HANGUL SYLLABLE BBEO
  		0xBEEC == code || // Lo       HANGUL SYLLABLE BBE
  		0xBF08 == code || // Lo       HANGUL SYLLABLE BBYEO
  		0xBF24 == code || // Lo       HANGUL SYLLABLE BBYE
  		0xBF40 == code || // Lo       HANGUL SYLLABLE BBO
  		0xBF5C == code || // Lo       HANGUL SYLLABLE BBWA
  		0xBF78 == code || // Lo       HANGUL SYLLABLE BBWAE
  		0xBF94 == code || // Lo       HANGUL SYLLABLE BBOE
  		0xBFB0 == code || // Lo       HANGUL SYLLABLE BBYO
  		0xBFCC == code || // Lo       HANGUL SYLLABLE BBU
  		0xBFE8 == code || // Lo       HANGUL SYLLABLE BBWEO
  		0xC004 == code || // Lo       HANGUL SYLLABLE BBWE
  		0xC020 == code || // Lo       HANGUL SYLLABLE BBWI
  		0xC03C == code || // Lo       HANGUL SYLLABLE BBYU
  		0xC058 == code || // Lo       HANGUL SYLLABLE BBEU
  		0xC074 == code || // Lo       HANGUL SYLLABLE BBYI
  		0xC090 == code || // Lo       HANGUL SYLLABLE BBI
  		0xC0AC == code || // Lo       HANGUL SYLLABLE SA
  		0xC0C8 == code || // Lo       HANGUL SYLLABLE SAE
  		0xC0E4 == code || // Lo       HANGUL SYLLABLE SYA
  		0xC100 == code || // Lo       HANGUL SYLLABLE SYAE
  		0xC11C == code || // Lo       HANGUL SYLLABLE SEO
  		0xC138 == code || // Lo       HANGUL SYLLABLE SE
  		0xC154 == code || // Lo       HANGUL SYLLABLE SYEO
  		0xC170 == code || // Lo       HANGUL SYLLABLE SYE
  		0xC18C == code || // Lo       HANGUL SYLLABLE SO
  		0xC1A8 == code || // Lo       HANGUL SYLLABLE SWA
  		0xC1C4 == code || // Lo       HANGUL SYLLABLE SWAE
  		0xC1E0 == code || // Lo       HANGUL SYLLABLE SOE
  		0xC1FC == code || // Lo       HANGUL SYLLABLE SYO
  		0xC218 == code || // Lo       HANGUL SYLLABLE SU
  		0xC234 == code || // Lo       HANGUL SYLLABLE SWEO
  		0xC250 == code || // Lo       HANGUL SYLLABLE SWE
  		0xC26C == code || // Lo       HANGUL SYLLABLE SWI
  		0xC288 == code || // Lo       HANGUL SYLLABLE SYU
  		0xC2A4 == code || // Lo       HANGUL SYLLABLE SEU
  		0xC2C0 == code || // Lo       HANGUL SYLLABLE SYI
  		0xC2DC == code || // Lo       HANGUL SYLLABLE SI
  		0xC2F8 == code || // Lo       HANGUL SYLLABLE SSA
  		0xC314 == code || // Lo       HANGUL SYLLABLE SSAE
  		0xC330 == code || // Lo       HANGUL SYLLABLE SSYA
  		0xC34C == code || // Lo       HANGUL SYLLABLE SSYAE
  		0xC368 == code || // Lo       HANGUL SYLLABLE SSEO
  		0xC384 == code || // Lo       HANGUL SYLLABLE SSE
  		0xC3A0 == code || // Lo       HANGUL SYLLABLE SSYEO
  		0xC3BC == code || // Lo       HANGUL SYLLABLE SSYE
  		0xC3D8 == code || // Lo       HANGUL SYLLABLE SSO
  		0xC3F4 == code || // Lo       HANGUL SYLLABLE SSWA
  		0xC410 == code || // Lo       HANGUL SYLLABLE SSWAE
  		0xC42C == code || // Lo       HANGUL SYLLABLE SSOE
  		0xC448 == code || // Lo       HANGUL SYLLABLE SSYO
  		0xC464 == code || // Lo       HANGUL SYLLABLE SSU
  		0xC480 == code || // Lo       HANGUL SYLLABLE SSWEO
  		0xC49C == code || // Lo       HANGUL SYLLABLE SSWE
  		0xC4B8 == code || // Lo       HANGUL SYLLABLE SSWI
  		0xC4D4 == code || // Lo       HANGUL SYLLABLE SSYU
  		0xC4F0 == code || // Lo       HANGUL SYLLABLE SSEU
  		0xC50C == code || // Lo       HANGUL SYLLABLE SSYI
  		0xC528 == code || // Lo       HANGUL SYLLABLE SSI
  		0xC544 == code || // Lo       HANGUL SYLLABLE A
  		0xC560 == code || // Lo       HANGUL SYLLABLE AE
  		0xC57C == code || // Lo       HANGUL SYLLABLE YA
  		0xC598 == code || // Lo       HANGUL SYLLABLE YAE
  		0xC5B4 == code || // Lo       HANGUL SYLLABLE EO
  		0xC5D0 == code || // Lo       HANGUL SYLLABLE E
  		0xC5EC == code || // Lo       HANGUL SYLLABLE YEO
  		0xC608 == code || // Lo       HANGUL SYLLABLE YE
  		0xC624 == code || // Lo       HANGUL SYLLABLE O
  		0xC640 == code || // Lo       HANGUL SYLLABLE WA
  		0xC65C == code || // Lo       HANGUL SYLLABLE WAE
  		0xC678 == code || // Lo       HANGUL SYLLABLE OE
  		0xC694 == code || // Lo       HANGUL SYLLABLE YO
  		0xC6B0 == code || // Lo       HANGUL SYLLABLE U
  		0xC6CC == code || // Lo       HANGUL SYLLABLE WEO
  		0xC6E8 == code || // Lo       HANGUL SYLLABLE WE
  		0xC704 == code || // Lo       HANGUL SYLLABLE WI
  		0xC720 == code || // Lo       HANGUL SYLLABLE YU
  		0xC73C == code || // Lo       HANGUL SYLLABLE EU
  		0xC758 == code || // Lo       HANGUL SYLLABLE YI
  		0xC774 == code || // Lo       HANGUL SYLLABLE I
  		0xC790 == code || // Lo       HANGUL SYLLABLE JA
  		0xC7AC == code || // Lo       HANGUL SYLLABLE JAE
  		0xC7C8 == code || // Lo       HANGUL SYLLABLE JYA
  		0xC7E4 == code || // Lo       HANGUL SYLLABLE JYAE
  		0xC800 == code || // Lo       HANGUL SYLLABLE JEO
  		0xC81C == code || // Lo       HANGUL SYLLABLE JE
  		0xC838 == code || // Lo       HANGUL SYLLABLE JYEO
  		0xC854 == code || // Lo       HANGUL SYLLABLE JYE
  		0xC870 == code || // Lo       HANGUL SYLLABLE JO
  		0xC88C == code || // Lo       HANGUL SYLLABLE JWA
  		0xC8A8 == code || // Lo       HANGUL SYLLABLE JWAE
  		0xC8C4 == code || // Lo       HANGUL SYLLABLE JOE
  		0xC8E0 == code || // Lo       HANGUL SYLLABLE JYO
  		0xC8FC == code || // Lo       HANGUL SYLLABLE JU
  		0xC918 == code || // Lo       HANGUL SYLLABLE JWEO
  		0xC934 == code || // Lo       HANGUL SYLLABLE JWE
  		0xC950 == code || // Lo       HANGUL SYLLABLE JWI
  		0xC96C == code || // Lo       HANGUL SYLLABLE JYU
  		0xC988 == code || // Lo       HANGUL SYLLABLE JEU
  		0xC9A4 == code || // Lo       HANGUL SYLLABLE JYI
  		0xC9C0 == code || // Lo       HANGUL SYLLABLE JI
  		0xC9DC == code || // Lo       HANGUL SYLLABLE JJA
  		0xC9F8 == code || // Lo       HANGUL SYLLABLE JJAE
  		0xCA14 == code || // Lo       HANGUL SYLLABLE JJYA
  		0xCA30 == code || // Lo       HANGUL SYLLABLE JJYAE
  		0xCA4C == code || // Lo       HANGUL SYLLABLE JJEO
  		0xCA68 == code || // Lo       HANGUL SYLLABLE JJE
  		0xCA84 == code || // Lo       HANGUL SYLLABLE JJYEO
  		0xCAA0 == code || // Lo       HANGUL SYLLABLE JJYE
  		0xCABC == code || // Lo       HANGUL SYLLABLE JJO
  		0xCAD8 == code || // Lo       HANGUL SYLLABLE JJWA
  		0xCAF4 == code || // Lo       HANGUL SYLLABLE JJWAE
  		0xCB10 == code || // Lo       HANGUL SYLLABLE JJOE
  		0xCB2C == code || // Lo       HANGUL SYLLABLE JJYO
  		0xCB48 == code || // Lo       HANGUL SYLLABLE JJU
  		0xCB64 == code || // Lo       HANGUL SYLLABLE JJWEO
  		0xCB80 == code || // Lo       HANGUL SYLLABLE JJWE
  		0xCB9C == code || // Lo       HANGUL SYLLABLE JJWI
  		0xCBB8 == code || // Lo       HANGUL SYLLABLE JJYU
  		0xCBD4 == code || // Lo       HANGUL SYLLABLE JJEU
  		0xCBF0 == code || // Lo       HANGUL SYLLABLE JJYI
  		0xCC0C == code || // Lo       HANGUL SYLLABLE JJI
  		0xCC28 == code || // Lo       HANGUL SYLLABLE CA
  		0xCC44 == code || // Lo       HANGUL SYLLABLE CAE
  		0xCC60 == code || // Lo       HANGUL SYLLABLE CYA
  		0xCC7C == code || // Lo       HANGUL SYLLABLE CYAE
  		0xCC98 == code || // Lo       HANGUL SYLLABLE CEO
  		0xCCB4 == code || // Lo       HANGUL SYLLABLE CE
  		0xCCD0 == code || // Lo       HANGUL SYLLABLE CYEO
  		0xCCEC == code || // Lo       HANGUL SYLLABLE CYE
  		0xCD08 == code || // Lo       HANGUL SYLLABLE CO
  		0xCD24 == code || // Lo       HANGUL SYLLABLE CWA
  		0xCD40 == code || // Lo       HANGUL SYLLABLE CWAE
  		0xCD5C == code || // Lo       HANGUL SYLLABLE COE
  		0xCD78 == code || // Lo       HANGUL SYLLABLE CYO
  		0xCD94 == code || // Lo       HANGUL SYLLABLE CU
  		0xCDB0 == code || // Lo       HANGUL SYLLABLE CWEO
  		0xCDCC == code || // Lo       HANGUL SYLLABLE CWE
  		0xCDE8 == code || // Lo       HANGUL SYLLABLE CWI
  		0xCE04 == code || // Lo       HANGUL SYLLABLE CYU
  		0xCE20 == code || // Lo       HANGUL SYLLABLE CEU
  		0xCE3C == code || // Lo       HANGUL SYLLABLE CYI
  		0xCE58 == code || // Lo       HANGUL SYLLABLE CI
  		0xCE74 == code || // Lo       HANGUL SYLLABLE KA
  		0xCE90 == code || // Lo       HANGUL SYLLABLE KAE
  		0xCEAC == code || // Lo       HANGUL SYLLABLE KYA
  		0xCEC8 == code || // Lo       HANGUL SYLLABLE KYAE
  		0xCEE4 == code || // Lo       HANGUL SYLLABLE KEO
  		0xCF00 == code || // Lo       HANGUL SYLLABLE KE
  		0xCF1C == code || // Lo       HANGUL SYLLABLE KYEO
  		0xCF38 == code || // Lo       HANGUL SYLLABLE KYE
  		0xCF54 == code || // Lo       HANGUL SYLLABLE KO
  		0xCF70 == code || // Lo       HANGUL SYLLABLE KWA
  		0xCF8C == code || // Lo       HANGUL SYLLABLE KWAE
  		0xCFA8 == code || // Lo       HANGUL SYLLABLE KOE
  		0xCFC4 == code || // Lo       HANGUL SYLLABLE KYO
  		0xCFE0 == code || // Lo       HANGUL SYLLABLE KU
  		0xCFFC == code || // Lo       HANGUL SYLLABLE KWEO
  		0xD018 == code || // Lo       HANGUL SYLLABLE KWE
  		0xD034 == code || // Lo       HANGUL SYLLABLE KWI
  		0xD050 == code || // Lo       HANGUL SYLLABLE KYU
  		0xD06C == code || // Lo       HANGUL SYLLABLE KEU
  		0xD088 == code || // Lo       HANGUL SYLLABLE KYI
  		0xD0A4 == code || // Lo       HANGUL SYLLABLE KI
  		0xD0C0 == code || // Lo       HANGUL SYLLABLE TA
  		0xD0DC == code || // Lo       HANGUL SYLLABLE TAE
  		0xD0F8 == code || // Lo       HANGUL SYLLABLE TYA
  		0xD114 == code || // Lo       HANGUL SYLLABLE TYAE
  		0xD130 == code || // Lo       HANGUL SYLLABLE TEO
  		0xD14C == code || // Lo       HANGUL SYLLABLE TE
  		0xD168 == code || // Lo       HANGUL SYLLABLE TYEO
  		0xD184 == code || // Lo       HANGUL SYLLABLE TYE
  		0xD1A0 == code || // Lo       HANGUL SYLLABLE TO
  		0xD1BC == code || // Lo       HANGUL SYLLABLE TWA
  		0xD1D8 == code || // Lo       HANGUL SYLLABLE TWAE
  		0xD1F4 == code || // Lo       HANGUL SYLLABLE TOE
  		0xD210 == code || // Lo       HANGUL SYLLABLE TYO
  		0xD22C == code || // Lo       HANGUL SYLLABLE TU
  		0xD248 == code || // Lo       HANGUL SYLLABLE TWEO
  		0xD264 == code || // Lo       HANGUL SYLLABLE TWE
  		0xD280 == code || // Lo       HANGUL SYLLABLE TWI
  		0xD29C == code || // Lo       HANGUL SYLLABLE TYU
  		0xD2B8 == code || // Lo       HANGUL SYLLABLE TEU
  		0xD2D4 == code || // Lo       HANGUL SYLLABLE TYI
  		0xD2F0 == code || // Lo       HANGUL SYLLABLE TI
  		0xD30C == code || // Lo       HANGUL SYLLABLE PA
  		0xD328 == code || // Lo       HANGUL SYLLABLE PAE
  		0xD344 == code || // Lo       HANGUL SYLLABLE PYA
  		0xD360 == code || // Lo       HANGUL SYLLABLE PYAE
  		0xD37C == code || // Lo       HANGUL SYLLABLE PEO
  		0xD398 == code || // Lo       HANGUL SYLLABLE PE
  		0xD3B4 == code || // Lo       HANGUL SYLLABLE PYEO
  		0xD3D0 == code || // Lo       HANGUL SYLLABLE PYE
  		0xD3EC == code || // Lo       HANGUL SYLLABLE PO
  		0xD408 == code || // Lo       HANGUL SYLLABLE PWA
  		0xD424 == code || // Lo       HANGUL SYLLABLE PWAE
  		0xD440 == code || // Lo       HANGUL SYLLABLE POE
  		0xD45C == code || // Lo       HANGUL SYLLABLE PYO
  		0xD478 == code || // Lo       HANGUL SYLLABLE PU
  		0xD494 == code || // Lo       HANGUL SYLLABLE PWEO
  		0xD4B0 == code || // Lo       HANGUL SYLLABLE PWE
  		0xD4CC == code || // Lo       HANGUL SYLLABLE PWI
  		0xD4E8 == code || // Lo       HANGUL SYLLABLE PYU
  		0xD504 == code || // Lo       HANGUL SYLLABLE PEU
  		0xD520 == code || // Lo       HANGUL SYLLABLE PYI
  		0xD53C == code || // Lo       HANGUL SYLLABLE PI
  		0xD558 == code || // Lo       HANGUL SYLLABLE HA
  		0xD574 == code || // Lo       HANGUL SYLLABLE HAE
  		0xD590 == code || // Lo       HANGUL SYLLABLE HYA
  		0xD5AC == code || // Lo       HANGUL SYLLABLE HYAE
  		0xD5C8 == code || // Lo       HANGUL SYLLABLE HEO
  		0xD5E4 == code || // Lo       HANGUL SYLLABLE HE
  		0xD600 == code || // Lo       HANGUL SYLLABLE HYEO
  		0xD61C == code || // Lo       HANGUL SYLLABLE HYE
  		0xD638 == code || // Lo       HANGUL SYLLABLE HO
  		0xD654 == code || // Lo       HANGUL SYLLABLE HWA
  		0xD670 == code || // Lo       HANGUL SYLLABLE HWAE
  		0xD68C == code || // Lo       HANGUL SYLLABLE HOE
  		0xD6A8 == code || // Lo       HANGUL SYLLABLE HYO
  		0xD6C4 == code || // Lo       HANGUL SYLLABLE HU
  		0xD6E0 == code || // Lo       HANGUL SYLLABLE HWEO
  		0xD6FC == code || // Lo       HANGUL SYLLABLE HWE
  		0xD718 == code || // Lo       HANGUL SYLLABLE HWI
  		0xD734 == code || // Lo       HANGUL SYLLABLE HYU
  		0xD750 == code || // Lo       HANGUL SYLLABLE HEU
  		0xD76C == code || // Lo       HANGUL SYLLABLE HYI
  		0xD788 == code // Lo       HANGUL SYLLABLE HI
  		){
  			return LV;
  		}
  		
  		if(
  		(0xAC01 <= code && code <= 0xAC1B) || // Lo  [27] HANGUL SYLLABLE GAG..HANGUL SYLLABLE GAH
  		(0xAC1D <= code && code <= 0xAC37) || // Lo  [27] HANGUL SYLLABLE GAEG..HANGUL SYLLABLE GAEH
  		(0xAC39 <= code && code <= 0xAC53) || // Lo  [27] HANGUL SYLLABLE GYAG..HANGUL SYLLABLE GYAH
  		(0xAC55 <= code && code <= 0xAC6F) || // Lo  [27] HANGUL SYLLABLE GYAEG..HANGUL SYLLABLE GYAEH
  		(0xAC71 <= code && code <= 0xAC8B) || // Lo  [27] HANGUL SYLLABLE GEOG..HANGUL SYLLABLE GEOH
  		(0xAC8D <= code && code <= 0xACA7) || // Lo  [27] HANGUL SYLLABLE GEG..HANGUL SYLLABLE GEH
  		(0xACA9 <= code && code <= 0xACC3) || // Lo  [27] HANGUL SYLLABLE GYEOG..HANGUL SYLLABLE GYEOH
  		(0xACC5 <= code && code <= 0xACDF) || // Lo  [27] HANGUL SYLLABLE GYEG..HANGUL SYLLABLE GYEH
  		(0xACE1 <= code && code <= 0xACFB) || // Lo  [27] HANGUL SYLLABLE GOG..HANGUL SYLLABLE GOH
  		(0xACFD <= code && code <= 0xAD17) || // Lo  [27] HANGUL SYLLABLE GWAG..HANGUL SYLLABLE GWAH
  		(0xAD19 <= code && code <= 0xAD33) || // Lo  [27] HANGUL SYLLABLE GWAEG..HANGUL SYLLABLE GWAEH
  		(0xAD35 <= code && code <= 0xAD4F) || // Lo  [27] HANGUL SYLLABLE GOEG..HANGUL SYLLABLE GOEH
  		(0xAD51 <= code && code <= 0xAD6B) || // Lo  [27] HANGUL SYLLABLE GYOG..HANGUL SYLLABLE GYOH
  		(0xAD6D <= code && code <= 0xAD87) || // Lo  [27] HANGUL SYLLABLE GUG..HANGUL SYLLABLE GUH
  		(0xAD89 <= code && code <= 0xADA3) || // Lo  [27] HANGUL SYLLABLE GWEOG..HANGUL SYLLABLE GWEOH
  		(0xADA5 <= code && code <= 0xADBF) || // Lo  [27] HANGUL SYLLABLE GWEG..HANGUL SYLLABLE GWEH
  		(0xADC1 <= code && code <= 0xADDB) || // Lo  [27] HANGUL SYLLABLE GWIG..HANGUL SYLLABLE GWIH
  		(0xADDD <= code && code <= 0xADF7) || // Lo  [27] HANGUL SYLLABLE GYUG..HANGUL SYLLABLE GYUH
  		(0xADF9 <= code && code <= 0xAE13) || // Lo  [27] HANGUL SYLLABLE GEUG..HANGUL SYLLABLE GEUH
  		(0xAE15 <= code && code <= 0xAE2F) || // Lo  [27] HANGUL SYLLABLE GYIG..HANGUL SYLLABLE GYIH
  		(0xAE31 <= code && code <= 0xAE4B) || // Lo  [27] HANGUL SYLLABLE GIG..HANGUL SYLLABLE GIH
  		(0xAE4D <= code && code <= 0xAE67) || // Lo  [27] HANGUL SYLLABLE GGAG..HANGUL SYLLABLE GGAH
  		(0xAE69 <= code && code <= 0xAE83) || // Lo  [27] HANGUL SYLLABLE GGAEG..HANGUL SYLLABLE GGAEH
  		(0xAE85 <= code && code <= 0xAE9F) || // Lo  [27] HANGUL SYLLABLE GGYAG..HANGUL SYLLABLE GGYAH
  		(0xAEA1 <= code && code <= 0xAEBB) || // Lo  [27] HANGUL SYLLABLE GGYAEG..HANGUL SYLLABLE GGYAEH
  		(0xAEBD <= code && code <= 0xAED7) || // Lo  [27] HANGUL SYLLABLE GGEOG..HANGUL SYLLABLE GGEOH
  		(0xAED9 <= code && code <= 0xAEF3) || // Lo  [27] HANGUL SYLLABLE GGEG..HANGUL SYLLABLE GGEH
  		(0xAEF5 <= code && code <= 0xAF0F) || // Lo  [27] HANGUL SYLLABLE GGYEOG..HANGUL SYLLABLE GGYEOH
  		(0xAF11 <= code && code <= 0xAF2B) || // Lo  [27] HANGUL SYLLABLE GGYEG..HANGUL SYLLABLE GGYEH
  		(0xAF2D <= code && code <= 0xAF47) || // Lo  [27] HANGUL SYLLABLE GGOG..HANGUL SYLLABLE GGOH
  		(0xAF49 <= code && code <= 0xAF63) || // Lo  [27] HANGUL SYLLABLE GGWAG..HANGUL SYLLABLE GGWAH
  		(0xAF65 <= code && code <= 0xAF7F) || // Lo  [27] HANGUL SYLLABLE GGWAEG..HANGUL SYLLABLE GGWAEH
  		(0xAF81 <= code && code <= 0xAF9B) || // Lo  [27] HANGUL SYLLABLE GGOEG..HANGUL SYLLABLE GGOEH
  		(0xAF9D <= code && code <= 0xAFB7) || // Lo  [27] HANGUL SYLLABLE GGYOG..HANGUL SYLLABLE GGYOH
  		(0xAFB9 <= code && code <= 0xAFD3) || // Lo  [27] HANGUL SYLLABLE GGUG..HANGUL SYLLABLE GGUH
  		(0xAFD5 <= code && code <= 0xAFEF) || // Lo  [27] HANGUL SYLLABLE GGWEOG..HANGUL SYLLABLE GGWEOH
  		(0xAFF1 <= code && code <= 0xB00B) || // Lo  [27] HANGUL SYLLABLE GGWEG..HANGUL SYLLABLE GGWEH
  		(0xB00D <= code && code <= 0xB027) || // Lo  [27] HANGUL SYLLABLE GGWIG..HANGUL SYLLABLE GGWIH
  		(0xB029 <= code && code <= 0xB043) || // Lo  [27] HANGUL SYLLABLE GGYUG..HANGUL SYLLABLE GGYUH
  		(0xB045 <= code && code <= 0xB05F) || // Lo  [27] HANGUL SYLLABLE GGEUG..HANGUL SYLLABLE GGEUH
  		(0xB061 <= code && code <= 0xB07B) || // Lo  [27] HANGUL SYLLABLE GGYIG..HANGUL SYLLABLE GGYIH
  		(0xB07D <= code && code <= 0xB097) || // Lo  [27] HANGUL SYLLABLE GGIG..HANGUL SYLLABLE GGIH
  		(0xB099 <= code && code <= 0xB0B3) || // Lo  [27] HANGUL SYLLABLE NAG..HANGUL SYLLABLE NAH
  		(0xB0B5 <= code && code <= 0xB0CF) || // Lo  [27] HANGUL SYLLABLE NAEG..HANGUL SYLLABLE NAEH
  		(0xB0D1 <= code && code <= 0xB0EB) || // Lo  [27] HANGUL SYLLABLE NYAG..HANGUL SYLLABLE NYAH
  		(0xB0ED <= code && code <= 0xB107) || // Lo  [27] HANGUL SYLLABLE NYAEG..HANGUL SYLLABLE NYAEH
  		(0xB109 <= code && code <= 0xB123) || // Lo  [27] HANGUL SYLLABLE NEOG..HANGUL SYLLABLE NEOH
  		(0xB125 <= code && code <= 0xB13F) || // Lo  [27] HANGUL SYLLABLE NEG..HANGUL SYLLABLE NEH
  		(0xB141 <= code && code <= 0xB15B) || // Lo  [27] HANGUL SYLLABLE NYEOG..HANGUL SYLLABLE NYEOH
  		(0xB15D <= code && code <= 0xB177) || // Lo  [27] HANGUL SYLLABLE NYEG..HANGUL SYLLABLE NYEH
  		(0xB179 <= code && code <= 0xB193) || // Lo  [27] HANGUL SYLLABLE NOG..HANGUL SYLLABLE NOH
  		(0xB195 <= code && code <= 0xB1AF) || // Lo  [27] HANGUL SYLLABLE NWAG..HANGUL SYLLABLE NWAH
  		(0xB1B1 <= code && code <= 0xB1CB) || // Lo  [27] HANGUL SYLLABLE NWAEG..HANGUL SYLLABLE NWAEH
  		(0xB1CD <= code && code <= 0xB1E7) || // Lo  [27] HANGUL SYLLABLE NOEG..HANGUL SYLLABLE NOEH
  		(0xB1E9 <= code && code <= 0xB203) || // Lo  [27] HANGUL SYLLABLE NYOG..HANGUL SYLLABLE NYOH
  		(0xB205 <= code && code <= 0xB21F) || // Lo  [27] HANGUL SYLLABLE NUG..HANGUL SYLLABLE NUH
  		(0xB221 <= code && code <= 0xB23B) || // Lo  [27] HANGUL SYLLABLE NWEOG..HANGUL SYLLABLE NWEOH
  		(0xB23D <= code && code <= 0xB257) || // Lo  [27] HANGUL SYLLABLE NWEG..HANGUL SYLLABLE NWEH
  		(0xB259 <= code && code <= 0xB273) || // Lo  [27] HANGUL SYLLABLE NWIG..HANGUL SYLLABLE NWIH
  		(0xB275 <= code && code <= 0xB28F) || // Lo  [27] HANGUL SYLLABLE NYUG..HANGUL SYLLABLE NYUH
  		(0xB291 <= code && code <= 0xB2AB) || // Lo  [27] HANGUL SYLLABLE NEUG..HANGUL SYLLABLE NEUH
  		(0xB2AD <= code && code <= 0xB2C7) || // Lo  [27] HANGUL SYLLABLE NYIG..HANGUL SYLLABLE NYIH
  		(0xB2C9 <= code && code <= 0xB2E3) || // Lo  [27] HANGUL SYLLABLE NIG..HANGUL SYLLABLE NIH
  		(0xB2E5 <= code && code <= 0xB2FF) || // Lo  [27] HANGUL SYLLABLE DAG..HANGUL SYLLABLE DAH
  		(0xB301 <= code && code <= 0xB31B) || // Lo  [27] HANGUL SYLLABLE DAEG..HANGUL SYLLABLE DAEH
  		(0xB31D <= code && code <= 0xB337) || // Lo  [27] HANGUL SYLLABLE DYAG..HANGUL SYLLABLE DYAH
  		(0xB339 <= code && code <= 0xB353) || // Lo  [27] HANGUL SYLLABLE DYAEG..HANGUL SYLLABLE DYAEH
  		(0xB355 <= code && code <= 0xB36F) || // Lo  [27] HANGUL SYLLABLE DEOG..HANGUL SYLLABLE DEOH
  		(0xB371 <= code && code <= 0xB38B) || // Lo  [27] HANGUL SYLLABLE DEG..HANGUL SYLLABLE DEH
  		(0xB38D <= code && code <= 0xB3A7) || // Lo  [27] HANGUL SYLLABLE DYEOG..HANGUL SYLLABLE DYEOH
  		(0xB3A9 <= code && code <= 0xB3C3) || // Lo  [27] HANGUL SYLLABLE DYEG..HANGUL SYLLABLE DYEH
  		(0xB3C5 <= code && code <= 0xB3DF) || // Lo  [27] HANGUL SYLLABLE DOG..HANGUL SYLLABLE DOH
  		(0xB3E1 <= code && code <= 0xB3FB) || // Lo  [27] HANGUL SYLLABLE DWAG..HANGUL SYLLABLE DWAH
  		(0xB3FD <= code && code <= 0xB417) || // Lo  [27] HANGUL SYLLABLE DWAEG..HANGUL SYLLABLE DWAEH
  		(0xB419 <= code && code <= 0xB433) || // Lo  [27] HANGUL SYLLABLE DOEG..HANGUL SYLLABLE DOEH
  		(0xB435 <= code && code <= 0xB44F) || // Lo  [27] HANGUL SYLLABLE DYOG..HANGUL SYLLABLE DYOH
  		(0xB451 <= code && code <= 0xB46B) || // Lo  [27] HANGUL SYLLABLE DUG..HANGUL SYLLABLE DUH
  		(0xB46D <= code && code <= 0xB487) || // Lo  [27] HANGUL SYLLABLE DWEOG..HANGUL SYLLABLE DWEOH
  		(0xB489 <= code && code <= 0xB4A3) || // Lo  [27] HANGUL SYLLABLE DWEG..HANGUL SYLLABLE DWEH
  		(0xB4A5 <= code && code <= 0xB4BF) || // Lo  [27] HANGUL SYLLABLE DWIG..HANGUL SYLLABLE DWIH
  		(0xB4C1 <= code && code <= 0xB4DB) || // Lo  [27] HANGUL SYLLABLE DYUG..HANGUL SYLLABLE DYUH
  		(0xB4DD <= code && code <= 0xB4F7) || // Lo  [27] HANGUL SYLLABLE DEUG..HANGUL SYLLABLE DEUH
  		(0xB4F9 <= code && code <= 0xB513) || // Lo  [27] HANGUL SYLLABLE DYIG..HANGUL SYLLABLE DYIH
  		(0xB515 <= code && code <= 0xB52F) || // Lo  [27] HANGUL SYLLABLE DIG..HANGUL SYLLABLE DIH
  		(0xB531 <= code && code <= 0xB54B) || // Lo  [27] HANGUL SYLLABLE DDAG..HANGUL SYLLABLE DDAH
  		(0xB54D <= code && code <= 0xB567) || // Lo  [27] HANGUL SYLLABLE DDAEG..HANGUL SYLLABLE DDAEH
  		(0xB569 <= code && code <= 0xB583) || // Lo  [27] HANGUL SYLLABLE DDYAG..HANGUL SYLLABLE DDYAH
  		(0xB585 <= code && code <= 0xB59F) || // Lo  [27] HANGUL SYLLABLE DDYAEG..HANGUL SYLLABLE DDYAEH
  		(0xB5A1 <= code && code <= 0xB5BB) || // Lo  [27] HANGUL SYLLABLE DDEOG..HANGUL SYLLABLE DDEOH
  		(0xB5BD <= code && code <= 0xB5D7) || // Lo  [27] HANGUL SYLLABLE DDEG..HANGUL SYLLABLE DDEH
  		(0xB5D9 <= code && code <= 0xB5F3) || // Lo  [27] HANGUL SYLLABLE DDYEOG..HANGUL SYLLABLE DDYEOH
  		(0xB5F5 <= code && code <= 0xB60F) || // Lo  [27] HANGUL SYLLABLE DDYEG..HANGUL SYLLABLE DDYEH
  		(0xB611 <= code && code <= 0xB62B) || // Lo  [27] HANGUL SYLLABLE DDOG..HANGUL SYLLABLE DDOH
  		(0xB62D <= code && code <= 0xB647) || // Lo  [27] HANGUL SYLLABLE DDWAG..HANGUL SYLLABLE DDWAH
  		(0xB649 <= code && code <= 0xB663) || // Lo  [27] HANGUL SYLLABLE DDWAEG..HANGUL SYLLABLE DDWAEH
  		(0xB665 <= code && code <= 0xB67F) || // Lo  [27] HANGUL SYLLABLE DDOEG..HANGUL SYLLABLE DDOEH
  		(0xB681 <= code && code <= 0xB69B) || // Lo  [27] HANGUL SYLLABLE DDYOG..HANGUL SYLLABLE DDYOH
  		(0xB69D <= code && code <= 0xB6B7) || // Lo  [27] HANGUL SYLLABLE DDUG..HANGUL SYLLABLE DDUH
  		(0xB6B9 <= code && code <= 0xB6D3) || // Lo  [27] HANGUL SYLLABLE DDWEOG..HANGUL SYLLABLE DDWEOH
  		(0xB6D5 <= code && code <= 0xB6EF) || // Lo  [27] HANGUL SYLLABLE DDWEG..HANGUL SYLLABLE DDWEH
  		(0xB6F1 <= code && code <= 0xB70B) || // Lo  [27] HANGUL SYLLABLE DDWIG..HANGUL SYLLABLE DDWIH
  		(0xB70D <= code && code <= 0xB727) || // Lo  [27] HANGUL SYLLABLE DDYUG..HANGUL SYLLABLE DDYUH
  		(0xB729 <= code && code <= 0xB743) || // Lo  [27] HANGUL SYLLABLE DDEUG..HANGUL SYLLABLE DDEUH
  		(0xB745 <= code && code <= 0xB75F) || // Lo  [27] HANGUL SYLLABLE DDYIG..HANGUL SYLLABLE DDYIH
  		(0xB761 <= code && code <= 0xB77B) || // Lo  [27] HANGUL SYLLABLE DDIG..HANGUL SYLLABLE DDIH
  		(0xB77D <= code && code <= 0xB797) || // Lo  [27] HANGUL SYLLABLE RAG..HANGUL SYLLABLE RAH
  		(0xB799 <= code && code <= 0xB7B3) || // Lo  [27] HANGUL SYLLABLE RAEG..HANGUL SYLLABLE RAEH
  		(0xB7B5 <= code && code <= 0xB7CF) || // Lo  [27] HANGUL SYLLABLE RYAG..HANGUL SYLLABLE RYAH
  		(0xB7D1 <= code && code <= 0xB7EB) || // Lo  [27] HANGUL SYLLABLE RYAEG..HANGUL SYLLABLE RYAEH
  		(0xB7ED <= code && code <= 0xB807) || // Lo  [27] HANGUL SYLLABLE REOG..HANGUL SYLLABLE REOH
  		(0xB809 <= code && code <= 0xB823) || // Lo  [27] HANGUL SYLLABLE REG..HANGUL SYLLABLE REH
  		(0xB825 <= code && code <= 0xB83F) || // Lo  [27] HANGUL SYLLABLE RYEOG..HANGUL SYLLABLE RYEOH
  		(0xB841 <= code && code <= 0xB85B) || // Lo  [27] HANGUL SYLLABLE RYEG..HANGUL SYLLABLE RYEH
  		(0xB85D <= code && code <= 0xB877) || // Lo  [27] HANGUL SYLLABLE ROG..HANGUL SYLLABLE ROH
  		(0xB879 <= code && code <= 0xB893) || // Lo  [27] HANGUL SYLLABLE RWAG..HANGUL SYLLABLE RWAH
  		(0xB895 <= code && code <= 0xB8AF) || // Lo  [27] HANGUL SYLLABLE RWAEG..HANGUL SYLLABLE RWAEH
  		(0xB8B1 <= code && code <= 0xB8CB) || // Lo  [27] HANGUL SYLLABLE ROEG..HANGUL SYLLABLE ROEH
  		(0xB8CD <= code && code <= 0xB8E7) || // Lo  [27] HANGUL SYLLABLE RYOG..HANGUL SYLLABLE RYOH
  		(0xB8E9 <= code && code <= 0xB903) || // Lo  [27] HANGUL SYLLABLE RUG..HANGUL SYLLABLE RUH
  		(0xB905 <= code && code <= 0xB91F) || // Lo  [27] HANGUL SYLLABLE RWEOG..HANGUL SYLLABLE RWEOH
  		(0xB921 <= code && code <= 0xB93B) || // Lo  [27] HANGUL SYLLABLE RWEG..HANGUL SYLLABLE RWEH
  		(0xB93D <= code && code <= 0xB957) || // Lo  [27] HANGUL SYLLABLE RWIG..HANGUL SYLLABLE RWIH
  		(0xB959 <= code && code <= 0xB973) || // Lo  [27] HANGUL SYLLABLE RYUG..HANGUL SYLLABLE RYUH
  		(0xB975 <= code && code <= 0xB98F) || // Lo  [27] HANGUL SYLLABLE REUG..HANGUL SYLLABLE REUH
  		(0xB991 <= code && code <= 0xB9AB) || // Lo  [27] HANGUL SYLLABLE RYIG..HANGUL SYLLABLE RYIH
  		(0xB9AD <= code && code <= 0xB9C7) || // Lo  [27] HANGUL SYLLABLE RIG..HANGUL SYLLABLE RIH
  		(0xB9C9 <= code && code <= 0xB9E3) || // Lo  [27] HANGUL SYLLABLE MAG..HANGUL SYLLABLE MAH
  		(0xB9E5 <= code && code <= 0xB9FF) || // Lo  [27] HANGUL SYLLABLE MAEG..HANGUL SYLLABLE MAEH
  		(0xBA01 <= code && code <= 0xBA1B) || // Lo  [27] HANGUL SYLLABLE MYAG..HANGUL SYLLABLE MYAH
  		(0xBA1D <= code && code <= 0xBA37) || // Lo  [27] HANGUL SYLLABLE MYAEG..HANGUL SYLLABLE MYAEH
  		(0xBA39 <= code && code <= 0xBA53) || // Lo  [27] HANGUL SYLLABLE MEOG..HANGUL SYLLABLE MEOH
  		(0xBA55 <= code && code <= 0xBA6F) || // Lo  [27] HANGUL SYLLABLE MEG..HANGUL SYLLABLE MEH
  		(0xBA71 <= code && code <= 0xBA8B) || // Lo  [27] HANGUL SYLLABLE MYEOG..HANGUL SYLLABLE MYEOH
  		(0xBA8D <= code && code <= 0xBAA7) || // Lo  [27] HANGUL SYLLABLE MYEG..HANGUL SYLLABLE MYEH
  		(0xBAA9 <= code && code <= 0xBAC3) || // Lo  [27] HANGUL SYLLABLE MOG..HANGUL SYLLABLE MOH
  		(0xBAC5 <= code && code <= 0xBADF) || // Lo  [27] HANGUL SYLLABLE MWAG..HANGUL SYLLABLE MWAH
  		(0xBAE1 <= code && code <= 0xBAFB) || // Lo  [27] HANGUL SYLLABLE MWAEG..HANGUL SYLLABLE MWAEH
  		(0xBAFD <= code && code <= 0xBB17) || // Lo  [27] HANGUL SYLLABLE MOEG..HANGUL SYLLABLE MOEH
  		(0xBB19 <= code && code <= 0xBB33) || // Lo  [27] HANGUL SYLLABLE MYOG..HANGUL SYLLABLE MYOH
  		(0xBB35 <= code && code <= 0xBB4F) || // Lo  [27] HANGUL SYLLABLE MUG..HANGUL SYLLABLE MUH
  		(0xBB51 <= code && code <= 0xBB6B) || // Lo  [27] HANGUL SYLLABLE MWEOG..HANGUL SYLLABLE MWEOH
  		(0xBB6D <= code && code <= 0xBB87) || // Lo  [27] HANGUL SYLLABLE MWEG..HANGUL SYLLABLE MWEH
  		(0xBB89 <= code && code <= 0xBBA3) || // Lo  [27] HANGUL SYLLABLE MWIG..HANGUL SYLLABLE MWIH
  		(0xBBA5 <= code && code <= 0xBBBF) || // Lo  [27] HANGUL SYLLABLE MYUG..HANGUL SYLLABLE MYUH
  		(0xBBC1 <= code && code <= 0xBBDB) || // Lo  [27] HANGUL SYLLABLE MEUG..HANGUL SYLLABLE MEUH
  		(0xBBDD <= code && code <= 0xBBF7) || // Lo  [27] HANGUL SYLLABLE MYIG..HANGUL SYLLABLE MYIH
  		(0xBBF9 <= code && code <= 0xBC13) || // Lo  [27] HANGUL SYLLABLE MIG..HANGUL SYLLABLE MIH
  		(0xBC15 <= code && code <= 0xBC2F) || // Lo  [27] HANGUL SYLLABLE BAG..HANGUL SYLLABLE BAH
  		(0xBC31 <= code && code <= 0xBC4B) || // Lo  [27] HANGUL SYLLABLE BAEG..HANGUL SYLLABLE BAEH
  		(0xBC4D <= code && code <= 0xBC67) || // Lo  [27] HANGUL SYLLABLE BYAG..HANGUL SYLLABLE BYAH
  		(0xBC69 <= code && code <= 0xBC83) || // Lo  [27] HANGUL SYLLABLE BYAEG..HANGUL SYLLABLE BYAEH
  		(0xBC85 <= code && code <= 0xBC9F) || // Lo  [27] HANGUL SYLLABLE BEOG..HANGUL SYLLABLE BEOH
  		(0xBCA1 <= code && code <= 0xBCBB) || // Lo  [27] HANGUL SYLLABLE BEG..HANGUL SYLLABLE BEH
  		(0xBCBD <= code && code <= 0xBCD7) || // Lo  [27] HANGUL SYLLABLE BYEOG..HANGUL SYLLABLE BYEOH
  		(0xBCD9 <= code && code <= 0xBCF3) || // Lo  [27] HANGUL SYLLABLE BYEG..HANGUL SYLLABLE BYEH
  		(0xBCF5 <= code && code <= 0xBD0F) || // Lo  [27] HANGUL SYLLABLE BOG..HANGUL SYLLABLE BOH
  		(0xBD11 <= code && code <= 0xBD2B) || // Lo  [27] HANGUL SYLLABLE BWAG..HANGUL SYLLABLE BWAH
  		(0xBD2D <= code && code <= 0xBD47) || // Lo  [27] HANGUL SYLLABLE BWAEG..HANGUL SYLLABLE BWAEH
  		(0xBD49 <= code && code <= 0xBD63) || // Lo  [27] HANGUL SYLLABLE BOEG..HANGUL SYLLABLE BOEH
  		(0xBD65 <= code && code <= 0xBD7F) || // Lo  [27] HANGUL SYLLABLE BYOG..HANGUL SYLLABLE BYOH
  		(0xBD81 <= code && code <= 0xBD9B) || // Lo  [27] HANGUL SYLLABLE BUG..HANGUL SYLLABLE BUH
  		(0xBD9D <= code && code <= 0xBDB7) || // Lo  [27] HANGUL SYLLABLE BWEOG..HANGUL SYLLABLE BWEOH
  		(0xBDB9 <= code && code <= 0xBDD3) || // Lo  [27] HANGUL SYLLABLE BWEG..HANGUL SYLLABLE BWEH
  		(0xBDD5 <= code && code <= 0xBDEF) || // Lo  [27] HANGUL SYLLABLE BWIG..HANGUL SYLLABLE BWIH
  		(0xBDF1 <= code && code <= 0xBE0B) || // Lo  [27] HANGUL SYLLABLE BYUG..HANGUL SYLLABLE BYUH
  		(0xBE0D <= code && code <= 0xBE27) || // Lo  [27] HANGUL SYLLABLE BEUG..HANGUL SYLLABLE BEUH
  		(0xBE29 <= code && code <= 0xBE43) || // Lo  [27] HANGUL SYLLABLE BYIG..HANGUL SYLLABLE BYIH
  		(0xBE45 <= code && code <= 0xBE5F) || // Lo  [27] HANGUL SYLLABLE BIG..HANGUL SYLLABLE BIH
  		(0xBE61 <= code && code <= 0xBE7B) || // Lo  [27] HANGUL SYLLABLE BBAG..HANGUL SYLLABLE BBAH
  		(0xBE7D <= code && code <= 0xBE97) || // Lo  [27] HANGUL SYLLABLE BBAEG..HANGUL SYLLABLE BBAEH
  		(0xBE99 <= code && code <= 0xBEB3) || // Lo  [27] HANGUL SYLLABLE BBYAG..HANGUL SYLLABLE BBYAH
  		(0xBEB5 <= code && code <= 0xBECF) || // Lo  [27] HANGUL SYLLABLE BBYAEG..HANGUL SYLLABLE BBYAEH
  		(0xBED1 <= code && code <= 0xBEEB) || // Lo  [27] HANGUL SYLLABLE BBEOG..HANGUL SYLLABLE BBEOH
  		(0xBEED <= code && code <= 0xBF07) || // Lo  [27] HANGUL SYLLABLE BBEG..HANGUL SYLLABLE BBEH
  		(0xBF09 <= code && code <= 0xBF23) || // Lo  [27] HANGUL SYLLABLE BBYEOG..HANGUL SYLLABLE BBYEOH
  		(0xBF25 <= code && code <= 0xBF3F) || // Lo  [27] HANGUL SYLLABLE BBYEG..HANGUL SYLLABLE BBYEH
  		(0xBF41 <= code && code <= 0xBF5B) || // Lo  [27] HANGUL SYLLABLE BBOG..HANGUL SYLLABLE BBOH
  		(0xBF5D <= code && code <= 0xBF77) || // Lo  [27] HANGUL SYLLABLE BBWAG..HANGUL SYLLABLE BBWAH
  		(0xBF79 <= code && code <= 0xBF93) || // Lo  [27] HANGUL SYLLABLE BBWAEG..HANGUL SYLLABLE BBWAEH
  		(0xBF95 <= code && code <= 0xBFAF) || // Lo  [27] HANGUL SYLLABLE BBOEG..HANGUL SYLLABLE BBOEH
  		(0xBFB1 <= code && code <= 0xBFCB) || // Lo  [27] HANGUL SYLLABLE BBYOG..HANGUL SYLLABLE BBYOH
  		(0xBFCD <= code && code <= 0xBFE7) || // Lo  [27] HANGUL SYLLABLE BBUG..HANGUL SYLLABLE BBUH
  		(0xBFE9 <= code && code <= 0xC003) || // Lo  [27] HANGUL SYLLABLE BBWEOG..HANGUL SYLLABLE BBWEOH
  		(0xC005 <= code && code <= 0xC01F) || // Lo  [27] HANGUL SYLLABLE BBWEG..HANGUL SYLLABLE BBWEH
  		(0xC021 <= code && code <= 0xC03B) || // Lo  [27] HANGUL SYLLABLE BBWIG..HANGUL SYLLABLE BBWIH
  		(0xC03D <= code && code <= 0xC057) || // Lo  [27] HANGUL SYLLABLE BBYUG..HANGUL SYLLABLE BBYUH
  		(0xC059 <= code && code <= 0xC073) || // Lo  [27] HANGUL SYLLABLE BBEUG..HANGUL SYLLABLE BBEUH
  		(0xC075 <= code && code <= 0xC08F) || // Lo  [27] HANGUL SYLLABLE BBYIG..HANGUL SYLLABLE BBYIH
  		(0xC091 <= code && code <= 0xC0AB) || // Lo  [27] HANGUL SYLLABLE BBIG..HANGUL SYLLABLE BBIH
  		(0xC0AD <= code && code <= 0xC0C7) || // Lo  [27] HANGUL SYLLABLE SAG..HANGUL SYLLABLE SAH
  		(0xC0C9 <= code && code <= 0xC0E3) || // Lo  [27] HANGUL SYLLABLE SAEG..HANGUL SYLLABLE SAEH
  		(0xC0E5 <= code && code <= 0xC0FF) || // Lo  [27] HANGUL SYLLABLE SYAG..HANGUL SYLLABLE SYAH
  		(0xC101 <= code && code <= 0xC11B) || // Lo  [27] HANGUL SYLLABLE SYAEG..HANGUL SYLLABLE SYAEH
  		(0xC11D <= code && code <= 0xC137) || // Lo  [27] HANGUL SYLLABLE SEOG..HANGUL SYLLABLE SEOH
  		(0xC139 <= code && code <= 0xC153) || // Lo  [27] HANGUL SYLLABLE SEG..HANGUL SYLLABLE SEH
  		(0xC155 <= code && code <= 0xC16F) || // Lo  [27] HANGUL SYLLABLE SYEOG..HANGUL SYLLABLE SYEOH
  		(0xC171 <= code && code <= 0xC18B) || // Lo  [27] HANGUL SYLLABLE SYEG..HANGUL SYLLABLE SYEH
  		(0xC18D <= code && code <= 0xC1A7) || // Lo  [27] HANGUL SYLLABLE SOG..HANGUL SYLLABLE SOH
  		(0xC1A9 <= code && code <= 0xC1C3) || // Lo  [27] HANGUL SYLLABLE SWAG..HANGUL SYLLABLE SWAH
  		(0xC1C5 <= code && code <= 0xC1DF) || // Lo  [27] HANGUL SYLLABLE SWAEG..HANGUL SYLLABLE SWAEH
  		(0xC1E1 <= code && code <= 0xC1FB) || // Lo  [27] HANGUL SYLLABLE SOEG..HANGUL SYLLABLE SOEH
  		(0xC1FD <= code && code <= 0xC217) || // Lo  [27] HANGUL SYLLABLE SYOG..HANGUL SYLLABLE SYOH
  		(0xC219 <= code && code <= 0xC233) || // Lo  [27] HANGUL SYLLABLE SUG..HANGUL SYLLABLE SUH
  		(0xC235 <= code && code <= 0xC24F) || // Lo  [27] HANGUL SYLLABLE SWEOG..HANGUL SYLLABLE SWEOH
  		(0xC251 <= code && code <= 0xC26B) || // Lo  [27] HANGUL SYLLABLE SWEG..HANGUL SYLLABLE SWEH
  		(0xC26D <= code && code <= 0xC287) || // Lo  [27] HANGUL SYLLABLE SWIG..HANGUL SYLLABLE SWIH
  		(0xC289 <= code && code <= 0xC2A3) || // Lo  [27] HANGUL SYLLABLE SYUG..HANGUL SYLLABLE SYUH
  		(0xC2A5 <= code && code <= 0xC2BF) || // Lo  [27] HANGUL SYLLABLE SEUG..HANGUL SYLLABLE SEUH
  		(0xC2C1 <= code && code <= 0xC2DB) || // Lo  [27] HANGUL SYLLABLE SYIG..HANGUL SYLLABLE SYIH
  		(0xC2DD <= code && code <= 0xC2F7) || // Lo  [27] HANGUL SYLLABLE SIG..HANGUL SYLLABLE SIH
  		(0xC2F9 <= code && code <= 0xC313) || // Lo  [27] HANGUL SYLLABLE SSAG..HANGUL SYLLABLE SSAH
  		(0xC315 <= code && code <= 0xC32F) || // Lo  [27] HANGUL SYLLABLE SSAEG..HANGUL SYLLABLE SSAEH
  		(0xC331 <= code && code <= 0xC34B) || // Lo  [27] HANGUL SYLLABLE SSYAG..HANGUL SYLLABLE SSYAH
  		(0xC34D <= code && code <= 0xC367) || // Lo  [27] HANGUL SYLLABLE SSYAEG..HANGUL SYLLABLE SSYAEH
  		(0xC369 <= code && code <= 0xC383) || // Lo  [27] HANGUL SYLLABLE SSEOG..HANGUL SYLLABLE SSEOH
  		(0xC385 <= code && code <= 0xC39F) || // Lo  [27] HANGUL SYLLABLE SSEG..HANGUL SYLLABLE SSEH
  		(0xC3A1 <= code && code <= 0xC3BB) || // Lo  [27] HANGUL SYLLABLE SSYEOG..HANGUL SYLLABLE SSYEOH
  		(0xC3BD <= code && code <= 0xC3D7) || // Lo  [27] HANGUL SYLLABLE SSYEG..HANGUL SYLLABLE SSYEH
  		(0xC3D9 <= code && code <= 0xC3F3) || // Lo  [27] HANGUL SYLLABLE SSOG..HANGUL SYLLABLE SSOH
  		(0xC3F5 <= code && code <= 0xC40F) || // Lo  [27] HANGUL SYLLABLE SSWAG..HANGUL SYLLABLE SSWAH
  		(0xC411 <= code && code <= 0xC42B) || // Lo  [27] HANGUL SYLLABLE SSWAEG..HANGUL SYLLABLE SSWAEH
  		(0xC42D <= code && code <= 0xC447) || // Lo  [27] HANGUL SYLLABLE SSOEG..HANGUL SYLLABLE SSOEH
  		(0xC449 <= code && code <= 0xC463) || // Lo  [27] HANGUL SYLLABLE SSYOG..HANGUL SYLLABLE SSYOH
  		(0xC465 <= code && code <= 0xC47F) || // Lo  [27] HANGUL SYLLABLE SSUG..HANGUL SYLLABLE SSUH
  		(0xC481 <= code && code <= 0xC49B) || // Lo  [27] HANGUL SYLLABLE SSWEOG..HANGUL SYLLABLE SSWEOH
  		(0xC49D <= code && code <= 0xC4B7) || // Lo  [27] HANGUL SYLLABLE SSWEG..HANGUL SYLLABLE SSWEH
  		(0xC4B9 <= code && code <= 0xC4D3) || // Lo  [27] HANGUL SYLLABLE SSWIG..HANGUL SYLLABLE SSWIH
  		(0xC4D5 <= code && code <= 0xC4EF) || // Lo  [27] HANGUL SYLLABLE SSYUG..HANGUL SYLLABLE SSYUH
  		(0xC4F1 <= code && code <= 0xC50B) || // Lo  [27] HANGUL SYLLABLE SSEUG..HANGUL SYLLABLE SSEUH
  		(0xC50D <= code && code <= 0xC527) || // Lo  [27] HANGUL SYLLABLE SSYIG..HANGUL SYLLABLE SSYIH
  		(0xC529 <= code && code <= 0xC543) || // Lo  [27] HANGUL SYLLABLE SSIG..HANGUL SYLLABLE SSIH
  		(0xC545 <= code && code <= 0xC55F) || // Lo  [27] HANGUL SYLLABLE AG..HANGUL SYLLABLE AH
  		(0xC561 <= code && code <= 0xC57B) || // Lo  [27] HANGUL SYLLABLE AEG..HANGUL SYLLABLE AEH
  		(0xC57D <= code && code <= 0xC597) || // Lo  [27] HANGUL SYLLABLE YAG..HANGUL SYLLABLE YAH
  		(0xC599 <= code && code <= 0xC5B3) || // Lo  [27] HANGUL SYLLABLE YAEG..HANGUL SYLLABLE YAEH
  		(0xC5B5 <= code && code <= 0xC5CF) || // Lo  [27] HANGUL SYLLABLE EOG..HANGUL SYLLABLE EOH
  		(0xC5D1 <= code && code <= 0xC5EB) || // Lo  [27] HANGUL SYLLABLE EG..HANGUL SYLLABLE EH
  		(0xC5ED <= code && code <= 0xC607) || // Lo  [27] HANGUL SYLLABLE YEOG..HANGUL SYLLABLE YEOH
  		(0xC609 <= code && code <= 0xC623) || // Lo  [27] HANGUL SYLLABLE YEG..HANGUL SYLLABLE YEH
  		(0xC625 <= code && code <= 0xC63F) || // Lo  [27] HANGUL SYLLABLE OG..HANGUL SYLLABLE OH
  		(0xC641 <= code && code <= 0xC65B) || // Lo  [27] HANGUL SYLLABLE WAG..HANGUL SYLLABLE WAH
  		(0xC65D <= code && code <= 0xC677) || // Lo  [27] HANGUL SYLLABLE WAEG..HANGUL SYLLABLE WAEH
  		(0xC679 <= code && code <= 0xC693) || // Lo  [27] HANGUL SYLLABLE OEG..HANGUL SYLLABLE OEH
  		(0xC695 <= code && code <= 0xC6AF) || // Lo  [27] HANGUL SYLLABLE YOG..HANGUL SYLLABLE YOH
  		(0xC6B1 <= code && code <= 0xC6CB) || // Lo  [27] HANGUL SYLLABLE UG..HANGUL SYLLABLE UH
  		(0xC6CD <= code && code <= 0xC6E7) || // Lo  [27] HANGUL SYLLABLE WEOG..HANGUL SYLLABLE WEOH
  		(0xC6E9 <= code && code <= 0xC703) || // Lo  [27] HANGUL SYLLABLE WEG..HANGUL SYLLABLE WEH
  		(0xC705 <= code && code <= 0xC71F) || // Lo  [27] HANGUL SYLLABLE WIG..HANGUL SYLLABLE WIH
  		(0xC721 <= code && code <= 0xC73B) || // Lo  [27] HANGUL SYLLABLE YUG..HANGUL SYLLABLE YUH
  		(0xC73D <= code && code <= 0xC757) || // Lo  [27] HANGUL SYLLABLE EUG..HANGUL SYLLABLE EUH
  		(0xC759 <= code && code <= 0xC773) || // Lo  [27] HANGUL SYLLABLE YIG..HANGUL SYLLABLE YIH
  		(0xC775 <= code && code <= 0xC78F) || // Lo  [27] HANGUL SYLLABLE IG..HANGUL SYLLABLE IH
  		(0xC791 <= code && code <= 0xC7AB) || // Lo  [27] HANGUL SYLLABLE JAG..HANGUL SYLLABLE JAH
  		(0xC7AD <= code && code <= 0xC7C7) || // Lo  [27] HANGUL SYLLABLE JAEG..HANGUL SYLLABLE JAEH
  		(0xC7C9 <= code && code <= 0xC7E3) || // Lo  [27] HANGUL SYLLABLE JYAG..HANGUL SYLLABLE JYAH
  		(0xC7E5 <= code && code <= 0xC7FF) || // Lo  [27] HANGUL SYLLABLE JYAEG..HANGUL SYLLABLE JYAEH
  		(0xC801 <= code && code <= 0xC81B) || // Lo  [27] HANGUL SYLLABLE JEOG..HANGUL SYLLABLE JEOH
  		(0xC81D <= code && code <= 0xC837) || // Lo  [27] HANGUL SYLLABLE JEG..HANGUL SYLLABLE JEH
  		(0xC839 <= code && code <= 0xC853) || // Lo  [27] HANGUL SYLLABLE JYEOG..HANGUL SYLLABLE JYEOH
  		(0xC855 <= code && code <= 0xC86F) || // Lo  [27] HANGUL SYLLABLE JYEG..HANGUL SYLLABLE JYEH
  		(0xC871 <= code && code <= 0xC88B) || // Lo  [27] HANGUL SYLLABLE JOG..HANGUL SYLLABLE JOH
  		(0xC88D <= code && code <= 0xC8A7) || // Lo  [27] HANGUL SYLLABLE JWAG..HANGUL SYLLABLE JWAH
  		(0xC8A9 <= code && code <= 0xC8C3) || // Lo  [27] HANGUL SYLLABLE JWAEG..HANGUL SYLLABLE JWAEH
  		(0xC8C5 <= code && code <= 0xC8DF) || // Lo  [27] HANGUL SYLLABLE JOEG..HANGUL SYLLABLE JOEH
  		(0xC8E1 <= code && code <= 0xC8FB) || // Lo  [27] HANGUL SYLLABLE JYOG..HANGUL SYLLABLE JYOH
  		(0xC8FD <= code && code <= 0xC917) || // Lo  [27] HANGUL SYLLABLE JUG..HANGUL SYLLABLE JUH
  		(0xC919 <= code && code <= 0xC933) || // Lo  [27] HANGUL SYLLABLE JWEOG..HANGUL SYLLABLE JWEOH
  		(0xC935 <= code && code <= 0xC94F) || // Lo  [27] HANGUL SYLLABLE JWEG..HANGUL SYLLABLE JWEH
  		(0xC951 <= code && code <= 0xC96B) || // Lo  [27] HANGUL SYLLABLE JWIG..HANGUL SYLLABLE JWIH
  		(0xC96D <= code && code <= 0xC987) || // Lo  [27] HANGUL SYLLABLE JYUG..HANGUL SYLLABLE JYUH
  		(0xC989 <= code && code <= 0xC9A3) || // Lo  [27] HANGUL SYLLABLE JEUG..HANGUL SYLLABLE JEUH
  		(0xC9A5 <= code && code <= 0xC9BF) || // Lo  [27] HANGUL SYLLABLE JYIG..HANGUL SYLLABLE JYIH
  		(0xC9C1 <= code && code <= 0xC9DB) || // Lo  [27] HANGUL SYLLABLE JIG..HANGUL SYLLABLE JIH
  		(0xC9DD <= code && code <= 0xC9F7) || // Lo  [27] HANGUL SYLLABLE JJAG..HANGUL SYLLABLE JJAH
  		(0xC9F9 <= code && code <= 0xCA13) || // Lo  [27] HANGUL SYLLABLE JJAEG..HANGUL SYLLABLE JJAEH
  		(0xCA15 <= code && code <= 0xCA2F) || // Lo  [27] HANGUL SYLLABLE JJYAG..HANGUL SYLLABLE JJYAH
  		(0xCA31 <= code && code <= 0xCA4B) || // Lo  [27] HANGUL SYLLABLE JJYAEG..HANGUL SYLLABLE JJYAEH
  		(0xCA4D <= code && code <= 0xCA67) || // Lo  [27] HANGUL SYLLABLE JJEOG..HANGUL SYLLABLE JJEOH
  		(0xCA69 <= code && code <= 0xCA83) || // Lo  [27] HANGUL SYLLABLE JJEG..HANGUL SYLLABLE JJEH
  		(0xCA85 <= code && code <= 0xCA9F) || // Lo  [27] HANGUL SYLLABLE JJYEOG..HANGUL SYLLABLE JJYEOH
  		(0xCAA1 <= code && code <= 0xCABB) || // Lo  [27] HANGUL SYLLABLE JJYEG..HANGUL SYLLABLE JJYEH
  		(0xCABD <= code && code <= 0xCAD7) || // Lo  [27] HANGUL SYLLABLE JJOG..HANGUL SYLLABLE JJOH
  		(0xCAD9 <= code && code <= 0xCAF3) || // Lo  [27] HANGUL SYLLABLE JJWAG..HANGUL SYLLABLE JJWAH
  		(0xCAF5 <= code && code <= 0xCB0F) || // Lo  [27] HANGUL SYLLABLE JJWAEG..HANGUL SYLLABLE JJWAEH
  		(0xCB11 <= code && code <= 0xCB2B) || // Lo  [27] HANGUL SYLLABLE JJOEG..HANGUL SYLLABLE JJOEH
  		(0xCB2D <= code && code <= 0xCB47) || // Lo  [27] HANGUL SYLLABLE JJYOG..HANGUL SYLLABLE JJYOH
  		(0xCB49 <= code && code <= 0xCB63) || // Lo  [27] HANGUL SYLLABLE JJUG..HANGUL SYLLABLE JJUH
  		(0xCB65 <= code && code <= 0xCB7F) || // Lo  [27] HANGUL SYLLABLE JJWEOG..HANGUL SYLLABLE JJWEOH
  		(0xCB81 <= code && code <= 0xCB9B) || // Lo  [27] HANGUL SYLLABLE JJWEG..HANGUL SYLLABLE JJWEH
  		(0xCB9D <= code && code <= 0xCBB7) || // Lo  [27] HANGUL SYLLABLE JJWIG..HANGUL SYLLABLE JJWIH
  		(0xCBB9 <= code && code <= 0xCBD3) || // Lo  [27] HANGUL SYLLABLE JJYUG..HANGUL SYLLABLE JJYUH
  		(0xCBD5 <= code && code <= 0xCBEF) || // Lo  [27] HANGUL SYLLABLE JJEUG..HANGUL SYLLABLE JJEUH
  		(0xCBF1 <= code && code <= 0xCC0B) || // Lo  [27] HANGUL SYLLABLE JJYIG..HANGUL SYLLABLE JJYIH
  		(0xCC0D <= code && code <= 0xCC27) || // Lo  [27] HANGUL SYLLABLE JJIG..HANGUL SYLLABLE JJIH
  		(0xCC29 <= code && code <= 0xCC43) || // Lo  [27] HANGUL SYLLABLE CAG..HANGUL SYLLABLE CAH
  		(0xCC45 <= code && code <= 0xCC5F) || // Lo  [27] HANGUL SYLLABLE CAEG..HANGUL SYLLABLE CAEH
  		(0xCC61 <= code && code <= 0xCC7B) || // Lo  [27] HANGUL SYLLABLE CYAG..HANGUL SYLLABLE CYAH
  		(0xCC7D <= code && code <= 0xCC97) || // Lo  [27] HANGUL SYLLABLE CYAEG..HANGUL SYLLABLE CYAEH
  		(0xCC99 <= code && code <= 0xCCB3) || // Lo  [27] HANGUL SYLLABLE CEOG..HANGUL SYLLABLE CEOH
  		(0xCCB5 <= code && code <= 0xCCCF) || // Lo  [27] HANGUL SYLLABLE CEG..HANGUL SYLLABLE CEH
  		(0xCCD1 <= code && code <= 0xCCEB) || // Lo  [27] HANGUL SYLLABLE CYEOG..HANGUL SYLLABLE CYEOH
  		(0xCCED <= code && code <= 0xCD07) || // Lo  [27] HANGUL SYLLABLE CYEG..HANGUL SYLLABLE CYEH
  		(0xCD09 <= code && code <= 0xCD23) || // Lo  [27] HANGUL SYLLABLE COG..HANGUL SYLLABLE COH
  		(0xCD25 <= code && code <= 0xCD3F) || // Lo  [27] HANGUL SYLLABLE CWAG..HANGUL SYLLABLE CWAH
  		(0xCD41 <= code && code <= 0xCD5B) || // Lo  [27] HANGUL SYLLABLE CWAEG..HANGUL SYLLABLE CWAEH
  		(0xCD5D <= code && code <= 0xCD77) || // Lo  [27] HANGUL SYLLABLE COEG..HANGUL SYLLABLE COEH
  		(0xCD79 <= code && code <= 0xCD93) || // Lo  [27] HANGUL SYLLABLE CYOG..HANGUL SYLLABLE CYOH
  		(0xCD95 <= code && code <= 0xCDAF) || // Lo  [27] HANGUL SYLLABLE CUG..HANGUL SYLLABLE CUH
  		(0xCDB1 <= code && code <= 0xCDCB) || // Lo  [27] HANGUL SYLLABLE CWEOG..HANGUL SYLLABLE CWEOH
  		(0xCDCD <= code && code <= 0xCDE7) || // Lo  [27] HANGUL SYLLABLE CWEG..HANGUL SYLLABLE CWEH
  		(0xCDE9 <= code && code <= 0xCE03) || // Lo  [27] HANGUL SYLLABLE CWIG..HANGUL SYLLABLE CWIH
  		(0xCE05 <= code && code <= 0xCE1F) || // Lo  [27] HANGUL SYLLABLE CYUG..HANGUL SYLLABLE CYUH
  		(0xCE21 <= code && code <= 0xCE3B) || // Lo  [27] HANGUL SYLLABLE CEUG..HANGUL SYLLABLE CEUH
  		(0xCE3D <= code && code <= 0xCE57) || // Lo  [27] HANGUL SYLLABLE CYIG..HANGUL SYLLABLE CYIH
  		(0xCE59 <= code && code <= 0xCE73) || // Lo  [27] HANGUL SYLLABLE CIG..HANGUL SYLLABLE CIH
  		(0xCE75 <= code && code <= 0xCE8F) || // Lo  [27] HANGUL SYLLABLE KAG..HANGUL SYLLABLE KAH
  		(0xCE91 <= code && code <= 0xCEAB) || // Lo  [27] HANGUL SYLLABLE KAEG..HANGUL SYLLABLE KAEH
  		(0xCEAD <= code && code <= 0xCEC7) || // Lo  [27] HANGUL SYLLABLE KYAG..HANGUL SYLLABLE KYAH
  		(0xCEC9 <= code && code <= 0xCEE3) || // Lo  [27] HANGUL SYLLABLE KYAEG..HANGUL SYLLABLE KYAEH
  		(0xCEE5 <= code && code <= 0xCEFF) || // Lo  [27] HANGUL SYLLABLE KEOG..HANGUL SYLLABLE KEOH
  		(0xCF01 <= code && code <= 0xCF1B) || // Lo  [27] HANGUL SYLLABLE KEG..HANGUL SYLLABLE KEH
  		(0xCF1D <= code && code <= 0xCF37) || // Lo  [27] HANGUL SYLLABLE KYEOG..HANGUL SYLLABLE KYEOH
  		(0xCF39 <= code && code <= 0xCF53) || // Lo  [27] HANGUL SYLLABLE KYEG..HANGUL SYLLABLE KYEH
  		(0xCF55 <= code && code <= 0xCF6F) || // Lo  [27] HANGUL SYLLABLE KOG..HANGUL SYLLABLE KOH
  		(0xCF71 <= code && code <= 0xCF8B) || // Lo  [27] HANGUL SYLLABLE KWAG..HANGUL SYLLABLE KWAH
  		(0xCF8D <= code && code <= 0xCFA7) || // Lo  [27] HANGUL SYLLABLE KWAEG..HANGUL SYLLABLE KWAEH
  		(0xCFA9 <= code && code <= 0xCFC3) || // Lo  [27] HANGUL SYLLABLE KOEG..HANGUL SYLLABLE KOEH
  		(0xCFC5 <= code && code <= 0xCFDF) || // Lo  [27] HANGUL SYLLABLE KYOG..HANGUL SYLLABLE KYOH
  		(0xCFE1 <= code && code <= 0xCFFB) || // Lo  [27] HANGUL SYLLABLE KUG..HANGUL SYLLABLE KUH
  		(0xCFFD <= code && code <= 0xD017) || // Lo  [27] HANGUL SYLLABLE KWEOG..HANGUL SYLLABLE KWEOH
  		(0xD019 <= code && code <= 0xD033) || // Lo  [27] HANGUL SYLLABLE KWEG..HANGUL SYLLABLE KWEH
  		(0xD035 <= code && code <= 0xD04F) || // Lo  [27] HANGUL SYLLABLE KWIG..HANGUL SYLLABLE KWIH
  		(0xD051 <= code && code <= 0xD06B) || // Lo  [27] HANGUL SYLLABLE KYUG..HANGUL SYLLABLE KYUH
  		(0xD06D <= code && code <= 0xD087) || // Lo  [27] HANGUL SYLLABLE KEUG..HANGUL SYLLABLE KEUH
  		(0xD089 <= code && code <= 0xD0A3) || // Lo  [27] HANGUL SYLLABLE KYIG..HANGUL SYLLABLE KYIH
  		(0xD0A5 <= code && code <= 0xD0BF) || // Lo  [27] HANGUL SYLLABLE KIG..HANGUL SYLLABLE KIH
  		(0xD0C1 <= code && code <= 0xD0DB) || // Lo  [27] HANGUL SYLLABLE TAG..HANGUL SYLLABLE TAH
  		(0xD0DD <= code && code <= 0xD0F7) || // Lo  [27] HANGUL SYLLABLE TAEG..HANGUL SYLLABLE TAEH
  		(0xD0F9 <= code && code <= 0xD113) || // Lo  [27] HANGUL SYLLABLE TYAG..HANGUL SYLLABLE TYAH
  		(0xD115 <= code && code <= 0xD12F) || // Lo  [27] HANGUL SYLLABLE TYAEG..HANGUL SYLLABLE TYAEH
  		(0xD131 <= code && code <= 0xD14B) || // Lo  [27] HANGUL SYLLABLE TEOG..HANGUL SYLLABLE TEOH
  		(0xD14D <= code && code <= 0xD167) || // Lo  [27] HANGUL SYLLABLE TEG..HANGUL SYLLABLE TEH
  		(0xD169 <= code && code <= 0xD183) || // Lo  [27] HANGUL SYLLABLE TYEOG..HANGUL SYLLABLE TYEOH
  		(0xD185 <= code && code <= 0xD19F) || // Lo  [27] HANGUL SYLLABLE TYEG..HANGUL SYLLABLE TYEH
  		(0xD1A1 <= code && code <= 0xD1BB) || // Lo  [27] HANGUL SYLLABLE TOG..HANGUL SYLLABLE TOH
  		(0xD1BD <= code && code <= 0xD1D7) || // Lo  [27] HANGUL SYLLABLE TWAG..HANGUL SYLLABLE TWAH
  		(0xD1D9 <= code && code <= 0xD1F3) || // Lo  [27] HANGUL SYLLABLE TWAEG..HANGUL SYLLABLE TWAEH
  		(0xD1F5 <= code && code <= 0xD20F) || // Lo  [27] HANGUL SYLLABLE TOEG..HANGUL SYLLABLE TOEH
  		(0xD211 <= code && code <= 0xD22B) || // Lo  [27] HANGUL SYLLABLE TYOG..HANGUL SYLLABLE TYOH
  		(0xD22D <= code && code <= 0xD247) || // Lo  [27] HANGUL SYLLABLE TUG..HANGUL SYLLABLE TUH
  		(0xD249 <= code && code <= 0xD263) || // Lo  [27] HANGUL SYLLABLE TWEOG..HANGUL SYLLABLE TWEOH
  		(0xD265 <= code && code <= 0xD27F) || // Lo  [27] HANGUL SYLLABLE TWEG..HANGUL SYLLABLE TWEH
  		(0xD281 <= code && code <= 0xD29B) || // Lo  [27] HANGUL SYLLABLE TWIG..HANGUL SYLLABLE TWIH
  		(0xD29D <= code && code <= 0xD2B7) || // Lo  [27] HANGUL SYLLABLE TYUG..HANGUL SYLLABLE TYUH
  		(0xD2B9 <= code && code <= 0xD2D3) || // Lo  [27] HANGUL SYLLABLE TEUG..HANGUL SYLLABLE TEUH
  		(0xD2D5 <= code && code <= 0xD2EF) || // Lo  [27] HANGUL SYLLABLE TYIG..HANGUL SYLLABLE TYIH
  		(0xD2F1 <= code && code <= 0xD30B) || // Lo  [27] HANGUL SYLLABLE TIG..HANGUL SYLLABLE TIH
  		(0xD30D <= code && code <= 0xD327) || // Lo  [27] HANGUL SYLLABLE PAG..HANGUL SYLLABLE PAH
  		(0xD329 <= code && code <= 0xD343) || // Lo  [27] HANGUL SYLLABLE PAEG..HANGUL SYLLABLE PAEH
  		(0xD345 <= code && code <= 0xD35F) || // Lo  [27] HANGUL SYLLABLE PYAG..HANGUL SYLLABLE PYAH
  		(0xD361 <= code && code <= 0xD37B) || // Lo  [27] HANGUL SYLLABLE PYAEG..HANGUL SYLLABLE PYAEH
  		(0xD37D <= code && code <= 0xD397) || // Lo  [27] HANGUL SYLLABLE PEOG..HANGUL SYLLABLE PEOH
  		(0xD399 <= code && code <= 0xD3B3) || // Lo  [27] HANGUL SYLLABLE PEG..HANGUL SYLLABLE PEH
  		(0xD3B5 <= code && code <= 0xD3CF) || // Lo  [27] HANGUL SYLLABLE PYEOG..HANGUL SYLLABLE PYEOH
  		(0xD3D1 <= code && code <= 0xD3EB) || // Lo  [27] HANGUL SYLLABLE PYEG..HANGUL SYLLABLE PYEH
  		(0xD3ED <= code && code <= 0xD407) || // Lo  [27] HANGUL SYLLABLE POG..HANGUL SYLLABLE POH
  		(0xD409 <= code && code <= 0xD423) || // Lo  [27] HANGUL SYLLABLE PWAG..HANGUL SYLLABLE PWAH
  		(0xD425 <= code && code <= 0xD43F) || // Lo  [27] HANGUL SYLLABLE PWAEG..HANGUL SYLLABLE PWAEH
  		(0xD441 <= code && code <= 0xD45B) || // Lo  [27] HANGUL SYLLABLE POEG..HANGUL SYLLABLE POEH
  		(0xD45D <= code && code <= 0xD477) || // Lo  [27] HANGUL SYLLABLE PYOG..HANGUL SYLLABLE PYOH
  		(0xD479 <= code && code <= 0xD493) || // Lo  [27] HANGUL SYLLABLE PUG..HANGUL SYLLABLE PUH
  		(0xD495 <= code && code <= 0xD4AF) || // Lo  [27] HANGUL SYLLABLE PWEOG..HANGUL SYLLABLE PWEOH
  		(0xD4B1 <= code && code <= 0xD4CB) || // Lo  [27] HANGUL SYLLABLE PWEG..HANGUL SYLLABLE PWEH
  		(0xD4CD <= code && code <= 0xD4E7) || // Lo  [27] HANGUL SYLLABLE PWIG..HANGUL SYLLABLE PWIH
  		(0xD4E9 <= code && code <= 0xD503) || // Lo  [27] HANGUL SYLLABLE PYUG..HANGUL SYLLABLE PYUH
  		(0xD505 <= code && code <= 0xD51F) || // Lo  [27] HANGUL SYLLABLE PEUG..HANGUL SYLLABLE PEUH
  		(0xD521 <= code && code <= 0xD53B) || // Lo  [27] HANGUL SYLLABLE PYIG..HANGUL SYLLABLE PYIH
  		(0xD53D <= code && code <= 0xD557) || // Lo  [27] HANGUL SYLLABLE PIG..HANGUL SYLLABLE PIH
  		(0xD559 <= code && code <= 0xD573) || // Lo  [27] HANGUL SYLLABLE HAG..HANGUL SYLLABLE HAH
  		(0xD575 <= code && code <= 0xD58F) || // Lo  [27] HANGUL SYLLABLE HAEG..HANGUL SYLLABLE HAEH
  		(0xD591 <= code && code <= 0xD5AB) || // Lo  [27] HANGUL SYLLABLE HYAG..HANGUL SYLLABLE HYAH
  		(0xD5AD <= code && code <= 0xD5C7) || // Lo  [27] HANGUL SYLLABLE HYAEG..HANGUL SYLLABLE HYAEH
  		(0xD5C9 <= code && code <= 0xD5E3) || // Lo  [27] HANGUL SYLLABLE HEOG..HANGUL SYLLABLE HEOH
  		(0xD5E5 <= code && code <= 0xD5FF) || // Lo  [27] HANGUL SYLLABLE HEG..HANGUL SYLLABLE HEH
  		(0xD601 <= code && code <= 0xD61B) || // Lo  [27] HANGUL SYLLABLE HYEOG..HANGUL SYLLABLE HYEOH
  		(0xD61D <= code && code <= 0xD637) || // Lo  [27] HANGUL SYLLABLE HYEG..HANGUL SYLLABLE HYEH
  		(0xD639 <= code && code <= 0xD653) || // Lo  [27] HANGUL SYLLABLE HOG..HANGUL SYLLABLE HOH
  		(0xD655 <= code && code <= 0xD66F) || // Lo  [27] HANGUL SYLLABLE HWAG..HANGUL SYLLABLE HWAH
  		(0xD671 <= code && code <= 0xD68B) || // Lo  [27] HANGUL SYLLABLE HWAEG..HANGUL SYLLABLE HWAEH
  		(0xD68D <= code && code <= 0xD6A7) || // Lo  [27] HANGUL SYLLABLE HOEG..HANGUL SYLLABLE HOEH
  		(0xD6A9 <= code && code <= 0xD6C3) || // Lo  [27] HANGUL SYLLABLE HYOG..HANGUL SYLLABLE HYOH
  		(0xD6C5 <= code && code <= 0xD6DF) || // Lo  [27] HANGUL SYLLABLE HUG..HANGUL SYLLABLE HUH
  		(0xD6E1 <= code && code <= 0xD6FB) || // Lo  [27] HANGUL SYLLABLE HWEOG..HANGUL SYLLABLE HWEOH
  		(0xD6FD <= code && code <= 0xD717) || // Lo  [27] HANGUL SYLLABLE HWEG..HANGUL SYLLABLE HWEH
  		(0xD719 <= code && code <= 0xD733) || // Lo  [27] HANGUL SYLLABLE HWIG..HANGUL SYLLABLE HWIH
  		(0xD735 <= code && code <= 0xD74F) || // Lo  [27] HANGUL SYLLABLE HYUG..HANGUL SYLLABLE HYUH
  		(0xD751 <= code && code <= 0xD76B) || // Lo  [27] HANGUL SYLLABLE HEUG..HANGUL SYLLABLE HEUH
  		(0xD76D <= code && code <= 0xD787) || // Lo  [27] HANGUL SYLLABLE HYIG..HANGUL SYLLABLE HYIH
  		(0xD789 <= code && code <= 0xD7A3) // Lo  [27] HANGUL SYLLABLE HIG..HANGUL SYLLABLE HIH
  		){
  			return LVT;
  		}
  		
  		if(
  		0x261D == code || // So       WHITE UP POINTING INDEX
  		0x26F9 == code || // So       PERSON WITH BALL
  		(0x270A <= code && code <= 0x270D) || // So   [4] RAISED FIST..WRITING HAND
  		0x1F385 == code || // So       FATHER CHRISTMAS
  		(0x1F3C2 <= code && code <= 0x1F3C4) || // So   [3] SNOWBOARDER..SURFER
  		0x1F3C7 == code || // So       HORSE RACING
  		(0x1F3CA <= code && code <= 0x1F3CC) || // So   [3] SWIMMER..GOLFER
  		(0x1F442 <= code && code <= 0x1F443) || // So   [2] EAR..NOSE
  		(0x1F446 <= code && code <= 0x1F450) || // So  [11] WHITE UP POINTING BACKHAND INDEX..OPEN HANDS SIGN
  		0x1F46E == code || // So       POLICE OFFICER
  		(0x1F470 <= code && code <= 0x1F478) || // So   [9] BRIDE WITH VEIL..PRINCESS
  		0x1F47C == code || // So       BABY ANGEL
  		(0x1F481 <= code && code <= 0x1F483) || // So   [3] INFORMATION DESK PERSON..DANCER
  		(0x1F485 <= code && code <= 0x1F487) || // So   [3] NAIL POLISH..HAIRCUT
  		0x1F4AA == code || // So       FLEXED BICEPS
  		(0x1F574 <= code && code <= 0x1F575) || // So   [2] MAN IN BUSINESS SUIT LEVITATING..SLEUTH OR SPY
  		0x1F57A == code || // So       MAN DANCING
  		0x1F590 == code || // So       RAISED HAND WITH FINGERS SPLAYED
  		(0x1F595 <= code && code <= 0x1F596) || // So   [2] REVERSED HAND WITH MIDDLE FINGER EXTENDED..RAISED HAND WITH PART BETWEEN MIDDLE AND RING FINGERS
  		(0x1F645 <= code && code <= 0x1F647) || // So   [3] FACE WITH NO GOOD GESTURE..PERSON BOWING DEEPLY
  		(0x1F64B <= code && code <= 0x1F64F) || // So   [5] HAPPY PERSON RAISING ONE HAND..PERSON WITH FOLDED HANDS
  		0x1F6A3 == code || // So       ROWBOAT
  		(0x1F6B4 <= code && code <= 0x1F6B6) || // So   [3] BICYCLIST..PEDESTRIAN
  		0x1F6C0 == code || // So       BATH
  		0x1F6CC == code || // So       SLEEPING ACCOMMODATION
  		(0x1F918 <= code && code <= 0x1F91C) || // So   [5] SIGN OF THE HORNS..RIGHT-FACING FIST
  		(0x1F91E <= code && code <= 0x1F91F) || // So   [2] HAND WITH INDEX AND MIDDLE FINGERS CROSSED..I LOVE YOU HAND SIGN
  		0x1F926 == code || // So       FACE PALM
  		(0x1F930 <= code && code <= 0x1F939) || // So  [10] PREGNANT WOMAN..JUGGLING
  		(0x1F93D <= code && code <= 0x1F93E) || // So   [2] WATER POLO..HANDBALL
  		(0x1F9D1 <= code && code <= 0x1F9DD) // So  [13] ADULT..ELF
  		){
  			return E_Base;
  		}

  		if(
  		(0x1F3FB <= code && code <= 0x1F3FF) // Sk   [5] EMOJI MODIFIER FITZPATRICK TYPE-1-2..EMOJI MODIFIER FITZPATRICK TYPE-6
  		){
  			return E_Modifier;
  		}

  		if(
  		0x200D == code // Cf       ZERO WIDTH JOINER
  		){
  			return ZWJ;
  		}

  		if(
  		0x2640 == code || // So       FEMALE SIGN
  		0x2642 == code || // So       MALE SIGN
  		(0x2695 <= code && code <= 0x2696) || // So   [2] STAFF OF AESCULAPIUS..SCALES
  		0x2708 == code || // So       AIRPLANE
  		0x2764 == code || // So       HEAVY BLACK HEART
  		0x1F308 == code || // So       RAINBOW
  		0x1F33E == code || // So       EAR OF RICE
  		0x1F373 == code || // So       COOKING
  		0x1F393 == code || // So       GRADUATION CAP
  		0x1F3A4 == code || // So       MICROPHONE
  		0x1F3A8 == code || // So       ARTIST PALETTE
  		0x1F3EB == code || // So       SCHOOL
  		0x1F3ED == code || // So       FACTORY
  		0x1F48B == code || // So       KISS MARK
  		(0x1F4BB <= code && code <= 0x1F4BC) || // So   [2] PERSONAL COMPUTER..BRIEFCASE
  		0x1F527 == code || // So       WRENCH
  		0x1F52C == code || // So       MICROSCOPE
  		0x1F5E8 == code || // So       LEFT SPEECH BUBBLE
  		0x1F680 == code || // So       ROCKET
  		0x1F692 == code // So       FIRE ENGINE
  		){
  			return Glue_After_Zwj;
  		}

  		if(
  		(0x1F466 <= code && code <= 0x1F469) // So   [4] BOY..WOMAN
  		){
  			return E_Base_GAZ;
  		}
  		
  		
  		//all unlisted characters have a grapheme break property of "Other"
  		return Other;
  	}
  	return this;
  }

  if (module.exports) {
      module.exports = GraphemeSplitter;
  }
  });

  // A glyph represents a single character in a particular label.  It may or may
  // not have a billboard, depending on whether the texture info has an index into
  // the the label collection's texture atlas.  Invisible characters have no texture, and
  // no billboard.  However, it always has a valid dimensions object.
  function Glyph() {
    this.textureInfo = undefined;
    this.dimensions = undefined;
    this.billboard = undefined;
  }

  // GlyphTextureInfo represents a single character, drawn in a particular style,
  // shared and reference counted across all labels.  It may or may not have an
  // index into the label collection's texture atlas, depending on whether the character
  // has both width and height, but it always has a valid dimensions object.
  function GlyphTextureInfo(labelCollection, index, dimensions) {
    this.labelCollection = labelCollection;
    this.index = index;
    this.dimensions = dimensions;
  }

  // Traditionally, leading is %20 of the font size.
  const defaultLineSpacingPercent = 1.2;
  const whitePixelCanvasId = "ID_WHITE_PIXEL";
  const whitePixelSize = new Cartesian2(4, 4);
  const whitePixelBoundingRegion = new BoundingRectangle(1, 1, 1, 1);

  function addWhitePixelCanvas(textureAtlas) {
    const canvas = document.createElement("canvas");
    canvas.width = whitePixelSize.x;
    canvas.height = whitePixelSize.y;

    const context2D = canvas.getContext("2d");
    context2D.fillStyle = "#fff";
    context2D.fillRect(0, 0, canvas.width, canvas.height);

    // Canvas operations take a frame to draw. Use the asynchronous add function which resolves a promise and allows the draw to complete,
    // but there's no need to wait on the promise before operation can continue
    textureAtlas.addImage(whitePixelCanvasId, canvas);
  }

  // reusable object for calling writeTextToCanvas
  const writeTextToCanvasParameters = {};
  function createGlyphCanvas(
    character,
    font,
    fillColor,
    outlineColor,
    outlineWidth,
    style,
    verticalOrigin
  ) {
    writeTextToCanvasParameters.font = font;
    writeTextToCanvasParameters.fillColor = fillColor;
    writeTextToCanvasParameters.strokeColor = outlineColor;
    writeTextToCanvasParameters.strokeWidth = outlineWidth;
    // Setting the padding to something bigger is necessary to get enough space for the outlining.
    writeTextToCanvasParameters.padding = SDFSettings$1.PADDING;

    if (verticalOrigin === VerticalOrigin$1.CENTER) {
      writeTextToCanvasParameters.textBaseline = "middle";
    } else if (verticalOrigin === VerticalOrigin$1.TOP) {
      writeTextToCanvasParameters.textBaseline = "top";
    } else {
      // VerticalOrigin.BOTTOM and VerticalOrigin.BASELINE
      writeTextToCanvasParameters.textBaseline = "bottom";
    }

    writeTextToCanvasParameters.fill =
      style === LabelStyle$1.FILL || style === LabelStyle$1.FILL_AND_OUTLINE;
    writeTextToCanvasParameters.stroke =
      style === LabelStyle$1.OUTLINE || style === LabelStyle$1.FILL_AND_OUTLINE;
    writeTextToCanvasParameters.backgroundColor = Color.BLACK;

    return writeTextToCanvas(character, writeTextToCanvasParameters);
  }

  function unbindGlyph(labelCollection, glyph) {
    glyph.textureInfo = undefined;
    glyph.dimensions = undefined;

    const billboard = glyph.billboard;
    if (defined(billboard)) {
      billboard.show = false;
      billboard.image = undefined;
      if (defined(billboard._removeCallbackFunc)) {
        billboard._removeCallbackFunc();
        billboard._removeCallbackFunc = undefined;
      }
      labelCollection._spareBillboards.push(billboard);
      glyph.billboard = undefined;
    }
  }

  function addGlyphToTextureAtlas(textureAtlas, id, canvas, glyphTextureInfo) {
    glyphTextureInfo.index = textureAtlas.addImageSync(id, canvas);
  }

  const splitter = new graphemeSplitter();

  function rebindAllGlyphs(labelCollection, label) {
    const text = label._renderedText;
    const graphemes = splitter.splitGraphemes(text);
    const textLength = graphemes.length;
    const glyphs = label._glyphs;
    const glyphsLength = glyphs.length;

    let glyph;
    let glyphIndex;
    let textIndex;

    // Compute a font size scale relative to the sdf font generated size.
    label._relativeSize = label._fontSize / SDFSettings$1.FONT_SIZE;

    // if we have more glyphs than needed, unbind the extras.
    if (textLength < glyphsLength) {
      for (glyphIndex = textLength; glyphIndex < glyphsLength; ++glyphIndex) {
        unbindGlyph(labelCollection, glyphs[glyphIndex]);
      }
    }

    // presize glyphs to match the new text length
    glyphs.length = textLength;

    const showBackground =
      label._showBackground && text.split("\n").join("").length > 0;
    let backgroundBillboard = label._backgroundBillboard;
    const backgroundBillboardCollection =
      labelCollection._backgroundBillboardCollection;
    if (!showBackground) {
      if (defined(backgroundBillboard)) {
        backgroundBillboardCollection.remove(backgroundBillboard);
        label._backgroundBillboard = backgroundBillboard = undefined;
      }
    } else {
      if (!defined(backgroundBillboard)) {
        backgroundBillboard = backgroundBillboardCollection.add({
          collection: labelCollection,
          image: whitePixelCanvasId,
          imageSubRegion: whitePixelBoundingRegion,
        });
        label._backgroundBillboard = backgroundBillboard;
      }

      backgroundBillboard.color = label._backgroundColor;
      backgroundBillboard.show = label._show;
      backgroundBillboard.position = label._position;
      backgroundBillboard.eyeOffset = label._eyeOffset;
      backgroundBillboard.pixelOffset = label._pixelOffset;
      backgroundBillboard.horizontalOrigin = HorizontalOrigin$1.LEFT;
      backgroundBillboard.verticalOrigin = label._verticalOrigin;
      backgroundBillboard.heightReference = label._heightReference;
      backgroundBillboard.scale = label.totalScale;
      backgroundBillboard.pickPrimitive = label;
      backgroundBillboard.id = label._id;
      backgroundBillboard.translucencyByDistance = label._translucencyByDistance;
      backgroundBillboard.pixelOffsetScaleByDistance =
        label._pixelOffsetScaleByDistance;
      backgroundBillboard.scaleByDistance = label._scaleByDistance;
      backgroundBillboard.distanceDisplayCondition =
        label._distanceDisplayCondition;
      backgroundBillboard.disableDepthTestDistance =
        label._disableDepthTestDistance;
    }

    const glyphTextureCache = labelCollection._glyphTextureCache;

    // walk the text looking for new characters (creating new glyphs for each)
    // or changed characters (rebinding existing glyphs)
    for (textIndex = 0; textIndex < textLength; ++textIndex) {
      const character = graphemes[textIndex];
      const verticalOrigin = label._verticalOrigin;

      const id = JSON.stringify([
        character,
        label._fontFamily,
        label._fontStyle,
        label._fontWeight,
        +verticalOrigin,
      ]);

      let glyphTextureInfo = glyphTextureCache[id];
      if (!defined(glyphTextureInfo)) {
        const glyphFont = `${label._fontStyle} ${label._fontWeight} ${SDFSettings$1.FONT_SIZE}px ${label._fontFamily}`;

        const canvas = createGlyphCanvas(
          character,
          glyphFont,
          Color.WHITE,
          Color.WHITE,
          0.0,
          LabelStyle$1.FILL,
          verticalOrigin
        );

        glyphTextureInfo = new GlyphTextureInfo(
          labelCollection,
          -1,
          canvas.dimensions
        );
        glyphTextureCache[id] = glyphTextureInfo;

        if (canvas.width > 0 && canvas.height > 0) {
          const sdfValues = bitmapSdf(canvas, {
            cutoff: SDFSettings$1.CUTOFF,
            radius: SDFSettings$1.RADIUS,
          });

          const ctx = canvas.getContext("2d");
          const canvasWidth = canvas.width;
          const canvasHeight = canvas.height;
          const imgData = ctx.getImageData(0, 0, canvasWidth, canvasHeight);
          for (let i = 0; i < canvasWidth; i++) {
            for (let j = 0; j < canvasHeight; j++) {
              const baseIndex = j * canvasWidth + i;
              const alpha = sdfValues[baseIndex] * 255;
              const imageIndex = baseIndex * 4;
              imgData.data[imageIndex + 0] = alpha;
              imgData.data[imageIndex + 1] = alpha;
              imgData.data[imageIndex + 2] = alpha;
              imgData.data[imageIndex + 3] = alpha;
            }
          }
          ctx.putImageData(imgData, 0, 0);
          if (character !== " ") {
            addGlyphToTextureAtlas(
              labelCollection._textureAtlas,
              id,
              canvas,
              glyphTextureInfo
            );
          }
        }
      }

      glyph = glyphs[textIndex];

      if (defined(glyph)) {
        // clean up leftover information from the previous glyph
        if (glyphTextureInfo.index === -1) {
          // no texture, and therefore no billboard, for this glyph.
          // so, completely unbind glyph.
          unbindGlyph(labelCollection, glyph);
        } else if (defined(glyph.textureInfo)) {
          // we have a texture and billboard.  If we had one before, release
          // our reference to that texture info, but reuse the billboard.
          glyph.textureInfo = undefined;
        }
      } else {
        // create a glyph object
        glyph = new Glyph();
        glyphs[textIndex] = glyph;
      }

      glyph.textureInfo = glyphTextureInfo;
      glyph.dimensions = glyphTextureInfo.dimensions;

      // if we have a texture, configure the existing billboard, or obtain one
      if (glyphTextureInfo.index !== -1) {
        let billboard = glyph.billboard;
        const spareBillboards = labelCollection._spareBillboards;
        if (!defined(billboard)) {
          if (spareBillboards.length > 0) {
            billboard = spareBillboards.pop();
          } else {
            billboard = labelCollection._billboardCollection.add({
              collection: labelCollection,
            });
            billboard._labelDimensions = new Cartesian2();
            billboard._labelTranslate = new Cartesian2();
          }
          glyph.billboard = billboard;
        }

        billboard.show = label._show;
        billboard.position = label._position;
        billboard.eyeOffset = label._eyeOffset;
        billboard.pixelOffset = label._pixelOffset;
        billboard.horizontalOrigin = HorizontalOrigin$1.LEFT;
        billboard.verticalOrigin = label._verticalOrigin;
        billboard.heightReference = label._heightReference;
        billboard.scale = label.totalScale;
        billboard.pickPrimitive = label;
        billboard.id = label._id;
        billboard.image = id;
        billboard.translucencyByDistance = label._translucencyByDistance;
        billboard.pixelOffsetScaleByDistance = label._pixelOffsetScaleByDistance;
        billboard.scaleByDistance = label._scaleByDistance;
        billboard.distanceDisplayCondition = label._distanceDisplayCondition;
        billboard.disableDepthTestDistance = label._disableDepthTestDistance;
        billboard._batchIndex = label._batchIndex;
        billboard.outlineColor = label.outlineColor;
        if (label.style === LabelStyle$1.FILL_AND_OUTLINE) {
          billboard.color = label._fillColor;
          billboard.outlineWidth = label.outlineWidth;
        } else if (label.style === LabelStyle$1.FILL) {
          billboard.color = label._fillColor;
          billboard.outlineWidth = 0.0;
        } else if (label.style === LabelStyle$1.OUTLINE) {
          billboard.color = Color.TRANSPARENT;
          billboard.outlineWidth = label.outlineWidth;
        }
      }
    }

    // changing glyphs will cause the position of the
    // glyphs to change, since different characters have different widths
    label._repositionAllGlyphs = true;
  }

  function calculateWidthOffset(lineWidth, horizontalOrigin, backgroundPadding) {
    if (horizontalOrigin === HorizontalOrigin$1.CENTER) {
      return -lineWidth / 2;
    } else if (horizontalOrigin === HorizontalOrigin$1.RIGHT) {
      return -(lineWidth + backgroundPadding.x);
    }
    return backgroundPadding.x;
  }

  // reusable Cartesian2 instances
  const glyphPixelOffset = new Cartesian2();
  const scratchBackgroundPadding = new Cartesian2();

  function repositionAllGlyphs(label) {
    const glyphs = label._glyphs;
    const text = label._renderedText;
    let glyph;
    let dimensions;
    let lastLineWidth = 0;
    let maxLineWidth = 0;
    const lineWidths = [];
    let maxGlyphDescent = Number.NEGATIVE_INFINITY;
    let maxGlyphY = 0;
    let numberOfLines = 1;
    let glyphIndex;
    const glyphLength = glyphs.length;

    const backgroundBillboard = label._backgroundBillboard;
    const backgroundPadding = Cartesian2.clone(
      defined(backgroundBillboard) ? label._backgroundPadding : Cartesian2.ZERO,
      scratchBackgroundPadding
    );

    // We need to scale the background padding, which is specified in pixels by the inverse of the relative size so it is scaled properly.
    backgroundPadding.x /= label._relativeSize;
    backgroundPadding.y /= label._relativeSize;

    for (glyphIndex = 0; glyphIndex < glyphLength; ++glyphIndex) {
      if (text.charAt(glyphIndex) === "\n") {
        lineWidths.push(lastLineWidth);
        ++numberOfLines;
        lastLineWidth = 0;
      } else {
        glyph = glyphs[glyphIndex];
        dimensions = glyph.dimensions;
        maxGlyphY = Math.max(maxGlyphY, dimensions.height - dimensions.descent);
        maxGlyphDescent = Math.max(maxGlyphDescent, dimensions.descent);

        //Computing the line width must also account for the kerning that occurs between letters.
        lastLineWidth += dimensions.width - dimensions.minx;
        if (glyphIndex < glyphLength - 1) {
          lastLineWidth += glyphs[glyphIndex + 1].dimensions.minx;
        }
        maxLineWidth = Math.max(maxLineWidth, lastLineWidth);
      }
    }
    lineWidths.push(lastLineWidth);
    const maxLineHeight = maxGlyphY + maxGlyphDescent;

    const scale = label.totalScale;
    const horizontalOrigin = label._horizontalOrigin;
    const verticalOrigin = label._verticalOrigin;
    let lineIndex = 0;
    let lineWidth = lineWidths[lineIndex];
    let widthOffset = calculateWidthOffset(
      lineWidth,
      horizontalOrigin,
      backgroundPadding
    );
    const lineSpacing =
      (defined(label._lineHeight)
        ? label._lineHeight
        : defaultLineSpacingPercent * label._fontSize) / label._relativeSize;
    const otherLinesHeight = lineSpacing * (numberOfLines - 1);
    let totalLineWidth = maxLineWidth;
    let totalLineHeight = maxLineHeight + otherLinesHeight;

    if (defined(backgroundBillboard)) {
      totalLineWidth += backgroundPadding.x * 2;
      totalLineHeight += backgroundPadding.y * 2;
      backgroundBillboard._labelHorizontalOrigin = horizontalOrigin;
    }

    glyphPixelOffset.x = widthOffset * scale;
    glyphPixelOffset.y = 0;

    let firstCharOfLine = true;

    let lineOffsetY = 0;
    for (glyphIndex = 0; glyphIndex < glyphLength; ++glyphIndex) {
      if (text.charAt(glyphIndex) === "\n") {
        ++lineIndex;
        lineOffsetY += lineSpacing;
        lineWidth = lineWidths[lineIndex];
        widthOffset = calculateWidthOffset(
          lineWidth,
          horizontalOrigin,
          backgroundPadding
        );
        glyphPixelOffset.x = widthOffset * scale;
        firstCharOfLine = true;
      } else {
        glyph = glyphs[glyphIndex];
        dimensions = glyph.dimensions;

        if (verticalOrigin === VerticalOrigin$1.TOP) {
          glyphPixelOffset.y =
            dimensions.height - maxGlyphY - backgroundPadding.y;
          glyphPixelOffset.y += SDFSettings$1.PADDING;
        } else if (verticalOrigin === VerticalOrigin$1.CENTER) {
          glyphPixelOffset.y =
            (otherLinesHeight + dimensions.height - maxGlyphY) / 2;
        } else if (verticalOrigin === VerticalOrigin$1.BASELINE) {
          glyphPixelOffset.y = otherLinesHeight;
          glyphPixelOffset.y -= SDFSettings$1.PADDING;
        } else {
          // VerticalOrigin.BOTTOM
          glyphPixelOffset.y =
            otherLinesHeight + maxGlyphDescent + backgroundPadding.y;
          glyphPixelOffset.y -= SDFSettings$1.PADDING;
        }
        glyphPixelOffset.y =
          (glyphPixelOffset.y - dimensions.descent - lineOffsetY) * scale;

        // Handle any offsets for the first character of the line since the bounds might not be right on the bottom left pixel.
        if (firstCharOfLine) {
          glyphPixelOffset.x -= SDFSettings$1.PADDING * scale;
          firstCharOfLine = false;
        }

        if (defined(glyph.billboard)) {
          glyph.billboard._setTranslate(glyphPixelOffset);
          glyph.billboard._labelDimensions.x = totalLineWidth;
          glyph.billboard._labelDimensions.y = totalLineHeight;
          glyph.billboard._labelHorizontalOrigin = horizontalOrigin;
        }

        //Compute the next x offset taking into account the kerning performed
        //on both the current letter as well as the next letter to be drawn
        //as well as any applied scale.
        if (glyphIndex < glyphLength - 1) {
          const nextGlyph = glyphs[glyphIndex + 1];
          glyphPixelOffset.x +=
            (dimensions.width - dimensions.minx + nextGlyph.dimensions.minx) *
            scale;
        }
      }
    }

    if (defined(backgroundBillboard) && text.split("\n").join("").length > 0) {
      if (horizontalOrigin === HorizontalOrigin$1.CENTER) {
        widthOffset = -maxLineWidth / 2 - backgroundPadding.x;
      } else if (horizontalOrigin === HorizontalOrigin$1.RIGHT) {
        widthOffset = -(maxLineWidth + backgroundPadding.x * 2);
      } else {
        widthOffset = 0;
      }
      glyphPixelOffset.x = widthOffset * scale;

      if (verticalOrigin === VerticalOrigin$1.TOP) {
        glyphPixelOffset.y = maxLineHeight - maxGlyphY - maxGlyphDescent;
      } else if (verticalOrigin === VerticalOrigin$1.CENTER) {
        glyphPixelOffset.y = (maxLineHeight - maxGlyphY) / 2 - maxGlyphDescent;
      } else if (verticalOrigin === VerticalOrigin$1.BASELINE) {
        glyphPixelOffset.y = -backgroundPadding.y - maxGlyphDescent;
      } else {
        // VerticalOrigin.BOTTOM
        glyphPixelOffset.y = 0;
      }
      glyphPixelOffset.y = glyphPixelOffset.y * scale;

      backgroundBillboard.width = totalLineWidth;
      backgroundBillboard.height = totalLineHeight;
      backgroundBillboard._setTranslate(glyphPixelOffset);
      backgroundBillboard._labelTranslate = Cartesian2.clone(
        glyphPixelOffset,
        backgroundBillboard._labelTranslate
      );
    }

    if (label.heightReference === HeightReference$1.CLAMP_TO_GROUND) {
      for (glyphIndex = 0; glyphIndex < glyphLength; ++glyphIndex) {
        glyph = glyphs[glyphIndex];
        const billboard = glyph.billboard;
        if (defined(billboard)) {
          billboard._labelTranslate = Cartesian2.clone(
            glyphPixelOffset,
            billboard._labelTranslate
          );
        }
      }
    }
  }

  function destroyLabel(labelCollection, label) {
    const glyphs = label._glyphs;
    for (let i = 0, len = glyphs.length; i < len; ++i) {
      unbindGlyph(labelCollection, glyphs[i]);
    }
    if (defined(label._backgroundBillboard)) {
      labelCollection._backgroundBillboardCollection.remove(
        label._backgroundBillboard
      );
      label._backgroundBillboard = undefined;
    }
    label._labelCollection = undefined;

    if (defined(label._removeCallbackFunc)) {
      label._removeCallbackFunc();
    }

    destroyObject(label);
  }

  /**
   * A renderable collection of labels.  Labels are viewport-aligned text positioned in the 3D scene.
   * Each label can have a different font, color, scale, etc.
   * <br /><br />
   * <div align='center'>
   * <img src='Images/Label.png' width='400' height='300' /><br />
   * Example labels
   * </div>
   * <br /><br />
   * Labels are added and removed from the collection using {@link LabelCollection#add}
   * and {@link LabelCollection#remove}.
   *
   * @alias LabelCollection
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] The 4x4 transformation matrix that transforms each label from model to world coordinates.
   * @param {Boolean} [options.debugShowBoundingVolume=false] For debugging only. Determines if this primitive's commands' bounding spheres are shown.
   * @param {Scene} [options.scene] Must be passed in for labels that use the height reference property or will be depth tested against the globe.
   * @param {BlendOption} [options.blendOption=BlendOption.OPAQUE_AND_TRANSLUCENT] The label blending option. The default
   * is used for rendering both opaque and translucent labels. However, if either all of the labels are completely opaque or all are completely translucent,
   * setting the technique to BlendOption.OPAQUE or BlendOption.TRANSLUCENT can improve performance by up to 2x.
   * @param {Boolean} [options.show=true] Determines if the labels in the collection will be shown.
   *
   * @performance For best performance, prefer a few collections, each with many labels, to
   * many collections with only a few labels each.  Avoid having collections where some
   * labels change every frame and others do not; instead, create one or more collections
   * for static labels, and one or more collections for dynamic labels.
   *
   * @see LabelCollection#add
   * @see LabelCollection#remove
   * @see Label
   * @see BillboardCollection
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Labels.html|Cesium Sandcastle Labels Demo}
   *
   * @example
   * // Create a label collection with two labels
   * const labels = scene.primitives.add(new Cesium.LabelCollection());
   * labels.add({
   *   position : new Cesium.Cartesian3(1.0, 2.0, 3.0),
   *   text : 'A label'
   * });
   * labels.add({
   *   position : new Cesium.Cartesian3(4.0, 5.0, 6.0),
   *   text : 'Another label'
   * });
   */
  function LabelCollection(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    this._scene = options.scene;
    this._batchTable = options.batchTable;

    this._textureAtlas = undefined;
    this._backgroundTextureAtlas = undefined;

    this._backgroundBillboardCollection = new BillboardCollection({
      scene: this._scene,
    });
    this._backgroundBillboardCollection.destroyTextureAtlas = false;

    this._billboardCollection = new BillboardCollection({
      scene: this._scene,
      batchTable: this._batchTable,
    });
    this._billboardCollection.destroyTextureAtlas = false;
    this._billboardCollection._sdf = true;

    this._spareBillboards = [];
    this._glyphTextureCache = {};
    this._labels = [];
    this._labelsToUpdate = [];
    this._totalGlyphCount = 0;

    this._highlightColor = Color.clone(Color.WHITE); // Only used by Vector3DTilePoints

    /**
     * Determines if labels in this collection will be shown.
     *
     * @type {Boolean}
     * @default true
     */
    this.show = defaultValue(options.show, true);

    /**
     * The 4x4 transformation matrix that transforms each label in this collection from model to world coordinates.
     * When this is the identity matrix, the labels are drawn in world coordinates, i.e., Earth's WGS84 coordinates.
     * Local reference frames can be used by providing a different transformation matrix, like that returned
     * by {@link Transforms.eastNorthUpToFixedFrame}.
     *
     * @type Matrix4
     * @default {@link Matrix4.IDENTITY}
     *
     * @example
     * const center = Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883);
     * labels.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(center);
     * labels.add({
     *   position : new Cesium.Cartesian3(0.0, 0.0, 0.0),
     *   text     : 'Center'
     * });
     * labels.add({
     *   position : new Cesium.Cartesian3(1000000.0, 0.0, 0.0),
     *   text     : 'East'
     * });
     * labels.add({
     *   position : new Cesium.Cartesian3(0.0, 1000000.0, 0.0),
     *   text     : 'North'
     * });
     * labels.add({
     *   position : new Cesium.Cartesian3(0.0, 0.0, 1000000.0),
     *   text     : 'Up'
     * });
     */
    this.modelMatrix = Matrix4.clone(
      defaultValue(options.modelMatrix, Matrix4.IDENTITY)
    );

    /**
     * This property is for debugging only; it is not for production use nor is it optimized.
     * <p>
     * Draws the bounding sphere for each draw command in the primitive.
     * </p>
     *
     * @type {Boolean}
     *
     * @default false
     */
    this.debugShowBoundingVolume = defaultValue(
      options.debugShowBoundingVolume,
      false
    );

    /**
     * The label blending option. The default is used for rendering both opaque and translucent labels.
     * However, if either all of the labels are completely opaque or all are completely translucent,
     * setting the technique to BlendOption.OPAQUE or BlendOption.TRANSLUCENT can improve
     * performance by up to 2x.
     * @type {BlendOption}
     * @default BlendOption.OPAQUE_AND_TRANSLUCENT
     */
    this.blendOption = defaultValue(
      options.blendOption,
      BlendOption$1.OPAQUE_AND_TRANSLUCENT
    );
  }

  Object.defineProperties(LabelCollection.prototype, {
    /**
     * Returns the number of labels in this collection.  This is commonly used with
     * {@link LabelCollection#get} to iterate over all the labels
     * in the collection.
     * @memberof LabelCollection.prototype
     * @type {Number}
     */
    length: {
      get: function () {
        return this._labels.length;
      },
    },
  });

  /**
   * Creates and adds a label with the specified initial properties to the collection.
   * The added label is returned so it can be modified or removed from the collection later.
   *
   * @param {Object} [options] A template describing the label's properties as shown in Example 1.
   * @returns {Label} The label that was added to the collection.
   *
   * @performance Calling <code>add</code> is expected constant time.  However, the collection's vertex buffer
   * is rewritten; this operations is <code>O(n)</code> and also incurs
   * CPU to GPU overhead.  For best performance, add as many billboards as possible before
   * calling <code>update</code>.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * // Example 1:  Add a label, specifying all the default values.
   * const l = labels.add({
   *   show : true,
   *   position : Cesium.Cartesian3.ZERO,
   *   text : '',
   *   font : '30px sans-serif',
   *   fillColor : Cesium.Color.WHITE,
   *   outlineColor : Cesium.Color.BLACK,
   *   outlineWidth : 1.0,
   *   showBackground : false,
   *   backgroundColor : new Cesium.Color(0.165, 0.165, 0.165, 0.8),
   *   backgroundPadding : new Cesium.Cartesian2(7, 5),
   *   style : Cesium.LabelStyle.FILL,
   *   pixelOffset : Cesium.Cartesian2.ZERO,
   *   eyeOffset : Cesium.Cartesian3.ZERO,
   *   horizontalOrigin : Cesium.HorizontalOrigin.LEFT,
   *   verticalOrigin : Cesium.VerticalOrigin.BASELINE,
   *   scale : 1.0,
   *   translucencyByDistance : undefined,
   *   pixelOffsetScaleByDistance : undefined,
   *   heightReference : HeightReference.NONE,
   *   distanceDisplayCondition : undefined
   * });
   *
   * @example
   * // Example 2:  Specify only the label's cartographic position,
   * // text, and font.
   * const l = labels.add({
   *   position : Cesium.Cartesian3.fromRadians(longitude, latitude, height),
   *   text : 'Hello World',
   *   font : '24px Helvetica',
   * });
   *
   * @see LabelCollection#remove
   * @see LabelCollection#removeAll
   */
  LabelCollection.prototype.add = function (options) {
    const label = new Label(options, this);

    this._labels.push(label);
    this._labelsToUpdate.push(label);

    return label;
  };

  /**
   * Removes a label from the collection.  Once removed, a label is no longer usable.
   *
   * @param {Label} label The label to remove.
   * @returns {Boolean} <code>true</code> if the label was removed; <code>false</code> if the label was not found in the collection.
   *
   * @performance Calling <code>remove</code> is expected constant time.  However, the collection's vertex buffer
   * is rewritten - an <code>O(n)</code> operation that also incurs CPU to GPU overhead.  For
   * best performance, remove as many labels as possible before calling <code>update</code>.
   * If you intend to temporarily hide a label, it is usually more efficient to call
   * {@link Label#show} instead of removing and re-adding the label.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * const l = labels.add(...);
   * labels.remove(l);  // Returns true
   *
   * @see LabelCollection#add
   * @see LabelCollection#removeAll
   * @see Label#show
   */
  LabelCollection.prototype.remove = function (label) {
    if (defined(label) && label._labelCollection === this) {
      const index = this._labels.indexOf(label);
      if (index !== -1) {
        this._labels.splice(index, 1);
        destroyLabel(this, label);
        return true;
      }
    }
    return false;
  };

  /**
   * Removes all labels from the collection.
   *
   * @performance <code>O(n)</code>.  It is more efficient to remove all the labels
   * from a collection and then add new ones than to create a new collection entirely.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * labels.add(...);
   * labels.add(...);
   * labels.removeAll();
   *
   * @see LabelCollection#add
   * @see LabelCollection#remove
   */
  LabelCollection.prototype.removeAll = function () {
    const labels = this._labels;

    for (let i = 0, len = labels.length; i < len; ++i) {
      destroyLabel(this, labels[i]);
    }

    labels.length = 0;
  };

  /**
   * Check whether this collection contains a given label.
   *
   * @param {Label} label The label to check for.
   * @returns {Boolean} true if this collection contains the label, false otherwise.
   *
   * @see LabelCollection#get
   *
   */
  LabelCollection.prototype.contains = function (label) {
    return defined(label) && label._labelCollection === this;
  };

  /**
   * Returns the label in the collection at the specified index.  Indices are zero-based
   * and increase as labels are added.  Removing a label shifts all labels after
   * it to the left, changing their indices.  This function is commonly used with
   * {@link LabelCollection#length} to iterate over all the labels
   * in the collection.
   *
   * @param {Number} index The zero-based index of the billboard.
   *
   * @returns {Label} The label at the specified index.
   *
   * @performance Expected constant time.  If labels were removed from the collection and
   * {@link Scene#render} was not called, an implicit <code>O(n)</code>
   * operation is performed.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * // Toggle the show property of every label in the collection
   * const len = labels.length;
   * for (let i = 0; i < len; ++i) {
   *   const l = billboards.get(i);
   *   l.show = !l.show;
   * }
   *
   * @see LabelCollection#length
   */
  LabelCollection.prototype.get = function (index) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(index)) {
      throw new DeveloperError("index is required.");
    }
    //>>includeEnd('debug');

    return this._labels[index];
  };

  /**
   * @private
   *
   */
  LabelCollection.prototype.update = function (frameState) {
    if (!this.show) {
      return;
    }

    const billboardCollection = this._billboardCollection;
    const backgroundBillboardCollection = this._backgroundBillboardCollection;

    billboardCollection.modelMatrix = this.modelMatrix;
    billboardCollection.debugShowBoundingVolume = this.debugShowBoundingVolume;
    backgroundBillboardCollection.modelMatrix = this.modelMatrix;
    backgroundBillboardCollection.debugShowBoundingVolume = this.debugShowBoundingVolume;

    const context = frameState.context;

    if (!defined(this._textureAtlas)) {
      this._textureAtlas = new TextureAtlas({
        context: context,
      });
      billboardCollection.textureAtlas = this._textureAtlas;
    }

    if (!defined(this._backgroundTextureAtlas)) {
      this._backgroundTextureAtlas = new TextureAtlas({
        context: context,
        initialSize: whitePixelSize,
      });
      backgroundBillboardCollection.textureAtlas = this._backgroundTextureAtlas;
      addWhitePixelCanvas(this._backgroundTextureAtlas);
    }

    const len = this._labelsToUpdate.length;
    for (let i = 0; i < len; ++i) {
      const label = this._labelsToUpdate[i];
      if (label.isDestroyed()) {
        continue;
      }

      const preUpdateGlyphCount = label._glyphs.length;

      if (label._rebindAllGlyphs) {
        rebindAllGlyphs(this, label);
        label._rebindAllGlyphs = false;
      }

      if (label._repositionAllGlyphs) {
        repositionAllGlyphs(label);
        label._repositionAllGlyphs = false;
      }

      const glyphCountDifference = label._glyphs.length - preUpdateGlyphCount;
      this._totalGlyphCount += glyphCountDifference;
    }

    const blendOption =
      backgroundBillboardCollection.length > 0
        ? BlendOption$1.TRANSLUCENT
        : this.blendOption;
    billboardCollection.blendOption = blendOption;
    backgroundBillboardCollection.blendOption = blendOption;

    billboardCollection._highlightColor = this._highlightColor;
    backgroundBillboardCollection._highlightColor = this._highlightColor;

    this._labelsToUpdate.length = 0;
    backgroundBillboardCollection.update(frameState);
    billboardCollection.update(frameState);
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} True if this object was destroyed; otherwise, false.
   *
   * @see LabelCollection#destroy
   */
  LabelCollection.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * labels = labels && labels.destroy();
   *
   * @see LabelCollection#isDestroyed
   */
  LabelCollection.prototype.destroy = function () {
    this.removeAll();
    this._billboardCollection = this._billboardCollection.destroy();
    this._textureAtlas = this._textureAtlas && this._textureAtlas.destroy();
    this._backgroundBillboardCollection = this._backgroundBillboardCollection.destroy();
    this._backgroundTextureAtlas =
      this._backgroundTextureAtlas && this._backgroundTextureAtlas.destroy();

    return destroyObject(this);
  };

  //This file is automatically rebuilt by the Cesium build process.
  var PolylineVS = "attribute vec3 position3DHigh;\n\
attribute vec3 position3DLow;\n\
attribute vec3 position2DHigh;\n\
attribute vec3 position2DLow;\n\
attribute vec3 prevPosition3DHigh;\n\
attribute vec3 prevPosition3DLow;\n\
attribute vec3 prevPosition2DHigh;\n\
attribute vec3 prevPosition2DLow;\n\
attribute vec3 nextPosition3DHigh;\n\
attribute vec3 nextPosition3DLow;\n\
attribute vec3 nextPosition2DHigh;\n\
attribute vec3 nextPosition2DLow;\n\
attribute vec4 texCoordExpandAndBatchIndex;\n\
varying vec2  v_st;\n\
varying float v_width;\n\
varying vec4 v_pickColor;\n\
varying float v_polylineAngle;\n\
void main()\n\
{\n\
float texCoord = texCoordExpandAndBatchIndex.x;\n\
float expandDir = texCoordExpandAndBatchIndex.y;\n\
bool usePrev = texCoordExpandAndBatchIndex.z < 0.0;\n\
float batchTableIndex = texCoordExpandAndBatchIndex.w;\n\
vec2 widthAndShow = batchTable_getWidthAndShow(batchTableIndex);\n\
float width = widthAndShow.x + 0.5;\n\
float show = widthAndShow.y;\n\
if (width < 1.0)\n\
{\n\
show = 0.0;\n\
}\n\
vec4 pickColor = batchTable_getPickColor(batchTableIndex);\n\
vec4 p, prev, next;\n\
if (czm_morphTime == 1.0)\n\
{\n\
p = czm_translateRelativeToEye(position3DHigh.xyz, position3DLow.xyz);\n\
prev = czm_translateRelativeToEye(prevPosition3DHigh.xyz, prevPosition3DLow.xyz);\n\
next = czm_translateRelativeToEye(nextPosition3DHigh.xyz, nextPosition3DLow.xyz);\n\
}\n\
else if (czm_morphTime == 0.0)\n\
{\n\
p = czm_translateRelativeToEye(position2DHigh.zxy, position2DLow.zxy);\n\
prev = czm_translateRelativeToEye(prevPosition2DHigh.zxy, prevPosition2DLow.zxy);\n\
next = czm_translateRelativeToEye(nextPosition2DHigh.zxy, nextPosition2DLow.zxy);\n\
}\n\
else\n\
{\n\
p = czm_columbusViewMorph(\n\
czm_translateRelativeToEye(position2DHigh.zxy, position2DLow.zxy),\n\
czm_translateRelativeToEye(position3DHigh.xyz, position3DLow.xyz),\n\
czm_morphTime);\n\
prev = czm_columbusViewMorph(\n\
czm_translateRelativeToEye(prevPosition2DHigh.zxy, prevPosition2DLow.zxy),\n\
czm_translateRelativeToEye(prevPosition3DHigh.xyz, prevPosition3DLow.xyz),\n\
czm_morphTime);\n\
next = czm_columbusViewMorph(\n\
czm_translateRelativeToEye(nextPosition2DHigh.zxy, nextPosition2DLow.zxy),\n\
czm_translateRelativeToEye(nextPosition3DHigh.xyz, nextPosition3DLow.xyz),\n\
czm_morphTime);\n\
}\n\
#ifdef DISTANCE_DISPLAY_CONDITION\n\
vec3 centerHigh = batchTable_getCenterHigh(batchTableIndex);\n\
vec4 centerLowAndRadius = batchTable_getCenterLowAndRadius(batchTableIndex);\n\
vec3 centerLow = centerLowAndRadius.xyz;\n\
float radius = centerLowAndRadius.w;\n\
vec2 distanceDisplayCondition = batchTable_getDistanceDisplayCondition(batchTableIndex);\n\
float lengthSq;\n\
if (czm_sceneMode == czm_sceneMode2D)\n\
{\n\
lengthSq = czm_eyeHeight2D.y;\n\
}\n\
else\n\
{\n\
vec4 center = czm_translateRelativeToEye(centerHigh.xyz, centerLow.xyz);\n\
lengthSq = max(0.0, dot(center.xyz, center.xyz) - radius * radius);\n\
}\n\
float nearSq = distanceDisplayCondition.x * distanceDisplayCondition.x;\n\
float farSq = distanceDisplayCondition.y * distanceDisplayCondition.y;\n\
if (lengthSq < nearSq || lengthSq > farSq)\n\
{\n\
show = 0.0;\n\
}\n\
#endif\n\
float polylineAngle;\n\
vec4 positionWC = getPolylineWindowCoordinates(p, prev, next, expandDir, width, usePrev, polylineAngle);\n\
gl_Position = czm_viewportOrthographic * positionWC * show;\n\
v_st.s = texCoord;\n\
v_st.t = czm_writeNonPerspective(clamp(expandDir, 0.0, 1.0), gl_Position.w);\n\
v_width = width;\n\
v_pickColor = pickColor;\n\
v_polylineAngle = polylineAngle;\n\
}\n\
";

  /**
   * A renderable polyline. Create this by calling {@link PolylineCollection#add}
   *
   * @alias Polyline
   * @internalConstructor
   * @class
   *
   * @param {Object} options Object with the following properties:
   * @param {Boolean} [options.show=true] <code>true</code> if this polyline will be shown; otherwise, <code>false</code>.
   * @param {Number} [options.width=1.0] The width of the polyline in pixels.
   * @param {Boolean} [options.loop=false] Whether a line segment will be added between the last and first line positions to make this line a loop.
   * @param {Material} [options.material=Material.ColorType] The material.
   * @param {Cartesian3[]} [options.positions] The positions.
   * @param {Object} [options.id] The user-defined object to be returned when this polyline is picked.
   * @param {DistanceDisplayCondition} [options.distanceDisplayCondition] The condition specifying at what distance from the camera that this polyline will be displayed.
   * @param {PolylineCollection} polylineCollection The renderable polyline collection.
   *
   * @see PolylineCollection
   *
   */
  function Polyline(options, polylineCollection) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    this._show = defaultValue(options.show, true);
    this._width = defaultValue(options.width, 1.0);
    this._loop = defaultValue(options.loop, false);
    this._distanceDisplayCondition = options.distanceDisplayCondition;

    this._material = options.material;
    if (!defined(this._material)) {
      this._material = Material$4.fromType(Material$4.ColorType, {
        color: new Color(1.0, 1.0, 1.0, 1.0),
      });
    }

    let positions = options.positions;
    if (!defined(positions)) {
      positions = [];
    }

    this._positions = positions;
    this._actualPositions = arrayRemoveDuplicates(
      positions,
      Cartesian3.equalsEpsilon
    );

    if (this._loop && this._actualPositions.length > 2) {
      if (this._actualPositions === this._positions) {
        this._actualPositions = positions.slice();
      }
      this._actualPositions.push(Cartesian3.clone(this._actualPositions[0]));
    }

    this._length = this._actualPositions.length;
    this._id = options.id;

    let modelMatrix;
    if (defined(polylineCollection)) {
      modelMatrix = Matrix4.clone(polylineCollection.modelMatrix);
    }

    this._modelMatrix = modelMatrix;
    this._segments = PolylinePipeline.wrapLongitude(
      this._actualPositions,
      modelMatrix
    );

    this._actualLength = undefined;

    // eslint-disable-next-line no-use-before-define
    this._propertiesChanged = new Uint32Array(NUMBER_OF_PROPERTIES$3);
    this._polylineCollection = polylineCollection;
    this._dirty = false;
    this._pickId = undefined;
    this._boundingVolume = BoundingSphere.fromPoints(this._actualPositions);
    this._boundingVolumeWC = BoundingSphere.transform(
      this._boundingVolume,
      this._modelMatrix
    );
    this._boundingVolume2D = new BoundingSphere(); // modified in PolylineCollection
  }

  const POSITION_INDEX$5 = (Polyline.POSITION_INDEX = 0);
  const SHOW_INDEX$5 = (Polyline.SHOW_INDEX = 1);
  const WIDTH_INDEX$1 = (Polyline.WIDTH_INDEX = 2);
  const MATERIAL_INDEX$1 = (Polyline.MATERIAL_INDEX = 3);
  const POSITION_SIZE_INDEX$1 = (Polyline.POSITION_SIZE_INDEX = 4);
  const DISTANCE_DISPLAY_CONDITION$1 = (Polyline.DISTANCE_DISPLAY_CONDITION = 5);
  const NUMBER_OF_PROPERTIES$3 = (Polyline.NUMBER_OF_PROPERTIES = 6);

  function makeDirty$2(polyline, propertyChanged) {
    ++polyline._propertiesChanged[propertyChanged];
    const polylineCollection = polyline._polylineCollection;
    if (defined(polylineCollection)) {
      polylineCollection._updatePolyline(polyline, propertyChanged);
      polyline._dirty = true;
    }
  }

  Object.defineProperties(Polyline.prototype, {
    /**
     * Determines if this polyline will be shown.  Use this to hide or show a polyline, instead
     * of removing it and re-adding it to the collection.
     * @memberof Polyline.prototype
     * @type {Boolean}
     */
    show: {
      get: function () {
        return this._show;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        if (value !== this._show) {
          this._show = value;
          makeDirty$2(this, SHOW_INDEX$5);
        }
      },
    },

    /**
     * Gets or sets the positions of the polyline.
     * @memberof Polyline.prototype
     * @type {Cartesian3[]}
     * @example
     * polyline.positions = Cesium.Cartesian3.fromDegreesArray([
     *     0.0, 0.0,
     *     10.0, 0.0,
     *     0.0, 20.0
     * ]);
     */
    positions: {
      get: function () {
        return this._positions;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        let positions = arrayRemoveDuplicates(value, Cartesian3.equalsEpsilon);

        if (this._loop && positions.length > 2) {
          if (positions === value) {
            positions = value.slice();
          }
          positions.push(Cartesian3.clone(positions[0]));
        }

        if (
          this._actualPositions.length !== positions.length ||
          this._actualPositions.length !== this._length
        ) {
          makeDirty$2(this, POSITION_SIZE_INDEX$1);
        }

        this._positions = value;
        this._actualPositions = positions;
        this._length = positions.length;
        this._boundingVolume = BoundingSphere.fromPoints(
          this._actualPositions,
          this._boundingVolume
        );
        this._boundingVolumeWC = BoundingSphere.transform(
          this._boundingVolume,
          this._modelMatrix,
          this._boundingVolumeWC
        );
        makeDirty$2(this, POSITION_INDEX$5);

        this.update();
      },
    },

    /**
     * Gets or sets the surface appearance of the polyline.  This can be one of several built-in {@link Material} objects or a custom material, scripted with
     * {@link https://github.com/CesiumGS/cesium/wiki/Fabric|Fabric}.
     * @memberof Polyline.prototype
     * @type {Material}
     */
    material: {
      get: function () {
        return this._material;
      },
      set: function (material) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(material)) {
          throw new DeveloperError("material is required.");
        }
        //>>includeEnd('debug');

        if (this._material !== material) {
          this._material = material;
          makeDirty$2(this, MATERIAL_INDEX$1);
        }
      },
    },

    /**
     * Gets or sets the width of the polyline.
     * @memberof Polyline.prototype
     * @type {Number}
     */
    width: {
      get: function () {
        return this._width;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug)
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        const width = this._width;
        if (value !== width) {
          this._width = value;
          makeDirty$2(this, WIDTH_INDEX$1);
        }
      },
    },

    /**
     * Gets or sets whether a line segment will be added between the first and last polyline positions.
     * @memberof Polyline.prototype
     * @type {Boolean}
     */
    loop: {
      get: function () {
        return this._loop;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug)
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        if (value !== this._loop) {
          let positions = this._actualPositions;
          if (value) {
            if (
              positions.length > 2 &&
              !Cartesian3.equals(positions[0], positions[positions.length - 1])
            ) {
              if (positions.length === this._positions.length) {
                this._actualPositions = positions = this._positions.slice();
              }
              positions.push(Cartesian3.clone(positions[0]));
            }
          } else if (
            positions.length > 2 &&
            Cartesian3.equals(positions[0], positions[positions.length - 1])
          ) {
            if (positions.length - 1 === this._positions.length) {
              this._actualPositions = this._positions;
            } else {
              positions.pop();
            }
          }

          this._loop = value;
          makeDirty$2(this, POSITION_SIZE_INDEX$1);
        }
      },
    },

    /**
     * Gets or sets the user-defined value returned when the polyline is picked.
     * @memberof Polyline.prototype
     * @type {*}
     */
    id: {
      get: function () {
        return this._id;
      },
      set: function (value) {
        this._id = value;
        if (defined(this._pickId)) {
          this._pickId.object.id = value;
        }
      },
    },

    /**
     * @private
     */
    pickId: {
      get: function () {
        return this._pickId;
      },
    },

    /**
     * Gets the destruction status of this polyline
     * @memberof Polyline.prototype
     * @type {Boolean}
     * @default false
     * @private
     */
    isDestroyed: {
      get: function () {
        return !defined(this._polylineCollection);
      },
    },

    /**
     * Gets or sets the condition specifying at what distance from the camera that this polyline will be displayed.
     * @memberof Polyline.prototype
     * @type {DistanceDisplayCondition}
     * @default undefined
     */
    distanceDisplayCondition: {
      get: function () {
        return this._distanceDisplayCondition;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (defined(value) && value.far <= value.near) {
          throw new DeveloperError(
            "far distance must be greater than near distance."
          );
        }
        //>>includeEnd('debug');
        if (
          !DistanceDisplayCondition.equals(value, this._distanceDisplayCondition)
        ) {
          this._distanceDisplayCondition = DistanceDisplayCondition.clone(
            value,
            this._distanceDisplayCondition
          );
          makeDirty$2(this, DISTANCE_DISPLAY_CONDITION$1);
        }
      },
    },
  });

  /**
   * @private
   */
  Polyline.prototype.update = function () {
    let modelMatrix = Matrix4.IDENTITY;
    if (defined(this._polylineCollection)) {
      modelMatrix = this._polylineCollection.modelMatrix;
    }

    const segmentPositionsLength = this._segments.positions.length;
    const segmentLengths = this._segments.lengths;

    const positionsChanged =
      this._propertiesChanged[POSITION_INDEX$5] > 0 ||
      this._propertiesChanged[POSITION_SIZE_INDEX$1] > 0;
    if (!Matrix4.equals(modelMatrix, this._modelMatrix) || positionsChanged) {
      this._segments = PolylinePipeline.wrapLongitude(
        this._actualPositions,
        modelMatrix
      );
      this._boundingVolumeWC = BoundingSphere.transform(
        this._boundingVolume,
        modelMatrix,
        this._boundingVolumeWC
      );
    }

    this._modelMatrix = Matrix4.clone(modelMatrix, this._modelMatrix);

    if (this._segments.positions.length !== segmentPositionsLength) {
      // number of positions changed
      makeDirty$2(this, POSITION_SIZE_INDEX$1);
    } else {
      const length = segmentLengths.length;
      for (let i = 0; i < length; ++i) {
        if (segmentLengths[i] !== this._segments.lengths[i]) {
          // indices changed
          makeDirty$2(this, POSITION_SIZE_INDEX$1);
          break;
        }
      }
    }
  };

  /**
   * @private
   */
  Polyline.prototype.getPickId = function (context) {
    if (!defined(this._pickId)) {
      this._pickId = context.createPickId({
        primitive: this,
        collection: this._polylineCollection,
        id: this._id,
      });
    }
    return this._pickId;
  };

  Polyline.prototype._clean = function () {
    this._dirty = false;
    const properties = this._propertiesChanged;
    for (let k = 0; k < NUMBER_OF_PROPERTIES$3 - 1; ++k) {
      properties[k] = 0;
    }
  };

  Polyline.prototype._destroy = function () {
    this._pickId = this._pickId && this._pickId.destroy();
    this._material = this._material && this._material.destroy();
    this._polylineCollection = undefined;
  };

  const SHOW_INDEX$4 = Polyline.SHOW_INDEX;
  const WIDTH_INDEX = Polyline.WIDTH_INDEX;
  const POSITION_INDEX$4 = Polyline.POSITION_INDEX;
  const MATERIAL_INDEX = Polyline.MATERIAL_INDEX;
  //POSITION_SIZE_INDEX is needed for when the polyline's position array changes size.
  //When it does, we need to recreate the indicesBuffer.
  const POSITION_SIZE_INDEX = Polyline.POSITION_SIZE_INDEX;
  const DISTANCE_DISPLAY_CONDITION = Polyline.DISTANCE_DISPLAY_CONDITION;
  const NUMBER_OF_PROPERTIES$2 = Polyline.NUMBER_OF_PROPERTIES;

  const attributeLocations$5 = {
    texCoordExpandAndBatchIndex: 0,
    position3DHigh: 1,
    position3DLow: 2,
    position2DHigh: 3,
    position2DLow: 4,
    prevPosition3DHigh: 5,
    prevPosition3DLow: 6,
    prevPosition2DHigh: 7,
    prevPosition2DLow: 8,
    nextPosition3DHigh: 9,
    nextPosition3DLow: 10,
    nextPosition2DHigh: 11,
    nextPosition2DLow: 12,
  };

  /**
   * A renderable collection of polylines.
   * <br /><br />
   * <div align="center">
   * <img src="Images/Polyline.png" width="400" height="300" /><br />
   * Example polylines
   * </div>
   * <br /><br />
   * Polylines are added and removed from the collection using {@link PolylineCollection#add}
   * and {@link PolylineCollection#remove}.
   *
   * @alias PolylineCollection
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] The 4x4 transformation matrix that transforms each polyline from model to world coordinates.
   * @param {Boolean} [options.debugShowBoundingVolume=false] For debugging only. Determines if this primitive's commands' bounding spheres are shown.
   * @param {Boolean} [options.show=true] Determines if the polylines in the collection will be shown.
   *
   * @performance For best performance, prefer a few collections, each with many polylines, to
   * many collections with only a few polylines each.  Organize collections so that polylines
   * with the same update frequency are in the same collection, i.e., polylines that do not
   * change should be in one collection; polylines that change every frame should be in another
   * collection; and so on.
   *
   * @see PolylineCollection#add
   * @see PolylineCollection#remove
   * @see Polyline
   * @see LabelCollection
   *
   * @example
   * // Create a polyline collection with two polylines
   * const polylines = new Cesium.PolylineCollection();
   * polylines.add({
   *   positions : Cesium.Cartesian3.fromDegreesArray([
   *     -75.10, 39.57,
   *     -77.02, 38.53,
   *     -80.50, 35.14,
   *     -80.12, 25.46]),
   *   width : 2
   * });
   *
   * polylines.add({
   *   positions : Cesium.Cartesian3.fromDegreesArray([
   *     -73.10, 37.57,
   *     -75.02, 36.53,
   *     -78.50, 33.14,
   *     -78.12, 23.46]),
   *   width : 4
   * });
   */
  function PolylineCollection(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    /**
     * Determines if polylines in this collection will be shown.
     *
     * @type {Boolean}
     * @default true
     */
    this.show = defaultValue(options.show, true);

    /**
     * The 4x4 transformation matrix that transforms each polyline in this collection from model to world coordinates.
     * When this is the identity matrix, the polylines are drawn in world coordinates, i.e., Earth's WGS84 coordinates.
     * Local reference frames can be used by providing a different transformation matrix, like that returned
     * by {@link Transforms.eastNorthUpToFixedFrame}.
     *
     * @type {Matrix4}
     * @default {@link Matrix4.IDENTITY}
     */
    this.modelMatrix = Matrix4.clone(
      defaultValue(options.modelMatrix, Matrix4.IDENTITY)
    );
    this._modelMatrix = Matrix4.clone(Matrix4.IDENTITY);

    /**
     * This property is for debugging only; it is not for production use nor is it optimized.
     * <p>
     * Draws the bounding sphere for each draw command in the primitive.
     * </p>
     *
     * @type {Boolean}
     *
     * @default false
     */
    this.debugShowBoundingVolume = defaultValue(
      options.debugShowBoundingVolume,
      false
    );

    this._opaqueRS = undefined;
    this._translucentRS = undefined;

    this._colorCommands = [];

    this._polylinesUpdated = false;
    this._polylinesRemoved = false;
    this._createVertexArray = false;
    this._propertiesChanged = new Uint32Array(NUMBER_OF_PROPERTIES$2);
    this._polylines = [];
    this._polylineBuckets = {};

    // The buffer usage is determined based on the usage of the attribute over time.
    this._positionBufferUsage = {
      bufferUsage: BufferUsage$1.STATIC_DRAW,
      frameCount: 0,
    };

    this._mode = undefined;

    this._polylinesToUpdate = [];
    this._vertexArrays = [];
    this._positionBuffer = undefined;
    this._texCoordExpandAndBatchIndexBuffer = undefined;

    this._batchTable = undefined;
    this._createBatchTable = false;

    // Only used by Vector3DTilePoints
    this._useHighlightColor = false;
    this._highlightColor = Color.clone(Color.WHITE);

    const that = this;
    this._uniformMap = {
      u_highlightColor: function () {
        return that._highlightColor;
      },
    };
  }

  Object.defineProperties(PolylineCollection.prototype, {
    /**
     * Returns the number of polylines in this collection.  This is commonly used with
     * {@link PolylineCollection#get} to iterate over all the polylines
     * in the collection.
     * @memberof PolylineCollection.prototype
     * @type {Number}
     */
    length: {
      get: function () {
        removePolylines(this);
        return this._polylines.length;
      },
    },
  });

  /**
       * Creates and adds a polyline with the specified initial properties to the collection.
       * The added polyline is returned so it can be modified or removed from the collection later.
       *
       * @param {Object}[options] A template describing the polyline's properties as shown in Example 1.
       * @returns {Polyline} The polyline that was added to the collection.
       *
       * @performance After calling <code>add</code>, {@link PolylineCollection#update} is called and
       * the collection's vertex buffer is rewritten - an <code>O(n)</code> operation that also incurs CPU to GPU overhead.
       * For best performance, add as many polylines as possible before calling <code>update</code>.
       *
       * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
       *
       *
       * @example
       * // Example 1:  Add a polyline, specifying all the default values.
       * const p = polylines.add({
       *   show : true,
       *   positions : ellipsoid.cartographicArrayToCartesianArray([
             Cesium.Cartographic.fromDegrees(-75.10, 39.57),
             Cesium.Cartographic.fromDegrees(-77.02, 38.53)]),
       *   width : 1
       * });
       *
       * @see PolylineCollection#remove
       * @see PolylineCollection#removeAll
       * @see PolylineCollection#update
       */
  PolylineCollection.prototype.add = function (options) {
    const p = new Polyline(options, this);
    p._index = this._polylines.length;
    this._polylines.push(p);
    this._createVertexArray = true;
    this._createBatchTable = true;
    return p;
  };

  /**
   * Removes a polyline from the collection.
   *
   * @param {Polyline} polyline The polyline to remove.
   * @returns {Boolean} <code>true</code> if the polyline was removed; <code>false</code> if the polyline was not found in the collection.
   *
   * @performance After calling <code>remove</code>, {@link PolylineCollection#update} is called and
   * the collection's vertex buffer is rewritten - an <code>O(n)</code> operation that also incurs CPU to GPU overhead.
   * For best performance, remove as many polylines as possible before calling <code>update</code>.
   * If you intend to temporarily hide a polyline, it is usually more efficient to call
   * {@link Polyline#show} instead of removing and re-adding the polyline.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * const p = polylines.add(...);
   * polylines.remove(p);  // Returns true
   *
   * @see PolylineCollection#add
   * @see PolylineCollection#removeAll
   * @see PolylineCollection#update
   * @see Polyline#show
   */
  PolylineCollection.prototype.remove = function (polyline) {
    if (this.contains(polyline)) {
      this._polylinesRemoved = true;
      this._createVertexArray = true;
      this._createBatchTable = true;
      if (defined(polyline._bucket)) {
        const bucket = polyline._bucket;
        bucket.shaderProgram =
          bucket.shaderProgram && bucket.shaderProgram.destroy();
      }
      polyline._destroy();
      return true;
    }

    return false;
  };

  /**
   * Removes all polylines from the collection.
   *
   * @performance <code>O(n)</code>.  It is more efficient to remove all the polylines
   * from a collection and then add new ones than to create a new collection entirely.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * polylines.add(...);
   * polylines.add(...);
   * polylines.removeAll();
   *
   * @see PolylineCollection#add
   * @see PolylineCollection#remove
   * @see PolylineCollection#update
   */
  PolylineCollection.prototype.removeAll = function () {
    releaseShaders(this);
    destroyPolylines(this);
    this._polylineBuckets = {};
    this._polylinesRemoved = false;
    this._polylines.length = 0;
    this._polylinesToUpdate.length = 0;
    this._createVertexArray = true;
  };

  /**
   * Determines if this collection contains the specified polyline.
   *
   * @param {Polyline} polyline The polyline to check for.
   * @returns {Boolean} true if this collection contains the polyline, false otherwise.
   *
   * @see PolylineCollection#get
   */
  PolylineCollection.prototype.contains = function (polyline) {
    return defined(polyline) && polyline._polylineCollection === this;
  };

  /**
   * Returns the polyline in the collection at the specified index.  Indices are zero-based
   * and increase as polylines are added.  Removing a polyline shifts all polylines after
   * it to the left, changing their indices.  This function is commonly used with
   * {@link PolylineCollection#length} to iterate over all the polylines
   * in the collection.
   *
   * @param {Number} index The zero-based index of the polyline.
   * @returns {Polyline} The polyline at the specified index.
   *
   * @performance If polylines were removed from the collection and
   * {@link PolylineCollection#update} was not called, an implicit <code>O(n)</code>
   * operation is performed.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @example
   * // Toggle the show property of every polyline in the collection
   * const len = polylines.length;
   * for (let i = 0; i < len; ++i) {
   *   const p = polylines.get(i);
   *   p.show = !p.show;
   * }
   *
   * @see PolylineCollection#length
   */
  PolylineCollection.prototype.get = function (index) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(index)) {
      throw new DeveloperError("index is required.");
    }
    //>>includeEnd('debug');

    removePolylines(this);
    return this._polylines[index];
  };

  function createBatchTable(collection, context) {
    if (defined(collection._batchTable)) {
      collection._batchTable.destroy();
    }

    const attributes = [
      {
        functionName: "batchTable_getWidthAndShow",
        componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
        componentsPerAttribute: 2,
      },
      {
        functionName: "batchTable_getPickColor",
        componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
        componentsPerAttribute: 4,
        normalize: true,
      },
      {
        functionName: "batchTable_getCenterHigh",
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 3,
      },
      {
        functionName: "batchTable_getCenterLowAndRadius",
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 4,
      },
      {
        functionName: "batchTable_getDistanceDisplayCondition",
        componentDatatype: ComponentDatatype$1.FLOAT,
        componentsPerAttribute: 2,
      },
    ];

    collection._batchTable = new BatchTable(
      context,
      attributes,
      collection._polylines.length
    );
  }

  const scratchUpdatePolylineEncodedCartesian = new EncodedCartesian3();
  const scratchUpdatePolylineCartesian4 = new Cartesian4();
  const scratchNearFarCartesian2 = new Cartesian2();

  /**
   * Called when {@link Viewer} or {@link CesiumWidget} render the scene to
   * get the draw commands needed to render this primitive.
   * <p>
   * Do not call this function directly.  This is documented just to
   * list the exceptions that may be propagated when the scene is rendered:
   * </p>
   *
   * @exception {RuntimeError} Vertex texture fetch support is required to render primitives with per-instance attributes. The maximum number of vertex texture image units must be greater than zero.
   */
  PolylineCollection.prototype.update = function (frameState) {
    removePolylines(this);

    if (this._polylines.length === 0 || !this.show) {
      return;
    }

    updateMode$1(this, frameState);

    const context = frameState.context;
    const projection = frameState.mapProjection;
    let polyline;
    let properties = this._propertiesChanged;

    if (this._createBatchTable) {
      if (ContextLimits.maximumVertexTextureImageUnits === 0) {
        throw new RuntimeError(
          "Vertex texture fetch support is required to render polylines. The maximum number of vertex texture image units must be greater than zero."
        );
      }
      createBatchTable(this, context);
      this._createBatchTable = false;
    }

    if (this._createVertexArray || computeNewBuffersUsage(this)) {
      createVertexArrays(this, context, projection);
    } else if (this._polylinesUpdated) {
      // Polylines were modified, but no polylines were added or removed.
      const polylinesToUpdate = this._polylinesToUpdate;
      if (this._mode !== SceneMode$1.SCENE3D) {
        const updateLength = polylinesToUpdate.length;
        for (let i = 0; i < updateLength; ++i) {
          polyline = polylinesToUpdate[i];
          polyline.update();
        }
      }

      // if a polyline's positions size changes, we need to recreate the vertex arrays and vertex buffers because the indices will be different.
      // if a polyline's material changes, we need to recreate the VAOs and VBOs because they will be batched differently.
      if (properties[POSITION_SIZE_INDEX] || properties[MATERIAL_INDEX]) {
        createVertexArrays(this, context, projection);
      } else {
        const length = polylinesToUpdate.length;
        const polylineBuckets = this._polylineBuckets;
        for (let ii = 0; ii < length; ++ii) {
          polyline = polylinesToUpdate[ii];
          properties = polyline._propertiesChanged;
          const bucket = polyline._bucket;
          let index = 0;
          for (const x in polylineBuckets) {
            if (polylineBuckets.hasOwnProperty(x)) {
              if (polylineBuckets[x] === bucket) {
                if (properties[POSITION_INDEX$4]) {
                  bucket.writeUpdate(
                    index,
                    polyline,
                    this._positionBuffer,
                    projection
                  );
                }
                break;
              }
              index += polylineBuckets[x].lengthOfPositions;
            }
          }

          if (properties[SHOW_INDEX$4] || properties[WIDTH_INDEX]) {
            this._batchTable.setBatchedAttribute(
              polyline._index,
              0,
              new Cartesian2(polyline._width, polyline._show)
            );
          }

          if (this._batchTable.attributes.length > 2) {
            if (properties[POSITION_INDEX$4] || properties[POSITION_SIZE_INDEX]) {
              const boundingSphere =
                frameState.mode === SceneMode$1.SCENE2D
                  ? polyline._boundingVolume2D
                  : polyline._boundingVolumeWC;
              const encodedCenter = EncodedCartesian3.fromCartesian(
                boundingSphere.center,
                scratchUpdatePolylineEncodedCartesian
              );
              const low = Cartesian4.fromElements(
                encodedCenter.low.x,
                encodedCenter.low.y,
                encodedCenter.low.z,
                boundingSphere.radius,
                scratchUpdatePolylineCartesian4
              );
              this._batchTable.setBatchedAttribute(
                polyline._index,
                2,
                encodedCenter.high
              );
              this._batchTable.setBatchedAttribute(polyline._index, 3, low);
            }

            if (properties[DISTANCE_DISPLAY_CONDITION]) {
              const nearFarCartesian = scratchNearFarCartesian2;
              nearFarCartesian.x = 0.0;
              nearFarCartesian.y = Number.MAX_VALUE;

              const distanceDisplayCondition = polyline.distanceDisplayCondition;
              if (defined(distanceDisplayCondition)) {
                nearFarCartesian.x = distanceDisplayCondition.near;
                nearFarCartesian.y = distanceDisplayCondition.far;
              }

              this._batchTable.setBatchedAttribute(
                polyline._index,
                4,
                nearFarCartesian
              );
            }
          }

          polyline._clean();
        }
      }
      polylinesToUpdate.length = 0;
      this._polylinesUpdated = false;
    }

    properties = this._propertiesChanged;
    for (let k = 0; k < NUMBER_OF_PROPERTIES$2; ++k) {
      properties[k] = 0;
    }

    let modelMatrix = Matrix4.IDENTITY;
    if (frameState.mode === SceneMode$1.SCENE3D) {
      modelMatrix = this.modelMatrix;
    }

    const pass = frameState.passes;
    const useDepthTest = frameState.morphTime !== 0.0;

    if (
      !defined(this._opaqueRS) ||
      this._opaqueRS.depthTest.enabled !== useDepthTest
    ) {
      this._opaqueRS = RenderState.fromCache({
        depthMask: useDepthTest,
        depthTest: {
          enabled: useDepthTest,
        },
      });
    }

    if (
      !defined(this._translucentRS) ||
      this._translucentRS.depthTest.enabled !== useDepthTest
    ) {
      this._translucentRS = RenderState.fromCache({
        blending: BlendingState$1.ALPHA_BLEND,
        depthMask: !useDepthTest,
        depthTest: {
          enabled: useDepthTest,
        },
      });
    }

    this._batchTable.update(frameState);

    if (pass.render || pass.pick) {
      const colorList = this._colorCommands;
      createCommandLists(this, frameState, colorList, modelMatrix);
    }
  };

  const boundingSphereScratch$2 = new BoundingSphere();
  const boundingSphereScratch2 = new BoundingSphere();

  function createCommandLists(
    polylineCollection,
    frameState,
    commands,
    modelMatrix
  ) {
    const context = frameState.context;
    const commandList = frameState.commandList;

    const commandsLength = commands.length;
    let commandIndex = 0;
    let cloneBoundingSphere = true;

    const vertexArrays = polylineCollection._vertexArrays;
    const debugShowBoundingVolume = polylineCollection.debugShowBoundingVolume;

    const batchTable = polylineCollection._batchTable;
    const uniformCallback = batchTable.getUniformMapCallback();

    const length = vertexArrays.length;
    for (let m = 0; m < length; ++m) {
      const va = vertexArrays[m];
      const buckets = va.buckets;
      const bucketLength = buckets.length;

      for (let n = 0; n < bucketLength; ++n) {
        const bucketLocator = buckets[n];

        let offset = bucketLocator.offset;
        const sp = bucketLocator.bucket.shaderProgram;

        const polylines = bucketLocator.bucket.polylines;
        const polylineLength = polylines.length;
        let currentId;
        let currentMaterial;
        let count = 0;
        let command;
        let uniformMap;

        for (let s = 0; s < polylineLength; ++s) {
          const polyline = polylines[s];
          const mId = createMaterialId(polyline._material);
          if (mId !== currentId) {
            if (defined(currentId) && count > 0) {
              const translucent = currentMaterial.isTranslucent();

              if (commandIndex >= commandsLength) {
                command = new DrawCommand({
                  owner: polylineCollection,
                });
                commands.push(command);
              } else {
                command = commands[commandIndex];
              }

              ++commandIndex;

              uniformMap = combine$2(
                uniformCallback(currentMaterial._uniforms),
                polylineCollection._uniformMap
              );

              command.boundingVolume = BoundingSphere.clone(
                boundingSphereScratch$2,
                command.boundingVolume
              );
              command.modelMatrix = modelMatrix;
              command.shaderProgram = sp;
              command.vertexArray = va.va;
              command.renderState = translucent
                ? polylineCollection._translucentRS
                : polylineCollection._opaqueRS;
              command.pass = translucent ? Pass$1.TRANSLUCENT : Pass$1.OPAQUE;
              command.debugShowBoundingVolume = debugShowBoundingVolume;
              command.pickId = "v_pickColor";

              command.uniformMap = uniformMap;
              command.count = count;
              command.offset = offset;

              offset += count;
              count = 0;
              cloneBoundingSphere = true;

              commandList.push(command);
            }

            currentMaterial = polyline._material;
            currentMaterial.update(context);
            currentId = mId;
          }

          const locators = polyline._locatorBuckets;
          const locatorLength = locators.length;
          for (let t = 0; t < locatorLength; ++t) {
            const locator = locators[t];
            if (locator.locator === bucketLocator) {
              count += locator.count;
            }
          }

          let boundingVolume;
          if (frameState.mode === SceneMode$1.SCENE3D) {
            boundingVolume = polyline._boundingVolumeWC;
          } else if (frameState.mode === SceneMode$1.COLUMBUS_VIEW) {
            boundingVolume = polyline._boundingVolume2D;
          } else if (frameState.mode === SceneMode$1.SCENE2D) {
            if (defined(polyline._boundingVolume2D)) {
              boundingVolume = BoundingSphere.clone(
                polyline._boundingVolume2D,
                boundingSphereScratch2
              );
              boundingVolume.center.x = 0.0;
            }
          } else if (
            defined(polyline._boundingVolumeWC) &&
            defined(polyline._boundingVolume2D)
          ) {
            boundingVolume = BoundingSphere.union(
              polyline._boundingVolumeWC,
              polyline._boundingVolume2D,
              boundingSphereScratch2
            );
          }

          if (cloneBoundingSphere) {
            cloneBoundingSphere = false;
            BoundingSphere.clone(boundingVolume, boundingSphereScratch$2);
          } else {
            BoundingSphere.union(
              boundingVolume,
              boundingSphereScratch$2,
              boundingSphereScratch$2
            );
          }
        }

        if (defined(currentId) && count > 0) {
          if (commandIndex >= commandsLength) {
            command = new DrawCommand({
              owner: polylineCollection,
            });
            commands.push(command);
          } else {
            command = commands[commandIndex];
          }

          ++commandIndex;

          uniformMap = combine$2(
            uniformCallback(currentMaterial._uniforms),
            polylineCollection._uniformMap
          );

          command.boundingVolume = BoundingSphere.clone(
            boundingSphereScratch$2,
            command.boundingVolume
          );
          command.modelMatrix = modelMatrix;
          command.shaderProgram = sp;
          command.vertexArray = va.va;
          command.renderState = currentMaterial.isTranslucent()
            ? polylineCollection._translucentRS
            : polylineCollection._opaqueRS;
          command.pass = currentMaterial.isTranslucent()
            ? Pass$1.TRANSLUCENT
            : Pass$1.OPAQUE;
          command.debugShowBoundingVolume = debugShowBoundingVolume;
          command.pickId = "v_pickColor";

          command.uniformMap = uniformMap;
          command.count = count;
          command.offset = offset;

          cloneBoundingSphere = true;

          commandList.push(command);
        }

        currentId = undefined;
      }
    }

    commands.length = commandIndex;
  }

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see PolylineCollection#destroy
   */
  PolylineCollection.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * polylines = polylines && polylines.destroy();
   *
   * @see PolylineCollection#isDestroyed
   */
  PolylineCollection.prototype.destroy = function () {
    destroyVertexArrays(this);
    releaseShaders(this);
    destroyPolylines(this);
    this._batchTable = this._batchTable && this._batchTable.destroy();
    return destroyObject(this);
  };

  function computeNewBuffersUsage(collection) {
    let usageChanged = false;
    const properties = collection._propertiesChanged;
    const bufferUsage = collection._positionBufferUsage;
    if (properties[POSITION_INDEX$4]) {
      if (bufferUsage.bufferUsage !== BufferUsage$1.STREAM_DRAW) {
        usageChanged = true;
        bufferUsage.bufferUsage = BufferUsage$1.STREAM_DRAW;
        bufferUsage.frameCount = 100;
      } else {
        bufferUsage.frameCount = 100;
      }
    } else if (bufferUsage.bufferUsage !== BufferUsage$1.STATIC_DRAW) {
      if (bufferUsage.frameCount === 0) {
        usageChanged = true;
        bufferUsage.bufferUsage = BufferUsage$1.STATIC_DRAW;
      } else {
        bufferUsage.frameCount--;
      }
    }

    return usageChanged;
  }

  const emptyVertexBuffer = [0.0, 0.0, 0.0];

  function createVertexArrays(collection, context, projection) {
    collection._createVertexArray = false;
    releaseShaders(collection);
    destroyVertexArrays(collection);
    sortPolylinesIntoBuckets(collection);

    //stores all of the individual indices arrays.
    const totalIndices = [[]];
    let indices = totalIndices[0];

    const batchTable = collection._batchTable;
    const useHighlightColor = collection._useHighlightColor;

    //used to determine the vertexBuffer offset if the indicesArray goes over 64k.
    //if it's the same polyline while it goes over 64k, the offset needs to backtrack componentsPerAttribute * componentDatatype bytes
    //so that the polyline looks contiguous.
    //if the polyline ends at the 64k mark, then the offset is just 64k * componentsPerAttribute * componentDatatype
    const vertexBufferOffset = [0];
    let offset = 0;
    const vertexArrayBuckets = [[]];
    let totalLength = 0;
    const polylineBuckets = collection._polylineBuckets;
    let x;
    let bucket;
    for (x in polylineBuckets) {
      if (polylineBuckets.hasOwnProperty(x)) {
        bucket = polylineBuckets[x];
        bucket.updateShader(context, batchTable, useHighlightColor);
        totalLength += bucket.lengthOfPositions;
      }
    }

    if (totalLength > 0) {
      const mode = collection._mode;

      const positionArray = new Float32Array(6 * totalLength * 3);
      const texCoordExpandAndBatchIndexArray = new Float32Array(totalLength * 4);
      let position3DArray;

      let positionIndex = 0;
      let colorIndex = 0;
      let texCoordExpandAndBatchIndexIndex = 0;
      for (x in polylineBuckets) {
        if (polylineBuckets.hasOwnProperty(x)) {
          bucket = polylineBuckets[x];
          bucket.write(
            positionArray,
            texCoordExpandAndBatchIndexArray,
            positionIndex,
            colorIndex,
            texCoordExpandAndBatchIndexIndex,
            batchTable,
            context,
            projection
          );

          if (mode === SceneMode$1.MORPHING) {
            if (!defined(position3DArray)) {
              position3DArray = new Float32Array(6 * totalLength * 3);
            }
            bucket.writeForMorph(position3DArray, positionIndex);
          }

          const bucketLength = bucket.lengthOfPositions;
          positionIndex += 6 * bucketLength * 3;
          colorIndex += bucketLength * 4;
          texCoordExpandAndBatchIndexIndex += bucketLength * 4;
          offset = bucket.updateIndices(
            totalIndices,
            vertexBufferOffset,
            vertexArrayBuckets,
            offset
          );
        }
      }

      const positionBufferUsage = collection._positionBufferUsage.bufferUsage;
      const texCoordExpandAndBatchIndexBufferUsage = BufferUsage$1.STATIC_DRAW;

      collection._positionBuffer = Buffer$1.createVertexBuffer({
        context: context,
        typedArray: positionArray,
        usage: positionBufferUsage,
      });
      let position3DBuffer;
      if (defined(position3DArray)) {
        position3DBuffer = Buffer$1.createVertexBuffer({
          context: context,
          typedArray: position3DArray,
          usage: positionBufferUsage,
        });
      }
      collection._texCoordExpandAndBatchIndexBuffer = Buffer$1.createVertexBuffer({
        context: context,
        typedArray: texCoordExpandAndBatchIndexArray,
        usage: texCoordExpandAndBatchIndexBufferUsage,
      });

      const positionSizeInBytes = 3 * Float32Array.BYTES_PER_ELEMENT;
      const texCoordExpandAndBatchIndexSizeInBytes =
        4 * Float32Array.BYTES_PER_ELEMENT;

      let vbo = 0;
      const numberOfIndicesArrays = totalIndices.length;
      for (let k = 0; k < numberOfIndicesArrays; ++k) {
        indices = totalIndices[k];

        if (indices.length > 0) {
          const indicesArray = new Uint16Array(indices);
          const indexBuffer = Buffer$1.createIndexBuffer({
            context: context,
            typedArray: indicesArray,
            usage: BufferUsage$1.STATIC_DRAW,
            indexDatatype: IndexDatatype$1.UNSIGNED_SHORT,
          });

          vbo += vertexBufferOffset[k];

          const positionHighOffset =
            6 *
            (k * (positionSizeInBytes * CesiumMath.SIXTY_FOUR_KILOBYTES) -
              vbo * positionSizeInBytes); //componentsPerAttribute(3) * componentDatatype(4)
          const positionLowOffset = positionSizeInBytes + positionHighOffset;
          const prevPositionHighOffset = positionSizeInBytes + positionLowOffset;
          const prevPositionLowOffset =
            positionSizeInBytes + prevPositionHighOffset;
          const nextPositionHighOffset =
            positionSizeInBytes + prevPositionLowOffset;
          const nextPositionLowOffset =
            positionSizeInBytes + nextPositionHighOffset;
          const vertexTexCoordExpandAndBatchIndexBufferOffset =
            k *
              (texCoordExpandAndBatchIndexSizeInBytes *
                CesiumMath.SIXTY_FOUR_KILOBYTES) -
            vbo * texCoordExpandAndBatchIndexSizeInBytes;

          const attributes = [
            {
              index: attributeLocations$5.position3DHigh,
              componentsPerAttribute: 3,
              componentDatatype: ComponentDatatype$1.FLOAT,
              offsetInBytes: positionHighOffset,
              strideInBytes: 6 * positionSizeInBytes,
            },
            {
              index: attributeLocations$5.position3DLow,
              componentsPerAttribute: 3,
              componentDatatype: ComponentDatatype$1.FLOAT,
              offsetInBytes: positionLowOffset,
              strideInBytes: 6 * positionSizeInBytes,
            },
            {
              index: attributeLocations$5.position2DHigh,
              componentsPerAttribute: 3,
              componentDatatype: ComponentDatatype$1.FLOAT,
              offsetInBytes: positionHighOffset,
              strideInBytes: 6 * positionSizeInBytes,
            },
            {
              index: attributeLocations$5.position2DLow,
              componentsPerAttribute: 3,
              componentDatatype: ComponentDatatype$1.FLOAT,
              offsetInBytes: positionLowOffset,
              strideInBytes: 6 * positionSizeInBytes,
            },
            {
              index: attributeLocations$5.prevPosition3DHigh,
              componentsPerAttribute: 3,
              componentDatatype: ComponentDatatype$1.FLOAT,
              offsetInBytes: prevPositionHighOffset,
              strideInBytes: 6 * positionSizeInBytes,
            },
            {
              index: attributeLocations$5.prevPosition3DLow,
              componentsPerAttribute: 3,
              componentDatatype: ComponentDatatype$1.FLOAT,
              offsetInBytes: prevPositionLowOffset,
              strideInBytes: 6 * positionSizeInBytes,
            },
            {
              index: attributeLocations$5.prevPosition2DHigh,
              componentsPerAttribute: 3,
              componentDatatype: ComponentDatatype$1.FLOAT,
              offsetInBytes: prevPositionHighOffset,
              strideInBytes: 6 * positionSizeInBytes,
            },
            {
              index: attributeLocations$5.prevPosition2DLow,
              componentsPerAttribute: 3,
              componentDatatype: ComponentDatatype$1.FLOAT,
              offsetInBytes: prevPositionLowOffset,
              strideInBytes: 6 * positionSizeInBytes,
            },
            {
              index: attributeLocations$5.nextPosition3DHigh,
              componentsPerAttribute: 3,
              componentDatatype: ComponentDatatype$1.FLOAT,
              offsetInBytes: nextPositionHighOffset,
              strideInBytes: 6 * positionSizeInBytes,
            },
            {
              index: attributeLocations$5.nextPosition3DLow,
              componentsPerAttribute: 3,
              componentDatatype: ComponentDatatype$1.FLOAT,
              offsetInBytes: nextPositionLowOffset,
              strideInBytes: 6 * positionSizeInBytes,
            },
            {
              index: attributeLocations$5.nextPosition2DHigh,
              componentsPerAttribute: 3,
              componentDatatype: ComponentDatatype$1.FLOAT,
              offsetInBytes: nextPositionHighOffset,
              strideInBytes: 6 * positionSizeInBytes,
            },
            {
              index: attributeLocations$5.nextPosition2DLow,
              componentsPerAttribute: 3,
              componentDatatype: ComponentDatatype$1.FLOAT,
              offsetInBytes: nextPositionLowOffset,
              strideInBytes: 6 * positionSizeInBytes,
            },
            {
              index: attributeLocations$5.texCoordExpandAndBatchIndex,
              componentsPerAttribute: 4,
              componentDatatype: ComponentDatatype$1.FLOAT,
              vertexBuffer: collection._texCoordExpandAndBatchIndexBuffer,
              offsetInBytes: vertexTexCoordExpandAndBatchIndexBufferOffset,
            },
          ];

          let bufferProperty3D;
          let buffer3D;
          let buffer2D;
          let bufferProperty2D;

          if (mode === SceneMode$1.SCENE3D) {
            buffer3D = collection._positionBuffer;
            bufferProperty3D = "vertexBuffer";
            buffer2D = emptyVertexBuffer;
            bufferProperty2D = "value";
          } else if (
            mode === SceneMode$1.SCENE2D ||
            mode === SceneMode$1.COLUMBUS_VIEW
          ) {
            buffer3D = emptyVertexBuffer;
            bufferProperty3D = "value";
            buffer2D = collection._positionBuffer;
            bufferProperty2D = "vertexBuffer";
          } else {
            buffer3D = position3DBuffer;
            bufferProperty3D = "vertexBuffer";
            buffer2D = collection._positionBuffer;
            bufferProperty2D = "vertexBuffer";
          }

          attributes[0][bufferProperty3D] = buffer3D;
          attributes[1][bufferProperty3D] = buffer3D;
          attributes[2][bufferProperty2D] = buffer2D;
          attributes[3][bufferProperty2D] = buffer2D;
          attributes[4][bufferProperty3D] = buffer3D;
          attributes[5][bufferProperty3D] = buffer3D;
          attributes[6][bufferProperty2D] = buffer2D;
          attributes[7][bufferProperty2D] = buffer2D;
          attributes[8][bufferProperty3D] = buffer3D;
          attributes[9][bufferProperty3D] = buffer3D;
          attributes[10][bufferProperty2D] = buffer2D;
          attributes[11][bufferProperty2D] = buffer2D;

          const va = new VertexArray({
            context: context,
            attributes: attributes,
            indexBuffer: indexBuffer,
          });
          collection._vertexArrays.push({
            va: va,
            buckets: vertexArrayBuckets[k],
          });
        }
      }
    }
  }

  function replacer(key, value) {
    if (value instanceof Texture) {
      return value.id;
    }

    return value;
  }

  const scratchUniformArray = [];
  function createMaterialId(material) {
    const uniforms = Material$4._uniformList[material.type];
    const length = uniforms.length;
    scratchUniformArray.length = 2.0 * length;

    let index = 0;
    for (let i = 0; i < length; ++i) {
      const uniform = uniforms[i];
      scratchUniformArray[index] = uniform;
      scratchUniformArray[index + 1] = material._uniforms[uniform]();
      index += 2;
    }

    return `${material.type}:${JSON.stringify(scratchUniformArray, replacer)}`;
  }

  function sortPolylinesIntoBuckets(collection) {
    const mode = collection._mode;
    const modelMatrix = collection._modelMatrix;

    const polylineBuckets = (collection._polylineBuckets = {});
    const polylines = collection._polylines;
    const length = polylines.length;
    for (let i = 0; i < length; ++i) {
      const p = polylines[i];
      if (p._actualPositions.length > 1) {
        p.update();
        const material = p.material;
        let value = polylineBuckets[material.type];
        if (!defined(value)) {
          value = polylineBuckets[material.type] = new PolylineBucket(
            material,
            mode,
            modelMatrix
          );
        }
        value.addPolyline(p);
      }
    }
  }

  function updateMode$1(collection, frameState) {
    const mode = frameState.mode;

    if (
      collection._mode !== mode ||
      !Matrix4.equals(collection._modelMatrix, collection.modelMatrix)
    ) {
      collection._mode = mode;
      collection._modelMatrix = Matrix4.clone(collection.modelMatrix);
      collection._createVertexArray = true;
    }
  }

  function removePolylines(collection) {
    if (collection._polylinesRemoved) {
      collection._polylinesRemoved = false;
      const definedPolylines = [];
      const definedPolylinesToUpdate = [];
      let polyIndex = 0;
      let polyline;

      const length = collection._polylines.length;
      for (let i = 0; i < length; ++i) {
        polyline = collection._polylines[i];
        if (!polyline.isDestroyed) {
          polyline._index = polyIndex++;
          definedPolylinesToUpdate.push(polyline);
          definedPolylines.push(polyline);
        }
      }

      collection._polylines = definedPolylines;
      collection._polylinesToUpdate = definedPolylinesToUpdate;
    }
  }

  function releaseShaders(collection) {
    const polylines = collection._polylines;
    const length = polylines.length;
    for (let i = 0; i < length; ++i) {
      if (!polylines[i].isDestroyed) {
        const bucket = polylines[i]._bucket;
        if (defined(bucket)) {
          bucket.shaderProgram =
            bucket.shaderProgram && bucket.shaderProgram.destroy();
        }
      }
    }
  }

  function destroyVertexArrays(collection) {
    const length = collection._vertexArrays.length;
    for (let t = 0; t < length; ++t) {
      collection._vertexArrays[t].va.destroy();
    }
    collection._vertexArrays.length = 0;
  }

  PolylineCollection.prototype._updatePolyline = function (
    polyline,
    propertyChanged
  ) {
    this._polylinesUpdated = true;
    if (!polyline._dirty) {
      this._polylinesToUpdate.push(polyline);
    }
    ++this._propertiesChanged[propertyChanged];
  };

  function destroyPolylines(collection) {
    const polylines = collection._polylines;
    const length = polylines.length;
    for (let i = 0; i < length; ++i) {
      if (!polylines[i].isDestroyed) {
        polylines[i]._destroy();
      }
    }
  }

  function VertexArrayBucketLocator(count, offset, bucket) {
    this.count = count;
    this.offset = offset;
    this.bucket = bucket;
  }

  function PolylineBucket(material, mode, modelMatrix) {
    this.polylines = [];
    this.lengthOfPositions = 0;
    this.material = material;
    this.shaderProgram = undefined;
    this.mode = mode;
    this.modelMatrix = modelMatrix;
  }

  PolylineBucket.prototype.addPolyline = function (p) {
    const polylines = this.polylines;
    polylines.push(p);
    p._actualLength = this.getPolylinePositionsLength(p);
    this.lengthOfPositions += p._actualLength;
    p._bucket = this;
  };

  PolylineBucket.prototype.updateShader = function (
    context,
    batchTable,
    useHighlightColor
  ) {
    if (defined(this.shaderProgram)) {
      return;
    }

    const defines = ["DISTANCE_DISPLAY_CONDITION"];
    if (useHighlightColor) {
      defines.push("VECTOR_TILE");
    }

    // Check for use of v_polylineAngle in material shader
    if (
      this.material.shaderSource.search(/varying\s+float\s+v_polylineAngle;/g) !==
      -1
    ) {
      defines.push("POLYLINE_DASH");
    }

    if (!FeatureDetection.isInternetExplorer()) {
      defines.push("CLIP_POLYLINE");
    }

    const fs = new ShaderSource({
      defines: defines,
      sources: [
        "varying vec4 v_pickColor;\n",
        this.material.shaderSource,
        PolylineFS$1,
      ],
    });

    const vsSource = batchTable.getVertexShaderCallback()(PolylineVS);
    const vs = new ShaderSource({
      defines: defines,
      sources: [PolylineCommon, vsSource],
    });

    this.shaderProgram = ShaderProgram.fromCache({
      context: context,
      vertexShaderSource: vs,
      fragmentShaderSource: fs,
      attributeLocations: attributeLocations$5,
    });
  };

  function intersectsIDL(polyline) {
    return (
      Cartesian3.dot(Cartesian3.UNIT_X, polyline._boundingVolume.center) < 0 ||
      polyline._boundingVolume.intersectPlane(Plane.ORIGIN_ZX_PLANE) ===
        Intersect$1.INTERSECTING
    );
  }

  PolylineBucket.prototype.getPolylinePositionsLength = function (polyline) {
    let length;
    if (this.mode === SceneMode$1.SCENE3D || !intersectsIDL(polyline)) {
      length = polyline._actualPositions.length;
      return length * 4.0 - 4.0;
    }

    let count = 0;
    const segmentLengths = polyline._segments.lengths;
    length = segmentLengths.length;
    for (let i = 0; i < length; ++i) {
      count += segmentLengths[i] * 4.0 - 4.0;
    }

    return count;
  };

  const scratchWritePosition = new Cartesian3();
  const scratchWritePrevPosition = new Cartesian3();
  const scratchWriteNextPosition = new Cartesian3();
  const scratchWriteVector = new Cartesian3();
  const scratchPickColorCartesian = new Cartesian4();
  const scratchWidthShowCartesian = new Cartesian2();

  PolylineBucket.prototype.write = function (
    positionArray,
    texCoordExpandAndBatchIndexArray,
    positionIndex,
    colorIndex,
    texCoordExpandAndBatchIndexIndex,
    batchTable,
    context,
    projection
  ) {
    const mode = this.mode;
    const maxLon = projection.ellipsoid.maximumRadius * CesiumMath.PI;

    const polylines = this.polylines;
    const length = polylines.length;
    for (let i = 0; i < length; ++i) {
      const polyline = polylines[i];
      const width = polyline.width;
      const show = polyline.show && width > 0.0;
      const polylineBatchIndex = polyline._index;
      const segments = this.getSegments(polyline, projection);
      const positions = segments.positions;
      const lengths = segments.lengths;
      const positionsLength = positions.length;

      const pickColor = polyline.getPickId(context).color;

      let segmentIndex = 0;
      let count = 0;
      let position;

      for (let j = 0; j < positionsLength; ++j) {
        if (j === 0) {
          if (polyline._loop) {
            position = positions[positionsLength - 2];
          } else {
            position = scratchWriteVector;
            Cartesian3.subtract(positions[0], positions[1], position);
            Cartesian3.add(positions[0], position, position);
          }
        } else {
          position = positions[j - 1];
        }

        Cartesian3.clone(position, scratchWritePrevPosition);
        Cartesian3.clone(positions[j], scratchWritePosition);

        if (j === positionsLength - 1) {
          if (polyline._loop) {
            position = positions[1];
          } else {
            position = scratchWriteVector;
            Cartesian3.subtract(
              positions[positionsLength - 1],
              positions[positionsLength - 2],
              position
            );
            Cartesian3.add(positions[positionsLength - 1], position, position);
          }
        } else {
          position = positions[j + 1];
        }

        Cartesian3.clone(position, scratchWriteNextPosition);

        const segmentLength = lengths[segmentIndex];
        if (j === count + segmentLength) {
          count += segmentLength;
          ++segmentIndex;
        }

        const segmentStart = j - count === 0;
        const segmentEnd = j === count + lengths[segmentIndex] - 1;

        if (mode === SceneMode$1.SCENE2D) {
          scratchWritePrevPosition.z = 0.0;
          scratchWritePosition.z = 0.0;
          scratchWriteNextPosition.z = 0.0;
        }

        if (mode === SceneMode$1.SCENE2D || mode === SceneMode$1.MORPHING) {
          if (
            (segmentStart || segmentEnd) &&
            maxLon - Math.abs(scratchWritePosition.x) < 1.0
          ) {
            if (
              (scratchWritePosition.x < 0.0 &&
                scratchWritePrevPosition.x > 0.0) ||
              (scratchWritePosition.x > 0.0 && scratchWritePrevPosition.x < 0.0)
            ) {
              Cartesian3.clone(scratchWritePosition, scratchWritePrevPosition);
            }

            if (
              (scratchWritePosition.x < 0.0 &&
                scratchWriteNextPosition.x > 0.0) ||
              (scratchWritePosition.x > 0.0 && scratchWriteNextPosition.x < 0.0)
            ) {
              Cartesian3.clone(scratchWritePosition, scratchWriteNextPosition);
            }
          }
        }

        const startK = segmentStart ? 2 : 0;
        const endK = segmentEnd ? 2 : 4;

        for (let k = startK; k < endK; ++k) {
          EncodedCartesian3.writeElements(
            scratchWritePosition,
            positionArray,
            positionIndex
          );
          EncodedCartesian3.writeElements(
            scratchWritePrevPosition,
            positionArray,
            positionIndex + 6
          );
          EncodedCartesian3.writeElements(
            scratchWriteNextPosition,
            positionArray,
            positionIndex + 12
          );

          const direction = k - 2 < 0 ? -1.0 : 1.0;
          texCoordExpandAndBatchIndexArray[texCoordExpandAndBatchIndexIndex] =
            j / (positionsLength - 1); // s tex coord
          texCoordExpandAndBatchIndexArray[texCoordExpandAndBatchIndexIndex + 1] =
            2 * (k % 2) - 1; // expand direction
          texCoordExpandAndBatchIndexArray[
            texCoordExpandAndBatchIndexIndex + 2
          ] = direction;
          texCoordExpandAndBatchIndexArray[
            texCoordExpandAndBatchIndexIndex + 3
          ] = polylineBatchIndex;

          positionIndex += 6 * 3;
          texCoordExpandAndBatchIndexIndex += 4;
        }
      }

      const colorCartesian = scratchPickColorCartesian;
      colorCartesian.x = Color.floatToByte(pickColor.red);
      colorCartesian.y = Color.floatToByte(pickColor.green);
      colorCartesian.z = Color.floatToByte(pickColor.blue);
      colorCartesian.w = Color.floatToByte(pickColor.alpha);

      const widthShowCartesian = scratchWidthShowCartesian;
      widthShowCartesian.x = width;
      widthShowCartesian.y = show ? 1.0 : 0.0;

      const boundingSphere =
        mode === SceneMode$1.SCENE2D
          ? polyline._boundingVolume2D
          : polyline._boundingVolumeWC;
      const encodedCenter = EncodedCartesian3.fromCartesian(
        boundingSphere.center,
        scratchUpdatePolylineEncodedCartesian
      );
      const high = encodedCenter.high;
      const low = Cartesian4.fromElements(
        encodedCenter.low.x,
        encodedCenter.low.y,
        encodedCenter.low.z,
        boundingSphere.radius,
        scratchUpdatePolylineCartesian4
      );

      const nearFarCartesian = scratchNearFarCartesian2;
      nearFarCartesian.x = 0.0;
      nearFarCartesian.y = Number.MAX_VALUE;

      const distanceDisplayCondition = polyline.distanceDisplayCondition;
      if (defined(distanceDisplayCondition)) {
        nearFarCartesian.x = distanceDisplayCondition.near;
        nearFarCartesian.y = distanceDisplayCondition.far;
      }

      batchTable.setBatchedAttribute(polylineBatchIndex, 0, widthShowCartesian);
      batchTable.setBatchedAttribute(polylineBatchIndex, 1, colorCartesian);

      if (batchTable.attributes.length > 2) {
        batchTable.setBatchedAttribute(polylineBatchIndex, 2, high);
        batchTable.setBatchedAttribute(polylineBatchIndex, 3, low);
        batchTable.setBatchedAttribute(polylineBatchIndex, 4, nearFarCartesian);
      }
    }
  };

  const morphPositionScratch = new Cartesian3();
  const morphPrevPositionScratch = new Cartesian3();
  const morphNextPositionScratch = new Cartesian3();
  const morphVectorScratch = new Cartesian3();

  PolylineBucket.prototype.writeForMorph = function (
    positionArray,
    positionIndex
  ) {
    const modelMatrix = this.modelMatrix;
    const polylines = this.polylines;
    const length = polylines.length;
    for (let i = 0; i < length; ++i) {
      const polyline = polylines[i];
      const positions = polyline._segments.positions;
      const lengths = polyline._segments.lengths;
      const positionsLength = positions.length;

      let segmentIndex = 0;
      let count = 0;

      for (let j = 0; j < positionsLength; ++j) {
        let prevPosition;
        if (j === 0) {
          if (polyline._loop) {
            prevPosition = positions[positionsLength - 2];
          } else {
            prevPosition = morphVectorScratch;
            Cartesian3.subtract(positions[0], positions[1], prevPosition);
            Cartesian3.add(positions[0], prevPosition, prevPosition);
          }
        } else {
          prevPosition = positions[j - 1];
        }

        prevPosition = Matrix4.multiplyByPoint(
          modelMatrix,
          prevPosition,
          morphPrevPositionScratch
        );

        const position = Matrix4.multiplyByPoint(
          modelMatrix,
          positions[j],
          morphPositionScratch
        );

        let nextPosition;
        if (j === positionsLength - 1) {
          if (polyline._loop) {
            nextPosition = positions[1];
          } else {
            nextPosition = morphVectorScratch;
            Cartesian3.subtract(
              positions[positionsLength - 1],
              positions[positionsLength - 2],
              nextPosition
            );
            Cartesian3.add(
              positions[positionsLength - 1],
              nextPosition,
              nextPosition
            );
          }
        } else {
          nextPosition = positions[j + 1];
        }

        nextPosition = Matrix4.multiplyByPoint(
          modelMatrix,
          nextPosition,
          morphNextPositionScratch
        );

        const segmentLength = lengths[segmentIndex];
        if (j === count + segmentLength) {
          count += segmentLength;
          ++segmentIndex;
        }

        const segmentStart = j - count === 0;
        const segmentEnd = j === count + lengths[segmentIndex] - 1;

        const startK = segmentStart ? 2 : 0;
        const endK = segmentEnd ? 2 : 4;

        for (let k = startK; k < endK; ++k) {
          EncodedCartesian3.writeElements(position, positionArray, positionIndex);
          EncodedCartesian3.writeElements(
            prevPosition,
            positionArray,
            positionIndex + 6
          );
          EncodedCartesian3.writeElements(
            nextPosition,
            positionArray,
            positionIndex + 12
          );

          positionIndex += 6 * 3;
        }
      }
    }
  };

  const scratchSegmentLengths = new Array(1);

  PolylineBucket.prototype.updateIndices = function (
    totalIndices,
    vertexBufferOffset,
    vertexArrayBuckets,
    offset
  ) {
    let vaCount = vertexArrayBuckets.length - 1;
    let bucketLocator = new VertexArrayBucketLocator(0, offset, this);
    vertexArrayBuckets[vaCount].push(bucketLocator);
    let count = 0;
    let indices = totalIndices[totalIndices.length - 1];
    let indicesCount = 0;
    if (indices.length > 0) {
      indicesCount = indices[indices.length - 1] + 1;
    }
    const polylines = this.polylines;
    const length = polylines.length;
    for (let i = 0; i < length; ++i) {
      const polyline = polylines[i];
      polyline._locatorBuckets = [];

      let segments;
      if (this.mode === SceneMode$1.SCENE3D) {
        segments = scratchSegmentLengths;
        const positionsLength = polyline._actualPositions.length;
        if (positionsLength > 0) {
          segments[0] = positionsLength;
        } else {
          continue;
        }
      } else {
        segments = polyline._segments.lengths;
      }

      const numberOfSegments = segments.length;
      if (numberOfSegments > 0) {
        let segmentIndexCount = 0;
        for (let j = 0; j < numberOfSegments; ++j) {
          const segmentLength = segments[j] - 1.0;
          for (let k = 0; k < segmentLength; ++k) {
            if (indicesCount + 4 > CesiumMath.SIXTY_FOUR_KILOBYTES) {
              polyline._locatorBuckets.push({
                locator: bucketLocator,
                count: segmentIndexCount,
              });
              segmentIndexCount = 0;
              vertexBufferOffset.push(4);
              indices = [];
              totalIndices.push(indices);
              indicesCount = 0;
              bucketLocator.count = count;
              count = 0;
              offset = 0;
              bucketLocator = new VertexArrayBucketLocator(0, 0, this);
              vertexArrayBuckets[++vaCount] = [bucketLocator];
            }

            indices.push(indicesCount, indicesCount + 2, indicesCount + 1);
            indices.push(indicesCount + 1, indicesCount + 2, indicesCount + 3);

            segmentIndexCount += 6;
            count += 6;
            offset += 6;
            indicesCount += 4;
          }
        }

        polyline._locatorBuckets.push({
          locator: bucketLocator,
          count: segmentIndexCount,
        });

        if (indicesCount + 4 > CesiumMath.SIXTY_FOUR_KILOBYTES) {
          vertexBufferOffset.push(0);
          indices = [];
          totalIndices.push(indices);
          indicesCount = 0;
          bucketLocator.count = count;
          offset = 0;
          count = 0;
          bucketLocator = new VertexArrayBucketLocator(0, 0, this);
          vertexArrayBuckets[++vaCount] = [bucketLocator];
        }
      }
      polyline._clean();
    }
    bucketLocator.count = count;
    return offset;
  };

  PolylineBucket.prototype.getPolylineStartIndex = function (polyline) {
    const polylines = this.polylines;
    let positionIndex = 0;
    const length = polylines.length;
    for (let i = 0; i < length; ++i) {
      const p = polylines[i];
      if (p === polyline) {
        break;
      }
      positionIndex += p._actualLength;
    }
    return positionIndex;
  };

  const scratchSegments = {
    positions: undefined,
    lengths: undefined,
  };
  const scratchLengths = new Array(1);
  const pscratch = new Cartesian3();
  const scratchCartographic$b = new Cartographic();

  PolylineBucket.prototype.getSegments = function (polyline, projection) {
    let positions = polyline._actualPositions;

    if (this.mode === SceneMode$1.SCENE3D) {
      scratchLengths[0] = positions.length;
      scratchSegments.positions = positions;
      scratchSegments.lengths = scratchLengths;
      return scratchSegments;
    }

    if (intersectsIDL(polyline)) {
      positions = polyline._segments.positions;
    }

    const ellipsoid = projection.ellipsoid;
    const newPositions = [];
    const modelMatrix = this.modelMatrix;
    const length = positions.length;
    let position;
    let p = pscratch;

    for (let n = 0; n < length; ++n) {
      position = positions[n];
      p = Matrix4.multiplyByPoint(modelMatrix, position, p);
      newPositions.push(
        projection.project(
          ellipsoid.cartesianToCartographic(p, scratchCartographic$b)
        )
      );
    }

    if (newPositions.length > 0) {
      polyline._boundingVolume2D = BoundingSphere.fromPoints(
        newPositions,
        polyline._boundingVolume2D
      );
      const center2D = polyline._boundingVolume2D.center;
      polyline._boundingVolume2D.center = new Cartesian3(
        center2D.z,
        center2D.x,
        center2D.y
      );
    }

    scratchSegments.positions = newPositions;
    scratchSegments.lengths = polyline._segments.lengths;
    return scratchSegments;
  };

  let scratchPositionsArray;

  PolylineBucket.prototype.writeUpdate = function (
    index,
    polyline,
    positionBuffer,
    projection
  ) {
    const mode = this.mode;
    const maxLon = projection.ellipsoid.maximumRadius * CesiumMath.PI;

    let positionsLength = polyline._actualLength;
    if (positionsLength) {
      index += this.getPolylineStartIndex(polyline);

      let positionArray = scratchPositionsArray;
      const positionsArrayLength = 6 * positionsLength * 3;

      if (
        !defined(positionArray) ||
        positionArray.length < positionsArrayLength
      ) {
        positionArray = scratchPositionsArray = new Float32Array(
          positionsArrayLength
        );
      } else if (positionArray.length > positionsArrayLength) {
        positionArray = new Float32Array(
          positionArray.buffer,
          0,
          positionsArrayLength
        );
      }

      const segments = this.getSegments(polyline, projection);
      const positions = segments.positions;
      const lengths = segments.lengths;

      let positionIndex = 0;
      let segmentIndex = 0;
      let count = 0;
      let position;

      positionsLength = positions.length;
      for (let i = 0; i < positionsLength; ++i) {
        if (i === 0) {
          if (polyline._loop) {
            position = positions[positionsLength - 2];
          } else {
            position = scratchWriteVector;
            Cartesian3.subtract(positions[0], positions[1], position);
            Cartesian3.add(positions[0], position, position);
          }
        } else {
          position = positions[i - 1];
        }

        Cartesian3.clone(position, scratchWritePrevPosition);
        Cartesian3.clone(positions[i], scratchWritePosition);

        if (i === positionsLength - 1) {
          if (polyline._loop) {
            position = positions[1];
          } else {
            position = scratchWriteVector;
            Cartesian3.subtract(
              positions[positionsLength - 1],
              positions[positionsLength - 2],
              position
            );
            Cartesian3.add(positions[positionsLength - 1], position, position);
          }
        } else {
          position = positions[i + 1];
        }

        Cartesian3.clone(position, scratchWriteNextPosition);

        const segmentLength = lengths[segmentIndex];
        if (i === count + segmentLength) {
          count += segmentLength;
          ++segmentIndex;
        }

        const segmentStart = i - count === 0;
        const segmentEnd = i === count + lengths[segmentIndex] - 1;

        if (mode === SceneMode$1.SCENE2D) {
          scratchWritePrevPosition.z = 0.0;
          scratchWritePosition.z = 0.0;
          scratchWriteNextPosition.z = 0.0;
        }

        if (mode === SceneMode$1.SCENE2D || mode === SceneMode$1.MORPHING) {
          if (
            (segmentStart || segmentEnd) &&
            maxLon - Math.abs(scratchWritePosition.x) < 1.0
          ) {
            if (
              (scratchWritePosition.x < 0.0 &&
                scratchWritePrevPosition.x > 0.0) ||
              (scratchWritePosition.x > 0.0 && scratchWritePrevPosition.x < 0.0)
            ) {
              Cartesian3.clone(scratchWritePosition, scratchWritePrevPosition);
            }

            if (
              (scratchWritePosition.x < 0.0 &&
                scratchWriteNextPosition.x > 0.0) ||
              (scratchWritePosition.x > 0.0 && scratchWriteNextPosition.x < 0.0)
            ) {
              Cartesian3.clone(scratchWritePosition, scratchWriteNextPosition);
            }
          }
        }

        const startJ = segmentStart ? 2 : 0;
        const endJ = segmentEnd ? 2 : 4;

        for (let j = startJ; j < endJ; ++j) {
          EncodedCartesian3.writeElements(
            scratchWritePosition,
            positionArray,
            positionIndex
          );
          EncodedCartesian3.writeElements(
            scratchWritePrevPosition,
            positionArray,
            positionIndex + 6
          );
          EncodedCartesian3.writeElements(
            scratchWriteNextPosition,
            positionArray,
            positionIndex + 12
          );
          positionIndex += 6 * 3;
        }
      }

      positionBuffer.copyFromArrayView(
        positionArray,
        6 * 3 * Float32Array.BYTES_PER_ELEMENT * index
      );
    }
  };

  /**
   * Creates a batch of points or billboards and labels.
   *
   * @alias Vector3DTilePoints
   * @constructor
   *
   * @param {Object} options An object with following properties:
   * @param {Uint16Array} options.positions The positions of the polygons.
   * @param {Number} options.minimumHeight The minimum height of the terrain covered by the tile.
   * @param {Number} options.maximumHeight The maximum height of the terrain covered by the tile.
   * @param {Rectangle} options.rectangle The rectangle containing the tile.
   * @param {Cesium3DTileBatchTable} options.batchTable The batch table for the tile containing the batched polygons.
   * @param {Uint16Array} options.batchIds The batch ids for each polygon.
   *
   * @private
   */
  function Vector3DTilePoints(options) {
    // released after the first update
    this._positions = options.positions;

    this._batchTable = options.batchTable;
    this._batchIds = options.batchIds;

    this._rectangle = options.rectangle;
    this._minHeight = options.minimumHeight;
    this._maxHeight = options.maximumHeight;

    this._billboardCollection = new BillboardCollection({
      batchTable: options.batchTable,
    });
    this._labelCollection = new LabelCollection({
      batchTable: options.batchTable,
    });
    this._polylineCollection = new PolylineCollection();
    this._polylineCollection._useHighlightColor = true;

    this._verticesPromise = undefined;
    this._packedBuffer = undefined;

    this._ready = false;
    this._update = function (points, frameState) {};
    this._readyPromise = initialize$d(this);
  }

  Object.defineProperties(Vector3DTilePoints.prototype, {
    /**
     * Gets the number of points.
     *
     * @memberof Vector3DTilePoints.prototype
     *
     * @type {Number}
     * @readonly
     */
    pointsLength: {
      get: function () {
        return this._billboardCollection.length;
      },
    },

    /**
     * Gets the texture atlas memory in bytes.
     *
     * @memberof Vector3DTilePoints.prototype
     *
     * @type {Number}
     * @readonly
     */
    texturesByteLength: {
      get: function () {
        const billboardSize = this._billboardCollection.textureAtlas.texture
          .sizeInBytes;
        const labelSize = this._labelCollection._textureAtlas.texture.sizeInBytes;
        return billboardSize + labelSize;
      },
    },

    /**
     * Gets a promise that resolves when the primitive is ready to render.
     * @memberof Vector3DTilePoints.prototype
     * @type {Promise<void>}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._readyPromise;
      },
    },
  });

  function packBuffer$3(points, ellipsoid) {
    const rectangle = points._rectangle;
    const minimumHeight = points._minHeight;
    const maximumHeight = points._maxHeight;

    const packedLength = 2 + Rectangle.packedLength + Ellipsoid.packedLength;
    const packedBuffer = new Float64Array(packedLength);

    let offset = 0;
    packedBuffer[offset++] = minimumHeight;
    packedBuffer[offset++] = maximumHeight;

    Rectangle.pack(rectangle, packedBuffer, offset);
    offset += Rectangle.packedLength;

    Ellipsoid.pack(ellipsoid, packedBuffer, offset);

    return packedBuffer;
  }

  const createVerticesTaskProcessor$3 = new TaskProcessor(
    "createVectorTilePoints",
    5
  );
  const scratchPosition$6 = new Cartesian3();

  function createPoints(points, ellipsoid) {
    let positions;
    if (!defined(points._verticesPromise)) {
      positions = points._positions;
      let packedBuffer = points._packedBuffer;

      if (!defined(packedBuffer)) {
        // Copy because they may be the views on the same buffer.
        positions = points._positions = positions.slice();
        points._batchIds = points._batchIds.slice();

        packedBuffer = points._packedBuffer = packBuffer$3(points, ellipsoid);
      }

      const transferrableObjects = [positions.buffer, packedBuffer.buffer];
      const parameters = {
        positions: positions.buffer,
        packedBuffer: packedBuffer.buffer,
      };

      const verticesPromise = (points._verticesPromise = createVerticesTaskProcessor$3.scheduleTask(
        parameters,
        transferrableObjects
      ));
      if (!defined(verticesPromise)) {
        // Postponed
        return;
      }

      return verticesPromise.then(function (result) {
        points._positions = new Float64Array(result.positions);
        const billboardCollection = points._billboardCollection;
        const labelCollection = points._labelCollection;
        const polylineCollection = points._polylineCollection;
        positions = points._positions;
        const batchIds = points._batchIds;
        const numberOfPoints = positions.length / 3;

        for (let i = 0; i < numberOfPoints; ++i) {
          const id = batchIds[i];

          const position = Cartesian3.unpack(positions, i * 3, scratchPosition$6);

          const b = billboardCollection.add();
          b.position = position;
          b._batchIndex = id;

          const l = labelCollection.add();
          l.text = " ";
          l.position = position;
          l._batchIndex = id;

          const p = polylineCollection.add();
          p.positions = [Cartesian3.clone(position), Cartesian3.clone(position)];
        }

        points._positions = undefined;
        points._packedBuffer = undefined;
        points._ready = true;
      });
    }
  }

  /**
   * Creates features for each point and places it at the batch id index of features.
   *
   * @param {Vector3DTileContent} content The vector tile content.
   * @param {Cesium3DTileFeature[]} features An array of features where the point features will be placed.
   */
  Vector3DTilePoints.prototype.createFeatures = function (content, features) {
    const billboardCollection = this._billboardCollection;
    const labelCollection = this._labelCollection;
    const polylineCollection = this._polylineCollection;

    const batchIds = this._batchIds;
    const length = batchIds.length;
    for (let i = 0; i < length; ++i) {
      const batchId = batchIds[i];

      const billboard = billboardCollection.get(i);
      const label = labelCollection.get(i);
      const polyline = polylineCollection.get(i);

      features[batchId] = new Cesium3DTilePointFeature(
        content,
        batchId,
        billboard,
        label,
        polyline
      );
    }
  };

  /**
   * Colors the entire tile when enabled is true. The resulting color will be (batch table color * color).
   *
   * @param {Boolean} enabled Whether to enable debug coloring.
   * @param {Color} color The debug color.
   */
  Vector3DTilePoints.prototype.applyDebugSettings = function (enabled, color) {
    if (enabled) {
      Color.clone(color, this._billboardCollection._highlightColor);
      Color.clone(color, this._labelCollection._highlightColor);
      Color.clone(color, this._polylineCollection._highlightColor);
    } else {
      Color.clone(Color.WHITE, this._billboardCollection._highlightColor);
      Color.clone(Color.WHITE, this._labelCollection._highlightColor);
      Color.clone(Color.WHITE, this._polylineCollection._highlightColor);
    }
  };

  function clearStyle$2(polygons, features) {
    const batchIds = polygons._batchIds;
    const length = batchIds.length;
    for (let i = 0; i < length; ++i) {
      const batchId = batchIds[i];
      const feature = features[batchId];

      feature.show = true;
      feature.pointSize = Cesium3DTilePointFeature.defaultPointSize;
      feature.color = Cesium3DTilePointFeature.defaultColor;
      feature.pointOutlineColor =
        Cesium3DTilePointFeature.defaultPointOutlineColor;
      feature.pointOutlineWidth =
        Cesium3DTilePointFeature.defaultPointOutlineWidth;
      feature.labelColor = Color.WHITE;
      feature.labelOutlineColor = Color.WHITE;
      feature.labelOutlineWidth = 1.0;
      feature.font = "30px sans-serif";
      feature.labelStyle = LabelStyle$1.FILL;
      feature.labelText = undefined;
      feature.backgroundColor = new Color(0.165, 0.165, 0.165, 0.8);
      feature.backgroundPadding = new Cartesian2(7, 5);
      feature.backgroundEnabled = false;
      feature.scaleByDistance = undefined;
      feature.translucencyByDistance = undefined;
      feature.distanceDisplayCondition = undefined;
      feature.heightOffset = 0.0;
      feature.anchorLineEnabled = false;
      feature.anchorLineColor = Color.WHITE;
      feature.image = undefined;
      feature.disableDepthTestDistance = 0.0;
      feature.horizontalOrigin = HorizontalOrigin$1.CENTER;
      feature.verticalOrigin = VerticalOrigin$1.CENTER;
      feature.labelHorizontalOrigin = HorizontalOrigin$1.RIGHT;
      feature.labelVerticalOrigin = VerticalOrigin$1.BASELINE;
    }
  }

  const scratchColor$i = new Color();
  const scratchColor2 = new Color();
  const scratchColor3 = new Color();
  const scratchColor4 = new Color();
  const scratchColor5 = new Color();
  const scratchColor6 = new Color();
  const scratchScaleByDistance = new NearFarScalar();
  const scratchTranslucencyByDistance = new NearFarScalar();
  const scratchDistanceDisplayCondition = new DistanceDisplayCondition();

  /**
   * Apply a style to the content.
   *
   * @param {Cesium3DTileStyle} style The style.
   * @param {Cesium3DTileFeature[]} features The array of features.
   */
  Vector3DTilePoints.prototype.applyStyle = function (style, features) {
    if (!defined(style)) {
      clearStyle$2(this, features);
      return;
    }

    const batchIds = this._batchIds;
    const length = batchIds.length;
    for (let i = 0; i < length; ++i) {
      const batchId = batchIds[i];
      const feature = features[batchId];

      if (defined(style.show)) {
        feature.show = style.show.evaluate(feature);
      }

      if (defined(style.pointSize)) {
        feature.pointSize = style.pointSize.evaluate(feature);
      }

      if (defined(style.color)) {
        feature.color = style.color.evaluateColor(feature, scratchColor$i);
      }

      if (defined(style.pointOutlineColor)) {
        feature.pointOutlineColor = style.pointOutlineColor.evaluateColor(
          feature,
          scratchColor2
        );
      }

      if (defined(style.pointOutlineWidth)) {
        feature.pointOutlineWidth = style.pointOutlineWidth.evaluate(feature);
      }

      if (defined(style.labelColor)) {
        feature.labelColor = style.labelColor.evaluateColor(
          feature,
          scratchColor3
        );
      }

      if (defined(style.labelOutlineColor)) {
        feature.labelOutlineColor = style.labelOutlineColor.evaluateColor(
          feature,
          scratchColor4
        );
      }

      if (defined(style.labelOutlineWidth)) {
        feature.labelOutlineWidth = style.labelOutlineWidth.evaluate(feature);
      }

      if (defined(style.font)) {
        feature.font = style.font.evaluate(feature);
      }

      if (defined(style.labelStyle)) {
        feature.labelStyle = style.labelStyle.evaluate(feature);
      }

      if (defined(style.labelText)) {
        feature.labelText = style.labelText.evaluate(feature);
      } else {
        feature.labelText = undefined;
      }

      if (defined(style.backgroundColor)) {
        feature.backgroundColor = style.backgroundColor.evaluateColor(
          feature,
          scratchColor5
        );
      }

      if (defined(style.backgroundPadding)) {
        feature.backgroundPadding = style.backgroundPadding.evaluate(feature);
      }

      if (defined(style.backgroundEnabled)) {
        feature.backgroundEnabled = style.backgroundEnabled.evaluate(feature);
      }

      if (defined(style.scaleByDistance)) {
        const scaleByDistanceCart4 = style.scaleByDistance.evaluate(feature);
        scratchScaleByDistance.near = scaleByDistanceCart4.x;
        scratchScaleByDistance.nearValue = scaleByDistanceCart4.y;
        scratchScaleByDistance.far = scaleByDistanceCart4.z;
        scratchScaleByDistance.farValue = scaleByDistanceCart4.w;
        feature.scaleByDistance = scratchScaleByDistance;
      } else {
        feature.scaleByDistance = undefined;
      }

      if (defined(style.translucencyByDistance)) {
        const translucencyByDistanceCart4 = style.translucencyByDistance.evaluate(
          feature
        );
        scratchTranslucencyByDistance.near = translucencyByDistanceCart4.x;
        scratchTranslucencyByDistance.nearValue = translucencyByDistanceCart4.y;
        scratchTranslucencyByDistance.far = translucencyByDistanceCart4.z;
        scratchTranslucencyByDistance.farValue = translucencyByDistanceCart4.w;
        feature.translucencyByDistance = scratchTranslucencyByDistance;
      } else {
        feature.translucencyByDistance = undefined;
      }

      if (defined(style.distanceDisplayCondition)) {
        const distanceDisplayConditionCart2 = style.distanceDisplayCondition.evaluate(
          feature
        );
        scratchDistanceDisplayCondition.near = distanceDisplayConditionCart2.x;
        scratchDistanceDisplayCondition.far = distanceDisplayConditionCart2.y;
        feature.distanceDisplayCondition = scratchDistanceDisplayCondition;
      } else {
        feature.distanceDisplayCondition = undefined;
      }

      if (defined(style.heightOffset)) {
        feature.heightOffset = style.heightOffset.evaluate(feature);
      }

      if (defined(style.anchorLineEnabled)) {
        feature.anchorLineEnabled = style.anchorLineEnabled.evaluate(feature);
      }

      if (defined(style.anchorLineColor)) {
        feature.anchorLineColor = style.anchorLineColor.evaluateColor(
          feature,
          scratchColor6
        );
      }

      if (defined(style.image)) {
        feature.image = style.image.evaluate(feature);
      } else {
        feature.image = undefined;
      }

      if (defined(style.disableDepthTestDistance)) {
        feature.disableDepthTestDistance = style.disableDepthTestDistance.evaluate(
          feature
        );
      }

      if (defined(style.horizontalOrigin)) {
        feature.horizontalOrigin = style.horizontalOrigin.evaluate(feature);
      }

      if (defined(style.verticalOrigin)) {
        feature.verticalOrigin = style.verticalOrigin.evaluate(feature);
      }

      if (defined(style.labelHorizontalOrigin)) {
        feature.labelHorizontalOrigin = style.labelHorizontalOrigin.evaluate(
          feature
        );
      }

      if (defined(style.labelVerticalOrigin)) {
        feature.labelVerticalOrigin = style.labelVerticalOrigin.evaluate(feature);
      }
    }
  };

  function initialize$d(points) {
    return new Promise(function (resolve, reject) {
      points._update = function (points, frameState) {
        const promise = createPoints(points, frameState.mapProjection.ellipsoid);

        if (points._ready) {
          points._polylineCollection.update(frameState);
          points._billboardCollection.update(frameState);
          points._labelCollection.update(frameState);
        }

        if (!defined(promise)) {
          return;
        }

        promise
          .then(function () {
            resolve();
          })
          .catch(function (e) {
            reject(e);
          });
      };
    });
  }

  /**
   * @private
   */
  Vector3DTilePoints.prototype.update = function (frameState) {
    this._update(this, frameState);
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <p>
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   * </p>
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   */
  Vector3DTilePoints.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <p>
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   * </p>
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   */
  Vector3DTilePoints.prototype.destroy = function () {
    this._billboardCollection =
      this._billboardCollection && this._billboardCollection.destroy();
    this._labelCollection =
      this._labelCollection && this._labelCollection.destroy();
    this._polylineCollection =
      this._polylineCollection && this._polylineCollection.destroy();
    return destroyObject(this);
  };

  /**
   * Creates a batch of pre-triangulated polygons draped on terrain and/or 3D Tiles.
   *
   * @alias Vector3DTilePolygons
   * @constructor
   *
   * @param {Object} options An object with following properties:
   * @param {Float32Array|Uint16Array} options.positions The positions of the polygons. The positions must be contiguous
   * so that the positions for polygon n are in [c, c + counts[n]] where c = sum{counts[0], counts[n - 1]} and they are the outer ring of
   * the polygon in counter-clockwise order.
   * @param {Uint32Array} options.counts The number of positions in the each polygon.
   * @param {Uint32Array} options.indices The indices of the triangulated polygons. The indices must be contiguous so that
   * the indices for polygon n are in [i, i + indexCounts[n]] where i = sum{indexCounts[0], indexCounts[n - 1]}.
   * @param {Uint32Array} options.indexCounts The number of indices for each polygon.
   * @param {Number} options.minimumHeight The minimum height of the terrain covered by the tile.
   * @param {Number} options.maximumHeight The maximum height of the terrain covered by the tile.
   * @param {Float32Array} [options.polygonMinimumHeights] An array containing the minimum heights for each polygon.
   * @param {Float32Array} [options.polygonMaximumHeights] An array containing the maximum heights for each polygon.
   * @param {Rectangle} options.rectangle The rectangle containing the tile.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid.
   * @param {Cartesian3} [options.center=Cartesian3.ZERO] The RTC center.
   * @param {Cesium3DTileBatchTable} options.batchTable The batch table for the tile containing the batched polygons.
   * @param {Uint16Array} options.batchIds The batch ids for each polygon.
   * @param {BoundingSphere} options.boundingVolume The bounding volume for the entire batch of polygons.
   *
   * @private
   */
  function Vector3DTilePolygons(options) {
    // All of the private properties will be released except _readyPromise
    // and _primitive after the Vector3DTilePrimitive is created.
    this._batchTable = options.batchTable;

    this._batchIds = options.batchIds;
    this._positions = options.positions;
    this._counts = options.counts;

    this._indices = options.indices;
    this._indexCounts = options.indexCounts;
    this._indexOffsets = undefined;

    this._batchTableColors = undefined;
    this._packedBuffer = undefined;

    this._batchedPositions = undefined;
    this._transferrableBatchIds = undefined;
    this._vertexBatchIds = undefined;

    this._ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);
    this._minimumHeight = options.minimumHeight;
    this._maximumHeight = options.maximumHeight;
    this._polygonMinimumHeights = options.polygonMinimumHeights;
    this._polygonMaximumHeights = options.polygonMaximumHeights;
    this._center = defaultValue(options.center, Cartesian3.ZERO);
    this._rectangle = options.rectangle;

    this._center = undefined;

    this._boundingVolume = options.boundingVolume;
    this._boundingVolumes = undefined;

    this._batchedIndices = undefined;

    this._ready = false;
    this._update = function (polygons, frameState) {};
    this._readyPromise = initialize$c(this);
    this._verticesPromise = undefined;

    this._primitive = undefined;

    /**
     * Draws the wireframe of the classification meshes.
     * @type {Boolean}
     * @default false
     */
    this.debugWireframe = false;

    /**
     * Forces a re-batch instead of waiting after a number of frames have been rendered. For testing only.
     * @type {Boolean}
     * @default false
     */
    this.forceRebatch = false;

    /**
     * What this tile will classify.
     * @type {ClassificationType}
     * @default ClassificationType.BOTH
     */
    this.classificationType = ClassificationType$1.BOTH;
  }

  Object.defineProperties(Vector3DTilePolygons.prototype, {
    /**
     * Gets the number of triangles.
     *
     * @memberof Vector3DTilePolygons.prototype
     *
     * @type {Number}
     * @readonly
     */
    trianglesLength: {
      get: function () {
        if (defined(this._primitive)) {
          return this._primitive.trianglesLength;
        }
        return 0;
      },
    },

    /**
     * Gets the geometry memory in bytes.
     *
     * @memberof Vector3DTilePolygons.prototype
     *
     * @type {Number}
     * @readonly
     */
    geometryByteLength: {
      get: function () {
        if (defined(this._primitive)) {
          return this._primitive.geometryByteLength;
        }
        return 0;
      },
    },

    /**
     * Gets a promise that resolves when the primitive is ready to render.
     * @memberof Vector3DTilePolygons.prototype
     * @type {Promise<void>}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._readyPromise;
      },
    },
  });

  function packBuffer$2(polygons) {
    const packedBuffer = new Float64Array(
      3 +
        Cartesian3.packedLength +
        Ellipsoid.packedLength +
        Rectangle.packedLength
    );

    let offset = 0;
    packedBuffer[offset++] = polygons._indices.BYTES_PER_ELEMENT;

    packedBuffer[offset++] = polygons._minimumHeight;
    packedBuffer[offset++] = polygons._maximumHeight;

    Cartesian3.pack(polygons._center, packedBuffer, offset);
    offset += Cartesian3.packedLength;

    Ellipsoid.pack(polygons._ellipsoid, packedBuffer, offset);
    offset += Ellipsoid.packedLength;

    Rectangle.pack(polygons._rectangle, packedBuffer, offset);

    return packedBuffer;
  }

  function unpackBuffer(polygons, packedBuffer) {
    let offset = 1;

    const numBVS = packedBuffer[offset++];
    const bvs = (polygons._boundingVolumes = new Array(numBVS));

    for (let i = 0; i < numBVS; ++i) {
      bvs[i] = OrientedBoundingBox.unpack(packedBuffer, offset);
      offset += OrientedBoundingBox.packedLength;
    }

    const numBatchedIndices = packedBuffer[offset++];
    const bis = (polygons._batchedIndices = new Array(numBatchedIndices));

    for (let j = 0; j < numBatchedIndices; ++j) {
      const color = Color.unpack(packedBuffer, offset);
      offset += Color.packedLength;

      const indexOffset = packedBuffer[offset++];
      const count = packedBuffer[offset++];

      const length = packedBuffer[offset++];
      const batchIds = new Array(length);

      for (let k = 0; k < length; ++k) {
        batchIds[k] = packedBuffer[offset++];
      }

      bis[j] = new Vector3DTileBatch({
        color: color,
        offset: indexOffset,
        count: count,
        batchIds: batchIds,
      });
    }
  }

  const createVerticesTaskProcessor$2 = new TaskProcessor(
    "createVectorTilePolygons",
    5
  );
  const scratchColor$h = new Color();

  function createPrimitive(polygons) {
    if (defined(polygons._primitive)) {
      return;
    }

    if (!defined(polygons._verticesPromise)) {
      let positions = polygons._positions;
      let counts = polygons._counts;
      let indexCounts = polygons._indexCounts;
      let indices = polygons._indices;

      let batchIds = polygons._transferrableBatchIds;
      let batchTableColors = polygons._batchTableColors;

      let packedBuffer = polygons._packedBuffer;

      if (!defined(batchTableColors)) {
        // Copy because they may be the views on the same buffer.
        positions = polygons._positions = polygons._positions.slice();
        counts = polygons._counts = polygons._counts.slice();
        indexCounts = polygons._indexCounts = polygons._indexCounts.slice();
        indices = polygons._indices = polygons._indices.slice();

        polygons._center = polygons._ellipsoid.cartographicToCartesian(
          Rectangle.center(polygons._rectangle)
        );

        batchIds = polygons._transferrableBatchIds = new Uint32Array(
          polygons._batchIds
        );
        batchTableColors = polygons._batchTableColors = new Uint32Array(
          batchIds.length
        );
        const batchTable = polygons._batchTable;

        const length = batchTableColors.length;
        for (let i = 0; i < length; ++i) {
          const color = batchTable.getColor(i, scratchColor$h);
          batchTableColors[i] = color.toRgba();
        }

        packedBuffer = polygons._packedBuffer = packBuffer$2(polygons);
      }

      const transferrableObjects = [
        positions.buffer,
        counts.buffer,
        indexCounts.buffer,
        indices.buffer,
        batchIds.buffer,
        batchTableColors.buffer,
        packedBuffer.buffer,
      ];
      const parameters = {
        packedBuffer: packedBuffer.buffer,
        positions: positions.buffer,
        counts: counts.buffer,
        indexCounts: indexCounts.buffer,
        indices: indices.buffer,
        batchIds: batchIds.buffer,
        batchTableColors: batchTableColors.buffer,
      };

      let minimumHeights = polygons._polygonMinimumHeights;
      let maximumHeights = polygons._polygonMaximumHeights;
      if (defined(minimumHeights) && defined(maximumHeights)) {
        minimumHeights = minimumHeights.slice();
        maximumHeights = maximumHeights.slice();

        transferrableObjects.push(minimumHeights.buffer, maximumHeights.buffer);
        parameters.minimumHeights = minimumHeights;
        parameters.maximumHeights = maximumHeights;
      }

      const verticesPromise = (polygons._verticesPromise = createVerticesTaskProcessor$2.scheduleTask(
        parameters,
        transferrableObjects
      ));
      if (!defined(verticesPromise)) {
        // Postponed
        return;
      }

      return verticesPromise.then(function (result) {
        polygons._positions = undefined;
        polygons._counts = undefined;
        polygons._polygonMinimumHeights = undefined;
        polygons._polygonMaximumHeights = undefined;

        const packedBuffer = new Float64Array(result.packedBuffer);
        const indexDatatype = packedBuffer[0];
        unpackBuffer(polygons, packedBuffer);

        polygons._indices =
          IndexDatatype$1.getSizeInBytes(indexDatatype) === 2
            ? new Uint16Array(result.indices)
            : new Uint32Array(result.indices);
        polygons._indexOffsets = new Uint32Array(result.indexOffsets);
        polygons._indexCounts = new Uint32Array(result.indexCounts);

        // will be released
        polygons._batchedPositions = new Float32Array(result.positions);
        polygons._vertexBatchIds = new Uint16Array(result.batchIds);

        polygons._ready = true;
      });
    }
  }

  function finishPrimitive(polygons) {
    if (polygons._ready && !defined(polygons._primitive)) {
      polygons._primitive = new Vector3DTilePrimitive({
        batchTable: polygons._batchTable,
        positions: polygons._batchedPositions,
        batchIds: polygons._batchIds,
        vertexBatchIds: polygons._vertexBatchIds,
        indices: polygons._indices,
        indexOffsets: polygons._indexOffsets,
        indexCounts: polygons._indexCounts,
        batchedIndices: polygons._batchedIndices,
        boundingVolume: polygons._boundingVolume,
        boundingVolumes: polygons._boundingVolumes,
        center: polygons._center,
      });

      polygons._batchTable = undefined;
      polygons._batchIds = undefined;
      polygons._positions = undefined;
      polygons._counts = undefined;
      polygons._indices = undefined;
      polygons._indexCounts = undefined;
      polygons._indexOffsets = undefined;
      polygons._batchTableColors = undefined;
      polygons._packedBuffer = undefined;
      polygons._batchedPositions = undefined;
      polygons._transferrableBatchIds = undefined;
      polygons._vertexBatchIds = undefined;
      polygons._ellipsoid = undefined;
      polygons._minimumHeight = undefined;
      polygons._maximumHeight = undefined;
      polygons._polygonMinimumHeights = undefined;
      polygons._polygonMaximumHeights = undefined;
      polygons._center = undefined;
      polygons._rectangle = undefined;
      polygons._boundingVolume = undefined;
      polygons._boundingVolumes = undefined;
      polygons._batchedIndices = undefined;
      polygons._verticesPromise = undefined;
    }
  }

  /**
   * Creates features for each polygon and places it at the batch id index of features.
   *
   * @param {Vector3DTileContent} content The vector tile content.
   * @param {Cesium3DTileFeature[]} features An array of features where the polygon features will be placed.
   */
  Vector3DTilePolygons.prototype.createFeatures = function (content, features) {
    this._primitive.createFeatures(content, features);
  };

  /**
   * Colors the entire tile when enabled is true. The resulting color will be (polygon batch table color * color).
   *
   * @param {Boolean} enabled Whether to enable debug coloring.
   * @param {Color} color The debug color.
   */
  Vector3DTilePolygons.prototype.applyDebugSettings = function (enabled, color) {
    this._primitive.applyDebugSettings(enabled, color);
  };

  /**
   * Apply a style to the content.
   *
   * @param {Cesium3DTileStyle} style The style.
   * @param {Cesium3DTileFeature[]} features The array of features.
   */
  Vector3DTilePolygons.prototype.applyStyle = function (style, features) {
    this._primitive.applyStyle(style, features);
  };

  /**
   * Call when updating the color of a polygon with batchId changes color. The polygons will need to be re-batched
   * on the next update.
   *
   * @param {Number} batchId The batch id of the polygon whose color has changed.
   * @param {Color} color The new polygon color.
   */
  Vector3DTilePolygons.prototype.updateCommands = function (batchId, color) {
    this._primitive.updateCommands(batchId, color);
  };

  function initialize$c(polygons) {
    return new Promise(function (resolve, reject) {
      polygons._update = function (polygons, frameState) {
        const promise = createPrimitive(polygons);

        if (polygons._ready) {
          polygons._primitive.debugWireframe = polygons.debugWireframe;
          polygons._primitive.forceRebatch = polygons.forceRebatch;
          polygons._primitive.classificationType = polygons.classificationType;
          polygons._primitive.update(frameState);
        }

        if (!defined(promise)) {
          return;
        }

        promise
          .then(function () {
            finishPrimitive(polygons);
            resolve(polygons);
          })
          .catch(function (e) {
            reject(e);
          });
      };
    });
  }

  /**
   * Updates the batches and queues the commands for rendering.
   *
   * @param {FrameState} frameState The current frame state.
   */
  Vector3DTilePolygons.prototype.update = function (frameState) {
    this._update(this, frameState);
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <p>
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   * </p>
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   */
  Vector3DTilePolygons.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <p>
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   * </p>
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   */
  Vector3DTilePolygons.prototype.destroy = function () {
    this._primitive = this._primitive && this._primitive.destroy();
    return destroyObject(this);
  };

  //This file is automatically rebuilt by the Cesium build process.
  var Vector3DTilePolylinesVS = "attribute vec4 currentPosition;\n\
attribute vec4 previousPosition;\n\
attribute vec4 nextPosition;\n\
attribute vec2 expandAndWidth;\n\
attribute float a_batchId;\n\
uniform mat4 u_modifiedModelView;\n\
void main()\n\
{\n\
float expandDir = expandAndWidth.x;\n\
float width = abs(expandAndWidth.y) + 0.5;\n\
bool usePrev = expandAndWidth.y < 0.0;\n\
vec4 p = u_modifiedModelView * currentPosition;\n\
vec4 prev = u_modifiedModelView * previousPosition;\n\
vec4 next = u_modifiedModelView * nextPosition;\n\
float angle;\n\
vec4 positionWC = getPolylineWindowCoordinatesEC(p, prev, next, expandDir, width, usePrev, angle);\n\
gl_Position = czm_viewportOrthographic * positionWC;\n\
}\n\
";

  /**
   * Creates a batch of polylines that have been subdivided to be draped on terrain.
   *
   * @alias Vector3DTilePolylines
   * @constructor
   *
   * @param {Object} options An object with following properties:
   * @param {Uint16Array} options.positions The positions of the polylines
   * @param {Uint32Array} options.counts The number or positions in the each polyline.
   * @param {Uint16Array} options.widths The width of each polyline.
   * @param {Number} options.minimumHeight The minimum height of the terrain covered by the tile.
   * @param {Number} options.maximumHeight The maximum height of the terrain covered by the tile.
   * @param {Rectangle} options.rectangle The rectangle containing the tile.
   * @param {Cartesian3} [options.center=Cartesian3.ZERO] The RTC center.
   * @param {Cesium3DTileBatchTable} options.batchTable The batch table for the tile containing the batched polylines.
   * @param {Uint16Array} options.batchIds The batch ids for each polyline.
   * @param {BoundingSphere} options.boundingVolume The bounding volume for the entire batch of polylines.
   * @param {Boolean} options.keepDecodedPositions Whether to keep decoded positions in memory.
   *
   * @private
   */
  function Vector3DTilePolylines(options) {
    // these arrays are all released after the first update.
    this._positions = options.positions;
    this._widths = options.widths;
    this._counts = options.counts;
    this._batchIds = options.batchIds;

    this._ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);
    this._minimumHeight = options.minimumHeight;
    this._maximumHeight = options.maximumHeight;
    this._center = options.center;
    this._rectangle = options.rectangle;

    this._boundingVolume = options.boundingVolume;
    this._batchTable = options.batchTable;

    this._va = undefined;
    this._sp = undefined;
    this._rs = undefined;
    this._uniformMap = undefined;
    this._command = undefined;

    this._transferrableBatchIds = undefined;
    this._packedBuffer = undefined;

    this._keepDecodedPositions = options.keepDecodedPositions;
    this._decodedPositions = undefined;
    this._decodedPositionOffsets = undefined;

    this._currentPositions = undefined;
    this._previousPositions = undefined;
    this._nextPositions = undefined;
    this._expandAndWidth = undefined;
    this._vertexBatchIds = undefined;
    this._indices = undefined;

    this._constantColor = Color.clone(Color.WHITE);
    this._highlightColor = this._constantColor;

    this._trianglesLength = 0;
    this._geometryByteLength = 0;

    this._ready = false;
    this._update = function (polylines, frameState) {};
    this._readyPromise = initialize$b(this);

    this._verticesPromise = undefined;
  }

  Object.defineProperties(Vector3DTilePolylines.prototype, {
    /**
     * Gets the number of triangles.
     *
     * @memberof Vector3DTilePolylines.prototype
     *
     * @type {Number}
     * @readonly
     */
    trianglesLength: {
      get: function () {
        return this._trianglesLength;
      },
    },

    /**
     * Gets the geometry memory in bytes.
     *
     * @memberof Vector3DTilePolylines.prototype
     *
     * @type {Number}
     * @readonly
     */
    geometryByteLength: {
      get: function () {
        return this._geometryByteLength;
      },
    },

    /**
     * Gets a promise that resolves when the primitive is ready to render.
     * @memberof Vector3DTilePolylines.prototype
     * @type {Promise<void>}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._readyPromise;
      },
    },
  });

  function packBuffer$1(polylines) {
    const rectangle = polylines._rectangle;
    const minimumHeight = polylines._minimumHeight;
    const maximumHeight = polylines._maximumHeight;
    const ellipsoid = polylines._ellipsoid;
    const center = polylines._center;

    const packedLength =
      2 +
      Rectangle.packedLength +
      Ellipsoid.packedLength +
      Cartesian3.packedLength;
    const packedBuffer = new Float64Array(packedLength);

    let offset = 0;
    packedBuffer[offset++] = minimumHeight;
    packedBuffer[offset++] = maximumHeight;

    Rectangle.pack(rectangle, packedBuffer, offset);
    offset += Rectangle.packedLength;

    Ellipsoid.pack(ellipsoid, packedBuffer, offset);
    offset += Ellipsoid.packedLength;

    Cartesian3.pack(center, packedBuffer, offset);

    return packedBuffer;
  }

  const createVerticesTaskProcessor$1 = new TaskProcessor(
    "createVectorTilePolylines",
    5
  );
  const attributeLocations$4 = {
    previousPosition: 0,
    currentPosition: 1,
    nextPosition: 2,
    expandAndWidth: 3,
    a_batchId: 4,
  };

  function createVertexArray$2(polylines, context) {
    if (defined(polylines._va)) {
      return;
    }

    if (!defined(polylines._verticesPromise)) {
      let positions = polylines._positions;
      let widths = polylines._widths;
      let counts = polylines._counts;
      let batchIds = polylines._transferrableBatchIds;

      let packedBuffer = polylines._packedBuffer;

      if (!defined(packedBuffer)) {
        // Copy because they may be the views on the same buffer.
        positions = polylines._positions = positions.slice();
        widths = polylines._widths = widths.slice();
        counts = polylines._counts = counts.slice();

        batchIds = polylines._transferrableBatchIds = polylines._batchIds.slice();

        packedBuffer = polylines._packedBuffer = packBuffer$1(polylines);
      }

      const transferrableObjects = [
        positions.buffer,
        widths.buffer,
        counts.buffer,
        batchIds.buffer,
        packedBuffer.buffer,
      ];
      const parameters = {
        positions: positions.buffer,
        widths: widths.buffer,
        counts: counts.buffer,
        batchIds: batchIds.buffer,
        packedBuffer: packedBuffer.buffer,
        keepDecodedPositions: polylines._keepDecodedPositions,
      };

      const verticesPromise = (polylines._verticesPromise = createVerticesTaskProcessor$1.scheduleTask(
        parameters,
        transferrableObjects
      ));
      if (!defined(verticesPromise)) {
        // Postponed
        return;
      }

      return verticesPromise.then(function (result) {
        if (polylines._keepDecodedPositions) {
          polylines._decodedPositions = new Float64Array(result.decodedPositions);
          polylines._decodedPositionOffsets = new Uint32Array(
            result.decodedPositionOffsets
          );
        }

        polylines._currentPositions = new Float32Array(result.currentPositions);
        polylines._previousPositions = new Float32Array(result.previousPositions);
        polylines._nextPositions = new Float32Array(result.nextPositions);
        polylines._expandAndWidth = new Float32Array(result.expandAndWidth);
        polylines._vertexBatchIds = new Uint16Array(result.batchIds);

        const indexDatatype = result.indexDatatype;
        polylines._indices =
          indexDatatype === IndexDatatype$1.UNSIGNED_SHORT
            ? new Uint16Array(result.indices)
            : new Uint32Array(result.indices);

        polylines._ready = true;
      });
    }
  }

  function finishVertexArray$1(polylines, context) {
    if (polylines._ready && !defined(polylines._va)) {
      const curPositions = polylines._currentPositions;
      const prevPositions = polylines._previousPositions;
      const nextPositions = polylines._nextPositions;
      const expandAndWidth = polylines._expandAndWidth;
      const vertexBatchIds = polylines._vertexBatchIds;
      const indices = polylines._indices;

      let byteLength =
        prevPositions.byteLength +
        curPositions.byteLength +
        nextPositions.byteLength;
      byteLength +=
        expandAndWidth.byteLength +
        vertexBatchIds.byteLength +
        indices.byteLength;
      polylines._trianglesLength = indices.length / 3;
      polylines._geometryByteLength = byteLength;

      const prevPositionBuffer = Buffer$1.createVertexBuffer({
        context: context,
        typedArray: prevPositions,
        usage: BufferUsage$1.STATIC_DRAW,
      });
      const curPositionBuffer = Buffer$1.createVertexBuffer({
        context: context,
        typedArray: curPositions,
        usage: BufferUsage$1.STATIC_DRAW,
      });
      const nextPositionBuffer = Buffer$1.createVertexBuffer({
        context: context,
        typedArray: nextPositions,
        usage: BufferUsage$1.STATIC_DRAW,
      });
      const expandAndWidthBuffer = Buffer$1.createVertexBuffer({
        context: context,
        typedArray: expandAndWidth,
        usage: BufferUsage$1.STATIC_DRAW,
      });
      const idBuffer = Buffer$1.createVertexBuffer({
        context: context,
        typedArray: vertexBatchIds,
        usage: BufferUsage$1.STATIC_DRAW,
      });

      const indexBuffer = Buffer$1.createIndexBuffer({
        context: context,
        typedArray: indices,
        usage: BufferUsage$1.STATIC_DRAW,
        indexDatatype:
          indices.BYTES_PER_ELEMENT === 2
            ? IndexDatatype$1.UNSIGNED_SHORT
            : IndexDatatype$1.UNSIGNED_INT,
      });

      const vertexAttributes = [
        {
          index: attributeLocations$4.previousPosition,
          vertexBuffer: prevPositionBuffer,
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 3,
        },
        {
          index: attributeLocations$4.currentPosition,
          vertexBuffer: curPositionBuffer,
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 3,
        },
        {
          index: attributeLocations$4.nextPosition,
          vertexBuffer: nextPositionBuffer,
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 3,
        },
        {
          index: attributeLocations$4.expandAndWidth,
          vertexBuffer: expandAndWidthBuffer,
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 2,
        },
        {
          index: attributeLocations$4.a_batchId,
          vertexBuffer: idBuffer,
          componentDatatype: ComponentDatatype$1.UNSIGNED_SHORT,
          componentsPerAttribute: 1,
        },
      ];

      polylines._va = new VertexArray({
        context: context,
        attributes: vertexAttributes,
        indexBuffer: indexBuffer,
      });

      polylines._positions = undefined;
      polylines._widths = undefined;
      polylines._counts = undefined;

      polylines._ellipsoid = undefined;
      polylines._minimumHeight = undefined;
      polylines._maximumHeight = undefined;
      polylines._rectangle = undefined;

      polylines._transferrableBatchIds = undefined;
      polylines._packedBuffer = undefined;

      polylines._currentPositions = undefined;
      polylines._previousPositions = undefined;
      polylines._nextPositions = undefined;
      polylines._expandAndWidth = undefined;
      polylines._vertexBatchIds = undefined;
      polylines._indices = undefined;
    }
  }

  const modifiedModelViewScratch$2 = new Matrix4();
  const rtcScratch$2 = new Cartesian3();

  function createUniformMap$3(primitive, context) {
    if (defined(primitive._uniformMap)) {
      return;
    }

    primitive._uniformMap = {
      u_modifiedModelView: function () {
        const viewMatrix = context.uniformState.view;
        Matrix4.clone(viewMatrix, modifiedModelViewScratch$2);
        Matrix4.multiplyByPoint(
          modifiedModelViewScratch$2,
          primitive._center,
          rtcScratch$2
        );
        Matrix4.setTranslation(
          modifiedModelViewScratch$2,
          rtcScratch$2,
          modifiedModelViewScratch$2
        );
        return modifiedModelViewScratch$2;
      },
      u_highlightColor: function () {
        return primitive._highlightColor;
      },
    };
  }

  function createRenderStates$2(primitive) {
    if (defined(primitive._rs)) {
      return;
    }

    const polygonOffset = {
      enabled: true,
      factor: -5.0,
      units: -5.0,
    };

    primitive._rs = RenderState.fromCache({
      blending: BlendingState$1.ALPHA_BLEND,
      depthMask: false,
      depthTest: {
        enabled: true,
      },
      polygonOffset: polygonOffset,
    });
  }

  const PolylineFS =
    "uniform vec4 u_highlightColor; \n" +
    "void main()\n" +
    "{\n" +
    "    gl_FragColor = u_highlightColor;\n" +
    "}\n";

  function createShaders$1(primitive, context) {
    if (defined(primitive._sp)) {
      return;
    }

    const batchTable = primitive._batchTable;

    const vsSource = batchTable.getVertexShaderCallback(
      false,
      "a_batchId",
      undefined
    )(Vector3DTilePolylinesVS);
    const fsSource = batchTable.getFragmentShaderCallback(
      false,
      undefined,
      false
    )(PolylineFS);

    const vs = new ShaderSource({
      defines: [
        "VECTOR_TILE",
        !FeatureDetection.isInternetExplorer() ? "CLIP_POLYLINE" : "",
      ],
      sources: [PolylineCommon, vsSource],
    });
    const fs = new ShaderSource({
      defines: ["VECTOR_TILE"],
      sources: [fsSource],
    });

    primitive._sp = ShaderProgram.fromCache({
      context: context,
      vertexShaderSource: vs,
      fragmentShaderSource: fs,
      attributeLocations: attributeLocations$4,
    });
  }

  function queueCommands$1(primitive, frameState) {
    if (!defined(primitive._command)) {
      const uniformMap = primitive._batchTable.getUniformMapCallback()(
        primitive._uniformMap
      );
      primitive._command = new DrawCommand({
        owner: primitive,
        vertexArray: primitive._va,
        renderState: primitive._rs,
        shaderProgram: primitive._sp,
        uniformMap: uniformMap,
        boundingVolume: primitive._boundingVolume,
        pass: Pass$1.TRANSLUCENT,
        pickId: primitive._batchTable.getPickId(),
      });
    }

    frameState.commandList.push(primitive._command);
  }

  Vector3DTilePolylines.getPolylinePositions = function (polylines, batchId) {
    const batchIds = polylines._batchIds;
    const positions = polylines._decodedPositions;
    const offsets = polylines._decodedPositionOffsets;

    if (!defined(batchIds) || !defined(positions)) {
      return undefined;
    }

    let i;
    let j;
    const polylinesLength = batchIds.length;
    let positionsLength = 0;
    let resultCounter = 0;

    for (i = 0; i < polylinesLength; ++i) {
      if (batchIds[i] === batchId) {
        positionsLength += offsets[i + 1] - offsets[i];
      }
    }

    if (positionsLength === 0) {
      return undefined;
    }

    const results = new Float64Array(positionsLength * 3);

    for (i = 0; i < polylinesLength; ++i) {
      if (batchIds[i] === batchId) {
        const offset = offsets[i];
        const count = offsets[i + 1] - offset;
        for (j = 0; j < count; ++j) {
          const decodedOffset = (offset + j) * 3;
          results[resultCounter++] = positions[decodedOffset];
          results[resultCounter++] = positions[decodedOffset + 1];
          results[resultCounter++] = positions[decodedOffset + 2];
        }
      }
    }

    return results;
  };

  /**
   * Get the polyline positions for the given feature.
   *
   * @param {Number} batchId The batch ID of the feature.
   */
  Vector3DTilePolylines.prototype.getPositions = function (batchId) {
    return Vector3DTilePolylines.getPolylinePositions(this, batchId);
  };

  /**
   * Creates features for each polyline and places it at the batch id index of features.
   *
   * @param {Vector3DTileContent} content The vector tile content.
   * @param {Cesium3DTileFeature[]} features An array of features where the polygon features will be placed.
   */
  Vector3DTilePolylines.prototype.createFeatures = function (content, features) {
    const batchIds = this._batchIds;
    const length = batchIds.length;
    for (let i = 0; i < length; ++i) {
      const batchId = batchIds[i];
      features[batchId] = new Cesium3DTileFeature(content, batchId);
    }
  };

  /**
   * Colors the entire tile when enabled is true. The resulting color will be (polyline batch table color * color).
   *
   * @param {Boolean} enabled Whether to enable debug coloring.
   * @param {Color} color The debug color.
   */
  Vector3DTilePolylines.prototype.applyDebugSettings = function (enabled, color) {
    this._highlightColor = enabled ? color : this._constantColor;
  };

  function clearStyle$1(polygons, features) {
    const batchIds = polygons._batchIds;
    const length = batchIds.length;
    for (let i = 0; i < length; ++i) {
      const batchId = batchIds[i];
      const feature = features[batchId];

      feature.show = true;
      feature.color = Color.WHITE;
    }
  }

  const scratchColor$g = new Color();

  const DEFAULT_COLOR_VALUE$1 = Color.WHITE;
  const DEFAULT_SHOW_VALUE$1 = true;

  /**
   * Apply a style to the content.
   *
   * @param {Cesium3DTileStyle} style The style.
   * @param {Cesium3DTileFeature[]} features The array of features.
   */
  Vector3DTilePolylines.prototype.applyStyle = function (style, features) {
    if (!defined(style)) {
      clearStyle$1(this, features);
      return;
    }

    const batchIds = this._batchIds;
    const length = batchIds.length;
    for (let i = 0; i < length; ++i) {
      const batchId = batchIds[i];
      const feature = features[batchId];

      feature.color = defined(style.color)
        ? style.color.evaluateColor(feature, scratchColor$g)
        : DEFAULT_COLOR_VALUE$1;
      feature.show = defined(style.show)
        ? style.show.evaluate(feature)
        : DEFAULT_SHOW_VALUE$1;
    }
  };

  function initialize$b(polylines) {
    return new Promise(function (resolve, reject) {
      polylines._update = function (polylines, frameState) {
        const context = frameState.context;
        const promise = createVertexArray$2(polylines);
        createUniformMap$3(polylines, context);
        createShaders$1(polylines, context);
        createRenderStates$2(polylines);

        if (polylines._ready) {
          const passes = frameState.passes;
          if (passes.render || passes.pick) {
            queueCommands$1(polylines, frameState);
          }
        }

        if (!defined(promise)) {
          return;
        }

        promise
          .then(function () {
            finishVertexArray$1(polylines, context);
            resolve();
          })
          .catch(function (e) {
            reject(e);
          });
      };
    });
  }

  /**
   * Updates the batches and queues the commands for rendering.
   *
   * @param {FrameState} frameState The current frame state.
   */
  Vector3DTilePolylines.prototype.update = function (frameState) {
    this._update(this, frameState);
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <p>
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   * </p>
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   */
  Vector3DTilePolylines.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <p>
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   * </p>
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   */
  Vector3DTilePolylines.prototype.destroy = function () {
    this._va = this._va && this._va.destroy();
    this._sp = this._sp && this._sp.destroy();
    return destroyObject(this);
  };

  //This file is automatically rebuilt by the Cesium build process.
  var Vector3DTileClampedPolylinesVS = "attribute vec3 startEllipsoidNormal;\n\
attribute vec3 endEllipsoidNormal;\n\
attribute vec4 startPositionAndHeight;\n\
attribute vec4 endPositionAndHeight;\n\
attribute vec4 startFaceNormalAndVertexCorner;\n\
attribute vec4 endFaceNormalAndHalfWidth;\n\
attribute float a_batchId;\n\
uniform mat4 u_modifiedModelView;\n\
uniform vec2 u_minimumMaximumVectorHeights;\n\
varying vec4 v_startPlaneEC;\n\
varying vec4 v_endPlaneEC;\n\
varying vec4 v_rightPlaneEC;\n\
varying float v_halfWidth;\n\
varying vec3 v_volumeUpEC;\n\
void main()\n\
{\n\
float isEnd = floor(startFaceNormalAndVertexCorner.w * 0.251);\n\
float isTop = floor(startFaceNormalAndVertexCorner.w * mix(0.51, 0.19, isEnd));\n\
vec3 forward = endPositionAndHeight.xyz - startPositionAndHeight.xyz;\n\
vec3 right = normalize(cross(forward, startEllipsoidNormal));\n\
vec4 position = vec4(startPositionAndHeight.xyz, 1.0);\n\
position.xyz += forward * isEnd;\n\
v_volumeUpEC = czm_normal * normalize(cross(right, forward));\n\
float offset;\n\
vec3 ellipsoidNormal = mix(startEllipsoidNormal, endEllipsoidNormal, isEnd);\n\
offset = mix(startPositionAndHeight.w, endPositionAndHeight.w, isEnd);\n\
offset = mix(u_minimumMaximumVectorHeights.y, u_minimumMaximumVectorHeights.x, isTop) - offset;\n\
position.xyz += offset * ellipsoidNormal;\n\
position = u_modifiedModelView * position;\n\
right = czm_normal * right;\n\
vec3 scratchNormal = mix(-startFaceNormalAndVertexCorner.xyz, endFaceNormalAndHalfWidth.xyz, isEnd);\n\
scratchNormal = cross(scratchNormal, mix(startEllipsoidNormal, endEllipsoidNormal, isEnd));\n\
vec3 miterPushNormal = czm_normal * normalize(scratchNormal);\n\
offset = 2.0 * endFaceNormalAndHalfWidth.w * max(0.0, czm_metersPerPixel(position));\n\
offset = offset / dot(miterPushNormal, right);\n\
position.xyz += miterPushNormal * (offset * sign(0.5 - mod(startFaceNormalAndVertexCorner.w, 2.0)));\n\
gl_Position = czm_depthClamp(czm_projection * position);\n\
position = u_modifiedModelView * vec4(startPositionAndHeight.xyz, 1.0);\n\
vec3 startNormalEC = czm_normal * startFaceNormalAndVertexCorner.xyz;\n\
v_startPlaneEC = vec4(startNormalEC, -dot(startNormalEC, position.xyz));\n\
v_rightPlaneEC = vec4(right, -dot(right, position.xyz));\n\
position = u_modifiedModelView * vec4(endPositionAndHeight.xyz, 1.0);\n\
vec3 endNormalEC = czm_normal * endFaceNormalAndHalfWidth.xyz;\n\
v_endPlaneEC = vec4(endNormalEC, -dot(endNormalEC, position.xyz));\n\
v_halfWidth = endFaceNormalAndHalfWidth.w;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var Vector3DTileClampedPolylinesFS = "#ifdef GL_EXT_frag_depth\n\
#extension GL_EXT_frag_depth : enable\n\
#endif\n\
varying vec4 v_startPlaneEC;\n\
varying vec4 v_endPlaneEC;\n\
varying vec4 v_rightPlaneEC;\n\
varying float v_halfWidth;\n\
varying vec3 v_volumeUpEC;\n\
uniform vec4 u_highlightColor;\n\
void main()\n\
{\n\
float logDepthOrDepth = czm_branchFreeTernary(czm_sceneMode == czm_sceneMode2D, gl_FragCoord.z, czm_unpackDepth(texture2D(czm_globeDepthTexture, gl_FragCoord.xy / czm_viewport.zw)));\n\
if (logDepthOrDepth == 0.0) {\n\
#ifdef DEBUG_SHOW_VOLUME\n\
gl_FragColor = vec4(0.0, 0.0, 1.0, 0.5);\n\
return;\n\
#else // DEBUG_SHOW_VOLUME\n\
discard;\n\
#endif // DEBUG_SHOW_VOLUME\n\
}\n\
vec4 eyeCoordinate = czm_windowToEyeCoordinates(gl_FragCoord.xy, logDepthOrDepth);\n\
eyeCoordinate /= eyeCoordinate.w;\n\
float halfMaxWidth = v_halfWidth * czm_metersPerPixel(eyeCoordinate);\n\
halfMaxWidth += halfMaxWidth * (1.0 - dot(-normalize(eyeCoordinate.xyz), v_volumeUpEC));\n\
float widthwiseDistance = czm_planeDistance(v_rightPlaneEC, eyeCoordinate.xyz);\n\
float distanceFromStart = czm_planeDistance(v_startPlaneEC, eyeCoordinate.xyz);\n\
float distanceFromEnd = czm_planeDistance(v_endPlaneEC, eyeCoordinate.xyz);\n\
if (abs(widthwiseDistance) > halfMaxWidth || distanceFromStart < 0.0 || distanceFromEnd < 0.0) {\n\
#ifdef DEBUG_SHOW_VOLUME\n\
gl_FragColor = vec4(logDepthOrDepth, 0.0, 0.0, 0.5);\n\
return;\n\
#else // DEBUG_SHOW_VOLUME\n\
discard;\n\
#endif // DEBUG_SHOW_VOLUME\n\
}\n\
gl_FragColor = u_highlightColor;\n\
czm_writeDepthClamp();\n\
}\n\
";

  /**
   * Creates a batch of polylines as volumes with shader-adjustable width.
   *
   * @alias Vector3DTileClampedPolylines
   * @constructor
   *
   * @param {Object} options An object with following properties:
   * @param {Uint16Array} options.positions The positions of the polylines
   * @param {Uint32Array} options.counts The number or positions in the each polyline.
   * @param {Uint16Array} options.widths The width of each polyline.
   * @param {Number} options.minimumHeight The minimum height of the tile's region.
   * @param {Number} options.maximumHeight The maximum height of the tile's region.
   * @param {Rectangle} options.rectangle The rectangle containing the tile.
   * @param {Cartesian3} [options.center=Cartesian3.ZERO] The RTC center.
   * @param {Cesium3DTileBatchTable} options.batchTable The batch table for the tile containing the batched polylines.
   * @param {Uint16Array} options.batchIds The batch ids for each polyline.
   * @param {ClassificationType} options.classificationType The classification type.
   * @param {Boolean} options.keepDecodedPositions Whether to keep decoded positions in memory.
   *
   * @private
   */
  function Vector3DTileClampedPolylines(options) {
    // these arrays hold data from the tile payload
    // and are all released after the first update.
    this._positions = options.positions;
    this._widths = options.widths;
    this._counts = options.counts;
    this._batchIds = options.batchIds;

    this._ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);
    this._minimumHeight = options.minimumHeight;
    this._maximumHeight = options.maximumHeight;
    this._center = options.center;
    this._rectangle = options.rectangle;

    this._batchTable = options.batchTable;

    this._va = undefined;
    this._sp = undefined;
    this._rs = undefined;
    this._uniformMap = undefined;
    this._command = undefined;

    this._transferrableBatchIds = undefined;
    this._packedBuffer = undefined;
    this._minimumMaximumVectorHeights = new Cartesian2(
      ApproximateTerrainHeights._defaultMinTerrainHeight,
      ApproximateTerrainHeights._defaultMaxTerrainHeight
    );
    this._boundingVolume = OrientedBoundingBox.fromRectangle(
      options.rectangle,
      ApproximateTerrainHeights._defaultMinTerrainHeight,
      ApproximateTerrainHeights._defaultMaxTerrainHeight,
      this._ellipsoid
    );
    this._classificationType = options.classificationType;

    this._keepDecodedPositions = options.keepDecodedPositions;
    this._decodedPositions = undefined;
    this._decodedPositionOffsets = undefined;

    // Fat vertices - all information for each volume packed to a vec3 and 5 vec4s
    this._startEllipsoidNormals = undefined;
    this._endEllipsoidNormals = undefined;
    this._startPositionAndHeights = undefined;
    this._startFaceNormalAndVertexCornerIds = undefined;
    this._endPositionAndHeights = undefined;
    this._endFaceNormalAndHalfWidths = undefined;
    this._vertexBatchIds = undefined;

    this._indices = undefined;

    this._constantColor = Color.clone(Color.WHITE);
    this._highlightColor = this._constantColor;

    this._trianglesLength = 0;
    this._geometryByteLength = 0;

    this._ready = false;
    this._update = function (polylines, frameState) {};
    this._readyPromise = initialize$a(this);
    this._verticesPromise = undefined;
  }

  Object.defineProperties(Vector3DTileClampedPolylines.prototype, {
    /**
     * Gets the number of triangles.
     *
     * @memberof Vector3DTileClampedPolylines.prototype
     *
     * @type {Number}
     * @readonly
     */
    trianglesLength: {
      get: function () {
        return this._trianglesLength;
      },
    },

    /**
     * Gets the geometry memory in bytes.
     *
     * @memberof Vector3DTileClampedPolylines.prototype
     *
     * @type {Number}
     * @readonly
     */
    geometryByteLength: {
      get: function () {
        return this._geometryByteLength;
      },
    },

    /**
     * Gets a promise that resolves when the primitive is ready to render.
     * @memberof Vector3DTileClampedPolylines.prototype
     * @type {Promise}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._readyPromise;
      },
    },
  });

  function updateMinimumMaximumHeights(polylines, rectangle, ellipsoid) {
    const result = ApproximateTerrainHeights.getMinimumMaximumHeights(
      rectangle,
      ellipsoid
    );
    const min = result.minimumTerrainHeight;
    const max = result.maximumTerrainHeight;
    const minimumMaximumVectorHeights = polylines._minimumMaximumVectorHeights;
    minimumMaximumVectorHeights.x = min;
    minimumMaximumVectorHeights.y = max;

    const obb = polylines._boundingVolume;
    const rect = polylines._rectangle;
    OrientedBoundingBox.fromRectangle(rect, min, max, ellipsoid, obb);
  }

  function packBuffer(polylines) {
    const rectangle = polylines._rectangle;
    const minimumHeight = polylines._minimumHeight;
    const maximumHeight = polylines._maximumHeight;
    const ellipsoid = polylines._ellipsoid;
    const center = polylines._center;

    const packedLength =
      2 +
      Rectangle.packedLength +
      Ellipsoid.packedLength +
      Cartesian3.packedLength;
    const packedBuffer = new Float64Array(packedLength);

    let offset = 0;
    packedBuffer[offset++] = minimumHeight;
    packedBuffer[offset++] = maximumHeight;

    Rectangle.pack(rectangle, packedBuffer, offset);
    offset += Rectangle.packedLength;

    Ellipsoid.pack(ellipsoid, packedBuffer, offset);
    offset += Ellipsoid.packedLength;

    Cartesian3.pack(center, packedBuffer, offset);

    return packedBuffer;
  }

  const createVerticesTaskProcessor = new TaskProcessor(
    "createVectorTileClampedPolylines"
  );
  const attributeLocations$3 = {
    startEllipsoidNormal: 0,
    endEllipsoidNormal: 1,
    startPositionAndHeight: 2,
    endPositionAndHeight: 3,
    startFaceNormalAndVertexCorner: 4,
    endFaceNormalAndHalfWidth: 5,
    a_batchId: 6,
  };

  function createVertexArray$1(polylines, context) {
    if (defined(polylines._va)) {
      return;
    }

    if (!defined(polylines._verticesPromise)) {
      let positions = polylines._positions;
      let widths = polylines._widths;
      let counts = polylines._counts;
      let batchIds = polylines._transferrableBatchIds;

      let packedBuffer = polylines._packedBuffer;

      if (!defined(packedBuffer)) {
        // Copy because they may be the views on the same buffer.
        positions = polylines._positions = positions.slice();
        widths = polylines._widths = widths.slice();
        counts = polylines._counts = counts.slice();

        batchIds = polylines._transferrableBatchIds = polylines._batchIds.slice();

        packedBuffer = polylines._packedBuffer = packBuffer(polylines);
      }

      const transferrableObjects = [
        positions.buffer,
        widths.buffer,
        counts.buffer,
        batchIds.buffer,
        packedBuffer.buffer,
      ];
      const parameters = {
        positions: positions.buffer,
        widths: widths.buffer,
        counts: counts.buffer,
        batchIds: batchIds.buffer,
        packedBuffer: packedBuffer.buffer,
        keepDecodedPositions: polylines._keepDecodedPositions,
      };

      const verticesPromise = (polylines._verticesPromise = createVerticesTaskProcessor.scheduleTask(
        parameters,
        transferrableObjects
      ));
      if (!defined(verticesPromise)) {
        // Postponed
        return;
      }

      return verticesPromise.then(function (result) {
        if (polylines._keepDecodedPositions) {
          polylines._decodedPositions = new Float64Array(result.decodedPositions);
          polylines._decodedPositionOffsets = new Uint32Array(
            result.decodedPositionOffsets
          );
        }

        polylines._startEllipsoidNormals = new Float32Array(
          result.startEllipsoidNormals
        );
        polylines._endEllipsoidNormals = new Float32Array(
          result.endEllipsoidNormals
        );
        polylines._startPositionAndHeights = new Float32Array(
          result.startPositionAndHeights
        );
        polylines._startFaceNormalAndVertexCornerIds = new Float32Array(
          result.startFaceNormalAndVertexCornerIds
        );
        polylines._endPositionAndHeights = new Float32Array(
          result.endPositionAndHeights
        );
        polylines._endFaceNormalAndHalfWidths = new Float32Array(
          result.endFaceNormalAndHalfWidths
        );
        polylines._vertexBatchIds = new Uint16Array(result.vertexBatchIds);

        const indexDatatype = result.indexDatatype;
        polylines._indices =
          indexDatatype === IndexDatatype$1.UNSIGNED_SHORT
            ? new Uint16Array(result.indices)
            : new Uint32Array(result.indices);

        polylines._ready = true;
      });
    }
  }

  function finishVertexArray(polylines, context) {
    if (polylines._ready && !defined(polylines._va)) {
      const startEllipsoidNormals = polylines._startEllipsoidNormals;
      const endEllipsoidNormals = polylines._endEllipsoidNormals;
      const startPositionAndHeights = polylines._startPositionAndHeights;
      const endPositionAndHeights = polylines._endPositionAndHeights;
      const startFaceNormalAndVertexCornerIds =
        polylines._startFaceNormalAndVertexCornerIds;
      const endFaceNormalAndHalfWidths = polylines._endFaceNormalAndHalfWidths;
      const batchIdAttribute = polylines._vertexBatchIds;

      const indices = polylines._indices;

      let byteLength =
        startEllipsoidNormals.byteLength + endEllipsoidNormals.byteLength;
      byteLength +=
        startPositionAndHeights.byteLength + endPositionAndHeights.byteLength;
      byteLength +=
        startFaceNormalAndVertexCornerIds.byteLength +
        endFaceNormalAndHalfWidths.byteLength;
      byteLength += batchIdAttribute.byteLength + indices.byteLength;

      polylines._trianglesLength = indices.length / 3;
      polylines._geometryByteLength = byteLength;

      const startEllipsoidNormalsBuffer = Buffer$1.createVertexBuffer({
        context: context,
        typedArray: startEllipsoidNormals,
        usage: BufferUsage$1.STATIC_DRAW,
      });
      const endEllipsoidNormalsBuffer = Buffer$1.createVertexBuffer({
        context: context,
        typedArray: endEllipsoidNormals,
        usage: BufferUsage$1.STATIC_DRAW,
      });
      const startPositionAndHeightsBuffer = Buffer$1.createVertexBuffer({
        context: context,
        typedArray: startPositionAndHeights,
        usage: BufferUsage$1.STATIC_DRAW,
      });
      const endPositionAndHeightsBuffer = Buffer$1.createVertexBuffer({
        context: context,
        typedArray: endPositionAndHeights,
        usage: BufferUsage$1.STATIC_DRAW,
      });
      const startFaceNormalAndVertexCornerIdsBuffer = Buffer$1.createVertexBuffer({
        context: context,
        typedArray: startFaceNormalAndVertexCornerIds,
        usage: BufferUsage$1.STATIC_DRAW,
      });
      const endFaceNormalAndHalfWidthsBuffer = Buffer$1.createVertexBuffer({
        context: context,
        typedArray: endFaceNormalAndHalfWidths,
        usage: BufferUsage$1.STATIC_DRAW,
      });
      const batchIdAttributeBuffer = Buffer$1.createVertexBuffer({
        context: context,
        typedArray: batchIdAttribute,
        usage: BufferUsage$1.STATIC_DRAW,
      });

      const indexBuffer = Buffer$1.createIndexBuffer({
        context: context,
        typedArray: indices,
        usage: BufferUsage$1.STATIC_DRAW,
        indexDatatype:
          indices.BYTES_PER_ELEMENT === 2
            ? IndexDatatype$1.UNSIGNED_SHORT
            : IndexDatatype$1.UNSIGNED_INT,
      });

      const vertexAttributes = [
        {
          index: attributeLocations$3.startEllipsoidNormal,
          vertexBuffer: startEllipsoidNormalsBuffer,
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 3,
        },
        {
          index: attributeLocations$3.endEllipsoidNormal,
          vertexBuffer: endEllipsoidNormalsBuffer,
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 3,
        },
        {
          index: attributeLocations$3.startPositionAndHeight,
          vertexBuffer: startPositionAndHeightsBuffer,
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 4,
        },
        {
          index: attributeLocations$3.endPositionAndHeight,
          vertexBuffer: endPositionAndHeightsBuffer,
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 4,
        },
        {
          index: attributeLocations$3.startFaceNormalAndVertexCorner,
          vertexBuffer: startFaceNormalAndVertexCornerIdsBuffer,
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 4,
        },
        {
          index: attributeLocations$3.endFaceNormalAndHalfWidth,
          vertexBuffer: endFaceNormalAndHalfWidthsBuffer,
          componentDatatype: ComponentDatatype$1.FLOAT,
          componentsPerAttribute: 4,
        },
        {
          index: attributeLocations$3.a_batchId,
          vertexBuffer: batchIdAttributeBuffer,
          componentDatatype: ComponentDatatype$1.UNSIGNED_SHORT,
          componentsPerAttribute: 1,
        },
      ];

      polylines._va = new VertexArray({
        context: context,
        attributes: vertexAttributes,
        indexBuffer: indexBuffer,
      });

      polylines._positions = undefined;
      polylines._widths = undefined;
      polylines._counts = undefined;

      polylines._ellipsoid = undefined;
      polylines._minimumHeight = undefined;
      polylines._maximumHeight = undefined;
      polylines._rectangle = undefined;

      polylines._transferrableBatchIds = undefined;
      polylines._packedBuffer = undefined;

      polylines._startEllipsoidNormals = undefined;
      polylines._endEllipsoidNormals = undefined;
      polylines._startPositionAndHeights = undefined;
      polylines._startFaceNormalAndVertexCornerIds = undefined;
      polylines._endPositionAndHeights = undefined;
      polylines._endFaceNormalAndHalfWidths = undefined;
      polylines._vertexBatchIds = undefined;

      polylines._indices = undefined;
    }
  }

  const modifiedModelViewScratch$1 = new Matrix4();
  const rtcScratch$1 = new Cartesian3();

  function createUniformMap$2(primitive, context) {
    if (defined(primitive._uniformMap)) {
      return;
    }

    primitive._uniformMap = {
      u_modifiedModelView: function () {
        const viewMatrix = context.uniformState.view;
        Matrix4.clone(viewMatrix, modifiedModelViewScratch$1);
        Matrix4.multiplyByPoint(
          modifiedModelViewScratch$1,
          primitive._center,
          rtcScratch$1
        );
        Matrix4.setTranslation(
          modifiedModelViewScratch$1,
          rtcScratch$1,
          modifiedModelViewScratch$1
        );
        return modifiedModelViewScratch$1;
      },
      u_highlightColor: function () {
        return primitive._highlightColor;
      },
      u_minimumMaximumVectorHeights: function () {
        return primitive._minimumMaximumVectorHeights;
      },
    };
  }

  function getRenderState(mask3DTiles) {
    /**
     * Cull front faces of each volume (relative to camera) to prevent
     * classification drawing from both the front and back faces, double-draw.
     * The geometry is "inverted" (inside-out winding order for the indices) but
     * the vertex shader seems to re-invert so that the triangles face "out" again.
     * So cull FRONT faces.
     */
    return RenderState.fromCache({
      cull: {
        enabled: true,
        face: CullFace$1.FRONT,
      },
      blending: BlendingState$1.PRE_MULTIPLIED_ALPHA_BLEND,
      depthMask: false,
      stencilTest: {
        enabled: mask3DTiles,
        frontFunction: StencilFunction$1.EQUAL,
        frontOperation: {
          fail: StencilOperation$1.KEEP,
          zFail: StencilOperation$1.KEEP,
          zPass: StencilOperation$1.KEEP,
        },
        backFunction: StencilFunction$1.EQUAL,
        backOperation: {
          fail: StencilOperation$1.KEEP,
          zFail: StencilOperation$1.KEEP,
          zPass: StencilOperation$1.KEEP,
        },
        reference: StencilConstants$1.CESIUM_3D_TILE_MASK,
        mask: StencilConstants$1.CESIUM_3D_TILE_MASK,
      },
    });
  }

  function createRenderStates$1(primitive) {
    if (defined(primitive._rs)) {
      return;
    }

    primitive._rs = getRenderState(false);
    primitive._rs3DTiles = getRenderState(true);
  }

  function createShaders(primitive, context) {
    if (defined(primitive._sp)) {
      return;
    }

    const batchTable = primitive._batchTable;

    const vsSource = batchTable.getVertexShaderCallback(
      false,
      "a_batchId",
      undefined
    )(Vector3DTileClampedPolylinesVS);
    const fsSource = batchTable.getFragmentShaderCallback(
      false,
      undefined,
      true
    )(Vector3DTileClampedPolylinesFS);

    const vs = new ShaderSource({
      defines: [
        "VECTOR_TILE",
        !FeatureDetection.isInternetExplorer() ? "CLIP_POLYLINE" : "",
      ],
      sources: [PolylineCommon, vsSource],
    });
    const fs = new ShaderSource({
      defines: ["VECTOR_TILE"],
      sources: [fsSource],
    });

    primitive._sp = ShaderProgram.fromCache({
      context: context,
      vertexShaderSource: vs,
      fragmentShaderSource: fs,
      attributeLocations: attributeLocations$3,
    });
  }

  function queueCommands(primitive, frameState) {
    let command = primitive._command;
    if (!defined(primitive._command)) {
      const uniformMap = primitive._batchTable.getUniformMapCallback()(
        primitive._uniformMap
      );
      command = primitive._command = new DrawCommand({
        owner: primitive,
        vertexArray: primitive._va,
        renderState: primitive._rs,
        shaderProgram: primitive._sp,
        uniformMap: uniformMap,
        boundingVolume: primitive._boundingVolume,
        pass: Pass$1.TERRAIN_CLASSIFICATION,
        pickId: primitive._batchTable.getPickId(),
      });

      const derivedTilesetCommand = DrawCommand.shallowClone(
        command,
        command.derivedCommands.tileset
      );
      derivedTilesetCommand.renderState = primitive._rs3DTiles;
      derivedTilesetCommand.pass = Pass$1.CESIUM_3D_TILE_CLASSIFICATION;
      command.derivedCommands.tileset = derivedTilesetCommand;
    }

    const classificationType = primitive._classificationType;
    if (
      classificationType === ClassificationType$1.TERRAIN ||
      classificationType === ClassificationType$1.BOTH
    ) {
      frameState.commandList.push(command);
    }
    if (
      classificationType === ClassificationType$1.CESIUM_3D_TILE ||
      classificationType === ClassificationType$1.BOTH
    ) {
      frameState.commandList.push(command.derivedCommands.tileset);
    }
  }

  /**
   * Get the polyline positions for the given feature.
   *
   * @param {Number} batchId The batch ID of the feature.
   */
  Vector3DTileClampedPolylines.prototype.getPositions = function (batchId) {
    return Vector3DTilePolylines.getPolylinePositions(this, batchId);
  };

  /**
   * Creates features for each polyline and places it at the batch id index of features.
   *
   * @param {Vector3DTileContent} content The vector tile content.
   * @param {Cesium3DTileFeature[]} features An array of features where the polygon features will be placed.
   */
  Vector3DTileClampedPolylines.prototype.createFeatures = function (
    content,
    features
  ) {
    const batchIds = this._batchIds;
    const length = batchIds.length;
    for (let i = 0; i < length; ++i) {
      const batchId = batchIds[i];
      features[batchId] = new Cesium3DTileFeature(content, batchId);
    }
  };

  /**
   * Colors the entire tile when enabled is true. The resulting color will be (polyline batch table color * color).
   *
   * @param {Boolean} enabled Whether to enable debug coloring.
   * @param {Color} color The debug color.
   */
  Vector3DTileClampedPolylines.prototype.applyDebugSettings = function (
    enabled,
    color
  ) {
    this._highlightColor = enabled ? color : this._constantColor;
  };

  function clearStyle(polygons, features) {
    const batchIds = polygons._batchIds;
    const length = batchIds.length;
    for (let i = 0; i < length; ++i) {
      const batchId = batchIds[i];
      const feature = features[batchId];

      feature.show = true;
      feature.color = Color.WHITE;
    }
  }

  const scratchColor$f = new Color();

  const DEFAULT_COLOR_VALUE = Color.WHITE;
  const DEFAULT_SHOW_VALUE = true;

  /**
   * Apply a style to the content.
   *
   * @param {Cesium3DTileStyle} style The style.
   * @param {Cesium3DTileFeature[]} features The dictionary of features.
   */
  Vector3DTileClampedPolylines.prototype.applyStyle = function (style, features) {
    if (!defined(style)) {
      clearStyle(this, features);
      return;
    }

    const batchIds = this._batchIds;
    const length = batchIds.length;
    for (let i = 0; i < length; ++i) {
      const batchId = batchIds[i];
      const feature = features[batchId];

      feature.color = defined(style.color)
        ? style.color.evaluateColor(feature, scratchColor$f)
        : DEFAULT_COLOR_VALUE;
      feature.show = defined(style.show)
        ? style.show.evaluate(feature)
        : DEFAULT_SHOW_VALUE;
    }
  };

  function initialize$a(polylines) {
    return ApproximateTerrainHeights.initialize().then(function () {
      updateMinimumMaximumHeights(
        polylines,
        polylines._rectangle,
        polylines._ellipsoid
      );

      return new Promise(function (resolve, reject) {
        polylines._update = function (polylines, frameState) {
          const context = frameState.context;
          const promise = createVertexArray$1(polylines);
          createUniformMap$2(polylines, context);
          createShaders(polylines, context);
          createRenderStates$1(polylines);

          if (polylines._ready) {
            const passes = frameState.passes;
            if (passes.render || passes.pick) {
              queueCommands(polylines, frameState);
            }
          }

          if (!defined(promise)) {
            return;
          }

          promise
            .then(function () {
              finishVertexArray(polylines, context);
              resolve(polylines);
            })
            .catch(function (e) {
              reject(e);
            });
        };
      });
    });
  }

  /**
   * Updates the batches and queues the commands for rendering.
   *
   * @param {FrameState} frameState The current frame state.
   */
  Vector3DTileClampedPolylines.prototype.update = function (frameState) {
    this._update(this, frameState);
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <p>
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   * </p>
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   */
  Vector3DTileClampedPolylines.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <p>
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   * </p>
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   */
  Vector3DTileClampedPolylines.prototype.destroy = function () {
    this._va = this._va && this._va.destroy();
    this._sp = this._sp && this._sp.destroy();
    return destroyObject(this);
  };

  /**
   * Represents the contents of a
   * {@link https://github.com/CesiumGS/3d-tiles/tree/vctr/TileFormats/VectorData|Vector}
   * tile in a {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification|3D Tiles} tileset.
   * <p>
   * Implements the {@link Cesium3DTileContent} interface.
   * </p>
   *
   * @alias Vector3DTileContent
   * @constructor
   *
   * @private
   */
  function Vector3DTileContent(tileset, tile, resource, arrayBuffer, byteOffset) {
    this._tileset = tileset;
    this._tile = tile;
    this._resource = resource;

    this._polygons = undefined;
    this._polylines = undefined;
    this._points = undefined;

    this._metadata = undefined;

    this._batchTable = undefined;
    this._features = undefined;

    /**
     * Part of the {@link Cesium3DTileContent} interface.
     */
    this.featurePropertiesDirty = false;
    this._group = undefined;

    initialize$9(this, arrayBuffer, byteOffset);
  }

  Object.defineProperties(Vector3DTileContent.prototype, {
    featuresLength: {
      get: function () {
        return defined(this._batchTable) ? this._batchTable.featuresLength : 0;
      },
    },

    pointsLength: {
      get: function () {
        if (defined(this._points)) {
          return this._points.pointsLength;
        }
        return 0;
      },
    },

    trianglesLength: {
      get: function () {
        let trianglesLength = 0;
        if (defined(this._polygons)) {
          trianglesLength += this._polygons.trianglesLength;
        }
        if (defined(this._polylines)) {
          trianglesLength += this._polylines.trianglesLength;
        }
        return trianglesLength;
      },
    },

    geometryByteLength: {
      get: function () {
        let geometryByteLength = 0;
        if (defined(this._polygons)) {
          geometryByteLength += this._polygons.geometryByteLength;
        }
        if (defined(this._polylines)) {
          geometryByteLength += this._polylines.geometryByteLength;
        }
        return geometryByteLength;
      },
    },

    texturesByteLength: {
      get: function () {
        if (defined(this._points)) {
          return this._points.texturesByteLength;
        }
        return 0;
      },
    },

    batchTableByteLength: {
      get: function () {
        return defined(this._batchTable)
          ? this._batchTable.batchTableByteLength
          : 0;
      },
    },

    innerContents: {
      get: function () {
        return undefined;
      },
    },

    readyPromise: {
      get: function () {
        const pointsPromise = defined(this._points)
          ? this._points.readyPromise
          : undefined;
        const polygonPromise = defined(this._polygons)
          ? this._polygons.readyPromise
          : undefined;
        const polylinePromise = defined(this._polylines)
          ? this._polylines.readyPromise
          : undefined;

        const that = this;
        return Promise.all([pointsPromise, polygonPromise, polylinePromise]).then(
          function () {
            return that;
          }
        );
      },
    },

    tileset: {
      get: function () {
        return this._tileset;
      },
    },

    tile: {
      get: function () {
        return this._tile;
      },
    },

    url: {
      get: function () {
        return this._resource.getUrlComponent(true);
      },
    },

    metadata: {
      get: function () {
        return this._metadata;
      },
      set: function (value) {
        this._metadata = value;
      },
    },

    batchTable: {
      get: function () {
        return this._batchTable;
      },
    },

    group: {
      get: function () {
        return this._group;
      },
      set: function (value) {
        this._group = value;
      },
    },
  });

  function createColorChangedCallback(content) {
    return function (batchId, color) {
      if (defined(content._polygons)) {
        content._polygons.updateCommands(batchId, color);
      }
    };
  }

  function getBatchIds(featureTableJson, featureTableBinary) {
    let polygonBatchIds;
    let polylineBatchIds;
    let pointBatchIds;
    let i;

    const numberOfPolygons = defaultValue(featureTableJson.POLYGONS_LENGTH, 0);
    const numberOfPolylines = defaultValue(featureTableJson.POLYLINES_LENGTH, 0);
    const numberOfPoints = defaultValue(featureTableJson.POINTS_LENGTH, 0);

    if (numberOfPolygons > 0 && defined(featureTableJson.POLYGON_BATCH_IDS)) {
      const polygonBatchIdsByteOffset =
        featureTableBinary.byteOffset +
        featureTableJson.POLYGON_BATCH_IDS.byteOffset;
      polygonBatchIds = new Uint16Array(
        featureTableBinary.buffer,
        polygonBatchIdsByteOffset,
        numberOfPolygons
      );
    }

    if (numberOfPolylines > 0 && defined(featureTableJson.POLYLINE_BATCH_IDS)) {
      const polylineBatchIdsByteOffset =
        featureTableBinary.byteOffset +
        featureTableJson.POLYLINE_BATCH_IDS.byteOffset;
      polylineBatchIds = new Uint16Array(
        featureTableBinary.buffer,
        polylineBatchIdsByteOffset,
        numberOfPolylines
      );
    }

    if (numberOfPoints > 0 && defined(featureTableJson.POINT_BATCH_IDS)) {
      const pointBatchIdsByteOffset =
        featureTableBinary.byteOffset +
        featureTableJson.POINT_BATCH_IDS.byteOffset;
      pointBatchIds = new Uint16Array(
        featureTableBinary.buffer,
        pointBatchIdsByteOffset,
        numberOfPoints
      );
    }

    const atLeastOneDefined =
      defined(polygonBatchIds) ||
      defined(polylineBatchIds) ||
      defined(pointBatchIds);
    const atLeastOneUndefined =
      (numberOfPolygons > 0 && !defined(polygonBatchIds)) ||
      (numberOfPolylines > 0 && !defined(polylineBatchIds)) ||
      (numberOfPoints > 0 && !defined(pointBatchIds));

    if (atLeastOneDefined && atLeastOneUndefined) {
      throw new RuntimeError(
        "If one group of batch ids is defined, then all batch ids must be defined."
      );
    }

    const allUndefinedBatchIds =
      !defined(polygonBatchIds) &&
      !defined(polylineBatchIds) &&
      !defined(pointBatchIds);
    if (allUndefinedBatchIds) {
      let id = 0;
      if (!defined(polygonBatchIds) && numberOfPolygons > 0) {
        polygonBatchIds = new Uint16Array(numberOfPolygons);
        for (i = 0; i < numberOfPolygons; ++i) {
          polygonBatchIds[i] = id++;
        }
      }
      if (!defined(polylineBatchIds) && numberOfPolylines > 0) {
        polylineBatchIds = new Uint16Array(numberOfPolylines);
        for (i = 0; i < numberOfPolylines; ++i) {
          polylineBatchIds[i] = id++;
        }
      }
      if (!defined(pointBatchIds) && numberOfPoints > 0) {
        pointBatchIds = new Uint16Array(numberOfPoints);
        for (i = 0; i < numberOfPoints; ++i) {
          pointBatchIds[i] = id++;
        }
      }
    }

    return {
      polygons: polygonBatchIds,
      polylines: polylineBatchIds,
      points: pointBatchIds,
    };
  }

  const sizeOfUint32 = Uint32Array.BYTES_PER_ELEMENT;

  function createFloatingPolylines(options) {
    return new Vector3DTilePolylines(options);
  }

  function createClampedPolylines(options) {
    return new Vector3DTileClampedPolylines(options);
  }

  function initialize$9(content, arrayBuffer, byteOffset) {
    byteOffset = defaultValue(byteOffset, 0);

    const uint8Array = new Uint8Array(arrayBuffer);
    const view = new DataView(arrayBuffer);
    byteOffset += sizeOfUint32; // Skip magic number

    const version = view.getUint32(byteOffset, true);
    if (version !== 1) {
      throw new RuntimeError(
        `Only Vector tile version 1 is supported.  Version ${version} is not.`
      );
    }
    byteOffset += sizeOfUint32;

    const byteLength = view.getUint32(byteOffset, true);
    byteOffset += sizeOfUint32;

    if (byteLength === 0) {
      return Promise.resolve(content);
    }

    const featureTableJSONByteLength = view.getUint32(byteOffset, true);
    byteOffset += sizeOfUint32;

    if (featureTableJSONByteLength === 0) {
      throw new RuntimeError(
        "Feature table must have a byte length greater than zero"
      );
    }

    const featureTableBinaryByteLength = view.getUint32(byteOffset, true);
    byteOffset += sizeOfUint32;
    const batchTableJSONByteLength = view.getUint32(byteOffset, true);
    byteOffset += sizeOfUint32;
    const batchTableBinaryByteLength = view.getUint32(byteOffset, true);
    byteOffset += sizeOfUint32;
    const indicesByteLength = view.getUint32(byteOffset, true);
    byteOffset += sizeOfUint32;
    const positionByteLength = view.getUint32(byteOffset, true);
    byteOffset += sizeOfUint32;
    const polylinePositionByteLength = view.getUint32(byteOffset, true);
    byteOffset += sizeOfUint32;
    const pointsPositionByteLength = view.getUint32(byteOffset, true);
    byteOffset += sizeOfUint32;

    const featureTableJson = getJsonFromTypedArray(
      uint8Array,
      byteOffset,
      featureTableJSONByteLength
    );
    byteOffset += featureTableJSONByteLength;

    const featureTableBinary = new Uint8Array(
      arrayBuffer,
      byteOffset,
      featureTableBinaryByteLength
    );
    byteOffset += featureTableBinaryByteLength;

    let batchTableJson;
    let batchTableBinary;
    if (batchTableJSONByteLength > 0) {
      // PERFORMANCE_IDEA: is it possible to allocate this on-demand?  Perhaps keep the
      // arraybuffer/string compressed in memory and then decompress it when it is first accessed.
      //
      // We could also make another request for it, but that would make the property set/get
      // API async, and would double the number of numbers in some cases.
      batchTableJson = getJsonFromTypedArray(
        uint8Array,
        byteOffset,
        batchTableJSONByteLength
      );
      byteOffset += batchTableJSONByteLength;

      if (batchTableBinaryByteLength > 0) {
        // Has a batch table binary
        batchTableBinary = new Uint8Array(
          arrayBuffer,
          byteOffset,
          batchTableBinaryByteLength
        );
        // Copy the batchTableBinary section and let the underlying ArrayBuffer be freed
        batchTableBinary = new Uint8Array(batchTableBinary);
        byteOffset += batchTableBinaryByteLength;
      }
    }

    const numberOfPolygons = defaultValue(featureTableJson.POLYGONS_LENGTH, 0);
    const numberOfPolylines = defaultValue(featureTableJson.POLYLINES_LENGTH, 0);
    const numberOfPoints = defaultValue(featureTableJson.POINTS_LENGTH, 0);
    const totalPrimitives = numberOfPolygons + numberOfPolylines + numberOfPoints;

    const batchTable = new Cesium3DTileBatchTable(
      content,
      totalPrimitives,
      batchTableJson,
      batchTableBinary,
      createColorChangedCallback(content)
    );
    content._batchTable = batchTable;

    if (totalPrimitives === 0) {
      return;
    }

    const featureTable = new Cesium3DTileFeatureTable(
      featureTableJson,
      featureTableBinary
    );
    const region = featureTable.getGlobalProperty("REGION");
    if (!defined(region)) {
      throw new RuntimeError(
        "Feature table global property: REGION must be defined"
      );
    }
    const rectangle = Rectangle.unpack(region);
    const minHeight = region[4];
    const maxHeight = region[5];

    const modelMatrix = content._tile.computedTransform;

    let center = featureTable.getGlobalProperty(
      "RTC_CENTER",
      ComponentDatatype$1.FLOAT,
      3
    );
    if (defined(center)) {
      center = Cartesian3.unpack(center);
      Matrix4.multiplyByPoint(modelMatrix, center, center);
    } else {
      center = Rectangle.center(rectangle);
      center.height = CesiumMath.lerp(minHeight, maxHeight, 0.5);
      center = Ellipsoid.WGS84.cartographicToCartesian(center);
    }

    const batchIds = getBatchIds(featureTableJson, featureTableBinary);
    byteOffset += (4 - (byteOffset % 4)) % 4;

    if (numberOfPolygons > 0) {
      featureTable.featuresLength = numberOfPolygons;

      const polygonCounts = defaultValue(
        featureTable.getPropertyArray(
          "POLYGON_COUNTS",
          ComponentDatatype$1.UNSIGNED_INT,
          1
        ),
        featureTable.getPropertyArray(
          "POLYGON_COUNT",
          ComponentDatatype$1.UNSIGNED_INT,
          1
        ) // Workaround for old vector tilesets using the non-plural name
      );

      if (!defined(polygonCounts)) {
        throw new RuntimeError(
          "Feature table property: POLYGON_COUNTS must be defined when POLYGONS_LENGTH is greater than 0"
        );
      }

      const polygonIndexCounts = defaultValue(
        featureTable.getPropertyArray(
          "POLYGON_INDEX_COUNTS",
          ComponentDatatype$1.UNSIGNED_INT,
          1
        ),
        featureTable.getPropertyArray(
          "POLYGON_INDEX_COUNT",
          ComponentDatatype$1.UNSIGNED_INT,
          1
        ) // Workaround for old vector tilesets using the non-plural name
      );

      if (!defined(polygonIndexCounts)) {
        throw new RuntimeError(
          "Feature table property: POLYGON_INDEX_COUNTS must be defined when POLYGONS_LENGTH is greater than 0"
        );
      }

      // Use the counts array to determine how many position values we want. If we used the byte length then
      // zero padding values would be included and cause the delta zig-zag decoding to fail
      const numPolygonPositions = polygonCounts.reduce(function (total, count) {
        return total + count * 2;
      }, 0);

      const numPolygonIndices = polygonIndexCounts.reduce(function (
        total,
        count
      ) {
        return total + count;
      },
      0);

      const indices = new Uint32Array(arrayBuffer, byteOffset, numPolygonIndices);
      byteOffset += indicesByteLength;

      const polygonPositions = new Uint16Array(
        arrayBuffer,
        byteOffset,
        numPolygonPositions
      );
      byteOffset += positionByteLength;

      let polygonMinimumHeights;
      let polygonMaximumHeights;
      if (
        defined(featureTableJson.POLYGON_MINIMUM_HEIGHTS) &&
        defined(featureTableJson.POLYGON_MAXIMUM_HEIGHTS)
      ) {
        polygonMinimumHeights = featureTable.getPropertyArray(
          "POLYGON_MINIMUM_HEIGHTS",
          ComponentDatatype$1.FLOAT,
          1
        );
        polygonMaximumHeights = featureTable.getPropertyArray(
          "POLYGON_MAXIMUM_HEIGHTS",
          ComponentDatatype$1.FLOAT,
          1
        );
      }

      content._polygons = new Vector3DTilePolygons({
        positions: polygonPositions,
        counts: polygonCounts,
        indexCounts: polygonIndexCounts,
        indices: indices,
        minimumHeight: minHeight,
        maximumHeight: maxHeight,
        polygonMinimumHeights: polygonMinimumHeights,
        polygonMaximumHeights: polygonMaximumHeights,
        center: center,
        rectangle: rectangle,
        boundingVolume: content.tile.boundingVolume.boundingVolume,
        batchTable: batchTable,
        batchIds: batchIds.polygons,
        modelMatrix: modelMatrix,
      });
    }

    if (numberOfPolylines > 0) {
      featureTable.featuresLength = numberOfPolylines;

      const polylineCounts = defaultValue(
        featureTable.getPropertyArray(
          "POLYLINE_COUNTS",
          ComponentDatatype$1.UNSIGNED_INT,
          1
        ),
        featureTable.getPropertyArray(
          "POLYLINE_COUNT",
          ComponentDatatype$1.UNSIGNED_INT,
          1
        ) // Workaround for old vector tilesets using the non-plural name
      );

      if (!defined(polylineCounts)) {
        throw new RuntimeError(
          "Feature table property: POLYLINE_COUNTS must be defined when POLYLINES_LENGTH is greater than 0"
        );
      }

      let widths = featureTable.getPropertyArray(
        "POLYLINE_WIDTHS",
        ComponentDatatype$1.UNSIGNED_SHORT,
        1
      );
      if (!defined(widths)) {
        widths = new Uint16Array(numberOfPolylines);
        for (let i = 0; i < numberOfPolylines; ++i) {
          widths[i] = 2.0;
        }
      }

      // Use the counts array to determine how many position values we want. If we used the byte length then
      // zero padding values would be included and cause the delta zig-zag decoding to fail
      const numPolylinePositions = polylineCounts.reduce(function (total, count) {
        return total + count * 3;
      }, 0);
      const polylinePositions = new Uint16Array(
        arrayBuffer,
        byteOffset,
        numPolylinePositions
      );
      byteOffset += polylinePositionByteLength;

      const tileset = content._tileset;
      const examineVectorLinesFunction = tileset.examineVectorLinesFunction;
      if (defined(examineVectorLinesFunction)) {
        const decodedPositions = decodeVectorPolylinePositions(
          new Uint16Array(polylinePositions),
          rectangle,
          minHeight,
          maxHeight,
          Ellipsoid.WGS84
        );
        examineVectorLines(
          decodedPositions,
          polylineCounts,
          batchIds.polylines,
          batchTable,
          content.url,
          examineVectorLinesFunction
        );
      }

      let createPolylines = createFloatingPolylines;
      if (defined(tileset.classificationType)) {
        createPolylines = createClampedPolylines;
      }

      content._polylines = createPolylines({
        positions: polylinePositions,
        widths: widths,
        counts: polylineCounts,
        batchIds: batchIds.polylines,
        minimumHeight: minHeight,
        maximumHeight: maxHeight,
        center: center,
        rectangle: rectangle,
        boundingVolume: content.tile.boundingVolume.boundingVolume,
        batchTable: batchTable,
        classificationType: tileset.classificationType,
        keepDecodedPositions: tileset.vectorKeepDecodedPositions,
      });
    }

    if (numberOfPoints > 0) {
      const pointPositions = new Uint16Array(
        arrayBuffer,
        byteOffset,
        numberOfPoints * 3
      );
      byteOffset += pointsPositionByteLength;
      content._points = new Vector3DTilePoints({
        positions: pointPositions,
        batchIds: batchIds.points,
        minimumHeight: minHeight,
        maximumHeight: maxHeight,
        rectangle: rectangle,
        batchTable: batchTable,
      });
    }

    return Promise.resolve(content);
  }

  function createFeatures(content) {
    const featuresLength = content.featuresLength;
    if (!defined(content._features) && featuresLength > 0) {
      const features = new Array(featuresLength);

      if (defined(content._polygons)) {
        content._polygons.createFeatures(content, features);
      }
      if (defined(content._polylines)) {
        content._polylines.createFeatures(content, features);
      }
      if (defined(content._points)) {
        content._points.createFeatures(content, features);
      }
      content._features = features;
    }
  }

  Vector3DTileContent.prototype.hasProperty = function (batchId, name) {
    return this._batchTable.hasProperty(batchId, name);
  };

  Vector3DTileContent.prototype.getFeature = function (batchId) {
    //>>includeStart('debug', pragmas.debug);
    const featuresLength = this.featuresLength;
    if (!defined(batchId) || batchId < 0 || batchId >= featuresLength) {
      throw new DeveloperError(
        `batchId is required and between zero and featuresLength - 1 (${
        featuresLength - 1
      }).`
      );
    }
    //>>includeEnd('debug');

    createFeatures(this);
    return this._features[batchId];
  };

  Vector3DTileContent.prototype.applyDebugSettings = function (enabled, color) {
    if (defined(this._polygons)) {
      this._polygons.applyDebugSettings(enabled, color);
    }
    if (defined(this._polylines)) {
      this._polylines.applyDebugSettings(enabled, color);
    }
    if (defined(this._points)) {
      this._points.applyDebugSettings(enabled, color);
    }
  };

  Vector3DTileContent.prototype.applyStyle = function (style) {
    createFeatures(this);
    if (defined(this._polygons)) {
      this._polygons.applyStyle(style, this._features);
    }
    if (defined(this._polylines)) {
      this._polylines.applyStyle(style, this._features);
    }
    if (defined(this._points)) {
      this._points.applyStyle(style, this._features);
    }
  };

  Vector3DTileContent.prototype.update = function (tileset, frameState) {
    let ready = true;
    if (defined(this._polygons)) {
      this._polygons.classificationType = this._tileset.classificationType;
      this._polygons.debugWireframe = this._tileset.debugWireframe;
      this._polygons.update(frameState);
      ready = ready && this._polygons._ready;
    }
    if (defined(this._polylines)) {
      this._polylines.update(frameState);
      ready = ready && this._polylines._ready;
    }
    if (defined(this._points)) {
      this._points.update(frameState);
      ready = ready && this._points._ready;
    }
    if (defined(this._batchTable) && ready) {
      this._batchTable.update(tileset, frameState);
    }
  };

  Vector3DTileContent.prototype.getPolylinePositions = function (batchId) {
    const polylines = this._polylines;
    if (!defined(polylines)) {
      return undefined;
    }

    return polylines.getPositions(batchId);
  };

  Vector3DTileContent.prototype.isDestroyed = function () {
    return false;
  };

  Vector3DTileContent.prototype.destroy = function () {
    this._polygons = this._polygons && this._polygons.destroy();
    this._polylines = this._polylines && this._polylines.destroy();
    this._points = this._points && this._points.destroy();
    this._batchTable = this._batchTable && this._batchTable.destroy();
    return destroyObject(this);
  };

  function examineVectorLines(
    positions,
    counts,
    batchIds,
    batchTable,
    url,
    callback
  ) {
    const countsLength = counts.length;
    let polylineStart = 0;
    for (let i = 0; i < countsLength; i++) {
      const count = counts[i] * 3;
      const linePositions = positions.slice(polylineStart, polylineStart + count);
      polylineStart += count;

      callback(linePositions, batchIds[i], url, batchTable);
    }
  }

  /**
   * A property table for use with the <code>EXT_structural_metadata</code> extension or
   * legacy <code>EXT_feature_metadata</code> glTF extension. It also includes some
   * options to be compatible with the 3D Tiles 1.0 batch table.
   * <p>
   * For batch tables, properties are resolved in the following order:
   * </p>
   * <ol>
   *   <li>binary properties from options.metadataTable</li>
   *   <li>JSON properties from options.jsonMetadataTable</li>
   *   <li>batch table hierarchy properties from options.batchTableHierarchy</li>
   * </ol>
   * <p>
   * See the {@link https://github.com/CesiumGS/glTF/tree/3d-tiles-next/extensions/2.0/Vendor/EXT_structural_metadata|EXT_structural_metadata Extension} as well as the
   * previous {@link https://github.com/CesiumGS/glTF/tree/3d-tiles-next/extensions/2.0/Vendor/EXT_feature_metadata|EXT_feature_metadata Extension} for glTF.
   * </p>
   *
   * @param {Object} options Object with the following properties:
   * @param {String} [options.name] Human-readable name to describe the table
   * @param {String|Number} [options.id] A unique id to identify the property table, useful for debugging. For <code>EXT_structural_metadata</code>, this is the array index in the property tables array, for <code>EXT_feature_metadata</code> this is the dictionary key in the property tables dictionary.
   * @param {Number} options.count The number of features in the table.
   * @param {MetadataTable} [options.metadataTable] A table of binary properties.
   * @param {JsonMetadataTable} [options.jsonMetadataTable] For compatibility with the old batch table, free-form JSON properties can be passed in.
   * @param {BatchTableHierarchy} [options.batchTableHierarchy] For compatibility with the <code>3DTILES_batch_table_hierarchy</code> extension, a hierarchy can be provided.
   * @param {Object} [options.extras] Extra user-defined properties
   * @param {Object} [options.extensions] An object containing extensions
   *
   * @alias PropertyTable
   * @constructor
   *
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function PropertyTable(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("options.count", options.count);
    //>>includeEnd('debug');

    this._name = options.name;
    this._id = options.id;
    this._count = options.count;
    this._extras = options.extras;
    this._extensions = options.extensions;
    this._metadataTable = options.metadataTable;
    this._jsonMetadataTable = options.jsonMetadataTable;
    this._batchTableHierarchy = options.batchTableHierarchy;
  }

  Object.defineProperties(PropertyTable.prototype, {
    /**
     * A human-readable name for this table
     *
     * @memberof PropertyTable.prototype
     * @type {String}
     * @readonly
     * @private
     */
    name: {
      get: function () {
        return this._name;
      },
    },
    /**
     * An identifier for this table. Useful for debugging.
     *
     * @memberof PropertyTable.prototype
     * @type {String|Number}
     * @readonly
     * @private
     */
    id: {
      get: function () {
        return this._id;
      },
    },
    /**
     * The number of features in the table.
     *
     * @memberof PropertyTable.prototype
     * @type {Number}
     * @readonly
     * @private
     */
    count: {
      get: function () {
        return this._count;
      },
    },

    /**
     * The class that properties conform to.
     *
     * @memberof PropertyTable.prototype
     * @type {MetadataClass}
     * @readonly
     */
    class: {
      get: function () {
        if (defined(this._metadataTable)) {
          return this._metadataTable.class;
        }

        return undefined;
      },
    },

    /**
     * Extras in the JSON object.
     *
     * @memberof PropertyTable.prototype
     * @type {*}
     * @readonly
     * @private
     */
    extras: {
      get: function () {
        return this._extras;
      },
    },

    /**
     * Extensions in the JSON object.
     *
     * @memberof PropertyTable.prototype
     * @type {Object}
     * @readonly
     * @private
     */
    extensions: {
      get: function () {
        return this._extensions;
      },
    },

    /**
     * Get the total amount of binary metadata stored in memory. This does
     * not include JSON metadata
     *
     * @memberof PropertyTable.prototype
     * @type {Number}
     * @readonly
     * @private
     */
    byteLength: {
      get: function () {
        let totalByteLength = 0;
        if (defined(this._metadataTable)) {
          totalByteLength += this._metadataTable.byteLength;
        }

        if (defined(this._batchTableHierarchy)) {
          totalByteLength += this._batchTableHierarchy.byteLength;
        }

        return totalByteLength;
      },
    },
  });

  /**
   * Returns whether the feature has this property. For compatibility with the <code>3DTILES_batch_table_hierarchy</code> extension, this is computed for a specific feature.
   *
   * @param {Number} index The index of the feature.
   * @param {String} propertyId The case-sensitive ID of the property.
   * @returns {Boolean} Whether the feature has this property.
   * @private
   */
  PropertyTable.prototype.hasProperty = function (index, propertyId) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("index", index);
    Check.typeOf.string("propertyId", propertyId);
    //>>includeEnd('debug');

    if (
      defined(this._metadataTable) &&
      this._metadataTable.hasProperty(propertyId)
    ) {
      return true;
    }

    if (
      defined(this._jsonMetadataTable) &&
      this._jsonMetadataTable.hasProperty(propertyId)
    ) {
      return true;
    }

    if (
      defined(this._batchTableHierarchy) &&
      this._batchTableHierarchy.hasProperty(index, propertyId)
    ) {
      return true;
    }

    return false;
  };

  /**
   * Returns whether the feature has a property with the given semantic.
   *
   * @param {String} semantic The case-sensitive semantic of the property.
   * @returns {Boolean} Whether the feature has a property with the given semantic.
   * @private
   */
  PropertyTable.prototype.hasPropertyBySemantic = function (index, semantic) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("index", index);
    Check.typeOf.string("semantic", semantic);
    //>>includeEnd('debug');

    if (defined(this._metadataTable)) {
      return this._metadataTable.hasPropertyBySemantic(semantic);
    }

    return false;
  };

  /**
   * Returns whether any feature has this property.
   * This is mainly useful for checking whether a property exists in the class
   * hierarchy when using the <code>3DTILES_batch_table_hierarchy</code> extension.
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @returns {Boolean} Whether any feature has this property.
   * @private
   */
  PropertyTable.prototype.propertyExists = function (propertyId) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("propertyId", propertyId);
    //>>includeEnd('debug');

    if (
      defined(this._metadataTable) &&
      this._metadataTable.hasProperty(propertyId)
    ) {
      return true;
    }

    if (
      defined(this._jsonMetadataTable) &&
      this._jsonMetadataTable.hasProperty(propertyId)
    ) {
      return true;
    }

    if (
      defined(this._batchTableHierarchy) &&
      this._batchTableHierarchy.propertyExists(propertyId)
    ) {
      return true;
    }

    return false;
  };

  /**
   * Returns whether any feature has a property with the given semantic.
   *
   * @param {String} semantic The case-sensitive semantic of the property.
   * @returns {Boolean} Whether any feature has a property with the given semantic.
   * @private
   */
  PropertyTable.prototype.propertyExistsBySemantic = function (semantic) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("semantic", semantic);
    //>>includeEnd('debug');

    if (defined(this._metadataTable)) {
      return this._metadataTable.hasPropertyBySemantic(semantic);
    }

    return false;
  };

  const scratchResults = [];

  /**
   * Returns an array of property IDs. For compatibility with the <code>3DTILES_batch_table_hierarchy</code> extension, this is computed for a specific feature.
   *
   * @param {Number} index The index of the feature.
   * @param {String[]} [results] An array into which to store the results.
   * @returns {String[]} The property IDs.
   * @private
   */
  PropertyTable.prototype.getPropertyIds = function (index, results) {
    results = defined(results) ? results : [];
    results.length = 0;

    if (defined(this._metadataTable)) {
      // concat in place to avoid unnecessary array allocation
      results.push.apply(
        results,
        this._metadataTable.getPropertyIds(scratchResults)
      );
    }

    if (defined(this._jsonMetadataTable)) {
      results.push.apply(
        results,
        this._jsonMetadataTable.getPropertyIds(scratchResults)
      );
    }

    if (defined(this._batchTableHierarchy)) {
      results.push.apply(
        results,
        this._batchTableHierarchy.getPropertyIds(index, scratchResults)
      );
    }

    return results;
  };

  /**
   * Returns a copy of the value of the property with the given ID.
   * <p>
   * If the property is normalized the normalized value is returned.
   * </p>
   *
   * @param {Number} index The index of the feature.
   * @param {String} propertyId The case-sensitive ID of the property.
   * @returns {*} The value of the property or <code>undefined</code> if the feature does not have this property.
   * @private
   */
  PropertyTable.prototype.getProperty = function (index, propertyId) {
    let result;
    if (defined(this._metadataTable)) {
      result = this._metadataTable.getProperty(index, propertyId);
      if (defined(result)) {
        return result;
      }
    }

    if (defined(this._jsonMetadataTable)) {
      result = this._jsonMetadataTable.getProperty(index, propertyId);
      if (defined(result)) {
        return result;
      }
    }

    if (defined(this._batchTableHierarchy)) {
      result = this._batchTableHierarchy.getProperty(index, propertyId);
      if (defined(result)) {
        return result;
      }
    }

    return undefined;
  };

  /**
   * Sets the value of the property with the given ID.
   * <p>
   * If the property is normalized a normalized value must be provided to this function.
   * </p>
   *
   * @param {Number} index The index of the feature.
   * @param {String} propertyId The case-sensitive ID of the property.
   * @param {*} value The value of the property that will be copied.
   * @returns {Boolean} <code>true</code> if the property was set, <code>false</code> otherwise.
   * @private
   */
  PropertyTable.prototype.setProperty = function (index, propertyId, value) {
    if (
      defined(this._metadataTable) &&
      this._metadataTable.setProperty(index, propertyId, value)
    ) {
      return true;
    }

    if (
      defined(this._jsonMetadataTable) &&
      this._jsonMetadataTable.setProperty(index, propertyId, value)
    ) {
      return true;
    }

    return (
      defined(this._batchTableHierarchy) &&
      this._batchTableHierarchy.setProperty(index, propertyId, value)
    );
  };

  /**
   * Returns a copy of the value of the property with the given semantic.
   * <p>
   * This only operates on the underlying {@link MetadataTable} (if present) as
   * {@link JsonMetadataTable} and {@link BatchTableHierarchy} do not have
   * semantics.
   * </p>
   *
   * @param {Number} index The index of the feature.
   * @param {String} semantic The case-sensitive semantic of the property.
   * @returns {*} The value of the property or <code>undefined</code> if the feature does not have this semantic.
   * @private
   */
  PropertyTable.prototype.getPropertyBySemantic = function (index, semantic) {
    if (defined(this._metadataTable)) {
      return this._metadataTable.getPropertyBySemantic(index, semantic);
    }

    return undefined;
  };

  /**
   * Sets the value of the property with the given semantic.
   * <p>
   * This only operates on the underlying {@link MetadataTable} (if present) as
   * {@link JsonMetadataTable} and {@link BatchTableHierarchy} do not have
   * semantics.
   * </p>
   *
   * @param {Number} index The index of the feature.
   * @param {String} semantic The case-sensitive semantic of the property.
   * @param {*} value The value of the property that will be copied.
   * @returns {Boolean} <code>true</code> if the property was set, <code>false</code> otherwise.
   * @private
   */
  PropertyTable.prototype.setPropertyBySemantic = function (
    index,
    semantic,
    value
  ) {
    if (defined(this._metadataTable)) {
      return this._metadataTable.setPropertyBySemantic(index, semantic, value);
    }

    return false;
  };

  /**
   * Returns a typed array containing the property values for a given propertyId.
   * <p>
   * This only operates on the underlying {@link MetadataTable} (if present) as
   * {@link JsonMetadataTable} and {@link BatchTableHierarchy} do not store
   * values in typed arrays.
   * </p>
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @returns {*} The typed array containing the property values or <code>undefined</code> if the property values are not stored in a typed array.
   *
   * @private
   */
  PropertyTable.prototype.getPropertyTypedArray = function (propertyId) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("propertyId", propertyId);
    //>>includeEnd('debug');

    if (defined(this._metadataTable)) {
      return this._metadataTable.getPropertyTypedArray(propertyId);
    }

    return undefined;
  };

  /**
   * Returns a typed array containing the property values for the property with the given semantic.
   * <p>
   * This only operates on the underlying {@link MetadataTable} (if present) as
   * {@link JsonMetadataTable} and {@link BatchTableHierarchy} do not have
   * semantics.
   * </p>
   *
   * @param {String} semantic The case-sensitive semantic of the property.
   * @returns {*} The typed array containing the property values or <code>undefined</code> if the property values are not stored in a typed array.
   *
   * @private
   */
  PropertyTable.prototype.getPropertyTypedArrayBySemantic = function (semantic) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("semantic", semantic);
    //>>includeEnd('debug');

    if (defined(this._metadataTable)) {
      return this._metadataTable.getPropertyTypedArrayBySemantic(semantic);
    }

    return undefined;
  };

  /**
   * A property in a property texture.
   *
   * <p>
   * See the {@link https://github.com/CesiumGS/glTF/tree/3d-tiles-next/extensions/2.0/Vendor/EXT_structural_metadata|EXT_structural_metadata Extension} as well as the
   * previous {@link https://github.com/CesiumGS/glTF/tree/3d-tiles-next/extensions/2.0/Vendor/EXT_feature_metadata|EXT_feature_metadata Extension} for glTF.
   * </p>
   *
   * @param {Object} options Object with the following properties:
   * @param {Object} options.property The property JSON object.
   * @param {MetadataClassProperty} options.classProperty The class property.
   * @param {Object.<Number, Texture>} options.textures An object mapping texture IDs to {@link Texture} objects.
   *
   * @alias PropertyTextureProperty
   * @constructor
   *
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function PropertyTextureProperty(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const property = options.property;
    const classProperty = options.classProperty;
    const textures = options.textures;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.property", property);
    Check.typeOf.object("options.classProperty", classProperty);
    Check.typeOf.object("options.textures", textures);
    //>>includeEnd('debug');

    // in EXT_structural_metadata, the property is a valid glTF textureInfo
    const textureInfo = property;
    const textureReader = GltfLoaderUtil.createModelTextureReader({
      textureInfo: textureInfo,
      channels: reformatChannels$1(property.channels),
      texture: textures[textureInfo.index],
    });

    this._min = property.min;
    this._max = property.max;

    let offset = property.offset;
    let scale = property.scale;

    // This needs to be set before handling default values
    const hasValueTransform =
      classProperty.hasValueTransform || defined(offset) || defined(scale);

    // If the property attribute does not define an offset/scale, it inherits from
    // the class property. The class property handles setting the default of
    // identity: (offset 0, scale 1) with the same scalar/vector/matrix types.
    // array types are disallowed by the spec.
    offset = defaultValue(offset, classProperty.offset);
    scale = defaultValue(scale, classProperty.scale);

    // offset and scale are applied on the GPU, so unpack the values
    // as math types we can use in uniform callbacks.
    offset = classProperty.unpackVectorAndMatrixTypes(offset);
    scale = classProperty.unpackVectorAndMatrixTypes(scale);

    this._offset = offset;
    this._scale = scale;
    this._hasValueTransform = hasValueTransform;

    this._textureReader = textureReader;
    this._classProperty = classProperty;
    this._extras = property.extras;
    this._extensions = property.extensions;
  }

  Object.defineProperties(PropertyTextureProperty.prototype, {
    /**
     * The texture reader.
     *
     * @memberof PropertyTextureProperty.prototype
     * @type {ModelComponents.TextureReader}
     * @readonly
     * @private
     */
    textureReader: {
      get: function () {
        return this._textureReader;
      },
    },

    /**
     * True if offset/scale should be applied. If both offset/scale were
     * undefined, they default to identity so this property is set false
     *
     * @memberof PropertyTextureProperty.prototype
     * @type {Boolean}
     * @readonly
     * @private
     */
    hasValueTransform: {
      get: function () {
        return this._hasValueTransform;
      },
    },

    /**
     * The offset to be added to property values as part of the value transform.
     *
     * @memberof PropertyTextureProperty.prototype
     * @type {Number|Cartesian2|Cartesian3|Cartesian4|Matrix2|Matrix3|Matrix4}
     * @readonly
     * @private
     */
    offset: {
      get: function () {
        return this._offset;
      },
    },

    /**
     * The scale to be multiplied to property values as part of the value transform.
     *
     * @memberof PropertyTextureProperty.prototype
     * @type {Number|Cartesian2|Cartesian3|Cartesian4|Matrix2|Matrix3|Matrix4}
     * @readonly
     * @private
     */
    scale: {
      get: function () {
        return this._scale;
      },
    },

    /**
     * Extras in the JSON object.
     *
     * @memberof PropertyTextureProperty.prototype
     * @type {*}
     * @readonly
     * @private
     */
    extras: {
      get: function () {
        return this._extras;
      },
    },

    /**
     * Extensions in the JSON object.
     *
     * @memberof PropertyTextureProperty.prototype
     * @type {*}
     * @readonly
     * @private
     */
    extensions: {
      get: function () {
        return this._extensions;
      },
    },
  });

  PropertyTextureProperty.prototype.isGpuCompatible = function () {
    const classProperty = this._classProperty;
    const type = classProperty.type;
    const componentType = classProperty.componentType;

    if (classProperty.isArray) {
      // only support arrays of 1-4 UINT8 scalars (normalized or unnormalized)
      return (
        !classProperty.isVariableLengthArray &&
        classProperty.arrayLength <= 4 &&
        type === MetadataType$1.SCALAR &&
        componentType === MetadataComponentType$1.UINT8
      );
    }

    if (MetadataType$1.isVectorType(type) || type === MetadataType$1.SCALAR) {
      return componentType === MetadataComponentType$1.UINT8;
    }

    // For this initial implementation, only UINT8-based properties
    // are supported.
    return false;
  };

  const floatTypesByComponentCount = [undefined, "float", "vec2", "vec3", "vec4"];
  const integerTypesByComponentCount = [
    undefined,
    "int",
    "ivec2",
    "ivec3",
    "ivec4",
  ];
  PropertyTextureProperty.prototype.getGlslType = function () {
    const classProperty = this._classProperty;

    let componentCount = MetadataType$1.getComponentCount(classProperty.type);
    if (classProperty.isArray) {
      // fixed-sized arrays of length 2-4 UINT8s are represented as vectors as the
      // shader since those are more useful in GLSL.
      componentCount = classProperty.arrayLength;
    }

    // Normalized UINT8 properties are float types in the shader
    if (classProperty.normalized) {
      return floatTypesByComponentCount[componentCount];
    }

    // other UINT8-based properties are represented as integer types.
    return integerTypesByComponentCount[componentCount];
  };

  PropertyTextureProperty.prototype.unpackInShader = function (packedValueGlsl) {
    const classProperty = this._classProperty;

    // no unpacking needed if for normalized types
    if (classProperty.normalized) {
      return packedValueGlsl;
    }

    // integer types are read from the texture as normalized float values.
    // these need to be rescaled to [0, 255] and cast to the appropriate integer
    // type.
    const glslType = this.getGlslType();
    return `${glslType}(255.0 * ${packedValueGlsl})`;
  };

  /**
   * Reformat from an array of channel indices like <code>[0, 1]</code> to a
   * string of channels as would be used in GLSL swizzling (e.g. "rg")
   *
   * @param {Number[]} channels the channel indices
   * @return {String} The channels as a string of "r", "g", "b" or "a" characters.
   * @private
   */
  function reformatChannels$1(channels) {
    return channels
      .map(function (channelIndex) {
        return "rgba".charAt(channelIndex);
      })
      .join("");
  }

  /**
   * A property texture.
   * <p>
   * See the {@link https://github.com/CesiumGS/glTF/tree/3d-tiles-next/extensions/2.0/Vendor/EXT_structural_metadata|EXT_structural_metadata Extension} as well as the
   * previous {@link https://github.com/CesiumGS/glTF/tree/3d-tiles-next/extensions/2.0/Vendor/EXT_feature_metadata|EXT_feature_metadata Extension} for glTF.
   * </p>
   *
   * @param {Object} options Object with the following properties:
   * @param {String} [options.name] Optional human-readable name to describe the texture
   * @param {String|Number} [options.id] A unique id to identify the property texture, useful for debugging. For <code>EXT_structural_metadata</code>, this is the array index in the property textures array, for <code>EXT_feature_metadata</code> this is the dictionary key in the property textures dictionary.
   * @param {Object} options.propertyTexture The property texture JSON, following the EXT_structural_metadata schema.
   * @param {MetadataClass} options.class The class that properties conform to.
   * @param {Object.<String, Texture>} options.textures An object mapping texture IDs to {@link Texture} objects.
   *
   * @alias PropertyTexture
   * @constructor
   *
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function PropertyTexture(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const propertyTexture = options.propertyTexture;
    const classDefinition = options.class;
    const textures = options.textures;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.propertyTexture", propertyTexture);
    Check.typeOf.object("options.class", classDefinition);
    Check.typeOf.object("options.textures", textures);
    //>>includeEnd('debug');

    const extensions = propertyTexture.extensions;
    const extras = propertyTexture.extras;

    const properties = {};
    if (defined(propertyTexture.properties)) {
      for (const propertyId in propertyTexture.properties) {
        if (propertyTexture.properties.hasOwnProperty(propertyId)) {
          properties[propertyId] = new PropertyTextureProperty({
            property: propertyTexture.properties[propertyId],
            classProperty: classDefinition.properties[propertyId],
            textures: textures,
          });
        }
      }
    }

    this._name = options.name;
    this._id = options.id;
    this._class = classDefinition;
    this._properties = properties;
    this._extras = extras;
    this._extensions = extensions;
  }

  Object.defineProperties(PropertyTexture.prototype, {
    /**
     * A human-readable name for this texture
     *
     * @memberof PropertyTexture.prototype
     * @type {String}
     * @readonly
     * @private
     */
    name: {
      get: function () {
        return this._name;
      },
    },
    /**
     * An identifier for this texture. Useful for debugging.
     *
     * @memberof PropertyTexture.prototype
     * @type {String|Number}
     * @readonly
     * @private
     */
    id: {
      get: function () {
        return this._id;
      },
    },
    /**
     * The class that properties conform to.
     *
     * @memberof PropertyTexture.prototype
     * @type {MetadataClass}
     * @readonly
     * @private
     */
    class: {
      get: function () {
        return this._class;
      },
    },

    /**
     * The properties in this property texture.
     *
     * @memberof PropertyTexture.prototype
     *
     * @type {PropertyTextureProperty}
     * @readonly
     * @private
     */
    properties: {
      get: function () {
        return this._properties;
      },
    },

    /**
     * Extras in the JSON object.
     *
     * @memberof PropertyTexture.prototype
     * @type {*}
     * @readonly
     * @private
     */
    extras: {
      get: function () {
        return this._extras;
      },
    },

    /**
     * Extensions in the JSON object.
     *
     * @memberof PropertyTexture.prototype
     * @type {Object}
     * @readonly
     * @private
     */
    extensions: {
      get: function () {
        return this._extensions;
      },
    },
  });

  /**
   * Gets the property with the given property ID.
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @returns {PropertyTextureProperty|undefined} The property, or <code>undefined</code> if the property does not exist.
   * @private
   */
  PropertyTexture.prototype.getProperty = function (propertyId) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("propertyId", propertyId);
    //>>includeEnd('debug');

    return this._properties[propertyId];
  };

  /**
   * A property in a property attribute from EXT_structural_metadata.
   *
   * <p>
   * See the {@link https://github.com/CesiumGS/glTF/tree/3d-tiles-next/extensions/2.0/Vendor/EXT_structural_metadata|EXT_structural_metadata Extension}
   * </p>
   *
   * @param {Object} options Object with the following properties:
   * @param {Object} options.property The property JSON object.
   * @param {MetadataClassProperty} options.classProperty The class property.
   *
   * @alias PropertyAttributeProperty
   * @constructor
   *
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function PropertyAttributeProperty(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const property = options.property;
    const classProperty = options.classProperty;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.property", property);
    Check.typeOf.object("options.classProperty", classProperty);
    //>>includeEnd('debug');

    this._attribute = property.attribute;
    this._classProperty = classProperty;
    this._min = property.min;
    this._max = property.max;

    let offset = property.offset;
    let scale = property.scale;

    // This needs to be set before handling default values
    const hasValueTransform =
      classProperty.hasValueTransform || defined(offset) || defined(scale);

    // If the property attribute does not define an offset/scale, it inherits from
    // the class property. The class property handles setting the default of
    // identity: (offset 0, scale 1) with the same scalar/vector/matrix types.
    // array types are disallowed by the spec.
    offset = defaultValue(offset, classProperty.offset);
    scale = defaultValue(scale, classProperty.scale);

    // offset and scale are applied on the GPU, so unpack the values
    // as math types we can use in uniform callbacks.
    offset = classProperty.unpackVectorAndMatrixTypes(offset);
    scale = classProperty.unpackVectorAndMatrixTypes(scale);

    this._offset = offset;
    this._scale = scale;
    this._hasValueTransform = hasValueTransform;

    this._extras = property.extras;
    this._extensions = property.extensions;
  }

  Object.defineProperties(PropertyAttributeProperty.prototype, {
    /**
     * The attribute semantic
     *
     * @memberof PropertyAttributeProperty.prototype
     * @type {String}
     * @readonly
     * @private
     */
    attribute: {
      get: function () {
        return this._attribute;
      },
    },

    /**
     * True if offset/scale should be applied. If both offset/scale were
     * undefined, they default to identity so this property is set false
     *
     * @memberof MetadataClassProperty.prototype
     * @type {Boolean}
     * @readonly
     * @private
     */
    hasValueTransform: {
      get: function () {
        return this._hasValueTransform;
      },
    },

    /**
     * The offset to be added to property values as part of the value transform.
     *
     * @memberof MetadataClassProperty.prototype
     * @type {Number|Cartesian2|Cartesian3|Cartesian4|Matrix2|Matrix3|Matrix4}
     * @readonly
     * @private
     */
    offset: {
      get: function () {
        return this._offset;
      },
    },

    /**
     * The scale to be multiplied to property values as part of the value transform.
     *
     * @memberof MetadataClassProperty.prototype
     * @type {Number|Cartesian2|Cartesian3|Cartesian4|Matrix2|Matrix3|Matrix4}
     * @readonly
     * @private
     */
    scale: {
      get: function () {
        return this._scale;
      },
    },

    /**
     * Extras in the JSON object.
     *
     * @memberof PropertyAttributeProperty.prototype
     * @type {*}
     * @readonly
     * @private
     */
    extras: {
      get: function () {
        return this._extras;
      },
    },

    /**
     * Extensions in the JSON object.
     *
     * @memberof PropertyAttributeProperty.prototype
     * @type {*}
     * @readonly
     * @private
     */
    extensions: {
      get: function () {
        return this._extensions;
      },
    },
  });

  /**
   * A property attribute; a collection of per-point properties stored as custom
   * vertex attributes.
   * <p>
   * See the {@link https://github.com/CesiumGS/glTF/tree/3d-tiles-next/extensions/2.0/Vendor/EXT_structural_metadata|EXT_structural_metadata Extension}
   * </p>
   *
   * @param {Object} options Object with the following properties:
   * @param {String} [options.name] Optional human-readable name to describe the attribute
   * @param {Number} [options.id] A unique id to identify the property attribute, useful for debugging. This is the array index in the property attributes array
   * @param {Object} options.propertyAttribute The property attribute JSON, following the EXT_structural_metadata schema.
   * @param {MetadataClass} options.class The class that properties conform to.
   *
   * @alias PropertyAttribute
   * @constructor
   *
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function PropertyAttribute(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const propertyAttribute = options.propertyAttribute;
    const classDefinition = options.class;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.propertyAttribute", propertyAttribute);
    Check.typeOf.object("options.class", classDefinition);
    //>>includeEnd('debug');

    const properties = {};
    if (defined(propertyAttribute.properties)) {
      for (const propertyId in propertyAttribute.properties) {
        if (propertyAttribute.properties.hasOwnProperty(propertyId)) {
          properties[propertyId] = new PropertyAttributeProperty({
            property: propertyAttribute.properties[propertyId],
            classProperty: classDefinition.properties[propertyId],
          });
        }
      }
    }

    this._name = options.name;
    this._id = options.id;
    this._class = classDefinition;
    this._properties = properties;
    this._extras = propertyAttribute.extras;
    this._extensions = propertyAttribute.extensions;
  }

  Object.defineProperties(PropertyAttribute.prototype, {
    /**
     * A human-readable name for this attribute
     *
     * @memberof PropertyAttribute.prototype
     *
     * @type {String}
     * @readonly
     * @private
     */
    name: {
      get: function () {
        return this._name;
      },
    },
    /**
     * An identifier for this attribute. Useful for debugging.
     *
     * @memberof PropertyAttribute.prototype
     *
     * @type {String|Number}
     * @readonly
     * @private
     */
    id: {
      get: function () {
        return this._id;
      },
    },
    /**
     * The class that properties conform to.
     *
     * @memberof PropertyAttribute.prototype
     *
     * @type {MetadataClass}
     * @readonly
     * @private
     */
    class: {
      get: function () {
        return this._class;
      },
    },

    /**
     * The properties in this property attribute.
     *
     * @memberof PropertyAttribute.prototype
     *
     * @type {PropertyAttributeProperty}
     * @readonly
     * @private
     */
    properties: {
      get: function () {
        return this._properties;
      },
    },

    /**
     * Extras in the JSON object.
     *
     * @memberof PropertyAttribute.prototype
     *
     * @type {*}
     * @readonly
     * @private
     */
    extras: {
      get: function () {
        return this._extras;
      },
    },

    /**
     * Extensions in the JSON object.
     *
     * @memberof PropertyAttribute.prototype
     *
     * @type {Object}
     * @readonly
     * @private
     */
    extensions: {
      get: function () {
        return this._extensions;
      },
    },
  });

  /**
   * Gets the property with the given property ID.
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @returns {PropertyAttributeProperty|undefined} The property, or <code>undefined</code> if the property does not exist.
   * @private
   */
  PropertyAttribute.prototype.getProperty = function (propertyId) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("propertyId", propertyId);
    //>>includeEnd('debug');

    return this._properties[propertyId];
  };

  /**
   * An object containing structural metadata.
   * <p>
   * See the {@link https://github.com/CesiumGS/glTF/tree/3d-tiles-next/extensions/2.0/Vendor/EXT_structural_metadatas|EXT_structural_metadata Extension} as well as the
   * previous {@link https://github.com/CesiumGS/glTF/tree/3d-tiles-next/extensions/2.0/Vendor/EXT_feature_metadata|EXT_feature_metadata Extension} for glTF.
   * </p>
   *
   * @param {Object} options Object with the following properties:
   * @param {MetadataSchema} options.schema The parsed schema.
   * @param {PropertyTable[]} [options.propertyTables] An array of property table objects. For the legacy <code>EXT_feature_metadata</code> extension, this is sorted by the key in the propertyTables dictionary
   * @param {PropertyTexture[]} [options.propertyTextures] An array of property texture objects. For the legacy <code>EXT_feature_metadata</code> extension, this is sorted by the key in the propertyTextures dictionary
   * @param {PropertyAttribute[]} [options.propertyAttributes] An array of property attribute objects. This is new in <code>EXT_structural_metadata</code>
   * @param {Object} [options.statistics] Statistics about metadata
   * @param {Object} [options.extras] Extra user-defined properties
   * @param {Object} [options.extensions] An object containing extensions
   *
   * @alias StructuralMetadata
   * @constructor
   *
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function StructuralMetadata(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.schema", options.schema);
    //>>includeEnd('debug');

    this._schema = options.schema;
    const propertyTables = options.propertyTables;
    this._propertyTableCount = defined(propertyTables)
      ? propertyTables.length
      : 0;
    this._propertyTables = propertyTables;
    this._propertyTextures = options.propertyTextures;
    this._propertyAttributes = options.propertyAttributes;
    this._statistics = options.statistics;
    this._extras = options.extras;
    this._extensions = options.extensions;
  }

  Object.defineProperties(StructuralMetadata.prototype, {
    /**
     * Schema containing classes and enums.
     *
     * @memberof StructuralMetadata.prototype
     * @type {MetadataSchema}
     * @readonly
     * @private
     */
    schema: {
      get: function () {
        return this._schema;
      },
    },

    /**
     * Statistics about the metadata.
     * <p>
     * See the {@link https://github.com/CesiumGS/glTF/blob/3d-tiles-next/extensions/2.0/Vendor/EXT_feature_metadata/schema/statistics.schema.json|statistics schema reference} for the full set of properties.
     * </p>
     *
     * @memberof StructuralMetadata.prototype
     * @type {Object}
     * @readonly
     * @private
     */
    statistics: {
      get: function () {
        return this._statistics;
      },
    },

    /**
     * Extras in the JSON object.
     *
     * @memberof StructuralMetadata.prototype
     * @type {*}
     * @readonly
     * @private
     */
    extras: {
      get: function () {
        return this._extras;
      },
    },

    /**
     * Extensions in the JSON object.
     *
     * @memberof StructuralMetadata.prototype
     * @type {Object}
     * @readonly
     * @private
     */
    extensions: {
      get: function () {
        return this._extensions;
      },
    },

    /**
     * Number of property tables in the metadata.
     *
     * @memberof StructuralMetadata.prototype
     * @type {Number}
     * @readonly
     * @private
     */
    propertyTableCount: {
      get: function () {
        return this._propertyTableCount;
      },
    },

    /**
     * The property tables in the metadata.
     *
     * @memberof StructuralMetadata.prototype
     * @type {PropertyTable[]}
     * @readonly
     * @private
     */
    propertyTables: {
      get: function () {
        return this._propertyTables;
      },
    },

    /**
     * The property textures in the metadata.
     *
     * @memberof StructuralMetadata.prototype
     * @type {PropertyTexture[]}
     * @readonly
     * @private
     */
    propertyTextures: {
      get: function () {
        return this._propertyTextures;
      },
    },

    /**
     * The property attributes from the structural metadata extension
     *
     * @memberof StructuralMetadata.prototype
     * @type {PropertyAttribute[]}
     * @readonly
     * @private
     */
    propertyAttributes: {
      get: function () {
        return this._propertyAttributes;
      },
    },

    /**
     * Total size in bytes across all property tables
     *
     * @memberof StructuralMetadata.prototype
     * @type {Number}
     * @readonly
     * @private
     */
    propertyTablesByteLength: {
      get: function () {
        if (!defined(this._propertyTables)) {
          return 0;
        }

        let totalByteLength = 0;
        const length = this._propertyTables.length;
        for (let i = 0; i < length; i++) {
          totalByteLength += this._propertyTables[i].byteLength;
        }

        return totalByteLength;
      },
    },
  });

  /**
   * Gets the property table with the given ID.
   * <p>
   * For the legacy <code>EXT_feature_metadata</code>, textures are stored in an array sorted
   * by the key in the propertyTables dictionary.
   * </p>
   *
   * @param {Number} propertyTableId The property table ID.
   * @returns {PropertyTable} The property table.
   * @private
   */
  StructuralMetadata.prototype.getPropertyTable = function (propertyTableId) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("propertyTableId", propertyTableId);
    //>>includeEnd('debug');

    return this._propertyTables[propertyTableId];
  };

  /**
   * Gets the property texture with the given ID.
   * <p>
   * For the legacy <code>EXT_feature_metadata</code>, textures are stored in an array sorted
   * by the key in the propertyTextures dictionary.
   * </p>
   *
   * @param {Number} propertyTextureId The index into the property textures array.
   * @returns {PropertyTexture} The property texture
   * @private
   */
  StructuralMetadata.prototype.getPropertyTexture = function (propertyTextureId) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("propertyTextureId", propertyTextureId);
    //>>includeEnd('debug');

    return this._propertyTextures[propertyTextureId];
  };

  /**
   * Gets the property attribute with the given ID. This concept is new in
   * EXT_structural_metadata
   *
   * @param {Number} propertyAttributeId The index into the property attributes array.
   * @returns {PropertyAttribute} The property attribute
   * @private
   */
  StructuralMetadata.prototype.getPropertyAttribute = function (
    propertyAttributeId
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("propertyAttributeId", propertyAttributeId);
    //>>includeEnd('debug');

    return this._propertyAttributes[propertyAttributeId];
  };

  /**
   * Parse the <code>EXT_structural_metadata</code> glTF extension to create a
   * structural metadata object.
   *
   * @param {Object} options Object with the following properties:
   * @param {Object} options.extension The extension JSON object.
   * @param {MetadataSchema} options.schema The parsed schema.
   * @param {Object.<String, Uint8Array>} [options.bufferViews] An object mapping bufferView IDs to Uint8Array objects.
   * @param {Object.<String, Texture>} [options.textures] An object mapping texture IDs to {@link Texture} objects.
   * @return {StructuralMetadata} A structural metadata object
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function parseStructuralMetadata(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const extension = options.extension;

    // The calling code is responsible for loading the schema.
    // This keeps metadata parsing synchronous.
    const schema = options.schema;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.extension", extension);
    Check.typeOf.object("options.schema", schema);
    //>>includeEnd('debug');

    const propertyTables = [];
    if (defined(extension.propertyTables)) {
      for (let i = 0; i < extension.propertyTables.length; i++) {
        const propertyTable = extension.propertyTables[i];
        const classDefinition = schema.classes[propertyTable.class];
        const metadataTable = new MetadataTable({
          count: propertyTable.count,
          properties: propertyTable.properties,
          class: classDefinition,
          bufferViews: options.bufferViews,
        });
        propertyTables.push(
          new PropertyTable({
            id: i,
            name: propertyTable.name,
            count: propertyTable.count,
            metadataTable: metadataTable,
            extras: propertyTable.extras,
            extensions: propertyTable.extensions,
          })
        );
      }
    }

    const propertyTextures = [];
    if (defined(extension.propertyTextures)) {
      for (let i = 0; i < extension.propertyTextures.length; i++) {
        const propertyTexture = extension.propertyTextures[i];
        propertyTextures.push(
          new PropertyTexture({
            id: i,
            name: propertyTexture.name,
            propertyTexture: propertyTexture,
            class: schema.classes[propertyTexture.class],
            textures: options.textures,
          })
        );
      }
    }

    const propertyAttributes = [];
    if (defined(extension.propertyAttributes)) {
      for (let i = 0; i < extension.propertyAttributes.length; i++) {
        const propertyAttribute = extension.propertyAttributes[i];
        propertyAttributes.push(
          new PropertyAttribute({
            id: i,
            name: propertyAttribute.name,
            class: schema.classes[propertyAttribute.class],
            propertyAttribute: propertyAttribute,
          })
        );
      }
    }

    return new StructuralMetadata({
      schema: schema,
      propertyTables: propertyTables,
      propertyTextures: propertyTextures,
      propertyAttributes: propertyAttributes,
      statistics: extension.statistics,
      extras: extension.extras,
      extensions: extension.extensions,
    });
  }

  /**
   * Parse the <code>EXT_feature_metadata</code> glTF extension to create a
   * structural metadata object.
   *
   * @param {Object} options Object with the following properties:
   * @param {Object} options.extension The extension JSON object.
   * @param {MetadataSchema} options.schema The parsed schema.
   * @param {Object.<String, Uint8Array>} [options.bufferViews] An object mapping bufferView IDs to Uint8Array objects.
   * @param {Object.<String, Texture>} [options.textures] An object mapping texture IDs to {@link Texture} objects.
   * @return {StructuralMetadata} A structural metadata object
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function parseFeatureMetadataLegacy(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const extension = options.extension;

    // The calling code is responsible for loading the schema.
    // This keeps metadata parsing synchronous.
    const schema = options.schema;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.extension", extension);
    Check.typeOf.object("options.schema", schema);
    //>>includeEnd('debug');

    let i;
    const propertyTables = [];
    let sortedIds;
    if (defined(extension.featureTables)) {
      // Store textures in an array sorted by the dictionary keys. This
      // allows compatibility with the newer EXT_structural_metadata extension
      // which is array-based.
      sortedIds = Object.keys(extension.featureTables).sort();
      for (i = 0; i < sortedIds.length; i++) {
        const featureTableId = sortedIds[i];
        const featureTable = extension.featureTables[featureTableId];
        const classDefinition = schema.classes[featureTable.class];

        const metadataTable = new MetadataTable({
          count: featureTable.count,
          properties: featureTable.properties,
          class: classDefinition,
          bufferViews: options.bufferViews,
        });

        propertyTables.push(
          new PropertyTable({
            id: featureTableId,
            count: featureTable.count,
            metadataTable: metadataTable,
            extras: featureTable.extras,
            extensions: featureTable.extensions,
          })
        );
      }
    }

    const propertyTextures = [];
    if (defined(extension.featureTextures)) {
      // Store textures in an array sorted by the dictionary keys. This
      // allows compatibility with the newer EXT_structural_metadata extension
      // which is array-based.
      sortedIds = Object.keys(extension.featureTextures).sort();
      for (i = 0; i < sortedIds.length; i++) {
        const featureTextureId = sortedIds[i];
        const featureTexture = extension.featureTextures[featureTextureId];
        propertyTextures.push(
          new PropertyTexture({
            id: featureTextureId,
            propertyTexture: transcodeToPropertyTexture(featureTexture),
            class: schema.classes[featureTexture.class],
            textures: options.textures,
          })
        );
      }
    }

    return new StructuralMetadata({
      schema: schema,
      propertyTables: propertyTables,
      propertyTextures: propertyTextures,
      statistics: extension.statistics,
      extras: extension.extras,
      extensions: extension.extensions,
    });
  }

  function transcodeToPropertyTexture(featureTexture) {
    const propertyTexture = {
      class: featureTexture.class,
      properties: {},
    };

    const properties = featureTexture.properties;
    for (const propertyId in properties) {
      if (properties.hasOwnProperty(propertyId)) {
        const oldProperty = properties[propertyId];
        const property = {
          // EXT_structural_metadata uses numeric channel indices instead of
          // a string of channel letters like "rgba".
          channels: reformatChannels(oldProperty.channels),
          extras: oldProperty.extras,
          extensions: oldProperty.extensions,
        };

        // EXT_feature_metadata puts the textureInfo in property.texture.
        // EXT_structural_metadata flattens this structure; essentially a
        // textureInfo + channels
        propertyTexture.properties[propertyId] = combine$2(
          oldProperty.texture,
          property,
          true
        );
      }
    }

    return propertyTexture;
  }

  function reformatChannels(channelsString) {
    const length = channelsString.length;
    const result = new Array(length);
    for (let i = 0; i < length; i++) {
      result[i] = "rgba".indexOf(channelsString[i]);
    }
    return result;
  }

  /**
   * Loads glTF structural metadata
   * <p>
   * Implements the {@link ResourceLoader} interface.
   * </p>
   *
   * @alias GltfStructuralMetadataLoader
   * @constructor
   * @augments ResourceLoader
   *
   * @param {Object} options Object with the following properties:
   * @param {Object} options.gltf The glTF JSON.
   * @param {String} [options.extension] The <code>EXT_structural_metadata</code> extension object. If this is undefined, then extensionLegacy must be defined.
   * @param {String} [options.extensionLegacy] The legacy <code>EXT_feature_metadata</code> extension for backwards compatibility.
   * @param {Resource} options.gltfResource The {@link Resource} containing the glTF.
   * @param {Resource} options.baseResource The {@link Resource} that paths in the glTF JSON are relative to.
   * @param {SupportedImageFormats} options.supportedImageFormats The supported image formats.
   * @param {String} [options.cacheKey] The cache key of the resource.
   * @param {Boolean} [options.asynchronous=true] Determines if WebGL resource creation will be spread out over several frames or block until all WebGL resources are created.
   *
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function GltfStructuralMetadataLoader(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const gltf = options.gltf;
    const extension = options.extension;
    const extensionLegacy = options.extensionLegacy;
    const gltfResource = options.gltfResource;
    const baseResource = options.baseResource;
    const supportedImageFormats = options.supportedImageFormats;
    const cacheKey = options.cacheKey;
    const asynchronous = defaultValue(options.asynchronous, true);

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.gltf", gltf);
    Check.typeOf.object("options.gltfResource", gltfResource);
    Check.typeOf.object("options.baseResource", baseResource);
    Check.typeOf.object("options.supportedImageFormats", supportedImageFormats);

    if (!defined(options.extension) && !defined(options.extensionLegacy)) {
      throw new DeveloperError(
        "One of options.extension or options.extensionLegacy must be specified"
      );
    }
    //>>includeEnd('debug');

    this._gltfResource = gltfResource;
    this._baseResource = baseResource;
    this._gltf = gltf;
    this._extension = extension;
    this._extensionLegacy = extensionLegacy;
    this._supportedImageFormats = supportedImageFormats;
    this._cacheKey = cacheKey;
    this._asynchronous = asynchronous;
    this._bufferViewLoaders = [];
    this._textureLoaders = [];
    this._schemaLoader = undefined;
    this._structuralMetadata = undefined;
    this._state = ResourceLoaderState$1.UNLOADED;
    this._promise = undefined;
  }

  if (defined(Object.create)) {
    GltfStructuralMetadataLoader.prototype = Object.create(
      ResourceLoader.prototype
    );
    GltfStructuralMetadataLoader.prototype.constructor = GltfStructuralMetadataLoader;
  }

  Object.defineProperties(GltfStructuralMetadataLoader.prototype, {
    /**
     * A promise that resolves to the resource when the resource is ready, or undefined if the resource hasn't started loading.
     *
     * @memberof GltfStructuralMetadataLoader.prototype
     *
     * @type {Promise.<GltfStructuralMetadataLoader>|undefined}
     * @readonly
     * @private
     */
    promise: {
      get: function () {
        return this._promise;
      },
    },
    /**
     * The cache key of the resource.
     *
     * @memberof GltfStructuralMetadataLoader.prototype
     *
     * @type {String}
     * @readonly
     * @private
     */
    cacheKey: {
      get: function () {
        return this._cacheKey;
      },
    },
    /**
     * The parsed structural metadata
     *
     * @memberof GltfStructuralMetadataLoader.prototype
     *
     * @type {StructuralMetadata}
     * @readonly
     * @private
     */
    structuralMetadata: {
      get: function () {
        return this._structuralMetadata;
      },
    },
  });

  /**
   * Loads the resource.
   * @returns {Promise.<GltfStructuralMetadataLoader>} A promise which resolves to the loader when the resource loading is completed.
   * @private
   */
  GltfStructuralMetadataLoader.prototype.load = function () {
    const bufferViewsPromise = loadBufferViews(this);
    const texturesPromise = loadTextures(this);
    const schemaPromise = loadSchema(this);

    this._gltf = undefined; // No longer need to hold onto the glTF
    this._state = ResourceLoaderState$1.LOADING;

    const that = this;

    this._promise = Promise.all([
      bufferViewsPromise,
      texturesPromise,
      schemaPromise,
    ])
      .then(function (results) {
        if (that.isDestroyed()) {
          return;
        }
        const bufferViews = results[0];
        const textures = results[1];
        const schema = results[2];

        if (defined(that._extension)) {
          that._structuralMetadata = parseStructuralMetadata({
            extension: that._extension,
            schema: schema,
            bufferViews: bufferViews,
            textures: textures,
          });
        } else {
          that._structuralMetadata = parseFeatureMetadataLegacy({
            extension: that._extensionLegacy,
            schema: schema,
            bufferViews: bufferViews,
            textures: textures,
          });
        }
        that._state = ResourceLoaderState$1.READY;
        return that;
      })
      .catch(function (error) {
        if (that.isDestroyed()) {
          return;
        }
        that.unload();
        that._state = ResourceLoaderState$1.FAILED;
        const errorMessage = "Failed to load structural metadata";
        return Promise.reject(that.getError(errorMessage, error));
      });
  };

  function gatherBufferViewIdsFromProperties(properties, bufferViewIdSet) {
    for (const propertyId in properties) {
      if (properties.hasOwnProperty(propertyId)) {
        const property = properties[propertyId];
        const values = property.values;
        const arrayOffsets = property.arrayOffsets;
        const stringOffsets = property.stringOffsets;

        // Using an object like a mathematical set
        if (defined(values)) {
          bufferViewIdSet[values] = true;
        }
        if (defined(arrayOffsets)) {
          bufferViewIdSet[arrayOffsets] = true;
        }
        if (defined(stringOffsets)) {
          bufferViewIdSet[stringOffsets] = true;
        }
      }
    }
  }

  function gatherBufferViewIdsFromPropertiesLegacy(properties, bufferViewIdSet) {
    for (const propertyId in properties) {
      if (properties.hasOwnProperty(propertyId)) {
        const property = properties[propertyId];
        const bufferView = property.bufferView;
        const arrayOffsetBufferView = property.arrayOffsetBufferView;
        const stringOffsetBufferView = property.stringOffsetBufferView;

        // Using an object like a mathematical set
        if (defined(bufferView)) {
          bufferViewIdSet[bufferView] = true;
        }
        if (defined(arrayOffsetBufferView)) {
          bufferViewIdSet[arrayOffsetBufferView] = true;
        }
        if (defined(stringOffsetBufferView)) {
          bufferViewIdSet[stringOffsetBufferView] = true;
        }
      }
    }
  }

  function gatherUsedBufferViewIds(extension) {
    const propertyTables = extension.propertyTables;
    const bufferViewIdSet = {};
    if (defined(propertyTables)) {
      for (let i = 0; i < propertyTables.length; i++) {
        const propertyTable = propertyTables[i];
        gatherBufferViewIdsFromProperties(
          propertyTable.properties,
          bufferViewIdSet
        );
      }
    }
    return bufferViewIdSet;
  }

  function gatherUsedBufferViewIdsLegacy(extensionLegacy) {
    const featureTables = extensionLegacy.featureTables;

    const bufferViewIdSet = {};
    if (defined(featureTables)) {
      for (const featureTableId in featureTables) {
        if (featureTables.hasOwnProperty(featureTableId)) {
          const featureTable = featureTables[featureTableId];
          const properties = featureTable.properties;
          if (defined(properties)) {
            gatherBufferViewIdsFromPropertiesLegacy(properties, bufferViewIdSet);
          }
        }
      }
    }
    return bufferViewIdSet;
  }

  function loadBufferViews(structuralMetadataLoader) {
    let bufferViewIds;
    if (defined(structuralMetadataLoader._extension)) {
      bufferViewIds = gatherUsedBufferViewIds(
        structuralMetadataLoader._extension
      );
    } else {
      bufferViewIds = gatherUsedBufferViewIdsLegacy(
        structuralMetadataLoader._extensionLegacy
      );
    }

    // Load the buffer views
    const bufferViewPromises = [];
    const bufferViewLoaders = {};
    for (const bufferViewId in bufferViewIds) {
      if (bufferViewIds.hasOwnProperty(bufferViewId)) {
        const bufferViewLoader = ResourceCache.loadBufferView({
          gltf: structuralMetadataLoader._gltf,
          bufferViewId: parseInt(bufferViewId),
          gltfResource: structuralMetadataLoader._gltfResource,
          baseResource: structuralMetadataLoader._baseResource,
        });
        bufferViewPromises.push(bufferViewLoader.promise);
        structuralMetadataLoader._bufferViewLoaders.push(bufferViewLoader);
        bufferViewLoaders[bufferViewId] = bufferViewLoader;
      }
    }

    // Return a promise to a map of buffer view IDs to typed arrays
    return Promise.all(bufferViewPromises).then(function () {
      const bufferViews = {};
      for (const bufferViewId in bufferViewLoaders) {
        if (bufferViewLoaders.hasOwnProperty(bufferViewId)) {
          const bufferViewLoader = bufferViewLoaders[bufferViewId];
          // Copy the typed array and let the underlying ArrayBuffer be freed
          const bufferViewTypedArray = new Uint8Array(
            bufferViewLoader.typedArray
          );
          bufferViews[bufferViewId] = bufferViewTypedArray;
        }
      }

      // Buffer views can be unloaded after the data has been copied
      unloadBufferViews$1(structuralMetadataLoader);

      return bufferViews;
    });
  }

  function gatherUsedTextureIds(structuralMetadataExtension) {
    // Gather the used textures
    const textureIds = {};
    const propertyTextures = structuralMetadataExtension.propertyTextures;
    if (defined(propertyTextures)) {
      for (let i = 0; i < propertyTextures.length; i++) {
        const propertyTexture = propertyTextures[i];
        const properties = propertyTexture.properties;
        if (defined(properties)) {
          gatherTextureIdsFromProperties(properties, textureIds);
        }
      }
    }
    return textureIds;
  }

  function gatherTextureIdsFromProperties(properties, textureIds) {
    for (const propertyId in properties) {
      if (properties.hasOwnProperty(propertyId)) {
        // in EXT_structural_metadata the property is a valid textureInfo.
        const textureInfo = properties[propertyId];
        textureIds[textureInfo.index] = textureInfo;
      }
    }
  }

  function gatherUsedTextureIdsLegacy(extensionLegacy) {
    // Gather the used textures
    const textureIds = {};
    const featureTextures = extensionLegacy.featureTextures;
    if (defined(featureTextures)) {
      for (const featureTextureId in featureTextures) {
        if (featureTextures.hasOwnProperty(featureTextureId)) {
          const featureTexture = featureTextures[featureTextureId];
          const properties = featureTexture.properties;
          if (defined(properties)) {
            gatherTextureIdsFromPropertiesLegacy(properties, textureIds);
          }
        }
      }
    }

    return textureIds;
  }

  function gatherTextureIdsFromPropertiesLegacy(properties, textureIds) {
    for (const propertyId in properties) {
      if (properties.hasOwnProperty(propertyId)) {
        const property = properties[propertyId];
        const textureInfo = property.texture;
        textureIds[textureInfo.index] = textureInfo;
      }
    }
  }

  function loadTextures(structuralMetadataLoader) {
    let textureIds;
    if (defined(structuralMetadataLoader._extension)) {
      textureIds = gatherUsedTextureIds(structuralMetadataLoader._extension);
    } else {
      textureIds = gatherUsedTextureIdsLegacy(
        structuralMetadataLoader._extensionLegacy
      );
    }

    const gltf = structuralMetadataLoader._gltf;
    const gltfResource = structuralMetadataLoader._gltfResource;
    const baseResource = structuralMetadataLoader._baseResource;
    const supportedImageFormats = structuralMetadataLoader._supportedImageFormats;
    const asynchronous = structuralMetadataLoader._asynchronous;

    // Load the textures
    const texturePromises = [];
    const textureLoaders = {};
    for (const textureId in textureIds) {
      if (textureIds.hasOwnProperty(textureId)) {
        const textureLoader = ResourceCache.loadTexture({
          gltf: gltf,
          textureInfo: textureIds[textureId],
          gltfResource: gltfResource,
          baseResource: baseResource,
          supportedImageFormats: supportedImageFormats,
          asynchronous: asynchronous,
        });
        texturePromises.push(textureLoader.promise);
        structuralMetadataLoader._textureLoaders.push(textureLoader);
        textureLoaders[textureId] = textureLoader;
      }
    }

    // Return a promise to a map of texture IDs to Texture objects
    return Promise.all(texturePromises).then(function () {
      const textures = {};
      for (const textureId in textureLoaders) {
        if (textureLoaders.hasOwnProperty(textureId)) {
          const textureLoader = textureLoaders[textureId];
          textures[textureId] = textureLoader.texture;
        }
      }
      return textures;
    });
  }

  function loadSchema(structuralMetadataLoader) {
    const extension = defaultValue(
      structuralMetadataLoader._extension,
      structuralMetadataLoader._extensionLegacy
    );

    let schemaLoader;
    if (defined(extension.schemaUri)) {
      const resource = structuralMetadataLoader._baseResource.getDerivedResource({
        url: extension.schemaUri,
      });
      schemaLoader = ResourceCache.loadSchema({
        resource: resource,
      });
    } else {
      schemaLoader = ResourceCache.loadSchema({
        schema: extension.schema,
      });
    }

    structuralMetadataLoader._schemaLoader = schemaLoader;

    return schemaLoader.promise.then(function (schemaLoader) {
      return schemaLoader.schema;
    });
  }

  /**
   * Processes the resource until it becomes ready.
   *
   * @param {FrameState} frameState The frame state.
   * @private
   */
  GltfStructuralMetadataLoader.prototype.process = function (frameState) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("frameState", frameState);
    //>>includeEnd('debug');

    if (this._state !== ResourceLoaderState$1.LOADING) {
      return;
    }

    const textureLoaders = this._textureLoaders;
    const textureLoadersLength = textureLoaders.length;

    for (let i = 0; i < textureLoadersLength; ++i) {
      const textureLoader = textureLoaders[i];
      textureLoader.process(frameState);
    }
  };

  function unloadBufferViews$1(structuralMetadataLoader) {
    const bufferViewLoaders = structuralMetadataLoader._bufferViewLoaders;
    const bufferViewLoadersLength = bufferViewLoaders.length;
    for (let i = 0; i < bufferViewLoadersLength; ++i) {
      ResourceCache.unload(bufferViewLoaders[i]);
    }
    structuralMetadataLoader._bufferViewLoaders.length = 0;
  }

  function unloadTextures$1(structuralMetadataLoader) {
    const textureLoaders = structuralMetadataLoader._textureLoaders;
    const textureLoadersLength = textureLoaders.length;
    for (let i = 0; i < textureLoadersLength; ++i) {
      ResourceCache.unload(textureLoaders[i]);
    }
    structuralMetadataLoader._textureLoaders.length = 0;
  }

  /**
   * Unloads the resource.
   * @private
   */
  GltfStructuralMetadataLoader.prototype.unload = function () {
    unloadBufferViews$1(this);
    unloadTextures$1(this);

    if (defined(this._schemaLoader)) {
      ResourceCache.unload(this._schemaLoader);
    }
    this._schemaLoader = undefined;

    this._structuralMetadata = undefined;
  };

  /**
   * An enum describing the built-in instance attribute semantics.
   *
   * @enum {String}
   *
   * @private
   */
  const InstanceAttributeSemantic = {
    /**
     * Per-instance translation.
     *
     * @type {String}
     * @constant
     */
    TRANSLATION: "TRANSLATION",

    /**
     * Per-instance rotation.
     *
     * @type {String}
     * @constant
     */
    ROTATION: "ROTATION",

    /**
     * Per-instance scale.
     *
     * @type {String}
     * @constant
     */
    SCALE: "SCALE",

    /**
     * Per-instance feature ID.
     *
     * @type {String}
     * @constant
     */
    FEATURE_ID: "_FEATURE_ID",
  };

  /**
   * Gets the instance attribute semantic matching the glTF attribute semantic.
   *
   * @returns {InstanceAttributeSemantic} The instance attribute semantic, or undefined if there is no match.
   *
   * @private
   */
  InstanceAttributeSemantic.fromGltfSemantic = function (gltfSemantic) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("gltfSemantic", gltfSemantic);
    //>>includeEnd('debug')

    let semantic = gltfSemantic;

    // Strip the set index from the semantic
    const setIndexRegex = /^(\w+)_\d+$/;
    const setIndexMatch = setIndexRegex.exec(gltfSemantic);
    if (setIndexMatch !== null) {
      semantic = setIndexMatch[1];
    }

    switch (semantic) {
      case "TRANSLATION":
        return InstanceAttributeSemantic.TRANSLATION;
      case "ROTATION":
        return InstanceAttributeSemantic.ROTATION;
      case "SCALE":
        return InstanceAttributeSemantic.SCALE;
      case "_FEATURE_ID":
        return InstanceAttributeSemantic.FEATURE_ID;
    }

    return undefined;
  };

  var InstanceAttributeSemantic$1 = Object.freeze(InstanceAttributeSemantic);

  /**
   * Image formats supported by the browser.
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Boolean} [options.webp=false] Whether the browser supports WebP images.
   * @param {Boolean} [options.basis=false] Whether the browser supports compressed textures required to view KTX2 + Basis Universal images.
   *
   * @private
   */
  function SupportedImageFormats(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    this.webp = defaultValue(options.webp, false);
    this.basis = defaultValue(options.basis, false);
  }

  const Attribute$2 = ModelComponents.Attribute;
  const Indices = ModelComponents.Indices;
  const FeatureIdAttribute$3 = ModelComponents.FeatureIdAttribute;
  const FeatureIdTexture = ModelComponents.FeatureIdTexture;
  const FeatureIdImplicitRange = ModelComponents.FeatureIdImplicitRange;
  const MorphTarget = ModelComponents.MorphTarget;
  const Primitive$1 = ModelComponents.Primitive;
  const Instances$1 = ModelComponents.Instances;
  const Skin = ModelComponents.Skin;
  const Node$2 = ModelComponents.Node;
  const AnimatedPropertyType$1 = ModelComponents.AnimatedPropertyType;
  const AnimationSampler = ModelComponents.AnimationSampler;
  const AnimationTarget = ModelComponents.AnimationTarget;
  const AnimationChannel = ModelComponents.AnimationChannel;
  const Animation$1 = ModelComponents.Animation;
  const ArticulationStage = ModelComponents.ArticulationStage;
  const Articulation = ModelComponents.Articulation;
  const Asset = ModelComponents.Asset;
  const Scene$2 = ModelComponents.Scene;
  const Components$1 = ModelComponents.Components;
  const MetallicRoughness$2 = ModelComponents.MetallicRoughness;
  const SpecularGlossiness$1 = ModelComponents.SpecularGlossiness;
  const Material$2 = ModelComponents.Material;

  const GltfLoaderState = {
    UNLOADED: 0,
    LOADING: 1,
    LOADED: 2,
    PROCESSING: 3,
    PROCESSED: 4,
    READY: 4,
    FAILED: 5,
  };

  /**
   * Loads a glTF model.
   * <p>
   * Implements the {@link ResourceLoader} interface.
   * </p>
   *
   * @alias GltfLoader
   * @constructor
   * @augments ResourceLoader
   *
   * @param {Object} options Object with the following properties:
   * @param {Resource} options.gltfResource The {@link Resource} containing the glTF. This is often the path of the .gltf or .glb file, but may also be the path of the .b3dm, .i3dm, or .cmpt file containing the embedded glb. .cmpt resources should have a URI fragment indicating the index of the inner content to which the glb belongs in order to individually identify the glb in the cache, e.g. http://example.com/tile.cmpt#index=2.
   * @param {Resource} [options.baseResource] The {@link Resource} that paths in the glTF JSON are relative to.
   * @param {Uint8Array} [options.typedArray] The typed array containing the glTF contents, e.g. from a .b3dm, .i3dm, or .cmpt file.
   * @param {Object} [options.gltfJson] A parsed glTF JSON file instead of passing it in as a typed array.
   * @param {Boolean} [options.releaseGltfJson=false] When true, the glTF JSON is released once the glTF is loaded. This is especially useful for cases like 3D Tiles, where each .gltf model is unique and caching the glTF JSON is not effective.
   * @param {Boolean} [options.asynchronous=true] Determines if WebGL resource creation will be spread out over several frames or block until all WebGL resources are created.
   * @param {Boolean} [options.incrementallyLoadTextures=true] Determine if textures may continue to stream in after the glTF is loaded.
   * @param {Axis} [options.upAxis=Axis.Y] The up-axis of the glTF model.
   * @param {Axis} [options.forwardAxis=Axis.Z] The forward-axis of the glTF model.
   * @param {Boolean} [options.loadAttributesAsTypedArray=false] Load all attributes and indices as typed arrays instead of GPU buffers.
   * @param {Boolean} [options.loadAttributesFor2D=false] If true, load the positions buffer and any instanced attribute buffers as typed arrays for accurately projecting models to 2D.
   * @param {Boolean} [options.loadIndicesForWireframe=false] If true, load the index buffer as both a buffer and typed array. The latter is useful for creating wireframe indices in WebGL1.
   * @param {Boolean} [options.renameBatchIdSemantic=false] If true, rename _BATCHID or BATCHID to _FEATURE_ID_0. This is used for .b3dm models
   * @private
   */
  function GltfLoader(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const gltfResource = options.gltfResource;
    let baseResource = options.baseResource;
    const typedArray = options.typedArray;
    const releaseGltfJson = defaultValue(options.releaseGltfJson, false);
    const asynchronous = defaultValue(options.asynchronous, true);
    const incrementallyLoadTextures = defaultValue(
      options.incrementallyLoadTextures,
      true
    );
    const upAxis = defaultValue(options.upAxis, Axis$1.Y);
    const forwardAxis = defaultValue(options.forwardAxis, Axis$1.Z);
    const loadAttributesAsTypedArray = defaultValue(
      options.loadAttributesAsTypedArray,
      false
    );
    const loadAttributesFor2D = defaultValue(options.loadAttributesFor2D, false);
    const loadIndicesForWireframe = defaultValue(
      options.loadIndicesForWireframe,
      false
    );
    const renameBatchIdSemantic = defaultValue(
      options.renameBatchIdSemantic,
      false
    );

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.gltfResource", gltfResource);
    //>>includeEnd('debug');

    baseResource = defined(baseResource) ? baseResource : gltfResource.clone();

    this._gltfJson = options.gltfJson;
    this._gltfResource = gltfResource;
    this._baseResource = baseResource;
    this._typedArray = typedArray;
    this._releaseGltfJson = releaseGltfJson;
    this._asynchronous = asynchronous;
    this._incrementallyLoadTextures = incrementallyLoadTextures;
    this._upAxis = upAxis;
    this._forwardAxis = forwardAxis;
    this._loadAttributesAsTypedArray = loadAttributesAsTypedArray;
    this._loadAttributesFor2D = loadAttributesFor2D;
    this._loadIndicesForWireframe = loadIndicesForWireframe;
    this._renameBatchIdSemantic = renameBatchIdSemantic;

    // When loading EXT_feature_metadata, the feature tables and textures
    // are now stored as arrays like the newer EXT_structural_metadata extension.
    // This requires sorting the dictionary keys for a consistent ordering.
    this._sortedPropertyTableIds = undefined;
    this._sortedFeatureTextureIds = undefined;

    this._gltfJsonLoader = undefined;
    this._state = GltfLoaderState.UNLOADED;
    this._textureState = GltfLoaderState.UNLOADED;
    this._promise = undefined;
    this._texturesLoadedPromise = undefined;
    this._process = function (loader, frameState) {};
    this._processTextures = function (loader, frameState) {};

    // Loaders that need to be processed before the glTF becomes ready
    this._loaderPromises = [];
    this._textureLoaders = [];
    this._texturesPromises = [];
    this._bufferViewLoaders = [];
    this._geometryLoaders = [];
    this._structuralMetadataLoader = undefined;

    // Loaded results
    this._components = undefined;
  }

  if (defined(Object.create)) {
    GltfLoader.prototype = Object.create(ResourceLoader.prototype);
    GltfLoader.prototype.constructor = GltfLoader;
  }

  Object.defineProperties(GltfLoader.prototype, {
    /**
     * A promise that resolves to the resource when the resource is ready, or undefined if the resource hasn't started loading.
     *
     * @memberof GltfLoader.prototype
     *
     * @type {Promise.<GltfLoader>|undefined}
     * @readonly
     * @private
     */
    promise: {
      get: function () {
        return this._promise;
      },
    },
    /**
     * The cache key of the resource.
     *
     * @memberof GltfLoader.prototype
     *
     * @type {String}
     * @readonly
     * @private
     */
    cacheKey: {
      get: function () {
        return undefined;
      },
    },
    /**
     * The loaded components.
     *
     * @memberof GltfLoader.prototype
     *
     * @type {ModelComponents.Components}
     * @readonly
     * @private
     */
    components: {
      get: function () {
        return this._components;
      },
    },

    /**
     * A promise that resolves when all textures are loaded.
     * When <code>incrementallyLoadTextures</code> is true this may resolve after
     * <code>promise</code> resolves.
     *
     * @memberof GltfLoader.prototype
     *
     * @type {Promise<void>}
     * @readonly
     * @private
     */
    texturesLoadedPromise: {
      get: function () {
        return this._texturesLoadedPromise;
      },
    },
  });

  /**
   * Loads the resource.
   * @returns {Promise.<GltfLoader>} A promise which resolves to the loader when the resource loading is completed.
   * @private
   */
  GltfLoader.prototype.load = function () {
    const gltfJsonLoader = ResourceCache.loadGltfJson({
      gltfResource: this._gltfResource,
      baseResource: this._baseResource,
      typedArray: this._typedArray,
      gltfJson: this._gltfJson,
    });

    this._gltfJsonLoader = gltfJsonLoader;
    this._state = GltfLoaderState.LOADING;
    this._textureState = GltfLoaderState.LOADING;

    const that = this;
    let textureProcessPromise;
    const processPromise = new Promise(function (resolve, reject) {
      textureProcessPromise = new Promise(function (
        resolveTextures,
        rejectTextures
      ) {
        that._process = function (loader, frameState) {
          if (!FeatureDetection.supportsWebP.initialized) {
            FeatureDetection.supportsWebP.initialize();
            return;
          }

          if (loader._state === GltfLoaderState.LOADED) {
            loader._state = GltfLoaderState.PROCESSING;

            const supportedImageFormats = new SupportedImageFormats({
              webp: FeatureDetection.supportsWebP(),
              basis: frameState.context.supportsBasis,
            });

            let gltf;
            if (defined(loader._gltfJsonLoader)) {
              gltf = loader._gltfJsonLoader.gltf;
            } else {
              gltf = loader._gltfJson;
            }

            // Parse the glTF which populates the loaders arrays. The promise will
            // resolve once all the loaders are ready (i.e. all external resources
            // have been fetched and all GPU resources have been created). Loaders that
            // create GPU resources need to be processed every frame until they become
            // ready since the JobScheduler is not able to execute all jobs in a single
            // frame. Also note that it's fine to call process before a loader is ready
            // to process; nothing will happen.
            parse$1(
              loader,
              gltf,
              supportedImageFormats,
              frameState,
              reject,
              rejectTextures
            );

            if (defined(loader._gltfJsonLoader) && loader._releaseGltfJson) {
              // Check that the glTF JSON loader is still defined before trying to unload it.
              // It may be undefined if the ready promise rejects immediately (which can happen in unit tests)
              ResourceCache.unload(loader._gltfJsonLoader);
              loader._gltfJsonLoader = undefined;
            }
          }

          if (loader._state === GltfLoaderState.PROCESSING) {
            processLoaders(loader, frameState);
          }

          if (loader._state === GltfLoaderState.PROCESSED) {
            unloadBufferViews(loader); // Buffer views can be unloaded after the data has been copied
            loader._state = GltfLoaderState.READY;
            resolve(loader);
          }
        };

        that._processTextures = function (loader, frameState) {
          if (loader._textureState === GltfLoaderState.LOADED) {
            loader._textureState = GltfLoaderState.PROCESSING;
          }

          if (loader._textureState === GltfLoaderState.PROCESSING) {
            let i;
            const textureLoaders = loader._textureLoaders;
            const textureLoadersLength = textureLoaders.length;
            for (i = 0; i < textureLoadersLength; ++i) {
              textureLoaders[i].process(frameState);
            }
          }

          if (loader._textureState === GltfLoaderState.PROCESSED) {
            loader._textureState = GltfLoaderState.READY;
            resolveTextures(loader);
          }
        };
      });
    });

    this._promise = gltfJsonLoader.promise
      .then(function () {
        if (that.isDestroyed()) {
          return;
        }
        that._state = GltfLoaderState.LOADED;
        that._textureState = GltfLoaderState.LOADED;

        return processPromise;
      })
      .catch(function (error) {
        if (that.isDestroyed()) {
          return;
        }
        that._state = GltfLoaderState.FAILED;
        that._textureState = GltfLoaderState.FAILED;
        return handleError$2(that, error);
      });

    this._texturesLoadedPromise = textureProcessPromise.catch(function (error) {
      if (that.isDestroyed()) {
        return;
      }

      that._textureState = GltfLoaderState.FAILED;
      return handleError$2(that, error);
    });

    return this._promise;
  };

  function handleError$2(gltfLoader, error) {
    gltfLoader.unload();
    const errorMessage = "Failed to load glTF";
    error = gltfLoader.getError(errorMessage, error);
    return Promise.reject(error);
  }

  function processLoaders(loader, frameState) {
    let i;
    const bufferViewLoaders = loader._bufferViewLoaders;
    const bufferViewLoadersLength = bufferViewLoaders.length;
    for (i = 0; i < bufferViewLoadersLength; ++i) {
      bufferViewLoaders[i].process(frameState);
    }

    const geometryLoaders = loader._geometryLoaders;
    const geometryLoadersLength = geometryLoaders.length;
    for (i = 0; i < geometryLoadersLength; ++i) {
      geometryLoaders[i].process(frameState);
    }

    if (defined(loader._structuralMetadataLoader)) {
      loader._structuralMetadataLoader.process(frameState);
    }
  }

  /**
   * Processes the resource until it becomes ready.
   *
   * @param {FrameState} frameState The frame state.
   * @private
   */
  GltfLoader.prototype.process = function (frameState) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("frameState", frameState);
    //>>includeEnd('debug');

    this._process(this, frameState);
    // Since textures can be loaded independently and are handled through a separate promise, they are processed in their own function
    this._processTextures(this, frameState);
  };

  function loadVertexBuffer(
    loader,
    gltf,
    accessorId,
    semantic,
    draco,
    dequantize,
    loadBuffer,
    loadTypedArray
  ) {
    const accessor = gltf.accessors[accessorId];
    const bufferViewId = accessor.bufferView;

    const vertexBufferLoader = ResourceCache.loadVertexBuffer({
      gltf: gltf,
      gltfResource: loader._gltfResource,
      baseResource: loader._baseResource,
      bufferViewId: bufferViewId,
      draco: draco,
      attributeSemantic: semantic,
      accessorId: accessorId,
      asynchronous: loader._asynchronous,
      dequantize: dequantize,
      loadBuffer: loadBuffer,
      loadTypedArray: loadTypedArray,
    });

    loader._geometryLoaders.push(vertexBufferLoader);

    return vertexBufferLoader;
  }

  function loadIndexBuffer(loader, gltf, accessorId, draco, frameState) {
    const loadAttributesAsTypedArray = loader._loadAttributesAsTypedArray;

    // Load the index buffer as a typed array to generate wireframes in WebGL1.
    const loadForWireframe =
      loader._loadIndicesForWireframe && !frameState.context.webgl2;

    const loadBuffer = !loadAttributesAsTypedArray;
    const loadTypedArray = loadAttributesAsTypedArray || loadForWireframe;

    const indexBufferLoader = ResourceCache.loadIndexBuffer({
      gltf: gltf,
      accessorId: accessorId,
      gltfResource: loader._gltfResource,
      baseResource: loader._baseResource,
      draco: draco,
      asynchronous: loader._asynchronous,
      loadBuffer: loadBuffer,
      loadTypedArray: loadTypedArray,
    });

    loader._geometryLoaders.push(indexBufferLoader);

    return indexBufferLoader;
  }

  function loadBufferView(loader, gltf, bufferViewId) {
    const bufferViewLoader = ResourceCache.loadBufferView({
      gltf: gltf,
      bufferViewId: bufferViewId,
      gltfResource: loader._gltfResource,
      baseResource: loader._baseResource,
    });

    loader._bufferViewLoaders.push(bufferViewLoader);

    return bufferViewLoader;
  }

  function getPackedTypedArray(gltf, accessor, bufferViewTypedArray) {
    let byteOffset = accessor.byteOffset;
    const byteStride = getAccessorByteStride(gltf, accessor);
    const count = accessor.count;
    const componentCount = numberOfComponentsForType(accessor.type);
    const componentType = accessor.componentType;
    const componentByteLength = ComponentDatatype$1.getSizeInBytes(componentType);
    const defaultByteStride = componentByteLength * componentCount;
    const componentsLength = count * componentCount;

    if (byteStride === defaultByteStride) {
      // Copy the typed array and let the underlying ArrayBuffer be freed
      bufferViewTypedArray = new Uint8Array(bufferViewTypedArray);
      return ComponentDatatype$1.createArrayBufferView(
        componentType,
        bufferViewTypedArray.buffer,
        bufferViewTypedArray.byteOffset + byteOffset,
        componentsLength
      );
    }

    const accessorTypedArray = ComponentDatatype$1.createTypedArray(
      componentType,
      componentsLength
    );

    const dataView = new DataView(bufferViewTypedArray.buffer);
    const components = new Array(componentCount);
    const componentReader = getComponentReader(accessor.componentType);
    byteOffset = bufferViewTypedArray.byteOffset + byteOffset;

    for (let i = 0; i < count; ++i) {
      componentReader(
        dataView,
        byteOffset,
        componentCount,
        componentByteLength,
        components
      );
      for (let j = 0; j < componentCount; ++j) {
        accessorTypedArray[i * componentCount + j] = components[j];
      }
      byteOffset += byteStride;
    }

    return accessorTypedArray;
  }

  function loadDefaultAccessorValues(accessor, values) {
    const accessorType = accessor.type;
    if (accessorType === AttributeType$1.SCALAR) {
      return values.fill(0);
    }

    const MathType = AttributeType$1.getMathType(accessorType);
    return values.fill(MathType.clone(MathType.ZERO));
  }

  function loadAccessorValues(accessor, packedTypedArray, values, useQuaternion) {
    const accessorType = accessor.type;
    const accessorCount = accessor.count;

    if (accessorType === AttributeType$1.SCALAR) {
      for (let i = 0; i < accessorCount; i++) {
        values[i] = packedTypedArray[i];
      }
    } else if (accessorType === AttributeType$1.VEC4 && useQuaternion) {
      for (let i = 0; i < accessorCount; i++) {
        values[i] = Quaternion.unpack(packedTypedArray, i * 4);
      }
    } else {
      const MathType = AttributeType$1.getMathType(accessorType);
      const numberOfComponents = AttributeType$1.getNumberOfComponents(
        accessorType
      );

      for (let i = 0; i < accessorCount; i++) {
        values[i] = MathType.unpack(packedTypedArray, i * numberOfComponents);
      }
    }

    return values;
  }

  function loadAccessor(loader, gltf, accessorId, useQuaternion) {
    const accessor = gltf.accessors[accessorId];
    const accessorCount = accessor.count;
    const values = new Array(accessorCount);

    const bufferViewId = accessor.bufferView;
    if (defined(bufferViewId)) {
      const bufferViewLoader = loadBufferView(loader, gltf, bufferViewId);
      const promise = bufferViewLoader.promise
        .then(function (bufferViewLoader) {
          if (loader.isDestroyed()) {
            return;
          }
          const bufferViewTypedArray = bufferViewLoader.typedArray;
          const packedTypedArray = getPackedTypedArray(
            gltf,
            accessor,
            bufferViewTypedArray
          );

          useQuaternion = defaultValue(useQuaternion, false);
          loadAccessorValues(accessor, packedTypedArray, values, useQuaternion);
        })
        .catch(function () {
          loadDefaultAccessorValues(accessor, values);
        });
      loader._loaderPromises.push(promise);

      return values;
    }

    return loadDefaultAccessorValues(accessor, values);
  }

  function fromArray(MathType, values) {
    if (!defined(values)) {
      return undefined;
    }

    if (MathType === Number) {
      return values[0];
    }

    return MathType.unpack(values);
  }

  function getDefault(MathType) {
    if (MathType === Number) {
      return 0.0;
    }

    return new MathType(); // defaults to 0.0 for all types
  }

  function createAttribute(gltf, accessorId, name, semantic, setIndex) {
    const accessor = gltf.accessors[accessorId];
    const MathType = AttributeType$1.getMathType(accessor.type);

    const attribute = new Attribute$2();
    attribute.name = name;
    attribute.semantic = semantic;
    attribute.setIndex = setIndex;
    attribute.constant = getDefault(MathType);
    attribute.componentDatatype = accessor.componentType;
    attribute.normalized = defaultValue(accessor.normalized, false);
    attribute.count = accessor.count;
    attribute.type = accessor.type;
    attribute.min = fromArray(MathType, accessor.min);
    attribute.max = fromArray(MathType, accessor.max);
    attribute.byteOffset = accessor.byteOffset;
    attribute.byteStride = getAccessorByteStride(gltf, accessor);

    return attribute;
  }

  function getSetIndex(gltfSemantic) {
    const setIndexRegex = /^\w+_(\d+)$/;
    const setIndexMatch = setIndexRegex.exec(gltfSemantic);
    if (setIndexMatch !== null) {
      return parseInt(setIndexMatch[1]);
    }
    return undefined;
  }

  const scratchSemanticInfo = {
    gltfSemantic: undefined,
    renamedSemantic: undefined,
    modelSemantic: undefined,
  };

  function getSemanticInfo(loader, semanticType, gltfSemantic) {
    // For .b3dm, rename _BATCHID (or the legacy BATCHID) to _FEATURE_ID_0
    // in the generated model components for compatibility with EXT_mesh_features
    let renamedSemantic = gltfSemantic;
    if (
      loader._renameBatchIdSemantic &&
      (gltfSemantic === "_BATCHID" || gltfSemantic === "BATCHID")
    ) {
      renamedSemantic = "_FEATURE_ID_0";
    }

    const modelSemantic = semanticType.fromGltfSemantic(renamedSemantic);

    const semanticInfo = scratchSemanticInfo;
    semanticInfo.gltfSemantic = gltfSemantic;
    semanticInfo.renamedSemantic = renamedSemantic;
    semanticInfo.modelSemantic = modelSemantic;

    return semanticInfo;
  }

  function loadAttribute(
    loader,
    gltf,
    accessorId,
    semanticInfo,
    draco,
    dequantize,
    loadBuffer,
    loadTypedArray,
    loadAsTypedArrayPacked
  ) {
    const accessor = gltf.accessors[accessorId];
    const bufferViewId = accessor.bufferView;

    const gltfSemantic = semanticInfo.gltfSemantic;
    const renamedSemantic = semanticInfo.renamedSemantic;
    const modelSemantic = semanticInfo.modelSemantic;

    const setIndex = defined(modelSemantic)
      ? getSetIndex(renamedSemantic)
      : undefined;

    const name = gltfSemantic;
    const attribute = createAttribute(
      gltf,
      accessorId,
      name,
      modelSemantic,
      setIndex
    );

    if (!defined(draco) && !defined(bufferViewId)) {
      return attribute;
    }

    const vertexBufferLoader = loadVertexBuffer(
      loader,
      gltf,
      accessorId,
      gltfSemantic,
      draco,
      dequantize,
      loadBuffer,
      loadTypedArray
    );
    const promise = vertexBufferLoader.promise.then(function (
      vertexBufferLoader
    ) {
      if (loader.isDestroyed()) {
        return;
      }

      if (loadAsTypedArrayPacked) {
        // The accessor's byteOffset and byteStride should be ignored since values
        // are tightly packed in a typed array
        const bufferViewTypedArray = vertexBufferLoader.typedArray;
        attribute.packedTypedArray = getPackedTypedArray(
          gltf,
          accessor,
          bufferViewTypedArray
        );
        attribute.byteOffset = 0;
        attribute.byteStride = undefined;

        if (loadBuffer) {
          attribute.buffer = vertexBufferLoader.buffer;
        }
      } else {
        attribute.typedArray = vertexBufferLoader.typedArray;
        attribute.buffer = vertexBufferLoader.buffer;
      }

      if (
        defined(draco) &&
        defined(draco.attributes) &&
        defined(draco.attributes[gltfSemantic])
      ) {
        // The accessor's byteOffset and byteStride should be ignored for draco.
        // Each attribute is tightly packed in its own buffer after decode.
        attribute.byteOffset = 0;
        attribute.byteStride = undefined;
        attribute.quantization = vertexBufferLoader.quantization;
      }
    });

    loader._loaderPromises.push(promise);

    return attribute;
  }

  function loadVertexAttribute(
    loader,
    gltf,
    accessorId,
    gltfSemantic,
    draco,
    hasInstances,
    frameState
  ) {
    const semanticInfo = getSemanticInfo(
      loader,
      VertexAttributeSemantic$1,
      gltfSemantic
    );

    const modelSemantic = semanticInfo.modelSemantic;
    const isPositionAttribute =
      modelSemantic === VertexAttributeSemantic$1.POSITION;
    const loadFor2D =
      isPositionAttribute &&
      !hasInstances &&
      loader._loadAttributesFor2D &&
      !frameState.scene3DOnly;

    const loadAsTypedArrayOnly = loader._loadAttributesAsTypedArray;
    const loadBuffer = !loadAsTypedArrayOnly;
    const loadTypedArray = loadAsTypedArrayOnly || loadFor2D;
    const loadAsTypedArrayPacked = false;

    return loadAttribute(
      loader,
      gltf,
      accessorId,
      semanticInfo,
      draco,
      false,
      loadBuffer,
      loadTypedArray,
      loadAsTypedArrayPacked
    );
  }

  function loadInstancedAttribute(
    loader,
    gltf,
    accessorId,
    gltfSemantic,
    loadAsTypedArrayPacked,
    frameState
  ) {
    const semanticInfo = getSemanticInfo(
      loader,
      InstanceAttributeSemantic$1,
      gltfSemantic
    );

    const modelSemantic = semanticInfo.modelSemantic;

    const isTranslationAttribute =
      modelSemantic === InstanceAttributeSemantic$1.TRANSLATION;

    const loadFor2D =
      isTranslationAttribute &&
      loader._loadAttributesFor2D &&
      !frameState.scene3DOnly;

    const loadBuffer = !loadAsTypedArrayPacked;
    loadAsTypedArrayPacked = loadAsTypedArrayPacked || loadFor2D;

    // Don't pass in draco object since instanced attributes can't be draco compressed
    return loadAttribute(
      loader,
      gltf,
      accessorId,
      semanticInfo,
      undefined,
      true,
      loadBuffer,
      loadAsTypedArrayPacked,
      loadAsTypedArrayPacked
    );
  }

  function loadIndices(loader, gltf, accessorId, draco, frameState) {
    const accessor = gltf.accessors[accessorId];
    const bufferViewId = accessor.bufferView;

    if (!defined(draco) && !defined(bufferViewId)) {
      return undefined;
    }

    const indices = new Indices();
    indices.count = accessor.count;

    const indexBufferLoader = loadIndexBuffer(
      loader,
      gltf,
      accessorId,
      draco,
      frameState
    );

    const promise = indexBufferLoader.promise.then(function (indexBufferLoader) {
      if (loader.isDestroyed()) {
        return;
      }

      indices.indexDatatype = indexBufferLoader.indexDatatype;

      indices.buffer = indexBufferLoader.buffer;
      indices.typedArray = indexBufferLoader.typedArray;
    });

    loader._loaderPromises.push(promise);

    return indices;
  }

  function loadTexture(
    loader,
    gltf,
    textureInfo,
    supportedImageFormats,
    samplerOverride
  ) {
    const imageId = GltfLoaderUtil.getImageIdFromTexture({
      gltf: gltf,
      textureId: textureInfo.index,
      supportedImageFormats: supportedImageFormats,
    });

    if (!defined(imageId)) {
      return undefined;
    }

    const textureLoader = ResourceCache.loadTexture({
      gltf: gltf,
      textureInfo: textureInfo,
      gltfResource: loader._gltfResource,
      baseResource: loader._baseResource,
      supportedImageFormats: supportedImageFormats,
      asynchronous: loader._asynchronous,
    });

    loader._textureLoaders.push(textureLoader);

    const textureReader = GltfLoaderUtil.createModelTextureReader({
      textureInfo: textureInfo,
    });

    const promise = textureLoader.promise.then(function (textureLoader) {
      if (loader.isDestroyed()) {
        return;
      }
      textureReader.texture = textureLoader.texture;
      if (defined(samplerOverride)) {
        textureReader.texture.sampler = samplerOverride;
      }
    });

    loader._texturesPromises.push(promise);

    return textureReader;
  }

  function loadMaterial(loader, gltf, gltfMaterial, supportedImageFormats) {
    const material = new Material$2();

    const extensions = defaultValue(
      gltfMaterial.extensions,
      defaultValue.EMPTY_OBJECT
    );
    const pbrSpecularGlossiness = extensions.KHR_materials_pbrSpecularGlossiness;
    const pbrMetallicRoughness = gltfMaterial.pbrMetallicRoughness;

    material.unlit = defined(extensions.KHR_materials_unlit);

    if (defined(pbrSpecularGlossiness)) {
      const specularGlossiness = new SpecularGlossiness$1();
      material.specularGlossiness = specularGlossiness;

      if (defined(pbrSpecularGlossiness.diffuseTexture)) {
        specularGlossiness.diffuseTexture = loadTexture(
          loader,
          gltf,
          pbrSpecularGlossiness.diffuseTexture,
          supportedImageFormats
        );
      }
      if (defined(pbrSpecularGlossiness.specularGlossinessTexture)) {
        if (defined(pbrSpecularGlossiness.specularGlossinessTexture)) {
          specularGlossiness.specularGlossinessTexture = loadTexture(
            loader,
            gltf,
            pbrSpecularGlossiness.specularGlossinessTexture,
            supportedImageFormats
          );
        }
      }
      specularGlossiness.diffuseFactor = fromArray(
        Cartesian4,
        pbrSpecularGlossiness.diffuseFactor
      );
      specularGlossiness.specularFactor = fromArray(
        Cartesian3,
        pbrSpecularGlossiness.specularFactor
      );
      specularGlossiness.glossinessFactor =
        pbrSpecularGlossiness.glossinessFactor;
      material.pbrSpecularGlossiness = pbrSpecularGlossiness;
    } else if (defined(pbrMetallicRoughness)) {
      const metallicRoughness = new MetallicRoughness$2();
      material.metallicRoughness = metallicRoughness;

      if (defined(pbrMetallicRoughness.baseColorTexture)) {
        metallicRoughness.baseColorTexture = loadTexture(
          loader,
          gltf,
          pbrMetallicRoughness.baseColorTexture,
          supportedImageFormats
        );
      }
      if (defined(pbrMetallicRoughness.metallicRoughnessTexture)) {
        metallicRoughness.metallicRoughnessTexture = loadTexture(
          loader,
          gltf,
          pbrMetallicRoughness.metallicRoughnessTexture,
          supportedImageFormats
        );
      }
      metallicRoughness.baseColorFactor = fromArray(
        Cartesian4,
        pbrMetallicRoughness.baseColorFactor
      );
      metallicRoughness.metallicFactor = pbrMetallicRoughness.metallicFactor;
      metallicRoughness.roughnessFactor = pbrMetallicRoughness.roughnessFactor;
      material.pbrMetallicRoughness = pbrMetallicRoughness;
    }

    // Top level textures
    if (defined(gltfMaterial.emissiveTexture)) {
      material.emissiveTexture = loadTexture(
        loader,
        gltf,
        gltfMaterial.emissiveTexture,
        supportedImageFormats
      );
    }
    if (defined(gltfMaterial.normalTexture)) {
      material.normalTexture = loadTexture(
        loader,
        gltf,
        gltfMaterial.normalTexture,
        supportedImageFormats
      );
    }
    if (defined(gltfMaterial.occlusionTexture)) {
      material.occlusionTexture = loadTexture(
        loader,
        gltf,
        gltfMaterial.occlusionTexture,
        supportedImageFormats
      );
    }
    material.emissiveFactor = fromArray(Cartesian3, gltfMaterial.emissiveFactor);
    material.alphaMode = gltfMaterial.alphaMode;
    material.alphaCutoff = gltfMaterial.alphaCutoff;
    material.doubleSided = gltfMaterial.doubleSided;

    return material;
  }

  // for EXT_mesh_features
  function loadFeatureIdAttribute(featureIds, positionalLabel) {
    const featureIdAttribute = new FeatureIdAttribute$3();
    featureIdAttribute.featureCount = featureIds.featureCount;
    featureIdAttribute.nullFeatureId = featureIds.nullFeatureId;
    featureIdAttribute.propertyTableId = featureIds.propertyTable;
    featureIdAttribute.setIndex = featureIds.attribute;
    featureIdAttribute.label = featureIds.label;
    featureIdAttribute.positionalLabel = positionalLabel;
    return featureIdAttribute;
  }

  // for backwards compatibility with EXT_feature_metadata
  function loadFeatureIdAttributeLegacy(
    gltfFeatureIdAttribute,
    featureTableId,
    featureCount,
    positionalLabel
  ) {
    const featureIdAttribute = new FeatureIdAttribute$3();
    const featureIds = gltfFeatureIdAttribute.featureIds;
    featureIdAttribute.featureCount = featureCount;
    featureIdAttribute.propertyTableId = featureTableId;
    featureIdAttribute.setIndex = getSetIndex(featureIds.attribute);
    featureIdAttribute.positionalLabel = positionalLabel;
    return featureIdAttribute;
  }

  // implicit ranges do not exist in EXT_mesh_features and EXT_instance_features,
  // but both default to the vertex/instance ID which is like
  // an implicit range of {offset: 0, repeat: 1}
  function loadDefaultFeatureIds(featureIds, positionalLabel) {
    const featureIdRange = new FeatureIdImplicitRange();
    featureIdRange.propertyTableId = featureIds.propertyTable;
    featureIdRange.featureCount = featureIds.featureCount;
    featureIdRange.nullFeatureId = featureIds.nullFeatureId;
    featureIdRange.label = featureIds.label;
    featureIdRange.positionalLabel = positionalLabel;
    featureIdRange.offset = 0;
    featureIdRange.repeat = 1;
    return featureIdRange;
  }

  // for backwards compatibility with EXT_feature_metadata
  function loadFeatureIdImplicitRangeLegacy(
    gltfFeatureIdAttribute,
    featureTableId,
    featureCount,
    positionalLabel
  ) {
    const featureIdRange = new FeatureIdImplicitRange();
    const featureIds = gltfFeatureIdAttribute.featureIds;
    featureIdRange.propertyTableId = featureTableId;
    featureIdRange.featureCount = featureCount;

    // constant/divisor was renamed to offset/repeat
    featureIdRange.offset = defaultValue(featureIds.constant, 0);
    // The default is now undefined
    const divisor = defaultValue(featureIds.divisor, 0);
    featureIdRange.repeat = divisor === 0 ? undefined : divisor;

    featureIdRange.positionalLabel = positionalLabel;
    return featureIdRange;
  }

  // for EXT_mesh_features
  function loadFeatureIdTexture(
    loader,
    gltf,
    gltfFeatureIdTexture,
    supportedImageFormats,
    positionalLabel
  ) {
    const featureIdTexture = new FeatureIdTexture();

    featureIdTexture.featureCount = gltfFeatureIdTexture.featureCount;
    featureIdTexture.nullFeatureId = gltfFeatureIdTexture.nullFeatureId;
    featureIdTexture.propertyTableId = gltfFeatureIdTexture.propertyTable;
    featureIdTexture.label = gltfFeatureIdTexture.label;
    featureIdTexture.positionalLabel = positionalLabel;

    const textureInfo = gltfFeatureIdTexture.texture;
    featureIdTexture.textureReader = loadTexture(
      loader,
      gltf,
      textureInfo,
      supportedImageFormats,
      Sampler.NEAREST // Feature ID textures require nearest sampling
    );

    // Though the new channel index is more future-proof, this implementation
    // only supports RGBA textures. At least for now, the string representation
    // is more useful for generating shader code.
    const channelString = textureInfo.channels
      .map(function (channelIndex) {
        return "rgba".charAt(channelIndex);
      })
      .join("");
    featureIdTexture.textureReader.channels = channelString;

    return featureIdTexture;
  }

  // for backwards compatibility with EXT_feature_metadata
  function loadFeatureIdTextureLegacy(
    loader,
    gltf,
    gltfFeatureIdTexture,
    featureTableId,
    supportedImageFormats,
    featureCount,
    positionalLabel
  ) {
    const featureIdTexture = new FeatureIdTexture();
    const featureIds = gltfFeatureIdTexture.featureIds;
    const textureInfo = featureIds.texture;
    featureIdTexture.featureCount = featureCount;
    featureIdTexture.propertyTableId = featureTableId;
    featureIdTexture.textureReader = loadTexture(
      loader,
      gltf,
      textureInfo,
      supportedImageFormats,
      Sampler.NEAREST // Feature ID textures require nearest sampling
    );

    featureIdTexture.textureReader.channels = featureIds.channels;
    featureIdTexture.positionalLabel = positionalLabel;

    return featureIdTexture;
  }

  function loadMorphTarget(loader, gltf, target) {
    const morphTarget = new MorphTarget();

    for (const semantic in target) {
      if (target.hasOwnProperty(semantic)) {
        const accessorId = target[semantic];
        morphTarget.attributes.push(
          // Don't pass in draco object since morph targets can't be draco compressed
          loadVertexAttribute(loader, gltf, accessorId, semantic, undefined)
        );
      }
    }

    return morphTarget;
  }

  function loadPrimitive(
    loader,
    gltf,
    gltfPrimitive,
    hasInstances,
    supportedImageFormats,
    frameState
  ) {
    const primitive = new Primitive$1();

    const materialId = gltfPrimitive.material;
    if (defined(materialId)) {
      primitive.material = loadMaterial(
        loader,
        gltf,
        gltf.materials[materialId],
        supportedImageFormats
      );
    }

    const extensions = defaultValue(
      gltfPrimitive.extensions,
      defaultValue.EMPTY_OBJECT
    );
    const draco = extensions.KHR_draco_mesh_compression;

    const attributes = gltfPrimitive.attributes;
    if (defined(attributes)) {
      for (const semantic in attributes) {
        if (attributes.hasOwnProperty(semantic)) {
          const accessorId = attributes[semantic];
          primitive.attributes.push(
            loadVertexAttribute(
              loader,
              gltf,
              accessorId,
              semantic,
              draco,
              hasInstances,
              frameState
            )
          );
        }
      }
    }

    const targets = gltfPrimitive.targets;
    if (defined(targets)) {
      const targetsLength = targets.length;
      for (let i = 0; i < targetsLength; ++i) {
        primitive.morphTargets.push(loadMorphTarget(loader, gltf, targets[i]));
      }
    }

    const indices = gltfPrimitive.indices;
    if (defined(indices)) {
      primitive.indices = loadIndices(loader, gltf, indices, draco, frameState);
    }

    // With the latest revision, feature IDs are defined in EXT_mesh_features
    // while EXT_structural_metadata is for defining property textures and
    // property mappings. In the legacy EXT_feature_metadata, these concepts
    // were all in one extension.
    const structuralMetadata = extensions.EXT_structural_metadata;
    const meshFeatures = extensions.EXT_mesh_features;
    const featureMetadataLegacy = extensions.EXT_feature_metadata;
    const hasFeatureMetadataLegacy = defined(featureMetadataLegacy);

    // Load feature Ids
    if (defined(meshFeatures)) {
      loadPrimitiveFeatures(
        loader,
        gltf,
        primitive,
        meshFeatures,
        supportedImageFormats
      );
    } else if (hasFeatureMetadataLegacy) {
      loadPrimitiveFeaturesLegacy(
        loader,
        gltf,
        primitive,
        featureMetadataLegacy,
        supportedImageFormats
      );
    }

    // Load structural metadata
    if (defined(structuralMetadata)) {
      loadPrimitiveMetadata(primitive, structuralMetadata);
    } else if (hasFeatureMetadataLegacy) {
      loadPrimitiveMetadataLegacy(loader, primitive, featureMetadataLegacy);
    }

    primitive.primitiveType = gltfPrimitive.mode;

    return primitive;
  }

  // For EXT_mesh_features
  function loadPrimitiveFeatures(
    loader,
    gltf,
    primitive,
    meshFeaturesExtension,
    supportedImageFormats
  ) {
    let featureIdsArray;
    if (
      defined(meshFeaturesExtension) &&
      defined(meshFeaturesExtension.featureIds)
    ) {
      featureIdsArray = meshFeaturesExtension.featureIds;
    } else {
      featureIdsArray = [];
    }

    for (let i = 0; i < featureIdsArray.length; i++) {
      const featureIds = featureIdsArray[i];
      const label = `featureId_${i}`;

      let featureIdComponent;
      if (defined(featureIds.texture)) {
        featureIdComponent = loadFeatureIdTexture(
          loader,
          gltf,
          featureIds,
          supportedImageFormats,
          label
        );
      } else if (defined(featureIds.attribute)) {
        featureIdComponent = loadFeatureIdAttribute(featureIds, label);
      } else {
        // default to vertex ID, in other words an implicit range with
        // offset: 0, repeat: 1
        featureIdComponent = loadDefaultFeatureIds(featureIds, label);
      }

      primitive.featureIds.push(featureIdComponent);
    }
  }

  // For EXT_feature_metadata
  function loadPrimitiveFeaturesLegacy(
    loader,
    gltf,
    primitive,
    metadataExtension,
    supportedImageFormats
  ) {
    // For looking up the featureCount for each set of feature IDs
    const featureTables = gltf.extensions.EXT_feature_metadata.featureTables;

    let nextFeatureIdIndex = 0;

    // Feature ID Attributes
    const featureIdAttributes = metadataExtension.featureIdAttributes;
    if (defined(featureIdAttributes)) {
      const featureIdAttributesLength = featureIdAttributes.length;
      for (let i = 0; i < featureIdAttributesLength; ++i) {
        const featureIdAttribute = featureIdAttributes[i];
        const featureTableId = featureIdAttribute.featureTable;
        const propertyTableId = loader._sortedPropertyTableIds.indexOf(
          featureTableId
        );
        const featureCount = featureTables[featureTableId].count;
        const label = `featureId_${nextFeatureIdIndex}`;
        nextFeatureIdIndex++;

        let featureIdComponent;
        if (defined(featureIdAttribute.featureIds.attribute)) {
          featureIdComponent = loadFeatureIdAttributeLegacy(
            featureIdAttribute,
            propertyTableId,
            featureCount,
            label
          );
        } else {
          featureIdComponent = loadFeatureIdImplicitRangeLegacy(
            featureIdAttribute,
            propertyTableId,
            featureCount,
            label
          );
        }
        primitive.featureIds.push(featureIdComponent);
      }
    }

    // Feature ID Textures
    const featureIdTextures = metadataExtension.featureIdTextures;
    if (defined(featureIdTextures)) {
      const featureIdTexturesLength = featureIdTextures.length;
      for (let i = 0; i < featureIdTexturesLength; ++i) {
        const featureIdTexture = featureIdTextures[i];
        const featureTableId = featureIdTexture.featureTable;
        const propertyTableId = loader._sortedPropertyTableIds.indexOf(
          featureTableId
        );
        const featureCount = featureTables[featureTableId].count;
        const featureIdLabel = `featureId_${nextFeatureIdIndex}`;
        nextFeatureIdIndex++;

        const featureIdComponent = loadFeatureIdTextureLegacy(
          loader,
          gltf,
          featureIdTexture,
          propertyTableId,
          supportedImageFormats,
          featureCount,
          featureIdLabel
        );
        // Feature ID textures are added after feature ID attributes in the list
        primitive.featureIds.push(featureIdComponent);
      }
    }
  }

  // For primitive-level EXT_structural_metadata
  function loadPrimitiveMetadata(primitive, structuralMetadataExtension) {
    if (!defined(structuralMetadataExtension)) {
      return;
    }

    // Property Textures
    if (defined(structuralMetadataExtension.propertyTextures)) {
      primitive.propertyTextureIds = structuralMetadataExtension.propertyTextures;
    }

    // Property Attributes
    if (defined(structuralMetadataExtension.propertyAttributes)) {
      primitive.propertyAttributeIds =
        structuralMetadataExtension.propertyAttributes;
    }
  }

  // For EXT_feature_metadata
  function loadPrimitiveMetadataLegacy(loader, primitive, metadataExtension) {
    // Feature Textures
    if (defined(metadataExtension.featureTextures)) {
      // feature textures are now identified by an integer index. To convert the
      // string IDs to integers, find their place in the sorted list of feature
      // table names
      primitive.propertyTextureIds = metadataExtension.featureTextures.map(
        function (id) {
          return loader._sortedFeatureTextureIds.indexOf(id);
        }
      );
    }
  }

  function loadInstances(loader, gltf, nodeExtensions, frameState) {
    const instancingExtension = nodeExtensions.EXT_mesh_gpu_instancing;

    const instances = new Instances$1();
    const attributes = instancingExtension.attributes;
    if (defined(attributes)) {
      const hasRotation = defined(attributes.ROTATION);
      const hasTranslationMinMax =
        defined(attributes.TRANSLATION) &&
        defined(gltf.accessors[attributes.TRANSLATION].min) &&
        defined(gltf.accessors[attributes.TRANSLATION].max);
      for (const semantic in attributes) {
        if (attributes.hasOwnProperty(semantic)) {
          // In addition to the loader options, load the attributes as typed arrays if:
          // - the instances have rotations, so that instance matrices are computed on the CPU.
          //   This avoids the expensive quaternion -> rotation matrix conversion in the shader.
          // - the translation accessor does not have a min and max, so the values can be used
          //   for computing an accurate bounding volume.
          // - the attributes contain feature IDs, in order to add the instance's feature ID
          //   to the pick object.
          // - GPU instancing is not supported.
          const isTransformAttribute =
            semantic === InstanceAttributeSemantic$1.TRANSLATION ||
            semantic === InstanceAttributeSemantic$1.ROTATION ||
            semantic === InstanceAttributeSemantic$1.SCALE;
          const loadAsTypedArrayPacked =
            loader._loadAttributesAsTypedArray ||
            ((hasRotation || !hasTranslationMinMax) && isTransformAttribute) ||
            semantic.indexOf(InstanceAttributeSemantic$1.FEATURE_ID) >= 0 ||
            !frameState.context.instancedArrays;

          const accessorId = attributes[semantic];
          instances.attributes.push(
            loadInstancedAttribute(
              loader,
              gltf,
              accessorId,
              semantic,
              loadAsTypedArrayPacked,
              frameState
            )
          );
        }
      }
    }

    const instancingExtExtensions = defaultValue(
      instancingExtension.extensions,
      defaultValue.EMPTY_OBJECT
    );
    const instanceFeatures = nodeExtensions.EXT_instance_features;
    const featureMetadataLegacy = instancingExtExtensions.EXT_feature_metadata;

    if (defined(instanceFeatures)) {
      loadInstanceFeatures(instances, instanceFeatures);
    } else if (defined(featureMetadataLegacy)) {
      loadInstanceFeaturesLegacy(
        gltf,
        instances,
        featureMetadataLegacy,
        loader._sortedPropertyTableIds
      );
    }

    return instances;
  }

  // For EXT_mesh_features
  function loadInstanceFeatures(instances, instanceFeaturesExtension) {
    // feature IDs are required in EXT_instance_features
    const featureIdsArray = instanceFeaturesExtension.featureIds;

    for (let i = 0; i < featureIdsArray.length; i++) {
      const featureIds = featureIdsArray[i];
      const label = `instanceFeatureId_${i}`;

      let featureIdComponent;
      if (defined(featureIds.attribute)) {
        featureIdComponent = loadFeatureIdAttribute(featureIds, label);
      } else {
        // in EXT_instance_features, the default is to assign IDs by instance
        // ID. This can be expressed with offset: 0, repeat: 1
        featureIdComponent = loadDefaultFeatureIds(featureIds, label);
      }

      instances.featureIds.push(featureIdComponent);
    }
  }

  // For backwards-compatibility with EXT_feature_metadata
  function loadInstanceFeaturesLegacy(
    gltf,
    instances,
    metadataExtension,
    sortedPropertyTableIds
  ) {
    // For looking up the featureCount for each set of feature IDs
    const featureTables = gltf.extensions.EXT_feature_metadata.featureTables;

    const featureIdAttributes = metadataExtension.featureIdAttributes;
    if (defined(featureIdAttributes)) {
      const featureIdAttributesLength = featureIdAttributes.length;
      for (let i = 0; i < featureIdAttributesLength; ++i) {
        const featureIdAttribute = featureIdAttributes[i];
        const featureTableId = featureIdAttribute.featureTable;
        const propertyTableId = sortedPropertyTableIds.indexOf(featureTableId);
        const featureCount = featureTables[featureTableId].count;
        const label = `instanceFeatureId_${i}`;

        let featureIdComponent;
        if (defined(featureIdAttribute.featureIds.attribute)) {
          featureIdComponent = loadFeatureIdAttributeLegacy(
            featureIdAttribute,
            propertyTableId,
            featureCount,
            label
          );
        } else {
          featureIdComponent = loadFeatureIdImplicitRangeLegacy(
            featureIdAttribute,
            propertyTableId,
            featureCount,
            label
          );
        }
        instances.featureIds.push(featureIdComponent);
      }
    }
  }

  function loadNode(loader, gltf, gltfNode, supportedImageFormats, frameState) {
    const node = new Node$2();

    node.name = gltfNode.name;

    node.matrix = fromArray(Matrix4, gltfNode.matrix);
    node.translation = fromArray(Cartesian3, gltfNode.translation);
    node.rotation = fromArray(Quaternion, gltfNode.rotation);
    node.scale = fromArray(Cartesian3, gltfNode.scale);

    const nodeExtensions = defaultValue(
      gltfNode.extensions,
      defaultValue.EMPTY_OBJECT
    );
    const instancingExtension = nodeExtensions.EXT_mesh_gpu_instancing;
    const articulationsExtension = nodeExtensions.AGI_articulations;

    if (defined(instancingExtension)) {
      node.instances = loadInstances(loader, gltf, nodeExtensions, frameState);
    }

    if (defined(articulationsExtension)) {
      node.articulationName = articulationsExtension.articulationName;
    }

    const meshId = gltfNode.mesh;
    if (defined(meshId)) {
      const mesh = gltf.meshes[meshId];
      const primitives = mesh.primitives;
      const primitivesLength = primitives.length;
      for (let i = 0; i < primitivesLength; ++i) {
        node.primitives.push(
          loadPrimitive(
            loader,
            gltf,
            primitives[i],
            defined(node.instances),
            supportedImageFormats,
            frameState
          )
        );
      }

      // If the node has no weights array, it will look for the weights array provided
      // by the mesh. If both are undefined, it will default to an array of zero weights.
      const morphWeights = defaultValue(gltfNode.weights, mesh.weights);
      const targets = node.primitives[0].morphTargets;
      const targetsLength = targets.length;

      // Since meshes are not stored as separate components, the mesh weights will still
      // be stored at the node level.
      node.morphWeights = defined(morphWeights)
        ? morphWeights.slice()
        : new Array(targetsLength).fill(0.0);
    }

    return node;
  }

  function loadNodes(loader, gltf, supportedImageFormats, frameState) {
    let i;
    let j;

    const nodesLength = gltf.nodes.length;
    const nodes = new Array(nodesLength);
    for (i = 0; i < nodesLength; ++i) {
      const node = loadNode(
        loader,
        gltf,
        gltf.nodes[i],
        supportedImageFormats,
        frameState
      );
      node.index = i;
      nodes[i] = node;
    }

    for (i = 0; i < nodesLength; ++i) {
      const childrenNodeIds = gltf.nodes[i].children;
      if (defined(childrenNodeIds)) {
        const childrenLength = childrenNodeIds.length;
        for (j = 0; j < childrenLength; ++j) {
          nodes[i].children.push(nodes[childrenNodeIds[j]]);
        }
      }
    }

    return nodes;
  }

  function loadSkin(loader, gltf, gltfSkin, nodes) {
    const skin = new Skin();

    const jointIds = gltfSkin.joints;
    const jointsLength = jointIds.length;
    const joints = new Array(jointsLength);
    for (let i = 0; i < jointsLength; ++i) {
      joints[i] = nodes[jointIds[i]];
    }
    skin.joints = joints;

    const inverseBindMatricesAccessorId = gltfSkin.inverseBindMatrices;
    if (defined(inverseBindMatricesAccessorId)) {
      skin.inverseBindMatrices = loadAccessor(
        loader,
        gltf,
        inverseBindMatricesAccessorId
      );
    } else {
      skin.inverseBindMatrices = new Array(jointsLength).fill(Matrix4.IDENTITY);
    }

    return skin;
  }

  function loadSkins(loader, gltf, nodes) {
    let i;

    const gltfSkins = gltf.skins;
    if (!defined(gltfSkins)) {
      return [];
    }

    const skinsLength = gltf.skins.length;
    const skins = new Array(skinsLength);
    for (i = 0; i < skinsLength; ++i) {
      const skin = loadSkin(loader, gltf, gltf.skins[i], nodes);
      skin.index = i;
      skins[i] = skin;
    }

    const nodesLength = nodes.length;
    for (i = 0; i < nodesLength; ++i) {
      const skinId = gltf.nodes[i].skin;
      if (defined(skinId)) {
        nodes[i].skin = skins[skinId];
      }
    }

    return skins;
  }

  function loadStructuralMetadata(
    loader,
    gltf,
    extension,
    extensionLegacy,
    supportedImageFormats
  ) {
    const structuralMetadataLoader = new GltfStructuralMetadataLoader({
      gltf: gltf,
      extension: extension,
      extensionLegacy: extensionLegacy,
      gltfResource: loader._gltfResource,
      baseResource: loader._baseResource,
      supportedImageFormats: supportedImageFormats,
      asynchronous: loader._asynchronous,
    });
    structuralMetadataLoader.load();

    loader._structuralMetadataLoader = structuralMetadataLoader;

    return structuralMetadataLoader;
  }

  function loadAnimationSampler(loader, gltf, gltfSampler) {
    const animationSampler = new AnimationSampler();

    const inputAccessorId = gltfSampler.input;
    animationSampler.input = loadAccessor(loader, gltf, inputAccessorId);

    const gltfInterpolation = gltfSampler.interpolation;
    animationSampler.interpolation = defaultValue(
      InterpolationType$1[gltfInterpolation],
      InterpolationType$1.LINEAR
    );

    const outputAccessorId = gltfSampler.output;
    animationSampler.output = loadAccessor(loader, gltf, outputAccessorId, true);

    return animationSampler;
  }

  function loadAnimationTarget(gltfTarget, nodes) {
    const animationTarget = new AnimationTarget();

    const nodeIndex = gltfTarget.node;
    // If the node isn't defined, the animation channel should be ignored.
    // It's easiest to signal this by returning undefined.
    if (!defined(nodeIndex)) {
      return undefined;
    }

    animationTarget.node = nodes[nodeIndex];

    const path = gltfTarget.path.toUpperCase();
    animationTarget.path = AnimatedPropertyType$1[path];

    return animationTarget;
  }

  function loadAnimationChannel(gltfChannel, samplers, nodes) {
    const animationChannel = new AnimationChannel();

    const samplerIndex = gltfChannel.sampler;
    animationChannel.sampler = samplers[samplerIndex];
    animationChannel.target = loadAnimationTarget(gltfChannel.target, nodes);

    return animationChannel;
  }

  function loadAnimation(loader, gltf, gltfAnimation, nodes) {
    let i;

    const animation = new Animation$1();
    animation.name = gltfAnimation.name;

    const gltfSamplers = gltfAnimation.samplers;
    const samplersLength = gltfSamplers.length;

    const samplers = new Array(samplersLength);
    for (i = 0; i < samplersLength; i++) {
      const sampler = loadAnimationSampler(loader, gltf, gltfSamplers[i]);
      sampler.index = i;
      samplers[i] = sampler;
    }

    const gltfChannels = gltfAnimation.channels;
    const channelsLength = gltfChannels.length;

    const channels = new Array(channelsLength);
    for (i = 0; i < channelsLength; i++) {
      channels[i] = loadAnimationChannel(gltfChannels[i], samplers, nodes);
    }

    animation.samplers = samplers;
    animation.channels = channels;

    return animation;
  }

  function loadAnimations(loader, gltf, nodes) {
    let i;

    const gltfAnimations = gltf.animations;
    if (!defined(gltfAnimations)) {
      return [];
    }

    const animationsLength = gltf.animations.length;
    const animations = new Array(animationsLength);
    for (i = 0; i < animationsLength; ++i) {
      const animation = loadAnimation(loader, gltf, gltf.animations[i], nodes);
      animation.index = i;
      animations[i] = animation;
    }

    return animations;
  }

  function loadArticulationStage(gltfStage) {
    const stage = new ArticulationStage();
    stage.name = gltfStage.name;

    const type = gltfStage.type.toUpperCase();
    stage.type = ArticulationStageType$1[type];

    stage.minimumValue = gltfStage.minimumValue;
    stage.maximumValue = gltfStage.maximumValue;
    stage.initialValue = gltfStage.initialValue;

    return stage;
  }

  function loadArticulation(gltfArticulation) {
    const articulation = new Articulation();
    articulation.name = gltfArticulation.name;

    const gltfStages = gltfArticulation.stages;
    const gltfStagesLength = gltfStages.length;

    const stages = new Array(gltfStagesLength);
    for (let i = 0; i < gltfStagesLength; i++) {
      const stage = loadArticulationStage(gltfStages[i]);
      stages[i] = stage;
    }

    articulation.stages = stages;

    return articulation;
  }

  function loadArticulations(gltf) {
    const extensions = defaultValue(gltf.extensions, defaultValue.EMPTY_OBJECT);
    const articulationsExtension = extensions.AGI_articulations;

    if (!defined(articulationsExtension)) {
      return [];
    }

    const gltfArticulations = articulationsExtension.articulations;
    if (!defined(gltfArticulations)) {
      return [];
    }

    const gltfArticulationsLength = gltfArticulations.length;
    const articulations = new Array(gltfArticulationsLength);
    for (let i = 0; i < gltfArticulationsLength; i++) {
      const articulation = loadArticulation(gltfArticulations[i]);
      articulations[i] = articulation;
    }

    return articulations;
  }

  function getSceneNodeIds(gltf) {
    let nodesIds;
    if (defined(gltf.scenes) && defined(gltf.scene)) {
      nodesIds = gltf.scenes[gltf.scene].nodes;
    }
    nodesIds = defaultValue(nodesIds, gltf.nodes);
    nodesIds = defined(nodesIds) ? nodesIds : [];
    return nodesIds;
  }

  function loadScene(gltf, nodes) {
    const scene = new Scene$2();
    const sceneNodeIds = getSceneNodeIds(gltf);
    scene.nodes = sceneNodeIds.map(function (sceneNodeId) {
      return nodes[sceneNodeId];
    });
    return scene;
  }

  function parse$1(
    loader,
    gltf,
    supportedImageFormats,
    frameState,
    rejectPromise,
    rejectTexturesPromise
  ) {
    const extensions = defaultValue(gltf.extensions, defaultValue.EMPTY_OBJECT);
    const structuralMetadataExtension = extensions.EXT_structural_metadata;
    const featureMetadataExtensionLegacy = extensions.EXT_feature_metadata;

    if (defined(featureMetadataExtensionLegacy)) {
      // If the old EXT_feature_metadata extension is present, sort the IDs of the
      // feature tables and feature textures so we don't have to do this once
      // per primitive.
      //
      // This must run before loadNodes so these IDs are available when
      // attributes are processed.
      const featureTables = featureMetadataExtensionLegacy.featureTables;
      const featureTextures = featureMetadataExtensionLegacy.featureTextures;
      const allPropertyTableIds = defined(featureTables) ? featureTables : [];
      const allFeatureTextureIds = defined(featureTextures)
        ? featureTextures
        : [];
      loader._sortedPropertyTableIds = Object.keys(allPropertyTableIds).sort();
      loader._sortedFeatureTextureIds = Object.keys(allFeatureTextureIds).sort();
    }

    const nodes = loadNodes(loader, gltf, supportedImageFormats, frameState);
    const skins = loadSkins(loader, gltf, nodes);
    const animations = loadAnimations(loader, gltf, nodes);
    const articulations = loadArticulations(gltf);
    const scene = loadScene(gltf, nodes);

    const components = new Components$1();
    const asset = new Asset();
    const copyright = gltf.asset.copyright;
    if (defined(copyright)) {
      const credits = copyright.split(";").map(function (string) {
        return new Credit(string.trim());
      });
      asset.credits = credits;
    }

    components.asset = asset;
    components.scene = scene;
    components.nodes = nodes;
    components.skins = skins;
    components.animations = animations;
    components.articulations = articulations;
    components.upAxis = loader._upAxis;
    components.forwardAxis = loader._forwardAxis;

    loader._components = components;

    // Load structural metadata (property tables and property textures)
    if (
      defined(structuralMetadataExtension) ||
      defined(featureMetadataExtensionLegacy)
    ) {
      const structuralMetadataLoader = loadStructuralMetadata(
        loader,
        gltf,
        structuralMetadataExtension,
        featureMetadataExtensionLegacy,
        supportedImageFormats
      );
      const promise = structuralMetadataLoader.promise.then(function (
        structuralMetadataLoader
      ) {
        if (loader.isDestroyed()) {
          return;
        }
        components.structuralMetadata =
          structuralMetadataLoader.structuralMetadata;
      });
      loader._loaderPromises.push(promise);
    }

    // Gather promises and reject if any promises fail.
    const readyPromises = [];
    readyPromises.push.apply(readyPromises, loader._loaderPromises);

    if (!loader._incrementallyLoadTextures) {
      readyPromises.push.apply(readyPromises, loader._texturesPromises);
    }

    Promise.all(readyPromises)
      .then(function () {
        if (loader.isDestroyed()) {
          return;
        }
        loader._state = GltfLoaderState.PROCESSED;
      })
      .catch(rejectPromise);

    // Separate promise will resolve once textures are loaded.
    Promise.all(loader._texturesPromises)
      .then(function () {
        if (loader.isDestroyed()) {
          return;
        }
        loader._textureState = GltfLoaderState.PROCESSED;
      })
      .catch(rejectTexturesPromise);
  }

  function unloadTextures(loader) {
    const textureLoaders = loader._textureLoaders;
    const textureLoadersLength = textureLoaders.length;
    for (let i = 0; i < textureLoadersLength; ++i) {
      ResourceCache.unload(textureLoaders[i]);
    }
    loader._textureLoaders.length = 0;
  }

  function unloadBufferViews(loader) {
    const bufferViewLoaders = loader._bufferViewLoaders;
    const bufferViewLoadersLength = bufferViewLoaders.length;
    for (let i = 0; i < bufferViewLoadersLength; ++i) {
      ResourceCache.unload(bufferViewLoaders[i]);
    }
    loader._bufferViewLoaders.length = 0;
  }

  function unloadGeometry(loader) {
    const geometryLoaders = loader._geometryLoaders;
    const geometryLoadersLength = geometryLoaders.length;
    for (let i = 0; i < geometryLoadersLength; ++i) {
      ResourceCache.unload(geometryLoaders[i]);
    }
    loader._geometryLoaders.length = 0;
  }

  function unloadStructuralMetadata(loader) {
    if (defined(loader._structuralMetadataLoader)) {
      loader._structuralMetadataLoader.destroy();
      loader._structuralMetadataLoader = undefined;
    }
  }

  /**
   * Unloads the resource.
   * @private
   */
  GltfLoader.prototype.unload = function () {
    if (defined(this._gltfJsonLoader)) {
      ResourceCache.unload(this._gltfJsonLoader);
    }
    this._gltfJsonLoader = undefined;

    unloadTextures(this);
    unloadBufferViews(this);
    unloadGeometry(this);
    unloadStructuralMetadata(this);

    this._components = undefined;
  };

  const AnimatedPropertyType = ModelComponents.AnimatedPropertyType;

  /**
   * A runtime animation channel for a {@link ModelExperimentalAnimation}. An animation
   * channel is responsible for interpolating between the keyframe values of an animated
   * property, then applying the change to the target node.
   *
   * @param {Object} options An object containing the following options:
   * @param {ModelComponents.AnimationChannel} options.channel The corresponding animation channel components from the 3D model.
   * @param {ModelExperimentalAnimation} options.runtimeAnimation The runtime animation containing this channel.
   * @param {ModelExperimentalNode} options.runtimeNode The runtime node that this channel will animate.
   *
   * @alias ModelExperimentalAnimationChannel
   * @constructor
   *
   * @private
   */
  function ModelExperimentalAnimationChannel(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const channel = options.channel;
    const runtimeAnimation = options.runtimeAnimation;
    const runtimeNode = options.runtimeNode;
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.channel", channel);
    Check.typeOf.object("options.runtimeAnimation", runtimeAnimation);
    Check.typeOf.object("options.runtimeNode", runtimeNode);
    //>>includeEnd('debug');

    this._channel = channel;
    this._runtimeAnimation = runtimeAnimation;
    this._runtimeNode = runtimeNode;

    // An animation channel can have multiple splines if it animates
    // a node's morph weights, which will involve multiple morph targets.
    this._splines = [];
    this._path = undefined;

    initialize$8(this);
  }

  Object.defineProperties(ModelExperimentalAnimationChannel.prototype, {
    /**
     * The glTF animation channel.
     *
     * @memberof ModelExperimentalAnimationChannel.prototype
     *
     * @type {ModelComponents.AnimationChannel}
     * @readonly
     *
     * @private
     */
    channel: {
      get: function () {
        return this._channel;
      },
    },

    /**
     * The runtime animation that owns this channel.
     *
     * @memberof ModelExperimentalAnimationChannel.prototype
     *
     * @type {ModelExperimentalAnimation}
     * @readonly
     *
     * @private
     */
    runtimeAnimation: {
      get: function () {
        return this._runtimeAnimation;
      },
    },

    /**
     * The runtime node that this channel animates.
     *
     * @memberof ModelExperimentalAnimationChannel.prototype
     *
     * @type {ModelExperimentalNode}
     * @readonly
     *
     * @private
     */
    runtimeNode: {
      get: function () {
        return this._runtimeNode;
      },
    },

    /**
     * The splines used to evaluate this animation channel.
     *
     * @memberof ModelExperimentalAnimationChannel.prototype
     *
     * @type {Spline[]}
     * @readonly
     *
     * @private
     */
    splines: {
      get: function () {
        return this._splines;
      },
    },
  });

  function createCubicSpline(times, points) {
    const cubicPoints = [];
    const inTangents = [];
    const outTangents = [];

    const length = points.length;
    for (let i = 0; i < length; i += 3) {
      inTangents.push(points[i]);
      cubicPoints.push(points[i + 1]);
      outTangents.push(points[i + 2]);
    }

    // Remove the first in-tangent and last out-tangent, since they
    // are not used in the spline calculations
    inTangents.splice(0, 1);
    outTangents.length = outTangents.length - 1;

    return new HermiteSpline({
      times: times,
      points: cubicPoints,
      inTangents: inTangents,
      outTangents: outTangents,
    });
  }

  function createSpline(times, points, interpolation, path) {
    if (times.length === 1 && points.length === 1) {
      return new ConstantSpline(points[0]);
    }

    switch (interpolation) {
      case InterpolationType$1.STEP:
        return new SteppedSpline$1({
          times: times,
          points: points,
        });
      case InterpolationType$1.CUBICSPLINE:
        return createCubicSpline(times, points);
      case InterpolationType$1.LINEAR:
        if (path === AnimatedPropertyType.ROTATION) {
          return new QuaternionSpline({
            times: times,
            points: points,
          });
        }
        return new LinearSpline({
          times: times,
          points: points,
        });
    }
  }

  function createSplines(times, points, interpolation, path, count) {
    const splines = [];
    if (path === AnimatedPropertyType.WEIGHTS) {
      const pointsLength = points.length;
      // Get the number of keyframes in each weight's output.
      const outputLength = pointsLength / count;

      // Iterate over the array using the number of morph targets in the model.
      let targetIndex, i;
      for (targetIndex = 0; targetIndex < count; targetIndex++) {
        const output = new Array(outputLength);

        // Weights are ordered such that they are keyframed in the order in which
        // their targets appear the glTF. For example, the weights of three targets
        // may appear as [w(0,0), w(0,1), w(0,2), w(1,0), w(1,1), w(1,2) ...],
        // where i and j in w(i,j) are the time indices and target indices, respectively.

        // However, for morph targets with cubic interpolation, the data is stored per
        // keyframe in the order [a1, a2, ..., an, v1, v2, ... vn, b1, b2, ..., bn],
        // where ai, vi, and bi are the in-tangent, property, and out-tangents of
        // the ith morph target respectively.
        let pointsIndex = targetIndex;
        if (interpolation === InterpolationType$1.CUBICSPLINE) {
          for (i = 0; i < outputLength; i += 3) {
            output[i] = points[pointsIndex];
            output[i + 1] = points[pointsIndex + count];
            output[i + 2] = points[pointsIndex + 2 * count];
            pointsIndex += count * 3;
          }
        } else {
          for (i = 0; i < outputLength; i++) {
            output[i] = points[pointsIndex];
            pointsIndex += count;
          }
        }

        splines.push(createSpline(times, output, interpolation, path));
      }
    } else {
      splines.push(createSpline(times, points, interpolation, path));
    }

    return splines;
  }

  let scratchVariable;

  function initialize$8(runtimeChannel) {
    const channel = runtimeChannel._channel;

    const sampler = channel.sampler;
    const times = sampler.input;
    const points = sampler.output;

    const interpolation = sampler.interpolation;
    const target = channel.target;
    const path = target.path;

    const runtimeNode = runtimeChannel._runtimeNode;
    const count = defined(runtimeNode.morphWeights)
      ? runtimeNode.morphWeights.length
      : 1;
    const splines = createSplines(times, points, interpolation, path, count);

    runtimeChannel._splines = splines;
    runtimeChannel._path = path;

    switch (path) {
      case AnimatedPropertyType.TRANSLATION:
      case AnimatedPropertyType.SCALE:
        scratchVariable = new Cartesian3();
        break;
      case AnimatedPropertyType.ROTATION:
        scratchVariable = new Quaternion();
        break;
      case AnimatedPropertyType.WEIGHTS:
        // This is unused when setting a node's morph weights.
        break;
    }
  }

  /**
   * Animates the target node property based on its spline.
   *
   * @param {Number} time The local animation time.
   *
   * @private
   */
  ModelExperimentalAnimationChannel.prototype.animate = function (time) {
    const splines = this._splines;
    const path = this._path;
    const model = this._runtimeAnimation.model;

    // Weights are handled differently than the other properties because
    // they need to be updated in place.
    if (path === AnimatedPropertyType.WEIGHTS) {
      const morphWeights = this._runtimeNode.morphWeights;
      const length = morphWeights.length;
      for (let i = 0; i < length; i++) {
        const spline = splines[i];
        const localAnimationTime = model.clampAnimations
          ? spline.clampTime(time)
          : spline.wrapTime(time);
        morphWeights[i] = spline.evaluate(localAnimationTime);
      }
    } else {
      const spline = splines[0];
      const localAnimationTime = model.clampAnimations
        ? spline.clampTime(time)
        : spline.wrapTime(time);

      // This sets the translate, rotate, and scale properties.
      this._runtimeNode[path] = spline.evaluate(
        localAnimationTime,
        scratchVariable
      );
    }
  };

  /**
   * An active animation derived from a glTF asset. An active animation is an
   * animation that is either currently playing or scheduled to be played due to
   * being added to a model's {@link ModelExperimentalAnimationCollection}. An active animation
   * is an instance of an animation; for example, there can be multiple active
   * animations for the same glTF animation, each with a different start time.
   * <p>
   * Create this by calling {@link ModelExperimentalAnimationCollection#add}.
   * </p>
   *
   * @alias ModelExperimentalAnimation
   * @internalConstructor
   * @class
   *
   * @see ModelExperimentalAnimationCollection#add
   */
  function ModelExperimentalAnimation(model, animation, options) {
    this._animation = animation;
    this._name = animation.name;
    this._runtimeChannels = undefined;

    this._startTime = JulianDate.clone(options.startTime);
    this._delay = defaultValue(options.delay, 0.0); // in seconds
    this._stopTime = JulianDate.clone(options.stopTime);

    /**
     * When <code>true</code>, the animation is removed after it stops playing.
     * This is slightly more efficient that not removing it, but if, for example,
     * time is reversed, the animation is not played again.
     *
     * @type {Boolean}
     * @default false
     */
    this.removeOnStop = defaultValue(options.removeOnStop, false);
    this._multiplier = defaultValue(options.multiplier, 1.0);
    this._reverse = defaultValue(options.reverse, false);
    this._loop = defaultValue(options.loop, ModelAnimationLoop$1.NONE);
    this._animationTime = options.animationTime;
    this._prevAnimationDelta = undefined;

    /**
     * The event fired when this animation is started.  This can be used, for
     * example, to play a sound or start a particle system, when the animation starts.
     * <p>
     * This event is fired at the end of the frame after the scene is rendered.
     * </p>
     *
     * @type {Event}
     * @default new Event()
     *
     * @example
     * animation.start.addEventListener(function(model, animation) {
     *   console.log(`Animation started: ${animation.name}`);
     * });
     */
    this.start = new Event();

    /**
     * The event fired when on each frame when this animation is updated.  The
     * current time of the animation, relative to the glTF animation time span, is
     * passed to the event, which allows, for example, starting new animations at a
     * specific time relative to a playing animation.
     * <p>
     * This event is fired at the end of the frame after the scene is rendered.
     * </p>
     *
     * @type {Event}
     * @default new Event()
     *
     * @example
     * animation.update.addEventListener(function(model, animation, time) {
     *   console.log(`Animation updated: ${animation.name}. glTF animation time: ${time}`);
     * });
     */
    this.update = new Event();

    /**
     * The event fired when this animation is stopped.  This can be used, for
     * example, to play a sound or start a particle system, when the animation stops.
     * <p>
     * This event is fired at the end of the frame after the scene is rendered.
     * </p>
     *
     * @type {Event}
     * @default new Event()
     *
     * @example
     * animation.stop.addEventListener(function(model, animation) {
     *   console.log(`Animation stopped: ${animation.name}`);
     * });
     */
    this.stop = new Event();

    this._state = ModelAnimationState.STOPPED;

    // Set during animation update
    this._computedStartTime = undefined;
    this._duration = undefined;

    // To avoid allocations in ModelExperimentalAnimationCollection.update
    const that = this;
    this._raiseStartEvent = function () {
      that.start.raiseEvent(model, that);
    };
    this._updateEventTime = 0.0;
    this._raiseUpdateEvent = function () {
      that.update.raiseEvent(model, that, that._updateEventTime);
    };
    this._raiseStopEvent = function () {
      that.stop.raiseEvent(model, that);
    };

    this._model = model;

    this._localStartTime = undefined;
    this._localStopTime = undefined;

    initialize$7(this);
  }

  Object.defineProperties(ModelExperimentalAnimation.prototype, {
    /**
     * The glTF animation.
     *
     * @memberof ModelExperimentalAnimation.prototype
     *
     * @type {ModelComponents.Animation}
     * @readonly
     *
     * @private
     */
    animation: {
      get: function () {
        return this._animation;
      },
    },

    /**
     * The name that identifies this animation in the model, if it exists.
     *
     * @memberof ModelExperimentalAnimation.prototype
     *
     * @type {String}
     * @readonly
     */
    name: {
      get: function () {
        return this._name;
      },
    },

    /**
     * The runtime animation channels for this animation.
     *
     * @memberof ModelExperimentalAnimation.prototype
     *
     * @type {ModelExperimentalAnimationChannel[]}
     * @readonly
     *
     * @private
     */
    runtimeChannels: {
      get: function () {
        return this._runtimeChannels;
      },
    },

    /**
     * The {@link ModelExperimental} that owns this animation.
     *
     * @memberof ModelExperimentalAnimation.prototype
     *
     * @type {ModelExperimental}
     * @readonly
     *
     * @private
     */
    model: {
      get: function () {
        return this._model;
      },
    },

    /**
     * The starting point of the animation in local animation time. This is the minimum
     * time value across all of the keyframes belonging to this animation.
     *
     * @memberof ModelExperimentalAnimation.prototype
     *
     * @type {Number}
     * @readonly
     *
     * @private
     */
    localStartTime: {
      get: function () {
        return this._localStartTime;
      },
    },

    /**
     * The stopping point of the animation in local animation time. This is the maximum
     * time value across all of the keyframes belonging to this animation.
     *
     * @memberof ModelExperimentalAnimation.prototype
     *
     * @type {Number}
     * @readonly
     *
     * @private
     */
    localStopTime: {
      get: function () {
        return this._localStopTime;
      },
    },

    /**
     * The scene time to start playing this animation. When this is <code>undefined</code>,
     * the animation starts at the next frame.
     *
     * @memberof ModelExperimentalAnimation.prototype
     *
     * @type {JulianDate}
     * @readonly
     *
     * @default undefined
     */
    startTime: {
      get: function () {
        return this._startTime;
      },
    },

    /**
     * The delay, in seconds, from {@link ModelExperimentalAnimation#startTime} to start playing.
     *
     * @memberof ModelExperimentalAnimation.prototype
     *
     * @type {Number}
     * @readonly
     *
     * @default undefined
     */
    delay: {
      get: function () {
        return this._delay;
      },
    },

    /**
     * The scene time to stop playing this animation. When this is <code>undefined</code>,
     * the animation is played for its full duration and perhaps repeated depending on
     * {@link ModelExperimentalAnimation#loop}.
     *
     * @memberof ModelExperimentalAnimation.prototype
     *
     * @type {JulianDate}
     * @readonly
     *
     * @default undefined
     */
    stopTime: {
      get: function () {
        return this._stopTime;
      },
    },

    /**
     * Values greater than <code>1.0</code> increase the speed that the animation is played relative
     * to the scene clock speed; values less than <code>1.0</code> decrease the speed.  A value of
     * <code>1.0</code> plays the animation at the speed in the glTF animation mapped to the scene
     * clock speed.  For example, if the scene is played at 2x real-time, a two-second glTF animation
     * will play in one second even if <code>multiplier</code> is <code>1.0</code>.
     *
     * @memberof ModelExperimentalAnimation.prototype
     *
     * @type {Number}
     * @readonly
     *
     * @default 1.0
     */
    multiplier: {
      get: function () {
        return this._multiplier;
      },
    },

    /**
     * When <code>true</code>, the animation is played in reverse.
     *
     * @memberof ModelExperimentalAnimation.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default false
     */
    reverse: {
      get: function () {
        return this._reverse;
      },
    },

    /**
     * Determines if and how the animation is looped.
     *
     * @memberof ModelExperimentalAnimation.prototype
     *
     * @type {ModelAnimationLoop}
     * @readonly
     *
     * @default {@link ModelAnimationLoop.NONE}
     */
    loop: {
      get: function () {
        return this._loop;
      },
    },

    /**
     * If this is defined, it will be used to compute the local animation time
     * instead of the scene's time.
     *
     * @memberof ModelExperimentalAnimation.prototype
     *
     * @type {ModelExperimentalAnimation.AnimationTimeCallback}
     * @default undefined
     */
    animationTime: {
      get: function () {
        return this._animationTime;
      },
    },
  });

  function initialize$7(runtimeAnimation) {
    let localStartTime = Number.MAX_VALUE;
    let localStopTime = -Number.MAX_VALUE;

    const sceneGraph = runtimeAnimation._model.sceneGraph;
    const animation = runtimeAnimation._animation;
    const channels = animation.channels;
    const length = channels.length;

    const runtimeChannels = [];
    for (let i = 0; i < length; i++) {
      const channel = channels[i];
      const target = channel.target;

      // Ignore this channel if the target is invalid, i.e. if the node
      // it references doesn't exist.
      if (!defined(target)) {
        continue;
      }

      const nodeIndex = target.node.index;
      const runtimeNode = sceneGraph._runtimeNodes[nodeIndex];

      const runtimeChannel = new ModelExperimentalAnimationChannel({
        channel: channel,
        runtimeAnimation: runtimeAnimation,
        runtimeNode: runtimeNode,
      });

      const times = channel.sampler.input;
      localStartTime = Math.min(localStartTime, times[0]);
      localStopTime = Math.max(localStopTime, times[times.length - 1]);

      runtimeChannels.push(runtimeChannel);
    }

    runtimeAnimation._runtimeChannels = runtimeChannels;
    runtimeAnimation._localStartTime = localStartTime;
    runtimeAnimation._localStopTime = localStopTime;
  }

  /**
   * Evaluate all animation channels to advance this animation.
   *
   * @param {Number} time The local animation time.
   *
   * @private
   */
  ModelExperimentalAnimation.prototype.animate = function (time) {
    const runtimeChannels = this._runtimeChannels;
    const length = runtimeChannels.length;
    for (let i = 0; i < length; i++) {
      runtimeChannels[i].animate(time);
    }
  };

  /**
   * A collection of active model animations. Access this using {@link ModelExperimental#activeAnimations}.
   *
   * @alias ModelExperimentalAnimationCollection
   * @internalConstructor
   * @class
   *
   * @see ModelExperimental#activeAnimations
   */
  function ModelExperimentalAnimationCollection(model) {
    /**
     * The event fired when an animation is added to the collection.  This can be used, for
     * example, to keep a UI in sync.
     *
     * @type {Event}
     * @default new Event()
     *
     * @example
     * model.activeAnimations.animationAdded.addEventListener(function(model, animation) {
     *   console.log(`Animation added: ${animation.name}`);
     * });
     */
    this.animationAdded = new Event();

    /**
     * The event fired when an animation is removed from the collection.  This can be used, for
     * example, to keep a UI in sync.
     *
     * @type {Event}
     * @default new Event()
     *
     * @example
     * model.activeAnimations.animationRemoved.addEventListener(function(model, animation) {
     *   console.log(`Animation removed: ${animation.name}`);
     * });
     */
    this.animationRemoved = new Event();

    /**
     * When true, the animation will play even when the scene time is paused. However,
     * whether animation takes place will depend on the animationTime functions assigned
     * to the model's animations. By default, this is based on scene time, so models using
     * the default will not animate regardless of this setting.
     *
     * @type {Boolean}
     * @default false
     */
    this.animateWhilePaused = false;

    this._model = model;
    this._runtimeAnimations = [];
    this._previousTime = undefined;
  }

  Object.defineProperties(ModelExperimentalAnimationCollection.prototype, {
    /**
     * The number of animations in the collection.
     *
     * @memberof ModelExperimentalAnimationCollection.prototype
     *
     * @type {Number}
     * @readonly
     */
    length: {
      get: function () {
        return this._runtimeAnimations.length;
      },
    },

    /**
     * The model that owns this animation collection.
     *
     * @memberof ModelExperimentalAnimationCollection.prototype
     *
     * @type {ModelExperimental}
     * @readonly
     */
    model: {
      get: function () {
        return this._model;
      },
    },
  });

  function addAnimation(collection, animation, options) {
    const model = collection._model;
    const runtimeAnimation = new ModelExperimentalAnimation(
      model,
      animation,
      options
    );
    collection._runtimeAnimations.push(runtimeAnimation);
    collection.animationAdded.raiseEvent(model, runtimeAnimation);
    return runtimeAnimation;
  }

  /**
   * Creates and adds an animation with the specified initial properties to the collection.
   * <p>
   * This raises the {@link ModelExperimentalAnimationCollection#animationAdded} event so, for example, a UI can stay in sync.
   * </p>
   *
   * @param {Object} options Object with the following properties:
   * @param {String} [options.name] The glTF animation name that identifies the animation. Must be defined if <code>options.index</code> is <code>undefined</code>.
   * @param {Number} [options.index] The glTF animation index that identifies the animation. Must be defined if <code>options.name</code> is <code>undefined</code>.
   * @param {JulianDate} [options.startTime] The scene time to start playing the animation.  When this is <code>undefined</code>, the animation starts at the next frame.
   * @param {Number} [options.delay=0.0] The delay, in seconds, from <code>startTime</code> to start playing. This will only affect the animation if <code>options.loop</code> is ModelAnimationLoop.NONE.
   * @param {JulianDate} [options.stopTime] The scene time to stop playing the animation.  When this is <code>undefined</code>, the animation is played for its full duration.
   * @param {Boolean} [options.removeOnStop=false] When <code>true</code>, the animation is removed after it stops playing. This will only affect the animation if <code>options.loop</code> is ModelAnimationLoop.NONE.
   * @param {Number} [options.multiplier=1.0] Values greater than <code>1.0</code> increase the speed that the animation is played relative to the scene clock speed; values less than <code>1.0</code> decrease the speed.
   * @param {Boolean} [options.reverse=false] When <code>true</code>, the animation is played in reverse.
   * @param {ModelAnimationLoop} [options.loop=ModelAnimationLoop.NONE] Determines if and how the animation is looped.
   * @param {ModelExperimentalAnimation.AnimationTimeCallback} [options.animationTime=undefined] If defined, computes the local animation time for this animation.
   * @returns {ModelExperimentalAnimation} The animation that was added to the collection.
   *
   * @exception {DeveloperError} Animations are not loaded.  Wait for the {@link ModelExperimental#readyPromise} to resolve.
   * @exception {DeveloperError} options.name must be a valid animation name.
   * @exception {DeveloperError} options.index must be a valid animation index.
   * @exception {DeveloperError} Either options.name or options.index must be defined.
   * @exception {DeveloperError} options.multiplier must be greater than zero.
   *
   * @example
   * // Example 1. Add an animation by name
   * model.activeAnimations.add({
   *   name : 'animation name'
   * });
   *
   * @example
   * // Example 2. Add an animation by index
   * model.activeAnimations.add({
   *   index : 0
   * });
   *
   * @example
   * // Example 3. Add an animation and provide all properties and events
   * const startTime = Cesium.JulianDate.now();
   *
   * const animation = model.activeAnimations.add({
   *   name : 'another animation name',
   *   startTime : startTime,
   *   delay : 0.0,                                 // Play at startTime (default)
   *   stopTime : Cesium.JulianDate.addSeconds(startTime, 4.0, new Cesium.JulianDate()),
   *   removeOnStop : false,                        // Do not remove when animation stops (default)
   *   multiplier : 2.0,                            // Play at double speed
   *   reverse : true,                              // Play in reverse
   *   loop : Cesium.ModelAnimationLoop.REPEAT      // Loop the animation
   * });
   *
   * animation.start.addEventListener(function(model, animation) {
   *   console.log(`Animation started: ${animation.name}`);
   * });
   * animation.update.addEventListener(function(model, animation, time) {
   *   console.log(`Animation updated: ${animation.name}. glTF animation time: ${time}`);
   * });
   * animation.stop.addEventListener(function(model, animation) {
   *   console.log(`Animation stopped: ${animation.name}`);
   * });
   */
  ModelExperimentalAnimationCollection.prototype.add = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const model = this._model;

    //>>includeStart('debug', pragmas.debug);
    if (!model.ready) {
      throw new DeveloperError(
        "Animations are not loaded.  Wait for ModelExperimental.readyPromise to resolve."
      );
    }
    //>>includeEnd('debug');

    const animations = model.sceneGraph.components.animations;

    //>>includeStart('debug', pragmas.debug);
    if (!defined(options.name) && !defined(options.index)) {
      throw new DeveloperError(
        "Either options.name or options.index must be defined."
      );
    }

    if (defined(options.multiplier) && options.multiplier <= 0.0) {
      throw new DeveloperError("options.multiplier must be greater than zero.");
    }

    if (
      defined(options.index) &&
      (options.index >= animations.length || options.index < 0)
    ) {
      throw new DeveloperError("options.index must be a valid animation index.");
    }
    //>>includeEnd('debug');

    let index = options.index;
    if (defined(index)) {
      return addAnimation(this, animations[index], options);
    }

    // Find the index of the animation with the given name
    const length = animations.length;
    for (let i = 0; i < length; ++i) {
      if (animations[i].name === options.name) {
        index = i;
        break;
      }
    }

    //>>includeStart('debug', pragmas.debug);
    if (!defined(index)) {
      throw new DeveloperError("options.name must be a valid animation name.");
    }
    //>>includeEnd('debug');

    return addAnimation(this, animations[index], options);
  };

  /**
   * Creates and adds animations with the specified initial properties to the collection
   * for all animations in the model.
   * <p>
   * This raises the {@link ModelExperimentalAnimationCollection#animationAdded} event for each model so, for example, a UI can stay in sync.
   * </p>
   *
   * @param {Object} [options] Object with the following properties:
   * @param {JulianDate} [options.startTime] The scene time to start playing the animations. When this is <code>undefined</code>, the animations starts at the next frame.
   * @param {Number} [options.delay=0.0] The delay, in seconds, from <code>startTime</code> to start playing. This will only affect the animation if <code>options.loop</code> is ModelAnimationLoop.NONE.
   * @param {JulianDate} [options.stopTime] The scene time to stop playing the animations. When this is <code>undefined</code>, the animations are played for its full duration.
   * @param {Boolean} [options.removeOnStop=false] When <code>true</code>, the animations are removed after they stop playing. This will only affect the animation if <code>options.loop</code> is ModelAnimationLoop.NONE.
   * @param {Number} [options.multiplier=1.0] Values greater than <code>1.0</code> increase the speed that the animations play relative to the scene clock speed; values less than <code>1.0</code> decrease the speed.
   * @param {Boolean} [options.reverse=false] When <code>true</code>, the animations are played in reverse.
   * @param {ModelAnimationLoop} [options.loop=ModelAnimationLoop.NONE] Determines if and how the animations are looped.
   * @param {ModelExperimentalAnimation.AnimationTimeCallback} [options.animationTime=undefined] If defined, computes the local animation time for all of the animations.
   * @returns {ModelExperimentalAnimation[]} An array of {@link ModelExperimentalAnimation} objects, one for each animation added to the collection.  If there are no glTF animations, the array is empty.
   *
   * @exception {DeveloperError} Animations are not loaded. Wait for the {@link ModelExperimental#readyPromise} to resolve.
   * @exception {DeveloperError} options.multiplier must be greater than zero.
   *
   * @example
   * model.activeAnimations.addAll({
   *   multiplier : 0.5,                            // Play at half-speed
   *   loop : Cesium.ModelAnimationLoop.REPEAT      // Loop the animations
   * });
   */
  ModelExperimentalAnimationCollection.prototype.addAll = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const model = this._model;

    //>>includeStart('debug', pragmas.debug);
    if (!model.ready) {
      throw new DeveloperError(
        "Animations are not loaded.  Wait for Model.readyPromise to resolve."
      );
    }

    if (defined(options.multiplier) && options.multiplier <= 0.0) {
      throw new DeveloperError("options.multiplier must be greater than zero.");
    }
    //>>includeEnd('debug');

    const animations = model.sceneGraph.components.animations;

    const addedAnimations = [];
    const length = animations.length;
    for (let i = 0; i < length; ++i) {
      const animation = addAnimation(this, animations[i], options);
      addedAnimations.push(animation);
    }
    return addedAnimations;
  };

  /**
   * Removes an animation from the collection.
   * <p>
   * This raises the {@link ModelExperimentalAnimationCollection#animationRemoved} event so, for example, a UI can stay in sync.
   * </p>
   * <p>
   * An animation can also be implicitly removed from the collection by setting {@link ModelExperimentalAnimationCollection#removeOnStop} to
   * <code>true</code>.  The {@link ModelExperimentalAnimationCollection#animationRemoved} event is still fired when the animation is removed.
   * </p>
   *
   * @param {ModelExperimentalAnimation} runtimeAnimation The runtime animation to remove.
   * @returns {Boolean} <code>true</code> if the animation was removed; <code>false</code> if the animation was not found in the collection.
   *
   * @example
   * const a = model.activeAnimations.add({
   *   name : 'animation name'
   * });
   * model.activeAnimations.remove(a); // Returns true
   */
  ModelExperimentalAnimationCollection.prototype.remove = function (
    runtimeAnimation
  ) {
    if (!defined(runtimeAnimation)) {
      return false;
    }

    const animations = this._runtimeAnimations;
    const i = animations.indexOf(runtimeAnimation);
    if (i !== -1) {
      animations.splice(i, 1);
      this.animationRemoved.raiseEvent(this._model, runtimeAnimation);
      return true;
    }

    return false;
  };

  /**
   * Removes all animations from the collection.
   * <p>
   * This raises the {@link ModelExperimentalAnimationCollection#animationRemoved} event for each
   * animation so, for example, a UI can stay in sync.
   * </p>
   */
  ModelExperimentalAnimationCollection.prototype.removeAll = function () {
    const model = this._model;
    const animations = this._runtimeAnimations;
    const length = animations.length;

    this._runtimeAnimations.length = 0;

    for (let i = 0; i < length; ++i) {
      this.animationRemoved.raiseEvent(model, animations[i]);
    }
  };

  /**
   * Determines whether this collection contains a given animation.
   *
   * @param {ModelExperimentalAnimation} runtimeAnimation The runtime animation to check for.
   * @returns {Boolean} <code>true</code> if this collection contains the animation, <code>false</code> otherwise.
   */
  ModelExperimentalAnimationCollection.prototype.contains = function (
    runtimeAnimation
  ) {
    if (defined(runtimeAnimation)) {
      return this._runtimeAnimations.indexOf(runtimeAnimation) !== -1;
    }

    return false;
  };

  /**
   * Returns the animation in the collection at the specified index.  Indices are zero-based
   * and increase as animations are added.  Removing an animation shifts all animations after
   * it to the left, changing their indices.  This function is commonly used to iterate over
   * all the animations in the collection.
   *
   * @param {Number} index The zero-based index of the animation.
   * @returns {ModelExperimentalAnimation} The runtime animation at the specified index.
   *
   * @example
   * // Output the names of all the animations in the collection.
   * const animations = model.activeAnimations;
   * const length = animations.length;
   * for (let i = 0; i < length; ++i) {
   *   console.log(animations.get(i).name);
   * }
   */
  ModelExperimentalAnimationCollection.prototype.get = function (index) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(index)) {
      throw new DeveloperError("index is required.");
    }

    if (index >= this._runtimeAnimations.length || index < 0) {
      throw new DeveloperError(
        "index must be valid within the range of the collection"
      );
    }
    //>>includeEnd('debug');

    return this._runtimeAnimations[index];
  };

  const animationsToRemove = [];

  function createAnimationRemovedFunction(
    modelAnimationCollection,
    model,
    animation
  ) {
    return function () {
      modelAnimationCollection.animationRemoved.raiseEvent(model, animation);
    };
  }

  /**
   * Updates the runtime animations in this collection, removing any animations
   * that have stopped.
   *
   * @param {FrameState} frameState The current frame state.
   * @returns {Boolean} <code>true</code> if an animation played during this update, <code>false</code> otherwise.
   *
   * @private
   */
  ModelExperimentalAnimationCollection.prototype.update = function (frameState) {
    const runtimeAnimations = this._runtimeAnimations;
    let length = runtimeAnimations.length;

    if (length === 0) {
      this._previousTime = undefined;
      return false;
    }

    if (
      !this.animateWhilePaused &&
      JulianDate.equals(frameState.time, this._previousTime)
    ) {
      return false;
    }
    this._previousTime = JulianDate.clone(frameState.time, this._previousTime);

    let animationOccurred = false;
    const sceneTime = frameState.time;
    const model = this._model;

    for (let i = 0; i < length; ++i) {
      const runtimeAnimation = runtimeAnimations[i];

      if (!defined(runtimeAnimation._computedStartTime)) {
        runtimeAnimation._computedStartTime = JulianDate.addSeconds(
          defaultValue(runtimeAnimation.startTime, sceneTime),
          runtimeAnimation.delay,
          new JulianDate()
        );
      }

      if (!defined(runtimeAnimation._duration)) {
        runtimeAnimation._duration =
          runtimeAnimation.localStopTime * (1.0 / runtimeAnimation.multiplier);
      }

      const startTime = runtimeAnimation._computedStartTime;
      const duration = runtimeAnimation._duration;
      const stopTime = runtimeAnimation.stopTime;

      const pastStartTime = JulianDate.lessThanOrEquals(startTime, sceneTime);
      const reachedStopTime =
        defined(stopTime) && JulianDate.greaterThan(sceneTime, stopTime);

      // [0.0, 1.0] normalized local animation time
      let delta = 0.0;
      if (duration !== 0.0) {
        const seconds = JulianDate.secondsDifference(
          reachedStopTime ? stopTime : sceneTime,
          startTime
        );
        delta = defined(runtimeAnimation._animationTime)
          ? runtimeAnimation._animationTime(duration, seconds)
          : seconds / duration;
      }

      // Play animation if
      // * we are after the start time or the animation is being repeated, and
      // * before the end of the animation's duration or the animation is being repeated, and
      // * we did not reach a user-provided stop time.

      const repeat =
        runtimeAnimation.loop === ModelAnimationLoop$1.REPEAT ||
        runtimeAnimation.loop === ModelAnimationLoop$1.MIRRORED_REPEAT;

      const play =
        (pastStartTime || (repeat && !defined(runtimeAnimation.startTime))) &&
        (delta <= 1.0 || repeat) &&
        !reachedStopTime;

      if (delta === runtimeAnimation._prevAnimationDelta) {
        const animationStopped =
          runtimeAnimation._state === ModelAnimationState.STOPPED;
        // no change to delta, and no change to the animation state means we can
        // skip the update this time around.
        if (play !== animationStopped) {
          continue;
        }
      }
      runtimeAnimation._prevAnimationDelta = delta;

      // If it IS, or WAS, animating...
      if (play || runtimeAnimation._state === ModelAnimationState.ANIMATING) {
        // ...transition from STOPPED to ANIMATING
        if (play && runtimeAnimation._state === ModelAnimationState.STOPPED) {
          runtimeAnimation._state = ModelAnimationState.ANIMATING;
          if (runtimeAnimation.start.numberOfListeners > 0) {
            frameState.afterRender.push(runtimeAnimation._raiseStartEvent);
          }
        }

        // Truncate to [0.0, 1.0] for repeating animations
        if (runtimeAnimation.loop === ModelAnimationLoop$1.REPEAT) {
          delta = delta - Math.floor(delta);
        } else if (runtimeAnimation.loop === ModelAnimationLoop$1.MIRRORED_REPEAT) {
          const floor = Math.floor(delta);
          const fract = delta - floor;
          // When odd use (1.0 - fract) to mirror repeat
          delta = floor % 2 === 1.0 ? 1.0 - fract : fract;
        }

        if (runtimeAnimation.reverse) {
          delta = 1.0 - delta;
        }

        let localAnimationTime = delta * duration * runtimeAnimation.multiplier;
        // Clamp in case floating-point roundoff goes outside the animation's first or last keyframe
        localAnimationTime = CesiumMath.clamp(
          localAnimationTime,
          runtimeAnimation.localStartTime,
          runtimeAnimation.localStopTime
        );

        runtimeAnimation.animate(localAnimationTime);

        if (runtimeAnimation.update.numberOfListeners > 0) {
          runtimeAnimation._updateEventTime = localAnimationTime;
          frameState.afterRender.push(runtimeAnimation._raiseUpdateEvent);
        }
        animationOccurred = true;

        if (!play) {
          // transition from ANIMATING to STOPPED
          runtimeAnimation._state = ModelAnimationState.STOPPED;
          if (runtimeAnimation.stop.numberOfListeners > 0) {
            frameState.afterRender.push(runtimeAnimation._raiseStopEvent);
          }

          if (runtimeAnimation.removeOnStop) {
            animationsToRemove.push(runtimeAnimation);
          }
        }
      }
    }

    // Remove animations that stopped
    length = animationsToRemove.length;
    for (let j = 0; j < length; ++j) {
      const animationToRemove = animationsToRemove[j];
      runtimeAnimations.splice(runtimeAnimations.indexOf(animationToRemove), 1);
      frameState.afterRender.push(
        createAnimationRemovedFunction(this, model, animationToRemove)
      );
    }
    animationsToRemove.length = 0;

    return animationOccurred;
  };

  /**
   * An enum describing what commands (opaque) are required by a Cesium3DTileStyle.
   *
   * @private
   */
  const StyleCommandsNeeded = {
    ALL_OPAQUE: 0,
    ALL_TRANSLUCENT: 1,
    OPAQUE_AND_TRANSLUCENT: 2,
  };

  /**
   * @private
   */
  StyleCommandsNeeded.getStyleCommandsNeeded = function (
    featuresLength,
    translucentFeaturesLength
  ) {
    if (translucentFeaturesLength === 0) {
      return StyleCommandsNeeded.ALL_OPAQUE;
    } else if (translucentFeaturesLength === featuresLength) {
      return StyleCommandsNeeded.ALL_TRANSLUCENT;
    }
    return StyleCommandsNeeded.OPAQUE_AND_TRANSLUCENT;
  };

  var StyleCommandsNeeded$1 = Object.freeze(StyleCommandsNeeded);

  /**
   * A wrapper around the draw commands used to render a {@link ModelExperimentalPrimitive}.
   * This manages the derived commands and returns only the necessary commands depending
   * on the given frame state.
   *
   * @param {Object} options An object containing the following options:
   * @param {DrawCommand} options.command The draw command from which to derive other commands from.
   * @param {PrimitiveRenderResources} options.primitiveRenderResources The render resources of the primitive associated with the command.
   * @param {Boolean} [options.useSilhouetteCommands=false] Whether the model has a silhouette and needs to derive silhouette commands.
   * @alias ModelExperimentalDrawCommand
   * @constructor
   *
   * @private
   */
  function ModelExperimentalDrawCommand(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const command = options.command;
    const renderResources = options.primitiveRenderResources;
    const useSilhouetteCommands = defaultValue(
      options.useSilhouetteCommands,
      false
    );

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.command", command);
    Check.typeOf.object("options.primitiveRenderResources", renderResources);
    //>>includeEnd('debug');

    this._command = command;

    // Only derived if the original command wasn't translucent and the model's style
    // has translucency.
    this._translucentCommand = undefined;

    this._modelMatrix = Matrix4.clone(command.modelMatrix, new Matrix4());

    // The 2D projection of the model matrix depends on the frame state's
    // map projection, so it must be updated when the commands are being
    // retrieved in getCommands.
    this._modelMatrix2DDirty = false;

    this._styleCommandsNeeded = renderResources.styleCommandsNeeded;
    this._backFaceCulling = command.renderState.cull.enabled;
    this._cullFace = command.renderState.cull.face;
    this._shadows = renderResources.model.shadows;
    this._debugShowBoundingVolume = command.debugShowBoundingVolume;
    this._useSilhouetteCommands = useSilhouetteCommands;

    this._commandList = [];
    this._commandList2D = [];

    this._runtimePrimitive = renderResources.runtimePrimitive;
    this._model = renderResources.model;

    initialize$6(this);
  }

  function initialize$6(drawCommand) {
    const command = drawCommand._command;
    const styleCommandsNeeded = drawCommand._styleCommandsNeeded;

    // If the command was originally translucent then there's no need to derive
    // new commands. As of now, a style can't change an originally translucent
    // feature to opaque since the style's alpha is modulated, not a replacement.
    // When this changes, we need to derive new opaque commands in the constructor
    // of ModelExperimentalDrawCommand.
    if (defined(styleCommandsNeeded) && command.pass !== Pass$1.TRANSLUCENT) {
      const translucentCommand = deriveTranslucentCommand(command);
      switch (styleCommandsNeeded) {
        case StyleCommandsNeeded$1.ALL_OPAQUE:
          break;
        case StyleCommandsNeeded$1.ALL_TRANSLUCENT:
        case StyleCommandsNeeded$1.OPAQUE_AND_TRANSLUCENT:
          drawCommand._translucentCommand = translucentCommand;
          break;
        //>>includeStart('debug', pragmas.debug);
        default:
          throw new RuntimeError("styleCommandsNeeded is not a valid value.");
        //>>includeEnd('debug');
      }
    }

    buildCommandList(drawCommand);
  }

  Object.defineProperties(ModelExperimentalDrawCommand.prototype, {
    /**
     * The main draw command that the other commands are derived from.
     *
     * @memberof ModelExperimentalDrawCommand.prototype
     * @type {DrawCommand}
     *
     * @readonly
     * @private
     */
    command: {
      get: function () {
        return this._command;
      },
    },

    /**
     * The runtime primitive that the draw command belongs to.
     *
     * @memberof ModelExperimentalDrawCommand.prototype
     * @type {ModelExperimentalPrimitive}
     *
     * @readonly
     * @private
     */
    runtimePrimitive: {
      get: function () {
        return this._runtimePrimitive;
      },
    },

    /**
     * The model that the draw command belongs to.
     *
     * @memberof ModelExperimentalDrawCommand.prototype
     * @type {ModelExperimental}
     *
     * @readonly
     * @private
     */
    model: {
      get: function () {
        return this._model;
      },
    },

    /**
     * The primitive type of the main draw command.
     *
     * @memberof ModelExperimentalDrawCommand.prototype
     * @type {PrimitiveType}
     *
     * @readonly
     * @private
     */
    primitiveType: {
      get: function () {
        return this._command.primitiveType;
      },
    },

    /**
     * The current model matrix applied to the draw commands. If there are
     * 2D draw commands, their model matrix will be derived from the 3D one.
     *
     * @memberof ModelExperimentalDrawCommand.prototype
     * @type {Matrix4}
     *
     * @readonly
     * @private
     */
    modelMatrix: {
      get: function () {
        return this._modelMatrix;
      },
      set: function (value) {
        this._modelMatrix = Matrix4.clone(value, this._modelMatrix);
        this._modelMatrix2DDirty = true;
        updateModelMatrix$1(this);
      },
    },

    /**
     * The bounding volume of the main draw command. This is equivalent
     * to the the primitive's bounding sphere transformed by the draw
     * command's model matrix.
     *
     * @memberof ModelExperimentalDrawCommand.prototype
     * @type {BoundingSphere}
     *
     * @readonly
     * @private
     */
    boundingVolume: {
      get: function () {
        return this._command.boundingVolume;
      },
    },

    /**
     * Whether the geometry casts or receives shadows from light sources.
     *
     * @memberof ModelExperimentalDrawCommand.prototype
     * @type {ShadowMode}
     *
     * @private
     */
    shadows: {
      get: function () {
        return this._shadows;
      },
      set: function (value) {
        this._shadows = value;
        updateShadows(this);
      },
    },

    /**
     * Whether to cull back-facing geometry. When true, back face culling is
     * determined by the material's doubleSided property; when false, back face
     * culling is disabled. Back faces are not culled if the model's color is
     * translucent, if the command is drawing translucent geometry, or if the
     * model is being drawn with a silhouette.
     *
     * @memberof ModelExperimentalDrawCommand.prototype
     * @type {Boolean}
     *
     * @private
     */
    backFaceCulling: {
      get: function () {
        return this._backFaceCulling;
      },
      set: function (value) {
        if (this._backFaceCulling === value) {
          return;
        }

        this._backFaceCulling = value;
        updateBackFaceCulling(this);
      },
    },

    /**
     * Determines which faces to cull, if culling is enabled.
     *
     * @memberof ModelExperimentalDrawCommand.prototype
     * @type {CullFace}
     *
     * @private
     */
    cullFace: {
      get: function () {
        return this._cullFace;
      },
      set: function (value) {
        if (this._cullFace === value) {
          return;
        }

        this._cullFace = value;
        updateCullFace(this);
      },
    },

    /**
     * Whether to draw the bounding sphere associated with this draw command.
     *
     * @memberof ModelExperimentalDrawCommand.prototype
     * @type {Boolean}
     *
     * @private
     */
    debugShowBoundingVolume: {
      get: function () {
        return this._debugShowBoundingVolume;
      },
      set: function (value) {
        if (this._debugShowBoundingVolume === value) {
          return;
        }

        this._debugShowBoundingVolume = value;
        updateShowBoundingVolume(this);
      },
    },
  });

  function buildCommandList(drawCommand) {
    const commandList = drawCommand._commandList;
    const commandList2D = drawCommand._commandList2D;
    commandList.length = 0;
    commandList2D.length = 0;

    // Add opaque and translucent commands depending on the style commands needed.
    const styleCommandsNeeded = drawCommand._styleCommandsNeeded;
    const originalCommand = drawCommand._command;
    const translucentCommand = drawCommand._translucentCommand;
    if (defined(styleCommandsNeeded) && defined(translucentCommand)) {
      switch (styleCommandsNeeded) {
        case StyleCommandsNeeded$1.ALL_OPAQUE:
          commandList.push(originalCommand);
          break;
        case StyleCommandsNeeded$1.ALL_TRANSLUCENT:
          commandList.push(translucentCommand);
          break;
        case StyleCommandsNeeded$1.OPAQUE_AND_TRANSLUCENT:
          commandList.push(originalCommand, translucentCommand);
          break;
        //>>includeStart('debug', pragmas.debug);
        default:
          throw new RuntimeError("styleCommandsNeeded is not a valid value.");
        //>>includeEnd('debug');
      }
    } else {
      commandList.push(originalCommand);
    }

    // Derive silhouette commands from the active commands.
    if (drawCommand._useSilhouetteCommands) {
      const length = commandList.length;
      const silhouetteCommands = [];
      const model = drawCommand._model;
      for (let i = 0; i < length; i++) {
        const command = commandList[i];
        const silhouetteModelCommand = deriveSilhouetteModelCommand(
          command,
          model
        );
        const silhouetteColorCommand = deriveSilhouetteColorCommand(
          command,
          model
        );
        silhouetteCommands.push(silhouetteModelCommand);
        silhouetteCommands.push(silhouetteColorCommand);
      }

      // Replace the original command list.
      commandList.length = 0;
      commandList.push.apply(commandList, silhouetteCommands);
    }
  }

  function getAllCommands(drawCommand) {
    const commandList = [];
    commandList.push.apply(commandList, drawCommand._commandList);
    commandList.push.apply(commandList, drawCommand._commandList2D);
    return commandList;
  }

  const scratchMatrix2D = new Matrix4();

  function updateModelMatrix$1(drawCommand) {
    const modelMatrix = drawCommand.modelMatrix;
    const boundingSphere = drawCommand.runtimePrimitive.boundingSphere;
    const commandList = drawCommand._commandList;
    const length = commandList.length;

    for (let i = 0; i < length; i++) {
      const command = commandList[i];
      command.modelMatrix = Matrix4.clone(modelMatrix, command.modelMatrix);
      command.boundingVolume = BoundingSphere.transform(
        boundingSphere,
        command.modelMatrix,
        command.boundingVolume
      );
    }
  }

  function updateModelMatrix2D(drawCommand, frameState) {
    const modelMatrix = drawCommand.modelMatrix;
    const boundingSphere = drawCommand.runtimePrimitive.boundingSphere;
    const commandList2D = drawCommand._commandList2D;
    const length2D = commandList2D.length;
    if (length2D === 0) {
      return;
    }

    const modelMatrix2D = Matrix4.clone(modelMatrix, scratchMatrix2D);

    // Change the translation's y-component so it appears on the opposite side
    // of the map.
    modelMatrix2D[13] -=
      CesiumMath.sign(modelMatrix[13]) *
      2.0 *
      CesiumMath.PI *
      frameState.mapProjection.ellipsoid.maximumRadius;

    for (let i = 0; i < length2D; i++) {
      const command = commandList2D[i];
      command.modelMatrix = Matrix4.clone(modelMatrix2D, command.modelMatrix);
      command.boundingVolume = BoundingSphere.transform(
        boundingSphere,
        command.modelMatrix,
        command.boundingVolume
      );
    }
  }

  function updateShadows(drawCommand) {
    const shadows = drawCommand.shadows;
    const castShadows = ShadowMode$1.castShadows(shadows);
    const receiveShadows = ShadowMode$1.receiveShadows(shadows);

    const commandList = getAllCommands(drawCommand);
    const commandLength = commandList.length;
    for (let i = 0; i < commandLength; i++) {
      const command = commandList[i];

      // Shadows should stay disabled for the silhouette color command.
      const model_silhouettePass = command.uniformMap.model_silhouettePass;
      if (defined(model_silhouettePass) && model_silhouettePass()) {
        continue;
      }

      command.castShadows = castShadows;
      command.receiveShadows = receiveShadows;
    }
  }

  function updateBackFaceCulling(drawCommand) {
    let backFaceCulling = drawCommand.backFaceCulling;
    const doubleSided =
      drawCommand.runtimePrimitive.primitive.material.doubleSided;
    const translucent = drawCommand._model.isTranslucent();
    const useSilhouetteCommands = drawCommand._useSilhouetteCommands;
    backFaceCulling =
      backFaceCulling && !doubleSided && !translucent && !useSilhouetteCommands;

    const commandList = getAllCommands(drawCommand);
    const commandLength = commandList.length;
    for (let i = 0; i < commandLength; i++) {
      const command = commandList[i];

      // Back-face culling should stay disabled if the command
      // is drawing translucent geometry.
      if (command.pass === Pass$1.TRANSLUCENT) {
        continue;
      }

      const renderState = clone$1(command.renderState, true);
      renderState.cull.enabled = backFaceCulling;
      command.renderState = RenderState.fromCache(renderState);
    }
  }

  function updateCullFace(drawCommand) {
    const cullFace = drawCommand.cullFace;
    const commandList = getAllCommands(drawCommand);
    const commandLength = commandList.length;

    for (let i = 0; i < commandLength; i++) {
      const command = commandList[i];
      const renderState = clone$1(command.renderState, true);
      renderState.cull.face = cullFace;
      command.renderState = RenderState.fromCache(renderState);
    }
  }

  function updateShowBoundingVolume(drawCommand) {
    const debugShowBoundingVolume = drawCommand.debugShowBoundingVolume;

    const commandList = getAllCommands(drawCommand);
    const commandLength = commandList.length;
    for (let i = 0; i < commandLength; i++) {
      const command = commandList[i];
      command.debugShowBoundingVolume = debugShowBoundingVolume;
    }
  }

  /**
   * Returns an array of the draw commands necessary to render the primitive.
   *
   * @param {FrameState} frameState The frame state.
   *
   * @returns {DrawCommand[]} The draw commands.
   *
   * @private
   */
  ModelExperimentalDrawCommand.prototype.getCommands = function (frameState) {
    const commandList = this._commandList;
    const commandList2D = this._commandList2D;

    const use2D = shouldUse2DCommands(this, frameState);

    if (use2D && commandList2D.length === 0) {
      const length = commandList.length;
      for (let i = 0; i < length; i++) {
        const command2D = derive2DCommand(commandList[i]);
        commandList2D.push(command2D);
      }

      this._modelMatrix2DDirty = true;
    }

    if (this._modelMatrix2DDirty) {
      updateModelMatrix2D(this, frameState);
      this._modelMatrix2DDirty = false;
    }

    const commands = [];
    commands.push.apply(commands, commandList);

    if (use2D) {
      commands.push.apply(commands, commandList2D);
    }

    return commands;
  };

  /**
   * @private
   */
  function deriveTranslucentCommand(command) {
    const derivedCommand = DrawCommand.shallowClone(command);
    derivedCommand.pass = Pass$1.TRANSLUCENT;
    const rs = clone$1(command.renderState, true);
    rs.cull.enabled = false;
    rs.depthTest.enabled = true;
    rs.depthMask = false;
    rs.blending = BlendingState$1.ALPHA_BLEND;
    derivedCommand.renderState = RenderState.fromCache(rs);

    return derivedCommand;
  }

  /**
   * If the model crosses the IDL in 2D, it will be drawn in one viewport but get
   * clipped by the other viewport. We create a second command that translates
   * the model matrix to the opposite side of the map so the part that was clipped
   * in one viewport is drawn in the other.
   *
   * @param {DrawCommand} command The original draw command.
   *
   * @returns {DrawCommand} The derived command for rendering across the IDL in 2D.
   *
   * @private
   */
  function derive2DCommand(command) {
    const derivedCommand = DrawCommand.shallowClone(command);

    // These will be computed in updateModelMatrix2D()
    derivedCommand.modelMatrix = new Matrix4();
    derivedCommand.boundingVolume = new BoundingSphere();

    return derivedCommand;
  }

  /**
   * Tracks how many silhouettes have been created. This value is used to
   * assign a reference number to the stencil.
   *
   * @type {Number}
   * @private
   */
  ModelExperimentalDrawCommand.silhouettesLength = 0;

  function deriveSilhouetteModelCommand(command, model) {
    // Wrap around after exceeding the 8-bit stencil limit.
    // The reference is unique to each model until this point.
    const stencilReference =
      ++ModelExperimentalDrawCommand.silhouettesLength % 255;
    const silhouetteModelCommand = DrawCommand.shallowClone(command);
    let renderState = clone$1(command.renderState, true);

    // Write the reference value into the stencil buffer.
    renderState.stencilTest = {
      enabled: true,
      frontFunction: WebGLConstants$1.ALWAYS,
      backFunction: WebGLConstants$1.ALWAYS,
      reference: stencilReference,
      mask: ~0,
      frontOperation: {
        fail: WebGLConstants$1.KEEP,
        zFail: WebGLConstants$1.KEEP,
        zPass: WebGLConstants$1.REPLACE,
      },
      backOperation: {
        fail: WebGLConstants$1.KEEP,
        zFail: WebGLConstants$1.KEEP,
        zPass: WebGLConstants$1.REPLACE,
      },
    };

    if (model.isInvisible()) {
      // When the model is invisible, disable color and depth writes,
      // but still write into the stencil buffer.
      renderState.colorMask = {
        red: false,
        green: false,
        blue: false,
        alpha: false,
      };
      renderState.depthMask = false;
    }

    renderState = RenderState.fromCache(renderState);
    silhouetteModelCommand.renderState = renderState;

    return silhouetteModelCommand;
  }

  function deriveSilhouetteColorCommand(command, model) {
    // Wrap around after exceeding the 8-bit stencil limit.
    // The reference is unique to each model until this point.
    const stencilReference = ModelExperimentalDrawCommand.silhouettesLength % 255;
    const silhouetteColorCommand = DrawCommand.shallowClone(command);
    let renderState = clone$1(command.renderState, true);
    renderState.depthTest.enabled = true;
    renderState.cull.enabled = false;

    // Render the silhouette in the translucent pass if the command is translucent
    // or if the silhouette color is translucent. This accounts for translucent
    // model color, since ModelColorPipelineStage sets the pass to translucent.
    const silhouetteTranslucent =
      command.pass === Pass$1.TRANSLUCENT || model.silhouetteColor.alpha < 1.0;
    if (silhouetteTranslucent) {
      silhouetteColorCommand.pass = Pass$1.TRANSLUCENT;
      renderState.depthMask = false;
      renderState.blending = BlendingState$1.ALPHA_BLEND;
    }

    // Only render the pixels of the silhouette that don't conflict with the stencil buffer.
    // This way, the silhouette doesn't render over the original model.
    renderState.stencilTest = {
      enabled: true,
      frontFunction: WebGLConstants$1.NOTEQUAL,
      backFunction: WebGLConstants$1.NOTEQUAL,
      reference: stencilReference,
      mask: ~0,
      frontOperation: {
        fail: WebGLConstants$1.KEEP,
        zFail: WebGLConstants$1.KEEP,
        zPass: WebGLConstants$1.KEEP,
      },
      backOperation: {
        fail: WebGLConstants$1.KEEP,
        zFail: WebGLConstants$1.KEEP,
        zPass: WebGLConstants$1.KEEP,
      },
    };

    renderState = RenderState.fromCache(renderState);

    const uniformMap = clone$1(command.uniformMap);
    uniformMap.model_silhouettePass = function () {
      return true;
    };

    silhouetteColorCommand.renderState = renderState;
    silhouetteColorCommand.uniformMap = uniformMap;
    silhouetteColorCommand.castShadows = false;
    silhouetteColorCommand.receiveShadows = false;

    return silhouetteColorCommand;
  }

  function shouldUse2DCommands(drawCommand, frameState) {
    if (frameState.mode !== SceneMode$1.SCENE2D || drawCommand.model._projectTo2D) {
      return false;
    }

    const idl2D =
      frameState.mapProjection.ellipsoid.maximumRadius * CesiumMath.PI;

    // Using the draw command's bounding sphere might cause primitives to not render
    // over the IDL, even if they are part of the same model.
    const model = drawCommand.model;
    const boundingSphere = model.sceneGraph._boundingSphere2D;
    const left = boundingSphere.center.y - boundingSphere.radius;
    const right = boundingSphere.center.y + boundingSphere.radius;

    return (left < idl2D && right > idl2D) || (left < -idl2D && right > -idl2D);
  }

  //This file is automatically rebuilt by the Cesium build process.
  var ModelExperimentalFS = "#if defined(HAS_NORMALS) && !defined(HAS_TANGENTS) && !defined(LIGHTING_UNLIT)\n\
#ifdef GL_OES_standard_derivatives\n\
#extension GL_OES_standard_derivatives : enable\n\
#endif\n\
#endif\n\
czm_modelMaterial defaultModelMaterial()\n\
{\n\
czm_modelMaterial material;\n\
material.diffuse = vec3(0.0);\n\
material.specular = vec3(1.0);\n\
material.roughness = 1.0;\n\
material.occlusion = 1.0;\n\
material.normalEC = vec3(0.0, 0.0, 1.0);\n\
material.emissive = vec3(0.0);\n\
material.alpha = 1.0;\n\
return material;\n\
}\n\
vec4 handleAlpha(vec3 color, float alpha)\n\
{\n\
#ifdef ALPHA_MODE_MASK\n\
if (alpha < u_alphaCutoff) {\n\
discard;\n\
}\n\
return vec4(color, 1.0);\n\
#elif defined(ALPHA_MODE_BLEND)\n\
return vec4(color, alpha);\n\
#else // OPAQUE\n\
return vec4(color, 1.0);\n\
#endif\n\
}\n\
SelectedFeature selectedFeature;\n\
void main()\n\
{\n\
#ifdef HAS_MODEL_SPLITTER\n\
modelSplitterStage();\n\
#endif\n\
czm_modelMaterial material = defaultModelMaterial();\n\
ProcessedAttributes attributes;\n\
geometryStage(attributes);\n\
FeatureIds featureIds;\n\
featureIdStage(featureIds, attributes);\n\
Metadata metadata;\n\
metadataStage(metadata, attributes);\n\
#ifdef HAS_SELECTED_FEATURE_ID\n\
selectedFeatureIdStage(selectedFeature, featureIds);\n\
#endif\n\
#ifndef CUSTOM_SHADER_REPLACE_MATERIAL\n\
materialStage(material, attributes, selectedFeature);\n\
#endif\n\
#ifdef HAS_CUSTOM_FRAGMENT_SHADER\n\
customShaderStage(material, attributes, featureIds, metadata);\n\
#endif\n\
lightingStage(material, attributes);\n\
#ifdef HAS_SELECTED_FEATURE_ID\n\
cpuStylingStage(material, selectedFeature);\n\
#endif\n\
#ifdef HAS_MODEL_COLOR\n\
modelColorStage(material);\n\
#endif\n\
vec4 color = handleAlpha(material.diffuse, material.alpha);\n\
#ifdef HAS_CLIPPING_PLANES\n\
modelClippingPlanesStage(color);\n\
#endif\n\
#if defined(HAS_SILHOUETTE) && defined(HAS_NORMALS)\n\
silhouetteStage(color);\n\
#endif\n\
gl_FragColor = color;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var ModelExperimentalVS = "precision highp float;\n\
czm_modelVertexOutput defaultVertexOutput(vec3 positionMC) {\n\
czm_modelVertexOutput vsOutput;\n\
vsOutput.positionMC = positionMC;\n\
vsOutput.pointSize = 1.0;\n\
return vsOutput;\n\
}\n\
void main()\n\
{\n\
ProcessedAttributes attributes;\n\
initializeAttributes(attributes);\n\
#ifdef USE_DEQUANTIZATION\n\
dequantizationStage(attributes);\n\
#endif\n\
#ifdef HAS_MORPH_TARGETS\n\
morphTargetsStage(attributes);\n\
#endif\n\
#ifdef HAS_SKINNING\n\
skinningStage(attributes);\n\
#endif\n\
#ifdef HAS_BITANGENTS\n\
attributes.bitangentMC = normalize(cross(attributes.normalMC, attributes.tangentMC) * attributes.tangentSignMC);\n\
#endif\n\
FeatureIds featureIds;\n\
featureIdStage(featureIds, attributes);\n\
#ifdef HAS_SELECTED_FEATURE_ID\n\
SelectedFeature feature;\n\
selectedFeatureIdStage(feature, featureIds);\n\
cpuStylingStage(attributes.positionMC, feature);\n\
#endif\n\
#if defined(USE_2D_POSITIONS) || defined(USE_2D_INSTANCING)\n\
mat4 modelView = czm_modelView3D;\n\
mat3 normal = czm_normal3D;\n\
#else\n\
mat4 modelView = czm_modelView;\n\
mat3 normal = czm_normal;\n\
#endif\n\
#ifdef HAS_INSTANCING\n\
#ifdef USE_LEGACY_INSTANCING\n\
mat4 instanceModelView;\n\
mat3 instanceModelViewInverseTranspose;\n\
legacyInstancingStage(attributes, instanceModelView, instanceModelViewInverseTranspose);\n\
modelView = instanceModelView;\n\
normal = instanceModelViewInverseTranspose;\n\
#else\n\
instancingStage(attributes);\n\
#endif\n\
#ifdef USE_PICKING\n\
v_pickColor = a_pickColor;\n\
#endif\n\
#endif\n\
Metadata metadata;\n\
metadataStage(metadata, attributes);\n\
#ifdef HAS_CUSTOM_VERTEX_SHADER\n\
czm_modelVertexOutput vsOutput = defaultVertexOutput(attributes.positionMC);\n\
customShaderStage(vsOutput, attributes, featureIds, metadata);\n\
#endif\n\
geometryStage(attributes, modelView, normal);\n\
#ifdef HAS_SILHOUETTE\n\
silhouetteStage(attributes);\n\
#endif\n\
#ifdef PRIMITIVE_TYPE_POINTS\n\
#ifdef HAS_CUSTOM_VERTEX_SHADER\n\
gl_PointSize = vsOutput.pointSize;\n\
#elif defined(USE_POINT_CLOUD_ATTENUATION)\n\
gl_PointSize = pointCloudAttenuationStage(v_positionEC);\n\
#else\n\
gl_PointSize = 1.0;\n\
#endif\n\
#endif\n\
}\n\
";

  /**
   * Utility functions for {@link ModelExperimental}.
   *
   * @private
   */
  function ModelExperimentalUtility() {}

  /**
   * Create a function for reporting when a model fails to load
   *
   * @param {ModelExperimental} model The model to report about
   * @param {String} type The type of object to report about
   * @param {String} path The URI of the model file
   * @return {Function} An error function that throws an error for the failed model
   *
   * @private
   */
  ModelExperimentalUtility.getFailedLoadFunction = function (model, type, path) {
    return function (error) {
      let message = `Failed to load ${type}: ${path}`;
      if (defined(error)) {
        message += `\n${error.message}`;
      }
      return Promise.reject(new RuntimeError(message));
    };
  };

  /**
   * Get a transformation matrix from a node in the model.
   *
   * @param {ModelComponents.Node} node The node components
   * @return {Matrix4} The computed transformation matrix. If no transformation matrix or parameters are specified, this will be the identity matrix.
   *
   * @private
   */
  ModelExperimentalUtility.getNodeTransform = function (node) {
    if (defined(node.matrix)) {
      return node.matrix;
    }

    return Matrix4.fromTranslationQuaternionRotationScale(
      defined(node.translation) ? node.translation : Cartesian3.ZERO,
      defined(node.rotation) ? node.rotation : Quaternion.IDENTITY,
      defined(node.scale) ? node.scale : Cartesian3.ONE
    );
  };

  /**
   * Find an attribute by semantic such as POSITION or TANGENT.
   *
   * @param {ModelComponents.Primitive|ModelComponents.Instances} object The primitive components or instances object
   * @param {VertexAttributeSemantic|InstanceAttributeSemantic} semantic The semantic to search for
   * @param {Number} setIndex The set index of the semantic. May be undefined for some semantics (POSITION, NORMAL, TRANSLATION, ROTATION, for example)
   * @return {ModelComponents.Attribute} The selected attribute, or undefined if not found.
   *
   * @private
   */
  ModelExperimentalUtility.getAttributeBySemantic = function (
    object,
    semantic,
    setIndex
  ) {
    const attributes = object.attributes;
    const attributesLength = attributes.length;
    for (let i = 0; i < attributesLength; ++i) {
      const attribute = attributes[i];
      const matchesSetIndex = defined(setIndex)
        ? attribute.setIndex === setIndex
        : true;
      if (attribute.semantic === semantic && matchesSetIndex) {
        return attribute;
      }
    }
  };

  /**
   * Similar to getAttributeBySemantic, but search using the name field only,
   * as custom attributes do not have a semantic.
   *
   * @param {ModelComponents.Primitive|ModelComponents.Instances} object The primitive components or instances object
   * @param {String} name The name of the attribute as it appears in the model file.
   * @return {ModelComponents.Attribute} The selected attribute, or undefined if not found.
   *
   * @private
   */
  ModelExperimentalUtility.getAttributeByName = function (object, name) {
    const attributes = object.attributes;
    const attributesLength = attributes.length;
    for (let i = 0; i < attributesLength; ++i) {
      const attribute = attributes[i];
      if (attribute.name === name) {
        return attribute;
      }
    }
  };

  /**
   * Find a feature ID from an array with label or positionalLabel matching the
   * given label
   * @param {Array.<ModelComponents.FeatureIdAttribute|ModelComponents.FeatureIdImplicitRange|ModelComponents.FeatureIdTexture>} featureIds
   * @param {String} label the label to search for
   * @return {ModelComponents.FeatureIdAttribute|ModelComponents.FeatureIdImplicitRange|ModelComponents.FeatureIdTexture} The feature ID set if found, otherwise <code>undefined</code>
   *
   * @private
   */
  ModelExperimentalUtility.getFeatureIdsByLabel = function (featureIds, label) {
    for (let i = 0; i < featureIds.length; i++) {
      const featureIdSet = featureIds[i];
      if (
        featureIdSet.positionalLabel === label ||
        featureIdSet.label === label
      ) {
        return featureIdSet;
      }
    }

    return undefined;
  };

  ModelExperimentalUtility.hasQuantizedAttributes = function (attributes) {
    if (!defined(attributes)) {
      return false;
    }

    for (let i = 0; i < attributes.length; i++) {
      const attribute = attributes[i];
      if (defined(attribute.quantization)) {
        return true;
      }
    }
    return false;
  };

  /**
   * @param {ModelComponents.Attribute} attribute
   *
   * @private
   */
  ModelExperimentalUtility.getAttributeInfo = function (attribute) {
    const semantic = attribute.semantic;
    const setIndex = attribute.setIndex;

    let variableName;
    let hasSemantic = false;
    if (defined(semantic)) {
      variableName = VertexAttributeSemantic$1.getVariableName(semantic, setIndex);
      hasSemantic = true;
    } else {
      variableName = attribute.name;
      // According to the glTF 2.0 spec, custom attributes must be prepended with
      // an underscore.
      variableName = variableName.replace(/^_/, "");
      variableName = variableName.toLowerCase();
    }

    const isVertexColor = /^color_\d+$/.test(variableName);
    const attributeType = attribute.type;
    let glslType = AttributeType$1.getGlslType(attributeType);

    // color_n can be either a vec3 or a vec4. But in GLSL we can always use
    // attribute vec4 since GLSL promotes vec3 attribute data to vec4 with
    // the .a channel set to 1.0.
    if (isVertexColor) {
      glslType = "vec4";
    }

    const isQuantized = defined(attribute.quantization);
    let quantizedGlslType;
    if (isQuantized) {
      // The quantized color_n attribute also is promoted to a vec4 in the shader
      quantizedGlslType = isVertexColor
        ? "vec4"
        : AttributeType$1.getGlslType(attribute.quantization.type);
    }

    return {
      attribute: attribute,
      isQuantized: isQuantized,
      variableName: variableName,
      hasSemantic: hasSemantic,
      glslType: glslType,
      quantizedGlslType: quantizedGlslType,
    };
  };

  const cartesianMaxScratch = new Cartesian3();
  const cartesianMinScratch = new Cartesian3();

  /**
   * Get the minimum and maximum values for a primitive's POSITION attribute.
   * This is used to compute the bounding sphere of the primitive, as well as
   * the bounding sphere of the whole model.
   *
   * @param {ModelComponents.Primitive} primitive The primitive components.
   * @param {Cartesian3} [instancingTranslationMin] The component-wise minimum value of the instancing translation attribute.
   * @param {Cartesian3} [instancingTranslationMax] The component-wise maximum value of the instancing translation attribute.
   *
   * @return {Object} An object containing the minimum and maximum position values.
   *
   * @private
   */
  ModelExperimentalUtility.getPositionMinMax = function (
    primitive,
    instancingTranslationMin,
    instancingTranslationMax
  ) {
    const positionGltfAttribute = ModelExperimentalUtility.getAttributeBySemantic(
      primitive,
      "POSITION"
    );

    let positionMax = positionGltfAttribute.max;
    let positionMin = positionGltfAttribute.min;

    if (defined(instancingTranslationMax) && defined(instancingTranslationMin)) {
      positionMin = Cartesian3.add(
        positionMin,
        instancingTranslationMin,
        cartesianMinScratch
      );
      positionMax = Cartesian3.add(
        positionMax,
        instancingTranslationMax,
        cartesianMaxScratch
      );
    }

    return {
      min: positionMin,
      max: positionMax,
    };
  };

  /**
   * Model matrices in a model file (e.g. glTF) are typically in a different
   * coordinate system, such as with y-up instead of z-up in 3D Tiles.
   * This function returns a matrix that will correct this such that z is up,
   * and x is forward.
   *
   * @param {Axis} upAxis The original up direction
   * @param {Axis} forwardAxis The original forward direction
   * @param {Matrix4} result The matrix in which to store the result.
   * @return {Matrix4} The axis correction matrix
   *
   * @private
   */
  ModelExperimentalUtility.getAxisCorrectionMatrix = function (
    upAxis,
    forwardAxis,
    result
  ) {
    result = Matrix4.clone(Matrix4.IDENTITY, result);

    if (upAxis === Axis$1.Y) {
      result = Matrix4.clone(Axis$1.Y_UP_TO_Z_UP, result);
    } else if (upAxis === Axis$1.X) {
      result = Matrix4.clone(Axis$1.X_UP_TO_Z_UP, result);
    }

    if (forwardAxis === Axis$1.Z) {
      // glTF 2.0 has a Z-forward convention that must be adapted here to X-forward.
      result = Matrix4.multiplyTransformation(result, Axis$1.Z_UP_TO_X_UP, result);
    }

    return result;
  };

  const scratchMatrix3$1 = new Matrix3();

  /**
   * Get the cull face to use in the command's render state.
   * <p>
   * From the glTF spec section 3.7.4:
   * When a mesh primitive uses any triangle-based topology (i.e., triangles,
   * triangle strip, or triangle fan), the determinant of the node’s global
   * transform defines the winding order of that primitive. If the determinant
   * is a positive value, the winding order triangle faces is counterclockwise;
   * in the opposite case, the winding order is clockwise.
   * </p>
   *
   * @param {Matrix4} modelMatrix The model matrix
   * @param {PrimitiveType} primitiveType The primitive type
   * @return {CullFace} The cull face
   *
   * @private
   */
  ModelExperimentalUtility.getCullFace = function (modelMatrix, primitiveType) {
    if (!PrimitiveType$1.isTriangles(primitiveType)) {
      return CullFace$1.BACK;
    }

    const matrix3 = Matrix4.getMatrix3(modelMatrix, scratchMatrix3$1);
    return Matrix3.determinant(matrix3) < 0.0 ? CullFace$1.FRONT : CullFace$1.BACK;
  };

  /**
   * Builds the {@link ModelExperimentalDrawCommand} for a {@link ModelExperimentalPrimitive}
   * using its render resources.
   *
   * @param {PrimitiveRenderResources} primitiveRenderResources The render resources for a primitive.
   * @param {FrameState} frameState The frame state for creating GPU resources.
   *
   * @returns {ModelExperimentalDrawCommand} The generated ModelExperimentalDrawCommand.
   *
   * @private
   */
  function buildDrawCommand(primitiveRenderResources, frameState) {
    const shaderBuilder = primitiveRenderResources.shaderBuilder;
    shaderBuilder.addVertexLines([ModelExperimentalVS]);
    shaderBuilder.addFragmentLines([ModelExperimentalFS]);

    const model = primitiveRenderResources.model;
    const context = frameState.context;

    const indexBuffer = getIndexBuffer$1(primitiveRenderResources);

    const vertexArray = new VertexArray({
      context: context,
      indexBuffer: indexBuffer,
      attributes: primitiveRenderResources.attributes,
    });

    model._pipelineResources.push(vertexArray);

    const shaderProgram = shaderBuilder.buildShaderProgram(frameState.context);
    model._pipelineResources.push(shaderProgram);

    const pass = primitiveRenderResources.alphaOptions.pass;
    const sceneGraph = model.sceneGraph;

    const modelMatrix = Matrix4.multiplyTransformation(
      sceneGraph.computedModelMatrix,
      primitiveRenderResources.runtimeNode.computedTransform,
      new Matrix4()
    );

    let boundingSphere;
    if (
      frameState.mode !== SceneMode$1.SCENE3D &&
      !frameState.scene3DOnly &&
      model._projectTo2D
    ) {
      const runtimePrimitive = primitiveRenderResources.runtimePrimitive;
      boundingSphere = runtimePrimitive.boundingSphere2D;
    } else {
      boundingSphere = BoundingSphere.transform(
        primitiveRenderResources.boundingSphere,
        modelMatrix,
        primitiveRenderResources.boundingSphere
      );
    }

    // Initialize render state with default values
    let renderState = clone$1(
      RenderState.fromCache(primitiveRenderResources.renderStateOptions),
      true
    );

    if (model.opaquePass === Pass$1.CESIUM_3D_TILE) {
      // Set stencil values for classification on 3D Tiles
      renderState.stencilTest = StencilConstants$1.setCesium3DTileBit();
      renderState.stencilMask = StencilConstants$1.CESIUM_3D_TILE_MASK;
    }

    renderState.cull.face = ModelExperimentalUtility.getCullFace(
      modelMatrix,
      primitiveRenderResources.primitiveType
    );
    renderState = RenderState.fromCache(renderState);

    const count = primitiveRenderResources.count;

    const command = new DrawCommand({
      boundingVolume: boundingSphere,
      modelMatrix: modelMatrix,
      uniformMap: primitiveRenderResources.uniformMap,
      renderState: renderState,
      vertexArray: vertexArray,
      shaderProgram: shaderProgram,
      cull: model.cull,
      pass: pass,
      count: count,
      pickId: primitiveRenderResources.pickId,
      instanceCount: primitiveRenderResources.instanceCount,
      primitiveType: primitiveRenderResources.primitiveType,
      debugShowBoundingVolume: model.debugShowBoundingVolume,
      castShadows: ShadowMode$1.castShadows(model.shadows),
      receiveShadows: ShadowMode$1.receiveShadows(model.shadows),
    });

    const useSilhouetteCommands = model.hasSilhouette(frameState);

    return new ModelExperimentalDrawCommand({
      primitiveRenderResources: primitiveRenderResources,
      command: command,
      useSilhouetteCommands: useSilhouetteCommands,
    });
  }

  /**
   * @private
   */
  function getIndexBuffer$1(primitiveRenderResources, frameState) {
    const wireframeIndexBuffer = primitiveRenderResources.wireframeIndexBuffer;
    if (defined(wireframeIndexBuffer)) {
      return wireframeIndexBuffer;
    }

    const indices = primitiveRenderResources.indices;
    if (!defined(indices)) {
      return undefined;
    }

    //>>includeStart('debug', pragmas.debug);
    if (!defined(indices.buffer)) {
      throw new DeveloperError("Indices must be provided as a Buffer");
    }
    //>>includeEnd('debug');

    return indices.buffer;
  }

  //This file is automatically rebuilt by the Cesium build process.
  var ImageBasedLightingStageFS = "vec3 proceduralIBL(\n\
vec3 positionEC,\n\
vec3 normalEC,\n\
vec3 lightDirectionEC,\n\
vec3 lightColorHdr,\n\
czm_pbrParameters pbrParameters\n\
) {\n\
vec3 v = -positionEC;\n\
vec3 positionWC = vec3(czm_inverseView * vec4(positionEC, 1.0));\n\
vec3 vWC = -normalize(positionWC);\n\
vec3 l = normalize(lightDirectionEC);\n\
vec3 n = normalEC;\n\
vec3 r = normalize(czm_inverseViewRotation * normalize(reflect(v, n)));\n\
float NdotL = clamp(dot(n, l), 0.001, 1.0);\n\
float NdotV = abs(dot(n, v)) + 0.001;\n\
float vertexRadius = length(positionWC);\n\
float horizonDotNadir = 1.0 - min(1.0, czm_ellipsoidRadii.x / vertexRadius);\n\
float reflectionDotNadir = dot(r, normalize(positionWC));\n\
r.x = -r.x;\n\
r = -normalize(czm_temeToPseudoFixed * r);\n\
r.x = -r.x;\n\
vec3 diffuseColor = pbrParameters.diffuseColor;\n\
float roughness = pbrParameters.roughness;\n\
vec3 specularColor = pbrParameters.f0;\n\
float inverseRoughness = 1.04 - roughness;\n\
inverseRoughness *= inverseRoughness;\n\
vec3 sceneSkyBox = textureCube(czm_environmentMap, r).rgb * inverseRoughness;\n\
float atmosphereHeight = 0.05;\n\
float blendRegionSize = 0.1 * ((1.0 - inverseRoughness) * 8.0 + 1.1 - horizonDotNadir);\n\
float blendRegionOffset = roughness * -1.0;\n\
float farAboveHorizon = clamp(horizonDotNadir - blendRegionSize * 0.5 + blendRegionOffset, 1.0e-10 - blendRegionSize, 0.99999);\n\
float aroundHorizon = clamp(horizonDotNadir + blendRegionSize * 0.5, 1.0e-10 - blendRegionSize, 0.99999);\n\
float farBelowHorizon = clamp(horizonDotNadir + blendRegionSize * 1.5, 1.0e-10 - blendRegionSize, 0.99999);\n\
float smoothstepHeight = smoothstep(0.0, atmosphereHeight, horizonDotNadir);\n\
vec3 belowHorizonColor = mix(vec3(0.1, 0.15, 0.25), vec3(0.4, 0.7, 0.9), smoothstepHeight);\n\
vec3 nadirColor = belowHorizonColor * 0.5;\n\
vec3 aboveHorizonColor = mix(vec3(0.9, 1.0, 1.2), belowHorizonColor, roughness * 0.5);\n\
vec3 blueSkyColor = mix(vec3(0.18, 0.26, 0.48), aboveHorizonColor, reflectionDotNadir * inverseRoughness * 0.5 + 0.75);\n\
vec3 zenithColor = mix(blueSkyColor, sceneSkyBox, smoothstepHeight);\n\
vec3 blueSkyDiffuseColor = vec3(0.7, 0.85, 0.9);\n\
float diffuseIrradianceFromEarth = (1.0 - horizonDotNadir) * (reflectionDotNadir * 0.25 + 0.75) * smoothstepHeight;\n\
float diffuseIrradianceFromSky = (1.0 - smoothstepHeight) * (1.0 - (reflectionDotNadir * 0.25 + 0.25));\n\
vec3 diffuseIrradiance = blueSkyDiffuseColor * clamp(diffuseIrradianceFromEarth + diffuseIrradianceFromSky, 0.0, 1.0);\n\
float notDistantRough = (1.0 - horizonDotNadir * roughness * 0.8);\n\
vec3 specularIrradiance = mix(zenithColor, aboveHorizonColor, smoothstep(farAboveHorizon, aroundHorizon, reflectionDotNadir) * notDistantRough);\n\
specularIrradiance = mix(specularIrradiance, belowHorizonColor, smoothstep(aroundHorizon, farBelowHorizon, reflectionDotNadir) * inverseRoughness);\n\
specularIrradiance = mix(specularIrradiance, nadirColor, smoothstep(farBelowHorizon, 1.0, reflectionDotNadir) * inverseRoughness);\n\
#ifdef USE_SUN_LUMINANCE\n\
float LdotZenith = clamp(dot(normalize(czm_inverseViewRotation * l), vWC), 0.001, 1.0);\n\
float S = acos(LdotZenith);\n\
float NdotZenith = clamp(dot(normalize(czm_inverseViewRotation * n), vWC), 0.001, 1.0);\n\
float gamma = acos(NdotL);\n\
float numerator = ((0.91 + 10.0 * exp(-3.0 * gamma) + 0.45 * pow(NdotL, 2.0)) * (1.0 - exp(-0.32 / NdotZenith)));\n\
float denominator = (0.91 + 10.0 * exp(-3.0 * S) + 0.45 * pow(LdotZenith,2.0)) * (1.0 - exp(-0.32));\n\
float luminance = model_luminanceAtZenith * (numerator / denominator);\n\
#endif\n\
vec2 brdfLut = texture2D(czm_brdfLut, vec2(NdotV, roughness)).rg;\n\
vec3 iblColor = (diffuseIrradiance * diffuseColor * model_iblFactor.x) + (specularIrradiance * czm_srgbToLinear(specularColor * brdfLut.x + brdfLut.y) * model_iblFactor.y);\n\
float maximumComponent = max(max(lightColorHdr.x, lightColorHdr.y), lightColorHdr.z);\n\
vec3 lightColor = lightColorHdr / max(maximumComponent, 1.0);\n\
iblColor *= lightColor;\n\
#ifdef USE_SUN_LUMINANCE\n\
iblColor *= luminance;\n\
#endif\n\
return iblColor;\n\
}\n\
vec3 textureIBL(\n\
vec3 positionEC,\n\
vec3 normalEC,\n\
vec3 lightDirectionEC,\n\
czm_pbrParameters pbrParameters\n\
) {\n\
vec3 diffuseColor = pbrParameters.diffuseColor;\n\
float roughness = pbrParameters.roughness;\n\
vec3 specularColor = pbrParameters.f0;\n\
vec3 v = -positionEC;\n\
vec3 n = normalEC;\n\
vec3 l = normalize(lightDirectionEC);\n\
vec3 h = normalize(v + l);\n\
float NdotV = abs(dot(n, v)) + 0.001;\n\
float VdotH = clamp(dot(v, h), 0.0, 1.0);\n\
const mat3 yUpToZUp = mat3(\n\
-1.0, 0.0, 0.0,\n\
0.0, 0.0, -1.0,\n\
0.0, 1.0, 0.0\n\
);\n\
vec3 cubeDir = normalize(yUpToZUp * model_iblReferenceFrameMatrix * normalize(reflect(-v, n)));\n\
#ifdef DIFFUSE_IBL\n\
#ifdef CUSTOM_SPHERICAL_HARMONICS\n\
vec3 diffuseIrradiance = czm_sphericalHarmonics(cubeDir, model_sphericalHarmonicCoefficients);\n\
#else\n\
vec3 diffuseIrradiance = czm_sphericalHarmonics(cubeDir, czm_sphericalHarmonicCoefficients);\n\
#endif\n\
#else\n\
vec3 diffuseIrradiance = vec3(0.0);\n\
#endif\n\
#ifdef SPECULAR_IBL\n\
vec3 r0 = specularColor.rgb;\n\
float reflectance = max(max(r0.r, r0.g), r0.b);\n\
vec3 r90 = vec3(clamp(reflectance * 25.0, 0.0, 1.0));\n\
vec3 F = fresnelSchlick2(r0, r90, VdotH);\n\
vec2 brdfLut = texture2D(czm_brdfLut, vec2(NdotV, roughness)).rg;\n\
#ifdef CUSTOM_SPECULAR_IBL\n\
vec3 specularIBL = czm_sampleOctahedralProjection(model_specularEnvironmentMaps, model_specularEnvironmentMapsSize, cubeDir, roughness * model_specularEnvironmentMapsMaximumLOD, model_specularEnvironmentMapsMaximumLOD);\n\
#else\n\
vec3 specularIBL = czm_sampleOctahedralProjection(czm_specularEnvironmentMaps, czm_specularEnvironmentMapSize, cubeDir,  roughness * czm_specularEnvironmentMapsMaximumLOD, czm_specularEnvironmentMapsMaximumLOD);\n\
#endif\n\
specularIBL *= F * brdfLut.x + brdfLut.y;\n\
#else\n\
vec3 specularIBL = vec3(0.0);\n\
#endif\n\
return diffuseColor * diffuseIrradiance + specularColor * specularIBL;\n\
}\n\
vec3 imageBasedLightingStage(\n\
vec3 positionEC,\n\
vec3 normalEC,\n\
vec3 lightDirectionEC,\n\
vec3 lightColorHdr,\n\
czm_pbrParameters pbrParameters\n\
) {\n\
#if defined(DIFFUSE_IBL) || defined(SPECULAR_IBL)\n\
return textureIBL(\n\
positionEC,\n\
normalEC,\n\
lightDirectionEC,\n\
pbrParameters\n\
);\n\
#else\n\
return proceduralIBL(\n\
positionEC,\n\
normalEC,\n\
lightDirectionEC,\n\
lightColorHdr,\n\
pbrParameters\n\
);\n\
#endif\n\
}\n\
";

  /**
   * An enum describing whether a variable should be added to the
   * vertex shader, the fragment shader, or both.
   *
   * @private
   */
  const ShaderDestination = {
    VERTEX: 0,
    FRAGMENT: 1,
    BOTH: 2,
  };

  /**
   * Check if a variable should be included in the vertex shader.
   *
   * @param {ShaderDestination} destination The ShaderDestination to check
   * @return {Boolean} <code>true</code> if the variable appears in the vertex shader, or <code>false</code> otherwise
   * @private
   */
  ShaderDestination.includesVertexShader = function (destination) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("destination", destination);
    //>>includeEnd('debug');

    return (
      destination === ShaderDestination.VERTEX ||
      destination === ShaderDestination.BOTH
    );
  };

  /**
   * Check if a variable should be included in the vertex shader.
   *
   * @param {ShaderDestination} destination The ShaderDestination to check
   * @return {Boolean} <code>true</code> if the variable appears in the vertex shader, or <code>false</code> otherwise
   * @private
   */
  ShaderDestination.includesFragmentShader = function (destination) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("destination", destination);
    //>>includeEnd('debug');
    //
    return (
      destination === ShaderDestination.FRAGMENT ||
      destination === ShaderDestination.BOTH
    );
  };

  var ShaderDestination$1 = Object.freeze(ShaderDestination);

  const ImageBasedLightingPipelineStage = {};
  ImageBasedLightingPipelineStage.name = "ImageBasedLightingPipelineStage"; // Helps with debugging

  ImageBasedLightingPipelineStage.process = function (
    renderResources,
    model,
    frameState
  ) {
    const imageBasedLighting = model.imageBasedLighting;
    const shaderBuilder = renderResources.shaderBuilder;

    shaderBuilder.addDefine(
      "USE_IBL_LIGHTING",
      undefined,
      ShaderDestination$1.FRAGMENT
    );
    shaderBuilder.addUniform(
      "vec2",
      "model_iblFactor",
      ShaderDestination$1.FRAGMENT
    );

    if (OctahedralProjectedCubeMap.isSupported(frameState.context)) {
      const addMatrix =
        imageBasedLighting.useSphericalHarmonics ||
        imageBasedLighting.useSpecularEnvironmentMaps ||
        imageBasedLighting.enabled;
      if (addMatrix) {
        shaderBuilder.addUniform(
          "mat3",
          "model_iblReferenceFrameMatrix",
          ShaderDestination$1.FRAGMENT
        );
      }

      if (defined(imageBasedLighting.sphericalHarmonicCoefficients)) {
        shaderBuilder.addDefine(
          "DIFFUSE_IBL",
          undefined,
          ShaderDestination$1.FRAGMENT
        );
        shaderBuilder.addDefine(
          "CUSTOM_SPHERICAL_HARMONICS",
          undefined,
          ShaderDestination$1.FRAGMENT
        );
        shaderBuilder.addUniform(
          "vec3",
          "model_sphericalHarmonicCoefficients[9]",
          ShaderDestination$1.FRAGMENT
        );
      } else if (imageBasedLighting.useDefaultSphericalHarmonics) {
        shaderBuilder.addDefine(
          "DIFFUSE_IBL",
          undefined,
          ShaderDestination$1.FRAGMENT
        );
      }

      if (
        defined(imageBasedLighting.specularEnvironmentMapAtlas) &&
        imageBasedLighting.specularEnvironmentMapAtlas.ready
      ) {
        shaderBuilder.addDefine(
          "SPECULAR_IBL",
          undefined,
          ShaderDestination$1.FRAGMENT
        );
        shaderBuilder.addDefine(
          "CUSTOM_SPECULAR_IBL",
          undefined,
          ShaderDestination$1.FRAGMENT
        );
        shaderBuilder.addUniform(
          "sampler2D",
          "model_specularEnvironmentMaps",
          ShaderDestination$1.FRAGMENT
        );
        shaderBuilder.addUniform(
          "vec2",
          "model_specularEnvironmentMapsSize",
          ShaderDestination$1.FRAGMENT
        );
        shaderBuilder.addUniform(
          "float",
          "model_specularEnvironmentMapsMaximumLOD",
          ShaderDestination$1.FRAGMENT
        );
      } else if (model.useDefaultSpecularMaps) {
        shaderBuilder.addDefine(
          "SPECULAR_IBL",
          undefined,
          ShaderDestination$1.FRAGMENT
        );
      }
    }

    if (defined(imageBasedLighting.luminanceAtZenith)) {
      shaderBuilder.addDefine(
        "USE_SUN_LUMINANCE",
        undefined,
        ShaderDestination$1.FRAGMENT
      );
      shaderBuilder.addUniform(
        "float",
        "model_luminanceAtZenith",
        ShaderDestination$1.FRAGMENT
      );
    }

    shaderBuilder.addFragmentLines([ImageBasedLightingStageFS]);

    const uniformMap = {
      model_iblFactor: function () {
        return imageBasedLighting.imageBasedLightingFactor;
      },
      model_iblReferenceFrameMatrix: function () {
        return model._iblReferenceFrameMatrix;
      },
      model_luminanceAtZenith: function () {
        return imageBasedLighting.luminanceAtZenith;
      },
      model_sphericalHarmonicCoefficients: function () {
        return imageBasedLighting.sphericalHarmonicCoefficients;
      },
      model_specularEnvironmentMaps: function () {
        return imageBasedLighting.specularEnvironmentMapAtlas.texture;
      },
      model_specularEnvironmentMapsSize: function () {
        return imageBasedLighting.specularEnvironmentMapAtlas.texture.dimensions;
      },
      model_specularEnvironmentMapsMaximumLOD: function () {
        return imageBasedLighting.specularEnvironmentMapAtlas.maximumMipmapLevel;
      },
    };

    renderResources.uniformMap = combine$2(uniformMap, renderResources.uniformMap);
  };

  const articulationEpsilon = CesiumMath.EPSILON16;

  /**
   * An in-memory representation of an articulation stage belonging to a
   * {@link ModelExperimentalArticulation}.
   *
   * @param {Object} options An object containing the following options:
   * @param {ModelComponents.ArticulationStage} options.stage The articulation stage components from the 3D model.
   * @param {ModelExperimentalArticulation} options.runtimeArticulation The runtime articulation that this stage belongs to.
   *
   * @alias ModelExperimentalArticulationStage
   * @constructor
   *
   * @private
   */
  function ModelExperimentalArticulationStage(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const stage = options.stage;
    const runtimeArticulation = options.runtimeArticulation;
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.stage", stage);
    Check.typeOf.object("options.runtimeArticulation", runtimeArticulation);
    //>>includeEnd('debug');

    this._stage = stage;
    this._runtimeArticulation = runtimeArticulation;

    this._name = stage.name;
    this._type = stage.type;
    this._minimumValue = stage.minimumValue;
    this._maximumValue = stage.maximumValue;
    this._currentValue = stage.initialValue;
  }

  Object.defineProperties(ModelExperimentalArticulationStage.prototype, {
    /**
     * The internal articulation stage that this runtime stage represents.
     *
     * @memberof ModelExperimentalArticulationStage.prototype
     * @type {ModelComponents.ArticulationStage}
     * @readonly
     *
     * @private
     */
    stage: {
      get: function () {
        return this._stage;
      },
    },

    /**
     * The runtime articulation that this stage belongs to.
     *
     * @memberof ModelExperimentalArticulationStage.prototype
     * @type {ModelExperimentalArticulation}
     * @readonly
     *
     * @private
     */
    runtimeArticulation: {
      get: function () {
        return this._runtimeArticulation;
      },
    },

    /**
     * The name of this articulation stage.
     *
     * @memberof ModelExperimentalArticulationStage.prototype
     * @type {String}
     * @readonly
     *
     * @private
     */
    name: {
      get: function () {
        return this._name;
      },
    },

    /**
     * The type of this articulation stage. This specifies which of the
     * node's properties is modified by the stage's value.
     *
     * @memberof ModelExperimentalArticulationStage.prototype
     * @type {ArticulationStageType}
     * @readonly
     *
     * @private
     */
    type: {
      get: function () {
        return this._type;
      },
    },

    /**
     * The minimum value of this articulation stage.
     *
     * @memberof ModelExperimentalArticulationStage.prototype
     * @type {Number}
     * @readonly
     *
     * @private
     */
    minimumValue: {
      get: function () {
        return this._minimumValue;
      },
    },

    /**
     * The maximum value of this articulation stage.
     *
     * @memberof ModelExperimentalArticulationStage.prototype
     * @type {Number}
     * @readonly
     *
     * @private
     */
    maximumValue: {
      get: function () {
        return this._maximumValue;
      },
    },

    /**
     * The current value of this articulation stage.
     *
     * @memberof ModelExperimentalArticulationStage.prototype
     * @type {Number}
     *
     * @private
     */
    currentValue: {
      get: function () {
        return this._currentValue;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number("value", value);
        //>>includeEnd('debug');

        value = CesiumMath.clamp(value, this.minimumValue, this.maximumValue);
        if (
          !CesiumMath.equalsEpsilon(
            this._currentValue,
            value,
            articulationEpsilon
          )
        ) {
          this._currentValue = value;
          this.runtimeArticulation._dirty = true;
        }
      },
    },
  });

  const scratchArticulationCartesian = new Cartesian3();
  const scratchArticulationRotation = new Matrix3();

  /**
   * Modifies a Matrix4 by applying a transformation for a given value of a stage.
   * Note that the <code>result</code> parameter is not just a container for the
   * returned value. The incoming value of <code>result</code> is part of the
   * computation itself. Various stages of an articulation can be multiplied
   * together, so their transformations are all merged into a composite Matrix4
   * representing them all.
   *
   * @param {Matrix4} result The matrix to be modified.
   * @returns {Matrix4} The transformed matrix as requested by the articulation stage.
   *
   * @private
   */
  ModelExperimentalArticulationStage.prototype.applyStageToMatrix = function (
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("result", result);
    //>>includeEnd('debug');

    const type = this.type;
    const value = this.currentValue;
    const cartesian = scratchArticulationCartesian;
    let rotation;
    switch (type) {
      case ArticulationStageType$1.XROTATE:
        rotation = Matrix3.fromRotationX(
          CesiumMath.toRadians(value),
          scratchArticulationRotation
        );
        result = Matrix4.multiplyByMatrix3(result, rotation, result);
        break;
      case ArticulationStageType$1.YROTATE:
        rotation = Matrix3.fromRotationY(
          CesiumMath.toRadians(value),
          scratchArticulationRotation
        );
        result = Matrix4.multiplyByMatrix3(result, rotation, result);
        break;
      case ArticulationStageType$1.ZROTATE:
        rotation = Matrix3.fromRotationZ(
          CesiumMath.toRadians(value),
          scratchArticulationRotation
        );
        result = Matrix4.multiplyByMatrix3(result, rotation, result);
        break;
      case ArticulationStageType$1.XTRANSLATE:
        cartesian.x = value;
        cartesian.y = 0.0;
        cartesian.z = 0.0;
        result = Matrix4.multiplyByTranslation(result, cartesian, result);
        break;
      case ArticulationStageType$1.YTRANSLATE:
        cartesian.x = 0.0;
        cartesian.y = value;
        cartesian.z = 0.0;
        result = Matrix4.multiplyByTranslation(result, cartesian, result);
        break;
      case ArticulationStageType$1.ZTRANSLATE:
        cartesian.x = 0.0;
        cartesian.y = 0.0;
        cartesian.z = value;
        result = Matrix4.multiplyByTranslation(result, cartesian, result);
        break;
      case ArticulationStageType$1.XSCALE:
        cartesian.x = value;
        cartesian.y = 1.0;
        cartesian.z = 1.0;
        result = Matrix4.multiplyByScale(result, cartesian, result);
        break;
      case ArticulationStageType$1.YSCALE:
        cartesian.x = 1.0;
        cartesian.y = value;
        cartesian.z = 1.0;
        result = Matrix4.multiplyByScale(result, cartesian, result);
        break;
      case ArticulationStageType$1.ZSCALE:
        cartesian.x = 1.0;
        cartesian.y = 1.0;
        cartesian.z = value;
        result = Matrix4.multiplyByScale(result, cartesian, result);
        break;
      case ArticulationStageType$1.UNIFORMSCALE:
        result = Matrix4.multiplyByUniformScale(result, value, result);
        break;
    }

    return result;
  };

  /**
   * An in-memory representation of an articulation that affects nodes in the
   * {@link ModelExperimentalSceneGraph}. This is defined in a model by the
   * <code>AGI_articulations</code> extension.
   *
   * @param {Object} options An object containing the following options:
   * @param {ModelComponents.Articulation} options.articulation The articulation components from the 3D model.
   * @param {ModelExperimentalSceneGraph} options.sceneGraph The scene graph this articulation belongs to.
   *
   * @alias ModelExperimentalArticulation
   * @constructor
   *
   * @private
   */
  function ModelExperimentalArticulation(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const articulation = options.articulation;
    const sceneGraph = options.sceneGraph;
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.articulation", articulation);
    Check.typeOf.object("options.sceneGraph", sceneGraph);
    //>>includeEnd('debug');

    this._articulation = articulation;
    this._sceneGraph = sceneGraph;

    this._name = articulation.name;
    this._runtimeStages = [];
    this._runtimeStagesByName = {};

    // Will be populated as the runtime nodes are created
    this._runtimeNodes = [];

    // Set to true so that the first call to
    // ModelExperimentalSceneGraph.applyArticulations will work.
    this._dirty = true;

    initialize$5(this);
  }

  Object.defineProperties(ModelExperimentalArticulation.prototype, {
    /**
     * The internal articulation that this runtime articulation represents.
     *
     * @memberof ModelExperimentalArticulation.prototype
     * @type {ModelComponents.Articulation}
     * @readonly
     *
     * @private
     */
    articulation: {
      get: function () {
        return this._articulation;
      },
    },

    /**
     * The scene graph that this articulation belongs to.
     *
     * @memberof ModelExperimentalArticulation.prototype
     * @type {ModelExperimentalSceneGraph}
     * @readonly
     *
     * @private
     */
    sceneGraph: {
      get: function () {
        return this._sceneGraph;
      },
    },

    /**
     * The name of this articulation.
     *
     * @memberof ModelExperimentalArticulation.prototype
     * @type {String}
     * @readonly
     *
     * @private
     */
    name: {
      get: function () {
        return this._name;
      },
    },

    /**
     * The runtime stages that belong to this articulation.
     *
     * @memberof ModelExperimentalArticulation.prototype
     * @type {ModelExperimentalArticulationStage[]}
     * @readonly
     *
     * @private
     */
    runtimeStages: {
      get: function () {
        return this._runtimeStages;
      },
    },

    /**
     * The runtime nodes that are affected by this articulation.
     *
     * @memberof ModelExperimentalArticulation.prototype
     * @type {ModelExperimentalNode[]}
     * @readonly
     *
     * @private
     */
    runtimeNodes: {
      get: function () {
        return this._runtimeNodes;
      },
    },
  });

  function initialize$5(runtimeArticulation) {
    const articulation = runtimeArticulation.articulation;

    const stages = articulation.stages;
    const length = stages.length;

    const runtimeStages = runtimeArticulation._runtimeStages;
    const runtimeStagesByName = runtimeArticulation._runtimeStagesByName;
    for (let i = 0; i < length; i++) {
      const stage = stages[i];
      const runtimeStage = new ModelExperimentalArticulationStage({
        stage: stage,
        runtimeArticulation: runtimeArticulation,
      });

      // Store the stages in an array to preserve the order in which
      // they appeared in the 3D model.
      runtimeStages.push(runtimeStage);

      // Store the stages in a dictionary for retrieval by name.
      const stageName = stage.name;
      runtimeStagesByName[stageName] = runtimeStage;
    }
  }

  /**
   * Sets the current value of an articulation stage.
   *
   * @param {String} stageName The name of the articulation stage.
   * @param {Number} value The numeric value of this stage of the articulation.
   *
   * @private
   */
  ModelExperimentalArticulation.prototype.setArticulationStage = function (
    stageName,
    value
  ) {
    const stage = this._runtimeStagesByName[stageName];
    if (defined(stage)) {
      stage.currentValue = value;
    }
  };

  const scratchArticulationMatrix = new Matrix4();
  const scratchNodeMatrix = new Matrix4();

  /**
   * Applies the chain of articulation stages to the transform of each node that
   * participates in the articulation. This only recomputes the node transforms
   * if any stage in the articulation has been modified.
   * <p>
   * Note that this will overwrite any existing transformations on participating
   * nodes.
   * </p>
   *
   * @private
   */
  ModelExperimentalArticulation.prototype.apply = function () {
    if (!this._dirty) {
      return;
    }
    this._dirty = false;

    let articulationMatrix = Matrix4.clone(
      Matrix4.IDENTITY,
      scratchArticulationMatrix
    );

    let i;
    const stages = this._runtimeStages;
    const stagesLength = stages.length;

    // Compute the result of the articulation stages...
    for (i = 0; i < stagesLength; i++) {
      const stage = stages[i];
      articulationMatrix = stage.applyStageToMatrix(articulationMatrix);
    }

    // ...then apply it to the transforms of the affected nodes.
    const nodes = this._runtimeNodes;
    const nodesLength = nodes.length;
    for (i = 0; i < nodesLength; i++) {
      const node = nodes[i];
      const transform = Matrix4.multiplyTransformation(
        node.originalTransform,
        articulationMatrix,
        scratchNodeMatrix
      );
      node.transform = transform;
    }
  };

  //This file is automatically rebuilt by the Cesium build process.
  var ModelColorStageFS = "void modelColorStage(inout czm_modelMaterial material)\n\
{\n\
material.diffuse = mix(material.diffuse, model_color.rgb, model_colorBlend);\n\
float highlight = ceil(model_colorBlend);\n\
material.diffuse *= mix(model_color.rgb, vec3(1.0), highlight);\n\
material.alpha *= model_color.a;\n\
}\n\
";

  /**
   * The model color pipeline stage is responsible for handling the application of a static color to the model.
   *
   * @namespace ModelColorPipelineStage
   *
   * @private
   */
  const ModelColorPipelineStage = {};
  ModelColorPipelineStage.name = "ModelColorPipelineStage"; // Helps with debugging

  ModelColorPipelineStage.COLOR_UNIFORM_NAME = "model_color";
  ModelColorPipelineStage.COLOR_BLEND_UNIFORM_NAME = "model_colorBlend";

  /**
   * Process a model. This modifies the following parts of the render resources:
   *
   * <ul>
   *  <li>adds a define to the fragment shader to indicate that the model has a color</li>
   *  <li>adds a function to the fragment shader to apply the color to the model's base color</li>
   *  <li>adds the uniforms for the fragment shader for the model's color and blending properties</li>
   *  <li>updates the pass type in the render resources based on translucency of the model's color</li>
   *</ul>
   *
   * @param {ModelRenderResources} renderResources The render resources for this model.
   * @param {ModelExperimental} model The model.
   * @param {FrameState} frameState The frameState.
   *
   * @private
   */
  ModelColorPipelineStage.process = function (
    renderResources,
    model,
    frameState
  ) {
    const shaderBuilder = renderResources.shaderBuilder;

    shaderBuilder.addDefine(
      "HAS_MODEL_COLOR",
      undefined,
      ShaderDestination$1.FRAGMENT
    );
    shaderBuilder.addFragmentLines([ModelColorStageFS]);

    const stageUniforms = {};

    // Pass the model's color as a uniform. Set the pass type to translucent, if needed.
    const color = model.color;
    const renderStateOptions = renderResources.renderStateOptions;
    if (color.alpha === 0.0 && !model.hasSilhouette(frameState)) {
      // When the model is invisible, only disable the color and depth writes
      // if the model does not have a silhouette. Otherwise, the silhouette
      // will not render.
      renderStateOptions.colorMask = {
        red: false,
        green: false,
        blue: false,
        alpha: false,
      };
      renderStateOptions.depthMask = false;
    } else if (color.alpha < 1.0) {
      renderResources.alphaOptions.pass = Pass$1.TRANSLUCENT;
      renderResources.alphaOptions.alphaMode = AlphaMode$1.BLEND;
    }

    shaderBuilder.addUniform(
      "vec4",
      ModelColorPipelineStage.COLOR_UNIFORM_NAME,
      ShaderDestination$1.FRAGMENT
    );
    stageUniforms[ModelColorPipelineStage.COLOR_UNIFORM_NAME] = function () {
      return model.color;
    };

    // Create a colorBlend from the model's colorBlendMode and colorBlendAmount and pass it as a uniform.
    shaderBuilder.addUniform(
      "float",
      ModelColorPipelineStage.COLOR_BLEND_UNIFORM_NAME,
      ShaderDestination$1.FRAGMENT
    );
    stageUniforms[
      ModelColorPipelineStage.COLOR_BLEND_UNIFORM_NAME
    ] = function () {
      return ColorBlendMode$1.getColorBlend(
        model.colorBlendMode,
        model.colorBlendAmount
      );
    };

    renderResources.uniformMap = combine$2(
      stageUniforms,
      renderResources.uniformMap
    );
  };

  //This file is automatically rebuilt by the Cesium build process.
  var ModelClippingPlanesStageFS = "#ifdef USE_CLIPPING_PLANES_FLOAT_TEXTURE\n\
vec4 getClippingPlane(\n\
highp sampler2D packedClippingPlanes,\n\
int clippingPlaneNumber,\n\
mat4 transform\n\
) {\n\
int pixY = clippingPlaneNumber / CLIPPING_PLANES_TEXTURE_WIDTH;\n\
int pixX = clippingPlaneNumber - (pixY * CLIPPING_PLANES_TEXTURE_WIDTH);\n\
float pixelWidth = 1.0 / float(CLIPPING_PLANES_TEXTURE_WIDTH);\n\
float pixelHeight = 1.0 / float(CLIPPING_PLANES_TEXTURE_HEIGHT);\n\
float u = (float(pixX) + 0.5) * pixelWidth;\n\
float v = (float(pixY) + 0.5) * pixelHeight;\n\
vec4 plane = texture2D(packedClippingPlanes, vec2(u, v));\n\
return czm_transformPlane(plane, transform);\n\
}\n\
#else\n\
vec4 getClippingPlane(\n\
highp sampler2D packedClippingPlanes,\n\
int clippingPlaneNumber,\n\
mat4 transform\n\
) {\n\
int clippingPlaneStartIndex = clippingPlaneNumber * 2;\n\
int pixY = clippingPlaneStartIndex / CLIPPING_PLANES_TEXTURE_WIDTH;\n\
int pixX = clippingPlaneStartIndex - (pixY * CLIPPING_PLANES_TEXTURE_WIDTH);\n\
float pixelWidth = 1.0 / float(CLIPPING_PLANES_TEXTURE_WIDTH);\n\
float pixelHeight = 1.0 / float(CLIPPING_PLANES_TEXTURE_HEIGHT);\n\
float u = (float(pixX) + 0.5) * pixelWidth;\n\
float v = (float(pixY) + 0.5) * pixelHeight;\n\
vec4 oct32 = texture2D(packedClippingPlanes, vec2(u, v)) * 255.0;\n\
vec2 oct = vec2(oct32.x * 256.0 + oct32.y, oct32.z * 256.0 + oct32.w);\n\
vec4 plane;\n\
plane.xyz = czm_octDecode(oct, 65535.0);\n\
plane.w = czm_unpackFloat(texture2D(packedClippingPlanes, vec2(u + pixelWidth, v)));\n\
return czm_transformPlane(plane, transform);\n\
}\n\
#endif\n\
float clip(vec4 fragCoord, sampler2D clippingPlanes, mat4 clippingPlanesMatrix) {\n\
vec4 position = czm_windowToEyeCoordinates(fragCoord);\n\
vec3 clipNormal = vec3(0.0);\n\
vec3 clipPosition = vec3(0.0);\n\
float pixelWidth = czm_metersPerPixel(position);\n\
#ifdef UNION_CLIPPING_REGIONS\n\
float clipAmount;\n\
#else\n\
float clipAmount = 0.0;\n\
bool clipped = true;\n\
#endif\n\
for (int i = 0; i < CLIPPING_PLANES_LENGTH; ++i) {\n\
vec4 clippingPlane = getClippingPlane(clippingPlanes, i, clippingPlanesMatrix);\n\
clipNormal = clippingPlane.xyz;\n\
clipPosition = -clippingPlane.w * clipNormal;\n\
float amount = dot(clipNormal, (position.xyz - clipPosition)) / pixelWidth;\n\
#ifdef UNION_CLIPPING_REGIONS\n\
clipAmount = czm_branchFreeTernary(i == 0, amount, min(amount, clipAmount));\n\
if (amount <= 0.0) {\n\
discard;\n\
}\n\
#else\n\
clipAmount = max(amount, clipAmount);\n\
clipped = clipped && (amount <= 0.0);\n\
#endif\n\
}\n\
#ifndef UNION_CLIPPING_REGIONS\n\
if (clipped) {\n\
discard;\n\
}\n\
#endif\n\
return clipAmount;\n\
}\n\
void modelClippingPlanesStage(inout vec4 color)\n\
{\n\
float clipDistance = clip(gl_FragCoord, model_clippingPlanes, model_clippingPlanesMatrix);\n\
vec4 clippingPlanesEdgeColor = vec4(1.0);\n\
clippingPlanesEdgeColor.rgb = model_clippingPlanesEdgeStyle.rgb;\n\
float clippingPlanesEdgeWidth = model_clippingPlanesEdgeStyle.a;\n\
if (clipDistance > 0.0 && clipDistance < clippingPlanesEdgeWidth) {\n\
color = clippingPlanesEdgeColor;\n\
}\n\
}\n\
";

  /**
   * The model clipping planes stage is responsible for applying clipping planes to the model.
   *
   * @namespace ModelClippingPlanesPipelineStage
   *
   * @private
   */
  const ModelClippingPlanesPipelineStage = {};
  ModelClippingPlanesPipelineStage.name = "ModelClippingPlanesPipelineStage"; // Helps with debugging

  const textureResolutionScratch = new Cartesian2();
  /**
   * Process a model. This modifies the following parts of the render resources:
   *
   * <ul>
   *  <li>adds a define to the fragment shader to indicate that the model has clipping planes</li>
   *  <li>adds the defines to the fragment shader for parameters related to clipping planes, such as the number of planes</li>
   *  <li>adds a function to the fragment shader to apply the clipping planes to the model's base color</li>
   *  <li>adds the uniforms for the fragment shader for the clipping plane texture and matrix</li>
   *</ul>
   *
   * @param {ModelRenderResources} renderResources The render resources for this model.
   * @param {ModelExperimental} model The model.
   * @param {FrameState} frameState The frameState.
   *
   * @private
   */
  ModelClippingPlanesPipelineStage.process = function (
    renderResources,
    model,
    frameState
  ) {
    const clippingPlanes = model.clippingPlanes;
    const context = frameState.context;
    const shaderBuilder = renderResources.shaderBuilder;

    shaderBuilder.addDefine(
      "HAS_CLIPPING_PLANES",
      undefined,
      ShaderDestination$1.FRAGMENT
    );

    shaderBuilder.addDefine(
      "CLIPPING_PLANES_LENGTH",
      clippingPlanes.length,
      ShaderDestination$1.FRAGMENT
    );

    if (clippingPlanes.unionClippingRegions) {
      shaderBuilder.addDefine(
        "UNION_CLIPPING_REGIONS",
        undefined,
        ShaderDestination$1.FRAGMENT
      );
    }

    if (ClippingPlaneCollection.useFloatTexture(context)) {
      shaderBuilder.addDefine(
        "USE_CLIPPING_PLANES_FLOAT_TEXTURE",
        undefined,
        ShaderDestination$1.FRAGMENT
      );
    }

    const textureResolution = ClippingPlaneCollection.getTextureResolution(
      clippingPlanes,
      context,
      textureResolutionScratch
    );

    shaderBuilder.addDefine(
      "CLIPPING_PLANES_TEXTURE_WIDTH",
      textureResolution.x,
      ShaderDestination$1.FRAGMENT
    );

    shaderBuilder.addDefine(
      "CLIPPING_PLANES_TEXTURE_HEIGHT",
      textureResolution.y,
      ShaderDestination$1.FRAGMENT
    );

    shaderBuilder.addUniform(
      "sampler2D",
      "model_clippingPlanes",
      ShaderDestination$1.FRAGMENT
    );
    shaderBuilder.addUniform(
      "vec4",
      "model_clippingPlanesEdgeStyle",
      ShaderDestination$1.FRAGMENT
    );
    shaderBuilder.addUniform(
      "mat4",
      "model_clippingPlanesMatrix",
      ShaderDestination$1.FRAGMENT
    );

    shaderBuilder.addFragmentLines([ModelClippingPlanesStageFS]);

    const uniformMap = {
      model_clippingPlanes: function () {
        return clippingPlanes.texture;
      },
      model_clippingPlanesEdgeStyle: function () {
        const style = Color.clone(clippingPlanes.edgeColor);
        style.alpha = clippingPlanes.edgeWidth;
        return style;
      },
      model_clippingPlanesMatrix: function () {
        return model._clippingPlanesMatrix;
      },
    };

    renderResources.uniformMap = combine$2(uniformMap, renderResources.uniformMap);
  };

  /**
   * A pipeline stage for configuring the alpha options for handling translucency.
   *
   * @namespace MaterialPipelineStage
   *
   * @private
   */
  const AlphaPipelineStage = {};
  AlphaPipelineStage.name = "AlphaPipelineStage"; // Helps with debugging

  AlphaPipelineStage.process = function (renderResources, primitive, frameState) {
    const alphaOptions = renderResources.alphaOptions;

    // Ensure the pass is defined
    const model = renderResources.model;
    alphaOptions.pass = defaultValue(alphaOptions.pass, model.opaquePass);

    const renderStateOptions = renderResources.renderStateOptions;
    if (alphaOptions.pass === Pass$1.TRANSLUCENT) {
      renderStateOptions.blending = BlendingState$1.ALPHA_BLEND;
    } else {
      renderStateOptions.blending = BlendingState$1.DISABLED;
    }

    const shaderBuilder = renderResources.shaderBuilder;
    const uniformMap = renderResources.uniformMap;
    const alphaMode = alphaOptions.alphaMode;

    if (alphaMode === AlphaMode$1.MASK) {
      shaderBuilder.addDefine(
        "ALPHA_MODE_MASK",
        undefined,
        ShaderDestination$1.FRAGMENT
      );
      shaderBuilder.addUniform(
        "float",
        "u_alphaCutoff",
        ShaderDestination$1.FRAGMENT
      );
      uniformMap.u_alphaCutoff = function () {
        return alphaOptions.alphaCutoff;
      };
    } else if (alphaMode === AlphaMode$1.BLEND) {
      shaderBuilder.addDefine(
        "ALPHA_MODE_BLEND",
        undefined,
        ShaderDestination$1.FRAGMENT
      );
    } else {
      shaderBuilder.addDefine(
        "ALPHA_MODE_OPAQUE",
        undefined,
        ShaderDestination$1.FRAGMENT
      );
    }
  };

  /**
   * The batch texture stage is responsible for setting up the batch texture for the primitive.
   *
   * @namespace BatchTexturePipelineStage
   * @private
   */
  const BatchTexturePipelineStage = {};
  BatchTexturePipelineStage.name = "BatchTexturePipelineStage"; // Helps with debugging

  /**
   * Processes a primitive. This modifies the following parts of the render resources:
   * <ul>
   *  <li>adds uniforms for the batch texture</li>
   *  <li>adds defines for multiline batch textures</li>
   * </ul>
   *
   * @param {PrimitiveRenderResources} renderResources The render resources for this primitive.
   * @param {ModelComponents.Primitive} primitive The primitive.
   * @param {FrameState} frameState The frame state.
   */
  BatchTexturePipelineStage.process = function (
    renderResources,
    primitive,
    frameState
  ) {
    const shaderBuilder = renderResources.shaderBuilder;
    const batchTextureUniforms = {};

    const model = renderResources.model;

    const featureTable = model.featureTables[model.featureTableId];

    // Number of features in the feature table.
    const featuresLength = featureTable.featuresLength;
    shaderBuilder.addUniform("int", "model_featuresLength");
    batchTextureUniforms.model_featuresLength = function () {
      return featuresLength;
    };

    // Batch texture
    const batchTexture = featureTable.batchTexture;
    shaderBuilder.addUniform("sampler2D", "model_batchTexture");
    batchTextureUniforms.model_batchTexture = function () {
      return defaultValue(batchTexture.batchTexture, batchTexture.defaultTexture);
    };

    // Batch texture step size
    shaderBuilder.addUniform("vec4", "model_textureStep");
    batchTextureUniforms.model_textureStep = function () {
      return batchTexture.textureStep;
    };

    // Batch texture dimensions
    if (batchTexture.textureDimensions.y > 1) {
      shaderBuilder.addDefine("MULTILINE_BATCH_TEXTURE");
      shaderBuilder.addUniform("vec2", "model_textureDimensions");
      batchTextureUniforms.model_textureDimensions = function () {
        return batchTexture.textureDimensions;
      };
    }

    renderResources.uniformMap = combine$2(
      batchTextureUniforms,
      renderResources.uniformMap
    );
  };

  /**
   * An enum describing how the {@link CustomShader} will be added to the
   * fragment shader. This determines how the shader interacts with the material.
   *
   * @enum {String}
   *
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  const CustomShaderMode = {
    /**
     * The custom shader will be used to modify the results of the material stage
     * before lighting is applied.
     *
     * @type {String}
     * @constant
     */
    MODIFY_MATERIAL: "MODIFY_MATERIAL",
    /**
     * The custom shader will be used instead of the material stage. This is a hint
     * to optimize out the material processing code.
     *
     * @type {String}
     * @constant
     */
    REPLACE_MATERIAL: "REPLACE_MATERIAL",
  };

  /**
   * Convert the shader mode to an uppercase identifier for use in GLSL define
   * directives. For example:  <code>#define CUSTOM_SHADER_MODIFY_MATERIAL</code>
   * @param {CustomShaderMode} customShaderMode The shader mode
   * @return {String} The name of the GLSL macro to use
   *
   * @private
   */
  CustomShaderMode.getDefineName = function (customShaderMode) {
    return `CUSTOM_SHADER_${customShaderMode}`;
  };

  var CustomShaderMode$1 = Object.freeze(CustomShaderMode);

  //This file is automatically rebuilt by the Cesium build process.
  var CustomShaderStageVS = "void customShaderStage(\n\
inout czm_modelVertexOutput vsOutput,\n\
inout ProcessedAttributes attributes,\n\
FeatureIds featureIds,\n\
Metadata metadata\n\
) {\n\
VertexInput vsInput;\n\
initializeInputStruct(vsInput, attributes);\n\
vsInput.featureIds = featureIds;\n\
vsInput.metadata = metadata;\n\
vertexMain(vsInput, vsOutput);\n\
attributes.positionMC = vsOutput.positionMC;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var CustomShaderStageFS = "void customShaderStage(\n\
inout czm_modelMaterial material,\n\
ProcessedAttributes attributes,\n\
FeatureIds featureIds,\n\
Metadata metadata\n\
) {\n\
FragmentInput fsInput;\n\
initializeInputStruct(fsInput, attributes);\n\
fsInput.featureIds = featureIds;\n\
fsInput.metadata = metadata;\n\
fragmentMain(fsInput, material);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var FeatureIdStageFS = "void featureIdStage(out FeatureIds featureIds, ProcessedAttributes attributes) {\n\
initializeFeatureIds(featureIds, attributes);\n\
initializeFeatureIdAliases(featureIds);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var FeatureIdStageVS = "void featureIdStage(out FeatureIds featureIds, ProcessedAttributes attributes)\n\
{\n\
initializeFeatureIds(featureIds, attributes);\n\
initializeFeatureIdAliases(featureIds);\n\
setFeatureIdVaryings();\n\
}\n\
";

  /**
   * The feature ID pipeline stage is responsible for processing feature IDs
   * (both attributes and textures), updating the shader in preparation for
   * custom shaders, picking, and/or styling.
   *
   * @namespace FeatureIdPipelineStage
   * @private
   */
  const FeatureIdPipelineStage = {};
  FeatureIdPipelineStage.name = "FeatureIdPipelineStage"; // Helps with debugging

  FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_VS = "FeatureIdsVS";
  FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_FS = "FeatureIdsFS";
  FeatureIdPipelineStage.STRUCT_NAME_FEATURE_IDS = "FeatureIds";
  FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_VS =
    "initializeFeatureIdsVS";
  FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_FS =
    "initializeFeatureIdsFS";
  FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_ID_ALIASES_VS =
    "initializeFeatureIdAliasesVS";
  FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_ID_ALIASES_FS =
    "initializeFeatureIdAliasesFS";
  FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_IDS =
    "void initializeFeatureIds(out FeatureIds featureIds, ProcessedAttributes attributes)";
  FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_ID_ALIASES =
    "void initializeFeatureIdAliases(inout FeatureIds featureIds)";
  FeatureIdPipelineStage.FUNCTION_ID_SET_FEATURE_ID_VARYINGS =
    "setFeatureIdVaryings";
  FeatureIdPipelineStage.FUNCTION_SIGNATURE_SET_FEATURE_ID_VARYINGS =
    "void setFeatureIdVaryings()";

  /**
   * Process a primitive. This modifies the following parts of the render resources:
   * <ul>
   *  <li>Adds the FeatureIds struct and corresponding initialization functions in the vertex and fragment shader</li>
   *  <li>For each feature ID attribute, the attributes were already uploaded in the geometry stage, so just update the shader code </li>
   *  <li>For each feature ID implicit range, a new attribute is created and uploaded to the GPU since gl_VertexID is not available in WebGL 1. The shader is updated with an attribute, varying, and initialization code.</li>
   *  <li>For each feature ID texture, the texture is added to the uniform map, and shader code is added to perform the texture read.</li>
   * </ul>
   *
   * @param {PrimitiveRenderResources} renderResources The render resources for this primitive.
   * @param {ModelComponents.Primitive} primitive The primitive.
   * @param {FrameState} frameState The frame state.
   */
  FeatureIdPipelineStage.process = function (
    renderResources,
    primitive,
    frameState
  ) {
    const shaderBuilder = renderResources.shaderBuilder;
    declareStructsAndFunctions$1(shaderBuilder);

    const instances = renderResources.runtimeNode.node.instances;
    if (defined(instances)) {
      processInstanceFeatureIds(renderResources, instances, frameState);
    }
    processPrimitiveFeatureIds(renderResources, primitive, frameState);

    shaderBuilder.addVertexLines([FeatureIdStageVS]);
    shaderBuilder.addFragmentLines([FeatureIdStageFS]);
  };

  function declareStructsAndFunctions$1(shaderBuilder) {
    // Declare the FeatureIds struct. The vertex shader will only use
    // feature ID attributes, while the fragment shader will also use
    // feature ID textures.
    shaderBuilder.addStruct(
      FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_VS,
      FeatureIdPipelineStage.STRUCT_NAME_FEATURE_IDS,
      ShaderDestination$1.VERTEX
    );
    shaderBuilder.addStruct(
      FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_FS,
      FeatureIdPipelineStage.STRUCT_NAME_FEATURE_IDS,
      ShaderDestination$1.FRAGMENT
    );

    // declare the initializeFeatureIds() function. The details may differ
    // between vertex and fragment shader
    shaderBuilder.addFunction(
      FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_VS,
      FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_IDS,
      ShaderDestination$1.VERTEX
    );
    shaderBuilder.addFunction(
      FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_FS,
      FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_IDS,
      ShaderDestination$1.FRAGMENT
    );

    // declare the initializeFeatureIdAliases() function. The details may differ
    // between vertex and fragment shader
    shaderBuilder.addFunction(
      FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_ID_ALIASES_VS,
      FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_ID_ALIASES,
      ShaderDestination$1.VERTEX
    );
    shaderBuilder.addFunction(
      FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_ID_ALIASES_FS,
      FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_ID_ALIASES,
      ShaderDestination$1.FRAGMENT
    );

    // declare the setFeatureIdVaryings() function in the vertex shader only
    shaderBuilder.addFunction(
      FeatureIdPipelineStage.FUNCTION_ID_SET_FEATURE_ID_VARYINGS,
      FeatureIdPipelineStage.FUNCTION_SIGNATURE_SET_FEATURE_ID_VARYINGS,
      ShaderDestination$1.VERTEX
    );
  }

  function processInstanceFeatureIds(renderResources, instances, frameState) {
    const featureIdsArray = instances.featureIds;
    const count = instances.attributes[0].count;

    for (let i = 0; i < featureIdsArray.length; i++) {
      const featureIds = featureIdsArray[i];
      const variableName = featureIds.positionalLabel;

      if (featureIds instanceof ModelComponents.FeatureIdAttribute) {
        processInstanceAttribute(renderResources, featureIds, variableName);
      } else {
        const instanceDivisor = 1;
        processImplicitRange(
          renderResources,
          featureIds,
          variableName,
          count,
          instanceDivisor,
          frameState
        );
      }

      const label = featureIds.label;
      if (defined(label)) {
        addAlias(renderResources, variableName, label, ShaderDestination$1.BOTH);
      }
    }
  }

  function processPrimitiveFeatureIds(renderResources, primitive, frameState) {
    const featureIdsArray = primitive.featureIds;
    const positionAttribute = ModelExperimentalUtility.getAttributeBySemantic(
      primitive,
      VertexAttributeSemantic$1.POSITION
    );
    const count = positionAttribute.count;

    for (let i = 0; i < featureIdsArray.length; i++) {
      const featureIds = featureIdsArray[i];
      const variableName = featureIds.positionalLabel;

      let aliasDestination = ShaderDestination$1.BOTH;
      if (featureIds instanceof ModelComponents.FeatureIdAttribute) {
        processAttribute$1(renderResources, featureIds, variableName);
      } else if (featureIds instanceof ModelComponents.FeatureIdImplicitRange) {
        processImplicitRange(
          renderResources,
          featureIds,
          variableName,
          count,
          undefined,
          frameState
        );
      } else {
        processTexture$1(renderResources, featureIds, variableName, i, frameState);
        aliasDestination = ShaderDestination$1.FRAGMENT;
      }

      const label = featureIds.label;
      if (defined(label)) {
        addAlias(renderResources, variableName, label, aliasDestination);
      }
    }
  }

  function processInstanceAttribute(
    renderResources,
    featureIdAttribute,
    variableName
  ) {
    // Add a field to the FeatureIds struct.
    // Example:
    // struct FeatureIds {
    //   ...
    //   int instanceFeatureId_n;
    //   ...
    // }
    const shaderBuilder = renderResources.shaderBuilder;
    shaderBuilder.addStructField(
      FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_VS,
      "int",
      variableName
    );
    shaderBuilder.addStructField(
      FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_FS,
      "int",
      variableName
    );

    // Initialize the field from the corresponding attribute.
    // Example: featureIds.instanceFeatureId_n = int(czm_round(attributes.instanceFeatureId_0));
    const setIndex = featureIdAttribute.setIndex;
    const prefix = variableName.replace(/_\d+$/, "_");

    const attributeName = `a_${prefix}${setIndex}`;
    const varyingName = `v_${prefix}${setIndex}`;
    const vertexLine = `featureIds.${variableName} = int(czm_round(${attributeName}));`;
    const fragmentLine = `featureIds.${variableName} = int(czm_round(${varyingName}));`;

    shaderBuilder.addFunctionLines(
      FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_VS,
      [vertexLine]
    );
    shaderBuilder.addFunctionLines(
      FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_FS,
      [fragmentLine]
    );

    // Instanced attributes don't normally need varyings, so add one here
    shaderBuilder.addVarying("float", varyingName);

    // The varying needs initialization in the vertex shader
    // Example:
    // v_instanceFeatureId_n = a_instanceFeatureId_n;
    shaderBuilder.addFunctionLines(
      FeatureIdPipelineStage.FUNCTION_ID_SET_FEATURE_ID_VARYINGS,
      [`${varyingName} = ${attributeName};`]
    );
  }

  function processAttribute$1(renderResources, featureIdAttribute, variableName) {
    // Add a field to the FeatureIds struct.
    // Example:
    // struct FeatureIds {
    //   ...
    //   int featureId_n;
    //   ...
    // }
    const shaderBuilder = renderResources.shaderBuilder;
    shaderBuilder.addStructField(
      FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_VS,
      "int",
      variableName
    );
    shaderBuilder.addStructField(
      FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_FS,
      "int",
      variableName
    );

    // Initialize the field from the corresponding attribute.
    // Example: featureIds.featureId_n = attributes.featureId_0;
    // Since this uses the ProcessedAttributes struct, the line is the same
    // for both vertex and fragment shader.
    const setIndex = featureIdAttribute.setIndex;
    const prefix = variableName.replace(/_\d+$/, "_");

    const initializationLines = [
      `featureIds.${variableName} = int(czm_round(attributes.${prefix}${setIndex}));`,
    ];
    shaderBuilder.addFunctionLines(
      FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_VS,
      initializationLines
    );
    shaderBuilder.addFunctionLines(
      FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_FS,
      initializationLines
    );
  }

  function processImplicitRange(
    renderResources,
    implicitFeatureIds,
    variableName,
    count,
    instanceDivisor,
    frameState
  ) {
    // Generate a vertex attribute for the implicit IDs since WebGL 1 does not
    // support gl_VertexID
    generateImplicitFeatureIdAttribute(
      renderResources,
      implicitFeatureIds,
      count,
      instanceDivisor,
      frameState
    );

    // Declare the vertex attribute in the shader
    // Example: attribute float a_implicit_feature_id_n;
    const shaderBuilder = renderResources.shaderBuilder;
    const implicitAttributeName = `a_implicit_${variableName}`;
    shaderBuilder.addAttribute("float", implicitAttributeName);

    // Also declare the corresponding varyings
    // Example: varying float v_implicit_feature_id_n;
    const implicitVaryingName = `v_implicit_${variableName}`;
    shaderBuilder.addVarying("float", implicitVaryingName);

    // Add a field to the FeatureIds struct.
    // Example:
    // struct FeatureIds {
    //   ...
    //   int featureId_n;
    //   ...
    // }
    shaderBuilder.addStructField(
      FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_VS,
      "int",
      variableName
    );
    shaderBuilder.addStructField(
      FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_FS,
      "int",
      variableName
    );

    // The varying needs initialization in the vertex shader
    // Example:
    // v_implicit_featureId_n = a_implicit_featureId_n;
    shaderBuilder.addFunctionLines(
      FeatureIdPipelineStage.FUNCTION_ID_SET_FEATURE_ID_VARYINGS,
      [`${implicitVaryingName} = ${implicitAttributeName};`]
    );

    // Initialize the field from the generated attribute/varying.
    // Example:
    // featureIds.featureId_n = a_implicit_featureId_n; (VS)
    // featureIds.featureId_n = v_implicit_featureId_n; (FS)
    shaderBuilder.addFunctionLines(
      FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_VS,
      [`featureIds.${variableName} = int(czm_round(${implicitAttributeName}));`]
    );
    shaderBuilder.addFunctionLines(
      FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_FS,
      [`featureIds.${variableName} = int(czm_round(${implicitVaryingName}));`]
    );
  }

  function processTexture$1(
    renderResources,
    featureIdTexture,
    variableName,
    index,
    frameState
  ) {
    // Create the feature ID texture uniform. The index matches the index from
    // the featureIds array, even if this is not consecutive.
    const uniformName = `u_featureIdTexture_${index}`;
    const uniformMap = renderResources.uniformMap;
    const textureReader = featureIdTexture.textureReader;
    uniformMap[uniformName] = function () {
      return defaultValue(
        textureReader.texture,
        frameState.context.defaultTexture
      );
    };

    const channels = textureReader.channels;

    // Add a field to the FeatureIds struct in the fragment shader only
    // Example:
    // struct FeatureIds {
    //   ...
    //   int featureId_n;
    //   ...
    // }
    const shaderBuilder = renderResources.shaderBuilder;
    shaderBuilder.addStructField(
      FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_FS,
      "int",
      variableName
    );

    // Declare the uniform in the fragment shader
    shaderBuilder.addUniform(
      "sampler2D",
      uniformName,
      ShaderDestination$1.FRAGMENT
    );

    // Read one or more channels from the texture
    // example: texture2D(u_featureIdTexture_0, v_texCoord_1).rg
    const texCoord = `v_texCoord_${textureReader.texCoord}`;
    const textureRead = `texture2D(${uniformName}, ${texCoord}).${channels}`;

    // Finally, assign to the struct field. Example:
    // featureIds.featureId_0 = unpacked;
    const initializationLine = `featureIds.${variableName} = czm_unpackUint(${textureRead});`;

    shaderBuilder.addFunctionLines(
      FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_FS,
      [initializationLine]
    );
  }

  function addAlias(renderResources, variableName, alias, shaderDestination) {
    // Add a field to the FeatureIds struct.
    // Example:
    // struct FeatureIds {
    //   ...
    //   int alias;
    //   ...
    // }
    const shaderBuilder = renderResources.shaderBuilder;
    const updateVS = ShaderDestination$1.includesVertexShader(shaderDestination);
    if (updateVS) {
      shaderBuilder.addStructField(
        FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_VS,
        "int",
        alias
      );
    }
    shaderBuilder.addStructField(
      FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_FS,
      "int",
      alias
    );

    // Initialize the field from the original variable
    // Example: featureIds.alias = featureIds.featureId_n;
    const initializationLines = [
      `featureIds.${alias} = featureIds.${variableName};`,
    ];
    if (updateVS) {
      shaderBuilder.addFunctionLines(
        FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_ID_ALIASES_VS,
        initializationLines
      );
    }
    shaderBuilder.addFunctionLines(
      FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_ID_ALIASES_FS,
      initializationLines
    );
  }

  function generateImplicitFeatureIdAttribute(
    renderResources,
    implicitFeatureIds,
    count,
    instanceDivisor,
    frameState
  ) {
    const model = renderResources.model;
    let vertexBuffer;
    let value;
    if (defined(implicitFeatureIds.repeat)) {
      const typedArray = generateImplicitFeatureIdTypedArray(
        implicitFeatureIds,
        count
      );
      vertexBuffer = Buffer$1.createVertexBuffer({
        context: frameState.context,
        typedArray: typedArray,
        usage: BufferUsage$1.STATIC_DRAW,
      });
      vertexBuffer.vertexArrayDestroyable = false;
      model._pipelineResources.push(vertexBuffer);
      const hasCpuCopy = false;
      model.statistics.addBuffer(vertexBuffer, hasCpuCopy);
    } else {
      value = [implicitFeatureIds.offset];
    }

    const generatedFeatureIdAttribute = {
      index: renderResources.attributeIndex++,
      instanceDivisor: instanceDivisor,
      value: value,
      vertexBuffer: vertexBuffer,
      normalize: false,
      componentsPerAttribute: 1,
      componentDatatype: ComponentDatatype$1.FLOAT,
      strideInBytes: ComponentDatatype$1.getSizeInBytes(ComponentDatatype$1.FLOAT),
      offsetInBytes: 0,
    };

    renderResources.attributes.push(generatedFeatureIdAttribute);
  }

  /**
   * Generates a typed array for implicit feature IDs
   * @private
   */
  function generateImplicitFeatureIdTypedArray(implicitFeatureIds, count) {
    const offset = implicitFeatureIds.offset;
    const repeat = implicitFeatureIds.repeat;

    const typedArray = new Float32Array(count);
    for (let i = 0; i < count; i++) {
      typedArray[i] = offset + Math.floor(i / repeat);
    }

    return typedArray;
  }

  //This file is automatically rebuilt by the Cesium build process.
  var MetadataStageFS = "void metadataStage(out Metadata metadata, ProcessedAttributes attributes)\n\
{\n\
initializeMetadata(metadata, attributes);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var MetadataStageVS = "void metadataStage(out Metadata metadata, ProcessedAttributes attributes)\n\
{\n\
initializeMetadata(metadata, attributes);\n\
setMetadataVaryings();\n\
}\n\
";

  /**
   * The metadata pipeline stage processes metadata properties from
   * EXT_structural_metadata and inserts them into a struct in the shader.
   * This struct will be used by {@link CustomShaderPipelineStage} to allow the
   * user to access metadata using {@link CustomShader}
   *
   * @namespace MetadataPipelineStage
   *
   * @private
   */
  const MetadataPipelineStage = {};
  MetadataPipelineStage.name = "MetadataPipelineStage";

  MetadataPipelineStage.STRUCT_ID_METADATA_VS = "MetadataVS";
  MetadataPipelineStage.STRUCT_ID_METADATA_FS = "MetadataFS";
  MetadataPipelineStage.STRUCT_NAME_METADATA = "Metadata";
  MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_VS =
    "initializeMetadataVS";
  MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_FS =
    "initializeMetadataFS";
  MetadataPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_METADATA =
    "void initializeMetadata(out Metadata metadata, ProcessedAttributes attributes)";
  MetadataPipelineStage.FUNCTION_ID_SET_METADATA_VARYINGS = "setMetadataVaryings";
  MetadataPipelineStage.FUNCTION_SIGNATURE_SET_METADATA_VARYINGS =
    "void setMetadataVaryings()";

  /**
   * Process a primitive. This modifies the following parts of the render
   * resources:
   * <ul>
   *   <li>Adds a Metadata struct to the shader</li>
   *   <li>If the primitive has structural metadata, properties are added to the Metadata struct</li>
   *   <li>dynamic functions are added to the shader to initialize the metadata properties</li>
   *   <li>Adds uniforms for property textures to the uniform map as needed</li>
   *   <li>Adds uniforms for offset/scale to the uniform map as needed</li>
   * </ul>
   * @param {PrimitiveRenderResources} renderResources The render resources for the primitive
   * @param {ModelComponents.Primitive} primitive The primitive to be rendered
   * @param {FrameState} frameState The frame state
   * @private
   */
  MetadataPipelineStage.process = function (
    renderResources,
    primitive,
    frameState
  ) {
    const shaderBuilder = renderResources.shaderBuilder;

    // Always declare structs, even if not used
    declareStructsAndFunctions(shaderBuilder);
    shaderBuilder.addVertexLines([MetadataStageVS]);
    shaderBuilder.addFragmentLines([MetadataStageFS]);

    const structuralMetadata = renderResources.model.structuralMetadata;
    if (!defined(structuralMetadata)) {
      return;
    }

    processPropertyAttributes(renderResources, primitive, structuralMetadata);
    processPropertyTextures(renderResources, structuralMetadata);
  };

  function declareStructsAndFunctions(shaderBuilder) {
    // Declare the Metadata struct.
    shaderBuilder.addStruct(
      MetadataPipelineStage.STRUCT_ID_METADATA_VS,
      MetadataPipelineStage.STRUCT_NAME_METADATA,
      ShaderDestination$1.VERTEX
    );
    shaderBuilder.addStruct(
      MetadataPipelineStage.STRUCT_ID_METADATA_FS,
      MetadataPipelineStage.STRUCT_NAME_METADATA,
      ShaderDestination$1.FRAGMENT
    );

    // declare the initializeMetadata() function. The details may differ
    // between vertex and fragment shader
    shaderBuilder.addFunction(
      MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_VS,
      MetadataPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_METADATA,
      ShaderDestination$1.VERTEX
    );
    shaderBuilder.addFunction(
      MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_FS,
      MetadataPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_METADATA,
      ShaderDestination$1.FRAGMENT
    );

    // declare the setMetadataVaryings() function in the vertex shader only.
    shaderBuilder.addFunction(
      MetadataPipelineStage.FUNCTION_ID_SET_METADATA_VARYINGS,
      MetadataPipelineStage.FUNCTION_SIGNATURE_SET_METADATA_VARYINGS,
      ShaderDestination$1.VERTEX
    );
  }

  function processPropertyAttributes(
    renderResources,
    primitive,
    structuralMetadata
  ) {
    const propertyAttributes = structuralMetadata.propertyAttributes;

    if (!defined(propertyAttributes)) {
      return;
    }

    for (let i = 0; i < propertyAttributes.length; i++) {
      const propertyAttribute = propertyAttributes[i];
      const properties = propertyAttribute.properties;
      for (const propertyId in properties) {
        if (properties.hasOwnProperty(propertyId)) {
          const property = properties[propertyId];

          // Get information about the attribute the same way as the
          // GeometryPipelineStage to ensure we have the correct GLSL type and
          // variable name.
          const modelAttribute = ModelExperimentalUtility.getAttributeByName(
            primitive,
            property.attribute
          );
          const attributeInfo = ModelExperimentalUtility.getAttributeInfo(
            modelAttribute
          );

          addPropertyAttributeProperty(
            renderResources,
            attributeInfo,
            propertyId,
            property
          );
        }
      }
    }
  }

  function addPropertyAttributeProperty(
    renderResources,
    attributeInfo,
    propertyId,
    property
  ) {
    const metadataVariable = sanitizeGlslIdentifier(propertyId);
    const attributeVariable = attributeInfo.variableName;

    // in WebGL 1, attributes must have floating point components, so it's safe
    // to assume here that the types will match. Even if the property was
    // normalized, this is handled at upload time, not in the shader.
    const glslType = attributeInfo.glslType;

    const shaderBuilder = renderResources.shaderBuilder;

    // declare the struct field, e.g.
    // struct Metadata {
    //   float property;
    // }
    shaderBuilder.addStructField(
      MetadataPipelineStage.STRUCT_ID_METADATA_VS,
      glslType,
      metadataVariable
    );
    shaderBuilder.addStructField(
      MetadataPipelineStage.STRUCT_ID_METADATA_FS,
      glslType,
      metadataVariable
    );

    let unpackedValue = `attributes.${attributeVariable}`;

    // handle offset/scale transform. This wraps the GLSL expression with
    // the czm_valueTransform() call.
    if (property.hasValueTransform) {
      unpackedValue = addValueTransformUniforms(unpackedValue, {
        renderResources: renderResources,
        glslType: glslType,
        metadataVariable: metadataVariable,
        shaderDestination: ShaderDestination$1.BOTH,
        offset: property.offset,
        scale: property.scale,
      });
    }

    // assign the result to the metadata struct property.
    // e.g. metadata.property = unpackingSteps(attributes.property);
    const initializationLine = `metadata.${metadataVariable} = ${unpackedValue};`;
    shaderBuilder.addFunctionLines(
      MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_VS,
      [initializationLine]
    );
    shaderBuilder.addFunctionLines(
      MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_FS,
      [initializationLine]
    );
  }

  function processPropertyTextures(renderResources, structuralMetadata) {
    const propertyTextures = structuralMetadata.propertyTextures;

    if (!defined(propertyTextures)) {
      return;
    }

    for (let i = 0; i < propertyTextures.length; i++) {
      const propertyTexture = propertyTextures[i];

      const properties = propertyTexture.properties;
      for (const propertyId in properties) {
        if (properties.hasOwnProperty(propertyId)) {
          const property = properties[propertyId];
          if (property.isGpuCompatible()) {
            addPropertyTextureProperty(renderResources, propertyId, property);
          }
        }
      }
    }
  }

  function addPropertyTextureProperty(renderResources, propertyId, property) {
    // Property texture properties may share the same physical texture, so only
    // add the texture uniform the first time we encounter it.
    const textureReader = property.textureReader;
    const textureIndex = textureReader.index;
    const textureUniformName = `u_propertyTexture_${textureIndex}`;
    if (!renderResources.uniformMap.hasOwnProperty(textureUniformName)) {
      addPropertyTextureUniform(
        renderResources,
        textureUniformName,
        textureReader
      );
    }

    const metadataVariable = sanitizeGlslIdentifier(propertyId);
    const glslType = property.getGlslType();

    const shaderBuilder = renderResources.shaderBuilder;
    shaderBuilder.addStructField(
      MetadataPipelineStage.STRUCT_ID_METADATA_FS,
      glslType,
      metadataVariable
    );

    const texCoord = textureReader.texCoord;
    const texCoordVariable = `attributes.texCoord_${texCoord}`;
    const channels = textureReader.channels;
    let unpackedValue = `texture2D(${textureUniformName}, ${texCoordVariable}).${channels}`;

    // Some types need an unpacking step or two. For example, since texture reads
    // are always normalized, UINT8 (not normalized) properties need to be
    // un-normalized in the shader.
    unpackedValue = property.unpackInShader(unpackedValue);

    // handle offset/scale transform. This wraps the GLSL expression with
    // the czm_valueTransform() call.
    if (property.hasValueTransform) {
      unpackedValue = addValueTransformUniforms(unpackedValue, {
        renderResources: renderResources,
        glslType: glslType,
        metadataVariable: metadataVariable,
        shaderDestination: ShaderDestination$1.FRAGMENT,
        offset: property.offset,
        scale: property.scale,
      });
    }

    const initializationLine = `metadata.${metadataVariable} = ${unpackedValue};`;
    shaderBuilder.addFunctionLines(
      MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_FS,
      [initializationLine]
    );
  }

  function addPropertyTextureUniform(
    renderResources,
    uniformName,
    textureReader
  ) {
    const shaderBuilder = renderResources.shaderBuilder;
    shaderBuilder.addUniform(
      "sampler2D",
      uniformName,
      ShaderDestination$1.FRAGMENT
    );

    const uniformMap = renderResources.uniformMap;
    uniformMap[uniformName] = function () {
      return textureReader.texture;
    };
  }

  function addValueTransformUniforms(valueExpression, options) {
    const metadataVariable = options.metadataVariable;
    const offsetUniformName = `u_${metadataVariable}_offset`;
    const scaleUniformName = `u_${metadataVariable}_scale`;

    const renderResources = options.renderResources;
    const shaderBuilder = renderResources.shaderBuilder;
    const glslType = options.glslType;
    const shaderDestination = options.shaderDestination;
    shaderBuilder.addUniform(glslType, offsetUniformName, shaderDestination);
    shaderBuilder.addUniform(glslType, scaleUniformName, shaderDestination);

    const uniformMap = renderResources.uniformMap;
    uniformMap[offsetUniformName] = function () {
      return options.offset;
    };
    uniformMap[scaleUniformName] = function () {
      return options.scale;
    };

    return `czm_valueTransform(${offsetUniformName}, ${scaleUniformName}, ${valueExpression})`;
  }

  function sanitizeGlslIdentifier(identifier) {
    // for use in the shader, the property ID must be a valid GLSL identifier,
    // so replace invalid characters with _
    return identifier.replaceAll(/[^_a-zA-Z0-9]+/g, "_");
  }

  /**
   * The custom shader pipeline stage takes GLSL callbacks from the
   * {@link CustomShader} and inserts them into the overall shader code for the
   * {@link ModelExperimental}. The input to the callback is a struct with many
   * properties that depend on the attributes of the primitive. This shader code
   * is automatically generated by this stage.
   *
   * @namespace CustomShaderPipelineStage
   *
   * @private
   */
  const CustomShaderPipelineStage = {};
  CustomShaderPipelineStage.name = "CustomShaderPipelineStage"; // Helps with debugging

  CustomShaderPipelineStage.STRUCT_ID_ATTRIBUTES_VS = "AttributesVS";
  CustomShaderPipelineStage.STRUCT_ID_ATTRIBUTES_FS = "AttributesFS";
  CustomShaderPipelineStage.STRUCT_NAME_ATTRIBUTES = "Attributes";
  CustomShaderPipelineStage.STRUCT_ID_VERTEX_INPUT = "VertexInput";
  CustomShaderPipelineStage.STRUCT_NAME_VERTEX_INPUT = "VertexInput";
  CustomShaderPipelineStage.STRUCT_ID_FRAGMENT_INPUT = "FragmentInput";
  CustomShaderPipelineStage.STRUCT_NAME_FRAGMENT_INPUT = "FragmentInput";
  CustomShaderPipelineStage.FUNCTION_ID_INITIALIZE_INPUT_STRUCT_VS =
    "initializeInputStructVS";
  CustomShaderPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_INPUT_STRUCT_VS =
    "void initializeInputStruct(out VertexInput vsInput, ProcessedAttributes attributes)";
  CustomShaderPipelineStage.FUNCTION_ID_INITIALIZE_INPUT_STRUCT_FS =
    "initializeInputStructFS";
  CustomShaderPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_INPUT_STRUCT_FS =
    "void initializeInputStruct(out FragmentInput fsInput, ProcessedAttributes attributes)";

  /**
   * Process a primitive. This modifies the following parts of the render
   * resources:
   * <ul>
   *   <li>Modifies the shader to include the custom shader code to the vertex and fragment shaders</li>
   *   <li>Modifies the shader to include automatically-generated structs that serve as input to the custom shader callbacks </li>
   *   <li>Modifies the shader to include any additional user-defined uniforms</li>
   *   <li>Modifies the shader to include any additional user-defined varyings</li>
   *   <li>Adds any user-defined uniforms to the uniform map</li>
   *   <li>If the user specified a lighting model, the settings are overridden in the render resources</li>
   * </ul>
   * <p>
   * This pipeline stage is designed to fail gracefully where possible. If the
   * primitive does not have the right attributes to satisfy the shader code,
   * defaults will be inferred (when reasonable to do so). If not, the custom
   * shader will be disabled.
   * <p>
   *
   * @param {PrimitiveRenderResources} renderResources The render resources for the primitive
   * @param {ModelComponents.Primitive} primitive The primitive to be rendered
   * @param {FrameState} frameState The frame state.
   * @private
   */
  CustomShaderPipelineStage.process = function (
    renderResources,
    primitive,
    frameState
  ) {
    const shaderBuilder = renderResources.shaderBuilder;
    const customShader = renderResources.model.customShader;

    // Check the lighting model and translucent options first, as sometimes
    // these are used even if there is no vertex or fragment shader text.

    // if present, the lighting model overrides the material's lighting model.
    if (defined(customShader.lightingModel)) {
      renderResources.lightingOptions.lightingModel = customShader.lightingModel;
    }

    const alphaOptions = renderResources.alphaOptions;
    if (customShader.isTranslucent) {
      alphaOptions.pass = Pass$1.TRANSLUCENT;
      alphaOptions.alphaMode = AlphaMode$1.BLEND;
    } else {
      // Use the default pass (either OPAQUE or 3D_TILES), regardless of whether
      // the material pipeline stage used translucent. The default is configured
      // in AlphaPipelineStage
      alphaOptions.pass = undefined;
      alphaOptions.alphaMode = AlphaMode$1.OPAQUE;
    }

    // Generate lines of code for the shader, but don't add them to the shader
    // yet.
    const generatedCode = generateShaderLines(customShader, primitive);

    // In some corner cases, the primitive may not be compatible with the
    // shader. In this case, skip the custom shader.
    if (!generatedCode.customShaderEnabled) {
      return;
    }
    addLinesToShader(shaderBuilder, customShader, generatedCode);

    // the input to the fragment shader may include a low-precision ECEF position
    if (generatedCode.shouldComputePositionWC) {
      shaderBuilder.addDefine(
        "COMPUTE_POSITION_WC",
        undefined,
        ShaderDestination$1.BOTH
      );
    }

    if (defined(customShader.vertexShaderText)) {
      shaderBuilder.addDefine(
        "HAS_CUSTOM_VERTEX_SHADER",
        undefined,
        ShaderDestination$1.VERTEX
      );
    }

    if (defined(customShader.fragmentShaderText)) {
      shaderBuilder.addDefine(
        "HAS_CUSTOM_FRAGMENT_SHADER",
        undefined,
        ShaderDestination$1.FRAGMENT
      );

      // add defines like CUSTOM_SHADER_MODIFY_MATERIAL
      const shaderModeDefine = CustomShaderMode$1.getDefineName(customShader.mode);
      shaderBuilder.addDefine(
        shaderModeDefine,
        undefined,
        ShaderDestination$1.FRAGMENT
      );
    }

    const uniforms = customShader.uniforms;
    for (const uniformName in uniforms) {
      if (uniforms.hasOwnProperty(uniformName)) {
        const uniform = uniforms[uniformName];
        shaderBuilder.addUniform(uniform.type, uniformName);
      }
    }

    const varyings = customShader.varyings;
    for (const varyingName in varyings) {
      if (varyings.hasOwnProperty(varyingName)) {
        const varyingType = varyings[varyingName];
        shaderBuilder.addVarying(varyingType, varyingName);
      }
    }

    renderResources.uniformMap = combine$2(
      renderResources.uniformMap,
      customShader.uniformMap
    );
  };

  function getAttributesByName(attributes) {
    const names = {};
    for (let i = 0; i < attributes.length; i++) {
      const attribute = attributes[i];
      const attributeInfo = ModelExperimentalUtility.getAttributeInfo(attribute);

      names[attributeInfo.variableName] = attributeInfo;
    }
    return names;
  }

  // GLSL types of standard attribute types when uniquely defined
  const attributeTypeLUT = {
    position: "vec3",
    normal: "vec3",
    tangent: "vec3",
    bitangent: "vec3",
    texCoord: "vec2",
    color: "vec4",
    joints: "ivec4",
    weights: "vec4",
  };

  // Corresponding attribute values
  const attributeDefaultValueLUT = {
    position: "vec3(0.0)",
    normal: "vec3(0.0, 0.0, 1.0)",
    tangent: "vec3(1.0, 0.0, 0.0)",
    bitangent: "vec3(0.0, 1.0, 0.0)",
    texCoord: "vec2(0.0)",
    color: "vec4(1.0)",
    joints: "ivec4(0)",
    weights: "vec4(0.0)",
  };

  function inferAttributeDefaults(attributeName) {
    // remove trailing set indices. E.g. "texCoord_0" -> "texCoord"
    let trimmed = attributeName.replace(/_[0-9]+$/, "");
    // also remove the MC/EC since they will have the same default value
    trimmed = trimmed.replace(/(MC|EC)$/, "");

    const glslType = attributeTypeLUT[trimmed];
    const value = attributeDefaultValueLUT[trimmed];

    // - _CUSTOM_ATTRIBUTE has an unknown type.
    if (!defined(glslType)) {
      return undefined;
    }

    return {
      attributeField: [glslType, attributeName],
      value: value,
    };
  }

  function generateVertexShaderLines(
    customShader,
    attributesByName,
    vertexLines
  ) {
    const categories = partitionAttributes(
      attributesByName,
      customShader.usedVariablesVertex.attributeSet,
      false
    );
    const addToShader = categories.addToShader;
    const needsDefault = categories.missingAttributes;

    let variableName;
    let vertexInitialization;
    const attributeFields = [];
    const initializationLines = [];
    for (variableName in addToShader) {
      if (addToShader.hasOwnProperty(variableName)) {
        const attributeInfo = addToShader[variableName];
        const attributeField = [attributeInfo.glslType, variableName];
        attributeFields.push(attributeField);

        // Initializing attribute structs are just a matter of copying the
        // attribute or varying: E.g.:
        // "    vsInput.attributes.position = a_position;"
        vertexInitialization = `vsInput.attributes.${variableName} = attributes.${variableName};`;
        initializationLines.push(vertexInitialization);
      }
    }

    for (let i = 0; i < needsDefault.length; i++) {
      variableName = needsDefault[i];
      const attributeDefaults = inferAttributeDefaults(variableName);
      if (!defined(attributeDefaults)) {
        CustomShaderPipelineStage._oneTimeWarning(
          "CustomShaderPipelineStage.incompatiblePrimitiveVS",
          `Primitive is missing attribute ${variableName}, disabling custom vertex shader`
        );
        // This primitive isn't compatible with the shader. Return early
        // to skip the vertex shader
        return;
      }

      attributeFields.push(attributeDefaults.attributeField);
      vertexInitialization = `vsInput.attributes.${variableName} = ${attributeDefaults.value};`;
      initializationLines.push(vertexInitialization);
    }

    vertexLines.enabled = true;
    vertexLines.attributeFields = attributeFields;
    vertexLines.initializationLines = initializationLines;
  }

  function generatePositionBuiltins(customShader) {
    const attributeFields = [];
    const initializationLines = [];
    const usedVariables = customShader.usedVariablesFragment.attributeSet;

    // Model space position is the same position as in the glTF accessor,
    // this is already added to the shader with other attributes.

    // World coordinates in ECEF coordinates. Note that this is
    // low precision (32-bit floats) on the GPU.
    if (usedVariables.hasOwnProperty("positionWC")) {
      attributeFields.push(["vec3", "positionWC"]);
      initializationLines.push(
        "fsInput.attributes.positionWC = attributes.positionWC;"
      );
    }

    // position in eye coordinates
    if (usedVariables.hasOwnProperty("positionEC")) {
      attributeFields.push(["vec3", "positionEC"]);
      initializationLines.push(
        "fsInput.attributes.positionEC = attributes.positionEC;"
      );
    }

    return {
      attributeFields: attributeFields,
      initializationLines: initializationLines,
    };
  }

  function generateFragmentShaderLines(
    customShader,
    attributesByName,
    fragmentLines
  ) {
    const categories = partitionAttributes(
      attributesByName,
      customShader.usedVariablesFragment.attributeSet,
      true
    );
    const addToShader = categories.addToShader;
    const needsDefault = categories.missingAttributes;

    let variableName;
    let fragmentInitialization;
    const attributeFields = [];
    const initializationLines = [];
    for (variableName in addToShader) {
      if (addToShader.hasOwnProperty(variableName)) {
        const attributeInfo = addToShader[variableName];

        const attributeField = [attributeInfo.glslType, variableName];
        attributeFields.push(attributeField);

        // Initializing attribute structs are just a matter of copying the
        // value from the processed attributes
        // "    fsInput.attributes.positionMC = attributes.positionMC;"
        fragmentInitialization = `fsInput.attributes.${variableName} = attributes.${variableName};`;
        initializationLines.push(fragmentInitialization);
      }
    }

    for (let i = 0; i < needsDefault.length; i++) {
      variableName = needsDefault[i];
      const attributeDefaults = inferAttributeDefaults(variableName);
      if (!defined(attributeDefaults)) {
        CustomShaderPipelineStage._oneTimeWarning(
          "CustomShaderPipelineStage.incompatiblePrimitiveFS",
          `Primitive is missing attribute ${variableName}, disabling custom fragment shader.`
        );

        // This primitive isn't compatible with the shader. Return early
        // so the fragment shader is skipped
        return;
      }

      attributeFields.push(attributeDefaults.attributeField);
      fragmentInitialization = `fsInput.attributes.${variableName} = ${attributeDefaults.value};`;
      initializationLines.push(fragmentInitialization);
    }

    // Built-ins for positions in various coordinate systems.
    const positionBuiltins = generatePositionBuiltins(customShader);

    fragmentLines.enabled = true;
    fragmentLines.attributeFields = attributeFields.concat(
      positionBuiltins.attributeFields
    );
    fragmentLines.initializationLines = positionBuiltins.initializationLines.concat(
      initializationLines
    );
  }

  // These attributes are derived from positionMC, and are handled separately
  // from other attributes
  const builtinAttributes = {
    positionWC: true,
    positionEC: true,
  };

  function partitionAttributes(
    primitiveAttributes,
    shaderAttributeSet,
    isFragmentShader
  ) {
    // shaderAttributes = set of all attributes used in the shader
    // primitiveAttributes = set of all the primitive's attributes
    // partition into three categories:
    // - addToShader = shaderAttributes intersect primitiveAttributes
    // - missingAttributes = shaderAttributes - primitiveAttributes - builtinAttributes
    // - unneededAttributes = (primitiveAttributes - shaderAttributes) U builtinAttributes
    //
    // addToShader are attributes that should be added to the shader.
    // missingAttributes are attributes for which we need to provide a default value
    // unneededAttributes are other attributes that can be skipped.

    let renamed;
    let attributeName;
    const addToShader = {};
    for (attributeName in primitiveAttributes) {
      if (primitiveAttributes.hasOwnProperty(attributeName)) {
        const attribute = primitiveAttributes[attributeName];

        // normals and tangents are in model coordinates in the attributes but
        // in eye coordinates in the fragment shader.
        renamed = attributeName;
        if (isFragmentShader && attributeName === "normalMC") {
          renamed = "normalEC";
        } else if (isFragmentShader && attributeName === "tangentMC") {
          renamed = "tangentEC";
        }

        if (shaderAttributeSet.hasOwnProperty(renamed)) {
          addToShader[renamed] = attribute;
        }
      }
    }

    const missingAttributes = [];
    for (attributeName in shaderAttributeSet) {
      if (shaderAttributeSet.hasOwnProperty(attributeName)) {
        if (builtinAttributes.hasOwnProperty(attributeName)) {
          // Builtins are handled separately from attributes, so skip them here
          continue;
        }

        // normals and tangents are in model coordinates in the attributes but
        // in eye coordinates in the fragment shader.
        renamed = attributeName;
        if (isFragmentShader && attributeName === "normalEC") {
          renamed = "normalMC";
        } else if (isFragmentShader && attributeName === "tangentEC") {
          renamed = "tangentMC";
        }

        if (!primitiveAttributes.hasOwnProperty(renamed)) {
          missingAttributes.push(attributeName);
        }
      }
    }

    return {
      addToShader: addToShader,
      missingAttributes: missingAttributes,
    };
  }

  function generateShaderLines(customShader, primitive) {
    // Assume shader code is disabled unless proven otherwise
    const vertexLines = {
      enabled: false,
    };
    const fragmentLines = {
      enabled: false,
    };

    // Attempt to generate vertex and fragment shader lines before adding any
    // code to the shader.
    const attributesByName = getAttributesByName(primitive.attributes);
    if (defined(customShader.vertexShaderText)) {
      generateVertexShaderLines(customShader, attributesByName, vertexLines);
    }

    if (defined(customShader.fragmentShaderText)) {
      generateFragmentShaderLines(customShader, attributesByName, fragmentLines);
    }

    // positionWC must be computed in the vertex shader
    // for use in the fragmentShader. However, this can be skipped if:
    // - positionWC isn't used in the fragment shader
    // - or the fragment shader is disabled
    const attributeSetFS = customShader.usedVariablesFragment.attributeSet;
    const shouldComputePositionWC =
      attributeSetFS.hasOwnProperty("positionWC") && fragmentLines.enabled;

    // Return any generated shader code along with some flags to indicate which
    // defines should be added.
    return {
      vertexLines: vertexLines,
      fragmentLines: fragmentLines,
      vertexLinesEnabled: vertexLines.enabled,
      fragmentLinesEnabled: fragmentLines.enabled,
      customShaderEnabled: vertexLines.enabled || fragmentLines.enabled,
      shouldComputePositionWC: shouldComputePositionWC,
    };
  }

  function addVertexLinesToShader(shaderBuilder, vertexLines) {
    // Vertex Lines ---------------------------------------------------------

    let i;
    let structId = CustomShaderPipelineStage.STRUCT_ID_ATTRIBUTES_VS;
    shaderBuilder.addStruct(
      structId,
      CustomShaderPipelineStage.STRUCT_NAME_ATTRIBUTES,
      ShaderDestination$1.VERTEX
    );

    const attributeFields = vertexLines.attributeFields;
    for (i = 0; i < attributeFields.length; i++) {
      const field = attributeFields[i];
      const glslType = field[0];
      const variableName = field[1];
      shaderBuilder.addStructField(structId, glslType, variableName);
    }

    // This could be hard-coded, but the symmetry with other structs makes unit
    // tests more convenient
    structId = CustomShaderPipelineStage.STRUCT_ID_VERTEX_INPUT;
    shaderBuilder.addStruct(
      structId,
      CustomShaderPipelineStage.STRUCT_NAME_VERTEX_INPUT,
      ShaderDestination$1.VERTEX
    );
    shaderBuilder.addStructField(
      structId,
      CustomShaderPipelineStage.STRUCT_NAME_ATTRIBUTES,
      "attributes"
    );
    // Add FeatureIds struct from the Feature ID stage
    shaderBuilder.addStructField(
      structId,
      FeatureIdPipelineStage.STRUCT_NAME_FEATURE_IDS,
      "featureIds"
    );
    // Add Metadata struct from the metadata stage
    shaderBuilder.addStructField(
      structId,
      MetadataPipelineStage.STRUCT_NAME_METADATA,
      "metadata"
    );

    const functionId =
      CustomShaderPipelineStage.FUNCTION_ID_INITIALIZE_INPUT_STRUCT_VS;
    shaderBuilder.addFunction(
      functionId,
      CustomShaderPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_INPUT_STRUCT_VS,
      ShaderDestination$1.VERTEX
    );

    const initializationLines = vertexLines.initializationLines;
    shaderBuilder.addFunctionLines(functionId, initializationLines);
  }

  function addFragmentLinesToShader(shaderBuilder, fragmentLines) {
    let i;
    let structId = CustomShaderPipelineStage.STRUCT_ID_ATTRIBUTES_FS;
    shaderBuilder.addStruct(
      structId,
      CustomShaderPipelineStage.STRUCT_NAME_ATTRIBUTES,
      ShaderDestination$1.FRAGMENT
    );

    let field;
    let glslType;
    let variableName;
    const attributeFields = fragmentLines.attributeFields;
    for (i = 0; i < attributeFields.length; i++) {
      field = attributeFields[i];
      glslType = field[0];
      variableName = field[1];
      shaderBuilder.addStructField(structId, glslType, variableName);
    }

    structId = CustomShaderPipelineStage.STRUCT_ID_FRAGMENT_INPUT;
    shaderBuilder.addStruct(
      structId,
      CustomShaderPipelineStage.STRUCT_NAME_FRAGMENT_INPUT,
      ShaderDestination$1.FRAGMENT
    );
    shaderBuilder.addStructField(
      structId,
      CustomShaderPipelineStage.STRUCT_NAME_ATTRIBUTES,
      "attributes"
    );
    // Add FeatureIds struct from the Feature ID stage
    shaderBuilder.addStructField(
      structId,
      FeatureIdPipelineStage.STRUCT_NAME_FEATURE_IDS,
      "featureIds"
    );
    // Add Metadata struct from the metadata stage
    shaderBuilder.addStructField(
      structId,
      MetadataPipelineStage.STRUCT_NAME_METADATA,
      "metadata"
    );

    const functionId =
      CustomShaderPipelineStage.FUNCTION_ID_INITIALIZE_INPUT_STRUCT_FS;
    shaderBuilder.addFunction(
      functionId,
      CustomShaderPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_INPUT_STRUCT_FS,
      ShaderDestination$1.FRAGMENT
    );

    const initializationLines = fragmentLines.initializationLines;
    shaderBuilder.addFunctionLines(functionId, initializationLines);
  }

  function addLinesToShader(shaderBuilder, customShader, generatedCode) {
    const vertexLines = generatedCode.vertexLines;
    if (vertexLines.enabled) {
      addVertexLinesToShader(shaderBuilder, vertexLines);

      shaderBuilder.addVertexLines([
        "#line 0",
        customShader.vertexShaderText,
        CustomShaderStageVS,
      ]);
    }

    const fragmentLines = generatedCode.fragmentLines;
    if (fragmentLines.enabled) {
      addFragmentLinesToShader(shaderBuilder, fragmentLines);

      shaderBuilder.addFragmentLines([
        "#line 0",
        customShader.fragmentShaderText,
        CustomShaderStageFS,
      ]);
    }
  }

  // exposed for testing.
  CustomShaderPipelineStage._oneTimeWarning = oneTimeWarning;

  //This file is automatically rebuilt by the Cesium build process.
  var CPUStylingStageVS = "void filterByPassType(inout vec3 positionMC, vec4 featureColor)\n\
{\n\
bool styleTranslucent = (featureColor.a != 1.0);\n\
if (czm_pass == czm_passTranslucent && !styleTranslucent && !model_commandTranslucent)\n\
{\n\
#ifdef HAS_SILHOUETTE\n\
positionMC *= float(model_silhouettePass);\n\
#else\n\
positionMC *= 0.0;\n\
#endif\n\
}\n\
else if (czm_pass != czm_passTranslucent && styleTranslucent)\n\
{\n\
positionMC *= 0.0;\n\
}\n\
}\n\
void cpuStylingStage(inout vec3 positionMC, inout SelectedFeature feature)\n\
{\n\
float show = ceil(feature.color.a);\n\
positionMC *= show;\n\
#ifdef HAS_SELECTED_FEATURE_ID_ATTRIBUTE\n\
filterByPassType(positionMC, feature.color);\n\
#endif\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var CPUStylingStageFS = "void filterByPassType(vec4 featureColor)\n\
{\n\
bool styleTranslucent = (featureColor.a != 1.0);\n\
if (czm_pass == czm_passTranslucent && !styleTranslucent && !model_commandTranslucent)\n\
{\n\
#ifdef HAS_SILHOUETTE\n\
if(!model_silhouettePass) {\n\
discard;\n\
}\n\
#else\n\
discard;\n\
#endif\n\
}\n\
else if (czm_pass != czm_passTranslucent && styleTranslucent)\n\
{\n\
discard;\n\
}\n\
}\n\
void cpuStylingStage(inout czm_modelMaterial material, SelectedFeature feature)\n\
{\n\
vec4 featureColor = feature.color;\n\
if (featureColor.a == 0.0)\n\
{\n\
discard;\n\
}\n\
#ifdef HAS_SELECTED_FEATURE_ID_TEXTURE\n\
filterByPassType(featureColor);\n\
#endif\n\
featureColor = czm_gammaCorrect(featureColor);\n\
float highlight = ceil(model_colorBlend);\n\
material.diffuse *= mix(featureColor.rgb, vec3(1.0), highlight);\n\
material.alpha *= featureColor.a;\n\
}\n\
";

  /**
   * The CPU styling stage is responsible for ensuring that the feature's color is applied at runtime.
   *
   * @namespace CPUStylingPipelineStage
   *
   * @private
   */
  const CPUStylingPipelineStage = {};
  CPUStylingPipelineStage.name = "CPUStylingPipelineStage"; // Helps with debugging

  /**
   * Processes a primitive. This modifies the following parts of the render resources:
   * <ul>
   *  <li>adds the styling code to both the vertex and fragment shaders</li>
   *  <li>adds the define to trigger the stage's shader functions</li>
   *  <li>adds a uniform with the model's color blend mode and amount</li>
   *  <li>sets a variable in the render resources denoting whether or not the model has translucent colors that will require multiple draw commands</li>
   * </ul>
   *
   * @param {PrimitiveRenderResources} renderResources The render resources for this primitive.
   * @param {ModelComponents.Primitive} primitive The primitive.
   * @param {FrameState} frameState The frame state.
   *
   * @private
   */
  CPUStylingPipelineStage.process = function (
    renderResources,
    primitive,
    frameState
  ) {
    const model = renderResources.model;
    const shaderBuilder = renderResources.shaderBuilder;

    shaderBuilder.addVertexLines([CPUStylingStageVS]);
    shaderBuilder.addFragmentLines([CPUStylingStageFS]);
    shaderBuilder.addDefine("USE_CPU_STYLING", undefined, ShaderDestination$1.BOTH);

    // These uniforms may have already been added by the ModelColorStage if a static
    // color is applied.
    if (!defined(model.color)) {
      shaderBuilder.addUniform(
        "float",
        ModelColorPipelineStage.COLOR_BLEND_UNIFORM_NAME,
        ShaderDestination$1.FRAGMENT
      );
      renderResources.uniformMap[
        ModelColorPipelineStage.COLOR_BLEND_UNIFORM_NAME
      ] = function () {
        return ColorBlendMode$1.getColorBlend(
          model.colorBlendMode,
          model.colorBlendAmount
        );
      };
    }

    shaderBuilder.addUniform(
      "bool",
      "model_commandTranslucent",
      ShaderDestination$1.BOTH
    );
    renderResources.uniformMap.model_commandTranslucent = function () {
      // always check the current value, because custom shaders may
      // change the value with the isTranslucent flag
      return renderResources.alphaOptions.pass === Pass$1.TRANSLUCENT;
    };

    const featureTable = model.featureTables[model.featureTableId];
    const styleCommandsNeeded = StyleCommandsNeeded$1.getStyleCommandsNeeded(
      featureTable.featuresLength,
      featureTable.batchTexture.translucentFeaturesLength
    );

    if (styleCommandsNeeded !== StyleCommandsNeeded$1.ALL_OPAQUE) {
      renderResources.alphaOptions.alphaMode = AlphaMode$1.BLEND;
    }

    renderResources.styleCommandsNeeded = styleCommandsNeeded;
  };

  /**
   * The dequantization stage generates shader code to dequantize attributes
   * in the vertex shader
   *
   * @namespace DequantizationPipelineStage
   *
   * @private
   */
  const DequantizationPipelineStage = {};
  DequantizationPipelineStage.name = "DequantizationPipelineStage"; // Helps with debugging

  DequantizationPipelineStage.FUNCTION_ID_DEQUANTIZATION_STAGE_VS =
    "dequantizationStage";
  DequantizationPipelineStage.FUNCTION_SIGNATURE_DEQUANTIZATION_STAGE_VS =
    "void dequantizationStage(inout ProcessedAttributes attributes)";

  /**
   * Process a primitive with quantized attributes. This stage modifies the
   * following parts of the render resources:
   * <ul>
   *  <li>generates dequantization function and adds it to the shader</li>
   *  <li>adds any uniforms needed for dequantization to the shader and uniform map</li>
   * </ul>
   *
   * @param {PrimitiveRenderResources} renderResources The render resources for this primitive.
   * @param {ModelComponents.Primitive} primitive The primitive
   * @param {FrameState} frameState The frame state.
   *
   * @private
   */
  DequantizationPipelineStage.process = function (
    renderResources,
    primitive,
    frameState
  ) {
    const shaderBuilder = renderResources.shaderBuilder;
    shaderBuilder.addFunction(
      DequantizationPipelineStage.FUNCTION_ID_DEQUANTIZATION_STAGE_VS,
      DequantizationPipelineStage.FUNCTION_SIGNATURE_DEQUANTIZATION_STAGE_VS,
      ShaderDestination$1.VERTEX
    );

    shaderBuilder.addDefine(
      "USE_DEQUANTIZATION",
      undefined,
      ShaderDestination$1.VERTEX
    );

    const attributes = primitive.attributes;
    for (let i = 0; i < attributes.length; i++) {
      const attribute = attributes[i];
      const quantization = attribute.quantization;
      if (!defined(quantization)) {
        // Non-quantized attributes were already handled in GeometryPipelineStage
        continue;
      }

      const attributeInfo = ModelExperimentalUtility.getAttributeInfo(attribute);
      updateDequantizationFunction(shaderBuilder, attributeInfo);
      addDequantizationUniforms(renderResources, attributeInfo);
    }
  };

  function addDequantizationUniforms(renderResources, attributeInfo) {
    const shaderBuilder = renderResources.shaderBuilder;
    const uniformMap = renderResources.uniformMap;
    const variableName = attributeInfo.variableName;
    const quantization = attributeInfo.attribute.quantization;

    if (quantization.octEncoded) {
      const normalizationRange = `model_normalizationRange_${variableName}`;
      shaderBuilder.addUniform(
        "float",
        normalizationRange,
        ShaderDestination$1.VERTEX
      );
      uniformMap[normalizationRange] = function () {
        return quantization.normalizationRange;
      };
    } else {
      const offset = `model_quantizedVolumeOffset_${variableName}`;
      const stepSize = `model_quantizedVolumeStepSize_${variableName}`;
      const glslType = attributeInfo.glslType;
      shaderBuilder.addUniform(glslType, offset, ShaderDestination$1.VERTEX);
      shaderBuilder.addUniform(glslType, stepSize, ShaderDestination$1.VERTEX);

      let quantizedVolumeOffset = quantization.quantizedVolumeOffset;
      let quantizedVolumeStepSize = quantization.quantizedVolumeStepSize;

      // COLOR_n is promoted to a vec4 in the shader, so the alpha value
      // defaults to 1. For correctness, the quantization uniforms must be
      // promoted to vec4s. The alpha values are chosen so the alpha
      // dequantization is the identity, i.e. 0.0 + 1.0 * color.a
      if (/^color_\d+$/.test(variableName)) {
        quantizedVolumeOffset = promoteToVec4(quantizedVolumeOffset, 0);
        quantizedVolumeStepSize = promoteToVec4(quantizedVolumeStepSize, 1);
      }

      uniformMap[offset] = function () {
        return quantizedVolumeOffset;
      };

      uniformMap[stepSize] = function () {
        return quantizedVolumeStepSize;
      };
    }
  }

  function promoteToVec4(value, defaultAlpha) {
    if (value instanceof Cartesian4) {
      return value;
    }

    return new Cartesian4(value.x, value.y, value.z, defaultAlpha);
  }

  function updateDequantizationFunction(shaderBuilder, attributeInfo) {
    const variableName = attributeInfo.variableName;
    const quantization = attributeInfo.attribute.quantization;

    let line;
    if (quantization.octEncoded) {
      line = generateOctDecodeLine(variableName, quantization);
    } else {
      line = generateDequantizeLine(variableName);
    }

    shaderBuilder.addFunctionLines(
      DequantizationPipelineStage.FUNCTION_ID_DEQUANTIZATION_STAGE_VS,
      [line]
    );
  }

  function generateOctDecodeLine(variableName, quantization) {
    const structField = `attributes.${variableName}`;

    const quantizedAttribute = `a_quantized_${variableName}`;
    const normalizationRange = `model_normalizationRange_${variableName}`;

    // Draco stores things as .zxy instead of xyz, so be explicit about the
    // swizzle to avoid confusion
    const swizzle = quantization.octEncodedZXY ? ".zxy" : ".xyz";

    // This generates lines such as:
    // attributes.normal = czm_octDecode(a_quantized_normal, model_normalizationRange_normal).zxy;
    return `${structField} = czm_octDecode(${quantizedAttribute}, ${normalizationRange})${swizzle};`;
  }

  function generateDequantizeLine(variableName) {
    const structField = `attributes.${variableName}`;
    const quantizedAttribute = `a_quantized_${variableName}`;
    const offset = `model_quantizedVolumeOffset_${variableName}`;
    const stepSize = `model_quantizedVolumeStepSize_${variableName}`;

    // This generates lines such as:
    // attributes.texCoord_0 = model_quantizedVolumeOffset_texCoord_0 + a_quantized_texCoord_0 * model_quantizedVolumeStepSize;
    return `${structField} = ${offset} + ${quantizedAttribute} * ${stepSize};`;
  }

  //This file is automatically rebuilt by the Cesium build process.
  var GeometryStageFS = "void geometryStage(out ProcessedAttributes attributes)\n\
{\n\
attributes.positionMC = v_positionMC;\n\
attributes.positionEC = v_positionEC;\n\
#ifdef COMPUTE_POSITION_WC\n\
attributes.positionWC = v_positionWC;\n\
#endif\n\
#ifdef HAS_NORMALS\n\
attributes.normalEC = normalize(v_normalEC);\n\
#endif\n\
#ifdef HAS_TANGENTS\n\
attributes.tangentEC = normalize(v_tangentEC);\n\
#endif\n\
#ifdef HAS_BITANGENTS\n\
attributes.bitangentEC = normalize(v_bitangentEC);\n\
#endif\n\
setDynamicVaryings(attributes);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var GeometryStageVS = "void geometryStage(inout ProcessedAttributes attributes, mat4 modelView, mat3 normal)\n\
{\n\
vec3 positionMC = attributes.positionMC;\n\
v_positionMC = positionMC;\n\
v_positionEC = (modelView * vec4(positionMC, 1.0)).xyz;\n\
#if defined(USE_2D_POSITIONS) || defined(USE_2D_INSTANCING)\n\
vec3 position2D = attributes.position2D;\n\
vec3 positionEC = (u_modelView2D * vec4(position2D, 1.0)).xyz;\n\
gl_Position = czm_projection * vec4(positionEC, 1.0);\n\
#else\n\
gl_Position = czm_projection * vec4(v_positionEC, 1.0);\n\
#endif\n\
#ifdef COMPUTE_POSITION_WC\n\
v_positionWC = (czm_model * vec4(positionMC, 1.0)).xyz;\n\
#endif\n\
#ifdef HAS_NORMALS\n\
v_normalEC = normal * attributes.normalMC;\n\
#endif\n\
#ifdef HAS_TANGENTS\n\
v_tangentEC = normalize(normal * attributes.tangentMC);\n\
#endif\n\
#ifdef HAS_BITANGENTS\n\
v_bitangentEC = normalize(normal * attributes.bitangentMC);\n\
#endif\n\
setDynamicVaryings(attributes);\n\
}\n\
";

  /**
   * An enum to distinguish the different uses for {@link ModelExperimental},
   * which include individual glTF models, and various 3D Tiles formats
   * (including glTF via <code>3DTILES_content_gltf</code>).
   *
   * @enum {String}
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  const ModelExperimentalType = {
    /**
     * An individual glTF model.
     * <p>
     * Not to be confused with {@link ModelExperimentalType.TILE_GLTF}
     * which is for 3D Tiles
     * </p>
     *
     * @type {String}
     * @constant
     */
    GLTF: "GLTF",
    /**
     * A glTF model used as tile content in a 3D Tileset via
     * <code>3DTILES_content_gltf</code>.
     * <p>
     * Not to be confused with {@link ModelExperimentalType.GLTF}
     * which is for individual models
     * </p>
     *
     * @type {String}
     * @constant
     */
    TILE_GLTF: "TILE_GLTF",
    /**
     * A 3D Tiles 1.0 Batched 3D Model
     *
     * @type {String}
     * @constant
     */
    TILE_B3DM: "B3DM",
    /**
     * A 3D Tiles 1.0 Instanced 3D Model
     *
     * @type {String}
     * @constant
     */
    TILE_I3DM: "I3DM",
    /**
     * A 3D Tiles 1.0 Point Cloud
     *
     * @type {String}
     * @constant
     */
    TILE_PNTS: "PNTS",

    /**
     * GeoJSON content for <code>MAXAR_content_geojson</code> extension
     *
     * @type {String}
     * @constant
     */
    TILE_GEOJSON: "TILE_GEOJSON",
  };

  /**
   * Check if a model is used for 3D Tiles.
   * @param {ModelExperimentalType} modelType The type of model
   * @returns {Boolean} <code>true</code> if the model is a 3D Tiles format, <code>false</code> otherwise
   */
  ModelExperimentalType.is3DTiles = function (modelType) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("modelType", modelType);
    //>>includeEnd('debug');

    switch (modelType) {
      case ModelExperimentalType.TILE_GLTF:
      case ModelExperimentalType.TILE_B3DM:
      case ModelExperimentalType.TILE_I3DM:
      case ModelExperimentalType.TILE_PNTS:
      case ModelExperimentalType.TILE_GEOJSON:
        return true;
      case ModelExperimentalType.GLTF:
        return false;
      //>>includeStart('debug', pragmas.debug);
      default:
        throw new DeveloperError("modelType is not a valid value.");
      //>>includeEnd('debug');
    }
  };

  var ModelExperimentalType$1 = Object.freeze(ModelExperimentalType);

  //This file is automatically rebuilt by the Cesium build process.
  var SelectedFeatureIdStageCommon = "vec2 computeSt(float featureId)\n\
{\n\
float stepX = model_textureStep.x;\n\
float centerX = model_textureStep.y;\n\
#ifdef MULTILINE_BATCH_TEXTURE\n\
float stepY = model_textureStep.z;\n\
float centerY = model_textureStep.w;\n\
float xId = mod(featureId, model_textureDimensions.x);\n\
float yId = floor(featureId / model_textureDimensions.x);\n\
return vec2(centerX + (xId * stepX), centerY + (yId * stepY));\n\
#else\n\
return vec2(centerX + (featureId * stepX), 0.5);\n\
#endif\n\
}\n\
void selectedFeatureIdStage(out SelectedFeature feature, FeatureIds featureIds)\n\
{\n\
int featureId = featureIds.SELECTED_FEATURE_ID;\n\
if (featureId < model_featuresLength)\n\
{\n\
vec2 featureSt = computeSt(float(featureId));\n\
feature.id = featureId;\n\
feature.st = featureSt;\n\
feature.color = texture2D(model_batchTexture, featureSt);\n\
}\n\
else\n\
{\n\
feature.id = model_featuresLength + 1;\n\
feature.st = vec2(0.0);\n\
feature.color = vec4(1.0);\n\
}\n\
#ifdef HAS_NULL_FEATURE_ID\n\
if (featureId == model_nullFeatureId) {\n\
feature.id = featureId;\n\
feature.st = vec2(0.0);\n\
feature.color = vec4(1.0);\n\
}\n\
#endif\n\
}\n\
";

  /**
   * The selected feature ID pipeline stage is responsible for handling the
   * set of feature IDs selected for styling/picking.
   *
   * @namespace SelectedFeatureIdPipelineStage
   * @private
   */
  const SelectedFeatureIdPipelineStage = {};
  SelectedFeatureIdPipelineStage.name = "SelectedFeatureIdPipelineStage"; // Helps with debugging

  SelectedFeatureIdPipelineStage.STRUCT_ID_SELECTED_FEATURE = "SelectedFeature";
  SelectedFeatureIdPipelineStage.STRUCT_NAME_SELECTED_FEATURE = "SelectedFeature";
  SelectedFeatureIdPipelineStage.FUNCTION_ID_FEATURE_VARYINGS_VS =
    "updateFeatureStructVS";
  SelectedFeatureIdPipelineStage.FUNCTION_ID_FEATURE_VARYINGS_FS =
    "updateFeatureStructFS";
  SelectedFeatureIdPipelineStage.FUNCTION_SIGNATURE_UPDATE_FEATURE =
    "void updateFeatureStruct(inout SelectedFeature feature)";

  /**
   * Process a primitive. This modifies the following parts of the render resources:
   * <ul>
   *  <li>sets the defines for the feature ID attribute to use for styling/picking</li>
   *  <li>adds fields to the SelectedFeature struct in the shader</li>
   * </ul>
   *
   * @param {PrimitiveRenderResources} renderResources The render resources for this primitive.
   * @param {ModelComponents.Primitive} primitive The primitive.
   * @param {FrameState} frameState The frame state.
   */
  SelectedFeatureIdPipelineStage.process = function (
    renderResources,
    primitive,
    frameState
  ) {
    const shaderBuilder = renderResources.shaderBuilder;

    renderResources.hasPropertyTable = true;

    const model = renderResources.model;
    const node = renderResources.runtimeNode.node;
    const selectedFeatureIds = getSelectedFeatureIds(model, node, primitive);
    const shaderDestination = selectedFeatureIds.shaderDestination;

    shaderBuilder.addDefine(
      "HAS_SELECTED_FEATURE_ID",
      undefined,
      shaderDestination
    );

    // Add a define to insert the variable to use.
    // Example: #define SELECTED_FEATURE_ID featureId_1
    // This corresponds to featureIds.featureId_1
    shaderBuilder.addDefine(
      "SELECTED_FEATURE_ID",
      selectedFeatureIds.variableName,
      shaderDestination
    );

    // Add a define to the shader to distinguish feature ID attributes from
    // textures. This is needed for determining where to filter features
    // by pass type.
    shaderBuilder.addDefine(
      selectedFeatureIds.featureIdDefine,
      undefined,
      shaderDestination
    );

    updateFeatureStruct(shaderBuilder);

    const nullFeatureId = selectedFeatureIds.featureIds.nullFeatureId;
    const uniformMap = renderResources.uniformMap;
    if (defined(nullFeatureId)) {
      shaderBuilder.addDefine(
        "HAS_NULL_FEATURE_ID",
        undefined,
        shaderDestination
      );
      shaderBuilder.addUniform("int", "model_nullFeatureId", shaderDestination);
      uniformMap.model_nullFeatureId = function () {
        return nullFeatureId;
      };
    }

    if (selectedFeatureIds.shaderDestination === ShaderDestination$1.BOTH) {
      shaderBuilder.addVertexLines([SelectedFeatureIdStageCommon]);
    }
    shaderBuilder.addFragmentLines([SelectedFeatureIdStageCommon]);
  };

  function getFeatureIdDefine(featureIds) {
    if (featureIds instanceof ModelComponents.FeatureIdTexture) {
      return "HAS_SELECTED_FEATURE_ID_TEXTURE";
    }

    return "HAS_SELECTED_FEATURE_ID_ATTRIBUTE";
  }

  function getShaderDestination(featureIds) {
    // Feature ID textures are only supported in the fragment shader.
    if (featureIds instanceof ModelComponents.FeatureIdTexture) {
      return ShaderDestination$1.FRAGMENT;
    }

    return ShaderDestination$1.BOTH;
  }

  function getSelectedFeatureIds(model, node, primitive) {
    let variableName;
    let featureIds;
    // Check instances first, as this is the most specific type of
    // feature ID
    if (defined(node.instances)) {
      featureIds = ModelExperimentalUtility.getFeatureIdsByLabel(
        node.instances.featureIds,
        model.instanceFeatureIdLabel
      );

      if (defined(featureIds)) {
        // Either label could be used here, but prefer label as it may be more
        // meaningful when debugging
        variableName = defaultValue(featureIds.label, featureIds.positionalLabel);
        return {
          featureIds: featureIds,
          variableName: variableName,
          shaderDestination: getShaderDestination(featureIds),
          featureIdDefine: getFeatureIdDefine(featureIds),
        };
      }
    }

    featureIds = ModelExperimentalUtility.getFeatureIdsByLabel(
      primitive.featureIds,
      model.featureIdLabel
    );
    // again, prefer label for being more descriptive
    variableName = defaultValue(featureIds.label, featureIds.positionalLabel);
    return {
      featureIds: featureIds,
      variableName: variableName,
      shaderDestination: getShaderDestination(featureIds),
      featureIdDefine: getFeatureIdDefine(featureIds),
    };
  }

  /**
   * Populate the "SelectedFeature" struct in the shaders that holds information about the "active" (used for picking/styling) feature.
   * The struct is always added to the shader by the GeometryPipelineStage (required for compilation). The SelectedFeature struct looks
   * as follows:
   *
   * struct SelectedFeature {
   *   int id;
   *   vec2 st;
   *   vec4 color;
   * }
   *
   * @private
   */
  function updateFeatureStruct(shaderBuilder) {
    shaderBuilder.addStructField(
      SelectedFeatureIdPipelineStage.STRUCT_ID_SELECTED_FEATURE,
      "int",
      "id"
    );

    shaderBuilder.addStructField(
      SelectedFeatureIdPipelineStage.STRUCT_ID_SELECTED_FEATURE,
      "vec2",
      "st"
    );

    shaderBuilder.addStructField(
      SelectedFeatureIdPipelineStage.STRUCT_ID_SELECTED_FEATURE,
      "vec4",
      "color"
    );
  }

  /**
   * The geometry pipeline stage processes the vertex attributes of a primitive.
   *
   * @namespace GeometryPipelineStage
   *
   * @private
   */
  const GeometryPipelineStage = {};
  GeometryPipelineStage.name = "GeometryPipelineStage"; // Helps with debugging

  GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_VS =
    "ProcessedAttributesVS";
  GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_FS =
    "ProcessedAttributesFS";
  GeometryPipelineStage.STRUCT_NAME_PROCESSED_ATTRIBUTES = "ProcessedAttributes";
  GeometryPipelineStage.FUNCTION_ID_INITIALIZE_ATTRIBUTES =
    "initializeAttributes";
  GeometryPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_ATTRIBUTES =
    "void initializeAttributes(out ProcessedAttributes attributes)";
  GeometryPipelineStage.FUNCTION_ID_SET_DYNAMIC_VARYINGS_VS =
    "setDynamicVaryingsVS";
  GeometryPipelineStage.FUNCTION_ID_SET_DYNAMIC_VARYINGS_FS =
    "setDynamicVaryingsFS";
  GeometryPipelineStage.FUNCTION_SIGNATURE_SET_DYNAMIC_VARYINGS =
    "void setDynamicVaryings(inout ProcessedAttributes attributes)";

  /**
   * This pipeline stage processes the vertex attributes of a primitive, adding the attribute declarations to the shaders,
   * the attribute objects to the render resources and setting the flags as needed.
   *
   * Processes a primitive. This stage modifies the following parts of the render resources:
   * <ul>
   *  <li> adds attribute and varying declarations for the vertex attributes in the vertex and fragment shaders
   *  <li> creates the objects required to create VertexArrays
   *  <li> sets the flag for point primitive types
   * </ul>
   *
   * If the scene is in either 2D or CV mode, this stage also:
   * <ul>
   *  <li> adds a struct field for the 2D positions
   *  <li> adds an additional attribute object and declaration if the node containing this primitive is not instanced
   * </ul>
   *
   * @param {PrimitiveRenderResources} renderResources The render resources for this primitive.
   * @param {ModelComponents.Primitive} primitive The primitive.
   * @param {FrameState} frameState The frame state.
   *
   * @private
   */
  GeometryPipelineStage.process = function (
    renderResources,
    primitive,
    frameState
  ) {
    const shaderBuilder = renderResources.shaderBuilder;
    // These structs are similar, though the fragment shader version has a couple
    // additional fields.
    shaderBuilder.addStruct(
      GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_VS,
      "ProcessedAttributes",
      ShaderDestination$1.VERTEX
    );
    shaderBuilder.addStruct(
      GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_FS,
      "ProcessedAttributes",
      ShaderDestination$1.FRAGMENT
    );

    // The Feature struct is always added since it's required for compilation. It may be unused if features are not present.
    shaderBuilder.addStruct(
      SelectedFeatureIdPipelineStage.STRUCT_ID_SELECTED_FEATURE,
      SelectedFeatureIdPipelineStage.STRUCT_NAME_SELECTED_FEATURE,
      ShaderDestination$1.BOTH
    );

    // This initialization function is only needed in the vertex shader,
    // it assigns the non-quantized attribute struct fields from the
    // physical attributes
    shaderBuilder.addFunction(
      GeometryPipelineStage.FUNCTION_ID_INITIALIZE_ATTRIBUTES,
      GeometryPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_ATTRIBUTES,
      ShaderDestination$1.VERTEX
    );

    // Positions in other coordinate systems need more variables
    shaderBuilder.addVarying("vec3", "v_positionWC");
    shaderBuilder.addVarying("vec3", "v_positionEC");
    shaderBuilder.addStructField(
      GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_FS,
      "vec3",
      "positionWC"
    );
    shaderBuilder.addStructField(
      GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_FS,
      "vec3",
      "positionEC"
    );

    // Though they have identical signatures, the implementation is different
    // between vertex and fragment shaders. The VS stores attributes in
    // varyings, while the FS unpacks the varyings for use by other stages.
    shaderBuilder.addFunction(
      GeometryPipelineStage.FUNCTION_ID_SET_DYNAMIC_VARYINGS_VS,
      GeometryPipelineStage.FUNCTION_SIGNATURE_SET_DYNAMIC_VARYINGS,
      ShaderDestination$1.VERTEX
    );
    shaderBuilder.addFunction(
      GeometryPipelineStage.FUNCTION_ID_SET_DYNAMIC_VARYINGS_FS,
      GeometryPipelineStage.FUNCTION_SIGNATURE_SET_DYNAMIC_VARYINGS,
      ShaderDestination$1.FRAGMENT
    );

    // .pnts point clouds store sRGB color rather than linear color
    const model = renderResources.model;
    const modelType = model.type;
    if (modelType === ModelExperimentalType$1.TILE_PNTS) {
      shaderBuilder.addDefine(
        "HAS_SRGB_COLOR",
        undefined,
        ShaderDestination$1.FRAGMENT
      );
    }

    // The attributes, structs, and functions will need to be modified for 2D / CV.
    const use2D =
      frameState.mode !== SceneMode$1.SCENE3D &&
      !frameState.scene3DOnly &&
      model._projectTo2D;

    // If the model is instanced, the work for 2D projection will have been done
    // in InstancingPipelineStage. The attribute struct will be updated with
    // position2D, but nothing else should be modified.
    const instanced = defined(renderResources.runtimeNode.node.instances);

    // If the scene is in 3D or the model is instanced, the 2D position attribute
    // is not needed, so don't increment attributeIndex.
    const incrementIndexFor2D = use2D && !instanced;
    const length = primitive.attributes.length;
    for (let i = 0; i < length; i++) {
      const attribute = primitive.attributes[i];
      const attributeLocationCount = AttributeType$1.getAttributeLocationCount(
        attribute.type
      );
      const isPositionAttribute =
        attribute.semantic === VertexAttributeSemantic$1.POSITION;

      //>>includeStart('debug', pragmas.debug);
      if (!defined(attribute.buffer) && !defined(attribute.constant)) {
        throw new DeveloperError(
          "Attributes must be provided as a Buffer or constant value"
        );
      }
      //>>includeEnd('debug');

      let index;
      if (attributeLocationCount > 1) {
        index = renderResources.attributeIndex;
        renderResources.attributeIndex += attributeLocationCount;
      } else if (isPositionAttribute && !incrementIndexFor2D) {
        index = 0;
      } else {
        index = renderResources.attributeIndex++;
      }

      processAttribute(
        renderResources,
        attribute,
        index,
        attributeLocationCount,
        use2D,
        instanced
      );
    }

    handleBitangents(shaderBuilder, primitive.attributes);

    if (primitive.primitiveType === PrimitiveType$1.POINTS) {
      shaderBuilder.addDefine("PRIMITIVE_TYPE_POINTS");
    }

    shaderBuilder.addVertexLines([GeometryStageVS]);
    shaderBuilder.addFragmentLines([GeometryStageFS]);
  };

  function processAttribute(
    renderResources,
    attribute,
    attributeIndex,
    attributeLocationCount,
    use2D,
    instanced
  ) {
    const shaderBuilder = renderResources.shaderBuilder;
    const attributeInfo = ModelExperimentalUtility.getAttributeInfo(attribute);

    // This indicates to only modify the resources for 2D if the model is
    // not instanced.
    const modifyFor2D = use2D && !instanced;

    if (attributeLocationCount > 1) {
      // Matrices are stored as multiple attributes, one per column vector.
      addMatrixAttributeToRenderResources(
        renderResources,
        attribute,
        attributeIndex,
        attributeLocationCount
      );
    } else {
      addAttributeToRenderResources(
        renderResources,
        attribute,
        attributeIndex,
        modifyFor2D
      );
    }

    addAttributeDeclaration(shaderBuilder, attributeInfo, modifyFor2D);
    addVaryingDeclaration(shaderBuilder, attributeInfo);

    // For common attributes like normals and tangents, the code is
    // already in GeometryStageVS, we just need to enable it.
    if (defined(attribute.semantic)) {
      addSemanticDefine(shaderBuilder, attribute);
    }

    // Dynamically generate GLSL code for the current attribute.
    // For 2D projection, the position2D field will always be added
    // to the attributes struct, even if the model is instanced.
    updateAttributesStruct(shaderBuilder, attributeInfo, use2D);
    updateInitializeAttributesFunction(shaderBuilder, attributeInfo, modifyFor2D);
    updateSetDynamicVaryingsFunction(shaderBuilder, attributeInfo);
  }

  function addSemanticDefine(shaderBuilder, attribute) {
    const semantic = attribute.semantic;
    const setIndex = attribute.setIndex;
    switch (semantic) {
      case VertexAttributeSemantic$1.NORMAL:
        shaderBuilder.addDefine("HAS_NORMALS");
        break;
      case VertexAttributeSemantic$1.TANGENT:
        shaderBuilder.addDefine("HAS_TANGENTS");
        break;
      case VertexAttributeSemantic$1.FEATURE_ID:
        // `_FEATURE_ID starts with an underscore so no need to double the
        // underscore.
        shaderBuilder.addDefine(`HAS${semantic}_${setIndex}`);
        break;
      case VertexAttributeSemantic$1.TEXCOORD:
      case VertexAttributeSemantic$1.COLOR:
        shaderBuilder.addDefine(`HAS_${semantic}_${setIndex}`);
    }
  }

  function addAttributeToRenderResources(
    renderResources,
    attribute,
    attributeIndex,
    modifyFor2D
  ) {
    const quantization = attribute.quantization;
    let type;
    let componentDatatype;
    if (defined(quantization)) {
      type = quantization.type;
      componentDatatype = quantization.componentDatatype;
    } else {
      type = attribute.type;
      componentDatatype = attribute.componentDatatype;
    }

    const semantic = attribute.semantic;
    const setIndex = attribute.setIndex;
    if (
      semantic === VertexAttributeSemantic$1.FEATURE_ID &&
      setIndex >= renderResources.featureIdVertexAttributeSetIndex
    ) {
      renderResources.featureIdVertexAttributeSetIndex = setIndex + 1;
    }

    // The position attribute should always be in the first index.
    const isPositionAttribute = semantic === VertexAttributeSemantic$1.POSITION;
    const index = isPositionAttribute ? 0 : attributeIndex;
    const componentsPerAttribute = AttributeType$1.getNumberOfComponents(type);

    const vertexAttribute = {
      index: index,
      value: defined(attribute.buffer) ? undefined : attribute.constant,
      vertexBuffer: attribute.buffer,
      count: attribute.count,
      componentsPerAttribute: componentsPerAttribute,
      componentDatatype: componentDatatype,
      offsetInBytes: attribute.byteOffset,
      strideInBytes: attribute.byteStride,
      normalize: attribute.normalized,
    };

    renderResources.attributes.push(vertexAttribute);

    if (!isPositionAttribute || !modifyFor2D) {
      return;
    }

    // Add an additional attribute for the projected positions in 2D / CV.
    const buffer2D = renderResources.runtimePrimitive.positionBuffer2D;
    const positionAttribute2D = {
      index: attributeIndex,
      vertexBuffer: buffer2D,
      count: attribute.count,
      componentsPerAttribute: componentsPerAttribute,
      componentDatatype: ComponentDatatype$1.FLOAT, // Projected positions will always be floats.
      offsetInBytes: attribute.byteOffset,
      strideInBytes: attribute.byteStride,
      normalize: attribute.normalized,
    };

    renderResources.attributes.push(positionAttribute2D);
  }

  function addMatrixAttributeToRenderResources(
    renderResources,
    attribute,
    attributeIndex,
    columnCount
  ) {
    const quantization = attribute.quantization;
    let type;
    let componentDatatype;
    if (defined(quantization)) {
      type = quantization.type;
      componentDatatype = quantization.componentDatatype;
    } else {
      type = attribute.type;
      componentDatatype = attribute.componentDatatype;
    }

    const normalized = attribute.normalized;

    // componentCount is either 4, 9 or 16
    const componentCount = AttributeType$1.getNumberOfComponents(type);
    // componentsPerColumn is either 2, 3, or 4
    const componentsPerColumn = componentCount / columnCount;

    const componentSizeInBytes = ComponentDatatype$1.getSizeInBytes(
      componentDatatype
    );

    const columnLengthInBytes = componentsPerColumn * componentSizeInBytes;

    // The stride between corresponding columns of two matrices is constant
    // regardless of where you start
    const strideInBytes = attribute.byteStride;

    for (let i = 0; i < columnCount; i++) {
      const offsetInBytes = attribute.byteOffset + i * columnLengthInBytes;

      // upload a single column vector.
      const columnAttribute = {
        index: attributeIndex + i,
        vertexBuffer: attribute.buffer,
        componentsPerAttribute: componentsPerColumn,
        componentDatatype: componentDatatype,
        offsetInBytes: offsetInBytes,
        strideInBytes: strideInBytes,
        normalize: normalized,
      };

      renderResources.attributes.push(columnAttribute);
    }
  }

  function addVaryingDeclaration(shaderBuilder, attributeInfo) {
    const variableName = attributeInfo.variableName;
    let varyingName = `v_${variableName}`;

    let glslType;
    if (variableName === "normalMC") {
      // though the attribute is in model coordinates, the varying is
      // in eye coordinates.
      varyingName = "v_normalEC";
      glslType = attributeInfo.glslType;
    } else if (variableName === "tangentMC") {
      // Tangent's glslType is vec4, but in the shader it is split into
      // vec3 tangent and vec3 bitangent
      glslType = "vec3";
      // like normalMC, the varying is converted to eye coordinates
      varyingName = "v_tangentEC";
    } else {
      glslType = attributeInfo.glslType;
    }

    shaderBuilder.addVarying(glslType, varyingName);
  }

  function addAttributeDeclaration(shaderBuilder, attributeInfo, modifyFor2D) {
    const semantic = attributeInfo.attribute.semantic;
    const variableName = attributeInfo.variableName;

    let attributeName;
    let glslType;
    if (attributeInfo.isQuantized) {
      attributeName = `a_quantized_${variableName}`;
      glslType = attributeInfo.quantizedGlslType;
    } else {
      attributeName = `a_${variableName}`;
      glslType = attributeInfo.glslType;
    }

    const isPosition = semantic === VertexAttributeSemantic$1.POSITION;
    if (isPosition) {
      shaderBuilder.setPositionAttribute(glslType, attributeName);
    } else {
      shaderBuilder.addAttribute(glslType, attributeName);
    }

    if (isPosition && modifyFor2D) {
      shaderBuilder.addAttribute("vec3", "a_position2D");
    }
  }

  function updateAttributesStruct(shaderBuilder, attributeInfo, use2D) {
    const vsStructId = GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_VS;
    const fsStructId = GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_FS;
    const variableName = attributeInfo.variableName;

    if (variableName === "tangentMC") {
      // The w component of the tangent is only used for computing the bitangent,
      // so it can be separated from the other tangent components.
      shaderBuilder.addStructField(vsStructId, "vec3", "tangentMC");
      shaderBuilder.addStructField(vsStructId, "float", "tangentSignMC");
      // The tangent is in model coordinates in the vertex shader
      // but in eye space in the fragment coordinates
      shaderBuilder.addStructField(fsStructId, "vec3", "tangentEC");
    } else if (variableName === "normalMC") {
      // Normals are in model coordinates in the vertex shader but in eye
      // coordinates in the fragment shader
      shaderBuilder.addStructField(vsStructId, "vec3", "normalMC");
      shaderBuilder.addStructField(fsStructId, "vec3", "normalEC");
    } else {
      shaderBuilder.addStructField(
        vsStructId,
        attributeInfo.glslType,
        variableName
      );
      shaderBuilder.addStructField(
        fsStructId,
        attributeInfo.glslType,
        variableName
      );
    }

    if (variableName === "positionMC" && use2D) {
      shaderBuilder.addStructField(vsStructId, "vec3", "position2D");
    }
  }

  function updateInitializeAttributesFunction(
    shaderBuilder,
    attributeInfo,
    use2D
  ) {
    const functionId = GeometryPipelineStage.FUNCTION_ID_INITIALIZE_ATTRIBUTES;
    const variableName = attributeInfo.variableName;

    // If the scene is in 2D / CV mode, this line should always be added
    // regardless of whether the data is quantized.
    const use2DPosition = variableName === "positionMC" && use2D;
    if (use2DPosition) {
      const line = "attributes.position2D = a_position2D;";
      shaderBuilder.addFunctionLines(functionId, [line]);
    }

    if (attributeInfo.isQuantized) {
      // Skip initialization, it will be handled in the dequantization stage.
      return;
    }

    const lines = [];
    if (variableName === "tangentMC") {
      lines.push("attributes.tangentMC = a_tangentMC.xyz;");
      lines.push("attributes.tangentSignMC = a_tangentMC.w;");
    } else {
      lines.push(`attributes.${variableName} = a_${variableName};`);
    }

    shaderBuilder.addFunctionLines(functionId, lines);
  }

  function updateSetDynamicVaryingsFunction(shaderBuilder, attributeInfo) {
    const semantic = attributeInfo.attribute.semantic;
    const setIndex = attributeInfo.attribute.setIndex;
    if (defined(semantic) && !defined(setIndex)) {
      // positions, normals, and tangents are handled statically in
      // GeometryStageVS
      return;
    }

    // In the vertex shader, we want things like
    // v_texCoord_1 = attributes.texCoord_1;
    let functionId = GeometryPipelineStage.FUNCTION_ID_SET_DYNAMIC_VARYINGS_VS;
    const variableName = attributeInfo.variableName;
    let line = `v_${variableName} = attributes.${variableName};`;
    shaderBuilder.addFunctionLines(functionId, [line]);

    // In the fragment shader, we do the opposite:
    // attributes.texCoord_1 = v_texCoord_1;
    functionId = GeometryPipelineStage.FUNCTION_ID_SET_DYNAMIC_VARYINGS_FS;
    line = `attributes.${variableName} = v_${variableName};`;
    shaderBuilder.addFunctionLines(functionId, [line]);
  }

  function handleBitangents(shaderBuilder, attributes) {
    let hasNormals = false;
    let hasTangents = false;
    for (let i = 0; i < attributes.length; i++) {
      const attribute = attributes[i];
      if (attribute.semantic === VertexAttributeSemantic$1.NORMAL) {
        hasNormals = true;
      } else if (attribute.semantic === VertexAttributeSemantic$1.TANGENT) {
        hasTangents = true;
      }
    }

    // Bitangents are only defined if we have normals and tangents
    if (!hasNormals || !hasTangents) {
      return;
    }

    shaderBuilder.addDefine("HAS_BITANGENTS");

    shaderBuilder.addVarying("vec3", "v_bitangentEC");
    shaderBuilder.addStructField(
      GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_VS,
      "vec3",
      "bitangentMC"
    );
    shaderBuilder.addStructField(
      GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_FS,
      "vec3",
      "bitangentEC"
    );
  }

  //This file is automatically rebuilt by the Cesium build process.
  var LightingStageFS = "#ifdef LIGHTING_PBR\n\
vec3 computePbrLighting(czm_modelMaterial inputMaterial, ProcessedAttributes attributes)\n\
{\n\
czm_pbrParameters pbrParameters;\n\
pbrParameters.diffuseColor = inputMaterial.diffuse;\n\
pbrParameters.f0 = inputMaterial.specular;\n\
pbrParameters.roughness = inputMaterial.roughness;\n\
#ifdef USE_CUSTOM_LIGHT_COLOR\n\
vec3 lightColorHdr = model_lightColorHdr;\n\
#else\n\
vec3 lightColorHdr = czm_lightColorHdr;\n\
#endif\n\
vec3 color = inputMaterial.diffuse;\n\
#ifdef HAS_NORMALS\n\
color = czm_pbrLighting(\n\
attributes.positionEC,\n\
inputMaterial.normalEC,\n\
czm_lightDirectionEC,\n\
lightColorHdr,\n\
pbrParameters\n\
);\n\
#ifdef USE_IBL_LIGHTING\n\
color += imageBasedLightingStage(\n\
attributes.positionEC,\n\
inputMaterial.normalEC,\n\
czm_lightDirectionEC,\n\
lightColorHdr,\n\
pbrParameters\n\
);\n\
#endif\n\
#endif\n\
color *= inputMaterial.occlusion;\n\
color += inputMaterial.emissive;\n\
#ifndef HDR\n\
color = czm_acesTonemapping(color);\n\
#endif\n\
return color;\n\
}\n\
#endif\n\
void lightingStage(inout czm_modelMaterial material, ProcessedAttributes attributes)\n\
{\n\
vec3 color = vec3(0.0);\n\
#ifdef LIGHTING_PBR\n\
color = computePbrLighting(material, attributes);\n\
#else // unlit\n\
color = material.diffuse;\n\
#endif\n\
#ifndef HDR\n\
color = czm_linearToSrgb(color);\n\
#endif\n\
material.diffuse = color;\n\
}\n\
";

  /**
   * The lighting model to use for lighting a {@link ModelExperimental}.
   *
   * @enum {Number}
   *
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  const LightingModel = {
    /**
     * Use unlit shading, i.e. skip lighting calculations. The model's
     * diffuse color (assumed to be linear RGB, not sRGB) is used directly
     * when computing <code>gl_FragColor</code>. The alpha mode is still
     * applied.
     *
     * @type {Number}
     * @constant
     */
    UNLIT: 0,
    /**
     * Use physically-based rendering lighting calculations. This includes
     * both PBR metallic roughness and PBR specular glossiness. Image-based
     * lighting is also applied when possible.
     *
     * @type {Number}
     * @constant
     */
    PBR: 1,
  };

  var LightingModel$1 = Object.freeze(LightingModel);

  /**
   * The lighting pipeline stage is responsible for taking a material and rendering
   * it with a lighting model such as physically based rendering (PBR) or unlit
   * shading
   *
   * @namespace LightingPipelineStage
   *
   * @private
   */
  const LightingPipelineStage = {};
  LightingPipelineStage.name = "LightingPipelineStage"; // Helps with debugging

  /**
   * Process a primitive. This modifies the following parts of the render
   * resources:
   * <ul>
   *   <li>modifies the shader to include the lighting stage</li>
   * </ul>
   * @param {PrimitiveRenderResources} renderResources The render resources for the primitive
   * @param {ModelComponents.Primitive} primitive The primitive to be rendered
   *
   * @private
   */
  LightingPipelineStage.process = function (renderResources, primitive) {
    const model = renderResources.model;
    const lightingOptions = renderResources.lightingOptions;
    const shaderBuilder = renderResources.shaderBuilder;

    if (defined(model.lightColor)) {
      shaderBuilder.addDefine(
        "USE_CUSTOM_LIGHT_COLOR",
        undefined,
        ShaderDestination$1.FRAGMENT
      );

      shaderBuilder.addUniform(
        "vec3",
        "model_lightColorHdr",
        ShaderDestination$1.FRAGMENT
      );

      const uniformMap = renderResources.uniformMap;
      uniformMap.model_lightColorHdr = function () {
        return model.lightColor;
      };
    }

    // The lighting model is always set by the material. However, custom shaders
    // can override this.
    const lightingModel = lightingOptions.lightingModel;

    if (lightingModel === LightingModel$1.PBR) {
      shaderBuilder.addDefine(
        "LIGHTING_PBR",
        undefined,
        ShaderDestination$1.FRAGMENT
      );
    } else {
      shaderBuilder.addDefine(
        "LIGHTING_UNLIT",
        undefined,
        ShaderDestination$1.FRAGMENT
      );
    }

    shaderBuilder.addFragmentLines([LightingStageFS]);
  };

  //This file is automatically rebuilt by the Cesium build process.
  var MaterialStageFS = "bool isDefaultStyleColor(vec3 color)\n\
{\n\
return all(greaterThan(color, vec3(1.0 - czm_epsilon3)));\n\
}\n\
vec3 blend(vec3 sourceColor, vec3 styleColor, float styleColorBlend)\n\
{\n\
vec3 blendColor = mix(sourceColor, styleColor, styleColorBlend);\n\
vec3 color = isDefaultStyleColor(styleColor.rgb) ? sourceColor : blendColor;\n\
return color;\n\
}\n\
vec2 computeTextureTransform(vec2 texCoord, mat3 textureTransform)\n\
{\n\
return vec2(textureTransform * vec3(texCoord, 1.0));\n\
}\n\
#ifdef HAS_NORMALS\n\
vec3 computeNormal(ProcessedAttributes attributes)\n\
{\n\
vec3 ng = attributes.normalEC;\n\
vec3 normal = ng;\n\
#if defined(HAS_NORMAL_TEXTURE) && !defined(USE_WIREFRAME)\n\
vec2 normalTexCoords = TEXCOORD_NORMAL;\n\
#ifdef HAS_NORMAL_TEXTURE_TRANSFORM\n\
normalTexCoords = computeTextureTransform(normalTexCoords, u_normalTextureTransform);\n\
#endif\n\
#ifdef HAS_BITANGENTS\n\
vec3 t = attributes.tangentEC;\n\
vec3 b = attributes.bitangentEC;\n\
mat3 tbn = mat3(t, b, ng);\n\
vec3 n = texture2D(u_normalTexture, normalTexCoords).rgb;\n\
normal = normalize(tbn * (2.0 * n - 1.0));\n\
#elif defined(GL_OES_standard_derivatives)\n\
vec3 positionEC = attributes.positionEC;\n\
vec3 pos_dx = dFdx(positionEC);\n\
vec3 pos_dy = dFdy(positionEC);\n\
vec3 tex_dx = dFdx(vec3(normalTexCoords,0.0));\n\
vec3 tex_dy = dFdy(vec3(normalTexCoords,0.0));\n\
vec3 t = (tex_dy.t * pos_dx - tex_dx.t * pos_dy) / (tex_dx.s * tex_dy.t - tex_dy.s * tex_dx.t);\n\
t = normalize(t - ng * dot(ng, t));\n\
vec3 b = normalize(cross(ng, t));\n\
mat3 tbn = mat3(t, b, ng);\n\
vec3 n = texture2D(u_normalTexture, normalTexCoords).rgb;\n\
normal = normalize(tbn * (2.0 * n - 1.0));\n\
#endif\n\
#endif\n\
return normal;\n\
}\n\
#endif\n\
void materialStage(inout czm_modelMaterial material, ProcessedAttributes attributes, SelectedFeature feature)\n\
{\n\
#ifdef HAS_NORMALS\n\
material.normalEC = computeNormal(attributes);\n\
#endif\n\
vec4 baseColorWithAlpha = vec4(1.0);\n\
#ifdef HAS_BASE_COLOR_TEXTURE\n\
vec2 baseColorTexCoords = TEXCOORD_BASE_COLOR;\n\
#ifdef HAS_BASE_COLOR_TEXTURE_TRANSFORM\n\
baseColorTexCoords = computeTextureTransform(baseColorTexCoords, u_baseColorTextureTransform);\n\
#endif\n\
baseColorWithAlpha = czm_srgbToLinear(texture2D(u_baseColorTexture, baseColorTexCoords));\n\
#ifdef HAS_BASE_COLOR_FACTOR\n\
baseColorWithAlpha *= u_baseColorFactor;\n\
#endif\n\
#elif defined(HAS_BASE_COLOR_FACTOR)\n\
baseColorWithAlpha = u_baseColorFactor;\n\
#endif\n\
#ifdef HAS_COLOR_0\n\
vec4 color = attributes.color_0;\n\
#ifdef HAS_SRGB_COLOR\n\
color = czm_srgbToLinear(color);\n\
#endif\n\
baseColorWithAlpha *= color;\n\
#endif\n\
material.diffuse = baseColorWithAlpha.rgb;\n\
material.alpha = baseColorWithAlpha.a;\n\
#ifdef USE_CPU_STYLING\n\
material.diffuse = blend(material.diffuse, feature.color.rgb, model_colorBlend);\n\
#endif\n\
#ifdef HAS_OCCLUSION_TEXTURE\n\
vec2 occlusionTexCoords = TEXCOORD_OCCLUSION;\n\
#ifdef HAS_OCCLUSION_TEXTURE_TRANSFORM\n\
occlusionTexCoords = computeTextureTransform(occlusionTexCoords, u_occlusionTextureTransform);\n\
#endif\n\
material.occlusion = texture2D(u_occlusionTexture, occlusionTexCoords).r;\n\
#endif\n\
#ifdef HAS_EMISSIVE_TEXTURE\n\
vec2 emissiveTexCoords = TEXCOORD_EMISSIVE;\n\
#ifdef HAS_EMISSIVE_TEXTURE_TRANSFORM\n\
emissiveTexCoords = computeTextureTransform(emissiveTexCoords, u_emissiveTextureTransform);\n\
#endif\n\
vec3 emissive = czm_srgbToLinear(texture2D(u_emissiveTexture, emissiveTexCoords).rgb);\n\
#ifdef HAS_EMISSIVE_FACTOR\n\
emissive *= u_emissiveFactor;\n\
#endif\n\
material.emissive = emissive;\n\
#elif defined(HAS_EMISSIVE_FACTOR)\n\
material.emissive = u_emissiveFactor;\n\
#endif\n\
#if defined(LIGHTING_PBR) && defined(USE_SPECULAR_GLOSSINESS)\n\
#ifdef HAS_SPECULAR_GLOSSINESS_TEXTURE\n\
vec2 specularGlossinessTexCoords = TEXCOORD_SPECULAR_GLOSSINESS;\n\
#ifdef HAS_SPECULAR_GLOSSINESS_TEXTURE_TRANSFORM\n\
specularGlossinessTexCoords = computeTextureTransform(specularGlossinessTexCoords, u_specularGlossinessTextureTransform);\n\
#endif\n\
vec4 specularGlossiness = czm_srgbToLinear(texture2D(u_specularGlossinessTexture, specularGlossinessTexCoords));\n\
vec3 specular = specularGlossiness.rgb;\n\
float glossiness = specularGlossiness.a;\n\
#ifdef HAS_SPECULAR_FACTOR\n\
specular *= u_specularFactor;\n\
#endif\n\
#ifdef HAS_GLOSSINESS_FACTOR\n\
glossiness *= u_glossinessFactor;\n\
#endif\n\
#else\n\
#ifdef HAS_SPECULAR_FACTOR\n\
vec3 specular = clamp(u_specularFactor, vec3(0.0), vec3(1.0));\n\
#else\n\
vec3 specular = vec3(1.0);\n\
#endif\n\
#ifdef HAS_GLOSSINESS_FACTOR\n\
float glossiness = clamp(u_glossinessFactor, 0.0, 1.0);\n\
#else\n\
float glossiness = 1.0;\n\
#endif\n\
#endif\n\
#ifdef HAS_DIFFUSE_TEXTURE\n\
vec2 diffuseTexCoords = TEXCOORD_DIFFUSE;\n\
#ifdef HAS_DIFFUSE_TEXTURE_TRANSFORM\n\
diffuseTexCoords = computeTextureTransform(diffuseTexCoords, u_diffuseTextureTransform);\n\
#endif\n\
vec4 diffuse = czm_srgbToLinear(texture2D(u_diffuseTexture, diffuseTexCoords));\n\
#ifdef HAS_DIFFUSE_FACTOR\n\
diffuse *= u_diffuseFactor;\n\
#endif\n\
#elif defined(HAS_DIFFUSE_FACTOR)\n\
vec4 diffuse = clamp(u_diffuseFactor, vec4(0.0), vec4(1.0));\n\
#else\n\
vec4 diffuse = vec4(1.0);\n\
#endif\n\
czm_pbrParameters parameters = czm_pbrSpecularGlossinessMaterial(\n\
diffuse.rgb,\n\
specular,\n\
glossiness\n\
);\n\
material.diffuse = parameters.diffuseColor;\n\
material.alpha = diffuse.a;\n\
material.specular = parameters.f0;\n\
material.roughness = parameters.roughness;\n\
#elif defined(LIGHTING_PBR)\n\
#ifdef HAS_METALLIC_ROUGHNESS_TEXTURE\n\
vec2 metallicRoughnessTexCoords = TEXCOORD_METALLIC_ROUGHNESS;\n\
#ifdef HAS_METALLIC_ROUGHNESS_TEXTURE_TRANSFORM\n\
metallicRoughnessTexCoords = computeTextureTransform(metallicRoughnessTexCoords, u_metallicRoughnessTextureTransform);\n\
#endif\n\
vec3 metallicRoughness = texture2D(u_metallicRoughnessTexture, metallicRoughnessTexCoords).rgb;\n\
float metalness = clamp(metallicRoughness.b, 0.0, 1.0);\n\
float roughness = clamp(metallicRoughness.g, 0.04, 1.0);\n\
#ifdef HAS_METALLIC_FACTOR\n\
metalness *= u_metallicFactor;\n\
#endif\n\
#ifdef HAS_ROUGHNESS_FACTOR\n\
roughness *= u_roughnessFactor;\n\
#endif\n\
#else\n\
#ifdef HAS_METALLIC_FACTOR\n\
float metalness = clamp(u_metallicFactor, 0.0, 1.0);\n\
#else\n\
float metalness = 1.0;\n\
#endif\n\
#ifdef HAS_ROUGHNESS_FACTOR\n\
float roughness = clamp(u_roughnessFactor, 0.04, 1.0);\n\
#else\n\
float roughness = 1.0;\n\
#endif\n\
#endif\n\
czm_pbrParameters parameters = czm_pbrMetallicRoughnessMaterial(\n\
material.diffuse,\n\
metalness,\n\
roughness\n\
);\n\
material.diffuse = parameters.diffuseColor;\n\
material.specular = parameters.f0;\n\
material.roughness = parameters.roughness;\n\
#endif\n\
}\n\
";

  const Material$1 = ModelComponents.Material;
  const MetallicRoughness$1 = ModelComponents.MetallicRoughness;
  const SpecularGlossiness = ModelComponents.SpecularGlossiness;

  /**
   * The material pipeline stage processes textures and other uniforms needed
   * to render a primitive. This handles the following material types:
   * <ul>
   *   <li>Basic glTF materials (PBR metallic roughness model)</li>
   *   <li>The `KHR_materials_pbrSpecularGlossiness` glTF extension</li>
   *   <li>The `KHR_materials_unlit` glTF extension</li>
   * </ul>
   *
   * @namespace MaterialPipelineStage
   *
   * @private
   */
  const MaterialPipelineStage = {};
  MaterialPipelineStage.name = "MaterialPipelineStage"; // Helps with debugging

  /**
   * Process a primitive. This modifies the following parts of the render
   * resources:
   * <ul>
   *   <li>Modifies the shader to include the material processing stage</li>
   *   <li>Modifies the shader to include additional uniforms for textures and other rendering details</li>
   *   <li>Modifies the lighting options to set either PBR or unlit lighting</li>
   *   <li>Sets the render state for back-face culling</li>
   * </ul>
   * @param {PrimitiveRenderResources} renderResources The render resources for the primitive
   * @param {ModelComponents.Primitive} primitive The primitive to be rendered
   * @param {FrameState} frameState The frame state.
   * @private
   */
  MaterialPipelineStage.process = function (
    renderResources,
    primitive,
    frameState
  ) {
    // gltf-pipeline automatically creates a default material so this will always
    // be defined.
    const material = primitive.material;

    const uniformMap = renderResources.uniformMap;
    const shaderBuilder = renderResources.shaderBuilder;

    // When textures are loaded incrementally, fall back to a default 1x1 texture
    const defaultTexture = frameState.context.defaultTexture;
    const defaultNormalTexture = frameState.context.defaultNormalTexture;
    const defaultEmissiveTexture = frameState.context.defaultEmissiveTexture;

    processMaterialUniforms(
      material,
      uniformMap,
      shaderBuilder,
      defaultTexture,
      defaultNormalTexture,
      defaultEmissiveTexture
    );

    if (defined(material.specularGlossiness)) {
      processSpecularGlossinessUniforms(
        material,
        uniformMap,
        shaderBuilder,
        defaultTexture
      );
    } else {
      processMetallicRoughnessUniforms(
        material,
        uniformMap,
        shaderBuilder,
        defaultTexture
      );
    }

    // If the primitive does not have normals, fall back to unlit lighting.
    const hasNormals = ModelExperimentalUtility.getAttributeBySemantic(
      primitive,
      VertexAttributeSemantic$1.NORMAL
    );

    const lightingOptions = renderResources.lightingOptions;
    if (material.unlit || !hasNormals) {
      lightingOptions.lightingModel = LightingModel$1.UNLIT;
    } else {
      lightingOptions.lightingModel = LightingModel$1.PBR;
    }

    // Configure back-face culling
    const model = renderResources.model;
    const cull = model.backFaceCulling && !material.doubleSided;
    const translucent = defined(model.color) && model.color.alpha < 1.0;
    renderResources.renderStateOptions.cull = {
      enabled: cull && !translucent,
    };

    const alphaOptions = renderResources.alphaOptions;
    if (!defined(alphaOptions.alphaMode)) {
      alphaOptions.alphaMode = material.alphaMode;
      if (material.alphaMode === AlphaMode$1.BLEND) {
        alphaOptions.pass = Pass$1.TRANSLUCENT;
      } else if (material.alphaMode === AlphaMode$1.MASK) {
        alphaOptions.alphaCutoff = material.alphaCutoff;
      }
    }

    shaderBuilder.addFragmentLines([MaterialStageFS]);

    // Check if the model's debug wireframe is enabled. If so, add a define
    // to disable normal mapping.
    if (model.debugWireframe) {
      shaderBuilder.addDefine(
        "USE_WIREFRAME",
        undefined,
        ShaderDestination$1.FRAGMENT
      );
    }
  };

  /**
   * Process a single texture transformation and add it to the shader and uniform map.
   *
   * @param {ShaderBuilder} shaderBuilder The shader builder to modify
   * @param {Object.<String, Function>} uniformMap The uniform map to modify.
   * @param {ModelComponents.TextureReader} textureReader The texture to add to the shader
   * @param {String} uniformName The name of the sampler uniform such as <code>u_baseColorTexture</code>
   * @param {String} defineName The name of the texture for use in the defines, minus any prefix or suffix. For example, "BASE_COLOR" or "EMISSIVE"
   *
   * @private
   */
  function processTextureTransform(
    shaderBuilder,
    uniformMap,
    textureReader,
    uniformName,
    defineName
  ) {
    // Add a define to enable the texture transformation code in the shader.
    const transformDefine = `HAS_${defineName}_TEXTURE_TRANSFORM`;
    shaderBuilder.addDefine(
      transformDefine,
      undefined,
      ShaderDestination$1.FRAGMENT
    );

    // Add a uniform for the transformation matrix
    const transformUniformName = `${uniformName}Transform`;
    shaderBuilder.addUniform(
      "mat3",
      transformUniformName,
      ShaderDestination$1.FRAGMENT
    );
    uniformMap[transformUniformName] = function () {
      return textureReader.transform;
    };
  }

  /**
   * Process a single texture and add it to the shader and uniform map.
   *
   * @param {ShaderBuilder} shaderBuilder The shader builder to modify
   * @param {Object.<String, Function>} uniformMap The uniform map to modify.
   * @param {ModelComponents.TextureReader} textureReader The texture to add to the shader
   * @param {String} uniformName The name of the sampler uniform such as <code>u_baseColorTexture</code>
   * @param {String} defineName The name of the texture for use in the defines, minus any prefix or suffix. For example, "BASE_COLOR" or "EMISSIVE"
   *
   * @private
   */
  function processTexture(
    shaderBuilder,
    uniformMap,
    textureReader,
    uniformName,
    defineName,
    defaultTexture
  ) {
    // Add a uniform for the texture itself
    shaderBuilder.addUniform(
      "sampler2D",
      uniformName,
      ShaderDestination$1.FRAGMENT
    );
    uniformMap[uniformName] = function () {
      return defaultValue(textureReader.texture, defaultTexture);
    };

    // Add a #define directive to enable using the texture in the shader
    const textureDefine = `HAS_${defineName}_TEXTURE`;
    shaderBuilder.addDefine(textureDefine, undefined, ShaderDestination$1.FRAGMENT);

    // Add a #define to tell the shader which texture coordinates varying to use.
    const texCoordIndex = textureReader.texCoord;
    const texCoordVarying = `v_texCoord_${texCoordIndex}`;
    const texCoordDefine = `TEXCOORD_${defineName}`;
    shaderBuilder.addDefine(
      texCoordDefine,
      texCoordVarying,
      ShaderDestination$1.FRAGMENT
    );

    // Some textures have matrix transforms (e.g. for texture atlases). Add those
    // to the shader if present.
    const textureTransform = textureReader.transform;
    if (
      defined(textureTransform) &&
      !Matrix3.equals(textureTransform, Matrix3.IDENTITY)
    ) {
      processTextureTransform(
        shaderBuilder,
        uniformMap,
        textureReader,
        uniformName,
        defineName
      );
    }
  }

  function processMaterialUniforms(
    material,
    uniformMap,
    shaderBuilder,
    defaultTexture,
    defaultNormalTexture,
    defaultEmissiveTexture
  ) {
    const emissiveTexture = material.emissiveTexture;
    if (defined(emissiveTexture)) {
      processTexture(
        shaderBuilder,
        uniformMap,
        emissiveTexture,
        "u_emissiveTexture",
        "EMISSIVE",
        defaultEmissiveTexture
      );
    }

    const emissiveFactor = material.emissiveFactor;
    if (
      defined(emissiveFactor) &&
      !Cartesian3.equals(emissiveFactor, Material$1.DEFAULT_EMISSIVE_FACTOR)
    ) {
      shaderBuilder.addUniform(
        "vec3",
        "u_emissiveFactor",
        ShaderDestination$1.FRAGMENT
      );
      uniformMap.u_emissiveFactor = function () {
        return material.emissiveFactor;
      };
      shaderBuilder.addDefine(
        "HAS_EMISSIVE_FACTOR",
        undefined,
        ShaderDestination$1.FRAGMENT
      );
    }

    const normalTexture = material.normalTexture;
    if (defined(normalTexture)) {
      processTexture(
        shaderBuilder,
        uniformMap,
        normalTexture,
        "u_normalTexture",
        "NORMAL",
        defaultNormalTexture
      );
    }

    const occlusionTexture = material.occlusionTexture;
    if (defined(occlusionTexture)) {
      processTexture(
        shaderBuilder,
        uniformMap,
        occlusionTexture,
        "u_occlusionTexture",
        "OCCLUSION",
        defaultTexture
      );
    }
  }

  function processSpecularGlossinessUniforms(
    material,
    uniformMap,
    shaderBuilder,
    defaultTexture
  ) {
    const specularGlossiness = material.specularGlossiness;
    shaderBuilder.addDefine(
      "USE_SPECULAR_GLOSSINESS",
      undefined,
      ShaderDestination$1.FRAGMENT
    );

    const diffuseTexture = specularGlossiness.diffuseTexture;
    if (defined(diffuseTexture)) {
      processTexture(
        shaderBuilder,
        uniformMap,
        diffuseTexture,
        "u_diffuseTexture",
        "DIFFUSE",
        defaultTexture
      );
    }

    const diffuseFactor = specularGlossiness.diffuseFactor;
    if (
      defined(diffuseFactor) &&
      !Cartesian4.equals(diffuseFactor, SpecularGlossiness.DEFAULT_DIFFUSE_FACTOR)
    ) {
      shaderBuilder.addUniform(
        "vec4",
        "u_diffuseFactor",
        ShaderDestination$1.FRAGMENT
      );
      uniformMap.u_diffuseFactor = function () {
        return specularGlossiness.diffuseFactor;
      };
      shaderBuilder.addDefine(
        "HAS_DIFFUSE_FACTOR",
        undefined,
        ShaderDestination$1.FRAGMENT
      );
    }

    const specularGlossinessTexture =
      specularGlossiness.specularGlossinessTexture;
    if (defined(specularGlossinessTexture)) {
      processTexture(
        shaderBuilder,
        uniformMap,
        specularGlossinessTexture,
        "u_specularGlossinessTexture",
        "SPECULAR_GLOSSINESS",
        defaultTexture
      );
    }

    const specularFactor = specularGlossiness.specularFactor;
    if (
      defined(specularFactor) &&
      !Cartesian3.equals(
        specularFactor,
        SpecularGlossiness.DEFAULT_SPECULAR_FACTOR
      )
    ) {
      shaderBuilder.addUniform(
        "vec3",
        "u_specularFactor",
        ShaderDestination$1.FRAGMENT
      );
      uniformMap.u_specularFactor = function () {
        return specularGlossiness.specularFactor;
      };
      shaderBuilder.addDefine(
        "HAS_SPECULAR_FACTOR",
        undefined,
        ShaderDestination$1.FRAGMENT
      );
    }

    const glossinessFactor = specularGlossiness.glossinessFactor;
    if (
      defined(glossinessFactor) &&
      glossinessFactor !== SpecularGlossiness.DEFAULT_GLOSSINESS_FACTOR
    ) {
      shaderBuilder.addUniform(
        "float",
        "u_glossinessFactor",
        ShaderDestination$1.FRAGMENT
      );
      uniformMap.u_glossinessFactor = function () {
        return specularGlossiness.glossinessFactor;
      };
      shaderBuilder.addDefine(
        "HAS_GLOSSINESS_FACTOR",
        undefined,
        ShaderDestination$1.FRAGMENT
      );
    }
  }

  function processMetallicRoughnessUniforms(
    material,
    uniformMap,
    shaderBuilder,
    defaultTexture
  ) {
    const metallicRoughness = material.metallicRoughness;
    shaderBuilder.addDefine(
      "USE_METALLIC_ROUGHNESS",
      undefined,
      ShaderDestination$1.FRAGMENT
    );

    const baseColorTexture = metallicRoughness.baseColorTexture;
    if (defined(baseColorTexture)) {
      processTexture(
        shaderBuilder,
        uniformMap,
        baseColorTexture,
        "u_baseColorTexture",
        "BASE_COLOR",
        defaultTexture
      );
    }

    const baseColorFactor = metallicRoughness.baseColorFactor;
    if (
      defined(baseColorFactor) &&
      !Cartesian4.equals(
        baseColorFactor,
        MetallicRoughness$1.DEFAULT_BASE_COLOR_FACTOR
      )
    ) {
      shaderBuilder.addUniform(
        "vec4",
        "u_baseColorFactor",
        ShaderDestination$1.FRAGMENT
      );
      uniformMap.u_baseColorFactor = function () {
        return metallicRoughness.baseColorFactor;
      };
      shaderBuilder.addDefine(
        "HAS_BASE_COLOR_FACTOR",
        undefined,
        ShaderDestination$1.FRAGMENT
      );
    }

    const metallicRoughnessTexture = metallicRoughness.metallicRoughnessTexture;
    if (defined(metallicRoughnessTexture)) {
      processTexture(
        shaderBuilder,
        uniformMap,
        metallicRoughnessTexture,
        "u_metallicRoughnessTexture",
        "METALLIC_ROUGHNESS",
        defaultTexture
      );
    }

    const metallicFactor = metallicRoughness.metallicFactor;
    if (
      defined(metallicFactor) &&
      metallicFactor !== MetallicRoughness$1.DEFAULT_METALLIC_FACTOR
    ) {
      shaderBuilder.addUniform(
        "float",
        "u_metallicFactor",
        ShaderDestination$1.FRAGMENT
      );
      uniformMap.u_metallicFactor = function () {
        return metallicRoughness.metallicFactor;
      };
      shaderBuilder.addDefine(
        "HAS_METALLIC_FACTOR",
        undefined,
        ShaderDestination$1.FRAGMENT
      );
    }

    const roughnessFactor = metallicRoughness.roughnessFactor;
    if (
      defined(roughnessFactor) &&
      roughnessFactor !== MetallicRoughness$1.DEFAULT_ROUGHNESS_FACTOR
    ) {
      shaderBuilder.addUniform(
        "float",
        "u_roughnessFactor",
        ShaderDestination$1.FRAGMENT
      );
      uniformMap.u_roughnessFactor = function () {
        return metallicRoughness.roughnessFactor;
      };
      shaderBuilder.addDefine(
        "HAS_ROUGHNESS_FACTOR",
        undefined,
        ShaderDestination$1.FRAGMENT
      );
    }
  }

  // Exposed for testing
  MaterialPipelineStage._processTexture = processTexture;
  MaterialPipelineStage._processTextureTransform = processTextureTransform;

  //This file is automatically rebuilt by the Cesium build process.
  var MorphTargetsStageVS = "void morphTargetsStage(inout ProcessedAttributes attributes)\n\
{\n\
vec3 positionMC = attributes.positionMC;\n\
attributes.positionMC = getMorphedPosition(positionMC);\n\
#ifdef HAS_NORMALS\n\
vec3 normalMC = attributes.normalMC;\n\
attributes.normalMC = getMorphedNormal(normalMC);\n\
#endif\n\
#ifdef HAS_TANGENTS\n\
vec3 tangentMC = attributes.tangentMC;\n\
attributes.tangentMC = getMorphedTangent(tangentMC);\n\
#endif\n\
}\n\
";

  /**
   * The morph targets pipeline stage processes the morph targets and weights of a primitive.
   *
   * @namespace MorphTargetsPipelineStage
   *
   * @private
   */
  const MorphTargetsPipelineStage = {};
  MorphTargetsPipelineStage.name = "MorphTargetsPipelineStage"; // Helps with debugging
  MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_POSITION =
    "getMorphedPosition";
  MorphTargetsPipelineStage.FUNCTION_SIGNATURE_GET_MORPHED_POSITION =
    "vec3 getMorphedPosition(in vec3 position)";
  MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_NORMAL = "getMorphedNormal";
  MorphTargetsPipelineStage.FUNCTION_SIGNATURE_GET_MORPHED_NORMAL =
    "vec3 getMorphedNormal(in vec3 normal)";
  MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_TANGENT = "getMorphedTangent";
  MorphTargetsPipelineStage.FUNCTION_SIGNATURE_GET_MORPHED_TANGENT =
    "vec3 getMorphedTangent(in vec3 tangent)";

  /**
   * This pipeline stage processes the morph targets and weights of a primitive,
   * adding the relevant attribute declarations and functions to the shaders.
   *
   * Processes a primitive. This stage modifies the following parts of the render resources:
   * <ul>
   *  <li> adds attribute declarations for the morph targets in the vertex shader
   *  <li> adds the uniform declaration for the morph weights in the vertex shader
   *  <li> adds functions to apply the morphs in the vertex shader
   * </ul>
   *
   * @param {PrimitiveRenderResources} renderResources The render resources for this primitive.
   * @param {ModelComponents.Primitive} primitive The primitive.
   *
   * @private
   */
  MorphTargetsPipelineStage.process = function (renderResources, primitive) {
    const shaderBuilder = renderResources.shaderBuilder;

    shaderBuilder.addDefine(
      "HAS_MORPH_TARGETS",
      undefined,
      ShaderDestination$1.VERTEX
    );

    addGetMorphedAttributeFunctionDeclarations(shaderBuilder);

    const morphTargetsLength = primitive.morphTargets.length;
    for (let i = 0; i < morphTargetsLength; i++) {
      const attributes = primitive.morphTargets[i].attributes;

      const attributesLength = attributes.length;
      for (let j = 0; j < attributesLength; j++) {
        const attribute = attributes[j];
        const semantic = attribute.semantic;

        // Cesium only supports morph targets for positions, normals, and tangents
        if (
          semantic !== VertexAttributeSemantic$1.POSITION &&
          semantic !== VertexAttributeSemantic$1.NORMAL &&
          semantic !== VertexAttributeSemantic$1.TANGENT
        ) {
          continue;
        }

        processMorphTargetAttribute(
          renderResources,
          attribute,
          renderResources.attributeIndex,
          i
        );
        renderResources.attributeIndex++;
      }
    }

    addGetMorphedAttributeFunctionReturns(shaderBuilder);

    const weights = renderResources.runtimeNode.morphWeights;
    const weightsLength = weights.length;
    shaderBuilder.addUniform(
      "float",
      `u_morphWeights[${weightsLength}]`,
      ShaderDestination$1.VERTEX
    );

    shaderBuilder.addVertexLines([MorphTargetsStageVS]);

    const uniformMap = {
      u_morphWeights: function () {
        return renderResources.runtimeNode.morphWeights;
      },
    };

    renderResources.uniformMap = combine$2(uniformMap, renderResources.uniformMap);
  };

  const scratchAttributeInfo = {
    attributeString: undefined,
    functionId: undefined,
  };

  function processMorphTargetAttribute(
    renderResources,
    attribute,
    attributeIndex,
    morphTargetIndex
  ) {
    const shaderBuilder = renderResources.shaderBuilder;

    addMorphTargetAttributeToRenderResources(
      renderResources,
      attribute,
      attributeIndex
    );

    const attributeInfo = getMorphTargetAttributeInfo(
      attribute,
      scratchAttributeInfo
    );

    addMorphTargetAttributeDeclarationAndFunctionLine(
      shaderBuilder,
      attributeInfo,
      morphTargetIndex
    );
  }

  function addMorphTargetAttributeToRenderResources(
    renderResources,
    attribute,
    attributeIndex
  ) {
    const vertexAttribute = {
      index: attributeIndex,
      value: defined(attribute.buffer) ? undefined : attribute.constant,
      vertexBuffer: attribute.buffer,
      componentsPerAttribute: AttributeType$1.getNumberOfComponents(attribute.type),
      componentDatatype: attribute.componentDatatype,
      offsetInBytes: attribute.byteOffset,
      strideInBytes: attribute.byteStride,
      normalize: attribute.normalized,
    };

    renderResources.attributes.push(vertexAttribute);
  }

  function getMorphTargetAttributeInfo(attribute, result) {
    const semantic = attribute.semantic;
    switch (semantic) {
      case VertexAttributeSemantic$1.POSITION:
        result.attributeString = "Position";
        result.functionId =
          MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_POSITION;
        break;
      case VertexAttributeSemantic$1.NORMAL:
        result.attributeString = "Normal";
        result.functionId =
          MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_NORMAL;
        break;
      case VertexAttributeSemantic$1.TANGENT:
        result.attributeString = "Tangent";
        result.functionId =
          MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_TANGENT;
        break;
    }
    return result;
  }

  function addMorphTargetAttributeDeclarationAndFunctionLine(
    shaderBuilder,
    attributeInfo,
    morphTargetIndex
  ) {
    const attributeString = attributeInfo.attributeString;
    const attributeName = `a_target${attributeString}_${morphTargetIndex}`;
    const line = `morphed${attributeString} += u_morphWeights[${morphTargetIndex}] * a_target${attributeString}_${morphTargetIndex};`;
    shaderBuilder.addAttribute("vec3", attributeName);
    shaderBuilder.addFunctionLines(attributeInfo.functionId, [line]);
  }

  function addGetMorphedAttributeFunctionDeclarations(shaderBuilder) {
    shaderBuilder.addFunction(
      MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_POSITION,
      MorphTargetsPipelineStage.FUNCTION_SIGNATURE_GET_MORPHED_POSITION,
      ShaderDestination$1.VERTEX
    );

    const positionLine = "vec3 morphedPosition = position;";
    shaderBuilder.addFunctionLines(
      MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_POSITION,
      [positionLine]
    );

    shaderBuilder.addFunction(
      MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_NORMAL,
      MorphTargetsPipelineStage.FUNCTION_SIGNATURE_GET_MORPHED_NORMAL,
      ShaderDestination$1.VERTEX
    );

    const normalLine = "vec3 morphedNormal = normal;";
    shaderBuilder.addFunctionLines(
      MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_NORMAL,
      [normalLine]
    );

    shaderBuilder.addFunction(
      MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_TANGENT,
      MorphTargetsPipelineStage.FUNCTION_SIGNATURE_GET_MORPHED_TANGENT,
      ShaderDestination$1.VERTEX
    );

    const tangentLine = "vec3 morphedTangent = tangent;";
    shaderBuilder.addFunctionLines(
      MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_TANGENT,
      [tangentLine]
    );
  }

  function addGetMorphedAttributeFunctionReturns(shaderBuilder) {
    const positionLine = "return morphedPosition;";
    shaderBuilder.addFunctionLines(
      MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_POSITION,
      [positionLine]
    );

    const normalLine = "return morphedNormal;";
    shaderBuilder.addFunctionLines(
      MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_NORMAL,
      [normalLine]
    );

    const tangentLine = "return morphedTangent;";
    shaderBuilder.addFunctionLines(
      MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_TANGENT,
      [tangentLine]
    );
  }

  /**
   * The picking pipeline stage is responsible for handling picking of primitives.
   *
   * @namespace PickingPipelineStage
   * @private
   */
  const PickingPipelineStage = {};
  PickingPipelineStage.name = "PickingPipelineStage"; // Helps with debugging

  /**
   * Process a primitive. This modifies the following parts of the render resources:
   * <ul>
   *  <li>adds attribute and varying declaration for the pick color vertex attribute in the vertex shader for instanced meshes</li>
   *  <li>adds declaration for the pick color uniform for non-instanced meshes</li>
   *  <li>adds defines in the shader for when picking is enabled</li>
   *  <li>creates the pick ID objects in the context</li>
   * </ul>
   * @param {PrimitiveRenderResources} renderResources The render resources for this primitive.
   * @param {ModelComponents.Primitive} primitive The primitive.
   * @param {FrameState} frameState The frame state.
   */
  PickingPipelineStage.process = function (
    renderResources,
    primitive,
    frameState
  ) {
    const context = frameState.context;
    const runtimeNode = renderResources.runtimeNode;
    const shaderBuilder = renderResources.shaderBuilder;
    const model = renderResources.model;
    const instances = runtimeNode.node.instances;

    if (renderResources.hasPropertyTable) {
      processPickTexture(renderResources, primitive, instances);
    } else if (defined(instances)) {
      // For instanced meshes, a pick color vertex attribute is used.
      processInstancedPickIds(renderResources, context);
    } else {
      // For non-instanced meshes, a pick color uniform is used.
      const pickObject = buildPickObject(renderResources);

      const pickId = context.createPickId(pickObject);
      model._pipelineResources.push(pickId);
      model._pickIds.push(pickId);

      shaderBuilder.addUniform(
        "vec4",
        "czm_pickColor",
        ShaderDestination$1.FRAGMENT
      );

      const uniformMap = renderResources.uniformMap;
      uniformMap.czm_pickColor = function () {
        return pickId.color;
      };

      renderResources.pickId = "czm_pickColor";
    }
  };

  /**
   * @private
   */
  function buildPickObject(renderResources, instanceId) {
    const model = renderResources.model;

    const detailPickObject = {
      model: model,
      node: renderResources.runtimeNode,
      primitive: renderResources.runtimePrimitive,
    };

    let pickObject;

    if (ModelExperimentalType$1.is3DTiles(model.type)) {
      // For 3D Tiles, the pick object's content and primitive are set to the Cesium3DTileContent that owns the model
      // and the tileset it belongs to, respectively. The detail pick object is returned under the detail key.
      const content = model.content;
      pickObject = {
        content: content,
        primitive: content.tileset,
        detail: detailPickObject,
      };
    } else {
      // For models, the model itself is returned as the primitive, with the detail pick object under the detail key.
      pickObject = {
        primitive: model,
        detail: detailPickObject,
      };
    }

    pickObject.id = model.id;

    if (defined(instanceId)) {
      // For instanced models, an instanceId property is added to the pick object.
      pickObject.instanceId = instanceId;
    }

    return pickObject;
  }

  function processPickTexture(renderResources, primitive, instances) {
    const model = renderResources.model;
    let featureTableId;
    let featureIdAttribute;
    const featureIdLabel = model.featureIdLabel;
    const instanceFeatureIdLabel = model.instanceFeatureIdLabel;

    if (defined(model.featureTableId)) {
      // Extract the Feature Table ID from the Cesium3DTileContent.
      featureTableId = model.featureTableId;
    } else if (defined(instances)) {
      // Extract the Feature Table ID from the instanced Feature ID attributes.
      featureIdAttribute = ModelExperimentalUtility.getFeatureIdsByLabel(
        instances.featureIds,
        instanceFeatureIdLabel
      );
      featureTableId = featureIdAttribute.propertyTableId;
    } else {
      // Extract the Feature Table ID from the primitive Feature ID attributes.
      featureIdAttribute = ModelExperimentalUtility.getFeatureIdsByLabel(
        primitive.featureIds,
        featureIdLabel
      );
      featureTableId = featureIdAttribute.propertyTableId;
    }

    const featureTable = model.featureTables[featureTableId];

    const shaderBuilder = renderResources.shaderBuilder;
    shaderBuilder.addUniform(
      "sampler2D",
      "model_pickTexture",
      ShaderDestination$1.FRAGMENT
    );

    const batchTexture = featureTable.batchTexture;
    renderResources.uniformMap.model_pickTexture = function () {
      return defaultValue(batchTexture.pickTexture, batchTexture.defaultTexture);
    };

    // The feature ID  is ignored if it is greater than the number of features.
    renderResources.pickId =
      "((selectedFeature.id < int(model_featuresLength)) ? texture2D(model_pickTexture, selectedFeature.st) : vec4(0.0))";
  }

  function processInstancedPickIds(renderResources, context) {
    const instanceCount = renderResources.instanceCount;
    const pickIds = new Array(instanceCount);
    const pickIdsTypedArray = new Uint8Array(instanceCount * 4);

    const model = renderResources.model;

    const pipelineResources = model._pipelineResources;
    for (let i = 0; i < instanceCount; i++) {
      const pickObject = buildPickObject(renderResources, i);

      const pickId = context.createPickId(pickObject);
      pipelineResources.push(pickId);
      pickIds[i] = pickId;

      const pickColor = pickId.color;
      pickIdsTypedArray[i * 4 + 0] = Color.floatToByte(pickColor.red);
      pickIdsTypedArray[i * 4 + 1] = Color.floatToByte(pickColor.green);
      pickIdsTypedArray[i * 4 + 2] = Color.floatToByte(pickColor.blue);
      pickIdsTypedArray[i * 4 + 3] = Color.floatToByte(pickColor.alpha);
    }

    model._pickIds = pickIds;

    const pickIdsBuffer = Buffer$1.createVertexBuffer({
      context: context,
      typedArray: pickIdsTypedArray,
      usage: BufferUsage$1.STATIC_DRAW,
    });
    // Destruction of resources allocated by the ModelExperimental
    // is handled by ModelExperimental.destroyPipelineResources().
    pickIdsBuffer.vertexArrayDestroyable = false;
    const hasCpuCopy = false;
    model.statistics.addBuffer(pickIdsBuffer, hasCpuCopy);
    pipelineResources.push(pickIdsBuffer);

    const pickIdsVertexAttribute = {
      index: renderResources.attributeIndex++,
      vertexBuffer: pickIdsBuffer,
      componentsPerAttribute: 4,
      componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
      normalize: true,
      offsetInBytes: 0,
      strideInBytes: 0,
      instanceDivisor: 1,
    };

    renderResources.attributes.push(pickIdsVertexAttribute);

    const shaderBuilder = renderResources.shaderBuilder;
    shaderBuilder.addDefine("USE_PICKING", undefined, ShaderDestination$1.BOTH);
    shaderBuilder.addAttribute("vec4", "a_pickColor");
    shaderBuilder.addVarying("vec4", "v_pickColor");
    renderResources.pickId = "v_pickColor";
  }

  //This file is automatically rebuilt by the Cesium build process.
  var PointCloudAttenuationStageVS = "float pointCloudAttenuationStage(vec3 positionEC) {\n\
float pointSize = model_pointCloudAttenuation.x;\n\
float geometricError = model_pointCloudAttenuation.y;\n\
float depthMultiplier = model_pointCloudAttenuation.z;\n\
float depth = -positionEC.z;\n\
return min((geometricError / depth) * depthMultiplier, pointSize);\n\
}\n\
";

  /**
   * Stage to handle point cloud attenuation. This stage assumes that either
   * tileset.pointCloudShading.attenuation (3D Tiles) or
   * model.pointCloudShading.attenuation (individual model) is true
   *
   * @namespace PointCloudAttenuationPipelineStage
   *
   * @private
   */
  const PointCloudAttenuationPipelineStage = {};
  PointCloudAttenuationPipelineStage.name = "PointCloudAttenuationPipelineStage"; // Helps with debugging

  const scratchAttenuationUniform = new Cartesian3();

  /**
   * This stage does the following:
   * <ul>
   *  <li>Add vertex shader code to compute attenuation and update gl_PointSize</li>
   *  <li>Updates the uniform map to pass in the point cloud attenuation parameters</li>
   * </ul>
   * @param {PrimitiveRenderResources} renderResources The render resources for this primitive
   * @param {ModelComponents.primitive} primitive The primitive
   * @param {FrameState} frameState The frame state
   *
   * @private
   */
  PointCloudAttenuationPipelineStage.process = function (
    renderResources,
    primitive,
    frameState
  ) {
    const shaderBuilder = renderResources.shaderBuilder;
    shaderBuilder.addVertexLines([PointCloudAttenuationStageVS]);
    shaderBuilder.addDefine(
      "USE_POINT_CLOUD_ATTENUATION",
      undefined,
      ShaderDestination$1.VERTEX
    );

    const model = renderResources.model;
    const pointCloudShading = model.pointCloudShading;

    let content;
    let is3DTiles;
    let usesAddRefinement;
    if (ModelExperimentalType$1.is3DTiles(model.type)) {
      is3DTiles = true;
      content = model.content;
      usesAddRefinement = content.tile.refine === Cesium3DTileRefine$1.ADD;
    }

    shaderBuilder.addUniform(
      "vec3",
      "model_pointCloudAttenuation",
      ShaderDestination$1.VERTEX
    );
    renderResources.uniformMap.model_pointCloudAttenuation = function () {
      const scratch = scratchAttenuationUniform;

      // attenuation.x = pointSize
      let defaultPointSize = 1.0;
      if (is3DTiles) {
        defaultPointSize = usesAddRefinement
          ? 5.0
          : content.tileset.maximumScreenSpaceError;
      }
      scratch.x = defaultValue(
        pointCloudShading.maximumAttenuation,
        defaultPointSize
      );
      scratch.x *= frameState.pixelRatio;

      // attenuation.y = geometricError
      const geometricError = getGeometricError$1(
        renderResources,
        primitive,
        pointCloudShading,
        content
      );
      scratch.y = geometricError * pointCloudShading.geometricErrorScale;

      const context = frameState.context;
      const frustum = frameState.camera.frustum;
      let depthMultiplier;

      // Attenuation is maximumAttenuation in 2D/ortho
      if (
        frameState.mode === SceneMode$1.SCENE2D ||
        frustum instanceof OrthographicFrustum
      ) {
        depthMultiplier = Number.POSITIVE_INFINITY;
      } else {
        depthMultiplier =
          context.drawingBufferHeight / frameState.camera.frustum.sseDenominator;
      }

      // attenuation.z = depth multiplier
      scratch.z = depthMultiplier;

      return scratch;
    };
  };

  const scratchDimensions = new Cartesian3();
  function getGeometricError$1(
    renderResources,
    primitive,
    pointCloudShading,
    content
  ) {
    if (defined(content)) {
      const geometricError = content.tile.geometricError;

      if (geometricError > 0) {
        return geometricError;
      }
    }

    if (defined(pointCloudShading.baseResolution)) {
      return pointCloudShading.baseResolution;
    }

    const positionAttribute = ModelExperimentalUtility.getAttributeBySemantic(
      primitive,
      VertexAttributeSemantic$1.POSITION
    );
    const pointsLength = positionAttribute.count;

    // Estimate the geometric error
    const nodeTransform = renderResources.runtimeNode.transform;
    let dimensions = Cartesian3.subtract(
      positionAttribute.max,
      positionAttribute.min,
      scratchDimensions
    );
    // dimensions is a vector, as it is a subtraction between two points
    dimensions = Matrix4.multiplyByPointAsVector(
      nodeTransform,
      dimensions,
      scratchDimensions
    );
    const volume = dimensions.x * dimensions.y * dimensions.z;
    const geometricErrorEstimate = CesiumMath.cbrt(volume / pointsLength);
    return geometricErrorEstimate;
  }

  /**
   * The primitive statistics update stage updates memory usage statistics
   * on the primitive level. This counts the binary resources that exist
   * for the lifetime of the ModelExperimental (e.g. attributes and textures
   * loaded by GltfLoader). It does not count resources that are created
   * every time the pipeline is run. The individual pipeline stages are
   * responsible for tracking the additional memory they allocate.
   *
   * @namespace PrimitiveStatisticsPipelineStage
   *
   * @private
   */
  const PrimitiveStatisticsPipelineStage = {};
  PrimitiveStatisticsPipelineStage.name = "PrimitiveStatisticsPipelineStage"; // Helps with debugging

  PrimitiveStatisticsPipelineStage.process = function (
    renderResources,
    primitive,
    frameState
  ) {
    const model = renderResources.model;
    const statistics = model.statistics;

    countGeometry(statistics, primitive);
    count2DPositions(statistics, renderResources.runtimePrimitive);
    countMorphTargetAttributes(statistics, primitive);
    countMaterialTextures(statistics, primitive.material);
    countFeatureIdTextures(statistics, primitive.featureIds);
    countBinaryMetadata(statistics, model);

    // The following stages handle their own memory statistics since all their
    // resources are generated each time draw commands are built:
    //
    // - PickingPipelineStage
    // - WireframePipelineStage
    // - InstancingPipelineStage
    // - FeatureIdPipelineStage (feature ID implicit ranges only)
  };

  function countGeometry(statistics, primitive) {
    const indicesCount = defined(primitive.indices)
      ? primitive.indices.count
      : ModelExperimentalUtility.getAttributeBySemantic(primitive, "POSITION")
          .count;

    const primitiveType = primitive.primitiveType;

    if (primitiveType === PrimitiveType$1.POINTS) {
      statistics.pointsLength += indicesCount;
    } else if (PrimitiveType$1.isTriangles(primitiveType)) {
      statistics.trianglesLength += countTriangles(primitiveType, indicesCount);
    }

    const attributes = primitive.attributes;
    const length = attributes.length;
    for (let i = 0; i < length; i++) {
      const attribute = attributes[i];
      if (defined(attribute.buffer)) {
        const hasCpuCopy = defined(attribute.typedArray);
        statistics.addBuffer(attribute.buffer, hasCpuCopy);
      }
    }

    const indices = primitive.indices;
    if (defined(indices) && defined(indices.buffer)) {
      // Wireframe mode will have both GPU and CPU copies
      const hasCpuCopy = defined(indices.typedArray);
      statistics.addBuffer(indices.buffer, hasCpuCopy);
    }
  }

  function countTriangles(primitiveType, indicesCount) {
    switch (primitiveType) {
      case PrimitiveType$1.TRIANGLES:
        return indicesCount / 3;
      case PrimitiveType$1.TRIANGLE_STRIP:
      case PrimitiveType$1.TRIANGLE_FAN:
        return Math.max(indicesCount - 2, 0);
      default:
        return 0;
    }
  }

  function count2DPositions(statistics, runtimePrimitive) {
    const buffer2D = runtimePrimitive.positionBuffer2D;

    // The 2D buffer is only created the first time the scene switches to 2D mode.
    // This means there's two main cases for accounting for 2D positions:
    // 1. The scene was in 3D mode so positions were never generated from
    //    positionAttribute.typedArray. In this case, countGeometry() will
    //    detect the typed array and set hasCpuCopy = true. No memory is counted
    //    here.
    // 2. The scene was in 2D mode so positions were generated as a buffer.
    //    Even though the typed array was unlinked from the attribute, it still
    //    exists in the loader so we count it here.
    if (defined(buffer2D)) {
      const hasCpuCopy = true;
      statistics.addBuffer(buffer2D, hasCpuCopy);
    }
  }

  function countMorphTargetAttributes(statistics, primitive) {
    const morphTargets = primitive.morphTargets;
    if (!defined(morphTargets)) {
      return;
    }

    const hasCpuCopy = false;
    const morphTargetsLength = morphTargets.length;
    for (let i = 0; i < morphTargetsLength; i++) {
      const attributes = morphTargets[i].attributes;

      const attributesLength = attributes.length;
      for (let j = 0; j < attributesLength; j++) {
        const attribute = attributes[j];

        if (defined(attribute.buffer)) {
          statistics.addBuffer(attribute.buffer, hasCpuCopy);
        }
      }
    }
  }

  function countMaterialTextures(statistics, material) {
    // gltf-pipeline provides a default material so material will always be
    // defined.
    const textureReaders = getAllTextureReaders(material);
    const length = textureReaders.length;
    for (let i = 0; i < length; i++) {
      const textureReader = textureReaders[i];
      // If textures were loaded asynchronously, the texture may not be available
      // the first time this is run.
      if (defined(textureReader) && defined(textureReader.texture)) {
        statistics.addTexture(textureReader.texture);
      }
    }
  }

  function getAllTextureReaders(material) {
    const metallicRoughness = material.metallicRoughness;
    const textureReaders = [
      material.emissiveTexture,
      material.normalTexture,
      material.occlusionTexture,
      metallicRoughness.baseColorTexture,
      metallicRoughness.metallicRoughnessTexture,
    ];

    const specularGlossiness = material.specularGlossiness;
    if (defined(specularGlossiness)) {
      textureReaders.push(specularGlossiness.diffuseTexture);
      textureReaders.push(specularGlossiness.specularGlossinessTexture);
    }

    return textureReaders;
  }

  function countFeatureIdTextures(statistics, featureIdSets) {
    // Feature ID attributes are handled by countGeometry()

    // Feature ID implicit ranges are handled in the FeatureIdPipelineStage,
    // as they only are created as-needed.

    const length = featureIdSets.length;
    for (let i = 0; i < length; i++) {
      const featureIds = featureIdSets[i];
      if (featureIds instanceof ModelComponents.FeatureIdTexture) {
        const textureReader = featureIds.textureReader;
        if (defined(textureReader.texture)) {
          statistics.addTexture(textureReader.texture);
        }
      }
    }
  }

  function countBinaryMetadata(statistics, model) {
    // Add metadata memory to the statistics. Note that feature ID memory is
    // handled by the Feature ID pipeline stage.
    const structuralMetadata = model.structuralMetadata;
    if (defined(structuralMetadata)) {
      // Property textures are added to the texture memory count. If textures
      // are loaded asynchronously, this may add 0 to the total. The pipeline
      // will be re-run when textures are loaded for an accurate count.
      countPropertyTextures(statistics, structuralMetadata);

      // Property tables are accounted for here
      statistics.propertyTablesByteLength +=
        structuralMetadata.propertyTablesByteLength;

      // Intentionally skip property attributes since those are handled in
      // countGeometry()
    }

    // Model feature tables also have batch and pick textures that need to be
    // counted.
    const featureTables = model.featureTables;
    if (!defined(featureTables)) {
      return;
    }

    const length = featureTables.length;
    for (let i = 0; i < length; i++) {
      const featureTable = featureTables[i];

      // This does not include the property table memory, as that is already
      // counted through the structuralMetadata above.
      statistics.propertyTablesByteLength += featureTable.batchTextureByteLength;
    }
  }

  function countPropertyTextures(statistics, structuralMetadata) {
    const propertyTextures = structuralMetadata.propertyTextures;
    if (!defined(propertyTextures)) {
      return;
    }

    // Loop over the property textures from here so we can use
    // statistics.addTexture() which avoids double-counting shared textures.
    const texturesLength = propertyTextures.length;
    for (let i = 0; i < texturesLength; i++) {
      const propertyTexture = propertyTextures[i];
      const properties = propertyTexture.properties;
      for (const propertyId in properties) {
        if (properties.hasOwnProperty(propertyId)) {
          const property = properties[propertyId];
          const textureReader = property.textureReader;
          if (defined(textureReader.texture)) {
            statistics.addTexture(textureReader.texture);
          }
        }
      }
    }
  }

  // Exposed for testing
  PrimitiveStatisticsPipelineStage._countGeometry = countGeometry;
  PrimitiveStatisticsPipelineStage._count2DPositions = count2DPositions;
  PrimitiveStatisticsPipelineStage._countMorphTargetAttributes = countMorphTargetAttributes;
  PrimitiveStatisticsPipelineStage._countMaterialTextures = countMaterialTextures;
  PrimitiveStatisticsPipelineStage._countFeatureIdTextures = countFeatureIdTextures;
  PrimitiveStatisticsPipelineStage._countBinaryMetadata = countBinaryMetadata;

  const scratchModelMatrix$2 = new Matrix4();
  const scratchModelView2D = new Matrix4();

  /**
   * The scene mode 2D stage generates resources for rendering a primitive in 2D / CV mode.
   *
   * @namespace SceneMode2DPipelineStage
   *
   * @private
   */
  const SceneMode2DPipelineStage = {};
  SceneMode2DPipelineStage.name = "SceneMode2DPipelineStage"; // Helps with debugging

  /**
   * This pipeline stage processes the position attribute of a primitive and adds the relevant
   * define and uniform matrix to the shader. It also generates new resources for the primitive
   * in 2D. These resources persist in the runtime primitive so that the typed array used to
   * store the positional data can be freed.
   *
   * This stage must go before the GeometryPipelineStage in the primitive pipeline.
   *
   * Processes a primitive. This stage modifies the following parts of the render resources:
   * <ul>
   *  <li> creates a vertex buffer for the positions of the primitive projected to 2D
   *  <li> creates the bounding sphere for the primitive in 2D
   *  <li> adds a flag to the shader to use 2D positions
   *  <li> adds a uniform for the view model matrix in 2D
   * </ul>
   *
   * @param {PrimitiveRenderResources} renderResources The render resources for this primitive.
   * @param {ModelComponents.Primitive} primitive The primitive.
   * @param {FrameState} frameState The frame state.
   *
   * @private
   */

  SceneMode2DPipelineStage.process = function (
    renderResources,
    primitive,
    frameState
  ) {
    const positionAttribute = ModelExperimentalUtility.getAttributeBySemantic(
      primitive,
      VertexAttributeSemantic$1.POSITION
    );

    const shaderBuilder = renderResources.shaderBuilder;
    const model = renderResources.model;
    const modelMatrix = model.sceneGraph.computedModelMatrix;
    const nodeComputedTransform = renderResources.runtimeNode.computedTransform;
    const computedModelMatrix = Matrix4.multiplyTransformation(
      modelMatrix,
      nodeComputedTransform,
      scratchModelMatrix$2
    );

    const boundingSphere2D = computeBoundingSphere2D(
      renderResources,
      computedModelMatrix,
      frameState
    );

    const runtimePrimitive = renderResources.runtimePrimitive;
    runtimePrimitive.boundingSphere2D = boundingSphere2D;

    // If the model is instanced, 2D projection will be handled in the
    // InstancingPipelineStage.
    const instances = renderResources.runtimeNode.node.instances;
    if (defined(instances)) {
      return;
    }

    // If the typed array of the position attribute exists, then
    // the positions haven't been projected to 2D yet.
    if (defined(positionAttribute.typedArray)) {
      const buffer2D = createPositionBufferFor2D(
        positionAttribute,
        computedModelMatrix,
        boundingSphere2D,
        frameState
      );

      // Since this buffer will persist even if the pipeline is re-run,
      // its memory will be counted in PrimitiveStatisticsPipelineStage
      runtimePrimitive.positionBuffer2D = buffer2D;
      model._modelResources.push(buffer2D);

      // Unload the typed array. This is just a pointer to the array in
      // the vertex buffer loader, so if the typed array is shared by
      // multiple primitives (i.e. multiple instances of the same mesh),
      // this will not affect the other primitives.
      positionAttribute.typedArray = undefined;
    }

    shaderBuilder.addDefine(
      "USE_2D_POSITIONS",
      undefined,
      ShaderDestination$1.VERTEX
    );

    shaderBuilder.addUniform("mat4", "u_modelView2D", ShaderDestination$1.VERTEX);

    const modelMatrix2D = Matrix4.fromTranslation(
      boundingSphere2D.center,
      new Matrix4()
    );

    const context = frameState.context;
    const uniformMap = {
      u_modelView2D: function () {
        return Matrix4.multiplyTransformation(
          context.uniformState.view,
          modelMatrix2D,
          scratchModelView2D
        );
      },
    };

    renderResources.uniformMap = combine$2(uniformMap, renderResources.uniformMap);
  };

  const scratchProjectedMin$1 = new Cartesian3();
  const scratchProjectedMax$1 = new Cartesian3();

  function computeBoundingSphere2D(renderResources, modelMatrix, frameState) {
    // Compute the bounding sphere in 2D.
    const transformedPositionMin = Matrix4.multiplyByPoint(
      modelMatrix,
      renderResources.positionMin,
      scratchProjectedMin$1
    );

    const projectedMin = SceneTransforms.computeActualWgs84Position(
      frameState,
      transformedPositionMin,
      transformedPositionMin
    );

    const transformedPositionMax = Matrix4.multiplyByPoint(
      modelMatrix,
      renderResources.positionMax,
      scratchProjectedMax$1
    );

    const projectedMax = SceneTransforms.computeActualWgs84Position(
      frameState,
      transformedPositionMax,
      transformedPositionMax
    );

    return BoundingSphere.fromCornerPoints(
      projectedMin,
      projectedMax,
      new BoundingSphere()
    );
  }

  const scratchPosition$5 = new Cartesian3();

  function dequantizePositionsTypedArray(typedArray, quantization) {
    // Draco compression is normally handled in the dequantization stage
    // in the shader, but it must be decoded here in order to project
    // the positions to 2D / CV.
    const length = typedArray.length;
    const dequantizedArray = new Float32Array(length);
    const quantizedVolumeOffset = quantization.quantizedVolumeOffset;
    const quantizedVolumeStepSize = quantization.quantizedVolumeStepSize;
    for (let i = 0; i < length; i += 3) {
      const initialPosition = Cartesian3.fromArray(
        typedArray,
        i,
        scratchPosition$5
      );
      const scaledPosition = Cartesian3.multiplyComponents(
        initialPosition,
        quantizedVolumeStepSize,
        initialPosition
      );
      const dequantizedPosition = Cartesian3.add(
        scaledPosition,
        quantizedVolumeOffset,
        scaledPosition
      );

      dequantizedArray[i] = dequantizedPosition.x;
      dequantizedArray[i + 1] = dequantizedPosition.y;
      dequantizedArray[i + 2] = dequantizedPosition.z;
    }

    return dequantizedArray;
  }

  function createPositionsTypedArrayFor2D(
    attribute,
    modelMatrix,
    referencePoint,
    frameState
  ) {
    const typedArray = attribute.typedArray.slice();
    let result;
    if (defined(attribute.quantization)) {
      // Dequantize the positions if necessary.
      result = dequantizePositionsTypedArray(
        attribute.typedArray,
        attribute.quantization
      );
    } else {
      result = new Float32Array(
        typedArray.buffer,
        typedArray.byteOffset,
        typedArray.byteLength / Float32Array.BYTES_PER_ELEMENT
      );
    }

    const startIndex = attribute.byteOffset / Float32Array.BYTES_PER_ELEMENT;
    const length = result.length;
    const stride = defined(attribute.byteStride)
      ? attribute.byteStride / Float32Array.BYTES_PER_ELEMENT
      : 3;

    for (let i = startIndex; i < length; i += stride) {
      const initialPosition = Cartesian3.fromArray(result, i, scratchPosition$5);
      if (
        isNaN(initialPosition.x) ||
        isNaN(initialPosition.y) ||
        isNaN(initialPosition.z)
      ) {
        continue;
      }

      const transformedPosition = Matrix4.multiplyByPoint(
        modelMatrix,
        initialPosition,
        initialPosition
      );

      const projectedPosition = SceneTransforms.computeActualWgs84Position(
        frameState,
        transformedPosition,
        transformedPosition
      );

      const relativePosition = Cartesian3.subtract(
        projectedPosition,
        referencePoint,
        projectedPosition
      );

      result[i] = relativePosition.x;
      result[i + 1] = relativePosition.y;
      result[i + 2] = relativePosition.z;
    }

    return result;
  }

  function createPositionBufferFor2D(
    positionAttribute,
    modelMatrix,
    boundingSphere2D,
    frameState
  ) {
    // Force the scene mode to be CV. In 2D, projected positions will have
    // an x-coordinate of 0, which eliminates the height data that is
    // necessary for rendering in CV mode.
    const frameStateCV = clone$1(frameState);
    frameStateCV.mode = SceneMode$1.COLUMBUS_VIEW;

    // To prevent jitter, the positions are defined relative to a common
    // reference point. For convenience, this is the center of the
    // primitive's bounding sphere in 2D.
    const referencePoint = boundingSphere2D.center;
    const projectedPositions = createPositionsTypedArrayFor2D(
      positionAttribute,
      modelMatrix,
      referencePoint,
      frameStateCV
    );

    // Put the resulting data in a GPU buffer.
    const buffer = Buffer$1.createVertexBuffer({
      context: frameState.context,
      typedArray: projectedPositions,
      usage: BufferUsage$1.STATIC_DRAW,
    });
    buffer.vertexArrayDestroyable = false;

    return buffer;
  }

  //This file is automatically rebuilt by the Cesium build process.
  var SkinningStageVS = "void skinningStage(inout ProcessedAttributes attributes)\n\
{\n\
mat4 skinningMatrix = getSkinningMatrix();\n\
mat3 skinningMatrixMat3 = mat3(skinningMatrix);\n\
vec4 positionMC = vec4(attributes.positionMC, 1.0);\n\
attributes.positionMC = vec3(skinningMatrix * positionMC);\n\
#ifdef HAS_NORMALS\n\
vec3 normalMC = attributes.normalMC;\n\
attributes.normalMC = skinningMatrixMat3 * normalMC;\n\
#endif\n\
#ifdef HAS_TANGENTS\n\
vec3 tangentMC = attributes.tangentMC;\n\
attributes.tangentMC = skinningMatrixMat3 * tangentMC;\n\
#endif\n\
}\n\
";

  /**
   * The skinning pipeline stage processes the joint matrices of a skinned primitive.
   *
   * @namespace SkinningPipelineStage
   *
   * @private
   */

  const SkinningPipelineStage = {};
  SkinningPipelineStage.name = "SkinningPipelineStage"; // Helps with debugging

  SkinningPipelineStage.FUNCTION_ID_GET_SKINNING_MATRIX = "getSkinningMatrix";
  SkinningPipelineStage.FUNCTION_SIGNATURE_GET_SKINNING_MATRIX =
    "mat4 getSkinningMatrix()";

  /**
   * This pipeline stage processes the joint matrices of a skinned primitive, adding
   * the relevant functions and uniforms to the shaders. The joint and weight attributes
   * themselves are processed in the geometry pipeline stage.
   *
   * Processes a primitive. This stage modifies the following parts of the render resources:
   * <ul>
   *  <li> adds the uniform declaration for the joint matrices in the vertex shader</li>
   *  <li> adds the function to compute the skinning matrix in the vertex shader</li>
   * </ul>
   *
   * @param {PrimitiveRenderResources} renderResources The render resources for this primitive.
   * @param {ModelComponents.Primitive} primitive The primitive.
   * @private
   */
  SkinningPipelineStage.process = function (renderResources, primitive) {
    const shaderBuilder = renderResources.shaderBuilder;

    shaderBuilder.addDefine("HAS_SKINNING", undefined, ShaderDestination$1.VERTEX);
    addGetSkinningMatrixFunction(shaderBuilder, primitive);

    const runtimeNode = renderResources.runtimeNode;
    const jointMatrices = runtimeNode.computedJointMatrices;

    shaderBuilder.addUniform(
      "mat4",
      `u_jointMatrices[${jointMatrices.length}]`,
      ShaderDestination$1.VERTEX
    );

    shaderBuilder.addVertexLines([SkinningStageVS]);

    const uniformMap = {
      u_jointMatrices: function () {
        return runtimeNode.computedJointMatrices;
      },
    };

    renderResources.uniformMap = combine$2(uniformMap, renderResources.uniformMap);
  };

  function getMaximumAttributeSetIndex(primitive) {
    let setIndex = -1;
    const attributes = primitive.attributes;
    const length = attributes.length;
    for (let i = 0; i < length; i++) {
      const attribute = attributes[i];
      const isJointsOrWeights =
        attribute.semantic === VertexAttributeSemantic$1.JOINTS ||
        attribute.semantic === VertexAttributeSemantic$1.WEIGHTS;

      if (!isJointsOrWeights) {
        continue;
      }

      setIndex = Math.max(setIndex, attribute.setIndex);
    }

    return setIndex;
  }

  function addGetSkinningMatrixFunction(shaderBuilder, primitive) {
    shaderBuilder.addFunction(
      SkinningPipelineStage.FUNCTION_ID_GET_SKINNING_MATRIX,
      SkinningPipelineStage.FUNCTION_SIGNATURE_GET_SKINNING_MATRIX,
      ShaderDestination$1.VERTEX
    );

    const initialLine = "mat4 skinnedMatrix = mat4(0);";
    shaderBuilder.addFunctionLines(
      SkinningPipelineStage.FUNCTION_ID_GET_SKINNING_MATRIX,
      [initialLine]
    );

    let setIndex;
    let componentIndex;
    const componentStrings = ["x", "y", "z", "w"];
    const maximumSetIndex = getMaximumAttributeSetIndex(primitive);
    for (setIndex = 0; setIndex <= maximumSetIndex; setIndex++) {
      for (componentIndex = 0; componentIndex <= 3; componentIndex++) {
        const component = componentStrings[componentIndex];
        // Example: skinnedMatrix += a_weights_0.x * u_jointMatrices[int(a_joints_0.x)];
        const line = `skinnedMatrix += a_weights_${setIndex}.${component} * u_jointMatrices[int(a_joints_${setIndex}.${component})];`;
        shaderBuilder.addFunctionLines(
          SkinningPipelineStage.FUNCTION_ID_GET_SKINNING_MATRIX,
          [line]
        );
      }
    }

    const returnLine = "return skinnedMatrix;";
    shaderBuilder.addFunctionLines(
      SkinningPipelineStage.FUNCTION_ID_GET_SKINNING_MATRIX,
      [returnLine]
    );
  }

  /**
   * The wireframe pipeline stage generates a new index buffer for rendering the
   * structure of the mesh with gl.LINES.
   *
   * @namespace WireframePipelineStage
   * @private
   */
  const WireframePipelineStage = {};
  WireframePipelineStage.name = "WireframePipelineStage"; // Helps with debugging

  /**
   * Process a primitive. This modifies the render resources as follows:
   * <ul>
   *   <li>Adds a separate index buffer for wireframe indices</li>
   *   <li>Updates the primitive type and count for rendering with gl.LINES</li>
   * </ul>
   *
   * @param {PrimitiveRenderResources} renderResources The render resources for this node
   * @param {ModelComponents.primitive} primitive The primitive
   * @param {FrameState} frameState The frame state
   */
  WireframePipelineStage.process = function (
    renderResources,
    primitive,
    frameState
  ) {
    const model = renderResources.model;
    const wireframeIndexBuffer = createWireframeIndexBuffer(
      primitive,
      renderResources.indices,
      frameState
    );
    model._pipelineResources.push(wireframeIndexBuffer);
    renderResources.wireframeIndexBuffer = wireframeIndexBuffer;

    // We only need to count memory for the generated buffer. In WebGL 1, the CPU
    // copy of the original indices is already counted in the geometry stage,
    // and in WebGL 2, the CPU copy of the original indices (generated from the
    // data of the original buffer) is discarded after generating the wireframe
    // indices.
    const hasCpuCopy = false;
    model.statistics.addBuffer(wireframeIndexBuffer, hasCpuCopy);

    // Update render resources so we render LINES with the correct index count
    const originalPrimitiveType = renderResources.primitiveType;
    const originalCount = renderResources.count;
    renderResources.primitiveType = PrimitiveType$1.LINES;
    renderResources.count = WireframeIndexGenerator.getWireframeIndicesCount(
      originalPrimitiveType,
      originalCount
    );
  };

  function createWireframeIndexBuffer(primitive, indices, frameState) {
    const positionAttribute = ModelExperimentalUtility.getAttributeBySemantic(
      primitive,
      VertexAttributeSemantic$1.POSITION
    );
    const vertexCount = positionAttribute.count;
    const webgl2 = frameState.context.webgl2;

    let originalIndices;
    if (defined(indices)) {
      const indicesBuffer = indices.buffer;
      const indicesCount = indices.count;
      if (defined(indicesBuffer) && webgl2) {
        const useUint8Array = indicesBuffer.sizeInBytes === indicesCount;
        originalIndices = useUint8Array
          ? new Uint8Array(indicesCount)
          : IndexDatatype$1.createTypedArray(vertexCount, indicesCount);

        indicesBuffer.getBufferData(originalIndices);
      } else {
        originalIndices = indices.typedArray;
      }
    }

    const primitiveType = primitive.primitiveType;
    const wireframeIndices = WireframeIndexGenerator.createWireframeIndices(
      primitiveType,
      vertexCount,
      originalIndices
    );
    const indexDatatype = IndexDatatype$1.fromSizeInBytes(
      wireframeIndices.BYTES_PER_ELEMENT
    );

    return Buffer$1.createIndexBuffer({
      context: frameState.context,
      typedArray: wireframeIndices,
      usage: BufferUsage$1.STATIC_DRAW,
      indexDatatype: indexDatatype,
    });
  }

  /**
   * In memory representation of a single primitive, that is, a primitive
   * and its corresponding mesh.
   *
   * @param {Object} options An object containing the following options:
   * @param {ModelComponents.Primitive} options.primitive The primitive component.
   * @param {ModelComponents.Node} options.node The node that this primitive belongs to.
   * @param {ModelExperimental} options.model The {@link ModelExperimental} this primitive belongs to.
   *
   * @alias ModelExperimentalPrimitive
   * @constructor
   *
   * @private
   */
  function ModelExperimentalPrimitive(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const primitive = options.primitive;
    const node = options.node;
    const model = options.model;
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.primitive", primitive);
    Check.typeOf.object("options.node", node);
    Check.typeOf.object("options.model", model);
    //>>includeEnd('debug');

    /**
     * The primitive component associated with this primitive.
     *
     * @type {ModelComponents.Primitive}
     *
     * @private
     */
    this.primitive = primitive;

    /**
     * A reference to the node this primitive belongs to.
     *
     * @type {ModelComponents.Node}
     *
     * @private
     */
    this.node = node;

    /**
     * A reference to the model
     *
     * @type {ModelExperimental}
     *
     * @private
     */
    this.model = model;

    /**
     * Pipeline stages to apply to this primitive. This
     * is an array of classes, each with a static method called
     * <code>process()</code>
     *
     * @type {Object[]}
     * @readonly
     *
     * @private
     */
    this.pipelineStages = [];

    /**
     * The generated {@link ModelExperimentalDrawCommand} associated with this primitive.
     *
     * @type {ModelExperimentalDrawCommand}
     *
     * @private
     */
    this.drawCommand = undefined;

    /**
     * The bounding sphere of this primitive in object-space.
     *
     * @type {BoundingSphere}
     *
     * @private
     */
    this.boundingSphere = undefined;

    /**
     * The bounding sphere of this primitive in 2D world space.
     *
     * @type {BoundingSphere}
     *
     * @private
     */
    this.boundingSphere2D = undefined;

    /**
     * A buffer containing the primitive's positions projected to 2D world coordinates.
     * Used for rendering in 2D / CV mode. The memory is managed by ModelExperimental;
     * this is just a reference.
     *
     * @type {Buffer}
     * @readonly
     *
     * @private
     */
    this.positionBuffer2D = undefined;

    /**
     * Update stages to apply to this primitive.
     *
     * @private
     */
    this.updateStages = [];
  }

  /**
   * Configure the primitive pipeline stages. If the pipeline needs to be re-run,
   * call this method again to ensure the correct sequence of pipeline stages are
   * used.
   *
   * @param {FrameState} frameState The frame state.
   *
   * @private
   */
  ModelExperimentalPrimitive.prototype.configurePipeline = function (frameState) {
    const pipelineStages = this.pipelineStages;
    pipelineStages.length = 0;

    const primitive = this.primitive;
    const node = this.node;
    const model = this.model;
    const customShader = model.customShader;
    const useWebgl2 = frameState.context.webgl2;
    const mode = frameState.mode;

    const use2D =
      mode !== SceneMode$1.SCENE3D && !frameState.scene3DOnly && model._projectTo2D;
    const hasMorphTargets =
      defined(primitive.morphTargets) && primitive.morphTargets.length > 0;
    const hasSkinning = defined(node.skin);
    const hasCustomShader = defined(customShader);
    const hasCustomFragmentShader =
      hasCustomShader && defined(customShader.fragmentShaderText);
    const materialsEnabled =
      !hasCustomFragmentShader ||
      customShader.mode !== CustomShaderMode$1.REPLACE_MATERIAL;
    const hasQuantization = ModelExperimentalUtility.hasQuantizedAttributes(
      primitive.attributes
    );
    const generateWireframeIndices =
      model.debugWireframe &&
      PrimitiveType$1.isTriangles(primitive.primitiveType) &&
      // Generating index buffers for wireframes is always possible in WebGL2.
      // However, this will only work in WebGL1 if the model was constructed with
      // enableDebugWireframe set to true.
      (model._enableDebugWireframe || useWebgl2);

    const pointCloudShading = model.pointCloudShading;
    const hasAttenuation =
      defined(pointCloudShading) && pointCloudShading.attenuation;

    const featureIdFlags = inspectFeatureIds(model, node, primitive);

    // Start of pipeline -----------------------------------------------------
    if (use2D) {
      pipelineStages.push(SceneMode2DPipelineStage);
    }

    pipelineStages.push(GeometryPipelineStage);

    if (generateWireframeIndices) {
      pipelineStages.push(WireframePipelineStage);
    }

    if (hasMorphTargets) {
      pipelineStages.push(MorphTargetsPipelineStage);
    }

    if (hasSkinning) {
      pipelineStages.push(SkinningPipelineStage);
    }

    if (hasAttenuation && primitive.primitiveType === PrimitiveType$1.POINTS) {
      pipelineStages.push(PointCloudAttenuationPipelineStage);
    }

    if (hasQuantization) {
      pipelineStages.push(DequantizationPipelineStage);
    }

    if (materialsEnabled) {
      pipelineStages.push(MaterialPipelineStage);
    }

    // These stages are always run to ensure structs
    // are declared to avoid compilation errors.
    pipelineStages.push(FeatureIdPipelineStage);
    pipelineStages.push(MetadataPipelineStage);

    if (featureIdFlags.hasPropertyTable) {
      pipelineStages.push(SelectedFeatureIdPipelineStage);
      pipelineStages.push(BatchTexturePipelineStage);
      pipelineStages.push(CPUStylingPipelineStage);
    }

    if (hasCustomShader) {
      pipelineStages.push(CustomShaderPipelineStage);
    }

    pipelineStages.push(LightingPipelineStage);

    if (model.allowPicking) {
      pipelineStages.push(PickingPipelineStage);
    }

    pipelineStages.push(AlphaPipelineStage);

    pipelineStages.push(PrimitiveStatisticsPipelineStage);

    return;
  };

  function inspectFeatureIds(model, node, primitive) {
    let featureIds;
    // Check instances first, as this is the most specific type of
    // feature ID
    if (defined(node.instances)) {
      featureIds = ModelExperimentalUtility.getFeatureIdsByLabel(
        node.instances.featureIds,
        model.instanceFeatureIdLabel
      );

      if (defined(featureIds)) {
        return {
          hasFeatureIds: true,
          hasPropertyTable: defined(featureIds.propertyTableId),
        };
      }
    }

    featureIds = ModelExperimentalUtility.getFeatureIdsByLabel(
      primitive.featureIds,
      model.featureIdLabel
    );
    if (defined(featureIds)) {
      return {
        hasFeatureIds: true,
        hasPropertyTable: defined(featureIds.propertyTableId),
      };
    }

    return {
      hasFeatureIds: false,
      hasPropertyTable: false,
    };
  }

  //This file is automatically rebuilt by the Cesium build process.
  var InstancingStageCommon = "mat4 getInstancingTransform()\n\
{\n\
mat4 instancingTransform;\n\
#ifdef HAS_INSTANCE_MATRICES\n\
instancingTransform = mat4(\n\
a_instancingTransformRow0.x, a_instancingTransformRow1.x, a_instancingTransformRow2.x, 0.0,\n\
a_instancingTransformRow0.y, a_instancingTransformRow1.y, a_instancingTransformRow2.y, 0.0,\n\
a_instancingTransformRow0.z, a_instancingTransformRow1.z, a_instancingTransformRow2.z, 0.0,\n\
a_instancingTransformRow0.w, a_instancingTransformRow1.w, a_instancingTransformRow2.w, 1.0\n\
);\n\
#else\n\
vec3 translation = vec3(0.0, 0.0, 0.0);\n\
vec3 scale = vec3(1.0, 1.0, 1.0);\n\
#ifdef HAS_INSTANCE_TRANSLATION\n\
translation = a_instanceTranslation;\n\
#endif\n\
#ifdef HAS_INSTANCE_SCALE\n\
scale = a_instanceScale;\n\
#endif\n\
instancingTransform = mat4(\n\
scale.x, 0.0, 0.0, 0.0,\n\
0.0, scale.y, 0.0, 0.0,\n\
0.0, 0.0, scale.z, 0.0,\n\
translation.x, translation.y, translation.z, 1.0\n\
);\n\
#endif\n\
return instancingTransform;\n\
}\n\
#ifdef USE_2D_INSTANCING\n\
mat4 getInstancingTransform2D()\n\
{\n\
mat4 instancingTransform2D;\n\
#ifdef HAS_INSTANCE_MATRICES\n\
instancingTransform2D = mat4(\n\
a_instancingTransform2DRow0.x, a_instancingTransform2DRow1.x, a_instancingTransform2DRow2.x, 0.0,\n\
a_instancingTransform2DRow0.y, a_instancingTransform2DRow1.y, a_instancingTransform2DRow2.y, 0.0,\n\
a_instancingTransform2DRow0.z, a_instancingTransform2DRow1.z, a_instancingTransform2DRow2.z, 0.0,\n\
a_instancingTransform2DRow0.w, a_instancingTransform2DRow1.w, a_instancingTransform2DRow2.w, 1.0\n\
);\n\
#else\n\
vec3 translation2D = vec3(0.0, 0.0, 0.0);\n\
vec3 scale = vec3(1.0, 1.0, 1.0);\n\
#ifdef HAS_INSTANCE_TRANSLATION\n\
translation2D = a_instanceTranslation2D;\n\
#endif\n\
#ifdef HAS_INSTANCE_SCALE\n\
scale = a_instanceScale;\n\
#endif\n\
instancingTransform2D = mat4(\n\
scale.x, 0.0, 0.0, 0.0,\n\
0.0, scale.y, 0.0, 0.0,\n\
0.0, 0.0, scale.z, 0.0,\n\
translation2D.x, translation2D.y, translation2D.z, 1.0\n\
);\n\
#endif\n\
return instancingTransform2D;\n\
}\n\
#endif\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var InstancingStageVS = "void instancingStage(inout ProcessedAttributes attributes)\n\
{\n\
vec3 positionMC = attributes.positionMC;\n\
mat4 instancingTransform = getInstancingTransform();\n\
attributes.positionMC = (instancingTransform * vec4(positionMC, 1.0)).xyz;\n\
#ifdef USE_2D_INSTANCING\n\
mat4 instancingTransform2D = getInstancingTransform2D();\n\
attributes.position2D = (instancingTransform2D * vec4(positionMC, 1.0)).xyz;\n\
#endif\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var LegacyInstancingStageVS = "void legacyInstancingStage(\n\
inout ProcessedAttributes attributes,\n\
out mat4 instanceModelView,\n\
out mat3 instanceModelViewInverseTranspose)\n\
{\n\
vec3 positionMC = attributes.positionMC;\n\
mat4 instancingTransform = getInstancingTransform();\n\
mat4 instanceModel = instancingTransform * u_instance_nodeTransform;\n\
instanceModelView = u_instance_modifiedModelView;\n\
instanceModelViewInverseTranspose = mat3(u_instance_modifiedModelView * instanceModel);\n\
attributes.positionMC = (instanceModel * vec4(positionMC, 1.0)).xyz;\n\
#ifdef USE_2D_INSTANCING\n\
mat4 instancingTransform2D = getInstancingTransform2D();\n\
attributes.position2D = (instancingTransform2D * vec4(positionMC, 1.0)).xyz;\n\
#endif\n\
}\n\
";

  const modelViewScratch = new Matrix4();
  const nodeTransformScratch = new Matrix4();
  const modelView2DScratch = new Matrix4();

  /**
   * The instancing pipeline stage is responsible for handling GPU mesh instancing at the node
   * level.
   *
   * @namespace InstancingPipelineStage
   * @private
   */
  const InstancingPipelineStage = {};
  InstancingPipelineStage.name = "InstancingPipelineStage"; // Helps with debugging

  /**
   * Process a node. This modifies the following parts of the render resources:
   * <ul>
   *  <li> creates buffers for the typed arrays of each attribute, if they do not yet exist
   *  <li> adds attribute declarations for the instancing vertex attributes in the vertex shader</li>
   *  <li> adds an instancing translation min and max to compute an accurate bounding volume</li>
   * </ul>
   *
   * If the scene is in either 2D or CV mode, this stage also:
   * <ul>
   *  <li> adds additional attributes for the transformation attributes projected to 2D
   *  <li> adds a flag to the shader to use the 2D instanced attributes
   *  <li> adds a uniform for the view model matrix in 2D
   * </ul>
   *
   * @param {NodeRenderResources} renderResources The render resources for this node.
   * @param {ModelComponents.Node} node The node.
   * @param {FrameState} frameState The frame state.
   */
  InstancingPipelineStage.process = function (renderResources, node, frameState) {
    const instances = node.instances;
    const count = instances.attributes[0].count;

    const shaderBuilder = renderResources.shaderBuilder;
    shaderBuilder.addDefine("HAS_INSTANCING");
    shaderBuilder.addVertexLines([InstancingStageCommon]);

    const model = renderResources.model;
    const sceneGraph = model.sceneGraph;
    const use2D =
      frameState.mode !== SceneMode$1.SCENE3D &&
      !frameState.scene3DOnly &&
      model._projectTo2D;

    const instancingVertexAttributes = [];

    processTransformAttributes(
      renderResources,
      frameState,
      instances,
      instancingVertexAttributes,
      use2D
    );

    processFeatureIdAttributes(
      renderResources,
      frameState,
      instances,
      instancingVertexAttributes
    );

    const uniformMap = {};

    if (instances.transformInWorldSpace) {
      shaderBuilder.addDefine(
        "USE_LEGACY_INSTANCING",
        undefined,
        ShaderDestination$1.VERTEX
      );
      shaderBuilder.addUniform(
        "mat4",
        "u_instance_modifiedModelView",
        ShaderDestination$1.VERTEX
      );
      shaderBuilder.addUniform(
        "mat4",
        "u_instance_nodeTransform",
        ShaderDestination$1.VERTEX
      );

      // The i3dm format applies the instancing transforms in world space.
      // Instancing matrices come from a vertex attribute rather than a
      // uniform, and they are multiplied in the middle of the modelView matrix
      // product. This means czm_modelView can't be used. Instead, we split the
      // matrix into two parts, modifiedModelView and nodeTransform, and handle
      // this in LegacyInstancingStageVS.glsl. Conceptually the product looks like
      // this:
      //
      // modelView = u_modifiedModelView * a_instanceTransform * u_nodeTransform
      uniformMap.u_instance_modifiedModelView = function () {
        // Model matrix without the node hierarchy or axis correction
        // (see u_instance_nodeTransform).
        let modifiedModelMatrix = Matrix4.multiplyTransformation(
          // For 3D Tiles, model.modelMatrix is the computed tile
          // transform (which includes tileset.modelMatrix). This always applies
          // for i3dm, since such models are always part of a tileset.
          model.modelMatrix,
          // For i3dm models, components.transform contains the RTC_CENTER
          // translation.
          sceneGraph.components.transform,
          modelViewScratch
        );

        if (use2D) {
          // If projectTo2D is enabled, the 2D view matrix
          // will be accounted for in the u_modelView2D
          // uniform.
          //
          // modifiedModelView = view3D * modifiedModel
          return Matrix4.multiplyTransformation(
            frameState.context.uniformState.view3D,
            modifiedModelMatrix,
            modelViewScratch
          );
        }

        // For projection to 2D without projectTo2D enabled,
        // project the model matrix to 2D.
        if (frameState.mode !== SceneMode$1.SCENE3D) {
          modifiedModelMatrix = Transforms.basisTo2D(
            frameState.mapProjection,
            modifiedModelMatrix,
            modelViewScratch
          );
        }

        // modifiedModelView = view * modifiedModel
        return Matrix4.multiplyTransformation(
          frameState.context.uniformState.view,
          modifiedModelMatrix,
          modelViewScratch
        );
      };

      uniformMap.u_instance_nodeTransform = function () {
        // nodeTransform = axisCorrection * nodeHierarchyTransform
        return Matrix4.multiplyTransformation(
          // glTF y-up to 3D Tiles z-up
          sceneGraph.axisCorrectionMatrix,
          // This transforms from the node's coordinate system to the root
          // of the node hierarchy
          renderResources.runtimeNode.computedTransform,
          nodeTransformScratch
        );
      };

      shaderBuilder.addVertexLines([LegacyInstancingStageVS]);
    } else {
      shaderBuilder.addVertexLines([InstancingStageVS]);
    }

    if (use2D) {
      shaderBuilder.addDefine(
        "USE_2D_INSTANCING",
        undefined,
        ShaderDestination$1.VERTEX
      );

      shaderBuilder.addUniform("mat4", "u_modelView2D", ShaderDestination$1.VERTEX);

      const context = frameState.context;
      const modelMatrix2D = Matrix4.fromTranslation(
        renderResources.instancingReferencePoint2D,
        new Matrix4()
      );

      uniformMap.u_modelView2D = function () {
        return Matrix4.multiplyTransformation(
          context.uniformState.view,
          modelMatrix2D,
          modelView2DScratch
        );
      };
    }

    renderResources.uniformMap = combine$2(uniformMap, renderResources.uniformMap);

    renderResources.instanceCount = count;
    renderResources.attributes.push.apply(
      renderResources.attributes,
      instancingVertexAttributes
    );
  };

  const projectedTransformScratch = new Matrix4();
  const projectedPositionScratch = new Cartesian3();

  function projectTransformTo2D(
    transform,
    modelMatrix,
    nodeTransform,
    frameState,
    result
  ) {
    let projectedTransform = Matrix4.multiplyTransformation(
      modelMatrix,
      transform,
      projectedTransformScratch
    );

    projectedTransform = Matrix4.multiplyTransformation(
      projectedTransform,
      nodeTransform,
      projectedTransformScratch
    );

    result = Transforms.basisTo2D(
      frameState.mapProjection,
      projectedTransform,
      result
    );

    return result;
  }

  function projectPositionTo2D(
    position,
    modelMatrix,
    nodeTransform,
    frameState,
    result
  ) {
    const translationMatrix = Matrix4.fromTranslation(
      position,
      projectedTransformScratch
    );

    let projectedTransform = Matrix4.multiplyTransformation(
      modelMatrix,
      translationMatrix,
      projectedTransformScratch
    );

    projectedTransform = Matrix4.multiplyTransformation(
      projectedTransform,
      nodeTransform,
      projectedTransformScratch
    );

    const finalPosition = Matrix4.getTranslation(
      projectedTransform,
      projectedPositionScratch
    );

    result = SceneTransforms.computeActualWgs84Position(
      frameState,
      finalPosition,
      result
    );

    return result;
  }

  function getModelMatrixAndNodeTransform(
    renderResources,
    modelMatrix,
    nodeComputedTransform
  ) {
    const model = renderResources.model;
    const sceneGraph = model.sceneGraph;

    const instances = renderResources.runtimeNode.node.instances;
    if (instances.transformInWorldSpace) {
      // Replicate the multiplication order in LegacyInstancingStageVS.
      modelMatrix = Matrix4.multiplyTransformation(
        model.modelMatrix,
        sceneGraph.components.transform,
        modelMatrix
      );

      nodeComputedTransform = Matrix4.multiplyTransformation(
        sceneGraph.axisCorrectionMatrix,
        renderResources.runtimeNode.computedTransform,
        nodeComputedTransform
      );
    } else {
      // The node transform should be pre-multiplied with the instancing transform.
      modelMatrix = Matrix4.clone(sceneGraph.computedModelMatrix, modelMatrix);
      modelMatrix = Matrix4.multiplyTransformation(
        modelMatrix,
        renderResources.runtimeNode.computedTransform,
        modelMatrix
      );

      nodeComputedTransform = Matrix4.clone(
        Matrix4.IDENTITY,
        nodeComputedTransform
      );
    }
  }

  const modelMatrixScratch$2 = new Matrix4();
  const nodeComputedTransformScratch = new Matrix4();
  const transformScratch = new Matrix4();
  const positionScratch$6 = new Cartesian3();

  function projectTransformsTo2D(
    transforms,
    renderResources,
    frameState,
    result
  ) {
    const modelMatrix = modelMatrixScratch$2;
    const nodeComputedTransform = nodeComputedTransformScratch;

    getModelMatrixAndNodeTransform(
      renderResources,
      modelMatrix,
      nodeComputedTransform
    );

    const referencePoint = renderResources.instancingReferencePoint2D;
    const count = transforms.length;
    for (let i = 0; i < count; i++) {
      const transform = transforms[i];

      const projectedTransform = projectTransformTo2D(
        transform,
        modelMatrix,
        nodeComputedTransform,
        frameState,
        transformScratch
      );

      const position = Matrix4.getTranslation(
        projectedTransform,
        positionScratch$6
      );

      const finalTranslation = Cartesian3.subtract(
        position,
        referencePoint,
        position
      );

      result[i] = Matrix4.setTranslation(
        projectedTransform,
        finalTranslation,
        result[i]
      );
    }

    return result;
  }

  function projectTranslationsTo2D(
    translations,
    renderResources,
    frameState,
    result
  ) {
    const modelMatrix = modelMatrixScratch$2;
    const nodeComputedTransform = nodeComputedTransformScratch;

    getModelMatrixAndNodeTransform(
      renderResources,
      modelMatrix,
      nodeComputedTransform
    );

    const referencePoint = renderResources.instancingReferencePoint2D;
    const count = translations.length;
    for (let i = 0; i < count; i++) {
      const translation = translations[i];

      const projectedPosition = projectPositionTo2D(
        translation,
        modelMatrix,
        nodeComputedTransform,
        frameState,
        translation
      );

      result[i] = Cartesian3.subtract(
        projectedPosition,
        referencePoint,
        result[i]
      );
    }

    return result;
  }

  const scratchProjectedMin = new Cartesian3();
  const scratchProjectedMax = new Cartesian3();

  function computeReferencePoint2D(renderResources, frameState) {
    // Compute the reference point by averaging the instancing translation
    // min / max values after they are projected to 2D.
    const modelMatrix = renderResources.model.sceneGraph.computedModelMatrix;
    const transformedPositionMin = Matrix4.multiplyByPoint(
      modelMatrix,
      renderResources.instancingTranslationMin,
      scratchProjectedMin
    );

    const projectedMin = SceneTransforms.computeActualWgs84Position(
      frameState,
      transformedPositionMin,
      transformedPositionMin
    );

    const transformedPositionMax = Matrix4.multiplyByPoint(
      modelMatrix,
      renderResources.instancingTranslationMax,
      scratchProjectedMax
    );

    const projectedMax = SceneTransforms.computeActualWgs84Position(
      frameState,
      transformedPositionMax,
      transformedPositionMax
    );

    return Cartesian3.lerp(projectedMin, projectedMax, 0.5, new Cartesian3());
  }

  function transformsToTypedArray(transforms) {
    const elements = 12;
    const count = transforms.length;
    const transformsTypedArray = new Float32Array(count * elements);

    for (let i = 0; i < count; i++) {
      const transform = transforms[i];
      const offset = elements * i;

      transformsTypedArray[offset + 0] = transform[0];
      transformsTypedArray[offset + 1] = transform[4];
      transformsTypedArray[offset + 2] = transform[8];
      transformsTypedArray[offset + 3] = transform[12];
      transformsTypedArray[offset + 4] = transform[1];
      transformsTypedArray[offset + 5] = transform[5];
      transformsTypedArray[offset + 6] = transform[9];
      transformsTypedArray[offset + 7] = transform[13];
      transformsTypedArray[offset + 8] = transform[2];
      transformsTypedArray[offset + 9] = transform[6];
      transformsTypedArray[offset + 10] = transform[10];
      transformsTypedArray[offset + 11] = transform[14];
    }

    return transformsTypedArray;
  }

  function translationsToTypedArray(translations) {
    const elements = 3;
    const count = translations.length;
    const transationsTypedArray = new Float32Array(count * elements);

    for (let i = 0; i < count; i++) {
      const translation = translations[i];
      const offset = elements * i;

      transationsTypedArray[offset + 0] = translation[0];
      transationsTypedArray[offset + 1] = translation[4];
      transationsTypedArray[offset + 2] = translation[8];
    }

    return transationsTypedArray;
  }

  new Cartesian3();
  new Quaternion();
  new Cartesian3();

  function getInstanceTransformsAsMatrices(instances, count, renderResources) {
    const transforms = new Array(count);

    const translationAttribute = ModelExperimentalUtility.getAttributeBySemantic(
      instances,
      InstanceAttributeSemantic$1.TRANSLATION
    );
    const rotationAttribute = ModelExperimentalUtility.getAttributeBySemantic(
      instances,
      InstanceAttributeSemantic$1.ROTATION
    );
    const scaleAttribute = ModelExperimentalUtility.getAttributeBySemantic(
      instances,
      InstanceAttributeSemantic$1.SCALE
    );

    const instancingTranslationMax = new Cartesian3(
      -Number.MAX_VALUE,
      -Number.MAX_VALUE,
      -Number.MAX_VALUE
    );
    const instancingTranslationMin = new Cartesian3(
      Number.MAX_VALUE,
      Number.MAX_VALUE,
      Number.MAX_VALUE
    );

    const hasTranslation = defined(translationAttribute);
    const hasRotation = defined(rotationAttribute);
    const hasScale = defined(scaleAttribute);

    // Translations get initialized to (0, 0, 0).
    const translationTypedArray = hasTranslation
      ? translationAttribute.packedTypedArray
      : new Float32Array(count * 3);
    // Rotations get initialized to (0, 0, 0, 0). The w-component is set to 1 in the loop below.
    const rotationTypedArray = hasRotation
      ? rotationAttribute.packedTypedArray
      : new Float32Array(count * 4);
    // Scales get initialized to (1, 1, 1).
    let scaleTypedArray;
    if (hasScale) {
      scaleTypedArray = scaleAttribute.packedTypedArray;
    } else {
      scaleTypedArray = new Float32Array(count * 3);
      scaleTypedArray.fill(1);
    }

    for (let i = 0; i < count; i++) {
      const translation = new Cartesian3(
        translationTypedArray[i * 3],
        translationTypedArray[i * 3 + 1],
        translationTypedArray[i * 3 + 2]);

      Cartesian3.maximumByComponent(
        instancingTranslationMax,
        translation,
        instancingTranslationMax
      );
      Cartesian3.minimumByComponent(
        instancingTranslationMin,
        translation,
        instancingTranslationMin
      );

      const rotation = new Quaternion(
        rotationTypedArray[i * 4],
        rotationTypedArray[i * 4 + 1],
        rotationTypedArray[i * 4 + 2],
        hasRotation ? rotationTypedArray[i * 4 + 3] : 1);

      const scale = new Cartesian3(
        scaleTypedArray[i * 3],
        scaleTypedArray[i * 3 + 1],
        scaleTypedArray[i * 3 + 2]);

      const transform = Matrix4.fromTranslationQuaternionRotationScale(
        translation,
        rotation,
        scale,
        new Matrix4()
      );

      transforms[i] = transform;
    }

    renderResources.instancingTranslationMax = instancingTranslationMax;
    renderResources.instancingTranslationMin = instancingTranslationMin;

    return transforms;
  }

  function getInstanceTranslationsAsCartesian3s(translationAttribute, count) {
    const translations = new Array(count);
    const translationTypedArray = translationAttribute.packedTypedArray;

    for (let i = 0; i < count; i++) {
      translations[i] = new Cartesian3(
        translationTypedArray[i * 3],
        translationTypedArray[i * 3 + 1],
        translationTypedArray[i * 3 + 2]
      );
    }

    return translations;
  }

  function createVertexBuffer(typedArray, frameState) {
    const buffer = Buffer$1.createVertexBuffer({
      context: frameState.context,
      typedArray: typedArray,
      usage: BufferUsage$1.STATIC_DRAW,
    });

    // Destruction of resources allocated by the ModelExperimental
    // is handled by ModelExperimental.destroy().
    buffer.vertexArrayDestroyable = false;

    return buffer;
  }

  function processTransformAttributes(
    renderResources,
    frameState,
    instances,
    instancingVertexAttributes,
    use2D
  ) {
    const translationAttribute = ModelExperimentalUtility.getAttributeBySemantic(
      instances,
      InstanceAttributeSemantic$1.TRANSLATION
    );

    let translationMax;
    let translationMin;
    if (defined(translationAttribute)) {
      translationMax = translationAttribute.max;
      translationMin = translationAttribute.min;
    }

    const rotationAttribute = ModelExperimentalUtility.getAttributeBySemantic(
      instances,
      InstanceAttributeSemantic$1.ROTATION
    );

    const shaderBuilder = renderResources.shaderBuilder;
    const count = instances.attributes[0].count;
    const useMatrices =
      defined(rotationAttribute) ||
      !defined(translationMax) ||
      !defined(translationMin);

    const statistics = renderResources.model.statistics;

    // Packed typed arrays are omitted from statistics because they don't
    // necessarily correspond to the size of the GPU buffer containing
    // their data. It's also difficult to track which typed arrays have
    // already been counted.
    const hasCpuCopy = false;

    let transforms;
    if (useMatrices) {
      shaderBuilder.addDefine("HAS_INSTANCE_MATRICES");
      const attributeString = "Transform";

      transforms = getInstanceTransformsAsMatrices(
        instances,
        count,
        renderResources
      );

      const transformsTypedArray = transformsToTypedArray(transforms);
      const buffer = createVertexBuffer(transformsTypedArray, frameState);
      renderResources.model._pipelineResources.push(buffer);

      processMatrixAttributes(
        renderResources,
        buffer,
        instancingVertexAttributes,
        attributeString
      );

      // Count the buffer here since it had to be allocated
      // in this stage.
      statistics.addBuffer(buffer, hasCpuCopy);
    } else {
      if (defined(translationAttribute)) {
        shaderBuilder.addDefine("HAS_INSTANCE_TRANSLATION");

        const translationMax = translationAttribute.max;
        const translationMin = translationAttribute.min;
        renderResources.instancingTranslationMax = translationMax;
        renderResources.instancingTranslationMin = translationMin;

        let buffer = translationAttribute.buffer;
        let byteOffset = translationAttribute.byteOffset;
        let byteStride = translationAttribute.byteStride;

        if (!defined(buffer)) {
          buffer = createVertexBuffer(
            translationAttribute.packedTypedArray,
            frameState
          );
          renderResources.model._pipelineResources.push(buffer);

          byteOffset = 0;
          byteStride = undefined;

          // Count the buffer here if it had to be allocated
          // in this stage. Otherwise, it will be counted in
          // NodeStatisticsPipelineStage.
          statistics.addBuffer(buffer, hasCpuCopy);
        }

        const attributeString = "Translation";

        processVec3Attribute(
          renderResources,
          buffer,
          byteOffset,
          byteStride,
          instancingVertexAttributes,
          attributeString
        );
      }

      const scaleAttribute = ModelExperimentalUtility.getAttributeBySemantic(
        instances,
        InstanceAttributeSemantic$1.SCALE
      );

      if (defined(scaleAttribute)) {
        shaderBuilder.addDefine("HAS_INSTANCE_SCALE");

        let buffer = scaleAttribute.buffer;
        let byteOffset = scaleAttribute.byteOffset;
        let byteStride = scaleAttribute.byteStride;

        if (!defined(buffer)) {
          buffer = createVertexBuffer(
            scaleAttribute.packedTypedArray,
            frameState
          );
          renderResources.model._pipelineResources.push(buffer);

          byteOffset = 0;
          byteStride = undefined;

          // Count the buffer here if it had to be allocated
          // in this stage. Otherwise, it will be counted in
          // NodeStatisticsPipelineStage.
          statistics.addBuffer(buffer, hasCpuCopy);
        }

        const attributeString = "Scale";

        processVec3Attribute(
          renderResources,
          buffer,
          byteOffset,
          byteStride,
          instancingVertexAttributes,
          attributeString
        );
      }
    }

    if (!use2D) {
      return;
    }

    // Force the scene mode to be CV. In 2D, projected positions will have
    // an x-coordinate of 0, which eliminates the height data that is
    // necessary for rendering in CV mode.
    const frameStateCV = clone$1(frameState);
    frameStateCV.mode = SceneMode$1.COLUMBUS_VIEW;

    // To prevent jitter, the positions are defined relative to a common
    // reference point. For convenience, this is the center of the instanced
    // translation bounds projected to 2D.
    const referencePoint = computeReferencePoint2D(renderResources, frameStateCV);
    renderResources.instancingReferencePoint2D = referencePoint;

    const runtimeNode = renderResources.runtimeNode;

    if (useMatrices) {
      let buffer = runtimeNode.instancingTransformsBuffer2D;
      if (!defined(buffer)) {
        const projectedTransforms = projectTransformsTo2D(
          transforms,
          renderResources,
          frameStateCV,
          transforms
        );
        const projectedTypedArray = transformsToTypedArray(projectedTransforms);

        // This memory is counted during the statistics stage at the end
        // of the pipeline.
        buffer = createVertexBuffer(projectedTypedArray, frameState);
        renderResources.model._modelResources.push(buffer);

        runtimeNode.instancingTransformsBuffer2D = buffer;
      }

      const attributeString2D = "Transform2D";
      processMatrixAttributes(
        renderResources,
        buffer,
        instancingVertexAttributes,
        attributeString2D
      );
    } else {
      let buffer = runtimeNode.instancingTranslationBuffer2D;

      if (!defined(buffer)) {
        const translations = getInstanceTranslationsAsCartesian3s(
          translationAttribute,
          count
        );
        const projectedTranslations = projectTranslationsTo2D(
          translations,
          renderResources,
          frameStateCV,
          translations
        );
        const projectedTypedArray = translationsToTypedArray(
          projectedTranslations
        );

        // This memory is counted during the statistics stage at the end
        // of the pipeline.
        buffer = createVertexBuffer(projectedTypedArray, frameState);
        renderResources.model._modelResources.push(buffer);

        runtimeNode.instancingTranslationBuffer2D = buffer;
      }

      const byteOffset = 0;
      const byteStride = undefined;

      const attributeString2D = "Translation2D";
      processVec3Attribute(
        renderResources,
        buffer,
        byteOffset,
        byteStride,
        instancingVertexAttributes,
        attributeString2D
      );
    }
  }

  function processMatrixAttributes(
    renderResources,
    buffer,
    instancingVertexAttributes,
    attributeString
  ) {
    const vertexSizeInFloats = 12;
    const componentByteSize = ComponentDatatype$1.getSizeInBytes(
      ComponentDatatype$1.FLOAT
    );
    const strideInBytes = componentByteSize * vertexSizeInFloats;

    const matrixAttributes = [
      {
        index: renderResources.attributeIndex++,
        vertexBuffer: buffer,
        componentsPerAttribute: 4,
        componentDatatype: ComponentDatatype$1.FLOAT,
        normalize: false,
        offsetInBytes: 0,
        strideInBytes: strideInBytes,
        instanceDivisor: 1,
      },
      {
        index: renderResources.attributeIndex++,
        vertexBuffer: buffer,
        componentsPerAttribute: 4,
        componentDatatype: ComponentDatatype$1.FLOAT,
        normalize: false,
        offsetInBytes: componentByteSize * 4,
        strideInBytes: strideInBytes,
        instanceDivisor: 1,
      },
      {
        index: renderResources.attributeIndex++,
        vertexBuffer: buffer,
        componentsPerAttribute: 4,
        componentDatatype: ComponentDatatype$1.FLOAT,
        normalize: false,
        offsetInBytes: componentByteSize * 8,
        strideInBytes: strideInBytes,
        instanceDivisor: 1,
      },
    ];

    const shaderBuilder = renderResources.shaderBuilder;
    shaderBuilder.addAttribute("vec4", `a_instancing${attributeString}Row0`);
    shaderBuilder.addAttribute("vec4", `a_instancing${attributeString}Row1`);
    shaderBuilder.addAttribute("vec4", `a_instancing${attributeString}Row2`);

    instancingVertexAttributes.push.apply(
      instancingVertexAttributes,
      matrixAttributes
    );
  }

  function processVec3Attribute(
    renderResources,
    buffer,
    byteOffset,
    byteStride,
    instancingVertexAttributes,
    attributeString
  ) {
    instancingVertexAttributes.push({
      index: renderResources.attributeIndex++,
      vertexBuffer: buffer,
      componentsPerAttribute: 3,
      componentDatatype: ComponentDatatype$1.FLOAT,
      normalize: false,
      offsetInBytes: byteOffset,
      strideInBytes: byteStride,
      instanceDivisor: 1,
    });

    const shaderBuilder = renderResources.shaderBuilder;
    shaderBuilder.addAttribute("vec3", `a_instance${attributeString}`);
  }

  function processFeatureIdAttributes(
    renderResources,
    frameState,
    instances,
    instancingVertexAttributes
  ) {
    const attributes = instances.attributes;
    const model = renderResources.model;
    const shaderBuilder = renderResources.shaderBuilder;

    // Load Feature ID vertex attributes. These are loaded as typed arrays in GltfLoader
    // because we want to expose the instance feature ID when picking.
    for (let i = 0; i < attributes.length; i++) {
      const attribute = attributes[i];
      if (attribute.semantic !== InstanceAttributeSemantic$1.FEATURE_ID) {
        continue;
      }

      if (
        attribute.setIndex >= renderResources.featureIdVertexAttributeSetIndex
      ) {
        renderResources.featureIdVertexAttributeSetIndex = attribute.setIndex + 1;
      }

      const vertexBuffer = Buffer$1.createVertexBuffer({
        context: frameState.context,
        typedArray: attribute.packedTypedArray,
        usage: BufferUsage$1.STATIC_DRAW,
      });
      vertexBuffer.vertexArrayDestroyable = false;
      model._pipelineResources.push(vertexBuffer);

      // Packed typed arrays are omitted from statistics because they don't
      // necessarily correspond to the size of the GPU buffer containing
      // their data. It's also difficult to track which typed arrays have
      // already been counted.
      const hasCpuCopy = false;
      model.statistics.addBuffer(vertexBuffer, hasCpuCopy);

      instancingVertexAttributes.push({
        index: renderResources.attributeIndex++,
        vertexBuffer: vertexBuffer,
        componentsPerAttribute: AttributeType$1.getNumberOfComponents(
          attribute.type
        ),
        componentDatatype: attribute.componentDatatype,
        normalize: false,
        offsetInBytes: attribute.byteOffset,
        strideInBytes: attribute.byteStride,
        instanceDivisor: 1,
      });

      shaderBuilder.addAttribute(
        "float",
        `a_instanceFeatureId_${attribute.setIndex}`
      );
    }
  }

  // Exposed for testing
  InstancingPipelineStage._getInstanceTransformsAsMatrices = getInstanceTransformsAsMatrices;
  InstancingPipelineStage._transformsToTypedArray = transformsToTypedArray;

  /**
   * The model matrix update stage is responsible for updating the model matrices and bounding volumes of the draw commands.
   *
   * @namespace ModelMatrixUpdateStage
   *
   * @private
   */
  const ModelMatrixUpdateStage = {};
  ModelMatrixUpdateStage.name = "ModelMatrixUpdateStage"; // Helps with debugging

  /**
   * Processes a runtime node. This modifies the following parts of the scene graph and draw commands:
   * <ul>
   *  <li>updates the transforms the children of any nodes with a dirty transform</li>
   *  <li>updates the model matrix of each draw command in each primitive of the the dirty nodes and their children</li>
   *  <li>updates the bounding volume of each draw command in each primitive of the the dirty nodes and their children</li>
   * </ul>
   *
   * @param {ModelExperimentalNode} runtimeNode
   * @param {ModelExperimentalSceneGraph} sceneGraph
   * @param {FrameState} frameState
   *
   * @private
   */
  ModelMatrixUpdateStage.update = function (runtimeNode, sceneGraph, frameState) {
    // Skip the update stage if the model is being projected to 2D
    const use2D = frameState.mode !== SceneMode$1.SCENE3D;
    if (use2D && sceneGraph._model._projectTo2D) {
      return;
    }

    if (runtimeNode._transformDirty) {
      const modelMatrix = use2D
        ? sceneGraph._computedModelMatrix2D
        : sceneGraph._computedModelMatrix;

      updateRuntimeNode(
        runtimeNode,
        sceneGraph,
        modelMatrix,
        runtimeNode.transformToRoot
      );
      runtimeNode._transformDirty = false;
    }
  };

  /**
   * Recursively update all child runtime nodes and their runtime primitives.
   *
   * @private
   */
  function updateRuntimeNode(
    runtimeNode,
    sceneGraph,
    modelMatrix,
    transformToRoot
  ) {
    let i;

    // Apply the current node's transform to the end of the chain
    transformToRoot = Matrix4.multiplyTransformation(
      transformToRoot,
      runtimeNode.transform,
      new Matrix4()
    );

    runtimeNode.updateComputedTransform();

    const primitivesLength = runtimeNode.runtimePrimitives.length;
    for (i = 0; i < primitivesLength; i++) {
      const runtimePrimitive = runtimeNode.runtimePrimitives[i];
      const drawCommand = runtimePrimitive.drawCommand;
      drawCommand.modelMatrix = Matrix4.multiplyTransformation(
        modelMatrix,
        transformToRoot,
        drawCommand.modelMatrix
      );
      drawCommand.cullFace = ModelExperimentalUtility.getCullFace(
        drawCommand.modelMatrix,
        drawCommand.primitiveType
      );
    }

    const childrenLength = runtimeNode.children.length;
    for (i = 0; i < childrenLength; i++) {
      const childRuntimeNode = sceneGraph._runtimeNodes[runtimeNode.children[i]];

      // Update transformToRoot to accommodate changes in the transforms of this node and its ancestors
      childRuntimeNode._transformToRoot = Matrix4.clone(
        transformToRoot,
        childRuntimeNode._transformToRoot
      );

      updateRuntimeNode(
        childRuntimeNode,
        sceneGraph,
        modelMatrix,
        transformToRoot
      );
      childRuntimeNode._transformDirty = false;
    }
  }

  /**
   * The node statistics update stage updates memory usage statistics for
   * ModelExperimental on the node level. This counts the binary resources
   * that exist for the lifetime of the ModelExperimental (e.g. attributes
   * loaded by GltfLoader). It does not count resources that are created
   * every time the pipeline is run. The individual pipeline stages are
   * responsible for keeping track of additional memory they allocate.
   *
   * @namespace NodeStatisticsPipelineStage
   *
   * @private
   */
  const NodeStatisticsPipelineStage = {};
  NodeStatisticsPipelineStage.name = "NodeStatisticsPipelineStage"; // Helps with debugging

  NodeStatisticsPipelineStage.process = function (
    renderResources,
    node,
    frameState
  ) {
    const model = renderResources.model;
    const statistics = model.statistics;
    const runtimeNode = renderResources.runtimeNode;

    countInstancingAttributes(statistics, node.instances);
    countInstancing2DBuffers(statistics, runtimeNode);
  };

  function countInstancingAttributes(statistics, instances) {
    if (!defined(instances)) {
      return;
    }

    const attributes = instances.attributes;
    const length = attributes.length;
    for (let i = 0; i < length; i++) {
      const attribute = attributes[i];
      if (defined(attribute.buffer)) {
        // Packed typed arrays are not counted
        const hasCpuCopy = false;
        statistics.addBuffer(attribute.buffer, hasCpuCopy);
      }
    }
  }

  function countInstancing2DBuffers(statistics, runtimeNode) {
    if (defined(runtimeNode.instancingTransformsBuffer2D)) {
      // The typed array containing the computed 2D transforms
      // isn't saved after the buffer is created.
      const hasCpuCopy = false;
      statistics.addBuffer(runtimeNode.instancingTransformsBuffer2D, hasCpuCopy);
    }

    if (defined(runtimeNode.instancingTranslationBuffer2D)) {
      // The typed array containing the computed 2D translations
      // isn't saved after the buffer is created.
      const hasCpuCopy = false;
      statistics.addBuffer(runtimeNode.instancingTranslationBuffer2D, hasCpuCopy);
    }
  }

  // Exposed for testing
  NodeStatisticsPipelineStage._countInstancingAttributes = countInstancingAttributes;
  NodeStatisticsPipelineStage._countInstancing2DBuffers = countInstancing2DBuffers;

  /**
   * An in-memory representation of a node as part of the {@link ModelExperimentalSceneGraph}.
   *
   *
   * @param {Object} options An object containing the following options:
   * @param {ModelComponents.Node} options.node The corresponding node components from the 3D model
   * @param {Matrix4} options.transform The transform of this node, excluding transforms from the node's ancestors or children.
   * @param {Matrix4} options.transformToRoot The product of the transforms of all the node's ancestors, excluding the node's own transform.
   * @param {ModelExperimentalSceneGraph} options.sceneGraph The scene graph this node belongs to.
   * @param {Number[]} options.children The indices of the children of this node in the runtime nodes array of the scene graph.
   *
   * @alias ModelExperimentalNode
   * @constructor
   *
   * @private
   */
  function ModelExperimentalNode(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.node", options.node);
    Check.typeOf.object("options.transform", options.transform);
    Check.typeOf.object("options.transformToRoot", options.transformToRoot);
    Check.typeOf.object("options.sceneGraph", options.sceneGraph);
    Check.typeOf.object("options.children", options.children);
    //>>includeEnd('debug');

    const sceneGraph = options.sceneGraph;
    const transform = options.transform;
    const transformToRoot = options.transformToRoot;
    const node = options.node;

    this._sceneGraph = sceneGraph;
    this._children = options.children;
    this._node = node;

    this._name = node.name; // Helps with debugging

    this._originalTransform = Matrix4.clone(transform, this._originalTransform);
    this._transform = Matrix4.clone(transform, this._transform);
    this._transformToRoot = Matrix4.clone(transformToRoot, this._transformToRoot);

    this._computedTransform = new Matrix4(); // Computed in initialize()
    this._transformDirty = false;

    // Used for animation
    this._transformParameters = undefined;
    this._morphWeights = [];

    // Will be set by the scene graph after the skins have been created
    this._runtimeSkin = undefined;
    this._computedJointMatrices = [];

    /**
     * Pipeline stages to apply across all the mesh primitives of this node. This
     * is an array of classes, each with a static method called
     * <code>process()</code>
     *
     * @type {Object[]}
     * @readonly
     *
     * @private
     */
    this.pipelineStages = [];

    /**
     * The mesh primitives that belong to this node
     *
     * @type {ModelExperimentalPrimitive[]}
     * @readonly
     *
     * @private
     */
    this.runtimePrimitives = [];

    /**
     * Update stages to apply to this primitive.
     *
     * @private
     */
    this.updateStages = [];

    /**
     * A buffer containing the instanced transforms projected to 2D world
     * coordinates. Used for rendering in 2D / CV mode. The memory is managed
     * by ModelExperimental; this is just a reference.
     *
     * @type {Buffer}
     * @readonly
     *
     * @private
     */
    this.instancingTransformsBuffer2D = undefined;

    /**
     * A buffer containing the instanced translation values for the node if
     * it is instanced. Used for rendering in 2D / CV mode. The memory is
     * managed by ModelExperimental; this is just a reference.
     *
     * @type {Buffer}
     * @readonly
     *
     * @private
     */
    this.instancingTranslationBuffer2D = undefined;

    initialize$4(this);
  }

  Object.defineProperties(ModelExperimentalNode.prototype, {
    /**
     * The internal node this runtime node represents.
     *
     * @type {ModelComponents.Node}
     * @readonly
     *
     * @private
     */
    node: {
      get: function () {
        return this._node;
      },
    },
    /**
     * The scene graph this node belongs to.
     *
     * @type {ModelExperimentalSceneGraph}
     * @readonly
     *
     * @private
     */
    sceneGraph: {
      get: function () {
        return this._sceneGraph;
      },
    },

    /**
     * The indices of the children of this node in the scene graph.
     *
     * @type {Number[]}
     * @readonly
     */
    children: {
      get: function () {
        return this._children;
      },
    },

    /**
     * The node's local space transform. This can be changed externally so animation
     * can be driven by another source, not just an animation in the model's asset.
     * <p>
     * For changes to take effect, this property must be assigned to;
     * setting individual elements of the matrix will not work.
     * </p>
     *
     * @memberof ModelExperimentalNode.prototype
     * @type {Matrix4}
     */
    transform: {
      get: function () {
        return this._transform;
      },
      set: function (value) {
        if (Matrix4.equals(this._transform, value)) {
          return;
        }
        this._transformDirty = true;
        this._transform = Matrix4.clone(value, this._transform);
      },
    },

    /**
     * The transforms of all the node's ancestors, not including this node's
     * transform.
     *
     * @see ModelExperimentalNode#computedTransform
     *
     * @memberof ModelExperimentalNode.prototype
     * @type {Matrix4}
     * @readonly
     */
    transformToRoot: {
      get: function () {
        return this._transformToRoot;
      },
    },

    /**
     * A transform from the node's local space to the model's scene graph space.
     * This is the product of transformToRoot * transform.
     *
     * @memberof ModelExperimentalNode.prototype
     * @type {Matrix4}
     * @readonly
     */
    computedTransform: {
      get: function () {
        return this._computedTransform;
      },
    },

    /**
     * The node's original transform, as specified in the model. Does not include transformations from the node's ancestors.
     *
     * @memberof ModelExperimentalNode.prototype
     * @type {Matrix4}
     * @readonly
     */
    originalTransform: {
      get: function () {
        return this._originalTransform;
      },
    },

    /**
     * The node's local space translation. This is used internally to allow
     * animations in the model's asset to affect the node's properties.
     *
     * If the node's transformation was originally described using a matrix
     * in the model, then this will return undefined.
     *
     * @memberof ModelExperimentalNode.prototype
     * @type {Cartesian3}
     *
     * @exception {DeveloperError} The translation of a node cannot be set if it was defined using a matrix in the model.
     *
     * @private
     */
    translation: {
      get: function () {
        return defined(this._transformParameters)
          ? this._transformParameters.translation
          : undefined;
      },
      set: function (value) {
        const transformParameters = this._transformParameters;
        //>>includeStart('debug', pragmas.debug);
        if (!defined(transformParameters)) {
          throw new DeveloperError(
            "The translation of a node cannot be set if it was defined using a matrix in the model."
          );
        }
        //>>includeEnd('debug');

        const currentTranslation = transformParameters.translation;
        if (Cartesian3.equals(currentTranslation, value)) {
          return;
        }

        transformParameters.translation = Cartesian3.clone(
          value,
          transformParameters.translation
        );

        updateTransformFromParameters(this, transformParameters);
      },
    },

    /**
     * The node's local space rotation. This is used internally to allow
     * animations in the model's asset to affect the node's properties.
     *
     * If the node's transformation was originally described using a matrix
     * in the model, then this will return undefined.
     *
     * @memberof ModelExperimentalNode.prototype
     * @type {Quaternion}
     *
     * @exception {DeveloperError} The rotation of a node cannot be set if it was defined using a matrix in the model.
     *
     * @private
     */
    rotation: {
      get: function () {
        return defined(this._transformParameters)
          ? this._transformParameters.rotation
          : undefined;
      },
      set: function (value) {
        const transformParameters = this._transformParameters;
        //>>includeStart('debug', pragmas.debug);
        if (!defined(transformParameters)) {
          throw new DeveloperError(
            "The rotation of a node cannot be set if it was defined using a matrix in the model."
          );
        }
        //>>includeEnd('debug');

        const currentRotation = transformParameters.rotation;
        if (Quaternion.equals(currentRotation, value)) {
          return;
        }

        transformParameters.rotation = Quaternion.clone(
          value,
          transformParameters.rotation
        );

        updateTransformFromParameters(this, transformParameters);
      },
    },

    /**
     * The node's local space scale. This is used internally to allow
     * animations in the model's asset to affect the node's properties.
     *
     * If the node's transformation was originally described using a matrix
     * in the model, then this will return undefined.
     *
     * @memberof ModelExperimentalNode.prototype
     * @type {Cartesian3}
     *
     * @exception {DeveloperError} The scale of a node cannot be set if it was defined using a matrix in the model.
     * @private
     */
    scale: {
      get: function () {
        return defined(this._transformParameters)
          ? this._transformParameters.scale
          : undefined;
      },
      set: function (value) {
        const transformParameters = this._transformParameters;
        //>>includeStart('debug', pragmas.debug);
        if (!defined(transformParameters)) {
          throw new DeveloperError(
            "The scale of a node cannot be set if it was defined using a matrix in the model."
          );
        }
        //>>includeEnd('debug');
        const currentScale = transformParameters.scale;
        if (Cartesian3.equals(currentScale, value)) {
          return;
        }

        transformParameters.scale = Cartesian3.clone(
          value,
          transformParameters.scale
        );

        updateTransformFromParameters(this, transformParameters);
      },
    },

    /**
     * The node's morph weights. This is used internally to allow animations
     * in the model's asset to affect the node's properties.
     *
     * @memberof ModelExperimentalNode.prototype
     * @type {Number[]}
     *
     * @private
     */
    morphWeights: {
      get: function () {
        return this._morphWeights;
      },
      set: function (value) {
        const valueLength = value.length;
        //>>includeStart('debug', pragmas.debug);
        if (this._morphWeights.length !== valueLength) {
          throw new DeveloperError(
            "value must have the same length as the original weights array."
          );
        }
        //>>includeEnd('debug');
        for (let i = 0; i < valueLength; i++) {
          this._morphWeights[i] = value[i];
        }
      },
    },

    /**
     * The skin applied to this node, if it exists.
     *
     * @memberof ModelExperimentalNode.prototype
     * @type {ModelExperimentalSkin}
     * @readonly
     */
    runtimeSkin: {
      get: function () {
        return this._runtimeSkin;
      },
    },

    /**
     * The computed joint matrices of this node, derived from its skin.
     *
     * @memberof ModelExperimentalNode.prototype
     * @type {Matrix4[]}
     * @readonly
     */
    computedJointMatrices: {
      get: function () {
        return this._computedJointMatrices;
      },
    },
  });

  function initialize$4(runtimeNode) {
    const transform = runtimeNode.transform;
    const transformToRoot = runtimeNode.transformToRoot;
    const computedTransform = runtimeNode._computedTransform;
    runtimeNode._computedTransform = Matrix4.multiply(
      transformToRoot,
      transform,
      computedTransform
    );

    const node = runtimeNode.node;
    if (!defined(node.matrix)) {
      runtimeNode._transformParameters = new TranslationRotationScale(
        node.translation,
        node.rotation,
        node.scale
      );
    }

    if (defined(node.morphWeights)) {
      runtimeNode._morphWeights = node.morphWeights.slice();
    }

    // If this node is affected by an articulation from the AGI_articulations
    // extension, add this node to its list of affected nodes.
    const articulationName = node.articulationName;
    if (defined(articulationName)) {
      const sceneGraph = runtimeNode.sceneGraph;
      const runtimeArticulations = sceneGraph._runtimeArticulations;

      const runtimeArticulation = runtimeArticulations[articulationName];
      if (defined(runtimeArticulation)) {
        runtimeArticulation.runtimeNodes.push(runtimeNode);
      }
    }
  }

  function updateTransformFromParameters(runtimeNode, transformParameters) {
    runtimeNode._transformDirty = true;

    runtimeNode._transform = Matrix4.fromTranslationRotationScale(
      transformParameters,
      runtimeNode._transform
    );
  }

  /**
   * Returns the child with the given index.
   *
   * @param {Number} index The index of the child.
   *
   * @returns {ModelExperimentalNode}
   *
   * @example
   * // Iterate through all children of a runtime node.
   * for (let i = 0; i < runtimeNode.children.length; i++)
   * {
   *   const childNode = runtimeNode.getChild(i);
   * }
   */
  ModelExperimentalNode.prototype.getChild = function (index) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("index", index);
    if (index < 0 || index >= this.children.length) {
      throw new DeveloperError(
        "index must be greater than or equal to 0 and less than the number of children."
      );
    }
    //>>includeEnd('debug');

    return this.sceneGraph.runtimeNodes[this.children[index]];
  };

  /**
   * Configure the node pipeline stages. If the pipeline needs to be re-run, call
   * this method again to ensure the correct sequence of pipeline stages are
   * used.
   *
   * @private
   */
  ModelExperimentalNode.prototype.configurePipeline = function () {
    const node = this.node;
    const pipelineStages = this.pipelineStages;
    pipelineStages.length = 0;
    const updateStages = this.updateStages;
    updateStages.length = 0;

    if (defined(node.instances)) {
      pipelineStages.push(InstancingPipelineStage);
    }

    pipelineStages.push(NodeStatisticsPipelineStage);

    updateStages.push(ModelMatrixUpdateStage);
  };

  /**
   * Updates the computed transform used for rendering and instancing.
   *
   * @private
   */
  ModelExperimentalNode.prototype.updateComputedTransform = function () {
    this._computedTransform = Matrix4.multiply(
      this._transformToRoot,
      this._transform,
      this._computedTransform
    );
  };

  /**
   * Updates the joint matrices for this node, where each matrix is computed as
   * computedJointMatrix = nodeWorldTransform^(-1) * skinJointMatrix.
   *
   * @private
   */
  ModelExperimentalNode.prototype.updateJointMatrices = function () {
    const runtimeSkin = this._runtimeSkin;
    if (!defined(runtimeSkin)) {
      return;
    }

    runtimeSkin.updateJointMatrices();

    const computedJointMatrices = this._computedJointMatrices;
    const skinJointMatrices = runtimeSkin.jointMatrices;
    const length = skinJointMatrices.length;

    for (let i = 0; i < length; i++) {
      if (!defined(computedJointMatrices[i])) {
        computedJointMatrices[i] = new Matrix4();
      }

      const nodeWorldTransform = Matrix4.multiplyTransformation(
        this.transformToRoot,
        this.transform,
        computedJointMatrices[i]
      );

      const inverseNodeWorldTransform = Matrix4.inverseTransformation(
        nodeWorldTransform,
        computedJointMatrices[i]
      );

      computedJointMatrices[i] = Matrix4.multiplyTransformation(
        inverseNodeWorldTransform,
        skinJointMatrices[i],
        computedJointMatrices[i]
      );
    }
  };

  /**
   * An in-memory representation of a skin that affects nodes in the {@link ModelExperimentalSceneGraph}.
   * Skins should only be initialized after all of the {@link ModelExperimentalNode}s have been instantiated
   * by the scene graph.
   *
   * @param {Object} options An object containing the following options:
   * @param {ModelComponents.Skin} options.skin The corresponding skin components from the 3D model
   * @param {ModelExperimentalSceneGraph} options.sceneGraph The scene graph this skin belongs to.
   *
   * @alias ModelExperimentalSkin
   * @constructor
   *
   * @private
   */
  function ModelExperimentalSkin(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.skin", options.skin);
    Check.typeOf.object("options.sceneGraph", options.sceneGraph);
    //>>includeEnd('debug');

    this._sceneGraph = options.sceneGraph;
    const skin = options.skin;

    this._skin = skin;

    this._inverseBindMatrices = undefined;
    this._joints = [];
    this._jointMatrices = [];

    initialize$3(this);
  }

  Object.defineProperties(ModelExperimentalSkin.prototype, {
    /**
     * The internal skin this runtime skin represents.
     *
     * @memberof ModelExperimentalSkin.prototype
     * @type {ModelComponents.Skin}
     * @readonly
     *
     * @private
     */
    skin: {
      get: function () {
        return this._skin;
      },
    },

    /**
     * The scene graph this skin belongs to.
     *
     * @memberof ModelExperimentalSkin.prototype
     * @type {ModelExperimentalSceneGraph}
     * @readonly
     *
     * @private
     */
    sceneGraph: {
      get: function () {
        return this._sceneGraph;
      },
    },

    /**
     * The inverse bind matrices of the skin.
     *
     * @memberof ModelExperimentalSkin.prototype
     * @type {Matrix4[]}
     * @readonly
     *
     * @private
     */
    inverseBindMatrices: {
      get: function () {
        return this._inverseBindMatrices;
      },
    },

    /**
     * The joints of the skin.
     *
     * @memberof ModelExperimentalSkin.prototype
     * @type {ModelExperimentalNode[]}
     * @readonly
     *
     * @private
     */
    joints: {
      get: function () {
        return this._joints;
      },
    },

    /**
     * The joint matrices for the skin, where each joint matrix is computed as
     * jointMatrix = jointWorldTransform * inverseBindMatrix.
     *
     * Each node that references this skin is responsible for pre-multiplying its inverse
     * world transform to the joint matrices for its own use.
     *
     * @memberof ModelExperimentalSkin.prototype
     * @type {Matrix4[]}
     * @readonly
     *
     * @private
     */
    jointMatrices: {
      get: function () {
        return this._jointMatrices;
      },
    },
  });

  function initialize$3(runtimeSkin) {
    const skin = runtimeSkin.skin;
    const inverseBindMatrices = skin.inverseBindMatrices;
    runtimeSkin._inverseBindMatrices = inverseBindMatrices;

    const joints = skin.joints;
    const length = joints.length;

    const runtimeNodes = runtimeSkin.sceneGraph._runtimeNodes;
    const runtimeJoints = runtimeSkin.joints;
    const runtimeJointMatrices = runtimeSkin._jointMatrices;
    for (let i = 0; i < length; i++) {
      const jointIndex = joints[i].index;
      const runtimeNode = runtimeNodes[jointIndex];
      runtimeJoints.push(runtimeNode);

      const inverseBindMatrix = inverseBindMatrices[i];
      const jointMatrix = computeJointMatrix(
        runtimeNode,
        inverseBindMatrix,
        new Matrix4()
      );
      runtimeJointMatrices.push(jointMatrix);
    }
  }

  function computeJointMatrix(joint, inverseBindMatrix, result) {
    const jointWorldTransform = Matrix4.multiplyTransformation(
      joint.transformToRoot,
      joint.transform,
      result
    );

    result = Matrix4.multiplyTransformation(
      jointWorldTransform,
      inverseBindMatrix,
      result
    );

    return result;
  }

  /**
   * Updates the joint matrices for the skin.
   *
   * @private
   */
  ModelExperimentalSkin.prototype.updateJointMatrices = function () {
    const jointMatrices = this._jointMatrices;
    const length = jointMatrices.length;
    for (let i = 0; i < length; i++) {
      const joint = this.joints[i];
      const inverseBindMatrix = this.inverseBindMatrices[i];
      jointMatrices[i] = computeJointMatrix(
        joint,
        inverseBindMatrix,
        jointMatrices[i]
      );
    }
  };

  /**
   * Options for configuring the {@link AlphaPipelineStage}
   *
   * @alias ModelAlphaOptions
   * @constructor
   *
   * @private
   */
  function ModelAlphaOptions() {
    /**
     * Which render pass will render the model.
     *
     * @type {Pass}
     * @private
     */
    this.pass = undefined;
    /**
     * Which method to use for handling the alpha channel in the fragment shader.
     *
     * @type {AlphaMode}
     * @private
     */
    this.alphaMode = undefined;
    /**
     * When the alpha mode is MASK, this determines the alpha threshold
     * below which fragments are discarded
     *
     * @type {Number}
     * @private
     */
    this.alphaCutoff = undefined;
  }

  /**
   * A utility for dynamically-generating a GLSL struct.
   *
   * @alias ShaderStruct
   * @constructor
   *
   * @see {@link ShaderBuilder}
   * @param {String} name The name of the struct as it will appear in the shader.
   * @example
   * // Generate the struct:
   * //
   * // struct Attributes
   * // {
   * //     vec3 position;
   * //     vec3 normal;
   * //     vec2 texCoord;
   * // };
   * const struct = new ShaderStruct("Attributes");
   * struct.addField("vec3", "position");
   * struct.addField("vec3", "normal");
   * struct.addField("vec2", "texCoord");
   * const generatedLines = struct.generateGlslLines();
   *
   * @private
   */
  function ShaderStruct(name) {
    this.name = name;
    this.fields = [];
  }

  /**
   * Add a field to the struct
   * @param {String} type The type of the struct field
   * @param {String} identifier The identifier of the struct field
   */
  ShaderStruct.prototype.addField = function (type, identifier) {
    const field = `    ${type} ${identifier};`;
    this.fields.push(field);
  };

  /**
   * Generate a list of lines of GLSL code for use with {@link ShaderBuilder}
   * @return {String[]} The generated GLSL code.
   */
  ShaderStruct.prototype.generateGlslLines = function () {
    let fields = this.fields;
    if (fields.length === 0) {
      // GLSL requires structs to have at least one field
      fields = ["    float _empty;"];
    }

    return [].concat(`struct ${this.name}`, "{", fields, "};");
  };

  /**
   * A utility for dynamically-generating a GLSL function
   *
   * @alias ShaderFunction
   * @constructor
   *
   * @see {@link ShaderBuilder}
   * @param {String} signature The full signature of the function as it will appear in the shader. Do not include the curly braces.
   * @example
   * // generate the following function
   * //
   * // void assignVaryings(vec3 position)
   * // {
   * //    v_positionEC = (czm_modelView * vec4(a_position, 1.0)).xyz;
   * //    v_texCoord = a_texCoord;
   * // }
   * const signature = "void assignVaryings(vec3 position)";
   * const func = new ShaderFunction(signature);
   * func.addLine("v_positionEC = (czm_modelView * vec4(a_position, 1.0)).xyz;");
   * func.addLine("v_texCoord = a_texCoord;");
   * const generatedLines = func.generateGlslLines();
   *
   * @private
   */
  function ShaderFunction(signature) {
    this.signature = signature;
    this.body = [];
  }

  /**
   * Add an array of lines to the body of the function
   * @param {String[]} lines An array of lines of GLSL code to add to the function body. Do not include any preceding or ending whitespace, but do include the semicolon for each line.
   */
  ShaderFunction.prototype.addLines = function (lines) {
    const paddedLines = lines.map(function (line) {
      return `    ${line}`;
    });
    Array.prototype.push.apply(this.body, paddedLines);
  };

  /**
   * Generate lines of GLSL code for use with {@link ShaderBuilder}
   * @return {String[]}
   */
  ShaderFunction.prototype.generateGlslLines = function () {
    return [].concat(this.signature, "{", this.body, "}");
  };

  /**
   * An object that makes it easier to build the text of a {@link ShaderProgram}. This tracks GLSL code for both the vertex shader and the fragment shader.
   * <p>
   * For vertex shaders, the shader builder tracks a list of <code>#defines</code>,
   * a list of attributes, a list of uniforms, and a list of shader lines. It also
   * tracks the location of each attribute so the caller can easily build the {@link VertexArray}
   * </p>
   * <p>
   * For fragment shaders, the shader builder tracks a list of <code>#defines</code>,
   * a list of attributes, a list of uniforms, and a list of shader lines.
   * </p>
   *
   * @alias ShaderBuilder
   * @constructor
   *
   * @example
   * const shaderBuilder = new ShaderBuilder();
   * shaderBuilder.addDefine("SOLID_COLOR", undefined, ShaderDestination.FRAGMENT);
   * shaderBuilder.addUniform("vec3", "u_color", ShaderDestination.FRAGMENT);
   * shaderBuilder.addVarying("vec3", v_color");
   * // These locations can be used when creating the VertexArray
   * const positionLocation = shaderBuilder.addPositionAttribute("vec3", "a_position");
   * const colorLocation = shaderBuilder.addAttribute("vec3", "a_color");
   * shaderBuilder.addVertexLines([
   *  "void main()",
   *  "{",
   *  "    v_color = a_color;",
   *  "    gl_Position = vec4(a_position, 1.0);",
   *  "}"
   * ]);
   * shaderBuilder.addFragmentLines([
   *  "void main()",
   *  "{",
   *  "    #ifdef SOLID_COLOR",
   *  "    gl_FragColor = vec4(u_color, 1.0);",
   *  "    #else",
   *  "    gl_FragColor = vec4(v_color, 1.0);",
   *  "    #endif",
   *  "}"
   * ]);
   * const shaderProgram = shaderBuilder.build(context);
   *
   * @private
   */
  function ShaderBuilder() {
    // Some WebGL implementations require attribute 0 to always
    // be active, so the position attribute is tracked separately
    this._positionAttributeLine = undefined;
    this._nextAttributeLocation = 1;
    this._attributeLocations = {};
    this._attributeLines = [];

    // Dynamically-generated structs and functions
    // these are dictionaries of id -> ShaderStruct or ShaderFunction respectively
    this._structs = {};
    this._functions = {};

    this._vertexShaderParts = {
      defineLines: [],
      uniformLines: [],
      shaderLines: [],
      varyingLines: [],
      // identifiers of structs/functions to include, listed in insertion order
      structIds: [],
      functionIds: [],
    };
    this._fragmentShaderParts = {
      defineLines: [],
      uniformLines: [],
      shaderLines: [],
      varyingLines: [],
      // identifiers of structs/functions to include, listed in insertion order
      structIds: [],
      functionIds: [],
    };
  }

  Object.defineProperties(ShaderBuilder.prototype, {
    /**
     * Get a dictionary of attribute names to the integer location in
     * the vertex shader.
     *
     * @memberof ShaderBuilder.prototype
     * @type {Object.<String, Number>}
     * @readonly
     * @private
     */
    attributeLocations: {
      get: function () {
        return this._attributeLocations;
      },
    },
  });

  /**
   * Add a <code>#define</code> macro to one or both of the shaders. These lines
   * will appear at the top of the final shader source.
   *
   * @param {String} identifier An identifier for the macro. Identifiers must use uppercase letters with underscores to be consistent with Cesium's style guide.
   * @param {String} [value] The value of the macro. If undefined, the define will not include a value. The value will be converted to GLSL code via <code>toString()</code>
   * @param {ShaderDestination} [destination=ShaderDestination.BOTH] Whether the define appears in the vertex shader, the fragment shader, or both.
   *
   * @example
   * // creates the line "#define ENABLE_LIGHTING" in both shaders
   * shaderBuilder.addDefine("ENABLE_LIGHTING");
   * // creates the line "#define PI 3.141592" in the fragment shader
   * shaderBuilder.addDefine("PI", 3.141593, ShaderDestination.FRAGMENT);
   */
  ShaderBuilder.prototype.addDefine = function (identifier, value, destination) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("identifier", identifier);
    //>>includeEnd('debug');

    destination = defaultValue(destination, ShaderDestination$1.BOTH);

    // The ShaderSource created in build() will add the #define part
    let line = identifier;
    if (defined(value)) {
      line += ` ${value.toString()}`;
    }

    if (ShaderDestination$1.includesVertexShader(destination)) {
      this._vertexShaderParts.defineLines.push(line);
    }

    if (ShaderDestination$1.includesFragmentShader(destination)) {
      this._fragmentShaderParts.defineLines.push(line);
    }
  };

  /**
   * Add a new dynamically-generated struct to the shader
   * @param {String} structId A unique ID to identify this struct in {@link ShaderBuilder#addStructField}
   * @param {String} structName The name of the struct as it will appear in the shader.
   * @param {ShaderDestination} destination Whether the struct will appear in the vertex shader, the fragment shader, or both.
   *
   * @example
   * // generates the following struct in the fragment shader
   * // struct TestStruct
   * // {
   * // };
   * shaderBuilder.addStruct("testStructId", "TestStruct", ShaderDestination.FRAGMENT);
   */
  ShaderBuilder.prototype.addStruct = function (
    structId,
    structName,
    destination
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("structId", structId);
    Check.typeOf.string("structName", structName);
    Check.typeOf.number("destination", destination);
    //>>includeEnd('debug');
    this._structs[structId] = new ShaderStruct(structName);
    if (ShaderDestination$1.includesVertexShader(destination)) {
      this._vertexShaderParts.structIds.push(structId);
    }

    if (ShaderDestination$1.includesFragmentShader(destination)) {
      this._fragmentShaderParts.structIds.push(structId);
    }
  };

  /**
   * Add a field to a dynamically-generated struct.
   * @param {String} structId The ID of the struct. This must be created first with {@link ShaderBuilder#addStruct}
   * @param {String} type The GLSL type of the field
   * @param {String} identifier The identifier of the field.
   *
   * @example
   * // generates the following struct in the fragment shader
   * // struct TestStruct
   * // {
   * //    float minimum;
   * //    float maximum;
   * // };
   * shaderBuilder.addStruct("testStructId", "TestStruct", ShaderDestination.FRAGMENT);
   * shaderBuilder.addStructField("testStructId", "float", "maximum");
   * shaderBuilder.addStructField("testStructId", "float", "minimum");
   */
  ShaderBuilder.prototype.addStructField = function (structId, type, identifier) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("structId", structId);
    Check.typeOf.string("type", type);
    Check.typeOf.string("identifier", identifier);
    //>>includeEnd('debug');
    this._structs[structId].addField(type, identifier);
  };

  /**
   * Add a new dynamically-generated function to the shader.
   * @param {String} functionName The name of the function. This will be used to identify the function in {@link ShaderBuilder#addFunctionLines}.
   * @param {String} signature The full signature of the function as it will appear in the shader. Do not include the curly braces.
   * @param {ShaderDestination} destination Whether the struct will appear in the vertex shader, the fragment shader, or both.
   * @example
   * // generates the following function in the vertex shader
   * // vec3 testFunction(float parameter)
   * // {
   * // }
   * shaderBuilder.addStruct("testFunction", "vec3 testFunction(float parameter)", ShaderDestination.VERTEX);
   */
  ShaderBuilder.prototype.addFunction = function (
    functionName,
    signature,
    destination
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("functionName", functionName);
    Check.typeOf.string("signature", signature);
    Check.typeOf.number("destination", destination);
    //>>includeEnd('debug');
    this._functions[functionName] = new ShaderFunction(signature);

    if (ShaderDestination$1.includesVertexShader(destination)) {
      this._vertexShaderParts.functionIds.push(functionName);
    }

    if (ShaderDestination$1.includesFragmentShader(destination)) {
      this._fragmentShaderParts.functionIds.push(functionName);
    }
  };

  /**
   * Add lines to a dynamically-generated function
   * @param {String} functionName The name of the function. This must be created beforehand using {@link ShaderBuilder#addFunction}
   * @param {String[]} lines An array of lines of GLSL code to add to the function body. Do not include any preceding or ending whitespace, but do include the semicolon for each line.
   *
   * @example
   * // generates the following function in the vertex shader
   * // vec3 testFunction(float parameter)
   * // {
   * //   float signed = 2.0 * parameter - 1.0;
   * //   return vec3(signed, 0.0, 0.0);
   * // }
   * shaderBuilder.addStruct("testFunction", "vec3 testFunction(float parameter)", ShaderDestination.VERTEX);
   * shaderBuilder.addFunctionLines("testFunction", [
   *   "float signed = 2.0 * parameter - 1.0;",
   *   "return vec3(parameter);"
   * ]);
   */
  ShaderBuilder.prototype.addFunctionLines = function (functionName, lines) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("functionName", functionName);
    Check.typeOf.object("lines", lines);
    //>>includeEnd('debug');
    this._functions[functionName].addLines(lines);
  };

  /**
   * Add a uniform declaration to one or both of the shaders. These lines
   * will appear grouped near the top of the final shader source.
   *
   * @param {String} type The GLSL type of the uniform.
   * @param {String} identifier An identifier for the uniform. Identifiers must begin with <code>u_</code> to be consistent with Cesium's style guide.
   * @param {ShaderDestination} [destination=ShaderDestination.BOTH] Whether the uniform appears in the vertex shader, the fragment shader, or both.
   *
   * @example
   * // creates the line "uniform vec3 u_resolution;"
   * shaderBuilder.addUniform("vec3", "u_resolution", ShaderDestination.FRAGMENT);
   * // creates the line "uniform float u_time;" in both shaders
   * shaderBuilder.addUniform("float", "u_time", ShaderDestination.BOTH);
   */
  ShaderBuilder.prototype.addUniform = function (type, identifier, destination) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("type", type);
    Check.typeOf.string("identifier", identifier);
    //>>includeEnd('debug');

    destination = defaultValue(destination, ShaderDestination$1.BOTH);
    const line = `uniform ${type} ${identifier};`;

    if (ShaderDestination$1.includesVertexShader(destination)) {
      this._vertexShaderParts.uniformLines.push(line);
    }

    if (ShaderDestination$1.includesFragmentShader(destination)) {
      this._fragmentShaderParts.uniformLines.push(line);
    }
  };

  /**
   * Add a position attribute declaration to the vertex shader. These lines
   * will appear grouped near the top of the final shader source.
   * <p>
   * Some WebGL implementations require attribute 0 to be enabled, so this is
   * reserved for the position attribute. For all other attributes, see
   * {@link ShaderBuilder#addAttribute}
   * </p>
   *
   * @param {String} type The GLSL type of the attribute
   * @param {String} identifier An identifier for the attribute. Identifiers must begin with <code>a_</code> to be consistent with Cesium's style guide.
   * @return {Number} The integer location of the attribute. This location can be used when creating attributes for a {@link VertexArray}. This will always be 0.
   *
   * @example
   * // creates the line "attribute vec3 a_position;"
   * shaderBuilder.setPositionAttribute("vec3", "a_position");
   */
  ShaderBuilder.prototype.setPositionAttribute = function (type, identifier) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("type", type);
    Check.typeOf.string("identifier", identifier);

    if (defined(this._positionAttributeLine)) {
      throw new DeveloperError(
        "setPositionAttribute() must be called exactly once for the attribute used for gl_Position. For other attributes, use addAttribute()"
      );
    }
    //>>includeEnd('debug');

    this._positionAttributeLine = `attribute ${type} ${identifier};`;

    // Some WebGL implementations require attribute 0 to always be active, so
    // this builder assumes the position will always go in location 0
    this._attributeLocations[identifier] = 0;
    return 0;
  };

  /**
   * Add an attribute declaration to the vertex shader. These lines
   * will appear grouped near the top of the final shader source.
   * <p>
   * Some WebGL implementations require attribute 0 to be enabled, so this is
   * reserved for the position attribute. See {@link ShaderBuilder#setPositionAttribute}
   * </p>
   *
   * @param {String} type The GLSL type of the attribute
   * @param {String} identifier An identifier for the attribute. Identifiers must begin with <code>a_</code> to be consistent with Cesium's style guide.
   * @return {Number} The integer location of the attribute. This location can be used when creating attributes for a {@link VertexArray}
   *
   * @example
   * // creates the line "attribute vec2 a_texCoord0;" in the vertex shader
   * shaderBuilder.addAttribute("vec2", "a_texCoord0");
   */
  ShaderBuilder.prototype.addAttribute = function (type, identifier) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("type", type);
    Check.typeOf.string("identifier", identifier);
    //>>includeEnd('debug');

    const line = `attribute ${type} ${identifier};`;
    this._attributeLines.push(line);

    const location = this._nextAttributeLocation;
    this._attributeLocations[identifier] = location;

    // Most attributes only require a single attribute location, but matrices
    // require more.
    this._nextAttributeLocation += getAttributeLocationCount(type);
    return location;
  };

  /**
   * Add a varying declaration to both the vertex and fragment shaders.
   *
   * @param {String} type The GLSL type of the varying
   * @param {String} identifier An identifier for the varying. Identifiers must begin with <code>v_</code> to be consistent with Cesium's style guide.
   *
   * @example
   * // creates the line "varying vec3 v_color;" in both shaders
   * shaderBuilder.addVarying("vec3", "v_color");
   */
  ShaderBuilder.prototype.addVarying = function (type, identifier) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("type", type);
    Check.typeOf.string("identifier", identifier);
    //>>includeEnd('debug');

    const line = `varying ${type} ${identifier};`;
    this._vertexShaderParts.varyingLines.push(line);
    this._fragmentShaderParts.varyingLines.push(line);
  };

  /**
   * Appends lines of GLSL code to the vertex shader
   *
   * @param {String[]} lines The lines to add to the end of the vertex shader source
   *
   * @example
   * shaderBuilder.addVertexLines([
   *  "void main()",
   *  "{",
   *  "    v_color = a_color;",
   *  "    gl_Position = vec4(a_position, 1.0);",
   *  "}"
   * ]);
   */
  ShaderBuilder.prototype.addVertexLines = function (lines) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("lines", lines);
    //>>includeEnd('debug');

    Array.prototype.push.apply(this._vertexShaderParts.shaderLines, lines);
  };

  /**
   * Appends lines of GLSL code to the fragment shader
   *
   * @param {String[]} lines The lines to add to the end of the fragment shader source
   *
   * @example
   * shaderBuilder.addFragmentLines([
   *  "void main()",
   *  "{",
   *  "    #ifdef SOLID_COLOR",
   *  "    gl_FragColor = vec4(u_color, 1.0);",
   *  "    #else",
   *  "    gl_FragColor = vec4(v_color, 1.0);",
   *  "    #endif",
   *  "}"
   * ]);
   */
  ShaderBuilder.prototype.addFragmentLines = function (lines) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("lines", lines);
    //>>includeEnd('debug');
    Array.prototype.push.apply(this._fragmentShaderParts.shaderLines, lines);
  };

  /**
   * Builds the {@link ShaderProgram} from the pieces added by the other methods.
   * Call this one time at the end of modifying the shader through the other
   * methods in this class.
   *
   * @param {Context} context The context to use for creating the shader.
   * @return {ShaderProgram} A shader program to use for rendering.
   *
   * @example
   * const shaderProgram = shaderBuilder.buildShaderProgram(context);
   */
  ShaderBuilder.prototype.buildShaderProgram = function (context) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("context", context);
    //>>includeEnd('debug');

    const positionAttribute = defined(this._positionAttributeLine)
      ? [this._positionAttributeLine]
      : [];

    const structLines = generateStructLines(this);
    const functionLines = generateFunctionLines(this);

    // Lines are joined here so the ShaderSource
    // generates a single #line 0 directive
    const vertexLines = positionAttribute
      .concat(
        this._attributeLines,
        this._vertexShaderParts.uniformLines,
        this._vertexShaderParts.varyingLines,
        structLines.vertexLines,
        functionLines.vertexLines,
        this._vertexShaderParts.shaderLines
      )
      .join("\n");
    const vertexShaderSource = new ShaderSource({
      defines: this._vertexShaderParts.defineLines,
      sources: [vertexLines],
    });

    const fragmentLines = this._fragmentShaderParts.uniformLines
      .concat(
        this._fragmentShaderParts.varyingLines,
        structLines.fragmentLines,
        functionLines.fragmentLines,
        this._fragmentShaderParts.shaderLines
      )
      .join("\n");
    const fragmentShaderSource = new ShaderSource({
      defines: this._fragmentShaderParts.defineLines,
      sources: [fragmentLines],
    });

    return ShaderProgram.fromCache({
      context: context,
      vertexShaderSource: vertexShaderSource,
      fragmentShaderSource: fragmentShaderSource,
      attributeLocations: this._attributeLocations,
    });
  };

  ShaderBuilder.prototype.clone = function () {
    return clone$1(this, true);
  };

  function generateStructLines(shaderBuilder) {
    const vertexLines = [];
    const fragmentLines = [];

    let i;
    let structIds = shaderBuilder._vertexShaderParts.structIds;
    let structId;
    let struct;
    let structLines;
    for (i = 0; i < structIds.length; i++) {
      structId = structIds[i];
      struct = shaderBuilder._structs[structId];
      structLines = struct.generateGlslLines();
      vertexLines.push.apply(vertexLines, structLines);
    }

    structIds = shaderBuilder._fragmentShaderParts.structIds;
    for (i = 0; i < structIds.length; i++) {
      structId = structIds[i];
      struct = shaderBuilder._structs[structId];
      structLines = struct.generateGlslLines();
      fragmentLines.push.apply(fragmentLines, structLines);
    }

    return {
      vertexLines: vertexLines,
      fragmentLines: fragmentLines,
    };
  }

  function getAttributeLocationCount(glslType) {
    switch (glslType) {
      case "mat2":
        return 2;
      case "mat3":
        return 3;
      case "mat4":
        return 4;
      default:
        return 1;
    }
  }

  function generateFunctionLines(shaderBuilder) {
    const vertexLines = [];
    const fragmentLines = [];

    let i;
    let functionIds = shaderBuilder._vertexShaderParts.functionIds;
    let functionId;
    let func;
    let functionLines;
    for (i = 0; i < functionIds.length; i++) {
      functionId = functionIds[i];
      func = shaderBuilder._functions[functionId];
      functionLines = func.generateGlslLines();
      vertexLines.push.apply(vertexLines, functionLines);
    }

    functionIds = shaderBuilder._fragmentShaderParts.functionIds;
    for (i = 0; i < functionIds.length; i++) {
      functionId = functionIds[i];
      func = shaderBuilder._functions[functionId];
      functionLines = func.generateGlslLines();
      fragmentLines.push.apply(fragmentLines, functionLines);
    }

    return {
      vertexLines: vertexLines,
      fragmentLines: fragmentLines,
    };
  }

  /**
   * Model render resources are for setting details that are consistent across
   * the entire model.
   *
   * @constructor
   * @param {ModelExperimental} model The model that will be rendered
   *
   * @private
   */
  function ModelRenderResources(model) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("model", model);
    //>>includeEnd('debug');

    /**
     * An object used to build a shader incrementally. Each pipeline stage
     * may add lines of shader code to this object.
     *
     * @type {ShaderBuilder}
     * @readonly
     *
     * @private
     */
    this.shaderBuilder = new ShaderBuilder();
    /**
     * A reference to the model.
     *
     * @type {ModelExperimental}
     * @readonly
     *
     * @private
     */
    this.model = model;

    /**
     * A dictionary mapping uniform name to functions that return the uniform
     * values.
     *
     * @type {Object.<String, Function>}
     * @readonly
     *
     * @private
     */
    this.uniformMap = {};

    /**
     * Options for configuring the alpha stage such as pass and alpha mode.
     *
     * @type {ModelAlphaOptions}
     * @readonly
     *
     * @private
     */
    this.alphaOptions = new ModelAlphaOptions();

    /**
     * An object storing options for creating a {@link RenderState}.
     * The pipeline stages simply set the options, the render state is created
     * when the {@link DrawCommand} is constructed.
     *
     * @type {Object}
     * @readonly
     *
     * @private
     */
    this.renderStateOptions = {};
  }

  //This file is automatically rebuilt by the Cesium build process.
  var ModelSilhouetteStageFS = "void silhouetteStage(inout vec4 color) {\n\
if(model_silhouettePass) {\n\
color = czm_gammaCorrect(model_silhouetteColor);\n\
}\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var ModelSilhouetteStageVS = "void silhouetteStage(in ProcessedAttributes attributes) {\n\
#ifdef HAS_NORMALS\n\
if(model_silhouettePass) {\n\
vec3 normal = normalize(czm_normal3D * attributes.normalMC);\n\
normal.x *= czm_projection[0][0];\n\
normal.y *= czm_projection[1][1];\n\
vec4 clip = gl_Position;\n\
clip.xy += normal.xy * clip.w * model_silhouetteSize * czm_pixelRatio / czm_viewport.z;\n\
gl_Position = clip;\n\
}\n\
#endif\n\
}\n\
";

  /**
   * The model silhouette pipeline stage is responsible applying silhouettes to the model.
   *
   * @namespace ModelSilhouettePipelineStage
   *
   * @private
   */
  const ModelSilhouettePipelineStage = {};
  ModelSilhouettePipelineStage.name = "ModelSilhouettePipelineStage"; // Helps with debugging

  /**
   * Process a model. This modifies the following parts of the render resources:
   *
   * <ul>
   *  <li>adds a define to the shaders to indicate that the model uses silhouettes</li>
   *  <li>adds a function to the vertex shader to create the silhouette around the model</li>
   *  <li>adds a function to the fragment shader to apply color to the silhouette</li>
   *  <li>adds the uniforms to the shaders for the corresponding silhouette properties</li>
   *  <li>adds a uniform to distinguish which draw command is used to render the silhouette</li>
   * </ul>
   *
   * <p>
   * Note that the model must have a normal attribute in order to use silhouettes. The flag for this is
   * added to the shader in GeometryPipelineStage.
   * </p>
   *
   * @param {ModelRenderResources} renderResources The render resources for this model.
   * @param {ModelExperimental} model The model.
   * @param {FrameState} frameState The frameState.
   *
   * @private
   */
  ModelSilhouettePipelineStage.process = function (
    renderResources,
    model,
    frameState
  ) {
    const shaderBuilder = renderResources.shaderBuilder;
    shaderBuilder.addDefine("HAS_SILHOUETTE", undefined, ShaderDestination$1.BOTH);

    shaderBuilder.addVertexLines([ModelSilhouetteStageVS]);
    shaderBuilder.addFragmentLines([ModelSilhouetteStageFS]);

    shaderBuilder.addUniform(
      "vec4",
      "model_silhouetteColor",
      ShaderDestination$1.FRAGMENT
    );

    shaderBuilder.addUniform(
      "float",
      "model_silhouetteSize",
      ShaderDestination$1.VERTEX
    );

    // Rendering silhouettes requires two draw commands:
    // - First, the model is rendered as normal, writing to the stencil buffer.
    // - Second, the silhouette is drawn, and the stencil buffer is used to cutout
    //   the part that overlaps the regular model.
    //
    // To avoid creating a second shader program to handle silhouettes, a uniform
    // is used to distinguish between the two draw commands. The second command will set
    // this uniform true, such that only it applies the silhouette stage.
    shaderBuilder.addUniform(
      "bool",
      "model_silhouettePass",
      ShaderDestination$1.BOTH
    );

    const uniformMap = {
      model_silhouetteColor: function () {
        return model.silhouetteColor;
      },
      model_silhouetteSize: function () {
        return model.silhouetteSize;
      },
      model_silhouettePass: function () {
        // This will be set to true by the draw command that draws the silhouette.
        return false;
      },
    };

    renderResources.uniformMap = combine$2(uniformMap, renderResources.uniformMap);
  };

  //This file is automatically rebuilt by the Cesium build process.
  var ModelSplitterStageFS = "void modelSplitterStage()\n\
{\n\
#ifndef SHADOW_MAP\n\
if (model_splitDirection < 0.0 && gl_FragCoord.x > czm_splitPosition) discard;\n\
if (model_splitDirection > 0.0 && gl_FragCoord.x < czm_splitPosition) discard;\n\
#endif\n\
}\n\
";

  /**
   * The model splitting pipeline stage is responsible for discarding fragments on the wrong side of the splitter.
   *
   * @namespace ModelSplitterPipelineStage
   *
   * @private
   */
  const ModelSplitterPipelineStage = {};
  ModelSplitterPipelineStage.name = "ModelSplitterPipelineStage"; // Helps with debugging

  ModelSplitterPipelineStage.SPLIT_DIRECTION_UNIFORM_NAME =
    "model_splitDirection";

  /**
   * Process a model. This modifies the following parts of the render resources:
   *
   * <ul>
   *  <li>adds a define to the fragment shader to indicate that the model is split</li>
   *  <li>adds a function to the fragment shader to discard the fragment if it's on the wrong side of the splitter.</li>
   *  <li>adds a uniform indicating the "splitDirection" (side of the screen on which to show the model)
   *</ul>
   *
   * @param {ModelRenderResources} renderResources The render resources for this model.
   * @param {ModelExperimental} model The model.
   * @param {FrameState} frameState The frameState.
   *
   * @private
   */
  ModelSplitterPipelineStage.process = function (
    renderResources,
    model,
    frameState
  ) {
    const shaderBuilder = renderResources.shaderBuilder;

    shaderBuilder.addDefine(
      "HAS_MODEL_SPLITTER",
      undefined,
      ShaderDestination$1.FRAGMENT
    );
    shaderBuilder.addFragmentLines([ModelSplitterStageFS]);

    const stageUniforms = {};

    shaderBuilder.addUniform(
      "float",
      ModelSplitterPipelineStage.SPLIT_DIRECTION_UNIFORM_NAME,
      ShaderDestination$1.FRAGMENT
    );
    stageUniforms[
      ModelSplitterPipelineStage.SPLIT_DIRECTION_UNIFORM_NAME
    ] = function () {
      return model.splitDirection;
    };

    renderResources.uniformMap = combine$2(
      stageUniforms,
      renderResources.uniformMap
    );
  };

  /**
   * A model is made up of one or more nodes in the scene graph. Some details
   * such as instancing are computed on a per-node basis. This class provides
   * a place to store such details. It also inherits some properties from
   * the model render resources.
   *
   * @constructor
   *
   * @param {ModelRenderResources} modelRenderResources The model resources to inherit
   * @param {ModelExperimentalNode} runtimeNode The in-memory representation of the scene graph node.
   *
   * @private
   */
  function NodeRenderResources(modelRenderResources, runtimeNode) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("modelRenderResources", modelRenderResources);
    Check.typeOf.object("runtimeNode", runtimeNode);
    //>>includeEnd('debug');

    // Properties inherited from the ModelRenderResources.
    /**
     * A reference to the model. Inherited from the model render resources.
     *
     * @type {ModelExperimental}
     * @readonly
     *
     * @private
     */
    this.model = modelRenderResources.model;
    /**
     * An object used to build a shader incrementally. This is cloned from the
     * model render resources because each node can compute a different shader.
     *
     * @type {ShaderBuilder}
     * @readonly
     *
     * @private
     */
    this.shaderBuilder = modelRenderResources.shaderBuilder.clone();

    /**
     * A dictionary mapping uniform name to functions that return the uniform
     * values. Inherited from the model render resources.
     *
     * @type {Object.<String, Function>}
     *
     * @readonly
     *
     * @private
     */
    this.uniformMap = clone$1(modelRenderResources.uniformMap);

    /**
     * Options for configuring the alpha stage such as pass and alpha mode. Inherited from the model
     * render resources.
     *
     * @type {ModelAlphaOptions}
     * @readonly
     *
     * @private
     */
    this.alphaOptions = clone$1(modelRenderResources.alphaOptions);

    /**
     * An object storing options for creating a {@link RenderState}.
     * The pipeline stages simply set the options, the render state is created
     * when the {@link DrawCommand} is constructed. Inherited from the model
     * render resources.
     *
     * @type {Object}
     * @readonly
     *
     * @private
     */
    this.renderStateOptions = clone$1(modelRenderResources.renderStateOptions);

    // Other properties.
    /**
     * A reference to the runtime node
     *
     * @type {ModelExperimentalNode}
     * @readonly
     *
     * @private
     */
    this.runtimeNode = runtimeNode;

    /**
     * An array of objects describing vertex attributes that will eventually
     * be used to create a {@link VertexArray} for the draw command. Attributes
     * at the node level may be needed for extensions such as EXT_mesh_gpu_instancing.
     *
     * @type {Object[]}
     * @readonly
     *
     * @private
     */
    this.attributes = [];

    /**
     * The index to give to the next vertex attribute added to the attributes array. POSITION
     * takes index 0.
     *
     * @type {Number}
     * @readonly
     *
     * @private
     */
    this.attributeIndex = 1;

    /**
     * The set index to assign to feature ID vertex attribute(s) created from the offset/repeat in the feature ID attribute.
     *
     * @type {Number}
     * @readonly
     *
     * @private
     */
    this.featureIdVertexAttributeSetIndex = 0;

    /**
     * The number of instances. Default is 0, if instancing is not used.
     *
     * @type {Number}
     * @readonly
     *
     * @private
     */
    this.instanceCount = 0;

    /**
     * The component-wise maximum value of the translations of the instances.
     *
     * @type {Cartesian3}
     *
     * @private
     */
    this.instancingTranslationMax = undefined;

    /**
     * The component-wise minimum value of the translations of the instances.
     *
     * @type {Cartesian3}
     *
     * @private
     */
    this.instancingTranslationMin = undefined;

    /**
     * If the model is instanced and projected to 2D, the reference point is the
     * average of the instancing translation max and min. The 2D translations are
     * defined relative to this point to avoid precision issues on the GPU.
     *
     * @type {Cartesian3}
     *
     * @private
     */
    this.instancingReferencePoint2D = undefined;
  }

  /**
   * Options for configuring the {@link LightingPipelineStage}
   *
   * @param {Object} options An object containing the following options
   * @param {LightingModel} [options.lightingModel=LightingModel.UNLIT] The lighting model to use
   *
   * @alias ModelLightingOptions
   * @constructor
   *
   * @private
   */
  function ModelLightingOptions(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    /**
     * The lighting model to use, such as UNLIT or PBR. This is determined by
     * the primitive's material.
     *
     * @type {LightingModel}
     *
     * @private
     */
    this.lightingModel = defaultValue(options.lightingModel, LightingModel$1.UNLIT);
  }

  /**
   * Each node may have many mesh primitives. Most model pipeline stages operate
   * at the primitive level. Again, properties are inherited from the parent.
   *
   * @param {NodeRenderResources} nodeRenderResources The node resources to inherit from
   * @param {ModelExperimentalPrimitive} runtimePrimitive The primitive.
   *
   * @private
   */
  function PrimitiveRenderResources(
    nodeRenderResources,
    runtimePrimitive
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("nodeRenderResources", nodeRenderResources);
    Check.typeOf.object("runtimePrimitive", runtimePrimitive);
    //>>includeEnd('debug');

    // Properties inherited from NodeRenderResources.
    /**
     * A reference to the model. Inherited from the node render resources.
     *
     * @type {ModelExperimental}
     * @readonly
     *
     * @private
     */
    this.model = nodeRenderResources.model;
    /**
     * A reference to the runtime node. Inherited from the node render resources.
     *
     * @type {ModelExperimentalNode}
     * @readonly
     *
     * @private
     */
    this.runtimeNode = nodeRenderResources.runtimeNode;
    /**
     * The vertex attributes. This is shallow cloned from the node render
     * resources as the primitive will add additional properties.
     *
     * @type {Object[]}
     *
     * @private
     */
    this.attributes = nodeRenderResources.attributes.slice();

    /**
     * The index to give to the next vertex attribute added to the attributes array. POSITION
     * takes index 0. Inherited from the node render resources.
     *
     * @type {Number}
     * @readonly
     *
     * @private
     */
    this.attributeIndex = nodeRenderResources.attributeIndex;

    /**
     * The set index to assign to feature ID vertex attribute(s) created from the offset/repeat in the feature ID attribute.
     * Inherited from the node render resources.
     *
     * @type {Number}
     *
     * @private
     */
    this.featureIdVertexAttributeSetIndex =
      nodeRenderResources.featureIdVertexAttributeSetIndex;

    /**
     * Whether or not this primitive has a property table for storing metadata.
     * When present, picking and styling can use this
     *
     * @type {Boolean}
     * @default false
     * @readonly
     *
     * @private
     */
    this.hasPropertyTable = false;

    /**
     * A dictionary mapping uniform name to functions that return the uniform
     * values. Inherited from the node render resources.
     *
     * @type {Object.<String, Function>}
     * @readonly
     *
     * @private
     */
    this.uniformMap = clone$1(nodeRenderResources.uniformMap);

    /**
     * Options for configuring the alpha stage such as pass and alpha mode. Inherited from the node
     * render resources.
     *
     * @type {ModelAlphaOptions}
     * @readonly
     *
     * @private
     */
    this.alphaOptions = clone$1(nodeRenderResources.alphaOptions);

    /**
     * An object used to build a shader incrementally. This is cloned from the
     * node render resources because each primitive can compute a different shader.
     *
     * @type {ShaderBuilder}
     * @readonly
     *
     * @private
     */
    this.shaderBuilder = nodeRenderResources.shaderBuilder.clone();

    /**
     * The number of instances. Default is 0, if instancing is not used. Inherited from the node render resources.
     *
     * @type {Number}
     * @readonly
     *
     * @private
     */
    this.instanceCount = nodeRenderResources.instanceCount;

    /**
     * A reference to the runtime primitive
     *
     * @type {ModelExperimentalPrimitive}
     * @readonly
     *
     * @private
     */
    this.runtimePrimitive = runtimePrimitive;

    /**
     * The primitive associated with the render resources.
     *
     * @type {ModelComponents.Primitive}
     * @readonly
     *
     * @private
     */
    const primitive = runtimePrimitive.primitive;

    // other properties
    /**
     * The number of indices in the primitive. The interpretation of this
     * depends on the primitive type.
     *
     * @type {Number}
     * @readonly
     *
     * @private
     */
    this.count = defined(primitive.indices)
      ? primitive.indices.count
      : ModelExperimentalUtility.getAttributeBySemantic(primitive, "POSITION")
          .count;

    /**
     * The indices for this primitive
     *
     * @type {ModelComponents.Indices}
     * @readonly
     *
     * @private
     */
    this.indices = primitive.indices;

    /**
     * Additional index buffer for wireframe mode (if enabled)
     *
     * @type {Buffer}
     * @readonly
     *
     * @private
     */
    this.wireframeIndexBuffer = undefined;

    /**
     * The primitive type such as TRIANGLES or POINTS
     *
     * @type {PrimitiveType}
     * @readonly
     *
     * @private
     */
    this.primitiveType = primitive.primitiveType;

    const positionMinMax = ModelExperimentalUtility.getPositionMinMax(
      primitive,
      nodeRenderResources.instancingTranslationMin,
      nodeRenderResources.instancingTranslationMax
    );

    /**
     * The minimum position value for this primitive.
     *
     * @type {Cartesian3}
     * @readonly
     *
     * @private
     */
    this.positionMin = Cartesian3.clone(positionMinMax.min, new Cartesian3());

    /**
     * The maximum position value for this primitive.
     *
     * @type {Cartesian3}
     * @readonly
     *
     * @private
     */
    this.positionMax = Cartesian3.clone(positionMinMax.max, new Cartesian3());

    /**
     * The bounding sphere that contains all the vertices in this primitive.
     *
     * @type {BoundingSphere}
     * @readonly
     *
     * @private
     */
    this.boundingSphere = BoundingSphere.fromCornerPoints(
      this.positionMin,
      this.positionMax,
      new BoundingSphere()
    );

    /**
     * Options for configuring the lighting stage such as selecting between
     * unlit and PBR shading.
     *
     * @type {ModelLightingOptions}
     * @readonly
     *
     * @private
     */
    this.lightingOptions = new ModelLightingOptions();

    /**
     * The shader variable to use for picking.
     *
     * @type {String}
     * @readonly
     *
     * @private
     */
    this.pickId = undefined;

    /**
     * An object storing options for creating a {@link RenderState}.
     * the pipeline stages simply set the options, the render state is created
     * when the {@link DrawCommand} is constructed.
     *
     * @type {Object}
     * @readonly
     *
     * @private
     */
    this.renderStateOptions = combine$2(nodeRenderResources.renderStateOptions, {
      depthTest: {
        enabled: true,
        func: DepthFunction$1.LESS_OR_EQUAL,
      },
      blending: BlendingState$1.DISABLED,
    });

    /**
     * An enum describing the types of draw commands needed, based on the style.
     *
     * @type {StyleCommandsNeeded}
     * @readonly
     *
     * @private
     */
    this.styleCommandsNeeded = undefined;
  }

  /**
   * An in memory representation of the scene graph for a {@link ModelExperimental}
   *
   * @param {Object} options An object containing the following options
   * @param {ModelExperimental} options.model The model this scene graph belongs to
   * @param {ModelComponents} options.modelComponents The model components describing the model
   *
   * @alias ModelExperimentalSceneGraph
   * @constructor
   *
   * @private
   */
  function ModelExperimentalSceneGraph(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const components = options.modelComponents;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.model", options.model);
    Check.typeOf.object("options.modelComponents", components);
    //>>includeEnd('debug');

    /**
     * A reference to the {@link ModelExperimental} that owns this scene graph.
     *
     * @type {ModelExperimental}
     * @readonly
     *
     * @private
     */
    this._model = options.model;

    /**
     * The model components that represent the contents of the 3D model file.
     *
     * @type {ModelComponents}
     * @readonly
     *
     * @private
     */
    this._components = components;

    /**
     * Pipeline stages to apply across the model.
     *
     * @type {Object[]}
     * @readonly
     *
     * @private
     */
    this._pipelineStages = [];

    /**
     * Update stages to apply across the model.
     *
     * @type {Object[]}
     * @readonly
     *
     * @private
     */
    this._updateStages = [];

    /**
     * The runtime nodes that make up the scene graph
     *
     * @type {ModelExperimentalNode[]}
     * @readonly
     *
     * @private
     */
    this._runtimeNodes = [];

    /**
     * The indices of the root nodes in the runtime nodes array.
     *
     * @type {Number[]}
     * @readonly
     *
     * @private
     */
    this._rootNodes = [];

    /**
     * The indices of the skinned nodes in the runtime nodes array. These refer
     * to the nodes that will be manipulated by their skin, as opposed to the nodes
     * acting as joints for the skin.
     *
     * @type {Number[]}
     * @readonly
     *
     * @private
     */
    this._skinnedNodes = [];

    /**
     * The runtime skins that affect nodes in the scene graph.
     *
     * @type {ModelExperimentalSkin[]}
     * @readonly
     *
     * @private
     */
    this._runtimeSkins = [];

    /**
     * Pipeline stages to apply to this model. This
     * is an array of classes, each with a static method called
     * <code>process()</code>
     *
     * @type {Object[]}
     * @readonly
     *
     * @private
     */
    this.modelPipelineStages = [];

    // The scene graph's bounding sphere is model space, so that
    // the model's bounding sphere can be recomputed when given a
    // new model matrix.
    this._boundingSphere = undefined;

    // The 2D bounding sphere is in world space. This is checked
    // by the draw commands to see if the model is over the IDL,
    // and if so, renders the primitives using extra commands.
    this._boundingSphere2D = undefined;

    this._computedModelMatrix = Matrix4.clone(Matrix4.IDENTITY);
    this._computedModelMatrix2D = Matrix4.clone(Matrix4.IDENTITY);

    this._axisCorrectionMatrix = ModelExperimentalUtility.getAxisCorrectionMatrix(
      components.upAxis,
      components.forwardAxis,
      new Matrix4()
    );

    // Store articulations from the AGI_articulations extension
    // by name in a dictionary for easy retrieval.
    this._runtimeArticulations = {};

    initialize$2(this);
  }

  Object.defineProperties(ModelExperimentalSceneGraph.prototype, {
    /**
     * The model components this scene graph represents.
     *
     * @type {ModelComponents}
     * @readonly
     *
     * @private
     */
    components: {
      get: function () {
        return this._components;
      },
    },

    /**
     * The axis-corrected model matrix.
     *
     * @type {Matrix4}
     * @readonly
     *
     * @private
     */
    computedModelMatrix: {
      get: function () {
        return this._computedModelMatrix;
      },
    },

    /**
     * A matrix to correct from y-up in some model formats (e.g. glTF) to the
     * z-up coordinate system Cesium uses.
     *
     * @type {Matrix4}
     * @readonly
     *
     * @private
     */
    axisCorrectionMatrix: {
      get: function () {
        return this._axisCorrectionMatrix;
      },
    },

    /**
     * The bounding sphere containing all the primitives in the scene graph
     * in model space.
     *
     * @type {BoundingSphere}
     * @readonly
     *
     * @private
     */
    boundingSphere: {
      get: function () {
        return this._boundingSphere;
      },
    },
  });

  function initialize$2(sceneGraph) {
    const components = sceneGraph._components;
    const scene = components.scene;

    // If the model has a height reference that modifies the model matrix,
    // it will be accounted for in updateModelMatrix.
    const modelMatrix = sceneGraph._model.modelMatrix;
    computeModelMatrix(sceneGraph, modelMatrix);

    const articulations = components.articulations;
    const articulationsLength = articulations.length;

    const runtimeArticulations = sceneGraph._runtimeArticulations;
    for (let i = 0; i < articulationsLength; i++) {
      const articulation = articulations[i];
      const runtimeArticulation = new ModelExperimentalArticulation({
        articulation: articulation,
        sceneGraph: sceneGraph,
      });

      const name = runtimeArticulation.name;
      runtimeArticulations[name] = runtimeArticulation;
    }

    const nodes = components.nodes;
    const nodesLength = nodes.length;

    // Initialize this array to be the same size as the nodes array in
    // the model's file. This is so nodes can be stored by their index
    // in the file, for future ease of access.
    sceneGraph._runtimeNodes = new Array(nodesLength);

    const rootNodes = scene.nodes;
    const rootNodesLength = rootNodes.length;
    const transformToRoot = Matrix4.IDENTITY;
    for (let i = 0; i < rootNodesLength; i++) {
      const rootNode = scene.nodes[i];

      const rootNodeIndex = traverseSceneGraph(
        sceneGraph,
        rootNode,
        transformToRoot
      );

      sceneGraph._rootNodes.push(rootNodeIndex);
    }

    // Handle skins after all runtime nodes are created
    const skins = components.skins;
    const runtimeSkins = sceneGraph._runtimeSkins;

    const skinsLength = skins.length;
    for (let i = 0; i < skinsLength; i++) {
      const skin = skins[i];
      runtimeSkins.push(
        new ModelExperimentalSkin({
          skin: skin,
          sceneGraph: sceneGraph,
        })
      );
    }

    const skinnedNodes = sceneGraph._skinnedNodes;
    const skinnedNodesLength = skinnedNodes.length;
    for (let i = 0; i < skinnedNodesLength; i++) {
      const skinnedNodeIndex = skinnedNodes[i];
      const skinnedNode = sceneGraph._runtimeNodes[skinnedNodeIndex];

      // Use the index of the skin in the model components to find
      // the corresponding runtime skin.
      const skin = nodes[skinnedNodeIndex].skin;
      const skinIndex = skin.index;

      skinnedNode._runtimeSkin = runtimeSkins[skinIndex];
      skinnedNode.updateJointMatrices();
    }

    // Ensure articulations are applied with their initial values to their target nodes.
    sceneGraph.applyArticulations();
  }

  function computeModelMatrix(sceneGraph, modelMatrix) {
    const components = sceneGraph._components;
    const model = sceneGraph._model;

    sceneGraph._computedModelMatrix = Matrix4.multiplyTransformation(
      modelMatrix,
      components.transform,
      sceneGraph._computedModelMatrix
    );

    sceneGraph._computedModelMatrix = Matrix4.multiplyTransformation(
      sceneGraph._computedModelMatrix,
      sceneGraph._axisCorrectionMatrix,
      sceneGraph._computedModelMatrix
    );

    sceneGraph._computedModelMatrix = Matrix4.multiplyByUniformScale(
      sceneGraph._computedModelMatrix,
      model.computedScale,
      sceneGraph._computedModelMatrix
    );
  }

  const scratchComputedTranslation = new Cartesian3();

  function computeModelMatrix2D(sceneGraph, frameState) {
    const computedModelMatrix = sceneGraph._computedModelMatrix;
    const translation = Matrix4.getTranslation(
      computedModelMatrix,
      scratchComputedTranslation
    );

    if (!Cartesian3.equals(translation, Cartesian3.ZERO)) {
      sceneGraph._computedModelMatrix2D = Transforms.basisTo2D(
        frameState.mapProjection,
        computedModelMatrix,
        sceneGraph._computedModelMatrix2D
      );
    } else {
      const center = sceneGraph.boundingSphere.center;
      const to2D = Transforms.wgs84To2DModelMatrix(
        frameState.mapProjection,
        center,
        sceneGraph._computedModelMatrix2D
      );
      sceneGraph._computedModelMatrix2D = Matrix4.multiply(
        to2D,
        computedModelMatrix,
        sceneGraph._computedModelMatrix2D
      );
    }

    sceneGraph._boundingSphere2D = BoundingSphere.transform(
      sceneGraph._boundingSphere,
      sceneGraph._computedModelMatrix2D,
      sceneGraph._boundingSphere2D
    );
  }

  /**
   * Recursively traverse through the nodes in the scene graph, using depth-first
   * post-order traversal.
   *
   * @param {ModelSceneGraph} sceneGraph The scene graph
   * @param {ModelComponents.Node} node The current node
   * @param {Matrix4} transformToRoot The transforms of this node's ancestors.
   *
   * @returns {Number} The index of this node in the runtimeNodes array.
   *
   * @private
   */
  function traverseSceneGraph(sceneGraph, node, transformToRoot) {
    // The indices of the children of this node in the runtimeNodes array.
    const childrenIndices = [];
    const transform = ModelExperimentalUtility.getNodeTransform(node);

    // Traverse through scene graph.
    const childrenLength = node.children.length;
    for (let i = 0; i < childrenLength; i++) {
      const childNode = node.children[i];
      const childNodeTransformToRoot = Matrix4.multiplyTransformation(
        transformToRoot,
        transform,
        new Matrix4()
      );

      const childIndex = traverseSceneGraph(
        sceneGraph,
        childNode,
        childNodeTransformToRoot
      );
      childrenIndices.push(childIndex);
    }

    // Process node and mesh primitives.
    const runtimeNode = new ModelExperimentalNode({
      node: node,
      transform: transform,
      transformToRoot: transformToRoot,
      children: childrenIndices,
      sceneGraph: sceneGraph,
    });

    const primitivesLength = node.primitives.length;
    for (let i = 0; i < primitivesLength; i++) {
      runtimeNode.runtimePrimitives.push(
        new ModelExperimentalPrimitive({
          primitive: node.primitives[i],
          node: node,
          model: sceneGraph._model,
        })
      );
    }

    const index = node.index;
    sceneGraph._runtimeNodes[index] = runtimeNode;
    if (defined(node.skin)) {
      sceneGraph._skinnedNodes.push(index);
    }

    return index;
  }

  const scratchModelPositionMin = new Cartesian3();
  const scratchModelPositionMax = new Cartesian3();
  const scratchPrimitivePositionMin = new Cartesian3();
  const scratchPrimitivePositionMax = new Cartesian3();
  /**
   * Generates the {@link ModelExperimentalDrawCommand} for each primitive in the model.
   *
   * @param {FrameState} frameState The current frame state. This is needed to
   * allocate GPU resources as needed.
   *
   * @private
   */
  ModelExperimentalSceneGraph.prototype.buildDrawCommands = function (
    frameState
  ) {
    const model = this._model;
    const modelRenderResources = new ModelRenderResources(model);

    // Reset the memory counts before running the pipeline
    model.statistics.clear();

    this.configurePipeline(frameState);
    const modelPipelineStages = this.modelPipelineStages;

    let i, j, k;
    for (i = 0; i < modelPipelineStages.length; i++) {
      const modelPipelineStage = modelPipelineStages[i];
      modelPipelineStage.process(modelRenderResources, model, frameState);
    }

    const modelPositionMin = Cartesian3.fromElements(
      Number.MAX_VALUE,
      Number.MAX_VALUE,
      Number.MAX_VALUE,
      scratchModelPositionMin
    );
    const modelPositionMax = Cartesian3.fromElements(
      -Number.MAX_VALUE,
      -Number.MAX_VALUE,
      -Number.MAX_VALUE,
      scratchModelPositionMax
    );

    for (i = 0; i < this._runtimeNodes.length; i++) {
      const runtimeNode = this._runtimeNodes[i];
      runtimeNode.configurePipeline();
      const nodePipelineStages = runtimeNode.pipelineStages;

      const nodeRenderResources = new NodeRenderResources(
        modelRenderResources,
        runtimeNode
      );

      for (j = 0; j < nodePipelineStages.length; j++) {
        const nodePipelineStage = nodePipelineStages[j];

        nodePipelineStage.process(
          nodeRenderResources,
          runtimeNode.node,
          frameState
        );
      }

      const nodeTransform = runtimeNode.computedTransform;
      for (j = 0; j < runtimeNode.runtimePrimitives.length; j++) {
        const runtimePrimitive = runtimeNode.runtimePrimitives[j];

        runtimePrimitive.configurePipeline(frameState);
        const primitivePipelineStages = runtimePrimitive.pipelineStages;

        const primitiveRenderResources = new PrimitiveRenderResources(
          nodeRenderResources,
          runtimePrimitive
        );

        for (k = 0; k < primitivePipelineStages.length; k++) {
          const primitivePipelineStage = primitivePipelineStages[k];

          primitivePipelineStage.process(
            primitiveRenderResources,
            runtimePrimitive.primitive,
            frameState
          );
        }

        runtimePrimitive.boundingSphere = BoundingSphere.clone(
          primitiveRenderResources.boundingSphere,
          new BoundingSphere()
        );

        const primitivePositionMin = Matrix4.multiplyByPoint(
          nodeTransform,
          primitiveRenderResources.positionMin,
          scratchPrimitivePositionMin
        );
        const primitivePositionMax = Matrix4.multiplyByPoint(
          nodeTransform,
          primitiveRenderResources.positionMax,
          scratchPrimitivePositionMax
        );

        Cartesian3.minimumByComponent(
          modelPositionMin,
          primitivePositionMin,
          modelPositionMin
        );
        Cartesian3.maximumByComponent(
          modelPositionMax,
          primitivePositionMax,
          modelPositionMax
        );

        const drawCommand = buildDrawCommand(
          primitiveRenderResources,
          frameState
        );

        runtimePrimitive.drawCommand = drawCommand;
      }
    }

    this._boundingSphere = BoundingSphere.fromCornerPoints(
      modelPositionMin,
      modelPositionMax,
      new BoundingSphere()
    );

    this._boundingSphere = BoundingSphere.transformWithoutScale(
      this._boundingSphere,
      this._axisCorrectionMatrix,
      this._boundingSphere
    );

    model._boundingSphere = BoundingSphere.transform(
      this._boundingSphere,
      model.modelMatrix,
      model._boundingSphere
    );
    model._initialRadius = model._boundingSphere.radius;
    model._boundingSphere.radius *= model._clampedScale;
  };

  /**
   * Configure the model pipeline stages. If the pipeline needs to be re-run, call
   * this method again to ensure the correct sequence of pipeline stages are
   * used.
   *
   * @private
   */
  ModelExperimentalSceneGraph.prototype.configurePipeline = function (
    frameState
  ) {
    const modelPipelineStages = this.modelPipelineStages;
    modelPipelineStages.length = 0;

    const model = this._model;

    if (defined(model.color)) {
      modelPipelineStages.push(ModelColorPipelineStage);
    }

    if (model.imageBasedLighting.enabled) {
      modelPipelineStages.push(ImageBasedLightingPipelineStage);
    }

    if (model.isClippingEnabled()) {
      modelPipelineStages.push(ModelClippingPlanesPipelineStage);
    }

    if (
      defined(model.splitDirection) &&
      model.splitDirection !== SplitDirection$1.NONE
    ) {
      modelPipelineStages.push(ModelSplitterPipelineStage);
    }

    if (model.hasSilhouette(frameState)) {
      modelPipelineStages.push(ModelSilhouettePipelineStage);
    }
  };

  ModelExperimentalSceneGraph.prototype.update = function (
    frameState,
    updateForAnimations
  ) {
    let i, j, k;

    for (i = 0; i < this._runtimeNodes.length; i++) {
      const runtimeNode = this._runtimeNodes[i];

      for (j = 0; j < runtimeNode.updateStages.length; j++) {
        const nodeUpdateStage = runtimeNode.updateStages[j];
        nodeUpdateStage.update(runtimeNode, this, frameState);
      }

      const disableAnimations =
        frameState.mode !== SceneMode$1.SCENE3D && this._model._projectTo2D;
      if (updateForAnimations && !disableAnimations) {
        this.updateJointMatrices();
      }

      for (j = 0; j < runtimeNode.runtimePrimitives.length; j++) {
        const runtimePrimitive = runtimeNode.runtimePrimitives[j];
        for (k = 0; k < runtimePrimitive.updateStages.length; k++) {
          const stage = runtimePrimitive.updateStages[k];
          stage.update(runtimePrimitive, this);
        }
      }
    }
  };

  ModelExperimentalSceneGraph.prototype.updateModelMatrix = function (
    modelMatrix,
    frameState
  ) {
    computeModelMatrix(this, modelMatrix);
    if (frameState.mode !== SceneMode$1.SCENE3D) {
      computeModelMatrix2D(this, frameState);
    }

    // Mark all root nodes as dirty. Any and all children will be
    // affected recursively in the update stage.
    const rootNodes = this._rootNodes;
    for (let i = 0; i < rootNodes.length; i++) {
      const node = this._runtimeNodes[rootNodes[i]];
      node._transformDirty = true;
    }
  };

  /**
   * Updates the joint matrices for the skins and nodes of the model.
   *
   * @private
   */
  ModelExperimentalSceneGraph.prototype.updateJointMatrices = function () {
    const skinnedNodes = this._skinnedNodes;
    const length = skinnedNodes.length;

    for (let i = 0; i < length; i++) {
      const nodeIndex = skinnedNodes[i];
      const runtimeNode = this._runtimeNodes[nodeIndex];
      runtimeNode.updateJointMatrices();
    }
  };

  function forEachRuntimePrimitive(sceneGraph, callback) {
    for (let i = 0; i < sceneGraph._runtimeNodes.length; i++) {
      const runtimeNode = sceneGraph._runtimeNodes[i];
      for (let j = 0; j < runtimeNode.runtimePrimitives.length; j++) {
        const runtimePrimitive = runtimeNode.runtimePrimitives[j];
        callback(runtimePrimitive);
      }
    }
  }

  /**
   * Traverses through all draw commands and changes the back-face culling setting.
   *
   * @param {Boolean} backFaceCulling The new value for the back-face culling setting.
   *
   * @private
   */
  ModelExperimentalSceneGraph.prototype.updateBackFaceCulling = function (
    backFaceCulling
  ) {
    forEachRuntimePrimitive(this, function (runtimePrimitive) {
      const drawCommand = runtimePrimitive.drawCommand;
      drawCommand.backFaceCulling = backFaceCulling;
    });
  };

  /**
   * Traverses through all draw commands and changes the shadow settings.
   *
   * @param {ShadowMode} shadowMode The new shadow settings.
   *
   * @private
   */
  ModelExperimentalSceneGraph.prototype.updateShadows = function (shadowMode) {
    forEachRuntimePrimitive(this, function (runtimePrimitive) {
      const drawCommand = runtimePrimitive.drawCommand;
      drawCommand.shadows = shadowMode;
    });
  };

  /**
   * Traverses through all draw commands and changes whether to show the debug bounding volume.
   *
   * @param {Boolean} debugShowBoundingVolume The new value for showing the debug bounding volume.
   *
   * @private
   */
  ModelExperimentalSceneGraph.prototype.updateShowBoundingVolume = function (
    debugShowBoundingVolume
  ) {
    forEachRuntimePrimitive(this, function (runtimePrimitive) {
      const drawCommand = runtimePrimitive.drawCommand;
      drawCommand.debugShowBoundingVolume = debugShowBoundingVolume;
    });
  };

  /**
   * Returns an array of draw commands, obtained by traversing through the scene graph and collecting
   * the draw commands associated with each primitive.
   *
   * @param {FrameState} frameState The frame state.
   *
   * @returns {DrawCommand[]} The draw commands of the primitives in the scene graph.
   *
   * @private
   */
  ModelExperimentalSceneGraph.prototype.getDrawCommands = function (frameState) {
    const drawCommands = [];
    forEachRuntimePrimitive(this, function (runtimePrimitive) {
      const primitiveDrawCommand = runtimePrimitive.drawCommand;
      const result = primitiveDrawCommand.getCommands(frameState);
      drawCommands.push.apply(drawCommands, result);
    });
    return drawCommands;
  };

  /**
   * Sets the current value of an articulation stage.
   *
   * @param {String} articulationStageKey The name of the articulation, a space, and the name of the stage.
   * @param {Number} value The numeric value of this stage of the articulation.
   *
   * @private
   */
  ModelExperimentalSceneGraph.prototype.setArticulationStage = function (
    articulationStageKey,
    value
  ) {
    const names = articulationStageKey.split(" ");
    if (names.length !== 2) {
      return;
    }

    const articulationName = names[0];
    const stageName = names[1];

    const runtimeArticulation = this._runtimeArticulations[articulationName];
    if (defined(runtimeArticulation)) {
      runtimeArticulation.setArticulationStage(stageName, value);
    }
  };

  /**
   * Applies any modified articulation stages to the matrix of each node that participates
   * in any articulation.  Note that this will overwrite any nodeTransformations on participating nodes.
   *
   * @private
   */
  ModelExperimentalSceneGraph.prototype.applyArticulations = function () {
    const runtimeArticulations = this._runtimeArticulations;
    for (const articulationName in runtimeArticulations) {
      if (runtimeArticulations.hasOwnProperty(articulationName)) {
        const articulation = runtimeArticulations[articulationName];
        articulation.apply();
      }
    }
  };

  /**
   * Rendering statistics for a single model
   *
   * @alias ModelExperimentalStatistics
   * @constructor
   *
   * @see Cesium3DTilesetStatistics
   *
   * @private
   */
  function ModelExperimentalStatistics() {
    /**
     * Total number of points across all POINTS primitives in this model
     *
     * @type {Number}
     * @private
     */
    this.pointsLength = 0;

    /**
     * Total number of triangles across all TRIANGLES, TRIANGLE_STRIP or
     * TRIANGLE_FAN primitives in this model
     *
     * @type {Number}
     * @private
     */
    this.trianglesLength = 0;

    /**
     * Total size of all geometry buffers in bytes. This accounts for the vertex
     * attributes (which includes feature IDs and property attributes),
     * and index buffers of all the model's primitives. Any attributes generated
     * by the pipeline are included in this total.
     *
     * @type {Number}
     * @private
     */
    this.geometryByteLength = 0;

    /**
     * Total size of all textures in bytes. This includes materials,
     * feature ID textures, and property textures.
     *
     * @type {Number}
     * @private
     */
    this.texturesByteLength = 0;

    /**
     * Total size of property tables, including the batch textures used for
     * picking and styling.
     *
     * @type {Number}
     * @private
     */
    this.propertyTablesByteLength = 0;

    // Sets of buffers and textures we've already counted, so we don't
    // double-count cached assets.
    this.bufferIdSet = {};
    this.textureIdSet = {};
  }

  /**
   * Reset the memory counts for this model. This should be called each time the
   * draw command pipeline is rebuilt.
   *
   * @private
   */
  ModelExperimentalStatistics.prototype.clear = function () {
    this.pointsLength = 0;
    this.trianglesLength = 0;
    this.geometryByteLength = 0;
    this.texturesByteLength = 0;
    this.propertyTablesByteLength = 0;

    this.bufferIdSet = {};
    this.textureIdSet = {};
  };

  ModelExperimentalStatistics.prototype.addBuffer = function (
    buffer,
    hasCpuCopy
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("buffer", buffer);
    Check.typeOf.bool("hasCpuCopy", hasCpuCopy);
    //>>includeEnd('debug');

    if (!this.bufferIdSet.hasOwnProperty(buffer._id)) {
      // If there's a CPU copy, we need to count the memory twice
      const copies = hasCpuCopy ? 2 : 1;
      this.geometryByteLength += buffer.sizeInBytes * copies;
    }

    // Simulate set insertion
    this.bufferIdSet[buffer._id] = true;
  };

  ModelExperimentalStatistics.prototype.addTexture = function (texture) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("texture", texture);
    //>>includeEnd('debug');

    if (!this.textureIdSet.hasOwnProperty(texture._id)) {
      this.texturesByteLength += texture.sizeInBytes;
    }

    // Simulate set insertion
    this.textureIdSet[texture._id] = true;
  };

  /**
   * A feature of a {@link ModelExperimental}.
   * <p>
   * Provides access to a feature's properties stored in the model's feature table.
   * </p>
   * <p>
   * Modifications to a <code>ModelFeature</code> object have the lifetime of the model.
   * </p>
   * <p>
   * Do not construct this directly. Access it through picking using {@link Scene#pick}.
   * </p>
   *
   * @alias ModelFeature
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {ModelExperimental} options.model The model the feature belongs to.
   * @param {Number} options.featureId The unique integral identifier for this feature.
   *
   * @example
   * // On mouse over, display all the properties for a feature in the console log.
   * handler.setInputAction(function(movement) {
   *     const feature = scene.pick(movement.endPosition);
   *     if (feature instanceof Cesium.ModelFeature) {
   *         console.log(feature);
   *     }
   * }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
   *
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function ModelFeature(options) {
    this._model = options.model;

    // This ModelFeatureTable is not documented as an option since it is
    // part of the private API and should not appear in the documentation.
    this._featureTable = options.featureTable;

    this._featureId = options.featureId;
    this._color = undefined; // for calling getColor
  }

  Object.defineProperties(ModelFeature.prototype, {
    /**
     * Gets or sets if the feature will be shown. This is set for all features
     * when a style's show is evaluated.
     *
     * @memberof ModelFeature.prototype
     *
     * @type {Boolean}
     *
     * @default true
     */
    show: {
      get: function () {
        return this._featureTable.getShow(this._featureId);
      },
      set: function (value) {
        this._featureTable.setShow(this._featureId, value);
      },
    },

    /**
     * Gets or sets the highlight color multiplied with the feature's color.  When
     * this is white, the feature's color is not changed. This is set for all features
     * when a style's color is evaluated.
     *
     * @memberof ModelFeature.prototype
     *
     * @type {Color}
     *
     * @default {@link Color.WHITE}
     */
    color: {
      get: function () {
        if (!defined(this._color)) {
          this._color = new Color();
        }
        return this._featureTable.getColor(this._featureId, this._color);
      },
      set: function (value) {
        this._featureTable.setColor(this._featureId, value);
      },
    },
    /**
     * All objects returned by {@link Scene#pick} have a <code>primitive</code> property. This returns
     * the model containing the feature.
     *
     * @memberof ModelFeature.prototype
     *
     * @type {ModelExperimental}
     *
     * @readonly
     * @private
     */
    primitive: {
      get: function () {
        return this._model;
      },
    },

    /**
     *  The {@link ModelFeatureTable} that this feature belongs to.
     *
     * @memberof ModelFeature.prototype
     *
     * @type {ModelFeatureTable}
     *
     * @readonly
     * @private
     */
    featureTable: {
      get: function () {
        return this._featureTable;
      },
    },

    /**
     * Get the feature ID associated with this feature. For 3D Tiles 1.0, the
     * batch ID is returned. For EXT_mesh_features, this is the feature ID from
     * the selected feature ID set.
     *
     * @memberof ModelFeature.prototype
     *
     * @type {Number}
     *
     * @readonly
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     */
    featureId: {
      get: function () {
        return this._featureId;
      },
    },
  });

  /**
   * Returns whether the feature contains this property.
   *
   * @param {String} name The case-sensitive name of the property.
   * @returns {Boolean} Whether the feature contains this property.
   */
  ModelFeature.prototype.hasProperty = function (name) {
    return this._featureTable.hasProperty(this._featureId, name);
  };

  /**
   * Returns a copy of the value of the feature's property with the given name.
   *
   * @param {String} name The case-sensitive name of the property.
   * @returns {*} The value of the property or <code>undefined</code> if the feature does not have this property.
   *
   * @example
   * // Display all the properties for a feature in the console log.
   * const propertyIds = feature.getPropertyIds();
   * const length = propertyIds.length;
   * for (let i = 0; i < length; ++i) {
   *     const propertyId = propertyIds[i];
   *     console.log(propertyId + ': ' + feature.getProperty(propertyId));
   * }
   */
  ModelFeature.prototype.getProperty = function (name) {
    return this._featureTable.getProperty(this._featureId, name);
  };

  /**
   * Returns a copy of the feature's property with the given name, examining all
   * the metadata from the EXT_structural_metadata and legacy EXT_feature_metadata glTF
   * extensions. Metadata is checked against name from most specific to most
   * general and the first match is returned. Metadata is checked in this order:
   * <ol>
   *   <li>structural metadata property by semantic</li>
   *   <li>structural metadata property by property ID</li>
   * </ol>
   * <p>
   * See the {@link https://github.com/CesiumGS/glTF/tree/3d-tiles-next/extensions/2.0/Vendor/EXT_structural_metadata|EXT_structural_metadata Extension} as well as the
   * previous {@link https://github.com/CesiumGS/glTF/tree/3d-tiles-next/extensions/2.0/Vendor/EXT_feature_metadata|EXT_feature_metadata Extension} for glTF.
   * </p>
   *
   * @param {String} name The semantic or property ID of the feature. Semantics are checked before property IDs in each granularity of metadata.
   * @return {*} The value of the property or <code>undefined</code> if the feature does not have this property.
   *
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  ModelFeature.prototype.getPropertyInherited = function (name) {
    if (this._featureTable.hasPropertyBySemantic(this._featureId, name)) {
      return this._featureTable.getPropertyBySemantic(this._featureId, name);
    }

    return this._featureTable.getProperty(this._featureId, name);
  };

  /**
   * Returns an array of property names for the feature.
   *
   * @deprecated
   *
   * @param {String[]} [results] An array into which to store the results.
   * @returns {String[]} The names of the feature's properties.
   */
  ModelFeature.prototype.getPropertyNames = function (results) {
    deprecationWarning(
      "ModelFeature.getPropertyNames",
      "ModelFeature.getPropertyNames is deprecated in CesiumJS 1.95, and will be removed in 1.98. Use ModelFeature.getPropertyIds instead"
    );
    return this._featureTable.getPropertyIds(results);
  };

  /**
   * Returns an array of property IDs for the feature.
   *
   * @param {String[]} [results] An array into which to store the results.
   * @returns {String[]} The IDs of the feature's properties.
   */
  ModelFeature.prototype.getPropertyIds = function (results) {
    return this._featureTable.getPropertyIds(results);
  };

  /**
   * Sets the value of the feature's property with the given name.
   *
   * @param {String} name The case-sensitive name of the property.
   * @param {*} value The value of the property that will be copied.
   * @returns {Boolean} <code>true</code> if the property was set, <code>false</code> otherwise.
   *
   * @exception {DeveloperError} Inherited batch table hierarchy property is read only.
   *
   * @example
   * const height = feature.getProperty('Height'); // e.g., the height of a building
   *
   * @example
   * const name = 'clicked';
   * if (feature.getProperty(name)) {
   *     console.log('already clicked');
   * } else {
   *     feature.setProperty(name, true);
   *     console.log('first click');
   * }
   */
  ModelFeature.prototype.setProperty = function (name, value) {
    return this._featureTable.setProperty(this._featureId, name, value);
  };

  /**
   * Manages the {@link ModelFeature}s in a {@link ModelExperimental}.
   * Extracts the properties from a {@link PropertyTable}.
   *
   * @param {Object} options An object containing the following options:
   * @param {ModelExperimental} options.model The model that owns this feature table.
   * @param {PropertyTable} options.propertyTable The property table from the model used to initialize the model.
   *
   * @alias ModelFeatureTable
   * @constructor
   *
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function ModelFeatureTable(options) {
    const model = options.model;
    const propertyTable = options.propertyTable;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("propertyTable", propertyTable);
    Check.typeOf.object("model", model);
    //>>includeEnd('debug');

    this._propertyTable = propertyTable;
    this._model = model;

    this._features = undefined;
    this._featuresLength = 0;

    this._batchTexture = undefined;

    this._styleCommandsNeededDirty = false;
    this._styleCommandsNeeded = StyleCommandsNeeded$1.ALL_OPAQUE;

    initialize$1(this);
  }

  Object.defineProperties(ModelFeatureTable.prototype, {
    /**
     * The batch texture created for the features in this table.
     *
     * @memberof ModelFeatureTable.prototype
     *
     * @type {BatchTexture}
     * @readonly
     *
     * @private
     */
    batchTexture: {
      get: function () {
        return this._batchTexture;
      },
    },

    /**
     * The number of features in this table.
     *
     * @memberof ModelFeatureTable.prototype
     *
     * @type {Number}
     * @readonly
     *
     * @private
     */
    featuresLength: {
      get: function () {
        return this._featuresLength;
      },
    },

    /**
     * Size of the batch texture. This does not count the property table size
     * as that is counted separately through StructuralMetadata.
     *
     * @memberof ModelFeatureTable.prototype
     *
     * @type {Number}
     * @readonly
     *
     * @private
     */
    batchTextureByteLength: {
      get: function () {
        if (defined(this._batchTexture)) {
          return this._batchTexture.byteLength;
        }

        return 0;
      },
    },

    /**
     * A flag to indicate whether or not the types of style commands needed by this feature table have changed.
     *
     * @memberof ModelFeatureTable.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @private
     */
    styleCommandsNeededDirty: {
      get: function () {
        return this._styleCommandsNeededDirty;
      },
    },
  });

  function initialize$1(modelFeatureTable) {
    const model = modelFeatureTable._model;
    const is3DTiles = ModelExperimentalType$1.is3DTiles(model.type);

    const featuresLength = modelFeatureTable._propertyTable.count;
    if (featuresLength === 0) {
      return;
    }

    let i;
    const features = new Array(featuresLength);
    if (is3DTiles) {
      const content = model.content;
      for (i = 0; i < featuresLength; i++) {
        features[i] = new Cesium3DTileFeature(content, i);
      }
    } else {
      for (i = 0; i < featuresLength; i++) {
        features[i] = new ModelFeature({
          model: model,
          featureId: i,
          featureTable: modelFeatureTable,
        });
      }
    }

    modelFeatureTable._features = features;
    modelFeatureTable._featuresLength = featuresLength;

    modelFeatureTable._batchTexture = new BatchTexture({
      featuresLength: featuresLength,
      owner: modelFeatureTable,
      statistics: is3DTiles ? model.content.tileset.statistics : undefined,
    });
  }

  /**
   * Creates/updates the batch texture.
   *
   * @param {FrameState} frameState The frame state.
   *
   * @private
   */
  ModelFeatureTable.prototype.update = function (frameState) {
    // Assume the number of translucent features has not changed.
    this._styleCommandsNeededDirty = false;
    this._batchTexture.update(undefined, frameState);

    const currentStyleCommandsNeeded = StyleCommandsNeeded$1.getStyleCommandsNeeded(
      this._featuresLength,
      this._batchTexture.translucentFeaturesLength
    );

    if (this._styleCommandsNeeded !== currentStyleCommandsNeeded) {
      this._styleCommandsNeededDirty = true;
      this._styleCommandsNeeded = currentStyleCommandsNeeded;
    }
  };

  ModelFeatureTable.prototype.setShow = function (featureId, show) {
    this._batchTexture.setShow(featureId, show);
  };

  ModelFeatureTable.prototype.setAllShow = function (show) {
    this._batchTexture.setAllShow(show);
  };

  ModelFeatureTable.prototype.getShow = function (featureId) {
    return this._batchTexture.getShow(featureId);
  };

  ModelFeatureTable.prototype.setColor = function (featureId, color) {
    this._batchTexture.setColor(featureId, color);
  };

  ModelFeatureTable.prototype.setAllColor = function (color) {
    this._batchTexture.setAllColor(color);
  };

  ModelFeatureTable.prototype.getColor = function (featureId, result) {
    return this._batchTexture.getColor(featureId, result);
  };

  ModelFeatureTable.prototype.getPickColor = function (featureId) {
    return this._batchTexture.getPickColor(featureId);
  };

  ModelFeatureTable.prototype.getFeature = function (featureId) {
    return this._features[featureId];
  };

  ModelFeatureTable.prototype.hasProperty = function (featureId, propertyName) {
    return this._propertyTable.hasProperty(featureId, propertyName);
  };

  ModelFeatureTable.prototype.hasPropertyBySemantic = function (
    featureId,
    propertyName
  ) {
    return this._propertyTable.hasPropertyBySemantic(featureId, propertyName);
  };

  ModelFeatureTable.prototype.getProperty = function (featureId, name) {
    return this._propertyTable.getProperty(featureId, name);
  };

  ModelFeatureTable.prototype.getPropertyBySemantic = function (
    featureId,
    semantic
  ) {
    return this._propertyTable.getPropertyBySemantic(featureId, semantic);
  };

  ModelFeatureTable.prototype.getPropertyIds = function (results) {
    return this._propertyTable.getPropertyIds(results);
  };

  ModelFeatureTable.prototype.setProperty = function (featureId, name, value) {
    return this._propertyTable.setProperty(featureId, name, value);
  };

  const scratchColor$e = new Color();
  /**
   * @private
   */
  ModelFeatureTable.prototype.applyStyle = function (style) {
    if (!defined(style)) {
      this.setAllColor(BatchTexture.DEFAULT_COLOR_VALUE);
      this.setAllShow(BatchTexture.DEFAULT_SHOW_VALUE);
      return;
    }

    for (let i = 0; i < this._featuresLength; i++) {
      const feature = this.getFeature(i);
      const color = defined(style.color)
        ? defaultValue(
            style.color.evaluateColor(feature, scratchColor$e),
            BatchTexture.DEFAULT_COLOR_VALUE
          )
        : BatchTexture.DEFAULT_COLOR_VALUE;
      const show = defined(style.show)
        ? defaultValue(
            style.show.evaluate(feature),
            BatchTexture.DEFAULT_SHOW_VALUE
          )
        : BatchTexture.DEFAULT_SHOW_VALUE;

      this.setColor(i, color);
      this.setShow(i, show);
    }
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <p>
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   * </p>
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see ModelFeatureTable#destroy
   * @private
   */
  ModelFeatureTable.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <p>
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   * </p>
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @example
   * e = e && e.destroy();
   *
   * @see ModelFeatureTable#isDestroyed
   * @private
   */
  ModelFeatureTable.prototype.destroy = function (frameState) {
    this._batchTexture.destroy();
    destroyObject(this);
  };

  /**
   * A table for storing free-form JSON metadata, as in the 3D Tiles batch table.
   *
   * @param {Object} options Object with the following properties:
   * @param {Number} options.count The number of entities in the table.
   * @param {Object.<String, Array>} options.properties The JSON representation of the metadata table. All the arrays must have exactly options.count elements.
   *
   * @alias JsonMetadataTable
   * @constructor
   * @private
   */

  // An empty class is used because JsonMetadataTable is an older type of metadata table
  // that does not have a class definition.
  const emptyClass = {};

  function JsonMetadataTable(options) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number.greaterThan("options.count", options.count, 0);
    Check.typeOf.object("options.properties", options.properties);
    //>>includeEnd('debug');

    this._count = options.count;
    this._properties = clone$1(options.properties, true);
  }

  /**
   * Returns whether the table has this property.
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @returns {Boolean} Whether the table has this property.
   * @private
   */
  JsonMetadataTable.prototype.hasProperty = function (propertyId) {
    return MetadataEntity.hasProperty(propertyId, this._properties, emptyClass);
  };

  /**
   * Returns an array of property IDs.
   *
   * @param {String[]} [results] An array into which to store the results.
   * @returns {String[]} The property IDs.
   * @private
   */
  JsonMetadataTable.prototype.getPropertyIds = function (results) {
    return MetadataEntity.getPropertyIds(this._properties, emptyClass, results);
  };

  /**
   * Returns a copy of the value of the property with the given ID.
   *
   * @param {Number} index The index of the entity.
   * @param {String} propertyId The case-sensitive ID of the property.
   * @returns {*} The value of the property or <code>undefined</code> if the entity does not have this property.
   *
   * @exception {DeveloperError} index is out of bounds
   * @private
   */
  JsonMetadataTable.prototype.getProperty = function (index, propertyId) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("index", index);
    Check.typeOf.string("propertyId", propertyId);

    if (index < 0 || index >= this._count) {
      throw new DeveloperError(`index must be in the range [0, ${this._count})`);
    }
    //>>includeEnd('debug');

    const property = this._properties[propertyId];
    if (defined(property)) {
      return clone$1(property[index], true);
    }

    return undefined;
  };

  /**
   * Sets the value of the property with the given ID.
   *
   * @param {Number} index The index of the entity.
   * @param {String} propertyId The case-sensitive ID of the property.
   * @param {*} value The value of the property that will be copied.
   * @returns {Boolean} <code>true</code> if the property was set, <code>false</code> otherwise.
   *
   * @exception {DeveloperError} index is out of bounds
   * @private
   */
  JsonMetadataTable.prototype.setProperty = function (index, propertyId, value) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("index", index);
    Check.typeOf.string("propertyId", propertyId);

    if (index < 0 || index >= this._count) {
      throw new DeveloperError(`index must be in the range [0, ${this._count})`);
    }
    //>>includeEnd('debug');

    const property = this._properties[propertyId];
    if (defined(property)) {
      property[index] = clone$1(value, true);
      return true;
    }

    return false;
  };

  /**
   * An object that parses the the 3D Tiles 1.0 batch table and transcodes it to
   * be compatible with structural metadata from the <code>EXT_structural_metadata</code> glTF extension
   * <p>
   * See the {@link https://github.com/CesiumGS/glTF/tree/3d-tiles-next/extensions/2.0/Vendor/EXT_structural_metadata|EXT_structural_metadata Extension} for glTF.
   * </p>
   *
   * @param {Object} options Object with the following properties:
   * @param {Number} options.count The number of features in the batch table.
   * @param {Object} options.batchTable The batch table JSON
   * @param {Uint8Array} [options.binaryBody] The batch table binary body
   * @return {StructuralMetadata} A transcoded structural metadata object
   *
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function parseBatchTable(options) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("options.count", options.count);
    Check.typeOf.object("options.batchTable", options.batchTable);
    //>>includeEnd('debug');

    const featureCount = options.count;
    const batchTable = options.batchTable;
    const binaryBody = options.binaryBody;

    // divide properties into binary, json and hierarchy
    const partitionResults = partitionProperties(batchTable);

    const jsonMetadataTable = new JsonMetadataTable({
      count: featureCount,
      properties: partitionResults.jsonProperties,
    });

    const hierarchy = initializeHierarchy(partitionResults.hierarchy, binaryBody);

    const className = MetadataClass.BATCH_TABLE_CLASS_NAME;

    const binaryResults = transcodeBinaryProperties(
      featureCount,
      className,
      partitionResults.binaryProperties,
      binaryBody
    );

    const featureTableJson = binaryResults.featureTableJson;

    const metadataTable = new MetadataTable({
      count: featureTableJson.count,
      properties: featureTableJson.properties,
      class: binaryResults.transcodedClass,
      bufferViews: binaryResults.bufferViewsU8,
    });

    const propertyTable = new PropertyTable({
      id: 0,
      name: "Batch Table",
      count: featureTableJson.count,
      metadataTable: metadataTable,
      jsonMetadataTable: jsonMetadataTable,
      batchTableHierarchy: hierarchy,
    });

    return new StructuralMetadata({
      schema: binaryResults.transcodedSchema,
      propertyTables: [propertyTable],
      extensions: partitionResults.extensions,
      extras: partitionResults.extras,
    });
  }

  /**
   * Divide the batch table's properties into binary, JSON and hierarchy
   * extension as each is handled separately
   *
   * @param {Object} batchTable The batch table JSON
   * @returns {Object} The batch table divided into binary, JSON and hierarchy portions. Extras and extensions are also divided out for ease of processing.
   *
   * @private
   */
  function partitionProperties(batchTable) {
    const legacyHierarchy = batchTable.HIERARCHY;
    const extras = batchTable.extras;
    const extensions = batchTable.extensions;

    let hierarchyExtension;
    if (defined(legacyHierarchy)) {
      parseBatchTable._deprecationWarning(
        "batchTableHierarchyExtension",
        "The batch table HIERARCHY property has been moved to an extension. Use extensions.3DTILES_batch_table_hierarchy instead."
      );
      hierarchyExtension = legacyHierarchy;
    } else if (defined(extensions)) {
      hierarchyExtension = extensions["3DTILES_batch_table_hierarchy"];
    }

    const jsonProperties = {};
    const binaryProperties = {};
    for (const propertyId in batchTable) {
      if (
        !batchTable.hasOwnProperty(propertyId) ||
        // these cases were handled above;
        propertyId === "HIERARCHY" ||
        propertyId === "extensions" ||
        propertyId === "extras"
      ) {
        continue;
      }

      const property = batchTable[propertyId];
      if (Array.isArray(property)) {
        jsonProperties[propertyId] = property;
      } else {
        binaryProperties[propertyId] = property;
      }
    }

    return {
      binaryProperties: binaryProperties,
      jsonProperties: jsonProperties,
      hierarchy: hierarchyExtension,
      extras: extras,
      extensions: extensions,
    };
  }

  /**
   * Transcode the binary properties of the batch table to be compatible with
   * <code>EXT_structural_metadata</code>
   *
   * @param {Number} featureCount The number of features in the batch table
   * @param {String} className The name of the metadata class to be created.
   * @param {Object.<String, Object>} binaryProperties A dictionary of property ID to property definition
   * @param {Uint8Array} [binaryBody] The binary body of the batch table
   * @return {Object} Transcoded data needed for constructing a {@link StructuralMetadata} object.
   *
   * @private
   */
  function transcodeBinaryProperties(
    featureCount,
    className,
    binaryProperties,
    binaryBody
  ) {
    const classProperties = {};
    const featureTableProperties = {};
    const bufferViewsU8 = {};
    let bufferViewCount = 0;
    for (const propertyId in binaryProperties) {
      if (!binaryProperties.hasOwnProperty(propertyId)) {
        continue;
      }

      if (!defined(binaryBody)) {
        throw new RuntimeError(
          `Property ${propertyId} requires a batch table binary.`
        );
      }

      const property = binaryProperties[propertyId];
      const binaryAccessor = getBinaryAccessor(property);

      featureTableProperties[propertyId] = {
        bufferView: bufferViewCount,
      };

      classProperties[propertyId] = transcodePropertyType(property);

      bufferViewsU8[bufferViewCount] = binaryAccessor.createArrayBufferView(
        binaryBody.buffer,
        binaryBody.byteOffset + property.byteOffset,
        featureCount
      );

      bufferViewCount++;
    }

    const schemaJson = {
      classes: {},
    };
    schemaJson.classes[className] = {
      properties: classProperties,
    };

    const transcodedSchema = new MetadataSchema(schemaJson);

    const featureTableJson = {
      class: className,
      count: featureCount,
      properties: featureTableProperties,
    };

    return {
      featureTableJson: featureTableJson,
      bufferViewsU8: bufferViewsU8,
      transcodedSchema: transcodedSchema,
      transcodedClass: transcodedSchema.classes[className],
    };
  }

  /**
   * Given a property definition from the batch table, compute the equivalent
   * <code>EXT_structural_metadata</code> type definition
   *
   * @param {Object} property The batch table property definition
   * @return {Object} The corresponding structural metadata property definition
   * @private
   */
  function transcodePropertyType(property) {
    const componentType = transcodeComponentType(property.componentType);

    return {
      type: property.type,
      componentType: componentType,
    };
  }

  /**
   * Convert the component type of a batch table property to the corresponding
   * type used with structural metadata
   *
   * @property {String} componentType the batch table's component type
   * @return {String} The corresponding structural metadata data type
   *
   * @private
   */
  function transcodeComponentType(componentType) {
    switch (componentType) {
      case "BYTE":
        return "INT8";
      case "UNSIGNED_BYTE":
        return "UINT8";
      case "SHORT":
        return "INT16";
      case "UNSIGNED_SHORT":
        return "UINT16";
      case "INT":
        return "INT32";
      case "UNSIGNED_INT":
        return "UINT32";
      case "FLOAT":
        return "FLOAT32";
      case "DOUBLE":
        return "FLOAT64";
    }
  }

  /**
   * Construct a batch table hierarchy object if the <code>3DTILES_batch_table_hierarchy</code> extension is present
   *
   * @param {Object} [hierarchyExtension] The <code>3DTILES_batch_table_hierarchy</code> extension object.
   * @param {Uint8Array} binaryBody The binary body of the batch table
   * @return {BatchTableHierarchy} A batch table hierarchy, or <code>undefined</code> if the extension is not present.
   *
   * @private
   */
  function initializeHierarchy(hierarchyExtension, binaryBody) {
    if (defined(hierarchyExtension)) {
      return new BatchTableHierarchy({
        extension: hierarchyExtension,
        binaryBody: binaryBody,
      });
    }

    return undefined;
  }

  // exposed for testing
  parseBatchTable._deprecationWarning = deprecationWarning;

  const B3dmLoaderState = {
    UNLOADED: 0,
    LOADING: 1,
    PROCESSING: 2,
    READY: 3,
    FAILED: 4,
  };

  const FeatureIdAttribute$2 = ModelComponents.FeatureIdAttribute;

  /**
   * Loads a Batched 3D Model.
   * <p>
   * Implements the {@link ResourceLoader} interface.
   * </p>
   *
   * @alias B3dmLoader
   * @constructor
   * @augments ResourceLoader
   * @private
   *
   * @param {Object} options Object with the following properties:
   * @param {Resource} options.b3dmResource The {@link Resource} containing the b3dm.
   * @param {ArrayBuffer} options.arrayBuffer The array buffer of the b3dm contents.
   * @param {Number} [options.byteOffset] The byte offset to the beginning of the b3dm contents in the array buffer.
   * @param {Resource} [options.baseResource] The {@link Resource} that paths in the glTF JSON are relative to.
   * @param {Boolean} [options.releaseGltfJson=false] When true, the glTF JSON is released once the glTF is loaded. This is especially useful for cases like 3D Tiles, where each .gltf model is unique and caching the glTF JSON is not effective.
   * @param {Boolean} [options.asynchronous=true] Determines if WebGL resource creation will be spread out over several frames or block until all WebGL resources are created.
   * @param {Boolean} [options.incrementallyLoadTextures=true] Determine if textures may continue to stream in after the glTF is loaded.
   * @param {Axis} [options.upAxis=Axis.Y] The up-axis of the glTF model.
   * @param {Axis} [options.forwardAxis=Axis.X] The forward-axis of the glTF model.
   * @param {Boolean} [options.loadAttributesAsTypedArray=false] Load all attributes as typed arrays instead of GPU buffers.
   * @param {Boolean} [options.loadAttributesFor2D=false] If true, load the positions buffer and any instanced attribute buffers as typed arrays for accurately projecting models to 2D.
   * @param {Boolean} [options.loadIndicesForWireframe=false] Load the index buffer as a typed array. This is useful for creating wireframe indices in WebGL1.
   */
  function B3dmLoader(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const b3dmResource = options.b3dmResource;
    let baseResource = options.baseResource;
    const arrayBuffer = options.arrayBuffer;
    const byteOffset = defaultValue(options.byteOffset, 0);
    const releaseGltfJson = defaultValue(options.releaseGltfJson, false);
    const asynchronous = defaultValue(options.asynchronous, true);
    const incrementallyLoadTextures = defaultValue(
      options.incrementallyLoadTextures,
      true
    );
    const upAxis = defaultValue(options.upAxis, Axis$1.Y);
    const forwardAxis = defaultValue(options.forwardAxis, Axis$1.X);
    const loadAttributesAsTypedArray = defaultValue(
      options.loadAttributesAsTypedArray,
      false
    );
    const loadAttributesFor2D = defaultValue(options.loadAttributesFor2D, false);
    const loadIndicesForWireframe = defaultValue(
      options.loadIndicesForWireframe,
      false
    );

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.b3dmResource", b3dmResource);
    Check.typeOf.object("options.arrayBuffer", arrayBuffer);
    //>>includeEnd('debug');

    baseResource = defined(baseResource) ? baseResource : b3dmResource.clone();

    this._b3dmResource = b3dmResource;
    this._baseResource = baseResource;
    this._arrayBuffer = arrayBuffer;
    this._byteOffset = byteOffset;
    this._releaseGltfJson = releaseGltfJson;
    this._asynchronous = asynchronous;
    this._incrementallyLoadTextures = incrementallyLoadTextures;
    this._upAxis = upAxis;
    this._forwardAxis = forwardAxis;
    this._loadAttributesAsTypedArray = loadAttributesAsTypedArray;
    this._loadAttributesFor2D = loadAttributesFor2D;
    this._loadIndicesForWireframe = loadIndicesForWireframe;

    this._state = B3dmLoaderState.UNLOADED;

    this._promise = undefined;

    this._gltfLoader = undefined;

    // Loaded results.
    this._batchLength = 0;
    this._propertyTable = undefined;

    // The batch table object contains a json and a binary component access using keys of the same name.
    this._batchTable = undefined;
    this._components = undefined;
    this._transform = Matrix4.IDENTITY;
  }

  if (defined(Object.create)) {
    B3dmLoader.prototype = Object.create(ResourceLoader.prototype);
    B3dmLoader.prototype.constructor = B3dmLoader;
  }

  Object.defineProperties(B3dmLoader.prototype, {
    /**
     * A promise that resolves to the resource when the resource is ready, or undefined if the resource hasn't started loading.
     *
     * @memberof B3dmLoader.prototype
     *
     * @type {Promise.<B3dmLoader>|undefined}
     * @readonly
     * @private
     */
    promise: {
      get: function () {
        return this._promise;
      },
    },

    /**
     * A promise that resolves when all textures are loaded.
     * When <code>incrementallyLoadTextures</code> is true this may resolve after
     * <code>promise</code> resolves.
     *
     * @memberof B3dmLoader.prototype
     *
     * @type {Promise}
     * @readonly
     * @private
     */
    texturesLoadedPromise: {
      get: function () {
        return this._gltfLoader.texturesLoadedPromise;
      },
    },
    /**
     * The cache key of the resource
     *
     * @memberof B3dmLoader.prototype
     *
     * @type {String}
     * @readonly
     * @private
     */
    cacheKey: {
      get: function () {
        return undefined;
      },
    },

    /**
     * The loaded components.
     *
     * @memberof B3dmLoader.prototype
     *
     * @type {ModelComponents.Components}
     * @readonly
     * @private
     */
    components: {
      get: function () {
        return this._components;
      },
    },
  });

  /**
   * Loads the resource.
   * @returns {Promise.<B3dmLoader>} A promise which resolves to the loader when the resource loading is completed.
   * @private
   */
  B3dmLoader.prototype.load = function () {
    const b3dm = B3dmParser.parse(this._arrayBuffer, this._byteOffset);

    let batchLength = b3dm.batchLength;
    const featureTableJson = b3dm.featureTableJson;
    const featureTableBinary = b3dm.featureTableBinary;
    const batchTableJson = b3dm.batchTableJson;
    const batchTableBinary = b3dm.batchTableBinary;

    const featureTable = new Cesium3DTileFeatureTable(
      featureTableJson,
      featureTableBinary
    );
    batchLength = featureTable.getGlobalProperty("BATCH_LENGTH");
    // Set batch length.
    this._batchLength = batchLength;
    // Set the RTC Center transform, if present.
    const rtcCenter = featureTable.getGlobalProperty(
      "RTC_CENTER",
      ComponentDatatype$1.FLOAT,
      3
    );
    if (defined(rtcCenter)) {
      this._transform = Matrix4.fromTranslation(Cartesian3.fromArray(rtcCenter));
    }

    this._batchTable = {
      json: batchTableJson,
      binary: batchTableBinary,
    };

    const gltfLoader = new GltfLoader({
      typedArray: b3dm.gltf,
      upAxis: this._upAxis,
      forwardAxis: this._forwardAxis,
      gltfResource: this._b3dmResource,
      baseResource: this._baseResource,
      releaseGltfJson: this._releaseGltfJson,
      incrementallyLoadTextures: this._incrementallyLoadTextures,
      loadAttributesAsTypedArray: this._loadAttributesAsTypedArray,
      loadAttributesFor2D: this._loadAttributesFor2D,
      loadIndicesForWireframe: this._loadIndicesForWireframe,
      renameBatchIdSemantic: true,
    });

    this._gltfLoader = gltfLoader;
    this._state = B3dmLoaderState.LOADING;

    const that = this;
    gltfLoader.load();
    this._promise = gltfLoader.promise
      .then(function () {
        if (that.isDestroyed()) {
          return;
        }

        const components = gltfLoader.components;
        components.transform = that._transform;
        createStructuralMetadata$1(that, components);
        that._components = components;

        that._state = B3dmLoaderState.READY;
        return that;
      })
      .catch(function (error) {
        if (that.isDestroyed()) {
          return;
        }
        return handleError$1(that, error);
      });

    return this._promise;
  };

  function handleError$1(b3dmLoader, error) {
    b3dmLoader.unload();
    b3dmLoader._state = B3dmLoaderState.FAILED;
    const errorMessage = "Failed to load b3dm";
    error = b3dmLoader.getError(errorMessage, error);
    return Promise.reject(error);
  }

  B3dmLoader.prototype.process = function (frameState) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("frameState", frameState);
    //>>includeEnd('debug');

    if (this._state === B3dmLoaderState.LOADING) {
      this._state = B3dmLoaderState.PROCESSING;
    }

    if (this._state === B3dmLoaderState.PROCESSING) {
      this._gltfLoader.process(frameState);
    }
  };

  function createStructuralMetadata$1(loader, components) {
    const batchTable = loader._batchTable;
    const batchLength = loader._batchLength;

    if (batchLength === 0) {
      return;
    }

    let structuralMetadata;
    if (defined(batchTable.json)) {
      // Add the structural metadata from the batch table to the model components.
      structuralMetadata = parseBatchTable({
        count: batchLength,
        batchTable: batchTable.json,
        binaryBody: batchTable.binary,
      });
    } else {
      // If batch table is not defined, create a property table without any properties.
      const emptyPropertyTable = new PropertyTable({
        name: MetadataClass.BATCH_TABLE_CLASS_NAME,
        count: batchLength,
      });
      structuralMetadata = new StructuralMetadata({
        schema: {},
        propertyTables: [emptyPropertyTable],
      });
    }

    // Add the feature ID attribute to the primitives.
    const nodes = components.scene.nodes;
    const length = nodes.length;
    for (let i = 0; i < length; i++) {
      processNode(nodes[i]);
    }
    components.structuralMetadata = structuralMetadata;
  }

  // Recursive function to add the feature ID attribute to all primitives that have a feature ID vertex attribute.
  function processNode(node) {
    const childrenLength = node.children.length;
    for (let i = 0; i < childrenLength; i++) {
      processNode(node.children[i]);
    }

    const primitivesLength = node.primitives.length;
    for (let i = 0; i < primitivesLength; i++) {
      const primitive = node.primitives[i];
      const featureIdVertexAttribute = ModelExperimentalUtility.getAttributeBySemantic(
        primitive,
        VertexAttributeSemantic$1.FEATURE_ID
      );
      if (defined(featureIdVertexAttribute)) {
        featureIdVertexAttribute.setIndex = 0;
        const featureIdAttribute = new FeatureIdAttribute$2();
        featureIdAttribute.propertyTableId = 0;
        featureIdAttribute.setIndex = 0;
        featureIdAttribute.positionalLabel = "featureId_0";
        primitive.featureIds.push(featureIdAttribute);
      }
    }
  }

  B3dmLoader.prototype.unload = function () {
    if (defined(this._gltfLoader)) {
      this._gltfLoader.unload();
    }

    this._components = undefined;
  };

  /**
   * Loads a GeoJson model as part of the <code>MAXAR_content_geojson</code> extension with the following constraints:
   * <ul>
   *   <li>The top level GeoJSON type must be FeatureCollection or Feature.</li>
   *   <li>The geometry types must be LineString, MultiLineString, MultiPolygon, or Polygon.</li>
   *   <li>All geometries are converted to geodesic lines.</li>
   *   <li>Only WGS84 geographic coordinates are supported.</li>
   * </ul>
   * <p>
   * Implements the {@link ResourceLoader} interface.
   * </p>
   *
   * @alias GeoJsonLoader
   * @constructor
   * @augments ResourceLoader
   * @private
   *
   * @param {Object} options Object with the following properties:
   * @param {Object} options.geoJson The GeoJson object.
   */
  function GeoJsonLoader(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.geoJson", options.geoJson);
    //>>includeEnd('debug');

    this._geoJson = options.geoJson;
    this._promise = undefined;
    this._process = function (loader, frameState) {};
    this._components = undefined;
  }

  if (defined(Object.create)) {
    GeoJsonLoader.prototype = Object.create(ResourceLoader.prototype);
    GeoJsonLoader.prototype.constructor = GeoJsonLoader;
  }

  Object.defineProperties(GeoJsonLoader.prototype, {
    /**
     * A promise that resolves to the resource when the resource is ready, or undefined if the resource has not yet started loading.
     *
     * @memberof GeoJsonLoader.prototype
     *
     * @type {Promise.<GeoJsonLoader>|Undefined}
     * @readonly
     * @private
     */
    promise: {
      get: function () {
        return this._promise;
      },
    },
    /**
     * The cache key of the resource.
     *
     * @memberof GeoJsonLoader.prototype
     *
     * @type {String}
     * @readonly
     * @private
     */
    cacheKey: {
      get: function () {
        return undefined;
      },
    },
    /**
     * The loaded components.
     *
     * @memberof GeoJsonLoader.prototype
     *
     * @type {ModelComponents.Components}
     * @readonly
     * @private
     */
    components: {
      get: function () {
        return this._components;
      },
    },
  });

  /**
   * Loads the resource.
   * @returns {Promise.<GeoJsonLoader>} A promise which resolves to the loader when the resource loading is completed.
   * @private
   */
  GeoJsonLoader.prototype.load = function () {
    const loader = this;
    const promise = new Promise(function (resolve) {
      loader._process = function (loader, frameState) {
        if (defined(loader._components)) {
          return;
        }

        loader._components = parse(loader._geoJson, frameState);
        loader._geoJson = undefined;
        resolve(loader);
      };
    });

    this._promise = promise;
    return promise;
  };

  /**
   * Processes the resource until it becomes ready.
   *
   * @param {FrameState} frameState The frame state.
   * @private
   */
  GeoJsonLoader.prototype.process = function (frameState) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("frameState", frameState);
    //>>includeEnd('debug');

    this._process(this, frameState);
  };

  function ParsedFeature() {
    this.lines = undefined;
    this.properties = undefined;
  }

  function ParseResult() {
    this.features = [];
  }

  function parsePosition(position) {
    const x = position[0];
    const y = position[1];
    const z = defaultValue(position[2], 0.0);
    return new Cartesian3(x, y, z);
  }

  function parseLineString(coordinates) {
    const positionsLength = coordinates.length;
    const line = new Array(positionsLength);
    for (let i = 0; i < positionsLength; i++) {
      line[i] = parsePosition(coordinates[i]);
    }
    const lines = [line];
    return lines;
  }

  function parseMultiLineString(coordinates) {
    const linesLength = coordinates.length;
    const lines = new Array(linesLength);
    for (let i = 0; i < linesLength; i++) {
      lines[i] = parseLineString(coordinates[i])[0];
    }
    return lines;
  }

  function parsePolygon(coordinates) {
    // Treat exterior polygon and interior polygons as lines
    const linesLength = coordinates.length;
    const lines = new Array(linesLength);
    for (let i = 0; i < linesLength; i++) {
      lines[i] = parseLineString(coordinates[i])[0];
    }
    return lines;
  }

  function parseMultiPolygon(coordinates) {
    const polygonsLength = coordinates.length;
    const lines = [];
    for (let i = 0; i < polygonsLength; i++) {
      Array.prototype.push.apply(lines, parsePolygon(coordinates[i]));
    }
    return lines;
  }

  const geometryTypes$2 = {
    LineString: parseLineString,
    MultiLineString: parseMultiLineString,
    MultiPolygon: parseMultiPolygon,
    Polygon: parsePolygon,
  };

  function parseFeature(feature, result) {
    if (!defined(feature.geometry)) {
      return;
    }

    const geometryType = feature.geometry.type;
    const geometryFunction = geometryTypes$2[geometryType];
    const coordinates = feature.geometry.coordinates;

    if (!defined(geometryFunction)) {
      return;
    }

    if (!defined(coordinates)) {
      return;
    }

    const parsedFeature = new ParsedFeature();
    parsedFeature.lines = geometryFunction(coordinates);
    parsedFeature.properties = feature.properties;

    result.features.push(parsedFeature);
  }

  function parseFeatureCollection(featureCollection, result) {
    const features = featureCollection.features;
    const featuresLength = features.length;
    for (let i = 0; i < featuresLength; i++) {
      parseFeature(features[i], result);
    }
  }

  const geoJsonObjectTypes$1 = {
    FeatureCollection: parseFeatureCollection,
    Feature: parseFeature,
  };

  const scratchCartesian$7 = new Cartesian3();

  function parse(geoJson, frameState) {
    const result = new ParseResult();

    // Parse the GeoJSON
    const parseFunction = geoJsonObjectTypes$1[geoJson.type];
    if (defined(parseFunction)) {
      parseFunction(geoJson, result);
    }

    const featureCount = result.features.length;

    if (featureCount === 0) {
      throw new RuntimeError("GeoJSON must have at least one feature");
    }

    // Allocate space for property values
    const properties = {};
    for (let i = 0; i < featureCount; i++) {
      const feature = result.features[i];
      const featureProperties = defaultValue(
        feature.properties,
        defaultValue.EMPTY_OBJECT
      );
      for (const propertyId in featureProperties) {
        if (featureProperties.hasOwnProperty(propertyId)) {
          if (!defined(properties[propertyId])) {
            properties[propertyId] = new Array(featureCount);
          }
        }
      }
    }

    // Fill in the property values. Default to empty string for undefined values.
    for (let i = 0; i < featureCount; i++) {
      const feature = result.features[i];
      for (const propertyId in properties) {
        if (properties.hasOwnProperty(propertyId)) {
          const value = defaultValue(feature.properties[propertyId], "");
          properties[propertyId][i] = value;
        }
      }
    }

    const jsonMetadataTable = new JsonMetadataTable({
      count: featureCount,
      properties: properties,
    });

    const propertyTable = new PropertyTable({
      id: 0,
      count: featureCount,
      jsonMetadataTable: jsonMetadataTable,
    });
    const propertyTables = [propertyTable];

    const schema = new MetadataSchema({});

    const structuralMetadata = new StructuralMetadata({
      schema: schema,
      propertyTables: propertyTables,
    });

    // Find the cartographic bounding box
    const cartographicMin = new Cartesian3(
      Number.POSITIVE_INFINITY,
      Number.POSITIVE_INFINITY,
      Number.POSITIVE_INFINITY
    );

    const cartographicMax = new Cartesian3(
      Number.NEGATIVE_INFINITY,
      Number.NEGATIVE_INFINITY,
      Number.NEGATIVE_INFINITY
    );

    for (let i = 0; i < featureCount; i++) {
      const feature = result.features[i];
      const linesLength = feature.lines.length;
      for (let j = 0; j < linesLength; j++) {
        const line = feature.lines[j];
        const positionsLength = line.length;
        for (let k = 0; k < positionsLength; k++) {
          Cartesian3.minimumByComponent(
            cartographicMin,
            line[k],
            cartographicMin
          );
          Cartesian3.maximumByComponent(
            cartographicMax,
            line[k],
            cartographicMax
          );
        }
      }
    }

    // Compute the ENU matrix
    const cartographicCenter = Cartesian3.midpoint(
      cartographicMin,
      cartographicMax,
      new Cartesian3()
    );
    const ecefCenter = Cartesian3.fromDegrees(
      cartographicCenter.x,
      cartographicCenter.y,
      cartographicCenter.z,
      Ellipsoid.WGS84,
      new Cartesian3()
    );
    const toGlobal = Transforms.eastNorthUpToFixedFrame(
      ecefCenter,
      Ellipsoid.WGS84,
      new Matrix4()
    );
    const toLocal = Matrix4.inverseTransformation(toGlobal, new Matrix4());

    // Count the number of vertices and indices
    let vertexCount = 0;
    let indexCount = 0;

    for (let i = 0; i < featureCount; i++) {
      const feature = result.features[i];
      const linesLength = feature.lines.length;
      for (let j = 0; j < linesLength; j++) {
        const line = feature.lines[j];
        vertexCount += line.length;
        indexCount += (line.length - 1) * 2;
      }
    }

    // Allocate typed arrays
    const positionsTypedArray = new Float32Array(vertexCount * 3);
    const featureIdsTypedArray = new Float32Array(vertexCount);
    const indicesTypedArray = IndexDatatype$1.createTypedArray(
      vertexCount,
      indexCount
    );
    const indexDatatype = IndexDatatype$1.fromTypedArray(indicesTypedArray);

    // Process the data. Convert positions to local ENU. Generate indices.
    const localMin = new Cartesian3(
      Number.POSITIVE_INFINITY,
      Number.POSITIVE_INFINITY,
      Number.POSITIVE_INFINITY
    );

    const localMax = new Cartesian3(
      Number.NEGATIVE_INFINITY,
      Number.NEGATIVE_INFINITY,
      Number.NEGATIVE_INFINITY
    );

    let vertexCounter = 0;
    let segmentCounter = 0;

    for (let i = 0; i < featureCount; i++) {
      const feature = result.features[i];
      const linesLength = feature.lines.length;
      for (let j = 0; j < linesLength; j++) {
        const line = feature.lines[j];
        const positionsLength = line.length;
        for (let k = 0; k < positionsLength; k++) {
          const cartographic = line[k];
          const globalCartesian = Cartesian3.fromDegrees(
            cartographic.x,
            cartographic.y,
            cartographic.z,
            Ellipsoid.WGS84,
            scratchCartesian$7
          );
          const localCartesian = Matrix4.multiplyByPoint(
            toLocal,
            globalCartesian,
            scratchCartesian$7
          );

          Cartesian3.minimumByComponent(localMin, localCartesian, localMin);
          Cartesian3.maximumByComponent(localMax, localCartesian, localMax);

          Cartesian3.pack(localCartesian, positionsTypedArray, vertexCounter * 3);

          featureIdsTypedArray[vertexCounter] = i;

          if (k < positionsLength - 1) {
            indicesTypedArray[segmentCounter * 2] = vertexCounter;
            indicesTypedArray[segmentCounter * 2 + 1] = vertexCounter + 1;
            segmentCounter++;
          }

          vertexCounter++;
        }
      }
    }

    // Create GPU buffers
    const positionBuffer = Buffer$1.createVertexBuffer({
      typedArray: positionsTypedArray,
      context: frameState.context,
      usage: BufferUsage$1.STATIC_DRAW,
    });
    positionBuffer.vertexArrayDestroyable = false;

    const featureIdBuffer = Buffer$1.createVertexBuffer({
      typedArray: featureIdsTypedArray,
      context: frameState.context,
      usage: BufferUsage$1.STATIC_DRAW,
    });
    featureIdBuffer.vertexArrayDestroyable = false;

    const indexBuffer = Buffer$1.createIndexBuffer({
      typedArray: indicesTypedArray,
      context: frameState.context,
      usage: BufferUsage$1.STATIC_DRAW,
      indexDatatype: indexDatatype,
    });
    indexBuffer.vertexArrayDestroyable = false;

    // Create ModelComponents
    const positionAttribute = new ModelComponents.Attribute();
    positionAttribute.semantic = VertexAttributeSemantic$1.POSITION;
    positionAttribute.componentDatatype = ComponentDatatype$1.FLOAT;
    positionAttribute.type = AttributeType$1.VEC3;
    positionAttribute.count = vertexCount;
    positionAttribute.min = localMin;
    positionAttribute.max = localMax;
    positionAttribute.buffer = positionBuffer;

    const featureIdAttribute = new ModelComponents.Attribute();
    featureIdAttribute.semantic = VertexAttributeSemantic$1.FEATURE_ID;
    featureIdAttribute.setIndex = 0;
    featureIdAttribute.componentDatatype = ComponentDatatype$1.FLOAT;
    featureIdAttribute.type = AttributeType$1.SCALAR;
    featureIdAttribute.count = vertexCount;
    featureIdAttribute.buffer = featureIdBuffer;

    const attributes = [positionAttribute, featureIdAttribute];

    const material = new ModelComponents.Material();
    material.unlit = true;

    const indices = new ModelComponents.Indices();
    indices.indexDatatype = indexDatatype;
    indices.count = indicesTypedArray.length;
    indices.buffer = indexBuffer;

    const featureId = new ModelComponents.FeatureIdAttribute();
    featureId.featureCount = featureCount;
    featureId.propertyTableId = 0;
    featureId.setIndex = 0;
    featureId.positionalLabel = "featureId_0";

    const featureIds = [featureId];

    const primitive = new ModelComponents.Primitive();
    primitive.attributes = attributes;
    primitive.indices = indices;
    primitive.featureIds = featureIds;
    primitive.primitiveType = PrimitiveType$1.LINES;
    primitive.material = material;

    const primitives = [primitive];

    const node = new ModelComponents.Node();
    node.index = 0;
    node.primitives = primitives;

    const nodes = [node];

    const scene = new ModelComponents.Scene();
    scene.nodes = nodes;

    const components = new ModelComponents.Components();
    components.scene = scene;
    components.nodes = nodes;
    components.transform = toGlobal;
    components.structuralMetadata = structuralMetadata;

    return components;
  }

  /**
   * Unloads the resource.
   * @private
   */
  GeoJsonLoader.prototype.unload = function () {
    this._components = undefined;
  };

  const I3dmLoaderState = {
    UNLOADED: 0,
    LOADING: 1,
    PROCESSING: 2,
    READY: 3,
    FAILED: 4,
  };

  const Attribute$1 = ModelComponents.Attribute;
  const FeatureIdAttribute$1 = ModelComponents.FeatureIdAttribute;
  const Instances = ModelComponents.Instances;

  /**
   * Loads an Instanced 3D Model.
   * <p>
   * Implements the {@link ResourceLoader} interface.
   * </p>
   *
   * @alias I3dmLoader
   * @constructor
   * @augments ResourceLoader
   * @private
   *
   * @param {Object} options Object with the following properties:
   * @param {Resource} options.i3dmResource The {@link Resource} containing the i3dm.
   * @param {ArrayBuffer} options.arrayBuffer The array buffer of the i3dm contents.
   * @param {Number} [options.byteOffset=0] The byte offset to the beginning of the i3dm contents in the array buffer.
   * @param {Resource} [options.baseResource] The {@link Resource} that paths in the glTF JSON are relative to.
   * @param {Boolean} [options.releaseGltfJson=false] When true, the glTF JSON is released once the glTF is loaded. This is is especially useful for cases like 3D Tiles, where each .gltf model is unique and caching the glTF JSON is not effective.
   * @param {Boolean} [options.asynchronous=true] Determines if WebGL resource creation will be spread out over several frames or block until all WebGL resources are created.
   * @param {Boolean} [options.incrementallyLoadTextures=true] Determine if textures may continue to stream in after the glTF is loaded.
   * @param {Axis} [options.upAxis=Axis.Y] The up-axis of the glTF model.
   * @param {Axis} [options.forwardAxis=Axis.X] The forward-axis of the glTF model.
   * @param {Boolean} [options.loadAttributesAsTypedArray=false] Load all attributes as typed arrays instead of GPU buffers.
   * @param {Boolean} [options.loadIndicesForWireframe=false] Load the index buffer as a typed array so wireframe indices can be created for WebGL1.
   */
  function I3dmLoader(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const i3dmResource = options.i3dmResource;
    const arrayBuffer = options.arrayBuffer;
    let baseResource = options.baseResource;
    const byteOffset = defaultValue(options.byteOffset, 0);
    const releaseGltfJson = defaultValue(options.releaseGltfJson, false);
    const asynchronous = defaultValue(options.asynchronous, true);
    const incrementallyLoadTextures = defaultValue(
      options.incrementallyLoadTextures,
      true
    );
    const upAxis = defaultValue(options.upAxis, Axis$1.Y);
    const forwardAxis = defaultValue(options.forwardAxis, Axis$1.X);
    const loadAttributesAsTypedArray = defaultValue(
      options.loadAttributesAsTypedArray,
      false
    );
    const loadIndicesForWireframe = defaultValue(
      options.loadIndicesForWireframe,
      false
    );

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.i3dmResource", i3dmResource);
    Check.typeOf.object("options.arrayBuffer", arrayBuffer);
    //>>includeEnd('debug');

    baseResource = defined(baseResource) ? baseResource : i3dmResource.clone();

    this._i3dmResource = i3dmResource;
    this._baseResource = baseResource;
    this._arrayBuffer = arrayBuffer;
    this._byteOffset = byteOffset;
    this._releaseGltfJson = releaseGltfJson;
    this._asynchronous = asynchronous;
    this._incrementallyLoadTextures = incrementallyLoadTextures;
    this._upAxis = upAxis;
    this._forwardAxis = forwardAxis;
    this._loadAttributesAsTypedArray = loadAttributesAsTypedArray;
    this._loadIndicesForWireframe = loadIndicesForWireframe;

    this._state = I3dmLoaderState.UNLOADED;
    this._promise = undefined;

    this._gltfLoader = undefined;

    this._transform = Matrix4.IDENTITY;
    this._batchTable = undefined;
    this._featureTable = undefined;
    this._instancesLength = 0;
  }

  if (defined(Object.create)) {
    I3dmLoader.prototype = Object.create(ResourceLoader.prototype);
    I3dmLoader.prototype.constructor = I3dmLoader;
  }

  Object.defineProperties(I3dmLoader.prototype, {
    /**
     * A promise that resolves to the resource when the resource is ready, or undefined if the resource hasn't started loading.
     *
     * @memberof I3dmLoader.prototype
     *
     * @type {Promise.<I3dmLoader>|undefined}
     * @readonly
     * @private
     */
    promise: {
      get: function () {
        return this._promise;
      },
    },

    /**
     * A promise that resolves when all textures are loaded.
     * When <code>incrementallyLoadTextures</code> is true this may resolve after
     * <code>promise</code> resolves.
     *
     * @memberof I3dmLoader.prototype
     *
     * @type {Promise}
     * @readonly
     * @private
     */
    texturesLoadedPromise: {
      get: function () {
        return this._gltfLoader.texturesLoadedPromise;
      },
    },
    /**
     * The cache key of the resource
     *
     * @memberof I3dmLoader.prototype
     *
     * @type {String}
     * @readonly
     * @private
     */
    cacheKey: {
      get: function () {
        return undefined;
      },
    },

    /**
     * The loaded components.
     *
     * @memberof I3dmLoader.prototype
     *
     * @type {ModelComponents.Components}
     * @default {@link Matrix4.IDENTITY}
     * @readonly
     * @private
     */
    components: {
      get: function () {
        return this._components;
      },
    },
  });

  /**
   * Loads the resource.
   * @returns {Promise.<I3dmLoader>} A promise which resolves to the loader when the resource loading is completed.
   * @private
   */
  I3dmLoader.prototype.load = function () {
    // Parse the i3dm into its various sections.
    const i3dm = I3dmParser.parse(this._arrayBuffer, this._byteOffset);

    const featureTableJson = i3dm.featureTableJson;
    const featureTableBinary = i3dm.featureTableBinary;
    const batchTableJson = i3dm.batchTableJson;
    const batchTableBinary = i3dm.batchTableBinary;
    const gltfFormat = i3dm.gltfFormat;

    // Generate the feature table.
    const featureTable = new Cesium3DTileFeatureTable(
      featureTableJson,
      featureTableBinary
    );
    this._featureTable = featureTable;

    // Get the number of instances in the i3dm.
    const instancesLength = featureTable.getGlobalProperty("INSTANCES_LENGTH");
    featureTable.featuresLength = instancesLength;
    if (!defined(instancesLength)) {
      throw new RuntimeError(
        "Feature table global property: INSTANCES_LENGTH must be defined"
      );
    }
    this._instancesLength = instancesLength;

    // Get the RTC center, if available, and set the loader's transform.
    const rtcCenter = featureTable.getGlobalProperty(
      "RTC_CENTER",
      ComponentDatatype$1.FLOAT,
      3
    );
    if (defined(rtcCenter)) {
      this._transform = Matrix4.fromTranslation(Cartesian3.fromArray(rtcCenter));
    }

    // Save the batch table section to use for StructuralMetadata generation.
    this._batchTable = {
      json: batchTableJson,
      binary: batchTableBinary,
    };

    const loaderOptions = {
      upAxis: this._upAxis,
      forwardAxis: this._forwardAxis,
      releaseGltfJson: this._releaseGltfJson,
      incrementallyLoadTextures: this._incrementallyLoadTextures,
      loadAttributesAsTypedArray: this._loadAttributesAsTypedArray,
      loadIndicesForWireframe: this._loadIndicesForWireframe,
    };

    if (gltfFormat === 0) {
      let gltfUrl = getStringFromTypedArray(i3dm.gltf);

      // We need to remove padding from the end of the model URL in case this tile was part of a composite tile.
      // This removes all white space and null characters from the end of the string.
      gltfUrl = gltfUrl.replace(/[\s\0]+$/, "");
      const gltfResource = this._baseResource.getDerivedResource({
        url: gltfUrl,
      });
      loaderOptions.gltfResource = gltfResource;
      loaderOptions.baseResource = gltfResource;
    } else {
      loaderOptions.gltfResource = this._i3dmResource;
      loaderOptions.typedArray = i3dm.gltf;
    }

    // Create the GltfLoader, update the state and load the glTF.
    const gltfLoader = new GltfLoader(loaderOptions);

    this._gltfLoader = gltfLoader;
    this._state = I3dmLoaderState.LOADING;

    const that = this;
    gltfLoader.load();
    this._promise = gltfLoader.promise
      .then(function () {
        if (that.isDestroyed()) {
          return;
        }

        const components = gltfLoader.components;
        components.transform = that._transform;
        createInstances(that, components);
        createStructuralMetadata(that, components);
        that._components = components;

        that._state = I3dmLoaderState.READY;
        return that;
      })
      .catch(function (error) {
        if (that.isDestroyed()) {
          return;
        }
        return handleError(that, error);
      });

    return this._promise;
  };

  function handleError(i3dmLoader, error) {
    i3dmLoader.unload();
    i3dmLoader._state = I3dmLoaderState.FAILED;
    const errorMessage = "Failed to load i3dm";
    error = i3dmLoader.getError(errorMessage, error);
    return Promise.reject(error);
  }

  I3dmLoader.prototype.process = function (frameState) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("frameState", frameState);
    //>>includeEnd('debug');

    if (this._state === I3dmLoaderState.LOADING) {
      this._state = I3dmLoaderState.PROCESSING;
    }

    if (this._state === I3dmLoaderState.PROCESSING) {
      this._gltfLoader.process(frameState);
    }
  };

  function createStructuralMetadata(loader, components) {
    const batchTable = loader._batchTable;
    const instancesLength = loader._instancesLength;

    if (instancesLength === 0) {
      return;
    }

    let structuralMetadata;
    if (defined(batchTable.json)) {
      // Add the structural metadata from the batch table to the model components.
      structuralMetadata = parseBatchTable({
        count: instancesLength,
        batchTable: batchTable.json,
        binaryBody: batchTable.binary,
      });
    } else {
      // If batch table is not defined, create a property table without any properties.
      const emptyPropertyTable = new PropertyTable({
        name: MetadataClass.BATCH_TABLE_CLASS_NAME,
        count: instancesLength,
      });
      structuralMetadata = new StructuralMetadata({
        schema: {},
        propertyTables: [emptyPropertyTable],
      });
    }

    components.structuralMetadata = structuralMetadata;
  }

  const positionScratch$5 = new Cartesian3();
  const propertyScratch1 = new Array(4);
  function createInstances(loader, components) {
    let i;
    const featureTable = loader._featureTable;
    const instancesLength = loader._instancesLength;

    if (instancesLength === 0) {
      return;
    }

    const rtcCenter = featureTable.getGlobalProperty(
      "RTC_CENTER",
      ComponentDatatype$1.FLOAT,
      3
    );

    const eastNorthUp = featureTable.getGlobalProperty("EAST_NORTH_UP");
    const hasRotation =
      featureTable.hasProperty("NORMAL_UP") ||
      featureTable.hasProperty("NORMAL_UP_OCT32P") ||
      eastNorthUp;

    const hasScale =
      featureTable.hasProperty("SCALE") ||
      featureTable.hasProperty("SCALE_NON_UNIFORM");

    const translationTypedArray = getPositions(featureTable);
    let rotationTypedArray;
    if (hasRotation) {
      rotationTypedArray = new Float32Array(4 * instancesLength);
    }
    let scaleTypedArray;
    if (hasScale) {
      scaleTypedArray = new Float32Array(3 * instancesLength);
    }
    const featureIdArray = new Float32Array(instancesLength);

    const instancePositions = Cartesian3.unpackArray(translationTypedArray);
    let instancePosition = new Cartesian3();

    const instanceNormalRight = new Cartesian3();
    const instanceNormalUp = new Cartesian3();
    const instanceNormalForward = new Cartesian3();
    const instanceRotation = new Matrix3();
    const instanceQuaternion = new Quaternion();
    const instanceQuaternionArray = new Array(4);

    const instanceScale = new Cartesian3();
    const instanceScaleArray = new Array(3);

    const instanceTransform = new Matrix4();

    // For I3DMs that do not define an RTC center, we manually compute a BoundingSphere and store
    // positions relative to the center, to be uploaded to the GPU. This avoids jittering at higher
    // precisions.
    if (!defined(rtcCenter)) {
      const positionBoundingSphere = BoundingSphere.fromPoints(instancePositions);

      for (i = 0; i < instancePositions.length; i++) {
        Cartesian3.subtract(
          instancePositions[i],
          positionBoundingSphere.center,
          positionScratch$5
        );

        translationTypedArray[3 * i + 0] = positionScratch$5.x;
        translationTypedArray[3 * i + 1] = positionScratch$5.y;
        translationTypedArray[3 * i + 2] = positionScratch$5.z;
      }

      // Set the center of the bounding sphere as the RTC center transform.
      components.transform = Matrix4.fromTranslation(
        positionBoundingSphere.center
      );
    }

    for (i = 0; i < instancesLength; i++) {
      // Get the instance position
      instancePosition = Cartesian3.clone(instancePositions[i]);

      if (defined(rtcCenter)) {
        Cartesian3.add(
          instancePosition,
          Cartesian3.unpack(rtcCenter),
          instancePosition
        );
      }

      // Get the instance rotation, if present
      if (hasRotation) {
        processRotation(
          featureTable,
          eastNorthUp,
          i,
          instanceQuaternion,
          instancePosition,
          instanceNormalUp,
          instanceNormalRight,
          instanceNormalForward,
          instanceRotation,
          instanceTransform
        );
        Quaternion.pack(instanceQuaternion, instanceQuaternionArray, 0);
        rotationTypedArray[4 * i + 0] = instanceQuaternionArray[0];
        rotationTypedArray[4 * i + 1] = instanceQuaternionArray[1];
        rotationTypedArray[4 * i + 2] = instanceQuaternionArray[2];
        rotationTypedArray[4 * i + 3] = instanceQuaternionArray[3];
      }

      // Get the instance scale, if present
      if (hasScale) {
        processScale(featureTable, i, instanceScale);
        Cartesian3.pack(instanceScale, instanceScaleArray, 0);
        scaleTypedArray[3 * i + 0] = instanceScaleArray[0];
        scaleTypedArray[3 * i + 1] = instanceScaleArray[1];
        scaleTypedArray[3 * i + 2] = instanceScaleArray[2];
      }

      // Get the batchId
      let batchId = featureTable.getProperty(
        "BATCH_ID",
        ComponentDatatype$1.UNSIGNED_SHORT,
        1,
        i
      );
      if (!defined(batchId)) {
        // If BATCH_ID semantic is undefined, batchId is just the instance number
        batchId = i;
      }
      featureIdArray[i] = batchId;
    }

    // Create instances.
    const instances = new Instances();
    instances.transformInWorldSpace = true;

    // Create translation vertex attribute.
    const translationAttribute = new Attribute$1();
    translationAttribute.name = "Instance Translation";
    translationAttribute.semantic = InstanceAttributeSemantic$1.TRANSLATION;
    translationAttribute.componentDatatype = ComponentDatatype$1.FLOAT;
    translationAttribute.type = AttributeType$1.VEC3;
    translationAttribute.count = instancesLength;
    translationAttribute.packedTypedArray = translationTypedArray;
    instances.attributes.push(translationAttribute);

    // Create rotation vertex attribute.
    if (hasRotation) {
      const rotationAttribute = new Attribute$1();
      rotationAttribute.name = "Instance Rotation";
      rotationAttribute.semantic = InstanceAttributeSemantic$1.ROTATION;
      rotationAttribute.componentDatatype = ComponentDatatype$1.FLOAT;
      rotationAttribute.type = AttributeType$1.VEC4;
      rotationAttribute.count = instancesLength;
      rotationAttribute.packedTypedArray = rotationTypedArray;
      instances.attributes.push(rotationAttribute);
    }

    // Create scale vertex attribute.
    if (hasScale) {
      const scaleAttribute = new Attribute$1();
      scaleAttribute.name = "Instance Scale";
      scaleAttribute.semantic = InstanceAttributeSemantic$1.SCALE;
      scaleAttribute.componentDatatype = ComponentDatatype$1.FLOAT;
      scaleAttribute.type = AttributeType$1.VEC3;
      scaleAttribute.count = instancesLength;
      scaleAttribute.packedTypedArray = scaleTypedArray;
      instances.attributes.push(scaleAttribute);
    }

    // Create feature ID vertex attribute.
    const featureIdAttribute = new Attribute$1();
    featureIdAttribute.name = "Instance Feature ID";
    featureIdAttribute.setIndex = 0;
    featureIdAttribute.semantic = InstanceAttributeSemantic$1.FEATURE_ID;
    featureIdAttribute.componentDatatype = ComponentDatatype$1.FLOAT;
    featureIdAttribute.type = AttributeType$1.SCALAR;
    featureIdAttribute.count = instancesLength;
    featureIdAttribute.packedTypedArray = featureIdArray;
    instances.attributes.push(featureIdAttribute);

    // Create feature ID attribute.
    const featureIdInstanceAttribute = new FeatureIdAttribute$1();
    featureIdInstanceAttribute.propertyTableId = 0;
    featureIdInstanceAttribute.setIndex = 0;
    featureIdInstanceAttribute.positionalLabel = "instanceFeatureId_0";
    instances.featureIds.push(featureIdInstanceAttribute);

    // Apply instancing to every node that has at least one primitive.
    for (i = 0; i < components.nodes.length; i++) {
      const node = components.nodes[i];
      if (node.primitives.length > 0) {
        node.instances = instances;
      }
    }
  }

  /**
   * Returns a typed array of positions from the i3dm's feature table. The positions
   * returned are dequantized, if dequantization is applied.
   *
   * @private
   */
  function getPositions(featureTable, instancesLength) {
    if (featureTable.hasProperty("POSITION")) {
      // Handle positions.
      return featureTable.getPropertyArray(
        "POSITION",
        ComponentDatatype$1.FLOAT,
        3
      );
    } else if (featureTable.hasProperty("POSITION_QUANTIZED")) {
      // Handle quantized positions.
      const quantizedPositions = featureTable.getPropertyArray(
        "POSITION_QUANTIZED",
        ComponentDatatype$1.UNSIGNED_SHORT,
        3
      );

      const quantizedVolumeOffset = featureTable.getGlobalProperty(
        "QUANTIZED_VOLUME_OFFSET",
        ComponentDatatype$1.FLOAT,
        3
      );
      if (!defined(quantizedVolumeOffset)) {
        throw new RuntimeError(
          "Global property: QUANTIZED_VOLUME_OFFSET must be defined for quantized positions."
        );
      }

      const quantizedVolumeScale = featureTable.getGlobalProperty(
        "QUANTIZED_VOLUME_SCALE",
        ComponentDatatype$1.FLOAT,
        3
      );
      if (!defined(quantizedVolumeScale)) {
        throw new RuntimeError(
          "Global property: QUANTIZED_VOLUME_SCALE must be defined for quantized positions."
        );
      }

      for (let i = 0; i < quantizedPositions.length / 3; i++) {
        const quantizedPosition = quantizedPositions[i];
        for (let j = 0; j < 3; j++) {
          quantizedPositions[3 * i + j] =
            (quantizedPosition[j] / 65535.0) * quantizedVolumeScale[j] +
            quantizedVolumeOffset[j];
        }
      }

      return quantizedPositions;

      // eslint-disable-next-line no-else-return
    } else {
      throw new RuntimeError(
        "Either POSITION or POSITION_QUANTIZED must be defined for each instance."
      );
    }
  }

  const propertyScratch2 = new Array(4);
  function processRotation(
    featureTable,
    eastNorthUp,
    i,
    instanceQuaternion,
    instancePosition,
    instanceNormalUp,
    instanceNormalRight,
    instanceNormalForward,
    instanceRotation,
    instanceTransform
  ) {
    // Get the instance rotation
    const normalUp = featureTable.getProperty(
      "NORMAL_UP",
      ComponentDatatype$1.FLOAT,
      3,
      i,
      propertyScratch1
    );
    const normalRight = featureTable.getProperty(
      "NORMAL_RIGHT",
      ComponentDatatype$1.FLOAT,
      3,
      i,
      propertyScratch2
    );
    let hasCustomOrientation = false;
    if (defined(normalUp)) {
      if (!defined(normalRight)) {
        throw new RuntimeError(
          "To define a custom orientation, both NORMAL_UP and NORMAL_RIGHT must be defined."
        );
      }
      Cartesian3.unpack(normalUp, 0, instanceNormalUp);
      Cartesian3.unpack(normalRight, 0, instanceNormalRight);
      hasCustomOrientation = true;
    } else {
      const octNormalUp = featureTable.getProperty(
        "NORMAL_UP_OCT32P",
        ComponentDatatype$1.UNSIGNED_SHORT,
        2,
        i,
        propertyScratch1
      );
      const octNormalRight = featureTable.getProperty(
        "NORMAL_RIGHT_OCT32P",
        ComponentDatatype$1.UNSIGNED_SHORT,
        2,
        i,
        propertyScratch2
      );
      if (defined(octNormalUp)) {
        if (!defined(octNormalRight)) {
          throw new RuntimeError(
            "To define a custom orientation with oct-encoded vectors, both NORMAL_UP_OCT32P and NORMAL_RIGHT_OCT32P must be defined."
          );
        }
        AttributeCompression.octDecodeInRange(
          octNormalUp[0],
          octNormalUp[1],
          65535,
          instanceNormalUp
        );
        AttributeCompression.octDecodeInRange(
          octNormalRight[0],
          octNormalRight[1],
          65535,
          instanceNormalRight
        );
        hasCustomOrientation = true;
      } else if (eastNorthUp) {
        Transforms.eastNorthUpToFixedFrame(
          instancePosition,
          Ellipsoid.WGS84,
          instanceTransform
        );
        Matrix4.getMatrix3(instanceTransform, instanceRotation);
      } else {
        Matrix3.clone(Matrix3.IDENTITY, instanceRotation);
      }
    }
    if (hasCustomOrientation) {
      Cartesian3.cross(
        instanceNormalRight,
        instanceNormalUp,
        instanceNormalForward
      );
      Cartesian3.normalize(instanceNormalForward, instanceNormalForward);
      Matrix3.setColumn(
        instanceRotation,
        0,
        instanceNormalRight,
        instanceRotation
      );
      Matrix3.setColumn(instanceRotation, 1, instanceNormalUp, instanceRotation);
      Matrix3.setColumn(
        instanceRotation,
        2,
        instanceNormalForward,
        instanceRotation
      );
    }
    Quaternion.fromRotationMatrix(instanceRotation, instanceQuaternion);
  }

  function processScale(featureTable, i, instanceScale) {
    instanceScale = Cartesian3.fromElements(1.0, 1.0, 1.0, instanceScale);
    const scale = featureTable.getProperty(
      "SCALE",
      ComponentDatatype$1.FLOAT,
      1,
      i
    );
    if (defined(scale)) {
      Cartesian3.multiplyByScalar(instanceScale, scale, instanceScale);
    }
    const nonUniformScale = featureTable.getProperty(
      "SCALE_NON_UNIFORM",
      ComponentDatatype$1.FLOAT,
      3,
      i,
      propertyScratch1
    );
    if (defined(nonUniformScale)) {
      instanceScale.x *= nonUniformScale[0];
      instanceScale.y *= nonUniformScale[1];
      instanceScale.z *= nonUniformScale[2];
    }
  }

  I3dmLoader.prototype.unload = function () {
    if (defined(this._gltfLoader)) {
      this._gltfLoader.unload();
    }
    this._components = undefined;
  };

  const Components = ModelComponents.Components;
  const Scene$1 = ModelComponents.Scene;
  const Node$1 = ModelComponents.Node;
  const Primitive = ModelComponents.Primitive;
  const Attribute = ModelComponents.Attribute;
  const Quantization = ModelComponents.Quantization;
  const FeatureIdAttribute = ModelComponents.FeatureIdAttribute;
  const Material = ModelComponents.Material;
  const MetallicRoughness = ModelComponents.MetallicRoughness;

  /**
   * Loads a .pnts point cloud and transcodes it into a {@link ModelComponents}
   *
   * @alias PntsLoader
   * @constructor
   * @augments ResourceLoader
   * @private
   *
   * @param {Object} options An object containing the following properties
   * @param {ArrayBuffer} options.arrayBuffer The array buffer of the pnts contents
   * @param {Number} [options.byteOffset] The byte offset to the beginning of the pnts contents in the array buffer
   */
  function PntsLoader(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const arrayBuffer = options.arrayBuffer;
    const byteOffset = defaultValue(options.byteOffset, 0);

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.arrayBuffer", arrayBuffer);
    //>>includeEnd('debug');

    this._arrayBuffer = arrayBuffer;
    this._byteOffset = byteOffset;

    this._parsedContent = undefined;
    this._decodePromise = undefined;
    this._decodedAttributes = undefined;

    this._promise = undefined;
    this._process = function (frameState) {};
    this._state = ResourceLoaderState$1.UNLOADED;
    this._buffers = [];

    // The batch table object contains a json and a binary component access using keys of the same name.
    this._components = undefined;
    this._transform = Matrix4.IDENTITY;
  }

  if (defined(Object.create)) {
    PntsLoader.prototype = Object.create(ResourceLoader.prototype);
    PntsLoader.prototype.constructor = PntsLoader;
  }

  Object.defineProperties(PntsLoader.prototype, {
    /**
     * A promise that resolves to the resource when the resource is ready, or undefined if the resource hasn't started loading.
     *
     * @memberof PntsLoader.prototype
     *
     * @type {Promise.<PntsLoader>|undefined}
     * @readonly
     * @private
     */
    promise: {
      get: function () {
        return this._promise;
      },
    },
    /**
     * The cache key of the resource
     *
     * @memberof PntsLoader.prototype
     *
     * @type {String}
     * @readonly
     * @private
     */
    cacheKey: {
      get: function () {
        return undefined;
      },
    },

    /**
     * The loaded components.
     *
     * @memberof PntsLoader.prototype
     *
     * @type {ModelComponents.Components}
     * @readonly
     * @private
     */
    components: {
      get: function () {
        return this._components;
      },
    },

    /**
     * A world-space transform to apply to the primitives.
     * See {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/TileFormats/PointCloud#global-semantics}
     *
     * @memberof PntsLoader.prototype
     *
     * @type {Matrix4}
     * @readonly
     * @private
     */
    transform: {
      get: function () {
        return this._transform;
      },
    },
  });

  /**
   * Loads the resource.
   * @returns {Promise.<PntsLoader>} A promise which resolves to the loader when the resource loading is completed.
   * @private
   */
  PntsLoader.prototype.load = function () {
    this._parsedContent = PntsParser.parse(this._arrayBuffer, this._byteOffset);
    this._state = ResourceLoaderState$1.PROCESSING;

    const loader = this;
    this._promise = new Promise(function (resolve, reject) {
      loader._process = function (frameState) {
        if (loader._state === ResourceLoaderState$1.PROCESSING) {
          if (!defined(loader._decodePromise)) {
            decodeDraco(loader, frameState.context).then(resolve).catch(reject);
          }
        }
      };
    });
  };

  PntsLoader.prototype.process = function (frameState) {
    this._process(frameState);
  };

  function decodeDraco(loader, context) {
    const parsedContent = loader._parsedContent;
    const draco = parsedContent.draco;

    let decodePromise;
    if (!defined(draco)) {
      // The draco extension wasn't present,
      decodePromise = Promise.resolve();
    } else {
      decodePromise = DracoLoader.decodePointCloud(draco, context);
    }

    if (!defined(decodePromise)) {
      // Could not schedule Draco decoding this frame.
      return;
    }

    loader._decodePromise = decodePromise;
    return decodePromise
      .then(function (decodeDracoResult) {
        if (loader.isDestroyed()) {
          return;
        }

        if (defined(decodeDracoResult)) {
          processDracoAttributes(loader, draco, decodeDracoResult);
        }
        makeComponents(loader, context);
        loader._state = ResourceLoaderState$1.READY;
        return loader;
      })
      .catch(function (error) {
        loader.unload();
        loader._state = ResourceLoaderState$1.FAILED;
        const errorMessage = "Failed to load Draco";
        return Promise.reject(loader.getError(errorMessage, error));
      });
  }

  function processDracoAttributes(loader, draco, result) {
    loader._state = ResourceLoaderState$1.READY;
    const parsedContent = loader._parsedContent;

    let attribute;
    if (defined(result.POSITION)) {
      attribute = {
        name: "POSITION",
        semantic: VertexAttributeSemantic$1.POSITION,
        typedArray: result.POSITION.array,
        componentDatatype: ComponentDatatype$1.FLOAT,
        type: AttributeType$1.VEC3,
        isQuantized: false,
      };

      if (defined(result.POSITION.data.quantization)) {
        // Draco quantization range == quantized volume scale - size in meters of the quantized volume
        // Internal quantized range is the range of values of the quantized data, e.g. 255 for 8-bit, 1023 for 10-bit, etc
        const quantization = result.POSITION.data.quantization;
        const range = quantization.range;
        const quantizedVolumeScale = Cartesian3.fromElements(range, range, range);
        const quantizedVolumeOffset = Cartesian3.unpack(quantization.minValues);
        const quantizedRange = (1 << quantization.quantizationBits) - 1.0;

        attribute.isQuantized = true;
        attribute.quantizedRange = quantizedRange;
        attribute.quantizedVolumeOffset = quantizedVolumeOffset;
        attribute.quantizedVolumeScale = quantizedVolumeScale;
        attribute.quantizedComponentDatatype = ComponentDatatype$1.UNSIGNED_SHORT;
        attribute.quantizedType = AttributeType$1.VEC3;
      }

      parsedContent.positions = attribute;
    }

    if (defined(result.NORMAL)) {
      attribute = {
        name: "NORMAL",
        semantic: VertexAttributeSemantic$1.NORMAL,
        typedArray: result.NORMAL.array,
        componentDatatype: ComponentDatatype$1.FLOAT,
        type: AttributeType$1.VEC3,
        isQuantized: false,
        octEncoded: false,
        octEncodedZXY: false,
      };

      if (defined(result.NORMAL.data.quantization)) {
        const octEncodedRange =
          (1 << result.NORMAL.data.quantization.quantizationBits) - 1.0;
        attribute.quantizedRange = octEncodedRange;
        attribute.octEncoded = true;
        attribute.octEncodedZXY = true;
        attribute.quantizedComponentDatatype = ComponentDatatype$1.UNSIGNED_BYTE;
        attribute.quantizedType = AttributeType$1.VEC2;
      }

      parsedContent.normals = attribute;
    }

    if (defined(result.RGBA)) {
      parsedContent.colors = {
        name: "COLOR",
        semantic: VertexAttributeSemantic$1.COLOR,
        setIndex: 0,
        typedArray: result.RGBA.array,
        componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
        type: AttributeType$1.VEC4,
        normalized: true,
        isTranslucent: true,
      };
    } else if (defined(result.RGB)) {
      parsedContent.colors = {
        name: "COLOR",
        semantic: VertexAttributeSemantic$1.COLOR,
        setIndex: 0,
        typedArray: result.RGB.array,
        componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
        type: AttributeType$1.VEC3,
        normalized: true,
        isTranslucent: false,
      };
    }

    // Transcode Batch ID (3D Tiles 1.0) -> Feature ID (3D Tiles Next)
    if (defined(result.BATCH_ID)) {
      const batchIds = result.BATCH_ID.array;
      parsedContent.batchIds = {
        name: "_FEATURE_ID",
        semantic: VertexAttributeSemantic$1.FEATURE_ID,
        setIndex: 0,
        typedArray: batchIds,
        componentDatatype: ComponentDatatype$1.fromTypedArray(batchIds),
        type: AttributeType$1.SCALAR,
      };
    }

    let styleableProperties = parsedContent.styleableProperties;
    const batchTableProperties = draco.batchTableProperties;
    for (const name in batchTableProperties) {
      if (batchTableProperties.hasOwnProperty(name)) {
        const property = result[name];
        if (!defined(styleableProperties)) {
          styleableProperties = {};
        }
        styleableProperties[name] = {
          typedArray: property.array,
          componentCount: property.data.componentsPerAttribute,
        };
      }
    }
    parsedContent.styleableProperties = styleableProperties;
  }

  function makeAttribute(loader, attributeInfo, context) {
    let typedArray = attributeInfo.typedArray;
    let quantization;
    if (attributeInfo.octEncoded) {
      quantization = new Quantization();
      quantization.octEncoded = attributeInfo.octEncoded;
      quantization.octEncodedZXY = attributeInfo.octEncodedZXY;
      quantization.normalizationRange = attributeInfo.quantizedRange;
      quantization.type = attributeInfo.quantizedType;
      quantization.componentDatatype = attributeInfo.quantizedComponentDatatype;
    }
    if (attributeInfo.isQuantized) {
      quantization = new Quantization();
      const normalizationRange = attributeInfo.quantizedRange;
      quantization.normalizationRange = normalizationRange;
      // volume offset sometimes requires 64-bit precision so this is handled
      // in the components.transform matrix.
      quantization.quantizedVolumeOffset = Cartesian3.ZERO;
      const quantizedVolumeDimensions = attributeInfo.quantizedVolumeScale;
      quantization.quantizedVolumeDimensions = quantizedVolumeDimensions;
      quantization.quantizedVolumeStepSize = Cartesian3.divideByScalar(
        quantizedVolumeDimensions,
        normalizationRange,
        new Cartesian3()
      );
      quantization.componentDatatype = attributeInfo.quantizedComponentDatatype;
      quantization.type = attributeInfo.quantizedType;
    }

    const attribute = new Attribute();
    attribute.name = attributeInfo.name;
    attribute.semantic = attributeInfo.semantic;
    attribute.setIndex = attributeInfo.setIndex;
    attribute.componentDatatype = attributeInfo.componentDatatype;
    attribute.type = attributeInfo.type;
    attribute.normalized = defaultValue(attributeInfo.normalized, false);
    attribute.min = attributeInfo.min;
    attribute.max = attributeInfo.max;
    attribute.quantization = quantization;

    if (attributeInfo.isRGB565) {
      typedArray = AttributeCompression.decodeRGB565(typedArray);
    }

    if (defined(attributeInfo.constantColor)) {
      const packedColor = new Array(4);
      attribute.constant = Color.pack(attributeInfo.constantColor, packedColor);
    } else {
      const buffer = Buffer$1.createVertexBuffer({
        typedArray: typedArray,
        context: context,
        usage: BufferUsage$1.STATIC_DRAW,
      });
      buffer.vertexArrayDestroyable = false;
      loader._buffers.push(buffer);
      attribute.buffer = buffer;
    }

    return attribute;
  }

  let randomNumberGenerator;
  let randomValues;

  function getRandomValues$1(samplesLength) {
    // Use same random values across all runs
    if (!defined(randomValues)) {
      // Use MersenneTwister directly to avoid interfering with CesiumMath.nextRandomNumber()
      // See https://github.com/CesiumGS/cesium/issues/9730
      randomNumberGenerator = new mersenneTwister(0);
      randomValues = new Array(samplesLength);
      for (let i = 0; i < samplesLength; ++i) {
        randomValues[i] = randomNumberGenerator.random();
      }
    }
    return randomValues;
  }

  const scratchMin$1 = new Cartesian3();
  const scratchMax$1 = new Cartesian3();
  const scratchPosition$4 = new Cartesian3();
  function computeApproximateExtrema(positions) {
    const positionsArray = positions.typedArray;
    const maximumSamplesLength = 20;
    const pointsLength = positionsArray.length / 3;
    const samplesLength = Math.min(pointsLength, maximumSamplesLength);
    const randomValues = getRandomValues$1(maximumSamplesLength);
    const maxValue = Number.MAX_VALUE;
    const minValue = -Number.MAX_VALUE;
    let min = Cartesian3.fromElements(maxValue, maxValue, maxValue, scratchMin$1);
    let max = Cartesian3.fromElements(minValue, minValue, minValue, scratchMax$1);
    let i;
    let index;
    let position;
    if (positions.isQuantized) {
      // The quantized volume offset is not used here since it will become part of
      // the model matrix.
      min = Cartesian3.ZERO;
      max = positions.quantizedVolumeScale;
    } else {
      for (i = 0; i < samplesLength; ++i) {
        index = Math.floor(randomValues[i] * pointsLength);
        position = Cartesian3.unpack(positionsArray, index * 3, scratchPosition$4);

        Cartesian3.minimumByComponent(min, position, min);
        Cartesian3.maximumByComponent(max, position, max);
      }
    }

    positions.min = Cartesian3.clone(min);
    positions.max = Cartesian3.clone(max);
  }

  // By default, point clouds are rendered as dark gray.
  const defaultColorAttribute = {
    name: VertexAttributeSemantic$1.COLOR,
    semantic: VertexAttributeSemantic$1.COLOR,
    setIndex: 0,
    constantColor: Color.DARKGRAY,
    componentDatatype: ComponentDatatype$1.FLOAT,
    type: AttributeType$1.VEC4,
    isQuantized: false,
    isTranslucent: false,
  };

  function makeAttributes(loader, parsedContent, context) {
    const attributes = [];
    let attribute;
    const positions = parsedContent.positions;
    if (defined(positions)) {
      computeApproximateExtrema(positions);
      attribute = makeAttribute(loader, positions, context);
      attribute.count = parsedContent.pointsLength;
      attributes.push(attribute);
    }

    if (defined(parsedContent.normals)) {
      attribute = makeAttribute(loader, parsedContent.normals, context);
      attributes.push(attribute);
    }

    if (defined(parsedContent.colors)) {
      attribute = makeAttribute(loader, parsedContent.colors, context);
      attributes.push(attribute);
    } else {
      attribute = makeAttribute(loader, defaultColorAttribute, context);
      attributes.push(attribute);
    }

    if (defined(parsedContent.batchIds)) {
      attribute = makeAttribute(loader, parsedContent.batchIds, context);
      attributes.push(attribute);
    }

    return attributes;
  }

  function makeStructuralMetadata(parsedContent) {
    const batchLength = parsedContent.batchLength;
    const pointsLength = parsedContent.pointsLength;
    const batchTableBinary = parsedContent.batchTableBinary;

    if (defined(batchTableBinary)) {
      const count = defaultValue(batchLength, pointsLength);
      return parseBatchTable({
        count: count,
        batchTable: parsedContent.batchTableJson,
        binaryBody: batchTableBinary,
      });
    }

    // If batch table is not defined, create a property table without any properties.
    const emptyPropertyTable = new PropertyTable({
      name: MetadataClass.BATCH_TABLE_CLASS_NAME,
      count: pointsLength,
    });
    return new StructuralMetadata({
      schema: {},
      propertyTables: [emptyPropertyTable],
    });
  }

  function makeComponents(loader, context) {
    const parsedContent = loader._parsedContent;

    const metallicRoughness = new MetallicRoughness();
    metallicRoughness.metallicFactor = 0;
    metallicRoughness.roughnessFactor = 0.9;

    const material = new Material();
    material.metallicRoughness = metallicRoughness;

    const colors = parsedContent.colors;
    if (defined(colors) && colors.isTranslucent) {
      material.alphaMode = AlphaMode$1.BLEND;
    }

    // Render point clouds as unlit, unless normals are present, in which case
    // render as a PBR material.
    const isUnlit = !defined(parsedContent.normals);
    material.unlit = isUnlit;

    const primitive = new Primitive();
    primitive.attributes = makeAttributes(loader, parsedContent, context);
    primitive.primitiveType = PrimitiveType$1.POINTS;
    primitive.material = material;

    if (defined(parsedContent.batchIds)) {
      const featureIdAttribute = new FeatureIdAttribute();
      featureIdAttribute.propertyTableId = 0;
      featureIdAttribute.setIndex = 0;
      featureIdAttribute.positionalLabel = "featureId_0";
      primitive.featureIds.push(featureIdAttribute);
    }

    const node = new Node$1();
    node.index = 0;
    node.primitives = [primitive];

    const scene = new Scene$1();
    scene.nodes = [node];
    scene.upAxis = Axis$1.Z;
    scene.forwardAxis = Axis$1.X;

    const components = new Components();
    components.scene = scene;
    components.nodes = [node];
    components.structuralMetadata = makeStructuralMetadata(parsedContent);

    if (defined(parsedContent.rtcCenter)) {
      components.transform = Matrix4.multiplyByTranslation(
        components.transform,
        parsedContent.rtcCenter,
        components.transform
      );
    }

    const positions = parsedContent.positions;
    if (defined(positions) && positions.isQuantized) {
      // The volume offset is sometimes in ECEF, so this is applied here rather
      // than the dequantization shader to avoid jitter
      components.transform = Matrix4.multiplyByTranslation(
        components.transform,
        positions.quantizedVolumeOffset,
        components.transform
      );
    }

    loader._components = components;

    // Free the parsed content so we don't hold onto the large typed arrays.
    loader._parsedContent = undefined;
  }

  PntsLoader.prototype.unload = function () {
    const buffers = this._buffers;
    for (let i = 0; i < buffers.length; i++) {
      buffers[i].destroy();
    }
    buffers.length = 0;

    this._components = undefined;
    this._parsedContent = undefined;
  };

  /**
   * A 3D model. This is a new architecture that is more decoupled than the older {@link Model}. This class is still experimental.
   * <p>
   * Do not call this function directly, instead use the `from` functions to create
   * the Model from your source data type.
   * </p>
   *
   * @alias ModelExperimental
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Resource} options.resource The Resource to the 3D model.
   * @param {Boolean} [options.show=true] Whether or not to render the model.
   * @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY]  The 4x4 transformation matrix that transforms the model from model to world coordinates.
   * @param {Number} [options.scale=1.0] A uniform scale applied to this model.
   * @param {Number} [options.minimumPixelSize=0.0] The approximate minimum pixel size of the model regardless of zoom.
   * @param {Number} [options.maximumScale] The maximum scale size of a model. An upper limit for minimumPixelSize.
   * @param {Object} [options.id] A user-defined object to return when the model is picked with {@link Scene#pick}.
   * @param {Boolean} [options.allowPicking=true] When <code>true</code>, each primitive is pickable with {@link Scene#pick}.
   * @param {Boolean} [options.clampAnimations=true] Determines if the model's animations should hold a pose over frames where no keyframes are specified.
   * @param {ShadowMode} [options.shadows=ShadowMode.ENABLED] Determines whether the model casts or receives shadows from light sources.
   * @param {Boolean} [options.debugShowBoundingVolume=false] For debugging only. Draws the bounding sphere for each draw command in the model.
   * @param {Boolean} [options.enableDebugWireframe=false] For debugging only. This must be set to true for debugWireframe to work in WebGL1. This cannot be set after the model has loaded.
   * @param {Boolean} [options.debugWireframe=false] For debugging only. Draws the model in wireframe. Will only work for WebGL1 if enableDebugWireframe is set to true.
   * @param {Boolean} [options.cull=true]  Whether or not to cull the model using frustum/horizon culling. If the model is part of a 3D Tiles tileset, this property will always be false, since the 3D Tiles culling system is used.
   * @param {Boolean} [options.opaquePass=Pass.OPAQUE] The pass to use in the {@link DrawCommand} for the opaque portions of the model.
   * @param {CustomShader} [options.customShader] A custom shader. This will add user-defined GLSL code to the vertex and fragment shaders. Using custom shaders with a {@link Cesium3DTileStyle} may lead to undefined behavior.
   * @param {Cesium3DTileContent} [options.content] The tile content this model belongs to. This property will be undefined if model is not loaded as part of a tileset.
   * @param {HeightReference} [options.heightReference=HeightReference.NONE] Determines how the model is drawn relative to terrain.
   * @param {Scene} [options.scene] Must be passed in for models that use the height reference property.
   * @param {DistanceDisplayCondition} [options.distanceDisplayCondition] The condition specifying at what distance from the camera that this model will be displayed.
   * @param {Color} [options.color] A color that blends with the model's rendered color.
   * @param {ColorBlendMode} [options.colorBlendMode=ColorBlendMode.HIGHLIGHT] Defines how the color blends with the model.
   * @param {Number} [options.colorBlendAmount=0.5] Value used to determine the color strength when the <code>colorBlendMode</code> is <code>MIX</code>. A value of 0.0 results in the model's rendered color while a value of 1.0 results in a solid color, with any value in-between resulting in a mix of the two.
   * @param {Color} [options.silhouetteColor=Color.RED] The silhouette color. If more than 256 models have silhouettes enabled, there is a small chance that overlapping models will have minor artifacts.
   * @param {Number} [options.silhouetteSize=0.0] The size of the silhouette in pixels.
   * @param {ClippingPlaneCollection} [options.clippingPlanes] The {@link ClippingPlaneCollection} used to selectively disable rendering the model.
   * @param {Cartesian3} [options.lightColor] The light color when shading the model. When <code>undefined</code> the scene's light color is used instead.
   * @param {ImageBasedLighting} [options.imageBasedLighting] The properties for managing image-based lighting on this model.
   * @param {Boolean} [options.backFaceCulling=true] Whether to cull back-facing geometry. When true, back face culling is determined by the material's doubleSided property; when false, back face culling is disabled. Back faces are not culled if the model's color is translucent.
   * @param {Credit|String} [options.credit] A credit for the data source, which is displayed on the canvas.
   * @param {Boolean} [options.showCreditsOnScreen=false] Whether to display the credits of this model on screen.
   * @param {SplitDirection} [options.splitDirection=SplitDirection.NONE] The {@link SplitDirection} split to apply to this model.
   * @param {Boolean} [options.projectTo2D=false] Whether to accurately project the model's positions in 2D. If this is true, the model will be projected accurately to 2D, but it will use more memory to do so. If this is false, the model will use less memory and will still render in 2D / CV mode, but its positions may be inaccurate. This disables minimumPixelSize and prevents future modification to the model matrix. This also cannot be set after the model has loaded.
   * @param {String|Number} [options.featureIdLabel="featureId_0"] Label of the feature ID set to use for picking and styling. For EXT_mesh_features, this is the feature ID's label property, or "featureId_N" (where N is the index in the featureIds array) when not specified. EXT_feature_metadata did not have a label field, so such feature ID sets are always labeled "featureId_N" where N is the index in the list of all feature Ids, where feature ID attributes are listed before feature ID textures. If featureIdLabel is an integer N, it is converted to the string "featureId_N" automatically. If both per-primitive and per-instance feature IDs are present, the instance feature IDs take priority.
   * @param {String|Number} [options.instanceFeatureIdLabel="instanceFeatureId_0"] Label of the instance feature ID set used for picking and styling. If instanceFeatureIdLabel is set to an integer N, it is converted to the string "instanceFeatureId_N" automatically. If both per-primitive and per-instance feature IDs are present, the instance feature IDs take priority.
   * @param {Object} [options.pointCloudShading] Options for constructing a {@link PointCloudShading} object to control point attenuation based on geometric error and lighting.
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function ModelExperimental(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.loader", options.loader);
    Check.typeOf.object("options.resource", options.resource);
    //>>includeEnd('debug');

    /**
     * The loader used to load resources for this model.
     * The corresponding constructor parameter is undocumented, since
     * ResourceLoader is part of the private API.
     *
     * @type {ResourceLoader}
     * @private
     */
    this._loader = options.loader;
    this._resource = options.resource;

    /**
     * Type of this model, to distinguish individual glTF files from 3D Tiles
     * internally. The corresponding constructor parameter is undocumented, since
     * ModelExperimentalType is part of the private API.
     *
     * @type {ModelExperimentalType}
     * @readonly
     *
     * @private
     */
    this.type = defaultValue(options.type, ModelExperimentalType$1.GLTF);

    /**
     * The 4x4 transformation matrix that transforms the model from model to world coordinates.
     * When this is the identity matrix, the model is drawn in world coordinates, i.e., Earth's Cartesian WGS84 coordinates.
     * Local reference frames can be used by providing a different transformation matrix, like that returned
     * by {@link Transforms.eastNorthUpToFixedFrame}.
     *
     * @type {Matrix4}

     * @default {@link Matrix4.IDENTITY}
     *
     * @example
     * const origin = Cesium.Cartesian3.fromDegrees(-95.0, 40.0, 200000.0);
     * m.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(origin);
     */
    this.modelMatrix = Matrix4.clone(
      defaultValue(options.modelMatrix, Matrix4.IDENTITY)
    );
    this._modelMatrix = Matrix4.clone(this.modelMatrix);
    this._scale = defaultValue(options.scale, 1.0);

    this._minimumPixelSize = defaultValue(options.minimumPixelSize, 0.0);

    this._maximumScale = options.maximumScale;

    /**
     * The scale value after being clamped by the maximum scale parameter.
     * Used to adjust bounding spheres without repeated calculation.
     *
     * @type {Number}
     * @private
     */
    this._clampedScale = defined(this._maximumScale)
      ? Math.min(this._scale, this._maximumScale)
      : this._scale;

    this._computedScale = this._clampedScale;

    /**
     * Whether or not the ModelExperimentalSceneGraph should call updateModelMatrix.
     * This will be true if any of the model matrix, scale, minimum pixel size, or maximum scale are dirty.
     *
     * @type {Number}
     * @private
     */
    this._updateModelMatrix = false;

    /**
     * If defined, this matrix is used to transform miscellaneous properties like
     * clipping planes and image-based lighting instead of the modelMatrix. This is
     * so that when models are part of a tileset, these properties get transformed
     * relative to a common reference (such as the root).
     *
     * @type {Matrix4}
     * @private
     */
    this.referenceMatrix = undefined;
    this._iblReferenceFrameMatrix = Matrix3.clone(Matrix3.IDENTITY); // Derived from reference matrix and the current view matrix

    this._resourcesLoaded = false;
    this._drawCommandsBuilt = false;

    this._ready = false;
    this._customShader = options.customShader;
    this._content = options.content;

    this._texturesLoaded = false;
    this._defaultTexture = undefined;

    this._activeAnimations = new ModelExperimentalAnimationCollection(this);
    this._clampAnimations = defaultValue(options.clampAnimations, true);

    this._id = options.id;
    this._idDirty = false;

    const color = options.color;
    this._color = defaultValue(color) ? Color.clone(color) : undefined;
    this._colorBlendMode = defaultValue(
      options.colorBlendMode,
      ColorBlendMode$1.HIGHLIGHT
    );
    this._colorBlendAmount = defaultValue(options.colorBlendAmount, 0.5);

    const silhouetteColor = defaultValue(options.silhouetteColor, Color.RED);
    this._silhouetteColor = Color.clone(silhouetteColor);
    this._silhouetteSize = defaultValue(options.silhouetteSize, 0.0);
    this._silhouetteDirty = false;

    this._cull = defaultValue(options.cull, true);
    this._opaquePass = defaultValue(options.opaquePass, Pass$1.OPAQUE);
    this._allowPicking = defaultValue(options.allowPicking, true);
    this._show = defaultValue(options.show, true);

    this._style = undefined;

    let featureIdLabel = defaultValue(options.featureIdLabel, "featureId_0");
    if (typeof featureIdLabel === "number") {
      featureIdLabel = `featureId_${featureIdLabel}`;
    }
    this._featureIdLabel = featureIdLabel;

    let instanceFeatureIdLabel = defaultValue(
      options.instanceFeatureIdLabel,
      "instanceFeatureId_0"
    );
    if (typeof instanceFeatureIdLabel === "number") {
      instanceFeatureIdLabel = `instanceFeatureId_${instanceFeatureIdLabel}`;
    }
    this._instanceFeatureIdLabel = instanceFeatureIdLabel;

    this._featureTables = [];
    this._featureTableId = undefined;
    this._featureTableIdDirty = true;

    // Keeps track of resources that need to be destroyed when the draw commands are reset.
    this._pipelineResources = [];

    // Keeps track of resources that need to be destroyed when the Model is destroyed.
    this._modelResources = [];

    // Keeps track of the pick IDs for this model. These are stored and destroyed in the
    // pipeline resources array; the purpose of this array is to separate them from other
    // resources and update their ID objects when necessary.
    this._pickIds = [];

    // The model's bounding sphere and its initial radius are computed
    // in ModelExperimentalSceneGraph.
    this._boundingSphere = new BoundingSphere();
    this._initialRadius = undefined;

    this._heightReference = defaultValue(
      options.heightReference,
      HeightReference$1.NONE
    );
    this._heightDirty = this._heightReference !== HeightReference$1.NONE;
    this._removeUpdateHeightCallback = undefined;

    this._clampedModelMatrix = undefined; // For use with height reference

    const scene = options.scene;
    if (defined(scene) && defined(scene.terrainProviderChanged)) {
      this._terrainProviderChangedCallback = scene.terrainProviderChanged.addEventListener(
        function () {
          this._heightDirty = true;
        },
        this
      );
    }
    this._scene = scene;

    this._distanceDisplayCondition = options.distanceDisplayCondition;

    const pointCloudShading = new PointCloudShading(options.pointCloudShading);
    this._attenuation = pointCloudShading.attenuation;
    this._pointCloudShading = pointCloudShading;

    // If the given clipping planes don't have an owner, make this model its owner.
    // Otherwise, the clipping planes are passed down from a tileset.
    const clippingPlanes = options.clippingPlanes;
    if (defined(clippingPlanes) && clippingPlanes.owner === undefined) {
      ClippingPlaneCollection.setOwner(clippingPlanes, this, "_clippingPlanes");
    } else {
      this._clippingPlanes = clippingPlanes;
    }
    this._clippingPlanesState = 0; // If this value changes, the shaders need to be regenerated.
    this._clippingPlanesMatrix = Matrix4.clone(Matrix4.IDENTITY); // Derived from reference matrix and the current view matrix

    this._lightColor = Cartesian3.clone(options.lightColor);

    this._imageBasedLighting = defined(options.imageBasedLighting)
      ? options.imageBasedLighting
      : new ImageBasedLighting();
    this._shouldDestroyImageBasedLighting = !defined(options.imageBasedLighting);

    this._backFaceCulling = defaultValue(options.backFaceCulling, true);
    this._backFaceCullingDirty = false;

    this._shadows = defaultValue(options.shadows, ShadowMode$1.ENABLED);
    this._shadowsDirty = false;

    this._debugShowBoundingVolumeDirty = false;
    this._debugShowBoundingVolume = defaultValue(
      options.debugShowBoundingVolume,
      false
    );

    this._enableDebugWireframe = defaultValue(
      options.enableDebugWireframe,
      false
    );
    this._debugWireframe = defaultValue(options.debugWireframe, false);

    // Credit specified by the user.
    let credit = options.credit;
    if (typeof credit === "string") {
      credit = new Credit(credit);
    }

    this._credit = credit;

    // Credits to be added from the Resource (if it is an IonResource)
    this._resourceCredits = [];

    // Credits parsed from the glTF by GltfLoader.
    this._gltfCredits = [];

    this._showCreditsOnScreen = defaultValue(options.showCreditsOnScreen, false);
    this._showCreditsOnScreenDirty = true;

    this._splitDirection = defaultValue(
      options.splitDirection,
      SplitDirection$1.NONE
    );

    this._statistics = new ModelExperimentalStatistics();

    this._sceneMode = undefined;
    this._projectTo2D = defaultValue(options.projectTo2D, false);

    this._completeLoad = function (model, frameState) {};
    this._texturesLoadedPromise = undefined;
    this._readyPromise = initialize(this);
  }

  function createModelFeatureTables(model, structuralMetadata) {
    const featureTables = model._featureTables;

    const propertyTables = structuralMetadata.propertyTables;
    const length = propertyTables.length;
    for (let i = 0; i < length; i++) {
      const propertyTable = propertyTables[i];
      const modelFeatureTable = new ModelFeatureTable({
        model: model,
        propertyTable: propertyTable,
      });

      featureTables.push(modelFeatureTable);
    }

    return featureTables;
  }

  function selectFeatureTableId(components, model) {
    const featureIdLabel = model._featureIdLabel;
    const instanceFeatureIdLabel = model._instanceFeatureIdLabel;

    let i, j;
    let featureIdAttribute;

    let node;
    // Scan the nodes till we find one with instances, get the feature table ID
    // if the feature ID attribute of the user-selected index is present.
    for (i = 0; i < components.nodes.length; i++) {
      node = components.nodes[i];
      if (defined(node.instances)) {
        featureIdAttribute = ModelExperimentalUtility.getFeatureIdsByLabel(
          node.instances.featureIds,
          instanceFeatureIdLabel
        );
        if (
          defined(featureIdAttribute) &&
          defined(featureIdAttribute.propertyTableId)
        ) {
          return featureIdAttribute.propertyTableId;
        }
      }
    }

    // Scan the primitives till we find one with textures or attributes, get the feature table ID
    // if the feature ID attribute/texture of the user-selected index is present.
    for (i = 0; i < components.nodes.length; i++) {
      node = components.nodes[i];
      for (j = 0; j < node.primitives.length; j++) {
        const primitive = node.primitives[j];
        const featureIds = ModelExperimentalUtility.getFeatureIdsByLabel(
          primitive.featureIds,
          featureIdLabel
        );

        if (defined(featureIds)) {
          return featureIds.propertyTableId;
        }
      }
    }
  }

  // Returns whether the color alpha state has changed between invisible, translucent, or opaque
  function isColorAlphaDirty(currentColor, previousColor) {
    if (!defined(currentColor) && !defined(previousColor)) {
      return false;
    }

    if (defined(currentColor) !== defined(previousColor)) {
      return true;
    }

    const currentAlpha = currentColor.alpha;
    const previousAlpha = previousColor.alpha;
    return (
      Math.floor(currentAlpha) !== Math.floor(previousAlpha) ||
      Math.ceil(currentAlpha) !== Math.ceil(previousAlpha)
    );
  }

  function initialize(model) {
    const loader = model._loader;
    const resource = model._resource;

    loader.load();

    const loaderPromise = loader.promise.then(function (loader) {
      const components = loader.components;
      const structuralMetadata = components.structuralMetadata;

      if (
        defined(structuralMetadata) &&
        structuralMetadata.propertyTableCount > 0
      ) {
        createModelFeatureTables(model, structuralMetadata);
      }

      const sceneGraph = new ModelExperimentalSceneGraph({
        model: model,
        modelComponents: components,
      });

      model._sceneGraph = sceneGraph;
      model._gltfCredits = sceneGraph.components.asset.credits;

      const resourceCredits = model._resource.credits;
      if (defined(resourceCredits)) {
        const length = resourceCredits.length;
        for (let i = 0; i < length; i++) {
          model._resourceCredits.push(resourceCredits[i]);
        }
      }

      model._resourcesLoaded = true;
    });

    // Transcoded .pnts models do not have textures
    const texturesLoadedPromise = defaultValue(
      loader.texturesLoadedPromise,
      Promise.resolve()
    );
    model._texturesLoadedPromise = texturesLoadedPromise
      .then(function () {
        model._texturesLoaded = true;

        // Re-run the pipeline so texture memory statistics are re-computed
        if (loader._incrementallyLoadTextures) {
          model.resetDrawCommands();
        }
      })
      .catch(
        ModelExperimentalUtility.getFailedLoadFunction(model, "model", resource)
      );

    const promise = new Promise(function (resolve, reject) {
      model._completeLoad = function (model, frameState) {
        // Set the model as ready after the first frame render since the user might set up events subscribed to
        // the post render event, and the model may not be ready for those past the first frame.
        frameState.afterRender.push(function () {
          model._ready = true;
          resolve(model);
        });
      };
    });

    return loaderPromise
      .then(function () {
        return promise;
      })
      .catch(
        ModelExperimentalUtility.getFailedLoadFunction(model, "model", resource)
      );
  }

  Object.defineProperties(ModelExperimental.prototype, {
    /**
     * When <code>true</code>, this model is ready to render, i.e., the external binary, image,
     * and shader files were downloaded and the WebGL resources were created.  This is set to
     * <code>true</code> right before {@link ModelExperimental#readyPromise} is resolved.
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default false
     */
    ready: {
      get: function () {
        return this._ready;
      },
    },

    /**
     * Gets the promise that will be resolved when this model is ready to render, i.e. when the external resources
     * have been downloaded and the WebGL resources are created.
     * <p>
     * This promise is resolved at the end of the frame before the first frame the model is rendered in.
     * </p>
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {Promise.<ModelExperimental>}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._readyPromise;
      },
    },

    /**
     * A promise that resolves when all textures are loaded.
     * When <code>incrementallyLoadTextures</code> is true this may resolve after
     * <code>promise</code> resolves.
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {Promise<void>}
     * @readonly
     *
     * @private
     */
    texturesLoadedPromise: {
      get: function () {
        return this._texturesLoadedPromise;
      },
    },

    /**
     * @private
     */
    loader: {
      get: function () {
        return this._loader;
      },
    },

    /**
     * Get the estimated memory usage statistics for this model.
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {ModelExperimentalStatistics}
     * @readonly
     *
     * @private
     */
    statistics: {
      get: function () {
        return this._statistics;
      },
    },

    /**
     * The currently playing glTF animations.
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {ModelExperimentalAnimationCollection}
     * @readonly
     */
    activeAnimations: {
      get: function () {
        return this._activeAnimations;
      },
    },

    /**
     * Determines if the model's animations should hold a pose over frames where no keyframes are specified.
     *
     * @memberof ModelExperimental.prototype
     * @type {Boolean}
     *
     * @default true
     */
    clampAnimations: {
      get: function () {
        return this._clampAnimations;
      },
      set: function (value) {
        this._clampAnimations = value;
      },
    },

    /**
     * Whether or not to cull the model using frustum/horizon culling. If the model is part of a 3D Tiles tileset, this property
     * will always be false, since the 3D Tiles culling system is used.
     *
     * @type {Boolean}
     * @readonly
     *
     * @private
     */
    cull: {
      get: function () {
        return this._cull;
      },
    },

    /**
     * The pass to use in the {@link DrawCommand} for the opaque portions of the model.
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {Pass}
     * @readonly
     *
     * @private
     */
    opaquePass: {
      get: function () {
        return this._opaquePass;
      },
    },

    /**
     * Point cloud shading settings for controlling point cloud attenuation
     * and lighting. For 3D Tiles, this is inherited from the
     * {@link Cesium3DTileset}.
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {PointCloudShading}
     */
    pointCloudShading: {
      get: function () {
        return this._pointCloudShading;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.defined("pointCloudShading", value);
        //>>includeEnd('debug');
        if (value !== this._pointCloudShading) {
          this.resetDrawCommands();
        }
        this._pointCloudShading = value;
      },
    },

    /**
     * The model's custom shader, if it exists. Using custom shaders with a {@link Cesium3DTileStyle}
     * may lead to undefined behavior.
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {CustomShader}
     */
    customShader: {
      get: function () {
        return this._customShader;
      },
      set: function (value) {
        if (value !== this._customShader) {
          this.resetDrawCommands();
        }
        this._customShader = value;
      },
    },

    /**
     * The scene graph of this model.
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {ModelExperimentalSceneGraph}
     * @private
     */
    sceneGraph: {
      get: function () {
        return this._sceneGraph;
      },
    },

    /**
     * The tile content this model belongs to, if it is loaded as part of a {@link Cesium3DTileset}.
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {Cesium3DTileContent}
     * @readonly
     *
     * @private
     */
    content: {
      get: function () {
        return this._content;
      },
    },

    /**
     * The height reference of the model, which determines how the model is drawn
     * relative to terrain.
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {HeightReference}
     * @default {HeightReference.NONE}
     *
     */
    heightReference: {
      get: function () {
        return this._heightReference;
      },
      set: function (value) {
        if (value !== this._heightReference) {
          this._heightDirty = true;
        }
        this._heightReference = value;
      },
    },

    /**
     * Gets or sets the distance display condition, which specifies at what distance
     * from the camera this model will be displayed.
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {DistanceDisplayCondition}
     *
     * @default undefined
     *
     */
    distanceDisplayCondition: {
      get: function () {
        return this._distanceDisplayCondition;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (defined(value) && value.far <= value.near) {
          throw new DeveloperError("far must be greater than near");
        }
        //>>includeEnd('debug');
        this._distanceDisplayCondition = DistanceDisplayCondition.clone(
          value,
          this._distanceDisplayCondition
        );
      },
    },

    /**
     * The structural metadata from the EXT_structural_metadata extension
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {StructuralMetadata}
     * @readonly
     *
     * @private
     */
    structuralMetadata: {
      get: function () {
        return this._sceneGraph.components.structuralMetadata;
      },
    },

    /**
     * The ID for the feature table to use for picking and styling in this model.
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {Number}
     *
     * @private
     */
    featureTableId: {
      get: function () {
        return this._featureTableId;
      },
      set: function (value) {
        this._featureTableId = value;
      },
    },

    /**
     * The feature tables for this model.
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {Array}
     * @readonly
     *
     * @private
     */
    featureTables: {
      get: function () {
        return this._featureTables;
      },
      set: function (value) {
        this._featureTables = value;
      },
    },

    /**
     * A user-defined object that is returned when the model is picked.
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {Object}
     *
     * @default undefined
     *
     * @see Scene#pick
     */
    id: {
      get: function () {
        return this._id;
      },
      set: function (value) {
        if (value !== this._id) {
          this._idDirty = true;
        }

        this._id = value;
      },
    },

    /**
     * When <code>true</code>, each primitive is pickable with {@link Scene#pick}.  When <code>false</code>, GPU memory is saved.
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @private
     */
    allowPicking: {
      get: function () {
        return this._allowPicking;
      },
    },

    /**
     * The style to apply the to the features in the model. Cannot be applied if a {@link CustomShader} is also applied.
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {Cesium3DTileStyle}
     */
    style: {
      get: function () {
        return this._style;
      },
      set: function (value) {
        if (value !== this._style) {
          this.applyStyle(value);
        }
        this._style = value;
      },
    },

    /**
     * The color to blend with the model's rendered color.
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {Color}
     */
    color: {
      get: function () {
        return this._color;
      },
      set: function (value) {
        if (!Color.equals(this._color, value)) {
          this.resetDrawCommands();
        }
        this._color = Color.clone(value, this._color);
      },
    },

    /**
     * Defines how the color blends with the model.
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {Cesium3DTileColorBlendMode|ColorBlendMode}
     *
     * @default ColorBlendMode.HIGHLIGHT
     */
    colorBlendMode: {
      get: function () {
        return this._colorBlendMode;
      },
      set: function (value) {
        this._colorBlendMode = value;
      },
    },

    /**
     * Value used to determine the color strength when the <code>colorBlendMode</code> is <code>MIX</code>. A value of 0.0 results in the model's rendered color while a value of 1.0 results in a solid color, with any value in-between resulting in a mix of the two.
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {Number}
     *
     * @default 0.5
     */
    colorBlendAmount: {
      get: function () {
        return this._colorBlendAmount;
      },
      set: function (value) {
        this._colorBlendAmount = value;
      },
    },

    /**
     * The silhouette color.
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {Color}
     *
     * @default Color.RED
     */
    silhouetteColor: {
      get: function () {
        return this._silhouetteColor;
      },
      set: function (value) {
        if (!Color.equals(value, this._silhouetteColor)) {
          const alphaDirty = isColorAlphaDirty(value, this._silhouetteColor);
          this._silhouetteDirty = this._silhouetteDirty || alphaDirty;
        }

        this._silhouetteColor = Color.clone(value, this._silhouetteColor);
      },
    },

    /**
     * The size of the silhouette in pixels.
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {Number}
     *
     * @default 0.0
     */
    silhouetteSize: {
      get: function () {
        return this._silhouetteSize;
      },
      set: function (value) {
        if (value !== this._silhouetteSize) {
          const currentSize = this._silhouetteSize;
          const sizeDirty =
            (value > 0.0 && currentSize === 0.0) ||
            (value === 0.0 && currentSize > 0.0);
          this._silhouetteDirty = this._silhouetteDirty || sizeDirty;

          // Back-face culling needs to be updated in case the silhouette size
          // is greater than zero.
          this._backFaceCullingDirty = this._backFaceCullingDirty || sizeDirty;
        }

        this._silhouetteSize = value;
      },
    },

    /**
     * Gets the model's bounding sphere in world space. This does not take into account
     * glTF animations, skins, or morph targets. It also does not account for
     * {@link ModelExperimental#minimumPixelSize}.
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {BoundingSphere}
     * @readonly
     */
    boundingSphere: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "The model is not loaded. Use ModelExperimental.readyPromise or wait for ModelExperimental.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._boundingSphere;
      },
    },

    /**
     * This property is for debugging only; it is not for production use nor is it optimized.
     * <p>
     * Draws the bounding sphere for each draw command in the model.
     * </p>
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {Boolean}
     *
     * @default false
     */
    debugShowBoundingVolume: {
      get: function () {
        return this._debugShowBoundingVolume;
      },
      set: function (value) {
        if (this._debugShowBoundingVolume !== value) {
          this._debugShowBoundingVolumeDirty = true;
        }
        this._debugShowBoundingVolume = value;
      },
    },

    /**
     * This property is for debugging only; it is not for production use nor is it optimized.
     * <p>
     * Draws the model in wireframe.
     * </p>
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {Boolean}
     *
     * @default false
     */
    debugWireframe: {
      get: function () {
        return this._debugWireframe;
      },
      set: function (value) {
        if (this._debugWireframe !== value) {
          this.resetDrawCommands();
        }
        this._debugWireframe = value;
      },
    },

    /**
     * Whether or not to render the model.
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {Boolean}
     *
     * @default true
     */
    show: {
      get: function () {
        return this._show;
      },
      set: function (value) {
        this._show = value;
      },
    },

    /**
     * Label of the feature ID set to use for picking and styling.
     * <p>
     * For EXT_mesh_features, this is the feature ID's label property, or
     * "featureId_N" (where N is the index in the featureIds array) when not
     * specified. EXT_feature_metadata did not have a label field, so such
     * feature ID sets are always labeled "featureId_N" where N is the index in
     * the list of all feature Ids, where feature ID attributes are listed before
     * feature ID textures.
     * </p>
     * <p>
     * If featureIdLabel is set to an integer N, it is converted to
     * the string "featureId_N" automatically. If both per-primitive and
     * per-instance feature IDs are present, the instance feature IDs take
     * priority.
     * </p>
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {String}
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     */
    featureIdLabel: {
      get: function () {
        return this._featureIdLabel;
      },
      set: function (value) {
        // indices get converted into featureId_N
        if (typeof value === "number") {
          value = `featureId_${value}`;
        }

        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.string("value", value);
        //>>includeEnd('debug');

        if (value !== this._featureIdLabel) {
          this._featureTableIdDirty = true;
        }

        this._featureIdLabel = value;
      },
    },

    /**
     * Label of the instance feature ID set used for picking and styling.
     * <p>
     * If instanceFeatureIdLabel is set to an integer N, it is converted to
     * the string "instanceFeatureId_N" automatically.
     * If both per-primitive and per-instance feature IDs are present, the
     * instance feature IDs take priority.
     * </p>
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {String}
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     */
    instanceFeatureIdLabel: {
      get: function () {
        return this._instanceFeatureIdLabel;
      },
      set: function (value) {
        // indices get converted into instanceFeatureId_N
        if (typeof value === "number") {
          value = `instanceFeatureId_${value}`;
        }

        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.string("value", value);
        //>>includeEnd('debug');

        if (value !== this._instanceFeatureIdLabel) {
          this._featureTableIdDirty = true;
        }

        this._instanceFeatureIdLabel = value;
      },
    },

    /**
     * The {@link ClippingPlaneCollection} used to selectively disable rendering the model.
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {ClippingPlaneCollection}
     */
    clippingPlanes: {
      get: function () {
        return this._clippingPlanes;
      },
      set: function (value) {
        if (value !== this._clippingPlanes) {
          // Handle destroying old clipping planes, new clipping planes ownership
          ClippingPlaneCollection.setOwner(value, this, "_clippingPlanes");
          this.resetDrawCommands();
        }
      },
    },

    /**
     * The light color when shading the model. When <code>undefined</code> the scene's light color is used instead.
     * <p>
     * Disabling additional light sources by setting
     * <code>model.imageBasedLighting.imageBasedLightingFactor = new Cartesian2(0.0, 0.0)</code>
     * will make the model much darker. Here, increasing the intensity of the light source will make the model brighter.
     * </p>
     * @memberof ModelExperimental.prototype
     *
     * @type {Cartesian3}
     *
     * @default undefined
     */
    lightColor: {
      get: function () {
        return this._lightColor;
      },
      set: function (value) {
        if (defined(value) !== defined(this._lightColor)) {
          this.resetDrawCommands();
        }

        this._lightColor = Cartesian3.clone(value, this._lightColor);
      },
    },

    /**
     * The properties for managing image-based lighting on this model.
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {ImageBasedLighting}
     */
    imageBasedLighting: {
      get: function () {
        return this._imageBasedLighting;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.object("imageBasedLighting", this._imageBasedLighting);
        //>>includeEnd('debug');

        if (value !== this._imageBasedLighting) {
          if (
            this._shouldDestroyImageBasedLighting &&
            !this._imageBasedLighting.isDestroyed()
          ) {
            this._imageBasedLighting.destroy();
          }
          this._imageBasedLighting = value;
          this._shouldDestroyImageBasedLighting = false;
          this.resetDrawCommands();
        }
      },
    },

    /**
     * Whether to cull back-facing geometry. When true, back face culling is
     * determined by the material's doubleSided property; when false, back face
     * culling is disabled. Back faces are not culled if {@link ModelExperimental#color}
     * is translucent or {@link ModelExperimental#silhouetteSize} is greater than 0.0.
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {Boolean}
     *
     * @default true
     */
    backFaceCulling: {
      get: function () {
        return this._backFaceCulling;
      },
      set: function (value) {
        if (value !== this._backFaceCulling) {
          this._backFaceCullingDirty = true;
        }

        this._backFaceCulling = value;
      },
    },

    /**
     * A uniform scale applied to this model before the {@link Model#modelMatrix}.
     * Values greater than <code>1.0</code> increase the size of the model; values
     * less than <code>1.0</code> decrease.
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {Number}
     *
     * @default 1.0
     */
    scale: {
      get: function () {
        return this._scale;
      },
      set: function (value) {
        if (value !== this._scale) {
          this._updateModelMatrix = true;
        }
        this._scale = value;
      },
    },

    /**
     * The true scale of the model after being affected by the model's scale,
     * minimum pixel size, and maximum scale parameters.
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {Number}
     * @readonly
     *
     * @private
     */
    computedScale: {
      get: function () {
        return this._computedScale;
      },
    },

    /**
     * The approximate minimum pixel size of the model regardless of zoom.
     * This can be used to ensure that a model is visible even when the viewer
     * zooms out.  When <code>0.0</code>, no minimum size is enforced.
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {Number}
     *
     * @default 0.0
     */
    minimumPixelSize: {
      get: function () {
        return this._minimumPixelSize;
      },
      set: function (value) {
        if (value !== this._minimumPixelSize) {
          this._updateModelMatrix = true;
        }
        this._minimumPixelSize = value;
      },
    },

    /**
     * The maximum scale size for a model. This can be used to give
     * an upper limit to the {@link Model#minimumPixelSize}, ensuring that the model
     * is never an unreasonable scale.
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {Number}
     */
    maximumScale: {
      get: function () {
        return this._maximumScale;
      },
      set: function (value) {
        if (value !== this._maximumScale) {
          this._updateModelMatrix = true;
        }
        this._maximumScale = value;
      },
    },

    /**
     * Determines whether the model casts or receives shadows from light sources.

     * @memberof ModelExperimental.prototype
     *
     * @type {ShadowMode}
     *
     * @default ShadowMode.ENABLED
     */
    shadows: {
      get: function () {
        return this._shadows;
      },
      set: function (value) {
        if (value !== this._shadows) {
          this._shadowsDirty = true;
        }

        this._shadows = value;
      },
    },

    /**
     * Gets the credit that will be displayed for the model
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {Credit}
     * @readonly
     */
    credit: {
      get: function () {
        return this._credit;
      },
    },

    /**
     * Gets or sets whether the credits of the model will be displayed on the screen
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {Boolean}
     *
     * @default false
     */
    showCreditsOnScreen: {
      get: function () {
        return this._showCreditsOnScreen;
      },
      set: function (value) {
        if (this._showCreditsOnScreen !== value) {
          this._showCreditsOnScreenDirty = true;
        }

        this._showCreditsOnScreen = value;
      },
    },

    /**
     * The {@link SplitDirection} to apply to this model.
     *
     * @memberof ModelExperimental.prototype
     *
     * @type {SplitDirection}
     *
     * @default {@link SplitDirection.NONE}
     */
    splitDirection: {
      get: function () {
        return this._splitDirection;
      },
      set: function (value) {
        if (this._splitDirection !== value) {
          this.resetDrawCommands();
        }
        this._splitDirection = value;
      },
    },
  });

  /**
   * Sets the current value of an articulation stage.  After setting one or
   * multiple stage values, call ModelExperimental.applyArticulations() to
   * cause the node matrices to be recalculated.
   *
   * @param {String} articulationStageKey The name of the articulation, a space, and the name of the stage.
   * @param {Number} value The numeric value of this stage of the articulation.
   *
   * @exception {DeveloperError} The model is not loaded. Use ModelExperimental.readyPromise or wait for ModelExperimental.ready to be true.
   *
   * @see ModelExperimental#applyArticulations
   *
   * @example
   * // Sets the value of the stage named "MoveX" belonging to the articulation named "SampleArticulation"
   * model.setArticulationStage("SampleArticulation MoveX", 50.0);
   */
  ModelExperimental.prototype.setArticulationStage = function (
    articulationStageKey,
    value
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("value", value);
    if (!this._ready) {
      throw new DeveloperError(
        "The model is not loaded. Use ModelExperimental.readyPromise or wait for ModelExperimental.ready to be true."
      );
    }
    //>>includeEnd('debug');

    this._sceneGraph.setArticulationStage(articulationStageKey, value);
  };

  /**
   * Applies any modified articulation stages to the matrix of each node that
   * participates in any articulation. Note that this will overwrite any node
   * transformations on participating nodes.
   *
   * @exception {DeveloperError} The model is not loaded. Use ModelExperimental.readyPromise or wait for ModelExperimental.ready to be true.
   */
  ModelExperimental.prototype.applyArticulations = function () {
    //>>includeStart('debug', pragmas.debug);
    if (!this._ready) {
      throw new DeveloperError(
        "The model is not loaded. Use ModelExperimental.readyPromise or wait for ModelExperimental.ready to be true."
      );
    }
    //>>includeEnd('debug');

    this._sceneGraph.applyArticulations();
  };

  /**
   * Resets the draw commands for this model.
   *
   * @private
   */
  ModelExperimental.prototype.resetDrawCommands = function () {
    this._drawCommandsBuilt = false;
  };

  const scratchIBLReferenceFrameMatrix4 = new Matrix4();
  const scratchIBLReferenceFrameMatrix3 = new Matrix3();
  const scratchClippingPlanesMatrix$1 = new Matrix4();

  /**
   * Called when {@link Viewer} or {@link CesiumWidget} render the scene to
   * get the draw commands needed to render this primitive.
   * <p>
   * Do not call this function directly.  This is documented just to
   * list the exceptions that may be propagated when the scene is rendered:
   * </p>
   *
   * @exception {RuntimeError} Failed to load external reference.
   */
  ModelExperimental.prototype.update = function (frameState) {
    // Keep processing the model every frame until the main resources
    // (buffer views) and textures (which may be loaded asynchronously)
    // are processed.
    processLoader(this, frameState);

    // A custom shader may have to load texture uniforms.
    updateCustomShader(this, frameState);

    // The image-based lighting may have to load texture uniforms
    // for specular maps.
    updateImageBasedLighting(this, frameState);

    // Short-circuit if the model resources aren't ready or the scene
    // is currently morphing.
    if (!this._resourcesLoaded || frameState.mode === SceneMode$1.MORPHING) {
      return;
    }

    updatePointCloudAttenuation(this);
    updateSilhouette(this, frameState);
    updateClippingPlanes$1(this, frameState);
    updateSceneMode(this, frameState);
    updateFeatureTables(this, frameState);

    this._defaultTexture = frameState.context.defaultTexture;

    buildDrawCommands(this, frameState);
    updateModelMatrix(this, frameState);

    // Many features (e.g. image-based lighting, clipping planes) depend on the model
    // matrix being updated for the current height reference, so update it first.
    updateClamping(this);

    updateBoundingSphereAndScale(this, frameState);
    updateReferenceMatrices(this, frameState);

    // This check occurs after the bounding sphere has been updated so that
    // zooming to the bounding sphere can account for any modifications
    // from the clamp-to-ground setting.
    const model = this;
    if (!model._ready) {
      model._completeLoad(model, frameState);

      // Don't render until the next frame after the ready promise is resolved
      return;
    }

    updatePickIds(this);

    // Update the scene graph and draw commands for any changes in model's properties
    // (e.g. model matrix, back-face culling)
    updateSceneGraph(this, frameState);
    updateShowCreditsOnScreen(this);
    submitDrawCommands(this, frameState);
  };

  function processLoader(model, frameState) {
    if (!model._resourcesLoaded || !model._texturesLoaded) {
      model._loader.process(frameState);
    }
  }

  function updateCustomShader(model, frameState) {
    if (defined(model._customShader)) {
      model._customShader.update(frameState);
    }
  }

  function updateImageBasedLighting(model, frameState) {
    model._imageBasedLighting.update(frameState);
    if (model._imageBasedLighting.shouldRegenerateShaders) {
      model.resetDrawCommands();
    }
  }

  function updatePointCloudAttenuation(model) {
    // Check if the shader needs to be updated for point cloud attenuation
    // settings.
    if (model.pointCloudShading.attenuation !== model._attenuation) {
      model.resetDrawCommands();
      model._attenuation = model.pointCloudShading.attenuation;
    }
  }

  function updateSilhouette(model, frameState) {
    if (model._silhouetteDirty) {
      // Only rebuild draw commands if silhouettes are supported in the first place.
      if (supportsSilhouettes(frameState)) {
        model.resetDrawCommands();
      }

      model._silhouetteDirty = false;
    }
  }

  function updateClippingPlanes$1(model, frameState) {
    // Update the clipping planes collection for this model to detect any changes.
    if (model.isClippingEnabled()) {
      if (model._clippingPlanes.owner === model) {
        model._clippingPlanes.update(frameState);
      }

      const currentClippingPlanesState =
        model._clippingPlanes.clippingPlanesState;
      if (currentClippingPlanesState !== model._clippingPlanesState) {
        model.resetDrawCommands();
        model._clippingPlanesState = currentClippingPlanesState;
      }
    }
  }

  function updateSceneMode(model, frameState) {
    if (frameState.mode !== model._sceneMode) {
      if (model._projectTo2D) {
        model.resetDrawCommands();
      } else {
        model._updateModelMatrix = true;
      }
      model._sceneMode = frameState.mode;
    }
  }

  function updateFeatureTables(model, frameState) {
    if (model._featureTableIdDirty) {
      updateFeatureTableId(model);
      model._featureTableIdDirty = false;
    }

    const featureTables = model._featureTables;
    const length = featureTables.length;
    for (let i = 0; i < length; i++) {
      featureTables[i].update(frameState);
      // Check if the types of style commands needed have changed and trigger a reset of the draw commands
      // to ensure that translucent and opaque features are handled in the correct passes.
      if (featureTables[i].styleCommandsNeededDirty) {
        model.resetDrawCommands();
      }
    }
  }

  function updateFeatureTableId(model) {
    const components = model._sceneGraph.components;
    const structuralMetadata = components.structuralMetadata;

    if (
      defined(structuralMetadata) &&
      structuralMetadata.propertyTableCount > 0
    ) {
      model.featureTableId = selectFeatureTableId(components, model);
      // Re-apply the style to reflect the new feature ID table.
      // This in turn triggers a rebuild of the draw commands.
      model.applyStyle(model._style);
    }
  }

  function buildDrawCommands(model, frameState) {
    if (!model._drawCommandsBuilt) {
      model.destroyPipelineResources();
      model._sceneGraph.buildDrawCommands(frameState);
      model._drawCommandsBuilt = true;
    }
  }

  function updateModelMatrix(model, frameState) {
    // This is done without a dirty flag so that the model matrix can be updated in-place
    // without needing to use a setter.
    if (!Matrix4.equals(model.modelMatrix, model._modelMatrix)) {
      //>>includeStart('debug', pragmas.debug);
      if (frameState.mode !== SceneMode$1.SCENE3D && model._projectTo2D) {
        throw new DeveloperError(
          "ModelExperimental.modelMatrix cannot be changed in 2D or Columbus View if projectTo2D is true."
        );
      }
      //>>includeEnd('debug');
      model._updateModelMatrix = true;
      model._modelMatrix = Matrix4.clone(model.modelMatrix, model._modelMatrix);
    }
  }

  const scratchPosition$3 = new Cartesian3();
  const scratchCartographic$a = new Cartographic();

  function updateClamping(model) {
    if (
      !model._updateModelMatrix &&
      !model._heightDirty &&
      model._minimumPixelSize === 0.0
    ) {
      return;
    }

    if (defined(model._removeUpdateHeightCallback)) {
      model._removeUpdateHeightCallback();
      model._removeUpdateHeightCallback = undefined;
    }

    const scene = model._scene;
    if (
      !defined(scene) ||
      !defined(scene.globe) ||
      model.heightReference === HeightReference$1.NONE
    ) {
      //>>includeStart('debug', pragmas.debug);
      if (model.heightReference !== HeightReference$1.NONE) {
        throw new DeveloperError(
          "Height reference is not supported without a scene and globe."
        );
      }
      //>>includeEnd('debug');
      model._clampedModelMatrix = undefined;
      return;
    }

    const globe = scene.globe;
    const ellipsoid = globe.ellipsoid;

    // Compute cartographic position so we don't recompute every update
    const modelMatrix = model.modelMatrix;
    scratchPosition$3.x = modelMatrix[12];
    scratchPosition$3.y = modelMatrix[13];
    scratchPosition$3.z = modelMatrix[14];
    const cartoPosition = ellipsoid.cartesianToCartographic(scratchPosition$3);

    if (!defined(model._clampedModelMatrix)) {
      model._clampedModelMatrix = Matrix4.clone(modelMatrix, new Matrix4());
    }

    // Install callback to handle updating of terrain tiles
    const surface = globe._surface;
    model._removeUpdateHeightCallback = surface.updateHeight(
      cartoPosition,
      getUpdateHeightCallback(model, ellipsoid, cartoPosition)
    );

    // Set the correct height now
    const height = globe.getHeight(cartoPosition);
    if (defined(height)) {
      // Get callback with cartoPosition being the non-clamped position
      const callback = getUpdateHeightCallback(model, ellipsoid, cartoPosition);

      // Compute the clamped cartesian and call updateHeight callback
      Cartographic.clone(cartoPosition, scratchCartographic$a);
      scratchCartographic$a.height = height;
      ellipsoid.cartographicToCartesian(scratchCartographic$a, scratchPosition$3);
      callback(scratchPosition$3);
    }

    model._heightDirty = false;
    model._updateModelMatrix = true;
  }

  function updateBoundingSphereAndScale(model, frameState) {
    if (!model._updateModelMatrix && model._minimumPixelSize === 0.0) {
      return;
    }

    const modelMatrix = defined(model._clampedModelMatrix)
      ? model._clampedModelMatrix
      : model.modelMatrix;

    model._clampedScale = defined(model._maximumScale)
      ? Math.min(model._scale, model._maximumScale)
      : model._scale;

    model._boundingSphere = BoundingSphere.transform(
      model._sceneGraph.boundingSphere,
      modelMatrix,
      model._boundingSphere
    );
    model._boundingSphere.radius = model._initialRadius * model._clampedScale;
    model._computedScale = getScale(model, modelMatrix, frameState);
  }

  function updatePickIds(model) {
    if (!model._idDirty) {
      return;
    }
    model._idDirty = false;

    const id = model._id;
    const pickIds = model._pickIds;
    const length = pickIds.length;
    for (let i = 0; i < length; ++i) {
      pickIds[i].object.id = id;
    }
  }

  function updateReferenceMatrices(model, frameState) {
    const modelMatrix = defined(model._clampedModelMatrix)
      ? model._clampedModelMatrix
      : model.modelMatrix;
    const referenceMatrix = defaultValue(model.referenceMatrix, modelMatrix);
    const context = frameState.context;

    const ibl = model._imageBasedLighting;
    if (ibl.useSphericalHarmonicCoefficients || ibl.useSpecularEnvironmentMaps) {
      let iblReferenceFrameMatrix3 = scratchIBLReferenceFrameMatrix3;
      let iblReferenceFrameMatrix4 = scratchIBLReferenceFrameMatrix4;

      iblReferenceFrameMatrix4 = Matrix4.multiply(
        context.uniformState.view3D,
        referenceMatrix,
        iblReferenceFrameMatrix4
      );
      iblReferenceFrameMatrix3 = Matrix4.getMatrix3(
        iblReferenceFrameMatrix4,
        iblReferenceFrameMatrix3
      );
      iblReferenceFrameMatrix3 = Matrix3.getRotation(
        iblReferenceFrameMatrix3,
        iblReferenceFrameMatrix3
      );
      model._iblReferenceFrameMatrix = Matrix3.transpose(
        iblReferenceFrameMatrix3,
        model._iblReferenceFrameMatrix
      );
    }

    if (model.isClippingEnabled()) {
      let clippingPlanesMatrix = scratchClippingPlanesMatrix$1;
      clippingPlanesMatrix = Matrix4.multiply(
        context.uniformState.view3D,
        referenceMatrix,
        clippingPlanesMatrix
      );
      clippingPlanesMatrix = Matrix4.multiply(
        clippingPlanesMatrix,
        model._clippingPlanes.modelMatrix,
        clippingPlanesMatrix
      );
      model._clippingPlanesMatrix = Matrix4.inverseTranspose(
        clippingPlanesMatrix,
        model._clippingPlanesMatrix
      );
    }
  }

  function updateSceneGraph(model, frameState) {
    const sceneGraph = model._sceneGraph;
    if (model._updateModelMatrix || model._minimumPixelSize !== 0.0) {
      const modelMatrix = defined(model._clampedModelMatrix)
        ? model._clampedModelMatrix
        : model.modelMatrix;
      sceneGraph.updateModelMatrix(modelMatrix, frameState);
      model._updateModelMatrix = false;
    }

    if (model._backFaceCullingDirty) {
      sceneGraph.updateBackFaceCulling(model._backFaceCulling);
      model._backFaceCullingDirty = false;
    }

    if (model._shadowsDirty) {
      sceneGraph.updateShadows(model._shadows);
      model._shadowsDirty = false;
    }

    if (model._debugShowBoundingVolumeDirty) {
      sceneGraph.updateShowBoundingVolume(model._debugShowBoundingVolume);
      model._debugShowBoundingVolumeDirty = false;
    }

    const updateForAnimations = model._activeAnimations.update(frameState);
    sceneGraph.update(frameState, updateForAnimations);
  }

  function updateShowCreditsOnScreen(model) {
    if (!model._showCreditsOnScreenDirty) {
      return;
    }
    model._showCreditsOnScreenDirty = false;

    const showOnScreen = model._showCreditsOnScreen;
    if (defined(model._credit)) {
      model._credit.showOnScreen = showOnScreen;
    }

    const resourceCredits = model._resourceCredits;
    const resourceCreditsLength = resourceCredits.length;
    for (let i = 0; i < resourceCreditsLength; i++) {
      resourceCredits[i].showOnScreen = showOnScreen;
    }

    const gltfCredits = model._gltfCredits;
    const gltfCreditsLength = gltfCredits.length;
    for (let i = 0; i < gltfCreditsLength; i++) {
      gltfCredits[i].showOnScreen = showOnScreen;
    }
  }

  function submitDrawCommands(model, frameState) {
    // Check that show is true after draw commands are built;
    // we want the user to be able to instantly see the model
    // when show is set to true.

    const displayConditionPassed = passesDistanceDisplayCondition(
      model,
      frameState
    );

    const invisible = model.isInvisible();
    const silhouette = model.hasSilhouette(frameState);

    // If the model is invisible but has a silhouette, it still
    // needs to draw in order to write to the stencil buffer and
    // render the silhouette.
    const showModel =
      model._show &&
      model._computedScale !== 0 &&
      displayConditionPassed &&
      (!invisible || silhouette);

    if (showModel) {
      addCreditsToCreditDisplay(model, frameState);
      const drawCommands = model._sceneGraph.getDrawCommands(frameState);
      frameState.commandList.push.apply(frameState.commandList, drawCommands);
    }
  }

  const scratchBoundingSphere$1 = new BoundingSphere();

  function scaleInPixels(positionWC, radius, frameState) {
    scratchBoundingSphere$1.center = positionWC;
    scratchBoundingSphere$1.radius = radius;
    return frameState.camera.getPixelSize(
      scratchBoundingSphere$1,
      frameState.context.drawingBufferWidth,
      frameState.context.drawingBufferHeight
    );
  }

  function getScale(model, modelMatrix, frameState) {
    let scale = model.scale;

    if (model.minimumPixelSize !== 0.0 && !model._projectTo2D) {
      // Compute size of bounding sphere in pixels
      const context = frameState.context;
      const maxPixelSize = Math.max(
        context.drawingBufferWidth,
        context.drawingBufferHeight
      );
      scratchPosition$3.x = modelMatrix[12];
      scratchPosition$3.y = modelMatrix[13];
      scratchPosition$3.z = modelMatrix[14];

      if (model._sceneMode !== SceneMode$1.SCENE3D) {
        SceneTransforms.computeActualWgs84Position(
          frameState,
          scratchPosition$3,
          scratchPosition$3
        );
      }

      const radius = model._boundingSphere.radius;
      const metersPerPixel = scaleInPixels(scratchPosition$3, radius, frameState);

      // metersPerPixel is always > 0.0
      const pixelsPerMeter = 1.0 / metersPerPixel;
      const diameterInPixels = Math.min(
        pixelsPerMeter * (2.0 * radius),
        maxPixelSize
      );

      // Maintain model's minimum pixel size
      if (diameterInPixels < model.minimumPixelSize) {
        scale =
          (model.minimumPixelSize * metersPerPixel) /
          (2.0 * model._initialRadius);
      }
    }

    return defined(model.maximumScale)
      ? Math.min(model.maximumScale, scale)
      : scale;
  }

  function getUpdateHeightCallback(model, ellipsoid, cartoPosition) {
    return function (clampedPosition) {
      if (model.heightReference === HeightReference$1.RELATIVE_TO_GROUND) {
        const clampedCart = ellipsoid.cartesianToCartographic(
          clampedPosition,
          scratchCartographic$a
        );
        clampedCart.height += cartoPosition.height;
        ellipsoid.cartographicToCartesian(clampedCart, clampedPosition);
      }

      const clampedModelMatrix = model._clampedModelMatrix;

      // Modify clamped model matrix to use new height
      Matrix4.clone(model.modelMatrix, clampedModelMatrix);
      clampedModelMatrix[12] = clampedPosition.x;
      clampedModelMatrix[13] = clampedPosition.y;
      clampedModelMatrix[14] = clampedPosition.z;

      model._heightChanged = true;
    };
  }

  const scratchDisplayConditionCartesian = new Cartesian3();

  function passesDistanceDisplayCondition(model, frameState) {
    const condition = model.distanceDisplayCondition;
    if (!defined(condition)) {
      return true;
    }

    const nearSquared = condition.near * condition.near;
    const farSquared = condition.far * condition.far;
    let distanceSquared;

    if (frameState.mode === SceneMode$1.SCENE2D) {
      const frustum2DWidth =
        frameState.camera.frustum.right - frameState.camera.frustum.left;
      const distance = frustum2DWidth * 0.5;
      distanceSquared = distance * distance;
    } else {
      // Distance to center of primitive's reference frame
      const position = Matrix4.getTranslation(
        model.modelMatrix,
        scratchDisplayConditionCartesian
      );

      // This will project the position if the scene is in Columbus View,
      // but leave the position as-is in 3D mode.
      SceneTransforms.computeActualWgs84Position(frameState, position, position);

      distanceSquared = Cartesian3.distanceSquared(
        position,
        frameState.camera.positionWC
      );
    }

    return distanceSquared >= nearSquared && distanceSquared <= farSquared;
  }

  function addCreditsToCreditDisplay(model, frameState) {
    const creditDisplay = frameState.creditDisplay;
    // Add all credits to the credit display.
    const credit = model._credit;
    if (defined(credit)) {
      creditDisplay.addCredit(credit);
    }

    const resourceCredits = model._resourceCredits;
    const resourceCreditsLength = resourceCredits.length;
    for (let c = 0; c < resourceCreditsLength; c++) {
      creditDisplay.addCredit(resourceCredits[c]);
    }

    const gltfCredits = model._gltfCredits;
    const gltfCreditsLength = gltfCredits.length;
    for (let c = 0; c < gltfCreditsLength; c++) {
      creditDisplay.addCredit(gltfCredits[c]);
    }
  }

  /**
   * Gets whether or not the model is translucent based on its assigned model color.
   * If the model color's alpha is equal to zero, then it is considered invisible,
   * not translucent.
   *
   * @returns {Boolean} <code>true</code> if the model is translucent, <code>false</code>.
   * @private
   */
  ModelExperimental.prototype.isTranslucent = function () {
    const color = this.color;
    return defined(color) && color.alpha > 0.0 && color.alpha < 1.0;
  };

  /**
   * Gets whether or not the model is invisible, i.e. if the model color's alpha
   * is equal to zero.
   *
   * @returns {Boolean} <code>true</code> if the model is invisible, <code>false</code>.
   * @private
   */
  ModelExperimental.prototype.isInvisible = function () {
    const color = this.color;
    return defined(color) && color.alpha === 0.0;
  };

  function supportsSilhouettes(frameState) {
    return frameState.context.stencilBuffer;
  }

  /**
   * Gets whether or not the model has a silhouette. This accounts for whether
   * silhouettes are supported (i.e. the context supports stencil buffers).
   *
   * @returns {Boolean} <code>true</code> if the model has silhouettes, <code>false</code>.
   * @private
   */
  ModelExperimental.prototype.hasSilhouette = function (frameState) {
    return (
      supportsSilhouettes(frameState) &&
      this._silhouetteSize > 0.0 &&
      this._silhouetteColor.alpha > 0.0
    );
  };

  /**
   * Gets whether or not clipping planes are enabled for this model.
   *
   * @returns {Boolean} <code>true</code> if clipping planes are enabled for this model, <code>false</code>.
   * @private
   */
  ModelExperimental.prototype.isClippingEnabled = function () {
    const clippingPlanes = this._clippingPlanes;
    return (
      defined(clippingPlanes) &&
      clippingPlanes.enabled &&
      clippingPlanes.length !== 0
    );
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see ModelExperimental#destroy
   */
  ModelExperimental.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * model = model && model.destroy();
   *
   * @see ModelExperimental#isDestroyed
   */
  ModelExperimental.prototype.destroy = function () {
    const loader = this._loader;
    if (defined(loader)) {
      loader.destroy();
    }

    const featureTables = this._featureTables;
    if (defined(featureTables)) {
      const length = featureTables.length;
      for (let i = 0; i < length; i++) {
        featureTables[i].destroy();
      }
    }

    this.destroyPipelineResources();
    this.destroyModelResources();

    // Remove callbacks for height reference behavior.
    if (defined(this._removeUpdateHeightCallback)) {
      this._removeUpdateHeightCallback();
      this._removeUpdateHeightCallback = undefined;
    }

    if (defined(this._terrainProviderChangedCallback)) {
      this._terrainProviderChangedCallback();
      this._terrainProviderChangedCallback = undefined;
    }

    // Only destroy the ClippingPlaneCollection if this is the owner.
    const clippingPlaneCollection = this._clippingPlanes;
    if (
      defined(clippingPlaneCollection) &&
      !clippingPlaneCollection.isDestroyed() &&
      clippingPlaneCollection.owner === this
    ) {
      clippingPlaneCollection.destroy();
    }
    this._clippingPlanes = undefined;

    // Only destroy the ImageBasedLighting if this is the owner.
    if (
      this._shouldDestroyImageBasedLighting &&
      !this._imageBasedLighting.isDestroyed()
    ) {
      this._imageBasedLighting.destroy();
    }
    this._imageBasedLighting = undefined;

    destroyObject(this);
  };

  /**
   * Destroys resources generated in the pipeline stages
   * that must be destroyed when draw commands are rebuilt.
   * @private
   */
  ModelExperimental.prototype.destroyPipelineResources = function () {
    const resources = this._pipelineResources;
    for (let i = 0; i < resources.length; i++) {
      resources[i].destroy();
    }
    this._pipelineResources.length = 0;
    this._pickIds.length = 0;
  };

  /**
   * Destroys resources generated in the pipeline stages
   * that exist for the lifetime of the model.
   * @private
   */
  ModelExperimental.prototype.destroyModelResources = function () {
    const resources = this._modelResources;
    for (let i = 0; i < resources.length; i++) {
      resources[i].destroy();
    }
    this._modelResources.length = 0;
  };

  /**
   * <p>
   * Creates a model from a glTF asset.  When the model is ready to render, i.e., when the external binary, image,
   * and shader files are downloaded and the WebGL resources are created, the {@link Model#readyPromise} is resolved.
   * </p>
   * <p>
   * The model can be a traditional glTF asset with a .gltf extension or a Binary glTF using the .glb extension.
   *
   * @param {Object} options Object with the following properties:
   * @param {String|Resource} options.url The url to the .gltf or .glb file.
   * @param {String|Resource} [options.basePath=''] The base path that paths in the glTF JSON are relative to.
   * @param {Boolean} [options.show=true] Whether or not to render the model.
   * @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] The 4x4 transformation matrix that transforms the model from model to world coordinates.
   * @param {Number} [options.scale=1.0] A uniform scale applied to this model.
   * @param {Number} [options.minimumPixelSize=0.0] The approximate minimum pixel size of the model regardless of zoom.
   * @param {Number} [options.maximumScale] The maximum scale size of a model. An upper limit for minimumPixelSize.
   * @param {Object} [options.id] A user-defined object to return when the model is picked with {@link Scene#pick}.
   * @param {Boolean} [options.allowPicking=true] When <code>true</code>, each primitive is pickable with {@link Scene#pick}.
   * @param {Boolean} [options.incrementallyLoadTextures=true] Determine if textures may continue to stream in after the model is loaded.
   * @param {Boolean} [options.asynchronous=true] Determines if model WebGL resource creation will be spread out over several frames or block until completion once all glTF files are loaded.
   * @param {Boolean} [options.clampAnimations=true] Determines if the model's animations should hold a pose over frames where no keyframes are specified.
   * @param {ShadowMode} [options.shadows=ShadowMode.ENABLED] Determines whether the model casts or receives shadows from light sources.
   * @param {Boolean} [options.releaseGltfJson=false] When true, the glTF JSON is released once the glTF is loaded. This is is especially useful for cases like 3D Tiles, where each .gltf model is unique and caching the glTF JSON is not effective.
   * @param {Boolean} [options.debugShowBoundingVolume=false] For debugging only. Draws the bounding sphere for each draw command in the model.
   * @param {Boolean} [options.enableDebugWireframe=false] For debugging only. This must be set to true for debugWireframe to work in WebGL1. This cannot be set after the model has loaded.
   * @param {Boolean} [options.debugWireframe=false] For debugging only. Draws the model in wireframe. Will only work for WebGL1 if enableDebugWireframe is set to true.
   * @param {Boolean} [options.cull=true]  Whether or not to cull the model using frustum/horizon culling. If the model is part of a 3D Tiles tileset, this property will always be false, since the 3D Tiles culling system is used.
   * @param {Boolean} [options.opaquePass=Pass.OPAQUE] The pass to use in the {@link DrawCommand} for the opaque portions of the model.
   * @param {Axis} [options.upAxis=Axis.Y] The up-axis of the glTF model.
   * @param {Axis} [options.forwardAxis=Axis.Z] The forward-axis of the glTF model.
   * @param {CustomShader} [options.customShader] A custom shader. This will add user-defined GLSL code to the vertex and fragment shaders. Using custom shaders with a {@link Cesium3DTileStyle} may lead to undefined behavior.
   * @param {Cesium3DTileContent} [options.content] The tile content this model belongs to. This property will be undefined if model is not loaded as part of a tileset.
   * @param {HeightReference} [options.heightReference=HeightReference.NONE] Determines how the model is drawn relative to terrain.
   * @param {Scene} [options.scene] Must be passed in for models that use the height reference property.
   * @param {DistanceDisplayCondition} [options.distanceDisplayCondition] The condition specifying at what distance from the camera that this model will be displayed.
   * @param {Color} [options.color] A color that blends with the model's rendered color.
   * @param {ColorBlendMode} [options.colorBlendMode=ColorBlendMode.HIGHLIGHT] Defines how the color blends with the model.
   * @param {Number} [options.colorBlendAmount=0.5] Value used to determine the color strength when the <code>colorBlendMode</code> is <code>MIX</code>. A value of 0.0 results in the model's rendered color while a value of 1.0 results in a solid color, with any value in-between resulting in a mix of the two.
   * @param {Color} [options.silhouetteColor=Color.RED] The silhouette color. If more than 256 models have silhouettes enabled, there is a small chance that overlapping models will have minor artifacts.
   * @param {Number} [options.silhouetteSize=0.0] The size of the silhouette in pixels.
   * @param {ClippingPlaneCollection} [options.clippingPlanes] The {@link ClippingPlaneCollection} used to selectively disable rendering the model.
   * @param {Cartesian3} [options.lightColor] The light color when shading the model. When <code>undefined</code> the scene's light color is used instead.
   * @param {ImageBasedLighting} [options.imageBasedLighting] The properties for managing image-based lighting on this model.
   * @param {Boolean} [options.backFaceCulling=true] Whether to cull back-facing geometry. When true, back face culling is determined by the material's doubleSided property; when false, back face culling is disabled. Back faces are not culled if the model's color is translucent.
   * @param {Credit|String} [options.credit] A credit for the data source, which is displayed on the canvas.
   * @param {Boolean} [options.showCreditsOnScreen=false] Whether to display the credits of this model on screen.
   * @param {SplitDirection} [options.splitDirection=SplitDirection.NONE] The {@link SplitDirection} split to apply to this model.
   * @param {Boolean} [options.projectTo2D=false] Whether to accurately project the model's positions in 2D. If this is true, the model will be projected accurately to 2D, but it will use more memory to do so. If this is false, the model will use less memory and will still render in 2D / CV mode, but its positions may be inaccurate. This disables minimumPixelSize and prevents future modification to the model matrix. This also cannot be set after the model has loaded.
   * @param {String|Number} [options.featureIdLabel="featureId_0"] Label of the feature ID set to use for picking and styling. For EXT_mesh_features, this is the feature ID's label property, or "featureId_N" (where N is the index in the featureIds array) when not specified. EXT_feature_metadata did not have a label field, so such feature ID sets are always labeled "featureId_N" where N is the index in the list of all feature Ids, where feature ID attributes are listed before feature ID textures. If featureIdLabel is an integer N, it is converted to the string "featureId_N" automatically. If both per-primitive and per-instance feature IDs are present, the instance feature IDs take priority.
   * @param {String|Number} [options.instanceFeatureIdLabel="instanceFeatureId_0"] Label of the instance feature ID set used for picking and styling. If instanceFeatureIdLabel is set to an integer N, it is converted to the string "instanceFeatureId_N" automatically. If both per-primitive and per-instance feature IDs are present, the instance feature IDs take priority.
   * @param {Object} [options.pointCloudShading] Options for constructing a {@link PointCloudShading} object to control point attenuation and lighting.
   * @returns {ModelExperimental} The newly created model.
   */
  ModelExperimental.fromGltf = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    if (!defined(options.url) && !defined(options.gltf)) {
      throw new DeveloperError("options.url is required.");
    }
    //>>includeEnd('debug');

    // options.gltf is used internally for 3D Tiles. It can be a Resource, a URL
    // to a glTF/glb file, a binary glTF buffer, or a JSON object containing the
    // glTF contents.
    const gltf = defaultValue(options.url, options.gltf);

    const loaderOptions = {
      releaseGltfJson: options.releaseGltfJson,
      asynchronous: options.asynchronous,
      incrementallyLoadTextures: options.incrementallyLoadTextures,
      upAxis: options.upAxis,
      forwardAxis: options.forwardAxis,
      loadAttributesFor2D: options.projectTo2D,
      loadIndicesForWireframe: options.enableDebugWireframe,
    };

    const basePath = defaultValue(options.basePath, "");
    const baseResource = Resource.createIfNeeded(basePath);

    if (defined(gltf.asset)) {
      loaderOptions.gltfJson = gltf;
      loaderOptions.baseResource = baseResource;
      loaderOptions.gltfResource = baseResource;
    } else if (gltf instanceof Uint8Array) {
      loaderOptions.typedArray = gltf;
      loaderOptions.baseResource = baseResource;
      loaderOptions.gltfResource = baseResource;
    } else {
      loaderOptions.gltfResource = Resource.createIfNeeded(gltf);
    }

    const loader = new GltfLoader(loaderOptions);

    const is3DTiles = defined(options.content);
    const type = is3DTiles
      ? ModelExperimentalType$1.TILE_GLTF
      : ModelExperimentalType$1.GLTF;

    const modelOptions = makeModelOptions$1(loader, type, options);
    modelOptions.resource = loaderOptions.gltfResource;

    const model = new ModelExperimental(modelOptions);

    return model;
  };

  /*
   * @private
   */
  ModelExperimental.fromB3dm = function (options) {
    const loaderOptions = {
      b3dmResource: options.resource,
      arrayBuffer: options.arrayBuffer,
      byteOffset: options.byteOffset,
      releaseGltfJson: options.releaseGltfJson,
      asynchronous: options.asynchronous,
      incrementallyLoadTextures: options.incrementallyLoadTextures,
      upAxis: options.upAxis,
      forwardAxis: options.forwardAxis,
      loadAttributesFor2D: options.projectTo2D,
      loadIndicesForWireframe: options.enableDebugWireframe,
    };

    const loader = new B3dmLoader(loaderOptions);

    const modelOptions = makeModelOptions$1(
      loader,
      ModelExperimentalType$1.TILE_B3DM,
      options
    );
    const model = new ModelExperimental(modelOptions);
    return model;
  };

  /**
   * @private
   */
  ModelExperimental.fromPnts = function (options) {
    const loaderOptions = {
      arrayBuffer: options.arrayBuffer,
      byteOffset: options.byteOffset,
    };
    const loader = new PntsLoader(loaderOptions);

    const modelOptions = makeModelOptions$1(
      loader,
      ModelExperimentalType$1.TILE_PNTS,
      options
    );
    const model = new ModelExperimental(modelOptions);
    return model;
  };

  /*
   * @private
   */
  ModelExperimental.fromI3dm = function (options) {
    const loaderOptions = {
      i3dmResource: options.resource,
      arrayBuffer: options.arrayBuffer,
      byteOffset: options.byteOffset,
      releaseGltfJson: options.releaseGltfJson,
      asynchronous: options.asynchronous,
      incrementallyLoadTextures: options.incrementallyLoadTextures,
      upAxis: options.upAxis,
      forwardAxis: options.forwardAxis,
      loadAttributesFor2D: options.projectTo2D,
      loadIndicesForWireframe: options.enableDebugWireframe,
    };
    const loader = new I3dmLoader(loaderOptions);

    const modelOptions = makeModelOptions$1(
      loader,
      ModelExperimentalType$1.TILE_I3DM,
      options
    );
    const model = new ModelExperimental(modelOptions);
    return model;
  };

  /*
   * @private
   */
  ModelExperimental.fromGeoJson = function (options) {
    const loaderOptions = {
      geoJson: options.geoJson,
    };
    const loader = new GeoJsonLoader(loaderOptions);
    const modelOptions = makeModelOptions$1(
      loader,
      ModelExperimentalType$1.TILE_GEOJSON,
      options
    );
    const model = new ModelExperimental(modelOptions);
    return model;
  };

  /**
   * @private
   */
  ModelExperimental.prototype.applyColorAndShow = function (style) {
    const hasColorStyle = defined(style) && defined(style.color);
    const hasShowStyle = defined(style) && defined(style.show);

    this._color = hasColorStyle
      ? style.color.evaluateColor(undefined, this._color)
      : Color.clone(Color.WHITE, this._color);
    this._show = hasShowStyle ? style.show.evaluate(undefined) : true;
  };

  /**
   * @private
   */
  ModelExperimental.prototype.applyStyle = function (style) {
    // The style is only set by the ModelFeatureTable. If there are no features,
    // the color and show from the style are directly applied.
    if (
      defined(this.featureTableId) &&
      this.featureTables[this.featureTableId].featuresLength > 0
    ) {
      const featureTable = this.featureTables[this.featureTableId];
      featureTable.applyStyle(style);
    } else {
      this.applyColorAndShow(style);
    }

    this.resetDrawCommands();
  };

  function makeModelOptions$1(loader, modelType, options) {
    return {
      loader: loader,
      type: modelType,
      resource: options.resource,
      show: options.show,
      modelMatrix: options.modelMatrix,
      scale: options.scale,
      minimumPixelSize: options.minimumPixelSize,
      maximumScale: options.maximumScale,
      id: options.id,
      allowPicking: options.allowPicking,
      clampAnimations: options.clampAnimations,
      shadows: options.shadows,
      debugShowBoundingVolume: options.debugShowBoundingVolume,
      enableDebugWireframe: options.enableDebugWireframe,
      debugWireframe: options.debugWireframe,
      cull: options.cull,
      opaquePass: options.opaquePass,
      customShader: options.customShader,
      content: options.content,
      heightReference: options.heightReference,
      scene: options.scene,
      distanceDisplayCondition: options.distanceDisplayCondition,
      color: options.color,
      colorBlendAmount: options.colorBlendAmount,
      colorBlendMode: options.colorBlendMode,
      silhouetteColor: options.silhouetteColor,
      silhouetteSize: options.silhouetteSize,
      clippingPlanes: options.clippingPlanes,
      lightColor: options.lightColor,
      imageBasedLighting: options.imageBasedLighting,
      backFaceCulling: options.backFaceCulling,
      credit: options.credit,
      showCreditsOnScreen: options.showCreditsOnScreen,
      splitDirection: options.splitDirection,
      projectTo2D: options.projectTo2D,
      featureIdLabel: options.featureIdLabel,
      instanceFeatureIdLabel: options.instanceFeatureIdLabel,
      pointCloudShading: options.pointCloudShading,
    };
  }

  /**
   * Represents the contents of a glTF, glb or
   * {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/TileFormats/Batched3DModel|Batched 3D Model}
   * tile in a {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification|3D Tiles} tileset.
   * <p>
   * Implements the {@link Cesium3DTileContent} interface.
   * </p>
   * @alias ModelExperimental3DTileContent
   * @constructor
   * @private
   */
  function ModelExperimental3DTileContent(
    tileset,
    tile,
    resource
  ) {
    this._tileset = tileset;
    this._tile = tile;
    this._resource = resource;

    this._model = undefined;
    this._metadata = undefined;
    this._group = undefined;
  }

  Object.defineProperties(ModelExperimental3DTileContent.prototype, {
    featuresLength: {
      get: function () {
        const model = this._model;
        const featureTables = model.featureTables;
        const featureTableId = model.featureTableId;

        if (defined(featureTables) && defined(featureTables[featureTableId])) {
          return featureTables[featureTableId].featuresLength;
        }

        return 0;
      },
    },

    pointsLength: {
      get: function () {
        return this._model.statistics.pointsLength;
      },
    },

    trianglesLength: {
      get: function () {
        return this._model.statistics.trianglesLength;
      },
    },

    geometryByteLength: {
      get: function () {
        return this._model.statistics.geometryByteLength;
      },
    },

    texturesByteLength: {
      get: function () {
        return this._model.statistics.texturesByteLength;
      },
    },

    batchTableByteLength: {
      get: function () {
        return this._model.statistics.propertyTablesByteLength;
      },
    },

    innerContents: {
      get: function () {
        return undefined;
      },
    },

    readyPromise: {
      get: function () {
        return this._model.readyPromise;
      },
    },

    tileset: {
      get: function () {
        return this._tileset;
      },
    },

    tile: {
      get: function () {
        return this._tile;
      },
    },

    url: {
      get: function () {
        return this._resource.getUrlComponent(true);
      },
    },

    batchTable: {
      get: function () {
        const model = this._model;
        const featureTables = model.featureTables;
        const featureTableId = model.featureTableId;

        if (defined(featureTables) && defined(featureTables[featureTableId])) {
          return featureTables[featureTableId];
        }

        return undefined;
      },
    },

    metadata: {
      get: function () {
        return this._metadata;
      },
      set: function (value) {
        this._metadata = value;
      },
    },

    group: {
      get: function () {
        return this._group;
      },
      set: function (value) {
        this._group = value;
      },
    },
  });

  ModelExperimental3DTileContent.prototype.getFeature = function (featureId) {
    const model = this._model;
    const featureTableId = model.featureTableId;
    if (!defined(featureTableId)) {
      return undefined;
    }

    const featureTable = model.featureTables[featureTableId];
    return featureTable.getFeature(featureId);
  };

  ModelExperimental3DTileContent.prototype.hasProperty = function (
    featureId,
    name
  ) {
    const model = this._model;
    const featureTableId = model.featureTableId;
    if (!defined(featureTableId)) {
      return false;
    }

    const featureTable = model.featureTables[featureTableId];
    return featureTable.hasProperty(featureId, name);
  };

  ModelExperimental3DTileContent.prototype.applyDebugSettings = function (
    enabled,
    color
  ) {
    color = enabled ? color : Color.WHITE;
    if (this.featuresLength === 0) {
      this._model.color = color;
    } else if (defined(this.batchTable)) {
      this.batchTable.setAllColor(color);
    }
  };

  ModelExperimental3DTileContent.prototype.applyStyle = function (style) {
    // the setter will call model.applyStyle()
    this._model.style = style;
  };

  ModelExperimental3DTileContent.prototype.update = function (
    tileset,
    frameState
  ) {
    const model = this._model;
    const tile = this._tile;

    model.colorBlendAmount = tileset.colorBlendAmount;
    model.colorBlendMode = tileset.colorBlendMode;
    model.modelMatrix = tile.computedTransform;
    model.customShader = tileset.customShader;
    model.pointCloudShading = tileset.pointCloudShading;
    model.featureIdLabel = tileset.featureIdLabel;
    model.instanceFeatureIdLabel = tileset.instanceFeatureIdLabel;
    model.lightColor = tileset.lightColor;
    model.imageBasedLighting = tileset.imageBasedLighting;
    model.backFaceCulling = tileset.backFaceCulling;
    model.shadows = tileset.shadows;
    model.showCreditsOnScreen = tileset.showCreditsOnScreen;
    model.splitDirection = tileset.splitDirection;
    model.debugWireframe = tileset.debugWireframe;

    // Updating clipping planes requires more effort because of ownership checks
    const tilesetClippingPlanes = tileset.clippingPlanes;
    model.referenceMatrix = tileset.clippingPlanesOriginMatrix;
    if (defined(tilesetClippingPlanes) && tile.clippingPlanesDirty) {
      // Dereference the clipping planes from the model if they are irrelevant.
      model._clippingPlanes =
        tilesetClippingPlanes.enabled && tile._isClipped
          ? tilesetClippingPlanes
          : undefined;
    }

    // If the model references a different ClippingPlaneCollection from the tileset,
    // update the model to use the new ClippingPlaneCollection.
    if (
      defined(tilesetClippingPlanes) &&
      defined(model._clippingPlanes) &&
      model._clippingPlanes !== tilesetClippingPlanes
    ) {
      model._clippingPlanes = tilesetClippingPlanes;
    }

    model.update(frameState);
  };

  ModelExperimental3DTileContent.prototype.isDestroyed = function () {
    return false;
  };

  ModelExperimental3DTileContent.prototype.destroy = function () {
    this._model = this._model && this._model.destroy();
    return destroyObject(this);
  };

  ModelExperimental3DTileContent.fromGltf = function (
    tileset,
    tile,
    resource,
    gltf
  ) {
    const content = new ModelExperimental3DTileContent(tileset, tile, resource);

    const additionalOptions = {
      gltf: gltf,
      basePath: resource,
    };

    const modelOptions = makeModelOptions(
      tileset,
      tile,
      content,
      additionalOptions
    );
    content._model = ModelExperimental.fromGltf(modelOptions);
    return content;
  };

  ModelExperimental3DTileContent.fromB3dm = function (
    tileset,
    tile,
    resource,
    arrayBuffer,
    byteOffset
  ) {
    const content = new ModelExperimental3DTileContent(tileset, tile, resource);

    const additionalOptions = {
      arrayBuffer: arrayBuffer,
      byteOffset: byteOffset,
      resource: resource,
    };

    const modelOptions = makeModelOptions(
      tileset,
      tile,
      content,
      additionalOptions
    );
    content._model = ModelExperimental.fromB3dm(modelOptions);
    return content;
  };

  ModelExperimental3DTileContent.fromI3dm = function (
    tileset,
    tile,
    resource,
    arrayBuffer,
    byteOffset
  ) {
    const content = new ModelExperimental3DTileContent(tileset, tile, resource);

    const additionalOptions = {
      arrayBuffer: arrayBuffer,
      byteOffset: byteOffset,
      resource: resource,
    };

    const modelOptions = makeModelOptions(
      tileset,
      tile,
      content,
      additionalOptions
    );
    content._model = ModelExperimental.fromI3dm(modelOptions);
    return content;
  };

  ModelExperimental3DTileContent.fromPnts = function (
    tileset,
    tile,
    resource,
    arrayBuffer,
    byteOffset
  ) {
    const content = new ModelExperimental3DTileContent(tileset, tile, resource);

    const additionalOptions = {
      arrayBuffer: arrayBuffer,
      byteOffset: byteOffset,
      resource: resource,
    };

    const modelOptions = makeModelOptions(
      tileset,
      tile,
      content,
      additionalOptions
    );
    content._model = ModelExperimental.fromPnts(modelOptions);
    return content;
  };

  ModelExperimental3DTileContent.fromGeoJson = function (
    tileset,
    tile,
    resource,
    geoJson
  ) {
    const content = new ModelExperimental3DTileContent(tileset, tile, resource);

    const additionalOptions = {
      geoJson: geoJson,
      resource: resource,
    };

    const modelOptions = makeModelOptions(
      tileset,
      tile,
      content,
      additionalOptions
    );
    content._model = ModelExperimental.fromGeoJson(modelOptions);
    return content;
  };

  function makeModelOptions(tileset, tile, content, additionalOptions) {
    const mainOptions = {
      cull: false, // The model is already culled by 3D Tiles
      releaseGltfJson: true, // Models are unique and will not benefit from caching so save memory
      opaquePass: Pass$1.CESIUM_3D_TILE, // Draw opaque portions of the model during the 3D Tiles pass
      modelMatrix: tile.computedTransform,
      upAxis: tileset._modelUpAxis,
      forwardAxis: tileset._modelForwardAxis,
      incrementallyLoadTextures: false,
      customShader: tileset.customShader,
      content: content,
      show: tileset.show,
      colorBlendMode: tileset.colorBlendMode,
      colorBlendAmount: tileset.colorBlendAmount,
      lightColor: tileset.lightColor,
      imageBasedLighting: tileset.imageBasedLighting,
      featureIdLabel: tileset.featureIdLabel,
      instanceFeatureIdLabel: tileset.instanceFeatureIdLabel,
      pointCloudShading: tileset.pointCloudShading,
      clippingPlanes: tileset.clippingPlanes,
      backFaceCulling: tileset.backFaceCulling,
      shadows: tileset.shadows,
      showCreditsOnScreen: tileset.showCreditsOnScreen,
      splitDirection: tileset.splitDirection,
      enableDebugWireframe: tileset._enableDebugWireframe,
      debugWireframe: tileset.debugWireframe,
      projectTo2D: tileset._projectTo2D,
    };

    return combine$2(additionalOptions, mainOptions);
  }

  /**
   * Maps a tile's magic field in its header to a new content object for the tile's payload.
   *
   * @private
   */
  const Cesium3DTileContentFactory = {
    b3dm: function (tileset, tile, resource, arrayBuffer, byteOffset) {
      if (tileset.enableModelExperimental) {
        return ModelExperimental3DTileContent.fromB3dm(
          tileset,
          tile,
          resource,
          arrayBuffer,
          byteOffset
        );
      }
      return new Batched3DModel3DTileContent(
        tileset,
        tile,
        resource,
        arrayBuffer,
        byteOffset
      );
    },
    pnts: function (tileset, tile, resource, arrayBuffer, byteOffset) {
      if (tileset.enableModelExperimental) {
        return ModelExperimental3DTileContent.fromPnts(
          tileset,
          tile,
          resource,
          arrayBuffer,
          byteOffset
        );
      }
      return new PointCloud3DTileContent(
        tileset,
        tile,
        resource,
        arrayBuffer,
        byteOffset
      );
    },
    i3dm: function (tileset, tile, resource, arrayBuffer, byteOffset) {
      if (tileset.enableModelExperimental) {
        return ModelExperimental3DTileContent.fromI3dm(
          tileset,
          tile,
          resource,
          arrayBuffer,
          byteOffset
        );
      }
      return new Instanced3DModel3DTileContent(
        tileset,
        tile,
        resource,
        arrayBuffer,
        byteOffset
      );
    },
    cmpt: function (tileset, tile, resource, arrayBuffer, byteOffset) {
      // Send in the factory in order to avoid a cyclical dependency
      return new Composite3DTileContent(
        tileset,
        tile,
        resource,
        arrayBuffer,
        byteOffset,
        Cesium3DTileContentFactory
      );
    },
    externalTileset: function (tileset, tile, resource, json) {
      return new Tileset3DTileContent(tileset, tile, resource, json);
    },
    geom: function (tileset, tile, resource, arrayBuffer, byteOffset) {
      return new Geometry3DTileContent(
        tileset,
        tile,
        resource,
        arrayBuffer,
        byteOffset
      );
    },
    vctr: function (tileset, tile, resource, arrayBuffer, byteOffset) {
      return new Vector3DTileContent(
        tileset,
        tile,
        resource,
        arrayBuffer,
        byteOffset
      );
    },
    subt: function (tileset, tile, resource, arrayBuffer, byteOffset) {
      return new Implicit3DTileContent(
        tileset,
        tile,
        resource,
        undefined,
        arrayBuffer,
        byteOffset
      );
    },
    subtreeJson: function (tileset, tile, resource, json) {
      return new Implicit3DTileContent(tileset, tile, resource, json);
    },
    glb: function (tileset, tile, resource, arrayBuffer, byteOffset) {
      const arrayBufferByteLength = arrayBuffer.byteLength;
      if (arrayBufferByteLength < 12) {
        throw new RuntimeError("Invalid glb content");
      }
      const dataView = new DataView(arrayBuffer, byteOffset);
      const byteLength = dataView.getUint32(8, true);
      const glb = new Uint8Array(arrayBuffer, byteOffset, byteLength);
      return ModelExperimental3DTileContent.fromGltf(
        tileset,
        tile,
        resource,
        glb
      );
    },
    gltf: function (tileset, tile, resource, json) {
      return ModelExperimental3DTileContent.fromGltf(
        tileset,
        tile,
        resource,
        json
      );
    },
    geoJson: function (tileset, tile, resource, json) {
      return ModelExperimental3DTileContent.fromGeoJson(
        tileset,
        tile,
        resource,
        json
      );
    },
  };

  /**
   * @private
   */
  const Cesium3DTileContentState = {
    UNLOADED: 0, // Has never been requested
    LOADING: 1, // Is waiting on a pending request
    PROCESSING: 2, // Request received.  Contents are being processed for rendering.  Depending on the content, it might make its own requests for external data.
    READY: 3, // Ready to render.
    EXPIRED: 4, // Is expired and will be unloaded once new content is loaded.
    FAILED: 5, // Request failed.
  };
  var Cesium3DTileContentState$1 = Object.freeze(Cesium3DTileContentState);

  /**
   * An enum to indicate the different types of {@link Cesium3DTileContent}.
   * For binary files, the enum value is the magic number of the binary file
   * unless otherwise noted. For JSON files, the enum value is a unique name
   * for internal use.
   *
   * @enum {String}
   * @see Cesium3DTileContent
   *
   * @private
   */
  const Cesium3DTileContentType = {
    /**
     * A Batched 3D Model. This is a binary format with
     * magic number <code>b3dm</code>
     *
     * @type {String}
     * @constant
     * @private
     */
    BATCHED_3D_MODEL: "b3dm",
    /**
     * An Instanced 3D Model. This is a binary format with magic number
     * <code>i3dm</code>
     *
     * @type {String}
     * @constant
     * @private
     */
    INSTANCED_3D_MODEL: "i3dm",
    /**
     * A Composite model. This is a binary format with magic number
     * <code>cmpt</code>
     *
     * @type {String}
     * @constant
     * @private
     */
    COMPOSITE: "cmpt",
    /**
     * A Point Cloud model. This is a binary format with magic number
     * <code>pnts</code>
     *
     * @type {String}
     * @constant
     * @private
     */
    POINT_CLOUD: "pnts",
    /**
     * Vector tiles. This is a binary format with magic number
     * <code>vctr</code>
     *
     * @type {String}
     * @constant
     * @private
     */
    VECTOR: "vctr",
    /**
     * Geometry tiles. This is a binary format with magic number
     * <code>geom</code>
     *
     * @type {String}
     * @constant
     * @private
     */
    GEOMETRY: "geom",
    /**
     * A glTF model in JSON + external BIN form. This is treated
     * as a JSON format.
     *
     * @type {String}
     * @constant
     * @private
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     */
    GLTF: "gltf",
    /**
     * The binary form of a glTF file. Internally, the magic number is
     * changed from <code>glTF</code> to <code>glb</code> to distinguish it from
     * the JSON glTF format.
     *
     * @type {String}
     * @constant
     * @private
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     */
    GLTF_BINARY: "glb",
    /**
     * For implicit tiling, availability bitstreams are stored in binary subtree files.
     * The magic number is <code>subt</code>
     *
     * @type {String}
     * @constant
     * @private
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     */
    IMPLICIT_SUBTREE: "subt",
    /**
     * For implicit tiling. Subtrees can also be represented as JSON files.
     *
     * @type {String}
     * @constant
     * @private
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     */
    IMPLICIT_SUBTREE_JSON: "subtreeJson",
    /**
     * Contents can reference another tileset.json to use
     * as an external tileset. This is a JSON-based format.
     *
     * @type {String}
     * @constant
     * @private
     */
    EXTERNAL_TILESET: "externalTileset",
    /**
     * Multiple contents are handled separately from the other content types
     * due to differences in request scheduling.
     *
     * @type {String}
     * @constant
     * @private
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     */
    MULTIPLE_CONTENT: "multipleContent",
    /**
     * GeoJSON content for <code>MAXAR_content_geojson</code> extension.
     *
     * @type {String}
     * @constant
     * @private
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     */
    GEOJSON: "geoJson",
  };

  /**
   * Check if a content is one of the supported binary formats. Otherwise,
   * the caller can assume a JSON format.
   * @param {Cesium3DTileContentType} contentType The content type of the content payload.
   * @return {Boolean} <code>true</code> if the content type is a binary format, or <code>false</code> if the content type is a JSON format.
   * @private
   */
  Cesium3DTileContentType.isBinaryFormat = function (contentType) {
    switch (contentType) {
      case Cesium3DTileContentType.BATCHED_3D_MODEL:
      case Cesium3DTileContentType.INSTANCED_3D_MODEL:
      case Cesium3DTileContentType.COMPOSITE:
      case Cesium3DTileContentType.POINT_CLOUD:
      case Cesium3DTileContentType.VECTOR:
      case Cesium3DTileContentType.GEOMETRY:
      case Cesium3DTileContentType.IMPLICIT_SUBTREE:
      case Cesium3DTileContentType.GLTF_BINARY:
        return true;
      default:
        return false;
    }
  };

  var Cesium3DTileContentType$1 = Object.freeze(Cesium3DTileContentType);

  /**
   * Hint defining optimization support for a 3D tile
   *
   * @enum {Number}
   *
   * @private
   */
  const Cesium3DTileOptimizationHint = {
    NOT_COMPUTED: -1,
    USE_OPTIMIZATION: 1,
    SKIP_OPTIMIZATION: 0,
  };
  var Cesium3DTileOptimizationHint$1 = Object.freeze(Cesium3DTileOptimizationHint);

  /**
   * Traversal that loads all leaves that intersect the camera frustum.
   * Used to determine ray-tileset intersections during a pickFromRayMostDetailed call.
   *
   * @private
   */
  function Cesium3DTilesetMostDetailedTraversal() {}

  const traversal$1 = {
    stack: new ManagedArray(),
    stackMaximumLength: 0,
  };

  Cesium3DTilesetMostDetailedTraversal.selectTiles = function (
    tileset,
    frameState
  ) {
    tileset._selectedTiles.length = 0;
    tileset._requestedTiles.length = 0;
    tileset._hasMixedContent = false;

    let ready = true;

    const root = tileset.root;
    root.updateVisibility(frameState);

    if (!isVisible$1(root)) {
      return ready;
    }

    const stack = traversal$1.stack;
    stack.push(tileset.root);

    while (stack.length > 0) {
      traversal$1.stackMaximumLength = Math.max(
        traversal$1.stackMaximumLength,
        stack.length
      );

      const tile = stack.pop();
      const add = tile.refine === Cesium3DTileRefine$1.ADD;
      const replace = tile.refine === Cesium3DTileRefine$1.REPLACE;
      const traverse = canTraverse$1(tileset, tile);

      if (traverse) {
        updateAndPushChildren$1(tileset, tile, stack, frameState);
      }

      if (add || (replace && !traverse)) {
        loadTile$1(tileset, tile);
        touchTile$1(tileset, tile, frameState);
        selectDesiredTile$1(tileset, tile, frameState);

        if (!hasEmptyContent$1(tile) && !tile.contentAvailable) {
          ready = false;
        }
      }

      visitTile$3(tileset);
    }

    traversal$1.stack.trim(traversal$1.stackMaximumLength);

    return ready;
  };

  function isVisible$1(tile) {
    return tile._visible && tile._inRequestVolume;
  }

  function hasEmptyContent$1(tile) {
    return (
      tile.hasEmptyContent || tile.hasTilesetContent || tile.hasImplicitContent
    );
  }

  function hasUnloadedContent$1(tile) {
    return !hasEmptyContent$1(tile) && tile.contentUnloaded;
  }

  function canTraverse$1(tileset, tile) {
    if (tile.children.length === 0) {
      return false;
    }

    if (tile.hasTilesetContent || tile.hasImplicitContent) {
      // Traverse external tileset to visit its root tile
      // Don't traverse if the subtree is expired because it will be destroyed
      return !tile.contentExpired;
    }

    if (tile.hasEmptyContent) {
      return true;
    }

    return true; // Keep traversing until a leave is hit
  }

  function updateAndPushChildren$1(tileset, tile, stack, frameState) {
    const children = tile.children;
    const length = children.length;

    for (let i = 0; i < length; ++i) {
      const child = children[i];
      child.updateVisibility(frameState);
      if (isVisible$1(child)) {
        stack.push(child);
      }
    }
  }

  function loadTile$1(tileset, tile) {
    if (hasUnloadedContent$1(tile) || tile.contentExpired) {
      tile._priority = 0.0; // Highest priority
      tileset._requestedTiles.push(tile);
    }
  }

  function touchTile$1(tileset, tile, frameState) {
    if (tile._touchedFrame === frameState.frameNumber) {
      // Prevents another pass from touching the frame again
      return;
    }
    tileset._cache.touch(tile);
    tile._touchedFrame = frameState.frameNumber;
  }

  function visitTile$3(tileset) {
    ++tileset.statistics.visited;
  }

  function selectDesiredTile$1(tileset, tile, frameState) {
    if (
      tile.contentAvailable &&
      tile.contentVisibility(frameState) !== Intersect$1.OUTSIDE
    ) {
      tileset._selectedTiles.push(tile);
    }
  }

  /**
   * @private
   */
  function Cesium3DTilesetTraversal() {}

  function isVisible(tile) {
    return tile._visible && tile._inRequestVolume;
  }

  const traversal = {
    stack: new ManagedArray(),
    stackMaximumLength: 0,
  };

  const emptyTraversal = {
    stack: new ManagedArray(),
    stackMaximumLength: 0,
  };

  const descendantTraversal = {
    stack: new ManagedArray(),
    stackMaximumLength: 0,
  };

  const selectionTraversal = {
    stack: new ManagedArray(),
    stackMaximumLength: 0,
    ancestorStack: new ManagedArray(),
    ancestorStackMaximumLength: 0,
  };

  const descendantSelectionDepth = 2;

  Cesium3DTilesetTraversal.selectTiles = function (tileset, frameState) {
    tileset._requestedTiles.length = 0;

    if (tileset.debugFreezeFrame) {
      return;
    }

    tileset._selectedTiles.length = 0;
    tileset._selectedTilesToStyle.length = 0;
    tileset._emptyTiles.length = 0;
    tileset._hasMixedContent = false;

    const root = tileset.root;
    updateTile(tileset, root, frameState);

    // The root tile is not visible
    if (!isVisible(root)) {
      return;
    }

    // The tileset doesn't meet the SSE requirement, therefore the tree does not need to be rendered
    if (
      root.getScreenSpaceError(frameState, true) <=
      tileset._maximumScreenSpaceError
    ) {
      return;
    }

    if (!skipLevelOfDetail(tileset)) {
      executeBaseTraversal(tileset, root, frameState);
    } else if (tileset.immediatelyLoadDesiredLevelOfDetail) {
      executeSkipTraversal(tileset, root, frameState);
    } else {
      executeBaseAndSkipTraversal(tileset, root, frameState);
    }

    traversal.stack.trim(traversal.stackMaximumLength);
    emptyTraversal.stack.trim(emptyTraversal.stackMaximumLength);
    descendantTraversal.stack.trim(descendantTraversal.stackMaximumLength);
    selectionTraversal.stack.trim(selectionTraversal.stackMaximumLength);
    selectionTraversal.ancestorStack.trim(
      selectionTraversal.ancestorStackMaximumLength
    );

    // Update the priority for any requests found during traversal
    // Update after traversal so that min and max values can be used to normalize priority values
    const requestedTiles = tileset._requestedTiles;
    const length = requestedTiles.length;
    for (let i = 0; i < length; ++i) {
      requestedTiles[i].updatePriority();
    }
  };

  function executeBaseTraversal(tileset, root, frameState) {
    const baseScreenSpaceError = tileset._maximumScreenSpaceError;
    const maximumScreenSpaceError = tileset._maximumScreenSpaceError;
    executeTraversal(
      tileset,
      root,
      baseScreenSpaceError,
      maximumScreenSpaceError,
      frameState
    );
  }

  function executeSkipTraversal(tileset, root, frameState) {
    const baseScreenSpaceError = Number.MAX_VALUE;
    const maximumScreenSpaceError = tileset._maximumScreenSpaceError;
    executeTraversal(
      tileset,
      root,
      baseScreenSpaceError,
      maximumScreenSpaceError,
      frameState
    );
    traverseAndSelect(tileset, root, frameState);
  }

  function executeBaseAndSkipTraversal(tileset, root, frameState) {
    const baseScreenSpaceError = Math.max(
      tileset.baseScreenSpaceError,
      tileset.maximumScreenSpaceError
    );
    const maximumScreenSpaceError = tileset.maximumScreenSpaceError;
    executeTraversal(
      tileset,
      root,
      baseScreenSpaceError,
      maximumScreenSpaceError,
      frameState
    );
    traverseAndSelect(tileset, root, frameState);
  }

  function skipLevelOfDetail(tileset) {
    return tileset._skipLevelOfDetail;
  }

  function addEmptyTile(tileset, tile) {
    tileset._emptyTiles.push(tile);
  }

  function selectTile(tileset, tile, frameState) {
    if (tile.contentVisibility(frameState) !== Intersect$1.OUTSIDE) {
      const tileContent = tile.content;
      if (tileContent.featurePropertiesDirty) {
        // A feature's property in this tile changed, the tile needs to be re-styled.
        tileContent.featurePropertiesDirty = false;
        tile.lastStyleTime = 0; // Force applying the style to this tile
        tileset._selectedTilesToStyle.push(tile);
      } else if (tile._selectedFrame < frameState.frameNumber - 1) {
        // Tile is newly selected; it is selected this frame, but was not selected last frame.
        tileset._selectedTilesToStyle.push(tile);
      }
      tile._selectedFrame = frameState.frameNumber;
      tileset._selectedTiles.push(tile);
    }
  }

  function selectDescendants(tileset, root, frameState) {
    const stack = descendantTraversal.stack;
    stack.push(root);
    while (stack.length > 0) {
      descendantTraversal.stackMaximumLength = Math.max(
        descendantTraversal.stackMaximumLength,
        stack.length
      );
      const tile = stack.pop();
      const children = tile.children;
      const childrenLength = children.length;
      for (let i = 0; i < childrenLength; ++i) {
        const child = children[i];
        if (isVisible(child)) {
          if (child.contentAvailable) {
            updateTile(tileset, child, frameState);
            touchTile(tileset, child, frameState);
            selectTile(tileset, child, frameState);
          } else if (child._depth - root._depth < descendantSelectionDepth) {
            // Continue traversing, but not too far
            stack.push(child);
          }
        }
      }
    }
  }

  function selectDesiredTile(tileset, tile, frameState) {
    if (!skipLevelOfDetail(tileset)) {
      if (tile.contentAvailable) {
        // The tile can be selected right away and does not require traverseAndSelect
        selectTile(tileset, tile, frameState);
      }
      return;
    }

    // If this tile is not loaded attempt to select its ancestor instead
    const loadedTile = tile.contentAvailable
      ? tile
      : tile._ancestorWithContentAvailable;
    if (defined(loadedTile)) {
      // Tiles will actually be selected in traverseAndSelect
      loadedTile._shouldSelect = true;
    } else {
      // If no ancestors are ready traverse down and select tiles to minimize empty regions.
      // This happens often for immediatelyLoadDesiredLevelOfDetail where parent tiles are not necessarily loaded before zooming out.
      selectDescendants(tileset, tile, frameState);
    }
  }

  function visitTile$2(tileset, tile, frameState) {
    ++tileset._statistics.visited;
    tile._visitedFrame = frameState.frameNumber;
  }

  function touchTile(tileset, tile, frameState) {
    if (tile._touchedFrame === frameState.frameNumber) {
      // Prevents another pass from touching the frame again
      return;
    }
    tileset._cache.touch(tile);
    tile._touchedFrame = frameState.frameNumber;
  }

  function updateMinimumMaximumPriority(tileset, tile) {
    tileset._maximumPriority.distance = Math.max(
      tile._priorityHolder._distanceToCamera,
      tileset._maximumPriority.distance
    );
    tileset._minimumPriority.distance = Math.min(
      tile._priorityHolder._distanceToCamera,
      tileset._minimumPriority.distance
    );
    tileset._maximumPriority.depth = Math.max(
      tile._depth,
      tileset._maximumPriority.depth
    );
    tileset._minimumPriority.depth = Math.min(
      tile._depth,
      tileset._minimumPriority.depth
    );
    tileset._maximumPriority.foveatedFactor = Math.max(
      tile._priorityHolder._foveatedFactor,
      tileset._maximumPriority.foveatedFactor
    );
    tileset._minimumPriority.foveatedFactor = Math.min(
      tile._priorityHolder._foveatedFactor,
      tileset._minimumPriority.foveatedFactor
    );
    tileset._maximumPriority.reverseScreenSpaceError = Math.max(
      tile._priorityReverseScreenSpaceError,
      tileset._maximumPriority.reverseScreenSpaceError
    );
    tileset._minimumPriority.reverseScreenSpaceError = Math.min(
      tile._priorityReverseScreenSpaceError,
      tileset._minimumPriority.reverseScreenSpaceError
    );
  }

  function isOnScreenLongEnough(tileset, tile, frameState) {
    // Prevent unnecessary loads while camera is moving by getting the ratio of travel distance to tile size.
    if (!tileset._cullRequestsWhileMoving) {
      return true;
    }

    const sphere = tile.boundingSphere;
    const diameter = Math.max(sphere.radius * 2.0, 1.0);

    const camera = frameState.camera;
    const deltaMagnitude =
      camera.positionWCDeltaMagnitude !== 0.0
        ? camera.positionWCDeltaMagnitude
        : camera.positionWCDeltaMagnitudeLastFrame;
    const movementRatio =
      (tileset.cullRequestsWhileMovingMultiplier * deltaMagnitude) / diameter; // How do n frames of this movement compare to the tile's physical size.
    return movementRatio < 1.0;
  }

  function loadTile(tileset, tile, frameState) {
    if (
      tile._requestedFrame === frameState.frameNumber ||
      (!hasUnloadedContent(tile) && !tile.contentExpired)
    ) {
      return;
    }

    if (!isOnScreenLongEnough(tileset, tile, frameState)) {
      return;
    }

    const cameraHasNotStoppedMovingLongEnough =
      frameState.camera.timeSinceMoved < tileset.foveatedTimeDelay;
    if (tile.priorityDeferred && cameraHasNotStoppedMovingLongEnough) {
      return;
    }

    tile._requestedFrame = frameState.frameNumber;
    tileset._requestedTiles.push(tile);
  }

  function updateVisibility(tileset, tile, frameState) {
    if (tile._updatedVisibilityFrame === tileset._updatedVisibilityFrame) {
      // Return early if visibility has already been checked during the traversal.
      // The visibility may have already been checked if the cullWithChildrenBounds optimization is used.
      return;
    }

    tile.updateVisibility(frameState);
    tile._updatedVisibilityFrame = tileset._updatedVisibilityFrame;
  }

  function anyChildrenVisible(tileset, tile, frameState) {
    let anyVisible = false;
    const children = tile.children;
    const length = children.length;
    for (let i = 0; i < length; ++i) {
      const child = children[i];
      updateVisibility(tileset, child, frameState);
      anyVisible = anyVisible || isVisible(child);
    }
    return anyVisible;
  }

  function meetsScreenSpaceErrorEarly(tileset, tile, frameState) {
    const parent = tile.parent;
    if (
      !defined(parent) ||
      parent.hasTilesetContent ||
      parent.hasImplicitContent ||
      parent.refine !== Cesium3DTileRefine$1.ADD
    ) {
      return false;
    }

    // Use parent's geometric error with child's box to see if the tile already meet the SSE
    return (
      tile.getScreenSpaceError(frameState, true) <=
      tileset._maximumScreenSpaceError
    );
  }

  function updateTileVisibility(tileset, tile, frameState) {
    updateVisibility(tileset, tile, frameState);

    if (!isVisible(tile)) {
      return;
    }

    const hasChildren = tile.children.length > 0;
    if ((tile.hasTilesetContent || tile.hasImplicitContent) && hasChildren) {
      // Use the root tile's visibility instead of this tile's visibility.
      // The root tile may be culled by the children bounds optimization in which
      // case this tile should also be culled.
      const child = tile.children[0];
      updateTileVisibility(tileset, child, frameState);
      tile._visible = child._visible;
      return;
    }

    if (meetsScreenSpaceErrorEarly(tileset, tile, frameState)) {
      tile._visible = false;
      return;
    }

    // Optimization - if none of the tile's children are visible then this tile isn't visible
    const replace = tile.refine === Cesium3DTileRefine$1.REPLACE;
    const useOptimization =
      tile._optimChildrenWithinParent ===
      Cesium3DTileOptimizationHint$1.USE_OPTIMIZATION;
    if (replace && useOptimization && hasChildren) {
      if (!anyChildrenVisible(tileset, tile, frameState)) {
        ++tileset._statistics.numberOfTilesCulledWithChildrenUnion;
        tile._visible = false;
        return;
      }
    }
  }

  function updateTile(tileset, tile, frameState) {
    // Reset some of the tile's flags and re-evaluate visibility
    updateTileVisibility(tileset, tile, frameState);
    tile.updateExpiration();

    // Request priority
    tile._wasMinPriorityChild = false;
    tile._priorityHolder = tile;
    updateMinimumMaximumPriority(tileset, tile);

    // SkipLOD
    tile._shouldSelect = false;
    tile._finalResolution = true;
  }

  function updateTileAncestorContentLinks(tile, frameState) {
    tile._ancestorWithContent = undefined;
    tile._ancestorWithContentAvailable = undefined;

    const parent = tile.parent;
    if (defined(parent)) {
      // ancestorWithContent is an ancestor that has content or has the potential to have
      // content. Used in conjunction with tileset.skipLevels to know when to skip a tile.
      // ancestorWithContentAvailable is an ancestor that is rendered if a desired tile is not loaded.
      const hasContent =
        !hasUnloadedContent(parent) ||
        parent._requestedFrame === frameState.frameNumber;
      tile._ancestorWithContent = hasContent
        ? parent
        : parent._ancestorWithContent;
      tile._ancestorWithContentAvailable = parent.contentAvailable
        ? parent
        : parent._ancestorWithContentAvailable; // Links a descendant up to its contentAvailable ancestor as the traversal progresses.
    }
  }

  function hasEmptyContent(tile) {
    return (
      tile.hasEmptyContent || tile.hasTilesetContent || tile.hasImplicitContent
    );
  }

  function hasUnloadedContent(tile) {
    return !hasEmptyContent(tile) && tile.contentUnloaded;
  }

  function reachedSkippingThreshold(tileset, tile) {
    const ancestor = tile._ancestorWithContent;
    return (
      !tileset.immediatelyLoadDesiredLevelOfDetail &&
      (tile._priorityProgressiveResolutionScreenSpaceErrorLeaf ||
        (defined(ancestor) &&
          tile._screenSpaceError <
            ancestor._screenSpaceError / tileset.skipScreenSpaceErrorFactor &&
          tile._depth > ancestor._depth + tileset.skipLevels))
    );
  }

  function sortChildrenByDistanceToCamera(a, b) {
    // Sort by farthest child first since this is going on a stack
    if (b._distanceToCamera === 0 && a._distanceToCamera === 0) {
      return b._centerZDepth - a._centerZDepth;
    }

    return b._distanceToCamera - a._distanceToCamera;
  }

  function updateAndPushChildren(tileset, tile, stack, frameState) {
    let i;
    const replace = tile.refine === Cesium3DTileRefine$1.REPLACE;
    const children = tile.children;
    const length = children.length;

    for (i = 0; i < length; ++i) {
      updateTile(tileset, children[i], frameState);
    }

    // Sort by distance to take advantage of early Z and reduce artifacts for skipLevelOfDetail
    children.sort(sortChildrenByDistanceToCamera);

    // For traditional replacement refinement only refine if all children are loaded.
    // Empty tiles are exempt since it looks better if children stream in as they are loaded to fill the empty space.
    const checkRefines =
      !skipLevelOfDetail(tileset) && replace && !hasEmptyContent(tile);
    let refines = true;

    let anyChildrenVisible = false;

    // Determining min child
    let minIndex = -1;
    let minimumPriority = Number.MAX_VALUE;

    let child;
    for (i = 0; i < length; ++i) {
      child = children[i];
      if (isVisible(child)) {
        stack.push(child);
        if (child._foveatedFactor < minimumPriority) {
          minIndex = i;
          minimumPriority = child._foveatedFactor;
        }
        anyChildrenVisible = true;
      } else if (checkRefines || tileset.loadSiblings) {
        // Keep non-visible children loaded since they are still needed before the parent can refine.
        // Or loadSiblings is true so always load tiles regardless of visibility.
        if (child._foveatedFactor < minimumPriority) {
          minIndex = i;
          minimumPriority = child._foveatedFactor;
        }
        loadTile(tileset, child, frameState);
        touchTile(tileset, child, frameState);
      }
      if (checkRefines) {
        let childRefines;
        if (!child._inRequestVolume) {
          childRefines = false;
        } else if (hasEmptyContent(child)) {
          childRefines = executeEmptyTraversal(tileset, child, frameState);
        } else {
          childRefines = child.contentAvailable;
        }
        refines = refines && childRefines;
      }
    }

    if (!anyChildrenVisible) {
      refines = false;
    }

    if (minIndex !== -1 && !skipLevelOfDetail(tileset) && replace) {
      // An ancestor will hold the _foveatedFactor and _distanceToCamera for descendants between itself and its highest priority descendant. Siblings of a min children along the way use this ancestor as their priority holder as well.
      // Priority of all tiles that refer to the _foveatedFactor and _distanceToCamera stored in the common ancestor will be differentiated based on their _depth.
      const minPriorityChild = children[minIndex];
      minPriorityChild._wasMinPriorityChild = true;
      const priorityHolder =
        (tile._wasMinPriorityChild || tile === tileset.root) &&
        minimumPriority <= tile._priorityHolder._foveatedFactor
          ? tile._priorityHolder
          : tile; // This is where priority dependency chains are wired up or started anew.
      priorityHolder._foveatedFactor = Math.min(
        minPriorityChild._foveatedFactor,
        priorityHolder._foveatedFactor
      );
      priorityHolder._distanceToCamera = Math.min(
        minPriorityChild._distanceToCamera,
        priorityHolder._distanceToCamera
      );

      for (i = 0; i < length; ++i) {
        child = children[i];
        child._priorityHolder = priorityHolder;
      }
    }

    return refines;
  }

  function inBaseTraversal(tileset, tile, baseScreenSpaceError) {
    if (!skipLevelOfDetail(tileset)) {
      return true;
    }
    if (tileset.immediatelyLoadDesiredLevelOfDetail) {
      return false;
    }
    if (!defined(tile._ancestorWithContent)) {
      // Include root or near-root tiles in the base traversal so there is something to select up to
      return true;
    }
    if (tile._screenSpaceError === 0.0) {
      // If a leaf, use parent's SSE
      return tile.parent._screenSpaceError > baseScreenSpaceError;
    }
    return tile._screenSpaceError > baseScreenSpaceError;
  }

  function canTraverse(tileset, tile) {
    if (tile.children.length === 0) {
      return false;
    }
    if (tile.hasTilesetContent || tile.hasImplicitContent) {
      // Traverse external tileset to visit its root tile
      // Don't traverse if the subtree is expired because it will be destroyed
      return !tile.contentExpired;
    }
    return tile._screenSpaceError > tileset._maximumScreenSpaceError;
  }

  function executeTraversal(
    tileset,
    root,
    baseScreenSpaceError,
    maximumScreenSpaceError,
    frameState
  ) {
    // Depth-first traversal that traverses all visible tiles and marks tiles for selection.
    // If skipLevelOfDetail is off then a tile does not refine until all children are loaded.
    // This is the traditional replacement refinement approach and is called the base traversal.
    // Tiles that have a greater screen space error than the base screen space error are part of the base traversal,
    // all other tiles are part of the skip traversal. The skip traversal allows for skipping levels of the tree
    // and rendering children and parent tiles simultaneously.
    const stack = traversal.stack;
    stack.push(root);

    while (stack.length > 0) {
      traversal.stackMaximumLength = Math.max(
        traversal.stackMaximumLength,
        stack.length
      );

      const tile = stack.pop();

      updateTileAncestorContentLinks(tile, frameState);
      const baseTraversal = inBaseTraversal(tileset, tile, baseScreenSpaceError);
      const add = tile.refine === Cesium3DTileRefine$1.ADD;
      const replace = tile.refine === Cesium3DTileRefine$1.REPLACE;
      const parent = tile.parent;
      const parentRefines = !defined(parent) || parent._refines;
      let refines = false;

      if (canTraverse(tileset, tile)) {
        refines =
          updateAndPushChildren(tileset, tile, stack, frameState) &&
          parentRefines;
      }

      const stoppedRefining = !refines && parentRefines;

      if (hasEmptyContent(tile)) {
        // Add empty tile just to show its debug bounding volume
        // If the tile has tileset content load the external tileset
        // If the tile cannot refine further select its nearest loaded ancestor
        addEmptyTile(tileset, tile);
        loadTile(tileset, tile, frameState);
        if (stoppedRefining) {
          selectDesiredTile(tileset, tile, frameState);
        }
      } else if (add) {
        // Additive tiles are always loaded and selected
        selectDesiredTile(tileset, tile, frameState);
        loadTile(tileset, tile, frameState);
      } else if (replace) {
        if (baseTraversal) {
          // Always load tiles in the base traversal
          // Select tiles that can't refine further
          loadTile(tileset, tile, frameState);
          if (stoppedRefining) {
            selectDesiredTile(tileset, tile, frameState);
          }
        } else if (stoppedRefining) {
          // In skip traversal, load and select tiles that can't refine further
          selectDesiredTile(tileset, tile, frameState);
          loadTile(tileset, tile, frameState);
        } else if (reachedSkippingThreshold(tileset, tile)) {
          // In skip traversal, load tiles that aren't skipped. In practice roughly half the tiles stay unloaded.
          loadTile(tileset, tile, frameState);
        }
      }

      visitTile$2(tileset, tile, frameState);
      touchTile(tileset, tile, frameState);
      tile._refines = refines;
    }
  }

  function executeEmptyTraversal(tileset, root, frameState) {
    // Depth-first traversal that checks if all nearest descendants with content are loaded. Ignores visibility.
    let allDescendantsLoaded = true;
    const stack = emptyTraversal.stack;
    stack.push(root);

    while (stack.length > 0) {
      emptyTraversal.stackMaximumLength = Math.max(
        emptyTraversal.stackMaximumLength,
        stack.length
      );

      const tile = stack.pop();
      const children = tile.children;
      const childrenLength = children.length;

      // Only traverse if the tile is empty - traversal stop at descendants with content
      const emptyContent = hasEmptyContent(tile);
      const traverse = emptyContent && canTraverse(tileset, tile);
      const emptyLeaf = emptyContent && tile.children.length === 0;

      // Traversal stops but the tile does not have content yet
      // There will be holes if the parent tries to refine to its children, so don't refine
      // One exception: a parent may refine even if one of its descendants is an empty leaf
      if (!traverse && !tile.contentAvailable && !emptyLeaf) {
        allDescendantsLoaded = false;
      }

      updateTile(tileset, tile, frameState);
      if (!isVisible(tile)) {
        // Load tiles that aren't visible since they are still needed for the parent to refine
        loadTile(tileset, tile, frameState);
        touchTile(tileset, tile, frameState);
      }

      if (traverse) {
        for (let i = 0; i < childrenLength; ++i) {
          const child = children[i];
          stack.push(child);
        }
      }
    }

    return allDescendantsLoaded;
  }

  /**
   * Traverse the tree and check if their selected frame is the current frame. If so, add it to a selection queue.
   * This is a preorder traversal so children tiles are selected before ancestor tiles.
   *
   * The reason for the preorder traversal is so that tiles can easily be marked with their
   * selection depth. A tile's _selectionDepth is its depth in the tree where all non-selected tiles are removed.
   * This property is important for use in the stencil test because we want to render deeper tiles on top of their
   * ancestors. If a tileset is very deep, the depth is unlikely to fit into the stencil buffer.
   *
   * We want to select children before their ancestors because there is no guarantee on the relationship between
   * the children's z-depth and the ancestor's z-depth. We cannot rely on Z because we want the child to appear on top
   * of ancestor regardless of true depth. The stencil tests used require children to be drawn first.
   *
   * NOTE: 3D Tiles uses 3 bits from the stencil buffer meaning this will not work when there is a chain of
   * selected tiles that is deeper than 7. This is not very likely.
   * @private
   */
  function traverseAndSelect(tileset, root, frameState) {
    const stack = selectionTraversal.stack;
    const ancestorStack = selectionTraversal.ancestorStack;
    let lastAncestor;

    stack.push(root);

    while (stack.length > 0 || ancestorStack.length > 0) {
      selectionTraversal.stackMaximumLength = Math.max(
        selectionTraversal.stackMaximumLength,
        stack.length
      );
      selectionTraversal.ancestorStackMaximumLength = Math.max(
        selectionTraversal.ancestorStackMaximumLength,
        ancestorStack.length
      );

      if (ancestorStack.length > 0) {
        const waitingTile = ancestorStack.peek();
        if (waitingTile._stackLength === stack.length) {
          ancestorStack.pop();
          if (waitingTile !== lastAncestor) {
            waitingTile._finalResolution = false;
          }
          selectTile(tileset, waitingTile, frameState);
          continue;
        }
      }

      const tile = stack.pop();
      if (!defined(tile)) {
        // stack is empty but ancestorStack isn't
        continue;
      }

      const add = tile.refine === Cesium3DTileRefine$1.ADD;
      const shouldSelect = tile._shouldSelect;
      const children = tile.children;
      const childrenLength = children.length;
      const traverse = canTraverse(tileset, tile);

      if (shouldSelect) {
        if (add) {
          selectTile(tileset, tile, frameState);
        } else {
          tile._selectionDepth = ancestorStack.length;
          if (tile._selectionDepth > 0) {
            tileset._hasMixedContent = true;
          }
          lastAncestor = tile;
          if (!traverse) {
            selectTile(tileset, tile, frameState);
            continue;
          }
          ancestorStack.push(tile);
          tile._stackLength = stack.length;
        }
      }

      if (traverse) {
        for (let i = 0; i < childrenLength; ++i) {
          const child = children[i];
          if (isVisible(child)) {
            stack.push(child);
          }
        }
      }
    }
  }

  /**
   * The pass in which a 3D Tileset is updated.
   *
   * @private
   */
  const Cesium3DTilePass = {
    RENDER: 0,
    PICK: 1,
    SHADOW: 2,
    PRELOAD: 3,
    PRELOAD_FLIGHT: 4,
    REQUEST_RENDER_MODE_DEFER_CHECK: 5,
    MOST_DETAILED_PRELOAD: 6,
    MOST_DETAILED_PICK: 7,
    NUMBER_OF_PASSES: 8,
  };

  const passOptions = new Array(Cesium3DTilePass.NUMBER_OF_PASSES);

  passOptions[Cesium3DTilePass.RENDER] = Object.freeze({
    traversal: Cesium3DTilesetTraversal,
    isRender: true,
    requestTiles: true,
    ignoreCommands: false,
  });

  passOptions[Cesium3DTilePass.PICK] = Object.freeze({
    traversal: Cesium3DTilesetTraversal,
    isRender: false,
    requestTiles: false,
    ignoreCommands: false,
  });

  passOptions[Cesium3DTilePass.SHADOW] = Object.freeze({
    traversal: Cesium3DTilesetTraversal,
    isRender: false,
    requestTiles: true,
    ignoreCommands: false,
  });

  passOptions[Cesium3DTilePass.PRELOAD] = Object.freeze({
    traversal: Cesium3DTilesetTraversal,
    isRender: false,
    requestTiles: true,
    ignoreCommands: true,
  });

  passOptions[Cesium3DTilePass.PRELOAD_FLIGHT] = Object.freeze({
    traversal: Cesium3DTilesetTraversal,
    isRender: false,
    requestTiles: true,
    ignoreCommands: true,
  });

  passOptions[Cesium3DTilePass.REQUEST_RENDER_MODE_DEFER_CHECK] = Object.freeze({
    traversal: Cesium3DTilesetTraversal,
    isRender: false,
    requestTiles: true,
    ignoreCommands: true,
  });

  passOptions[Cesium3DTilePass.MOST_DETAILED_PRELOAD] = Object.freeze({
    traversal: Cesium3DTilesetMostDetailedTraversal,
    isRender: false,
    requestTiles: true,
    ignoreCommands: true,
  });

  passOptions[Cesium3DTilePass.MOST_DETAILED_PICK] = Object.freeze({
    traversal: Cesium3DTilesetMostDetailedTraversal,
    isRender: false,
    requestTiles: false,
    ignoreCommands: false,
  });

  Cesium3DTilePass.getPassOptions = function (pass) {
    return passOptions[pass];
  };
  var Cesium3DTilePass$1 = Object.freeze(Cesium3DTilePass);

  /**
   * Represents empty content for tiles in a
   * {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification|3D Tiles} tileset that
   * do not have content, e.g., because they are used to optimize hierarchical culling.
   * <p>
   * Implements the {@link Cesium3DTileContent} interface.
   * </p>
   *
   * @alias Empty3DTileContent
   * @constructor
   *
   * @private
   */
  function Empty3DTileContent(tileset, tile) {
    this._tileset = tileset;
    this._tile = tile;

    this.featurePropertiesDirty = false;
  }

  Object.defineProperties(Empty3DTileContent.prototype, {
    featuresLength: {
      get: function () {
        return 0;
      },
    },

    pointsLength: {
      get: function () {
        return 0;
      },
    },

    trianglesLength: {
      get: function () {
        return 0;
      },
    },

    geometryByteLength: {
      get: function () {
        return 0;
      },
    },

    texturesByteLength: {
      get: function () {
        return 0;
      },
    },

    batchTableByteLength: {
      get: function () {
        return 0;
      },
    },

    innerContents: {
      get: function () {
        return undefined;
      },
    },

    readyPromise: {
      get: function () {
        return undefined;
      },
    },

    tileset: {
      get: function () {
        return this._tileset;
      },
    },

    tile: {
      get: function () {
        return this._tile;
      },
    },

    url: {
      get: function () {
        return undefined;
      },
    },

    metadata: {
      get: function () {
        return undefined;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        throw new DeveloperError(
          "Empty3DTileContent cannot have content metadata"
        );
        //>>includeEnd('debug');
      },
    },

    batchTable: {
      get: function () {
        return undefined;
      },
    },

    group: {
      get: function () {
        return undefined;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        throw new DeveloperError("Empty3DTileContent cannot have group metadata");
        //>>includeEnd('debug');
      },
    },
  });

  /**
   * Part of the {@link Cesium3DTileContent} interface.  <code>Empty3DTileContent</code>
   * always returns <code>false</code> since a tile of this type does not have any features.
   */
  Empty3DTileContent.prototype.hasProperty = function (batchId, name) {
    return false;
  };

  /**
   * Part of the {@link Cesium3DTileContent} interface.  <code>Empty3DTileContent</code>
   * always returns <code>undefined</code> since a tile of this type does not have any features.
   */
  Empty3DTileContent.prototype.getFeature = function (batchId) {
    return undefined;
  };

  Empty3DTileContent.prototype.applyDebugSettings = function (enabled, color) {};

  Empty3DTileContent.prototype.applyStyle = function (style) {};

  Empty3DTileContent.prototype.update = function (tileset, frameState) {};

  Empty3DTileContent.prototype.isDestroyed = function () {
    return false;
  };

  Empty3DTileContent.prototype.destroy = function () {
    return destroyObject(this);
  };

  /**
   * Metadata about the content of a 3D Tile. This represents the content metadata JSON (3D Tiles 1.1)
   * or the <code>3DTILES_metadata</code> extension on a single {@link Cesium3DTileContent}
   * <p>
   * See the {@link https://github.com/CesiumGS/3d-tiles/tree/main/extensions/3DTILES_metadata|3DTILES_metadata Extension} for 3D Tiles
   * </p>
   *
   * @param {Object} options Object with the following properties:
   * @param {Object} options.content Either the content metadata JSON (3D Tiles 1.1) or the extension JSON attached to the content.
   * @param {MetadataClass} options.class The class that the content metadata conforms to.
   *
   * @alias ContentMetadata
   * @constructor
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function ContentMetadata(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const content = options.content;
    const metadataClass = options.class;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.content", content);
    Check.typeOf.object("options.class", metadataClass);
    //>>includeEnd('debug');

    this._class = metadataClass;
    this._properties = content.properties;
    this._extensions = content.extensions;
    this._extras = content.extras;
  }

  Object.defineProperties(ContentMetadata.prototype, {
    /**
     * The class that properties conform to.
     *
     * @memberof ContentMetadata.prototype
     * @type {MetadataClass}
     * @readonly
     * @private
     */
    class: {
      get: function () {
        return this._class;
      },
    },

    /**
     * Extras in the JSON object.
     *
     * @memberof ContentMetadata.prototype
     * @type {Object}
     * @readonly
     * @private
     */
    extras: {
      get: function () {
        return this._extras;
      },
    },

    /**
     * Extensions in the JSON object.
     *
     * @memberof ContentMetadata.prototype
     * @type {Object}
     * @readonly
     * @private
     */
    extensions: {
      get: function () {
        return this._extensions;
      },
    },
  });

  /**
   * Returns whether the content has this property.
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @returns {Boolean} Whether the content has this property.
   * @private
   */
  ContentMetadata.prototype.hasProperty = function (propertyId) {
    return MetadataEntity.hasProperty(propertyId, this._properties, this._class);
  };

  /**
   * Returns whether the content has a property with the given semantic.
   *
   * @param {String} semantic The case-sensitive semantic of the property.
   * @returns {Boolean} Whether the content has a property with the given semantic.
   * @private
   */
  ContentMetadata.prototype.hasPropertyBySemantic = function (semantic) {
    return MetadataEntity.hasPropertyBySemantic(
      semantic,
      this._properties,
      this._class
    );
  };

  /**
   * Returns an array of property IDs.
   *
   * @param {String[]} [results] An array into which to store the results.
   * @returns {String[]} The property IDs.
   * @private
   */
  ContentMetadata.prototype.getPropertyIds = function (results) {
    return MetadataEntity.getPropertyIds(this._properties, this._class, results);
  };

  /**
   * Returns a copy of the value of the property with the given ID.
   * <p>
   * If the property is normalized the normalized value is returned.
   * </p>
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @returns {*} The value of the property or <code>undefined</code> if the content does not have this property.
   * @private
   */
  ContentMetadata.prototype.getProperty = function (propertyId) {
    return MetadataEntity.getProperty(propertyId, this._properties, this._class);
  };

  /**
   * Sets the value of the property with the given ID.
   * <p>
   * If the property is normalized a normalized value must be provided to this function.
   * </p>
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @param {*} value The value of the property that will be copied.
   * @returns {Boolean} <code>true</code> if the property was set, <code>false</code> otherwise.
   * @private
   */
  ContentMetadata.prototype.setProperty = function (propertyId, value) {
    return MetadataEntity.setProperty(
      propertyId,
      value,
      this._properties,
      this._class
    );
  };

  /**
   * Returns a copy of the value of the property with the given semantic.
   *
   * @param {String} semantic The case-sensitive semantic of the property.
   * @returns {*} The value of the property or <code>undefined</code> if the content does not have this semantic.
   * @private
   */
  ContentMetadata.prototype.getPropertyBySemantic = function (semantic) {
    return MetadataEntity.getPropertyBySemantic(
      semantic,
      this._properties,
      this._class
    );
  };

  /**
   * Sets the value of the property with the given semantic.
   *
   * @param {String} semantic The case-sensitive semantic of the property.
   * @param {*} value The value of the property that will be copied.
   * @returns {Boolean} <code>true</code> if the property was set, <code>false</code> otherwise.
   * @private
   */
  ContentMetadata.prototype.setPropertyBySemantic = function (semantic, value) {
    return MetadataEntity.setPropertyBySemantic(
      semantic,
      value,
      this._properties,
      this._class
    );
  };

  /**
   * Check if a content has metadata, either defined in its metadata field (3D Tiles 1.1) or in
   * the <code>3DTILES_metadata</code> extension. If defined, get the content metadata
   * with the corresponding class.
   *
   * @function
   *
   * @param {Cesium3DTileset} tileset The tileset to query for content metadata
   * @param {Object} contentHeader the JSON header for a {@link Cesium3DTileContent}
   * @return {ContentMetadata} the content metadata, or <code>undefined</code> if not found
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function findContentMetadata(tileset, contentHeader) {
    const metadataJson = hasExtension(contentHeader, "3DTILES_metadata")
      ? contentHeader.extensions["3DTILES_metadata"]
      : contentHeader.metadata;

    if (!defined(metadataJson)) {
      return undefined;
    }

    if (!defined(tileset.schema)) {
      findContentMetadata._oneTimeWarning(
        "findContentMetadata-missing-root-schema",
        "Could not find a metadata schema for content metadata. For tilesets that contain external tilesets, make sure the schema is added to the root tileset.json."
      );
      return undefined;
    }

    const classes = defaultValue(
      tileset.schema.classes,
      defaultValue.EMPTY_OBJECT
    );
    if (defined(metadataJson.class)) {
      const contentClass = classes[metadataJson.class];
      return new ContentMetadata({
        content: metadataJson,
        class: contentClass,
      });
    }

    return undefined;
  }

  // Exposed for testing
  findContentMetadata._oneTimeWarning = oneTimeWarning;

  /**
   * Check if a content has metadata, either defined in its metadata field (3D Tiles 1.1)
   * or in the <code>3DTILES_metadata</code> extension. If so, look up the group with the
   * corresponding ID.
   *
   * @function
   *
   * @param {Cesium3DTileset} tileset The tileset to query for group metadata
   * @param {Object} contentHeader the JSON header for a {@link Cesium3DTileContent}
   * @return {GroupMetadata} the group metadata, or <code>undefined</code> if not found
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function findGroupMetadata(tileset, contentHeader) {
    const metadataExtension = tileset.metadataExtension;
    if (!defined(metadataExtension)) {
      return undefined;
    }
    const groups = metadataExtension.groups;

    const group = hasExtension(contentHeader, "3DTILES_metadata")
      ? contentHeader.extensions["3DTILES_metadata"].group
      : contentHeader.group;

    if (typeof group === "number") {
      return groups[group];
    }

    const index = metadataExtension.groupIds.findIndex(function (id) {
      return id === group;
    });

    return index >= 0 ? groups[index] : undefined;
  }

  /**
   * Metadata about a 3D Tile. This represents the tile metadata JSON (3D Tiles 1.1)
   * or the <code>3DTILES_metadata</code> extension on a single {@link Cesium3DTile}
   * <p>
   * See the {@link https://github.com/CesiumGS/3d-tiles/tree/main/extensions/3DTILES_metadata|3DTILES_metadata Extension} for 3D Tiles
   * </p>
   *
   * @param {Object} options Object with the following properties:
   * @param {Object} options.tile Either the tile metadata JSON (3D Tiles 1.1), or the extension JSON attached to the tile.
   * @param {MetadataClass} options.class The class that the tile metadata conforms to.
   *
   * @alias TileMetadata
   * @constructor
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function TileMetadata(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const tile = options.tile;
    const metadataClass = options.class;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.tile", tile);
    Check.typeOf.object("options.class", metadataClass);
    //>>includeEnd('debug');

    this._class = metadataClass;
    this._properties = tile.properties;
    this._extensions = tile.extensions;
    this._extras = tile.extras;
  }

  Object.defineProperties(TileMetadata.prototype, {
    /**
     * The class that properties conform to.
     *
     * @memberof TileMetadata.prototype
     * @type {MetadataClass}
     * @readonly
     * @private
     */
    class: {
      get: function () {
        return this._class;
      },
    },

    /**
     * Extras in the JSON object.
     *
     * @memberof TileMetadata.prototype
     * @type {Object}
     * @readonly
     * @private
     */
    extras: {
      get: function () {
        return this._extras;
      },
    },

    /**
     * Extensions in the JSON object.
     *
     * @memberof TileMetadata.prototype
     * @type {Object}
     * @readonly
     * @private
     */
    extensions: {
      get: function () {
        return this._extensions;
      },
    },
  });

  /**
   * Returns whether the tile has this property.
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @returns {Boolean} Whether the tile has this property.
   * @private
   */
  TileMetadata.prototype.hasProperty = function (propertyId) {
    return MetadataEntity.hasProperty(propertyId, this._properties, this._class);
  };

  /**
   * Returns whether the tile has a property with the given semantic.
   *
   * @param {String} semantic The case-sensitive semantic of the property.
   * @returns {Boolean} Whether the tile has a property with the given semantic.
   * @private
   */
  TileMetadata.prototype.hasPropertyBySemantic = function (semantic) {
    return MetadataEntity.hasPropertyBySemantic(
      semantic,
      this._properties,
      this._class
    );
  };

  /**
   * Returns an array of property IDs.
   *
   * @param {String[]} [results] An array into which to store the results.
   * @returns {String[]} The property IDs.
   * @private
   */
  TileMetadata.prototype.getPropertyIds = function (results) {
    return MetadataEntity.getPropertyIds(this._properties, this._class, results);
  };

  /**
   * Returns a copy of the value of the property with the given ID.
   * <p>
   * If the property is normalized the normalized value is returned.
   * </p>
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @returns {*} The value of the property or <code>undefined</code> if the tile does not have this property.
   * @private
   */
  TileMetadata.prototype.getProperty = function (propertyId) {
    return MetadataEntity.getProperty(propertyId, this._properties, this._class);
  };

  /**
   * Sets the value of the property with the given ID.
   * <p>
   * If the property is normalized a normalized value must be provided to this function.
   * </p>
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @param {*} value The value of the property that will be copied.
   * @returns {Boolean} <code>true</code> if the property was set, <code>false</code> otherwise.
   * @private
   */
  TileMetadata.prototype.setProperty = function (propertyId, value) {
    return MetadataEntity.setProperty(
      propertyId,
      value,
      this._properties,
      this._class
    );
  };

  /**
   * Returns a copy of the value of the property with the given semantic.
   *
   * @param {String} semantic The case-sensitive semantic of the property.
   * @returns {*} The value of the property or <code>undefined</code> if the tile does not have this semantic.
   * @private
   */
  TileMetadata.prototype.getPropertyBySemantic = function (semantic) {
    return MetadataEntity.getPropertyBySemantic(
      semantic,
      this._properties,
      this._class
    );
  };

  /**
   * Sets the value of the property with the given semantic.
   *
   * @param {String} semantic The case-sensitive semantic of the property.
   * @param {*} value The value of the property that will be copied.
   * @returns {Boolean} <code>true</code> if the property was set, <code>false</code> otherwise.
   * @private
   */
  TileMetadata.prototype.setPropertyBySemantic = function (semantic, value) {
    return MetadataEntity.setPropertyBySemantic(
      semantic,
      value,
      this._properties,
      this._class
    );
  };

  /**
   * Check if a tile has metadata, either defined in its metadata field (3D Tiles 1.1)
   * or in the <code>3DTILES_metadata</code> extension. If defined, get the tile metadata
   * with the corresponding class.
   * <p>
   * This assumes that tileset.metadata has been created before any tiles are constructed.
   * </p>
   * @function
   *
   * @param {Cesium3DTileset} tileset The tileset to query for tile metadata
   * @param {Object} tileHeader the JSON header for a {@link Cesium3DTile}
   * @return {TileMetadata} the tile metadata, or <code>undefined</code> if not found
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function findTileMetadata(tileset, tileHeader) {
    const metadataJson = hasExtension(tileHeader, "3DTILES_metadata")
      ? tileHeader.extensions["3DTILES_metadata"]
      : tileHeader.metadata;

    if (!defined(metadataJson)) {
      return undefined;
    }

    if (!defined(tileset.schema)) {
      findTileMetadata._oneTimeWarning(
        "findTileMetadata-missing-root-schema",
        "Could not find a metadata schema for tile metadata. For tilesets that contain external tilesets, make sure the schema is added to the root tileset.json."
      );
      return undefined;
    }

    const classes = defaultValue(
      tileset.schema.classes,
      defaultValue.EMPTY_OBJECT
    );
    if (defined(metadataJson.class)) {
      const tileClass = classes[metadataJson.class];
      return new TileMetadata({
        tile: metadataJson,
        class: tileClass,
      });
    }

    return undefined;
  }

  // Exposed for testing
  findTileMetadata._oneTimeWarning = oneTimeWarning;

  /**
   * Results of the preprocess3DTileContent() function. This includes the
   * {@link Cesium3DTileContentType} and the payload. The payload is either
   * binary or JSON depending on the content type.
   *
   * @typedef {Object} PreprocessedContent
   * @property {Cesium3DTileContentType} contentType The type of the content
   * @property {Uint8Array} [binaryPayload] For binary files, the payload is returned as a typed array with byteOffset of 0
   * @property {Object} [jsonPayload] For JSON files, the results are returned as a JSON object.
   * @private
   */

  /**
   * Preprocess a {@link Cesium3DTileContent}, to determine the type of content
   * and to parse JSON files into objects.
   *
   * @param {ArrayBuffer} arrayBuffer The raw binary payload
   * @return {PreprocessedContent}
   * @private
   */
  function preprocess3DTileContent(arrayBuffer) {
    const uint8Array = new Uint8Array(arrayBuffer);
    let contentType = getMagic(uint8Array);

    // We use glTF for JSON glTF files. For binary glTF, we rename this
    // to glb to disambiguate
    if (contentType === "glTF") {
      contentType = "glb";
    }

    if (Cesium3DTileContentType$1.isBinaryFormat(contentType)) {
      return {
        // For binary files, the enum value is the magic number
        contentType: contentType,
        binaryPayload: uint8Array,
      };
    }

    const json = getJsonContent(uint8Array);
    if (defined(json.root)) {
      // Most likely a tileset JSON
      return {
        contentType: Cesium3DTileContentType$1.EXTERNAL_TILESET,
        jsonPayload: json,
      };
    }

    if (defined(json.asset)) {
      // Most likely a glTF. Tileset JSON also has an "asset" property
      // so this check needs to happen second
      return {
        contentType: Cesium3DTileContentType$1.GLTF,
        jsonPayload: json,
      };
    }

    if (defined(json.tileAvailability)) {
      // Most likely a subtree JSON.
      return {
        contentType: Cesium3DTileContentType$1.IMPLICIT_SUBTREE_JSON,
        jsonPayload: json,
      };
    }

    if (defined(json.type)) {
      // Most likely a GeoJSON
      return {
        contentType: Cesium3DTileContentType$1.GEOJSON,
        jsonPayload: json,
      };
    }

    throw new RuntimeError("Invalid tile content.");
  }

  function getJsonContent(uint8Array) {
    let json;

    try {
      json = getJsonFromTypedArray(uint8Array);
    } catch (error) {
      throw new RuntimeError("Invalid tile content.");
    }

    return json;
  }

  /**
   * A collection of contents for tiles that have multiple contents, either via the tile JSON (3D Tiles 1.1) or the <code>3DTILES_multiple_contents</code> extension.
   * <p>
   * Implements the {@link Cesium3DTileContent} interface.
   * </p>
   *
   * @see {@link https://github.com/CesiumGS/3d-tiles/tree/main/extensions/3DTILES_multiple_contents|3DTILES_multiple_contents extension}
   *
   * @alias Multiple3DTileContent
   * @constructor
   *
   * @param {Cesium3DTileset} tileset The tileset this content belongs to
   * @param {Cesium3DTile} tile The content this content belongs to
   * @param {Resource} tilesetResource The resource that points to the tileset. This will be used to derive each inner content's resource.
   * @param {Object} contentsJson Either the tile JSON containing the contents array (3D Tiles 1.1), or <code>3DTILES_multiple_contents</code> extension JSON
   *
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function Multiple3DTileContent(
    tileset,
    tile,
    tilesetResource,
    contentsJson
  ) {
    this._tileset = tileset;
    this._tile = tile;
    this._tilesetResource = tilesetResource;
    this._contents = [];

    // An older version of 3DTILES_multiple_contents used "content" instead of "contents"
    const contentHeaders = defined(contentsJson.contents)
      ? contentsJson.contents
      : contentsJson.content;

    this._innerContentHeaders = contentHeaders;
    this._requestsInFlight = 0;

    // How many times cancelPendingRequests() has been called. This is
    // used to help short-circuit computations after a tile was canceled.
    this._cancelCount = 0;

    const contentCount = this._innerContentHeaders.length;
    this._arrayFetchPromises = new Array(contentCount);
    this._requests = new Array(contentCount);

    this._innerContentResources = new Array(contentCount);
    this._serverKeys = new Array(contentCount);

    for (let i = 0; i < contentCount; i++) {
      const contentResource = tilesetResource.getDerivedResource({
        url: contentHeaders[i].uri,
      });

      const serverKey = RequestScheduler.getServerKey(
        contentResource.getUrlComponent()
      );

      this._innerContentResources[i] = contentResource;
      this._serverKeys[i] = serverKey;
    }

    // undefined until the first time requests are scheduled
    this._contentsFetchedPromise = undefined;
  }

  Object.defineProperties(Multiple3DTileContent.prototype, {
    /**
     * Part of the {@link Cesium3DTileContent} interface.  <code>Multiple3DTileContent</code> checks if any of the inner contents have dirty featurePropertiesDirty.
     * @memberof Multiple3DTileContent.prototype
     *
     * @type {Boolean}
     *
     * @private
     */
    featurePropertiesDirty: {
      get: function () {
        const contents = this._contents;
        const length = contents.length;
        for (let i = 0; i < length; ++i) {
          if (contents[i].featurePropertiesDirty) {
            return true;
          }
        }

        return false;
      },
      set: function (value) {
        const contents = this._contents;
        const length = contents.length;
        for (let i = 0; i < length; ++i) {
          contents[i].featurePropertiesDirty = value;
        }
      },
    },

    /**
     * Part of the {@link Cesium3DTileContent} interface.  <code>Multiple3DTileContent</code>
     * always returns <code>0</code>.  Instead call <code>featuresLength</code> for a specific inner content.
     * @memberof Multiple3DTileContent.prototype
     * @private
     */
    featuresLength: {
      get: function () {
        return 0;
      },
    },

    /**
     * Part of the {@link Cesium3DTileContent} interface.  <code>Multiple3DTileContent</code>
     * always returns <code>0</code>.  Instead, call <code>pointsLength</code> for a specific inner content.
     * @memberof Multiple3DTileContent.prototype
     * @private
     */
    pointsLength: {
      get: function () {
        return 0;
      },
    },

    /**
     * Part of the {@link Cesium3DTileContent} interface.  <code>Multiple3DTileContent</code>
     * always returns <code>0</code>.  Instead call <code>trianglesLength</code> for a specific inner content.
     * @memberof Multiple3DTileContent.prototype
     * @private
     */
    trianglesLength: {
      get: function () {
        return 0;
      },
    },

    /**
     * Part of the {@link Cesium3DTileContent} interface.  <code>Multiple3DTileContent</code>
     * always returns <code>0</code>.  Instead call <code>geometryByteLength</code> for a specific inner content.
     * @memberof Multiple3DTileContent.prototype
     * @private
     */
    geometryByteLength: {
      get: function () {
        return 0;
      },
    },

    /**
     * Part of the {@link Cesium3DTileContent} interface.   <code>Multiple3DTileContent</code>
     * always returns <code>0</code>.  Instead call <code>texturesByteLength</code> for a specific inner content.
     * @memberof Multiple3DTileContent.prototype
     * @private
     */
    texturesByteLength: {
      get: function () {
        return 0;
      },
    },

    /**
     * Part of the {@link Cesium3DTileContent} interface.  <code>Multiple3DTileContent</code>
     * always returns <code>0</code>.  Instead call <code>batchTableByteLength</code> for a specific inner content.
     * @memberof Multiple3DTileContent.prototype
     * @private
     */
    batchTableByteLength: {
      get: function () {
        return 0;
      },
    },

    innerContents: {
      get: function () {
        return this._contents;
      },
    },

    readyPromise: {
      get: function () {
        const readyPromises = this._contents.map(function (content) {
          return content.readyPromise;
        });

        const that = this;
        return Promise.all(readyPromises).then(function () {
          return that;
        });
      },
    },

    tileset: {
      get: function () {
        return this._tileset;
      },
    },

    tile: {
      get: function () {
        return this._tile;
      },
    },

    /**
     * Part of the {@link Cesium3DTileContent} interface.
     * Unlike other content types, <code>Multiple3DTileContent</code> does not
     * have a single URL, so this returns undefined.
     * @memberof Multiple3DTileContent.prototype
     *
     * @type {String}
     * @readonly
     * @private
     */
    url: {
      get: function () {
        return undefined;
      },
    },

    /**
     * Part of the {@link Cesium3DTileContent} interface. <code>Multiple3DTileContent</code>
     * always returns <code>undefined</code>.  Instead call <code>metadata</code> for a specific inner content.
     * @memberof Multiple3DTileContent.prototype
     * @private
     */
    metadata: {
      get: function () {
        return undefined;
      },
      set: function () {
        //>>includeStart('debug', pragmas.debug);
        throw new DeveloperError("Multiple3DTileContent cannot have metadata");
        //>>includeEnd('debug');
      },
    },

    /**
     * Part of the {@link Cesium3DTileContent} interface. <code>Multiple3DTileContent</code>
     * always returns <code>undefined</code>.  Instead call <code>batchTable</code> for a specific inner content.
     * @memberof Multiple3DTileContent.prototype
     * @private
     */
    batchTable: {
      get: function () {
        return undefined;
      },
    },

    /**
     * Part of the {@link Cesium3DTileContent} interface. <code>Multiple3DTileContent</code>
     * always returns <code>undefined</code>.  Instead call <code>group</code> for a specific inner content.
     * @memberof Multiple3DTileContent.prototype
     * @private
     */
    group: {
      get: function () {
        return undefined;
      },
      set: function () {
        //>>includeStart('debug', pragmas.debug);
        throw new DeveloperError(
          "Multiple3DTileContent cannot have group metadata"
        );
        //>>includeEnd('debug');
      },
    },

    /**
     * Get an array of the inner content URLs, regardless of whether they've
     * been fetched or not. This is intended for use with
     * {@link Cesium3DTileset#debugShowUrl}.
     * @memberof Multiple3DTileContent.prototype
     *
     * @type {String[]}
     * @readonly
     * @private
     */
    innerContentUrls: {
      get: function () {
        return this._innerContentHeaders.map(function (contentHeader) {
          return contentHeader.uri;
        });
      },
    },

    /**
     * A promise that resolves when all of the inner contents have been fetched.
     * This promise is undefined until the first frame where all array buffer
     * requests have been scheduled.
     * @memberof Multiple3DTileContent.prototype
     *
     * @type {Promise}
     * @private
     */
    contentsFetchedPromise: {
      get: function () {
        return this._contentsFetchedPromise;
      },
    },
  });

  function updatePendingRequests(multipleContents, deltaRequestCount) {
    multipleContents._requestsInFlight += deltaRequestCount;
    multipleContents.tileset.statistics.numberOfPendingRequests += deltaRequestCount;
  }

  function cancelPendingRequests(multipleContents, originalContentState) {
    multipleContents._cancelCount++;

    // reset the tile's content state to try again later.
    multipleContents._tile._contentState = originalContentState;

    multipleContents.tileset.statistics.numberOfPendingRequests -=
      multipleContents._requestsInFlight;
    multipleContents._requestsInFlight = 0;

    // Discard the request promises.
    const contentCount = multipleContents._innerContentHeaders.length;
    multipleContents._arrayFetchPromises = new Array(contentCount);
  }

  /**
   * Request the inner contents of this <code>Multiple3DTileContent</code>. This must be called once a frame until
   * {@link Multiple3DTileContent#contentsFetchedPromise} is defined. This promise
   * becomes available as soon as all requests are scheduled.
   * <p>
   * This method also updates the tile statistics' pending request count if the
   * requests are successfully scheduled.
   * </p>
   *
   * @return {Number} The number of attempted requests that were unable to be scheduled.
   * @private
   */
  Multiple3DTileContent.prototype.requestInnerContents = function () {
    // It's possible for these promises to leak content array buffers if the
    // camera moves before they all are scheduled. To prevent this leak, check
    // if we can schedule all the requests at once. If not, no requests are
    // scheduled
    if (!canScheduleAllRequests(this._serverKeys)) {
      return this._serverKeys.length;
    }

    const contentHeaders = this._innerContentHeaders;
    updatePendingRequests(this, contentHeaders.length);

    for (let i = 0; i < contentHeaders.length; i++) {
      // The cancel count is needed to avoid a race condition where a content
      // is canceled multiple times.
      this._arrayFetchPromises[i] = requestInnerContent(
        this,
        i,
        this._cancelCount,
        this._tile._contentState
      );
    }

    this._contentsFetchedPromise = createInnerContents(this);

    return 0;
  };

  /**
   * Check if all requests for inner contents can be scheduled at once. This is slower, but it avoids a potential memory leak.
   * @param {String[]} serverKeys The server keys for all of the inner contents
   * @return {Boolean} True if the request scheduler has enough open slots for all inner contents
   * @private
   */
  function canScheduleAllRequests(serverKeys) {
    const requestCountsByServer = {};
    for (let i = 0; i < serverKeys.length; i++) {
      const serverKey = serverKeys[i];
      if (defined(requestCountsByServer[serverKey])) {
        requestCountsByServer[serverKey]++;
      } else {
        requestCountsByServer[serverKey] = 1;
      }
    }

    for (const key in requestCountsByServer) {
      if (
        requestCountsByServer.hasOwnProperty(key) &&
        !RequestScheduler.serverHasOpenSlots(key, requestCountsByServer[key])
      ) {
        return false;
      }
    }
    return RequestScheduler.heapHasOpenSlots(serverKeys.length);
  }

  function requestInnerContent(
    multipleContents,
    index,
    originalCancelCount,
    originalContentState
  ) {
    // it is important to clone here. The fetchArrayBuffer() below here uses
    // throttling, but other uses of the resources do not.
    const contentResource = multipleContents._innerContentResources[
      index
    ].clone();
    const tile = multipleContents.tile;

    // Always create a new request. If the tile gets canceled, this
    // avoids getting stuck in the canceled state.
    const priorityFunction = function () {
      return tile._priority;
    };
    const serverKey = multipleContents._serverKeys[index];
    const request = new Request({
      throttle: true,
      throttleByServer: true,
      type: RequestType$1.TILES3D,
      priorityFunction: priorityFunction,
      serverKey: serverKey,
    });
    contentResource.request = request;
    multipleContents._requests[index] = request;

    return contentResource
      .fetchArrayBuffer()
      .then(function (arrayBuffer) {
        // Short circuit if another inner content was canceled.
        if (originalCancelCount < multipleContents._cancelCount) {
          return undefined;
        }

        updatePendingRequests(multipleContents, -1);
        return arrayBuffer;
      })
      .catch(function (error) {
        // Short circuit if another inner content was canceled.
        if (originalCancelCount < multipleContents._cancelCount) {
          return undefined;
        }

        if (contentResource.request.state === RequestState$1.CANCELLED) {
          cancelPendingRequests(multipleContents, originalContentState);
          return undefined;
        }

        updatePendingRequests(multipleContents, -1);
        handleInnerContentFailed(multipleContents, index, error);
      });
  }

  function createInnerContents(multipleContents) {
    const originalCancelCount = multipleContents._cancelCount;
    return Promise.all(multipleContents._arrayFetchPromises).then(function (
      arrayBuffers
    ) {
      if (originalCancelCount < multipleContents._cancelCount) {
        return undefined;
      }

      const contents = arrayBuffers.map(function (arrayBuffer, i) {
        if (!defined(arrayBuffer)) {
          // Content was not fetched. The error was handled in
          // the fetch promise
          return undefined;
        }

        return createInnerContent(multipleContents, arrayBuffer, i);
      });

      multipleContents._contents = contents.filter(defined);
    });
  }

  function createInnerContent(multipleContents, arrayBuffer, index) {
    const preprocessed = preprocess3DTileContent(arrayBuffer);

    if (preprocessed.contentType === Cesium3DTileContentType$1.EXTERNAL_TILESET) {
      const error = new RuntimeError(
        "External tilesets are disallowed inside multiple contents"
      );

      return handleInnerContentFailed(multipleContents, index, error);
    }

    multipleContents._disableSkipLevelOfDetail =
      multipleContents._disableSkipLevelOfDetail ||
      preprocessed.contentType === Cesium3DTileContentType$1.GEOMETRY ||
      preprocessed.contentType === Cesium3DTileContentType$1.VECTOR;

    const tileset = multipleContents._tileset;
    const resource = multipleContents._innerContentResources[index];
    const tile = multipleContents._tile;

    let content;
    const contentFactory = Cesium3DTileContentFactory[preprocessed.contentType];
    if (defined(preprocessed.binaryPayload)) {
      content = contentFactory(
        tileset,
        tile,
        resource,
        preprocessed.binaryPayload.buffer,
        0
      );
    } else {
      // JSON formats
      content = contentFactory(tileset, tile, resource, preprocessed.jsonPayload);
    }

    const contentHeader = multipleContents._innerContentHeaders[index];

    if (tile.hasImplicitContentMetadata) {
      const subtree = tile.implicitSubtree;
      const coordinates = tile.implicitCoordinates;
      content.metadata = subtree.getContentMetadataView(coordinates, index);
    } else if (!tile.hasImplicitContent) {
      content.metadata = findContentMetadata(tileset, contentHeader);
    }

    const groupMetadata = findGroupMetadata(tileset, contentHeader);
    if (defined(groupMetadata)) {
      content.group = new Cesium3DContentGroup({
        metadata: groupMetadata,
      });
    }
    return content;
  }

  function handleInnerContentFailed(multipleContents, index, error) {
    const tileset = multipleContents._tileset;
    const url = multipleContents._innerContentResources[index].url;
    const message = defined(error.message) ? error.message : error.toString();
    if (tileset.tileFailed.numberOfListeners > 0) {
      tileset.tileFailed.raiseEvent({
        url: url,
        message: message,
      });
    } else {
      console.log(`A content failed to load: ${url}`);
      console.log(`Error: ${message}`);
    }
  }

  /**
   * Cancel all requests for inner contents. This is called by the tile
   * when a tile goes out of view.
   *
   * @private
   */
  Multiple3DTileContent.prototype.cancelRequests = function () {
    for (let i = 0; i < this._requests.length; i++) {
      const request = this._requests[i];
      if (defined(request)) {
        request.cancel();
      }
    }
  };

  /**
   * Part of the {@link Cesium3DTileContent} interface.  <code>Multiple3DTileContent</code>
   * always returns <code>false</code>.  Instead call <code>hasProperty</code> for a specific inner content
   * @private
   */
  Multiple3DTileContent.prototype.hasProperty = function (batchId, name) {
    return false;
  };

  /**
   * Part of the {@link Cesium3DTileContent} interface.  <code>Multiple3DTileContent</code>
   * always returns <code>undefined</code>.  Instead call <code>getFeature</code> for a specific inner content
   * @private
   */
  Multiple3DTileContent.prototype.getFeature = function (batchId) {
    return undefined;
  };

  Multiple3DTileContent.prototype.applyDebugSettings = function (enabled, color) {
    const contents = this._contents;
    const length = contents.length;
    for (let i = 0; i < length; ++i) {
      contents[i].applyDebugSettings(enabled, color);
    }
  };

  Multiple3DTileContent.prototype.applyStyle = function (style) {
    const contents = this._contents;
    const length = contents.length;
    for (let i = 0; i < length; ++i) {
      contents[i].applyStyle(style);
    }
  };

  Multiple3DTileContent.prototype.update = function (tileset, frameState) {
    const contents = this._contents;
    const length = contents.length;
    for (let i = 0; i < length; ++i) {
      contents[i].update(tileset, frameState);
    }
  };

  Multiple3DTileContent.prototype.isDestroyed = function () {
    return false;
  };

  Multiple3DTileContent.prototype.destroy = function () {
    const contents = this._contents;
    const length = contents.length;
    for (let i = 0; i < length; ++i) {
      contents[i].destroy();
    }
    return destroyObject(this);
  };

  /**
   * A tile bounding volume specified as a longitude/latitude/height region.
   * @alias TileBoundingRegion
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Rectangle} options.rectangle The rectangle specifying the longitude and latitude range of the region.
   * @param {Number} [options.minimumHeight=0.0] The minimum height of the region.
   * @param {Number} [options.maximumHeight=0.0] The maximum height of the region.
   * @param {Ellipsoid} [options.ellipsoid=Cesium.Ellipsoid.WGS84] The ellipsoid.
   * @param {Boolean} [options.computeBoundingVolumes=true] True to compute the {@link TileBoundingRegion#boundingVolume} and
   *                  {@link TileBoundingVolume#boundingSphere}. If false, these properties will be undefined.
   *
   * @private
   */
  function TileBoundingRegion(options) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options", options);
    Check.typeOf.object("options.rectangle", options.rectangle);
    //>>includeEnd('debug');

    this.rectangle = Rectangle.clone(options.rectangle);
    this.minimumHeight = defaultValue(options.minimumHeight, 0.0);
    this.maximumHeight = defaultValue(options.maximumHeight, 0.0);

    /**
     * The world coordinates of the southwest corner of the tile's rectangle.
     *
     * @type {Cartesian3}
     * @default Cartesian3()
     */
    this.southwestCornerCartesian = new Cartesian3();

    /**
     * The world coordinates of the northeast corner of the tile's rectangle.
     *
     * @type {Cartesian3}
     * @default Cartesian3()
     */
    this.northeastCornerCartesian = new Cartesian3();

    /**
     * A normal that, along with southwestCornerCartesian, defines a plane at the western edge of
     * the tile.  Any position above (in the direction of the normal) this plane is outside the tile.
     *
     * @type {Cartesian3}
     * @default Cartesian3()
     */
    this.westNormal = new Cartesian3();

    /**
     * A normal that, along with southwestCornerCartesian, defines a plane at the southern edge of
     * the tile.  Any position above (in the direction of the normal) this plane is outside the tile.
     * Because points of constant latitude do not necessary lie in a plane, positions below this
     * plane are not necessarily inside the tile, but they are close.
     *
     * @type {Cartesian3}
     * @default Cartesian3()
     */
    this.southNormal = new Cartesian3();

    /**
     * A normal that, along with northeastCornerCartesian, defines a plane at the eastern edge of
     * the tile.  Any position above (in the direction of the normal) this plane is outside the tile.
     *
     * @type {Cartesian3}
     * @default Cartesian3()
     */
    this.eastNormal = new Cartesian3();

    /**
     * A normal that, along with northeastCornerCartesian, defines a plane at the eastern edge of
     * the tile.  Any position above (in the direction of the normal) this plane is outside the tile.
     * Because points of constant latitude do not necessary lie in a plane, positions below this
     * plane are not necessarily inside the tile, but they are close.
     *
     * @type {Cartesian3}
     * @default Cartesian3()
     */
    this.northNormal = new Cartesian3();

    const ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);
    computeBox(this, options.rectangle, ellipsoid);

    this._orientedBoundingBox = undefined;
    this._boundingSphere = undefined;

    if (defaultValue(options.computeBoundingVolumes, true)) {
      this.computeBoundingVolumes(ellipsoid);
    }
  }

  Object.defineProperties(TileBoundingRegion.prototype, {
    /**
     * The underlying bounding volume
     *
     * @memberof TileBoundingRegion.prototype
     *
     * @type {Object}
     * @readonly
     */
    boundingVolume: {
      get: function () {
        return this._orientedBoundingBox;
      },
    },
    /**
     * The underlying bounding sphere
     *
     * @memberof TileBoundingRegion.prototype
     *
     * @type {BoundingSphere}
     * @readonly
     */
    boundingSphere: {
      get: function () {
        return this._boundingSphere;
      },
    },
  });

  TileBoundingRegion.prototype.computeBoundingVolumes = function (ellipsoid) {
    // An oriented bounding box that encloses this tile's region.  This is used to calculate tile visibility.
    this._orientedBoundingBox = OrientedBoundingBox.fromRectangle(
      this.rectangle,
      this.minimumHeight,
      this.maximumHeight,
      ellipsoid
    );

    this._boundingSphere = BoundingSphere.fromOrientedBoundingBox(
      this._orientedBoundingBox
    );
  };

  const cartesian3Scratch$1 = new Cartesian3();
  const cartesian3Scratch2 = new Cartesian3();
  const cartesian3Scratch3 = new Cartesian3();
  const westNormalScratch = new Cartesian3();
  const eastWestNormalScratch = new Cartesian3();
  const westernMidpointScratch = new Cartesian3();
  const easternMidpointScratch = new Cartesian3();
  const cartographicScratch$2 = new Cartographic();
  const planeScratch = new Plane(Cartesian3.UNIT_X, 0.0);
  const rayScratch = new Ray();

  function computeBox(tileBB, rectangle, ellipsoid) {
    ellipsoid.cartographicToCartesian(
      Rectangle.southwest(rectangle),
      tileBB.southwestCornerCartesian
    );
    ellipsoid.cartographicToCartesian(
      Rectangle.northeast(rectangle),
      tileBB.northeastCornerCartesian
    );

    // The middle latitude on the western edge.
    cartographicScratch$2.longitude = rectangle.west;
    cartographicScratch$2.latitude = (rectangle.south + rectangle.north) * 0.5;
    cartographicScratch$2.height = 0.0;
    const westernMidpointCartesian = ellipsoid.cartographicToCartesian(
      cartographicScratch$2,
      westernMidpointScratch
    );

    // Compute the normal of the plane on the western edge of the tile.
    const westNormal = Cartesian3.cross(
      westernMidpointCartesian,
      Cartesian3.UNIT_Z,
      westNormalScratch
    );
    Cartesian3.normalize(westNormal, tileBB.westNormal);

    // The middle latitude on the eastern edge.
    cartographicScratch$2.longitude = rectangle.east;
    const easternMidpointCartesian = ellipsoid.cartographicToCartesian(
      cartographicScratch$2,
      easternMidpointScratch
    );

    // Compute the normal of the plane on the eastern edge of the tile.
    const eastNormal = Cartesian3.cross(
      Cartesian3.UNIT_Z,
      easternMidpointCartesian,
      cartesian3Scratch$1
    );
    Cartesian3.normalize(eastNormal, tileBB.eastNormal);

    let westVector = Cartesian3.subtract(
      westernMidpointCartesian,
      easternMidpointCartesian,
      cartesian3Scratch$1
    );

    if (Cartesian3.magnitude(westVector) === 0.0) {
      westVector = Cartesian3.clone(westNormal, westVector);
    }

    const eastWestNormal = Cartesian3.normalize(
      westVector,
      eastWestNormalScratch
    );

    // Compute the normal of the plane bounding the southern edge of the tile.
    const south = rectangle.south;
    let southSurfaceNormal;

    if (south > 0.0) {
      // Compute a plane that doesn't cut through the tile.
      cartographicScratch$2.longitude = (rectangle.west + rectangle.east) * 0.5;
      cartographicScratch$2.latitude = south;
      const southCenterCartesian = ellipsoid.cartographicToCartesian(
        cartographicScratch$2,
        rayScratch.origin
      );
      Cartesian3.clone(eastWestNormal, rayScratch.direction);
      const westPlane = Plane.fromPointNormal(
        tileBB.southwestCornerCartesian,
        tileBB.westNormal,
        planeScratch
      );
      // Find a point that is on the west and the south planes
      IntersectionTests.rayPlane(
        rayScratch,
        westPlane,
        tileBB.southwestCornerCartesian
      );
      southSurfaceNormal = ellipsoid.geodeticSurfaceNormal(
        southCenterCartesian,
        cartesian3Scratch2
      );
    } else {
      southSurfaceNormal = ellipsoid.geodeticSurfaceNormalCartographic(
        Rectangle.southeast(rectangle),
        cartesian3Scratch2
      );
    }
    const southNormal = Cartesian3.cross(
      southSurfaceNormal,
      westVector,
      cartesian3Scratch3
    );
    Cartesian3.normalize(southNormal, tileBB.southNormal);

    // Compute the normal of the plane bounding the northern edge of the tile.
    const north = rectangle.north;
    let northSurfaceNormal;

    if (north < 0.0) {
      // Compute a plane that doesn't cut through the tile.
      cartographicScratch$2.longitude = (rectangle.west + rectangle.east) * 0.5;
      cartographicScratch$2.latitude = north;
      const northCenterCartesian = ellipsoid.cartographicToCartesian(
        cartographicScratch$2,
        rayScratch.origin
      );
      Cartesian3.negate(eastWestNormal, rayScratch.direction);
      const eastPlane = Plane.fromPointNormal(
        tileBB.northeastCornerCartesian,
        tileBB.eastNormal,
        planeScratch
      );
      // Find a point that is on the east and the north planes
      IntersectionTests.rayPlane(
        rayScratch,
        eastPlane,
        tileBB.northeastCornerCartesian
      );
      northSurfaceNormal = ellipsoid.geodeticSurfaceNormal(
        northCenterCartesian,
        cartesian3Scratch2
      );
    } else {
      northSurfaceNormal = ellipsoid.geodeticSurfaceNormalCartographic(
        Rectangle.northwest(rectangle),
        cartesian3Scratch2
      );
    }
    const northNormal = Cartesian3.cross(
      westVector,
      northSurfaceNormal,
      cartesian3Scratch3
    );
    Cartesian3.normalize(northNormal, tileBB.northNormal);
  }

  const southwestCornerScratch = new Cartesian3();
  const northeastCornerScratch = new Cartesian3();
  const negativeUnitY = new Cartesian3(0.0, -1.0, 0.0);
  const negativeUnitZ = new Cartesian3(0.0, 0.0, -1.0);
  const vectorScratch = new Cartesian3();

  function distanceToCameraRegion(tileBB, frameState) {
    const camera = frameState.camera;
    const cameraCartesianPosition = camera.positionWC;
    const cameraCartographicPosition = camera.positionCartographic;

    let result = 0.0;
    if (!Rectangle.contains(tileBB.rectangle, cameraCartographicPosition)) {
      let southwestCornerCartesian = tileBB.southwestCornerCartesian;
      let northeastCornerCartesian = tileBB.northeastCornerCartesian;
      let westNormal = tileBB.westNormal;
      let southNormal = tileBB.southNormal;
      let eastNormal = tileBB.eastNormal;
      let northNormal = tileBB.northNormal;

      if (frameState.mode !== SceneMode$1.SCENE3D) {
        southwestCornerCartesian = frameState.mapProjection.project(
          Rectangle.southwest(tileBB.rectangle),
          southwestCornerScratch
        );
        southwestCornerCartesian.z = southwestCornerCartesian.y;
        southwestCornerCartesian.y = southwestCornerCartesian.x;
        southwestCornerCartesian.x = 0.0;
        northeastCornerCartesian = frameState.mapProjection.project(
          Rectangle.northeast(tileBB.rectangle),
          northeastCornerScratch
        );
        northeastCornerCartesian.z = northeastCornerCartesian.y;
        northeastCornerCartesian.y = northeastCornerCartesian.x;
        northeastCornerCartesian.x = 0.0;
        westNormal = negativeUnitY;
        eastNormal = Cartesian3.UNIT_Y;
        southNormal = negativeUnitZ;
        northNormal = Cartesian3.UNIT_Z;
      }

      const vectorFromSouthwestCorner = Cartesian3.subtract(
        cameraCartesianPosition,
        southwestCornerCartesian,
        vectorScratch
      );
      const distanceToWestPlane = Cartesian3.dot(
        vectorFromSouthwestCorner,
        westNormal
      );
      const distanceToSouthPlane = Cartesian3.dot(
        vectorFromSouthwestCorner,
        southNormal
      );

      const vectorFromNortheastCorner = Cartesian3.subtract(
        cameraCartesianPosition,
        northeastCornerCartesian,
        vectorScratch
      );
      const distanceToEastPlane = Cartesian3.dot(
        vectorFromNortheastCorner,
        eastNormal
      );
      const distanceToNorthPlane = Cartesian3.dot(
        vectorFromNortheastCorner,
        northNormal
      );

      if (distanceToWestPlane > 0.0) {
        result += distanceToWestPlane * distanceToWestPlane;
      } else if (distanceToEastPlane > 0.0) {
        result += distanceToEastPlane * distanceToEastPlane;
      }

      if (distanceToSouthPlane > 0.0) {
        result += distanceToSouthPlane * distanceToSouthPlane;
      } else if (distanceToNorthPlane > 0.0) {
        result += distanceToNorthPlane * distanceToNorthPlane;
      }
    }

    let cameraHeight;
    let minimumHeight;
    let maximumHeight;
    if (frameState.mode === SceneMode$1.SCENE3D) {
      cameraHeight = cameraCartographicPosition.height;
      minimumHeight = tileBB.minimumHeight;
      maximumHeight = tileBB.maximumHeight;
    } else {
      cameraHeight = cameraCartesianPosition.x;
      minimumHeight = 0.0;
      maximumHeight = 0.0;
    }

    if (cameraHeight > maximumHeight) {
      const distanceAboveTop = cameraHeight - maximumHeight;
      result += distanceAboveTop * distanceAboveTop;
    } else if (cameraHeight < minimumHeight) {
      const distanceBelowBottom = minimumHeight - cameraHeight;
      result += distanceBelowBottom * distanceBelowBottom;
    }

    return Math.sqrt(result);
  }

  /**
   * Gets the distance from the camera to the closest point on the tile.  This is used for level of detail selection.
   *
   * @param {FrameState} frameState The state information of the current rendering frame.
   * @returns {Number} The distance from the camera to the closest point on the tile, in meters.
   */
  TileBoundingRegion.prototype.distanceToCamera = function (frameState) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("frameState", frameState);
    //>>includeEnd('debug');

    const regionResult = distanceToCameraRegion(this, frameState);
    if (
      frameState.mode === SceneMode$1.SCENE3D &&
      defined(this._orientedBoundingBox)
    ) {
      const obbResult = Math.sqrt(
        this._orientedBoundingBox.distanceSquaredTo(frameState.camera.positionWC)
      );
      return Math.max(regionResult, obbResult);
    }
    return regionResult;
  };

  /**
   * Determines which side of a plane this box is located.
   *
   * @param {Plane} plane The plane to test against.
   * @returns {Intersect} {@link Intersect.INSIDE} if the entire box is on the side of the plane
   *                      the normal is pointing, {@link Intersect.OUTSIDE} if the entire box is
   *                      on the opposite side, and {@link Intersect.INTERSECTING} if the box
   *                      intersects the plane.
   */
  TileBoundingRegion.prototype.intersectPlane = function (plane) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("plane", plane);
    //>>includeEnd('debug');
    return this._orientedBoundingBox.intersectPlane(plane);
  };

  /**
   * Creates a debug primitive that shows the outline of the tile bounding region.
   *
   * @param {Color} color The desired color of the primitive's mesh
   * @return {Primitive}
   *
   * @private
   */
  TileBoundingRegion.prototype.createDebugVolume = function (color) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("color", color);
    //>>includeEnd('debug');

    const modelMatrix = new Matrix4.clone(Matrix4.IDENTITY);
    const geometry = new RectangleOutlineGeometry({
      rectangle: this.rectangle,
      height: this.minimumHeight,
      extrudedHeight: this.maximumHeight,
    });
    const instance = new GeometryInstance({
      geometry: geometry,
      id: "outline",
      modelMatrix: modelMatrix,
      attributes: {
        color: ColorGeometryInstanceAttribute.fromColor(color),
      },
    });

    return new Primitive$3({
      geometryInstances: instance,
      appearance: new PerInstanceColorAppearance({
        translucent: false,
        flat: true,
      }),
      asynchronous: false,
    });
  };

  let centerCartographicScratch$1 = new Cartographic();
  /**
   * A tile bounding volume specified as an S2 cell token with minimum and maximum heights.
   * The bounding volume is a k DOP. A k-DOP is the Boolean intersection of extents along k directions.
   *
   * @alias TileBoundingS2Cell
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {String} options.token The token of the S2 cell.
   * @param {Number} [options.minimumHeight=0.0] The minimum height of the bounding volume.
   * @param {Number} [options.maximumHeight=0.0] The maximum height of the bounding volume.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid.
   * @param {Boolean} [options.computeBoundingVolumes=true] True to compute the {@link TileBoundingS2Cell#boundingVolume} and
   *                  {@link TileBoundingS2Cell#boundingSphere}. If false, these properties will be undefined.
   *
   * @private
   */
  function TileBoundingS2Cell(options) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options", options);
    Check.typeOf.string("options.token", options.token);
    //>>includeEnd('debug');

    const s2Cell = S2Cell.fromToken(options.token);
    const minimumHeight = defaultValue(options.minimumHeight, 0.0);
    const maximumHeight = defaultValue(options.maximumHeight, 0.0);
    const ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);

    this.s2Cell = s2Cell;
    this.minimumHeight = minimumHeight;
    this.maximumHeight = maximumHeight;
    this.ellipsoid = ellipsoid;

    const boundingPlanes = computeBoundingPlanes(
      s2Cell,
      minimumHeight,
      maximumHeight,
      ellipsoid
    );
    this._boundingPlanes = boundingPlanes;

    // Pre-compute vertices to speed up the plane intersection test.
    const vertices = computeVertices(boundingPlanes);
    this._vertices = vertices;

    // Pre-compute edge normals to speed up the point-polygon distance check in distanceToCamera.
    this._edgeNormals = new Array(6);

    this._edgeNormals[0] = computeEdgeNormals(
      boundingPlanes[0],
      vertices.slice(0, 4)
    );
    let i;
    // Based on the way the edge normals are computed, the edge normals all point away from the "face"
    // of the polyhedron they surround, except the plane for the top plane. Therefore, we negate the normals
    // for the top plane.
    for (i = 0; i < 4; i++) {
      this._edgeNormals[0][i] = Cartesian3.negate(
        this._edgeNormals[0][i],
        this._edgeNormals[0][i]
      );
    }

    this._edgeNormals[1] = computeEdgeNormals(
      boundingPlanes[1],
      vertices.slice(4, 8)
    );
    for (i = 0; i < 4; i++) {
      // For each plane, iterate through the vertices in CCW order.
      this._edgeNormals[2 + i] = computeEdgeNormals(boundingPlanes[2 + i], [
        vertices[i % 4],
        vertices[(i + 1) % 4],
        vertices[4 + ((i + 1) % 4)],
        vertices[4 + i],
      ]);
    }

    this._planeVertices = [
      this._vertices.slice(0, 4),
      this._vertices.slice(4, 8),
    ];
    for (i = 0; i < 4; i++) {
      this._planeVertices.push([
        this._vertices[i % 4],
        this._vertices[(i + 1) % 4],
        this._vertices[4 + ((i + 1) % 4)],
        this._vertices[4 + i],
      ]);
    }

    const center = s2Cell.getCenter();
    centerCartographicScratch$1 = ellipsoid.cartesianToCartographic(
      center,
      centerCartographicScratch$1
    );
    centerCartographicScratch$1.height = (maximumHeight + minimumHeight) / 2;
    this.center = ellipsoid.cartographicToCartesian(
      centerCartographicScratch$1,
      center
    );

    this._boundingSphere = BoundingSphere.fromPoints(vertices);
  }

  const centerGeodeticNormalScratch = new Cartesian3();
  const topCartographicScratch = new Cartographic();
  const topScratch = new Cartesian3();
  const vertexCartographicScratch = new Cartographic();
  const vertexScratch = new Cartesian3();
  const vertexGeodeticNormalScratch = new Cartesian3();
  const sideNormalScratch = new Cartesian3();
  const sideScratch = new Cartesian3();
  /**
   * Computes bounding planes of the kDOP.
   * @private
   */
  function computeBoundingPlanes(
    s2Cell,
    minimumHeight,
    maximumHeight,
    ellipsoid
  ) {
    const planes = new Array(6);
    const centerPoint = s2Cell.getCenter();

    // Compute top plane.
    // - Get geodetic surface normal at the center of the S2 cell.
    // - Get center point at maximum height of bounding volume.
    // - Create top plane from surface normal and top point.
    const centerSurfaceNormal = ellipsoid.geodeticSurfaceNormal(
      centerPoint,
      centerGeodeticNormalScratch
    );
    const topCartographic = ellipsoid.cartesianToCartographic(
      centerPoint,
      topCartographicScratch
    );
    topCartographic.height = maximumHeight;
    const top = ellipsoid.cartographicToCartesian(topCartographic, topScratch);
    const topPlane = Plane.fromPointNormal(top, centerSurfaceNormal);
    planes[0] = topPlane;

    // Compute bottom plane.
    // - Iterate through bottom vertices
    //   - Get distance from vertex to top plane
    // - Find longest distance from vertex to top plane
    // - Translate top plane by the distance
    let maxDistance = 0;
    let i;
    const vertices = [];
    let vertex, vertexCartographic;
    for (i = 0; i < 4; i++) {
      vertex = s2Cell.getVertex(i);
      vertices[i] = vertex;
      vertexCartographic = ellipsoid.cartesianToCartographic(
        vertex,
        vertexCartographicScratch
      );
      vertexCartographic.height = minimumHeight;
      const distance = Plane.getPointDistance(
        topPlane,
        ellipsoid.cartographicToCartesian(vertexCartographic, vertexScratch)
      );
      if (distance < maxDistance) {
        maxDistance = distance;
      }
    }
    const bottomPlane = Plane.clone(topPlane);
    // Negate the normal of the bottom plane since we want all normals to point "outwards".
    bottomPlane.normal = Cartesian3.negate(
      bottomPlane.normal,
      bottomPlane.normal
    );
    bottomPlane.distance = bottomPlane.distance * -1 + maxDistance;
    planes[1] = bottomPlane;

    // Compute side planes.
    // - Iterate through vertices (in CCW order, by default)
    //   - Get a vertex and another vertex adjacent to it.
    //   - Compute geodetic surface normal at one vertex.
    //   - Compute vector between vertices.
    //   - Compute normal of side plane. (cross product of top dir and side dir)
    for (i = 0; i < 4; i++) {
      vertex = vertices[i];
      const adjacentVertex = vertices[(i + 1) % 4];
      const geodeticNormal = ellipsoid.geodeticSurfaceNormal(
        vertex,
        vertexGeodeticNormalScratch
      );
      const side = Cartesian3.subtract(adjacentVertex, vertex, sideScratch);
      let sideNormal = Cartesian3.cross(side, geodeticNormal, sideNormalScratch);
      sideNormal = Cartesian3.normalize(sideNormal, sideNormal);
      planes[2 + i] = Plane.fromPointNormal(vertex, sideNormal);
    }

    return planes;
  }

  let n0Scratch = new Cartesian3();
  let n1Scratch = new Cartesian3();
  let n2Scratch = new Cartesian3();
  let x0Scratch = new Cartesian3();
  let x1Scratch = new Cartesian3();
  let x2Scratch = new Cartesian3();
  const t0Scratch = new Cartesian3();
  const t1Scratch = new Cartesian3();
  const t2Scratch = new Cartesian3();
  let f0Scratch = new Cartesian3();
  let f1Scratch = new Cartesian3();
  let f2Scratch = new Cartesian3();
  let sScratch = new Cartesian3();
  const matrixScratch = new Matrix3();
  /**
   * Computes intersection of 3 planes.
   * @private
   */
  function computeIntersection(p0, p1, p2) {
    n0Scratch = p0.normal;
    n1Scratch = p1.normal;
    n2Scratch = p2.normal;

    x0Scratch = Cartesian3.multiplyByScalar(p0.normal, -p0.distance, x0Scratch);
    x1Scratch = Cartesian3.multiplyByScalar(p1.normal, -p1.distance, x1Scratch);
    x2Scratch = Cartesian3.multiplyByScalar(p2.normal, -p2.distance, x2Scratch);

    f0Scratch = Cartesian3.multiplyByScalar(
      Cartesian3.cross(n1Scratch, n2Scratch, t0Scratch),
      Cartesian3.dot(x0Scratch, n0Scratch),
      f0Scratch
    );
    f1Scratch = Cartesian3.multiplyByScalar(
      Cartesian3.cross(n2Scratch, n0Scratch, t1Scratch),
      Cartesian3.dot(x1Scratch, n1Scratch),
      f1Scratch
    );
    f2Scratch = Cartesian3.multiplyByScalar(
      Cartesian3.cross(n0Scratch, n1Scratch, t2Scratch),
      Cartesian3.dot(x2Scratch, n2Scratch),
      f2Scratch
    );

    matrixScratch[0] = n0Scratch.x;
    matrixScratch[1] = n1Scratch.x;
    matrixScratch[2] = n2Scratch.x;
    matrixScratch[3] = n0Scratch.y;
    matrixScratch[4] = n1Scratch.y;
    matrixScratch[5] = n2Scratch.y;
    matrixScratch[6] = n0Scratch.z;
    matrixScratch[7] = n1Scratch.z;
    matrixScratch[8] = n2Scratch.z;
    const determinant = Matrix3.determinant(matrixScratch);
    sScratch = Cartesian3.add(f0Scratch, f1Scratch, sScratch);
    sScratch = Cartesian3.add(sScratch, f2Scratch, sScratch);
    return new Cartesian3(
      sScratch.x / determinant,
      sScratch.y / determinant,
      sScratch.z / determinant
    );
  }
  /**
   * Compute the vertices of the kDOP.
   * @private
   */
  function computeVertices(boundingPlanes) {
    const vertices = new Array(8);
    for (let i = 0; i < 4; i++) {
      // Vertices on the top plane.
      vertices[i] = computeIntersection(
        boundingPlanes[0],
        boundingPlanes[2 + ((i + 3) % 4)],
        boundingPlanes[2 + (i % 4)]
      );
      // Vertices on the bottom plane.
      vertices[i + 4] = computeIntersection(
        boundingPlanes[1],
        boundingPlanes[2 + ((i + 3) % 4)],
        boundingPlanes[2 + (i % 4)]
      );
    }
    return vertices;
  }

  let edgeScratch = new Cartesian3();
  let edgeNormalScratch = new Cartesian3();
  /**
   * Compute edge normals on a plane.
   * @private
   */
  function computeEdgeNormals(plane, vertices) {
    const edgeNormals = [];
    for (let i = 0; i < 4; i++) {
      edgeScratch = Cartesian3.subtract(
        vertices[(i + 1) % 4],
        vertices[i],
        edgeScratch
      );
      edgeNormalScratch = Cartesian3.cross(
        plane.normal,
        edgeScratch,
        edgeNormalScratch
      );
      edgeNormalScratch = Cartesian3.normalize(
        edgeNormalScratch,
        edgeNormalScratch
      );
      edgeNormals[i] = Cartesian3.clone(edgeNormalScratch);
    }
    return edgeNormals;
  }

  Object.defineProperties(TileBoundingS2Cell.prototype, {
    /**
     * The underlying bounding volume.
     *
     * @memberof TileOrientedBoundingBox.prototype
     *
     * @type {Object}
     * @readonly
     */
    boundingVolume: {
      get: function () {
        return this;
      },
    },
    /**
     * The underlying bounding sphere.
     *
     * @memberof TileOrientedBoundingBox.prototype
     *
     * @type {BoundingSphere}
     * @readonly
     */
    boundingSphere: {
      get: function () {
        return this._boundingSphere;
      },
    },
  });

  const facePointScratch = new Cartesian3();
  /**
   * The distance to point check for this kDOP involves checking the signed distance of the point to each bounding
   * plane. A plane qualifies for a distance check if the point being tested against is in the half-space in the direction
   * of the normal i.e. if the signed distance of the point from the plane is greater than 0.
   *
   * There are 4 possible cases for a point if it is outside the polyhedron:
   *
   *   \     X     /     X \           /       \           /       \           /
   * ---\---------/---   ---\---------/---   ---X---------/---   ---\---------/---
   *     \       /           \       /           \       /           \       /
   *   ---\-----/---       ---\-----/---       ---\-----/---       ---\-----/---
   *       \   /               \   /               \   /               \   /
   *                                                                    \ /
   *                                                                     \
   *                                                                    / \
   *                                                                   / X \
   *
   *         I                  II                  III                 IV
   *
   * Case I: There is only one plane selected.
   * In this case, we project the point onto the plane and do a point polygon distance check to find the closest point on the polygon.
   * The point may lie inside the "face" of the polygon or outside. If it is outside, we need to determine which edges to test against.
   *
   * Case II: There are two planes selected.
   * In this case, the point will lie somewhere on the line created at the intersection of the selected planes or one of the planes.
   *
   * Case III: There are three planes selected.
   * In this case, the point will lie on the vertex, at the intersection of the selected planes.
   *
   * Case IV: There are more than three planes selected.
   * Since we are on an ellipsoid, this will only happen in the bottom plane, which is what we will use for the distance test.
   */
  TileBoundingS2Cell.prototype.distanceToCamera = function (frameState) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("frameState", frameState);
    //>>includeEnd('debug');

    const point = frameState.camera.positionWC;

    const selectedPlaneIndices = [];
    const vertices = [];
    let edgeNormals;

    if (Plane.getPointDistance(this._boundingPlanes[0], point) > 0) {
      selectedPlaneIndices.push(0);
      vertices.push(this._planeVertices[0]);
      edgeNormals = this._edgeNormals[0];
    } else if (Plane.getPointDistance(this._boundingPlanes[1], point) > 0) {
      selectedPlaneIndices.push(1);
      vertices.push(this._planeVertices[1]);
      edgeNormals = this._edgeNormals[1];
    }

    let i;
    let sidePlaneIndex;
    for (i = 0; i < 4; i++) {
      sidePlaneIndex = 2 + i;
      if (
        Plane.getPointDistance(this._boundingPlanes[sidePlaneIndex], point) > 0
      ) {
        selectedPlaneIndices.push(sidePlaneIndex);
        // Store vertices in CCW order.
        vertices.push(this._planeVertices[sidePlaneIndex]);
        edgeNormals = this._edgeNormals[sidePlaneIndex];
      }
    }

    // Check if inside all planes.
    if (selectedPlaneIndices.length === 0) {
      return 0.0;
    }

    // We use the skip variable when the side plane indices are non-consecutive.
    let facePoint;
    let selectedPlane;
    if (selectedPlaneIndices.length === 1) {
      // Handles Case I
      selectedPlane = this._boundingPlanes[selectedPlaneIndices[0]];
      facePoint = closestPointPolygon(
        Plane.projectPointOntoPlane(selectedPlane, point, facePointScratch),
        vertices[0],
        selectedPlane,
        edgeNormals
      );

      return Cartesian3.distance(facePoint, point);
    } else if (selectedPlaneIndices.length === 2) {
      // Handles Case II
      // Since we are on the ellipsoid, the dihedral angle between a top plane and a side plane
      // will always be acute, so we can do a faster check there.
      if (selectedPlaneIndices[0] === 0) {
        const edge = [
          this._vertices[
            4 * selectedPlaneIndices[0] + (selectedPlaneIndices[1] - 2)
          ],
          this._vertices[
            4 * selectedPlaneIndices[0] + ((selectedPlaneIndices[1] - 2 + 1) % 4)
          ],
        ];
        facePoint = closestPointLineSegment(point, edge[0], edge[1]);
        return Cartesian3.distance(facePoint, point);
      }
      let minimumDistance = Number.MAX_VALUE;
      let distance;
      for (i = 0; i < 2; i++) {
        selectedPlane = this._boundingPlanes[selectedPlaneIndices[i]];
        facePoint = closestPointPolygon(
          Plane.projectPointOntoPlane(selectedPlane, point, facePointScratch),
          vertices[i],
          selectedPlane,
          this._edgeNormals[selectedPlaneIndices[i]]
        );

        distance = Cartesian3.distanceSquared(facePoint, point);
        if (distance < minimumDistance) {
          minimumDistance = distance;
        }
      }
      return Math.sqrt(minimumDistance);
    } else if (selectedPlaneIndices.length > 3) {
      // Handles Case IV
      facePoint = closestPointPolygon(
        Plane.projectPointOntoPlane(
          this._boundingPlanes[1],
          point,
          facePointScratch
        ),
        this._planeVertices[1],
        this._boundingPlanes[1],
        this._edgeNormals[1]
      );
      return Cartesian3.distance(facePoint, point);
    }

    // Handles Case III
    const skip =
      selectedPlaneIndices[1] === 2 && selectedPlaneIndices[2] === 5 ? 0 : 1;

    // Vertex is on top plane.
    if (selectedPlaneIndices[0] === 0) {
      return Cartesian3.distance(
        point,
        this._vertices[(selectedPlaneIndices[1] - 2 + skip) % 4]
      );
    }

    // Vertex is on bottom plane.
    return Cartesian3.distance(
      point,
      this._vertices[4 + ((selectedPlaneIndices[1] - 2 + skip) % 4)]
    );
  };

  const dScratch = new Cartesian3();
  const pL0Scratch = new Cartesian3();
  /**
   * Finds point on a line segment closest to a given point.
   * @private
   */
  function closestPointLineSegment(p, l0, l1) {
    const d = Cartesian3.subtract(l1, l0, dScratch);
    const pL0 = Cartesian3.subtract(p, l0, pL0Scratch);
    let t = Cartesian3.dot(d, pL0);

    if (t <= 0) {
      return l0;
    }

    const dMag = Cartesian3.dot(d, d);
    if (t >= dMag) {
      return l1;
    }

    t = t / dMag;
    return new Cartesian3(
      (1 - t) * l0.x + t * l1.x,
      (1 - t) * l0.y + t * l1.y,
      (1 - t) * l0.z + t * l1.z
    );
  }

  const edgePlaneScratch = new Plane(Cartesian3.UNIT_X, 0.0);
  /**
   * Finds closes point on the polygon, created by the given vertices, from
   * a point. The test point and the polygon are all on the same plane.
   * @private
   */
  function closestPointPolygon(p, vertices, plane, edgeNormals) {
    let minDistance = Number.MAX_VALUE;
    let distance;
    let closestPoint;
    let closestPointOnEdge;

    for (let i = 0; i < vertices.length; i++) {
      const edgePlane = Plane.fromPointNormal(
        vertices[i],
        edgeNormals[i],
        edgePlaneScratch
      );
      const edgePlaneDistance = Plane.getPointDistance(edgePlane, p);

      // Skip checking against the edge if the point is not in the half-space that the
      // edgePlane's normal points towards i.e. if the edgePlane is facing away from the point.
      if (edgePlaneDistance < 0) {
        continue;
      }

      closestPointOnEdge = closestPointLineSegment(
        p,
        vertices[i],
        vertices[(i + 1) % 4]
      );

      distance = Cartesian3.distance(p, closestPointOnEdge);
      if (distance < minDistance) {
        minDistance = distance;
        closestPoint = closestPointOnEdge;
      }
    }

    if (!defined(closestPoint)) {
      return p;
    }
    return closestPoint;
  }

  /**
   * Determines which side of a plane this volume is located.
   *
   * @param {Plane} plane The plane to test against.
   * @returns {Intersect} {@link Intersect.INSIDE} if the entire volume is on the side of the plane
   *                      the normal is pointing, {@link Intersect.OUTSIDE} if the entire volume is
   *                      on the opposite side, and {@link Intersect.INTERSECTING} if the volume
   *                      intersects the plane.
   */
  TileBoundingS2Cell.prototype.intersectPlane = function (plane) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("plane", plane);
    //>>includeEnd('debug');

    let plusCount = 0;
    let negCount = 0;
    for (let i = 0; i < this._vertices.length; i++) {
      const distanceToPlane =
        Cartesian3.dot(plane.normal, this._vertices[i]) + plane.distance;
      if (distanceToPlane < 0) {
        negCount++;
      } else {
        plusCount++;
      }
    }

    if (plusCount === this._vertices.length) {
      return Intersect$1.INSIDE;
    } else if (negCount === this._vertices.length) {
      return Intersect$1.OUTSIDE;
    }
    return Intersect$1.INTERSECTING;
  };

  /**
   * Creates a debug primitive that shows the outline of the tile bounding
   * volume.
   *
   * @param {Color} color The desired color of the primitive's mesh
   * @return {Primitive}
   */
  TileBoundingS2Cell.prototype.createDebugVolume = function (color) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("color", color);
    //>>includeEnd('debug');

    const modelMatrix = new Matrix4.clone(Matrix4.IDENTITY);
    const topPlanePolygon = new CoplanarPolygonOutlineGeometry({
      polygonHierarchy: {
        positions: this._planeVertices[0],
      },
    });
    const topPlaneGeometry = CoplanarPolygonOutlineGeometry.createGeometry(
      topPlanePolygon
    );
    const topPlaneInstance = new GeometryInstance({
      geometry: topPlaneGeometry,
      id: "outline",
      modelMatrix: modelMatrix,
      attributes: {
        color: ColorGeometryInstanceAttribute.fromColor(color),
      },
    });

    const bottomPlanePolygon = new CoplanarPolygonOutlineGeometry({
      polygonHierarchy: {
        positions: this._planeVertices[1],
      },
    });
    const bottomPlaneGeometry = CoplanarPolygonOutlineGeometry.createGeometry(
      bottomPlanePolygon
    );
    const bottomPlaneInstance = new GeometryInstance({
      geometry: bottomPlaneGeometry,
      id: "outline",
      modelMatrix: modelMatrix,
      attributes: {
        color: ColorGeometryInstanceAttribute.fromColor(color),
      },
    });

    const sideInstances = [];
    for (let i = 0; i < 4; i++) {
      const sidePlanePolygon = new CoplanarPolygonOutlineGeometry({
        polygonHierarchy: {
          positions: this._planeVertices[2 + i],
        },
      });
      const sidePlaneGeometry = CoplanarPolygonOutlineGeometry.createGeometry(
        sidePlanePolygon
      );
      sideInstances[i] = new GeometryInstance({
        geometry: sidePlaneGeometry,
        id: "outline",
        modelMatrix: modelMatrix,
        attributes: {
          color: ColorGeometryInstanceAttribute.fromColor(color),
        },
      });
    }

    return new Primitive$3({
      geometryInstances: [
        sideInstances[0],
        sideInstances[1],
        sideInstances[2],
        sideInstances[3],
        bottomPlaneInstance,
        topPlaneInstance,
      ],
      appearance: new PerInstanceColorAppearance({
        translucent: false,
        flat: true,
      }),
      asynchronous: false,
    });
  };

  /**
   * A tile bounding volume specified as a sphere.
   * @alias TileBoundingSphere
   * @constructor
   *
   * @param {Cartesian3} [center=Cartesian3.ZERO] The center of the bounding sphere.
   * @param {Number} [radius=0.0] The radius of the bounding sphere.
   *
   * @private
   */
  function TileBoundingSphere(center, radius) {
    if (radius === 0) {
      radius = CesiumMath.EPSILON7;
    }
    this._boundingSphere = new BoundingSphere(center, radius);
  }

  Object.defineProperties(TileBoundingSphere.prototype, {
    /**
     * The center of the bounding sphere
     *
     * @memberof TileBoundingSphere.prototype
     *
     * @type {Cartesian3}
     * @readonly
     */
    center: {
      get: function () {
        return this._boundingSphere.center;
      },
    },

    /**
     * The radius of the bounding sphere
     *
     * @memberof TileBoundingSphere.prototype
     *
     * @type {Number}
     * @readonly
     */
    radius: {
      get: function () {
        return this._boundingSphere.radius;
      },
    },

    /**
     * The underlying bounding volume
     *
     * @memberof TileBoundingSphere.prototype
     *
     * @type {Object}
     * @readonly
     */
    boundingVolume: {
      get: function () {
        return this._boundingSphere;
      },
    },
    /**
     * The underlying bounding sphere
     *
     * @memberof TileBoundingSphere.prototype
     *
     * @type {BoundingSphere}
     * @readonly
     */
    boundingSphere: {
      get: function () {
        return this._boundingSphere;
      },
    },
  });

  /**
   * Computes the distance between this bounding sphere and the camera attached to frameState.
   *
   * @param {FrameState} frameState The frameState to which the camera is attached.
   * @returns {Number} The distance between the camera and the bounding sphere in meters. Returns 0 if the camera is inside the bounding volume.
   *
   */
  TileBoundingSphere.prototype.distanceToCamera = function (frameState) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("frameState", frameState);
    //>>includeEnd('debug');
    const boundingSphere = this._boundingSphere;
    return Math.max(
      0.0,
      Cartesian3.distance(boundingSphere.center, frameState.camera.positionWC) -
        boundingSphere.radius
    );
  };

  /**
   * Determines which side of a plane this 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.
   */
  TileBoundingSphere.prototype.intersectPlane = function (plane) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("plane", plane);
    //>>includeEnd('debug');
    return BoundingSphere.intersectPlane(this._boundingSphere, plane);
  };

  /**
   * Update the bounding sphere after the tile is transformed.
   *
   * @param {Cartesian3} center The center of the bounding sphere.
   * @param {Number} radius The radius of the bounding sphere.
   */
  TileBoundingSphere.prototype.update = function (center, radius) {
    Cartesian3.clone(center, this._boundingSphere.center);
    this._boundingSphere.radius = radius;
  };

  /**
   * Creates a debug primitive that shows the outline of the sphere.
   *
   * @param {Color} color The desired color of the primitive's mesh
   * @return {Primitive}
   */
  TileBoundingSphere.prototype.createDebugVolume = function (color) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("color", color);
    //>>includeEnd('debug');
    const geometry = new SphereOutlineGeometry({
      radius: this.radius,
    });
    const modelMatrix = Matrix4.fromTranslation(
      this.center,
      new Matrix4.clone(Matrix4.IDENTITY)
    );
    const instance = new GeometryInstance({
      geometry: geometry,
      id: "outline",
      modelMatrix: modelMatrix,
      attributes: {
        color: ColorGeometryInstanceAttribute.fromColor(color),
      },
    });

    return new Primitive$3({
      geometryInstances: instance,
      appearance: new PerInstanceColorAppearance({
        translucent: false,
        flat: true,
      }),
      asynchronous: false,
    });
  };

  const scratchU = new Cartesian3();
  const scratchV = new Cartesian3();
  const scratchW = new Cartesian3();
  const scratchCartesian$6 = new Cartesian3();

  function computeMissingVector(a, b, result) {
    result = Cartesian3.cross(a, b, result);
    const magnitude = Cartesian3.magnitude(result);
    return Cartesian3.multiplyByScalar(
      result,
      CesiumMath.EPSILON7 / magnitude,
      result
    );
  }

  function findOrthogonalVector(a, result) {
    const temp = Cartesian3.normalize(a, scratchCartesian$6);
    const b = Cartesian3.equalsEpsilon(
      temp,
      Cartesian3.UNIT_X,
      CesiumMath.EPSILON6
    )
      ? Cartesian3.UNIT_Y
      : Cartesian3.UNIT_X;
    return computeMissingVector(a, b, result);
  }

  function checkHalfAxes(halfAxes) {
    let u = Matrix3.getColumn(halfAxes, 0, scratchU);
    let v = Matrix3.getColumn(halfAxes, 1, scratchV);
    let w = Matrix3.getColumn(halfAxes, 2, scratchW);

    const uZero = Cartesian3.equals(u, Cartesian3.ZERO);
    const vZero = Cartesian3.equals(v, Cartesian3.ZERO);
    const wZero = Cartesian3.equals(w, Cartesian3.ZERO);

    if (!uZero && !vZero && !wZero) {
      return halfAxes;
    }
    if (uZero && vZero && wZero) {
      halfAxes[0] = CesiumMath.EPSILON7;
      halfAxes[4] = CesiumMath.EPSILON7;
      halfAxes[8] = CesiumMath.EPSILON7;
      return halfAxes;
    }
    if (uZero && !vZero && !wZero) {
      u = computeMissingVector(v, w, u);
    } else if (!uZero && vZero && !wZero) {
      v = computeMissingVector(u, w, v);
    } else if (!uZero && !vZero && wZero) {
      w = computeMissingVector(v, u, w);
    } else if (!uZero) {
      v = findOrthogonalVector(u, v);
      w = computeMissingVector(v, u, w);
    } else if (!vZero) {
      u = findOrthogonalVector(v, u);
      w = computeMissingVector(v, u, w);
    } else if (!wZero) {
      u = findOrthogonalVector(w, u);
      v = computeMissingVector(w, u, v);
    }

    Matrix3.setColumn(halfAxes, 0, u, halfAxes);
    Matrix3.setColumn(halfAxes, 1, v, halfAxes);
    Matrix3.setColumn(halfAxes, 2, w, halfAxes);

    return halfAxes;
  }

  /**
   * A tile bounding volume specified as an oriented bounding box.
   * @alias TileOrientedBoundingBox
   * @constructor
   *
   * @param {Cartesian3} [center=Cartesian3.ZERO] The center of the box.
   * @param {Matrix3} [halfAxes=Matrix3.ZERO] The three orthogonal half-axes of the bounding box.
   *                                          Equivalently, the transformation matrix, to rotate and scale a 2x2x2
   *                                          cube centered at the origin.
   *
   * @private
   */
  function TileOrientedBoundingBox(center, halfAxes) {
    halfAxes = checkHalfAxes(halfAxes);
    this._orientedBoundingBox = new OrientedBoundingBox(center, halfAxes);
    this._boundingSphere = BoundingSphere.fromOrientedBoundingBox(
      this._orientedBoundingBox
    );
  }

  Object.defineProperties(TileOrientedBoundingBox.prototype, {
    /**
     * The underlying bounding volume.
     *
     * @memberof TileOrientedBoundingBox.prototype
     *
     * @type {Object}
     * @readonly
     */
    boundingVolume: {
      get: function () {
        return this._orientedBoundingBox;
      },
    },
    /**
     * The underlying bounding sphere.
     *
     * @memberof TileOrientedBoundingBox.prototype
     *
     * @type {BoundingSphere}
     * @readonly
     */
    boundingSphere: {
      get: function () {
        return this._boundingSphere;
      },
    },
  });

  /**
   * Computes the distance between this bounding box and the camera attached to frameState.
   *
   * @param {FrameState} frameState The frameState to which the camera is attached.
   * @returns {Number} The distance between the camera and the bounding box in meters. Returns 0 if the camera is inside the bounding volume.
   */
  TileOrientedBoundingBox.prototype.distanceToCamera = function (frameState) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("frameState", frameState);
    //>>includeEnd('debug');
    return Math.sqrt(
      this._orientedBoundingBox.distanceSquaredTo(frameState.camera.positionWC)
    );
  };

  /**
   * Determines which side of a plane this box is located.
   *
   * @param {Plane} plane The plane to test against.
   * @returns {Intersect} {@link Intersect.INSIDE} if the entire box is on the side of the plane
   *                      the normal is pointing, {@link Intersect.OUTSIDE} if the entire box is
   *                      on the opposite side, and {@link Intersect.INTERSECTING} if the box
   *                      intersects the plane.
   */
  TileOrientedBoundingBox.prototype.intersectPlane = function (plane) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("plane", plane);
    //>>includeEnd('debug');
    return this._orientedBoundingBox.intersectPlane(plane);
  };

  /**
   * Update the bounding box after the tile is transformed.
   *
   * @param {Cartesian3} center The center of the box.
   * @param {Matrix3} halfAxes The three orthogonal half-axes of the bounding box.
   *                           Equivalently, the transformation matrix, to rotate and scale a 2x2x2
   *                           cube centered at the origin.
   */
  TileOrientedBoundingBox.prototype.update = function (center, halfAxes) {
    Cartesian3.clone(center, this._orientedBoundingBox.center);
    halfAxes = checkHalfAxes(halfAxes);
    Matrix3.clone(halfAxes, this._orientedBoundingBox.halfAxes);
    BoundingSphere.fromOrientedBoundingBox(
      this._orientedBoundingBox,
      this._boundingSphere
    );
  };

  /**
   * Creates a debug primitive that shows the outline of the box.
   *
   * @param {Color} color The desired color of the primitive's mesh
   * @return {Primitive}
   */
  TileOrientedBoundingBox.prototype.createDebugVolume = function (color) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("color", color);
    //>>includeEnd('debug');

    const geometry = new BoxOutlineGeometry({
      // Make a 2x2x2 cube
      minimum: new Cartesian3(-1.0, -1.0, -1.0),
      maximum: new Cartesian3(1.0, 1.0, 1.0),
    });
    const modelMatrix = Matrix4.fromRotationTranslation(
      this.boundingVolume.halfAxes,
      this.boundingVolume.center
    );
    const instance = new GeometryInstance({
      geometry: geometry,
      id: "outline",
      modelMatrix: modelMatrix,
      attributes: {
        color: ColorGeometryInstanceAttribute.fromColor(color),
      },
    });

    return new Primitive$3({
      geometryInstances: instance,
      appearance: new PerInstanceColorAppearance({
        translucent: false,
        flat: true,
      }),
      asynchronous: false,
    });
  };

  /**
   * A tile in a {@link Cesium3DTileset}.  When a tile is first created, its content is not loaded;
   * the content is loaded on-demand when needed based on the view.
   * <p>
   * Do not construct this directly, instead access tiles through {@link Cesium3DTileset#tileVisible}.
   * </p>
   *
   * @alias Cesium3DTile
   * @constructor
   */
  function Cesium3DTile(tileset, baseResource, header, parent) {
    this._tileset = tileset;
    this._header = header;

    const hasContentsArray = defined(header.contents);
    const hasMultipleContents =
      (hasContentsArray && header.contents.length > 1) ||
      hasExtension(header, "3DTILES_multiple_contents");

    // In the 1.0 schema, content is stored in tile.content instead of tile.contents
    const contentHeader =
      hasContentsArray && !hasMultipleContents
        ? header.contents[0]
        : header.content;

    this._contentHeader = contentHeader;

    /**
     * The local transform of this tile.
     * @type {Matrix4}
     */
    this.transform = defined(header.transform)
      ? Matrix4.unpack(header.transform)
      : Matrix4.clone(Matrix4.IDENTITY);

    const parentTransform = defined(parent)
      ? parent.computedTransform
      : tileset.modelMatrix;
    const computedTransform = Matrix4.multiply(
      parentTransform,
      this.transform,
      new Matrix4()
    );

    const parentInitialTransform = defined(parent)
      ? parent._initialTransform
      : Matrix4.IDENTITY;
    this._initialTransform = Matrix4.multiply(
      parentInitialTransform,
      this.transform,
      new Matrix4()
    );

    /**
     * The final computed transform of this tile.
     * @type {Matrix4}
     * @readonly
     */
    this.computedTransform = computedTransform;

    this._boundingVolume = this.createBoundingVolume(
      header.boundingVolume,
      computedTransform
    );
    this._boundingVolume2D = undefined;

    let contentBoundingVolume;

    if (defined(contentHeader) && defined(contentHeader.boundingVolume)) {
      // Non-leaf tiles may have a content bounding-volume, which is a tight-fit bounding volume
      // around only the features in the tile.  This box is useful for culling for rendering,
      // but not for culling for traversing the tree since it does not guarantee spatial coherence, i.e.,
      // since it only bounds features in the tile, not the entire tile, children may be
      // outside of this box.
      contentBoundingVolume = this.createBoundingVolume(
        contentHeader.boundingVolume,
        computedTransform
      );
    }
    this._contentBoundingVolume = contentBoundingVolume;
    this._contentBoundingVolume2D = undefined;

    let viewerRequestVolume;
    if (defined(header.viewerRequestVolume)) {
      viewerRequestVolume = this.createBoundingVolume(
        header.viewerRequestVolume,
        computedTransform
      );
    }
    this._viewerRequestVolume = viewerRequestVolume;

    /**
     * The error, in meters, introduced if this tile is rendered and its children are not.
     * This is used to compute screen space error, i.e., the error measured in pixels.
     *
     * @type {Number}
     * @readonly
     */
    this.geometricError = header.geometricError;
    this._geometricError = header.geometricError;

    if (!defined(this._geometricError)) {
      this._geometricError = defined(parent)
        ? parent.geometricError
        : tileset._geometricError;
      Cesium3DTile._deprecationWarning(
        "geometricErrorUndefined",
        "Required property geometricError is undefined for this tile. Using parent's geometric error instead."
      );
    }

    this.updateGeometricErrorScale();

    let refine;
    if (defined(header.refine)) {
      if (header.refine === "replace" || header.refine === "add") {
        Cesium3DTile._deprecationWarning(
          "lowercase-refine",
          `This tile uses a lowercase refine "${
          header.refine
        }". Instead use "${header.refine.toUpperCase()}".`
        );
      }
      refine =
        header.refine.toUpperCase() === "REPLACE"
          ? Cesium3DTileRefine$1.REPLACE
          : Cesium3DTileRefine$1.ADD;
    } else if (defined(parent)) {
      // Inherit from parent tile if omitted.
      refine = parent.refine;
    } else {
      refine = Cesium3DTileRefine$1.REPLACE;
    }

    /**
     * Specifies the type of refinement that is used when traversing this tile for rendering.
     *
     * @type {Cesium3DTileRefine}
     * @readonly
     * @private
     */
    this.refine = refine;

    /**
     * Gets the tile's children.
     *
     * @type {Cesium3DTile[]}
     * @readonly
     */
    this.children = [];

    /**
     * This tile's parent or <code>undefined</code> if this tile is the root.
     * <p>
     * When a tile's content points to an external tileset JSON file, the external tileset's
     * root tile's parent is not <code>undefined</code>; instead, the parent references
     * the tile (with its content pointing to an external tileset JSON file) as if the two tilesets were merged.
     * </p>
     *
     * @type {Cesium3DTile}
     * @readonly
     */
    this.parent = parent;

    let content;
    let hasEmptyContent = false;
    let contentState;
    let contentResource;
    let serverKey;

    baseResource = Resource.createIfNeeded(baseResource);

    if (hasMultipleContents) {
      contentState = Cesium3DTileContentState$1.UNLOADED;
      // Each content may have its own URI, but they all need to be resolved
      // relative to the tileset, so the base resource is used.
      contentResource = baseResource.clone();
    } else if (defined(contentHeader)) {
      let contentHeaderUri = contentHeader.uri;
      if (defined(contentHeader.url)) {
        Cesium3DTile._deprecationWarning(
          "contentUrl",
          'This tileset JSON uses the "content.url" property which has been deprecated. Use "content.uri" instead.'
        );
        contentHeaderUri = contentHeader.url;
      }
      if (contentHeaderUri === "") {
        Cesium3DTile._deprecationWarning(
          "contentUriEmpty",
          "content.uri property is an empty string, which creates a circular dependency, making this tileset invalid. Omit the content property instead"
        );
        content = new Empty3DTileContent(tileset, this);
        hasEmptyContent = true;
        contentState = Cesium3DTileContentState$1.READY;
      } else {
        contentState = Cesium3DTileContentState$1.UNLOADED;
        contentResource = baseResource.getDerivedResource({
          url: contentHeaderUri,
        });
        serverKey = RequestScheduler.getServerKey(
          contentResource.getUrlComponent()
        );
      }
    } else {
      content = new Empty3DTileContent(tileset, this);
      hasEmptyContent = true;
      contentState = Cesium3DTileContentState$1.READY;
    }

    this._content = content;
    this._contentResource = contentResource;
    this._contentState = contentState;
    this._contentReadyToProcessPromise = undefined;
    this._contentReadyPromise = undefined;
    this._expiredContent = undefined;

    this._serverKey = serverKey;

    /**
     * When <code>true</code>, the tile has no content.
     *
     * @type {Boolean}
     * @readonly
     *
     * @private
     */
    this.hasEmptyContent = hasEmptyContent;

    /**
     * When <code>true</code>, the tile's content points to an external tileset.
     * <p>
     * This is <code>false</code> until the tile's content is loaded.
     * </p>
     *
     * @type {Boolean}
     * @readonly
     *
     * @private
     */
    this.hasTilesetContent = false;

    /**
     * When <code>true</code>, the tile's content is an implicit tileset.
     * <p>
     * This is <code>false</code> until the tile's implicit content is loaded.
     * </p>
     *
     * @type {Boolean}
     * @readonly
     *
     * @private
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     */
    this.hasImplicitContent = false;

    /**
     * When <code>true</code>, the tile contains content metadata from implicit tiling. This flag is set
     * for tiles transcoded by <code>Implicit3DTileContent</code>.
     * <p>
     * This is <code>false</code> until the tile's content is loaded.
     * </p>
     *
     * @type {Boolean}
     * @readonly
     *
     * @private
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     */
    this.hasImplicitContentMetadata = false;

    /**
     * When <code>true</code>, the tile has multiple contents, either in the tile JSON (3D Tiles 1.1)
     * or via the <code>3DTILES_multiple_contents</code> extension.
     *
     * @see {@link https://github.com/CesiumGS/3d-tiles/tree/main/extensions/3DTILES_multiple_contents|3DTILES_multiple_contents extension}
     *
     * @type {Boolean}
     * @readonly
     *
     * @private
     */
    this.hasMultipleContents = hasMultipleContents;

    /**
     * When tile metadata is present (3D Tiles 1.1) or the <code>3DTILES_metadata</code> extension is used,
     * this stores a {@link TileMetadata} object for accessing tile metadata.
     *
     * @type {TileMetadata}
     * @readonly
     * @private
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     */
    this.metadata = findTileMetadata(tileset, header);

    /**
     * The node in the tileset's LRU cache, used to determine when to unload a tile's content.
     *
     * See {@link Cesium3DTilesetCache}
     *
     * @type {DoublyLinkedListNode}
     * @readonly
     *
     * @private
     */
    this.cacheNode = undefined;

    const expire = header.expire;
    let expireDuration;
    let expireDate;
    if (defined(expire)) {
      expireDuration = expire.duration;
      if (defined(expire.date)) {
        expireDate = JulianDate.fromIso8601(expire.date);
      }
    }

    /**
     * The time in seconds after the tile's content is ready when the content expires and new content is requested.
     *
     * @type {Number}
     */
    this.expireDuration = expireDuration;

    /**
     * The date when the content expires and new content is requested.
     *
     * @type {JulianDate}
     */
    this.expireDate = expireDate;

    /**
     * The time when a style was last applied to this tile.
     *
     * @type {Number}
     *
     * @private
     */
    this.lastStyleTime = 0.0;

    /**
     * Marks whether the tile's children bounds are fully contained within the tile's bounds
     *
     * @type {Cesium3DTileOptimizationHint}
     *
     * @private
     */
    this._optimChildrenWithinParent = Cesium3DTileOptimizationHint$1.NOT_COMPUTED;

    /**
     * Tracks if the tile's relationship with a ClippingPlaneCollection has changed with regards
     * to the ClippingPlaneCollection's state.
     *
     * @type {Boolean}
     *
     * @private
     */
    this.clippingPlanesDirty = false;

    /**
     * Tracks if the tile's request should be deferred until all non-deferred
     * tiles load.
     *
     * @type {Boolean}
     *
     * @private
     */
    this.priorityDeferred = false;

    /**
     * For implicit tiling, an ImplicitTileset object will be attached to a
     * placeholder tile with either implicit tiling in the JSON (3D Tiles 1.1)
     * or the <code>3DTILES_implicit_tiling</code> extension.
     * This way the {@link Implicit3DTileContent} can access the tile later once the content is fetched.
     *
     * @type {ImplicitTileset|undefined}
     *
     * @private
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     */
    this.implicitTileset = undefined;

    /**
     * For implicit tiling, the (level, x, y, [z]) coordinates within the
     * implicit tileset are stored in the tile.
     *
     * @type {ImplicitTileCoordinates|undefined}
     *
     * @private
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     */
    this.implicitCoordinates = undefined;

    /**
     * For implicit tiling, each transcoded tile will hold a weak reference to
     * the {@link ImplicitSubtree}.
     *
     * @type {ImplicitSubtree|undefined}
     *
     * @private
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     */
    this.implicitSubtree = undefined;

    // Members that are updated every frame for tree traversal and rendering optimizations:
    this._distanceToCamera = 0.0;
    this._centerZDepth = 0.0;
    this._screenSpaceError = 0.0;
    this._screenSpaceErrorProgressiveResolution = 0.0; // The screen space error at a given screen height of tileset.progressiveResolutionHeightFraction * screenHeight
    this._visibilityPlaneMask = 0;
    this._visible = false;
    this._inRequestVolume = false;

    this._finalResolution = true;
    this._depth = 0;
    this._stackLength = 0;
    this._selectionDepth = 0;

    this._updatedVisibilityFrame = 0;
    this._touchedFrame = 0;
    this._visitedFrame = 0;
    this._selectedFrame = 0;
    this._requestedFrame = 0;
    this._ancestorWithContent = undefined;
    this._ancestorWithContentAvailable = undefined;
    this._refines = false;
    this._shouldSelect = false;
    this._isClipped = true;
    this._clippingPlanesState = 0; // encapsulates (_isClipped, clippingPlanes.enabled) and number/function
    this._debugBoundingVolume = undefined;
    this._debugContentBoundingVolume = undefined;
    this._debugViewerRequestVolume = undefined;
    this._debugColor = Color.fromRandom({ alpha: 1.0 });
    this._debugColorizeTiles = false;

    this._priority = 0.0; // The priority used for request sorting
    this._priorityHolder = this; // Reference to the ancestor up the tree that holds the _foveatedFactor and _distanceToCamera for all tiles in the refinement chain.
    this._priorityProgressiveResolution = false;
    this._priorityProgressiveResolutionScreenSpaceErrorLeaf = false;
    this._priorityReverseScreenSpaceError = 0.0;
    this._foveatedFactor = 0.0;
    this._wasMinPriorityChild = false; // Needed for knowing when to continue a refinement chain. Gets reset in updateTile in traversal and gets set in updateAndPushChildren in traversal.

    this._loadTimestamp = new JulianDate();

    this._commandsLength = 0;

    this._color = undefined;
    this._colorDirty = false;

    this._request = undefined;
  }

  // This can be overridden for testing purposes
  Cesium3DTile._deprecationWarning = deprecationWarning;

  Object.defineProperties(Cesium3DTile.prototype, {
    /**
     * The tileset containing this tile.
     *
     * @memberof Cesium3DTile.prototype
     *
     * @type {Cesium3DTileset}
     * @readonly
     */
    tileset: {
      get: function () {
        return this._tileset;
      },
    },

    /**
     * The tile's content.  This represents the actual tile's payload,
     * not the content's metadata in the tileset JSON file.
     *
     * @memberof Cesium3DTile.prototype
     *
     * @type {Cesium3DTileContent}
     * @readonly
     */
    content: {
      get: function () {
        return this._content;
      },
    },

    /**
     * Get the tile's bounding volume.
     *
     * @memberof Cesium3DTile.prototype
     *
     * @type {TileBoundingVolume}
     * @readonly
     * @private
     */
    boundingVolume: {
      get: function () {
        return this._boundingVolume;
      },
    },

    /**
     * Get the bounding volume of the tile's contents.  This defaults to the
     * tile's bounding volume when the content's bounding volume is
     * <code>undefined</code>.
     *
     * @memberof Cesium3DTile.prototype
     *
     * @type {TileBoundingVolume}
     * @readonly
     * @private
     */
    contentBoundingVolume: {
      get: function () {
        return defaultValue(this._contentBoundingVolume, this._boundingVolume);
      },
    },

    /**
     * Get the bounding sphere derived from the tile's bounding volume.
     *
     * @memberof Cesium3DTile.prototype
     *
     * @type {BoundingSphere}
     * @readonly
     */
    boundingSphere: {
      get: function () {
        return this._boundingVolume.boundingSphere;
      },
    },

    /**
     * Returns the <code>extras</code> property in the tileset JSON for this tile, which contains application specific metadata.
     * Returns <code>undefined</code> if <code>extras</code> does not exist.
     *
     * @memberof Cesium3DTile.prototype
     *
     * @type {*}
     * @readonly
     * @see {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification#specifying-extensions-and-application-specific-extras|Extras in the 3D Tiles specification.}
     */
    extras: {
      get: function () {
        return this._header.extras;
      },
    },

    /**
     * Gets or sets the tile's highlight color.
     *
     * @memberof Cesium3DTile.prototype
     *
     * @type {Color}
     *
     * @default {@link Color.WHITE}
     *
     * @private
     */
    color: {
      get: function () {
        if (!defined(this._color)) {
          this._color = new Color();
        }
        return Color.clone(this._color);
      },
      set: function (value) {
        this._color = Color.clone(value, this._color);
        this._colorDirty = true;
      },
    },

    /**
     * Determines if the tile has available content to render.  <code>true</code> if the tile's
     * content is ready or if it has expired content that renders while new content loads; otherwise,
     * <code>false</code>.
     *
     * @memberof Cesium3DTile.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @private
     */
    contentAvailable: {
      get: function () {
        return (
          (this.contentReady &&
            !this.hasEmptyContent &&
            !this.hasTilesetContent &&
            !this.hasImplicitContent) ||
          (defined(this._expiredContent) && !this.contentFailed)
        );
      },
    },

    /**
     * Determines if the tile's content is ready. This is automatically <code>true</code> for
     * tile's with empty content.
     *
     * @memberof Cesium3DTile.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @private
     */
    contentReady: {
      get: function () {
        return this._contentState === Cesium3DTileContentState$1.READY;
      },
    },

    /**
     * Determines if the tile's content has not be requested. <code>true</code> if tile's
     * content has not be requested; otherwise, <code>false</code>.
     *
     * @memberof Cesium3DTile.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @private
     */
    contentUnloaded: {
      get: function () {
        return this._contentState === Cesium3DTileContentState$1.UNLOADED;
      },
    },

    /**
     * Determines if the tile's content is expired. <code>true</code> if tile's
     * content is expired; otherwise, <code>false</code>.
     *
     * @memberof Cesium3DTile.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @private
     */
    contentExpired: {
      get: function () {
        return this._contentState === Cesium3DTileContentState$1.EXPIRED;
      },
    },

    /**
     * Determines if the tile's content failed to load.  <code>true</code> if the tile's
     * content failed to load; otherwise, <code>false</code>.
     *
     * @memberof Cesium3DTile.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @private
     */
    contentFailed: {
      get: function () {
        return this._contentState === Cesium3DTileContentState$1.FAILED;
      },
    },

    /**
     * Gets the promise that will be resolved when the tile's content is ready to process.
     * This happens after the content is downloaded but before the content is ready
     * to render.
     * <p>
     * The promise remains <code>undefined</code> until the tile's content is requested.
     * </p>
     *
     * @type {Promise.<Cesium3DTileContent>}
     * @readonly
     *
     * @private
     */
    contentReadyToProcessPromise: {
      get: function () {
        return this._contentReadyToProcessPromise;
      },
    },

    /**
     * Gets the promise that will be resolved when the tile's content is ready to render.
     * <p>
     * The promise remains <code>undefined</code> until the tile's content is requested.
     * </p>
     *
     * @type {Promise.<Cesium3DTileContent>}
     * @readonly
     *
     * @private
     */
    contentReadyPromise: {
      get: function () {
        return this._contentReadyPromise;
      },
    },

    /**
     * Returns the number of draw commands used by this tile.
     *
     * @readonly
     *
     * @private
     */
    commandsLength: {
      get: function () {
        return this._commandsLength;
      },
    },
  });

  const scratchCartesian$5 = new Cartesian3();
  function isPriorityDeferred(tile, frameState) {
    const tileset = tile._tileset;

    // If closest point on line is inside the sphere then set foveatedFactor to 0. Otherwise, the dot product is with the line from camera to the point on the sphere that is closest to the line.
    const camera = frameState.camera;
    const boundingSphere = tile.boundingSphere;
    const radius = boundingSphere.radius;
    const scaledCameraDirection = Cartesian3.multiplyByScalar(
      camera.directionWC,
      tile._centerZDepth,
      scratchCartesian$5
    );
    const closestPointOnLine = Cartesian3.add(
      camera.positionWC,
      scaledCameraDirection,
      scratchCartesian$5
    );
    // The distance from the camera's view direction to the tile.
    const toLine = Cartesian3.subtract(
      closestPointOnLine,
      boundingSphere.center,
      scratchCartesian$5
    );
    const distanceToCenterLine = Cartesian3.magnitude(toLine);
    const notTouchingSphere = distanceToCenterLine > radius;

    // If camera's direction vector is inside the bounding sphere then consider
    // this tile right along the line of sight and set _foveatedFactor to 0.
    // Otherwise,_foveatedFactor is one minus the dot product of the camera's direction
    // and the vector between the camera and the point on the bounding sphere closest to the view line.
    if (notTouchingSphere) {
      const toLineNormalized = Cartesian3.normalize(toLine, scratchCartesian$5);
      const scaledToLine = Cartesian3.multiplyByScalar(
        toLineNormalized,
        radius,
        scratchCartesian$5
      );
      const closestOnSphere = Cartesian3.add(
        boundingSphere.center,
        scaledToLine,
        scratchCartesian$5
      );
      const toClosestOnSphere = Cartesian3.subtract(
        closestOnSphere,
        camera.positionWC,
        scratchCartesian$5
      );
      const toClosestOnSphereNormalize = Cartesian3.normalize(
        toClosestOnSphere,
        scratchCartesian$5
      );
      tile._foveatedFactor =
        1.0 -
        Math.abs(Cartesian3.dot(camera.directionWC, toClosestOnSphereNormalize));
    } else {
      tile._foveatedFactor = 0.0;
    }

    // Skip this feature if: non-skipLevelOfDetail and replace refine, if the foveated settings are turned off, if tile is progressive resolution and replace refine and skipLevelOfDetail (will help get rid of ancestor artifacts faster)
    // Or if the tile is a preload of any kind
    const replace = tile.refine === Cesium3DTileRefine$1.REPLACE;
    const skipLevelOfDetail = tileset._skipLevelOfDetail;
    if (
      (replace && !skipLevelOfDetail) ||
      !tileset.foveatedScreenSpaceError ||
      tileset.foveatedConeSize === 1.0 ||
      (tile._priorityProgressiveResolution && replace && skipLevelOfDetail) ||
      tileset._pass === Cesium3DTilePass$1.PRELOAD_FLIGHT ||
      tileset._pass === Cesium3DTilePass$1.PRELOAD
    ) {
      return false;
    }

    const maximumFovatedFactor = 1.0 - Math.cos(camera.frustum.fov * 0.5); // 0.14 for fov = 60. NOTE very hard to defer vertically foveated tiles since max is based on fovy (which is fov). Lowering the 0.5 to a smaller fraction of the screen height will start to defer vertically foveated tiles.
    const foveatedConeFactor = tileset.foveatedConeSize * maximumFovatedFactor;

    // If it's inside the user-defined view cone, then it should not be deferred.
    if (tile._foveatedFactor <= foveatedConeFactor) {
      return false;
    }

    // Relax SSE based on how big the angle is between the tile and the edge of the foveated cone.
    const range = maximumFovatedFactor - foveatedConeFactor;
    const normalizedFoveatedFactor = CesiumMath.clamp(
      (tile._foveatedFactor - foveatedConeFactor) / range,
      0.0,
      1.0
    );
    const sseRelaxation = tileset.foveatedInterpolationCallback(
      tileset.foveatedMinimumScreenSpaceErrorRelaxation,
      tileset.maximumScreenSpaceError,
      normalizedFoveatedFactor
    );
    const sse =
      tile._screenSpaceError === 0.0 && defined(tile.parent)
        ? tile.parent._screenSpaceError * 0.5
        : tile._screenSpaceError;

    return tileset.maximumScreenSpaceError - sseRelaxation <= sse;
  }

  const scratchJulianDate$1 = new JulianDate();

  /**
   * Get the tile's screen space error.
   *
   * @private
   */
  Cesium3DTile.prototype.getScreenSpaceError = function (
    frameState,
    useParentGeometricError,
    progressiveResolutionHeightFraction
  ) {
    const tileset = this._tileset;
    const heightFraction = defaultValue(progressiveResolutionHeightFraction, 1.0);
    const parentGeometricError = defined(this.parent)
      ? this.parent.geometricError
      : tileset._geometricError;
    const geometricError = useParentGeometricError
      ? parentGeometricError
      : this.geometricError;
    if (geometricError === 0.0) {
      // Leaf tiles do not have any error so save the computation
      return 0.0;
    }
    const camera = frameState.camera;
    let frustum = camera.frustum;
    const context = frameState.context;
    const width = context.drawingBufferWidth;
    const height = context.drawingBufferHeight * heightFraction;
    let error;
    if (
      frameState.mode === SceneMode$1.SCENE2D ||
      frustum instanceof OrthographicFrustum
    ) {
      if (defined(frustum._offCenterFrustum)) {
        frustum = frustum._offCenterFrustum;
      }
      const pixelSize =
        Math.max(frustum.top - frustum.bottom, frustum.right - frustum.left) /
        Math.max(width, height);
      error = geometricError / pixelSize;
    } else {
      // Avoid divide by zero when viewer is inside the tile
      const distance = Math.max(this._distanceToCamera, CesiumMath.EPSILON7);
      const sseDenominator = camera.frustum.sseDenominator;
      error = (geometricError * height) / (distance * sseDenominator);
      if (tileset.dynamicScreenSpaceError) {
        const density = tileset._dynamicScreenSpaceErrorComputedDensity;
        const factor = tileset.dynamicScreenSpaceErrorFactor;
        const dynamicError = CesiumMath.fog(distance, density) * factor;
        error -= dynamicError;
      }
    }

    error /= frameState.pixelRatio;

    return error;
  };

  function isPriorityProgressiveResolution(tileset, tile) {
    if (
      tileset.progressiveResolutionHeightFraction <= 0.0 ||
      tileset.progressiveResolutionHeightFraction > 0.5
    ) {
      return false;
    }

    let isProgressiveResolutionTile =
      tile._screenSpaceErrorProgressiveResolution >
      tileset._maximumScreenSpaceError; // Mark non-SSE leaves
    tile._priorityProgressiveResolutionScreenSpaceErrorLeaf = false; // Needed for skipLOD
    const parent = tile.parent;
    const maximumScreenSpaceError = tileset._maximumScreenSpaceError;
    const tilePasses =
      tile._screenSpaceErrorProgressiveResolution <= maximumScreenSpaceError;
    const parentFails =
      defined(parent) &&
      parent._screenSpaceErrorProgressiveResolution > maximumScreenSpaceError;
    if (tilePasses && parentFails) {
      // A progressive resolution SSE leaf, promote its priority as well
      tile._priorityProgressiveResolutionScreenSpaceErrorLeaf = true;
      isProgressiveResolutionTile = true;
    }
    return isProgressiveResolutionTile;
  }

  function getPriorityReverseScreenSpaceError(tileset, tile) {
    const parent = tile.parent;
    const useParentScreenSpaceError =
      defined(parent) &&
      (!tileset._skipLevelOfDetail ||
        tile._screenSpaceError === 0.0 ||
        parent.hasTilesetContent ||
        parent.hasImplicitContent);
    const screenSpaceError = useParentScreenSpaceError
      ? parent._screenSpaceError
      : tile._screenSpaceError;
    return tileset.root._screenSpaceError - screenSpaceError;
  }

  /**
   * Update the tile's visibility.
   *
   * @private
   */
  Cesium3DTile.prototype.updateVisibility = function (frameState) {
    const parent = this.parent;
    const tileset = this._tileset;
    const parentTransform = defined(parent)
      ? parent.computedTransform
      : tileset.modelMatrix;
    const parentVisibilityPlaneMask = defined(parent)
      ? parent._visibilityPlaneMask
      : CullingVolume.MASK_INDETERMINATE;
    this.updateTransform(parentTransform);
    this._distanceToCamera = this.distanceToTile(frameState);
    this._centerZDepth = this.distanceToTileCenter(frameState);
    this._screenSpaceError = this.getScreenSpaceError(frameState, false);
    this._screenSpaceErrorProgressiveResolution = this.getScreenSpaceError(
      frameState,
      false,
      tileset.progressiveResolutionHeightFraction
    );
    this._visibilityPlaneMask = this.visibility(
      frameState,
      parentVisibilityPlaneMask
    ); // Use parent's plane mask to speed up visibility test
    this._visible = this._visibilityPlaneMask !== CullingVolume.MASK_OUTSIDE;
    this._inRequestVolume = this.insideViewerRequestVolume(frameState);
    this._priorityReverseScreenSpaceError = getPriorityReverseScreenSpaceError(
      tileset,
      this
    );
    this._priorityProgressiveResolution = isPriorityProgressiveResolution(
      tileset,
      this
    );
    this.priorityDeferred = isPriorityDeferred(this, frameState);
  };

  /**
   * Update whether the tile has expired.
   *
   * @private
   */
  Cesium3DTile.prototype.updateExpiration = function () {
    if (
      defined(this.expireDate) &&
      this.contentReady &&
      !this.hasEmptyContent &&
      !this.hasMultipleContents
    ) {
      const now = JulianDate.now(scratchJulianDate$1);
      if (JulianDate.lessThan(this.expireDate, now)) {
        this._contentState = Cesium3DTileContentState$1.EXPIRED;
        this._expiredContent = this._content;
      }
    }
  };

  function updateExpireDate(tile) {
    if (defined(tile.expireDuration)) {
      const expireDurationDate = JulianDate.now(scratchJulianDate$1);
      JulianDate.addSeconds(
        expireDurationDate,
        tile.expireDuration,
        expireDurationDate
      );

      if (defined(tile.expireDate)) {
        if (JulianDate.lessThan(tile.expireDate, expireDurationDate)) {
          JulianDate.clone(expireDurationDate, tile.expireDate);
        }
      } else {
        tile.expireDate = JulianDate.clone(expireDurationDate);
      }
    }
  }

  function createPriorityFunction(tile) {
    return function () {
      return tile._priority;
    };
  }

  /**
   * Requests the tile's content.
   * <p>
   * The request may not be made if the Cesium Request Scheduler can't prioritize it.
   * </p>
   *
   * @return {Number} The number of requests that were attempted but not scheduled.
   * @private
   */
  Cesium3DTile.prototype.requestContent = function () {
    // empty contents don't require any HTTP requests
    if (this.hasEmptyContent) {
      return 0;
    }

    if (this.hasMultipleContents) {
      return requestMultipleContents(this);
    }

    return requestSingleContent(this);
  };

  /**
   * Multiple {@link Cesium3DTileContent}s are allowed within a single tile either through
   * the tile JSON (3D Tiles 1.1) or the <code>3DTILES_multiple_contents</code> extension.
   * Due to differences in request scheduling, this is handled separately.
   * <p>
   * This implementation of multiple contents does not
   * support tile expiry like requestSingleContent does. If this changes,
   * note that the resource.setQueryParameters() details must go inside {@link Multiple3DTileContent} since that is per-request.
   * </p>
   *
   * @private
   */
  function requestMultipleContents(tile) {
    let multipleContents = tile._content;
    const tileset = tile._tileset;

    if (!defined(multipleContents)) {
      // Create the content object immediately, it will handle scheduling
      // requests for inner contents.
      const contentsJson = hasExtension(tile._header, "3DTILES_multiple_contents")
        ? tile._header.extensions["3DTILES_multiple_contents"]
        : tile._header;

      multipleContents = new Multiple3DTileContent(
        tileset,
        tile,
        tile._contentResource.clone(),
        contentsJson
      );
      tile._content = multipleContents;
    }

    const backloggedRequestCount = multipleContents.requestInnerContents();
    if (backloggedRequestCount > 0) {
      return backloggedRequestCount;
    }

    tile._contentState = Cesium3DTileContentState$1.LOADING;
    const contentReadyToProcessPromise = multipleContents.contentsFetchedPromise.then(
      function () {
        if (tile._contentState !== Cesium3DTileContentState$1.LOADING) {
          // tile was canceled, short circuit.
          return;
        }

        if (tile.isDestroyed()) {
          multipleContentFailed(
            tile,
            tileset);
          return;
        }

        tile._contentState = Cesium3DTileContentState$1.PROCESSING;
        return multipleContents;
      }
    );
    tile._contentReadyToProcessPromise = contentReadyToProcessPromise;
    tile._contentReadyPromise = contentReadyToProcessPromise
      .then(function (content) {
        if (!defined(content)) {
          // request was canceled, short circuit.
          return;
        }

        return multipleContents.readyPromise;
      })
      .then(function (content) {
        if (!defined(content)) {
          // tile was canceled, short circuit.
          return;
        }

        if (tile.isDestroyed()) {
          multipleContentFailed(
            tile,
            tileset);
          return;
        }

        // Refresh style for expired content
        tile._selectedFrame = 0;
        tile.lastStyleTime = 0.0;

        JulianDate.now(tile._loadTimestamp);
        tile._contentState = Cesium3DTileContentState$1.READY;
        return content;
      })
      .catch(function (error) {
        multipleContentFailed(tile, tileset);
      });

    return 0;
  }

  function multipleContentFailed(tile, tileset, error) {
    // note: The Multiple3DTileContent handles decrementing the number of pending
    // requests if the state is LOADING.
    if (tile._contentState === Cesium3DTileContentState$1.PROCESSING) {
      --tileset.statistics.numberOfTilesProcessing;
    }

    tile._contentState = Cesium3DTileContentState$1.FAILED;
  }

  function requestSingleContent(tile) {
    // it is important to clone here. The fetchArrayBuffer() below uses
    // throttling, but other uses of the resources do not.
    const resource = tile._contentResource.clone();
    const expired = tile.contentExpired;
    if (expired) {
      // Append a query parameter of the tile expiration date to prevent caching
      resource.setQueryParameters({
        expired: tile.expireDate.toString(),
      });
    }

    const request = new Request({
      throttle: true,
      throttleByServer: true,
      type: RequestType$1.TILES3D,
      priorityFunction: createPriorityFunction(tile),
      serverKey: tile._serverKey,
    });

    tile._request = request;
    resource.request = request;

    const promise = resource.fetchArrayBuffer();
    if (!defined(promise)) {
      return 1;
    }

    const previousState = tile._contentState;
    const tileset = tile._tileset;
    tile._contentState = Cesium3DTileContentState$1.LOADING;
    ++tileset.statistics.numberOfPendingRequests;
    const contentReadyToProcessPromise = promise.then(function (arrayBuffer) {
      if (tile.isDestroyed()) {
        // Tile is unloaded before the content finishes loading
        singleContentFailed(tile, tileset);
        return;
      }

      const content = makeContent(tile, arrayBuffer);

      if (expired) {
        tile.expireDate = undefined;
      }

      tile._content = content;
      tile._contentState = Cesium3DTileContentState$1.PROCESSING;
      return content;
    });
    tile._contentReadyToProcessPromise = contentReadyToProcessPromise;
    tile._contentReadyPromise = contentReadyToProcessPromise
      .then(function (content) {
        if (!defined(content)) {
          return;
        }

        --tileset.statistics.numberOfPendingRequests;
        return content.readyPromise;
      })
      .then(function (content) {
        if (!defined(content)) {
          return;
        }

        if (tile.isDestroyed()) {
          // Tile is unloaded before the content finishes processing
          singleContentFailed(tile, tileset);
          return;
        }
        updateExpireDate(tile);

        // Refresh style for expired content
        tile._selectedFrame = 0;
        tile.lastStyleTime = 0.0;

        JulianDate.now(tile._loadTimestamp);
        tile._contentState = Cesium3DTileContentState$1.READY;
        return content;
      })
      .catch(function (error) {
        if (request.state === RequestState$1.CANCELLED) {
          // Cancelled due to low priority - try again later.
          tile._contentState = previousState;
          --tileset.statistics.numberOfPendingRequests;
          ++tileset.statistics.numberOfAttemptedRequests;
          return Promise.reject("Cancelled");
        }
        singleContentFailed(tile, tileset);
        return Promise.reject(error);
      });

    return 0;
  }

  function singleContentFailed(tile, tileset) {
    if (tile._contentState === Cesium3DTileContentState$1.PROCESSING) {
      --tileset.statistics.numberOfTilesProcessing;
    } else {
      --tileset.statistics.numberOfPendingRequests;
    }
    tile._contentState = Cesium3DTileContentState$1.FAILED;
  }

  /**
   * Given a downloaded content payload, construct a {@link Cesium3DTileContent}.
   * <p>
   * This is only used for single contents.
   * </p>
   *
   * @param {Cesium3DTile} tile The tile
   * @param {ArrayBuffer} arrayBuffer The downloaded payload containing data for the content
   * @return {Cesium3DTileContent} A content object
   * @private
   */
  function makeContent(tile, arrayBuffer) {
    const preprocessed = preprocess3DTileContent(arrayBuffer);

    // Vector and Geometry tile rendering do not support the skip LOD optimization.
    const tileset = tile._tileset;
    tileset._disableSkipLevelOfDetail =
      tileset._disableSkipLevelOfDetail ||
      preprocessed.contentType === Cesium3DTileContentType$1.GEOMETRY ||
      preprocessed.contentType === Cesium3DTileContentType$1.VECTOR;

    if (
      preprocessed.contentType === Cesium3DTileContentType$1.IMPLICIT_SUBTREE ||
      preprocessed.contentType === Cesium3DTileContentType$1.IMPLICIT_SUBTREE_JSON
    ) {
      tile.hasImplicitContent = true;
    }

    if (preprocessed.contentType === Cesium3DTileContentType$1.EXTERNAL_TILESET) {
      tile.hasTilesetContent = true;
    }

    let content;
    const contentFactory = Cesium3DTileContentFactory[preprocessed.contentType];
    if (defined(preprocessed.binaryPayload)) {
      content = contentFactory(
        tileset,
        tile,
        tile._contentResource,
        preprocessed.binaryPayload.buffer,
        0
      );
    } else {
      // JSON formats
      content = contentFactory(
        tileset,
        tile,
        tile._contentResource,
        preprocessed.jsonPayload
      );
    }

    const contentHeader = tile._contentHeader;

    if (tile.hasImplicitContentMetadata) {
      const subtree = tile.implicitSubtree;
      const coordinates = tile.implicitCoordinates;
      content.metadata = subtree.getContentMetadataView(coordinates, 0);
    } else if (!tile.hasImplicitContent) {
      content.metadata = findContentMetadata(tileset, contentHeader);
    }

    const groupMetadata = findGroupMetadata(tileset, contentHeader);
    if (defined(groupMetadata)) {
      content.group = new Cesium3DContentGroup({
        metadata: groupMetadata,
      });
    }

    return content;
  }

  /**
   * Cancel requests for the tile's contents. This is called when the tile
   * goes out of view.
   *
   * @private
   */
  Cesium3DTile.prototype.cancelRequests = function () {
    if (this.hasMultipleContents) {
      this._content.cancelRequests();
    } else {
      this._request.cancel();
    }
  };

  /**
   * Unloads the tile's content.
   *
   * @private
   */
  Cesium3DTile.prototype.unloadContent = function () {
    if (
      this.hasEmptyContent ||
      this.hasTilesetContent ||
      this.hasImplicitContent
    ) {
      return;
    }

    this._content = this._content && this._content.destroy();
    this._contentState = Cesium3DTileContentState$1.UNLOADED;
    this._contentReadyToProcessPromise = undefined;
    this._contentReadyPromise = undefined;

    this.lastStyleTime = 0.0;
    this.clippingPlanesDirty = this._clippingPlanesState === 0;
    this._clippingPlanesState = 0;

    this._debugColorizeTiles = false;

    this._debugBoundingVolume =
      this._debugBoundingVolume && this._debugBoundingVolume.destroy();
    this._debugContentBoundingVolume =
      this._debugContentBoundingVolume &&
      this._debugContentBoundingVolume.destroy();
    this._debugViewerRequestVolume =
      this._debugViewerRequestVolume && this._debugViewerRequestVolume.destroy();
  };

  const scratchProjectedBoundingSphere = new BoundingSphere();

  function getBoundingVolume(tile, frameState) {
    if (
      frameState.mode !== SceneMode$1.SCENE3D &&
      !defined(tile._boundingVolume2D)
    ) {
      const boundingSphere = tile._boundingVolume.boundingSphere;
      const sphere = BoundingSphere.projectTo2D(
        boundingSphere,
        frameState.mapProjection,
        scratchProjectedBoundingSphere
      );
      tile._boundingVolume2D = new TileBoundingSphere(
        sphere.center,
        sphere.radius
      );
    }

    return frameState.mode !== SceneMode$1.SCENE3D
      ? tile._boundingVolume2D
      : tile._boundingVolume;
  }

  function getContentBoundingVolume(tile, frameState) {
    if (
      frameState.mode !== SceneMode$1.SCENE3D &&
      !defined(tile._contentBoundingVolume2D)
    ) {
      const boundingSphere = tile._contentBoundingVolume.boundingSphere;
      const sphere = BoundingSphere.projectTo2D(
        boundingSphere,
        frameState.mapProjection,
        scratchProjectedBoundingSphere
      );
      tile._contentBoundingVolume2D = new TileBoundingSphere(
        sphere.center,
        sphere.radius
      );
    }
    return frameState.mode !== SceneMode$1.SCENE3D
      ? tile._contentBoundingVolume2D
      : tile._contentBoundingVolume;
  }

  /**
   * Determines whether the tile's bounding volume intersects the culling volume.
   *
   * @param {FrameState} frameState The frame state.
   * @param {Number} parentVisibilityPlaneMask The parent's plane mask to speed up the visibility check.
   * @returns {Number} A plane mask as described above in {@link CullingVolume#computeVisibilityWithPlaneMask}.
   *
   * @private
   */
  Cesium3DTile.prototype.visibility = function (
    frameState,
    parentVisibilityPlaneMask
  ) {
    const cullingVolume = frameState.cullingVolume;
    const boundingVolume = getBoundingVolume(this, frameState);

    const tileset = this._tileset;
    const clippingPlanes = tileset.clippingPlanes;
    if (defined(clippingPlanes) && clippingPlanes.enabled) {
      const intersection = clippingPlanes.computeIntersectionWithBoundingVolume(
        boundingVolume,
        tileset.clippingPlanesOriginMatrix
      );
      this._isClipped = intersection !== Intersect$1.INSIDE;
      if (intersection === Intersect$1.OUTSIDE) {
        return CullingVolume.MASK_OUTSIDE;
      }
    }

    return cullingVolume.computeVisibilityWithPlaneMask(
      boundingVolume,
      parentVisibilityPlaneMask
    );
  };

  /**
   * Assuming the tile's bounding volume intersects the culling volume, determines
   * whether the tile's content's bounding volume intersects the culling volume.
   *
   * @param {FrameState} frameState The frame state.
   * @returns {Intersect} The result of the intersection: the tile's content is completely outside, completely inside, or intersecting the culling volume.
   *
   * @private
   */
  Cesium3DTile.prototype.contentVisibility = function (frameState) {
    // Assumes the tile's bounding volume intersects the culling volume already, so
    // just return Intersect.INSIDE if there is no content bounding volume.
    if (!defined(this._contentBoundingVolume)) {
      return Intersect$1.INSIDE;
    }

    if (this._visibilityPlaneMask === CullingVolume.MASK_INSIDE) {
      // The tile's bounding volume is completely inside the culling volume so
      // the content bounding volume must also be inside.
      return Intersect$1.INSIDE;
    }

    // PERFORMANCE_IDEA: is it possible to burn less CPU on this test since we know the
    // tile's (not the content's) bounding volume intersects the culling volume?
    const cullingVolume = frameState.cullingVolume;
    const boundingVolume = getContentBoundingVolume(this, frameState);

    const tileset = this._tileset;
    const clippingPlanes = tileset.clippingPlanes;
    if (defined(clippingPlanes) && clippingPlanes.enabled) {
      const intersection = clippingPlanes.computeIntersectionWithBoundingVolume(
        boundingVolume,
        tileset.clippingPlanesOriginMatrix
      );
      this._isClipped = intersection !== Intersect$1.INSIDE;
      if (intersection === Intersect$1.OUTSIDE) {
        return Intersect$1.OUTSIDE;
      }
    }

    return cullingVolume.computeVisibility(boundingVolume);
  };

  /**
   * Computes the (potentially approximate) distance from the closest point of the tile's bounding volume to the camera.
   *
   * @param {FrameState} frameState The frame state.
   * @returns {Number} The distance, in meters, or zero if the camera is inside the bounding volume.
   *
   * @private
   */
  Cesium3DTile.prototype.distanceToTile = function (frameState) {
    const boundingVolume = getBoundingVolume(this, frameState);
    return boundingVolume.distanceToCamera(frameState);
  };

  const scratchToTileCenter = new Cartesian3();

  /**
   * Computes the distance from the center of the tile's bounding volume to the camera's plane defined by its position and view direction.
   *
   * @param {FrameState} frameState The frame state.
   * @returns {Number} The distance, in meters.
   *
   * @private
   */
  Cesium3DTile.prototype.distanceToTileCenter = function (frameState) {
    const tileBoundingVolume = getBoundingVolume(this, frameState);
    const boundingVolume = tileBoundingVolume.boundingVolume; // Gets the underlying OrientedBoundingBox or BoundingSphere
    const toCenter = Cartesian3.subtract(
      boundingVolume.center,
      frameState.camera.positionWC,
      scratchToTileCenter
    );
    return Cartesian3.dot(frameState.camera.directionWC, toCenter);
  };

  /**
   * Checks if the camera is inside the viewer request volume.
   *
   * @param {FrameState} frameState The frame state.
   * @returns {Boolean} Whether the camera is inside the volume.
   *
   * @private
   */
  Cesium3DTile.prototype.insideViewerRequestVolume = function (frameState) {
    const viewerRequestVolume = this._viewerRequestVolume;
    return (
      !defined(viewerRequestVolume) ||
      viewerRequestVolume.distanceToCamera(frameState) === 0.0
    );
  };

  const scratchMatrix$2 = new Matrix3();
  const scratchScale$2 = new Cartesian3();
  const scratchHalfAxes = new Matrix3();
  const scratchCenter$4 = new Cartesian3();
  const scratchRectangle$5 = new Rectangle();
  const scratchOrientedBoundingBox = new OrientedBoundingBox();
  const scratchTransform = new Matrix4();

  function createBox(box, transform, result) {
    let center = Cartesian3.fromElements(box[0], box[1], box[2], scratchCenter$4);
    let halfAxes = Matrix3.fromArray(box, 3, scratchHalfAxes);

    // Find the transformed center and halfAxes
    center = Matrix4.multiplyByPoint(transform, center, center);
    const rotationScale = Matrix4.getMatrix3(transform, scratchMatrix$2);
    halfAxes = Matrix3.multiply(rotationScale, halfAxes, halfAxes);

    if (defined(result)) {
      result.update(center, halfAxes);
      return result;
    }
    return new TileOrientedBoundingBox(center, halfAxes);
  }

  function createBoxFromTransformedRegion(
    region,
    transform,
    initialTransform,
    result
  ) {
    const rectangle = Rectangle.unpack(region, 0, scratchRectangle$5);
    const minimumHeight = region[4];
    const maximumHeight = region[5];

    const orientedBoundingBox = OrientedBoundingBox.fromRectangle(
      rectangle,
      minimumHeight,
      maximumHeight,
      Ellipsoid.WGS84,
      scratchOrientedBoundingBox
    );
    let center = orientedBoundingBox.center;
    let halfAxes = orientedBoundingBox.halfAxes;

    // A region bounding volume is not transformed by the transform in the tileset JSON,
    // but may be transformed by additional transforms applied in Cesium.
    // This is why the transform is calculated as the difference between the initial transform and the current transform.
    transform = Matrix4.multiplyTransformation(
      transform,
      Matrix4.inverseTransformation(initialTransform, scratchTransform),
      scratchTransform
    );
    center = Matrix4.multiplyByPoint(transform, center, center);
    const rotationScale = Matrix4.getMatrix3(transform, scratchMatrix$2);
    halfAxes = Matrix3.multiply(rotationScale, halfAxes, halfAxes);

    if (defined(result) && result instanceof TileOrientedBoundingBox) {
      result.update(center, halfAxes);
      return result;
    }

    return new TileOrientedBoundingBox(center, halfAxes);
  }

  function createRegion(region, transform, initialTransform, result) {
    if (
      !Matrix4.equalsEpsilon(transform, initialTransform, CesiumMath.EPSILON8)
    ) {
      return createBoxFromTransformedRegion(
        region,
        transform,
        initialTransform,
        result
      );
    }

    if (defined(result)) {
      return result;
    }

    const rectangleRegion = Rectangle.unpack(region, 0, scratchRectangle$5);

    return new TileBoundingRegion({
      rectangle: rectangleRegion,
      minimumHeight: region[4],
      maximumHeight: region[5],
    });
  }

  function createSphere(sphere, transform, result) {
    let center = Cartesian3.fromElements(
      sphere[0],
      sphere[1],
      sphere[2],
      scratchCenter$4
    );
    let radius = sphere[3];

    // Find the transformed center and radius
    center = Matrix4.multiplyByPoint(transform, center, center);
    const scale = Matrix4.getScale(transform, scratchScale$2);
    const uniformScale = Cartesian3.maximumComponent(scale);
    radius *= uniformScale;

    if (defined(result)) {
      result.update(center, radius);
      return result;
    }
    return new TileBoundingSphere(center, radius);
  }

  /**
   * Create a bounding volume from the tile's bounding volume header.
   *
   * @param {Object} boundingVolumeHeader The tile's bounding volume header.
   * @param {Matrix4} transform The transform to apply to the bounding volume.
   * @param {TileBoundingVolume} [result] The object onto which to store the result.
   *
   * @returns {TileBoundingVolume} The modified result parameter or a new TileBoundingVolume instance if none was provided.
   *
   * @private
   */
  Cesium3DTile.prototype.createBoundingVolume = function (
    boundingVolumeHeader,
    transform,
    result
  ) {
    if (!defined(boundingVolumeHeader)) {
      throw new RuntimeError("boundingVolume must be defined");
    }

    if (hasExtension(boundingVolumeHeader, "3DTILES_bounding_volume_S2")) {
      return new TileBoundingS2Cell(
        boundingVolumeHeader.extensions["3DTILES_bounding_volume_S2"]
      );
    }

    if (defined(boundingVolumeHeader.box)) {
      return createBox(boundingVolumeHeader.box, transform, result);
    }
    if (defined(boundingVolumeHeader.region)) {
      return createRegion(
        boundingVolumeHeader.region,
        transform,
        this._initialTransform,
        result
      );
    }
    if (defined(boundingVolumeHeader.sphere)) {
      return createSphere(boundingVolumeHeader.sphere, transform, result);
    }
    throw new RuntimeError(
      "boundingVolume must contain a sphere, region, or box"
    );
  };

  /**
   * Update the tile's transform. The transform is applied to the tile's bounding volumes.
   *
   * @private
   */
  Cesium3DTile.prototype.updateTransform = function (parentTransform) {
    parentTransform = defaultValue(parentTransform, Matrix4.IDENTITY);
    const computedTransform = Matrix4.multiply(
      parentTransform,
      this.transform,
      scratchTransform
    );
    const transformChanged = !Matrix4.equals(
      computedTransform,
      this.computedTransform
    );

    if (!transformChanged) {
      return;
    }

    Matrix4.clone(computedTransform, this.computedTransform);

    // Update the bounding volumes
    const header = this._header;
    const contentHeader = this._contentHeader;
    this._boundingVolume = this.createBoundingVolume(
      header.boundingVolume,
      this.computedTransform,
      this._boundingVolume
    );
    if (defined(this._contentBoundingVolume)) {
      this._contentBoundingVolume = this.createBoundingVolume(
        contentHeader.boundingVolume,
        this.computedTransform,
        this._contentBoundingVolume
      );
    }
    if (defined(this._viewerRequestVolume)) {
      this._viewerRequestVolume = this.createBoundingVolume(
        header.viewerRequestVolume,
        this.computedTransform,
        this._viewerRequestVolume
      );
    }

    this.updateGeometricErrorScale();

    // Destroy the debug bounding volumes. They will be generated fresh.
    this._debugBoundingVolume =
      this._debugBoundingVolume && this._debugBoundingVolume.destroy();
    this._debugContentBoundingVolume =
      this._debugContentBoundingVolume &&
      this._debugContentBoundingVolume.destroy();
    this._debugViewerRequestVolume =
      this._debugViewerRequestVolume && this._debugViewerRequestVolume.destroy();
  };

  Cesium3DTile.prototype.updateGeometricErrorScale = function () {
    const scale = Matrix4.getScale(this.computedTransform, scratchScale$2);
    const uniformScale = Cartesian3.maximumComponent(scale);
    this.geometricError = this._geometricError * uniformScale;
  };

  function applyDebugSettings$1(tile, tileset, frameState, passOptions) {
    if (!passOptions.isRender) {
      return;
    }

    const hasContentBoundingVolume =
      defined(tile._contentHeader) && defined(tile._contentHeader.boundingVolume);
    const empty =
      tile.hasEmptyContent || tile.hasTilesetContent || tile.hasImplicitContent;

    const showVolume =
      tileset.debugShowBoundingVolume ||
      (tileset.debugShowContentBoundingVolume && !hasContentBoundingVolume);
    if (showVolume) {
      let color;
      if (!tile._finalResolution) {
        color = Color.YELLOW;
      } else if (empty) {
        color = Color.DARKGRAY;
      } else {
        color = Color.WHITE;
      }
      if (!defined(tile._debugBoundingVolume)) {
        tile._debugBoundingVolume = tile._boundingVolume.createDebugVolume(color);
      }
      tile._debugBoundingVolume.update(frameState);
      const attributes = tile._debugBoundingVolume.getGeometryInstanceAttributes(
        "outline"
      );
      attributes.color = ColorGeometryInstanceAttribute.toValue(
        color,
        attributes.color
      );
    } else if (!showVolume && defined(tile._debugBoundingVolume)) {
      tile._debugBoundingVolume = tile._debugBoundingVolume.destroy();
    }

    if (tileset.debugShowContentBoundingVolume && hasContentBoundingVolume) {
      if (!defined(tile._debugContentBoundingVolume)) {
        tile._debugContentBoundingVolume = tile._contentBoundingVolume.createDebugVolume(
          Color.BLUE
        );
      }
      tile._debugContentBoundingVolume.update(frameState);
    } else if (
      !tileset.debugShowContentBoundingVolume &&
      defined(tile._debugContentBoundingVolume)
    ) {
      tile._debugContentBoundingVolume = tile._debugContentBoundingVolume.destroy();
    }

    if (
      tileset.debugShowViewerRequestVolume &&
      defined(tile._viewerRequestVolume)
    ) {
      if (!defined(tile._debugViewerRequestVolume)) {
        tile._debugViewerRequestVolume = tile._viewerRequestVolume.createDebugVolume(
          Color.YELLOW
        );
      }
      tile._debugViewerRequestVolume.update(frameState);
    } else if (
      !tileset.debugShowViewerRequestVolume &&
      defined(tile._debugViewerRequestVolume)
    ) {
      tile._debugViewerRequestVolume = tile._debugViewerRequestVolume.destroy();
    }

    const debugColorizeTilesOn =
      (tileset.debugColorizeTiles && !tile._debugColorizeTiles) ||
      defined(tileset._heatmap.tilePropertyName);
    const debugColorizeTilesOff =
      !tileset.debugColorizeTiles && tile._debugColorizeTiles;

    if (debugColorizeTilesOn) {
      tileset._heatmap.colorize(tile, frameState); // Skipped if tileset._heatmap.tilePropertyName is undefined
      tile._debugColorizeTiles = true;
      tile.color = tile._debugColor;
    } else if (debugColorizeTilesOff) {
      tile._debugColorizeTiles = false;
      tile.color = Color.WHITE;
    }

    if (tile._colorDirty) {
      tile._colorDirty = false;
      tile._content.applyDebugSettings(true, tile._color);
    }

    if (debugColorizeTilesOff) {
      tileset.makeStyleDirty(); // Re-apply style now that colorize is switched off
    }
  }

  function updateContent(tile, tileset, frameState) {
    const content = tile._content;
    const expiredContent = tile._expiredContent;

    // expired content is not supported for multiple contents
    if (!tile.hasMultipleContents && defined(expiredContent)) {
      if (!tile.contentReady) {
        // Render the expired content while the content loads
        expiredContent.update(tileset, frameState);
        return;
      }

      // New content is ready, destroy expired content
      tile._expiredContent.destroy();
      tile._expiredContent = undefined;
    }

    content.update(tileset, frameState);
  }

  function updateClippingPlanes(tile, tileset) {
    // Compute and compare ClippingPlanes state:
    // - enabled-ness - are clipping planes enabled? is this tile clipped?
    // - clipping plane count
    // - clipping function (union v. intersection)
    const clippingPlanes = tileset.clippingPlanes;
    let currentClippingPlanesState = 0;
    if (defined(clippingPlanes) && tile._isClipped && clippingPlanes.enabled) {
      currentClippingPlanesState = clippingPlanes.clippingPlanesState;
    }
    // If clippingPlaneState for tile changed, mark clippingPlanesDirty so content can update
    if (currentClippingPlanesState !== tile._clippingPlanesState) {
      tile._clippingPlanesState = currentClippingPlanesState;
      tile.clippingPlanesDirty = true;
    }
  }

  /**
   * Get the draw commands needed to render this tile.
   *
   * @private
   */
  Cesium3DTile.prototype.update = function (tileset, frameState, passOptions) {
    const commandStart = frameState.commandList.length;

    updateClippingPlanes(this, tileset);
    applyDebugSettings$1(this, tileset, frameState, passOptions);
    updateContent(this, tileset, frameState);

    const commandEnd = frameState.commandList.length;
    const commandsLength = commandEnd - commandStart;
    this._commandsLength = commandsLength;

    for (let i = 0; i < commandsLength; ++i) {
      const command = frameState.commandList[commandStart + i];
      const translucent = command.pass === Pass$1.TRANSLUCENT;
      command.depthForTranslucentClassification = translucent;
    }

    this.clippingPlanesDirty = false; // reset after content update
  };

  const scratchCommandList$1 = [];

  /**
   * Processes the tile's content, e.g., create WebGL resources, to move from the PROCESSING to READY state.
   *
   * @param {Cesium3DTileset} tileset The tileset containing this tile.
   * @param {FrameState} frameState The frame state.
   *
   * @private
   */
  Cesium3DTile.prototype.process = function (tileset, frameState) {
    const savedCommandList = frameState.commandList;
    frameState.commandList = scratchCommandList$1;

    this._content.update(tileset, frameState);

    scratchCommandList$1.length = 0;
    frameState.commandList = savedCommandList;
  };

  function isolateDigits(normalizedValue, numberOfDigits, leftShift) {
    const scaled = normalizedValue * Math.pow(10, numberOfDigits);
    const integer = parseInt(scaled);
    return integer * Math.pow(10, leftShift);
  }

  function priorityNormalizeAndClamp(value, minimum, maximum) {
    return Math.max(
      CesiumMath.normalize(value, minimum, maximum) - CesiumMath.EPSILON7,
      0.0
    ); // Subtract epsilon since we only want decimal digits present in the output.
  }

  /**
   * Sets the priority of the tile based on distance and depth
   * @private
   */
  Cesium3DTile.prototype.updatePriority = function () {
    const tileset = this.tileset;
    const preferLeaves = tileset.preferLeaves;
    const minimumPriority = tileset._minimumPriority;
    const maximumPriority = tileset._maximumPriority;

    // Combine priority systems together by mapping them into a base 10 number where each priority controls a specific set of digits in the number.
    // For number priorities, map them to a 0.xxxxx number then left shift it up into a set number of digits before the decimal point. Chop of the fractional part then left shift again into the position it needs to go.
    // For blending number priorities, normalize them to 0-1 and interpolate to get a combined 0-1 number, then proceed as normal.
    // Booleans can just be 0 or 10^leftshift.
    // Think of digits as penalties since smaller numbers are higher priority. If a tile has some large quantity or has a flag raised it's (usually) penalized for it, expressed as a higher number for the digit.
    // Priority number format: preloadFlightDigits(1) | foveatedDeferDigits(1) | foveatedDigits(4) | preloadProgressiveResolutionDigits(1) | preferredSortingDigits(4) . depthDigits(the decimal digits)
    // Certain flags like preferLeaves will flip / turn off certain digits to get desired load order.

    // Setup leftShifts, digit counts, and scales (for booleans)
    const digitsForANumber = 4;
    const digitsForABoolean = 1;

    const preferredSortingLeftShift = 0;
    const preferredSortingDigitsCount = digitsForANumber;

    const foveatedLeftShift =
      preferredSortingLeftShift + preferredSortingDigitsCount;
    const foveatedDigitsCount = digitsForANumber;

    const preloadProgressiveResolutionLeftShift =
      foveatedLeftShift + foveatedDigitsCount;
    const preloadProgressiveResolutionDigitsCount = digitsForABoolean;
    const preloadProgressiveResolutionScale = Math.pow(
      10,
      preloadProgressiveResolutionLeftShift
    );

    const foveatedDeferLeftShift =
      preloadProgressiveResolutionLeftShift +
      preloadProgressiveResolutionDigitsCount;
    const foveatedDeferDigitsCount = digitsForABoolean;
    const foveatedDeferScale = Math.pow(10, foveatedDeferLeftShift);

    const preloadFlightLeftShift =
      foveatedDeferLeftShift + foveatedDeferDigitsCount;
    const preloadFlightScale = Math.pow(10, preloadFlightLeftShift);

    // Compute the digits for each priority
    let depthDigits = priorityNormalizeAndClamp(
      this._depth,
      minimumPriority.depth,
      maximumPriority.depth
    );
    depthDigits = preferLeaves ? 1.0 - depthDigits : depthDigits;

    // Map 0-1 then convert to digit. Include a distance sort when doing non-skipLOD and replacement refinement, helps things like non-skipLOD photogrammetry
    const useDistance =
      !tileset._skipLevelOfDetail && this.refine === Cesium3DTileRefine$1.REPLACE;
    const normalizedPreferredSorting = useDistance
      ? priorityNormalizeAndClamp(
          this._priorityHolder._distanceToCamera,
          minimumPriority.distance,
          maximumPriority.distance
        )
      : priorityNormalizeAndClamp(
          this._priorityReverseScreenSpaceError,
          minimumPriority.reverseScreenSpaceError,
          maximumPriority.reverseScreenSpaceError
        );
    const preferredSortingDigits = isolateDigits(
      normalizedPreferredSorting,
      preferredSortingDigitsCount,
      preferredSortingLeftShift
    );

    const preloadProgressiveResolutionDigits = this._priorityProgressiveResolution
      ? 0
      : preloadProgressiveResolutionScale;

    const normalizedFoveatedFactor = priorityNormalizeAndClamp(
      this._priorityHolder._foveatedFactor,
      minimumPriority.foveatedFactor,
      maximumPriority.foveatedFactor
    );
    const foveatedDigits = isolateDigits(
      normalizedFoveatedFactor,
      foveatedDigitsCount,
      foveatedLeftShift
    );

    const foveatedDeferDigits = this.priorityDeferred ? foveatedDeferScale : 0;

    const preloadFlightDigits =
      tileset._pass === Cesium3DTilePass$1.PRELOAD_FLIGHT ? 0 : preloadFlightScale;

    // Get the final base 10 number
    this._priority =
      depthDigits +
      preferredSortingDigits +
      preloadProgressiveResolutionDigits +
      foveatedDigits +
      foveatedDeferDigits +
      preloadFlightDigits;
  };

  /**
   * @private
   */
  Cesium3DTile.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * @private
   */
  Cesium3DTile.prototype.destroy = function () {
    // For the interval between new content being requested and downloaded, expiredContent === content, so don't destroy twice
    this._content = this._content && this._content.destroy();
    this._expiredContent =
      this._expiredContent &&
      !this._expiredContent.isDestroyed() &&
      this._expiredContent.destroy();
    this._debugBoundingVolume =
      this._debugBoundingVolume && this._debugBoundingVolume.destroy();
    this._debugContentBoundingVolume =
      this._debugContentBoundingVolume &&
      this._debugContentBoundingVolume.destroy();
    this._debugViewerRequestVolume =
      this._debugViewerRequestVolume && this._debugViewerRequestVolume.destroy();
    return destroyObject(this);
  };

  /**
   * Metadata about a group of {@link Cesium3DTileContent}
   * <p>
   * See the {@link https://github.com/CesiumGS/3d-tiles/tree/main/extensions/3DTILES_metadata|3DTILES_metadata Extension} for 3D Tiles
   * </p>
   *
   * @param {Object} options Object with the following properties:
   * @param {String} options.id The ID of the group.
   * @param {Object} options.group The group JSON object.
   * @param {MetadataClass} options.class The class that group metadata conforms to.
   *
   * @alias GroupMetadata
   * @constructor
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function GroupMetadata(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const id = options.id;
    const group = options.group;
    const metadataClass = options.class;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.group", group);
    Check.typeOf.object("options.class", metadataClass);
    //>>includeEnd('debug');

    const properties = defined(group.properties) ? group.properties : {};

    this._class = metadataClass;
    this._properties = properties;
    this._id = id;
    this._extras = group.extras;
    this._extensions = group.extensions;
  }

  Object.defineProperties(GroupMetadata.prototype, {
    /**
     * The class that properties conform to.
     *
     * @memberof GroupMetadata.prototype
     * @type {MetadataClass}
     * @readonly
     * @private
     */
    class: {
      get: function () {
        return this._class;
      },
    },

    /**
     * The ID of the group.
     *
     * @memberof GroupMetadata.prototype
     * @type {String}
     * @readonly
     * @private
     */
    id: {
      get: function () {
        return this._id;
      },
    },

    /**
     * Extras in the JSON object.
     *
     * @memberof GroupMetadata.prototype
     * @type {*}
     * @readonly
     * @private
     */
    extras: {
      get: function () {
        return this._extras;
      },
    },

    /**
     * Extensions in the JSON object.
     *
     * @memberof GroupMetadata.prototype
     * @type {Object}
     * @readonly
     * @private
     */
    extensions: {
      get: function () {
        return this._extensions;
      },
    },
  });

  /**
   * Returns whether the group has this property.
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @returns {Boolean} Whether the group has this property.
   * @private
   */
  GroupMetadata.prototype.hasProperty = function (propertyId) {
    return MetadataEntity.hasProperty(propertyId, this._properties, this._class);
  };

  /**
   * Returns whether the group has a property with the given semantic.
   *
   * @param {String} semantic The case-sensitive semantic of the property.
   * @returns {Boolean} Whether the group has a property with the given semantic.
   * @private
   */
  GroupMetadata.prototype.hasPropertyBySemantic = function (semantic) {
    return MetadataEntity.hasPropertyBySemantic(
      semantic,
      this._properties,
      this._class
    );
  };

  /**
   * Returns an array of property IDs.
   *
   * @param {String[]} [results] An array into which to store the results.
   * @returns {String[]} The property IDs.
   * @private
   */
  GroupMetadata.prototype.getPropertyIds = function (results) {
    return MetadataEntity.getPropertyIds(this._properties, this._class, results);
  };

  /**
   * Returns a copy of the value of the property with the given ID.
   * <p>
   * If the property is normalized the normalized value is returned.
   * </p>
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @returns {*} The value of the property or <code>undefined</code> if the group does not have this property.
   * @private
   */
  GroupMetadata.prototype.getProperty = function (propertyId) {
    return MetadataEntity.getProperty(propertyId, this._properties, this._class);
  };

  /**
   * Sets the value of the property with the given ID.
   * <p>
   * If the property is normalized a normalized value must be provided to this function.
   * </p>
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @param {*} value The value of the property that will be copied.
   * @returns {Boolean} <code>true</code> if the property was set, <code>false</code> otherwise.
   * @private
   */
  GroupMetadata.prototype.setProperty = function (propertyId, value) {
    return MetadataEntity.setProperty(
      propertyId,
      value,
      this._properties,
      this._class
    );
  };

  /**
   * Returns a copy of the value of the property with the given semantic.
   *
   * @param {String} semantic The case-sensitive semantic of the property.
   * @returns {*} The value of the property or <code>undefined</code> if the group does not have this semantic.
   * @private
   */
  GroupMetadata.prototype.getPropertyBySemantic = function (semantic) {
    return MetadataEntity.getPropertyBySemantic(
      semantic,
      this._properties,
      this._class
    );
  };

  /**
   * Sets the value of the property with the given semantic.
   *
   * @param {String} semantic The case-sensitive semantic of the property.
   * @param {*} value The value of the property that will be copied.
   * @returns {Boolean} <code>true</code> if the property was set, <code>false</code> otherwise.
   * @private
   */
  GroupMetadata.prototype.setPropertyBySemantic = function (semantic, value) {
    return MetadataEntity.setPropertyBySemantic(
      semantic,
      value,
      this._properties,
      this._class
    );
  };

  /**
   * Metadata about the tileset.
   * <p>
   * See the {@link https://github.com/CesiumGS/3d-tiles/tree/main/extensions/3DTILES_metadata|3DTILES_metadata Extension} for 3D Tiles
   * </p>
   *
   * @param {Object} options Object with the following properties:
   * @param {Object} options.tileset The tileset metadata JSON object.
   * @param {MetadataClass} options.class The class that tileset metadata conforms to.
   *
   * @alias TilesetMetadata
   * @constructor
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function TilesetMetadata(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const tileset = options.tileset;
    const metadataClass = options.class;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.tileset", tileset);
    Check.typeOf.object("options.class", metadataClass);
    //>>includeEnd('debug');

    const properties = defined(tileset.properties) ? tileset.properties : {};

    this._class = metadataClass;
    this._properties = properties;
    this._extras = tileset.extras;
    this._extensions = tileset.extensions;
  }

  Object.defineProperties(TilesetMetadata.prototype, {
    /**
     * The class that properties conform to.
     *
     * @memberof TilesetMetadata.prototype
     * @type {MetadataClass}
     * @readonly
     * @private
     */
    class: {
      get: function () {
        return this._class;
      },
    },

    /**
     * Extras in the JSON object.
     *
     * @memberof TilesetMetadata.prototype
     * @type {*}
     * @readonly
     * @private
     */
    extras: {
      get: function () {
        return this._extras;
      },
    },

    /**
     * Extensions in the JSON object.
     *
     * @memberof TilesetMetadata.prototype
     * @type {Object}
     * @readonly
     * @private
     */
    extensions: {
      get: function () {
        return this._extensions;
      },
    },
  });

  /**
   * Returns whether the tileset has this property.
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @returns {Boolean} Whether the tileset has this property.
   * @private
   */
  TilesetMetadata.prototype.hasProperty = function (propertyId) {
    return MetadataEntity.hasProperty(propertyId, this._properties, this._class);
  };

  /**
   * Returns whether the tileset has a property with the given semantic.
   *
   * @param {String} semantic The case-sensitive semantic of the property.
   * @returns {Boolean} Whether the tileset has a property with the given semantic.
   * @private
   */
  TilesetMetadata.prototype.hasPropertyBySemantic = function (semantic) {
    return MetadataEntity.hasPropertyBySemantic(
      semantic,
      this._properties,
      this._class
    );
  };

  /**
   * Returns an array of property IDs.
   *
   * @param {String[]} [results] An array into which to store the results.
   * @returns {String[]} The property IDs.
   * @private
   */
  TilesetMetadata.prototype.getPropertyIds = function (results) {
    return MetadataEntity.getPropertyIds(this._properties, this._class, results);
  };

  /**
   * Returns a copy of the value of the property with the given ID.
   * <p>
   * If the property is normalized the normalized value is returned.
   * </p>
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @returns {*} The value of the property or <code>undefined</code> if the tileset does not have this property.
   * @private
   */
  TilesetMetadata.prototype.getProperty = function (propertyId) {
    return MetadataEntity.getProperty(propertyId, this._properties, this._class);
  };

  /**
   * Sets the value of the property with the given ID.
   * <p>
   * If the property is normalized a normalized value must be provided to this function.
   * </p>
   *
   * @param {String} propertyId The case-sensitive ID of the property.
   * @param {*} value The value of the property that will be copied.
   * @returns {Boolean} <code>true</code> if the property was set, <code>false</code> otherwise.
   * @private
   */
  TilesetMetadata.prototype.setProperty = function (propertyId, value) {
    return MetadataEntity.setProperty(
      propertyId,
      value,
      this._properties,
      this._class
    );
  };

  /**
   * Returns a copy of the value of the property with the given semantic.
   *
   * @param {String} semantic The case-sensitive semantic of the property.
   * @returns {*} The value of the property or <code>undefined</code> if the tileset does not have this semantic.
   * @private
   */
  TilesetMetadata.prototype.getPropertyBySemantic = function (semantic) {
    return MetadataEntity.getPropertyBySemantic(
      semantic,
      this._properties,
      this._class
    );
  };

  /**
   * Sets the value of the property with the given semantic.
   *
   * @param {String} semantic The case-sensitive semantic of the property.
   * @param {*} value The value of the property that will be copied.
   * @returns {Boolean} <code>true</code> if the property was set, <code>false</code> otherwise.
   * @private
   */
  TilesetMetadata.prototype.setPropertyBySemantic = function (semantic, value) {
    return MetadataEntity.setPropertyBySemantic(
      semantic,
      value,
      this._properties,
      this._class
    );
  };

  /**
   * An object containing metadata about a 3D Tileset.
   * <p>
   * See the {@link https://github.com/CesiumGS/3d-tiles/tree/main/extensions/3DTILES_metadata|3DTILES_metadata Extension} for 3D Tiles.
   * </p>
   * <p>
   * This object represents the tileset JSON (3D Tiles 1.1) or the <code>3DTILES_metadata</code> object that contains
   * the schema ({@link MetadataSchema}), tileset metadata ({@link TilesetMetadata}), group metadata (dictionary of {@link GroupMetadata}), and metadata statistics (dictionary)
   * </p>
   *
   * @param {Object} options Object with the following properties:
   * @param {Object} options.metadataJson Either the tileset JSON (3D Tiles 1.1) or the <code>3DTILES_metadata</code> extension object that contains the tileset metadata.
   * @param {MetadataSchema} options.schema The parsed schema.
   *
   * @alias Cesium3DTilesetMetadata
   * @constructor
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function Cesium3DTilesetMetadata(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const metadataJson = options.metadataJson;

    // The calling code is responsible for loading the schema.
    // This keeps metadata parsing synchronous.
    const schema = options.schema;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.metadataJson", metadataJson);
    Check.typeOf.object("options.schema", schema);
    //>>includeEnd('debug');

    // An older schema stored the tileset metadata in the "tileset" property.
    const metadata = defaultValue(metadataJson.metadata, metadataJson.tileset);

    let tileset;
    if (defined(metadata)) {
      tileset = new TilesetMetadata({
        tileset: metadata,
        class: schema.classes[metadata.class],
      });
    }

    let groupIds = [];
    const groups = [];
    const groupsJson = metadataJson.groups;
    if (Array.isArray(groupsJson)) {
      const length = groupsJson.length;
      for (let i = 0; i < length; i++) {
        const group = groupsJson[i];
        groups.push(
          new GroupMetadata({
            group: group,
            class: schema.classes[group.class],
          })
        );
      }
    } else if (defined(groupsJson)) {
      // An older version of group metadata stored groups in a dictionary
      // instead of an array.
      groupIds = Object.keys(groupsJson).sort();
      const length = groupIds.length;
      for (let i = 0; i < length; i++) {
        const groupId = groupIds[i];
        if (groupsJson.hasOwnProperty(groupId)) {
          const group = groupsJson[groupId];
          groups.push(
            new GroupMetadata({
              id: groupId,
              group: groupsJson[groupId],
              class: schema.classes[group.class],
            })
          );
        }
      }
    }

    this._schema = schema;
    this._groups = groups;
    this._groupIds = groupIds;
    this._tileset = tileset;

    this._statistics = metadataJson.statistics;
    this._extras = metadataJson.extras;
    this._extensions = metadataJson.extensions;
  }

  Object.defineProperties(Cesium3DTilesetMetadata.prototype, {
    /**
     * Schema containing classes and enums.
     *
     * @memberof Cesium3DTilesetMetadata.prototype
     * @type {MetadataSchema}
     * @readonly
     * @private
     */
    schema: {
      get: function () {
        return this._schema;
      },
    },

    /**
     * Metadata about groups of content.
     *
     * @memberof Cesium3DTilesetMetadata.prototype
     * @type {GroupMetadata[]}
     * @readonly
     * @private
     */
    groups: {
      get: function () {
        return this._groups;
      },
    },

    /**
     * The IDs of the group metadata in the corresponding groups dictionary.
     * Only populated if using the legacy schema.
     *
     * @memberof Cesium3DTilesetMetadata.prototype
     * @type {String[]}
     * @readonly
     * @private
     */
    groupIds: {
      get: function () {
        return this._groupIds;
      },
    },

    /**
     * Metadata about the tileset as a whole.
     *
     * @memberof Cesium3DTilesetMetadata.prototype
     * @type {TilesetMetadata}
     * @readonly
     * @private
     */
    tileset: {
      get: function () {
        return this._tileset;
      },
    },

    /**
     * Statistics about the metadata.
     * <p>
     * See the {@link https://github.com/CesiumGS/3d-tiles/blob/main/extensions/3DTILES_metadata/schema/statistics.schema.json|statistics schema reference}
     * in the 3D Tiles spec for the full set of properties.
     * </p>
     *
     * @memberof Cesium3DTilesetMetadata.prototype
     * @type {Object}
     * @readonly
     * @private
     */
    statistics: {
      get: function () {
        return this._statistics;
      },
    },

    /**
     * Extras in the JSON object.
     *
     * @memberof Cesium3DTilesetMetadata.prototype
     * @type {*}
     * @readonly
     * @private
     */
    extras: {
      get: function () {
        return this._extras;
      },
    },

    /**
     * Extensions in the JSON object.
     *
     * @memberof Cesium3DTilesetMetadata.prototype
     * @type {Object}
     * @readonly
     * @private
     */
    extensions: {
      get: function () {
        return this._extensions;
      },
    },
  });

  /**
   * Utility functions for computing optimization hints for a {@link Cesium3DTileset}.
   *
   * @namespace Cesium3DTileOptimizations
   *
   * @private
   */
  const Cesium3DTileOptimizations = {};

  const scratchAxis$1 = new Cartesian3();

  /**
   * Evaluates support for the childrenWithinParent optimization. This is used to more tightly cull tilesets if
   * children bounds are fully contained within the parent. Currently, support for the optimization only works for
   * oriented bounding boxes, so both the child and parent tile must be either a {@link TileOrientedBoundingBox} or
   * {@link TileBoundingRegion}. The purpose of this check is to prevent use of a culling optimization when the child
   * bounds exceed those of the parent. If the child bounds are greater, it is more likely that the optimization will
   * waste CPU cycles. Bounding spheres are not supported for the reason that the child bounds can very often be
   * partially outside of the parent bounds.
   *
   * @param {Cesium3DTile} tile The tile to check.
   * @returns {Boolean} Whether the childrenWithinParent optimization is supported.
   */
  Cesium3DTileOptimizations.checkChildrenWithinParent = function (tile) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("tile", tile);
    //>>includeEnd('debug');

    const children = tile.children;
    const length = children.length;

    // Check if the parent has an oriented bounding box.
    const boundingVolume = tile.boundingVolume;
    if (
      boundingVolume instanceof TileOrientedBoundingBox ||
      boundingVolume instanceof TileBoundingRegion
    ) {
      const orientedBoundingBox = boundingVolume._orientedBoundingBox;
      tile._optimChildrenWithinParent =
        Cesium3DTileOptimizationHint$1.USE_OPTIMIZATION;
      for (let i = 0; i < length; ++i) {
        const child = children[i];

        // Check if the child has an oriented bounding box.
        const childBoundingVolume = child.boundingVolume;
        if (
          !(
            childBoundingVolume instanceof TileOrientedBoundingBox ||
            childBoundingVolume instanceof TileBoundingRegion
          )
        ) {
          // Do not support if the parent and child both do not have oriented bounding boxes.
          tile._optimChildrenWithinParent =
            Cesium3DTileOptimizationHint$1.SKIP_OPTIMIZATION;
          break;
        }

        const childOrientedBoundingBox = childBoundingVolume._orientedBoundingBox;

        // Compute the axis from the parent to the child.
        const axis = Cartesian3.subtract(
          childOrientedBoundingBox.center,
          orientedBoundingBox.center,
          scratchAxis$1
        );
        const axisLength = Cartesian3.magnitude(axis);
        Cartesian3.divideByScalar(axis, axisLength, axis);

        // Project the bounding box of the parent onto the axis. Because the axis is a ray from the parent
        // to the child, the projection parameterized along the ray will be (+/- proj1).
        const proj1 =
          Math.abs(orientedBoundingBox.halfAxes[0] * axis.x) +
          Math.abs(orientedBoundingBox.halfAxes[1] * axis.y) +
          Math.abs(orientedBoundingBox.halfAxes[2] * axis.z) +
          Math.abs(orientedBoundingBox.halfAxes[3] * axis.x) +
          Math.abs(orientedBoundingBox.halfAxes[4] * axis.y) +
          Math.abs(orientedBoundingBox.halfAxes[5] * axis.z) +
          Math.abs(orientedBoundingBox.halfAxes[6] * axis.x) +
          Math.abs(orientedBoundingBox.halfAxes[7] * axis.y) +
          Math.abs(orientedBoundingBox.halfAxes[8] * axis.z);

        // Project the bounding box of the child onto the axis. Because the axis is a ray from the parent
        // to the child, the projection parameterized along the ray will be (+/- proj2) + axis.length.
        const proj2 =
          Math.abs(childOrientedBoundingBox.halfAxes[0] * axis.x) +
          Math.abs(childOrientedBoundingBox.halfAxes[1] * axis.y) +
          Math.abs(childOrientedBoundingBox.halfAxes[2] * axis.z) +
          Math.abs(childOrientedBoundingBox.halfAxes[3] * axis.x) +
          Math.abs(childOrientedBoundingBox.halfAxes[4] * axis.y) +
          Math.abs(childOrientedBoundingBox.halfAxes[5] * axis.z) +
          Math.abs(childOrientedBoundingBox.halfAxes[6] * axis.x) +
          Math.abs(childOrientedBoundingBox.halfAxes[7] * axis.y) +
          Math.abs(childOrientedBoundingBox.halfAxes[8] * axis.z);

        // If the child extends the parent's bounds, the optimization is not valid and we skip it.
        if (proj1 <= proj2 + axisLength) {
          tile._optimChildrenWithinParent =
            Cesium3DTileOptimizationHint$1.SKIP_OPTIMIZATION;
          break;
        }
      }
    }

    return (
      tile._optimChildrenWithinParent ===
      Cesium3DTileOptimizationHint$1.USE_OPTIMIZATION
    );
  };

  /**
   * Stores tiles with content loaded.
   *
   * @private
   */
  function Cesium3DTilesetCache() {
    // [head, sentinel) -> tiles that weren't selected this frame and may be removed from the cache
    // (sentinel, tail] -> tiles that were selected this frame
    this._list = new DoublyLinkedList();
    this._sentinel = this._list.add();
    this._trimTiles = false;
  }

  Cesium3DTilesetCache.prototype.reset = function () {
    // Move sentinel node to the tail so, at the start of the frame, all tiles
    // may be potentially replaced.  Tiles are moved to the right of the sentinel
    // when they are selected so they will not be replaced.
    this._list.splice(this._list.tail, this._sentinel);
  };

  Cesium3DTilesetCache.prototype.touch = function (tile) {
    const node = tile.cacheNode;
    if (defined(node)) {
      this._list.splice(this._sentinel, node);
    }
  };

  Cesium3DTilesetCache.prototype.add = function (tile) {
    if (!defined(tile.cacheNode)) {
      tile.cacheNode = this._list.add(tile);
    }
  };

  Cesium3DTilesetCache.prototype.unloadTile = function (
    tileset,
    tile,
    unloadCallback
  ) {
    const node = tile.cacheNode;
    if (!defined(node)) {
      return;
    }

    this._list.remove(node);
    tile.cacheNode = undefined;
    unloadCallback(tileset, tile);
  };

  Cesium3DTilesetCache.prototype.unloadTiles = function (
    tileset,
    unloadCallback
  ) {
    const trimTiles = this._trimTiles;
    this._trimTiles = false;

    const list = this._list;

    const maximumMemoryUsageInBytes = tileset.maximumMemoryUsage * 1024 * 1024;

    // Traverse the list only to the sentinel since tiles/nodes to the
    // right of the sentinel were used this frame.
    //
    // The sub-list to the left of the sentinel is ordered from LRU to MRU.
    const sentinel = this._sentinel;
    let node = list.head;
    while (
      node !== sentinel &&
      (tileset.totalMemoryUsageInBytes > maximumMemoryUsageInBytes || trimTiles)
    ) {
      const tile = node.item;
      node = node.next;
      this.unloadTile(tileset, tile, unloadCallback);
    }
  };

  Cesium3DTilesetCache.prototype.trim = function () {
    this._trimTiles = true;
  };

  /**
   * A heatmap colorizer in a {@link Cesium3DTileset}. A tileset can colorize its visible tiles in a heatmap style.
   *
   * @alias Cesium3DTilesetHeatmap
   * @constructor
   * @private
   */
  function Cesium3DTilesetHeatmap(tilePropertyName) {
    /**
     * The tile variable to track for heatmap colorization.
     * Tile's will be colorized relative to the other visible tile's values for this variable.
     *
     * @type {String}
     */
    this.tilePropertyName = tilePropertyName;

    // Members that are updated every time a tile is colorized
    this._minimum = Number.MAX_VALUE;
    this._maximum = -Number.MAX_VALUE;

    // Members that are updated once every frame
    this._previousMinimum = Number.MAX_VALUE;
    this._previousMaximum = -Number.MAX_VALUE;

    // If defined uses a reference minimum maximum to colorize by instead of using last frames minimum maximum of rendered tiles.
    // For example, the _loadTimestamp can get a better colorization using setReferenceMinimumMaximum in order to take accurate colored timing diffs of various scenes.
    this._referenceMinimum = {};
    this._referenceMaximum = {};
  }

  /**
   * Convert to a usable heatmap value (i.e. a number). Ensures that tile values that aren't stored as numbers can be used for colorization.
   * @private
   */
  function getHeatmapValue(tileValue, tilePropertyName) {
    let value;
    if (tilePropertyName === "_loadTimestamp") {
      value = JulianDate.toDate(tileValue).getTime();
    } else {
      value = tileValue;
    }
    return value;
  }

  /**
   * Sets the reference minimum and maximum for the variable name. Converted to numbers before they are stored.
   *
   * @param {Object} minimum The minimum reference value.
   * @param {Object} maximum The maximum reference value.
   * @param {String} tilePropertyName The tile variable that will use these reference values when it is colorized.
   */
  Cesium3DTilesetHeatmap.prototype.setReferenceMinimumMaximum = function (
    minimum,
    maximum,
    tilePropertyName
  ) {
    this._referenceMinimum[tilePropertyName] = getHeatmapValue(
      minimum,
      tilePropertyName
    );
    this._referenceMaximum[tilePropertyName] = getHeatmapValue(
      maximum,
      tilePropertyName
    );
  };

  function getHeatmapValueAndUpdateMinimumMaximum(heatmap, tile) {
    const tilePropertyName = heatmap.tilePropertyName;
    if (defined(tilePropertyName)) {
      const heatmapValue = getHeatmapValue(
        tile[tilePropertyName],
        tilePropertyName
      );
      if (!defined(heatmapValue)) {
        heatmap.tilePropertyName = undefined;
        return heatmapValue;
      }
      heatmap._maximum = Math.max(heatmapValue, heatmap._maximum);
      heatmap._minimum = Math.min(heatmapValue, heatmap._minimum);
      return heatmapValue;
    }
  }

  const heatmapColors = [
    new Color(0.1, 0.1, 0.1, 1), // Dark Gray
    new Color(0.153, 0.278, 0.878, 1), // Blue
    new Color(0.827, 0.231, 0.49, 1), // Pink
    new Color(0.827, 0.188, 0.22, 1), // Red
    new Color(1.0, 0.592, 0.259, 1), // Orange
    new Color(1.0, 0.843, 0.0, 1),
  ]; // Yellow
  /**
   * Colorize the tile in heat map style based on where it lies within the minimum maximum window.
   * Heatmap colors are black, blue, pink, red, orange, yellow. 'Cold' or low numbers will be black and blue, 'Hot' or high numbers will be orange and yellow,
   * @param {Cesium3DTile} tile The tile to colorize relative to last frame's minimum and maximum values of all visible tiles.
   * @param {FrameState} frameState The frame state.
   */
  Cesium3DTilesetHeatmap.prototype.colorize = function (tile, frameState) {
    const tilePropertyName = this.tilePropertyName;
    if (
      !defined(tilePropertyName) ||
      !tile.contentAvailable ||
      tile._selectedFrame !== frameState.frameNumber
    ) {
      return;
    }

    const heatmapValue = getHeatmapValueAndUpdateMinimumMaximum(this, tile);
    const minimum = this._previousMinimum;
    const maximum = this._previousMaximum;

    if (minimum === Number.MAX_VALUE || maximum === -Number.MAX_VALUE) {
      return;
    }

    // Shift the minimum maximum window down to 0
    const shiftedMax = maximum - minimum + CesiumMath.EPSILON7; // Prevent divide by 0
    const shiftedValue = CesiumMath.clamp(
      heatmapValue - minimum,
      0.0,
      shiftedMax
    );

    // Get position between minimum and maximum and convert that to a position in the color array
    const zeroToOne = shiftedValue / shiftedMax;
    const lastIndex = heatmapColors.length - 1.0;
    const colorPosition = zeroToOne * lastIndex;

    // Take floor and ceil of the value to get the two colors to lerp between, lerp using the fractional portion
    const colorPositionFloor = Math.floor(colorPosition);
    const colorPositionCeil = Math.ceil(colorPosition);
    const t = colorPosition - colorPositionFloor;
    const colorZero = heatmapColors[colorPositionFloor];
    const colorOne = heatmapColors[colorPositionCeil];

    // Perform the lerp
    const finalColor = Color.clone(Color.WHITE);
    finalColor.red = CesiumMath.lerp(colorZero.red, colorOne.red, t);
    finalColor.green = CesiumMath.lerp(colorZero.green, colorOne.green, t);
    finalColor.blue = CesiumMath.lerp(colorZero.blue, colorOne.blue, t);
    tile._debugColor = finalColor;
  };

  /**
   * Resets the tracked minimum maximum values for heatmap colorization. Happens right before tileset traversal.
   */
  Cesium3DTilesetHeatmap.prototype.resetMinimumMaximum = function () {
    // For heat map colorization
    const tilePropertyName = this.tilePropertyName;
    if (defined(tilePropertyName)) {
      const referenceMinimum = this._referenceMinimum[tilePropertyName];
      const referenceMaximum = this._referenceMaximum[tilePropertyName];
      const useReference = defined(referenceMinimum) && defined(referenceMaximum);
      this._previousMinimum = useReference ? referenceMinimum : this._minimum;
      this._previousMaximum = useReference ? referenceMaximum : this._maximum;
      this._minimum = Number.MAX_VALUE;
      this._maximum = -Number.MAX_VALUE;
    }
  };

  /**
   * @private
   */
  function Cesium3DTilesetStatistics() {
    // Rendering statistics
    this.selected = 0;
    this.visited = 0;
    // Loading statistics
    this.numberOfCommands = 0;
    this.numberOfAttemptedRequests = 0;
    this.numberOfPendingRequests = 0;
    this.numberOfTilesProcessing = 0;
    this.numberOfTilesWithContentReady = 0; // Number of tiles with content loaded, does not include empty tiles
    this.numberOfTilesTotal = 0; // Number of tiles in tileset JSON (and other tileset JSON files as they are loaded)
    this.numberOfLoadedTilesTotal = 0; // Running total of loaded tiles for the lifetime of the session
    // Features statistics
    this.numberOfFeaturesSelected = 0; // Number of features rendered
    this.numberOfFeaturesLoaded = 0; // Number of features in memory
    this.numberOfPointsSelected = 0;
    this.numberOfPointsLoaded = 0;
    this.numberOfTrianglesSelected = 0;
    // Styling statistics
    this.numberOfTilesStyled = 0;
    this.numberOfFeaturesStyled = 0;
    // Optimization statistics
    this.numberOfTilesCulledWithChildrenUnion = 0;
    // Memory statistics
    this.geometryByteLength = 0;
    this.texturesByteLength = 0;
    this.batchTableByteLength = 0; // batch textures and any binary metadata properties not otherwise accounted for
  }

  Cesium3DTilesetStatistics.prototype.clear = function () {
    this.selected = 0;
    this.visited = 0;
    this.numberOfCommands = 0;
    this.numberOfAttemptedRequests = 0;
    this.numberOfFeaturesSelected = 0;
    this.numberOfPointsSelected = 0;
    this.numberOfTrianglesSelected = 0;
    this.numberOfTilesStyled = 0;
    this.numberOfFeaturesStyled = 0;
    this.numberOfTilesCulledWithChildrenUnion = 0;
  };

  function updatePointAndFeatureCounts(statistics, content, decrement, load) {
    const contents = content.innerContents;
    const pointsLength = content.pointsLength;
    const trianglesLength = content.trianglesLength;
    const featuresLength = content.featuresLength;
    const geometryByteLength = content.geometryByteLength;
    const texturesByteLength = content.texturesByteLength;
    const batchTableByteLength = content.batchTableByteLength;

    if (load) {
      statistics.numberOfFeaturesLoaded += decrement
        ? -featuresLength
        : featuresLength;
      statistics.numberOfPointsLoaded += decrement ? -pointsLength : pointsLength;
      statistics.geometryByteLength += decrement
        ? -geometryByteLength
        : geometryByteLength;
      statistics.texturesByteLength += decrement
        ? -texturesByteLength
        : texturesByteLength;
      statistics.batchTableByteLength += decrement
        ? -batchTableByteLength
        : batchTableByteLength;
    } else {
      statistics.numberOfFeaturesSelected += decrement
        ? -featuresLength
        : featuresLength;
      statistics.numberOfPointsSelected += decrement
        ? -pointsLength
        : pointsLength;
      statistics.numberOfTrianglesSelected += decrement
        ? -trianglesLength
        : trianglesLength;
    }

    if (defined(contents)) {
      const length = contents.length;
      for (let i = 0; i < length; ++i) {
        updatePointAndFeatureCounts(statistics, contents[i], decrement, load);
      }
    }
  }

  Cesium3DTilesetStatistics.prototype.incrementSelectionCounts = function (
    content
  ) {
    updatePointAndFeatureCounts(this, content, false, false);
  };

  Cesium3DTilesetStatistics.prototype.incrementLoadCounts = function (content) {
    updatePointAndFeatureCounts(this, content, false, true);
  };

  Cesium3DTilesetStatistics.prototype.decrementLoadCounts = function (content) {
    updatePointAndFeatureCounts(this, content, true, true);
  };

  Cesium3DTilesetStatistics.clone = function (statistics, result) {
    result.selected = statistics.selected;
    result.visited = statistics.visited;
    result.numberOfCommands = statistics.numberOfCommands;
    result.selected = statistics.selected;
    result.numberOfAttemptedRequests = statistics.numberOfAttemptedRequests;
    result.numberOfPendingRequests = statistics.numberOfPendingRequests;
    result.numberOfTilesProcessing = statistics.numberOfTilesProcessing;
    result.numberOfTilesWithContentReady =
      statistics.numberOfTilesWithContentReady;
    result.numberOfTilesTotal = statistics.numberOfTilesTotal;
    result.numberOfFeaturesSelected = statistics.numberOfFeaturesSelected;
    result.numberOfFeaturesLoaded = statistics.numberOfFeaturesLoaded;
    result.numberOfPointsSelected = statistics.numberOfPointsSelected;
    result.numberOfPointsLoaded = statistics.numberOfPointsLoaded;
    result.numberOfTrianglesSelected = statistics.numberOfTrianglesSelected;
    result.numberOfTilesStyled = statistics.numberOfTilesStyled;
    result.numberOfFeaturesStyled = statistics.numberOfFeaturesStyled;
    result.numberOfTilesCulledWithChildrenUnion =
      statistics.numberOfTilesCulledWithChildrenUnion;
    result.geometryByteLength = statistics.geometryByteLength;
    result.texturesByteLength = statistics.texturesByteLength;
    result.batchTableByteLength = statistics.batchTableByteLength;
  };

  /**
   * @private
   */
  function Cesium3DTileStyleEngine() {
    this._style = undefined; // The style provided by the user
    this._styleDirty = false; // true when the style is reassigned
    this._lastStyleTime = 0; // The "time" when the last style was assigned
  }

  Object.defineProperties(Cesium3DTileStyleEngine.prototype, {
    style: {
      get: function () {
        return this._style;
      },
      set: function (value) {
        if (value === this._style) {
          return;
        }
        this._style = value;
        this._styleDirty = true;
      },
    },
  });

  Cesium3DTileStyleEngine.prototype.makeDirty = function () {
    this._styleDirty = true;
  };

  Cesium3DTileStyleEngine.prototype.resetDirty = function () {
    this._styleDirty = false;
  };

  Cesium3DTileStyleEngine.prototype.applyStyle = function (tileset) {
    if (!tileset.ready) {
      return;
    }

    if (defined(this._style) && !this._style._ready) {
      return;
    }

    const styleDirty = this._styleDirty;

    if (styleDirty) {
      // Increase "time", so the style is applied to all visible tiles
      ++this._lastStyleTime;
    }

    const lastStyleTime = this._lastStyleTime;
    const statistics = tileset._statistics;

    // If a new style was assigned, loop through all the visible tiles; otherwise, loop through
    // only the tiles that are newly visible, i.e., they are visible this frame, but were not
    // visible last frame.  In many cases, the newly selected tiles list will be short or empty.
    const tiles = styleDirty
      ? tileset._selectedTiles
      : tileset._selectedTilesToStyle;
    // PERFORMANCE_IDEA: does mouse-over picking basically trash this?  We need to style on
    // pick, for example, because a feature's show may be false.

    const length = tiles.length;
    for (let i = 0; i < length; ++i) {
      const tile = tiles[i];
      if (tile.lastStyleTime !== lastStyleTime) {
        // Apply the style to this tile if it wasn't already applied because:
        //   1) the user assigned a new style to the tileset
        //   2) this tile is now visible, but it wasn't visible when the style was first assigned
        const content = tile.content;
        tile.lastStyleTime = lastStyleTime;
        content.applyStyle(this._style);
        statistics.numberOfFeaturesStyled += content.featuresLength;
        ++statistics.numberOfTilesStyled;
      }
    }
  };

  /**
   * An ImplicitTileset is a simple struct that stores information about the
   * structure of a single implicit tileset. This includes template URIs for
   * locating resources, details from the implicit root tile (bounding volume,
   * geometricError, etc.), and details about the subtrees (e.g. subtreeLevels,
   * subdivisionScheme).
   *
   * @alias ImplicitTileset
   * @constructor
   *
   * @param {Resource} baseResource The base resource for the tileset
   * @param {Object} tileJson The JSON header of the tile with either implicit tiling (3D Tiles 1.1) or the 3DTILES_implicit_tiling extension.
   * @param {MetadataSchema} [metadataSchema] The metadata schema containing the implicit tile metadata class.
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function ImplicitTileset(
    baseResource,
    tileJson,
    metadataSchema
  ) {
    const implicitTiling = hasExtension(tileJson, "3DTILES_implicit_tiling")
      ? tileJson.extensions["3DTILES_implicit_tiling"]
      : tileJson.implicitTiling;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("implicitTiling", implicitTiling);
    //>>includeEnd('debug');

    /**
     * The base resource for the tileset. This is stored here as it is needed
     * later when expanding Implicit3DTileContents so tile URLs are relative
     * to the tileset, not the subtree file.
     *
     * @type {Resource}
     * @readonly
     * @private
     */
    this.baseResource = baseResource;

    /**
     * The geometric error of the root tile
     *
     * @type {Number}
     * @readonly
     * @private
     */
    this.geometricError = tileJson.geometricError;

    /**
     * The metadata schema containing the implicit tile metadata class.
     *
     * @type {MetadataSchema|undefined}
     * @readonly
     * @private
     */
    this.metadataSchema = metadataSchema;

    const boundingVolume = tileJson.boundingVolume;
    if (
      !defined(boundingVolume.box) &&
      !defined(boundingVolume.region) &&
      !hasExtension(boundingVolume, "3DTILES_bounding_volume_S2")
    ) {
      throw new RuntimeError(
        "Only box, region and 3DTILES_bounding_volume_S2 are supported for implicit tiling"
      );
    }

    /**
     * The JSON representation of a bounding volume. This is either a box or a
     * region.
     *
     * @type {Object}
     * @readonly
     * @private
     */
    this.boundingVolume = boundingVolume;

    /**
     * The refine strategy as a string, either 'ADD' or 'REPLACE'
     *
     * @type {String}
     * @readonly
     * @private
     */
    this.refine = tileJson.refine;

    /**
     * Template URI for the subtree resources, e.g.
     * <code>https://example.com/{level}/{x}/{y}.subtree</code>
     *
     * @type {Resource}
     * @readonly
     * @private
     */

    this.subtreeUriTemplate = new Resource({ url: implicitTiling.subtrees.uri });

    /**
     * Template URIs for locating content resources, e.g.
     * <code>https://example.com/{level}/{x}/{y}.b3dm</code>.
     * <p>
     * This is an array to support multiple contents.
     * </p>
     *
     * @type {Resource[]}
     * @readonly
     * @private
     */
    this.contentUriTemplates = [];

    /**
     * Store a copy of the content headers, so properties such as
     * <code>extras</code> or <code>extensions</code> are preserved when
     * {@link Cesium3DTile}s are created for each tile.
     * <p>
     * This is an array to support multiple contents.
     * </p>
     *
     * @type {Object[]}
     * @readonly
     * @private
     */
    this.contentHeaders = [];

    const contentHeaders = gatherContentHeaders(tileJson);
    for (let i = 0; i < contentHeaders.length; i++) {
      const contentHeader = contentHeaders[i];
      this.contentHeaders.push(clone$1(contentHeader, true));
      const contentResource = new Resource({ url: contentHeader.uri });
      this.contentUriTemplates.push(contentResource);
    }

    /**
     * The maximum number of contents as well as content availability bitstreams.
     * This is used for loop bounds when checking content availability.
     *
     * @type {Number}
     * @readonly
     * @private
     */
    this.contentCount = this.contentHeaders.length;

    /**
     * Stores a copy of the root implicit tile's JSON header. This is used
     * as a template for creating {@link Cesium3DTile}s. The following properties
     * are removed:
     *
     * <ul>
     * <li><code>tile.implicitTiling</code> to prevent infinite loops of implicit tiling</li>
     * <li><code>tile.extensions["3DTILES_implicit_tiling"]</code>, if used instead of tile.implicitTiling</li>
     * <li><code>tile.contents</code>, since contents are handled separately</li>
     * <li><code>tile.content</code>, if used instead of tile.contents</li>
     * <li><code>tile.extensions["3DTILES_multiple_contents"]</code>, if used instead of tile.contents or tile.content</li>
     * </ul>
     *
     * @type {Object}
     * @readonly
     * @private
     */
    this.tileHeader = makeTileHeaderTemplate(tileJson);

    /**
     * The subdivision scheme for this implicit tileset; either OCTREE or QUADTREE
     *
     * @type {ImplicitSubdivisionScheme}
     * @readonly
     * @private
     */
    this.subdivisionScheme =
      ImplicitSubdivisionScheme$1[implicitTiling.subdivisionScheme];

    /**
     * The branching factor for this tileset. Either 4 for quadtrees or 8 for
     * octrees.
     *
     * @type {Number}
     * @readonly
     * @private
     */
    this.branchingFactor = ImplicitSubdivisionScheme$1.getBranchingFactor(
      this.subdivisionScheme
    );

    /**
     * How many distinct levels within each subtree. For example, a quadtree
     * with subtreeLevels = 2 will have 5 nodes per quadtree (1 root + 4 children)
     *
     * @type {Number}
     * @readonly
     * @private
     */
    this.subtreeLevels = implicitTiling.subtreeLevels;

    /**
     * The number of levels containing available tiles in the tileset.
     *
     * @type {Number}
     * @readonly
     * @private
     */
    if (defined(implicitTiling.availableLevels)) {
      this.availableLevels = implicitTiling.availableLevels;
    } else {
      this.availableLevels = implicitTiling.maximumLevel + 1;
    }
  }

  /**
   * Gather JSON headers for all contents in the tile.
   * This handles both regular tiles and tiles with multiple contents, either
   * in the contents array (3D Tiles 1.1) or the `3DTILES_multiple_contents` extension
   *
   * @param {Object} tileJson The JSON header of the tile with either implicit tiling (3D Tiles 1.1) or the 3DTILES_implicit_tiling extension.
   * @return {Object[]} An array of JSON headers for the contents of each tile
   * @private
   */
  function gatherContentHeaders(tileJson) {
    if (hasExtension(tileJson, "3DTILES_multiple_contents")) {
      const extension = tileJson.extensions["3DTILES_multiple_contents"];
      return defined(extension.contents) ? extension.contents : extension.content;
    }

    if (defined(tileJson.contents)) {
      return tileJson.contents;
    }

    if (defined(tileJson.content)) {
      return [tileJson.content];
    }

    return [];
  }

  function makeTileHeaderTemplate(tileJson) {
    const template = clone$1(tileJson, true);

    // Remove the implicit tiling extension to prevent infinite loops,
    // as well as content-related properties since content is handled separately
    if (defined(template.extensions)) {
      delete template.extensions["3DTILES_implicit_tiling"];
      delete template.extensions["3DTILES_multiple_contents"];

      // if there are no other extensions, remove the extensions property to
      // keep each tile simple
      if (Object.keys(template.extensions).length === 0) {
        delete template.extensions;
      }
    }

    delete template.implicitTiling;
    delete template.contents;
    delete template.content;

    return template;
  }

  /**
   * The coordinates for a tile in an implicit tileset. The coordinates
   * are (level, x, y) for quadtrees or (level, x, y, z) for octrees.
   * <p>
   * Level numbers are 0-indexed and typically start at the root of the implicit
   * tileset (the tile with either implicitTiling in its JSON (3D Tiles 1.1) or
   * the <code>3DTILES_implicit_tiling</code> extension).
   * This object can also represent the relative offset from one set of coordinates
   * to another. See {@link ImplicitTileCoordinates#getOffsetCoordinates}. The term
   * local coordinates refers to coordinates that are relative to the root of a
   * subtree and the term global coordinates refers to coordinates relative to the
   * root of an implicit tileset.
   * </p>
   * <p>
   * For box bounding volumes, x, y, z increase along the +x, +y, and +z
   * directions defined by the half axes.
   * </p>
   * <p>
   * For region bounding volumes, x increases in the +longitude direction, y
   * increases in the +latitude direction, and z increases in the +height
   * direction.
   * </p>
   * <p>
   * Care must be taken when converting between implicit coordinates and Morton
   * indices because there is a 16-bit limit on {@link MortonOrder#encode2D} and
   * a 10-bit limit on {@link MortonOrder#encode3D}. Typically these conversions
   * should be done on local coordinates, not global coordinates, and the maximum
   * number of levels in the subtree should be 15 for quadtree and 9 for octree (to
   * account for the extra level needed by child subtree coordinates).
   * </p>
   *
   * @alias ImplicitTileCoordinates
   * @constructor
   *
   * @param {Object} options An object with the following properties:
   * @param {ImplicitSubdivisionScheme} options.subdivisionScheme Whether the coordinates are for a quadtree or octree
   * @param {Number} options.subtreeLevels The number of distinct levels within the coordinate's subtree
   * @param {Number} options.level The level of a tile relative to the tile with the extension
   * @param {Number} options.x The x coordinate of the tile
   * @param {Number} options.y The y coordinate of the tile
   * @param {Number} [options.z] The z coordinate of the tile. Only required when options.subdivisionScheme is ImplicitSubdivisionScheme.OCTREE
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function ImplicitTileCoordinates(options) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("options.subdivisionScheme", options.subdivisionScheme);
    Check.typeOf.number("options.subtreeLevels", options.subtreeLevels);
    Check.typeOf.number("options.level", options.level);
    Check.typeOf.number("options.x", options.x);
    Check.typeOf.number("options.y", options.y);
    if (options.subdivisionScheme === ImplicitSubdivisionScheme$1.OCTREE) {
      Check.typeOf.number("options.z", options.z);
    }
    // Check for values that are negative
    if (options.level < 0) {
      throw new DeveloperError("level must be non-negative");
    }
    if (options.x < 0) {
      throw new DeveloperError("x must be non-negative");
    }
    if (options.y < 0) {
      throw new DeveloperError("y must be non-negative");
    }
    if (options.subdivisionScheme === ImplicitSubdivisionScheme$1.OCTREE) {
      if (options.z < 0) {
        throw new DeveloperError("z must be non-negative");
      }
    }

    // Check for values that are too large
    const dimensionAtLevel = 1 << options.level;
    if (options.x >= dimensionAtLevel) {
      throw new DeveloperError("x is out of range");
    }
    if (options.y >= dimensionAtLevel) {
      throw new DeveloperError("y is out of range");
    }
    if (options.subdivisionScheme === ImplicitSubdivisionScheme$1.OCTREE) {
      if (options.z >= dimensionAtLevel) {
        throw new DeveloperError("z is out of range");
      }
    }
    //>>includeEnd('debug');

    /**
     * Whether the tileset is a quadtree or octree
     *
     * @type {ImplicitSubdivisionScheme}
     * @readonly
     * @private
     */
    this.subdivisionScheme = options.subdivisionScheme;

    /**
     * The number of distinct levels within the coordinate's subtree
     *
     * @type {Number}
     * @readonly
     * @private
     */
    this.subtreeLevels = options.subtreeLevels;

    /**
     * Level of this tile, relative to the tile with implicit tiling in its JSON
     * (3D Tiles 1.1) or the <code>3DTILES_implicit_tiling</code> extension.
     * Level numbers start at 0.
     *
     * @type {Number}
     * @readonly
     * @private
     */
    this.level = options.level;

    /**
     * X coordinate of this tile
     *
     * @type {Number}
     * @readonly
     * @private
     */
    this.x = options.x;

    /**
     * Y coordinate of this tile
     *
     * @type {Number}
     * @readonly
     * @private
     */
    this.y = options.y;

    /**
     * Z coordinate of this tile. Only defined for octrees.
     *
     * @type {Number|undefined}
     * @readonly
     * @private
     */
    this.z = undefined;
    if (options.subdivisionScheme === ImplicitSubdivisionScheme$1.OCTREE) {
      this.z = options.z;
    }
  }

  Object.defineProperties(ImplicitTileCoordinates.prototype, {
    /**
     * An index in the range of [0, branchingFactor) that indicates
     * which child of the parent cell these coordinates correspond to.
     * This can be viewed as a morton index within the parent tile.
     * <p>
     * This is the last 3 bits of the morton index of the tile, but it can
     * be computed more directly by concatenating the bits [z0] y0 x0
     * </p>
     *
     * @type {Number}
     * @readonly
     * @private
     */
    childIndex: {
      get: function () {
        let childIndex = 0;
        childIndex |= this.x & 1;
        childIndex |= (this.y & 1) << 1;
        if (this.subdivisionScheme === ImplicitSubdivisionScheme$1.OCTREE) {
          childIndex |= (this.z & 1) << 2;
        }

        return childIndex;
      },
    },

    /**
     * Get the Morton index for this tile within the current level by interleaving
     * the bits of the x, y and z coordinates.
     *
     * @type {Number}
     * @readonly
     * @private
     */
    mortonIndex: {
      get: function () {
        if (this.subdivisionScheme === ImplicitSubdivisionScheme$1.OCTREE) {
          return MortonOrder.encode3D(this.x, this.y, this.z);
        }
        return MortonOrder.encode2D(this.x, this.y);
      },
    },

    /**
     * Get the tile index by adding the Morton index to the level offset
     *
     * @type {Number}
     * @readonly
     * @private
     */
    tileIndex: {
      get: function () {
        const levelOffset =
          this.subdivisionScheme === ImplicitSubdivisionScheme$1.OCTREE
            ? // (8^N - 1) / (8-1)
              ((1 << (3 * this.level)) - 1) / 7
            : // (4^N - 1) / (4-1)
              ((1 << (2 * this.level)) - 1) / 3;

        const mortonIndex = this.mortonIndex;
        return levelOffset + mortonIndex;
      },
    },
  });

  /**
   * Check that the two coordinates are compatible
   * @param {ImplicitTileCoordinates} a
   * @param {ImplicitTileCoordinates} b
   * @private
   */
  function checkMatchingSubtreeShape(a, b) {
    if (a.subdivisionScheme !== b.subdivisionScheme) {
      throw new DeveloperError("coordinates must have same subdivisionScheme");
    }
    if (a.subtreeLevels !== b.subtreeLevels) {
      throw new DeveloperError("coordinates must have same subtreeLevels");
    }
  }

  /**
   * Compute the coordinates of a tile deeper in the tree with a (level, x, y, [z]) relative offset.
   *
   * @param {ImplicitTileCoordinates} offsetCoordinates The offset from the ancestor
   * @returns {ImplicitTileCoordinates} The coordinates of the descendant
   * @private
   */
  ImplicitTileCoordinates.prototype.getDescendantCoordinates = function (
    offsetCoordinates
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("offsetCoordinates", offsetCoordinates);
    checkMatchingSubtreeShape(this, offsetCoordinates);
    //>>includeEnd('debug');

    const descendantLevel = this.level + offsetCoordinates.level;
    const descendantX = (this.x << offsetCoordinates.level) + offsetCoordinates.x;
    const descendantY = (this.y << offsetCoordinates.level) + offsetCoordinates.y;

    if (this.subdivisionScheme === ImplicitSubdivisionScheme$1.OCTREE) {
      const descendantZ =
        (this.z << offsetCoordinates.level) + offsetCoordinates.z;

      return new ImplicitTileCoordinates({
        subdivisionScheme: this.subdivisionScheme,
        subtreeLevels: this.subtreeLevels,
        level: descendantLevel,
        x: descendantX,
        y: descendantY,
        z: descendantZ,
      });
    }

    // Quadtree
    return new ImplicitTileCoordinates({
      subdivisionScheme: this.subdivisionScheme,
      subtreeLevels: this.subtreeLevels,
      level: descendantLevel,
      x: descendantX,
      y: descendantY,
    });
  };

  /**
   * Compute the coordinates of a tile higher up in the tree by going up a number of levels.
   *
   * @param {Number} offsetLevels The number of levels to go up in the tree
   * @returns {ImplicitTileCoordinates} The coordinates of the ancestor
   * @private
   */
  ImplicitTileCoordinates.prototype.getAncestorCoordinates = function (
    offsetLevels
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("offsetLevels", offsetLevels);
    if (offsetLevels < 0) {
      throw new DeveloperError("offsetLevels must be non-negative");
    }
    if (offsetLevels > this.level) {
      throw new DeveloperError("ancestor cannot be above the tileset root");
    }
    //>>includeEnd('debug');

    const divisor = 1 << offsetLevels;
    const ancestorLevel = this.level - offsetLevels;
    const ancestorX = Math.floor(this.x / divisor);
    const ancestorY = Math.floor(this.y / divisor);

    if (this.subdivisionScheme === ImplicitSubdivisionScheme$1.OCTREE) {
      const ancestorZ = Math.floor(this.z / divisor);

      return new ImplicitTileCoordinates({
        subdivisionScheme: this.subdivisionScheme,
        subtreeLevels: this.subtreeLevels,
        level: ancestorLevel,
        x: ancestorX,
        y: ancestorY,
        z: ancestorZ,
      });
    }

    // Quadtree
    return new ImplicitTileCoordinates({
      subdivisionScheme: this.subdivisionScheme,
      subtreeLevels: this.subtreeLevels,
      level: ancestorLevel,
      x: ancestorX,
      y: ancestorY,
    });
  };

  /**
   * Compute the (level, x, y, [z]) offset to a descendant
   *
   * @param {ImplicitTileCoordinates} descendantCoordinates The descendant coordinates
   * @returns {ImplicitTileCoordinates} The offset between the ancestor and the descendant
   */
  ImplicitTileCoordinates.prototype.getOffsetCoordinates = function (
    descendantCoordinates
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("descendantCoordinates", descendantCoordinates);
    if (
      !this.isEqual(descendantCoordinates) &&
      !this.isAncestor(descendantCoordinates)
    ) {
      throw new DeveloperError("this is not an ancestor of descendant");
    }
    checkMatchingSubtreeShape(this, descendantCoordinates);
    //>>includeEnd('debug');

    const offsetLevel = descendantCoordinates.level - this.level;
    const dimensionAtOffsetLevel = 1 << offsetLevel;

    const offsetX = descendantCoordinates.x % dimensionAtOffsetLevel;
    const offsetY = descendantCoordinates.y % dimensionAtOffsetLevel;

    if (this.subdivisionScheme === ImplicitSubdivisionScheme$1.OCTREE) {
      const offsetZ = descendantCoordinates.z % dimensionAtOffsetLevel;

      return new ImplicitTileCoordinates({
        subdivisionScheme: this.subdivisionScheme,
        subtreeLevels: this.subtreeLevels,
        level: offsetLevel,
        x: offsetX,
        y: offsetY,
        z: offsetZ,
      });
    }

    // Quadtree
    return new ImplicitTileCoordinates({
      subdivisionScheme: this.subdivisionScheme,
      subtreeLevels: this.subtreeLevels,
      level: offsetLevel,
      x: offsetX,
      y: offsetY,
    });
  };

  /**
   * Given the morton index of the child, compute the coordinates of the child.
   * This is a special case of {@link ImplicitTileCoordinates#getDescendantCoordinates}.
   *
   * @param {Number} childIndex The morton index of the child tile relative to its parent
   * @returns {ImplicitTileCoordinates} The tile coordinates of the child
   * @private
   */
  ImplicitTileCoordinates.prototype.getChildCoordinates = function (childIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("childIndex", childIndex);
    const branchingFactor = ImplicitSubdivisionScheme$1.getBranchingFactor(
      this.subdivisionScheme
    );
    if (childIndex < 0 || branchingFactor <= childIndex) {
      throw new DeveloperError(
        `childIndex must be at least 0 and less than ${branchingFactor}`
      );
    }
    //>>includeEnd('debug');

    const level = this.level + 1;
    const x = 2 * this.x + (childIndex % 2);
    const y = 2 * this.y + (Math.floor(childIndex / 2) % 2);

    if (this.subdivisionScheme === ImplicitSubdivisionScheme$1.OCTREE) {
      const z = 2 * this.z + (Math.floor(childIndex / 4) % 2);
      return new ImplicitTileCoordinates({
        subdivisionScheme: this.subdivisionScheme,
        subtreeLevels: this.subtreeLevels,
        level: level,
        x: x,
        y: y,
        z: z,
      });
    }

    // Quadtree
    return new ImplicitTileCoordinates({
      subdivisionScheme: this.subdivisionScheme,
      subtreeLevels: this.subtreeLevels,
      level: level,
      x: x,
      y: y,
    });
  };

  /**
   * Get the coordinates of the subtree that contains this tile. If the tile is
   * the root of the subtree, the root of the subtree is returned.
   *
   * @returns {ImplicitTileCoordinates} The subtree that contains this tile
   * @private
   */
  ImplicitTileCoordinates.prototype.getSubtreeCoordinates = function () {
    return this.getAncestorCoordinates(this.level % this.subtreeLevels);
  };

  /**
   * Get the coordinates of the parent subtree that contains this tile
   *
   * @returns {ImplicitTileCoordinates} The parent subtree that contains this tile
   * @private
   */
  ImplicitTileCoordinates.prototype.getParentSubtreeCoordinates = function () {
    return this.getAncestorCoordinates(
      (this.level % this.subtreeLevels) + this.subtreeLevels
    );
  };

  /**
   * Returns whether this tile is an ancestor of another tile
   *
   * @param {ImplicitTileCoordinates} descendantCoordinates the descendant coordinates
   * @returns {Boolean} <code>true</code> if this tile is an ancestor of the other tile
   * @private
   */
  ImplicitTileCoordinates.prototype.isAncestor = function (
    descendantCoordinates
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("descendantCoordinates", descendantCoordinates);
    checkMatchingSubtreeShape(this, descendantCoordinates);
    //>>includeEnd('debug');

    const levelDifference = descendantCoordinates.level - this.level;
    if (levelDifference <= 0) {
      return false;
    }

    const ancestorX = descendantCoordinates.x >> levelDifference;
    const ancestorY = descendantCoordinates.y >> levelDifference;
    const isAncestorX = this.x === ancestorX;
    const isAncestorY = this.y === ancestorY;

    if (this.subdivisionScheme === ImplicitSubdivisionScheme$1.OCTREE) {
      const ancestorZ = descendantCoordinates.z >> levelDifference;
      const isAncestorZ = this.z === ancestorZ;
      return isAncestorX && isAncestorY && isAncestorZ;
    }

    // Quadtree
    return isAncestorX && isAncestorY;
  };

  /**
   * Returns whether the provided coordinates are equal to this coordinate
   *
   * @param {ImplicitTileCoordinates} otherCoordinates the other coordinates
   * @returns {Boolean} <code>true</code> if the coordinates are equal
   * @private
   */
  ImplicitTileCoordinates.prototype.isEqual = function (otherCoordinates) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("otherCoordinates", otherCoordinates);
    //>>includeEnd('debug');

    return (
      this.subdivisionScheme === otherCoordinates.subdivisionScheme &&
      this.subtreeLevels === otherCoordinates.subtreeLevels &&
      this.level === otherCoordinates.level &&
      this.x === otherCoordinates.x &&
      this.y === otherCoordinates.y &&
      (this.subdivisionScheme === ImplicitSubdivisionScheme$1.OCTREE
        ? this.z === otherCoordinates.z
        : true)
    );
  };

  /**
   * Returns whether this tile is the root of the implicit tileset
   *
   * @returns {Boolean} <code>true</code> if this tile is the root
   * @private
   */
  ImplicitTileCoordinates.prototype.isImplicitTilesetRoot = function () {
    return this.level === 0;
  };

  /**
   * Returns whether this tile is the root of the subtree
   *
   * @returns {Boolean} <code>true</code> if this tile is the root of the subtree
   * @private
   */
  ImplicitTileCoordinates.prototype.isSubtreeRoot = function () {
    return this.level % this.subtreeLevels === 0;
  };

  /**
   * Returns whether this tile is on the last row of tiles in the subtree
   *
   * @returns {Boolean} <code>true</code> if this tile is on the last row of tiles in the subtree
   * @private
   */
  ImplicitTileCoordinates.prototype.isBottomOfSubtree = function () {
    return this.level % this.subtreeLevels === this.subtreeLevels - 1;
  };

  /**
   * Get a dictionary of values for templating into an implicit template URI.
   *
   * @returns {Object} An object suitable for use with {@link Resource#getDerivedResource}
   * @private
   */
  ImplicitTileCoordinates.prototype.getTemplateValues = function () {
    const values = {
      level: this.level,
      x: this.x,
      y: this.y,
    };
    if (this.subdivisionScheme === ImplicitSubdivisionScheme$1.OCTREE) {
      values.z = this.z;
    }

    return values;
  };

  const scratchCoordinatesArray = [0, 0, 0];

  /**
   * Given a level number, morton index, and whether the tileset is an
   * octree/quadtree, compute the (level, x, y, [z]) coordinates
   *
   * @param {ImplicitSubdivisionScheme} subdivisionScheme Whether the coordinates are for a quadtree or octree
   * @param {Number} subtreeLevels The number of distinct levels within the coordinate's subtree
   * @param {Number} level The level of the tree
   * @param {Number} mortonIndex The morton index of the tile.
   * @returns {ImplicitTileCoordinates} The coordinates of the tile with the given Morton index
   * @private
   */
  ImplicitTileCoordinates.fromMortonIndex = function (
    subdivisionScheme,
    subtreeLevels,
    level,
    mortonIndex
  ) {
    let coordinatesArray;
    if (subdivisionScheme === ImplicitSubdivisionScheme$1.OCTREE) {
      coordinatesArray = MortonOrder.decode3D(
        mortonIndex,
        scratchCoordinatesArray
      );
      return new ImplicitTileCoordinates({
        subdivisionScheme: subdivisionScheme,
        subtreeLevels: subtreeLevels,
        level: level,
        x: coordinatesArray[0],
        y: coordinatesArray[1],
        z: coordinatesArray[2],
      });
    }

    coordinatesArray = MortonOrder.decode2D(mortonIndex, scratchCoordinatesArray);
    return new ImplicitTileCoordinates({
      subdivisionScheme: subdivisionScheme,
      subtreeLevels: subtreeLevels,
      level: level,
      x: coordinatesArray[0],
      y: coordinatesArray[1],
    });
  };

  /**
   * Given a tile index and whether the tileset is an octree/quadtree, compute
   * the (level, x, y, [z]) coordinates
   *
   * @param {ImplicitSubdivisionScheme} subdivisionScheme Whether the coordinates are for a quadtree or octree
   * @param {Number} subtreeLevels The number of distinct levels within the coordinate's subtree
   * @param {Number} tileIndex The tile's index
   * @returns {ImplicitTileCoordinates} The coordinates of the tile with the given tile index
   * @private
   */
  ImplicitTileCoordinates.fromTileIndex = function (
    subdivisionScheme,
    subtreeLevels,
    tileIndex
  ) {
    let level;
    let levelOffset;
    let mortonIndex;

    if (subdivisionScheme === ImplicitSubdivisionScheme$1.OCTREE) {
      // Node count up to octree level: (8^L - 1) / (8-1)
      // (8^L - 1) / (8-1) <= X < (8^(L+1) - 1) / (8-1)
      // 8^L <= (7x + 1) < 8^(L+1)
      // L <= log8(7x + 1) < L + 1
      // L = floor(log8(7x + 1))
      // L = floor(log2(7x + 1) / log2(8))
      // L = floor(log2(7x + 1) / 3)
      level = Math.floor(CesiumMath.log2(7 * tileIndex + 1) / 3);
      levelOffset = ((1 << (3 * level)) - 1) / 7;
      mortonIndex = tileIndex - levelOffset;
    } else {
      // Node count up to quadtree level: (4^L - 1) / (4-1)
      // (4^L - 1) / (4-1) <= X < (4^(L+1) - 1) / (4-1)
      // 4^L <= (3x + 1) < 4^(L+1)
      // L <= log4(3x + 1) < L + 1
      // L = floor(log4(3x + 1))
      // L = floor(log2(3x + 1) / log2(4))
      // L = floor(log2(3x + 1) / 2)
      level = Math.floor(CesiumMath.log2(3 * tileIndex + 1) / 2);
      levelOffset = ((1 << (2 * level)) - 1) / 3;
      mortonIndex = tileIndex - levelOffset;
    }

    return ImplicitTileCoordinates.fromMortonIndex(
      subdivisionScheme,
      subtreeLevels,
      level,
      mortonIndex
    );
  };

  /**
   * A {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification|3D Tiles tileset},
   * used for streaming massive heterogeneous 3D geospatial datasets.
   *
   * @alias Cesium3DTileset
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Resource|String|Promise<Resource>|Promise<String>} options.url The url to a tileset JSON file.
   * @param {Boolean} [options.show=true] Determines if the tileset will be shown.
   * @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] A 4x4 transformation matrix that transforms the tileset's root tile.
   * @param {Axis} [options.modelUpAxis=Axis.Y] Which axis is considered up when loading models for tile contents.
   * @param {Axis} [options.modelForwardAxis=Axis.X] Which axis is considered forward when loading models for tile contents.
   * @param {ShadowMode} [options.shadows=ShadowMode.ENABLED] Determines whether the tileset casts or receives shadows from light sources.
   * @param {Number} [options.maximumScreenSpaceError=16] The maximum screen space error used to drive level of detail refinement.
   * @param {Number} [options.maximumMemoryUsage=512] The maximum amount of memory in MB that can be used by the tileset.
   * @param {Boolean} [options.cullWithChildrenBounds=true] Optimization option. Whether to cull tiles using the union of their children bounding volumes.
   * @param {Boolean} [options.cullRequestsWhileMoving=true] Optimization option. Don't request tiles that will likely be unused when they come back because of the camera's movement. This optimization only applies to stationary tilesets.
   * @param {Number} [options.cullRequestsWhileMovingMultiplier=60.0] Optimization option. Multiplier used in culling requests while moving. Larger is more aggressive culling, smaller less aggressive culling.
   * @param {Boolean} [options.preloadWhenHidden=false] Preload tiles when <code>tileset.show</code> is <code>false</code>. Loads tiles as if the tileset is visible but does not render them.
   * @param {Boolean} [options.preloadFlightDestinations=true] Optimization option. Preload tiles at the camera's flight destination while the camera is in flight.
   * @param {Boolean} [options.preferLeaves=false] Optimization option. Prefer loading of leaves first.
   * @param {Boolean} [options.dynamicScreenSpaceError=false] Optimization option. Reduce the screen space error for tiles that are further away from the camera.
   * @param {Number} [options.dynamicScreenSpaceErrorDensity=0.00278] Density used to adjust the dynamic screen space error, similar to fog density.
   * @param {Number} [options.dynamicScreenSpaceErrorFactor=4.0] A factor used to increase the computed dynamic screen space error.
   * @param {Number} [options.dynamicScreenSpaceErrorHeightFalloff=0.25] A ratio of the tileset's height at which the density starts to falloff.
   * @param {Number} [options.progressiveResolutionHeightFraction=0.3] Optimization option. If between (0.0, 0.5], tiles at or above the screen space error for the reduced screen resolution of <code>progressiveResolutionHeightFraction*screenHeight</code> will be prioritized first. This can help get a quick layer of tiles down while full resolution tiles continue to load.
   * @param {Boolean} [options.foveatedScreenSpaceError=true] Optimization option. Prioritize loading tiles in the center of the screen by temporarily raising the screen space error for tiles around the edge of the screen. Screen space error returns to normal once all the tiles in the center of the screen as determined by the {@link Cesium3DTileset#foveatedConeSize} are loaded.
   * @param {Number} [options.foveatedConeSize=0.1] Optimization option. Used when {@link Cesium3DTileset#foveatedScreenSpaceError} is true to control the cone size that determines which tiles are deferred. Tiles that are inside this cone are loaded immediately. Tiles outside the cone are potentially deferred based on how far outside the cone they are and their screen space error. This is controlled by {@link Cesium3DTileset#foveatedInterpolationCallback} and {@link Cesium3DTileset#foveatedMinimumScreenSpaceErrorRelaxation}. Setting this to 0.0 means the cone will be the line formed by the camera position and its view direction. Setting this to 1.0 means the cone encompasses the entire field of view of the camera, disabling the effect.
   * @param {Number} [options.foveatedMinimumScreenSpaceErrorRelaxation=0.0] Optimization option. Used when {@link Cesium3DTileset#foveatedScreenSpaceError} is true to control the starting screen space error relaxation for tiles outside the foveated cone. The screen space error will be raised starting with tileset value up to {@link Cesium3DTileset#maximumScreenSpaceError} based on the provided {@link Cesium3DTileset#foveatedInterpolationCallback}.
   * @param {Cesium3DTileset.foveatedInterpolationCallback} [options.foveatedInterpolationCallback=Math.lerp] Optimization option. Used when {@link Cesium3DTileset#foveatedScreenSpaceError} is true to control how much to raise the screen space error for tiles outside the foveated cone, interpolating between {@link Cesium3DTileset#foveatedMinimumScreenSpaceErrorRelaxation} and {@link Cesium3DTileset#maximumScreenSpaceError}
   * @param {Number} [options.foveatedTimeDelay=0.2] Optimization option. Used when {@link Cesium3DTileset#foveatedScreenSpaceError} is true to control how long in seconds to wait after the camera stops moving before deferred tiles start loading in. This time delay prevents requesting tiles around the edges of the screen when the camera is moving. Setting this to 0.0 will immediately request all tiles in any given view.
   * @param {Boolean} [options.skipLevelOfDetail=false] Optimization option. Determines if level of detail skipping should be applied during the traversal.
   * @param {Number} [options.baseScreenSpaceError=1024] When <code>skipLevelOfDetail</code> is <code>true</code>, the screen space error that must be reached before skipping levels of detail.
   * @param {Number} [options.skipScreenSpaceErrorFactor=16] When <code>skipLevelOfDetail</code> is <code>true</code>, a multiplier defining the minimum screen space error to skip. Used in conjunction with <code>skipLevels</code> to determine which tiles to load.
   * @param {Number} [options.skipLevels=1] When <code>skipLevelOfDetail</code> is <code>true</code>, a constant defining the minimum number of levels to skip when loading tiles. When it is 0, no levels are skipped. Used in conjunction with <code>skipScreenSpaceErrorFactor</code> to determine which tiles to load.
   * @param {Boolean} [options.immediatelyLoadDesiredLevelOfDetail=false] When <code>skipLevelOfDetail</code> is <code>true</code>, only tiles that meet the maximum screen space error will ever be downloaded. Skipping factors are ignored and just the desired tiles are loaded.
   * @param {Boolean} [options.loadSiblings=false] When <code>skipLevelOfDetail</code> is <code>true</code>, determines whether siblings of visible tiles are always downloaded during traversal.
   * @param {ClippingPlaneCollection} [options.clippingPlanes] The {@link ClippingPlaneCollection} used to selectively disable rendering the tileset.
   * @param {ClassificationType} [options.classificationType] Determines whether terrain, 3D Tiles or both will be classified by this tileset. See {@link Cesium3DTileset#classificationType} for details about restrictions and limitations.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid determining the size and shape of the globe.
   * @param {Object} [options.pointCloudShading] Options for constructing a {@link PointCloudShading} object to control point attenuation based on geometric error and lighting.
   * @param {Cartesian3} [options.lightColor] The light color when shading models. When <code>undefined</code> the scene's light color is used instead.
   * @param {ImageBasedLighting} [options.imageBasedLighting] The properties for managing image-based lighting for this tileset.
   * @param {Boolean} [options.backFaceCulling=true] Whether to cull back-facing geometry. When true, back face culling is determined by the glTF material's doubleSided property; when false, back face culling is disabled.
   * @param {Boolean} [options.showOutline=true] Whether to display the outline for models using the {@link https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/CESIUM_primitive_outline|CESIUM_primitive_outline} extension. When true, outlines are displayed. When false, outlines are not displayed.
   * @param {Boolean} [options.vectorClassificationOnly=false] Indicates that only the tileset's vector tiles should be used for classification.
   * @param {Boolean} [options.vectorKeepDecodedPositions=false] Whether vector tiles should keep decoded positions in memory. This is used with {@link Cesium3DTileFeature.getPolylinePositions}.
   * @param {String|Number} [options.featureIdLabel="featureId_0"] Label of the feature ID set to use for picking and styling. For EXT_mesh_features, this is the feature ID's label property, or "featureId_N" (where N is the index in the featureIds array) when not specified. EXT_feature_metadata did not have a label field, so such feature ID sets are always labeled "featureId_N" where N is the index in the list of all feature Ids, where feature ID attributes are listed before feature ID textures. If featureIdLabel is an integer N, it is converted to the string "featureId_N" automatically. If both per-primitive and per-instance feature IDs are present, the instance feature IDs take priority.
   * @param {String|Number} [options.instanceFeatureIdLabel="instanceFeatureId_0"] Label of the instance feature ID set used for picking and styling. If instanceFeatureIdLabel is set to an integer N, it is converted to the string "instanceFeatureId_N" automatically. If both per-primitive and per-instance feature IDs are present, the instance feature IDs take priority.
   * @param {Boolean} [options.showCreditsOnScreen=false] Whether to display the credits of this tileset on screen.
   * @param {SplitDirection} [options.splitDirection=SplitDirection.NONE] The {@link SplitDirection} split to apply to this tileset.
   * @param {Boolean} [options.projectTo2D=false] Whether to accurately project the tileset to 2D. If this is true, the tileset will be projected accurately to 2D, but it will use more memory to do so. If this is false, the tileset will use less memory and will still render in 2D / CV mode, but its projected positions may be inaccurate. This cannot be set after the tileset has loaded.
   * @param {String} [options.debugHeatmapTilePropertyName] The tile variable to colorize as a heatmap. All rendered tiles will be colorized relative to each other's specified variable value.
   * @param {Boolean} [options.debugFreezeFrame=false] For debugging only. Determines if only the tiles from last frame should be used for rendering.
   * @param {Boolean} [options.debugColorizeTiles=false] For debugging only. When true, assigns a random color to each tile.
   * @param {Boolean} [options.enableDebugWireframe] For debugging only. This must be true for debugWireframe to work for ModelExperimental in WebGL1. This cannot be set after the tileset has loaded.
   * @param {Boolean} [options.debugWireframe=false] For debugging only. When true, render's each tile's content as a wireframe.
   * @param {Boolean} [options.debugShowBoundingVolume=false] For debugging only. When true, renders the bounding volume for each tile.
   * @param {Boolean} [options.debugShowContentBoundingVolume=false] For debugging only. When true, renders the bounding volume for each tile's content.
   * @param {Boolean} [options.debugShowViewerRequestVolume=false] For debugging only. When true, renders the viewer request volume for each tile.
   * @param {Boolean} [options.debugShowGeometricError=false] For debugging only. When true, draws labels to indicate the geometric error of each tile.
   * @param {Boolean} [options.debugShowRenderingStatistics=false] For debugging only. When true, draws labels to indicate the number of commands, points, triangles and features for each tile.
   * @param {Boolean} [options.debugShowMemoryUsage=false] For debugging only. When true, draws labels to indicate the texture and geometry memory in megabytes used by each tile.
   * @param {Boolean} [options.debugShowUrl=false] For debugging only. When true, draws labels to indicate the url of each tile.
   *
   * @exception {DeveloperError} The tileset must be 3D Tiles version 0.0 or 1.0.
   *
   * @example
   * const tileset = scene.primitives.add(new Cesium.Cesium3DTileset({
   *      url : 'http://localhost:8002/tilesets/Seattle/tileset.json'
   * }));
   *
   * @example
   * // Common setting for the skipLevelOfDetail optimization
   * const tileset = scene.primitives.add(new Cesium.Cesium3DTileset({
   *      url : 'http://localhost:8002/tilesets/Seattle/tileset.json',
   *      skipLevelOfDetail : true,
   *      baseScreenSpaceError : 1024,
   *      skipScreenSpaceErrorFactor : 16,
   *      skipLevels : 1,
   *      immediatelyLoadDesiredLevelOfDetail : false,
   *      loadSiblings : false,
   *      cullWithChildrenBounds : true
   * }));
   *
   * @example
   * // Common settings for the dynamicScreenSpaceError optimization
   * const tileset = scene.primitives.add(new Cesium.Cesium3DTileset({
   *      url : 'http://localhost:8002/tilesets/Seattle/tileset.json',
   *      dynamicScreenSpaceError : true,
   *      dynamicScreenSpaceErrorDensity : 0.00278,
   *      dynamicScreenSpaceErrorFactor : 4.0,
   *      dynamicScreenSpaceErrorHeightFalloff : 0.25
   * }));
   *
   * @see {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification|3D Tiles specification}
   */
  function Cesium3DTileset(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    Check.defined("options.url", options.url);
    //>>includeEnd('debug');

    this._url = undefined;
    this._basePath = undefined;
    this._root = undefined;
    this._resource = undefined;
    this._asset = undefined; // Metadata for the entire tileset
    this._properties = undefined; // Metadata for per-model/point/etc properties
    this._geometricError = undefined; // Geometric error when the tree is not rendered at all
    this._extensionsUsed = undefined;
    this._extensions = undefined;
    this._modelUpAxis = undefined;
    this._modelForwardAxis = undefined;
    this._cache = new Cesium3DTilesetCache();
    this._processingQueue = [];
    this._selectedTiles = [];
    this._emptyTiles = [];
    this._requestedTiles = [];
    this._selectedTilesToStyle = [];
    this._loadTimestamp = undefined;
    this._timeSinceLoad = 0.0;
    this._updatedVisibilityFrame = 0;
    this._updatedModelMatrixFrame = 0;
    this._modelMatrixChanged = false;
    this._previousModelMatrix = undefined;
    this._extras = undefined;
    this._credits = undefined;

    this._showCreditsOnScreen = defaultValue(options.showCreditsOnScreen, false);

    this._cullWithChildrenBounds = defaultValue(
      options.cullWithChildrenBounds,
      true
    );
    this._allTilesAdditive = true;

    this._hasMixedContent = false;

    this._stencilClearCommand = undefined;
    this._backfaceCommands = new ManagedArray();

    this._maximumScreenSpaceError = defaultValue(
      options.maximumScreenSpaceError,
      16
    );
    this._maximumMemoryUsage = defaultValue(options.maximumMemoryUsage, 512);

    this._styleEngine = new Cesium3DTileStyleEngine();

    this._modelMatrix = defined(options.modelMatrix)
      ? Matrix4.clone(options.modelMatrix)
      : Matrix4.clone(Matrix4.IDENTITY);

    this._statistics = new Cesium3DTilesetStatistics();
    this._statisticsLast = new Cesium3DTilesetStatistics();
    this._statisticsPerPass = new Array(Cesium3DTilePass$1.NUMBER_OF_PASSES);

    for (let i = 0; i < Cesium3DTilePass$1.NUMBER_OF_PASSES; ++i) {
      this._statisticsPerPass[i] = new Cesium3DTilesetStatistics();
    }

    this._requestedTilesInFlight = [];

    this._maximumPriority = {
      foveatedFactor: -Number.MAX_VALUE,
      depth: -Number.MAX_VALUE,
      distance: -Number.MAX_VALUE,
      reverseScreenSpaceError: -Number.MAX_VALUE,
    };
    this._minimumPriority = {
      foveatedFactor: Number.MAX_VALUE,
      depth: Number.MAX_VALUE,
      distance: Number.MAX_VALUE,
      reverseScreenSpaceError: Number.MAX_VALUE,
    };
    this._heatmap = new Cesium3DTilesetHeatmap(
      options.debugHeatmapTilePropertyName
    );

    /**
     * Optimization option. Don't request tiles that will likely be unused when they come back because of the camera's movement. This optimization only applies to stationary tilesets.
     *
     * @type {Boolean}
     * @default true
     */
    this.cullRequestsWhileMoving = defaultValue(
      options.cullRequestsWhileMoving,
      true
    );
    this._cullRequestsWhileMoving = false;

    /**
     * Optimization option. Multiplier used in culling requests while moving. Larger is more aggressive culling, smaller less aggressive culling.
     *
     * @type {Number}
     * @default 60.0
     */
    this.cullRequestsWhileMovingMultiplier = defaultValue(
      options.cullRequestsWhileMovingMultiplier,
      60.0
    );

    /**
     * Optimization option. If between (0.0, 0.5], tiles at or above the screen space error for the reduced screen resolution of <code>progressiveResolutionHeightFraction*screenHeight</code> will be prioritized first. This can help get a quick layer of tiles down while full resolution tiles continue to load.
     *
     * @type {Number}
     * @default 0.3
     */
    this.progressiveResolutionHeightFraction = CesiumMath.clamp(
      defaultValue(options.progressiveResolutionHeightFraction, 0.3),
      0.0,
      0.5
    );

    /**
     * Optimization option. Prefer loading of leaves first.
     *
     * @type {Boolean}
     * @default false
     */
    this.preferLeaves = defaultValue(options.preferLeaves, false);

    this._tilesLoaded = false;
    this._initialTilesLoaded = false;

    this._tileDebugLabels = undefined;

    this._classificationType = options.classificationType;

    this._ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);

    this._initialClippingPlanesOriginMatrix = Matrix4.IDENTITY; // Computed from the tileset JSON.
    this._clippingPlanesOriginMatrix = undefined; // Combines the above with any run-time transforms.
    this._clippingPlanesOriginMatrixDirty = true;

    this._vectorClassificationOnly = defaultValue(
      options.vectorClassificationOnly,
      false
    );

    this._vectorKeepDecodedPositions = defaultValue(
      options.vectorKeepDecodedPositions,
      false
    );

    /**
     * Preload tiles when <code>tileset.show</code> is <code>false</code>. Loads tiles as if the tileset is visible but does not render them.
     *
     * @type {Boolean}
     * @default false
     */
    this.preloadWhenHidden = defaultValue(options.preloadWhenHidden, false);

    /**
     * Optimization option. Fetch tiles at the camera's flight destination while the camera is in flight.
     *
     * @type {Boolean}
     * @default true
     */
    this.preloadFlightDestinations = defaultValue(
      options.preloadFlightDestinations,
      true
    );
    this._pass = undefined; // Cesium3DTilePass

    /**
     * Optimization option. Whether the tileset should refine based on a dynamic screen space error. Tiles that are further
     * away will be rendered with lower detail than closer tiles. This improves performance by rendering fewer
     * tiles and making less requests, but may result in a slight drop in visual quality for tiles in the distance.
     * The algorithm is biased towards "street views" where the camera is close to the ground plane of the tileset and looking
     * at the horizon. In addition results are more accurate for tightly fitting bounding volumes like box and region.
     *
     * @type {Boolean}
     * @default false
     */
    this.dynamicScreenSpaceError = defaultValue(
      options.dynamicScreenSpaceError,
      false
    );

    /**
     * Optimization option. Prioritize loading tiles in the center of the screen by temporarily raising the
     * screen space error for tiles around the edge of the screen. Screen space error returns to normal once all
     * the tiles in the center of the screen as determined by the {@link Cesium3DTileset#foveatedConeSize} are loaded.
     *
     * @type {Boolean}
     * @default true
     */
    this.foveatedScreenSpaceError = defaultValue(
      options.foveatedScreenSpaceError,
      true
    );
    this._foveatedConeSize = defaultValue(options.foveatedConeSize, 0.1);
    this._foveatedMinimumScreenSpaceErrorRelaxation = defaultValue(
      options.foveatedMinimumScreenSpaceErrorRelaxation,
      0.0
    );

    /**
     * Gets or sets a callback to control how much to raise the screen space error for tiles outside the foveated cone,
     * interpolating between {@link Cesium3DTileset#foveatedMinimumScreenSpaceErrorRelaxation} and {@link Cesium3DTileset#maximumScreenSpaceError}.
     *
     * @type {Cesium3DTileset.foveatedInterpolationCallback}
     */
    this.foveatedInterpolationCallback = defaultValue(
      options.foveatedInterpolationCallback,
      CesiumMath.lerp
    );

    /**
     * Optimization option. Used when {@link Cesium3DTileset#foveatedScreenSpaceError} is true to control
     * how long in seconds to wait after the camera stops moving before deferred tiles start loading in.
     * This time delay prevents requesting tiles around the edges of the screen when the camera is moving.
     * Setting this to 0.0 will immediately request all tiles in any given view.
     *
     * @type {Number}
     * @default 0.2
     */
    this.foveatedTimeDelay = defaultValue(options.foveatedTimeDelay, 0.2);

    /**
     * A scalar that determines the density used to adjust the dynamic screen space error, similar to {@link Fog}. Increasing this
     * value has the effect of increasing the maximum screen space error for all tiles, but in a non-linear fashion.
     * The error starts at 0.0 and increases exponentially until a midpoint is reached, and then approaches 1.0 asymptotically.
     * This has the effect of keeping high detail in the closer tiles and lower detail in the further tiles, with all tiles
     * beyond a certain distance all roughly having an error of 1.0.
     * <p>
     * The dynamic error is in the range [0.0, 1.0) and is multiplied by <code>dynamicScreenSpaceErrorFactor</code> to produce the
     * final dynamic error. This dynamic error is then subtracted from the tile's actual screen space error.
     * </p>
     * <p>
     * Increasing <code>dynamicScreenSpaceErrorDensity</code> has the effect of moving the error midpoint closer to the camera.
     * It is analogous to moving fog closer to the camera.
     * </p>
     *
     * @type {Number}
     * @default 0.00278
     */
    this.dynamicScreenSpaceErrorDensity = 0.00278;

    /**
     * A factor used to increase the screen space error of tiles for dynamic screen space error. As this value increases less tiles
     * are requested for rendering and tiles in the distance will have lower detail. If set to zero, the feature will be disabled.
     *
     * @type {Number}
     * @default 4.0
     */
    this.dynamicScreenSpaceErrorFactor = 4.0;

    /**
     * A ratio of the tileset's height at which the density starts to falloff. If the camera is below this height the
     * full computed density is applied, otherwise the density falls off. This has the effect of higher density at
     * street level views.
     * <p>
     * Valid values are between 0.0 and 1.0.
     * </p>
     *
     * @type {Number}
     * @default 0.25
     */
    this.dynamicScreenSpaceErrorHeightFalloff = 0.25;

    this._dynamicScreenSpaceErrorComputedDensity = 0.0; // Updated based on the camera position and direction

    /**
     * Determines whether the tileset casts or receives shadows from light sources.
     * <p>
     * Enabling shadows has a performance impact. A tileset that casts shadows must be rendered twice, once from the camera and again from the light's point of view.
     * </p>
     * <p>
     * Shadows are rendered only when {@link Viewer#shadows} is <code>true</code>.
     * </p>
     *
     * @type {ShadowMode}
     * @default ShadowMode.ENABLED
     */
    this.shadows = defaultValue(options.shadows, ShadowMode$1.ENABLED);

    /**
     * Determines if the tileset will be shown.
     *
     * @type {Boolean}
     * @default true
     */
    this.show = defaultValue(options.show, true);

    /**
     * Defines how per-feature colors set from the Cesium API or declarative styling blend with the source colors from
     * the original feature, e.g. glTF material or per-point color in the tile.
     *
     * @type {Cesium3DTileColorBlendMode}
     * @default Cesium3DTileColorBlendMode.HIGHLIGHT
     */
    this.colorBlendMode = Cesium3DTileColorBlendMode$1.HIGHLIGHT;

    /**
     * Defines the value used to linearly interpolate between the source color and feature color when the {@link Cesium3DTileset#colorBlendMode} is <code>MIX</code>.
     * A value of 0.0 results in the source color while a value of 1.0 results in the feature color, with any value in-between
     * resulting in a mix of the source color and feature color.
     *
     * @type {Number}
     * @default 0.5
     */
    this.colorBlendAmount = 0.5;

    this._pointCloudShading = new PointCloudShading(options.pointCloudShading);
    this._pointCloudEyeDomeLighting = new PointCloudEyeDomeLighting();

    /**
     * The event fired to indicate progress of loading new tiles.  This event is fired when a new tile
     * is requested, when a requested tile is finished downloading, and when a downloaded tile has been
     * processed and is ready to render.
     * <p>
     * The number of pending tile requests, <code>numberOfPendingRequests</code>, and number of tiles
     * processing, <code>numberOfTilesProcessing</code> are passed to the event listener.
     * </p>
     * <p>
     * This event is fired at the end of the frame after the scene is rendered.
     * </p>
     *
     * @type {Event}
     * @default new Event()
     *
     * @example
     * tileset.loadProgress.addEventListener(function(numberOfPendingRequests, numberOfTilesProcessing) {
     *     if ((numberOfPendingRequests === 0) && (numberOfTilesProcessing === 0)) {
     *         console.log('Stopped loading');
     *         return;
     *     }
     *
     *     console.log(`Loading: requests: ${numberOfPendingRequests}, processing: ${numberOfTilesProcessing}`);
     * });
     */
    this.loadProgress = new Event();

    /**
     * The event fired to indicate that all tiles that meet the screen space error this frame are loaded. The tileset
     * is completely loaded for this view.
     * <p>
     * This event is fired at the end of the frame after the scene is rendered.
     * </p>
     *
     * @type {Event}
     * @default new Event()
     *
     * @example
     * tileset.allTilesLoaded.addEventListener(function() {
     *     console.log('All tiles are loaded');
     * });
     *
     * @see Cesium3DTileset#tilesLoaded
     */
    this.allTilesLoaded = new Event();

    /**
     * The event fired to indicate that all tiles that meet the screen space error this frame are loaded. This event
     * is fired once when all tiles in the initial view are loaded.
     * <p>
     * This event is fired at the end of the frame after the scene is rendered.
     * </p>
     *
     * @type {Event}
     * @default new Event()
     *
     * @example
     * tileset.initialTilesLoaded.addEventListener(function() {
     *     console.log('Initial tiles are loaded');
     * });
     *
     * @see Cesium3DTileset#allTilesLoaded
     */
    this.initialTilesLoaded = new Event();

    /**
     * The event fired to indicate that a tile's content was loaded.
     * <p>
     * The loaded {@link Cesium3DTile} is passed to the event listener.
     * </p>
     * <p>
     * This event is fired during the tileset traversal while the frame is being rendered
     * so that updates to the tile take effect in the same frame.  Do not create or modify
     * Cesium entities or primitives during the event listener.
     * </p>
     *
     * @type {Event}
     * @default new Event()
     *
     * @example
     * tileset.tileLoad.addEventListener(function(tile) {
     *     console.log('A tile was loaded.');
     * });
     */
    this.tileLoad = new Event();

    /**
     * The event fired to indicate that a tile's content was unloaded.
     * <p>
     * The unloaded {@link Cesium3DTile} is passed to the event listener.
     * </p>
     * <p>
     * This event is fired immediately before the tile's content is unloaded while the frame is being
     * rendered so that the event listener has access to the tile's content.  Do not create
     * or modify Cesium entities or primitives during the event listener.
     * </p>
     *
     * @type {Event}
     * @default new Event()
     *
     * @example
     * tileset.tileUnload.addEventListener(function(tile) {
     *     console.log('A tile was unloaded from the cache.');
     * });
     *
     * @see Cesium3DTileset#maximumMemoryUsage
     * @see Cesium3DTileset#trimLoadedTiles
     */
    this.tileUnload = new Event();

    /**
     * The event fired to indicate that a tile's content failed to load.
     * <p>
     * If there are no event listeners, error messages will be logged to the console.
     * </p>
     * <p>
     * The error object passed to the listener contains two properties:
     * <ul>
     * <li><code>url</code>: the url of the failed tile.</li>
     * <li><code>message</code>: the error message.</li>
     * </ul>
     * <p>
     * If multiple contents are present, this event is raised once per inner content with errors.
     * </p>
     *
     * @type {Event}
     * @default new Event()
     *
     * @example
     * tileset.tileFailed.addEventListener(function(error) {
     *     console.log(`An error occurred loading tile: ${error.url}`);
     *     console.log(`Error: ${error.message}`);
     * });
     */
    this.tileFailed = new Event();

    /**
     * This event fires once for each visible tile in a frame.  This can be used to manually
     * style a tileset.
     * <p>
     * The visible {@link Cesium3DTile} is passed to the event listener.
     * </p>
     * <p>
     * This event is fired during the tileset traversal while the frame is being rendered
     * so that updates to the tile take effect in the same frame.  Do not create or modify
     * Cesium entities or primitives during the event listener.
     * </p>
     *
     * @type {Event}
     * @default new Event()
     *
     * @example
     * tileset.tileVisible.addEventListener(function(tile) {
     *     if (tile.content instanceof Cesium.Batched3DModel3DTileContent) {
     *         console.log('A Batched 3D Model tile is visible.');
     *     }
     * });
     *
     * @example
     * // Apply a red style and then manually set random colors for every other feature when the tile becomes visible.
     * tileset.style = new Cesium.Cesium3DTileStyle({
     *     color : 'color("red")'
     * });
     * tileset.tileVisible.addEventListener(function(tile) {
     *     const content = tile.content;
     *     const featuresLength = content.featuresLength;
     *     for (let i = 0; i < featuresLength; i+=2) {
     *         content.getFeature(i).color = Cesium.Color.fromRandom();
     *     }
     * });
     */
    this.tileVisible = new Event();

    /**
     * Optimization option. Determines if level of detail skipping should be applied during the traversal.
     * <p>
     * The common strategy for replacement-refinement traversal is to store all levels of the tree in memory and require
     * all children to be loaded before the parent can refine. With this optimization levels of the tree can be skipped
     * entirely and children can be rendered alongside their parents. The tileset requires significantly less memory when
     * using this optimization.
     * </p>
     *
     * @type {Boolean}
     * @default false
     */
    this.skipLevelOfDetail = defaultValue(options.skipLevelOfDetail, false);
    this._skipLevelOfDetail = this.skipLevelOfDetail;
    this._disableSkipLevelOfDetail = false;

    /**
     * The screen space error that must be reached before skipping levels of detail.
     * <p>
     * Only used when {@link Cesium3DTileset#skipLevelOfDetail} is <code>true</code>.
     * </p>
     *
     * @type {Number}
     * @default 1024
     */
    this.baseScreenSpaceError = defaultValue(options.baseScreenSpaceError, 1024);

    /**
     * Multiplier defining the minimum screen space error to skip.
     * For example, if a tile has screen space error of 100, no tiles will be loaded unless they
     * are leaves or have a screen space error <code><= 100 / skipScreenSpaceErrorFactor</code>.
     * <p>
     * Only used when {@link Cesium3DTileset#skipLevelOfDetail} is <code>true</code>.
     * </p>
     *
     * @type {Number}
     * @default 16
     */
    this.skipScreenSpaceErrorFactor = defaultValue(
      options.skipScreenSpaceErrorFactor,
      16
    );

    /**
     * Constant defining the minimum number of levels to skip when loading tiles. When it is 0, no levels are skipped.
     * For example, if a tile is level 1, no tiles will be loaded unless they are at level greater than 2.
     * <p>
     * Only used when {@link Cesium3DTileset#skipLevelOfDetail} is <code>true</code>.
     * </p>
     *
     * @type {Number}
     * @default 1
     */
    this.skipLevels = defaultValue(options.skipLevels, 1);

    /**
     * When true, only tiles that meet the maximum screen space error will ever be downloaded.
     * Skipping factors are ignored and just the desired tiles are loaded.
     * <p>
     * Only used when {@link Cesium3DTileset#skipLevelOfDetail} is <code>true</code>.
     * </p>
     *
     * @type {Boolean}
     * @default false
     */
    this.immediatelyLoadDesiredLevelOfDetail = defaultValue(
      options.immediatelyLoadDesiredLevelOfDetail,
      false
    );

    /**
     * Determines whether siblings of visible tiles are always downloaded during traversal.
     * This may be useful for ensuring that tiles are already available when the viewer turns left/right.
     * <p>
     * Only used when {@link Cesium3DTileset#skipLevelOfDetail} is <code>true</code>.
     * </p>
     *
     * @type {Boolean}
     * @default false
     */
    this.loadSiblings = defaultValue(options.loadSiblings, false);

    this._clippingPlanes = undefined;
    this.clippingPlanes = options.clippingPlanes;

    if (defined(options.imageBasedLighting)) {
      this._imageBasedLighting = options.imageBasedLighting;
      this._shouldDestroyImageBasedLighting = false;
    } else {
      this._imageBasedLighting = new ImageBasedLighting();
      this._shouldDestroyImageBasedLighting = true;
    }

    /**
     * The light color when shading models. When <code>undefined</code> the scene's light color is used instead.
     * <p>
     * For example, disabling additional light sources by setting
     * <code>tileset.imageBasedLighting.imageBasedLightingFactor = new Cartesian2(0.0, 0.0)</code>
     * will make the tileset much darker. Here, increasing the intensity of the light source will make the tileset brighter.
     * </p>
     *
     * @type {Cartesian3}
     * @default undefined
     */
    this.lightColor = options.lightColor;

    /**
     * Whether to cull back-facing geometry. When true, back face culling is determined
     * by the glTF material's doubleSided property; when false, back face culling is disabled.
     *
     * @type {Boolean}
     * @default true
     */
    this.backFaceCulling = defaultValue(options.backFaceCulling, true);

    /**
     * Whether to display the outline for models using the
     * {@link https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/CESIUM_primitive_outline|CESIUM_primitive_outline} extension.
     * When true, outlines are displayed. When false, outlines are not displayed.
     *
     * @type {Boolean}
     * @readonly
     *
     * @default true
     */
    this.showOutline = defaultValue(options.showOutline, true);

    /**
     * The {@link SplitDirection} to apply to this tileset.
     *
     * @type {SplitDirection}
     * @default {@link SplitDirection.NONE}
     */
    this.splitDirection = defaultValue(
      options.splitDirection,
      SplitDirection$1.NONE
    );

    this._projectTo2D = defaultValue(options.projectTo2D, false);

    /**
     * This property is for debugging only; it is not optimized for production use.
     * <p>
     * Determines if only the tiles from last frame should be used for rendering.  This
     * effectively "freezes" the tileset to the previous frame so it is possible to zoom
     * out and see what was rendered.
     * </p>
     *
     * @type {Boolean}
     * @default false
     */
    this.debugFreezeFrame = defaultValue(options.debugFreezeFrame, false);

    /**
     * This property is for debugging only; it is not optimized for production use.
     * <p>
     * When true, assigns a random color to each tile.  This is useful for visualizing
     * what features belong to what tiles, especially with additive refinement where features
     * from parent tiles may be interleaved with features from child tiles.
     * </p>
     *
     * @type {Boolean}
     * @default false
     */
    this.debugColorizeTiles = defaultValue(options.debugColorizeTiles, false);

    this._enableDebugWireframe = defaultValue(
      options.enableDebugWireframe,
      false
    );

    /**
     * This property is for debugging only; it is not optimized for production use.
     * <p>
     * When true, renders each tile's content as a wireframe.
     * </p>
     *
     * @type {Boolean}
     * @default false
     */
    this.debugWireframe = defaultValue(options.debugWireframe, false);

    /**
     * This property is for debugging only; it is not optimized for production use.
     * <p>
     * When true, renders the bounding volume for each visible tile.  The bounding volume is
     * white if the tile has a content bounding volume or is empty; otherwise, it is red.  Tiles that don't meet the
     * screen space error and are still refining to their descendants are yellow.
     * </p>
     *
     * @type {Boolean}
     * @default false
     */
    this.debugShowBoundingVolume = defaultValue(
      options.debugShowBoundingVolume,
      false
    );

    /**
     * This property is for debugging only; it is not optimized for production use.
     * <p>
     * When true, renders the bounding volume for each visible tile's content. The bounding volume is
     * blue if the tile has a content bounding volume; otherwise it is red.
     * </p>
     *
     * @type {Boolean}
     * @default false
     */
    this.debugShowContentBoundingVolume = defaultValue(
      options.debugShowContentBoundingVolume,
      false
    );

    /**
     * This property is for debugging only; it is not optimized for production use.
     * <p>
     * When true, renders the viewer request volume for each tile.
     * </p>
     *
     * @type {Boolean}
     * @default false
     */
    this.debugShowViewerRequestVolume = defaultValue(
      options.debugShowViewerRequestVolume,
      false
    );

    this._tileDebugLabels = undefined;
    this.debugPickedTileLabelOnly = false;
    this.debugPickedTile = undefined;
    this.debugPickPosition = undefined;

    /**
     * This property is for debugging only; it is not optimized for production use.
     * <p>
     * When true, draws labels to indicate the geometric error of each tile.
     * </p>
     *
     * @type {Boolean}
     * @default false
     */
    this.debugShowGeometricError = defaultValue(
      options.debugShowGeometricError,
      false
    );

    /**
     * This property is for debugging only; it is not optimized for production use.
     * <p>
     * When true, draws labels to indicate the number of commands, points, triangles and features of each tile.
     * </p>
     *
     * @type {Boolean}
     * @default false
     */
    this.debugShowRenderingStatistics = defaultValue(
      options.debugShowRenderingStatistics,
      false
    );

    /**
     * This property is for debugging only; it is not optimized for production use.
     * <p>
     * When true, draws labels to indicate the geometry and texture memory usage of each tile.
     * </p>
     *
     * @type {Boolean}
     * @default false
     */
    this.debugShowMemoryUsage = defaultValue(options.debugShowMemoryUsage, false);

    /**
     * This property is for debugging only; it is not optimized for production use.
     * <p>
     * When true, draws labels to indicate the url of each tile.
     * </p>
     *
     * @type {Boolean}
     * @default false
     */
    this.debugShowUrl = defaultValue(options.debugShowUrl, false);

    /**
     * Function for examining vector lines as they are being streamed.
     *
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     *
     * @type {Function}
     */
    this.examineVectorLinesFunction = undefined;

    // this is the underlying Cesium3DTileMetadata object, whether it came from
    // the 3DTILES_metadata extension or a 3D Tiles 1.1 tileset JSON. Getters
    // like tileset.metadata and tileset.schema will delegate to this object.
    this._metadataExtension = undefined;

    this._customShader = options.customShader;

    /**
     * If true, {@link ModelExperimental} will be used instead of {@link Model}
     * for each tile with a glTF or 3D Tiles 1.0 content (where applicable).
     * <p>
     * The value defaults to {@link ExperimentalFeatures.enableModelExperimental}.
     * </p>
     *
     * @memberof Cesium3DTileset.prototype
     * @type {Boolean}
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     */
    this.enableModelExperimental = defaultValue(
      options.enableModelExperimental,
      ExperimentalFeatures.enableModelExperimental
    );

    let featureIdLabel = defaultValue(options.featureIdLabel, "featureId_0");
    if (typeof featureIdLabel === "number") {
      featureIdLabel = `featureId_${featureIdLabel}`;
    }
    this._featureIdLabel = featureIdLabel;

    let instanceFeatureIdLabel = defaultValue(
      options.instanceFeatureIdLabel,
      "instanceFeatureId_0"
    );
    if (typeof instanceFeatureIdLabel === "number") {
      instanceFeatureIdLabel = `instanceFeatureId_${instanceFeatureIdLabel}`;
    }
    this._instanceFeatureIdLabel = instanceFeatureIdLabel;

    this._schemaLoader = undefined;

    const that = this;
    let resource;
    this._readyPromise = Promise.resolve(options.url)
      .then(function (url) {
        let basePath;
        resource = Resource.createIfNeeded(url);
        that._resource = resource;

        // ion resources have a credits property we can use for additional attribution.
        that._credits = resource.credits;

        if (resource.extension === "json") {
          basePath = resource.getBaseUri(true);
        } else if (resource.isDataUri) {
          basePath = "";
        }

        that._url = resource.url;
        that._basePath = basePath;

        return Cesium3DTileset.loadJson(resource);
      })
      .then(function (tilesetJson) {
        if (that.isDestroyed()) {
          return;
        }

        // This needs to be called before loadTileset() so tile metadata
        // can be initialized synchronously in the Cesium3DTile constructor
        return processMetadataExtension(that, tilesetJson);
      })
      .then(function (tilesetJson) {
        if (that.isDestroyed()) {
          return;
        }

        that._root = that.loadTileset(resource, tilesetJson);

        // Handle legacy gltfUpAxis option
        const gltfUpAxis = defined(tilesetJson.asset.gltfUpAxis)
          ? Axis$1.fromName(tilesetJson.asset.gltfUpAxis)
          : Axis$1.Y;
        const modelUpAxis = defaultValue(options.modelUpAxis, gltfUpAxis);
        const modelForwardAxis = defaultValue(options.modelForwardAxis, Axis$1.X);

        const asset = tilesetJson.asset;
        that._asset = asset;
        that._properties = tilesetJson.properties;
        that._geometricError = tilesetJson.geometricError;
        that._extensionsUsed = tilesetJson.extensionsUsed;
        that._extensions = tilesetJson.extensions;
        that._modelUpAxis = modelUpAxis;
        that._modelForwardAxis = modelForwardAxis;
        that._extras = tilesetJson.extras;

        const extras = asset.extras;
        if (
          defined(extras) &&
          defined(extras.cesium) &&
          defined(extras.cesium.credits)
        ) {
          const extraCredits = extras.cesium.credits;
          let credits = that._credits;
          if (!defined(credits)) {
            credits = [];
            that._credits = credits;
          }
          for (let i = 0; i < extraCredits.length; ++i) {
            const credit = extraCredits[i];
            credits.push(new Credit(credit.html, that._showCreditsOnScreen));
          }
        }

        // Save the original, untransformed bounding volume position so we can apply
        // the tile transform and model matrix at run time
        const boundingVolume = that._root.createBoundingVolume(
          tilesetJson.root.boundingVolume,
          Matrix4.IDENTITY
        );
        const clippingPlanesOrigin = boundingVolume.boundingSphere.center;
        // If this origin is above the surface of the earth
        // we want to apply an ENU orientation as our best guess of orientation.
        // Otherwise, we assume it gets its position/orientation completely from the
        // root tile transform and the tileset's model matrix
        const originCartographic = that._ellipsoid.cartesianToCartographic(
          clippingPlanesOrigin
        );
        if (
          defined(originCartographic) &&
          originCartographic.height >
            ApproximateTerrainHeights._defaultMinTerrainHeight
        ) {
          that._initialClippingPlanesOriginMatrix = Transforms.eastNorthUpToFixedFrame(
            clippingPlanesOrigin
          );
        }
        that._clippingPlanesOriginMatrix = Matrix4.clone(
          that._initialClippingPlanesOriginMatrix
        );

        return that;
      });
  }

  Object.defineProperties(Cesium3DTileset.prototype, {
    /**
     * NOTE: This getter exists so that `Picking.js` can differentiate between
     *       PrimitiveCollection and Cesium3DTileset objects without inflating
     *       the size of the module via `instanceof Cesium3DTileset`
     * @private
     */
    isCesium3DTileset: {
      get: function () {
        return true;
      },
    },

    /**
     * Gets the tileset's asset object property, which contains metadata about the tileset.
     * <p>
     * See the {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification#reference-asset|asset schema reference}
     * in the 3D Tiles spec for the full set of properties.
     * </p>
     *
     * @memberof Cesium3DTileset.prototype
     *
     * @type {Object}
     * @readonly
     *
     * @exception {DeveloperError} The tileset is not loaded.  Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true.
     */
    asset: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this.ready) {
          throw new DeveloperError(
            "The tileset is not loaded.  Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._asset;
      },
    },

    /**
     * Gets the tileset's extensions object property.
     *
     * @memberof Cesium3DTileset.prototype
     *
     * @type {Object}
     * @readonly
     *
     * @exception {DeveloperError} The tileset is not loaded.  Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true.
     */
    extensions: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this.ready) {
          throw new DeveloperError(
            "The tileset is not loaded.  Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._extensions;
      },
    },

    /**
     * The {@link ClippingPlaneCollection} used to selectively disable rendering the tileset.
     *
     * @memberof Cesium3DTileset.prototype
     *
     * @type {ClippingPlaneCollection}
     */
    clippingPlanes: {
      get: function () {
        return this._clippingPlanes;
      },
      set: function (value) {
        ClippingPlaneCollection.setOwner(value, this, "_clippingPlanes");
      },
    },

    /**
     * Gets the tileset's properties dictionary object, which contains metadata about per-feature properties.
     * <p>
     * See the {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification#reference-properties|properties schema reference}
     * in the 3D Tiles spec for the full set of properties.
     * </p>
     *
     * @memberof Cesium3DTileset.prototype
     *
     * @type {Object}
     * @readonly
     *
     * @exception {DeveloperError} The tileset is not loaded.  Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true.
     *
     * @example
     * console.log(`Maximum building height: ${tileset.properties.height.maximum}`);
     * console.log(`Minimum building height: ${tileset.properties.height.minimum}`);
     *
     * @see Cesium3DTileFeature#getProperty
     * @see Cesium3DTileFeature#setProperty
     */
    properties: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this.ready) {
          throw new DeveloperError(
            "The tileset is not loaded.  Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._properties;
      },
    },

    /**
     * When <code>true</code>, the tileset's root tile is loaded and the tileset is ready to render.
     * This is set to <code>true</code> right before {@link Cesium3DTileset#readyPromise} is resolved.
     *
     * @memberof Cesium3DTileset.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default false
     */
    ready: {
      get: function () {
        return defined(this._root);
      },
    },

    /**
     * Gets the promise that will be resolved when the tileset's root tile is loaded and the tileset is ready to render.
     * <p>
     * This promise is resolved at the end of the frame before the first frame the tileset is rendered in.
     * </p>
     *
     * @memberof Cesium3DTileset.prototype
     *
     * @type {Promise.<Cesium3DTileset>}
     * @readonly
     *
     * @example
     * tileset.readyPromise.then(function(tileset) {
     *     // tile.properties is not defined until readyPromise resolves.
     *     const properties = tileset.properties;
     *     if (Cesium.defined(properties)) {
     *         for (const name in properties) {
     *             console.log(properties[name]);
     *         }
     *     }
     * });
     */
    readyPromise: {
      get: function () {
        return this._readyPromise;
      },
    },

    /**
     * When <code>true</code>, all tiles that meet the screen space error this frame are loaded. The tileset is
     * completely loaded for this view.
     *
     * @memberof Cesium3DTileset.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default false
     *
     * @see Cesium3DTileset#allTilesLoaded
     */
    tilesLoaded: {
      get: function () {
        return this._tilesLoaded;
      },
    },

    /**
     * The resource used to fetch the tileset JSON file
     *
     * @memberof Cesium3DTileset.prototype
     *
     * @type {Resource}
     * @readonly
     */
    resource: {
      get: function () {
        return this._resource;
      },
    },

    /**
     * The base path that non-absolute paths in tileset JSON file are relative to.
     *
     * @memberof Cesium3DTileset.prototype
     *
     * @type {String}
     * @readonly
     * @deprecated
     */
    basePath: {
      get: function () {
        deprecationWarning(
          "Cesium3DTileset.basePath",
          "Cesium3DTileset.basePath has been deprecated. All tiles are relative to the url of the tileset JSON file that contains them. Use the url property instead."
        );
        return this._basePath;
      },
    },

    /**
     * The style, defined using the
     * {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/Styling|3D Tiles Styling language},
     * applied to each feature in the tileset.
     * <p>
     * Assign <code>undefined</code> to remove the style, which will restore the visual
     * appearance of the tileset to its default when no style was applied.
     * </p>
     * <p>
     * The style is applied to a tile before the {@link Cesium3DTileset#tileVisible}
     * event is raised, so code in <code>tileVisible</code> can manually set a feature's
     * properties (e.g. color and show) after the style is applied. When
     * a new style is assigned any manually set properties are overwritten.
     * </p>
     * <p>
     * Use an always "true" condition to specify the Color for all objects that are not
     * overridden by pre-existing conditions. Otherwise, the default color Cesium.Color.White
     * will be used. Similarly, use an always "true" condition to specify the show property
     * for all objects that are not overridden by pre-existing conditions. Otherwise, the
     * default show value true will be used.
     * </p>
     *
     * @memberof Cesium3DTileset.prototype
     *
     * @type {Cesium3DTileStyle|undefined}
     *
     * @default undefined
     *
     * @example
     * tileset.style = new Cesium.Cesium3DTileStyle({
     *    color : {
     *        conditions : [
     *            ['${Height} >= 100', 'color("purple", 0.5)'],
     *            ['${Height} >= 50', 'color("red")'],
     *            ['true', 'color("blue")']
     *        ]
     *    },
     *    show : '${Height} > 0',
     *    meta : {
     *        description : '"Building id ${id} has height ${Height}."'
     *    }
     * });
     *
     * @see {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/Styling|3D Tiles Styling language}
     */
    style: {
      get: function () {
        return this._styleEngine.style;
      },
      set: function (value) {
        this._styleEngine.style = value;
      },
    },

    /**
     * A custom shader to apply to all tiles in the tileset. Only used for
     * contents that use {@link ModelExperimental}. Using custom shaders with a
     * {@link Cesium3DTileStyle} may lead to undefined behavior.
     * <p>
     * To enable {@link ModelExperimental}, set {@link ExperimentalFeatures.enableModelExperimental} or tileset.enableModelExperimental to <code>true</code>.
     * </p>
     *
     * @memberof Cesium3DTileset.prototype
     *
     * @type {CustomShader|undefined}
     *
     * @default undefined
     *
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     */
    customShader: {
      get: function () {
        return this._customShader;
      },
      set: function (value) {
        this._customShader = value;
      },
    },

    /**
     * The tileset's schema, groups, tileset metadata and other details from the
     * 3DTILES_metadata extension or a 3D Tiles 1.1 tileset JSON. This getter is
     * for internal use by other classes.
     *
     * @memberof Cesium3DTileset.prototype
     * @type {Cesium3DTilesetMetadata}
     * @private
     * @readonly
     *
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     */
    metadataExtension: {
      get: function () {
        return this._metadataExtension;
      },
    },

    /**
     * The metadata properties attached to the tileset as a whole.
     *
     * @memberof Cesium3DTileset.prototype
     *
     * @type {TilesetMetadata}
     * @private
     * @readonly
     *
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     */
    metadata: {
      get: function () {
        if (defined(this._metadataExtension)) {
          return this._metadataExtension.tileset;
        }

        return undefined;
      },
    },

    /**
     * The metadata schema used in this tileset. Shorthand for
     * <code>tileset.metadataExtension.schema</code>
     *
     * @memberof Cesium3DTileset.prototype
     *
     * @type {MetadataSchema}
     * @private
     * @readonly
     *
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     */
    schema: {
      get: function () {
        if (defined(this._metadataExtension)) {
          return this._metadataExtension.schema;
        }

        return undefined;
      },
    },

    /**
     * The maximum screen space error used to drive level of detail refinement.  This value helps determine when a tile
     * refines to its descendants, and therefore plays a major role in balancing performance with visual quality.
     * <p>
     * A tile's screen space error is roughly equivalent to the number of pixels wide that would be drawn if a sphere with a
     * radius equal to the tile's <b>geometric error</b> were rendered at the tile's position. If this value exceeds
     * <code>maximumScreenSpaceError</code> the tile refines to its descendants.
     * </p>
     * <p>
     * Depending on the tileset, <code>maximumScreenSpaceError</code> may need to be tweaked to achieve the right balance.
     * Higher values provide better performance but lower visual quality.
     * </p>
     *
     * @memberof Cesium3DTileset.prototype
     *
     * @type {Number}
     * @default 16
     *
     * @exception {DeveloperError} <code>maximumScreenSpaceError</code> must be greater than or equal to zero.
     */
    maximumScreenSpaceError: {
      get: function () {
        return this._maximumScreenSpaceError;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number.greaterThanOrEquals(
          "maximumScreenSpaceError",
          value,
          0
        );
        //>>includeEnd('debug');

        this._maximumScreenSpaceError = value;
      },
    },

    /**
     * The maximum amount of GPU memory (in MB) that may be used to cache tiles. This value is estimated from
     * geometry, textures, and batch table textures of loaded tiles. For point clouds, this value also
     * includes per-point metadata.
     * <p>
     * Tiles not in view are unloaded to enforce this.
     * </p>
     * <p>
     * If decreasing this value results in unloading tiles, the tiles are unloaded the next frame.
     * </p>
     * <p>
     * If tiles sized more than <code>maximumMemoryUsage</code> are needed
     * to meet the desired screen space error, determined by {@link Cesium3DTileset#maximumScreenSpaceError},
     * for the current view, then the memory usage of the tiles loaded will exceed
     * <code>maximumMemoryUsage</code>.  For example, if the maximum is 256 MB, but
     * 300 MB of tiles are needed to meet the screen space error, then 300 MB of tiles may be loaded.  When
     * these tiles go out of view, they will be unloaded.
     * </p>
     *
     * @memberof Cesium3DTileset.prototype
     *
     * @type {Number}
     * @default 512
     *
     * @exception {DeveloperError} <code>maximumMemoryUsage</code> must be greater than or equal to zero.
     * @see Cesium3DTileset#totalMemoryUsageInBytes
     */
    maximumMemoryUsage: {
      get: function () {
        return this._maximumMemoryUsage;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number.greaterThanOrEquals("value", value, 0);
        //>>includeEnd('debug');

        this._maximumMemoryUsage = value;
      },
    },

    /**
     * Options for controlling point size based on geometric error and eye dome lighting.
     *
     * @memberof Cesium3DTileset.prototype
     *
     * @type {PointCloudShading}
     */
    pointCloudShading: {
      get: function () {
        return this._pointCloudShading;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.defined("pointCloudShading", value);
        //>>includeEnd('debug');
        this._pointCloudShading = value;
      },
    },

    /**
     * The root tile.
     *
     * @memberOf Cesium3DTileset.prototype
     *
     * @type {Cesium3DTile}
     * @readonly
     *
     * @exception {DeveloperError} The tileset is not loaded.  Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true.
     */
    root: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this.ready) {
          throw new DeveloperError(
            "The tileset is not loaded.  Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._root;
      },
    },

    /**
     * The tileset's bounding sphere.
     *
     * @memberof Cesium3DTileset.prototype
     *
     * @type {BoundingSphere}
     * @readonly
     *
     * @exception {DeveloperError} The tileset is not loaded.  Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true.
     *
     * @example
     * const tileset = viewer.scene.primitives.add(new Cesium.Cesium3DTileset({
     *     url : 'http://localhost:8002/tilesets/Seattle/tileset.json'
     * }));
     *
     * tileset.readyPromise.then(function(tileset) {
     *     // Set the camera to view the newly added tileset
     *     viewer.camera.viewBoundingSphere(tileset.boundingSphere, new Cesium.HeadingPitchRange(0, -0.5, 0));
     * });
     */
    boundingSphere: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this.ready) {
          throw new DeveloperError(
            "The tileset is not loaded.  Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true."
          );
        }
        //>>includeEnd('debug');

        this._root.updateTransform(this._modelMatrix);
        return this._root.boundingSphere;
      },
    },

    /**
     * A 4x4 transformation matrix that transforms the entire tileset.
     *
     * @memberof Cesium3DTileset.prototype
     *
     * @type {Matrix4}
     * @default Matrix4.IDENTITY
     *
     * @example
     * // Adjust a tileset's height from the globe's surface.
     * const heightOffset = 20.0;
     * const boundingSphere = tileset.boundingSphere;
     * const cartographic = Cesium.Cartographic.fromCartesian(boundingSphere.center);
     * const surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, 0.0);
     * const offset = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, heightOffset);
     * const translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3());
     * tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
     */
    modelMatrix: {
      get: function () {
        return this._modelMatrix;
      },
      set: function (value) {
        this._modelMatrix = Matrix4.clone(value, this._modelMatrix);
      },
    },

    /**
     * Returns the time, in milliseconds, since the tileset was loaded and first updated.
     *
     * @memberof Cesium3DTileset.prototype
     *
     * @type {Number}
     * @readonly
     */
    timeSinceLoad: {
      get: function () {
        return this._timeSinceLoad;
      },
    },

    /**
     * The total amount of GPU memory in bytes used by the tileset. This value is estimated from
     * geometry, texture, batch table textures, and binary metadata of loaded tiles.
     *
     * @memberof Cesium3DTileset.prototype
     *
     * @type {Number}
     * @readonly
     *
     * @see Cesium3DTileset#maximumMemoryUsage
     */
    totalMemoryUsageInBytes: {
      get: function () {
        const statistics = this._statistics;
        return (
          statistics.texturesByteLength +
          statistics.geometryByteLength +
          statistics.batchTableByteLength
        );
      },
    },

    /**
     * @private
     */
    clippingPlanesOriginMatrix: {
      get: function () {
        if (!defined(this._clippingPlanesOriginMatrix)) {
          return Matrix4.IDENTITY;
        }

        if (this._clippingPlanesOriginMatrixDirty) {
          Matrix4.multiply(
            this.root.computedTransform,
            this._initialClippingPlanesOriginMatrix,
            this._clippingPlanesOriginMatrix
          );
          this._clippingPlanesOriginMatrixDirty = false;
        }

        return this._clippingPlanesOriginMatrix;
      },
    },

    /**
     * @private
     */
    styleEngine: {
      get: function () {
        return this._styleEngine;
      },
    },

    /**
     * @private
     */
    statistics: {
      get: function () {
        return this._statistics;
      },
    },

    /**
     * Determines whether terrain, 3D Tiles or both will be classified by this tileset.
     * <p>
     * This option is only applied to tilesets containing batched 3D models, geometry data, or vector data. Even when undefined, vector data and geometry data
     * must render as classifications and will default to rendering on both terrain and other 3D Tiles tilesets.
     * </p>
     * <p>
     * When enabled for batched 3D model tilesets, there are a few requirements/limitations on the glTF:
     * <ul>
     *     <li>POSITION and _BATCHID semantics are required.</li>
     *     <li>All indices with the same batch id must occupy contiguous sections of the index buffer.</li>
     *     <li>All shaders and techniques are ignored. The generated shader simply multiplies the position by the model-view-projection matrix.</li>
     *     <li>The only supported extensions are CESIUM_RTC and WEB3D_quantized_attributes.</li>
     *     <li>Only one node is supported.</li>
     *     <li>Only one mesh per node is supported.</li>
     *     <li>Only one primitive per mesh is supported.</li>
     * </ul>
     * </p>
     *
     * @memberof Cesium3DTileset.prototype
     *
     * @type {ClassificationType}
     * @default undefined
     *
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     * @readonly
     */
    classificationType: {
      get: function () {
        return this._classificationType;
      },
    },

    /**
     * Gets an ellipsoid describing the shape of the globe.
     *
     * @memberof Cesium3DTileset.prototype
     *
     * @type {Ellipsoid}
     * @readonly
     */
    ellipsoid: {
      get: function () {
        return this._ellipsoid;
      },
    },

    /**
     * Optimization option. Used when {@link Cesium3DTileset#foveatedScreenSpaceError} is true to control the cone size that determines which tiles are deferred.
     * Tiles that are inside this cone are loaded immediately. Tiles outside the cone are potentially deferred based on how far outside the cone they are and {@link Cesium3DTileset#foveatedInterpolationCallback} and {@link Cesium3DTileset#foveatedMinimumScreenSpaceErrorRelaxation}.
     * Setting this to 0.0 means the cone will be the line formed by the camera position and its view direction. Setting this to 1.0 means the cone encompasses the entire field of view of the camera, essentially disabling the effect.
     *
     * @memberof Cesium3DTileset.prototype
     *
     * @type {Number}
     * @default 0.3
     */
    foveatedConeSize: {
      get: function () {
        return this._foveatedConeSize;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number.greaterThanOrEquals("foveatedConeSize", value, 0.0);
        Check.typeOf.number.lessThanOrEquals("foveatedConeSize", value, 1.0);
        //>>includeEnd('debug');

        this._foveatedConeSize = value;
      },
    },

    /**
     * Optimization option. Used when {@link Cesium3DTileset#foveatedScreenSpaceError} is true to control the starting screen space error relaxation for tiles outside the foveated cone.
     * The screen space error will be raised starting with this value up to {@link Cesium3DTileset#maximumScreenSpaceError} based on the provided {@link Cesium3DTileset#foveatedInterpolationCallback}.
     *
     * @memberof Cesium3DTileset.prototype
     *
     * @type {Number}
     * @default 0.0
     */
    foveatedMinimumScreenSpaceErrorRelaxation: {
      get: function () {
        return this._foveatedMinimumScreenSpaceErrorRelaxation;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number.greaterThanOrEquals(
          "foveatedMinimumScreenSpaceErrorRelaxation",
          value,
          0.0
        );
        Check.typeOf.number.lessThanOrEquals(
          "foveatedMinimumScreenSpaceErrorRelaxation",
          value,
          this.maximumScreenSpaceError
        );
        //>>includeEnd('debug');

        this._foveatedMinimumScreenSpaceErrorRelaxation = value;
      },
    },

    /**
     * Returns the <code>extras</code> property at the top-level of the tileset JSON, which contains application specific metadata.
     * Returns <code>undefined</code> if <code>extras</code> does not exist.
     *
     * @memberof Cesium3DTileset.prototype
     *
     * @exception {DeveloperError} The tileset is not loaded.  Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true.
     *
     * @type {*}
     * @readonly
     *
     * @see {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification#specifying-extensions-and-application-specific-extras|Extras in the 3D Tiles specification.}
     */
    extras: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this.ready) {
          throw new DeveloperError(
            "The tileset is not loaded.  Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._extras;
      },
    },

    /**
     * The properties for managing image-based lighting on this tileset.
     *
     * @memberof Cesium3DTileset.prototype
     *
     * @type {ImageBasedLighting}
     */
    imageBasedLighting: {
      get: function () {
        return this._imageBasedLighting;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.object("imageBasedLighting", this._imageBasedLighting);
        //>>includeEnd('debug');
        if (value !== this._imageBasedLighting) {
          if (
            this._shouldDestroyImageBasedLighting &&
            !this._imageBasedLighting.isDestroyed()
          ) {
            this._imageBasedLighting.destroy();
          }
          this._imageBasedLighting = value;
          this._shouldDestroyImageBasedLighting = false;
        }
      },
    },

    /**
     * Indicates that only the tileset's vector tiles should be used for classification.
     *
     * @memberof Cesium3DTileset.prototype
     *
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     *
     * @type {Boolean}
     * @default false
     */
    vectorClassificationOnly: {
      get: function () {
        return this._vectorClassificationOnly;
      },
    },

    /**
     * Whether vector tiles should keep decoded positions in memory.
     * This is used with {@link Cesium3DTileFeature.getPolylinePositions}.
     *
     * @memberof Cesium3DTileset.prototype
     *
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     *
     * @type {Boolean}
     * @default false
     */
    vectorKeepDecodedPositions: {
      get: function () {
        return this._vectorKeepDecodedPositions;
      },
    },

    /**
     * Determines whether the credits of the tileset will be displayed on the screen
     *
     * @memberof Cesium3DTileset.prototype
     *
     * @type {Boolean}
     * @default false
     */
    showCreditsOnScreen: {
      get: function () {
        return this._showCreditsOnScreen;
      },
      set: function (value) {
        this._showCreditsOnScreen = value;
      },
    },

    /**
     * Label of the feature ID set to use for picking and styling.
     * <p>
     * For EXT_mesh_features, this is the feature ID's label property, or
     * "featureId_N" (where N is the index in the featureIds array) when not
     * specified. EXT_feature_metadata did not have a label field, so such
     * feature ID sets are always labeled "featureId_N" where N is the index in
     * the list of all feature Ids, where feature ID attributes are listed before
     * feature ID textures.
     * </p>
     * <p>
     * If featureIdLabel is set to an integer N, it is converted to
     * the string "featureId_N" automatically. If both per-primitive and
     * per-instance feature IDs are present, the instance feature IDs take
     * priority.
     * </p>
     *
     * @memberof Cesium3DTileset.prototype
     *
     * @type {String}
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     */
    featureIdLabel: {
      get: function () {
        return this._featureIdLabel;
      },
      set: function (value) {
        // indices get converted into featureId_N
        if (typeof value === "number") {
          value = `featureId_${value}`;
        }

        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.string("value", value);
        //>>includeEnd('debug');

        this._featureIdLabel = value;
      },
    },

    /**
     * Label of the instance feature ID set used for picking and styling.
     * <p>
     * If instanceFeatureIdLabel is set to an integer N, it is converted to
     * the string "instanceFeatureId_N" automatically.
     * If both per-primitive and per-instance feature IDs are present, the
     * instance feature IDs take priority.
     * </p>
     *
     * @memberof Cesium3DTileset.prototype
     *
     * @type {String}
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     */
    instanceFeatureIdLabel: {
      get: function () {
        return this._instanceFeatureIdLabel;
      },
      set: function (value) {
        // indices get converted into instanceFeatureId_N
        if (typeof value === "number") {
          value = `instanceFeatureId_${value}`;
        }

        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.string("value", value);
        //>>includeEnd('debug');

        this._instanceFeatureIdLabel = value;
      },
    },
  });

  /**
   * Provides a hook to override the method used to request the tileset json
   * useful when fetching tilesets from remote servers
   * @param {Resource|String} tilesetUrl The url of the json file to be fetched
   * @returns {Promise.<Object>} A promise that resolves with the fetched json data
   */
  Cesium3DTileset.loadJson = function (tilesetUrl) {
    const resource = Resource.createIfNeeded(tilesetUrl);
    return resource.fetchJson();
  };

  /**
   * Marks the tileset's {@link Cesium3DTileset#style} as dirty, which forces all
   * features to re-evaluate the style in the next frame each is visible.
   */
  Cesium3DTileset.prototype.makeStyleDirty = function () {
    this._styleEngine.makeDirty();
  };

  /**
   * Loads the main tileset JSON file or a tileset JSON file referenced from a tile.
   *
   * @private
   */
  Cesium3DTileset.prototype.loadTileset = function (
    resource,
    tilesetJson,
    parentTile
  ) {
    const asset = tilesetJson.asset;
    if (!defined(asset)) {
      throw new RuntimeError("Tileset must have an asset property.");
    }
    if (
      asset.version !== "0.0" &&
      asset.version !== "1.0" &&
      asset.version !== "1.1"
    ) {
      throw new RuntimeError(
        "The tileset must be 3D Tiles version 0.0, 1.0, or 1.1"
      );
    }

    if (defined(tilesetJson.extensionsRequired)) {
      Cesium3DTileset.checkSupportedExtensions(tilesetJson.extensionsRequired);
    }

    const statistics = this._statistics;

    const tilesetVersion = asset.tilesetVersion;
    if (defined(tilesetVersion)) {
      // Append the tileset version to the resource
      this._basePath += `?v=${tilesetVersion}`;
      resource = resource.clone();
      resource.setQueryParameters({ v: tilesetVersion });
    }

    // A tileset JSON file referenced from a tile may exist in a different directory than the root tileset.
    // Get the basePath relative to the external tileset.
    const rootTile = makeTile(this, resource, tilesetJson.root, parentTile);

    // If there is a parentTile, add the root of the currently loading tileset
    // to parentTile's children, and update its _depth.
    if (defined(parentTile)) {
      parentTile.children.push(rootTile);
      rootTile._depth = parentTile._depth + 1;
    }

    const stack = [];
    stack.push(rootTile);

    while (stack.length > 0) {
      const tile = stack.pop();
      ++statistics.numberOfTilesTotal;
      this._allTilesAdditive =
        this._allTilesAdditive && tile.refine === Cesium3DTileRefine$1.ADD;
      const children = tile._header.children;
      if (defined(children)) {
        const length = children.length;
        for (let i = 0; i < length; ++i) {
          const childHeader = children[i];
          const childTile = makeTile(this, resource, childHeader, tile);
          tile.children.push(childTile);
          childTile._depth = tile._depth + 1;
          stack.push(childTile);
        }
      }

      if (this._cullWithChildrenBounds) {
        Cesium3DTileOptimizations.checkChildrenWithinParent(tile);
      }
    }

    return rootTile;
  };

  /**
   * Make a {@link Cesium3DTile} for a specific tile. If the tile's header has implicit
   * tiling (3D Tiles 1.1) or uses the <code>3DTILES_implicit_tiling</code> extension,
   * it creates a placeholder tile instead for lazy evaluation of the implicit tileset.
   *
   * @param {Cesium3DTileset} tileset The tileset
   * @param {Resource} baseResource The base resource for the tileset
   * @param {Object} tileHeader The JSON header for the tile
   * @param {Cesium3DTile} [parentTile] The parent tile of the new tile
   * @returns {Cesium3DTile} The newly created tile
   *
   * @private
   */
  function makeTile(tileset, baseResource, tileHeader, parentTile) {
    const hasImplicitTiling =
      defined(tileHeader.implicitTiling) ||
      hasExtension(tileHeader, "3DTILES_implicit_tiling");

    if (hasImplicitTiling) {
      const metadataSchema = tileset.schema;

      const implicitTileset = new ImplicitTileset(
        baseResource,
        tileHeader,
        metadataSchema
      );
      const rootCoordinates = new ImplicitTileCoordinates({
        subdivisionScheme: implicitTileset.subdivisionScheme,
        subtreeLevels: implicitTileset.subtreeLevels,
        level: 0,
        x: 0,
        y: 0,
        // The constructor will only use this for octrees.
        z: 0,
      });

      // Create a placeholder Cesium3DTile that has an ImplicitTileset
      // object and whose content will resolve to an Implicit3DTileContent
      const contentUri = implicitTileset.subtreeUriTemplate.getDerivedResource({
        templateValues: rootCoordinates.getTemplateValues(),
      }).url;

      const deepCopy = true;
      const tileJson = clone$1(tileHeader, deepCopy);
      // Replace contents with the subtree
      tileJson.contents = [
        {
          uri: contentUri,
        },
      ];

      delete tileJson.content;

      // The placeholder tile does not have any extensions. If there are any
      // extensions beyond 3DTILES_implicit_tiling, Implicit3DTileContent will
      // copy them to the transcoded tiles.
      delete tileJson.extensions;

      const tile = new Cesium3DTile(tileset, baseResource, tileJson, parentTile);
      tile.implicitTileset = implicitTileset;
      tile.implicitCoordinates = rootCoordinates;
      return tile;
    }

    return new Cesium3DTile(tileset, baseResource, tileHeader, parentTile);
  }

  /**
   * If tileset metadata is present, initialize the {@link Cesium3DTilesetMetadata}
   * instance. This is asynchronous since metadata schemas may be external.
   *
   * @param {Cesium3DTileset} tileset The tileset
   * @param {Object} tilesetJson The tileset JSON
   * @return {Promise<Object>} A promise that resolves to tilesetJson for chaining.
   * @private
   */
  function processMetadataExtension(tileset, tilesetJson) {
    const metadataJson = hasExtension(tilesetJson, "3DTILES_metadata")
      ? tilesetJson.extensions["3DTILES_metadata"]
      : tilesetJson;

    let schemaLoader;
    if (defined(metadataJson.schemaUri)) {
      const resource = tileset._resource.getDerivedResource({
        url: metadataJson.schemaUri,
      });
      schemaLoader = ResourceCache.loadSchema({
        resource: resource,
      });
    } else if (defined(metadataJson.schema)) {
      schemaLoader = ResourceCache.loadSchema({
        schema: metadataJson.schema,
      });
    } else {
      return Promise.resolve(tilesetJson);
    }

    tileset._schemaLoader = schemaLoader;

    return schemaLoader.promise.then(function (schemaLoader) {
      tileset._metadataExtension = new Cesium3DTilesetMetadata({
        schema: schemaLoader.schema,
        metadataJson: metadataJson,
      });

      return tilesetJson;
    });
  }

  const scratchPositionNormal$2 = new Cartesian3();
  const scratchCartographic$9 = new Cartographic();
  const scratchMatrix$1 = new Matrix4();
  const scratchCenter$3 = new Cartesian3();
  const scratchPosition$2 = new Cartesian3();
  const scratchDirection$1 = new Cartesian3();

  function updateDynamicScreenSpaceError(tileset, frameState) {
    let up;
    let direction;
    let height;
    let minimumHeight;
    let maximumHeight;

    const camera = frameState.camera;
    const root = tileset._root;
    const tileBoundingVolume = root.contentBoundingVolume;

    if (tileBoundingVolume instanceof TileBoundingRegion) {
      up = Cartesian3.normalize(camera.positionWC, scratchPositionNormal$2);
      direction = camera.directionWC;
      height = camera.positionCartographic.height;
      minimumHeight = tileBoundingVolume.minimumHeight;
      maximumHeight = tileBoundingVolume.maximumHeight;
    } else {
      // Transform camera position and direction into the local coordinate system of the tileset
      const transformLocal = Matrix4.inverseTransformation(
        root.computedTransform,
        scratchMatrix$1
      );
      const ellipsoid = frameState.mapProjection.ellipsoid;
      const boundingVolume = tileBoundingVolume.boundingVolume;
      const centerLocal = Matrix4.multiplyByPoint(
        transformLocal,
        boundingVolume.center,
        scratchCenter$3
      );
      if (Cartesian3.magnitude(centerLocal) > ellipsoid.minimumRadius) {
        // The tileset is defined in WGS84. Approximate the minimum and maximum height.
        const centerCartographic = Cartographic.fromCartesian(
          centerLocal,
          ellipsoid,
          scratchCartographic$9
        );
        up = Cartesian3.normalize(camera.positionWC, scratchPositionNormal$2);
        direction = camera.directionWC;
        height = camera.positionCartographic.height;
        minimumHeight = 0.0;
        maximumHeight = centerCartographic.height * 2.0;
      } else {
        // The tileset is defined in local coordinates (z-up)
        const positionLocal = Matrix4.multiplyByPoint(
          transformLocal,
          camera.positionWC,
          scratchPosition$2
        );
        up = Cartesian3.UNIT_Z;
        direction = Matrix4.multiplyByPointAsVector(
          transformLocal,
          camera.directionWC,
          scratchDirection$1
        );
        direction = Cartesian3.normalize(direction, direction);
        height = positionLocal.z;
        if (tileBoundingVolume instanceof TileOrientedBoundingBox) {
          // Assuming z-up, the last component stores the half-height of the box
          const boxHeight = root._header.boundingVolume.box[11];
          minimumHeight = centerLocal.z - boxHeight;
          maximumHeight = centerLocal.z + boxHeight;
        } else if (tileBoundingVolume instanceof TileBoundingSphere) {
          const radius = boundingVolume.radius;
          minimumHeight = centerLocal.z - radius;
          maximumHeight = centerLocal.z + radius;
        }
      }
    }

    // The range where the density starts to lessen. Start at the quarter height of the tileset.
    const heightFalloff = tileset.dynamicScreenSpaceErrorHeightFalloff;
    const heightClose =
      minimumHeight + (maximumHeight - minimumHeight) * heightFalloff;
    const heightFar = maximumHeight;

    const t = CesiumMath.clamp(
      (height - heightClose) / (heightFar - heightClose),
      0.0,
      1.0
    );

    // Increase density as the camera tilts towards the horizon
    const dot = Math.abs(Cartesian3.dot(direction, up));
    let horizonFactor = 1.0 - dot;

    // Weaken the horizon factor as the camera height increases, implying the camera is further away from the tileset.
    // The goal is to increase density for the "street view", not when viewing the tileset from a distance.
    horizonFactor = horizonFactor * (1.0 - t);

    let density = tileset.dynamicScreenSpaceErrorDensity;
    density *= horizonFactor;

    tileset._dynamicScreenSpaceErrorComputedDensity = density;
  }

  ///////////////////////////////////////////////////////////////////////////

  function requestContent(tileset, tile) {
    if (tile.hasEmptyContent) {
      return;
    }

    const statistics = tileset._statistics;
    const expired = tile.contentExpired;
    const attemptedRequests = tile.requestContent();

    if (attemptedRequests > 0) {
      statistics.numberOfAttemptedRequests += attemptedRequests;
      return;
    }

    if (expired) {
      if (tile.hasTilesetContent || tile.hasImplicitContent) {
        destroySubtree(tileset, tile);
      } else {
        statistics.decrementLoadCounts(tile.content);
        --statistics.numberOfTilesWithContentReady;
      }
    }

    tileset._requestedTilesInFlight.push(tile);

    tile.contentReadyToProcessPromise
      .then(addToProcessingQueue(tileset, tile))
      .catch(function (e) {
        // Any error will propagate through contentReadyPromise and will be handled below
      });
    tile.contentReadyPromise
      .then(handleTileSuccess(tileset, tile))
      .catch(handleTileFailure(tileset, tile));
  }

  function sortRequestByPriority(a, b) {
    return a._priority - b._priority;
  }

  /**
   * Perform any pass invariant tasks here. Called after the render pass.
   * @private
   */
  Cesium3DTileset.prototype.postPassesUpdate = function (frameState) {
    if (!this.ready) {
      return;
    }

    cancelOutOfViewRequests(this, frameState);
    raiseLoadProgressEvent(this, frameState);
    this._cache.unloadTiles(this, unloadTile);
    this._styleEngine.resetDirty();
  };

  /**
   * Perform any pass invariant tasks here. Called before any passes are executed.
   * @private
   */
  Cesium3DTileset.prototype.prePassesUpdate = function (frameState) {
    if (!this.ready) {
      return;
    }

    processTiles(this, frameState);

    // Update clipping planes
    const clippingPlanes = this._clippingPlanes;
    this._clippingPlanesOriginMatrixDirty = true;
    if (defined(clippingPlanes) && clippingPlanes.enabled) {
      clippingPlanes.update(frameState);
    }

    if (!defined(this._loadTimestamp)) {
      this._loadTimestamp = JulianDate.clone(frameState.time);
    }
    this._timeSinceLoad = Math.max(
      JulianDate.secondsDifference(frameState.time, this._loadTimestamp) * 1000,
      0.0
    );

    this._skipLevelOfDetail =
      this.skipLevelOfDetail &&
      !defined(this._classificationType) &&
      !this._disableSkipLevelOfDetail &&
      !this._allTilesAdditive;

    if (this.dynamicScreenSpaceError) {
      updateDynamicScreenSpaceError(this, frameState);
    }

    if (frameState.newFrame) {
      this._cache.reset();
    }
  };

  function cancelOutOfViewRequests(tileset, frameState) {
    const requestedTilesInFlight = tileset._requestedTilesInFlight;
    let removeCount = 0;
    const length = requestedTilesInFlight.length;
    for (let i = 0; i < length; ++i) {
      const tile = requestedTilesInFlight[i];

      // NOTE: This is framerate dependant so make sure the threshold check is small
      const outOfView = frameState.frameNumber - tile._touchedFrame >= 1;
      if (tile._contentState !== Cesium3DTileContentState$1.LOADING) {
        // No longer fetching from host, don't need to track it anymore. Gets marked as LOADING in Cesium3DTile::requestContent().
        ++removeCount;
        continue;
      } else if (outOfView) {
        // RequestScheduler will take care of cancelling it
        tile.cancelRequests();
        ++removeCount;
        continue;
      }

      if (removeCount > 0) {
        requestedTilesInFlight[i - removeCount] = tile;
      }
    }

    requestedTilesInFlight.length -= removeCount;
  }

  function requestTiles(tileset, isAsync) {
    // Sort requests by priority before making any requests.
    // This makes it less likely that requests will be cancelled after being issued.
    const requestedTiles = tileset._requestedTiles;
    const length = requestedTiles.length;
    requestedTiles.sort(sortRequestByPriority);
    for (let i = 0; i < length; ++i) {
      requestContent(tileset, requestedTiles[i]);
    }
  }

  function addToProcessingQueue(tileset, tile) {
    return function () {
      tileset._processingQueue.push(tile);

      ++tileset._statistics.numberOfTilesProcessing;
    };
  }

  function handleTileFailure(tileset, tile) {
    return function (error) {
      if (tile._contentState !== Cesium3DTileContentState$1.FAILED) {
        // If the tile has not failed, the request has been rejected this frame, but will be retried. Do not bubble up the error.
        return;
      }

      const url = tile._contentResource.url;
      const message = defined(error.message) ? error.message : error.toString();
      if (tileset.tileFailed.numberOfListeners > 0) {
        tileset.tileFailed.raiseEvent({
          url: url,
          message: message,
        });
      } else {
        console.log(`A 3D tile failed to load: ${url}`);
        console.log(`Error: ${message}`);
      }
    };
  }

  function handleTileSuccess(tileset, tile) {
    return function (content) {
      --tileset._statistics.numberOfTilesProcessing;

      if (!defined(content)) {
        // A request was cancelled. Do not update successful statistics. The request will be retried.
        return;
      }

      if (!tile.hasTilesetContent && !tile.hasImplicitContent) {
        // RESEARCH_IDEA: ability to unload tiles (without content) for an
        // external tileset when all the tiles are unloaded.
        tileset._statistics.incrementLoadCounts(tile.content);
        ++tileset._statistics.numberOfTilesWithContentReady;
        ++tileset._statistics.numberOfLoadedTilesTotal;

        // Add to the tile cache. Previously expired tiles are already in the cache and won't get re-added.
        tileset._cache.add(tile);
      }

      tileset.tileLoad.raiseEvent(tile);
    };
  }

  function filterProcessingQueue(tileset) {
    const tiles = tileset._processingQueue;
    const length = tiles.length;

    let removeCount = 0;
    for (let i = 0; i < length; ++i) {
      const tile = tiles[i];
      if (tile._contentState !== Cesium3DTileContentState$1.PROCESSING) {
        ++removeCount;
        continue;
      }
      if (removeCount > 0) {
        tiles[i - removeCount] = tile;
      }
    }
    tiles.length -= removeCount;
  }

  function processTiles(tileset, frameState) {
    filterProcessingQueue(tileset);
    const tiles = tileset._processingQueue;
    const length = tiles.length;
    // Process tiles in the PROCESSING state so they will eventually move to the READY state.
    for (let i = 0; i < length; ++i) {
      tiles[i].process(tileset, frameState);
    }
  }

  ///////////////////////////////////////////////////////////////////////////

  const scratchCartesian$4 = new Cartesian3();

  const stringOptions$1 = {
    maximumFractionDigits: 3,
  };

  function formatMemoryString$1(memorySizeInBytes) {
    const memoryInMegabytes = memorySizeInBytes / 1048576;
    if (memoryInMegabytes < 1.0) {
      return memoryInMegabytes.toLocaleString(undefined, stringOptions$1);
    }
    return Math.round(memoryInMegabytes).toLocaleString();
  }

  function computeTileLabelPosition(tile) {
    const boundingVolume = tile.boundingVolume.boundingVolume;
    const halfAxes = boundingVolume.halfAxes;
    const radius = boundingVolume.radius;

    let position = Cartesian3.clone(boundingVolume.center, scratchCartesian$4);
    if (defined(halfAxes)) {
      position.x += 0.75 * (halfAxes[0] + halfAxes[3] + halfAxes[6]);
      position.y += 0.75 * (halfAxes[1] + halfAxes[4] + halfAxes[7]);
      position.z += 0.75 * (halfAxes[2] + halfAxes[5] + halfAxes[8]);
    } else if (defined(radius)) {
      let normal = Cartesian3.normalize(boundingVolume.center, scratchCartesian$4);
      normal = Cartesian3.multiplyByScalar(
        normal,
        0.75 * radius,
        scratchCartesian$4
      );
      position = Cartesian3.add(normal, boundingVolume.center, scratchCartesian$4);
    }
    return position;
  }

  function addTileDebugLabel(tile, tileset, position) {
    let labelString = "";
    let attributes = 0;

    if (tileset.debugShowGeometricError) {
      labelString += `\nGeometric error: ${tile.geometricError}`;
      attributes++;
    }

    if (tileset.debugShowRenderingStatistics) {
      labelString += `\nCommands: ${tile.commandsLength}`;
      attributes++;

      // Don't display number of points or triangles if 0.
      const numberOfPoints = tile.content.pointsLength;
      if (numberOfPoints > 0) {
        labelString += `\nPoints: ${tile.content.pointsLength}`;
        attributes++;
      }

      const numberOfTriangles = tile.content.trianglesLength;
      if (numberOfTriangles > 0) {
        labelString += `\nTriangles: ${tile.content.trianglesLength}`;
        attributes++;
      }

      labelString += `\nFeatures: ${tile.content.featuresLength}`;
      attributes++;
    }

    if (tileset.debugShowMemoryUsage) {
      labelString += `\nTexture Memory: ${formatMemoryString$1(
      tile.content.texturesByteLength
    )}`;
      labelString += `\nGeometry Memory: ${formatMemoryString$1(
      tile.content.geometryByteLength
    )}`;
      attributes += 2;
    }

    if (tileset.debugShowUrl) {
      if (tile.hasMultipleContents) {
        labelString += "\nUrls:";
        const urls = tile.content.innerContentUrls;
        for (let i = 0; i < urls.length; i++) {
          labelString += `\n- ${urls[i]}`;
        }
        attributes += urls.length;
      } else {
        labelString += `\nUrl: ${tile._contentHeader.uri}`;
        attributes++;
      }
    }

    const newLabel = {
      text: labelString.substring(1),
      position: position,
      font: `${19 - attributes}px sans-serif`,
      showBackground: true,
      disableDepthTestDistance: Number.POSITIVE_INFINITY,
    };

    return tileset._tileDebugLabels.add(newLabel);
  }

  function updateTileDebugLabels(tileset, frameState) {
    let i;
    let tile;
    const selectedTiles = tileset._selectedTiles;
    const selectedLength = selectedTiles.length;
    const emptyTiles = tileset._emptyTiles;
    const emptyLength = emptyTiles.length;
    tileset._tileDebugLabels.removeAll();

    if (tileset.debugPickedTileLabelOnly) {
      if (defined(tileset.debugPickedTile)) {
        const position = defined(tileset.debugPickPosition)
          ? tileset.debugPickPosition
          : computeTileLabelPosition(tileset.debugPickedTile);
        const label = addTileDebugLabel(
          tileset.debugPickedTile,
          tileset,
          position
        );
        label.pixelOffset = new Cartesian2(15, -15); // Offset to avoid picking the label.
      }
    } else {
      for (i = 0; i < selectedLength; ++i) {
        tile = selectedTiles[i];
        addTileDebugLabel(tile, tileset, computeTileLabelPosition(tile));
      }
      for (i = 0; i < emptyLength; ++i) {
        tile = emptyTiles[i];
        if (tile.hasTilesetContent || tile.hasImplicitContent) {
          addTileDebugLabel(tile, tileset, computeTileLabelPosition(tile));
        }
      }
    }
    tileset._tileDebugLabels.update(frameState);
  }

  function updateTiles(tileset, frameState, passOptions) {
    tileset._styleEngine.applyStyle(tileset);

    const isRender = passOptions.isRender;
    const statistics = tileset._statistics;
    const commandList = frameState.commandList;
    const numberOfInitialCommands = commandList.length;
    const selectedTiles = tileset._selectedTiles;
    const selectedLength = selectedTiles.length;
    const emptyTiles = tileset._emptyTiles;
    const emptyLength = emptyTiles.length;
    const tileVisible = tileset.tileVisible;
    let i;
    let tile;

    const bivariateVisibilityTest =
      tileset._skipLevelOfDetail &&
      tileset._hasMixedContent &&
      frameState.context.stencilBuffer &&
      selectedLength > 0;

    tileset._backfaceCommands.length = 0;

    if (bivariateVisibilityTest) {
      if (!defined(tileset._stencilClearCommand)) {
        tileset._stencilClearCommand = new ClearCommand({
          stencil: 0,
          pass: Pass$1.CESIUM_3D_TILE,
          renderState: RenderState.fromCache({
            stencilMask: StencilConstants$1.SKIP_LOD_MASK,
          }),
        });
      }
      commandList.push(tileset._stencilClearCommand);
    }

    const lengthBeforeUpdate = commandList.length;
    for (i = 0; i < selectedLength; ++i) {
      tile = selectedTiles[i];
      // Raise the tileVisible event before update in case the tileVisible event
      // handler makes changes that update needs to apply to WebGL resources
      if (isRender) {
        tileVisible.raiseEvent(tile);
      }
      tile.update(tileset, frameState, passOptions);
      statistics.incrementSelectionCounts(tile.content);
      ++statistics.selected;
    }
    for (i = 0; i < emptyLength; ++i) {
      tile = emptyTiles[i];
      tile.update(tileset, frameState, passOptions);
    }

    let addedCommandsLength = commandList.length - lengthBeforeUpdate;

    tileset._backfaceCommands.trim();

    if (bivariateVisibilityTest) {
      /*
       * Consider 'effective leaf' tiles as selected tiles that have no selected descendants. They may have children,
       * but they are currently our effective leaves because they do not have selected descendants. These tiles
       * are those where with tile._finalResolution === true.
       * Let 'unresolved' tiles be those with tile._finalResolution === false.
       *
       * 1. Render just the backfaces of unresolved tiles in order to lay down z
       * 2. Render all frontfaces wherever tile._selectionDepth > stencilBuffer.
       *    Replace stencilBuffer with tile._selectionDepth, when passing the z test.
       *    Because children are always drawn before ancestors {@link Cesium3DTilesetTraversal#traverseAndSelect},
       *    this effectively draws children first and does not draw ancestors if a descendant has already
       *    been drawn at that pixel.
       *    Step 1 prevents child tiles from appearing on top when they are truly behind ancestor content.
       *    If they are behind the backfaces of the ancestor, then they will not be drawn.
       *
       * NOTE: Step 2 sometimes causes visual artifacts when backfacing child content has some faces that
       * partially face the camera and are inside of the ancestor content. Because they are inside, they will
       * not be culled by the depth writes in Step 1, and because they partially face the camera, the stencil tests
       * will draw them on top of the ancestor content.
       *
       * NOTE: Because we always render backfaces of unresolved tiles, if the camera is looking at the backfaces
       * of an object, they will always be drawn while loading, even if backface culling is enabled.
       */

      const backfaceCommands = tileset._backfaceCommands.values;
      const backfaceCommandsLength = backfaceCommands.length;

      commandList.length += backfaceCommandsLength;

      // copy commands to the back of the commandList
      for (i = addedCommandsLength - 1; i >= 0; --i) {
        commandList[lengthBeforeUpdate + backfaceCommandsLength + i] =
          commandList[lengthBeforeUpdate + i];
      }

      // move backface commands to the front of the commandList
      for (i = 0; i < backfaceCommandsLength; ++i) {
        commandList[lengthBeforeUpdate + i] = backfaceCommands[i];
      }
    }

    // Number of commands added by each update above
    addedCommandsLength = commandList.length - numberOfInitialCommands;
    statistics.numberOfCommands = addedCommandsLength;

    // Only run EDL if simple attenuation is on
    if (
      isRender &&
      tileset.pointCloudShading.attenuation &&
      tileset.pointCloudShading.eyeDomeLighting &&
      addedCommandsLength > 0
    ) {
      tileset._pointCloudEyeDomeLighting.update(
        frameState,
        numberOfInitialCommands,
        tileset.pointCloudShading,
        tileset.boundingSphere
      );
    }

    if (isRender) {
      if (
        tileset.debugShowGeometricError ||
        tileset.debugShowRenderingStatistics ||
        tileset.debugShowMemoryUsage ||
        tileset.debugShowUrl
      ) {
        if (!defined(tileset._tileDebugLabels)) {
          tileset._tileDebugLabels = new LabelCollection();
        }
        updateTileDebugLabels(tileset, frameState);
      } else {
        tileset._tileDebugLabels =
          tileset._tileDebugLabels && tileset._tileDebugLabels.destroy();
      }
    }
  }

  const scratchStack = [];

  function destroySubtree(tileset, tile) {
    const root = tile;
    const stack = scratchStack;
    stack.push(tile);
    while (stack.length > 0) {
      tile = stack.pop();
      const children = tile.children;
      const length = children.length;
      for (let i = 0; i < length; ++i) {
        stack.push(children[i]);
      }
      if (tile !== root) {
        destroyTile(tileset, tile);
        --tileset._statistics.numberOfTilesTotal;
      }
    }
    root.children = [];
  }

  function unloadTile(tileset, tile) {
    tileset.tileUnload.raiseEvent(tile);
    tileset._statistics.decrementLoadCounts(tile.content);
    --tileset._statistics.numberOfTilesWithContentReady;
    tile.unloadContent();
  }

  function destroyTile(tileset, tile) {
    tileset._cache.unloadTile(tileset, tile, unloadTile);
    tile.destroy();
  }

  /**
   * Unloads all tiles that weren't selected the previous frame.  This can be used to
   * explicitly manage the tile cache and reduce the total number of tiles loaded below
   * {@link Cesium3DTileset#maximumMemoryUsage}.
   * <p>
   * Tile unloads occur at the next frame to keep all the WebGL delete calls
   * within the render loop.
   * </p>
   */
  Cesium3DTileset.prototype.trimLoadedTiles = function () {
    this._cache.trim();
  };

  ///////////////////////////////////////////////////////////////////////////

  function raiseLoadProgressEvent(tileset, frameState) {
    const statistics = tileset._statistics;
    const statisticsLast = tileset._statisticsLast;

    const numberOfPendingRequests = statistics.numberOfPendingRequests;
    const numberOfTilesProcessing = statistics.numberOfTilesProcessing;
    const lastNumberOfPendingRequest = statisticsLast.numberOfPendingRequests;
    const lastNumberOfTilesProcessing = statisticsLast.numberOfTilesProcessing;

    Cesium3DTilesetStatistics.clone(statistics, statisticsLast);

    const progressChanged =
      numberOfPendingRequests !== lastNumberOfPendingRequest ||
      numberOfTilesProcessing !== lastNumberOfTilesProcessing;

    if (progressChanged) {
      frameState.afterRender.push(function () {
        tileset.loadProgress.raiseEvent(
          numberOfPendingRequests,
          numberOfTilesProcessing
        );
      });
    }

    tileset._tilesLoaded =
      statistics.numberOfPendingRequests === 0 &&
      statistics.numberOfTilesProcessing === 0 &&
      statistics.numberOfAttemptedRequests === 0;

    // Events are raised (added to the afterRender queue) here since promises
    // may resolve outside of the update loop that then raise events, e.g.,
    // model's readyPromise.
    if (progressChanged && tileset._tilesLoaded) {
      frameState.afterRender.push(function () {
        tileset.allTilesLoaded.raiseEvent();
      });
      if (!tileset._initialTilesLoaded) {
        tileset._initialTilesLoaded = true;
        frameState.afterRender.push(function () {
          tileset.initialTilesLoaded.raiseEvent();
        });
      }
    }
  }

  function resetMinimumMaximum(tileset) {
    tileset._heatmap.resetMinimumMaximum();
    tileset._minimumPriority.depth = Number.MAX_VALUE;
    tileset._maximumPriority.depth = -Number.MAX_VALUE;
    tileset._minimumPriority.foveatedFactor = Number.MAX_VALUE;
    tileset._maximumPriority.foveatedFactor = -Number.MAX_VALUE;
    tileset._minimumPriority.distance = Number.MAX_VALUE;
    tileset._maximumPriority.distance = -Number.MAX_VALUE;
    tileset._minimumPriority.reverseScreenSpaceError = Number.MAX_VALUE;
    tileset._maximumPriority.reverseScreenSpaceError = -Number.MAX_VALUE;
  }

  function detectModelMatrixChanged(tileset, frameState) {
    if (
      frameState.frameNumber !== tileset._updatedModelMatrixFrame ||
      !defined(tileset._previousModelMatrix)
    ) {
      tileset._updatedModelMatrixFrame = frameState.frameNumber;
      tileset._modelMatrixChanged = !Matrix4.equals(
        tileset.modelMatrix,
        tileset._previousModelMatrix
      );
      if (tileset._modelMatrixChanged) {
        tileset._previousModelMatrix = Matrix4.clone(
          tileset.modelMatrix,
          tileset._previousModelMatrix
        );
      }
    }
  }

  ///////////////////////////////////////////////////////////////////////////

  function update$1(tileset, frameState, passStatistics, passOptions) {
    if (frameState.mode === SceneMode$1.MORPHING) {
      return false;
    }

    if (!tileset.ready) {
      return false;
    }

    const statistics = tileset._statistics;
    statistics.clear();

    const isRender = passOptions.isRender;

    // Resets the visibility check for each pass
    ++tileset._updatedVisibilityFrame;

    // Update any tracked min max values
    resetMinimumMaximum(tileset);

    detectModelMatrixChanged(tileset, frameState);
    tileset._cullRequestsWhileMoving =
      tileset.cullRequestsWhileMoving && !tileset._modelMatrixChanged;

    const ready = passOptions.traversal.selectTiles(tileset, frameState);

    if (passOptions.requestTiles) {
      requestTiles(tileset);
    }

    updateTiles(tileset, frameState, passOptions);

    // Update pass statistics
    Cesium3DTilesetStatistics.clone(statistics, passStatistics);

    if (isRender) {
      const credits = tileset._credits;
      if (defined(credits) && statistics.selected !== 0) {
        const length = credits.length;
        for (let i = 0; i < length; ++i) {
          const credit = credits[i];
          credit.showOnScreen = tileset._showCreditsOnScreen;
          frameState.creditDisplay.addCredit(credit);
        }
      }
    }

    return ready;
  }

  /**
   * @private
   */
  Cesium3DTileset.prototype.update = function (frameState) {
    this.updateForPass(frameState, frameState.tilesetPassState);
  };

  /**
   * @private
   */
  Cesium3DTileset.prototype.updateForPass = function (
    frameState,
    tilesetPassState
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("frameState", frameState);
    Check.typeOf.object("tilesetPassState", tilesetPassState);
    //>>includeEnd('debug');

    const pass = tilesetPassState.pass;
    if (
      (pass === Cesium3DTilePass$1.PRELOAD &&
        (!this.preloadWhenHidden || this.show)) ||
      (pass === Cesium3DTilePass$1.PRELOAD_FLIGHT &&
        (!this.preloadFlightDestinations ||
          (!this.show && !this.preloadWhenHidden))) ||
      (pass === Cesium3DTilePass$1.REQUEST_RENDER_MODE_DEFER_CHECK &&
        ((!this._cullRequestsWhileMoving && this.foveatedTimeDelay <= 0) ||
          !this.show))
    ) {
      return;
    }

    const originalCommandList = frameState.commandList;
    const originalCamera = frameState.camera;
    const originalCullingVolume = frameState.cullingVolume;

    tilesetPassState.ready = false;

    const passOptions = Cesium3DTilePass$1.getPassOptions(pass);
    const ignoreCommands = passOptions.ignoreCommands;

    const commandList = defaultValue(
      tilesetPassState.commandList,
      originalCommandList
    );
    const commandStart = commandList.length;

    frameState.commandList = commandList;
    frameState.camera = defaultValue(tilesetPassState.camera, originalCamera);
    frameState.cullingVolume = defaultValue(
      tilesetPassState.cullingVolume,
      originalCullingVolume
    );

    const passStatistics = this._statisticsPerPass[pass];

    if (this.show || ignoreCommands) {
      this._pass = pass;
      tilesetPassState.ready = update$1(
        this,
        frameState,
        passStatistics,
        passOptions
      );
    }

    if (ignoreCommands) {
      commandList.length = commandStart;
    }

    frameState.commandList = originalCommandList;
    frameState.camera = originalCamera;
    frameState.cullingVolume = originalCullingVolume;
  };

  /**
   * <code>true</code> if the tileset JSON file lists the extension in extensionsUsed; otherwise, <code>false</code>.
   * @param {String} extensionName The name of the extension to check.
   *
   * @returns {Boolean} <code>true</code> if the tileset JSON file lists the extension in extensionsUsed; otherwise, <code>false</code>.
   */
  Cesium3DTileset.prototype.hasExtension = function (extensionName) {
    if (!defined(this._extensionsUsed)) {
      return false;
    }

    return this._extensionsUsed.indexOf(extensionName) > -1;
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see Cesium3DTileset#destroy
   */
  Cesium3DTileset.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @example
   * tileset = tileset && tileset.destroy();
   *
   * @see Cesium3DTileset#isDestroyed
   */
  Cesium3DTileset.prototype.destroy = function () {
    this._tileDebugLabels =
      this._tileDebugLabels && this._tileDebugLabels.destroy();
    this._clippingPlanes = this._clippingPlanes && this._clippingPlanes.destroy();

    if (defined(this._schemaLoader)) {
      ResourceCache.unload(this._schemaLoader);
    }

    // Traverse the tree and destroy all tiles
    if (defined(this._root)) {
      const stack = scratchStack;
      stack.push(this._root);

      while (stack.length > 0) {
        const tile = stack.pop();
        tile.destroy();

        const children = tile.children;
        const length = children.length;
        for (let i = 0; i < length; ++i) {
          stack.push(children[i]);
        }
      }
    }
    this._root = undefined;

    if (
      this._shouldDestroyImageBasedLighting &&
      !this._imageBasedLighting.isDestroyed()
    ) {
      this._imageBasedLighting.destroy();
    }
    this._imageBasedLighting = undefined;

    return destroyObject(this);
  };

  Cesium3DTileset.supportedExtensions = {
    "3DTILES_metadata": true,
    "3DTILES_implicit_tiling": true,
    "3DTILES_content_gltf": true,
    "3DTILES_multiple_contents": true,
    "3DTILES_bounding_volume_S2": true,
    "3DTILES_batch_table_hierarchy": true,
    "3DTILES_draco_point_compression": true,
    MAXAR_content_geojson: true,
  };

  /**
   * Checks to see if a given extension is supported by Cesium3DTileset. If
   * the extension is not supported by Cesium3DTileset, it throws a RuntimeError.
   *
   * @param {Object} extensionsRequired The extensions we wish to check
   *
   * @private
   */
  Cesium3DTileset.checkSupportedExtensions = function (extensionsRequired) {
    for (let i = 0; i < extensionsRequired.length; i++) {
      if (!Cesium3DTileset.supportedExtensions[extensionsRequired[i]]) {
        throw new RuntimeError(
          `Unsupported 3D Tiles Extension: ${extensionsRequired[i]}`
        );
      }
    }
  };

  const modelMatrixScratch$1 = new Matrix4();

  /**
   * A {@link Visualizer} which maps {@link Entity#tileset} to a {@link Cesium3DTileset}.
   * @alias Cesium3DTilesetVisualizer
   * @constructor
   *
   * @param {Scene} scene The scene the primitives will be rendered in.
   * @param {EntityCollection} entityCollection The entityCollection to visualize.
   */
  function Cesium3DTilesetVisualizer(scene, entityCollection) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(scene)) {
      throw new DeveloperError("scene is required.");
    }
    if (!defined(entityCollection)) {
      throw new DeveloperError("entityCollection is required.");
    }
    //>>includeEnd('debug');

    entityCollection.collectionChanged.addEventListener(
      Cesium3DTilesetVisualizer.prototype._onCollectionChanged,
      this
    );

    this._scene = scene;
    this._primitives = scene.primitives;
    this._entityCollection = entityCollection;
    this._tilesetHash = {};
    this._entitiesToVisualize = new AssociativeArray();
    this._onCollectionChanged(entityCollection, entityCollection.values, [], []);
  }

  /**
   * Updates models created this visualizer to match their
   * Entity counterpart at the given time.
   *
   * @param {JulianDate} time The time to update to.
   * @returns {Boolean} This function always returns true.
   */
  Cesium3DTilesetVisualizer.prototype.update = function (time) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(time)) {
      throw new DeveloperError("time is required.");
    }
    //>>includeEnd('debug');

    const entities = this._entitiesToVisualize.values;
    const tilesetHash = this._tilesetHash;
    const primitives = this._primitives;

    for (let i = 0, len = entities.length; i < len; i++) {
      const entity = entities[i];
      const tilesetGraphics = entity._tileset;

      let resource;
      let tilesetData = tilesetHash[entity.id];
      const show =
        entity.isShowing &&
        entity.isAvailable(time) &&
        Property.getValueOrDefault(tilesetGraphics._show, time, true);

      let modelMatrix;
      if (show) {
        modelMatrix = entity.computeModelMatrix(time, modelMatrixScratch$1);
        resource = Resource.createIfNeeded(
          Property.getValueOrUndefined(tilesetGraphics._uri, time)
        );
      }

      if (!show) {
        if (defined(tilesetData)) {
          tilesetData.tilesetPrimitive.show = false;
        }
        continue;
      }

      let tileset = defined(tilesetData)
        ? tilesetData.tilesetPrimitive
        : undefined;
      if (!defined(tileset) || resource.url !== tilesetData.url) {
        if (defined(tileset)) {
          primitives.removeAndDestroy(tileset);
          delete tilesetHash[entity.id];
        }
        tileset = new Cesium3DTileset({
          url: resource,
        });
        tileset.id = entity;
        primitives.add(tileset);

        tilesetData = {
          tilesetPrimitive: tileset,
          url: resource.url,
          loadFail: false,
        };
        tilesetHash[entity.id] = tilesetData;

        checkLoad(tileset, entity, tilesetHash);
      }

      tileset.show = true;
      if (defined(modelMatrix)) {
        tileset.modelMatrix = modelMatrix;
      }
      tileset.maximumScreenSpaceError = Property.getValueOrDefault(
        tilesetGraphics.maximumScreenSpaceError,
        time,
        tileset.maximumScreenSpaceError
      );
    }

    return true;
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   *
   * @returns {Boolean} True if this object was destroyed; otherwise, false.
   */
  Cesium3DTilesetVisualizer.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Removes and destroys all primitives created by this instance.
   */
  Cesium3DTilesetVisualizer.prototype.destroy = function () {
    this._entityCollection.collectionChanged.removeEventListener(
      Cesium3DTilesetVisualizer.prototype._onCollectionChanged,
      this
    );
    const entities = this._entitiesToVisualize.values;
    const tilesetHash = this._tilesetHash;
    const primitives = this._primitives;
    for (let i = entities.length - 1; i > -1; i--) {
      removeTileset(this, entities[i], tilesetHash, primitives);
    }
    return destroyObject(this);
  };

  /**
   * Computes a bounding sphere which encloses the visualization produced for the specified entity.
   * The bounding sphere is in the fixed frame of the scene's globe.
   *
   * @param {Entity} entity The entity whose bounding sphere to compute.
   * @param {BoundingSphere} result The bounding sphere onto which to store the result.
   * @returns {BoundingSphereState} BoundingSphereState.DONE if the result contains the bounding sphere,
   *                       BoundingSphereState.PENDING if the result is still being computed, or
   *                       BoundingSphereState.FAILED if the entity has no visualization in the current scene.
   * @private
   */
  Cesium3DTilesetVisualizer.prototype.getBoundingSphere = function (
    entity,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(entity)) {
      throw new DeveloperError("entity is required.");
    }
    if (!defined(result)) {
      throw new DeveloperError("result is required.");
    }
    //>>includeEnd('debug');

    const tilesetData = this._tilesetHash[entity.id];
    if (!defined(tilesetData) || tilesetData.loadFail) {
      return BoundingSphereState$1.FAILED;
    }

    const primitive = tilesetData.tilesetPrimitive;
    if (!defined(primitive) || !primitive.show) {
      return BoundingSphereState$1.FAILED;
    }

    if (!primitive.ready) {
      return BoundingSphereState$1.PENDING;
    }

    BoundingSphere.clone(primitive.boundingSphere, result);

    return BoundingSphereState$1.DONE;
  };

  /**
   * @private
   */
  Cesium3DTilesetVisualizer.prototype._onCollectionChanged = function (
    entityCollection,
    added,
    removed,
    changed
  ) {
    let i;
    let entity;
    const entities = this._entitiesToVisualize;
    const tilesetHash = this._tilesetHash;
    const primitives = this._primitives;

    for (i = added.length - 1; i > -1; i--) {
      entity = added[i];
      if (defined(entity._tileset)) {
        entities.set(entity.id, entity);
      }
    }

    for (i = changed.length - 1; i > -1; i--) {
      entity = changed[i];
      if (defined(entity._tileset)) {
        entities.set(entity.id, entity);
      } else {
        removeTileset(this, entity, tilesetHash, primitives);
        entities.remove(entity.id);
      }
    }

    for (i = removed.length - 1; i > -1; i--) {
      entity = removed[i];
      removeTileset(this, entity, tilesetHash, primitives);
      entities.remove(entity.id);
    }
  };

  function removeTileset(visualizer, entity, tilesetHash, primitives) {
    const tilesetData = tilesetHash[entity.id];
    if (defined(tilesetData)) {
      primitives.removeAndDestroy(tilesetData.tilesetPrimitive);
      delete tilesetHash[entity.id];
    }
  }

  function checkLoad(primitive, entity, tilesetHash) {
    primitive.readyPromise.catch(function (error) {
      console.error(error);
      tilesetHash[entity.id].loadFail = true;
    });
  }

  const defaultEvenColor$1 = Color.WHITE;
  const defaultOddColor$1 = Color.BLACK;
  const defaultRepeat$1 = new Cartesian2(2.0, 2.0);

  /**
   * A {@link MaterialProperty} that maps to checkerboard {@link Material} uniforms.
   * @alias CheckerboardMaterialProperty
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Property|Color} [options.evenColor=Color.WHITE] A Property specifying the first {@link Color}.
   * @param {Property|Color} [options.oddColor=Color.BLACK] A Property specifying the second {@link Color}.
   * @param {Property|Cartesian2} [options.repeat=new Cartesian2(2.0, 2.0)] A {@link Cartesian2} Property specifying how many times the tiles repeat in each direction.
   */
  function CheckerboardMaterialProperty(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    this._definitionChanged = new Event();
    this._evenColor = undefined;
    this._evenColorSubscription = undefined;
    this._oddColor = undefined;
    this._oddColorSubscription = undefined;
    this._repeat = undefined;
    this._repeatSubscription = undefined;

    this.evenColor = options.evenColor;
    this.oddColor = options.oddColor;
    this.repeat = options.repeat;
  }

  Object.defineProperties(CheckerboardMaterialProperty.prototype, {
    /**
     * Gets a value indicating if this property is constant.  A property is considered
     * constant if getValue always returns the same result for the current definition.
     * @memberof CheckerboardMaterialProperty.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    isConstant: {
      get: function () {
        return (
          Property.isConstant(this._evenColor) && //
          Property.isConstant(this._oddColor) && //
          Property.isConstant(this._repeat)
        );
      },
    },

    /**
     * Gets the event that is raised whenever the definition of this property changes.
     * The definition is considered to have changed if a call to getValue would return
     * a different result for the same time.
     * @memberof CheckerboardMaterialProperty.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },

    /**
     * Gets or sets the Property specifying the first {@link Color}.
     * @memberof CheckerboardMaterialProperty.prototype
     * @type {Property|undefined}
     * @default Color.WHITE
     */
    evenColor: createPropertyDescriptor("evenColor"),

    /**
     * Gets or sets the Property specifying the second {@link Color}.
     * @memberof CheckerboardMaterialProperty.prototype
     * @type {Property|undefined}
     * @default Color.BLACK
     */
    oddColor: createPropertyDescriptor("oddColor"),

    /**
     * Gets or sets the {@link Cartesian2} Property specifying how many times the tiles repeat in each direction.
     * @memberof CheckerboardMaterialProperty.prototype
     * @type {Property|undefined}
     * @default new Cartesian2(2.0, 2.0)
     */
    repeat: createPropertyDescriptor("repeat"),
  });

  /**
   * Gets the {@link Material} type at the provided time.
   *
   * @param {JulianDate} time The time for which to retrieve the type.
   * @returns {String} The type of material.
   */
  CheckerboardMaterialProperty.prototype.getType = function (time) {
    return "Checkerboard";
  };

  /**
   * Gets the value of the property at the provided time.
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {Object} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Object} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  CheckerboardMaterialProperty.prototype.getValue = function (time, result) {
    if (!defined(result)) {
      result = {};
    }
    result.lightColor = Property.getValueOrClonedDefault(
      this._evenColor,
      time,
      defaultEvenColor$1,
      result.lightColor
    );
    result.darkColor = Property.getValueOrClonedDefault(
      this._oddColor,
      time,
      defaultOddColor$1,
      result.darkColor
    );
    result.repeat = Property.getValueOrDefault(this._repeat, time, defaultRepeat$1);
    return result;
  };

  /**
   * Compares this property to the provided property and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Property} [other] The other property.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  CheckerboardMaterialProperty.prototype.equals = function (other) {
    return (
      this === other || //
      (other instanceof CheckerboardMaterialProperty && //
        Property.equals(this._evenColor, other._evenColor) && //
        Property.equals(this._oddColor, other._oddColor) && //
        Property.equals(this._repeat, other._repeat))
    );
  };

  const entityOptionsScratch$1 = {
    id: undefined,
  };

  function fireChangedEvent(collection) {
    if (collection._firing) {
      collection._refire = true;
      return;
    }

    if (collection._suspendCount === 0) {
      const added = collection._addedEntities;
      const removed = collection._removedEntities;
      const changed = collection._changedEntities;
      if (changed.length !== 0 || added.length !== 0 || removed.length !== 0) {
        collection._firing = true;
        do {
          collection._refire = false;
          const addedArray = added.values.slice(0);
          const removedArray = removed.values.slice(0);
          const changedArray = changed.values.slice(0);

          added.removeAll();
          removed.removeAll();
          changed.removeAll();
          collection._collectionChanged.raiseEvent(
            collection,
            addedArray,
            removedArray,
            changedArray
          );
        } while (collection._refire);
        collection._firing = false;
      }
    }
  }

  /**
   * An observable collection of {@link Entity} instances where each entity has a unique id.
   * @alias EntityCollection
   * @constructor
   *
   * @param {DataSource|CompositeEntityCollection} [owner] The data source (or composite entity collection) which created this collection.
   */
  function EntityCollection(owner) {
    this._owner = owner;
    this._entities = new AssociativeArray();
    this._addedEntities = new AssociativeArray();
    this._removedEntities = new AssociativeArray();
    this._changedEntities = new AssociativeArray();
    this._suspendCount = 0;
    this._collectionChanged = new Event();
    this._id = createGuid();
    this._show = true;
    this._firing = false;
    this._refire = false;
  }

  /**
   * Prevents {@link EntityCollection#collectionChanged} events from being raised
   * until a corresponding call is made to {@link EntityCollection#resumeEvents}, at which
   * point a single event will be raised that covers all suspended operations.
   * This allows for many items to be added and removed efficiently.
   * This function can be safely called multiple times as long as there
   * are corresponding calls to {@link EntityCollection#resumeEvents}.
   */
  EntityCollection.prototype.suspendEvents = function () {
    this._suspendCount++;
  };

  /**
   * Resumes raising {@link EntityCollection#collectionChanged} events immediately
   * when an item is added or removed.  Any modifications made while while events were suspended
   * will be triggered as a single event when this function is called.
   * This function is reference counted and can safely be called multiple times as long as there
   * are corresponding calls to {@link EntityCollection#resumeEvents}.
   *
   * @exception {DeveloperError} resumeEvents can not be called before suspendEvents.
   */
  EntityCollection.prototype.resumeEvents = function () {
    //>>includeStart('debug', pragmas.debug);
    if (this._suspendCount === 0) {
      throw new DeveloperError(
        "resumeEvents can not be called before suspendEvents."
      );
    }
    //>>includeEnd('debug');

    this._suspendCount--;
    fireChangedEvent(this);
  };

  /**
   * The signature of the event generated by {@link EntityCollection#collectionChanged}.
   * @callback EntityCollection.CollectionChangedEventCallback
   *
   * @param {EntityCollection} collection The collection that triggered the event.
   * @param {Entity[]} added The array of {@link Entity} instances that have been added to the collection.
   * @param {Entity[]} removed The array of {@link Entity} instances that have been removed from the collection.
   * @param {Entity[]} changed The array of {@link Entity} instances that have been modified.
   */

  Object.defineProperties(EntityCollection.prototype, {
    /**
     * Gets the event that is fired when entities are added or removed from the collection.
     * The generated event is a {@link EntityCollection.CollectionChangedEventCallback}.
     * @memberof EntityCollection.prototype
     * @readonly
     * @type {Event<EntityCollection.CollectionChangedEventCallback>}
     */
    collectionChanged: {
      get: function () {
        return this._collectionChanged;
      },
    },
    /**
     * Gets a globally unique identifier for this collection.
     * @memberof EntityCollection.prototype
     * @readonly
     * @type {String}
     */
    id: {
      get: function () {
        return this._id;
      },
    },
    /**
     * Gets the array of Entity instances in the collection.
     * This array should not be modified directly.
     * @memberof EntityCollection.prototype
     * @readonly
     * @type {Entity[]}
     */
    values: {
      get: function () {
        return this._entities.values;
      },
    },
    /**
     * Gets whether or not this entity collection should be
     * displayed.  When true, each entity is only displayed if
     * its own show property is also true.
     * @memberof EntityCollection.prototype
     * @type {Boolean}
     */
    show: {
      get: function () {
        return this._show;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        if (value === this._show) {
          return;
        }

        //Since entity.isShowing includes the EntityCollection.show state
        //in its calculation, we need to loop over the entities array
        //twice, once to get the old showing value and a second time
        //to raise the changed event.
        this.suspendEvents();

        let i;
        const oldShows = [];
        const entities = this._entities.values;
        const entitiesLength = entities.length;

        for (i = 0; i < entitiesLength; i++) {
          oldShows.push(entities[i].isShowing);
        }

        this._show = value;

        for (i = 0; i < entitiesLength; i++) {
          const oldShow = oldShows[i];
          const entity = entities[i];
          if (oldShow !== entity.isShowing) {
            entity.definitionChanged.raiseEvent(
              entity,
              "isShowing",
              entity.isShowing,
              oldShow
            );
          }
        }

        this.resumeEvents();
      },
    },
    /**
     * Gets the owner of this entity collection, ie. the data source or composite entity collection which created it.
     * @memberof EntityCollection.prototype
     * @readonly
     * @type {DataSource|CompositeEntityCollection}
     */
    owner: {
      get: function () {
        return this._owner;
      },
    },
  });

  /**
   * Computes the maximum availability of the entities in the collection.
   * If the collection contains a mix of infinitely available data and non-infinite data,
   * it will return the interval pertaining to the non-infinite data only.  If all
   * data is infinite, an infinite interval will be returned.
   *
   * @returns {TimeInterval} The availability of entities in the collection.
   */
  EntityCollection.prototype.computeAvailability = function () {
    let startTime = Iso8601.MAXIMUM_VALUE;
    let stopTime = Iso8601.MINIMUM_VALUE;
    const entities = this._entities.values;
    for (let i = 0, len = entities.length; i < len; i++) {
      const entity = entities[i];
      const availability = entity.availability;
      if (defined(availability)) {
        const start = availability.start;
        const stop = availability.stop;
        if (
          JulianDate.lessThan(start, startTime) &&
          !start.equals(Iso8601.MINIMUM_VALUE)
        ) {
          startTime = start;
        }
        if (
          JulianDate.greaterThan(stop, stopTime) &&
          !stop.equals(Iso8601.MAXIMUM_VALUE)
        ) {
          stopTime = stop;
        }
      }
    }

    if (Iso8601.MAXIMUM_VALUE.equals(startTime)) {
      startTime = Iso8601.MINIMUM_VALUE;
    }
    if (Iso8601.MINIMUM_VALUE.equals(stopTime)) {
      stopTime = Iso8601.MAXIMUM_VALUE;
    }
    return new TimeInterval({
      start: startTime,
      stop: stopTime,
    });
  };

  /**
   * Add an entity to the collection.
   *
   * @param {Entity | Entity.ConstructorOptions} entity The entity to be added.
   * @returns {Entity} The entity that was added.
   * @exception {DeveloperError} An entity with <entity.id> already exists in this collection.
   */
  EntityCollection.prototype.add = function (entity) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(entity)) {
      throw new DeveloperError("entity is required.");
    }
    //>>includeEnd('debug');

    if (!(entity instanceof Entity)) {
      entity = new Entity(entity);
    }

    const id = entity.id;
    const entities = this._entities;
    if (entities.contains(id)) {
      throw new RuntimeError(
        `An entity with id ${id} already exists in this collection.`
      );
    }

    entity.entityCollection = this;
    entities.set(id, entity);

    if (!this._removedEntities.remove(id)) {
      this._addedEntities.set(id, entity);
    }
    entity.definitionChanged.addEventListener(
      EntityCollection.prototype._onEntityDefinitionChanged,
      this
    );

    fireChangedEvent(this);
    return entity;
  };

  /**
   * Removes an entity from the collection.
   *
   * @param {Entity} entity The entity to be removed.
   * @returns {Boolean} true if the item was removed, false if it did not exist in the collection.
   */
  EntityCollection.prototype.remove = function (entity) {
    if (!defined(entity)) {
      return false;
    }
    return this.removeById(entity.id);
  };

  /**
   * Returns true if the provided entity is in this collection, false otherwise.
   *
   * @param {Entity} entity The entity.
   * @returns {Boolean} true if the provided entity is in this collection, false otherwise.
   */
  EntityCollection.prototype.contains = function (entity) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(entity)) {
      throw new DeveloperError("entity is required");
    }
    //>>includeEnd('debug');
    return this._entities.get(entity.id) === entity;
  };

  /**
   * Removes an entity with the provided id from the collection.
   *
   * @param {String} id The id of the entity to remove.
   * @returns {Boolean} true if the item was removed, false if no item with the provided id existed in the collection.
   */
  EntityCollection.prototype.removeById = function (id) {
    if (!defined(id)) {
      return false;
    }

    const entities = this._entities;
    const entity = entities.get(id);
    if (!this._entities.remove(id)) {
      return false;
    }

    if (!this._addedEntities.remove(id)) {
      this._removedEntities.set(id, entity);
      this._changedEntities.remove(id);
    }
    this._entities.remove(id);
    entity.definitionChanged.removeEventListener(
      EntityCollection.prototype._onEntityDefinitionChanged,
      this
    );
    fireChangedEvent(this);

    return true;
  };

  /**
   * Removes all Entities from the collection.
   */
  EntityCollection.prototype.removeAll = function () {
    //The event should only contain items added before events were suspended
    //and the contents of the collection.
    const entities = this._entities;
    const entitiesLength = entities.length;
    const array = entities.values;

    const addedEntities = this._addedEntities;
    const removed = this._removedEntities;

    for (let i = 0; i < entitiesLength; i++) {
      const existingItem = array[i];
      const existingItemId = existingItem.id;
      const addedItem = addedEntities.get(existingItemId);
      if (!defined(addedItem)) {
        existingItem.definitionChanged.removeEventListener(
          EntityCollection.prototype._onEntityDefinitionChanged,
          this
        );
        removed.set(existingItemId, existingItem);
      }
    }

    entities.removeAll();
    addedEntities.removeAll();
    this._changedEntities.removeAll();
    fireChangedEvent(this);
  };

  /**
   * Gets an entity with the specified id.
   *
   * @param {String} id The id of the entity to retrieve.
   * @returns {Entity|undefined} The entity with the provided id or undefined if the id did not exist in the collection.
   */
  EntityCollection.prototype.getById = function (id) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(id)) {
      throw new DeveloperError("id is required.");
    }
    //>>includeEnd('debug');

    return this._entities.get(id);
  };

  /**
   * Gets an entity with the specified id or creates it and adds it to the collection if it does not exist.
   *
   * @param {String} id The id of the entity to retrieve or create.
   * @returns {Entity} The new or existing object.
   */
  EntityCollection.prototype.getOrCreateEntity = function (id) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(id)) {
      throw new DeveloperError("id is required.");
    }
    //>>includeEnd('debug');

    let entity = this._entities.get(id);
    if (!defined(entity)) {
      entityOptionsScratch$1.id = id;
      entity = new Entity(entityOptionsScratch$1);
      this.add(entity);
    }
    return entity;
  };

  EntityCollection.prototype._onEntityDefinitionChanged = function (entity) {
    const id = entity.id;
    if (!this._addedEntities.contains(id)) {
      this._changedEntities.set(id, entity);
    }
    fireChangedEvent(this);
  };

  const entityOptionsScratch = {
    id: undefined,
  };
  const entityIdScratch = new Array(2);

  function clean(entity) {
    const propertyNames = entity.propertyNames;
    const propertyNamesLength = propertyNames.length;
    for (let i = 0; i < propertyNamesLength; i++) {
      entity[propertyNames[i]] = undefined;
    }
    entity._name = undefined;
    entity._availability = undefined;
  }

  function subscribeToEntity(that, eventHash, collectionId, entity) {
    entityIdScratch[0] = collectionId;
    entityIdScratch[1] = entity.id;
    eventHash[
      JSON.stringify(entityIdScratch)
    ] = entity.definitionChanged.addEventListener(
      CompositeEntityCollection.prototype._onDefinitionChanged,
      that
    );
  }

  function unsubscribeFromEntity(that, eventHash, collectionId, entity) {
    entityIdScratch[0] = collectionId;
    entityIdScratch[1] = entity.id;
    const id = JSON.stringify(entityIdScratch);
    eventHash[id]();
    eventHash[id] = undefined;
  }

  function recomposite(that) {
    that._shouldRecomposite = true;
    if (that._suspendCount !== 0) {
      return;
    }

    const collections = that._collections;
    const collectionsLength = collections.length;

    const collectionsCopy = that._collectionsCopy;
    const collectionsCopyLength = collectionsCopy.length;

    let i;
    let entity;
    let entities;
    let iEntities;
    let collection;
    const composite = that._composite;
    const newEntities = new EntityCollection(that);
    const eventHash = that._eventHash;
    let collectionId;

    for (i = 0; i < collectionsCopyLength; i++) {
      collection = collectionsCopy[i];
      collection.collectionChanged.removeEventListener(
        CompositeEntityCollection.prototype._onCollectionChanged,
        that
      );
      entities = collection.values;
      collectionId = collection.id;
      for (iEntities = entities.length - 1; iEntities > -1; iEntities--) {
        entity = entities[iEntities];
        unsubscribeFromEntity(that, eventHash, collectionId, entity);
      }
    }

    for (i = collectionsLength - 1; i >= 0; i--) {
      collection = collections[i];
      collection.collectionChanged.addEventListener(
        CompositeEntityCollection.prototype._onCollectionChanged,
        that
      );

      //Merge all of the existing entities.
      entities = collection.values;
      collectionId = collection.id;
      for (iEntities = entities.length - 1; iEntities > -1; iEntities--) {
        entity = entities[iEntities];
        subscribeToEntity(that, eventHash, collectionId, entity);

        let compositeEntity = newEntities.getById(entity.id);
        if (!defined(compositeEntity)) {
          compositeEntity = composite.getById(entity.id);
          if (!defined(compositeEntity)) {
            entityOptionsScratch.id = entity.id;
            compositeEntity = new Entity(entityOptionsScratch);
          } else {
            clean(compositeEntity);
          }
          newEntities.add(compositeEntity);
        }
        compositeEntity.merge(entity);
      }
    }
    that._collectionsCopy = collections.slice(0);

    composite.suspendEvents();
    composite.removeAll();
    const newEntitiesArray = newEntities.values;
    for (i = 0; i < newEntitiesArray.length; i++) {
      composite.add(newEntitiesArray[i]);
    }
    composite.resumeEvents();
  }

  /**
   * Non-destructively composites multiple {@link EntityCollection} instances into a single collection.
   * If a Entity with the same ID exists in multiple collections, it is non-destructively
   * merged into a single new entity instance.  If an entity has the same property in multiple
   * collections, the property of the Entity in the last collection of the list it
   * belongs to is used.  CompositeEntityCollection can be used almost anywhere that a
   * EntityCollection is used.
   *
   * @alias CompositeEntityCollection
   * @constructor
   *
   * @param {EntityCollection[]} [collections] The initial list of EntityCollection instances to merge.
   * @param {DataSource|CompositeEntityCollection} [owner] The data source (or composite entity collection) which created this collection.
   */
  function CompositeEntityCollection(collections, owner) {
    this._owner = owner;
    this._composite = new EntityCollection(this);
    this._suspendCount = 0;
    this._collections = defined(collections) ? collections.slice() : [];
    this._collectionsCopy = [];
    this._id = createGuid();
    this._eventHash = {};
    recomposite(this);
    this._shouldRecomposite = false;
  }

  Object.defineProperties(CompositeEntityCollection.prototype, {
    /**
     * Gets the event that is fired when entities are added or removed from the collection.
     * The generated event is a {@link EntityCollection.collectionChangedEventCallback}.
     * @memberof CompositeEntityCollection.prototype
     * @readonly
     * @type {Event}
     */
    collectionChanged: {
      get: function () {
        return this._composite._collectionChanged;
      },
    },
    /**
     * Gets a globally unique identifier for this collection.
     * @memberof CompositeEntityCollection.prototype
     * @readonly
     * @type {String}
     */
    id: {
      get: function () {
        return this._id;
      },
    },
    /**
     * Gets the array of Entity instances in the collection.
     * This array should not be modified directly.
     * @memberof CompositeEntityCollection.prototype
     * @readonly
     * @type {Entity[]}
     */
    values: {
      get: function () {
        return this._composite.values;
      },
    },
    /**
     * Gets the owner of this composite entity collection, ie. the data source or composite entity collection which created it.
     * @memberof CompositeEntityCollection.prototype
     * @readonly
     * @type {DataSource|CompositeEntityCollection}
     */
    owner: {
      get: function () {
        return this._owner;
      },
    },
  });

  /**
   * Adds a collection to the composite.
   *
   * @param {EntityCollection} collection the collection to add.
   * @param {Number} [index] the index to add the collection at.  If omitted, the collection will
   *                         added on top of all existing collections.
   *
   * @exception {DeveloperError} index, if supplied, must be greater than or equal to zero and less than or equal to the number of collections.
   */
  CompositeEntityCollection.prototype.addCollection = function (
    collection,
    index
  ) {
    const hasIndex = defined(index);
    //>>includeStart('debug', pragmas.debug);
    if (!defined(collection)) {
      throw new DeveloperError("collection is required.");
    }
    if (hasIndex) {
      if (index < 0) {
        throw new DeveloperError("index must be greater than or equal to zero.");
      } else if (index > this._collections.length) {
        throw new DeveloperError(
          "index must be less than or equal to the number of collections."
        );
      }
    }
    //>>includeEnd('debug');

    if (!hasIndex) {
      index = this._collections.length;
      this._collections.push(collection);
    } else {
      this._collections.splice(index, 0, collection);
    }

    recomposite(this);
  };

  /**
   * Removes a collection from this composite, if present.
   *
   * @param {EntityCollection} collection The collection to remove.
   * @returns {Boolean} true if the collection was in the composite and was removed,
   *                    false if the collection was not in the composite.
   */
  CompositeEntityCollection.prototype.removeCollection = function (collection) {
    const index = this._collections.indexOf(collection);
    if (index !== -1) {
      this._collections.splice(index, 1);
      recomposite(this);
      return true;
    }
    return false;
  };

  /**
   * Removes all collections from this composite.
   */
  CompositeEntityCollection.prototype.removeAllCollections = function () {
    this._collections.length = 0;
    recomposite(this);
  };

  /**
   * Checks to see if the composite contains a given collection.
   *
   * @param {EntityCollection} collection the collection to check for.
   * @returns {Boolean} true if the composite contains the collection, false otherwise.
   */
  CompositeEntityCollection.prototype.containsCollection = function (collection) {
    return this._collections.indexOf(collection) !== -1;
  };

  /**
   * Returns true if the provided entity is in this collection, false otherwise.
   *
   * @param {Entity} entity The entity.
   * @returns {Boolean} true if the provided entity is in this collection, false otherwise.
   */
  CompositeEntityCollection.prototype.contains = function (entity) {
    return this._composite.contains(entity);
  };

  /**
   * Determines the index of a given collection in the composite.
   *
   * @param {EntityCollection} collection The collection to find the index of.
   * @returns {Number} The index of the collection in the composite, or -1 if the collection does not exist in the composite.
   */
  CompositeEntityCollection.prototype.indexOfCollection = function (collection) {
    return this._collections.indexOf(collection);
  };

  /**
   * Gets a collection by index from the composite.
   *
   * @param {Number} index the index to retrieve.
   */
  CompositeEntityCollection.prototype.getCollection = function (index) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(index)) {
      throw new DeveloperError("index is required.");
    }
    //>>includeEnd('debug');

    return this._collections[index];
  };

  /**
   * Gets the number of collections in this composite.
   */
  CompositeEntityCollection.prototype.getCollectionsLength = function () {
    return this._collections.length;
  };

  function getCollectionIndex(collections, collection) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(collection)) {
      throw new DeveloperError("collection is required.");
    }
    //>>includeEnd('debug');

    const index = collections.indexOf(collection);

    //>>includeStart('debug', pragmas.debug);
    if (index === -1) {
      throw new DeveloperError("collection is not in this composite.");
    }
    //>>includeEnd('debug');

    return index;
  }

  function swapCollections(composite, i, j) {
    const arr = composite._collections;
    i = CesiumMath.clamp(i, 0, arr.length - 1);
    j = CesiumMath.clamp(j, 0, arr.length - 1);

    if (i === j) {
      return;
    }

    const temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;

    recomposite(composite);
  }

  /**
   * Raises a collection up one position in the composite.
   *
   * @param {EntityCollection} collection the collection to move.
   *
   * @exception {DeveloperError} collection is not in this composite.
   */
  CompositeEntityCollection.prototype.raiseCollection = function (collection) {
    const index = getCollectionIndex(this._collections, collection);
    swapCollections(this, index, index + 1);
  };

  /**
   * Lowers a collection down one position in the composite.
   *
   * @param {EntityCollection} collection the collection to move.
   *
   * @exception {DeveloperError} collection is not in this composite.
   */
  CompositeEntityCollection.prototype.lowerCollection = function (collection) {
    const index = getCollectionIndex(this._collections, collection);
    swapCollections(this, index, index - 1);
  };

  /**
   * Raises a collection to the top of the composite.
   *
   * @param {EntityCollection} collection the collection to move.
   *
   * @exception {DeveloperError} collection is not in this composite.
   */
  CompositeEntityCollection.prototype.raiseCollectionToTop = function (
    collection
  ) {
    const index = getCollectionIndex(this._collections, collection);
    if (index === this._collections.length - 1) {
      return;
    }
    this._collections.splice(index, 1);
    this._collections.push(collection);

    recomposite(this);
  };

  /**
   * Lowers a collection to the bottom of the composite.
   *
   * @param {EntityCollection} collection the collection to move.
   *
   * @exception {DeveloperError} collection is not in this composite.
   */
  CompositeEntityCollection.prototype.lowerCollectionToBottom = function (
    collection
  ) {
    const index = getCollectionIndex(this._collections, collection);
    if (index === 0) {
      return;
    }
    this._collections.splice(index, 1);
    this._collections.splice(0, 0, collection);

    recomposite(this);
  };

  /**
   * Prevents {@link EntityCollection#collectionChanged} events from being raised
   * until a corresponding call is made to {@link EntityCollection#resumeEvents}, at which
   * point a single event will be raised that covers all suspended operations.
   * This allows for many items to be added and removed efficiently.
   * While events are suspended, recompositing of the collections will
   * also be suspended, as this can be a costly operation.
   * This function can be safely called multiple times as long as there
   * are corresponding calls to {@link EntityCollection#resumeEvents}.
   */
  CompositeEntityCollection.prototype.suspendEvents = function () {
    this._suspendCount++;
    this._composite.suspendEvents();
  };

  /**
   * Resumes raising {@link EntityCollection#collectionChanged} events immediately
   * when an item is added or removed.  Any modifications made while while events were suspended
   * will be triggered as a single event when this function is called.  This function also ensures
   * the collection is recomposited if events are also resumed.
   * This function is reference counted and can safely be called multiple times as long as there
   * are corresponding calls to {@link EntityCollection#resumeEvents}.
   *
   * @exception {DeveloperError} resumeEvents can not be called before suspendEvents.
   */
  CompositeEntityCollection.prototype.resumeEvents = function () {
    //>>includeStart('debug', pragmas.debug);
    if (this._suspendCount === 0) {
      throw new DeveloperError(
        "resumeEvents can not be called before suspendEvents."
      );
    }
    //>>includeEnd('debug');

    this._suspendCount--;
    // recomposite before triggering events (but only if required for performance) that might depend on a composited collection
    if (this._shouldRecomposite && this._suspendCount === 0) {
      recomposite(this);
      this._shouldRecomposite = false;
    }

    this._composite.resumeEvents();
  };

  /**
   * Computes the maximum availability of the entities in the collection.
   * If the collection contains a mix of infinitely available data and non-infinite data,
   * It will return the interval pertaining to the non-infinite data only.  If all
   * data is infinite, an infinite interval will be returned.
   *
   * @returns {TimeInterval} The availability of entities in the collection.
   */
  CompositeEntityCollection.prototype.computeAvailability = function () {
    return this._composite.computeAvailability();
  };

  /**
   * Gets an entity with the specified id.
   *
   * @param {String} id The id of the entity to retrieve.
   * @returns {Entity|undefined} The entity with the provided id or undefined if the id did not exist in the collection.
   */
  CompositeEntityCollection.prototype.getById = function (id) {
    return this._composite.getById(id);
  };

  CompositeEntityCollection.prototype._onCollectionChanged = function (
    collection,
    added,
    removed
  ) {
    const collections = this._collectionsCopy;
    const collectionsLength = collections.length;
    const composite = this._composite;
    composite.suspendEvents();

    let i;
    let q;
    let entity;
    let compositeEntity;
    const removedLength = removed.length;
    const eventHash = this._eventHash;
    const collectionId = collection.id;
    for (i = 0; i < removedLength; i++) {
      const removedEntity = removed[i];
      unsubscribeFromEntity(this, eventHash, collectionId, removedEntity);

      const removedId = removedEntity.id;
      //Check if the removed entity exists in any of the remaining collections
      //If so, we clean and remerge it.
      for (q = collectionsLength - 1; q >= 0; q--) {
        entity = collections[q].getById(removedId);
        if (defined(entity)) {
          if (!defined(compositeEntity)) {
            compositeEntity = composite.getById(removedId);
            clean(compositeEntity);
          }
          compositeEntity.merge(entity);
        }
      }
      //We never retrieved the compositeEntity, which means it no longer
      //exists in any of the collections, remove it from the composite.
      if (!defined(compositeEntity)) {
        composite.removeById(removedId);
      }
      compositeEntity = undefined;
    }

    const addedLength = added.length;
    for (i = 0; i < addedLength; i++) {
      const addedEntity = added[i];
      subscribeToEntity(this, eventHash, collectionId, addedEntity);

      const addedId = addedEntity.id;
      //We know the added entity exists in at least one collection,
      //but we need to check all collections and re-merge in order
      //to maintain the priority of properties.
      for (q = collectionsLength - 1; q >= 0; q--) {
        entity = collections[q].getById(addedId);
        if (defined(entity)) {
          if (!defined(compositeEntity)) {
            compositeEntity = composite.getById(addedId);
            if (!defined(compositeEntity)) {
              entityOptionsScratch.id = addedId;
              compositeEntity = new Entity(entityOptionsScratch);
              composite.add(compositeEntity);
            } else {
              clean(compositeEntity);
            }
          }
          compositeEntity.merge(entity);
        }
      }
      compositeEntity = undefined;
    }

    composite.resumeEvents();
  };

  CompositeEntityCollection.prototype._onDefinitionChanged = function (
    entity,
    propertyName,
    newValue,
    oldValue
  ) {
    const collections = this._collections;
    const composite = this._composite;

    const collectionsLength = collections.length;
    const id = entity.id;
    const compositeEntity = composite.getById(id);
    let compositeProperty = compositeEntity[propertyName];
    const newProperty = !defined(compositeProperty);

    let firstTime = true;
    for (let q = collectionsLength - 1; q >= 0; q--) {
      const innerEntity = collections[q].getById(entity.id);
      if (defined(innerEntity)) {
        const property = innerEntity[propertyName];
        if (defined(property)) {
          if (firstTime) {
            firstTime = false;
            //We only want to clone if the property is also mergeable.
            //This ensures that leaf properties are referenced and not copied,
            //which is the entire point of compositing.
            if (defined(property.merge) && defined(property.clone)) {
              compositeProperty = property.clone(compositeProperty);
            } else {
              compositeProperty = property;
              break;
            }
          }
          compositeProperty.merge(property);
        }
      }
    }

    if (
      newProperty &&
      compositeEntity.propertyNames.indexOf(propertyName) === -1
    ) {
      compositeEntity.addProperty(propertyName);
    }

    compositeEntity[propertyName] = compositeProperty;
  };

  function subscribeAll(property, eventHelper, definitionChanged, intervals) {
    function callback() {
      definitionChanged.raiseEvent(property);
    }
    const items = [];
    eventHelper.removeAll();
    const length = intervals.length;
    for (let i = 0; i < length; i++) {
      const interval = intervals.get(i);
      if (defined(interval.data) && items.indexOf(interval.data) === -1) {
        eventHelper.add(interval.data.definitionChanged, callback);
      }
    }
  }

  /**
   * A {@link Property} which is defined by a {@link TimeIntervalCollection}, where the
   * data property of each {@link TimeInterval} is another Property instance which is
   * evaluated at the provided time.
   *
   * @alias CompositeProperty
   * @constructor
   *
   *
   * @example
   * const constantProperty = ...;
   * const sampledProperty = ...;
   *
   * //Create a composite property from two previously defined properties
   * //where the property is valid on August 1st, 2012 and uses a constant
   * //property for the first half of the day and a sampled property for the
   * //remaining half.
   * const composite = new Cesium.CompositeProperty();
   * composite.intervals.addInterval(Cesium.TimeInterval.fromIso8601({
   *     iso8601 : '2012-08-01T00:00:00.00Z/2012-08-01T12:00:00.00Z',
   *     data : constantProperty
   * }));
   * composite.intervals.addInterval(Cesium.TimeInterval.fromIso8601({
   *     iso8601 : '2012-08-01T12:00:00.00Z/2012-08-02T00:00:00.00Z',
   *     isStartIncluded : false,
   *     isStopIncluded : false,
   *     data : sampledProperty
   * }));
   *
   * @see CompositeMaterialProperty
   * @see CompositePositionProperty
   */
  function CompositeProperty() {
    this._eventHelper = new EventHelper();
    this._definitionChanged = new Event();
    this._intervals = new TimeIntervalCollection();
    this._intervals.changedEvent.addEventListener(
      CompositeProperty.prototype._intervalsChanged,
      this
    );
  }

  Object.defineProperties(CompositeProperty.prototype, {
    /**
     * Gets a value indicating if this property is constant.  A property is considered
     * constant if getValue always returns the same result for the current definition.
     * @memberof CompositeProperty.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    isConstant: {
      get: function () {
        return this._intervals.isEmpty;
      },
    },
    /**
     * Gets the event that is raised whenever the definition of this property changes.
     * The definition is changed whenever setValue is called with data different
     * than the current value.
     * @memberof CompositeProperty.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },
    /**
     * Gets the interval collection.
     * @memberof CompositeProperty.prototype
     *
     * @type {TimeIntervalCollection}
     */
    intervals: {
      get: function () {
        return this._intervals;
      },
    },
  });

  /**
   * Gets the value of the property at the provided time.
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {Object} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Object} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  CompositeProperty.prototype.getValue = function (time, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(time)) {
      throw new DeveloperError("time is required");
    }
    //>>includeEnd('debug');

    const innerProperty = this._intervals.findDataForIntervalContainingDate(time);
    if (defined(innerProperty)) {
      return innerProperty.getValue(time, result);
    }
    return undefined;
  };

  /**
   * Compares this property to the provided property and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Property} [other] The other property.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  CompositeProperty.prototype.equals = function (other) {
    return (
      this === other || //
      (other instanceof CompositeProperty && //
        this._intervals.equals(other._intervals, Property.equals))
    );
  };

  /**
   * @private
   */
  CompositeProperty.prototype._intervalsChanged = function () {
    subscribeAll(
      this,
      this._eventHelper,
      this._definitionChanged,
      this._intervals
    );
    this._definitionChanged.raiseEvent(this);
  };

  /**
   * A {@link CompositeProperty} which is also a {@link MaterialProperty}.
   *
   * @alias CompositeMaterialProperty
   * @constructor
   */
  function CompositeMaterialProperty() {
    this._definitionChanged = new Event();
    this._composite = new CompositeProperty();
    this._composite.definitionChanged.addEventListener(
      CompositeMaterialProperty.prototype._raiseDefinitionChanged,
      this
    );
  }

  Object.defineProperties(CompositeMaterialProperty.prototype, {
    /**
     * Gets a value indicating if this property is constant.  A property is considered
     * constant if getValue always returns the same result for the current definition.
     * @memberof CompositeMaterialProperty.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    isConstant: {
      get: function () {
        return this._composite.isConstant;
      },
    },
    /**
     * Gets the event that is raised whenever the definition of this property changes.
     * The definition is changed whenever setValue is called with data different
     * than the current value.
     * @memberof CompositeMaterialProperty.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },
    /**
     * Gets the interval collection.
     * @memberof CompositeMaterialProperty.prototype
     *
     * @type {TimeIntervalCollection}
     */
    intervals: {
      get: function () {
        return this._composite._intervals;
      },
    },
  });

  /**
   * Gets the {@link Material} type at the provided time.
   *
   * @param {JulianDate} time The time for which to retrieve the type.
   * @returns {String} The type of material.
   */
  CompositeMaterialProperty.prototype.getType = function (time) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(time)) {
      throw new DeveloperError("time is required");
    }
    //>>includeEnd('debug');

    const innerProperty = this._composite._intervals.findDataForIntervalContainingDate(
      time
    );
    if (defined(innerProperty)) {
      return innerProperty.getType(time);
    }
    return undefined;
  };

  /**
   * Gets the value of the property at the provided time.
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {Object} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Object} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  CompositeMaterialProperty.prototype.getValue = function (time, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(time)) {
      throw new DeveloperError("time is required");
    }
    //>>includeEnd('debug');

    const innerProperty = this._composite._intervals.findDataForIntervalContainingDate(
      time
    );
    if (defined(innerProperty)) {
      return innerProperty.getValue(time, result);
    }
    return undefined;
  };

  /**
   * Compares this property to the provided property and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Property} [other] The other property.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  CompositeMaterialProperty.prototype.equals = function (other) {
    return (
      this === other || //
      (other instanceof CompositeMaterialProperty && //
        this._composite.equals(other._composite, Property.equals))
    );
  };

  /**
   * @private
   */
  CompositeMaterialProperty.prototype._raiseDefinitionChanged = function () {
    this._definitionChanged.raiseEvent(this);
  };

  /**
   * A {@link CompositeProperty} which is also a {@link PositionProperty}.
   *
   * @alias CompositePositionProperty
   * @constructor
   *
   * @param {ReferenceFrame} [referenceFrame=ReferenceFrame.FIXED] The reference frame in which the position is defined.
   */
  function CompositePositionProperty(referenceFrame) {
    this._referenceFrame = defaultValue(referenceFrame, ReferenceFrame$1.FIXED);
    this._definitionChanged = new Event();
    this._composite = new CompositeProperty();
    this._composite.definitionChanged.addEventListener(
      CompositePositionProperty.prototype._raiseDefinitionChanged,
      this
    );
  }

  Object.defineProperties(CompositePositionProperty.prototype, {
    /**
     * Gets a value indicating if this property is constant.  A property is considered
     * constant if getValue always returns the same result for the current definition.
     * @memberof CompositePositionProperty.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    isConstant: {
      get: function () {
        return this._composite.isConstant;
      },
    },
    /**
     * Gets the event that is raised whenever the definition of this property changes.
     * The definition is changed whenever setValue is called with data different
     * than the current value.
     * @memberof CompositePositionProperty.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },
    /**
     * Gets the interval collection.
     * @memberof CompositePositionProperty.prototype
     *
     * @type {TimeIntervalCollection}
     */
    intervals: {
      get: function () {
        return this._composite.intervals;
      },
    },
    /**
     * Gets or sets the reference frame which this position presents itself as.
     * Each PositionProperty making up this object has it's own reference frame,
     * so this property merely exposes a "preferred" reference frame for clients
     * to use.
     * @memberof CompositePositionProperty.prototype
     *
     * @type {ReferenceFrame}
     */
    referenceFrame: {
      get: function () {
        return this._referenceFrame;
      },
      set: function (value) {
        this._referenceFrame = value;
      },
    },
  });

  /**
   * Gets the value of the property at the provided time in the fixed frame.
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {Cartesian3} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Cartesian3 | undefined} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  CompositePositionProperty.prototype.getValue = function (time, result) {
    return this.getValueInReferenceFrame(time, ReferenceFrame$1.FIXED, result);
  };

  /**
   * Gets the value of the property at the provided time and in the provided reference frame.
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {ReferenceFrame} referenceFrame The desired referenceFrame of the result.
   * @param {Cartesian3} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Cartesian3 | undefined} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  CompositePositionProperty.prototype.getValueInReferenceFrame = function (
    time,
    referenceFrame,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(time)) {
      throw new DeveloperError("time is required.");
    }
    if (!defined(referenceFrame)) {
      throw new DeveloperError("referenceFrame is required.");
    }
    //>>includeEnd('debug');

    const innerProperty = this._composite._intervals.findDataForIntervalContainingDate(
      time
    );
    if (defined(innerProperty)) {
      return innerProperty.getValueInReferenceFrame(time, referenceFrame, result);
    }
    return undefined;
  };

  /**
   * Compares this property to the provided property and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Property} [other] The other property.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  CompositePositionProperty.prototype.equals = function (other) {
    return (
      this === other || //
      (other instanceof CompositePositionProperty && //
        this._referenceFrame === other._referenceFrame && //
        this._composite.equals(other._composite, Property.equals))
    );
  };

  /**
   * @private
   */
  CompositePositionProperty.prototype._raiseDefinitionChanged = function () {
    this._definitionChanged.raiseEvent(this);
  };

  const defaultZIndex$1 = new ConstantProperty(0);

  /**
   * An abstract class for updating ground geometry entities.
   * @constructor
   * @alias GroundGeometryUpdater
   * @param {Object} options An object with the following properties:
   * @param {Entity} options.entity The entity containing the geometry to be visualized.
   * @param {Scene} options.scene The scene where visualization is taking place.
   * @param {Object} options.geometryOptions Options for the geometry
   * @param {String} options.geometryPropertyName The geometry property name
   * @param {String[]} options.observedPropertyNames The entity properties this geometry cares about
   */
  function GroundGeometryUpdater(options) {
    GeometryUpdater.call(this, options);

    this._zIndex = 0;
    this._terrainOffsetProperty = undefined;
  }

  if (defined(Object.create)) {
    GroundGeometryUpdater.prototype = Object.create(GeometryUpdater.prototype);
    GroundGeometryUpdater.prototype.constructor = GroundGeometryUpdater;
  }

  Object.defineProperties(GroundGeometryUpdater.prototype, {
    /**
     * Gets the zindex
     * @type {Number}
     * @memberof GroundGeometryUpdater.prototype
     * @readonly
     */
    zIndex: {
      get: function () {
        return this._zIndex;
      },
    },

    /**
     * Gets the terrain offset property
     * @type {TerrainOffsetProperty}
     * @memberof GroundGeometryUpdater.prototype
     * @readonly
     * @private
     */
    terrainOffsetProperty: {
      get: function () {
        return this._terrainOffsetProperty;
      },
    },
  });

  GroundGeometryUpdater.prototype._isOnTerrain = function (entity, geometry) {
    return (
      this._fillEnabled &&
      !defined(geometry.height) &&
      !defined(geometry.extrudedHeight) &&
      GroundPrimitive.isSupported(this._scene)
    );
  };

  GroundGeometryUpdater.prototype._getIsClosed = function (options) {
    const height = options.height;
    const extrudedHeight = options.extrudedHeight;
    return height === 0 || (defined(extrudedHeight) && extrudedHeight !== height);
  };

  GroundGeometryUpdater.prototype._computeCenter =
    DeveloperError.throwInstantiationError;

  GroundGeometryUpdater.prototype._onEntityPropertyChanged = function (
    entity,
    propertyName,
    newValue,
    oldValue
  ) {
    GeometryUpdater.prototype._onEntityPropertyChanged.call(
      this,
      entity,
      propertyName,
      newValue,
      oldValue
    );
    if (this._observedPropertyNames.indexOf(propertyName) === -1) {
      return;
    }

    const geometry = this._entity[this._geometryPropertyName];
    if (!defined(geometry)) {
      return;
    }
    if (
      defined(geometry.zIndex) &&
      (defined(geometry.height) || defined(geometry.extrudedHeight))
    ) {
      oneTimeWarning(oneTimeWarning.geometryZIndex);
    }

    this._zIndex = defaultValue(geometry.zIndex, defaultZIndex$1);

    if (defined(this._terrainOffsetProperty)) {
      this._terrainOffsetProperty.destroy();
      this._terrainOffsetProperty = undefined;
    }

    const heightReferenceProperty = geometry.heightReference;
    const extrudedHeightReferenceProperty = geometry.extrudedHeightReference;

    if (
      defined(heightReferenceProperty) ||
      defined(extrudedHeightReferenceProperty)
    ) {
      const centerPosition = new CallbackProperty(
        this._computeCenter.bind(this),
        !this._dynamic
      );
      this._terrainOffsetProperty = new TerrainOffsetProperty(
        this._scene,
        centerPosition,
        heightReferenceProperty,
        extrudedHeightReferenceProperty
      );
    }
  };

  /**
   * Destroys and resources used by the object.  Once an object is destroyed, it should not be used.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   */
  GroundGeometryUpdater.prototype.destroy = function () {
    if (defined(this._terrainOffsetProperty)) {
      this._terrainOffsetProperty.destroy();
      this._terrainOffsetProperty = undefined;
    }

    GeometryUpdater.prototype.destroy.call(this);
  };

  /**
   * @private
   */
  GroundGeometryUpdater.getGeometryHeight = function (height, heightReference) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("heightReference", heightReference);
    //>>includeEnd('debug');
    if (!defined(height)) {
      if (heightReference !== HeightReference$1.NONE) {
        oneTimeWarning(oneTimeWarning.geometryHeightReference);
      }
      return;
    }

    if (heightReference !== HeightReference$1.CLAMP_TO_GROUND) {
      return height;
    }
    return 0.0;
  };

  /**
   * @private
   */
  GroundGeometryUpdater.getGeometryExtrudedHeight = function (
    extrudedHeight,
    extrudedHeightReference
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("extrudedHeightReference", extrudedHeightReference);
    //>>includeEnd('debug');
    if (!defined(extrudedHeight)) {
      if (extrudedHeightReference !== HeightReference$1.NONE) {
        oneTimeWarning(oneTimeWarning.geometryExtrudedHeightReference);
      }
      return;
    }
    if (extrudedHeightReference !== HeightReference$1.CLAMP_TO_GROUND) {
      return extrudedHeight;
    }

    return GroundGeometryUpdater.CLAMP_TO_GROUND;
  };

  /**
   * @private
   */
  GroundGeometryUpdater.CLAMP_TO_GROUND = "clamp";

  /**
   * @private
   */
  GroundGeometryUpdater.computeGeometryOffsetAttribute = function (
    height,
    heightReference,
    extrudedHeight,
    extrudedHeightReference
  ) {
    if (!defined(height) || !defined(heightReference)) {
      heightReference = HeightReference$1.NONE;
    }
    if (!defined(extrudedHeight) || !defined(extrudedHeightReference)) {
      extrudedHeightReference = HeightReference$1.NONE;
    }
    let n = 0;
    if (heightReference !== HeightReference$1.NONE) {
      n++;
    }
    if (extrudedHeightReference === HeightReference$1.RELATIVE_TO_GROUND) {
      n++;
    }
    if (n === 2) {
      return GeometryOffsetAttribute$1.ALL;
    }
    if (n === 1) {
      return GeometryOffsetAttribute$1.TOP;
    }

    return undefined;
  };

  const scratchColor$d = new Color();
  const defaultOffset$9 = Cartesian3.ZERO;
  const offsetScratch$8 = new Cartesian3();
  const scratchRectangle$4 = new Rectangle();

  function CorridorGeometryOptions(entity) {
    this.id = entity;
    this.vertexFormat = undefined;
    this.positions = undefined;
    this.width = undefined;
    this.cornerType = undefined;
    this.height = undefined;
    this.extrudedHeight = undefined;
    this.granularity = undefined;
    this.offsetAttribute = undefined;
  }

  /**
   * A {@link GeometryUpdater} for corridors.
   * Clients do not normally create this class directly, but instead rely on {@link DataSourceDisplay}.
   * @alias CorridorGeometryUpdater
   * @constructor
   *
   * @param {Entity} entity The entity containing the geometry to be visualized.
   * @param {Scene} scene The scene where visualization is taking place.
   */
  function CorridorGeometryUpdater(entity, scene) {
    GroundGeometryUpdater.call(this, {
      entity: entity,
      scene: scene,
      geometryOptions: new CorridorGeometryOptions(entity),
      geometryPropertyName: "corridor",
      observedPropertyNames: ["availability", "corridor"],
    });

    this._onEntityPropertyChanged(entity, "corridor", entity.corridor, undefined);
  }

  if (defined(Object.create)) {
    CorridorGeometryUpdater.prototype = Object.create(
      GroundGeometryUpdater.prototype
    );
    CorridorGeometryUpdater.prototype.constructor = CorridorGeometryUpdater;
  }

  /**
   * Creates the geometry instance which represents the fill of the geometry.
   *
   * @param {JulianDate} time The time to use when retrieving initial attribute values.
   * @returns {GeometryInstance} The geometry instance representing the filled portion of the geometry.
   *
   * @exception {DeveloperError} This instance does not represent a filled geometry.
   */
  CorridorGeometryUpdater.prototype.createFillGeometryInstance = function (time) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("time", time);

    if (!this._fillEnabled) {
      throw new DeveloperError(
        "This instance does not represent a filled geometry."
      );
    }
    //>>includeEnd('debug');

    const entity = this._entity;
    const isAvailable = entity.isAvailable(time);

    const attributes = {
      show: new ShowGeometryInstanceAttribute(
        isAvailable &&
          entity.isShowing &&
          this._showProperty.getValue(time) &&
          this._fillProperty.getValue(time)
      ),
      distanceDisplayCondition: DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
        this._distanceDisplayConditionProperty.getValue(time)
      ),
      offset: undefined,
      color: undefined,
    };

    if (this._materialProperty instanceof ColorMaterialProperty) {
      let currentColor;
      if (
        defined(this._materialProperty.color) &&
        (this._materialProperty.color.isConstant || isAvailable)
      ) {
        currentColor = this._materialProperty.color.getValue(time, scratchColor$d);
      }
      if (!defined(currentColor)) {
        currentColor = Color.WHITE;
      }
      attributes.color = ColorGeometryInstanceAttribute.fromColor(currentColor);
    }

    if (defined(this._options.offsetAttribute)) {
      attributes.offset = OffsetGeometryInstanceAttribute.fromCartesian3(
        Property.getValueOrDefault(
          this._terrainOffsetProperty,
          time,
          defaultOffset$9,
          offsetScratch$8
        )
      );
    }

    return new GeometryInstance({
      id: entity,
      geometry: new CorridorGeometry(this._options),
      attributes: attributes,
    });
  };

  /**
   * Creates the geometry instance which represents the outline of the geometry.
   *
   * @param {JulianDate} time The time to use when retrieving initial attribute values.
   * @returns {GeometryInstance} The geometry instance representing the outline portion of the geometry.
   *
   * @exception {DeveloperError} This instance does not represent an outlined geometry.
   */
  CorridorGeometryUpdater.prototype.createOutlineGeometryInstance = function (
    time
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("time", time);

    if (!this._outlineEnabled) {
      throw new DeveloperError(
        "This instance does not represent an outlined geometry."
      );
    }
    //>>includeEnd('debug');

    const entity = this._entity;
    const isAvailable = entity.isAvailable(time);
    const outlineColor = Property.getValueOrDefault(
      this._outlineColorProperty,
      time,
      Color.BLACK,
      scratchColor$d
    );

    const attributes = {
      show: new ShowGeometryInstanceAttribute(
        isAvailable &&
          entity.isShowing &&
          this._showProperty.getValue(time) &&
          this._showOutlineProperty.getValue(time)
      ),
      color: ColorGeometryInstanceAttribute.fromColor(outlineColor),
      distanceDisplayCondition: DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
        this._distanceDisplayConditionProperty.getValue(time)
      ),
      offset: undefined,
    };

    if (defined(this._options.offsetAttribute)) {
      attributes.offset = OffsetGeometryInstanceAttribute.fromCartesian3(
        Property.getValueOrDefault(
          this._terrainOffsetProperty,
          time,
          defaultOffset$9,
          offsetScratch$8
        )
      );
    }

    return new GeometryInstance({
      id: entity,
      geometry: new CorridorOutlineGeometry(this._options),
      attributes: attributes,
    });
  };

  CorridorGeometryUpdater.prototype._computeCenter = function (time, result) {
    const positions = Property.getValueOrUndefined(
      this._entity.corridor.positions,
      time
    );
    if (!defined(positions) || positions.length === 0) {
      return;
    }
    return Cartesian3.clone(
      positions[Math.floor(positions.length / 2.0)],
      result
    );
  };

  CorridorGeometryUpdater.prototype._isHidden = function (entity, corridor) {
    return (
      !defined(corridor.positions) ||
      !defined(corridor.width) ||
      GeometryUpdater.prototype._isHidden.call(this, entity, corridor)
    );
  };

  CorridorGeometryUpdater.prototype._isDynamic = function (entity, corridor) {
    return (
      !corridor.positions.isConstant || //
      !Property.isConstant(corridor.height) || //
      !Property.isConstant(corridor.extrudedHeight) || //
      !Property.isConstant(corridor.granularity) || //
      !Property.isConstant(corridor.width) || //
      !Property.isConstant(corridor.outlineWidth) || //
      !Property.isConstant(corridor.cornerType) || //
      !Property.isConstant(corridor.zIndex) || //
      (this._onTerrain &&
        !Property.isConstant(this._materialProperty) &&
        !(this._materialProperty instanceof ColorMaterialProperty))
    );
  };

  CorridorGeometryUpdater.prototype._setStaticOptions = function (
    entity,
    corridor
  ) {
    let heightValue = Property.getValueOrUndefined(
      corridor.height,
      Iso8601.MINIMUM_VALUE
    );
    const heightReferenceValue = Property.getValueOrDefault(
      corridor.heightReference,
      Iso8601.MINIMUM_VALUE,
      HeightReference$1.NONE
    );
    let extrudedHeightValue = Property.getValueOrUndefined(
      corridor.extrudedHeight,
      Iso8601.MINIMUM_VALUE
    );
    const extrudedHeightReferenceValue = Property.getValueOrDefault(
      corridor.extrudedHeightReference,
      Iso8601.MINIMUM_VALUE,
      HeightReference$1.NONE
    );
    if (defined(extrudedHeightValue) && !defined(heightValue)) {
      heightValue = 0;
    }

    const options = this._options;
    options.vertexFormat =
      this._materialProperty instanceof ColorMaterialProperty
        ? PerInstanceColorAppearance.VERTEX_FORMAT
        : MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat;
    options.positions = corridor.positions.getValue(
      Iso8601.MINIMUM_VALUE,
      options.positions
    );
    options.width = corridor.width.getValue(Iso8601.MINIMUM_VALUE);
    options.granularity = Property.getValueOrUndefined(
      corridor.granularity,
      Iso8601.MINIMUM_VALUE
    );
    options.cornerType = Property.getValueOrUndefined(
      corridor.cornerType,
      Iso8601.MINIMUM_VALUE
    );
    options.offsetAttribute = GroundGeometryUpdater.computeGeometryOffsetAttribute(
      heightValue,
      heightReferenceValue,
      extrudedHeightValue,
      extrudedHeightReferenceValue
    );
    options.height = GroundGeometryUpdater.getGeometryHeight(
      heightValue,
      heightReferenceValue
    );

    extrudedHeightValue = GroundGeometryUpdater.getGeometryExtrudedHeight(
      extrudedHeightValue,
      extrudedHeightReferenceValue
    );
    if (extrudedHeightValue === GroundGeometryUpdater.CLAMP_TO_GROUND) {
      extrudedHeightValue = ApproximateTerrainHeights.getMinimumMaximumHeights(
        CorridorGeometry.computeRectangle(options, scratchRectangle$4)
      ).minimumTerrainHeight;
    }

    options.extrudedHeight = extrudedHeightValue;
  };

  CorridorGeometryUpdater.DynamicGeometryUpdater = DynamicCorridorGeometryUpdater;

  /**
   * @private
   */
  function DynamicCorridorGeometryUpdater(
    geometryUpdater,
    primitives,
    groundPrimitives
  ) {
    DynamicGeometryUpdater$1.call(
      this,
      geometryUpdater,
      primitives,
      groundPrimitives
    );
  }

  if (defined(Object.create)) {
    DynamicCorridorGeometryUpdater.prototype = Object.create(
      DynamicGeometryUpdater$1.prototype
    );
    DynamicCorridorGeometryUpdater.prototype.constructor = DynamicCorridorGeometryUpdater;
  }

  DynamicCorridorGeometryUpdater.prototype._isHidden = function (
    entity,
    corridor,
    time
  ) {
    const options = this._options;
    return (
      !defined(options.positions) ||
      !defined(options.width) ||
      DynamicGeometryUpdater$1.prototype._isHidden.call(
        this,
        entity,
        corridor,
        time
      )
    );
  };

  DynamicCorridorGeometryUpdater.prototype._setOptions = function (
    entity,
    corridor,
    time
  ) {
    const options = this._options;
    let heightValue = Property.getValueOrUndefined(corridor.height, time);
    const heightReferenceValue = Property.getValueOrDefault(
      corridor.heightReference,
      time,
      HeightReference$1.NONE
    );
    let extrudedHeightValue = Property.getValueOrUndefined(
      corridor.extrudedHeight,
      time
    );
    const extrudedHeightReferenceValue = Property.getValueOrDefault(
      corridor.extrudedHeightReference,
      time,
      HeightReference$1.NONE
    );
    if (defined(extrudedHeightValue) && !defined(heightValue)) {
      heightValue = 0;
    }

    options.positions = Property.getValueOrUndefined(corridor.positions, time);
    options.width = Property.getValueOrUndefined(corridor.width, time);
    options.granularity = Property.getValueOrUndefined(
      corridor.granularity,
      time
    );
    options.cornerType = Property.getValueOrUndefined(corridor.cornerType, time);
    options.offsetAttribute = GroundGeometryUpdater.computeGeometryOffsetAttribute(
      heightValue,
      heightReferenceValue,
      extrudedHeightValue,
      extrudedHeightReferenceValue
    );
    options.height = GroundGeometryUpdater.getGeometryHeight(
      heightValue,
      heightReferenceValue
    );

    extrudedHeightValue = GroundGeometryUpdater.getGeometryExtrudedHeight(
      extrudedHeightValue,
      extrudedHeightReferenceValue
    );
    if (extrudedHeightValue === GroundGeometryUpdater.CLAMP_TO_GROUND) {
      extrudedHeightValue = ApproximateTerrainHeights.getMinimumMaximumHeights(
        CorridorGeometry.computeRectangle(options, scratchRectangle$4)
      ).minimumTerrainHeight;
    }

    options.extrudedHeight = extrudedHeightValue;
  };

  /**
   * Defines the interface for data sources, which turn arbitrary data into a
   * {@link EntityCollection} for generic consumption. This object is an interface
   * for documentation purposes and is not intended to be instantiated directly.
   * @alias DataSource
   * @constructor
   *
   * @see Entity
   * @see DataSourceDisplay
   */
  function DataSource() {
    DeveloperError.throwInstantiationError();
  }

  Object.defineProperties(DataSource.prototype, {
    /**
     * Gets a human-readable name for this instance.
     * @memberof DataSource.prototype
     * @type {String}
     */
    name: {
      get: DeveloperError.throwInstantiationError,
    },
    /**
     * Gets the preferred clock settings for this data source.
     * @memberof DataSource.prototype
     * @type {DataSourceClock}
     */
    clock: {
      get: DeveloperError.throwInstantiationError,
    },
    /**
     * Gets the collection of {@link Entity} instances.
     * @memberof DataSource.prototype
     * @type {EntityCollection}
     */
    entities: {
      get: DeveloperError.throwInstantiationError,
    },
    /**
     * Gets a value indicating if the data source is currently loading data.
     * @memberof DataSource.prototype
     * @type {Boolean}
     */
    isLoading: {
      get: DeveloperError.throwInstantiationError,
    },
    /**
     * Gets an event that will be raised when the underlying data changes.
     * @memberof DataSource.prototype
     * @type {Event}
     */
    changedEvent: {
      get: DeveloperError.throwInstantiationError,
    },
    /**
     * Gets an event that will be raised if an error is encountered during processing.
     * @memberof DataSource.prototype
     * @type {Event<function(this, RequestErrorEvent)>}
     */
    errorEvent: {
      get: DeveloperError.throwInstantiationError,
    },
    /**
     * Gets an event that will be raised when the value of isLoading changes.
     * @memberof DataSource.prototype
     * @type {Event<function(this, boolean)>}
     */
    loadingEvent: {
      get: DeveloperError.throwInstantiationError,
    },
    /**
     * Gets whether or not this data source should be displayed.
     * @memberof DataSource.prototype
     * @type {Boolean}
     */
    show: {
      get: DeveloperError.throwInstantiationError,
    },

    /**
     * Gets or sets the clustering options for this data source. This object can be shared between multiple data sources.
     *
     * @memberof DataSource.prototype
     * @type {EntityCluster}
     */
    clustering: {
      get: DeveloperError.throwInstantiationError,
    },
  });

  /**
   * Updates the data source to the provided time.  This function is optional and
   * is not required to be implemented.  It is provided for data sources which
   * retrieve data based on the current animation time or scene state.
   * If implemented, update will be called by {@link DataSourceDisplay} once a frame.
   *
   * @param {JulianDate} time The simulation time.
   * @returns {Boolean} True if this data source is ready to be displayed at the provided time, false otherwise.
   */
  DataSource.prototype.update = function (time) {
    DeveloperError.throwInstantiationError();
  };

  /**
   * @private
   */
  DataSource.setLoading = function (dataSource, isLoading) {
    if (dataSource._isLoading !== isLoading) {
      if (isLoading) {
        dataSource._entityCollection.suspendEvents();
      } else {
        dataSource._entityCollection.resumeEvents();
      }
      dataSource._isLoading = isLoading;
      dataSource._loading.raiseEvent(dataSource, isLoading);
    }
  };

  /**
   * A graphical point positioned in the 3D scene, that is created
   * and rendered using a {@link PointPrimitiveCollection}.  A point is created and its initial
   * properties are set by calling {@link PointPrimitiveCollection#add}.
   *
   * @alias PointPrimitive
   *
   * @performance Reading a property, e.g., {@link PointPrimitive#show}, is constant time.
   * Assigning to a property is constant time but results in
   * CPU to GPU traffic when {@link PointPrimitiveCollection#update} is called.  The per-pointPrimitive traffic is
   * the same regardless of how many properties were updated.  If most pointPrimitives in a collection need to be
   * updated, it may be more efficient to clear the collection with {@link PointPrimitiveCollection#removeAll}
   * and add new pointPrimitives instead of modifying each one.
   *
   * @exception {DeveloperError} scaleByDistance.far must be greater than scaleByDistance.near
   * @exception {DeveloperError} translucencyByDistance.far must be greater than translucencyByDistance.near
   * @exception {DeveloperError} distanceDisplayCondition.far must be greater than distanceDisplayCondition.near
   *
   * @see PointPrimitiveCollection
   * @see PointPrimitiveCollection#add
   *
   * @internalConstructor
   * @class
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Points.html|Cesium Sandcastle Points Demo}
   */
  function PointPrimitive(options, pointPrimitiveCollection) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    if (
      defined(options.disableDepthTestDistance) &&
      options.disableDepthTestDistance < 0.0
    ) {
      throw new DeveloperError(
        "disableDepthTestDistance must be greater than or equal to 0.0."
      );
    }
    //>>includeEnd('debug');

    let translucencyByDistance = options.translucencyByDistance;
    let scaleByDistance = options.scaleByDistance;
    let distanceDisplayCondition = options.distanceDisplayCondition;
    if (defined(translucencyByDistance)) {
      //>>includeStart('debug', pragmas.debug);
      if (translucencyByDistance.far <= translucencyByDistance.near) {
        throw new DeveloperError(
          "translucencyByDistance.far must be greater than translucencyByDistance.near."
        );
      }
      //>>includeEnd('debug');
      translucencyByDistance = NearFarScalar.clone(translucencyByDistance);
    }
    if (defined(scaleByDistance)) {
      //>>includeStart('debug', pragmas.debug);
      if (scaleByDistance.far <= scaleByDistance.near) {
        throw new DeveloperError(
          "scaleByDistance.far must be greater than scaleByDistance.near."
        );
      }
      //>>includeEnd('debug');
      scaleByDistance = NearFarScalar.clone(scaleByDistance);
    }
    if (defined(distanceDisplayCondition)) {
      //>>includeStart('debug', pragmas.debug);
      if (distanceDisplayCondition.far <= distanceDisplayCondition.near) {
        throw new DeveloperError(
          "distanceDisplayCondition.far must be greater than distanceDisplayCondition.near."
        );
      }
      //>>includeEnd('debug');
      distanceDisplayCondition = DistanceDisplayCondition.clone(
        distanceDisplayCondition
      );
    }

    this._show = defaultValue(options.show, true);
    this._position = Cartesian3.clone(
      defaultValue(options.position, Cartesian3.ZERO)
    );
    this._actualPosition = Cartesian3.clone(this._position); // For columbus view and 2D
    this._color = Color.clone(defaultValue(options.color, Color.WHITE));
    this._outlineColor = Color.clone(
      defaultValue(options.outlineColor, Color.TRANSPARENT)
    );
    this._outlineWidth = defaultValue(options.outlineWidth, 0.0);
    this._pixelSize = defaultValue(options.pixelSize, 10.0);
    this._scaleByDistance = scaleByDistance;
    this._translucencyByDistance = translucencyByDistance;
    this._distanceDisplayCondition = distanceDisplayCondition;
    this._disableDepthTestDistance = defaultValue(
      options.disableDepthTestDistance,
      0.0
    );
    this._id = options.id;
    this._collection = defaultValue(options.collection, pointPrimitiveCollection);

    this._clusterShow = true;

    this._pickId = undefined;
    this._pointPrimitiveCollection = pointPrimitiveCollection;
    this._dirty = false;
    this._index = -1; //Used only by PointPrimitiveCollection
  }

  const SHOW_INDEX$3 = (PointPrimitive.SHOW_INDEX = 0);
  const POSITION_INDEX$3 = (PointPrimitive.POSITION_INDEX = 1);
  const COLOR_INDEX$3 = (PointPrimitive.COLOR_INDEX = 2);
  const OUTLINE_COLOR_INDEX$1 = (PointPrimitive.OUTLINE_COLOR_INDEX = 3);
  const OUTLINE_WIDTH_INDEX$1 = (PointPrimitive.OUTLINE_WIDTH_INDEX = 4);
  const PIXEL_SIZE_INDEX$1 = (PointPrimitive.PIXEL_SIZE_INDEX = 5);
  const SCALE_BY_DISTANCE_INDEX$1 = (PointPrimitive.SCALE_BY_DISTANCE_INDEX = 6);
  const TRANSLUCENCY_BY_DISTANCE_INDEX$1 = (PointPrimitive.TRANSLUCENCY_BY_DISTANCE_INDEX = 7);
  const DISTANCE_DISPLAY_CONDITION_INDEX$1 = (PointPrimitive.DISTANCE_DISPLAY_CONDITION_INDEX = 8);
  const DISABLE_DEPTH_DISTANCE_INDEX$1 = (PointPrimitive.DISABLE_DEPTH_DISTANCE_INDEX = 9);
  PointPrimitive.NUMBER_OF_PROPERTIES = 10;

  function makeDirty$1(pointPrimitive, propertyChanged) {
    const pointPrimitiveCollection = pointPrimitive._pointPrimitiveCollection;
    if (defined(pointPrimitiveCollection)) {
      pointPrimitiveCollection._updatePointPrimitive(
        pointPrimitive,
        propertyChanged
      );
      pointPrimitive._dirty = true;
    }
  }

  Object.defineProperties(PointPrimitive.prototype, {
    /**
     * Determines if this point will be shown.  Use this to hide or show a point, instead
     * of removing it and re-adding it to the collection.
     * @memberof PointPrimitive.prototype
     * @type {Boolean}
     */
    show: {
      get: function () {
        return this._show;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        if (this._show !== value) {
          this._show = value;
          makeDirty$1(this, SHOW_INDEX$3);
        }
      },
    },

    /**
     * Gets or sets the Cartesian position of this point.
     * @memberof PointPrimitive.prototype
     * @type {Cartesian3}
     */
    position: {
      get: function () {
        return this._position;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug)
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        const position = this._position;
        if (!Cartesian3.equals(position, value)) {
          Cartesian3.clone(value, position);
          Cartesian3.clone(value, this._actualPosition);

          makeDirty$1(this, POSITION_INDEX$3);
        }
      },
    },

    /**
     * Gets or sets near and far scaling properties of a point based on the point's distance from the camera.
     * A point's scale will interpolate between the {@link NearFarScalar#nearValue} and
     * {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds
     * of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}.
     * Outside of these ranges the point's scale remains clamped to the nearest bound.  This scale
     * multiplies the pixelSize and outlineWidth to affect the total size of the point.  If undefined,
     * scaleByDistance will be disabled.
     * @memberof PointPrimitive.prototype
     * @type {NearFarScalar}
     *
     * @example
     * // Example 1.
     * // Set a pointPrimitive's scaleByDistance to scale to 15 when the
     * // camera is 1500 meters from the pointPrimitive and disappear as
     * // the camera distance approaches 8.0e6 meters.
     * p.scaleByDistance = new Cesium.NearFarScalar(1.5e2, 15, 8.0e6, 0.0);
     *
     * @example
     * // Example 2.
     * // disable scaling by distance
     * p.scaleByDistance = undefined;
     */
    scaleByDistance: {
      get: function () {
        return this._scaleByDistance;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (defined(value) && value.far <= value.near) {
          throw new DeveloperError(
            "far distance must be greater than near distance."
          );
        }
        //>>includeEnd('debug');

        const scaleByDistance = this._scaleByDistance;
        if (!NearFarScalar.equals(scaleByDistance, value)) {
          this._scaleByDistance = NearFarScalar.clone(value, scaleByDistance);
          makeDirty$1(this, SCALE_BY_DISTANCE_INDEX$1);
        }
      },
    },

    /**
     * Gets or sets near and far translucency properties of a point based on the point's distance from the camera.
     * A point's translucency will interpolate between the {@link NearFarScalar#nearValue} and
     * {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds
     * of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}.
     * Outside of these ranges the point's translucency remains clamped to the nearest bound.  If undefined,
     * translucencyByDistance will be disabled.
     * @memberof PointPrimitive.prototype
     * @type {NearFarScalar}
     *
     * @example
     * // Example 1.
     * // Set a point's translucency to 1.0 when the
     * // camera is 1500 meters from the point and disappear as
     * // the camera distance approaches 8.0e6 meters.
     * p.translucencyByDistance = new Cesium.NearFarScalar(1.5e2, 1.0, 8.0e6, 0.0);
     *
     * @example
     * // Example 2.
     * // disable translucency by distance
     * p.translucencyByDistance = undefined;
     */
    translucencyByDistance: {
      get: function () {
        return this._translucencyByDistance;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (defined(value) && value.far <= value.near) {
          throw new DeveloperError(
            "far distance must be greater than near distance."
          );
        }
        //>>includeEnd('debug');

        const translucencyByDistance = this._translucencyByDistance;
        if (!NearFarScalar.equals(translucencyByDistance, value)) {
          this._translucencyByDistance = NearFarScalar.clone(
            value,
            translucencyByDistance
          );
          makeDirty$1(this, TRANSLUCENCY_BY_DISTANCE_INDEX$1);
        }
      },
    },

    /**
     * Gets or sets the inner size of the point in pixels.
     * @memberof PointPrimitive.prototype
     * @type {Number}
     */
    pixelSize: {
      get: function () {
        return this._pixelSize;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        if (this._pixelSize !== value) {
          this._pixelSize = value;
          makeDirty$1(this, PIXEL_SIZE_INDEX$1);
        }
      },
    },

    /**
     * Gets or sets the inner color of the point.
     * The red, green, blue, and alpha values are indicated by <code>value</code>'s <code>red</code>, <code>green</code>,
     * <code>blue</code>, and <code>alpha</code> properties as shown in Example 1.  These components range from <code>0.0</code>
     * (no intensity) to <code>1.0</code> (full intensity).
     * @memberof PointPrimitive.prototype
     * @type {Color}
     *
     * @example
     * // Example 1. Assign yellow.
     * p.color = Cesium.Color.YELLOW;
     *
     * @example
     * // Example 2. Make a pointPrimitive 50% translucent.
     * p.color = new Cesium.Color(1.0, 1.0, 1.0, 0.5);
     */
    color: {
      get: function () {
        return this._color;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        const color = this._color;
        if (!Color.equals(color, value)) {
          Color.clone(value, color);
          makeDirty$1(this, COLOR_INDEX$3);
        }
      },
    },

    /**
     * Gets or sets the outline color of the point.
     * @memberof PointPrimitive.prototype
     * @type {Color}
     */
    outlineColor: {
      get: function () {
        return this._outlineColor;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        const outlineColor = this._outlineColor;
        if (!Color.equals(outlineColor, value)) {
          Color.clone(value, outlineColor);
          makeDirty$1(this, OUTLINE_COLOR_INDEX$1);
        }
      },
    },

    /**
     * Gets or sets the outline width in pixels.  This width adds to pixelSize,
     * increasing the total size of the point.
     * @memberof PointPrimitive.prototype
     * @type {Number}
     */
    outlineWidth: {
      get: function () {
        return this._outlineWidth;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        if (this._outlineWidth !== value) {
          this._outlineWidth = value;
          makeDirty$1(this, OUTLINE_WIDTH_INDEX$1);
        }
      },
    },

    /**
     * Gets or sets the condition specifying at what distance from the camera that this point will be displayed.
     * @memberof PointPrimitive.prototype
     * @type {DistanceDisplayCondition}
     * @default undefined
     */
    distanceDisplayCondition: {
      get: function () {
        return this._distanceDisplayCondition;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (defined(value) && value.far <= value.near) {
          throw new DeveloperError("far must be greater than near");
        }
        //>>includeEnd('debug');
        if (
          !DistanceDisplayCondition.equals(this._distanceDisplayCondition, value)
        ) {
          this._distanceDisplayCondition = DistanceDisplayCondition.clone(
            value,
            this._distanceDisplayCondition
          );
          makeDirty$1(this, DISTANCE_DISPLAY_CONDITION_INDEX$1);
        }
      },
    },

    /**
     * Gets or sets the distance from the camera at which to disable the depth test to, for example, prevent clipping against terrain.
     * When set to zero, the depth test is always applied. When set to Number.POSITIVE_INFINITY, the depth test is never applied.
     * @memberof PointPrimitive.prototype
     * @type {Number}
     * @default 0.0
     */
    disableDepthTestDistance: {
      get: function () {
        return this._disableDepthTestDistance;
      },
      set: function (value) {
        if (this._disableDepthTestDistance !== value) {
          //>>includeStart('debug', pragmas.debug);
          if (!defined(value) || value < 0.0) {
            throw new DeveloperError(
              "disableDepthTestDistance must be greater than or equal to 0.0."
            );
          }
          //>>includeEnd('debug');
          this._disableDepthTestDistance = value;
          makeDirty$1(this, DISABLE_DEPTH_DISTANCE_INDEX$1);
        }
      },
    },

    /**
     * Gets or sets the user-defined value returned when the point is picked.
     * @memberof PointPrimitive.prototype
     * @type {*}
     */
    id: {
      get: function () {
        return this._id;
      },
      set: function (value) {
        this._id = value;
        if (defined(this._pickId)) {
          this._pickId.object.id = value;
        }
      },
    },

    /**
     * @private
     */
    pickId: {
      get: function () {
        return this._pickId;
      },
    },

    /**
     * Determines whether or not this point will be shown or hidden because it was clustered.
     * @memberof PointPrimitive.prototype
     * @type {Boolean}
     * @private
     */
    clusterShow: {
      get: function () {
        return this._clusterShow;
      },
      set: function (value) {
        if (this._clusterShow !== value) {
          this._clusterShow = value;
          makeDirty$1(this, SHOW_INDEX$3);
        }
      },
    },
  });

  PointPrimitive.prototype.getPickId = function (context) {
    if (!defined(this._pickId)) {
      this._pickId = context.createPickId({
        primitive: this,
        collection: this._collection,
        id: this._id,
      });
    }

    return this._pickId;
  };

  PointPrimitive.prototype._getActualPosition = function () {
    return this._actualPosition;
  };

  PointPrimitive.prototype._setActualPosition = function (value) {
    Cartesian3.clone(value, this._actualPosition);
    makeDirty$1(this, POSITION_INDEX$3);
  };

  const tempCartesian3 = new Cartesian4();
  PointPrimitive._computeActualPosition = function (
    position,
    frameState,
    modelMatrix
  ) {
    if (frameState.mode === SceneMode$1.SCENE3D) {
      return position;
    }

    Matrix4.multiplyByPoint(modelMatrix, position, tempCartesian3);
    return SceneTransforms.computeActualWgs84Position(frameState, tempCartesian3);
  };

  const scratchCartesian4$2 = new Cartesian4();

  // This function is basically a stripped-down JavaScript version of PointPrimitiveCollectionVS.glsl
  PointPrimitive._computeScreenSpacePosition = function (
    modelMatrix,
    position,
    scene,
    result
  ) {
    // Model to world coordinates
    const positionWorld = Matrix4.multiplyByVector(
      modelMatrix,
      Cartesian4.fromElements(
        position.x,
        position.y,
        position.z,
        1,
        scratchCartesian4$2
      ),
      scratchCartesian4$2
    );
    const positionWC = SceneTransforms.wgs84ToWindowCoordinates(
      scene,
      positionWorld,
      result
    );
    return positionWC;
  };

  /**
   * Computes the screen-space position of the point's origin.
   * The screen space origin is the top, left corner of the canvas; <code>x</code> increases from
   * left to right, and <code>y</code> increases from top to bottom.
   *
   * @param {Scene} scene The scene.
   * @param {Cartesian2} [result] The object onto which to store the result.
   * @returns {Cartesian2} The screen-space position of the point.
   *
   * @exception {DeveloperError} PointPrimitive must be in a collection.
   *
   * @example
   * console.log(p.computeScreenSpacePosition(scene).toString());
   */
  PointPrimitive.prototype.computeScreenSpacePosition = function (scene, result) {
    const pointPrimitiveCollection = this._pointPrimitiveCollection;
    if (!defined(result)) {
      result = new Cartesian2();
    }

    //>>includeStart('debug', pragmas.debug);
    if (!defined(pointPrimitiveCollection)) {
      throw new DeveloperError("PointPrimitive must be in a collection.");
    }
    if (!defined(scene)) {
      throw new DeveloperError("scene is required.");
    }
    //>>includeEnd('debug');

    const modelMatrix = pointPrimitiveCollection.modelMatrix;
    const windowCoordinates = PointPrimitive._computeScreenSpacePosition(
      modelMatrix,
      this._actualPosition,
      scene,
      result
    );
    if (!defined(windowCoordinates)) {
      return undefined;
    }

    windowCoordinates.y = scene.canvas.clientHeight - windowCoordinates.y;
    return windowCoordinates;
  };

  /**
   * Gets a point's screen space bounding box centered around screenSpacePosition.
   * @param {PointPrimitive} point The point to get the screen space bounding box for.
   * @param {Cartesian2} screenSpacePosition The screen space center of the label.
   * @param {BoundingRectangle} [result] The object onto which to store the result.
   * @returns {BoundingRectangle} The screen space bounding box.
   *
   * @private
   */
  PointPrimitive.getScreenSpaceBoundingBox = function (
    point,
    screenSpacePosition,
    result
  ) {
    const size = point.pixelSize;
    const halfSize = size * 0.5;

    const x = screenSpacePosition.x - halfSize;
    const y = screenSpacePosition.y - halfSize;
    const width = size;
    const height = size;

    if (!defined(result)) {
      result = new BoundingRectangle();
    }

    result.x = x;
    result.y = y;
    result.width = width;
    result.height = height;

    return result;
  };

  /**
   * Determines if this point equals another point.  Points are equal if all their properties
   * are equal.  Points in different collections can be equal.
   *
   * @param {PointPrimitive} other The point to compare for equality.
   * @returns {Boolean} <code>true</code> if the points are equal; otherwise, <code>false</code>.
   */
  PointPrimitive.prototype.equals = function (other) {
    return (
      this === other ||
      (defined(other) &&
        this._id === other._id &&
        Cartesian3.equals(this._position, other._position) &&
        Color.equals(this._color, other._color) &&
        this._pixelSize === other._pixelSize &&
        this._outlineWidth === other._outlineWidth &&
        this._show === other._show &&
        Color.equals(this._outlineColor, other._outlineColor) &&
        NearFarScalar.equals(this._scaleByDistance, other._scaleByDistance) &&
        NearFarScalar.equals(
          this._translucencyByDistance,
          other._translucencyByDistance
        ) &&
        DistanceDisplayCondition.equals(
          this._distanceDisplayCondition,
          other._distanceDisplayCondition
        ) &&
        this._disableDepthTestDistance === other._disableDepthTestDistance)
    );
  };

  PointPrimitive.prototype._destroy = function () {
    this._pickId = this._pickId && this._pickId.destroy();
    this._pointPrimitiveCollection = undefined;
  };

  //This file is automatically rebuilt by the Cesium build process.
  var PointPrimitiveCollectionFS = "varying vec4 v_color;\n\
varying vec4 v_outlineColor;\n\
varying float v_innerPercent;\n\
varying float v_pixelDistance;\n\
varying vec4 v_pickColor;\n\
void main()\n\
{\n\
float distanceToCenter = length(gl_PointCoord - vec2(0.5));\n\
float maxDistance = max(0.0, 0.5 - v_pixelDistance);\n\
float wholeAlpha = 1.0 - smoothstep(maxDistance, 0.5, distanceToCenter);\n\
float innerAlpha = 1.0 - smoothstep(maxDistance * v_innerPercent, 0.5 * v_innerPercent, distanceToCenter);\n\
vec4 color = mix(v_outlineColor, v_color, innerAlpha);\n\
color.a *= wholeAlpha;\n\
#if !defined(OPAQUE) && !defined(TRANSLUCENT)\n\
if (color.a < 0.005)\n\
{\n\
discard;\n\
}\n\
#else\n\
#ifdef OPAQUE\n\
if (color.a < 0.995)\n\
{\n\
discard;\n\
}\n\
#else\n\
if (color.a >= 0.995)\n\
{\n\
discard;\n\
}\n\
#endif\n\
#endif\n\
gl_FragColor = czm_gammaCorrect(color);\n\
czm_writeLogDepth();\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var PointPrimitiveCollectionVS = "uniform float u_maxTotalPointSize;\n\
attribute vec4 positionHighAndSize;\n\
attribute vec4 positionLowAndOutline;\n\
attribute vec4 compressedAttribute0;\n\
attribute vec4 compressedAttribute1;\n\
attribute vec4 scaleByDistance;\n\
attribute vec3 distanceDisplayConditionAndDisableDepth;\n\
varying vec4 v_color;\n\
varying vec4 v_outlineColor;\n\
varying float v_innerPercent;\n\
varying float v_pixelDistance;\n\
varying vec4 v_pickColor;\n\
const float SHIFT_LEFT8 = 256.0;\n\
const float SHIFT_RIGHT8 = 1.0 / 256.0;\n\
void main()\n\
{\n\
vec3 positionHigh = positionHighAndSize.xyz;\n\
vec3 positionLow = positionLowAndOutline.xyz;\n\
float outlineWidthBothSides = 2.0 * positionLowAndOutline.w;\n\
float totalSize = positionHighAndSize.w + outlineWidthBothSides;\n\
float outlinePercent = outlineWidthBothSides / totalSize;\n\
totalSize *= czm_pixelRatio;\n\
totalSize += 3.0;\n\
float temp = compressedAttribute1.x * SHIFT_RIGHT8;\n\
float show = floor(temp);\n\
#ifdef EYE_DISTANCE_TRANSLUCENCY\n\
vec4 translucencyByDistance;\n\
translucencyByDistance.x = compressedAttribute1.z;\n\
translucencyByDistance.z = compressedAttribute1.w;\n\
translucencyByDistance.y = ((temp - floor(temp)) * SHIFT_LEFT8) / 255.0;\n\
temp = compressedAttribute1.y * SHIFT_RIGHT8;\n\
translucencyByDistance.w = ((temp - floor(temp)) * SHIFT_LEFT8) / 255.0;\n\
#endif\n\
vec4 color;\n\
vec4 outlineColor;\n\
vec4 pickColor;\n\
temp = compressedAttribute0.z * SHIFT_RIGHT8;\n\
pickColor.b = (temp - floor(temp)) * SHIFT_LEFT8;\n\
temp = floor(temp) * SHIFT_RIGHT8;\n\
pickColor.g = (temp - floor(temp)) * SHIFT_LEFT8;\n\
pickColor.r = floor(temp);\n\
temp = compressedAttribute0.x * SHIFT_RIGHT8;\n\
color.b = (temp - floor(temp)) * SHIFT_LEFT8;\n\
temp = floor(temp) * SHIFT_RIGHT8;\n\
color.g = (temp - floor(temp)) * SHIFT_LEFT8;\n\
color.r = floor(temp);\n\
temp = compressedAttribute0.y * SHIFT_RIGHT8;\n\
outlineColor.b = (temp - floor(temp)) * SHIFT_LEFT8;\n\
temp = floor(temp) * SHIFT_RIGHT8;\n\
outlineColor.g = (temp - floor(temp)) * SHIFT_LEFT8;\n\
outlineColor.r = floor(temp);\n\
temp = compressedAttribute0.w * SHIFT_RIGHT8;\n\
pickColor.a = (temp - floor(temp)) * SHIFT_LEFT8;\n\
pickColor = pickColor / 255.0;\n\
temp = floor(temp) * SHIFT_RIGHT8;\n\
outlineColor.a = (temp - floor(temp)) * SHIFT_LEFT8;\n\
outlineColor /= 255.0;\n\
color.a = floor(temp);\n\
color /= 255.0;\n\
vec4 p = czm_translateRelativeToEye(positionHigh, positionLow);\n\
vec4 positionEC = czm_modelViewRelativeToEye * p;\n\
#if defined(EYE_DISTANCE_SCALING) || defined(EYE_DISTANCE_TRANSLUCENCY) || defined(DISTANCE_DISPLAY_CONDITION) || defined(DISABLE_DEPTH_DISTANCE)\n\
float lengthSq;\n\
if (czm_sceneMode == czm_sceneMode2D)\n\
{\n\
lengthSq = czm_eyeHeight2D.y;\n\
}\n\
else\n\
{\n\
lengthSq = dot(positionEC.xyz, positionEC.xyz);\n\
}\n\
#endif\n\
#ifdef EYE_DISTANCE_SCALING\n\
totalSize *= czm_nearFarScalar(scaleByDistance, lengthSq);\n\
#endif\n\
totalSize = min(totalSize, u_maxTotalPointSize);\n\
if (totalSize < 1.0)\n\
{\n\
positionEC.xyz = vec3(0.0);\n\
totalSize = 1.0;\n\
}\n\
float translucency = 1.0;\n\
#ifdef EYE_DISTANCE_TRANSLUCENCY\n\
translucency = czm_nearFarScalar(translucencyByDistance, lengthSq);\n\
if (translucency < 0.004)\n\
{\n\
positionEC.xyz = vec3(0.0);\n\
}\n\
#endif\n\
#ifdef DISTANCE_DISPLAY_CONDITION\n\
float nearSq = distanceDisplayConditionAndDisableDepth.x;\n\
float farSq = distanceDisplayConditionAndDisableDepth.y;\n\
if (lengthSq < nearSq || lengthSq > farSq) {\n\
positionEC.xyz = vec3(0.0, 0.0, 1.0);\n\
}\n\
#endif\n\
gl_Position = czm_projection * positionEC;\n\
czm_vertexLogDepth();\n\
#ifdef DISABLE_DEPTH_DISTANCE\n\
float disableDepthTestDistance = distanceDisplayConditionAndDisableDepth.z;\n\
if (disableDepthTestDistance == 0.0 && czm_minimumDisableDepthTestDistance != 0.0)\n\
{\n\
disableDepthTestDistance = czm_minimumDisableDepthTestDistance;\n\
}\n\
if (disableDepthTestDistance != 0.0)\n\
{\n\
float zclip = gl_Position.z / gl_Position.w;\n\
bool clipped = (zclip < -1.0 || zclip > 1.0);\n\
if (!clipped && (disableDepthTestDistance < 0.0 || (lengthSq > 0.0 && lengthSq < disableDepthTestDistance)))\n\
{\n\
gl_Position.z = -gl_Position.w;\n\
#ifdef LOG_DEPTH\n\
czm_vertexLogDepth(vec4(czm_currentFrustum.x));\n\
#endif\n\
}\n\
}\n\
#endif\n\
v_color = color;\n\
v_color.a *= translucency * show;\n\
v_outlineColor = outlineColor;\n\
v_outlineColor.a *= translucency * show;\n\
v_innerPercent = 1.0 - outlinePercent;\n\
v_pixelDistance = 2.0 / totalSize;\n\
gl_PointSize = totalSize * show;\n\
gl_Position *= show;\n\
v_pickColor = pickColor;\n\
}\n\
";

  const SHOW_INDEX$2 = PointPrimitive.SHOW_INDEX;
  const POSITION_INDEX$2 = PointPrimitive.POSITION_INDEX;
  const COLOR_INDEX$2 = PointPrimitive.COLOR_INDEX;
  const OUTLINE_COLOR_INDEX = PointPrimitive.OUTLINE_COLOR_INDEX;
  const OUTLINE_WIDTH_INDEX = PointPrimitive.OUTLINE_WIDTH_INDEX;
  const PIXEL_SIZE_INDEX = PointPrimitive.PIXEL_SIZE_INDEX;
  const SCALE_BY_DISTANCE_INDEX = PointPrimitive.SCALE_BY_DISTANCE_INDEX;
  const TRANSLUCENCY_BY_DISTANCE_INDEX =
    PointPrimitive.TRANSLUCENCY_BY_DISTANCE_INDEX;
  const DISTANCE_DISPLAY_CONDITION_INDEX =
    PointPrimitive.DISTANCE_DISPLAY_CONDITION_INDEX;
  const DISABLE_DEPTH_DISTANCE_INDEX =
    PointPrimitive.DISABLE_DEPTH_DISTANCE_INDEX;
  const NUMBER_OF_PROPERTIES$1 = PointPrimitive.NUMBER_OF_PROPERTIES;

  const attributeLocations$2 = {
    positionHighAndSize: 0,
    positionLowAndOutline: 1,
    compressedAttribute0: 2, // color, outlineColor, pick color
    compressedAttribute1: 3, // show, translucency by distance, some free space
    scaleByDistance: 4,
    distanceDisplayConditionAndDisableDepth: 5,
  };

  /**
   * A renderable collection of points.
   * <br /><br />
   * Points are added and removed from the collection using {@link PointPrimitiveCollection#add}
   * and {@link PointPrimitiveCollection#remove}.
   *
   * @alias PointPrimitiveCollection
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] The 4x4 transformation matrix that transforms each point from model to world coordinates.
   * @param {Boolean} [options.debugShowBoundingVolume=false] For debugging only. Determines if this primitive's commands' bounding spheres are shown.
   * @param {BlendOption} [options.blendOption=BlendOption.OPAQUE_AND_TRANSLUCENT] The point blending option. The default
   * is used for rendering both opaque and translucent points. However, if either all of the points are completely opaque or all are completely translucent,
   * setting the technique to BlendOption.OPAQUE or BlendOption.TRANSLUCENT can improve performance by up to 2x.
   * @param {Boolean} [options.show=true] Determines if the primitives in the collection will be shown.
   *
   * @performance For best performance, prefer a few collections, each with many points, to
   * many collections with only a few points each.  Organize collections so that points
   * with the same update frequency are in the same collection, i.e., points that do not
   * change should be in one collection; points that change every frame should be in another
   * collection; and so on.
   *
   *
   * @example
   * // Create a pointPrimitive collection with two points
   * const points = scene.primitives.add(new Cesium.PointPrimitiveCollection());
   * points.add({
   *   position : new Cesium.Cartesian3(1.0, 2.0, 3.0),
   *   color : Cesium.Color.YELLOW
   * });
   * points.add({
   *   position : new Cesium.Cartesian3(4.0, 5.0, 6.0),
   *   color : Cesium.Color.CYAN
   * });
   *
   * @see PointPrimitiveCollection#add
   * @see PointPrimitiveCollection#remove
   * @see PointPrimitive
   */
  function PointPrimitiveCollection(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    this._sp = undefined;
    this._spTranslucent = undefined;
    this._rsOpaque = undefined;
    this._rsTranslucent = undefined;
    this._vaf = undefined;

    this._pointPrimitives = [];
    this._pointPrimitivesToUpdate = [];
    this._pointPrimitivesToUpdateIndex = 0;
    this._pointPrimitivesRemoved = false;
    this._createVertexArray = false;

    this._shaderScaleByDistance = false;
    this._compiledShaderScaleByDistance = false;

    this._shaderTranslucencyByDistance = false;
    this._compiledShaderTranslucencyByDistance = false;

    this._shaderDistanceDisplayCondition = false;
    this._compiledShaderDistanceDisplayCondition = false;

    this._shaderDisableDepthDistance = false;
    this._compiledShaderDisableDepthDistance = false;

    this._propertiesChanged = new Uint32Array(NUMBER_OF_PROPERTIES$1);

    this._maxPixelSize = 1.0;

    this._baseVolume = new BoundingSphere();
    this._baseVolumeWC = new BoundingSphere();
    this._baseVolume2D = new BoundingSphere();
    this._boundingVolume = new BoundingSphere();
    this._boundingVolumeDirty = false;

    this._colorCommands = [];

    /**
     * Determines if primitives in this collection will be shown.
     *
     * @type {Boolean}
     * @default true
     */
    this.show = defaultValue(options.show, true);

    /**
     * The 4x4 transformation matrix that transforms each point in this collection from model to world coordinates.
     * When this is the identity matrix, the pointPrimitives are drawn in world coordinates, i.e., Earth's WGS84 coordinates.
     * Local reference frames can be used by providing a different transformation matrix, like that returned
     * by {@link Transforms.eastNorthUpToFixedFrame}.
     *
     * @type {Matrix4}
     * @default {@link Matrix4.IDENTITY}
     *
     *
     * @example
     * const center = Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883);
     * pointPrimitives.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(center);
     * pointPrimitives.add({
     *   color : Cesium.Color.ORANGE,
     *   position : new Cesium.Cartesian3(0.0, 0.0, 0.0) // center
     * });
     * pointPrimitives.add({
     *   color : Cesium.Color.YELLOW,
     *   position : new Cesium.Cartesian3(1000000.0, 0.0, 0.0) // east
     * });
     * pointPrimitives.add({
     *   color : Cesium.Color.GREEN,
     *   position : new Cesium.Cartesian3(0.0, 1000000.0, 0.0) // north
     * });
     * pointPrimitives.add({
     *   color : Cesium.Color.CYAN,
     *   position : new Cesium.Cartesian3(0.0, 0.0, 1000000.0) // up
     * });
     *
     * @see Transforms.eastNorthUpToFixedFrame
     */
    this.modelMatrix = Matrix4.clone(
      defaultValue(options.modelMatrix, Matrix4.IDENTITY)
    );
    this._modelMatrix = Matrix4.clone(Matrix4.IDENTITY);

    /**
     * This property is for debugging only; it is not for production use nor is it optimized.
     * <p>
     * Draws the bounding sphere for each draw command in the primitive.
     * </p>
     *
     * @type {Boolean}
     *
     * @default false
     */
    this.debugShowBoundingVolume = defaultValue(
      options.debugShowBoundingVolume,
      false
    );

    /**
     * The point blending option. The default is used for rendering both opaque and translucent points.
     * However, if either all of the points are completely opaque or all are completely translucent,
     * setting the technique to BlendOption.OPAQUE or BlendOption.TRANSLUCENT can improve
     * performance by up to 2x.
     * @type {BlendOption}
     * @default BlendOption.OPAQUE_AND_TRANSLUCENT
     */
    this.blendOption = defaultValue(
      options.blendOption,
      BlendOption$1.OPAQUE_AND_TRANSLUCENT
    );
    this._blendOption = undefined;

    this._mode = SceneMode$1.SCENE3D;
    this._maxTotalPointSize = 1;

    // The buffer usage for each attribute is determined based on the usage of the attribute over time.
    this._buffersUsage = [
      BufferUsage$1.STATIC_DRAW, // SHOW_INDEX
      BufferUsage$1.STATIC_DRAW, // POSITION_INDEX
      BufferUsage$1.STATIC_DRAW, // COLOR_INDEX
      BufferUsage$1.STATIC_DRAW, // OUTLINE_COLOR_INDEX
      BufferUsage$1.STATIC_DRAW, // OUTLINE_WIDTH_INDEX
      BufferUsage$1.STATIC_DRAW, // PIXEL_SIZE_INDEX
      BufferUsage$1.STATIC_DRAW, // SCALE_BY_DISTANCE_INDEX
      BufferUsage$1.STATIC_DRAW, // TRANSLUCENCY_BY_DISTANCE_INDEX
      BufferUsage$1.STATIC_DRAW, // DISTANCE_DISPLAY_CONDITION_INDEX
    ];

    const that = this;
    this._uniforms = {
      u_maxTotalPointSize: function () {
        return that._maxTotalPointSize;
      },
    };
  }

  Object.defineProperties(PointPrimitiveCollection.prototype, {
    /**
     * Returns the number of points in this collection.  This is commonly used with
     * {@link PointPrimitiveCollection#get} to iterate over all the points
     * in the collection.
     * @memberof PointPrimitiveCollection.prototype
     * @type {Number}
     */
    length: {
      get: function () {
        removePointPrimitives(this);
        return this._pointPrimitives.length;
      },
    },
  });

  function destroyPointPrimitives(pointPrimitives) {
    const length = pointPrimitives.length;
    for (let i = 0; i < length; ++i) {
      if (pointPrimitives[i]) {
        pointPrimitives[i]._destroy();
      }
    }
  }

  /**
   * Creates and adds a point with the specified initial properties to the collection.
   * The added point is returned so it can be modified or removed from the collection later.
   *
   * @param {Object}[options] A template describing the point's properties as shown in Example 1.
   * @returns {PointPrimitive} The point that was added to the collection.
   *
   * @performance Calling <code>add</code> is expected constant time.  However, the collection's vertex buffer
   * is rewritten - an <code>O(n)</code> operation that also incurs CPU to GPU overhead.  For
   * best performance, add as many pointPrimitives as possible before calling <code>update</code>.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * // Example 1:  Add a point, specifying all the default values.
   * const p = pointPrimitives.add({
   *   show : true,
   *   position : Cesium.Cartesian3.ZERO,
   *   pixelSize : 10.0,
   *   color : Cesium.Color.WHITE,
   *   outlineColor : Cesium.Color.TRANSPARENT,
   *   outlineWidth : 0.0,
   *   id : undefined
   * });
   *
   * @example
   * // Example 2:  Specify only the point's cartographic position.
   * const p = pointPrimitives.add({
   *   position : Cesium.Cartesian3.fromDegrees(longitude, latitude, height)
   * });
   *
   * @see PointPrimitiveCollection#remove
   * @see PointPrimitiveCollection#removeAll
   */
  PointPrimitiveCollection.prototype.add = function (options) {
    const p = new PointPrimitive(options, this);
    p._index = this._pointPrimitives.length;

    this._pointPrimitives.push(p);
    this._createVertexArray = true;

    return p;
  };

  /**
   * Removes a point from the collection.
   *
   * @param {PointPrimitive} pointPrimitive The point to remove.
   * @returns {Boolean} <code>true</code> if the point was removed; <code>false</code> if the point was not found in the collection.
   *
   * @performance Calling <code>remove</code> is expected constant time.  However, the collection's vertex buffer
   * is rewritten - an <code>O(n)</code> operation that also incurs CPU to GPU overhead.  For
   * best performance, remove as many points as possible before calling <code>update</code>.
   * If you intend to temporarily hide a point, it is usually more efficient to call
   * {@link PointPrimitive#show} instead of removing and re-adding the point.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * const p = pointPrimitives.add(...);
   * pointPrimitives.remove(p);  // Returns true
   *
   * @see PointPrimitiveCollection#add
   * @see PointPrimitiveCollection#removeAll
   * @see PointPrimitive#show
   */
  PointPrimitiveCollection.prototype.remove = function (pointPrimitive) {
    if (this.contains(pointPrimitive)) {
      this._pointPrimitives[pointPrimitive._index] = null; // Removed later
      this._pointPrimitivesRemoved = true;
      this._createVertexArray = true;
      pointPrimitive._destroy();
      return true;
    }

    return false;
  };

  /**
   * Removes all points from the collection.
   *
   * @performance <code>O(n)</code>.  It is more efficient to remove all the points
   * from a collection and then add new ones than to create a new collection entirely.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * pointPrimitives.add(...);
   * pointPrimitives.add(...);
   * pointPrimitives.removeAll();
   *
   * @see PointPrimitiveCollection#add
   * @see PointPrimitiveCollection#remove
   */
  PointPrimitiveCollection.prototype.removeAll = function () {
    destroyPointPrimitives(this._pointPrimitives);
    this._pointPrimitives = [];
    this._pointPrimitivesToUpdate = [];
    this._pointPrimitivesToUpdateIndex = 0;
    this._pointPrimitivesRemoved = false;

    this._createVertexArray = true;
  };

  function removePointPrimitives(pointPrimitiveCollection) {
    if (pointPrimitiveCollection._pointPrimitivesRemoved) {
      pointPrimitiveCollection._pointPrimitivesRemoved = false;

      const newPointPrimitives = [];
      const pointPrimitives = pointPrimitiveCollection._pointPrimitives;
      const length = pointPrimitives.length;
      for (let i = 0, j = 0; i < length; ++i) {
        const pointPrimitive = pointPrimitives[i];
        if (pointPrimitive) {
          pointPrimitive._index = j++;
          newPointPrimitives.push(pointPrimitive);
        }
      }

      pointPrimitiveCollection._pointPrimitives = newPointPrimitives;
    }
  }

  PointPrimitiveCollection.prototype._updatePointPrimitive = function (
    pointPrimitive,
    propertyChanged
  ) {
    if (!pointPrimitive._dirty) {
      this._pointPrimitivesToUpdate[
        this._pointPrimitivesToUpdateIndex++
      ] = pointPrimitive;
    }

    ++this._propertiesChanged[propertyChanged];
  };

  /**
   * Check whether this collection contains a given point.
   *
   * @param {PointPrimitive} [pointPrimitive] The point to check for.
   * @returns {Boolean} true if this collection contains the point, false otherwise.
   *
   * @see PointPrimitiveCollection#get
   */
  PointPrimitiveCollection.prototype.contains = function (pointPrimitive) {
    return (
      defined(pointPrimitive) && pointPrimitive._pointPrimitiveCollection === this
    );
  };

  /**
   * Returns the point in the collection at the specified index.  Indices are zero-based
   * and increase as points are added.  Removing a point shifts all points after
   * it to the left, changing their indices.  This function is commonly used with
   * {@link PointPrimitiveCollection#length} to iterate over all the points
   * in the collection.
   *
   * @param {Number} index The zero-based index of the point.
   * @returns {PointPrimitive} The point at the specified index.
   *
   * @performance Expected constant time.  If points were removed from the collection and
   * {@link PointPrimitiveCollection#update} was not called, an implicit <code>O(n)</code>
   * operation is performed.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * // Toggle the show property of every point in the collection
   * const len = pointPrimitives.length;
   * for (let i = 0; i < len; ++i) {
   *   const p = pointPrimitives.get(i);
   *   p.show = !p.show;
   * }
   *
   * @see PointPrimitiveCollection#length
   */
  PointPrimitiveCollection.prototype.get = function (index) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(index)) {
      throw new DeveloperError("index is required.");
    }
    //>>includeEnd('debug');

    removePointPrimitives(this);
    return this._pointPrimitives[index];
  };

  PointPrimitiveCollection.prototype.computeNewBuffersUsage = function () {
    const buffersUsage = this._buffersUsage;
    let usageChanged = false;

    const properties = this._propertiesChanged;
    for (let k = 0; k < NUMBER_OF_PROPERTIES$1; ++k) {
      const newUsage =
        properties[k] === 0 ? BufferUsage$1.STATIC_DRAW : BufferUsage$1.STREAM_DRAW;
      usageChanged = usageChanged || buffersUsage[k] !== newUsage;
      buffersUsage[k] = newUsage;
    }

    return usageChanged;
  };

  function createVAF$1(context, numberOfPointPrimitives, buffersUsage) {
    return new VertexArrayFacade(
      context,
      [
        {
          index: attributeLocations$2.positionHighAndSize,
          componentsPerAttribute: 4,
          componentDatatype: ComponentDatatype$1.FLOAT,
          usage: buffersUsage[POSITION_INDEX$2],
        },
        {
          index: attributeLocations$2.positionLowAndShow,
          componentsPerAttribute: 4,
          componentDatatype: ComponentDatatype$1.FLOAT,
          usage: buffersUsage[POSITION_INDEX$2],
        },
        {
          index: attributeLocations$2.compressedAttribute0,
          componentsPerAttribute: 4,
          componentDatatype: ComponentDatatype$1.FLOAT,
          usage: buffersUsage[COLOR_INDEX$2],
        },
        {
          index: attributeLocations$2.compressedAttribute1,
          componentsPerAttribute: 4,
          componentDatatype: ComponentDatatype$1.FLOAT,
          usage: buffersUsage[TRANSLUCENCY_BY_DISTANCE_INDEX],
        },
        {
          index: attributeLocations$2.scaleByDistance,
          componentsPerAttribute: 4,
          componentDatatype: ComponentDatatype$1.FLOAT,
          usage: buffersUsage[SCALE_BY_DISTANCE_INDEX],
        },
        {
          index: attributeLocations$2.distanceDisplayConditionAndDisableDepth,
          componentsPerAttribute: 3,
          componentDatatype: ComponentDatatype$1.FLOAT,
          usage: buffersUsage[DISTANCE_DISPLAY_CONDITION_INDEX],
        },
      ],
      numberOfPointPrimitives
    ); // 1 vertex per pointPrimitive
  }

  ///////////////////////////////////////////////////////////////////////////

  // PERFORMANCE_IDEA:  Save memory if a property is the same for all pointPrimitives, use a latched attribute state,
  // instead of storing it in a vertex buffer.

  const writePositionScratch$1 = new EncodedCartesian3();

  function writePositionSizeAndOutline(
    pointPrimitiveCollection,
    context,
    vafWriters,
    pointPrimitive
  ) {
    const i = pointPrimitive._index;
    const position = pointPrimitive._getActualPosition();

    if (pointPrimitiveCollection._mode === SceneMode$1.SCENE3D) {
      BoundingSphere.expand(
        pointPrimitiveCollection._baseVolume,
        position,
        pointPrimitiveCollection._baseVolume
      );
      pointPrimitiveCollection._boundingVolumeDirty = true;
    }

    EncodedCartesian3.fromCartesian(position, writePositionScratch$1);
    const pixelSize = pointPrimitive.pixelSize;
    const outlineWidth = pointPrimitive.outlineWidth;

    pointPrimitiveCollection._maxPixelSize = Math.max(
      pointPrimitiveCollection._maxPixelSize,
      pixelSize + outlineWidth
    );

    const positionHighWriter = vafWriters[attributeLocations$2.positionHighAndSize];
    const high = writePositionScratch$1.high;
    positionHighWriter(i, high.x, high.y, high.z, pixelSize);

    const positionLowWriter =
      vafWriters[attributeLocations$2.positionLowAndOutline];
    const low = writePositionScratch$1.low;
    positionLowWriter(i, low.x, low.y, low.z, outlineWidth);
  }

  const LEFT_SHIFT16 = 65536.0; // 2^16
  const LEFT_SHIFT8 = 256.0; // 2^8

  function writeCompressedAttrib0(
    pointPrimitiveCollection,
    context,
    vafWriters,
    pointPrimitive
  ) {
    const i = pointPrimitive._index;

    const color = pointPrimitive.color;
    const pickColor = pointPrimitive.getPickId(context).color;
    const outlineColor = pointPrimitive.outlineColor;

    let red = Color.floatToByte(color.red);
    let green = Color.floatToByte(color.green);
    let blue = Color.floatToByte(color.blue);
    const compressed0 = red * LEFT_SHIFT16 + green * LEFT_SHIFT8 + blue;

    red = Color.floatToByte(outlineColor.red);
    green = Color.floatToByte(outlineColor.green);
    blue = Color.floatToByte(outlineColor.blue);
    const compressed1 = red * LEFT_SHIFT16 + green * LEFT_SHIFT8 + blue;

    red = Color.floatToByte(pickColor.red);
    green = Color.floatToByte(pickColor.green);
    blue = Color.floatToByte(pickColor.blue);
    const compressed2 = red * LEFT_SHIFT16 + green * LEFT_SHIFT8 + blue;

    const compressed3 =
      Color.floatToByte(color.alpha) * LEFT_SHIFT16 +
      Color.floatToByte(outlineColor.alpha) * LEFT_SHIFT8 +
      Color.floatToByte(pickColor.alpha);

    const writer = vafWriters[attributeLocations$2.compressedAttribute0];
    writer(i, compressed0, compressed1, compressed2, compressed3);
  }

  function writeCompressedAttrib1(
    pointPrimitiveCollection,
    context,
    vafWriters,
    pointPrimitive
  ) {
    const i = pointPrimitive._index;

    let near = 0.0;
    let nearValue = 1.0;
    let far = 1.0;
    let farValue = 1.0;

    const translucency = pointPrimitive.translucencyByDistance;
    if (defined(translucency)) {
      near = translucency.near;
      nearValue = translucency.nearValue;
      far = translucency.far;
      farValue = translucency.farValue;

      if (nearValue !== 1.0 || farValue !== 1.0) {
        // translucency by distance calculation in shader need not be enabled
        // until a pointPrimitive with near and far !== 1.0 is found
        pointPrimitiveCollection._shaderTranslucencyByDistance = true;
      }
    }

    let show = pointPrimitive.show && pointPrimitive.clusterShow;

    // If the color alphas are zero, do not show this pointPrimitive.  This lets us avoid providing
    // color during the pick pass and also eliminates a discard in the fragment shader.
    if (
      pointPrimitive.color.alpha === 0.0 &&
      pointPrimitive.outlineColor.alpha === 0.0
    ) {
      show = false;
    }

    nearValue = CesiumMath.clamp(nearValue, 0.0, 1.0);
    nearValue = nearValue === 1.0 ? 255.0 : (nearValue * 255.0) | 0;
    const compressed0 = (show ? 1.0 : 0.0) * LEFT_SHIFT8 + nearValue;

    farValue = CesiumMath.clamp(farValue, 0.0, 1.0);
    farValue = farValue === 1.0 ? 255.0 : (farValue * 255.0) | 0;
    const compressed1 = farValue;

    const writer = vafWriters[attributeLocations$2.compressedAttribute1];
    writer(i, compressed0, compressed1, near, far);
  }

  function writeScaleByDistance(
    pointPrimitiveCollection,
    context,
    vafWriters,
    pointPrimitive
  ) {
    const i = pointPrimitive._index;
    const writer = vafWriters[attributeLocations$2.scaleByDistance];
    let near = 0.0;
    let nearValue = 1.0;
    let far = 1.0;
    let farValue = 1.0;

    const scale = pointPrimitive.scaleByDistance;
    if (defined(scale)) {
      near = scale.near;
      nearValue = scale.nearValue;
      far = scale.far;
      farValue = scale.farValue;

      if (nearValue !== 1.0 || farValue !== 1.0) {
        // scale by distance calculation in shader need not be enabled
        // until a pointPrimitive with near and far !== 1.0 is found
        pointPrimitiveCollection._shaderScaleByDistance = true;
      }
    }

    writer(i, near, nearValue, far, farValue);
  }

  function writeDistanceDisplayConditionAndDepthDisable(
    pointPrimitiveCollection,
    context,
    vafWriters,
    pointPrimitive
  ) {
    const i = pointPrimitive._index;
    const writer =
      vafWriters[attributeLocations$2.distanceDisplayConditionAndDisableDepth];
    let near = 0.0;
    let far = Number.MAX_VALUE;

    const distanceDisplayCondition = pointPrimitive.distanceDisplayCondition;
    if (defined(distanceDisplayCondition)) {
      near = distanceDisplayCondition.near;
      far = distanceDisplayCondition.far;

      near *= near;
      far *= far;

      pointPrimitiveCollection._shaderDistanceDisplayCondition = true;
    }

    let disableDepthTestDistance = pointPrimitive.disableDepthTestDistance;
    disableDepthTestDistance *= disableDepthTestDistance;
    if (disableDepthTestDistance > 0.0) {
      pointPrimitiveCollection._shaderDisableDepthDistance = true;
      if (disableDepthTestDistance === Number.POSITIVE_INFINITY) {
        disableDepthTestDistance = -1.0;
      }
    }

    writer(i, near, far, disableDepthTestDistance);
  }

  function writePointPrimitive(
    pointPrimitiveCollection,
    context,
    vafWriters,
    pointPrimitive
  ) {
    writePositionSizeAndOutline(
      pointPrimitiveCollection,
      context,
      vafWriters,
      pointPrimitive
    );
    writeCompressedAttrib0(
      pointPrimitiveCollection,
      context,
      vafWriters,
      pointPrimitive
    );
    writeCompressedAttrib1(
      pointPrimitiveCollection,
      context,
      vafWriters,
      pointPrimitive
    );
    writeScaleByDistance(
      pointPrimitiveCollection,
      context,
      vafWriters,
      pointPrimitive
    );
    writeDistanceDisplayConditionAndDepthDisable(
      pointPrimitiveCollection,
      context,
      vafWriters,
      pointPrimitive
    );
  }

  function recomputeActualPositions(
    pointPrimitiveCollection,
    pointPrimitives,
    length,
    frameState,
    modelMatrix,
    recomputeBoundingVolume
  ) {
    let boundingVolume;
    if (frameState.mode === SceneMode$1.SCENE3D) {
      boundingVolume = pointPrimitiveCollection._baseVolume;
      pointPrimitiveCollection._boundingVolumeDirty = true;
    } else {
      boundingVolume = pointPrimitiveCollection._baseVolume2D;
    }

    const positions = [];
    for (let i = 0; i < length; ++i) {
      const pointPrimitive = pointPrimitives[i];
      const position = pointPrimitive.position;
      const actualPosition = PointPrimitive._computeActualPosition(
        position,
        frameState,
        modelMatrix
      );
      if (defined(actualPosition)) {
        pointPrimitive._setActualPosition(actualPosition);

        if (recomputeBoundingVolume) {
          positions.push(actualPosition);
        } else {
          BoundingSphere.expand(boundingVolume, actualPosition, boundingVolume);
        }
      }
    }

    if (recomputeBoundingVolume) {
      BoundingSphere.fromPoints(positions, boundingVolume);
    }
  }

  function updateMode(pointPrimitiveCollection, frameState) {
    const mode = frameState.mode;

    const pointPrimitives = pointPrimitiveCollection._pointPrimitives;
    const pointPrimitivesToUpdate =
      pointPrimitiveCollection._pointPrimitivesToUpdate;
    const modelMatrix = pointPrimitiveCollection._modelMatrix;

    if (
      pointPrimitiveCollection._createVertexArray ||
      pointPrimitiveCollection._mode !== mode ||
      (mode !== SceneMode$1.SCENE3D &&
        !Matrix4.equals(modelMatrix, pointPrimitiveCollection.modelMatrix))
    ) {
      pointPrimitiveCollection._mode = mode;
      Matrix4.clone(pointPrimitiveCollection.modelMatrix, modelMatrix);
      pointPrimitiveCollection._createVertexArray = true;

      if (
        mode === SceneMode$1.SCENE3D ||
        mode === SceneMode$1.SCENE2D ||
        mode === SceneMode$1.COLUMBUS_VIEW
      ) {
        recomputeActualPositions(
          pointPrimitiveCollection,
          pointPrimitives,
          pointPrimitives.length,
          frameState,
          modelMatrix,
          true
        );
      }
    } else if (mode === SceneMode$1.MORPHING) {
      recomputeActualPositions(
        pointPrimitiveCollection,
        pointPrimitives,
        pointPrimitives.length,
        frameState,
        modelMatrix,
        true
      );
    } else if (mode === SceneMode$1.SCENE2D || mode === SceneMode$1.COLUMBUS_VIEW) {
      recomputeActualPositions(
        pointPrimitiveCollection,
        pointPrimitivesToUpdate,
        pointPrimitiveCollection._pointPrimitivesToUpdateIndex,
        frameState,
        modelMatrix,
        false
      );
    }
  }

  function updateBoundingVolume(collection, frameState, boundingVolume) {
    const pixelSize = frameState.camera.getPixelSize(
      boundingVolume,
      frameState.context.drawingBufferWidth,
      frameState.context.drawingBufferHeight
    );
    const size = pixelSize * collection._maxPixelSize;
    boundingVolume.radius += size;
  }

  const scratchWriterArray$1 = [];

  /**
   * @private
   */
  PointPrimitiveCollection.prototype.update = function (frameState) {
    removePointPrimitives(this);

    if (!this.show) {
      return;
    }

    this._maxTotalPointSize = ContextLimits.maximumAliasedPointSize;

    updateMode(this, frameState);

    const pointPrimitives = this._pointPrimitives;
    const pointPrimitivesLength = pointPrimitives.length;
    const pointPrimitivesToUpdate = this._pointPrimitivesToUpdate;
    const pointPrimitivesToUpdateLength = this._pointPrimitivesToUpdateIndex;

    const properties = this._propertiesChanged;

    const createVertexArray = this._createVertexArray;

    let vafWriters;
    const context = frameState.context;
    const pass = frameState.passes;
    const picking = pass.pick;

    // PERFORMANCE_IDEA: Round robin multiple buffers.
    if (createVertexArray || (!picking && this.computeNewBuffersUsage())) {
      this._createVertexArray = false;

      for (let k = 0; k < NUMBER_OF_PROPERTIES$1; ++k) {
        properties[k] = 0;
      }

      this._vaf = this._vaf && this._vaf.destroy();

      if (pointPrimitivesLength > 0) {
        // PERFORMANCE_IDEA:  Instead of creating a new one, resize like std::vector.
        this._vaf = createVAF$1(context, pointPrimitivesLength, this._buffersUsage);
        vafWriters = this._vaf.writers;

        // Rewrite entire buffer if pointPrimitives were added or removed.
        for (let i = 0; i < pointPrimitivesLength; ++i) {
          const pointPrimitive = this._pointPrimitives[i];
          pointPrimitive._dirty = false; // In case it needed an update.
          writePointPrimitive(this, context, vafWriters, pointPrimitive);
        }

        this._vaf.commit();
      }

      this._pointPrimitivesToUpdateIndex = 0;
    } else if (pointPrimitivesToUpdateLength > 0) {
      // PointPrimitives were modified, but none were added or removed.
      const writers = scratchWriterArray$1;
      writers.length = 0;

      if (
        properties[POSITION_INDEX$2] ||
        properties[OUTLINE_WIDTH_INDEX] ||
        properties[PIXEL_SIZE_INDEX]
      ) {
        writers.push(writePositionSizeAndOutline);
      }

      if (properties[COLOR_INDEX$2] || properties[OUTLINE_COLOR_INDEX]) {
        writers.push(writeCompressedAttrib0);
      }

      if (properties[SHOW_INDEX$2] || properties[TRANSLUCENCY_BY_DISTANCE_INDEX]) {
        writers.push(writeCompressedAttrib1);
      }

      if (properties[SCALE_BY_DISTANCE_INDEX]) {
        writers.push(writeScaleByDistance);
      }

      if (
        properties[DISTANCE_DISPLAY_CONDITION_INDEX] ||
        properties[DISABLE_DEPTH_DISTANCE_INDEX]
      ) {
        writers.push(writeDistanceDisplayConditionAndDepthDisable);
      }

      const numWriters = writers.length;

      vafWriters = this._vaf.writers;

      if (pointPrimitivesToUpdateLength / pointPrimitivesLength > 0.1) {
        // If more than 10% of pointPrimitive change, rewrite the entire buffer.

        // PERFORMANCE_IDEA:  I totally made up 10% :).

        for (let m = 0; m < pointPrimitivesToUpdateLength; ++m) {
          const b = pointPrimitivesToUpdate[m];
          b._dirty = false;

          for (let n = 0; n < numWriters; ++n) {
            writers[n](this, context, vafWriters, b);
          }
        }
        this._vaf.commit();
      } else {
        for (let h = 0; h < pointPrimitivesToUpdateLength; ++h) {
          const bb = pointPrimitivesToUpdate[h];
          bb._dirty = false;

          for (let o = 0; o < numWriters; ++o) {
            writers[o](this, context, vafWriters, bb);
          }
          this._vaf.subCommit(bb._index, 1);
        }
        this._vaf.endSubCommits();
      }

      this._pointPrimitivesToUpdateIndex = 0;
    }

    // If the number of total pointPrimitives ever shrinks considerably
    // Truncate pointPrimitivesToUpdate so that we free memory that we're
    // not going to be using.
    if (pointPrimitivesToUpdateLength > pointPrimitivesLength * 1.5) {
      pointPrimitivesToUpdate.length = pointPrimitivesLength;
    }

    if (!defined(this._vaf) || !defined(this._vaf.va)) {
      return;
    }

    if (this._boundingVolumeDirty) {
      this._boundingVolumeDirty = false;
      BoundingSphere.transform(
        this._baseVolume,
        this.modelMatrix,
        this._baseVolumeWC
      );
    }

    let boundingVolume;
    let modelMatrix = Matrix4.IDENTITY;
    if (frameState.mode === SceneMode$1.SCENE3D) {
      modelMatrix = this.modelMatrix;
      boundingVolume = BoundingSphere.clone(
        this._baseVolumeWC,
        this._boundingVolume
      );
    } else {
      boundingVolume = BoundingSphere.clone(
        this._baseVolume2D,
        this._boundingVolume
      );
    }
    updateBoundingVolume(this, frameState, boundingVolume);

    const blendOptionChanged = this._blendOption !== this.blendOption;
    this._blendOption = this.blendOption;

    if (blendOptionChanged) {
      if (
        this._blendOption === BlendOption$1.OPAQUE ||
        this._blendOption === BlendOption$1.OPAQUE_AND_TRANSLUCENT
      ) {
        this._rsOpaque = RenderState.fromCache({
          depthTest: {
            enabled: true,
            func: WebGLConstants$1.LEQUAL,
          },
          depthMask: true,
        });
      } else {
        this._rsOpaque = undefined;
      }

      if (
        this._blendOption === BlendOption$1.TRANSLUCENT ||
        this._blendOption === BlendOption$1.OPAQUE_AND_TRANSLUCENT
      ) {
        this._rsTranslucent = RenderState.fromCache({
          depthTest: {
            enabled: true,
            func: WebGLConstants$1.LEQUAL,
          },
          depthMask: false,
          blending: BlendingState$1.ALPHA_BLEND,
        });
      } else {
        this._rsTranslucent = undefined;
      }
    }

    this._shaderDisableDepthDistance =
      this._shaderDisableDepthDistance ||
      frameState.minimumDisableDepthTestDistance !== 0.0;
    let vs;
    let fs;

    if (
      blendOptionChanged ||
      (this._shaderScaleByDistance && !this._compiledShaderScaleByDistance) ||
      (this._shaderTranslucencyByDistance &&
        !this._compiledShaderTranslucencyByDistance) ||
      (this._shaderDistanceDisplayCondition &&
        !this._compiledShaderDistanceDisplayCondition) ||
      this._shaderDisableDepthDistance !==
        this._compiledShaderDisableDepthDistance
    ) {
      vs = new ShaderSource({
        sources: [PointPrimitiveCollectionVS],
      });
      if (this._shaderScaleByDistance) {
        vs.defines.push("EYE_DISTANCE_SCALING");
      }
      if (this._shaderTranslucencyByDistance) {
        vs.defines.push("EYE_DISTANCE_TRANSLUCENCY");
      }
      if (this._shaderDistanceDisplayCondition) {
        vs.defines.push("DISTANCE_DISPLAY_CONDITION");
      }
      if (this._shaderDisableDepthDistance) {
        vs.defines.push("DISABLE_DEPTH_DISTANCE");
      }

      if (this._blendOption === BlendOption$1.OPAQUE_AND_TRANSLUCENT) {
        fs = new ShaderSource({
          defines: ["OPAQUE"],
          sources: [PointPrimitiveCollectionFS],
        });
        this._sp = ShaderProgram.replaceCache({
          context: context,
          shaderProgram: this._sp,
          vertexShaderSource: vs,
          fragmentShaderSource: fs,
          attributeLocations: attributeLocations$2,
        });

        fs = new ShaderSource({
          defines: ["TRANSLUCENT"],
          sources: [PointPrimitiveCollectionFS],
        });
        this._spTranslucent = ShaderProgram.replaceCache({
          context: context,
          shaderProgram: this._spTranslucent,
          vertexShaderSource: vs,
          fragmentShaderSource: fs,
          attributeLocations: attributeLocations$2,
        });
      }

      if (this._blendOption === BlendOption$1.OPAQUE) {
        fs = new ShaderSource({
          sources: [PointPrimitiveCollectionFS],
        });
        this._sp = ShaderProgram.replaceCache({
          context: context,
          shaderProgram: this._sp,
          vertexShaderSource: vs,
          fragmentShaderSource: fs,
          attributeLocations: attributeLocations$2,
        });
      }

      if (this._blendOption === BlendOption$1.TRANSLUCENT) {
        fs = new ShaderSource({
          sources: [PointPrimitiveCollectionFS],
        });
        this._spTranslucent = ShaderProgram.replaceCache({
          context: context,
          shaderProgram: this._spTranslucent,
          vertexShaderSource: vs,
          fragmentShaderSource: fs,
          attributeLocations: attributeLocations$2,
        });
      }

      this._compiledShaderScaleByDistance = this._shaderScaleByDistance;
      this._compiledShaderTranslucencyByDistance = this._shaderTranslucencyByDistance;
      this._compiledShaderDistanceDisplayCondition = this._shaderDistanceDisplayCondition;
      this._compiledShaderDisableDepthDistance = this._shaderDisableDepthDistance;
    }

    let va;
    let vaLength;
    let command;
    let j;

    const commandList = frameState.commandList;

    if (pass.render || picking) {
      const colorList = this._colorCommands;

      const opaque = this._blendOption === BlendOption$1.OPAQUE;
      const opaqueAndTranslucent =
        this._blendOption === BlendOption$1.OPAQUE_AND_TRANSLUCENT;

      va = this._vaf.va;
      vaLength = va.length;

      colorList.length = vaLength;
      const totalLength = opaqueAndTranslucent ? vaLength * 2 : vaLength;
      for (j = 0; j < totalLength; ++j) {
        const opaqueCommand = opaque || (opaqueAndTranslucent && j % 2 === 0);

        command = colorList[j];
        if (!defined(command)) {
          command = colorList[j] = new DrawCommand();
        }

        command.primitiveType = PrimitiveType$1.POINTS;
        command.pass =
          opaqueCommand || !opaqueAndTranslucent ? Pass$1.OPAQUE : Pass$1.TRANSLUCENT;
        command.owner = this;

        const index = opaqueAndTranslucent ? Math.floor(j / 2.0) : j;
        command.boundingVolume = boundingVolume;
        command.modelMatrix = modelMatrix;
        command.shaderProgram = opaqueCommand ? this._sp : this._spTranslucent;
        command.uniformMap = this._uniforms;
        command.vertexArray = va[index].va;
        command.renderState = opaqueCommand
          ? this._rsOpaque
          : this._rsTranslucent;
        command.debugShowBoundingVolume = this.debugShowBoundingVolume;
        command.pickId = "v_pickColor";

        commandList.push(command);
      }
    }
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see PointPrimitiveCollection#destroy
   */
  PointPrimitiveCollection.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * pointPrimitives = pointPrimitives && pointPrimitives.destroy();
   *
   * @see PointPrimitiveCollection#isDestroyed
   */
  PointPrimitiveCollection.prototype.destroy = function () {
    this._sp = this._sp && this._sp.destroy();
    this._spTranslucent = this._spTranslucent && this._spTranslucent.destroy();
    this._spPick = this._spPick && this._spPick.destroy();
    this._vaf = this._vaf && this._vaf.destroy();
    destroyPointPrimitives(this._pointPrimitives);

    return destroyObject(this);
  };

  /* This file is automatically rebuilt by the Cesium build process. */
  function sortKD(ids, coords, nodeSize, left, right, depth) {
      if (right - left <= nodeSize) return;

      const m = (left + right) >> 1;

      select(ids, coords, m, left, right, depth % 2);

      sortKD(ids, coords, nodeSize, left, m - 1, depth + 1);
      sortKD(ids, coords, nodeSize, m + 1, right, depth + 1);
  }

  function select(ids, coords, k, left, right, inc) {

      while (right > left) {
          if (right - left > 600) {
              const n = right - left + 1;
              const m = k - left + 1;
              const z = Math.log(n);
              const s = 0.5 * Math.exp(2 * z / 3);
              const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
              const newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
              const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
              select(ids, coords, k, newLeft, newRight, inc);
          }

          const t = coords[2 * k + inc];
          let i = left;
          let j = right;

          swapItem(ids, coords, left, k);
          if (coords[2 * right + inc] > t) swapItem(ids, coords, left, right);

          while (i < j) {
              swapItem(ids, coords, i, j);
              i++;
              j--;
              while (coords[2 * i + inc] < t) i++;
              while (coords[2 * j + inc] > t) j--;
          }

          if (coords[2 * left + inc] === t) swapItem(ids, coords, left, j);
          else {
              j++;
              swapItem(ids, coords, j, right);
          }

          if (j <= k) left = j + 1;
          if (k <= j) right = j - 1;
      }
  }

  function swapItem(ids, coords, i, j) {
      swap(ids, i, j);
      swap(coords, 2 * i, 2 * j);
      swap(coords, 2 * i + 1, 2 * j + 1);
  }

  function swap(arr, i, j) {
      const tmp = arr[i];
      arr[i] = arr[j];
      arr[j] = tmp;
  }

  function range(ids, coords, minX, minY, maxX, maxY, nodeSize) {
      const stack = [0, ids.length - 1, 0];
      const result = [];
      let x, y;

      while (stack.length) {
          const axis = stack.pop();
          const right = stack.pop();
          const left = stack.pop();

          if (right - left <= nodeSize) {
              for (let i = left; i <= right; i++) {
                  x = coords[2 * i];
                  y = coords[2 * i + 1];
                  if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[i]);
              }
              continue;
          }

          const m = Math.floor((left + right) / 2);

          x = coords[2 * m];
          y = coords[2 * m + 1];

          if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[m]);

          const nextAxis = (axis + 1) % 2;

          if (axis === 0 ? minX <= x : minY <= y) {
              stack.push(left);
              stack.push(m - 1);
              stack.push(nextAxis);
          }
          if (axis === 0 ? maxX >= x : maxY >= y) {
              stack.push(m + 1);
              stack.push(right);
              stack.push(nextAxis);
          }
      }

      return result;
  }

  function within(ids, coords, qx, qy, r, nodeSize) {
      const stack = [0, ids.length - 1, 0];
      const result = [];
      const r2 = r * r;

      while (stack.length) {
          const axis = stack.pop();
          const right = stack.pop();
          const left = stack.pop();

          if (right - left <= nodeSize) {
              for (let i = left; i <= right; i++) {
                  if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) result.push(ids[i]);
              }
              continue;
          }

          const m = Math.floor((left + right) / 2);

          const x = coords[2 * m];
          const y = coords[2 * m + 1];

          if (sqDist(x, y, qx, qy) <= r2) result.push(ids[m]);

          const nextAxis = (axis + 1) % 2;

          if (axis === 0 ? qx - r <= x : qy - r <= y) {
              stack.push(left);
              stack.push(m - 1);
              stack.push(nextAxis);
          }
          if (axis === 0 ? qx + r >= x : qy + r >= y) {
              stack.push(m + 1);
              stack.push(right);
              stack.push(nextAxis);
          }
      }

      return result;
  }

  function sqDist(ax, ay, bx, by) {
      const dx = ax - bx;
      const dy = ay - by;
      return dx * dx + dy * dy;
  }

  const defaultGetX = p => p[0];
  const defaultGetY = p => p[1];

  class KDBush {
      constructor(points, getX = defaultGetX, getY = defaultGetY, nodeSize = 64, ArrayType = Float64Array) {
          this.nodeSize = nodeSize;
          this.points = points;

          const IndexArrayType = points.length < 65536 ? Uint16Array : Uint32Array;

          const ids = this.ids = new IndexArrayType(points.length);
          const coords = this.coords = new ArrayType(points.length * 2);

          for (let i = 0; i < points.length; i++) {
              ids[i] = i;
              coords[2 * i] = getX(points[i]);
              coords[2 * i + 1] = getY(points[i]);
          }

          sortKD(ids, coords, nodeSize, 0, ids.length - 1, 0);
      }

      range(minX, minY, maxX, maxY) {
          return range(this.ids, this.coords, minX, minY, maxX, maxY, this.nodeSize);
      }

      within(x, y, r) {
          return within(this.ids, this.coords, x, y, r, this.nodeSize);
      }
  }

  /**
   * Defines how screen space objects (billboards, points, labels) are clustered.
   *
   * @param {Object} [options] An object with the following properties:
   * @param {Boolean} [options.enabled=false] Whether or not to enable clustering.
   * @param {Number} [options.pixelRange=80] The pixel range to extend the screen space bounding box.
   * @param {Number} [options.minimumClusterSize=2] The minimum number of screen space objects that can be clustered.
   * @param {Boolean} [options.clusterBillboards=true] Whether or not to cluster the billboards of an entity.
   * @param {Boolean} [options.clusterLabels=true] Whether or not to cluster the labels of an entity.
   * @param {Boolean} [options.clusterPoints=true] Whether or not to cluster the points of an entity.
   * @param {Boolean} [options.show=true] Determines if the entities in the cluster will be shown.
   *
   * @alias EntityCluster
   * @constructor
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Clustering.html|Cesium Sandcastle Clustering Demo}
   */
  function EntityCluster(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    this._enabled = defaultValue(options.enabled, false);
    this._pixelRange = defaultValue(options.pixelRange, 80);
    this._minimumClusterSize = defaultValue(options.minimumClusterSize, 2);
    this._clusterBillboards = defaultValue(options.clusterBillboards, true);
    this._clusterLabels = defaultValue(options.clusterLabels, true);
    this._clusterPoints = defaultValue(options.clusterPoints, true);

    this._labelCollection = undefined;
    this._billboardCollection = undefined;
    this._pointCollection = undefined;

    this._clusterBillboardCollection = undefined;
    this._clusterLabelCollection = undefined;
    this._clusterPointCollection = undefined;

    this._collectionIndicesByEntity = {};

    this._unusedLabelIndices = [];
    this._unusedBillboardIndices = [];
    this._unusedPointIndices = [];

    this._previousClusters = [];
    this._previousHeight = undefined;

    this._enabledDirty = false;
    this._clusterDirty = false;

    this._cluster = undefined;
    this._removeEventListener = undefined;

    this._clusterEvent = new Event();

    /**
     * Determines if entities in this collection will be shown.
     *
     * @type {Boolean}
     * @default true
     */
    this.show = defaultValue(options.show, true);
  }

  function getX(point) {
    return point.coord.x;
  }

  function getY(point) {
    return point.coord.y;
  }

  function expandBoundingBox(bbox, pixelRange) {
    bbox.x -= pixelRange;
    bbox.y -= pixelRange;
    bbox.width += pixelRange * 2.0;
    bbox.height += pixelRange * 2.0;
  }

  const labelBoundingBoxScratch = new BoundingRectangle();

  function getBoundingBox(item, coord, pixelRange, entityCluster, result) {
    if (defined(item._labelCollection) && entityCluster._clusterLabels) {
      result = Label.getScreenSpaceBoundingBox(item, coord, result);
    } else if (
      defined(item._billboardCollection) &&
      entityCluster._clusterBillboards
    ) {
      result = Billboard.getScreenSpaceBoundingBox(item, coord, result);
    } else if (
      defined(item._pointPrimitiveCollection) &&
      entityCluster._clusterPoints
    ) {
      result = PointPrimitive.getScreenSpaceBoundingBox(item, coord, result);
    }

    expandBoundingBox(result, pixelRange);

    if (
      entityCluster._clusterLabels &&
      !defined(item._labelCollection) &&
      defined(item.id) &&
      hasLabelIndex(entityCluster, item.id.id) &&
      defined(item.id._label)
    ) {
      const labelIndex =
        entityCluster._collectionIndicesByEntity[item.id.id].labelIndex;
      const label = entityCluster._labelCollection.get(labelIndex);
      const labelBBox = Label.getScreenSpaceBoundingBox(
        label,
        coord,
        labelBoundingBoxScratch
      );
      expandBoundingBox(labelBBox, pixelRange);
      result = BoundingRectangle.union(result, labelBBox, result);
    }

    return result;
  }

  function addNonClusteredItem(item, entityCluster) {
    item.clusterShow = true;

    if (
      !defined(item._labelCollection) &&
      defined(item.id) &&
      hasLabelIndex(entityCluster, item.id.id) &&
      defined(item.id._label)
    ) {
      const labelIndex =
        entityCluster._collectionIndicesByEntity[item.id.id].labelIndex;
      const label = entityCluster._labelCollection.get(labelIndex);
      label.clusterShow = true;
    }
  }

  function addCluster(position, numPoints, ids, entityCluster) {
    const cluster = {
      billboard: entityCluster._clusterBillboardCollection.add(),
      label: entityCluster._clusterLabelCollection.add(),
      point: entityCluster._clusterPointCollection.add(),
    };

    cluster.billboard.show = false;
    cluster.point.show = false;
    cluster.label.show = true;
    cluster.label.text = numPoints.toLocaleString();
    cluster.label.id = ids;
    cluster.billboard.position = cluster.label.position = cluster.point.position = position;

    entityCluster._clusterEvent.raiseEvent(ids, cluster);
  }

  function hasLabelIndex(entityCluster, entityId) {
    return (
      defined(entityCluster) &&
      defined(entityCluster._collectionIndicesByEntity[entityId]) &&
      defined(entityCluster._collectionIndicesByEntity[entityId].labelIndex)
    );
  }

  function getScreenSpacePositions(
    collection,
    points,
    scene,
    occluder,
    entityCluster
  ) {
    if (!defined(collection)) {
      return;
    }

    const length = collection.length;
    for (let i = 0; i < length; ++i) {
      const item = collection.get(i);
      item.clusterShow = false;

      if (
        !item.show ||
        (entityCluster._scene.mode === SceneMode$1.SCENE3D &&
          !occluder.isPointVisible(item.position))
      ) {
        continue;
      }

      const canClusterLabels =
        entityCluster._clusterLabels && defined(item._labelCollection);
      const canClusterBillboards =
        entityCluster._clusterBillboards && defined(item.id._billboard);
      const canClusterPoints =
        entityCluster._clusterPoints && defined(item.id._point);
      if (canClusterLabels && (canClusterPoints || canClusterBillboards)) {
        continue;
      }

      const coord = item.computeScreenSpacePosition(scene);
      if (!defined(coord)) {
        continue;
      }

      points.push({
        index: i,
        collection: collection,
        clustered: false,
        coord: coord,
      });
    }
  }

  const pointBoundinRectangleScratch = new BoundingRectangle();
  const totalBoundingRectangleScratch = new BoundingRectangle();
  const neighborBoundingRectangleScratch = new BoundingRectangle();

  function createDeclutterCallback(entityCluster) {
    return function (amount) {
      if ((defined(amount) && amount < 0.05) || !entityCluster.enabled) {
        return;
      }

      const scene = entityCluster._scene;

      const labelCollection = entityCluster._labelCollection;
      const billboardCollection = entityCluster._billboardCollection;
      const pointCollection = entityCluster._pointCollection;

      if (
        (!defined(labelCollection) &&
          !defined(billboardCollection) &&
          !defined(pointCollection)) ||
        (!entityCluster._clusterBillboards &&
          !entityCluster._clusterLabels &&
          !entityCluster._clusterPoints)
      ) {
        return;
      }

      let clusteredLabelCollection = entityCluster._clusterLabelCollection;
      let clusteredBillboardCollection =
        entityCluster._clusterBillboardCollection;
      let clusteredPointCollection = entityCluster._clusterPointCollection;

      if (defined(clusteredLabelCollection)) {
        clusteredLabelCollection.removeAll();
      } else {
        clusteredLabelCollection = entityCluster._clusterLabelCollection = new LabelCollection(
          {
            scene: scene,
          }
        );
      }

      if (defined(clusteredBillboardCollection)) {
        clusteredBillboardCollection.removeAll();
      } else {
        clusteredBillboardCollection = entityCluster._clusterBillboardCollection = new BillboardCollection(
          {
            scene: scene,
          }
        );
      }

      if (defined(clusteredPointCollection)) {
        clusteredPointCollection.removeAll();
      } else {
        clusteredPointCollection = entityCluster._clusterPointCollection = new PointPrimitiveCollection();
      }

      const pixelRange = entityCluster._pixelRange;
      const minimumClusterSize = entityCluster._minimumClusterSize;

      const clusters = entityCluster._previousClusters;
      const newClusters = [];

      const previousHeight = entityCluster._previousHeight;
      const currentHeight = scene.camera.positionCartographic.height;

      const ellipsoid = scene.mapProjection.ellipsoid;
      const cameraPosition = scene.camera.positionWC;
      const occluder = new EllipsoidalOccluder(ellipsoid, cameraPosition);

      const points = [];
      if (entityCluster._clusterLabels) {
        getScreenSpacePositions(
          labelCollection,
          points,
          scene,
          occluder,
          entityCluster
        );
      }
      if (entityCluster._clusterBillboards) {
        getScreenSpacePositions(
          billboardCollection,
          points,
          scene,
          occluder,
          entityCluster
        );
      }
      if (entityCluster._clusterPoints) {
        getScreenSpacePositions(
          pointCollection,
          points,
          scene,
          occluder,
          entityCluster
        );
      }

      let i;
      let j;
      let length;
      let bbox;
      let neighbors;
      let neighborLength;
      let neighborIndex;
      let neighborPoint;
      let ids;
      let numPoints;

      let collection;
      let collectionIndex;

      const index = new KDBush(points, getX, getY, 64, Int32Array);

      if (currentHeight < previousHeight) {
        length = clusters.length;
        for (i = 0; i < length; ++i) {
          const cluster = clusters[i];

          if (!occluder.isPointVisible(cluster.position)) {
            continue;
          }

          const coord = Billboard._computeScreenSpacePosition(
            Matrix4.IDENTITY,
            cluster.position,
            Cartesian3.ZERO,
            Cartesian2.ZERO,
            scene
          );
          if (!defined(coord)) {
            continue;
          }

          const factor = 1.0 - currentHeight / previousHeight;
          let width = (cluster.width = cluster.width * factor);
          let height = (cluster.height = cluster.height * factor);

          width = Math.max(width, cluster.minimumWidth);
          height = Math.max(height, cluster.minimumHeight);

          const minX = coord.x - width * 0.5;
          const minY = coord.y - height * 0.5;
          const maxX = coord.x + width;
          const maxY = coord.y + height;

          neighbors = index.range(minX, minY, maxX, maxY);
          neighborLength = neighbors.length;
          numPoints = 0;
          ids = [];

          for (j = 0; j < neighborLength; ++j) {
            neighborIndex = neighbors[j];
            neighborPoint = points[neighborIndex];
            if (!neighborPoint.clustered) {
              ++numPoints;

              collection = neighborPoint.collection;
              collectionIndex = neighborPoint.index;
              ids.push(collection.get(collectionIndex).id);
            }
          }

          if (numPoints >= minimumClusterSize) {
            addCluster(cluster.position, numPoints, ids, entityCluster);
            newClusters.push(cluster);

            for (j = 0; j < neighborLength; ++j) {
              points[neighbors[j]].clustered = true;
            }
          }
        }
      }

      length = points.length;
      for (i = 0; i < length; ++i) {
        const point = points[i];
        if (point.clustered) {
          continue;
        }

        point.clustered = true;

        collection = point.collection;
        collectionIndex = point.index;

        const item = collection.get(collectionIndex);
        bbox = getBoundingBox(
          item,
          point.coord,
          pixelRange,
          entityCluster,
          pointBoundinRectangleScratch
        );
        const totalBBox = BoundingRectangle.clone(
          bbox,
          totalBoundingRectangleScratch
        );

        neighbors = index.range(
          bbox.x,
          bbox.y,
          bbox.x + bbox.width,
          bbox.y + bbox.height
        );
        neighborLength = neighbors.length;

        const clusterPosition = Cartesian3.clone(item.position);
        numPoints = 1;
        ids = [item.id];

        for (j = 0; j < neighborLength; ++j) {
          neighborIndex = neighbors[j];
          neighborPoint = points[neighborIndex];
          if (!neighborPoint.clustered) {
            const neighborItem = neighborPoint.collection.get(
              neighborPoint.index
            );
            const neighborBBox = getBoundingBox(
              neighborItem,
              neighborPoint.coord,
              pixelRange,
              entityCluster,
              neighborBoundingRectangleScratch
            );

            Cartesian3.add(
              neighborItem.position,
              clusterPosition,
              clusterPosition
            );

            BoundingRectangle.union(totalBBox, neighborBBox, totalBBox);
            ++numPoints;

            ids.push(neighborItem.id);
          }
        }

        if (numPoints >= minimumClusterSize) {
          const position = Cartesian3.multiplyByScalar(
            clusterPosition,
            1.0 / numPoints,
            clusterPosition
          );
          addCluster(position, numPoints, ids, entityCluster);
          newClusters.push({
            position: position,
            width: totalBBox.width,
            height: totalBBox.height,
            minimumWidth: bbox.width,
            minimumHeight: bbox.height,
          });

          for (j = 0; j < neighborLength; ++j) {
            points[neighbors[j]].clustered = true;
          }
        } else {
          addNonClusteredItem(item, entityCluster);
        }
      }

      if (clusteredLabelCollection.length === 0) {
        clusteredLabelCollection.destroy();
        entityCluster._clusterLabelCollection = undefined;
      }

      if (clusteredBillboardCollection.length === 0) {
        clusteredBillboardCollection.destroy();
        entityCluster._clusterBillboardCollection = undefined;
      }

      if (clusteredPointCollection.length === 0) {
        clusteredPointCollection.destroy();
        entityCluster._clusterPointCollection = undefined;
      }

      entityCluster._previousClusters = newClusters;
      entityCluster._previousHeight = currentHeight;
    };
  }

  EntityCluster.prototype._initialize = function (scene) {
    this._scene = scene;

    const cluster = createDeclutterCallback(this);
    this._cluster = cluster;
    this._removeEventListener = scene.camera.changed.addEventListener(cluster);
  };

  Object.defineProperties(EntityCluster.prototype, {
    /**
     * Gets or sets whether clustering is enabled.
     * @memberof EntityCluster.prototype
     * @type {Boolean}
     */
    enabled: {
      get: function () {
        return this._enabled;
      },
      set: function (value) {
        this._enabledDirty = value !== this._enabled;
        this._enabled = value;
      },
    },
    /**
     * Gets or sets the pixel range to extend the screen space bounding box.
     * @memberof EntityCluster.prototype
     * @type {Number}
     */
    pixelRange: {
      get: function () {
        return this._pixelRange;
      },
      set: function (value) {
        this._clusterDirty = this._clusterDirty || value !== this._pixelRange;
        this._pixelRange = value;
      },
    },
    /**
     * Gets or sets the minimum number of screen space objects that can be clustered.
     * @memberof EntityCluster.prototype
     * @type {Number}
     */
    minimumClusterSize: {
      get: function () {
        return this._minimumClusterSize;
      },
      set: function (value) {
        this._clusterDirty =
          this._clusterDirty || value !== this._minimumClusterSize;
        this._minimumClusterSize = value;
      },
    },
    /**
     * Gets the event that will be raised when a new cluster will be displayed. The signature of the event listener is {@link EntityCluster.newClusterCallback}.
     * @memberof EntityCluster.prototype
     * @type {Event<EntityCluster.newClusterCallback>}
     */
    clusterEvent: {
      get: function () {
        return this._clusterEvent;
      },
    },
    /**
     * Gets or sets whether clustering billboard entities is enabled.
     * @memberof EntityCluster.prototype
     * @type {Boolean}
     */
    clusterBillboards: {
      get: function () {
        return this._clusterBillboards;
      },
      set: function (value) {
        this._clusterDirty =
          this._clusterDirty || value !== this._clusterBillboards;
        this._clusterBillboards = value;
      },
    },
    /**
     * Gets or sets whether clustering labels entities is enabled.
     * @memberof EntityCluster.prototype
     * @type {Boolean}
     */
    clusterLabels: {
      get: function () {
        return this._clusterLabels;
      },
      set: function (value) {
        this._clusterDirty = this._clusterDirty || value !== this._clusterLabels;
        this._clusterLabels = value;
      },
    },
    /**
     * Gets or sets whether clustering point entities is enabled.
     * @memberof EntityCluster.prototype
     * @type {Boolean}
     */
    clusterPoints: {
      get: function () {
        return this._clusterPoints;
      },
      set: function (value) {
        this._clusterDirty = this._clusterDirty || value !== this._clusterPoints;
        this._clusterPoints = value;
      },
    },
  });

  function createGetEntity(
    collectionProperty,
    CollectionConstructor,
    unusedIndicesProperty,
    entityIndexProperty
  ) {
    return function (entity) {
      let collection = this[collectionProperty];

      if (!defined(this._collectionIndicesByEntity)) {
        this._collectionIndicesByEntity = {};
      }

      let entityIndices = this._collectionIndicesByEntity[entity.id];

      if (!defined(entityIndices)) {
        entityIndices = this._collectionIndicesByEntity[entity.id] = {
          billboardIndex: undefined,
          labelIndex: undefined,
          pointIndex: undefined,
        };
      }

      if (defined(collection) && defined(entityIndices[entityIndexProperty])) {
        return collection.get(entityIndices[entityIndexProperty]);
      }

      if (!defined(collection)) {
        collection = this[collectionProperty] = new CollectionConstructor({
          scene: this._scene,
        });
      }

      let index;
      let entityItem;

      const unusedIndices = this[unusedIndicesProperty];
      if (unusedIndices.length > 0) {
        index = unusedIndices.pop();
        entityItem = collection.get(index);
      } else {
        entityItem = collection.add();
        index = collection.length - 1;
      }

      entityIndices[entityIndexProperty] = index;

      const that = this;
      Promise.resolve().then(function () {
        that._clusterDirty = true;
      });

      return entityItem;
    };
  }

  function removeEntityIndicesIfUnused(entityCluster, entityId) {
    const indices = entityCluster._collectionIndicesByEntity[entityId];

    if (
      !defined(indices.billboardIndex) &&
      !defined(indices.labelIndex) &&
      !defined(indices.pointIndex)
    ) {
      delete entityCluster._collectionIndicesByEntity[entityId];
    }
  }

  /**
   * Returns a new {@link Label}.
   * @param {Entity} entity The entity that will use the returned {@link Label} for visualization.
   * @returns {Label} The label that will be used to visualize an entity.
   *
   * @private
   */
  EntityCluster.prototype.getLabel = createGetEntity(
    "_labelCollection",
    LabelCollection,
    "_unusedLabelIndices",
    "labelIndex"
  );

  /**
   * Removes the {@link Label} associated with an entity so it can be reused by another entity.
   * @param {Entity} entity The entity that will uses the returned {@link Label} for visualization.
   *
   * @private
   */
  EntityCluster.prototype.removeLabel = function (entity) {
    const entityIndices =
      this._collectionIndicesByEntity &&
      this._collectionIndicesByEntity[entity.id];
    if (
      !defined(this._labelCollection) ||
      !defined(entityIndices) ||
      !defined(entityIndices.labelIndex)
    ) {
      return;
    }

    const index = entityIndices.labelIndex;
    entityIndices.labelIndex = undefined;
    removeEntityIndicesIfUnused(this, entity.id);

    const label = this._labelCollection.get(index);
    label.show = false;
    label.text = "";
    label.id = undefined;

    this._unusedLabelIndices.push(index);

    this._clusterDirty = true;
  };

  /**
   * Returns a new {@link Billboard}.
   * @param {Entity} entity The entity that will use the returned {@link Billboard} for visualization.
   * @returns {Billboard} The label that will be used to visualize an entity.
   *
   * @private
   */
  EntityCluster.prototype.getBillboard = createGetEntity(
    "_billboardCollection",
    BillboardCollection,
    "_unusedBillboardIndices",
    "billboardIndex"
  );

  /**
   * Removes the {@link Billboard} associated with an entity so it can be reused by another entity.
   * @param {Entity} entity The entity that will uses the returned {@link Billboard} for visualization.
   *
   * @private
   */
  EntityCluster.prototype.removeBillboard = function (entity) {
    const entityIndices =
      this._collectionIndicesByEntity &&
      this._collectionIndicesByEntity[entity.id];
    if (
      !defined(this._billboardCollection) ||
      !defined(entityIndices) ||
      !defined(entityIndices.billboardIndex)
    ) {
      return;
    }

    const index = entityIndices.billboardIndex;
    entityIndices.billboardIndex = undefined;
    removeEntityIndicesIfUnused(this, entity.id);

    const billboard = this._billboardCollection.get(index);
    billboard.id = undefined;
    billboard.show = false;
    billboard.image = undefined;

    this._unusedBillboardIndices.push(index);

    this._clusterDirty = true;
  };

  /**
   * Returns a new {@link Point}.
   * @param {Entity} entity The entity that will use the returned {@link Point} for visualization.
   * @returns {Point} The label that will be used to visualize an entity.
   *
   * @private
   */
  EntityCluster.prototype.getPoint = createGetEntity(
    "_pointCollection",
    PointPrimitiveCollection,
    "_unusedPointIndices",
    "pointIndex"
  );

  /**
   * Removes the {@link Point} associated with an entity so it can be reused by another entity.
   * @param {Entity} entity The entity that will uses the returned {@link Point} for visualization.
   *
   * @private
   */
  EntityCluster.prototype.removePoint = function (entity) {
    const entityIndices =
      this._collectionIndicesByEntity &&
      this._collectionIndicesByEntity[entity.id];
    if (
      !defined(this._pointCollection) ||
      !defined(entityIndices) ||
      !defined(entityIndices.pointIndex)
    ) {
      return;
    }

    const index = entityIndices.pointIndex;
    entityIndices.pointIndex = undefined;
    removeEntityIndicesIfUnused(this, entity.id);

    const point = this._pointCollection.get(index);
    point.show = false;
    point.id = undefined;

    this._unusedPointIndices.push(index);

    this._clusterDirty = true;
  };

  function disableCollectionClustering(collection) {
    if (!defined(collection)) {
      return;
    }

    const length = collection.length;
    for (let i = 0; i < length; ++i) {
      collection.get(i).clusterShow = true;
    }
  }

  function updateEnable(entityCluster) {
    if (entityCluster.enabled) {
      return;
    }

    if (defined(entityCluster._clusterLabelCollection)) {
      entityCluster._clusterLabelCollection.destroy();
    }
    if (defined(entityCluster._clusterBillboardCollection)) {
      entityCluster._clusterBillboardCollection.destroy();
    }
    if (defined(entityCluster._clusterPointCollection)) {
      entityCluster._clusterPointCollection.destroy();
    }

    entityCluster._clusterLabelCollection = undefined;
    entityCluster._clusterBillboardCollection = undefined;
    entityCluster._clusterPointCollection = undefined;

    disableCollectionClustering(entityCluster._labelCollection);
    disableCollectionClustering(entityCluster._billboardCollection);
    disableCollectionClustering(entityCluster._pointCollection);
  }

  /**
   * Gets the draw commands for the clustered billboards/points/labels if enabled, otherwise,
   * queues the draw commands for billboards/points/labels created for entities.
   * @private
   */
  EntityCluster.prototype.update = function (frameState) {
    if (!this.show) {
      return;
    }

    // If clustering is enabled before the label collection is updated,
    // the glyphs haven't been created so the screen space bounding boxes
    // are incorrect.
    let commandList;
    if (
      defined(this._labelCollection) &&
      this._labelCollection.length > 0 &&
      this._labelCollection.get(0)._glyphs.length === 0
    ) {
      commandList = frameState.commandList;
      frameState.commandList = [];
      this._labelCollection.update(frameState);
      frameState.commandList = commandList;
    }

    // If clustering is enabled before the billboard collection is updated,
    // the images haven't been added to the image atlas so the screen space bounding boxes
    // are incorrect.
    if (
      defined(this._billboardCollection) &&
      this._billboardCollection.length > 0 &&
      !defined(this._billboardCollection.get(0).width)
    ) {
      commandList = frameState.commandList;
      frameState.commandList = [];
      this._billboardCollection.update(frameState);
      frameState.commandList = commandList;
    }

    if (this._enabledDirty) {
      this._enabledDirty = false;
      updateEnable(this);
      this._clusterDirty = true;
    }

    if (this._clusterDirty) {
      this._clusterDirty = false;
      this._cluster();
    }

    if (defined(this._clusterLabelCollection)) {
      this._clusterLabelCollection.update(frameState);
    }
    if (defined(this._clusterBillboardCollection)) {
      this._clusterBillboardCollection.update(frameState);
    }
    if (defined(this._clusterPointCollection)) {
      this._clusterPointCollection.update(frameState);
    }

    if (defined(this._labelCollection)) {
      this._labelCollection.update(frameState);
    }
    if (defined(this._billboardCollection)) {
      this._billboardCollection.update(frameState);
    }
    if (defined(this._pointCollection)) {
      this._pointCollection.update(frameState);
    }
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <p>
   * Unlike other objects that use WebGL resources, this object can be reused. For example, if a data source is removed
   * from a data source collection and added to another.
   * </p>
   */
  EntityCluster.prototype.destroy = function () {
    this._labelCollection =
      this._labelCollection && this._labelCollection.destroy();
    this._billboardCollection =
      this._billboardCollection && this._billboardCollection.destroy();
    this._pointCollection =
      this._pointCollection && this._pointCollection.destroy();

    this._clusterLabelCollection =
      this._clusterLabelCollection && this._clusterLabelCollection.destroy();
    this._clusterBillboardCollection =
      this._clusterBillboardCollection &&
      this._clusterBillboardCollection.destroy();
    this._clusterPointCollection =
      this._clusterPointCollection && this._clusterPointCollection.destroy();

    if (defined(this._removeEventListener)) {
      this._removeEventListener();
      this._removeEventListener = undefined;
    }

    this._labelCollection = undefined;
    this._billboardCollection = undefined;
    this._pointCollection = undefined;

    this._clusterBillboardCollection = undefined;
    this._clusterLabelCollection = undefined;
    this._clusterPointCollection = undefined;

    this._collectionIndicesByEntity = undefined;

    this._unusedLabelIndices = [];
    this._unusedBillboardIndices = [];
    this._unusedPointIndices = [];

    this._previousClusters = [];
    this._previousHeight = undefined;

    this._enabledDirty = false;
    this._pixelRangeDirty = false;
    this._minimumClusterSizeDirty = false;

    return undefined;
  };

  /**
   * A {@link DataSource} implementation which can be used to manually manage a group of entities.
   *
   * @alias CustomDataSource
   * @constructor
   *
   * @param {String} [name] A human-readable name for this instance.
   *
   * @example
   * const dataSource = new Cesium.CustomDataSource('myData');
   *
   * const entity = dataSource.entities.add({
   *    position : Cesium.Cartesian3.fromDegrees(1, 2, 0),
   *    billboard : {
   *        image : 'image.png'
   *    }
   * });
   *
   * viewer.dataSources.add(dataSource);
   */
  function CustomDataSource(name) {
    this._name = name;
    this._clock = undefined;
    this._changed = new Event();
    this._error = new Event();
    this._isLoading = false;
    this._loading = new Event();
    this._entityCollection = new EntityCollection(this);
    this._entityCluster = new EntityCluster();
  }

  Object.defineProperties(CustomDataSource.prototype, {
    /**
     * Gets or sets a human-readable name for this instance.
     * @memberof CustomDataSource.prototype
     * @type {String}
     */
    name: {
      get: function () {
        return this._name;
      },
      set: function (value) {
        if (this._name !== value) {
          this._name = value;
          this._changed.raiseEvent(this);
        }
      },
    },
    /**
     * Gets or sets the clock for this instance.
     * @memberof CustomDataSource.prototype
     * @type {DataSourceClock}
     */
    clock: {
      get: function () {
        return this._clock;
      },
      set: function (value) {
        if (this._clock !== value) {
          this._clock = value;
          this._changed.raiseEvent(this);
        }
      },
    },
    /**
     * Gets the collection of {@link Entity} instances.
     * @memberof CustomDataSource.prototype
     * @type {EntityCollection}
     */
    entities: {
      get: function () {
        return this._entityCollection;
      },
    },
    /**
     * Gets or sets whether the data source is currently loading data.
     * @memberof CustomDataSource.prototype
     * @type {Boolean}
     */
    isLoading: {
      get: function () {
        return this._isLoading;
      },
      set: function (value) {
        DataSource.setLoading(this, value);
      },
    },
    /**
     * Gets an event that will be raised when the underlying data changes.
     * @memberof CustomDataSource.prototype
     * @type {Event}
     */
    changedEvent: {
      get: function () {
        return this._changed;
      },
    },
    /**
     * Gets an event that will be raised if an error is encountered during processing.
     * @memberof CustomDataSource.prototype
     * @type {Event}
     */
    errorEvent: {
      get: function () {
        return this._error;
      },
    },
    /**
     * Gets an event that will be raised when the data source either starts or stops loading.
     * @memberof CustomDataSource.prototype
     * @type {Event}
     */
    loadingEvent: {
      get: function () {
        return this._loading;
      },
    },
    /**
     * Gets whether or not this data source should be displayed.
     * @memberof CustomDataSource.prototype
     * @type {Boolean}
     */
    show: {
      get: function () {
        return this._entityCollection.show;
      },
      set: function (value) {
        this._entityCollection.show = value;
      },
    },

    /**
     * Gets or sets the clustering options for this data source. This object can be shared between multiple data sources.
     *
     * @memberof CustomDataSource.prototype
     * @type {EntityCluster}
     */
    clustering: {
      get: function () {
        return this._entityCluster;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value must be defined.");
        }
        //>>includeEnd('debug');
        this._entityCluster = value;
      },
    },
  });

  /**
   * Updates the data source to the provided time.  This function is optional and
   * is not required to be implemented.  It is provided for data sources which
   * retrieve data based on the current animation time or scene state.
   * If implemented, update will be called by {@link DataSourceDisplay} once a frame.
   *
   * @param {JulianDate} time The simulation time.
   * @returns {Boolean} True if this data source is ready to be displayed at the provided time, false otherwise.
   */
  CustomDataSource.prototype.update = function (time) {
    return true;
  };

  const defaultOffset$8 = Cartesian3.ZERO;

  const offsetScratch$7 = new Cartesian3();
  const positionScratch$4 = new Cartesian3();
  const scratchColor$c = new Color();

  function CylinderGeometryOptions(entity) {
    this.id = entity;
    this.vertexFormat = undefined;
    this.length = undefined;
    this.topRadius = undefined;
    this.bottomRadius = undefined;
    this.slices = undefined;
    this.numberOfVerticalLines = undefined;
    this.offsetAttribute = undefined;
  }

  /**
   * A {@link GeometryUpdater} for cylinders.
   * Clients do not normally create this class directly, but instead rely on {@link DataSourceDisplay}.
   * @alias CylinderGeometryUpdater
   * @constructor
   *
   * @param {Entity} entity The entity containing the geometry to be visualized.
   * @param {Scene} scene The scene where visualization is taking place.
   */
  function CylinderGeometryUpdater(entity, scene) {
    GeometryUpdater.call(this, {
      entity: entity,
      scene: scene,
      geometryOptions: new CylinderGeometryOptions(entity),
      geometryPropertyName: "cylinder",
      observedPropertyNames: [
        "availability",
        "position",
        "orientation",
        "cylinder",
      ],
    });

    this._onEntityPropertyChanged(entity, "cylinder", entity.cylinder, undefined);
  }

  if (defined(Object.create)) {
    CylinderGeometryUpdater.prototype = Object.create(GeometryUpdater.prototype);
    CylinderGeometryUpdater.prototype.constructor = CylinderGeometryUpdater;
  }

  Object.defineProperties(CylinderGeometryUpdater.prototype, {
    /**
     * Gets the terrain offset property
     * @type {TerrainOffsetProperty}
     * @memberof CylinderGeometryUpdater.prototype
     * @readonly
     * @private
     */
    terrainOffsetProperty: {
      get: function () {
        return this._terrainOffsetProperty;
      },
    },
  });

  /**
   * Creates the geometry instance which represents the fill of the geometry.
   *
   * @param {JulianDate} time The time to use when retrieving initial attribute values.
   * @returns {GeometryInstance} The geometry instance representing the filled portion of the geometry.
   *
   * @exception {DeveloperError} This instance does not represent a filled geometry.
   */
  CylinderGeometryUpdater.prototype.createFillGeometryInstance = function (time) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("time", time);

    if (!this._fillEnabled) {
      throw new DeveloperError(
        "This instance does not represent a filled geometry."
      );
    }
    //>>includeEnd('debug');

    const entity = this._entity;
    const isAvailable = entity.isAvailable(time);

    const show = new ShowGeometryInstanceAttribute(
      isAvailable &&
        entity.isShowing &&
        this._showProperty.getValue(time) &&
        this._fillProperty.getValue(time)
    );
    const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
      time
    );
    const distanceDisplayConditionAttribute = DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
      distanceDisplayCondition
    );

    const attributes = {
      show: show,
      distanceDisplayCondition: distanceDisplayConditionAttribute,
      color: undefined,
      offset: undefined,
    };
    if (this._materialProperty instanceof ColorMaterialProperty) {
      let currentColor;
      if (
        defined(this._materialProperty.color) &&
        (this._materialProperty.color.isConstant || isAvailable)
      ) {
        currentColor = this._materialProperty.color.getValue(time, scratchColor$c);
      }
      if (!defined(currentColor)) {
        currentColor = Color.WHITE;
      }
      attributes.color = ColorGeometryInstanceAttribute.fromColor(currentColor);
    }

    if (defined(this._options.offsetAttribute)) {
      attributes.offset = OffsetGeometryInstanceAttribute.fromCartesian3(
        Property.getValueOrDefault(
          this._terrainOffsetProperty,
          time,
          defaultOffset$8,
          offsetScratch$7
        )
      );
    }

    return new GeometryInstance({
      id: entity,
      geometry: new CylinderGeometry(this._options),
      modelMatrix: entity.computeModelMatrixForHeightReference(
        time,
        entity.cylinder.heightReference,
        this._options.length * 0.5,
        this._scene.mapProjection.ellipsoid
      ),
      attributes: attributes,
    });
  };

  /**
   * Creates the geometry instance which represents the outline of the geometry.
   *
   * @param {JulianDate} time The time to use when retrieving initial attribute values.
   * @returns {GeometryInstance} The geometry instance representing the outline portion of the geometry.
   *
   * @exception {DeveloperError} This instance does not represent an outlined geometry.
   */
  CylinderGeometryUpdater.prototype.createOutlineGeometryInstance = function (
    time
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("time", time);

    if (!this._outlineEnabled) {
      throw new DeveloperError(
        "This instance does not represent an outlined geometry."
      );
    }
    //>>includeEnd('debug');

    const entity = this._entity;
    const isAvailable = entity.isAvailable(time);
    const outlineColor = Property.getValueOrDefault(
      this._outlineColorProperty,
      time,
      Color.BLACK,
      scratchColor$c
    );
    const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
      time
    );

    const attributes = {
      show: new ShowGeometryInstanceAttribute(
        isAvailable &&
          entity.isShowing &&
          this._showProperty.getValue(time) &&
          this._showOutlineProperty.getValue(time)
      ),
      color: ColorGeometryInstanceAttribute.fromColor(outlineColor),
      distanceDisplayCondition: DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
        distanceDisplayCondition
      ),
      offset: undefined,
    };
    if (defined(this._options.offsetAttribute)) {
      attributes.offset = OffsetGeometryInstanceAttribute.fromCartesian3(
        Property.getValueOrDefault(
          this._terrainOffsetProperty,
          time,
          defaultOffset$8,
          offsetScratch$7
        )
      );
    }

    return new GeometryInstance({
      id: entity,
      geometry: new CylinderOutlineGeometry(this._options),
      modelMatrix: entity.computeModelMatrixForHeightReference(
        time,
        entity.cylinder.heightReference,
        this._options.length * 0.5,
        this._scene.mapProjection.ellipsoid
      ),
      attributes: attributes,
    });
  };

  CylinderGeometryUpdater.prototype._computeCenter = function (time, result) {
    return Property.getValueOrUndefined(this._entity.position, time, result);
  };

  CylinderGeometryUpdater.prototype._isHidden = function (entity, cylinder) {
    return (
      !defined(entity.position) ||
      !defined(cylinder.length) ||
      !defined(cylinder.topRadius) ||
      !defined(cylinder.bottomRadius) ||
      GeometryUpdater.prototype._isHidden.call(this, entity, cylinder)
    );
  };

  CylinderGeometryUpdater.prototype._isDynamic = function (entity, cylinder) {
    return (
      !entity.position.isConstant || //
      !Property.isConstant(entity.orientation) || //
      !cylinder.length.isConstant || //
      !cylinder.topRadius.isConstant || //
      !cylinder.bottomRadius.isConstant || //
      !Property.isConstant(cylinder.slices) || //
      !Property.isConstant(cylinder.outlineWidth) || //
      !Property.isConstant(cylinder.numberOfVerticalLines)
    );
  };

  CylinderGeometryUpdater.prototype._setStaticOptions = function (
    entity,
    cylinder
  ) {
    const heightReference = Property.getValueOrDefault(
      cylinder.heightReference,
      Iso8601.MINIMUM_VALUE,
      HeightReference$1.NONE
    );
    const options = this._options;
    options.vertexFormat =
      this._materialProperty instanceof ColorMaterialProperty
        ? PerInstanceColorAppearance.VERTEX_FORMAT
        : MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat;
    options.length = cylinder.length.getValue(Iso8601.MINIMUM_VALUE);
    options.topRadius = cylinder.topRadius.getValue(Iso8601.MINIMUM_VALUE);
    options.bottomRadius = cylinder.bottomRadius.getValue(Iso8601.MINIMUM_VALUE);
    options.slices = Property.getValueOrUndefined(
      cylinder.slices,
      Iso8601.MINIMUM_VALUE
    );
    options.numberOfVerticalLines = Property.getValueOrUndefined(
      cylinder.numberOfVerticalLines,
      Iso8601.MINIMUM_VALUE
    );
    options.offsetAttribute =
      heightReference !== HeightReference$1.NONE
        ? GeometryOffsetAttribute$1.ALL
        : undefined;
  };

  CylinderGeometryUpdater.prototype._onEntityPropertyChanged = heightReferenceOnEntityPropertyChanged;

  CylinderGeometryUpdater.DynamicGeometryUpdater = DynamicCylinderGeometryUpdater;

  /**
   * @private
   */
  function DynamicCylinderGeometryUpdater(
    geometryUpdater,
    primitives,
    groundPrimitives
  ) {
    DynamicGeometryUpdater$1.call(
      this,
      geometryUpdater,
      primitives,
      groundPrimitives
    );
  }

  if (defined(Object.create)) {
    DynamicCylinderGeometryUpdater.prototype = Object.create(
      DynamicGeometryUpdater$1.prototype
    );
    DynamicCylinderGeometryUpdater.prototype.constructor = DynamicCylinderGeometryUpdater;
  }

  DynamicCylinderGeometryUpdater.prototype._isHidden = function (
    entity,
    cylinder,
    time
  ) {
    const options = this._options;
    const position = Property.getValueOrUndefined(
      entity.position,
      time,
      positionScratch$4
    );
    return (
      !defined(position) ||
      !defined(options.length) ||
      !defined(options.topRadius) || //
      !defined(options.bottomRadius) ||
      DynamicGeometryUpdater$1.prototype._isHidden.call(
        this,
        entity,
        cylinder,
        time
      )
    );
  };

  DynamicCylinderGeometryUpdater.prototype._setOptions = function (
    entity,
    cylinder,
    time
  ) {
    const heightReference = Property.getValueOrDefault(
      cylinder.heightReference,
      time,
      HeightReference$1.NONE
    );
    const options = this._options;
    options.length = Property.getValueOrUndefined(cylinder.length, time);
    options.topRadius = Property.getValueOrUndefined(cylinder.topRadius, time);
    options.bottomRadius = Property.getValueOrUndefined(
      cylinder.bottomRadius,
      time
    );
    options.slices = Property.getValueOrUndefined(cylinder.slices, time);
    options.numberOfVerticalLines = Property.getValueOrUndefined(
      cylinder.numberOfVerticalLines,
      time
    );
    options.offsetAttribute =
      heightReference !== HeightReference$1.NONE
        ? GeometryOffsetAttribute$1.ALL
        : undefined;
  };

  /**
   * Represents desired clock settings for a particular {@link DataSource}.  These settings may be applied
   * to the {@link Clock} when the DataSource is loaded.
   *
   * @alias DataSourceClock
   * @constructor
   */
  function DataSourceClock() {
    this._definitionChanged = new Event();
    this._startTime = undefined;
    this._stopTime = undefined;
    this._currentTime = undefined;
    this._clockRange = undefined;
    this._clockStep = undefined;
    this._multiplier = undefined;
  }

  Object.defineProperties(DataSourceClock.prototype, {
    /**
     * Gets the event that is raised whenever a new property is assigned.
     * @memberof DataSourceClock.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },

    /**
     * Gets or sets the desired start time of the clock.
     * See {@link Clock#startTime}.
     * @memberof DataSourceClock.prototype
     * @type {JulianDate}
     */
    startTime: createRawPropertyDescriptor("startTime"),

    /**
     * Gets or sets the desired stop time of the clock.
     * See {@link Clock#stopTime}.
     * @memberof DataSourceClock.prototype
     * @type {JulianDate}
     */
    stopTime: createRawPropertyDescriptor("stopTime"),

    /**
     * Gets or sets the desired current time when this data source is loaded.
     * See {@link Clock#currentTime}.
     * @memberof DataSourceClock.prototype
     * @type {JulianDate}
     */
    currentTime: createRawPropertyDescriptor("currentTime"),

    /**
     * Gets or sets the desired clock range setting.
     * See {@link Clock#clockRange}.
     * @memberof DataSourceClock.prototype
     * @type {ClockRange}
     */
    clockRange: createRawPropertyDescriptor("clockRange"),

    /**
     * Gets or sets the desired clock step setting.
     * See {@link Clock#clockStep}.
     * @memberof DataSourceClock.prototype
     * @type {ClockStep}
     */
    clockStep: createRawPropertyDescriptor("clockStep"),

    /**
     * Gets or sets the desired clock multiplier.
     * See {@link Clock#multiplier}.
     * @memberof DataSourceClock.prototype
     * @type {Number}
     */
    multiplier: createRawPropertyDescriptor("multiplier"),
  });

  /**
   * Duplicates a DataSourceClock instance.
   *
   * @param {DataSourceClock} [result] The object onto which to store the result.
   * @returns {DataSourceClock} The modified result parameter or a new instance if one was not provided.
   */
  DataSourceClock.prototype.clone = function (result) {
    if (!defined(result)) {
      result = new DataSourceClock();
    }
    result.startTime = this.startTime;
    result.stopTime = this.stopTime;
    result.currentTime = this.currentTime;
    result.clockRange = this.clockRange;
    result.clockStep = this.clockStep;
    result.multiplier = this.multiplier;
    return result;
  };

  /**
   * Returns true if this DataSourceClock is equivalent to the other
   *
   * @param {DataSourceClock} other The other DataSourceClock to compare to.
   * @returns {Boolean} <code>true</code> if the DataSourceClocks are equal; otherwise, <code>false</code>.
   */
  DataSourceClock.prototype.equals = function (other) {
    return (
      this === other ||
      (defined(other) &&
        JulianDate.equals(this.startTime, other.startTime) &&
        JulianDate.equals(this.stopTime, other.stopTime) &&
        JulianDate.equals(this.currentTime, other.currentTime) &&
        this.clockRange === other.clockRange &&
        this.clockStep === other.clockStep &&
        this.multiplier === other.multiplier)
    );
  };

  /**
   * Assigns each unassigned property on this object to the value
   * of the same property on the provided source object.
   *
   * @param {DataSourceClock} source The object to be merged into this object.
   */
  DataSourceClock.prototype.merge = function (source) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(source)) {
      throw new DeveloperError("source is required.");
    }
    //>>includeEnd('debug');

    this.startTime = defaultValue(this.startTime, source.startTime);
    this.stopTime = defaultValue(this.stopTime, source.stopTime);
    this.currentTime = defaultValue(this.currentTime, source.currentTime);
    this.clockRange = defaultValue(this.clockRange, source.clockRange);
    this.clockStep = defaultValue(this.clockStep, source.clockStep);
    this.multiplier = defaultValue(this.multiplier, source.multiplier);
  };

  /**
   * Gets the value of this clock instance as a {@link Clock} object.
   *
   * @returns {Clock} The modified result parameter or a new instance if one was not provided.
   */
  DataSourceClock.prototype.getValue = function (result) {
    if (!defined(result)) {
      result = new Clock();
    }
    result.startTime = defaultValue(this.startTime, result.startTime);
    result.stopTime = defaultValue(this.stopTime, result.stopTime);
    result.currentTime = defaultValue(this.currentTime, result.currentTime);
    result.clockRange = defaultValue(this.clockRange, result.clockRange);
    result.multiplier = defaultValue(this.multiplier, result.multiplier);
    result.clockStep = defaultValue(this.clockStep, result.clockStep);
    return result;
  };

  const defaultColor$6 = Color.WHITE;
  const defaultCellAlpha = 0.1;
  const defaultLineCount = new Cartesian2(8, 8);
  const defaultLineOffset = new Cartesian2(0, 0);
  const defaultLineThickness = new Cartesian2(1, 1);

  /**
   * A {@link MaterialProperty} that maps to grid {@link Material} uniforms.
   * @alias GridMaterialProperty
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Property|Color} [options.color=Color.WHITE] A Property specifying the grid {@link Color}.
   * @param {Property|Number} [options.cellAlpha=0.1] A numeric Property specifying cell alpha values.
   * @param {Property|Cartesian2} [options.lineCount=new Cartesian2(8, 8)] A {@link Cartesian2} Property specifying the number of grid lines along each axis.
   * @param {Property|Cartesian2} [options.lineThickness=new Cartesian2(1.0, 1.0)] A {@link Cartesian2} Property specifying the thickness of grid lines along each axis.
   * @param {Property|Cartesian2} [options.lineOffset=new Cartesian2(0.0, 0.0)] A {@link Cartesian2} Property specifying starting offset of grid lines along each axis.
   *
   * @constructor
   */
  function GridMaterialProperty(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    this._definitionChanged = new Event();
    this._color = undefined;
    this._colorSubscription = undefined;
    this._cellAlpha = undefined;
    this._cellAlphaSubscription = undefined;
    this._lineCount = undefined;
    this._lineCountSubscription = undefined;
    this._lineThickness = undefined;
    this._lineThicknessSubscription = undefined;
    this._lineOffset = undefined;
    this._lineOffsetSubscription = undefined;

    this.color = options.color;
    this.cellAlpha = options.cellAlpha;
    this.lineCount = options.lineCount;
    this.lineThickness = options.lineThickness;
    this.lineOffset = options.lineOffset;
  }

  Object.defineProperties(GridMaterialProperty.prototype, {
    /**
     * Gets a value indicating if this property is constant.  A property is considered
     * constant if getValue always returns the same result for the current definition.
     * @memberof GridMaterialProperty.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    isConstant: {
      get: function () {
        return (
          Property.isConstant(this._color) &&
          Property.isConstant(this._cellAlpha) &&
          Property.isConstant(this._lineCount) &&
          Property.isConstant(this._lineThickness) &&
          Property.isConstant(this._lineOffset)
        );
      },
    },

    /**
     * Gets the event that is raised whenever the definition of this property changes.
     * The definition is considered to have changed if a call to getValue would return
     * a different result for the same time.
     * @memberof GridMaterialProperty.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },

    /**
     * Gets or sets the Property specifying the grid {@link Color}.
     * @memberof GridMaterialProperty.prototype
     * @type {Property|undefined}
     * @default Color.WHITE
     */
    color: createPropertyDescriptor("color"),

    /**
     * Gets or sets the numeric Property specifying cell alpha values.
     * @memberof GridMaterialProperty.prototype
     * @type {Property|undefined}
     * @default 0.1
     */
    cellAlpha: createPropertyDescriptor("cellAlpha"),

    /**
     * Gets or sets the {@link Cartesian2} Property specifying the number of grid lines along each axis.
     * @memberof GridMaterialProperty.prototype
     * @type {Property|undefined}
     * @default new Cartesian2(8.0, 8.0)
     */
    lineCount: createPropertyDescriptor("lineCount"),

    /**
     * Gets or sets the {@link Cartesian2} Property specifying the thickness of grid lines along each axis.
     * @memberof GridMaterialProperty.prototype
     * @type {Property|undefined}
     * @default new Cartesian2(1.0, 1.0)
     */
    lineThickness: createPropertyDescriptor("lineThickness"),

    /**
     * Gets or sets the {@link Cartesian2} Property specifying the starting offset of grid lines along each axis.
     * @memberof GridMaterialProperty.prototype
     * @type {Property|undefined}
     * @default new Cartesian2(0.0, 0.0)
     */
    lineOffset: createPropertyDescriptor("lineOffset"),
  });

  /**
   * Gets the {@link Material} type at the provided time.
   *
   * @param {JulianDate} time The time for which to retrieve the type.
   * @returns {String} The type of material.
   */
  GridMaterialProperty.prototype.getType = function (time) {
    return "Grid";
  };

  /**
   * Gets the value of the property at the provided time.
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {Object} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Object} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  GridMaterialProperty.prototype.getValue = function (time, result) {
    if (!defined(result)) {
      result = {};
    }
    result.color = Property.getValueOrClonedDefault(
      this._color,
      time,
      defaultColor$6,
      result.color
    );
    result.cellAlpha = Property.getValueOrDefault(
      this._cellAlpha,
      time,
      defaultCellAlpha
    );
    result.lineCount = Property.getValueOrClonedDefault(
      this._lineCount,
      time,
      defaultLineCount,
      result.lineCount
    );
    result.lineThickness = Property.getValueOrClonedDefault(
      this._lineThickness,
      time,
      defaultLineThickness,
      result.lineThickness
    );
    result.lineOffset = Property.getValueOrClonedDefault(
      this._lineOffset,
      time,
      defaultLineOffset,
      result.lineOffset
    );
    return result;
  };

  /**
   * Compares this property to the provided property and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Property} [other] The other property.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  GridMaterialProperty.prototype.equals = function (other) {
    return (
      this === other || //
      (other instanceof GridMaterialProperty && //
        Property.equals(this._color, other._color) && //
        Property.equals(this._cellAlpha, other._cellAlpha) && //
        Property.equals(this._lineCount, other._lineCount) && //
        Property.equals(this._lineThickness, other._lineThickness) && //
        Property.equals(this._lineOffset, other._lineOffset))
    );
  };

  /**
   * A {@link MaterialProperty} that maps to PolylineArrow {@link Material} uniforms.
   *
   * @param {Property|Color} [color=Color.WHITE] The {@link Color} Property to be used.
   *
   * @alias PolylineArrowMaterialProperty
   * @constructor
   */
  function PolylineArrowMaterialProperty(color) {
    this._definitionChanged = new Event();
    this._color = undefined;
    this._colorSubscription = undefined;

    this.color = color;
  }

  Object.defineProperties(PolylineArrowMaterialProperty.prototype, {
    /**
     * Gets a value indicating if this property is constant.  A property is considered
     * constant if getValue always returns the same result for the current definition.
     * @memberof PolylineArrowMaterialProperty.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    isConstant: {
      get: function () {
        return Property.isConstant(this._color);
      },
    },
    /**
     * Gets the event that is raised whenever the definition of this property changes.
     * The definition is considered to have changed if a call to getValue would return
     * a different result for the same time.
     * @memberof PolylineArrowMaterialProperty.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },
    /**
     * Gets or sets the {@link Color} {@link Property}.
     * @memberof PolylineArrowMaterialProperty.prototype
     * @type {Property|undefined}
     * @default Color.WHITE
     */
    color: createPropertyDescriptor("color"),
  });

  /**
   * Gets the {@link Material} type at the provided time.
   *
   * @param {JulianDate} time The time for which to retrieve the type.
   * @returns {String} The type of material.
   */
  PolylineArrowMaterialProperty.prototype.getType = function (time) {
    return "PolylineArrow";
  };

  /**
   * Gets the value of the property at the provided time.
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {Object} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Object} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  PolylineArrowMaterialProperty.prototype.getValue = function (time, result) {
    if (!defined(result)) {
      result = {};
    }
    result.color = Property.getValueOrClonedDefault(
      this._color,
      time,
      Color.WHITE,
      result.color
    );
    return result;
  };

  /**
   * Compares this property to the provided property and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Property} [other] The other property.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  PolylineArrowMaterialProperty.prototype.equals = function (other) {
    return (
      this === other || //
      (other instanceof PolylineArrowMaterialProperty && //
        Property.equals(this._color, other._color))
    );
  };

  const defaultColor$5 = Color.WHITE;
  const defaultGapColor = Color.TRANSPARENT;
  const defaultDashLength = 16.0;
  const defaultDashPattern = 255.0;

  /**
   * A {@link MaterialProperty} that maps to polyline dash {@link Material} uniforms.
   * @alias PolylineDashMaterialProperty
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Property|Color} [options.color=Color.WHITE] A Property specifying the {@link Color} of the line.
   * @param {Property|Color} [options.gapColor=Color.TRANSPARENT] A Property specifying the {@link Color} of the gaps in the line.
   * @param {Property|Number} [options.dashLength=16.0] A numeric Property specifying the length of the dash pattern in pixels.
   * @param {Property|Number} [options.dashPattern=255.0] A numeric Property specifying a 16 bit pattern for the dash
   */
  function PolylineDashMaterialProperty(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    this._definitionChanged = new Event();
    this._color = undefined;
    this._colorSubscription = undefined;
    this._gapColor = undefined;
    this._gapColorSubscription = undefined;
    this._dashLength = undefined;
    this._dashLengthSubscription = undefined;
    this._dashPattern = undefined;
    this._dashPatternSubscription = undefined;

    this.color = options.color;
    this.gapColor = options.gapColor;
    this.dashLength = options.dashLength;
    this.dashPattern = options.dashPattern;
  }

  Object.defineProperties(PolylineDashMaterialProperty.prototype, {
    /**
     * Gets a value indicating if this property is constant.  A property is considered
     * constant if getValue always returns the same result for the current definition.
     * @memberof PolylineDashMaterialProperty.prototype
     * @type {Boolean}
     * @readonly
     */
    isConstant: {
      get: function () {
        return (
          Property.isConstant(this._color) &&
          Property.isConstant(this._gapColor) &&
          Property.isConstant(this._dashLength) &&
          Property.isConstant(this._dashPattern)
        );
      },
    },
    /**
     * Gets the event that is raised whenever the definition of this property changes.
     * The definition is considered to have changed if a call to getValue would return
     * a different result for the same time.
     * @memberof PolylineDashMaterialProperty.prototype
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },
    /**
     * Gets or sets the Property specifying the {@link Color} of the line.
     * @memberof PolylineDashMaterialProperty.prototype
     * @type {Property|undefined}
     */
    color: createPropertyDescriptor("color"),

    /**
     * Gets or sets the Property specifying the {@link Color} of the gaps in the line.
     * @memberof PolylineDashMaterialProperty.prototype
     * @type {Property|undefined}
     */
    gapColor: createPropertyDescriptor("gapColor"),

    /**
     * Gets or sets the numeric Property specifying the length of a dash cycle
     * @memberof PolylineDashMaterialProperty.prototype
     * @type {Property|undefined}
     */
    dashLength: createPropertyDescriptor("dashLength"),

    /**
     * Gets or sets the numeric Property specifying a dash pattern
     * @memberof PolylineDashMaterialProperty.prototype
     * @type {Property|undefined}
     */
    dashPattern: createPropertyDescriptor("dashPattern"),
  });

  /**
   * Gets the {@link Material} type at the provided time.
   *
   * @param {JulianDate} time The time for which to retrieve the type.
   * @returns {String} The type of material.
   */
  PolylineDashMaterialProperty.prototype.getType = function (time) {
    return "PolylineDash";
  };

  /**
   * Gets the value of the property at the provided time.
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {Object} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Object} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  PolylineDashMaterialProperty.prototype.getValue = function (time, result) {
    if (!defined(result)) {
      result = {};
    }
    result.color = Property.getValueOrClonedDefault(
      this._color,
      time,
      defaultColor$5,
      result.color
    );
    result.gapColor = Property.getValueOrClonedDefault(
      this._gapColor,
      time,
      defaultGapColor,
      result.gapColor
    );
    result.dashLength = Property.getValueOrDefault(
      this._dashLength,
      time,
      defaultDashLength,
      result.dashLength
    );
    result.dashPattern = Property.getValueOrDefault(
      this._dashPattern,
      time,
      defaultDashPattern,
      result.dashPattern
    );
    return result;
  };

  /**
   * Compares this property to the provided property and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Property} [other] The other property.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  PolylineDashMaterialProperty.prototype.equals = function (other) {
    return (
      this === other || //
      (other instanceof PolylineDashMaterialProperty &&
        Property.equals(this._color, other._color) &&
        Property.equals(this._gapColor, other._gapColor) &&
        Property.equals(this._dashLength, other._dashLength) &&
        Property.equals(this._dashPattern, other._dashPattern))
    );
  };

  const defaultColor$4 = Color.WHITE;
  const defaultGlowPower = 0.25;
  const defaultTaperPower = 1.0;

  /**
   * A {@link MaterialProperty} that maps to polyline glow {@link Material} uniforms.
   * @alias PolylineGlowMaterialProperty
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Property|Color} [options.color=Color.WHITE] A Property specifying the {@link Color} of the line.
   * @param {Property|Number} [options.glowPower=0.25] A numeric Property specifying the strength of the glow, as a percentage of the total line width.
   * @param {Property|Number} [options.taperPower=1.0] A numeric Property specifying the strength of the tapering effect, as a percentage of the total line length.  If 1.0 or higher, no taper effect is used.
   */
  function PolylineGlowMaterialProperty(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    this._definitionChanged = new Event();
    this._color = undefined;
    this._colorSubscription = undefined;
    this._glowPower = undefined;
    this._glowPowerSubscription = undefined;
    this._taperPower = undefined;
    this._taperPowerSubscription = undefined;

    this.color = options.color;
    this.glowPower = options.glowPower;
    this.taperPower = options.taperPower;
  }

  Object.defineProperties(PolylineGlowMaterialProperty.prototype, {
    /**
     * Gets a value indicating if this property is constant.  A property is considered
     * constant if getValue always returns the same result for the current definition.
     * @memberof PolylineGlowMaterialProperty.prototype
     * @type {Boolean}
     * @readonly
     */
    isConstant: {
      get: function () {
        return (
          Property.isConstant(this._color) && Property.isConstant(this._glow)
        );
      },
    },
    /**
     * Gets the event that is raised whenever the definition of this property changes.
     * The definition is considered to have changed if a call to getValue would return
     * a different result for the same time.
     * @memberof PolylineGlowMaterialProperty.prototype
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },
    /**
     * Gets or sets the Property specifying the {@link Color} of the line.
     * @memberof PolylineGlowMaterialProperty.prototype
     * @type {Property|undefined}
     */
    color: createPropertyDescriptor("color"),

    /**
     * Gets or sets the numeric Property specifying the strength of the glow, as a percentage of the total line width (less than 1.0).
     * @memberof PolylineGlowMaterialProperty.prototype
     * @type {Property|undefined}
     */
    glowPower: createPropertyDescriptor("glowPower"),

    /**
     * Gets or sets the numeric Property specifying the strength of the tapering effect, as a percentage of the total line length.  If 1.0 or higher, no taper effect is used.
     * @memberof PolylineGlowMaterialProperty.prototype
     * @type {Property|undefined}
     */
    taperPower: createPropertyDescriptor("taperPower"),
  });

  /**
   * Gets the {@link Material} type at the provided time.
   *
   * @param {JulianDate} time The time for which to retrieve the type.
   * @returns {String} The type of material.
   */
  PolylineGlowMaterialProperty.prototype.getType = function (time) {
    return "PolylineGlow";
  };

  /**
   * Gets the value of the property at the provided time.
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {Object} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Object} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  PolylineGlowMaterialProperty.prototype.getValue = function (time, result) {
    if (!defined(result)) {
      result = {};
    }
    result.color = Property.getValueOrClonedDefault(
      this._color,
      time,
      defaultColor$4,
      result.color
    );
    result.glowPower = Property.getValueOrDefault(
      this._glowPower,
      time,
      defaultGlowPower,
      result.glowPower
    );
    result.taperPower = Property.getValueOrDefault(
      this._taperPower,
      time,
      defaultTaperPower,
      result.taperPower
    );
    return result;
  };

  /**
   * Compares this property to the provided property and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Property} [other] The other property.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  PolylineGlowMaterialProperty.prototype.equals = function (other) {
    return (
      this === other ||
      (other instanceof PolylineGlowMaterialProperty &&
        Property.equals(this._color, other._color) &&
        Property.equals(this._glowPower, other._glowPower) &&
        Property.equals(this._taperPower, other._taperPower))
    );
  };

  const defaultColor$3 = Color.WHITE;
  const defaultOutlineColor$2 = Color.BLACK;
  const defaultOutlineWidth$2 = 1.0;

  /**
   * A {@link MaterialProperty} that maps to polyline outline {@link Material} uniforms.
   * @alias PolylineOutlineMaterialProperty
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Property|Color} [options.color=Color.WHITE] A Property specifying the {@link Color} of the line.
   * @param {Property|Color} [options.outlineColor=Color.BLACK] A Property specifying the {@link Color} of the outline.
   * @param {Property|Number} [options.outlineWidth=1.0] A numeric Property specifying the width of the outline, in pixels.
   */
  function PolylineOutlineMaterialProperty(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    this._definitionChanged = new Event();
    this._color = undefined;
    this._colorSubscription = undefined;
    this._outlineColor = undefined;
    this._outlineColorSubscription = undefined;
    this._outlineWidth = undefined;
    this._outlineWidthSubscription = undefined;

    this.color = options.color;
    this.outlineColor = options.outlineColor;
    this.outlineWidth = options.outlineWidth;
  }

  Object.defineProperties(PolylineOutlineMaterialProperty.prototype, {
    /**
     * Gets a value indicating if this property is constant.  A property is considered
     * constant if getValue always returns the same result for the current definition.
     * @memberof PolylineOutlineMaterialProperty.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    isConstant: {
      get: function () {
        return (
          Property.isConstant(this._color) &&
          Property.isConstant(this._outlineColor) &&
          Property.isConstant(this._outlineWidth)
        );
      },
    },
    /**
     * Gets the event that is raised whenever the definition of this property changes.
     * The definition is considered to have changed if a call to getValue would return
     * a different result for the same time.
     * @memberof PolylineOutlineMaterialProperty.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },
    /**
     * Gets or sets the Property specifying the {@link Color} of the line.
     * @memberof PolylineOutlineMaterialProperty.prototype
     * @type {Property|undefined}
     * @default Color.WHITE
     */
    color: createPropertyDescriptor("color"),

    /**
     * Gets or sets the Property specifying the {@link Color} of the outline.
     * @memberof PolylineOutlineMaterialProperty.prototype
     * @type {Property|undefined}
     * @default Color.BLACK
     */
    outlineColor: createPropertyDescriptor("outlineColor"),

    /**
     * Gets or sets the numeric Property specifying the width of the outline.
     * @memberof PolylineOutlineMaterialProperty.prototype
     * @type {Property|undefined}
     * @default 1.0
     */
    outlineWidth: createPropertyDescriptor("outlineWidth"),
  });

  /**
   * Gets the {@link Material} type at the provided time.
   *
   * @param {JulianDate} time The time for which to retrieve the type.
   * @returns {String} The type of material.
   */
  PolylineOutlineMaterialProperty.prototype.getType = function (time) {
    return "PolylineOutline";
  };

  /**
   * Gets the value of the property at the provided time.
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {Object} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Object} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  PolylineOutlineMaterialProperty.prototype.getValue = function (time, result) {
    if (!defined(result)) {
      result = {};
    }
    result.color = Property.getValueOrClonedDefault(
      this._color,
      time,
      defaultColor$3,
      result.color
    );
    result.outlineColor = Property.getValueOrClonedDefault(
      this._outlineColor,
      time,
      defaultOutlineColor$2,
      result.outlineColor
    );
    result.outlineWidth = Property.getValueOrDefault(
      this._outlineWidth,
      time,
      defaultOutlineWidth$2
    );
    return result;
  };

  /**
   * Compares this property to the provided property and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Property} [other] The other property.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  PolylineOutlineMaterialProperty.prototype.equals = function (other) {
    return (
      this === other || //
      (other instanceof PolylineOutlineMaterialProperty && //
        Property.equals(this._color, other._color) && //
        Property.equals(this._outlineColor, other._outlineColor) && //
        Property.equals(this._outlineWidth, other._outlineWidth))
    );
  };

  /**
   * A {@link Property} whose value is an array whose items are the computed value
   * of other PositionProperty instances.
   *
   * @alias PositionPropertyArray
   * @constructor
   *
   * @param {Property[]} [value] An array of Property instances.
   * @param {ReferenceFrame} [referenceFrame=ReferenceFrame.FIXED] The reference frame in which the position is defined.
   */
  function PositionPropertyArray(value, referenceFrame) {
    this._value = undefined;
    this._definitionChanged = new Event();
    this._eventHelper = new EventHelper();
    this._referenceFrame = defaultValue(referenceFrame, ReferenceFrame$1.FIXED);
    this.setValue(value);
  }

  Object.defineProperties(PositionPropertyArray.prototype, {
    /**
     * Gets a value indicating if this property is constant.  This property
     * is considered constant if all property items in the array are constant.
     * @memberof PositionPropertyArray.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    isConstant: {
      get: function () {
        const value = this._value;
        if (!defined(value)) {
          return true;
        }

        const length = value.length;
        for (let i = 0; i < length; i++) {
          if (!Property.isConstant(value[i])) {
            return false;
          }
        }
        return true;
      },
    },
    /**
     * Gets the event that is raised whenever the definition of this property changes.
     * The definition is changed whenever setValue is called with data different
     * than the current value or one of the properties in the array also changes.
     * @memberof PositionPropertyArray.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },
    /**
     * Gets the reference frame in which the position is defined.
     * @memberof PositionPropertyArray.prototype
     * @type {ReferenceFrame}
     * @default ReferenceFrame.FIXED;
     */
    referenceFrame: {
      get: function () {
        return this._referenceFrame;
      },
    },
  });

  /**
   * Gets the value of the property.
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {Cartesian3[]} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Cartesian3[]} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  PositionPropertyArray.prototype.getValue = function (time, result) {
    return this.getValueInReferenceFrame(time, ReferenceFrame$1.FIXED, result);
  };

  /**
   * Gets the value of the property at the provided time and in the provided reference frame.
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {ReferenceFrame} referenceFrame The desired referenceFrame of the result.
   * @param {Cartesian3[]} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Cartesian3[]} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  PositionPropertyArray.prototype.getValueInReferenceFrame = function (
    time,
    referenceFrame,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(time)) {
      throw new DeveloperError("time is required.");
    }
    if (!defined(referenceFrame)) {
      throw new DeveloperError("referenceFrame is required.");
    }
    //>>includeEnd('debug');

    const value = this._value;
    if (!defined(value)) {
      return undefined;
    }

    const length = value.length;
    if (!defined(result)) {
      result = new Array(length);
    }
    let i = 0;
    let x = 0;
    while (i < length) {
      const property = value[i];
      const itemValue = property.getValueInReferenceFrame(
        time,
        referenceFrame,
        result[i]
      );
      if (defined(itemValue)) {
        result[x] = itemValue;
        x++;
      }
      i++;
    }
    result.length = x;
    return result;
  };

  /**
   * Sets the value of the property.
   *
   * @param {Property[]} value An array of Property instances.
   */
  PositionPropertyArray.prototype.setValue = function (value) {
    const eventHelper = this._eventHelper;
    eventHelper.removeAll();

    if (defined(value)) {
      this._value = value.slice();
      const length = value.length;
      for (let i = 0; i < length; i++) {
        const property = value[i];
        if (defined(property)) {
          eventHelper.add(
            property.definitionChanged,
            PositionPropertyArray.prototype._raiseDefinitionChanged,
            this
          );
        }
      }
    } else {
      this._value = undefined;
    }
    this._definitionChanged.raiseEvent(this);
  };

  /**
   * Compares this property to the provided property and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Property} [other] The other property.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  PositionPropertyArray.prototype.equals = function (other) {
    return (
      this === other || //
      (other instanceof PositionPropertyArray && //
        this._referenceFrame === other._referenceFrame && //
        Property.arrayEquals(this._value, other._value))
    );
  };

  PositionPropertyArray.prototype._raiseDefinitionChanged = function () {
    this._definitionChanged.raiseEvent(this);
  };

  /**
   * A {@link Property} whose value is an array whose items are the computed value
   * of other property instances.
   *
   * @alias PropertyArray
   * @constructor
   *
   * @param {Property[]} [value] An array of Property instances.
   */
  function PropertyArray(value) {
    this._value = undefined;
    this._definitionChanged = new Event();
    this._eventHelper = new EventHelper();
    this.setValue(value);
  }

  Object.defineProperties(PropertyArray.prototype, {
    /**
     * Gets a value indicating if this property is constant.  This property
     * is considered constant if all property items in the array are constant.
     * @memberof PropertyArray.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    isConstant: {
      get: function () {
        const value = this._value;
        if (!defined(value)) {
          return true;
        }
        const length = value.length;
        for (let i = 0; i < length; i++) {
          if (!Property.isConstant(value[i])) {
            return false;
          }
        }
        return true;
      },
    },
    /**
     * Gets the event that is raised whenever the definition of this property changes.
     * The definition is changed whenever setValue is called with data different
     * than the current value or one of the properties in the array also changes.
     * @memberof PropertyArray.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },
  });

  /**
   * Gets the value of the property.
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {Object[]} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Object[]} The modified result parameter, which is an array of values produced by evaluating each of the contained properties at the given time or a new instance if the result parameter was not supplied.
   */
  PropertyArray.prototype.getValue = function (time, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(time)) {
      throw new DeveloperError("time is required.");
    }
    //>>includeEnd('debug');

    const value = this._value;
    if (!defined(value)) {
      return undefined;
    }

    const length = value.length;
    if (!defined(result)) {
      result = new Array(length);
    }
    let i = 0;
    let x = 0;
    while (i < length) {
      const property = this._value[i];
      const itemValue = property.getValue(time, result[i]);
      if (defined(itemValue)) {
        result[x] = itemValue;
        x++;
      }
      i++;
    }
    result.length = x;
    return result;
  };

  /**
   * Sets the value of the property.
   *
   * @param {Property[]} value An array of Property instances.
   */
  PropertyArray.prototype.setValue = function (value) {
    const eventHelper = this._eventHelper;
    eventHelper.removeAll();

    if (defined(value)) {
      this._value = value.slice();
      const length = value.length;
      for (let i = 0; i < length; i++) {
        const property = value[i];
        if (defined(property)) {
          eventHelper.add(
            property.definitionChanged,
            PropertyArray.prototype._raiseDefinitionChanged,
            this
          );
        }
      }
    } else {
      this._value = undefined;
    }
    this._definitionChanged.raiseEvent(this);
  };

  /**
   * Compares this property to the provided property and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Property} [other] The other property.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  PropertyArray.prototype.equals = function (other) {
    return (
      this === other || //
      (other instanceof PropertyArray && //
        Property.arrayEquals(this._value, other._value))
    );
  };

  PropertyArray.prototype._raiseDefinitionChanged = function () {
    this._definitionChanged.raiseEvent(this);
  };

  function resolve(that) {
    let targetProperty = that._targetProperty;

    if (!defined(targetProperty)) {
      let targetEntity = that._targetEntity;

      if (!defined(targetEntity)) {
        targetEntity = that._targetCollection.getById(that._targetId);

        if (!defined(targetEntity)) {
          // target entity not found
          that._targetEntity = that._targetProperty = undefined;
          return;
        }

        // target entity was found. listen for changes to entity definition
        targetEntity.definitionChanged.addEventListener(
          ReferenceProperty.prototype._onTargetEntityDefinitionChanged,
          that
        );
        that._targetEntity = targetEntity;
      }

      // walk the list of property names and resolve properties
      const targetPropertyNames = that._targetPropertyNames;
      targetProperty = that._targetEntity;
      for (
        let i = 0, len = targetPropertyNames.length;
        i < len && defined(targetProperty);
        ++i
      ) {
        targetProperty = targetProperty[targetPropertyNames[i]];
      }

      // target property may or may not be defined, depending on if it was found
      that._targetProperty = targetProperty;
    }

    return targetProperty;
  }

  /**
   * A {@link Property} which transparently links to another property on a provided object.
   *
   * @alias ReferenceProperty
   * @constructor
   *
   * @param {EntityCollection} targetCollection The entity collection which will be used to resolve the reference.
   * @param {String} targetId The id of the entity which is being referenced.
   * @param {String[]} targetPropertyNames The names of the property on the target entity which we will use.
   *
   * @example
   * const collection = new Cesium.EntityCollection();
   *
   * //Create a new entity and assign a billboard scale.
   * const object1 = new Cesium.Entity({id:'object1'});
   * object1.billboard = new Cesium.BillboardGraphics();
   * object1.billboard.scale = new Cesium.ConstantProperty(2.0);
   * collection.add(object1);
   *
   * //Create a second entity and reference the scale from the first one.
   * const object2 = new Cesium.Entity({id:'object2'});
   * object2.model = new Cesium.ModelGraphics();
   * object2.model.scale = new Cesium.ReferenceProperty(collection, 'object1', ['billboard', 'scale']);
   * collection.add(object2);
   *
   * //Create a third object, but use the fromString helper function.
   * const object3 = new Cesium.Entity({id:'object3'});
   * object3.billboard = new Cesium.BillboardGraphics();
   * object3.billboard.scale = Cesium.ReferenceProperty.fromString(collection, 'object1#billboard.scale');
   * collection.add(object3);
   *
   * //You can refer to an entity with a # or . in id and property names by escaping them.
   * const object4 = new Cesium.Entity({id:'#object.4'});
   * object4.billboard = new Cesium.BillboardGraphics();
   * object4.billboard.scale = new Cesium.ConstantProperty(2.0);
   * collection.add(object4);
   *
   * const object5 = new Cesium.Entity({id:'object5'});
   * object5.billboard = new Cesium.BillboardGraphics();
   * object5.billboard.scale = Cesium.ReferenceProperty.fromString(collection, '\\#object\\.4#billboard.scale');
   * collection.add(object5);
   */
  function ReferenceProperty(targetCollection, targetId, targetPropertyNames) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(targetCollection)) {
      throw new DeveloperError("targetCollection is required.");
    }
    if (!defined(targetId) || targetId === "") {
      throw new DeveloperError("targetId is required.");
    }
    if (!defined(targetPropertyNames) || targetPropertyNames.length === 0) {
      throw new DeveloperError("targetPropertyNames is required.");
    }
    for (let i = 0; i < targetPropertyNames.length; i++) {
      const item = targetPropertyNames[i];
      if (!defined(item) || item === "") {
        throw new DeveloperError("reference contains invalid properties.");
      }
    }
    //>>includeEnd('debug');

    this._targetCollection = targetCollection;
    this._targetId = targetId;
    this._targetPropertyNames = targetPropertyNames;
    this._targetProperty = undefined;
    this._targetEntity = undefined;
    this._definitionChanged = new Event();

    targetCollection.collectionChanged.addEventListener(
      ReferenceProperty.prototype._onCollectionChanged,
      this
    );
  }

  Object.defineProperties(ReferenceProperty.prototype, {
    /**
     * Gets a value indicating if this property is constant.
     * @memberof ReferenceProperty.prototype
     * @type {Boolean}
     * @readonly
     */
    isConstant: {
      get: function () {
        return Property.isConstant(resolve(this));
      },
    },
    /**
     * Gets the event that is raised whenever the definition of this property changes.
     * The definition is changed whenever the referenced property's definition is changed.
     * @memberof ReferenceProperty.prototype
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },
    /**
     * Gets the reference frame that the position is defined in.
     * This property is only valid if the referenced property is a {@link PositionProperty}.
     * @memberof ReferenceProperty.prototype
     * @type {ReferenceFrame}
     * @readonly
     */
    referenceFrame: {
      get: function () {
        const target = resolve(this);
        return defined(target) ? target.referenceFrame : undefined;
      },
    },
    /**
     * Gets the id of the entity being referenced.
     * @memberof ReferenceProperty.prototype
     * @type {String}
     * @readonly
     */
    targetId: {
      get: function () {
        return this._targetId;
      },
    },
    /**
     * Gets the collection containing the entity being referenced.
     * @memberof ReferenceProperty.prototype
     * @type {EntityCollection}
     * @readonly
     */
    targetCollection: {
      get: function () {
        return this._targetCollection;
      },
    },
    /**
     * Gets the array of property names used to retrieve the referenced property.
     * @memberof ReferenceProperty.prototype
     * @type {String[]}
     * @readonly
     */
    targetPropertyNames: {
      get: function () {
        return this._targetPropertyNames;
      },
    },
    /**
     * Gets the resolved instance of the underlying referenced property.
     * @memberof ReferenceProperty.prototype
     * @type {Property|undefined}
     * @readonly
     */
    resolvedProperty: {
      get: function () {
        return resolve(this);
      },
    },
  });

  /**
   * Creates a new instance given the entity collection that will
   * be used to resolve it and a string indicating the target entity id and property.
   * The format of the string is "objectId#foo.bar", where # separates the id from
   * property path and . separates sub-properties.  If the reference identifier or
   * or any sub-properties contains a # . or \ they must be escaped.
   *
   * @param {EntityCollection} targetCollection
   * @param {String} referenceString
   * @returns {ReferenceProperty} A new instance of ReferenceProperty.
   *
   * @exception {DeveloperError} invalid referenceString.
   */
  ReferenceProperty.fromString = function (targetCollection, referenceString) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(targetCollection)) {
      throw new DeveloperError("targetCollection is required.");
    }
    if (!defined(referenceString)) {
      throw new DeveloperError("referenceString is required.");
    }
    //>>includeEnd('debug');

    let identifier;
    const values = [];

    let inIdentifier = true;
    let isEscaped = false;
    let token = "";
    for (let i = 0; i < referenceString.length; ++i) {
      const c = referenceString.charAt(i);

      if (isEscaped) {
        token += c;
        isEscaped = false;
      } else if (c === "\\") {
        isEscaped = true;
      } else if (inIdentifier && c === "#") {
        identifier = token;
        inIdentifier = false;
        token = "";
      } else if (!inIdentifier && c === ".") {
        values.push(token);
        token = "";
      } else {
        token += c;
      }
    }
    values.push(token);

    return new ReferenceProperty(targetCollection, identifier, values);
  };

  /**
   * Gets the value of the property at the provided time.
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {Object} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Object} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  ReferenceProperty.prototype.getValue = function (time, result) {
    const target = resolve(this);
    return defined(target) ? target.getValue(time, result) : undefined;
  };

  /**
   * Gets the value of the property at the provided time and in the provided reference frame.
   * This method is only valid if the property being referenced is a {@link PositionProperty}.
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {ReferenceFrame} referenceFrame The desired referenceFrame of the result.
   * @param {Cartesian3} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Cartesian3} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  ReferenceProperty.prototype.getValueInReferenceFrame = function (
    time,
    referenceFrame,
    result
  ) {
    const target = resolve(this);
    return defined(target)
      ? target.getValueInReferenceFrame(time, referenceFrame, result)
      : undefined;
  };

  /**
   * Gets the {@link Material} type at the provided time.
   * This method is only valid if the property being referenced is a {@link MaterialProperty}.
   *
   * @param {JulianDate} time The time for which to retrieve the type.
   * @returns {String} The type of material.
   */
  ReferenceProperty.prototype.getType = function (time) {
    const target = resolve(this);
    return defined(target) ? target.getType(time) : undefined;
  };

  /**
   * Compares this property to the provided property and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Property} [other] The other property.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  ReferenceProperty.prototype.equals = function (other) {
    if (this === other) {
      return true;
    }

    const names = this._targetPropertyNames;
    const otherNames = other._targetPropertyNames;

    if (
      this._targetCollection !== other._targetCollection || //
      this._targetId !== other._targetId || //
      names.length !== otherNames.length
    ) {
      return false;
    }

    const length = this._targetPropertyNames.length;
    for (let i = 0; i < length; i++) {
      if (names[i] !== otherNames[i]) {
        return false;
      }
    }

    return true;
  };

  ReferenceProperty.prototype._onTargetEntityDefinitionChanged = function (
    targetEntity,
    name,
    value,
    oldValue
  ) {
    if (defined(this._targetProperty) && this._targetPropertyNames[0] === name) {
      this._targetProperty = undefined;
      this._definitionChanged.raiseEvent(this);
    }
  };

  ReferenceProperty.prototype._onCollectionChanged = function (
    collection,
    added,
    removed
  ) {
    let targetEntity = this._targetEntity;
    if (defined(targetEntity) && removed.indexOf(targetEntity) !== -1) {
      targetEntity.definitionChanged.removeEventListener(
        ReferenceProperty.prototype._onTargetEntityDefinitionChanged,
        this
      );
      this._targetEntity = this._targetProperty = undefined;
    } else if (!defined(targetEntity)) {
      targetEntity = resolve(this);
      if (defined(targetEntity)) {
        this._definitionChanged.raiseEvent(this);
      }
    }
  };

  /**
   * Represents a {@link Packable} number that always interpolates values
   * towards the shortest angle of rotation. This object is never used directly
   * but is instead passed to the constructor of {@link SampledProperty}
   * in order to represent a two-dimensional angle of rotation.
   *
   * @interface Rotation
   *
   *
   * @example
   * const time1 = Cesium.JulianDate.fromIso8601('2010-05-07T00:00:00');
   * const time2 = Cesium.JulianDate.fromIso8601('2010-05-07T00:01:00');
   * const time3 = Cesium.JulianDate.fromIso8601('2010-05-07T00:02:00');
   *
   * const property = new Cesium.SampledProperty(Cesium.Rotation);
   * property.addSample(time1, 0);
   * property.addSample(time3, Cesium.Math.toRadians(350));
   *
   * //Getting the value at time2 will equal 355 degrees instead
   * //of 175 degrees (which is what you get if you construct
   * //a SampledProperty(Number) instead.  Note, the actual
   * //return value is in radians, not degrees.
   * property.getValue(time2);
   *
   * @see PackableForInterpolation
   */
  const Rotation = {
    /**
     * The number of elements used to pack the object into an array.
     * @type {Number}
     */
    packedLength: 1,

    /**
     * Stores the provided instance into the provided array.
     *
     * @param {Rotation} 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
     */
    pack: function (value, array, startingIndex) {
      //>>includeStart('debug', pragmas.debug);
      if (!defined(value)) {
        throw new DeveloperError("value is required");
      }

      if (!defined(array)) {
        throw new DeveloperError("array is required");
      }
      //>>includeEnd('debug');

      startingIndex = defaultValue(startingIndex, 0);
      array[startingIndex] = value;

      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 {Rotation} [result] The object into which to store the result.
     * @returns {Rotation} The modified result parameter or a new Rotation instance if one was not provided.
     */
    unpack: function (array, startingIndex, result) {
      //>>includeStart('debug', pragmas.debug);
      if (!defined(array)) {
        throw new DeveloperError("array is required");
      }
      //>>includeEnd('debug');

      startingIndex = defaultValue(startingIndex, 0);
      return array[startingIndex];
    },

    /**
     * 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.
     */
    convertPackedArrayForInterpolation: function (
      packedArray,
      startingIndex,
      lastIndex,
      result
    ) {
      //>>includeStart('debug', pragmas.debug);
      if (!defined(packedArray)) {
        throw new DeveloperError("packedArray is required");
      }
      //>>includeEnd('debug');

      if (!defined(result)) {
        result = [];
      }

      startingIndex = defaultValue(startingIndex, 0);
      lastIndex = defaultValue(lastIndex, packedArray.length);

      let previousValue;
      for (let i = 0, len = lastIndex - startingIndex + 1; i < len; i++) {
        const value = packedArray[startingIndex + i];
        if (i === 0 || Math.abs(previousValue - value) < Math.PI) {
          result[i] = value;
        } else {
          result[i] = value - CesiumMath.TWO_PI;
        }
        previousValue = value;
      }
    },

    /**
     * Retrieves an instance from a packed array converted with {@link Rotation.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 {Rotation} [result] The object into which to store the result.
     * @returns {Rotation} The modified result parameter or a new Rotation instance if one was not provided.
     */
    unpackInterpolationResult: function (
      array,
      sourceArray,
      firstIndex,
      lastIndex,
      result
    ) {
      //>>includeStart('debug', pragmas.debug);
      if (!defined(array)) {
        throw new DeveloperError("array is required");
      }
      if (!defined(sourceArray)) {
        throw new DeveloperError("sourceArray is required");
      }
      //>>includeEnd('debug');

      result = array[0];
      if (result < 0) {
        return result + CesiumMath.TWO_PI;
      }
      return result;
    },
  };

  const PackableNumber = {
    packedLength: 1,
    pack: function (value, array, startingIndex) {
      startingIndex = defaultValue(startingIndex, 0);
      array[startingIndex] = value;
    },
    unpack: function (array, startingIndex, result) {
      startingIndex = defaultValue(startingIndex, 0);
      return array[startingIndex];
    },
  };

  //We can't use splice for inserting new elements because function apply can't handle
  //a huge number of arguments.  See https://code.google.com/p/chromium/issues/detail?id=56588
  function arrayInsert(array, startIndex, items) {
    let i;
    const arrayLength = array.length;
    const itemsLength = items.length;
    const newLength = arrayLength + itemsLength;

    array.length = newLength;
    if (arrayLength !== startIndex) {
      let q = arrayLength - 1;
      for (i = newLength - 1; i >= startIndex; i--) {
        array[i] = array[q--];
      }
    }

    for (i = 0; i < itemsLength; i++) {
      array[startIndex++] = items[i];
    }
  }

  function convertDate(date, epoch) {
    if (date instanceof JulianDate) {
      return date;
    }
    if (typeof date === "string") {
      return JulianDate.fromIso8601(date);
    }
    return JulianDate.addSeconds(epoch, date, new JulianDate());
  }

  const timesSpliceArgs = [];
  const valuesSpliceArgs = [];

  function mergeNewSamples(epoch, times, values, newData, packedLength) {
    let newDataIndex = 0;
    let i;
    let prevItem;
    let timesInsertionPoint;
    let valuesInsertionPoint;
    let currentTime;
    let nextTime;

    while (newDataIndex < newData.length) {
      currentTime = convertDate(newData[newDataIndex], epoch);
      timesInsertionPoint = binarySearch(times, currentTime, JulianDate.compare);
      let timesSpliceArgsCount = 0;
      let valuesSpliceArgsCount = 0;

      if (timesInsertionPoint < 0) {
        //Doesn't exist, insert as many additional values as we can.
        timesInsertionPoint = ~timesInsertionPoint;

        valuesInsertionPoint = timesInsertionPoint * packedLength;
        prevItem = undefined;
        nextTime = times[timesInsertionPoint];
        while (newDataIndex < newData.length) {
          currentTime = convertDate(newData[newDataIndex], epoch);
          if (
            (defined(prevItem) &&
              JulianDate.compare(prevItem, currentTime) >= 0) ||
            (defined(nextTime) && JulianDate.compare(currentTime, nextTime) >= 0)
          ) {
            break;
          }
          timesSpliceArgs[timesSpliceArgsCount++] = currentTime;
          newDataIndex = newDataIndex + 1;
          for (i = 0; i < packedLength; i++) {
            valuesSpliceArgs[valuesSpliceArgsCount++] = newData[newDataIndex];
            newDataIndex = newDataIndex + 1;
          }
          prevItem = currentTime;
        }

        if (timesSpliceArgsCount > 0) {
          valuesSpliceArgs.length = valuesSpliceArgsCount;
          arrayInsert(values, valuesInsertionPoint, valuesSpliceArgs);

          timesSpliceArgs.length = timesSpliceArgsCount;
          arrayInsert(times, timesInsertionPoint, timesSpliceArgs);
        }
      } else {
        //Found an exact match
        for (i = 0; i < packedLength; i++) {
          newDataIndex++;
          values[timesInsertionPoint * packedLength + i] = newData[newDataIndex];
        }
        newDataIndex++;
      }
    }
  }

  /**
   * A {@link Property} whose value is interpolated for a given time from the
   * provided set of samples and specified interpolation algorithm and degree.
   * @alias SampledProperty
   * @constructor
   *
   * @param {Number|Packable} type The type of property.
   * @param {Packable[]} [derivativeTypes] When supplied, indicates that samples will contain derivative information of the specified types.
   *
   *
   * @example
   * //Create a linearly interpolated Cartesian2
   * const property = new Cesium.SampledProperty(Cesium.Cartesian2);
   *
   * //Populate it with data
   * property.addSample(Cesium.JulianDate.fromIso8601('2012-08-01T00:00:00.00Z'), new Cesium.Cartesian2(0, 0));
   * property.addSample(Cesium.JulianDate.fromIso8601('2012-08-02T00:00:00.00Z'), new Cesium.Cartesian2(4, 7));
   *
   * //Retrieve an interpolated value
   * const result = property.getValue(Cesium.JulianDate.fromIso8601('2012-08-01T12:00:00.00Z'));
   *
   * @example
   * //Create a simple numeric SampledProperty that uses third degree Hermite Polynomial Approximation
   * const property = new Cesium.SampledProperty(Number);
   * property.setInterpolationOptions({
   *     interpolationDegree : 3,
   *     interpolationAlgorithm : Cesium.HermitePolynomialApproximation
   * });
   *
   * //Populate it with data
   * property.addSample(Cesium.JulianDate.fromIso8601('2012-08-01T00:00:00.00Z'), 1.0);
   * property.addSample(Cesium.JulianDate.fromIso8601('2012-08-01T00:01:00.00Z'), 6.0);
   * property.addSample(Cesium.JulianDate.fromIso8601('2012-08-01T00:02:00.00Z'), 12.0);
   * property.addSample(Cesium.JulianDate.fromIso8601('2012-08-01T00:03:30.00Z'), 5.0);
   * property.addSample(Cesium.JulianDate.fromIso8601('2012-08-01T00:06:30.00Z'), 2.0);
   *
   * //Samples can be added in any order.
   * property.addSample(Cesium.JulianDate.fromIso8601('2012-08-01T00:00:30.00Z'), 6.2);
   *
   * //Retrieve an interpolated value
   * const result = property.getValue(Cesium.JulianDate.fromIso8601('2012-08-01T00:02:34.00Z'));
   *
   * @see SampledPositionProperty
   */
  function SampledProperty(type, derivativeTypes) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("type", type);
    //>>includeEnd('debug');

    let innerType = type;
    if (innerType === Number) {
      innerType = PackableNumber;
    }
    let packedLength = innerType.packedLength;
    let packedInterpolationLength = defaultValue(
      innerType.packedInterpolationLength,
      packedLength
    );

    let inputOrder = 0;
    let innerDerivativeTypes;
    if (defined(derivativeTypes)) {
      const length = derivativeTypes.length;
      innerDerivativeTypes = new Array(length);
      for (let i = 0; i < length; i++) {
        let derivativeType = derivativeTypes[i];
        if (derivativeType === Number) {
          derivativeType = PackableNumber;
        }
        const derivativePackedLength = derivativeType.packedLength;
        packedLength += derivativePackedLength;
        packedInterpolationLength += defaultValue(
          derivativeType.packedInterpolationLength,
          derivativePackedLength
        );
        innerDerivativeTypes[i] = derivativeType;
      }
      inputOrder = length;
    }

    this._type = type;
    this._innerType = innerType;
    this._interpolationDegree = 1;
    this._interpolationAlgorithm = LinearApproximation;
    this._numberOfPoints = 0;
    this._times = [];
    this._values = [];
    this._xTable = [];
    this._yTable = [];
    this._packedLength = packedLength;
    this._packedInterpolationLength = packedInterpolationLength;
    this._updateTableLength = true;
    this._interpolationResult = new Array(packedInterpolationLength);
    this._definitionChanged = new Event();
    this._derivativeTypes = derivativeTypes;
    this._innerDerivativeTypes = innerDerivativeTypes;
    this._inputOrder = inputOrder;
    this._forwardExtrapolationType = ExtrapolationType$1.NONE;
    this._forwardExtrapolationDuration = 0;
    this._backwardExtrapolationType = ExtrapolationType$1.NONE;
    this._backwardExtrapolationDuration = 0;
  }

  Object.defineProperties(SampledProperty.prototype, {
    /**
     * Gets a value indicating if this property is constant.  A property is considered
     * constant if getValue always returns the same result for the current definition.
     * @memberof SampledProperty.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    isConstant: {
      get: function () {
        return this._values.length === 0;
      },
    },
    /**
     * Gets the event that is raised whenever the definition of this property changes.
     * The definition is considered to have changed if a call to getValue would return
     * a different result for the same time.
     * @memberof SampledProperty.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },
    /**
     * Gets the type of property.
     * @memberof SampledProperty.prototype
     * @type {*}
     */
    type: {
      get: function () {
        return this._type;
      },
    },
    /**
     * Gets the derivative types used by this property.
     * @memberof SampledProperty.prototype
     * @type {Packable[]}
     */
    derivativeTypes: {
      get: function () {
        return this._derivativeTypes;
      },
    },
    /**
     * Gets the degree of interpolation to perform when retrieving a value.
     * @memberof SampledProperty.prototype
     * @type {Number}
     * @default 1
     */
    interpolationDegree: {
      get: function () {
        return this._interpolationDegree;
      },
    },
    /**
     * Gets the interpolation algorithm to use when retrieving a value.
     * @memberof SampledProperty.prototype
     * @type {InterpolationAlgorithm}
     * @default LinearApproximation
     */
    interpolationAlgorithm: {
      get: function () {
        return this._interpolationAlgorithm;
      },
    },
    /**
     * Gets or sets the type of extrapolation to perform when a value
     * is requested at a time after any available samples.
     * @memberof SampledProperty.prototype
     * @type {ExtrapolationType}
     * @default ExtrapolationType.NONE
     */
    forwardExtrapolationType: {
      get: function () {
        return this._forwardExtrapolationType;
      },
      set: function (value) {
        if (this._forwardExtrapolationType !== value) {
          this._forwardExtrapolationType = value;
          this._definitionChanged.raiseEvent(this);
        }
      },
    },
    /**
     * Gets or sets the amount of time to extrapolate forward before
     * the property becomes undefined.  A value of 0 will extrapolate forever.
     * @memberof SampledProperty.prototype
     * @type {Number}
     * @default 0
     */
    forwardExtrapolationDuration: {
      get: function () {
        return this._forwardExtrapolationDuration;
      },
      set: function (value) {
        if (this._forwardExtrapolationDuration !== value) {
          this._forwardExtrapolationDuration = value;
          this._definitionChanged.raiseEvent(this);
        }
      },
    },
    /**
     * Gets or sets the type of extrapolation to perform when a value
     * is requested at a time before any available samples.
     * @memberof SampledProperty.prototype
     * @type {ExtrapolationType}
     * @default ExtrapolationType.NONE
     */
    backwardExtrapolationType: {
      get: function () {
        return this._backwardExtrapolationType;
      },
      set: function (value) {
        if (this._backwardExtrapolationType !== value) {
          this._backwardExtrapolationType = value;
          this._definitionChanged.raiseEvent(this);
        }
      },
    },
    /**
     * Gets or sets the amount of time to extrapolate backward
     * before the property becomes undefined.  A value of 0 will extrapolate forever.
     * @memberof SampledProperty.prototype
     * @type {Number}
     * @default 0
     */
    backwardExtrapolationDuration: {
      get: function () {
        return this._backwardExtrapolationDuration;
      },
      set: function (value) {
        if (this._backwardExtrapolationDuration !== value) {
          this._backwardExtrapolationDuration = value;
          this._definitionChanged.raiseEvent(this);
        }
      },
    },
  });

  /**
   * Gets the value of the property at the provided time.
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {Object} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Object} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  SampledProperty.prototype.getValue = function (time, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("time", time);
    //>>includeEnd('debug');

    const times = this._times;
    const timesLength = times.length;
    if (timesLength === 0) {
      return undefined;
    }

    let timeout;
    const innerType = this._innerType;
    const values = this._values;
    let index = binarySearch(times, time, JulianDate.compare);

    if (index < 0) {
      index = ~index;

      if (index === 0) {
        const startTime = times[index];
        timeout = this._backwardExtrapolationDuration;
        if (
          this._backwardExtrapolationType === ExtrapolationType$1.NONE ||
          (timeout !== 0 &&
            JulianDate.secondsDifference(startTime, time) > timeout)
        ) {
          return undefined;
        }
        if (this._backwardExtrapolationType === ExtrapolationType$1.HOLD) {
          return innerType.unpack(values, 0, result);
        }
      }

      if (index >= timesLength) {
        index = timesLength - 1;
        const endTime = times[index];
        timeout = this._forwardExtrapolationDuration;
        if (
          this._forwardExtrapolationType === ExtrapolationType$1.NONE ||
          (timeout !== 0 && JulianDate.secondsDifference(time, endTime) > timeout)
        ) {
          return undefined;
        }
        if (this._forwardExtrapolationType === ExtrapolationType$1.HOLD) {
          index = timesLength - 1;
          return innerType.unpack(values, index * innerType.packedLength, result);
        }
      }

      const xTable = this._xTable;
      const yTable = this._yTable;
      const interpolationAlgorithm = this._interpolationAlgorithm;
      const packedInterpolationLength = this._packedInterpolationLength;
      const inputOrder = this._inputOrder;

      if (this._updateTableLength) {
        this._updateTableLength = false;
        const numberOfPoints = Math.min(
          interpolationAlgorithm.getRequiredDataPoints(
            this._interpolationDegree,
            inputOrder
          ),
          timesLength
        );
        if (numberOfPoints !== this._numberOfPoints) {
          this._numberOfPoints = numberOfPoints;
          xTable.length = numberOfPoints;
          yTable.length = numberOfPoints * packedInterpolationLength;
        }
      }

      const degree = this._numberOfPoints - 1;
      if (degree < 1) {
        return undefined;
      }

      let firstIndex = 0;
      let lastIndex = timesLength - 1;
      const pointsInCollection = lastIndex - firstIndex + 1;

      if (pointsInCollection >= degree + 1) {
        let computedFirstIndex = index - ((degree / 2) | 0) - 1;
        if (computedFirstIndex < firstIndex) {
          computedFirstIndex = firstIndex;
        }
        let computedLastIndex = computedFirstIndex + degree;
        if (computedLastIndex > lastIndex) {
          computedLastIndex = lastIndex;
          computedFirstIndex = computedLastIndex - degree;
          if (computedFirstIndex < firstIndex) {
            computedFirstIndex = firstIndex;
          }
        }

        firstIndex = computedFirstIndex;
        lastIndex = computedLastIndex;
      }
      const length = lastIndex - firstIndex + 1;

      // Build the tables
      for (let i = 0; i < length; ++i) {
        xTable[i] = JulianDate.secondsDifference(
          times[firstIndex + i],
          times[lastIndex]
        );
      }

      if (!defined(innerType.convertPackedArrayForInterpolation)) {
        let destinationIndex = 0;
        const packedLength = this._packedLength;
        let sourceIndex = firstIndex * packedLength;
        const stop = (lastIndex + 1) * packedLength;

        while (sourceIndex < stop) {
          yTable[destinationIndex] = values[sourceIndex];
          sourceIndex++;
          destinationIndex++;
        }
      } else {
        innerType.convertPackedArrayForInterpolation(
          values,
          firstIndex,
          lastIndex,
          yTable
        );
      }

      // Interpolate!
      const x = JulianDate.secondsDifference(time, times[lastIndex]);
      let interpolationResult;
      if (inputOrder === 0 || !defined(interpolationAlgorithm.interpolate)) {
        interpolationResult = interpolationAlgorithm.interpolateOrderZero(
          x,
          xTable,
          yTable,
          packedInterpolationLength,
          this._interpolationResult
        );
      } else {
        const yStride = Math.floor(packedInterpolationLength / (inputOrder + 1));
        interpolationResult = interpolationAlgorithm.interpolate(
          x,
          xTable,
          yTable,
          yStride,
          inputOrder,
          inputOrder,
          this._interpolationResult
        );
      }

      if (!defined(innerType.unpackInterpolationResult)) {
        return innerType.unpack(interpolationResult, 0, result);
      }
      return innerType.unpackInterpolationResult(
        interpolationResult,
        values,
        firstIndex,
        lastIndex,
        result
      );
    }
    return innerType.unpack(values, index * this._packedLength, result);
  };

  /**
   * Sets the algorithm and degree to use when interpolating a value.
   *
   * @param {Object} [options] Object with the following properties:
   * @param {InterpolationAlgorithm} [options.interpolationAlgorithm] The new interpolation algorithm.  If undefined, the existing property will be unchanged.
   * @param {Number} [options.interpolationDegree] The new interpolation degree.  If undefined, the existing property will be unchanged.
   */
  SampledProperty.prototype.setInterpolationOptions = function (options) {
    if (!defined(options)) {
      return;
    }

    let valuesChanged = false;

    const interpolationAlgorithm = options.interpolationAlgorithm;
    const interpolationDegree = options.interpolationDegree;

    if (
      defined(interpolationAlgorithm) &&
      this._interpolationAlgorithm !== interpolationAlgorithm
    ) {
      this._interpolationAlgorithm = interpolationAlgorithm;
      valuesChanged = true;
    }

    if (
      defined(interpolationDegree) &&
      this._interpolationDegree !== interpolationDegree
    ) {
      this._interpolationDegree = interpolationDegree;
      valuesChanged = true;
    }

    if (valuesChanged) {
      this._updateTableLength = true;
      this._definitionChanged.raiseEvent(this);
    }
  };

  /**
   * Adds a new sample.
   *
   * @param {JulianDate} time The sample time.
   * @param {Packable} value The value at the provided time.
   * @param {Packable[]} [derivatives] The array of derivatives at the provided time.
   */
  SampledProperty.prototype.addSample = function (time, value, derivatives) {
    const innerDerivativeTypes = this._innerDerivativeTypes;
    const hasDerivatives = defined(innerDerivativeTypes);

    //>>includeStart('debug', pragmas.debug);
    Check.defined("time", time);
    Check.defined("value", value);
    if (hasDerivatives) {
      Check.defined("derivatives", derivatives);
    }
    //>>includeEnd('debug');

    const innerType = this._innerType;
    const data = [];
    data.push(time);
    innerType.pack(value, data, data.length);

    if (hasDerivatives) {
      const derivativesLength = innerDerivativeTypes.length;
      for (let x = 0; x < derivativesLength; x++) {
        innerDerivativeTypes[x].pack(derivatives[x], data, data.length);
      }
    }
    mergeNewSamples(
      undefined,
      this._times,
      this._values,
      data,
      this._packedLength
    );
    this._updateTableLength = true;
    this._definitionChanged.raiseEvent(this);
  };

  /**
   * Adds an array of samples.
   *
   * @param {JulianDate[]} times An array of JulianDate instances where each index is a sample time.
   * @param {Packable[]} values The array of values, where each value corresponds to the provided times index.
   * @param {Array[]} [derivativeValues] An array where each item is the array of derivatives at the equivalent time index.
   *
   * @exception {DeveloperError} times and values must be the same length.
   * @exception {DeveloperError} times and derivativeValues must be the same length.
   */
  SampledProperty.prototype.addSamples = function (
    times,
    values,
    derivativeValues
  ) {
    const innerDerivativeTypes = this._innerDerivativeTypes;
    const hasDerivatives = defined(innerDerivativeTypes);

    //>>includeStart('debug', pragmas.debug);
    Check.defined("times", times);
    Check.defined("values", values);
    if (times.length !== values.length) {
      throw new DeveloperError("times and values must be the same length.");
    }
    if (
      hasDerivatives &&
      (!defined(derivativeValues) || derivativeValues.length !== times.length)
    ) {
      throw new DeveloperError(
        "times and derivativeValues must be the same length."
      );
    }
    //>>includeEnd('debug');

    const innerType = this._innerType;
    const length = times.length;
    const data = [];
    for (let i = 0; i < length; i++) {
      data.push(times[i]);
      innerType.pack(values[i], data, data.length);

      if (hasDerivatives) {
        const derivatives = derivativeValues[i];
        const derivativesLength = innerDerivativeTypes.length;
        for (let x = 0; x < derivativesLength; x++) {
          innerDerivativeTypes[x].pack(derivatives[x], data, data.length);
        }
      }
    }
    mergeNewSamples(
      undefined,
      this._times,
      this._values,
      data,
      this._packedLength
    );
    this._updateTableLength = true;
    this._definitionChanged.raiseEvent(this);
  };

  /**
   * Adds samples as a single packed array where each new sample is represented as a date,
   * followed by the packed representation of the corresponding value and derivatives.
   *
   * @param {Number[]} packedSamples The array of packed samples.
   * @param {JulianDate} [epoch] If any of the dates in packedSamples are numbers, they are considered an offset from this epoch, in seconds.
   */
  SampledProperty.prototype.addSamplesPackedArray = function (
    packedSamples,
    epoch
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("packedSamples", packedSamples);
    //>>includeEnd('debug');

    mergeNewSamples(
      epoch,
      this._times,
      this._values,
      packedSamples,
      this._packedLength
    );
    this._updateTableLength = true;
    this._definitionChanged.raiseEvent(this);
  };

  /**
   * Removes a sample at the given time, if present.
   *
   * @param {JulianDate} time The sample time.
   * @returns {Boolean} <code>true</code> if a sample at time was removed, <code>false</code> otherwise.
   */
  SampledProperty.prototype.removeSample = function (time) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("time", time);
    //>>includeEnd('debug');

    const index = binarySearch(this._times, time, JulianDate.compare);
    if (index < 0) {
      return false;
    }
    removeSamples(this, index, 1);
    return true;
  };

  function removeSamples(property, startIndex, numberToRemove) {
    const packedLength = property._packedLength;
    property._times.splice(startIndex, numberToRemove);
    property._values.splice(
      startIndex * packedLength,
      numberToRemove * packedLength
    );
    property._updateTableLength = true;
    property._definitionChanged.raiseEvent(property);
  }

  /**
   * Removes all samples for the given time interval.
   *
   * @param {TimeInterval} time The time interval for which to remove all samples.
   */
  SampledProperty.prototype.removeSamples = function (timeInterval) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("timeInterval", timeInterval);
    //>>includeEnd('debug');

    const times = this._times;
    let startIndex = binarySearch(times, timeInterval.start, JulianDate.compare);
    if (startIndex < 0) {
      startIndex = ~startIndex;
    } else if (!timeInterval.isStartIncluded) {
      ++startIndex;
    }
    let stopIndex = binarySearch(times, timeInterval.stop, JulianDate.compare);
    if (stopIndex < 0) {
      stopIndex = ~stopIndex;
    } else if (timeInterval.isStopIncluded) {
      ++stopIndex;
    }

    removeSamples(this, startIndex, stopIndex - startIndex);
  };

  /**
   * Compares this property to the provided property and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Property} [other] The other property.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  SampledProperty.prototype.equals = function (other) {
    if (this === other) {
      return true;
    }
    if (!defined(other)) {
      return false;
    }

    if (
      this._type !== other._type || //
      this._interpolationDegree !== other._interpolationDegree || //
      this._interpolationAlgorithm !== other._interpolationAlgorithm
    ) {
      return false;
    }

    const derivativeTypes = this._derivativeTypes;
    const hasDerivatives = defined(derivativeTypes);
    const otherDerivativeTypes = other._derivativeTypes;
    const otherHasDerivatives = defined(otherDerivativeTypes);
    if (hasDerivatives !== otherHasDerivatives) {
      return false;
    }

    let i;
    let length;
    if (hasDerivatives) {
      length = derivativeTypes.length;
      if (length !== otherDerivativeTypes.length) {
        return false;
      }

      for (i = 0; i < length; i++) {
        if (derivativeTypes[i] !== otherDerivativeTypes[i]) {
          return false;
        }
      }
    }

    const times = this._times;
    const otherTimes = other._times;
    length = times.length;

    if (length !== otherTimes.length) {
      return false;
    }

    for (i = 0; i < length; i++) {
      if (!JulianDate.equals(times[i], otherTimes[i])) {
        return false;
      }
    }

    const values = this._values;
    const otherValues = other._values;
    length = values.length;

    //Since time lengths are equal, values length and other length are guaranteed to be equal.
    for (i = 0; i < length; i++) {
      if (values[i] !== otherValues[i]) {
        return false;
      }
    }

    return true;
  };

  //Exposed for testing.
  SampledProperty._mergeNewSamples = mergeNewSamples;

  /**
   * A {@link SampledProperty} which is also a {@link PositionProperty}.
   *
   * @alias SampledPositionProperty
   * @constructor
   *
   * @param {ReferenceFrame} [referenceFrame=ReferenceFrame.FIXED] The reference frame in which the position is defined.
   * @param {Number} [numberOfDerivatives=0] The number of derivatives that accompany each position; i.e. velocity, acceleration, etc...
   */
  function SampledPositionProperty(referenceFrame, numberOfDerivatives) {
    numberOfDerivatives = defaultValue(numberOfDerivatives, 0);

    let derivativeTypes;
    if (numberOfDerivatives > 0) {
      derivativeTypes = new Array(numberOfDerivatives);
      for (let i = 0; i < numberOfDerivatives; i++) {
        derivativeTypes[i] = Cartesian3;
      }
    }

    this._numberOfDerivatives = numberOfDerivatives;
    this._property = new SampledProperty(Cartesian3, derivativeTypes);
    this._definitionChanged = new Event();
    this._referenceFrame = defaultValue(referenceFrame, ReferenceFrame$1.FIXED);

    this._property._definitionChanged.addEventListener(function () {
      this._definitionChanged.raiseEvent(this);
    }, this);
  }

  Object.defineProperties(SampledPositionProperty.prototype, {
    /**
     * Gets a value indicating if this property is constant.  A property is considered
     * constant if getValue always returns the same result for the current definition.
     * @memberof SampledPositionProperty.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    isConstant: {
      get: function () {
        return this._property.isConstant;
      },
    },
    /**
     * Gets the event that is raised whenever the definition of this property changes.
     * The definition is considered to have changed if a call to getValue would return
     * a different result for the same time.
     * @memberof SampledPositionProperty.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },
    /**
     * Gets the reference frame in which the position is defined.
     * @memberof SampledPositionProperty.prototype
     * @type {ReferenceFrame}
     * @default ReferenceFrame.FIXED;
     */
    referenceFrame: {
      get: function () {
        return this._referenceFrame;
      },
    },
    /**
     * Gets the degree of interpolation to perform when retrieving a value. Call <code>setInterpolationOptions</code> to set this.
     * @memberof SampledPositionProperty.prototype
     *
     * @type {Number}
     * @default 1
     * @readonly
     */
    interpolationDegree: {
      get: function () {
        return this._property.interpolationDegree;
      },
    },
    /**
     * Gets the interpolation algorithm to use when retrieving a value. Call <code>setInterpolationOptions</code> to set this.
     * @memberof SampledPositionProperty.prototype
     *
     * @type {InterpolationAlgorithm}
     * @default LinearApproximation
     * @readonly
     */
    interpolationAlgorithm: {
      get: function () {
        return this._property.interpolationAlgorithm;
      },
    },
    /**
     * The number of derivatives contained by this property; i.e. 0 for just position, 1 for velocity, etc.
     * @memberof SampledPositionProperty.prototype
     *
     * @type {Number}
     * @default 0
     */
    numberOfDerivatives: {
      get: function () {
        return this._numberOfDerivatives;
      },
    },
    /**
     * Gets or sets the type of extrapolation to perform when a value
     * is requested at a time after any available samples.
     * @memberof SampledPositionProperty.prototype
     * @type {ExtrapolationType}
     * @default ExtrapolationType.NONE
     */
    forwardExtrapolationType: {
      get: function () {
        return this._property.forwardExtrapolationType;
      },
      set: function (value) {
        this._property.forwardExtrapolationType = value;
      },
    },
    /**
     * Gets or sets the amount of time to extrapolate forward before
     * the property becomes undefined.  A value of 0 will extrapolate forever.
     * @memberof SampledPositionProperty.prototype
     * @type {Number}
     * @default 0
     */
    forwardExtrapolationDuration: {
      get: function () {
        return this._property.forwardExtrapolationDuration;
      },
      set: function (value) {
        this._property.forwardExtrapolationDuration = value;
      },
    },
    /**
     * Gets or sets the type of extrapolation to perform when a value
     * is requested at a time before any available samples.
     * @memberof SampledPositionProperty.prototype
     * @type {ExtrapolationType}
     * @default ExtrapolationType.NONE
     */
    backwardExtrapolationType: {
      get: function () {
        return this._property.backwardExtrapolationType;
      },
      set: function (value) {
        this._property.backwardExtrapolationType = value;
      },
    },
    /**
     * Gets or sets the amount of time to extrapolate backward
     * before the property becomes undefined.  A value of 0 will extrapolate forever.
     * @memberof SampledPositionProperty.prototype
     * @type {Number}
     * @default 0
     */
    backwardExtrapolationDuration: {
      get: function () {
        return this._property.backwardExtrapolationDuration;
      },
      set: function (value) {
        this._property.backwardExtrapolationDuration = value;
      },
    },
  });

  /**
   * Gets the position at the provided time.
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {Cartesian3} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Cartesian3 | undefined} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  SampledPositionProperty.prototype.getValue = function (time, result) {
    return this.getValueInReferenceFrame(time, ReferenceFrame$1.FIXED, result);
  };

  /**
   * Gets the position at the provided time and in the provided reference frame.
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {ReferenceFrame} referenceFrame The desired referenceFrame of the result.
   * @param {Cartesian3} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Cartesian3 | undefined} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  SampledPositionProperty.prototype.getValueInReferenceFrame = function (
    time,
    referenceFrame,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("time", time);
    Check.defined("referenceFrame", referenceFrame);
    //>>includeEnd('debug');

    result = this._property.getValue(time, result);
    if (defined(result)) {
      return PositionProperty.convertToReferenceFrame(
        time,
        result,
        this._referenceFrame,
        referenceFrame,
        result
      );
    }
    return undefined;
  };

  /**
   * Sets the algorithm and degree to use when interpolating a position.
   *
   * @param {Object} [options] Object with the following properties:
   * @param {InterpolationAlgorithm} [options.interpolationAlgorithm] The new interpolation algorithm.  If undefined, the existing property will be unchanged.
   * @param {Number} [options.interpolationDegree] The new interpolation degree.  If undefined, the existing property will be unchanged.
   */
  SampledPositionProperty.prototype.setInterpolationOptions = function (options) {
    this._property.setInterpolationOptions(options);
  };

  /**
   * Adds a new sample.
   *
   * @param {JulianDate} time The sample time.
   * @param {Cartesian3} position The position at the provided time.
   * @param {Cartesian3[]} [derivatives] The array of derivative values at the provided time.
   */
  SampledPositionProperty.prototype.addSample = function (
    time,
    position,
    derivatives
  ) {
    const numberOfDerivatives = this._numberOfDerivatives;
    //>>includeStart('debug', pragmas.debug);
    if (
      numberOfDerivatives > 0 &&
      (!defined(derivatives) || derivatives.length !== numberOfDerivatives)
    ) {
      throw new DeveloperError(
        "derivatives length must be equal to the number of derivatives."
      );
    }
    //>>includeEnd('debug');
    this._property.addSample(time, position, derivatives);
  };

  /**
   * Adds multiple samples via parallel arrays.
   *
   * @param {JulianDate[]} times An array of JulianDate instances where each index is a sample time.
   * @param {Cartesian3[]} positions An array of Cartesian3 position instances, where each value corresponds to the provided time index.
   * @param {Array[]} [derivatives] An array where each value is another array containing derivatives for the corresponding time index.
   *
   * @exception {DeveloperError} All arrays must be the same length.
   */
  SampledPositionProperty.prototype.addSamples = function (
    times,
    positions,
    derivatives
  ) {
    this._property.addSamples(times, positions, derivatives);
  };

  /**
   * Adds samples as a single packed array where each new sample is represented as a date,
   * followed by the packed representation of the corresponding value and derivatives.
   *
   * @param {Number[]} packedSamples The array of packed samples.
   * @param {JulianDate} [epoch] If any of the dates in packedSamples are numbers, they are considered an offset from this epoch, in seconds.
   */
  SampledPositionProperty.prototype.addSamplesPackedArray = function (
    packedSamples,
    epoch
  ) {
    this._property.addSamplesPackedArray(packedSamples, epoch);
  };

  /**
   * Removes a sample at the given time, if present.
   *
   * @param {JulianDate} time The sample time.
   * @returns {Boolean} <code>true</code> if a sample at time was removed, <code>false</code> otherwise.
   */
  SampledPositionProperty.prototype.removeSample = function (time) {
    return this._property.removeSample(time);
  };

  /**
   * Removes all samples for the given time interval.
   *
   * @param {TimeInterval} time The time interval for which to remove all samples.
   */
  SampledPositionProperty.prototype.removeSamples = function (timeInterval) {
    this._property.removeSamples(timeInterval);
  };

  /**
   * Compares this property to the provided property and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Property} [other] The other property.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  SampledPositionProperty.prototype.equals = function (other) {
    return (
      this === other || //
      (other instanceof SampledPositionProperty &&
        Property.equals(this._property, other._property) && //
        this._referenceFrame === other._referenceFrame)
    );
  };

  /**
   * Defined the orientation of stripes in {@link StripeMaterialProperty}.
   *
   * @enum {Number}
   */
  const StripeOrientation = {
    /**
     * Horizontal orientation.
     * @type {Number}
     */
    HORIZONTAL: 0,

    /**
     * Vertical orientation.
     * @type {Number}
     */
    VERTICAL: 1,
  };
  var StripeOrientation$1 = Object.freeze(StripeOrientation);

  const defaultOrientation = StripeOrientation$1.HORIZONTAL;
  const defaultEvenColor = Color.WHITE;
  const defaultOddColor = Color.BLACK;
  const defaultOffset$7 = 0;
  const defaultRepeat = 1;

  /**
   * A {@link MaterialProperty} that maps to stripe {@link Material} uniforms.
   * @alias StripeMaterialProperty
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Property|StripeOrientation} [options.orientation=StripeOrientation.HORIZONTAL] A Property specifying the {@link StripeOrientation}.
   * @param {Property|Color} [options.evenColor=Color.WHITE] A Property specifying the first {@link Color}.
   * @param {Property|Color} [options.oddColor=Color.BLACK] A Property specifying the second {@link Color}.
   * @param {Property|Number} [options.offset=0] A numeric Property specifying how far into the pattern to start the material.
   * @param {Property|Number} [options.repeat=1] A numeric Property specifying how many times the stripes repeat.
   */
  function StripeMaterialProperty(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    this._definitionChanged = new Event();
    this._orientation = undefined;
    this._orientationSubscription = undefined;
    this._evenColor = undefined;
    this._evenColorSubscription = undefined;
    this._oddColor = undefined;
    this._oddColorSubscription = undefined;
    this._offset = undefined;
    this._offsetSubscription = undefined;
    this._repeat = undefined;
    this._repeatSubscription = undefined;

    this.orientation = options.orientation;
    this.evenColor = options.evenColor;
    this.oddColor = options.oddColor;
    this.offset = options.offset;
    this.repeat = options.repeat;
  }

  Object.defineProperties(StripeMaterialProperty.prototype, {
    /**
     * Gets a value indicating if this property is constant.  A property is considered
     * constant if getValue always returns the same result for the current definition.
     * @memberof StripeMaterialProperty.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    isConstant: {
      get: function () {
        return (
          Property.isConstant(this._orientation) && //
          Property.isConstant(this._evenColor) && //
          Property.isConstant(this._oddColor) && //
          Property.isConstant(this._offset) && //
          Property.isConstant(this._repeat)
        );
      },
    },
    /**
     * Gets the event that is raised whenever the definition of this property changes.
     * The definition is considered to have changed if a call to getValue would return
     * a different result for the same time.
     * @memberof StripeMaterialProperty.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },

    /**
     * Gets or sets the Property specifying the {@link StripeOrientation}/
     * @memberof StripeMaterialProperty.prototype
     * @type {Property|undefined}
     * @default StripeOrientation.HORIZONTAL
     */
    orientation: createPropertyDescriptor("orientation"),

    /**
     * Gets or sets the Property specifying the first {@link Color}.
     * @memberof StripeMaterialProperty.prototype
     * @type {Property|undefined}
     * @default Color.WHITE
     */
    evenColor: createPropertyDescriptor("evenColor"),

    /**
     * Gets or sets the Property specifying the second {@link Color}.
     * @memberof StripeMaterialProperty.prototype
     * @type {Property|undefined}
     * @default Color.BLACK
     */
    oddColor: createPropertyDescriptor("oddColor"),

    /**
     * Gets or sets the numeric Property specifying the point into the pattern
     * to begin drawing; with 0.0 being the beginning of the even color, 1.0 the beginning
     * of the odd color, 2.0 being the even color again, and any multiple or fractional values
     * being in between.
     * @memberof StripeMaterialProperty.prototype
     * @type {Property|undefined}
     * @default 0.0
     */
    offset: createPropertyDescriptor("offset"),

    /**
     * Gets or sets the numeric Property specifying how many times the stripes repeat.
     * @memberof StripeMaterialProperty.prototype
     * @type {Property|undefined}
     * @default 1.0
     */
    repeat: createPropertyDescriptor("repeat"),
  });

  /**
   * Gets the {@link Material} type at the provided time.
   *
   * @param {JulianDate} time The time for which to retrieve the type.
   * @returns {String} The type of material.
   */
  StripeMaterialProperty.prototype.getType = function (time) {
    return "Stripe";
  };

  /**
   * Gets the value of the property at the provided time.
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {Object} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Object} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  StripeMaterialProperty.prototype.getValue = function (time, result) {
    if (!defined(result)) {
      result = {};
    }
    result.horizontal =
      Property.getValueOrDefault(this._orientation, time, defaultOrientation) ===
      StripeOrientation$1.HORIZONTAL;
    result.evenColor = Property.getValueOrClonedDefault(
      this._evenColor,
      time,
      defaultEvenColor,
      result.evenColor
    );
    result.oddColor = Property.getValueOrClonedDefault(
      this._oddColor,
      time,
      defaultOddColor,
      result.oddColor
    );
    result.offset = Property.getValueOrDefault(this._offset, time, defaultOffset$7);
    result.repeat = Property.getValueOrDefault(this._repeat, time, defaultRepeat);
    return result;
  };

  /**
   * Compares this property to the provided property and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Property} [other] The other property.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  StripeMaterialProperty.prototype.equals = function (other) {
    return (
      this === other || //
      (other instanceof StripeMaterialProperty && //
        Property.equals(this._orientation, other._orientation) && //
        Property.equals(this._evenColor, other._evenColor) && //
        Property.equals(this._oddColor, other._oddColor) && //
        Property.equals(this._offset, other._offset) && //
        Property.equals(this._repeat, other._repeat))
    );
  };

  /**
   * A {@link TimeIntervalCollectionProperty} which is also a {@link PositionProperty}.
   *
   * @alias TimeIntervalCollectionPositionProperty
   * @constructor
   *
   * @param {ReferenceFrame} [referenceFrame=ReferenceFrame.FIXED] The reference frame in which the position is defined.
   */
  function TimeIntervalCollectionPositionProperty(referenceFrame) {
    this._definitionChanged = new Event();
    this._intervals = new TimeIntervalCollection();
    this._intervals.changedEvent.addEventListener(
      TimeIntervalCollectionPositionProperty.prototype._intervalsChanged,
      this
    );
    this._referenceFrame = defaultValue(referenceFrame, ReferenceFrame$1.FIXED);
  }

  Object.defineProperties(TimeIntervalCollectionPositionProperty.prototype, {
    /**
     * Gets a value indicating if this property is constant.  A property is considered
     * constant if getValue always returns the same result for the current definition.
     * @memberof TimeIntervalCollectionPositionProperty.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    isConstant: {
      get: function () {
        return this._intervals.isEmpty;
      },
    },
    /**
     * Gets the event that is raised whenever the definition of this property changes.
     * The definition is considered to have changed if a call to getValue would return
     * a different result for the same time.
     * @memberof TimeIntervalCollectionPositionProperty.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },
    /**
     * Gets the interval collection.
     * @memberof TimeIntervalCollectionPositionProperty.prototype
     * @type {TimeIntervalCollection}
     * @readonly
     */
    intervals: {
      get: function () {
        return this._intervals;
      },
    },
    /**
     * Gets the reference frame in which the position is defined.
     * @memberof TimeIntervalCollectionPositionProperty.prototype
     * @type {ReferenceFrame}
     * @readonly
     * @default ReferenceFrame.FIXED;
     */
    referenceFrame: {
      get: function () {
        return this._referenceFrame;
      },
    },
  });

  /**
   * Gets the value of the property at the provided time in the fixed frame.
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {Object} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Cartesian3 | undefined} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  TimeIntervalCollectionPositionProperty.prototype.getValue = function (
    time,
    result
  ) {
    return this.getValueInReferenceFrame(time, ReferenceFrame$1.FIXED, result);
  };

  /**
   * Gets the value of the property at the provided time and in the provided reference frame.
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {ReferenceFrame} referenceFrame The desired referenceFrame of the result.
   * @param {Cartesian3} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Cartesian3 | undefined} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  TimeIntervalCollectionPositionProperty.prototype.getValueInReferenceFrame = function (
    time,
    referenceFrame,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(time)) {
      throw new DeveloperError("time is required.");
    }
    if (!defined(referenceFrame)) {
      throw new DeveloperError("referenceFrame is required.");
    }
    //>>includeEnd('debug');

    const position = this._intervals.findDataForIntervalContainingDate(time);
    if (defined(position)) {
      return PositionProperty.convertToReferenceFrame(
        time,
        position,
        this._referenceFrame,
        referenceFrame,
        result
      );
    }
    return undefined;
  };

  /**
   * Compares this property to the provided property and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Property} [other] The other property.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  TimeIntervalCollectionPositionProperty.prototype.equals = function (other) {
    return (
      this === other || //
      (other instanceof TimeIntervalCollectionPositionProperty && //
        this._intervals.equals(other._intervals, Property.equals) && //
        this._referenceFrame === other._referenceFrame)
    );
  };

  /**
   * @private
   */
  TimeIntervalCollectionPositionProperty.prototype._intervalsChanged = function () {
    this._definitionChanged.raiseEvent(this);
  };

  /**
   * A {@link Property} which is defined by a {@link TimeIntervalCollection}, where the
   * data property of each {@link TimeInterval} represents the value at time.
   *
   * @alias TimeIntervalCollectionProperty
   * @constructor
   *
   * @example
   * //Create a Cartesian2 interval property which contains data on August 1st, 2012
   * //and uses a different value every 6 hours.
   * const composite = new Cesium.TimeIntervalCollectionProperty();
   * composite.intervals.addInterval(Cesium.TimeInterval.fromIso8601({
   *     iso8601 : '2012-08-01T00:00:00.00Z/2012-08-01T06:00:00.00Z',
   *     isStartIncluded : true,
   *     isStopIncluded : false,
   *     data : new Cesium.Cartesian2(2.0, 3.4)
   * }));
   * composite.intervals.addInterval(Cesium.TimeInterval.fromIso8601({
   *     iso8601 : '2012-08-01T06:00:00.00Z/2012-08-01T12:00:00.00Z',
   *     isStartIncluded : true,
   *     isStopIncluded : false,
   *     data : new Cesium.Cartesian2(12.0, 2.7)
   * }));
   * composite.intervals.addInterval(Cesium.TimeInterval.fromIso8601({
   *     iso8601 : '2012-08-01T12:00:00.00Z/2012-08-01T18:00:00.00Z',
   *     isStartIncluded : true,
   *     isStopIncluded : false,
   *     data : new Cesium.Cartesian2(5.0, 12.4)
   * }));
   * composite.intervals.addInterval(Cesium.TimeInterval.fromIso8601({
   *     iso8601 : '2012-08-01T18:00:00.00Z/2012-08-02T00:00:00.00Z',
   *     isStartIncluded : true,
   *     isStopIncluded : true,
   *     data : new Cesium.Cartesian2(85.0, 4.1)
   * }));
   */
  function TimeIntervalCollectionProperty() {
    this._definitionChanged = new Event();
    this._intervals = new TimeIntervalCollection();
    this._intervals.changedEvent.addEventListener(
      TimeIntervalCollectionProperty.prototype._intervalsChanged,
      this
    );
  }

  Object.defineProperties(TimeIntervalCollectionProperty.prototype, {
    /**
     * Gets a value indicating if this property is constant.  A property is considered
     * constant if getValue always returns the same result for the current definition.
     * @memberof TimeIntervalCollectionProperty.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    isConstant: {
      get: function () {
        return this._intervals.isEmpty;
      },
    },
    /**
     * Gets the event that is raised whenever the definition of this property changes.
     * The definition is changed whenever setValue is called with data different
     * than the current value.
     * @memberof TimeIntervalCollectionProperty.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },
    /**
     * Gets the interval collection.
     * @memberof TimeIntervalCollectionProperty.prototype
     *
     * @type {TimeIntervalCollection}
     * @readonly
     */
    intervals: {
      get: function () {
        return this._intervals;
      },
    },
  });

  /**
   * Gets the value of the property at the provided time.
   *
   * @param {JulianDate} time The time for which to retrieve the value.
   * @param {Object} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Object} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  TimeIntervalCollectionProperty.prototype.getValue = function (time, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(time)) {
      throw new DeveloperError("time is required");
    }
    //>>includeEnd('debug');

    const value = this._intervals.findDataForIntervalContainingDate(time);
    if (defined(value) && typeof value.clone === "function") {
      return value.clone(result);
    }
    return value;
  };

  /**
   * Compares this property to the provided property and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Property} [other] The other property.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  TimeIntervalCollectionProperty.prototype.equals = function (other) {
    return (
      this === other || //
      (other instanceof TimeIntervalCollectionProperty && //
        this._intervals.equals(other._intervals, Property.equals))
    );
  };

  /**
   * @private
   */
  TimeIntervalCollectionProperty.prototype._intervalsChanged = function () {
    this._definitionChanged.raiseEvent(this);
  };

  /**
   * A {@link Property} which evaluates to a {@link Cartesian3} vector
   * based on the velocity of the provided {@link PositionProperty}.
   *
   * @alias VelocityVectorProperty
   * @constructor
   *
   * @param {PositionProperty} [position] The position property used to compute the velocity.
   * @param {Boolean} [normalize=true] Whether to normalize the computed velocity vector.
   *
   * @example
   * //Create an entity with a billboard rotated to match its velocity.
   * const position = new Cesium.SampledProperty();
   * position.addSamples(...);
   * const entity = viewer.entities.add({
   *   position : position,
   *   billboard : {
   *     image : 'image.png',
   *     alignedAxis : new Cesium.VelocityVectorProperty(position, true) // alignedAxis must be a unit vector
   *   }
   * }));
   */
  function VelocityVectorProperty(position, normalize) {
    this._position = undefined;
    this._subscription = undefined;
    this._definitionChanged = new Event();
    this._normalize = defaultValue(normalize, true);

    this.position = position;
  }

  Object.defineProperties(VelocityVectorProperty.prototype, {
    /**
     * Gets a value indicating if this property is constant.
     * @memberof VelocityVectorProperty.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    isConstant: {
      get: function () {
        return Property.isConstant(this._position);
      },
    },
    /**
     * Gets the event that is raised whenever the definition of this property changes.
     * @memberof VelocityVectorProperty.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },
    /**
     * Gets or sets the position property used to compute the velocity vector.
     * @memberof VelocityVectorProperty.prototype
     *
     * @type {Property|undefined}
     */
    position: {
      get: function () {
        return this._position;
      },
      set: function (value) {
        const oldValue = this._position;
        if (oldValue !== value) {
          if (defined(oldValue)) {
            this._subscription();
          }

          this._position = value;

          if (defined(value)) {
            this._subscription = value._definitionChanged.addEventListener(
              function () {
                this._definitionChanged.raiseEvent(this);
              },
              this
            );
          }

          this._definitionChanged.raiseEvent(this);
        }
      },
    },
    /**
     * Gets or sets whether the vector produced by this property
     * will be normalized or not.
     * @memberof VelocityVectorProperty.prototype
     *
     * @type {Boolean}
     */
    normalize: {
      get: function () {
        return this._normalize;
      },
      set: function (value) {
        if (this._normalize === value) {
          return;
        }

        this._normalize = value;
        this._definitionChanged.raiseEvent(this);
      },
    },
  });

  const position1Scratch = new Cartesian3();
  const position2Scratch = new Cartesian3();
  const timeScratch = new JulianDate();
  const step = 1.0 / 60.0;

  /**
   * Gets the value of the property at the provided time.
   *
   * @param {JulianDate} [time] The time for which to retrieve the value.
   * @param {Cartesian3} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Cartesian3} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  VelocityVectorProperty.prototype.getValue = function (time, result) {
    return this._getValue(time, result);
  };

  /**
   * @private
   */
  VelocityVectorProperty.prototype._getValue = function (
    time,
    velocityResult,
    positionResult
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(time)) {
      throw new DeveloperError("time is required");
    }
    //>>includeEnd('debug');

    if (!defined(velocityResult)) {
      velocityResult = new Cartesian3();
    }

    const property = this._position;
    if (Property.isConstant(property)) {
      return this._normalize
        ? undefined
        : Cartesian3.clone(Cartesian3.ZERO, velocityResult);
    }

    let position1 = property.getValue(time, position1Scratch);
    let position2 = property.getValue(
      JulianDate.addSeconds(time, step, timeScratch),
      position2Scratch
    );

    //If we don't have a position for now, return undefined.
    if (!defined(position1)) {
      return undefined;
    }

    //If we don't have a position for now + step, see if we have a position for now - step.
    if (!defined(position2)) {
      position2 = position1;
      position1 = property.getValue(
        JulianDate.addSeconds(time, -step, timeScratch),
        position2Scratch
      );

      if (!defined(position1)) {
        return undefined;
      }
    }

    if (Cartesian3.equals(position1, position2)) {
      return this._normalize
        ? undefined
        : Cartesian3.clone(Cartesian3.ZERO, velocityResult);
    }

    if (defined(positionResult)) {
      position1.clone(positionResult);
    }

    const velocity = Cartesian3.subtract(position2, position1, velocityResult);
    if (this._normalize) {
      return Cartesian3.normalize(velocity, velocityResult);
    }

    return Cartesian3.divideByScalar(velocity, step, velocityResult);
  };

  /**
   * Compares this property to the provided property and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Property} [other] The other property.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  VelocityVectorProperty.prototype.equals = function (other) {
    return (
      this === other || //
      (other instanceof VelocityVectorProperty &&
        Property.equals(this._position, other._position))
    );
  };

  /**
   * A {@link Property} which evaluates to a {@link Quaternion} rotation
   * based on the velocity of the provided {@link PositionProperty}.
   *
   * @alias VelocityOrientationProperty
   * @constructor
   *
   * @param {PositionProperty} [position] The position property used to compute the orientation.
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid used to determine which way is up.
   *
   * @example
   * //Create an entity with position and orientation.
   * const position = new Cesium.SampledProperty();
   * position.addSamples(...);
   * const entity = viewer.entities.add({
   *   position : position,
   *   orientation : new Cesium.VelocityOrientationProperty(position)
   * }));
   */
  function VelocityOrientationProperty(position, ellipsoid) {
    this._velocityVectorProperty = new VelocityVectorProperty(position, true);
    this._subscription = undefined;
    this._ellipsoid = undefined;
    this._definitionChanged = new Event();

    this.ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);

    const that = this;
    this._velocityVectorProperty.definitionChanged.addEventListener(function () {
      that._definitionChanged.raiseEvent(that);
    });
  }

  Object.defineProperties(VelocityOrientationProperty.prototype, {
    /**
     * Gets a value indicating if this property is constant.
     * @memberof VelocityOrientationProperty.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    isConstant: {
      get: function () {
        return Property.isConstant(this._velocityVectorProperty);
      },
    },
    /**
     * Gets the event that is raised whenever the definition of this property changes.
     * @memberof VelocityOrientationProperty.prototype
     *
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },
    /**
     * Gets or sets the position property used to compute orientation.
     * @memberof VelocityOrientationProperty.prototype
     *
     * @type {Property|undefined}
     */
    position: {
      get: function () {
        return this._velocityVectorProperty.position;
      },
      set: function (value) {
        this._velocityVectorProperty.position = value;
      },
    },
    /**
     * Gets or sets the ellipsoid used to determine which way is up.
     * @memberof VelocityOrientationProperty.prototype
     *
     * @type {Property|undefined}
     */
    ellipsoid: {
      get: function () {
        return this._ellipsoid;
      },
      set: function (value) {
        const oldValue = this._ellipsoid;
        if (oldValue !== value) {
          this._ellipsoid = value;
          this._definitionChanged.raiseEvent(this);
        }
      },
    },
  });

  const positionScratch$3 = new Cartesian3();
  const velocityScratch = new Cartesian3();
  const rotationScratch$1 = new Matrix3();

  /**
   * Gets the value of the property at the provided time.
   *
   * @param {JulianDate} [time] The time for which to retrieve the value.
   * @param {Quaternion} [result] The object to store the value into, if omitted, a new instance is created and returned.
   * @returns {Quaternion} The modified result parameter or a new instance if the result parameter was not supplied.
   */
  VelocityOrientationProperty.prototype.getValue = function (time, result) {
    const velocity = this._velocityVectorProperty._getValue(
      time,
      velocityScratch,
      positionScratch$3
    );

    if (!defined(velocity)) {
      return undefined;
    }

    Transforms.rotationMatrixFromPositionVelocity(
      positionScratch$3,
      velocity,
      this._ellipsoid,
      rotationScratch$1
    );
    return Quaternion.fromRotationMatrix(rotationScratch$1, result);
  };

  /**
   * Compares this property to the provided property and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Property} [other] The other property.
   * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  VelocityOrientationProperty.prototype.equals = function (other) {
    return (
      this === other || //
      (other instanceof VelocityOrientationProperty &&
        Property.equals(
          this._velocityVectorProperty,
          other._velocityVectorProperty
        ) &&
        (this._ellipsoid === other._ellipsoid ||
          this._ellipsoid.equals(other._ellipsoid)))
    );
  };

  // A marker type to distinguish CZML properties where we need to end up with a unit vector.
  // The data is still loaded into Cartesian3 objects but they are normalized.
  function UnitCartesian3() {}
  UnitCartesian3.packedLength = Cartesian3.packedLength;
  UnitCartesian3.unpack = Cartesian3.unpack;
  UnitCartesian3.pack = Cartesian3.pack;

  // As a side note, for the purposes of CZML, Quaternion always indicates a unit quaternion.

  let currentId;

  function createReferenceProperty(entityCollection, referenceString) {
    if (referenceString[0] === "#") {
      referenceString = currentId + referenceString;
    }
    return ReferenceProperty.fromString(entityCollection, referenceString);
  }

  function createSpecializedProperty(type, entityCollection, packetData) {
    if (defined(packetData.reference)) {
      return createReferenceProperty(entityCollection, packetData.reference);
    }

    if (defined(packetData.velocityReference)) {
      const referenceProperty = createReferenceProperty(
        entityCollection,
        packetData.velocityReference
      );
      switch (type) {
        case Cartesian3:
        case UnitCartesian3:
          return new VelocityVectorProperty(
            referenceProperty,
            type === UnitCartesian3
          );
        case Quaternion:
          return new VelocityOrientationProperty(referenceProperty);
      }
    }

    throw new RuntimeError(`${JSON.stringify(packetData)} is not valid CZML.`);
  }

  function createAdapterProperty(property, adapterFunction) {
    return new CallbackProperty(function (time, result) {
      return adapterFunction(property.getValue(time, result));
    }, property.isConstant);
  }

  const scratchCartesian$3 = new Cartesian3();
  const scratchSpherical = new Spherical();
  const scratchCartographic$8 = new Cartographic();
  const scratchTimeInterval$1 = new TimeInterval();
  const scratchQuaternion = new Quaternion();

  function unwrapColorInterval(czmlInterval) {
    let rgbaf = czmlInterval.rgbaf;
    if (defined(rgbaf)) {
      return rgbaf;
    }

    const rgba = czmlInterval.rgba;
    if (!defined(rgba)) {
      return undefined;
    }

    const length = rgba.length;
    if (length === Color.packedLength) {
      return [
        Color.byteToFloat(rgba[0]),
        Color.byteToFloat(rgba[1]),
        Color.byteToFloat(rgba[2]),
        Color.byteToFloat(rgba[3]),
      ];
    }

    rgbaf = new Array(length);
    for (let i = 0; i < length; i += 5) {
      rgbaf[i] = rgba[i];
      rgbaf[i + 1] = Color.byteToFloat(rgba[i + 1]);
      rgbaf[i + 2] = Color.byteToFloat(rgba[i + 2]);
      rgbaf[i + 3] = Color.byteToFloat(rgba[i + 3]);
      rgbaf[i + 4] = Color.byteToFloat(rgba[i + 4]);
    }
    return rgbaf;
  }

  function unwrapUriInterval(czmlInterval, sourceUri) {
    const uri = defaultValue(czmlInterval.uri, czmlInterval);
    if (defined(sourceUri)) {
      return sourceUri.getDerivedResource({
        url: uri,
      });
    }

    return Resource.createIfNeeded(uri);
  }

  function unwrapRectangleInterval(czmlInterval) {
    let wsen = czmlInterval.wsen;
    if (defined(wsen)) {
      return wsen;
    }

    const wsenDegrees = czmlInterval.wsenDegrees;
    if (!defined(wsenDegrees)) {
      return undefined;
    }

    const length = wsenDegrees.length;
    if (length === Rectangle.packedLength) {
      return [
        CesiumMath.toRadians(wsenDegrees[0]),
        CesiumMath.toRadians(wsenDegrees[1]),
        CesiumMath.toRadians(wsenDegrees[2]),
        CesiumMath.toRadians(wsenDegrees[3]),
      ];
    }

    wsen = new Array(length);
    for (let i = 0; i < length; i += 5) {
      wsen[i] = wsenDegrees[i];
      wsen[i + 1] = CesiumMath.toRadians(wsenDegrees[i + 1]);
      wsen[i + 2] = CesiumMath.toRadians(wsenDegrees[i + 2]);
      wsen[i + 3] = CesiumMath.toRadians(wsenDegrees[i + 3]);
      wsen[i + 4] = CesiumMath.toRadians(wsenDegrees[i + 4]);
    }
    return wsen;
  }

  function convertUnitSphericalToCartesian(unitSpherical) {
    const length = unitSpherical.length;
    scratchSpherical.magnitude = 1.0;
    if (length === 2) {
      scratchSpherical.clock = unitSpherical[0];
      scratchSpherical.cone = unitSpherical[1];
      Cartesian3.fromSpherical(scratchSpherical, scratchCartesian$3);
      return [scratchCartesian$3.x, scratchCartesian$3.y, scratchCartesian$3.z];
    }

    const result = new Array((length / 3) * 4);
    for (let i = 0, j = 0; i < length; i += 3, j += 4) {
      result[j] = unitSpherical[i];

      scratchSpherical.clock = unitSpherical[i + 1];
      scratchSpherical.cone = unitSpherical[i + 2];
      Cartesian3.fromSpherical(scratchSpherical, scratchCartesian$3);

      result[j + 1] = scratchCartesian$3.x;
      result[j + 2] = scratchCartesian$3.y;
      result[j + 3] = scratchCartesian$3.z;
    }
    return result;
  }

  function convertSphericalToCartesian(spherical) {
    const length = spherical.length;
    if (length === 3) {
      scratchSpherical.clock = spherical[0];
      scratchSpherical.cone = spherical[1];
      scratchSpherical.magnitude = spherical[2];
      Cartesian3.fromSpherical(scratchSpherical, scratchCartesian$3);
      return [scratchCartesian$3.x, scratchCartesian$3.y, scratchCartesian$3.z];
    }

    const result = new Array(length);
    for (let i = 0; i < length; i += 4) {
      result[i] = spherical[i];

      scratchSpherical.clock = spherical[i + 1];
      scratchSpherical.cone = spherical[i + 2];
      scratchSpherical.magnitude = spherical[i + 3];
      Cartesian3.fromSpherical(scratchSpherical, scratchCartesian$3);

      result[i + 1] = scratchCartesian$3.x;
      result[i + 2] = scratchCartesian$3.y;
      result[i + 3] = scratchCartesian$3.z;
    }
    return result;
  }

  function convertCartographicRadiansToCartesian(cartographicRadians) {
    const length = cartographicRadians.length;
    if (length === 3) {
      scratchCartographic$8.longitude = cartographicRadians[0];
      scratchCartographic$8.latitude = cartographicRadians[1];
      scratchCartographic$8.height = cartographicRadians[2];
      Ellipsoid.WGS84.cartographicToCartesian(
        scratchCartographic$8,
        scratchCartesian$3
      );
      return [scratchCartesian$3.x, scratchCartesian$3.y, scratchCartesian$3.z];
    }

    const result = new Array(length);
    for (let i = 0; i < length; i += 4) {
      result[i] = cartographicRadians[i];

      scratchCartographic$8.longitude = cartographicRadians[i + 1];
      scratchCartographic$8.latitude = cartographicRadians[i + 2];
      scratchCartographic$8.height = cartographicRadians[i + 3];
      Ellipsoid.WGS84.cartographicToCartesian(
        scratchCartographic$8,
        scratchCartesian$3
      );

      result[i + 1] = scratchCartesian$3.x;
      result[i + 2] = scratchCartesian$3.y;
      result[i + 3] = scratchCartesian$3.z;
    }
    return result;
  }

  function convertCartographicDegreesToCartesian(cartographicDegrees) {
    const length = cartographicDegrees.length;
    if (length === 3) {
      scratchCartographic$8.longitude = CesiumMath.toRadians(
        cartographicDegrees[0]
      );
      scratchCartographic$8.latitude = CesiumMath.toRadians(cartographicDegrees[1]);
      scratchCartographic$8.height = cartographicDegrees[2];
      Ellipsoid.WGS84.cartographicToCartesian(
        scratchCartographic$8,
        scratchCartesian$3
      );
      return [scratchCartesian$3.x, scratchCartesian$3.y, scratchCartesian$3.z];
    }

    const result = new Array(length);
    for (let i = 0; i < length; i += 4) {
      result[i] = cartographicDegrees[i];

      scratchCartographic$8.longitude = CesiumMath.toRadians(
        cartographicDegrees[i + 1]
      );
      scratchCartographic$8.latitude = CesiumMath.toRadians(
        cartographicDegrees[i + 2]
      );
      scratchCartographic$8.height = cartographicDegrees[i + 3];
      Ellipsoid.WGS84.cartographicToCartesian(
        scratchCartographic$8,
        scratchCartesian$3
      );

      result[i + 1] = scratchCartesian$3.x;
      result[i + 2] = scratchCartesian$3.y;
      result[i + 3] = scratchCartesian$3.z;
    }
    return result;
  }

  function unwrapCartesianInterval(czmlInterval) {
    const cartesian = czmlInterval.cartesian;
    if (defined(cartesian)) {
      return cartesian;
    }

    const cartesianVelocity = czmlInterval.cartesianVelocity;
    if (defined(cartesianVelocity)) {
      return cartesianVelocity;
    }

    const unitCartesian = czmlInterval.unitCartesian;
    if (defined(unitCartesian)) {
      return unitCartesian;
    }

    const unitSpherical = czmlInterval.unitSpherical;
    if (defined(unitSpherical)) {
      return convertUnitSphericalToCartesian(unitSpherical);
    }

    const spherical = czmlInterval.spherical;
    if (defined(spherical)) {
      return convertSphericalToCartesian(spherical);
    }

    const cartographicRadians = czmlInterval.cartographicRadians;
    if (defined(cartographicRadians)) {
      return convertCartographicRadiansToCartesian(cartographicRadians);
    }

    const cartographicDegrees = czmlInterval.cartographicDegrees;
    if (defined(cartographicDegrees)) {
      return convertCartographicDegreesToCartesian(cartographicDegrees);
    }

    throw new RuntimeError(
      `${JSON.stringify(czmlInterval)} is not a valid CZML interval.`
    );
  }

  function normalizePackedCartesianArray(array, startingIndex) {
    Cartesian3.unpack(array, startingIndex, scratchCartesian$3);
    Cartesian3.normalize(scratchCartesian$3, scratchCartesian$3);
    Cartesian3.pack(scratchCartesian$3, array, startingIndex);
  }

  function unwrapUnitCartesianInterval(czmlInterval) {
    const cartesian = unwrapCartesianInterval(czmlInterval);
    if (cartesian.length === 3) {
      normalizePackedCartesianArray(cartesian, 0);
      return cartesian;
    }

    for (let i = 1; i < cartesian.length; i += 4) {
      normalizePackedCartesianArray(cartesian, i);
    }

    return cartesian;
  }

  function normalizePackedQuaternionArray(array, startingIndex) {
    Quaternion.unpack(array, startingIndex, scratchQuaternion);
    Quaternion.normalize(scratchQuaternion, scratchQuaternion);
    Quaternion.pack(scratchQuaternion, array, startingIndex);
  }

  function unwrapQuaternionInterval(czmlInterval) {
    const unitQuaternion = czmlInterval.unitQuaternion;
    if (defined(unitQuaternion)) {
      if (unitQuaternion.length === 4) {
        normalizePackedQuaternionArray(unitQuaternion, 0);
        return unitQuaternion;
      }

      for (let i = 1; i < unitQuaternion.length; i += 5) {
        normalizePackedQuaternionArray(unitQuaternion, i);
      }
    }
    return unitQuaternion;
  }

  function getPropertyType(czmlInterval) {
    // The associations in this function need to be kept in sync with the
    // associations in unwrapInterval.

    // Intentionally omitted due to conficts in CZML property names:
    // * Image (conflicts with Uri)
    // * Rotation (conflicts with Number)
    //
    // cartesianVelocity is also omitted due to incomplete support for
    // derivative information in CZML properties.
    // (Currently cartesianVelocity is hacked directly into the position processing code)
    if (typeof czmlInterval === "boolean") {
      return Boolean;
    } else if (typeof czmlInterval === "number") {
      return Number;
    } else if (typeof czmlInterval === "string") {
      return String;
    } else if (czmlInterval.hasOwnProperty("array")) {
      return Array;
    } else if (czmlInterval.hasOwnProperty("boolean")) {
      return Boolean;
    } else if (czmlInterval.hasOwnProperty("boundingRectangle")) {
      return BoundingRectangle;
    } else if (czmlInterval.hasOwnProperty("cartesian2")) {
      return Cartesian2;
    } else if (
      czmlInterval.hasOwnProperty("cartesian") ||
      czmlInterval.hasOwnProperty("spherical") ||
      czmlInterval.hasOwnProperty("cartographicRadians") ||
      czmlInterval.hasOwnProperty("cartographicDegrees")
    ) {
      return Cartesian3;
    } else if (
      czmlInterval.hasOwnProperty("unitCartesian") ||
      czmlInterval.hasOwnProperty("unitSpherical")
    ) {
      return UnitCartesian3;
    } else if (
      czmlInterval.hasOwnProperty("rgba") ||
      czmlInterval.hasOwnProperty("rgbaf")
    ) {
      return Color;
    } else if (czmlInterval.hasOwnProperty("arcType")) {
      return ArcType$1;
    } else if (czmlInterval.hasOwnProperty("classificationType")) {
      return ClassificationType$1;
    } else if (czmlInterval.hasOwnProperty("colorBlendMode")) {
      return ColorBlendMode$1;
    } else if (czmlInterval.hasOwnProperty("cornerType")) {
      return CornerType$1;
    } else if (czmlInterval.hasOwnProperty("heightReference")) {
      return HeightReference$1;
    } else if (czmlInterval.hasOwnProperty("horizontalOrigin")) {
      return HorizontalOrigin$1;
    } else if (czmlInterval.hasOwnProperty("date")) {
      return JulianDate;
    } else if (czmlInterval.hasOwnProperty("labelStyle")) {
      return LabelStyle$1;
    } else if (czmlInterval.hasOwnProperty("number")) {
      return Number;
    } else if (czmlInterval.hasOwnProperty("nearFarScalar")) {
      return NearFarScalar;
    } else if (czmlInterval.hasOwnProperty("distanceDisplayCondition")) {
      return DistanceDisplayCondition;
    } else if (
      czmlInterval.hasOwnProperty("object") ||
      czmlInterval.hasOwnProperty("value")
    ) {
      return Object;
    } else if (czmlInterval.hasOwnProperty("unitQuaternion")) {
      return Quaternion;
    } else if (czmlInterval.hasOwnProperty("shadowMode")) {
      return ShadowMode$1;
    } else if (czmlInterval.hasOwnProperty("string")) {
      return String;
    } else if (czmlInterval.hasOwnProperty("stripeOrientation")) {
      return StripeOrientation$1;
    } else if (
      czmlInterval.hasOwnProperty("wsen") ||
      czmlInterval.hasOwnProperty("wsenDegrees")
    ) {
      return Rectangle;
    } else if (czmlInterval.hasOwnProperty("uri")) {
      return URI;
    } else if (czmlInterval.hasOwnProperty("verticalOrigin")) {
      return VerticalOrigin$1;
    }
    // fallback case
    return Object;
  }

  function unwrapInterval(type, czmlInterval, sourceUri) {
    // The associations in this function need to be kept in sync with the
    // associations in getPropertyType
    switch (type) {
      case ArcType$1:
        return ArcType$1[defaultValue(czmlInterval.arcType, czmlInterval)];
      case Array:
        return czmlInterval.array;
      case Boolean:
        return defaultValue(czmlInterval["boolean"], czmlInterval);
      case BoundingRectangle:
        return czmlInterval.boundingRectangle;
      case Cartesian2:
        return czmlInterval.cartesian2;
      case Cartesian3:
        return unwrapCartesianInterval(czmlInterval);
      case UnitCartesian3:
        return unwrapUnitCartesianInterval(czmlInterval);
      case Color:
        return unwrapColorInterval(czmlInterval);
      case ClassificationType$1:
        return ClassificationType$1[
          defaultValue(czmlInterval.classificationType, czmlInterval)
        ];
      case ColorBlendMode$1:
        return ColorBlendMode$1[
          defaultValue(czmlInterval.colorBlendMode, czmlInterval)
        ];
      case CornerType$1:
        return CornerType$1[defaultValue(czmlInterval.cornerType, czmlInterval)];
      case HeightReference$1:
        return HeightReference$1[
          defaultValue(czmlInterval.heightReference, czmlInterval)
        ];
      case HorizontalOrigin$1:
        return HorizontalOrigin$1[
          defaultValue(czmlInterval.horizontalOrigin, czmlInterval)
        ];
      case Image:
        return unwrapUriInterval(czmlInterval, sourceUri);
      case JulianDate:
        return JulianDate.fromIso8601(
          defaultValue(czmlInterval.date, czmlInterval)
        );
      case LabelStyle$1:
        return LabelStyle$1[defaultValue(czmlInterval.labelStyle, czmlInterval)];
      case Number:
        return defaultValue(czmlInterval.number, czmlInterval);
      case NearFarScalar:
        return czmlInterval.nearFarScalar;
      case DistanceDisplayCondition:
        return czmlInterval.distanceDisplayCondition;
      case Object:
        return defaultValue(
          defaultValue(czmlInterval.object, czmlInterval.value),
          czmlInterval
        );
      case Quaternion:
        return unwrapQuaternionInterval(czmlInterval);
      case Rotation:
        return defaultValue(czmlInterval.number, czmlInterval);
      case ShadowMode$1:
        return ShadowMode$1[
          defaultValue(
            defaultValue(czmlInterval.shadowMode, czmlInterval.shadows),
            czmlInterval
          )
        ];
      case String:
        return defaultValue(czmlInterval.string, czmlInterval);
      case StripeOrientation$1:
        return StripeOrientation$1[
          defaultValue(czmlInterval.stripeOrientation, czmlInterval)
        ];
      case Rectangle:
        return unwrapRectangleInterval(czmlInterval);
      case URI:
        return unwrapUriInterval(czmlInterval, sourceUri);
      case VerticalOrigin$1:
        return VerticalOrigin$1[
          defaultValue(czmlInterval.verticalOrigin, czmlInterval)
        ];
      default:
        throw new RuntimeError(type);
    }
  }

  const interpolators = {
    HERMITE: HermitePolynomialApproximation,
    LAGRANGE: LagrangePolynomialApproximation,
    LINEAR: LinearApproximation,
  };

  function updateInterpolationSettings(packetData, property) {
    const interpolationAlgorithm = packetData.interpolationAlgorithm;
    const interpolationDegree = packetData.interpolationDegree;
    if (defined(interpolationAlgorithm) || defined(interpolationDegree)) {
      property.setInterpolationOptions({
        interpolationAlgorithm: interpolators[interpolationAlgorithm],
        interpolationDegree: interpolationDegree,
      });
    }

    const forwardExtrapolationType = packetData.forwardExtrapolationType;
    if (defined(forwardExtrapolationType)) {
      property.forwardExtrapolationType =
        ExtrapolationType$1[forwardExtrapolationType];
    }

    const forwardExtrapolationDuration = packetData.forwardExtrapolationDuration;
    if (defined(forwardExtrapolationDuration)) {
      property.forwardExtrapolationDuration = forwardExtrapolationDuration;
    }

    const backwardExtrapolationType = packetData.backwardExtrapolationType;
    if (defined(backwardExtrapolationType)) {
      property.backwardExtrapolationType =
        ExtrapolationType$1[backwardExtrapolationType];
    }

    const backwardExtrapolationDuration =
      packetData.backwardExtrapolationDuration;
    if (defined(backwardExtrapolationDuration)) {
      property.backwardExtrapolationDuration = backwardExtrapolationDuration;
    }
  }

  const iso8601Scratch = {
    iso8601: undefined,
  };

  function intervalFromString(intervalString) {
    if (!defined(intervalString)) {
      return undefined;
    }
    iso8601Scratch.iso8601 = intervalString;
    return TimeInterval.fromIso8601(iso8601Scratch);
  }

  function wrapPropertyInInfiniteInterval(property) {
    const interval = Iso8601.MAXIMUM_INTERVAL.clone();
    interval.data = property;
    return interval;
  }

  function convertPropertyToComposite(property) {
    // Create the composite and add the old property, wrapped in an infinite interval.
    const composite = new CompositeProperty();
    composite.intervals.addInterval(wrapPropertyInInfiniteInterval(property));
    return composite;
  }

  function convertPositionPropertyToComposite(property) {
    // Create the composite and add the old property, wrapped in an infinite interval.
    const composite = new CompositePositionProperty(property.referenceFrame);
    composite.intervals.addInterval(wrapPropertyInInfiniteInterval(property));
    return composite;
  }

  function processProperty(
    type,
    object,
    propertyName,
    packetData,
    constrainedInterval,
    sourceUri,
    entityCollection
  ) {
    let combinedInterval = intervalFromString(packetData.interval);
    if (defined(constrainedInterval)) {
      if (defined(combinedInterval)) {
        combinedInterval = TimeInterval.intersect(
          combinedInterval,
          constrainedInterval,
          scratchTimeInterval$1
        );
      } else {
        combinedInterval = constrainedInterval;
      }
    }

    let packedLength;
    let unwrappedInterval;
    let unwrappedIntervalLength;

    // CZML properties can be defined in many ways.  Most ways represent a structure for
    // encoding a single value (number, string, cartesian, etc.)  Regardless of the value type,
    // if it encodes a single value it will get loaded into a ConstantProperty eventually.
    // Alternatively, there are ways of defining a property that require specialized
    // client-side representation. Currently, these are ReferenceProperty,
    // and client-side velocity computation properties such as VelocityVectorProperty.
    const isValue =
      !defined(packetData.reference) && !defined(packetData.velocityReference);
    const hasInterval =
      defined(combinedInterval) &&
      !combinedInterval.equals(Iso8601.MAXIMUM_INTERVAL);

    if (packetData.delete === true) {
      // If deleting this property for all time, we can simply set to undefined and return.
      if (!hasInterval) {
        object[propertyName] = undefined;
        return;
      }

      // Deleting depends on the type of property we have.
      return removePropertyData(object[propertyName], combinedInterval);
    }

    let isSampled = false;

    if (isValue) {
      unwrappedInterval = unwrapInterval(type, packetData, sourceUri);
      if (!defined(unwrappedInterval)) {
        // not a known value type, bail
        return;
      }
      packedLength = defaultValue(type.packedLength, 1);
      unwrappedIntervalLength = defaultValue(unwrappedInterval.length, 1);
      isSampled =
        !defined(packetData.array) &&
        typeof unwrappedInterval !== "string" &&
        unwrappedIntervalLength > packedLength &&
        type !== Object;
    }

    // Rotation is a special case because it represents a native type (Number)
    // and therefore does not need to be unpacked when loaded as a constant value.
    const needsUnpacking = typeof type.unpack === "function" && type !== Rotation;

    // Any time a constant value is assigned, it completely blows away anything else.
    if (!isSampled && !hasInterval) {
      if (isValue) {
        object[propertyName] = new ConstantProperty(
          needsUnpacking ? type.unpack(unwrappedInterval, 0) : unwrappedInterval
        );
      } else {
        object[propertyName] = createSpecializedProperty(
          type,
          entityCollection,
          packetData
        );
      }
      return;
    }

    let property = object[propertyName];

    let epoch;
    const packetEpoch = packetData.epoch;
    if (defined(packetEpoch)) {
      epoch = JulianDate.fromIso8601(packetEpoch);
    }

    // Without an interval, any sampled value is infinite, meaning it completely
    // replaces any non-sampled property that may exist.
    if (isSampled && !hasInterval) {
      if (!(property instanceof SampledProperty)) {
        object[propertyName] = property = new SampledProperty(type);
      }
      property.addSamplesPackedArray(unwrappedInterval, epoch);
      updateInterpolationSettings(packetData, property);
      return;
    }

    let interval;

    // A constant value with an interval is normally part of a TimeIntervalCollection,
    // However, if the current property is not a time-interval collection, we need
    // to turn it into a Composite, preserving the old data with the new interval.
    if (!isSampled && hasInterval) {
      // Create a new interval for the constant value.
      combinedInterval = combinedInterval.clone();
      if (isValue) {
        combinedInterval.data = needsUnpacking
          ? type.unpack(unwrappedInterval, 0)
          : unwrappedInterval;
      } else {
        combinedInterval.data = createSpecializedProperty(
          type,
          entityCollection,
          packetData
        );
      }

      // If no property exists, simply use a new interval collection
      if (!defined(property)) {
        object[propertyName] = property = isValue
          ? new TimeIntervalCollectionProperty()
          : new CompositeProperty();
      }

      if (isValue && property instanceof TimeIntervalCollectionProperty) {
        // If we created a collection, or it already was one, use it.
        property.intervals.addInterval(combinedInterval);
      } else if (property instanceof CompositeProperty) {
        // If the collection was already a CompositeProperty, use it.
        if (isValue) {
          combinedInterval.data = new ConstantProperty(combinedInterval.data);
        }
        property.intervals.addInterval(combinedInterval);
      } else {
        // Otherwise, create a CompositeProperty but preserve the existing data.
        object[propertyName] = property = convertPropertyToComposite(property);

        // Change the new data to a ConstantProperty and add it.
        if (isValue) {
          combinedInterval.data = new ConstantProperty(combinedInterval.data);
        }
        property.intervals.addInterval(combinedInterval);
      }

      return;
    }

    // isSampled && hasInterval
    if (!defined(property)) {
      object[propertyName] = property = new CompositeProperty();
    }

    // Create a CompositeProperty but preserve the existing data.
    if (!(property instanceof CompositeProperty)) {
      object[propertyName] = property = convertPropertyToComposite(property);
    }

    // Check if the interval already exists in the composite.
    const intervals = property.intervals;
    interval = intervals.findInterval(combinedInterval);
    if (!defined(interval) || !(interval.data instanceof SampledProperty)) {
      // If not, create a SampledProperty for it.
      interval = combinedInterval.clone();
      interval.data = new SampledProperty(type);
      intervals.addInterval(interval);
    }
    interval.data.addSamplesPackedArray(unwrappedInterval, epoch);
    updateInterpolationSettings(packetData, interval.data);
  }

  function removePropertyData(property, interval) {
    if (property instanceof SampledProperty) {
      property.removeSamples(interval);
      return;
    } else if (property instanceof TimeIntervalCollectionProperty) {
      property.intervals.removeInterval(interval);
      return;
    } else if (property instanceof CompositeProperty) {
      const intervals = property.intervals;
      for (let i = 0; i < intervals.length; ++i) {
        const intersection = TimeInterval.intersect(
          intervals.get(i),
          interval,
          scratchTimeInterval$1
        );
        if (!intersection.isEmpty) {
          // remove data from the contained properties
          removePropertyData(intersection.data, interval);
        }
      }
      // remove the intervals from the composite
      intervals.removeInterval(interval);
      return;
    }
  }

  function processPacketData(
    type,
    object,
    propertyName,
    packetData,
    interval,
    sourceUri,
    entityCollection
  ) {
    if (!defined(packetData)) {
      return;
    }

    if (Array.isArray(packetData)) {
      for (let i = 0, len = packetData.length; i < len; ++i) {
        processProperty(
          type,
          object,
          propertyName,
          packetData[i],
          interval,
          sourceUri,
          entityCollection
        );
      }
    } else {
      processProperty(
        type,
        object,
        propertyName,
        packetData,
        interval,
        sourceUri,
        entityCollection
      );
    }
  }

  function processPositionProperty(
    object,
    propertyName,
    packetData,
    constrainedInterval,
    sourceUri,
    entityCollection
  ) {
    let combinedInterval = intervalFromString(packetData.interval);
    if (defined(constrainedInterval)) {
      if (defined(combinedInterval)) {
        combinedInterval = TimeInterval.intersect(
          combinedInterval,
          constrainedInterval,
          scratchTimeInterval$1
        );
      } else {
        combinedInterval = constrainedInterval;
      }
    }

    const numberOfDerivatives = defined(packetData.cartesianVelocity) ? 1 : 0;
    const packedLength = Cartesian3.packedLength * (numberOfDerivatives + 1);
    let unwrappedInterval;
    let unwrappedIntervalLength;
    const isValue = !defined(packetData.reference);
    const hasInterval =
      defined(combinedInterval) &&
      !combinedInterval.equals(Iso8601.MAXIMUM_INTERVAL);

    if (packetData.delete === true) {
      // If deleting this property for all time, we can simply set to undefined and return.
      if (!hasInterval) {
        object[propertyName] = undefined;
        return;
      }

      // Deleting depends on the type of property we have.
      return removePositionPropertyData(object[propertyName], combinedInterval);
    }

    let referenceFrame;
    let isSampled = false;

    if (isValue) {
      if (defined(packetData.referenceFrame)) {
        referenceFrame = ReferenceFrame$1[packetData.referenceFrame];
      }
      referenceFrame = defaultValue(referenceFrame, ReferenceFrame$1.FIXED);
      unwrappedInterval = unwrapCartesianInterval(packetData);
      unwrappedIntervalLength = defaultValue(unwrappedInterval.length, 1);
      isSampled = unwrappedIntervalLength > packedLength;
    }

    // Any time a constant value is assigned, it completely blows away anything else.
    if (!isSampled && !hasInterval) {
      if (isValue) {
        object[propertyName] = new ConstantPositionProperty(
          Cartesian3.unpack(unwrappedInterval),
          referenceFrame
        );
      } else {
        object[propertyName] = createReferenceProperty(
          entityCollection,
          packetData.reference
        );
      }
      return;
    }

    let property = object[propertyName];

    let epoch;
    const packetEpoch = packetData.epoch;
    if (defined(packetEpoch)) {
      epoch = JulianDate.fromIso8601(packetEpoch);
    }

    // Without an interval, any sampled value is infinite, meaning it completely
    // replaces any non-sampled property that may exist.
    if (isSampled && !hasInterval) {
      if (
        !(property instanceof SampledPositionProperty) ||
        (defined(referenceFrame) && property.referenceFrame !== referenceFrame)
      ) {
        object[propertyName] = property = new SampledPositionProperty(
          referenceFrame,
          numberOfDerivatives
        );
      }
      property.addSamplesPackedArray(unwrappedInterval, epoch);
      updateInterpolationSettings(packetData, property);
      return;
    }

    let interval;

    // A constant value with an interval is normally part of a TimeIntervalCollection,
    // However, if the current property is not a time-interval collection, we need
    // to turn it into a Composite, preserving the old data with the new interval.
    if (!isSampled && hasInterval) {
      // Create a new interval for the constant value.
      combinedInterval = combinedInterval.clone();
      if (isValue) {
        combinedInterval.data = Cartesian3.unpack(unwrappedInterval);
      } else {
        combinedInterval.data = createReferenceProperty(
          entityCollection,
          packetData.reference
        );
      }

      // If no property exists, simply use a new interval collection
      if (!defined(property)) {
        if (isValue) {
          property = new TimeIntervalCollectionPositionProperty(referenceFrame);
        } else {
          property = new CompositePositionProperty(referenceFrame);
        }
        object[propertyName] = property;
      }

      if (
        isValue &&
        property instanceof TimeIntervalCollectionPositionProperty &&
        defined(referenceFrame) &&
        property.referenceFrame === referenceFrame
      ) {
        // If we create a collection, or it already existed, use it.
        property.intervals.addInterval(combinedInterval);
      } else if (property instanceof CompositePositionProperty) {
        // If the collection was already a CompositePositionProperty, use it.
        if (isValue) {
          combinedInterval.data = new ConstantPositionProperty(
            combinedInterval.data,
            referenceFrame
          );
        }
        property.intervals.addInterval(combinedInterval);
      } else {
        // Otherwise, create a CompositePositionProperty but preserve the existing data.
        object[propertyName] = property = convertPositionPropertyToComposite(
          property
        );

        // Change the new data to a ConstantPositionProperty and add it.
        if (isValue) {
          combinedInterval.data = new ConstantPositionProperty(
            combinedInterval.data,
            referenceFrame
          );
        }
        property.intervals.addInterval(combinedInterval);
      }

      return;
    }

    // isSampled && hasInterval
    if (!defined(property)) {
      object[propertyName] = property = new CompositePositionProperty(
        referenceFrame
      );
    } else if (!(property instanceof CompositePositionProperty)) {
      // Create a CompositeProperty but preserve the existing data.
      object[propertyName] = property = convertPositionPropertyToComposite(
        property
      );
    }

    // Check if the interval already exists in the composite.
    const intervals = property.intervals;
    interval = intervals.findInterval(combinedInterval);
    if (
      !defined(interval) ||
      !(interval.data instanceof SampledPositionProperty) ||
      (defined(referenceFrame) && interval.data.referenceFrame !== referenceFrame)
    ) {
      // If not, create a SampledPositionProperty for it.
      interval = combinedInterval.clone();
      interval.data = new SampledPositionProperty(
        referenceFrame,
        numberOfDerivatives
      );
      intervals.addInterval(interval);
    }
    interval.data.addSamplesPackedArray(unwrappedInterval, epoch);
    updateInterpolationSettings(packetData, interval.data);
  }

  function removePositionPropertyData(property, interval) {
    if (property instanceof SampledPositionProperty) {
      property.removeSamples(interval);
      return;
    } else if (property instanceof TimeIntervalCollectionPositionProperty) {
      property.intervals.removeInterval(interval);
      return;
    } else if (property instanceof CompositePositionProperty) {
      const intervals = property.intervals;
      for (let i = 0; i < intervals.length; ++i) {
        const intersection = TimeInterval.intersect(
          intervals.get(i),
          interval,
          scratchTimeInterval$1
        );
        if (!intersection.isEmpty) {
          // remove data from the contained properties
          removePositionPropertyData(intersection.data, interval);
        }
      }
      // remove the intervals from the composite
      intervals.removeInterval(interval);
      return;
    }
  }

  function processPositionPacketData(
    object,
    propertyName,
    packetData,
    interval,
    sourceUri,
    entityCollection
  ) {
    if (!defined(packetData)) {
      return;
    }

    if (Array.isArray(packetData)) {
      for (let i = 0, len = packetData.length; i < len; ++i) {
        processPositionProperty(
          object,
          propertyName,
          packetData[i],
          interval,
          sourceUri,
          entityCollection
        );
      }
    } else {
      processPositionProperty(
        object,
        propertyName,
        packetData,
        interval,
        sourceUri,
        entityCollection
      );
    }
  }

  function processShapePacketData(
    object,
    propertyName,
    packetData,
    entityCollection
  ) {
    if (defined(packetData.references)) {
      processReferencesArrayPacketData(
        object,
        propertyName,
        packetData.references,
        packetData.interval,
        entityCollection,
        PropertyArray,
        CompositeProperty
      );
    } else {
      if (defined(packetData.cartesian2)) {
        packetData.array = Cartesian2.unpackArray(packetData.cartesian2);
      } else if (defined(packetData.cartesian)) {
        // for backwards compatibility, also accept `cartesian`
        packetData.array = Cartesian2.unpackArray(packetData.cartesian);
      }

      if (defined(packetData.array)) {
        processPacketData(
          Array,
          object,
          propertyName,
          packetData,
          undefined,
          undefined,
          entityCollection
        );
      }
    }
  }

  function processMaterialProperty(
    object,
    propertyName,
    packetData,
    constrainedInterval,
    sourceUri,
    entityCollection
  ) {
    let combinedInterval = intervalFromString(packetData.interval);
    if (defined(constrainedInterval)) {
      if (defined(combinedInterval)) {
        combinedInterval = TimeInterval.intersect(
          combinedInterval,
          constrainedInterval,
          scratchTimeInterval$1
        );
      } else {
        combinedInterval = constrainedInterval;
      }
    }

    let property = object[propertyName];
    let existingMaterial;
    let existingInterval;

    if (defined(combinedInterval)) {
      if (!(property instanceof CompositeMaterialProperty)) {
        property = new CompositeMaterialProperty();
        object[propertyName] = property;
      }
      //See if we already have data at that interval.
      const thisIntervals = property.intervals;
      existingInterval = thisIntervals.findInterval({
        start: combinedInterval.start,
        stop: combinedInterval.stop,
      });
      if (defined(existingInterval)) {
        //We have an interval, but we need to make sure the
        //new data is the same type of material as the old data.
        existingMaterial = existingInterval.data;
      } else {
        //If not, create it.
        existingInterval = combinedInterval.clone();
        thisIntervals.addInterval(existingInterval);
      }
    } else {
      existingMaterial = property;
    }

    let materialData;
    if (defined(packetData.solidColor)) {
      if (!(existingMaterial instanceof ColorMaterialProperty)) {
        existingMaterial = new ColorMaterialProperty();
      }
      materialData = packetData.solidColor;
      processPacketData(
        Color,
        existingMaterial,
        "color",
        materialData.color,
        undefined,
        undefined,
        entityCollection
      );
    } else if (defined(packetData.grid)) {
      if (!(existingMaterial instanceof GridMaterialProperty)) {
        existingMaterial = new GridMaterialProperty();
      }
      materialData = packetData.grid;
      processPacketData(
        Color,
        existingMaterial,
        "color",
        materialData.color,
        undefined,
        sourceUri,
        entityCollection
      );
      processPacketData(
        Number,
        existingMaterial,
        "cellAlpha",
        materialData.cellAlpha,
        undefined,
        sourceUri,
        entityCollection
      );
      processPacketData(
        Cartesian2,
        existingMaterial,
        "lineCount",
        materialData.lineCount,
        undefined,
        sourceUri,
        entityCollection
      );
      processPacketData(
        Cartesian2,
        existingMaterial,
        "lineThickness",
        materialData.lineThickness,
        undefined,
        sourceUri,
        entityCollection
      );
      processPacketData(
        Cartesian2,
        existingMaterial,
        "lineOffset",
        materialData.lineOffset,
        undefined,
        sourceUri,
        entityCollection
      );
    } else if (defined(packetData.image)) {
      if (!(existingMaterial instanceof ImageMaterialProperty)) {
        existingMaterial = new ImageMaterialProperty();
      }
      materialData = packetData.image;
      processPacketData(
        Image,
        existingMaterial,
        "image",
        materialData.image,
        undefined,
        sourceUri,
        entityCollection
      );
      processPacketData(
        Cartesian2,
        existingMaterial,
        "repeat",
        materialData.repeat,
        undefined,
        sourceUri,
        entityCollection
      );
      processPacketData(
        Color,
        existingMaterial,
        "color",
        materialData.color,
        undefined,
        sourceUri,
        entityCollection
      );
      processPacketData(
        Boolean,
        existingMaterial,
        "transparent",
        materialData.transparent,
        undefined,
        sourceUri,
        entityCollection
      );
    } else if (defined(packetData.stripe)) {
      if (!(existingMaterial instanceof StripeMaterialProperty)) {
        existingMaterial = new StripeMaterialProperty();
      }
      materialData = packetData.stripe;
      processPacketData(
        StripeOrientation$1,
        existingMaterial,
        "orientation",
        materialData.orientation,
        undefined,
        sourceUri,
        entityCollection
      );
      processPacketData(
        Color,
        existingMaterial,
        "evenColor",
        materialData.evenColor,
        undefined,
        sourceUri,
        entityCollection
      );
      processPacketData(
        Color,
        existingMaterial,
        "oddColor",
        materialData.oddColor,
        undefined,
        sourceUri,
        entityCollection
      );
      processPacketData(
        Number,
        existingMaterial,
        "offset",
        materialData.offset,
        undefined,
        sourceUri,
        entityCollection
      );
      processPacketData(
        Number,
        existingMaterial,
        "repeat",
        materialData.repeat,
        undefined,
        sourceUri,
        entityCollection
      );
    } else if (defined(packetData.polylineOutline)) {
      if (!(existingMaterial instanceof PolylineOutlineMaterialProperty)) {
        existingMaterial = new PolylineOutlineMaterialProperty();
      }
      materialData = packetData.polylineOutline;
      processPacketData(
        Color,
        existingMaterial,
        "color",
        materialData.color,
        undefined,
        sourceUri,
        entityCollection
      );
      processPacketData(
        Color,
        existingMaterial,
        "outlineColor",
        materialData.outlineColor,
        undefined,
        sourceUri,
        entityCollection
      );
      processPacketData(
        Number,
        existingMaterial,
        "outlineWidth",
        materialData.outlineWidth,
        undefined,
        sourceUri,
        entityCollection
      );
    } else if (defined(packetData.polylineGlow)) {
      if (!(existingMaterial instanceof PolylineGlowMaterialProperty)) {
        existingMaterial = new PolylineGlowMaterialProperty();
      }
      materialData = packetData.polylineGlow;
      processPacketData(
        Color,
        existingMaterial,
        "color",
        materialData.color,
        undefined,
        sourceUri,
        entityCollection
      );
      processPacketData(
        Number,
        existingMaterial,
        "glowPower",
        materialData.glowPower,
        undefined,
        sourceUri,
        entityCollection
      );
      processPacketData(
        Number,
        existingMaterial,
        "taperPower",
        materialData.taperPower,
        undefined,
        sourceUri,
        entityCollection
      );
    } else if (defined(packetData.polylineArrow)) {
      if (!(existingMaterial instanceof PolylineArrowMaterialProperty)) {
        existingMaterial = new PolylineArrowMaterialProperty();
      }
      materialData = packetData.polylineArrow;
      processPacketData(
        Color,
        existingMaterial,
        "color",
        materialData.color,
        undefined,
        undefined,
        entityCollection
      );
    } else if (defined(packetData.polylineDash)) {
      if (!(existingMaterial instanceof PolylineDashMaterialProperty)) {
        existingMaterial = new PolylineDashMaterialProperty();
      }
      materialData = packetData.polylineDash;
      processPacketData(
        Color,
        existingMaterial,
        "color",
        materialData.color,
        undefined,
        undefined,
        entityCollection
      );
      processPacketData(
        Color,
        existingMaterial,
        "gapColor",
        materialData.gapColor,
        undefined,
        undefined,
        entityCollection
      );
      processPacketData(
        Number,
        existingMaterial,
        "dashLength",
        materialData.dashLength,
        undefined,
        sourceUri,
        entityCollection
      );
      processPacketData(
        Number,
        existingMaterial,
        "dashPattern",
        materialData.dashPattern,
        undefined,
        sourceUri,
        entityCollection
      );
    } else if (defined(packetData.checkerboard)) {
      if (!(existingMaterial instanceof CheckerboardMaterialProperty)) {
        existingMaterial = new CheckerboardMaterialProperty();
      }
      materialData = packetData.checkerboard;
      processPacketData(
        Color,
        existingMaterial,
        "evenColor",
        materialData.evenColor,
        undefined,
        sourceUri,
        entityCollection
      );
      processPacketData(
        Color,
        existingMaterial,
        "oddColor",
        materialData.oddColor,
        undefined,
        sourceUri,
        entityCollection
      );
      processPacketData(
        Cartesian2,
        existingMaterial,
        "repeat",
        materialData.repeat,
        undefined,
        sourceUri,
        entityCollection
      );
    }

    if (defined(existingInterval)) {
      existingInterval.data = existingMaterial;
    } else {
      object[propertyName] = existingMaterial;
    }
  }

  function processMaterialPacketData(
    object,
    propertyName,
    packetData,
    interval,
    sourceUri,
    entityCollection
  ) {
    if (!defined(packetData)) {
      return;
    }

    if (Array.isArray(packetData)) {
      for (let i = 0, len = packetData.length; i < len; ++i) {
        processMaterialProperty(
          object,
          propertyName,
          packetData[i],
          interval,
          sourceUri,
          entityCollection
        );
      }
    } else {
      processMaterialProperty(
        object,
        propertyName,
        packetData,
        interval,
        sourceUri,
        entityCollection
      );
    }
  }

  function processName(entity, packet, entityCollection, sourceUri) {
    const nameData = packet.name;
    if (defined(nameData)) {
      entity.name = packet.name;
    }
  }

  function processDescription$2(entity, packet, entityCollection, sourceUri) {
    const descriptionData = packet.description;
    if (defined(descriptionData)) {
      processPacketData(
        String,
        entity,
        "description",
        descriptionData,
        undefined,
        sourceUri,
        entityCollection
      );
    }
  }

  function processPosition(entity, packet, entityCollection, sourceUri) {
    const positionData = packet.position;
    if (defined(positionData)) {
      processPositionPacketData(
        entity,
        "position",
        positionData,
        undefined,
        sourceUri,
        entityCollection
      );
    }
  }

  function processViewFrom(entity, packet, entityCollection, sourceUri) {
    const viewFromData = packet.viewFrom;
    if (defined(viewFromData)) {
      processPacketData(
        Cartesian3,
        entity,
        "viewFrom",
        viewFromData,
        undefined,
        sourceUri,
        entityCollection
      );
    }
  }

  function processOrientation(entity, packet, entityCollection, sourceUri) {
    const orientationData = packet.orientation;
    if (defined(orientationData)) {
      processPacketData(
        Quaternion,
        entity,
        "orientation",
        orientationData,
        undefined,
        sourceUri,
        entityCollection
      );
    }
  }

  function processProperties(entity, packet, entityCollection, sourceUri) {
    const propertiesData = packet.properties;
    if (defined(propertiesData)) {
      if (!defined(entity.properties)) {
        entity.properties = new PropertyBag();
      }

      // We cannot simply call processPacketData(entity, 'properties', propertyData, undefined, sourceUri, entityCollection)
      // because each property of "properties" may vary separately.
      // The properties will be accessible as entity.properties.myprop.getValue(time).

      for (const key in propertiesData) {
        if (propertiesData.hasOwnProperty(key)) {
          if (!entity.properties.hasProperty(key)) {
            entity.properties.addProperty(key);
          }

          const propertyData = propertiesData[key];
          if (Array.isArray(propertyData)) {
            for (let i = 0, len = propertyData.length; i < len; ++i) {
              processProperty(
                getPropertyType(propertyData[i]),
                entity.properties,
                key,
                propertyData[i],
                undefined,
                sourceUri,
                entityCollection
              );
            }
          } else {
            processProperty(
              getPropertyType(propertyData),
              entity.properties,
              key,
              propertyData,
              undefined,
              sourceUri,
              entityCollection
            );
          }
        }
      }
    }
  }

  function processReferencesArrayPacketData(
    object,
    propertyName,
    references,
    interval,
    entityCollection,
    PropertyArrayType,
    CompositePropertyArrayType
  ) {
    const properties = references.map(function (reference) {
      return createReferenceProperty(entityCollection, reference);
    });

    if (defined(interval)) {
      interval = intervalFromString(interval);
      let property = object[propertyName];
      if (!(property instanceof CompositePropertyArrayType)) {
        // If the property was not already a CompositeProperty,
        // create a CompositeProperty but preserve the existing data.

        // Create the composite and add the old property, wrapped in an infinite interval.
        const composite = new CompositePropertyArrayType();
        composite.intervals.addInterval(wrapPropertyInInfiniteInterval(property));

        object[propertyName] = property = composite;
      }

      interval.data = new PropertyArrayType(properties);
      property.intervals.addInterval(interval);
    } else {
      object[propertyName] = new PropertyArrayType(properties);
    }
  }

  function processArrayPacketData(
    object,
    propertyName,
    packetData,
    entityCollection
  ) {
    const references = packetData.references;
    if (defined(references)) {
      processReferencesArrayPacketData(
        object,
        propertyName,
        references,
        packetData.interval,
        entityCollection,
        PropertyArray,
        CompositeProperty
      );
    } else {
      processPacketData(
        Array,
        object,
        propertyName,
        packetData,
        undefined,
        undefined,
        entityCollection
      );
    }
  }

  function processArray(object, propertyName, packetData, entityCollection) {
    if (!defined(packetData)) {
      return;
    }

    if (Array.isArray(packetData)) {
      for (let i = 0, length = packetData.length; i < length; ++i) {
        processArrayPacketData(
          object,
          propertyName,
          packetData[i],
          entityCollection
        );
      }
    } else {
      processArrayPacketData(object, propertyName, packetData, entityCollection);
    }
  }

  function processPositionArrayPacketData(
    object,
    propertyName,
    packetData,
    entityCollection
  ) {
    const references = packetData.references;
    if (defined(references)) {
      processReferencesArrayPacketData(
        object,
        propertyName,
        references,
        packetData.interval,
        entityCollection,
        PositionPropertyArray,
        CompositePositionProperty
      );
    } else {
      if (defined(packetData.cartesian)) {
        packetData.array = Cartesian3.unpackArray(packetData.cartesian);
      } else if (defined(packetData.cartographicRadians)) {
        packetData.array = Cartesian3.fromRadiansArrayHeights(
          packetData.cartographicRadians
        );
      } else if (defined(packetData.cartographicDegrees)) {
        packetData.array = Cartesian3.fromDegreesArrayHeights(
          packetData.cartographicDegrees
        );
      }

      if (defined(packetData.array)) {
        processPacketData(
          Array,
          object,
          propertyName,
          packetData,
          undefined,
          undefined,
          entityCollection
        );
      }
    }
  }

  function processPositionArray(
    object,
    propertyName,
    packetData,
    entityCollection
  ) {
    if (!defined(packetData)) {
      return;
    }

    if (Array.isArray(packetData)) {
      for (let i = 0, length = packetData.length; i < length; ++i) {
        processPositionArrayPacketData(
          object,
          propertyName,
          packetData[i],
          entityCollection
        );
      }
    } else {
      processPositionArrayPacketData(
        object,
        propertyName,
        packetData,
        entityCollection
      );
    }
  }

  function unpackCartesianArray(array) {
    return Cartesian3.unpackArray(array);
  }

  function unpackCartographicRadiansArray(array) {
    return Cartesian3.fromRadiansArrayHeights(array);
  }

  function unpackCartographicDegreesArray(array) {
    return Cartesian3.fromDegreesArrayHeights(array);
  }

  function processPositionArrayOfArraysPacketData(
    object,
    propertyName,
    packetData,
    entityCollection
  ) {
    const references = packetData.references;
    if (defined(references)) {
      const properties = references.map(function (referenceArray) {
        const tempObj = {};
        processReferencesArrayPacketData(
          tempObj,
          "positions",
          referenceArray,
          packetData.interval,
          entityCollection,
          PositionPropertyArray,
          CompositePositionProperty
        );
        return tempObj.positions;
      });
      object[propertyName] = new PositionPropertyArray(properties);
    } else {
      if (defined(packetData.cartesian)) {
        packetData.array = packetData.cartesian.map(unpackCartesianArray);
      } else if (defined(packetData.cartographicRadians)) {
        packetData.array = packetData.cartographicRadians.map(
          unpackCartographicRadiansArray
        );
      } else if (defined(packetData.cartographicDegrees)) {
        packetData.array = packetData.cartographicDegrees.map(
          unpackCartographicDegreesArray
        );
      }

      if (defined(packetData.array)) {
        processPacketData(
          Array,
          object,
          propertyName,
          packetData,
          undefined,
          undefined,
          entityCollection
        );
      }
    }
  }

  function processPositionArrayOfArrays(
    object,
    propertyName,
    packetData,
    entityCollection
  ) {
    if (!defined(packetData)) {
      return;
    }

    if (Array.isArray(packetData)) {
      for (let i = 0, length = packetData.length; i < length; ++i) {
        processPositionArrayOfArraysPacketData(
          object,
          propertyName,
          packetData[i],
          entityCollection
        );
      }
    } else {
      processPositionArrayOfArraysPacketData(
        object,
        propertyName,
        packetData,
        entityCollection
      );
    }
  }

  function processShape(object, propertyName, packetData, entityCollection) {
    if (!defined(packetData)) {
      return;
    }

    if (Array.isArray(packetData)) {
      for (let i = 0, length = packetData.length; i < length; i++) {
        processShapePacketData(
          object,
          propertyName,
          packetData[i],
          entityCollection
        );
      }
    } else {
      processShapePacketData(object, propertyName, packetData, entityCollection);
    }
  }

  function processAvailability(entity, packet, entityCollection, sourceUri) {
    const packetData = packet.availability;
    if (!defined(packetData)) {
      return;
    }

    let intervals;
    if (Array.isArray(packetData)) {
      for (let i = 0, len = packetData.length; i < len; ++i) {
        if (!defined(intervals)) {
          intervals = new TimeIntervalCollection();
        }
        intervals.addInterval(intervalFromString(packetData[i]));
      }
    } else {
      intervals = new TimeIntervalCollection();
      intervals.addInterval(intervalFromString(packetData));
    }
    entity.availability = intervals;
  }

  function processAlignedAxis(
    billboard,
    packetData,
    interval,
    sourceUri,
    entityCollection
  ) {
    if (!defined(packetData)) {
      return;
    }

    processPacketData(
      UnitCartesian3,
      billboard,
      "alignedAxis",
      packetData,
      interval,
      sourceUri,
      entityCollection
    );
  }

  function processBillboard(entity, packet, entityCollection, sourceUri) {
    const billboardData = packet.billboard;
    if (!defined(billboardData)) {
      return;
    }

    const interval = intervalFromString(billboardData.interval);
    let billboard = entity.billboard;
    if (!defined(billboard)) {
      entity.billboard = billboard = new BillboardGraphics();
    }

    processPacketData(
      Boolean,
      billboard,
      "show",
      billboardData.show,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Image,
      billboard,
      "image",
      billboardData.image,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      billboard,
      "scale",
      billboardData.scale,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Cartesian2,
      billboard,
      "pixelOffset",
      billboardData.pixelOffset,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Cartesian3,
      billboard,
      "eyeOffset",
      billboardData.eyeOffset,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      HorizontalOrigin$1,
      billboard,
      "horizontalOrigin",
      billboardData.horizontalOrigin,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      VerticalOrigin$1,
      billboard,
      "verticalOrigin",
      billboardData.verticalOrigin,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      HeightReference$1,
      billboard,
      "heightReference",
      billboardData.heightReference,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Color,
      billboard,
      "color",
      billboardData.color,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Rotation,
      billboard,
      "rotation",
      billboardData.rotation,
      interval,
      sourceUri,
      entityCollection
    );
    processAlignedAxis(
      billboard,
      billboardData.alignedAxis,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Boolean,
      billboard,
      "sizeInMeters",
      billboardData.sizeInMeters,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      billboard,
      "width",
      billboardData.width,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      billboard,
      "height",
      billboardData.height,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      NearFarScalar,
      billboard,
      "scaleByDistance",
      billboardData.scaleByDistance,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      NearFarScalar,
      billboard,
      "translucencyByDistance",
      billboardData.translucencyByDistance,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      NearFarScalar,
      billboard,
      "pixelOffsetScaleByDistance",
      billboardData.pixelOffsetScaleByDistance,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      BoundingRectangle,
      billboard,
      "imageSubRegion",
      billboardData.imageSubRegion,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      DistanceDisplayCondition,
      billboard,
      "distanceDisplayCondition",
      billboardData.distanceDisplayCondition,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      billboard,
      "disableDepthTestDistance",
      billboardData.disableDepthTestDistance,
      interval,
      sourceUri,
      entityCollection
    );
  }

  function processBox(entity, packet, entityCollection, sourceUri) {
    const boxData = packet.box;
    if (!defined(boxData)) {
      return;
    }

    const interval = intervalFromString(boxData.interval);
    let box = entity.box;
    if (!defined(box)) {
      entity.box = box = new BoxGraphics();
    }

    processPacketData(
      Boolean,
      box,
      "show",
      boxData.show,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Cartesian3,
      box,
      "dimensions",
      boxData.dimensions,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      HeightReference$1,
      box,
      "heightReference",
      boxData.heightReference,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Boolean,
      box,
      "fill",
      boxData.fill,
      interval,
      sourceUri,
      entityCollection
    );
    processMaterialPacketData(
      box,
      "material",
      boxData.material,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Boolean,
      box,
      "outline",
      boxData.outline,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Color,
      box,
      "outlineColor",
      boxData.outlineColor,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      box,
      "outlineWidth",
      boxData.outlineWidth,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      ShadowMode$1,
      box,
      "shadows",
      boxData.shadows,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      DistanceDisplayCondition,
      box,
      "distanceDisplayCondition",
      boxData.distanceDisplayCondition,
      interval,
      sourceUri,
      entityCollection
    );
  }

  function processCorridor(entity, packet, entityCollection, sourceUri) {
    const corridorData = packet.corridor;
    if (!defined(corridorData)) {
      return;
    }

    const interval = intervalFromString(corridorData.interval);
    let corridor = entity.corridor;
    if (!defined(corridor)) {
      entity.corridor = corridor = new CorridorGraphics();
    }

    processPacketData(
      Boolean,
      corridor,
      "show",
      corridorData.show,
      interval,
      sourceUri,
      entityCollection
    );
    processPositionArray(
      corridor,
      "positions",
      corridorData.positions,
      entityCollection
    );
    processPacketData(
      Number,
      corridor,
      "width",
      corridorData.width,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      corridor,
      "height",
      corridorData.height,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      HeightReference$1,
      corridor,
      "heightReference",
      corridorData.heightReference,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      corridor,
      "extrudedHeight",
      corridorData.extrudedHeight,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      HeightReference$1,
      corridor,
      "extrudedHeightReference",
      corridorData.extrudedHeightReference,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      CornerType$1,
      corridor,
      "cornerType",
      corridorData.cornerType,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      corridor,
      "granularity",
      corridorData.granularity,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Boolean,
      corridor,
      "fill",
      corridorData.fill,
      interval,
      sourceUri,
      entityCollection
    );
    processMaterialPacketData(
      corridor,
      "material",
      corridorData.material,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Boolean,
      corridor,
      "outline",
      corridorData.outline,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Color,
      corridor,
      "outlineColor",
      corridorData.outlineColor,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      corridor,
      "outlineWidth",
      corridorData.outlineWidth,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      ShadowMode$1,
      corridor,
      "shadows",
      corridorData.shadows,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      DistanceDisplayCondition,
      corridor,
      "distanceDisplayCondition",
      corridorData.distanceDisplayCondition,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      ClassificationType$1,
      corridor,
      "classificationType",
      corridorData.classificationType,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      corridor,
      "zIndex",
      corridorData.zIndex,
      interval,
      sourceUri,
      entityCollection
    );
  }

  function processCylinder(entity, packet, entityCollection, sourceUri) {
    const cylinderData = packet.cylinder;
    if (!defined(cylinderData)) {
      return;
    }

    const interval = intervalFromString(cylinderData.interval);
    let cylinder = entity.cylinder;
    if (!defined(cylinder)) {
      entity.cylinder = cylinder = new CylinderGraphics();
    }

    processPacketData(
      Boolean,
      cylinder,
      "show",
      cylinderData.show,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      cylinder,
      "length",
      cylinderData.length,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      cylinder,
      "topRadius",
      cylinderData.topRadius,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      cylinder,
      "bottomRadius",
      cylinderData.bottomRadius,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      HeightReference$1,
      cylinder,
      "heightReference",
      cylinderData.heightReference,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Boolean,
      cylinder,
      "fill",
      cylinderData.fill,
      interval,
      sourceUri,
      entityCollection
    );
    processMaterialPacketData(
      cylinder,
      "material",
      cylinderData.material,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Boolean,
      cylinder,
      "outline",
      cylinderData.outline,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Color,
      cylinder,
      "outlineColor",
      cylinderData.outlineColor,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      cylinder,
      "outlineWidth",
      cylinderData.outlineWidth,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      cylinder,
      "numberOfVerticalLines",
      cylinderData.numberOfVerticalLines,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      cylinder,
      "slices",
      cylinderData.slices,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      ShadowMode$1,
      cylinder,
      "shadows",
      cylinderData.shadows,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      DistanceDisplayCondition,
      cylinder,
      "distanceDisplayCondition",
      cylinderData.distanceDisplayCondition,
      interval,
      sourceUri,
      entityCollection
    );
  }

  function processDocument$1(packet, dataSource) {
    const version = packet.version;
    if (defined(version)) {
      if (typeof version === "string") {
        const tokens = version.split(".");
        if (tokens.length === 2) {
          if (tokens[0] !== "1") {
            throw new RuntimeError("Cesium only supports CZML version 1.");
          }
          dataSource._version = version;
        }
      }
    }

    if (!defined(dataSource._version)) {
      throw new RuntimeError(
        "CZML version information invalid.  It is expected to be a property on the document object in the <Major>.<Minor> version format."
      );
    }

    const documentPacket = dataSource._documentPacket;

    if (defined(packet.name)) {
      documentPacket.name = packet.name;
    }

    const clockPacket = packet.clock;
    if (defined(clockPacket)) {
      const clock = documentPacket.clock;
      if (!defined(clock)) {
        documentPacket.clock = {
          interval: clockPacket.interval,
          currentTime: clockPacket.currentTime,
          range: clockPacket.range,
          step: clockPacket.step,
          multiplier: clockPacket.multiplier,
        };
      } else {
        clock.interval = defaultValue(clockPacket.interval, clock.interval);
        clock.currentTime = defaultValue(
          clockPacket.currentTime,
          clock.currentTime
        );
        clock.range = defaultValue(clockPacket.range, clock.range);
        clock.step = defaultValue(clockPacket.step, clock.step);
        clock.multiplier = defaultValue(clockPacket.multiplier, clock.multiplier);
      }
    }
  }

  function processEllipse(entity, packet, entityCollection, sourceUri) {
    const ellipseData = packet.ellipse;
    if (!defined(ellipseData)) {
      return;
    }

    const interval = intervalFromString(ellipseData.interval);
    let ellipse = entity.ellipse;
    if (!defined(ellipse)) {
      entity.ellipse = ellipse = new EllipseGraphics();
    }

    processPacketData(
      Boolean,
      ellipse,
      "show",
      ellipseData.show,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      ellipse,
      "semiMajorAxis",
      ellipseData.semiMajorAxis,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      ellipse,
      "semiMinorAxis",
      ellipseData.semiMinorAxis,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      ellipse,
      "height",
      ellipseData.height,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      HeightReference$1,
      ellipse,
      "heightReference",
      ellipseData.heightReference,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      ellipse,
      "extrudedHeight",
      ellipseData.extrudedHeight,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      HeightReference$1,
      ellipse,
      "extrudedHeightReference",
      ellipseData.extrudedHeightReference,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Rotation,
      ellipse,
      "rotation",
      ellipseData.rotation,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Rotation,
      ellipse,
      "stRotation",
      ellipseData.stRotation,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      ellipse,
      "granularity",
      ellipseData.granularity,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Boolean,
      ellipse,
      "fill",
      ellipseData.fill,
      interval,
      sourceUri,
      entityCollection
    );
    processMaterialPacketData(
      ellipse,
      "material",
      ellipseData.material,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Boolean,
      ellipse,
      "outline",
      ellipseData.outline,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Color,
      ellipse,
      "outlineColor",
      ellipseData.outlineColor,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      ellipse,
      "outlineWidth",
      ellipseData.outlineWidth,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      ellipse,
      "numberOfVerticalLines",
      ellipseData.numberOfVerticalLines,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      ShadowMode$1,
      ellipse,
      "shadows",
      ellipseData.shadows,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      DistanceDisplayCondition,
      ellipse,
      "distanceDisplayCondition",
      ellipseData.distanceDisplayCondition,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      ClassificationType$1,
      ellipse,
      "classificationType",
      ellipseData.classificationType,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      ellipse,
      "zIndex",
      ellipseData.zIndex,
      interval,
      sourceUri,
      entityCollection
    );
  }

  function processEllipsoid(entity, packet, entityCollection, sourceUri) {
    const ellipsoidData = packet.ellipsoid;
    if (!defined(ellipsoidData)) {
      return;
    }

    const interval = intervalFromString(ellipsoidData.interval);
    let ellipsoid = entity.ellipsoid;
    if (!defined(ellipsoid)) {
      entity.ellipsoid = ellipsoid = new EllipsoidGraphics();
    }

    processPacketData(
      Boolean,
      ellipsoid,
      "show",
      ellipsoidData.show,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Cartesian3,
      ellipsoid,
      "radii",
      ellipsoidData.radii,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Cartesian3,
      ellipsoid,
      "innerRadii",
      ellipsoidData.innerRadii,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      ellipsoid,
      "minimumClock",
      ellipsoidData.minimumClock,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      ellipsoid,
      "maximumClock",
      ellipsoidData.maximumClock,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      ellipsoid,
      "minimumCone",
      ellipsoidData.minimumCone,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      ellipsoid,
      "maximumCone",
      ellipsoidData.maximumCone,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      HeightReference$1,
      ellipsoid,
      "heightReference",
      ellipsoidData.heightReference,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Boolean,
      ellipsoid,
      "fill",
      ellipsoidData.fill,
      interval,
      sourceUri,
      entityCollection
    );
    processMaterialPacketData(
      ellipsoid,
      "material",
      ellipsoidData.material,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Boolean,
      ellipsoid,
      "outline",
      ellipsoidData.outline,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Color,
      ellipsoid,
      "outlineColor",
      ellipsoidData.outlineColor,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      ellipsoid,
      "outlineWidth",
      ellipsoidData.outlineWidth,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      ellipsoid,
      "stackPartitions",
      ellipsoidData.stackPartitions,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      ellipsoid,
      "slicePartitions",
      ellipsoidData.slicePartitions,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      ellipsoid,
      "subdivisions",
      ellipsoidData.subdivisions,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      ShadowMode$1,
      ellipsoid,
      "shadows",
      ellipsoidData.shadows,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      DistanceDisplayCondition,
      ellipsoid,
      "distanceDisplayCondition",
      ellipsoidData.distanceDisplayCondition,
      interval,
      sourceUri,
      entityCollection
    );
  }

  function processLabel(entity, packet, entityCollection, sourceUri) {
    const labelData = packet.label;
    if (!defined(labelData)) {
      return;
    }

    const interval = intervalFromString(labelData.interval);
    let label = entity.label;
    if (!defined(label)) {
      entity.label = label = new LabelGraphics();
    }

    processPacketData(
      Boolean,
      label,
      "show",
      labelData.show,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      String,
      label,
      "text",
      labelData.text,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      String,
      label,
      "font",
      labelData.font,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      LabelStyle$1,
      label,
      "style",
      labelData.style,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      label,
      "scale",
      labelData.scale,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Boolean,
      label,
      "showBackground",
      labelData.showBackground,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Color,
      label,
      "backgroundColor",
      labelData.backgroundColor,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Cartesian2,
      label,
      "backgroundPadding",
      labelData.backgroundPadding,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Cartesian2,
      label,
      "pixelOffset",
      labelData.pixelOffset,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Cartesian3,
      label,
      "eyeOffset",
      labelData.eyeOffset,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      HorizontalOrigin$1,
      label,
      "horizontalOrigin",
      labelData.horizontalOrigin,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      VerticalOrigin$1,
      label,
      "verticalOrigin",
      labelData.verticalOrigin,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      HeightReference$1,
      label,
      "heightReference",
      labelData.heightReference,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Color,
      label,
      "fillColor",
      labelData.fillColor,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Color,
      label,
      "outlineColor",
      labelData.outlineColor,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      label,
      "outlineWidth",
      labelData.outlineWidth,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      NearFarScalar,
      label,
      "translucencyByDistance",
      labelData.translucencyByDistance,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      NearFarScalar,
      label,
      "pixelOffsetScaleByDistance",
      labelData.pixelOffsetScaleByDistance,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      NearFarScalar,
      label,
      "scaleByDistance",
      labelData.scaleByDistance,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      DistanceDisplayCondition,
      label,
      "distanceDisplayCondition",
      labelData.distanceDisplayCondition,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      label,
      "disableDepthTestDistance",
      labelData.disableDepthTestDistance,
      interval,
      sourceUri,
      entityCollection
    );
  }

  function processModel(entity, packet, entityCollection, sourceUri) {
    const modelData = packet.model;
    if (!defined(modelData)) {
      return;
    }

    const interval = intervalFromString(modelData.interval);
    let model = entity.model;
    if (!defined(model)) {
      entity.model = model = new ModelGraphics();
    }

    processPacketData(
      Boolean,
      model,
      "show",
      modelData.show,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      URI,
      model,
      "uri",
      modelData.gltf,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      model,
      "scale",
      modelData.scale,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      model,
      "minimumPixelSize",
      modelData.minimumPixelSize,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      model,
      "maximumScale",
      modelData.maximumScale,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Boolean,
      model,
      "incrementallyLoadTextures",
      modelData.incrementallyLoadTextures,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Boolean,
      model,
      "runAnimations",
      modelData.runAnimations,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Boolean,
      model,
      "clampAnimations",
      modelData.clampAnimations,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      ShadowMode$1,
      model,
      "shadows",
      modelData.shadows,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      HeightReference$1,
      model,
      "heightReference",
      modelData.heightReference,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Color,
      model,
      "silhouetteColor",
      modelData.silhouetteColor,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      model,
      "silhouetteSize",
      modelData.silhouetteSize,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Color,
      model,
      "color",
      modelData.color,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      ColorBlendMode$1,
      model,
      "colorBlendMode",
      modelData.colorBlendMode,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      model,
      "colorBlendAmount",
      modelData.colorBlendAmount,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      DistanceDisplayCondition,
      model,
      "distanceDisplayCondition",
      modelData.distanceDisplayCondition,
      interval,
      sourceUri,
      entityCollection
    );

    let i, len;
    const nodeTransformationsData = modelData.nodeTransformations;
    if (defined(nodeTransformationsData)) {
      if (Array.isArray(nodeTransformationsData)) {
        for (i = 0, len = nodeTransformationsData.length; i < len; ++i) {
          processNodeTransformations(
            model,
            nodeTransformationsData[i],
            interval,
            sourceUri,
            entityCollection
          );
        }
      } else {
        processNodeTransformations(
          model,
          nodeTransformationsData,
          interval,
          sourceUri,
          entityCollection
        );
      }
    }

    const articulationsData = modelData.articulations;
    if (defined(articulationsData)) {
      if (Array.isArray(articulationsData)) {
        for (i = 0, len = articulationsData.length; i < len; ++i) {
          processArticulations(
            model,
            articulationsData[i],
            interval,
            sourceUri,
            entityCollection
          );
        }
      } else {
        processArticulations(
          model,
          articulationsData,
          interval,
          sourceUri,
          entityCollection
        );
      }
    }
  }

  function processNodeTransformations(
    model,
    nodeTransformationsData,
    constrainedInterval,
    sourceUri,
    entityCollection
  ) {
    let combinedInterval = intervalFromString(nodeTransformationsData.interval);
    if (defined(constrainedInterval)) {
      if (defined(combinedInterval)) {
        combinedInterval = TimeInterval.intersect(
          combinedInterval,
          constrainedInterval,
          scratchTimeInterval$1
        );
      } else {
        combinedInterval = constrainedInterval;
      }
    }

    let nodeTransformations = model.nodeTransformations;
    const nodeNames = Object.keys(nodeTransformationsData);
    for (let i = 0, len = nodeNames.length; i < len; ++i) {
      const nodeName = nodeNames[i];
      if (nodeName === "interval") {
        continue;
      }

      const nodeTransformationData = nodeTransformationsData[nodeName];
      if (!defined(nodeTransformationData)) {
        continue;
      }

      if (!defined(nodeTransformations)) {
        model.nodeTransformations = nodeTransformations = new PropertyBag();
      }

      if (!nodeTransformations.hasProperty(nodeName)) {
        nodeTransformations.addProperty(nodeName);
      }

      let nodeTransformation = nodeTransformations[nodeName];
      if (!defined(nodeTransformation)) {
        nodeTransformations[
          nodeName
        ] = nodeTransformation = new NodeTransformationProperty();
      }

      processPacketData(
        Cartesian3,
        nodeTransformation,
        "translation",
        nodeTransformationData.translation,
        combinedInterval,
        sourceUri,
        entityCollection
      );
      processPacketData(
        Quaternion,
        nodeTransformation,
        "rotation",
        nodeTransformationData.rotation,
        combinedInterval,
        sourceUri,
        entityCollection
      );
      processPacketData(
        Cartesian3,
        nodeTransformation,
        "scale",
        nodeTransformationData.scale,
        combinedInterval,
        sourceUri,
        entityCollection
      );
    }
  }

  function processArticulations(
    model,
    articulationsData,
    constrainedInterval,
    sourceUri,
    entityCollection
  ) {
    let combinedInterval = intervalFromString(articulationsData.interval);
    if (defined(constrainedInterval)) {
      if (defined(combinedInterval)) {
        combinedInterval = TimeInterval.intersect(
          combinedInterval,
          constrainedInterval,
          scratchTimeInterval$1
        );
      } else {
        combinedInterval = constrainedInterval;
      }
    }

    let articulations = model.articulations;
    const keys = Object.keys(articulationsData);
    for (let i = 0, len = keys.length; i < len; ++i) {
      const key = keys[i];
      if (key === "interval") {
        continue;
      }

      const articulationStageData = articulationsData[key];
      if (!defined(articulationStageData)) {
        continue;
      }

      if (!defined(articulations)) {
        model.articulations = articulations = new PropertyBag();
      }

      if (!articulations.hasProperty(key)) {
        articulations.addProperty(key);
      }

      processPacketData(
        Number,
        articulations,
        key,
        articulationStageData,
        combinedInterval,
        sourceUri,
        entityCollection
      );
    }
  }

  function processPath(entity, packet, entityCollection, sourceUri) {
    const pathData = packet.path;
    if (!defined(pathData)) {
      return;
    }

    const interval = intervalFromString(pathData.interval);
    let path = entity.path;
    if (!defined(path)) {
      entity.path = path = new PathGraphics();
    }

    processPacketData(
      Boolean,
      path,
      "show",
      pathData.show,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      path,
      "leadTime",
      pathData.leadTime,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      path,
      "trailTime",
      pathData.trailTime,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      path,
      "width",
      pathData.width,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      path,
      "resolution",
      pathData.resolution,
      interval,
      sourceUri,
      entityCollection
    );
    processMaterialPacketData(
      path,
      "material",
      pathData.material,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      DistanceDisplayCondition,
      path,
      "distanceDisplayCondition",
      pathData.distanceDisplayCondition,
      interval,
      sourceUri,
      entityCollection
    );
  }

  function processPoint$2(entity, packet, entityCollection, sourceUri) {
    const pointData = packet.point;
    if (!defined(pointData)) {
      return;
    }

    const interval = intervalFromString(pointData.interval);
    let point = entity.point;
    if (!defined(point)) {
      entity.point = point = new PointGraphics();
    }

    processPacketData(
      Boolean,
      point,
      "show",
      pointData.show,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      point,
      "pixelSize",
      pointData.pixelSize,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      HeightReference$1,
      point,
      "heightReference",
      pointData.heightReference,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Color,
      point,
      "color",
      pointData.color,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Color,
      point,
      "outlineColor",
      pointData.outlineColor,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      point,
      "outlineWidth",
      pointData.outlineWidth,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      NearFarScalar,
      point,
      "scaleByDistance",
      pointData.scaleByDistance,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      NearFarScalar,
      point,
      "translucencyByDistance",
      pointData.translucencyByDistance,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      DistanceDisplayCondition,
      point,
      "distanceDisplayCondition",
      pointData.distanceDisplayCondition,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      point,
      "disableDepthTestDistance",
      pointData.disableDepthTestDistance,
      interval,
      sourceUri,
      entityCollection
    );
  }

  function PolygonHierarchyProperty(polygon) {
    this.polygon = polygon;
    this._definitionChanged = new Event();
  }

  Object.defineProperties(PolygonHierarchyProperty.prototype, {
    isConstant: {
      get: function () {
        const positions = this.polygon._positions;
        const holes = this.polygon._holes;
        return (
          (!defined(positions) || positions.isConstant) &&
          (!defined(holes) || holes.isConstant)
        );
      },
    },
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },
  });

  PolygonHierarchyProperty.prototype.getValue = function (time, result) {
    let positions;
    if (defined(this.polygon._positions)) {
      positions = this.polygon._positions.getValue(time);
    }

    let holes;
    if (defined(this.polygon._holes)) {
      holes = this.polygon._holes.getValue(time);
      if (defined(holes)) {
        holes = holes.map(function (holePositions) {
          return new PolygonHierarchy(holePositions);
        });
      }
    }

    if (!defined(result)) {
      return new PolygonHierarchy(positions, holes);
    }

    result.positions = positions;
    result.holes = holes;
    return result;
  };

  PolygonHierarchyProperty.prototype.equals = function (other) {
    return (
      this === other ||
      (other instanceof PolygonHierarchyProperty &&
        Property.equals(this.polygon._positions, other.polygon._positions) &&
        Property.equals(this.polygon._holes, other.polygon._holes))
    );
  };

  function processPolygon$2(entity, packet, entityCollection, sourceUri) {
    const polygonData = packet.polygon;
    if (!defined(polygonData)) {
      return;
    }

    const interval = intervalFromString(polygonData.interval);
    let polygon = entity.polygon;
    if (!defined(polygon)) {
      entity.polygon = polygon = new PolygonGraphics();
    }

    processPacketData(
      Boolean,
      polygon,
      "show",
      polygonData.show,
      interval,
      sourceUri,
      entityCollection
    );

    // adapt 'position' property producing Cartesian[]
    // and 'holes' property producing Cartesian[][]
    // to a single property producing PolygonHierarchy
    processPositionArray(
      polygon,
      "_positions",
      polygonData.positions,
      entityCollection
    );
    processPositionArrayOfArrays(
      polygon,
      "_holes",
      polygonData.holes,
      entityCollection
    );
    if (defined(polygon._positions) || defined(polygon._holes)) {
      polygon.hierarchy = new PolygonHierarchyProperty(polygon);
    }

    processPacketData(
      Number,
      polygon,
      "height",
      polygonData.height,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      HeightReference$1,
      polygon,
      "heightReference",
      polygonData.heightReference,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      polygon,
      "extrudedHeight",
      polygonData.extrudedHeight,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      HeightReference$1,
      polygon,
      "extrudedHeightReference",
      polygonData.extrudedHeightReference,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Rotation,
      polygon,
      "stRotation",
      polygonData.stRotation,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      polygon,
      "granularity",
      polygonData.granularity,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Boolean,
      polygon,
      "fill",
      polygonData.fill,
      interval,
      sourceUri,
      entityCollection
    );
    processMaterialPacketData(
      polygon,
      "material",
      polygonData.material,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Boolean,
      polygon,
      "outline",
      polygonData.outline,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Color,
      polygon,
      "outlineColor",
      polygonData.outlineColor,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      polygon,
      "outlineWidth",
      polygonData.outlineWidth,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Boolean,
      polygon,
      "perPositionHeight",
      polygonData.perPositionHeight,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Boolean,
      polygon,
      "closeTop",
      polygonData.closeTop,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Boolean,
      polygon,
      "closeBottom",
      polygonData.closeBottom,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      ArcType$1,
      polygon,
      "arcType",
      polygonData.arcType,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      ShadowMode$1,
      polygon,
      "shadows",
      polygonData.shadows,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      DistanceDisplayCondition,
      polygon,
      "distanceDisplayCondition",
      polygonData.distanceDisplayCondition,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      ClassificationType$1,
      polygon,
      "classificationType",
      polygonData.classificationType,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      polygon,
      "zIndex",
      polygonData.zIndex,
      interval,
      sourceUri,
      entityCollection
    );
  }

  function adaptFollowSurfaceToArcType(followSurface) {
    return followSurface ? ArcType$1.GEODESIC : ArcType$1.NONE;
  }

  function processPolyline(entity, packet, entityCollection, sourceUri) {
    const polylineData = packet.polyline;
    if (!defined(polylineData)) {
      return;
    }

    const interval = intervalFromString(polylineData.interval);
    let polyline = entity.polyline;
    if (!defined(polyline)) {
      entity.polyline = polyline = new PolylineGraphics();
    }

    processPacketData(
      Boolean,
      polyline,
      "show",
      polylineData.show,
      interval,
      sourceUri,
      entityCollection
    );
    processPositionArray(
      polyline,
      "positions",
      polylineData.positions,
      entityCollection
    );
    processPacketData(
      Number,
      polyline,
      "width",
      polylineData.width,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      polyline,
      "granularity",
      polylineData.granularity,
      interval,
      sourceUri,
      entityCollection
    );
    processMaterialPacketData(
      polyline,
      "material",
      polylineData.material,
      interval,
      sourceUri,
      entityCollection
    );
    processMaterialPacketData(
      polyline,
      "depthFailMaterial",
      polylineData.depthFailMaterial,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      ArcType$1,
      polyline,
      "arcType",
      polylineData.arcType,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Boolean,
      polyline,
      "clampToGround",
      polylineData.clampToGround,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      ShadowMode$1,
      polyline,
      "shadows",
      polylineData.shadows,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      DistanceDisplayCondition,
      polyline,
      "distanceDisplayCondition",
      polylineData.distanceDisplayCondition,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      ClassificationType$1,
      polyline,
      "classificationType",
      polylineData.classificationType,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      polyline,
      "zIndex",
      polylineData.zIndex,
      interval,
      sourceUri,
      entityCollection
    );

    // for backwards compatibility, adapt CZML followSurface to arcType.
    if (defined(polylineData.followSurface) && !defined(polylineData.arcType)) {
      const tempObj = {};
      processPacketData(
        Boolean,
        tempObj,
        "followSurface",
        polylineData.followSurface,
        interval,
        sourceUri,
        entityCollection
      );
      polyline.arcType = createAdapterProperty(
        tempObj.followSurface,
        adaptFollowSurfaceToArcType
      );
    }
  }

  function processPolylineVolume(entity, packet, entityCollection, sourceUri) {
    const polylineVolumeData = packet.polylineVolume;
    if (!defined(polylineVolumeData)) {
      return;
    }

    const interval = intervalFromString(polylineVolumeData.interval);
    let polylineVolume = entity.polylineVolume;
    if (!defined(polylineVolume)) {
      entity.polylineVolume = polylineVolume = new PolylineVolumeGraphics();
    }

    processPositionArray(
      polylineVolume,
      "positions",
      polylineVolumeData.positions,
      entityCollection
    );
    processShape(
      polylineVolume,
      "shape",
      polylineVolumeData.shape,
      entityCollection
    );
    processPacketData(
      Boolean,
      polylineVolume,
      "show",
      polylineVolumeData.show,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      CornerType$1,
      polylineVolume,
      "cornerType",
      polylineVolumeData.cornerType,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Boolean,
      polylineVolume,
      "fill",
      polylineVolumeData.fill,
      interval,
      sourceUri,
      entityCollection
    );
    processMaterialPacketData(
      polylineVolume,
      "material",
      polylineVolumeData.material,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Boolean,
      polylineVolume,
      "outline",
      polylineVolumeData.outline,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Color,
      polylineVolume,
      "outlineColor",
      polylineVolumeData.outlineColor,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      polylineVolume,
      "outlineWidth",
      polylineVolumeData.outlineWidth,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      polylineVolume,
      "granularity",
      polylineVolumeData.granularity,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      ShadowMode$1,
      polylineVolume,
      "shadows",
      polylineVolumeData.shadows,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      DistanceDisplayCondition,
      polylineVolume,
      "distanceDisplayCondition",
      polylineVolumeData.distanceDisplayCondition,
      interval,
      sourceUri,
      entityCollection
    );
  }

  function processRectangle(entity, packet, entityCollection, sourceUri) {
    const rectangleData = packet.rectangle;
    if (!defined(rectangleData)) {
      return;
    }

    const interval = intervalFromString(rectangleData.interval);
    let rectangle = entity.rectangle;
    if (!defined(rectangle)) {
      entity.rectangle = rectangle = new RectangleGraphics();
    }

    processPacketData(
      Boolean,
      rectangle,
      "show",
      rectangleData.show,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Rectangle,
      rectangle,
      "coordinates",
      rectangleData.coordinates,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      rectangle,
      "height",
      rectangleData.height,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      HeightReference$1,
      rectangle,
      "heightReference",
      rectangleData.heightReference,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      rectangle,
      "extrudedHeight",
      rectangleData.extrudedHeight,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      HeightReference$1,
      rectangle,
      "extrudedHeightReference",
      rectangleData.extrudedHeightReference,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Rotation,
      rectangle,
      "rotation",
      rectangleData.rotation,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Rotation,
      rectangle,
      "stRotation",
      rectangleData.stRotation,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      rectangle,
      "granularity",
      rectangleData.granularity,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Boolean,
      rectangle,
      "fill",
      rectangleData.fill,
      interval,
      sourceUri,
      entityCollection
    );
    processMaterialPacketData(
      rectangle,
      "material",
      rectangleData.material,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Boolean,
      rectangle,
      "outline",
      rectangleData.outline,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Color,
      rectangle,
      "outlineColor",
      rectangleData.outlineColor,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      rectangle,
      "outlineWidth",
      rectangleData.outlineWidth,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      ShadowMode$1,
      rectangle,
      "shadows",
      rectangleData.shadows,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      DistanceDisplayCondition,
      rectangle,
      "distanceDisplayCondition",
      rectangleData.distanceDisplayCondition,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      ClassificationType$1,
      rectangle,
      "classificationType",
      rectangleData.classificationType,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      rectangle,
      "zIndex",
      rectangleData.zIndex,
      interval,
      sourceUri,
      entityCollection
    );
  }

  function processTileset(entity, packet, entityCollection, sourceUri) {
    const tilesetData = packet.tileset;
    if (!defined(tilesetData)) {
      return;
    }

    const interval = intervalFromString(tilesetData.interval);
    let tileset = entity.tileset;
    if (!defined(tileset)) {
      entity.tileset = tileset = new Cesium3DTilesetGraphics();
    }

    processPacketData(
      Boolean,
      tileset,
      "show",
      tilesetData.show,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      URI,
      tileset,
      "uri",
      tilesetData.uri,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      tileset,
      "maximumScreenSpaceError",
      tilesetData.maximumScreenSpaceError,
      interval,
      sourceUri,
      entityCollection
    );
  }

  function processWall(entity, packet, entityCollection, sourceUri) {
    const wallData = packet.wall;
    if (!defined(wallData)) {
      return;
    }

    const interval = intervalFromString(wallData.interval);
    let wall = entity.wall;
    if (!defined(wall)) {
      entity.wall = wall = new WallGraphics();
    }

    processPacketData(
      Boolean,
      wall,
      "show",
      wallData.show,
      interval,
      sourceUri,
      entityCollection
    );
    processPositionArray(wall, "positions", wallData.positions, entityCollection);
    processArray(
      wall,
      "minimumHeights",
      wallData.minimumHeights,
      entityCollection
    );
    processArray(
      wall,
      "maximumHeights",
      wallData.maximumHeights,
      entityCollection
    );
    processPacketData(
      Number,
      wall,
      "granularity",
      wallData.granularity,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Boolean,
      wall,
      "fill",
      wallData.fill,
      interval,
      sourceUri,
      entityCollection
    );
    processMaterialPacketData(
      wall,
      "material",
      wallData.material,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Boolean,
      wall,
      "outline",
      wallData.outline,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Color,
      wall,
      "outlineColor",
      wallData.outlineColor,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      Number,
      wall,
      "outlineWidth",
      wallData.outlineWidth,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      ShadowMode$1,
      wall,
      "shadows",
      wallData.shadows,
      interval,
      sourceUri,
      entityCollection
    );
    processPacketData(
      DistanceDisplayCondition,
      wall,
      "distanceDisplayCondition",
      wallData.distanceDisplayCondition,
      interval,
      sourceUri,
      entityCollection
    );
  }

  function processCzmlPacket(
    packet,
    entityCollection,
    updaterFunctions,
    sourceUri,
    dataSource
  ) {
    let objectId = packet.id;
    if (!defined(objectId)) {
      objectId = createGuid();
    }

    currentId = objectId;

    if (!defined(dataSource._version) && objectId !== "document") {
      throw new RuntimeError(
        "The first CZML packet is required to be the document object."
      );
    }

    if (packet["delete"] === true) {
      entityCollection.removeById(objectId);
    } else if (objectId === "document") {
      processDocument$1(packet, dataSource);
    } else {
      const entity = entityCollection.getOrCreateEntity(objectId);

      const parentId = packet.parent;
      if (defined(parentId)) {
        entity.parent = entityCollection.getOrCreateEntity(parentId);
      }

      for (let i = updaterFunctions.length - 1; i > -1; i--) {
        updaterFunctions[i](entity, packet, entityCollection, sourceUri);
      }
    }

    currentId = undefined;
  }

  function updateClock(dataSource) {
    let clock;
    const clockPacket = dataSource._documentPacket.clock;
    if (!defined(clockPacket)) {
      if (!defined(dataSource._clock)) {
        const availability = dataSource._entityCollection.computeAvailability();
        if (!availability.start.equals(Iso8601.MINIMUM_VALUE)) {
          const startTime = availability.start;
          const stopTime = availability.stop;
          const totalSeconds = JulianDate.secondsDifference(stopTime, startTime);
          const multiplier = Math.round(totalSeconds / 120.0);

          clock = new DataSourceClock();
          clock.startTime = JulianDate.clone(startTime);
          clock.stopTime = JulianDate.clone(stopTime);
          clock.clockRange = ClockRange$1.LOOP_STOP;
          clock.multiplier = multiplier;
          clock.currentTime = JulianDate.clone(startTime);
          clock.clockStep = ClockStep$1.SYSTEM_CLOCK_MULTIPLIER;
          dataSource._clock = clock;
          return true;
        }
      }
      return false;
    }

    if (defined(dataSource._clock)) {
      clock = dataSource._clock.clone();
    } else {
      clock = new DataSourceClock();
      clock.startTime = Iso8601.MINIMUM_VALUE.clone();
      clock.stopTime = Iso8601.MAXIMUM_VALUE.clone();
      clock.currentTime = Iso8601.MINIMUM_VALUE.clone();
      clock.clockRange = ClockRange$1.LOOP_STOP;
      clock.clockStep = ClockStep$1.SYSTEM_CLOCK_MULTIPLIER;
      clock.multiplier = 1.0;
    }

    const interval = intervalFromString(clockPacket.interval);
    if (defined(interval)) {
      clock.startTime = interval.start;
      clock.stopTime = interval.stop;
    }

    if (defined(clockPacket.currentTime)) {
      clock.currentTime = JulianDate.fromIso8601(clockPacket.currentTime);
    }
    if (defined(clockPacket.range)) {
      clock.clockRange = defaultValue(
        ClockRange$1[clockPacket.range],
        ClockRange$1.LOOP_STOP
      );
    }
    if (defined(clockPacket.step)) {
      clock.clockStep = defaultValue(
        ClockStep$1[clockPacket.step],
        ClockStep$1.SYSTEM_CLOCK_MULTIPLIER
      );
    }
    if (defined(clockPacket.multiplier)) {
      clock.multiplier = clockPacket.multiplier;
    }

    if (!clock.equals(dataSource._clock)) {
      dataSource._clock = clock.clone(dataSource._clock);
      return true;
    }

    return false;
  }

  function load$3(dataSource, czml, options, clear) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(czml)) {
      throw new DeveloperError("czml is required.");
    }
    //>>includeEnd('debug');

    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    let promise = czml;
    let sourceUri = options.sourceUri;

    // User specified credit
    let credit = options.credit;
    if (typeof credit === "string") {
      credit = new Credit(credit);
    }
    dataSource._credit = credit;

    // If the czml is a URL
    if (typeof czml === "string" || czml instanceof Resource) {
      czml = Resource.createIfNeeded(czml);
      promise = czml.fetchJson();
      sourceUri = defaultValue(sourceUri, czml.clone());

      // Add resource credits to our list of credits to display
      const resourceCredits = dataSource._resourceCredits;
      const credits = czml.credits;
      if (defined(credits)) {
        const length = credits.length;
        for (let i = 0; i < length; i++) {
          resourceCredits.push(credits[i]);
        }
      }
    }

    sourceUri = Resource.createIfNeeded(sourceUri);

    DataSource.setLoading(dataSource, true);

    return Promise.resolve(promise)
      .then(function (czml) {
        return loadCzml(dataSource, czml, sourceUri, clear);
      })
      .catch(function (error) {
        DataSource.setLoading(dataSource, false);
        dataSource._error.raiseEvent(dataSource, error);
        console.log(error);
        return Promise.reject(error);
      });
  }

  function loadCzml(dataSource, czml, sourceUri, clear) {
    DataSource.setLoading(dataSource, true);
    const entityCollection = dataSource._entityCollection;

    if (clear) {
      dataSource._version = undefined;
      dataSource._documentPacket = new DocumentPacket();
      entityCollection.removeAll();
    }

    CzmlDataSource._processCzml(
      czml,
      entityCollection,
      sourceUri,
      undefined,
      dataSource
    );

    let raiseChangedEvent = updateClock(dataSource);

    const documentPacket = dataSource._documentPacket;
    if (
      defined(documentPacket.name) &&
      dataSource._name !== documentPacket.name
    ) {
      dataSource._name = documentPacket.name;
      raiseChangedEvent = true;
    } else if (!defined(dataSource._name) && defined(sourceUri)) {
      dataSource._name = getFilenameFromUri(sourceUri.getUrlComponent());
      raiseChangedEvent = true;
    }

    DataSource.setLoading(dataSource, false);
    if (raiseChangedEvent) {
      dataSource._changed.raiseEvent(dataSource);
    }

    return dataSource;
  }

  function DocumentPacket() {
    this.name = undefined;
    this.clock = undefined;
  }

  /**
   * @typedef {Object} CzmlDataSource.LoadOptions
   *
   * Initialization options for the <code>load</code> method.
   *
   * @property {Resource|string} [sourceUri] Overrides the url to use for resolving relative links.
   * @property {Credit|string} [credit] A credit for the data source, which is displayed on the canvas.
   */

  /**
   * A {@link DataSource} which processes {@link https://github.com/AnalyticalGraphicsInc/czml-writer/wiki/CZML-Guide|CZML}.
   * @alias CzmlDataSource
   * @constructor
   *
   * @param {String} [name] An optional name for the data source.  This value will be overwritten if a loaded document contains a name.
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=CZML.html|Cesium Sandcastle CZML Demo}
   */
  function CzmlDataSource(name) {
    this._name = name;
    this._changed = new Event();
    this._error = new Event();
    this._isLoading = false;
    this._loading = new Event();
    this._clock = undefined;
    this._documentPacket = new DocumentPacket();
    this._version = undefined;
    this._entityCollection = new EntityCollection(this);
    this._entityCluster = new EntityCluster();
    this._credit = undefined;
    this._resourceCredits = [];
  }

  /**
   * Creates a Promise to a new instance loaded with the provided CZML data.
   *
   * @param {Resource|String|Object} czml A url or CZML object to be processed.
   * @param {CzmlDataSource.LoadOptions} [options] An object specifying configuration options
   *
   * @returns {Promise.<CzmlDataSource>} A promise that resolves to the new instance once the data is processed.
   */
  CzmlDataSource.load = function (czml, options) {
    return new CzmlDataSource().load(czml, options);
  };

  Object.defineProperties(CzmlDataSource.prototype, {
    /**
     * Gets a human-readable name for this instance.
     * @memberof CzmlDataSource.prototype
     * @type {String}
     */
    name: {
      get: function () {
        return this._name;
      },
    },
    /**
     * Gets the clock settings defined by the loaded CZML.  If no clock is explicitly
     * defined in the CZML, the combined availability of all objects is returned.  If
     * only static data exists, this value is undefined.
     * @memberof CzmlDataSource.prototype
     * @type {DataSourceClock}
     */
    clock: {
      get: function () {
        return this._clock;
      },
    },
    /**
     * Gets the collection of {@link Entity} instances.
     * @memberof CzmlDataSource.prototype
     * @type {EntityCollection}
     */
    entities: {
      get: function () {
        return this._entityCollection;
      },
    },
    /**
     * Gets a value indicating if the data source is currently loading data.
     * @memberof CzmlDataSource.prototype
     * @type {Boolean}
     */
    isLoading: {
      get: function () {
        return this._isLoading;
      },
    },
    /**
     * Gets an event that will be raised when the underlying data changes.
     * @memberof CzmlDataSource.prototype
     * @type {Event}
     */
    changedEvent: {
      get: function () {
        return this._changed;
      },
    },
    /**
     * Gets an event that will be raised if an error is encountered during processing.
     * @memberof CzmlDataSource.prototype
     * @type {Event}
     */
    errorEvent: {
      get: function () {
        return this._error;
      },
    },
    /**
     * Gets an event that will be raised when the data source either starts or stops loading.
     * @memberof CzmlDataSource.prototype
     * @type {Event}
     */
    loadingEvent: {
      get: function () {
        return this._loading;
      },
    },
    /**
     * Gets whether or not this data source should be displayed.
     * @memberof CzmlDataSource.prototype
     * @type {Boolean}
     */
    show: {
      get: function () {
        return this._entityCollection.show;
      },
      set: function (value) {
        this._entityCollection.show = value;
      },
    },

    /**
     * Gets or sets the clustering options for this data source. This object can be shared between multiple data sources.
     *
     * @memberof CzmlDataSource.prototype
     * @type {EntityCluster}
     */
    clustering: {
      get: function () {
        return this._entityCluster;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value must be defined.");
        }
        //>>includeEnd('debug');
        this._entityCluster = value;
      },
    },
    /**
     * Gets the credit that will be displayed for the data source
     * @memberof CzmlDataSource.prototype
     * @type {Credit}
     */
    credit: {
      get: function () {
        return this._credit;
      },
    },
  });

  /**
   * @callback CzmlDataSource.UpdaterFunction
   *
   * A CZML processing function that adds or updates entities in the provided
   * collection based on the provided CZML packet.
   *
   * @param {Entity} entity
   * @param {Object} packet
   * @param {EntityCollection} entityCollection
   * @param {string} sourceUri
   */

  /**
   * Gets the array of CZML processing functions.
   * @memberof CzmlDataSource
   * @type {Array.<CzmlDataSource.UpdaterFunction>}
   */
  CzmlDataSource.updaters = [
    processBillboard, //
    processBox, //
    processCorridor, //
    processCylinder, //
    processEllipse, //
    processEllipsoid, //
    processLabel, //
    processModel, //
    processName, //
    processDescription$2, //
    processPath, //
    processPoint$2, //
    processPolygon$2, //
    processPolyline, //
    processPolylineVolume, //
    processProperties, //
    processRectangle, //
    processPosition, //
    processTileset, //
    processViewFrom, //
    processWall, //
    processOrientation, //
    processAvailability,
  ];

  /**
   * Processes the provided url or CZML object without clearing any existing data.
   *
   * @param {Resource|String|Object} czml A url or CZML object to be processed.
   * @param {CzmlDataSource.LoadOptions} [options] An object specifying configuration options
   *
   * @returns {Promise.<CzmlDataSource>} A promise that resolves to this instances once the data is processed.
   */
  CzmlDataSource.prototype.process = function (czml, options) {
    return load$3(this, czml, options, false);
  };

  /**
   * Loads the provided url or CZML object, replacing any existing data.
   *
   * @param {Resource|String|Object} czml A url or CZML object to be processed.
   * @param {CzmlDataSource.LoadOptions} [options] An object specifying configuration options
   *
   * @returns {Promise.<CzmlDataSource>} A promise that resolves to this instances once the data is processed.
   */
  CzmlDataSource.prototype.load = function (czml, options) {
    return load$3(this, czml, options, true);
  };

  /**
   * Updates the data source to the provided time.  This function is optional and
   * is not required to be implemented.  It is provided for data sources which
   * retrieve data based on the current animation time or scene state.
   * If implemented, update will be called by {@link DataSourceDisplay} once a frame.
   *
   * @param {JulianDate} time The simulation time.
   * @returns {Boolean} True if this data source is ready to be displayed at the provided time, false otherwise.
   */
  CzmlDataSource.prototype.update = function (time) {
    return true;
  };

  /**
   * A helper function used by custom CZML updater functions
   * which creates or updates a {@link Property} from a CZML packet.
   * @function
   *
   * @param {Function} type The constructor function for the property being processed.
   * @param {Object} object The object on which the property will be added or updated.
   * @param {String} propertyName The name of the property on the object.
   * @param {Object} packetData The CZML packet being processed.
   * @param {TimeInterval} interval A constraining interval for which the data is valid.
   * @param {String} sourceUri The originating uri of the data being processed.
   * @param {EntityCollection} entityCollection The collection being processsed.
   */
  CzmlDataSource.processPacketData = processPacketData;

  /**
   * A helper function used by custom CZML updater functions
   * which creates or updates a {@link PositionProperty} from a CZML packet.
   * @function
   *
   * @param {Object} object The object on which the property will be added or updated.
   * @param {String} propertyName The name of the property on the object.
   * @param {Object} packetData The CZML packet being processed.
   * @param {TimeInterval} interval A constraining interval for which the data is valid.
   * @param {String} sourceUri The originating uri of the data being processed.
   * @param {EntityCollection} entityCollection The collection being processsed.
   */
  CzmlDataSource.processPositionPacketData = processPositionPacketData;

  /**
   * A helper function used by custom CZML updater functions
   * which creates or updates a {@link MaterialProperty} from a CZML packet.
   * @function
   *
   * @param {Object} object The object on which the property will be added or updated.
   * @param {String} propertyName The name of the property on the object.
   * @param {Object} packetData The CZML packet being processed.
   * @param {TimeInterval} interval A constraining interval for which the data is valid.
   * @param {String} sourceUri The originating uri of the data being processed.
   * @param {EntityCollection} entityCollection The collection being processsed.
   */
  CzmlDataSource.processMaterialPacketData = processMaterialPacketData;

  CzmlDataSource._processCzml = function (
    czml,
    entityCollection,
    sourceUri,
    updaterFunctions,
    dataSource
  ) {
    updaterFunctions = defaultValue(updaterFunctions, CzmlDataSource.updaters);

    if (Array.isArray(czml)) {
      for (let i = 0, len = czml.length; i < len; ++i) {
        processCzmlPacket(
          czml[i],
          entityCollection,
          updaterFunctions,
          sourceUri,
          dataSource
        );
      }
    } else {
      processCzmlPacket(
        czml,
        entityCollection,
        updaterFunctions,
        sourceUri,
        dataSource
      );
    }
  };

  /**
   * A collection of {@link DataSource} instances.
   * @alias DataSourceCollection
   * @constructor
   */
  function DataSourceCollection() {
    this._dataSources = [];
    this._dataSourceAdded = new Event();
    this._dataSourceRemoved = new Event();
    this._dataSourceMoved = new Event();
  }

  Object.defineProperties(DataSourceCollection.prototype, {
    /**
     * Gets the number of data sources in this collection.
     * @memberof DataSourceCollection.prototype
     * @type {Number}
     * @readonly
     */
    length: {
      get: function () {
        return this._dataSources.length;
      },
    },

    /**
     * An event that is raised when a data source is added to the collection.
     * Event handlers are passed the data source that was added.
     * @memberof DataSourceCollection.prototype
     * @type {Event}
     * @readonly
     */
    dataSourceAdded: {
      get: function () {
        return this._dataSourceAdded;
      },
    },

    /**
     * An event that is raised when a data source is removed from the collection.
     * Event handlers are passed the data source that was removed.
     * @memberof DataSourceCollection.prototype
     * @type {Event}
     * @readonly
     */
    dataSourceRemoved: {
      get: function () {
        return this._dataSourceRemoved;
      },
    },

    /**
     * An event that is raised when a data source changes position in the collection.  Event handlers are passed the data source
     * that was moved, its new index after the move, and its old index prior to the move.
     * @memberof DataSourceCollection.prototype
     * @type {Event}
     * @readonly
     */
    dataSourceMoved: {
      get: function () {
        return this._dataSourceMoved;
      },
    },
  });

  /**
   * Adds a data source to the collection.
   *
   * @param {DataSource|Promise.<DataSource>} dataSource A data source or a promise to a data source to add to the collection.
   *                                        When passing a promise, the data source will not actually be added
   *                                        to the collection until the promise resolves successfully.
   * @returns {Promise.<DataSource>} A Promise that resolves once the data source has been added to the collection.
   */
  DataSourceCollection.prototype.add = function (dataSource) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(dataSource)) {
      throw new DeveloperError("dataSource is required.");
    }
    //>>includeEnd('debug');

    const that = this;
    const dataSources = this._dataSources;
    return Promise.resolve(dataSource).then(function (value) {
      //Only add the data source if removeAll has not been called
      //Since it was added.
      if (dataSources === that._dataSources) {
        that._dataSources.push(value);
        that._dataSourceAdded.raiseEvent(that, value);
      }
      return value;
    });
  };

  /**
   * Removes a data source from this collection, if present.
   *
   * @param {DataSource} dataSource The data source to remove.
   * @param {Boolean} [destroy=false] Whether to destroy the data source in addition to removing it.
   * @returns {Boolean} true if the data source was in the collection and was removed,
   *                    false if the data source was not in the collection.
   */
  DataSourceCollection.prototype.remove = function (dataSource, destroy) {
    destroy = defaultValue(destroy, false);

    const index = this._dataSources.indexOf(dataSource);
    if (index !== -1) {
      this._dataSources.splice(index, 1);
      this._dataSourceRemoved.raiseEvent(this, dataSource);

      if (destroy && typeof dataSource.destroy === "function") {
        dataSource.destroy();
      }

      return true;
    }

    return false;
  };

  /**
   * Removes all data sources from this collection.
   *
   * @param {Boolean} [destroy=false] whether to destroy the data sources in addition to removing them.
   */
  DataSourceCollection.prototype.removeAll = function (destroy) {
    destroy = defaultValue(destroy, false);

    const dataSources = this._dataSources;
    for (let i = 0, len = dataSources.length; i < len; ++i) {
      const dataSource = dataSources[i];
      this._dataSourceRemoved.raiseEvent(this, dataSource);

      if (destroy && typeof dataSource.destroy === "function") {
        dataSource.destroy();
      }
    }
    this._dataSources = [];
  };

  /**
   * Checks to see if the collection contains a given data source.
   *
   * @param {DataSource} dataSource The data source to check for.
   * @returns {Boolean} true if the collection contains the data source, false otherwise.
   */
  DataSourceCollection.prototype.contains = function (dataSource) {
    return this.indexOf(dataSource) !== -1;
  };

  /**
   * Determines the index of a given data source in the collection.
   *
   * @param {DataSource} dataSource The data source to find the index of.
   * @returns {Number} The index of the data source in the collection, or -1 if the data source does not exist in the collection.
   */
  DataSourceCollection.prototype.indexOf = function (dataSource) {
    return this._dataSources.indexOf(dataSource);
  };

  /**
   * Gets a data source by index from the collection.
   *
   * @param {Number} index the index to retrieve.
   * @returns {DataSource} The data source at the specified index.
   */
  DataSourceCollection.prototype.get = function (index) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(index)) {
      throw new DeveloperError("index is required.");
    }
    //>>includeEnd('debug');

    return this._dataSources[index];
  };

  /**
   * Gets a data source by name from the collection.
   *
   * @param {String} name The name to retrieve.
   * @returns {DataSource[]} A list of all data sources matching the provided name.
   */
  DataSourceCollection.prototype.getByName = function (name) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(name)) {
      throw new DeveloperError("name is required.");
    }
    //>>includeEnd('debug');

    return this._dataSources.filter(function (dataSource) {
      return dataSource.name === name;
    });
  };

  function getIndex(dataSources, dataSource) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(dataSource)) {
      throw new DeveloperError("dataSource is required.");
    }
    //>>includeEnd('debug');

    const index = dataSources.indexOf(dataSource);

    //>>includeStart('debug', pragmas.debug);
    if (index === -1) {
      throw new DeveloperError("dataSource is not in this collection.");
    }
    //>>includeEnd('debug');

    return index;
  }

  function swapDataSources(collection, i, j) {
    const arr = collection._dataSources;
    const length = arr.length - 1;
    i = CesiumMath.clamp(i, 0, length);
    j = CesiumMath.clamp(j, 0, length);

    if (i === j) {
      return;
    }

    const temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;

    collection.dataSourceMoved.raiseEvent(temp, j, i);
  }

  /**
   * Raises a data source up one position in the collection.
   *
   * @param {DataSource} dataSource The data source to move.
   *
   * @exception {DeveloperError} dataSource is not in this collection.
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   */
  DataSourceCollection.prototype.raise = function (dataSource) {
    const index = getIndex(this._dataSources, dataSource);
    swapDataSources(this, index, index + 1);
  };

  /**
   * Lowers a data source down one position in the collection.
   *
   * @param {DataSource} dataSource The data source to move.
   *
   * @exception {DeveloperError} dataSource is not in this collection.
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   */
  DataSourceCollection.prototype.lower = function (dataSource) {
    const index = getIndex(this._dataSources, dataSource);
    swapDataSources(this, index, index - 1);
  };

  /**
   * Raises a data source to the top of the collection.
   *
   * @param {DataSource} dataSource The data source to move.
   *
   * @exception {DeveloperError} dataSource is not in this collection.
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   */
  DataSourceCollection.prototype.raiseToTop = function (dataSource) {
    const index = getIndex(this._dataSources, dataSource);
    if (index === this._dataSources.length - 1) {
      return;
    }
    this._dataSources.splice(index, 1);
    this._dataSources.push(dataSource);

    this.dataSourceMoved.raiseEvent(
      dataSource,
      this._dataSources.length - 1,
      index
    );
  };

  /**
   * Lowers a data source to the bottom of the collection.
   *
   * @param {DataSource} dataSource The data source to move.
   *
   * @exception {DeveloperError} dataSource is not in this collection.
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   */
  DataSourceCollection.prototype.lowerToBottom = function (dataSource) {
    const index = getIndex(this._dataSources, dataSource);
    if (index === 0) {
      return;
    }
    this._dataSources.splice(index, 1);
    this._dataSources.splice(0, 0, dataSource);

    this.dataSourceMoved.raiseEvent(dataSource, 0, index);
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} true if this object was destroyed; otherwise, false.
   *
   * @see DataSourceCollection#destroy
   */
  DataSourceCollection.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the resources held by all data sources in this collection.  Explicitly destroying this
   * object allows for deterministic release of WebGL resources, instead of relying on the garbage
   * collector. Once this object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * dataSourceCollection = dataSourceCollection && dataSourceCollection.destroy();
   *
   * @see DataSourceCollection#isDestroyed
   */
  DataSourceCollection.prototype.destroy = function () {
    this.removeAll(true);
    return destroyObject(this);
  };

  /**
   * A collection of primitives.  This is most often used with {@link Scene#primitives},
   * but <code>PrimitiveCollection</code> is also a primitive itself so collections can
   * be added to collections forming a hierarchy.
   *
   * @alias PrimitiveCollection
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Boolean} [options.show=true] Determines if the primitives in the collection will be shown.
   * @param {Boolean} [options.destroyPrimitives=true] Determines if primitives in the collection are destroyed when they are removed.
   *
   * @example
   * const billboards = new Cesium.BillboardCollection();
   * const labels = new Cesium.LabelCollection();
   *
   * const collection = new Cesium.PrimitiveCollection();
   * collection.add(billboards);
   *
   * scene.primitives.add(collection);  // Add collection
   * scene.primitives.add(labels);      // Add regular primitive
   */
  function PrimitiveCollection(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    this._primitives = [];
    this._guid = createGuid();

    // Used by the OrderedGroundPrimitiveCollection
    this._zIndex = undefined;

    /**
     * Determines if primitives in this collection will be shown.
     *
     * @type {Boolean}
     * @default true
     */
    this.show = defaultValue(options.show, true);

    /**
     * Determines if primitives in the collection are destroyed when they are removed by
     * {@link PrimitiveCollection#destroy} or  {@link PrimitiveCollection#remove} or implicitly
     * by {@link PrimitiveCollection#removeAll}.
     *
     * @type {Boolean}
     * @default true
     *
     * @example
     * // Example 1. Primitives are destroyed by default.
     * const primitives = new Cesium.PrimitiveCollection();
     * const labels = primitives.add(new Cesium.LabelCollection());
     * primitives = primitives.destroy();
     * const b = labels.isDestroyed(); // true
     *
     * @example
     * // Example 2. Do not destroy primitives in a collection.
     * const primitives = new Cesium.PrimitiveCollection();
     * primitives.destroyPrimitives = false;
     * const labels = primitives.add(new Cesium.LabelCollection());
     * primitives = primitives.destroy();
     * const b = labels.isDestroyed(); // false
     * labels = labels.destroy();    // explicitly destroy
     */
    this.destroyPrimitives = defaultValue(options.destroyPrimitives, true);
  }

  Object.defineProperties(PrimitiveCollection.prototype, {
    /**
     * Gets the number of primitives in the collection.
     *
     * @memberof PrimitiveCollection.prototype
     *
     * @type {Number}
     * @readonly
     */
    length: {
      get: function () {
        return this._primitives.length;
      },
    },
  });

  /**
   * Adds a primitive to the collection.
   *
   * @param {Object} primitive The primitive to add.
   * @param {Number} [index] The index to add the layer at.  If omitted, the primitive will be added at the bottom of all existing primitives.
   * @returns {Object} The primitive added to the collection.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @example
   * const billboards = scene.primitives.add(new Cesium.BillboardCollection());
   */
  PrimitiveCollection.prototype.add = function (primitive, index) {
    const hasIndex = defined(index);

    //>>includeStart('debug', pragmas.debug);
    if (!defined(primitive)) {
      throw new DeveloperError("primitive is required.");
    }
    if (hasIndex) {
      if (index < 0) {
        throw new DeveloperError("index must be greater than or equal to zero.");
      } else if (index > this._primitives.length) {
        throw new DeveloperError(
          "index must be less than or equal to the number of primitives."
        );
      }
    }
    //>>includeEnd('debug');

    const external = (primitive._external = primitive._external || {});
    const composites = (external._composites = external._composites || {});
    composites[this._guid] = {
      collection: this,
    };

    if (!hasIndex) {
      this._primitives.push(primitive);
    } else {
      this._primitives.splice(index, 0, primitive);
    }

    return primitive;
  };

  /**
   * Removes a primitive from the collection.
   *
   * @param {Object} [primitive] The primitive to remove.
   * @returns {Boolean} <code>true</code> if the primitive was removed; <code>false</code> if the primitive is <code>undefined</code> or was not found in the collection.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * const billboards = scene.primitives.add(new Cesium.BillboardCollection());
   * scene.primitives.remove(billboards);  // Returns true
   *
   * @see PrimitiveCollection#destroyPrimitives
   */
  PrimitiveCollection.prototype.remove = function (primitive) {
    // PERFORMANCE_IDEA:  We can obviously make this a lot faster.
    if (this.contains(primitive)) {
      const index = this._primitives.indexOf(primitive);
      if (index !== -1) {
        this._primitives.splice(index, 1);

        delete primitive._external._composites[this._guid];

        if (this.destroyPrimitives) {
          primitive.destroy();
        }

        return true;
      }
      // else ... this is not possible, I swear.
    }

    return false;
  };

  /**
   * Removes and destroys a primitive, regardless of destroyPrimitives setting.
   * @private
   */
  PrimitiveCollection.prototype.removeAndDestroy = function (primitive) {
    const removed = this.remove(primitive);
    if (removed && !this.destroyPrimitives) {
      primitive.destroy();
    }
    return removed;
  };

  /**
   * Removes all primitives in the collection.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @see PrimitiveCollection#destroyPrimitives
   */
  PrimitiveCollection.prototype.removeAll = function () {
    const primitives = this._primitives;
    const length = primitives.length;
    for (let i = 0; i < length; ++i) {
      delete primitives[i]._external._composites[this._guid];
      if (this.destroyPrimitives) {
        primitives[i].destroy();
      }
    }
    this._primitives = [];
  };

  /**
   * Determines if this collection contains a primitive.
   *
   * @param {Object} [primitive] The primitive to check for.
   * @returns {Boolean} <code>true</code> if the primitive is in the collection; <code>false</code> if the primitive is <code>undefined</code> or was not found in the collection.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @see PrimitiveCollection#get
   */
  PrimitiveCollection.prototype.contains = function (primitive) {
    return !!(
      defined(primitive) &&
      primitive._external &&
      primitive._external._composites &&
      primitive._external._composites[this._guid]
    );
  };

  function getPrimitiveIndex(compositePrimitive, primitive) {
    //>>includeStart('debug', pragmas.debug);
    if (!compositePrimitive.contains(primitive)) {
      throw new DeveloperError("primitive is not in this collection.");
    }
    //>>includeEnd('debug');

    return compositePrimitive._primitives.indexOf(primitive);
  }

  /**
   * Raises a primitive "up one" in the collection.  If all primitives in the collection are drawn
   * on the globe surface, this visually moves the primitive up one.
   *
   * @param {Object} [primitive] The primitive to raise.
   *
   * @exception {DeveloperError} primitive is not in this collection.
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @see PrimitiveCollection#raiseToTop
   * @see PrimitiveCollection#lower
   * @see PrimitiveCollection#lowerToBottom
   */
  PrimitiveCollection.prototype.raise = function (primitive) {
    if (defined(primitive)) {
      const index = getPrimitiveIndex(this, primitive);
      const primitives = this._primitives;

      if (index !== primitives.length - 1) {
        const p = primitives[index];
        primitives[index] = primitives[index + 1];
        primitives[index + 1] = p;
      }
    }
  };

  /**
   * Raises a primitive to the "top" of the collection.  If all primitives in the collection are drawn
   * on the globe surface, this visually moves the primitive to the top.
   *
   * @param {Object} [primitive] The primitive to raise the top.
   *
   * @exception {DeveloperError} primitive is not in this collection.
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @see PrimitiveCollection#raise
   * @see PrimitiveCollection#lower
   * @see PrimitiveCollection#lowerToBottom
   */
  PrimitiveCollection.prototype.raiseToTop = function (primitive) {
    if (defined(primitive)) {
      const index = getPrimitiveIndex(this, primitive);
      const primitives = this._primitives;

      if (index !== primitives.length - 1) {
        // PERFORMANCE_IDEA:  Could be faster
        primitives.splice(index, 1);
        primitives.push(primitive);
      }
    }
  };

  /**
   * Lowers a primitive "down one" in the collection.  If all primitives in the collection are drawn
   * on the globe surface, this visually moves the primitive down one.
   *
   * @param {Object} [primitive] The primitive to lower.
   *
   * @exception {DeveloperError} primitive is not in this collection.
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @see PrimitiveCollection#lowerToBottom
   * @see PrimitiveCollection#raise
   * @see PrimitiveCollection#raiseToTop
   */
  PrimitiveCollection.prototype.lower = function (primitive) {
    if (defined(primitive)) {
      const index = getPrimitiveIndex(this, primitive);
      const primitives = this._primitives;

      if (index !== 0) {
        const p = primitives[index];
        primitives[index] = primitives[index - 1];
        primitives[index - 1] = p;
      }
    }
  };

  /**
   * Lowers a primitive to the "bottom" of the collection.  If all primitives in the collection are drawn
   * on the globe surface, this visually moves the primitive to the bottom.
   *
   * @param {Object} [primitive] The primitive to lower to the bottom.
   *
   * @exception {DeveloperError} primitive is not in this collection.
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @see PrimitiveCollection#lower
   * @see PrimitiveCollection#raise
   * @see PrimitiveCollection#raiseToTop
   */
  PrimitiveCollection.prototype.lowerToBottom = function (primitive) {
    if (defined(primitive)) {
      const index = getPrimitiveIndex(this, primitive);
      const primitives = this._primitives;

      if (index !== 0) {
        // PERFORMANCE_IDEA:  Could be faster
        primitives.splice(index, 1);
        primitives.unshift(primitive);
      }
    }
  };

  /**
   * Returns the primitive in the collection at the specified index.
   *
   * @param {Number} index The zero-based index of the primitive to return.
   * @returns {Object} The primitive at the <code>index</code>.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * // Toggle the show property of every primitive in the collection.
   * const primitives = scene.primitives;
   * const length = primitives.length;
   * for (let i = 0; i < length; ++i) {
   *   const p = primitives.get(i);
   *   p.show = !p.show;
   * }
   *
   * @see PrimitiveCollection#length
   */
  PrimitiveCollection.prototype.get = function (index) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(index)) {
      throw new DeveloperError("index is required.");
    }
    //>>includeEnd('debug');

    return this._primitives[index];
  };

  /**
   * @private
   */
  PrimitiveCollection.prototype.update = function (frameState) {
    if (!this.show) {
      return;
    }

    const primitives = this._primitives;
    // Using primitives.length in the loop is a temporary workaround
    // to allow quadtree updates to add and remove primitives in
    // update().  This will be changed to manage added and removed lists.
    for (let i = 0; i < primitives.length; ++i) {
      primitives[i].update(frameState);
    }
  };

  /**
   * @private
   */
  PrimitiveCollection.prototype.prePassesUpdate = function (frameState) {
    const primitives = this._primitives;
    // Using primitives.length in the loop is a temporary workaround
    // to allow quadtree updates to add and remove primitives in
    // update().  This will be changed to manage added and removed lists.
    for (let i = 0; i < primitives.length; ++i) {
      const primitive = primitives[i];
      if (defined(primitive.prePassesUpdate)) {
        primitive.prePassesUpdate(frameState);
      }
    }
  };

  /**
   * @private
   */
  PrimitiveCollection.prototype.updateForPass = function (frameState, passState) {
    const primitives = this._primitives;
    // Using primitives.length in the loop is a temporary workaround
    // to allow quadtree updates to add and remove primitives in
    // update().  This will be changed to manage added and removed lists.
    for (let i = 0; i < primitives.length; ++i) {
      const primitive = primitives[i];
      if (defined(primitive.updateForPass)) {
        primitive.updateForPass(frameState, passState);
      }
    }
  };

  /**
   * @private
   */
  PrimitiveCollection.prototype.postPassesUpdate = function (frameState) {
    const primitives = this._primitives;
    // Using primitives.length in the loop is a temporary workaround
    // to allow quadtree updates to add and remove primitives in
    // update().  This will be changed to manage added and removed lists.
    for (let i = 0; i < primitives.length; ++i) {
      const primitive = primitives[i];
      if (defined(primitive.postPassesUpdate)) {
        primitive.postPassesUpdate(frameState);
      }
    }
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} True if this object was destroyed; otherwise, false.
   *
   * @see PrimitiveCollection#destroy
   */
  PrimitiveCollection.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by each primitive in this collection.  Explicitly destroying this
   * collection allows for deterministic release of WebGL resources, instead of relying on the garbage
   * collector to destroy this collection.
   * <br /><br />
   * Since destroying a collection destroys all the contained primitives, only destroy a collection
   * when you are sure no other code is still using any of the contained primitives.
   * <br /><br />
   * Once this collection is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * primitives = primitives && primitives.destroy();
   *
   * @see PrimitiveCollection#isDestroyed
   */
  PrimitiveCollection.prototype.destroy = function () {
    this.removeAll();
    return destroyObject(this);
  };

  /**
   * A primitive collection for helping maintain the order or ground primitives based on a z-index
   *
   * @private
   */
  function OrderedGroundPrimitiveCollection() {
    this._length = 0;
    this._collections = {};
    this._collectionsArray = [];

    this.show = true;
  }

  Object.defineProperties(OrderedGroundPrimitiveCollection.prototype, {
    /**
     * Gets the number of primitives in the collection.
     *
     * @memberof OrderedGroundPrimitiveCollection.prototype
     *
     * @type {Number}
     * @readonly
     */
    length: {
      get: function () {
        return this._length;
      },
    },
  });

  /**
   * Adds a primitive to the collection.
   *
   * @param {GroundPrimitive} primitive The primitive to add.
   * @param {Number} [zIndex = 0] The index of the primitive
   * @returns {GroundPrimitive} The primitive added to the collection.
   */
  OrderedGroundPrimitiveCollection.prototype.add = function (primitive, zIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("primitive", primitive);
    if (defined(zIndex)) {
      Check.typeOf.number("zIndex", zIndex);
    }
    //>>includeEnd('debug');

    zIndex = defaultValue(zIndex, 0);
    let collection = this._collections[zIndex];
    if (!defined(collection)) {
      collection = new PrimitiveCollection({ destroyPrimitives: false });
      collection._zIndex = zIndex;
      this._collections[zIndex] = collection;
      const array = this._collectionsArray;
      let i = 0;
      while (i < array.length && array[i]._zIndex < zIndex) {
        i++;
      }
      array.splice(i, 0, collection);
    }

    collection.add(primitive);
    this._length++;
    primitive._zIndex = zIndex;

    return primitive;
  };

  /**
   * Adjusts the z-index
   * @param {GroundPrimitive} primitive
   * @param {Number} zIndex
   */
  OrderedGroundPrimitiveCollection.prototype.set = function (primitive, zIndex) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("primitive", primitive);
    Check.typeOf.number("zIndex", zIndex);
    //>>includeEnd('debug');

    if (zIndex === primitive._zIndex) {
      return primitive;
    }

    this.remove(primitive, true);
    this.add(primitive, zIndex);

    return primitive;
  };

  /**
   * Removes a primitive from the collection.
   *
   * @param {Object} primitive The primitive to remove.
   * @param {Boolean} [doNotDestroy = false]
   * @returns {Boolean} <code>true</code> if the primitive was removed; <code>false</code> if the primitive is <code>undefined</code> or was not found in the collection.
   */
  OrderedGroundPrimitiveCollection.prototype.remove = function (
    primitive,
    doNotDestroy
  ) {
    if (this.contains(primitive)) {
      const index = primitive._zIndex;
      const collection = this._collections[index];
      let result;
      if (doNotDestroy) {
        result = collection.remove(primitive);
      } else {
        result = collection.removeAndDestroy(primitive);
      }

      if (result) {
        this._length--;
      }

      if (collection.length === 0) {
        this._collectionsArray.splice(
          this._collectionsArray.indexOf(collection),
          1
        );
        this._collections[index] = undefined;
        collection.destroy();
      }

      return result;
    }

    return false;
  };

  /**
   * Removes all primitives in the collection.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @see OrderedGroundPrimitiveCollection#destroyPrimitives
   */
  OrderedGroundPrimitiveCollection.prototype.removeAll = function () {
    const collections = this._collectionsArray;
    for (let i = 0; i < collections.length; i++) {
      const collection = collections[i];
      collection.destroyPrimitives = true;
      collection.destroy();
    }

    this._collections = {};
    this._collectionsArray = [];
    this._length = 0;
  };

  /**
   * Determines if this collection contains a primitive.
   *
   * @param {Object} primitive The primitive to check for.
   * @returns {Boolean} <code>true</code> if the primitive is in the collection; <code>false</code> if the primitive is <code>undefined</code> or was not found in the collection.
   */
  OrderedGroundPrimitiveCollection.prototype.contains = function (primitive) {
    if (!defined(primitive)) {
      return false;
    }
    const collection = this._collections[primitive._zIndex];
    return defined(collection) && collection.contains(primitive);
  };

  /**
   * @private
   */
  OrderedGroundPrimitiveCollection.prototype.update = function (frameState) {
    if (!this.show) {
      return;
    }

    const collections = this._collectionsArray;
    for (let i = 0; i < collections.length; i++) {
      collections[i].update(frameState);
    }
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} True if this object was destroyed; otherwise, false.
   *
   * @see OrderedGroundPrimitiveCollection#destroy
   */
  OrderedGroundPrimitiveCollection.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by each primitive in this collection.  Explicitly destroying this
   * collection allows for deterministic release of WebGL resources, instead of relying on the garbage
   * collector to destroy this collection.
   * <br /><br />
   * Since destroying a collection destroys all the contained primitives, only destroy a collection
   * when you are sure no other code is still using any of the contained primitives.
   * <br /><br />
   * Once this collection is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * primitives = primitives && primitives.destroy();
   *
   * @see OrderedGroundPrimitiveCollection#isDestroyed
   */
  OrderedGroundPrimitiveCollection.prototype.destroy = function () {
    this.removeAll();
    return destroyObject(this);
  };

  /**
   * @private
   */
  function DynamicGeometryBatch(primitives, orderedGroundPrimitives) {
    this._primitives = primitives;
    this._orderedGroundPrimitives = orderedGroundPrimitives;
    this._dynamicUpdaters = new AssociativeArray();
  }

  DynamicGeometryBatch.prototype.add = function (time, updater) {
    this._dynamicUpdaters.set(
      updater.id,
      updater.createDynamicUpdater(
        this._primitives,
        this._orderedGroundPrimitives
      )
    );
  };

  DynamicGeometryBatch.prototype.remove = function (updater) {
    const id = updater.id;
    const dynamicUpdater = this._dynamicUpdaters.get(id);
    if (defined(dynamicUpdater)) {
      this._dynamicUpdaters.remove(id);
      dynamicUpdater.destroy();
    }
  };

  DynamicGeometryBatch.prototype.update = function (time) {
    const geometries = this._dynamicUpdaters.values;
    for (let i = 0, len = geometries.length; i < len; i++) {
      geometries[i].update(time);
    }
    return true;
  };

  DynamicGeometryBatch.prototype.removeAllPrimitives = function () {
    const geometries = this._dynamicUpdaters.values;
    for (let i = 0, len = geometries.length; i < len; i++) {
      geometries[i].destroy();
    }
    this._dynamicUpdaters.removeAll();
  };

  DynamicGeometryBatch.prototype.getBoundingSphere = function (updater, result) {
    updater = this._dynamicUpdaters.get(updater.id);
    if (defined(updater) && defined(updater.getBoundingSphere)) {
      return updater.getBoundingSphere(result);
    }
    return BoundingSphereState$1.FAILED;
  };

  const scratchColor$b = new Color();
  const defaultOffset$6 = Cartesian3.ZERO;
  const offsetScratch$6 = new Cartesian3();
  const scratchRectangle$3 = new Rectangle();

  function EllipseGeometryOptions(entity) {
    this.id = entity;
    this.vertexFormat = undefined;
    this.center = undefined;
    this.semiMajorAxis = undefined;
    this.semiMinorAxis = undefined;
    this.rotation = undefined;
    this.height = undefined;
    this.extrudedHeight = undefined;
    this.granularity = undefined;
    this.stRotation = undefined;
    this.numberOfVerticalLines = undefined;
    this.offsetAttribute = undefined;
  }

  /**
   * A {@link GeometryUpdater} for ellipses.
   * Clients do not normally create this class directly, but instead rely on {@link DataSourceDisplay}.
   * @alias EllipseGeometryUpdater
   * @constructor
   *
   * @param {Entity} entity The entity containing the geometry to be visualized.
   * @param {Scene} scene The scene where visualization is taking place.
   */
  function EllipseGeometryUpdater(entity, scene) {
    GroundGeometryUpdater.call(this, {
      entity: entity,
      scene: scene,
      geometryOptions: new EllipseGeometryOptions(entity),
      geometryPropertyName: "ellipse",
      observedPropertyNames: ["availability", "position", "ellipse"],
    });

    this._onEntityPropertyChanged(entity, "ellipse", entity.ellipse, undefined);
  }

  if (defined(Object.create)) {
    EllipseGeometryUpdater.prototype = Object.create(
      GroundGeometryUpdater.prototype
    );
    EllipseGeometryUpdater.prototype.constructor = EllipseGeometryUpdater;
  }

  /**
   * Creates the geometry instance which represents the fill of the geometry.
   *
   * @param {JulianDate} time The time to use when retrieving initial attribute values.
   * @returns {GeometryInstance} The geometry instance representing the filled portion of the geometry.
   *
   * @exception {DeveloperError} This instance does not represent a filled geometry.
   */
  EllipseGeometryUpdater.prototype.createFillGeometryInstance = function (time) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("time", time);

    if (!this._fillEnabled) {
      throw new DeveloperError(
        "This instance does not represent a filled geometry."
      );
    }
    //>>includeEnd('debug');

    const entity = this._entity;
    const isAvailable = entity.isAvailable(time);

    const attributes = {
      show: new ShowGeometryInstanceAttribute(
        isAvailable &&
          entity.isShowing &&
          this._showProperty.getValue(time) &&
          this._fillProperty.getValue(time)
      ),
      distanceDisplayCondition: DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
        this._distanceDisplayConditionProperty.getValue(time)
      ),
      offset: undefined,
      color: undefined,
    };

    if (this._materialProperty instanceof ColorMaterialProperty) {
      let currentColor;
      if (
        defined(this._materialProperty.color) &&
        (this._materialProperty.color.isConstant || isAvailable)
      ) {
        currentColor = this._materialProperty.color.getValue(time, scratchColor$b);
      }
      if (!defined(currentColor)) {
        currentColor = Color.WHITE;
      }
      attributes.color = ColorGeometryInstanceAttribute.fromColor(currentColor);
    }

    if (defined(this._options.offsetAttribute)) {
      attributes.offset = OffsetGeometryInstanceAttribute.fromCartesian3(
        Property.getValueOrDefault(
          this._terrainOffsetProperty,
          time,
          defaultOffset$6,
          offsetScratch$6
        )
      );
    }

    return new GeometryInstance({
      id: entity,
      geometry: new EllipseGeometry(this._options),
      attributes: attributes,
    });
  };

  /**
   * Creates the geometry instance which represents the outline of the geometry.
   *
   * @param {JulianDate} time The time to use when retrieving initial attribute values.
   * @returns {GeometryInstance} The geometry instance representing the outline portion of the geometry.
   *
   * @exception {DeveloperError} This instance does not represent an outlined geometry.
   */
  EllipseGeometryUpdater.prototype.createOutlineGeometryInstance = function (
    time
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("time", time);

    if (!this._outlineEnabled) {
      throw new DeveloperError(
        "This instance does not represent an outlined geometry."
      );
    }
    //>>includeEnd('debug');

    const entity = this._entity;
    const isAvailable = entity.isAvailable(time);
    const outlineColor = Property.getValueOrDefault(
      this._outlineColorProperty,
      time,
      Color.BLACK,
      scratchColor$b
    );
    const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
      time
    );

    const attributes = {
      show: new ShowGeometryInstanceAttribute(
        isAvailable &&
          entity.isShowing &&
          this._showProperty.getValue(time) &&
          this._showOutlineProperty.getValue(time)
      ),
      color: ColorGeometryInstanceAttribute.fromColor(outlineColor),
      distanceDisplayCondition: DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
        distanceDisplayCondition
      ),
      offset: undefined,
    };

    if (defined(this._options.offsetAttribute)) {
      attributes.offset = OffsetGeometryInstanceAttribute.fromCartesian3(
        Property.getValueOrDefault(
          this._terrainOffsetProperty,
          time,
          defaultOffset$6,
          offsetScratch$6
        )
      );
    }

    return new GeometryInstance({
      id: entity,
      geometry: new EllipseOutlineGeometry(this._options),
      attributes: attributes,
    });
  };

  EllipseGeometryUpdater.prototype._computeCenter = function (time, result) {
    return Property.getValueOrUndefined(this._entity.position, time, result);
  };

  EllipseGeometryUpdater.prototype._isHidden = function (entity, ellipse) {
    const position = entity.position;

    return (
      !defined(position) ||
      !defined(ellipse.semiMajorAxis) ||
      !defined(ellipse.semiMinorAxis) ||
      GeometryUpdater.prototype._isHidden.call(this, entity, ellipse)
    );
  };

  EllipseGeometryUpdater.prototype._isDynamic = function (entity, ellipse) {
    return (
      !entity.position.isConstant || //
      !ellipse.semiMajorAxis.isConstant || //
      !ellipse.semiMinorAxis.isConstant || //
      !Property.isConstant(ellipse.rotation) || //
      !Property.isConstant(ellipse.height) || //
      !Property.isConstant(ellipse.extrudedHeight) || //
      !Property.isConstant(ellipse.granularity) || //
      !Property.isConstant(ellipse.stRotation) || //
      !Property.isConstant(ellipse.outlineWidth) || //
      !Property.isConstant(ellipse.numberOfVerticalLines) || //
      !Property.isConstant(ellipse.zIndex) || //
      (this._onTerrain &&
        !Property.isConstant(this._materialProperty) &&
        !(this._materialProperty instanceof ColorMaterialProperty))
    );
  };

  EllipseGeometryUpdater.prototype._setStaticOptions = function (
    entity,
    ellipse
  ) {
    let heightValue = Property.getValueOrUndefined(
      ellipse.height,
      Iso8601.MINIMUM_VALUE
    );
    const heightReferenceValue = Property.getValueOrDefault(
      ellipse.heightReference,
      Iso8601.MINIMUM_VALUE,
      HeightReference$1.NONE
    );
    let extrudedHeightValue = Property.getValueOrUndefined(
      ellipse.extrudedHeight,
      Iso8601.MINIMUM_VALUE
    );
    const extrudedHeightReferenceValue = Property.getValueOrDefault(
      ellipse.extrudedHeightReference,
      Iso8601.MINIMUM_VALUE,
      HeightReference$1.NONE
    );
    if (defined(extrudedHeightValue) && !defined(heightValue)) {
      heightValue = 0;
    }

    const options = this._options;
    options.vertexFormat =
      this._materialProperty instanceof ColorMaterialProperty
        ? PerInstanceColorAppearance.VERTEX_FORMAT
        : MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat;
    options.center = entity.position.getValue(
      Iso8601.MINIMUM_VALUE,
      options.center
    );
    options.semiMajorAxis = ellipse.semiMajorAxis.getValue(
      Iso8601.MINIMUM_VALUE,
      options.semiMajorAxis
    );
    options.semiMinorAxis = ellipse.semiMinorAxis.getValue(
      Iso8601.MINIMUM_VALUE,
      options.semiMinorAxis
    );
    options.rotation = Property.getValueOrUndefined(
      ellipse.rotation,
      Iso8601.MINIMUM_VALUE
    );
    options.granularity = Property.getValueOrUndefined(
      ellipse.granularity,
      Iso8601.MINIMUM_VALUE
    );
    options.stRotation = Property.getValueOrUndefined(
      ellipse.stRotation,
      Iso8601.MINIMUM_VALUE
    );
    options.numberOfVerticalLines = Property.getValueOrUndefined(
      ellipse.numberOfVerticalLines,
      Iso8601.MINIMUM_VALUE
    );
    options.offsetAttribute = GroundGeometryUpdater.computeGeometryOffsetAttribute(
      heightValue,
      heightReferenceValue,
      extrudedHeightValue,
      extrudedHeightReferenceValue
    );
    options.height = GroundGeometryUpdater.getGeometryHeight(
      heightValue,
      heightReferenceValue
    );

    extrudedHeightValue = GroundGeometryUpdater.getGeometryExtrudedHeight(
      extrudedHeightValue,
      extrudedHeightReferenceValue
    );
    if (extrudedHeightValue === GroundGeometryUpdater.CLAMP_TO_GROUND) {
      extrudedHeightValue = ApproximateTerrainHeights.getMinimumMaximumHeights(
        EllipseGeometry.computeRectangle(options, scratchRectangle$3)
      ).minimumTerrainHeight;
    }

    options.extrudedHeight = extrudedHeightValue;
  };

  EllipseGeometryUpdater.DynamicGeometryUpdater = DynamicEllipseGeometryUpdater;

  /**
   * @private
   */
  function DynamicEllipseGeometryUpdater(
    geometryUpdater,
    primitives,
    groundPrimitives
  ) {
    DynamicGeometryUpdater$1.call(
      this,
      geometryUpdater,
      primitives,
      groundPrimitives
    );
  }

  if (defined(Object.create)) {
    DynamicEllipseGeometryUpdater.prototype = Object.create(
      DynamicGeometryUpdater$1.prototype
    );
    DynamicEllipseGeometryUpdater.prototype.constructor = DynamicEllipseGeometryUpdater;
  }

  DynamicEllipseGeometryUpdater.prototype._isHidden = function (
    entity,
    ellipse,
    time
  ) {
    const options = this._options;
    return (
      !defined(options.center) ||
      !defined(options.semiMajorAxis) ||
      !defined(options.semiMinorAxis) ||
      DynamicGeometryUpdater$1.prototype._isHidden.call(this, entity, ellipse, time)
    );
  };

  DynamicEllipseGeometryUpdater.prototype._setOptions = function (
    entity,
    ellipse,
    time
  ) {
    const options = this._options;
    let heightValue = Property.getValueOrUndefined(ellipse.height, time);
    const heightReferenceValue = Property.getValueOrDefault(
      ellipse.heightReference,
      time,
      HeightReference$1.NONE
    );
    let extrudedHeightValue = Property.getValueOrUndefined(
      ellipse.extrudedHeight,
      time
    );
    const extrudedHeightReferenceValue = Property.getValueOrDefault(
      ellipse.extrudedHeightReference,
      time,
      HeightReference$1.NONE
    );
    if (defined(extrudedHeightValue) && !defined(heightValue)) {
      heightValue = 0;
    }

    options.center = Property.getValueOrUndefined(
      entity.position,
      time,
      options.center
    );
    options.semiMajorAxis = Property.getValueOrUndefined(
      ellipse.semiMajorAxis,
      time
    );
    options.semiMinorAxis = Property.getValueOrUndefined(
      ellipse.semiMinorAxis,
      time
    );
    options.rotation = Property.getValueOrUndefined(ellipse.rotation, time);
    options.granularity = Property.getValueOrUndefined(ellipse.granularity, time);
    options.stRotation = Property.getValueOrUndefined(ellipse.stRotation, time);
    options.numberOfVerticalLines = Property.getValueOrUndefined(
      ellipse.numberOfVerticalLines,
      time
    );
    options.offsetAttribute = GroundGeometryUpdater.computeGeometryOffsetAttribute(
      heightValue,
      heightReferenceValue,
      extrudedHeightValue,
      extrudedHeightReferenceValue
    );
    options.height = GroundGeometryUpdater.getGeometryHeight(
      heightValue,
      heightReferenceValue
    );

    extrudedHeightValue = GroundGeometryUpdater.getGeometryExtrudedHeight(
      extrudedHeightValue,
      extrudedHeightReferenceValue
    );
    if (extrudedHeightValue === GroundGeometryUpdater.CLAMP_TO_GROUND) {
      extrudedHeightValue = ApproximateTerrainHeights.getMinimumMaximumHeights(
        EllipseGeometry.computeRectangle(options, scratchRectangle$3)
      ).minimumTerrainHeight;
    }

    options.extrudedHeight = extrudedHeightValue;
  };

  const defaultMaterial$1 = new ColorMaterialProperty(Color.WHITE);
  const defaultOffset$5 = Cartesian3.ZERO;

  const offsetScratch$5 = new Cartesian3();
  const radiiScratch = new Cartesian3();
  const innerRadiiScratch = new Cartesian3();
  const scratchColor$a = new Color();
  const unitSphere = new Cartesian3(1, 1, 1);

  function EllipsoidGeometryOptions(entity) {
    this.id = entity;
    this.vertexFormat = undefined;
    this.radii = undefined;
    this.innerRadii = undefined;
    this.minimumClock = undefined;
    this.maximumClock = undefined;
    this.minimumCone = undefined;
    this.maximumCone = undefined;
    this.stackPartitions = undefined;
    this.slicePartitions = undefined;
    this.subdivisions = undefined;
    this.offsetAttribute = undefined;
  }

  /**
   * A {@link GeometryUpdater} for ellipsoids.
   * Clients do not normally create this class directly, but instead rely on {@link DataSourceDisplay}.
   * @alias EllipsoidGeometryUpdater
   * @constructor
   *
   * @param {Entity} entity The entity containing the geometry to be visualized.
   * @param {Scene} scene The scene where visualization is taking place.
   */
  function EllipsoidGeometryUpdater(entity, scene) {
    GeometryUpdater.call(this, {
      entity: entity,
      scene: scene,
      geometryOptions: new EllipsoidGeometryOptions(entity),
      geometryPropertyName: "ellipsoid",
      observedPropertyNames: [
        "availability",
        "position",
        "orientation",
        "ellipsoid",
      ],
    });

    this._onEntityPropertyChanged(
      entity,
      "ellipsoid",
      entity.ellipsoid,
      undefined
    );
  }

  if (defined(Object.create)) {
    EllipsoidGeometryUpdater.prototype = Object.create(GeometryUpdater.prototype);
    EllipsoidGeometryUpdater.prototype.constructor = EllipsoidGeometryUpdater;
  }

  Object.defineProperties(EllipsoidGeometryUpdater.prototype, {
    /**
     * Gets the terrain offset property
     * @type {TerrainOffsetProperty}
     * @memberof EllipsoidGeometryUpdater.prototype
     * @readonly
     * @private
     */
    terrainOffsetProperty: {
      get: function () {
        return this._terrainOffsetProperty;
      },
    },
  });

  /**
   * Creates the geometry instance which represents the fill of the geometry.
   *
   * @param {JulianDate} time The time to use when retrieving initial attribute values.
   * @param {Boolean} [skipModelMatrix=false] Whether to compute a model matrix for the geometry instance
   * @param {Matrix4} [modelMatrixResult] Used to store the result of the model matrix calculation
   * @returns {GeometryInstance} The geometry instance representing the filled portion of the geometry.
   *
   * @exception {DeveloperError} This instance does not represent a filled geometry.
   */
  EllipsoidGeometryUpdater.prototype.createFillGeometryInstance = function (
    time,
    skipModelMatrix,
    modelMatrixResult
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("time", time);
    //>>includeEnd('debug');

    const entity = this._entity;
    const isAvailable = entity.isAvailable(time);

    let color;
    const show = new ShowGeometryInstanceAttribute(
      isAvailable &&
        entity.isShowing &&
        this._showProperty.getValue(time) &&
        this._fillProperty.getValue(time)
    );
    const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
      time
    );
    const distanceDisplayConditionAttribute = DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
      distanceDisplayCondition
    );

    const attributes = {
      show: show,
      distanceDisplayCondition: distanceDisplayConditionAttribute,
      color: undefined,
      offset: undefined,
    };

    if (this._materialProperty instanceof ColorMaterialProperty) {
      let currentColor;
      if (
        defined(this._materialProperty.color) &&
        (this._materialProperty.color.isConstant || isAvailable)
      ) {
        currentColor = this._materialProperty.color.getValue(time, scratchColor$a);
      }
      if (!defined(currentColor)) {
        currentColor = Color.WHITE;
      }
      color = ColorGeometryInstanceAttribute.fromColor(currentColor);
      attributes.color = color;
    }
    if (defined(this._options.offsetAttribute)) {
      attributes.offset = OffsetGeometryInstanceAttribute.fromCartesian3(
        Property.getValueOrDefault(
          this._terrainOffsetProperty,
          time,
          defaultOffset$5,
          offsetScratch$5
        )
      );
    }

    return new GeometryInstance({
      id: entity,
      geometry: new EllipsoidGeometry(this._options),
      modelMatrix: skipModelMatrix
        ? undefined
        : entity.computeModelMatrixForHeightReference(
            time,
            entity.ellipsoid.heightReference,
            this._options.radii.z * 0.5,
            this._scene.mapProjection.ellipsoid,
            modelMatrixResult
          ),
      attributes: attributes,
    });
  };

  /**
   * Creates the geometry instance which represents the outline of the geometry.
   *
   * @param {JulianDate} time The time to use when retrieving initial attribute values.
   * @param {Boolean} [skipModelMatrix=false] Whether to compute a model matrix for the geometry instance
   * @param {Matrix4} [modelMatrixResult] Used to store the result of the model matrix calculation
   * @returns {GeometryInstance} The geometry instance representing the outline portion of the geometry.
   *
   * @exception {DeveloperError} This instance does not represent an outlined geometry.
   */
  EllipsoidGeometryUpdater.prototype.createOutlineGeometryInstance = function (
    time,
    skipModelMatrix,
    modelMatrixResult
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("time", time);
    //>>includeEnd('debug');

    const entity = this._entity;
    const isAvailable = entity.isAvailable(time);

    const outlineColor = Property.getValueOrDefault(
      this._outlineColorProperty,
      time,
      Color.BLACK,
      scratchColor$a
    );
    const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
      time
    );

    const attributes = {
      show: new ShowGeometryInstanceAttribute(
        isAvailable &&
          entity.isShowing &&
          this._showProperty.getValue(time) &&
          this._showOutlineProperty.getValue(time)
      ),
      color: ColorGeometryInstanceAttribute.fromColor(outlineColor),
      distanceDisplayCondition: DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
        distanceDisplayCondition
      ),
      offset: undefined,
    };
    if (defined(this._options.offsetAttribute)) {
      attributes.offset = OffsetGeometryInstanceAttribute.fromCartesian3(
        Property.getValueOrDefault(
          this._terrainOffsetProperty,
          time,
          defaultOffset$5,
          offsetScratch$5
        )
      );
    }

    return new GeometryInstance({
      id: entity,
      geometry: new EllipsoidOutlineGeometry(this._options),
      modelMatrix: skipModelMatrix
        ? undefined
        : entity.computeModelMatrixForHeightReference(
            time,
            entity.ellipsoid.heightReference,
            this._options.radii.z * 0.5,
            this._scene.mapProjection.ellipsoid,
            modelMatrixResult
          ),
      attributes: attributes,
    });
  };

  EllipsoidGeometryUpdater.prototype._computeCenter = function (time, result) {
    return Property.getValueOrUndefined(this._entity.position, time, result);
  };

  EllipsoidGeometryUpdater.prototype._isHidden = function (entity, ellipsoid) {
    return (
      !defined(entity.position) ||
      !defined(ellipsoid.radii) ||
      GeometryUpdater.prototype._isHidden.call(this, entity, ellipsoid)
    );
  };

  EllipsoidGeometryUpdater.prototype._isDynamic = function (entity, ellipsoid) {
    return (
      !entity.position.isConstant || //
      !Property.isConstant(entity.orientation) || //
      !ellipsoid.radii.isConstant || //
      !Property.isConstant(ellipsoid.innerRadii) || //
      !Property.isConstant(ellipsoid.stackPartitions) || //
      !Property.isConstant(ellipsoid.slicePartitions) || //
      !Property.isConstant(ellipsoid.outlineWidth) || //
      !Property.isConstant(ellipsoid.minimumClock) || //
      !Property.isConstant(ellipsoid.maximumClock) || //
      !Property.isConstant(ellipsoid.minimumCone) || //
      !Property.isConstant(ellipsoid.maximumCone) || //
      !Property.isConstant(ellipsoid.subdivisions)
    );
  };

  EllipsoidGeometryUpdater.prototype._setStaticOptions = function (
    entity,
    ellipsoid
  ) {
    const heightReference = Property.getValueOrDefault(
      ellipsoid.heightReference,
      Iso8601.MINIMUM_VALUE,
      HeightReference$1.NONE
    );
    const options = this._options;
    options.vertexFormat =
      this._materialProperty instanceof ColorMaterialProperty
        ? PerInstanceColorAppearance.VERTEX_FORMAT
        : MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat;
    options.radii = ellipsoid.radii.getValue(
      Iso8601.MINIMUM_VALUE,
      options.radii
    );
    options.innerRadii = Property.getValueOrUndefined(
      ellipsoid.innerRadii,
      options.radii
    );
    options.minimumClock = Property.getValueOrUndefined(
      ellipsoid.minimumClock,
      Iso8601.MINIMUM_VALUE
    );
    options.maximumClock = Property.getValueOrUndefined(
      ellipsoid.maximumClock,
      Iso8601.MINIMUM_VALUE
    );
    options.minimumCone = Property.getValueOrUndefined(
      ellipsoid.minimumCone,
      Iso8601.MINIMUM_VALUE
    );
    options.maximumCone = Property.getValueOrUndefined(
      ellipsoid.maximumCone,
      Iso8601.MINIMUM_VALUE
    );
    options.stackPartitions = Property.getValueOrUndefined(
      ellipsoid.stackPartitions,
      Iso8601.MINIMUM_VALUE
    );
    options.slicePartitions = Property.getValueOrUndefined(
      ellipsoid.slicePartitions,
      Iso8601.MINIMUM_VALUE
    );
    options.subdivisions = Property.getValueOrUndefined(
      ellipsoid.subdivisions,
      Iso8601.MINIMUM_VALUE
    );
    options.offsetAttribute =
      heightReference !== HeightReference$1.NONE
        ? GeometryOffsetAttribute$1.ALL
        : undefined;
  };

  EllipsoidGeometryUpdater.prototype._onEntityPropertyChanged = heightReferenceOnEntityPropertyChanged;

  EllipsoidGeometryUpdater.DynamicGeometryUpdater = DynamicEllipsoidGeometryUpdater;

  /**
   * @private
   */
  function DynamicEllipsoidGeometryUpdater(
    geometryUpdater,
    primitives,
    groundPrimitives
  ) {
    DynamicGeometryUpdater$1.call(
      this,
      geometryUpdater,
      primitives,
      groundPrimitives
    );

    this._scene = geometryUpdater._scene;
    this._modelMatrix = new Matrix4();
    this._attributes = undefined;
    this._outlineAttributes = undefined;
    this._lastSceneMode = undefined;
    this._lastShow = undefined;
    this._lastOutlineShow = undefined;
    this._lastOutlineWidth = undefined;
    this._lastOutlineColor = undefined;
    this._lastOffset = new Cartesian3();
    this._material = {};
  }

  if (defined(Object.create)) {
    DynamicEllipsoidGeometryUpdater.prototype = Object.create(
      DynamicGeometryUpdater$1.prototype
    );
    DynamicEllipsoidGeometryUpdater.prototype.constructor = DynamicEllipsoidGeometryUpdater;
  }

  DynamicEllipsoidGeometryUpdater.prototype.update = function (time) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("time", time);
    //>>includeEnd('debug');

    const entity = this._entity;
    const ellipsoid = entity.ellipsoid;
    if (
      !entity.isShowing ||
      !entity.isAvailable(time) ||
      !Property.getValueOrDefault(ellipsoid.show, time, true)
    ) {
      if (defined(this._primitive)) {
        this._primitive.show = false;
      }

      if (defined(this._outlinePrimitive)) {
        this._outlinePrimitive.show = false;
      }
      return;
    }

    const radii = Property.getValueOrUndefined(
      ellipsoid.radii,
      time,
      radiiScratch
    );
    let modelMatrix = defined(radii)
      ? entity.computeModelMatrixForHeightReference(
          time,
          ellipsoid.heightReference,
          radii.z * 0.5,
          this._scene.mapProjection.ellipsoid,
          this._modelMatrix
        )
      : undefined;
    if (!defined(modelMatrix) || !defined(radii)) {
      if (defined(this._primitive)) {
        this._primitive.show = false;
      }

      if (defined(this._outlinePrimitive)) {
        this._outlinePrimitive.show = false;
      }
      return;
    }

    //Compute attributes and material.
    const showFill = Property.getValueOrDefault(ellipsoid.fill, time, true);
    const showOutline = Property.getValueOrDefault(
      ellipsoid.outline,
      time,
      false
    );
    const outlineColor = Property.getValueOrClonedDefault(
      ellipsoid.outlineColor,
      time,
      Color.BLACK,
      scratchColor$a
    );
    const material = MaterialProperty.getValue(
      time,
      defaultValue(ellipsoid.material, defaultMaterial$1),
      this._material
    );

    // Check properties that could trigger a primitive rebuild.
    const innerRadii = Property.getValueOrUndefined(
      ellipsoid.innerRadii,
      time,
      innerRadiiScratch
    );
    const minimumClock = Property.getValueOrUndefined(
      ellipsoid.minimumClock,
      time
    );
    const maximumClock = Property.getValueOrUndefined(
      ellipsoid.maximumClock,
      time
    );
    const minimumCone = Property.getValueOrUndefined(ellipsoid.minimumCone, time);
    const maximumCone = Property.getValueOrUndefined(ellipsoid.maximumCone, time);
    const stackPartitions = Property.getValueOrUndefined(
      ellipsoid.stackPartitions,
      time
    );
    const slicePartitions = Property.getValueOrUndefined(
      ellipsoid.slicePartitions,
      time
    );
    const subdivisions = Property.getValueOrUndefined(
      ellipsoid.subdivisions,
      time
    );
    const outlineWidth = Property.getValueOrDefault(
      ellipsoid.outlineWidth,
      time,
      1.0
    );
    const heightReference = Property.getValueOrDefault(
      ellipsoid.heightReference,
      time,
      HeightReference$1.NONE
    );
    const offsetAttribute =
      heightReference !== HeightReference$1.NONE
        ? GeometryOffsetAttribute$1.ALL
        : undefined;

    //In 3D we use a fast path by modifying Primitive.modelMatrix instead of regenerating the primitive every frame.
    //Also check for height reference because this method doesn't work when the height is relative to terrain.
    const sceneMode = this._scene.mode;
    const in3D =
      sceneMode === SceneMode$1.SCENE3D && heightReference === HeightReference$1.NONE;

    const options = this._options;

    const shadows = this._geometryUpdater.shadowsProperty.getValue(time);

    const distanceDisplayConditionProperty = this._geometryUpdater
      .distanceDisplayConditionProperty;
    const distanceDisplayCondition = distanceDisplayConditionProperty.getValue(
      time
    );

    const offset = Property.getValueOrDefault(
      this._geometryUpdater.terrainOffsetProperty,
      time,
      defaultOffset$5,
      offsetScratch$5
    );

    //We only rebuild the primitive if something other than the radii has changed
    //For the radii, we use unit sphere and then deform it with a scale matrix.
    const rebuildPrimitives =
      !in3D ||
      this._lastSceneMode !== sceneMode ||
      !defined(this._primitive) || //
      options.stackPartitions !== stackPartitions ||
      options.slicePartitions !== slicePartitions || //
      (defined(innerRadii) &&
        !Cartesian3.equals(options.innerRadii !== innerRadii)) ||
      options.minimumClock !== minimumClock || //
      options.maximumClock !== maximumClock ||
      options.minimumCone !== minimumCone || //
      options.maximumCone !== maximumCone ||
      options.subdivisions !== subdivisions || //
      this._lastOutlineWidth !== outlineWidth ||
      options.offsetAttribute !== offsetAttribute;

    if (rebuildPrimitives) {
      const primitives = this._primitives;
      primitives.removeAndDestroy(this._primitive);
      primitives.removeAndDestroy(this._outlinePrimitive);
      this._primitive = undefined;
      this._outlinePrimitive = undefined;
      this._lastSceneMode = sceneMode;
      this._lastOutlineWidth = outlineWidth;

      options.stackPartitions = stackPartitions;
      options.slicePartitions = slicePartitions;
      options.subdivisions = subdivisions;
      options.offsetAttribute = offsetAttribute;
      options.radii = Cartesian3.clone(in3D ? unitSphere : radii, options.radii);
      if (defined(innerRadii)) {
        if (in3D) {
          const mag = Cartesian3.magnitude(radii);
          options.innerRadii = Cartesian3.fromElements(
            innerRadii.x / mag,
            innerRadii.y / mag,
            innerRadii.z / mag,
            options.innerRadii
          );
        } else {
          options.innerRadii = Cartesian3.clone(innerRadii, options.innerRadii);
        }
      } else {
        options.innerRadii = undefined;
      }
      options.minimumClock = minimumClock;
      options.maximumClock = maximumClock;
      options.minimumCone = minimumCone;
      options.maximumCone = maximumCone;

      const appearance = new MaterialAppearance({
        material: material,
        translucent: material.isTranslucent(),
        closed: true,
      });
      options.vertexFormat = appearance.vertexFormat;

      const fillInstance = this._geometryUpdater.createFillGeometryInstance(
        time,
        in3D,
        this._modelMatrix
      );

      this._primitive = primitives.add(
        new Primitive$3({
          geometryInstances: fillInstance,
          appearance: appearance,
          asynchronous: false,
          shadows: shadows,
        })
      );

      const outlineInstance = this._geometryUpdater.createOutlineGeometryInstance(
        time,
        in3D,
        this._modelMatrix
      );
      this._outlinePrimitive = primitives.add(
        new Primitive$3({
          geometryInstances: outlineInstance,
          appearance: new PerInstanceColorAppearance({
            flat: true,
            translucent: outlineInstance.attributes.color.value[3] !== 255,
            renderState: {
              lineWidth: this._geometryUpdater._scene.clampLineWidth(
                outlineWidth
              ),
            },
          }),
          asynchronous: false,
          shadows: shadows,
        })
      );

      this._lastShow = showFill;
      this._lastOutlineShow = showOutline;
      this._lastOutlineColor = Color.clone(outlineColor, this._lastOutlineColor);
      this._lastDistanceDisplayCondition = distanceDisplayCondition;
      this._lastOffset = Cartesian3.clone(offset, this._lastOffset);
    } else if (this._primitive.ready) {
      //Update attributes only.
      const primitive = this._primitive;
      const outlinePrimitive = this._outlinePrimitive;

      primitive.show = true;
      outlinePrimitive.show = true;
      primitive.appearance.material = material;

      let attributes = this._attributes;
      if (!defined(attributes)) {
        attributes = primitive.getGeometryInstanceAttributes(entity);
        this._attributes = attributes;
      }
      if (showFill !== this._lastShow) {
        attributes.show = ShowGeometryInstanceAttribute.toValue(
          showFill,
          attributes.show
        );
        this._lastShow = showFill;
      }

      let outlineAttributes = this._outlineAttributes;

      if (!defined(outlineAttributes)) {
        outlineAttributes = outlinePrimitive.getGeometryInstanceAttributes(
          entity
        );
        this._outlineAttributes = outlineAttributes;
      }

      if (showOutline !== this._lastOutlineShow) {
        outlineAttributes.show = ShowGeometryInstanceAttribute.toValue(
          showOutline,
          outlineAttributes.show
        );
        this._lastOutlineShow = showOutline;
      }

      if (!Color.equals(outlineColor, this._lastOutlineColor)) {
        outlineAttributes.color = ColorGeometryInstanceAttribute.toValue(
          outlineColor,
          outlineAttributes.color
        );
        Color.clone(outlineColor, this._lastOutlineColor);
      }

      if (
        !DistanceDisplayCondition.equals(
          distanceDisplayCondition,
          this._lastDistanceDisplayCondition
        )
      ) {
        attributes.distanceDisplayCondition = DistanceDisplayConditionGeometryInstanceAttribute.toValue(
          distanceDisplayCondition,
          attributes.distanceDisplayCondition
        );
        outlineAttributes.distanceDisplayCondition = DistanceDisplayConditionGeometryInstanceAttribute.toValue(
          distanceDisplayCondition,
          outlineAttributes.distanceDisplayCondition
        );
        DistanceDisplayCondition.clone(
          distanceDisplayCondition,
          this._lastDistanceDisplayCondition
        );
      }

      if (!Cartesian3.equals(offset, this._lastOffset)) {
        attributes.offset = OffsetGeometryInstanceAttribute.toValue(
          offset,
          attributes.offset
        );
        outlineAttributes.offset = OffsetGeometryInstanceAttribute.toValue(
          offset,
          attributes.offset
        );
        Cartesian3.clone(offset, this._lastOffset);
      }
    }

    if (in3D) {
      //Since we are scaling a unit sphere, we can't let any of the values go to zero.
      //Instead we clamp them to a small value.  To the naked eye, this produces the same results
      //that you get passing EllipsoidGeometry a radii with a zero component.
      radii.x = Math.max(radii.x, 0.001);
      radii.y = Math.max(radii.y, 0.001);
      radii.z = Math.max(radii.z, 0.001);

      modelMatrix = Matrix4.multiplyByScale(modelMatrix, radii, modelMatrix);
      this._primitive.modelMatrix = modelMatrix;
      this._outlinePrimitive.modelMatrix = modelMatrix;
    }
  };

  const positionScratch$2 = new Cartesian3();
  const scratchColor$9 = new Color();

  function PlaneGeometryOptions(entity) {
    this.id = entity;
    this.vertexFormat = undefined;
    this.plane = undefined;
    this.dimensions = undefined;
  }

  /**
   * A {@link GeometryUpdater} for planes.
   * Clients do not normally create this class directly, but instead rely on {@link DataSourceDisplay}.
   * @alias PlaneGeometryUpdater
   * @constructor
   *
   * @param {Entity} entity The entity containing the geometry to be visualized.
   * @param {Scene} scene The scene where visualization is taking place.
   */
  function PlaneGeometryUpdater(entity, scene) {
    GeometryUpdater.call(this, {
      entity: entity,
      scene: scene,
      geometryOptions: new PlaneGeometryOptions(entity),
      geometryPropertyName: "plane",
      observedPropertyNames: ["availability", "position", "orientation", "plane"],
    });

    this._onEntityPropertyChanged(entity, "plane", entity.plane, undefined);
  }

  if (defined(Object.create)) {
    PlaneGeometryUpdater.prototype = Object.create(GeometryUpdater.prototype);
    PlaneGeometryUpdater.prototype.constructor = PlaneGeometryUpdater;
  }

  /**
   * Creates the geometry instance which represents the fill of the geometry.
   *
   * @param {JulianDate} time The time to use when retrieving initial attribute values.
   * @returns {GeometryInstance} The geometry instance representing the filled portion of the geometry.
   *
   * @exception {DeveloperError} This instance does not represent a filled geometry.
   */
  PlaneGeometryUpdater.prototype.createFillGeometryInstance = function (time) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("time", time);

    if (!this._fillEnabled) {
      throw new DeveloperError(
        "This instance does not represent a filled geometry."
      );
    }
    //>>includeEnd('debug');

    const entity = this._entity;
    const isAvailable = entity.isAvailable(time);

    let attributes;

    let color;
    const show = new ShowGeometryInstanceAttribute(
      isAvailable &&
        entity.isShowing &&
        this._showProperty.getValue(time) &&
        this._fillProperty.getValue(time)
    );
    const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
      time
    );
    const distanceDisplayConditionAttribute = DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
      distanceDisplayCondition
    );
    if (this._materialProperty instanceof ColorMaterialProperty) {
      let currentColor;
      if (
        defined(this._materialProperty.color) &&
        (this._materialProperty.color.isConstant || isAvailable)
      ) {
        currentColor = this._materialProperty.color.getValue(time, scratchColor$9);
      }
      if (!defined(currentColor)) {
        currentColor = Color.WHITE;
      }
      color = ColorGeometryInstanceAttribute.fromColor(currentColor);
      attributes = {
        show: show,
        distanceDisplayCondition: distanceDisplayConditionAttribute,
        color: color,
      };
    } else {
      attributes = {
        show: show,
        distanceDisplayCondition: distanceDisplayConditionAttribute,
      };
    }

    const planeGraphics = entity.plane;
    const options = this._options;
    let modelMatrix = entity.computeModelMatrix(time);
    const plane = Property.getValueOrDefault(
      planeGraphics.plane,
      time,
      options.plane
    );
    const dimensions = Property.getValueOrUndefined(
      planeGraphics.dimensions,
      time,
      options.dimensions
    );

    options.plane = plane;
    options.dimensions = dimensions;

    modelMatrix = createPrimitiveMatrix(
      plane,
      dimensions,
      modelMatrix,
      modelMatrix
    );

    return new GeometryInstance({
      id: entity,
      geometry: new PlaneGeometry(this._options),
      modelMatrix: modelMatrix,
      attributes: attributes,
    });
  };

  /**
   * Creates the geometry instance which represents the outline of the geometry.
   *
   * @param {JulianDate} time The time to use when retrieving initial attribute values.
   * @returns {GeometryInstance} The geometry instance representing the outline portion of the geometry.
   *
   * @exception {DeveloperError} This instance does not represent an outlined geometry.
   */
  PlaneGeometryUpdater.prototype.createOutlineGeometryInstance = function (time) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("time", time);

    if (!this._outlineEnabled) {
      throw new DeveloperError(
        "This instance does not represent an outlined geometry."
      );
    }
    //>>includeEnd('debug');

    const entity = this._entity;
    const isAvailable = entity.isAvailable(time);
    const outlineColor = Property.getValueOrDefault(
      this._outlineColorProperty,
      time,
      Color.BLACK,
      scratchColor$9
    );
    const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
      time
    );

    const planeGraphics = entity.plane;
    const options = this._options;
    let modelMatrix = entity.computeModelMatrix(time);
    const plane = Property.getValueOrDefault(
      planeGraphics.plane,
      time,
      options.plane
    );
    const dimensions = Property.getValueOrUndefined(
      planeGraphics.dimensions,
      time,
      options.dimensions
    );

    options.plane = plane;
    options.dimensions = dimensions;

    modelMatrix = createPrimitiveMatrix(
      plane,
      dimensions,
      modelMatrix,
      modelMatrix
    );

    return new GeometryInstance({
      id: entity,
      geometry: new PlaneOutlineGeometry(),
      modelMatrix: modelMatrix,
      attributes: {
        show: new ShowGeometryInstanceAttribute(
          isAvailable &&
            entity.isShowing &&
            this._showProperty.getValue(time) &&
            this._showOutlineProperty.getValue(time)
        ),
        color: ColorGeometryInstanceAttribute.fromColor(outlineColor),
        distanceDisplayCondition: DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
          distanceDisplayCondition
        ),
      },
    });
  };

  PlaneGeometryUpdater.prototype._isHidden = function (entity, plane) {
    return (
      !defined(plane.plane) ||
      !defined(plane.dimensions) ||
      !defined(entity.position) ||
      GeometryUpdater.prototype._isHidden.call(this, entity, plane)
    );
  };

  PlaneGeometryUpdater.prototype._getIsClosed = function (options) {
    return false;
  };

  PlaneGeometryUpdater.prototype._isDynamic = function (entity, plane) {
    return (
      !entity.position.isConstant || //
      !Property.isConstant(entity.orientation) || //
      !plane.plane.isConstant || //
      !plane.dimensions.isConstant || //
      !Property.isConstant(plane.outlineWidth)
    );
  };

  PlaneGeometryUpdater.prototype._setStaticOptions = function (entity, plane) {
    const isColorMaterial =
      this._materialProperty instanceof ColorMaterialProperty;

    const options = this._options;
    options.vertexFormat = isColorMaterial
      ? PerInstanceColorAppearance.VERTEX_FORMAT
      : MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat;
    options.plane = plane.plane.getValue(Iso8601.MINIMUM_VALUE, options.plane);
    options.dimensions = plane.dimensions.getValue(
      Iso8601.MINIMUM_VALUE,
      options.dimensions
    );
  };

  PlaneGeometryUpdater.DynamicGeometryUpdater = DynamicPlaneGeometryUpdater;

  /**
   * @private
   */
  function DynamicPlaneGeometryUpdater(
    geometryUpdater,
    primitives,
    groundPrimitives
  ) {
    DynamicGeometryUpdater$1.call(
      this,
      geometryUpdater,
      primitives,
      groundPrimitives
    );
  }

  if (defined(Object.create)) {
    DynamicPlaneGeometryUpdater.prototype = Object.create(
      DynamicGeometryUpdater$1.prototype
    );
    DynamicPlaneGeometryUpdater.prototype.constructor = DynamicPlaneGeometryUpdater;
  }

  DynamicPlaneGeometryUpdater.prototype._isHidden = function (
    entity,
    plane,
    time
  ) {
    const options = this._options;
    const position = Property.getValueOrUndefined(
      entity.position,
      time,
      positionScratch$2
    );
    return (
      !defined(position) ||
      !defined(options.plane) ||
      !defined(options.dimensions) ||
      DynamicGeometryUpdater$1.prototype._isHidden.call(this, entity, plane, time)
    );
  };

  DynamicPlaneGeometryUpdater.prototype._setOptions = function (
    entity,
    plane,
    time
  ) {
    const options = this._options;
    options.plane = Property.getValueOrDefault(plane.plane, time, options.plane);
    options.dimensions = Property.getValueOrUndefined(
      plane.dimensions,
      time,
      options.dimensions
    );
  };

  const scratchAxis = new Cartesian3();
  const scratchUp$2 = new Cartesian3();
  const scratchTranslation$1 = new Cartesian3();
  const scratchScale$1 = new Cartesian3();
  const scratchRotation$1 = new Matrix3();
  const scratchRotationScale = new Matrix3();
  const scratchLocalTransform = new Matrix4();
  function createPrimitiveMatrix(plane, dimensions, transform, result) {
    const normal = plane.normal;
    const distance = plane.distance;

    const translation = Cartesian3.multiplyByScalar(
      normal,
      -distance,
      scratchTranslation$1
    );

    let up = Cartesian3.clone(Cartesian3.UNIT_Z, scratchUp$2);
    if (
      CesiumMath.equalsEpsilon(
        Math.abs(Cartesian3.dot(up, normal)),
        1.0,
        CesiumMath.EPSILON8
      )
    ) {
      up = Cartesian3.clone(Cartesian3.UNIT_Y, up);
    }

    const left = Cartesian3.cross(up, normal, scratchAxis);
    up = Cartesian3.cross(normal, left, up);
    Cartesian3.normalize(left, left);
    Cartesian3.normalize(up, up);

    const rotationMatrix = scratchRotation$1;
    Matrix3.setColumn(rotationMatrix, 0, left, rotationMatrix);
    Matrix3.setColumn(rotationMatrix, 1, up, rotationMatrix);
    Matrix3.setColumn(rotationMatrix, 2, normal, rotationMatrix);

    const scale = Cartesian3.fromElements(
      dimensions.x,
      dimensions.y,
      1.0,
      scratchScale$1
    );
    const rotationScaleMatrix = Matrix3.multiplyByScale(
      rotationMatrix,
      scale,
      scratchRotationScale
    );

    const localTransform = Matrix4.fromRotationTranslation(
      rotationScaleMatrix,
      translation,
      scratchLocalTransform
    );
    return Matrix4.multiplyTransformation(transform, localTransform, result);
  }

  /**
   * @private
   */
  PlaneGeometryUpdater.createPrimitiveMatrix = createPrimitiveMatrix;

  const heightAndPerPositionHeightWarning =
    "Entity polygons cannot have both height and perPositionHeight.  height will be ignored";
  const heightReferenceAndPerPositionHeightWarning =
    "heightReference is not supported for entity polygons with perPositionHeight. heightReference will be ignored";

  const scratchColor$8 = new Color();
  const defaultOffset$4 = Cartesian3.ZERO;
  const offsetScratch$4 = new Cartesian3();
  const scratchRectangle$2 = new Rectangle();
  const scratch2DPositions = [];
  const cart2Scratch = new Cartesian2();

  function PolygonGeometryOptions(entity) {
    this.id = entity;
    this.vertexFormat = undefined;
    this.polygonHierarchy = undefined;
    this.perPositionHeight = undefined;
    this.closeTop = undefined;
    this.closeBottom = undefined;
    this.height = undefined;
    this.extrudedHeight = undefined;
    this.granularity = undefined;
    this.stRotation = undefined;
    this.offsetAttribute = undefined;
    this.arcType = undefined;
    this.textureCoordinates = undefined;
  }

  /**
   * A {@link GeometryUpdater} for polygons.
   * Clients do not normally create this class directly, but instead rely on {@link DataSourceDisplay}.
   * @alias PolygonGeometryUpdater
   * @constructor
   *
   * @param {Entity} entity The entity containing the geometry to be visualized.
   * @param {Scene} scene The scene where visualization is taking place.
   */
  function PolygonGeometryUpdater(entity, scene) {
    GroundGeometryUpdater.call(this, {
      entity: entity,
      scene: scene,
      geometryOptions: new PolygonGeometryOptions(entity),
      geometryPropertyName: "polygon",
      observedPropertyNames: ["availability", "polygon"],
    });

    this._onEntityPropertyChanged(entity, "polygon", entity.polygon, undefined);
  }

  if (defined(Object.create)) {
    PolygonGeometryUpdater.prototype = Object.create(
      GroundGeometryUpdater.prototype
    );
    PolygonGeometryUpdater.prototype.constructor = PolygonGeometryUpdater;
  }

  /**
   * Creates the geometry instance which represents the fill of the geometry.
   *
   * @param {JulianDate} time The time to use when retrieving initial attribute values.
   * @returns {GeometryInstance} The geometry instance representing the filled portion of the geometry.
   *
   * @exception {DeveloperError} This instance does not represent a filled geometry.
   */
  PolygonGeometryUpdater.prototype.createFillGeometryInstance = function (time) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("time", time);

    if (!this._fillEnabled) {
      throw new DeveloperError(
        "This instance does not represent a filled geometry."
      );
    }
    //>>includeEnd('debug');

    const entity = this._entity;
    const isAvailable = entity.isAvailable(time);
    const options = this._options;

    const attributes = {
      show: new ShowGeometryInstanceAttribute(
        isAvailable &&
          entity.isShowing &&
          this._showProperty.getValue(time) &&
          this._fillProperty.getValue(time)
      ),
      distanceDisplayCondition: DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
        this._distanceDisplayConditionProperty.getValue(time)
      ),
      offset: undefined,
      color: undefined,
    };

    if (this._materialProperty instanceof ColorMaterialProperty) {
      let currentColor;
      if (
        defined(this._materialProperty.color) &&
        (this._materialProperty.color.isConstant || isAvailable)
      ) {
        currentColor = this._materialProperty.color.getValue(time, scratchColor$8);
      }
      if (!defined(currentColor)) {
        currentColor = Color.WHITE;
      }
      attributes.color = ColorGeometryInstanceAttribute.fromColor(currentColor);
    }
    if (defined(options.offsetAttribute)) {
      attributes.offset = OffsetGeometryInstanceAttribute.fromCartesian3(
        Property.getValueOrDefault(
          this._terrainOffsetProperty,
          time,
          defaultOffset$4,
          offsetScratch$4
        )
      );
    }

    let geometry;
    if (options.perPositionHeight && !defined(options.extrudedHeight)) {
      geometry = new CoplanarPolygonGeometry(options);
    } else {
      geometry = new PolygonGeometry(options);
    }

    return new GeometryInstance({
      id: entity,
      geometry: geometry,
      attributes: attributes,
    });
  };

  /**
   * Creates the geometry instance which represents the outline of the geometry.
   *
   * @param {JulianDate} time The time to use when retrieving initial attribute values.
   * @returns {GeometryInstance} The geometry instance representing the outline portion of the geometry.
   *
   * @exception {DeveloperError} This instance does not represent an outlined geometry.
   */
  PolygonGeometryUpdater.prototype.createOutlineGeometryInstance = function (
    time
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("time", time);

    if (!this._outlineEnabled) {
      throw new DeveloperError(
        "This instance does not represent an outlined geometry."
      );
    }
    //>>includeEnd('debug');

    const entity = this._entity;
    const isAvailable = entity.isAvailable(time);
    const options = this._options;
    const outlineColor = Property.getValueOrDefault(
      this._outlineColorProperty,
      time,
      Color.BLACK,
      scratchColor$8
    );
    const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
      time
    );

    const attributes = {
      show: new ShowGeometryInstanceAttribute(
        isAvailable &&
          entity.isShowing &&
          this._showProperty.getValue(time) &&
          this._showOutlineProperty.getValue(time)
      ),
      color: ColorGeometryInstanceAttribute.fromColor(outlineColor),
      distanceDisplayCondition: DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
        distanceDisplayCondition
      ),
      offset: undefined,
    };

    if (defined(options.offsetAttribute)) {
      attributes.offset = OffsetGeometryInstanceAttribute.fromCartesian3(
        Property.getValueOrDefault(
          this._terrainOffsetProperty,
          time,
          defaultOffset$4,
          offsetScratch$4
        )
      );
    }

    let geometry;
    if (options.perPositionHeight && !defined(options.extrudedHeight)) {
      geometry = new CoplanarPolygonOutlineGeometry(options);
    } else {
      geometry = new PolygonOutlineGeometry(options);
    }
    return new GeometryInstance({
      id: entity,
      geometry: geometry,
      attributes: attributes,
    });
  };

  PolygonGeometryUpdater.prototype._computeCenter = function (time, result) {
    const hierarchy = Property.getValueOrUndefined(
      this._entity.polygon.hierarchy,
      time
    );
    if (!defined(hierarchy)) {
      return;
    }
    const positions = hierarchy.positions;
    if (positions.length === 0) {
      return;
    }
    const ellipsoid = this._scene.mapProjection.ellipsoid;

    const tangentPlane = EllipsoidTangentPlane.fromPoints(positions, ellipsoid);
    const positions2D = tangentPlane.projectPointsOntoPlane(
      positions,
      scratch2DPositions
    );

    const length = positions2D.length;
    let area = 0;
    let j = length - 1;
    let centroid2D = new Cartesian2();
    for (let i = 0; i < length; j = i++) {
      const p1 = positions2D[i];
      const p2 = positions2D[j];
      const f = p1.x * p2.y - p2.x * p1.y;

      let sum = Cartesian2.add(p1, p2, cart2Scratch);
      sum = Cartesian2.multiplyByScalar(sum, f, sum);
      centroid2D = Cartesian2.add(centroid2D, sum, centroid2D);

      area += f;
    }

    const a = 1.0 / (area * 3.0);
    centroid2D = Cartesian2.multiplyByScalar(centroid2D, a, centroid2D);
    return tangentPlane.projectPointOntoEllipsoid(centroid2D, result);
  };

  PolygonGeometryUpdater.prototype._isHidden = function (entity, polygon) {
    return (
      !defined(polygon.hierarchy) ||
      GeometryUpdater.prototype._isHidden.call(this, entity, polygon)
    );
  };

  PolygonGeometryUpdater.prototype._isOnTerrain = function (entity, polygon) {
    const onTerrain = GroundGeometryUpdater.prototype._isOnTerrain.call(
      this,
      entity,
      polygon
    );
    const perPositionHeightProperty = polygon.perPositionHeight;
    const perPositionHeightEnabled =
      defined(perPositionHeightProperty) &&
      (perPositionHeightProperty.isConstant
        ? perPositionHeightProperty.getValue(Iso8601.MINIMUM_VALUE)
        : true);
    return onTerrain && !perPositionHeightEnabled;
  };

  PolygonGeometryUpdater.prototype._isDynamic = function (entity, polygon) {
    return (
      !polygon.hierarchy.isConstant || //
      !Property.isConstant(polygon.height) || //
      !Property.isConstant(polygon.extrudedHeight) || //
      !Property.isConstant(polygon.granularity) || //
      !Property.isConstant(polygon.stRotation) || //
      !Property.isConstant(polygon.textureCoordinates) || //
      !Property.isConstant(polygon.outlineWidth) || //
      !Property.isConstant(polygon.perPositionHeight) || //
      !Property.isConstant(polygon.closeTop) || //
      !Property.isConstant(polygon.closeBottom) || //
      !Property.isConstant(polygon.zIndex) || //
      !Property.isConstant(polygon.arcType) || //
      (this._onTerrain &&
        !Property.isConstant(this._materialProperty) &&
        !(this._materialProperty instanceof ColorMaterialProperty))
    );
  };

  PolygonGeometryUpdater.prototype._setStaticOptions = function (
    entity,
    polygon
  ) {
    const isColorMaterial =
      this._materialProperty instanceof ColorMaterialProperty;

    const options = this._options;
    options.vertexFormat = isColorMaterial
      ? PerInstanceColorAppearance.VERTEX_FORMAT
      : MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat;

    const hierarchyValue = polygon.hierarchy.getValue(Iso8601.MINIMUM_VALUE);
    let heightValue = Property.getValueOrUndefined(
      polygon.height,
      Iso8601.MINIMUM_VALUE
    );
    const heightReferenceValue = Property.getValueOrDefault(
      polygon.heightReference,
      Iso8601.MINIMUM_VALUE,
      HeightReference$1.NONE
    );
    let extrudedHeightValue = Property.getValueOrUndefined(
      polygon.extrudedHeight,
      Iso8601.MINIMUM_VALUE
    );
    const extrudedHeightReferenceValue = Property.getValueOrDefault(
      polygon.extrudedHeightReference,
      Iso8601.MINIMUM_VALUE,
      HeightReference$1.NONE
    );
    const perPositionHeightValue = Property.getValueOrDefault(
      polygon.perPositionHeight,
      Iso8601.MINIMUM_VALUE,
      false
    );

    heightValue = GroundGeometryUpdater.getGeometryHeight(
      heightValue,
      heightReferenceValue
    );

    let offsetAttribute;
    if (perPositionHeightValue) {
      if (defined(heightValue)) {
        heightValue = undefined;
        oneTimeWarning(heightAndPerPositionHeightWarning);
      }
      if (
        heightReferenceValue !== HeightReference$1.NONE &&
        perPositionHeightValue
      ) {
        heightValue = undefined;
        oneTimeWarning(heightReferenceAndPerPositionHeightWarning);
      }
    } else {
      if (defined(extrudedHeightValue) && !defined(heightValue)) {
        heightValue = 0;
      }
      offsetAttribute = GroundGeometryUpdater.computeGeometryOffsetAttribute(
        heightValue,
        heightReferenceValue,
        extrudedHeightValue,
        extrudedHeightReferenceValue
      );
    }

    options.polygonHierarchy = hierarchyValue;
    options.granularity = Property.getValueOrUndefined(
      polygon.granularity,
      Iso8601.MINIMUM_VALUE
    );
    options.stRotation = Property.getValueOrUndefined(
      polygon.stRotation,
      Iso8601.MINIMUM_VALUE
    );
    options.perPositionHeight = perPositionHeightValue;
    options.closeTop = Property.getValueOrDefault(
      polygon.closeTop,
      Iso8601.MINIMUM_VALUE,
      true
    );
    options.closeBottom = Property.getValueOrDefault(
      polygon.closeBottom,
      Iso8601.MINIMUM_VALUE,
      true
    );
    options.offsetAttribute = offsetAttribute;
    options.height = heightValue;
    options.arcType = Property.getValueOrDefault(
      polygon.arcType,
      Iso8601.MINIMUM_VALUE,
      ArcType$1.GEODESIC
    );
    options.textureCoordinates = Property.getValueOrUndefined(
      polygon.textureCoordinates,
      Iso8601.MINIMUM_VALUE
    );

    extrudedHeightValue = GroundGeometryUpdater.getGeometryExtrudedHeight(
      extrudedHeightValue,
      extrudedHeightReferenceValue
    );
    if (extrudedHeightValue === GroundGeometryUpdater.CLAMP_TO_GROUND) {
      extrudedHeightValue = ApproximateTerrainHeights.getMinimumMaximumHeights(
        PolygonGeometry.computeRectangle(options, scratchRectangle$2)
      ).minimumTerrainHeight;
    }

    options.extrudedHeight = extrudedHeightValue;
  };

  PolygonGeometryUpdater.prototype._getIsClosed = function (options) {
    const height = options.height;
    const extrudedHeight = options.extrudedHeight;
    const isExtruded = defined(extrudedHeight) && extrudedHeight !== height;
    return (
      !options.perPositionHeight &&
      ((!isExtruded && height === 0) ||
        (isExtruded && options.closeTop && options.closeBottom))
    );
  };

  PolygonGeometryUpdater.DynamicGeometryUpdater = DyanmicPolygonGeometryUpdater;

  /**
   * @private
   */
  function DyanmicPolygonGeometryUpdater(
    geometryUpdater,
    primitives,
    groundPrimitives
  ) {
    DynamicGeometryUpdater$1.call(
      this,
      geometryUpdater,
      primitives,
      groundPrimitives
    );
  }

  if (defined(Object.create)) {
    DyanmicPolygonGeometryUpdater.prototype = Object.create(
      DynamicGeometryUpdater$1.prototype
    );
    DyanmicPolygonGeometryUpdater.prototype.constructor = DyanmicPolygonGeometryUpdater;
  }

  DyanmicPolygonGeometryUpdater.prototype._isHidden = function (
    entity,
    polygon,
    time
  ) {
    return (
      !defined(this._options.polygonHierarchy) ||
      DynamicGeometryUpdater$1.prototype._isHidden.call(this, entity, polygon, time)
    );
  };

  DyanmicPolygonGeometryUpdater.prototype._setOptions = function (
    entity,
    polygon,
    time
  ) {
    const options = this._options;

    options.polygonHierarchy = Property.getValueOrUndefined(
      polygon.hierarchy,
      time
    );

    let heightValue = Property.getValueOrUndefined(polygon.height, time);
    const heightReferenceValue = Property.getValueOrDefault(
      polygon.heightReference,
      time,
      HeightReference$1.NONE
    );
    const extrudedHeightReferenceValue = Property.getValueOrDefault(
      polygon.extrudedHeightReference,
      time,
      HeightReference$1.NONE
    );
    let extrudedHeightValue = Property.getValueOrUndefined(
      polygon.extrudedHeight,
      time
    );
    const perPositionHeightValue = Property.getValueOrUndefined(
      polygon.perPositionHeight,
      time
    );

    heightValue = GroundGeometryUpdater.getGeometryHeight(
      heightValue,
      extrudedHeightReferenceValue
    );

    let offsetAttribute;
    if (perPositionHeightValue) {
      if (defined(heightValue)) {
        heightValue = undefined;
        oneTimeWarning(heightAndPerPositionHeightWarning);
      }
      if (
        heightReferenceValue !== HeightReference$1.NONE &&
        perPositionHeightValue
      ) {
        heightValue = undefined;
        oneTimeWarning(heightReferenceAndPerPositionHeightWarning);
      }
    } else {
      if (defined(extrudedHeightValue) && !defined(heightValue)) {
        heightValue = 0;
      }

      offsetAttribute = GroundGeometryUpdater.computeGeometryOffsetAttribute(
        heightValue,
        heightReferenceValue,
        extrudedHeightValue,
        extrudedHeightReferenceValue
      );
    }

    options.granularity = Property.getValueOrUndefined(polygon.granularity, time);
    options.stRotation = Property.getValueOrUndefined(polygon.stRotation, time);
    options.textureCoordinates = Property.getValueOrUndefined(
      polygon.textureCoordinates,
      time
    );
    options.perPositionHeight = Property.getValueOrUndefined(
      polygon.perPositionHeight,
      time
    );
    options.closeTop = Property.getValueOrDefault(polygon.closeTop, time, true);
    options.closeBottom = Property.getValueOrDefault(
      polygon.closeBottom,
      time,
      true
    );
    options.offsetAttribute = offsetAttribute;
    options.height = heightValue;
    options.arcType = Property.getValueOrDefault(
      polygon.arcType,
      time,
      ArcType$1.GEODESIC
    );

    extrudedHeightValue = GroundGeometryUpdater.getGeometryExtrudedHeight(
      extrudedHeightValue,
      extrudedHeightReferenceValue
    );
    if (extrudedHeightValue === GroundGeometryUpdater.CLAMP_TO_GROUND) {
      extrudedHeightValue = ApproximateTerrainHeights.getMinimumMaximumHeights(
        PolygonGeometry.computeRectangle(options, scratchRectangle$2)
      ).minimumTerrainHeight;
    }

    options.extrudedHeight = extrudedHeightValue;
  };

  const scratchColor$7 = new Color();

  function PolylineVolumeGeometryOptions(entity) {
    this.id = entity;
    this.vertexFormat = undefined;
    this.polylinePositions = undefined;
    this.shapePositions = undefined;
    this.cornerType = undefined;
    this.granularity = undefined;
  }

  /**
   * A {@link GeometryUpdater} for polyline volumes.
   * Clients do not normally create this class directly, but instead rely on {@link DataSourceDisplay}.
   * @alias PolylineVolumeGeometryUpdater
   * @constructor
   *
   * @param {Entity} entity The entity containing the geometry to be visualized.
   * @param {Scene} scene The scene where visualization is taking place.
   */
  function PolylineVolumeGeometryUpdater(entity, scene) {
    GeometryUpdater.call(this, {
      entity: entity,
      scene: scene,
      geometryOptions: new PolylineVolumeGeometryOptions(entity),
      geometryPropertyName: "polylineVolume",
      observedPropertyNames: ["availability", "polylineVolume"],
    });

    this._onEntityPropertyChanged(
      entity,
      "polylineVolume",
      entity.polylineVolume,
      undefined
    );
  }

  if (defined(Object.create)) {
    PolylineVolumeGeometryUpdater.prototype = Object.create(
      GeometryUpdater.prototype
    );
    PolylineVolumeGeometryUpdater.prototype.constructor = PolylineVolumeGeometryUpdater;
  }

  /**
   * Creates the geometry instance which represents the fill of the geometry.
   *
   * @param {JulianDate} time The time to use when retrieving initial attribute values.
   * @returns {GeometryInstance} The geometry instance representing the filled portion of the geometry.
   *
   * @exception {DeveloperError} This instance does not represent a filled geometry.
   */
  PolylineVolumeGeometryUpdater.prototype.createFillGeometryInstance = function (
    time
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("time", time);

    if (!this._fillEnabled) {
      throw new DeveloperError(
        "This instance does not represent a filled geometry."
      );
    }
    //>>includeEnd('debug');

    const entity = this._entity;
    const isAvailable = entity.isAvailable(time);

    let attributes;

    let color;
    const show = new ShowGeometryInstanceAttribute(
      isAvailable &&
        entity.isShowing &&
        this._showProperty.getValue(time) &&
        this._fillProperty.getValue(time)
    );
    const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
      time
    );
    const distanceDisplayConditionAttribute = DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
      distanceDisplayCondition
    );
    if (this._materialProperty instanceof ColorMaterialProperty) {
      let currentColor;
      if (
        defined(this._materialProperty.color) &&
        (this._materialProperty.color.isConstant || isAvailable)
      ) {
        currentColor = this._materialProperty.color.getValue(time, scratchColor$7);
      }
      if (!defined(currentColor)) {
        currentColor = Color.WHITE;
      }
      color = ColorGeometryInstanceAttribute.fromColor(currentColor);
      attributes = {
        show: show,
        distanceDisplayCondition: distanceDisplayConditionAttribute,
        color: color,
      };
    } else {
      attributes = {
        show: show,
        distanceDisplayCondition: distanceDisplayConditionAttribute,
      };
    }

    return new GeometryInstance({
      id: entity,
      geometry: new PolylineVolumeGeometry(this._options),
      attributes: attributes,
    });
  };

  /**
   * Creates the geometry instance which represents the outline of the geometry.
   *
   * @param {JulianDate} time The time to use when retrieving initial attribute values.
   * @returns {GeometryInstance} The geometry instance representing the outline portion of the geometry.
   *
   * @exception {DeveloperError} This instance does not represent an outlined geometry.
   */
  PolylineVolumeGeometryUpdater.prototype.createOutlineGeometryInstance = function (
    time
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("time", time);

    if (!this._outlineEnabled) {
      throw new DeveloperError(
        "This instance does not represent an outlined geometry."
      );
    }
    //>>includeEnd('debug');

    const entity = this._entity;
    const isAvailable = entity.isAvailable(time);
    const outlineColor = Property.getValueOrDefault(
      this._outlineColorProperty,
      time,
      Color.BLACK,
      scratchColor$7
    );
    const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
      time
    );

    return new GeometryInstance({
      id: entity,
      geometry: new PolylineVolumeOutlineGeometry(this._options),
      attributes: {
        show: new ShowGeometryInstanceAttribute(
          isAvailable &&
            entity.isShowing &&
            this._showProperty.getValue(time) &&
            this._showOutlineProperty.getValue(time)
        ),
        color: ColorGeometryInstanceAttribute.fromColor(outlineColor),
        distanceDisplayCondition: DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
          distanceDisplayCondition
        ),
      },
    });
  };

  PolylineVolumeGeometryUpdater.prototype._isHidden = function (
    entity,
    polylineVolume
  ) {
    return (
      !defined(polylineVolume.positions) ||
      !defined(polylineVolume.shape) ||
      GeometryUpdater.prototype._isHidden.call(this, entity, polylineVolume)
    );
  };

  PolylineVolumeGeometryUpdater.prototype._isDynamic = function (
    entity,
    polylineVolume
  ) {
    return (
      !polylineVolume.positions.isConstant || //
      !polylineVolume.shape.isConstant || //
      !Property.isConstant(polylineVolume.granularity) || //
      !Property.isConstant(polylineVolume.outlineWidth) || //
      !Property.isConstant(polylineVolume.cornerType)
    );
  };

  PolylineVolumeGeometryUpdater.prototype._setStaticOptions = function (
    entity,
    polylineVolume
  ) {
    const granularity = polylineVolume.granularity;
    const cornerType = polylineVolume.cornerType;

    const options = this._options;
    const isColorMaterial =
      this._materialProperty instanceof ColorMaterialProperty;
    options.vertexFormat = isColorMaterial
      ? PerInstanceColorAppearance.VERTEX_FORMAT
      : MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat;
    options.polylinePositions = polylineVolume.positions.getValue(
      Iso8601.MINIMUM_VALUE,
      options.polylinePositions
    );
    options.shapePositions = polylineVolume.shape.getValue(
      Iso8601.MINIMUM_VALUE,
      options.shape
    );
    options.granularity = defined(granularity)
      ? granularity.getValue(Iso8601.MINIMUM_VALUE)
      : undefined;
    options.cornerType = defined(cornerType)
      ? cornerType.getValue(Iso8601.MINIMUM_VALUE)
      : undefined;
  };

  PolylineVolumeGeometryUpdater.DynamicGeometryUpdater = DynamicPolylineVolumeGeometryUpdater;

  /**
   * @private
   */
  function DynamicPolylineVolumeGeometryUpdater(
    geometryUpdater,
    primitives,
    groundPrimitives
  ) {
    DynamicGeometryUpdater$1.call(
      this,
      geometryUpdater,
      primitives,
      groundPrimitives
    );
  }

  if (defined(Object.create)) {
    DynamicPolylineVolumeGeometryUpdater.prototype = Object.create(
      DynamicGeometryUpdater$1.prototype
    );
    DynamicPolylineVolumeGeometryUpdater.prototype.constructor = DynamicPolylineVolumeGeometryUpdater;
  }

  DynamicPolylineVolumeGeometryUpdater.prototype._isHidden = function (
    entity,
    polylineVolume,
    time
  ) {
    const options = this._options;
    return (
      !defined(options.polylinePositions) ||
      !defined(options.shapePositions) ||
      DynamicGeometryUpdater$1.prototype._isHidden.call(
        this,
        entity,
        polylineVolume,
        time
      )
    );
  };

  DynamicPolylineVolumeGeometryUpdater.prototype._setOptions = function (
    entity,
    polylineVolume,
    time
  ) {
    const options = this._options;
    options.polylinePositions = Property.getValueOrUndefined(
      polylineVolume.positions,
      time,
      options.polylinePositions
    );
    options.shapePositions = Property.getValueOrUndefined(
      polylineVolume.shape,
      time
    );
    options.granularity = Property.getValueOrUndefined(
      polylineVolume.granularity,
      time
    );
    options.cornerType = Property.getValueOrUndefined(
      polylineVolume.cornerType,
      time
    );
  };

  const scratchColor$6 = new Color();
  const defaultOffset$3 = Cartesian3.ZERO;
  const offsetScratch$3 = new Cartesian3();
  const scratchRectangle$1 = new Rectangle();
  const scratchCenterRect = new Rectangle();
  const scratchCarto = new Cartographic();

  function RectangleGeometryOptions(entity) {
    this.id = entity;
    this.vertexFormat = undefined;
    this.rectangle = undefined;
    this.height = undefined;
    this.extrudedHeight = undefined;
    this.granularity = undefined;
    this.stRotation = undefined;
    this.rotation = undefined;
    this.offsetAttribute = undefined;
  }

  /**
   * A {@link GeometryUpdater} for rectangles.
   * Clients do not normally create this class directly, but instead rely on {@link DataSourceDisplay}.
   * @alias RectangleGeometryUpdater
   * @constructor
   *
   * @param {Entity} entity The entity containing the geometry to be visualized.
   * @param {Scene} scene The scene where visualization is taking place.
   */
  function RectangleGeometryUpdater(entity, scene) {
    GroundGeometryUpdater.call(this, {
      entity: entity,
      scene: scene,
      geometryOptions: new RectangleGeometryOptions(entity),
      geometryPropertyName: "rectangle",
      observedPropertyNames: ["availability", "rectangle"],
    });

    this._onEntityPropertyChanged(
      entity,
      "rectangle",
      entity.rectangle,
      undefined
    );
  }

  if (defined(Object.create)) {
    RectangleGeometryUpdater.prototype = Object.create(
      GroundGeometryUpdater.prototype
    );
    RectangleGeometryUpdater.prototype.constructor = RectangleGeometryUpdater;
  }

  /**
   * Creates the geometry instance which represents the fill of the geometry.
   *
   * @param {JulianDate} time The time to use when retrieving initial attribute values.
   * @returns {GeometryInstance} The geometry instance representing the filled portion of the geometry.
   *
   * @exception {DeveloperError} This instance does not represent a filled geometry.
   */
  RectangleGeometryUpdater.prototype.createFillGeometryInstance = function (
    time
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("time", time);

    if (!this._fillEnabled) {
      throw new DeveloperError(
        "This instance does not represent a filled geometry."
      );
    }
    //>>includeEnd('debug');

    const entity = this._entity;
    const isAvailable = entity.isAvailable(time);

    const attributes = {
      show: new ShowGeometryInstanceAttribute(
        isAvailable &&
          entity.isShowing &&
          this._showProperty.getValue(time) &&
          this._fillProperty.getValue(time)
      ),
      distanceDisplayCondition: DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
        this._distanceDisplayConditionProperty.getValue(time)
      ),
      offset: undefined,
      color: undefined,
    };

    if (this._materialProperty instanceof ColorMaterialProperty) {
      let currentColor;
      if (
        defined(this._materialProperty.color) &&
        (this._materialProperty.color.isConstant || isAvailable)
      ) {
        currentColor = this._materialProperty.color.getValue(time, scratchColor$6);
      }
      if (!defined(currentColor)) {
        currentColor = Color.WHITE;
      }
      attributes.color = ColorGeometryInstanceAttribute.fromColor(currentColor);
    }
    if (defined(this._options.offsetAttribute)) {
      attributes.offset = OffsetGeometryInstanceAttribute.fromCartesian3(
        Property.getValueOrDefault(
          this._terrainOffsetProperty,
          time,
          defaultOffset$3,
          offsetScratch$3
        )
      );
    }

    return new GeometryInstance({
      id: entity,
      geometry: new RectangleGeometry(this._options),
      attributes: attributes,
    });
  };

  /**
   * Creates the geometry instance which represents the outline of the geometry.
   *
   * @param {JulianDate} time The time to use when retrieving initial attribute values.
   * @returns {GeometryInstance} The geometry instance representing the outline portion of the geometry.
   *
   * @exception {DeveloperError} This instance does not represent an outlined geometry.
   */
  RectangleGeometryUpdater.prototype.createOutlineGeometryInstance = function (
    time
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("time", time);

    if (!this._outlineEnabled) {
      throw new DeveloperError(
        "This instance does not represent an outlined geometry."
      );
    }
    //>>includeEnd('debug');

    const entity = this._entity;
    const isAvailable = entity.isAvailable(time);
    const outlineColor = Property.getValueOrDefault(
      this._outlineColorProperty,
      time,
      Color.BLACK,
      scratchColor$6
    );
    const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
      time
    );

    const attributes = {
      show: new ShowGeometryInstanceAttribute(
        isAvailable &&
          entity.isShowing &&
          this._showProperty.getValue(time) &&
          this._showOutlineProperty.getValue(time)
      ),
      color: ColorGeometryInstanceAttribute.fromColor(outlineColor),
      distanceDisplayCondition: DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
        distanceDisplayCondition
      ),
      offset: undefined,
    };

    if (defined(this._options.offsetAttribute)) {
      attributes.offset = OffsetGeometryInstanceAttribute.fromCartesian3(
        Property.getValueOrDefault(
          this._terrainOffsetProperty,
          time,
          defaultOffset$3,
          offsetScratch$3
        )
      );
    }

    return new GeometryInstance({
      id: entity,
      geometry: new RectangleOutlineGeometry(this._options),
      attributes: attributes,
    });
  };

  RectangleGeometryUpdater.prototype._computeCenter = function (time, result) {
    const rect = Property.getValueOrUndefined(
      this._entity.rectangle.coordinates,
      time,
      scratchCenterRect
    );
    if (!defined(rect)) {
      return;
    }
    const center = Rectangle.center(rect, scratchCarto);
    return Cartographic.toCartesian(center, Ellipsoid.WGS84, result);
  };

  RectangleGeometryUpdater.prototype._isHidden = function (entity, rectangle) {
    return (
      !defined(rectangle.coordinates) ||
      GeometryUpdater.prototype._isHidden.call(this, entity, rectangle)
    );
  };

  RectangleGeometryUpdater.prototype._isDynamic = function (entity, rectangle) {
    return (
      !rectangle.coordinates.isConstant || //
      !Property.isConstant(rectangle.height) || //
      !Property.isConstant(rectangle.extrudedHeight) || //
      !Property.isConstant(rectangle.granularity) || //
      !Property.isConstant(rectangle.stRotation) || //
      !Property.isConstant(rectangle.rotation) || //
      !Property.isConstant(rectangle.outlineWidth) || //
      !Property.isConstant(rectangle.zIndex) || //
      (this._onTerrain &&
        !Property.isConstant(this._materialProperty) &&
        !(this._materialProperty instanceof ColorMaterialProperty))
    );
  };

  RectangleGeometryUpdater.prototype._setStaticOptions = function (
    entity,
    rectangle
  ) {
    const isColorMaterial =
      this._materialProperty instanceof ColorMaterialProperty;

    let heightValue = Property.getValueOrUndefined(
      rectangle.height,
      Iso8601.MINIMUM_VALUE
    );
    const heightReferenceValue = Property.getValueOrDefault(
      rectangle.heightReference,
      Iso8601.MINIMUM_VALUE,
      HeightReference$1.NONE
    );
    let extrudedHeightValue = Property.getValueOrUndefined(
      rectangle.extrudedHeight,
      Iso8601.MINIMUM_VALUE
    );
    const extrudedHeightReferenceValue = Property.getValueOrDefault(
      rectangle.extrudedHeightReference,
      Iso8601.MINIMUM_VALUE,
      HeightReference$1.NONE
    );
    if (defined(extrudedHeightValue) && !defined(heightValue)) {
      heightValue = 0;
    }

    const options = this._options;
    options.vertexFormat = isColorMaterial
      ? PerInstanceColorAppearance.VERTEX_FORMAT
      : MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat;
    options.rectangle = rectangle.coordinates.getValue(
      Iso8601.MINIMUM_VALUE,
      options.rectangle
    );
    options.granularity = Property.getValueOrUndefined(
      rectangle.granularity,
      Iso8601.MINIMUM_VALUE
    );
    options.stRotation = Property.getValueOrUndefined(
      rectangle.stRotation,
      Iso8601.MINIMUM_VALUE
    );
    options.rotation = Property.getValueOrUndefined(
      rectangle.rotation,
      Iso8601.MINIMUM_VALUE
    );
    options.offsetAttribute = GroundGeometryUpdater.computeGeometryOffsetAttribute(
      heightValue,
      heightReferenceValue,
      extrudedHeightValue,
      extrudedHeightReferenceValue
    );
    options.height = GroundGeometryUpdater.getGeometryHeight(
      heightValue,
      heightReferenceValue
    );

    extrudedHeightValue = GroundGeometryUpdater.getGeometryExtrudedHeight(
      extrudedHeightValue,
      extrudedHeightReferenceValue
    );
    if (extrudedHeightValue === GroundGeometryUpdater.CLAMP_TO_GROUND) {
      extrudedHeightValue = ApproximateTerrainHeights.getMinimumMaximumHeights(
        RectangleGeometry.computeRectangle(options, scratchRectangle$1)
      ).minimumTerrainHeight;
    }

    options.extrudedHeight = extrudedHeightValue;
  };

  RectangleGeometryUpdater.DynamicGeometryUpdater = DynamicRectangleGeometryUpdater;

  /**
   * @private
   */
  function DynamicRectangleGeometryUpdater(
    geometryUpdater,
    primitives,
    groundPrimitives
  ) {
    DynamicGeometryUpdater$1.call(
      this,
      geometryUpdater,
      primitives,
      groundPrimitives
    );
  }

  if (defined(Object.create)) {
    DynamicRectangleGeometryUpdater.prototype = Object.create(
      DynamicGeometryUpdater$1.prototype
    );
    DynamicRectangleGeometryUpdater.prototype.constructor = DynamicRectangleGeometryUpdater;
  }

  DynamicRectangleGeometryUpdater.prototype._isHidden = function (
    entity,
    rectangle,
    time
  ) {
    return (
      !defined(this._options.rectangle) ||
      DynamicGeometryUpdater$1.prototype._isHidden.call(
        this,
        entity,
        rectangle,
        time
      )
    );
  };

  DynamicRectangleGeometryUpdater.prototype._setOptions = function (
    entity,
    rectangle,
    time
  ) {
    const options = this._options;
    let heightValue = Property.getValueOrUndefined(rectangle.height, time);
    const heightReferenceValue = Property.getValueOrDefault(
      rectangle.heightReference,
      time,
      HeightReference$1.NONE
    );
    let extrudedHeightValue = Property.getValueOrUndefined(
      rectangle.extrudedHeight,
      time
    );
    const extrudedHeightReferenceValue = Property.getValueOrDefault(
      rectangle.extrudedHeightReference,
      time,
      HeightReference$1.NONE
    );
    if (defined(extrudedHeightValue) && !defined(heightValue)) {
      heightValue = 0;
    }

    options.rectangle = Property.getValueOrUndefined(
      rectangle.coordinates,
      time,
      options.rectangle
    );
    options.granularity = Property.getValueOrUndefined(
      rectangle.granularity,
      time
    );
    options.stRotation = Property.getValueOrUndefined(rectangle.stRotation, time);
    options.rotation = Property.getValueOrUndefined(rectangle.rotation, time);
    options.offsetAttribute = GroundGeometryUpdater.computeGeometryOffsetAttribute(
      heightValue,
      heightReferenceValue,
      extrudedHeightValue,
      extrudedHeightReferenceValue
    );
    options.height = GroundGeometryUpdater.getGeometryHeight(
      heightValue,
      heightReferenceValue
    );

    extrudedHeightValue = GroundGeometryUpdater.getGeometryExtrudedHeight(
      extrudedHeightValue,
      extrudedHeightReferenceValue
    );
    if (extrudedHeightValue === GroundGeometryUpdater.CLAMP_TO_GROUND) {
      extrudedHeightValue = ApproximateTerrainHeights.getMinimumMaximumHeights(
        RectangleGeometry.computeRectangle(options, scratchRectangle$1)
      ).minimumTerrainHeight;
    }

    options.extrudedHeight = extrudedHeightValue;
  };

  const colorScratch$5 = new Color();
  const distanceDisplayConditionScratch$7 = new DistanceDisplayCondition();
  const defaultDistanceDisplayCondition$6 = new DistanceDisplayCondition();
  const defaultOffset$2 = Cartesian3.ZERO;
  const offsetScratch$2 = new Cartesian3();

  function Batch$5(
    primitives,
    translucent,
    appearanceType,
    depthFailAppearanceType,
    depthFailMaterialProperty,
    closed,
    shadows
  ) {
    this.translucent = translucent;
    this.appearanceType = appearanceType;
    this.depthFailAppearanceType = depthFailAppearanceType;
    this.depthFailMaterialProperty = depthFailMaterialProperty;
    this.depthFailMaterial = undefined;
    this.closed = closed;
    this.shadows = shadows;
    this.primitives = primitives;
    this.createPrimitive = false;
    this.waitingOnCreate = false;
    this.primitive = undefined;
    this.oldPrimitive = undefined;
    this.geometry = new AssociativeArray();
    this.updaters = new AssociativeArray();
    this.updatersWithAttributes = new AssociativeArray();
    this.attributes = new AssociativeArray();
    this.subscriptions = new AssociativeArray();
    this.showsUpdated = new AssociativeArray();
    this.itemsToRemove = [];
    this.invalidated = false;

    let removeMaterialSubscription;
    if (defined(depthFailMaterialProperty)) {
      removeMaterialSubscription = depthFailMaterialProperty.definitionChanged.addEventListener(
        Batch$5.prototype.onMaterialChanged,
        this
      );
    }
    this.removeMaterialSubscription = removeMaterialSubscription;
  }

  Batch$5.prototype.onMaterialChanged = function () {
    this.invalidated = true;
  };

  Batch$5.prototype.isMaterial = function (updater) {
    const material = this.depthFailMaterialProperty;
    const updaterMaterial = updater.depthFailMaterialProperty;
    if (updaterMaterial === material) {
      return true;
    }
    if (defined(material)) {
      return material.equals(updaterMaterial);
    }
    return false;
  };

  Batch$5.prototype.add = function (updater, instance) {
    const id = updater.id;
    this.createPrimitive = true;
    this.geometry.set(id, instance);
    this.updaters.set(id, updater);
    if (
      !updater.hasConstantFill ||
      !updater.fillMaterialProperty.isConstant ||
      !Property.isConstant(updater.distanceDisplayConditionProperty) ||
      !Property.isConstant(updater.terrainOffsetProperty)
    ) {
      this.updatersWithAttributes.set(id, updater);
    } else {
      const that = this;
      this.subscriptions.set(
        id,
        updater.entity.definitionChanged.addEventListener(function (
          entity,
          propertyName,
          newValue,
          oldValue
        ) {
          if (propertyName === "isShowing") {
            that.showsUpdated.set(updater.id, updater);
          }
        })
      );
    }
  };

  Batch$5.prototype.remove = function (updater) {
    const id = updater.id;
    this.createPrimitive = this.geometry.remove(id) || this.createPrimitive;
    if (this.updaters.remove(id)) {
      this.updatersWithAttributes.remove(id);
      const unsubscribe = this.subscriptions.get(id);
      if (defined(unsubscribe)) {
        unsubscribe();
        this.subscriptions.remove(id);
        this.showsUpdated.remove(id);
      }
      return true;
    }
    return false;
  };

  Batch$5.prototype.update = function (time) {
    let isUpdated = true;
    let removedCount = 0;
    let primitive = this.primitive;
    const primitives = this.primitives;
    let i;

    if (this.createPrimitive) {
      const geometries = this.geometry.values;
      const geometriesLength = geometries.length;
      if (geometriesLength > 0) {
        if (defined(primitive)) {
          if (!defined(this.oldPrimitive)) {
            this.oldPrimitive = primitive;
          } else {
            primitives.remove(primitive);
          }
        }

        let depthFailAppearance;
        if (defined(this.depthFailAppearanceType)) {
          if (defined(this.depthFailMaterialProperty)) {
            this.depthFailMaterial = MaterialProperty.getValue(
              time,
              this.depthFailMaterialProperty,
              this.depthFailMaterial
            );
          }
          depthFailAppearance = new this.depthFailAppearanceType({
            material: this.depthFailMaterial,
            translucent: this.translucent,
            closed: this.closed,
          });
        }

        primitive = new Primitive$3({
          show: false,
          asynchronous: true,
          geometryInstances: geometries.slice(),
          appearance: new this.appearanceType({
            translucent: this.translucent,
            closed: this.closed,
          }),
          depthFailAppearance: depthFailAppearance,
          shadows: this.shadows,
        });
        primitives.add(primitive);
        isUpdated = false;
      } else {
        if (defined(primitive)) {
          primitives.remove(primitive);
          primitive = undefined;
        }
        const oldPrimitive = this.oldPrimitive;
        if (defined(oldPrimitive)) {
          primitives.remove(oldPrimitive);
          this.oldPrimitive = undefined;
        }
      }

      this.attributes.removeAll();
      this.primitive = primitive;
      this.createPrimitive = false;
      this.waitingOnCreate = true;
    } else if (defined(primitive) && primitive.ready) {
      primitive.show = true;
      if (defined(this.oldPrimitive)) {
        primitives.remove(this.oldPrimitive);
        this.oldPrimitive = undefined;
      }

      if (
        defined(this.depthFailAppearanceType) &&
        !(this.depthFailMaterialProperty instanceof ColorMaterialProperty)
      ) {
        this.depthFailMaterial = MaterialProperty.getValue(
          time,
          this.depthFailMaterialProperty,
          this.depthFailMaterial
        );
        this.primitive.depthFailAppearance.material = this.depthFailMaterial;
      }

      const updatersWithAttributes = this.updatersWithAttributes.values;
      const length = updatersWithAttributes.length;
      const waitingOnCreate = this.waitingOnCreate;
      for (i = 0; i < length; i++) {
        const updater = updatersWithAttributes[i];
        const instance = this.geometry.get(updater.id);

        let attributes = this.attributes.get(instance.id.id);
        if (!defined(attributes)) {
          attributes = primitive.getGeometryInstanceAttributes(instance.id);
          this.attributes.set(instance.id.id, attributes);
        }

        if (!updater.fillMaterialProperty.isConstant || waitingOnCreate) {
          const colorProperty = updater.fillMaterialProperty.color;
          const resultColor = Property.getValueOrDefault(
            colorProperty,
            time,
            Color.WHITE,
            colorScratch$5
          );
          if (!Color.equals(attributes._lastColor, resultColor)) {
            attributes._lastColor = Color.clone(
              resultColor,
              attributes._lastColor
            );
            attributes.color = ColorGeometryInstanceAttribute.toValue(
              resultColor,
              attributes.color
            );
            if (
              (this.translucent && attributes.color[3] === 255) ||
              (!this.translucent && attributes.color[3] !== 255)
            ) {
              this.itemsToRemove[removedCount++] = updater;
            }
          }
        }

        if (
          defined(this.depthFailAppearanceType) &&
          updater.depthFailMaterialProperty instanceof ColorMaterialProperty &&
          (!updater.depthFailMaterialProperty.isConstant || waitingOnCreate)
        ) {
          const depthFailColorProperty = updater.depthFailMaterialProperty.color;
          const depthColor = Property.getValueOrDefault(
            depthFailColorProperty,
            time,
            Color.WHITE,
            colorScratch$5
          );
          if (!Color.equals(attributes._lastDepthFailColor, depthColor)) {
            attributes._lastDepthFailColor = Color.clone(
              depthColor,
              attributes._lastDepthFailColor
            );
            attributes.depthFailColor = ColorGeometryInstanceAttribute.toValue(
              depthColor,
              attributes.depthFailColor
            );
          }
        }

        const show =
          updater.entity.isShowing &&
          (updater.hasConstantFill || updater.isFilled(time));
        const currentShow = attributes.show[0] === 1;
        if (show !== currentShow) {
          attributes.show = ShowGeometryInstanceAttribute.toValue(
            show,
            attributes.show
          );
        }

        const distanceDisplayConditionProperty =
          updater.distanceDisplayConditionProperty;
        if (!Property.isConstant(distanceDisplayConditionProperty)) {
          const distanceDisplayCondition = Property.getValueOrDefault(
            distanceDisplayConditionProperty,
            time,
            defaultDistanceDisplayCondition$6,
            distanceDisplayConditionScratch$7
          );
          if (
            !DistanceDisplayCondition.equals(
              distanceDisplayCondition,
              attributes._lastDistanceDisplayCondition
            )
          ) {
            attributes._lastDistanceDisplayCondition = DistanceDisplayCondition.clone(
              distanceDisplayCondition,
              attributes._lastDistanceDisplayCondition
            );
            attributes.distanceDisplayCondition = DistanceDisplayConditionGeometryInstanceAttribute.toValue(
              distanceDisplayCondition,
              attributes.distanceDisplayCondition
            );
          }
        }

        const offsetProperty = updater.terrainOffsetProperty;
        if (!Property.isConstant(offsetProperty)) {
          const offset = Property.getValueOrDefault(
            offsetProperty,
            time,
            defaultOffset$2,
            offsetScratch$2
          );
          if (!Cartesian3.equals(offset, attributes._lastOffset)) {
            attributes._lastOffset = Cartesian3.clone(
              offset,
              attributes._lastOffset
            );
            attributes.offset = OffsetGeometryInstanceAttribute.toValue(
              offset,
              attributes.offset
            );
          }
        }
      }

      this.updateShows(primitive);
      this.waitingOnCreate = false;
    } else if (defined(primitive) && !primitive.ready) {
      isUpdated = false;
    }
    this.itemsToRemove.length = removedCount;
    return isUpdated;
  };

  Batch$5.prototype.updateShows = function (primitive) {
    const showsUpdated = this.showsUpdated.values;
    const length = showsUpdated.length;
    for (let i = 0; i < length; i++) {
      const updater = showsUpdated[i];
      const instance = this.geometry.get(updater.id);

      let attributes = this.attributes.get(instance.id.id);
      if (!defined(attributes)) {
        attributes = primitive.getGeometryInstanceAttributes(instance.id);
        this.attributes.set(instance.id.id, attributes);
      }

      const show = updater.entity.isShowing;
      const currentShow = attributes.show[0] === 1;
      if (show !== currentShow) {
        attributes.show = ShowGeometryInstanceAttribute.toValue(
          show,
          attributes.show
        );
        instance.attributes.show.value[0] = attributes.show[0];
      }
    }
    this.showsUpdated.removeAll();
  };

  Batch$5.prototype.contains = function (updater) {
    return this.updaters.contains(updater.id);
  };

  Batch$5.prototype.getBoundingSphere = function (updater, result) {
    const primitive = this.primitive;
    if (!primitive.ready) {
      return BoundingSphereState$1.PENDING;
    }
    const attributes = primitive.getGeometryInstanceAttributes(updater.entity);
    if (
      !defined(attributes) ||
      !defined(attributes.boundingSphere) || //
      (defined(attributes.show) && attributes.show[0] === 0)
    ) {
      return BoundingSphereState$1.FAILED;
    }
    attributes.boundingSphere.clone(result);
    return BoundingSphereState$1.DONE;
  };

  Batch$5.prototype.destroy = function () {
    const primitive = this.primitive;
    const primitives = this.primitives;
    if (defined(primitive)) {
      primitives.remove(primitive);
    }
    const oldPrimitive = this.oldPrimitive;
    if (defined(oldPrimitive)) {
      primitives.remove(oldPrimitive);
    }
    if (defined(this.removeMaterialSubscription)) {
      this.removeMaterialSubscription();
    }
  };

  /**
   * @private
   */
  function StaticGeometryColorBatch(
    primitives,
    appearanceType,
    depthFailAppearanceType,
    closed,
    shadows
  ) {
    this._solidItems = [];
    this._translucentItems = [];
    this._primitives = primitives;
    this._appearanceType = appearanceType;
    this._depthFailAppearanceType = depthFailAppearanceType;
    this._closed = closed;
    this._shadows = shadows;
  }

  StaticGeometryColorBatch.prototype.add = function (time, updater) {
    let items;
    let translucent;
    const instance = updater.createFillGeometryInstance(time);
    if (instance.attributes.color.value[3] === 255) {
      items = this._solidItems;
      translucent = false;
    } else {
      items = this._translucentItems;
      translucent = true;
    }

    const length = items.length;
    for (let i = 0; i < length; i++) {
      const item = items[i];
      if (item.isMaterial(updater)) {
        item.add(updater, instance);
        return;
      }
    }
    const batch = new Batch$5(
      this._primitives,
      translucent,
      this._appearanceType,
      this._depthFailAppearanceType,
      updater.depthFailMaterialProperty,
      this._closed,
      this._shadows
    );
    batch.add(updater, instance);
    items.push(batch);
  };

  function removeItem(items, updater) {
    const length = items.length;
    for (let i = length - 1; i >= 0; i--) {
      const item = items[i];
      if (item.remove(updater)) {
        if (item.updaters.length === 0) {
          items.splice(i, 1);
          item.destroy();
        }
        return true;
      }
    }
    return false;
  }

  StaticGeometryColorBatch.prototype.remove = function (updater) {
    if (!removeItem(this._solidItems, updater)) {
      removeItem(this._translucentItems, updater);
    }
  };

  function moveItems(batch, items, time) {
    let itemsMoved = false;
    const length = items.length;
    for (let i = 0; i < length; ++i) {
      const item = items[i];
      const itemsToRemove = item.itemsToRemove;
      const itemsToMoveLength = itemsToRemove.length;
      if (itemsToMoveLength > 0) {
        for (i = 0; i < itemsToMoveLength; i++) {
          const updater = itemsToRemove[i];
          item.remove(updater);
          batch.add(time, updater);
          itemsMoved = true;
        }
      }
    }
    return itemsMoved;
  }

  function updateItems(batch, items, time, isUpdated) {
    let length = items.length;
    let i;
    for (i = length - 1; i >= 0; i--) {
      const item = items[i];
      if (item.invalidated) {
        items.splice(i, 1);
        const updaters = item.updaters.values;
        const updatersLength = updaters.length;
        for (let h = 0; h < updatersLength; h++) {
          batch.add(time, updaters[h]);
        }
        item.destroy();
      }
    }

    length = items.length;
    for (i = 0; i < length; ++i) {
      isUpdated = items[i].update(time) && isUpdated;
    }
    return isUpdated;
  }

  StaticGeometryColorBatch.prototype.update = function (time) {
    //Perform initial update
    let isUpdated = updateItems(this, this._solidItems, time, true);
    isUpdated =
      updateItems(this, this._translucentItems, time, isUpdated) && isUpdated;

    //If any items swapped between solid/translucent, we need to
    //move them between batches
    const solidsMoved = moveItems(this, this._solidItems, time);
    const translucentsMoved = moveItems(this, this._translucentItems, time);

    //If we moved anything around, we need to re-build the primitive
    if (solidsMoved || translucentsMoved) {
      isUpdated =
        updateItems(this, this._solidItems, time, isUpdated) && isUpdated;
      isUpdated =
        updateItems(this, this._translucentItems, time, isUpdated) && isUpdated;
    }

    return isUpdated;
  };

  function getBoundingSphere(items, updater, result) {
    const length = items.length;
    for (let i = 0; i < length; i++) {
      const item = items[i];
      if (item.contains(updater)) {
        return item.getBoundingSphere(updater, result);
      }
    }
    return BoundingSphereState$1.FAILED;
  }

  StaticGeometryColorBatch.prototype.getBoundingSphere = function (
    updater,
    result
  ) {
    const boundingSphere = getBoundingSphere(this._solidItems, updater, result);
    if (boundingSphere === BoundingSphereState$1.FAILED) {
      return getBoundingSphere(this._translucentItems, updater, result);
    }
    return boundingSphere;
  };

  function removeAllPrimitives(items) {
    const length = items.length;
    for (let i = 0; i < length; i++) {
      items[i].destroy();
    }
    items.length = 0;
  }

  StaticGeometryColorBatch.prototype.removeAllPrimitives = function () {
    removeAllPrimitives(this._solidItems);
    removeAllPrimitives(this._translucentItems);
  };

  const distanceDisplayConditionScratch$6 = new DistanceDisplayCondition();
  const defaultDistanceDisplayCondition$5 = new DistanceDisplayCondition();
  const defaultOffset$1 = Cartesian3.ZERO;
  const offsetScratch$1 = new Cartesian3();

  function Batch$4(
    primitives,
    appearanceType,
    materialProperty,
    depthFailAppearanceType,
    depthFailMaterialProperty,
    closed,
    shadows
  ) {
    this.primitives = primitives;
    this.appearanceType = appearanceType;
    this.materialProperty = materialProperty;
    this.depthFailAppearanceType = depthFailAppearanceType;
    this.depthFailMaterialProperty = depthFailMaterialProperty;
    this.closed = closed;
    this.shadows = shadows;
    this.updaters = new AssociativeArray();
    this.createPrimitive = true;
    this.primitive = undefined;
    this.oldPrimitive = undefined;
    this.geometry = new AssociativeArray();
    this.material = undefined;
    this.depthFailMaterial = undefined;
    this.updatersWithAttributes = new AssociativeArray();
    this.attributes = new AssociativeArray();
    this.invalidated = false;
    this.removeMaterialSubscription = materialProperty.definitionChanged.addEventListener(
      Batch$4.prototype.onMaterialChanged,
      this
    );
    this.subscriptions = new AssociativeArray();
    this.showsUpdated = new AssociativeArray();
  }

  Batch$4.prototype.onMaterialChanged = function () {
    this.invalidated = true;
  };

  Batch$4.prototype.isMaterial = function (updater) {
    const material = this.materialProperty;
    const updaterMaterial = updater.fillMaterialProperty;
    const depthFailMaterial = this.depthFailMaterialProperty;
    const updaterDepthFailMaterial = updater.depthFailMaterialProperty;

    if (
      updaterMaterial === material &&
      updaterDepthFailMaterial === depthFailMaterial
    ) {
      return true;
    }
    let equals = defined(material) && material.equals(updaterMaterial);
    equals =
      ((!defined(depthFailMaterial) && !defined(updaterDepthFailMaterial)) ||
        (defined(depthFailMaterial) &&
          depthFailMaterial.equals(updaterDepthFailMaterial))) &&
      equals;
    return equals;
  };

  Batch$4.prototype.add = function (time, updater) {
    const id = updater.id;
    this.updaters.set(id, updater);
    this.geometry.set(id, updater.createFillGeometryInstance(time));
    if (
      !updater.hasConstantFill ||
      !updater.fillMaterialProperty.isConstant ||
      !Property.isConstant(updater.distanceDisplayConditionProperty) ||
      !Property.isConstant(updater.terrainOffsetProperty)
    ) {
      this.updatersWithAttributes.set(id, updater);
    } else {
      const that = this;
      this.subscriptions.set(
        id,
        updater.entity.definitionChanged.addEventListener(function (
          entity,
          propertyName,
          newValue,
          oldValue
        ) {
          if (propertyName === "isShowing") {
            that.showsUpdated.set(updater.id, updater);
          }
        })
      );
    }
    this.createPrimitive = true;
  };

  Batch$4.prototype.remove = function (updater) {
    const id = updater.id;
    this.createPrimitive = this.geometry.remove(id) || this.createPrimitive;
    if (this.updaters.remove(id)) {
      this.updatersWithAttributes.remove(id);
      const unsubscribe = this.subscriptions.get(id);
      if (defined(unsubscribe)) {
        unsubscribe();
        this.subscriptions.remove(id);
        this.showsUpdated.remove(id);
      }
      return true;
    }
    return false;
  };

  const colorScratch$4 = new Color();

  Batch$4.prototype.update = function (time) {
    let isUpdated = true;
    let primitive = this.primitive;
    const primitives = this.primitives;
    const geometries = this.geometry.values;
    let i;

    if (this.createPrimitive) {
      const geometriesLength = geometries.length;
      if (geometriesLength > 0) {
        if (defined(primitive)) {
          if (!defined(this.oldPrimitive)) {
            this.oldPrimitive = primitive;
          } else {
            primitives.remove(primitive);
          }
        }

        this.material = MaterialProperty.getValue(
          time,
          this.materialProperty,
          this.material
        );

        let depthFailAppearance;
        if (defined(this.depthFailMaterialProperty)) {
          this.depthFailMaterial = MaterialProperty.getValue(
            time,
            this.depthFailMaterialProperty,
            this.depthFailMaterial
          );
          depthFailAppearance = new this.depthFailAppearanceType({
            material: this.depthFailMaterial,
            translucent: this.depthFailMaterial.isTranslucent(),
            closed: this.closed,
          });
        }

        primitive = new Primitive$3({
          show: false,
          asynchronous: true,
          geometryInstances: geometries.slice(),
          appearance: new this.appearanceType({
            material: this.material,
            translucent: this.material.isTranslucent(),
            closed: this.closed,
          }),
          depthFailAppearance: depthFailAppearance,
          shadows: this.shadows,
        });

        primitives.add(primitive);
        isUpdated = false;
      } else {
        if (defined(primitive)) {
          primitives.remove(primitive);
          primitive = undefined;
        }
        const oldPrimitive = this.oldPrimitive;
        if (defined(oldPrimitive)) {
          primitives.remove(oldPrimitive);
          this.oldPrimitive = undefined;
        }
      }

      this.attributes.removeAll();
      this.primitive = primitive;
      this.createPrimitive = false;
    } else if (defined(primitive) && primitive.ready) {
      primitive.show = true;
      if (defined(this.oldPrimitive)) {
        primitives.remove(this.oldPrimitive);
        this.oldPrimitive = undefined;
      }

      this.material = MaterialProperty.getValue(
        time,
        this.materialProperty,
        this.material
      );
      this.primitive.appearance.material = this.material;

      if (
        defined(this.depthFailAppearanceType) &&
        !(this.depthFailMaterialProperty instanceof ColorMaterialProperty)
      ) {
        this.depthFailMaterial = MaterialProperty.getValue(
          time,
          this.depthFailMaterialProperty,
          this.depthFailMaterial
        );
        this.primitive.depthFailAppearance.material = this.depthFailMaterial;
      }

      const updatersWithAttributes = this.updatersWithAttributes.values;
      const length = updatersWithAttributes.length;
      for (i = 0; i < length; i++) {
        const updater = updatersWithAttributes[i];
        const entity = updater.entity;
        const instance = this.geometry.get(updater.id);

        let attributes = this.attributes.get(instance.id.id);
        if (!defined(attributes)) {
          attributes = primitive.getGeometryInstanceAttributes(instance.id);
          this.attributes.set(instance.id.id, attributes);
        }

        if (
          defined(this.depthFailAppearanceType) &&
          this.depthFailMaterialProperty instanceof ColorMaterialProperty &&
          !updater.depthFailMaterialProperty.isConstant
        ) {
          const depthFailColorProperty = updater.depthFailMaterialProperty.color;
          const depthFailColor = Property.getValueOrDefault(
            depthFailColorProperty,
            time,
            Color.WHITE,
            colorScratch$4
          );
          if (!Color.equals(attributes._lastDepthFailColor, depthFailColor)) {
            attributes._lastDepthFailColor = Color.clone(
              depthFailColor,
              attributes._lastDepthFailColor
            );
            attributes.depthFailColor = ColorGeometryInstanceAttribute.toValue(
              depthFailColor,
              attributes.depthFailColor
            );
          }
        }

        const show =
          entity.isShowing && (updater.hasConstantFill || updater.isFilled(time));
        const currentShow = attributes.show[0] === 1;
        if (show !== currentShow) {
          attributes.show = ShowGeometryInstanceAttribute.toValue(
            show,
            attributes.show
          );
        }

        const distanceDisplayConditionProperty =
          updater.distanceDisplayConditionProperty;
        if (!Property.isConstant(distanceDisplayConditionProperty)) {
          const distanceDisplayCondition = Property.getValueOrDefault(
            distanceDisplayConditionProperty,
            time,
            defaultDistanceDisplayCondition$5,
            distanceDisplayConditionScratch$6
          );
          if (
            !DistanceDisplayCondition.equals(
              distanceDisplayCondition,
              attributes._lastDistanceDisplayCondition
            )
          ) {
            attributes._lastDistanceDisplayCondition = DistanceDisplayCondition.clone(
              distanceDisplayCondition,
              attributes._lastDistanceDisplayCondition
            );
            attributes.distanceDisplayCondition = DistanceDisplayConditionGeometryInstanceAttribute.toValue(
              distanceDisplayCondition,
              attributes.distanceDisplayCondition
            );
          }
        }

        const offsetProperty = updater.terrainOffsetProperty;
        if (!Property.isConstant(offsetProperty)) {
          const offset = Property.getValueOrDefault(
            offsetProperty,
            time,
            defaultOffset$1,
            offsetScratch$1
          );
          if (!Cartesian3.equals(offset, attributes._lastOffset)) {
            attributes._lastOffset = Cartesian3.clone(
              offset,
              attributes._lastOffset
            );
            attributes.offset = OffsetGeometryInstanceAttribute.toValue(
              offset,
              attributes.offset
            );
          }
        }
      }

      this.updateShows(primitive);
    } else if (defined(primitive) && !primitive.ready) {
      isUpdated = false;
    }
    return isUpdated;
  };

  Batch$4.prototype.updateShows = function (primitive) {
    const showsUpdated = this.showsUpdated.values;
    const length = showsUpdated.length;
    for (let i = 0; i < length; i++) {
      const updater = showsUpdated[i];
      const entity = updater.entity;
      const instance = this.geometry.get(updater.id);

      let attributes = this.attributes.get(instance.id.id);
      if (!defined(attributes)) {
        attributes = primitive.getGeometryInstanceAttributes(instance.id);
        this.attributes.set(instance.id.id, attributes);
      }

      const show = entity.isShowing;
      const currentShow = attributes.show[0] === 1;
      if (show !== currentShow) {
        attributes.show = ShowGeometryInstanceAttribute.toValue(
          show,
          attributes.show
        );
        instance.attributes.show.value[0] = attributes.show[0];
      }
    }
    this.showsUpdated.removeAll();
  };

  Batch$4.prototype.contains = function (updater) {
    return this.updaters.contains(updater.id);
  };

  Batch$4.prototype.getBoundingSphere = function (updater, result) {
    const primitive = this.primitive;
    if (!primitive.ready) {
      return BoundingSphereState$1.PENDING;
    }
    const attributes = primitive.getGeometryInstanceAttributes(updater.entity);
    if (
      !defined(attributes) ||
      !defined(attributes.boundingSphere) ||
      (defined(attributes.show) && attributes.show[0] === 0)
    ) {
      return BoundingSphereState$1.FAILED;
    }
    attributes.boundingSphere.clone(result);
    return BoundingSphereState$1.DONE;
  };

  Batch$4.prototype.destroy = function () {
    const primitive = this.primitive;
    const primitives = this.primitives;
    if (defined(primitive)) {
      primitives.remove(primitive);
    }
    const oldPrimitive = this.oldPrimitive;
    if (defined(oldPrimitive)) {
      primitives.remove(oldPrimitive);
    }
    this.removeMaterialSubscription();
  };

  /**
   * @private
   */
  function StaticGeometryPerMaterialBatch(
    primitives,
    appearanceType,
    depthFailAppearanceType,
    closed,
    shadows
  ) {
    this._items = [];
    this._primitives = primitives;
    this._appearanceType = appearanceType;
    this._depthFailAppearanceType = depthFailAppearanceType;
    this._closed = closed;
    this._shadows = shadows;
  }

  StaticGeometryPerMaterialBatch.prototype.add = function (time, updater) {
    const items = this._items;
    const length = items.length;
    for (let i = 0; i < length; i++) {
      const item = items[i];
      if (item.isMaterial(updater)) {
        item.add(time, updater);
        return;
      }
    }
    const batch = new Batch$4(
      this._primitives,
      this._appearanceType,
      updater.fillMaterialProperty,
      this._depthFailAppearanceType,
      updater.depthFailMaterialProperty,
      this._closed,
      this._shadows
    );
    batch.add(time, updater);
    items.push(batch);
  };

  StaticGeometryPerMaterialBatch.prototype.remove = function (updater) {
    const items = this._items;
    const length = items.length;
    for (let i = length - 1; i >= 0; i--) {
      const item = items[i];
      if (item.remove(updater)) {
        if (item.updaters.length === 0) {
          items.splice(i, 1);
          item.destroy();
        }
        break;
      }
    }
  };

  StaticGeometryPerMaterialBatch.prototype.update = function (time) {
    let i;
    const items = this._items;
    const length = items.length;

    for (i = length - 1; i >= 0; i--) {
      const item = items[i];
      if (item.invalidated) {
        items.splice(i, 1);
        const updaters = item.updaters.values;
        const updatersLength = updaters.length;
        for (let h = 0; h < updatersLength; h++) {
          this.add(time, updaters[h]);
        }
        item.destroy();
      }
    }

    let isUpdated = true;
    for (i = 0; i < items.length; i++) {
      isUpdated = items[i].update(time) && isUpdated;
    }
    return isUpdated;
  };

  StaticGeometryPerMaterialBatch.prototype.getBoundingSphere = function (
    updater,
    result
  ) {
    const items = this._items;
    const length = items.length;
    for (let i = 0; i < length; i++) {
      const item = items[i];
      if (item.contains(updater)) {
        return item.getBoundingSphere(updater, result);
      }
    }
    return BoundingSphereState$1.FAILED;
  };

  StaticGeometryPerMaterialBatch.prototype.removeAllPrimitives = function () {
    const items = this._items;
    const length = items.length;
    for (let i = 0; i < length; i++) {
      items[i].destroy();
    }
    this._items.length = 0;
  };

  const colorScratch$3 = new Color();
  const distanceDisplayConditionScratch$5 = new DistanceDisplayCondition();
  const defaultDistanceDisplayCondition$4 = new DistanceDisplayCondition();

  function Batch$3(primitives, classificationType, color, zIndex) {
    this.primitives = primitives;
    this.zIndex = zIndex;
    this.classificationType = classificationType;
    this.color = color;
    this.createPrimitive = false;
    this.waitingOnCreate = false;
    this.primitive = undefined;
    this.oldPrimitive = undefined;
    this.geometry = new AssociativeArray();
    this.updaters = new AssociativeArray();
    this.updatersWithAttributes = new AssociativeArray();
    this.attributes = new AssociativeArray();
    this.subscriptions = new AssociativeArray();
    this.showsUpdated = new AssociativeArray();
    this.itemsToRemove = [];
    this.isDirty = false;
    this.rectangleCollisionCheck = new RectangleCollisionChecker();
  }

  Batch$3.prototype.overlapping = function (rectangle) {
    return this.rectangleCollisionCheck.collides(rectangle);
  };

  Batch$3.prototype.add = function (updater, instance) {
    const id = updater.id;
    this.createPrimitive = true;
    this.geometry.set(id, instance);
    this.updaters.set(id, updater);
    this.rectangleCollisionCheck.insert(id, instance.geometry.rectangle);
    if (
      !updater.hasConstantFill ||
      !updater.fillMaterialProperty.isConstant ||
      !Property.isConstant(updater.distanceDisplayConditionProperty)
    ) {
      this.updatersWithAttributes.set(id, updater);
    } else {
      const that = this;
      this.subscriptions.set(
        id,
        updater.entity.definitionChanged.addEventListener(function (
          entity,
          propertyName,
          newValue,
          oldValue
        ) {
          if (propertyName === "isShowing") {
            that.showsUpdated.set(updater.id, updater);
          }
        })
      );
    }
  };

  Batch$3.prototype.remove = function (updater) {
    const id = updater.id;
    const geometryInstance = this.geometry.get(id);
    this.createPrimitive = this.geometry.remove(id) || this.createPrimitive;
    if (this.updaters.remove(id)) {
      this.rectangleCollisionCheck.remove(
        id,
        geometryInstance.geometry.rectangle
      );
      this.updatersWithAttributes.remove(id);
      const unsubscribe = this.subscriptions.get(id);
      if (defined(unsubscribe)) {
        unsubscribe();
        this.subscriptions.remove(id);
        this.showsUpdated.remove(id);
      }
      return true;
    }
    return false;
  };

  Batch$3.prototype.update = function (time) {
    let isUpdated = true;
    const removedCount = 0;
    let primitive = this.primitive;
    const primitives = this.primitives;
    let i;

    if (this.createPrimitive) {
      const geometries = this.geometry.values;
      const geometriesLength = geometries.length;
      if (geometriesLength > 0) {
        if (defined(primitive)) {
          if (!defined(this.oldPrimitive)) {
            this.oldPrimitive = primitive;
          } else {
            primitives.remove(primitive);
          }
        }

        primitive = new GroundPrimitive({
          show: false,
          asynchronous: true,
          geometryInstances: geometries.slice(),
          classificationType: this.classificationType,
        });
        primitives.add(primitive, this.zIndex);
        isUpdated = false;
      } else {
        if (defined(primitive)) {
          primitives.remove(primitive);
          primitive = undefined;
        }
        const oldPrimitive = this.oldPrimitive;
        if (defined(oldPrimitive)) {
          primitives.remove(oldPrimitive);
          this.oldPrimitive = undefined;
        }
      }

      this.attributes.removeAll();
      this.primitive = primitive;
      this.createPrimitive = false;
      this.waitingOnCreate = true;
    } else if (defined(primitive) && primitive.ready) {
      primitive.show = true;
      if (defined(this.oldPrimitive)) {
        primitives.remove(this.oldPrimitive);
        this.oldPrimitive = undefined;
      }
      const updatersWithAttributes = this.updatersWithAttributes.values;
      const length = updatersWithAttributes.length;
      const waitingOnCreate = this.waitingOnCreate;
      for (i = 0; i < length; i++) {
        const updater = updatersWithAttributes[i];
        const instance = this.geometry.get(updater.id);

        let attributes = this.attributes.get(instance.id.id);
        if (!defined(attributes)) {
          attributes = primitive.getGeometryInstanceAttributes(instance.id);
          this.attributes.set(instance.id.id, attributes);
        }

        if (!updater.fillMaterialProperty.isConstant || waitingOnCreate) {
          const colorProperty = updater.fillMaterialProperty.color;
          const fillColor = Property.getValueOrDefault(
            colorProperty,
            time,
            Color.WHITE,
            colorScratch$3
          );

          if (!Color.equals(attributes._lastColor, fillColor)) {
            attributes._lastColor = Color.clone(fillColor, attributes._lastColor);
            attributes.color = ColorGeometryInstanceAttribute.toValue(
              fillColor,
              attributes.color
            );
          }
        }

        const show =
          updater.entity.isShowing &&
          (updater.hasConstantFill || updater.isFilled(time));
        const currentShow = attributes.show[0] === 1;
        if (show !== currentShow) {
          attributes.show = ShowGeometryInstanceAttribute.toValue(
            show,
            attributes.show
          );
        }

        const distanceDisplayConditionProperty =
          updater.distanceDisplayConditionProperty;
        if (!Property.isConstant(distanceDisplayConditionProperty)) {
          const distanceDisplayCondition = Property.getValueOrDefault(
            distanceDisplayConditionProperty,
            time,
            defaultDistanceDisplayCondition$4,
            distanceDisplayConditionScratch$5
          );
          if (
            !DistanceDisplayCondition.equals(
              distanceDisplayCondition,
              attributes._lastDistanceDisplayCondition
            )
          ) {
            attributes._lastDistanceDisplayCondition = DistanceDisplayCondition.clone(
              distanceDisplayCondition,
              attributes._lastDistanceDisplayCondition
            );
            attributes.distanceDisplayCondition = DistanceDisplayConditionGeometryInstanceAttribute.toValue(
              distanceDisplayCondition,
              attributes.distanceDisplayCondition
            );
          }
        }
      }

      this.updateShows(primitive);
      this.waitingOnCreate = false;
    } else if (defined(primitive) && !primitive.ready) {
      isUpdated = false;
    }
    this.itemsToRemove.length = removedCount;
    return isUpdated;
  };

  Batch$3.prototype.updateShows = function (primitive) {
    const showsUpdated = this.showsUpdated.values;
    const length = showsUpdated.length;
    for (let i = 0; i < length; i++) {
      const updater = showsUpdated[i];
      const instance = this.geometry.get(updater.id);

      let attributes = this.attributes.get(instance.id.id);
      if (!defined(attributes)) {
        attributes = primitive.getGeometryInstanceAttributes(instance.id);
        this.attributes.set(instance.id.id, attributes);
      }

      const show = updater.entity.isShowing;
      const currentShow = attributes.show[0] === 1;
      if (show !== currentShow) {
        attributes.show = ShowGeometryInstanceAttribute.toValue(
          show,
          attributes.show
        );
        instance.attributes.show.value[0] = attributes.show[0];
      }
    }
    this.showsUpdated.removeAll();
  };

  Batch$3.prototype.contains = function (updater) {
    return this.updaters.contains(updater.id);
  };

  Batch$3.prototype.getBoundingSphere = function (updater, result) {
    const primitive = this.primitive;
    if (!primitive.ready) {
      return BoundingSphereState$1.PENDING;
    }

    const bs = primitive.getBoundingSphere(updater.entity);
    if (!defined(bs)) {
      return BoundingSphereState$1.FAILED;
    }

    bs.clone(result);
    return BoundingSphereState$1.DONE;
  };

  Batch$3.prototype.removeAllPrimitives = function () {
    const primitives = this.primitives;

    const primitive = this.primitive;
    if (defined(primitive)) {
      primitives.remove(primitive);
      this.primitive = undefined;
      this.geometry.removeAll();
      this.updaters.removeAll();
    }

    const oldPrimitive = this.oldPrimitive;
    if (defined(oldPrimitive)) {
      primitives.remove(oldPrimitive);
      this.oldPrimitive = undefined;
    }
  };

  /**
   * @private
   */
  function StaticGroundGeometryColorBatch(primitives, classificationType) {
    this._batches = [];
    this._primitives = primitives;
    this._classificationType = classificationType;
  }

  StaticGroundGeometryColorBatch.prototype.add = function (time, updater) {
    const instance = updater.createFillGeometryInstance(time);
    const batches = this._batches;
    const zIndex = Property.getValueOrDefault(updater.zIndex, 0);
    let batch;
    const length = batches.length;
    for (let i = 0; i < length; ++i) {
      const item = batches[i];
      if (
        item.zIndex === zIndex &&
        !item.overlapping(instance.geometry.rectangle)
      ) {
        batch = item;
        break;
      }
    }

    if (!defined(batch)) {
      batch = new Batch$3(
        this._primitives,
        this._classificationType,
        instance.attributes.color.value,
        zIndex
      );
      batches.push(batch);
    }
    batch.add(updater, instance);
    return batch;
  };

  StaticGroundGeometryColorBatch.prototype.remove = function (updater) {
    const batches = this._batches;
    const count = batches.length;
    for (let i = 0; i < count; ++i) {
      if (batches[i].remove(updater)) {
        return;
      }
    }
  };

  StaticGroundGeometryColorBatch.prototype.update = function (time) {
    let i;
    let updater;

    //Perform initial update
    let isUpdated = true;
    const batches = this._batches;
    const batchCount = batches.length;
    for (i = 0; i < batchCount; ++i) {
      isUpdated = batches[i].update(time) && isUpdated;
    }

    //If any items swapped between batches we need to move them
    for (i = 0; i < batchCount; ++i) {
      const oldBatch = batches[i];
      const itemsToRemove = oldBatch.itemsToRemove;
      const itemsToMoveLength = itemsToRemove.length;
      for (let j = 0; j < itemsToMoveLength; j++) {
        updater = itemsToRemove[j];
        oldBatch.remove(updater);
        const newBatch = this.add(time, updater);
        oldBatch.isDirty = true;
        newBatch.isDirty = true;
      }
    }

    //If we moved anything around, we need to re-build the primitive and remove empty batches
    for (i = batchCount - 1; i >= 0; --i) {
      const batch = batches[i];
      if (batch.isDirty) {
        isUpdated = batches[i].update(time) && isUpdated;
        batch.isDirty = false;
      }
      if (batch.geometry.length === 0) {
        batches.splice(i, 1);
      }
    }

    return isUpdated;
  };

  StaticGroundGeometryColorBatch.prototype.getBoundingSphere = function (
    updater,
    result
  ) {
    const batches = this._batches;
    const batchCount = batches.length;
    for (let i = 0; i < batchCount; ++i) {
      const batch = batches[i];
      if (batch.contains(updater)) {
        return batch.getBoundingSphere(updater, result);
      }
    }

    return BoundingSphereState$1.FAILED;
  };

  StaticGroundGeometryColorBatch.prototype.removeAllPrimitives = function () {
    const batches = this._batches;
    const batchCount = batches.length;
    for (let i = 0; i < batchCount; ++i) {
      batches[i].removeAllPrimitives();
    }
  };

  const distanceDisplayConditionScratch$4 = new DistanceDisplayCondition();
  const defaultDistanceDisplayCondition$3 = new DistanceDisplayCondition();

  // Encapsulates a Primitive and all the entities that it represents.
  function Batch$2(
    primitives,
    classificationType,
    appearanceType,
    materialProperty,
    usingSphericalTextureCoordinates,
    zIndex
  ) {
    this.primitives = primitives; // scene level primitive collection
    this.classificationType = classificationType;
    this.appearanceType = appearanceType;
    this.materialProperty = materialProperty;
    this.updaters = new AssociativeArray();
    this.createPrimitive = true;
    this.primitive = undefined; // a GroundPrimitive encapsulating all the entities
    this.oldPrimitive = undefined;
    this.geometry = new AssociativeArray();
    this.material = undefined;
    this.updatersWithAttributes = new AssociativeArray();
    this.attributes = new AssociativeArray();
    this.invalidated = false;
    this.removeMaterialSubscription = materialProperty.definitionChanged.addEventListener(
      Batch$2.prototype.onMaterialChanged,
      this
    );
    this.subscriptions = new AssociativeArray();
    this.showsUpdated = new AssociativeArray();
    this.usingSphericalTextureCoordinates = usingSphericalTextureCoordinates;
    this.zIndex = zIndex;
    this.rectangleCollisionCheck = new RectangleCollisionChecker();
  }

  Batch$2.prototype.onMaterialChanged = function () {
    this.invalidated = true;
  };

  Batch$2.prototype.overlapping = function (rectangle) {
    return this.rectangleCollisionCheck.collides(rectangle);
  };

  // Check if the given updater's material is compatible with this batch
  Batch$2.prototype.isMaterial = function (updater) {
    const material = this.materialProperty;
    const updaterMaterial = updater.fillMaterialProperty;

    if (
      updaterMaterial === material ||
      (updaterMaterial instanceof ColorMaterialProperty &&
        material instanceof ColorMaterialProperty)
    ) {
      return true;
    }
    return defined(material) && material.equals(updaterMaterial);
  };

  Batch$2.prototype.add = function (time, updater, geometryInstance) {
    const id = updater.id;
    this.updaters.set(id, updater);
    this.geometry.set(id, geometryInstance);
    this.rectangleCollisionCheck.insert(id, geometryInstance.geometry.rectangle);
    // Updaters with dynamic attributes must be tracked separately, may exit the batch
    if (
      !updater.hasConstantFill ||
      !updater.fillMaterialProperty.isConstant ||
      !Property.isConstant(updater.distanceDisplayConditionProperty)
    ) {
      this.updatersWithAttributes.set(id, updater);
    } else {
      const that = this;
      // Listen for show changes. These will be synchronized in updateShows.
      this.subscriptions.set(
        id,
        updater.entity.definitionChanged.addEventListener(function (
          entity,
          propertyName,
          newValue,
          oldValue
        ) {
          if (propertyName === "isShowing") {
            that.showsUpdated.set(updater.id, updater);
          }
        })
      );
    }
    this.createPrimitive = true;
  };

  Batch$2.prototype.remove = function (updater) {
    const id = updater.id;
    const geometryInstance = this.geometry.get(id);
    this.createPrimitive = this.geometry.remove(id) || this.createPrimitive;
    if (this.updaters.remove(id)) {
      this.rectangleCollisionCheck.remove(
        id,
        geometryInstance.geometry.rectangle
      );
      this.updatersWithAttributes.remove(id);
      const unsubscribe = this.subscriptions.get(id);
      if (defined(unsubscribe)) {
        unsubscribe();
        this.subscriptions.remove(id);
      }
      return true;
    }
    return false;
  };

  Batch$2.prototype.update = function (time) {
    let isUpdated = true;
    let primitive = this.primitive;
    const primitives = this.primitives;
    const geometries = this.geometry.values;
    let i;

    if (this.createPrimitive) {
      const geometriesLength = geometries.length;
      if (geometriesLength > 0) {
        if (defined(primitive)) {
          // Keep a handle to the old primitive so it can be removed when the updated version is ready.
          if (!defined(this.oldPrimitive)) {
            this.oldPrimitive = primitive;
          } else {
            // For if the new primitive changes again before it is ready.
            primitives.remove(primitive);
          }
        }

        this.material = MaterialProperty.getValue(
          time,
          this.materialProperty,
          this.material
        );

        primitive = new GroundPrimitive({
          show: false,
          asynchronous: true,
          geometryInstances: geometries.slice(),
          appearance: new this.appearanceType({
            material: this.material,
            // translucent and closed properties overridden
          }),
          classificationType: this.classificationType,
        });

        primitives.add(primitive, this.zIndex);
        isUpdated = false;
      } else {
        if (defined(primitive)) {
          primitives.remove(primitive);
          primitive = undefined;
        }
        const oldPrimitive = this.oldPrimitive;
        if (defined(oldPrimitive)) {
          primitives.remove(oldPrimitive);
          this.oldPrimitive = undefined;
        }
      }

      this.attributes.removeAll();
      this.primitive = primitive;
      this.createPrimitive = false;
    } else if (defined(primitive) && primitive.ready) {
      primitive.show = true;
      if (defined(this.oldPrimitive)) {
        primitives.remove(this.oldPrimitive);
        this.oldPrimitive = undefined;
      }

      this.material = MaterialProperty.getValue(
        time,
        this.materialProperty,
        this.material
      );
      this.primitive.appearance.material = this.material;

      const updatersWithAttributes = this.updatersWithAttributes.values;
      const length = updatersWithAttributes.length;
      for (i = 0; i < length; i++) {
        const updater = updatersWithAttributes[i];
        const entity = updater.entity;
        const instance = this.geometry.get(updater.id);

        let attributes = this.attributes.get(instance.id.id);
        if (!defined(attributes)) {
          attributes = primitive.getGeometryInstanceAttributes(instance.id);
          this.attributes.set(instance.id.id, attributes);
        }

        const show =
          entity.isShowing && (updater.hasConstantFill || updater.isFilled(time));
        const currentShow = attributes.show[0] === 1;
        if (show !== currentShow) {
          attributes.show = ShowGeometryInstanceAttribute.toValue(
            show,
            attributes.show
          );
        }

        const distanceDisplayConditionProperty =
          updater.distanceDisplayConditionProperty;
        if (!Property.isConstant(distanceDisplayConditionProperty)) {
          const distanceDisplayCondition = Property.getValueOrDefault(
            distanceDisplayConditionProperty,
            time,
            defaultDistanceDisplayCondition$3,
            distanceDisplayConditionScratch$4
          );
          if (
            !DistanceDisplayCondition.equals(
              distanceDisplayCondition,
              attributes._lastDistanceDisplayCondition
            )
          ) {
            attributes._lastDistanceDisplayCondition = DistanceDisplayCondition.clone(
              distanceDisplayCondition,
              attributes._lastDistanceDisplayCondition
            );
            attributes.distanceDisplayCondition = DistanceDisplayConditionGeometryInstanceAttribute.toValue(
              distanceDisplayCondition,
              attributes.distanceDisplayCondition
            );
          }
        }
      }

      this.updateShows(primitive);
    } else if (defined(primitive) && !primitive.ready) {
      isUpdated = false;
    }
    return isUpdated;
  };

  Batch$2.prototype.updateShows = function (primitive) {
    const showsUpdated = this.showsUpdated.values;
    const length = showsUpdated.length;
    for (let i = 0; i < length; i++) {
      const updater = showsUpdated[i];
      const entity = updater.entity;
      const instance = this.geometry.get(updater.id);

      let attributes = this.attributes.get(instance.id.id);
      if (!defined(attributes)) {
        attributes = primitive.getGeometryInstanceAttributes(instance.id);
        this.attributes.set(instance.id.id, attributes);
      }

      const show = entity.isShowing;
      const currentShow = attributes.show[0] === 1;
      if (show !== currentShow) {
        attributes.show = ShowGeometryInstanceAttribute.toValue(
          show,
          attributes.show
        );
        instance.attributes.show.value[0] = attributes.show[0];
      }
    }
    this.showsUpdated.removeAll();
  };

  Batch$2.prototype.contains = function (updater) {
    return this.updaters.contains(updater.id);
  };

  Batch$2.prototype.getBoundingSphere = function (updater, result) {
    const primitive = this.primitive;
    if (!primitive.ready) {
      return BoundingSphereState$1.PENDING;
    }
    const attributes = primitive.getGeometryInstanceAttributes(updater.entity);
    if (
      !defined(attributes) ||
      !defined(attributes.boundingSphere) ||
      (defined(attributes.show) && attributes.show[0] === 0)
    ) {
      return BoundingSphereState$1.FAILED;
    }
    attributes.boundingSphere.clone(result);
    return BoundingSphereState$1.DONE;
  };

  Batch$2.prototype.destroy = function () {
    const primitive = this.primitive;
    const primitives = this.primitives;
    if (defined(primitive)) {
      primitives.remove(primitive);
    }
    const oldPrimitive = this.oldPrimitive;
    if (defined(oldPrimitive)) {
      primitives.remove(oldPrimitive);
    }
    this.removeMaterialSubscription();
  };

  /**
   * @private
   */
  function StaticGroundGeometryPerMaterialBatch(
    primitives,
    classificationType,
    appearanceType
  ) {
    this._items = [];
    this._primitives = primitives;
    this._classificationType = classificationType;
    this._appearanceType = appearanceType;
  }

  StaticGroundGeometryPerMaterialBatch.prototype.add = function (time, updater) {
    const items = this._items;
    const length = items.length;
    const geometryInstance = updater.createFillGeometryInstance(time);
    const usingSphericalTextureCoordinates = ShadowVolumeAppearance.shouldUseSphericalCoordinates(
      geometryInstance.geometry.rectangle
    );
    const zIndex = Property.getValueOrDefault(updater.zIndex, 0);
    // Check if the Entity represented by the updater can be placed in an existing batch. Requirements:
    // * compatible material (same material or same color)
    // * same type of texture coordinates (spherical vs. planar)
    // * conservatively non-overlapping with any entities in the existing batch
    for (let i = 0; i < length; ++i) {
      const item = items[i];
      if (
        item.isMaterial(updater) &&
        item.usingSphericalTextureCoordinates ===
          usingSphericalTextureCoordinates &&
        item.zIndex === zIndex &&
        !item.overlapping(geometryInstance.geometry.rectangle)
      ) {
        item.add(time, updater, geometryInstance);
        return;
      }
    }
    // If a compatible batch wasn't found, create a new batch.
    const batch = new Batch$2(
      this._primitives,
      this._classificationType,
      this._appearanceType,
      updater.fillMaterialProperty,
      usingSphericalTextureCoordinates,
      zIndex
    );
    batch.add(time, updater, geometryInstance);
    items.push(batch);
  };

  StaticGroundGeometryPerMaterialBatch.prototype.remove = function (updater) {
    const items = this._items;
    const length = items.length;
    for (let i = length - 1; i >= 0; i--) {
      const item = items[i];
      if (item.remove(updater)) {
        if (item.updaters.length === 0) {
          items.splice(i, 1);
          item.destroy();
        }
        break;
      }
    }
  };

  StaticGroundGeometryPerMaterialBatch.prototype.update = function (time) {
    let i;
    const items = this._items;
    const length = items.length;

    for (i = length - 1; i >= 0; i--) {
      const item = items[i];
      if (item.invalidated) {
        items.splice(i, 1);
        const updaters = item.updaters.values;
        const updatersLength = updaters.length;
        for (let h = 0; h < updatersLength; h++) {
          this.add(time, updaters[h]);
        }
        item.destroy();
      }
    }

    let isUpdated = true;
    for (i = 0; i < items.length; i++) {
      isUpdated = items[i].update(time) && isUpdated;
    }
    return isUpdated;
  };

  StaticGroundGeometryPerMaterialBatch.prototype.getBoundingSphere = function (
    updater,
    result
  ) {
    const items = this._items;
    const length = items.length;
    for (let i = 0; i < length; i++) {
      const item = items[i];
      if (item.contains(updater)) {
        return item.getBoundingSphere(updater, result);
      }
    }
    return BoundingSphereState$1.FAILED;
  };

  StaticGroundGeometryPerMaterialBatch.prototype.removeAllPrimitives = function () {
    const items = this._items;
    const length = items.length;
    for (let i = 0; i < length; i++) {
      items[i].destroy();
    }
    this._items.length = 0;
  };

  const colorScratch$2 = new Color();
  const distanceDisplayConditionScratch$3 = new DistanceDisplayCondition();
  const defaultDistanceDisplayCondition$2 = new DistanceDisplayCondition();
  const defaultOffset = Cartesian3.ZERO;
  const offsetScratch = new Cartesian3();

  function Batch$1(primitives, translucent, width, shadows) {
    this.translucent = translucent;
    this.width = width;
    this.shadows = shadows;
    this.primitives = primitives;
    this.createPrimitive = false;
    this.waitingOnCreate = false;
    this.primitive = undefined;
    this.oldPrimitive = undefined;
    this.geometry = new AssociativeArray();
    this.updaters = new AssociativeArray();
    this.updatersWithAttributes = new AssociativeArray();
    this.attributes = new AssociativeArray();
    this.itemsToRemove = [];
    this.subscriptions = new AssociativeArray();
    this.showsUpdated = new AssociativeArray();
  }
  Batch$1.prototype.add = function (updater, instance) {
    const id = updater.id;
    this.createPrimitive = true;
    this.geometry.set(id, instance);
    this.updaters.set(id, updater);
    if (
      !updater.hasConstantOutline ||
      !updater.outlineColorProperty.isConstant ||
      !Property.isConstant(updater.distanceDisplayConditionProperty) ||
      !Property.isConstant(updater.terrainOffsetProperty)
    ) {
      this.updatersWithAttributes.set(id, updater);
    } else {
      const that = this;
      this.subscriptions.set(
        id,
        updater.entity.definitionChanged.addEventListener(function (
          entity,
          propertyName,
          newValue,
          oldValue
        ) {
          if (propertyName === "isShowing") {
            that.showsUpdated.set(updater.id, updater);
          }
        })
      );
    }
  };

  Batch$1.prototype.remove = function (updater) {
    const id = updater.id;
    this.createPrimitive = this.geometry.remove(id) || this.createPrimitive;
    if (this.updaters.remove(id)) {
      this.updatersWithAttributes.remove(id);
      const unsubscribe = this.subscriptions.get(id);
      if (defined(unsubscribe)) {
        unsubscribe();
        this.subscriptions.remove(id);
        this.showsUpdated.remove(id);
      }
      return true;
    }
    return false;
  };

  Batch$1.prototype.update = function (time) {
    let isUpdated = true;
    let removedCount = 0;
    let primitive = this.primitive;
    const primitives = this.primitives;
    let i;

    if (this.createPrimitive) {
      const geometries = this.geometry.values;
      const geometriesLength = geometries.length;
      if (geometriesLength > 0) {
        if (defined(primitive)) {
          if (!defined(this.oldPrimitive)) {
            this.oldPrimitive = primitive;
          } else {
            primitives.remove(primitive);
          }
        }

        primitive = new Primitive$3({
          show: false,
          asynchronous: true,
          geometryInstances: geometries.slice(),
          appearance: new PerInstanceColorAppearance({
            flat: true,
            translucent: this.translucent,
            renderState: {
              lineWidth: this.width,
            },
          }),
          shadows: this.shadows,
        });

        primitives.add(primitive);
        isUpdated = false;
      } else {
        if (defined(primitive)) {
          primitives.remove(primitive);
          primitive = undefined;
        }
        const oldPrimitive = this.oldPrimitive;
        if (defined(oldPrimitive)) {
          primitives.remove(oldPrimitive);
          this.oldPrimitive = undefined;
        }
      }

      this.attributes.removeAll();
      this.primitive = primitive;
      this.createPrimitive = false;
      this.waitingOnCreate = true;
    } else if (defined(primitive) && primitive.ready) {
      primitive.show = true;
      if (defined(this.oldPrimitive)) {
        primitives.remove(this.oldPrimitive);
        this.oldPrimitive = undefined;
      }

      const updatersWithAttributes = this.updatersWithAttributes.values;
      const length = updatersWithAttributes.length;
      const waitingOnCreate = this.waitingOnCreate;
      for (i = 0; i < length; i++) {
        const updater = updatersWithAttributes[i];
        const instance = this.geometry.get(updater.id);

        let attributes = this.attributes.get(instance.id.id);
        if (!defined(attributes)) {
          attributes = primitive.getGeometryInstanceAttributes(instance.id);
          this.attributes.set(instance.id.id, attributes);
        }

        if (!updater.outlineColorProperty.isConstant || waitingOnCreate) {
          const outlineColorProperty = updater.outlineColorProperty;
          const outlineColor = Property.getValueOrDefault(
            outlineColorProperty,
            time,
            Color.WHITE,
            colorScratch$2
          );
          if (!Color.equals(attributes._lastColor, outlineColor)) {
            attributes._lastColor = Color.clone(
              outlineColor,
              attributes._lastColor
            );
            attributes.color = ColorGeometryInstanceAttribute.toValue(
              outlineColor,
              attributes.color
            );
            if (
              (this.translucent && attributes.color[3] === 255) ||
              (!this.translucent && attributes.color[3] !== 255)
            ) {
              this.itemsToRemove[removedCount++] = updater;
            }
          }
        }

        const show =
          updater.entity.isShowing &&
          (updater.hasConstantOutline || updater.isOutlineVisible(time));
        const currentShow = attributes.show[0] === 1;
        if (show !== currentShow) {
          attributes.show = ShowGeometryInstanceAttribute.toValue(
            show,
            attributes.show
          );
        }

        const distanceDisplayConditionProperty =
          updater.distanceDisplayConditionProperty;
        if (!Property.isConstant(distanceDisplayConditionProperty)) {
          const distanceDisplayCondition = Property.getValueOrDefault(
            distanceDisplayConditionProperty,
            time,
            defaultDistanceDisplayCondition$2,
            distanceDisplayConditionScratch$3
          );
          if (
            !DistanceDisplayCondition.equals(
              distanceDisplayCondition,
              attributes._lastDistanceDisplayCondition
            )
          ) {
            attributes._lastDistanceDisplayCondition = DistanceDisplayCondition.clone(
              distanceDisplayCondition,
              attributes._lastDistanceDisplayCondition
            );
            attributes.distanceDisplayCondition = DistanceDisplayConditionGeometryInstanceAttribute.toValue(
              distanceDisplayCondition,
              attributes.distanceDisplayCondition
            );
          }
        }

        const offsetProperty = updater.terrainOffsetProperty;
        if (!Property.isConstant(offsetProperty)) {
          const offset = Property.getValueOrDefault(
            offsetProperty,
            time,
            defaultOffset,
            offsetScratch
          );
          if (!Cartesian3.equals(offset, attributes._lastOffset)) {
            attributes._lastOffset = Cartesian3.clone(
              offset,
              attributes._lastOffset
            );
            attributes.offset = OffsetGeometryInstanceAttribute.toValue(
              offset,
              attributes.offset
            );
          }
        }
      }

      this.updateShows(primitive);
      this.waitingOnCreate = false;
    } else if (defined(primitive) && !primitive.ready) {
      isUpdated = false;
    }

    this.itemsToRemove.length = removedCount;
    return isUpdated;
  };

  Batch$1.prototype.updateShows = function (primitive) {
    const showsUpdated = this.showsUpdated.values;
    const length = showsUpdated.length;
    for (let i = 0; i < length; i++) {
      const updater = showsUpdated[i];
      const instance = this.geometry.get(updater.id);

      let attributes = this.attributes.get(instance.id.id);
      if (!defined(attributes)) {
        attributes = primitive.getGeometryInstanceAttributes(instance.id);
        this.attributes.set(instance.id.id, attributes);
      }

      const show = updater.entity.isShowing;
      const currentShow = attributes.show[0] === 1;
      if (show !== currentShow) {
        attributes.show = ShowGeometryInstanceAttribute.toValue(
          show,
          attributes.show
        );
        instance.attributes.show.value[0] = attributes.show[0];
      }
    }
    this.showsUpdated.removeAll();
  };

  Batch$1.prototype.contains = function (updater) {
    return this.updaters.contains(updater.id);
  };

  Batch$1.prototype.getBoundingSphere = function (updater, result) {
    const primitive = this.primitive;
    if (!primitive.ready) {
      return BoundingSphereState$1.PENDING;
    }
    const attributes = primitive.getGeometryInstanceAttributes(updater.entity);
    if (
      !defined(attributes) ||
      !defined(attributes.boundingSphere) || //
      (defined(attributes.show) && attributes.show[0] === 0)
    ) {
      return BoundingSphereState$1.FAILED;
    }
    attributes.boundingSphere.clone(result);
    return BoundingSphereState$1.DONE;
  };

  Batch$1.prototype.removeAllPrimitives = function () {
    const primitives = this.primitives;

    const primitive = this.primitive;
    if (defined(primitive)) {
      primitives.remove(primitive);
      this.primitive = undefined;
      this.geometry.removeAll();
      this.updaters.removeAll();
    }

    const oldPrimitive = this.oldPrimitive;
    if (defined(oldPrimitive)) {
      primitives.remove(oldPrimitive);
      this.oldPrimitive = undefined;
    }
  };

  /**
   * @private
   */
  function StaticOutlineGeometryBatch(primitives, scene, shadows) {
    this._primitives = primitives;
    this._scene = scene;
    this._shadows = shadows;
    this._solidBatches = new AssociativeArray();
    this._translucentBatches = new AssociativeArray();
  }
  StaticOutlineGeometryBatch.prototype.add = function (time, updater) {
    const instance = updater.createOutlineGeometryInstance(time);
    const width = this._scene.clampLineWidth(updater.outlineWidth);
    let batches;
    let batch;
    if (instance.attributes.color.value[3] === 255) {
      batches = this._solidBatches;
      batch = batches.get(width);
      if (!defined(batch)) {
        batch = new Batch$1(this._primitives, false, width, this._shadows);
        batches.set(width, batch);
      }
      batch.add(updater, instance);
    } else {
      batches = this._translucentBatches;
      batch = batches.get(width);
      if (!defined(batch)) {
        batch = new Batch$1(this._primitives, true, width, this._shadows);
        batches.set(width, batch);
      }
      batch.add(updater, instance);
    }
  };

  StaticOutlineGeometryBatch.prototype.remove = function (updater) {
    let i;

    const solidBatches = this._solidBatches.values;
    const solidBatchesLength = solidBatches.length;
    for (i = 0; i < solidBatchesLength; i++) {
      if (solidBatches[i].remove(updater)) {
        return;
      }
    }

    const translucentBatches = this._translucentBatches.values;
    const translucentBatchesLength = translucentBatches.length;
    for (i = 0; i < translucentBatchesLength; i++) {
      if (translucentBatches[i].remove(updater)) {
        return;
      }
    }
  };

  StaticOutlineGeometryBatch.prototype.update = function (time) {
    let i;
    let x;
    let updater;
    let batch;
    const solidBatches = this._solidBatches.values;
    const solidBatchesLength = solidBatches.length;
    const translucentBatches = this._translucentBatches.values;
    const translucentBatchesLength = translucentBatches.length;
    let itemsToRemove;
    let isUpdated = true;
    let needUpdate = false;

    do {
      needUpdate = false;
      for (x = 0; x < solidBatchesLength; x++) {
        batch = solidBatches[x];
        //Perform initial update
        isUpdated = batch.update(time);

        //If any items swapped between solid/translucent, we need to
        //move them between batches
        itemsToRemove = batch.itemsToRemove;
        const solidsToMoveLength = itemsToRemove.length;
        if (solidsToMoveLength > 0) {
          needUpdate = true;
          for (i = 0; i < solidsToMoveLength; i++) {
            updater = itemsToRemove[i];
            batch.remove(updater);
            this.add(time, updater);
          }
        }
      }
      for (x = 0; x < translucentBatchesLength; x++) {
        batch = translucentBatches[x];
        //Perform initial update
        isUpdated = batch.update(time);

        //If any items swapped between solid/translucent, we need to
        //move them between batches
        itemsToRemove = batch.itemsToRemove;
        const translucentToMoveLength = itemsToRemove.length;
        if (translucentToMoveLength > 0) {
          needUpdate = true;
          for (i = 0; i < translucentToMoveLength; i++) {
            updater = itemsToRemove[i];
            batch.remove(updater);
            this.add(time, updater);
          }
        }
      }
    } while (needUpdate);

    return isUpdated;
  };

  StaticOutlineGeometryBatch.prototype.getBoundingSphere = function (
    updater,
    result
  ) {
    let i;

    const solidBatches = this._solidBatches.values;
    const solidBatchesLength = solidBatches.length;
    for (i = 0; i < solidBatchesLength; i++) {
      const solidBatch = solidBatches[i];
      if (solidBatch.contains(updater)) {
        return solidBatch.getBoundingSphere(updater, result);
      }
    }

    const translucentBatches = this._translucentBatches.values;
    const translucentBatchesLength = translucentBatches.length;
    for (i = 0; i < translucentBatchesLength; i++) {
      const translucentBatch = translucentBatches[i];
      if (translucentBatch.contains(updater)) {
        return translucentBatch.getBoundingSphere(updater, result);
      }
    }

    return BoundingSphereState$1.FAILED;
  };

  StaticOutlineGeometryBatch.prototype.removeAllPrimitives = function () {
    let i;

    const solidBatches = this._solidBatches.values;
    const solidBatchesLength = solidBatches.length;
    for (i = 0; i < solidBatchesLength; i++) {
      solidBatches[i].removeAllPrimitives();
    }

    const translucentBatches = this._translucentBatches.values;
    const translucentBatchesLength = translucentBatches.length;
    for (i = 0; i < translucentBatchesLength; i++) {
      translucentBatches[i].removeAllPrimitives();
    }
  };

  const scratchColor$5 = new Color();

  function WallGeometryOptions(entity) {
    this.id = entity;
    this.vertexFormat = undefined;
    this.positions = undefined;
    this.minimumHeights = undefined;
    this.maximumHeights = undefined;
    this.granularity = undefined;
  }

  /**
   * A {@link GeometryUpdater} for walls.
   * Clients do not normally create this class directly, but instead rely on {@link DataSourceDisplay}.
   * @alias WallGeometryUpdater
   * @constructor
   *
   * @param {Entity} entity The entity containing the geometry to be visualized.
   * @param {Scene} scene The scene where visualization is taking place.
   */
  function WallGeometryUpdater(entity, scene) {
    GeometryUpdater.call(this, {
      entity: entity,
      scene: scene,
      geometryOptions: new WallGeometryOptions(entity),
      geometryPropertyName: "wall",
      observedPropertyNames: ["availability", "wall"],
    });

    this._onEntityPropertyChanged(entity, "wall", entity.wall, undefined);
  }

  if (defined(Object.create)) {
    WallGeometryUpdater.prototype = Object.create(GeometryUpdater.prototype);
    WallGeometryUpdater.prototype.constructor = WallGeometryUpdater;
  }

  /**
   * Creates the geometry instance which represents the fill of the geometry.
   *
   * @param {JulianDate} time The time to use when retrieving initial attribute values.
   * @returns {GeometryInstance} The geometry instance representing the filled portion of the geometry.
   *
   * @exception {DeveloperError} This instance does not represent a filled geometry.
   */
  WallGeometryUpdater.prototype.createFillGeometryInstance = function (time) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("time", time);

    if (!this._fillEnabled) {
      throw new DeveloperError(
        "This instance does not represent a filled geometry."
      );
    }
    //>>includeEnd('debug');

    const entity = this._entity;
    const isAvailable = entity.isAvailable(time);

    let attributes;

    let color;
    const show = new ShowGeometryInstanceAttribute(
      isAvailable &&
        entity.isShowing &&
        this._showProperty.getValue(time) &&
        this._fillProperty.getValue(time)
    );
    const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
      time
    );
    const distanceDisplayConditionAttribute = DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
      distanceDisplayCondition
    );
    if (this._materialProperty instanceof ColorMaterialProperty) {
      let currentColor;
      if (
        defined(this._materialProperty.color) &&
        (this._materialProperty.color.isConstant || isAvailable)
      ) {
        currentColor = this._materialProperty.color.getValue(time, scratchColor$5);
      }
      if (!defined(currentColor)) {
        currentColor = Color.WHITE;
      }
      color = ColorGeometryInstanceAttribute.fromColor(currentColor);
      attributes = {
        show: show,
        distanceDisplayCondition: distanceDisplayConditionAttribute,
        color: color,
      };
    } else {
      attributes = {
        show: show,
        distanceDisplayCondition: distanceDisplayConditionAttribute,
      };
    }

    return new GeometryInstance({
      id: entity,
      geometry: new WallGeometry(this._options),
      attributes: attributes,
    });
  };

  /**
   * Creates the geometry instance which represents the outline of the geometry.
   *
   * @param {JulianDate} time The time to use when retrieving initial attribute values.
   * @returns {GeometryInstance} The geometry instance representing the outline portion of the geometry.
   *
   * @exception {DeveloperError} This instance does not represent an outlined geometry.
   */
  WallGeometryUpdater.prototype.createOutlineGeometryInstance = function (time) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("time", time);

    if (!this._outlineEnabled) {
      throw new DeveloperError(
        "This instance does not represent an outlined geometry."
      );
    }
    //>>includeEnd('debug');

    const entity = this._entity;
    const isAvailable = entity.isAvailable(time);
    const outlineColor = Property.getValueOrDefault(
      this._outlineColorProperty,
      time,
      Color.BLACK,
      scratchColor$5
    );
    const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
      time
    );

    return new GeometryInstance({
      id: entity,
      geometry: new WallOutlineGeometry(this._options),
      attributes: {
        show: new ShowGeometryInstanceAttribute(
          isAvailable &&
            entity.isShowing &&
            this._showProperty.getValue(time) &&
            this._showOutlineProperty.getValue(time)
        ),
        color: ColorGeometryInstanceAttribute.fromColor(outlineColor),
        distanceDisplayCondition: DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
          distanceDisplayCondition
        ),
      },
    });
  };

  WallGeometryUpdater.prototype._isHidden = function (entity, wall) {
    return (
      !defined(wall.positions) ||
      GeometryUpdater.prototype._isHidden.call(this, entity, wall)
    );
  };

  WallGeometryUpdater.prototype._getIsClosed = function (options) {
    return false;
  };

  WallGeometryUpdater.prototype._isDynamic = function (entity, wall) {
    return (
      !wall.positions.isConstant || //
      !Property.isConstant(wall.minimumHeights) || //
      !Property.isConstant(wall.maximumHeights) || //
      !Property.isConstant(wall.outlineWidth) || //
      !Property.isConstant(wall.granularity)
    );
  };

  WallGeometryUpdater.prototype._setStaticOptions = function (entity, wall) {
    const minimumHeights = wall.minimumHeights;
    const maximumHeights = wall.maximumHeights;
    const granularity = wall.granularity;
    const isColorMaterial =
      this._materialProperty instanceof ColorMaterialProperty;

    const options = this._options;
    options.vertexFormat = isColorMaterial
      ? PerInstanceColorAppearance.VERTEX_FORMAT
      : MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat;
    options.positions = wall.positions.getValue(
      Iso8601.MINIMUM_VALUE,
      options.positions
    );
    options.minimumHeights = defined(minimumHeights)
      ? minimumHeights.getValue(Iso8601.MINIMUM_VALUE, options.minimumHeights)
      : undefined;
    options.maximumHeights = defined(maximumHeights)
      ? maximumHeights.getValue(Iso8601.MINIMUM_VALUE, options.maximumHeights)
      : undefined;
    options.granularity = defined(granularity)
      ? granularity.getValue(Iso8601.MINIMUM_VALUE)
      : undefined;
  };

  WallGeometryUpdater.DynamicGeometryUpdater = DynamicWallGeometryUpdater;

  /**
   * @private
   */
  function DynamicWallGeometryUpdater(
    geometryUpdater,
    primitives,
    groundPrimitives
  ) {
    DynamicGeometryUpdater$1.call(
      this,
      geometryUpdater,
      primitives,
      groundPrimitives
    );
  }

  if (defined(Object.create)) {
    DynamicWallGeometryUpdater.prototype = Object.create(
      DynamicGeometryUpdater$1.prototype
    );
    DynamicWallGeometryUpdater.prototype.constructor = DynamicWallGeometryUpdater;
  }

  DynamicWallGeometryUpdater.prototype._isHidden = function (entity, wall, time) {
    return (
      !defined(this._options.positions) ||
      DynamicGeometryUpdater$1.prototype._isHidden.call(this, entity, wall, time)
    );
  };

  DynamicWallGeometryUpdater.prototype._setOptions = function (
    entity,
    wall,
    time
  ) {
    const options = this._options;
    options.positions = Property.getValueOrUndefined(
      wall.positions,
      time,
      options.positions
    );
    options.minimumHeights = Property.getValueOrUndefined(
      wall.minimumHeights,
      time,
      options.minimumHeights
    );
    options.maximumHeights = Property.getValueOrUndefined(
      wall.maximumHeights,
      time,
      options.maximumHeights
    );
    options.granularity = Property.getValueOrUndefined(wall.granularity, time);
  };

  const emptyArray$1 = [];

  const geometryUpdaters = [
    BoxGeometryUpdater,
    CylinderGeometryUpdater,
    CorridorGeometryUpdater,
    EllipseGeometryUpdater,
    EllipsoidGeometryUpdater,
    PlaneGeometryUpdater,
    PolygonGeometryUpdater,
    PolylineVolumeGeometryUpdater,
    RectangleGeometryUpdater,
    WallGeometryUpdater,
  ];

  function GeometryUpdaterSet(entity, scene) {
    this.entity = entity;
    this.scene = scene;
    const updaters = new Array(geometryUpdaters.length);
    const geometryChanged = new Event();
    function raiseEvent(geometry) {
      geometryChanged.raiseEvent(geometry);
    }
    const eventHelper = new EventHelper();
    for (let i = 0; i < updaters.length; i++) {
      const updater = new geometryUpdaters[i](entity, scene);
      eventHelper.add(updater.geometryChanged, raiseEvent);
      updaters[i] = updater;
    }
    this.updaters = updaters;
    this.geometryChanged = geometryChanged;
    this.eventHelper = eventHelper;

    this._removeEntitySubscription = entity.definitionChanged.addEventListener(
      GeometryUpdaterSet.prototype._onEntityPropertyChanged,
      this
    );
  }

  GeometryUpdaterSet.prototype._onEntityPropertyChanged = function (
    entity,
    propertyName,
    newValue,
    oldValue
  ) {
    const updaters = this.updaters;
    for (let i = 0; i < updaters.length; i++) {
      updaters[i]._onEntityPropertyChanged(
        entity,
        propertyName,
        newValue,
        oldValue
      );
    }
  };

  GeometryUpdaterSet.prototype.forEach = function (callback) {
    const updaters = this.updaters;
    for (let i = 0; i < updaters.length; i++) {
      callback(updaters[i]);
    }
  };

  GeometryUpdaterSet.prototype.destroy = function () {
    this.eventHelper.removeAll();
    const updaters = this.updaters;
    for (let i = 0; i < updaters.length; i++) {
      updaters[i].destroy();
    }
    this._removeEntitySubscription();
    destroyObject(this);
  };

  /**
   * A general purpose visualizer for geometry represented by {@link Primitive} instances.
   * @alias GeometryVisualizer
   * @constructor
   *
   * @param {Scene} scene The scene the primitives will be rendered in.
   * @param {EntityCollection} entityCollection The entityCollection to visualize.
   * @param {PrimitiveCollection} [primitives=scene.primitives] A collection to add primitives related to the entities
   * @param {PrimitiveCollection} [groundPrimitives=scene.groundPrimitives] A collection to add ground primitives related to the entities
   */
  function GeometryVisualizer(
    scene,
    entityCollection,
    primitives,
    groundPrimitives
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("scene", scene);
    Check.defined("entityCollection", entityCollection);
    //>>includeEnd('debug');

    primitives = defaultValue(primitives, scene.primitives);
    groundPrimitives = defaultValue(groundPrimitives, scene.groundPrimitives);

    this._scene = scene;
    this._primitives = primitives;
    this._groundPrimitives = groundPrimitives;
    this._entityCollection = undefined;
    this._addedObjects = new AssociativeArray();
    this._removedObjects = new AssociativeArray();
    this._changedObjects = new AssociativeArray();

    const numberOfShadowModes = ShadowMode$1.NUMBER_OF_SHADOW_MODES;
    this._outlineBatches = new Array(numberOfShadowModes * 2);
    this._closedColorBatches = new Array(numberOfShadowModes * 2);
    this._closedMaterialBatches = new Array(numberOfShadowModes * 2);
    this._openColorBatches = new Array(numberOfShadowModes * 2);
    this._openMaterialBatches = new Array(numberOfShadowModes * 2);

    const supportsMaterialsforEntitiesOnTerrain = Entity.supportsMaterialsforEntitiesOnTerrain(
      scene
    );
    this._supportsMaterialsforEntitiesOnTerrain = supportsMaterialsforEntitiesOnTerrain;

    let i;
    for (i = 0; i < numberOfShadowModes; ++i) {
      this._outlineBatches[i] = new StaticOutlineGeometryBatch(
        primitives,
        scene,
        i);
      this._outlineBatches[
        numberOfShadowModes + i
      ] = new StaticOutlineGeometryBatch(primitives, scene, i);

      this._closedColorBatches[i] = new StaticGeometryColorBatch(
        primitives,
        PerInstanceColorAppearance,
        undefined,
        true,
        i);
      this._closedColorBatches[
        numberOfShadowModes + i
      ] = new StaticGeometryColorBatch(
        primitives,
        PerInstanceColorAppearance,
        undefined,
        true,
        i);

      this._closedMaterialBatches[i] = new StaticGeometryPerMaterialBatch(
        primitives,
        MaterialAppearance,
        undefined,
        true,
        i);
      this._closedMaterialBatches[
        numberOfShadowModes + i
      ] = new StaticGeometryPerMaterialBatch(
        primitives,
        MaterialAppearance,
        undefined,
        true,
        i);

      this._openColorBatches[i] = new StaticGeometryColorBatch(
        primitives,
        PerInstanceColorAppearance,
        undefined,
        false,
        i);
      this._openColorBatches[
        numberOfShadowModes + i
      ] = new StaticGeometryColorBatch(
        primitives,
        PerInstanceColorAppearance,
        undefined,
        false,
        i);

      this._openMaterialBatches[i] = new StaticGeometryPerMaterialBatch(
        primitives,
        MaterialAppearance,
        undefined,
        false,
        i);
      this._openMaterialBatches[
        numberOfShadowModes + i
      ] = new StaticGeometryPerMaterialBatch(
        primitives,
        MaterialAppearance,
        undefined,
        false,
        i);
    }

    const numberOfClassificationTypes =
      ClassificationType$1.NUMBER_OF_CLASSIFICATION_TYPES;
    const groundColorBatches = new Array(numberOfClassificationTypes);
    const groundMaterialBatches = [];
    if (supportsMaterialsforEntitiesOnTerrain) {
      for (i = 0; i < numberOfClassificationTypes; ++i) {
        groundMaterialBatches.push(
          new StaticGroundGeometryPerMaterialBatch(
            groundPrimitives,
            i,
            MaterialAppearance
          )
        );
        groundColorBatches[i] = new StaticGroundGeometryColorBatch(
          groundPrimitives,
          i
        );
      }
    } else {
      for (i = 0; i < numberOfClassificationTypes; ++i) {
        groundColorBatches[i] = new StaticGroundGeometryColorBatch(
          groundPrimitives,
          i
        );
      }
    }

    this._groundColorBatches = groundColorBatches;
    this._groundMaterialBatches = groundMaterialBatches;

    this._dynamicBatch = new DynamicGeometryBatch(primitives, groundPrimitives);

    this._batches = this._outlineBatches.concat(
      this._closedColorBatches,
      this._closedMaterialBatches,
      this._openColorBatches,
      this._openMaterialBatches,
      this._groundColorBatches,
      this._groundMaterialBatches,
      this._dynamicBatch
    );

    this._subscriptions = new AssociativeArray();
    this._updaterSets = new AssociativeArray();

    this._entityCollection = entityCollection;
    entityCollection.collectionChanged.addEventListener(
      GeometryVisualizer.prototype._onCollectionChanged,
      this
    );
    this._onCollectionChanged(
      entityCollection,
      entityCollection.values,
      emptyArray$1
    );
  }

  /**
   * Updates all of the primitives created by this visualizer to match their
   * Entity counterpart at the given time.
   *
   * @param {JulianDate} time The time to update to.
   * @returns {Boolean} True if the visualizer successfully updated to the provided time,
   * false if the visualizer is waiting for asynchronous primitives to be created.
   */
  GeometryVisualizer.prototype.update = function (time) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("time", time);
    //>>includeEnd('debug');

    const addedObjects = this._addedObjects;
    const added = addedObjects.values;
    const removedObjects = this._removedObjects;
    const removed = removedObjects.values;
    const changedObjects = this._changedObjects;
    const changed = changedObjects.values;

    let i;
    let entity;
    let id;
    let updaterSet;
    const that = this;

    for (i = changed.length - 1; i > -1; i--) {
      entity = changed[i];
      id = entity.id;
      updaterSet = this._updaterSets.get(id);

      //If in a single update, an entity gets removed and a new instance
      //re-added with the same id, the updater no longer tracks the
      //correct entity, we need to both remove the old one and
      //add the new one, which is done by pushing the entity
      //onto the removed/added lists.
      if (updaterSet.entity === entity) {
        updaterSet.forEach(function (updater) {
          that._removeUpdater(updater);
          that._insertUpdaterIntoBatch(time, updater);
        });
      } else {
        removed.push(entity);
        added.push(entity);
      }
    }

    for (i = removed.length - 1; i > -1; i--) {
      entity = removed[i];
      id = entity.id;
      updaterSet = this._updaterSets.get(id);
      updaterSet.forEach(this._removeUpdater.bind(this));
      updaterSet.destroy();
      this._updaterSets.remove(id);
      this._subscriptions.get(id)();
      this._subscriptions.remove(id);
    }

    for (i = added.length - 1; i > -1; i--) {
      entity = added[i];
      id = entity.id;
      updaterSet = new GeometryUpdaterSet(entity, this._scene);
      this._updaterSets.set(id, updaterSet);
      updaterSet.forEach(function (updater) {
        that._insertUpdaterIntoBatch(time, updater);
      });
      this._subscriptions.set(
        id,
        updaterSet.geometryChanged.addEventListener(
          GeometryVisualizer._onGeometryChanged,
          this
        )
      );
    }

    addedObjects.removeAll();
    removedObjects.removeAll();
    changedObjects.removeAll();

    let isUpdated = true;
    const batches = this._batches;
    const length = batches.length;
    for (i = 0; i < length; i++) {
      isUpdated = batches[i].update(time) && isUpdated;
    }

    return isUpdated;
  };

  const getBoundingSphereArrayScratch$2 = [];
  const getBoundingSphereBoundingSphereScratch$2 = new BoundingSphere();

  /**
   * Computes a bounding sphere which encloses the visualization produced for the specified entity.
   * The bounding sphere is in the fixed frame of the scene's globe.
   *
   * @param {Entity} entity The entity whose bounding sphere to compute.
   * @param {BoundingSphere} result The bounding sphere onto which to store the result.
   * @returns {BoundingSphereState} BoundingSphereState.DONE if the result contains the bounding sphere,
   *                       BoundingSphereState.PENDING if the result is still being computed, or
   *                       BoundingSphereState.FAILED if the entity has no visualization in the current scene.
   * @private
   */
  GeometryVisualizer.prototype.getBoundingSphere = function (entity, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("entity", entity);
    Check.defined("result", result);
    //>>includeEnd('debug');

    const boundingSpheres = getBoundingSphereArrayScratch$2;
    const tmp = getBoundingSphereBoundingSphereScratch$2;

    let count = 0;
    let state = BoundingSphereState$1.DONE;
    const batches = this._batches;
    const batchesLength = batches.length;

    const id = entity.id;
    const updaters = this._updaterSets.get(id).updaters;

    for (let j = 0; j < updaters.length; j++) {
      const updater = updaters[j];
      for (let i = 0; i < batchesLength; i++) {
        state = batches[i].getBoundingSphere(updater, tmp);
        if (state === BoundingSphereState$1.PENDING) {
          return BoundingSphereState$1.PENDING;
        } else if (state === BoundingSphereState$1.DONE) {
          boundingSpheres[count] = BoundingSphere.clone(
            tmp,
            boundingSpheres[count]
          );
          count++;
        }
      }
    }

    if (count === 0) {
      return BoundingSphereState$1.FAILED;
    }

    boundingSpheres.length = count;
    BoundingSphere.fromBoundingSpheres(boundingSpheres, result);
    return BoundingSphereState$1.DONE;
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   *
   * @returns {Boolean} True if this object was destroyed; otherwise, false.
   */
  GeometryVisualizer.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Removes and destroys all primitives created by this instance.
   */
  GeometryVisualizer.prototype.destroy = function () {
    this._entityCollection.collectionChanged.removeEventListener(
      GeometryVisualizer.prototype._onCollectionChanged,
      this
    );
    this._addedObjects.removeAll();
    this._removedObjects.removeAll();

    let i;
    const batches = this._batches;
    let length = batches.length;
    for (i = 0; i < length; i++) {
      batches[i].removeAllPrimitives();
    }

    const subscriptions = this._subscriptions.values;
    length = subscriptions.length;
    for (i = 0; i < length; i++) {
      subscriptions[i]();
    }
    this._subscriptions.removeAll();

    const updaterSets = this._updaterSets.values;
    length = updaterSets.length;
    for (i = 0; i < length; i++) {
      updaterSets[i].destroy();
    }
    this._updaterSets.removeAll();
    return destroyObject(this);
  };

  /**
   * @private
   */
  GeometryVisualizer.prototype._removeUpdater = function (updater) {
    //We don't keep track of which batch an updater is in, so just remove it from all of them.
    const batches = this._batches;
    const length = batches.length;
    for (let i = 0; i < length; i++) {
      batches[i].remove(updater);
    }
  };

  /**
   * @private
   */
  GeometryVisualizer.prototype._insertUpdaterIntoBatch = function (
    time,
    updater
  ) {
    if (updater.isDynamic) {
      this._dynamicBatch.add(time, updater);
      return;
    }

    let shadows;
    if (updater.outlineEnabled || updater.fillEnabled) {
      shadows = updater.shadowsProperty.getValue(time);
    }

    const numberOfShadowModes = ShadowMode$1.NUMBER_OF_SHADOW_MODES;
    if (updater.outlineEnabled) {
      if (defined(updater.terrainOffsetProperty)) {
        this._outlineBatches[numberOfShadowModes + shadows].add(time, updater);
      } else {
        this._outlineBatches[shadows].add(time, updater);
      }
    }

    if (updater.fillEnabled) {
      if (updater.onTerrain) {
        const classificationType = updater.classificationTypeProperty.getValue(
          time
        );
        if (updater.fillMaterialProperty instanceof ColorMaterialProperty) {
          this._groundColorBatches[classificationType].add(time, updater);
        } else {
          // If unsupported, updater will not be on terrain.
          this._groundMaterialBatches[classificationType].add(time, updater);
        }
      } else if (updater.isClosed) {
        if (updater.fillMaterialProperty instanceof ColorMaterialProperty) {
          if (defined(updater.terrainOffsetProperty)) {
            this._closedColorBatches[numberOfShadowModes + shadows].add(
              time,
              updater
            );
          } else {
            this._closedColorBatches[shadows].add(time, updater);
          }
        } else if (defined(updater.terrainOffsetProperty)) {
          this._closedMaterialBatches[numberOfShadowModes + shadows].add(
            time,
            updater
          );
        } else {
          this._closedMaterialBatches[shadows].add(time, updater);
        }
      } else if (updater.fillMaterialProperty instanceof ColorMaterialProperty) {
        if (defined(updater.terrainOffsetProperty)) {
          this._openColorBatches[numberOfShadowModes + shadows].add(
            time,
            updater
          );
        } else {
          this._openColorBatches[shadows].add(time, updater);
        }
      } else if (defined(updater.terrainOffsetProperty)) {
        this._openMaterialBatches[numberOfShadowModes + shadows].add(
          time,
          updater
        );
      } else {
        this._openMaterialBatches[shadows].add(time, updater);
      }
    }
  };

  /**
   * @private
   */
  GeometryVisualizer._onGeometryChanged = function (updater) {
    const removedObjects = this._removedObjects;
    const changedObjects = this._changedObjects;

    const entity = updater.entity;
    const id = entity.id;

    if (!defined(removedObjects.get(id)) && !defined(changedObjects.get(id))) {
      changedObjects.set(id, entity);
    }
  };

  /**
   * @private
   */
  GeometryVisualizer.prototype._onCollectionChanged = function (
    entityCollection,
    added,
    removed
  ) {
    const addedObjects = this._addedObjects;
    const removedObjects = this._removedObjects;
    const changedObjects = this._changedObjects;

    let i;
    let id;
    let entity;
    for (i = removed.length - 1; i > -1; i--) {
      entity = removed[i];
      id = entity.id;
      if (!addedObjects.remove(id)) {
        removedObjects.set(id, entity);
        changedObjects.remove(id);
      }
    }

    for (i = added.length - 1; i > -1; i--) {
      entity = added[i];
      id = entity.id;
      if (removedObjects.remove(id)) {
        changedObjects.set(id, entity);
      } else {
        addedObjects.set(id, entity);
      }
    }
  };

  const defaultScale$1 = 1.0;
  const defaultFont = "30px sans-serif";
  const defaultStyle = LabelStyle$1.FILL;
  const defaultFillColor = Color.WHITE;
  const defaultOutlineColor$1 = Color.BLACK;
  const defaultOutlineWidth$1 = 1.0;
  const defaultShowBackground = false;
  const defaultBackgroundColor$1 = new Color(0.165, 0.165, 0.165, 0.8);
  const defaultBackgroundPadding = new Cartesian2(7, 5);
  const defaultPixelOffset = Cartesian2.ZERO;
  const defaultEyeOffset = Cartesian3.ZERO;
  const defaultHeightReference$1 = HeightReference$1.NONE;
  const defaultHorizontalOrigin = HorizontalOrigin$1.CENTER;
  const defaultVerticalOrigin = VerticalOrigin$1.CENTER;

  const positionScratch$1 = new Cartesian3();
  const fillColorScratch = new Color();
  const outlineColorScratch$1 = new Color();
  const backgroundColorScratch = new Color();
  const backgroundPaddingScratch = new Cartesian2();
  const eyeOffsetScratch = new Cartesian3();
  const pixelOffsetScratch = new Cartesian2();
  const translucencyByDistanceScratch$1 = new NearFarScalar();
  const pixelOffsetScaleByDistanceScratch = new NearFarScalar();
  const scaleByDistanceScratch$1 = new NearFarScalar();
  const distanceDisplayConditionScratch$2 = new DistanceDisplayCondition();

  function EntityData$2(entity) {
    this.entity = entity;
    this.label = undefined;
    this.index = undefined;
  }

  /**
   * A {@link Visualizer} which maps the {@link LabelGraphics} instance
   * in {@link Entity#label} to a {@link Label}.
   * @alias LabelVisualizer
   * @constructor
   *
   * @param {EntityCluster} entityCluster The entity cluster to manage the collection of billboards and optionally cluster with other entities.
   * @param {EntityCollection} entityCollection The entityCollection to visualize.
   */
  function LabelVisualizer(entityCluster, entityCollection) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(entityCluster)) {
      throw new DeveloperError("entityCluster is required.");
    }
    if (!defined(entityCollection)) {
      throw new DeveloperError("entityCollection is required.");
    }
    //>>includeEnd('debug');

    entityCollection.collectionChanged.addEventListener(
      LabelVisualizer.prototype._onCollectionChanged,
      this
    );

    this._cluster = entityCluster;
    this._entityCollection = entityCollection;
    this._items = new AssociativeArray();

    this._onCollectionChanged(entityCollection, entityCollection.values, [], []);
  }

  /**
   * Updates the primitives created by this visualizer to match their
   * Entity counterpart at the given time.
   *
   * @param {JulianDate} time The time to update to.
   * @returns {Boolean} This function always returns true.
   */
  LabelVisualizer.prototype.update = function (time) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(time)) {
      throw new DeveloperError("time is required.");
    }
    //>>includeEnd('debug');

    const items = this._items.values;
    const cluster = this._cluster;

    for (let i = 0, len = items.length; i < len; i++) {
      const item = items[i];
      const entity = item.entity;
      const labelGraphics = entity._label;
      let text;
      let label = item.label;
      let show =
        entity.isShowing &&
        entity.isAvailable(time) &&
        Property.getValueOrDefault(labelGraphics._show, time, true);
      let position;
      if (show) {
        position = Property.getValueOrUndefined(
          entity._position,
          time,
          positionScratch$1
        );
        text = Property.getValueOrUndefined(labelGraphics._text, time);
        show = defined(position) && defined(text);
      }

      if (!show) {
        //don't bother creating or updating anything else
        returnPrimitive$1(item, entity, cluster);
        continue;
      }

      if (!Property.isConstant(entity._position)) {
        cluster._clusterDirty = true;
      }

      let updateClamping = false;
      const heightReference = Property.getValueOrDefault(
        labelGraphics._heightReference,
        time,
        defaultHeightReference$1
      );

      if (!defined(label)) {
        label = cluster.getLabel(entity);
        label.id = entity;
        item.label = label;

        // If this new label happens to have a position and height reference that match our new values,
        // label._updateClamping will not be called automatically. That's a problem because the clamped
        // height may be based on different terrain than is now loaded. So we'll manually call
        // _updateClamping below.
        updateClamping =
          Cartesian3.equals(label.position, position) &&
          label.heightReference === heightReference;
      }

      label.show = true;
      label.position = position;
      label.text = text;
      label.scale = Property.getValueOrDefault(
        labelGraphics._scale,
        time,
        defaultScale$1
      );
      label.font = Property.getValueOrDefault(
        labelGraphics._font,
        time,
        defaultFont
      );
      label.style = Property.getValueOrDefault(
        labelGraphics._style,
        time,
        defaultStyle
      );
      label.fillColor = Property.getValueOrDefault(
        labelGraphics._fillColor,
        time,
        defaultFillColor,
        fillColorScratch
      );
      label.outlineColor = Property.getValueOrDefault(
        labelGraphics._outlineColor,
        time,
        defaultOutlineColor$1,
        outlineColorScratch$1
      );
      label.outlineWidth = Property.getValueOrDefault(
        labelGraphics._outlineWidth,
        time,
        defaultOutlineWidth$1
      );
      label.showBackground = Property.getValueOrDefault(
        labelGraphics._showBackground,
        time,
        defaultShowBackground
      );
      label.backgroundColor = Property.getValueOrDefault(
        labelGraphics._backgroundColor,
        time,
        defaultBackgroundColor$1,
        backgroundColorScratch
      );
      label.backgroundPadding = Property.getValueOrDefault(
        labelGraphics._backgroundPadding,
        time,
        defaultBackgroundPadding,
        backgroundPaddingScratch
      );
      label.pixelOffset = Property.getValueOrDefault(
        labelGraphics._pixelOffset,
        time,
        defaultPixelOffset,
        pixelOffsetScratch
      );
      label.eyeOffset = Property.getValueOrDefault(
        labelGraphics._eyeOffset,
        time,
        defaultEyeOffset,
        eyeOffsetScratch
      );
      label.heightReference = heightReference;
      label.horizontalOrigin = Property.getValueOrDefault(
        labelGraphics._horizontalOrigin,
        time,
        defaultHorizontalOrigin
      );
      label.verticalOrigin = Property.getValueOrDefault(
        labelGraphics._verticalOrigin,
        time,
        defaultVerticalOrigin
      );
      label.translucencyByDistance = Property.getValueOrUndefined(
        labelGraphics._translucencyByDistance,
        time,
        translucencyByDistanceScratch$1
      );
      label.pixelOffsetScaleByDistance = Property.getValueOrUndefined(
        labelGraphics._pixelOffsetScaleByDistance,
        time,
        pixelOffsetScaleByDistanceScratch
      );
      label.scaleByDistance = Property.getValueOrUndefined(
        labelGraphics._scaleByDistance,
        time,
        scaleByDistanceScratch$1
      );
      label.distanceDisplayCondition = Property.getValueOrUndefined(
        labelGraphics._distanceDisplayCondition,
        time,
        distanceDisplayConditionScratch$2
      );
      label.disableDepthTestDistance = Property.getValueOrUndefined(
        labelGraphics._disableDepthTestDistance,
        time
      );

      if (updateClamping) {
        label._updateClamping();
      }
    }
    return true;
  };

  /**
   * Computes a bounding sphere which encloses the visualization produced for the specified entity.
   * The bounding sphere is in the fixed frame of the scene's globe.
   *
   * @param {Entity} entity The entity whose bounding sphere to compute.
   * @param {BoundingSphere} result The bounding sphere onto which to store the result.
   * @returns {BoundingSphereState} BoundingSphereState.DONE if the result contains the bounding sphere,
   *                       BoundingSphereState.PENDING if the result is still being computed, or
   *                       BoundingSphereState.FAILED if the entity has no visualization in the current scene.
   * @private
   */
  LabelVisualizer.prototype.getBoundingSphere = function (entity, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(entity)) {
      throw new DeveloperError("entity is required.");
    }
    if (!defined(result)) {
      throw new DeveloperError("result is required.");
    }
    //>>includeEnd('debug');

    const item = this._items.get(entity.id);
    if (!defined(item) || !defined(item.label)) {
      return BoundingSphereState$1.FAILED;
    }

    const label = item.label;
    result.center = Cartesian3.clone(
      defaultValue(label._clampedPosition, label.position),
      result.center
    );
    result.radius = 0;
    return BoundingSphereState$1.DONE;
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   *
   * @returns {Boolean} True if this object was destroyed; otherwise, false.
   */
  LabelVisualizer.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Removes and destroys all primitives created by this instance.
   */
  LabelVisualizer.prototype.destroy = function () {
    this._entityCollection.collectionChanged.removeEventListener(
      LabelVisualizer.prototype._onCollectionChanged,
      this
    );
    const entities = this._entityCollection.values;
    for (let i = 0; i < entities.length; i++) {
      this._cluster.removeLabel(entities[i]);
    }
    return destroyObject(this);
  };

  LabelVisualizer.prototype._onCollectionChanged = function (
    entityCollection,
    added,
    removed,
    changed
  ) {
    let i;
    let entity;
    const items = this._items;
    const cluster = this._cluster;

    for (i = added.length - 1; i > -1; i--) {
      entity = added[i];
      if (defined(entity._label) && defined(entity._position)) {
        items.set(entity.id, new EntityData$2(entity));
      }
    }

    for (i = changed.length - 1; i > -1; i--) {
      entity = changed[i];
      if (defined(entity._label) && defined(entity._position)) {
        if (!items.contains(entity.id)) {
          items.set(entity.id, new EntityData$2(entity));
        }
      } else {
        returnPrimitive$1(items.get(entity.id), entity, cluster);
        items.remove(entity.id);
      }
    }

    for (i = removed.length - 1; i > -1; i--) {
      entity = removed[i];
      returnPrimitive$1(items.get(entity.id), entity, cluster);
      items.remove(entity.id);
    }
  };

  function returnPrimitive$1(item, entity, cluster) {
    if (defined(item)) {
      item.label = undefined;
      cluster.removeLabel(entity);
    }
  }

  const defaultScale = 1.0;
  const defaultMinimumPixelSize = 0.0;
  const defaultIncrementallyLoadTextures = true;
  const defaultClampAnimations = true;
  const defaultShadows$1 = ShadowMode$1.ENABLED;
  const defaultHeightReference = HeightReference$1.NONE;
  const defaultSilhouetteColor = Color.RED;
  const defaultSilhouetteSize = 0.0;
  const defaultColor$2 = Color.WHITE;
  const defaultColorBlendMode = ColorBlendMode$1.HIGHLIGHT;
  const defaultColorBlendAmount = 0.5;
  const defaultImageBasedLightingFactor = new Cartesian2(1.0, 1.0);

  const modelMatrixScratch = new Matrix4();
  const nodeMatrixScratch = new Matrix4();

  /**
   * A {@link Visualizer} which maps {@link Entity#model} to a {@link Model}.
   * @alias ModelVisualizer
   * @constructor
   *
   * @param {Scene} scene The scene the primitives will be rendered in.
   * @param {EntityCollection} entityCollection The entityCollection to visualize.
   */
  function ModelVisualizer(scene, entityCollection) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(scene)) {
      throw new DeveloperError("scene is required.");
    }
    if (!defined(entityCollection)) {
      throw new DeveloperError("entityCollection is required.");
    }
    //>>includeEnd('debug');

    entityCollection.collectionChanged.addEventListener(
      ModelVisualizer.prototype._onCollectionChanged,
      this
    );

    this._scene = scene;
    this._primitives = scene.primitives;
    this._entityCollection = entityCollection;
    this._modelHash = {};
    this._entitiesToVisualize = new AssociativeArray();
    this._onCollectionChanged(entityCollection, entityCollection.values, [], []);
  }

  /**
   * Updates models created this visualizer to match their
   * Entity counterpart at the given time.
   *
   * @param {JulianDate} time The time to update to.
   * @returns {Boolean} This function always returns true.
   */
  ModelVisualizer.prototype.update = function (time) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(time)) {
      throw new DeveloperError("time is required.");
    }
    //>>includeEnd('debug');

    const entities = this._entitiesToVisualize.values;
    const modelHash = this._modelHash;
    const primitives = this._primitives;

    for (let i = 0, len = entities.length; i < len; i++) {
      const entity = entities[i];
      const modelGraphics = entity._model;

      let resource;
      let modelData = modelHash[entity.id];
      let show =
        entity.isShowing &&
        entity.isAvailable(time) &&
        Property.getValueOrDefault(modelGraphics._show, time, true);

      let modelMatrix;
      if (show) {
        modelMatrix = entity.computeModelMatrix(time, modelMatrixScratch);
        resource = Resource.createIfNeeded(
          Property.getValueOrUndefined(modelGraphics._uri, time)
        );
        show = defined(modelMatrix) && defined(resource);
      }

      if (!show) {
        if (defined(modelData)) {
          modelData.modelPrimitive.show = false;
        }
        continue;
      }

      let model = defined(modelData) ? modelData.modelPrimitive : undefined;
      if (!defined(model) || resource.url !== modelData.url) {
        if (defined(model)) {
          primitives.removeAndDestroy(model);
          delete modelHash[entity.id];
        }

        const ModelType = ExperimentalFeatures.enableModelExperimental
          ? ModelExperimental
          : Model;

        model = ModelType.fromGltf({
          url: resource,
          incrementallyLoadTextures: Property.getValueOrDefault(
            modelGraphics._incrementallyLoadTextures,
            time,
            defaultIncrementallyLoadTextures
          ),
          scene: this._scene,
        });
        model.id = entity;
        primitives.add(model);

        modelData = {
          modelPrimitive: model,
          url: resource.url,
          animationsRunning: false,
          nodeTransformationsScratch: {},
          articulationsScratch: {},
          loadFail: false,
        };
        modelHash[entity.id] = modelData;

        checkModelLoad(model, entity, modelHash);
      }

      model.show = true;
      model.scale = Property.getValueOrDefault(
        modelGraphics._scale,
        time,
        defaultScale
      );
      model.minimumPixelSize = Property.getValueOrDefault(
        modelGraphics._minimumPixelSize,
        time,
        defaultMinimumPixelSize
      );
      model.maximumScale = Property.getValueOrUndefined(
        modelGraphics._maximumScale,
        time
      );
      model.modelMatrix = Matrix4.clone(modelMatrix, model.modelMatrix);
      model.shadows = Property.getValueOrDefault(
        modelGraphics._shadows,
        time,
        defaultShadows$1
      );
      model.heightReference = Property.getValueOrDefault(
        modelGraphics._heightReference,
        time,
        defaultHeightReference
      );
      model.distanceDisplayCondition = Property.getValueOrUndefined(
        modelGraphics._distanceDisplayCondition,
        time
      );
      model.silhouetteColor = Property.getValueOrDefault(
        modelGraphics._silhouetteColor,
        time,
        defaultSilhouetteColor,
        model._silhouetteColor
      );
      model.silhouetteSize = Property.getValueOrDefault(
        modelGraphics._silhouetteSize,
        time,
        defaultSilhouetteSize
      );
      model.color = Property.getValueOrDefault(
        modelGraphics._color,
        time,
        defaultColor$2,
        model._color
      );
      model.colorBlendMode = Property.getValueOrDefault(
        modelGraphics._colorBlendMode,
        time,
        defaultColorBlendMode
      );
      model.colorBlendAmount = Property.getValueOrDefault(
        modelGraphics._colorBlendAmount,
        time,
        defaultColorBlendAmount
      );
      model.clippingPlanes = Property.getValueOrUndefined(
        modelGraphics._clippingPlanes,
        time
      );
      model.clampAnimations = Property.getValueOrDefault(
        modelGraphics._clampAnimations,
        time,
        defaultClampAnimations
      );
      model.imageBasedLighting.imageBasedLightingFactor = Property.getValueOrDefault(
        modelGraphics._imageBasedLightingFactor,
        time,
        defaultImageBasedLightingFactor
      );
      model.lightColor = Property.getValueOrUndefined(
        modelGraphics._lightColor,
        time
      );

      if (model.ready) {
        const runAnimations = Property.getValueOrDefault(
          modelGraphics._runAnimations,
          time,
          true
        );
        if (modelData.animationsRunning !== runAnimations) {
          if (runAnimations) {
            model.activeAnimations.addAll({
              loop: ModelAnimationLoop$1.REPEAT,
            });
          } else {
            model.activeAnimations.removeAll();
          }
          modelData.animationsRunning = runAnimations;
        }

        // Apply node transformations
        const nodeTransformations = Property.getValueOrUndefined(
          modelGraphics._nodeTransformations,
          time,
          modelData.nodeTransformationsScratch
        );
        if (defined(nodeTransformations)) {
          const nodeNames = Object.keys(nodeTransformations);
          for (
            let nodeIndex = 0, nodeLength = nodeNames.length;
            nodeIndex < nodeLength;
            ++nodeIndex
          ) {
            const nodeName = nodeNames[nodeIndex];

            const nodeTransformation = nodeTransformations[nodeName];
            if (!defined(nodeTransformation)) {
              continue;
            }

            const modelNode = model.getNode(nodeName);
            if (!defined(modelNode)) {
              continue;
            }

            const transformationMatrix = Matrix4.fromTranslationRotationScale(
              nodeTransformation,
              nodeMatrixScratch
            );
            modelNode.matrix = Matrix4.multiply(
              modelNode.originalMatrix,
              transformationMatrix,
              transformationMatrix
            );
          }
        }

        // Apply articulations
        let anyArticulationUpdated = false;
        const articulations = Property.getValueOrUndefined(
          modelGraphics._articulations,
          time,
          modelData.articulationsScratch
        );
        if (defined(articulations)) {
          const articulationStageKeys = Object.keys(articulations);
          for (
            let s = 0, numKeys = articulationStageKeys.length;
            s < numKeys;
            ++s
          ) {
            const key = articulationStageKeys[s];

            const articulationStageValue = articulations[key];
            if (!defined(articulationStageValue)) {
              continue;
            }

            anyArticulationUpdated = true;
            model.setArticulationStage(key, articulationStageValue);
          }
        }

        if (anyArticulationUpdated) {
          model.applyArticulations();
        }
      }
    }

    return true;
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   *
   * @returns {Boolean} True if this object was destroyed; otherwise, false.
   */
  ModelVisualizer.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Removes and destroys all primitives created by this instance.
   */
  ModelVisualizer.prototype.destroy = function () {
    this._entityCollection.collectionChanged.removeEventListener(
      ModelVisualizer.prototype._onCollectionChanged,
      this
    );
    const entities = this._entitiesToVisualize.values;
    const modelHash = this._modelHash;
    const primitives = this._primitives;
    for (let i = entities.length - 1; i > -1; i--) {
      removeModel(this, entities[i], modelHash, primitives);
    }
    return destroyObject(this);
  };

  /**
   * Computes a bounding sphere which encloses the visualization produced for the specified entity.
   * The bounding sphere is in the fixed frame of the scene's globe.
   *
   * @param {Entity} entity The entity whose bounding sphere to compute.
   * @param {BoundingSphere} result The bounding sphere onto which to store the result.
   * @returns {BoundingSphereState} BoundingSphereState.DONE if the result contains the bounding sphere,
   *                       BoundingSphereState.PENDING if the result is still being computed, or
   *                       BoundingSphereState.FAILED if the entity has no visualization in the current scene.
   * @private
   */
  ModelVisualizer.prototype.getBoundingSphere = function (entity, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(entity)) {
      throw new DeveloperError("entity is required.");
    }
    if (!defined(result)) {
      throw new DeveloperError("result is required.");
    }
    //>>includeEnd('debug');

    const modelData = this._modelHash[entity.id];
    if (!defined(modelData) || modelData.loadFail) {
      return BoundingSphereState$1.FAILED;
    }

    const model = modelData.modelPrimitive;
    if (!defined(model) || !model.show) {
      return BoundingSphereState$1.FAILED;
    }

    if (!model.ready) {
      return BoundingSphereState$1.PENDING;
    }

    if (ExperimentalFeatures.enableModelExperimental) {
      // ModelExperimental's bounding sphere is already in world space, it does
      // not need to be transformed.
      BoundingSphere.clone(model.boundingSphere, result);
      return BoundingSphereState$1.DONE;
    }

    if (model.heightReference === HeightReference$1.NONE) {
      BoundingSphere.transform(
        model.boundingSphereInternal,
        model.modelMatrix,
        result
      );
    } else {
      if (!defined(model._clampedModelMatrix)) {
        return BoundingSphereState$1.PENDING;
      }
      BoundingSphere.transform(
        model.boundingSphereInternal,
        model._clampedModelMatrix,
        result
      );
    }
    return BoundingSphereState$1.DONE;
  };

  /**
   * @private
   */
  ModelVisualizer.prototype._onCollectionChanged = function (
    entityCollection,
    added,
    removed,
    changed
  ) {
    let i;
    let entity;
    const entities = this._entitiesToVisualize;
    const modelHash = this._modelHash;
    const primitives = this._primitives;

    for (i = added.length - 1; i > -1; i--) {
      entity = added[i];
      if (defined(entity._model) && defined(entity._position)) {
        entities.set(entity.id, entity);
      }
    }

    for (i = changed.length - 1; i > -1; i--) {
      entity = changed[i];
      if (defined(entity._model) && defined(entity._position)) {
        clearNodeTransformationsArticulationsScratch(entity, modelHash);
        entities.set(entity.id, entity);
      } else {
        removeModel(this, entity, modelHash, primitives);
        entities.remove(entity.id);
      }
    }

    for (i = removed.length - 1; i > -1; i--) {
      entity = removed[i];
      removeModel(this, entity, modelHash, primitives);
      entities.remove(entity.id);
    }
  };

  function removeModel(visualizer, entity, modelHash, primitives) {
    const modelData = modelHash[entity.id];
    if (defined(modelData)) {
      primitives.removeAndDestroy(modelData.modelPrimitive);
      delete modelHash[entity.id];
    }
  }

  function clearNodeTransformationsArticulationsScratch(entity, modelHash) {
    const modelData = modelHash[entity.id];
    if (defined(modelData)) {
      modelData.nodeTransformationsScratch = {};
      modelData.articulationsScratch = {};
    }
  }

  function checkModelLoad(model, entity, modelHash) {
    model.readyPromise.catch(function (error) {
      console.error(error);
      modelHash[entity.id].loadFail = true;
    });
  }

  /**
   * This is a temporary class for scaling position properties to the WGS84 surface.
   * It will go away or be refactored to support data with arbitrary height references.
   * @private
   */
  function ScaledPositionProperty(value) {
    this._definitionChanged = new Event();
    this._value = undefined;
    this._removeSubscription = undefined;
    this.setValue(value);
  }

  Object.defineProperties(ScaledPositionProperty.prototype, {
    isConstant: {
      get: function () {
        return Property.isConstant(this._value);
      },
    },
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },
    referenceFrame: {
      get: function () {
        return defined(this._value)
          ? this._value.referenceFrame
          : ReferenceFrame$1.FIXED;
      },
    },
  });

  ScaledPositionProperty.prototype.getValue = function (time, result) {
    return this.getValueInReferenceFrame(time, ReferenceFrame$1.FIXED, result);
  };

  ScaledPositionProperty.prototype.setValue = function (value) {
    if (this._value !== value) {
      this._value = value;

      if (defined(this._removeSubscription)) {
        this._removeSubscription();
        this._removeSubscription = undefined;
      }

      if (defined(value)) {
        this._removeSubscription = value.definitionChanged.addEventListener(
          this._raiseDefinitionChanged,
          this
        );
      }
      this._definitionChanged.raiseEvent(this);
    }
  };

  ScaledPositionProperty.prototype.getValueInReferenceFrame = function (
    time,
    referenceFrame,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(time)) {
      throw new DeveloperError("time is required.");
    }
    if (!defined(referenceFrame)) {
      throw new DeveloperError("referenceFrame is required.");
    }
    //>>includeEnd('debug');

    if (!defined(this._value)) {
      return undefined;
    }

    result = this._value.getValueInReferenceFrame(time, referenceFrame, result);
    return defined(result)
      ? Ellipsoid.WGS84.scaleToGeodeticSurface(result, result)
      : undefined;
  };

  ScaledPositionProperty.prototype.equals = function (other) {
    return (
      this === other ||
      (other instanceof ScaledPositionProperty && this._value === other._value)
    );
  };

  ScaledPositionProperty.prototype._raiseDefinitionChanged = function () {
    this._definitionChanged.raiseEvent(this);
  };

  const defaultResolution = 60.0;
  const defaultWidth = 1.0;

  const scratchTimeInterval = new TimeInterval();
  const subSampleCompositePropertyScratch = new TimeInterval();
  const subSampleIntervalPropertyScratch = new TimeInterval();

  function EntityData$1(entity) {
    this.entity = entity;
    this.polyline = undefined;
    this.index = undefined;
    this.updater = undefined;
  }

  function subSampleSampledProperty(
    property,
    start,
    stop,
    times,
    updateTime,
    referenceFrame,
    maximumStep,
    startingIndex,
    result
  ) {
    let r = startingIndex;
    //Always step exactly on start (but only use it if it exists.)
    let tmp;
    tmp = property.getValueInReferenceFrame(start, referenceFrame, result[r]);
    if (defined(tmp)) {
      result[r++] = tmp;
    }

    let steppedOnNow =
      !defined(updateTime) ||
      JulianDate.lessThanOrEquals(updateTime, start) ||
      JulianDate.greaterThanOrEquals(updateTime, stop);

    //Iterate over all interval times and add the ones that fall in our
    //time range.  Note that times can contain data outside of
    //the intervals range.  This is by design for use with interpolation.
    let t = 0;
    const len = times.length;
    let current = times[t];
    const loopStop = stop;
    let sampling = false;
    let sampleStepsToTake;
    let sampleStepsTaken;
    let sampleStepSize;

    while (t < len) {
      if (!steppedOnNow && JulianDate.greaterThanOrEquals(current, updateTime)) {
        tmp = property.getValueInReferenceFrame(
          updateTime,
          referenceFrame,
          result[r]
        );
        if (defined(tmp)) {
          result[r++] = tmp;
        }
        steppedOnNow = true;
      }
      if (
        JulianDate.greaterThan(current, start) &&
        JulianDate.lessThan(current, loopStop) &&
        !current.equals(updateTime)
      ) {
        tmp = property.getValueInReferenceFrame(
          current,
          referenceFrame,
          result[r]
        );
        if (defined(tmp)) {
          result[r++] = tmp;
        }
      }

      if (t < len - 1) {
        if (maximumStep > 0 && !sampling) {
          const next = times[t + 1];
          const secondsUntilNext = JulianDate.secondsDifference(next, current);
          sampling = secondsUntilNext > maximumStep;

          if (sampling) {
            sampleStepsToTake = Math.ceil(secondsUntilNext / maximumStep);
            sampleStepsTaken = 0;
            sampleStepSize = secondsUntilNext / Math.max(sampleStepsToTake, 2);
            sampleStepsToTake = Math.max(sampleStepsToTake - 1, 1);
          }
        }

        if (sampling && sampleStepsTaken < sampleStepsToTake) {
          current = JulianDate.addSeconds(
            current,
            sampleStepSize,
            new JulianDate()
          );
          sampleStepsTaken++;
          continue;
        }
      }
      sampling = false;
      t++;
      current = times[t];
    }

    //Always step exactly on stop (but only use it if it exists.)
    tmp = property.getValueInReferenceFrame(stop, referenceFrame, result[r]);
    if (defined(tmp)) {
      result[r++] = tmp;
    }

    return r;
  }

  function subSampleGenericProperty(
    property,
    start,
    stop,
    updateTime,
    referenceFrame,
    maximumStep,
    startingIndex,
    result
  ) {
    let tmp;
    let i = 0;
    let index = startingIndex;
    let time = start;
    const stepSize = Math.max(maximumStep, 60);
    let steppedOnNow =
      !defined(updateTime) ||
      JulianDate.lessThanOrEquals(updateTime, start) ||
      JulianDate.greaterThanOrEquals(updateTime, stop);
    while (JulianDate.lessThan(time, stop)) {
      if (!steppedOnNow && JulianDate.greaterThanOrEquals(time, updateTime)) {
        steppedOnNow = true;
        tmp = property.getValueInReferenceFrame(
          updateTime,
          referenceFrame,
          result[index]
        );
        if (defined(tmp)) {
          result[index] = tmp;
          index++;
        }
      }
      tmp = property.getValueInReferenceFrame(
        time,
        referenceFrame,
        result[index]
      );
      if (defined(tmp)) {
        result[index] = tmp;
        index++;
      }
      i++;
      time = JulianDate.addSeconds(start, stepSize * i, new JulianDate());
    }
    //Always sample stop.
    tmp = property.getValueInReferenceFrame(stop, referenceFrame, result[index]);
    if (defined(tmp)) {
      result[index] = tmp;
      index++;
    }
    return index;
  }

  function subSampleIntervalProperty(
    property,
    start,
    stop,
    updateTime,
    referenceFrame,
    maximumStep,
    startingIndex,
    result
  ) {
    subSampleIntervalPropertyScratch.start = start;
    subSampleIntervalPropertyScratch.stop = stop;

    let index = startingIndex;
    const intervals = property.intervals;
    for (let i = 0; i < intervals.length; i++) {
      const interval = intervals.get(i);
      if (
        !TimeInterval.intersect(
          interval,
          subSampleIntervalPropertyScratch,
          scratchTimeInterval
        ).isEmpty
      ) {
        let time = interval.start;
        if (!interval.isStartIncluded) {
          if (interval.isStopIncluded) {
            time = interval.stop;
          } else {
            time = JulianDate.addSeconds(
              interval.start,
              JulianDate.secondsDifference(interval.stop, interval.start) / 2,
              new JulianDate()
            );
          }
        }
        const tmp = property.getValueInReferenceFrame(
          time,
          referenceFrame,
          result[index]
        );
        if (defined(tmp)) {
          result[index] = tmp;
          index++;
        }
      }
    }
    return index;
  }

  function subSampleConstantProperty(
    property,
    start,
    stop,
    updateTime,
    referenceFrame,
    maximumStep,
    startingIndex,
    result
  ) {
    const tmp = property.getValueInReferenceFrame(
      start,
      referenceFrame,
      result[startingIndex]
    );
    if (defined(tmp)) {
      result[startingIndex++] = tmp;
    }
    return startingIndex;
  }

  function subSampleCompositeProperty(
    property,
    start,
    stop,
    updateTime,
    referenceFrame,
    maximumStep,
    startingIndex,
    result
  ) {
    subSampleCompositePropertyScratch.start = start;
    subSampleCompositePropertyScratch.stop = stop;

    let index = startingIndex;
    const intervals = property.intervals;
    for (let i = 0; i < intervals.length; i++) {
      const interval = intervals.get(i);
      if (
        !TimeInterval.intersect(
          interval,
          subSampleCompositePropertyScratch,
          scratchTimeInterval
        ).isEmpty
      ) {
        const intervalStart = interval.start;
        const intervalStop = interval.stop;

        let sampleStart = start;
        if (JulianDate.greaterThan(intervalStart, sampleStart)) {
          sampleStart = intervalStart;
        }

        let sampleStop = stop;
        if (JulianDate.lessThan(intervalStop, sampleStop)) {
          sampleStop = intervalStop;
        }

        index = reallySubSample(
          interval.data,
          sampleStart,
          sampleStop,
          updateTime,
          referenceFrame,
          maximumStep,
          index,
          result
        );
      }
    }
    return index;
  }

  function reallySubSample(
    property,
    start,
    stop,
    updateTime,
    referenceFrame,
    maximumStep,
    index,
    result
  ) {
    //Unwrap any references until we have the actual property.
    while (property instanceof ReferenceProperty) {
      property = property.resolvedProperty;
    }

    if (property instanceof SampledPositionProperty) {
      const times = property._property._times;
      index = subSampleSampledProperty(
        property,
        start,
        stop,
        times,
        updateTime,
        referenceFrame,
        maximumStep,
        index,
        result
      );
    } else if (property instanceof CompositePositionProperty) {
      index = subSampleCompositeProperty(
        property,
        start,
        stop,
        updateTime,
        referenceFrame,
        maximumStep,
        index,
        result
      );
    } else if (property instanceof TimeIntervalCollectionPositionProperty) {
      index = subSampleIntervalProperty(
        property,
        start,
        stop,
        updateTime,
        referenceFrame,
        maximumStep,
        index,
        result
      );
    } else if (
      property instanceof ConstantPositionProperty ||
      (property instanceof ScaledPositionProperty &&
        Property.isConstant(property))
    ) {
      index = subSampleConstantProperty(
        property,
        start,
        stop,
        updateTime,
        referenceFrame,
        maximumStep,
        index,
        result
      );
    } else {
      //Fallback to generic sampling.
      index = subSampleGenericProperty(
        property,
        start,
        stop,
        updateTime,
        referenceFrame,
        maximumStep,
        index,
        result
      );
    }
    return index;
  }

  function subSample(
    property,
    start,
    stop,
    updateTime,
    referenceFrame,
    maximumStep,
    result
  ) {
    if (!defined(result)) {
      result = [];
    }

    const length = reallySubSample(
      property,
      start,
      stop,
      updateTime,
      referenceFrame,
      maximumStep,
      0,
      result
    );
    result.length = length;
    return result;
  }

  const toFixedScratch = new Matrix3();
  function PolylineUpdater(scene, referenceFrame) {
    this._unusedIndexes = [];
    this._polylineCollection = new PolylineCollection();
    this._scene = scene;
    this._referenceFrame = referenceFrame;
    scene.primitives.add(this._polylineCollection);
  }

  PolylineUpdater.prototype.update = function (time) {
    if (this._referenceFrame === ReferenceFrame$1.INERTIAL) {
      let toFixed = Transforms.computeIcrfToFixedMatrix(time, toFixedScratch);
      if (!defined(toFixed)) {
        toFixed = Transforms.computeTemeToPseudoFixedMatrix(time, toFixedScratch);
      }
      Matrix4.fromRotationTranslation(
        toFixed,
        Cartesian3.ZERO,
        this._polylineCollection.modelMatrix
      );
    }
  };

  PolylineUpdater.prototype.updateObject = function (time, item) {
    const entity = item.entity;
    const pathGraphics = entity._path;
    const positionProperty = entity._position;

    let sampleStart;
    let sampleStop;
    const showProperty = pathGraphics._show;
    let polyline = item.polyline;
    let show =
      entity.isShowing &&
      entity.isAvailable(time) &&
      (!defined(showProperty) || showProperty.getValue(time));

    //While we want to show the path, there may not actually be anything to show
    //depending on lead/trail settings.  Compute the interval of the path to
    //show and check against actual availability.
    if (show) {
      const leadTime = Property.getValueOrUndefined(pathGraphics._leadTime, time);
      const trailTime = Property.getValueOrUndefined(
        pathGraphics._trailTime,
        time
      );
      const availability = entity._availability;
      const hasAvailability = defined(availability);
      const hasLeadTime = defined(leadTime);
      const hasTrailTime = defined(trailTime);

      //Objects need to have either defined availability or both a lead and trail time in order to
      //draw a path (since we can't draw "infinite" paths.
      show = hasAvailability || (hasLeadTime && hasTrailTime);

      //The final step is to compute the actual start/stop times of the path to show.
      //If current time is outside of the availability interval, there's a chance that
      //we won't have to draw anything anyway.
      if (show) {
        if (hasTrailTime) {
          sampleStart = JulianDate.addSeconds(time, -trailTime, new JulianDate());
        }
        if (hasLeadTime) {
          sampleStop = JulianDate.addSeconds(time, leadTime, new JulianDate());
        }

        if (hasAvailability) {
          const start = availability.start;
          const stop = availability.stop;

          if (!hasTrailTime || JulianDate.greaterThan(start, sampleStart)) {
            sampleStart = start;
          }

          if (!hasLeadTime || JulianDate.lessThan(stop, sampleStop)) {
            sampleStop = stop;
          }
        }
        show = JulianDate.lessThan(sampleStart, sampleStop);
      }
    }

    if (!show) {
      //don't bother creating or updating anything else
      if (defined(polyline)) {
        this._unusedIndexes.push(item.index);
        item.polyline = undefined;
        polyline.show = false;
        item.index = undefined;
      }
      return;
    }

    if (!defined(polyline)) {
      const unusedIndexes = this._unusedIndexes;
      const length = unusedIndexes.length;
      if (length > 0) {
        const index = unusedIndexes.pop();
        polyline = this._polylineCollection.get(index);
        item.index = index;
      } else {
        item.index = this._polylineCollection.length;
        polyline = this._polylineCollection.add();
      }
      polyline.id = entity;
      item.polyline = polyline;
    }

    const resolution = Property.getValueOrDefault(
      pathGraphics._resolution,
      time,
      defaultResolution
    );

    polyline.show = true;
    polyline.positions = subSample(
      positionProperty,
      sampleStart,
      sampleStop,
      time,
      this._referenceFrame,
      resolution,
      polyline.positions.slice()
    );
    polyline.material = MaterialProperty.getValue(
      time,
      pathGraphics._material,
      polyline.material
    );
    polyline.width = Property.getValueOrDefault(
      pathGraphics._width,
      time,
      defaultWidth
    );
    polyline.distanceDisplayCondition = Property.getValueOrUndefined(
      pathGraphics._distanceDisplayCondition,
      time,
      polyline.distanceDisplayCondition
    );
  };

  PolylineUpdater.prototype.removeObject = function (item) {
    const polyline = item.polyline;
    if (defined(polyline)) {
      this._unusedIndexes.push(item.index);
      item.polyline = undefined;
      polyline.show = false;
      polyline.id = undefined;
      item.index = undefined;
    }
  };

  PolylineUpdater.prototype.destroy = function () {
    this._scene.primitives.remove(this._polylineCollection);
    return destroyObject(this);
  };

  /**
   * A {@link Visualizer} which maps {@link Entity#path} to a {@link Polyline}.
   * @alias PathVisualizer
   * @constructor
   *
   * @param {Scene} scene The scene the primitives will be rendered in.
   * @param {EntityCollection} entityCollection The entityCollection to visualize.
   */
  function PathVisualizer(scene, entityCollection) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(scene)) {
      throw new DeveloperError("scene is required.");
    }
    if (!defined(entityCollection)) {
      throw new DeveloperError("entityCollection is required.");
    }
    //>>includeEnd('debug');

    entityCollection.collectionChanged.addEventListener(
      PathVisualizer.prototype._onCollectionChanged,
      this
    );

    this._scene = scene;
    this._updaters = {};
    this._entityCollection = entityCollection;
    this._items = new AssociativeArray();

    this._onCollectionChanged(entityCollection, entityCollection.values, [], []);
  }

  /**
   * Updates all of the primitives created by this visualizer to match their
   * Entity counterpart at the given time.
   *
   * @param {JulianDate} time The time to update to.
   * @returns {Boolean} This function always returns true.
   */
  PathVisualizer.prototype.update = function (time) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(time)) {
      throw new DeveloperError("time is required.");
    }
    //>>includeEnd('debug');

    const updaters = this._updaters;
    for (const key in updaters) {
      if (updaters.hasOwnProperty(key)) {
        updaters[key].update(time);
      }
    }

    const items = this._items.values;
    if (
      items.length === 0 &&
      defined(this._updaters) &&
      Object.keys(this._updaters).length > 0
    ) {
      for (const u in updaters) {
        if (updaters.hasOwnProperty(u)) {
          updaters[u].destroy();
        }
      }
      this._updaters = {};
    }

    for (let i = 0, len = items.length; i < len; i++) {
      const item = items[i];
      const entity = item.entity;
      const positionProperty = entity._position;

      const lastUpdater = item.updater;

      let frameToVisualize = ReferenceFrame$1.FIXED;
      if (this._scene.mode === SceneMode$1.SCENE3D) {
        frameToVisualize = positionProperty.referenceFrame;
      }

      let currentUpdater = this._updaters[frameToVisualize];

      if (lastUpdater === currentUpdater && defined(currentUpdater)) {
        currentUpdater.updateObject(time, item);
        continue;
      }

      if (defined(lastUpdater)) {
        lastUpdater.removeObject(item);
      }

      if (!defined(currentUpdater)) {
        currentUpdater = new PolylineUpdater(this._scene, frameToVisualize);
        currentUpdater.update(time);
        this._updaters[frameToVisualize] = currentUpdater;
      }

      item.updater = currentUpdater;
      if (defined(currentUpdater)) {
        currentUpdater.updateObject(time, item);
      }
    }
    return true;
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   *
   * @returns {Boolean} True if this object was destroyed; otherwise, false.
   */
  PathVisualizer.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Removes and destroys all primitives created by this instance.
   */
  PathVisualizer.prototype.destroy = function () {
    this._entityCollection.collectionChanged.removeEventListener(
      PathVisualizer.prototype._onCollectionChanged,
      this
    );

    const updaters = this._updaters;
    for (const key in updaters) {
      if (updaters.hasOwnProperty(key)) {
        updaters[key].destroy();
      }
    }

    return destroyObject(this);
  };

  PathVisualizer.prototype._onCollectionChanged = function (
    entityCollection,
    added,
    removed,
    changed
  ) {
    let i;
    let entity;
    let item;
    const items = this._items;

    for (i = added.length - 1; i > -1; i--) {
      entity = added[i];
      if (defined(entity._path) && defined(entity._position)) {
        items.set(entity.id, new EntityData$1(entity));
      }
    }

    for (i = changed.length - 1; i > -1; i--) {
      entity = changed[i];
      if (defined(entity._path) && defined(entity._position)) {
        if (!items.contains(entity.id)) {
          items.set(entity.id, new EntityData$1(entity));
        }
      } else {
        item = items.get(entity.id);
        if (defined(item)) {
          if (defined(item.updater)) {
            item.updater.removeObject(item);
          }
          items.remove(entity.id);
        }
      }
    }

    for (i = removed.length - 1; i > -1; i--) {
      entity = removed[i];
      item = items.get(entity.id);
      if (defined(item)) {
        if (defined(item.updater)) {
          item.updater.removeObject(item);
        }
        items.remove(entity.id);
      }
    }
  };

  //for testing
  PathVisualizer._subSample = subSample;

  const defaultColor$1 = Color.WHITE;
  const defaultOutlineColor = Color.BLACK;
  const defaultOutlineWidth = 0.0;
  const defaultPixelSize = 1.0;
  const defaultDisableDepthTestDistance = 0.0;

  const colorScratch$1 = new Color();
  const positionScratch = new Cartesian3();
  const outlineColorScratch = new Color();
  const scaleByDistanceScratch = new NearFarScalar();
  const translucencyByDistanceScratch = new NearFarScalar();
  const distanceDisplayConditionScratch$1 = new DistanceDisplayCondition();

  function EntityData(entity) {
    this.entity = entity;
    this.pointPrimitive = undefined;
    this.billboard = undefined;
    this.color = undefined;
    this.outlineColor = undefined;
    this.pixelSize = undefined;
    this.outlineWidth = undefined;
  }

  /**
   * A {@link Visualizer} which maps {@link Entity#point} to a {@link PointPrimitive}.
   * @alias PointVisualizer
   * @constructor
   *
   * @param {EntityCluster} entityCluster The entity cluster to manage the collection of billboards and optionally cluster with other entities.
   * @param {EntityCollection} entityCollection The entityCollection to visualize.
   */
  function PointVisualizer(entityCluster, entityCollection) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(entityCluster)) {
      throw new DeveloperError("entityCluster is required.");
    }
    if (!defined(entityCollection)) {
      throw new DeveloperError("entityCollection is required.");
    }
    //>>includeEnd('debug');

    entityCollection.collectionChanged.addEventListener(
      PointVisualizer.prototype._onCollectionChanged,
      this
    );

    this._cluster = entityCluster;
    this._entityCollection = entityCollection;
    this._items = new AssociativeArray();
    this._onCollectionChanged(entityCollection, entityCollection.values, [], []);
  }

  /**
   * Updates the primitives created by this visualizer to match their
   * Entity counterpart at the given time.
   *
   * @param {JulianDate} time The time to update to.
   * @returns {Boolean} This function always returns true.
   */
  PointVisualizer.prototype.update = function (time) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(time)) {
      throw new DeveloperError("time is required.");
    }
    //>>includeEnd('debug');

    const items = this._items.values;
    const cluster = this._cluster;
    for (let i = 0, len = items.length; i < len; i++) {
      const item = items[i];
      const entity = item.entity;
      const pointGraphics = entity._point;
      let pointPrimitive = item.pointPrimitive;
      let billboard = item.billboard;
      const heightReference = Property.getValueOrDefault(
        pointGraphics._heightReference,
        time,
        HeightReference$1.NONE
      );
      let show =
        entity.isShowing &&
        entity.isAvailable(time) &&
        Property.getValueOrDefault(pointGraphics._show, time, true);
      let position;
      if (show) {
        position = Property.getValueOrUndefined(
          entity._position,
          time,
          positionScratch
        );
        show = defined(position);
      }
      if (!show) {
        returnPrimitive(item, entity, cluster);
        continue;
      }

      if (!Property.isConstant(entity._position)) {
        cluster._clusterDirty = true;
      }

      let needsRedraw = false;
      let updateClamping = false;
      if (heightReference !== HeightReference$1.NONE && !defined(billboard)) {
        if (defined(pointPrimitive)) {
          returnPrimitive(item, entity, cluster);
          pointPrimitive = undefined;
        }

        billboard = cluster.getBillboard(entity);
        billboard.id = entity;
        billboard.image = undefined;
        item.billboard = billboard;
        needsRedraw = true;

        // If this new billboard happens to have a position and height reference that match our new values,
        // billboard._updateClamping will not be called automatically. That's a problem because the clamped
        // height may be based on different terrain than is now loaded. So we'll manually call
        // _updateClamping below.
        updateClamping =
          Cartesian3.equals(billboard.position, position) &&
          billboard.heightReference === heightReference;
      } else if (
        heightReference === HeightReference$1.NONE &&
        !defined(pointPrimitive)
      ) {
        if (defined(billboard)) {
          returnPrimitive(item, entity, cluster);
          billboard = undefined;
        }

        pointPrimitive = cluster.getPoint(entity);
        pointPrimitive.id = entity;
        item.pointPrimitive = pointPrimitive;
      }

      if (defined(pointPrimitive)) {
        pointPrimitive.show = true;
        pointPrimitive.position = position;
        pointPrimitive.scaleByDistance = Property.getValueOrUndefined(
          pointGraphics._scaleByDistance,
          time,
          scaleByDistanceScratch
        );
        pointPrimitive.translucencyByDistance = Property.getValueOrUndefined(
          pointGraphics._translucencyByDistance,
          time,
          translucencyByDistanceScratch
        );
        pointPrimitive.color = Property.getValueOrDefault(
          pointGraphics._color,
          time,
          defaultColor$1,
          colorScratch$1
        );
        pointPrimitive.outlineColor = Property.getValueOrDefault(
          pointGraphics._outlineColor,
          time,
          defaultOutlineColor,
          outlineColorScratch
        );
        pointPrimitive.outlineWidth = Property.getValueOrDefault(
          pointGraphics._outlineWidth,
          time,
          defaultOutlineWidth
        );
        pointPrimitive.pixelSize = Property.getValueOrDefault(
          pointGraphics._pixelSize,
          time,
          defaultPixelSize
        );
        pointPrimitive.distanceDisplayCondition = Property.getValueOrUndefined(
          pointGraphics._distanceDisplayCondition,
          time,
          distanceDisplayConditionScratch$1
        );
        pointPrimitive.disableDepthTestDistance = Property.getValueOrDefault(
          pointGraphics._disableDepthTestDistance,
          time,
          defaultDisableDepthTestDistance
        );
      } else if (defined(billboard)) {
        billboard.show = true;
        billboard.position = position;
        billboard.scaleByDistance = Property.getValueOrUndefined(
          pointGraphics._scaleByDistance,
          time,
          scaleByDistanceScratch
        );
        billboard.translucencyByDistance = Property.getValueOrUndefined(
          pointGraphics._translucencyByDistance,
          time,
          translucencyByDistanceScratch
        );
        billboard.distanceDisplayCondition = Property.getValueOrUndefined(
          pointGraphics._distanceDisplayCondition,
          time,
          distanceDisplayConditionScratch$1
        );
        billboard.disableDepthTestDistance = Property.getValueOrDefault(
          pointGraphics._disableDepthTestDistance,
          time,
          defaultDisableDepthTestDistance
        );
        billboard.heightReference = heightReference;

        const newColor = Property.getValueOrDefault(
          pointGraphics._color,
          time,
          defaultColor$1,
          colorScratch$1
        );
        const newOutlineColor = Property.getValueOrDefault(
          pointGraphics._outlineColor,
          time,
          defaultOutlineColor,
          outlineColorScratch
        );
        const newOutlineWidth = Math.round(
          Property.getValueOrDefault(
            pointGraphics._outlineWidth,
            time,
            defaultOutlineWidth
          )
        );
        let newPixelSize = Math.max(
          1,
          Math.round(
            Property.getValueOrDefault(
              pointGraphics._pixelSize,
              time,
              defaultPixelSize
            )
          )
        );

        if (newOutlineWidth > 0) {
          billboard.scale = 1.0;
          needsRedraw =
            needsRedraw || //
            newOutlineWidth !== item.outlineWidth || //
            newPixelSize !== item.pixelSize || //
            !Color.equals(newColor, item.color) || //
            !Color.equals(newOutlineColor, item.outlineColor);
        } else {
          billboard.scale = newPixelSize / 50.0;
          newPixelSize = 50.0;
          needsRedraw =
            needsRedraw || //
            newOutlineWidth !== item.outlineWidth || //
            !Color.equals(newColor, item.color) || //
            !Color.equals(newOutlineColor, item.outlineColor);
        }

        if (needsRedraw) {
          item.color = Color.clone(newColor, item.color);
          item.outlineColor = Color.clone(newOutlineColor, item.outlineColor);
          item.pixelSize = newPixelSize;
          item.outlineWidth = newOutlineWidth;

          const centerAlpha = newColor.alpha;
          const cssColor = newColor.toCssColorString();
          const cssOutlineColor = newOutlineColor.toCssColorString();
          const textureId = JSON.stringify([
            cssColor,
            newPixelSize,
            cssOutlineColor,
            newOutlineWidth,
          ]);

          billboard.setImage(
            textureId,
            createBillboardPointCallback(
              centerAlpha,
              cssColor,
              cssOutlineColor,
              newOutlineWidth,
              newPixelSize
            )
          );
        }

        if (updateClamping) {
          billboard._updateClamping();
        }
      }
    }
    return true;
  };

  /**
   * Computes a bounding sphere which encloses the visualization produced for the specified entity.
   * The bounding sphere is in the fixed frame of the scene's globe.
   *
   * @param {Entity} entity The entity whose bounding sphere to compute.
   * @param {BoundingSphere} result The bounding sphere onto which to store the result.
   * @returns {BoundingSphereState} BoundingSphereState.DONE if the result contains the bounding sphere,
   *                       BoundingSphereState.PENDING if the result is still being computed, or
   *                       BoundingSphereState.FAILED if the entity has no visualization in the current scene.
   * @private
   */
  PointVisualizer.prototype.getBoundingSphere = function (entity, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(entity)) {
      throw new DeveloperError("entity is required.");
    }
    if (!defined(result)) {
      throw new DeveloperError("result is required.");
    }
    //>>includeEnd('debug');

    const item = this._items.get(entity.id);
    if (
      !defined(item) ||
      !(defined(item.pointPrimitive) || defined(item.billboard))
    ) {
      return BoundingSphereState$1.FAILED;
    }

    if (defined(item.pointPrimitive)) {
      result.center = Cartesian3.clone(
        item.pointPrimitive.position,
        result.center
      );
    } else {
      const billboard = item.billboard;
      if (!defined(billboard._clampedPosition)) {
        return BoundingSphereState$1.PENDING;
      }
      result.center = Cartesian3.clone(billboard._clampedPosition, result.center);
    }

    result.radius = 0;
    return BoundingSphereState$1.DONE;
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   *
   * @returns {Boolean} True if this object was destroyed; otherwise, false.
   */
  PointVisualizer.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Removes and destroys all primitives created by this instance.
   */
  PointVisualizer.prototype.destroy = function () {
    this._entityCollection.collectionChanged.removeEventListener(
      PointVisualizer.prototype._onCollectionChanged,
      this
    );
    const entities = this._entityCollection.values;
    for (let i = 0; i < entities.length; i++) {
      this._cluster.removePoint(entities[i]);
    }
    return destroyObject(this);
  };

  PointVisualizer.prototype._onCollectionChanged = function (
    entityCollection,
    added,
    removed,
    changed
  ) {
    let i;
    let entity;
    const items = this._items;
    const cluster = this._cluster;

    for (i = added.length - 1; i > -1; i--) {
      entity = added[i];
      if (defined(entity._point) && defined(entity._position)) {
        items.set(entity.id, new EntityData(entity));
      }
    }

    for (i = changed.length - 1; i > -1; i--) {
      entity = changed[i];
      if (defined(entity._point) && defined(entity._position)) {
        if (!items.contains(entity.id)) {
          items.set(entity.id, new EntityData(entity));
        }
      } else {
        returnPrimitive(items.get(entity.id), entity, cluster);
        items.remove(entity.id);
      }
    }

    for (i = removed.length - 1; i > -1; i--) {
      entity = removed[i];
      returnPrimitive(items.get(entity.id), entity, cluster);
      items.remove(entity.id);
    }
  };

  function returnPrimitive(item, entity, cluster) {
    if (defined(item)) {
      const pointPrimitive = item.pointPrimitive;
      if (defined(pointPrimitive)) {
        item.pointPrimitive = undefined;
        cluster.removePoint(entity);
        return;
      }
      const billboard = item.billboard;
      if (defined(billboard)) {
        item.billboard = undefined;
        cluster.removeBillboard(entity);
      }
    }
  }

  const defaultZIndex = new ConstantProperty(0);

  //We use this object to create one polyline collection per-scene.
  const polylineCollections = {};

  const scratchColor$4 = new Color();
  const defaultMaterial = new ColorMaterialProperty(Color.WHITE);
  const defaultShow = new ConstantProperty(true);
  const defaultShadows = new ConstantProperty(ShadowMode$1.DISABLED);
  const defaultDistanceDisplayCondition$1 = new ConstantProperty(
    new DistanceDisplayCondition()
  );
  const defaultClassificationType = new ConstantProperty(ClassificationType$1.BOTH);

  function GeometryOptions() {
    this.vertexFormat = undefined;
    this.positions = undefined;
    this.width = undefined;
    this.arcType = undefined;
    this.granularity = undefined;
  }

  function GroundGeometryOptions() {
    this.positions = undefined;
    this.width = undefined;
    this.arcType = undefined;
    this.granularity = undefined;
  }

  /**
   * A {@link GeometryUpdater} for polylines.
   * Clients do not normally create this class directly, but instead rely on {@link DataSourceDisplay}.
   * @alias PolylineGeometryUpdater
   * @constructor
   *
   * @param {Entity} entity The entity containing the geometry to be visualized.
   * @param {Scene} scene The scene where visualization is taking place.
   */
  function PolylineGeometryUpdater(entity, scene) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(entity)) {
      throw new DeveloperError("entity is required");
    }
    if (!defined(scene)) {
      throw new DeveloperError("scene is required");
    }
    //>>includeEnd('debug');

    this._entity = entity;
    this._scene = scene;
    this._entitySubscription = entity.definitionChanged.addEventListener(
      PolylineGeometryUpdater.prototype._onEntityPropertyChanged,
      this
    );
    this._fillEnabled = false;
    this._dynamic = false;
    this._geometryChanged = new Event();
    this._showProperty = undefined;
    this._materialProperty = undefined;
    this._shadowsProperty = undefined;
    this._distanceDisplayConditionProperty = undefined;
    this._classificationTypeProperty = undefined;
    this._depthFailMaterialProperty = undefined;
    this._geometryOptions = new GeometryOptions();
    this._groundGeometryOptions = new GroundGeometryOptions();
    this._id = `polyline-${entity.id}`;
    this._clampToGround = false;
    this._supportsPolylinesOnTerrain = Entity.supportsPolylinesOnTerrain(scene);

    this._zIndex = 0;

    this._onEntityPropertyChanged(entity, "polyline", entity.polyline, undefined);
  }

  Object.defineProperties(PolylineGeometryUpdater.prototype, {
    /**
     * Gets the unique ID associated with this updater
     * @memberof PolylineGeometryUpdater.prototype
     * @type {String}
     * @readonly
     */
    id: {
      get: function () {
        return this._id;
      },
    },
    /**
     * Gets the entity associated with this geometry.
     * @memberof PolylineGeometryUpdater.prototype
     *
     * @type {Entity}
     * @readonly
     */
    entity: {
      get: function () {
        return this._entity;
      },
    },
    /**
     * Gets a value indicating if the geometry has a fill component.
     * @memberof PolylineGeometryUpdater.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    fillEnabled: {
      get: function () {
        return this._fillEnabled;
      },
    },
    /**
     * Gets a value indicating if fill visibility varies with simulation time.
     * @memberof PolylineGeometryUpdater.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    hasConstantFill: {
      get: function () {
        return (
          !this._fillEnabled ||
          (!defined(this._entity.availability) &&
            Property.isConstant(this._showProperty))
        );
      },
    },
    /**
     * Gets the material property used to fill the geometry.
     * @memberof PolylineGeometryUpdater.prototype
     *
     * @type {MaterialProperty}
     * @readonly
     */
    fillMaterialProperty: {
      get: function () {
        return this._materialProperty;
      },
    },
    /**
     * Gets the material property used to fill the geometry when it fails the depth test.
     * @memberof PolylineGeometryUpdater.prototype
     *
     * @type {MaterialProperty}
     * @readonly
     */
    depthFailMaterialProperty: {
      get: function () {
        return this._depthFailMaterialProperty;
      },
    },
    /**
     * Gets a value indicating if the geometry has an outline component.
     * @memberof PolylineGeometryUpdater.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    outlineEnabled: {
      value: false,
    },
    /**
     * Gets a value indicating if outline visibility varies with simulation time.
     * @memberof PolylineGeometryUpdater.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    hasConstantOutline: {
      value: true,
    },
    /**
     * Gets the {@link Color} property for the geometry outline.
     * @memberof PolylineGeometryUpdater.prototype
     *
     * @type {Property}
     * @readonly
     */
    outlineColorProperty: {
      value: undefined,
    },
    /**
     * Gets the property specifying whether the geometry
     * casts or receives shadows from light sources.
     * @memberof PolylineGeometryUpdater.prototype
     *
     * @type {Property}
     * @readonly
     */
    shadowsProperty: {
      get: function () {
        return this._shadowsProperty;
      },
    },
    /**
     * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this geometry will be displayed.
     * @memberof PolylineGeometryUpdater.prototype
     *
     * @type {Property}
     * @readonly
     */
    distanceDisplayConditionProperty: {
      get: function () {
        return this._distanceDisplayConditionProperty;
      },
    },
    /**
     * Gets or sets the {@link ClassificationType} Property specifying if this geometry will classify terrain, 3D Tiles, or both when on the ground.
     * @memberof PolylineGeometryUpdater.prototype
     *
     * @type {Property}
     * @readonly
     */
    classificationTypeProperty: {
      get: function () {
        return this._classificationTypeProperty;
      },
    },
    /**
     * Gets a value indicating if the geometry is time-varying.
     * If true, all visualization is delegated to the {@link DynamicGeometryUpdater}
     * returned by GeometryUpdater#createDynamicUpdater.
     * @memberof PolylineGeometryUpdater.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    isDynamic: {
      get: function () {
        return this._dynamic;
      },
    },
    /**
     * Gets a value indicating if the geometry is closed.
     * This property is only valid for static geometry.
     * @memberof PolylineGeometryUpdater.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    isClosed: {
      value: false,
    },
    /**
     * Gets an event that is raised whenever the public properties
     * of this updater change.
     * @memberof PolylineGeometryUpdater.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    geometryChanged: {
      get: function () {
        return this._geometryChanged;
      },
    },

    /**
     * Gets a value indicating if the path of the line.
     * @memberof PolylineGeometryUpdater.prototype
     *
     * @type {ArcType}
     * @readonly
     */
    arcType: {
      get: function () {
        return this._arcType;
      },
    },

    /**
     * Gets a value indicating if the geometry is clamped to the ground.
     * Returns false if polylines on terrain is not supported.
     * @memberof PolylineGeometryUpdater.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    clampToGround: {
      get: function () {
        return this._clampToGround && this._supportsPolylinesOnTerrain;
      },
    },

    /**
     * Gets the zindex
     * @type {Number}
     * @memberof PolylineGeometryUpdater.prototype
     * @readonly
     */
    zIndex: {
      get: function () {
        return this._zIndex;
      },
    },
  });

  /**
   * Checks if the geometry is outlined at the provided time.
   *
   * @param {JulianDate} time The time for which to retrieve visibility.
   * @returns {Boolean} true if geometry is outlined at the provided time, false otherwise.
   */
  PolylineGeometryUpdater.prototype.isOutlineVisible = function (time) {
    return false;
  };

  /**
   * Checks if the geometry is filled at the provided time.
   *
   * @param {JulianDate} time The time for which to retrieve visibility.
   * @returns {Boolean} true if geometry is filled at the provided time, false otherwise.
   */
  PolylineGeometryUpdater.prototype.isFilled = function (time) {
    const entity = this._entity;
    const visible =
      this._fillEnabled &&
      entity.isAvailable(time) &&
      this._showProperty.getValue(time);
    return defaultValue(visible, false);
  };

  /**
   * Creates the geometry instance which represents the fill of the geometry.
   *
   * @param {JulianDate} time The time to use when retrieving initial attribute values.
   * @returns {GeometryInstance} The geometry instance representing the filled portion of the geometry.
   *
   * @exception {DeveloperError} This instance does not represent a filled geometry.
   */
  PolylineGeometryUpdater.prototype.createFillGeometryInstance = function (time) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(time)) {
      throw new DeveloperError("time is required.");
    }

    if (!this._fillEnabled) {
      throw new DeveloperError(
        "This instance does not represent a filled geometry."
      );
    }
    //>>includeEnd('debug');

    const entity = this._entity;
    const isAvailable = entity.isAvailable(time);
    const show = new ShowGeometryInstanceAttribute(
      isAvailable && entity.isShowing && this._showProperty.getValue(time)
    );
    const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
      time
    );
    const distanceDisplayConditionAttribute = DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
      distanceDisplayCondition
    );

    const attributes = {
      show: show,
      distanceDisplayCondition: distanceDisplayConditionAttribute,
    };

    let currentColor;
    if (this._materialProperty instanceof ColorMaterialProperty) {
      if (
        defined(this._materialProperty.color) &&
        (this._materialProperty.color.isConstant || isAvailable)
      ) {
        currentColor = this._materialProperty.color.getValue(time, scratchColor$4);
      }
      if (!defined(currentColor)) {
        currentColor = Color.WHITE;
      }
      attributes.color = ColorGeometryInstanceAttribute.fromColor(currentColor);
    }

    if (this.clampToGround) {
      return new GeometryInstance({
        id: entity,
        geometry: new GroundPolylineGeometry(this._groundGeometryOptions),
        attributes: attributes,
      });
    }

    if (
      defined(this._depthFailMaterialProperty) &&
      this._depthFailMaterialProperty instanceof ColorMaterialProperty
    ) {
      if (
        defined(this._depthFailMaterialProperty.color) &&
        (this._depthFailMaterialProperty.color.isConstant || isAvailable)
      ) {
        currentColor = this._depthFailMaterialProperty.color.getValue(
          time,
          scratchColor$4
        );
      }
      if (!defined(currentColor)) {
        currentColor = Color.WHITE;
      }
      attributes.depthFailColor = ColorGeometryInstanceAttribute.fromColor(
        currentColor
      );
    }

    return new GeometryInstance({
      id: entity,
      geometry: new PolylineGeometry(this._geometryOptions),
      attributes: attributes,
    });
  };

  /**
   * Creates the geometry instance which represents the outline of the geometry.
   *
   * @param {JulianDate} time The time to use when retrieving initial attribute values.
   * @returns {GeometryInstance} The geometry instance representing the outline portion of the geometry.
   *
   * @exception {DeveloperError} This instance does not represent an outlined geometry.
   */
  PolylineGeometryUpdater.prototype.createOutlineGeometryInstance = function (
    time
  ) {
    //>>includeStart('debug', pragmas.debug);
    throw new DeveloperError(
      "This instance does not represent an outlined geometry."
    );
    //>>includeEnd('debug');
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   *
   * @returns {Boolean} True if this object was destroyed; otherwise, false.
   */
  PolylineGeometryUpdater.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys and resources used by the object.  Once an object is destroyed, it should not be used.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   */
  PolylineGeometryUpdater.prototype.destroy = function () {
    this._entitySubscription();
    destroyObject(this);
  };

  PolylineGeometryUpdater.prototype._onEntityPropertyChanged = function (
    entity,
    propertyName,
    newValue,
    oldValue
  ) {
    if (!(propertyName === "availability" || propertyName === "polyline")) {
      return;
    }

    const polyline = this._entity.polyline;

    if (!defined(polyline)) {
      if (this._fillEnabled) {
        this._fillEnabled = false;
        this._geometryChanged.raiseEvent(this);
      }
      return;
    }

    const positionsProperty = polyline.positions;

    const show = polyline.show;
    if (
      (defined(show) &&
        show.isConstant &&
        !show.getValue(Iso8601.MINIMUM_VALUE)) || //
      !defined(positionsProperty)
    ) {
      if (this._fillEnabled) {
        this._fillEnabled = false;
        this._geometryChanged.raiseEvent(this);
      }
      return;
    }

    const zIndex = polyline.zIndex;
    const material = defaultValue(polyline.material, defaultMaterial);
    const isColorMaterial = material instanceof ColorMaterialProperty;
    this._materialProperty = material;
    this._depthFailMaterialProperty = polyline.depthFailMaterial;
    this._showProperty = defaultValue(show, defaultShow);
    this._shadowsProperty = defaultValue(polyline.shadows, defaultShadows);
    this._distanceDisplayConditionProperty = defaultValue(
      polyline.distanceDisplayCondition,
      defaultDistanceDisplayCondition$1
    );
    this._classificationTypeProperty = defaultValue(
      polyline.classificationType,
      defaultClassificationType
    );
    this._fillEnabled = true;
    this._zIndex = defaultValue(zIndex, defaultZIndex);

    const width = polyline.width;
    const arcType = polyline.arcType;
    const clampToGround = polyline.clampToGround;
    const granularity = polyline.granularity;

    if (
      !positionsProperty.isConstant ||
      !Property.isConstant(width) ||
      !Property.isConstant(arcType) ||
      !Property.isConstant(granularity) ||
      !Property.isConstant(clampToGround) ||
      !Property.isConstant(zIndex)
    ) {
      if (!this._dynamic) {
        this._dynamic = true;
        this._geometryChanged.raiseEvent(this);
      }
    } else {
      const geometryOptions = this._geometryOptions;
      const positions = positionsProperty.getValue(
        Iso8601.MINIMUM_VALUE,
        geometryOptions.positions
      );

      //Because of the way we currently handle reference properties,
      //we can't automatically assume the positions are always valid.
      if (!defined(positions) || positions.length < 2) {
        if (this._fillEnabled) {
          this._fillEnabled = false;
          this._geometryChanged.raiseEvent(this);
        }
        return;
      }

      let vertexFormat;
      if (
        isColorMaterial &&
        (!defined(this._depthFailMaterialProperty) ||
          this._depthFailMaterialProperty instanceof ColorMaterialProperty)
      ) {
        vertexFormat = PolylineColorAppearance.VERTEX_FORMAT;
      } else {
        vertexFormat = PolylineMaterialAppearance.VERTEX_FORMAT;
      }

      geometryOptions.vertexFormat = vertexFormat;
      geometryOptions.positions = positions;
      geometryOptions.width = defined(width)
        ? width.getValue(Iso8601.MINIMUM_VALUE)
        : undefined;
      geometryOptions.arcType = defined(arcType)
        ? arcType.getValue(Iso8601.MINIMUM_VALUE)
        : undefined;
      geometryOptions.granularity = defined(granularity)
        ? granularity.getValue(Iso8601.MINIMUM_VALUE)
        : undefined;

      const groundGeometryOptions = this._groundGeometryOptions;
      groundGeometryOptions.positions = positions;
      groundGeometryOptions.width = geometryOptions.width;
      groundGeometryOptions.arcType = geometryOptions.arcType;
      groundGeometryOptions.granularity = geometryOptions.granularity;

      this._clampToGround = defined(clampToGround)
        ? clampToGround.getValue(Iso8601.MINIMUM_VALUE)
        : false;

      if (!this._clampToGround && defined(zIndex)) {
        oneTimeWarning(
          "Entity polylines must have clampToGround: true when using zIndex.  zIndex will be ignored."
        );
      }

      this._dynamic = false;
      this._geometryChanged.raiseEvent(this);
    }
  };

  /**
   * Creates the dynamic updater to be used when GeometryUpdater#isDynamic is true.
   *
   * @param {PrimitiveCollection} primitives The primitive collection to use.
   * @param {PrimitiveCollection|OrderedGroundPrimitiveCollection} groundPrimitives The primitive collection to use for ordered ground primitives.
   * @returns {DynamicGeometryUpdater} The dynamic updater used to update the geometry each frame.
   *
   * @exception {DeveloperError} This instance does not represent dynamic geometry.
   * @private
   */
  PolylineGeometryUpdater.prototype.createDynamicUpdater = function (
    primitives,
    groundPrimitives
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("primitives", primitives);
    Check.defined("groundPrimitives", groundPrimitives);

    if (!this._dynamic) {
      throw new DeveloperError(
        "This instance does not represent dynamic geometry."
      );
    }
    //>>includeEnd('debug');

    return new DynamicGeometryUpdater(primitives, groundPrimitives, this);
  };

  /**
   * @private
   */
  const generateCartesianArcOptions = {
    positions: undefined,
    granularity: undefined,
    height: undefined,
    ellipsoid: undefined,
  };

  function DynamicGeometryUpdater(primitives, groundPrimitives, geometryUpdater) {
    this._line = undefined;
    this._primitives = primitives;
    this._groundPrimitives = groundPrimitives;
    this._groundPolylinePrimitive = undefined;
    this._material = undefined;
    this._geometryUpdater = geometryUpdater;
    this._positions = [];
  }

  function getLine(dynamicGeometryUpdater) {
    if (defined(dynamicGeometryUpdater._line)) {
      return dynamicGeometryUpdater._line;
    }

    const sceneId = dynamicGeometryUpdater._geometryUpdater._scene.id;
    let polylineCollection = polylineCollections[sceneId];
    const primitives = dynamicGeometryUpdater._primitives;
    if (!defined(polylineCollection) || polylineCollection.isDestroyed()) {
      polylineCollection = new PolylineCollection();
      polylineCollections[sceneId] = polylineCollection;
      primitives.add(polylineCollection);
    } else if (!primitives.contains(polylineCollection)) {
      primitives.add(polylineCollection);
    }

    const line = polylineCollection.add();
    line.id = dynamicGeometryUpdater._geometryUpdater._entity;
    dynamicGeometryUpdater._line = line;
    return line;
  }

  DynamicGeometryUpdater.prototype.update = function (time) {
    const geometryUpdater = this._geometryUpdater;
    const entity = geometryUpdater._entity;
    const polyline = entity.polyline;

    const positionsProperty = polyline.positions;
    let positions = Property.getValueOrUndefined(
      positionsProperty,
      time,
      this._positions
    );

    // Synchronize with geometryUpdater for GroundPolylinePrimitive
    geometryUpdater._clampToGround = Property.getValueOrDefault(
      polyline._clampToGround,
      time,
      false
    );
    geometryUpdater._groundGeometryOptions.positions = positions;
    geometryUpdater._groundGeometryOptions.width = Property.getValueOrDefault(
      polyline._width,
      time,
      1
    );
    geometryUpdater._groundGeometryOptions.arcType = Property.getValueOrDefault(
      polyline._arcType,
      time,
      ArcType$1.GEODESIC
    );
    geometryUpdater._groundGeometryOptions.granularity = Property.getValueOrDefault(
      polyline._granularity,
      time,
      9999
    );

    const groundPrimitives = this._groundPrimitives;

    if (defined(this._groundPolylinePrimitive)) {
      groundPrimitives.remove(this._groundPolylinePrimitive); // destroys by default
      this._groundPolylinePrimitive = undefined;
    }

    if (geometryUpdater.clampToGround) {
      if (
        !entity.isShowing ||
        !entity.isAvailable(time) ||
        !Property.getValueOrDefault(polyline._show, time, true)
      ) {
        return;
      }

      if (!defined(positions) || positions.length < 2) {
        return;
      }

      const fillMaterialProperty = geometryUpdater.fillMaterialProperty;
      let appearance;
      if (fillMaterialProperty instanceof ColorMaterialProperty) {
        appearance = new PolylineColorAppearance();
      } else {
        const material = MaterialProperty.getValue(
          time,
          fillMaterialProperty,
          this._material
        );
        appearance = new PolylineMaterialAppearance({
          material: material,
          translucent: material.isTranslucent(),
        });
        this._material = material;
      }

      this._groundPolylinePrimitive = groundPrimitives.add(
        new GroundPolylinePrimitive({
          geometryInstances: geometryUpdater.createFillGeometryInstance(time),
          appearance: appearance,
          classificationType: geometryUpdater.classificationTypeProperty.getValue(
            time
          ),
          asynchronous: false,
        }),
        Property.getValueOrUndefined(geometryUpdater.zIndex, time)
      );

      // Hide the polyline in the collection, if any
      if (defined(this._line)) {
        this._line.show = false;
      }
      return;
    }

    const line = getLine(this);

    if (
      !entity.isShowing ||
      !entity.isAvailable(time) ||
      !Property.getValueOrDefault(polyline._show, time, true)
    ) {
      line.show = false;
      return;
    }

    if (!defined(positions) || positions.length < 2) {
      line.show = false;
      return;
    }

    let arcType = ArcType$1.GEODESIC;
    arcType = Property.getValueOrDefault(polyline._arcType, time, arcType);

    const globe = geometryUpdater._scene.globe;
    if (arcType !== ArcType$1.NONE && defined(globe)) {
      generateCartesianArcOptions.ellipsoid = globe.ellipsoid;
      generateCartesianArcOptions.positions = positions;
      generateCartesianArcOptions.granularity = Property.getValueOrUndefined(
        polyline._granularity,
        time
      );
      generateCartesianArcOptions.height = PolylinePipeline.extractHeights(
        positions,
        globe.ellipsoid
      );
      if (arcType === ArcType$1.GEODESIC) {
        positions = PolylinePipeline.generateCartesianArc(
          generateCartesianArcOptions
        );
      } else {
        positions = PolylinePipeline.generateCartesianRhumbArc(
          generateCartesianArcOptions
        );
      }
    }

    line.show = true;
    line.positions = positions.slice();
    line.material = MaterialProperty.getValue(
      time,
      geometryUpdater.fillMaterialProperty,
      line.material
    );
    line.width = Property.getValueOrDefault(polyline._width, time, 1);
    line.distanceDisplayCondition = Property.getValueOrUndefined(
      polyline._distanceDisplayCondition,
      time,
      line.distanceDisplayCondition
    );
  };

  DynamicGeometryUpdater.prototype.getBoundingSphere = function (result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("result", result);
    //>>includeEnd('debug');

    if (!this._geometryUpdater.clampToGround) {
      const line = getLine(this);
      if (line.show && line.positions.length > 0) {
        BoundingSphere.fromPoints(line.positions, result);
        return BoundingSphereState$1.DONE;
      }
    } else {
      const groundPolylinePrimitive = this._groundPolylinePrimitive;
      if (
        defined(groundPolylinePrimitive) &&
        groundPolylinePrimitive.show &&
        groundPolylinePrimitive.ready
      ) {
        const attributes = groundPolylinePrimitive.getGeometryInstanceAttributes(
          this._geometryUpdater._entity
        );
        if (defined(attributes) && defined(attributes.boundingSphere)) {
          BoundingSphere.clone(attributes.boundingSphere, result);
          return BoundingSphereState$1.DONE;
        }
      }

      if (defined(groundPolylinePrimitive) && !groundPolylinePrimitive.ready) {
        return BoundingSphereState$1.PENDING;
      }

      return BoundingSphereState$1.DONE;
    }

    return BoundingSphereState$1.FAILED;
  };

  DynamicGeometryUpdater.prototype.isDestroyed = function () {
    return false;
  };

  DynamicGeometryUpdater.prototype.destroy = function () {
    const geometryUpdater = this._geometryUpdater;
    const sceneId = geometryUpdater._scene.id;
    const polylineCollection = polylineCollections[sceneId];
    if (defined(polylineCollection)) {
      polylineCollection.remove(this._line);
      if (polylineCollection.length === 0) {
        this._primitives.removeAndDestroy(polylineCollection);
        delete polylineCollections[sceneId];
      }
    }
    if (defined(this._groundPolylinePrimitive)) {
      this._groundPrimitives.remove(this._groundPolylinePrimitive);
    }
    destroyObject(this);
  };

  const scratchColor$3 = new Color();
  const distanceDisplayConditionScratch = new DistanceDisplayCondition();
  const defaultDistanceDisplayCondition = new DistanceDisplayCondition();

  // Encapsulates a Primitive and all the entities that it represents.
  function Batch(
    orderedGroundPrimitives,
    classificationType,
    materialProperty,
    zIndex,
    asynchronous
  ) {
    let appearanceType;
    if (materialProperty instanceof ColorMaterialProperty) {
      appearanceType = PolylineColorAppearance;
    } else {
      appearanceType = PolylineMaterialAppearance;
    }

    this.orderedGroundPrimitives = orderedGroundPrimitives; // scene level primitive collection
    this.classificationType = classificationType;
    this.appearanceType = appearanceType;
    this.materialProperty = materialProperty;
    this.updaters = new AssociativeArray();
    this.createPrimitive = true;
    this.primitive = undefined; // a GroundPolylinePrimitive encapsulating all the entities
    this.oldPrimitive = undefined;
    this.geometry = new AssociativeArray();
    this.material = undefined;
    this.updatersWithAttributes = new AssociativeArray();
    this.attributes = new AssociativeArray();
    this.invalidated = false;
    this.removeMaterialSubscription = materialProperty.definitionChanged.addEventListener(
      Batch.prototype.onMaterialChanged,
      this
    );
    this.subscriptions = new AssociativeArray();
    this.showsUpdated = new AssociativeArray();
    this.zIndex = zIndex;

    this._asynchronous = asynchronous;
  }

  Batch.prototype.onMaterialChanged = function () {
    this.invalidated = true;
  };

  // Check if the given updater's material is compatible with this batch
  Batch.prototype.isMaterial = function (updater) {
    const material = this.materialProperty;
    const updaterMaterial = updater.fillMaterialProperty;

    if (
      updaterMaterial === material ||
      (updaterMaterial instanceof ColorMaterialProperty &&
        material instanceof ColorMaterialProperty)
    ) {
      return true;
    }
    return defined(material) && material.equals(updaterMaterial);
  };

  Batch.prototype.add = function (time, updater, geometryInstance) {
    const id = updater.id;
    this.updaters.set(id, updater);
    this.geometry.set(id, geometryInstance);
    // Updaters with dynamic attributes must be tracked separately, may exit the batch
    if (
      !updater.hasConstantFill ||
      !updater.fillMaterialProperty.isConstant ||
      !Property.isConstant(updater.distanceDisplayConditionProperty)
    ) {
      this.updatersWithAttributes.set(id, updater);
    } else {
      const that = this;
      // Listen for show changes. These will be synchronized in updateShows.
      this.subscriptions.set(
        id,
        updater.entity.definitionChanged.addEventListener(function (
          entity,
          propertyName,
          newValue,
          oldValue
        ) {
          if (propertyName === "isShowing") {
            that.showsUpdated.set(updater.id, updater);
          }
        })
      );
    }
    this.createPrimitive = true;
  };

  Batch.prototype.remove = function (updater) {
    const id = updater.id;
    this.createPrimitive = this.geometry.remove(id) || this.createPrimitive;
    if (this.updaters.remove(id)) {
      this.updatersWithAttributes.remove(id);
      const unsubscribe = this.subscriptions.get(id);
      if (defined(unsubscribe)) {
        unsubscribe();
        this.subscriptions.remove(id);
      }
      return true;
    }
    return false;
  };

  Batch.prototype.update = function (time) {
    let isUpdated = true;
    let primitive = this.primitive;
    const orderedGroundPrimitives = this.orderedGroundPrimitives;
    const geometries = this.geometry.values;
    let i;

    if (this.createPrimitive) {
      const geometriesLength = geometries.length;
      if (geometriesLength > 0) {
        if (defined(primitive)) {
          // Keep a handle to the old primitive so it can be removed when the updated version is ready.
          if (!defined(this.oldPrimitive)) {
            this.oldPrimitive = primitive;
          } else {
            // For if the new primitive changes again before it is ready.
            orderedGroundPrimitives.remove(primitive);
          }
        }

        primitive = new GroundPolylinePrimitive({
          show: false,
          asynchronous: this._asynchronous,
          geometryInstances: geometries.slice(),
          appearance: new this.appearanceType(),
          classificationType: this.classificationType,
        });

        if (this.appearanceType === PolylineMaterialAppearance) {
          this.material = MaterialProperty.getValue(
            time,
            this.materialProperty,
            this.material
          );
          primitive.appearance.material = this.material;
        }

        orderedGroundPrimitives.add(primitive, this.zIndex);
        isUpdated = false;
      } else {
        if (defined(primitive)) {
          orderedGroundPrimitives.remove(primitive);
          primitive = undefined;
        }
        const oldPrimitive = this.oldPrimitive;
        if (defined(oldPrimitive)) {
          orderedGroundPrimitives.remove(oldPrimitive);
          this.oldPrimitive = undefined;
        }
      }

      this.attributes.removeAll();
      this.primitive = primitive;
      this.createPrimitive = false;
    } else if (defined(primitive) && primitive.ready) {
      primitive.show = true;
      if (defined(this.oldPrimitive)) {
        orderedGroundPrimitives.remove(this.oldPrimitive);
        this.oldPrimitive = undefined;
      }

      if (this.appearanceType === PolylineMaterialAppearance) {
        this.material = MaterialProperty.getValue(
          time,
          this.materialProperty,
          this.material
        );
        this.primitive.appearance.material = this.material;
      }
      const updatersWithAttributes = this.updatersWithAttributes.values;
      const length = updatersWithAttributes.length;
      for (i = 0; i < length; i++) {
        const updater = updatersWithAttributes[i];
        const entity = updater.entity;
        const instance = this.geometry.get(updater.id);

        let attributes = this.attributes.get(instance.id.id);
        if (!defined(attributes)) {
          attributes = primitive.getGeometryInstanceAttributes(instance.id);
          this.attributes.set(instance.id.id, attributes);
        }

        if (!updater.fillMaterialProperty.isConstant) {
          const colorProperty = updater.fillMaterialProperty.color;
          const resultColor = Property.getValueOrDefault(
            colorProperty,
            time,
            Color.WHITE,
            scratchColor$3
          );
          if (!Color.equals(attributes._lastColor, resultColor)) {
            attributes._lastColor = Color.clone(
              resultColor,
              attributes._lastColor
            );
            attributes.color = ColorGeometryInstanceAttribute.toValue(
              resultColor,
              attributes.color
            );
          }
        }

        const show =
          entity.isShowing && (updater.hasConstantFill || updater.isFilled(time));
        const currentShow = attributes.show[0] === 1;
        if (show !== currentShow) {
          attributes.show = ShowGeometryInstanceAttribute.toValue(
            show,
            attributes.show
          );
        }

        const distanceDisplayConditionProperty =
          updater.distanceDisplayConditionProperty;
        if (!Property.isConstant(distanceDisplayConditionProperty)) {
          const distanceDisplayCondition = Property.getValueOrDefault(
            distanceDisplayConditionProperty,
            time,
            defaultDistanceDisplayCondition,
            distanceDisplayConditionScratch
          );
          if (
            !DistanceDisplayCondition.equals(
              distanceDisplayCondition,
              attributes._lastDistanceDisplayCondition
            )
          ) {
            attributes._lastDistanceDisplayCondition = DistanceDisplayCondition.clone(
              distanceDisplayCondition,
              attributes._lastDistanceDisplayCondition
            );
            attributes.distanceDisplayCondition = DistanceDisplayConditionGeometryInstanceAttribute.toValue(
              distanceDisplayCondition,
              attributes.distanceDisplayCondition
            );
          }
        }
      }

      this.updateShows(primitive);
    } else if (defined(primitive) && !primitive.ready) {
      isUpdated = false;
    }
    return isUpdated;
  };

  Batch.prototype.updateShows = function (primitive) {
    const showsUpdated = this.showsUpdated.values;
    const length = showsUpdated.length;
    for (let i = 0; i < length; i++) {
      const updater = showsUpdated[i];
      const entity = updater.entity;
      const instance = this.geometry.get(updater.id);

      let attributes = this.attributes.get(instance.id.id);
      if (!defined(attributes)) {
        attributes = primitive.getGeometryInstanceAttributes(instance.id);
        this.attributes.set(instance.id.id, attributes);
      }

      const show = entity.isShowing;
      const currentShow = attributes.show[0] === 1;
      if (show !== currentShow) {
        attributes.show = ShowGeometryInstanceAttribute.toValue(
          show,
          attributes.show
        );
        instance.attributes.show.value[0] = attributes.show[0];
      }
    }
    this.showsUpdated.removeAll();
  };

  Batch.prototype.contains = function (updater) {
    return this.updaters.contains(updater.id);
  };

  Batch.prototype.getBoundingSphere = function (updater, result) {
    const primitive = this.primitive;
    if (!primitive.ready) {
      return BoundingSphereState$1.PENDING;
    }
    const attributes = primitive.getGeometryInstanceAttributes(updater.entity);
    if (
      !defined(attributes) ||
      !defined(attributes.boundingSphere) ||
      (defined(attributes.show) && attributes.show[0] === 0)
    ) {
      return BoundingSphereState$1.FAILED;
    }
    attributes.boundingSphere.clone(result);
    return BoundingSphereState$1.DONE;
  };

  Batch.prototype.destroy = function () {
    const primitive = this.primitive;
    const orderedGroundPrimitives = this.orderedGroundPrimitives;
    if (defined(primitive)) {
      orderedGroundPrimitives.remove(primitive);
    }
    const oldPrimitive = this.oldPrimitive;
    if (defined(oldPrimitive)) {
      orderedGroundPrimitives.remove(oldPrimitive);
    }
    this.removeMaterialSubscription();
  };

  /**
   * @private
   */
  function StaticGroundPolylinePerMaterialBatch(
    orderedGroundPrimitives,
    classificationType,
    asynchronous
  ) {
    this._items = [];
    this._orderedGroundPrimitives = orderedGroundPrimitives;
    this._classificationType = classificationType;
    this._asynchronous = defaultValue(asynchronous, true);
  }

  StaticGroundPolylinePerMaterialBatch.prototype.add = function (time, updater) {
    const items = this._items;
    const length = items.length;
    const geometryInstance = updater.createFillGeometryInstance(time);
    const zIndex = Property.getValueOrDefault(updater.zIndex, 0);
    // Check if the Entity represented by the updater has the same material or a material representable with per-instance color.
    for (let i = 0; i < length; ++i) {
      const item = items[i];
      if (item.isMaterial(updater) && item.zIndex === zIndex) {
        item.add(time, updater, geometryInstance);
        return;
      }
    }
    // If a compatible batch wasn't found, create a new batch.
    const batch = new Batch(
      this._orderedGroundPrimitives,
      this._classificationType,
      updater.fillMaterialProperty,
      zIndex,
      this._asynchronous
    );
    batch.add(time, updater, geometryInstance);
    items.push(batch);
  };

  StaticGroundPolylinePerMaterialBatch.prototype.remove = function (updater) {
    const items = this._items;
    const length = items.length;
    for (let i = length - 1; i >= 0; i--) {
      const item = items[i];
      if (item.remove(updater)) {
        if (item.updaters.length === 0) {
          items.splice(i, 1);
          item.destroy();
        }
        break;
      }
    }
  };

  StaticGroundPolylinePerMaterialBatch.prototype.update = function (time) {
    let i;
    const items = this._items;
    const length = items.length;

    for (i = length - 1; i >= 0; i--) {
      const item = items[i];
      if (item.invalidated) {
        items.splice(i, 1);
        const updaters = item.updaters.values;
        const updatersLength = updaters.length;
        for (let h = 0; h < updatersLength; h++) {
          this.add(time, updaters[h]);
        }
        item.destroy();
      }
    }

    let isUpdated = true;
    for (i = 0; i < items.length; i++) {
      isUpdated = items[i].update(time) && isUpdated;
    }
    return isUpdated;
  };

  StaticGroundPolylinePerMaterialBatch.prototype.getBoundingSphere = function (
    updater,
    result
  ) {
    const items = this._items;
    const length = items.length;
    for (let i = 0; i < length; i++) {
      const item = items[i];
      if (item.contains(updater)) {
        return item.getBoundingSphere(updater, result);
      }
    }
    return BoundingSphereState$1.FAILED;
  };

  StaticGroundPolylinePerMaterialBatch.prototype.removeAllPrimitives = function () {
    const items = this._items;
    const length = items.length;
    for (let i = 0; i < length; i++) {
      items[i].destroy();
    }
    this._items.length = 0;
  };

  const emptyArray = [];

  function removeUpdater(that, updater) {
    //We don't keep track of which batch an updater is in, so just remove it from all of them.
    const batches = that._batches;
    const length = batches.length;
    for (let i = 0; i < length; i++) {
      batches[i].remove(updater);
    }
  }

  function insertUpdaterIntoBatch(that, time, updater) {
    if (updater.isDynamic) {
      that._dynamicBatch.add(time, updater);
      return;
    }

    if (updater.clampToGround && updater.fillEnabled) {
      // Also checks for support
      const classificationType = updater.classificationTypeProperty.getValue(
        time
      );
      that._groundBatches[classificationType].add(time, updater);
      return;
    }

    let shadows;
    if (updater.fillEnabled) {
      shadows = updater.shadowsProperty.getValue(time);
    }

    let multiplier = 0;
    if (defined(updater.depthFailMaterialProperty)) {
      multiplier =
        updater.depthFailMaterialProperty instanceof ColorMaterialProperty
          ? 1
          : 2;
    }

    let index;
    if (defined(shadows)) {
      index = shadows + multiplier * ShadowMode$1.NUMBER_OF_SHADOW_MODES;
    }

    if (updater.fillEnabled) {
      if (updater.fillMaterialProperty instanceof ColorMaterialProperty) {
        that._colorBatches[index].add(time, updater);
      } else {
        that._materialBatches[index].add(time, updater);
      }
    }
  }

  /**
   * A visualizer for polylines represented by {@link Primitive} instances.
   * @alias PolylineVisualizer
   * @constructor
   *
   * @param {Scene} scene The scene the primitives will be rendered in.
   * @param {EntityCollection} entityCollection The entityCollection to visualize.
   * @param {PrimitiveCollection} [primitives=scene.primitives] A collection to add primitives related to the entities
   * @param {PrimitiveCollection} [groundPrimitives=scene.groundPrimitives] A collection to add ground primitives related to the entities
   */
  function PolylineVisualizer(
    scene,
    entityCollection,
    primitives,
    groundPrimitives
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("scene", scene);
    Check.defined("entityCollection", entityCollection);
    //>>includeEnd('debug');

    groundPrimitives = defaultValue(groundPrimitives, scene.groundPrimitives);
    primitives = defaultValue(primitives, scene.primitives);

    this._scene = scene;
    this._primitives = primitives;
    this._entityCollection = undefined;
    this._addedObjects = new AssociativeArray();
    this._removedObjects = new AssociativeArray();
    this._changedObjects = new AssociativeArray();

    let i;
    const numberOfShadowModes = ShadowMode$1.NUMBER_OF_SHADOW_MODES;
    this._colorBatches = new Array(numberOfShadowModes * 3);
    this._materialBatches = new Array(numberOfShadowModes * 3);

    for (i = 0; i < numberOfShadowModes; ++i) {
      this._colorBatches[i] = new StaticGeometryColorBatch(
        primitives,
        PolylineColorAppearance,
        undefined,
        false,
        i
      ); // no depth fail appearance
      this._materialBatches[i] = new StaticGeometryPerMaterialBatch(
        primitives,
        PolylineMaterialAppearance,
        undefined,
        false,
        i
      );

      this._colorBatches[i + numberOfShadowModes] = new StaticGeometryColorBatch(
        primitives,
        PolylineColorAppearance,
        PolylineColorAppearance,
        false,
        i
      ); //depth fail appearance variations
      this._materialBatches[
        i + numberOfShadowModes
      ] = new StaticGeometryPerMaterialBatch(
        primitives,
        PolylineMaterialAppearance,
        PolylineColorAppearance,
        false,
        i
      );

      this._colorBatches[
        i + numberOfShadowModes * 2
      ] = new StaticGeometryColorBatch(
        primitives,
        PolylineColorAppearance,
        PolylineMaterialAppearance,
        false,
        i
      );
      this._materialBatches[
        i + numberOfShadowModes * 2
      ] = new StaticGeometryPerMaterialBatch(
        primitives,
        PolylineMaterialAppearance,
        PolylineMaterialAppearance,
        false,
        i
      );
    }

    this._dynamicBatch = new DynamicGeometryBatch(primitives, groundPrimitives);

    const numberOfClassificationTypes =
      ClassificationType$1.NUMBER_OF_CLASSIFICATION_TYPES;
    this._groundBatches = new Array(numberOfClassificationTypes);

    for (i = 0; i < numberOfClassificationTypes; ++i) {
      this._groundBatches[i] = new StaticGroundPolylinePerMaterialBatch(
        groundPrimitives,
        i
      );
    }

    this._batches = this._colorBatches.concat(
      this._materialBatches,
      this._dynamicBatch,
      this._groundBatches
    );

    this._subscriptions = new AssociativeArray();
    this._updaters = new AssociativeArray();

    this._entityCollection = entityCollection;
    entityCollection.collectionChanged.addEventListener(
      PolylineVisualizer.prototype._onCollectionChanged,
      this
    );
    this._onCollectionChanged(
      entityCollection,
      entityCollection.values,
      emptyArray
    );
  }

  /**
   * Updates all of the primitives created by this visualizer to match their
   * Entity counterpart at the given time.
   *
   * @param {JulianDate} time The time to update to.
   * @returns {Boolean} True if the visualizer successfully updated to the provided time,
   * false if the visualizer is waiting for asynchronous primitives to be created.
   */
  PolylineVisualizer.prototype.update = function (time) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("time", time);
    //>>includeEnd('debug');

    const addedObjects = this._addedObjects;
    const added = addedObjects.values;
    const removedObjects = this._removedObjects;
    const removed = removedObjects.values;
    const changedObjects = this._changedObjects;
    const changed = changedObjects.values;

    let i;
    let entity;
    let id;
    let updater;

    for (i = changed.length - 1; i > -1; i--) {
      entity = changed[i];
      id = entity.id;
      updater = this._updaters.get(id);

      //If in a single update, an entity gets removed and a new instance
      //re-added with the same id, the updater no longer tracks the
      //correct entity, we need to both remove the old one and
      //add the new one, which is done by pushing the entity
      //onto the removed/added lists.
      if (updater.entity === entity) {
        removeUpdater(this, updater);
        insertUpdaterIntoBatch(this, time, updater);
      } else {
        removed.push(entity);
        added.push(entity);
      }
    }

    for (i = removed.length - 1; i > -1; i--) {
      entity = removed[i];
      id = entity.id;
      updater = this._updaters.get(id);
      removeUpdater(this, updater);
      updater.destroy();
      this._updaters.remove(id);
      this._subscriptions.get(id)();
      this._subscriptions.remove(id);
    }

    for (i = added.length - 1; i > -1; i--) {
      entity = added[i];
      id = entity.id;
      updater = new PolylineGeometryUpdater(entity, this._scene);
      this._updaters.set(id, updater);
      insertUpdaterIntoBatch(this, time, updater);
      this._subscriptions.set(
        id,
        updater.geometryChanged.addEventListener(
          PolylineVisualizer._onGeometryChanged,
          this
        )
      );
    }

    addedObjects.removeAll();
    removedObjects.removeAll();
    changedObjects.removeAll();

    let isUpdated = true;
    const batches = this._batches;
    const length = batches.length;
    for (i = 0; i < length; i++) {
      isUpdated = batches[i].update(time) && isUpdated;
    }

    return isUpdated;
  };

  const getBoundingSphereArrayScratch$1 = [];
  const getBoundingSphereBoundingSphereScratch$1 = new BoundingSphere();

  /**
   * Computes a bounding sphere which encloses the visualization produced for the specified entity.
   * The bounding sphere is in the fixed frame of the scene's globe.
   *
   * @param {Entity} entity The entity whose bounding sphere to compute.
   * @param {BoundingSphere} result The bounding sphere onto which to store the result.
   * @returns {BoundingSphereState} BoundingSphereState.DONE if the result contains the bounding sphere,
   *                       BoundingSphereState.PENDING if the result is still being computed, or
   *                       BoundingSphereState.FAILED if the entity has no visualization in the current scene.
   * @private
   */
  PolylineVisualizer.prototype.getBoundingSphere = function (entity, result) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("entity", entity);
    Check.defined("result", result);
    //>>includeEnd('debug');

    const boundingSpheres = getBoundingSphereArrayScratch$1;
    const tmp = getBoundingSphereBoundingSphereScratch$1;

    let count = 0;
    let state = BoundingSphereState$1.DONE;
    const batches = this._batches;
    const batchesLength = batches.length;
    const updater = this._updaters.get(entity.id);
    for (let i = 0; i < batchesLength; i++) {
      state = batches[i].getBoundingSphere(updater, tmp);
      if (state === BoundingSphereState$1.PENDING) {
        return BoundingSphereState$1.PENDING;
      } else if (state === BoundingSphereState$1.DONE) {
        boundingSpheres[count] = BoundingSphere.clone(
          tmp,
          boundingSpheres[count]
        );
        count++;
      }
    }

    if (count === 0) {
      return BoundingSphereState$1.FAILED;
    }

    boundingSpheres.length = count;
    BoundingSphere.fromBoundingSpheres(boundingSpheres, result);
    return BoundingSphereState$1.DONE;
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   *
   * @returns {Boolean} True if this object was destroyed; otherwise, false.
   */
  PolylineVisualizer.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Removes and destroys all primitives created by this instance.
   */
  PolylineVisualizer.prototype.destroy = function () {
    this._entityCollection.collectionChanged.removeEventListener(
      PolylineVisualizer.prototype._onCollectionChanged,
      this
    );
    this._addedObjects.removeAll();
    this._removedObjects.removeAll();

    let i;
    const batches = this._batches;
    let length = batches.length;
    for (i = 0; i < length; i++) {
      batches[i].removeAllPrimitives();
    }

    const subscriptions = this._subscriptions.values;
    length = subscriptions.length;
    for (i = 0; i < length; i++) {
      subscriptions[i]();
    }
    this._subscriptions.removeAll();
    return destroyObject(this);
  };

  /**
   * @private
   */
  PolylineVisualizer._onGeometryChanged = function (updater) {
    const removedObjects = this._removedObjects;
    const changedObjects = this._changedObjects;

    const entity = updater.entity;
    const id = entity.id;

    if (!defined(removedObjects.get(id)) && !defined(changedObjects.get(id))) {
      changedObjects.set(id, entity);
    }
  };

  /**
   * @private
   */
  PolylineVisualizer.prototype._onCollectionChanged = function (
    entityCollection,
    added,
    removed
  ) {
    const addedObjects = this._addedObjects;
    const removedObjects = this._removedObjects;
    const changedObjects = this._changedObjects;

    let i;
    let id;
    let entity;
    for (i = removed.length - 1; i > -1; i--) {
      entity = removed[i];
      id = entity.id;
      if (!addedObjects.remove(id)) {
        removedObjects.set(id, entity);
        changedObjects.remove(id);
      }
    }

    for (i = added.length - 1; i > -1; i--) {
      entity = added[i];
      id = entity.id;
      if (removedObjects.remove(id)) {
        changedObjects.set(id, entity);
      } else {
        addedObjects.set(id, entity);
      }
    }
  };

  /**
   * Visualizes a collection of {@link DataSource} instances.
   * @alias DataSourceDisplay
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Scene} options.scene The scene in which to display the data.
   * @param {DataSourceCollection} options.dataSourceCollection The data sources to display.
   * @param {DataSourceDisplay.VisualizersCallback} [options.visualizersCallback=DataSourceDisplay.defaultVisualizersCallback]
   *        A function which creates an array of visualizers used for visualization.
   *        If undefined, all standard visualizers are used.
   */
  function DataSourceDisplay(options) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options", options);
    Check.typeOf.object("options.scene", options.scene);
    Check.typeOf.object(
      "options.dataSourceCollection",
      options.dataSourceCollection
    );
    //>>includeEnd('debug');

    GroundPrimitive.initializeTerrainHeights();
    GroundPolylinePrimitive.initializeTerrainHeights();

    const scene = options.scene;
    const dataSourceCollection = options.dataSourceCollection;

    this._eventHelper = new EventHelper();
    this._eventHelper.add(
      dataSourceCollection.dataSourceAdded,
      this._onDataSourceAdded,
      this
    );
    this._eventHelper.add(
      dataSourceCollection.dataSourceRemoved,
      this._onDataSourceRemoved,
      this
    );
    this._eventHelper.add(
      dataSourceCollection.dataSourceMoved,
      this._onDataSourceMoved,
      this
    );
    this._eventHelper.add(scene.postRender, this._postRender, this);

    this._dataSourceCollection = dataSourceCollection;
    this._scene = scene;
    this._visualizersCallback = defaultValue(
      options.visualizersCallback,
      DataSourceDisplay.defaultVisualizersCallback
    );

    let primitivesAdded = false;
    const primitives = new PrimitiveCollection();
    const groundPrimitives = new PrimitiveCollection();

    if (dataSourceCollection.length > 0) {
      scene.primitives.add(primitives);
      scene.groundPrimitives.add(groundPrimitives);
      primitivesAdded = true;
    }

    this._primitives = primitives;
    this._groundPrimitives = groundPrimitives;

    for (let i = 0, len = dataSourceCollection.length; i < len; i++) {
      this._onDataSourceAdded(dataSourceCollection, dataSourceCollection.get(i));
    }

    const defaultDataSource = new CustomDataSource();
    this._onDataSourceAdded(undefined, defaultDataSource);
    this._defaultDataSource = defaultDataSource;

    let removeDefaultDataSourceListener;
    let removeDataSourceCollectionListener;
    if (!primitivesAdded) {
      const that = this;
      const addPrimitives = function () {
        scene.primitives.add(primitives);
        scene.groundPrimitives.add(groundPrimitives);
        removeDefaultDataSourceListener();
        removeDataSourceCollectionListener();
        that._removeDefaultDataSourceListener = undefined;
        that._removeDataSourceCollectionListener = undefined;
      };
      removeDefaultDataSourceListener = defaultDataSource.entities.collectionChanged.addEventListener(
        addPrimitives
      );
      removeDataSourceCollectionListener = dataSourceCollection.dataSourceAdded.addEventListener(
        addPrimitives
      );
    }

    this._removeDefaultDataSourceListener = removeDefaultDataSourceListener;
    this._removeDataSourceCollectionListener = removeDataSourceCollectionListener;

    this._ready = false;
  }

  /**
   * Gets or sets the default function which creates an array of visualizers used for visualization.
   * By default, this function uses all standard visualizers.
   *
   * @type {DataSourceDisplay.VisualizersCallback}
   */
  DataSourceDisplay.defaultVisualizersCallback = function (
    scene,
    entityCluster,
    dataSource
  ) {
    const entities = dataSource.entities;
    return [
      new BillboardVisualizer(entityCluster, entities),
      new GeometryVisualizer(
        scene,
        entities,
        dataSource._primitives,
        dataSource._groundPrimitives
      ),
      new LabelVisualizer(entityCluster, entities),
      new ModelVisualizer(scene, entities),
      new Cesium3DTilesetVisualizer(scene, entities),
      new PointVisualizer(entityCluster, entities),
      new PathVisualizer(scene, entities),
      new PolylineVisualizer(
        scene,
        entities,
        dataSource._primitives,
        dataSource._groundPrimitives
      ),
    ];
  };

  Object.defineProperties(DataSourceDisplay.prototype, {
    /**
     * Gets the scene associated with this display.
     * @memberof DataSourceDisplay.prototype
     * @type {Scene}
     */
    scene: {
      get: function () {
        return this._scene;
      },
    },
    /**
     * Gets the collection of data sources to display.
     * @memberof DataSourceDisplay.prototype
     * @type {DataSourceCollection}
     */
    dataSources: {
      get: function () {
        return this._dataSourceCollection;
      },
    },
    /**
     * Gets the default data source instance which can be used to
     * manually create and visualize entities not tied to
     * a specific data source. This instance is always available
     * and does not appear in the list dataSources collection.
     * @memberof DataSourceDisplay.prototype
     * @type {CustomDataSource}
     */
    defaultDataSource: {
      get: function () {
        return this._defaultDataSource;
      },
    },

    /**
     * Gets a value indicating whether or not all entities in the data source are ready
     * @memberof DataSourceDisplay.prototype
     * @type {Boolean}
     * @readonly
     */
    ready: {
      get: function () {
        return this._ready;
      },
    },
  });

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} True if this object was destroyed; otherwise, false.
   *
   * @see DataSourceDisplay#destroy
   */
  DataSourceDisplay.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * dataSourceDisplay = dataSourceDisplay.destroy();
   *
   * @see DataSourceDisplay#isDestroyed
   */
  DataSourceDisplay.prototype.destroy = function () {
    this._eventHelper.removeAll();

    const dataSourceCollection = this._dataSourceCollection;
    for (let i = 0, length = dataSourceCollection.length; i < length; ++i) {
      this._onDataSourceRemoved(
        this._dataSourceCollection,
        dataSourceCollection.get(i)
      );
    }
    this._onDataSourceRemoved(undefined, this._defaultDataSource);

    if (defined(this._removeDefaultDataSourceListener)) {
      this._removeDefaultDataSourceListener();
      this._removeDataSourceCollectionListener();
    } else {
      this._scene.primitives.remove(this._primitives);
      this._scene.groundPrimitives.remove(this._groundPrimitives);
    }

    return destroyObject(this);
  };

  /**
   * Updates the display to the provided time.
   *
   * @param {JulianDate} time The simulation time.
   * @returns {Boolean} True if all data sources are ready to be displayed, false otherwise.
   */
  DataSourceDisplay.prototype.update = function (time) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("time", time);
    //>>includeEnd('debug');

    if (!ApproximateTerrainHeights.initialized) {
      this._ready = false;
      return false;
    }

    let result = true;

    let i;
    let x;
    let visualizers;
    let vLength;
    const dataSources = this._dataSourceCollection;
    const length = dataSources.length;
    for (i = 0; i < length; i++) {
      const dataSource = dataSources.get(i);
      if (defined(dataSource.update)) {
        result = dataSource.update(time) && result;
      }

      visualizers = dataSource._visualizers;
      vLength = visualizers.length;
      for (x = 0; x < vLength; x++) {
        result = visualizers[x].update(time) && result;
      }
    }

    visualizers = this._defaultDataSource._visualizers;
    vLength = visualizers.length;
    for (x = 0; x < vLength; x++) {
      result = visualizers[x].update(time) && result;
    }

    this._ready = result;

    return result;
  };

  DataSourceDisplay.prototype._postRender = function () {
    // Adds credits for all datasources
    const frameState = this._scene.frameState;
    const dataSources = this._dataSourceCollection;
    const length = dataSources.length;
    for (let i = 0; i < length; i++) {
      const dataSource = dataSources.get(i);

      const credit = dataSource.credit;
      if (defined(credit)) {
        frameState.creditDisplay.addCredit(credit);
      }

      // Credits from the resource that the user can't remove
      const credits = dataSource._resourceCredits;
      if (defined(credits)) {
        const creditCount = credits.length;
        for (let c = 0; c < creditCount; c++) {
          frameState.creditDisplay.addCredit(credits[c]);
        }
      }
    }
  };

  const getBoundingSphereArrayScratch = [];
  const getBoundingSphereBoundingSphereScratch = new BoundingSphere();

  /**
   * Computes a bounding sphere which encloses the visualization produced for the specified entity.
   * The bounding sphere is in the fixed frame of the scene's globe.
   *
   * @param {Entity} entity The entity whose bounding sphere to compute.
   * @param {Boolean} allowPartial If true, pending bounding spheres are ignored and an answer will be returned from the currently available data.
   *                               If false, the the function will halt and return pending if any of the bounding spheres are pending.
   * @param {BoundingSphere} result The bounding sphere onto which to store the result.
   * @returns {BoundingSphereState} BoundingSphereState.DONE if the result contains the bounding sphere,
   *                       BoundingSphereState.PENDING if the result is still being computed, or
   *                       BoundingSphereState.FAILED if the entity has no visualization in the current scene.
   * @private
   */
  DataSourceDisplay.prototype.getBoundingSphere = function (
    entity,
    allowPartial,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("entity", entity);
    Check.typeOf.bool("allowPartial", allowPartial);
    Check.defined("result", result);
    //>>includeEnd('debug');

    if (!this._ready) {
      return BoundingSphereState$1.PENDING;
    }

    let i;
    let length;
    let dataSource = this._defaultDataSource;
    if (!dataSource.entities.contains(entity)) {
      dataSource = undefined;

      const dataSources = this._dataSourceCollection;
      length = dataSources.length;
      for (i = 0; i < length; i++) {
        const d = dataSources.get(i);
        if (d.entities.contains(entity)) {
          dataSource = d;
          break;
        }
      }
    }

    if (!defined(dataSource)) {
      return BoundingSphereState$1.FAILED;
    }

    const boundingSpheres = getBoundingSphereArrayScratch;
    const tmp = getBoundingSphereBoundingSphereScratch;

    let count = 0;
    let state = BoundingSphereState$1.DONE;
    const visualizers = dataSource._visualizers;
    const visualizersLength = visualizers.length;

    for (i = 0; i < visualizersLength; i++) {
      const visualizer = visualizers[i];
      if (defined(visualizer.getBoundingSphere)) {
        state = visualizers[i].getBoundingSphere(entity, tmp);
        if (!allowPartial && state === BoundingSphereState$1.PENDING) {
          return BoundingSphereState$1.PENDING;
        } else if (state === BoundingSphereState$1.DONE) {
          boundingSpheres[count] = BoundingSphere.clone(
            tmp,
            boundingSpheres[count]
          );
          count++;
        }
      }
    }

    if (count === 0) {
      return BoundingSphereState$1.FAILED;
    }

    boundingSpheres.length = count;
    BoundingSphere.fromBoundingSpheres(boundingSpheres, result);
    return BoundingSphereState$1.DONE;
  };

  DataSourceDisplay.prototype._onDataSourceAdded = function (
    dataSourceCollection,
    dataSource
  ) {
    const scene = this._scene;

    const displayPrimitives = this._primitives;
    const displayGroundPrimitives = this._groundPrimitives;

    const primitives = displayPrimitives.add(new PrimitiveCollection());
    const groundPrimitives = displayGroundPrimitives.add(
      new OrderedGroundPrimitiveCollection()
    );

    dataSource._primitives = primitives;
    dataSource._groundPrimitives = groundPrimitives;

    const entityCluster = dataSource.clustering;
    entityCluster._initialize(scene);

    primitives.add(entityCluster);

    dataSource._visualizers = this._visualizersCallback(
      scene,
      entityCluster,
      dataSource
    );
  };

  DataSourceDisplay.prototype._onDataSourceRemoved = function (
    dataSourceCollection,
    dataSource
  ) {
    const displayPrimitives = this._primitives;
    const displayGroundPrimitives = this._groundPrimitives;

    const primitives = dataSource._primitives;
    const groundPrimitives = dataSource._groundPrimitives;

    const entityCluster = dataSource.clustering;
    primitives.remove(entityCluster);

    const visualizers = dataSource._visualizers;
    const length = visualizers.length;
    for (let i = 0; i < length; i++) {
      visualizers[i].destroy();
    }

    displayPrimitives.remove(primitives);
    displayGroundPrimitives.remove(groundPrimitives);

    dataSource._visualizers = undefined;
  };

  DataSourceDisplay.prototype._onDataSourceMoved = function (
    dataSource,
    newIndex,
    oldIndex
  ) {
    const displayPrimitives = this._primitives;
    const displayGroundPrimitives = this._groundPrimitives;

    const primitives = dataSource._primitives;
    const groundPrimitives = dataSource._groundPrimitives;

    if (newIndex === oldIndex + 1) {
      displayPrimitives.raise(primitives);
      displayGroundPrimitives.raise(groundPrimitives);
    } else if (newIndex === oldIndex - 1) {
      displayPrimitives.lower(primitives);
      displayGroundPrimitives.lower(groundPrimitives);
    } else if (newIndex === 0) {
      displayPrimitives.lowerToBottom(primitives);
      displayGroundPrimitives.lowerToBottom(groundPrimitives);
      displayPrimitives.raise(primitives); // keep defaultDataSource primitives at index 0 since it's not in the collection
      displayGroundPrimitives.raise(groundPrimitives);
    } else {
      displayPrimitives.raiseToTop(primitives);
      displayGroundPrimitives.raiseToTop(groundPrimitives);
    }
  };

  const updateTransformMatrix3Scratch1 = new Matrix3();
  const updateTransformMatrix3Scratch2 = new Matrix3();
  const updateTransformMatrix3Scratch3 = new Matrix3();
  const updateTransformMatrix4Scratch = new Matrix4();
  const updateTransformCartesian3Scratch1 = new Cartesian3();
  const updateTransformCartesian3Scratch2 = new Cartesian3();
  const updateTransformCartesian3Scratch3 = new Cartesian3();
  const updateTransformCartesian3Scratch4 = new Cartesian3();
  const updateTransformCartesian3Scratch5 = new Cartesian3();
  const updateTransformCartesian3Scratch6 = new Cartesian3();
  const deltaTime = new JulianDate();
  const northUpAxisFactor = 1.25; // times ellipsoid's maximum radius

  function updateTransform(
    that,
    camera,
    updateLookAt,
    saveCamera,
    positionProperty,
    time,
    ellipsoid
  ) {
    const mode = that.scene.mode;
    let cartesian = positionProperty.getValue(time, that._lastCartesian);
    if (defined(cartesian)) {
      let hasBasis = false;
      let invertVelocity = false;
      let xBasis;
      let yBasis;
      let zBasis;

      if (mode === SceneMode$1.SCENE3D) {
        // The time delta was determined based on how fast satellites move compared to vehicles near the surface.
        // Slower moving vehicles will most likely default to east-north-up, while faster ones will be VVLH.
        JulianDate.addSeconds(time, 0.001, deltaTime);
        let deltaCartesian = positionProperty.getValue(
          deltaTime,
          updateTransformCartesian3Scratch1
        );

        // If no valid position at (time + 0.001), sample at (time - 0.001) and invert the vector
        if (!defined(deltaCartesian)) {
          JulianDate.addSeconds(time, -0.001, deltaTime);
          deltaCartesian = positionProperty.getValue(
            deltaTime,
            updateTransformCartesian3Scratch1
          );
          invertVelocity = true;
        }

        if (defined(deltaCartesian)) {
          let toInertial = Transforms.computeFixedToIcrfMatrix(
            time,
            updateTransformMatrix3Scratch1
          );
          let toInertialDelta = Transforms.computeFixedToIcrfMatrix(
            deltaTime,
            updateTransformMatrix3Scratch2
          );
          let toFixed;

          if (!defined(toInertial) || !defined(toInertialDelta)) {
            toFixed = Transforms.computeTemeToPseudoFixedMatrix(
              time,
              updateTransformMatrix3Scratch3
            );
            toInertial = Matrix3.transpose(
              toFixed,
              updateTransformMatrix3Scratch1
            );
            toInertialDelta = Transforms.computeTemeToPseudoFixedMatrix(
              deltaTime,
              updateTransformMatrix3Scratch2
            );
            Matrix3.transpose(toInertialDelta, toInertialDelta);
          } else {
            toFixed = Matrix3.transpose(
              toInertial,
              updateTransformMatrix3Scratch3
            );
          }

          const inertialCartesian = Matrix3.multiplyByVector(
            toInertial,
            cartesian,
            updateTransformCartesian3Scratch5
          );
          const inertialDeltaCartesian = Matrix3.multiplyByVector(
            toInertialDelta,
            deltaCartesian,
            updateTransformCartesian3Scratch6
          );

          Cartesian3.subtract(
            inertialCartesian,
            inertialDeltaCartesian,
            updateTransformCartesian3Scratch4
          );
          const inertialVelocity =
            Cartesian3.magnitude(updateTransformCartesian3Scratch4) * 1000.0; // meters/sec

          const mu = CesiumMath.GRAVITATIONALPARAMETER; // m^3 / sec^2
          const semiMajorAxis =
            -mu /
            (inertialVelocity * inertialVelocity -
              (2 * mu) / Cartesian3.magnitude(inertialCartesian));

          if (
            semiMajorAxis < 0 ||
            semiMajorAxis > northUpAxisFactor * ellipsoid.maximumRadius
          ) {
            // North-up viewing from deep space.

            // X along the nadir
            xBasis = updateTransformCartesian3Scratch2;
            Cartesian3.normalize(cartesian, xBasis);
            Cartesian3.negate(xBasis, xBasis);

            // Z is North
            zBasis = Cartesian3.clone(
              Cartesian3.UNIT_Z,
              updateTransformCartesian3Scratch3
            );

            // Y is along the cross of z and x (right handed basis / in the direction of motion)
            yBasis = Cartesian3.cross(
              zBasis,
              xBasis,
              updateTransformCartesian3Scratch1
            );
            if (Cartesian3.magnitude(yBasis) > CesiumMath.EPSILON7) {
              Cartesian3.normalize(xBasis, xBasis);
              Cartesian3.normalize(yBasis, yBasis);

              zBasis = Cartesian3.cross(
                xBasis,
                yBasis,
                updateTransformCartesian3Scratch3
              );
              Cartesian3.normalize(zBasis, zBasis);

              hasBasis = true;
            }
          } else if (
            !Cartesian3.equalsEpsilon(
              cartesian,
              deltaCartesian,
              CesiumMath.EPSILON7
            )
          ) {
            // Approximation of VVLH (Vehicle Velocity Local Horizontal) with the Z-axis flipped.

            // Z along the position
            zBasis = updateTransformCartesian3Scratch2;
            Cartesian3.normalize(inertialCartesian, zBasis);
            Cartesian3.normalize(inertialDeltaCartesian, inertialDeltaCartesian);

            // Y is along the angular momentum vector (e.g. "orbit normal")
            yBasis = Cartesian3.cross(
              zBasis,
              inertialDeltaCartesian,
              updateTransformCartesian3Scratch3
            );

            if (invertVelocity) {
              yBasis = Cartesian3.multiplyByScalar(yBasis, -1, yBasis);
            }

            if (
              !Cartesian3.equalsEpsilon(
                yBasis,
                Cartesian3.ZERO,
                CesiumMath.EPSILON7
              )
            ) {
              // X is along the cross of y and z (right handed basis / in the direction of motion)
              xBasis = Cartesian3.cross(
                yBasis,
                zBasis,
                updateTransformCartesian3Scratch1
              );

              Matrix3.multiplyByVector(toFixed, xBasis, xBasis);
              Matrix3.multiplyByVector(toFixed, yBasis, yBasis);
              Matrix3.multiplyByVector(toFixed, zBasis, zBasis);

              Cartesian3.normalize(xBasis, xBasis);
              Cartesian3.normalize(yBasis, yBasis);
              Cartesian3.normalize(zBasis, zBasis);

              hasBasis = true;
            }
          }
        }
      }

      if (defined(that.boundingSphere)) {
        cartesian = that.boundingSphere.center;
      }

      let position;
      let direction;
      let up;

      if (saveCamera) {
        position = Cartesian3.clone(
          camera.position,
          updateTransformCartesian3Scratch4
        );
        direction = Cartesian3.clone(
          camera.direction,
          updateTransformCartesian3Scratch5
        );
        up = Cartesian3.clone(camera.up, updateTransformCartesian3Scratch6);
      }

      const transform = updateTransformMatrix4Scratch;
      if (hasBasis) {
        transform[0] = xBasis.x;
        transform[1] = xBasis.y;
        transform[2] = xBasis.z;
        transform[3] = 0.0;
        transform[4] = yBasis.x;
        transform[5] = yBasis.y;
        transform[6] = yBasis.z;
        transform[7] = 0.0;
        transform[8] = zBasis.x;
        transform[9] = zBasis.y;
        transform[10] = zBasis.z;
        transform[11] = 0.0;
        transform[12] = cartesian.x;
        transform[13] = cartesian.y;
        transform[14] = cartesian.z;
        transform[15] = 0.0;
      } else {
        // Stationary or slow-moving, low-altitude objects use East-North-Up.
        Transforms.eastNorthUpToFixedFrame(cartesian, ellipsoid, transform);
      }

      camera._setTransform(transform);

      if (saveCamera) {
        Cartesian3.clone(position, camera.position);
        Cartesian3.clone(direction, camera.direction);
        Cartesian3.clone(up, camera.up);
        Cartesian3.cross(direction, up, camera.right);
      }
    }

    if (updateLookAt) {
      const offset =
        mode === SceneMode$1.SCENE2D ||
        Cartesian3.equals(that._offset3D, Cartesian3.ZERO)
          ? undefined
          : that._offset3D;
      camera.lookAtTransform(camera.transform, offset);
    }
  }

  /**
   * A utility object for tracking an entity with the camera.
   * @alias EntityView
   * @constructor
   *
   * @param {Entity} entity The entity to track with the camera.
   * @param {Scene} scene The scene to use.
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid to use for orienting the camera.
   */
  function EntityView(entity, scene, ellipsoid) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("entity", entity);
    Check.defined("scene", scene);
    //>>includeEnd('debug');

    /**
     * The entity to track with the camera.
     * @type {Entity}
     */
    this.entity = entity;

    /**
     * The scene in which to track the object.
     * @type {Scene}
     */
    this.scene = scene;

    /**
     * The ellipsoid to use for orienting the camera.
     * @type {Ellipsoid}
     */
    this.ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);

    /**
     * The bounding sphere of the object.
     * @type {BoundingSphere}
     */
    this.boundingSphere = undefined;

    // Shadow copies of the objects so we can detect changes.
    this._lastEntity = undefined;
    this._mode = undefined;

    this._lastCartesian = new Cartesian3();
    this._defaultOffset3D = undefined;

    this._offset3D = new Cartesian3();
  }

  // STATIC properties defined here, not per-instance.
  Object.defineProperties(EntityView, {
    /**
     * Gets or sets a camera offset that will be used to
     * initialize subsequent EntityViews.
     * @memberof EntityView
     * @type {Cartesian3}
     */
    defaultOffset3D: {
      get: function () {
        return this._defaultOffset3D;
      },
      set: function (vector) {
        this._defaultOffset3D = Cartesian3.clone(vector, new Cartesian3());
      },
    },
  });

  // Initialize the static property.
  EntityView.defaultOffset3D = new Cartesian3(-14000, 3500, 3500);

  const scratchHeadingPitchRange = new HeadingPitchRange();
  const scratchCartesian$2 = new Cartesian3();

  /**
   * Should be called each animation frame to update the camera
   * to the latest settings.
   * @param {JulianDate} time The current animation time.
   * @param {BoundingSphere} [boundingSphere] bounding sphere of the object.
   */
  EntityView.prototype.update = function (time, boundingSphere) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("time", time);
    //>>includeEnd('debug');

    const scene = this.scene;
    const ellipsoid = this.ellipsoid;
    const sceneMode = scene.mode;
    if (sceneMode === SceneMode$1.MORPHING) {
      return;
    }

    const entity = this.entity;
    const positionProperty = entity.position;
    if (!defined(positionProperty)) {
      return;
    }
    const objectChanged = entity !== this._lastEntity;
    const sceneModeChanged = sceneMode !== this._mode;

    const camera = scene.camera;

    let updateLookAt = objectChanged || sceneModeChanged;
    let saveCamera = true;

    if (objectChanged) {
      const viewFromProperty = entity.viewFrom;
      const hasViewFrom = defined(viewFromProperty);

      if (!hasViewFrom && defined(boundingSphere)) {
        // The default HPR is not ideal for high altitude objects so
        // we scale the pitch as we get further from the earth for a more
        // downward view.
        scratchHeadingPitchRange.pitch = -CesiumMath.PI_OVER_FOUR;
        scratchHeadingPitchRange.range = 0;
        const position = positionProperty.getValue(time, scratchCartesian$2);
        if (defined(position)) {
          const factor =
            2 -
            1 /
              Math.max(
                1,
                Cartesian3.magnitude(position) / ellipsoid.maximumRadius
              );
          scratchHeadingPitchRange.pitch *= factor;
        }

        camera.viewBoundingSphere(boundingSphere, scratchHeadingPitchRange);
        this.boundingSphere = boundingSphere;
        updateLookAt = false;
        saveCamera = false;
      } else if (
        !hasViewFrom ||
        !defined(viewFromProperty.getValue(time, this._offset3D))
      ) {
        Cartesian3.clone(EntityView._defaultOffset3D, this._offset3D);
      }
    } else if (!sceneModeChanged && this._mode !== SceneMode$1.SCENE2D) {
      Cartesian3.clone(camera.position, this._offset3D);
    }

    this._lastEntity = entity;
    this._mode = sceneMode;

    updateTransform(
      this,
      camera,
      updateLookAt,
      saveCamera,
      positionProperty,
      time,
      ellipsoid
    );
  };

  /* This file is automatically rebuilt by the Cesium build process. */
  function identity(x) {
    return x;
  }

  function transform$1(transform) {
    if (transform == null) return identity;
    var x0,
        y0,
        kx = transform.scale[0],
        ky = transform.scale[1],
        dx = transform.translate[0],
        dy = transform.translate[1];
    return function(input, i) {
      if (!i) x0 = y0 = 0;
      var j = 2, n = input.length, output = new Array(n);
      output[0] = (x0 += input[0]) * kx + dx;
      output[1] = (y0 += input[1]) * ky + dy;
      while (j < n) output[j] = input[j], ++j;
      return output;
    };
  }

  function bbox(topology) {
    var t = transform$1(topology.transform), key,
        x0 = Infinity, y0 = x0, x1 = -x0, y1 = -x0;

    function bboxPoint(p) {
      p = t(p);
      if (p[0] < x0) x0 = p[0];
      if (p[0] > x1) x1 = p[0];
      if (p[1] < y0) y0 = p[1];
      if (p[1] > y1) y1 = p[1];
    }

    function bboxGeometry(o) {
      switch (o.type) {
        case "GeometryCollection": o.geometries.forEach(bboxGeometry); break;
        case "Point": bboxPoint(o.coordinates); break;
        case "MultiPoint": o.coordinates.forEach(bboxPoint); break;
      }
    }

    topology.arcs.forEach(function(arc) {
      var i = -1, n = arc.length, p;
      while (++i < n) {
        p = t(arc[i], i);
        if (p[0] < x0) x0 = p[0];
        if (p[0] > x1) x1 = p[0];
        if (p[1] < y0) y0 = p[1];
        if (p[1] > y1) y1 = p[1];
      }
    });

    for (key in topology.objects) {
      bboxGeometry(topology.objects[key]);
    }

    return [x0, y0, x1, y1];
  }

  function reverse(array, n) {
    var t, j = array.length, i = j - n;
    while (i < --j) t = array[i], array[i++] = array[j], array[j] = t;
  }

  function feature(topology, o) {
    if (typeof o === "string") o = topology.objects[o];
    return o.type === "GeometryCollection"
        ? {type: "FeatureCollection", features: o.geometries.map(function(o) { return feature$1(topology, o); })}
        : feature$1(topology, o);
  }

  function feature$1(topology, o) {
    var id = o.id,
        bbox = o.bbox,
        properties = o.properties == null ? {} : o.properties,
        geometry = object(topology, o);
    return id == null && bbox == null ? {type: "Feature", properties: properties, geometry: geometry}
        : bbox == null ? {type: "Feature", id: id, properties: properties, geometry: geometry}
        : {type: "Feature", id: id, bbox: bbox, properties: properties, geometry: geometry};
  }

  function object(topology, o) {
    var transformPoint = transform$1(topology.transform),
        arcs = topology.arcs;

    function arc(i, points) {
      if (points.length) points.pop();
      for (var a = arcs[i < 0 ? ~i : i], k = 0, n = a.length; k < n; ++k) {
        points.push(transformPoint(a[k], k));
      }
      if (i < 0) reverse(points, n);
    }

    function point(p) {
      return transformPoint(p);
    }

    function line(arcs) {
      var points = [];
      for (var i = 0, n = arcs.length; i < n; ++i) arc(arcs[i], points);
      if (points.length < 2) points.push(points[0]); // This should never happen per the specification.
      return points;
    }

    function ring(arcs) {
      var points = line(arcs);
      while (points.length < 4) points.push(points[0]); // This may happen if an arc has only two points.
      return points;
    }

    function polygon(arcs) {
      return arcs.map(ring);
    }

    function geometry(o) {
      var type = o.type, coordinates;
      switch (type) {
        case "GeometryCollection": return {type: type, geometries: o.geometries.map(geometry)};
        case "Point": coordinates = point(o.coordinates); break;
        case "MultiPoint": coordinates = o.coordinates.map(point); break;
        case "LineString": coordinates = line(o.arcs); break;
        case "MultiLineString": coordinates = o.arcs.map(line); break;
        case "Polygon": coordinates = polygon(o.arcs); break;
        case "MultiPolygon": coordinates = o.arcs.map(polygon); break;
        default: return null;
      }
      return {type: type, coordinates: coordinates};
    }

    return geometry(o);
  }

  function stitch(topology, arcs) {
    var stitchedArcs = {},
        fragmentByStart = {},
        fragmentByEnd = {},
        fragments = [],
        emptyIndex = -1;

    // Stitch empty arcs first, since they may be subsumed by other arcs.
    arcs.forEach(function(i, j) {
      var arc = topology.arcs[i < 0 ? ~i : i], t;
      if (arc.length < 3 && !arc[1][0] && !arc[1][1]) {
        t = arcs[++emptyIndex], arcs[emptyIndex] = i, arcs[j] = t;
      }
    });

    arcs.forEach(function(i) {
      var e = ends(i),
          start = e[0],
          end = e[1],
          f, g;

      if (f = fragmentByEnd[start]) {
        delete fragmentByEnd[f.end];
        f.push(i);
        f.end = end;
        if (g = fragmentByStart[end]) {
          delete fragmentByStart[g.start];
          var fg = g === f ? f : f.concat(g);
          fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.end] = fg;
        } else {
          fragmentByStart[f.start] = fragmentByEnd[f.end] = f;
        }
      } else if (f = fragmentByStart[end]) {
        delete fragmentByStart[f.start];
        f.unshift(i);
        f.start = start;
        if (g = fragmentByEnd[start]) {
          delete fragmentByEnd[g.end];
          var gf = g === f ? f : g.concat(f);
          fragmentByStart[gf.start = g.start] = fragmentByEnd[gf.end = f.end] = gf;
        } else {
          fragmentByStart[f.start] = fragmentByEnd[f.end] = f;
        }
      } else {
        f = [i];
        fragmentByStart[f.start = start] = fragmentByEnd[f.end = end] = f;
      }
    });

    function ends(i) {
      var arc = topology.arcs[i < 0 ? ~i : i], p0 = arc[0], p1;
      if (topology.transform) p1 = [0, 0], arc.forEach(function(dp) { p1[0] += dp[0], p1[1] += dp[1]; });
      else p1 = arc[arc.length - 1];
      return i < 0 ? [p1, p0] : [p0, p1];
    }

    function flush(fragmentByEnd, fragmentByStart) {
      for (var k in fragmentByEnd) {
        var f = fragmentByEnd[k];
        delete fragmentByStart[f.start];
        delete f.start;
        delete f.end;
        f.forEach(function(i) { stitchedArcs[i < 0 ? ~i : i] = 1; });
        fragments.push(f);
      }
    }

    flush(fragmentByEnd, fragmentByStart);
    flush(fragmentByStart, fragmentByEnd);
    arcs.forEach(function(i) { if (!stitchedArcs[i < 0 ? ~i : i]) fragments.push([i]); });

    return fragments;
  }

  function mesh(topology) {
    return object(topology, meshArcs.apply(this, arguments));
  }

  function meshArcs(topology, object, filter) {
    var arcs, i, n;
    if (arguments.length > 1) arcs = extractArcs(topology, object, filter);
    else for (i = 0, arcs = new Array(n = topology.arcs.length); i < n; ++i) arcs[i] = i;
    return {type: "MultiLineString", arcs: stitch(topology, arcs)};
  }

  function extractArcs(topology, object, filter) {
    var arcs = [],
        geomsByArc = [],
        geom;

    function extract0(i) {
      var j = i < 0 ? ~i : i;
      (geomsByArc[j] || (geomsByArc[j] = [])).push({i: i, g: geom});
    }

    function extract1(arcs) {
      arcs.forEach(extract0);
    }

    function extract2(arcs) {
      arcs.forEach(extract1);
    }

    function extract3(arcs) {
      arcs.forEach(extract2);
    }

    function geometry(o) {
      switch (geom = o, o.type) {
        case "GeometryCollection": o.geometries.forEach(geometry); break;
        case "LineString": extract1(o.arcs); break;
        case "MultiLineString": case "Polygon": extract2(o.arcs); break;
        case "MultiPolygon": extract3(o.arcs); break;
      }
    }

    geometry(object);

    geomsByArc.forEach(filter == null
        ? function(geoms) { arcs.push(geoms[0].i); }
        : function(geoms) { if (filter(geoms[0].g, geoms[geoms.length - 1].g)) arcs.push(geoms[0].i); });

    return arcs;
  }

  function planarRingArea(ring) {
    var i = -1, n = ring.length, a, b = ring[n - 1], area = 0;
    while (++i < n) a = b, b = ring[i], area += a[0] * b[1] - a[1] * b[0];
    return Math.abs(area); // Note: doubled area!
  }

  function merge(topology) {
    return object(topology, mergeArcs.apply(this, arguments));
  }

  function mergeArcs(topology, objects) {
    var polygonsByArc = {},
        polygons = [],
        groups = [];

    objects.forEach(geometry);

    function geometry(o) {
      switch (o.type) {
        case "GeometryCollection": o.geometries.forEach(geometry); break;
        case "Polygon": extract(o.arcs); break;
        case "MultiPolygon": o.arcs.forEach(extract); break;
      }
    }

    function extract(polygon) {
      polygon.forEach(function(ring) {
        ring.forEach(function(arc) {
          (polygonsByArc[arc = arc < 0 ? ~arc : arc] || (polygonsByArc[arc] = [])).push(polygon);
        });
      });
      polygons.push(polygon);
    }

    function area(ring) {
      return planarRingArea(object(topology, {type: "Polygon", arcs: [ring]}).coordinates[0]);
    }

    polygons.forEach(function(polygon) {
      if (!polygon._) {
        var group = [],
            neighbors = [polygon];
        polygon._ = 1;
        groups.push(group);
        while (polygon = neighbors.pop()) {
          group.push(polygon);
          polygon.forEach(function(ring) {
            ring.forEach(function(arc) {
              polygonsByArc[arc < 0 ? ~arc : arc].forEach(function(polygon) {
                if (!polygon._) {
                  polygon._ = 1;
                  neighbors.push(polygon);
                }
              });
            });
          });
        }
      }
    });

    polygons.forEach(function(polygon) {
      delete polygon._;
    });

    return {
      type: "MultiPolygon",
      arcs: groups.map(function(polygons) {
        var arcs = [], n;

        // Extract the exterior (unique) arcs.
        polygons.forEach(function(polygon) {
          polygon.forEach(function(ring) {
            ring.forEach(function(arc) {
              if (polygonsByArc[arc < 0 ? ~arc : arc].length < 2) {
                arcs.push(arc);
              }
            });
          });
        });

        // Stitch the arcs into one or more rings.
        arcs = stitch(topology, arcs);

        // If more than one ring is returned,
        // at most one of these rings can be the exterior;
        // choose the one with the greatest absolute area.
        if ((n = arcs.length) > 1) {
          for (var i = 1, k = area(arcs[0]), ki, t; i < n; ++i) {
            if ((ki = area(arcs[i])) > k) {
              t = arcs[0], arcs[0] = arcs[i], arcs[i] = t, k = ki;
            }
          }
        }

        return arcs;
      }).filter(function(arcs) {
        return arcs.length > 0;
      })
    };
  }

  function bisect(a, x) {
    var lo = 0, hi = a.length;
    while (lo < hi) {
      var mid = lo + hi >>> 1;
      if (a[mid] < x) lo = mid + 1;
      else hi = mid;
    }
    return lo;
  }

  function neighbors(objects) {
    var indexesByArc = {}, // arc index -> array of object indexes
        neighbors = objects.map(function() { return []; });

    function line(arcs, i) {
      arcs.forEach(function(a) {
        if (a < 0) a = ~a;
        var o = indexesByArc[a];
        if (o) o.push(i);
        else indexesByArc[a] = [i];
      });
    }

    function polygon(arcs, i) {
      arcs.forEach(function(arc) { line(arc, i); });
    }

    function geometry(o, i) {
      if (o.type === "GeometryCollection") o.geometries.forEach(function(o) { geometry(o, i); });
      else if (o.type in geometryType) geometryType[o.type](o.arcs, i);
    }

    var geometryType = {
      LineString: line,
      MultiLineString: polygon,
      Polygon: polygon,
      MultiPolygon: function(arcs, i) { arcs.forEach(function(arc) { polygon(arc, i); }); }
    };

    objects.forEach(geometry);

    for (var i in indexesByArc) {
      for (var indexes = indexesByArc[i], m = indexes.length, j = 0; j < m; ++j) {
        for (var k = j + 1; k < m; ++k) {
          var ij = indexes[j], ik = indexes[k], n;
          if ((n = neighbors[ij])[i = bisect(n, ik)] !== ik) n.splice(i, 0, ik);
          if ((n = neighbors[ik])[i = bisect(n, ij)] !== ij) n.splice(i, 0, ij);
        }
      }
    }

    return neighbors;
  }

  function untransform(transform) {
    if (transform == null) return identity;
    var x0,
        y0,
        kx = transform.scale[0],
        ky = transform.scale[1],
        dx = transform.translate[0],
        dy = transform.translate[1];
    return function(input, i) {
      if (!i) x0 = y0 = 0;
      var j = 2,
          n = input.length,
          output = new Array(n),
          x1 = Math.round((input[0] - dx) / kx),
          y1 = Math.round((input[1] - dy) / ky);
      output[0] = x1 - x0, x0 = x1;
      output[1] = y1 - y0, y0 = y1;
      while (j < n) output[j] = input[j], ++j;
      return output;
    };
  }

  function quantize(topology, transform) {
    if (topology.transform) throw new Error("already quantized");

    if (!transform || !transform.scale) {
      if (!((n = Math.floor(transform)) >= 2)) throw new Error("n must be ≥2");
      box = topology.bbox || bbox(topology);
      var x0 = box[0], y0 = box[1], x1 = box[2], y1 = box[3], n;
      transform = {scale: [x1 - x0 ? (x1 - x0) / (n - 1) : 1, y1 - y0 ? (y1 - y0) / (n - 1) : 1], translate: [x0, y0]};
    } else {
      box = topology.bbox;
    }

    var t = untransform(transform), box, key, inputs = topology.objects, outputs = {};

    function quantizePoint(point) {
      return t(point);
    }

    function quantizeGeometry(input) {
      var output;
      switch (input.type) {
        case "GeometryCollection": output = {type: "GeometryCollection", geometries: input.geometries.map(quantizeGeometry)}; break;
        case "Point": output = {type: "Point", coordinates: quantizePoint(input.coordinates)}; break;
        case "MultiPoint": output = {type: "MultiPoint", coordinates: input.coordinates.map(quantizePoint)}; break;
        default: return input;
      }
      if (input.id != null) output.id = input.id;
      if (input.bbox != null) output.bbox = input.bbox;
      if (input.properties != null) output.properties = input.properties;
      return output;
    }

    function quantizeArc(input) {
      var i = 0, j = 1, n = input.length, p, output = new Array(n); // pessimistic
      output[0] = t(input[0], 0);
      while (++i < n) if ((p = t(input[i], i))[0] || p[1]) output[j++] = p; // non-coincident points
      if (j === 1) output[j++] = [0, 0]; // an arc must have at least two points
      output.length = j;
      return output;
    }

    for (key in inputs) outputs[key] = quantizeGeometry(inputs[key]);

    return {
      type: "Topology",
      bbox: box,
      transform: transform,
      objects: outputs,
      arcs: topology.arcs.map(quantizeArc)
    };
  }

  var index = /*#__PURE__*/Object.freeze({
    __proto__: null,
    bbox: bbox,
    feature: feature,
    mesh: mesh,
    meshArcs: meshArcs,
    merge: merge,
    mergeArcs: mergeArcs,
    neighbors: neighbors,
    quantize: quantize,
    transform: transform$1,
    untransform: untransform
  });

  function defaultCrsFunction(coordinates) {
    return Cartesian3.fromDegrees(coordinates[0], coordinates[1], coordinates[2]);
  }

  const crsNames = {
    "urn:ogc:def:crs:OGC:1.3:CRS84": defaultCrsFunction,
    "EPSG:4326": defaultCrsFunction,
    "urn:ogc:def:crs:EPSG::4326": defaultCrsFunction,
  };

  const crsLinkHrefs = {};
  const crsLinkTypes = {};
  let defaultMarkerSize = 48;
  let defaultMarkerSymbol;
  let defaultMarkerColor = Color.ROYALBLUE;
  let defaultStroke = Color.YELLOW;
  let defaultStrokeWidth = 2;
  let defaultFill = Color.fromBytes(255, 255, 0, 100);
  let defaultClampToGround = false;

  const sizes = {
    small: 24,
    medium: 48,
    large: 64,
  };

  const simpleStyleIdentifiers = [
    "title",
    "description", //
    "marker-size",
    "marker-symbol",
    "marker-color",
    "stroke", //
    "stroke-opacity",
    "stroke-width",
    "fill",
    "fill-opacity",
  ];

  function defaultDescribe(properties, nameProperty) {
    let html = "";
    for (const key in properties) {
      if (properties.hasOwnProperty(key)) {
        if (key === nameProperty || simpleStyleIdentifiers.indexOf(key) !== -1) {
          continue;
        }
        const value = properties[key];
        if (defined(value)) {
          if (typeof value === "object") {
            html += `<tr><th>${key}</th><td>${defaultDescribe(value)}</td></tr>`;
          } else {
            html += `<tr><th>${key}</th><td>${value}</td></tr>`;
          }
        }
      }
    }

    if (html.length > 0) {
      html = `<table class="cesium-infoBox-defaultTable"><tbody>${html}</tbody></table>`;
    }

    return html;
  }

  function createDescriptionCallback(describe, properties, nameProperty) {
    let description;
    return function (time, result) {
      if (!defined(description)) {
        description = describe(properties, nameProperty);
      }
      return description;
    };
  }

  function defaultDescribeProperty(properties, nameProperty) {
    return new CallbackProperty(
      createDescriptionCallback(defaultDescribe, properties, nameProperty),
      true
    );
  }

  //GeoJSON specifies only the Feature object has a usable id property
  //But since "multi" geometries create multiple entity,
  //we can't use it for them either.
  function createObject(geoJson, entityCollection, describe) {
    let id = geoJson.id;
    if (!defined(id) || geoJson.type !== "Feature") {
      id = createGuid();
    } else {
      let i = 2;
      let finalId = id;
      while (defined(entityCollection.getById(finalId))) {
        finalId = `${id}_${i}`;
        i++;
      }
      id = finalId;
    }

    const entity = entityCollection.getOrCreateEntity(id);
    const properties = geoJson.properties;
    if (defined(properties)) {
      entity.properties = properties;

      let nameProperty;

      //Check for the simplestyle specified name first.
      const name = properties.title;
      if (defined(name)) {
        entity.name = name;
        nameProperty = "title";
      } else {
        //Else, find the name by selecting an appropriate property.
        //The name will be obtained based on this order:
        //1) The first case-insensitive property with the name 'title',
        //2) The first case-insensitive property with the name 'name',
        //3) The first property containing the word 'title'.
        //4) The first property containing the word 'name',
        let namePropertyPrecedence = Number.MAX_VALUE;
        for (const key in properties) {
          if (properties.hasOwnProperty(key) && properties[key]) {
            const lowerKey = key.toLowerCase();

            if (namePropertyPrecedence > 1 && lowerKey === "title") {
              namePropertyPrecedence = 1;
              nameProperty = key;
              break;
            } else if (namePropertyPrecedence > 2 && lowerKey === "name") {
              namePropertyPrecedence = 2;
              nameProperty = key;
            } else if (namePropertyPrecedence > 3 && /title/i.test(key)) {
              namePropertyPrecedence = 3;
              nameProperty = key;
            } else if (namePropertyPrecedence > 4 && /name/i.test(key)) {
              namePropertyPrecedence = 4;
              nameProperty = key;
            }
          }
        }
        if (defined(nameProperty)) {
          entity.name = properties[nameProperty];
        }
      }

      const description = properties.description;
      if (description !== null) {
        entity.description = !defined(description)
          ? describe(properties, nameProperty)
          : new ConstantProperty(description);
      }
    }
    return entity;
  }

  function coordinatesArrayToCartesianArray(coordinates, crsFunction) {
    const positions = new Array(coordinates.length);
    for (let i = 0; i < coordinates.length; i++) {
      positions[i] = crsFunction(coordinates[i]);
    }
    return positions;
  }

  const geoJsonObjectTypes = {
    Feature: processFeature$1,
    FeatureCollection: processFeatureCollection,
    GeometryCollection: processGeometryCollection,
    LineString: processLineString,
    MultiLineString: processMultiLineString,
    MultiPoint: processMultiPoint,
    MultiPolygon: processMultiPolygon,
    Point: processPoint$1,
    Polygon: processPolygon$1,
    Topology: processTopology,
  };

  const geometryTypes$1 = {
    GeometryCollection: processGeometryCollection,
    LineString: processLineString,
    MultiLineString: processMultiLineString,
    MultiPoint: processMultiPoint,
    MultiPolygon: processMultiPolygon,
    Point: processPoint$1,
    Polygon: processPolygon$1,
    Topology: processTopology,
  };

  // GeoJSON processing functions
  function processFeature$1(dataSource, feature, notUsed, crsFunction, options) {
    if (feature.geometry === null) {
      //Null geometry is allowed, so just create an empty entity instance for it.
      createObject(feature, dataSource._entityCollection, options.describe);
      return;
    }

    if (!defined(feature.geometry)) {
      throw new RuntimeError("feature.geometry is required.");
    }

    const geometryType = feature.geometry.type;
    const geometryHandler = geometryTypes$1[geometryType];
    if (!defined(geometryHandler)) {
      throw new RuntimeError(`Unknown geometry type: ${geometryType}`);
    }
    geometryHandler(dataSource, feature, feature.geometry, crsFunction, options);
  }

  function processFeatureCollection(
    dataSource,
    featureCollection,
    notUsed,
    crsFunction,
    options
  ) {
    const features = featureCollection.features;
    for (let i = 0, len = features.length; i < len; i++) {
      processFeature$1(dataSource, features[i], undefined, crsFunction, options);
    }
  }

  function processGeometryCollection(
    dataSource,
    geoJson,
    geometryCollection,
    crsFunction,
    options
  ) {
    const geometries = geometryCollection.geometries;
    for (let i = 0, len = geometries.length; i < len; i++) {
      const geometry = geometries[i];
      const geometryType = geometry.type;
      const geometryHandler = geometryTypes$1[geometryType];
      if (!defined(geometryHandler)) {
        throw new RuntimeError(`Unknown geometry type: ${geometryType}`);
      }
      geometryHandler(dataSource, geoJson, geometry, crsFunction, options);
    }
  }

  function createPoint$1(dataSource, geoJson, crsFunction, coordinates, options) {
    let symbol = options.markerSymbol;
    let color = options.markerColor;
    let size = options.markerSize;

    const properties = geoJson.properties;
    if (defined(properties)) {
      const cssColor = properties["marker-color"];
      if (defined(cssColor)) {
        color = Color.fromCssColorString(cssColor);
      }

      size = defaultValue(sizes[properties["marker-size"]], size);
      const markerSymbol = properties["marker-symbol"];
      if (defined(markerSymbol)) {
        symbol = markerSymbol;
      }
    }

    let canvasOrPromise;
    if (defined(symbol)) {
      if (symbol.length === 1) {
        canvasOrPromise = dataSource._pinBuilder.fromText(
          symbol.toUpperCase(),
          color,
          size
        );
      } else {
        canvasOrPromise = dataSource._pinBuilder.fromMakiIconId(
          symbol,
          color,
          size
        );
      }
    } else {
      canvasOrPromise = dataSource._pinBuilder.fromColor(color, size);
    }

    const billboard = new BillboardGraphics();
    billboard.verticalOrigin = new ConstantProperty(VerticalOrigin$1.BOTTOM);

    // Clamp to ground if there isn't a height specified
    if (coordinates.length === 2 && options.clampToGround) {
      billboard.heightReference = HeightReference$1.CLAMP_TO_GROUND;
    }

    const entity = createObject(
      geoJson,
      dataSource._entityCollection,
      options.describe
    );
    entity.billboard = billboard;
    entity.position = new ConstantPositionProperty(crsFunction(coordinates));

    const promise = Promise.resolve(canvasOrPromise)
      .then(function (image) {
        billboard.image = new ConstantProperty(image);
      })
      .catch(function () {
        billboard.image = new ConstantProperty(
          dataSource._pinBuilder.fromColor(color, size)
        );
      });

    dataSource._promises.push(promise);
  }

  function processPoint$1(dataSource, geoJson, geometry, crsFunction, options) {
    createPoint$1(dataSource, geoJson, crsFunction, geometry.coordinates, options);
  }

  function processMultiPoint(
    dataSource,
    geoJson,
    geometry,
    crsFunction,
    options
  ) {
    const coordinates = geometry.coordinates;
    for (let i = 0; i < coordinates.length; i++) {
      createPoint$1(dataSource, geoJson, crsFunction, coordinates[i], options);
    }
  }

  function createLineString$1(
    dataSource,
    geoJson,
    crsFunction,
    coordinates,
    options
  ) {
    let material = options.strokeMaterialProperty;
    let widthProperty = options.strokeWidthProperty;

    const properties = geoJson.properties;
    if (defined(properties)) {
      const width = properties["stroke-width"];
      if (defined(width)) {
        widthProperty = new ConstantProperty(width);
      }

      let color;
      const stroke = properties.stroke;
      if (defined(stroke)) {
        color = Color.fromCssColorString(stroke);
      }
      const opacity = properties["stroke-opacity"];
      if (defined(opacity) && opacity !== 1.0) {
        if (!defined(color)) {
          color = material.color.getValue().clone();
        }
        color.alpha = opacity;
      }
      if (defined(color)) {
        material = new ColorMaterialProperty(color);
      }
    }

    const entity = createObject(
      geoJson,
      dataSource._entityCollection,
      options.describe
    );
    const polylineGraphics = new PolylineGraphics();
    entity.polyline = polylineGraphics;

    polylineGraphics.clampToGround = options.clampToGround;
    polylineGraphics.material = material;
    polylineGraphics.width = widthProperty;
    polylineGraphics.positions = new ConstantProperty(
      coordinatesArrayToCartesianArray(coordinates, crsFunction)
    );
    polylineGraphics.arcType = ArcType$1.RHUMB;
  }

  function processLineString(
    dataSource,
    geoJson,
    geometry,
    crsFunction,
    options
  ) {
    createLineString$1(
      dataSource,
      geoJson,
      crsFunction,
      geometry.coordinates,
      options
    );
  }

  function processMultiLineString(
    dataSource,
    geoJson,
    geometry,
    crsFunction,
    options
  ) {
    const lineStrings = geometry.coordinates;
    for (let i = 0; i < lineStrings.length; i++) {
      createLineString$1(dataSource, geoJson, crsFunction, lineStrings[i], options);
    }
  }

  function createPolygon$1(dataSource, geoJson, crsFunction, coordinates, options) {
    if (coordinates.length === 0 || coordinates[0].length === 0) {
      return;
    }

    let outlineColorProperty = options.strokeMaterialProperty.color;
    let material = options.fillMaterialProperty;
    let widthProperty = options.strokeWidthProperty;

    const properties = geoJson.properties;
    if (defined(properties)) {
      const width = properties["stroke-width"];
      if (defined(width)) {
        widthProperty = new ConstantProperty(width);
      }

      let color;
      const stroke = properties.stroke;
      if (defined(stroke)) {
        color = Color.fromCssColorString(stroke);
      }
      let opacity = properties["stroke-opacity"];
      if (defined(opacity) && opacity !== 1.0) {
        if (!defined(color)) {
          color = outlineColorProperty.getValue().clone();
        }
        color.alpha = opacity;
      }

      if (defined(color)) {
        outlineColorProperty = new ConstantProperty(color);
      }

      let fillColor;
      const fill = properties.fill;
      const materialColor = material.color.getValue();
      if (defined(fill)) {
        fillColor = Color.fromCssColorString(fill);
        fillColor.alpha = materialColor.alpha;
      }
      opacity = properties["fill-opacity"];
      if (defined(opacity) && opacity !== materialColor.alpha) {
        if (!defined(fillColor)) {
          fillColor = materialColor.clone();
        }
        fillColor.alpha = opacity;
      }
      if (defined(fillColor)) {
        material = new ColorMaterialProperty(fillColor);
      }
    }

    const polygon = new PolygonGraphics();
    polygon.outline = new ConstantProperty(true);
    polygon.outlineColor = outlineColorProperty;
    polygon.outlineWidth = widthProperty;
    polygon.material = material;
    polygon.arcType = ArcType$1.RHUMB;

    const holes = [];
    for (let i = 1, len = coordinates.length; i < len; i++) {
      holes.push(
        new PolygonHierarchy(
          coordinatesArrayToCartesianArray(coordinates[i], crsFunction)
        )
      );
    }

    const positions = coordinates[0];
    polygon.hierarchy = new ConstantProperty(
      new PolygonHierarchy(
        coordinatesArrayToCartesianArray(positions, crsFunction),
        holes
      )
    );
    if (positions[0].length > 2) {
      polygon.perPositionHeight = new ConstantProperty(true);
    } else if (!options.clampToGround) {
      polygon.height = 0;
    }

    const entity = createObject(
      geoJson,
      dataSource._entityCollection,
      options.describe
    );
    entity.polygon = polygon;
  }

  function processPolygon$1(dataSource, geoJson, geometry, crsFunction, options) {
    createPolygon$1(
      dataSource,
      geoJson,
      crsFunction,
      geometry.coordinates,
      options
    );
  }

  function processMultiPolygon(
    dataSource,
    geoJson,
    geometry,
    crsFunction,
    options
  ) {
    const polygons = geometry.coordinates;
    for (let i = 0; i < polygons.length; i++) {
      createPolygon$1(dataSource, geoJson, crsFunction, polygons[i], options);
    }
  }

  function processTopology(dataSource, geoJson, geometry, crsFunction, options) {
    for (const property in geometry.objects) {
      if (geometry.objects.hasOwnProperty(property)) {
        const feature = index.feature(geometry, geometry.objects[property]);
        const typeHandler = geoJsonObjectTypes[feature.type];
        typeHandler(dataSource, feature, feature, crsFunction, options);
      }
    }
  }

  /**
   * @typedef {Object} GeoJsonDataSource.LoadOptions
   *
   * Initialization options for the <code>load</code> method.
   *
   * @property {String} [sourceUri] Overrides the url to use for resolving relative links.
   * @property {GeoJsonDataSource.describe} [describe=GeoJsonDataSource.defaultDescribeProperty] A function which returns a Property object (or just a string).
   * @property {Number} [markerSize=GeoJsonDataSource.markerSize] The default size of the map pin created for each point, in pixels.
   * @property {String} [markerSymbol=GeoJsonDataSource.markerSymbol] The default symbol of the map pin created for each point.
   * @property {Color} [markerColor=GeoJsonDataSource.markerColor] The default color of the map pin created for each point.
   * @property {Color} [stroke=GeoJsonDataSource.stroke] The default color of polylines and polygon outlines.
   * @property {Number} [strokeWidth=GeoJsonDataSource.strokeWidth] The default width of polylines and polygon outlines.
   * @property {Color} [fill=GeoJsonDataSource.fill] The default color for polygon interiors.
   * @property {Boolean} [clampToGround=GeoJsonDataSource.clampToGround] true if we want the geometry features (polygons or linestrings) clamped to the ground.
   * @property {Credit|String} [credit] A credit for the data source, which is displayed on the canvas.
   */

  /**
   * A {@link DataSource} which processes both
   * {@link http://www.geojson.org/|GeoJSON} and {@link https://github.com/mbostock/topojson|TopoJSON} data.
   * {@link https://github.com/mapbox/simplestyle-spec|simplestyle-spec} properties will also be used if they
   * are present.
   *
   * @alias GeoJsonDataSource
   * @constructor
   *
   * @param {String} [name] The name of this data source.  If undefined, a name will be taken from
   *                        the name of the GeoJSON file.
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=GeoJSON%20and%20TopoJSON.html|Cesium Sandcastle GeoJSON and TopoJSON Demo}
   * @demo {@link https://sandcastle.cesium.com/index.html?src=GeoJSON%20simplestyle.html|Cesium Sandcastle GeoJSON simplestyle Demo}
   *
   * @example
   * const viewer = new Cesium.Viewer('cesiumContainer');
   * viewer.dataSources.add(Cesium.GeoJsonDataSource.load('../../SampleData/ne_10m_us_states.topojson', {
   *   stroke: Cesium.Color.HOTPINK,
   *   fill: Cesium.Color.PINK,
   *   strokeWidth: 3,
   *   markerSymbol: '?'
   * }));
   */
  function GeoJsonDataSource(name) {
    this._name = name;
    this._changed = new Event();
    this._error = new Event();
    this._isLoading = false;
    this._loading = new Event();
    this._entityCollection = new EntityCollection(this);
    this._promises = [];
    this._pinBuilder = new PinBuilder();
    this._entityCluster = new EntityCluster();
    this._credit = undefined;
    this._resourceCredits = [];
  }

  /**
   * Creates a Promise to a new instance loaded with the provided GeoJSON or TopoJSON data.
   *
   * @param {Resource|String|Object} data A url, GeoJSON object, or TopoJSON object to be loaded.
   * @param {GeoJsonDataSource.LoadOptions} [options] An object specifying configuration options
   *
   * @returns {Promise.<GeoJsonDataSource>} A promise that will resolve when the data is loaded.
   */
  GeoJsonDataSource.load = function (data, options) {
    return new GeoJsonDataSource().load(data, options);
  };

  Object.defineProperties(GeoJsonDataSource, {
    /**
     * Gets or sets the default size of the map pin created for each point, in pixels.
     * @memberof GeoJsonDataSource
     * @type {Number}
     * @default 48
     */
    markerSize: {
      get: function () {
        return defaultMarkerSize;
      },
      set: function (value) {
        defaultMarkerSize = value;
      },
    },
    /**
     * Gets or sets the default symbol of the map pin created for each point.
     * This can be any valid {@link http://mapbox.com/maki/|Maki} identifier, any single character,
     * or blank if no symbol is to be used.
     * @memberof GeoJsonDataSource
     * @type {String}
     */
    markerSymbol: {
      get: function () {
        return defaultMarkerSymbol;
      },
      set: function (value) {
        defaultMarkerSymbol = value;
      },
    },
    /**
     * Gets or sets the default color of the map pin created for each point.
     * @memberof GeoJsonDataSource
     * @type {Color}
     * @default Color.ROYALBLUE
     */
    markerColor: {
      get: function () {
        return defaultMarkerColor;
      },
      set: function (value) {
        defaultMarkerColor = value;
      },
    },
    /**
     * Gets or sets the default color of polylines and polygon outlines.
     * @memberof GeoJsonDataSource
     * @type {Color}
     * @default Color.BLACK
     */
    stroke: {
      get: function () {
        return defaultStroke;
      },
      set: function (value) {
        defaultStroke = value;
      },
    },
    /**
     * Gets or sets the default width of polylines and polygon outlines.
     * @memberof GeoJsonDataSource
     * @type {Number}
     * @default 2.0
     */
    strokeWidth: {
      get: function () {
        return defaultStrokeWidth;
      },
      set: function (value) {
        defaultStrokeWidth = value;
      },
    },
    /**
     * Gets or sets default color for polygon interiors.
     * @memberof GeoJsonDataSource
     * @type {Color}
     * @default Color.YELLOW
     */
    fill: {
      get: function () {
        return defaultFill;
      },
      set: function (value) {
        defaultFill = value;
      },
    },
    /**
     * Gets or sets default of whether to clamp to the ground.
     * @memberof GeoJsonDataSource
     * @type {Boolean}
     * @default false
     */
    clampToGround: {
      get: function () {
        return defaultClampToGround;
      },
      set: function (value) {
        defaultClampToGround = value;
      },
    },

    /**
     * Gets an object that maps the name of a crs to a callback function which takes a GeoJSON coordinate
     * and transforms it into a WGS84 Earth-fixed Cartesian.  Older versions of GeoJSON which
     * supported the EPSG type can be added to this list as well, by specifying the complete EPSG name,
     * for example 'EPSG:4326'.
     * @memberof GeoJsonDataSource
     * @type {Object}
     */
    crsNames: {
      get: function () {
        return crsNames;
      },
    },

    /**
     * Gets an object that maps the href property of a crs link to a callback function
     * which takes the crs properties object and returns a Promise that resolves
     * to a function that takes a GeoJSON coordinate and transforms it into a WGS84 Earth-fixed Cartesian.
     * Items in this object take precedence over those defined in <code>crsLinkHrefs</code>, assuming
     * the link has a type specified.
     * @memberof GeoJsonDataSource
     * @type {Object}
     */
    crsLinkHrefs: {
      get: function () {
        return crsLinkHrefs;
      },
    },

    /**
     * Gets an object that maps the type property of a crs link to a callback function
     * which takes the crs properties object and returns a Promise that resolves
     * to a function that takes a GeoJSON coordinate and transforms it into a WGS84 Earth-fixed Cartesian.
     * Items in <code>crsLinkHrefs</code> take precedence over this object.
     * @memberof GeoJsonDataSource
     * @type {Object}
     */
    crsLinkTypes: {
      get: function () {
        return crsLinkTypes;
      },
    },
  });

  Object.defineProperties(GeoJsonDataSource.prototype, {
    /**
     * Gets or sets a human-readable name for this instance.
     * @memberof GeoJsonDataSource.prototype
     * @type {String}
     */
    name: {
      get: function () {
        return this._name;
      },
      set: function (value) {
        if (this._name !== value) {
          this._name = value;
          this._changed.raiseEvent(this);
        }
      },
    },
    /**
     * This DataSource only defines static data, therefore this property is always undefined.
     * @memberof GeoJsonDataSource.prototype
     * @type {DataSourceClock}
     */
    clock: {
      value: undefined,
      writable: false,
    },
    /**
     * Gets the collection of {@link Entity} instances.
     * @memberof GeoJsonDataSource.prototype
     * @type {EntityCollection}
     */
    entities: {
      get: function () {
        return this._entityCollection;
      },
    },
    /**
     * Gets a value indicating if the data source is currently loading data.
     * @memberof GeoJsonDataSource.prototype
     * @type {Boolean}
     */
    isLoading: {
      get: function () {
        return this._isLoading;
      },
    },
    /**
     * Gets an event that will be raised when the underlying data changes.
     * @memberof GeoJsonDataSource.prototype
     * @type {Event}
     */
    changedEvent: {
      get: function () {
        return this._changed;
      },
    },
    /**
     * Gets an event that will be raised if an error is encountered during processing.
     * @memberof GeoJsonDataSource.prototype
     * @type {Event}
     */
    errorEvent: {
      get: function () {
        return this._error;
      },
    },
    /**
     * Gets an event that will be raised when the data source either starts or stops loading.
     * @memberof GeoJsonDataSource.prototype
     * @type {Event}
     */
    loadingEvent: {
      get: function () {
        return this._loading;
      },
    },
    /**
     * Gets whether or not this data source should be displayed.
     * @memberof GeoJsonDataSource.prototype
     * @type {Boolean}
     */
    show: {
      get: function () {
        return this._entityCollection.show;
      },
      set: function (value) {
        this._entityCollection.show = value;
      },
    },

    /**
     * Gets or sets the clustering options for this data source. This object can be shared between multiple data sources.
     *
     * @memberof GeoJsonDataSource.prototype
     * @type {EntityCluster}
     */
    clustering: {
      get: function () {
        return this._entityCluster;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value must be defined.");
        }
        //>>includeEnd('debug');
        this._entityCluster = value;
      },
    },
    /**
     * Gets the credit that will be displayed for the data source
     * @memberof GeoJsonDataSource.prototype
     * @type {Credit}
     */
    credit: {
      get: function () {
        return this._credit;
      },
    },
  });

  /**
   * Asynchronously loads the provided GeoJSON or TopoJSON data, replacing any existing data.
   *
   * @param {Resource|String|Object} data A url, GeoJSON object, or TopoJSON object to be loaded.
   * @param {GeoJsonDataSource.LoadOptions} [options] An object specifying configuration options
   *
   * @returns {Promise.<GeoJsonDataSource>} a promise that will resolve when the GeoJSON is loaded.
   */
  GeoJsonDataSource.prototype.load = function (data, options) {
    return preload(this, data, options, true);
  };

  /**
   * Asynchronously loads the provided GeoJSON or TopoJSON data, without replacing any existing data.
   *
   * @param {Resource|String|Object} data A url, GeoJSON object, or TopoJSON object to be loaded.
   * @param {GeoJsonDataSource.LoadOptions} [options] An object specifying configuration options
   *
   * @returns {Promise.<GeoJsonDataSource>} a promise that will resolve when the GeoJSON is loaded.
   */
  GeoJsonDataSource.prototype.process = function (data, options) {
    return preload(this, data, options, false);
  };

  function preload(that, data, options, clear) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(data)) {
      throw new DeveloperError("data is required.");
    }
    //>>includeEnd('debug');

    DataSource.setLoading(that, true);
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    // User specified credit
    let credit = options.credit;
    if (typeof credit === "string") {
      credit = new Credit(credit);
    }
    that._credit = credit;

    let promise = data;
    let sourceUri = options.sourceUri;
    if (typeof data === "string" || data instanceof Resource) {
      data = Resource.createIfNeeded(data);
      promise = data.fetchJson();
      sourceUri = defaultValue(sourceUri, data.getUrlComponent());

      // Add resource credits to our list of credits to display
      const resourceCredits = that._resourceCredits;
      const credits = data.credits;
      if (defined(credits)) {
        const length = credits.length;
        for (let i = 0; i < length; i++) {
          resourceCredits.push(credits[i]);
        }
      }
    }

    options = {
      describe: defaultValue(options.describe, defaultDescribeProperty),
      markerSize: defaultValue(options.markerSize, defaultMarkerSize),
      markerSymbol: defaultValue(options.markerSymbol, defaultMarkerSymbol),
      markerColor: defaultValue(options.markerColor, defaultMarkerColor),
      strokeWidthProperty: new ConstantProperty(
        defaultValue(options.strokeWidth, defaultStrokeWidth)
      ),
      strokeMaterialProperty: new ColorMaterialProperty(
        defaultValue(options.stroke, defaultStroke)
      ),
      fillMaterialProperty: new ColorMaterialProperty(
        defaultValue(options.fill, defaultFill)
      ),
      clampToGround: defaultValue(options.clampToGround, defaultClampToGround),
    };

    return Promise.resolve(promise)
      .then(function (geoJson) {
        return load$2(that, geoJson, options, sourceUri, clear);
      })
      .catch(function (error) {
        DataSource.setLoading(that, false);
        that._error.raiseEvent(that, error);
        throw error;
      });
  }

  /**
   * Updates the data source to the provided time.  This function is optional and
   * is not required to be implemented.  It is provided for data sources which
   * retrieve data based on the current animation time or scene state.
   * If implemented, update will be called by {@link DataSourceDisplay} once a frame.
   *
   * @param {JulianDate} time The simulation time.
   * @returns {Boolean} True if this data source is ready to be displayed at the provided time, false otherwise.
   */
  GeoJsonDataSource.prototype.update = function (time) {
    return true;
  };

  function load$2(that, geoJson, options, sourceUri, clear) {
    let name;
    if (defined(sourceUri)) {
      name = getFilenameFromUri(sourceUri);
    }

    if (defined(name) && that._name !== name) {
      that._name = name;
      that._changed.raiseEvent(that);
    }

    const typeHandler = geoJsonObjectTypes[geoJson.type];
    if (!defined(typeHandler)) {
      throw new RuntimeError(`Unsupported GeoJSON object type: ${geoJson.type}`);
    }

    //Check for a Coordinate Reference System.
    const crs = geoJson.crs;
    let crsFunction = crs !== null ? defaultCrsFunction : null;

    if (defined(crs)) {
      if (!defined(crs.properties)) {
        throw new RuntimeError("crs.properties is undefined.");
      }

      const properties = crs.properties;
      if (crs.type === "name") {
        crsFunction = crsNames[properties.name];
        if (!defined(crsFunction)) {
          throw new RuntimeError(`Unknown crs name: ${properties.name}`);
        }
      } else if (crs.type === "link") {
        let handler = crsLinkHrefs[properties.href];
        if (!defined(handler)) {
          handler = crsLinkTypes[properties.type];
        }

        if (!defined(handler)) {
          throw new RuntimeError(
            `Unable to resolve crs link: ${JSON.stringify(properties)}`
          );
        }

        crsFunction = handler(properties);
      } else if (crs.type === "EPSG") {
        crsFunction = crsNames[`EPSG:${properties.code}`];
        if (!defined(crsFunction)) {
          throw new RuntimeError(`Unknown crs EPSG code: ${properties.code}`);
        }
      } else {
        throw new RuntimeError(`Unknown crs type: ${crs.type}`);
      }
    }

    return Promise.resolve(crsFunction).then(function (crsFunction) {
      if (clear) {
        that._entityCollection.removeAll();
      }

      // null is a valid value for the crs, but means the entire load process becomes a no-op
      // because we can't assume anything about the coordinates.
      if (crsFunction !== null) {
        typeHandler(that, geoJson, geoJson, crsFunction, options);
      }

      return Promise.all(that._promises).then(function () {
        that._promises.length = 0;
        DataSource.setLoading(that, false);
        return that;
      });
    });
  }

  /* This file is automatically rebuilt by the Cesium build process. */
  /**
   * Assigns (shallow copies) the properties of `src` onto `dest`, if the
   * corresponding property on `dest` === `undefined`.
   *
   * @param {Object} dest The destination object.
   * @param {Object} src The source object.
   * @return {Object} The destination object (`dest`)
   */
  function defaults(dest, src) {
      for (var prop in src) {
          if (src.hasOwnProperty(prop) && dest[prop] === undefined) {
              dest[prop] = src[prop];
          }
      }
      return dest;
  }
  /**
   * Truncates the `str` at `len - ellipsisChars.length`, and adds the `ellipsisChars` to the
   * end of the string (by default, two periods: '..'). If the `str` length does not exceed
   * `len`, the string will be returned unchanged.
   *
   * @param {String} str The string to truncate and add an ellipsis to.
   * @param {Number} truncateLen The length to truncate the string at.
   * @param {String} [ellipsisChars=...] The ellipsis character(s) to add to the end of `str`
   *   when truncated. Defaults to '...'
   */
  function ellipsis(str, truncateLen, ellipsisChars) {
      var ellipsisLength;
      if (str.length > truncateLen) {
          if (ellipsisChars == null) {
              ellipsisChars = '&hellip;';
              ellipsisLength = 3;
          }
          else {
              ellipsisLength = ellipsisChars.length;
          }
          str = str.substring(0, truncateLen - ellipsisLength) + ellipsisChars;
      }
      return str;
  }
  /**
   * Supports `Array.prototype.indexOf()` functionality for old IE (IE8 and below).
   *
   * @param {Array} arr The array to find an element of.
   * @param {*} element The element to find in the array, and return the index of.
   * @return {Number} The index of the `element`, or -1 if it was not found.
   */
  function indexOf(arr, element) {
      // @ts-ignore - As far as TypeScript is concerned, this method will always
      // exist (lowest "lib" in TS is "ES5"). Hence we need to ignore this error
      // to support IE8 which only implements ES3 and doesn't have this method
      if (Array.prototype.indexOf) {
          return arr.indexOf(element);
      }
      else {
          for (var i = 0, len = arr.length; i < len; i++) {
              if (arr[i] === element)
                  return i;
          }
          return -1;
      }
  }
  /**
   * Removes array elements based on a filtering function. Mutates the input
   * array.
   *
   * Using this instead of the ES5 Array.prototype.filter() function, to allow
   * Autolinker compatibility with IE8, and also to prevent creating many new
   * arrays in memory for filtering.
   *
   * @param {Array} arr The array to remove elements from. This array is
   *   mutated.
   * @param {Function} fn A function which should return `true` to
   *   remove an element.
   * @return {Array} The mutated input `arr`.
   */
  function remove$1(arr, fn) {
      for (var i = arr.length - 1; i >= 0; i--) {
          if (fn(arr[i]) === true) {
              arr.splice(i, 1);
          }
      }
  }
  /**
   * Performs the functionality of what modern browsers do when `String.prototype.split()` is called
   * with a regular expression that contains capturing parenthesis.
   *
   * For example:
   *
   *     // Modern browsers:
   *     "a,b,c".split( /(,)/ );  // --> [ 'a', ',', 'b', ',', 'c' ]
   *
   *     // Old IE (including IE8):
   *     "a,b,c".split( /(,)/ );  // --> [ 'a', 'b', 'c' ]
   *
   * This method emulates the functionality of modern browsers for the old IE case.
   *
   * @param {String} str The string to split.
   * @param {RegExp} splitRegex The regular expression to split the input `str` on. The splitting
   *   character(s) will be spliced into the array, as in the "modern browsers" example in the
   *   description of this method.
   *   Note #1: the supplied regular expression **must** have the 'g' flag specified.
   *   Note #2: for simplicity's sake, the regular expression does not need
   *   to contain capturing parenthesis - it will be assumed that any match has them.
   * @return {String[]} The split array of strings, with the splitting character(s) included.
   */
  function splitAndCapture(str, splitRegex) {
      if (!splitRegex.global)
          throw new Error("`splitRegex` must have the 'g' flag set");
      var result = [], lastIdx = 0, match;
      while (match = splitRegex.exec(str)) {
          result.push(str.substring(lastIdx, match.index));
          result.push(match[0]); // push the splitting char(s)
          lastIdx = match.index + match[0].length;
      }
      result.push(str.substring(lastIdx));
      return result;
  }
  /**
   * Function that should never be called but is used to check that every
   * enum value is handled using TypeScript's 'never' type.
   */
  function throwUnhandledCaseError(theValue) {
      throw new Error("Unhandled case for value: '".concat(theValue, "'"));
  }

  /**
   * @class Autolinker.HtmlTag
   * @extends Object
   *
   * Represents an HTML tag, which can be used to easily build/modify HTML tags programmatically.
   *
   * Autolinker uses this abstraction to create HTML tags, and then write them out as strings. You may also use
   * this class in your code, especially within a {@link Autolinker#replaceFn replaceFn}.
   *
   * ## Examples
   *
   * Example instantiation:
   *
   *     var tag = new Autolinker.HtmlTag( {
   *         tagName : 'a',
   *         attrs   : { 'href': 'http://google.com', 'class': 'external-link' },
   *         innerHtml : 'Google'
   *     } );
   *
   *     tag.toAnchorString();  // <a href="http://google.com" class="external-link">Google</a>
   *
   *     // Individual accessor methods
   *     tag.getTagName();                 // 'a'
   *     tag.getAttr( 'href' );            // 'http://google.com'
   *     tag.hasClass( 'external-link' );  // true
   *
   *
   * Using mutator methods (which may be used in combination with instantiation config properties):
   *
   *     var tag = new Autolinker.HtmlTag();
   *     tag.setTagName( 'a' );
   *     tag.setAttr( 'href', 'http://google.com' );
   *     tag.addClass( 'external-link' );
   *     tag.setInnerHtml( 'Google' );
   *
   *     tag.getTagName();                 // 'a'
   *     tag.getAttr( 'href' );            // 'http://google.com'
   *     tag.hasClass( 'external-link' );  // true
   *
   *     tag.toAnchorString();  // <a href="http://google.com" class="external-link">Google</a>
   *
   *
   * ## Example use within a {@link Autolinker#replaceFn replaceFn}
   *
   *     var html = Autolinker.link( "Test google.com", {
   *         replaceFn : function( match ) {
   *             var tag = match.buildTag();  // returns an {@link Autolinker.HtmlTag} instance, configured with the Match's href and anchor text
   *             tag.setAttr( 'rel', 'nofollow' );
   *
   *             return tag;
   *         }
   *     } );
   *
   *     // generated html:
   *     //   Test <a href="http://google.com" target="_blank" rel="nofollow">google.com</a>
   *
   *
   * ## Example use with a new tag for the replacement
   *
   *     var html = Autolinker.link( "Test google.com", {
   *         replaceFn : function( match ) {
   *             var tag = new Autolinker.HtmlTag( {
   *                 tagName : 'button',
   *                 attrs   : { 'title': 'Load URL: ' + match.getAnchorHref() },
   *                 innerHtml : 'Load URL: ' + match.getAnchorText()
   *             } );
   *
   *             return tag;
   *         }
   *     } );
   *
   *     // generated html:
   *     //   Test <button title="Load URL: http://google.com">Load URL: google.com</button>
   */
  var HtmlTag = /** @class */ (function () {
      /**
       * @method constructor
       * @param {Object} [cfg] The configuration properties for this class, in an Object (map)
       */
      function HtmlTag(cfg) {
          if (cfg === void 0) { cfg = {}; }
          /**
           * @cfg {String} tagName
           *
           * The tag name. Ex: 'a', 'button', etc.
           *
           * Not required at instantiation time, but should be set using {@link #setTagName} before {@link #toAnchorString}
           * is executed.
           */
          this.tagName = ''; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @cfg {Object.<String, String>} attrs
           *
           * An key/value Object (map) of attributes to create the tag with. The keys are the attribute names, and the
           * values are the attribute values.
           */
          this.attrs = {}; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @cfg {String} innerHTML
           *
           * The inner HTML for the tag.
           */
          this.innerHTML = ''; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @protected
           * @property {RegExp} whitespaceRegex
           *
           * Regular expression used to match whitespace in a string of CSS classes.
           */
          this.whitespaceRegex = /\s+/; // default value just to get the above doc comment in the ES5 output and documentation generator
          this.tagName = cfg.tagName || '';
          this.attrs = cfg.attrs || {};
          this.innerHTML = cfg.innerHtml || cfg.innerHTML || ''; // accept either the camelCased form or the fully capitalized acronym as in the DOM
      }
      /**
       * Sets the tag name that will be used to generate the tag with.
       *
       * @param {String} tagName
       * @return {Autolinker.HtmlTag} This HtmlTag instance, so that method calls may be chained.
       */
      HtmlTag.prototype.setTagName = function (tagName) {
          this.tagName = tagName;
          return this;
      };
      /**
       * Retrieves the tag name.
       *
       * @return {String}
       */
      HtmlTag.prototype.getTagName = function () {
          return this.tagName || '';
      };
      /**
       * Sets an attribute on the HtmlTag.
       *
       * @param {String} attrName The attribute name to set.
       * @param {String} attrValue The attribute value to set.
       * @return {Autolinker.HtmlTag} This HtmlTag instance, so that method calls may be chained.
       */
      HtmlTag.prototype.setAttr = function (attrName, attrValue) {
          var tagAttrs = this.getAttrs();
          tagAttrs[attrName] = attrValue;
          return this;
      };
      /**
       * Retrieves an attribute from the HtmlTag. If the attribute does not exist, returns `undefined`.
       *
       * @param {String} attrName The attribute name to retrieve.
       * @return {String} The attribute's value, or `undefined` if it does not exist on the HtmlTag.
       */
      HtmlTag.prototype.getAttr = function (attrName) {
          return this.getAttrs()[attrName];
      };
      /**
       * Sets one or more attributes on the HtmlTag.
       *
       * @param {Object.<String, String>} attrs A key/value Object (map) of the attributes to set.
       * @return {Autolinker.HtmlTag} This HtmlTag instance, so that method calls may be chained.
       */
      HtmlTag.prototype.setAttrs = function (attrs) {
          Object.assign(this.getAttrs(), attrs);
          return this;
      };
      /**
       * Retrieves the attributes Object (map) for the HtmlTag.
       *
       * @return {Object.<String, String>} A key/value object of the attributes for the HtmlTag.
       */
      HtmlTag.prototype.getAttrs = function () {
          return this.attrs || (this.attrs = {});
      };
      /**
       * Sets the provided `cssClass`, overwriting any current CSS classes on the HtmlTag.
       *
       * @param {String} cssClass One or more space-separated CSS classes to set (overwrite).
       * @return {Autolinker.HtmlTag} This HtmlTag instance, so that method calls may be chained.
       */
      HtmlTag.prototype.setClass = function (cssClass) {
          return this.setAttr('class', cssClass);
      };
      /**
       * Convenience method to add one or more CSS classes to the HtmlTag. Will not add duplicate CSS classes.
       *
       * @param {String} cssClass One or more space-separated CSS classes to add.
       * @return {Autolinker.HtmlTag} This HtmlTag instance, so that method calls may be chained.
       */
      HtmlTag.prototype.addClass = function (cssClass) {
          var classAttr = this.getClass(), whitespaceRegex = this.whitespaceRegex, classes = (!classAttr) ? [] : classAttr.split(whitespaceRegex), newClasses = cssClass.split(whitespaceRegex), newClass;
          while (newClass = newClasses.shift()) {
              if (indexOf(classes, newClass) === -1) {
                  classes.push(newClass);
              }
          }
          this.getAttrs()['class'] = classes.join(" ");
          return this;
      };
      /**
       * Convenience method to remove one or more CSS classes from the HtmlTag.
       *
       * @param {String} cssClass One or more space-separated CSS classes to remove.
       * @return {Autolinker.HtmlTag} This HtmlTag instance, so that method calls may be chained.
       */
      HtmlTag.prototype.removeClass = function (cssClass) {
          var classAttr = this.getClass(), whitespaceRegex = this.whitespaceRegex, classes = (!classAttr) ? [] : classAttr.split(whitespaceRegex), removeClasses = cssClass.split(whitespaceRegex), removeClass;
          while (classes.length && (removeClass = removeClasses.shift())) {
              var idx = indexOf(classes, removeClass);
              if (idx !== -1) {
                  classes.splice(idx, 1);
              }
          }
          this.getAttrs()['class'] = classes.join(" ");
          return this;
      };
      /**
       * Convenience method to retrieve the CSS class(es) for the HtmlTag, which will each be separated by spaces when
       * there are multiple.
       *
       * @return {String}
       */
      HtmlTag.prototype.getClass = function () {
          return this.getAttrs()['class'] || "";
      };
      /**
       * Convenience method to check if the tag has a CSS class or not.
       *
       * @param {String} cssClass The CSS class to check for.
       * @return {Boolean} `true` if the HtmlTag has the CSS class, `false` otherwise.
       */
      HtmlTag.prototype.hasClass = function (cssClass) {
          return (' ' + this.getClass() + ' ').indexOf(' ' + cssClass + ' ') !== -1;
      };
      /**
       * Sets the inner HTML for the tag.
       *
       * @param {String} html The inner HTML to set.
       * @return {Autolinker.HtmlTag} This HtmlTag instance, so that method calls may be chained.
       */
      HtmlTag.prototype.setInnerHTML = function (html) {
          this.innerHTML = html;
          return this;
      };
      /**
       * Backwards compatibility method name.
       *
       * @param {String} html The inner HTML to set.
       * @return {Autolinker.HtmlTag} This HtmlTag instance, so that method calls may be chained.
       */
      HtmlTag.prototype.setInnerHtml = function (html) {
          return this.setInnerHTML(html);
      };
      /**
       * Retrieves the inner HTML for the tag.
       *
       * @return {String}
       */
      HtmlTag.prototype.getInnerHTML = function () {
          return this.innerHTML || "";
      };
      /**
       * Backward compatibility method name.
       *
       * @return {String}
       */
      HtmlTag.prototype.getInnerHtml = function () {
          return this.getInnerHTML();
      };
      /**
       * Override of superclass method used to generate the HTML string for the tag.
       *
       * @return {String}
       */
      HtmlTag.prototype.toAnchorString = function () {
          var tagName = this.getTagName(), attrsStr = this.buildAttrsStr();
          attrsStr = (attrsStr) ? ' ' + attrsStr : ''; // prepend a space if there are actually attributes
          return ['<', tagName, attrsStr, '>', this.getInnerHtml(), '</', tagName, '>'].join("");
      };
      /**
       * Support method for {@link #toAnchorString}, returns the string space-separated key="value" pairs, used to populate
       * the stringified HtmlTag.
       *
       * @protected
       * @return {String} Example return: `attr1="value1" attr2="value2"`
       */
      HtmlTag.prototype.buildAttrsStr = function () {
          if (!this.attrs)
              return ""; // no `attrs` Object (map) has been set, return empty string
          var attrs = this.getAttrs(), attrsArr = [];
          for (var prop in attrs) {
              if (attrs.hasOwnProperty(prop)) {
                  attrsArr.push(prop + '="' + attrs[prop] + '"');
              }
          }
          return attrsArr.join(" ");
      };
      return HtmlTag;
  }());

  /**
   * Date: 2015-10-05
   * Author: Kasper Søfren <soefritz@gmail.com> (https://github.com/kafoso)
   *
   * A truncation feature, where the ellipsis will be placed at a section within
   * the URL making it still somewhat human readable.
   *
   * @param {String} url						 A URL.
   * @param {Number} truncateLen		 The maximum length of the truncated output URL string.
   * @param {String} ellipsisChars	 The characters to place within the url, e.g. "...".
   * @return {String} The truncated URL.
   */
  function truncateSmart(url, truncateLen, ellipsisChars) {
      var ellipsisLengthBeforeParsing;
      var ellipsisLength;
      if (ellipsisChars == null) {
          ellipsisChars = '&hellip;';
          ellipsisLength = 3;
          ellipsisLengthBeforeParsing = 8;
      }
      else {
          ellipsisLength = ellipsisChars.length;
          ellipsisLengthBeforeParsing = ellipsisChars.length;
      }
      var parse_url = function (url) {
          var urlObj = {};
          var urlSub = url;
          var match = urlSub.match(/^([a-z]+):\/\//i);
          if (match) {
              urlObj.scheme = match[1];
              urlSub = urlSub.substr(match[0].length);
          }
          match = urlSub.match(/^(.*?)(?=(\?|#|\/|$))/i);
          if (match) {
              urlObj.host = match[1];
              urlSub = urlSub.substr(match[0].length);
          }
          match = urlSub.match(/^\/(.*?)(?=(\?|#|$))/i);
          if (match) {
              urlObj.path = match[1];
              urlSub = urlSub.substr(match[0].length);
          }
          match = urlSub.match(/^\?(.*?)(?=(#|$))/i);
          if (match) {
              urlObj.query = match[1];
              urlSub = urlSub.substr(match[0].length);
          }
          match = urlSub.match(/^#(.*?)$/i);
          if (match) {
              urlObj.fragment = match[1];
              //urlSub = urlSub.substr(match[0].length);  -- not used. Uncomment if adding another block.
          }
          return urlObj;
      };
      var buildUrl = function (urlObj) {
          var url = "";
          if (urlObj.scheme && urlObj.host) {
              url += urlObj.scheme + "://";
          }
          if (urlObj.host) {
              url += urlObj.host;
          }
          if (urlObj.path) {
              url += "/" + urlObj.path;
          }
          if (urlObj.query) {
              url += "?" + urlObj.query;
          }
          if (urlObj.fragment) {
              url += "#" + urlObj.fragment;
          }
          return url;
      };
      var buildSegment = function (segment, remainingAvailableLength) {
          var remainingAvailableLengthHalf = remainingAvailableLength / 2, startOffset = Math.ceil(remainingAvailableLengthHalf), endOffset = (-1) * Math.floor(remainingAvailableLengthHalf), end = "";
          if (endOffset < 0) {
              end = segment.substr(endOffset);
          }
          return segment.substr(0, startOffset) + ellipsisChars + end;
      };
      if (url.length <= truncateLen) {
          return url;
      }
      var availableLength = truncateLen - ellipsisLength;
      var urlObj = parse_url(url);
      // Clean up the URL
      if (urlObj.query) {
          var matchQuery = urlObj.query.match(/^(.*?)(?=(\?|\#))(.*?)$/i);
          if (matchQuery) {
              // Malformed URL; two or more "?". Removed any content behind the 2nd.
              urlObj.query = urlObj.query.substr(0, matchQuery[1].length);
              url = buildUrl(urlObj);
          }
      }
      if (url.length <= truncateLen) {
          return url;
      }
      if (urlObj.host) {
          urlObj.host = urlObj.host.replace(/^www\./, "");
          url = buildUrl(urlObj);
      }
      if (url.length <= truncateLen) {
          return url;
      }
      // Process and build the URL
      var str = "";
      if (urlObj.host) {
          str += urlObj.host;
      }
      if (str.length >= availableLength) {
          if (urlObj.host.length == truncateLen) {
              return (urlObj.host.substr(0, (truncateLen - ellipsisLength)) + ellipsisChars).substr(0, availableLength + ellipsisLengthBeforeParsing);
          }
          return buildSegment(str, availableLength).substr(0, availableLength + ellipsisLengthBeforeParsing);
      }
      var pathAndQuery = "";
      if (urlObj.path) {
          pathAndQuery += "/" + urlObj.path;
      }
      if (urlObj.query) {
          pathAndQuery += "?" + urlObj.query;
      }
      if (pathAndQuery) {
          if ((str + pathAndQuery).length >= availableLength) {
              if ((str + pathAndQuery).length == truncateLen) {
                  return (str + pathAndQuery).substr(0, truncateLen);
              }
              var remainingAvailableLength = availableLength - str.length;
              return (str + buildSegment(pathAndQuery, remainingAvailableLength)).substr(0, availableLength + ellipsisLengthBeforeParsing);
          }
          else {
              str += pathAndQuery;
          }
      }
      if (urlObj.fragment) {
          var fragment = "#" + urlObj.fragment;
          if ((str + fragment).length >= availableLength) {
              if ((str + fragment).length == truncateLen) {
                  return (str + fragment).substr(0, truncateLen);
              }
              var remainingAvailableLength2 = availableLength - str.length;
              return (str + buildSegment(fragment, remainingAvailableLength2)).substr(0, availableLength + ellipsisLengthBeforeParsing);
          }
          else {
              str += fragment;
          }
      }
      if (urlObj.scheme && urlObj.host) {
          var scheme = urlObj.scheme + "://";
          if ((str + scheme).length < availableLength) {
              return (scheme + str).substr(0, truncateLen);
          }
      }
      if (str.length <= truncateLen) {
          return str;
      }
      var end = "";
      if (availableLength > 0) {
          end = str.substr((-1) * Math.floor(availableLength / 2));
      }
      return (str.substr(0, Math.ceil(availableLength / 2)) + ellipsisChars + end).substr(0, availableLength + ellipsisLengthBeforeParsing);
  }

  /**
   * Date: 2015-10-05
   * Author: Kasper Søfren <soefritz@gmail.com> (https://github.com/kafoso)
   *
   * A truncation feature, where the ellipsis will be placed in the dead-center of the URL.
   *
   * @param {String} url             A URL.
   * @param {Number} truncateLen     The maximum length of the truncated output URL string.
   * @param {String} ellipsisChars   The characters to place within the url, e.g. "..".
   * @return {String} The truncated URL.
   */
  function truncateMiddle(url, truncateLen, ellipsisChars) {
      if (url.length <= truncateLen) {
          return url;
      }
      var ellipsisLengthBeforeParsing;
      var ellipsisLength;
      if (ellipsisChars == null) {
          ellipsisChars = '&hellip;';
          ellipsisLengthBeforeParsing = 8;
          ellipsisLength = 3;
      }
      else {
          ellipsisLengthBeforeParsing = ellipsisChars.length;
          ellipsisLength = ellipsisChars.length;
      }
      var availableLength = truncateLen - ellipsisLength;
      var end = "";
      if (availableLength > 0) {
          end = url.substr((-1) * Math.floor(availableLength / 2));
      }
      return (url.substr(0, Math.ceil(availableLength / 2)) + ellipsisChars + end).substr(0, availableLength + ellipsisLengthBeforeParsing);
  }

  /**
   * A truncation feature where the ellipsis will be placed at the end of the URL.
   *
   * @param {String} anchorText
   * @param {Number} truncateLen The maximum length of the truncated output URL string.
   * @param {String} ellipsisChars The characters to place within the url, e.g. "..".
   * @return {String} The truncated URL.
   */
  function truncateEnd(anchorText, truncateLen, ellipsisChars) {
      return ellipsis(anchorText, truncateLen, ellipsisChars);
  }

  /**
   * @protected
   * @class Autolinker.AnchorTagBuilder
   * @extends Object
   *
   * Builds anchor (&lt;a&gt;) tags for the Autolinker utility when a match is
   * found.
   *
   * Normally this class is instantiated, configured, and used internally by an
   * {@link Autolinker} instance, but may actually be used indirectly in a
   * {@link Autolinker#replaceFn replaceFn} to create {@link Autolinker.HtmlTag HtmlTag}
   * instances which may be modified before returning from the
   * {@link Autolinker#replaceFn replaceFn}. For example:
   *
   *     var html = Autolinker.link( "Test google.com", {
   *         replaceFn : function( match ) {
   *             var tag = match.buildTag();  // returns an {@link Autolinker.HtmlTag} instance
   *             tag.setAttr( 'rel', 'nofollow' );
   *
   *             return tag;
   *         }
   *     } );
   *
   *     // generated html:
   *     //   Test <a href="http://google.com" target="_blank" rel="nofollow">google.com</a>
   */
  var AnchorTagBuilder = /** @class */ (function () {
      /**
       * @method constructor
       * @param {Object} [cfg] The configuration options for the AnchorTagBuilder instance, specified in an Object (map).
       */
      function AnchorTagBuilder(cfg) {
          if (cfg === void 0) { cfg = {}; }
          /**
           * @cfg {Boolean} newWindow
           * @inheritdoc Autolinker#newWindow
           */
          this.newWindow = false; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @cfg {Object} truncate
           * @inheritdoc Autolinker#truncate
           */
          this.truncate = {}; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @cfg {String} className
           * @inheritdoc Autolinker#className
           */
          this.className = ''; // default value just to get the above doc comment in the ES5 output and documentation generator
          this.newWindow = cfg.newWindow || false;
          this.truncate = cfg.truncate || {};
          this.className = cfg.className || '';
      }
      /**
       * Generates the actual anchor (&lt;a&gt;) tag to use in place of the
       * matched text, via its `match` object.
       *
       * @param {Autolinker.match.Match} match The Match instance to generate an
       *   anchor tag from.
       * @return {Autolinker.HtmlTag} The HtmlTag instance for the anchor tag.
       */
      AnchorTagBuilder.prototype.build = function (match) {
          return new HtmlTag({
              tagName: 'a',
              attrs: this.createAttrs(match),
              innerHtml: this.processAnchorText(match.getAnchorText())
          });
      };
      /**
       * Creates the Object (map) of the HTML attributes for the anchor (&lt;a&gt;)
       *   tag being generated.
       *
       * @protected
       * @param {Autolinker.match.Match} match The Match instance to generate an
       *   anchor tag from.
       * @return {Object} A key/value Object (map) of the anchor tag's attributes.
       */
      AnchorTagBuilder.prototype.createAttrs = function (match) {
          var attrs = {
              'href': match.getAnchorHref() // we'll always have the `href` attribute
          };
          var cssClass = this.createCssClass(match);
          if (cssClass) {
              attrs['class'] = cssClass;
          }
          if (this.newWindow) {
              attrs['target'] = "_blank";
              attrs['rel'] = "noopener noreferrer"; // Issue #149. See https://mathiasbynens.github.io/rel-noopener/
          }
          if (this.truncate) {
              if (this.truncate.length && this.truncate.length < match.getAnchorText().length) {
                  attrs['title'] = match.getAnchorHref();
              }
          }
          return attrs;
      };
      /**
       * Creates the CSS class that will be used for a given anchor tag, based on
       * the `matchType` and the {@link #className} config.
       *
       * Example returns:
       *
       * - ""                                      // no {@link #className}
       * - "myLink myLink-url"                     // url match
       * - "myLink myLink-email"                   // email match
       * - "myLink myLink-phone"                   // phone match
       * - "myLink myLink-hashtag"                 // hashtag match
       * - "myLink myLink-mention myLink-twitter"  // mention match with Twitter service
       *
       * @protected
       * @param {Autolinker.match.Match} match The Match instance to generate an
       *   anchor tag from.
       * @return {String} The CSS class string for the link. Example return:
       *   "myLink myLink-url". If no {@link #className} was configured, returns
       *   an empty string.
       */
      AnchorTagBuilder.prototype.createCssClass = function (match) {
          var className = this.className;
          if (!className) {
              return "";
          }
          else {
              var returnClasses = [className], cssClassSuffixes = match.getCssClassSuffixes();
              for (var i = 0, len = cssClassSuffixes.length; i < len; i++) {
                  returnClasses.push(className + '-' + cssClassSuffixes[i]);
              }
              return returnClasses.join(' ');
          }
      };
      /**
       * Processes the `anchorText` by truncating the text according to the
       * {@link #truncate} config.
       *
       * @private
       * @param {String} anchorText The anchor tag's text (i.e. what will be
       *   displayed).
       * @return {String} The processed `anchorText`.
       */
      AnchorTagBuilder.prototype.processAnchorText = function (anchorText) {
          anchorText = this.doTruncate(anchorText);
          return anchorText;
      };
      /**
       * Performs the truncation of the `anchorText` based on the {@link #truncate}
       * option. If the `anchorText` is longer than the length specified by the
       * {@link #truncate} option, the truncation is performed based on the
       * `location` property. See {@link #truncate} for details.
       *
       * @private
       * @param {String} anchorText The anchor tag's text (i.e. what will be
       *   displayed).
       * @return {String} The truncated anchor text.
       */
      AnchorTagBuilder.prototype.doTruncate = function (anchorText) {
          var truncate = this.truncate;
          if (!truncate || !truncate.length)
              return anchorText;
          var truncateLength = truncate.length, truncateLocation = truncate.location;
          if (truncateLocation === 'smart') {
              return truncateSmart(anchorText, truncateLength);
          }
          else if (truncateLocation === 'middle') {
              return truncateMiddle(anchorText, truncateLength);
          }
          else {
              return truncateEnd(anchorText, truncateLength);
          }
      };
      return AnchorTagBuilder;
  }());

  /**
   * @abstract
   * @class Autolinker.match.Match
   *
   * Represents a match found in an input string which should be Autolinked. A Match object is what is provided in a
   * {@link Autolinker#replaceFn replaceFn}, and may be used to query for details about the match.
   *
   * For example:
   *
   *     var input = "...";  // string with URLs, Email Addresses, and Mentions (Twitter, Instagram, Soundcloud)
   *
   *     var linkedText = Autolinker.link( input, {
   *         replaceFn : function( match ) {
   *             console.log( "href = ", match.getAnchorHref() );
   *             console.log( "text = ", match.getAnchorText() );
   *
   *             switch( match.getType() ) {
   *                 case 'url' :
   *                     console.log( "url: ", match.getUrl() );
   *
   *                 case 'email' :
   *                     console.log( "email: ", match.getEmail() );
   *
   *                 case 'mention' :
   *                     console.log( "mention: ", match.getMention() );
   *             }
   *         }
   *     } );
   *
   * See the {@link Autolinker} class for more details on using the {@link Autolinker#replaceFn replaceFn}.
   */
  var Match = /** @class */ (function () {
      /**
       * @member Autolinker.match.Match
       * @method constructor
       * @param {Object} cfg The configuration properties for the Match
       *   instance, specified in an Object (map).
       */
      function Match(cfg) {
          /**
           * @cfg {Autolinker.AnchorTagBuilder} tagBuilder (required)
           *
           * Reference to the AnchorTagBuilder instance to use to generate an anchor
           * tag for the Match.
           */
          this.__jsduckDummyDocProp = null; // property used just to get the above doc comment into the ES5 output and documentation generator
          /**
           * @cfg {String} matchedText (required)
           *
           * The original text that was matched by the {@link Autolinker.matcher.Matcher}.
           */
          this.matchedText = ''; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @cfg {Number} offset (required)
           *
           * The offset of where the match was made in the input string.
           */
          this.offset = 0; // default value just to get the above doc comment in the ES5 output and documentation generator
          this.tagBuilder = cfg.tagBuilder;
          this.matchedText = cfg.matchedText;
          this.offset = cfg.offset;
      }
      /**
       * Returns the original text that was matched.
       *
       * @return {String}
       */
      Match.prototype.getMatchedText = function () {
          return this.matchedText;
      };
      /**
       * Sets the {@link #offset} of where the match was made in the input string.
       *
       * A {@link Autolinker.matcher.Matcher} will be fed only HTML text nodes,
       * and will therefore set an original offset that is relative to the HTML
       * text node itself. However, we want this offset to be relative to the full
       * HTML input string, and thus if using {@link Autolinker#parse} (rather
       * than calling a {@link Autolinker.matcher.Matcher} directly), then this
       * offset is corrected after the Matcher itself has done its job.
       *
       * @param {Number} offset
       */
      Match.prototype.setOffset = function (offset) {
          this.offset = offset;
      };
      /**
       * Returns the offset of where the match was made in the input string. This
       * is the 0-based index of the match.
       *
       * @return {Number}
       */
      Match.prototype.getOffset = function () {
          return this.offset;
      };
      /**
       * Returns the CSS class suffix(es) for this match.
       *
       * A CSS class suffix is appended to the {@link Autolinker#className} in
       * the {@link Autolinker.AnchorTagBuilder} when a match is translated into
       * an anchor tag.
       *
       * For example, if {@link Autolinker#className} was configured as 'myLink',
       * and this method returns `[ 'url' ]`, the final class name of the element
       * will become: 'myLink myLink-url'.
       *
       * The match may provide multiple CSS class suffixes to be appended to the
       * {@link Autolinker#className} in order to facilitate better styling
       * options for different match criteria. See {@link Autolinker.match.Mention}
       * for an example.
       *
       * By default, this method returns a single array with the match's
       * {@link #getType type} name, but may be overridden by subclasses.
       *
       * @return {String[]}
       */
      Match.prototype.getCssClassSuffixes = function () {
          return [this.getType()];
      };
      /**
       * Builds and returns an {@link Autolinker.HtmlTag} instance based on the
       * Match.
       *
       * This can be used to easily generate anchor tags from matches, and either
       * return their HTML string, or modify them before doing so.
       *
       * Example Usage:
       *
       *     var tag = match.buildTag();
       *     tag.addClass( 'cordova-link' );
       *     tag.setAttr( 'target', '_system' );
       *
       *     tag.toAnchorString();  // <a href="http://google.com" class="cordova-link" target="_system">Google</a>
       *
       * Example Usage in {@link Autolinker#replaceFn}:
       *
       *     var html = Autolinker.link( "Test google.com", {
       *         replaceFn : function( match ) {
       *             var tag = match.buildTag();  // returns an {@link Autolinker.HtmlTag} instance
       *             tag.setAttr( 'rel', 'nofollow' );
       *
       *             return tag;
       *         }
       *     } );
       *
       *     // generated html:
       *     //   Test <a href="http://google.com" target="_blank" rel="nofollow">google.com</a>
       */
      Match.prototype.buildTag = function () {
          return this.tagBuilder.build(this);
      };
      return Match;
  }());

  /******************************************************************************
  Copyright (c) Microsoft Corporation.

  Permission to use, copy, modify, and/or distribute this software for any
  purpose with or without fee is hereby granted.

  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  PERFORMANCE OF THIS SOFTWARE.
  ***************************************************************************** */
  /* global Reflect, Promise */

  var extendStatics = function(d, b) {
      extendStatics = Object.setPrototypeOf ||
          ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
          function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
      return extendStatics(d, b);
  };

  function __extends(d, b) {
      if (typeof b !== "function" && b !== null)
          throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
      extendStatics(d, b);
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  }

  var __assign = function() {
      __assign = Object.assign || function __assign(t) {
          for (var s, i = 1, n = arguments.length; i < n; i++) {
              s = arguments[i];
              for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
          }
          return t;
      };
      return __assign.apply(this, arguments);
  };

  /**
   * @class Autolinker.match.Email
   * @extends Autolinker.match.Match
   *
   * Represents a Email match found in an input string which should be Autolinked.
   *
   * See this class's superclass ({@link Autolinker.match.Match}) for more details.
   */
  var EmailMatch = /** @class */ (function (_super) {
      __extends(EmailMatch, _super);
      /**
       * @method constructor
       * @param {Object} cfg The configuration properties for the Match
       *   instance, specified in an Object (map).
       */
      function EmailMatch(cfg) {
          var _this = _super.call(this, cfg) || this;
          /**
           * @cfg {String} email (required)
           *
           * The email address that was matched.
           */
          _this.email = ''; // default value just to get the above doc comment in the ES5 output and documentation generator
          _this.email = cfg.email;
          return _this;
      }
      /**
       * Returns a string name for the type of match that this class represents.
       * For the case of EmailMatch, returns 'email'.
       *
       * @return {String}
       */
      EmailMatch.prototype.getType = function () {
          return 'email';
      };
      /**
       * Returns the email address that was matched.
       *
       * @return {String}
       */
      EmailMatch.prototype.getEmail = function () {
          return this.email;
      };
      /**
       * Returns the anchor href that should be generated for the match.
       *
       * @return {String}
       */
      EmailMatch.prototype.getAnchorHref = function () {
          return 'mailto:' + this.email;
      };
      /**
       * Returns the anchor text that should be generated for the match.
       *
       * @return {String}
       */
      EmailMatch.prototype.getAnchorText = function () {
          return this.email;
      };
      return EmailMatch;
  }(Match));

  /**
   * @class Autolinker.match.Hashtag
   * @extends Autolinker.match.Match
   *
   * Represents a Hashtag match found in an input string which should be
   * Autolinked.
   *
   * See this class's superclass ({@link Autolinker.match.Match}) for more
   * details.
   */
  var HashtagMatch = /** @class */ (function (_super) {
      __extends(HashtagMatch, _super);
      /**
       * @method constructor
       * @param {Object} cfg The configuration properties for the Match
       *   instance, specified in an Object (map).
       */
      function HashtagMatch(cfg) {
          var _this = _super.call(this, cfg) || this;
          /**
           * @cfg {String} serviceName
           *
           * The service to point hashtag matches to. See {@link Autolinker#hashtag}
           * for available values.
           */
          _this.serviceName = ''; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @cfg {String} hashtag (required)
           *
           * The HashtagMatch that was matched, without the '#'.
           */
          _this.hashtag = ''; // default value just to get the above doc comment in the ES5 output and documentation generator
          _this.serviceName = cfg.serviceName;
          _this.hashtag = cfg.hashtag;
          return _this;
      }
      /**
       * Returns a string name for the type of match that this class represents.
       * For the case of HashtagMatch, returns 'hashtag'.
       *
       * @return {String}
       */
      HashtagMatch.prototype.getType = function () {
          return 'hashtag';
      };
      /**
       * Returns the configured {@link #serviceName} to point the HashtagMatch to.
       * Ex: 'facebook', 'twitter'.
       *
       * @return {String}
       */
      HashtagMatch.prototype.getServiceName = function () {
          return this.serviceName;
      };
      /**
       * Returns the matched hashtag, without the '#' character.
       *
       * @return {String}
       */
      HashtagMatch.prototype.getHashtag = function () {
          return this.hashtag;
      };
      /**
       * Returns the anchor href that should be generated for the match.
       *
       * @return {String}
       */
      HashtagMatch.prototype.getAnchorHref = function () {
          var serviceName = this.serviceName, hashtag = this.hashtag;
          switch (serviceName) {
              case 'twitter':
                  return 'https://twitter.com/hashtag/' + hashtag;
              case 'facebook':
                  return 'https://www.facebook.com/hashtag/' + hashtag;
              case 'instagram':
                  return 'https://instagram.com/explore/tags/' + hashtag;
              case 'tiktok':
                  return 'https://www.tiktok.com/tag/' + hashtag;
              default: // Shouldn't happen because Autolinker's constructor should block any invalid values, but just in case.
                  throw new Error('Unknown service name to point hashtag to: ' + serviceName);
          }
      };
      /**
       * Returns the anchor text that should be generated for the match.
       *
       * @return {String}
       */
      HashtagMatch.prototype.getAnchorText = function () {
          return '#' + this.hashtag;
      };
      return HashtagMatch;
  }(Match));

  /**
   * @class Autolinker.match.Mention
   * @extends Autolinker.match.Match
   *
   * Represents a Mention match found in an input string which should be Autolinked.
   *
   * See this class's superclass ({@link Autolinker.match.Match}) for more details.
   */
  var MentionMatch = /** @class */ (function (_super) {
      __extends(MentionMatch, _super);
      /**
       * @method constructor
       * @param {Object} cfg The configuration properties for the Match
       *   instance, specified in an Object (map).
       */
      function MentionMatch(cfg) {
          var _this = _super.call(this, cfg) || this;
          /**
           * @cfg {String} serviceName
           *
           * The service to point mention matches to. See {@link Autolinker#mention}
           * for available values.
           */
          _this.serviceName = 'twitter'; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @cfg {String} mention (required)
           *
           * The Mention that was matched, without the '@' character.
           */
          _this.mention = ''; // default value just to get the above doc comment in the ES5 output and documentation generator
          _this.mention = cfg.mention;
          _this.serviceName = cfg.serviceName;
          return _this;
      }
      /**
       * Returns a string name for the type of match that this class represents.
       * For the case of MentionMatch, returns 'mention'.
       *
       * @return {String}
       */
      MentionMatch.prototype.getType = function () {
          return 'mention';
      };
      /**
       * Returns the mention, without the '@' character.
       *
       * @return {String}
       */
      MentionMatch.prototype.getMention = function () {
          return this.mention;
      };
      /**
       * Returns the configured {@link #serviceName} to point the mention to.
       * Ex: 'instagram', 'twitter', 'soundcloud'.
       *
       * @return {String}
       */
      MentionMatch.prototype.getServiceName = function () {
          return this.serviceName;
      };
      /**
       * Returns the anchor href that should be generated for the match.
       *
       * @return {String}
       */
      MentionMatch.prototype.getAnchorHref = function () {
          switch (this.serviceName) {
              case 'twitter':
                  return 'https://twitter.com/' + this.mention;
              case 'instagram':
                  return 'https://instagram.com/' + this.mention;
              case 'soundcloud':
                  return 'https://soundcloud.com/' + this.mention;
              case 'tiktok':
                  return 'https://www.tiktok.com/@' + this.mention;
              default: // Shouldn't happen because Autolinker's constructor should block any invalid values, but just in case.
                  throw new Error('Unknown service name to point mention to: ' + this.serviceName);
          }
      };
      /**
       * Returns the anchor text that should be generated for the match.
       *
       * @return {String}
       */
      MentionMatch.prototype.getAnchorText = function () {
          return '@' + this.mention;
      };
      /**
       * Returns the CSS class suffixes that should be used on a tag built with
       * the match. See {@link Autolinker.match.Match#getCssClassSuffixes} for
       * details.
       *
       * @return {String[]}
       */
      MentionMatch.prototype.getCssClassSuffixes = function () {
          var cssClassSuffixes = _super.prototype.getCssClassSuffixes.call(this), serviceName = this.getServiceName();
          if (serviceName) {
              cssClassSuffixes.push(serviceName);
          }
          return cssClassSuffixes;
      };
      return MentionMatch;
  }(Match));

  /**
   * @class Autolinker.match.Phone
   * @extends Autolinker.match.Match
   *
   * Represents a Phone number match found in an input string which should be
   * Autolinked.
   *
   * See this class's superclass ({@link Autolinker.match.Match}) for more
   * details.
   */
  var PhoneMatch = /** @class */ (function (_super) {
      __extends(PhoneMatch, _super);
      /**
       * @method constructor
       * @param {Object} cfg The configuration properties for the Match
       *   instance, specified in an Object (map).
       */
      function PhoneMatch(cfg) {
          var _this = _super.call(this, cfg) || this;
          /**
           * @protected
           * @property {String} number (required)
           *
           * The phone number that was matched, without any delimiter characters.
           *
           * Note: This is a string to allow for prefixed 0's.
           */
          _this.number = ''; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @protected
           * @property  {Boolean} plusSign (required)
           *
           * `true` if the matched phone number started with a '+' sign. We'll include
           * it in the `tel:` URL if so, as this is needed for international numbers.
           *
           * Ex: '+1 (123) 456 7879'
           */
          _this.plusSign = false; // default value just to get the above doc comment in the ES5 output and documentation generator
          _this.number = cfg.number;
          _this.plusSign = cfg.plusSign;
          return _this;
      }
      /**
       * Returns a string name for the type of match that this class represents.
       * For the case of PhoneMatch, returns 'phone'.
       *
       * @return {String}
       */
      PhoneMatch.prototype.getType = function () {
          return 'phone';
      };
      /**
       * Returns the phone number that was matched as a string, without any
       * delimiter characters.
       *
       * Note: This is a string to allow for prefixed 0's.
       *
       * @return {String}
       */
      PhoneMatch.prototype.getPhoneNumber = function () {
          return this.number;
      };
      /**
       * Alias of {@link #getPhoneNumber}, returns the phone number that was
       * matched as a string, without any delimiter characters.
       *
       * Note: This is a string to allow for prefixed 0's.
       *
       * @return {String}
       */
      PhoneMatch.prototype.getNumber = function () {
          return this.getPhoneNumber();
      };
      /**
       * Returns the anchor href that should be generated for the match.
       *
       * @return {String}
       */
      PhoneMatch.prototype.getAnchorHref = function () {
          return 'tel:' + (this.plusSign ? '+' : '') + this.number;
      };
      /**
       * Returns the anchor text that should be generated for the match.
       *
       * @return {String}
       */
      PhoneMatch.prototype.getAnchorText = function () {
          return this.matchedText;
      };
      return PhoneMatch;
  }(Match));

  /**
   * @class Autolinker.match.Url
   * @extends Autolinker.match.Match
   *
   * Represents a Url match found in an input string which should be Autolinked.
   *
   * See this class's superclass ({@link Autolinker.match.Match}) for more details.
   */
  var UrlMatch = /** @class */ (function (_super) {
      __extends(UrlMatch, _super);
      /**
       * @method constructor
       * @param {Object} cfg The configuration properties for the Match
       *   instance, specified in an Object (map).
       */
      function UrlMatch(cfg) {
          var _this = _super.call(this, cfg) || this;
          /**
           * @cfg {String} url (required)
           *
           * The url that was matched.
           */
          _this.url = ''; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @cfg {"scheme"/"www"/"tld"} urlMatchType (required)
           *
           * The type of URL match that this class represents. This helps to determine
           * if the match was made in the original text with a prefixed scheme (ex:
           * 'http://www.google.com'), a prefixed 'www' (ex: 'www.google.com'), or
           * was matched by a known top-level domain (ex: 'google.com').
           */
          _this.urlMatchType = 'scheme'; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @cfg {Boolean} protocolUrlMatch (required)
           *
           * `true` if the URL is a match which already has a protocol (i.e.
           * 'http://'), `false` if the match was from a 'www' or known TLD match.
           */
          _this.protocolUrlMatch = false; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @cfg {Boolean} protocolRelativeMatch (required)
           *
           * `true` if the URL is a protocol-relative match. A protocol-relative match
           * is a URL that starts with '//', and will be either http:// or https://
           * based on the protocol that the site is loaded under.
           */
          _this.protocolRelativeMatch = false; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @cfg {Object} stripPrefix (required)
           *
           * The Object form of {@link Autolinker#cfg-stripPrefix}.
           */
          _this.stripPrefix = { scheme: true, www: true }; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @cfg {Boolean} stripTrailingSlash (required)
           * @inheritdoc Autolinker#cfg-stripTrailingSlash
           */
          _this.stripTrailingSlash = true; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @cfg {Boolean} decodePercentEncoding (required)
           * @inheritdoc Autolinker#cfg-decodePercentEncoding
           */
          _this.decodePercentEncoding = true; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @private
           * @property {RegExp} schemePrefixRegex
           *
           * A regular expression used to remove the 'http://' or 'https://' from
           * URLs.
           */
          _this.schemePrefixRegex = /^(https?:\/\/)?/i;
          /**
           * @private
           * @property {RegExp} wwwPrefixRegex
           *
           * A regular expression used to remove the 'www.' from URLs.
           */
          _this.wwwPrefixRegex = /^(https?:\/\/)?(www\.)?/i;
          /**
           * @private
           * @property {RegExp} protocolRelativeRegex
           *
           * The regular expression used to remove the protocol-relative '//' from the {@link #url} string, for purposes
           * of {@link #getAnchorText}. A protocol-relative URL is, for example, "//yahoo.com"
           */
          _this.protocolRelativeRegex = /^\/\//;
          /**
           * @private
           * @property {Boolean} protocolPrepended
           *
           * Will be set to `true` if the 'http://' protocol has been prepended to the {@link #url} (because the
           * {@link #url} did not have a protocol)
           */
          _this.protocolPrepended = false;
          _this.urlMatchType = cfg.urlMatchType;
          _this.url = cfg.url;
          _this.protocolUrlMatch = cfg.protocolUrlMatch;
          _this.protocolRelativeMatch = cfg.protocolRelativeMatch;
          _this.stripPrefix = cfg.stripPrefix;
          _this.stripTrailingSlash = cfg.stripTrailingSlash;
          _this.decodePercentEncoding = cfg.decodePercentEncoding;
          return _this;
      }
      /**
       * Returns a string name for the type of match that this class represents.
       * For the case of UrlMatch, returns 'url'.
       *
       * @return {String}
       */
      UrlMatch.prototype.getType = function () {
          return 'url';
      };
      /**
       * Returns a string name for the type of URL match that this class
       * represents.
       *
       * This helps to determine if the match was made in the original text with a
       * prefixed scheme (ex: 'http://www.google.com'), a prefixed 'www' (ex:
       * 'www.google.com'), or was matched by a known top-level domain (ex:
       * 'google.com').
       *
       * @return {"scheme"/"www"/"tld"}
       */
      UrlMatch.prototype.getUrlMatchType = function () {
          return this.urlMatchType;
      };
      /**
       * Returns the url that was matched, assuming the protocol to be 'http://' if the original
       * match was missing a protocol.
       *
       * @return {String}
       */
      UrlMatch.prototype.getUrl = function () {
          var url = this.url;
          // if the url string doesn't begin with a protocol, assume 'http://'
          if (!this.protocolRelativeMatch && !this.protocolUrlMatch && !this.protocolPrepended) {
              url = this.url = 'http://' + url;
              this.protocolPrepended = true;
          }
          return url;
      };
      /**
       * Returns the anchor href that should be generated for the match.
       *
       * @return {String}
       */
      UrlMatch.prototype.getAnchorHref = function () {
          var url = this.getUrl();
          return url.replace(/&amp;/g, '&'); // any &amp;'s in the URL should be converted back to '&' if they were displayed as &amp; in the source html
      };
      /**
       * Returns the anchor text that should be generated for the match.
       *
       * @return {String}
       */
      UrlMatch.prototype.getAnchorText = function () {
          var anchorText = this.getMatchedText();
          if (this.protocolRelativeMatch) {
              // Strip off any protocol-relative '//' from the anchor text
              anchorText = this.stripProtocolRelativePrefix(anchorText);
          }
          if (this.stripPrefix.scheme) {
              anchorText = this.stripSchemePrefix(anchorText);
          }
          if (this.stripPrefix.www) {
              anchorText = this.stripWwwPrefix(anchorText);
          }
          if (this.stripTrailingSlash) {
              anchorText = this.removeTrailingSlash(anchorText); // remove trailing slash, if there is one
          }
          if (this.decodePercentEncoding) {
              anchorText = this.removePercentEncoding(anchorText);
          }
          return anchorText;
      };
      // ---------------------------------------
      // Utility Functionality
      /**
       * Strips the scheme prefix (such as "http://" or "https://") from the given
       * `url`.
       *
       * @private
       * @param {String} url The text of the anchor that is being generated, for
       *   which to strip off the url scheme.
       * @return {String} The `url`, with the scheme stripped.
       */
      UrlMatch.prototype.stripSchemePrefix = function (url) {
          return url.replace(this.schemePrefixRegex, '');
      };
      /**
       * Strips the 'www' prefix from the given `url`.
       *
       * @private
       * @param {String} url The text of the anchor that is being generated, for
       *   which to strip off the 'www' if it exists.
       * @return {String} The `url`, with the 'www' stripped.
       */
      UrlMatch.prototype.stripWwwPrefix = function (url) {
          return url.replace(this.wwwPrefixRegex, '$1'); // leave any scheme ($1), it one exists
      };
      /**
       * Strips any protocol-relative '//' from the anchor text.
       *
       * @private
       * @param {String} text The text of the anchor that is being generated, for which to strip off the
       *   protocol-relative prefix (such as stripping off "//")
       * @return {String} The `anchorText`, with the protocol-relative prefix stripped.
       */
      UrlMatch.prototype.stripProtocolRelativePrefix = function (text) {
          return text.replace(this.protocolRelativeRegex, '');
      };
      /**
       * Removes any trailing slash from the given `anchorText`, in preparation for the text to be displayed.
       *
       * @private
       * @param {String} anchorText The text of the anchor that is being generated, for which to remove any trailing
       *   slash ('/') that may exist.
       * @return {String} The `anchorText`, with the trailing slash removed.
       */
      UrlMatch.prototype.removeTrailingSlash = function (anchorText) {
          if (anchorText.charAt(anchorText.length - 1) === '/') {
              anchorText = anchorText.slice(0, -1);
          }
          return anchorText;
      };
      /**
       * Decodes percent-encoded characters from the given `anchorText`, in
       * preparation for the text to be displayed.
       *
       * @private
       * @param {String} anchorText The text of the anchor that is being
       *   generated, for which to decode any percent-encoded characters.
       * @return {String} The `anchorText`, with the percent-encoded characters
       *   decoded.
       */
      UrlMatch.prototype.removePercentEncoding = function (anchorText) {
          // First, convert a few of the known % encodings to the corresponding
          // HTML entities that could accidentally be interpretted as special
          // HTML characters
          var preProcessedEntityAnchorText = anchorText
              .replace(/%22/gi, '&quot;') // " char
              .replace(/%26/gi, '&amp;') // & char
              .replace(/%27/gi, '&#39;') // ' char
              .replace(/%3C/gi, '&lt;') // < char
              .replace(/%3E/gi, '&gt;'); // > char
          try {
              // Now attempt to decode the rest of the anchor text
              return decodeURIComponent(preProcessedEntityAnchorText);
          }
          catch (e) { // Invalid % escape sequence in the anchor text
              return preProcessedEntityAnchorText;
          }
      };
      return UrlMatch;
  }(Match));

  /**
   * @abstract
   * @class Autolinker.matcher.Matcher
   *
   * An abstract class and interface for individual matchers to find matches in
   * an input string with linkified versions of them.
   *
   * Note that Matchers do not take HTML into account - they must be fed the text
   * nodes of any HTML string, which is handled by {@link Autolinker#parse}.
   */
  var Matcher = /** @class */ (function () {
      /**
       * @method constructor
       * @param {Object} cfg The configuration properties for the Matcher
       *   instance, specified in an Object (map).
       */
      function Matcher(cfg) {
          /**
           * @cfg {Autolinker.AnchorTagBuilder} tagBuilder (required)
           *
           * Reference to the AnchorTagBuilder instance to use to generate HTML tags
           * for {@link Autolinker.match.Match Matches}.
           */
          this.__jsduckDummyDocProp = null; // property used just to get the above doc comment into the ES5 output and documentation generator
          this.tagBuilder = cfg.tagBuilder;
      }
      return Matcher;
  }());

  /*
   * This file builds and stores a library of the common regular expressions used
   * by the Autolinker utility.
   *
   * Other regular expressions may exist ad-hoc, but these are generally the
   * regular expressions that are shared between source files.
   */
  /**
   * Regular expression to match upper and lowercase ASCII letters
   */
  var letterRe = /[A-Za-z]/;
  /**
   * Regular expression to match ASCII digits
   */
  var digitRe = /[\d]/;
  /**
   * Regular expression to match everything *except* ASCII digits
   */
  var nonDigitRe = /[\D]/;
  /**
   * Regular expression to match whitespace
   */
  var whitespaceRe = /\s/;
  /**
   * Regular expression to match quote characters
   */
  var quoteRe = /['"]/;
  /**
   * Regular expression to match the range of ASCII control characters (0-31), and
   * the backspace char (127)
   */
  var controlCharsRe = /[\x00-\x1F\x7F]/;
  /**
   * The string form of a regular expression that would match all of the
   * alphabetic ("letter") chars in the unicode character set when placed in a
   * RegExp character class (`[]`). This includes all international alphabetic
   * characters.
   *
   * These would be the characters matched by unicode regex engines `\p{L}`
   * escape ("all letters").
   *
   * Taken from the XRegExp library: http://xregexp.com/ (thanks @https://github.com/slevithan)
   * Specifically: http://xregexp.com/v/3.2.0/xregexp-all.js, the 'Letter'
   *   regex's bmp
   *
   * VERY IMPORTANT: This set of characters is defined inside of a Regular
   *   Expression literal rather than a string literal to prevent UglifyJS from
   *   compressing the unicode escape sequences into their actual unicode
   *   characters. If Uglify compresses these into the unicode characters
   *   themselves, this results in the error "Range out of order in character
   *   class" when these characters are used inside of a Regular Expression
   *   character class (`[]`). See usages of this const. Alternatively, we can set
   *   the UglifyJS option `ascii_only` to true for the build, but that doesn't
   *   help others who are pulling in Autolinker into their own build and running
   *   UglifyJS themselves.
   */
  var alphaCharsStr = /A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC/
      .source; // see note in above variable description
  /**
   * The string form of a regular expression that would match all emoji characters
   * Based on the emoji regex defined in this article: https://thekevinscott.com/emojis-in-javascript/
   */
  var emojiStr = /\u2700-\u27bf\udde6-\uddff\ud800-\udbff\udc00-\udfff\ufe0e\ufe0f\u0300-\u036f\ufe20-\ufe23\u20d0-\u20f0\ud83c\udffb-\udfff\u200d\u3299\u3297\u303d\u3030\u24c2\ud83c\udd70-\udd71\udd7e-\udd7f\udd8e\udd91-\udd9a\udde6-\uddff\ude01-\ude02\ude1a\ude2f\ude32-\ude3a\ude50-\ude51\u203c\u2049\u25aa-\u25ab\u25b6\u25c0\u25fb-\u25fe\u00a9\u00ae\u2122\u2139\udc04\u2600-\u26FF\u2b05\u2b06\u2b07\u2b1b\u2b1c\u2b50\u2b55\u231a\u231b\u2328\u23cf\u23e9-\u23f3\u23f8-\u23fa\udccf\u2935\u2934\u2190-\u21ff/
      .source;
  /**
   * The string form of a regular expression that would match all of the
   * combining mark characters in the unicode character set when placed in a
   * RegExp character class (`[]`).
   *
   * These would be the characters matched by unicode regex engines `\p{M}`
   * escape ("all marks").
   *
   * Taken from the XRegExp library: http://xregexp.com/ (thanks @https://github.com/slevithan)
   * Specifically: http://xregexp.com/v/3.2.0/xregexp-all.js, the 'Mark'
   *   regex's bmp
   *
   * VERY IMPORTANT: This set of characters is defined inside of a Regular
   *   Expression literal rather than a string literal to prevent UglifyJS from
   *   compressing the unicode escape sequences into their actual unicode
   *   characters. If Uglify compresses these into the unicode characters
   *   themselves, this results in the error "Range out of order in character
   *   class" when these characters are used inside of a Regular Expression
   *   character class (`[]`). See usages of this const. Alternatively, we can set
   *   the UglifyJS option `ascii_only` to true for the build, but that doesn't
   *   help others who are pulling in Autolinker into their own build and running
   *   UglifyJS themselves.
   */
  var marksStr = /\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D4-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F/
      .source; // see note in above variable description
  /**
   * The string form of a regular expression that would match all of the
   * alphabetic ("letter") chars, emoji, and combining marks in the unicode character set
   * when placed in a RegExp character class (`[]`). This includes all
   * international alphabetic characters.
   *
   * These would be the characters matched by unicode regex engines `\p{L}\p{M}`
   * escapes and emoji characters.
   */
  var alphaCharsAndMarksStr = alphaCharsStr + emojiStr + marksStr;
  /**
   * The string form of a regular expression that would match all of the
   * decimal number chars in the unicode character set when placed in a RegExp
   * character class (`[]`).
   *
   * These would be the characters matched by unicode regex engines `\p{Nd}`
   * escape ("all decimal numbers")
   *
   * Taken from the XRegExp library: http://xregexp.com/ (thanks @https://github.com/slevithan)
   * Specifically: http://xregexp.com/v/3.2.0/xregexp-all.js, the 'Decimal_Number'
   *   regex's bmp
   *
   * VERY IMPORTANT: This set of characters is defined inside of a Regular
   *   Expression literal rather than a string literal to prevent UglifyJS from
   *   compressing the unicode escape sequences into their actual unicode
   *   characters. If Uglify compresses these into the unicode characters
   *   themselves, this results in the error "Range out of order in character
   *   class" when these characters are used inside of a Regular Expression
   *   character class (`[]`). See usages of this const. Alternatively, we can set
   *   the UglifyJS option `ascii_only` to true for the build, but that doesn't
   *   help others who are pulling in Autolinker into their own build and running
   *   UglifyJS themselves.
   */
  var decimalNumbersStr = /0-9\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0BE6-\u0BEF\u0C66-\u0C6F\u0CE6-\u0CEF\u0D66-\u0D6F\u0DE6-\u0DEF\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F29\u1040-\u1049\u1090-\u1099\u17E0-\u17E9\u1810-\u1819\u1946-\u194F\u19D0-\u19D9\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\uA620-\uA629\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uA9F0-\uA9F9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19/
      .source; // see note in above variable description
  /**
   * The string form of a regular expression that would match all of the
   * letters and decimal number chars in the unicode character set when placed in
   * a RegExp character class (`[]`).
   *
   * These would be the characters matched by unicode regex engines
   * `[\p{L}\p{Nd}]` escape ("all letters and decimal numbers")
   */
  var alphaNumericCharsStr = alphaCharsAndMarksStr + decimalNumbersStr;
  /**
   * The string form of a regular expression that would match all of the
   * letters, combining marks, and decimal number chars in the unicode character
   * set when placed in a RegExp character class (`[]`).
   *
   * These would be the characters matched by unicode regex engines
   * `[\p{L}\p{M}\p{Nd}]` escape ("all letters, combining marks, and decimal
   * numbers")
   */
  var alphaNumericAndMarksCharsStr = alphaCharsAndMarksStr + decimalNumbersStr;
  // Simplified IP regular expression
  var ipStr = '(?:[' + decimalNumbersStr + ']{1,3}\\.){3}[' + decimalNumbersStr + ']{1,3}';
  // Protected domain label which do not allow "-" character on the beginning and the end of a single label
  var domainLabelStr = '[' + alphaNumericAndMarksCharsStr + '](?:[' + alphaNumericAndMarksCharsStr + '\\-]{0,61}[' + alphaNumericAndMarksCharsStr + '])?';
  var getDomainLabelStr = function (group) {
      return '(?=(' + domainLabelStr + '))\\' + group;
  };
  /**
   * A function to match domain names of a URL or email address.
   * Ex: 'google', 'yahoo', 'some-other-company', etc.
   */
  var getDomainNameStr = function (group) {
      return '(?:' + getDomainLabelStr(group) + '(?:\\.' + getDomainLabelStr(group + 1) + '){0,126}|' + ipStr + ')';
  };
  /**
   * A regular expression that is simply the character class of the characters
   * that may be used in a domain name, minus the '-' or '.'
   */
  var domainNameCharRegex = new RegExp("[".concat(alphaNumericAndMarksCharsStr, "]"));

  // NOTE: THIS IS A GENERATED FILE
  // To update with the latest TLD list, run `npm run update-tld-regex` or `yarn update-tld-regex` (depending on which you have installed)
  var tldRegex = /(?:xn--vermgensberatung-pwb|xn--vermgensberater-ctb|xn--clchc0ea0b2g2a9gcd|xn--w4r85el8fhu5dnra|northwesternmutual|travelersinsurance|vermögensberatung|xn--3oq18vl8pn36a|xn--5su34j936bgsg|xn--bck1b9a5dre4c|xn--mgbah1a3hjkrd|xn--mgbai9azgqp6j|xn--mgberp4a5d4ar|xn--xkc2dl3a5ee0h|vermögensberater|xn--fzys8d69uvgm|xn--mgba7c0bbn0a|xn--mgbcpq6gpa1a|xn--xkc2al3hye2a|americanexpress|kerryproperties|sandvikcoromant|xn--i1b6b1a6a2e|xn--kcrx77d1x4a|xn--lgbbat1ad8j|xn--mgba3a4f16a|xn--mgbaakc7dvf|xn--mgbc0a9azcg|xn--nqv7fs00ema|afamilycompany|americanfamily|bananarepublic|cancerresearch|cookingchannel|kerrylogistics|weatherchannel|xn--54b7fta0cc|xn--6qq986b3xl|xn--80aqecdr1a|xn--b4w605ferd|xn--fiq228c5hs|xn--h2breg3eve|xn--jlq480n2rg|xn--jlq61u9w7b|xn--mgba3a3ejt|xn--mgbaam7a8h|xn--mgbayh7gpa|xn--mgbbh1a71e|xn--mgbca7dzdo|xn--mgbi4ecexp|xn--mgbx4cd0ab|xn--rvc1e0am3e|international|lifeinsurance|travelchannel|wolterskluwer|xn--cckwcxetd|xn--eckvdtc9d|xn--fpcrj9c3d|xn--fzc2c9e2c|xn--h2brj9c8c|xn--tiq49xqyj|xn--yfro4i67o|xn--ygbi2ammx|construction|lplfinancial|scholarships|versicherung|xn--3e0b707e|xn--45br5cyl|xn--4dbrk0ce|xn--80adxhks|xn--80asehdb|xn--8y0a063a|xn--gckr3f0f|xn--mgb9awbf|xn--mgbab2bd|xn--mgbgu82a|xn--mgbpl2fh|xn--mgbt3dhd|xn--mk1bu44c|xn--ngbc5azd|xn--ngbe9e0a|xn--ogbpf8fl|xn--qcka1pmc|accountants|barclaycard|blackfriday|blockbuster|bridgestone|calvinklein|contractors|creditunion|engineering|enterprises|foodnetwork|investments|kerryhotels|lamborghini|motorcycles|olayangroup|photography|playstation|productions|progressive|redumbrella|williamhill|xn--11b4c3d|xn--1ck2e1b|xn--1qqw23a|xn--2scrj9c|xn--3bst00m|xn--3ds443g|xn--3hcrj9c|xn--42c2d9a|xn--45brj9c|xn--55qw42g|xn--6frz82g|xn--80ao21a|xn--9krt00a|xn--cck2b3b|xn--czr694b|xn--d1acj3b|xn--efvy88h|xn--fct429k|xn--fjq720a|xn--flw351e|xn--g2xx48c|xn--gecrj9c|xn--gk3at1e|xn--h2brj9c|xn--hxt814e|xn--imr513n|xn--j6w193g|xn--jvr189m|xn--kprw13d|xn--kpry57d|xn--mgbbh1a|xn--mgbtx2b|xn--mix891f|xn--nyqy26a|xn--otu796d|xn--pgbs0dh|xn--q9jyb4c|xn--rhqv96g|xn--rovu88b|xn--s9brj9c|xn--ses554g|xn--t60b56a|xn--vuq861b|xn--w4rs40l|xn--xhq521b|xn--zfr164b|சிங்கப்பூர்|accountant|apartments|associates|basketball|bnpparibas|boehringer|capitalone|consulting|creditcard|cuisinella|eurovision|extraspace|foundation|healthcare|immobilien|industries|management|mitsubishi|nextdirect|properties|protection|prudential|realestate|republican|restaurant|schaeffler|swiftcover|tatamotors|technology|university|vlaanderen|volkswagen|xn--30rr7y|xn--3pxu8k|xn--45q11c|xn--4gbrim|xn--55qx5d|xn--5tzm5g|xn--80aswg|xn--90a3ac|xn--9dbq2a|xn--9et52u|xn--c2br7g|xn--cg4bki|xn--czrs0t|xn--czru2d|xn--fiq64b|xn--fiqs8s|xn--fiqz9s|xn--io0a7i|xn--kput3i|xn--mxtq1m|xn--o3cw4h|xn--pssy2u|xn--q7ce6a|xn--unup4y|xn--wgbh1c|xn--wgbl6a|xn--y9a3aq|accenture|alfaromeo|allfinanz|amsterdam|analytics|aquarelle|barcelona|bloomberg|christmas|community|directory|education|equipment|fairwinds|financial|firestone|fresenius|frontdoor|furniture|goldpoint|hisamitsu|homedepot|homegoods|homesense|institute|insurance|kuokgroup|lancaster|landrover|lifestyle|marketing|marshalls|melbourne|microsoft|panasonic|passagens|pramerica|richardli|scjohnson|shangrila|solutions|statebank|statefarm|stockholm|travelers|vacations|xn--90ais|xn--c1avg|xn--d1alf|xn--e1a4c|xn--fhbei|xn--j1aef|xn--j1amh|xn--l1acc|xn--ngbrx|xn--nqv7f|xn--p1acf|xn--qxa6a|xn--tckwe|xn--vhquv|yodobashi|موريتانيا|abudhabi|airforce|allstate|attorney|barclays|barefoot|bargains|baseball|boutique|bradesco|broadway|brussels|budapest|builders|business|capetown|catering|catholic|cipriani|cityeats|cleaning|clinique|clothing|commbank|computer|delivery|deloitte|democrat|diamonds|discount|discover|download|engineer|ericsson|etisalat|exchange|feedback|fidelity|firmdale|football|frontier|goodyear|grainger|graphics|guardian|hdfcbank|helsinki|holdings|hospital|infiniti|ipiranga|istanbul|jpmorgan|lighting|lundbeck|marriott|maserati|mckinsey|memorial|merckmsd|mortgage|observer|partners|pharmacy|pictures|plumbing|property|redstone|reliance|saarland|samsclub|security|services|shopping|showtime|softbank|software|stcgroup|supplies|training|vanguard|ventures|verisign|woodside|xn--90ae|xn--node|xn--p1ai|xn--qxam|yokohama|السعودية|abogado|academy|agakhan|alibaba|android|athleta|auction|audible|auspost|avianca|banamex|bauhaus|bentley|bestbuy|booking|brother|bugatti|capital|caravan|careers|channel|charity|chintai|citadel|clubmed|college|cologne|comcast|company|compare|contact|cooking|corsica|country|coupons|courses|cricket|cruises|dentist|digital|domains|exposed|express|farmers|fashion|ferrari|ferrero|finance|fishing|fitness|flights|florist|flowers|forsale|frogans|fujitsu|gallery|genting|godaddy|grocery|guitars|hamburg|hangout|hitachi|holiday|hosting|hoteles|hotmail|hyundai|ismaili|jewelry|juniper|kitchen|komatsu|lacaixa|lanxess|lasalle|latrobe|leclerc|limited|lincoln|markets|monster|netbank|netflix|network|neustar|okinawa|oldnavy|organic|origins|philips|pioneer|politie|realtor|recipes|rentals|reviews|rexroth|samsung|sandvik|schmidt|schwarz|science|shiksha|singles|staples|storage|support|surgery|systems|temasek|theater|theatre|tickets|tiffany|toshiba|trading|walmart|wanggou|watches|weather|website|wedding|whoswho|windows|winners|xfinity|yamaxun|youtube|zuerich|католик|اتصالات|البحرين|الجزائر|العليان|پاکستان|كاثوليك|இந்தியா|abarth|abbott|abbvie|africa|agency|airbus|airtel|alipay|alsace|alstom|amazon|anquan|aramco|author|bayern|beauty|berlin|bharti|bostik|boston|broker|camera|career|casino|center|chanel|chrome|church|circle|claims|clinic|coffee|comsec|condos|coupon|credit|cruise|dating|datsun|dealer|degree|dental|design|direct|doctor|dunlop|dupont|durban|emerck|energy|estate|events|expert|family|flickr|futbol|gallup|garden|george|giving|global|google|gratis|health|hermes|hiphop|hockey|hotels|hughes|imamat|insure|intuit|jaguar|joburg|juegos|kaufen|kinder|kindle|kosher|lancia|latino|lawyer|lefrak|living|locker|london|luxury|madrid|maison|makeup|market|mattel|mobile|monash|mormon|moscow|museum|mutual|nagoya|natura|nissan|nissay|norton|nowruz|office|olayan|online|oracle|orange|otsuka|pfizer|photos|physio|pictet|quebec|racing|realty|reisen|repair|report|review|rocher|rogers|ryukyu|safety|sakura|sanofi|school|schule|search|secure|select|shouji|soccer|social|stream|studio|supply|suzuki|swatch|sydney|taipei|taobao|target|tattoo|tennis|tienda|tjmaxx|tkmaxx|toyota|travel|unicom|viajes|viking|villas|virgin|vision|voting|voyage|vuelos|walter|webcam|xihuan|yachts|yandex|zappos|москва|онлайн|ابوظبي|ارامكو|الاردن|المغرب|امارات|فلسطين|مليسيا|भारतम्|இலங்கை|ファッション|actor|adult|aetna|amfam|amica|apple|archi|audio|autos|azure|baidu|beats|bible|bingo|black|boats|bosch|build|canon|cards|chase|cheap|cisco|citic|click|cloud|coach|codes|crown|cymru|dabur|dance|deals|delta|drive|dubai|earth|edeka|email|epson|faith|fedex|final|forex|forum|gallo|games|gifts|gives|glade|glass|globo|gmail|green|gripe|group|gucci|guide|homes|honda|horse|house|hyatt|ikano|irish|jetzt|koeln|kyoto|lamer|lease|legal|lexus|lilly|linde|lipsy|lixil|loans|locus|lotte|lotto|macys|mango|media|miami|money|movie|nexus|nikon|ninja|nokia|nowtv|omega|osaka|paris|parts|party|phone|photo|pizza|place|poker|praxi|press|prime|promo|quest|radio|rehab|reise|ricoh|rocks|rodeo|rugby|salon|sener|seven|sharp|shell|shoes|skype|sling|smart|smile|solar|space|sport|stada|store|study|style|sucks|swiss|tatar|tires|tirol|tmall|today|tokyo|tools|toray|total|tours|trade|trust|tunes|tushu|ubank|vegas|video|vodka|volvo|wales|watch|weber|weibo|works|world|xerox|yahoo|ישראל|ایران|بازار|بھارت|سودان|سورية|همراه|भारोत|संगठन|বাংলা|భారత్|ഭാരതം|嘉里大酒店|aarp|able|adac|aero|akdn|ally|amex|arab|army|arpa|arte|asda|asia|audi|auto|baby|band|bank|bbva|beer|best|bike|bing|blog|blue|bofa|bond|book|buzz|cafe|call|camp|care|cars|casa|case|cash|cbre|cern|chat|citi|city|club|cool|coop|cyou|data|date|dclk|deal|dell|desi|diet|dish|docs|duck|dvag|erni|fage|fail|fans|farm|fast|fiat|fido|film|fire|fish|flir|food|ford|free|fund|game|gbiz|gent|ggee|gift|gmbh|gold|golf|goog|guge|guru|hair|haus|hdfc|help|here|hgtv|host|hsbc|icbc|ieee|imdb|immo|info|itau|java|jeep|jobs|jprs|kddi|kiwi|kpmg|kred|land|lego|lgbt|lidl|life|like|limo|link|live|loan|loft|love|ltda|luxe|maif|meet|meme|menu|mini|mint|mobi|moda|moto|name|navy|news|next|nico|nike|ollo|open|page|pars|pccw|pics|ping|pink|play|plus|pohl|porn|post|prod|prof|qpon|raid|read|reit|rent|rest|rich|rmit|room|rsvp|ruhr|safe|sale|sarl|save|saxo|scot|seat|seek|sexy|shaw|shia|shop|show|silk|sina|site|skin|sncf|sohu|song|sony|spot|star|surf|talk|taxi|team|tech|teva|tiaa|tips|town|toys|tube|vana|visa|viva|vivo|vote|voto|wang|weir|wien|wiki|wine|work|xbox|yoga|zara|zero|zone|дети|сайт|بارت|بيتك|ڀارت|تونس|شبكة|عراق|عمان|موقع|भारत|ভারত|ভাৰত|ਭਾਰਤ|ભારત|ଭାରତ|ಭಾರತ|ලංකා|アマゾン|グーグル|クラウド|ポイント|大众汽车|组织机构|電訊盈科|香格里拉|aaa|abb|abc|aco|ads|aeg|afl|aig|anz|aol|app|art|aws|axa|bar|bbc|bbt|bcg|bcn|bet|bid|bio|biz|bms|bmw|bom|boo|bot|box|buy|bzh|cab|cal|cam|car|cat|cba|cbn|cbs|ceo|cfa|cfd|com|cpa|crs|csc|dad|day|dds|dev|dhl|diy|dnp|dog|dot|dtv|dvr|eat|eco|edu|esq|eus|fan|fit|fly|foo|fox|frl|ftr|fun|fyi|gal|gap|gay|gdn|gea|gle|gmo|gmx|goo|gop|got|gov|hbo|hiv|hkt|hot|how|ibm|ice|icu|ifm|inc|ing|ink|int|ist|itv|jcb|jio|jll|jmp|jnj|jot|joy|kfh|kia|kim|kpn|krd|lat|law|lds|llc|llp|lol|lpl|ltd|man|map|mba|med|men|mil|mit|mlb|mls|mma|moe|moi|mom|mov|msd|mtn|mtr|nab|nba|nec|net|new|nfl|ngo|nhk|now|nra|nrw|ntt|nyc|obi|off|one|ong|onl|ooo|org|ott|ovh|pay|pet|phd|pid|pin|pnc|pro|pru|pub|pwc|qvc|red|ren|ril|rio|rip|run|rwe|sap|sas|sbi|sbs|sca|scb|ses|sew|sex|sfr|ski|sky|soy|spa|srl|stc|tab|tax|tci|tdk|tel|thd|tjx|top|trv|tui|tvs|ubs|uno|uol|ups|vet|vig|vin|vip|wed|win|wme|wow|wtc|wtf|xin|xxx|xyz|you|yun|zip|бел|ком|қаз|мкд|мон|орг|рус|срб|укр|հայ|קום|عرب|قطر|كوم|مصر|कॉम|नेट|คอม|ไทย|ລາວ|ストア|セール|みんな|中文网|亚马逊|天主教|我爱你|新加坡|淡马锡|诺基亚|飞利浦|ac|ad|ae|af|ag|ai|al|am|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cw|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|za|zm|zw|ελ|ευ|бг|ею|рф|გე|닷넷|닷컴|삼성|한국|コム|世界|中信|中国|中國|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|嘉里|在线|大拿|娱乐|家電|广东|微博|慈善|手机|招聘|政务|政府|新闻|时尚|書籍|机构|游戏|澳門|点看|移动|网址|网店|网站|网络|联通|谷歌|购物|通販|集团|食品|餐厅|香港)/;

  // For debugging: search for other "For debugging" lines
  // import CliTable from 'cli-table';
  // RegExp objects which are shared by all instances of EmailMatcher. These are
  // here to avoid re-instantiating the RegExp objects if `Autolinker.link()` is
  // called multiple times, thus instantiating EmailMatcher and its RegExp 
  // objects each time (which is very expensive - see https://github.com/gregjacobs/Autolinker.js/issues/314). 
  // See descriptions of the properties where they are used for details about them
  var localPartCharRegex = new RegExp("[".concat(alphaNumericAndMarksCharsStr, "!#$%&'*+/=?^_`{|}~-]"));
  var strictTldRegex = new RegExp("^".concat(tldRegex.source, "$"));
  /**
   * @class Autolinker.matcher.Email
   * @extends Autolinker.matcher.Matcher
   *
   * Matcher to find email matches in an input string.
   *
   * See this class's superclass ({@link Autolinker.matcher.Matcher}) for more details.
   */
  var EmailMatcher = /** @class */ (function (_super) {
      __extends(EmailMatcher, _super);
      function EmailMatcher() {
          var _this = _super !== null && _super.apply(this, arguments) || this;
          /**
           * Valid characters that can be used in the "local" part of an email address,
           * i.e. the "name" part of "name@site.com"
           */
          _this.localPartCharRegex = localPartCharRegex;
          /**
           * Stricter TLD regex which adds a beginning and end check to ensure
           * the string is a valid TLD
           */
          _this.strictTldRegex = strictTldRegex;
          return _this;
      }
      /**
       * @inheritdoc
       */
      EmailMatcher.prototype.parseMatches = function (text) {
          var tagBuilder = this.tagBuilder, localPartCharRegex = this.localPartCharRegex, strictTldRegex = this.strictTldRegex, matches = [], len = text.length, noCurrentEmailMatch = new CurrentEmailMatch();
          // for matching a 'mailto:' prefix
          var mailtoTransitions = {
              'm': 'a',
              'a': 'i',
              'i': 'l',
              'l': 't',
              't': 'o',
              'o': ':',
          };
          var charIdx = 0, state = 0 /* NonEmailMatch */, currentEmailMatch = noCurrentEmailMatch;
          // For debugging: search for other "For debugging" lines
          // const table = new CliTable( {
          // 	head: [ 'charIdx', 'char', 'state', 'charIdx', 'currentEmailAddress.idx', 'hasDomainDot' ]
          // } );
          while (charIdx < len) {
              var char = text.charAt(charIdx);
              // For debugging: search for other "For debugging" lines
              // table.push( 
              // 	[ charIdx, char, State[ state ], charIdx, currentEmailAddress.idx, currentEmailAddress.hasDomainDot ] 
              // );
              switch (state) {
                  case 0 /* NonEmailMatch */:
                      stateNonEmailAddress(char);
                      break;
                  case 1 /* Mailto */:
                      stateMailTo(text.charAt(charIdx - 1), char);
                      break;
                  case 2 /* LocalPart */:
                      stateLocalPart(char);
                      break;
                  case 3 /* LocalPartDot */:
                      stateLocalPartDot(char);
                      break;
                  case 4 /* AtSign */:
                      stateAtSign(char);
                      break;
                  case 5 /* DomainChar */:
                      stateDomainChar(char);
                      break;
                  case 6 /* DomainHyphen */:
                      stateDomainHyphen(char);
                      break;
                  case 7 /* DomainDot */:
                      stateDomainDot(char);
                      break;
                  default:
                      throwUnhandledCaseError(state);
              }
              // For debugging: search for other "For debugging" lines
              // table.push( 
              // 	[ charIdx, char, State[ state ], charIdx, currentEmailAddress.idx, currentEmailAddress.hasDomainDot ] 
              // );
              charIdx++;
          }
          // Capture any valid match at the end of the string
          captureMatchIfValidAndReset();
          // For debugging: search for other "For debugging" lines
          //console.log( '\n' + table.toString() );
          return matches;
          // Handles the state when we're not in an email address
          function stateNonEmailAddress(char) {
              if (char === 'm') {
                  beginEmailMatch(1 /* Mailto */);
              }
              else if (localPartCharRegex.test(char)) {
                  beginEmailMatch();
              }
              else ;
          }
          // Handles if we're reading a 'mailto:' prefix on the string
          function stateMailTo(prevChar, char) {
              if (prevChar === ':') {
                  // We've reached the end of the 'mailto:' prefix
                  if (localPartCharRegex.test(char)) {
                      state = 2 /* LocalPart */;
                      currentEmailMatch = new CurrentEmailMatch(__assign(__assign({}, currentEmailMatch), { hasMailtoPrefix: true }));
                  }
                  else {
                      // we've matched 'mailto:' but didn't get anything meaningful
                      // immediately afterwards (for example, we encountered a 
                      // space character, or an '@' character which formed 'mailto:@'
                      resetToNonEmailMatchState();
                  }
              }
              else if (mailtoTransitions[prevChar] === char) ;
              else if (localPartCharRegex.test(char)) {
                  // We we're reading a prefix of 'mailto:', but encountered a
                  // different character that didn't continue the prefix
                  state = 2 /* LocalPart */;
              }
              else if (char === '.') {
                  // We we're reading a prefix of 'mailto:', but encountered a
                  // dot character
                  state = 3 /* LocalPartDot */;
              }
              else if (char === '@') {
                  // We we're reading a prefix of 'mailto:', but encountered a
                  // an @ character
                  state = 4 /* AtSign */;
              }
              else {
                  // not an email address character, return to "NonEmailAddress" state
                  resetToNonEmailMatchState();
              }
          }
          // Handles the state when we're currently in the "local part" of an 
          // email address (as opposed to the "domain part")
          function stateLocalPart(char) {
              if (char === '.') {
                  state = 3 /* LocalPartDot */;
              }
              else if (char === '@') {
                  state = 4 /* AtSign */;
              }
              else if (localPartCharRegex.test(char)) ;
              else {
                  // not an email address character, return to "NonEmailAddress" state
                  resetToNonEmailMatchState();
              }
          }
          // Handles the state where we've read 
          function stateLocalPartDot(char) {
              if (char === '.') {
                  // We read a second '.' in a row, not a valid email address 
                  // local part
                  resetToNonEmailMatchState();
              }
              else if (char === '@') {
                  // We read the '@' character immediately after a dot ('.'), not 
                  // an email address
                  resetToNonEmailMatchState();
              }
              else if (localPartCharRegex.test(char)) {
                  state = 2 /* LocalPart */;
              }
              else {
                  // Anything else, not an email address
                  resetToNonEmailMatchState();
              }
          }
          function stateAtSign(char) {
              if (domainNameCharRegex.test(char)) {
                  state = 5 /* DomainChar */;
              }
              else {
                  // Anything else, not an email address
                  resetToNonEmailMatchState();
              }
          }
          function stateDomainChar(char) {
              if (char === '.') {
                  state = 7 /* DomainDot */;
              }
              else if (char === '-') {
                  state = 6 /* DomainHyphen */;
              }
              else if (domainNameCharRegex.test(char)) ;
              else {
                  // Anything else, we potentially matched if the criteria has
                  // been met
                  captureMatchIfValidAndReset();
              }
          }
          function stateDomainHyphen(char) {
              if (char === '-' || char === '.') {
                  // Not valid to have two hyphens ("--") or hypen+dot ("-.")
                  captureMatchIfValidAndReset();
              }
              else if (domainNameCharRegex.test(char)) {
                  state = 5 /* DomainChar */;
              }
              else {
                  // Anything else
                  captureMatchIfValidAndReset();
              }
          }
          function stateDomainDot(char) {
              if (char === '.' || char === '-') {
                  // not valid to have two dots ("..") or dot+hypen (".-")
                  captureMatchIfValidAndReset();
              }
              else if (domainNameCharRegex.test(char)) {
                  state = 5 /* DomainChar */;
                  // After having read a '.' and then a valid domain character,
                  // we now know that the domain part of the email is valid, and
                  // we have found at least a partial EmailMatch (however, the
                  // email address may have additional characters from this point)
                  currentEmailMatch = new CurrentEmailMatch(__assign(__assign({}, currentEmailMatch), { hasDomainDot: true }));
              }
              else {
                  // Anything else
                  captureMatchIfValidAndReset();
              }
          }
          function beginEmailMatch(newState) {
              if (newState === void 0) { newState = 2 /* LocalPart */; }
              state = newState;
              currentEmailMatch = new CurrentEmailMatch({ idx: charIdx });
          }
          function resetToNonEmailMatchState() {
              state = 0 /* NonEmailMatch */;
              currentEmailMatch = noCurrentEmailMatch;
          }
          /*
           * Captures the current email address as an EmailMatch if it's valid,
           * and resets the state to read another email address.
           */
          function captureMatchIfValidAndReset() {
              if (currentEmailMatch.hasDomainDot) { // we need at least one dot in the domain to be considered a valid email address
                  var matchedText = text.slice(currentEmailMatch.idx, charIdx);
                  // If we read a '.' or '-' char that ended the email address
                  // (valid domain name characters, but only valid email address
                  // characters if they are followed by something else), strip 
                  // it off now
                  if (/[-.]$/.test(matchedText)) {
                      matchedText = matchedText.slice(0, -1);
                  }
                  var emailAddress = currentEmailMatch.hasMailtoPrefix
                      ? matchedText.slice('mailto:'.length)
                      : matchedText;
                  // if the email address has a valid TLD, add it to the list of matches
                  if (doesEmailHaveValidTld(emailAddress)) {
                      matches.push(new EmailMatch({
                          tagBuilder: tagBuilder,
                          matchedText: matchedText,
                          offset: currentEmailMatch.idx,
                          email: emailAddress
                      }));
                  }
              }
              resetToNonEmailMatchState();
              /**
               * Determines if the given email address has a valid TLD or not
               * @param {string} emailAddress - email address
               * @return {Boolean} - true is email have valid TLD, false otherwise
               */
              function doesEmailHaveValidTld(emailAddress) {
                  var emailAddressTld = emailAddress.split('.').pop() || '';
                  var emailAddressNormalized = emailAddressTld.toLowerCase();
                  var isValidTld = strictTldRegex.test(emailAddressNormalized);
                  return isValidTld;
              }
          }
      };
      return EmailMatcher;
  }(Matcher));
  var CurrentEmailMatch = /** @class */ (function () {
      function CurrentEmailMatch(cfg) {
          if (cfg === void 0) { cfg = {}; }
          this.idx = cfg.idx !== undefined ? cfg.idx : -1;
          this.hasMailtoPrefix = !!cfg.hasMailtoPrefix;
          this.hasDomainDot = !!cfg.hasDomainDot;
      }
      return CurrentEmailMatch;
  }());

  /**
   * @private
   * @class Autolinker.matcher.UrlMatchValidator
   * @singleton
   *
   * Used by Autolinker to filter out false URL positives from the
   * {@link Autolinker.matcher.Url UrlMatcher}.
   *
   * Due to the limitations of regular expressions (including the missing feature
   * of look-behinds in JS regular expressions), we cannot always determine the
   * validity of a given match. This class applies a bit of additional logic to
   * filter out any false positives that have been matched by the
   * {@link Autolinker.matcher.Url UrlMatcher}.
   */
  var UrlMatchValidator = /** @class */ (function () {
      function UrlMatchValidator() {
      }
      /**
       * Determines if a given URL match found by the {@link Autolinker.matcher.Url UrlMatcher}
       * is valid. Will return `false` for:
       *
       * 1) URL matches which do not have at least have one period ('.') in the
       *    domain name (effectively skipping over matches like "abc:def").
       *    However, URL matches with a protocol will be allowed (ex: 'http://localhost')
       * 2) URL matches which do not have at least one word character in the
       *    domain name (effectively skipping over matches like "git:1.0").
       *    However, URL matches with a protocol will be allowed (ex: 'intra-net://271219.76')
       * 3) A protocol-relative url match (a URL beginning with '//') whose
       *    previous character is a word character (effectively skipping over
       *    strings like "abc//google.com")
       *
       * Otherwise, returns `true`.
       *
       * @param {String} urlMatch The matched URL, if there was one. Will be an
       *   empty string if the match is not a URL match.
       * @param {String} protocolUrlMatch The match URL string for a protocol
       *   match. Ex: 'http://yahoo.com'. This is used to match something like
       *   'http://localhost', where we won't double check that the domain name
       *   has at least one '.' in it.
       * @return {Boolean} `true` if the match given is valid and should be
       *   processed, or `false` if the match is invalid and/or should just not be
       *   processed.
       */
      UrlMatchValidator.isValid = function (urlMatch, protocolUrlMatch) {
          if ((protocolUrlMatch && !this.isValidUriScheme(protocolUrlMatch)) ||
              this.urlMatchDoesNotHaveProtocolOrDot(urlMatch, protocolUrlMatch) || // At least one period ('.') must exist in the URL match for us to consider it an actual URL, *unless* it was a full protocol match (like 'http://localhost')
              (this.urlMatchDoesNotHaveAtLeastOneWordChar(urlMatch, protocolUrlMatch) && // At least one letter character must exist in the domain name after a protocol match. Ex: skip over something like "git:1.0"
                  !this.isValidIpAddress(urlMatch)) || // Except if it's an IP address
              this.containsMultipleDots(urlMatch)) {
              return false;
          }
          return true;
      };
      UrlMatchValidator.isValidIpAddress = function (uriSchemeMatch) {
          var newRegex = new RegExp(this.hasFullProtocolRegex.source + this.ipRegex.source);
          var uriScheme = uriSchemeMatch.match(newRegex);
          return uriScheme !== null;
      };
      UrlMatchValidator.containsMultipleDots = function (urlMatch) {
          var stringBeforeSlash = urlMatch;
          if (this.hasFullProtocolRegex.test(urlMatch)) {
              stringBeforeSlash = urlMatch.split('://')[1];
          }
          return stringBeforeSlash.split('/')[0].indexOf("..") > -1;
      };
      /**
       * Determines if the URI scheme is a valid scheme to be autolinked. Returns
       * `false` if the scheme is 'javascript:' or 'vbscript:'
       *
       * @private
       * @param {String} uriSchemeMatch The match URL string for a full URI scheme
       *   match. Ex: 'http://yahoo.com' or 'mailto:a@a.com'.
       * @return {Boolean} `true` if the scheme is a valid one, `false` otherwise.
       */
      UrlMatchValidator.isValidUriScheme = function (uriSchemeMatch) {
          var uriSchemeMatchArr = uriSchemeMatch.match(this.uriSchemeRegex), uriScheme = uriSchemeMatchArr && uriSchemeMatchArr[0].toLowerCase();
          return (uriScheme !== 'javascript:' && uriScheme !== 'vbscript:');
      };
      /**
       * Determines if a URL match does not have either:
       *
       * a) a full protocol (i.e. 'http://'), or
       * b) at least one dot ('.') in the domain name (for a non-full-protocol
       *    match).
       *
       * Either situation is considered an invalid URL (ex: 'git:d' does not have
       * either the '://' part, or at least one dot in the domain name. If the
       * match was 'git:abc.com', we would consider this valid.)
       *
       * @private
       * @param {String} urlMatch The matched URL, if there was one. Will be an
       *   empty string if the match is not a URL match.
       * @param {String} protocolUrlMatch The match URL string for a protocol
       *   match. Ex: 'http://yahoo.com'. This is used to match something like
       *   'http://localhost', where we won't double check that the domain name
       *   has at least one '.' in it.
       * @return {Boolean} `true` if the URL match does not have a full protocol,
       *   or at least one dot ('.') in a non-full-protocol match.
       */
      UrlMatchValidator.urlMatchDoesNotHaveProtocolOrDot = function (urlMatch, protocolUrlMatch) {
          return (!!urlMatch && (!protocolUrlMatch || !this.hasFullProtocolRegex.test(protocolUrlMatch)) && urlMatch.indexOf('.') === -1);
      };
      /**
       * Determines if a URL match does not have either:
       *
       * a) a full protocol (i.e. 'http://'), or
       * b) at least one word character after the protocol (i.e. in the domain name)
       *
       * At least one letter character must exist in the domain name after a
       * protocol match. Ex: skip over something like "git:1.0"
       *
       * @private
       * @param {String} urlMatch The matched URL, if there was one. Will be an
       *   empty string if the match is not a URL match.
       * @param {String} protocolUrlMatch The match URL string for a protocol
       *   match. Ex: 'http://yahoo.com'. This is used to know whether or not we
       *   have a protocol in the URL string, in order to check for a word
       *   character after the protocol separator (':').
       * @return {Boolean} `true` if the URL match does not have a full protocol, or
       * at least one word character in it, `false` otherwise.
       */
      UrlMatchValidator.urlMatchDoesNotHaveAtLeastOneWordChar = function (urlMatch, protocolUrlMatch) {
          if (urlMatch && protocolUrlMatch) {
              return !this.hasFullProtocolRegex.test(protocolUrlMatch) && !this.hasWordCharAfterProtocolRegex.test(urlMatch);
          }
          else {
              return false;
          }
      };
      /**
       * Regex to test for a full protocol, with the two trailing slashes. Ex: 'http://'
       *
       * @private
       * @property {RegExp} hasFullProtocolRegex
       */
      UrlMatchValidator.hasFullProtocolRegex = /^[A-Za-z][-.+A-Za-z0-9]*:\/\//;
      /**
       * Regex to find the URI scheme, such as 'mailto:'.
       *
       * This is used to filter out 'javascript:' and 'vbscript:' schemes.
       *
       * @private
       * @property {RegExp} uriSchemeRegex
       */
      UrlMatchValidator.uriSchemeRegex = /^[A-Za-z][-.+A-Za-z0-9]*:/;
      /**
       * Regex to determine if at least one word char exists after the protocol (i.e. after the ':')
       *
       * @private
       * @property {RegExp} hasWordCharAfterProtocolRegex
       */
      UrlMatchValidator.hasWordCharAfterProtocolRegex = new RegExp(":[^\\s]*?[" + alphaCharsStr + "]");
      /**
       * Regex to determine if the string is a valid IP address
       *
       * @private
       * @property {RegExp} ipRegex
       */
      UrlMatchValidator.ipRegex = /[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?(:[0-9]*)?\/?$/;
      return UrlMatchValidator;
  }());

  // RegExp objects which are shared by all instances of UrlMatcher. These are
  // here to avoid re-instantiating the RegExp objects if `Autolinker.link()` is
  // called multiple times, thus instantiating UrlMatcher and its RegExp 
  // objects each time (which is very expensive - see https://github.com/gregjacobs/Autolinker.js/issues/314). 
  // See descriptions of the properties where they are used for details about them
  var matcherRegex$1 = (function () {
      var schemeRegex = /(?:[A-Za-z][-.+A-Za-z0-9]{0,63}:(?![A-Za-z][-.+A-Za-z0-9]{0,63}:\/\/)(?!\d+\/?)(?:\/\/)?)/, // match protocol, allow in format "http://" or "mailto:". However, do not match the first part of something like 'link:http://www.google.com' (i.e. don't match "link:"). Also, make sure we don't interpret 'google.com:8000' as if 'google.com' was a protocol here (i.e. ignore a trailing port number in this regex)
      wwwRegex = /(?:www\.)/, // starting with 'www.'
      // Allow optional path, query string, and hash anchor, not ending in the following characters: "?!:,.;"
      // http://blog.codinghorror.com/the-problem-with-urls/
      urlSuffixRegex = new RegExp('[/?#](?:[' + alphaNumericAndMarksCharsStr + '\\-+&@#/%=~_()|\'$*\\[\\]{}?!:,.;^\u2713]*[' + alphaNumericAndMarksCharsStr + '\\-+&@#/%=~_()|\'$*\\[\\]{}\u2713])?');
      return new RegExp([
          '(?:',
          '(',
          schemeRegex.source,
          getDomainNameStr(2),
          ')',
          '|',
          '(',
          '(//)?',
          wwwRegex.source,
          getDomainNameStr(6),
          ')',
          '|',
          '(',
          '(//)?',
          getDomainNameStr(10) + '\\.',
          tldRegex.source,
          '(?![-' + alphaNumericCharsStr + '])',
          ')',
          ')',
          '(?::[0-9]+)?',
          '(?:' + urlSuffixRegex.source + ')?' // match for path, query string, and/or hash anchor - optional
      ].join(""), 'gi');
  })();
  var wordCharRegExp = new RegExp('[' + alphaNumericAndMarksCharsStr + ']');
  /**
   * @class Autolinker.matcher.Url
   * @extends Autolinker.matcher.Matcher
   *
   * Matcher to find URL matches in an input string.
   *
   * See this class's superclass ({@link Autolinker.matcher.Matcher}) for more details.
   */
  var UrlMatcher = /** @class */ (function (_super) {
      __extends(UrlMatcher, _super);
      /**
       * @method constructor
       * @param {Object} cfg The configuration properties for the Match instance,
       *   specified in an Object (map).
       */
      function UrlMatcher(cfg) {
          var _this = _super.call(this, cfg) || this;
          /**
           * @cfg {Object} stripPrefix (required)
           *
           * The Object form of {@link Autolinker#cfg-stripPrefix}.
           */
          _this.stripPrefix = { scheme: true, www: true }; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @cfg {Boolean} stripTrailingSlash (required)
           * @inheritdoc Autolinker#stripTrailingSlash
           */
          _this.stripTrailingSlash = true; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @cfg {Boolean} decodePercentEncoding (required)
           * @inheritdoc Autolinker#decodePercentEncoding
           */
          _this.decodePercentEncoding = true; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @protected
           * @property {RegExp} matcherRegex
           *
           * The regular expression to match URLs with an optional scheme, port
           * number, path, query string, and hash anchor.
           *
           * Example matches:
           *
           *     http://google.com
           *     www.google.com
           *     google.com/path/to/file?q1=1&q2=2#myAnchor
           *
           *
           * This regular expression will have the following capturing groups:
           *
           * 1.  Group that matches a scheme-prefixed URL (i.e. 'http://google.com').
           *     This is used to match scheme URLs with just a single word, such as
           *     'http://localhost', where we won't double check that the domain name
           *     has at least one dot ('.') in it.
           * 2.  Group that matches a 'www.' prefixed URL. This is only matched if the
           *     'www.' text was not prefixed by a scheme (i.e.: not prefixed by
           *     'http://', 'ftp:', etc.)
           * 3.  A protocol-relative ('//') match for the case of a 'www.' prefixed
           *     URL. Will be an empty string if it is not a protocol-relative match.
           *     We need to know the character before the '//' in order to determine
           *     if it is a valid match or the // was in a string we don't want to
           *     auto-link.
           * 4.  Group that matches a known TLD (top level domain), when a scheme
           *     or 'www.'-prefixed domain is not matched.
           * 5.  A protocol-relative ('//') match for the case of a known TLD prefixed
           *     URL. Will be an empty string if it is not a protocol-relative match.
           *     See #3 for more info.
           */
          _this.matcherRegex = matcherRegex$1;
          /**
           * A regular expression to use to check the character before a protocol-relative
           * URL match. We don't want to match a protocol-relative URL if it is part
           * of another word.
           *
           * For example, we want to match something like "Go to: //google.com",
           * but we don't want to match something like "abc//google.com"
           *
           * This regular expression is used to test the character before the '//'.
           *
           * @protected
           * @type {RegExp} wordCharRegExp
           */
          _this.wordCharRegExp = wordCharRegExp;
          _this.stripPrefix = cfg.stripPrefix;
          _this.stripTrailingSlash = cfg.stripTrailingSlash;
          _this.decodePercentEncoding = cfg.decodePercentEncoding;
          return _this;
      }
      /**
       * @inheritdoc
       */
      UrlMatcher.prototype.parseMatches = function (text) {
          var matcherRegex = this.matcherRegex, stripPrefix = this.stripPrefix, stripTrailingSlash = this.stripTrailingSlash, decodePercentEncoding = this.decodePercentEncoding, tagBuilder = this.tagBuilder, matches = [], match;
          var _loop_1 = function () {
              var matchStr = match[0], schemeUrlMatch = match[1], wwwUrlMatch = match[4], wwwProtocolRelativeMatch = match[5], 
              //tldUrlMatch = match[ 8 ],  -- not needed at the moment
              tldProtocolRelativeMatch = match[9], offset = match.index, protocolRelativeMatch = wwwProtocolRelativeMatch || tldProtocolRelativeMatch, prevChar = text.charAt(offset - 1);
              if (!UrlMatchValidator.isValid(matchStr, schemeUrlMatch)) {
                  return "continue";
              }
              // If the match is preceded by an '@' character, then it is either
              // an email address or a username. Skip these types of matches.
              if (offset > 0 && prevChar === '@') {
                  return "continue";
              }
              // If it's a protocol-relative '//' match, but the character before the '//'
              // was a word character (i.e. a letter/number), then we found the '//' in the
              // middle of another word (such as "asdf//asdf.com"). In this case, skip the
              // match.
              if (offset > 0 && protocolRelativeMatch && this_1.wordCharRegExp.test(prevChar)) {
                  return "continue";
              }
              // If the URL ends with a question mark, don't include the question
              // mark as part of the URL. We'll assume the question mark was the
              // end of a sentence, such as: "Going to google.com?"
              if (/\?$/.test(matchStr)) {
                  matchStr = matchStr.substr(0, matchStr.length - 1);
              }
              // Handle a closing parenthesis or square bracket at the end of the 
              // match, and exclude it if there is not a matching open parenthesis 
              // or square bracket in the match itself.
              if (this_1.matchHasUnbalancedClosingParen(matchStr)) {
                  matchStr = matchStr.substr(0, matchStr.length - 1); // remove the trailing ")"
              }
              else {
                  // Handle an invalid character after the TLD
                  var pos = this_1.matchHasInvalidCharAfterTld(matchStr, schemeUrlMatch);
                  if (pos > -1) {
                      matchStr = matchStr.substr(0, pos); // remove the trailing invalid chars
                  }
              }
              // The autolinker accepts many characters in a url's scheme (like `fake://test.com`).
              // However, in cases where a URL is missing whitespace before an obvious link,
              // (for example: `nowhitespacehttp://www.test.com`), we only want the match to start
              // at the http:// part. We will check if the match contains a common scheme and then 
              // shift the match to start from there. 		
              var foundCommonScheme = ['http://', 'https://'].find(function (commonScheme) { return !!schemeUrlMatch && schemeUrlMatch.indexOf(commonScheme) !== -1; });
              if (foundCommonScheme) {
                  // If we found an overmatched URL, we want to find the index
                  // of where the match should start and shift the match to
                  // start from the beginning of the common scheme
                  var indexOfSchemeStart = matchStr.indexOf(foundCommonScheme);
                  matchStr = matchStr.substr(indexOfSchemeStart);
                  schemeUrlMatch = schemeUrlMatch.substr(indexOfSchemeStart);
                  offset = offset + indexOfSchemeStart;
              }
              var urlMatchType = schemeUrlMatch ? 'scheme' : (wwwUrlMatch ? 'www' : 'tld'), protocolUrlMatch = !!schemeUrlMatch;
              matches.push(new UrlMatch({
                  tagBuilder: tagBuilder,
                  matchedText: matchStr,
                  offset: offset,
                  urlMatchType: urlMatchType,
                  url: matchStr,
                  protocolUrlMatch: protocolUrlMatch,
                  protocolRelativeMatch: !!protocolRelativeMatch,
                  stripPrefix: stripPrefix,
                  stripTrailingSlash: stripTrailingSlash,
                  decodePercentEncoding: decodePercentEncoding,
              }));
          };
          var this_1 = this;
          while ((match = matcherRegex.exec(text)) !== null) {
              _loop_1();
          }
          return matches;
      };
      /**
       * Determines if a match found has an unmatched closing parenthesis,
       * square bracket or curly bracket. If so, the symbol will be removed
       * from the match itself, and appended after the generated anchor tag.
       *
       * A match may have an extra closing parenthesis at the end of the match
       * because the regular expression must include parenthesis for URLs such as
       * "wikipedia.com/something_(disambiguation)", which should be auto-linked.
       *
       * However, an extra parenthesis *will* be included when the URL itself is
       * wrapped in parenthesis, such as in the case of:
       *     "(wikipedia.com/something_(disambiguation))"
       * In this case, the last closing parenthesis should *not* be part of the
       * URL itself, and this method will return `true`.
       *
       * For square brackets in URLs such as in PHP arrays, the same behavior as
       * parenthesis discussed above should happen:
       *     "[http://www.example.com/foo.php?bar[]=1&bar[]=2&bar[]=3]"
       * The closing square bracket should not be part of the URL itself, and this
       * method will return `true`.
       *
       * @protected
       * @param {String} matchStr The full match string from the {@link #matcherRegex}.
       * @return {Boolean} `true` if there is an unbalanced closing parenthesis or
       *   square bracket at the end of the `matchStr`, `false` otherwise.
       */
      UrlMatcher.prototype.matchHasUnbalancedClosingParen = function (matchStr) {
          var endChar = matchStr.charAt(matchStr.length - 1);
          var startChar;
          if (endChar === ')') {
              startChar = '(';
          }
          else if (endChar === ']') {
              startChar = '[';
          }
          else if (endChar === '}') {
              startChar = '{';
          }
          else {
              return false; // not a close parenthesis or square bracket
          }
          // Find if there are the same number of open braces as close braces in
          // the URL string, minus the last character (which we have already 
          // determined to be either ')', ']' or '}'
          var numOpenBraces = 0;
          for (var i = 0, len = matchStr.length - 1; i < len; i++) {
              var char = matchStr.charAt(i);
              if (char === startChar) {
                  numOpenBraces++;
              }
              else if (char === endChar) {
                  numOpenBraces = Math.max(numOpenBraces - 1, 0);
              }
          }
          // If the number of open braces matches the number of close braces in
          // the URL minus the last character, then the match has *unbalanced*
          // braces because of the last character. Example of unbalanced braces
          // from the regex match:
          //     "http://example.com?a[]=1]"
          if (numOpenBraces === 0) {
              return true;
          }
          return false;
      };
      /**
       * Determine if there's an invalid character after the TLD in a URL. Valid
       * characters after TLD are ':/?#'. Exclude scheme matched URLs from this
       * check.
       *
       * @protected
       * @param {String} urlMatch The matched URL, if there was one. Will be an
       *   empty string if the match is not a URL match.
       * @param {String} schemeUrlMatch The match URL string for a scheme
       *   match. Ex: 'http://yahoo.com'. This is used to match something like
       *   'http://localhost', where we won't double check that the domain name
       *   has at least one '.' in it.
       * @return {Number} the position where the invalid character was found. If
       *   no such character was found, returns -1
       */
      UrlMatcher.prototype.matchHasInvalidCharAfterTld = function (urlMatch, schemeUrlMatch) {
          if (!urlMatch) {
              return -1;
          }
          var offset = 0;
          if (schemeUrlMatch) {
              offset = urlMatch.indexOf(':');
              urlMatch = urlMatch.slice(offset);
          }
          var re = new RegExp("^((.?\/\/)?[-." + alphaNumericAndMarksCharsStr + "]*[-" + alphaNumericAndMarksCharsStr + "]\\.[-" + alphaNumericAndMarksCharsStr + "]+)");
          var res = re.exec(urlMatch);
          if (res === null) {
              return -1;
          }
          offset += res[1].length;
          urlMatch = urlMatch.slice(res[1].length);
          if (/^[^-.A-Za-z0-9:\/?#]/.test(urlMatch)) {
              return offset;
          }
          return -1;
      };
      return UrlMatcher;
  }(Matcher));

  // RegExp objects which are shared by all instances of HashtagMatcher. These are
  // here to avoid re-instantiating the RegExp objects if `Autolinker.link()` is
  // called multiple times, thus instantiating HashtagMatcher and its RegExp 
  // objects each time (which is very expensive - see https://github.com/gregjacobs/Autolinker.js/issues/314). 
  // See descriptions of the properties where they are used for details about them
  var matcherRegex = new RegExp("#[_".concat(alphaNumericAndMarksCharsStr, "]{1,139}(?![_").concat(alphaNumericAndMarksCharsStr, "])"), 'g'); // lookahead used to make sure we don't match something above 139 characters
  var nonWordCharRegex$1 = new RegExp('[^' + alphaNumericAndMarksCharsStr + ']');
  /**
   * @class Autolinker.matcher.Hashtag
   * @extends Autolinker.matcher.Matcher
   *
   * Matcher to find HashtagMatch matches in an input string.
   */
  var HashtagMatcher = /** @class */ (function (_super) {
      __extends(HashtagMatcher, _super);
      /**
       * @method constructor
       * @param {Object} cfg The configuration properties for the Match instance,
       *   specified in an Object (map).
       */
      function HashtagMatcher(cfg) {
          var _this = _super.call(this, cfg) || this;
          /**
           * @cfg {String} serviceName
           *
           * The service to point hashtag matches to. See {@link Autolinker#hashtag}
           * for available values.
           */
          _this.serviceName = 'twitter'; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * The regular expression to match Hashtags. Example match:
           *
           *     #asdf
           *
           * @protected
           * @property {RegExp} matcherRegex
           */
          _this.matcherRegex = matcherRegex;
          /**
           * The regular expression to use to check the character before a username match to
           * make sure we didn't accidentally match an email address.
           *
           * For example, the string "asdf@asdf.com" should not match "@asdf" as a username.
           *
           * @protected
           * @property {RegExp} nonWordCharRegex
           */
          _this.nonWordCharRegex = nonWordCharRegex$1;
          _this.serviceName = cfg.serviceName;
          return _this;
      }
      /**
       * @inheritdoc
       */
      HashtagMatcher.prototype.parseMatches = function (text) {
          var matcherRegex = this.matcherRegex, nonWordCharRegex = this.nonWordCharRegex, serviceName = this.serviceName, tagBuilder = this.tagBuilder, matches = [], match;
          while ((match = matcherRegex.exec(text)) !== null) {
              var offset = match.index, prevChar = text.charAt(offset - 1);
              // If we found the match at the beginning of the string, or we found the match
              // and there is a whitespace char in front of it (meaning it is not a '#' char
              // in the middle of a word), then it is a hashtag match.
              if (offset === 0 || nonWordCharRegex.test(prevChar)) {
                  var matchedText = match[0], hashtag = match[0].slice(1); // strip off the '#' character at the beginning
                  matches.push(new HashtagMatch({
                      tagBuilder: tagBuilder,
                      matchedText: matchedText,
                      offset: offset,
                      serviceName: serviceName,
                      hashtag: hashtag
                  }));
              }
          }
          return matches;
      };
      return HashtagMatcher;
  }(Matcher));

  // RegExp objects which are shared by all instances of PhoneMatcher. These are
  // here to avoid re-instantiating the RegExp objects if `Autolinker.link()` is
  // called multiple times, thus instantiating PhoneMatcher and its RegExp
  // objects each time (which is very expensive - see https://github.com/gregjacobs/Autolinker.js/issues/314).
  // See descriptions of the properties where they are used for details about them
  // Over the years, many people have added to this regex, but it should have been
  // split up by country. Maybe one day we can break this down.
  var mostPhoneNumbers = /(?:(?:(?:(\+)?\d{1,3}[-\040.]?)?\(?\d{3}\)?[-\040.]?\d{3}[-\040.]?\d{4})|(?:(\+)(?:9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|4[987654310]|3[9643210]|2[70]|7|1)[-\040.]?(?:\d[-\040.]?){6,12}\d+))([,;]+[0-9]+#?)*/;
  // Regex for Japanese phone numbers
  var japanesePhoneRe = /(0([1-9]{1}-?[1-9]\d{3}|[1-9]{2}-?\d{3}|[1-9]{2}\d{1}-?\d{2}|[1-9]{2}\d{2}-?\d{1})-?\d{4}|0[789]0-?\d{4}-?\d{4}|050-?\d{4}-?\d{4})/;
  // Combined regex
  var phoneMatcherRegex = new RegExp("".concat(mostPhoneNumbers.source, "|").concat(japanesePhoneRe.source), 'g');
  /**
   * @class Autolinker.matcher.Phone
   * @extends Autolinker.matcher.Matcher
   *
   * Matcher to find Phone number matches in an input string.
   *
   * See this class's superclass ({@link Autolinker.matcher.Matcher}) for more
   * details.
   */
  var PhoneMatcher = /** @class */ (function (_super) {
      __extends(PhoneMatcher, _super);
      function PhoneMatcher() {
          var _this = _super !== null && _super.apply(this, arguments) || this;
          /**
           * The regular expression to match Phone numbers. Example matches:
           *
           *     (123) 456-7890
           *     123 456 7890
           *     123-456-7890
           *     +18004441234,,;,10226420346#
           *     +1 (800) 444 1234
           *     10226420346#
           *     1-800-444-1234,1022,64,20346#
           *
           * This regular expression has the following capturing groups:
           *
           * 1 or 2. The prefixed '+' sign, if there is one.
           *
           * @protected
           * @property {RegExp} matcherRegex
           */
          _this.matcherRegex = phoneMatcherRegex;
          return _this;
      }
      /**
       * @inheritdoc
       */
      PhoneMatcher.prototype.parseMatches = function (text) {
          var matcherRegex = this.matcherRegex, tagBuilder = this.tagBuilder, matches = [], match;
          while ((match = matcherRegex.exec(text)) !== null) {
              // Remove non-numeric values from phone number string
              var matchedText = match[0], cleanNumber = matchedText.replace(/[^0-9,;#]/g, ''), // strip out non-digit characters exclude comma semicolon and #
              plusSign = !!(match[1] || match[2]), // match[ 1 ] or match[ 2 ] is the prefixed plus sign, if there is one
              before = match.index == 0 ? '' : text.substr(match.index - 1, 1), after = text.substr(match.index + matchedText.length, 1), contextClear = !before.match(/\d/) && !after.match(/\d/);
              if (this.testMatch(match[3]) && this.testMatch(matchedText) && contextClear) {
                  matches.push(new PhoneMatch({
                      tagBuilder: tagBuilder,
                      matchedText: matchedText,
                      offset: match.index,
                      number: cleanNumber,
                      plusSign: plusSign
                  }));
              }
          }
          return matches;
      };
      PhoneMatcher.prototype.testMatch = function (text) {
          return nonDigitRe.test(text);
      };
      return PhoneMatcher;
  }(Matcher));

  // RegExp objects which are shared by all instances of MentionMatcher. These are
  // here to avoid re-instantiating the RegExp objects if `Autolinker.link()` is
  // called multiple times, thus instantiating MentionMatcher and its RegExp 
  // objects each time (which is very expensive - see https://github.com/gregjacobs/Autolinker.js/issues/314). 
  // See descriptions of the properties where they are used for details about them
  var twitterRegex = new RegExp("@[_".concat(alphaNumericAndMarksCharsStr, "]{1,50}(?![_").concat(alphaNumericAndMarksCharsStr, "])"), 'g'); // lookahead used to make sure we don't match something above 50 characters
  var instagramRegex = new RegExp("@[_.".concat(alphaNumericAndMarksCharsStr, "]{1,30}(?![_").concat(alphaNumericAndMarksCharsStr, "])"), 'g'); // lookahead used to make sure we don't match something above 30 characters
  var soundcloudRegex = new RegExp("@[-_.".concat(alphaNumericAndMarksCharsStr, "]{1,50}(?![-_").concat(alphaNumericAndMarksCharsStr, "])"), 'g'); // lookahead used to make sure we don't match something above 50 characters
  // TikTok usernames are 1-24 characters containing letters, numbers, underscores
  // and periods, but cannot end in a period: https://support.tiktok.com/en/getting-started/setting-up-your-profile/changing-your-username
  var tiktokRegex = new RegExp("@[_.".concat(alphaNumericAndMarksCharsStr, "]{1,23}[_").concat(alphaNumericAndMarksCharsStr, "](?![_").concat(alphaNumericAndMarksCharsStr, "])"), 'g'); // lookahead used to make sure we don't match something above 24 characters
  var nonWordCharRegex = new RegExp('[^' + alphaNumericAndMarksCharsStr + ']');
  /**
   * @class Autolinker.matcher.Mention
   * @extends Autolinker.matcher.Matcher
   *
   * Matcher to find/replace username matches in an input string.
   */
  var MentionMatcher = /** @class */ (function (_super) {
      __extends(MentionMatcher, _super);
      /**
       * @method constructor
       * @param {Object} cfg The configuration properties for the Match instance,
       *   specified in an Object (map).
       */
      function MentionMatcher(cfg) {
          var _this = _super.call(this, cfg) || this;
          /**
           * @cfg {'twitter'/'instagram'/'soundcloud'} protected
           *
           * The name of service to link @mentions to.
           *
           * Valid values are: 'twitter', 'instagram', 'soundcloud', or 'tiktok'
           */
          _this.serviceName = 'twitter'; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * Hash of regular expression to match username handles. Example match:
           *
           *     @asdf
           *
           * @private
           * @property {Object} matcherRegexes
           */
          _this.matcherRegexes = {
              'twitter': twitterRegex,
              'instagram': instagramRegex,
              'soundcloud': soundcloudRegex,
              'tiktok': tiktokRegex
          };
          /**
           * The regular expression to use to check the character before a username match to
           * make sure we didn't accidentally match an email address.
           *
           * For example, the string "asdf@asdf.com" should not match "@asdf" as a username.
           *
           * @private
           * @property {RegExp} nonWordCharRegex
           */
          _this.nonWordCharRegex = nonWordCharRegex;
          _this.serviceName = cfg.serviceName;
          return _this;
      }
      /**
       * @inheritdoc
       */
      MentionMatcher.prototype.parseMatches = function (text) {
          var serviceName = this.serviceName, matcherRegex = this.matcherRegexes[this.serviceName], nonWordCharRegex = this.nonWordCharRegex, tagBuilder = this.tagBuilder, matches = [], match;
          if (!matcherRegex) {
              return matches;
          }
          while ((match = matcherRegex.exec(text)) !== null) {
              var offset = match.index, prevChar = text.charAt(offset - 1);
              // If we found the match at the beginning of the string, or we found the match
              // and there is a whitespace char in front of it (meaning it is not an email
              // address), then it is a username match.
              if (offset === 0 || nonWordCharRegex.test(prevChar)) {
                  var matchedText = match[0].replace(/\.+$/g, ''), // strip off trailing .
                  mention = matchedText.slice(1); // strip off the '@' character at the beginning
                  matches.push(new MentionMatch({
                      tagBuilder: tagBuilder,
                      matchedText: matchedText,
                      offset: offset,
                      serviceName: serviceName,
                      mention: mention
                  }));
              }
          }
          return matches;
      };
      return MentionMatcher;
  }(Matcher));

  // For debugging: search for other "For debugging" lines
  // import CliTable from 'cli-table';
  /**
   * Parses an HTML string, calling the callbacks to notify of tags and text.
   *
   * ## History
   *
   * This file previously used a regular expression to find html tags in the input
   * text. Unfortunately, we ran into a bunch of catastrophic backtracking issues
   * with certain input text, causing Autolinker to either hang or just take a
   * really long time to parse the string.
   *
   * The current code is intended to be a O(n) algorithm that walks through
   * the string in one pass, and tries to be as cheap as possible. We don't need
   * to implement the full HTML spec, but rather simply determine where the string
   * looks like an HTML tag, and where it looks like text (so that we can autolink
   * that).
   *
   * This state machine parser is intended just to be a simple but performant
   * parser of HTML for the subset of requirements we have. We simply need to:
   *
   * 1. Determine where HTML tags are
   * 2. Determine the tag name (Autolinker specifically only cares about <a>,
   *    <script>, and <style> tags, so as not to link any text within them)
   *
   * We don't need to:
   *
   * 1. Create a parse tree
   * 2. Auto-close tags with invalid markup
   * 3. etc.
   *
   * The other intention behind this is that we didn't want to add external
   * dependencies on the Autolinker utility which would increase its size. For
   * instance, adding htmlparser2 adds 125kb to the minified output file,
   * increasing its final size from 47kb to 172kb (at the time of writing). It
   * also doesn't work exactly correctly, treating the string "<3 blah blah blah"
   * as an HTML tag.
   *
   * Reference for HTML spec:
   *
   *     https://www.w3.org/TR/html51/syntax.html#sec-tokenization
   *
   * @param {String} html The HTML to parse
   * @param {Object} callbacks
   * @param {Function} callbacks.onOpenTag Callback function to call when an open
   *   tag is parsed. Called with the tagName as its argument.
   * @param {Function} callbacks.onCloseTag Callback function to call when a close
   *   tag is parsed. Called with the tagName as its argument. If a self-closing
   *   tag is found, `onCloseTag` is called immediately after `onOpenTag`.
   * @param {Function} callbacks.onText Callback function to call when text (i.e
   *   not an HTML tag) is parsed. Called with the text (string) as its first
   *   argument, and offset (number) into the string as its second.
   */
  function parseHtml(html, _a) {
      var onOpenTag = _a.onOpenTag, onCloseTag = _a.onCloseTag, onText = _a.onText, onComment = _a.onComment, onDoctype = _a.onDoctype;
      var noCurrentTag = new CurrentTag();
      var charIdx = 0, len = html.length, state = 0 /* Data */, currentDataIdx = 0, // where the current data start index is
      currentTag = noCurrentTag; // describes the current tag that is being read
      // For debugging: search for other "For debugging" lines
      // const table = new CliTable( {
      // 	head: [ 'charIdx', 'char', 'state', 'currentDataIdx', 'currentOpenTagIdx', 'tag.type' ]
      // } );
      while (charIdx < len) {
          var char = html.charAt(charIdx);
          // For debugging: search for other "For debugging" lines
          // ALSO: Temporarily remove the 'const' keyword on the State enum
          // table.push( 
          // 	[ charIdx, char, State[ state ], currentDataIdx, currentTag.idx, currentTag.idx === -1 ? '' : currentTag.type ] 
          // );
          switch (state) {
              case 0 /* Data */:
                  stateData(char);
                  break;
              case 1 /* TagOpen */:
                  stateTagOpen(char);
                  break;
              case 2 /* EndTagOpen */:
                  stateEndTagOpen(char);
                  break;
              case 3 /* TagName */:
                  stateTagName(char);
                  break;
              case 4 /* BeforeAttributeName */:
                  stateBeforeAttributeName(char);
                  break;
              case 5 /* AttributeName */:
                  stateAttributeName(char);
                  break;
              case 6 /* AfterAttributeName */:
                  stateAfterAttributeName(char);
                  break;
              case 7 /* BeforeAttributeValue */:
                  stateBeforeAttributeValue(char);
                  break;
              case 8 /* AttributeValueDoubleQuoted */:
                  stateAttributeValueDoubleQuoted(char);
                  break;
              case 9 /* AttributeValueSingleQuoted */:
                  stateAttributeValueSingleQuoted(char);
                  break;
              case 10 /* AttributeValueUnquoted */:
                  stateAttributeValueUnquoted(char);
                  break;
              case 11 /* AfterAttributeValueQuoted */:
                  stateAfterAttributeValueQuoted(char);
                  break;
              case 12 /* SelfClosingStartTag */:
                  stateSelfClosingStartTag(char);
                  break;
              case 13 /* MarkupDeclarationOpenState */:
                  stateMarkupDeclarationOpen();
                  break;
              case 14 /* CommentStart */:
                  stateCommentStart(char);
                  break;
              case 15 /* CommentStartDash */:
                  stateCommentStartDash(char);
                  break;
              case 16 /* Comment */:
                  stateComment(char);
                  break;
              case 17 /* CommentEndDash */:
                  stateCommentEndDash(char);
                  break;
              case 18 /* CommentEnd */:
                  stateCommentEnd(char);
                  break;
              case 19 /* CommentEndBang */:
                  stateCommentEndBang(char);
                  break;
              case 20 /* Doctype */:
                  stateDoctype(char);
                  break;
              default:
                  throwUnhandledCaseError(state);
          }
          // For debugging: search for other "For debugging" lines
          // ALSO: Temporarily remove the 'const' keyword on the State enum
          // table.push( 
          // 	[ charIdx, char, State[ state ], currentDataIdx, currentTag.idx, currentTag.idx === -1 ? '' : currentTag.type ] 
          // );
          charIdx++;
      }
      if (currentDataIdx < charIdx) {
          emitText();
      }
      // For debugging: search for other "For debugging" lines
      // console.log( '\n' + table.toString() );
      // Called when non-tags are being read (i.e. the text around HTML †ags)
      // https://www.w3.org/TR/html51/syntax.html#data-state
      function stateData(char) {
          if (char === '<') {
              startNewTag();
          }
      }
      // Called after a '<' is read from the Data state
      // https://www.w3.org/TR/html51/syntax.html#tag-open-state
      function stateTagOpen(char) {
          if (char === '!') {
              state = 13 /* MarkupDeclarationOpenState */;
          }
          else if (char === '/') {
              state = 2 /* EndTagOpen */;
              currentTag = new CurrentTag(__assign(__assign({}, currentTag), { isClosing: true }));
          }
          else if (char === '<') {
              // start of another tag (ignore the previous, incomplete one)
              startNewTag();
          }
          else if (letterRe.test(char)) {
              // tag name start (and no '/' read)
              state = 3 /* TagName */;
              currentTag = new CurrentTag(__assign(__assign({}, currentTag), { isOpening: true }));
          }
          else {
              // Any other 
              state = 0 /* Data */;
              currentTag = noCurrentTag;
          }
      }
      // After a '<x', '</x' sequence is read (where 'x' is a letter character), 
      // this is to continue reading the tag name
      // https://www.w3.org/TR/html51/syntax.html#tag-name-state
      function stateTagName(char) {
          if (whitespaceRe.test(char)) {
              currentTag = new CurrentTag(__assign(__assign({}, currentTag), { name: captureTagName() }));
              state = 4 /* BeforeAttributeName */;
          }
          else if (char === '<') {
              // start of another tag (ignore the previous, incomplete one)
              startNewTag();
          }
          else if (char === '/') {
              currentTag = new CurrentTag(__assign(__assign({}, currentTag), { name: captureTagName() }));
              state = 12 /* SelfClosingStartTag */;
          }
          else if (char === '>') {
              currentTag = new CurrentTag(__assign(__assign({}, currentTag), { name: captureTagName() }));
              emitTagAndPreviousTextNode(); // resets to Data state as well
          }
          else if (!letterRe.test(char) && !digitRe.test(char) && char !== ':') {
              // Anything else that does not form an html tag. Note: the colon 
              // character is accepted for XML namespaced tags
              resetToDataState();
          }
          else ;
      }
      // Called after the '/' is read from a '</' sequence
      // https://www.w3.org/TR/html51/syntax.html#end-tag-open-state
      function stateEndTagOpen(char) {
          if (char === '>') { // parse error. Encountered "</>". Skip it without treating as a tag
              resetToDataState();
          }
          else if (letterRe.test(char)) {
              state = 3 /* TagName */;
          }
          else {
              // some other non-tag-like character, don't treat this as a tag
              resetToDataState();
          }
      }
      // https://www.w3.org/TR/html51/syntax.html#before-attribute-name-state
      function stateBeforeAttributeName(char) {
          if (whitespaceRe.test(char)) ;
          else if (char === '/') {
              state = 12 /* SelfClosingStartTag */;
          }
          else if (char === '>') {
              emitTagAndPreviousTextNode(); // resets to Data state as well
          }
          else if (char === '<') {
              // start of another tag (ignore the previous, incomplete one)
              startNewTag();
          }
          else if (char === "=" || quoteRe.test(char) || controlCharsRe.test(char)) {
              // "Parse error" characters that, according to the spec, should be
              // appended to the attribute name, but we'll treat these characters
              // as not forming a real HTML tag
              resetToDataState();
          }
          else {
              // Any other char, start of a new attribute name
              state = 5 /* AttributeName */;
          }
      }
      // https://www.w3.org/TR/html51/syntax.html#attribute-name-state
      function stateAttributeName(char) {
          if (whitespaceRe.test(char)) {
              state = 6 /* AfterAttributeName */;
          }
          else if (char === '/') {
              state = 12 /* SelfClosingStartTag */;
          }
          else if (char === '=') {
              state = 7 /* BeforeAttributeValue */;
          }
          else if (char === '>') {
              emitTagAndPreviousTextNode(); // resets to Data state as well
          }
          else if (char === '<') {
              // start of another tag (ignore the previous, incomplete one)
              startNewTag();
          }
          else if (quoteRe.test(char)) {
              // "Parse error" characters that, according to the spec, should be
              // appended to the attribute name, but we'll treat these characters
              // as not forming a real HTML tag
              resetToDataState();
          }
          else ;
      }
      // https://www.w3.org/TR/html51/syntax.html#after-attribute-name-state
      function stateAfterAttributeName(char) {
          if (whitespaceRe.test(char)) ;
          else if (char === '/') {
              state = 12 /* SelfClosingStartTag */;
          }
          else if (char === '=') {
              state = 7 /* BeforeAttributeValue */;
          }
          else if (char === '>') {
              emitTagAndPreviousTextNode();
          }
          else if (char === '<') {
              // start of another tag (ignore the previous, incomplete one)
              startNewTag();
          }
          else if (quoteRe.test(char)) {
              // "Parse error" characters that, according to the spec, should be
              // appended to the attribute name, but we'll treat these characters
              // as not forming a real HTML tag
              resetToDataState();
          }
          else {
              // Any other character, start a new attribute in the current tag
              state = 5 /* AttributeName */;
          }
      }
      // https://www.w3.org/TR/html51/syntax.html#before-attribute-value-state
      function stateBeforeAttributeValue(char) {
          if (whitespaceRe.test(char)) ;
          else if (char === "\"") {
              state = 8 /* AttributeValueDoubleQuoted */;
          }
          else if (char === "'") {
              state = 9 /* AttributeValueSingleQuoted */;
          }
          else if (/[>=`]/.test(char)) {
              // Invalid chars after an '=' for an attribute value, don't count 
              // the current tag as an HTML tag
              resetToDataState();
          }
          else if (char === '<') {
              // start of another tag (ignore the previous, incomplete one)
              startNewTag();
          }
          else {
              // Any other character, consider it an unquoted attribute value
              state = 10 /* AttributeValueUnquoted */;
          }
      }
      // https://www.w3.org/TR/html51/syntax.html#attribute-value-double-quoted-state
      function stateAttributeValueDoubleQuoted(char) {
          if (char === "\"") { // end the current double-quoted attribute
              state = 11 /* AfterAttributeValueQuoted */;
          }
      }
      // https://www.w3.org/TR/html51/syntax.html#attribute-value-single-quoted-state
      function stateAttributeValueSingleQuoted(char) {
          if (char === "'") { // end the current single-quoted attribute
              state = 11 /* AfterAttributeValueQuoted */;
          }
      }
      // https://www.w3.org/TR/html51/syntax.html#attribute-value-unquoted-state
      function stateAttributeValueUnquoted(char) {
          if (whitespaceRe.test(char)) {
              state = 4 /* BeforeAttributeName */;
          }
          else if (char === '>') {
              emitTagAndPreviousTextNode();
          }
          else if (char === '<') {
              // start of another tag (ignore the previous, incomplete one)
              startNewTag();
          }
          else ;
      }
      // https://www.w3.org/TR/html51/syntax.html#after-attribute-value-quoted-state
      function stateAfterAttributeValueQuoted(char) {
          if (whitespaceRe.test(char)) {
              state = 4 /* BeforeAttributeName */;
          }
          else if (char === '/') {
              state = 12 /* SelfClosingStartTag */;
          }
          else if (char === '>') {
              emitTagAndPreviousTextNode();
          }
          else if (char === '<') {
              // start of another tag (ignore the previous, incomplete one)
              startNewTag();
          }
          else {
              // Any other character, "parse error". Spec says to switch to the
              // BeforeAttributeState and re-consume the character, as it may be
              // the start of a new attribute name
              state = 4 /* BeforeAttributeName */;
              reconsumeCurrentCharacter();
          }
      }
      // A '/' has just been read in the current tag (presumably for '/>'), and 
      // this handles the next character
      // https://www.w3.org/TR/html51/syntax.html#self-closing-start-tag-state
      function stateSelfClosingStartTag(char) {
          if (char === '>') {
              currentTag = new CurrentTag(__assign(__assign({}, currentTag), { isClosing: true }));
              emitTagAndPreviousTextNode(); // resets to Data state as well
          }
          else {
              state = 4 /* BeforeAttributeName */;
          }
      }
      // https://www.w3.org/TR/html51/syntax.html#markup-declaration-open-state
      // (HTML Comments or !DOCTYPE)
      function stateMarkupDeclarationOpen(char) {
          if (html.substr(charIdx, 2) === '--') { // html comment
              charIdx += 2; // "consume" characters
              currentTag = new CurrentTag(__assign(__assign({}, currentTag), { type: 'comment' }));
              state = 14 /* CommentStart */;
          }
          else if (html.substr(charIdx, 7).toUpperCase() === 'DOCTYPE') {
              charIdx += 7; // "consume" characters
              currentTag = new CurrentTag(__assign(__assign({}, currentTag), { type: 'doctype' }));
              state = 20 /* Doctype */;
          }
          else {
              // At this point, the spec specifies that the state machine should
              // enter the "bogus comment" state, in which case any character(s) 
              // after the '<!' that were read should become an HTML comment up
              // until the first '>' that is read (or EOF). Instead, we'll assume
              // that a user just typed '<!' as part of text data
              resetToDataState();
          }
      }
      // Handles after the sequence '<!--' has been read
      // https://www.w3.org/TR/html51/syntax.html#comment-start-state
      function stateCommentStart(char) {
          if (char === '-') {
              // We've read the sequence '<!---' at this point (3 dashes)
              state = 15 /* CommentStartDash */;
          }
          else if (char === '>') {
              // At this point, we'll assume the comment wasn't a real comment
              // so we'll just emit it as data. We basically read the sequence 
              // '<!-->'
              resetToDataState();
          }
          else {
              // Any other char, take it as part of the comment
              state = 16 /* Comment */;
          }
      }
      // We've read the sequence '<!---' at this point (3 dashes)
      // https://www.w3.org/TR/html51/syntax.html#comment-start-dash-state
      function stateCommentStartDash(char) {
          if (char === '-') {
              // We've read '<!----' (4 dashes) at this point
              state = 18 /* CommentEnd */;
          }
          else if (char === '>') {
              // At this point, we'll assume the comment wasn't a real comment
              // so we'll just emit it as data. We basically read the sequence 
              // '<!--->'
              resetToDataState();
          }
          else {
              // Anything else, take it as a valid comment
              state = 16 /* Comment */;
          }
      }
      // Currently reading the comment's text (data)
      // https://www.w3.org/TR/html51/syntax.html#comment-state
      function stateComment(char) {
          if (char === '-') {
              state = 17 /* CommentEndDash */;
          }
      }
      // When we we've read the first dash inside a comment, it may signal the
      // end of the comment if we read another dash
      // https://www.w3.org/TR/html51/syntax.html#comment-end-dash-state
      function stateCommentEndDash(char) {
          if (char === '-') {
              state = 18 /* CommentEnd */;
          }
          else {
              // Wasn't a dash, must still be part of the comment
              state = 16 /* Comment */;
          }
      }
      // After we've read two dashes inside a comment, it may signal the end of 
      // the comment if we then read a '>' char
      // https://www.w3.org/TR/html51/syntax.html#comment-end-state
      function stateCommentEnd(char) {
          if (char === '>') {
              emitTagAndPreviousTextNode();
          }
          else if (char === '!') {
              state = 19 /* CommentEndBang */;
          }
          else if (char === '-') ;
          else {
              // Anything else, switch back to the comment state since we didn't
              // read the full "end comment" sequence (i.e. '-->')
              state = 16 /* Comment */;
          }
      }
      // We've read the sequence '--!' inside of a comment
      // https://www.w3.org/TR/html51/syntax.html#comment-end-bang-state
      function stateCommentEndBang(char) {
          if (char === '-') {
              // We read the sequence '--!-' inside of a comment. The last dash
              // could signify that the comment is going to close
              state = 17 /* CommentEndDash */;
          }
          else if (char === '>') {
              // End of comment with the sequence '--!>'
              emitTagAndPreviousTextNode();
          }
          else {
              // The '--!' was not followed by a '>', continue reading the 
              // comment's text
              state = 16 /* Comment */;
          }
      }
      /**
       * For DOCTYPES in particular, we don't care about the attributes. Just
       * advance to the '>' character and emit the tag, unless we find a '<'
       * character in which case we'll start a new tag.
       *
       * Example doctype tag:
       *    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
       *
       * Actual spec: https://www.w3.org/TR/html51/syntax.html#doctype-state
       */
      function stateDoctype(char) {
          if (char === '>') {
              emitTagAndPreviousTextNode();
          }
          else if (char === '<') {
              startNewTag();
          }
          else ;
      }
      /**
       * Resets the state back to the Data state, and removes the current tag.
       *
       * We'll generally run this function whenever a "parse error" is
       * encountered, where the current tag that is being read no longer looks
       * like a real HTML tag.
       */
      function resetToDataState() {
          state = 0 /* Data */;
          currentTag = noCurrentTag;
      }
      /**
       * Starts a new HTML tag at the current index, ignoring any previous HTML
       * tag that was being read.
       *
       * We'll generally run this function whenever we read a new '<' character,
       * including when we read a '<' character inside of an HTML tag that we were
       * previously reading.
       */
      function startNewTag() {
          state = 1 /* TagOpen */;
          currentTag = new CurrentTag({ idx: charIdx });
      }
      /**
       * Once we've decided to emit an open tag, that means we can also emit the
       * text node before it.
       */
      function emitTagAndPreviousTextNode() {
          var textBeforeTag = html.slice(currentDataIdx, currentTag.idx);
          if (textBeforeTag) {
              // the html tag was the first element in the html string, or two 
              // tags next to each other, in which case we should not emit a text 
              // node
              onText(textBeforeTag, currentDataIdx);
          }
          if (currentTag.type === 'comment') {
              onComment(currentTag.idx);
          }
          else if (currentTag.type === 'doctype') {
              onDoctype(currentTag.idx);
          }
          else {
              if (currentTag.isOpening) {
                  onOpenTag(currentTag.name, currentTag.idx);
              }
              if (currentTag.isClosing) { // note: self-closing tags will emit both opening and closing
                  onCloseTag(currentTag.name, currentTag.idx);
              }
          }
          // Since we just emitted a tag, reset to the data state for the next char
          resetToDataState();
          currentDataIdx = charIdx + 1;
      }
      function emitText() {
          var text = html.slice(currentDataIdx, charIdx);
          onText(text, currentDataIdx);
          currentDataIdx = charIdx + 1;
      }
      /**
       * Captures the tag name from the start of the tag to the current character
       * index, and converts it to lower case
       */
      function captureTagName() {
          var startIdx = currentTag.idx + (currentTag.isClosing ? 2 : 1);
          return html.slice(startIdx, charIdx).toLowerCase();
      }
      /**
       * Causes the main loop to re-consume the current character, such as after
       * encountering a "parse error" that changed state and needs to reconsume
       * the same character in that new state.
       */
      function reconsumeCurrentCharacter() {
          charIdx--;
      }
  }
  var CurrentTag = /** @class */ (function () {
      function CurrentTag(cfg) {
          if (cfg === void 0) { cfg = {}; }
          this.idx = cfg.idx !== undefined ? cfg.idx : -1;
          this.type = cfg.type || 'tag';
          this.name = cfg.name || '';
          this.isOpening = !!cfg.isOpening;
          this.isClosing = !!cfg.isClosing;
      }
      return CurrentTag;
  }());

  /**
   * @class Autolinker
   * @extends Object
   *
   * Utility class used to process a given string of text, and wrap the matches in
   * the appropriate anchor (&lt;a&gt;) tags to turn them into links.
   *
   * Any of the configuration options may be provided in an Object provided
   * to the Autolinker constructor, which will configure how the {@link #link link()}
   * method will process the links.
   *
   * For example:
   *
   *     var autolinker = new Autolinker( {
   *         newWindow : false,
   *         truncate  : 30
   *     } );
   *
   *     var html = autolinker.link( "Joe went to www.yahoo.com" );
   *     // produces: 'Joe went to <a href="http://www.yahoo.com">yahoo.com</a>'
   *
   *
   * The {@link #static-link static link()} method may also be used to inline
   * options into a single call, which may be more convenient for one-off uses.
   * For example:
   *
   *     var html = Autolinker.link( "Joe went to www.yahoo.com", {
   *         newWindow : false,
   *         truncate  : 30
   *     } );
   *     // produces: 'Joe went to <a href="http://www.yahoo.com">yahoo.com</a>'
   *
   *
   * ## Custom Replacements of Links
   *
   * If the configuration options do not provide enough flexibility, a {@link #replaceFn}
   * may be provided to fully customize the output of Autolinker. This function is
   * called once for each URL/Email/Phone#/Hashtag/Mention (Twitter, Instagram, Soundcloud)
   * match that is encountered.
   *
   * For example:
   *
   *     var input = "...";  // string with URLs, Email Addresses, Phone #s, Hashtags, and Mentions (Twitter, Instagram, Soundcloud)
   *
   *     var linkedText = Autolinker.link( input, {
   *         replaceFn : function( match ) {
   *             console.log( "href = ", match.getAnchorHref() );
   *             console.log( "text = ", match.getAnchorText() );
   *
   *             switch( match.getType() ) {
   *                 case 'url' :
   *                     console.log( "url: ", match.getUrl() );
   *
   *                     if( match.getUrl().indexOf( 'mysite.com' ) === -1 ) {
   *                         var tag = match.buildTag();  // returns an `Autolinker.HtmlTag` instance, which provides mutator methods for easy changes
   *                         tag.setAttr( 'rel', 'nofollow' );
   *                         tag.addClass( 'external-link' );
   *
   *                         return tag;
   *
   *                     } else {
   *                         return true;  // let Autolinker perform its normal anchor tag replacement
   *                     }
   *
   *                 case 'email' :
   *                     var email = match.getEmail();
   *                     console.log( "email: ", email );
   *
   *                     if( email === "my@own.address" ) {
   *                         return false;  // don't auto-link this particular email address; leave as-is
   *                     } else {
   *                         return;  // no return value will have Autolinker perform its normal anchor tag replacement (same as returning `true`)
   *                     }
   *
   *                 case 'phone' :
   *                     var phoneNumber = match.getPhoneNumber();
   *                     console.log( phoneNumber );
   *
   *                     return '<a href="http://newplace.to.link.phone.numbers.to/">' + phoneNumber + '</a>';
   *
   *                 case 'hashtag' :
   *                     var hashtag = match.getHashtag();
   *                     console.log( hashtag );
   *
   *                     return '<a href="http://newplace.to.link.hashtag.handles.to/">' + hashtag + '</a>';
   *
   *                 case 'mention' :
   *                     var mention = match.getMention();
   *                     console.log( mention );
   *
   *                     return '<a href="http://newplace.to.link.mention.to/">' + mention + '</a>';
   *             }
   *         }
   *     } );
   *
   *
   * The function may return the following values:
   *
   * - `true` (Boolean): Allow Autolinker to replace the match as it normally
   *   would.
   * - `false` (Boolean): Do not replace the current match at all - leave as-is.
   * - Any String: If a string is returned from the function, the string will be
   *   used directly as the replacement HTML for the match.
   * - An {@link Autolinker.HtmlTag} instance, which can be used to build/modify
   *   an HTML tag before writing out its HTML text.
   */
  var Autolinker = /** @class */ (function () {
      /**
       * @method constructor
       * @param {Object} [cfg] The configuration options for the Autolinker instance,
       *   specified in an Object (map).
       */
      function Autolinker(cfg) {
          if (cfg === void 0) { cfg = {}; }
          /**
           * The Autolinker version number exposed on the instance itself.
           *
           * Ex: 0.25.1
           */
          this.version = Autolinker.version;
          /**
           * @cfg {Boolean/Object} [urls]
           *
           * `true` if URLs should be automatically linked, `false` if they should not
           * be. Defaults to `true`.
           *
           * Examples:
           *
           *     urls: true
           *
           *     // or
           *
           *     urls: {
           *         schemeMatches : true,
           *         wwwMatches    : true,
           *         tldMatches    : true
           *     }
           *
           * As shown above, this option also accepts an Object form with 3 properties
           * to allow for more customization of what exactly gets linked. All default
           * to `true`:
           *
           * @cfg {Boolean} [urls.schemeMatches] `true` to match URLs found prefixed
           *   with a scheme, i.e. `http://google.com`, or `other+scheme://google.com`,
           *   `false` to prevent these types of matches.
           * @cfg {Boolean} [urls.wwwMatches] `true` to match urls found prefixed with
           *   `'www.'`, i.e. `www.google.com`. `false` to prevent these types of
           *   matches. Note that if the URL had a prefixed scheme, and
           *   `schemeMatches` is true, it will still be linked.
           * @cfg {Boolean} [urls.tldMatches] `true` to match URLs with known top
           *   level domains (.com, .net, etc.) that are not prefixed with a scheme or
           *   `'www.'`. This option attempts to match anything that looks like a URL
           *   in the given text. Ex: `google.com`, `asdf.org/?page=1`, etc. `false`
           *   to prevent these types of matches.
           */
          this.urls = {}; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @cfg {Boolean} [email=true]
           *
           * `true` if email addresses should be automatically linked, `false` if they
           * should not be.
           */
          this.email = true; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @cfg {Boolean} [phone=true]
           *
           * `true` if Phone numbers ("(555)555-5555") should be automatically linked,
           * `false` if they should not be.
           */
          this.phone = true; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @cfg {Boolean/String} [hashtag=false]
           *
           * A string for the service name to have hashtags (ex: "#myHashtag")
           * auto-linked to. The currently-supported values are:
           *
           * - 'twitter'
           * - 'facebook'
           * - 'instagram'
           *
           * Pass `false` to skip auto-linking of hashtags.
           */
          this.hashtag = false; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @cfg {String/Boolean} [mention=false]
           *
           * A string for the service name to have mentions (ex: "@myuser")
           * auto-linked to. The currently supported values are:
           *
           * - 'twitter'
           * - 'instagram'
           * - 'soundcloud'
           *
           * Defaults to `false` to skip auto-linking of mentions.
           */
          this.mention = false; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @cfg {Boolean} [newWindow=true]
           *
           * `true` if the links should open in a new window, `false` otherwise.
           */
          this.newWindow = true; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @cfg {Boolean/Object} [stripPrefix=true]
           *
           * `true` if 'http://' (or 'https://') and/or the 'www.' should be stripped
           * from the beginning of URL links' text, `false` otherwise. Defaults to
           * `true`.
           *
           * Examples:
           *
           *     stripPrefix: true
           *
           *     // or
           *
           *     stripPrefix: {
           *         scheme : true,
           *         www    : true
           *     }
           *
           * As shown above, this option also accepts an Object form with 2 properties
           * to allow for more customization of what exactly is prevented from being
           * displayed. Both default to `true`:
           *
           * @cfg {Boolean} [stripPrefix.scheme] `true` to prevent the scheme part of
           *   a URL match from being displayed to the user. Example:
           *   `'http://google.com'` will be displayed as `'google.com'`. `false` to
           *   not strip the scheme. NOTE: Only an `'http://'` or `'https://'` scheme
           *   will be removed, so as not to remove a potentially dangerous scheme
           *   (such as `'file://'` or `'javascript:'`)
           * @cfg {Boolean} [stripPrefix.www] www (Boolean): `true` to prevent the
           *   `'www.'` part of a URL match from being displayed to the user. Ex:
           *   `'www.google.com'` will be displayed as `'google.com'`. `false` to not
           *   strip the `'www'`.
           */
          this.stripPrefix = { scheme: true, www: true }; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @cfg {Boolean} [stripTrailingSlash=true]
           *
           * `true` to remove the trailing slash from URL matches, `false` to keep
           *  the trailing slash.
           *
           *  Example when `true`: `http://google.com/` will be displayed as
           *  `http://google.com`.
           */
          this.stripTrailingSlash = true; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @cfg {Boolean} [decodePercentEncoding=true]
           *
           * `true` to decode percent-encoded characters in URL matches, `false` to keep
           *  the percent-encoded characters.
           *
           *  Example when `true`: `https://en.wikipedia.org/wiki/San_Jos%C3%A9` will
           *  be displayed as `https://en.wikipedia.org/wiki/San_José`.
           */
          this.decodePercentEncoding = true; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @cfg {Number/Object} [truncate=0]
           *
           * ## Number Form
           *
           * A number for how many characters matched text should be truncated to
           * inside the text of a link. If the matched text is over this number of
           * characters, it will be truncated to this length by adding a two period
           * ellipsis ('..') to the end of the string.
           *
           * For example: A url like 'http://www.yahoo.com/some/long/path/to/a/file'
           * truncated to 25 characters might look something like this:
           * 'yahoo.com/some/long/pat..'
           *
           * Example Usage:
           *
           *     truncate: 25
           *
           *
           *  Defaults to `0` for "no truncation."
           *
           *
           * ## Object Form
           *
           * An Object may also be provided with two properties: `length` (Number) and
           * `location` (String). `location` may be one of the following: 'end'
           * (default), 'middle', or 'smart'.
           *
           * Example Usage:
           *
           *     truncate: { length: 25, location: 'middle' }
           *
           * @cfg {Number} [truncate.length=0] How many characters to allow before
           *   truncation will occur. Defaults to `0` for "no truncation."
           * @cfg {"end"/"middle"/"smart"} [truncate.location="end"]
           *
           * - 'end' (default): will truncate up to the number of characters, and then
           *   add an ellipsis at the end. Ex: 'yahoo.com/some/long/pat..'
           * - 'middle': will truncate and add the ellipsis in the middle. Ex:
           *   'yahoo.com/s..th/to/a/file'
           * - 'smart': for URLs where the algorithm attempts to strip out unnecessary
           *   parts first (such as the 'www.', then URL scheme, hash, etc.),
           *   attempting to make the URL human-readable before looking for a good
           *   point to insert the ellipsis if it is still too long. Ex:
           *   'yahoo.com/some..to/a/file'. For more details, see
           *   {@link Autolinker.truncate.TruncateSmart}.
           */
          this.truncate = { length: 0, location: 'end' }; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @cfg {String} className
           *
           * A CSS class name to add to the generated links. This class will be added
           * to all links, as well as this class plus match suffixes for styling
           * url/email/phone/hashtag/mention links differently.
           *
           * For example, if this config is provided as "myLink", then:
           *
           * - URL links will have the CSS classes: "myLink myLink-url"
           * - Email links will have the CSS classes: "myLink myLink-email", and
           * - Phone links will have the CSS classes: "myLink myLink-phone"
           * - Hashtag links will have the CSS classes: "myLink myLink-hashtag"
           * - Mention links will have the CSS classes: "myLink myLink-mention myLink-[type]"
           *   where [type] is either "instagram", "twitter" or "soundcloud"
           */
          this.className = ''; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @cfg {Function} replaceFn
           *
           * A function to individually process each match found in the input string.
           *
           * See the class's description for usage.
           *
           * The `replaceFn` can be called with a different context object (`this`
           * reference) using the {@link #context} cfg.
           *
           * This function is called with the following parameter:
           *
           * @cfg {Autolinker.match.Match} replaceFn.match The Match instance which
           *   can be used to retrieve information about the match that the `replaceFn`
           *   is currently processing. See {@link Autolinker.match.Match} subclasses
           *   for details.
           */
          this.replaceFn = null; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @cfg {Object} context
           *
           * The context object (`this` reference) to call the `replaceFn` with.
           *
           * Defaults to this Autolinker instance.
           */
          this.context = undefined; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @cfg {Boolean} [sanitizeHtml=false]
           *
           * `true` to HTML-encode the start and end brackets of existing HTML tags found
           * in the input string. This will escape `<` and `>` characters to `&lt;` and
           * `&gt;`, respectively.
           *
           * Setting this to `true` will prevent XSS (Cross-site Scripting) attacks,
           * but will remove the significance of existing HTML tags in the input string. If
           * you would like to maintain the significance of existing HTML tags while also
           * making the output HTML string safe, leave this option as `false` and use a
           * tool like https://github.com/cure53/DOMPurify (or others) on the input string
           * before running Autolinker.
           */
          this.sanitizeHtml = false; // default value just to get the above doc comment in the ES5 output and documentation generator
          /**
           * @private
           * @property {Autolinker.matcher.Matcher[]} matchers
           *
           * The {@link Autolinker.matcher.Matcher} instances for this Autolinker
           * instance.
           *
           * This is lazily created in {@link #getMatchers}.
           */
          this.matchers = null;
          /**
           * @private
           * @property {Autolinker.AnchorTagBuilder} tagBuilder
           *
           * The AnchorTagBuilder instance used to build match replacement anchor tags.
           * Note: this is lazily instantiated in the {@link #getTagBuilder} method.
           */
          this.tagBuilder = null;
          // Note: when `this.something` is used in the rhs of these assignments,
          //       it refers to the default values set above the constructor
          this.urls = this.normalizeUrlsCfg(cfg.urls);
          this.email = typeof cfg.email === 'boolean' ? cfg.email : this.email;
          this.phone = typeof cfg.phone === 'boolean' ? cfg.phone : this.phone;
          this.hashtag = cfg.hashtag || this.hashtag;
          this.mention = cfg.mention || this.mention;
          this.newWindow = typeof cfg.newWindow === 'boolean' ? cfg.newWindow : this.newWindow;
          this.stripPrefix = this.normalizeStripPrefixCfg(cfg.stripPrefix);
          this.stripTrailingSlash = typeof cfg.stripTrailingSlash === 'boolean' ? cfg.stripTrailingSlash : this.stripTrailingSlash;
          this.decodePercentEncoding = typeof cfg.decodePercentEncoding === 'boolean' ? cfg.decodePercentEncoding : this.decodePercentEncoding;
          this.sanitizeHtml = cfg.sanitizeHtml || false;
          // Validate the value of the `mention` cfg
          var mention = this.mention;
          if (mention !== false && ['twitter', 'instagram', 'soundcloud', 'tiktok'].indexOf(mention) === -1) {
              throw new Error("invalid `mention` cfg '".concat(mention, "' - see docs"));
          }
          // Validate the value of the `hashtag` cfg
          var hashtag = this.hashtag;
          if (hashtag !== false && ['twitter', 'facebook', 'instagram', 'tiktok'].indexOf(hashtag) === -1) {
              throw new Error("invalid `hashtag` cfg '".concat(hashtag, "' - see docs"));
          }
          this.truncate = this.normalizeTruncateCfg(cfg.truncate);
          this.className = cfg.className || this.className;
          this.replaceFn = cfg.replaceFn || this.replaceFn;
          this.context = cfg.context || this;
      }
      /**
       * Automatically links URLs, Email addresses, Phone Numbers, Twitter handles,
       * Hashtags, and Mentions found in the given chunk of HTML. Does not link URLs
       * found within HTML tags.
       *
       * For instance, if given the text: `You should go to http://www.yahoo.com`,
       * then the result will be `You should go to &lt;a href="http://www.yahoo.com"&gt;http://www.yahoo.com&lt;/a&gt;`
       *
       * Example:
       *
       *     var linkedText = Autolinker.link( "Go to google.com", { newWindow: false } );
       *     // Produces: "Go to <a href="http://google.com">google.com</a>"
       *
       * @static
       * @param {String} textOrHtml The HTML or text to find matches within (depending
       *   on if the {@link #urls}, {@link #email}, {@link #phone}, {@link #mention},
       *   {@link #hashtag}, and {@link #mention} options are enabled).
       * @param {Object} [options] Any of the configuration options for the Autolinker
       *   class, specified in an Object (map). See the class description for an
       *   example call.
       * @return {String} The HTML text, with matches automatically linked.
       */
      Autolinker.link = function (textOrHtml, options) {
          var autolinker = new Autolinker(options);
          return autolinker.link(textOrHtml);
      };
      /**
       * Parses the input `textOrHtml` looking for URLs, email addresses, phone
       * numbers, username handles, and hashtags (depending on the configuration
       * of the Autolinker instance), and returns an array of {@link Autolinker.match.Match}
       * objects describing those matches (without making any replacements).
       *
       * Note that if parsing multiple pieces of text, it is slightly more efficient
       * to create an Autolinker instance, and use the instance-level {@link #parse}
       * method.
       *
       * Example:
       *
       *     var matches = Autolinker.parse( "Hello google.com, I am asdf@asdf.com", {
       *         urls: true,
       *         email: true
       *     } );
       *
       *     console.log( matches.length );           // 2
       *     console.log( matches[ 0 ].getType() );   // 'url'
       *     console.log( matches[ 0 ].getUrl() );    // 'google.com'
       *     console.log( matches[ 1 ].getType() );   // 'email'
       *     console.log( matches[ 1 ].getEmail() );  // 'asdf@asdf.com'
       *
       * @static
       * @param {String} textOrHtml The HTML or text to find matches within
       *   (depending on if the {@link #urls}, {@link #email}, {@link #phone},
       *   {@link #hashtag}, and {@link #mention} options are enabled).
       * @param {Object} [options] Any of the configuration options for the Autolinker
       *   class, specified in an Object (map). See the class description for an
       *   example call.
       * @return {Autolinker.match.Match[]} The array of Matches found in the
       *   given input `textOrHtml`.
       */
      Autolinker.parse = function (textOrHtml, options) {
          var autolinker = new Autolinker(options);
          return autolinker.parse(textOrHtml);
      };
      /**
       * Normalizes the {@link #urls} config into an Object with 3 properties:
       * `schemeMatches`, `wwwMatches`, and `tldMatches`, all Booleans.
       *
       * See {@link #urls} config for details.
       *
       * @private
       * @param {Boolean/Object} urls
       * @return {Object}
       */
      Autolinker.prototype.normalizeUrlsCfg = function (urls) {
          if (urls == null)
              urls = true; // default to `true`
          if (typeof urls === 'boolean') {
              return { schemeMatches: urls, wwwMatches: urls, tldMatches: urls };
          }
          else { // object form
              return {
                  schemeMatches: typeof urls.schemeMatches === 'boolean' ? urls.schemeMatches : true,
                  wwwMatches: typeof urls.wwwMatches === 'boolean' ? urls.wwwMatches : true,
                  tldMatches: typeof urls.tldMatches === 'boolean' ? urls.tldMatches : true
              };
          }
      };
      /**
       * Normalizes the {@link #stripPrefix} config into an Object with 2
       * properties: `scheme`, and `www` - both Booleans.
       *
       * See {@link #stripPrefix} config for details.
       *
       * @private
       * @param {Boolean/Object} stripPrefix
       * @return {Object}
       */
      Autolinker.prototype.normalizeStripPrefixCfg = function (stripPrefix) {
          if (stripPrefix == null)
              stripPrefix = true; // default to `true`
          if (typeof stripPrefix === 'boolean') {
              return { scheme: stripPrefix, www: stripPrefix };
          }
          else { // object form
              return {
                  scheme: typeof stripPrefix.scheme === 'boolean' ? stripPrefix.scheme : true,
                  www: typeof stripPrefix.www === 'boolean' ? stripPrefix.www : true
              };
          }
      };
      /**
       * Normalizes the {@link #truncate} config into an Object with 2 properties:
       * `length` (Number), and `location` (String).
       *
       * See {@link #truncate} config for details.
       *
       * @private
       * @param {Number/Object} truncate
       * @return {Object}
       */
      Autolinker.prototype.normalizeTruncateCfg = function (truncate) {
          if (typeof truncate === 'number') {
              return { length: truncate, location: 'end' };
          }
          else { // object, or undefined/null
              return defaults(truncate || {}, {
                  length: Number.POSITIVE_INFINITY,
                  location: 'end'
              });
          }
      };
      /**
       * Parses the input `textOrHtml` looking for URLs, email addresses, phone
       * numbers, username handles, and hashtags (depending on the configuration
       * of the Autolinker instance), and returns an array of {@link Autolinker.match.Match}
       * objects describing those matches (without making any replacements).
       *
       * This method is used by the {@link #link} method, but can also be used to
       * simply do parsing of the input in order to discover what kinds of links
       * there are and how many.
       *
       * Example usage:
       *
       *     var autolinker = new Autolinker( {
       *         urls: true,
       *         email: true
       *     } );
       *
       *     var matches = autolinker.parse( "Hello google.com, I am asdf@asdf.com" );
       *
       *     console.log( matches.length );           // 2
       *     console.log( matches[ 0 ].getType() );   // 'url'
       *     console.log( matches[ 0 ].getUrl() );    // 'google.com'
       *     console.log( matches[ 1 ].getType() );   // 'email'
       *     console.log( matches[ 1 ].getEmail() );  // 'asdf@asdf.com'
       *
       * @param {String} textOrHtml The HTML or text to find matches within
       *   (depending on if the {@link #urls}, {@link #email}, {@link #phone},
       *   {@link #hashtag}, and {@link #mention} options are enabled).
       * @return {Autolinker.match.Match[]} The array of Matches found in the
       *   given input `textOrHtml`.
       */
      Autolinker.prototype.parse = function (textOrHtml) {
          var _this = this;
          var skipTagNames = ['a', 'style', 'script'], skipTagsStackCount = 0, // used to only Autolink text outside of anchor/script/style tags. We don't want to autolink something that is already linked inside of an <a> tag, for instance
          matches = [];
          // Find all matches within the `textOrHtml` (but not matches that are
          // already nested within <a>, <style> and <script> tags)
          parseHtml(textOrHtml, {
              onOpenTag: function (tagName) {
                  if (skipTagNames.indexOf(tagName) >= 0) {
                      skipTagsStackCount++;
                  }
              },
              onText: function (text, offset) {
                  // Only process text nodes that are not within an <a>, <style> or <script> tag
                  if (skipTagsStackCount === 0) {
                      // "Walk around" common HTML entities. An '&nbsp;' (for example)
                      // could be at the end of a URL, but we don't want to 
                      // include the trailing '&' in the URL. See issue #76
                      // TODO: Handle HTML entities separately in parseHtml() and
                      // don't emit them as "text" except for &amp; entities
                      var htmlCharacterEntitiesRegex = /(&nbsp;|&#160;|&lt;|&#60;|&gt;|&#62;|&quot;|&#34;|&#39;)/gi;
                      var textSplit = splitAndCapture(text, htmlCharacterEntitiesRegex);
                      var currentOffset_1 = offset;
                      textSplit.forEach(function (splitText, i) {
                          // even number matches are text, odd numbers are html entities
                          if (i % 2 === 0) {
                              var textNodeMatches = _this.parseText(splitText, currentOffset_1);
                              matches.push.apply(matches, textNodeMatches);
                          }
                          currentOffset_1 += splitText.length;
                      });
                  }
              },
              onCloseTag: function (tagName) {
                  if (skipTagNames.indexOf(tagName) >= 0) {
                      skipTagsStackCount = Math.max(skipTagsStackCount - 1, 0); // attempt to handle extraneous </a> tags by making sure the stack count never goes below 0
                  }
              },
              onComment: function (offset) { },
              onDoctype: function (offset) { }, // no need to process doctype nodes
          });
          // After we have found all matches, remove subsequent matches that
          // overlap with a previous match. This can happen for instance with URLs,
          // where the url 'google.com/#link' would match '#link' as a hashtag.
          matches = this.compactMatches(matches);
          // And finally, remove matches for match types that have been turned
          // off. We needed to have all match types turned on initially so that
          // things like hashtags could be filtered out if they were really just
          // part of a URL match (for instance, as a named anchor).
          matches = this.removeUnwantedMatches(matches);
          return matches;
      };
      /**
       * After we have found all matches, we need to remove matches that overlap
       * with a previous match. This can happen for instance with URLs, where the
       * url 'google.com/#link' would match '#link' as a hashtag. Because the
       * '#link' part is contained in a larger match that comes before the HashTag
       * match, we'll remove the HashTag match.
       *
       * @private
       * @param {Autolinker.match.Match[]} matches
       * @return {Autolinker.match.Match[]}
       */
      Autolinker.prototype.compactMatches = function (matches) {
          // First, the matches need to be sorted in order of offset
          matches.sort(function (a, b) { return a.getOffset() - b.getOffset(); });
          var i = 0;
          while (i < matches.length - 1) {
              var match = matches[i], offset = match.getOffset(), matchedTextLength = match.getMatchedText().length, endIdx = offset + matchedTextLength;
              if (i + 1 < matches.length) {
                  // Remove subsequent matches that equal offset with current match
                  if (matches[i + 1].getOffset() === offset) {
                      var removeIdx = matches[i + 1].getMatchedText().length > matchedTextLength ? i : i + 1;
                      matches.splice(removeIdx, 1);
                      continue;
                  }
                  // Remove subsequent matches that overlap with the current match
                  if (matches[i + 1].getOffset() < endIdx) {
                      matches.splice(i + 1, 1);
                      continue;
                  }
              }
              i++;
          }
          return matches;
      };
      /**
       * Removes matches for matchers that were turned off in the options. For
       * example, if {@link #hashtag hashtags} were not to be matched, we'll
       * remove them from the `matches` array here.
       *
       * Note: we *must* use all Matchers on the input string, and then filter
       * them out later. For example, if the options were `{ url: false, hashtag: true }`,
       * we wouldn't want to match the text '#link' as a HashTag inside of the text
       * 'google.com/#link'. The way the algorithm works is that we match the full
       * URL first (which prevents the accidental HashTag match), and then we'll
       * simply throw away the URL match.
       *
       * @private
       * @param {Autolinker.match.Match[]} matches The array of matches to remove
       *   the unwanted matches from. Note: this array is mutated for the
       *   removals.
       * @return {Autolinker.match.Match[]} The mutated input `matches` array.
       */
      Autolinker.prototype.removeUnwantedMatches = function (matches) {
          if (!this.hashtag)
              remove$1(matches, function (match) { return match.getType() === 'hashtag'; });
          if (!this.email)
              remove$1(matches, function (match) { return match.getType() === 'email'; });
          if (!this.phone)
              remove$1(matches, function (match) { return match.getType() === 'phone'; });
          if (!this.mention)
              remove$1(matches, function (match) { return match.getType() === 'mention'; });
          if (!this.urls.schemeMatches) {
              remove$1(matches, function (m) { return m.getType() === 'url' && m.getUrlMatchType() === 'scheme'; });
          }
          if (!this.urls.wwwMatches) {
              remove$1(matches, function (m) { return m.getType() === 'url' && m.getUrlMatchType() === 'www'; });
          }
          if (!this.urls.tldMatches) {
              remove$1(matches, function (m) { return m.getType() === 'url' && m.getUrlMatchType() === 'tld'; });
          }
          return matches;
      };
      /**
       * Parses the input `text` looking for URLs, email addresses, phone
       * numbers, username handles, and hashtags (depending on the configuration
       * of the Autolinker instance), and returns an array of {@link Autolinker.match.Match}
       * objects describing those matches.
       *
       * This method processes a **non-HTML string**, and is used to parse and
       * match within the text nodes of an HTML string. This method is used
       * internally by {@link #parse}.
       *
       * @private
       * @param {String} text The text to find matches within (depending on if the
       *   {@link #urls}, {@link #email}, {@link #phone},
       *   {@link #hashtag}, and {@link #mention} options are enabled). This must be a non-HTML string.
       * @param {Number} [offset=0] The offset of the text node within the
       *   original string. This is used when parsing with the {@link #parse}
       *   method to generate correct offsets within the {@link Autolinker.match.Match}
       *   instances, but may be omitted if calling this method publicly.
       * @return {Autolinker.match.Match[]} The array of Matches found in the
       *   given input `text`.
       */
      Autolinker.prototype.parseText = function (text, offset) {
          if (offset === void 0) { offset = 0; }
          offset = offset || 0;
          var matchers = this.getMatchers(), matches = [];
          for (var i = 0, numMatchers = matchers.length; i < numMatchers; i++) {
              var textMatches = matchers[i].parseMatches(text);
              // Correct the offset of each of the matches. They are originally
              // the offset of the match within the provided text node, but we
              // need to correct them to be relative to the original HTML input
              // string (i.e. the one provided to #parse).
              for (var j = 0, numTextMatches = textMatches.length; j < numTextMatches; j++) {
                  textMatches[j].setOffset(offset + textMatches[j].getOffset());
              }
              matches.push.apply(matches, textMatches);
          }
          return matches;
      };
      /**
       * Automatically links URLs, Email addresses, Phone numbers, Hashtags,
       * and Mentions (Twitter, Instagram, Soundcloud) found in the given chunk of HTML. Does not link
       * URLs found within HTML tags.
       *
       * For instance, if given the text: `You should go to http://www.yahoo.com`,
       * then the result will be `You should go to
       * &lt;a href="http://www.yahoo.com"&gt;http://www.yahoo.com&lt;/a&gt;`
       *
       * This method finds the text around any HTML elements in the input
       * `textOrHtml`, which will be the text that is processed. Any original HTML
       * elements will be left as-is, as well as the text that is already wrapped
       * in anchor (&lt;a&gt;) tags.
       *
       * @param {String} textOrHtml The HTML or text to autolink matches within
       *   (depending on if the {@link #urls}, {@link #email}, {@link #phone}, {@link #hashtag}, and {@link #mention} options are enabled).
       * @return {String} The HTML, with matches automatically linked.
       */
      Autolinker.prototype.link = function (textOrHtml) {
          if (!textOrHtml) {
              return "";
          } // handle `null` and `undefined` (for JavaScript users that don't have TypeScript support)
          /* We would want to sanitize the start and end characters of a tag
           * before processing the string in order to avoid an XSS scenario.
           * This behaviour can be changed by toggling the sanitizeHtml option.
           */
          if (this.sanitizeHtml) {
              textOrHtml = textOrHtml
                  .replace(/</g, '&lt;')
                  .replace(/>/g, '&gt;');
          }
          var matches = this.parse(textOrHtml), newHtml = [], lastIndex = 0;
          for (var i = 0, len = matches.length; i < len; i++) {
              var match = matches[i];
              newHtml.push(textOrHtml.substring(lastIndex, match.getOffset()));
              newHtml.push(this.createMatchReturnVal(match));
              lastIndex = match.getOffset() + match.getMatchedText().length;
          }
          newHtml.push(textOrHtml.substring(lastIndex)); // handle the text after the last match
          return newHtml.join('');
      };
      /**
       * Creates the return string value for a given match in the input string.
       *
       * This method handles the {@link #replaceFn}, if one was provided.
       *
       * @private
       * @param {Autolinker.match.Match} match The Match object that represents
       *   the match.
       * @return {String} The string that the `match` should be replaced with.
       *   This is usually the anchor tag string, but may be the `matchStr` itself
       *   if the match is not to be replaced.
       */
      Autolinker.prototype.createMatchReturnVal = function (match) {
          // Handle a custom `replaceFn` being provided
          var replaceFnResult;
          if (this.replaceFn) {
              replaceFnResult = this.replaceFn.call(this.context, match); // Autolinker instance is the context
          }
          if (typeof replaceFnResult === 'string') {
              return replaceFnResult; // `replaceFn` returned a string, use that
          }
          else if (replaceFnResult === false) {
              return match.getMatchedText(); // no replacement for the match
          }
          else if (replaceFnResult instanceof HtmlTag) {
              return replaceFnResult.toAnchorString();
          }
          else { // replaceFnResult === true, or no/unknown return value from function
              // Perform Autolinker's default anchor tag generation
              var anchorTag = match.buildTag(); // returns an Autolinker.HtmlTag instance
              return anchorTag.toAnchorString();
          }
      };
      /**
       * Lazily instantiates and returns the {@link Autolinker.matcher.Matcher}
       * instances for this Autolinker instance.
       *
       * @private
       * @return {Autolinker.matcher.Matcher[]}
       */
      Autolinker.prototype.getMatchers = function () {
          if (!this.matchers) {
              var tagBuilder = this.getTagBuilder();
              var matchers = [
                  new HashtagMatcher({ tagBuilder: tagBuilder, serviceName: this.hashtag }),
                  new EmailMatcher({ tagBuilder: tagBuilder }),
                  new PhoneMatcher({ tagBuilder: tagBuilder }),
                  new MentionMatcher({ tagBuilder: tagBuilder, serviceName: this.mention }),
                  new UrlMatcher({ tagBuilder: tagBuilder, stripPrefix: this.stripPrefix, stripTrailingSlash: this.stripTrailingSlash, decodePercentEncoding: this.decodePercentEncoding })
              ];
              return (this.matchers = matchers);
          }
          else {
              return this.matchers;
          }
      };
      /**
       * Returns the {@link #tagBuilder} instance for this Autolinker instance,
       * lazily instantiating it if it does not yet exist.
       *
       * @private
       * @return {Autolinker.AnchorTagBuilder}
       */
      Autolinker.prototype.getTagBuilder = function () {
          var tagBuilder = this.tagBuilder;
          if (!tagBuilder) {
              tagBuilder = this.tagBuilder = new AnchorTagBuilder({
                  newWindow: this.newWindow,
                  truncate: this.truncate,
                  className: this.className
              });
          }
          return tagBuilder;
      };
      /**
       * @static
       * @property {String} version
       *
       * The Autolinker version number in the form major.minor.patch
       *
       * Ex: 0.25.1
       */
      Autolinker.version = '3.15.0';
      /**
       * For backwards compatibility with Autolinker 1.x, the AnchorTagBuilder
       * class is provided as a static on the Autolinker class.
       */
      Autolinker.AnchorTagBuilder = AnchorTagBuilder;
      /**
       * For backwards compatibility with Autolinker 1.x, the HtmlTag class is
       * provided as a static on the Autolinker class.
       */
      Autolinker.HtmlTag = HtmlTag;
      /**
       * For backwards compatibility with Autolinker 1.x, the Matcher classes are
       * provided as statics on the Autolinker class.
       */
      Autolinker.matcher = {
          Email: EmailMatcher,
          Hashtag: HashtagMatcher,
          Matcher: Matcher,
          Mention: MentionMatcher,
          Phone: PhoneMatcher,
          Url: UrlMatcher
      };
      /**
       * For backwards compatibility with Autolinker 1.x, the Match classes are
       * provided as statics on the Autolinker class.
       */
      Autolinker.match = {
          Email: EmailMatch,
          Hashtag: HashtagMatch,
          Match: Match,
          Mention: MentionMatch,
          Phone: PhoneMatch,
          Url: UrlMatch
      };
      return Autolinker;
  }());

  let parser$1;
  if (typeof DOMParser !== "undefined") {
    parser$1 = new DOMParser();
  }

  const autolinker$1 = new Autolinker({
    stripPrefix: false,
    email: false,
    replaceFn: function (linker, match) {
      if (!match.protocolUrlMatch) {
        // Prevent matching of non-explicit urls.
        // i.e. foo.id won't match but http://foo.id will
        return false;
      }
    },
  });

  const BILLBOARD_SIZE$2 = 32;
  const BILLBOARD_NEAR_DISTANCE$1 = 2414016;
  const BILLBOARD_NEAR_RATIO$1 = 1.0;
  const BILLBOARD_FAR_DISTANCE$1 = 1.6093e7;
  const BILLBOARD_FAR_RATIO$1 = 0.1;

  const gpxNamespaces = [null, undefined, "http://www.topografix.com/GPX/1/1"];
  const namespaces$1 = {
    gpx: gpxNamespaces,
  };

  function readBlobAsText$1(blob) {
    const deferred = defer();
    const reader = new FileReader();
    reader.addEventListener("load", function () {
      deferred.resolve(reader.result);
    });
    reader.addEventListener("error", function () {
      deferred.reject(reader.error);
    });
    reader.readAsText(blob);
    return deferred.promise;
  }

  function getOrCreateEntity(node, entityCollection) {
    let id = queryStringAttribute$1(node, "id");
    id = defined(id) ? id : createGuid();
    const entity = entityCollection.getOrCreateEntity(id);
    return entity;
  }

  function readCoordinateFromNode(node) {
    const longitude = queryNumericAttribute$1(node, "lon");
    const latitude = queryNumericAttribute$1(node, "lat");
    const elevation = queryNumericValue$1(node, "ele", namespaces$1.gpx);
    return Cartesian3.fromDegrees(longitude, latitude, elevation);
  }

  function queryNumericAttribute$1(node, attributeName) {
    if (!defined(node)) {
      return undefined;
    }

    const value = node.getAttribute(attributeName);
    if (value !== null) {
      const result = parseFloat(value);
      return !isNaN(result) ? result : undefined;
    }
    return undefined;
  }

  function queryStringAttribute$1(node, attributeName) {
    if (!defined(node)) {
      return undefined;
    }
    const value = node.getAttribute(attributeName);
    return value !== null ? value : undefined;
  }

  function queryFirstNode$1(node, tagName, namespace) {
    if (!defined(node)) {
      return undefined;
    }
    const childNodes = node.childNodes;
    const length = childNodes.length;
    for (let q = 0; q < length; q++) {
      const child = childNodes[q];
      if (
        child.localName === tagName &&
        namespace.indexOf(child.namespaceURI) !== -1
      ) {
        return child;
      }
    }
    return undefined;
  }

  function queryNodes$1(node, tagName, namespace) {
    if (!defined(node)) {
      return undefined;
    }
    const result = [];
    const childNodes = node.getElementsByTagName(tagName);
    const length = childNodes.length;
    for (let q = 0; q < length; q++) {
      const child = childNodes[q];
      if (
        child.localName === tagName &&
        namespace.indexOf(child.namespaceURI) !== -1
      ) {
        result.push(child);
      }
    }
    return result;
  }

  function queryNumericValue$1(node, tagName, namespace) {
    const resultNode = queryFirstNode$1(node, tagName, namespace);
    if (defined(resultNode)) {
      const result = parseFloat(resultNode.textContent);
      return !isNaN(result) ? result : undefined;
    }
    return undefined;
  }

  function queryStringValue$1(node, tagName, namespace) {
    const result = queryFirstNode$1(node, tagName, namespace);
    if (defined(result)) {
      return result.textContent.trim();
    }
    return undefined;
  }

  function createDefaultBillboard$1(image) {
    const billboard = new BillboardGraphics();
    billboard.width = BILLBOARD_SIZE$2;
    billboard.height = BILLBOARD_SIZE$2;
    billboard.scaleByDistance = new NearFarScalar(
      BILLBOARD_NEAR_DISTANCE$1,
      BILLBOARD_NEAR_RATIO$1,
      BILLBOARD_FAR_DISTANCE$1,
      BILLBOARD_FAR_RATIO$1
    );
    billboard.pixelOffsetScaleByDistance = new NearFarScalar(
      BILLBOARD_NEAR_DISTANCE$1,
      BILLBOARD_NEAR_RATIO$1,
      BILLBOARD_FAR_DISTANCE$1,
      BILLBOARD_FAR_RATIO$1
    );
    billboard.verticalOrigin = new ConstantProperty(VerticalOrigin$1.BOTTOM);
    billboard.image = image;
    return billboard;
  }

  function createDefaultLabel$1() {
    const label = new LabelGraphics();
    label.translucencyByDistance = new NearFarScalar(3000000, 1.0, 5000000, 0.0);
    label.pixelOffset = new Cartesian2(17, 0);
    label.horizontalOrigin = HorizontalOrigin$1.LEFT;
    label.font = "16px sans-serif";
    label.style = LabelStyle$1.FILL_AND_OUTLINE;
    return label;
  }

  function createDefaultPolyline(color) {
    const polyline = new PolylineGraphics();
    polyline.width = 4;
    polyline.material = new PolylineOutlineMaterialProperty();
    polyline.material.color = defined(color) ? color : Color.RED;
    polyline.material.outlineWidth = 2;
    polyline.material.outlineColor = Color.BLACK;
    return polyline;
  }

  // This is a list of the Optional Description Information:
  //  <cmt> GPS comment of the waypoint
  //  <desc> Descriptive description of the waypoint
  //  <src> Source of the waypoint data
  //  <type> Type (category) of waypoint
  const descriptiveInfoTypes = {
    time: {
      text: "Time",
      tag: "time",
    },
    comment: {
      text: "Comment",
      tag: "cmt",
    },
    description: {
      text: "Description",
      tag: "desc",
    },
    source: {
      text: "Source",
      tag: "src",
    },
    number: {
      text: "GPS track/route number",
      tag: "number",
    },
    type: {
      text: "Type",
      tag: "type",
    },
  };

  let scratchDiv$1;
  if (typeof document !== "undefined") {
    scratchDiv$1 = document.createElement("div");
  }
  function processDescription$1(node, entity) {
    let i;

    let text = "";
    const infoTypeNames = Object.keys(descriptiveInfoTypes);
    const length = infoTypeNames.length;
    for (i = 0; i < length; i++) {
      const infoTypeName = infoTypeNames[i];
      const infoType = descriptiveInfoTypes[infoTypeName];
      infoType.value = defaultValue(
        queryStringValue$1(node, infoType.tag, namespaces$1.gpx),
        ""
      );
      if (defined(infoType.value) && infoType.value !== "") {
        text = `${text}<p>${infoType.text}: ${infoType.value}</p>`;
      }
    }

    if (!defined(text) || text === "") {
      // No description
      return;
    }

    // Turns non-explicit links into clickable links.
    text = autolinker$1.link(text);

    // Use a temporary div to manipulate the links
    // so that they open in a new window.
    scratchDiv$1.innerHTML = text;
    const links = scratchDiv$1.querySelectorAll("a");

    for (i = 0; i < links.length; i++) {
      links[i].setAttribute("target", "_blank");
    }

    const background = Color.WHITE;
    const foreground = Color.BLACK;
    let tmp = '<div class="cesium-infoBox-description-lighter" style="';
    tmp += "overflow:auto;";
    tmp += "word-wrap:break-word;";
    tmp += `background-color:${background.toCssColorString()};`;
    tmp += `color:${foreground.toCssColorString()};`;
    tmp += '">';
    tmp += `${scratchDiv$1.innerHTML}</div>`;
    scratchDiv$1.innerHTML = "";

    // return the final HTML as the description.
    return tmp;
  }

  function processWpt(dataSource, geometryNode, entityCollection, options) {
    const position = readCoordinateFromNode(geometryNode);

    const entity = getOrCreateEntity(geometryNode, entityCollection);
    entity.position = position;

    // Get billboard image
    const image = defined(options.waypointImage)
      ? options.waypointImage
      : dataSource._pinBuilder.fromMakiIconId(
          "marker",
          Color.RED,
          BILLBOARD_SIZE$2
        );
    entity.billboard = createDefaultBillboard$1(image);

    const name = queryStringValue$1(geometryNode, "name", namespaces$1.gpx);
    entity.name = name;
    entity.label = createDefaultLabel$1();
    entity.label.text = name;
    entity.description = processDescription$1(geometryNode);

    if (options.clampToGround) {
      entity.billboard.heightReference = HeightReference$1.CLAMP_TO_GROUND;
      entity.label.heightReference = HeightReference$1.CLAMP_TO_GROUND;
    }
  }

  // rte represents route - an ordered list of waypoints representing a series of turn points leading to a destination
  function processRte(dataSource, geometryNode, entityCollection, options) {
    const entity = getOrCreateEntity(geometryNode, entityCollection);
    entity.description = processDescription$1(geometryNode);

    // a list of waypoint
    const routePoints = queryNodes$1(geometryNode, "rtept", namespaces$1.gpx);
    const coordinateTuples = new Array(routePoints.length);
    for (let i = 0; i < routePoints.length; i++) {
      processWpt(dataSource, routePoints[i], entityCollection, options);
      coordinateTuples[i] = readCoordinateFromNode(routePoints[i]);
    }
    entity.polyline = createDefaultPolyline(options.routeColor);
    if (options.clampToGround) {
      entity.polyline.clampToGround = true;
    }
    entity.polyline.positions = coordinateTuples;
  }

  // trk represents a track - an ordered list of points describing a path.
  function processTrk(dataSource, geometryNode, entityCollection, options) {
    const entity = getOrCreateEntity(geometryNode, entityCollection);
    entity.description = processDescription$1(geometryNode);

    const trackSegs = queryNodes$1(geometryNode, "trkseg", namespaces$1.gpx);
    let positions = [];
    let times = [];
    let trackSegInfo;
    let isTimeDynamic = true;
    const property = new SampledPositionProperty();
    for (let i = 0; i < trackSegs.length; i++) {
      trackSegInfo = processTrkSeg(trackSegs[i]);
      positions = positions.concat(trackSegInfo.positions);
      if (trackSegInfo.times.length > 0) {
        times = times.concat(trackSegInfo.times);
        property.addSamples(times, positions);
        // if one track segment is non dynamic the whole track must also be
        isTimeDynamic = isTimeDynamic && true;
      } else {
        isTimeDynamic = false;
      }
    }
    if (isTimeDynamic) {
      // Assign billboard image
      const image = defined(options.waypointImage)
        ? options.waypointImage
        : dataSource._pinBuilder.fromMakiIconId(
            "marker",
            Color.RED,
            BILLBOARD_SIZE$2
          );
      entity.billboard = createDefaultBillboard$1(image);
      entity.position = property;
      if (options.clampToGround) {
        entity.billboard.heightReference = HeightReference$1.CLAMP_TO_GROUND;
      }
      entity.availability = new TimeIntervalCollection();
      entity.availability.addInterval(
        new TimeInterval({
          start: times[0],
          stop: times[times.length - 1],
        })
      );
    }
    entity.polyline = createDefaultPolyline(options.trackColor);
    entity.polyline.positions = positions;
    if (options.clampToGround) {
      entity.polyline.clampToGround = true;
    }
  }

  function processTrkSeg(node) {
    const result = {
      positions: [],
      times: [],
    };
    const trackPoints = queryNodes$1(node, "trkpt", namespaces$1.gpx);
    let time;
    for (let i = 0; i < trackPoints.length; i++) {
      const position = readCoordinateFromNode(trackPoints[i]);
      result.positions.push(position);

      time = queryStringValue$1(trackPoints[i], "time", namespaces$1.gpx);
      if (defined(time)) {
        result.times.push(JulianDate.fromIso8601(time));
      }
    }
    return result;
  }

  // Processes a metadataType node and returns a metadata object
  // {@link http://www.topografix.com/gpx/1/1/#type_metadataType|GPX Schema}
  function processMetadata(node) {
    const metadataNode = queryFirstNode$1(node, "metadata", namespaces$1.gpx);
    if (defined(metadataNode)) {
      const metadata = {
        name: queryStringValue$1(metadataNode, "name", namespaces$1.gpx),
        desc: queryStringValue$1(metadataNode, "desc", namespaces$1.gpx),
        author: getPerson(metadataNode),
        copyright: getCopyright(metadataNode),
        link: getLink(metadataNode),
        time: queryStringValue$1(metadataNode, "time", namespaces$1.gpx),
        keywords: queryStringValue$1(metadataNode, "keywords", namespaces$1.gpx),
        bounds: getBounds(metadataNode),
      };
      if (
        defined(metadata.name) ||
        defined(metadata.desc) ||
        defined(metadata.author) ||
        defined(metadata.copyright) ||
        defined(metadata.link) ||
        defined(metadata.time) ||
        defined(metadata.keywords) ||
        defined(metadata.bounds)
      ) {
        return metadata;
      }
    }
    return undefined;
  }

  // Receives a XML node and returns a personType object, refer to
  // {@link http://www.topografix.com/gpx/1/1/#type_personType|GPX Schema}
  function getPerson(node) {
    const personNode = queryFirstNode$1(node, "author", namespaces$1.gpx);
    if (defined(personNode)) {
      const person = {
        name: queryStringValue$1(personNode, "name", namespaces$1.gpx),
        email: getEmail(personNode),
        link: getLink(personNode),
      };
      if (defined(person.name) || defined(person.email) || defined(person.link)) {
        return person;
      }
    }
    return undefined;
  }

  // Receives a XML node and returns an email address (from emailType), refer to
  // {@link http://www.topografix.com/gpx/1/1/#type_emailType|GPX Schema}
  function getEmail(node) {
    const emailNode = queryFirstNode$1(node, "email", namespaces$1.gpx);
    if (defined(emailNode)) {
      const id = queryStringValue$1(emailNode, "id", namespaces$1.gpx);
      const domain = queryStringValue$1(emailNode, "domain", namespaces$1.gpx);
      return `${id}@${domain}`;
    }
    return undefined;
  }

  // Receives a XML node and returns a linkType object, refer to
  // {@link http://www.topografix.com/gpx/1/1/#type_linkType|GPX Schema}
  function getLink(node) {
    const linkNode = queryFirstNode$1(node, "link", namespaces$1.gpx);
    if (defined(linkNode)) {
      const link = {
        href: queryStringAttribute$1(linkNode, "href"),
        text: queryStringValue$1(linkNode, "text", namespaces$1.gpx),
        mimeType: queryStringValue$1(linkNode, "type", namespaces$1.gpx),
      };
      if (defined(link.href) || defined(link.text) || defined(link.mimeType)) {
        return link;
      }
    }
    return undefined;
  }

  // Receives a XML node and returns a copyrightType object, refer to
  // {@link http://www.topografix.com/gpx/1/1/#type_copyrightType|GPX Schema}
  function getCopyright(node) {
    const copyrightNode = queryFirstNode$1(node, "copyright", namespaces$1.gpx);
    if (defined(copyrightNode)) {
      const copyright = {
        author: queryStringAttribute$1(copyrightNode, "author"),
        year: queryStringValue$1(copyrightNode, "year", namespaces$1.gpx),
        license: queryStringValue$1(copyrightNode, "license", namespaces$1.gpx),
      };
      if (
        defined(copyright.author) ||
        defined(copyright.year) ||
        defined(copyright.license)
      ) {
        return copyright;
      }
    }
    return undefined;
  }

  // Receives a XML node and returns a boundsType object, refer to
  // {@link http://www.topografix.com/gpx/1/1/#type_boundsType|GPX Schema}
  function getBounds(node) {
    const boundsNode = queryFirstNode$1(node, "bounds", namespaces$1.gpx);
    if (defined(boundsNode)) {
      const bounds = {
        minLat: queryNumericValue$1(boundsNode, "minlat", namespaces$1.gpx),
        maxLat: queryNumericValue$1(boundsNode, "maxlat", namespaces$1.gpx),
        minLon: queryNumericValue$1(boundsNode, "minlon", namespaces$1.gpx),
        maxLon: queryNumericValue$1(boundsNode, "maxlon", namespaces$1.gpx),
      };
      if (
        defined(bounds.minLat) ||
        defined(bounds.maxLat) ||
        defined(bounds.minLon) ||
        defined(bounds.maxLon)
      ) {
        return bounds;
      }
    }
    return undefined;
  }

  const complexTypes = {
    wpt: processWpt,
    rte: processRte,
    trk: processTrk,
  };

  function processGpx(dataSource, node, entityCollection, options) {
    const complexTypeNames = Object.keys(complexTypes);
    const complexTypeNamesLength = complexTypeNames.length;

    for (let i = 0; i < complexTypeNamesLength; i++) {
      const typeName = complexTypeNames[i];
      const processComplexTypeNode = complexTypes[typeName];

      const childNodes = node.childNodes;
      const length = childNodes.length;
      for (let q = 0; q < length; q++) {
        const child = childNodes[q];
        if (
          child.localName === typeName &&
          namespaces$1.gpx.indexOf(child.namespaceURI) !== -1
        ) {
          processComplexTypeNode(dataSource, child, entityCollection, options);
        }
      }
    }
  }

  function loadGpx(dataSource, gpx, options) {
    const entityCollection = dataSource._entityCollection;

    entityCollection.removeAll();

    const element = gpx.documentElement;
    const version = queryStringAttribute$1(element, "version");
    const creator = queryStringAttribute$1(element, "creator");

    let name;
    const metadata = processMetadata(element);
    if (defined(metadata)) {
      name = metadata.name;
    }

    if (element.localName === "gpx") {
      processGpx(dataSource, element, entityCollection, options);
    } else {
      console.log(`GPX - Unsupported node: ${element.localName}`);
    }

    let clock;
    const availability = entityCollection.computeAvailability();

    let start = availability.start;
    let stop = availability.stop;
    const isMinStart = JulianDate.equals(start, Iso8601.MINIMUM_VALUE);
    const isMaxStop = JulianDate.equals(stop, Iso8601.MAXIMUM_VALUE);
    if (!isMinStart || !isMaxStop) {
      let date;

      // If start is min time just start at midnight this morning, local time
      if (isMinStart) {
        date = new Date();
        date.setHours(0, 0, 0, 0);
        start = JulianDate.fromDate(date);
      }

      // If stop is max value just stop at midnight tonight, local time
      if (isMaxStop) {
        date = new Date();
        date.setHours(24, 0, 0, 0);
        stop = JulianDate.fromDate(date);
      }

      clock = new DataSourceClock();
      clock.startTime = start;
      clock.stopTime = stop;
      clock.currentTime = JulianDate.clone(start);
      clock.clockRange = ClockRange$1.LOOP_STOP;
      clock.clockStep = ClockStep$1.SYSTEM_CLOCK_MULTIPLIER;
      clock.multiplier = Math.round(
        Math.min(
          Math.max(JulianDate.secondsDifference(stop, start) / 60, 1),
          3.15569e7
        )
      );
    }
    let changed = false;
    if (dataSource._name !== name) {
      dataSource._name = name;
      changed = true;
    }

    if (dataSource._creator !== creator) {
      dataSource._creator = creator;
      changed = true;
    }

    if (metadataChanged(dataSource._metadata, metadata)) {
      dataSource._metadata = metadata;
      changed = true;
    }

    if (dataSource._version !== version) {
      dataSource._version = version;
      changed = true;
    }

    if (clock !== dataSource._clock) {
      changed = true;
      dataSource._clock = clock;
    }

    if (changed) {
      dataSource._changed.raiseEvent(dataSource);
    }

    DataSource.setLoading(dataSource, false);
    return dataSource;
  }

  function metadataChanged(old, current) {
    if (!defined(old) && !defined(current)) {
      return false;
    } else if (defined(old) && defined(current)) {
      if (
        old.name !== current.name ||
        old.dec !== current.desc ||
        old.src !== current.src ||
        old.author !== current.author ||
        old.copyright !== current.copyright ||
        old.link !== current.link ||
        old.time !== current.time ||
        old.bounds !== current.bounds
      ) {
        return true;
      }
      return false;
    }
    return true;
  }

  function load$1(dataSource, entityCollection, data, options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    let promise = data;
    if (typeof data === "string" || data instanceof Resource) {
      data = Resource.createIfNeeded(data);
      promise = data.fetchBlob();

      // Add resource credits to our list of credits to display
      const resourceCredits = dataSource._resourceCredits;
      const credits = data.credits;
      if (defined(credits)) {
        const length = credits.length;
        for (let i = 0; i < length; i++) {
          resourceCredits.push(credits[i]);
        }
      }
    }

    return Promise.resolve(promise)
      .then(function (dataToLoad) {
        if (dataToLoad instanceof Blob) {
          return readBlobAsText$1(dataToLoad).then(function (text) {
            // There's no official way to validate if a parse was successful.
            // The following check detects the error on various browsers.
            // IE raises an exception
            let gpx;
            let error;
            try {
              gpx = parser$1.parseFromString(text, "application/xml");
            } catch (e) {
              error = e.toString();
            }

            // The parse succeeds on Chrome and Firefox, but the error
            // handling is different in each.
            if (
              defined(error) ||
              gpx.body ||
              gpx.documentElement.tagName === "parsererror"
            ) {
              // Firefox has error information as the firstChild nodeValue.
              let msg = defined(error)
                ? error
                : gpx.documentElement.firstChild.nodeValue;

              // Chrome has it in the body text.
              if (!msg) {
                msg = gpx.body.innerText;
              }

              // Return the error
              throw new RuntimeError(msg);
            }
            return loadGpx(dataSource, gpx, options);
          });
        }
        return loadGpx(dataSource, dataToLoad, options);
      })
      .catch(function (error) {
        dataSource._error.raiseEvent(dataSource, error);
        console.log(error);
        return Promise.reject(error);
      });
  }

  /**
   * A {@link DataSource} which processes the GPS Exchange Format (GPX).
   *
   * @alias GpxDataSource
   * @constructor
   *
   * @see {@link http://www.topografix.com/gpx.asp|Topografix GPX Standard}
   * @see {@link http://www.topografix.com/gpx/1/1/|Topografix GPX Documentation}
   *
   * @demo {@link http://sandcastle.cesium.com/index.html?src=GPX.html}
   *
   * @example
   * const viewer = new Cesium.Viewer('cesiumContainer');
   * viewer.dataSources.add(Cesium.GpxDataSource.load('../../SampleData/track.gpx'));
   */
  function GpxDataSource() {
    this._changed = new Event();
    this._error = new Event();
    this._loading = new Event();
    this._clock = undefined;
    this._entityCollection = new EntityCollection();
    this._entityCluster = new EntityCluster();
    this._name = undefined;
    this._version = undefined;
    this._creator = undefined;
    this._metadata = undefined;
    this._isLoading = false;
    this._pinBuilder = new PinBuilder();
  }

  /**
   * Creates a Promise to a new instance loaded with the provided GPX data.
   *
   * @param {String|Document|Blob} data A url, parsed GPX document, or Blob containing binary GPX data.
   * @param {Object} [options] An object with the following properties:
   * @param {Boolean} [options.clampToGround] True if the symbols should be rendered at the same height as the terrain
   * @param {String} [options.waypointImage] Image to use for waypoint billboards.
   * @param {String} [options.trackImage] Image to use for track billboards.
   * @param {String} [options.trackColor] Color to use for track lines.
   * @param {String} [options.routeColor] Color to use for route lines.
   * @returns {Promise.<GpxDataSource>} A promise that will resolve to a new GpxDataSource instance once the gpx is loaded.
   */
  GpxDataSource.load = function (data, options) {
    return new GpxDataSource().load(data, options);
  };

  Object.defineProperties(GpxDataSource.prototype, {
    /**
     * Gets a human-readable name for this instance.
     * This will be automatically be set to the GPX document name on load.
     * @memberof GpxDataSource.prototype
     * @type {String}
     */
    name: {
      get: function () {
        return this._name;
      },
    },
    /**
     * Gets the version of the GPX Schema in use.
     * @memberof GpxDataSource.prototype
     * @type {String}
     */
    version: {
      get: function () {
        return this._version;
      },
    },
    /**
     * Gets the creator of the GPX document.
     * @memberof GpxDataSource.prototype
     * @type {String}
     */
    creator: {
      get: function () {
        return this._creator;
      },
    },
    /**
     * Gets an object containing metadata about the GPX file.
     * @memberof GpxDataSource.prototype
     * @type {Object}
     */
    metadata: {
      get: function () {
        return this._metadata;
      },
    },
    /**
     * Gets the clock settings defined by the loaded GPX. This represents the total
     * availability interval for all time-dynamic data. If the GPX does not contain
     * time-dynamic data, this value is undefined.
     * @memberof GpxDataSource.prototype
     * @type {DataSourceClock}
     */
    clock: {
      get: function () {
        return this._clock;
      },
    },
    /**
     * Gets the collection of {@link Entity} instances.
     * @memberof GpxDataSource.prototype
     * @type {EntityCollection}
     */
    entities: {
      get: function () {
        return this._entityCollection;
      },
    },
    /**
     * Gets a value indicating if the data source is currently loading data.
     * @memberof GpxDataSource.prototype
     * @type {Boolean}
     */
    isLoading: {
      get: function () {
        return this._isLoading;
      },
    },
    /**
     * Gets an event that will be raised when the underlying data changes.
     * @memberof GpxDataSource.prototype
     * @type {Event}
     */
    changedEvent: {
      get: function () {
        return this._changed;
      },
    },
    /**
     * Gets an event that will be raised if an error is encountered during processing.
     * @memberof GpxDataSource.prototype
     * @type {Event}
     */
    errorEvent: {
      get: function () {
        return this._error;
      },
    },
    /**
     * Gets an event that will be raised when the data source either starts or stops loading.
     * @memberof GpxDataSource.prototype
     * @type {Event}
     */
    loadingEvent: {
      get: function () {
        return this._loading;
      },
    },
    /**
     * Gets whether or not this data source should be displayed.
     * @memberof GpxDataSource.prototype
     * @type {Boolean}
     */
    show: {
      get: function () {
        return this._entityCollection.show;
      },
      set: function (value) {
        this._entityCollection.show = value;
      },
    },

    /**
     * Gets or sets the clustering options for this data source. This object can be shared between multiple data sources.
     *
     * @memberof GpxDataSource.prototype
     * @type {EntityCluster}
     */
    clustering: {
      get: function () {
        return this._entityCluster;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value must be defined.");
        }
        //>>includeEnd('debug');
        this._entityCluster = value;
      },
    },
  });

  /**
   * Updates the data source to the provided time.  This function is optional and
   * is not required to be implemented.  It is provided for data sources which
   * retrieve data based on the current animation time or scene state.
   * If implemented, update will be called by {@link DataSourceDisplay} once a frame.
   *
   * @param {JulianDate} time The simulation time.
   * @returns {Boolean} True if this data source is ready to be displayed at the provided time, false otherwise.
   */
  GpxDataSource.prototype.update = function (time) {
    return true;
  };

  /**
   * Asynchronously loads the provided GPX data, replacing any existing data.
   *
   * @param {String|Document|Blob} data A url, parsed GPX document, or Blob containing binary GPX data or a parsed GPX document.
   * @param {Object} [options] An object with the following properties:
   * @param {Boolean} [options.clampToGround] True if the symbols should be rendered at the same height as the terrain
   * @param {String} [options.waypointImage] Image to use for waypoint billboards.
   * @param {String} [options.trackImage] Image to use for track billboards.
   * @param {String} [options.trackColor] Color to use for track lines.
   * @param {String} [options.routeColor] Color to use for route lines.
   * @returns {Promise.<GpxDataSource>} A promise that will resolve to this instances once the GPX is loaded.
   */
  GpxDataSource.prototype.load = function (data, options) {
    if (!defined(data)) {
      throw new DeveloperError("data is required.");
    }

    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    DataSource.setLoading(this, true);
    const oldName = this._name;
    const that = this;
    return load$1(this, this._entityCollection, data, options)
      .then(function () {
        let clock;

        const availability = that._entityCollection.computeAvailability();

        let start = availability.start;
        let stop = availability.stop;
        const isMinStart = JulianDate.equals(start, Iso8601.MINIMUM_VALUE);
        const isMaxStop = JulianDate.equals(stop, Iso8601.MAXIMUM_VALUE);
        if (!isMinStart || !isMaxStop) {
          let date;

          // If start is min time just start at midnight this morning, local time
          if (isMinStart) {
            date = new Date();
            date.setHours(0, 0, 0, 0);
            start = JulianDate.fromDate(date);
          }

          // If stop is max value just stop at midnight tonight, local time
          if (isMaxStop) {
            date = new Date();
            date.setHours(24, 0, 0, 0);
            stop = JulianDate.fromDate(date);
          }

          clock = new DataSourceClock();
          clock.startTime = start;
          clock.stopTime = stop;
          clock.currentTime = JulianDate.clone(start);
          clock.clockRange = ClockRange$1.LOOP_STOP;
          clock.clockStep = ClockStep$1.SYSTEM_CLOCK_MULTIPLIER;
          clock.multiplier = Math.round(
            Math.min(
              Math.max(JulianDate.secondsDifference(stop, start) / 60, 1),
              3.15569e7
            )
          );
        }

        let changed = false;
        if (clock !== that._clock) {
          that._clock = clock;
          changed = true;
        }

        if (oldName !== that._name) {
          changed = true;
        }

        if (changed) {
          that._changed.raiseEvent(that);
        }

        DataSource.setLoading(that, false);

        return that;
      })
      .catch(function (error) {
        DataSource.setLoading(that, false);
        that._error.raiseEvent(that, error);
        console.log(error);
        return Promise.reject(error);
      });
  };

  /**
   * Representation of <Camera> from KML
   * @alias KmlCamera
   * @constructor
   *
   * @param {Cartesian3} position camera position
   * @param {HeadingPitchRoll} headingPitchRoll camera orientation
   */
  function KmlCamera(position, headingPitchRoll) {
    this.position = position;
    this.headingPitchRoll = headingPitchRoll;
  }

  /* This file is automatically rebuilt by the Cesium build process. */
  /*
   Copyright (c) 2022 Gildas Lormeau. All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright 
   notice, this list of conditions and the following disclaimer in 
   the documentation and/or other materials provided with the distribution.

   3. The names of the authors may not be used to endorse or promote products
   derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
   INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
   OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
   EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   */

  /*
   * This program is based on JZlib 1.0.2 ymnk, JCraft,Inc.
   * JZlib is based on zlib-1.1.3, so all credit should go authors
   * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
   * and contributors of zlib.
   */

  // deno-lint-ignore-file no-this-alias prefer-const

  // Global

  const MAX_BITS$1 = 15;
  const D_CODES = 30;
  const BL_CODES = 19;

  const LENGTH_CODES = 29;
  const LITERALS = 256;
  const L_CODES = (LITERALS + 1 + LENGTH_CODES);
  const HEAP_SIZE = (2 * L_CODES + 1);

  const END_BLOCK = 256;

  // Bit length codes must not exceed MAX_BL_BITS bits
  const MAX_BL_BITS = 7;

  // repeat previous bit length 3-6 times (2 bits of repeat count)
  const REP_3_6 = 16;

  // repeat a zero length 3-10 times (3 bits of repeat count)
  const REPZ_3_10 = 17;

  // repeat a zero length 11-138 times (7 bits of repeat count)
  const REPZ_11_138 = 18;

  // The lengths of the bit length codes are sent in order of decreasing
  // probability, to avoid transmitting the lengths for unused bit
  // length codes.

  const Buf_size = 8 * 2;

  // JZlib version : "1.0.2"
  const Z_DEFAULT_COMPRESSION = -1;

  // compression strategy
  const Z_FILTERED = 1;
  const Z_HUFFMAN_ONLY = 2;
  const Z_DEFAULT_STRATEGY = 0;

  const Z_NO_FLUSH$1 = 0;
  const Z_PARTIAL_FLUSH = 1;
  const Z_FULL_FLUSH = 3;
  const Z_FINISH$1 = 4;

  const Z_OK$1 = 0;
  const Z_STREAM_END$1 = 1;
  const Z_NEED_DICT$1 = 2;
  const Z_STREAM_ERROR$1 = -2;
  const Z_DATA_ERROR$1 = -3;
  const Z_BUF_ERROR$1 = -5;

  // Tree

  function extractArray(array) {
  	return flatArray(array.map(([length, value]) => (new Array(length)).fill(value, 0, length)));
  }

  function flatArray(array) {
  	return array.reduce((a, b) => a.concat(Array.isArray(b) ? flatArray(b) : b), []);
  }

  // see definition of array dist_code below
  const _dist_code = [0, 1, 2, 3].concat(...extractArray([
  	[2, 4], [2, 5], [4, 6], [4, 7], [8, 8], [8, 9], [16, 10], [16, 11], [32, 12], [32, 13], [64, 14], [64, 15], [2, 0], [1, 16],
  	[1, 17], [2, 18], [2, 19], [4, 20], [4, 21], [8, 22], [8, 23], [16, 24], [16, 25], [32, 26], [32, 27], [64, 28], [64, 29]
  ]));

  function Tree() {
  	const that = this;

  	// dyn_tree; // the dynamic tree
  	// max_code; // largest code with non zero frequency
  	// stat_desc; // the corresponding static tree

  	// Compute the optimal bit lengths for a tree and update the total bit
  	// length
  	// for the current block.
  	// IN assertion: the fields freq and dad are set, heap[heap_max] and
  	// above are the tree nodes sorted by increasing frequency.
  	// OUT assertions: the field len is set to the optimal bit length, the
  	// array bl_count contains the frequencies for each bit length.
  	// The length opt_len is updated; static_len is also updated if stree is
  	// not null.
  	function gen_bitlen(s) {
  		const tree = that.dyn_tree;
  		const stree = that.stat_desc.static_tree;
  		const extra = that.stat_desc.extra_bits;
  		const base = that.stat_desc.extra_base;
  		const max_length = that.stat_desc.max_length;
  		let h; // heap index
  		let n, m; // iterate over the tree elements
  		let bits; // bit length
  		let xbits; // extra bits
  		let f; // frequency
  		let overflow = 0; // number of elements with bit length too large

  		for (bits = 0; bits <= MAX_BITS$1; bits++)
  			s.bl_count[bits] = 0;

  		// In a first pass, compute the optimal bit lengths (which may
  		// overflow in the case of the bit length tree).
  		tree[s.heap[s.heap_max] * 2 + 1] = 0; // root of the heap

  		for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
  			n = s.heap[h];
  			bits = tree[tree[n * 2 + 1] * 2 + 1] + 1;
  			if (bits > max_length) {
  				bits = max_length;
  				overflow++;
  			}
  			tree[n * 2 + 1] = bits;
  			// We overwrite tree[n*2+1] which is no longer needed

  			if (n > that.max_code)
  				continue; // not a leaf node

  			s.bl_count[bits]++;
  			xbits = 0;
  			if (n >= base)
  				xbits = extra[n - base];
  			f = tree[n * 2];
  			s.opt_len += f * (bits + xbits);
  			if (stree)
  				s.static_len += f * (stree[n * 2 + 1] + xbits);
  		}
  		if (overflow === 0)
  			return;

  		// This happens for example on obj2 and pic of the Calgary corpus
  		// Find the first bit length which could increase:
  		do {
  			bits = max_length - 1;
  			while (s.bl_count[bits] === 0)
  				bits--;
  			s.bl_count[bits]--; // move one leaf down the tree
  			s.bl_count[bits + 1] += 2; // move one overflow item as its brother
  			s.bl_count[max_length]--;
  			// The brother of the overflow item also moves one step up,
  			// but this does not affect bl_count[max_length]
  			overflow -= 2;
  		} while (overflow > 0);

  		for (bits = max_length; bits !== 0; bits--) {
  			n = s.bl_count[bits];
  			while (n !== 0) {
  				m = s.heap[--h];
  				if (m > that.max_code)
  					continue;
  				if (tree[m * 2 + 1] != bits) {
  					s.opt_len += (bits - tree[m * 2 + 1]) * tree[m * 2];
  					tree[m * 2 + 1] = bits;
  				}
  				n--;
  			}
  		}
  	}

  	// Reverse the first len bits of a code, using straightforward code (a
  	// faster
  	// method would use a table)
  	// IN assertion: 1 <= len <= 15
  	function bi_reverse(code, // the value to invert
  		len // its bit length
  	) {
  		let res = 0;
  		do {
  			res |= code & 1;
  			code >>>= 1;
  			res <<= 1;
  		} while (--len > 0);
  		return res >>> 1;
  	}

  	// Generate the codes for a given tree and bit counts (which need not be
  	// optimal).
  	// IN assertion: the array bl_count contains the bit length statistics for
  	// the given tree and the field len is set for all tree elements.
  	// OUT assertion: the field code is set for all tree elements of non
  	// zero code length.
  	function gen_codes(tree, // the tree to decorate
  		max_code, // largest code with non zero frequency
  		bl_count // number of codes at each bit length
  	) {
  		const next_code = []; // next code value for each
  		// bit length
  		let code = 0; // running code value
  		let bits; // bit index
  		let n; // code index
  		let len;

  		// The distribution counts are first used to generate the code values
  		// without bit reversal.
  		for (bits = 1; bits <= MAX_BITS$1; bits++) {
  			next_code[bits] = code = ((code + bl_count[bits - 1]) << 1);
  		}

  		// Check that the bit counts in bl_count are consistent. The last code
  		// must be all ones.
  		// Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  		// "inconsistent bit counts");
  		// Tracev((stderr,"gen_codes: max_code %d ", max_code));

  		for (n = 0; n <= max_code; n++) {
  			len = tree[n * 2 + 1];
  			if (len === 0)
  				continue;
  			// Now reverse the bits
  			tree[n * 2] = bi_reverse(next_code[len]++, len);
  		}
  	}

  	// Construct one Huffman tree and assigns the code bit strings and lengths.
  	// Update the total bit length for the current block.
  	// IN assertion: the field freq is set for all tree elements.
  	// OUT assertions: the fields len and code are set to the optimal bit length
  	// and corresponding code. The length opt_len is updated; static_len is
  	// also updated if stree is not null. The field max_code is set.
  	that.build_tree = function (s) {
  		const tree = that.dyn_tree;
  		const stree = that.stat_desc.static_tree;
  		const elems = that.stat_desc.elems;
  		let n, m; // iterate over heap elements
  		let max_code = -1; // largest code with non zero frequency
  		let node; // new node being created

  		// Construct the initial heap, with least frequent element in
  		// heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  		// heap[0] is not used.
  		s.heap_len = 0;
  		s.heap_max = HEAP_SIZE;

  		for (n = 0; n < elems; n++) {
  			if (tree[n * 2] !== 0) {
  				s.heap[++s.heap_len] = max_code = n;
  				s.depth[n] = 0;
  			} else {
  				tree[n * 2 + 1] = 0;
  			}
  		}

  		// The pkzip format requires that at least one distance code exists,
  		// and that at least one bit should be sent even if there is only one
  		// possible code. So to avoid special checks later on we force at least
  		// two codes of non zero frequency.
  		while (s.heap_len < 2) {
  			node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0;
  			tree[node * 2] = 1;
  			s.depth[node] = 0;
  			s.opt_len--;
  			if (stree)
  				s.static_len -= stree[node * 2 + 1];
  			// node is 0 or 1 so it does not have extra bits
  		}
  		that.max_code = max_code;

  		// The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  		// establish sub-heaps of increasing lengths:

  		for (n = Math.floor(s.heap_len / 2); n >= 1; n--)
  			s.pqdownheap(tree, n);

  		// Construct the Huffman tree by repeatedly combining the least two
  		// frequent nodes.

  		node = elems; // next internal node of the tree
  		do {
  			// n = node of least frequency
  			n = s.heap[1];
  			s.heap[1] = s.heap[s.heap_len--];
  			s.pqdownheap(tree, 1);
  			m = s.heap[1]; // m = node of next least frequency

  			s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency
  			s.heap[--s.heap_max] = m;

  			// Create a new node father of n and m
  			tree[node * 2] = (tree[n * 2] + tree[m * 2]);
  			s.depth[node] = Math.max(s.depth[n], s.depth[m]) + 1;
  			tree[n * 2 + 1] = tree[m * 2 + 1] = node;

  			// and insert the new node in the heap
  			s.heap[1] = node++;
  			s.pqdownheap(tree, 1);
  		} while (s.heap_len >= 2);

  		s.heap[--s.heap_max] = s.heap[1];

  		// At this point, the fields freq and dad are set. We can now
  		// generate the bit lengths.

  		gen_bitlen(s);

  		// The field len is now set, we can generate the bit codes
  		gen_codes(tree, that.max_code, s.bl_count);
  	};

  }

  Tree._length_code = [0, 1, 2, 3, 4, 5, 6, 7].concat(...extractArray([
  	[2, 8], [2, 9], [2, 10], [2, 11], [4, 12], [4, 13], [4, 14], [4, 15], [8, 16], [8, 17], [8, 18], [8, 19],
  	[16, 20], [16, 21], [16, 22], [16, 23], [32, 24], [32, 25], [32, 26], [31, 27], [1, 28]]));

  Tree.base_length = [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 0];

  Tree.base_dist = [0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384,
  	24576];

  // Mapping from a distance to a distance code. dist is the distance - 1 and
  // must not have side effects. _dist_code[256] and _dist_code[257] are never
  // used.
  Tree.d_code = function (dist) {
  	return ((dist) < 256 ? _dist_code[dist] : _dist_code[256 + ((dist) >>> 7)]);
  };

  // extra bits for each length code
  Tree.extra_lbits = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0];

  // extra bits for each distance code
  Tree.extra_dbits = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13];

  // extra bits for each bit length code
  Tree.extra_blbits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7];

  Tree.bl_order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];

  // StaticTree

  function StaticTree(static_tree, extra_bits, extra_base, elems, max_length) {
  	const that = this;
  	that.static_tree = static_tree;
  	that.extra_bits = extra_bits;
  	that.extra_base = extra_base;
  	that.elems = elems;
  	that.max_length = max_length;
  }

  const static_ltree2_first_part = [12, 140, 76, 204, 44, 172, 108, 236, 28, 156, 92, 220, 60, 188, 124, 252, 2, 130, 66, 194, 34, 162, 98, 226, 18, 146, 82,
  	210, 50, 178, 114, 242, 10, 138, 74, 202, 42, 170, 106, 234, 26, 154, 90, 218, 58, 186, 122, 250, 6, 134, 70, 198, 38, 166, 102, 230, 22, 150, 86,
  	214, 54, 182, 118, 246, 14, 142, 78, 206, 46, 174, 110, 238, 30, 158, 94, 222, 62, 190, 126, 254, 1, 129, 65, 193, 33, 161, 97, 225, 17, 145, 81,
  	209, 49, 177, 113, 241, 9, 137, 73, 201, 41, 169, 105, 233, 25, 153, 89, 217, 57, 185, 121, 249, 5, 133, 69, 197, 37, 165, 101, 229, 21, 149, 85,
  	213, 53, 181, 117, 245, 13, 141, 77, 205, 45, 173, 109, 237, 29, 157, 93, 221, 61, 189, 125, 253, 19, 275, 147, 403, 83, 339, 211, 467, 51, 307,
  	179, 435, 115, 371, 243, 499, 11, 267, 139, 395, 75, 331, 203, 459, 43, 299, 171, 427, 107, 363, 235, 491, 27, 283, 155, 411, 91, 347, 219, 475,
  	59, 315, 187, 443, 123, 379, 251, 507, 7, 263, 135, 391, 71, 327, 199, 455, 39, 295, 167, 423, 103, 359, 231, 487, 23, 279, 151, 407, 87, 343, 215,
  	471, 55, 311, 183, 439, 119, 375, 247, 503, 15, 271, 143, 399, 79, 335, 207, 463, 47, 303, 175, 431, 111, 367, 239, 495, 31, 287, 159, 415, 95,
  	351, 223, 479, 63, 319, 191, 447, 127, 383, 255, 511, 0, 64, 32, 96, 16, 80, 48, 112, 8, 72, 40, 104, 24, 88, 56, 120, 4, 68, 36, 100, 20, 84, 52,
  	116, 3, 131, 67, 195, 35, 163, 99, 227];
  const static_ltree2_second_part = extractArray([[144, 8], [112, 9], [24, 7], [8, 8]]);
  StaticTree.static_ltree = flatArray(static_ltree2_first_part.map((value, index) => [value, static_ltree2_second_part[index]]));

  const static_dtree_first_part = [0, 16, 8, 24, 4, 20, 12, 28, 2, 18, 10, 26, 6, 22, 14, 30, 1, 17, 9, 25, 5, 21, 13, 29, 3, 19, 11, 27, 7, 23];
  const static_dtree_second_part = extractArray([[30, 5]]);
  StaticTree.static_dtree = flatArray(static_dtree_first_part.map((value, index) => [value, static_dtree_second_part[index]]));

  StaticTree.static_l_desc = new StaticTree(StaticTree.static_ltree, Tree.extra_lbits, LITERALS + 1, L_CODES, MAX_BITS$1);

  StaticTree.static_d_desc = new StaticTree(StaticTree.static_dtree, Tree.extra_dbits, 0, D_CODES, MAX_BITS$1);

  StaticTree.static_bl_desc = new StaticTree(null, Tree.extra_blbits, 0, BL_CODES, MAX_BL_BITS);

  // Deflate

  const MAX_MEM_LEVEL = 9;
  const DEF_MEM_LEVEL = 8;

  function Config(good_length, max_lazy, nice_length, max_chain, func) {
  	const that = this;
  	that.good_length = good_length;
  	that.max_lazy = max_lazy;
  	that.nice_length = nice_length;
  	that.max_chain = max_chain;
  	that.func = func;
  }

  const STORED$1 = 0;
  const FAST = 1;
  const SLOW = 2;
  const config_table = [
  	new Config(0, 0, 0, 0, STORED$1),
  	new Config(4, 4, 8, 4, FAST),
  	new Config(4, 5, 16, 8, FAST),
  	new Config(4, 6, 32, 32, FAST),
  	new Config(4, 4, 16, 16, SLOW),
  	new Config(8, 16, 32, 32, SLOW),
  	new Config(8, 16, 128, 128, SLOW),
  	new Config(8, 32, 128, 256, SLOW),
  	new Config(32, 128, 258, 1024, SLOW),
  	new Config(32, 258, 258, 4096, SLOW)
  ];

  const z_errmsg = ["need dictionary", // Z_NEED_DICT
  	// 2
  	"stream end", // Z_STREAM_END 1
  	"", // Z_OK 0
  	"", // Z_ERRNO (-1)
  	"stream error", // Z_STREAM_ERROR (-2)
  	"data error", // Z_DATA_ERROR (-3)
  	"", // Z_MEM_ERROR (-4)
  	"buffer error", // Z_BUF_ERROR (-5)
  	"",// Z_VERSION_ERROR (-6)
  	""];

  // block not completed, need more input or more output
  const NeedMore = 0;

  // block flush performed
  const BlockDone = 1;

  // finish started, need only more output at next deflate
  const FinishStarted = 2;

  // finish done, accept no more input or output
  const FinishDone = 3;

  // preset dictionary flag in zlib header
  const PRESET_DICT$1 = 0x20;

  const INIT_STATE = 42;
  const BUSY_STATE = 113;
  const FINISH_STATE = 666;

  // The deflate compression method
  const Z_DEFLATED$1 = 8;

  const STORED_BLOCK = 0;
  const STATIC_TREES = 1;
  const DYN_TREES = 2;

  const MIN_MATCH = 3;
  const MAX_MATCH = 258;
  const MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);

  function smaller(tree, n, m, depth) {
  	const tn2 = tree[n * 2];
  	const tm2 = tree[m * 2];
  	return (tn2 < tm2 || (tn2 == tm2 && depth[n] <= depth[m]));
  }

  function Deflate$1() {

  	const that = this;
  	let strm; // pointer back to this zlib stream
  	let status; // as the name implies
  	// pending_buf; // output still pending
  	let pending_buf_size; // size of pending_buf
  	// pending_out; // next pending byte to output to the stream
  	// pending; // nb of bytes in the pending buffer

  	// dist_buf; // buffer for distances
  	// lc_buf; // buffer for literals or lengths
  	// To simplify the code, dist_buf and lc_buf have the same number of elements.
  	// To use different lengths, an extra flag array would be necessary.

  	let last_flush; // value of flush param for previous deflate call

  	let w_size; // LZ77 win size (32K by default)
  	let w_bits; // log2(w_size) (8..16)
  	let w_mask; // w_size - 1

  	let win;
  	// Sliding win. Input bytes are read into the second half of the win,
  	// and move to the first half later to keep a dictionary of at least wSize
  	// bytes. With this organization, matches are limited to a distance of
  	// wSize-MAX_MATCH bytes, but this ensures that IO is always
  	// performed with a length multiple of the block size. Also, it limits
  	// the win size to 64K, which is quite useful on MSDOS.
  	// To do: use the user input buffer as sliding win.

  	let window_size;
  	// Actual size of win: 2*wSize, except when the user input buffer
  	// is directly used as sliding win.

  	let prev;
  	// Link to older string with same hash index. To limit the size of this
  	// array to 64K, this link is maintained only for the last 32K strings.
  	// An index in this array is thus a win index modulo 32K.

  	let head; // Heads of the hash chains or NIL.

  	let ins_h; // hash index of string to be inserted
  	let hash_size; // number of elements in hash table
  	let hash_bits; // log2(hash_size)
  	let hash_mask; // hash_size-1

  	// Number of bits by which ins_h must be shifted at each input
  	// step. It must be such that after MIN_MATCH steps, the oldest
  	// byte no longer takes part in the hash key, that is:
  	// hash_shift * MIN_MATCH >= hash_bits
  	let hash_shift;

  	// Window position at the beginning of the current output block. Gets
  	// negative when the win is moved backwards.

  	let block_start;

  	let match_length; // length of best match
  	let prev_match; // previous match
  	let match_available; // set if previous match exists
  	let strstart; // start of string to insert
  	let match_start; // start of matching string
  	let lookahead; // number of valid bytes ahead in win

  	// Length of the best match at previous step. Matches not greater than this
  	// are discarded. This is used in the lazy match evaluation.
  	let prev_length;

  	// To speed up deflation, hash chains are never searched beyond this
  	// length. A higher limit improves compression ratio but degrades the speed.
  	let max_chain_length;

  	// Attempt to find a better match only when the current match is strictly
  	// smaller than this value. This mechanism is used only for compression
  	// levels >= 4.
  	let max_lazy_match;

  	// Insert new strings in the hash table only if the match length is not
  	// greater than this length. This saves time but degrades compression.
  	// max_insert_length is used only for compression levels <= 3.

  	let level; // compression level (1..9)
  	let strategy; // favor or force Huffman coding

  	// Use a faster search when the previous match is longer than this
  	let good_match;

  	// Stop searching when current match exceeds this
  	let nice_match;

  	let dyn_ltree; // literal and length tree
  	let dyn_dtree; // distance tree
  	let bl_tree; // Huffman tree for bit lengths

  	const l_desc = new Tree(); // desc for literal tree
  	const d_desc = new Tree(); // desc for distance tree
  	const bl_desc = new Tree(); // desc for bit length tree

  	// that.heap_len; // number of elements in the heap
  	// that.heap_max; // element of largest frequency
  	// The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  	// The same heap array is used to build all trees.

  	// Depth of each subtree used as tie breaker for trees of equal frequency
  	that.depth = [];

  	// Size of match buffer for literals/lengths. There are 4 reasons for
  	// limiting lit_bufsize to 64K:
  	// - frequencies can be kept in 16 bit counters
  	// - if compression is not successful for the first block, all input
  	// data is still in the win so we can still emit a stored block even
  	// when input comes from standard input. (This can also be done for
  	// all blocks if lit_bufsize is not greater than 32K.)
  	// - if compression is not successful for a file smaller than 64K, we can
  	// even emit a stored file instead of a stored block (saving 5 bytes).
  	// This is applicable only for zip (not gzip or zlib).
  	// - creating new Huffman trees less frequently may not provide fast
  	// adaptation to changes in the input data statistics. (Take for
  	// example a binary file with poorly compressible code followed by
  	// a highly compressible string table.) Smaller buffer sizes give
  	// fast adaptation but have of course the overhead of transmitting
  	// trees more frequently.
  	// - I can't count above 4
  	let lit_bufsize;

  	let last_lit; // running index in dist_buf and lc_buf

  	// that.opt_len; // bit length of current block with optimal trees
  	// that.static_len; // bit length of current block with static trees
  	let matches; // number of string matches in current block
  	let last_eob_len; // bit length of EOB code for last block

  	// Output buffer. bits are inserted starting at the bottom (least
  	// significant bits).
  	let bi_buf;

  	// Number of valid bits in bi_buf. All bits above the last valid bit
  	// are always zero.
  	let bi_valid;

  	// number of codes at each bit length for an optimal tree
  	that.bl_count = [];

  	// heap used to build the Huffman trees
  	that.heap = [];

  	dyn_ltree = [];
  	dyn_dtree = [];
  	bl_tree = [];

  	function lm_init() {
  		window_size = 2 * w_size;

  		head[hash_size - 1] = 0;
  		for (let i = 0; i < hash_size - 1; i++) {
  			head[i] = 0;
  		}

  		// Set the default configuration parameters:
  		max_lazy_match = config_table[level].max_lazy;
  		good_match = config_table[level].good_length;
  		nice_match = config_table[level].nice_length;
  		max_chain_length = config_table[level].max_chain;

  		strstart = 0;
  		block_start = 0;
  		lookahead = 0;
  		match_length = prev_length = MIN_MATCH - 1;
  		match_available = 0;
  		ins_h = 0;
  	}

  	function init_block() {
  		let i;
  		// Initialize the trees.
  		for (i = 0; i < L_CODES; i++)
  			dyn_ltree[i * 2] = 0;
  		for (i = 0; i < D_CODES; i++)
  			dyn_dtree[i * 2] = 0;
  		for (i = 0; i < BL_CODES; i++)
  			bl_tree[i * 2] = 0;

  		dyn_ltree[END_BLOCK * 2] = 1;
  		that.opt_len = that.static_len = 0;
  		last_lit = matches = 0;
  	}

  	// Initialize the tree data structures for a new zlib stream.
  	function tr_init() {

  		l_desc.dyn_tree = dyn_ltree;
  		l_desc.stat_desc = StaticTree.static_l_desc;

  		d_desc.dyn_tree = dyn_dtree;
  		d_desc.stat_desc = StaticTree.static_d_desc;

  		bl_desc.dyn_tree = bl_tree;
  		bl_desc.stat_desc = StaticTree.static_bl_desc;

  		bi_buf = 0;
  		bi_valid = 0;
  		last_eob_len = 8; // enough lookahead for inflate

  		// Initialize the first block of the first file:
  		init_block();
  	}

  	// Restore the heap property by moving down the tree starting at node k,
  	// exchanging a node with the smallest of its two sons if necessary,
  	// stopping
  	// when the heap property is re-established (each father smaller than its
  	// two sons).
  	that.pqdownheap = function (tree, // the tree to restore
  		k // node to move down
  	) {
  		const heap = that.heap;
  		const v = heap[k];
  		let j = k << 1; // left son of k
  		while (j <= that.heap_len) {
  			// Set j to the smallest of the two sons:
  			if (j < that.heap_len && smaller(tree, heap[j + 1], heap[j], that.depth)) {
  				j++;
  			}
  			// Exit if v is smaller than both sons
  			if (smaller(tree, v, heap[j], that.depth))
  				break;

  			// Exchange v with the smallest son
  			heap[k] = heap[j];
  			k = j;
  			// And continue down the tree, setting j to the left son of k
  			j <<= 1;
  		}
  		heap[k] = v;
  	};

  	// Scan a literal or distance tree to determine the frequencies of the codes
  	// in the bit length tree.
  	function scan_tree(tree,// the tree to be scanned
  		max_code // and its largest code of non zero frequency
  	) {
  		let prevlen = -1; // last emitted length
  		let curlen; // length of current code
  		let nextlen = tree[0 * 2 + 1]; // length of next code
  		let count = 0; // repeat count of the current code
  		let max_count = 7; // max repeat count
  		let min_count = 4; // min repeat count

  		if (nextlen === 0) {
  			max_count = 138;
  			min_count = 3;
  		}
  		tree[(max_code + 1) * 2 + 1] = 0xffff; // guard

  		for (let n = 0; n <= max_code; n++) {
  			curlen = nextlen;
  			nextlen = tree[(n + 1) * 2 + 1];
  			if (++count < max_count && curlen == nextlen) {
  				continue;
  			} else if (count < min_count) {
  				bl_tree[curlen * 2] += count;
  			} else if (curlen !== 0) {
  				if (curlen != prevlen)
  					bl_tree[curlen * 2]++;
  				bl_tree[REP_3_6 * 2]++;
  			} else if (count <= 10) {
  				bl_tree[REPZ_3_10 * 2]++;
  			} else {
  				bl_tree[REPZ_11_138 * 2]++;
  			}
  			count = 0;
  			prevlen = curlen;
  			if (nextlen === 0) {
  				max_count = 138;
  				min_count = 3;
  			} else if (curlen == nextlen) {
  				max_count = 6;
  				min_count = 3;
  			} else {
  				max_count = 7;
  				min_count = 4;
  			}
  		}
  	}

  	// Construct the Huffman tree for the bit lengths and return the index in
  	// bl_order of the last bit length code to send.
  	function build_bl_tree() {
  		let max_blindex; // index of last bit length code of non zero freq

  		// Determine the bit length frequencies for literal and distance trees
  		scan_tree(dyn_ltree, l_desc.max_code);
  		scan_tree(dyn_dtree, d_desc.max_code);

  		// Build the bit length tree:
  		bl_desc.build_tree(that);
  		// opt_len now includes the length of the tree representations, except
  		// the lengths of the bit lengths codes and the 5+5+4 bits for the
  		// counts.

  		// Determine the number of bit length codes to send. The pkzip format
  		// requires that at least 4 bit length codes be sent. (appnote.txt says
  		// 3 but the actual value used is 4.)
  		for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  			if (bl_tree[Tree.bl_order[max_blindex] * 2 + 1] !== 0)
  				break;
  		}
  		// Update opt_len to include the bit length tree and counts
  		that.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;

  		return max_blindex;
  	}

  	// Output a byte on the stream.
  	// IN assertion: there is enough room in pending_buf.
  	function put_byte(p) {
  		that.pending_buf[that.pending++] = p;
  	}

  	function put_short(w) {
  		put_byte(w & 0xff);
  		put_byte((w >>> 8) & 0xff);
  	}

  	function putShortMSB(b) {
  		put_byte((b >> 8) & 0xff);
  		put_byte((b & 0xff) & 0xff);
  	}

  	function send_bits(value, length) {
  		let val;
  		const len = length;
  		if (bi_valid > Buf_size - len) {
  			val = value;
  			// bi_buf |= (val << bi_valid);
  			bi_buf |= ((val << bi_valid) & 0xffff);
  			put_short(bi_buf);
  			bi_buf = val >>> (Buf_size - bi_valid);
  			bi_valid += len - Buf_size;
  		} else {
  			// bi_buf |= (value) << bi_valid;
  			bi_buf |= (((value) << bi_valid) & 0xffff);
  			bi_valid += len;
  		}
  	}

  	function send_code(c, tree) {
  		const c2 = c * 2;
  		send_bits(tree[c2] & 0xffff, tree[c2 + 1] & 0xffff);
  	}

  	// Send a literal or distance tree in compressed form, using the codes in
  	// bl_tree.
  	function send_tree(tree,// the tree to be sent
  		max_code // and its largest code of non zero frequency
  	) {
  		let n; // iterates over all tree elements
  		let prevlen = -1; // last emitted length
  		let curlen; // length of current code
  		let nextlen = tree[0 * 2 + 1]; // length of next code
  		let count = 0; // repeat count of the current code
  		let max_count = 7; // max repeat count
  		let min_count = 4; // min repeat count

  		if (nextlen === 0) {
  			max_count = 138;
  			min_count = 3;
  		}

  		for (n = 0; n <= max_code; n++) {
  			curlen = nextlen;
  			nextlen = tree[(n + 1) * 2 + 1];
  			if (++count < max_count && curlen == nextlen) {
  				continue;
  			} else if (count < min_count) {
  				do {
  					send_code(curlen, bl_tree);
  				} while (--count !== 0);
  			} else if (curlen !== 0) {
  				if (curlen != prevlen) {
  					send_code(curlen, bl_tree);
  					count--;
  				}
  				send_code(REP_3_6, bl_tree);
  				send_bits(count - 3, 2);
  			} else if (count <= 10) {
  				send_code(REPZ_3_10, bl_tree);
  				send_bits(count - 3, 3);
  			} else {
  				send_code(REPZ_11_138, bl_tree);
  				send_bits(count - 11, 7);
  			}
  			count = 0;
  			prevlen = curlen;
  			if (nextlen === 0) {
  				max_count = 138;
  				min_count = 3;
  			} else if (curlen == nextlen) {
  				max_count = 6;
  				min_count = 3;
  			} else {
  				max_count = 7;
  				min_count = 4;
  			}
  		}
  	}

  	// Send the header for a block using dynamic Huffman trees: the counts, the
  	// lengths of the bit length codes, the literal tree and the distance tree.
  	// IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  	function send_all_trees(lcodes, dcodes, blcodes) {
  		let rank; // index in bl_order

  		send_bits(lcodes - 257, 5); // not +255 as stated in appnote.txt
  		send_bits(dcodes - 1, 5);
  		send_bits(blcodes - 4, 4); // not -3 as stated in appnote.txt
  		for (rank = 0; rank < blcodes; rank++) {
  			send_bits(bl_tree[Tree.bl_order[rank] * 2 + 1], 3);
  		}
  		send_tree(dyn_ltree, lcodes - 1); // literal tree
  		send_tree(dyn_dtree, dcodes - 1); // distance tree
  	}

  	// Flush the bit buffer, keeping at most 7 bits in it.
  	function bi_flush() {
  		if (bi_valid == 16) {
  			put_short(bi_buf);
  			bi_buf = 0;
  			bi_valid = 0;
  		} else if (bi_valid >= 8) {
  			put_byte(bi_buf & 0xff);
  			bi_buf >>>= 8;
  			bi_valid -= 8;
  		}
  	}

  	// Send one empty static block to give enough lookahead for inflate.
  	// This takes 10 bits, of which 7 may remain in the bit buffer.
  	// The current inflate code requires 9 bits of lookahead. If the
  	// last two codes for the previous block (real code plus EOB) were coded
  	// on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  	// the last real code. In this case we send two empty static blocks instead
  	// of one. (There are no problems if the previous block is stored or fixed.)
  	// To simplify the code, we assume the worst case of last real code encoded
  	// on one bit only.
  	function _tr_align() {
  		send_bits(STATIC_TREES << 1, 3);
  		send_code(END_BLOCK, StaticTree.static_ltree);

  		bi_flush();

  		// Of the 10 bits for the empty block, we have already sent
  		// (10 - bi_valid) bits. The lookahead for the last real code (before
  		// the EOB of the previous block) was thus at least one plus the length
  		// of the EOB plus what we have just sent of the empty static block.
  		if (1 + last_eob_len + 10 - bi_valid < 9) {
  			send_bits(STATIC_TREES << 1, 3);
  			send_code(END_BLOCK, StaticTree.static_ltree);
  			bi_flush();
  		}
  		last_eob_len = 7;
  	}

  	// Save the match info and tally the frequency counts. Return true if
  	// the current block must be flushed.
  	function _tr_tally(dist, // distance of matched string
  		lc // match length-MIN_MATCH or unmatched char (if dist==0)
  	) {
  		let out_length, in_length, dcode;
  		that.dist_buf[last_lit] = dist;
  		that.lc_buf[last_lit] = lc & 0xff;
  		last_lit++;

  		if (dist === 0) {
  			// lc is the unmatched char
  			dyn_ltree[lc * 2]++;
  		} else {
  			matches++;
  			// Here, lc is the match length - MIN_MATCH
  			dist--; // dist = match distance - 1
  			dyn_ltree[(Tree._length_code[lc] + LITERALS + 1) * 2]++;
  			dyn_dtree[Tree.d_code(dist) * 2]++;
  		}

  		if ((last_lit & 0x1fff) === 0 && level > 2) {
  			// Compute an upper bound for the compressed length
  			out_length = last_lit * 8;
  			in_length = strstart - block_start;
  			for (dcode = 0; dcode < D_CODES; dcode++) {
  				out_length += dyn_dtree[dcode * 2] * (5 + Tree.extra_dbits[dcode]);
  			}
  			out_length >>>= 3;
  			if ((matches < Math.floor(last_lit / 2)) && out_length < Math.floor(in_length / 2))
  				return true;
  		}

  		return (last_lit == lit_bufsize - 1);
  		// We avoid equality with lit_bufsize because of wraparound at 64K
  		// on 16 bit machines and because stored blocks are restricted to
  		// 64K-1 bytes.
  	}

  	// Send the block data compressed using the given Huffman trees
  	function compress_block(ltree, dtree) {
  		let dist; // distance of matched string
  		let lc; // match length or unmatched char (if dist === 0)
  		let lx = 0; // running index in dist_buf and lc_buf
  		let code; // the code to send
  		let extra; // number of extra bits to send

  		if (last_lit !== 0) {
  			do {
  				dist = that.dist_buf[lx];
  				lc = that.lc_buf[lx];
  				lx++;

  				if (dist === 0) {
  					send_code(lc, ltree); // send a literal byte
  				} else {
  					// Here, lc is the match length - MIN_MATCH
  					code = Tree._length_code[lc];

  					send_code(code + LITERALS + 1, ltree); // send the length
  					// code
  					extra = Tree.extra_lbits[code];
  					if (extra !== 0) {
  						lc -= Tree.base_length[code];
  						send_bits(lc, extra); // send the extra length bits
  					}
  					dist--; // dist is now the match distance - 1
  					code = Tree.d_code(dist);

  					send_code(code, dtree); // send the distance code
  					extra = Tree.extra_dbits[code];
  					if (extra !== 0) {
  						dist -= Tree.base_dist[code];
  						send_bits(dist, extra); // send the extra distance bits
  					}
  				} // literal or match pair ?
  			} while (lx < last_lit);
  		}

  		send_code(END_BLOCK, ltree);
  		last_eob_len = ltree[END_BLOCK * 2 + 1];
  	}

  	// Flush the bit buffer and align the output on a byte boundary
  	function bi_windup() {
  		if (bi_valid > 8) {
  			put_short(bi_buf);
  		} else if (bi_valid > 0) {
  			put_byte(bi_buf & 0xff);
  		}
  		bi_buf = 0;
  		bi_valid = 0;
  	}

  	// Copy a stored block, storing first the length and its
  	// one's complement if requested.
  	function copy_block(buf, // the input data
  		len, // its length
  		header // true if block header must be written
  	) {
  		bi_windup(); // align on byte boundary
  		last_eob_len = 8; // enough lookahead for inflate

  		if (header) {
  			put_short(len);
  			put_short(~len);
  		}

  		that.pending_buf.set(win.subarray(buf, buf + len), that.pending);
  		that.pending += len;
  	}

  	// Send a stored block
  	function _tr_stored_block(buf, // input block
  		stored_len, // length of input block
  		eof // true if this is the last block for a file
  	) {
  		send_bits((STORED_BLOCK << 1) + (eof ? 1 : 0), 3); // send block type
  		copy_block(buf, stored_len, true); // with header
  	}

  	// Determine the best encoding for the current block: dynamic trees, static
  	// trees or store, and output the encoded block to the zip file.
  	function _tr_flush_block(buf, // input block, or NULL if too old
  		stored_len, // length of input block
  		eof // true if this is the last block for a file
  	) {
  		let opt_lenb, static_lenb;// opt_len and static_len in bytes
  		let max_blindex = 0; // index of last bit length code of non zero freq

  		// Build the Huffman trees unless a stored block is forced
  		if (level > 0) {
  			// Construct the literal and distance trees
  			l_desc.build_tree(that);

  			d_desc.build_tree(that);

  			// At this point, opt_len and static_len are the total bit lengths
  			// of
  			// the compressed block data, excluding the tree representations.

  			// Build the bit length tree for the above two trees, and get the
  			// index
  			// in bl_order of the last bit length code to send.
  			max_blindex = build_bl_tree();

  			// Determine the best encoding. Compute first the block length in
  			// bytes
  			opt_lenb = (that.opt_len + 3 + 7) >>> 3;
  			static_lenb = (that.static_len + 3 + 7) >>> 3;

  			if (static_lenb <= opt_lenb)
  				opt_lenb = static_lenb;
  		} else {
  			opt_lenb = static_lenb = stored_len + 5; // force a stored block
  		}

  		if ((stored_len + 4 <= opt_lenb) && buf != -1) {
  			// 4: two words for the lengths
  			// The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  			// Otherwise we can't have processed more than WSIZE input bytes
  			// since
  			// the last block flush, because compression would have been
  			// successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  			// transform a block into a stored block.
  			_tr_stored_block(buf, stored_len, eof);
  		} else if (static_lenb == opt_lenb) {
  			send_bits((STATIC_TREES << 1) + (eof ? 1 : 0), 3);
  			compress_block(StaticTree.static_ltree, StaticTree.static_dtree);
  		} else {
  			send_bits((DYN_TREES << 1) + (eof ? 1 : 0), 3);
  			send_all_trees(l_desc.max_code + 1, d_desc.max_code + 1, max_blindex + 1);
  			compress_block(dyn_ltree, dyn_dtree);
  		}

  		// The above check is made mod 2^32, for files larger than 512 MB
  		// and uLong implemented on 32 bits.

  		init_block();

  		if (eof) {
  			bi_windup();
  		}
  	}

  	function flush_block_only(eof) {
  		_tr_flush_block(block_start >= 0 ? block_start : -1, strstart - block_start, eof);
  		block_start = strstart;
  		strm.flush_pending();
  	}

  	// Fill the win when the lookahead becomes insufficient.
  	// Updates strstart and lookahead.
  	//
  	// IN assertion: lookahead < MIN_LOOKAHEAD
  	// OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  	// At least one byte has been read, or avail_in === 0; reads are
  	// performed for at least two bytes (required for the zip translate_eol
  	// option -- not supported here).
  	function fill_window() {
  		let n, m;
  		let p;
  		let more; // Amount of free space at the end of the win.

  		do {
  			more = (window_size - lookahead - strstart);

  			// Deal with !@#$% 64K limit:
  			if (more === 0 && strstart === 0 && lookahead === 0) {
  				more = w_size;
  			} else if (more == -1) {
  				// Very unlikely, but possible on 16 bit machine if strstart ==
  				// 0
  				// and lookahead == 1 (input done one byte at time)
  				more--;

  				// If the win is almost full and there is insufficient
  				// lookahead,
  				// move the upper half to the lower one to make room in the
  				// upper half.
  			} else if (strstart >= w_size + w_size - MIN_LOOKAHEAD) {
  				win.set(win.subarray(w_size, w_size + w_size), 0);

  				match_start -= w_size;
  				strstart -= w_size; // we now have strstart >= MAX_DIST
  				block_start -= w_size;

  				// Slide the hash table (could be avoided with 32 bit values
  				// at the expense of memory usage). We slide even when level ==
  				// 0
  				// to keep the hash table consistent if we switch back to level
  				// > 0
  				// later. (Using level 0 permanently is not an optimal usage of
  				// zlib, so we don't care about this pathological case.)

  				n = hash_size;
  				p = n;
  				do {
  					m = (head[--p] & 0xffff);
  					head[p] = (m >= w_size ? m - w_size : 0);
  				} while (--n !== 0);

  				n = w_size;
  				p = n;
  				do {
  					m = (prev[--p] & 0xffff);
  					prev[p] = (m >= w_size ? m - w_size : 0);
  					// If n is not on any hash chain, prev[n] is garbage but
  					// its value will never be used.
  				} while (--n !== 0);
  				more += w_size;
  			}

  			if (strm.avail_in === 0)
  				return;

  			// If there was no sliding:
  			// strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  			// more == window_size - lookahead - strstart
  			// => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  			// => more >= window_size - 2*WSIZE + 2
  			// In the BIG_MEM or MMAP case (not yet supported),
  			// window_size == input_size + MIN_LOOKAHEAD &&
  			// strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  			// Otherwise, window_size == 2*WSIZE so more >= 2.
  			// If there was sliding, more >= WSIZE. So in all cases, more >= 2.

  			n = strm.read_buf(win, strstart + lookahead, more);
  			lookahead += n;

  			// Initialize the hash value now that we have some input:
  			if (lookahead >= MIN_MATCH) {
  				ins_h = win[strstart] & 0xff;
  				ins_h = (((ins_h) << hash_shift) ^ (win[strstart + 1] & 0xff)) & hash_mask;
  			}
  			// If the whole input has less than MIN_MATCH bytes, ins_h is
  			// garbage,
  			// but this is not important since only literal bytes will be
  			// emitted.
  		} while (lookahead < MIN_LOOKAHEAD && strm.avail_in !== 0);
  	}

  	// Copy without compression as much as possible from the input stream,
  	// return
  	// the current block state.
  	// This function does not insert new strings in the dictionary since
  	// uncompressible data is probably not useful. This function is used
  	// only for the level=0 compression option.
  	// NOTE: this function should be optimized to avoid extra copying from
  	// win to pending_buf.
  	function deflate_stored(flush) {
  		// Stored blocks are limited to 0xffff bytes, pending_buf is limited
  		// to pending_buf_size, and each stored block has a 5 byte header:

  		let max_block_size = 0xffff;
  		let max_start;

  		if (max_block_size > pending_buf_size - 5) {
  			max_block_size = pending_buf_size - 5;
  		}

  		// Copy as much as possible from input to output:
  		// eslint-disable-next-line no-constant-condition
  		while (true) {
  			// Fill the win as much as possible:
  			if (lookahead <= 1) {
  				fill_window();
  				if (lookahead === 0 && flush == Z_NO_FLUSH$1)
  					return NeedMore;
  				if (lookahead === 0)
  					break; // flush the current block
  			}

  			strstart += lookahead;
  			lookahead = 0;

  			// Emit a stored block if pending_buf will be full:
  			max_start = block_start + max_block_size;
  			if (strstart === 0 || strstart >= max_start) {
  				// strstart === 0 is possible when wraparound on 16-bit machine
  				lookahead = (strstart - max_start);
  				strstart = max_start;

  				flush_block_only(false);
  				if (strm.avail_out === 0)
  					return NeedMore;

  			}

  			// Flush if we may have to slide, otherwise block_start may become
  			// negative and the data will be gone:
  			if (strstart - block_start >= w_size - MIN_LOOKAHEAD) {
  				flush_block_only(false);
  				if (strm.avail_out === 0)
  					return NeedMore;
  			}
  		}

  		flush_block_only(flush == Z_FINISH$1);
  		if (strm.avail_out === 0)
  			return (flush == Z_FINISH$1) ? FinishStarted : NeedMore;

  		return flush == Z_FINISH$1 ? FinishDone : BlockDone;
  	}

  	function longest_match(cur_match) {
  		let chain_length = max_chain_length; // max hash chain length
  		let scan = strstart; // current string
  		let match; // matched string
  		let len; // length of current match
  		let best_len = prev_length; // best match length so far
  		const limit = strstart > (w_size - MIN_LOOKAHEAD) ? strstart - (w_size - MIN_LOOKAHEAD) : 0;
  		let _nice_match = nice_match;

  		// Stop when cur_match becomes <= limit. To simplify the code,
  		// we prevent matches with the string of win index 0.

  		const wmask = w_mask;

  		const strend = strstart + MAX_MATCH;
  		let scan_end1 = win[scan + best_len - 1];
  		let scan_end = win[scan + best_len];

  		// The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of
  		// 16.
  		// It is easy to get rid of this optimization if necessary.

  		// Do not waste too much time if we already have a good match:
  		if (prev_length >= good_match) {
  			chain_length >>= 2;
  		}

  		// Do not look for matches beyond the end of the input. This is
  		// necessary
  		// to make deflate deterministic.
  		if (_nice_match > lookahead)
  			_nice_match = lookahead;

  		do {
  			match = cur_match;

  			// Skip to next match if the match length cannot increase
  			// or if the match length is less than 2:
  			if (win[match + best_len] != scan_end || win[match + best_len - 1] != scan_end1 || win[match] != win[scan]
  				|| win[++match] != win[scan + 1])
  				continue;

  			// The check at best_len-1 can be removed because it will be made
  			// again later. (This heuristic is not always a win.)
  			// It is not necessary to compare scan[2] and match[2] since they
  			// are always equal when the other bytes match, given that
  			// the hash keys are equal and that HASH_BITS >= 8.
  			scan += 2;
  			match++;

  			// We check for insufficient lookahead only every 8th comparison;
  			// the 256th check will be made at strstart+258.
  			// eslint-disable-next-line no-empty
  			do {
  				// empty block
  			} while (win[++scan] == win[++match] && win[++scan] == win[++match] && win[++scan] == win[++match]
  			&& win[++scan] == win[++match] && win[++scan] == win[++match] && win[++scan] == win[++match]
  			&& win[++scan] == win[++match] && win[++scan] == win[++match] && scan < strend);

  			len = MAX_MATCH - (strend - scan);
  			scan = strend - MAX_MATCH;

  			if (len > best_len) {
  				match_start = cur_match;
  				best_len = len;
  				if (len >= _nice_match)
  					break;
  				scan_end1 = win[scan + best_len - 1];
  				scan_end = win[scan + best_len];
  			}

  		} while ((cur_match = (prev[cur_match & wmask] & 0xffff)) > limit && --chain_length !== 0);

  		if (best_len <= lookahead)
  			return best_len;
  		return lookahead;
  	}

  	// Compress as much as possible from the input stream, return the current
  	// block state.
  	// This function does not perform lazy evaluation of matches and inserts
  	// new strings in the dictionary only for unmatched strings or for short
  	// matches. It is used only for the fast compression options.
  	function deflate_fast(flush) {
  		// short hash_head = 0; // head of the hash chain
  		let hash_head = 0; // head of the hash chain
  		let bflush; // set if current block must be flushed

  		// eslint-disable-next-line no-constant-condition
  		while (true) {
  			// Make sure that we always have enough lookahead, except
  			// at the end of the input file. We need MAX_MATCH bytes
  			// for the next match, plus MIN_MATCH bytes to insert the
  			// string following the next match.
  			if (lookahead < MIN_LOOKAHEAD) {
  				fill_window();
  				if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH$1) {
  					return NeedMore;
  				}
  				if (lookahead === 0)
  					break; // flush the current block
  			}

  			// Insert the string win[strstart .. strstart+2] in the
  			// dictionary, and set hash_head to the head of the hash chain:
  			if (lookahead >= MIN_MATCH) {
  				ins_h = (((ins_h) << hash_shift) ^ (win[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;

  				// prev[strstart&w_mask]=hash_head=head[ins_h];
  				hash_head = (head[ins_h] & 0xffff);
  				prev[strstart & w_mask] = head[ins_h];
  				head[ins_h] = strstart;
  			}

  			// Find the longest match, discarding those <= prev_length.
  			// At this point we have always match_length < MIN_MATCH

  			if (hash_head !== 0 && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD) {
  				// To simplify the code, we prevent matches with the string
  				// of win index 0 (in particular we have to avoid a match
  				// of the string with itself at the start of the input file).
  				if (strategy != Z_HUFFMAN_ONLY) {
  					match_length = longest_match(hash_head);
  				}
  				// longest_match() sets match_start
  			}
  			if (match_length >= MIN_MATCH) {
  				// check_match(strstart, match_start, match_length);

  				bflush = _tr_tally(strstart - match_start, match_length - MIN_MATCH);

  				lookahead -= match_length;

  				// Insert new strings in the hash table only if the match length
  				// is not too large. This saves time but degrades compression.
  				if (match_length <= max_lazy_match && lookahead >= MIN_MATCH) {
  					match_length--; // string at strstart already in hash table
  					do {
  						strstart++;

  						ins_h = ((ins_h << hash_shift) ^ (win[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  						// prev[strstart&w_mask]=hash_head=head[ins_h];
  						hash_head = (head[ins_h] & 0xffff);
  						prev[strstart & w_mask] = head[ins_h];
  						head[ins_h] = strstart;

  						// strstart never exceeds WSIZE-MAX_MATCH, so there are
  						// always MIN_MATCH bytes ahead.
  					} while (--match_length !== 0);
  					strstart++;
  				} else {
  					strstart += match_length;
  					match_length = 0;
  					ins_h = win[strstart] & 0xff;

  					ins_h = (((ins_h) << hash_shift) ^ (win[strstart + 1] & 0xff)) & hash_mask;
  					// If lookahead < MIN_MATCH, ins_h is garbage, but it does
  					// not
  					// matter since it will be recomputed at next deflate call.
  				}
  			} else {
  				// No match, output a literal byte

  				bflush = _tr_tally(0, win[strstart] & 0xff);
  				lookahead--;
  				strstart++;
  			}
  			if (bflush) {

  				flush_block_only(false);
  				if (strm.avail_out === 0)
  					return NeedMore;
  			}
  		}

  		flush_block_only(flush == Z_FINISH$1);
  		if (strm.avail_out === 0) {
  			if (flush == Z_FINISH$1)
  				return FinishStarted;
  			else
  				return NeedMore;
  		}
  		return flush == Z_FINISH$1 ? FinishDone : BlockDone;
  	}

  	// Same as above, but achieves better compression. We use a lazy
  	// evaluation for matches: a match is finally adopted only if there is
  	// no better match at the next win position.
  	function deflate_slow(flush) {
  		// short hash_head = 0; // head of hash chain
  		let hash_head = 0; // head of hash chain
  		let bflush; // set if current block must be flushed
  		let max_insert;

  		// Process the input block.
  		// eslint-disable-next-line no-constant-condition
  		while (true) {
  			// Make sure that we always have enough lookahead, except
  			// at the end of the input file. We need MAX_MATCH bytes
  			// for the next match, plus MIN_MATCH bytes to insert the
  			// string following the next match.

  			if (lookahead < MIN_LOOKAHEAD) {
  				fill_window();
  				if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH$1) {
  					return NeedMore;
  				}
  				if (lookahead === 0)
  					break; // flush the current block
  			}

  			// Insert the string win[strstart .. strstart+2] in the
  			// dictionary, and set hash_head to the head of the hash chain:

  			if (lookahead >= MIN_MATCH) {
  				ins_h = (((ins_h) << hash_shift) ^ (win[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  				// prev[strstart&w_mask]=hash_head=head[ins_h];
  				hash_head = (head[ins_h] & 0xffff);
  				prev[strstart & w_mask] = head[ins_h];
  				head[ins_h] = strstart;
  			}

  			// Find the longest match, discarding those <= prev_length.
  			prev_length = match_length;
  			prev_match = match_start;
  			match_length = MIN_MATCH - 1;

  			if (hash_head !== 0 && prev_length < max_lazy_match && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD) {
  				// To simplify the code, we prevent matches with the string
  				// of win index 0 (in particular we have to avoid a match
  				// of the string with itself at the start of the input file).

  				if (strategy != Z_HUFFMAN_ONLY) {
  					match_length = longest_match(hash_head);
  				}
  				// longest_match() sets match_start

  				if (match_length <= 5 && (strategy == Z_FILTERED || (match_length == MIN_MATCH && strstart - match_start > 4096))) {

  					// If prev_match is also MIN_MATCH, match_start is garbage
  					// but we will ignore the current match anyway.
  					match_length = MIN_MATCH - 1;
  				}
  			}

  			// If there was a match at the previous step and the current
  			// match is not better, output the previous match:
  			if (prev_length >= MIN_MATCH && match_length <= prev_length) {
  				max_insert = strstart + lookahead - MIN_MATCH;
  				// Do not insert strings in hash table beyond this.

  				// check_match(strstart-1, prev_match, prev_length);

  				bflush = _tr_tally(strstart - 1 - prev_match, prev_length - MIN_MATCH);

  				// Insert in hash table all strings up to the end of the match.
  				// strstart-1 and strstart are already inserted. If there is not
  				// enough lookahead, the last two strings are not inserted in
  				// the hash table.
  				lookahead -= prev_length - 1;
  				prev_length -= 2;
  				do {
  					if (++strstart <= max_insert) {
  						ins_h = (((ins_h) << hash_shift) ^ (win[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  						// prev[strstart&w_mask]=hash_head=head[ins_h];
  						hash_head = (head[ins_h] & 0xffff);
  						prev[strstart & w_mask] = head[ins_h];
  						head[ins_h] = strstart;
  					}
  				} while (--prev_length !== 0);
  				match_available = 0;
  				match_length = MIN_MATCH - 1;
  				strstart++;

  				if (bflush) {
  					flush_block_only(false);
  					if (strm.avail_out === 0)
  						return NeedMore;
  				}
  			} else if (match_available !== 0) {

  				// If there was no match at the previous position, output a
  				// single literal. If there was a match but the current match
  				// is longer, truncate the previous match to a single literal.

  				bflush = _tr_tally(0, win[strstart - 1] & 0xff);

  				if (bflush) {
  					flush_block_only(false);
  				}
  				strstart++;
  				lookahead--;
  				if (strm.avail_out === 0)
  					return NeedMore;
  			} else {
  				// There is no previous match to compare with, wait for
  				// the next step to decide.

  				match_available = 1;
  				strstart++;
  				lookahead--;
  			}
  		}

  		if (match_available !== 0) {
  			bflush = _tr_tally(0, win[strstart - 1] & 0xff);
  			match_available = 0;
  		}
  		flush_block_only(flush == Z_FINISH$1);

  		if (strm.avail_out === 0) {
  			if (flush == Z_FINISH$1)
  				return FinishStarted;
  			else
  				return NeedMore;
  		}

  		return flush == Z_FINISH$1 ? FinishDone : BlockDone;
  	}

  	function deflateReset(strm) {
  		strm.total_in = strm.total_out = 0;
  		strm.msg = null; //

  		that.pending = 0;
  		that.pending_out = 0;

  		status = BUSY_STATE;

  		last_flush = Z_NO_FLUSH$1;

  		tr_init();
  		lm_init();
  		return Z_OK$1;
  	}

  	that.deflateInit = function (strm, _level, bits, _method, memLevel, _strategy) {
  		if (!_method)
  			_method = Z_DEFLATED$1;
  		if (!memLevel)
  			memLevel = DEF_MEM_LEVEL;
  		if (!_strategy)
  			_strategy = Z_DEFAULT_STRATEGY;

  		// byte[] my_version=ZLIB_VERSION;

  		//
  		// if (!version || version[0] != my_version[0]
  		// || stream_size != sizeof(z_stream)) {
  		// return Z_VERSION_ERROR;
  		// }

  		strm.msg = null;

  		if (_level == Z_DEFAULT_COMPRESSION)
  			_level = 6;

  		if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || _method != Z_DEFLATED$1 || bits < 9 || bits > 15 || _level < 0 || _level > 9 || _strategy < 0
  			|| _strategy > Z_HUFFMAN_ONLY) {
  			return Z_STREAM_ERROR$1;
  		}

  		strm.dstate = that;

  		w_bits = bits;
  		w_size = 1 << w_bits;
  		w_mask = w_size - 1;

  		hash_bits = memLevel + 7;
  		hash_size = 1 << hash_bits;
  		hash_mask = hash_size - 1;
  		hash_shift = Math.floor((hash_bits + MIN_MATCH - 1) / MIN_MATCH);

  		win = new Uint8Array(w_size * 2);
  		prev = [];
  		head = [];

  		lit_bufsize = 1 << (memLevel + 6); // 16K elements by default

  		that.pending_buf = new Uint8Array(lit_bufsize * 4);
  		pending_buf_size = lit_bufsize * 4;

  		that.dist_buf = new Uint16Array(lit_bufsize);
  		that.lc_buf = new Uint8Array(lit_bufsize);

  		level = _level;

  		strategy = _strategy;

  		return deflateReset(strm);
  	};

  	that.deflateEnd = function () {
  		if (status != INIT_STATE && status != BUSY_STATE && status != FINISH_STATE) {
  			return Z_STREAM_ERROR$1;
  		}
  		// Deallocate in reverse order of allocations:
  		that.lc_buf = null;
  		that.dist_buf = null;
  		that.pending_buf = null;
  		head = null;
  		prev = null;
  		win = null;
  		// free
  		that.dstate = null;
  		return status == BUSY_STATE ? Z_DATA_ERROR$1 : Z_OK$1;
  	};

  	that.deflateParams = function (strm, _level, _strategy) {
  		let err = Z_OK$1;

  		if (_level == Z_DEFAULT_COMPRESSION) {
  			_level = 6;
  		}
  		if (_level < 0 || _level > 9 || _strategy < 0 || _strategy > Z_HUFFMAN_ONLY) {
  			return Z_STREAM_ERROR$1;
  		}

  		if (config_table[level].func != config_table[_level].func && strm.total_in !== 0) {
  			// Flush the last buffer:
  			err = strm.deflate(Z_PARTIAL_FLUSH);
  		}

  		if (level != _level) {
  			level = _level;
  			max_lazy_match = config_table[level].max_lazy;
  			good_match = config_table[level].good_length;
  			nice_match = config_table[level].nice_length;
  			max_chain_length = config_table[level].max_chain;
  		}
  		strategy = _strategy;
  		return err;
  	};

  	that.deflateSetDictionary = function (_strm, dictionary, dictLength) {
  		let length = dictLength;
  		let n, index = 0;

  		if (!dictionary || status != INIT_STATE)
  			return Z_STREAM_ERROR$1;

  		if (length < MIN_MATCH)
  			return Z_OK$1;
  		if (length > w_size - MIN_LOOKAHEAD) {
  			length = w_size - MIN_LOOKAHEAD;
  			index = dictLength - length; // use the tail of the dictionary
  		}
  		win.set(dictionary.subarray(index, index + length), 0);

  		strstart = length;
  		block_start = length;

  		// Insert all strings in the hash table (except for the last two bytes).
  		// s->lookahead stays null, so s->ins_h will be recomputed at the next
  		// call of fill_window.

  		ins_h = win[0] & 0xff;
  		ins_h = (((ins_h) << hash_shift) ^ (win[1] & 0xff)) & hash_mask;

  		for (n = 0; n <= length - MIN_MATCH; n++) {
  			ins_h = (((ins_h) << hash_shift) ^ (win[(n) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  			prev[n & w_mask] = head[ins_h];
  			head[ins_h] = n;
  		}
  		return Z_OK$1;
  	};

  	that.deflate = function (_strm, flush) {
  		let i, header, level_flags, old_flush, bstate;

  		if (flush > Z_FINISH$1 || flush < 0) {
  			return Z_STREAM_ERROR$1;
  		}

  		if (!_strm.next_out || (!_strm.next_in && _strm.avail_in !== 0) || (status == FINISH_STATE && flush != Z_FINISH$1)) {
  			_strm.msg = z_errmsg[Z_NEED_DICT$1 - (Z_STREAM_ERROR$1)];
  			return Z_STREAM_ERROR$1;
  		}
  		if (_strm.avail_out === 0) {
  			_strm.msg = z_errmsg[Z_NEED_DICT$1 - (Z_BUF_ERROR$1)];
  			return Z_BUF_ERROR$1;
  		}

  		strm = _strm; // just in case
  		old_flush = last_flush;
  		last_flush = flush;

  		// Write the zlib header
  		if (status == INIT_STATE) {
  			header = (Z_DEFLATED$1 + ((w_bits - 8) << 4)) << 8;
  			level_flags = ((level - 1) & 0xff) >> 1;

  			if (level_flags > 3)
  				level_flags = 3;
  			header |= (level_flags << 6);
  			if (strstart !== 0)
  				header |= PRESET_DICT$1;
  			header += 31 - (header % 31);

  			status = BUSY_STATE;
  			putShortMSB(header);
  		}

  		// Flush as much pending output as possible
  		if (that.pending !== 0) {
  			strm.flush_pending();
  			if (strm.avail_out === 0) {
  				// console.log(" avail_out==0");
  				// Since avail_out is 0, deflate will be called again with
  				// more output space, but possibly with both pending and
  				// avail_in equal to zero. There won't be anything to do,
  				// but this is not an error situation so make sure we
  				// return OK instead of BUF_ERROR at next call of deflate:
  				last_flush = -1;
  				return Z_OK$1;
  			}

  			// Make sure there is something to do and avoid duplicate
  			// consecutive
  			// flushes. For repeated and useless calls with Z_FINISH, we keep
  			// returning Z_STREAM_END instead of Z_BUFF_ERROR.
  		} else if (strm.avail_in === 0 && flush <= old_flush && flush != Z_FINISH$1) {
  			strm.msg = z_errmsg[Z_NEED_DICT$1 - (Z_BUF_ERROR$1)];
  			return Z_BUF_ERROR$1;
  		}

  		// User must not provide more input after the first FINISH:
  		if (status == FINISH_STATE && strm.avail_in !== 0) {
  			_strm.msg = z_errmsg[Z_NEED_DICT$1 - (Z_BUF_ERROR$1)];
  			return Z_BUF_ERROR$1;
  		}

  		// Start a new block or continue the current one.
  		if (strm.avail_in !== 0 || lookahead !== 0 || (flush != Z_NO_FLUSH$1 && status != FINISH_STATE)) {
  			bstate = -1;
  			switch (config_table[level].func) {
  				case STORED$1:
  					bstate = deflate_stored(flush);
  					break;
  				case FAST:
  					bstate = deflate_fast(flush);
  					break;
  				case SLOW:
  					bstate = deflate_slow(flush);
  					break;
  			}

  			if (bstate == FinishStarted || bstate == FinishDone) {
  				status = FINISH_STATE;
  			}
  			if (bstate == NeedMore || bstate == FinishStarted) {
  				if (strm.avail_out === 0) {
  					last_flush = -1; // avoid BUF_ERROR next call, see above
  				}
  				return Z_OK$1;
  				// If flush != Z_NO_FLUSH && avail_out === 0, the next call
  				// of deflate should use the same flush parameter to make sure
  				// that the flush is complete. So we don't have to output an
  				// empty block here, this will be done at next call. This also
  				// ensures that for a very small output buffer, we emit at most
  				// one empty block.
  			}

  			if (bstate == BlockDone) {
  				if (flush == Z_PARTIAL_FLUSH) {
  					_tr_align();
  				} else { // FULL_FLUSH or SYNC_FLUSH
  					_tr_stored_block(0, 0, false);
  					// For a full flush, this empty block will be recognized
  					// as a special marker by inflate_sync().
  					if (flush == Z_FULL_FLUSH) {
  						// state.head[s.hash_size-1]=0;
  						for (i = 0; i < hash_size/*-1*/; i++)
  							// forget history
  							head[i] = 0;
  					}
  				}
  				strm.flush_pending();
  				if (strm.avail_out === 0) {
  					last_flush = -1; // avoid BUF_ERROR at next call, see above
  					return Z_OK$1;
  				}
  			}
  		}

  		if (flush != Z_FINISH$1)
  			return Z_OK$1;
  		return Z_STREAM_END$1;
  	};
  }

  // ZStream

  function ZStream$1() {
  	const that = this;
  	that.next_in_index = 0;
  	that.next_out_index = 0;
  	// that.next_in; // next input byte
  	that.avail_in = 0; // number of bytes available at next_in
  	that.total_in = 0; // total nb of input bytes read so far
  	// that.next_out; // next output byte should be put there
  	that.avail_out = 0; // remaining free space at next_out
  	that.total_out = 0; // total nb of bytes output so far
  	// that.msg;
  	// that.dstate;
  }

  ZStream$1.prototype = {
  	deflateInit: function (level, bits) {
  		const that = this;
  		that.dstate = new Deflate$1();
  		if (!bits)
  			bits = MAX_BITS$1;
  		return that.dstate.deflateInit(that, level, bits);
  	},

  	deflate: function (flush) {
  		const that = this;
  		if (!that.dstate) {
  			return Z_STREAM_ERROR$1;
  		}
  		return that.dstate.deflate(that, flush);
  	},

  	deflateEnd: function () {
  		const that = this;
  		if (!that.dstate)
  			return Z_STREAM_ERROR$1;
  		const ret = that.dstate.deflateEnd();
  		that.dstate = null;
  		return ret;
  	},

  	deflateParams: function (level, strategy) {
  		const that = this;
  		if (!that.dstate)
  			return Z_STREAM_ERROR$1;
  		return that.dstate.deflateParams(that, level, strategy);
  	},

  	deflateSetDictionary: function (dictionary, dictLength) {
  		const that = this;
  		if (!that.dstate)
  			return Z_STREAM_ERROR$1;
  		return that.dstate.deflateSetDictionary(that, dictionary, dictLength);
  	},

  	// Read a new buffer from the current input stream, update the
  	// total number of bytes read. All deflate() input goes through
  	// this function so some applications may wish to modify it to avoid
  	// allocating a large strm->next_in buffer and copying from it.
  	// (See also flush_pending()).
  	read_buf: function (buf, start, size) {
  		const that = this;
  		let len = that.avail_in;
  		if (len > size)
  			len = size;
  		if (len === 0)
  			return 0;
  		that.avail_in -= len;
  		buf.set(that.next_in.subarray(that.next_in_index, that.next_in_index + len), start);
  		that.next_in_index += len;
  		that.total_in += len;
  		return len;
  	},

  	// Flush as much pending output as possible. All deflate() output goes
  	// through this function so some applications may wish to modify it
  	// to avoid allocating a large strm->next_out buffer and copying into it.
  	// (See also read_buf()).
  	flush_pending: function () {
  		const that = this;
  		let len = that.dstate.pending;

  		if (len > that.avail_out)
  			len = that.avail_out;
  		if (len === 0)
  			return;

  		// if (that.dstate.pending_buf.length <= that.dstate.pending_out || that.next_out.length <= that.next_out_index
  		// || that.dstate.pending_buf.length < (that.dstate.pending_out + len) || that.next_out.length < (that.next_out_index +
  		// len)) {
  		// console.log(that.dstate.pending_buf.length + ", " + that.dstate.pending_out + ", " + that.next_out.length + ", " +
  		// that.next_out_index + ", " + len);
  		// console.log("avail_out=" + that.avail_out);
  		// }

  		that.next_out.set(that.dstate.pending_buf.subarray(that.dstate.pending_out, that.dstate.pending_out + len), that.next_out_index);

  		that.next_out_index += len;
  		that.dstate.pending_out += len;
  		that.total_out += len;
  		that.avail_out -= len;
  		that.dstate.pending -= len;
  		if (that.dstate.pending === 0) {
  			that.dstate.pending_out = 0;
  		}
  	}
  };

  // Deflate

  function ZipDeflate(options) {
  	const that = this;
  	const z = new ZStream$1();
  	const bufsize = getMaximumCompressedSize$1(options && options.chunkSize ? options.chunkSize : 64 * 1024);
  	const flush = Z_NO_FLUSH$1;
  	const buf = new Uint8Array(bufsize);
  	let level = options ? options.level : Z_DEFAULT_COMPRESSION;
  	if (typeof level == "undefined")
  		level = Z_DEFAULT_COMPRESSION;
  	z.deflateInit(level);
  	z.next_out = buf;

  	that.append = function (data, onprogress) {
  		let err, array, lastIndex = 0, bufferIndex = 0, bufferSize = 0;
  		const buffers = [];
  		if (!data.length)
  			return;
  		z.next_in_index = 0;
  		z.next_in = data;
  		z.avail_in = data.length;
  		do {
  			z.next_out_index = 0;
  			z.avail_out = bufsize;
  			err = z.deflate(flush);
  			if (err != Z_OK$1)
  				throw new Error("deflating: " + z.msg);
  			if (z.next_out_index)
  				if (z.next_out_index == bufsize)
  					buffers.push(new Uint8Array(buf));
  				else
  					buffers.push(buf.slice(0, z.next_out_index));
  			bufferSize += z.next_out_index;
  			if (onprogress && z.next_in_index > 0 && z.next_in_index != lastIndex) {
  				onprogress(z.next_in_index);
  				lastIndex = z.next_in_index;
  			}
  		} while (z.avail_in > 0 || z.avail_out === 0);
  		if (buffers.length > 1) {
  			array = new Uint8Array(bufferSize);
  			buffers.forEach(function (chunk) {
  				array.set(chunk, bufferIndex);
  				bufferIndex += chunk.length;
  			});
  		} else {
  			array = buffers[0] || new Uint8Array(0);
  		}
  		return array;
  	};
  	that.flush = function () {
  		let err, array, bufferIndex = 0, bufferSize = 0;
  		const buffers = [];
  		do {
  			z.next_out_index = 0;
  			z.avail_out = bufsize;
  			err = z.deflate(Z_FINISH$1);
  			if (err != Z_STREAM_END$1 && err != Z_OK$1)
  				throw new Error("deflating: " + z.msg);
  			if (bufsize - z.avail_out > 0)
  				buffers.push(buf.slice(0, z.next_out_index));
  			bufferSize += z.next_out_index;
  		} while (z.avail_in > 0 || z.avail_out === 0);
  		z.deflateEnd();
  		array = new Uint8Array(bufferSize);
  		buffers.forEach(function (chunk) {
  			array.set(chunk, bufferIndex);
  			bufferIndex += chunk.length;
  		});
  		return array;
  	};
  }

  function getMaximumCompressedSize$1(uncompressedSize) {
  	return uncompressedSize + (5 * (Math.floor(uncompressedSize / 16383) + 1));
  }

  /*
   Copyright (c) 2022 Gildas Lormeau. All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright 
   notice, this list of conditions and the following disclaimer in 
   the documentation and/or other materials provided with the distribution.

   3. The names of the authors may not be used to endorse or promote products
   derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
   INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
   OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
   EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   */

  /*
   * This program is based on JZlib 1.0.2 ymnk, JCraft,Inc.
   * JZlib is based on zlib-1.1.3, so all credit should go authors
   * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
   * and contributors of zlib.
   */

  // deno-lint-ignore-file no-this-alias prefer-const

  // Global
  const MAX_BITS = 15;

  const Z_OK$2 = 0;
  const Z_STREAM_END$2 = 1;
  const Z_NEED_DICT$2 = 2;
  const Z_STREAM_ERROR$2 = -2;
  const Z_DATA_ERROR$2 = -3;
  const Z_MEM_ERROR$1 = -4;
  const Z_BUF_ERROR$2 = -5;

  const inflate_mask = [0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000f, 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff, 0x000001ff, 0x000003ff,
  	0x000007ff, 0x00000fff, 0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff];

  const MANY = 1440;

  // JZlib version : "1.0.2"
  const Z_NO_FLUSH = 0;
  const Z_FINISH$2 = 4;

  // InfTree
  const fixed_bl = 9;
  const fixed_bd = 5;

  const fixed_tl = [96, 7, 256, 0, 8, 80, 0, 8, 16, 84, 8, 115, 82, 7, 31, 0, 8, 112, 0, 8, 48, 0, 9, 192, 80, 7, 10, 0, 8, 96, 0, 8, 32, 0, 9, 160, 0, 8, 0,
  	0, 8, 128, 0, 8, 64, 0, 9, 224, 80, 7, 6, 0, 8, 88, 0, 8, 24, 0, 9, 144, 83, 7, 59, 0, 8, 120, 0, 8, 56, 0, 9, 208, 81, 7, 17, 0, 8, 104, 0, 8, 40,
  	0, 9, 176, 0, 8, 8, 0, 8, 136, 0, 8, 72, 0, 9, 240, 80, 7, 4, 0, 8, 84, 0, 8, 20, 85, 8, 227, 83, 7, 43, 0, 8, 116, 0, 8, 52, 0, 9, 200, 81, 7, 13,
  	0, 8, 100, 0, 8, 36, 0, 9, 168, 0, 8, 4, 0, 8, 132, 0, 8, 68, 0, 9, 232, 80, 7, 8, 0, 8, 92, 0, 8, 28, 0, 9, 152, 84, 7, 83, 0, 8, 124, 0, 8, 60,
  	0, 9, 216, 82, 7, 23, 0, 8, 108, 0, 8, 44, 0, 9, 184, 0, 8, 12, 0, 8, 140, 0, 8, 76, 0, 9, 248, 80, 7, 3, 0, 8, 82, 0, 8, 18, 85, 8, 163, 83, 7,
  	35, 0, 8, 114, 0, 8, 50, 0, 9, 196, 81, 7, 11, 0, 8, 98, 0, 8, 34, 0, 9, 164, 0, 8, 2, 0, 8, 130, 0, 8, 66, 0, 9, 228, 80, 7, 7, 0, 8, 90, 0, 8,
  	26, 0, 9, 148, 84, 7, 67, 0, 8, 122, 0, 8, 58, 0, 9, 212, 82, 7, 19, 0, 8, 106, 0, 8, 42, 0, 9, 180, 0, 8, 10, 0, 8, 138, 0, 8, 74, 0, 9, 244, 80,
  	7, 5, 0, 8, 86, 0, 8, 22, 192, 8, 0, 83, 7, 51, 0, 8, 118, 0, 8, 54, 0, 9, 204, 81, 7, 15, 0, 8, 102, 0, 8, 38, 0, 9, 172, 0, 8, 6, 0, 8, 134, 0,
  	8, 70, 0, 9, 236, 80, 7, 9, 0, 8, 94, 0, 8, 30, 0, 9, 156, 84, 7, 99, 0, 8, 126, 0, 8, 62, 0, 9, 220, 82, 7, 27, 0, 8, 110, 0, 8, 46, 0, 9, 188, 0,
  	8, 14, 0, 8, 142, 0, 8, 78, 0, 9, 252, 96, 7, 256, 0, 8, 81, 0, 8, 17, 85, 8, 131, 82, 7, 31, 0, 8, 113, 0, 8, 49, 0, 9, 194, 80, 7, 10, 0, 8, 97,
  	0, 8, 33, 0, 9, 162, 0, 8, 1, 0, 8, 129, 0, 8, 65, 0, 9, 226, 80, 7, 6, 0, 8, 89, 0, 8, 25, 0, 9, 146, 83, 7, 59, 0, 8, 121, 0, 8, 57, 0, 9, 210,
  	81, 7, 17, 0, 8, 105, 0, 8, 41, 0, 9, 178, 0, 8, 9, 0, 8, 137, 0, 8, 73, 0, 9, 242, 80, 7, 4, 0, 8, 85, 0, 8, 21, 80, 8, 258, 83, 7, 43, 0, 8, 117,
  	0, 8, 53, 0, 9, 202, 81, 7, 13, 0, 8, 101, 0, 8, 37, 0, 9, 170, 0, 8, 5, 0, 8, 133, 0, 8, 69, 0, 9, 234, 80, 7, 8, 0, 8, 93, 0, 8, 29, 0, 9, 154,
  	84, 7, 83, 0, 8, 125, 0, 8, 61, 0, 9, 218, 82, 7, 23, 0, 8, 109, 0, 8, 45, 0, 9, 186, 0, 8, 13, 0, 8, 141, 0, 8, 77, 0, 9, 250, 80, 7, 3, 0, 8, 83,
  	0, 8, 19, 85, 8, 195, 83, 7, 35, 0, 8, 115, 0, 8, 51, 0, 9, 198, 81, 7, 11, 0, 8, 99, 0, 8, 35, 0, 9, 166, 0, 8, 3, 0, 8, 131, 0, 8, 67, 0, 9, 230,
  	80, 7, 7, 0, 8, 91, 0, 8, 27, 0, 9, 150, 84, 7, 67, 0, 8, 123, 0, 8, 59, 0, 9, 214, 82, 7, 19, 0, 8, 107, 0, 8, 43, 0, 9, 182, 0, 8, 11, 0, 8, 139,
  	0, 8, 75, 0, 9, 246, 80, 7, 5, 0, 8, 87, 0, 8, 23, 192, 8, 0, 83, 7, 51, 0, 8, 119, 0, 8, 55, 0, 9, 206, 81, 7, 15, 0, 8, 103, 0, 8, 39, 0, 9, 174,
  	0, 8, 7, 0, 8, 135, 0, 8, 71, 0, 9, 238, 80, 7, 9, 0, 8, 95, 0, 8, 31, 0, 9, 158, 84, 7, 99, 0, 8, 127, 0, 8, 63, 0, 9, 222, 82, 7, 27, 0, 8, 111,
  	0, 8, 47, 0, 9, 190, 0, 8, 15, 0, 8, 143, 0, 8, 79, 0, 9, 254, 96, 7, 256, 0, 8, 80, 0, 8, 16, 84, 8, 115, 82, 7, 31, 0, 8, 112, 0, 8, 48, 0, 9,
  	193, 80, 7, 10, 0, 8, 96, 0, 8, 32, 0, 9, 161, 0, 8, 0, 0, 8, 128, 0, 8, 64, 0, 9, 225, 80, 7, 6, 0, 8, 88, 0, 8, 24, 0, 9, 145, 83, 7, 59, 0, 8,
  	120, 0, 8, 56, 0, 9, 209, 81, 7, 17, 0, 8, 104, 0, 8, 40, 0, 9, 177, 0, 8, 8, 0, 8, 136, 0, 8, 72, 0, 9, 241, 80, 7, 4, 0, 8, 84, 0, 8, 20, 85, 8,
  	227, 83, 7, 43, 0, 8, 116, 0, 8, 52, 0, 9, 201, 81, 7, 13, 0, 8, 100, 0, 8, 36, 0, 9, 169, 0, 8, 4, 0, 8, 132, 0, 8, 68, 0, 9, 233, 80, 7, 8, 0, 8,
  	92, 0, 8, 28, 0, 9, 153, 84, 7, 83, 0, 8, 124, 0, 8, 60, 0, 9, 217, 82, 7, 23, 0, 8, 108, 0, 8, 44, 0, 9, 185, 0, 8, 12, 0, 8, 140, 0, 8, 76, 0, 9,
  	249, 80, 7, 3, 0, 8, 82, 0, 8, 18, 85, 8, 163, 83, 7, 35, 0, 8, 114, 0, 8, 50, 0, 9, 197, 81, 7, 11, 0, 8, 98, 0, 8, 34, 0, 9, 165, 0, 8, 2, 0, 8,
  	130, 0, 8, 66, 0, 9, 229, 80, 7, 7, 0, 8, 90, 0, 8, 26, 0, 9, 149, 84, 7, 67, 0, 8, 122, 0, 8, 58, 0, 9, 213, 82, 7, 19, 0, 8, 106, 0, 8, 42, 0, 9,
  	181, 0, 8, 10, 0, 8, 138, 0, 8, 74, 0, 9, 245, 80, 7, 5, 0, 8, 86, 0, 8, 22, 192, 8, 0, 83, 7, 51, 0, 8, 118, 0, 8, 54, 0, 9, 205, 81, 7, 15, 0, 8,
  	102, 0, 8, 38, 0, 9, 173, 0, 8, 6, 0, 8, 134, 0, 8, 70, 0, 9, 237, 80, 7, 9, 0, 8, 94, 0, 8, 30, 0, 9, 157, 84, 7, 99, 0, 8, 126, 0, 8, 62, 0, 9,
  	221, 82, 7, 27, 0, 8, 110, 0, 8, 46, 0, 9, 189, 0, 8, 14, 0, 8, 142, 0, 8, 78, 0, 9, 253, 96, 7, 256, 0, 8, 81, 0, 8, 17, 85, 8, 131, 82, 7, 31, 0,
  	8, 113, 0, 8, 49, 0, 9, 195, 80, 7, 10, 0, 8, 97, 0, 8, 33, 0, 9, 163, 0, 8, 1, 0, 8, 129, 0, 8, 65, 0, 9, 227, 80, 7, 6, 0, 8, 89, 0, 8, 25, 0, 9,
  	147, 83, 7, 59, 0, 8, 121, 0, 8, 57, 0, 9, 211, 81, 7, 17, 0, 8, 105, 0, 8, 41, 0, 9, 179, 0, 8, 9, 0, 8, 137, 0, 8, 73, 0, 9, 243, 80, 7, 4, 0, 8,
  	85, 0, 8, 21, 80, 8, 258, 83, 7, 43, 0, 8, 117, 0, 8, 53, 0, 9, 203, 81, 7, 13, 0, 8, 101, 0, 8, 37, 0, 9, 171, 0, 8, 5, 0, 8, 133, 0, 8, 69, 0, 9,
  	235, 80, 7, 8, 0, 8, 93, 0, 8, 29, 0, 9, 155, 84, 7, 83, 0, 8, 125, 0, 8, 61, 0, 9, 219, 82, 7, 23, 0, 8, 109, 0, 8, 45, 0, 9, 187, 0, 8, 13, 0, 8,
  	141, 0, 8, 77, 0, 9, 251, 80, 7, 3, 0, 8, 83, 0, 8, 19, 85, 8, 195, 83, 7, 35, 0, 8, 115, 0, 8, 51, 0, 9, 199, 81, 7, 11, 0, 8, 99, 0, 8, 35, 0, 9,
  	167, 0, 8, 3, 0, 8, 131, 0, 8, 67, 0, 9, 231, 80, 7, 7, 0, 8, 91, 0, 8, 27, 0, 9, 151, 84, 7, 67, 0, 8, 123, 0, 8, 59, 0, 9, 215, 82, 7, 19, 0, 8,
  	107, 0, 8, 43, 0, 9, 183, 0, 8, 11, 0, 8, 139, 0, 8, 75, 0, 9, 247, 80, 7, 5, 0, 8, 87, 0, 8, 23, 192, 8, 0, 83, 7, 51, 0, 8, 119, 0, 8, 55, 0, 9,
  	207, 81, 7, 15, 0, 8, 103, 0, 8, 39, 0, 9, 175, 0, 8, 7, 0, 8, 135, 0, 8, 71, 0, 9, 239, 80, 7, 9, 0, 8, 95, 0, 8, 31, 0, 9, 159, 84, 7, 99, 0, 8,
  	127, 0, 8, 63, 0, 9, 223, 82, 7, 27, 0, 8, 111, 0, 8, 47, 0, 9, 191, 0, 8, 15, 0, 8, 143, 0, 8, 79, 0, 9, 255];
  const fixed_td = [80, 5, 1, 87, 5, 257, 83, 5, 17, 91, 5, 4097, 81, 5, 5, 89, 5, 1025, 85, 5, 65, 93, 5, 16385, 80, 5, 3, 88, 5, 513, 84, 5, 33, 92, 5,
  	8193, 82, 5, 9, 90, 5, 2049, 86, 5, 129, 192, 5, 24577, 80, 5, 2, 87, 5, 385, 83, 5, 25, 91, 5, 6145, 81, 5, 7, 89, 5, 1537, 85, 5, 97, 93, 5,
  	24577, 80, 5, 4, 88, 5, 769, 84, 5, 49, 92, 5, 12289, 82, 5, 13, 90, 5, 3073, 86, 5, 193, 192, 5, 24577];

  // Tables for deflate from PKZIP's appnote.txt.
  const cplens = [ // Copy lengths for literal codes 257..285
  	3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0];

  // see note #13 above about 258
  const cplext = [ // Extra bits for literal codes 257..285
  	0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112 // 112==invalid
  ];

  const cpdist = [ // Copy offsets for distance codes 0..29
  	1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577];

  const cpdext = [ // Extra bits for distance codes
  	0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13];

  // If BMAX needs to be larger than 16, then h and x[] should be uLong.
  const BMAX = 15; // maximum bit length of any code

  function InfTree() {
  	const that = this;

  	let hn; // hufts used in space
  	let v; // work area for huft_build
  	let c; // bit length count table
  	let r; // table entry for structure assignment
  	let u; // table stack
  	let x; // bit offsets, then code stack

  	function huft_build(b, // code lengths in bits (all assumed <=
  		// BMAX)
  		bindex, n, // number of codes (assumed <= 288)
  		s, // number of simple-valued codes (0..s-1)
  		d, // list of base values for non-simple codes
  		e, // list of extra bits for non-simple codes
  		t, // result: starting table
  		m, // maximum lookup bits, returns actual
  		hp,// space for trees
  		hn,// hufts used in space
  		v // working area: values in order of bit length
  	) {
  		// Given a list of code lengths and a maximum table size, make a set of
  		// tables to decode that set of codes. Return Z_OK on success,
  		// Z_BUF_ERROR
  		// if the given code set is incomplete (the tables are still built in
  		// this
  		// case), Z_DATA_ERROR if the input is invalid (an over-subscribed set
  		// of
  		// lengths), or Z_MEM_ERROR if not enough memory.

  		let a; // counter for codes of length k
  		let f; // i repeats in table every f entries
  		let g; // maximum code length
  		let h; // table level
  		let i; // counter, current code
  		let j; // counter
  		let k; // number of bits in current code
  		let l; // bits per table (returned in m)
  		let mask; // (1 << w) - 1, to avoid cc -O bug on HP
  		let p; // pointer into c[], b[], or v[]
  		let q; // points to current table
  		let w; // bits before this table == (l * h)
  		let xp; // pointer into x
  		let y; // number of dummy codes added
  		let z; // number of entries in current table

  		// Generate counts for each bit length

  		p = 0;
  		i = n;
  		do {
  			c[b[bindex + p]]++;
  			p++;
  			i--; // assume all entries <= BMAX
  		} while (i !== 0);

  		if (c[0] == n) { // null input--all zero length codes
  			t[0] = -1;
  			m[0] = 0;
  			return Z_OK$2;
  		}

  		// Find minimum and maximum length, bound *m by those
  		l = m[0];
  		for (j = 1; j <= BMAX; j++)
  			if (c[j] !== 0)
  				break;
  		k = j; // minimum code length
  		if (l < j) {
  			l = j;
  		}
  		for (i = BMAX; i !== 0; i--) {
  			if (c[i] !== 0)
  				break;
  		}
  		g = i; // maximum code length
  		if (l > i) {
  			l = i;
  		}
  		m[0] = l;

  		// Adjust last length count to fill out codes, if needed
  		for (y = 1 << j; j < i; j++, y <<= 1) {
  			if ((y -= c[j]) < 0) {
  				return Z_DATA_ERROR$2;
  			}
  		}
  		if ((y -= c[i]) < 0) {
  			return Z_DATA_ERROR$2;
  		}
  		c[i] += y;

  		// Generate starting offsets into the value table for each length
  		x[1] = j = 0;
  		p = 1;
  		xp = 2;
  		while (--i !== 0) { // note that i == g from above
  			x[xp] = (j += c[p]);
  			xp++;
  			p++;
  		}

  		// Make a table of values in order of bit lengths
  		i = 0;
  		p = 0;
  		do {
  			if ((j = b[bindex + p]) !== 0) {
  				v[x[j]++] = i;
  			}
  			p++;
  		} while (++i < n);
  		n = x[g]; // set n to length of v

  		// Generate the Huffman codes and for each, make the table entries
  		x[0] = i = 0; // first Huffman code is zero
  		p = 0; // grab values in bit order
  		h = -1; // no tables yet--level -1
  		w = -l; // bits decoded == (l * h)
  		u[0] = 0; // just to keep compilers happy
  		q = 0; // ditto
  		z = 0; // ditto

  		// go through the bit lengths (k already is bits in shortest code)
  		for (; k <= g; k++) {
  			a = c[k];
  			while (a-- !== 0) {
  				// here i is the Huffman code of length k bits for value *p
  				// make tables up to required level
  				while (k > w + l) {
  					h++;
  					w += l; // previous table always l bits
  					// compute minimum size table less than or equal to l bits
  					z = g - w;
  					z = (z > l) ? l : z; // table size upper limit
  					if ((f = 1 << (j = k - w)) > a + 1) { // try a k-w bit table
  						// too few codes for
  						// k-w bit table
  						f -= a + 1; // deduct codes from patterns left
  						xp = k;
  						if (j < z) {
  							while (++j < z) { // try smaller tables up to z bits
  								if ((f <<= 1) <= c[++xp])
  									break; // enough codes to use up j bits
  								f -= c[xp]; // else deduct codes from patterns
  							}
  						}
  					}
  					z = 1 << j; // table entries for j-bit table

  					// allocate new table
  					if (hn[0] + z > MANY) { // (note: doesn't matter for fixed)
  						return Z_DATA_ERROR$2; // overflow of MANY
  					}
  					u[h] = q = /* hp+ */hn[0]; // DEBUG
  					hn[0] += z;

  					// connect to last table, if there is one
  					if (h !== 0) {
  						x[h] = i; // save pattern for backing up
  						r[0] = /* (byte) */j; // bits in this table
  						r[1] = /* (byte) */l; // bits to dump before this table
  						j = i >>> (w - l);
  						r[2] = /* (int) */(q - u[h - 1] - j); // offset to this table
  						hp.set(r, (u[h - 1] + j) * 3);
  						// to
  						// last
  						// table
  					} else {
  						t[0] = q; // first table is returned result
  					}
  				}

  				// set up table entry in r
  				r[1] = /* (byte) */(k - w);
  				if (p >= n) {
  					r[0] = 128 + 64; // out of values--invalid code
  				} else if (v[p] < s) {
  					r[0] = /* (byte) */(v[p] < 256 ? 0 : 32 + 64); // 256 is
  					// end-of-block
  					r[2] = v[p++]; // simple code is just the value
  				} else {
  					r[0] = /* (byte) */(e[v[p] - s] + 16 + 64); // non-simple--look
  					// up in lists
  					r[2] = d[v[p++] - s];
  				}

  				// fill code-like entries with r
  				f = 1 << (k - w);
  				for (j = i >>> w; j < z; j += f) {
  					hp.set(r, (q + j) * 3);
  				}

  				// backwards increment the k-bit code i
  				for (j = 1 << (k - 1); (i & j) !== 0; j >>>= 1) {
  					i ^= j;
  				}
  				i ^= j;

  				// backup over finished tables
  				mask = (1 << w) - 1; // needed on HP, cc -O bug
  				while ((i & mask) != x[h]) {
  					h--; // don't need to update q
  					w -= l;
  					mask = (1 << w) - 1;
  				}
  			}
  		}
  		// Return Z_BUF_ERROR if we were given an incomplete table
  		return y !== 0 && g != 1 ? Z_BUF_ERROR$2 : Z_OK$2;
  	}

  	function initWorkArea(vsize) {
  		let i;
  		if (!hn) {
  			hn = []; // []; //new Array(1);
  			v = []; // new Array(vsize);
  			c = new Int32Array(BMAX + 1); // new Array(BMAX + 1);
  			r = []; // new Array(3);
  			u = new Int32Array(BMAX); // new Array(BMAX);
  			x = new Int32Array(BMAX + 1); // new Array(BMAX + 1);
  		}
  		if (v.length < vsize) {
  			v = []; // new Array(vsize);
  		}
  		for (i = 0; i < vsize; i++) {
  			v[i] = 0;
  		}
  		for (i = 0; i < BMAX + 1; i++) {
  			c[i] = 0;
  		}
  		for (i = 0; i < 3; i++) {
  			r[i] = 0;
  		}
  		// for(int i=0; i<BMAX; i++){u[i]=0;}
  		u.set(c.subarray(0, BMAX), 0);
  		// for(int i=0; i<BMAX+1; i++){x[i]=0;}
  		x.set(c.subarray(0, BMAX + 1), 0);
  	}

  	that.inflate_trees_bits = function (c, // 19 code lengths
  		bb, // bits tree desired/actual depth
  		tb, // bits tree result
  		hp, // space for trees
  		z // for messages
  	) {
  		let result;
  		initWorkArea(19);
  		hn[0] = 0;
  		result = huft_build(c, 0, 19, 19, null, null, tb, bb, hp, hn, v);

  		if (result == Z_DATA_ERROR$2) {
  			z.msg = "oversubscribed dynamic bit lengths tree";
  		} else if (result == Z_BUF_ERROR$2 || bb[0] === 0) {
  			z.msg = "incomplete dynamic bit lengths tree";
  			result = Z_DATA_ERROR$2;
  		}
  		return result;
  	};

  	that.inflate_trees_dynamic = function (nl, // number of literal/length codes
  		nd, // number of distance codes
  		c, // that many (total) code lengths
  		bl, // literal desired/actual bit depth
  		bd, // distance desired/actual bit depth
  		tl, // literal/length tree result
  		td, // distance tree result
  		hp, // space for trees
  		z // for messages
  	) {
  		let result;

  		// build literal/length tree
  		initWorkArea(288);
  		hn[0] = 0;
  		result = huft_build(c, 0, nl, 257, cplens, cplext, tl, bl, hp, hn, v);
  		if (result != Z_OK$2 || bl[0] === 0) {
  			if (result == Z_DATA_ERROR$2) {
  				z.msg = "oversubscribed literal/length tree";
  			} else if (result != Z_MEM_ERROR$1) {
  				z.msg = "incomplete literal/length tree";
  				result = Z_DATA_ERROR$2;
  			}
  			return result;
  		}

  		// build distance tree
  		initWorkArea(288);
  		result = huft_build(c, nl, nd, 0, cpdist, cpdext, td, bd, hp, hn, v);

  		if (result != Z_OK$2 || (bd[0] === 0 && nl > 257)) {
  			if (result == Z_DATA_ERROR$2) {
  				z.msg = "oversubscribed distance tree";
  			} else if (result == Z_BUF_ERROR$2) {
  				z.msg = "incomplete distance tree";
  				result = Z_DATA_ERROR$2;
  			} else if (result != Z_MEM_ERROR$1) {
  				z.msg = "empty distance tree with lengths";
  				result = Z_DATA_ERROR$2;
  			}
  			return result;
  		}

  		return Z_OK$2;
  	};

  }

  InfTree.inflate_trees_fixed = function (bl, // literal desired/actual bit depth
  	bd, // distance desired/actual bit depth
  	tl,// literal/length tree result
  	td// distance tree result
  ) {
  	bl[0] = fixed_bl;
  	bd[0] = fixed_bd;
  	tl[0] = fixed_tl;
  	td[0] = fixed_td;
  	return Z_OK$2;
  };

  // InfCodes

  // waiting for "i:"=input,
  // "o:"=output,
  // "x:"=nothing
  const START = 0; // x: set up for LEN
  const LEN$1 = 1; // i: get length/literal/eob next
  const LENEXT$1 = 2; // i: getting length extra (have base)
  const DIST$1 = 3; // i: get distance next
  const DISTEXT$1 = 4;// i: getting distance extra
  const COPY$1 = 5; // o: copying bytes in win, waiting
  // for space
  const LIT$1 = 6; // o: got literal, waiting for output
  // space
  const WASH = 7; // o: got eob, possibly still output
  // waiting
  const END = 8; // x: got eob and all data flushed
  const BADCODE = 9;// x: got error

  function InfCodes() {
  	const that = this;

  	let mode; // current inflate_codes mode

  	// mode dependent information
  	let len = 0;

  	let tree; // pointer into tree
  	let tree_index = 0;
  	let need = 0; // bits needed

  	let lit = 0;

  	// if EXT or COPY, where and how much
  	let get = 0; // bits to get for extra
  	let dist = 0; // distance back to copy from

  	let lbits = 0; // ltree bits decoded per branch
  	let dbits = 0; // dtree bits decoder per branch
  	let ltree; // literal/length/eob tree
  	let ltree_index = 0; // literal/length/eob tree
  	let dtree; // distance tree
  	let dtree_index = 0; // distance tree

  	// Called with number of bytes left to write in win at least 258
  	// (the maximum string length) and number of input bytes available
  	// at least ten. The ten bytes are six bytes for the longest length/
  	// distance pair plus four bytes for overloading the bit buffer.

  	function inflate_fast(bl, bd, tl, tl_index, td, td_index, s, z) {
  		let t; // temporary pointer
  		let tp; // temporary pointer
  		let tp_index; // temporary pointer
  		let e; // extra bits or operation
  		let b; // bit buffer
  		let k; // bits in bit buffer
  		let p; // input data pointer
  		let n; // bytes available there
  		let q; // output win write pointer
  		let m; // bytes to end of win or read pointer
  		let ml; // mask for literal/length tree
  		let md; // mask for distance tree
  		let c; // bytes to copy
  		let d; // distance back to copy from
  		let r; // copy source pointer

  		let tp_index_t_3; // (tp_index+t)*3

  		// load input, output, bit values
  		p = z.next_in_index;
  		n = z.avail_in;
  		b = s.bitb;
  		k = s.bitk;
  		q = s.write;
  		m = q < s.read ? s.read - q - 1 : s.end - q;

  		// initialize masks
  		ml = inflate_mask[bl];
  		md = inflate_mask[bd];

  		// do until not enough input or output space for fast loop
  		do { // assume called with m >= 258 && n >= 10
  			// get literal/length code
  			while (k < (20)) { // max bits for literal/length code
  				n--;
  				b |= (z.read_byte(p++) & 0xff) << k;
  				k += 8;
  			}

  			t = b & ml;
  			tp = tl;
  			tp_index = tl_index;
  			tp_index_t_3 = (tp_index + t) * 3;
  			if ((e = tp[tp_index_t_3]) === 0) {
  				b >>= (tp[tp_index_t_3 + 1]);
  				k -= (tp[tp_index_t_3 + 1]);

  				s.win[q++] = /* (byte) */tp[tp_index_t_3 + 2];
  				m--;
  				continue;
  			}
  			do {

  				b >>= (tp[tp_index_t_3 + 1]);
  				k -= (tp[tp_index_t_3 + 1]);

  				if ((e & 16) !== 0) {
  					e &= 15;
  					c = tp[tp_index_t_3 + 2] + (/* (int) */b & inflate_mask[e]);

  					b >>= e;
  					k -= e;

  					// decode distance base of block to copy
  					while (k < (15)) { // max bits for distance code
  						n--;
  						b |= (z.read_byte(p++) & 0xff) << k;
  						k += 8;
  					}

  					t = b & md;
  					tp = td;
  					tp_index = td_index;
  					tp_index_t_3 = (tp_index + t) * 3;
  					e = tp[tp_index_t_3];

  					do {

  						b >>= (tp[tp_index_t_3 + 1]);
  						k -= (tp[tp_index_t_3 + 1]);

  						if ((e & 16) !== 0) {
  							// get extra bits to add to distance base
  							e &= 15;
  							while (k < (e)) { // get extra bits (up to 13)
  								n--;
  								b |= (z.read_byte(p++) & 0xff) << k;
  								k += 8;
  							}

  							d = tp[tp_index_t_3 + 2] + (b & inflate_mask[e]);

  							b >>= (e);
  							k -= (e);

  							// do the copy
  							m -= c;
  							if (q >= d) { // offset before dest
  								// just copy
  								r = q - d;
  								if (q - r > 0 && 2 > (q - r)) {
  									s.win[q++] = s.win[r++]; // minimum
  									// count is
  									// three,
  									s.win[q++] = s.win[r++]; // so unroll
  									// loop a
  									// little
  									c -= 2;
  								} else {
  									s.win.set(s.win.subarray(r, r + 2), q);
  									q += 2;
  									r += 2;
  									c -= 2;
  								}
  							} else { // else offset after destination
  								r = q - d;
  								do {
  									r += s.end; // force pointer in win
  								} while (r < 0); // covers invalid distances
  								e = s.end - r;
  								if (c > e) { // if source crosses,
  									c -= e; // wrapped copy
  									if (q - r > 0 && e > (q - r)) {
  										do {
  											s.win[q++] = s.win[r++];
  										} while (--e !== 0);
  									} else {
  										s.win.set(s.win.subarray(r, r + e), q);
  										q += e;
  										r += e;
  										e = 0;
  									}
  									r = 0; // copy rest from start of win
  								}

  							}

  							// copy all or what's left
  							if (q - r > 0 && c > (q - r)) {
  								do {
  									s.win[q++] = s.win[r++];
  								} while (--c !== 0);
  							} else {
  								s.win.set(s.win.subarray(r, r + c), q);
  								q += c;
  								r += c;
  								c = 0;
  							}
  							break;
  						} else if ((e & 64) === 0) {
  							t += tp[tp_index_t_3 + 2];
  							t += (b & inflate_mask[e]);
  							tp_index_t_3 = (tp_index + t) * 3;
  							e = tp[tp_index_t_3];
  						} else {
  							z.msg = "invalid distance code";

  							c = z.avail_in - n;
  							c = (k >> 3) < c ? k >> 3 : c;
  							n += c;
  							p -= c;
  							k -= c << 3;

  							s.bitb = b;
  							s.bitk = k;
  							z.avail_in = n;
  							z.total_in += p - z.next_in_index;
  							z.next_in_index = p;
  							s.write = q;

  							return Z_DATA_ERROR$2;
  						}
  						// eslint-disable-next-line no-constant-condition
  					} while (true);
  					break;
  				}

  				if ((e & 64) === 0) {
  					t += tp[tp_index_t_3 + 2];
  					t += (b & inflate_mask[e]);
  					tp_index_t_3 = (tp_index + t) * 3;
  					if ((e = tp[tp_index_t_3]) === 0) {

  						b >>= (tp[tp_index_t_3 + 1]);
  						k -= (tp[tp_index_t_3 + 1]);

  						s.win[q++] = /* (byte) */tp[tp_index_t_3 + 2];
  						m--;
  						break;
  					}
  				} else if ((e & 32) !== 0) {

  					c = z.avail_in - n;
  					c = (k >> 3) < c ? k >> 3 : c;
  					n += c;
  					p -= c;
  					k -= c << 3;

  					s.bitb = b;
  					s.bitk = k;
  					z.avail_in = n;
  					z.total_in += p - z.next_in_index;
  					z.next_in_index = p;
  					s.write = q;

  					return Z_STREAM_END$2;
  				} else {
  					z.msg = "invalid literal/length code";

  					c = z.avail_in - n;
  					c = (k >> 3) < c ? k >> 3 : c;
  					n += c;
  					p -= c;
  					k -= c << 3;

  					s.bitb = b;
  					s.bitk = k;
  					z.avail_in = n;
  					z.total_in += p - z.next_in_index;
  					z.next_in_index = p;
  					s.write = q;

  					return Z_DATA_ERROR$2;
  				}
  				// eslint-disable-next-line no-constant-condition
  			} while (true);
  		} while (m >= 258 && n >= 10);

  		// not enough input or output--restore pointers and return
  		c = z.avail_in - n;
  		c = (k >> 3) < c ? k >> 3 : c;
  		n += c;
  		p -= c;
  		k -= c << 3;

  		s.bitb = b;
  		s.bitk = k;
  		z.avail_in = n;
  		z.total_in += p - z.next_in_index;
  		z.next_in_index = p;
  		s.write = q;

  		return Z_OK$2;
  	}

  	that.init = function (bl, bd, tl, tl_index, td, td_index) {
  		mode = START;
  		lbits = /* (byte) */bl;
  		dbits = /* (byte) */bd;
  		ltree = tl;
  		ltree_index = tl_index;
  		dtree = td;
  		dtree_index = td_index;
  		tree = null;
  	};

  	that.proc = function (s, z, r) {
  		let j; // temporary storage
  		let tindex; // temporary pointer
  		let e; // extra bits or operation
  		let b = 0; // bit buffer
  		let k = 0; // bits in bit buffer
  		let p = 0; // input data pointer
  		let n; // bytes available there
  		let q; // output win write pointer
  		let m; // bytes to end of win or read pointer
  		let f; // pointer to copy strings from

  		// copy input/output information to locals (UPDATE macro restores)
  		p = z.next_in_index;
  		n = z.avail_in;
  		b = s.bitb;
  		k = s.bitk;
  		q = s.write;
  		m = q < s.read ? s.read - q - 1 : s.end - q;

  		// process input and output based on current state
  		// eslint-disable-next-line no-constant-condition
  		while (true) {
  			switch (mode) {
  				// waiting for "i:"=input, "o:"=output, "x:"=nothing
  				case START: // x: set up for LEN
  					if (m >= 258 && n >= 10) {

  						s.bitb = b;
  						s.bitk = k;
  						z.avail_in = n;
  						z.total_in += p - z.next_in_index;
  						z.next_in_index = p;
  						s.write = q;
  						r = inflate_fast(lbits, dbits, ltree, ltree_index, dtree, dtree_index, s, z);

  						p = z.next_in_index;
  						n = z.avail_in;
  						b = s.bitb;
  						k = s.bitk;
  						q = s.write;
  						m = q < s.read ? s.read - q - 1 : s.end - q;

  						if (r != Z_OK$2) {
  							mode = r == Z_STREAM_END$2 ? WASH : BADCODE;
  							break;
  						}
  					}
  					need = lbits;
  					tree = ltree;
  					tree_index = ltree_index;

  					mode = LEN$1;
  				/* falls through */
  				case LEN$1: // i: get length/literal/eob next
  					j = need;

  					while (k < (j)) {
  						if (n !== 0)
  							r = Z_OK$2;
  						else {

  							s.bitb = b;
  							s.bitk = k;
  							z.avail_in = n;
  							z.total_in += p - z.next_in_index;
  							z.next_in_index = p;
  							s.write = q;
  							return s.inflate_flush(z, r);
  						}
  						n--;
  						b |= (z.read_byte(p++) & 0xff) << k;
  						k += 8;
  					}

  					tindex = (tree_index + (b & inflate_mask[j])) * 3;

  					b >>>= (tree[tindex + 1]);
  					k -= (tree[tindex + 1]);

  					e = tree[tindex];

  					if (e === 0) { // literal
  						lit = tree[tindex + 2];
  						mode = LIT$1;
  						break;
  					}
  					if ((e & 16) !== 0) { // length
  						get = e & 15;
  						len = tree[tindex + 2];
  						mode = LENEXT$1;
  						break;
  					}
  					if ((e & 64) === 0) { // next table
  						need = e;
  						tree_index = tindex / 3 + tree[tindex + 2];
  						break;
  					}
  					if ((e & 32) !== 0) { // end of block
  						mode = WASH;
  						break;
  					}
  					mode = BADCODE; // invalid code
  					z.msg = "invalid literal/length code";
  					r = Z_DATA_ERROR$2;

  					s.bitb = b;
  					s.bitk = k;
  					z.avail_in = n;
  					z.total_in += p - z.next_in_index;
  					z.next_in_index = p;
  					s.write = q;
  					return s.inflate_flush(z, r);

  				case LENEXT$1: // i: getting length extra (have base)
  					j = get;

  					while (k < (j)) {
  						if (n !== 0)
  							r = Z_OK$2;
  						else {

  							s.bitb = b;
  							s.bitk = k;
  							z.avail_in = n;
  							z.total_in += p - z.next_in_index;
  							z.next_in_index = p;
  							s.write = q;
  							return s.inflate_flush(z, r);
  						}
  						n--;
  						b |= (z.read_byte(p++) & 0xff) << k;
  						k += 8;
  					}

  					len += (b & inflate_mask[j]);

  					b >>= j;
  					k -= j;

  					need = dbits;
  					tree = dtree;
  					tree_index = dtree_index;
  					mode = DIST$1;
  				/* falls through */
  				case DIST$1: // i: get distance next
  					j = need;

  					while (k < (j)) {
  						if (n !== 0)
  							r = Z_OK$2;
  						else {

  							s.bitb = b;
  							s.bitk = k;
  							z.avail_in = n;
  							z.total_in += p - z.next_in_index;
  							z.next_in_index = p;
  							s.write = q;
  							return s.inflate_flush(z, r);
  						}
  						n--;
  						b |= (z.read_byte(p++) & 0xff) << k;
  						k += 8;
  					}

  					tindex = (tree_index + (b & inflate_mask[j])) * 3;

  					b >>= tree[tindex + 1];
  					k -= tree[tindex + 1];

  					e = (tree[tindex]);
  					if ((e & 16) !== 0) { // distance
  						get = e & 15;
  						dist = tree[tindex + 2];
  						mode = DISTEXT$1;
  						break;
  					}
  					if ((e & 64) === 0) { // next table
  						need = e;
  						tree_index = tindex / 3 + tree[tindex + 2];
  						break;
  					}
  					mode = BADCODE; // invalid code
  					z.msg = "invalid distance code";
  					r = Z_DATA_ERROR$2;

  					s.bitb = b;
  					s.bitk = k;
  					z.avail_in = n;
  					z.total_in += p - z.next_in_index;
  					z.next_in_index = p;
  					s.write = q;
  					return s.inflate_flush(z, r);

  				case DISTEXT$1: // i: getting distance extra
  					j = get;

  					while (k < (j)) {
  						if (n !== 0)
  							r = Z_OK$2;
  						else {

  							s.bitb = b;
  							s.bitk = k;
  							z.avail_in = n;
  							z.total_in += p - z.next_in_index;
  							z.next_in_index = p;
  							s.write = q;
  							return s.inflate_flush(z, r);
  						}
  						n--;
  						b |= (z.read_byte(p++) & 0xff) << k;
  						k += 8;
  					}

  					dist += (b & inflate_mask[j]);

  					b >>= j;
  					k -= j;

  					mode = COPY$1;
  				/* falls through */
  				case COPY$1: // o: copying bytes in win, waiting for space
  					f = q - dist;
  					while (f < 0) { // modulo win size-"while" instead
  						f += s.end; // of "if" handles invalid distances
  					}
  					while (len !== 0) {

  						if (m === 0) {
  							if (q == s.end && s.read !== 0) {
  								q = 0;
  								m = q < s.read ? s.read - q - 1 : s.end - q;
  							}
  							if (m === 0) {
  								s.write = q;
  								r = s.inflate_flush(z, r);
  								q = s.write;
  								m = q < s.read ? s.read - q - 1 : s.end - q;

  								if (q == s.end && s.read !== 0) {
  									q = 0;
  									m = q < s.read ? s.read - q - 1 : s.end - q;
  								}

  								if (m === 0) {
  									s.bitb = b;
  									s.bitk = k;
  									z.avail_in = n;
  									z.total_in += p - z.next_in_index;
  									z.next_in_index = p;
  									s.write = q;
  									return s.inflate_flush(z, r);
  								}
  							}
  						}

  						s.win[q++] = s.win[f++];
  						m--;

  						if (f == s.end)
  							f = 0;
  						len--;
  					}
  					mode = START;
  					break;
  				case LIT$1: // o: got literal, waiting for output space
  					if (m === 0) {
  						if (q == s.end && s.read !== 0) {
  							q = 0;
  							m = q < s.read ? s.read - q - 1 : s.end - q;
  						}
  						if (m === 0) {
  							s.write = q;
  							r = s.inflate_flush(z, r);
  							q = s.write;
  							m = q < s.read ? s.read - q - 1 : s.end - q;

  							if (q == s.end && s.read !== 0) {
  								q = 0;
  								m = q < s.read ? s.read - q - 1 : s.end - q;
  							}
  							if (m === 0) {
  								s.bitb = b;
  								s.bitk = k;
  								z.avail_in = n;
  								z.total_in += p - z.next_in_index;
  								z.next_in_index = p;
  								s.write = q;
  								return s.inflate_flush(z, r);
  							}
  						}
  					}
  					r = Z_OK$2;

  					s.win[q++] = /* (byte) */lit;
  					m--;

  					mode = START;
  					break;
  				case WASH: // o: got eob, possibly more output
  					if (k > 7) { // return unused byte, if any
  						k -= 8;
  						n++;
  						p--; // can always return one
  					}

  					s.write = q;
  					r = s.inflate_flush(z, r);
  					q = s.write;
  					m = q < s.read ? s.read - q - 1 : s.end - q;

  					if (s.read != s.write) {
  						s.bitb = b;
  						s.bitk = k;
  						z.avail_in = n;
  						z.total_in += p - z.next_in_index;
  						z.next_in_index = p;
  						s.write = q;
  						return s.inflate_flush(z, r);
  					}
  					mode = END;
  				/* falls through */
  				case END:
  					r = Z_STREAM_END$2;
  					s.bitb = b;
  					s.bitk = k;
  					z.avail_in = n;
  					z.total_in += p - z.next_in_index;
  					z.next_in_index = p;
  					s.write = q;
  					return s.inflate_flush(z, r);

  				case BADCODE: // x: got error

  					r = Z_DATA_ERROR$2;

  					s.bitb = b;
  					s.bitk = k;
  					z.avail_in = n;
  					z.total_in += p - z.next_in_index;
  					z.next_in_index = p;
  					s.write = q;
  					return s.inflate_flush(z, r);

  				default:
  					r = Z_STREAM_ERROR$2;

  					s.bitb = b;
  					s.bitk = k;
  					z.avail_in = n;
  					z.total_in += p - z.next_in_index;
  					z.next_in_index = p;
  					s.write = q;
  					return s.inflate_flush(z, r);
  			}
  		}
  	};

  	that.free = function () {
  		// ZFREE(z, c);
  	};

  }

  // InfBlocks

  // Table for deflate from PKZIP's appnote.txt.
  const border = [ // Order of the bit length code lengths
  	16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];

  const TYPE$2 = 0; // get type bits (3, including end bit)
  const LENS$2 = 1; // get lengths for stored
  const STORED$2 = 2;// processing stored block
  const TABLE$1 = 3; // get table lengths
  const BTREE = 4; // get bit lengths tree for a dynamic
  // block
  const DTREE = 5; // get length, distance trees for a
  // dynamic block
  const CODES$2 = 6; // processing fixed or dynamic block
  const DRY = 7; // output remaining win bytes
  const DONELOCKS = 8; // finished last block, done
  const BADBLOCKS = 9; // ot a data error--stuck here

  function InfBlocks(z, w) {
  	const that = this;

  	let mode = TYPE$2; // current inflate_block mode

  	let left = 0; // if STORED, bytes left to copy

  	let table = 0; // table lengths (14 bits)
  	let index = 0; // index into blens (or border)
  	let blens; // bit lengths of codes
  	const bb = [0]; // bit length tree depth
  	const tb = [0]; // bit length decoding tree

  	const codes = new InfCodes(); // if CODES, current state

  	let last = 0; // true if this block is the last block

  	let hufts = new Int32Array(MANY * 3); // single malloc for tree space
  	const check = 0; // check on output
  	const inftree = new InfTree();

  	that.bitk = 0; // bits in bit buffer
  	that.bitb = 0; // bit buffer
  	that.win = new Uint8Array(w); // sliding win
  	that.end = w; // one byte after sliding win
  	that.read = 0; // win read pointer
  	that.write = 0; // win write pointer

  	that.reset = function (z, c) {
  		if (c)
  			c[0] = check;
  		// if (mode == BTREE || mode == DTREE) {
  		// }
  		if (mode == CODES$2) {
  			codes.free(z);
  		}
  		mode = TYPE$2;
  		that.bitk = 0;
  		that.bitb = 0;
  		that.read = that.write = 0;
  	};

  	that.reset(z, null);

  	// copy as much as possible from the sliding win to the output area
  	that.inflate_flush = function (z, r) {
  		let n;
  		let p;
  		let q;

  		// local copies of source and destination pointers
  		p = z.next_out_index;
  		q = that.read;

  		// compute number of bytes to copy as far as end of win
  		n = /* (int) */((q <= that.write ? that.write : that.end) - q);
  		if (n > z.avail_out)
  			n = z.avail_out;
  		if (n !== 0 && r == Z_BUF_ERROR$2)
  			r = Z_OK$2;

  		// update counters
  		z.avail_out -= n;
  		z.total_out += n;

  		// copy as far as end of win
  		z.next_out.set(that.win.subarray(q, q + n), p);
  		p += n;
  		q += n;

  		// see if more to copy at beginning of win
  		if (q == that.end) {
  			// wrap pointers
  			q = 0;
  			if (that.write == that.end)
  				that.write = 0;

  			// compute bytes to copy
  			n = that.write - q;
  			if (n > z.avail_out)
  				n = z.avail_out;
  			if (n !== 0 && r == Z_BUF_ERROR$2)
  				r = Z_OK$2;

  			// update counters
  			z.avail_out -= n;
  			z.total_out += n;

  			// copy
  			z.next_out.set(that.win.subarray(q, q + n), p);
  			p += n;
  			q += n;
  		}

  		// update pointers
  		z.next_out_index = p;
  		that.read = q;

  		// done
  		return r;
  	};

  	that.proc = function (z, r) {
  		let t; // temporary storage
  		let b; // bit buffer
  		let k; // bits in bit buffer
  		let p; // input data pointer
  		let n; // bytes available there
  		let q; // output win write pointer
  		let m; // bytes to end of win or read pointer

  		let i;

  		// copy input/output information to locals (UPDATE macro restores)
  		// {
  		p = z.next_in_index;
  		n = z.avail_in;
  		b = that.bitb;
  		k = that.bitk;
  		// }
  		// {
  		q = that.write;
  		m = /* (int) */(q < that.read ? that.read - q - 1 : that.end - q);
  		// }

  		// process input based on current state
  		// DEBUG dtree
  		// eslint-disable-next-line no-constant-condition
  		while (true) {
  			let bl, bd, tl, td, bl_, bd_, tl_, td_;
  			switch (mode) {
  				case TYPE$2:

  					while (k < (3)) {
  						if (n !== 0) {
  							r = Z_OK$2;
  						} else {
  							that.bitb = b;
  							that.bitk = k;
  							z.avail_in = n;
  							z.total_in += p - z.next_in_index;
  							z.next_in_index = p;
  							that.write = q;
  							return that.inflate_flush(z, r);
  						}
  						n--;
  						b |= (z.read_byte(p++) & 0xff) << k;
  						k += 8;
  					}
  					t = /* (int) */(b & 7);
  					last = t & 1;

  					switch (t >>> 1) {
  						case 0: // stored
  							// {
  							b >>>= (3);
  							k -= (3);
  							// }
  							t = k & 7; // go to byte boundary

  							// {
  							b >>>= (t);
  							k -= (t);
  							// }
  							mode = LENS$2; // get length of stored block
  							break;
  						case 1: // fixed
  							// {
  							bl = []; // new Array(1);
  							bd = []; // new Array(1);
  							tl = [[]]; // new Array(1);
  							td = [[]]; // new Array(1);

  							InfTree.inflate_trees_fixed(bl, bd, tl, td);
  							codes.init(bl[0], bd[0], tl[0], 0, td[0], 0);
  							// }

  							// {
  							b >>>= (3);
  							k -= (3);
  							// }

  							mode = CODES$2;
  							break;
  						case 2: // dynamic

  							// {
  							b >>>= (3);
  							k -= (3);
  							// }

  							mode = TABLE$1;
  							break;
  						case 3: // illegal

  							// {
  							b >>>= (3);
  							k -= (3);
  							// }
  							mode = BADBLOCKS;
  							z.msg = "invalid block type";
  							r = Z_DATA_ERROR$2;

  							that.bitb = b;
  							that.bitk = k;
  							z.avail_in = n;
  							z.total_in += p - z.next_in_index;
  							z.next_in_index = p;
  							that.write = q;
  							return that.inflate_flush(z, r);
  					}
  					break;
  				case LENS$2:

  					while (k < (32)) {
  						if (n !== 0) {
  							r = Z_OK$2;
  						} else {
  							that.bitb = b;
  							that.bitk = k;
  							z.avail_in = n;
  							z.total_in += p - z.next_in_index;
  							z.next_in_index = p;
  							that.write = q;
  							return that.inflate_flush(z, r);
  						}
  						n--;
  						b |= (z.read_byte(p++) & 0xff) << k;
  						k += 8;
  					}

  					if ((((~b) >>> 16) & 0xffff) != (b & 0xffff)) {
  						mode = BADBLOCKS;
  						z.msg = "invalid stored block lengths";
  						r = Z_DATA_ERROR$2;

  						that.bitb = b;
  						that.bitk = k;
  						z.avail_in = n;
  						z.total_in += p - z.next_in_index;
  						z.next_in_index = p;
  						that.write = q;
  						return that.inflate_flush(z, r);
  					}
  					left = (b & 0xffff);
  					b = k = 0; // dump bits
  					mode = left !== 0 ? STORED$2 : (last !== 0 ? DRY : TYPE$2);
  					break;
  				case STORED$2:
  					if (n === 0) {
  						that.bitb = b;
  						that.bitk = k;
  						z.avail_in = n;
  						z.total_in += p - z.next_in_index;
  						z.next_in_index = p;
  						that.write = q;
  						return that.inflate_flush(z, r);
  					}

  					if (m === 0) {
  						if (q == that.end && that.read !== 0) {
  							q = 0;
  							m = /* (int) */(q < that.read ? that.read - q - 1 : that.end - q);
  						}
  						if (m === 0) {
  							that.write = q;
  							r = that.inflate_flush(z, r);
  							q = that.write;
  							m = /* (int) */(q < that.read ? that.read - q - 1 : that.end - q);
  							if (q == that.end && that.read !== 0) {
  								q = 0;
  								m = /* (int) */(q < that.read ? that.read - q - 1 : that.end - q);
  							}
  							if (m === 0) {
  								that.bitb = b;
  								that.bitk = k;
  								z.avail_in = n;
  								z.total_in += p - z.next_in_index;
  								z.next_in_index = p;
  								that.write = q;
  								return that.inflate_flush(z, r);
  							}
  						}
  					}
  					r = Z_OK$2;

  					t = left;
  					if (t > n)
  						t = n;
  					if (t > m)
  						t = m;
  					that.win.set(z.read_buf(p, t), q);
  					p += t;
  					n -= t;
  					q += t;
  					m -= t;
  					if ((left -= t) !== 0)
  						break;
  					mode = last !== 0 ? DRY : TYPE$2;
  					break;
  				case TABLE$1:

  					while (k < (14)) {
  						if (n !== 0) {
  							r = Z_OK$2;
  						} else {
  							that.bitb = b;
  							that.bitk = k;
  							z.avail_in = n;
  							z.total_in += p - z.next_in_index;
  							z.next_in_index = p;
  							that.write = q;
  							return that.inflate_flush(z, r);
  						}

  						n--;
  						b |= (z.read_byte(p++) & 0xff) << k;
  						k += 8;
  					}

  					table = t = (b & 0x3fff);
  					if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29) {
  						mode = BADBLOCKS;
  						z.msg = "too many length or distance symbols";
  						r = Z_DATA_ERROR$2;

  						that.bitb = b;
  						that.bitk = k;
  						z.avail_in = n;
  						z.total_in += p - z.next_in_index;
  						z.next_in_index = p;
  						that.write = q;
  						return that.inflate_flush(z, r);
  					}
  					t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f);
  					if (!blens || blens.length < t) {
  						blens = []; // new Array(t);
  					} else {
  						for (i = 0; i < t; i++) {
  							blens[i] = 0;
  						}
  					}

  					// {
  					b >>>= (14);
  					k -= (14);
  					// }

  					index = 0;
  					mode = BTREE;
  				/* falls through */
  				case BTREE:
  					while (index < 4 + (table >>> 10)) {
  						while (k < (3)) {
  							if (n !== 0) {
  								r = Z_OK$2;
  							} else {
  								that.bitb = b;
  								that.bitk = k;
  								z.avail_in = n;
  								z.total_in += p - z.next_in_index;
  								z.next_in_index = p;
  								that.write = q;
  								return that.inflate_flush(z, r);
  							}
  							n--;
  							b |= (z.read_byte(p++) & 0xff) << k;
  							k += 8;
  						}

  						blens[border[index++]] = b & 7;

  						// {
  						b >>>= (3);
  						k -= (3);
  						// }
  					}

  					while (index < 19) {
  						blens[border[index++]] = 0;
  					}

  					bb[0] = 7;
  					t = inftree.inflate_trees_bits(blens, bb, tb, hufts, z);
  					if (t != Z_OK$2) {
  						r = t;
  						if (r == Z_DATA_ERROR$2) {
  							blens = null;
  							mode = BADBLOCKS;
  						}

  						that.bitb = b;
  						that.bitk = k;
  						z.avail_in = n;
  						z.total_in += p - z.next_in_index;
  						z.next_in_index = p;
  						that.write = q;
  						return that.inflate_flush(z, r);
  					}

  					index = 0;
  					mode = DTREE;
  				/* falls through */
  				case DTREE:
  					// eslint-disable-next-line no-constant-condition
  					while (true) {
  						t = table;
  						if (index >= 258 + (t & 0x1f) + ((t >> 5) & 0x1f)) {
  							break;
  						}

  						let j, c;

  						t = bb[0];

  						while (k < (t)) {
  							if (n !== 0) {
  								r = Z_OK$2;
  							} else {
  								that.bitb = b;
  								that.bitk = k;
  								z.avail_in = n;
  								z.total_in += p - z.next_in_index;
  								z.next_in_index = p;
  								that.write = q;
  								return that.inflate_flush(z, r);
  							}
  							n--;
  							b |= (z.read_byte(p++) & 0xff) << k;
  							k += 8;
  						}

  						// if (tb[0] == -1) {
  						// System.err.println("null...");
  						// }

  						t = hufts[(tb[0] + (b & inflate_mask[t])) * 3 + 1];
  						c = hufts[(tb[0] + (b & inflate_mask[t])) * 3 + 2];

  						if (c < 16) {
  							b >>>= (t);
  							k -= (t);
  							blens[index++] = c;
  						} else { // c == 16..18
  							i = c == 18 ? 7 : c - 14;
  							j = c == 18 ? 11 : 3;

  							while (k < (t + i)) {
  								if (n !== 0) {
  									r = Z_OK$2;
  								} else {
  									that.bitb = b;
  									that.bitk = k;
  									z.avail_in = n;
  									z.total_in += p - z.next_in_index;
  									z.next_in_index = p;
  									that.write = q;
  									return that.inflate_flush(z, r);
  								}
  								n--;
  								b |= (z.read_byte(p++) & 0xff) << k;
  								k += 8;
  							}

  							b >>>= (t);
  							k -= (t);

  							j += (b & inflate_mask[i]);

  							b >>>= (i);
  							k -= (i);

  							i = index;
  							t = table;
  							if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) || (c == 16 && i < 1)) {
  								blens = null;
  								mode = BADBLOCKS;
  								z.msg = "invalid bit length repeat";
  								r = Z_DATA_ERROR$2;

  								that.bitb = b;
  								that.bitk = k;
  								z.avail_in = n;
  								z.total_in += p - z.next_in_index;
  								z.next_in_index = p;
  								that.write = q;
  								return that.inflate_flush(z, r);
  							}

  							c = c == 16 ? blens[i - 1] : 0;
  							do {
  								blens[i++] = c;
  							} while (--j !== 0);
  							index = i;
  						}
  					}

  					tb[0] = -1;
  					// {
  					bl_ = []; // new Array(1);
  					bd_ = []; // new Array(1);
  					tl_ = []; // new Array(1);
  					td_ = []; // new Array(1);
  					bl_[0] = 9; // must be <= 9 for lookahead assumptions
  					bd_[0] = 6; // must be <= 9 for lookahead assumptions

  					t = table;
  					t = inftree.inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f), blens, bl_, bd_, tl_, td_, hufts, z);

  					if (t != Z_OK$2) {
  						if (t == Z_DATA_ERROR$2) {
  							blens = null;
  							mode = BADBLOCKS;
  						}
  						r = t;

  						that.bitb = b;
  						that.bitk = k;
  						z.avail_in = n;
  						z.total_in += p - z.next_in_index;
  						z.next_in_index = p;
  						that.write = q;
  						return that.inflate_flush(z, r);
  					}
  					codes.init(bl_[0], bd_[0], hufts, tl_[0], hufts, td_[0]);
  					// }
  					mode = CODES$2;
  				/* falls through */
  				case CODES$2:
  					that.bitb = b;
  					that.bitk = k;
  					z.avail_in = n;
  					z.total_in += p - z.next_in_index;
  					z.next_in_index = p;
  					that.write = q;

  					if ((r = codes.proc(that, z, r)) != Z_STREAM_END$2) {
  						return that.inflate_flush(z, r);
  					}
  					r = Z_OK$2;
  					codes.free(z);

  					p = z.next_in_index;
  					n = z.avail_in;
  					b = that.bitb;
  					k = that.bitk;
  					q = that.write;
  					m = /* (int) */(q < that.read ? that.read - q - 1 : that.end - q);

  					if (last === 0) {
  						mode = TYPE$2;
  						break;
  					}
  					mode = DRY;
  				/* falls through */
  				case DRY:
  					that.write = q;
  					r = that.inflate_flush(z, r);
  					q = that.write;
  					m = /* (int) */(q < that.read ? that.read - q - 1 : that.end - q);
  					if (that.read != that.write) {
  						that.bitb = b;
  						that.bitk = k;
  						z.avail_in = n;
  						z.total_in += p - z.next_in_index;
  						z.next_in_index = p;
  						that.write = q;
  						return that.inflate_flush(z, r);
  					}
  					mode = DONELOCKS;
  				/* falls through */
  				case DONELOCKS:
  					r = Z_STREAM_END$2;

  					that.bitb = b;
  					that.bitk = k;
  					z.avail_in = n;
  					z.total_in += p - z.next_in_index;
  					z.next_in_index = p;
  					that.write = q;
  					return that.inflate_flush(z, r);
  				case BADBLOCKS:
  					r = Z_DATA_ERROR$2;

  					that.bitb = b;
  					that.bitk = k;
  					z.avail_in = n;
  					z.total_in += p - z.next_in_index;
  					z.next_in_index = p;
  					that.write = q;
  					return that.inflate_flush(z, r);

  				default:
  					r = Z_STREAM_ERROR$2;

  					that.bitb = b;
  					that.bitk = k;
  					z.avail_in = n;
  					z.total_in += p - z.next_in_index;
  					z.next_in_index = p;
  					that.write = q;
  					return that.inflate_flush(z, r);
  			}
  		}
  	};

  	that.free = function (z) {
  		that.reset(z, null);
  		that.win = null;
  		hufts = null;
  		// ZFREE(z, s);
  	};

  	that.set_dictionary = function (d, start, n) {
  		that.win.set(d.subarray(start, start + n), 0);
  		that.read = that.write = n;
  	};

  	// Returns true if inflate is currently at the end of a block generated
  	// by Z_SYNC_FLUSH or Z_FULL_FLUSH.
  	that.sync_point = function () {
  		return mode == LENS$2 ? 1 : 0;
  	};

  }

  // Inflate

  // preset dictionary flag in zlib header
  const PRESET_DICT = 0x20;

  const Z_DEFLATED$2 = 8;

  const METHOD = 0; // waiting for method byte
  const FLAG = 1; // waiting for flag byte
  const DICT4 = 2; // four dictionary check bytes to go
  const DICT3 = 3; // three dictionary check bytes to go
  const DICT2 = 4; // two dictionary check bytes to go
  const DICT1 = 5; // one dictionary check byte to go
  const DICT0 = 6; // waiting for inflateSetDictionary
  const BLOCKS = 7; // decompressing blocks
  const DONE$1 = 12; // finished check, done
  const BAD$2 = 13; // got an error--stay here

  const mark = [0, 0, 0xff, 0xff];

  function Inflate$1() {
  	const that = this;

  	that.mode = 0; // current inflate mode

  	// mode dependent information
  	that.method = 0; // if FLAGS, method byte

  	// if CHECK, check values to compare
  	that.was = [0]; // new Array(1); // computed check value
  	that.need = 0; // stream check value

  	// if BAD, inflateSync's marker bytes count
  	that.marker = 0;

  	// mode independent information
  	that.wbits = 0; // log2(win size) (8..15, defaults to 15)

  	// this.blocks; // current inflate_blocks state

  	function inflateReset(z) {
  		if (!z || !z.istate)
  			return Z_STREAM_ERROR$2;

  		z.total_in = z.total_out = 0;
  		z.msg = null;
  		z.istate.mode = BLOCKS;
  		z.istate.blocks.reset(z, null);
  		return Z_OK$2;
  	}

  	that.inflateEnd = function (z) {
  		if (that.blocks)
  			that.blocks.free(z);
  		that.blocks = null;
  		// ZFREE(z, z->state);
  		return Z_OK$2;
  	};

  	that.inflateInit = function (z, w) {
  		z.msg = null;
  		that.blocks = null;

  		// set win size
  		if (w < 8 || w > 15) {
  			that.inflateEnd(z);
  			return Z_STREAM_ERROR$2;
  		}
  		that.wbits = w;

  		z.istate.blocks = new InfBlocks(z, 1 << w);

  		// reset state
  		inflateReset(z);
  		return Z_OK$2;
  	};

  	that.inflate = function (z, f) {
  		let r;
  		let b;

  		if (!z || !z.istate || !z.next_in)
  			return Z_STREAM_ERROR$2;
  		const istate = z.istate;
  		f = f == Z_FINISH$2 ? Z_BUF_ERROR$2 : Z_OK$2;
  		r = Z_BUF_ERROR$2;
  		// eslint-disable-next-line no-constant-condition
  		while (true) {
  			switch (istate.mode) {
  				case METHOD:

  					if (z.avail_in === 0)
  						return r;
  					r = f;

  					z.avail_in--;
  					z.total_in++;
  					if (((istate.method = z.read_byte(z.next_in_index++)) & 0xf) != Z_DEFLATED$2) {
  						istate.mode = BAD$2;
  						z.msg = "unknown compression method";
  						istate.marker = 5; // can't try inflateSync
  						break;
  					}
  					if ((istate.method >> 4) + 8 > istate.wbits) {
  						istate.mode = BAD$2;
  						z.msg = "invalid win size";
  						istate.marker = 5; // can't try inflateSync
  						break;
  					}
  					istate.mode = FLAG;
  				/* falls through */
  				case FLAG:

  					if (z.avail_in === 0)
  						return r;
  					r = f;

  					z.avail_in--;
  					z.total_in++;
  					b = (z.read_byte(z.next_in_index++)) & 0xff;

  					if ((((istate.method << 8) + b) % 31) !== 0) {
  						istate.mode = BAD$2;
  						z.msg = "incorrect header check";
  						istate.marker = 5; // can't try inflateSync
  						break;
  					}

  					if ((b & PRESET_DICT) === 0) {
  						istate.mode = BLOCKS;
  						break;
  					}
  					istate.mode = DICT4;
  				/* falls through */
  				case DICT4:

  					if (z.avail_in === 0)
  						return r;
  					r = f;

  					z.avail_in--;
  					z.total_in++;
  					istate.need = ((z.read_byte(z.next_in_index++) & 0xff) << 24) & 0xff000000;
  					istate.mode = DICT3;
  				/* falls through */
  				case DICT3:

  					if (z.avail_in === 0)
  						return r;
  					r = f;

  					z.avail_in--;
  					z.total_in++;
  					istate.need += ((z.read_byte(z.next_in_index++) & 0xff) << 16) & 0xff0000;
  					istate.mode = DICT2;
  				/* falls through */
  				case DICT2:

  					if (z.avail_in === 0)
  						return r;
  					r = f;

  					z.avail_in--;
  					z.total_in++;
  					istate.need += ((z.read_byte(z.next_in_index++) & 0xff) << 8) & 0xff00;
  					istate.mode = DICT1;
  				/* falls through */
  				case DICT1:

  					if (z.avail_in === 0)
  						return r;
  					r = f;

  					z.avail_in--;
  					z.total_in++;
  					istate.need += (z.read_byte(z.next_in_index++) & 0xff);
  					istate.mode = DICT0;
  					return Z_NEED_DICT$2;
  				case DICT0:
  					istate.mode = BAD$2;
  					z.msg = "need dictionary";
  					istate.marker = 0; // can try inflateSync
  					return Z_STREAM_ERROR$2;
  				case BLOCKS:

  					r = istate.blocks.proc(z, r);
  					if (r == Z_DATA_ERROR$2) {
  						istate.mode = BAD$2;
  						istate.marker = 0; // can try inflateSync
  						break;
  					}
  					if (r == Z_OK$2) {
  						r = f;
  					}
  					if (r != Z_STREAM_END$2) {
  						return r;
  					}
  					r = f;
  					istate.blocks.reset(z, istate.was);
  					istate.mode = DONE$1;
  				/* falls through */
  				case DONE$1:
  					z.avail_in = 0;
  					return Z_STREAM_END$2;
  				case BAD$2:
  					return Z_DATA_ERROR$2;
  				default:
  					return Z_STREAM_ERROR$2;
  			}
  		}
  	};

  	that.inflateSetDictionary = function (z, dictionary, dictLength) {
  		let index = 0, length = dictLength;
  		if (!z || !z.istate || z.istate.mode != DICT0)
  			return Z_STREAM_ERROR$2;
  		const istate = z.istate;
  		if (length >= (1 << istate.wbits)) {
  			length = (1 << istate.wbits) - 1;
  			index = dictLength - length;
  		}
  		istate.blocks.set_dictionary(dictionary, index, length);
  		istate.mode = BLOCKS;
  		return Z_OK$2;
  	};

  	that.inflateSync = function (z) {
  		let n; // number of bytes to look at
  		let p; // pointer to bytes
  		let m; // number of marker bytes found in a row
  		let r, w; // temporaries to save total_in and total_out

  		// set up
  		if (!z || !z.istate)
  			return Z_STREAM_ERROR$2;
  		const istate = z.istate;
  		if (istate.mode != BAD$2) {
  			istate.mode = BAD$2;
  			istate.marker = 0;
  		}
  		if ((n = z.avail_in) === 0)
  			return Z_BUF_ERROR$2;
  		p = z.next_in_index;
  		m = istate.marker;

  		// search
  		while (n !== 0 && m < 4) {
  			if (z.read_byte(p) == mark[m]) {
  				m++;
  			} else if (z.read_byte(p) !== 0) {
  				m = 0;
  			} else {
  				m = 4 - m;
  			}
  			p++;
  			n--;
  		}

  		// restore
  		z.total_in += p - z.next_in_index;
  		z.next_in_index = p;
  		z.avail_in = n;
  		istate.marker = m;

  		// return no joy or set up to restart on a new block
  		if (m != 4) {
  			return Z_DATA_ERROR$2;
  		}
  		r = z.total_in;
  		w = z.total_out;
  		inflateReset(z);
  		z.total_in = r;
  		z.total_out = w;
  		istate.mode = BLOCKS;
  		return Z_OK$2;
  	};

  	// Returns true if inflate is currently at the end of a block generated
  	// by Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  	// implementation to provide an additional safety check. PPP uses
  	// Z_SYNC_FLUSH
  	// but removes the length bytes of the resulting empty stored block. When
  	// decompressing, PPP checks that at the end of input packet, inflate is
  	// waiting for these length bytes.
  	that.inflateSyncPoint = function (z) {
  		if (!z || !z.istate || !z.istate.blocks)
  			return Z_STREAM_ERROR$2;
  		return z.istate.blocks.sync_point();
  	};
  }

  // ZStream

  function ZStream$2() {
  }

  ZStream$2.prototype = {
  	inflateInit: function (bits) {
  		const that = this;
  		that.istate = new Inflate$1();
  		if (!bits)
  			bits = MAX_BITS;
  		return that.istate.inflateInit(that, bits);
  	},

  	inflate: function (f) {
  		const that = this;
  		if (!that.istate)
  			return Z_STREAM_ERROR$2;
  		return that.istate.inflate(that, f);
  	},

  	inflateEnd: function () {
  		const that = this;
  		if (!that.istate)
  			return Z_STREAM_ERROR$2;
  		const ret = that.istate.inflateEnd(that);
  		that.istate = null;
  		return ret;
  	},

  	inflateSync: function () {
  		const that = this;
  		if (!that.istate)
  			return Z_STREAM_ERROR$2;
  		return that.istate.inflateSync(that);
  	},
  	inflateSetDictionary: function (dictionary, dictLength) {
  		const that = this;
  		if (!that.istate)
  			return Z_STREAM_ERROR$2;
  		return that.istate.inflateSetDictionary(that, dictionary, dictLength);
  	},
  	read_byte: function (start) {
  		const that = this;
  		return that.next_in[start];
  	},
  	read_buf: function (start, size) {
  		const that = this;
  		return that.next_in.subarray(start, start + size);
  	}
  };

  // Inflater

  function ZipInflate(options) {
  	const that = this;
  	const z = new ZStream$2();
  	const bufsize = options && options.chunkSize ? Math.floor(options.chunkSize * 2) : 128 * 1024;
  	const flush = Z_NO_FLUSH;
  	const buf = new Uint8Array(bufsize);
  	let nomoreinput = false;

  	z.inflateInit();
  	z.next_out = buf;

  	that.append = function (data, onprogress) {
  		const buffers = [];
  		let err, array, lastIndex = 0, bufferIndex = 0, bufferSize = 0;
  		if (data.length === 0)
  			return;
  		z.next_in_index = 0;
  		z.next_in = data;
  		z.avail_in = data.length;
  		do {
  			z.next_out_index = 0;
  			z.avail_out = bufsize;
  			if ((z.avail_in === 0) && (!nomoreinput)) { // if buffer is empty and more input is available, refill it
  				z.next_in_index = 0;
  				nomoreinput = true;
  			}
  			err = z.inflate(flush);
  			if (nomoreinput && (err === Z_BUF_ERROR$2)) {
  				if (z.avail_in !== 0)
  					throw new Error("inflating: bad input");
  			} else if (err !== Z_OK$2 && err !== Z_STREAM_END$2)
  				throw new Error("inflating: " + z.msg);
  			if ((nomoreinput || err === Z_STREAM_END$2) && (z.avail_in === data.length))
  				throw new Error("inflating: bad input");
  			if (z.next_out_index)
  				if (z.next_out_index === bufsize)
  					buffers.push(new Uint8Array(buf));
  				else
  					buffers.push(buf.slice(0, z.next_out_index));
  			bufferSize += z.next_out_index;
  			if (onprogress && z.next_in_index > 0 && z.next_in_index != lastIndex) {
  				onprogress(z.next_in_index);
  				lastIndex = z.next_in_index;
  			}
  		} while (z.avail_in > 0 || z.avail_out === 0);
  		if (buffers.length > 1) {
  			array = new Uint8Array(bufferSize);
  			buffers.forEach(function (chunk) {
  				array.set(chunk, bufferIndex);
  				bufferIndex += chunk.length;
  			});
  		} else {
  			array = buffers[0] || new Uint8Array(0);
  		}
  		return array;
  	};
  	that.flush = function () {
  		z.inflateEnd();
  	};
  }

  /*
   Copyright (c) 2022 Gildas Lormeau. All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright 
   notice, this list of conditions and the following disclaimer in 
   the documentation and/or other materials provided with the distribution.

   3. The names of the authors may not be used to endorse or promote products
   derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
   INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
   OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
   EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   */

  /* global navigator */

  const DEFAULT_CONFIGURATION = {
  	chunkSize: 512 * 1024,
  	maxWorkers: (typeof navigator != "undefined" && navigator.hardwareConcurrency) || 2,
  	terminateWorkerTimeout: 5000,
  	useWebWorkers: true,
  	workerScripts: undefined
  };

  const config = Object.assign({}, DEFAULT_CONFIGURATION);

  function getConfiguration() {
  	return config;
  }

  function configure(configuration) {
  	if (configuration.baseURL !== undefined) {
  		config.baseURL = configuration.baseURL;
  	}
  	if (configuration.chunkSize !== undefined) {
  		config.chunkSize = configuration.chunkSize;
  	}
  	if (configuration.maxWorkers !== undefined) {
  		config.maxWorkers = configuration.maxWorkers;
  	}
  	if (configuration.terminateWorkerTimeout !== undefined) {
  		config.terminateWorkerTimeout = configuration.terminateWorkerTimeout;
  	}
  	if (configuration.useWebWorkers !== undefined) {
  		config.useWebWorkers = configuration.useWebWorkers;
  	}
  	if (configuration.Deflate !== undefined) {
  		config.Deflate = configuration.Deflate;
  	}
  	if (configuration.Inflate !== undefined) {
  		config.Inflate = configuration.Inflate;
  	}
  	if (configuration.workerScripts !== undefined) {
  		if (configuration.workerScripts.deflate) {
  			if (!Array.isArray(configuration.workerScripts.deflate)) {
  				throw new Error("workerScripts.deflate must be an array");
  			}
  			if (!config.workerScripts) {
  				config.workerScripts = {};
  			}
  			config.workerScripts.deflate = configuration.workerScripts.deflate;
  		}
  		if (configuration.workerScripts.inflate) {
  			if (!Array.isArray(configuration.workerScripts.inflate)) {
  				throw new Error("workerScripts.inflate must be an array");
  			}
  			if (!config.workerScripts) {
  				config.workerScripts = {};
  			}
  			config.workerScripts.inflate = configuration.workerScripts.inflate;
  		}
  	}
  }

  /*
   Copyright (c) 2022 Gildas Lormeau. All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright 
   notice, this list of conditions and the following disclaimer in 
   the documentation and/or other materials provided with the distribution.

   3. The names of the authors may not be used to endorse or promote products
   derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
   INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
   OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
   EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   */

  function getMimeType() {
  	return "application/octet-stream";
  }

  /*
   Copyright (c) 2022 Gildas Lormeau. All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright 
   notice, this list of conditions and the following disclaimer in 
   the documentation and/or other materials provided with the distribution.

   3. The names of the authors may not be used to endorse or promote products
   derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
   INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
   OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
   EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   */

  const table = [];
  for (let i = 0; i < 256; i++) {
  	let t = i;
  	for (let j = 0; j < 8; j++) {
  		if (t & 1) {
  			t = (t >>> 1) ^ 0xEDB88320;
  		} else {
  			t = t >>> 1;
  		}
  	}
  	table[i] = t;
  }

  class Crc32 {

  	constructor(crc) {
  		this.crc = crc || -1;
  	}

  	append(data) {
  		let crc = this.crc | 0;
  		for (let offset = 0, length = data.length | 0; offset < length; offset++) {
  			crc = (crc >>> 8) ^ table[(crc ^ data[offset]) & 0xFF];
  		}
  		this.crc = crc;
  	}

  	get() {
  		return ~this.crc;
  	}
  }

  /*
   Copyright (c) 2022 Gildas Lormeau. All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright 
   notice, this list of conditions and the following disclaimer in 
   the documentation and/or other materials provided with the distribution.

   3. The names of the authors may not be used to endorse or promote products
   derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
   INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
   OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
   EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   */

  function encodeText(value) {
  	if (typeof TextEncoder == "undefined") {
  		value = unescape(encodeURIComponent(value));
  		const result = new Uint8Array(value.length);
  		for (let i = 0; i < result.length; i++) {
  			result[i] = value.charCodeAt(i);
  		}
  		return result;
  	} else {
  		return new TextEncoder().encode(value);
  	}
  }

  // Derived from https://github.com/xqdoo00o/jszip/blob/master/lib/sjcl.js and https://github.com/bitwiseshiftleft/sjcl

  /*// deno-lint-ignore-file no-this-alias *

  /*
   * SJCL is open. You can use, modify and redistribute it under a BSD
   * license or under the GNU GPL, version 2.0.
   */

  /** @fileOverview Javascript cryptography implementation.
   *
   * Crush to remove comments, shorten variable names and
   * generally reduce transmission size.
   *
   * @author Emily Stark
   * @author Mike Hamburg
   * @author Dan Boneh
   */

  /*jslint indent: 2, bitwise: false, nomen: false, plusplus: false, white: false, regexp: false */

  /** @fileOverview Arrays of bits, encoded as arrays of Numbers.
   *
   * @author Emily Stark
   * @author Mike Hamburg
   * @author Dan Boneh
   */

  /**
   * Arrays of bits, encoded as arrays of Numbers.
   * @namespace
   * @description
   * <p>
   * These objects are the currency accepted by SJCL's crypto functions.
   * </p>
   *
   * <p>
   * Most of our crypto primitives operate on arrays of 4-byte words internally,
   * but many of them can take arguments that are not a multiple of 4 bytes.
   * This library encodes arrays of bits (whose size need not be a multiple of 8
   * bits) as arrays of 32-bit words.  The bits are packed, big-endian, into an
   * array of words, 32 bits at a time.  Since the words are double-precision
   * floating point numbers, they fit some extra data.  We use this (in a private,
   * possibly-changing manner) to encode the number of bits actually  present
   * in the last word of the array.
   * </p>
   *
   * <p>
   * Because bitwise ops clear this out-of-band data, these arrays can be passed
   * to ciphers like AES which want arrays of words.
   * </p>
   */
  const bitArray = {
  	/**
  	 * Concatenate two bit arrays.
  	 * @param {bitArray} a1 The first array.
  	 * @param {bitArray} a2 The second array.
  	 * @return {bitArray} The concatenation of a1 and a2.
  	 */
  	concat(a1, a2) {
  		if (a1.length === 0 || a2.length === 0) {
  			return a1.concat(a2);
  		}

  		const last = a1[a1.length - 1], shift = bitArray.getPartial(last);
  		if (shift === 32) {
  			return a1.concat(a2);
  		} else {
  			return bitArray._shiftRight(a2, shift, last | 0, a1.slice(0, a1.length - 1));
  		}
  	},

  	/**
  	 * Find the length of an array of bits.
  	 * @param {bitArray} a The array.
  	 * @return {Number} The length of a, in bits.
  	 */
  	bitLength(a) {
  		const l = a.length;
  		if (l === 0) {
  			return 0;
  		}
  		const x = a[l - 1];
  		return (l - 1) * 32 + bitArray.getPartial(x);
  	},

  	/**
  	 * Truncate an array.
  	 * @param {bitArray} a The array.
  	 * @param {Number} len The length to truncate to, in bits.
  	 * @return {bitArray} A new array, truncated to len bits.
  	 */
  	clamp(a, len) {
  		if (a.length * 32 < len) {
  			return a;
  		}
  		a = a.slice(0, Math.ceil(len / 32));
  		const l = a.length;
  		len = len & 31;
  		if (l > 0 && len) {
  			a[l - 1] = bitArray.partial(len, a[l - 1] & 0x80000000 >> (len - 1), 1);
  		}
  		return a;
  	},

  	/**
  	 * Make a partial word for a bit array.
  	 * @param {Number} len The number of bits in the word.
  	 * @param {Number} x The bits.
  	 * @param {Number} [_end=0] Pass 1 if x has already been shifted to the high side.
  	 * @return {Number} The partial word.
  	 */
  	partial(len, x, _end) {
  		if (len === 32) {
  			return x;
  		}
  		return (_end ? x | 0 : x << (32 - len)) + len * 0x10000000000;
  	},

  	/**
  	 * Get the number of bits used by a partial word.
  	 * @param {Number} x The partial word.
  	 * @return {Number} The number of bits used by the partial word.
  	 */
  	getPartial(x) {
  		return Math.round(x / 0x10000000000) || 32;
  	},

  	/** Shift an array right.
  	 * @param {bitArray} a The array to shift.
  	 * @param {Number} shift The number of bits to shift.
  	 * @param {Number} [carry=0] A byte to carry in
  	 * @param {bitArray} [out=[]] An array to prepend to the output.
  	 * @private
  	 */
  	_shiftRight(a, shift, carry, out) {
  		if (out === undefined) {
  			out = [];
  		}

  		for (; shift >= 32; shift -= 32) {
  			out.push(carry);
  			carry = 0;
  		}
  		if (shift === 0) {
  			return out.concat(a);
  		}

  		for (let i = 0; i < a.length; i++) {
  			out.push(carry | a[i] >>> shift);
  			carry = a[i] << (32 - shift);
  		}
  		const last2 = a.length ? a[a.length - 1] : 0;
  		const shift2 = bitArray.getPartial(last2);
  		out.push(bitArray.partial(shift + shift2 & 31, (shift + shift2 > 32) ? carry : out.pop(), 1));
  		return out;
  	}
  };

  /** @fileOverview Bit array codec implementations.
   *
   * @author Emily Stark
   * @author Mike Hamburg
   * @author Dan Boneh
   */

  /**
   * Arrays of bytes
   * @namespace
   */
  const codec = {
  	bytes: {
  		/** Convert from a bitArray to an array of bytes. */
  		fromBits(arr) {
  			const bl = bitArray.bitLength(arr);
  			const byteLength = bl / 8;
  			const out = new Uint8Array(byteLength);
  			let tmp;
  			for (let i = 0; i < byteLength; i++) {
  				if ((i & 3) === 0) {
  					tmp = arr[i / 4];
  				}
  				out[i] = tmp >>> 24;
  				tmp <<= 8;
  			}
  			return out;
  		},
  		/** Convert from an array of bytes to a bitArray. */
  		toBits(bytes) {
  			const out = [];
  			let i;
  			let tmp = 0;
  			for (i = 0; i < bytes.length; i++) {
  				tmp = tmp << 8 | bytes[i];
  				if ((i & 3) === 3) {
  					out.push(tmp);
  					tmp = 0;
  				}
  			}
  			if (i & 3) {
  				out.push(bitArray.partial(8 * (i & 3), tmp));
  			}
  			return out;
  		}
  	}
  };

  const hash = {};

  /**
   * Context for a SHA-1 operation in progress.
   * @constructor
   */
  hash.sha1 = function (hash) {
  	if (hash) {
  		this._h = hash._h.slice(0);
  		this._buffer = hash._buffer.slice(0);
  		this._length = hash._length;
  	} else {
  		this.reset();
  	}
  };

  hash.sha1.prototype = {
  	/**
  	 * The hash's block size, in bits.
  	 * @constant
  	 */
  	blockSize: 512,

  	/**
  	 * Reset the hash state.
  	 * @return this
  	 */
  	reset: function () {
  		const sha1 = this;
  		sha1._h = this._init.slice(0);
  		sha1._buffer = [];
  		sha1._length = 0;
  		return sha1;
  	},

  	/**
  	 * Input several words to the hash.
  	 * @param {bitArray|String} data the data to hash.
  	 * @return this
  	 */
  	update: function (data) {
  		const sha1 = this;
  		if (typeof data === "string") {
  			data = codec.utf8String.toBits(data);
  		}
  		const b = sha1._buffer = bitArray.concat(sha1._buffer, data);
  		const ol = sha1._length;
  		const nl = sha1._length = ol + bitArray.bitLength(data);
  		if (nl > 9007199254740991) {
  			throw new Error("Cannot hash more than 2^53 - 1 bits");
  		}
  		const c = new Uint32Array(b);
  		let j = 0;
  		for (let i = sha1.blockSize + ol - ((sha1.blockSize + ol) & (sha1.blockSize - 1)); i <= nl;
  			i += sha1.blockSize) {
  			sha1._block(c.subarray(16 * j, 16 * (j + 1)));
  			j += 1;
  		}
  		b.splice(0, 16 * j);
  		return sha1;
  	},

  	/**
  	 * Complete hashing and output the hash value.
  	 * @return {bitArray} The hash value, an array of 5 big-endian words. TODO
  	 */
  	finalize: function () {
  		const sha1 = this;
  		let b = sha1._buffer;
  		const h = sha1._h;

  		// Round out and push the buffer
  		b = bitArray.concat(b, [bitArray.partial(1, 1)]);
  		// Round out the buffer to a multiple of 16 words, less the 2 length words.
  		for (let i = b.length + 2; i & 15; i++) {
  			b.push(0);
  		}

  		// append the length
  		b.push(Math.floor(sha1._length / 0x100000000));
  		b.push(sha1._length | 0);

  		while (b.length) {
  			sha1._block(b.splice(0, 16));
  		}

  		sha1.reset();
  		return h;
  	},

  	/**
  	 * The SHA-1 initialization vector.
  	 * @private
  	 */
  	_init: [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0],

  	/**
  	 * The SHA-1 hash key.
  	 * @private
  	 */
  	_key: [0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6],

  	/**
  	 * The SHA-1 logical functions f(0), f(1), ..., f(79).
  	 * @private
  	 */
  	_f: function (t, b, c, d) {
  		if (t <= 19) {
  			return (b & c) | (~b & d);
  		} else if (t <= 39) {
  			return b ^ c ^ d;
  		} else if (t <= 59) {
  			return (b & c) | (b & d) | (c & d);
  		} else if (t <= 79) {
  			return b ^ c ^ d;
  		}
  	},

  	/**
  	 * Circular left-shift operator.
  	 * @private
  	 */
  	_S: function (n, x) {
  		return (x << n) | (x >>> 32 - n);
  	},

  	/**
  	 * Perform one cycle of SHA-1.
  	 * @param {Uint32Array|bitArray} words one block of words.
  	 * @private
  	 */
  	_block: function (words) {
  		const sha1 = this;
  		const h = sha1._h;
  		// When words is passed to _block, it has 16 elements. SHA1 _block
  		// function extends words with new elements (at the end there are 80 elements). 
  		// The problem is that if we use Uint32Array instead of Array, 
  		// the length of Uint32Array cannot be changed. Thus, we replace words with a 
  		// normal Array here.
  		const w = Array(80); // do not use Uint32Array here as the instantiation is slower
  		for (let j = 0; j < 16; j++) {
  			w[j] = words[j];
  		}

  		let a = h[0];
  		let b = h[1];
  		let c = h[2];
  		let d = h[3];
  		let e = h[4];

  		for (let t = 0; t <= 79; t++) {
  			if (t >= 16) {
  				w[t] = sha1._S(1, w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16]);
  			}
  			const tmp = (sha1._S(5, a) + sha1._f(t, b, c, d) + e + w[t] +
  				sha1._key[Math.floor(t / 20)]) | 0;
  			e = d;
  			d = c;
  			c = sha1._S(30, b);
  			b = a;
  			a = tmp;
  		}

  		h[0] = (h[0] + a) | 0;
  		h[1] = (h[1] + b) | 0;
  		h[2] = (h[2] + c) | 0;
  		h[3] = (h[3] + d) | 0;
  		h[4] = (h[4] + e) | 0;
  	}
  };

  /** @fileOverview Low-level AES implementation.
   *
   * This file contains a low-level implementation of AES, optimized for
   * size and for efficiency on several browsers.  It is based on
   * OpenSSL's aes_core.c, a public-domain implementation by Vincent
   * Rijmen, Antoon Bosselaers and Paulo Barreto.
   *
   * An older version of this implementation is available in the public
   * domain, but this one is (c) Emily Stark, Mike Hamburg, Dan Boneh,
   * Stanford University 2008-2010 and BSD-licensed for liability
   * reasons.
   *
   * @author Emily Stark
   * @author Mike Hamburg
   * @author Dan Boneh
   */

  const cipher = {};

  /**
   * Schedule out an AES key for both encryption and decryption.  This
   * is a low-level class.  Use a cipher mode to do bulk encryption.
   *
   * @constructor
   * @param {Array} key The key as an array of 4, 6 or 8 words.
   */
  cipher.aes = class {
  	constructor(key) {
  		/**
  		 * The expanded S-box and inverse S-box tables.  These will be computed
  		 * on the client so that we don't have to send them down the wire.
  		 *
  		 * There are two tables, _tables[0] is for encryption and
  		 * _tables[1] is for decryption.
  		 *
  		 * The first 4 sub-tables are the expanded S-box with MixColumns.  The
  		 * last (_tables[01][4]) is the S-box itself.
  		 *
  		 * @private
  		 */
  		const aes = this;
  		aes._tables = [[[], [], [], [], []], [[], [], [], [], []]];

  		if (!aes._tables[0][0][0]) {
  			aes._precompute();
  		}

  		const sbox = aes._tables[0][4];
  		const decTable = aes._tables[1];
  		const keyLen = key.length;

  		let i, encKey, decKey, rcon = 1;

  		if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
  			throw new Error("invalid aes key size");
  		}

  		aes._key = [encKey = key.slice(0), decKey = []];

  		// schedule encryption keys
  		for (i = keyLen; i < 4 * keyLen + 28; i++) {
  			let tmp = encKey[i - 1];

  			// apply sbox
  			if (i % keyLen === 0 || (keyLen === 8 && i % keyLen === 4)) {
  				tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255];

  				// shift rows and add rcon
  				if (i % keyLen === 0) {
  					tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
  					rcon = rcon << 1 ^ (rcon >> 7) * 283;
  				}
  			}

  			encKey[i] = encKey[i - keyLen] ^ tmp;
  		}

  		// schedule decryption keys
  		for (let j = 0; i; j++, i--) {
  			const tmp = encKey[j & 3 ? i : i - 4];
  			if (i <= 4 || j < 4) {
  				decKey[j] = tmp;
  			} else {
  				decKey[j] = decTable[0][sbox[tmp >>> 24]] ^
  					decTable[1][sbox[tmp >> 16 & 255]] ^
  					decTable[2][sbox[tmp >> 8 & 255]] ^
  					decTable[3][sbox[tmp & 255]];
  			}
  		}
  	}
  	// public
  	/* Something like this might appear here eventually
  	name: "AES",
  	blockSize: 4,
  	keySizes: [4,6,8],
  	*/

  	/**
  	 * Encrypt an array of 4 big-endian words.
  	 * @param {Array} data The plaintext.
  	 * @return {Array} The ciphertext.
  	 */
  	encrypt(data) {
  		return this._crypt(data, 0);
  	}

  	/**
  	 * Decrypt an array of 4 big-endian words.
  	 * @param {Array} data The ciphertext.
  	 * @return {Array} The plaintext.
  	 */
  	decrypt(data) {
  		return this._crypt(data, 1);
  	}

  	/**
  	 * Expand the S-box tables.
  	 *
  	 * @private
  	 */
  	_precompute() {
  		const encTable = this._tables[0];
  		const decTable = this._tables[1];
  		const sbox = encTable[4];
  		const sboxInv = decTable[4];
  		const d = [];
  		const th = [];
  		let xInv, x2, x4, x8;

  		// Compute double and third tables
  		for (let i = 0; i < 256; i++) {
  			th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
  		}

  		for (let x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
  			// Compute sbox
  			let s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
  			s = s >> 8 ^ s & 255 ^ 99;
  			sbox[x] = s;
  			sboxInv[s] = x;

  			// Compute MixColumns
  			x8 = d[x4 = d[x2 = d[x]]];
  			let tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  			let tEnc = d[s] * 0x101 ^ s * 0x1010100;

  			for (let i = 0; i < 4; i++) {
  				encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
  				decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
  			}
  		}

  		// Compactify.  Considerable speedup on Firefox.
  		for (let i = 0; i < 5; i++) {
  			encTable[i] = encTable[i].slice(0);
  			decTable[i] = decTable[i].slice(0);
  		}
  	}

  	/**
  	 * Encryption and decryption core.
  	 * @param {Array} input Four words to be encrypted or decrypted.
  	 * @param dir The direction, 0 for encrypt and 1 for decrypt.
  	 * @return {Array} The four encrypted or decrypted words.
  	 * @private
  	 */
  	_crypt(input, dir) {
  		if (input.length !== 4) {
  			throw new Error("invalid aes block size");
  		}

  		const key = this._key[dir];

  		const nInnerRounds = key.length / 4 - 2;
  		const out = [0, 0, 0, 0];
  		const table = this._tables[dir];

  		// load up the tables
  		const t0 = table[0];
  		const t1 = table[1];
  		const t2 = table[2];
  		const t3 = table[3];
  		const sbox = table[4];

  		// state variables a,b,c,d are loaded with pre-whitened data
  		let a = input[0] ^ key[0];
  		let b = input[dir ? 3 : 1] ^ key[1];
  		let c = input[2] ^ key[2];
  		let d = input[dir ? 1 : 3] ^ key[3];
  		let kIndex = 4;
  		let a2, b2, c2;

  		// Inner rounds.  Cribbed from OpenSSL.
  		for (let i = 0; i < nInnerRounds; i++) {
  			a2 = t0[a >>> 24] ^ t1[b >> 16 & 255] ^ t2[c >> 8 & 255] ^ t3[d & 255] ^ key[kIndex];
  			b2 = t0[b >>> 24] ^ t1[c >> 16 & 255] ^ t2[d >> 8 & 255] ^ t3[a & 255] ^ key[kIndex + 1];
  			c2 = t0[c >>> 24] ^ t1[d >> 16 & 255] ^ t2[a >> 8 & 255] ^ t3[b & 255] ^ key[kIndex + 2];
  			d = t0[d >>> 24] ^ t1[a >> 16 & 255] ^ t2[b >> 8 & 255] ^ t3[c & 255] ^ key[kIndex + 3];
  			kIndex += 4;
  			a = a2; b = b2; c = c2;
  		}

  		// Last round.
  		for (let i = 0; i < 4; i++) {
  			out[dir ? 3 & -i : i] =
  				sbox[a >>> 24] << 24 ^
  				sbox[b >> 16 & 255] << 16 ^
  				sbox[c >> 8 & 255] << 8 ^
  				sbox[d & 255] ^
  				key[kIndex++];
  			a2 = a; a = b; b = c; c = d; d = a2;
  		}

  		return out;
  	}
  };

  /**
   * Random values
   * @namespace
   */
  const random = {
  	/** 
  	 * Generate random words with pure js, cryptographically not as strong & safe as native implementation.
  	 * @param {TypedArray} typedArray The array to fill.
  	 * @return {TypedArray} The random values.
  	 */
  	getRandomValues(typedArray) {
  		const words = new Uint32Array(typedArray.buffer);
  		const r = (m_w) => {
  			let m_z = 0x3ade68b1;
  			const mask = 0xffffffff;
  			return function () {
  				m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask;
  				m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask;
  				const result = ((((m_z << 0x10) + m_w) & mask) / 0x100000000) + .5;
  				return result * (Math.random() > .5 ? 1 : -1);
  			};
  		};
  		for (let i = 0, rcache; i < typedArray.length; i += 4) {
  			const _r = r((rcache || Math.random()) * 0x100000000);
  			rcache = _r() * 0x3ade67b7;
  			words[i / 4] = (_r() * 0x100000000) | 0;
  		}
  		return typedArray;
  	}
  };

  /** @fileOverview CTR mode implementation.
   *
   * Special thanks to Roy Nicholson for pointing out a bug in our
   * implementation.
   *
   * @author Emily Stark
   * @author Mike Hamburg
   * @author Dan Boneh
   */

  /** Brian Gladman's CTR Mode.
  * @constructor
  * @param {Object} _prf The aes instance to generate key.
  * @param {bitArray} _iv The iv for ctr mode, it must be 128 bits.
  */

  const mode = {};

  /**
   * Brian Gladman's CTR Mode.
   * @namespace
   */
  mode.ctrGladman = class {
  	constructor(prf, iv) {
  		this._prf = prf;
  		this._initIv = iv;
  		this._iv = iv;
  	}

  	reset() {
  		this._iv = this._initIv;
  	}

  	/** Input some data to calculate.
  	 * @param {bitArray} data the data to process, it must be intergral multiple of 128 bits unless it's the last.
  	 */
  	update(data) {
  		return this.calculate(this._prf, data, this._iv);
  	}

  	incWord(word) {
  		if (((word >> 24) & 0xff) === 0xff) { //overflow
  			let b1 = (word >> 16) & 0xff;
  			let b2 = (word >> 8) & 0xff;
  			let b3 = word & 0xff;

  			if (b1 === 0xff) { // overflow b1   
  				b1 = 0;
  				if (b2 === 0xff) {
  					b2 = 0;
  					if (b3 === 0xff) {
  						b3 = 0;
  					} else {
  						++b3;
  					}
  				} else {
  					++b2;
  				}
  			} else {
  				++b1;
  			}

  			word = 0;
  			word += (b1 << 16);
  			word += (b2 << 8);
  			word += b3;
  		} else {
  			word += (0x01 << 24);
  		}
  		return word;
  	}

  	incCounter(counter) {
  		if ((counter[0] = this.incWord(counter[0])) === 0) {
  			// encr_data in fileenc.c from  Dr Brian Gladman's counts only with DWORD j < 8
  			counter[1] = this.incWord(counter[1]);
  		}
  	}

  	calculate(prf, data, iv) {
  		let l;
  		if (!(l = data.length)) {
  			return [];
  		}
  		const bl = bitArray.bitLength(data);
  		for (let i = 0; i < l; i += 4) {
  			this.incCounter(iv);
  			const e = prf.encrypt(iv);
  			data[i] ^= e[0];
  			data[i + 1] ^= e[1];
  			data[i + 2] ^= e[2];
  			data[i + 3] ^= e[3];
  		}
  		return bitArray.clamp(data, bl);
  	}
  };

  const misc = {
  	importKey(password) {
  		return new misc.hmacSha1(codec.bytes.toBits(password));
  	},
  	pbkdf2(prf, salt, count, length) {
  		count = count || 10000;
  		if (length < 0 || count < 0) {
  			throw new Error("invalid params to pbkdf2");
  		}
  		const byteLength = ((length >> 5) + 1) << 2;
  		let u, ui, i, j, k;
  		const arrayBuffer = new ArrayBuffer(byteLength);
  		const out = new DataView(arrayBuffer);
  		let outLength = 0;
  		const b = bitArray;
  		salt = codec.bytes.toBits(salt);
  		for (k = 1; outLength < (byteLength || 1); k++) {
  			u = ui = prf.encrypt(b.concat(salt, [k]));
  			for (i = 1; i < count; i++) {
  				ui = prf.encrypt(ui);
  				for (j = 0; j < ui.length; j++) {
  					u[j] ^= ui[j];
  				}
  			}
  			for (i = 0; outLength < (byteLength || 1) && i < u.length; i++) {
  				out.setInt32(outLength, u[i]);
  				outLength += 4;
  			}
  		}
  		return arrayBuffer.slice(0, length / 8);
  	}
  };

  /** @fileOverview HMAC implementation.
   *
   * @author Emily Stark
   * @author Mike Hamburg
   * @author Dan Boneh
   */

  /** HMAC with the specified hash function.
   * @constructor
   * @param {bitArray} key the key for HMAC.
   * @param {Object} [Hash=hash.sha1] The hash function to use.
   */
  misc.hmacSha1 = class {

  	constructor(key) {
  		const hmac = this;
  		const Hash = hmac._hash = hash.sha1;
  		const exKey = [[], []];
  		const bs = Hash.prototype.blockSize / 32;
  		hmac._baseHash = [new Hash(), new Hash()];

  		if (key.length > bs) {
  			key = Hash.hash(key);
  		}

  		for (let i = 0; i < bs; i++) {
  			exKey[0][i] = key[i] ^ 0x36363636;
  			exKey[1][i] = key[i] ^ 0x5C5C5C5C;
  		}

  		hmac._baseHash[0].update(exKey[0]);
  		hmac._baseHash[1].update(exKey[1]);
  		hmac._resultHash = new Hash(hmac._baseHash[0]);
  	}
  	reset() {
  		const hmac = this;
  		hmac._resultHash = new hmac._hash(hmac._baseHash[0]);
  		hmac._updated = false;
  	}

  	update(data) {
  		const hmac = this;
  		hmac._updated = true;
  		hmac._resultHash.update(data);
  	}

  	digest() {
  		const hmac = this;
  		const w = hmac._resultHash.finalize();
  		const result = new (hmac._hash)(hmac._baseHash[1]).update(w).finalize();

  		hmac.reset();

  		return result;
  	}

  	encrypt(data) {
  		if (!this._updated) {
  			this.update(data);
  			return this.digest(data);
  		} else {
  			throw new Error("encrypt on already updated hmac called!");
  		}
  	}
  };

  /*
   Copyright (c) 2022 Gildas Lormeau. All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright 
   notice, this list of conditions and the following disclaimer in 
   the documentation and/or other materials provided with the distribution.

   3. The names of the authors may not be used to endorse or promote products
   derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
   INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
   OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
   EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   */

  const ERR_INVALID_PASSWORD = "Invalid pasword";
  const BLOCK_LENGTH = 16;
  const RAW_FORMAT = "raw";
  const PBKDF2_ALGORITHM = { name: "PBKDF2" };
  const HASH_ALGORITHM = { name: "HMAC" };
  const HASH_FUNCTION = "SHA-1";
  const BASE_KEY_ALGORITHM = Object.assign({ hash: HASH_ALGORITHM }, PBKDF2_ALGORITHM);
  const DERIVED_BITS_ALGORITHM = Object.assign({ iterations: 1000, hash: { name: HASH_FUNCTION } }, PBKDF2_ALGORITHM);
  const DERIVED_BITS_USAGE = ["deriveBits"];
  const SALT_LENGTH = [8, 12, 16];
  const KEY_LENGTH = [16, 24, 32];
  const SIGNATURE_LENGTH = 10;
  const COUNTER_DEFAULT_VALUE = [0, 0, 0, 0];
  const CRYPTO_API_SUPPORTED = typeof crypto != "undefined";
  const SUBTLE_API_SUPPORTED = CRYPTO_API_SUPPORTED && typeof crypto.subtle != "undefined";
  const codecBytes = codec.bytes;
  const Aes = cipher.aes;
  const CtrGladman = mode.ctrGladman;
  const HmacSha1 = misc.hmacSha1;
  class AESDecrypt {

  	constructor(password, signed, strength) {
  		Object.assign(this, {
  			password,
  			signed,
  			strength: strength - 1,
  			pendingInput: new Uint8Array(0)
  		});
  	}

  	async append(input) {
  		const aesCrypto = this;
  		if (aesCrypto.password) {
  			const preamble = subarray(input, 0, SALT_LENGTH[aesCrypto.strength] + 2);
  			await createDecryptionKeys(aesCrypto, preamble, aesCrypto.password);
  			aesCrypto.password = null;
  			aesCrypto.aesCtrGladman = new CtrGladman(new Aes(aesCrypto.keys.key), Array.from(COUNTER_DEFAULT_VALUE));
  			aesCrypto.hmac = new HmacSha1(aesCrypto.keys.authentication);
  			input = subarray(input, SALT_LENGTH[aesCrypto.strength] + 2);
  		}
  		const output = new Uint8Array(input.length - SIGNATURE_LENGTH - ((input.length - SIGNATURE_LENGTH) % BLOCK_LENGTH));
  		return append(aesCrypto, input, output, 0, SIGNATURE_LENGTH, true);
  	}

  	flush() {
  		const aesCrypto = this;
  		const pendingInput = aesCrypto.pendingInput;
  		const chunkToDecrypt = subarray(pendingInput, 0, pendingInput.length - SIGNATURE_LENGTH);
  		const originalSignature = subarray(pendingInput, pendingInput.length - SIGNATURE_LENGTH);
  		let decryptedChunkArray = new Uint8Array(0);
  		if (chunkToDecrypt.length) {
  			const encryptedChunk = codecBytes.toBits(chunkToDecrypt);
  			aesCrypto.hmac.update(encryptedChunk);
  			const decryptedChunk = aesCrypto.aesCtrGladman.update(encryptedChunk);
  			decryptedChunkArray = codecBytes.fromBits(decryptedChunk);
  		}
  		let valid = true;
  		if (aesCrypto.signed) {
  			const signature = subarray(codecBytes.fromBits(aesCrypto.hmac.digest()), 0, SIGNATURE_LENGTH);
  			for (let indexSignature = 0; indexSignature < SIGNATURE_LENGTH; indexSignature++) {
  				if (signature[indexSignature] != originalSignature[indexSignature]) {
  					valid = false;
  				}
  			}
  		}
  		return {
  			valid,
  			data: decryptedChunkArray
  		};
  	}
  }

  class AESEncrypt {

  	constructor(password, strength) {
  		Object.assign(this, {
  			password,
  			strength: strength - 1,
  			pendingInput: new Uint8Array(0)
  		});
  	}

  	async append(input) {
  		const aesCrypto = this;
  		let preamble = new Uint8Array(0);
  		if (aesCrypto.password) {
  			preamble = await createEncryptionKeys(aesCrypto, aesCrypto.password);
  			aesCrypto.password = null;
  			aesCrypto.aesCtrGladman = new CtrGladman(new Aes(aesCrypto.keys.key), Array.from(COUNTER_DEFAULT_VALUE));
  			aesCrypto.hmac = new HmacSha1(aesCrypto.keys.authentication);
  		}
  		const output = new Uint8Array(preamble.length + input.length - (input.length % BLOCK_LENGTH));
  		output.set(preamble, 0);
  		return append(aesCrypto, input, output, preamble.length, 0);
  	}

  	flush() {
  		const aesCrypto = this;
  		let encryptedChunkArray = new Uint8Array(0);
  		if (aesCrypto.pendingInput.length) {
  			const encryptedChunk = aesCrypto.aesCtrGladman.update(codecBytes.toBits(aesCrypto.pendingInput));
  			aesCrypto.hmac.update(encryptedChunk);
  			encryptedChunkArray = codecBytes.fromBits(encryptedChunk);
  		}
  		const signature = subarray(codecBytes.fromBits(aesCrypto.hmac.digest()), 0, SIGNATURE_LENGTH);
  		return {
  			data: concat(encryptedChunkArray, signature),
  			signature
  		};
  	}
  }

  function append(aesCrypto, input, output, paddingStart, paddingEnd, verifySignature) {
  	const inputLength = input.length - paddingEnd;
  	if (aesCrypto.pendingInput.length) {
  		input = concat(aesCrypto.pendingInput, input);
  		output = expand(output, inputLength - (inputLength % BLOCK_LENGTH));
  	}
  	let offset;
  	for (offset = 0; offset <= inputLength - BLOCK_LENGTH; offset += BLOCK_LENGTH) {
  		const inputChunk = codecBytes.toBits(subarray(input, offset, offset + BLOCK_LENGTH));
  		if (verifySignature) {
  			aesCrypto.hmac.update(inputChunk);
  		}
  		const outputChunk = aesCrypto.aesCtrGladman.update(inputChunk);
  		if (!verifySignature) {
  			aesCrypto.hmac.update(outputChunk);
  		}
  		output.set(codecBytes.fromBits(outputChunk), offset + paddingStart);
  	}
  	aesCrypto.pendingInput = subarray(input, offset);
  	return output;
  }

  async function createDecryptionKeys(decrypt, preambleArray, password) {
  	await createKeys$1(decrypt, password, subarray(preambleArray, 0, SALT_LENGTH[decrypt.strength]));
  	const passwordVerification = subarray(preambleArray, SALT_LENGTH[decrypt.strength]);
  	const passwordVerificationKey = decrypt.keys.passwordVerification;
  	if (passwordVerificationKey[0] != passwordVerification[0] || passwordVerificationKey[1] != passwordVerification[1]) {
  		throw new Error(ERR_INVALID_PASSWORD);
  	}
  }

  async function createEncryptionKeys(encrypt, password) {
  	const salt = getRandomValues(new Uint8Array(SALT_LENGTH[encrypt.strength]));
  	await createKeys$1(encrypt, password, salt);
  	return concat(salt, encrypt.keys.passwordVerification);
  }

  async function createKeys$1(target, password, salt) {
  	const encodedPassword = encodeText(password);
  	const basekey = await importKey(RAW_FORMAT, encodedPassword, BASE_KEY_ALGORITHM, false, DERIVED_BITS_USAGE);
  	const derivedBits = await deriveBits(Object.assign({ salt }, DERIVED_BITS_ALGORITHM), basekey, 8 * ((KEY_LENGTH[target.strength] * 2) + 2));
  	const compositeKey = new Uint8Array(derivedBits);
  	target.keys = {
  		key: codecBytes.toBits(subarray(compositeKey, 0, KEY_LENGTH[target.strength])),
  		authentication: codecBytes.toBits(subarray(compositeKey, KEY_LENGTH[target.strength], KEY_LENGTH[target.strength] * 2)),
  		passwordVerification: subarray(compositeKey, KEY_LENGTH[target.strength] * 2)
  	};
  }

  function getRandomValues(array) {
  	if (CRYPTO_API_SUPPORTED && typeof crypto.getRandomValues == "function") {
  		return crypto.getRandomValues(array);
  	} else {
  		return random.getRandomValues(array);
  	}
  }

  function importKey(format, password, algorithm, extractable, keyUsages) {
  	if (CRYPTO_API_SUPPORTED && SUBTLE_API_SUPPORTED && typeof crypto.subtle.importKey == "function") {
  		return crypto.subtle.importKey(format, password, algorithm, extractable, keyUsages);
  	} else {
  		return misc.importKey(password);
  	}
  }

  async function deriveBits(algorithm, baseKey, length) {
  	if (CRYPTO_API_SUPPORTED && SUBTLE_API_SUPPORTED && typeof crypto.subtle.deriveBits == "function") {
  		return await crypto.subtle.deriveBits(algorithm, baseKey, length);
  	} else {
  		return misc.pbkdf2(baseKey, algorithm.salt, DERIVED_BITS_ALGORITHM.iterations, length);
  	}
  }

  function concat(leftArray, rightArray) {
  	let array = leftArray;
  	if (leftArray.length + rightArray.length) {
  		array = new Uint8Array(leftArray.length + rightArray.length);
  		array.set(leftArray, 0);
  		array.set(rightArray, leftArray.length);
  	}
  	return array;
  }

  function expand(inputArray, length) {
  	if (length && length > inputArray.length) {
  		const array = inputArray;
  		inputArray = new Uint8Array(length);
  		inputArray.set(array, 0);
  	}
  	return inputArray;
  }

  function subarray(array, begin, end) {
  	return array.subarray(begin, end);
  }

  /*
   Copyright (c) 2022 Gildas Lormeau. All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright 
   notice, this list of conditions and the following disclaimer in 
   the documentation and/or other materials provided with the distribution.

   3. The names of the authors may not be used to endorse or promote products
   derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
   INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
   OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
   EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   */

  const HEADER_LENGTH = 12;

  class ZipCryptoDecrypt {

  	constructor(password, passwordVerification) {
  		const zipCrypto = this;
  		Object.assign(zipCrypto, {
  			password,
  			passwordVerification
  		});
  		createKeys(zipCrypto, password);
  	}

  	append(input) {
  		const zipCrypto = this;
  		if (zipCrypto.password) {
  			const decryptedHeader = decrypt(zipCrypto, input.subarray(0, HEADER_LENGTH));
  			zipCrypto.password = null;
  			if (decryptedHeader[HEADER_LENGTH - 1] != zipCrypto.passwordVerification) {
  				throw new Error(ERR_INVALID_PASSWORD);
  			}
  			input = input.subarray(HEADER_LENGTH);
  		}
  		return decrypt(zipCrypto, input);
  	}

  	flush() {
  		return {
  			valid: true,
  			data: new Uint8Array(0)
  		};
  	}
  }

  class ZipCryptoEncrypt {

  	constructor(password, passwordVerification) {
  		const zipCrypto = this;
  		Object.assign(zipCrypto, {
  			password,
  			passwordVerification
  		});
  		createKeys(zipCrypto, password);
  	}

  	append(input) {
  		const zipCrypto = this;
  		let output;
  		let offset;
  		if (zipCrypto.password) {
  			zipCrypto.password = null;
  			const header = crypto.getRandomValues(new Uint8Array(HEADER_LENGTH));
  			header[HEADER_LENGTH - 1] = zipCrypto.passwordVerification;
  			output = new Uint8Array(input.length + header.length);
  			output.set(encrypt(zipCrypto, header), 0);
  			offset = HEADER_LENGTH;
  		} else {
  			output = new Uint8Array(input.length);
  			offset = 0;
  		}
  		output.set(encrypt(zipCrypto, input), offset);
  		return output;
  	}

  	flush() {
  		return {
  			data: new Uint8Array(0)
  		};
  	}
  }

  function decrypt(target, input) {
  	const output = new Uint8Array(input.length);
  	for (let index = 0; index < input.length; index++) {
  		output[index] = getByte(target) ^ input[index];
  		updateKeys(target, output[index]);
  	}
  	return output;
  }

  function encrypt(target, input) {
  	const output = new Uint8Array(input.length);
  	for (let index = 0; index < input.length; index++) {
  		output[index] = getByte(target) ^ input[index];
  		updateKeys(target, input[index]);
  	}
  	return output;
  }

  function createKeys(target, password) {
  	target.keys = [0x12345678, 0x23456789, 0x34567890];
  	target.crcKey0 = new Crc32(target.keys[0]);
  	target.crcKey2 = new Crc32(target.keys[2]);
  	for (let index = 0; index < password.length; index++) {
  		updateKeys(target, password.charCodeAt(index));
  	}
  }

  function updateKeys(target, byte) {
  	target.crcKey0.append([byte]);
  	target.keys[0] = ~target.crcKey0.get();
  	target.keys[1] = getInt32(target.keys[1] + getInt8(target.keys[0]));
  	target.keys[1] = getInt32(Math.imul(target.keys[1], 134775813) + 1);
  	target.crcKey2.append([target.keys[1] >>> 24]);
  	target.keys[2] = ~target.crcKey2.get();
  }

  function getByte(target) {
  	const temp = target.keys[2] | 2;
  	return getInt8(Math.imul(temp, (temp ^ 1)) >>> 8);
  }

  function getInt8(number) {
  	return number & 0xFF;
  }

  function getInt32(number) {
  	return number & 0xFFFFFFFF;
  }

  /*
   Copyright (c) 2022 Gildas Lormeau. All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright 
   notice, this list of conditions and the following disclaimer in 
   the documentation and/or other materials provided with the distribution.

   3. The names of the authors may not be used to endorse or promote products
   derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
   INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
   OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
   EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   */

  const CODEC_DEFLATE = "deflate";
  const CODEC_INFLATE = "inflate";
  const ERR_INVALID_SIGNATURE = "Invalid signature";

  class Inflate$2 {

  	constructor(codecConstructor, {
  		signature,
  		password,
  		signed,
  		compressed,
  		zipCrypto,
  		passwordVerification,
  		encryptionStrength
  	}, { chunkSize }) {
  		const encrypted = Boolean(password);
  		Object.assign(this, {
  			signature,
  			encrypted,
  			signed,
  			compressed,
  			inflate: compressed && new codecConstructor({ chunkSize }),
  			crc32: signed && new Crc32(),
  			zipCrypto,
  			decrypt: encrypted && zipCrypto ?
  				new ZipCryptoDecrypt(password, passwordVerification) :
  				new AESDecrypt(password, signed, encryptionStrength)
  		});
  	}

  	async append(data) {
  		const codec = this;
  		if (codec.encrypted && data.length) {
  			data = await codec.decrypt.append(data);
  		}
  		if (codec.compressed && data.length) {
  			data = await codec.inflate.append(data);
  		}
  		if ((!codec.encrypted || codec.zipCrypto) && codec.signed && data.length) {
  			codec.crc32.append(data);
  		}
  		return data;
  	}

  	async flush() {
  		const codec = this;
  		let signature;
  		let data = new Uint8Array(0);
  		if (codec.encrypted) {
  			const result = codec.decrypt.flush();
  			if (!result.valid) {
  				throw new Error(ERR_INVALID_SIGNATURE);
  			}
  			data = result.data;
  		}
  		if ((!codec.encrypted || codec.zipCrypto) && codec.signed) {
  			const dataViewSignature = new DataView(new Uint8Array(4).buffer);
  			signature = codec.crc32.get();
  			dataViewSignature.setUint32(0, signature);
  			if (codec.signature != dataViewSignature.getUint32(0, false)) {
  				throw new Error(ERR_INVALID_SIGNATURE);
  			}
  		}
  		if (codec.compressed) {
  			data = (await codec.inflate.append(data)) || new Uint8Array(0);
  			await codec.inflate.flush();
  		}
  		return { data, signature };
  	}
  }

  class Deflate {

  	constructor(codecConstructor, {
  		encrypted,
  		signed,
  		compressed,
  		level,
  		zipCrypto,
  		password,
  		passwordVerification,
  		encryptionStrength
  	}, { chunkSize }) {
  		Object.assign(this, {
  			encrypted,
  			signed,
  			compressed,
  			deflate: compressed && new codecConstructor({ level: level || 5, chunkSize }),
  			crc32: signed && new Crc32(),
  			zipCrypto,
  			encrypt: encrypted && zipCrypto ?
  				new ZipCryptoEncrypt(password, passwordVerification) :
  				new AESEncrypt(password, encryptionStrength)
  		});
  	}

  	async append(inputData) {
  		const codec = this;
  		let data = inputData;
  		if (codec.compressed && inputData.length) {
  			data = await codec.deflate.append(inputData);
  		}
  		if (codec.encrypted && data.length) {
  			data = await codec.encrypt.append(data);
  		}
  		if ((!codec.encrypted || codec.zipCrypto) && codec.signed && inputData.length) {
  			codec.crc32.append(inputData);
  		}
  		return data;
  	}

  	async flush() {
  		const codec = this;
  		let signature;
  		let data = new Uint8Array(0);
  		if (codec.compressed) {
  			data = (await codec.deflate.flush()) || new Uint8Array(0);
  		}
  		if (codec.encrypted) {
  			data = await codec.encrypt.append(data);
  			const result = codec.encrypt.flush();
  			signature = result.signature;
  			const newData = new Uint8Array(data.length + result.data.length);
  			newData.set(data, 0);
  			newData.set(result.data, data.length);
  			data = newData;
  		}
  		if ((!codec.encrypted || codec.zipCrypto) && codec.signed) {
  			signature = codec.crc32.get();
  		}
  		return { data, signature };
  	}
  }

  function createCodec$1(codecConstructor, options, config) {
  	if (options.codecType.startsWith(CODEC_DEFLATE)) {
  		return new Deflate(codecConstructor, options, config);
  	} else if (options.codecType.startsWith(CODEC_INFLATE)) {
  		return new Inflate$2(codecConstructor, options, config);
  	}
  }

  /*
   Copyright (c) 2022 Gildas Lormeau. All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright 
   notice, this list of conditions and the following disclaimer in 
   the documentation and/or other materials provided with the distribution.

   3. The names of the authors may not be used to endorse or promote products
   derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
   INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
   OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
   EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   */

  const MESSAGE_INIT = "init";
  const MESSAGE_APPEND = "append";
  const MESSAGE_FLUSH = "flush";
  const MESSAGE_EVENT_TYPE = "message";

  let classicWorkersSupported = true;

  var getWorker = (workerData, codecConstructor, options, config, onTaskFinished, webWorker, scripts) => {
  	Object.assign(workerData, {
  		busy: true,
  		codecConstructor,
  		options: Object.assign({}, options),
  		scripts,
  		terminate() {
  			if (workerData.worker && !workerData.busy) {
  				workerData.worker.terminate();
  				workerData.interface = null;
  			}
  		},
  		onTaskFinished() {
  			workerData.busy = false;
  			onTaskFinished(workerData);
  		}
  	});
  	return webWorker ? createWebWorkerInterface(workerData, config) : createWorkerInterface(workerData, config);
  };

  function createWorkerInterface(workerData, config) {
  	const interfaceCodec = createCodec$1(workerData.codecConstructor, workerData.options, config);
  	return {
  		async append(data) {
  			try {
  				return await interfaceCodec.append(data);
  			} catch (error) {
  				workerData.onTaskFinished();
  				throw error;
  			}
  		},
  		async flush() {
  			try {
  				return await interfaceCodec.flush();
  			} finally {
  				workerData.onTaskFinished();
  			}
  		},
  		abort() {
  			workerData.onTaskFinished();
  		}
  	};
  }

  function createWebWorkerInterface(workerData, config) {
  	let messageTask;
  	const workerOptions = { type: "module" };
  	if (!workerData.interface) {
  		if (!classicWorkersSupported) {
  			workerData.worker = getWorker(workerOptions, config.baseURL);
  		} else {
  			try {
  				workerData.worker = getWorker({}, config.baseURL);
  			} catch (_error) {
  				classicWorkersSupported = false;
  				workerData.worker = getWorker(workerOptions, config.baseURL);
  			}
  		}
  		workerData.worker.addEventListener(MESSAGE_EVENT_TYPE, onMessage, false);
  		workerData.interface = {
  			append(data) {
  				return initAndSendMessage({ type: MESSAGE_APPEND, data });
  			},
  			flush() {
  				return initAndSendMessage({ type: MESSAGE_FLUSH });
  			},
  			abort() {
  				workerData.onTaskFinished();
  			}
  		};
  	}
  	return workerData.interface;

  	function getWorker(options, baseURL) {
  		let url, scriptUrl;
  		url = workerData.scripts[0];
  		if (typeof url == "function") {
  			url = url();
  		}
  		try {
  			scriptUrl = new URL(url, baseURL);
  		} catch (_error) {
  			scriptUrl = url;
  		}
  		return new Worker(scriptUrl, options);
  	}

  	async function initAndSendMessage(message) {
  		if (!messageTask) {
  			const options = workerData.options;
  			const scripts = workerData.scripts.slice(1);
  			await sendMessage({ scripts, type: MESSAGE_INIT, options, config: { chunkSize: config.chunkSize } });
  		}
  		return sendMessage(message);
  	}

  	function sendMessage(message) {
  		const worker = workerData.worker;
  		const result = new Promise((resolve, reject) => messageTask = { resolve, reject });
  		try {
  			if (message.data) {
  				try {
  					message.data = message.data.buffer;
  					worker.postMessage(message, [message.data]);
  				} catch (_error) {
  					worker.postMessage(message);
  				}
  			} else {
  				worker.postMessage(message);
  			}
  		} catch (error) {
  			messageTask.reject(error);
  			messageTask = null;
  			workerData.onTaskFinished();
  		}
  		return result;
  	}

  	function onMessage(event) {
  		const message = event.data;
  		if (messageTask) {
  			const reponseError = message.error;
  			const type = message.type;
  			if (reponseError) {
  				const error = new Error(reponseError.message);
  				error.stack = reponseError.stack;
  				messageTask.reject(error);
  				messageTask = null;
  				workerData.onTaskFinished();
  			} else if (type == MESSAGE_INIT || type == MESSAGE_FLUSH || type == MESSAGE_APPEND) {
  				const data = message.data;
  				if (type == MESSAGE_FLUSH) {
  					messageTask.resolve({ data: new Uint8Array(data), signature: message.signature });
  					messageTask = null;
  					workerData.onTaskFinished();
  				} else {
  					messageTask.resolve(data && new Uint8Array(data));
  				}
  			}
  		}
  	}
  }

  /*
   Copyright (c) 2022 Gildas Lormeau. All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright 
   notice, this list of conditions and the following disclaimer in 
   the documentation and/or other materials provided with the distribution.

   3. The names of the authors may not be used to endorse or promote products
   derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
   INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
   OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
   EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   */

  let pool = [];
  const pendingRequests = [];

  function createCodec(codecConstructor, options, config) {
  	const streamCopy = !options.compressed && !options.signed && !options.encrypted;
  	const webWorker = !streamCopy && (options.useWebWorkers || (options.useWebWorkers === undefined && config.useWebWorkers));
  	const scripts = webWorker && config.workerScripts ? config.workerScripts[options.codecType] : [];
  	if (pool.length < config.maxWorkers) {
  		const workerData = {};
  		pool.push(workerData);
  		return getWorker(workerData, codecConstructor, options, config, onTaskFinished, webWorker, scripts);
  	} else {
  		const workerData = pool.find(workerData => !workerData.busy);
  		if (workerData) {
  			clearTerminateTimeout(workerData);
  			return getWorker(workerData, codecConstructor, options, config, onTaskFinished, webWorker, scripts);
  		} else {
  			return new Promise(resolve => pendingRequests.push({ resolve, codecConstructor, options, webWorker, scripts }));
  		}
  	}

  	function onTaskFinished(workerData) {
  		if (pendingRequests.length) {
  			const [{ resolve, codecConstructor, options, webWorker, scripts }] = pendingRequests.splice(0, 1);
  			resolve(getWorker(workerData, codecConstructor, options, config, onTaskFinished, webWorker, scripts));
  		} else if (workerData.worker) {
  			clearTerminateTimeout(workerData);
  			if (Number.isFinite(config.terminateWorkerTimeout) && config.terminateWorkerTimeout >= 0) {
  				workerData.terminateTimeout = setTimeout(() => {
  					pool = pool.filter(data => data != workerData);
  					workerData.terminate();
  				}, config.terminateWorkerTimeout);
  			}
  		} else {
  			pool = pool.filter(data => data != workerData);
  		}
  	}
  }

  function clearTerminateTimeout(workerData) {
  	if (workerData.terminateTimeout) {
  		clearTimeout(workerData.terminateTimeout);
  		workerData.terminateTimeout = null;
  	}
  }

  function terminateWorkers() {
  	pool.forEach(workerData => {
  		clearTerminateTimeout(workerData);
  		workerData.terminate();
  	});
  }

  /*
   Copyright (c) 2022 Gildas Lormeau. All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright 
   notice, this list of conditions and the following disclaimer in 
   the documentation and/or other materials provided with the distribution.

   3. The names of the authors may not be used to endorse or promote products
   derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
   INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
   OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
   EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   */

  const MINIMUM_CHUNK_SIZE = 64;
  const ERR_ABORT = "Abort error";

  async function processData(codec, reader, writer, offset, inputLengthGetter, config, options) {
  	const chunkSize = Math.max(config.chunkSize, MINIMUM_CHUNK_SIZE);
  	return processChunk();

  	async function processChunk(chunkOffset = 0, outputLength = 0) {
  		const signal = options.signal;
  		const inputLength = inputLengthGetter();
  		if (chunkOffset < inputLength) {
  			testAborted(signal, codec);
  			const inputData = await reader.readUint8Array(chunkOffset + offset, Math.min(chunkSize, inputLength - chunkOffset));
  			const chunkLength = inputData.length;
  			testAborted(signal, codec);
  			const data = await codec.append(inputData);
  			testAborted(signal, codec);
  			outputLength += await writeData(writer, data);
  			if (options.onprogress) {
  				try {
  					options.onprogress(chunkOffset + chunkLength, inputLength);
  				} catch (error) {
  					// ignored
  				}
  			}
  			return processChunk(chunkOffset + chunkSize, outputLength);
  		} else {
  			const result = await codec.flush();
  			outputLength += await writeData(writer, result.data);
  			return { signature: result.signature, length: outputLength };
  		}
  	}
  }

  function testAborted(signal, codec) {
  	if (signal && signal.aborted) {
  		codec.abort();
  		throw new Error(ERR_ABORT);
  	}
  }

  async function writeData(writer, data) {
  	if (data.length) {
  		await writer.writeUint8Array(data);
  	}
  	return data.length;
  }

  /*
   Copyright (c) 2022 Gildas Lormeau. All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright 
   notice, this list of conditions and the following disclaimer in 
   the documentation and/or other materials provided with the distribution.

   3. The names of the authors may not be used to endorse or promote products
   derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
   INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
   OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
   EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   */

  /* global Blob, FileReader, atob, btoa, XMLHttpRequest, document, fetch */

  const ERR_HTTP_STATUS = "HTTP error ";
  const ERR_HTTP_RANGE = "HTTP Range not supported";
  const ERR_NOT_SEEKABLE_READER = "Reader is not seekable";

  const CONTENT_TYPE_TEXT_PLAIN = "text/plain";
  const HTTP_HEADER_CONTENT_LENGTH = "Content-Length";
  const HTTP_HEADER_CONTENT_RANGE = "Content-Range";
  const HTTP_HEADER_ACCEPT_RANGES = "Accept-Ranges";
  const HTTP_HEADER_RANGE = "Range";
  const HTTP_METHOD_HEAD = "HEAD";
  const HTTP_METHOD_GET = "GET";
  const HTTP_RANGE_UNIT = "bytes";

  class Stream {

  	constructor() {
  		this.size = 0;
  	}

  	init() {
  		this.initialized = true;
  	}
  }

  class Reader extends Stream {
  }

  class Writer extends Stream {

  	writeUint8Array(array) {
  		this.size += array.length;
  	}
  }

  class TextReader extends Reader {

  	constructor(text) {
  		super();
  		this.blobReader = new BlobReader(new Blob([text], { type: CONTENT_TYPE_TEXT_PLAIN }));
  	}

  	init() {
  		super.init();
  		this.blobReader.init();
  		this.size = this.blobReader.size;
  	}

  	readUint8Array(offset, length) {
  		return this.blobReader.readUint8Array(offset, length);
  	}
  }

  class TextWriter extends Writer {

  	constructor(encoding) {
  		super();
  		this.encoding = encoding;
  		this.blob = new Blob([], { type: CONTENT_TYPE_TEXT_PLAIN });
  	}

  	writeUint8Array(array) {
  		super.writeUint8Array(array);
  		this.blob = new Blob([this.blob, array.buffer], { type: CONTENT_TYPE_TEXT_PLAIN });
  	}

  	getData() {
  		if (this.blob.text) {
  			return this.blob.text();
  		} else {
  			const reader = new FileReader();
  			return new Promise((resolve, reject) => {
  				reader.onload = event => resolve(event.target.result);
  				reader.onerror = () => reject(reader.error);
  				reader.readAsText(this.blob, this.encoding);
  			});
  		}
  	}
  }

  class Data64URIReader extends Reader {

  	constructor(dataURI) {
  		super();
  		this.dataURI = dataURI;
  		let dataEnd = dataURI.length;
  		while (dataURI.charAt(dataEnd - 1) == "=") {
  			dataEnd--;
  		}
  		this.dataStart = dataURI.indexOf(",") + 1;
  		this.size = Math.floor((dataEnd - this.dataStart) * 0.75);
  	}

  	readUint8Array(offset, length) {
  		const dataArray = new Uint8Array(length);
  		const start = Math.floor(offset / 3) * 4;
  		const bytes = atob(this.dataURI.substring(start + this.dataStart, Math.ceil((offset + length) / 3) * 4 + this.dataStart));
  		const delta = offset - Math.floor(start / 4) * 3;
  		for (let indexByte = delta; indexByte < delta + length; indexByte++) {
  			dataArray[indexByte - delta] = bytes.charCodeAt(indexByte);
  		}
  		return dataArray;
  	}
  }

  class Data64URIWriter extends Writer {

  	constructor(contentType) {
  		super();
  		this.data = "data:" + (contentType || "") + ";base64,";
  		this.pending = [];
  	}

  	writeUint8Array(array) {
  		super.writeUint8Array(array);
  		let indexArray = 0;
  		let dataString = this.pending;
  		const delta = this.pending.length;
  		this.pending = "";
  		for (indexArray = 0; indexArray < (Math.floor((delta + array.length) / 3) * 3) - delta; indexArray++) {
  			dataString += String.fromCharCode(array[indexArray]);
  		}
  		for (; indexArray < array.length; indexArray++) {
  			this.pending += String.fromCharCode(array[indexArray]);
  		}
  		if (dataString.length > 2) {
  			this.data += btoa(dataString);
  		} else {
  			this.pending = dataString;
  		}
  	}

  	getData() {
  		return this.data + btoa(this.pending);
  	}
  }

  class BlobReader extends Reader {

  	constructor(blob) {
  		super();
  		this.blob = blob;
  		this.size = blob.size;
  	}

  	async readUint8Array(offset, length) {
  		if (this.blob.arrayBuffer) {
  			return new Uint8Array(await this.blob.slice(offset, offset + length).arrayBuffer());
  		} else {
  			const reader = new FileReader();
  			return new Promise((resolve, reject) => {
  				reader.onload = event => resolve(new Uint8Array(event.target.result));
  				reader.onerror = () => reject(reader.error);
  				reader.readAsArrayBuffer(this.blob.slice(offset, offset + length));
  			});
  		}
  	}
  }

  class BlobWriter extends Writer {

  	constructor(contentType) {
  		super();
  		this.contentType = contentType;
  		this.arrayBuffersMaxlength = 8;
  		initArrayBuffers(this);
  	}

  	writeUint8Array(array) {
  		super.writeUint8Array(array);
  		if (this.arrayBuffers.length == this.arrayBuffersMaxlength) {
  			flushArrayBuffers(this);
  		}
  		this.arrayBuffers.push(array.buffer);
  	}

  	getData() {
  		if (!this.blob) {
  			if (this.arrayBuffers.length) {
  				flushArrayBuffers(this);
  			}
  			this.blob = this.pendingBlob;
  			initArrayBuffers(this);
  		}
  		return this.blob;
  	}
  }

  function initArrayBuffers(blobWriter) {
  	blobWriter.pendingBlob = new Blob([], { type: blobWriter.contentType });
  	blobWriter.arrayBuffers = [];
  }

  function flushArrayBuffers(blobWriter) {
  	blobWriter.pendingBlob = new Blob([blobWriter.pendingBlob, ...blobWriter.arrayBuffers], { type: blobWriter.contentType });
  	blobWriter.arrayBuffers = [];
  }

  class ReadableStreamReader {

  	constructor(readableStream) {
  		this.readableStream = readableStream;
  		this.reader = readableStream.getReader();
  		this.size = Infinity;
  		this.index = 0;
  		this.currentSize = 0;
  		this.pendingValue = new Uint8Array();
  	}

  	init() {
  		this.initialized = true;
  	}

  	async readUint8Array(index, length) {
  		if (this.index != index) {
  			throw new Error(ERR_NOT_SEEKABLE_READER);
  		}
  		let data = new Uint8Array(length);
  		let size = 0, done;
  		do {
  			const result = await this.reader.read();
  			let { value } = result;
  			done = result.done;
  			if (value) {
  				this.currentSize += value.length;
  			} else {
  				value = this.pendingValue;
  				this.pendingValue = new Uint8Array();
  			}
  			if (this.pendingValue.length) {
  				const newValue = new Uint8Array(this.pendingValue.length + value.length);
  				newValue.set(this.pendingValue);
  				newValue.set(value, this.pendingValue.length);
  				this.pendingValue = new Uint8Array();
  				value = newValue;
  			}
  			if (size + value.length > length) {
  				data.set(value.subarray(0, length), size);
  				this.pendingValue = value.subarray(length);
  				size += length;
  			} else {
  				data.set(value, size);
  				size += value.length;
  			}
  		} while (size < length && !done);
  		if (done && this.size == Infinity) {
  			this.size = this.currentSize;
  		}
  		if (this.size < length) {
  			data = data.slice(0, this.size);
  			length = this.size;
  		}
  		this.index += length;
  		return data;
  	}
  }

  class WritableStreamWriter extends Writer {

  	constructor(writableStream) {
  		super();
  		this.writableStream = writableStream;
  		this.writer = writableStream.getWriter();
  	}

  	async writeUint8Array(array) {
  		await this.writer.ready;
  		return this.writer.write(array);
  	}

  	async getData() {
  		await this.writer.ready;
  		await this.writer.close();
  		return this.writableStream;
  	}
  }

  class FetchReader extends Reader {

  	constructor(url, options) {
  		super();
  		this.url = url;
  		this.preventHeadRequest = options.preventHeadRequest;
  		this.useRangeHeader = options.useRangeHeader;
  		this.forceRangeRequests = options.forceRangeRequests;
  		this.options = Object.assign({}, options);
  		delete this.options.preventHeadRequest;
  		delete this.options.useRangeHeader;
  		delete this.options.forceRangeRequests;
  		delete this.options.useXHR;
  	}

  	async init() {
  		super.init();
  		await initHttpReader(this, sendFetchRequest, getFetchRequestData);
  	}

  	readUint8Array(index, length) {
  		return readUint8ArrayHttpReader(this, index, length, sendFetchRequest, getFetchRequestData);
  	}
  }

  class XHRReader extends Reader {

  	constructor(url, options) {
  		super();
  		this.url = url;
  		this.preventHeadRequest = options.preventHeadRequest;
  		this.useRangeHeader = options.useRangeHeader;
  		this.forceRangeRequests = options.forceRangeRequests;
  		this.options = options;
  	}

  	async init() {
  		super.init();
  		await initHttpReader(this, sendXMLHttpRequest, getXMLHttpRequestData);
  	}

  	readUint8Array(index, length) {
  		return readUint8ArrayHttpReader(this, index, length, sendXMLHttpRequest, getXMLHttpRequestData);
  	}
  }

  async function initHttpReader(httpReader, sendRequest, getRequestData) {
  	if (isHttpFamily(httpReader.url) && (httpReader.useRangeHeader || httpReader.forceRangeRequests)) {
  		const response = await sendRequest(HTTP_METHOD_GET, httpReader, getRangeHeaders(httpReader));
  		if (!httpReader.forceRangeRequests && response.headers.get(HTTP_HEADER_ACCEPT_RANGES) != HTTP_RANGE_UNIT) {
  			throw new Error(ERR_HTTP_RANGE);
  		} else {
  			let contentSize;
  			const contentRangeHeader = response.headers.get(HTTP_HEADER_CONTENT_RANGE);
  			if (contentRangeHeader) {
  				const splitHeader = contentRangeHeader.trim().split(/\s*\/\s*/);
  				if (splitHeader.length) {
  					const headerValue = splitHeader[1];
  					if (headerValue && headerValue != "*") {
  						contentSize = Number(headerValue);
  					}
  				}
  			}
  			if (contentSize === undefined) {
  				await getContentLength(httpReader, sendRequest, getRequestData);
  			} else {
  				httpReader.size = contentSize;
  			}
  		}
  	} else {
  		await getContentLength(httpReader, sendRequest, getRequestData);
  	}
  }

  async function readUint8ArrayHttpReader(httpReader, index, length, sendRequest, getRequestData) {
  	if (httpReader.useRangeHeader || httpReader.forceRangeRequests) {
  		const response = await sendRequest(HTTP_METHOD_GET, httpReader, getRangeHeaders(httpReader, index, length));
  		if (response.status != 206) {
  			throw new Error(ERR_HTTP_RANGE);
  		}
  		return new Uint8Array(await response.arrayBuffer());
  	} else {
  		if (!httpReader.data) {
  			await getRequestData(httpReader, httpReader.options);
  		}
  		return new Uint8Array(httpReader.data.subarray(index, index + length));
  	}
  }

  function getRangeHeaders(httpReader, index = 0, length = 1) {
  	return Object.assign({}, getHeaders(httpReader), { [HTTP_HEADER_RANGE]: HTTP_RANGE_UNIT + "=" + index + "-" + (index + length - 1) });
  }

  function getHeaders(httpReader) {
  	const headers = httpReader.options.headers;
  	if (headers) {
  		if (Symbol.iterator in headers) {
  			return Object.fromEntries(headers);
  		} else {
  			return headers;
  		}
  	}
  }

  async function getFetchRequestData(httpReader) {
  	await getRequestData(httpReader, sendFetchRequest);
  }

  async function getXMLHttpRequestData(httpReader) {
  	await getRequestData(httpReader, sendXMLHttpRequest);
  }

  async function getRequestData(httpReader, sendRequest) {
  	const response = await sendRequest(HTTP_METHOD_GET, httpReader, getHeaders(httpReader));
  	httpReader.data = new Uint8Array(await response.arrayBuffer());
  	if (!httpReader.size) {
  		httpReader.size = httpReader.data.length;
  	}
  }

  async function getContentLength(httpReader, sendRequest, getRequestData) {
  	if (httpReader.preventHeadRequest) {
  		await getRequestData(httpReader, httpReader.options);
  	} else {
  		const response = await sendRequest(HTTP_METHOD_HEAD, httpReader, getHeaders(httpReader));
  		const contentLength = response.headers.get(HTTP_HEADER_CONTENT_LENGTH);
  		if (contentLength) {
  			httpReader.size = Number(contentLength);
  		} else {
  			await getRequestData(httpReader, httpReader.options);
  		}
  	}
  }

  async function sendFetchRequest(method, { options, url }, headers) {
  	const response = await fetch(url, Object.assign({}, options, { method, headers }));
  	if (response.status < 400) {
  		return response;
  	} else {
  		throw new Error(ERR_HTTP_STATUS + (response.statusText || response.status));
  	}
  }

  function sendXMLHttpRequest(method, { url }, headers) {
  	return new Promise((resolve, reject) => {
  		const request = new XMLHttpRequest();
  		request.addEventListener("load", () => {
  			if (request.status < 400) {
  				const headers = [];
  				request.getAllResponseHeaders().trim().split(/[\r\n]+/).forEach(header => {
  					const splitHeader = header.trim().split(/\s*:\s*/);
  					splitHeader[0] = splitHeader[0].trim().replace(/^[a-z]|-[a-z]/g, value => value.toUpperCase());
  					headers.push(splitHeader);
  				});
  				resolve({
  					status: request.status,
  					arrayBuffer: () => request.response,
  					headers: new Map(headers)
  				});
  			} else {
  				reject(new Error(ERR_HTTP_STATUS + (request.statusText || request.status)));
  			}
  		}, false);
  		request.addEventListener("error", event => reject(event.detail.error), false);
  		request.open(method, url);
  		if (headers) {
  			for (const entry of Object.entries(headers)) {
  				request.setRequestHeader(entry[0], entry[1]);
  			}
  		}
  		request.responseType = "arraybuffer";
  		request.send();
  	});
  }

  class HttpReader extends Reader {

  	constructor(url, options = {}) {
  		super();
  		this.url = url;
  		if (options.useXHR) {
  			this.reader = new XHRReader(url, options);
  		} else {
  			this.reader = new FetchReader(url, options);
  		}
  	}

  	set size(value) {
  		// ignored
  	}

  	get size() {
  		return this.reader.size;
  	}

  	async init() {
  		super.init();
  		await this.reader.init();
  	}

  	readUint8Array(index, length) {
  		return this.reader.readUint8Array(index, length);
  	}
  }

  class HttpRangeReader extends HttpReader {

  	constructor(url, options = {}) {
  		options.useRangeHeader = true;
  		super(url, options);
  	}
  }


  class Uint8ArrayReader extends Reader {

  	constructor(array) {
  		super();
  		this.array = array;
  		this.size = array.length;
  	}

  	readUint8Array(index, length) {
  		return this.array.slice(index, index + length);
  	}
  }

  class Uint8ArrayWriter extends Writer {

  	constructor() {
  		super();
  		this.array = new Uint8Array(0);
  	}

  	writeUint8Array(array) {
  		super.writeUint8Array(array);
  		const previousArray = this.array;
  		this.array = new Uint8Array(previousArray.length + array.length);
  		this.array.set(previousArray);
  		this.array.set(array, previousArray.length);
  	}

  	getData() {
  		return this.array;
  	}
  }

  function isHttpFamily(url) {
  	if (typeof document != "undefined") {
  		const anchor = document.createElement("a");
  		anchor.href = url;
  		return anchor.protocol == "http:" || anchor.protocol == "https:";
  	} else {
  		return /^https?:\/\//i.test(url);
  	}
  }

  /*
   Copyright (c) 2022 Gildas Lormeau. All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright 
   notice, this list of conditions and the following disclaimer in 
   the documentation and/or other materials provided with the distribution.

   3. The names of the authors may not be used to endorse or promote products
   derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
   INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
   OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
   EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   */

  const MAX_32_BITS = 0xffffffff;
  const MAX_16_BITS = 0xffff;
  const COMPRESSION_METHOD_DEFLATE = 0x08;
  const COMPRESSION_METHOD_STORE = 0x00;
  const COMPRESSION_METHOD_AES = 0x63;

  const LOCAL_FILE_HEADER_SIGNATURE = 0x04034b50;
  const DATA_DESCRIPTOR_RECORD_SIGNATURE = 0x08074b50;
  const CENTRAL_FILE_HEADER_SIGNATURE = 0x02014b50;
  const END_OF_CENTRAL_DIR_SIGNATURE = 0x06054b50;
  const ZIP64_END_OF_CENTRAL_DIR_SIGNATURE = 0x06064b50;
  const ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIGNATURE = 0x07064b50;
  const END_OF_CENTRAL_DIR_LENGTH = 22;
  const ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH = 20;
  const ZIP64_END_OF_CENTRAL_DIR_LENGTH = 56;
  const ZIP64_END_OF_CENTRAL_DIR_TOTAL_LENGTH = END_OF_CENTRAL_DIR_LENGTH + ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH + ZIP64_END_OF_CENTRAL_DIR_LENGTH;

  const ZIP64_TOTAL_NUMBER_OF_DISKS = 1;

  const EXTRAFIELD_TYPE_ZIP64 = 0x0001;
  const EXTRAFIELD_TYPE_AES = 0x9901;
  const EXTRAFIELD_TYPE_NTFS = 0x000a;
  const EXTRAFIELD_TYPE_NTFS_TAG1 = 0x0001;
  const EXTRAFIELD_TYPE_EXTENDED_TIMESTAMP = 0x5455;
  const EXTRAFIELD_TYPE_UNICODE_PATH = 0x7075;
  const EXTRAFIELD_TYPE_UNICODE_COMMENT = 0x6375;

  const BITFLAG_ENCRYPTED = 0x01;
  const BITFLAG_LEVEL = 0x06;
  const BITFLAG_DATA_DESCRIPTOR = 0x0008;
  const BITFLAG_LANG_ENCODING_FLAG = 0x0800;
  const FILE_ATTR_MSDOS_DIR_MASK = 0x10;

  const VERSION_DEFLATE = 0x14;
  const VERSION_ZIP64 = 0x2D;
  const VERSION_AES = 0x33;

  const DIRECTORY_SIGNATURE = "/";

  const MAX_DATE = new Date(2107, 11, 31);
  const MIN_DATE = new Date(1980, 0, 1);

  /*
   Copyright (c) 2022 Gildas Lormeau. All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright 
   notice, this list of conditions and the following disclaimer in 
   the documentation and/or other materials provided with the distribution.

   3. The names of the authors may not be used to endorse or promote products
   derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
   INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
   OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
   EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   */

  const CP437 = "\0☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñÑªº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ ".split("");

  var decodeCP437 = stringValue => {
  	let result = "";
  	for (let indexCharacter = 0; indexCharacter < stringValue.length; indexCharacter++) {
  		result += CP437[stringValue[indexCharacter]];
  	}
  	return result;
  };

  /*
   Copyright (c) 2022 Gildas Lormeau. All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright 
   notice, this list of conditions and the following disclaimer in 
   the documentation and/or other materials provided with the distribution.

   3. The names of the authors may not be used to endorse or promote products
   derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
   INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
   OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
   EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   */

  function decodeText(value, encoding) {
  	if (encoding && encoding.trim().toLowerCase() == "cp437") {
  		return decodeCP437(value);
  	} else if (typeof TextDecoder == "undefined") {
  		const fileReader = new FileReader();
  		return new Promise((resolve, reject) => {
  			fileReader.onload = event => resolve(event.target.result);
  			fileReader.onerror = () => reject(fileReader.error);
  			fileReader.readAsText(new Blob([value]));
  		});
  	} else {
  		return new TextDecoder(encoding).decode(value);
  	}
  }

  /*
   Copyright (c) 2022 Gildas Lormeau. All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright 
   notice, this list of conditions and the following disclaimer in 
   the documentation and/or other materials provided with the distribution.

   3. The names of the authors may not be used to endorse or promote products
   derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
   INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
   OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
   EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   */

  const PROPERTY_NAMES = [
  	"filename", "rawFilename", "directory", "encrypted", "compressedSize", "uncompressedSize",
  	"lastModDate", "rawLastModDate", "comment", "rawComment", "signature", "extraField",
  	"rawExtraField", "bitFlag", "extraFieldZip64", "extraFieldUnicodePath", "extraFieldUnicodeComment",
  	"extraFieldAES", "filenameUTF8", "commentUTF8", "offset", "zip64", "compressionMethod",
  	"extraFieldNTFS", "lastAccessDate", "creationDate", "extraFieldExtendedTimestamp",
  	"version", "versionMadeBy", "msDosCompatible", "internalFileAttribute", "externalFileAttribute"];

  class Entry {

  	constructor(data) {
  		PROPERTY_NAMES.forEach(name => this[name] = data[name]);
  	}

  }

  /*
   Copyright (c) 2022 Gildas Lormeau. All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright 
   notice, this list of conditions and the following disclaimer in 
   the documentation and/or other materials provided with the distribution.

   3. The names of the authors may not be used to endorse or promote products
   derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
   INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
   OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
   EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   */

  const ERR_BAD_FORMAT = "File format is not recognized";
  const ERR_EOCDR_NOT_FOUND = "End of central directory not found";
  const ERR_EOCDR_ZIP64_NOT_FOUND = "End of Zip64 central directory not found";
  const ERR_EOCDR_LOCATOR_ZIP64_NOT_FOUND = "End of Zip64 central directory locator not found";
  const ERR_CENTRAL_DIRECTORY_NOT_FOUND = "Central directory header not found";
  const ERR_LOCAL_FILE_HEADER_NOT_FOUND = "Local file header not found";
  const ERR_EXTRAFIELD_ZIP64_NOT_FOUND = "Zip64 extra field not found";
  const ERR_ENCRYPTED = "File contains encrypted entry";
  const ERR_UNSUPPORTED_ENCRYPTION = "Encryption method not supported";
  const ERR_UNSUPPORTED_COMPRESSION = "Compression method not supported";
  const CHARSET_UTF8 = "utf-8";
  const CHARSET_CP437 = "cp437";
  const ZIP64_PROPERTIES = ["uncompressedSize", "compressedSize", "offset"];

  class ZipReader {

  	constructor(reader, options = {}) {
  		Object.assign(this, {
  			reader,
  			options,
  			config: getConfiguration()
  		});
  	}

  	async* getEntriesGenerator(options = {}) {
  		const zipReader = this;
  		const reader = zipReader.reader;
  		if (!reader.initialized) {
  			await reader.init();
  		}
  		if (reader.size < END_OF_CENTRAL_DIR_LENGTH) {
  			throw new Error(ERR_BAD_FORMAT);
  		}
  		const endOfDirectoryInfo = await seekSignature(reader, END_OF_CENTRAL_DIR_SIGNATURE, reader.size, END_OF_CENTRAL_DIR_LENGTH, MAX_16_BITS * 16);
  		if (!endOfDirectoryInfo) {
  			throw new Error(ERR_EOCDR_NOT_FOUND);
  		}
  		const endOfDirectoryView = getDataView$1(endOfDirectoryInfo);
  		let directoryDataLength = getUint32(endOfDirectoryView, 12);
  		let directoryDataOffset = getUint32(endOfDirectoryView, 16);
  		let filesLength = getUint16(endOfDirectoryView, 8);
  		let prependedDataLength = 0;
  		if (directoryDataOffset == MAX_32_BITS || directoryDataLength == MAX_32_BITS || filesLength == MAX_16_BITS) {
  			const endOfDirectoryLocatorArray = await readUint8Array(reader, endOfDirectoryInfo.offset - ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH, ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH);
  			const endOfDirectoryLocatorView = getDataView$1(endOfDirectoryLocatorArray);
  			if (getUint32(endOfDirectoryLocatorView, 0) != ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIGNATURE) {
  				throw new Error(ERR_EOCDR_ZIP64_NOT_FOUND);
  			}
  			directoryDataOffset = getBigUint64(endOfDirectoryLocatorView, 8);
  			let endOfDirectoryArray = await readUint8Array(reader, directoryDataOffset, ZIP64_END_OF_CENTRAL_DIR_LENGTH);
  			let endOfDirectoryView = getDataView$1(endOfDirectoryArray);
  			const expectedDirectoryDataOffset = endOfDirectoryInfo.offset - ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH - ZIP64_END_OF_CENTRAL_DIR_LENGTH;
  			if (getUint32(endOfDirectoryView, 0) != ZIP64_END_OF_CENTRAL_DIR_SIGNATURE && directoryDataOffset != expectedDirectoryDataOffset) {
  				const originalDirectoryDataOffset = directoryDataOffset;
  				directoryDataOffset = expectedDirectoryDataOffset;
  				prependedDataLength = directoryDataOffset - originalDirectoryDataOffset;
  				endOfDirectoryArray = await readUint8Array(reader, directoryDataOffset, ZIP64_END_OF_CENTRAL_DIR_LENGTH);
  				endOfDirectoryView = getDataView$1(endOfDirectoryArray);
  			}
  			if (getUint32(endOfDirectoryView, 0) != ZIP64_END_OF_CENTRAL_DIR_SIGNATURE) {
  				throw new Error(ERR_EOCDR_LOCATOR_ZIP64_NOT_FOUND);
  			}
  			filesLength = getBigUint64(endOfDirectoryView, 32);
  			directoryDataLength = getBigUint64(endOfDirectoryView, 40);
  			directoryDataOffset -= directoryDataLength;
  		}
  		if (directoryDataOffset < 0 || directoryDataOffset >= reader.size) {
  			throw new Error(ERR_BAD_FORMAT);
  		}
  		let offset = 0;
  		let directoryArray = await readUint8Array(reader, directoryDataOffset, directoryDataLength);
  		let directoryView = getDataView$1(directoryArray);
  		if (directoryDataLength) {
  			const expectedDirectoryDataOffset = endOfDirectoryInfo.offset - directoryDataLength;
  			if (getUint32(directoryView, offset) != CENTRAL_FILE_HEADER_SIGNATURE && directoryDataOffset != expectedDirectoryDataOffset) {
  				const originalDirectoryDataOffset = directoryDataOffset;
  				directoryDataOffset = expectedDirectoryDataOffset;
  				prependedDataLength = directoryDataOffset - originalDirectoryDataOffset;
  				directoryArray = await readUint8Array(reader, directoryDataOffset, directoryDataLength);
  				directoryView = getDataView$1(directoryArray);
  			}
  		}
  		if (directoryDataOffset < 0 || directoryDataOffset >= reader.size) {
  			throw new Error(ERR_BAD_FORMAT);
  		}
  		for (let indexFile = 0; indexFile < filesLength; indexFile++) {
  			const fileEntry = new ZipEntry(reader, zipReader.config, zipReader.options);
  			if (getUint32(directoryView, offset) != CENTRAL_FILE_HEADER_SIGNATURE) {
  				throw new Error(ERR_CENTRAL_DIRECTORY_NOT_FOUND);
  			}
  			readCommonHeader(fileEntry, directoryView, offset + 6);
  			const languageEncodingFlag = Boolean(fileEntry.bitFlag.languageEncodingFlag);
  			const filenameOffset = offset + 46;
  			const extraFieldOffset = filenameOffset + fileEntry.filenameLength;
  			const commentOffset = extraFieldOffset + fileEntry.extraFieldLength;
  			const versionMadeBy = getUint16(directoryView, offset + 4);
  			const msDosCompatible = (versionMadeBy & 0) == 0;
  			Object.assign(fileEntry, {
  				versionMadeBy,
  				msDosCompatible,
  				compressedSize: 0,
  				uncompressedSize: 0,
  				commentLength: getUint16(directoryView, offset + 32),
  				directory: msDosCompatible && ((getUint8(directoryView, offset + 38) & FILE_ATTR_MSDOS_DIR_MASK) == FILE_ATTR_MSDOS_DIR_MASK),
  				offset: getUint32(directoryView, offset + 42) + prependedDataLength,
  				internalFileAttribute: getUint32(directoryView, offset + 34),
  				externalFileAttribute: getUint32(directoryView, offset + 38),
  				rawFilename: directoryArray.subarray(filenameOffset, extraFieldOffset),
  				filenameUTF8: languageEncodingFlag,
  				commentUTF8: languageEncodingFlag,
  				rawExtraField: directoryArray.subarray(extraFieldOffset, commentOffset)
  			});
  			const endOffset = commentOffset + fileEntry.commentLength;
  			fileEntry.rawComment = directoryArray.subarray(commentOffset, endOffset);
  			const filenameEncoding = getOptionValue$1(zipReader, options, "filenameEncoding");
  			const commentEncoding = getOptionValue$1(zipReader, options, "commentEncoding");
  			const [filename, comment] = await Promise.all([
  				decodeText(fileEntry.rawFilename, fileEntry.filenameUTF8 ? CHARSET_UTF8 : filenameEncoding || CHARSET_CP437),
  				decodeText(fileEntry.rawComment, fileEntry.commentUTF8 ? CHARSET_UTF8 : commentEncoding || CHARSET_CP437)
  			]);
  			fileEntry.filename = filename;
  			fileEntry.comment = comment;
  			if (!fileEntry.directory && fileEntry.filename.endsWith(DIRECTORY_SIGNATURE)) {
  				fileEntry.directory = true;
  			}
  			await readCommonFooter(fileEntry, fileEntry, directoryView, offset + 6);
  			const entry = new Entry(fileEntry);
  			entry.getData = (writer, options) => fileEntry.getData(writer, entry, options);
  			offset = endOffset;
  			if (options.onprogress) {
  				try {
  					options.onprogress(indexFile + 1, filesLength, new Entry(fileEntry));
  				} catch (_error) {
  					// ignored
  				}
  			}
  			yield entry;
  		}
  		return true;
  	}

  	async getEntries(options = {}) {
  		const entries = [];
  		const iter = this.getEntriesGenerator(options);
  		let curr = iter.next();
  		while(!(await curr).done) {
  			entries.push((await curr).value);
  			curr = iter.next();
  		}
  		return entries;
  	}

  	async close() {
  	}
  }

  class ZipEntry {

  	constructor(reader, config, options) {
  		Object.assign(this, {
  			reader,
  			config,
  			options
  		});
  	}

  	async getData(writer, fileEntry, options = {}) {
  		const zipEntry = this;
  		const {
  			reader,
  			offset,
  			extraFieldAES,
  			compressionMethod,
  			config,
  			bitFlag,
  			signature,
  			rawLastModDate,
  			compressedSize
  		} = zipEntry;
  		const localDirectory = zipEntry.localDirectory = {};
  		if (!reader.initialized) {
  			await reader.init();
  		}
  		let dataArray = await readUint8Array(reader, offset, 30);
  		const dataView = getDataView$1(dataArray);
  		let password = getOptionValue$1(zipEntry, options, "password");
  		password = password && password.length && password;
  		if (extraFieldAES) {
  			if (extraFieldAES.originalCompressionMethod != COMPRESSION_METHOD_AES) {
  				throw new Error(ERR_UNSUPPORTED_COMPRESSION);
  			}
  		}
  		if (compressionMethod != COMPRESSION_METHOD_STORE && compressionMethod != COMPRESSION_METHOD_DEFLATE) {
  			throw new Error(ERR_UNSUPPORTED_COMPRESSION);
  		}
  		if (getUint32(dataView, 0) != LOCAL_FILE_HEADER_SIGNATURE) {
  			throw new Error(ERR_LOCAL_FILE_HEADER_NOT_FOUND);
  		}
  		readCommonHeader(localDirectory, dataView, 4);
  		dataArray = await readUint8Array(reader, offset, 30 + localDirectory.filenameLength + localDirectory.extraFieldLength);
  		localDirectory.rawExtraField = dataArray.subarray(30 + localDirectory.filenameLength);
  		await readCommonFooter(zipEntry, localDirectory, dataView, 4);
  		fileEntry.lastAccessDate = localDirectory.lastAccessDate;
  		fileEntry.creationDate = localDirectory.creationDate;
  		const encrypted = zipEntry.encrypted && localDirectory.encrypted;
  		const zipCrypto = encrypted && !extraFieldAES;
  		if (encrypted) {
  			if (!zipCrypto && extraFieldAES.strength === undefined) {
  				throw new Error(ERR_UNSUPPORTED_ENCRYPTION);
  			} else if (!password) {
  				throw new Error(ERR_ENCRYPTED);
  			}
  		}
  		const codec = await createCodec(config.Inflate, {
  			codecType: CODEC_INFLATE,
  			password,
  			zipCrypto,
  			encryptionStrength: extraFieldAES && extraFieldAES.strength,
  			signed: getOptionValue$1(zipEntry, options, "checkSignature"),
  			passwordVerification: zipCrypto && (bitFlag.dataDescriptor ? ((rawLastModDate >>> 8) & 0xFF) : ((signature >>> 24) & 0xFF)),
  			signature,
  			compressed: compressionMethod != 0,
  			encrypted,
  			useWebWorkers: getOptionValue$1(zipEntry, options, "useWebWorkers")
  		}, config);
  		if (!writer.initialized) {
  			await writer.init();
  		}
  		const signal = getOptionValue$1(zipEntry, options, "signal");
  		const dataOffset = offset + 30 + localDirectory.filenameLength + localDirectory.extraFieldLength;
  		await processData(codec, reader, writer, dataOffset, () => compressedSize, config, { onprogress: options.onprogress, signal });
  		return writer.getData();
  	}
  }

  function readCommonHeader(directory, dataView, offset) {
  	const rawBitFlag = directory.rawBitFlag = getUint16(dataView, offset + 2);
  	const encrypted = (rawBitFlag & BITFLAG_ENCRYPTED) == BITFLAG_ENCRYPTED;
  	const rawLastModDate = getUint32(dataView, offset + 6);
  	Object.assign(directory, {
  		encrypted,
  		version: getUint16(dataView, offset),
  		bitFlag: {
  			level: (rawBitFlag & BITFLAG_LEVEL) >> 1,
  			dataDescriptor: (rawBitFlag & BITFLAG_DATA_DESCRIPTOR) == BITFLAG_DATA_DESCRIPTOR,
  			languageEncodingFlag: (rawBitFlag & BITFLAG_LANG_ENCODING_FLAG) == BITFLAG_LANG_ENCODING_FLAG
  		},
  		rawLastModDate,
  		lastModDate: getDate(rawLastModDate),
  		filenameLength: getUint16(dataView, offset + 22),
  		extraFieldLength: getUint16(dataView, offset + 24)
  	});
  }

  async function readCommonFooter(fileEntry, directory, dataView, offset) {
  	const rawExtraField = directory.rawExtraField;
  	const extraField = directory.extraField = new Map();
  	const rawExtraFieldView = getDataView$1(new Uint8Array(rawExtraField));
  	let offsetExtraField = 0;
  	try {
  		while (offsetExtraField < rawExtraField.length) {
  			const type = getUint16(rawExtraFieldView, offsetExtraField);
  			const size = getUint16(rawExtraFieldView, offsetExtraField + 2);
  			extraField.set(type, {
  				type,
  				data: rawExtraField.slice(offsetExtraField + 4, offsetExtraField + 4 + size)
  			});
  			offsetExtraField += 4 + size;
  		}
  	} catch (_error) {
  		// ignored
  	}
  	const compressionMethod = getUint16(dataView, offset + 4);
  	directory.signature = getUint32(dataView, offset + 10);
  	directory.uncompressedSize = getUint32(dataView, offset + 18);
  	directory.compressedSize = getUint32(dataView, offset + 14);
  	const extraFieldZip64 = extraField.get(EXTRAFIELD_TYPE_ZIP64);
  	if (extraFieldZip64) {
  		readExtraFieldZip64(extraFieldZip64, directory);
  		directory.extraFieldZip64 = extraFieldZip64;
  	}
  	const extraFieldUnicodePath = extraField.get(EXTRAFIELD_TYPE_UNICODE_PATH);
  	if (extraFieldUnicodePath) {
  		await readExtraFieldUnicode(extraFieldUnicodePath, "filename", "rawFilename", directory, fileEntry);
  		directory.extraFieldUnicodePath = extraFieldUnicodePath;
  	}
  	const extraFieldUnicodeComment = extraField.get(EXTRAFIELD_TYPE_UNICODE_COMMENT);
  	if (extraFieldUnicodeComment) {
  		await readExtraFieldUnicode(extraFieldUnicodeComment, "comment", "rawComment", directory, fileEntry);
  		directory.extraFieldUnicodeComment = extraFieldUnicodeComment;
  	}
  	const extraFieldAES = extraField.get(EXTRAFIELD_TYPE_AES);
  	if (extraFieldAES) {
  		readExtraFieldAES(extraFieldAES, directory, compressionMethod);
  		directory.extraFieldAES = extraFieldAES;
  	} else {
  		directory.compressionMethod = compressionMethod;
  	}
  	const extraFieldNTFS = extraField.get(EXTRAFIELD_TYPE_NTFS);
  	if (extraFieldNTFS) {
  		readExtraFieldNTFS(extraFieldNTFS, directory);
  		directory.extraFieldNTFS = extraFieldNTFS;
  	}
  	const extraFieldExtendedTimestamp = extraField.get(EXTRAFIELD_TYPE_EXTENDED_TIMESTAMP);
  	if (extraFieldExtendedTimestamp) {
  		readExtraFieldExtendedTimestamp(extraFieldExtendedTimestamp, directory);
  		directory.extraFieldExtendedTimestamp = extraFieldExtendedTimestamp;
  	}
  }

  function readExtraFieldZip64(extraFieldZip64, directory) {
  	directory.zip64 = true;
  	const extraFieldView = getDataView$1(extraFieldZip64.data);
  	extraFieldZip64.values = [];
  	for (let indexValue = 0; indexValue < Math.floor(extraFieldZip64.data.length / 8); indexValue++) {
  		extraFieldZip64.values.push(getBigUint64(extraFieldView, 0 + indexValue * 8));
  	}
  	const missingProperties = ZIP64_PROPERTIES.filter(propertyName => directory[propertyName] == MAX_32_BITS);
  	for (let indexMissingProperty = 0; indexMissingProperty < missingProperties.length; indexMissingProperty++) {
  		extraFieldZip64[missingProperties[indexMissingProperty]] = extraFieldZip64.values[indexMissingProperty];
  	}
  	ZIP64_PROPERTIES.forEach(propertyName => {
  		if (directory[propertyName] == MAX_32_BITS) {
  			if (extraFieldZip64[propertyName] !== undefined) {
  				directory[propertyName] = extraFieldZip64[propertyName];
  			} else {
  				throw new Error(ERR_EXTRAFIELD_ZIP64_NOT_FOUND);
  			}
  		}
  	});
  }

  async function readExtraFieldUnicode(extraFieldUnicode, propertyName, rawPropertyName, directory, fileEntry) {
  	const extraFieldView = getDataView$1(extraFieldUnicode.data);
  	extraFieldUnicode.version = getUint8(extraFieldView, 0);
  	extraFieldUnicode.signature = getUint32(extraFieldView, 1);
  	const crc32 = new Crc32();
  	crc32.append(fileEntry[rawPropertyName]);
  	const dataViewSignature = getDataView$1(new Uint8Array(4));
  	dataViewSignature.setUint32(0, crc32.get(), true);
  	extraFieldUnicode[propertyName] = await decodeText(extraFieldUnicode.data.subarray(5));
  	extraFieldUnicode.valid = !fileEntry.bitFlag.languageEncodingFlag && extraFieldUnicode.signature == getUint32(dataViewSignature, 0);
  	if (extraFieldUnicode.valid) {
  		directory[propertyName] = extraFieldUnicode[propertyName];
  		directory[propertyName + "UTF8"] = true;
  	}
  }

  function readExtraFieldAES(extraFieldAES, directory, compressionMethod) {
  	const extraFieldView = getDataView$1(extraFieldAES.data);
  	extraFieldAES.vendorVersion = getUint8(extraFieldView, 0);
  	extraFieldAES.vendorId = getUint8(extraFieldView, 2);
  	const strength = getUint8(extraFieldView, 4);
  	extraFieldAES.strength = strength;
  	extraFieldAES.originalCompressionMethod = compressionMethod;
  	directory.compressionMethod = extraFieldAES.compressionMethod = getUint16(extraFieldView, 5);
  }

  function readExtraFieldNTFS(extraFieldNTFS, directory) {
  	const extraFieldView = getDataView$1(extraFieldNTFS.data);
  	let offsetExtraField = 4;
  	let tag1Data;
  	try {
  		while (offsetExtraField < extraFieldNTFS.data.length && !tag1Data) {
  			const tagValue = getUint16(extraFieldView, offsetExtraField);
  			const attributeSize = getUint16(extraFieldView, offsetExtraField + 2);
  			if (tagValue == EXTRAFIELD_TYPE_NTFS_TAG1) {
  				tag1Data = extraFieldNTFS.data.slice(offsetExtraField + 4, offsetExtraField + 4 + attributeSize);
  			}
  			offsetExtraField += 4 + attributeSize;
  		}
  	} catch (_error) {
  		// ignored
  	}
  	try {
  		if (tag1Data && tag1Data.length == 24) {
  			const tag1View = getDataView$1(tag1Data);
  			const rawLastModDate = tag1View.getBigUint64(0, true);
  			const rawLastAccessDate = tag1View.getBigUint64(8, true);
  			const rawCreationDate = tag1View.getBigUint64(16, true);
  			Object.assign(extraFieldNTFS, {
  				rawLastModDate,
  				rawLastAccessDate,
  				rawCreationDate
  			});
  			const lastModDate = getDateNTFS(rawLastModDate);
  			const lastAccessDate = getDateNTFS(rawLastAccessDate);
  			const creationDate = getDateNTFS(rawCreationDate);
  			const extraFieldData = { lastModDate, lastAccessDate, creationDate };
  			Object.assign(extraFieldNTFS, extraFieldData);
  			Object.assign(directory, extraFieldData);
  		}
  	} catch (_error) {
  		// ignored
  	}
  }

  function readExtraFieldExtendedTimestamp(extraFieldExtendedTimestamp, directory) {
  	const extraFieldView = getDataView$1(extraFieldExtendedTimestamp.data);
  	const flags = getUint8(extraFieldView, 0);
  	const timeProperties = [];
  	const timeRawProperties = [];
  	if ((flags & 0x1) == 0x1) {
  		timeProperties.push("lastModDate");
  		timeRawProperties.push("rawLastModDate");
  	}
  	if ((flags & 0x2) == 0x2) {
  		timeProperties.push("lastAccessDate");
  		timeRawProperties.push("rawLastAccessDate");
  	}
  	if ((flags & 0x4) == 0x4) {
  		timeProperties.push("creationDate");
  		timeRawProperties.push("rawCreationDate");
  	}
  	let offset = 1;
  	timeProperties.forEach((propertyName, indexProperty) => {
  		if (extraFieldExtendedTimestamp.data.length >= offset + 4) {
  			const time = getUint32(extraFieldView, offset);
  			directory[propertyName] = extraFieldExtendedTimestamp[propertyName] = new Date(time * 1000);
  			const rawPropertyName = timeRawProperties[indexProperty];
  			extraFieldExtendedTimestamp[rawPropertyName] = time;
  		}
  		offset += 4;
  	});
  }

  async function seekSignature(reader, signature, startOffset, minimumBytes, maximumLength) {
  	const signatureArray = new Uint8Array(4);
  	const signatureView = getDataView$1(signatureArray);
  	setUint32$1(signatureView, 0, signature);
  	const maximumBytes = minimumBytes + maximumLength;
  	return (await seek(minimumBytes)) || await seek(Math.min(maximumBytes, startOffset));

  	async function seek(length) {
  		const offset = startOffset - length;
  		const bytes = await readUint8Array(reader, offset, length);
  		for (let indexByte = bytes.length - minimumBytes; indexByte >= 0; indexByte--) {
  			if (bytes[indexByte] == signatureArray[0] && bytes[indexByte + 1] == signatureArray[1] &&
  				bytes[indexByte + 2] == signatureArray[2] && bytes[indexByte + 3] == signatureArray[3]) {
  				return {
  					offset: offset + indexByte,
  					buffer: bytes.slice(indexByte, indexByte + minimumBytes).buffer
  				};
  			}
  		}
  	}
  }

  function getOptionValue$1(zipReader, options, name) {
  	return options[name] === undefined ? zipReader.options[name] : options[name];
  }

  function getDate(timeRaw) {
  	const date = (timeRaw & 0xffff0000) >> 16, time = timeRaw & 0x0000ffff;
  	try {
  		return new Date(1980 + ((date & 0xFE00) >> 9), ((date & 0x01E0) >> 5) - 1, date & 0x001F, (time & 0xF800) >> 11, (time & 0x07E0) >> 5, (time & 0x001F) * 2, 0);
  	} catch (_error) {
  		// ignored
  	}
  }

  function getDateNTFS(timeRaw) {
  	return new Date((Number((timeRaw / BigInt(10000)) - BigInt(11644473600000))));
  }

  function getUint8(view, offset) {
  	return view.getUint8(offset);
  }

  function getUint16(view, offset) {
  	return view.getUint16(offset, true);
  }

  function getUint32(view, offset) {
  	return view.getUint32(offset, true);
  }

  function getBigUint64(view, offset) {
  	return Number(view.getBigUint64(offset, true));
  }

  function setUint32$1(view, offset, value) {
  	view.setUint32(offset, value, true);
  }

  function getDataView$1(array) {
  	return new DataView(array.buffer);
  }

  function readUint8Array(reader, offset, size) {
  	return reader.readUint8Array(offset, size);
  }

  /*
   Copyright (c) 2022 Gildas Lormeau. All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright 
   notice, this list of conditions and the following disclaimer in 
   the documentation and/or other materials provided with the distribution.

   3. The names of the authors may not be used to endorse or promote products
   derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
   INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
   OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
   EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   */

  const ERR_DUPLICATED_NAME = "File already exists";
  const ERR_INVALID_COMMENT = "Zip file comment exceeds 64KB";
  const ERR_INVALID_ENTRY_COMMENT = "File entry comment exceeds 64KB";
  const ERR_INVALID_ENTRY_NAME = "File entry name exceeds 64KB";
  const ERR_INVALID_VERSION = "Version exceeds 65535";
  const ERR_INVALID_ENCRYPTION_STRENGTH = "The strength must equal 1, 2, or 3";
  const ERR_INVALID_EXTRAFIELD_TYPE = "Extra field type exceeds 65535";
  const ERR_INVALID_EXTRAFIELD_DATA = "Extra field data exceeds 64KB";
  const ERR_UNSUPPORTED_FORMAT = "Zip64 is not supported";

  const EXTRAFIELD_DATA_AES = new Uint8Array([0x07, 0x00, 0x02, 0x00, 0x41, 0x45, 0x03, 0x00, 0x00]);
  const EXTRAFIELD_LENGTH_ZIP64 = 24;

  let workers = 0;

  class ZipWriter {

  	constructor(writer, options = {}) {
  		Object.assign(this, {
  			writer,
  			options,
  			config: getConfiguration(),
  			files: new Map(),
  			offset: writer.size,
  			pendingCompressedSize: 0,
  			pendingEntries: [],
  			pendingAddFileCalls: new Set()
  		});
  	}

  	async add(name = "", reader, options = {}) {
  		const zipWriter = this;
  		if (workers < zipWriter.config.maxWorkers) {
  			workers++;
  			let promiseAddFile;
  			try {
  				promiseAddFile = addFile(zipWriter, name, reader, options);
  				this.pendingAddFileCalls.add(promiseAddFile);
  				return await promiseAddFile;
  			} finally {
  				this.pendingAddFileCalls.delete(promiseAddFile);
  				workers--;
  				const pendingEntry = zipWriter.pendingEntries.shift();
  				if (pendingEntry) {
  					zipWriter.add(pendingEntry.name, pendingEntry.reader, pendingEntry.options)
  						.then(pendingEntry.resolve)
  						.catch(pendingEntry.reject);
  				}
  			}
  		} else {
  			return new Promise((resolve, reject) => zipWriter.pendingEntries.push({ name, reader, options, resolve, reject }));
  		}
  	}

  	async close(comment = new Uint8Array(0), options = {}) {
  		while (this.pendingAddFileCalls.size) {
  			await Promise.all(Array.from(this.pendingAddFileCalls));
  		}
  		await closeFile(this, comment, options);
  		return this.writer.getData();
  	}
  }

  async function addFile(zipWriter, name, reader, options) {
  	name = name.trim();
  	if (options.directory && (!name.endsWith(DIRECTORY_SIGNATURE))) {
  		name += DIRECTORY_SIGNATURE;
  	} else {
  		options.directory = name.endsWith(DIRECTORY_SIGNATURE);
  	}
  	if (zipWriter.files.has(name)) {
  		throw new Error(ERR_DUPLICATED_NAME);
  	}
  	const rawFilename = encodeText(name);
  	if (rawFilename.length > MAX_16_BITS) {
  		throw new Error(ERR_INVALID_ENTRY_NAME);
  	}
  	const comment = options.comment || "";
  	const rawComment = encodeText(comment);
  	if (rawComment.length > MAX_16_BITS) {
  		throw new Error(ERR_INVALID_ENTRY_COMMENT);
  	}
  	const version = zipWriter.options.version || options.version || 0;
  	if (version > MAX_16_BITS) {
  		throw new Error(ERR_INVALID_VERSION);
  	}
  	const versionMadeBy = zipWriter.options.versionMadeBy || options.versionMadeBy || 20;
  	if (versionMadeBy > MAX_16_BITS) {
  		throw new Error(ERR_INVALID_VERSION);
  	}
  	const lastModDate = getOptionValue(zipWriter, options, "lastModDate") || new Date();
  	const lastAccessDate = getOptionValue(zipWriter, options, "lastAccessDate");
  	const creationDate = getOptionValue(zipWriter, options, "creationDate");
  	const password = getOptionValue(zipWriter, options, "password");
  	const encryptionStrength = getOptionValue(zipWriter, options, "encryptionStrength") || 3;
  	const zipCrypto = getOptionValue(zipWriter, options, "zipCrypto");
  	if (password !== undefined && encryptionStrength !== undefined && (encryptionStrength < 1 || encryptionStrength > 3)) {
  		throw new Error(ERR_INVALID_ENCRYPTION_STRENGTH);
  	}
  	let rawExtraField = new Uint8Array(0);
  	const extraField = options.extraField;
  	if (extraField) {
  		let extraFieldSize = 0;
  		let offset = 0;
  		extraField.forEach(data => extraFieldSize += 4 + data.length);
  		rawExtraField = new Uint8Array(extraFieldSize);
  		extraField.forEach((data, type) => {
  			if (type > MAX_16_BITS) {
  				throw new Error(ERR_INVALID_EXTRAFIELD_TYPE);
  			}
  			if (data.length > MAX_16_BITS) {
  				throw new Error(ERR_INVALID_EXTRAFIELD_DATA);
  			}
  			arraySet(rawExtraField, new Uint16Array([type]), offset);
  			arraySet(rawExtraField, new Uint16Array([data.length]), offset + 2);
  			arraySet(rawExtraField, data, offset + 4);
  			offset += 4 + data.length;
  		});
  	}
  	let extendedTimestamp = getOptionValue(zipWriter, options, "extendedTimestamp");
  	if (extendedTimestamp === undefined) {
  		extendedTimestamp = true;
  	}
  	let maximumCompressedSize = 0;
  	let keepOrder = getOptionValue(zipWriter, options, "keepOrder");
  	if (keepOrder === undefined) {
  		keepOrder = true;
  	}
  	let uncompressedSize = 0;
  	let msDosCompatible = getOptionValue(zipWriter, options, "msDosCompatible");
  	if (msDosCompatible === undefined) {
  		msDosCompatible = true;
  	}
  	const internalFileAttribute = getOptionValue(zipWriter, options, "internalFileAttribute") || 0;
  	const externalFileAttribute = getOptionValue(zipWriter, options, "externalFileAttribute") || 0;
  	if (reader) {
  		if (!reader.initialized) {
  			await reader.init();
  		}
  		uncompressedSize = reader.size;
  		maximumCompressedSize = getMaximumCompressedSize(uncompressedSize);
  	}
  	let zip64 = options.zip64 || zipWriter.options.zip64 || false;
  	if (zipWriter.offset + zipWriter.pendingCompressedSize >= MAX_32_BITS ||
  		uncompressedSize >= MAX_32_BITS ||
  		maximumCompressedSize >= MAX_32_BITS) {
  		if (options.zip64 === false || zipWriter.options.zip64 === false || !keepOrder) {
  			throw new Error(ERR_UNSUPPORTED_FORMAT);
  		} else {
  			zip64 = true;
  		}
  	}
  	zipWriter.pendingCompressedSize += maximumCompressedSize;
  	await Promise.resolve();
  	const level = getOptionValue(zipWriter, options, "level");
  	const useWebWorkers = getOptionValue(zipWriter, options, "useWebWorkers");
  	const bufferedWrite = getOptionValue(zipWriter, options, "bufferedWrite");
  	let dataDescriptor = getOptionValue(zipWriter, options, "dataDescriptor");
  	let dataDescriptorSignature = getOptionValue(zipWriter, options, "dataDescriptorSignature");
  	const signal = getOptionValue(zipWriter, options, "signal");
  	if (dataDescriptor === undefined) {
  		dataDescriptor = true;
  	}
  	if (dataDescriptor && dataDescriptorSignature === undefined) {
  		dataDescriptorSignature = false;
  	}
  	const fileEntry = await getFileEntry(zipWriter, name, reader, Object.assign({}, options, {
  		rawFilename,
  		rawComment,
  		version,
  		versionMadeBy,
  		lastModDate,
  		lastAccessDate,
  		creationDate,
  		rawExtraField,
  		zip64,
  		password,
  		level,
  		useWebWorkers,
  		encryptionStrength,
  		extendedTimestamp,
  		zipCrypto,
  		bufferedWrite,
  		keepOrder,
  		dataDescriptor,
  		dataDescriptorSignature,
  		signal,
  		msDosCompatible,
  		internalFileAttribute,
  		externalFileAttribute
  	}));
  	if (maximumCompressedSize) {
  		zipWriter.pendingCompressedSize -= maximumCompressedSize;
  	}
  	Object.assign(fileEntry, { name, comment, extraField });
  	return new Entry(fileEntry);
  }

  async function getFileEntry(zipWriter, name, reader, options) {
  	const files = zipWriter.files;
  	const writer = zipWriter.writer;
  	const previousFileEntry = Array.from(files.values()).pop();
  	let fileEntry = {};
  	let bufferedWrite;
  	let resolveLockUnbufferedWrite;
  	let resolveLockCurrentFileEntry;
  	files.set(name, fileEntry);
  	try {
  		let lockPreviousFileEntry;
  		let fileWriter;
  		let lockCurrentFileEntry;
  		if (options.keepOrder) {
  			lockPreviousFileEntry = previousFileEntry && previousFileEntry.lock;
  		}
  		fileEntry.lock = lockCurrentFileEntry = new Promise(resolve => resolveLockCurrentFileEntry = resolve);
  		if (options.bufferedWrite || zipWriter.lockWrite || !options.dataDescriptor) {
  			fileWriter = new BlobWriter();
  			fileWriter.init();
  			bufferedWrite = true;
  		} else {
  			zipWriter.lockWrite = new Promise(resolve => resolveLockUnbufferedWrite = resolve);
  			if (!writer.initialized) {
  				await writer.init();
  			}
  			fileWriter = writer;
  		}
  		fileEntry = await createFileEntry(reader, fileWriter, zipWriter.config, options);
  		fileEntry.lock = lockCurrentFileEntry;
  		files.set(name, fileEntry);
  		fileEntry.filename = name;
  		if (bufferedWrite) {
  			let indexWrittenData = 0;
  			const blob = fileWriter.getData();
  			await Promise.all([zipWriter.lockWrite, lockPreviousFileEntry]);
  			let pendingFileEntry;
  			do {
  				pendingFileEntry = Array.from(files.values()).find(fileEntry => fileEntry.writingBufferedData);
  				if (pendingFileEntry) {
  					await pendingFileEntry.lock;
  				}
  			} while (pendingFileEntry && pendingFileEntry.lock);
  			fileEntry.writingBufferedData = true;
  			if (!options.dataDescriptor) {
  				const headerLength = 26;
  				const arrayBuffer = await sliceAsArrayBuffer(blob, 0, headerLength);
  				const arrayBufferView = new DataView(arrayBuffer);
  				if (!fileEntry.encrypted || options.zipCrypto) {
  					setUint32(arrayBufferView, 14, fileEntry.signature);
  				}
  				if (fileEntry.zip64) {
  					setUint32(arrayBufferView, 18, MAX_32_BITS);
  					setUint32(arrayBufferView, 22, MAX_32_BITS);
  				} else {
  					setUint32(arrayBufferView, 18, fileEntry.compressedSize);
  					setUint32(arrayBufferView, 22, fileEntry.uncompressedSize);
  				}
  				await writer.writeUint8Array(new Uint8Array(arrayBuffer));
  				indexWrittenData = headerLength;
  			}
  			await writeBlob(writer, blob, indexWrittenData);
  			delete fileEntry.writingBufferedData;
  		}
  		fileEntry.offset = zipWriter.offset;
  		if (fileEntry.zip64) {
  			const rawExtraFieldZip64View = getDataView(fileEntry.rawExtraFieldZip64);
  			setBigUint64(rawExtraFieldZip64View, 20, BigInt(fileEntry.offset));
  		} else if (fileEntry.offset >= MAX_32_BITS) {
  			throw new Error(ERR_UNSUPPORTED_FORMAT);
  		}
  		zipWriter.offset += fileEntry.length;
  		return fileEntry;
  	} catch (error) {
  		if ((bufferedWrite && fileEntry.writingBufferedData) || (!bufferedWrite && fileEntry.dataWritten)) {
  			error.corruptedEntry = zipWriter.hasCorruptedEntries = true;
  			if (fileEntry.uncompressedSize) {
  				zipWriter.offset += fileEntry.uncompressedSize;
  			}
  		}
  		files.delete(name);
  		throw error;
  	} finally {
  		resolveLockCurrentFileEntry();
  		if (resolveLockUnbufferedWrite) {
  			resolveLockUnbufferedWrite();
  		}
  	}
  }

  async function createFileEntry(reader, writer, config, options) {
  	const {
  		rawFilename,
  		lastAccessDate,
  		creationDate,
  		password,
  		level,
  		zip64,
  		zipCrypto,
  		dataDescriptor,
  		dataDescriptorSignature,
  		directory,
  		version,
  		versionMadeBy,
  		rawComment,
  		rawExtraField,
  		useWebWorkers,
  		onprogress,
  		signal,
  		encryptionStrength,
  		extendedTimestamp,
  		msDosCompatible,
  		internalFileAttribute,
  		externalFileAttribute
  	} = options;
  	const encrypted = Boolean(password && password.length);
  	const compressed = level !== 0 && !directory;
  	let rawExtraFieldAES;
  	if (encrypted && !zipCrypto) {
  		rawExtraFieldAES = new Uint8Array(EXTRAFIELD_DATA_AES.length + 2);
  		const extraFieldAESView = getDataView(rawExtraFieldAES);
  		setUint16(extraFieldAESView, 0, EXTRAFIELD_TYPE_AES);
  		arraySet(rawExtraFieldAES, EXTRAFIELD_DATA_AES, 2);
  		setUint8(extraFieldAESView, 8, encryptionStrength);
  	} else {
  		rawExtraFieldAES = new Uint8Array(0);
  	}
  	let rawExtraFieldNTFS;
  	let rawExtraFieldExtendedTimestamp;
  	if (extendedTimestamp) {
  		rawExtraFieldExtendedTimestamp = new Uint8Array(9 + (lastAccessDate ? 4 : 0) + (creationDate ? 4 : 0));
  		const extraFieldExtendedTimestampView = getDataView(rawExtraFieldExtendedTimestamp);
  		setUint16(extraFieldExtendedTimestampView, 0, EXTRAFIELD_TYPE_EXTENDED_TIMESTAMP);
  		setUint16(extraFieldExtendedTimestampView, 2, rawExtraFieldExtendedTimestamp.length - 4);
  		const extraFieldExtendedTimestampFlag = 0x1 + (lastAccessDate ? 0x2 : 0) + (creationDate ? 0x4 : 0);
  		setUint8(extraFieldExtendedTimestampView, 4, extraFieldExtendedTimestampFlag);
  		setUint32(extraFieldExtendedTimestampView, 5, Math.floor(options.lastModDate.getTime() / 1000));
  		if (lastAccessDate) {
  			setUint32(extraFieldExtendedTimestampView, 9, Math.floor(lastAccessDate.getTime() / 1000));
  		}
  		if (creationDate) {
  			setUint32(extraFieldExtendedTimestampView, 13, Math.floor(creationDate.getTime() / 1000));
  		}
  		try {
  			rawExtraFieldNTFS = new Uint8Array(36);
  			const extraFieldNTFSView = getDataView(rawExtraFieldNTFS);
  			const lastModTimeNTFS = getTimeNTFS(options.lastModDate);
  			setUint16(extraFieldNTFSView, 0, EXTRAFIELD_TYPE_NTFS);
  			setUint16(extraFieldNTFSView, 2, 32);
  			setUint16(extraFieldNTFSView, 8, EXTRAFIELD_TYPE_NTFS_TAG1);
  			setUint16(extraFieldNTFSView, 10, 24);
  			setBigUint64(extraFieldNTFSView, 12, lastModTimeNTFS);
  			setBigUint64(extraFieldNTFSView, 20, getTimeNTFS(lastAccessDate) || lastModTimeNTFS);
  			setBigUint64(extraFieldNTFSView, 28, getTimeNTFS(creationDate) || lastModTimeNTFS);
  		} catch (_error) {
  			rawExtraFieldNTFS = new Uint8Array(0);
  		}
  	} else {
  		rawExtraFieldNTFS = rawExtraFieldExtendedTimestamp = new Uint8Array(0);
  	}
  	const fileEntry = {
  		version: version || VERSION_DEFLATE,
  		versionMadeBy,
  		zip64,
  		directory: Boolean(directory),
  		filenameUTF8: true,
  		rawFilename,
  		commentUTF8: true,
  		rawComment,
  		rawExtraFieldZip64: zip64 ? new Uint8Array(EXTRAFIELD_LENGTH_ZIP64 + 4) : new Uint8Array(0),
  		rawExtraFieldExtendedTimestamp,
  		rawExtraFieldNTFS,
  		rawExtraFieldAES,
  		rawExtraField,
  		extendedTimestamp,
  		msDosCompatible,
  		internalFileAttribute,
  		externalFileAttribute
  	};
  	let uncompressedSize = fileEntry.uncompressedSize = 0;
  	let bitFlag = BITFLAG_LANG_ENCODING_FLAG;
  	if (dataDescriptor) {
  		bitFlag = bitFlag | BITFLAG_DATA_DESCRIPTOR;
  	}
  	let compressionMethod = COMPRESSION_METHOD_STORE;
  	if (compressed) {
  		compressionMethod = COMPRESSION_METHOD_DEFLATE;
  	}
  	if (zip64) {
  		fileEntry.version = fileEntry.version > VERSION_ZIP64 ? fileEntry.version : VERSION_ZIP64;
  	}
  	if (encrypted) {
  		bitFlag = bitFlag | BITFLAG_ENCRYPTED;
  		if (!zipCrypto) {
  			fileEntry.version = fileEntry.version > VERSION_AES ? fileEntry.version : VERSION_AES;
  			compressionMethod = COMPRESSION_METHOD_AES;
  			if (compressed) {
  				fileEntry.rawExtraFieldAES[9] = COMPRESSION_METHOD_DEFLATE;
  			}
  		}
  	}
  	fileEntry.compressionMethod = compressionMethod;
  	const headerArray = fileEntry.headerArray = new Uint8Array(26);
  	const headerView = getDataView(headerArray);
  	setUint16(headerView, 0, fileEntry.version);
  	setUint16(headerView, 2, bitFlag);
  	setUint16(headerView, 4, compressionMethod);
  	const dateArray = new Uint32Array(1);
  	const dateView = getDataView(dateArray);
  	let lastModDate;
  	if (options.lastModDate < MIN_DATE) {
  		lastModDate = MIN_DATE;
  	} else if (options.lastModDate > MAX_DATE) {
  		lastModDate = MAX_DATE;
  	} else {
  		lastModDate = options.lastModDate;
  	}
  	setUint16(dateView, 0, (((lastModDate.getHours() << 6) | lastModDate.getMinutes()) << 5) | lastModDate.getSeconds() / 2);
  	setUint16(dateView, 2, ((((lastModDate.getFullYear() - 1980) << 4) | (lastModDate.getMonth() + 1)) << 5) | lastModDate.getDate());
  	const rawLastModDate = dateArray[0];
  	setUint32(headerView, 6, rawLastModDate);
  	setUint16(headerView, 22, rawFilename.length);
  	const extraFieldLength = rawExtraFieldAES.length + rawExtraFieldExtendedTimestamp.length + rawExtraFieldNTFS.length + fileEntry.rawExtraField.length;
  	setUint16(headerView, 24, extraFieldLength);
  	const localHeaderArray = new Uint8Array(30 + rawFilename.length + extraFieldLength);
  	const localHeaderView = getDataView(localHeaderArray);
  	setUint32(localHeaderView, 0, LOCAL_FILE_HEADER_SIGNATURE);
  	arraySet(localHeaderArray, headerArray, 4);
  	arraySet(localHeaderArray, rawFilename, 30);
  	arraySet(localHeaderArray, rawExtraFieldAES, 30 + rawFilename.length);
  	arraySet(localHeaderArray, rawExtraFieldExtendedTimestamp, 30 + rawFilename.length + rawExtraFieldAES.length);
  	arraySet(localHeaderArray, rawExtraFieldNTFS, 30 + rawFilename.length + rawExtraFieldAES.length + rawExtraFieldExtendedTimestamp.length);
  	arraySet(localHeaderArray, fileEntry.rawExtraField, 30 + rawFilename.length + rawExtraFieldAES.length + rawExtraFieldExtendedTimestamp.length + rawExtraFieldNTFS.length);
  	let result;
  	let compressedSize = 0;
  	if (reader) {
  		const codec = await createCodec(config.Deflate, {
  			codecType: CODEC_DEFLATE,
  			level,
  			password,
  			encryptionStrength,
  			zipCrypto: encrypted && zipCrypto,
  			passwordVerification: encrypted && zipCrypto && (rawLastModDate >> 8) & 0xFF,
  			signed: true,
  			compressed,
  			encrypted,
  			useWebWorkers
  		}, config);
  		await writer.writeUint8Array(localHeaderArray);
  		fileEntry.dataWritten = true;
  		result = await processData(codec, reader, writer, 0, () => reader.size, config, { onprogress, signal });
  		uncompressedSize = fileEntry.uncompressedSize = reader.size;
  		compressedSize = result.length;
  	} else {
  		await writer.writeUint8Array(localHeaderArray);
  		fileEntry.dataWritten = true;
  	}
  	let dataDescriptorArray = new Uint8Array(0);
  	let dataDescriptorView, dataDescriptorOffset = 0;
  	if (dataDescriptor) {
  		dataDescriptorArray = new Uint8Array(zip64 ? (dataDescriptorSignature ? 24 : 20) : (dataDescriptorSignature ? 16 : 12));
  		dataDescriptorView = getDataView(dataDescriptorArray);
  		if (dataDescriptorSignature) {
  			dataDescriptorOffset = 4;
  			setUint32(dataDescriptorView, 0, DATA_DESCRIPTOR_RECORD_SIGNATURE);
  		}
  	}
  	if (reader) {
  		const signature = result.signature;
  		if ((!encrypted || zipCrypto) && signature !== undefined) {
  			setUint32(headerView, 10, signature);
  			fileEntry.signature = signature;
  			if (dataDescriptor) {
  				setUint32(dataDescriptorView, dataDescriptorOffset, signature);
  			}
  		}
  		if (zip64) {
  			const rawExtraFieldZip64View = getDataView(fileEntry.rawExtraFieldZip64);
  			setUint16(rawExtraFieldZip64View, 0, EXTRAFIELD_TYPE_ZIP64);
  			setUint16(rawExtraFieldZip64View, 2, EXTRAFIELD_LENGTH_ZIP64);
  			setUint32(headerView, 14, MAX_32_BITS);
  			setBigUint64(rawExtraFieldZip64View, 12, BigInt(compressedSize));
  			setUint32(headerView, 18, MAX_32_BITS);
  			setBigUint64(rawExtraFieldZip64View, 4, BigInt(uncompressedSize));
  			if (dataDescriptor) {
  				setBigUint64(dataDescriptorView, dataDescriptorOffset + 4, BigInt(compressedSize));
  				setBigUint64(dataDescriptorView, dataDescriptorOffset + 12, BigInt(uncompressedSize));
  			}
  		} else {
  			setUint32(headerView, 14, compressedSize);
  			setUint32(headerView, 18, uncompressedSize);
  			if (dataDescriptor) {
  				setUint32(dataDescriptorView, dataDescriptorOffset + 4, compressedSize);
  				setUint32(dataDescriptorView, dataDescriptorOffset + 8, uncompressedSize);
  			}
  		}
  	}
  	if (dataDescriptor) {
  		await writer.writeUint8Array(dataDescriptorArray);
  	}
  	const length = localHeaderArray.length + compressedSize + dataDescriptorArray.length;
  	Object.assign(fileEntry, { compressedSize, lastModDate, rawLastModDate, creationDate, lastAccessDate, encrypted, length });
  	return fileEntry;
  }

  async function closeFile(zipWriter, comment, options) {
  	const writer = zipWriter.writer;
  	const files = zipWriter.files;
  	let offset = 0;
  	let directoryDataLength = 0;
  	let directoryOffset = zipWriter.offset;
  	let filesLength = files.size;
  	for (const [, fileEntry] of files) {
  		directoryDataLength += 46 +
  			fileEntry.rawFilename.length +
  			fileEntry.rawComment.length +
  			fileEntry.rawExtraFieldZip64.length +
  			fileEntry.rawExtraFieldAES.length +
  			fileEntry.rawExtraFieldExtendedTimestamp.length +
  			fileEntry.rawExtraFieldNTFS.length +
  			fileEntry.rawExtraField.length;
  	}
  	let zip64 = options.zip64 || zipWriter.options.zip64 || false;
  	if (directoryOffset >= MAX_32_BITS || directoryDataLength >= MAX_32_BITS || filesLength >= MAX_16_BITS) {
  		if (options.zip64 === false || zipWriter.options.zip64 === false) {
  			throw new Error(ERR_UNSUPPORTED_FORMAT);
  		} else {
  			zip64 = true;
  		}
  	}
  	const directoryArray = new Uint8Array(directoryDataLength + (zip64 ? ZIP64_END_OF_CENTRAL_DIR_TOTAL_LENGTH : END_OF_CENTRAL_DIR_LENGTH));
  	const directoryView = getDataView(directoryArray);
  	if (comment && comment.length) {
  		if (comment.length <= MAX_16_BITS) {
  			setUint16(directoryView, offset + 20, comment.length);
  		} else {
  			throw new Error(ERR_INVALID_COMMENT);
  		}
  	}
  	for (const [indexFileEntry, fileEntry] of Array.from(files.values()).entries()) {
  		const {
  			rawFilename,
  			rawExtraFieldZip64,
  			rawExtraFieldAES,
  			rawExtraField,
  			rawComment,
  			versionMadeBy,
  			headerArray,
  			directory,
  			zip64,
  			msDosCompatible,
  			internalFileAttribute,
  			externalFileAttribute
  		} = fileEntry;
  		let rawExtraFieldExtendedTimestamp;
  		let rawExtraFieldNTFS;
  		if (fileEntry.extendedTimestamp) {
  			rawExtraFieldNTFS = fileEntry.rawExtraFieldNTFS;
  			rawExtraFieldExtendedTimestamp = new Uint8Array(9);
  			const extraFieldExtendedTimestampView = getDataView(rawExtraFieldExtendedTimestamp);
  			setUint16(extraFieldExtendedTimestampView, 0, EXTRAFIELD_TYPE_EXTENDED_TIMESTAMP);
  			setUint16(extraFieldExtendedTimestampView, 2, rawExtraFieldExtendedTimestamp.length - 4);
  			setUint8(extraFieldExtendedTimestampView, 4, 0x1);
  			setUint32(extraFieldExtendedTimestampView, 5, Math.floor(fileEntry.lastModDate.getTime() / 1000));
  		} else {
  			rawExtraFieldNTFS = rawExtraFieldExtendedTimestamp = new Uint8Array(0);
  		}
  		const extraFieldLength = rawExtraFieldZip64.length + rawExtraFieldAES.length + rawExtraFieldExtendedTimestamp.length + rawExtraFieldNTFS.length + rawExtraField.length;
  		setUint32(directoryView, offset, CENTRAL_FILE_HEADER_SIGNATURE);
  		setUint16(directoryView, offset + 4, versionMadeBy);
  		arraySet(directoryArray, headerArray, offset + 6);
  		setUint16(directoryView, offset + 30, extraFieldLength);
  		setUint16(directoryView, offset + 32, rawComment.length);
  		setUint32(directoryView, offset + 34, internalFileAttribute);
  		if (externalFileAttribute) {
  			setUint32(directoryView, offset + 38, externalFileAttribute);
  		} else if (directory && msDosCompatible) {
  			setUint8(directoryView, offset + 38, FILE_ATTR_MSDOS_DIR_MASK);
  		}
  		if (zip64) {
  			setUint32(directoryView, offset + 42, MAX_32_BITS);
  		} else {
  			setUint32(directoryView, offset + 42, fileEntry.offset);
  		}
  		arraySet(directoryArray, rawFilename, offset + 46);
  		arraySet(directoryArray, rawExtraFieldZip64, offset + 46 + rawFilename.length);
  		arraySet(directoryArray, rawExtraFieldAES, offset + 46 + rawFilename.length + rawExtraFieldZip64.length);
  		arraySet(directoryArray, rawExtraFieldExtendedTimestamp, offset + 46 + rawFilename.length + rawExtraFieldZip64.length + rawExtraFieldAES.length);
  		arraySet(directoryArray, rawExtraFieldNTFS, offset + 46 + rawFilename.length + rawExtraFieldZip64.length + rawExtraFieldAES.length + rawExtraFieldExtendedTimestamp.length);
  		arraySet(directoryArray, rawExtraField, offset + 46 + rawFilename.length + rawExtraFieldZip64.length + rawExtraFieldAES.length + rawExtraFieldExtendedTimestamp.length + rawExtraFieldNTFS.length);
  		arraySet(directoryArray, rawComment, offset + 46 + rawFilename.length + extraFieldLength);
  		offset += 46 + rawFilename.length + extraFieldLength + rawComment.length;
  		if (options.onprogress) {
  			try {
  				options.onprogress(indexFileEntry + 1, files.size, new Entry(fileEntry));
  			} catch (_error) {
  				// ignored
  			}
  		}
  	}
  	if (zip64) {
  		setUint32(directoryView, offset, ZIP64_END_OF_CENTRAL_DIR_SIGNATURE);
  		setBigUint64(directoryView, offset + 4, BigInt(44));
  		setUint16(directoryView, offset + 12, 45);
  		setUint16(directoryView, offset + 14, 45);
  		setBigUint64(directoryView, offset + 24, BigInt(filesLength));
  		setBigUint64(directoryView, offset + 32, BigInt(filesLength));
  		setBigUint64(directoryView, offset + 40, BigInt(directoryDataLength));
  		setBigUint64(directoryView, offset + 48, BigInt(directoryOffset));
  		setUint32(directoryView, offset + 56, ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIGNATURE);
  		setBigUint64(directoryView, offset + 64, BigInt(directoryOffset) + BigInt(directoryDataLength));
  		setUint32(directoryView, offset + 72, ZIP64_TOTAL_NUMBER_OF_DISKS);
  		filesLength = MAX_16_BITS;
  		directoryOffset = MAX_32_BITS;
  		directoryDataLength = MAX_32_BITS;
  		offset += 76;
  	}
  	setUint32(directoryView, offset, END_OF_CENTRAL_DIR_SIGNATURE);
  	setUint16(directoryView, offset + 8, filesLength);
  	setUint16(directoryView, offset + 10, filesLength);
  	setUint32(directoryView, offset + 12, directoryDataLength);
  	setUint32(directoryView, offset + 16, directoryOffset);
  	await writer.writeUint8Array(directoryArray);
  	if (comment && comment.length) {
  		await writer.writeUint8Array(comment);
  	}
  }

  function sliceAsArrayBuffer(blob, start, end) {
  	if (blob.arrayBuffer) {
  		if (start || end) {
  			return blob.slice(start, end).arrayBuffer();
  		} else {
  			return blob.arrayBuffer();
  		}
  	} else {
  		const fileReader = new FileReader();
  		return new Promise((resolve, reject) => {
  			fileReader.onload = event => resolve(event.target.result);
  			fileReader.onerror = () => reject(fileReader.error);
  			fileReader.readAsArrayBuffer(start || end ? blob.slice(start, end) : blob);
  		});
  	}
  }

  async function writeBlob(writer, blob, start = 0) {
  	const blockSize = 512 * 1024 * 1024;
  	await writeSlice();

  	async function writeSlice() {
  		if (start < blob.size) {
  			const arrayBuffer = await sliceAsArrayBuffer(blob, start, start + blockSize);
  			await writer.writeUint8Array(new Uint8Array(arrayBuffer));
  			start += blockSize;
  			await writeSlice();
  		}
  	}
  }

  function getTimeNTFS(date) {
  	if (date) {
  		return ((BigInt(date.getTime()) + BigInt(11644473600000)) * BigInt(10000));
  	}
  }

  function getOptionValue(zipWriter, options, name) {
  	return options[name] === undefined ? zipWriter.options[name] : options[name];
  }

  function getMaximumCompressedSize(uncompressedSize) {
  	return uncompressedSize + (5 * (Math.floor(uncompressedSize / 16383) + 1));
  }

  function setUint8(view, offset, value) {
  	view.setUint8(offset, value);
  }

  function setUint16(view, offset, value) {
  	view.setUint16(offset, value, true);
  }

  function setUint32(view, offset, value) {
  	view.setUint32(offset, value, true);
  }

  function setBigUint64(view, offset, value) {
  	view.setBigUint64(offset, value, true);
  }

  function arraySet(array, typedArray, offset) {
  	array.set(typedArray, offset);
  }

  function getDataView(array) {
  	return new DataView(array.buffer);
  }

  /*
   Copyright (c) 2022 Gildas Lormeau. All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright 
   notice, this list of conditions and the following disclaimer in 
   the documentation and/or other materials provided with the distribution.

   3. The names of the authors may not be used to endorse or promote products
   derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
   INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
   OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
   EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   */

  configure({ Deflate: ZipDeflate, Inflate: ZipInflate });

  var zipNoWorker = /*#__PURE__*/Object.freeze({
  	__proto__: null,
  	configure: configure,
  	getMimeType: getMimeType,
  	terminateWorkers: terminateWorkers,
  	ERR_ABORT: ERR_ABORT,
  	Reader: Reader,
  	Writer: Writer,
  	TextReader: TextReader,
  	TextWriter: TextWriter,
  	Data64URIReader: Data64URIReader,
  	Data64URIWriter: Data64URIWriter,
  	BlobReader: BlobReader,
  	BlobWriter: BlobWriter,
  	Uint8ArrayReader: Uint8ArrayReader,
  	Uint8ArrayWriter: Uint8ArrayWriter,
  	HttpReader: HttpReader,
  	HttpRangeReader: HttpRangeReader,
  	ReadableStreamReader: ReadableStreamReader,
  	WritableStreamWriter: WritableStreamWriter,
  	ERR_HTTP_RANGE: ERR_HTTP_RANGE,
  	ERR_NOT_SEEKABLE_READER: ERR_NOT_SEEKABLE_READER,
  	ZipReader: ZipReader,
  	ERR_BAD_FORMAT: ERR_BAD_FORMAT,
  	ERR_EOCDR_NOT_FOUND: ERR_EOCDR_NOT_FOUND,
  	ERR_EOCDR_ZIP64_NOT_FOUND: ERR_EOCDR_ZIP64_NOT_FOUND,
  	ERR_EOCDR_LOCATOR_ZIP64_NOT_FOUND: ERR_EOCDR_LOCATOR_ZIP64_NOT_FOUND,
  	ERR_CENTRAL_DIRECTORY_NOT_FOUND: ERR_CENTRAL_DIRECTORY_NOT_FOUND,
  	ERR_LOCAL_FILE_HEADER_NOT_FOUND: ERR_LOCAL_FILE_HEADER_NOT_FOUND,
  	ERR_EXTRAFIELD_ZIP64_NOT_FOUND: ERR_EXTRAFIELD_ZIP64_NOT_FOUND,
  	ERR_ENCRYPTED: ERR_ENCRYPTED,
  	ERR_UNSUPPORTED_ENCRYPTION: ERR_UNSUPPORTED_ENCRYPTION,
  	ERR_UNSUPPORTED_COMPRESSION: ERR_UNSUPPORTED_COMPRESSION,
  	ERR_INVALID_SIGNATURE: ERR_INVALID_SIGNATURE,
  	ERR_INVALID_PASSWORD: ERR_INVALID_PASSWORD,
  	ZipWriter: ZipWriter,
  	ERR_DUPLICATED_NAME: ERR_DUPLICATED_NAME,
  	ERR_INVALID_COMMENT: ERR_INVALID_COMMENT,
  	ERR_INVALID_ENTRY_NAME: ERR_INVALID_ENTRY_NAME,
  	ERR_INVALID_ENTRY_COMMENT: ERR_INVALID_ENTRY_COMMENT,
  	ERR_INVALID_VERSION: ERR_INVALID_VERSION,
  	ERR_INVALID_EXTRAFIELD_TYPE: ERR_INVALID_EXTRAFIELD_TYPE,
  	ERR_INVALID_EXTRAFIELD_DATA: ERR_INVALID_EXTRAFIELD_DATA,
  	ERR_INVALID_ENCRYPTION_STRENGTH: ERR_INVALID_ENCRYPTION_STRENGTH,
  	ERR_UNSUPPORTED_FORMAT: ERR_UNSUPPORTED_FORMAT
  });

  /**
   * If element is a string, look up the element in the DOM by ID.  Otherwise return element.
   *
   * @private
   *
   * @exception {DeveloperError} Element with id "id" does not exist in the document.
   */
  function getElement(element) {
    if (typeof element === "string") {
      const foundElement = document.getElementById(element);

      //>>includeStart('debug', pragmas.debug);
      if (foundElement === null) {
        throw new DeveloperError(
          `Element with id "${element}" does not exist in the document.`
        );
      }
      //>>includeEnd('debug');

      element = foundElement;
    }
    return element;
  }

  /**
   * @alias KmlLookAt
   * @constructor
   *
   * @param {Cartesian3} position camera position
   * @param {HeadingPitchRange} headingPitchRange camera orientation
   */
  function KmlLookAt(position, headingPitchRange) {
    this.position = position;
    this.headingPitchRange = headingPitchRange;
  }

  /**
   * Describes a KmlTour, which uses KmlTourFlyTo, and KmlTourWait to
   * guide the camera to a specified destinations on given time intervals.
   *
   * @alias KmlTour
   * @constructor
   *
   * @param {String} name name parsed from KML
   * @param {String} id id parsed from KML
   * @param {Array} playlist array with KmlTourFlyTos and KmlTourWaits
   *
   * @see KmlTourFlyTo
   * @see KmlTourWait
   *
   * @demo {@link https://sandcastle.cesium.com/?src=KML%20Tours.html|KML Tours}
   */
  function KmlTour(name, id) {
    /**
     * Id of kml gx:Tour entry
     * @type String
     */
    this.id = id;
    /**
     * Tour name
     * @type String
     */
    this.name = name;
    /**
     * Index of current entry from playlist
     * @type Number
     */
    this.playlistIndex = 0;
    /**
     * Array of playlist entries
     * @type Array
     */
    this.playlist = [];
    /**
     * Event will be called when tour starts to play,
     * before any playlist entry starts to play.
     * @type Event
     */
    this.tourStart = new Event();
    /**
     * Event will be called when all playlist entries are
     * played, or tour playback being canceled.
     *
     * If tour playback was terminated, event callback will
     * be called with terminated=true parameter.
     * @type Event
     */
    this.tourEnd = new Event();
    /**
     * Event will be called when entry from playlist starts to play.
     *
     * Event callback will be called with curent entry as first parameter.
     * @type Event
     */
    this.entryStart = new Event();
    /**
     * Event will be called when entry from playlist ends to play.
     *
     * Event callback will be called with following parameters:
     * 1. entry - entry
     * 2. terminated - true if playback was terminated by calling {@link KmlTour#stop}
     * @type Event
     */
    this.entryEnd = new Event();

    this._activeEntries = [];
  }

  /**
   * Add entry to this tour playlist.
   *
   * @param {KmlTourFlyTo|KmlTourWait} entry an entry to add to the playlist.
   */
  KmlTour.prototype.addPlaylistEntry = function (entry) {
    this.playlist.push(entry);
  };

  /**
   * Play this tour.
   *
   * @param {Viewer} viewer viewer widget.
   * @param {Object} [cameraOptions] these options will be merged with {@link Camera#flyTo}
   * options for FlyTo playlist entries.
   */
  KmlTour.prototype.play = function (viewer, cameraOptions) {
    this.tourStart.raiseEvent();

    const tour = this;
    playEntry.call(this, viewer, cameraOptions, function (terminated) {
      tour.playlistIndex = 0;
      // Stop nonblocking entries
      if (!terminated) {
        cancelAllEntries(tour._activeEntries);
      }
      tour.tourEnd.raiseEvent(terminated);
    });
  };

  /**
   * Stop curently playing tour.
   */
  KmlTour.prototype.stop = function () {
    cancelAllEntries(this._activeEntries);
  };

  // Stop all activeEntries.
  function cancelAllEntries(activeEntries) {
    for (
      let entry = activeEntries.pop();
      entry !== undefined;
      entry = activeEntries.pop()
    ) {
      entry.stop();
    }
  }

  // Play playlist entry.
  // This function is called recursevly with playNext and iterates over all entries from playlist.
  function playEntry(viewer, cameraOptions, allDone) {
    const entry = this.playlist[this.playlistIndex];
    if (entry) {
      const _playNext = playNext.bind(this, viewer, cameraOptions, allDone);
      this._activeEntries.push(entry);
      this.entryStart.raiseEvent(entry);
      if (entry.blocking) {
        entry.play(_playNext, viewer.scene.camera, cameraOptions);
      } else {
        const tour = this;
        entry.play(function () {
          tour.entryEnd.raiseEvent(entry);
          const indx = tour._activeEntries.indexOf(entry);
          if (indx >= 0) {
            tour._activeEntries.splice(indx, 1);
          }
        });
        _playNext(viewer, cameraOptions, allDone);
      }
    } else if (defined(allDone)) {
      allDone(false);
    }
  }

  // Increment playlistIndex and call playEntry if terminated isn't true.
  function playNext(viewer, cameraOptions, allDone, terminated) {
    const entry = this.playlist[this.playlistIndex];
    this.entryEnd.raiseEvent(entry, terminated);

    if (terminated) {
      allDone(terminated);
    } else {
      const indx = this._activeEntries.indexOf(entry);
      if (indx >= 0) {
        this._activeEntries.splice(indx, 1);
      }
      this.playlistIndex++;
      playEntry.call(this, viewer, cameraOptions, allDone);
    }
  }

  /**
   * Transitions the KmlTour to the next destination. This transition is facilitated
   * using a specified flyToMode over a given number of seconds.
   *
   * @alias KmlTourFlyTo
   * @constructor
   *
   * @param {Number} duration entry duration
   * @param {String} flyToMode KML fly to mode: bounce, smooth, etc
   * @param {KmlCamera|KmlLookAt} view KmlCamera or KmlLookAt
   *
   * @see KmlTour
   * @see KmlTourWait
   */
  function KmlTourFlyTo(duration, flyToMode, view) {
    this.type = "KmlTourFlyTo";
    this.blocking = true;
    this.activeCamera = null;
    this.activeCallback = null;

    this.duration = duration;
    this.view = view;
    this.flyToMode = flyToMode;
  }

  /**
   * Play this playlist entry
   *
   * @param {KmlTourFlyTo.DoneCallback} done function which will be called when playback ends
   * @param {Camera} camera Cesium camera
   * @param {Object} [cameraOptions] which will be merged with camera flyTo options. See {@link Camera#flyTo}
   */
  KmlTourFlyTo.prototype.play = function (done, camera, cameraOptions) {
    this.activeCamera = camera;
    if (defined(done) && done !== null) {
      const self = this;
      this.activeCallback = function (terminated) {
        delete self.activeCallback;
        delete self.activeCamera;
        done(defined(terminated) ? false : terminated);
      };
    }

    const options = this.getCameraOptions(cameraOptions);
    if (this.view.headingPitchRoll) {
      camera.flyTo(options);
    } else if (this.view.headingPitchRange) {
      const target = new BoundingSphere(this.view.position);
      camera.flyToBoundingSphere(target, options);
    }
  };

  /**
   * Stop execution of curent entry. Cancel camera flyTo
   */
  KmlTourFlyTo.prototype.stop = function () {
    if (defined(this.activeCamera)) {
      this.activeCamera.cancelFlight();
    }
    if (defined(this.activeCallback)) {
      this.activeCallback(true);
    }
  };

  /**
   * Returns options for {@link Camera#flyTo} or {@link Camera#flyToBoundingSphere}
   * depends on this.view type.
   *
   * @param {Object} cameraOptions options to merge with generated. See {@link Camera#flyTo}
   * @returns {Object} {@link Camera#flyTo} or {@link Camera#flyToBoundingSphere} options
   */
  KmlTourFlyTo.prototype.getCameraOptions = function (cameraOptions) {
    let options = {
      duration: this.duration,
    };

    if (defined(this.activeCallback)) {
      options.complete = this.activeCallback;
    }

    if (this.flyToMode === "smooth") {
      options.easingFunction = EasingFunction$1.LINEAR_NONE;
    }

    if (this.view.headingPitchRoll) {
      options.destination = this.view.position;
      options.orientation = this.view.headingPitchRoll;
    } else if (this.view.headingPitchRange) {
      options.offset = this.view.headingPitchRange;
    }

    if (defined(cameraOptions)) {
      options = combine$2(options, cameraOptions);
    }
    return options;
  };

  /**
   * Pauses the KmlTour for a given number of seconds.
   *
   * @alias KmlTourWait
   * @constructor
   *
   * @param {Number} duration entry duration
   *
   * @see KmlTour
   * @see KmlTourFlyTo
   */
  function KmlTourWait(duration) {
    this.type = "KmlTourWait";
    this.blocking = true;
    this.duration = duration;

    this.timeout = null;
  }

  /**
   * Play this playlist entry
   *
   * @param {KmlTourWait.DoneCallback} done function which will be called when playback ends
   */
  KmlTourWait.prototype.play = function (done) {
    const self = this;
    this.activeCallback = done;
    this.timeout = setTimeout(function () {
      delete self.activeCallback;
      done(false);
    }, this.duration * 1000);
  };

  /**
   * Stop execution of curent entry, cancel curent timeout
   */
  KmlTourWait.prototype.stop = function () {
    clearTimeout(this.timeout);
    if (defined(this.activeCallback)) {
      this.activeCallback(true);
    }
  };

  //This is by no means an exhaustive list of MIME types.
  //The purpose of this list is to be able to accurately identify content embedded
  //in KMZ files. Eventually, we can make this configurable by the end user so they can add
  //there own content types if they have KMZ files that require it.
  const MimeTypes = {
    avi: "video/x-msvideo",
    bmp: "image/bmp",
    bz2: "application/x-bzip2",
    chm: "application/vnd.ms-htmlhelp",
    css: "text/css",
    csv: "text/csv",
    doc: "application/msword",
    dvi: "application/x-dvi",
    eps: "application/postscript",
    flv: "video/x-flv",
    gif: "image/gif",
    gz: "application/x-gzip",
    htm: "text/html",
    html: "text/html",
    ico: "image/vnd.microsoft.icon",
    jnlp: "application/x-java-jnlp-file",
    jpeg: "image/jpeg",
    jpg: "image/jpeg",
    m3u: "audio/x-mpegurl",
    m4v: "video/mp4",
    mathml: "application/mathml+xml",
    mid: "audio/midi",
    midi: "audio/midi",
    mov: "video/quicktime",
    mp3: "audio/mpeg",
    mp4: "video/mp4",
    mp4v: "video/mp4",
    mpeg: "video/mpeg",
    mpg: "video/mpeg",
    odp: "application/vnd.oasis.opendocument.presentation",
    ods: "application/vnd.oasis.opendocument.spreadsheet",
    odt: "application/vnd.oasis.opendocument.text",
    ogg: "application/ogg",
    pdf: "application/pdf",
    png: "image/png",
    pps: "application/vnd.ms-powerpoint",
    ppt: "application/vnd.ms-powerpoint",
    ps: "application/postscript",
    qt: "video/quicktime",
    rdf: "application/rdf+xml",
    rss: "application/rss+xml",
    rtf: "application/rtf",
    svg: "image/svg+xml",
    swf: "application/x-shockwave-flash",
    text: "text/plain",
    tif: "image/tiff",
    tiff: "image/tiff",
    txt: "text/plain",
    wav: "audio/x-wav",
    wma: "audio/x-ms-wma",
    wmv: "video/x-ms-wmv",
    xml: "application/xml",
    zip: "application/zip",

    detectFromFilename: function (filename) {
      let ext = filename.toLowerCase();
      ext = getExtensionFromUri(ext);
      return MimeTypes[ext];
    },
  };

  let parser;
  if (typeof DOMParser !== "undefined") {
    parser = new DOMParser();
  }

  const autolinker = new Autolinker({
    stripPrefix: false,
    email: false,
    replaceFn: function (match) {
      if (!match.protocolUrlMatch) {
        //Prevent matching of non-explicit urls.
        //i.e. foo.id won't match but http://foo.id will
        return false;
      }
    },
  });

  const BILLBOARD_SIZE$1 = 32;

  const BILLBOARD_NEAR_DISTANCE = 2414016;
  const BILLBOARD_NEAR_RATIO = 1.0;
  const BILLBOARD_FAR_DISTANCE = 1.6093e7;
  const BILLBOARD_FAR_RATIO = 0.1;

  const kmlNamespaces = [
    null,
    undefined,
    "http://www.opengis.net/kml/2.2",
    "http://earth.google.com/kml/2.2",
    "http://earth.google.com/kml/2.1",
    "http://earth.google.com/kml/2.0",
  ];
  const gxNamespaces = ["http://www.google.com/kml/ext/2.2"];
  const atomNamespaces = ["http://www.w3.org/2005/Atom"];
  const namespaces = {
    kml: kmlNamespaces,
    gx: gxNamespaces,
    atom: atomNamespaces,
    kmlgx: kmlNamespaces.concat(gxNamespaces),
  };

  // Ensure Specs/Data/KML/unsupported.kml is kept up to date with these supported types
  const featureTypes = {
    Document: processDocument,
    Folder: processFolder,
    Placemark: processPlacemark,
    NetworkLink: processNetworkLink,
    GroundOverlay: processGroundOverlay,
    PhotoOverlay: processUnsupportedFeature,
    ScreenOverlay: processScreenOverlay,
    Tour: processTour,
  };

  function DeferredLoading(dataSource) {
    this._dataSource = dataSource;
    this._deferred = defer();
    this._stack = [];
    this._promises = [];
    this._timeoutSet = false;
    this._used = false;

    this._started = 0;
    this._timeThreshold = 1000; // Initial load is 1 second
  }

  Object.defineProperties(DeferredLoading.prototype, {
    dataSource: {
      get: function () {
        return this._dataSource;
      },
    },
  });

  DeferredLoading.prototype.addNodes = function (nodes, processingData) {
    this._stack.push({
      nodes: nodes,
      index: 0,
      processingData: processingData,
    });
    this._used = true;
  };

  DeferredLoading.prototype.addPromise = function (promise) {
    this._promises.push(promise);
  };

  DeferredLoading.prototype.wait = function () {
    // Case where we had a non-document/folder as the root
    const deferred = this._deferred;
    if (!this._used) {
      deferred.resolve();
    }

    return Promise.all([deferred.promise, Promise.all(this._promises)]);
  };

  DeferredLoading.prototype.process = function () {
    const isFirstCall = this._stack.length === 1;
    if (isFirstCall) {
      this._started = KmlDataSource._getTimestamp();
    }

    return this._process(isFirstCall);
  };

  DeferredLoading.prototype._giveUpTime = function () {
    if (this._timeoutSet) {
      // Timeout was already set so just return
      return;
    }

    this._timeoutSet = true;
    this._timeThreshold = 50; // After the first load lower threshold to 0.5 seconds
    const that = this;
    setTimeout(function () {
      that._timeoutSet = false;
      that._started = KmlDataSource._getTimestamp();
      that._process(true);
    }, 0);
  };

  DeferredLoading.prototype._nextNode = function () {
    const stack = this._stack;
    const top = stack[stack.length - 1];
    const index = top.index;
    const nodes = top.nodes;
    if (index === nodes.length) {
      return;
    }
    ++top.index;

    return nodes[index];
  };

  DeferredLoading.prototype._pop = function () {
    const stack = this._stack;
    stack.pop();

    // Return false if we are done
    if (stack.length === 0) {
      this._deferred.resolve();
      return false;
    }

    return true;
  };

  DeferredLoading.prototype._process = function (isFirstCall) {
    const dataSource = this.dataSource;
    const processingData = this._stack[this._stack.length - 1].processingData;

    let child = this._nextNode();
    while (defined(child)) {
      const featureProcessor = featureTypes[child.localName];
      if (
        defined(featureProcessor) &&
        (namespaces.kml.indexOf(child.namespaceURI) !== -1 ||
          namespaces.gx.indexOf(child.namespaceURI) !== -1)
      ) {
        featureProcessor(dataSource, child, processingData, this);

        // Give up time and continue loading later
        if (
          this._timeoutSet ||
          KmlDataSource._getTimestamp() > this._started + this._timeThreshold
        ) {
          this._giveUpTime();
          return;
        }
      }

      child = this._nextNode();
    }

    // If we are a recursive call from a subfolder, just return so the parent folder can continue processing
    // If we aren't then make another call to processNodes because there is stuff still left in the queue
    if (this._pop() && isFirstCall) {
      this._process(true);
    }
  };

  function isZipFile(blob) {
    const magicBlob = blob.slice(0, Math.min(4, blob.size));
    const deferred = defer();
    const reader = new FileReader();
    reader.addEventListener("load", function () {
      deferred.resolve(
        new DataView(reader.result).getUint32(0, false) === 0x504b0304
      );
    });
    reader.addEventListener("error", function () {
      deferred.reject(reader.error);
    });
    reader.readAsArrayBuffer(magicBlob);
    return deferred.promise;
  }

  function readBlobAsText(blob) {
    const deferred = defer();
    const reader = new FileReader();
    reader.addEventListener("load", function () {
      deferred.resolve(reader.result);
    });
    reader.addEventListener("error", function () {
      deferred.reject(reader.error);
    });
    reader.readAsText(blob);
    return deferred.promise;
  }

  function insertNamespaces(text) {
    const namespaceMap = {
      xsi: "http://www.w3.org/2001/XMLSchema-instance",
    };
    let firstPart, lastPart, reg, declaration;

    for (const key in namespaceMap) {
      if (namespaceMap.hasOwnProperty(key)) {
        reg = RegExp(`[< ]${key}:`);
        declaration = `xmlns:${key}=`;
        if (reg.test(text) && text.indexOf(declaration) === -1) {
          if (!defined(firstPart)) {
            firstPart = text.substr(0, text.indexOf("<kml") + 4);
            lastPart = text.substr(firstPart.length);
          }
          firstPart += ` ${declaration}"${namespaceMap[key]}"`;
        }
      }
    }

    if (defined(firstPart)) {
      text = firstPart + lastPart;
    }

    return text;
  }

  function removeDuplicateNamespaces(text) {
    let index = text.indexOf("xmlns:");
    const endDeclaration = text.indexOf(">", index);
    let namespace, startIndex, endIndex;

    while (index !== -1 && index < endDeclaration) {
      namespace = text.slice(index, text.indexOf('"', index));
      startIndex = index;
      index = text.indexOf(namespace, index + 1);
      if (index !== -1) {
        endIndex = text.indexOf('"', text.indexOf('"', index) + 1);
        text = text.slice(0, index - 1) + text.slice(endIndex + 1, text.length);
        index = text.indexOf("xmlns:", startIndex - 1);
      } else {
        index = text.indexOf("xmlns:", startIndex + 1);
      }
    }

    return text;
  }

  function loadXmlFromZip(entry, uriResolver) {
    return Promise.resolve(entry.getData(new zipNoWorker.TextWriter())).then(function (
      text
    ) {
      text = insertNamespaces(text);
      text = removeDuplicateNamespaces(text);
      uriResolver.kml = parser.parseFromString(text, "application/xml");
    });
  }

  function loadDataUriFromZip(entry, uriResolver) {
    const mimeType = defaultValue(
      MimeTypes.detectFromFilename(entry.filename),
      "application/octet-stream"
    );
    return Promise.resolve(entry.getData(new zipNoWorker.Data64URIWriter(mimeType))).then(
      function (dataUri) {
        uriResolver[entry.filename] = dataUri;
      }
    );
  }

  function embedDataUris(div, elementType, attributeName, uriResolver) {
    const keys = uriResolver.keys;
    const baseUri = new URI(".");
    const elements = div.querySelectorAll(elementType);
    for (let i = 0; i < elements.length; i++) {
      const element = elements[i];
      const value = element.getAttribute(attributeName);
      const relativeUri = new URI(value);
      const uri = relativeUri.absoluteTo(baseUri).toString();
      const index = keys.indexOf(uri);
      if (index !== -1) {
        const key = keys[index];
        element.setAttribute(attributeName, uriResolver[key]);
        if (elementType === "a" && element.getAttribute("download") === null) {
          element.setAttribute("download", key);
        }
      }
    }
  }

  function applyBasePath(div, elementType, attributeName, sourceResource) {
    const elements = div.querySelectorAll(elementType);
    for (let i = 0; i < elements.length; i++) {
      const element = elements[i];
      const value = element.getAttribute(attributeName);
      const resource = resolveHref(value, sourceResource);
      element.setAttribute(attributeName, resource.url);
    }
  }

  // an optional context is passed to allow for some malformed kmls (those with multiple geometries with same ids) to still parse
  // correctly, as they do in Google Earth.
  function createEntity(node, entityCollection, context) {
    let id = queryStringAttribute(node, "id");
    id = defined(id) && id.length !== 0 ? id : createGuid();
    if (defined(context)) {
      id = context + id;
    }

    // If we have a duplicate ID just generate one.
    // This isn't valid KML but Google Earth handles this case.
    let entity = entityCollection.getById(id);
    if (defined(entity)) {
      id = createGuid();
      if (defined(context)) {
        id = context + id;
      }
    }

    entity = entityCollection.add(new Entity({ id: id }));
    if (!defined(entity.kml)) {
      entity.addProperty("kml");
      entity.kml = new KmlFeatureData();
    }
    return entity;
  }

  function isExtrudable(altitudeMode, gxAltitudeMode) {
    return (
      altitudeMode === "absolute" ||
      altitudeMode === "relativeToGround" ||
      gxAltitudeMode === "relativeToSeaFloor"
    );
  }

  function readCoordinate(value, ellipsoid) {
    //Google Earth treats empty or missing coordinates as 0.
    if (!defined(value)) {
      return Cartesian3.fromDegrees(0, 0, 0, ellipsoid);
    }

    const digits = value.match(/[^\s,\n]+/g);
    if (!defined(digits)) {
      return Cartesian3.fromDegrees(0, 0, 0, ellipsoid);
    }

    let longitude = parseFloat(digits[0]);
    let latitude = parseFloat(digits[1]);
    let height = parseFloat(digits[2]);

    longitude = isNaN(longitude) ? 0.0 : longitude;
    latitude = isNaN(latitude) ? 0.0 : latitude;
    height = isNaN(height) ? 0.0 : height;

    return Cartesian3.fromDegrees(longitude, latitude, height, ellipsoid);
  }

  function readCoordinates(element, ellipsoid) {
    if (!defined(element)) {
      return undefined;
    }

    const tuples = element.textContent.match(/[^\s\n]+/g);
    if (!defined(tuples)) {
      return undefined;
    }

    const length = tuples.length;
    const result = new Array(length);
    let resultIndex = 0;
    for (let i = 0; i < length; i++) {
      result[resultIndex++] = readCoordinate(tuples[i], ellipsoid);
    }
    return result;
  }

  function queryNumericAttribute(node, attributeName) {
    if (!defined(node)) {
      return undefined;
    }

    const value = node.getAttribute(attributeName);
    if (value !== null) {
      const result = parseFloat(value);
      return !isNaN(result) ? result : undefined;
    }
    return undefined;
  }

  function queryStringAttribute(node, attributeName) {
    if (!defined(node)) {
      return undefined;
    }
    const value = node.getAttribute(attributeName);
    return value !== null ? value : undefined;
  }

  function queryFirstNode(node, tagName, namespace) {
    if (!defined(node)) {
      return undefined;
    }
    const childNodes = node.childNodes;
    const length = childNodes.length;
    for (let q = 0; q < length; q++) {
      const child = childNodes[q];
      if (
        child.localName === tagName &&
        namespace.indexOf(child.namespaceURI) !== -1
      ) {
        return child;
      }
    }
    return undefined;
  }

  function queryNodes(node, tagName, namespace) {
    if (!defined(node)) {
      return undefined;
    }
    const result = [];
    const childNodes = node.getElementsByTagNameNS("*", tagName);
    const length = childNodes.length;
    for (let q = 0; q < length; q++) {
      const child = childNodes[q];
      if (
        child.localName === tagName &&
        namespace.indexOf(child.namespaceURI) !== -1
      ) {
        result.push(child);
      }
    }
    return result;
  }

  function queryChildNodes(node, tagName, namespace) {
    if (!defined(node)) {
      return [];
    }
    const result = [];
    const childNodes = node.childNodes;
    const length = childNodes.length;
    for (let q = 0; q < length; q++) {
      const child = childNodes[q];
      if (
        child.localName === tagName &&
        namespace.indexOf(child.namespaceURI) !== -1
      ) {
        result.push(child);
      }
    }
    return result;
  }

  function queryNumericValue(node, tagName, namespace) {
    const resultNode = queryFirstNode(node, tagName, namespace);
    if (defined(resultNode)) {
      const result = parseFloat(resultNode.textContent);
      return !isNaN(result) ? result : undefined;
    }
    return undefined;
  }

  function queryStringValue(node, tagName, namespace) {
    const result = queryFirstNode(node, tagName, namespace);
    if (defined(result)) {
      return result.textContent.trim();
    }
    return undefined;
  }

  function queryBooleanValue(node, tagName, namespace) {
    const result = queryFirstNode(node, tagName, namespace);
    if (defined(result)) {
      const value = result.textContent.trim();
      return value === "1" || /^true$/i.test(value);
    }
    return undefined;
  }

  function resolveHref(href, sourceResource, uriResolver) {
    if (!defined(href)) {
      return undefined;
    }

    let resource;
    if (defined(uriResolver)) {
      // To resolve issues with KML sources defined in Windows style paths.
      href = href.replace(/\\/g, "/");
      let blob = uriResolver[href];
      if (defined(blob)) {
        resource = new Resource({
          url: blob,
        });
      } else {
        // Needed for multiple levels of KML files in a KMZ
        const baseUri = new URI(sourceResource.getUrlComponent());
        const uri = new URI(href);
        blob = uriResolver[uri.absoluteTo(baseUri)];
        if (defined(blob)) {
          resource = new Resource({
            url: blob,
          });
        }
      }
    }

    if (!defined(resource)) {
      resource = sourceResource.getDerivedResource({
        url: href,
      });
    }

    return resource;
  }

  const colorOptions = {
    maximumRed: undefined,
    red: undefined,
    maximumGreen: undefined,
    green: undefined,
    maximumBlue: undefined,
    blue: undefined,
  };

  function parseColorString(value, isRandom) {
    if (!defined(value) || /^\s*$/gm.test(value)) {
      return undefined;
    }

    if (value[0] === "#") {
      value = value.substring(1);
    }

    const alpha = parseInt(value.substring(0, 2), 16) / 255.0;
    const blue = parseInt(value.substring(2, 4), 16) / 255.0;
    const green = parseInt(value.substring(4, 6), 16) / 255.0;
    const red = parseInt(value.substring(6, 8), 16) / 255.0;

    if (!isRandom) {
      return new Color(red, green, blue, alpha);
    }

    if (red > 0) {
      colorOptions.maximumRed = red;
      colorOptions.red = undefined;
    } else {
      colorOptions.maximumRed = undefined;
      colorOptions.red = 0;
    }
    if (green > 0) {
      colorOptions.maximumGreen = green;
      colorOptions.green = undefined;
    } else {
      colorOptions.maximumGreen = undefined;
      colorOptions.green = 0;
    }
    if (blue > 0) {
      colorOptions.maximumBlue = blue;
      colorOptions.blue = undefined;
    } else {
      colorOptions.maximumBlue = undefined;
      colorOptions.blue = 0;
    }
    colorOptions.alpha = alpha;
    return Color.fromRandom(colorOptions);
  }

  function queryColorValue(node, tagName, namespace) {
    const value = queryStringValue(node, tagName, namespace);
    if (!defined(value)) {
      return undefined;
    }
    return parseColorString(
      value,
      queryStringValue(node, "colorMode", namespace) === "random"
    );
  }

  function processTimeStamp(featureNode) {
    const node = queryFirstNode(featureNode, "TimeStamp", namespaces.kmlgx);
    const whenString = queryStringValue(node, "when", namespaces.kmlgx);

    if (!defined(node) || !defined(whenString) || whenString.length === 0) {
      return undefined;
    }

    //According to the KML spec, a TimeStamp represents a "single moment in time"
    //However, since Cesium animates much differently than Google Earth, that doesn't
    //Make much sense here.  Instead, we use the TimeStamp as the moment the feature
    //comes into existence.  This works much better and gives a similar feel to
    //GE's experience.
    const when = JulianDate.fromIso8601(whenString);
    const result = new TimeIntervalCollection();
    result.addInterval(
      new TimeInterval({
        start: when,
        stop: Iso8601.MAXIMUM_VALUE,
      })
    );
    return result;
  }

  function processTimeSpan(featureNode) {
    const node = queryFirstNode(featureNode, "TimeSpan", namespaces.kmlgx);
    if (!defined(node)) {
      return undefined;
    }
    let result;

    const beginNode = queryFirstNode(node, "begin", namespaces.kmlgx);
    let beginDate = defined(beginNode)
      ? JulianDate.fromIso8601(beginNode.textContent)
      : undefined;

    const endNode = queryFirstNode(node, "end", namespaces.kmlgx);
    let endDate = defined(endNode)
      ? JulianDate.fromIso8601(endNode.textContent)
      : undefined;

    if (defined(beginDate) && defined(endDate)) {
      if (JulianDate.lessThan(endDate, beginDate)) {
        const tmp = beginDate;
        beginDate = endDate;
        endDate = tmp;
      }
      result = new TimeIntervalCollection();
      result.addInterval(
        new TimeInterval({
          start: beginDate,
          stop: endDate,
        })
      );
    } else if (defined(beginDate)) {
      result = new TimeIntervalCollection();
      result.addInterval(
        new TimeInterval({
          start: beginDate,
          stop: Iso8601.MAXIMUM_VALUE,
        })
      );
    } else if (defined(endDate)) {
      result = new TimeIntervalCollection();
      result.addInterval(
        new TimeInterval({
          start: Iso8601.MINIMUM_VALUE,
          stop: endDate,
        })
      );
    }

    return result;
  }

  function createDefaultBillboard() {
    const billboard = new BillboardGraphics();
    billboard.width = BILLBOARD_SIZE$1;
    billboard.height = BILLBOARD_SIZE$1;
    billboard.scaleByDistance = new NearFarScalar(
      BILLBOARD_NEAR_DISTANCE,
      BILLBOARD_NEAR_RATIO,
      BILLBOARD_FAR_DISTANCE,
      BILLBOARD_FAR_RATIO
    );
    billboard.pixelOffsetScaleByDistance = new NearFarScalar(
      BILLBOARD_NEAR_DISTANCE,
      BILLBOARD_NEAR_RATIO,
      BILLBOARD_FAR_DISTANCE,
      BILLBOARD_FAR_RATIO
    );
    return billboard;
  }

  function createDefaultPolygon() {
    const polygon = new PolygonGraphics();
    polygon.outline = true;
    polygon.outlineColor = Color.WHITE;
    return polygon;
  }

  function createDefaultLabel() {
    const label = new LabelGraphics();
    label.translucencyByDistance = new NearFarScalar(3000000, 1.0, 5000000, 0.0);
    label.pixelOffset = new Cartesian2(17, 0);
    label.horizontalOrigin = HorizontalOrigin$1.LEFT;
    label.font = "16px sans-serif";
    label.style = LabelStyle$1.FILL_AND_OUTLINE;
    return label;
  }

  function getIconHref(
    iconNode,
    dataSource,
    sourceResource,
    uriResolver,
    canRefresh
  ) {
    let href = queryStringValue(iconNode, "href", namespaces.kml);
    if (!defined(href) || href.length === 0) {
      return undefined;
    }

    if (href.indexOf("root://icons/palette-") === 0) {
      const palette = href.charAt(21);

      // Get the icon number
      let x = defaultValue(queryNumericValue(iconNode, "x", namespaces.gx), 0);
      let y = defaultValue(queryNumericValue(iconNode, "y", namespaces.gx), 0);
      x = Math.min(x / 32, 7);
      y = 7 - Math.min(y / 32, 7);
      const iconNum = 8 * y + x;

      href = `https://maps.google.com/mapfiles/kml/pal${palette}/icon${iconNum}.png`;
    }

    const hrefResource = resolveHref(href, sourceResource, uriResolver);

    if (canRefresh) {
      const refreshMode = queryStringValue(
        iconNode,
        "refreshMode",
        namespaces.kml
      );
      const viewRefreshMode = queryStringValue(
        iconNode,
        "viewRefreshMode",
        namespaces.kml
      );
      if (refreshMode === "onInterval" || refreshMode === "onExpire") {
        oneTimeWarning(
          `kml-refreshMode-${refreshMode}`,
          `KML - Unsupported Icon refreshMode: ${refreshMode}`
        );
      } else if (viewRefreshMode === "onStop" || viewRefreshMode === "onRegion") {
        oneTimeWarning(
          `kml-refreshMode-${viewRefreshMode}`,
          `KML - Unsupported Icon viewRefreshMode: ${viewRefreshMode}`
        );
      }

      const viewBoundScale = defaultValue(
        queryStringValue(iconNode, "viewBoundScale", namespaces.kml),
        1.0
      );
      const defaultViewFormat =
        viewRefreshMode === "onStop"
          ? "BBOX=[bboxWest],[bboxSouth],[bboxEast],[bboxNorth]"
          : "";
      const viewFormat = defaultValue(
        queryStringValue(iconNode, "viewFormat", namespaces.kml),
        defaultViewFormat
      );
      const httpQuery = queryStringValue(iconNode, "httpQuery", namespaces.kml);
      if (defined(viewFormat)) {
        hrefResource.setQueryParameters(queryToObject(cleanupString(viewFormat)));
      }
      if (defined(httpQuery)) {
        hrefResource.setQueryParameters(queryToObject(cleanupString(httpQuery)));
      }

      const ellipsoid = dataSource._ellipsoid;
      processNetworkLinkQueryString(
        hrefResource,
        dataSource.camera,
        dataSource.canvas,
        viewBoundScale,
        dataSource._lastCameraView.bbox,
        ellipsoid
      );

      return hrefResource;
    }

    return hrefResource;
  }

  function processBillboardIcon(
    dataSource,
    node,
    targetEntity,
    sourceResource,
    uriResolver
  ) {
    let scale = queryNumericValue(node, "scale", namespaces.kml);
    const heading = queryNumericValue(node, "heading", namespaces.kml);
    const color = queryColorValue(node, "color", namespaces.kml);

    const iconNode = queryFirstNode(node, "Icon", namespaces.kml);
    let icon = getIconHref(
      iconNode,
      dataSource,
      sourceResource,
      uriResolver,
      false
    );

    // If icon tags are present but blank, we do not want to show an icon
    if (defined(iconNode) && !defined(icon)) {
      icon = false;
    }

    const x = queryNumericValue(iconNode, "x", namespaces.gx);
    const y = queryNumericValue(iconNode, "y", namespaces.gx);
    const w = queryNumericValue(iconNode, "w", namespaces.gx);
    const h = queryNumericValue(iconNode, "h", namespaces.gx);

    const hotSpotNode = queryFirstNode(node, "hotSpot", namespaces.kml);
    const hotSpotX = queryNumericAttribute(hotSpotNode, "x");
    const hotSpotY = queryNumericAttribute(hotSpotNode, "y");
    const hotSpotXUnit = queryStringAttribute(hotSpotNode, "xunits");
    const hotSpotYUnit = queryStringAttribute(hotSpotNode, "yunits");

    let billboard = targetEntity.billboard;
    if (!defined(billboard)) {
      billboard = createDefaultBillboard();
      targetEntity.billboard = billboard;
    }

    billboard.image = icon;
    billboard.scale = scale;
    billboard.color = color;

    if (defined(x) || defined(y) || defined(w) || defined(h)) {
      billboard.imageSubRegion = new BoundingRectangle(x, y, w, h);
    }

    //GE treats a heading of zero as no heading
    //You can still point north using a 360 degree angle (or any multiple of 360)
    if (defined(heading) && heading !== 0) {
      billboard.rotation = CesiumMath.toRadians(-heading);
      billboard.alignedAxis = Cartesian3.UNIT_Z;
    }

    //Hotpot is the KML equivalent of pixel offset
    //The hotspot origin is the lower left, but we leave
    //our billboard origin at the center and simply
    //modify the pixel offset to take this into account
    scale = defaultValue(scale, 1.0);

    let xOffset;
    let yOffset;
    if (defined(hotSpotX)) {
      if (hotSpotXUnit === "pixels") {
        xOffset = -hotSpotX * scale;
      } else if (hotSpotXUnit === "insetPixels") {
        xOffset = (hotSpotX - BILLBOARD_SIZE$1) * scale;
      } else if (hotSpotXUnit === "fraction") {
        xOffset = -hotSpotX * BILLBOARD_SIZE$1 * scale;
      }
      xOffset += BILLBOARD_SIZE$1 * 0.5 * scale;
    }

    if (defined(hotSpotY)) {
      if (hotSpotYUnit === "pixels") {
        yOffset = hotSpotY * scale;
      } else if (hotSpotYUnit === "insetPixels") {
        yOffset = (-hotSpotY + BILLBOARD_SIZE$1) * scale;
      } else if (hotSpotYUnit === "fraction") {
        yOffset = hotSpotY * BILLBOARD_SIZE$1 * scale;
      }

      yOffset -= BILLBOARD_SIZE$1 * 0.5 * scale;
    }

    if (defined(xOffset) || defined(yOffset)) {
      billboard.pixelOffset = new Cartesian2(xOffset, yOffset);
    }
  }

  function applyStyle(
    dataSource,
    styleNode,
    targetEntity,
    sourceResource,
    uriResolver
  ) {
    for (let i = 0, len = styleNode.childNodes.length; i < len; i++) {
      const node = styleNode.childNodes.item(i);
      if (node.localName === "IconStyle") {
        processBillboardIcon(
          dataSource,
          node,
          targetEntity,
          sourceResource,
          uriResolver
        );
      } else if (node.localName === "LabelStyle") {
        let label = targetEntity.label;
        if (!defined(label)) {
          label = createDefaultLabel();
          targetEntity.label = label;
        }
        label.scale = defaultValue(
          queryNumericValue(node, "scale", namespaces.kml),
          label.scale
        );
        label.fillColor = defaultValue(
          queryColorValue(node, "color", namespaces.kml),
          label.fillColor
        );
        label.text = targetEntity.name;
      } else if (node.localName === "LineStyle") {
        let polyline = targetEntity.polyline;
        if (!defined(polyline)) {
          polyline = new PolylineGraphics();
          targetEntity.polyline = polyline;
        }
        polyline.width = queryNumericValue(node, "width", namespaces.kml);
        polyline.material = queryColorValue(node, "color", namespaces.kml);
        if (defined(queryColorValue(node, "outerColor", namespaces.gx))) {
          oneTimeWarning(
            "kml-gx:outerColor",
            "KML - gx:outerColor is not supported in a LineStyle"
          );
        }
        if (defined(queryNumericValue(node, "outerWidth", namespaces.gx))) {
          oneTimeWarning(
            "kml-gx:outerWidth",
            "KML - gx:outerWidth is not supported in a LineStyle"
          );
        }
        if (defined(queryNumericValue(node, "physicalWidth", namespaces.gx))) {
          oneTimeWarning(
            "kml-gx:physicalWidth",
            "KML - gx:physicalWidth is not supported in a LineStyle"
          );
        }
        if (defined(queryBooleanValue(node, "labelVisibility", namespaces.gx))) {
          oneTimeWarning(
            "kml-gx:labelVisibility",
            "KML - gx:labelVisibility is not supported in a LineStyle"
          );
        }
      } else if (node.localName === "PolyStyle") {
        let polygon = targetEntity.polygon;
        if (!defined(polygon)) {
          polygon = createDefaultPolygon();
          targetEntity.polygon = polygon;
        }
        polygon.material = defaultValue(
          queryColorValue(node, "color", namespaces.kml),
          polygon.material
        );
        polygon.fill = defaultValue(
          queryBooleanValue(node, "fill", namespaces.kml),
          polygon.fill
        );
        polygon.outline = defaultValue(
          queryBooleanValue(node, "outline", namespaces.kml),
          polygon.outline
        );
      } else if (node.localName === "BalloonStyle") {
        const bgColor = defaultValue(
          parseColorString(queryStringValue(node, "bgColor", namespaces.kml)),
          Color.WHITE
        );
        const textColor = defaultValue(
          parseColorString(queryStringValue(node, "textColor", namespaces.kml)),
          Color.BLACK
        );
        const text = queryStringValue(node, "text", namespaces.kml);

        //This is purely an internal property used in style processing,
        //it never ends up on the final entity.
        targetEntity.addProperty("balloonStyle");
        targetEntity.balloonStyle = {
          bgColor: bgColor,
          textColor: textColor,
          text: text,
        };
      } else if (node.localName === "ListStyle") {
        const listItemType = queryStringValue(
          node,
          "listItemType",
          namespaces.kml
        );
        if (listItemType === "radioFolder" || listItemType === "checkOffOnly") {
          oneTimeWarning(
            `kml-listStyle-${listItemType}`,
            `KML - Unsupported ListStyle with listItemType: ${listItemType}`
          );
        }
      }
    }
  }

  //Processes and merges any inline styles for the provided node into the provided entity.
  function computeFinalStyle(
    dataSource,
    placeMark,
    styleCollection,
    sourceResource,
    uriResolver
  ) {
    const result = new Entity();
    let styleEntity;

    //Google earth seems to always use the last inline Style/StyleMap only
    let styleIndex = -1;
    const childNodes = placeMark.childNodes;
    const length = childNodes.length;
    for (let q = 0; q < length; q++) {
      const child = childNodes[q];
      if (child.localName === "Style" || child.localName === "StyleMap") {
        styleIndex = q;
      }
    }

    if (styleIndex !== -1) {
      const inlineStyleNode = childNodes[styleIndex];
      if (inlineStyleNode.localName === "Style") {
        applyStyle(
          dataSource,
          inlineStyleNode,
          result,
          sourceResource,
          uriResolver
        );
      } else {
        // StyleMap
        const pairs = queryChildNodes(inlineStyleNode, "Pair", namespaces.kml);
        for (let p = 0; p < pairs.length; p++) {
          const pair = pairs[p];
          const key = queryStringValue(pair, "key", namespaces.kml);
          if (key === "normal") {
            const styleUrl = queryStringValue(pair, "styleUrl", namespaces.kml);
            if (defined(styleUrl)) {
              styleEntity = styleCollection.getById(styleUrl);
              if (!defined(styleEntity)) {
                styleEntity = styleCollection.getById(`#${styleUrl}`);
              }
              if (defined(styleEntity)) {
                result.merge(styleEntity);
              }
            } else {
              const node = queryFirstNode(pair, "Style", namespaces.kml);
              applyStyle(dataSource, node, result, sourceResource, uriResolver);
            }
          } else {
            oneTimeWarning(
              `kml-styleMap-${key}`,
              `KML - Unsupported StyleMap key: ${key}`
            );
          }
        }
      }
    }

    //Google earth seems to always use the first external style only.
    const externalStyle = queryStringValue(placeMark, "styleUrl", namespaces.kml);
    if (defined(externalStyle)) {
      let id = externalStyle;
      if (externalStyle[0] !== "#" && externalStyle.indexOf("#") !== -1) {
        const tokens = externalStyle.split("#");
        const uri = tokens[0];
        const resource = sourceResource.getDerivedResource({
          url: uri,
        });

        id = `${resource.getUrlComponent()}#${tokens[1]}`;
      }

      styleEntity = styleCollection.getById(id);
      if (!defined(styleEntity)) {
        styleEntity = styleCollection.getById(`#${id}`);
      }
      if (defined(styleEntity)) {
        result.merge(styleEntity);
      }
    }

    return result;
  }

  //Asynchronously processes an external style file.
  function processExternalStyles(dataSource, resource, styleCollection) {
    return resource.fetchXML().then(function (styleKml) {
      return processStyles(dataSource, styleKml, styleCollection, resource, true);
    });
  }

  //Processes all shared and external styles and stores
  //their id into the provided styleCollection.
  //Returns an array of promises that will resolve when
  //each style is loaded.
  function processStyles(
    dataSource,
    kml,
    styleCollection,
    sourceResource,
    isExternal,
    uriResolver
  ) {
    let i;
    let id;
    let styleEntity;

    let node;
    const styleNodes = queryNodes(kml, "Style", namespaces.kml);
    if (defined(styleNodes)) {
      const styleNodesLength = styleNodes.length;
      for (i = 0; i < styleNodesLength; i++) {
        node = styleNodes[i];
        id = queryStringAttribute(node, "id");
        if (defined(id)) {
          id = `#${id}`;
          if (isExternal && defined(sourceResource)) {
            id = sourceResource.getUrlComponent() + id;
          }
          if (!defined(styleCollection.getById(id))) {
            styleEntity = new Entity({
              id: id,
            });
            styleCollection.add(styleEntity);
            applyStyle(
              dataSource,
              node,
              styleEntity,
              sourceResource,
              uriResolver
            );
          }
        }
      }
    }

    const styleMaps = queryNodes(kml, "StyleMap", namespaces.kml);
    if (defined(styleMaps)) {
      const styleMapsLength = styleMaps.length;
      for (i = 0; i < styleMapsLength; i++) {
        const styleMap = styleMaps[i];
        id = queryStringAttribute(styleMap, "id");
        if (defined(id)) {
          const pairs = queryChildNodes(styleMap, "Pair", namespaces.kml);
          for (let p = 0; p < pairs.length; p++) {
            const pair = pairs[p];
            const key = queryStringValue(pair, "key", namespaces.kml);
            if (key === "normal") {
              id = `#${id}`;
              if (isExternal && defined(sourceResource)) {
                id = sourceResource.getUrlComponent() + id;
              }
              if (!defined(styleCollection.getById(id))) {
                styleEntity = styleCollection.getOrCreateEntity(id);

                let styleUrl = queryStringValue(pair, "styleUrl", namespaces.kml);
                if (defined(styleUrl)) {
                  if (styleUrl[0] !== "#") {
                    styleUrl = `#${styleUrl}`;
                  }

                  if (isExternal && defined(sourceResource)) {
                    styleUrl = sourceResource.getUrlComponent() + styleUrl;
                  }
                  const base = styleCollection.getById(styleUrl);

                  if (defined(base)) {
                    styleEntity.merge(base);
                  }
                } else {
                  node = queryFirstNode(pair, "Style", namespaces.kml);
                  applyStyle(
                    dataSource,
                    node,
                    styleEntity,
                    sourceResource,
                    uriResolver
                  );
                }
              }
            } else {
              oneTimeWarning(
                `kml-styleMap-${key}`,
                `KML - Unsupported StyleMap key: ${key}`
              );
            }
          }
        }
      }
    }

    const promises = [];
    const styleUrlNodes = kml.getElementsByTagName("styleUrl");
    const styleUrlNodesLength = styleUrlNodes.length;
    for (i = 0; i < styleUrlNodesLength; i++) {
      const styleReference = styleUrlNodes[i].textContent;
      if (styleReference[0] !== "#") {
        //According to the spec, all local styles should start with a #
        //and everything else is an external style that has a # seperating
        //the URL of the document and the style.  However, Google Earth
        //also accepts styleUrls without a # as meaning a local style.
        const tokens = styleReference.split("#");
        if (tokens.length === 2) {
          const uri = tokens[0];
          const resource = sourceResource.getDerivedResource({
            url: uri,
          });

          promises.push(
            processExternalStyles(dataSource, resource, styleCollection)
          );
        }
      }
    }

    return promises;
  }

  function createDropLine(entityCollection, entity, styleEntity) {
    const entityPosition = new ReferenceProperty(entityCollection, entity.id, [
      "position",
    ]);
    const surfacePosition = new ScaledPositionProperty(entity.position);
    entity.polyline = defined(styleEntity.polyline)
      ? styleEntity.polyline.clone()
      : new PolylineGraphics();
    entity.polyline.positions = new PositionPropertyArray([
      entityPosition,
      surfacePosition,
    ]);
  }

  function heightReferenceFromAltitudeMode(altitudeMode, gxAltitudeMode) {
    if (
      (!defined(altitudeMode) && !defined(gxAltitudeMode)) ||
      altitudeMode === "clampToGround"
    ) {
      return HeightReference$1.CLAMP_TO_GROUND;
    }

    if (altitudeMode === "relativeToGround") {
      return HeightReference$1.RELATIVE_TO_GROUND;
    }

    if (altitudeMode === "absolute") {
      return HeightReference$1.NONE;
    }

    if (gxAltitudeMode === "clampToSeaFloor") {
      oneTimeWarning(
        "kml-gx:altitudeMode-clampToSeaFloor",
        "KML - <gx:altitudeMode>:clampToSeaFloor is currently not supported, using <kml:altitudeMode>:clampToGround."
      );
      return HeightReference$1.CLAMP_TO_GROUND;
    }

    if (gxAltitudeMode === "relativeToSeaFloor") {
      oneTimeWarning(
        "kml-gx:altitudeMode-relativeToSeaFloor",
        "KML - <gx:altitudeMode>:relativeToSeaFloor is currently not supported, using <kml:altitudeMode>:relativeToGround."
      );
      return HeightReference$1.RELATIVE_TO_GROUND;
    }

    if (defined(altitudeMode)) {
      oneTimeWarning(
        "kml-altitudeMode-unknown",
        `KML - Unknown <kml:altitudeMode>:${altitudeMode}, using <kml:altitudeMode>:CLAMP_TO_GROUND.`
      );
    } else {
      oneTimeWarning(
        "kml-gx:altitudeMode-unknown",
        `KML - Unknown <gx:altitudeMode>:${gxAltitudeMode}, using <kml:altitudeMode>:CLAMP_TO_GROUND.`
      );
    }

    // Clamp to ground is the default
    return HeightReference$1.CLAMP_TO_GROUND;
  }

  function createPositionPropertyFromAltitudeMode(
    property,
    altitudeMode,
    gxAltitudeMode
  ) {
    if (
      gxAltitudeMode === "relativeToSeaFloor" ||
      altitudeMode === "absolute" ||
      altitudeMode === "relativeToGround"
    ) {
      //Just return the ellipsoid referenced property until we support MSL
      return property;
    }

    if (
      (defined(altitudeMode) && altitudeMode !== "clampToGround") || //
      (defined(gxAltitudeMode) && gxAltitudeMode !== "clampToSeaFloor")
    ) {
      oneTimeWarning(
        "kml-altitudeMode-unknown",
        `KML - Unknown altitudeMode: ${defaultValue(
        altitudeMode,
        gxAltitudeMode
      )}`
      );
    }

    // Clamp to ground is the default
    return new ScaledPositionProperty(property);
  }

  function createPositionPropertyArrayFromAltitudeMode(
    properties,
    altitudeMode,
    gxAltitudeMode,
    ellipsoid
  ) {
    if (!defined(properties)) {
      return undefined;
    }

    if (
      gxAltitudeMode === "relativeToSeaFloor" ||
      altitudeMode === "absolute" ||
      altitudeMode === "relativeToGround"
    ) {
      //Just return the ellipsoid referenced property until we support MSL
      return properties;
    }

    if (
      (defined(altitudeMode) && altitudeMode !== "clampToGround") || //
      (defined(gxAltitudeMode) && gxAltitudeMode !== "clampToSeaFloor")
    ) {
      oneTimeWarning(
        "kml-altitudeMode-unknown",
        `KML - Unknown altitudeMode: ${defaultValue(
        altitudeMode,
        gxAltitudeMode
      )}`
      );
    }

    // Clamp to ground is the default
    const propertiesLength = properties.length;
    for (let i = 0; i < propertiesLength; i++) {
      const property = properties[i];
      ellipsoid.scaleToGeodeticSurface(property, property);
    }
    return properties;
  }

  function processPositionGraphics(
    dataSource,
    entity,
    styleEntity,
    heightReference
  ) {
    let label = entity.label;
    if (!defined(label)) {
      label = defined(styleEntity.label)
        ? styleEntity.label.clone()
        : createDefaultLabel();
      entity.label = label;
    }
    label.text = entity.name;

    let billboard = entity.billboard;
    if (!defined(billboard)) {
      billboard = defined(styleEntity.billboard)
        ? styleEntity.billboard.clone()
        : createDefaultBillboard();
      entity.billboard = billboard;
    }

    if (!defined(billboard.image)) {
      billboard.image = dataSource._pinBuilder.fromColor(Color.YELLOW, 64);

      // If there were empty <Icon> tags in the KML, then billboard.image was set to false above
      // However, in this case, the false value would have been converted to a property afterwards
      // Thus, we check if billboard.image is defined with value of false
    } else if (!billboard.image.getValue()) {
      billboard.image = undefined;
    }

    let scale = 1.0;
    if (defined(billboard.scale)) {
      scale = billboard.scale.getValue();
      if (scale !== 0) {
        label.pixelOffset = new Cartesian2(scale * 16 + 1, 0);
      } else {
        //Minor tweaks to better match Google Earth.
        label.pixelOffset = undefined;
        label.horizontalOrigin = undefined;
      }
    }

    if (defined(heightReference) && dataSource._clampToGround) {
      billboard.heightReference = heightReference;
      label.heightReference = heightReference;
    }
  }

  function processPathGraphics(entity, styleEntity) {
    let path = entity.path;
    if (!defined(path)) {
      path = new PathGraphics();
      path.leadTime = 0;
      entity.path = path;
    }

    const polyline = styleEntity.polyline;
    if (defined(polyline)) {
      path.material = polyline.material;
      path.width = polyline.width;
    }
  }

  function processPoint(
    dataSource,
    entityCollection,
    geometryNode,
    entity,
    styleEntity
  ) {
    const coordinatesString = queryStringValue(
      geometryNode,
      "coordinates",
      namespaces.kml
    );
    const altitudeMode = queryStringValue(
      geometryNode,
      "altitudeMode",
      namespaces.kml
    );
    const gxAltitudeMode = queryStringValue(
      geometryNode,
      "altitudeMode",
      namespaces.gx
    );
    const extrude = queryBooleanValue(geometryNode, "extrude", namespaces.kml);
    const ellipsoid = dataSource._ellipsoid;
    const position = readCoordinate(coordinatesString, ellipsoid);

    entity.position = position;
    processPositionGraphics(
      dataSource,
      entity,
      styleEntity,
      heightReferenceFromAltitudeMode(altitudeMode, gxAltitudeMode)
    );

    if (extrude && isExtrudable(altitudeMode, gxAltitudeMode)) {
      createDropLine(entityCollection, entity, styleEntity);
    }

    return true;
  }

  function processLineStringOrLinearRing(
    dataSource,
    entityCollection,
    geometryNode,
    entity,
    styleEntity
  ) {
    const coordinatesNode = queryFirstNode(
      geometryNode,
      "coordinates",
      namespaces.kml
    );
    const altitudeMode = queryStringValue(
      geometryNode,
      "altitudeMode",
      namespaces.kml
    );
    const gxAltitudeMode = queryStringValue(
      geometryNode,
      "altitudeMode",
      namespaces.gx
    );
    const extrude = queryBooleanValue(geometryNode, "extrude", namespaces.kml);
    const tessellate = queryBooleanValue(
      geometryNode,
      "tessellate",
      namespaces.kml
    );
    const canExtrude = isExtrudable(altitudeMode, gxAltitudeMode);
    const zIndex = queryNumericValue(geometryNode, "drawOrder", namespaces.gx);

    const ellipsoid = dataSource._ellipsoid;
    const coordinates = readCoordinates(coordinatesNode, ellipsoid);
    let polyline = styleEntity.polyline;
    if (canExtrude && extrude) {
      const wall = new WallGraphics();
      entity.wall = wall;
      wall.positions = coordinates;
      const polygon = styleEntity.polygon;

      if (defined(polygon)) {
        wall.fill = polygon.fill;
        wall.material = polygon.material;
      }

      //Always outline walls so they show up in 2D.
      wall.outline = true;
      if (defined(polyline)) {
        wall.outlineColor = defined(polyline.material)
          ? polyline.material.color
          : Color.WHITE;
        wall.outlineWidth = polyline.width;
      } else if (defined(polygon)) {
        wall.outlineColor = defined(polygon.material)
          ? polygon.material.color
          : Color.WHITE;
      }
    } else if (dataSource._clampToGround && !canExtrude && tessellate) {
      const polylineGraphics = new PolylineGraphics();
      polylineGraphics.clampToGround = true;
      entity.polyline = polylineGraphics;
      polylineGraphics.positions = coordinates;
      if (defined(polyline)) {
        polylineGraphics.material = defined(polyline.material)
          ? polyline.material.color.getValue(Iso8601.MINIMUM_VALUE)
          : Color.WHITE;
        polylineGraphics.width = defaultValue(polyline.width, 1.0);
      } else {
        polylineGraphics.material = Color.WHITE;
        polylineGraphics.width = 1.0;
      }
      polylineGraphics.zIndex = zIndex;
    } else {
      if (defined(zIndex)) {
        oneTimeWarning(
          "kml-gx:drawOrder",
          "KML - gx:drawOrder is not supported in LineStrings when clampToGround is false"
        );
      }
      if (dataSource._clampToGround && !tessellate) {
        oneTimeWarning(
          "kml-line-tesselate",
          "Ignoring clampToGround for KML lines without the tessellate flag."
        );
      }

      polyline = defined(polyline) ? polyline.clone() : new PolylineGraphics();
      entity.polyline = polyline;
      polyline.positions = createPositionPropertyArrayFromAltitudeMode(
        coordinates,
        altitudeMode,
        gxAltitudeMode,
        ellipsoid
      );
      if (!tessellate || canExtrude) {
        polyline.arcType = ArcType$1.NONE;
      }
    }

    return true;
  }

  function processPolygon(
    dataSource,
    entityCollection,
    geometryNode,
    entity,
    styleEntity
  ) {
    const outerBoundaryIsNode = queryFirstNode(
      geometryNode,
      "outerBoundaryIs",
      namespaces.kml
    );
    let linearRingNode = queryFirstNode(
      outerBoundaryIsNode,
      "LinearRing",
      namespaces.kml
    );
    let coordinatesNode = queryFirstNode(
      linearRingNode,
      "coordinates",
      namespaces.kml
    );
    const ellipsoid = dataSource._ellipsoid;
    let coordinates = readCoordinates(coordinatesNode, ellipsoid);
    const extrude = queryBooleanValue(geometryNode, "extrude", namespaces.kml);
    const altitudeMode = queryStringValue(
      geometryNode,
      "altitudeMode",
      namespaces.kml
    );
    const gxAltitudeMode = queryStringValue(
      geometryNode,
      "altitudeMode",
      namespaces.gx
    );
    const canExtrude = isExtrudable(altitudeMode, gxAltitudeMode);

    const polygon = defined(styleEntity.polygon)
      ? styleEntity.polygon.clone()
      : createDefaultPolygon();

    const polyline = styleEntity.polyline;
    if (defined(polyline)) {
      polygon.outlineColor = defined(polyline.material)
        ? polyline.material.color
        : Color.WHITE;
      polygon.outlineWidth = polyline.width;
    }
    entity.polygon = polygon;

    if (canExtrude) {
      polygon.perPositionHeight = true;
      polygon.extrudedHeight = extrude ? 0 : undefined;
    } else if (!dataSource._clampToGround) {
      polygon.height = 0;
    }

    if (defined(coordinates)) {
      const hierarchy = new PolygonHierarchy(coordinates);
      const innerBoundaryIsNodes = queryChildNodes(
        geometryNode,
        "innerBoundaryIs",
        namespaces.kml
      );
      for (let j = 0; j < innerBoundaryIsNodes.length; j++) {
        linearRingNode = queryChildNodes(
          innerBoundaryIsNodes[j],
          "LinearRing",
          namespaces.kml
        );
        for (let k = 0; k < linearRingNode.length; k++) {
          coordinatesNode = queryFirstNode(
            linearRingNode[k],
            "coordinates",
            namespaces.kml
          );
          coordinates = readCoordinates(coordinatesNode, ellipsoid);
          if (defined(coordinates)) {
            hierarchy.holes.push(new PolygonHierarchy(coordinates));
          }
        }
      }
      polygon.hierarchy = hierarchy;
    }

    return true;
  }

  function processTrack(
    dataSource,
    entityCollection,
    geometryNode,
    entity,
    styleEntity
  ) {
    const altitudeMode = queryStringValue(
      geometryNode,
      "altitudeMode",
      namespaces.kml
    );
    const gxAltitudeMode = queryStringValue(
      geometryNode,
      "altitudeMode",
      namespaces.gx
    );
    const coordNodes = queryChildNodes(geometryNode, "coord", namespaces.gx);
    const angleNodes = queryChildNodes(geometryNode, "angles", namespaces.gx);
    const timeNodes = queryChildNodes(geometryNode, "when", namespaces.kml);
    const extrude = queryBooleanValue(geometryNode, "extrude", namespaces.kml);
    const canExtrude = isExtrudable(altitudeMode, gxAltitudeMode);
    const ellipsoid = dataSource._ellipsoid;

    if (angleNodes.length > 0) {
      oneTimeWarning(
        "kml-gx:angles",
        "KML - gx:angles are not supported in gx:Tracks"
      );
    }

    const length = Math.min(coordNodes.length, timeNodes.length);
    const coordinates = [];
    const times = [];
    for (let i = 0; i < length; i++) {
      const position = readCoordinate(coordNodes[i].textContent, ellipsoid);
      coordinates.push(position);
      times.push(JulianDate.fromIso8601(timeNodes[i].textContent));
    }
    const property = new SampledPositionProperty();
    property.addSamples(times, coordinates);
    entity.position = property;
    processPositionGraphics(
      dataSource,
      entity,
      styleEntity,
      heightReferenceFromAltitudeMode(altitudeMode, gxAltitudeMode)
    );
    processPathGraphics(entity, styleEntity);

    entity.availability = new TimeIntervalCollection();

    if (timeNodes.length > 0) {
      entity.availability.addInterval(
        new TimeInterval({
          start: times[0],
          stop: times[times.length - 1],
        })
      );
    }

    if (canExtrude && extrude) {
      createDropLine(entityCollection, entity, styleEntity);
    }

    return true;
  }

  function addToMultiTrack(
    times,
    positions,
    composite,
    availability,
    dropShowProperty,
    extrude,
    altitudeMode,
    gxAltitudeMode,
    includeEndPoints
  ) {
    const start = times[0];
    const stop = times[times.length - 1];

    const data = new SampledPositionProperty();
    data.addSamples(times, positions);

    composite.intervals.addInterval(
      new TimeInterval({
        start: start,
        stop: stop,
        isStartIncluded: includeEndPoints,
        isStopIncluded: includeEndPoints,
        data: createPositionPropertyFromAltitudeMode(
          data,
          altitudeMode,
          gxAltitudeMode
        ),
      })
    );
    availability.addInterval(
      new TimeInterval({
        start: start,
        stop: stop,
        isStartIncluded: includeEndPoints,
        isStopIncluded: includeEndPoints,
      })
    );
    dropShowProperty.intervals.addInterval(
      new TimeInterval({
        start: start,
        stop: stop,
        isStartIncluded: includeEndPoints,
        isStopIncluded: includeEndPoints,
        data: extrude,
      })
    );
  }

  function processMultiTrack(
    dataSource,
    entityCollection,
    geometryNode,
    entity,
    styleEntity
  ) {
    // Multitrack options do not work in GE as detailed in the spec,
    // rather than altitudeMode being at the MultiTrack level,
    // GE just defers all settings to the underlying track.

    const interpolate = queryBooleanValue(
      geometryNode,
      "interpolate",
      namespaces.gx
    );
    const trackNodes = queryChildNodes(geometryNode, "Track", namespaces.gx);

    let times;
    let lastStop;
    let lastStopPosition;
    let needDropLine = false;
    const dropShowProperty = new TimeIntervalCollectionProperty();
    const availability = new TimeIntervalCollection();
    const composite = new CompositePositionProperty();
    const ellipsoid = dataSource._ellipsoid;
    for (let i = 0, len = trackNodes.length; i < len; i++) {
      const trackNode = trackNodes[i];
      const timeNodes = queryChildNodes(trackNode, "when", namespaces.kml);
      const coordNodes = queryChildNodes(trackNode, "coord", namespaces.gx);
      const altitudeMode = queryStringValue(
        trackNode,
        "altitudeMode",
        namespaces.kml
      );
      const gxAltitudeMode = queryStringValue(
        trackNode,
        "altitudeMode",
        namespaces.gx
      );
      const canExtrude = isExtrudable(altitudeMode, gxAltitudeMode);
      const extrude = queryBooleanValue(trackNode, "extrude", namespaces.kml);

      const length = Math.min(coordNodes.length, timeNodes.length);

      const positions = [];
      times = [];
      for (let x = 0; x < length; x++) {
        const position = readCoordinate(coordNodes[x].textContent, ellipsoid);
        positions.push(position);
        times.push(JulianDate.fromIso8601(timeNodes[x].textContent));
      }

      if (interpolate) {
        //If we are interpolating, then we need to fill in the end of
        //the last track and the beginning of this one with a sampled
        //property.  From testing in Google Earth, this property
        //is never extruded and always absolute.
        if (defined(lastStop)) {
          addToMultiTrack(
            [lastStop, times[0]],
            [lastStopPosition, positions[0]],
            composite,
            availability,
            dropShowProperty,
            false,
            "absolute",
            undefined,
            false
          );
        }
        lastStop = times[length - 1];
        lastStopPosition = positions[positions.length - 1];
      }

      addToMultiTrack(
        times,
        positions,
        composite,
        availability,
        dropShowProperty,
        canExtrude && extrude,
        altitudeMode,
        gxAltitudeMode,
        true
      );
      needDropLine = needDropLine || (canExtrude && extrude);
    }

    entity.availability = availability;
    entity.position = composite;
    processPositionGraphics(dataSource, entity, styleEntity);
    processPathGraphics(entity, styleEntity);
    if (needDropLine) {
      createDropLine(entityCollection, entity, styleEntity);
      entity.polyline.show = dropShowProperty;
    }

    return true;
  }

  const geometryTypes = {
    Point: processPoint,
    LineString: processLineStringOrLinearRing,
    LinearRing: processLineStringOrLinearRing,
    Polygon: processPolygon,
    Track: processTrack,
    MultiTrack: processMultiTrack,
    MultiGeometry: processMultiGeometry,
    Model: processUnsupportedGeometry,
  };

  function processMultiGeometry(
    dataSource,
    entityCollection,
    geometryNode,
    entity,
    styleEntity,
    context
  ) {
    const childNodes = geometryNode.childNodes;
    let hasGeometry = false;
    for (let i = 0, len = childNodes.length; i < len; i++) {
      const childNode = childNodes.item(i);
      const geometryProcessor = geometryTypes[childNode.localName];
      if (defined(geometryProcessor)) {
        const childEntity = createEntity(childNode, entityCollection, context);
        childEntity.parent = entity;
        childEntity.name = entity.name;
        childEntity.availability = entity.availability;
        childEntity.description = entity.description;
        childEntity.kml = entity.kml;
        if (
          geometryProcessor(
            dataSource,
            entityCollection,
            childNode,
            childEntity,
            styleEntity
          )
        ) {
          hasGeometry = true;
        }
      }
    }

    return hasGeometry;
  }

  function processUnsupportedGeometry(
    dataSource,
    entityCollection,
    geometryNode,
    entity,
    styleEntity
  ) {
    oneTimeWarning(
      "kml-unsupportedGeometry",
      `KML - Unsupported geometry: ${geometryNode.localName}`
    );
    return false;
  }

  function processExtendedData(node, entity) {
    const extendedDataNode = queryFirstNode(node, "ExtendedData", namespaces.kml);

    if (!defined(extendedDataNode)) {
      return undefined;
    }

    if (defined(queryFirstNode(extendedDataNode, "SchemaData", namespaces.kml))) {
      oneTimeWarning("kml-schemaData", "KML - SchemaData is unsupported");
    }
    if (defined(queryStringAttribute(extendedDataNode, "xmlns:prefix"))) {
      oneTimeWarning(
        "kml-extendedData",
        "KML - ExtendedData with xmlns:prefix is unsupported"
      );
    }

    const result = {};
    const dataNodes = queryChildNodes(extendedDataNode, "Data", namespaces.kml);
    if (defined(dataNodes)) {
      const length = dataNodes.length;
      for (let i = 0; i < length; i++) {
        const dataNode = dataNodes[i];
        const name = queryStringAttribute(dataNode, "name");
        if (defined(name)) {
          result[name] = {
            displayName: queryStringValue(
              dataNode,
              "displayName",
              namespaces.kml
            ),
            value: queryStringValue(dataNode, "value", namespaces.kml),
          };
        }
      }
    }
    entity.kml.extendedData = result;
  }

  let scratchDiv;
  if (typeof document !== "undefined") {
    scratchDiv = document.createElement("div");
  }

  function processDescription(
    node,
    entity,
    styleEntity,
    uriResolver,
    sourceResource
  ) {
    let i;
    let key;
    let keys;

    const kmlData = entity.kml;
    const extendedData = kmlData.extendedData;
    const description = queryStringValue(node, "description", namespaces.kml);

    const balloonStyle = defaultValue(
      entity.balloonStyle,
      styleEntity.balloonStyle
    );

    let background = Color.WHITE;
    let foreground = Color.BLACK;
    let text = description;

    if (defined(balloonStyle)) {
      background = defaultValue(balloonStyle.bgColor, Color.WHITE);
      foreground = defaultValue(balloonStyle.textColor, Color.BLACK);
      text = defaultValue(balloonStyle.text, description);
    }

    let value;
    if (defined(text)) {
      text = text.replace("$[name]", defaultValue(entity.name, ""));
      text = text.replace("$[description]", defaultValue(description, ""));
      text = text.replace("$[address]", defaultValue(kmlData.address, ""));
      text = text.replace("$[Snippet]", defaultValue(kmlData.snippet, ""));
      text = text.replace("$[id]", entity.id);

      //While not explicitly defined by the OGC spec, in Google Earth
      //The appearance of geDirections adds the directions to/from links
      //We simply replace this string with nothing.
      text = text.replace("$[geDirections]", "");

      if (defined(extendedData)) {
        const matches = text.match(/\$\[.+?\]/g);
        if (matches !== null) {
          for (i = 0; i < matches.length; i++) {
            const token = matches[i];
            let propertyName = token.substr(2, token.length - 3);
            const isDisplayName = /\/displayName$/.test(propertyName);
            propertyName = propertyName.replace(/\/displayName$/, "");

            value = extendedData[propertyName];
            if (defined(value)) {
              value = isDisplayName ? value.displayName : value.value;
            }
            if (defined(value)) {
              text = text.replace(token, defaultValue(value, ""));
            }
          }
        }
      }
    } else if (defined(extendedData)) {
      //If no description exists, build a table out of the extended data
      keys = Object.keys(extendedData);
      if (keys.length > 0) {
        text =
          '<table class="cesium-infoBox-defaultTable cesium-infoBox-defaultTable-lighter"><tbody>';
        for (i = 0; i < keys.length; i++) {
          key = keys[i];
          value = extendedData[key];
          text += `<tr><th>${defaultValue(
          value.displayName,
          key
        )}</th><td>${defaultValue(value.value, "")}</td></tr>`;
        }
        text += "</tbody></table>";
      }
    }

    if (!defined(text)) {
      //No description
      return;
    }

    //Turns non-explicit links into clickable links.
    text = autolinker.link(text);

    //Use a temporary div to manipulate the links
    //so that they open in a new window.
    scratchDiv.innerHTML = text;
    const links = scratchDiv.querySelectorAll("a");
    for (i = 0; i < links.length; i++) {
      links[i].setAttribute("target", "_blank");
    }

    //Rewrite any KMZ embedded urls
    if (defined(uriResolver) && uriResolver.keys.length > 1) {
      embedDataUris(scratchDiv, "a", "href", uriResolver);
      embedDataUris(scratchDiv, "link", "href", uriResolver);
      embedDataUris(scratchDiv, "area", "href", uriResolver);
      embedDataUris(scratchDiv, "img", "src", uriResolver);
      embedDataUris(scratchDiv, "iframe", "src", uriResolver);
      embedDataUris(scratchDiv, "video", "src", uriResolver);
      embedDataUris(scratchDiv, "audio", "src", uriResolver);
      embedDataUris(scratchDiv, "source", "src", uriResolver);
      embedDataUris(scratchDiv, "track", "src", uriResolver);
      embedDataUris(scratchDiv, "input", "src", uriResolver);
      embedDataUris(scratchDiv, "embed", "src", uriResolver);
      embedDataUris(scratchDiv, "script", "src", uriResolver);
      embedDataUris(scratchDiv, "video", "poster", uriResolver);
    }

    //Make relative urls absolute using the sourceResource
    applyBasePath(scratchDiv, "a", "href", sourceResource);
    applyBasePath(scratchDiv, "link", "href", sourceResource);
    applyBasePath(scratchDiv, "area", "href", sourceResource);
    applyBasePath(scratchDiv, "img", "src", sourceResource);
    applyBasePath(scratchDiv, "iframe", "src", sourceResource);
    applyBasePath(scratchDiv, "video", "src", sourceResource);
    applyBasePath(scratchDiv, "audio", "src", sourceResource);
    applyBasePath(scratchDiv, "source", "src", sourceResource);
    applyBasePath(scratchDiv, "track", "src", sourceResource);
    applyBasePath(scratchDiv, "input", "src", sourceResource);
    applyBasePath(scratchDiv, "embed", "src", sourceResource);
    applyBasePath(scratchDiv, "script", "src", sourceResource);
    applyBasePath(scratchDiv, "video", "poster", sourceResource);

    let tmp = '<div class="cesium-infoBox-description-lighter" style="';
    tmp += "overflow:auto;";
    tmp += "word-wrap:break-word;";
    tmp += `background-color:${background.toCssColorString()};`;
    tmp += `color:${foreground.toCssColorString()};`;
    tmp += '">';
    tmp += `${scratchDiv.innerHTML}</div>`;
    scratchDiv.innerHTML = "";

    //Set the final HTML as the description.
    entity.description = tmp;
  }

  function processFeature(dataSource, featureNode, processingData) {
    const entityCollection = processingData.entityCollection;
    const parent = processingData.parentEntity;
    const sourceResource = processingData.sourceResource;
    const uriResolver = processingData.uriResolver;

    const entity = createEntity(
      featureNode,
      entityCollection,
      processingData.context
    );
    const kmlData = entity.kml;
    const styleEntity = computeFinalStyle(
      dataSource,
      featureNode,
      processingData.styleCollection,
      sourceResource,
      uriResolver
    );

    const name = queryStringValue(featureNode, "name", namespaces.kml);
    entity.name = name;
    entity.parent = parent;

    let availability = processTimeSpan(featureNode);
    if (!defined(availability)) {
      availability = processTimeStamp(featureNode);
    }
    entity.availability = availability;

    mergeAvailabilityWithParent(entity);

    // Per KML spec "A Feature is visible only if it and all its ancestors are visible."
    function ancestryIsVisible(parentEntity) {
      if (!parentEntity) {
        return true;
      }
      return parentEntity.show && ancestryIsVisible(parentEntity.parent);
    }

    const visibility = queryBooleanValue(
      featureNode,
      "visibility",
      namespaces.kml
    );
    entity.show = ancestryIsVisible(parent) && defaultValue(visibility, true);
    //const open = queryBooleanValue(featureNode, 'open', namespaces.kml);

    const authorNode = queryFirstNode(featureNode, "author", namespaces.atom);
    const author = kmlData.author;
    author.name = queryStringValue(authorNode, "name", namespaces.atom);
    author.uri = queryStringValue(authorNode, "uri", namespaces.atom);
    author.email = queryStringValue(authorNode, "email", namespaces.atom);

    const linkNode = queryFirstNode(featureNode, "link", namespaces.atom);
    const link = kmlData.link;
    link.href = queryStringAttribute(linkNode, "href");
    link.hreflang = queryStringAttribute(linkNode, "hreflang");
    link.rel = queryStringAttribute(linkNode, "rel");
    link.type = queryStringAttribute(linkNode, "type");
    link.title = queryStringAttribute(linkNode, "title");
    link.length = queryStringAttribute(linkNode, "length");

    kmlData.address = queryStringValue(featureNode, "address", namespaces.kml);
    kmlData.phoneNumber = queryStringValue(
      featureNode,
      "phoneNumber",
      namespaces.kml
    );
    kmlData.snippet = queryStringValue(featureNode, "Snippet", namespaces.kml);

    processExtendedData(featureNode, entity);
    processDescription(
      featureNode,
      entity,
      styleEntity,
      uriResolver,
      sourceResource
    );

    const ellipsoid = dataSource._ellipsoid;
    processLookAt(featureNode, entity, ellipsoid);
    processCamera(featureNode, entity, ellipsoid);

    if (defined(queryFirstNode(featureNode, "Region", namespaces.kml))) {
      oneTimeWarning("kml-region", "KML - Placemark Regions are unsupported");
    }

    return {
      entity: entity,
      styleEntity: styleEntity,
    };
  }

  function processDocument(dataSource, node, processingData, deferredLoading) {
    deferredLoading.addNodes(node.childNodes, processingData);
    deferredLoading.process();
  }

  function processFolder(dataSource, node, processingData, deferredLoading) {
    const r = processFeature(dataSource, node, processingData);
    const newProcessingData = clone$1(processingData);
    newProcessingData.parentEntity = r.entity;
    processDocument(dataSource, node, newProcessingData, deferredLoading);
  }

  function processPlacemark(
    dataSource,
    placemark,
    processingData,
    deferredLoading
  ) {
    const r = processFeature(dataSource, placemark, processingData);
    const entity = r.entity;
    const styleEntity = r.styleEntity;

    let hasGeometry = false;
    const childNodes = placemark.childNodes;
    for (let i = 0, len = childNodes.length; i < len && !hasGeometry; i++) {
      const childNode = childNodes.item(i);
      const geometryProcessor = geometryTypes[childNode.localName];
      if (defined(geometryProcessor)) {
        // pass the placemark entity id as a context for case of defining multiple child entities together to handle case
        // where some malformed kmls reuse the same id across placemarks, which works in GE, but is not technically to spec.
        geometryProcessor(
          dataSource,
          processingData.entityCollection,
          childNode,
          entity,
          styleEntity,
          entity.id
        );
        hasGeometry = true;
      }
    }

    if (!hasGeometry) {
      entity.merge(styleEntity);
      processPositionGraphics(dataSource, entity, styleEntity);
    }
  }

  const playlistNodeProcessors = {
    FlyTo: processTourFlyTo,
    Wait: processTourWait,
    SoundCue: processTourUnsupportedNode,
    AnimatedUpdate: processTourUnsupportedNode,
    TourControl: processTourUnsupportedNode,
  };

  function processTour(dataSource, node, processingData, deferredLoading) {
    const name = queryStringValue(node, "name", namespaces.kml);
    const id = queryStringAttribute(node, "id");
    const tour = new KmlTour(name, id);

    const playlistNode = queryFirstNode(node, "Playlist", namespaces.gx);
    if (playlistNode) {
      const ellipsoid = dataSource._ellipsoid;
      const childNodes = playlistNode.childNodes;
      for (let i = 0; i < childNodes.length; i++) {
        const entryNode = childNodes[i];
        if (entryNode.localName) {
          const playlistNodeProcessor =
            playlistNodeProcessors[entryNode.localName];
          if (playlistNodeProcessor) {
            playlistNodeProcessor(tour, entryNode, ellipsoid);
          } else {
            console.log(
              `Unknown KML Tour playlist entry type ${entryNode.localName}`
            );
          }
        }
      }
    }

    dataSource._kmlTours.push(tour);
  }

  function processTourUnsupportedNode(tour, entryNode) {
    oneTimeWarning(`KML Tour unsupported node ${entryNode.localName}`);
  }

  function processTourWait(tour, entryNode) {
    const duration = queryNumericValue(entryNode, "duration", namespaces.gx);
    tour.addPlaylistEntry(new KmlTourWait(duration));
  }

  function processTourFlyTo(tour, entryNode, ellipsoid) {
    const duration = queryNumericValue(entryNode, "duration", namespaces.gx);
    const flyToMode = queryStringValue(entryNode, "flyToMode", namespaces.gx);

    const t = { kml: {} };

    processLookAt(entryNode, t, ellipsoid);
    processCamera(entryNode, t, ellipsoid);

    const view = t.kml.lookAt || t.kml.camera;

    const flyto = new KmlTourFlyTo(duration, flyToMode, view);
    tour.addPlaylistEntry(flyto);
  }

  function processCamera(featureNode, entity, ellipsoid) {
    const camera = queryFirstNode(featureNode, "Camera", namespaces.kml);
    if (defined(camera)) {
      const lon = defaultValue(
        queryNumericValue(camera, "longitude", namespaces.kml),
        0.0
      );
      const lat = defaultValue(
        queryNumericValue(camera, "latitude", namespaces.kml),
        0.0
      );
      const altitude = defaultValue(
        queryNumericValue(camera, "altitude", namespaces.kml),
        0.0
      );

      const heading = defaultValue(
        queryNumericValue(camera, "heading", namespaces.kml),
        0.0
      );
      const tilt = defaultValue(
        queryNumericValue(camera, "tilt", namespaces.kml),
        0.0
      );
      const roll = defaultValue(
        queryNumericValue(camera, "roll", namespaces.kml),
        0.0
      );

      const position = Cartesian3.fromDegrees(lon, lat, altitude, ellipsoid);
      const hpr = HeadingPitchRoll.fromDegrees(heading, tilt - 90.0, roll);

      entity.kml.camera = new KmlCamera(position, hpr);
    }
  }

  function processLookAt(featureNode, entity, ellipsoid) {
    const lookAt = queryFirstNode(featureNode, "LookAt", namespaces.kml);
    if (defined(lookAt)) {
      const lon = defaultValue(
        queryNumericValue(lookAt, "longitude", namespaces.kml),
        0.0
      );
      const lat = defaultValue(
        queryNumericValue(lookAt, "latitude", namespaces.kml),
        0.0
      );
      const altitude = defaultValue(
        queryNumericValue(lookAt, "altitude", namespaces.kml),
        0.0
      );
      let heading = queryNumericValue(lookAt, "heading", namespaces.kml);
      let tilt = queryNumericValue(lookAt, "tilt", namespaces.kml);
      const range = defaultValue(
        queryNumericValue(lookAt, "range", namespaces.kml),
        0.0
      );

      tilt = CesiumMath.toRadians(defaultValue(tilt, 0.0));
      heading = CesiumMath.toRadians(defaultValue(heading, 0.0));

      const hpr = new HeadingPitchRange(
        heading,
        tilt - CesiumMath.PI_OVER_TWO,
        range
      );
      const viewPoint = Cartesian3.fromDegrees(lon, lat, altitude, ellipsoid);

      entity.kml.lookAt = new KmlLookAt(viewPoint, hpr);
    }
  }

  function processScreenOverlay(
    dataSource,
    screenOverlayNode,
    processingData,
    deferredLoading
  ) {
    const screenOverlay = processingData.screenOverlayContainer;
    if (!defined(screenOverlay)) {
      return undefined;
    }

    const sourceResource = processingData.sourceResource;
    const uriResolver = processingData.uriResolver;

    const iconNode = queryFirstNode(screenOverlayNode, "Icon", namespaces.kml);
    const icon = getIconHref(
      iconNode,
      dataSource,
      sourceResource,
      uriResolver,
      false
    );

    if (!defined(icon)) {
      return undefined;
    }

    const img = document.createElement("img");
    dataSource._screenOverlays.push(img);

    img.src = icon.url;
    img.onload = function () {
      const styles = ["position: absolute"];

      const screenXY = queryFirstNode(
        screenOverlayNode,
        "screenXY",
        namespaces.kml
      );
      const overlayXY = queryFirstNode(
        screenOverlayNode,
        "overlayXY",
        namespaces.kml
      );
      const size = queryFirstNode(screenOverlayNode, "size", namespaces.kml);

      let x, y;
      let xUnit, yUnit;
      let xStyle, yStyle;

      if (defined(size)) {
        x = queryNumericAttribute(size, "x");
        y = queryNumericAttribute(size, "y");
        xUnit = queryStringAttribute(size, "xunits");
        yUnit = queryStringAttribute(size, "yunits");

        if (defined(x) && x !== -1 && x !== 0) {
          if (xUnit === "fraction") {
            xStyle = `width: ${Math.floor(x * 100)}%`;
          } else if (xUnit === "pixels") {
            xStyle = `width: ${x}px`;
          }

          styles.push(xStyle);
        }

        if (defined(y) && y !== -1 && y !== 0) {
          if (yUnit === "fraction") {
            yStyle = `height: ${Math.floor(y * 100)}%`;
          } else if (yUnit === "pixels") {
            yStyle = `height: ${y}px`;
          }

          styles.push(yStyle);
        }
      }

      // set the interim style so the width/height properties get calculated
      img.style = styles.join(";");

      let xOrigin = 0;
      let yOrigin = img.height;

      if (defined(overlayXY)) {
        x = queryNumericAttribute(overlayXY, "x");
        y = queryNumericAttribute(overlayXY, "y");
        xUnit = queryStringAttribute(overlayXY, "xunits");
        yUnit = queryStringAttribute(overlayXY, "yunits");

        if (defined(x)) {
          if (xUnit === "fraction") {
            xOrigin = x * img.width;
          } else if (xUnit === "pixels") {
            xOrigin = x;
          } else if (xUnit === "insetPixels") {
            xOrigin = x;
          }
        }

        if (defined(y)) {
          if (yUnit === "fraction") {
            yOrigin = y * img.height;
          } else if (yUnit === "pixels") {
            yOrigin = y;
          } else if (yUnit === "insetPixels") {
            yOrigin = y;
          }
        }
      }

      if (defined(screenXY)) {
        x = queryNumericAttribute(screenXY, "x");
        y = queryNumericAttribute(screenXY, "y");
        xUnit = queryStringAttribute(screenXY, "xunits");
        yUnit = queryStringAttribute(screenXY, "yunits");

        if (defined(x)) {
          if (xUnit === "fraction") {
            xStyle = `${"left: " + "calc("}${Math.floor(
            x * 100
          )}% - ${xOrigin}px)`;
          } else if (xUnit === "pixels") {
            xStyle = `left: ${x - xOrigin}px`;
          } else if (xUnit === "insetPixels") {
            xStyle = `right: ${x - xOrigin}px`;
          }

          styles.push(xStyle);
        }

        if (defined(y)) {
          if (yUnit === "fraction") {
            yStyle = `${"bottom: " + "calc("}${Math.floor(
            y * 100
          )}% - ${yOrigin}px)`;
          } else if (yUnit === "pixels") {
            yStyle = `bottom: ${y - yOrigin}px`;
          } else if (yUnit === "insetPixels") {
            yStyle = `top: ${y - yOrigin}px`;
          }

          styles.push(yStyle);
        }
      }

      img.style = styles.join(";");
    };

    screenOverlay.appendChild(img);
  }

  function processGroundOverlay(
    dataSource,
    groundOverlay,
    processingData,
    deferredLoading
  ) {
    const r = processFeature(dataSource, groundOverlay, processingData);
    const entity = r.entity;

    let geometry;
    let isLatLonQuad = false;

    const ellipsoid = dataSource._ellipsoid;
    const positions = readCoordinates(
      queryFirstNode(groundOverlay, "LatLonQuad", namespaces.gx),
      ellipsoid
    );
    const zIndex = queryNumericValue(groundOverlay, "drawOrder", namespaces.kml);
    if (defined(positions)) {
      geometry = createDefaultPolygon();
      geometry.hierarchy = new PolygonHierarchy(positions);
      geometry.zIndex = zIndex;
      entity.polygon = geometry;
      isLatLonQuad = true;
    } else {
      geometry = new RectangleGraphics();
      geometry.zIndex = zIndex;
      entity.rectangle = geometry;

      const latLonBox = queryFirstNode(
        groundOverlay,
        "LatLonBox",
        namespaces.kml
      );
      if (defined(latLonBox)) {
        let west = queryNumericValue(latLonBox, "west", namespaces.kml);
        let south = queryNumericValue(latLonBox, "south", namespaces.kml);
        let east = queryNumericValue(latLonBox, "east", namespaces.kml);
        let north = queryNumericValue(latLonBox, "north", namespaces.kml);

        if (defined(west)) {
          west = CesiumMath.negativePiToPi(CesiumMath.toRadians(west));
        }
        if (defined(south)) {
          south = CesiumMath.clampToLatitudeRange(CesiumMath.toRadians(south));
        }
        if (defined(east)) {
          east = CesiumMath.negativePiToPi(CesiumMath.toRadians(east));
        }
        if (defined(north)) {
          north = CesiumMath.clampToLatitudeRange(CesiumMath.toRadians(north));
        }
        geometry.coordinates = new Rectangle(west, south, east, north);

        const rotation = queryNumericValue(latLonBox, "rotation", namespaces.kml);
        if (defined(rotation)) {
          const rotationRadians = CesiumMath.toRadians(rotation);
          geometry.rotation = rotationRadians;
          geometry.stRotation = rotationRadians;
        }
      }
    }

    const iconNode = queryFirstNode(groundOverlay, "Icon", namespaces.kml);
    const href = getIconHref(
      iconNode,
      dataSource,
      processingData.sourceResource,
      processingData.uriResolver,
      true
    );
    if (defined(href)) {
      if (isLatLonQuad) {
        oneTimeWarning(
          "kml-gx:LatLonQuad",
          "KML - gx:LatLonQuad Icon does not support texture projection."
        );
      }
      const x = queryNumericValue(iconNode, "x", namespaces.gx);
      const y = queryNumericValue(iconNode, "y", namespaces.gx);
      const w = queryNumericValue(iconNode, "w", namespaces.gx);
      const h = queryNumericValue(iconNode, "h", namespaces.gx);

      if (defined(x) || defined(y) || defined(w) || defined(h)) {
        oneTimeWarning(
          "kml-groundOverlay-xywh",
          "KML - gx:x, gx:y, gx:w, gx:h aren't supported for GroundOverlays"
        );
      }

      geometry.material = href;
      geometry.material.color = queryColorValue(
        groundOverlay,
        "color",
        namespaces.kml
      );
      geometry.material.transparent = true;
    } else {
      geometry.material = queryColorValue(groundOverlay, "color", namespaces.kml);
    }

    let altitudeMode = queryStringValue(
      groundOverlay,
      "altitudeMode",
      namespaces.kml
    );

    if (defined(altitudeMode)) {
      if (altitudeMode === "absolute") {
        //Use height above ellipsoid until we support MSL.
        geometry.height = queryNumericValue(
          groundOverlay,
          "altitude",
          namespaces.kml
        );
        geometry.zIndex = undefined;
      } else if (altitudeMode !== "clampToGround") {
        oneTimeWarning(
          "kml-altitudeMode-unknown",
          `KML - Unknown altitudeMode: ${altitudeMode}`
        );
      }
      // else just use the default of 0 until we support 'clampToGround'
    } else {
      altitudeMode = queryStringValue(
        groundOverlay,
        "altitudeMode",
        namespaces.gx
      );
      if (altitudeMode === "relativeToSeaFloor") {
        oneTimeWarning(
          "kml-altitudeMode-relativeToSeaFloor",
          "KML - altitudeMode relativeToSeaFloor is currently not supported, treating as absolute."
        );
        geometry.height = queryNumericValue(
          groundOverlay,
          "altitude",
          namespaces.kml
        );
        geometry.zIndex = undefined;
      } else if (altitudeMode === "clampToSeaFloor") {
        oneTimeWarning(
          "kml-altitudeMode-clampToSeaFloor",
          "KML - altitudeMode clampToSeaFloor is currently not supported, treating as clampToGround."
        );
      } else if (defined(altitudeMode)) {
        oneTimeWarning(
          "kml-altitudeMode-unknown",
          `KML - Unknown altitudeMode: ${altitudeMode}`
        );
      }
    }
  }

  function processUnsupportedFeature(
    dataSource,
    node,
    processingData,
    deferredLoading
  ) {
    dataSource._unsupportedNode.raiseEvent(
      dataSource,
      processingData.parentEntity,
      node,
      processingData.entityCollection,
      processingData.styleCollection,
      processingData.sourceResource,
      processingData.uriResolver
    );
    oneTimeWarning(
      `kml-unsupportedFeature-${node.nodeName}`,
      `KML - Unsupported feature: ${node.nodeName}`
    );
  }

  const RefreshMode = {
    INTERVAL: 0,
    EXPIRE: 1,
    STOP: 2,
  };

  function cleanupString(s) {
    if (!defined(s) || s.length === 0) {
      return "";
    }

    const sFirst = s[0];
    if (sFirst === "&" || sFirst === "?") {
      s = s.substring(1);
    }

    return s;
  }

  const zeroRectangle = new Rectangle();
  const scratchCartographic$7 = new Cartographic();
  const scratchCartesian2$2 = new Cartesian2();
  const scratchCartesian3$3 = new Cartesian3();

  function processNetworkLinkQueryString(
    resource,
    camera,
    canvas,
    viewBoundScale,
    bbox,
    ellipsoid
  ) {
    function fixLatitude(value) {
      if (value < -CesiumMath.PI_OVER_TWO) {
        return -CesiumMath.PI_OVER_TWO;
      } else if (value > CesiumMath.PI_OVER_TWO) {
        return CesiumMath.PI_OVER_TWO;
      }
      return value;
    }

    function fixLongitude(value) {
      if (value > CesiumMath.PI) {
        return value - CesiumMath.TWO_PI;
      } else if (value < -CesiumMath.PI) {
        return value + CesiumMath.TWO_PI;
      }

      return value;
    }

    let queryString = objectToQuery(resource.queryParameters);

    // objectToQuery escapes [ and ], so fix that
    queryString = queryString.replace(/%5B/g, "[").replace(/%5D/g, "]");

    if (defined(camera) && camera._mode !== SceneMode$1.MORPHING) {
      let centerCartesian;
      let centerCartographic;

      bbox = defaultValue(bbox, zeroRectangle);
      if (defined(canvas)) {
        scratchCartesian2$2.x = canvas.clientWidth * 0.5;
        scratchCartesian2$2.y = canvas.clientHeight * 0.5;
        centerCartesian = camera.pickEllipsoid(
          scratchCartesian2$2,
          ellipsoid,
          scratchCartesian3$3
        );
      }

      if (defined(centerCartesian)) {
        centerCartographic = ellipsoid.cartesianToCartographic(
          centerCartesian,
          scratchCartographic$7
        );
      } else {
        centerCartographic = Rectangle.center(bbox, scratchCartographic$7);
        centerCartesian = ellipsoid.cartographicToCartesian(centerCartographic);
      }

      if (
        defined(viewBoundScale) &&
        !CesiumMath.equalsEpsilon(viewBoundScale, 1.0, CesiumMath.EPSILON9)
      ) {
        const newHalfWidth = bbox.width * viewBoundScale * 0.5;
        const newHalfHeight = bbox.height * viewBoundScale * 0.5;
        bbox = new Rectangle(
          fixLongitude(centerCartographic.longitude - newHalfWidth),
          fixLatitude(centerCartographic.latitude - newHalfHeight),
          fixLongitude(centerCartographic.longitude + newHalfWidth),
          fixLatitude(centerCartographic.latitude + newHalfHeight)
        );
      }

      queryString = queryString.replace(
        "[bboxWest]",
        CesiumMath.toDegrees(bbox.west).toString()
      );
      queryString = queryString.replace(
        "[bboxSouth]",
        CesiumMath.toDegrees(bbox.south).toString()
      );
      queryString = queryString.replace(
        "[bboxEast]",
        CesiumMath.toDegrees(bbox.east).toString()
      );
      queryString = queryString.replace(
        "[bboxNorth]",
        CesiumMath.toDegrees(bbox.north).toString()
      );

      const lon = CesiumMath.toDegrees(centerCartographic.longitude).toString();
      const lat = CesiumMath.toDegrees(centerCartographic.latitude).toString();
      queryString = queryString.replace("[lookatLon]", lon);
      queryString = queryString.replace("[lookatLat]", lat);
      queryString = queryString.replace(
        "[lookatTilt]",
        CesiumMath.toDegrees(camera.pitch).toString()
      );
      queryString = queryString.replace(
        "[lookatHeading]",
        CesiumMath.toDegrees(camera.heading).toString()
      );
      queryString = queryString.replace(
        "[lookatRange]",
        Cartesian3.distance(camera.positionWC, centerCartesian)
      );
      queryString = queryString.replace("[lookatTerrainLon]", lon);
      queryString = queryString.replace("[lookatTerrainLat]", lat);
      queryString = queryString.replace(
        "[lookatTerrainAlt]",
        centerCartographic.height.toString()
      );

      ellipsoid.cartesianToCartographic(camera.positionWC, scratchCartographic$7);
      queryString = queryString.replace(
        "[cameraLon]",
        CesiumMath.toDegrees(scratchCartographic$7.longitude).toString()
      );
      queryString = queryString.replace(
        "[cameraLat]",
        CesiumMath.toDegrees(scratchCartographic$7.latitude).toString()
      );
      queryString = queryString.replace(
        "[cameraAlt]",
        CesiumMath.toDegrees(scratchCartographic$7.height).toString()
      );

      const frustum = camera.frustum;
      const aspectRatio = frustum.aspectRatio;
      let horizFov = "";
      let vertFov = "";
      if (defined(aspectRatio)) {
        const fov = CesiumMath.toDegrees(frustum.fov);
        if (aspectRatio > 1.0) {
          horizFov = fov;
          vertFov = fov / aspectRatio;
        } else {
          vertFov = fov;
          horizFov = fov * aspectRatio;
        }
      }
      queryString = queryString.replace("[horizFov]", horizFov.toString());
      queryString = queryString.replace("[vertFov]", vertFov.toString());
    } else {
      queryString = queryString.replace("[bboxWest]", "-180");
      queryString = queryString.replace("[bboxSouth]", "-90");
      queryString = queryString.replace("[bboxEast]", "180");
      queryString = queryString.replace("[bboxNorth]", "90");

      queryString = queryString.replace("[lookatLon]", "");
      queryString = queryString.replace("[lookatLat]", "");
      queryString = queryString.replace("[lookatRange]", "");
      queryString = queryString.replace("[lookatTilt]", "");
      queryString = queryString.replace("[lookatHeading]", "");
      queryString = queryString.replace("[lookatTerrainLon]", "");
      queryString = queryString.replace("[lookatTerrainLat]", "");
      queryString = queryString.replace("[lookatTerrainAlt]", "");

      queryString = queryString.replace("[cameraLon]", "");
      queryString = queryString.replace("[cameraLat]", "");
      queryString = queryString.replace("[cameraAlt]", "");
      queryString = queryString.replace("[horizFov]", "");
      queryString = queryString.replace("[vertFov]", "");
    }

    if (defined(canvas)) {
      queryString = queryString.replace("[horizPixels]", canvas.clientWidth);
      queryString = queryString.replace("[vertPixels]", canvas.clientHeight);
    } else {
      queryString = queryString.replace("[horizPixels]", "");
      queryString = queryString.replace("[vertPixels]", "");
    }

    queryString = queryString.replace("[terrainEnabled]", "1");
    queryString = queryString.replace("[clientVersion]", "1");
    queryString = queryString.replace("[kmlVersion]", "2.2");
    queryString = queryString.replace("[clientName]", "Cesium");
    queryString = queryString.replace("[language]", "English");

    resource.setQueryParameters(queryToObject(queryString));
  }

  function processNetworkLink(dataSource, node, processingData, deferredLoading) {
    const r = processFeature(dataSource, node, processingData);
    const networkEntity = r.entity;

    const sourceResource = processingData.sourceResource;
    const uriResolver = processingData.uriResolver;

    let link = queryFirstNode(node, "Link", namespaces.kml);

    if (!defined(link)) {
      link = queryFirstNode(node, "Url", namespaces.kml);
    }
    if (defined(link)) {
      let href = queryStringValue(link, "href", namespaces.kml);
      let viewRefreshMode;
      let viewBoundScale;
      if (defined(href)) {
        let newSourceUri = href;
        href = resolveHref(href, sourceResource, processingData.uriResolver);

        // We need to pass in the original path if resolveHref returns a data uri because the network link
        //  references a document in a KMZ archive
        if (/^data:/.test(href.getUrlComponent())) {
          // So if sourceUri isn't the kmz file, then its another kml in the archive, so resolve it
          if (!/\.kmz/i.test(sourceResource.getUrlComponent())) {
            newSourceUri = sourceResource.getDerivedResource({
              url: newSourceUri,
            });
          }
        } else {
          newSourceUri = href.clone(); // Not a data uri so use the fully qualified uri
          viewRefreshMode = queryStringValue(
            link,
            "viewRefreshMode",
            namespaces.kml
          );
          viewBoundScale = defaultValue(
            queryStringValue(link, "viewBoundScale", namespaces.kml),
            1.0
          );
          const defaultViewFormat =
            viewRefreshMode === "onStop"
              ? "BBOX=[bboxWest],[bboxSouth],[bboxEast],[bboxNorth]"
              : "";
          const viewFormat = defaultValue(
            queryStringValue(link, "viewFormat", namespaces.kml),
            defaultViewFormat
          );
          const httpQuery = queryStringValue(link, "httpQuery", namespaces.kml);
          if (defined(viewFormat)) {
            href.setQueryParameters(queryToObject(cleanupString(viewFormat)));
          }
          if (defined(httpQuery)) {
            href.setQueryParameters(queryToObject(cleanupString(httpQuery)));
          }

          const ellipsoid = dataSource._ellipsoid;
          processNetworkLinkQueryString(
            href,
            dataSource.camera,
            dataSource.canvas,
            viewBoundScale,
            dataSource._lastCameraView.bbox,
            ellipsoid
          );
        }

        const options = {
          sourceUri: newSourceUri,
          uriResolver: uriResolver,
          context: networkEntity.id,
          screenOverlayContainer: processingData.screenOverlayContainer,
        };
        const networkLinkCollection = new EntityCollection();
        const promise = load(dataSource, networkLinkCollection, href, options)
          .then(function (rootElement) {
            const entities = dataSource._entityCollection;
            const newEntities = networkLinkCollection.values;
            entities.suspendEvents();
            for (let i = 0; i < newEntities.length; i++) {
              const newEntity = newEntities[i];
              if (!defined(newEntity.parent)) {
                newEntity.parent = networkEntity;
                mergeAvailabilityWithParent(newEntity);
              }

              entities.add(newEntity);
            }
            entities.resumeEvents();

            // Add network links to a list if we need they will need to be updated
            const refreshMode = queryStringValue(
              link,
              "refreshMode",
              namespaces.kml
            );
            let refreshInterval = defaultValue(
              queryNumericValue(link, "refreshInterval", namespaces.kml),
              0
            );
            if (
              (refreshMode === "onInterval" && refreshInterval > 0) ||
              refreshMode === "onExpire" ||
              viewRefreshMode === "onStop"
            ) {
              const networkLinkControl = queryFirstNode(
                rootElement,
                "NetworkLinkControl",
                namespaces.kml
              );
              const hasNetworkLinkControl = defined(networkLinkControl);

              const now = JulianDate.now();
              const networkLinkInfo = {
                id: createGuid(),
                href: href,
                cookie: {},
                lastUpdated: now,
                updating: false,
                entity: networkEntity,
                viewBoundScale: viewBoundScale,
                needsUpdate: false,
                cameraUpdateTime: now,
              };

              let minRefreshPeriod = 0;
              if (hasNetworkLinkControl) {
                networkLinkInfo.cookie = queryToObject(
                  defaultValue(
                    queryStringValue(
                      networkLinkControl,
                      "cookie",
                      namespaces.kml
                    ),
                    ""
                  )
                );
                minRefreshPeriod = defaultValue(
                  queryNumericValue(
                    networkLinkControl,
                    "minRefreshPeriod",
                    namespaces.kml
                  ),
                  0
                );
              }

              if (refreshMode === "onInterval") {
                if (hasNetworkLinkControl) {
                  refreshInterval = Math.max(minRefreshPeriod, refreshInterval);
                }
                networkLinkInfo.refreshMode = RefreshMode.INTERVAL;
                networkLinkInfo.time = refreshInterval;
              } else if (refreshMode === "onExpire") {
                let expires;
                if (hasNetworkLinkControl) {
                  expires = queryStringValue(
                    networkLinkControl,
                    "expires",
                    namespaces.kml
                  );
                }
                if (defined(expires)) {
                  try {
                    const date = JulianDate.fromIso8601(expires);
                    const diff = JulianDate.secondsDifference(date, now);
                    if (diff > 0 && diff < minRefreshPeriod) {
                      JulianDate.addSeconds(now, minRefreshPeriod, date);
                    }
                    networkLinkInfo.refreshMode = RefreshMode.EXPIRE;
                    networkLinkInfo.time = date;
                  } catch (e) {
                    oneTimeWarning(
                      "kml-refreshMode-onInterval-onExpire",
                      "KML - NetworkLinkControl expires is not a valid date"
                    );
                  }
                } else {
                  oneTimeWarning(
                    "kml-refreshMode-onExpire",
                    "KML - refreshMode of onExpire requires the NetworkLinkControl to have an expires element"
                  );
                }
              } else if (defined(dataSource.camera)) {
                // Only allow onStop refreshes if we have a camera
                networkLinkInfo.refreshMode = RefreshMode.STOP;
                networkLinkInfo.time = defaultValue(
                  queryNumericValue(link, "viewRefreshTime", namespaces.kml),
                  0
                );
              } else {
                oneTimeWarning(
                  "kml-refrehMode-onStop-noCamera",
                  "A NetworkLink with viewRefreshMode=onStop requires the `camera` property to be defined."
                );
              }

              if (defined(networkLinkInfo.refreshMode)) {
                dataSource._networkLinks.set(networkLinkInfo.id, networkLinkInfo);
              }
            } else if (viewRefreshMode === "onRegion") {
              oneTimeWarning(
                "kml-refrehMode-onRegion",
                "KML - Unsupported viewRefreshMode: onRegion"
              );
            }
          })
          .catch(function (error) {
            oneTimeWarning(`An error occured during loading ${href.url}`);
            dataSource._error.raiseEvent(dataSource, error);
          });

        deferredLoading.addPromise(promise);
      }
    }
  }

  function processFeatureNode(dataSource, node, processingData, deferredLoading) {
    const featureProcessor = featureTypes[node.localName];
    if (defined(featureProcessor)) {
      return featureProcessor(dataSource, node, processingData, deferredLoading);
    }

    return processUnsupportedFeature(
      dataSource,
      node,
      processingData);
  }

  function loadKml(
    dataSource,
    entityCollection,
    kml,
    sourceResource,
    uriResolver,
    screenOverlayContainer,
    context
  ) {
    entityCollection.removeAll();

    const documentElement = kml.documentElement;
    const document =
      documentElement.localName === "Document"
        ? documentElement
        : queryFirstNode(documentElement, "Document", namespaces.kml);
    let name = queryStringValue(document, "name", namespaces.kml);
    if (!defined(name)) {
      name = getFilenameFromUri(sourceResource.getUrlComponent());
    }

    // Only set the name from the root document
    if (!defined(dataSource._name)) {
      dataSource._name = name;
    }

    const deferredLoading = new KmlDataSource._DeferredLoading(dataSource);
    const styleCollection = new EntityCollection(dataSource);
    return Promise.all(
      processStyles(
        dataSource,
        kml,
        styleCollection,
        sourceResource,
        false,
        uriResolver
      )
    ).then(function () {
      let element = kml.documentElement;
      if (element.localName === "kml") {
        const childNodes = element.childNodes;
        for (let i = 0; i < childNodes.length; i++) {
          const tmp = childNodes[i];
          if (defined(featureTypes[tmp.localName])) {
            element = tmp;
            break;
          }
        }
      }

      const processingData = {
        parentEntity: undefined,
        entityCollection: entityCollection,
        styleCollection: styleCollection,
        sourceResource: sourceResource,
        uriResolver: uriResolver,
        context: context,
        screenOverlayContainer: screenOverlayContainer,
      };

      entityCollection.suspendEvents();
      processFeatureNode(dataSource, element, processingData, deferredLoading);
      entityCollection.resumeEvents();

      return deferredLoading.wait().then(function () {
        return kml.documentElement;
      });
    });
  }

  function loadKmz(
    dataSource,
    entityCollection,
    blob,
    sourceResource,
    screenOverlayContainer
  ) {
    const zWorkerUrl = buildModuleUrl("ThirdParty/Workers/z-worker-pako.js");
    zipNoWorker.configure({
      workerScripts: {
        deflate: [zWorkerUrl, "./pako_deflate.min.js"],
        inflate: [zWorkerUrl, "./pako_inflate.min.js"],
      },
    });

    const reader = new zipNoWorker.ZipReader(new zipNoWorker.BlobReader(blob));
    return Promise.resolve(reader.getEntries()).then(function (entries) {
      const promises = [];
      const uriResolver = {};
      let docEntry;
      for (let i = 0; i < entries.length; i++) {
        const entry = entries[i];
        if (!entry.directory) {
          if (/\.kml$/i.test(entry.filename)) {
            // We use the first KML document we come across
            //  https://developers.google.com/kml/documentation/kmzarchives
            // Unless we come across a .kml file at the root of the archive because GE does this
            if (!defined(docEntry) || !/\//i.test(entry.filename)) {
              if (defined(docEntry)) {
                // We found one at the root so load the initial kml as a data uri
                promises.push(loadDataUriFromZip(docEntry, uriResolver));
              }
              docEntry = entry;
            } else {
              // Wasn't the first kml and wasn't at the root
              promises.push(loadDataUriFromZip(entry, uriResolver));
            }
          } else {
            promises.push(loadDataUriFromZip(entry, uriResolver));
          }
        }
      }

      // Now load the root KML document
      if (defined(docEntry)) {
        promises.push(loadXmlFromZip(docEntry, uriResolver));
      }
      return Promise.all(promises).then(function () {
        reader.close();
        if (!defined(uriResolver.kml)) {
          throw new RuntimeError("KMZ file does not contain a KML document.");
        }
        uriResolver.keys = Object.keys(uriResolver);
        return loadKml(
          dataSource,
          entityCollection,
          uriResolver.kml,
          sourceResource,
          uriResolver,
          screenOverlayContainer
        );
      });
    });
  }

  function load(dataSource, entityCollection, data, options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    let sourceUri = options.sourceUri;
    const uriResolver = options.uriResolver;
    const context = options.context;
    let screenOverlayContainer = options.screenOverlayContainer;

    let promise = data;
    if (typeof data === "string" || data instanceof Resource) {
      data = Resource.createIfNeeded(data);
      promise = data.fetchBlob();
      sourceUri = defaultValue(sourceUri, data.clone());

      // Add resource credits to our list of credits to display
      const resourceCredits = dataSource._resourceCredits;
      const credits = data.credits;
      if (defined(credits)) {
        const length = credits.length;
        for (let i = 0; i < length; i++) {
          resourceCredits.push(credits[i]);
        }
      }
    } else {
      sourceUri = defaultValue(sourceUri, Resource.DEFAULT.clone());
    }

    sourceUri = Resource.createIfNeeded(sourceUri);

    if (defined(screenOverlayContainer)) {
      screenOverlayContainer = getElement(screenOverlayContainer);
    }

    return Promise.resolve(promise)
      .then(function (dataToLoad) {
        if (dataToLoad instanceof Blob) {
          return isZipFile(dataToLoad).then(function (isZip) {
            if (isZip) {
              return loadKmz(
                dataSource,
                entityCollection,
                dataToLoad,
                sourceUri,
                screenOverlayContainer
              );
            }
            return readBlobAsText(dataToLoad).then(function (text) {
              //There's no official way to validate if a parse was successful.
              //The following check detects the error on various browsers.

              //Insert missing namespaces
              text = insertNamespaces(text);

              //Remove Duplicate Namespaces
              text = removeDuplicateNamespaces(text);

              //IE raises an exception
              let kml;
              let error;
              try {
                kml = parser.parseFromString(text, "application/xml");
              } catch (e) {
                error = e.toString();
              }

              //The parse succeeds on Chrome and Firefox, but the error
              //handling is different in each.
              if (
                defined(error) ||
                kml.body ||
                kml.documentElement.tagName === "parsererror"
              ) {
                //Firefox has error information as the firstChild nodeValue.
                let msg = defined(error)
                  ? error
                  : kml.documentElement.firstChild.nodeValue;

                //Chrome has it in the body text.
                if (!msg) {
                  msg = kml.body.innerText;
                }

                //Return the error
                throw new RuntimeError(msg);
              }
              return loadKml(
                dataSource,
                entityCollection,
                kml,
                sourceUri,
                uriResolver,
                screenOverlayContainer,
                context
              );
            });
          });
        }
        return loadKml(
          dataSource,
          entityCollection,
          dataToLoad,
          sourceUri,
          uriResolver,
          screenOverlayContainer,
          context
        );
      })
      .catch(function (error) {
        dataSource._error.raiseEvent(dataSource, error);
        console.log(error);
        return Promise.reject(error);
      });
  }

  // NOTE: LoadOptions properties are repeated in ConstructorOptions because some
  // tooling does not support "base types" for @typedef.  Remove if/when
  // https://github.com/microsoft/TypeScript/issues/20077 and/or
  // https://github.com/jsdoc/jsdoc/issues/1199 actually get resolved
  /**
   * @typedef {Object} KmlDataSource.LoadOptions
   *
   * Initialization options for the `load` method.
   *
   * @property {String} [sourceUri] Overrides the url to use for resolving relative links and other KML network features.
   * @property {Boolean} [clampToGround=false] true if we want the geometry features (Polygons, LineStrings and LinearRings) clamped to the ground.
   * @property {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The global ellipsoid used for geographical calculations.
   * @property {Element|String} [screenOverlayContainer] A container for ScreenOverlay images.
   */

  /**
   * @typedef {Object} KmlDataSource.ConstructorOptions
   *
   * Options for constructing a new KmlDataSource, or calling the static `load` method.
   *
   * @property {Camera} [camera] The camera that is used for viewRefreshModes and sending camera properties to network links.
   * @property {HTMLCanvasElement} [canvas] The canvas that is used for sending viewer properties to network links.
   * @property {Credit|String} [credit] A credit for the data source, which is displayed on the canvas.
   *
   * @property {String} [sourceUri] Overrides the url to use for resolving relative links and other KML network features.
   * @property {Boolean} [clampToGround=false] true if we want the geometry features (Polygons, LineStrings and LinearRings) clamped to the ground.
   * @property {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The global ellipsoid used for geographical calculations.
   * @property {Element|String} [screenOverlayContainer] A container for ScreenOverlay images.

  */

  /**
   * A {@link DataSource} which processes Keyhole Markup Language 2.2 (KML).
   * <p>
   * KML support in Cesium is incomplete, but a large amount of the standard,
   * as well as Google's <code>gx</code> extension namespace, is supported. See Github issue
   * {@link https://github.com/CesiumGS/cesium/issues/873|#873} for a
   * detailed list of what is and isn't supported. Cesium will also write information to the
   * console when it encounters most unsupported features.
   * </p>
   * <p>
   * Non visual feature data, such as <code>atom:author</code> and <code>ExtendedData</code>
   * is exposed via an instance of {@link KmlFeatureData}, which is added to each {@link Entity}
   * under the <code>kml</code> property.
   * </p>
   *
   * @alias KmlDataSource
   * @constructor
   *
   * @param {KmlDataSource.ConstructorOptions} [options] Object describing initialization options
   *
   * @see {@link http://www.opengeospatial.org/standards/kml/|Open Geospatial Consortium KML Standard}
   * @see {@link https://developers.google.com/kml/|Google KML Documentation}
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=KML.html|Cesium Sandcastle KML Demo}
   *
   * @example
   * const viewer = new Cesium.Viewer('cesiumContainer');
   * viewer.dataSources.add(Cesium.KmlDataSource.load('../../SampleData/facilities.kmz',
   *      {
   *           camera: viewer.scene.camera,
   *           canvas: viewer.scene.canvas
   *      })
   * );
   */
  function KmlDataSource(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const camera = options.camera;
    const canvas = options.canvas;

    this._changed = new Event();
    this._error = new Event();
    this._loading = new Event();
    this._refresh = new Event();
    this._unsupportedNode = new Event();

    this._clock = undefined;
    this._entityCollection = new EntityCollection(this);
    this._name = undefined;
    this._isLoading = false;
    this._pinBuilder = new PinBuilder();
    this._networkLinks = new AssociativeArray();
    this._entityCluster = new EntityCluster();

    /**
     * The current size of this Canvas will be used to populate the Link parameters
     * for client height and width.
     *
     * @type {HTMLCanvasElement | undefined}
     */
    this.canvas = canvas;

    /**
     * The position and orientation of this {@link Camera} will be used to
     * populate various camera parameters when making network requests.
     * Camera movement will determine when to trigger NetworkLink refresh if
     * <code>viewRefreshMode</code> is <code>onStop</code>.
     *
     * @type {Camera | undefined}
     */
    this.camera = camera;

    this._lastCameraView = {
      position: defined(camera) ? Cartesian3.clone(camera.positionWC) : undefined,
      direction: defined(camera)
        ? Cartesian3.clone(camera.directionWC)
        : undefined,
      up: defined(camera) ? Cartesian3.clone(camera.upWC) : undefined,
      bbox: defined(camera)
        ? camera.computeViewRectangle()
        : Rectangle.clone(Rectangle.MAX_VALUE),
    };

    this._ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);

    // User specified credit
    let credit = options.credit;
    if (typeof credit === "string") {
      credit = new Credit(credit);
    }
    this._credit = credit;

    // Create a list of Credit's from the resource that the user can't remove
    this._resourceCredits = [];

    this._kmlTours = [];

    this._screenOverlays = [];
  }

  /**
   * Creates a Promise to a new instance loaded with the provided KML data.
   *
   * @param {Resource|String|Document|Blob} data A url, parsed KML document, or Blob containing binary KMZ data or a parsed KML document.
   * @param {KmlDataSource.ConstructorOptions} [options] An object specifying configuration options
   *
   * @returns {Promise.<KmlDataSource>} A promise that will resolve to a new KmlDataSource instance once the KML is loaded.
   */
  KmlDataSource.load = function (data, options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const dataSource = new KmlDataSource(options);
    return dataSource.load(data, options);
  };

  Object.defineProperties(KmlDataSource.prototype, {
    /**
     * Gets or sets a human-readable name for this instance.
     * This will be automatically be set to the KML document name on load.
     * @memberof KmlDataSource.prototype
     * @type {String}
     */
    name: {
      get: function () {
        return this._name;
      },
      set: function (value) {
        if (this._name !== value) {
          this._name = value;
          this._changed.raiseEvent(this);
        }
      },
    },
    /**
     * Gets the clock settings defined by the loaded KML. This represents the total
     * availability interval for all time-dynamic data. If the KML does not contain
     * time-dynamic data, this value is undefined.
     * @memberof KmlDataSource.prototype
     * @type {DataSourceClock}
     */
    clock: {
      get: function () {
        return this._clock;
      },
    },
    /**
     * Gets the collection of {@link Entity} instances.
     * @memberof KmlDataSource.prototype
     * @type {EntityCollection}
     */
    entities: {
      get: function () {
        return this._entityCollection;
      },
    },
    /**
     * Gets a value indicating if the data source is currently loading data.
     * @memberof KmlDataSource.prototype
     * @type {Boolean}
     */
    isLoading: {
      get: function () {
        return this._isLoading;
      },
    },
    /**
     * Gets an event that will be raised when the underlying data changes.
     * @memberof KmlDataSource.prototype
     * @type {Event}
     */
    changedEvent: {
      get: function () {
        return this._changed;
      },
    },
    /**
     * Gets an event that will be raised if an error is encountered during processing.
     * @memberof KmlDataSource.prototype
     * @type {Event}
     */
    errorEvent: {
      get: function () {
        return this._error;
      },
    },
    /**
     * Gets an event that will be raised when the data source either starts or stops loading.
     * @memberof KmlDataSource.prototype
     * @type {Event}
     */
    loadingEvent: {
      get: function () {
        return this._loading;
      },
    },
    /**
     * Gets an event that will be raised when the data source refreshes a network link.
     * @memberof KmlDataSource.prototype
     * @type {Event}
     */
    refreshEvent: {
      get: function () {
        return this._refresh;
      },
    },
    /**
     * Gets an event that will be raised when the data source finds an unsupported node type.
     * @memberof KmlDataSource.prototype
     * @type {Event}
     */
    unsupportedNodeEvent: {
      get: function () {
        return this._unsupportedNode;
      },
    },
    /**
     * Gets whether or not this data source should be displayed.
     * @memberof KmlDataSource.prototype
     * @type {Boolean}
     */
    show: {
      get: function () {
        return this._entityCollection.show;
      },
      set: function (value) {
        this._entityCollection.show = value;
      },
    },

    /**
     * Gets or sets the clustering options for this data source. This object can be shared between multiple data sources.
     *
     * @memberof KmlDataSource.prototype
     * @type {EntityCluster}
     */
    clustering: {
      get: function () {
        return this._entityCluster;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value must be defined.");
        }
        //>>includeEnd('debug');
        this._entityCluster = value;
      },
    },
    /**
     * Gets the credit that will be displayed for the data source
     * @memberof KmlDataSource.prototype
     * @type {Credit}
     */
    credit: {
      get: function () {
        return this._credit;
      },
    },
    /**
     * Gets the KML Tours that are used to guide the camera to specified destinations on given time intervals.
     * @memberof KmlDataSource.prototype
     * @type {KmlTour[]}
     */
    kmlTours: {
      get: function () {
        return this._kmlTours;
      },
    },
  });

  /**
   * Asynchronously loads the provided KML data, replacing any existing data.
   *
   * @param {Resource|String|Document|Blob} data A url, parsed KML document, or Blob containing binary KMZ data or a parsed KML document.
   * @param {KmlDataSource.LoadOptions} [options] An object specifying configuration options
   *
   * @returns {Promise.<KmlDataSource>} A promise that will resolve to this instances once the KML is loaded.
   */
  KmlDataSource.prototype.load = function (data, options) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(data)) {
      throw new DeveloperError("data is required.");
    }
    //>>includeEnd('debug');

    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    DataSource.setLoading(this, true);

    const oldName = this._name;
    this._name = undefined;
    this._clampToGround = defaultValue(options.clampToGround, false);

    const that = this;
    return load(this, this._entityCollection, data, options)
      .then(function () {
        let clock;

        const availability = that._entityCollection.computeAvailability();

        let start = availability.start;
        let stop = availability.stop;
        const isMinStart = JulianDate.equals(start, Iso8601.MINIMUM_VALUE);
        const isMaxStop = JulianDate.equals(stop, Iso8601.MAXIMUM_VALUE);
        if (!isMinStart || !isMaxStop) {
          let date;

          //If start is min time just start at midnight this morning, local time
          if (isMinStart) {
            date = new Date();
            date.setHours(0, 0, 0, 0);
            start = JulianDate.fromDate(date);
          }

          //If stop is max value just stop at midnight tonight, local time
          if (isMaxStop) {
            date = new Date();
            date.setHours(24, 0, 0, 0);
            stop = JulianDate.fromDate(date);
          }

          clock = new DataSourceClock();
          clock.startTime = start;
          clock.stopTime = stop;
          clock.currentTime = JulianDate.clone(start);
          clock.clockRange = ClockRange$1.LOOP_STOP;
          clock.clockStep = ClockStep$1.SYSTEM_CLOCK_MULTIPLIER;
          clock.multiplier = Math.round(
            Math.min(
              Math.max(JulianDate.secondsDifference(stop, start) / 60, 1),
              3.15569e7
            )
          );
        }

        let changed = false;
        if (clock !== that._clock) {
          that._clock = clock;
          changed = true;
        }

        if (oldName !== that._name) {
          changed = true;
        }

        if (changed) {
          that._changed.raiseEvent(that);
        }

        DataSource.setLoading(that, false);

        return that;
      })
      .catch(function (error) {
        DataSource.setLoading(that, false);
        that._error.raiseEvent(that, error);
        console.log(error);
        return Promise.reject(error);
      });
  };

  /**
   * Cleans up any non-entity elements created by the data source. Currently this only affects ScreenOverlay elements.
   */
  KmlDataSource.prototype.destroy = function () {
    while (this._screenOverlays.length > 0) {
      const elem = this._screenOverlays.pop();
      elem.remove();
    }
  };

  function mergeAvailabilityWithParent(child) {
    const parent = child.parent;
    if (defined(parent)) {
      const parentAvailability = parent.availability;
      if (defined(parentAvailability)) {
        const childAvailability = child.availability;
        if (defined(childAvailability)) {
          childAvailability.intersect(parentAvailability);
        } else {
          child.availability = parentAvailability;
        }
      }
    }
  }

  function getNetworkLinkUpdateCallback(
    dataSource,
    networkLink,
    newEntityCollection,
    networkLinks,
    processedHref
  ) {
    return function (rootElement) {
      if (!networkLinks.contains(networkLink.id)) {
        // Got into the odd case where a parent network link was updated while a child
        //  network link update was in flight, so just throw it away.
        return;
      }
      let remove = false;
      const networkLinkControl = queryFirstNode(
        rootElement,
        "NetworkLinkControl",
        namespaces.kml
      );
      const hasNetworkLinkControl = defined(networkLinkControl);

      let minRefreshPeriod = 0;
      if (hasNetworkLinkControl) {
        if (
          defined(queryFirstNode(networkLinkControl, "Update", namespaces.kml))
        ) {
          oneTimeWarning(
            "kml-networkLinkControl-update",
            "KML - NetworkLinkControl updates aren't supported."
          );
          networkLink.updating = false;
          networkLinks.remove(networkLink.id);
          return;
        }
        networkLink.cookie = queryToObject(
          defaultValue(
            queryStringValue(networkLinkControl, "cookie", namespaces.kml),
            ""
          )
        );
        minRefreshPeriod = defaultValue(
          queryNumericValue(
            networkLinkControl,
            "minRefreshPeriod",
            namespaces.kml
          ),
          0
        );
      }

      const now = JulianDate.now();
      const refreshMode = networkLink.refreshMode;
      if (refreshMode === RefreshMode.INTERVAL) {
        if (defined(networkLinkControl)) {
          networkLink.time = Math.max(minRefreshPeriod, networkLink.time);
        }
      } else if (refreshMode === RefreshMode.EXPIRE) {
        let expires;
        if (defined(networkLinkControl)) {
          expires = queryStringValue(
            networkLinkControl,
            "expires",
            namespaces.kml
          );
        }
        if (defined(expires)) {
          try {
            const date = JulianDate.fromIso8601(expires);
            const diff = JulianDate.secondsDifference(date, now);
            if (diff > 0 && diff < minRefreshPeriod) {
              JulianDate.addSeconds(now, minRefreshPeriod, date);
            }
            networkLink.time = date;
          } catch (e) {
            oneTimeWarning(
              "kml-networkLinkControl-expires",
              "KML - NetworkLinkControl expires is not a valid date"
            );
            remove = true;
          }
        } else {
          oneTimeWarning(
            "kml-refreshMode-onExpire",
            "KML - refreshMode of onExpire requires the NetworkLinkControl to have an expires element"
          );
          remove = true;
        }
      }

      const networkLinkEntity = networkLink.entity;
      const entityCollection = dataSource._entityCollection;
      const newEntities = newEntityCollection.values;

      function removeChildren(entity) {
        entityCollection.remove(entity);
        const children = entity._children;
        const count = children.length;
        for (let i = 0; i < count; ++i) {
          removeChildren(children[i]);
        }
      }

      // Remove old entities
      entityCollection.suspendEvents();
      const entitiesCopy = entityCollection.values.slice();
      let i;
      for (i = 0; i < entitiesCopy.length; ++i) {
        const entityToRemove = entitiesCopy[i];
        if (entityToRemove.parent === networkLinkEntity) {
          entityToRemove.parent = undefined;
          removeChildren(entityToRemove);
        }
      }
      entityCollection.resumeEvents();

      // Add new entities
      entityCollection.suspendEvents();
      for (i = 0; i < newEntities.length; i++) {
        const newEntity = newEntities[i];
        if (!defined(newEntity.parent)) {
          newEntity.parent = networkLinkEntity;
          mergeAvailabilityWithParent(newEntity);
        }
        entityCollection.add(newEntity);
      }
      entityCollection.resumeEvents();

      // No refresh information remove it, otherwise update lastUpdate time
      if (remove) {
        networkLinks.remove(networkLink.id);
      } else {
        networkLink.lastUpdated = now;
      }

      const availability = entityCollection.computeAvailability();

      const start = availability.start;
      const stop = availability.stop;
      const isMinStart = JulianDate.equals(start, Iso8601.MINIMUM_VALUE);
      const isMaxStop = JulianDate.equals(stop, Iso8601.MAXIMUM_VALUE);
      if (!isMinStart || !isMaxStop) {
        const clock = dataSource._clock;

        if (clock.startTime !== start || clock.stopTime !== stop) {
          clock.startTime = start;
          clock.stopTime = stop;
          dataSource._changed.raiseEvent(dataSource);
        }
      }

      networkLink.updating = false;
      networkLink.needsUpdate = false;
      dataSource._refresh.raiseEvent(
        dataSource,
        processedHref.getUrlComponent(true)
      );
    };
  }

  const entitiesToIgnore = new AssociativeArray();

  /**
   * Updates any NetworkLink that require updating.
   *
   * @param {JulianDate} time The simulation time.
   * @returns {Boolean} True if this data source is ready to be displayed at the provided time, false otherwise.
   */
  KmlDataSource.prototype.update = function (time) {
    const networkLinks = this._networkLinks;
    if (networkLinks.length === 0) {
      return true;
    }

    const now = JulianDate.now();
    const that = this;

    entitiesToIgnore.removeAll();

    function recurseIgnoreEntities(entity) {
      const children = entity._children;
      const count = children.length;
      for (let i = 0; i < count; ++i) {
        const child = children[i];
        entitiesToIgnore.set(child.id, child);
        recurseIgnoreEntities(child);
      }
    }

    let cameraViewUpdate = false;
    const lastCameraView = this._lastCameraView;
    const camera = this.camera;
    if (
      defined(camera) &&
      !(
        camera.positionWC.equalsEpsilon(
          lastCameraView.position,
          CesiumMath.EPSILON7
        ) &&
        camera.directionWC.equalsEpsilon(
          lastCameraView.direction,
          CesiumMath.EPSILON7
        ) &&
        camera.upWC.equalsEpsilon(lastCameraView.up, CesiumMath.EPSILON7)
      )
    ) {
      // Camera has changed so update the last view
      lastCameraView.position = Cartesian3.clone(camera.positionWC);
      lastCameraView.direction = Cartesian3.clone(camera.directionWC);
      lastCameraView.up = Cartesian3.clone(camera.upWC);
      lastCameraView.bbox = camera.computeViewRectangle();
      cameraViewUpdate = true;
    }

    const newNetworkLinks = new AssociativeArray();
    let changed = false;
    networkLinks.values.forEach(function (networkLink) {
      const entity = networkLink.entity;
      if (entitiesToIgnore.contains(entity.id)) {
        return;
      }

      if (!networkLink.updating) {
        let doUpdate = false;
        if (networkLink.refreshMode === RefreshMode.INTERVAL) {
          if (
            JulianDate.secondsDifference(now, networkLink.lastUpdated) >
            networkLink.time
          ) {
            doUpdate = true;
          }
        } else if (networkLink.refreshMode === RefreshMode.EXPIRE) {
          if (JulianDate.greaterThan(now, networkLink.time)) {
            doUpdate = true;
          }
        } else if (networkLink.refreshMode === RefreshMode.STOP) {
          if (cameraViewUpdate) {
            networkLink.needsUpdate = true;
            networkLink.cameraUpdateTime = now;
          }

          if (
            networkLink.needsUpdate &&
            JulianDate.secondsDifference(now, networkLink.cameraUpdateTime) >=
              networkLink.time
          ) {
            doUpdate = true;
          }
        }

        if (doUpdate) {
          recurseIgnoreEntities(entity);
          networkLink.updating = true;
          const newEntityCollection = new EntityCollection();
          const href = networkLink.href.clone();

          href.setQueryParameters(networkLink.cookie);
          const ellipsoid = defaultValue(that._ellipsoid, Ellipsoid.WGS84);
          processNetworkLinkQueryString(
            href,
            that.camera,
            that.canvas,
            networkLink.viewBoundScale,
            lastCameraView.bbox,
            ellipsoid
          );

          load(that, newEntityCollection, href, {
            context: entity.id,
          })
            .then(
              getNetworkLinkUpdateCallback(
                that,
                networkLink,
                newEntityCollection,
                newNetworkLinks,
                href
              )
            )
            .catch(function (error) {
              const msg = `NetworkLink ${networkLink.href} refresh failed: ${error}`;
              console.log(msg);
              that._error.raiseEvent(that, msg);
            });
          changed = true;
        }
      }
      newNetworkLinks.set(networkLink.id, networkLink);
    });

    if (changed) {
      this._networkLinks = newNetworkLinks;
      this._changed.raiseEvent(this);
    }

    return true;
  };

  /**
   * Contains KML Feature data loaded into the <code>Entity.kml</code> property by {@link KmlDataSource}.
   * @alias KmlFeatureData
   * @constructor
   */
  function KmlFeatureData() {
    /**
     * @typedef KmlFeatureData.Author
     * @type {Object}
     * @property {String} name Gets the name.
     * @property {String} uri Gets the URI.
     * @property {Number} age Gets the email.
     */

    /**
     * Gets the atom syndication format author field.
     * @type {KmlFeatureData.Author}
     */
    this.author = {
      name: undefined,
      uri: undefined,
      email: undefined,
    };

    /**
     * @typedef KmlFeatureData.Link
     * @type {Object}
     * @property {String} href Gets the href.
     * @property {String} hreflang Gets the language of the linked resource.
     * @property {String} rel Gets the link relation.
     * @property {String} type Gets the link type.
     * @property {String} title Gets the link title.
     * @property {String} length Gets the link length.
     */

    /**
     * Gets the link.
     * @type {KmlFeatureData.Link}
     */
    this.link = {
      href: undefined,
      hreflang: undefined,
      rel: undefined,
      type: undefined,
      title: undefined,
      length: undefined,
    };

    /**
     * Gets the unstructured address field.
     * @type {String}
     */
    this.address = undefined;
    /**
     * Gets the phone number.
     * @type {String}
     */
    this.phoneNumber = undefined;
    /**
     * Gets the snippet.
     * @type {String}
     */
    this.snippet = undefined;
    /**
     * Gets the extended data, parsed into a JSON object.
     * Currently only the <code>Data</code> property is supported.
     * <code>SchemaData</code> and custom data are ignored.
     * @type {String}
     */
    this.extendedData = undefined;
  }

  // For testing
  KmlDataSource._DeferredLoading = DeferredLoading;
  KmlDataSource._getTimestamp = getTimestamp$1;

  /**
   * Defines the interface for visualizers. Visualizers are plug-ins to
   * {@link DataSourceDisplay} that render data associated with
   * {@link DataSource} instances.
   * This object is an interface for documentation purposes and is not intended
   * to be instantiated directly.
   * @alias Visualizer
   * @constructor
   *
   * @see BillboardVisualizer
   * @see LabelVisualizer
   * @see ModelVisualizer
   * @see PathVisualizer
   * @see PointVisualizer
   * @see GeometryVisualizer
   */
  function Visualizer() {
    DeveloperError.throwInstantiationError();
  }

  /**
   * Updates the visualization to the provided time.
   * @function
   *
   * @param {JulianDate} time The time.
   *
   * @returns {Boolean} True if the display was updated to the provided time,
   * false if the visualizer is waiting for an asynchronous operation to
   * complete before data can be updated.
   */
  Visualizer.prototype.update = DeveloperError.throwInstantiationError;

  /**
   * Computes a bounding sphere which encloses the visualization produced for the specified entity.
   * The bounding sphere is in the fixed frame of the scene's globe.
   *
   * @param {Entity} entity The entity whose bounding sphere to compute.
   * @param {BoundingSphere} result The bounding sphere onto which to store the result.
   * @returns {BoundingSphereState} BoundingSphereState.DONE if the result contains the bounding sphere,
   *                       BoundingSphereState.PENDING if the result is still being computed, or
   *                       BoundingSphereState.FAILED if the entity has no visualization in the current scene.
   * @private
   */
  Visualizer.prototype.getBoundingSphere = DeveloperError.throwInstantiationError;

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * @function
   *
   * @returns {Boolean} True if this object was destroyed; otherwise, false.
   */
  Visualizer.prototype.isDestroyed = DeveloperError.throwInstantiationError;

  /**
   * Removes all visualization and cleans up any resources associated with this instance.
   * @function
   */
  Visualizer.prototype.destroy = DeveloperError.throwInstantiationError;

  const BILLBOARD_SIZE = 32;
  const kmlNamespace = "http://www.opengis.net/kml/2.2";
  const gxNamespace = "http://www.google.com/kml/ext/2.2";
  const xmlnsNamespace = "http://www.w3.org/2000/xmlns/";

  //
  // Handles files external to the KML (eg. textures and models)
  //
  function ExternalFileHandler(modelCallback) {
    this._files = {};
    this._promises = [];
    this._count = 0;
    this._modelCallback = modelCallback;
  }

  const imageTypeRegex = /^data:image\/([^,;]+)/;
  ExternalFileHandler.prototype.texture = function (texture) {
    const that = this;
    let filename;

    if (typeof texture === "string" || texture instanceof Resource) {
      texture = Resource.createIfNeeded(texture);
      if (!texture.isDataUri) {
        return texture.url;
      }

      // If its a data URI try and get the correct extension and then fetch the blob
      const regexResult = texture.url.match(imageTypeRegex);
      filename = `texture_${++this._count}`;
      if (defined(regexResult)) {
        filename += `.${regexResult[1]}`;
      }

      const promise = texture.fetchBlob().then(function (blob) {
        that._files[filename] = blob;
      });

      this._promises.push(promise);

      return filename;
    }

    if (texture instanceof HTMLCanvasElement) {
      const deferred = defer();
      this._promises.push(deferred.promise);

      filename = `texture_${++this._count}.png`;
      texture.toBlob(function (blob) {
        that._files[filename] = blob;
        deferred.resolve();
      });

      return filename;
    }

    return "";
  };

  function getModelBlobHander(that, filename) {
    return function (blob) {
      that._files[filename] = blob;
    };
  }

  ExternalFileHandler.prototype.model = function (model, time) {
    const modelCallback = this._modelCallback;
    if (!defined(modelCallback)) {
      throw new RuntimeError(
        "Encountered a model entity while exporting to KML, but no model callback was supplied."
      );
    }

    const externalFiles = {};
    const url = modelCallback(model, time, externalFiles);

    // Iterate through external files and add them to our list once the promise resolves
    for (const filename in externalFiles) {
      if (externalFiles.hasOwnProperty(filename)) {
        const promise = Promise.resolve(externalFiles[filename]);
        this._promises.push(promise);

        promise.then(getModelBlobHander(this, filename));
      }
    }

    return url;
  };

  Object.defineProperties(ExternalFileHandler.prototype, {
    promise: {
      get: function () {
        return Promise.all(this._promises);
      },
    },
    files: {
      get: function () {
        return this._files;
      },
    },
  });

  //
  // Handles getting values from properties taking the desired time and default values into account
  //
  function ValueGetter(time) {
    this._time = time;
  }

  ValueGetter.prototype.get = function (property, defaultVal, result) {
    let value;
    if (defined(property)) {
      value = defined(property.getValue)
        ? property.getValue(this._time, result)
        : property;
    }

    return defaultValue(value, defaultVal);
  };

  ValueGetter.prototype.getColor = function (property, defaultVal) {
    const result = this.get(property, defaultVal);
    if (defined(result)) {
      return colorToString(result);
    }
  };

  ValueGetter.prototype.getMaterialType = function (property) {
    if (!defined(property)) {
      return;
    }

    return property.getType(this._time);
  };

  //
  // Caches styles so we don't generate a ton of duplicate styles
  //
  function StyleCache() {
    this._ids = {};
    this._styles = {};
    this._count = 0;
  }

  StyleCache.prototype.get = function (element) {
    const ids = this._ids;
    const key = element.innerHTML;
    if (defined(ids[key])) {
      return ids[key];
    }

    let styleId = `style-${++this._count}`;
    element.setAttribute("id", styleId);

    // Store with #
    styleId = `#${styleId}`;
    ids[key] = styleId;
    this._styles[key] = element;

    return styleId;
  };

  StyleCache.prototype.save = function (parentElement) {
    const styles = this._styles;

    const firstElement = parentElement.childNodes[0];
    for (const key in styles) {
      if (styles.hasOwnProperty(key)) {
        parentElement.insertBefore(styles[key], firstElement);
      }
    }
  };

  //
  // Manages the generation of IDs because an entity may have geometry and a Folder for children
  //
  function IdManager() {
    this._ids = {};
  }

  IdManager.prototype.get = function (id) {
    if (!defined(id)) {
      return this.get(createGuid());
    }

    const ids = this._ids;
    if (!defined(ids[id])) {
      ids[id] = 0;
      return id;
    }

    return `${id.toString()}-${++ids[id]}`;
  };

  /**
   * @typedef exportKmlResultKml
   * @type {Object}
   * @property {String} kml The generated KML.
   * @property {Object.<string, Blob>} externalFiles An object dictionary of external files
   */

  /**
   * @typedef exportKmlResultKmz
   * @type {Object}
   * @property {Blob} kmz The generated kmz file.
   */

  /**
   * Exports an EntityCollection as a KML document. Only Point, Billboard, Model, Path, Polygon, Polyline geometries
   * will be exported. Note that there is not a 1 to 1 mapping of Entity properties to KML Feature properties. For
   * example, entity properties that are time dynamic but cannot be dynamic in KML are exported with their values at
   * options.time or the beginning of the EntityCollection's time interval if not specified. For time-dynamic properties
   * that are supported in KML, we use the samples if it is a {@link SampledProperty} otherwise we sample the value using
   * the options.sampleDuration. Point, Billboard, Model and Path geometries with time-dynamic positions will be exported
   * as gx:Track Features. Not all Materials are representable in KML, so for more advanced Materials just the primary
   * color is used. Canvas objects are exported as PNG images.
   *
   * @function exportKml
   *
   * @param {Object} options An object with the following properties:
   * @param {EntityCollection} options.entities The EntityCollection to export as KML.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid for the output file.
   * @param {exportKmlModelCallback} [options.modelCallback] A callback that will be called with a {@link ModelGraphics} instance and should return the URI to use in the KML. Required if a model exists in the entity collection.
   * @param {JulianDate} [options.time=entities.computeAvailability().start] The time value to use to get properties that are not time varying in KML.
   * @param {TimeInterval} [options.defaultAvailability=entities.computeAvailability()] The interval that will be sampled if an entity doesn't have an availability.
   * @param {Number} [options.sampleDuration=60] The number of seconds to sample properties that are varying in KML.
   * @param {Boolean} [options.kmz=false] If true KML and external files will be compressed into a kmz file.
   *
   * @returns {Promise<exportKmlResultKml|exportKmlResultKmz>} A promise that resolved to an object containing the KML string and a dictionary of external file blobs, or a kmz file as a blob if options.kmz is true.
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Export%20KML.html|Cesium Sandcastle KML Export Demo}
   * @example
   * Cesium.exportKml({
   *      entities: entityCollection
   *  })
   *   .then(function(result) {
   *     // The XML string is in result.kml
   *
   *     const externalFiles = result.externalFiles
   *     for(const file in externalFiles) {
   *       // file is the name of the file used in the KML document as the href
   *       // externalFiles[file] is a blob with the contents of the file
   *     }
   *   });
   *
   */
  function exportKml(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const entities = options.entities;
    const kmz = defaultValue(options.kmz, false);

    //>>includeStart('debug', pragmas.debug);
    if (!defined(entities)) {
      throw new DeveloperError("entities is required.");
    }
    //>>includeEnd('debug');

    // Get the state that is passed around during the recursion
    // This is separated out for testing.
    const state = exportKml._createState(options);

    // Filter EntityCollection so we only have top level entities
    const rootEntities = entities.values.filter(function (entity) {
      return !defined(entity.parent);
    });

    // Add the <Document>
    const kmlDoc = state.kmlDoc;
    const kmlElement = kmlDoc.documentElement;
    kmlElement.setAttributeNS(xmlnsNamespace, "xmlns:gx", gxNamespace);
    const kmlDocumentElement = kmlDoc.createElement("Document");
    kmlElement.appendChild(kmlDocumentElement);

    // Create the KML Hierarchy
    recurseEntities(state, kmlDocumentElement, rootEntities);

    // Write out the <Style> elements
    state.styleCache.save(kmlDocumentElement);

    // Once all the blobs have resolved return the KML string along with the blob collection
    const externalFileHandler = state.externalFileHandler;
    return externalFileHandler.promise.then(function () {
      const serializer = new XMLSerializer();
      const kmlString = serializer.serializeToString(state.kmlDoc);
      if (kmz) {
        return createKmz(kmlString, externalFileHandler.files);
      }

      return {
        kml: kmlString,
        externalFiles: externalFileHandler.files,
      };
    });
  }

  function createKmz(kmlString, externalFiles) {
    const zWorkerUrl = buildModuleUrl("ThirdParty/Workers/z-worker-pako.js");
    zipNoWorker.configure({
      workerScripts: {
        deflate: [zWorkerUrl, "./pako_deflate.min.js"],
        inflate: [zWorkerUrl, "./pako_inflate.min.js"],
      },
    });
    const blobWriter = new zipNoWorker.BlobWriter();
    const writer = new zipNoWorker.ZipWriter(blobWriter);
    // We need to only write one file at a time so the zip doesn't get corrupted
    return writer
      .add("doc.kml", new zipNoWorker.TextReader(kmlString))
      .then(function () {
        const keys = Object.keys(externalFiles);
        return addExternalFilesToZip(writer, keys, externalFiles, 0);
      })
      .then(function () {
        return writer.close();
      })
      .then(function (blob) {
        return {
          kmz: blob,
        };
      });
  }

  function addExternalFilesToZip(writer, keys, externalFiles, index) {
    if (keys.length === index) {
      return;
    }
    const filename = keys[index];
    return writer
      .add(filename, new zipNoWorker.BlobReader(externalFiles[filename]))
      .then(function () {
        return addExternalFilesToZip(writer, keys, externalFiles, index + 1);
      });
  }

  exportKml._createState = function (options) {
    const entities = options.entities;

    const styleCache = new StyleCache();

    // Use the start time as the default because just in case they define
    //  properties with an interval even if they don't change.
    const entityAvailability = entities.computeAvailability();
    const time = defined(options.time) ? options.time : entityAvailability.start;

    // Figure out how we will sample dynamic position properties
    let defaultAvailability = defaultValue(
      options.defaultAvailability,
      entityAvailability
    );
    const sampleDuration = defaultValue(options.sampleDuration, 60);

    // Make sure we don't have infinite availability if we need to sample
    if (defaultAvailability.start === Iso8601.MINIMUM_VALUE) {
      if (defaultAvailability.stop === Iso8601.MAXIMUM_VALUE) {
        // Infinite, so just use the default
        defaultAvailability = new TimeInterval();
      } else {
        // No start time, so just sample 10 times before the stop
        JulianDate.addSeconds(
          defaultAvailability.stop,
          -10 * sampleDuration,
          defaultAvailability.start
        );
      }
    } else if (defaultAvailability.stop === Iso8601.MAXIMUM_VALUE) {
      // No stop time, so just sample 10 times after the start
      JulianDate.addSeconds(
        defaultAvailability.start,
        10 * sampleDuration,
        defaultAvailability.stop
      );
    }

    const externalFileHandler = new ExternalFileHandler(options.modelCallback);

    const kmlDoc = document.implementation.createDocument(kmlNamespace, "kml");
    return {
      kmlDoc: kmlDoc,
      ellipsoid: defaultValue(options.ellipsoid, Ellipsoid.WGS84),
      idManager: new IdManager(),
      styleCache: styleCache,
      externalFileHandler: externalFileHandler,
      time: time,
      valueGetter: new ValueGetter(time),
      sampleDuration: sampleDuration,
      // Wrap it in a TimeIntervalCollection because that is what entity.availability is
      defaultAvailability: new TimeIntervalCollection([defaultAvailability]),
    };
  };

  function recurseEntities(state, parentNode, entities) {
    const kmlDoc = state.kmlDoc;
    const styleCache = state.styleCache;
    const valueGetter = state.valueGetter;
    const idManager = state.idManager;

    const count = entities.length;
    let overlays;
    let geometries;
    let styles;
    for (let i = 0; i < count; ++i) {
      const entity = entities[i];
      overlays = [];
      geometries = [];
      styles = [];

      createPoint(state, entity, geometries, styles);
      createLineString(state, entity.polyline, geometries, styles);
      createPolygon(state, entity.rectangle, geometries, styles, overlays);
      createPolygon(state, entity.polygon, geometries, styles, overlays);
      createModel(state, entity, entity.model, geometries, styles);

      let timeSpan;
      const availability = entity.availability;
      if (defined(availability)) {
        timeSpan = kmlDoc.createElement("TimeSpan");

        if (!JulianDate.equals(availability.start, Iso8601.MINIMUM_VALUE)) {
          timeSpan.appendChild(
            createBasicElementWithText(
              kmlDoc,
              "begin",
              JulianDate.toIso8601(availability.start)
            )
          );
        }

        if (!JulianDate.equals(availability.stop, Iso8601.MAXIMUM_VALUE)) {
          timeSpan.appendChild(
            createBasicElementWithText(
              kmlDoc,
              "end",
              JulianDate.toIso8601(availability.stop)
            )
          );
        }
      }

      for (let overlayIndex = 0; overlayIndex < overlays.length; ++overlayIndex) {
        const overlay = overlays[overlayIndex];

        overlay.setAttribute("id", idManager.get(entity.id));
        overlay.appendChild(
          createBasicElementWithText(kmlDoc, "name", entity.name)
        );
        overlay.appendChild(
          createBasicElementWithText(kmlDoc, "visibility", entity.show)
        );
        overlay.appendChild(
          createBasicElementWithText(kmlDoc, "description", entity.description)
        );

        if (defined(timeSpan)) {
          overlay.appendChild(timeSpan);
        }

        parentNode.appendChild(overlay);
      }

      const geometryCount = geometries.length;
      if (geometryCount > 0) {
        const placemark = kmlDoc.createElement("Placemark");
        placemark.setAttribute("id", idManager.get(entity.id));

        let name = entity.name;
        const labelGraphics = entity.label;
        if (defined(labelGraphics)) {
          const labelStyle = kmlDoc.createElement("LabelStyle");

          // KML only shows the name as a label, so just change the name if we need to show a label
          const text = valueGetter.get(labelGraphics.text);
          name = defined(text) && text.length > 0 ? text : name;

          const color = valueGetter.getColor(labelGraphics.fillColor);
          if (defined(color)) {
            labelStyle.appendChild(
              createBasicElementWithText(kmlDoc, "color", color)
            );
            labelStyle.appendChild(
              createBasicElementWithText(kmlDoc, "colorMode", "normal")
            );
          }

          const scale = valueGetter.get(labelGraphics.scale);
          if (defined(scale)) {
            labelStyle.appendChild(
              createBasicElementWithText(kmlDoc, "scale", scale)
            );
          }

          styles.push(labelStyle);
        }

        placemark.appendChild(createBasicElementWithText(kmlDoc, "name", name));
        placemark.appendChild(
          createBasicElementWithText(kmlDoc, "visibility", entity.show)
        );
        placemark.appendChild(
          createBasicElementWithText(kmlDoc, "description", entity.description)
        );

        if (defined(timeSpan)) {
          placemark.appendChild(timeSpan);
        }

        parentNode.appendChild(placemark);

        const styleCount = styles.length;
        if (styleCount > 0) {
          const style = kmlDoc.createElement("Style");
          for (let styleIndex = 0; styleIndex < styleCount; ++styleIndex) {
            style.appendChild(styles[styleIndex]);
          }

          placemark.appendChild(
            createBasicElementWithText(kmlDoc, "styleUrl", styleCache.get(style))
          );
        }

        if (geometries.length === 1) {
          placemark.appendChild(geometries[0]);
        } else if (geometries.length > 1) {
          const multigeometry = kmlDoc.createElement("MultiGeometry");
          for (
            let geometryIndex = 0;
            geometryIndex < geometryCount;
            ++geometryIndex
          ) {
            multigeometry.appendChild(geometries[geometryIndex]);
          }
          placemark.appendChild(multigeometry);
        }
      }

      const children = entity._children;
      if (children.length > 0) {
        const folderNode = kmlDoc.createElement("Folder");
        folderNode.setAttribute("id", idManager.get(entity.id));
        folderNode.appendChild(
          createBasicElementWithText(kmlDoc, "name", entity.name)
        );
        folderNode.appendChild(
          createBasicElementWithText(kmlDoc, "visibility", entity.show)
        );
        folderNode.appendChild(
          createBasicElementWithText(kmlDoc, "description", entity.description)
        );

        parentNode.appendChild(folderNode);

        recurseEntities(state, folderNode, children);
      }
    }
  }

  const scratchCartesian3$2 = new Cartesian3();
  const scratchCartographic$6 = new Cartographic();
  const scratchJulianDate = new JulianDate();

  function createPoint(state, entity, geometries, styles) {
    const kmlDoc = state.kmlDoc;
    const ellipsoid = state.ellipsoid;
    const valueGetter = state.valueGetter;

    const pointGraphics = defaultValue(entity.billboard, entity.point);
    if (!defined(pointGraphics) && !defined(entity.path)) {
      return;
    }

    // If the point isn't constant then create gx:Track or gx:MultiTrack
    const entityPositionProperty = entity.position;
    if (!entityPositionProperty.isConstant) {
      createTracks(state, entity, pointGraphics, geometries, styles);
      return;
    }

    valueGetter.get(entityPositionProperty, undefined, scratchCartesian3$2);
    const coordinates = createBasicElementWithText(
      kmlDoc,
      "coordinates",
      getCoordinates(scratchCartesian3$2, ellipsoid)
    );

    const pointGeometry = kmlDoc.createElement("Point");

    // Set altitude mode
    const altitudeMode = kmlDoc.createElement("altitudeMode");
    altitudeMode.appendChild(
      getAltitudeMode(state, pointGraphics.heightReference)
    );
    pointGeometry.appendChild(altitudeMode);

    pointGeometry.appendChild(coordinates);
    geometries.push(pointGeometry);

    // Create style
    const iconStyle =
      pointGraphics instanceof BillboardGraphics
        ? createIconStyleFromBillboard(state, pointGraphics)
        : createIconStyleFromPoint(state, pointGraphics);
    styles.push(iconStyle);
  }

  function createTracks(state, entity, pointGraphics, geometries, styles) {
    const kmlDoc = state.kmlDoc;
    const ellipsoid = state.ellipsoid;
    const valueGetter = state.valueGetter;

    let intervals;
    const entityPositionProperty = entity.position;
    let useEntityPositionProperty = true;
    if (entityPositionProperty instanceof CompositePositionProperty) {
      intervals = entityPositionProperty.intervals;
      useEntityPositionProperty = false;
    } else {
      intervals = defaultValue(entity.availability, state.defaultAvailability);
    }

    const isModel = pointGraphics instanceof ModelGraphics;

    let i, j, times;
    const tracks = [];
    for (i = 0; i < intervals.length; ++i) {
      const interval = intervals.get(i);
      let positionProperty = useEntityPositionProperty
        ? entityPositionProperty
        : interval.data;

      const trackAltitudeMode = kmlDoc.createElement("altitudeMode");
      // This is something that KML importing uses to handle clampToGround,
      //  so just extract the internal property and set the altitudeMode.
      if (positionProperty instanceof ScaledPositionProperty) {
        positionProperty = positionProperty._value;
        trackAltitudeMode.appendChild(
          getAltitudeMode(state, HeightReference$1.CLAMP_TO_GROUND)
        );
      } else if (defined(pointGraphics)) {
        trackAltitudeMode.appendChild(
          getAltitudeMode(state, pointGraphics.heightReference)
        );
      } else {
        // Path graphics only, which has no height reference
        trackAltitudeMode.appendChild(
          getAltitudeMode(state, HeightReference$1.NONE)
        );
      }

      const positionTimes = [];
      const positionValues = [];

      if (positionProperty.isConstant) {
        valueGetter.get(positionProperty, undefined, scratchCartesian3$2);
        const constCoordinates = createBasicElementWithText(
          kmlDoc,
          "coordinates",
          getCoordinates(scratchCartesian3$2, ellipsoid)
        );

        // This interval is constant so add a track with the same position
        positionTimes.push(JulianDate.toIso8601(interval.start));
        positionValues.push(constCoordinates);
        positionTimes.push(JulianDate.toIso8601(interval.stop));
        positionValues.push(constCoordinates);
      } else if (positionProperty instanceof SampledPositionProperty) {
        times = positionProperty._property._times;

        for (j = 0; j < times.length; ++j) {
          positionTimes.push(JulianDate.toIso8601(times[j]));
          positionProperty.getValueInReferenceFrame(
            times[j],
            ReferenceFrame$1.FIXED,
            scratchCartesian3$2
          );
          positionValues.push(getCoordinates(scratchCartesian3$2, ellipsoid));
        }
      } else if (positionProperty instanceof SampledProperty) {
        times = positionProperty._times;
        const values = positionProperty._values;

        for (j = 0; j < times.length; ++j) {
          positionTimes.push(JulianDate.toIso8601(times[j]));
          Cartesian3.fromArray(values, j * 3, scratchCartesian3$2);
          positionValues.push(getCoordinates(scratchCartesian3$2, ellipsoid));
        }
      } else {
        const duration = state.sampleDuration;
        interval.start.clone(scratchJulianDate);
        if (!interval.isStartIncluded) {
          JulianDate.addSeconds(scratchJulianDate, duration, scratchJulianDate);
        }

        const stopDate = interval.stop;
        while (JulianDate.lessThan(scratchJulianDate, stopDate)) {
          positionProperty.getValue(scratchJulianDate, scratchCartesian3$2);

          positionTimes.push(JulianDate.toIso8601(scratchJulianDate));
          positionValues.push(getCoordinates(scratchCartesian3$2, ellipsoid));

          JulianDate.addSeconds(scratchJulianDate, duration, scratchJulianDate);
        }

        if (
          interval.isStopIncluded &&
          JulianDate.equals(scratchJulianDate, stopDate)
        ) {
          positionProperty.getValue(scratchJulianDate, scratchCartesian3$2);

          positionTimes.push(JulianDate.toIso8601(scratchJulianDate));
          positionValues.push(getCoordinates(scratchCartesian3$2, ellipsoid));
        }
      }

      const trackGeometry = kmlDoc.createElementNS(gxNamespace, "Track");
      trackGeometry.appendChild(trackAltitudeMode);

      for (let k = 0; k < positionTimes.length; ++k) {
        const when = createBasicElementWithText(kmlDoc, "when", positionTimes[k]);
        const coord = createBasicElementWithText(
          kmlDoc,
          "coord",
          positionValues[k],
          gxNamespace
        );

        trackGeometry.appendChild(when);
        trackGeometry.appendChild(coord);
      }

      if (isModel) {
        trackGeometry.appendChild(createModelGeometry(state, pointGraphics));
      }

      tracks.push(trackGeometry);
    }

    // If one track, then use it otherwise combine into a multitrack
    if (tracks.length === 1) {
      geometries.push(tracks[0]);
    } else if (tracks.length > 1) {
      const multiTrackGeometry = kmlDoc.createElementNS(
        gxNamespace,
        "MultiTrack"
      );

      for (i = 0; i < tracks.length; ++i) {
        multiTrackGeometry.appendChild(tracks[i]);
      }

      geometries.push(multiTrackGeometry);
    }

    // Create style
    if (defined(pointGraphics) && !isModel) {
      const iconStyle =
        pointGraphics instanceof BillboardGraphics
          ? createIconStyleFromBillboard(state, pointGraphics)
          : createIconStyleFromPoint(state, pointGraphics);
      styles.push(iconStyle);
    }

    // See if we have a line that needs to be drawn
    const path = entity.path;
    if (defined(path)) {
      const width = valueGetter.get(path.width);
      const material = path.material;
      if (defined(material) || defined(width)) {
        const lineStyle = kmlDoc.createElement("LineStyle");
        if (defined(width)) {
          lineStyle.appendChild(
            createBasicElementWithText(kmlDoc, "width", width)
          );
        }

        processMaterial(state, material, lineStyle);
        styles.push(lineStyle);
      }
    }
  }

  function createIconStyleFromPoint(state, pointGraphics) {
    const kmlDoc = state.kmlDoc;
    const valueGetter = state.valueGetter;

    const iconStyle = kmlDoc.createElement("IconStyle");

    const color = valueGetter.getColor(pointGraphics.color);
    if (defined(color)) {
      iconStyle.appendChild(createBasicElementWithText(kmlDoc, "color", color));
      iconStyle.appendChild(
        createBasicElementWithText(kmlDoc, "colorMode", "normal")
      );
    }

    const pixelSize = valueGetter.get(pointGraphics.pixelSize);
    if (defined(pixelSize)) {
      iconStyle.appendChild(
        createBasicElementWithText(kmlDoc, "scale", pixelSize / BILLBOARD_SIZE)
      );
    }

    return iconStyle;
  }

  function createIconStyleFromBillboard(state, billboardGraphics) {
    const kmlDoc = state.kmlDoc;
    const valueGetter = state.valueGetter;
    const externalFileHandler = state.externalFileHandler;

    const iconStyle = kmlDoc.createElement("IconStyle");

    let image = valueGetter.get(billboardGraphics.image);
    if (defined(image)) {
      image = externalFileHandler.texture(image);

      const icon = kmlDoc.createElement("Icon");
      icon.appendChild(createBasicElementWithText(kmlDoc, "href", image));

      const imageSubRegion = valueGetter.get(billboardGraphics.imageSubRegion);
      if (defined(imageSubRegion)) {
        icon.appendChild(
          createBasicElementWithText(kmlDoc, "x", imageSubRegion.x, gxNamespace)
        );
        icon.appendChild(
          createBasicElementWithText(kmlDoc, "y", imageSubRegion.y, gxNamespace)
        );
        icon.appendChild(
          createBasicElementWithText(
            kmlDoc,
            "w",
            imageSubRegion.width,
            gxNamespace
          )
        );
        icon.appendChild(
          createBasicElementWithText(
            kmlDoc,
            "h",
            imageSubRegion.height,
            gxNamespace
          )
        );
      }

      iconStyle.appendChild(icon);
    }

    const color = valueGetter.getColor(billboardGraphics.color);
    if (defined(color)) {
      iconStyle.appendChild(createBasicElementWithText(kmlDoc, "color", color));
      iconStyle.appendChild(
        createBasicElementWithText(kmlDoc, "colorMode", "normal")
      );
    }

    let scale = valueGetter.get(billboardGraphics.scale);
    if (defined(scale)) {
      iconStyle.appendChild(createBasicElementWithText(kmlDoc, "scale", scale));
    }

    const pixelOffset = valueGetter.get(billboardGraphics.pixelOffset);
    if (defined(pixelOffset)) {
      scale = defaultValue(scale, 1.0);

      Cartesian2.divideByScalar(pixelOffset, scale, pixelOffset);

      const width = valueGetter.get(billboardGraphics.width, BILLBOARD_SIZE);
      const height = valueGetter.get(billboardGraphics.height, BILLBOARD_SIZE);

      // KML Hotspots are from the bottom left, but we work from the top left

      // Move to left
      const horizontalOrigin = valueGetter.get(
        billboardGraphics.horizontalOrigin,
        HorizontalOrigin$1.CENTER
      );
      if (horizontalOrigin === HorizontalOrigin$1.CENTER) {
        pixelOffset.x -= width * 0.5;
      } else if (horizontalOrigin === HorizontalOrigin$1.RIGHT) {
        pixelOffset.x -= width;
      }

      // Move to bottom
      const verticalOrigin = valueGetter.get(
        billboardGraphics.verticalOrigin,
        VerticalOrigin$1.CENTER
      );
      if (verticalOrigin === VerticalOrigin$1.TOP) {
        pixelOffset.y += height;
      } else if (verticalOrigin === VerticalOrigin$1.CENTER) {
        pixelOffset.y += height * 0.5;
      }

      const hotSpot = kmlDoc.createElement("hotSpot");
      hotSpot.setAttribute("x", -pixelOffset.x);
      hotSpot.setAttribute("y", pixelOffset.y);
      hotSpot.setAttribute("xunits", "pixels");
      hotSpot.setAttribute("yunits", "pixels");

      iconStyle.appendChild(hotSpot);
    }

    // We can only specify heading so if axis isn't Z, then we skip the rotation
    // GE treats a heading of zero as no heading but can still point north using a 360 degree angle
    let rotation = valueGetter.get(billboardGraphics.rotation);
    const alignedAxis = valueGetter.get(billboardGraphics.alignedAxis);
    if (defined(rotation) && Cartesian3.equals(Cartesian3.UNIT_Z, alignedAxis)) {
      rotation = CesiumMath.toDegrees(-rotation);
      if (rotation === 0) {
        rotation = 360;
      }

      iconStyle.appendChild(
        createBasicElementWithText(kmlDoc, "heading", rotation)
      );
    }

    return iconStyle;
  }

  function createLineString(state, polylineGraphics, geometries, styles) {
    const kmlDoc = state.kmlDoc;
    const ellipsoid = state.ellipsoid;
    const valueGetter = state.valueGetter;

    if (!defined(polylineGraphics)) {
      return;
    }

    const lineStringGeometry = kmlDoc.createElement("LineString");

    // Set altitude mode
    const altitudeMode = kmlDoc.createElement("altitudeMode");
    const clampToGround = valueGetter.get(polylineGraphics.clampToGround, false);
    let altitudeModeText;
    if (clampToGround) {
      lineStringGeometry.appendChild(
        createBasicElementWithText(kmlDoc, "tessellate", true)
      );
      altitudeModeText = kmlDoc.createTextNode("clampToGround");
    } else {
      altitudeModeText = kmlDoc.createTextNode("absolute");
    }
    altitudeMode.appendChild(altitudeModeText);
    lineStringGeometry.appendChild(altitudeMode);

    // Set coordinates
    const positionsProperty = polylineGraphics.positions;
    const cartesians = valueGetter.get(positionsProperty);
    const coordinates = createBasicElementWithText(
      kmlDoc,
      "coordinates",
      getCoordinates(cartesians, ellipsoid)
    );
    lineStringGeometry.appendChild(coordinates);

    // Set draw order
    const zIndex = valueGetter.get(polylineGraphics.zIndex);
    if (clampToGround && defined(zIndex)) {
      lineStringGeometry.appendChild(
        createBasicElementWithText(kmlDoc, "drawOrder", zIndex, gxNamespace)
      );
    }

    geometries.push(lineStringGeometry);

    // Create style
    const lineStyle = kmlDoc.createElement("LineStyle");

    const width = valueGetter.get(polylineGraphics.width);
    if (defined(width)) {
      lineStyle.appendChild(createBasicElementWithText(kmlDoc, "width", width));
    }

    processMaterial(state, polylineGraphics.material, lineStyle);

    styles.push(lineStyle);
  }

  function getRectangleBoundaries(state, rectangleGraphics, extrudedHeight) {
    const kmlDoc = state.kmlDoc;
    const valueGetter = state.valueGetter;

    let height = valueGetter.get(rectangleGraphics.height, 0.0);

    if (extrudedHeight > 0) {
      // We extrude up and KML extrudes down, so if we extrude, set the polygon height to
      // the extruded height so KML will look similar to Cesium
      height = extrudedHeight;
    }

    const coordinatesProperty = rectangleGraphics.coordinates;
    const rectangle = valueGetter.get(coordinatesProperty);

    const coordinateStrings = [];
    const cornerFunction = [
      Rectangle.northeast,
      Rectangle.southeast,
      Rectangle.southwest,
      Rectangle.northwest,
    ];

    for (let i = 0; i < 4; ++i) {
      cornerFunction[i](rectangle, scratchCartographic$6);
      coordinateStrings.push(
        `${CesiumMath.toDegrees(
        scratchCartographic$6.longitude
      )},${CesiumMath.toDegrees(scratchCartographic$6.latitude)},${height}`
      );
    }

    const coordinates = createBasicElementWithText(
      kmlDoc,
      "coordinates",
      coordinateStrings.join(" ")
    );

    const outerBoundaryIs = kmlDoc.createElement("outerBoundaryIs");
    const linearRing = kmlDoc.createElement("LinearRing");
    linearRing.appendChild(coordinates);
    outerBoundaryIs.appendChild(linearRing);

    return [outerBoundaryIs];
  }

  function getLinearRing(state, positions, height, perPositionHeight) {
    const kmlDoc = state.kmlDoc;
    const ellipsoid = state.ellipsoid;

    const coordinateStrings = [];
    const positionCount = positions.length;
    for (let i = 0; i < positionCount; ++i) {
      Cartographic.fromCartesian(positions[i], ellipsoid, scratchCartographic$6);
      coordinateStrings.push(
        `${CesiumMath.toDegrees(
        scratchCartographic$6.longitude
      )},${CesiumMath.toDegrees(scratchCartographic$6.latitude)},${
        perPositionHeight ? scratchCartographic$6.height : height
      }`
      );
    }

    const coordinates = createBasicElementWithText(
      kmlDoc,
      "coordinates",
      coordinateStrings.join(" ")
    );
    const linearRing = kmlDoc.createElement("LinearRing");
    linearRing.appendChild(coordinates);

    return linearRing;
  }

  function getPolygonBoundaries(state, polygonGraphics, extrudedHeight) {
    const kmlDoc = state.kmlDoc;
    const valueGetter = state.valueGetter;

    let height = valueGetter.get(polygonGraphics.height, 0.0);
    const perPositionHeight = valueGetter.get(
      polygonGraphics.perPositionHeight,
      false
    );

    if (!perPositionHeight && extrudedHeight > 0) {
      // We extrude up and KML extrudes down, so if we extrude, set the polygon height to
      // the extruded height so KML will look similar to Cesium
      height = extrudedHeight;
    }

    const boundaries = [];
    const hierarchyProperty = polygonGraphics.hierarchy;
    const hierarchy = valueGetter.get(hierarchyProperty);

    // Polygon hierarchy can sometimes just be an array of positions
    const positions = Array.isArray(hierarchy) ? hierarchy : hierarchy.positions;

    // Polygon boundaries
    const outerBoundaryIs = kmlDoc.createElement("outerBoundaryIs");
    outerBoundaryIs.appendChild(
      getLinearRing(state, positions, height, perPositionHeight)
    );
    boundaries.push(outerBoundaryIs);

    // Hole boundaries
    const holes = hierarchy.holes;
    if (defined(holes)) {
      const holeCount = holes.length;
      for (let i = 0; i < holeCount; ++i) {
        const innerBoundaryIs = kmlDoc.createElement("innerBoundaryIs");
        innerBoundaryIs.appendChild(
          getLinearRing(state, holes[i].positions, height, perPositionHeight)
        );
        boundaries.push(innerBoundaryIs);
      }
    }

    return boundaries;
  }

  function createPolygon(state, geometry, geometries, styles, overlays) {
    const kmlDoc = state.kmlDoc;
    const valueGetter = state.valueGetter;

    if (!defined(geometry)) {
      return;
    }

    // Detect textured quads and use ground overlays instead
    const isRectangle = geometry instanceof RectangleGraphics;
    if (
      isRectangle &&
      valueGetter.getMaterialType(geometry.material) === "Image"
    ) {
      createGroundOverlay(state, geometry, overlays);
      return;
    }

    const polygonGeometry = kmlDoc.createElement("Polygon");

    const extrudedHeight = valueGetter.get(geometry.extrudedHeight, 0.0);
    if (extrudedHeight > 0) {
      polygonGeometry.appendChild(
        createBasicElementWithText(kmlDoc, "extrude", true)
      );
    }

    // Set boundaries
    const boundaries = isRectangle
      ? getRectangleBoundaries(state, geometry, extrudedHeight)
      : getPolygonBoundaries(state, geometry, extrudedHeight);

    const boundaryCount = boundaries.length;
    for (let i = 0; i < boundaryCount; ++i) {
      polygonGeometry.appendChild(boundaries[i]);
    }

    // Set altitude mode
    const altitudeMode = kmlDoc.createElement("altitudeMode");
    altitudeMode.appendChild(getAltitudeMode(state, geometry.heightReference));
    polygonGeometry.appendChild(altitudeMode);

    geometries.push(polygonGeometry);

    // Create style
    const polyStyle = kmlDoc.createElement("PolyStyle");

    const fill = valueGetter.get(geometry.fill, false);
    if (fill) {
      polyStyle.appendChild(createBasicElementWithText(kmlDoc, "fill", fill));
    }

    processMaterial(state, geometry.material, polyStyle);

    const outline = valueGetter.get(geometry.outline, false);
    if (outline) {
      polyStyle.appendChild(
        createBasicElementWithText(kmlDoc, "outline", outline)
      );

      // Outline uses LineStyle
      const lineStyle = kmlDoc.createElement("LineStyle");

      const outlineWidth = valueGetter.get(geometry.outlineWidth, 1.0);
      lineStyle.appendChild(
        createBasicElementWithText(kmlDoc, "width", outlineWidth)
      );

      const outlineColor = valueGetter.getColor(
        geometry.outlineColor,
        Color.BLACK
      );
      lineStyle.appendChild(
        createBasicElementWithText(kmlDoc, "color", outlineColor)
      );
      lineStyle.appendChild(
        createBasicElementWithText(kmlDoc, "colorMode", "normal")
      );

      styles.push(lineStyle);
    }

    styles.push(polyStyle);
  }

  function createGroundOverlay(state, rectangleGraphics, overlays) {
    const kmlDoc = state.kmlDoc;
    const valueGetter = state.valueGetter;
    const externalFileHandler = state.externalFileHandler;

    const groundOverlay = kmlDoc.createElement("GroundOverlay");

    // Set altitude mode
    const altitudeMode = kmlDoc.createElement("altitudeMode");
    altitudeMode.appendChild(
      getAltitudeMode(state, rectangleGraphics.heightReference)
    );
    groundOverlay.appendChild(altitudeMode);

    const height = valueGetter.get(rectangleGraphics.height);
    if (defined(height)) {
      groundOverlay.appendChild(
        createBasicElementWithText(kmlDoc, "altitude", height)
      );
    }

    const rectangle = valueGetter.get(rectangleGraphics.coordinates);
    const latLonBox = kmlDoc.createElement("LatLonBox");
    latLonBox.appendChild(
      createBasicElementWithText(
        kmlDoc,
        "north",
        CesiumMath.toDegrees(rectangle.north)
      )
    );
    latLonBox.appendChild(
      createBasicElementWithText(
        kmlDoc,
        "south",
        CesiumMath.toDegrees(rectangle.south)
      )
    );
    latLonBox.appendChild(
      createBasicElementWithText(
        kmlDoc,
        "east",
        CesiumMath.toDegrees(rectangle.east)
      )
    );
    latLonBox.appendChild(
      createBasicElementWithText(
        kmlDoc,
        "west",
        CesiumMath.toDegrees(rectangle.west)
      )
    );
    groundOverlay.appendChild(latLonBox);

    // We should only end up here if we have an ImageMaterialProperty
    const material = valueGetter.get(rectangleGraphics.material);
    const href = externalFileHandler.texture(material.image);
    const icon = kmlDoc.createElement("Icon");
    icon.appendChild(createBasicElementWithText(kmlDoc, "href", href));
    groundOverlay.appendChild(icon);

    const color = material.color;
    if (defined(color)) {
      groundOverlay.appendChild(
        createBasicElementWithText(kmlDoc, "color", colorToString(material.color))
      );
    }

    overlays.push(groundOverlay);
  }

  function createModelGeometry(state, modelGraphics) {
    const kmlDoc = state.kmlDoc;
    const valueGetter = state.valueGetter;
    const externalFileHandler = state.externalFileHandler;

    const modelGeometry = kmlDoc.createElement("Model");

    const scale = valueGetter.get(modelGraphics.scale);
    if (defined(scale)) {
      const scaleElement = kmlDoc.createElement("scale");
      scaleElement.appendChild(createBasicElementWithText(kmlDoc, "x", scale));
      scaleElement.appendChild(createBasicElementWithText(kmlDoc, "y", scale));
      scaleElement.appendChild(createBasicElementWithText(kmlDoc, "z", scale));
      modelGeometry.appendChild(scaleElement);
    }

    const link = kmlDoc.createElement("Link");
    const uri = externalFileHandler.model(modelGraphics, state.time);

    link.appendChild(createBasicElementWithText(kmlDoc, "href", uri));
    modelGeometry.appendChild(link);

    return modelGeometry;
  }

  function createModel(state, entity, modelGraphics, geometries, styles) {
    const kmlDoc = state.kmlDoc;
    const ellipsoid = state.ellipsoid;
    const valueGetter = state.valueGetter;

    if (!defined(modelGraphics)) {
      return;
    }

    // If the point isn't constant then create gx:Track or gx:MultiTrack
    const entityPositionProperty = entity.position;
    if (!entityPositionProperty.isConstant) {
      createTracks(state, entity, modelGraphics, geometries, styles);
      return;
    }

    const modelGeometry = createModelGeometry(state, modelGraphics);

    // Set altitude mode
    const altitudeMode = kmlDoc.createElement("altitudeMode");
    altitudeMode.appendChild(
      getAltitudeMode(state, modelGraphics.heightReference)
    );
    modelGeometry.appendChild(altitudeMode);

    valueGetter.get(entityPositionProperty, undefined, scratchCartesian3$2);
    Cartographic.fromCartesian(scratchCartesian3$2, ellipsoid, scratchCartographic$6);
    const location = kmlDoc.createElement("Location");
    location.appendChild(
      createBasicElementWithText(
        kmlDoc,
        "longitude",
        CesiumMath.toDegrees(scratchCartographic$6.longitude)
      )
    );
    location.appendChild(
      createBasicElementWithText(
        kmlDoc,
        "latitude",
        CesiumMath.toDegrees(scratchCartographic$6.latitude)
      )
    );
    location.appendChild(
      createBasicElementWithText(kmlDoc, "altitude", scratchCartographic$6.height)
    );
    modelGeometry.appendChild(location);

    geometries.push(modelGeometry);
  }

  function processMaterial(state, materialProperty, style) {
    const kmlDoc = state.kmlDoc;
    const valueGetter = state.valueGetter;

    if (!defined(materialProperty)) {
      return;
    }

    const material = valueGetter.get(materialProperty);
    if (!defined(material)) {
      return;
    }

    let color;
    const type = valueGetter.getMaterialType(materialProperty);
    let outlineColor;
    let outlineWidth;
    switch (type) {
      case "Image":
        // Image materials are only able to be represented on rectangles, so if we make it
        //  here we can't texture a generic polygon or polyline in KML, so just use white.
        color = colorToString(Color.WHITE);
        break;
      case "Color":
      case "Grid":
      case "PolylineGlow":
      case "PolylineArrow":
      case "PolylineDash":
        color = colorToString(material.color);
        break;
      case "PolylineOutline":
        color = colorToString(material.color);

        outlineColor = colorToString(material.outlineColor);
        outlineWidth = material.outlineWidth;
        style.appendChild(
          createBasicElementWithText(
            kmlDoc,
            "outerColor",
            outlineColor,
            gxNamespace
          )
        );
        style.appendChild(
          createBasicElementWithText(
            kmlDoc,
            "outerWidth",
            outlineWidth,
            gxNamespace
          )
        );
        break;
      case "Stripe":
        color = colorToString(material.oddColor);
        break;
    }

    if (defined(color)) {
      style.appendChild(createBasicElementWithText(kmlDoc, "color", color));
      style.appendChild(
        createBasicElementWithText(kmlDoc, "colorMode", "normal")
      );
    }
  }

  function getAltitudeMode(state, heightReferenceProperty) {
    const kmlDoc = state.kmlDoc;
    const valueGetter = state.valueGetter;

    const heightReference = valueGetter.get(
      heightReferenceProperty,
      HeightReference$1.NONE
    );
    let altitudeModeText;
    switch (heightReference) {
      case HeightReference$1.NONE:
        altitudeModeText = kmlDoc.createTextNode("absolute");
        break;
      case HeightReference$1.CLAMP_TO_GROUND:
        altitudeModeText = kmlDoc.createTextNode("clampToGround");
        break;
      case HeightReference$1.RELATIVE_TO_GROUND:
        altitudeModeText = kmlDoc.createTextNode("relativeToGround");
        break;
    }

    return altitudeModeText;
  }

  function getCoordinates(coordinates, ellipsoid) {
    if (!Array.isArray(coordinates)) {
      coordinates = [coordinates];
    }

    const count = coordinates.length;
    const coordinateStrings = [];
    for (let i = 0; i < count; ++i) {
      Cartographic.fromCartesian(coordinates[i], ellipsoid, scratchCartographic$6);
      coordinateStrings.push(
        `${CesiumMath.toDegrees(
        scratchCartographic$6.longitude
      )},${CesiumMath.toDegrees(scratchCartographic$6.latitude)},${
        scratchCartographic$6.height
      }`
      );
    }

    return coordinateStrings.join(" ");
  }

  function createBasicElementWithText(
    kmlDoc,
    elementName,
    elementValue,
    namespace
  ) {
    elementValue = defaultValue(elementValue, "");

    if (typeof elementValue === "boolean") {
      elementValue = elementValue ? "1" : "0";
    }

    // Create element with optional namespace
    const element = defined(namespace)
      ? kmlDoc.createElementNS(namespace, elementName)
      : kmlDoc.createElement(elementName);

    // Wrap value in CDATA section if it contains HTML
    const text =
      elementValue === "string" && elementValue.indexOf("<") !== -1
        ? kmlDoc.createCDATASection(elementValue)
        : kmlDoc.createTextNode(elementValue);

    element.appendChild(text);

    return element;
  }

  function colorToString(color) {
    let result = "";
    const bytes = color.toBytes();
    for (let i = 3; i >= 0; --i) {
      result +=
        bytes[i] < 16 ? `0${bytes[i].toString(16)}` : bytes[i].toString(16);
    }

    return result;
  }

  //This file is automatically rebuilt by the Cesium build process.
  var ViewportQuadVS = "attribute vec4 position;\n\
attribute vec2 textureCoordinates;\n\
varying vec2 v_textureCoordinates;\n\
void main()\n\
{\n\
gl_Position = position;\n\
v_textureCoordinates = textureCoordinates;\n\
}\n\
";

  /**
   * @private
   */
  function ComputeEngine(context) {
    this._context = context;
  }

  let renderStateScratch;
  const drawCommandScratch = new DrawCommand({
    primitiveType: PrimitiveType$1.TRIANGLES,
  });
  const clearCommandScratch = new ClearCommand({
    color: new Color(0.0, 0.0, 0.0, 0.0),
  });

  function createFramebuffer$1(context, outputTexture) {
    return new Framebuffer({
      context: context,
      colorTextures: [outputTexture],
      destroyAttachments: false,
    });
  }

  function createViewportQuadShader(context, fragmentShaderSource) {
    return ShaderProgram.fromCache({
      context: context,
      vertexShaderSource: ViewportQuadVS,
      fragmentShaderSource: fragmentShaderSource,
      attributeLocations: {
        position: 0,
        textureCoordinates: 1,
      },
    });
  }

  function createRenderState$1(width, height) {
    if (
      !defined(renderStateScratch) ||
      renderStateScratch.viewport.width !== width ||
      renderStateScratch.viewport.height !== height
    ) {
      renderStateScratch = RenderState.fromCache({
        viewport: new BoundingRectangle(0, 0, width, height),
      });
    }
    return renderStateScratch;
  }

  ComputeEngine.prototype.execute = function (computeCommand) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("computeCommand", computeCommand);
    //>>includeEnd('debug');

    // This may modify the command's resources, so do error checking afterwards
    if (defined(computeCommand.preExecute)) {
      computeCommand.preExecute(computeCommand);
    }

    //>>includeStart('debug', pragmas.debug);
    if (
      !defined(computeCommand.fragmentShaderSource) &&
      !defined(computeCommand.shaderProgram)
    ) {
      throw new DeveloperError(
        "computeCommand.fragmentShaderSource or computeCommand.shaderProgram is required."
      );
    }

    Check.defined("computeCommand.outputTexture", computeCommand.outputTexture);
    //>>includeEnd('debug');

    const outputTexture = computeCommand.outputTexture;
    const width = outputTexture.width;
    const height = outputTexture.height;

    const context = this._context;
    const vertexArray = defined(computeCommand.vertexArray)
      ? computeCommand.vertexArray
      : context.getViewportQuadVertexArray();
    const shaderProgram = defined(computeCommand.shaderProgram)
      ? computeCommand.shaderProgram
      : createViewportQuadShader(context, computeCommand.fragmentShaderSource);
    const framebuffer = createFramebuffer$1(context, outputTexture);
    const renderState = createRenderState$1(width, height);
    const uniformMap = computeCommand.uniformMap;

    const clearCommand = clearCommandScratch;
    clearCommand.framebuffer = framebuffer;
    clearCommand.renderState = renderState;
    clearCommand.execute(context);

    const drawCommand = drawCommandScratch;
    drawCommand.vertexArray = vertexArray;
    drawCommand.renderState = renderState;
    drawCommand.shaderProgram = shaderProgram;
    drawCommand.uniformMap = uniformMap;
    drawCommand.framebuffer = framebuffer;
    drawCommand.execute(context);

    framebuffer.destroy();

    if (!computeCommand.persists) {
      shaderProgram.destroy();
      if (defined(computeCommand.vertexArray)) {
        vertexArray.destroy();
      }
    }

    if (defined(computeCommand.postExecute)) {
      computeCommand.postExecute(outputTexture);
    }
  };

  ComputeEngine.prototype.isDestroyed = function () {
    return false;
  };

  ComputeEngine.prototype.destroy = function () {
    return destroyObject(this);
  };

  /**
   * The state for a particular rendering pass.  This is used to supplement the state
   * in a command being executed.
   *
   * @private
   * @constructor
   */
  function PassState(context) {
    /**
     * The context used to execute commands for this pass.
     *
     * @type {Context}
     */
    this.context = context;

    /**
     * The framebuffer to render to.  This framebuffer is used unless a {@link DrawCommand}
     * or {@link ClearCommand} explicitly define a framebuffer, which is used for off-screen
     * rendering.
     *
     * @type {Framebuffer}
     * @default undefined
     */
    this.framebuffer = undefined;

    /**
     * When defined, this overrides the blending property of a {@link DrawCommand}'s render state.
     * This is used to, for example, to allow the renderer to turn off blending during the picking pass.
     * <p>
     * When this is <code>undefined</code>, the {@link DrawCommand}'s property is used.
     * </p>
     *
     * @type {Boolean}
     * @default undefined
     */
    this.blendingEnabled = undefined;

    /**
     * When defined, this overrides the scissor test property of a {@link DrawCommand}'s render state.
     * This is used to, for example, to allow the renderer to scissor out the pick region during the picking pass.
     * <p>
     * When this is <code>undefined</code>, the {@link DrawCommand}'s property is used.
     * </p>
     *
     * @type {Object}
     * @default undefined
     */
    this.scissorTest = undefined;

    /**
     * The viewport used when one is not defined by a {@link DrawCommand}'s render state.
     * @type {BoundingRectangle}
     * @default undefined
     */
    this.viewport = undefined;
  }

  /**
   * @private
   */
  function ShaderCache(context) {
    this._context = context;
    this._shaders = {};
    this._numberOfShaders = 0;
    this._shadersToRelease = {};
  }

  Object.defineProperties(ShaderCache.prototype, {
    numberOfShaders: {
      get: function () {
        return this._numberOfShaders;
      },
    },
  });

  /**
       * Returns a shader program from the cache, or creates and caches a new shader program,
       * given the GLSL vertex and fragment shader source and attribute locations.
       * <p>
       * The difference between this and {@link ShaderCache#getShaderProgram}, is this is used to
       * replace an existing reference to a shader program, which is passed as the first argument.
       * </p>
       *
       * @param {Object} options Object with the following properties:
       * @param {ShaderProgram} [options.shaderProgram] The shader program that is being reassigned.
       * @param {String|ShaderSource} options.vertexShaderSource The GLSL source for the vertex shader.
       * @param {String|ShaderSource} options.fragmentShaderSource The GLSL source for the fragment shader.
       * @param {Object} options.attributeLocations Indices for the attribute inputs to the vertex shader.

       * @returns {ShaderProgram} The cached or newly created shader program.
       *
       *
       * @example
       * this._shaderProgram = context.shaderCache.replaceShaderProgram({
       *     shaderProgram : this._shaderProgram,
       *     vertexShaderSource : vs,
       *     fragmentShaderSource : fs,
       *     attributeLocations : attributeLocations
       * });
       *
       * @see ShaderCache#getShaderProgram
       */
  ShaderCache.prototype.replaceShaderProgram = function (options) {
    if (defined(options.shaderProgram)) {
      options.shaderProgram.destroy();
    }

    return this.getShaderProgram(options);
  };

  /**
   * Returns a shader program from the cache, or creates and caches a new shader program,
   * given the GLSL vertex and fragment shader source and attribute locations.
   *
   * @param {Object} options Object with the following properties:
   * @param {String|ShaderSource} options.vertexShaderSource The GLSL source for the vertex shader.
   * @param {String|ShaderSource} options.fragmentShaderSource The GLSL source for the fragment shader.
   * @param {Object} options.attributeLocations Indices for the attribute inputs to the vertex shader.
   *
   * @returns {ShaderProgram} The cached or newly created shader program.
   */
  ShaderCache.prototype.getShaderProgram = function (options) {
    // convert shaders which are provided as strings into ShaderSource objects
    // because ShaderSource handles all the automatic including of built-in functions, etc.

    let vertexShaderSource = options.vertexShaderSource;
    let fragmentShaderSource = options.fragmentShaderSource;
    const attributeLocations = options.attributeLocations;

    if (typeof vertexShaderSource === "string") {
      vertexShaderSource = new ShaderSource({
        sources: [vertexShaderSource],
      });
    }

    if (typeof fragmentShaderSource === "string") {
      fragmentShaderSource = new ShaderSource({
        sources: [fragmentShaderSource],
      });
    }

    const vertexShaderText = vertexShaderSource.createCombinedVertexShader(
      this._context
    );
    const fragmentShaderText = fragmentShaderSource.createCombinedFragmentShader(
      this._context
    );

    const keyword =
      vertexShaderText + fragmentShaderText + JSON.stringify(attributeLocations);
    let cachedShader;

    if (defined(this._shaders[keyword])) {
      cachedShader = this._shaders[keyword];

      // No longer want to release this if it was previously released.
      delete this._shadersToRelease[keyword];
    } else {
      const context = this._context;
      const shaderProgram = new ShaderProgram({
        gl: context._gl,
        logShaderCompilation: context.logShaderCompilation,
        debugShaders: context.debugShaders,
        vertexShaderSource: vertexShaderSource,
        vertexShaderText: vertexShaderText,
        fragmentShaderSource: fragmentShaderSource,
        fragmentShaderText: fragmentShaderText,
        attributeLocations: attributeLocations,
      });

      cachedShader = {
        cache: this,
        shaderProgram: shaderProgram,
        keyword: keyword,
        derivedKeywords: [],
        count: 0,
      };

      // A shader can't be in more than one cache.
      shaderProgram._cachedShader = cachedShader;
      this._shaders[keyword] = cachedShader;
      ++this._numberOfShaders;
    }

    ++cachedShader.count;
    return cachedShader.shaderProgram;
  };

  ShaderCache.prototype.replaceDerivedShaderProgram = function (
    shaderProgram,
    keyword,
    options
  ) {
    const cachedShader = shaderProgram._cachedShader;
    const derivedKeyword = keyword + cachedShader.keyword;
    const cachedDerivedShader = this._shaders[derivedKeyword];
    if (defined(cachedDerivedShader)) {
      destroyShader(this, cachedDerivedShader);
      const index = cachedShader.derivedKeywords.indexOf(keyword);
      if (index > -1) {
        cachedShader.derivedKeywords.splice(index, 1);
      }
    }

    return this.createDerivedShaderProgram(shaderProgram, keyword, options);
  };

  ShaderCache.prototype.getDerivedShaderProgram = function (
    shaderProgram,
    keyword
  ) {
    const cachedShader = shaderProgram._cachedShader;
    const derivedKeyword = keyword + cachedShader.keyword;
    const cachedDerivedShader = this._shaders[derivedKeyword];
    if (!defined(cachedDerivedShader)) {
      return undefined;
    }

    return cachedDerivedShader.shaderProgram;
  };

  ShaderCache.prototype.createDerivedShaderProgram = function (
    shaderProgram,
    keyword,
    options
  ) {
    const cachedShader = shaderProgram._cachedShader;
    const derivedKeyword = keyword + cachedShader.keyword;

    let vertexShaderSource = options.vertexShaderSource;
    let fragmentShaderSource = options.fragmentShaderSource;
    const attributeLocations = options.attributeLocations;

    if (typeof vertexShaderSource === "string") {
      vertexShaderSource = new ShaderSource({
        sources: [vertexShaderSource],
      });
    }

    if (typeof fragmentShaderSource === "string") {
      fragmentShaderSource = new ShaderSource({
        sources: [fragmentShaderSource],
      });
    }

    const context = this._context;

    const vertexShaderText = vertexShaderSource.createCombinedVertexShader(
      context
    );
    const fragmentShaderText = fragmentShaderSource.createCombinedFragmentShader(
      context
    );

    const derivedShaderProgram = new ShaderProgram({
      gl: context._gl,
      logShaderCompilation: context.logShaderCompilation,
      debugShaders: context.debugShaders,
      vertexShaderSource: vertexShaderSource,
      vertexShaderText: vertexShaderText,
      fragmentShaderSource: fragmentShaderSource,
      fragmentShaderText: fragmentShaderText,
      attributeLocations: attributeLocations,
    });

    const derivedCachedShader = {
      cache: this,
      shaderProgram: derivedShaderProgram,
      keyword: derivedKeyword,
      derivedKeywords: [],
      count: 0,
    };

    cachedShader.derivedKeywords.push(keyword);
    derivedShaderProgram._cachedShader = derivedCachedShader;
    this._shaders[derivedKeyword] = derivedCachedShader;
    return derivedShaderProgram;
  };

  function destroyShader(cache, cachedShader) {
    const derivedKeywords = cachedShader.derivedKeywords;
    const length = derivedKeywords.length;
    for (let i = 0; i < length; ++i) {
      const keyword = derivedKeywords[i] + cachedShader.keyword;
      const derivedCachedShader = cache._shaders[keyword];
      destroyShader(cache, derivedCachedShader);
    }

    delete cache._shaders[cachedShader.keyword];
    cachedShader.shaderProgram.finalDestroy();
  }

  ShaderCache.prototype.destroyReleasedShaderPrograms = function () {
    const shadersToRelease = this._shadersToRelease;

    for (const keyword in shadersToRelease) {
      if (shadersToRelease.hasOwnProperty(keyword)) {
        const cachedShader = shadersToRelease[keyword];
        destroyShader(this, cachedShader);
        --this._numberOfShaders;
      }
    }

    this._shadersToRelease = {};
  };

  ShaderCache.prototype.releaseShaderProgram = function (shaderProgram) {
    if (defined(shaderProgram)) {
      const cachedShader = shaderProgram._cachedShader;
      if (cachedShader && --cachedShader.count === 0) {
        this._shadersToRelease[cachedShader.keyword] = cachedShader;
      }
    }
  };

  ShaderCache.prototype.isDestroyed = function () {
    return false;
  };

  ShaderCache.prototype.destroy = function () {
    const shaders = this._shaders;
    for (const keyword in shaders) {
      if (shaders.hasOwnProperty(keyword)) {
        shaders[keyword].shaderProgram.finalDestroy();
      }
    }
    return destroyObject(this);
  };

  /**
   * @private
   */
  function TextureCache() {
    this._textures = {};
    this._numberOfTextures = 0;
    this._texturesToRelease = {};
  }

  Object.defineProperties(TextureCache.prototype, {
    numberOfTextures: {
      get: function () {
        return this._numberOfTextures;
      },
    },
  });

  TextureCache.prototype.getTexture = function (keyword) {
    const cachedTexture = this._textures[keyword];
    if (!defined(cachedTexture)) {
      return undefined;
    }

    // No longer want to release this if it was previously released.
    delete this._texturesToRelease[keyword];

    ++cachedTexture.count;
    return cachedTexture.texture;
  };

  TextureCache.prototype.addTexture = function (keyword, texture) {
    const cachedTexture = {
      texture: texture,
      count: 1,
    };

    texture.finalDestroy = texture.destroy;

    const that = this;
    texture.destroy = function () {
      if (--cachedTexture.count === 0) {
        that._texturesToRelease[keyword] = cachedTexture;
      }
    };

    this._textures[keyword] = cachedTexture;
    ++this._numberOfTextures;
  };

  TextureCache.prototype.destroyReleasedTextures = function () {
    const texturesToRelease = this._texturesToRelease;

    for (const keyword in texturesToRelease) {
      if (texturesToRelease.hasOwnProperty(keyword)) {
        const cachedTexture = texturesToRelease[keyword];
        delete this._textures[keyword];
        cachedTexture.texture.finalDestroy();
        --this._numberOfTextures;
      }
    }

    this._texturesToRelease = {};
  };

  TextureCache.prototype.isDestroyed = function () {
    return false;
  };

  TextureCache.prototype.destroy = function () {
    const textures = this._textures;
    for (const keyword in textures) {
      if (textures.hasOwnProperty(keyword)) {
        textures[keyword].texture.finalDestroy();
      }
    }
    return destroyObject(this);
  };

  /**
   * A directional light source that originates from the Sun.
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Color} [options.color=Color.WHITE] The light's color.
   * @param {Number} [options.intensity=2.0] The light's intensity.
   *
   * @alias SunLight
   * @constructor
   */
  function SunLight(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    /**
     * The color of the light.
     * @type {Color}
     * @default Color.WHITE
     */
    this.color = Color.clone(defaultValue(options.color, Color.WHITE));

    /**
     * The intensity of the light.
     * @type {Number}
     * @default 2.0
     */
    this.intensity = defaultValue(options.intensity, 2.0);
  }

  /**
   * @private
   * @constructor
   */
  function UniformState() {
    /**
     * @type {Texture}
     */
    this.globeDepthTexture = undefined;
    /**
     * @type {Number}
     */
    this.gamma = undefined;

    this._viewport = new BoundingRectangle();
    this._viewportCartesian4 = new Cartesian4();
    this._viewportDirty = false;
    this._viewportOrthographicMatrix = Matrix4.clone(Matrix4.IDENTITY);
    this._viewportTransformation = Matrix4.clone(Matrix4.IDENTITY);

    this._model = Matrix4.clone(Matrix4.IDENTITY);
    this._view = Matrix4.clone(Matrix4.IDENTITY);
    this._inverseView = Matrix4.clone(Matrix4.IDENTITY);
    this._projection = Matrix4.clone(Matrix4.IDENTITY);
    this._infiniteProjection = Matrix4.clone(Matrix4.IDENTITY);
    this._entireFrustum = new Cartesian2();
    this._currentFrustum = new Cartesian2();
    this._frustumPlanes = new Cartesian4();
    this._farDepthFromNearPlusOne = undefined;
    this._log2FarDepthFromNearPlusOne = undefined;
    this._oneOverLog2FarDepthFromNearPlusOne = undefined;

    this._frameState = undefined;
    this._temeToPseudoFixed = Matrix3.clone(Matrix4.IDENTITY);

    // Derived members
    this._view3DDirty = true;
    this._view3D = new Matrix4();

    this._inverseView3DDirty = true;
    this._inverseView3D = new Matrix4();

    this._inverseModelDirty = true;
    this._inverseModel = new Matrix4();

    this._inverseTransposeModelDirty = true;
    this._inverseTransposeModel = new Matrix3();

    this._viewRotation = new Matrix3();
    this._inverseViewRotation = new Matrix3();

    this._viewRotation3D = new Matrix3();
    this._inverseViewRotation3D = new Matrix3();

    this._inverseProjectionDirty = true;
    this._inverseProjection = new Matrix4();

    this._modelViewDirty = true;
    this._modelView = new Matrix4();

    this._modelView3DDirty = true;
    this._modelView3D = new Matrix4();

    this._modelViewRelativeToEyeDirty = true;
    this._modelViewRelativeToEye = new Matrix4();

    this._inverseModelViewDirty = true;
    this._inverseModelView = new Matrix4();

    this._inverseModelView3DDirty = true;
    this._inverseModelView3D = new Matrix4();

    this._viewProjectionDirty = true;
    this._viewProjection = new Matrix4();

    this._inverseViewProjectionDirty = true;
    this._inverseViewProjection = new Matrix4();

    this._modelViewProjectionDirty = true;
    this._modelViewProjection = new Matrix4();

    this._inverseModelViewProjectionDirty = true;
    this._inverseModelViewProjection = new Matrix4();

    this._modelViewProjectionRelativeToEyeDirty = true;
    this._modelViewProjectionRelativeToEye = new Matrix4();

    this._modelViewInfiniteProjectionDirty = true;
    this._modelViewInfiniteProjection = new Matrix4();

    this._normalDirty = true;
    this._normal = new Matrix3();

    this._normal3DDirty = true;
    this._normal3D = new Matrix3();

    this._inverseNormalDirty = true;
    this._inverseNormal = new Matrix3();

    this._inverseNormal3DDirty = true;
    this._inverseNormal3D = new Matrix3();

    this._encodedCameraPositionMCDirty = true;
    this._encodedCameraPositionMC = new EncodedCartesian3();
    this._cameraPosition = new Cartesian3();

    this._sunPositionWC = new Cartesian3();
    this._sunPositionColumbusView = new Cartesian3();
    this._sunDirectionWC = new Cartesian3();
    this._sunDirectionEC = new Cartesian3();
    this._moonDirectionEC = new Cartesian3();

    this._lightDirectionWC = new Cartesian3();
    this._lightDirectionEC = new Cartesian3();
    this._lightColor = new Cartesian3();
    this._lightColorHdr = new Cartesian3();

    this._pass = undefined;
    this._mode = undefined;
    this._mapProjection = undefined;
    this._ellipsoid = undefined;
    this._cameraDirection = new Cartesian3();
    this._cameraRight = new Cartesian3();
    this._cameraUp = new Cartesian3();
    this._frustum2DWidth = 0.0;
    this._eyeHeight = 0.0;
    this._eyeHeight2D = new Cartesian2();
    this._pixelRatio = 1.0;
    this._orthographicIn3D = false;
    this._backgroundColor = new Color();

    this._brdfLut = undefined;
    this._environmentMap = undefined;

    this._sphericalHarmonicCoefficients = undefined;
    this._specularEnvironmentMaps = undefined;
    this._specularEnvironmentMapsDimensions = new Cartesian2();
    this._specularEnvironmentMapsMaximumLOD = undefined;

    this._fogDensity = undefined;

    this._invertClassificationColor = undefined;

    this._splitPosition = 0.0;
    this._pixelSizePerMeter = undefined;
    this._geometricToleranceOverMeter = undefined;

    this._minimumDisableDepthTestDistance = undefined;
  }

  Object.defineProperties(UniformState.prototype, {
    /**
     * @memberof UniformState.prototype
     * @type {FrameState}
     * @readonly
     */
    frameState: {
      get: function () {
        return this._frameState;
      },
    },
    /**
     * @memberof UniformState.prototype
     * @type {BoundingRectangle}
     */
    viewport: {
      get: function () {
        return this._viewport;
      },
      set: function (viewport) {
        if (!BoundingRectangle.equals(viewport, this._viewport)) {
          BoundingRectangle.clone(viewport, this._viewport);

          const v = this._viewport;
          const vc = this._viewportCartesian4;
          vc.x = v.x;
          vc.y = v.y;
          vc.z = v.width;
          vc.w = v.height;

          this._viewportDirty = true;
        }
      },
    },

    /**
     * @memberof UniformState.prototype
     * @private
     */
    viewportCartesian4: {
      get: function () {
        return this._viewportCartesian4;
      },
    },

    viewportOrthographic: {
      get: function () {
        cleanViewport(this);
        return this._viewportOrthographicMatrix;
      },
    },

    viewportTransformation: {
      get: function () {
        cleanViewport(this);
        return this._viewportTransformation;
      },
    },

    /**
     * @memberof UniformState.prototype
     * @type {Matrix4}
     */
    model: {
      get: function () {
        return this._model;
      },
      set: function (matrix) {
        Matrix4.clone(matrix, this._model);

        this._modelView3DDirty = true;
        this._inverseModelView3DDirty = true;
        this._inverseModelDirty = true;
        this._inverseTransposeModelDirty = true;
        this._modelViewDirty = true;
        this._inverseModelViewDirty = true;
        this._modelViewRelativeToEyeDirty = true;
        this._inverseModelViewDirty = true;
        this._modelViewProjectionDirty = true;
        this._inverseModelViewProjectionDirty = true;
        this._modelViewProjectionRelativeToEyeDirty = true;
        this._modelViewInfiniteProjectionDirty = true;
        this._normalDirty = true;
        this._inverseNormalDirty = true;
        this._normal3DDirty = true;
        this._inverseNormal3DDirty = true;
        this._encodedCameraPositionMCDirty = true;
      },
    },

    /**
     * @memberof UniformState.prototype
     * @type {Matrix4}
     */
    inverseModel: {
      get: function () {
        if (this._inverseModelDirty) {
          this._inverseModelDirty = false;

          Matrix4.inverse(this._model, this._inverseModel);
        }

        return this._inverseModel;
      },
    },

    /**
     * @memberof UniformState.prototype
     * @private
     */
    inverseTransposeModel: {
      get: function () {
        const m = this._inverseTransposeModel;
        if (this._inverseTransposeModelDirty) {
          this._inverseTransposeModelDirty = false;

          Matrix4.getMatrix3(this.inverseModel, m);
          Matrix3.transpose(m, m);
        }

        return m;
      },
    },

    /**
     * @memberof UniformState.prototype
     * @type {Matrix4}
     */
    view: {
      get: function () {
        return this._view;
      },
    },

    /**
     * The 3D view matrix.  In 3D mode, this is identical to {@link UniformState#view},
     * but in 2D and Columbus View it is a synthetic matrix based on the equivalent position
     * of the camera in the 3D world.
     * @memberof UniformState.prototype
     * @type {Matrix4}
     */
    view3D: {
      get: function () {
        updateView3D(this);
        return this._view3D;
      },
    },

    /**
     * The 3x3 rotation matrix of the current view matrix ({@link UniformState#view}).
     * @memberof UniformState.prototype
     * @type {Matrix3}
     */
    viewRotation: {
      get: function () {
        updateView3D(this);
        return this._viewRotation;
      },
    },

    /**
     * @memberof UniformState.prototype
     * @type {Matrix3}
     */
    viewRotation3D: {
      get: function () {
        updateView3D(this);
        return this._viewRotation3D;
      },
    },

    /**
     * @memberof UniformState.prototype
     * @type {Matrix4}
     */
    inverseView: {
      get: function () {
        return this._inverseView;
      },
    },

    /**
     * the 4x4 inverse-view matrix that transforms from eye to 3D world coordinates.  In 3D mode, this is
     * identical to {@link UniformState#inverseView}, but in 2D and Columbus View it is a synthetic matrix
     * based on the equivalent position of the camera in the 3D world.
     * @memberof UniformState.prototype
     * @type {Matrix4}
     */
    inverseView3D: {
      get: function () {
        updateInverseView3D(this);
        return this._inverseView3D;
      },
    },

    /**
     * @memberof UniformState.prototype
     * @type {Matrix3}
     */
    inverseViewRotation: {
      get: function () {
        return this._inverseViewRotation;
      },
    },

    /**
     * The 3x3 rotation matrix of the current 3D inverse-view matrix ({@link UniformState#inverseView3D}).
     * @memberof UniformState.prototype
     * @type {Matrix3}
     */
    inverseViewRotation3D: {
      get: function () {
        updateInverseView3D(this);
        return this._inverseViewRotation3D;
      },
    },

    /**
     * @memberof UniformState.prototype
     * @type {Matrix4}
     */
    projection: {
      get: function () {
        return this._projection;
      },
    },

    /**
     * @memberof UniformState.prototype
     * @type {Matrix4}
     */
    inverseProjection: {
      get: function () {
        cleanInverseProjection(this);
        return this._inverseProjection;
      },
    },

    /**
     * @memberof UniformState.prototype
     * @type {Matrix4}
     */
    infiniteProjection: {
      get: function () {
        return this._infiniteProjection;
      },
    },

    /**
     * @memberof UniformState.prototype
     * @type {Matrix4}
     */
    modelView: {
      get: function () {
        cleanModelView(this);
        return this._modelView;
      },
    },

    /**
     * The 3D model-view matrix.  In 3D mode, this is equivalent to {@link UniformState#modelView}.  In 2D and
     * Columbus View, however, it is a synthetic matrix based on the equivalent position of the camera in the 3D world.
     * @memberof UniformState.prototype
     * @type {Matrix4}
     */
    modelView3D: {
      get: function () {
        cleanModelView3D(this);
        return this._modelView3D;
      },
    },

    /**
     * Model-view relative to eye matrix.
     *
     * @memberof UniformState.prototype
     * @type {Matrix4}
     */
    modelViewRelativeToEye: {
      get: function () {
        cleanModelViewRelativeToEye(this);
        return this._modelViewRelativeToEye;
      },
    },

    /**
     * @memberof UniformState.prototype
     * @type {Matrix4}
     */
    inverseModelView: {
      get: function () {
        cleanInverseModelView(this);
        return this._inverseModelView;
      },
    },

    /**
     * The inverse of the 3D model-view matrix.  In 3D mode, this is equivalent to {@link UniformState#inverseModelView}.
     * In 2D and Columbus View, however, it is a synthetic matrix based on the equivalent position of the camera in the 3D world.
     * @memberof UniformState.prototype
     * @type {Matrix4}
     */
    inverseModelView3D: {
      get: function () {
        cleanInverseModelView3D(this);
        return this._inverseModelView3D;
      },
    },

    /**
     * @memberof UniformState.prototype
     * @type {Matrix4}
     */
    viewProjection: {
      get: function () {
        cleanViewProjection(this);
        return this._viewProjection;
      },
    },

    /**
     * @memberof UniformState.prototype
     * @type {Matrix4}
     */
    inverseViewProjection: {
      get: function () {
        cleanInverseViewProjection(this);
        return this._inverseViewProjection;
      },
    },

    /**
     * @memberof UniformState.prototype
     * @type {Matrix4}
     */
    modelViewProjection: {
      get: function () {
        cleanModelViewProjection(this);
        return this._modelViewProjection;
      },
    },

    /**
     * @memberof UniformState.prototype
     * @type {Matrix4}
     */
    inverseModelViewProjection: {
      get: function () {
        cleanInverseModelViewProjection(this);
        return this._inverseModelViewProjection;
      },
    },

    /**
     * Model-view-projection relative to eye matrix.
     *
     * @memberof UniformState.prototype
     * @type {Matrix4}
     */
    modelViewProjectionRelativeToEye: {
      get: function () {
        cleanModelViewProjectionRelativeToEye(this);
        return this._modelViewProjectionRelativeToEye;
      },
    },

    /**
     * @memberof UniformState.prototype
     * @type {Matrix4}
     */
    modelViewInfiniteProjection: {
      get: function () {
        cleanModelViewInfiniteProjection(this);
        return this._modelViewInfiniteProjection;
      },
    },

    /**
     * A 3x3 normal transformation matrix that transforms normal vectors in model coordinates to
     * eye coordinates.
     * @memberof UniformState.prototype
     * @type {Matrix3}
     */
    normal: {
      get: function () {
        cleanNormal(this);
        return this._normal;
      },
    },

    /**
     * A 3x3 normal transformation matrix that transforms normal vectors in 3D model
     * coordinates to eye coordinates.  In 3D mode, this is identical to
     * {@link UniformState#normal}, but in 2D and Columbus View it represents the normal transformation
     * matrix as if the camera were at an equivalent location in 3D mode.
     * @memberof UniformState.prototype
     * @type {Matrix3}
     */
    normal3D: {
      get: function () {
        cleanNormal3D(this);
        return this._normal3D;
      },
    },

    /**
     * An inverse 3x3 normal transformation matrix that transforms normal vectors in model coordinates
     * to eye coordinates.
     * @memberof UniformState.prototype
     * @type {Matrix3}
     */
    inverseNormal: {
      get: function () {
        cleanInverseNormal(this);
        return this._inverseNormal;
      },
    },

    /**
     * An inverse 3x3 normal transformation matrix that transforms normal vectors in eye coordinates
     * to 3D model coordinates.  In 3D mode, this is identical to
     * {@link UniformState#inverseNormal}, but in 2D and Columbus View it represents the normal transformation
     * matrix as if the camera were at an equivalent location in 3D mode.
     * @memberof UniformState.prototype
     * @type {Matrix3}
     */
    inverseNormal3D: {
      get: function () {
        cleanInverseNormal3D(this);
        return this._inverseNormal3D;
      },
    },

    /**
     * The near distance (<code>x</code>) and the far distance (<code>y</code>) of the frustum defined by the camera.
     * This is the largest possible frustum, not an individual frustum used for multi-frustum rendering.
     * @memberof UniformState.prototype
     * @type {Cartesian2}
     */
    entireFrustum: {
      get: function () {
        return this._entireFrustum;
      },
    },

    /**
     * The near distance (<code>x</code>) and the far distance (<code>y</code>) of the frustum defined by the camera.
     * This is the individual frustum used for multi-frustum rendering.
     * @memberof UniformState.prototype
     * @type {Cartesian2}
     */
    currentFrustum: {
      get: function () {
        return this._currentFrustum;
      },
    },

    /**
     * The distances to the frustum planes. The top, bottom, left and right distances are
     * the x, y, z, and w components, respectively.
     * @memberof UniformState.prototype
     * @type {Cartesian4}
     */
    frustumPlanes: {
      get: function () {
        return this._frustumPlanes;
      },
    },

    /**
     * The far plane's distance from the near plane, plus 1.0.
     *
     * @memberof UniformState.prototype
     * @type {Number}
     */
    farDepthFromNearPlusOne: {
      get: function () {
        return this._farDepthFromNearPlusOne;
      },
    },

    /**
     * The log2 of {@link UniformState#farDepthFromNearPlusOne}.
     *
     * @memberof UniformState.prototype
     * @type {Number}
     */
    log2FarDepthFromNearPlusOne: {
      get: function () {
        return this._log2FarDepthFromNearPlusOne;
      },
    },

    /**
     * 1.0 divided by {@link UniformState#log2FarDepthFromNearPlusOne}.
     *
     * @memberof UniformState.prototype
     * @type {Number}
     */
    oneOverLog2FarDepthFromNearPlusOne: {
      get: function () {
        return this._oneOverLog2FarDepthFromNearPlusOne;
      },
    },

    /**
     * The height in meters of the eye (camera) above or below the ellipsoid.
     * @memberof UniformState.prototype
     * @type {Number}
     */
    eyeHeight: {
      get: function () {
        return this._eyeHeight;
      },
    },

    /**
     * The height (<code>x</code>) and the height squared (<code>y</code>)
     * in meters of the eye (camera) above the 2D world plane. This uniform is only valid
     * when the {@link SceneMode} is <code>SCENE2D</code>.
     * @memberof UniformState.prototype
     * @type {Cartesian2}
     */
    eyeHeight2D: {
      get: function () {
        return this._eyeHeight2D;
      },
    },

    /**
     * The sun position in 3D world coordinates at the current scene time.
     * @memberof UniformState.prototype
     * @type {Cartesian3}
     */
    sunPositionWC: {
      get: function () {
        return this._sunPositionWC;
      },
    },

    /**
     * The sun position in 2D world coordinates at the current scene time.
     * @memberof UniformState.prototype
     * @type {Cartesian3}
     */
    sunPositionColumbusView: {
      get: function () {
        return this._sunPositionColumbusView;
      },
    },

    /**
     * A normalized vector to the sun in 3D world coordinates at the current scene time.  Even in 2D or
     * Columbus View mode, this returns the direction to the sun in the 3D scene.
     * @memberof UniformState.prototype
     * @type {Cartesian3}
     */
    sunDirectionWC: {
      get: function () {
        return this._sunDirectionWC;
      },
    },

    /**
     * A normalized vector to the sun in eye coordinates at the current scene time.  In 3D mode, this
     * returns the actual vector from the camera position to the sun position.  In 2D and Columbus View, it returns
     * the vector from the equivalent 3D camera position to the position of the sun in the 3D scene.
     * @memberof UniformState.prototype
     * @type {Cartesian3}
     */
    sunDirectionEC: {
      get: function () {
        return this._sunDirectionEC;
      },
    },

    /**
     * A normalized vector to the moon in eye coordinates at the current scene time.  In 3D mode, this
     * returns the actual vector from the camera position to the moon position.  In 2D and Columbus View, it returns
     * the vector from the equivalent 3D camera position to the position of the moon in the 3D scene.
     * @memberof UniformState.prototype
     * @type {Cartesian3}
     */
    moonDirectionEC: {
      get: function () {
        return this._moonDirectionEC;
      },
    },

    /**
     * A normalized vector to the scene's light source in 3D world coordinates.  Even in 2D or
     * Columbus View mode, this returns the direction to the light in the 3D scene.
     * @memberof UniformState.prototype
     * @type {Cartesian3}
     */
    lightDirectionWC: {
      get: function () {
        return this._lightDirectionWC;
      },
    },

    /**
     * A normalized vector to the scene's light source in eye coordinates.  In 3D mode, this
     * returns the actual vector from the camera position to the light.  In 2D and Columbus View, it returns
     * the vector from the equivalent 3D camera position in the 3D scene.
     * @memberof UniformState.prototype
     * @type {Cartesian3}
     */
    lightDirectionEC: {
      get: function () {
        return this._lightDirectionEC;
      },
    },

    /**
     * The color of light emitted by the scene's light source. This is equivalent to the light
     * color multiplied by the light intensity limited to a maximum luminance of 1.0 suitable
     * for non-HDR lighting.
     * @memberof UniformState.prototype
     * @type {Cartesian3}
     */
    lightColor: {
      get: function () {
        return this._lightColor;
      },
    },

    /**
     * The high dynamic range color of light emitted by the scene's light source. This is equivalent to
     * the light color multiplied by the light intensity suitable for HDR lighting.
     * @memberof UniformState.prototype
     * @type {Cartesian3}
     */
    lightColorHdr: {
      get: function () {
        return this._lightColorHdr;
      },
    },

    /**
     * The high bits of the camera position.
     * @memberof UniformState.prototype
     * @type {Cartesian3}
     */
    encodedCameraPositionMCHigh: {
      get: function () {
        cleanEncodedCameraPositionMC(this);
        return this._encodedCameraPositionMC.high;
      },
    },

    /**
     * The low bits of the camera position.
     * @memberof UniformState.prototype
     * @type {Cartesian3}
     */
    encodedCameraPositionMCLow: {
      get: function () {
        cleanEncodedCameraPositionMC(this);
        return this._encodedCameraPositionMC.low;
      },
    },

    /**
     * A 3x3 matrix that transforms from True Equator Mean Equinox (TEME) axes to the
     * pseudo-fixed axes at the Scene's current time.
     * @memberof UniformState.prototype
     * @type {Matrix3}
     */
    temeToPseudoFixedMatrix: {
      get: function () {
        return this._temeToPseudoFixed;
      },
    },

    /**
     * Gets the scaling factor for transforming from the canvas
     * pixel space to canvas coordinate space.
     * @memberof UniformState.prototype
     * @type {Number}
     */
    pixelRatio: {
      get: function () {
        return this._pixelRatio;
      },
    },

    /**
     * A scalar used to mix a color with the fog color based on the distance to the camera.
     * @memberof UniformState.prototype
     * @type {Number}
     */
    fogDensity: {
      get: function () {
        return this._fogDensity;
      },
    },

    /**
     * A scalar that represents the geometric tolerance per meter
     * @memberof UniformState.prototype
     * @type {Number}
     */
    geometricToleranceOverMeter: {
      get: function () {
        return this._geometricToleranceOverMeter;
      },
    },

    /**
     * @memberof UniformState.prototype
     * @type {Pass}
     */
    pass: {
      get: function () {
        return this._pass;
      },
    },

    /**
     * The current background color
     * @memberof UniformState.prototype
     * @type {Color}
     */
    backgroundColor: {
      get: function () {
        return this._backgroundColor;
      },
    },

    /**
     * The look up texture used to find the BRDF for a material
     * @memberof UniformState.prototype
     * @type {Texture}
     */
    brdfLut: {
      get: function () {
        return this._brdfLut;
      },
    },

    /**
     * The environment map of the scene
     * @memberof UniformState.prototype
     * @type {CubeMap}
     */
    environmentMap: {
      get: function () {
        return this._environmentMap;
      },
    },

    /**
     * The spherical harmonic coefficients of the scene.
     * @memberof UniformState.prototype
     * @type {Cartesian3[]}
     */
    sphericalHarmonicCoefficients: {
      get: function () {
        return this._sphericalHarmonicCoefficients;
      },
    },

    /**
     * The specular environment map atlas of the scene.
     * @memberof UniformState.prototype
     * @type {Texture}
     */
    specularEnvironmentMaps: {
      get: function () {
        return this._specularEnvironmentMaps;
      },
    },

    /**
     * The dimensions of the specular environment map atlas of the scene.
     * @memberof UniformState.prototype
     * @type {Cartesian2}
     */
    specularEnvironmentMapsDimensions: {
      get: function () {
        return this._specularEnvironmentMapsDimensions;
      },
    },

    /**
     * The maximum level-of-detail of the specular environment map atlas of the scene.
     * @memberof UniformState.prototype
     * @type {Number}
     */
    specularEnvironmentMapsMaximumLOD: {
      get: function () {
        return this._specularEnvironmentMapsMaximumLOD;
      },
    },

    /**
     * The splitter position to use when rendering with a splitter. This will be in pixel coordinates relative to the canvas.
     * @memberof UniformState.prototype
     * @type {Number}
     */
    splitPosition: {
      get: function () {
        return this._splitPosition;
      },
    },

    /**
     * The distance from the camera at which to disable the depth test of billboards, labels and points
     * to, for example, prevent clipping against terrain. When set to zero, the depth test should always
     * be applied. When less than zero, the depth test should never be applied.
     *
     * @memberof UniformState.prototype
     * @type {Number}
     */
    minimumDisableDepthTestDistance: {
      get: function () {
        return this._minimumDisableDepthTestDistance;
      },
    },

    /**
     * The highlight color of unclassified 3D Tiles.
     *
     * @memberof UniformState.prototype
     * @type {Color}
     */
    invertClassificationColor: {
      get: function () {
        return this._invertClassificationColor;
      },
    },

    /**
     * Whether or not the current projection is orthographic in 3D.
     *
     * @memberOf UniformState.prototype
     * @type {Boolean}
     */
    orthographicIn3D: {
      get: function () {
        return this._orthographicIn3D;
      },
    },

    /**
     * The current ellipsoid.
     *
     * @memberOf UniformState.prototype
     * @type {Ellipsoid}
     */
    ellipsoid: {
      get: function () {
        return defaultValue(this._ellipsoid, Ellipsoid.WGS84);
      },
    },
  });

  function setView(uniformState, matrix) {
    Matrix4.clone(matrix, uniformState._view);
    Matrix4.getMatrix3(matrix, uniformState._viewRotation);

    uniformState._view3DDirty = true;
    uniformState._inverseView3DDirty = true;
    uniformState._modelViewDirty = true;
    uniformState._modelView3DDirty = true;
    uniformState._modelViewRelativeToEyeDirty = true;
    uniformState._inverseModelViewDirty = true;
    uniformState._inverseModelView3DDirty = true;
    uniformState._viewProjectionDirty = true;
    uniformState._inverseViewProjectionDirty = true;
    uniformState._modelViewProjectionDirty = true;
    uniformState._modelViewProjectionRelativeToEyeDirty = true;
    uniformState._modelViewInfiniteProjectionDirty = true;
    uniformState._normalDirty = true;
    uniformState._inverseNormalDirty = true;
    uniformState._normal3DDirty = true;
    uniformState._inverseNormal3DDirty = true;
  }

  function setInverseView(uniformState, matrix) {
    Matrix4.clone(matrix, uniformState._inverseView);
    Matrix4.getMatrix3(matrix, uniformState._inverseViewRotation);
  }

  function setProjection(uniformState, matrix) {
    Matrix4.clone(matrix, uniformState._projection);

    uniformState._inverseProjectionDirty = true;
    uniformState._viewProjectionDirty = true;
    uniformState._inverseViewProjectionDirty = true;
    uniformState._modelViewProjectionDirty = true;
    uniformState._modelViewProjectionRelativeToEyeDirty = true;
  }

  function setInfiniteProjection(uniformState, matrix) {
    Matrix4.clone(matrix, uniformState._infiniteProjection);

    uniformState._modelViewInfiniteProjectionDirty = true;
  }

  function setCamera(uniformState, camera) {
    Cartesian3.clone(camera.positionWC, uniformState._cameraPosition);
    Cartesian3.clone(camera.directionWC, uniformState._cameraDirection);
    Cartesian3.clone(camera.rightWC, uniformState._cameraRight);
    Cartesian3.clone(camera.upWC, uniformState._cameraUp);

    const positionCartographic = camera.positionCartographic;
    if (!defined(positionCartographic)) {
      uniformState._eyeHeight = -uniformState._ellipsoid.maximumRadius;
    } else {
      uniformState._eyeHeight = positionCartographic.height;
    }

    uniformState._encodedCameraPositionMCDirty = true;
  }

  let transformMatrix = new Matrix3();
  const sunCartographicScratch = new Cartographic();
  function setSunAndMoonDirections(uniformState, frameState) {
    if (
      !defined(
        Transforms.computeIcrfToFixedMatrix(frameState.time, transformMatrix)
      )
    ) {
      transformMatrix = Transforms.computeTemeToPseudoFixedMatrix(
        frameState.time,
        transformMatrix
      );
    }

    let position = Simon1994PlanetaryPositions.computeSunPositionInEarthInertialFrame(
      frameState.time,
      uniformState._sunPositionWC
    );
    Matrix3.multiplyByVector(transformMatrix, position, position);

    Cartesian3.normalize(position, uniformState._sunDirectionWC);

    position = Matrix3.multiplyByVector(
      uniformState.viewRotation3D,
      position,
      uniformState._sunDirectionEC
    );
    Cartesian3.normalize(position, position);

    position = Simon1994PlanetaryPositions.computeMoonPositionInEarthInertialFrame(
      frameState.time,
      uniformState._moonDirectionEC
    );
    Matrix3.multiplyByVector(transformMatrix, position, position);
    Matrix3.multiplyByVector(uniformState.viewRotation3D, position, position);
    Cartesian3.normalize(position, position);

    const projection = frameState.mapProjection;
    const ellipsoid = projection.ellipsoid;
    const sunCartographic = ellipsoid.cartesianToCartographic(
      uniformState._sunPositionWC,
      sunCartographicScratch
    );
    projection.project(sunCartographic, uniformState._sunPositionColumbusView);
  }

  /**
   * Synchronizes the frustum's state with the camera state.  This is called
   * by the {@link Scene} when rendering to ensure that automatic GLSL uniforms
   * are set to the right value.
   *
   * @param {Object} camera The camera to synchronize with.
   */
  UniformState.prototype.updateCamera = function (camera) {
    setView(this, camera.viewMatrix);
    setInverseView(this, camera.inverseViewMatrix);
    setCamera(this, camera);

    this._entireFrustum.x = camera.frustum.near;
    this._entireFrustum.y = camera.frustum.far;
    this.updateFrustum(camera.frustum);

    this._orthographicIn3D =
      this._mode !== SceneMode$1.SCENE2D &&
      camera.frustum instanceof OrthographicFrustum;
  };

  /**
   * Synchronizes the frustum's state with the uniform state.  This is called
   * by the {@link Scene} when rendering to ensure that automatic GLSL uniforms
   * are set to the right value.
   *
   * @param {Object} frustum The frustum to synchronize with.
   */
  UniformState.prototype.updateFrustum = function (frustum) {
    setProjection(this, frustum.projectionMatrix);
    if (defined(frustum.infiniteProjectionMatrix)) {
      setInfiniteProjection(this, frustum.infiniteProjectionMatrix);
    }
    this._currentFrustum.x = frustum.near;
    this._currentFrustum.y = frustum.far;

    this._farDepthFromNearPlusOne = frustum.far - frustum.near + 1.0;
    this._log2FarDepthFromNearPlusOne = CesiumMath.log2(
      this._farDepthFromNearPlusOne
    );
    this._oneOverLog2FarDepthFromNearPlusOne =
      1.0 / this._log2FarDepthFromNearPlusOne;

    if (defined(frustum._offCenterFrustum)) {
      frustum = frustum._offCenterFrustum;
    }

    this._frustumPlanes.x = frustum.top;
    this._frustumPlanes.y = frustum.bottom;
    this._frustumPlanes.z = frustum.left;
    this._frustumPlanes.w = frustum.right;
  };

  UniformState.prototype.updatePass = function (pass) {
    this._pass = pass;
  };

  const EMPTY_ARRAY = [];
  const defaultLight = new SunLight();

  /**
   * Synchronizes frame state with the uniform state.  This is called
   * by the {@link Scene} when rendering to ensure that automatic GLSL uniforms
   * are set to the right value.
   *
   * @param {FrameState} frameState The frameState to synchronize with.
   */
  UniformState.prototype.update = function (frameState) {
    this._mode = frameState.mode;
    this._mapProjection = frameState.mapProjection;
    this._ellipsoid = frameState.mapProjection.ellipsoid;
    this._pixelRatio = frameState.pixelRatio;

    const camera = frameState.camera;
    this.updateCamera(camera);

    if (frameState.mode === SceneMode$1.SCENE2D) {
      this._frustum2DWidth = camera.frustum.right - camera.frustum.left;
      this._eyeHeight2D.x = this._frustum2DWidth * 0.5;
      this._eyeHeight2D.y = this._eyeHeight2D.x * this._eyeHeight2D.x;
    } else {
      this._frustum2DWidth = 0.0;
      this._eyeHeight2D.x = 0.0;
      this._eyeHeight2D.y = 0.0;
    }

    setSunAndMoonDirections(this, frameState);

    const light = defaultValue(frameState.light, defaultLight);
    if (light instanceof SunLight) {
      this._lightDirectionWC = Cartesian3.clone(
        this._sunDirectionWC,
        this._lightDirectionWC
      );
      this._lightDirectionEC = Cartesian3.clone(
        this._sunDirectionEC,
        this._lightDirectionEC
      );
    } else {
      this._lightDirectionWC = Cartesian3.normalize(
        Cartesian3.negate(light.direction, this._lightDirectionWC),
        this._lightDirectionWC
      );
      this._lightDirectionEC = Matrix3.multiplyByVector(
        this.viewRotation3D,
        this._lightDirectionWC,
        this._lightDirectionEC
      );
    }

    const lightColor = light.color;
    let lightColorHdr = Cartesian3.fromElements(
      lightColor.red,
      lightColor.green,
      lightColor.blue,
      this._lightColorHdr
    );
    lightColorHdr = Cartesian3.multiplyByScalar(
      lightColorHdr,
      light.intensity,
      lightColorHdr
    );
    const maximumComponent = Cartesian3.maximumComponent(lightColorHdr);
    if (maximumComponent > 1.0) {
      Cartesian3.divideByScalar(
        lightColorHdr,
        maximumComponent,
        this._lightColor
      );
    } else {
      Cartesian3.clone(lightColorHdr, this._lightColor);
    }

    const brdfLutGenerator = frameState.brdfLutGenerator;
    const brdfLut = defined(brdfLutGenerator)
      ? brdfLutGenerator.colorTexture
      : undefined;
    this._brdfLut = brdfLut;

    this._environmentMap = defaultValue(
      frameState.environmentMap,
      frameState.context.defaultCubeMap
    );

    // IE 11 doesn't optimize out uniforms that are #ifdef'd out. So undefined values for the spherical harmonic
    // coefficients and specular environment map atlas dimensions cause a crash.
    this._sphericalHarmonicCoefficients = defaultValue(
      frameState.sphericalHarmonicCoefficients,
      EMPTY_ARRAY
    );
    this._specularEnvironmentMaps = frameState.specularEnvironmentMaps;
    this._specularEnvironmentMapsMaximumLOD =
      frameState.specularEnvironmentMapsMaximumLOD;

    if (defined(this._specularEnvironmentMaps)) {
      Cartesian2.clone(
        this._specularEnvironmentMaps.dimensions,
        this._specularEnvironmentMapsDimensions
      );
    }

    this._fogDensity = frameState.fog.density;

    this._invertClassificationColor = frameState.invertClassificationColor;

    this._frameState = frameState;
    this._temeToPseudoFixed = Transforms.computeTemeToPseudoFixedMatrix(
      frameState.time,
      this._temeToPseudoFixed
    );

    // Convert the relative splitPosition to absolute pixel coordinates
    this._splitPosition =
      frameState.splitPosition * frameState.context.drawingBufferWidth;
    const fov = camera.frustum.fov;
    const viewport = this._viewport;
    let pixelSizePerMeter;
    if (defined(fov)) {
      if (viewport.height > viewport.width) {
        pixelSizePerMeter = (Math.tan(0.5 * fov) * 2.0) / viewport.height;
      } else {
        pixelSizePerMeter = (Math.tan(0.5 * fov) * 2.0) / viewport.width;
      }
    } else {
      pixelSizePerMeter = 1.0 / Math.max(viewport.width, viewport.height);
    }

    this._geometricToleranceOverMeter =
      pixelSizePerMeter * frameState.maximumScreenSpaceError;
    Color.clone(frameState.backgroundColor, this._backgroundColor);

    this._minimumDisableDepthTestDistance =
      frameState.minimumDisableDepthTestDistance;
    this._minimumDisableDepthTestDistance *= this._minimumDisableDepthTestDistance;
    if (this._minimumDisableDepthTestDistance === Number.POSITIVE_INFINITY) {
      this._minimumDisableDepthTestDistance = -1.0;
    }
  };

  function cleanViewport(uniformState) {
    if (uniformState._viewportDirty) {
      const v = uniformState._viewport;
      Matrix4.computeOrthographicOffCenter(
        v.x,
        v.x + v.width,
        v.y,
        v.y + v.height,
        0.0,
        1.0,
        uniformState._viewportOrthographicMatrix
      );
      Matrix4.computeViewportTransformation(
        v,
        0.0,
        1.0,
        uniformState._viewportTransformation
      );
      uniformState._viewportDirty = false;
    }
  }

  function cleanInverseProjection(uniformState) {
    if (uniformState._inverseProjectionDirty) {
      uniformState._inverseProjectionDirty = false;

      if (
        uniformState._mode !== SceneMode$1.SCENE2D &&
        uniformState._mode !== SceneMode$1.MORPHING &&
        !uniformState._orthographicIn3D
      ) {
        Matrix4.inverse(
          uniformState._projection,
          uniformState._inverseProjection
        );
      } else {
        Matrix4.clone(Matrix4.ZERO, uniformState._inverseProjection);
      }
    }
  }

  // Derived
  function cleanModelView(uniformState) {
    if (uniformState._modelViewDirty) {
      uniformState._modelViewDirty = false;

      Matrix4.multiplyTransformation(
        uniformState._view,
        uniformState._model,
        uniformState._modelView
      );
    }
  }

  function cleanModelView3D(uniformState) {
    if (uniformState._modelView3DDirty) {
      uniformState._modelView3DDirty = false;

      Matrix4.multiplyTransformation(
        uniformState.view3D,
        uniformState._model,
        uniformState._modelView3D
      );
    }
  }

  function cleanInverseModelView(uniformState) {
    if (uniformState._inverseModelViewDirty) {
      uniformState._inverseModelViewDirty = false;

      Matrix4.inverse(uniformState.modelView, uniformState._inverseModelView);
    }
  }

  function cleanInverseModelView3D(uniformState) {
    if (uniformState._inverseModelView3DDirty) {
      uniformState._inverseModelView3DDirty = false;

      Matrix4.inverse(uniformState.modelView3D, uniformState._inverseModelView3D);
    }
  }

  function cleanViewProjection(uniformState) {
    if (uniformState._viewProjectionDirty) {
      uniformState._viewProjectionDirty = false;

      Matrix4.multiply(
        uniformState._projection,
        uniformState._view,
        uniformState._viewProjection
      );
    }
  }

  function cleanInverseViewProjection(uniformState) {
    if (uniformState._inverseViewProjectionDirty) {
      uniformState._inverseViewProjectionDirty = false;

      Matrix4.inverse(
        uniformState.viewProjection,
        uniformState._inverseViewProjection
      );
    }
  }

  function cleanModelViewProjection(uniformState) {
    if (uniformState._modelViewProjectionDirty) {
      uniformState._modelViewProjectionDirty = false;

      Matrix4.multiply(
        uniformState._projection,
        uniformState.modelView,
        uniformState._modelViewProjection
      );
    }
  }

  function cleanModelViewRelativeToEye(uniformState) {
    if (uniformState._modelViewRelativeToEyeDirty) {
      uniformState._modelViewRelativeToEyeDirty = false;

      const mv = uniformState.modelView;
      const mvRte = uniformState._modelViewRelativeToEye;
      mvRte[0] = mv[0];
      mvRte[1] = mv[1];
      mvRte[2] = mv[2];
      mvRte[3] = mv[3];
      mvRte[4] = mv[4];
      mvRte[5] = mv[5];
      mvRte[6] = mv[6];
      mvRte[7] = mv[7];
      mvRte[8] = mv[8];
      mvRte[9] = mv[9];
      mvRte[10] = mv[10];
      mvRte[11] = mv[11];
      mvRte[12] = 0.0;
      mvRte[13] = 0.0;
      mvRte[14] = 0.0;
      mvRte[15] = mv[15];
    }
  }

  function cleanInverseModelViewProjection(uniformState) {
    if (uniformState._inverseModelViewProjectionDirty) {
      uniformState._inverseModelViewProjectionDirty = false;

      Matrix4.inverse(
        uniformState.modelViewProjection,
        uniformState._inverseModelViewProjection
      );
    }
  }

  function cleanModelViewProjectionRelativeToEye(uniformState) {
    if (uniformState._modelViewProjectionRelativeToEyeDirty) {
      uniformState._modelViewProjectionRelativeToEyeDirty = false;

      Matrix4.multiply(
        uniformState._projection,
        uniformState.modelViewRelativeToEye,
        uniformState._modelViewProjectionRelativeToEye
      );
    }
  }

  function cleanModelViewInfiniteProjection(uniformState) {
    if (uniformState._modelViewInfiniteProjectionDirty) {
      uniformState._modelViewInfiniteProjectionDirty = false;

      Matrix4.multiply(
        uniformState._infiniteProjection,
        uniformState.modelView,
        uniformState._modelViewInfiniteProjection
      );
    }
  }

  function cleanNormal(uniformState) {
    if (uniformState._normalDirty) {
      uniformState._normalDirty = false;

      const m = uniformState._normal;
      Matrix4.getMatrix3(uniformState.inverseModelView, m);
      Matrix3.getRotation(m, m);
      Matrix3.transpose(m, m);
    }
  }

  function cleanNormal3D(uniformState) {
    if (uniformState._normal3DDirty) {
      uniformState._normal3DDirty = false;

      const m = uniformState._normal3D;
      Matrix4.getMatrix3(uniformState.inverseModelView3D, m);
      Matrix3.getRotation(m, m);
      Matrix3.transpose(m, m);
    }
  }

  function cleanInverseNormal(uniformState) {
    if (uniformState._inverseNormalDirty) {
      uniformState._inverseNormalDirty = false;
      Matrix4.getMatrix3(
        uniformState.inverseModelView,
        uniformState._inverseNormal
      );
      Matrix3.getRotation(
        uniformState._inverseNormal,
        uniformState._inverseNormal
      );
    }
  }

  function cleanInverseNormal3D(uniformState) {
    if (uniformState._inverseNormal3DDirty) {
      uniformState._inverseNormal3DDirty = false;
      Matrix4.getMatrix3(
        uniformState.inverseModelView3D,
        uniformState._inverseNormal3D
      );
      Matrix3.getRotation(
        uniformState._inverseNormal3D,
        uniformState._inverseNormal3D
      );
    }
  }

  const cameraPositionMC = new Cartesian3();

  function cleanEncodedCameraPositionMC(uniformState) {
    if (uniformState._encodedCameraPositionMCDirty) {
      uniformState._encodedCameraPositionMCDirty = false;

      Matrix4.multiplyByPoint(
        uniformState.inverseModel,
        uniformState._cameraPosition,
        cameraPositionMC
      );
      EncodedCartesian3.fromCartesian(
        cameraPositionMC,
        uniformState._encodedCameraPositionMC
      );
    }
  }

  const view2Dto3DPScratch = new Cartesian3();
  const view2Dto3DRScratch = new Cartesian3();
  const view2Dto3DUScratch = new Cartesian3();
  const view2Dto3DDScratch = new Cartesian3();
  const view2Dto3DCartographicScratch = new Cartographic();
  const view2Dto3DCartesian3Scratch = new Cartesian3();
  const view2Dto3DMatrix4Scratch = new Matrix4();

  function view2Dto3D(
    position2D,
    direction2D,
    right2D,
    up2D,
    frustum2DWidth,
    mode,
    projection,
    result
  ) {
    // The camera position and directions are expressed in the 2D coordinate system where the Y axis is to the East,
    // the Z axis is to the North, and the X axis is out of the map.  Express them instead in the ENU axes where
    // X is to the East, Y is to the North, and Z is out of the local horizontal plane.
    const p = view2Dto3DPScratch;
    p.x = position2D.y;
    p.y = position2D.z;
    p.z = position2D.x;

    const r = view2Dto3DRScratch;
    r.x = right2D.y;
    r.y = right2D.z;
    r.z = right2D.x;

    const u = view2Dto3DUScratch;
    u.x = up2D.y;
    u.y = up2D.z;
    u.z = up2D.x;

    const d = view2Dto3DDScratch;
    d.x = direction2D.y;
    d.y = direction2D.z;
    d.z = direction2D.x;

    // In 2D, the camera height is always 12.7 million meters.
    // The apparent height is equal to half the frustum width.
    if (mode === SceneMode$1.SCENE2D) {
      p.z = frustum2DWidth * 0.5;
    }

    // Compute the equivalent camera position in the real (3D) world.
    // In 2D and Columbus View, the camera can travel outside the projection, and when it does so
    // there's not really any corresponding location in the real world.  So clamp the unprojected
    // longitude and latitude to their valid ranges.
    const cartographic = projection.unproject(p, view2Dto3DCartographicScratch);
    cartographic.longitude = CesiumMath.clamp(
      cartographic.longitude,
      -Math.PI,
      Math.PI
    );
    cartographic.latitude = CesiumMath.clamp(
      cartographic.latitude,
      -CesiumMath.PI_OVER_TWO,
      CesiumMath.PI_OVER_TWO
    );
    const ellipsoid = projection.ellipsoid;
    const position3D = ellipsoid.cartographicToCartesian(
      cartographic,
      view2Dto3DCartesian3Scratch
    );

    // Compute the rotation from the local ENU at the real world camera position to the fixed axes.
    const enuToFixed = Transforms.eastNorthUpToFixedFrame(
      position3D,
      ellipsoid,
      view2Dto3DMatrix4Scratch
    );

    // Transform each camera direction to the fixed axes.
    Matrix4.multiplyByPointAsVector(enuToFixed, r, r);
    Matrix4.multiplyByPointAsVector(enuToFixed, u, u);
    Matrix4.multiplyByPointAsVector(enuToFixed, d, d);

    // Compute the view matrix based on the new fixed-frame camera position and directions.
    if (!defined(result)) {
      result = new Matrix4();
    }

    result[0] = r.x;
    result[1] = u.x;
    result[2] = -d.x;
    result[3] = 0.0;
    result[4] = r.y;
    result[5] = u.y;
    result[6] = -d.y;
    result[7] = 0.0;
    result[8] = r.z;
    result[9] = u.z;
    result[10] = -d.z;
    result[11] = 0.0;
    result[12] = -Cartesian3.dot(r, position3D);
    result[13] = -Cartesian3.dot(u, position3D);
    result[14] = Cartesian3.dot(d, position3D);
    result[15] = 1.0;

    return result;
  }

  function updateView3D(that) {
    if (that._view3DDirty) {
      if (that._mode === SceneMode$1.SCENE3D) {
        Matrix4.clone(that._view, that._view3D);
      } else {
        view2Dto3D(
          that._cameraPosition,
          that._cameraDirection,
          that._cameraRight,
          that._cameraUp,
          that._frustum2DWidth,
          that._mode,
          that._mapProjection,
          that._view3D
        );
      }
      Matrix4.getMatrix3(that._view3D, that._viewRotation3D);
      that._view3DDirty = false;
    }
  }

  function updateInverseView3D(that) {
    if (that._inverseView3DDirty) {
      Matrix4.inverseTransformation(that.view3D, that._inverseView3D);
      Matrix4.getMatrix3(that._inverseView3D, that._inverseViewRotation3D);
      that._inverseView3DDirty = false;
    }
  }

  function errorToString(gl, error) {
    let message = "WebGL Error:  ";
    switch (error) {
      case gl.INVALID_ENUM:
        message += "INVALID_ENUM";
        break;
      case gl.INVALID_VALUE:
        message += "INVALID_VALUE";
        break;
      case gl.INVALID_OPERATION:
        message += "INVALID_OPERATION";
        break;
      case gl.OUT_OF_MEMORY:
        message += "OUT_OF_MEMORY";
        break;
      case gl.CONTEXT_LOST_WEBGL:
        message += "CONTEXT_LOST_WEBGL lost";
        break;
      default:
        message += `Unknown (${error})`;
    }

    return message;
  }

  function createErrorMessage(gl, glFunc, glFuncArguments, error) {
    let message = `${errorToString(gl, error)}: ${glFunc.name}(`;

    for (let i = 0; i < glFuncArguments.length; ++i) {
      if (i !== 0) {
        message += ", ";
      }
      message += glFuncArguments[i];
    }
    message += ");";

    return message;
  }

  function throwOnError(gl, glFunc, glFuncArguments) {
    const error = gl.getError();
    if (error !== gl.NO_ERROR) {
      throw new RuntimeError(
        createErrorMessage(gl, glFunc, glFuncArguments, error)
      );
    }
  }

  function makeGetterSetter(gl, propertyName, logFunction) {
    return {
      get: function () {
        const value = gl[propertyName];
        logFunction(gl, `get: ${propertyName}`, value);
        return gl[propertyName];
      },
      set: function (value) {
        gl[propertyName] = value;
        logFunction(gl, `set: ${propertyName}`, value);
      },
    };
  }

  function wrapGL(gl, logFunction) {
    if (!defined(logFunction)) {
      return gl;
    }

    function wrapFunction(property) {
      return function () {
        const result = property.apply(gl, arguments);
        logFunction(gl, property, arguments);
        return result;
      };
    }

    const glWrapper = {};

    // JavaScript linters normally demand that a for..in loop must directly contain an if,
    // but in our loop below, we actually intend to iterate all properties, including
    // those in the prototype.
    /*eslint-disable guard-for-in*/
    for (const propertyName in gl) {
      const property = gl[propertyName];

      // wrap any functions we encounter, otherwise just copy the property to the wrapper.
      if (property instanceof Function) {
        glWrapper[propertyName] = wrapFunction(property);
      } else {
        Object.defineProperty(
          glWrapper,
          propertyName,
          makeGetterSetter(gl, propertyName, logFunction)
        );
      }
    }
    /*eslint-enable guard-for-in*/

    return glWrapper;
  }

  function getExtension(gl, names) {
    const length = names.length;
    for (let i = 0; i < length; ++i) {
      const extension = gl.getExtension(names[i]);
      if (extension) {
        return extension;
      }
    }

    return undefined;
  }

  /**
   * @private
   * @constructor
   */
  function Context(canvas, options) {
    // this check must use typeof, not defined, because defined doesn't work with undeclared variables.
    if (typeof WebGLRenderingContext === "undefined") {
      throw new RuntimeError(
        "The browser does not support WebGL.  Visit http://get.webgl.org."
      );
    }

    //>>includeStart('debug', pragmas.debug);
    Check.defined("canvas", canvas);
    //>>includeEnd('debug');

    this._canvas = canvas;

    options = clone$1(options, true);
    // Don't use defaultValue.EMPTY_OBJECT here because the options object gets modified in the next line.
    options = defaultValue(options, {});
    options.allowTextureFilterAnisotropic = defaultValue(
      options.allowTextureFilterAnisotropic,
      true
    );
    const webglOptions = defaultValue(options.webgl, {});

    // Override select WebGL defaults
    webglOptions.alpha = defaultValue(webglOptions.alpha, false); // WebGL default is true
    webglOptions.stencil = defaultValue(webglOptions.stencil, true); // WebGL default is false

    const requestWebgl2 =
      defaultValue(options.requestWebgl2, false) &&
      typeof WebGL2RenderingContext !== "undefined";
    let webgl2 = false;

    let glContext;
    const getWebGLStub = options.getWebGLStub;

    if (!defined(getWebGLStub)) {
      if (requestWebgl2) {
        glContext =
          canvas.getContext("webgl2", webglOptions) ||
          canvas.getContext("experimental-webgl2", webglOptions) ||
          undefined;
        if (defined(glContext)) {
          webgl2 = true;
        }
      }
      if (!defined(glContext)) {
        glContext =
          canvas.getContext("webgl", webglOptions) ||
          canvas.getContext("experimental-webgl", webglOptions) ||
          undefined;
      }
      if (!defined(glContext)) {
        throw new RuntimeError(
          "The browser supports WebGL, but initialization failed."
        );
      }
    } else {
      // Use WebGL stub when requested for unit tests
      glContext = getWebGLStub(canvas, webglOptions);
    }

    this._originalGLContext = glContext;
    this._gl = glContext;
    this._webgl2 = webgl2;
    this._id = createGuid();

    // Validation and logging disabled by default for speed.
    this.validateFramebuffer = false;
    this.validateShaderProgram = false;
    this.logShaderCompilation = false;

    this._throwOnWebGLError = false;

    this._shaderCache = new ShaderCache(this);
    this._textureCache = new TextureCache();

    const gl = glContext;

    this._stencilBits = gl.getParameter(gl.STENCIL_BITS);

    ContextLimits._maximumCombinedTextureImageUnits = gl.getParameter(
      gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS
    ); // min: 8
    ContextLimits._maximumCubeMapSize = gl.getParameter(
      gl.MAX_CUBE_MAP_TEXTURE_SIZE
    ); // min: 16
    ContextLimits._maximumFragmentUniformVectors = gl.getParameter(
      gl.MAX_FRAGMENT_UNIFORM_VECTORS
    ); // min: 16
    ContextLimits._maximumTextureImageUnits = gl.getParameter(
      gl.MAX_TEXTURE_IMAGE_UNITS
    ); // min: 8
    ContextLimits._maximumRenderbufferSize = gl.getParameter(
      gl.MAX_RENDERBUFFER_SIZE
    ); // min: 1
    ContextLimits._maximumTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); // min: 64
    ContextLimits._maximumVaryingVectors = gl.getParameter(
      gl.MAX_VARYING_VECTORS
    ); // min: 8
    ContextLimits._maximumVertexAttributes = gl.getParameter(
      gl.MAX_VERTEX_ATTRIBS
    ); // min: 8
    ContextLimits._maximumVertexTextureImageUnits = gl.getParameter(
      gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS
    ); // min: 0
    ContextLimits._maximumVertexUniformVectors = gl.getParameter(
      gl.MAX_VERTEX_UNIFORM_VECTORS
    ); // min: 128

    ContextLimits._maximumSamples = this._webgl2
      ? gl.getParameter(gl.MAX_SAMPLES)
      : 0;

    const aliasedLineWidthRange = gl.getParameter(gl.ALIASED_LINE_WIDTH_RANGE); // must include 1
    ContextLimits._minimumAliasedLineWidth = aliasedLineWidthRange[0];
    ContextLimits._maximumAliasedLineWidth = aliasedLineWidthRange[1];

    const aliasedPointSizeRange = gl.getParameter(gl.ALIASED_POINT_SIZE_RANGE); // must include 1
    ContextLimits._minimumAliasedPointSize = aliasedPointSizeRange[0];
    ContextLimits._maximumAliasedPointSize = aliasedPointSizeRange[1];

    const maximumViewportDimensions = gl.getParameter(gl.MAX_VIEWPORT_DIMS);
    ContextLimits._maximumViewportWidth = maximumViewportDimensions[0];
    ContextLimits._maximumViewportHeight = maximumViewportDimensions[1];

    const highpFloat = gl.getShaderPrecisionFormat(
      gl.FRAGMENT_SHADER,
      gl.HIGH_FLOAT
    );
    ContextLimits._highpFloatSupported = highpFloat.precision !== 0;
    const highpInt = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_INT);
    ContextLimits._highpIntSupported = highpInt.rangeMax !== 0;

    this._antialias = gl.getContextAttributes().antialias;

    // Query and initialize extensions
    this._standardDerivatives = !!getExtension(gl, ["OES_standard_derivatives"]);
    this._blendMinmax = !!getExtension(gl, ["EXT_blend_minmax"]);
    this._elementIndexUint = !!getExtension(gl, ["OES_element_index_uint"]);
    this._depthTexture = !!getExtension(gl, [
      "WEBGL_depth_texture",
      "WEBKIT_WEBGL_depth_texture",
    ]);
    this._fragDepth = !!getExtension(gl, ["EXT_frag_depth"]);
    this._debugShaders = getExtension(gl, ["WEBGL_debug_shaders"]);

    this._textureFloat = !!getExtension(gl, ["OES_texture_float"]);
    this._textureHalfFloat = !!getExtension(gl, ["OES_texture_half_float"]);

    this._textureFloatLinear = !!getExtension(gl, ["OES_texture_float_linear"]);
    this._textureHalfFloatLinear = !!getExtension(gl, [
      "OES_texture_half_float_linear",
    ]);

    this._colorBufferFloat = !!getExtension(gl, [
      "EXT_color_buffer_float",
      "WEBGL_color_buffer_float",
    ]);
    this._floatBlend = !!getExtension(gl, ["EXT_float_blend"]);
    this._colorBufferHalfFloat = !!getExtension(gl, [
      "EXT_color_buffer_half_float",
    ]);

    this._s3tc = !!getExtension(gl, [
      "WEBGL_compressed_texture_s3tc",
      "MOZ_WEBGL_compressed_texture_s3tc",
      "WEBKIT_WEBGL_compressed_texture_s3tc",
    ]);
    this._pvrtc = !!getExtension(gl, [
      "WEBGL_compressed_texture_pvrtc",
      "WEBKIT_WEBGL_compressed_texture_pvrtc",
    ]);
    this._astc = !!getExtension(gl, ["WEBGL_compressed_texture_astc"]);
    this._etc = !!getExtension(gl, ["WEBG_compressed_texture_etc"]);
    this._etc1 = !!getExtension(gl, ["WEBGL_compressed_texture_etc1"]);
    this._bc7 = !!getExtension(gl, ["EXT_texture_compression_bptc"]);

    // It is necessary to pass supported formats to loadKTX2
    // because imagery layers don't have access to the context.
    loadKTX2.setKTX2SupportedFormats(
      this._s3tc,
      this._pvrtc,
      this._astc,
      this._etc,
      this._etc1,
      this._bc7
    );

    const textureFilterAnisotropic = options.allowTextureFilterAnisotropic
      ? getExtension(gl, [
          "EXT_texture_filter_anisotropic",
          "WEBKIT_EXT_texture_filter_anisotropic",
        ])
      : undefined;
    this._textureFilterAnisotropic = textureFilterAnisotropic;
    ContextLimits._maximumTextureFilterAnisotropy = defined(
      textureFilterAnisotropic
    )
      ? gl.getParameter(textureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT)
      : 1.0;

    let glCreateVertexArray;
    let glBindVertexArray;
    let glDeleteVertexArray;

    let glDrawElementsInstanced;
    let glDrawArraysInstanced;
    let glVertexAttribDivisor;

    let glDrawBuffers;

    let vertexArrayObject;
    let instancedArrays;
    let drawBuffers;

    if (webgl2) {
      const that = this;

      glCreateVertexArray = function () {
        return that._gl.createVertexArray();
      };
      glBindVertexArray = function (vao) {
        that._gl.bindVertexArray(vao);
      };
      glDeleteVertexArray = function (vao) {
        that._gl.deleteVertexArray(vao);
      };

      glDrawElementsInstanced = function (
        mode,
        count,
        type,
        offset,
        instanceCount
      ) {
        gl.drawElementsInstanced(mode, count, type, offset, instanceCount);
      };
      glDrawArraysInstanced = function (mode, first, count, instanceCount) {
        gl.drawArraysInstanced(mode, first, count, instanceCount);
      };
      glVertexAttribDivisor = function (index, divisor) {
        gl.vertexAttribDivisor(index, divisor);
      };

      glDrawBuffers = function (buffers) {
        gl.drawBuffers(buffers);
      };
    } else {
      vertexArrayObject = getExtension(gl, ["OES_vertex_array_object"]);
      if (defined(vertexArrayObject)) {
        glCreateVertexArray = function () {
          return vertexArrayObject.createVertexArrayOES();
        };
        glBindVertexArray = function (vertexArray) {
          vertexArrayObject.bindVertexArrayOES(vertexArray);
        };
        glDeleteVertexArray = function (vertexArray) {
          vertexArrayObject.deleteVertexArrayOES(vertexArray);
        };
      }

      instancedArrays = getExtension(gl, ["ANGLE_instanced_arrays"]);
      if (defined(instancedArrays)) {
        glDrawElementsInstanced = function (
          mode,
          count,
          type,
          offset,
          instanceCount
        ) {
          instancedArrays.drawElementsInstancedANGLE(
            mode,
            count,
            type,
            offset,
            instanceCount
          );
        };
        glDrawArraysInstanced = function (mode, first, count, instanceCount) {
          instancedArrays.drawArraysInstancedANGLE(
            mode,
            first,
            count,
            instanceCount
          );
        };
        glVertexAttribDivisor = function (index, divisor) {
          instancedArrays.vertexAttribDivisorANGLE(index, divisor);
        };
      }

      drawBuffers = getExtension(gl, ["WEBGL_draw_buffers"]);
      if (defined(drawBuffers)) {
        glDrawBuffers = function (buffers) {
          drawBuffers.drawBuffersWEBGL(buffers);
        };
      }
    }

    this.glCreateVertexArray = glCreateVertexArray;
    this.glBindVertexArray = glBindVertexArray;
    this.glDeleteVertexArray = glDeleteVertexArray;

    this.glDrawElementsInstanced = glDrawElementsInstanced;
    this.glDrawArraysInstanced = glDrawArraysInstanced;
    this.glVertexAttribDivisor = glVertexAttribDivisor;

    this.glDrawBuffers = glDrawBuffers;

    this._vertexArrayObject = !!vertexArrayObject;
    this._instancedArrays = !!instancedArrays;
    this._drawBuffers = !!drawBuffers;

    ContextLimits._maximumDrawBuffers = this.drawBuffers
      ? gl.getParameter(WebGLConstants$1.MAX_DRAW_BUFFERS)
      : 1;
    ContextLimits._maximumColorAttachments = this.drawBuffers
      ? gl.getParameter(WebGLConstants$1.MAX_COLOR_ATTACHMENTS)
      : 1;

    this._clearColor = new Color(0.0, 0.0, 0.0, 0.0);
    this._clearDepth = 1.0;
    this._clearStencil = 0;

    const us = new UniformState();
    const ps = new PassState(this);
    const rs = RenderState.fromCache();

    this._defaultPassState = ps;
    this._defaultRenderState = rs;
    // default texture has a value of (1, 1, 1)
    // default emissive texture has a value of (0, 0, 0)
    // default normal texture is +z which is encoded as (0.5, 0.5, 1)
    this._defaultTexture = undefined;
    this._defaultEmissiveTexture = undefined;
    this._defaultNormalTexture = undefined;
    this._defaultCubeMap = undefined;

    this._us = us;
    this._currentRenderState = rs;
    this._currentPassState = ps;
    this._currentFramebuffer = undefined;
    this._maxFrameTextureUnitIndex = 0;

    // Vertex attribute divisor state cache. Workaround for ANGLE (also look at VertexArray.setVertexAttribDivisor)
    this._vertexAttribDivisors = [];
    this._previousDrawInstanced = false;
    for (let i = 0; i < ContextLimits._maximumVertexAttributes; i++) {
      this._vertexAttribDivisors.push(0);
    }

    this._pickObjects = {};
    this._nextPickColor = new Uint32Array(1);

    /**
     * @example
     * {
     *   webgl : {
     *     alpha : false,
     *     depth : true,
     *     stencil : false,
     *     antialias : true,
     *     premultipliedAlpha : true,
     *     preserveDrawingBuffer : false,
     *     failIfMajorPerformanceCaveat : true
     *   },
     *   allowTextureFilterAnisotropic : true
     * }
     */
    this.options = options;

    /**
     * A cache of objects tied to this context.  Just before the Context is destroyed,
     * <code>destroy</code> will be invoked on each object in this object literal that has
     * such a method.  This is useful for caching any objects that might otherwise
     * be stored globally, except they're tied to a particular context, and to manage
     * their lifetime.
     *
     * @type {Object}
     */
    this.cache = {};

    RenderState.apply(gl, rs, ps);
  }

  const defaultFramebufferMarker = {};

  Object.defineProperties(Context.prototype, {
    id: {
      get: function () {
        return this._id;
      },
    },
    webgl2: {
      get: function () {
        return this._webgl2;
      },
    },
    canvas: {
      get: function () {
        return this._canvas;
      },
    },
    shaderCache: {
      get: function () {
        return this._shaderCache;
      },
    },
    textureCache: {
      get: function () {
        return this._textureCache;
      },
    },
    uniformState: {
      get: function () {
        return this._us;
      },
    },

    /**
     * The number of stencil bits per pixel in the default bound framebuffer.  The minimum is eight bits.
     * @memberof Context.prototype
     * @type {Number}
     * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with <code>STENCIL_BITS</code>.
     */
    stencilBits: {
      get: function () {
        return this._stencilBits;
      },
    },

    /**
     * <code>true</code> if the WebGL context supports stencil buffers.
     * Stencil buffers are not supported by all systems.
     * @memberof Context.prototype
     * @type {Boolean}
     */
    stencilBuffer: {
      get: function () {
        return this._stencilBits >= 8;
      },
    },

    /**
     * <code>true</code> if the WebGL context supports antialiasing.  By default
     * antialiasing is requested, but it is not supported by all systems.
     * @memberof Context.prototype
     * @type {Boolean}
     */
    antialias: {
      get: function () {
        return this._antialias;
      },
    },

    /**
     * <code>true</code> if the WebGL context supports multisample antialiasing. Requires
     * WebGL2.
     * @memberof Context.prototype
     * @type {Boolean}
     */
    msaa: {
      get: function () {
        return this._webgl2;
      },
    },

    /**
     * <code>true</code> if the OES_standard_derivatives extension is supported.  This
     * extension provides access to <code>dFdx</code>, <code>dFdy</code>, and <code>fwidth</code>
     * functions from GLSL.  A shader using these functions still needs to explicitly enable the
     * extension with <code>#extension GL_OES_standard_derivatives : enable</code>.
     * @memberof Context.prototype
     * @type {Boolean}
     * @see {@link http://www.khronos.org/registry/gles/extensions/OES/OES_standard_derivatives.txt|OES_standard_derivatives}
     */
    standardDerivatives: {
      get: function () {
        return this._standardDerivatives || this._webgl2;
      },
    },

    /**
     * <code>true</code> if the EXT_float_blend extension is supported. This
     * extension enables blending with 32-bit float values.
     * @memberof Context.prototype
     * @type {Boolean}
     * @see {@link https://www.khronos.org/registry/webgl/extensions/EXT_float_blend/}
     */
    floatBlend: {
      get: function () {
        return this._floatBlend;
      },
    },

    /**
     * <code>true</code> if the EXT_blend_minmax extension is supported.  This
     * extension extends blending capabilities by adding two new blend equations:
     * the minimum or maximum color components of the source and destination colors.
     * @memberof Context.prototype
     * @type {Boolean}
     * @see {@link https://www.khronos.org/registry/webgl/extensions/EXT_blend_minmax/}
     */
    blendMinmax: {
      get: function () {
        return this._blendMinmax || this._webgl2;
      },
    },

    /**
     * <code>true</code> if the OES_element_index_uint extension is supported.  This
     * extension allows the use of unsigned int indices, which can improve performance by
     * eliminating batch breaking caused by unsigned short indices.
     * @memberof Context.prototype
     * @type {Boolean}
     * @see {@link http://www.khronos.org/registry/webgl/extensions/OES_element_index_uint/|OES_element_index_uint}
     */
    elementIndexUint: {
      get: function () {
        return this._elementIndexUint || this._webgl2;
      },
    },

    /**
     * <code>true</code> if WEBGL_depth_texture is supported.  This extension provides
     * access to depth textures that, for example, can be attached to framebuffers for shadow mapping.
     * @memberof Context.prototype
     * @type {Boolean}
     * @see {@link http://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/|WEBGL_depth_texture}
     */
    depthTexture: {
      get: function () {
        return this._depthTexture || this._webgl2;
      },
    },

    /**
     * <code>true</code> if OES_texture_float is supported. This extension provides
     * access to floating point textures that, for example, can be attached to framebuffers for high dynamic range.
     * @memberof Context.prototype
     * @type {Boolean}
     * @see {@link https://www.khronos.org/registry/webgl/extensions/OES_texture_float/}
     */
    floatingPointTexture: {
      get: function () {
        return this._webgl2 || this._textureFloat;
      },
    },

    /**
     * <code>true</code> if OES_texture_half_float is supported. This extension provides
     * access to floating point textures that, for example, can be attached to framebuffers for high dynamic range.
     * @memberof Context.prototype
     * @type {Boolean}
     * @see {@link https://www.khronos.org/registry/webgl/extensions/OES_texture_half_float/}
     */
    halfFloatingPointTexture: {
      get: function () {
        return this._webgl2 || this._textureHalfFloat;
      },
    },

    /**
     * <code>true</code> if OES_texture_float_linear is supported. This extension provides
     * access to linear sampling methods for minification and magnification filters of floating-point textures.
     * @memberof Context.prototype
     * @type {Boolean}
     * @see {@link https://www.khronos.org/registry/webgl/extensions/OES_texture_float_linear/}
     */
    textureFloatLinear: {
      get: function () {
        return this._textureFloatLinear;
      },
    },

    /**
     * <code>true</code> if OES_texture_half_float_linear is supported. This extension provides
     * access to linear sampling methods for minification and magnification filters of half floating-point textures.
     * @memberof Context.prototype
     * @type {Boolean}
     * @see {@link https://www.khronos.org/registry/webgl/extensions/OES_texture_half_float_linear/}
     */
    textureHalfFloatLinear: {
      get: function () {
        return (
          (this._webgl2 && this._textureFloatLinear) ||
          (!this._webgl2 && this._textureHalfFloatLinear)
        );
      },
    },

    /**
     * <code>true</code> if EXT_texture_filter_anisotropic is supported. This extension provides
     * access to anisotropic filtering for textured surfaces at an oblique angle from the viewer.
     * @memberof Context.prototype
     * @type {Boolean}
     * @see {@link https://www.khronos.org/registry/webgl/extensions/EXT_texture_filter_anisotropic/}
     */
    textureFilterAnisotropic: {
      get: function () {
        return !!this._textureFilterAnisotropic;
      },
    },

    /**
     * <code>true</code> if WEBGL_compressed_texture_s3tc is supported.  This extension provides
     * access to DXT compressed textures.
     * @memberof Context.prototype
     * @type {Boolean}
     * @see {@link https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_s3tc/}
     */
    s3tc: {
      get: function () {
        return this._s3tc;
      },
    },

    /**
     * <code>true</code> if WEBGL_compressed_texture_pvrtc is supported.  This extension provides
     * access to PVR compressed textures.
     * @memberof Context.prototype
     * @type {Boolean}
     * @see {@link https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_pvrtc/}
     */
    pvrtc: {
      get: function () {
        return this._pvrtc;
      },
    },

    /**
     * <code>true</code> if WEBGL_compressed_texture_astc is supported.  This extension provides
     * access to ASTC compressed textures.
     * @memberof Context.prototype
     * @type {Boolean}
     * @see {@link https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_astc/}
     */
    astc: {
      get: function () {
        return this._astc;
      },
    },

    /**
     * <code>true</code> if WEBGL_compressed_texture_etc is supported.  This extension provides
     * access to ETC compressed textures.
     * @memberof Context.prototype
     * @type {Boolean}
     * @see {@link https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_etc/}
     */
    etc: {
      get: function () {
        return this._etc;
      },
    },

    /**
     * <code>true</code> if WEBGL_compressed_texture_etc1 is supported.  This extension provides
     * access to ETC1 compressed textures.
     * @memberof Context.prototype
     * @type {Boolean}
     * @see {@link https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_etc1/}
     */
    etc1: {
      get: function () {
        return this._etc1;
      },
    },

    /**
     * <code>true</code> if EXT_texture_compression_bptc is supported.  This extension provides
     * access to BC7 compressed textures.
     * @memberof Context.prototype
     * @type {Boolean}
     * @see {@link https://www.khronos.org/registry/webgl/extensions/EXT_texture_compression_bptc/}
     */
    bc7: {
      get: function () {
        return this._bc7;
      },
    },

    /**
     * <code>true</code> if S3TC, PVRTC, ASTC, ETC, ETC1, or BC7 compression is supported.
     * @memberof Context.prototype
     * @type {Boolean}
     */
    supportsBasis: {
      get: function () {
        return (
          this._s3tc ||
          this._pvrtc ||
          this._astc ||
          this._etc ||
          this._etc1 ||
          this._bc7
        );
      },
    },

    /**
     * <code>true</code> if the OES_vertex_array_object extension is supported.  This
     * extension can improve performance by reducing the overhead of switching vertex arrays.
     * When enabled, this extension is automatically used by {@link VertexArray}.
     * @memberof Context.prototype
     * @type {Boolean}
     * @see {@link http://www.khronos.org/registry/webgl/extensions/OES_vertex_array_object/|OES_vertex_array_object}
     */
    vertexArrayObject: {
      get: function () {
        return this._vertexArrayObject || this._webgl2;
      },
    },

    /**
     * <code>true</code> if the EXT_frag_depth extension is supported.  This
     * extension provides access to the <code>gl_FragDepthEXT</code> built-in output variable
     * from GLSL fragment shaders.  A shader using these functions still needs to explicitly enable the
     * extension with <code>#extension GL_EXT_frag_depth : enable</code>.
     * @memberof Context.prototype
     * @type {Boolean}
     * @see {@link http://www.khronos.org/registry/webgl/extensions/EXT_frag_depth/|EXT_frag_depth}
     */
    fragmentDepth: {
      get: function () {
        return this._fragDepth || this._webgl2;
      },
    },

    /**
     * <code>true</code> if the ANGLE_instanced_arrays extension is supported.  This
     * extension provides access to instanced rendering.
     * @memberof Context.prototype
     * @type {Boolean}
     * @see {@link https://www.khronos.org/registry/webgl/extensions/ANGLE_instanced_arrays}
     */
    instancedArrays: {
      get: function () {
        return this._instancedArrays || this._webgl2;
      },
    },

    /**
     * <code>true</code> if the EXT_color_buffer_float extension is supported.  This
     * extension makes the gl.RGBA32F format color renderable.
     * @memberof Context.prototype
     * @type {Boolean}
     * @see {@link https://www.khronos.org/registry/webgl/extensions/WEBGL_color_buffer_float/}
     * @see {@link https://www.khronos.org/registry/webgl/extensions/EXT_color_buffer_float/}
     */
    colorBufferFloat: {
      get: function () {
        return this._colorBufferFloat;
      },
    },

    /**
     * <code>true</code> if the EXT_color_buffer_half_float extension is supported.  This
     * extension makes the format gl.RGBA16F format color renderable.
     * @memberof Context.prototype
     * @type {Boolean}
     * @see {@link https://www.khronos.org/registry/webgl/extensions/EXT_color_buffer_half_float/}
     * @see {@link https://www.khronos.org/registry/webgl/extensions/EXT_color_buffer_float/}
     */
    colorBufferHalfFloat: {
      get: function () {
        return (
          (this._webgl2 && this._colorBufferFloat) ||
          (!this._webgl2 && this._colorBufferHalfFloat)
        );
      },
    },

    /**
     * <code>true</code> if the WEBGL_draw_buffers extension is supported. This
     * extensions provides support for multiple render targets. The framebuffer object can have mutiple
     * color attachments and the GLSL fragment shader can write to the built-in output array <code>gl_FragData</code>.
     * A shader using this feature needs to explicitly enable the extension with
     * <code>#extension GL_EXT_draw_buffers : enable</code>.
     * @memberof Context.prototype
     * @type {Boolean}
     * @see {@link http://www.khronos.org/registry/webgl/extensions/WEBGL_draw_buffers/|WEBGL_draw_buffers}
     */
    drawBuffers: {
      get: function () {
        return this._drawBuffers || this._webgl2;
      },
    },

    debugShaders: {
      get: function () {
        return this._debugShaders;
      },
    },

    throwOnWebGLError: {
      get: function () {
        return this._throwOnWebGLError;
      },
      set: function (value) {
        this._throwOnWebGLError = value;
        this._gl = wrapGL(
          this._originalGLContext,
          value ? throwOnError : undefined
        );
      },
    },

    /**
     * A 1x1 RGBA texture initialized to [255, 255, 255, 255].  This can
     * be used as a placeholder texture while other textures are downloaded.
     * @memberof Context.prototype
     * @type {Texture}
     */
    defaultTexture: {
      get: function () {
        if (this._defaultTexture === undefined) {
          this._defaultTexture = new Texture({
            context: this,
            source: {
              width: 1,
              height: 1,
              arrayBufferView: new Uint8Array([255, 255, 255, 255]),
            },
            flipY: false,
          });
        }

        return this._defaultTexture;
      },
    },
    /**
     * A 1x1 RGB texture initialized to [0, 0, 0] representing a material that is
     * not emissive. This can be used as a placeholder texture for emissive
     * textures while other textures are downloaded.
     * @memberof Context.prototype
     * @type {Texture}
     */
    defaultEmissiveTexture: {
      get: function () {
        if (this._defaultEmissiveTexture === undefined) {
          this._defaultEmissiveTexture = new Texture({
            context: this,
            pixelFormat: PixelFormat$1.RGB,
            source: {
              width: 1,
              height: 1,
              arrayBufferView: new Uint8Array([0, 0, 0]),
            },
            flipY: false,
          });
        }

        return this._defaultEmissiveTexture;
      },
    },
    /**
     * A 1x1 RGBA texture initialized to [128, 128, 255] to encode a tangent
     * space normal pointing in the +z direction, i.e. (0, 0, 1). This can
     * be used as a placeholder normal texture while other textures are
     * downloaded.
     * @memberof Context.prototype
     * @type {Texture}
     */
    defaultNormalTexture: {
      get: function () {
        if (this._defaultNormalTexture === undefined) {
          this._defaultNormalTexture = new Texture({
            context: this,
            pixelFormat: PixelFormat$1.RGB,
            source: {
              width: 1,
              height: 1,
              arrayBufferView: new Uint8Array([128, 128, 255]),
            },
            flipY: false,
          });
        }

        return this._defaultNormalTexture;
      },
    },

    /**
     * A cube map, where each face is a 1x1 RGBA texture initialized to
     * [255, 255, 255, 255].  This can be used as a placeholder cube map while
     * other cube maps are downloaded.
     * @memberof Context.prototype
     * @type {CubeMap}
     */
    defaultCubeMap: {
      get: function () {
        if (this._defaultCubeMap === undefined) {
          const face = {
            width: 1,
            height: 1,
            arrayBufferView: new Uint8Array([255, 255, 255, 255]),
          };

          this._defaultCubeMap = new CubeMap({
            context: this,
            source: {
              positiveX: face,
              negativeX: face,
              positiveY: face,
              negativeY: face,
              positiveZ: face,
              negativeZ: face,
            },
            flipY: false,
          });
        }

        return this._defaultCubeMap;
      },
    },

    /**
     * The drawingBufferHeight of the underlying GL context.
     * @memberof Context.prototype
     * @type {Number}
     * @see {@link https://www.khronos.org/registry/webgl/specs/1.0/#DOM-WebGLRenderingContext-drawingBufferHeight|drawingBufferHeight}
     */
    drawingBufferHeight: {
      get: function () {
        return this._gl.drawingBufferHeight;
      },
    },

    /**
     * The drawingBufferWidth of the underlying GL context.
     * @memberof Context.prototype
     * @type {Number}
     * @see {@link https://www.khronos.org/registry/webgl/specs/1.0/#DOM-WebGLRenderingContext-drawingBufferWidth|drawingBufferWidth}
     */
    drawingBufferWidth: {
      get: function () {
        return this._gl.drawingBufferWidth;
      },
    },

    /**
     * Gets an object representing the currently bound framebuffer.  While this instance is not an actual
     * {@link Framebuffer}, it is used to represent the default framebuffer in calls to
     * {@link Texture.fromFramebuffer}.
     * @memberof Context.prototype
     * @type {Object}
     */
    defaultFramebuffer: {
      get: function () {
        return defaultFramebufferMarker;
      },
    },
  });

  /**
   * Validates a framebuffer.
   * Available in debug builds only.
   * @private
   */
  function validateFramebuffer(context) {
    //>>includeStart('debug', pragmas.debug);
    if (context.validateFramebuffer) {
      const gl = context._gl;
      const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);

      if (status !== gl.FRAMEBUFFER_COMPLETE) {
        let message;

        switch (status) {
          case gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
            message =
              "Framebuffer is not complete.  Incomplete attachment: at least one attachment point with a renderbuffer or texture attached has its attached object no longer in existence or has an attached image with a width or height of zero, or the color attachment point has a non-color-renderable image attached, or the depth attachment point has a non-depth-renderable image attached, or the stencil attachment point has a non-stencil-renderable image attached.  Color-renderable formats include GL_RGBA4, GL_RGB5_A1, and GL_RGB565. GL_DEPTH_COMPONENT16 is the only depth-renderable format. GL_STENCIL_INDEX8 is the only stencil-renderable format.";
            break;
          case gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
            message =
              "Framebuffer is not complete.  Incomplete dimensions: not all attached images have the same width and height.";
            break;
          case gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
            message =
              "Framebuffer is not complete.  Missing attachment: no images are attached to the framebuffer.";
            break;
          case gl.FRAMEBUFFER_UNSUPPORTED:
            message =
              "Framebuffer is not complete.  Unsupported: the combination of internal formats of the attached images violates an implementation-dependent set of restrictions.";
            break;
        }

        throw new DeveloperError(message);
      }
    }
    //>>includeEnd('debug');
  }

  function applyRenderState(context, renderState, passState, clear) {
    const previousRenderState = context._currentRenderState;
    const previousPassState = context._currentPassState;
    context._currentRenderState = renderState;
    context._currentPassState = passState;
    RenderState.partialApply(
      context._gl,
      previousRenderState,
      renderState,
      previousPassState,
      passState,
      clear
    );
  }

  let scratchBackBufferArray;
  // this check must use typeof, not defined, because defined doesn't work with undeclared variables.
  if (typeof WebGLRenderingContext !== "undefined") {
    scratchBackBufferArray = [WebGLConstants$1.BACK];
  }

  function bindFramebuffer(context, framebuffer) {
    if (framebuffer !== context._currentFramebuffer) {
      context._currentFramebuffer = framebuffer;
      let buffers = scratchBackBufferArray;

      if (defined(framebuffer)) {
        framebuffer._bind();
        validateFramebuffer(context);

        // TODO: Need a way for a command to give what draw buffers are active.
        buffers = framebuffer._getActiveColorAttachments();
      } else {
        const gl = context._gl;
        gl.bindFramebuffer(gl.FRAMEBUFFER, null);
      }

      if (context.drawBuffers) {
        context.glDrawBuffers(buffers);
      }
    }
  }

  const defaultClearCommand = new ClearCommand();

  Context.prototype.clear = function (clearCommand, passState) {
    clearCommand = defaultValue(clearCommand, defaultClearCommand);
    passState = defaultValue(passState, this._defaultPassState);

    const gl = this._gl;
    let bitmask = 0;

    const c = clearCommand.color;
    const d = clearCommand.depth;
    const s = clearCommand.stencil;

    if (defined(c)) {
      if (!Color.equals(this._clearColor, c)) {
        Color.clone(c, this._clearColor);
        gl.clearColor(c.red, c.green, c.blue, c.alpha);
      }
      bitmask |= gl.COLOR_BUFFER_BIT;
    }

    if (defined(d)) {
      if (d !== this._clearDepth) {
        this._clearDepth = d;
        gl.clearDepth(d);
      }
      bitmask |= gl.DEPTH_BUFFER_BIT;
    }

    if (defined(s)) {
      if (s !== this._clearStencil) {
        this._clearStencil = s;
        gl.clearStencil(s);
      }
      bitmask |= gl.STENCIL_BUFFER_BIT;
    }

    const rs = defaultValue(clearCommand.renderState, this._defaultRenderState);
    applyRenderState(this, rs, passState, true);

    // The command's framebuffer takes presidence over the pass' framebuffer, e.g., for off-screen rendering.
    const framebuffer = defaultValue(
      clearCommand.framebuffer,
      passState.framebuffer
    );
    bindFramebuffer(this, framebuffer);

    gl.clear(bitmask);
  };

  function beginDraw(
    context,
    framebuffer,
    passState,
    shaderProgram,
    renderState
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (defined(framebuffer) && renderState.depthTest) {
      if (renderState.depthTest.enabled && !framebuffer.hasDepthAttachment) {
        throw new DeveloperError(
          "The depth test can not be enabled (drawCommand.renderState.depthTest.enabled) because the framebuffer (drawCommand.framebuffer) does not have a depth or depth-stencil renderbuffer."
        );
      }
    }
    //>>includeEnd('debug');

    bindFramebuffer(context, framebuffer);
    applyRenderState(context, renderState, passState, false);
    shaderProgram._bind();
    context._maxFrameTextureUnitIndex = Math.max(
      context._maxFrameTextureUnitIndex,
      shaderProgram.maximumTextureUnitIndex
    );
  }

  function continueDraw(context, drawCommand, shaderProgram, uniformMap) {
    const primitiveType = drawCommand._primitiveType;
    const va = drawCommand._vertexArray;
    let offset = drawCommand._offset;
    let count = drawCommand._count;
    const instanceCount = drawCommand.instanceCount;

    //>>includeStart('debug', pragmas.debug);
    if (!PrimitiveType$1.validate(primitiveType)) {
      throw new DeveloperError(
        "drawCommand.primitiveType is required and must be valid."
      );
    }

    Check.defined("drawCommand.vertexArray", va);
    Check.typeOf.number.greaterThanOrEquals("drawCommand.offset", offset, 0);
    if (defined(count)) {
      Check.typeOf.number.greaterThanOrEquals("drawCommand.count", count, 0);
    }
    Check.typeOf.number.greaterThanOrEquals(
      "drawCommand.instanceCount",
      instanceCount,
      0
    );
    if (instanceCount > 0 && !context.instancedArrays) {
      throw new DeveloperError("Instanced arrays extension is not supported");
    }
    //>>includeEnd('debug');

    context._us.model = defaultValue(drawCommand._modelMatrix, Matrix4.IDENTITY);
    shaderProgram._setUniforms(
      uniformMap,
      context._us,
      context.validateShaderProgram
    );

    va._bind();
    const indexBuffer = va.indexBuffer;

    if (defined(indexBuffer)) {
      offset = offset * indexBuffer.bytesPerIndex; // offset in vertices to offset in bytes
      count = defaultValue(count, indexBuffer.numberOfIndices);
      if (instanceCount === 0) {
        context._gl.drawElements(
          primitiveType,
          count,
          indexBuffer.indexDatatype,
          offset
        );
      } else {
        context.glDrawElementsInstanced(
          primitiveType,
          count,
          indexBuffer.indexDatatype,
          offset,
          instanceCount
        );
      }
    } else {
      count = defaultValue(count, va.numberOfVertices);
      if (instanceCount === 0) {
        context._gl.drawArrays(primitiveType, offset, count);
      } else {
        context.glDrawArraysInstanced(
          primitiveType,
          offset,
          count,
          instanceCount
        );
      }
    }

    va._unBind();
  }

  Context.prototype.draw = function (
    drawCommand,
    passState,
    shaderProgram,
    uniformMap
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("drawCommand", drawCommand);
    Check.defined("drawCommand.shaderProgram", drawCommand._shaderProgram);
    //>>includeEnd('debug');

    passState = defaultValue(passState, this._defaultPassState);
    // The command's framebuffer takes presidence over the pass' framebuffer, e.g., for off-screen rendering.
    const framebuffer = defaultValue(
      drawCommand._framebuffer,
      passState.framebuffer
    );
    const renderState = defaultValue(
      drawCommand._renderState,
      this._defaultRenderState
    );
    shaderProgram = defaultValue(shaderProgram, drawCommand._shaderProgram);
    uniformMap = defaultValue(uniformMap, drawCommand._uniformMap);

    beginDraw(this, framebuffer, passState, shaderProgram, renderState);
    continueDraw(this, drawCommand, shaderProgram, uniformMap);
  };

  Context.prototype.endFrame = function () {
    const gl = this._gl;
    gl.useProgram(null);

    this._currentFramebuffer = undefined;
    gl.bindFramebuffer(gl.FRAMEBUFFER, null);

    const buffers = scratchBackBufferArray;
    if (this.drawBuffers) {
      this.glDrawBuffers(buffers);
    }

    const length = this._maxFrameTextureUnitIndex;
    this._maxFrameTextureUnitIndex = 0;

    for (let i = 0; i < length; ++i) {
      gl.activeTexture(gl.TEXTURE0 + i);
      gl.bindTexture(gl.TEXTURE_2D, null);
      gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
    }
  };

  Context.prototype.readPixels = function (readState) {
    const gl = this._gl;

    readState = defaultValue(readState, defaultValue.EMPTY_OBJECT);
    const x = Math.max(defaultValue(readState.x, 0), 0);
    const y = Math.max(defaultValue(readState.y, 0), 0);
    const width = defaultValue(readState.width, gl.drawingBufferWidth);
    const height = defaultValue(readState.height, gl.drawingBufferHeight);
    const framebuffer = readState.framebuffer;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number.greaterThan("readState.width", width, 0);
    Check.typeOf.number.greaterThan("readState.height", height, 0);
    //>>includeEnd('debug');

    let pixelDatatype = PixelDatatype$1.UNSIGNED_BYTE;
    if (defined(framebuffer) && framebuffer.numberOfColorAttachments > 0) {
      pixelDatatype = framebuffer.getColorTexture(0).pixelDatatype;
    }

    const pixels = PixelFormat$1.createTypedArray(
      PixelFormat$1.RGBA,
      pixelDatatype,
      width,
      height
    );

    bindFramebuffer(this, framebuffer);

    gl.readPixels(
      x,
      y,
      width,
      height,
      PixelFormat$1.RGBA,
      PixelDatatype$1.toWebGLConstant(pixelDatatype, this),
      pixels
    );

    return pixels;
  };

  const viewportQuadAttributeLocations = {
    position: 0,
    textureCoordinates: 1,
  };

  Context.prototype.getViewportQuadVertexArray = function () {
    // Per-context cache for viewport quads
    let vertexArray = this.cache.viewportQuad_vertexArray;

    if (!defined(vertexArray)) {
      const geometry = new Geometry({
        attributes: {
          position: new GeometryAttribute({
            componentDatatype: ComponentDatatype$1.FLOAT,
            componentsPerAttribute: 2,
            values: [-1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0],
          }),

          textureCoordinates: new GeometryAttribute({
            componentDatatype: ComponentDatatype$1.FLOAT,
            componentsPerAttribute: 2,
            values: [0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0],
          }),
        },
        // Workaround Internet Explorer 11.0.8 lack of TRIANGLE_FAN
        indices: new Uint16Array([0, 1, 2, 0, 2, 3]),
        primitiveType: PrimitiveType$1.TRIANGLES,
      });

      vertexArray = VertexArray.fromGeometry({
        context: this,
        geometry: geometry,
        attributeLocations: viewportQuadAttributeLocations,
        bufferUsage: BufferUsage$1.STATIC_DRAW,
        interleave: true,
      });

      this.cache.viewportQuad_vertexArray = vertexArray;
    }

    return vertexArray;
  };

  Context.prototype.createViewportQuadCommand = function (
    fragmentShaderSource,
    overrides
  ) {
    overrides = defaultValue(overrides, defaultValue.EMPTY_OBJECT);

    return new DrawCommand({
      vertexArray: this.getViewportQuadVertexArray(),
      primitiveType: PrimitiveType$1.TRIANGLES,
      renderState: overrides.renderState,
      shaderProgram: ShaderProgram.fromCache({
        context: this,
        vertexShaderSource: ViewportQuadVS,
        fragmentShaderSource: fragmentShaderSource,
        attributeLocations: viewportQuadAttributeLocations,
      }),
      uniformMap: overrides.uniformMap,
      owner: overrides.owner,
      framebuffer: overrides.framebuffer,
      pass: overrides.pass,
    });
  };

  /**
   * Gets the object associated with a pick color.
   *
   * @param {Color} pickColor The pick color.
   * @returns {Object} The object associated with the pick color, or undefined if no object is associated with that color.
   *
   * @example
   * const object = context.getObjectByPickColor(pickColor);
   *
   * @see Context#createPickId
   */
  Context.prototype.getObjectByPickColor = function (pickColor) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("pickColor", pickColor);
    //>>includeEnd('debug');

    return this._pickObjects[pickColor.toRgba()];
  };

  function PickId(pickObjects, key, color) {
    this._pickObjects = pickObjects;
    this.key = key;
    this.color = color;
  }

  Object.defineProperties(PickId.prototype, {
    object: {
      get: function () {
        return this._pickObjects[this.key];
      },
      set: function (value) {
        this._pickObjects[this.key] = value;
      },
    },
  });

  PickId.prototype.destroy = function () {
    delete this._pickObjects[this.key];
    return undefined;
  };

  /**
   * Creates a unique ID associated with the input object for use with color-buffer picking.
   * The ID has an RGBA color value unique to this context.  You must call destroy()
   * on the pick ID when destroying the input object.
   *
   * @param {Object} object The object to associate with the pick ID.
   * @returns {Object} A PickId object with a <code>color</code> property.
   *
   * @exception {RuntimeError} Out of unique Pick IDs.
   *
   *
   * @example
   * this._pickId = context.createPickId({
   *   primitive : this,
   *   id : this.id
   * });
   *
   * @see Context#getObjectByPickColor
   */
  Context.prototype.createPickId = function (object) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("object", object);
    //>>includeEnd('debug');

    // the increment and assignment have to be separate statements to
    // actually detect overflow in the Uint32 value
    ++this._nextPickColor[0];
    const key = this._nextPickColor[0];
    if (key === 0) {
      // In case of overflow
      throw new RuntimeError("Out of unique Pick IDs.");
    }

    this._pickObjects[key] = object;
    return new PickId(this._pickObjects, key, Color.fromRgba(key));
  };

  Context.prototype.isDestroyed = function () {
    return false;
  };

  Context.prototype.destroy = function () {
    // Destroy all objects in the cache that have a destroy method.
    const cache = this.cache;
    for (const property in cache) {
      if (cache.hasOwnProperty(property)) {
        const propertyValue = cache[property];
        if (defined(propertyValue.destroy)) {
          propertyValue.destroy();
        }
      }
    }

    this._shaderCache = this._shaderCache.destroy();
    this._textureCache = this._textureCache.destroy();
    this._defaultTexture = this._defaultTexture && this._defaultTexture.destroy();
    this._defaultEmissiveTexture =
      this._defaultEmissiveTexture && this._defaultEmissiveTexture.destroy();
    this._defaultNormalTexture =
      this._defaultNormalTexture && this._defaultNormalTexture.destroy();
    this._defaultCubeMap = this._defaultCubeMap && this._defaultCubeMap.destroy();

    return destroyObject(this);
  };

  /**
   * Asynchronously loads six images and creates a cube map.  Returns a promise that
   * will resolve to a {@link CubeMap} once loaded, or reject if any image fails to load.
   *
   * @function loadCubeMap
   *
   * @param {Context} context The context to use to create the cube map.
   * @param {Object} urls The source URL of each image.  See the example below.
   * @param {Boolean} [skipColorSpaceConversion=false] If true, any custom gamma or color profiles in the images will be ignored.
   * @returns {Promise.<CubeMap>} a promise that will resolve to the requested {@link CubeMap} when loaded.
   *
   * @exception {DeveloperError} context is required.
   * @exception {DeveloperError} urls is required and must have positiveX, negativeX, positiveY, negativeY, positiveZ, and negativeZ properties.
   *
   *
   * @example
   * Cesium.loadCubeMap(context, {
   *     positiveX : 'skybox_px.png',
   *     negativeX : 'skybox_nx.png',
   *     positiveY : 'skybox_py.png',
   *     negativeY : 'skybox_ny.png',
   *     positiveZ : 'skybox_pz.png',
   *     negativeZ : 'skybox_nz.png'
   * }).then(function(cubeMap) {
   *     // use the cubemap
   * }).catch(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}
   *
   * @private
   */
  function loadCubeMap(context, urls, skipColorSpaceConversion) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("context", context);
    if (
      !defined(urls) ||
      !defined(urls.positiveX) ||
      !defined(urls.negativeX) ||
      !defined(urls.positiveY) ||
      !defined(urls.negativeY) ||
      !defined(urls.positiveZ) ||
      !defined(urls.negativeZ)
    ) {
      throw new DeveloperError(
        "urls is required and must have positiveX, negativeX, positiveY, negativeY, positiveZ, and negativeZ properties."
      );
    }
    //>>includeEnd('debug');

    // PERFORMANCE_IDEA: Given the size of some cube maps, we should consider tiling them, which
    // would prevent hiccups when uploading, for example, six 4096x4096 textures to the GPU.
    //
    // Also, it is perhaps acceptable to use the context here in the callbacks, but
    // ideally, we would do it in the primitive's update function.
    const flipOptions = {
      flipY: true,
      skipColorSpaceConversion: skipColorSpaceConversion,
      preferImageBitmap: true,
    };

    const facePromises = [
      Resource.createIfNeeded(urls.positiveX).fetchImage(flipOptions),
      Resource.createIfNeeded(urls.negativeX).fetchImage(flipOptions),
      Resource.createIfNeeded(urls.positiveY).fetchImage(flipOptions),
      Resource.createIfNeeded(urls.negativeY).fetchImage(flipOptions),
      Resource.createIfNeeded(urls.positiveZ).fetchImage(flipOptions),
      Resource.createIfNeeded(urls.negativeZ).fetchImage(flipOptions),
    ];

    return Promise.all(facePromises).then(function (images) {
      return new CubeMap({
        context: context,
        source: {
          positiveX: images[0],
          negativeX: images[1],
          positiveY: images[2],
          negativeY: images[3],
          positiveZ: images[4],
          negativeZ: images[5],
        },
      });
    });
  }

  /**
   * A policy for discarding tile images that match a known image containing a
   * "missing" image.
   *
   * @alias DiscardMissingTileImagePolicy
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Resource|String} options.missingImageUrl The URL of the known missing image.
   * @param {Cartesian2[]} options.pixelsToCheck An array of {@link Cartesian2} pixel positions to
   *        compare against the missing image.
   * @param {Boolean} [options.disableCheckIfAllPixelsAreTransparent=false] If true, the discard check will be disabled
   *                  if all of the pixelsToCheck in the missingImageUrl have an alpha value of 0.  If false, the
   *                  discard check will proceed no matter the values of the pixelsToCheck.
   */
  function DiscardMissingTileImagePolicy(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    if (!defined(options.missingImageUrl)) {
      throw new DeveloperError("options.missingImageUrl is required.");
    }

    if (!defined(options.pixelsToCheck)) {
      throw new DeveloperError("options.pixelsToCheck is required.");
    }
    //>>includeEnd('debug');

    this._pixelsToCheck = options.pixelsToCheck;
    this._missingImagePixels = undefined;
    this._missingImageByteLength = undefined;
    this._isReady = false;

    const resource = Resource.createIfNeeded(options.missingImageUrl);

    const that = this;

    function success(image) {
      if (defined(image.blob)) {
        that._missingImageByteLength = image.blob.size;
      }

      let pixels = getImagePixels(image);

      if (options.disableCheckIfAllPixelsAreTransparent) {
        let allAreTransparent = true;
        const width = image.width;

        const pixelsToCheck = options.pixelsToCheck;
        for (
          let i = 0, len = pixelsToCheck.length;
          allAreTransparent && i < len;
          ++i
        ) {
          const pos = pixelsToCheck[i];
          const index = pos.x * 4 + pos.y * width;
          const alpha = pixels[index + 3];

          if (alpha > 0) {
            allAreTransparent = false;
          }
        }

        if (allAreTransparent) {
          pixels = undefined;
        }
      }

      that._missingImagePixels = pixels;
      that._isReady = true;
    }

    function failure() {
      // Failed to download "missing" image, so assume that any truly missing tiles
      // will also fail to download and disable the discard check.
      that._missingImagePixels = undefined;
      that._isReady = true;
    }

    resource
      .fetchImage({
        preferBlob: true,
        preferImageBitmap: true,
        flipY: true,
      })
      .then(success)
      .catch(failure);
  }

  /**
   * Determines if the discard policy is ready to process images.
   * @returns {Boolean} True if the discard policy is ready to process images; otherwise, false.
   */
  DiscardMissingTileImagePolicy.prototype.isReady = function () {
    return this._isReady;
  };

  /**
   * Given a tile image, decide whether to discard that image.
   *
   * @param {HTMLImageElement} image An image to test.
   * @returns {Boolean} True if the image should be discarded; otherwise, false.
   *
   * @exception {DeveloperError} <code>shouldDiscardImage</code> must not be called before the discard policy is ready.
   */
  DiscardMissingTileImagePolicy.prototype.shouldDiscardImage = function (image) {
    //>>includeStart('debug', pragmas.debug);
    if (!this._isReady) {
      throw new DeveloperError(
        "shouldDiscardImage must not be called before the discard policy is ready."
      );
    }
    //>>includeEnd('debug');

    const pixelsToCheck = this._pixelsToCheck;
    const missingImagePixels = this._missingImagePixels;

    // If missingImagePixels is undefined, it indicates that the discard check has been disabled.
    if (!defined(missingImagePixels)) {
      return false;
    }

    if (defined(image.blob) && image.blob.size !== this._missingImageByteLength) {
      return false;
    }

    const pixels = getImagePixels(image);
    const width = image.width;

    for (let i = 0, len = pixelsToCheck.length; i < len; ++i) {
      const pos = pixelsToCheck[i];
      const index = pos.x * 4 + pos.y * width;
      for (let offset = 0; offset < 4; ++offset) {
        const pixel = index + offset;
        if (pixels[pixel] !== missingImagePixels[pixel]) {
          return false;
        }
      }
    }
    return true;
  };

  /**
   * Describes a rasterized feature, such as a point, polygon, polyline, etc., in an imagery layer.
   *
   * @alias ImageryLayerFeatureInfo
   * @constructor
   */
  function ImageryLayerFeatureInfo() {
    /**
     * Gets or sets the name of the feature.
     * @type {String|undefined}
     */
    this.name = undefined;

    /**
     * Gets or sets an HTML description of the feature.  The HTML is not trusted and should
     * be sanitized before display to the user.
     * @type {String|undefined}
     */
    this.description = undefined;

    /**
     * Gets or sets the position of the feature, or undefined if the position is not known.
     *
     * @type {Cartographic|undefined}
     */
    this.position = undefined;

    /**
     * Gets or sets the raw data describing the feature.  The raw data may be in any
     * number of formats, such as GeoJSON, KML, etc.
     * @type {Object|undefined}
     */
    this.data = undefined;

    /**
     * Gets or sets the image layer of the feature.
     * @type {Object|undefined}
     */
    this.imageryLayer = undefined;
  }

  /**
   * Configures the name of this feature by selecting an appropriate property.  The name will be obtained from
   * one of the following sources, in this order: 1) the property with the name 'name', 2) the property with the name 'title',
   * 3) the first property containing the word 'name', 4) the first property containing the word 'title'.  If
   * the name cannot be obtained from any of these sources, the existing name will be left unchanged.
   *
   * @param {Object} properties An object literal containing the properties of the feature.
   */
  ImageryLayerFeatureInfo.prototype.configureNameFromProperties = function (
    properties
  ) {
    let namePropertyPrecedence = 10;
    let nameProperty;

    for (const key in properties) {
      if (properties.hasOwnProperty(key) && properties[key]) {
        const lowerKey = key.toLowerCase();

        if (namePropertyPrecedence > 1 && lowerKey === "name") {
          namePropertyPrecedence = 1;
          nameProperty = key;
        } else if (namePropertyPrecedence > 2 && lowerKey === "title") {
          namePropertyPrecedence = 2;
          nameProperty = key;
        } else if (namePropertyPrecedence > 3 && /name/i.test(key)) {
          namePropertyPrecedence = 3;
          nameProperty = key;
        } else if (namePropertyPrecedence > 4 && /title/i.test(key)) {
          namePropertyPrecedence = 4;
          nameProperty = key;
        }
      }
    }

    if (defined(nameProperty)) {
      this.name = properties[nameProperty];
    }
  };

  /**
   * Configures the description of this feature by creating an HTML table of properties and their values.
   *
   * @param {Object} properties An object literal containing the properties of the feature.
   */
  ImageryLayerFeatureInfo.prototype.configureDescriptionFromProperties = function (
    properties
  ) {
    function describe(properties) {
      let html = '<table class="cesium-infoBox-defaultTable">';
      for (const key in properties) {
        if (properties.hasOwnProperty(key)) {
          const value = properties[key];
          if (defined(value)) {
            if (typeof value === "object") {
              html += `<tr><td>${key}</td><td>${describe(value)}</td></tr>`;
            } else {
              html += `<tr><td>${key}</td><td>${value}</td></tr>`;
            }
          }
        }
      }
      html += "</table>";

      return html;
    }

    this.description = describe(properties);
  };

  /**
   * @typedef {HTMLImageElement|HTMLCanvasElement|ImageBitmap} ImageryTypes
   *
   * The format in which {@link ImageryProvider} methods return an image may
   * vary by provider, configuration, or server settings.  Most common are
   * <code>HTMLImageElement</code>, <code>HTMLCanvasElement</code>, or on supported
   * browsers, <code>ImageBitmap</code>.
   *
   * See the documentation for each ImageryProvider class for more information about how they return images.
   */

  /**
   * Provides imagery to be displayed on the surface of an ellipsoid.  This type describes an
   * interface and is not intended to be instantiated directly.
   *
   * @alias ImageryProvider
   * @constructor
   * @abstract
   *
   * @see ArcGisMapServerImageryProvider
   * @see BingMapsImageryProvider
   * @see OpenStreetMapImageryProvider
   * @see TileMapServiceImageryProvider
   * @see GoogleEarthEnterpriseImageryProvider
   * @see GoogleEarthEnterpriseMapsProvider
   * @see GridImageryProvider
   * @see IonImageryProvider
   * @see MapboxImageryProvider
   * @see MapboxStyleImageryProvider
   * @see SingleTileImageryProvider
   * @see TileCoordinatesImageryProvider
   * @see UrlTemplateImageryProvider
   * @see WebMapServiceImageryProvider
   * @see WebMapTileServiceImageryProvider
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Imagery%20Layers.html|Cesium Sandcastle Imagery Layers Demo}
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Imagery%20Layers%20Manipulation.html|Cesium Sandcastle Imagery Manipulation Demo}
   */
  function ImageryProvider() {
    /**
     * The default alpha blending value of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultAlpha = undefined;

    /**
     * The default alpha blending value on the night side of the globe of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultNightAlpha = undefined;

    /**
     * The default alpha blending value on the day side of the globe of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultDayAlpha = undefined;

    /**
     * The default brightness of this provider.  1.0 uses the unmodified imagery color.  Less than 1.0
     * makes the imagery darker while greater than 1.0 makes it brighter.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultBrightness = undefined;

    /**
     * The default contrast of this provider.  1.0 uses the unmodified imagery color.  Less than 1.0 reduces
     * the contrast while greater than 1.0 increases it.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultContrast = undefined;

    /**
     * The default hue of this provider in radians. 0.0 uses the unmodified imagery color.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultHue = undefined;

    /**
     * The default saturation of this provider. 1.0 uses the unmodified imagery color. Less than 1.0 reduces the
     * saturation while greater than 1.0 increases it.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultSaturation = undefined;

    /**
     * The default gamma correction to apply to this provider.  1.0 uses the unmodified imagery color.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultGamma = undefined;

    /**
     * The default texture minification filter to apply to this provider.
     *
     * @type {TextureMinificationFilter}
     * @default undefined
     */
    this.defaultMinificationFilter = undefined;

    /**
     * The default texture magnification filter to apply to this provider.
     *
     * @type {TextureMagnificationFilter}
     * @default undefined
     */
    this.defaultMagnificationFilter = undefined;

    DeveloperError.throwInstantiationError();
  }

  Object.defineProperties(ImageryProvider.prototype, {
    /**
     * Gets a value indicating whether or not the provider is ready for use.
     * @memberof ImageryProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    ready: {
      get: DeveloperError.throwInstantiationError,
    },

    /**
     * Gets a promise that resolves to true when the provider is ready for use.
     * @memberof ImageryProvider.prototype
     * @type {Promise.<Boolean>}
     * @readonly
     */
    readyPromise: {
      get: DeveloperError.throwInstantiationError,
    },

    /**
     * Gets the rectangle, in radians, of the imagery provided by the instance.  This function should
     * not be called before {@link ImageryProvider#ready} returns true.
     * @memberof ImageryProvider.prototype
     * @type {Rectangle}
     * @readonly
     */
    rectangle: {
      get: DeveloperError.throwInstantiationError,
    },

    /**
     * Gets the width of each tile, in pixels.  This function should
     * not be called before {@link ImageryProvider#ready} returns true.
     * @memberof ImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    tileWidth: {
      get: DeveloperError.throwInstantiationError,
    },

    /**
     * Gets the height of each tile, in pixels.  This function should
     * not be called before {@link ImageryProvider#ready} returns true.
     * @memberof ImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    tileHeight: {
      get: DeveloperError.throwInstantiationError,
    },

    /**
     * Gets the maximum level-of-detail that can be requested.  This function should
     * not be called before {@link ImageryProvider#ready} returns true.
     * @memberof ImageryProvider.prototype
     * @type {Number|undefined}
     * @readonly
     */
    maximumLevel: {
      get: DeveloperError.throwInstantiationError,
    },

    /**
     * Gets the minimum level-of-detail that can be requested.  This function should
     * not be called before {@link ImageryProvider#ready} returns true. Generally,
     * a minimum level should only be used when the rectangle of the imagery is small
     * enough that the number of tiles at the minimum level is small.  An imagery
     * provider with more than a few tiles at the minimum level will lead to
     * rendering problems.
     * @memberof ImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    minimumLevel: {
      get: DeveloperError.throwInstantiationError,
    },

    /**
     * Gets the tiling scheme used by the provider.  This function should
     * not be called before {@link ImageryProvider#ready} returns true.
     * @memberof ImageryProvider.prototype
     * @type {TilingScheme}
     * @readonly
     */
    tilingScheme: {
      get: DeveloperError.throwInstantiationError,
    },

    /**
     * Gets the tile discard policy.  If not undefined, the discard policy is responsible
     * for filtering out "missing" tiles via its shouldDiscardImage function.  If this function
     * returns undefined, no tiles are filtered.  This function should
     * not be called before {@link ImageryProvider#ready} returns true.
     * @memberof ImageryProvider.prototype
     * @type {TileDiscardPolicy}
     * @readonly
     */
    tileDiscardPolicy: {
      get: DeveloperError.throwInstantiationError,
    },

    /**
     * Gets an event that is raised when the imagery provider encounters an asynchronous error..  By subscribing
     * to the event, you will be notified of the error and can potentially recover from it.  Event listeners
     * are passed an instance of {@link TileProviderError}.
     * @memberof ImageryProvider.prototype
     * @type {Event}
     * @readonly
     */
    errorEvent: {
      get: DeveloperError.throwInstantiationError,
    },

    /**
     * Gets the credit to display when this imagery provider is active.  Typically this is used to credit
     * the source of the imagery. This function should
     * not be called before {@link ImageryProvider#ready} returns true.
     * @memberof ImageryProvider.prototype
     * @type {Credit}
     * @readonly
     */
    credit: {
      get: DeveloperError.throwInstantiationError,
    },

    /**
     * Gets the proxy used by this provider.
     * @memberof ImageryProvider.prototype
     * @type {Proxy}
     * @readonly
     */
    proxy: {
      get: DeveloperError.throwInstantiationError,
    },

    /**
     * Gets a value indicating whether or not the images provided by this imagery provider
     * include an alpha channel.  If this property is false, an alpha channel, if present, will
     * be ignored.  If this property is true, any images without an alpha channel will be treated
     * as if their alpha is 1.0 everywhere.  When this property is false, memory usage
     * and texture upload time are reduced.
     * @memberof ImageryProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    hasAlphaChannel: {
      get: DeveloperError.throwInstantiationError,
    },
  });

  /**
   * Gets the credits to be displayed when a given tile is displayed.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level;
   * @returns {Credit[]} The credits to be displayed when the tile is displayed.
   *
   * @exception {DeveloperError} <code>getTileCredits</code> must not be called before the imagery provider is ready.
   */
  ImageryProvider.prototype.getTileCredits = function (x, y, level) {
    DeveloperError.throwInstantiationError();
  };

  /**
   * Requests the image for a given tile.  This function should
   * not be called before {@link ImageryProvider#ready} returns true.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level.
   * @param {Request} [request] The request object. Intended for internal use only.
   * @returns {Promise.<ImageryTypes>|undefined} Returns a promise for the image that will resolve when the image is available, or
   *          undefined if there are too many active requests to the server, and the request should be retried later.
   *
   * @exception {DeveloperError} <code>requestImage</code> must not be called before the imagery provider is ready.
   */
  ImageryProvider.prototype.requestImage = function (x, y, level, request) {
    DeveloperError.throwInstantiationError();
  };

  /**
   * Asynchronously determines what features, if any, are located at a given longitude and latitude within
   * a tile.  This function should not be called before {@link ImageryProvider#ready} returns true.
   * This function is optional, so it may not exist on all ImageryProviders.
   *
   * @function
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level.
   * @param {Number} longitude The longitude at which to pick features.
   * @param {Number} latitude  The latitude at which to pick features.
   * @return {Promise.<ImageryLayerFeatureInfo[]>|undefined} A promise for the picked features that will resolve when the asynchronous
   *                   picking completes.  The resolved value is an array of {@link ImageryLayerFeatureInfo}
   *                   instances.  The array may be empty if no features are found at the given location.
   *                   It may also be undefined if picking is not supported.
   *
   * @exception {DeveloperError} <code>pickFeatures</code> must not be called before the imagery provider is ready.
   */
  ImageryProvider.prototype.pickFeatures = function (
    x,
    y,
    level,
    longitude,
    latitude
  ) {
    DeveloperError.throwInstantiationError();
  };

  const ktx2Regex = /\.ktx2$/i;

  /**
   * Loads an image from a given URL.  If the server referenced by the URL already has
   * too many requests pending, this function will instead return undefined, indicating
   * that the request should be retried later.
   *
   * @param {ImageryProvider} imageryProvider The imagery provider for the URL.
   * @param {Resource|String} url The URL of the image.
   * @returns {Promise.<ImageryTypes|CompressedTextureBuffer>|undefined} A promise for the image that will resolve when the image is available, or
   *          undefined if there are too many active requests to the server, and the request should be retried later.
   */
  ImageryProvider.loadImage = function (imageryProvider, url) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("url", url);
    //>>includeEnd('debug');

    const resource = Resource.createIfNeeded(url);

    if (ktx2Regex.test(resource.url)) {
      // Resolves with `CompressedTextureBuffer`
      return loadKTX2(resource);
    } else if (
      defined(imageryProvider) &&
      defined(imageryProvider.tileDiscardPolicy)
    ) {
      // Resolves with `HTMLImageElement` or `ImageBitmap`
      return resource.fetchImage({
        preferBlob: true,
        preferImageBitmap: true,
        flipY: true,
      });
    }

    return resource.fetchImage({
      preferImageBitmap: true,
      flipY: true,
    });
  };

  /**
   * @typedef {Object} ArcGisMapServerImageryProvider.ConstructorOptions
   *
   * Initialization options for the ArcGisMapServerImageryProvider constructor
   *
   * @property {Resource|String} url The URL of the ArcGIS MapServer service.
   * @property {String} [token] The ArcGIS token used to authenticate with the ArcGIS MapServer service.
   * @property {TileDiscardPolicy} [tileDiscardPolicy] The policy that determines if a tile
   *        is invalid and should be discarded.  If this value is not specified, a default
   *        {@link DiscardMissingTileImagePolicy} is used for tiled map servers, and a
   *        {@link NeverTileDiscardPolicy} is used for non-tiled map servers.  In the former case,
   *        we request tile 0,0 at the maximum tile level and check pixels (0,0), (200,20), (20,200),
   *        (80,110), and (160, 130).  If all of these pixels are transparent, the discard check is
   *        disabled and no tiles are discarded.  If any of them have a non-transparent color, any
   *        tile that has the same values in these pixel locations is discarded.  The end result of
   *        these defaults should be correct tile discarding for a standard ArcGIS Server.  To ensure
   *        that no tiles are discarded, construct and pass a {@link NeverTileDiscardPolicy} for this
   *        parameter.
   * @property {Boolean} [usePreCachedTilesIfAvailable=true] If true, the server's pre-cached
   *        tiles are used if they are available.  If false, any pre-cached tiles are ignored and the
   *        'export' service is used.
   * @property {String} [layers] A comma-separated list of the layers to show, or undefined if all layers should be shown.
   * @property {Boolean} [enablePickFeatures=true] If true, {@link ArcGisMapServerImageryProvider#pickFeatures} will invoke
   *        the Identify service on the MapServer and return the features included in the response.  If false,
   *        {@link ArcGisMapServerImageryProvider#pickFeatures} will immediately return undefined (indicating no pickable features)
   *        without communicating with the server.  Set this property to false if you don't want this provider's features to
   *        be pickable. Can be overridden by setting the {@link ArcGisMapServerImageryProvider#enablePickFeatures} property on the object.
   * @property {Rectangle} [rectangle=Rectangle.MAX_VALUE] The rectangle of the layer.  This parameter is ignored when accessing
   *                    a tiled layer.
   * @property {TilingScheme} [tilingScheme=new GeographicTilingScheme()] The tiling scheme to use to divide the world into tiles.
   *                       This parameter is ignored when accessing a tiled server.
   * @property {Ellipsoid} [ellipsoid] The ellipsoid.  If the tilingScheme is specified and used,
   *                    this parameter is ignored and the tiling scheme's ellipsoid is used instead. If neither
   *                    parameter is specified, the WGS84 ellipsoid is used.
   * @property {Credit|String} [credit] A credit for the data source, which is displayed on the canvas.  This parameter is ignored when accessing a tiled server.
   * @property {Number} [tileWidth=256] The width of each tile in pixels.  This parameter is ignored when accessing a tiled server.
   * @property {Number} [tileHeight=256] The height of each tile in pixels.  This parameter is ignored when accessing a tiled server.
   * @property {Number} [maximumLevel] The maximum tile level to request, or undefined if there is no maximum.  This parameter is ignored when accessing
   *                                        a tiled server.
   */

  /**
   * Provides tiled imagery hosted by an ArcGIS MapServer.  By default, the server's pre-cached tiles are
   * used, if available.
   *
   * @alias ArcGisMapServerImageryProvider
   * @constructor
   *
   * @param {ArcGisMapServerImageryProvider.ConstructorOptions} options Object describing initialization options
   *
   * @see BingMapsImageryProvider
   * @see GoogleEarthEnterpriseMapsProvider
   * @see OpenStreetMapImageryProvider
   * @see SingleTileImageryProvider
   * @see TileMapServiceImageryProvider
   * @see WebMapServiceImageryProvider
   * @see WebMapTileServiceImageryProvider
   * @see UrlTemplateImageryProvider
   *
   *
   * @example
   * const esri = new Cesium.ArcGisMapServerImageryProvider({
   *     url : 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer'
   * });
   *
   * @see {@link https://developers.arcgis.com/rest/|ArcGIS Server REST API}
   * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
   */
  function ArcGisMapServerImageryProvider(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    if (!defined(options.url)) {
      throw new DeveloperError("options.url is required.");
    }
    //>>includeEnd('debug');

    /**
     * The default alpha blending value of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultAlpha = undefined;

    /**
     * The default alpha blending value on the night side of the globe of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultNightAlpha = undefined;

    /**
     * The default alpha blending value on the day side of the globe of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultDayAlpha = undefined;

    /**
     * The default brightness of this provider.  1.0 uses the unmodified imagery color.  Less than 1.0
     * makes the imagery darker while greater than 1.0 makes it brighter.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultBrightness = undefined;

    /**
     * The default contrast of this provider.  1.0 uses the unmodified imagery color.  Less than 1.0 reduces
     * the contrast while greater than 1.0 increases it.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultContrast = undefined;

    /**
     * The default hue of this provider in radians. 0.0 uses the unmodified imagery color.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultHue = undefined;

    /**
     * The default saturation of this provider. 1.0 uses the unmodified imagery color. Less than 1.0 reduces the
     * saturation while greater than 1.0 increases it.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultSaturation = undefined;

    /**
     * The default gamma correction to apply to this provider.  1.0 uses the unmodified imagery color.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultGamma = undefined;

    /**
     * The default texture minification filter to apply to this provider.
     *
     * @type {TextureMinificationFilter}
     * @default undefined
     */
    this.defaultMinificationFilter = undefined;

    /**
     * The default texture magnification filter to apply to this provider.
     *
     * @type {TextureMagnificationFilter}
     * @default undefined
     */
    this.defaultMagnificationFilter = undefined;

    const resource = Resource.createIfNeeded(options.url);
    resource.appendForwardSlash();

    if (defined(options.token)) {
      resource.setQueryParameters({
        token: options.token,
      });
    }

    this._resource = resource;
    this._tileDiscardPolicy = options.tileDiscardPolicy;

    this._tileWidth = defaultValue(options.tileWidth, 256);
    this._tileHeight = defaultValue(options.tileHeight, 256);
    this._maximumLevel = options.maximumLevel;
    this._tilingScheme = defaultValue(
      options.tilingScheme,
      new GeographicTilingScheme({ ellipsoid: options.ellipsoid })
    );
    this._useTiles = defaultValue(options.usePreCachedTilesIfAvailable, true);
    this._rectangle = defaultValue(
      options.rectangle,
      this._tilingScheme.rectangle
    );
    this._layers = options.layers;

    let credit = options.credit;
    if (typeof credit === "string") {
      credit = new Credit(credit);
    }
    this._credit = credit;

    /**
     * Gets or sets a value indicating whether feature picking is enabled.  If true, {@link ArcGisMapServerImageryProvider#pickFeatures} will
     * invoke the "identify" operation on the ArcGIS server and return the features included in the response.  If false,
     * {@link ArcGisMapServerImageryProvider#pickFeatures} will immediately return undefined (indicating no pickable features)
     * without communicating with the server.
     * @type {Boolean}
     * @default true
     */
    this.enablePickFeatures = defaultValue(options.enablePickFeatures, true);

    this._errorEvent = new Event();

    this._ready = false;
    this._readyPromise = defer();

    // Grab the details of this MapServer.
    const that = this;
    let metadataError;

    function metadataSuccess(data) {
      const tileInfo = data.tileInfo;
      if (!defined(tileInfo)) {
        that._useTiles = false;
      } else {
        that._tileWidth = tileInfo.rows;
        that._tileHeight = tileInfo.cols;

        if (
          tileInfo.spatialReference.wkid === 102100 ||
          tileInfo.spatialReference.wkid === 102113
        ) {
          that._tilingScheme = new WebMercatorTilingScheme({
            ellipsoid: options.ellipsoid,
          });
        } else if (data.tileInfo.spatialReference.wkid === 4326) {
          that._tilingScheme = new GeographicTilingScheme({
            ellipsoid: options.ellipsoid,
          });
        } else {
          const message = `Tile spatial reference WKID ${data.tileInfo.spatialReference.wkid} is not supported.`;
          metadataError = TileProviderError.handleError(
            metadataError,
            that,
            that._errorEvent,
            message,
            undefined,
            undefined,
            undefined,
            requestMetadata
          );
          if (!metadataError.retry) {
            that._readyPromise.reject(new RuntimeError(message));
          }
          return;
        }
        that._maximumLevel = data.tileInfo.lods.length - 1;

        if (defined(data.fullExtent)) {
          if (
            defined(data.fullExtent.spatialReference) &&
            defined(data.fullExtent.spatialReference.wkid)
          ) {
            if (
              data.fullExtent.spatialReference.wkid === 102100 ||
              data.fullExtent.spatialReference.wkid === 102113
            ) {
              const projection = new WebMercatorProjection();
              const extent = data.fullExtent;
              const sw = projection.unproject(
                new Cartesian3(
                  Math.max(
                    extent.xmin,
                    -that._tilingScheme.ellipsoid.maximumRadius * Math.PI
                  ),
                  Math.max(
                    extent.ymin,
                    -that._tilingScheme.ellipsoid.maximumRadius * Math.PI
                  ),
                  0.0
                )
              );
              const ne = projection.unproject(
                new Cartesian3(
                  Math.min(
                    extent.xmax,
                    that._tilingScheme.ellipsoid.maximumRadius * Math.PI
                  ),
                  Math.min(
                    extent.ymax,
                    that._tilingScheme.ellipsoid.maximumRadius * Math.PI
                  ),
                  0.0
                )
              );
              that._rectangle = new Rectangle(
                sw.longitude,
                sw.latitude,
                ne.longitude,
                ne.latitude
              );
            } else if (data.fullExtent.spatialReference.wkid === 4326) {
              that._rectangle = Rectangle.fromDegrees(
                data.fullExtent.xmin,
                data.fullExtent.ymin,
                data.fullExtent.xmax,
                data.fullExtent.ymax
              );
            } else {
              const extentMessage = `fullExtent.spatialReference WKID ${data.fullExtent.spatialReference.wkid} is not supported.`;
              metadataError = TileProviderError.handleError(
                metadataError,
                that,
                that._errorEvent,
                extentMessage,
                undefined,
                undefined,
                undefined,
                requestMetadata
              );
              if (!metadataError.retry) {
                that._readyPromise.reject(new RuntimeError(extentMessage));
              }
              return;
            }
          }
        } else {
          that._rectangle = that._tilingScheme.rectangle;
        }

        // Install the default tile discard policy if none has been supplied.
        if (!defined(that._tileDiscardPolicy)) {
          that._tileDiscardPolicy = new DiscardMissingTileImagePolicy({
            missingImageUrl: buildImageResource$3(that, 0, 0, that._maximumLevel)
              .url,
            pixelsToCheck: [
              new Cartesian2(0, 0),
              new Cartesian2(200, 20),
              new Cartesian2(20, 200),
              new Cartesian2(80, 110),
              new Cartesian2(160, 130),
            ],
            disableCheckIfAllPixelsAreTransparent: true,
          });
        }

        that._useTiles = true;
      }

      if (defined(data.copyrightText) && data.copyrightText.length > 0) {
        that._credit = new Credit(data.copyrightText);
      }

      that._ready = true;
      that._readyPromise.resolve(true);
      TileProviderError.handleSuccess(metadataError);
    }

    function metadataFailure(e) {
      const message = `An error occurred while accessing ${that._resource.url}.`;
      metadataError = TileProviderError.handleError(
        metadataError,
        that,
        that._errorEvent,
        message,
        undefined,
        undefined,
        undefined,
        requestMetadata
      );
      that._readyPromise.reject(new RuntimeError(message));
    }

    function requestMetadata() {
      const resource = that._resource.getDerivedResource({
        queryParameters: {
          f: "json",
        },
      });
      resource
        .fetchJsonp()
        .then(function (result) {
          metadataSuccess(result);
        })
        .catch(function (e) {
          metadataFailure();
        });
    }

    if (this._useTiles) {
      requestMetadata();
    } else {
      this._ready = true;
      this._readyPromise.resolve(true);
    }
  }

  function buildImageResource$3(imageryProvider, x, y, level, request) {
    let resource;
    if (imageryProvider._useTiles) {
      resource = imageryProvider._resource.getDerivedResource({
        url: `tile/${level}/${y}/${x}`,
        request: request,
      });
    } else {
      const nativeRectangle = imageryProvider._tilingScheme.tileXYToNativeRectangle(
        x,
        y,
        level
      );
      const bbox = `${nativeRectangle.west},${nativeRectangle.south},${nativeRectangle.east},${nativeRectangle.north}`;

      const query = {
        bbox: bbox,
        size: `${imageryProvider._tileWidth},${imageryProvider._tileHeight}`,
        format: "png32",
        transparent: true,
        f: "image",
      };

      if (
        imageryProvider._tilingScheme.projection instanceof GeographicProjection
      ) {
        query.bboxSR = 4326;
        query.imageSR = 4326;
      } else {
        query.bboxSR = 3857;
        query.imageSR = 3857;
      }
      if (imageryProvider.layers) {
        query.layers = `show:${imageryProvider.layers}`;
      }

      resource = imageryProvider._resource.getDerivedResource({
        url: "export",
        request: request,
        queryParameters: query,
      });
    }

    return resource;
  }

  Object.defineProperties(ArcGisMapServerImageryProvider.prototype, {
    /**
     * Gets the URL of the ArcGIS MapServer.
     * @memberof ArcGisMapServerImageryProvider.prototype
     * @type {String}
     * @readonly
     */
    url: {
      get: function () {
        return this._resource._url;
      },
    },

    /**
     * Gets the ArcGIS token used to authenticate with the ArcGis MapServer service.
     * @memberof ArcGisMapServerImageryProvider.prototype
     * @type {String}
     * @readonly
     */
    token: {
      get: function () {
        return this._resource.queryParameters.token;
      },
    },

    /**
     * Gets the proxy used by this provider.
     * @memberof ArcGisMapServerImageryProvider.prototype
     * @type {Proxy}
     * @readonly
     */
    proxy: {
      get: function () {
        return this._resource.proxy;
      },
    },

    /**
     * Gets the width of each tile, in pixels. This function should
     * not be called before {@link ArcGisMapServerImageryProvider#ready} returns true.
     * @memberof ArcGisMapServerImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    tileWidth: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "tileWidth must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._tileWidth;
      },
    },

    /**
     * Gets the height of each tile, in pixels.  This function should
     * not be called before {@link ArcGisMapServerImageryProvider#ready} returns true.
     * @memberof ArcGisMapServerImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    tileHeight: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "tileHeight must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._tileHeight;
      },
    },

    /**
     * Gets the maximum level-of-detail that can be requested.  This function should
     * not be called before {@link ArcGisMapServerImageryProvider#ready} returns true.
     * @memberof ArcGisMapServerImageryProvider.prototype
     * @type {Number|undefined}
     * @readonly
     */
    maximumLevel: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "maximumLevel must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._maximumLevel;
      },
    },

    /**
     * Gets the minimum level-of-detail that can be requested.  This function should
     * not be called before {@link ArcGisMapServerImageryProvider#ready} returns true.
     * @memberof ArcGisMapServerImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    minimumLevel: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "minimumLevel must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return 0;
      },
    },

    /**
     * Gets the tiling scheme used by this provider.  This function should
     * not be called before {@link ArcGisMapServerImageryProvider#ready} returns true.
     * @memberof ArcGisMapServerImageryProvider.prototype
     * @type {TilingScheme}
     * @readonly
     */
    tilingScheme: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "tilingScheme must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._tilingScheme;
      },
    },

    /**
     * Gets the rectangle, in radians, of the imagery provided by this instance.  This function should
     * not be called before {@link ArcGisMapServerImageryProvider#ready} returns true.
     * @memberof ArcGisMapServerImageryProvider.prototype
     * @type {Rectangle}
     * @readonly
     */
    rectangle: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "rectangle must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._rectangle;
      },
    },

    /**
     * Gets the tile discard policy.  If not undefined, the discard policy is responsible
     * for filtering out "missing" tiles via its shouldDiscardImage function.  If this function
     * returns undefined, no tiles are filtered.  This function should
     * not be called before {@link ArcGisMapServerImageryProvider#ready} returns true.
     * @memberof ArcGisMapServerImageryProvider.prototype
     * @type {TileDiscardPolicy}
     * @readonly
     */
    tileDiscardPolicy: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "tileDiscardPolicy must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._tileDiscardPolicy;
      },
    },

    /**
     * Gets an event that is raised when the imagery provider encounters an asynchronous error.  By subscribing
     * to the event, you will be notified of the error and can potentially recover from it.  Event listeners
     * are passed an instance of {@link TileProviderError}.
     * @memberof ArcGisMapServerImageryProvider.prototype
     * @type {Event}
     * @readonly
     */
    errorEvent: {
      get: function () {
        return this._errorEvent;
      },
    },

    /**
     * Gets a value indicating whether or not the provider is ready for use.
     * @memberof ArcGisMapServerImageryProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    ready: {
      get: function () {
        return this._ready;
      },
    },

    /**
     * Gets a promise that resolves to true when the provider is ready for use.
     * @memberof ArcGisMapServerImageryProvider.prototype
     * @type {Promise.<Boolean>}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._readyPromise.promise;
      },
    },

    /**
     * Gets the credit to display when this imagery provider is active.  Typically this is used to credit
     * the source of the imagery.  This function should not be called before {@link ArcGisMapServerImageryProvider#ready} returns true.
     * @memberof ArcGisMapServerImageryProvider.prototype
     * @type {Credit}
     * @readonly
     */
    credit: {
      get: function () {
        return this._credit;
      },
    },

    /**
     * Gets a value indicating whether this imagery provider is using pre-cached tiles from the
     * ArcGIS MapServer.  If the imagery provider is not yet ready ({@link ArcGisMapServerImageryProvider#ready}), this function
     * will return the value of `options.usePreCachedTilesIfAvailable`, even if the MapServer does
     * not have pre-cached tiles.
     * @memberof ArcGisMapServerImageryProvider.prototype
     *
     * @type {Boolean}
     * @readonly
     * @default true
     */
    usingPrecachedTiles: {
      get: function () {
        return this._useTiles;
      },
    },

    /**
     * Gets a value indicating whether or not the images provided by this imagery provider
     * include an alpha channel.  If this property is false, an alpha channel, if present, will
     * be ignored.  If this property is true, any images without an alpha channel will be treated
     * as if their alpha is 1.0 everywhere.  When this property is false, memory usage
     * and texture upload time are reduced.
     * @memberof ArcGisMapServerImageryProvider.prototype
     *
     * @type {Boolean}
     * @readonly
     * @default true
     */
    hasAlphaChannel: {
      get: function () {
        return true;
      },
    },

    /**
     * Gets the comma-separated list of layer IDs to show.
     * @memberof ArcGisMapServerImageryProvider.prototype
     *
     * @type {String}
     */
    layers: {
      get: function () {
        return this._layers;
      },
    },
  });

  /**
   * Gets the credits to be displayed when a given tile is displayed.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level;
   * @returns {Credit[]} The credits to be displayed when the tile is displayed.
   *
   * @exception {DeveloperError} <code>getTileCredits</code> must not be called before the imagery provider is ready.
   */
  ArcGisMapServerImageryProvider.prototype.getTileCredits = function (
    x,
    y,
    level
  ) {
    return undefined;
  };

  /**
   * Requests the image for a given tile.  This function should
   * not be called before {@link ArcGisMapServerImageryProvider#ready} returns true.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level.
   * @param {Request} [request] The request object. Intended for internal use only.
   * @returns {Promise.<ImageryTypes>|undefined} A promise for the image that will resolve when the image is available, or
   *          undefined if there are too many active requests to the server, and the request should be retried later.
   *
   * @exception {DeveloperError} <code>requestImage</code> must not be called before the imagery provider is ready.
   */
  ArcGisMapServerImageryProvider.prototype.requestImage = function (
    x,
    y,
    level,
    request
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!this._ready) {
      throw new DeveloperError(
        "requestImage must not be called before the imagery provider is ready."
      );
    }
    //>>includeEnd('debug');

    return ImageryProvider.loadImage(
      this,
      buildImageResource$3(this, x, y, level, request)
    );
  };

  /**
      /**
       * Asynchronously determines what features, if any, are located at a given longitude and latitude within
       * a tile.  This function should not be called before {@link ImageryProvider#ready} returns true.
       *
       * @param {Number} x The tile X coordinate.
       * @param {Number} y The tile Y coordinate.
       * @param {Number} level The tile level.
       * @param {Number} longitude The longitude at which to pick features.
       * @param {Number} latitude  The latitude at which to pick features.
       * @return {Promise.<ImageryLayerFeatureInfo[]>|undefined} A promise for the picked features that will resolve when the asynchronous
       *                   picking completes.  The resolved value is an array of {@link ImageryLayerFeatureInfo}
       *                   instances.  The array may be empty if no features are found at the given location.
       *
       * @exception {DeveloperError} <code>pickFeatures</code> must not be called before the imagery provider is ready.
       */
  ArcGisMapServerImageryProvider.prototype.pickFeatures = function (
    x,
    y,
    level,
    longitude,
    latitude
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!this._ready) {
      throw new DeveloperError(
        "pickFeatures must not be called before the imagery provider is ready."
      );
    }
    //>>includeEnd('debug');

    if (!this.enablePickFeatures) {
      return undefined;
    }

    const rectangle = this._tilingScheme.tileXYToNativeRectangle(x, y, level);

    let horizontal;
    let vertical;
    let sr;
    if (this._tilingScheme.projection instanceof GeographicProjection) {
      horizontal = CesiumMath.toDegrees(longitude);
      vertical = CesiumMath.toDegrees(latitude);
      sr = "4326";
    } else {
      const projected = this._tilingScheme.projection.project(
        new Cartographic(longitude, latitude, 0.0)
      );
      horizontal = projected.x;
      vertical = projected.y;
      sr = "3857";
    }

    let layers = "visible";
    if (defined(this._layers)) {
      layers += `:${this._layers}`;
    }

    const query = {
      f: "json",
      tolerance: 2,
      geometryType: "esriGeometryPoint",
      geometry: `${horizontal},${vertical}`,
      mapExtent: `${rectangle.west},${rectangle.south},${rectangle.east},${rectangle.north}`,
      imageDisplay: `${this._tileWidth},${this._tileHeight},96`,
      sr: sr,
      layers: layers,
    };

    const resource = this._resource.getDerivedResource({
      url: "identify",
      queryParameters: query,
    });

    return resource.fetchJson().then(function (json) {
      const result = [];

      const features = json.results;
      if (!defined(features)) {
        return result;
      }

      for (let i = 0; i < features.length; ++i) {
        const feature = features[i];

        const featureInfo = new ImageryLayerFeatureInfo();
        featureInfo.data = feature;
        featureInfo.name = feature.value;
        featureInfo.properties = feature.attributes;
        featureInfo.configureDescriptionFromProperties(feature.attributes);

        // If this is a point feature, use the coordinates of the point.
        if (feature.geometryType === "esriGeometryPoint" && feature.geometry) {
          const wkid =
            feature.geometry.spatialReference &&
            feature.geometry.spatialReference.wkid
              ? feature.geometry.spatialReference.wkid
              : 4326;
          if (wkid === 4326 || wkid === 4283) {
            featureInfo.position = Cartographic.fromDegrees(
              feature.geometry.x,
              feature.geometry.y,
              feature.geometry.z
            );
          } else if (wkid === 102100 || wkid === 900913 || wkid === 3857) {
            const projection = new WebMercatorProjection();
            featureInfo.position = projection.unproject(
              new Cartesian3(
                feature.geometry.x,
                feature.geometry.y,
                feature.geometry.z
              )
            );
          }
        }

        result.push(featureInfo);
      }

      return result;
    });
  };

  /**
   * A post process stage that will get the luminance value at each pixel and
   * uses parallel reduction to compute the average luminance in a 1x1 texture.
   * This texture can be used as input for tone mapping.
   *
   * @constructor
   * @private
   */
  function AutoExposure() {
    this._uniformMap = undefined;
    this._command = undefined;

    this._colorTexture = undefined;
    this._depthTexture = undefined;

    this._ready = false;

    this._name = "czm_autoexposure";

    this._logDepthChanged = undefined;
    this._useLogDepth = undefined;

    this._framebuffers = undefined;
    this._previousLuminance = new FramebufferManager();

    this._commands = undefined;
    this._clearCommand = undefined;

    this._minMaxLuminance = new Cartesian2();

    /**
     * Whether or not to execute this post-process stage when ready.
     *
     * @type {Boolean}
     */
    this.enabled = true;
    this._enabled = true;

    /**
     * The minimum value used to clamp the luminance.
     *
     * @type {Number}
     * @default 0.1
     */
    this.minimumLuminance = 0.1;

    /**
     * The maximum value used to clamp the luminance.
     *
     * @type {Number}
     * @default 10.0
     */
    this.maximumLuminance = 10.0;
  }

  Object.defineProperties(AutoExposure.prototype, {
    /**
     * Determines if this post-process stage is ready to be executed. A stage is only executed when both <code>ready</code>
     * and {@link AutoExposure#enabled} are <code>true</code>. A stage will not be ready while it is waiting on textures
     * to load.
     *
     * @memberof AutoExposure.prototype
     * @type {Boolean}
     * @readonly
     */
    ready: {
      get: function () {
        return this._ready;
      },
    },
    /**
     * The unique name of this post-process stage for reference by other stages.
     *
     * @memberof AutoExposure.prototype
     * @type {String}
     * @readonly
     */
    name: {
      get: function () {
        return this._name;
      },
    },

    /**
     * A reference to the texture written to when executing this post process stage.
     *
     * @memberof AutoExposure.prototype
     * @type {Texture}
     * @readonly
     * @private
     */
    outputTexture: {
      get: function () {
        const framebuffers = this._framebuffers;
        if (!defined(framebuffers)) {
          return undefined;
        }
        return framebuffers[framebuffers.length - 1].getColorTexture(0);
      },
    },
  });

  function destroyFramebuffers$3(autoexposure) {
    const framebuffers = autoexposure._framebuffers;
    if (!defined(framebuffers)) {
      return;
    }

    const length = framebuffers.length;
    for (let i = 0; i < length; ++i) {
      framebuffers[i].destroy();
    }
    autoexposure._framebuffers = undefined;

    autoexposure._previousLuminance.destroy();
    autoexposure._previousLuminance = undefined;
  }

  function createFramebuffers$1(autoexposure, context) {
    destroyFramebuffers$3(autoexposure);

    let width = autoexposure._width;
    let height = autoexposure._height;

    const pixelDatatype = context.halfFloatingPointTexture
      ? PixelDatatype$1.HALF_FLOAT
      : PixelDatatype$1.FLOAT;

    const length = Math.ceil(Math.log(Math.max(width, height)) / Math.log(3.0));
    const framebuffers = new Array(length);
    for (let i = 0; i < length; ++i) {
      width = Math.max(Math.ceil(width / 3.0), 1.0);
      height = Math.max(Math.ceil(height / 3.0), 1.0);
      framebuffers[i] = new FramebufferManager();
      framebuffers[i].update(context, width, height, 1, pixelDatatype);
    }

    const lastTexture = framebuffers[length - 1].getColorTexture(0);
    autoexposure._previousLuminance.update(
      context,
      lastTexture.width,
      lastTexture.height,
      1,
      pixelDatatype
    );
    autoexposure._framebuffers = framebuffers;
  }

  function destroyCommands(autoexposure) {
    const commands = autoexposure._commands;
    if (!defined(commands)) {
      return;
    }

    const length = commands.length;
    for (let i = 0; i < length; ++i) {
      commands[i].shaderProgram.destroy();
    }
    autoexposure._commands = undefined;
  }

  function createUniformMap$1(autoexposure, index) {
    let uniforms;
    if (index === 0) {
      uniforms = {
        colorTexture: function () {
          return autoexposure._colorTexture;
        },
        colorTextureDimensions: function () {
          return autoexposure._colorTexture.dimensions;
        },
      };
    } else {
      const texture = autoexposure._framebuffers[index - 1].getColorTexture(0);
      uniforms = {
        colorTexture: function () {
          return texture;
        },
        colorTextureDimensions: function () {
          return texture.dimensions;
        },
      };
    }

    uniforms.minMaxLuminance = function () {
      return autoexposure._minMaxLuminance;
    };
    uniforms.previousLuminance = function () {
      return autoexposure._previousLuminance.getColorTexture(0);
    };

    return uniforms;
  }

  function getShaderSource(index, length) {
    let source =
      "uniform sampler2D colorTexture; \n" +
      "varying vec2 v_textureCoordinates; \n" +
      "float sampleTexture(vec2 offset) { \n";

    if (index === 0) {
      source +=
        "    vec4 color = texture2D(colorTexture, v_textureCoordinates + offset); \n" +
        "    return czm_luminance(color.rgb); \n";
    } else {
      source +=
        "    return texture2D(colorTexture, v_textureCoordinates + offset).r; \n";
    }

    source += "}\n\n";

    source +=
      "uniform vec2 colorTextureDimensions; \n" +
      "uniform vec2 minMaxLuminance; \n" +
      "uniform sampler2D previousLuminance; \n" +
      "void main() { \n" +
      "    float color = 0.0; \n" +
      "    float xStep = 1.0 / colorTextureDimensions.x; \n" +
      "    float yStep = 1.0 / colorTextureDimensions.y; \n" +
      "    int count = 0; \n" +
      "    for (int i = 0; i < 3; ++i) { \n" +
      "        for (int j = 0; j < 3; ++j) { \n" +
      "            vec2 offset; \n" +
      "            offset.x = -xStep + float(i) * xStep; \n" +
      "            offset.y = -yStep + float(j) * yStep; \n" +
      "            if (offset.x < 0.0 || offset.x > 1.0 || offset.y < 0.0 || offset.y > 1.0) { \n" +
      "                continue; \n" +
      "            } \n" +
      "            color += sampleTexture(offset); \n" +
      "            ++count; \n" +
      "        } \n" +
      "    } \n" +
      "    if (count > 0) { \n" +
      "        color /= float(count); \n" +
      "    } \n";

    if (index === length - 1) {
      source +=
        "    float previous = texture2D(previousLuminance, vec2(0.5)).r; \n" +
        "    color = clamp(color, minMaxLuminance.x, minMaxLuminance.y); \n" +
        "    color = previous + (color - previous) / (60.0 * 1.5); \n" +
        "    color = clamp(color, minMaxLuminance.x, minMaxLuminance.y); \n";
    }

    source += "    gl_FragColor = vec4(color); \n" + "} \n";
    return source;
  }

  function createCommands(autoexposure, context) {
    destroyCommands(autoexposure);
    const framebuffers = autoexposure._framebuffers;
    const length = framebuffers.length;

    const commands = new Array(length);

    for (let i = 0; i < length; ++i) {
      commands[i] = context.createViewportQuadCommand(
        getShaderSource(i, length),
        {
          framebuffer: framebuffers[i].framebuffer,
          uniformMap: createUniformMap$1(autoexposure, i),
        }
      );
    }
    autoexposure._commands = commands;
  }

  /**
   * A function that will be called before execute. Used to clear any textures attached to framebuffers.
   * @param {Context} context The context.
   * @private
   */
  AutoExposure.prototype.clear = function (context) {
    const framebuffers = this._framebuffers;
    if (!defined(framebuffers)) {
      return;
    }

    let clearCommand = this._clearCommand;
    if (!defined(clearCommand)) {
      clearCommand = this._clearCommand = new ClearCommand({
        color: new Color(0.0, 0.0, 0.0, 0.0),
        framebuffer: undefined,
      });
    }

    const length = framebuffers.length;
    for (let i = 0; i < length; ++i) {
      framebuffers[i].clear(context, clearCommand);
    }
  };

  /**
   * A function that will be called before execute. Used to create WebGL resources and load any textures.
   * @param {Context} context The context.
   * @private
   */
  AutoExposure.prototype.update = function (context) {
    const width = context.drawingBufferWidth;
    const height = context.drawingBufferHeight;

    if (width !== this._width || height !== this._height) {
      this._width = width;
      this._height = height;

      createFramebuffers$1(this, context);
      createCommands(this, context);

      if (!this._ready) {
        this._ready = true;
      }
    }

    this._minMaxLuminance.x = this.minimumLuminance;
    this._minMaxLuminance.y = this.maximumLuminance;

    const framebuffers = this._framebuffers;
    const temp = framebuffers[framebuffers.length - 1];
    framebuffers[framebuffers.length - 1] = this._previousLuminance;
    this._commands[
      this._commands.length - 1
    ].framebuffer = this._previousLuminance.framebuffer;
    this._previousLuminance = temp;
  };

  /**
   * Executes the post-process stage. The color texture is the texture rendered to by the scene or from the previous stage.
   * @param {Context} context The context.
   * @param {Texture} colorTexture The input color texture.
   * @private
   */
  AutoExposure.prototype.execute = function (context, colorTexture) {
    this._colorTexture = colorTexture;

    const commands = this._commands;
    if (!defined(commands)) {
      return;
    }

    const length = commands.length;
    for (let i = 0; i < length; ++i) {
      commands[i].execute(context);
    }
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <p>
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   * </p>
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see AutoExposure#destroy
   */
  AutoExposure.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <p>
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   * </p>
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @see AutoExposure#isDestroyed
   */
  AutoExposure.prototype.destroy = function () {
    destroyFramebuffers$3(this);
    destroyCommands(this);
    return destroyObject(this);
  };

  /**
   * The types of imagery provided by Bing Maps.
   *
   * @enum {Number}
   *
   * @see BingMapsImageryProvider
   */
  const BingMapsStyle = {
    /**
     * Aerial imagery.
     *
     * @type {String}
     * @constant
     */
    AERIAL: "Aerial",

    /**
     * Aerial imagery with a road overlay.
     *
     * @type {String}
     * @constant
     * @deprecated See https://github.com/CesiumGS/cesium/issues/7128.
     * Use `BingMapsStyle.AERIAL_WITH_LABELS_ON_DEMAND` instead
     */
    AERIAL_WITH_LABELS: "AerialWithLabels",

    /**
     * Aerial imagery with a road overlay.
     *
     * @type {String}
     * @constant
     */
    AERIAL_WITH_LABELS_ON_DEMAND: "AerialWithLabelsOnDemand",

    /**
     * Roads without additional imagery.
     *
     * @type {String}
     * @constant
     * @deprecated See https://github.com/CesiumGS/cesium/issues/7128.
     * Use `BingMapsStyle.ROAD_ON_DEMAND` instead
     */
    ROAD: "Road",

    /**
     * Roads without additional imagery.
     *
     * @type {String}
     * @constant
     */
    ROAD_ON_DEMAND: "RoadOnDemand",

    /**
     * A dark version of the road maps.
     *
     * @type {String}
     * @constant
     */
    CANVAS_DARK: "CanvasDark",

    /**
     * A lighter version of the road maps.
     *
     * @type {String}
     * @constant
     */
    CANVAS_LIGHT: "CanvasLight",

    /**
     * A grayscale version of the road maps.
     *
     * @type {String}
     * @constant
     */
    CANVAS_GRAY: "CanvasGray",

    /**
     * Ordnance Survey imagery. This imagery is visible only for the London, UK area.
     *
     * @type {String}
     * @constant
     */
    ORDNANCE_SURVEY: "OrdnanceSurvey",

    /**
     * Collins Bart imagery.
     *
     * @type {String}
     * @constant
     */
    COLLINS_BART: "CollinsBart",
  };
  var BingMapsStyle$1 = Object.freeze(BingMapsStyle);

  /**
   * A policy for discarding tile images that contain no data (and so aren't actually images).
   * This policy discards {@link DiscardEmptyTileImagePolicy.EMPTY_IMAGE}, which is
   * expected to be used in place of any empty tile images by the image loading code.
   *
   * @alias DiscardEmptyTileImagePolicy
   * @constructor
   *
   * @see DiscardMissingTileImagePolicy
   */
  function DiscardEmptyTileImagePolicy(options) {}

  /**
   * Determines if the discard policy is ready to process images.
   * @returns {Boolean} True if the discard policy is ready to process images; otherwise, false.
   */
  DiscardEmptyTileImagePolicy.prototype.isReady = function () {
    return true;
  };

  /**
   * Given a tile image, decide whether to discard that image.
   *
   * @param {HTMLImageElement} image An image to test.
   * @returns {Boolean} True if the image should be discarded; otherwise, false.
   */
  DiscardEmptyTileImagePolicy.prototype.shouldDiscardImage = function (image) {
    return DiscardEmptyTileImagePolicy.EMPTY_IMAGE === image;
  };

  let emptyImage;

  Object.defineProperties(DiscardEmptyTileImagePolicy, {
    /**
     * Default value for representing an empty image.
     * @type {HTMLImageElement}
     * @readonly
     * @memberof DiscardEmptyTileImagePolicy
     */
    EMPTY_IMAGE: {
      get: function () {
        if (!defined(emptyImage)) {
          emptyImage = new Image();
          // load a blank data URI with a 1x1 transparent pixel.
          emptyImage.src =
            "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
        }
        return emptyImage;
      },
    },
  });

  /**
   * @typedef {Object} BingMapsImageryProvider.ConstructorOptions
   *
   * Initialization options for the BingMapsImageryProvider constructor
   *
   * @property {Resource|String} url The url of the Bing Maps server hosting the imagery.
   * @property {String} key The Bing Maps key for your application, which can be
   *        created at {@link https://www.bingmapsportal.com/}.
   * @property {String} [tileProtocol] The protocol to use when loading tiles, e.g. 'http' or 'https'.
   *        By default, tiles are loaded using the same protocol as the page.
   * @property {BingMapsStyle} [mapStyle=BingMapsStyle.AERIAL] The type of Bing Maps imagery to load.
   * @property {String} [culture=''] The culture to use when requesting Bing Maps imagery. Not
   *        all cultures are supported. See {@link http://msdn.microsoft.com/en-us/library/hh441729.aspx}
   *        for information on the supported cultures.
   * @property {Ellipsoid} [ellipsoid] The ellipsoid.  If not specified, the WGS84 ellipsoid is used.
   * @property {TileDiscardPolicy} [tileDiscardPolicy] The policy that determines if a tile
   *        is invalid and should be discarded.  By default, a {@link DiscardEmptyTileImagePolicy}
   *        will be used, with the expectation that the Bing Maps server will send a zero-length response for missing tiles.
   *        To ensure that no tiles are discarded, construct and pass a {@link NeverTileDiscardPolicy} for this parameter.
   */

  /**
   * Provides tiled imagery using the Bing Maps Imagery REST API.
   *
   * @alias BingMapsImageryProvider
   * @constructor
   *
   * @param {BingMapsImageryProvider.ConstructorOptions} options Object describing initialization options
   *
   * @see ArcGisMapServerImageryProvider
   * @see GoogleEarthEnterpriseMapsProvider
   * @see OpenStreetMapImageryProvider
   * @see SingleTileImageryProvider
   * @see TileMapServiceImageryProvider
   * @see WebMapServiceImageryProvider
   * @see WebMapTileServiceImageryProvider
   * @see UrlTemplateImageryProvider
   *
   *
   * @example
   * const bing = new Cesium.BingMapsImageryProvider({
   *     url : 'https://dev.virtualearth.net',
   *     key : 'get-yours-at-https://www.bingmapsportal.com/',
   *     mapStyle : Cesium.BingMapsStyle.AERIAL
   * });
   *
   * @see {@link http://msdn.microsoft.com/en-us/library/ff701713.aspx|Bing Maps REST Services}
   * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
   */
  function BingMapsImageryProvider(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const accessKey = options.key;

    //>>includeStart('debug', pragmas.debug);
    if (!defined(options.url)) {
      throw new DeveloperError("options.url is required.");
    }
    if (!defined(accessKey)) {
      throw new DeveloperError("options.key is required.");
    }
    //>>includeEnd('debug');

    /**
     * The default alpha blending value of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultAlpha = undefined;

    /**
     * The default alpha blending value on the night side of the globe of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultNightAlpha = undefined;

    /**
     * The default alpha blending value on the day side of the globe of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultDayAlpha = undefined;

    /**
     * The default brightness of this provider.  1.0 uses the unmodified imagery color.  Less than 1.0
     * makes the imagery darker while greater than 1.0 makes it brighter.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultBrightness = undefined;

    /**
     * The default contrast of this provider.  1.0 uses the unmodified imagery color.  Less than 1.0 reduces
     * the contrast while greater than 1.0 increases it.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultContrast = undefined;

    /**
     * The default hue of this provider in radians. 0.0 uses the unmodified imagery color.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultHue = undefined;

    /**
     * The default saturation of this provider. 1.0 uses the unmodified imagery color. Less than 1.0 reduces the
     * saturation while greater than 1.0 increases it.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultSaturation = undefined;

    /**
     * The default gamma correction to apply to this provider.  1.0 uses the unmodified imagery color.
     *
     * @type {Number|undefined}
     * @default 1.0
     */
    this.defaultGamma = 1.0;

    /**
     * The default texture minification filter to apply to this provider.
     *
     * @type {TextureMinificationFilter}
     * @default undefined
     */
    this.defaultMinificationFilter = undefined;

    /**
     * The default texture magnification filter to apply to this provider.
     *
     * @type {TextureMagnificationFilter}
     * @default undefined
     */
    this.defaultMagnificationFilter = undefined;

    this._key = accessKey;
    this._resource = Resource.createIfNeeded(options.url);
    this._resource.appendForwardSlash();
    this._tileProtocol = options.tileProtocol;
    this._mapStyle = defaultValue(options.mapStyle, BingMapsStyle$1.AERIAL);
    this._culture = defaultValue(options.culture, "");

    this._tileDiscardPolicy = options.tileDiscardPolicy;
    if (!defined(this._tileDiscardPolicy)) {
      this._tileDiscardPolicy = new DiscardEmptyTileImagePolicy();
    }

    this._proxy = options.proxy;
    this._credit = new Credit(
      `<a href="http://www.bing.com"><img src="${BingMapsImageryProvider.logoUrl}" title="Bing Imagery"/></a>`
    );

    this._tilingScheme = new WebMercatorTilingScheme({
      numberOfLevelZeroTilesX: 2,
      numberOfLevelZeroTilesY: 2,
      ellipsoid: options.ellipsoid,
    });

    this._tileWidth = undefined;
    this._tileHeight = undefined;
    this._maximumLevel = undefined;
    this._imageUrlTemplate = undefined;
    this._imageUrlSubdomains = undefined;

    this._errorEvent = new Event();

    this._ready = false;
    this._readyPromise = defer();

    let tileProtocol = this._tileProtocol;

    // For backward compatibility reasons, the tileProtocol may end with
    // a `:`. Remove it.
    if (defined(tileProtocol)) {
      if (
        tileProtocol.length > 0 &&
        tileProtocol[tileProtocol.length - 1] === ":"
      ) {
        tileProtocol = tileProtocol.substr(0, tileProtocol.length - 1);
      }
    } else {
      // use http if the document's protocol is http, otherwise use https
      const documentProtocol = document.location.protocol;
      tileProtocol = documentProtocol === "http:" ? "http" : "https";
    }

    const metadataResource = this._resource.getDerivedResource({
      url: `REST/v1/Imagery/Metadata/${this._mapStyle}`,
      queryParameters: {
        incl: "ImageryProviders",
        key: this._key,
        uriScheme: tileProtocol,
      },
    });
    const that = this;
    let metadataError;

    function metadataSuccess(data) {
      if (data.resourceSets.length !== 1) {
        metadataFailure();
        return;
      }
      const resource = data.resourceSets[0].resources[0];

      that._tileWidth = resource.imageWidth;
      that._tileHeight = resource.imageHeight;
      that._maximumLevel = resource.zoomMax - 1;
      that._imageUrlSubdomains = resource.imageUrlSubdomains;
      that._imageUrlTemplate = resource.imageUrl;

      let attributionList = (that._attributionList = resource.imageryProviders);
      if (!attributionList) {
        attributionList = that._attributionList = [];
      }

      for (
        let attributionIndex = 0, attributionLength = attributionList.length;
        attributionIndex < attributionLength;
        ++attributionIndex
      ) {
        const attribution = attributionList[attributionIndex];

        if (attribution.credit instanceof Credit) {
          // If attribution.credit has already been created
          // then we are using a cached value, which means
          // none of the remaining processing needs to be done.
          break;
        }

        attribution.credit = new Credit(attribution.attribution);
        const coverageAreas = attribution.coverageAreas;

        for (
          let areaIndex = 0, areaLength = attribution.coverageAreas.length;
          areaIndex < areaLength;
          ++areaIndex
        ) {
          const area = coverageAreas[areaIndex];
          const bbox = area.bbox;
          area.bbox = new Rectangle(
            CesiumMath.toRadians(bbox[1]),
            CesiumMath.toRadians(bbox[0]),
            CesiumMath.toRadians(bbox[3]),
            CesiumMath.toRadians(bbox[2])
          );
        }
      }

      that._ready = true;
      that._readyPromise.resolve(true);
      TileProviderError.handleSuccess(metadataError);
    }

    function metadataFailure(e) {
      const message = `An error occurred while accessing ${metadataResource.url}.`;
      metadataError = TileProviderError.handleError(
        metadataError,
        that,
        that._errorEvent,
        message,
        undefined,
        undefined,
        undefined,
        requestMetadata
      );
      that._readyPromise.reject(new RuntimeError(message));
    }

    const cacheKey = metadataResource.url;
    function requestMetadata() {
      const promise = metadataResource.fetchJsonp("jsonp");
      BingMapsImageryProvider._metadataCache[cacheKey] = promise;
      promise.then(metadataSuccess).catch(metadataFailure);
    }

    const promise = BingMapsImageryProvider._metadataCache[cacheKey];
    if (defined(promise)) {
      promise.then(metadataSuccess).catch(metadataFailure);
    } else {
      requestMetadata();
    }
  }

  Object.defineProperties(BingMapsImageryProvider.prototype, {
    /**
     * Gets the name of the BingMaps server url hosting the imagery.
     * @memberof BingMapsImageryProvider.prototype
     * @type {String}
     * @readonly
     */
    url: {
      get: function () {
        return this._resource.url;
      },
    },

    /**
     * Gets the proxy used by this provider.
     * @memberof BingMapsImageryProvider.prototype
     * @type {Proxy}
     * @readonly
     */
    proxy: {
      get: function () {
        return this._resource.proxy;
      },
    },

    /**
     * Gets the Bing Maps key.
     * @memberof BingMapsImageryProvider.prototype
     * @type {String}
     * @readonly
     */
    key: {
      get: function () {
        return this._key;
      },
    },

    /**
     * Gets the type of Bing Maps imagery to load.
     * @memberof BingMapsImageryProvider.prototype
     * @type {BingMapsStyle}
     * @readonly
     */
    mapStyle: {
      get: function () {
        return this._mapStyle;
      },
    },

    /**
     * The culture to use when requesting Bing Maps imagery. Not
     * all cultures are supported. See {@link http://msdn.microsoft.com/en-us/library/hh441729.aspx}
     * for information on the supported cultures.
     * @memberof BingMapsImageryProvider.prototype
     * @type {String}
     * @readonly
     */
    culture: {
      get: function () {
        return this._culture;
      },
    },

    /**
     * Gets the width of each tile, in pixels. This function should
     * not be called before {@link BingMapsImageryProvider#ready} returns true.
     * @memberof BingMapsImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    tileWidth: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "tileWidth must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._tileWidth;
      },
    },

    /**
     * Gets the height of each tile, in pixels.  This function should
     * not be called before {@link BingMapsImageryProvider#ready} returns true.
     * @memberof BingMapsImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    tileHeight: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "tileHeight must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._tileHeight;
      },
    },

    /**
     * Gets the maximum level-of-detail that can be requested.  This function should
     * not be called before {@link BingMapsImageryProvider#ready} returns true.
     * @memberof BingMapsImageryProvider.prototype
     * @type {Number|undefined}
     * @readonly
     */
    maximumLevel: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "maximumLevel must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._maximumLevel;
      },
    },

    /**
     * Gets the minimum level-of-detail that can be requested.  This function should
     * not be called before {@link BingMapsImageryProvider#ready} returns true.
     * @memberof BingMapsImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    minimumLevel: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "minimumLevel must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return 0;
      },
    },

    /**
     * Gets the tiling scheme used by this provider.  This function should
     * not be called before {@link BingMapsImageryProvider#ready} returns true.
     * @memberof BingMapsImageryProvider.prototype
     * @type {TilingScheme}
     * @readonly
     */
    tilingScheme: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "tilingScheme must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._tilingScheme;
      },
    },

    /**
     * Gets the rectangle, in radians, of the imagery provided by this instance.  This function should
     * not be called before {@link BingMapsImageryProvider#ready} returns true.
     * @memberof BingMapsImageryProvider.prototype
     * @type {Rectangle}
     * @readonly
     */
    rectangle: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "rectangle must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._tilingScheme.rectangle;
      },
    },

    /**
     * Gets the tile discard policy.  If not undefined, the discard policy is responsible
     * for filtering out "missing" tiles via its shouldDiscardImage function.  If this function
     * returns undefined, no tiles are filtered.  This function should
     * not be called before {@link BingMapsImageryProvider#ready} returns true.
     * @memberof BingMapsImageryProvider.prototype
     * @type {TileDiscardPolicy}
     * @readonly
     */
    tileDiscardPolicy: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "tileDiscardPolicy must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._tileDiscardPolicy;
      },
    },

    /**
     * Gets an event that is raised when the imagery provider encounters an asynchronous error.  By subscribing
     * to the event, you will be notified of the error and can potentially recover from it.  Event listeners
     * are passed an instance of {@link TileProviderError}.
     * @memberof BingMapsImageryProvider.prototype
     * @type {Event}
     * @readonly
     */
    errorEvent: {
      get: function () {
        return this._errorEvent;
      },
    },

    /**
     * Gets a value indicating whether or not the provider is ready for use.
     * @memberof BingMapsImageryProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    ready: {
      get: function () {
        return this._ready;
      },
    },

    /**
     * Gets a promise that resolves to true when the provider is ready for use.
     * @memberof BingMapsImageryProvider.prototype
     * @type {Promise.<Boolean>}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._readyPromise.promise;
      },
    },

    /**
     * Gets the credit to display when this imagery provider is active.  Typically this is used to credit
     * the source of the imagery.  This function should not be called before {@link BingMapsImageryProvider#ready} returns true.
     * @memberof BingMapsImageryProvider.prototype
     * @type {Credit}
     * @readonly
     */
    credit: {
      get: function () {
        return this._credit;
      },
    },

    /**
     * Gets a value indicating whether or not the images provided by this imagery provider
     * include an alpha channel.  If this property is false, an alpha channel, if present, will
     * be ignored.  If this property is true, any images without an alpha channel will be treated
     * as if their alpha is 1.0 everywhere.  Setting this property to false reduces memory usage
     * and texture upload time.
     * @memberof BingMapsImageryProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    hasAlphaChannel: {
      get: function () {
        return false;
      },
    },
  });

  const rectangleScratch$1 = new Rectangle();

  /**
   * Gets the credits to be displayed when a given tile is displayed.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level;
   * @returns {Credit[]} The credits to be displayed when the tile is displayed.
   *
   * @exception {DeveloperError} <code>getTileCredits</code> must not be called before the imagery provider is ready.
   */
  BingMapsImageryProvider.prototype.getTileCredits = function (x, y, level) {
    //>>includeStart('debug', pragmas.debug);
    if (!this._ready) {
      throw new DeveloperError(
        "getTileCredits must not be called before the imagery provider is ready."
      );
    }
    //>>includeEnd('debug');

    const rectangle = this._tilingScheme.tileXYToRectangle(
      x,
      y,
      level,
      rectangleScratch$1
    );
    const result = getRectangleAttribution(
      this._attributionList,
      level,
      rectangle
    );

    return result;
  };

  /**
   * Requests the image for a given tile.  This function should
   * not be called before {@link BingMapsImageryProvider#ready} returns true.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level.
   * @param {Request} [request] The request object. Intended for internal use only.
   * @returns {Promise.<ImageryTypes>|undefined} A promise for the image that will resolve when the image is available, or
   *          undefined if there are too many active requests to the server, and the request should be retried later.
   *
   * @exception {DeveloperError} <code>requestImage</code> must not be called before the imagery provider is ready.
   */
  BingMapsImageryProvider.prototype.requestImage = function (
    x,
    y,
    level,
    request
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!this._ready) {
      throw new DeveloperError(
        "requestImage must not be called before the imagery provider is ready."
      );
    }
    //>>includeEnd('debug');

    const promise = ImageryProvider.loadImage(
      this,
      buildImageResource$2(this, x, y, level, request)
    );

    if (defined(promise)) {
      return promise.catch(function (error) {
        // One cause of an error here is that the image we tried to load was zero-length.
        // This isn't actually a problem, since it indicates that there is no tile.
        // So, in that case we return the EMPTY_IMAGE sentinel value for later discarding.
        if (defined(error.blob) && error.blob.size === 0) {
          return DiscardEmptyTileImagePolicy.EMPTY_IMAGE;
        }
        return Promise.reject(error);
      });
    }

    return undefined;
  };

  /**
   * Picking features is not currently supported by this imagery provider, so this function simply returns
   * undefined.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level.
   * @param {Number} longitude The longitude at which to pick features.
   * @param {Number} latitude  The latitude at which to pick features.
   * @return {undefined} Undefined since picking is not supported.
   */
  BingMapsImageryProvider.prototype.pickFeatures = function (
    x,
    y,
    level,
    longitude,
    latitude
  ) {
    return undefined;
  };

  /**
   * Converts a tiles (x, y, level) position into a quadkey used to request an image
   * from a Bing Maps server.
   *
   * @param {Number} x The tile's x coordinate.
   * @param {Number} y The tile's y coordinate.
   * @param {Number} level The tile's zoom level.
   *
   * @see {@link http://msdn.microsoft.com/en-us/library/bb259689.aspx|Bing Maps Tile System}
   * @see BingMapsImageryProvider#quadKeyToTileXY
   */
  BingMapsImageryProvider.tileXYToQuadKey = function (x, y, level) {
    let quadkey = "";
    for (let i = level; i >= 0; --i) {
      const bitmask = 1 << i;
      let digit = 0;

      if ((x & bitmask) !== 0) {
        digit |= 1;
      }

      if ((y & bitmask) !== 0) {
        digit |= 2;
      }

      quadkey += digit;
    }
    return quadkey;
  };

  /**
   * Converts a tile's quadkey used to request an image from a Bing Maps server into the
   * (x, y, level) position.
   *
   * @param {String} quadkey The tile's quad key
   *
   * @see {@link http://msdn.microsoft.com/en-us/library/bb259689.aspx|Bing Maps Tile System}
   * @see BingMapsImageryProvider#tileXYToQuadKey
   */
  BingMapsImageryProvider.quadKeyToTileXY = function (quadkey) {
    let x = 0;
    let y = 0;
    const level = quadkey.length - 1;
    for (let i = level; i >= 0; --i) {
      const bitmask = 1 << i;
      const digit = +quadkey[level - i];

      if ((digit & 1) !== 0) {
        x |= bitmask;
      }

      if ((digit & 2) !== 0) {
        y |= bitmask;
      }
    }
    return {
      x: x,
      y: y,
      level: level,
    };
  };

  BingMapsImageryProvider._logoUrl = undefined;

  Object.defineProperties(BingMapsImageryProvider, {
    /**
     * Gets or sets the URL to the Bing logo for display in the credit.
     * @memberof BingMapsImageryProvider
     * @type {String}
     */
    logoUrl: {
      get: function () {
        if (!defined(BingMapsImageryProvider._logoUrl)) {
          BingMapsImageryProvider._logoUrl = buildModuleUrl(
            "Assets/Images/bing_maps_credit.png"
          );
        }
        return BingMapsImageryProvider._logoUrl;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.defined("value", value);
        //>>includeEnd('debug');

        BingMapsImageryProvider._logoUrl = value;
      },
    },
  });

  function buildImageResource$2(imageryProvider, x, y, level, request) {
    const imageUrl = imageryProvider._imageUrlTemplate;

    const subdomains = imageryProvider._imageUrlSubdomains;
    const subdomainIndex = (x + y + level) % subdomains.length;

    return imageryProvider._resource.getDerivedResource({
      url: imageUrl,
      request: request,
      templateValues: {
        quadkey: BingMapsImageryProvider.tileXYToQuadKey(x, y, level),
        subdomain: subdomains[subdomainIndex],
        culture: imageryProvider._culture,
      },
      queryParameters: {
        // this parameter tells the Bing servers to send a zero-length response
        // instead of a placeholder image for missing tiles.
        n: "z",
      },
    });
  }

  const intersectionScratch = new Rectangle();

  function getRectangleAttribution(attributionList, level, rectangle) {
    // Bing levels start at 1, while ours start at 0.
    ++level;

    const result = [];

    for (
      let attributionIndex = 0, attributionLength = attributionList.length;
      attributionIndex < attributionLength;
      ++attributionIndex
    ) {
      const attribution = attributionList[attributionIndex];
      const coverageAreas = attribution.coverageAreas;

      let included = false;

      for (
        let areaIndex = 0, areaLength = attribution.coverageAreas.length;
        !included && areaIndex < areaLength;
        ++areaIndex
      ) {
        const area = coverageAreas[areaIndex];
        if (level >= area.zoomMin && level <= area.zoomMax) {
          const intersection = Rectangle.intersection(
            rectangle,
            area.bbox,
            intersectionScratch
          );
          if (defined(intersection)) {
            included = true;
          }
        }
      }

      if (included) {
        result.push(attribution.credit);
      }
    }

    return result;
  }

  // Exposed for testing
  BingMapsImageryProvider._metadataCache = {};

  const defaultDimensions = new Cartesian3(1.0, 1.0, 1.0);

  /**
   * A ParticleEmitter that emits particles within a box.
   * Particles will be positioned randomly within the box and have initial velocities emanating from the center of the box.
   *
   * @alias BoxEmitter
   * @constructor
   *
   * @param {Cartesian3} dimensions The width, height and depth dimensions of the box.
   */
  function BoxEmitter(dimensions) {
    dimensions = defaultValue(dimensions, defaultDimensions);

    //>>includeStart('debug', pragmas.debug);
    Check.defined("dimensions", dimensions);
    Check.typeOf.number.greaterThanOrEquals("dimensions.x", dimensions.x, 0.0);
    Check.typeOf.number.greaterThanOrEquals("dimensions.y", dimensions.y, 0.0);
    Check.typeOf.number.greaterThanOrEquals("dimensions.z", dimensions.z, 0.0);
    //>>includeEnd('debug');

    this._dimensions = Cartesian3.clone(dimensions);
  }

  Object.defineProperties(BoxEmitter.prototype, {
    /**
     * The width, height and depth dimensions of the box in meters.
     * @memberof BoxEmitter.prototype
     * @type {Cartesian3}
     * @default new Cartesian3(1.0, 1.0, 1.0)
     */
    dimensions: {
      get: function () {
        return this._dimensions;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.defined("value", value);
        Check.typeOf.number.greaterThanOrEquals("value.x", value.x, 0.0);
        Check.typeOf.number.greaterThanOrEquals("value.y", value.y, 0.0);
        Check.typeOf.number.greaterThanOrEquals("value.z", value.z, 0.0);
        //>>includeEnd('debug');
        Cartesian3.clone(value, this._dimensions);
      },
    },
  });

  const scratchHalfDim = new Cartesian3();

  /**
   * Initializes the given {Particle} by setting it's position and velocity.
   *
   * @private
   * @param {Particle} particle The particle to initialize.
   */
  BoxEmitter.prototype.emit = function (particle) {
    const dim = this._dimensions;
    const halfDim = Cartesian3.multiplyByScalar(dim, 0.5, scratchHalfDim);

    const x = CesiumMath.randomBetween(-halfDim.x, halfDim.x);
    const y = CesiumMath.randomBetween(-halfDim.y, halfDim.y);
    const z = CesiumMath.randomBetween(-halfDim.z, halfDim.z);

    particle.position = Cartesian3.fromElements(x, y, z, particle.position);
    particle.velocity = Cartesian3.normalize(
      particle.position,
      particle.velocity
    );
  };

  //This file is automatically rebuilt by the Cesium build process.
  var BrdfLutGeneratorFS = "varying vec2 v_textureCoordinates;\n\
const float M_PI = 3.141592653589793;\n\
float vdcRadicalInverse(int i)\n\
{\n\
float r;\n\
float base = 2.0;\n\
float value = 0.0;\n\
float invBase = 1.0 / base;\n\
float invBi = invBase;\n\
for (int x = 0; x < 100; x++)\n\
{\n\
if (i <= 0)\n\
{\n\
break;\n\
}\n\
r = mod(float(i), base);\n\
value += r * invBi;\n\
invBi *= invBase;\n\
i = int(float(i) * invBase);\n\
}\n\
return value;\n\
}\n\
vec2 hammersley2D(int i, int N)\n\
{\n\
return vec2(float(i) / float(N), vdcRadicalInverse(i));\n\
}\n\
vec3 importanceSampleGGX(vec2 xi, float roughness, vec3 N)\n\
{\n\
float a = roughness * roughness;\n\
float phi = 2.0 * M_PI * xi.x;\n\
float cosTheta = sqrt((1.0 - xi.y) / (1.0 + (a * a - 1.0) * xi.y));\n\
float sinTheta = sqrt(1.0 - cosTheta * cosTheta);\n\
vec3 H = vec3(sinTheta * cos(phi), sinTheta * sin(phi), cosTheta);\n\
vec3 upVector = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);\n\
vec3 tangentX = normalize(cross(upVector, N));\n\
vec3 tangentY = cross(N, tangentX);\n\
return tangentX * H.x + tangentY * H.y + N * H.z;\n\
}\n\
float G1_Smith(float NdotV, float k)\n\
{\n\
return NdotV / (NdotV * (1.0 - k) + k);\n\
}\n\
float G_Smith(float roughness, float NdotV, float NdotL)\n\
{\n\
float k = roughness * roughness / 2.0;\n\
return G1_Smith(NdotV, k) * G1_Smith(NdotL, k);\n\
}\n\
vec2 integrateBrdf(float roughness, float NdotV)\n\
{\n\
vec3 V = vec3(sqrt(1.0 - NdotV * NdotV), 0.0, NdotV);\n\
float A = 0.0;\n\
float B = 0.0;\n\
const int NumSamples = 1024;\n\
for (int i = 0; i < NumSamples; i++)\n\
{\n\
vec2 xi = hammersley2D(i, NumSamples);\n\
vec3 H = importanceSampleGGX(xi, roughness, vec3(0.0, 0.0, 1.0));\n\
vec3 L = 2.0 * dot(V, H) * H - V;\n\
float NdotL = clamp(L.z, 0.0, 1.0);\n\
float NdotH = clamp(H.z, 0.0, 1.0);\n\
float VdotH = clamp(dot(V, H), 0.0, 1.0);\n\
if (NdotL > 0.0)\n\
{\n\
float G = G_Smith(roughness, NdotV, NdotL);\n\
float G_Vis = G * VdotH / (NdotH * NdotV);\n\
float Fc = pow(1.0 - VdotH, 5.0);\n\
A += (1.0 - Fc) * G_Vis;\n\
B += Fc * G_Vis;\n\
}\n\
}\n\
return vec2(A, B) / float(NumSamples);\n\
}\n\
void main()\n\
{\n\
gl_FragColor = vec4(integrateBrdf(v_textureCoordinates.y, v_textureCoordinates.x), 0.0, 1.0);\n\
}\n\
";

  /**
   * @private
   */
  function BrdfLutGenerator() {
    this._colorTexture = undefined;
    this._drawCommand = undefined;
  }

  Object.defineProperties(BrdfLutGenerator.prototype, {
    colorTexture: {
      get: function () {
        return this._colorTexture;
      },
    },
  });

  function createCommand$1(generator, context, framebuffer) {
    const drawCommand = context.createViewportQuadCommand(BrdfLutGeneratorFS, {
      framebuffer: framebuffer,
      renderState: RenderState.fromCache({
        viewport: new BoundingRectangle(0.0, 0.0, 256.0, 256.0),
      }),
    });

    generator._drawCommand = drawCommand;
  }

  BrdfLutGenerator.prototype.update = function (frameState) {
    if (!defined(this._colorTexture)) {
      const context = frameState.context;
      const colorTexture = new Texture({
        context: context,
        width: 256,
        height: 256,
        pixelFormat: PixelFormat$1.RGBA,
        pixelDatatype: PixelDatatype$1.UNSIGNED_BYTE,
        sampler: Sampler.NEAREST,
      });

      this._colorTexture = colorTexture;
      const framebuffer = new Framebuffer({
        context: context,
        colorTextures: [colorTexture],
        destroyAttachments: false,
      });

      createCommand$1(this, context, framebuffer);
      this._drawCommand.execute(context);
      framebuffer.destroy();
      this._drawCommand.shaderProgram =
        this._drawCommand.shaderProgram &&
        this._drawCommand.shaderProgram.destroy();
    }
  };

  BrdfLutGenerator.prototype.isDestroyed = function () {
    return false;
  };

  BrdfLutGenerator.prototype.destroy = function () {
    this._colorTexture = this._colorTexture && this._colorTexture.destroy();
    return destroyObject(this);
  };

  /**
   * Creates tweens for camera flights.
   * <br /><br />
   * Mouse interaction is disabled during flights.
   *
   * @private
   */
  const CameraFlightPath = {};

  function getAltitude(frustum, dx, dy) {
    let near;
    let top;
    let right;
    if (frustum instanceof PerspectiveFrustum) {
      const tanTheta = Math.tan(0.5 * frustum.fovy);
      near = frustum.near;
      top = frustum.near * tanTheta;
      right = frustum.aspectRatio * top;
      return Math.max((dx * near) / right, (dy * near) / top);
    } else if (frustum instanceof PerspectiveOffCenterFrustum) {
      near = frustum.near;
      top = frustum.top;
      right = frustum.right;
      return Math.max((dx * near) / right, (dy * near) / top);
    }

    return Math.max(dx, dy);
  }

  const scratchCart = new Cartesian3();
  const scratchCart2 = new Cartesian3();

  function createPitchFunction(
    startPitch,
    endPitch,
    heightFunction,
    pitchAdjustHeight
  ) {
    if (defined(pitchAdjustHeight) && heightFunction(0.5) > pitchAdjustHeight) {
      const startHeight = heightFunction(0.0);
      const endHeight = heightFunction(1.0);
      const middleHeight = heightFunction(0.5);

      const d1 = middleHeight - startHeight;
      const d2 = middleHeight - endHeight;

      return function (time) {
        const altitude = heightFunction(time);
        if (time <= 0.5) {
          const t1 = (altitude - startHeight) / d1;
          return CesiumMath.lerp(startPitch, -CesiumMath.PI_OVER_TWO, t1);
        }

        const t2 = (altitude - endHeight) / d2;
        return CesiumMath.lerp(-CesiumMath.PI_OVER_TWO, endPitch, 1 - t2);
      };
    }
    return function (time) {
      return CesiumMath.lerp(startPitch, endPitch, time);
    };
  }

  function createHeightFunction(
    camera,
    destination,
    startHeight,
    endHeight,
    optionAltitude
  ) {
    let altitude = optionAltitude;
    const maxHeight = Math.max(startHeight, endHeight);

    if (!defined(altitude)) {
      const start = camera.position;
      const end = destination;
      const up = camera.up;
      const right = camera.right;
      const frustum = camera.frustum;

      const diff = Cartesian3.subtract(start, end, scratchCart);
      const verticalDistance = Cartesian3.magnitude(
        Cartesian3.multiplyByScalar(up, Cartesian3.dot(diff, up), scratchCart2)
      );
      const horizontalDistance = Cartesian3.magnitude(
        Cartesian3.multiplyByScalar(
          right,
          Cartesian3.dot(diff, right),
          scratchCart2
        )
      );

      altitude = Math.min(
        getAltitude(frustum, verticalDistance, horizontalDistance) * 0.2,
        1000000000.0
      );
    }

    if (maxHeight < altitude) {
      const power = 8.0;
      const factor = 1000000.0;

      const s = -Math.pow((altitude - startHeight) * factor, 1.0 / power);
      const e = Math.pow((altitude - endHeight) * factor, 1.0 / power);

      return function (t) {
        const x = t * (e - s) + s;
        return -Math.pow(x, power) / factor + altitude;
      };
    }

    return function (t) {
      return CesiumMath.lerp(startHeight, endHeight, t);
    };
  }

  function adjustAngleForLERP(startAngle, endAngle) {
    if (
      CesiumMath.equalsEpsilon(
        startAngle,
        CesiumMath.TWO_PI,
        CesiumMath.EPSILON11
      )
    ) {
      startAngle = 0.0;
    }

    if (endAngle > startAngle + Math.PI) {
      startAngle += CesiumMath.TWO_PI;
    } else if (endAngle < startAngle - Math.PI) {
      startAngle -= CesiumMath.TWO_PI;
    }

    return startAngle;
  }

  const scratchStart = new Cartesian3();

  function createUpdateCV(
    scene,
    duration,
    destination,
    heading,
    pitch,
    roll,
    optionAltitude,
    optionPitchAdjustHeight
  ) {
    const camera = scene.camera;

    const start = Cartesian3.clone(camera.position, scratchStart);
    const startPitch = camera.pitch;
    const startHeading = adjustAngleForLERP(camera.heading, heading);
    const startRoll = adjustAngleForLERP(camera.roll, roll);

    const heightFunction = createHeightFunction(
      camera,
      destination,
      start.z,
      destination.z,
      optionAltitude
    );

    const pitchFunction = createPitchFunction(
      startPitch,
      pitch,
      heightFunction,
      optionPitchAdjustHeight
    );

    function update(value) {
      const time = value.time / duration;

      camera.setView({
        orientation: {
          heading: CesiumMath.lerp(startHeading, heading, time),
          pitch: pitchFunction(time),
          roll: CesiumMath.lerp(startRoll, roll, time),
        },
      });

      Cartesian2.lerp(start, destination, time, camera.position);
      camera.position.z = heightFunction(time);
    }
    return update;
  }

  function useLongestFlight(startCart, destCart) {
    if (startCart.longitude < destCart.longitude) {
      startCart.longitude += CesiumMath.TWO_PI;
    } else {
      destCart.longitude += CesiumMath.TWO_PI;
    }
  }

  function useShortestFlight(startCart, destCart) {
    const diff = startCart.longitude - destCart.longitude;
    if (diff < -CesiumMath.PI) {
      startCart.longitude += CesiumMath.TWO_PI;
    } else if (diff > CesiumMath.PI) {
      destCart.longitude += CesiumMath.TWO_PI;
    }
  }

  const scratchStartCart = new Cartographic();
  const scratchEndCart = new Cartographic();

  function createUpdate3D(
    scene,
    duration,
    destination,
    heading,
    pitch,
    roll,
    optionAltitude,
    optionFlyOverLongitude,
    optionFlyOverLongitudeWeight,
    optionPitchAdjustHeight
  ) {
    const camera = scene.camera;
    const projection = scene.mapProjection;
    const ellipsoid = projection.ellipsoid;

    const startCart = Cartographic.clone(
      camera.positionCartographic,
      scratchStartCart
    );
    const startPitch = camera.pitch;
    const startHeading = adjustAngleForLERP(camera.heading, heading);
    const startRoll = adjustAngleForLERP(camera.roll, roll);

    const destCart = ellipsoid.cartesianToCartographic(
      destination,
      scratchEndCart
    );
    startCart.longitude = CesiumMath.zeroToTwoPi(startCart.longitude);
    destCart.longitude = CesiumMath.zeroToTwoPi(destCart.longitude);

    let useLongFlight = false;

    if (defined(optionFlyOverLongitude)) {
      const hitLon = CesiumMath.zeroToTwoPi(optionFlyOverLongitude);

      const lonMin = Math.min(startCart.longitude, destCart.longitude);
      const lonMax = Math.max(startCart.longitude, destCart.longitude);

      const hitInside = hitLon >= lonMin && hitLon <= lonMax;

      if (defined(optionFlyOverLongitudeWeight)) {
        // Distance inside  (0...2Pi)
        const din = Math.abs(startCart.longitude - destCart.longitude);
        // Distance outside (0...2Pi)
        const dot = CesiumMath.TWO_PI - din;

        const hitDistance = hitInside ? din : dot;
        const offDistance = hitInside ? dot : din;

        if (
          hitDistance < offDistance * optionFlyOverLongitudeWeight &&
          !hitInside
        ) {
          useLongFlight = true;
        }
      } else if (!hitInside) {
        useLongFlight = true;
      }
    }

    if (useLongFlight) {
      useLongestFlight(startCart, destCart);
    } else {
      useShortestFlight(startCart, destCart);
    }

    const heightFunction = createHeightFunction(
      camera,
      destination,
      startCart.height,
      destCart.height,
      optionAltitude
    );
    const pitchFunction = createPitchFunction(
      startPitch,
      pitch,
      heightFunction,
      optionPitchAdjustHeight
    );

    // Isolate scope for update function.
    // to have local copies of vars used in lerp
    // Othervise, if you call nex
    // createUpdate3D (createAnimationTween)
    // before you played animation, variables will be overwriten.
    function isolateUpdateFunction() {
      const startLongitude = startCart.longitude;
      const destLongitude = destCart.longitude;
      const startLatitude = startCart.latitude;
      const destLatitude = destCart.latitude;

      return function update(value) {
        const time = value.time / duration;

        const position = Cartesian3.fromRadians(
          CesiumMath.lerp(startLongitude, destLongitude, time),
          CesiumMath.lerp(startLatitude, destLatitude, time),
          heightFunction(time),
          ellipsoid
        );

        camera.setView({
          destination: position,
          orientation: {
            heading: CesiumMath.lerp(startHeading, heading, time),
            pitch: pitchFunction(time),
            roll: CesiumMath.lerp(startRoll, roll, time),
          },
        });
      };
    }
    return isolateUpdateFunction();
  }

  function createUpdate2D(
    scene,
    duration,
    destination,
    heading,
    pitch,
    roll,
    optionAltitude
  ) {
    const camera = scene.camera;

    const start = Cartesian3.clone(camera.position, scratchStart);
    const startHeading = adjustAngleForLERP(camera.heading, heading);

    const startHeight = camera.frustum.right - camera.frustum.left;
    const heightFunction = createHeightFunction(
      camera,
      destination,
      startHeight,
      destination.z,
      optionAltitude
    );

    function update(value) {
      const time = value.time / duration;

      camera.setView({
        orientation: {
          heading: CesiumMath.lerp(startHeading, heading, time),
        },
      });

      Cartesian2.lerp(start, destination, time, camera.position);

      const zoom = heightFunction(time);

      const frustum = camera.frustum;
      const ratio = frustum.top / frustum.right;

      const incrementAmount = (zoom - (frustum.right - frustum.left)) * 0.5;
      frustum.right += incrementAmount;
      frustum.left -= incrementAmount;
      frustum.top = ratio * frustum.right;
      frustum.bottom = -frustum.top;
    }
    return update;
  }

  const scratchCartographic$5 = new Cartographic();
  const scratchDestination = new Cartesian3();

  function emptyFlight(complete, cancel) {
    return {
      startObject: {},
      stopObject: {},
      duration: 0.0,
      complete: complete,
      cancel: cancel,
    };
  }

  function wrapCallback(controller, cb) {
    function wrapped() {
      if (typeof cb === "function") {
        cb();
      }

      controller.enableInputs = true;
    }
    return wrapped;
  }

  CameraFlightPath.createTween = function (scene, options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    let destination = options.destination;

    //>>includeStart('debug', pragmas.debug);
    if (!defined(scene)) {
      throw new DeveloperError("scene is required.");
    }
    if (!defined(destination)) {
      throw new DeveloperError("destination is required.");
    }
    //>>includeEnd('debug');
    const mode = scene.mode;

    if (mode === SceneMode$1.MORPHING) {
      return emptyFlight();
    }

    const convert = defaultValue(options.convert, true);
    const projection = scene.mapProjection;
    const ellipsoid = projection.ellipsoid;
    const maximumHeight = options.maximumHeight;
    const flyOverLongitude = options.flyOverLongitude;
    const flyOverLongitudeWeight = options.flyOverLongitudeWeight;
    const pitchAdjustHeight = options.pitchAdjustHeight;
    let easingFunction = options.easingFunction;

    if (convert && mode !== SceneMode$1.SCENE3D) {
      ellipsoid.cartesianToCartographic(destination, scratchCartographic$5);
      destination = projection.project(scratchCartographic$5, scratchDestination);
    }

    const camera = scene.camera;
    const transform = options.endTransform;
    if (defined(transform)) {
      camera._setTransform(transform);
    }

    let duration = options.duration;
    if (!defined(duration)) {
      duration =
        Math.ceil(Cartesian3.distance(camera.position, destination) / 1000000.0) +
        2.0;
      duration = Math.min(duration, 3.0);
    }

    const heading = defaultValue(options.heading, 0.0);
    const pitch = defaultValue(options.pitch, -CesiumMath.PI_OVER_TWO);
    const roll = defaultValue(options.roll, 0.0);

    const controller = scene.screenSpaceCameraController;
    controller.enableInputs = false;

    const complete = wrapCallback(controller, options.complete);
    const cancel = wrapCallback(controller, options.cancel);

    const frustum = camera.frustum;

    let empty = scene.mode === SceneMode$1.SCENE2D;
    empty =
      empty &&
      Cartesian2.equalsEpsilon(camera.position, destination, CesiumMath.EPSILON6);
    empty =
      empty &&
      CesiumMath.equalsEpsilon(
        Math.max(frustum.right - frustum.left, frustum.top - frustum.bottom),
        destination.z,
        CesiumMath.EPSILON6
      );

    empty =
      empty ||
      (scene.mode !== SceneMode$1.SCENE2D &&
        Cartesian3.equalsEpsilon(
          destination,
          camera.position,
          CesiumMath.EPSILON10
        ));

    empty =
      empty &&
      CesiumMath.equalsEpsilon(
        CesiumMath.negativePiToPi(heading),
        CesiumMath.negativePiToPi(camera.heading),
        CesiumMath.EPSILON10
      ) &&
      CesiumMath.equalsEpsilon(
        CesiumMath.negativePiToPi(pitch),
        CesiumMath.negativePiToPi(camera.pitch),
        CesiumMath.EPSILON10
      ) &&
      CesiumMath.equalsEpsilon(
        CesiumMath.negativePiToPi(roll),
        CesiumMath.negativePiToPi(camera.roll),
        CesiumMath.EPSILON10
      );

    if (empty) {
      return emptyFlight(complete, cancel);
    }

    const updateFunctions = new Array(4);
    updateFunctions[SceneMode$1.SCENE2D] = createUpdate2D;
    updateFunctions[SceneMode$1.SCENE3D] = createUpdate3D;
    updateFunctions[SceneMode$1.COLUMBUS_VIEW] = createUpdateCV;

    if (duration <= 0.0) {
      const newOnComplete = function () {
        const update = updateFunctions[mode](
          scene,
          1.0,
          destination,
          heading,
          pitch,
          roll,
          maximumHeight,
          flyOverLongitude,
          flyOverLongitudeWeight,
          pitchAdjustHeight
        );
        update({ time: 1.0 });

        if (typeof complete === "function") {
          complete();
        }
      };
      return emptyFlight(newOnComplete, cancel);
    }

    const update = updateFunctions[mode](
      scene,
      duration,
      destination,
      heading,
      pitch,
      roll,
      maximumHeight,
      flyOverLongitude,
      flyOverLongitudeWeight,
      pitchAdjustHeight
    );

    if (!defined(easingFunction)) {
      const startHeight = camera.positionCartographic.height;
      const endHeight =
        mode === SceneMode$1.SCENE3D
          ? ellipsoid.cartesianToCartographic(destination).height
          : destination.z;

      if (startHeight > endHeight && startHeight > 11500.0) {
        easingFunction = EasingFunction$1.CUBIC_OUT;
      } else {
        easingFunction = EasingFunction$1.QUINTIC_IN_OUT;
      }
    }

    return {
      duration: duration,
      easingFunction: easingFunction,
      startObject: {
        time: 0.0,
      },
      stopObject: {
        time: duration,
      },
      update: update,
      complete: complete,
      cancel: cancel,
    };
  };

  /**
   * Describes how the map will operate in 2D.
   *
   * @enum {Number}
   */
  const MapMode2D = {
    /**
     * The 2D map can be rotated about the z axis.
     *
     * @type {Number}
     * @constant
     */
    ROTATE: 0,

    /**
     * The 2D map can be scrolled infinitely in the horizontal direction.
     *
     * @type {Number}
     * @constant
     */
    INFINITE_SCROLL: 1,
  };
  var MapMode2D$1 = Object.freeze(MapMode2D);

  /**
   * @typedef {Object} DirectionUp
   *
   * An orientation given by a pair of unit vectors
   *
   * @property {Cartesian3} direction The unit "direction" vector
   * @property {Cartesian3} up The unit "up" vector
   **/
  /**
   * @typedef {Object} HeadingPitchRollValues
   *
   * An orientation given by numeric heading, pitch, and roll
   *
   * @property {number} [heading=0.0] The heading in radians
   * @property {number} [pitch=-CesiumMath.PI_OVER_TWO] The pitch in radians
   * @property {number} [roll=0.0] The roll in meters
   **/

  /**
   * The camera is defined by a position, orientation, and view frustum.
   * <br /><br />
   * The orientation forms an orthonormal basis with a view, up and right = view x up unit vectors.
   * <br /><br />
   * The viewing frustum is defined by 6 planes.
   * Each plane is represented by a {@link Cartesian4} object, where the x, y, and z components
   * define the unit vector normal to the plane, and the w component is the distance of the
   * plane from the origin/camera position.
   *
   * @alias Camera
   *
   * @constructor
   *
   * @param {Scene} scene The scene.
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Camera.html|Cesium Sandcastle Camera Demo}
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Camera%20Tutorial.html|Cesium Sandcastle Camera Tutorial Example}
   * @demo {@link https://cesium.com/learn/cesiumjs-learn/cesiumjs-camera|Camera Tutorial}
   *
   * @example
   * // Create a camera looking down the negative z-axis, positioned at the origin,
   * // with a field of view of 60 degrees, and 1:1 aspect ratio.
   * const camera = new Cesium.Camera(scene);
   * camera.position = new Cesium.Cartesian3();
   * camera.direction = Cesium.Cartesian3.negate(Cesium.Cartesian3.UNIT_Z, new Cesium.Cartesian3());
   * camera.up = Cesium.Cartesian3.clone(Cesium.Cartesian3.UNIT_Y);
   * camera.frustum.fov = Cesium.Math.PI_OVER_THREE;
   * camera.frustum.near = 1.0;
   * camera.frustum.far = 2.0;
   */
  function Camera(scene) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(scene)) {
      throw new DeveloperError("scene is required.");
    }
    //>>includeEnd('debug');
    this._scene = scene;

    this._transform = Matrix4.clone(Matrix4.IDENTITY);
    this._invTransform = Matrix4.clone(Matrix4.IDENTITY);
    this._actualTransform = Matrix4.clone(Matrix4.IDENTITY);
    this._actualInvTransform = Matrix4.clone(Matrix4.IDENTITY);
    this._transformChanged = false;

    /**
     * The position of the camera.
     *
     * @type {Cartesian3}
     */
    this.position = new Cartesian3();
    this._position = new Cartesian3();
    this._positionWC = new Cartesian3();
    this._positionCartographic = new Cartographic();
    this._oldPositionWC = undefined;

    /**
     * The position delta magnitude.
     *
     * @private
     */
    this.positionWCDeltaMagnitude = 0.0;

    /**
     * The position delta magnitude last frame.
     *
     * @private
     */
    this.positionWCDeltaMagnitudeLastFrame = 0.0;

    /**
     * How long in seconds since the camera has stopped moving
     *
     * @private
     */
    this.timeSinceMoved = 0.0;
    this._lastMovedTimestamp = 0.0;

    /**
     * The view direction of the camera.
     *
     * @type {Cartesian3}
     */
    this.direction = new Cartesian3();
    this._direction = new Cartesian3();
    this._directionWC = new Cartesian3();

    /**
     * The up direction of the camera.
     *
     * @type {Cartesian3}
     */
    this.up = new Cartesian3();
    this._up = new Cartesian3();
    this._upWC = new Cartesian3();

    /**
     * The right direction of the camera.
     *
     * @type {Cartesian3}
     */
    this.right = new Cartesian3();
    this._right = new Cartesian3();
    this._rightWC = new Cartesian3();

    /**
     * The region of space in view.
     *
     * @type {PerspectiveFrustum|PerspectiveOffCenterFrustum|OrthographicFrustum}
     * @default PerspectiveFrustum()
     *
     * @see PerspectiveFrustum
     * @see PerspectiveOffCenterFrustum
     * @see OrthographicFrustum
     */
    this.frustum = new PerspectiveFrustum();
    this.frustum.aspectRatio =
      scene.drawingBufferWidth / scene.drawingBufferHeight;
    this.frustum.fov = CesiumMath.toRadians(60.0);

    /**
     * The default amount to move the camera when an argument is not
     * provided to the move methods.
     * @type {Number}
     * @default 100000.0;
     */
    this.defaultMoveAmount = 100000.0;
    /**
     * The default amount to rotate the camera when an argument is not
     * provided to the look methods.
     * @type {Number}
     * @default Math.PI / 60.0
     */
    this.defaultLookAmount = Math.PI / 60.0;
    /**
     * The default amount to rotate the camera when an argument is not
     * provided to the rotate methods.
     * @type {Number}
     * @default Math.PI / 3600.0
     */
    this.defaultRotateAmount = Math.PI / 3600.0;
    /**
     * The default amount to move the camera when an argument is not
     * provided to the zoom methods.
     * @type {Number}
     * @default 100000.0;
     */
    this.defaultZoomAmount = 100000.0;
    /**
     * If set, the camera will not be able to rotate past this axis in either direction.
     * @type {Cartesian3}
     * @default undefined
     */
    this.constrainedAxis = undefined;
    /**
     * The factor multiplied by the the map size used to determine where to clamp the camera position
     * when zooming out from the surface. The default is 1.5. Only valid for 2D and the map is rotatable.
     * @type {Number}
     * @default 1.5
     */
    this.maximumZoomFactor = 1.5;

    this._moveStart = new Event();
    this._moveEnd = new Event();

    this._changed = new Event();
    this._changedPosition = undefined;
    this._changedDirection = undefined;
    this._changedFrustum = undefined;
    this._changedHeading = undefined;

    /**
     * The amount the camera has to change before the <code>changed</code> event is raised. The value is a percentage in the [0, 1] range.
     * @type {number}
     * @default 0.5
     */
    this.percentageChanged = 0.5;

    this._viewMatrix = new Matrix4();
    this._invViewMatrix = new Matrix4();
    updateViewMatrix(this);

    this._mode = SceneMode$1.SCENE3D;
    this._modeChanged = true;
    const projection = scene.mapProjection;
    this._projection = projection;
    this._maxCoord = projection.project(
      new Cartographic(Math.PI, CesiumMath.PI_OVER_TWO)
    );
    this._max2Dfrustum = undefined;

    // set default view
    rectangleCameraPosition3D(
      this,
      Camera.DEFAULT_VIEW_RECTANGLE,
      this.position,
      true
    );

    let mag = Cartesian3.magnitude(this.position);
    mag += mag * Camera.DEFAULT_VIEW_FACTOR;
    Cartesian3.normalize(this.position, this.position);
    Cartesian3.multiplyByScalar(this.position, mag, this.position);
  }

  /**
   * @private
   */
  Camera.TRANSFORM_2D = new Matrix4(
    0.0,
    0.0,
    1.0,
    0.0,
    1.0,
    0.0,
    0.0,
    0.0,
    0.0,
    1.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    1.0
  );

  /**
   * @private
   */
  Camera.TRANSFORM_2D_INVERSE = Matrix4.inverseTransformation(
    Camera.TRANSFORM_2D,
    new Matrix4()
  );

  /**
   * The default rectangle the camera will view on creation.
   * @type Rectangle
   */
  Camera.DEFAULT_VIEW_RECTANGLE = Rectangle.fromDegrees(
    -95.0,
    -20.0,
    -70.0,
    90.0
  );

  /**
   * A scalar to multiply to the camera position and add it back after setting the camera to view the rectangle.
   * A value of zero means the camera will view the entire {@link Camera#DEFAULT_VIEW_RECTANGLE}, a value greater than zero
   * will move it further away from the extent, and a value less than zero will move it close to the extent.
   * @type Number
   */
  Camera.DEFAULT_VIEW_FACTOR = 0.5;

  /**
   * The default heading/pitch/range that is used when the camera flies to a location that contains a bounding sphere.
   * @type HeadingPitchRange
   */
  Camera.DEFAULT_OFFSET = new HeadingPitchRange(
    0.0,
    -CesiumMath.PI_OVER_FOUR,
    0.0
  );

  function updateViewMatrix(camera) {
    Matrix4.computeView(
      camera._position,
      camera._direction,
      camera._up,
      camera._right,
      camera._viewMatrix
    );
    Matrix4.multiply(
      camera._viewMatrix,
      camera._actualInvTransform,
      camera._viewMatrix
    );
    Matrix4.inverseTransformation(camera._viewMatrix, camera._invViewMatrix);
  }

  function updateCameraDeltas(camera) {
    if (!defined(camera._oldPositionWC)) {
      camera._oldPositionWC = Cartesian3.clone(
        camera.positionWC,
        camera._oldPositionWC
      );
    } else {
      camera.positionWCDeltaMagnitudeLastFrame = camera.positionWCDeltaMagnitude;
      const delta = Cartesian3.subtract(
        camera.positionWC,
        camera._oldPositionWC,
        camera._oldPositionWC
      );
      camera.positionWCDeltaMagnitude = Cartesian3.magnitude(delta);
      camera._oldPositionWC = Cartesian3.clone(
        camera.positionWC,
        camera._oldPositionWC
      );

      // Update move timers
      if (camera.positionWCDeltaMagnitude > 0.0) {
        camera.timeSinceMoved = 0.0;
        camera._lastMovedTimestamp = getTimestamp$1();
      } else {
        camera.timeSinceMoved =
          Math.max(getTimestamp$1() - camera._lastMovedTimestamp, 0.0) / 1000.0;
      }
    }
  }

  /**
   * Checks if there's a camera flight with preload for this camera.
   *
   * @returns {Boolean} Whether or not this camera has a current flight with a valid preloadFlightCamera in scene.
   *
   * @private
   *
   */
  Camera.prototype.canPreloadFlight = function () {
    return defined(this._currentFlight) && this._mode !== SceneMode$1.SCENE2D;
  };

  Camera.prototype._updateCameraChanged = function () {
    const camera = this;

    updateCameraDeltas(camera);

    if (camera._changed.numberOfListeners === 0) {
      return;
    }

    const percentageChanged = camera.percentageChanged;

    const currentHeading = camera.heading;

    if (!defined(camera._changedHeading)) {
      camera._changedHeading = currentHeading;
    }

    let delta =
      Math.abs(camera._changedHeading - currentHeading) % CesiumMath.TWO_PI;
    delta = delta > CesiumMath.PI ? CesiumMath.TWO_PI - delta : delta;

    // Since delta is computed as the shortest distance between two angles
    // the percentage is relative to the half circle.
    const headingChangedPercentage = delta / Math.PI;

    if (headingChangedPercentage > percentageChanged) {
      camera._changed.raiseEvent(headingChangedPercentage);
      camera._changedHeading = currentHeading;
    }

    if (camera._mode === SceneMode$1.SCENE2D) {
      if (!defined(camera._changedFrustum)) {
        camera._changedPosition = Cartesian3.clone(
          camera.position,
          camera._changedPosition
        );
        camera._changedFrustum = camera.frustum.clone();
        return;
      }

      const position = camera.position;
      const lastPosition = camera._changedPosition;

      const frustum = camera.frustum;
      const lastFrustum = camera._changedFrustum;

      const x0 = position.x + frustum.left;
      const x1 = position.x + frustum.right;
      const x2 = lastPosition.x + lastFrustum.left;
      const x3 = lastPosition.x + lastFrustum.right;

      const y0 = position.y + frustum.bottom;
      const y1 = position.y + frustum.top;
      const y2 = lastPosition.y + lastFrustum.bottom;
      const y3 = lastPosition.y + lastFrustum.top;

      const leftX = Math.max(x0, x2);
      const rightX = Math.min(x1, x3);
      const bottomY = Math.max(y0, y2);
      const topY = Math.min(y1, y3);

      let areaPercentage;
      if (leftX >= rightX || bottomY >= y1) {
        areaPercentage = 1.0;
      } else {
        let areaRef = lastFrustum;
        if (x0 < x2 && x1 > x3 && y0 < y2 && y1 > y3) {
          areaRef = frustum;
        }
        areaPercentage =
          1.0 -
          ((rightX - leftX) * (topY - bottomY)) /
            ((areaRef.right - areaRef.left) * (areaRef.top - areaRef.bottom));
      }

      if (areaPercentage > percentageChanged) {
        camera._changed.raiseEvent(areaPercentage);
        camera._changedPosition = Cartesian3.clone(
          camera.position,
          camera._changedPosition
        );
        camera._changedFrustum = camera.frustum.clone(camera._changedFrustum);
      }
      return;
    }

    if (!defined(camera._changedDirection)) {
      camera._changedPosition = Cartesian3.clone(
        camera.positionWC,
        camera._changedPosition
      );
      camera._changedDirection = Cartesian3.clone(
        camera.directionWC,
        camera._changedDirection
      );
      return;
    }

    const dirAngle = CesiumMath.acosClamped(
      Cartesian3.dot(camera.directionWC, camera._changedDirection)
    );

    let dirPercentage;
    if (defined(camera.frustum.fovy)) {
      dirPercentage = dirAngle / (camera.frustum.fovy * 0.5);
    } else {
      dirPercentage = dirAngle;
    }

    const distance = Cartesian3.distance(
      camera.positionWC,
      camera._changedPosition
    );
    const heightPercentage = distance / camera.positionCartographic.height;

    if (
      dirPercentage > percentageChanged ||
      heightPercentage > percentageChanged
    ) {
      camera._changed.raiseEvent(Math.max(dirPercentage, heightPercentage));
      camera._changedPosition = Cartesian3.clone(
        camera.positionWC,
        camera._changedPosition
      );
      camera._changedDirection = Cartesian3.clone(
        camera.directionWC,
        camera._changedDirection
      );
    }
  };

  function convertTransformForColumbusView(camera) {
    Transforms.basisTo2D(
      camera._projection,
      camera._transform,
      camera._actualTransform
    );
  }

  const scratchCartographic$4 = new Cartographic();
  const scratchCartesian3Projection = new Cartesian3();
  const scratchCartesian3$1 = new Cartesian3();
  const scratchCartesian4Origin = new Cartesian4();
  const scratchCartesian4NewOrigin = new Cartesian4();
  const scratchCartesian4NewXAxis = new Cartesian4();
  const scratchCartesian4NewYAxis = new Cartesian4();
  const scratchCartesian4NewZAxis = new Cartesian4();

  function convertTransformFor2D(camera) {
    const projection = camera._projection;
    const ellipsoid = projection.ellipsoid;

    const origin = Matrix4.getColumn(
      camera._transform,
      3,
      scratchCartesian4Origin
    );
    const cartographic = ellipsoid.cartesianToCartographic(
      origin,
      scratchCartographic$4
    );

    const projectedPosition = projection.project(
      cartographic,
      scratchCartesian3Projection
    );
    const newOrigin = scratchCartesian4NewOrigin;
    newOrigin.x = projectedPosition.z;
    newOrigin.y = projectedPosition.x;
    newOrigin.z = projectedPosition.y;
    newOrigin.w = 1.0;

    const newZAxis = Cartesian4.clone(
      Cartesian4.UNIT_X,
      scratchCartesian4NewZAxis
    );

    const xAxis = Cartesian4.add(
      Matrix4.getColumn(camera._transform, 0, scratchCartesian3$1),
      origin,
      scratchCartesian3$1
    );
    ellipsoid.cartesianToCartographic(xAxis, cartographic);

    projection.project(cartographic, projectedPosition);
    const newXAxis = scratchCartesian4NewXAxis;
    newXAxis.x = projectedPosition.z;
    newXAxis.y = projectedPosition.x;
    newXAxis.z = projectedPosition.y;
    newXAxis.w = 0.0;

    Cartesian3.subtract(newXAxis, newOrigin, newXAxis);
    newXAxis.x = 0.0;

    const newYAxis = scratchCartesian4NewYAxis;
    if (Cartesian3.magnitudeSquared(newXAxis) > CesiumMath.EPSILON10) {
      Cartesian3.cross(newZAxis, newXAxis, newYAxis);
    } else {
      const yAxis = Cartesian4.add(
        Matrix4.getColumn(camera._transform, 1, scratchCartesian3$1),
        origin,
        scratchCartesian3$1
      );
      ellipsoid.cartesianToCartographic(yAxis, cartographic);

      projection.project(cartographic, projectedPosition);
      newYAxis.x = projectedPosition.z;
      newYAxis.y = projectedPosition.x;
      newYAxis.z = projectedPosition.y;
      newYAxis.w = 0.0;

      Cartesian3.subtract(newYAxis, newOrigin, newYAxis);
      newYAxis.x = 0.0;

      if (Cartesian3.magnitudeSquared(newYAxis) < CesiumMath.EPSILON10) {
        Cartesian4.clone(Cartesian4.UNIT_Y, newXAxis);
        Cartesian4.clone(Cartesian4.UNIT_Z, newYAxis);
      }
    }

    Cartesian3.cross(newYAxis, newZAxis, newXAxis);
    Cartesian3.normalize(newXAxis, newXAxis);
    Cartesian3.cross(newZAxis, newXAxis, newYAxis);
    Cartesian3.normalize(newYAxis, newYAxis);

    Matrix4.setColumn(
      camera._actualTransform,
      0,
      newXAxis,
      camera._actualTransform
    );
    Matrix4.setColumn(
      camera._actualTransform,
      1,
      newYAxis,
      camera._actualTransform
    );
    Matrix4.setColumn(
      camera._actualTransform,
      2,
      newZAxis,
      camera._actualTransform
    );
    Matrix4.setColumn(
      camera._actualTransform,
      3,
      newOrigin,
      camera._actualTransform
    );
  }

  const scratchCartesian$1 = new Cartesian3();

  function updateMembers(camera) {
    const mode = camera._mode;

    let heightChanged = false;
    let height = 0.0;
    if (mode === SceneMode$1.SCENE2D) {
      height = camera.frustum.right - camera.frustum.left;
      heightChanged = height !== camera._positionCartographic.height;
    }

    let position = camera._position;
    const positionChanged =
      !Cartesian3.equals(position, camera.position) || heightChanged;
    if (positionChanged) {
      position = Cartesian3.clone(camera.position, camera._position);
    }

    let direction = camera._direction;
    const directionChanged = !Cartesian3.equals(direction, camera.direction);
    if (directionChanged) {
      Cartesian3.normalize(camera.direction, camera.direction);
      direction = Cartesian3.clone(camera.direction, camera._direction);
    }

    let up = camera._up;
    const upChanged = !Cartesian3.equals(up, camera.up);
    if (upChanged) {
      Cartesian3.normalize(camera.up, camera.up);
      up = Cartesian3.clone(camera.up, camera._up);
    }

    let right = camera._right;
    const rightChanged = !Cartesian3.equals(right, camera.right);
    if (rightChanged) {
      Cartesian3.normalize(camera.right, camera.right);
      right = Cartesian3.clone(camera.right, camera._right);
    }

    const transformChanged = camera._transformChanged || camera._modeChanged;
    camera._transformChanged = false;

    if (transformChanged) {
      Matrix4.inverseTransformation(camera._transform, camera._invTransform);

      if (
        camera._mode === SceneMode$1.COLUMBUS_VIEW ||
        camera._mode === SceneMode$1.SCENE2D
      ) {
        if (Matrix4.equals(Matrix4.IDENTITY, camera._transform)) {
          Matrix4.clone(Camera.TRANSFORM_2D, camera._actualTransform);
        } else if (camera._mode === SceneMode$1.COLUMBUS_VIEW) {
          convertTransformForColumbusView(camera);
        } else {
          convertTransformFor2D(camera);
        }
      } else {
        Matrix4.clone(camera._transform, camera._actualTransform);
      }

      Matrix4.inverseTransformation(
        camera._actualTransform,
        camera._actualInvTransform
      );

      camera._modeChanged = false;
    }

    const transform = camera._actualTransform;

    if (positionChanged || transformChanged) {
      camera._positionWC = Matrix4.multiplyByPoint(
        transform,
        position,
        camera._positionWC
      );

      // Compute the Cartographic position of the camera.
      if (mode === SceneMode$1.SCENE3D || mode === SceneMode$1.MORPHING) {
        camera._positionCartographic = camera._projection.ellipsoid.cartesianToCartographic(
          camera._positionWC,
          camera._positionCartographic
        );
      } else {
        // The camera position is expressed in the 2D coordinate system where the Y axis is to the East,
        // the Z axis is to the North, and the X axis is out of the map.  Express them instead in the ENU axes where
        // X is to the East, Y is to the North, and Z is out of the local horizontal plane.
        const positionENU = scratchCartesian$1;
        positionENU.x = camera._positionWC.y;
        positionENU.y = camera._positionWC.z;
        positionENU.z = camera._positionWC.x;

        // In 2D, the camera height is always 12.7 million meters.
        // The apparent height is equal to half the frustum width.
        if (mode === SceneMode$1.SCENE2D) {
          positionENU.z = height;
        }

        camera._projection.unproject(positionENU, camera._positionCartographic);
      }
    }

    if (directionChanged || upChanged || rightChanged) {
      const det = Cartesian3.dot(
        direction,
        Cartesian3.cross(up, right, scratchCartesian$1)
      );
      if (Math.abs(1.0 - det) > CesiumMath.EPSILON2) {
        //orthonormalize axes
        const invUpMag = 1.0 / Cartesian3.magnitudeSquared(up);
        const scalar = Cartesian3.dot(up, direction) * invUpMag;
        const w0 = Cartesian3.multiplyByScalar(
          direction,
          scalar,
          scratchCartesian$1
        );
        up = Cartesian3.normalize(
          Cartesian3.subtract(up, w0, camera._up),
          camera._up
        );
        Cartesian3.clone(up, camera.up);

        right = Cartesian3.cross(direction, up, camera._right);
        Cartesian3.clone(right, camera.right);
      }
    }

    if (directionChanged || transformChanged) {
      camera._directionWC = Matrix4.multiplyByPointAsVector(
        transform,
        direction,
        camera._directionWC
      );
      Cartesian3.normalize(camera._directionWC, camera._directionWC);
    }

    if (upChanged || transformChanged) {
      camera._upWC = Matrix4.multiplyByPointAsVector(transform, up, camera._upWC);
      Cartesian3.normalize(camera._upWC, camera._upWC);
    }

    if (rightChanged || transformChanged) {
      camera._rightWC = Matrix4.multiplyByPointAsVector(
        transform,
        right,
        camera._rightWC
      );
      Cartesian3.normalize(camera._rightWC, camera._rightWC);
    }

    if (
      positionChanged ||
      directionChanged ||
      upChanged ||
      rightChanged ||
      transformChanged
    ) {
      updateViewMatrix(camera);
    }
  }

  function getHeading(direction, up) {
    let heading;
    if (
      !CesiumMath.equalsEpsilon(Math.abs(direction.z), 1.0, CesiumMath.EPSILON3)
    ) {
      heading = Math.atan2(direction.y, direction.x) - CesiumMath.PI_OVER_TWO;
    } else {
      heading = Math.atan2(up.y, up.x) - CesiumMath.PI_OVER_TWO;
    }

    return CesiumMath.TWO_PI - CesiumMath.zeroToTwoPi(heading);
  }

  function getPitch(direction) {
    return CesiumMath.PI_OVER_TWO - CesiumMath.acosClamped(direction.z);
  }

  function getRoll(direction, up, right) {
    let roll = 0.0;
    if (
      !CesiumMath.equalsEpsilon(Math.abs(direction.z), 1.0, CesiumMath.EPSILON3)
    ) {
      roll = Math.atan2(-right.z, up.z);
      roll = CesiumMath.zeroToTwoPi(roll + CesiumMath.TWO_PI);
    }

    return roll;
  }

  const scratchHPRMatrix1 = new Matrix4();
  const scratchHPRMatrix2 = new Matrix4();

  Object.defineProperties(Camera.prototype, {
    /**
     * Gets the camera's reference frame. The inverse of this transformation is appended to the view matrix.
     * @memberof Camera.prototype
     *
     * @type {Matrix4}
     * @readonly
     *
     * @default {@link Matrix4.IDENTITY}
     */
    transform: {
      get: function () {
        return this._transform;
      },
    },

    /**
     * Gets the inverse camera transform.
     * @memberof Camera.prototype
     *
     * @type {Matrix4}
     * @readonly
     *
     * @default {@link Matrix4.IDENTITY}
     */
    inverseTransform: {
      get: function () {
        updateMembers(this);
        return this._invTransform;
      },
    },

    /**
     * Gets the view matrix.
     * @memberof Camera.prototype
     *
     * @type {Matrix4}
     * @readonly
     *
     * @see Camera#inverseViewMatrix
     */
    viewMatrix: {
      get: function () {
        updateMembers(this);
        return this._viewMatrix;
      },
    },

    /**
     * Gets the inverse view matrix.
     * @memberof Camera.prototype
     *
     * @type {Matrix4}
     * @readonly
     *
     * @see Camera#viewMatrix
     */
    inverseViewMatrix: {
      get: function () {
        updateMembers(this);
        return this._invViewMatrix;
      },
    },

    /**
     * Gets the {@link Cartographic} position of the camera, with longitude and latitude
     * expressed in radians and height in meters.  In 2D and Columbus View, it is possible
     * for the returned longitude and latitude to be outside the range of valid longitudes
     * and latitudes when the camera is outside the map.
     * @memberof Camera.prototype
     *
     * @type {Cartographic}
     * @readonly
     */
    positionCartographic: {
      get: function () {
        updateMembers(this);
        return this._positionCartographic;
      },
    },

    /**
     * Gets the position of the camera in world coordinates.
     * @memberof Camera.prototype
     *
     * @type {Cartesian3}
     * @readonly
     */
    positionWC: {
      get: function () {
        updateMembers(this);
        return this._positionWC;
      },
    },

    /**
     * Gets the view direction of the camera in world coordinates.
     * @memberof Camera.prototype
     *
     * @type {Cartesian3}
     * @readonly
     */
    directionWC: {
      get: function () {
        updateMembers(this);
        return this._directionWC;
      },
    },

    /**
     * Gets the up direction of the camera in world coordinates.
     * @memberof Camera.prototype
     *
     * @type {Cartesian3}
     * @readonly
     */
    upWC: {
      get: function () {
        updateMembers(this);
        return this._upWC;
      },
    },

    /**
     * Gets the right direction of the camera in world coordinates.
     * @memberof Camera.prototype
     *
     * @type {Cartesian3}
     * @readonly
     */
    rightWC: {
      get: function () {
        updateMembers(this);
        return this._rightWC;
      },
    },

    /**
     * Gets the camera heading in radians.
     * @memberof Camera.prototype
     *
     * @type {Number}
     * @readonly
     */
    heading: {
      get: function () {
        if (this._mode !== SceneMode$1.MORPHING) {
          const ellipsoid = this._projection.ellipsoid;

          const oldTransform = Matrix4.clone(this._transform, scratchHPRMatrix1);
          const transform = Transforms.eastNorthUpToFixedFrame(
            this.positionWC,
            ellipsoid,
            scratchHPRMatrix2
          );
          this._setTransform(transform);

          const heading = getHeading(this.direction, this.up);

          this._setTransform(oldTransform);

          return heading;
        }

        return undefined;
      },
    },

    /**
     * Gets the camera pitch in radians.
     * @memberof Camera.prototype
     *
     * @type {Number}
     * @readonly
     */
    pitch: {
      get: function () {
        if (this._mode !== SceneMode$1.MORPHING) {
          const ellipsoid = this._projection.ellipsoid;

          const oldTransform = Matrix4.clone(this._transform, scratchHPRMatrix1);
          const transform = Transforms.eastNorthUpToFixedFrame(
            this.positionWC,
            ellipsoid,
            scratchHPRMatrix2
          );
          this._setTransform(transform);

          const pitch = getPitch(this.direction);

          this._setTransform(oldTransform);

          return pitch;
        }

        return undefined;
      },
    },

    /**
     * Gets the camera roll in radians.
     * @memberof Camera.prototype
     *
     * @type {Number}
     * @readonly
     */
    roll: {
      get: function () {
        if (this._mode !== SceneMode$1.MORPHING) {
          const ellipsoid = this._projection.ellipsoid;

          const oldTransform = Matrix4.clone(this._transform, scratchHPRMatrix1);
          const transform = Transforms.eastNorthUpToFixedFrame(
            this.positionWC,
            ellipsoid,
            scratchHPRMatrix2
          );
          this._setTransform(transform);

          const roll = getRoll(this.direction, this.up, this.right);

          this._setTransform(oldTransform);

          return roll;
        }

        return undefined;
      },
    },

    /**
     * Gets the event that will be raised at when the camera starts to move.
     * @memberof Camera.prototype
     * @type {Event}
     * @readonly
     */
    moveStart: {
      get: function () {
        return this._moveStart;
      },
    },

    /**
     * Gets the event that will be raised when the camera has stopped moving.
     * @memberof Camera.prototype
     * @type {Event}
     * @readonly
     */
    moveEnd: {
      get: function () {
        return this._moveEnd;
      },
    },

    /**
     * Gets the event that will be raised when the camera has changed by <code>percentageChanged</code>.
     * @memberof Camera.prototype
     * @type {Event}
     * @readonly
     */
    changed: {
      get: function () {
        return this._changed;
      },
    },
  });

  /**
   * @private
   */
  Camera.prototype.update = function (mode) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(mode)) {
      throw new DeveloperError("mode is required.");
    }
    if (
      mode === SceneMode$1.SCENE2D &&
      !(this.frustum instanceof OrthographicOffCenterFrustum)
    ) {
      throw new DeveloperError(
        "An OrthographicOffCenterFrustum is required in 2D."
      );
    }
    if (
      (mode === SceneMode$1.SCENE3D || mode === SceneMode$1.COLUMBUS_VIEW) &&
      !(this.frustum instanceof PerspectiveFrustum) &&
      !(this.frustum instanceof OrthographicFrustum)
    ) {
      throw new DeveloperError(
        "A PerspectiveFrustum or OrthographicFrustum is required in 3D and Columbus view"
      );
    }
    //>>includeEnd('debug');

    let updateFrustum = false;
    if (mode !== this._mode) {
      this._mode = mode;
      this._modeChanged = mode !== SceneMode$1.MORPHING;
      updateFrustum = this._mode === SceneMode$1.SCENE2D;
    }

    if (updateFrustum) {
      const frustum = (this._max2Dfrustum = this.frustum.clone());

      //>>includeStart('debug', pragmas.debug);
      if (!(frustum instanceof OrthographicOffCenterFrustum)) {
        throw new DeveloperError(
          "The camera frustum is expected to be orthographic for 2D camera control."
        );
      }
      //>>includeEnd('debug');

      const maxZoomOut = 2.0;
      const ratio = frustum.top / frustum.right;
      frustum.right = this._maxCoord.x * maxZoomOut;
      frustum.left = -frustum.right;
      frustum.top = ratio * frustum.right;
      frustum.bottom = -frustum.top;
    }

    if (this._mode === SceneMode$1.SCENE2D) {
      clampMove2D(this, this.position);
    }
  };

  const setTransformPosition = new Cartesian3();
  const setTransformUp = new Cartesian3();
  const setTransformDirection = new Cartesian3();

  Camera.prototype._setTransform = function (transform) {
    const position = Cartesian3.clone(this.positionWC, setTransformPosition);
    const up = Cartesian3.clone(this.upWC, setTransformUp);
    const direction = Cartesian3.clone(this.directionWC, setTransformDirection);

    Matrix4.clone(transform, this._transform);
    this._transformChanged = true;
    updateMembers(this);
    const inverse = this._actualInvTransform;

    Matrix4.multiplyByPoint(inverse, position, this.position);
    Matrix4.multiplyByPointAsVector(inverse, direction, this.direction);
    Matrix4.multiplyByPointAsVector(inverse, up, this.up);
    Cartesian3.cross(this.direction, this.up, this.right);

    updateMembers(this);
  };

  const scratchAdjustOrthographicFrustumMousePosition = new Cartesian2();
  const scratchPickRay$1 = new Ray();
  const scratchRayIntersection$1 = new Cartesian3();
  const scratchDepthIntersection$1 = new Cartesian3();

  function calculateOrthographicFrustumWidth(camera) {
    // Camera is fixed to an object, so keep frustum width constant.
    if (!Matrix4.equals(Matrix4.IDENTITY, camera.transform)) {
      return Cartesian3.magnitude(camera.position);
    }

    const scene = camera._scene;
    const globe = scene.globe;

    const mousePosition = scratchAdjustOrthographicFrustumMousePosition;
    mousePosition.x = scene.drawingBufferWidth / 2.0;
    mousePosition.y = scene.drawingBufferHeight / 2.0;

    let rayIntersection;
    if (defined(globe)) {
      const ray = camera.getPickRay(mousePosition, scratchPickRay$1);
      rayIntersection = globe.pickWorldCoordinates(
        ray,
        scene,
        true,
        scratchRayIntersection$1
      );
    }

    let depthIntersection;
    if (scene.pickPositionSupported) {
      depthIntersection = scene.pickPositionWorldCoordinates(
        mousePosition,
        scratchDepthIntersection$1
      );
    }

    let distance;
    if (defined(rayIntersection) || defined(depthIntersection)) {
      const depthDistance = defined(depthIntersection)
        ? Cartesian3.distance(depthIntersection, camera.positionWC)
        : Number.POSITIVE_INFINITY;
      const rayDistance = defined(rayIntersection)
        ? Cartesian3.distance(rayIntersection, camera.positionWC)
        : Number.POSITIVE_INFINITY;
      distance = Math.min(depthDistance, rayDistance);
    } else {
      distance = Math.max(camera.positionCartographic.height, 0.0);
    }
    return distance;
  }

  Camera.prototype._adjustOrthographicFrustum = function (zooming) {
    if (!(this.frustum instanceof OrthographicFrustum)) {
      return;
    }

    if (!zooming && this._positionCartographic.height < 150000.0) {
      return;
    }

    this.frustum.width = calculateOrthographicFrustumWidth(this);
  };

  const scratchSetViewCartesian = new Cartesian3();
  const scratchSetViewTransform1 = new Matrix4();
  const scratchSetViewTransform2 = new Matrix4();
  const scratchSetViewQuaternion = new Quaternion();
  const scratchSetViewMatrix3 = new Matrix3();
  const scratchSetViewCartographic = new Cartographic();

  function setView3D(camera, position, hpr) {
    const currentTransform = Matrix4.clone(
      camera.transform,
      scratchSetViewTransform1
    );
    const localTransform = Transforms.eastNorthUpToFixedFrame(
      position,
      camera._projection.ellipsoid,
      scratchSetViewTransform2
    );
    camera._setTransform(localTransform);

    Cartesian3.clone(Cartesian3.ZERO, camera.position);
    hpr.heading = hpr.heading - CesiumMath.PI_OVER_TWO;

    const rotQuat = Quaternion.fromHeadingPitchRoll(
      hpr,
      scratchSetViewQuaternion
    );
    const rotMat = Matrix3.fromQuaternion(rotQuat, scratchSetViewMatrix3);

    Matrix3.getColumn(rotMat, 0, camera.direction);
    Matrix3.getColumn(rotMat, 2, camera.up);
    Cartesian3.cross(camera.direction, camera.up, camera.right);

    camera._setTransform(currentTransform);

    camera._adjustOrthographicFrustum(true);
  }

  function setViewCV(camera, position, hpr, convert) {
    const currentTransform = Matrix4.clone(
      camera.transform,
      scratchSetViewTransform1
    );
    camera._setTransform(Matrix4.IDENTITY);

    if (!Cartesian3.equals(position, camera.positionWC)) {
      if (convert) {
        const projection = camera._projection;
        const cartographic = projection.ellipsoid.cartesianToCartographic(
          position,
          scratchSetViewCartographic
        );
        position = projection.project(cartographic, scratchSetViewCartesian);
      }
      Cartesian3.clone(position, camera.position);
    }
    hpr.heading = hpr.heading - CesiumMath.PI_OVER_TWO;

    const rotQuat = Quaternion.fromHeadingPitchRoll(
      hpr,
      scratchSetViewQuaternion
    );
    const rotMat = Matrix3.fromQuaternion(rotQuat, scratchSetViewMatrix3);

    Matrix3.getColumn(rotMat, 0, camera.direction);
    Matrix3.getColumn(rotMat, 2, camera.up);
    Cartesian3.cross(camera.direction, camera.up, camera.right);

    camera._setTransform(currentTransform);

    camera._adjustOrthographicFrustum(true);
  }

  function setView2D(camera, position, hpr, convert) {
    const currentTransform = Matrix4.clone(
      camera.transform,
      scratchSetViewTransform1
    );
    camera._setTransform(Matrix4.IDENTITY);

    if (!Cartesian3.equals(position, camera.positionWC)) {
      if (convert) {
        const projection = camera._projection;
        const cartographic = projection.ellipsoid.cartesianToCartographic(
          position,
          scratchSetViewCartographic
        );
        position = projection.project(cartographic, scratchSetViewCartesian);
      }

      Cartesian2.clone(position, camera.position);

      const newLeft = -position.z * 0.5;
      const newRight = -newLeft;

      const frustum = camera.frustum;
      if (newRight > newLeft) {
        const ratio = frustum.top / frustum.right;
        frustum.right = newRight;
        frustum.left = newLeft;
        frustum.top = frustum.right * ratio;
        frustum.bottom = -frustum.top;
      }
    }

    if (camera._scene.mapMode2D === MapMode2D$1.ROTATE) {
      hpr.heading = hpr.heading - CesiumMath.PI_OVER_TWO;
      hpr.pitch = -CesiumMath.PI_OVER_TWO;
      hpr.roll = 0.0;
      const rotQuat = Quaternion.fromHeadingPitchRoll(
        hpr,
        scratchSetViewQuaternion
      );
      const rotMat = Matrix3.fromQuaternion(rotQuat, scratchSetViewMatrix3);

      Matrix3.getColumn(rotMat, 2, camera.up);
      Cartesian3.cross(camera.direction, camera.up, camera.right);
    }

    camera._setTransform(currentTransform);
  }

  const scratchToHPRDirection = new Cartesian3();
  const scratchToHPRUp = new Cartesian3();
  const scratchToHPRRight = new Cartesian3();

  function directionUpToHeadingPitchRoll(camera, position, orientation, result) {
    const direction = Cartesian3.clone(
      orientation.direction,
      scratchToHPRDirection
    );
    const up = Cartesian3.clone(orientation.up, scratchToHPRUp);

    if (camera._scene.mode === SceneMode$1.SCENE3D) {
      const ellipsoid = camera._projection.ellipsoid;
      const transform = Transforms.eastNorthUpToFixedFrame(
        position,
        ellipsoid,
        scratchHPRMatrix1
      );
      const invTransform = Matrix4.inverseTransformation(
        transform,
        scratchHPRMatrix2
      );

      Matrix4.multiplyByPointAsVector(invTransform, direction, direction);
      Matrix4.multiplyByPointAsVector(invTransform, up, up);
    }

    const right = Cartesian3.cross(direction, up, scratchToHPRRight);

    result.heading = getHeading(direction, up);
    result.pitch = getPitch(direction);
    result.roll = getRoll(direction, up, right);

    return result;
  }

  const scratchSetViewOptions = {
    destination: undefined,
    orientation: {
      direction: undefined,
      up: undefined,
      heading: undefined,
      pitch: undefined,
      roll: undefined,
    },
    convert: undefined,
    endTransform: undefined,
  };

  const scratchHpr = new HeadingPitchRoll();
  /**
   * Sets the camera position, orientation and transform.
   *
   * @param {Object} options Object with the following properties:
   * @param {Cartesian3|Rectangle} [options.destination] The final position of the camera in WGS84 (world) coordinates or a rectangle that would be visible from a top-down view.
   * @param {HeadingPitchRollValues|DirectionUp} [options.orientation] An object that contains either direction and up properties or heading, pitch and roll properties. By default, the direction will point
   * towards the center of the frame in 3D and in the negative z direction in Columbus view. The up direction will point towards local north in 3D and in the positive
   * y direction in Columbus view. Orientation is not used in 2D when in infinite scrolling mode.
   * @param {Matrix4} [options.endTransform] Transform matrix representing the reference frame of the camera.
   * @param {Boolean} [options.convert] Whether to convert the destination from world coordinates to scene coordinates (only relevant when not using 3D). Defaults to <code>true</code>.
   *
   * @example
   * // 1. Set position with a top-down view
   * viewer.camera.setView({
   *     destination : Cesium.Cartesian3.fromDegrees(-117.16, 32.71, 15000.0)
   * });
   *
   * // 2 Set view with heading, pitch and roll
   * viewer.camera.setView({
   *     destination : cartesianPosition,
   *     orientation: {
   *         heading : Cesium.Math.toRadians(90.0), // east, default value is 0.0 (north)
   *         pitch : Cesium.Math.toRadians(-90),    // default value (looking down)
   *         roll : 0.0                             // default value
   *     }
   * });
   *
   * // 3. Change heading, pitch and roll with the camera position remaining the same.
   * viewer.camera.setView({
   *     orientation: {
   *         heading : Cesium.Math.toRadians(90.0), // east, default value is 0.0 (north)
   *         pitch : Cesium.Math.toRadians(-90),    // default value (looking down)
   *         roll : 0.0                             // default value
   *     }
   * });
   *
   *
   * // 4. View rectangle with a top-down view
   * viewer.camera.setView({
   *     destination : Cesium.Rectangle.fromDegrees(west, south, east, north)
   * });
   *
   * // 5. Set position with an orientation using unit vectors.
   * viewer.camera.setView({
   *     destination : Cesium.Cartesian3.fromDegrees(-122.19, 46.25, 5000.0),
   *     orientation : {
   *         direction : new Cesium.Cartesian3(-0.04231243104240401, -0.20123236049443421, -0.97862924300734),
   *         up : new Cesium.Cartesian3(-0.47934589305293746, -0.8553216253114552, 0.1966022179118339)
   *     }
   * });
   */
  Camera.prototype.setView = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    let orientation = defaultValue(
      options.orientation,
      defaultValue.EMPTY_OBJECT
    );

    const mode = this._mode;
    if (mode === SceneMode$1.MORPHING) {
      return;
    }

    if (defined(options.endTransform)) {
      this._setTransform(options.endTransform);
    }

    let convert = defaultValue(options.convert, true);
    let destination = defaultValue(
      options.destination,
      Cartesian3.clone(this.positionWC, scratchSetViewCartesian)
    );
    if (defined(destination) && defined(destination.west)) {
      destination = this.getRectangleCameraCoordinates(
        destination,
        scratchSetViewCartesian
      );
      convert = false;
    }

    if (defined(orientation.direction)) {
      orientation = directionUpToHeadingPitchRoll(
        this,
        destination,
        orientation,
        scratchSetViewOptions.orientation
      );
    }

    scratchHpr.heading = defaultValue(orientation.heading, 0.0);
    scratchHpr.pitch = defaultValue(orientation.pitch, -CesiumMath.PI_OVER_TWO);
    scratchHpr.roll = defaultValue(orientation.roll, 0.0);

    if (mode === SceneMode$1.SCENE3D) {
      setView3D(this, destination, scratchHpr);
    } else if (mode === SceneMode$1.SCENE2D) {
      setView2D(this, destination, scratchHpr, convert);
    } else {
      setViewCV(this, destination, scratchHpr, convert);
    }
  };

  const pitchScratch = new Cartesian3();
  /**
   * Fly the camera to the home view.  Use {@link Camera#.DEFAULT_VIEW_RECTANGLE} to set
   * the default view for the 3D scene.  The home view for 2D and columbus view shows the
   * entire map.
   *
   * @param {Number} [duration] The duration of the flight in seconds. If omitted, Cesium attempts to calculate an ideal duration based on the distance to be traveled by the flight. See {@link Camera#flyTo}
   */
  Camera.prototype.flyHome = function (duration) {
    const mode = this._mode;

    if (mode === SceneMode$1.MORPHING) {
      this._scene.completeMorph();
    }

    if (mode === SceneMode$1.SCENE2D) {
      this.flyTo({
        destination: Camera.DEFAULT_VIEW_RECTANGLE,
        duration: duration,
        endTransform: Matrix4.IDENTITY,
      });
    } else if (mode === SceneMode$1.SCENE3D) {
      const destination = this.getRectangleCameraCoordinates(
        Camera.DEFAULT_VIEW_RECTANGLE
      );

      let mag = Cartesian3.magnitude(destination);
      mag += mag * Camera.DEFAULT_VIEW_FACTOR;
      Cartesian3.normalize(destination, destination);
      Cartesian3.multiplyByScalar(destination, mag, destination);

      this.flyTo({
        destination: destination,
        duration: duration,
        endTransform: Matrix4.IDENTITY,
      });
    } else if (mode === SceneMode$1.COLUMBUS_VIEW) {
      const maxRadii = this._projection.ellipsoid.maximumRadius;
      let position = new Cartesian3(0.0, -1.0, 1.0);
      position = Cartesian3.multiplyByScalar(
        Cartesian3.normalize(position, position),
        5.0 * maxRadii,
        position
      );
      this.flyTo({
        destination: position,
        duration: duration,
        orientation: {
          heading: 0.0,
          pitch: -Math.acos(Cartesian3.normalize(position, pitchScratch).z),
          roll: 0.0,
        },
        endTransform: Matrix4.IDENTITY,
        convert: false,
      });
    }
  };

  /**
   * Transform a vector or point from world coordinates to the camera's reference frame.
   *
   * @param {Cartesian4} cartesian The vector or point to transform.
   * @param {Cartesian4} [result] The object onto which to store the result.
   * @returns {Cartesian4} The transformed vector or point.
   */
  Camera.prototype.worldToCameraCoordinates = function (cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(cartesian)) {
      throw new DeveloperError("cartesian is required.");
    }
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Cartesian4();
    }
    updateMembers(this);
    return Matrix4.multiplyByVector(this._actualInvTransform, cartesian, result);
  };

  /**
   * Transform a point from world coordinates to the camera's reference frame.
   *
   * @param {Cartesian3} cartesian The point to transform.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} The transformed point.
   */
  Camera.prototype.worldToCameraCoordinatesPoint = function (cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(cartesian)) {
      throw new DeveloperError("cartesian is required.");
    }
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Cartesian3();
    }
    updateMembers(this);
    return Matrix4.multiplyByPoint(this._actualInvTransform, cartesian, result);
  };

  /**
   * Transform a vector from world coordinates to the camera's reference frame.
   *
   * @param {Cartesian3} cartesian The vector to transform.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} The transformed vector.
   */
  Camera.prototype.worldToCameraCoordinatesVector = function (cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(cartesian)) {
      throw new DeveloperError("cartesian is required.");
    }
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Cartesian3();
    }
    updateMembers(this);
    return Matrix4.multiplyByPointAsVector(
      this._actualInvTransform,
      cartesian,
      result
    );
  };

  /**
   * Transform a vector or point from the camera's reference frame to world coordinates.
   *
   * @param {Cartesian4} cartesian The vector or point to transform.
   * @param {Cartesian4} [result] The object onto which to store the result.
   * @returns {Cartesian4} The transformed vector or point.
   */
  Camera.prototype.cameraToWorldCoordinates = function (cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(cartesian)) {
      throw new DeveloperError("cartesian is required.");
    }
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Cartesian4();
    }
    updateMembers(this);
    return Matrix4.multiplyByVector(this._actualTransform, cartesian, result);
  };

  /**
   * Transform a point from the camera's reference frame to world coordinates.
   *
   * @param {Cartesian3} cartesian The point to transform.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} The transformed point.
   */
  Camera.prototype.cameraToWorldCoordinatesPoint = function (cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(cartesian)) {
      throw new DeveloperError("cartesian is required.");
    }
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Cartesian3();
    }
    updateMembers(this);
    return Matrix4.multiplyByPoint(this._actualTransform, cartesian, result);
  };

  /**
   * Transform a vector from the camera's reference frame to world coordinates.
   *
   * @param {Cartesian3} cartesian The vector to transform.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} The transformed vector.
   */
  Camera.prototype.cameraToWorldCoordinatesVector = function (cartesian, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(cartesian)) {
      throw new DeveloperError("cartesian is required.");
    }
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Cartesian3();
    }
    updateMembers(this);
    return Matrix4.multiplyByPointAsVector(
      this._actualTransform,
      cartesian,
      result
    );
  };

  function clampMove2D(camera, position) {
    const rotatable2D = camera._scene.mapMode2D === MapMode2D$1.ROTATE;
    const maxProjectedX = camera._maxCoord.x;
    const maxProjectedY = camera._maxCoord.y;

    let minX;
    let maxX;
    if (rotatable2D) {
      maxX = maxProjectedX;
      minX = -maxX;
    } else {
      maxX = position.x - maxProjectedX * 2.0;
      minX = position.x + maxProjectedX * 2.0;
    }

    if (position.x > maxProjectedX) {
      position.x = maxX;
    }
    if (position.x < -maxProjectedX) {
      position.x = minX;
    }

    if (position.y > maxProjectedY) {
      position.y = maxProjectedY;
    }
    if (position.y < -maxProjectedY) {
      position.y = -maxProjectedY;
    }
  }

  const moveScratch = new Cartesian3();
  /**
   * Translates the camera's position by <code>amount</code> along <code>direction</code>.
   *
   * @param {Cartesian3} direction The direction to move.
   * @param {Number} [amount] The amount, in meters, to move. Defaults to <code>defaultMoveAmount</code>.
   *
   * @see Camera#moveBackward
   * @see Camera#moveForward
   * @see Camera#moveLeft
   * @see Camera#moveRight
   * @see Camera#moveUp
   * @see Camera#moveDown
   */
  Camera.prototype.move = function (direction, amount) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(direction)) {
      throw new DeveloperError("direction is required.");
    }
    //>>includeEnd('debug');

    const cameraPosition = this.position;
    Cartesian3.multiplyByScalar(direction, amount, moveScratch);
    Cartesian3.add(cameraPosition, moveScratch, cameraPosition);

    if (this._mode === SceneMode$1.SCENE2D) {
      clampMove2D(this, cameraPosition);
    }
    this._adjustOrthographicFrustum(true);
  };

  /**
   * Translates the camera's position by <code>amount</code> along the camera's view vector.
   * When in 2D mode, this will zoom in the camera instead of translating the camera's position.
   *
   * @param {Number} [amount] The amount, in meters, to move. Defaults to <code>defaultMoveAmount</code>.
   *
   * @see Camera#moveBackward
   */
  Camera.prototype.moveForward = function (amount) {
    amount = defaultValue(amount, this.defaultMoveAmount);

    if (this._mode === SceneMode$1.SCENE2D) {
      // 2D mode
      zoom2D$1(this, amount);
    } else {
      // 3D or Columbus view mode
      this.move(this.direction, amount);
    }
  };

  /**
   * Translates the camera's position by <code>amount</code> along the opposite direction
   * of the camera's view vector.
   * When in 2D mode, this will zoom out the camera instead of translating the camera's position.
   *
   * @param {Number} [amount] The amount, in meters, to move. Defaults to <code>defaultMoveAmount</code>.
   *
   * @see Camera#moveForward
   */
  Camera.prototype.moveBackward = function (amount) {
    amount = defaultValue(amount, this.defaultMoveAmount);

    if (this._mode === SceneMode$1.SCENE2D) {
      // 2D mode
      zoom2D$1(this, -amount);
    } else {
      // 3D or Columbus view mode
      this.move(this.direction, -amount);
    }
  };

  /**
   * Translates the camera's position by <code>amount</code> along the camera's up vector.
   *
   * @param {Number} [amount] The amount, in meters, to move. Defaults to <code>defaultMoveAmount</code>.
   *
   * @see Camera#moveDown
   */
  Camera.prototype.moveUp = function (amount) {
    amount = defaultValue(amount, this.defaultMoveAmount);
    this.move(this.up, amount);
  };

  /**
   * Translates the camera's position by <code>amount</code> along the opposite direction
   * of the camera's up vector.
   *
   * @param {Number} [amount] The amount, in meters, to move. Defaults to <code>defaultMoveAmount</code>.
   *
   * @see Camera#moveUp
   */
  Camera.prototype.moveDown = function (amount) {
    amount = defaultValue(amount, this.defaultMoveAmount);
    this.move(this.up, -amount);
  };

  /**
   * Translates the camera's position by <code>amount</code> along the camera's right vector.
   *
   * @param {Number} [amount] The amount, in meters, to move. Defaults to <code>defaultMoveAmount</code>.
   *
   * @see Camera#moveLeft
   */
  Camera.prototype.moveRight = function (amount) {
    amount = defaultValue(amount, this.defaultMoveAmount);
    this.move(this.right, amount);
  };

  /**
   * Translates the camera's position by <code>amount</code> along the opposite direction
   * of the camera's right vector.
   *
   * @param {Number} [amount] The amount, in meters, to move. Defaults to <code>defaultMoveAmount</code>.
   *
   * @see Camera#moveRight
   */
  Camera.prototype.moveLeft = function (amount) {
    amount = defaultValue(amount, this.defaultMoveAmount);
    this.move(this.right, -amount);
  };

  /**
   * Rotates the camera around its up vector by amount, in radians, in the opposite direction
   * of its right vector if not in 2D mode.
   *
   * @param {Number} [amount] The amount, in radians, to rotate by. Defaults to <code>defaultLookAmount</code>.
   *
   * @see Camera#lookRight
   */
  Camera.prototype.lookLeft = function (amount) {
    amount = defaultValue(amount, this.defaultLookAmount);

    // only want view of map to change in 3D mode, 2D visual is incorrect when look changes
    if (this._mode !== SceneMode$1.SCENE2D) {
      this.look(this.up, -amount);
    }
  };

  /**
   * Rotates the camera around its up vector by amount, in radians, in the direction
   * of its right vector if not in 2D mode.
   *
   * @param {Number} [amount] The amount, in radians, to rotate by. Defaults to <code>defaultLookAmount</code>.
   *
   * @see Camera#lookLeft
   */
  Camera.prototype.lookRight = function (amount) {
    amount = defaultValue(amount, this.defaultLookAmount);

    // only want view of map to change in 3D mode, 2D visual is incorrect when look changes
    if (this._mode !== SceneMode$1.SCENE2D) {
      this.look(this.up, amount);
    }
  };

  /**
   * Rotates the camera around its right vector by amount, in radians, in the direction
   * of its up vector if not in 2D mode.
   *
   * @param {Number} [amount] The amount, in radians, to rotate by. Defaults to <code>defaultLookAmount</code>.
   *
   * @see Camera#lookDown
   */
  Camera.prototype.lookUp = function (amount) {
    amount = defaultValue(amount, this.defaultLookAmount);

    // only want view of map to change in 3D mode, 2D visual is incorrect when look changes
    if (this._mode !== SceneMode$1.SCENE2D) {
      this.look(this.right, -amount);
    }
  };

  /**
   * Rotates the camera around its right vector by amount, in radians, in the opposite direction
   * of its up vector if not in 2D mode.
   *
   * @param {Number} [amount] The amount, in radians, to rotate by. Defaults to <code>defaultLookAmount</code>.
   *
   * @see Camera#lookUp
   */
  Camera.prototype.lookDown = function (amount) {
    amount = defaultValue(amount, this.defaultLookAmount);

    // only want view of map to change in 3D mode, 2D visual is incorrect when look changes
    if (this._mode !== SceneMode$1.SCENE2D) {
      this.look(this.right, amount);
    }
  };

  const lookScratchQuaternion = new Quaternion();
  const lookScratchMatrix = new Matrix3();
  /**
   * Rotate each of the camera's orientation vectors around <code>axis</code> by <code>angle</code>
   *
   * @param {Cartesian3} axis The axis to rotate around.
   * @param {Number} [angle] The angle, in radians, to rotate by. Defaults to <code>defaultLookAmount</code>.
   *
   * @see Camera#lookUp
   * @see Camera#lookDown
   * @see Camera#lookLeft
   * @see Camera#lookRight
   */
  Camera.prototype.look = function (axis, angle) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(axis)) {
      throw new DeveloperError("axis is required.");
    }
    //>>includeEnd('debug');

    const turnAngle = defaultValue(angle, this.defaultLookAmount);
    const quaternion = Quaternion.fromAxisAngle(
      axis,
      -turnAngle,
      lookScratchQuaternion
    );
    const rotation = Matrix3.fromQuaternion(quaternion, lookScratchMatrix);

    const direction = this.direction;
    const up = this.up;
    const right = this.right;

    Matrix3.multiplyByVector(rotation, direction, direction);
    Matrix3.multiplyByVector(rotation, up, up);
    Matrix3.multiplyByVector(rotation, right, right);
  };

  /**
   * Rotate the camera counter-clockwise around its direction vector by amount, in radians.
   *
   * @param {Number} [amount] The amount, in radians, to rotate by. Defaults to <code>defaultLookAmount</code>.
   *
   * @see Camera#twistRight
   */
  Camera.prototype.twistLeft = function (amount) {
    amount = defaultValue(amount, this.defaultLookAmount);
    this.look(this.direction, amount);
  };

  /**
   * Rotate the camera clockwise around its direction vector by amount, in radians.
   *
   * @param {Number} [amount] The amount, in radians, to rotate by. Defaults to <code>defaultLookAmount</code>.
   *
   * @see Camera#twistLeft
   */
  Camera.prototype.twistRight = function (amount) {
    amount = defaultValue(amount, this.defaultLookAmount);
    this.look(this.direction, -amount);
  };

  const rotateScratchQuaternion = new Quaternion();
  const rotateScratchMatrix = new Matrix3();
  /**
   * Rotates the camera around <code>axis</code> by <code>angle</code>. The distance
   * of the camera's position to the center of the camera's reference frame remains the same.
   *
   * @param {Cartesian3} axis The axis to rotate around given in world coordinates.
   * @param {Number} [angle] The angle, in radians, to rotate by. Defaults to <code>defaultRotateAmount</code>.
   *
   * @see Camera#rotateUp
   * @see Camera#rotateDown
   * @see Camera#rotateLeft
   * @see Camera#rotateRight
   */
  Camera.prototype.rotate = function (axis, angle) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(axis)) {
      throw new DeveloperError("axis is required.");
    }
    //>>includeEnd('debug');

    const turnAngle = defaultValue(angle, this.defaultRotateAmount);
    const quaternion = Quaternion.fromAxisAngle(
      axis,
      -turnAngle,
      rotateScratchQuaternion
    );
    const rotation = Matrix3.fromQuaternion(quaternion, rotateScratchMatrix);
    Matrix3.multiplyByVector(rotation, this.position, this.position);
    Matrix3.multiplyByVector(rotation, this.direction, this.direction);
    Matrix3.multiplyByVector(rotation, this.up, this.up);
    Cartesian3.cross(this.direction, this.up, this.right);
    Cartesian3.cross(this.right, this.direction, this.up);

    this._adjustOrthographicFrustum(false);
  };

  /**
   * Rotates the camera around the center of the camera's reference frame by angle downwards.
   *
   * @param {Number} [angle] The angle, in radians, to rotate by. Defaults to <code>defaultRotateAmount</code>.
   *
   * @see Camera#rotateUp
   * @see Camera#rotate
   */
  Camera.prototype.rotateDown = function (angle) {
    angle = defaultValue(angle, this.defaultRotateAmount);
    rotateVertical(this, angle);
  };

  /**
   * Rotates the camera around the center of the camera's reference frame by angle upwards.
   *
   * @param {Number} [angle] The angle, in radians, to rotate by. Defaults to <code>defaultRotateAmount</code>.
   *
   * @see Camera#rotateDown
   * @see Camera#rotate
   */
  Camera.prototype.rotateUp = function (angle) {
    angle = defaultValue(angle, this.defaultRotateAmount);
    rotateVertical(this, -angle);
  };

  const rotateVertScratchP = new Cartesian3();
  const rotateVertScratchA = new Cartesian3();
  const rotateVertScratchTan = new Cartesian3();
  const rotateVertScratchNegate = new Cartesian3();
  function rotateVertical(camera, angle) {
    const position = camera.position;
    if (
      defined(camera.constrainedAxis) &&
      !Cartesian3.equalsEpsilon(
        camera.position,
        Cartesian3.ZERO,
        CesiumMath.EPSILON2
      )
    ) {
      const p = Cartesian3.normalize(position, rotateVertScratchP);
      const northParallel = Cartesian3.equalsEpsilon(
        p,
        camera.constrainedAxis,
        CesiumMath.EPSILON2
      );
      const southParallel = Cartesian3.equalsEpsilon(
        p,
        Cartesian3.negate(camera.constrainedAxis, rotateVertScratchNegate),
        CesiumMath.EPSILON2
      );
      if (!northParallel && !southParallel) {
        const constrainedAxis = Cartesian3.normalize(
          camera.constrainedAxis,
          rotateVertScratchA
        );

        let dot = Cartesian3.dot(p, constrainedAxis);
        let angleToAxis = CesiumMath.acosClamped(dot);
        if (angle > 0 && angle > angleToAxis) {
          angle = angleToAxis - CesiumMath.EPSILON4;
        }

        dot = Cartesian3.dot(
          p,
          Cartesian3.negate(constrainedAxis, rotateVertScratchNegate)
        );
        angleToAxis = CesiumMath.acosClamped(dot);
        if (angle < 0 && -angle > angleToAxis) {
          angle = -angleToAxis + CesiumMath.EPSILON4;
        }

        const tangent = Cartesian3.cross(
          constrainedAxis,
          p,
          rotateVertScratchTan
        );
        camera.rotate(tangent, angle);
      } else if ((northParallel && angle < 0) || (southParallel && angle > 0)) {
        camera.rotate(camera.right, angle);
      }
    } else {
      camera.rotate(camera.right, angle);
    }
  }

  /**
   * Rotates the camera around the center of the camera's reference frame by angle to the right.
   *
   * @param {Number} [angle] The angle, in radians, to rotate by. Defaults to <code>defaultRotateAmount</code>.
   *
   * @see Camera#rotateLeft
   * @see Camera#rotate
   */
  Camera.prototype.rotateRight = function (angle) {
    angle = defaultValue(angle, this.defaultRotateAmount);
    rotateHorizontal(this, -angle);
  };

  /**
   * Rotates the camera around the center of the camera's reference frame by angle to the left.
   *
   * @param {Number} [angle] The angle, in radians, to rotate by. Defaults to <code>defaultRotateAmount</code>.
   *
   * @see Camera#rotateRight
   * @see Camera#rotate
   */
  Camera.prototype.rotateLeft = function (angle) {
    angle = defaultValue(angle, this.defaultRotateAmount);
    rotateHorizontal(this, angle);
  };

  function rotateHorizontal(camera, angle) {
    if (defined(camera.constrainedAxis)) {
      camera.rotate(camera.constrainedAxis, angle);
    } else {
      camera.rotate(camera.up, angle);
    }
  }

  function zoom2D$1(camera, amount) {
    const frustum = camera.frustum;

    //>>includeStart('debug', pragmas.debug);
    if (
      !(frustum instanceof OrthographicOffCenterFrustum) ||
      !defined(frustum.left) ||
      !defined(frustum.right) ||
      !defined(frustum.bottom) ||
      !defined(frustum.top)
    ) {
      throw new DeveloperError(
        "The camera frustum is expected to be orthographic for 2D camera control."
      );
    }
    //>>includeEnd('debug');

    let ratio;
    amount = amount * 0.5;

    if (
      Math.abs(frustum.top) + Math.abs(frustum.bottom) >
      Math.abs(frustum.left) + Math.abs(frustum.right)
    ) {
      let newTop = frustum.top - amount;
      let newBottom = frustum.bottom + amount;

      let maxBottom = camera._maxCoord.y;
      if (camera._scene.mapMode2D === MapMode2D$1.ROTATE) {
        maxBottom *= camera.maximumZoomFactor;
      }

      if (newBottom > maxBottom) {
        newBottom = maxBottom;
        newTop = -maxBottom;
      }

      if (newTop <= newBottom) {
        newTop = 1.0;
        newBottom = -1.0;
      }

      ratio = frustum.right / frustum.top;
      frustum.top = newTop;
      frustum.bottom = newBottom;
      frustum.right = frustum.top * ratio;
      frustum.left = -frustum.right;
    } else {
      let newRight = frustum.right - amount;
      let newLeft = frustum.left + amount;

      let maxRight = camera._maxCoord.x;
      if (camera._scene.mapMode2D === MapMode2D$1.ROTATE) {
        maxRight *= camera.maximumZoomFactor;
      }

      if (newRight > maxRight) {
        newRight = maxRight;
        newLeft = -maxRight;
      }

      if (newRight <= newLeft) {
        newRight = 1.0;
        newLeft = -1.0;
      }
      ratio = frustum.top / frustum.right;
      frustum.right = newRight;
      frustum.left = newLeft;
      frustum.top = frustum.right * ratio;
      frustum.bottom = -frustum.top;
    }
  }

  function zoom3D$1(camera, amount) {
    camera.move(camera.direction, amount);
  }

  /**
   * Zooms <code>amount</code> along the camera's view vector.
   *
   * @param {Number} [amount] The amount to move. Defaults to <code>defaultZoomAmount</code>.
   *
   * @see Camera#zoomOut
   */
  Camera.prototype.zoomIn = function (amount) {
    amount = defaultValue(amount, this.defaultZoomAmount);
    if (this._mode === SceneMode$1.SCENE2D) {
      zoom2D$1(this, amount);
    } else {
      zoom3D$1(this, amount);
    }
  };

  /**
   * Zooms <code>amount</code> along the opposite direction of
   * the camera's view vector.
   *
   * @param {Number} [amount] The amount to move. Defaults to <code>defaultZoomAmount</code>.
   *
   * @see Camera#zoomIn
   */
  Camera.prototype.zoomOut = function (amount) {
    amount = defaultValue(amount, this.defaultZoomAmount);
    if (this._mode === SceneMode$1.SCENE2D) {
      zoom2D$1(this, -amount);
    } else {
      zoom3D$1(this, -amount);
    }
  };

  /**
   * Gets the magnitude of the camera position. In 3D, this is the vector magnitude. In 2D and
   * Columbus view, this is the distance to the map.
   *
   * @returns {Number} The magnitude of the position.
   */
  Camera.prototype.getMagnitude = function () {
    if (this._mode === SceneMode$1.SCENE3D) {
      return Cartesian3.magnitude(this.position);
    } else if (this._mode === SceneMode$1.COLUMBUS_VIEW) {
      return Math.abs(this.position.z);
    } else if (this._mode === SceneMode$1.SCENE2D) {
      return Math.max(
        this.frustum.right - this.frustum.left,
        this.frustum.top - this.frustum.bottom
      );
    }
  };

  const scratchLookAtMatrix4 = new Matrix4();

  /**
   * Sets the camera position and orientation using a target and offset. The target must be given in
   * world coordinates. The offset can be either a cartesian or heading/pitch/range in the local east-north-up reference frame centered at the target.
   * If the offset is a cartesian, then it is an offset from the center of the reference frame defined by the transformation matrix. If the offset
   * is heading/pitch/range, then the heading and the pitch angles are defined in the reference frame defined by the transformation matrix.
   * The heading is the angle from y axis and increasing towards the x axis. Pitch is the rotation from the xy-plane. Positive pitch
   * angles are below the plane. Negative pitch angles are above the plane. The range is the distance from the center.
   *
   * In 2D, there must be a top down view. The camera will be placed above the target looking down. The height above the
   * target will be the magnitude of the offset. The heading will be determined from the offset. If the heading cannot be
   * determined from the offset, the heading will be north.
   *
   * @param {Cartesian3} target The target position in world coordinates.
   * @param {Cartesian3|HeadingPitchRange} offset The offset from the target in the local east-north-up reference frame centered at the target.
   *
   * @exception {DeveloperError} lookAt is not supported while morphing.
   *
   * @example
   * // 1. Using a cartesian offset
   * const center = Cesium.Cartesian3.fromDegrees(-98.0, 40.0);
   * viewer.camera.lookAt(center, new Cesium.Cartesian3(0.0, -4790000.0, 3930000.0));
   *
   * // 2. Using a HeadingPitchRange offset
   * const center = Cesium.Cartesian3.fromDegrees(-72.0, 40.0);
   * const heading = Cesium.Math.toRadians(50.0);
   * const pitch = Cesium.Math.toRadians(-20.0);
   * const range = 5000.0;
   * viewer.camera.lookAt(center, new Cesium.HeadingPitchRange(heading, pitch, range));
   */
  Camera.prototype.lookAt = function (target, offset) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(target)) {
      throw new DeveloperError("target is required");
    }
    if (!defined(offset)) {
      throw new DeveloperError("offset is required");
    }
    if (this._mode === SceneMode$1.MORPHING) {
      throw new DeveloperError("lookAt is not supported while morphing.");
    }
    //>>includeEnd('debug');

    const transform = Transforms.eastNorthUpToFixedFrame(
      target,
      Ellipsoid.WGS84,
      scratchLookAtMatrix4
    );
    this.lookAtTransform(transform, offset);
  };

  const scratchLookAtHeadingPitchRangeOffset = new Cartesian3();
  const scratchLookAtHeadingPitchRangeQuaternion1 = new Quaternion();
  const scratchLookAtHeadingPitchRangeQuaternion2 = new Quaternion();
  const scratchHeadingPitchRangeMatrix3 = new Matrix3();

  function offsetFromHeadingPitchRange(heading, pitch, range) {
    pitch = CesiumMath.clamp(
      pitch,
      -CesiumMath.PI_OVER_TWO,
      CesiumMath.PI_OVER_TWO
    );
    heading = CesiumMath.zeroToTwoPi(heading) - CesiumMath.PI_OVER_TWO;

    const pitchQuat = Quaternion.fromAxisAngle(
      Cartesian3.UNIT_Y,
      -pitch,
      scratchLookAtHeadingPitchRangeQuaternion1
    );
    const headingQuat = Quaternion.fromAxisAngle(
      Cartesian3.UNIT_Z,
      -heading,
      scratchLookAtHeadingPitchRangeQuaternion2
    );
    const rotQuat = Quaternion.multiply(headingQuat, pitchQuat, headingQuat);
    const rotMatrix = Matrix3.fromQuaternion(
      rotQuat,
      scratchHeadingPitchRangeMatrix3
    );

    const offset = Cartesian3.clone(
      Cartesian3.UNIT_X,
      scratchLookAtHeadingPitchRangeOffset
    );
    Matrix3.multiplyByVector(rotMatrix, offset, offset);
    Cartesian3.negate(offset, offset);
    Cartesian3.multiplyByScalar(offset, range, offset);
    return offset;
  }

  /**
   * Sets the camera position and orientation using a target and transformation matrix. The offset can be either a cartesian or heading/pitch/range.
   * If the offset is a cartesian, then it is an offset from the center of the reference frame defined by the transformation matrix. If the offset
   * is heading/pitch/range, then the heading and the pitch angles are defined in the reference frame defined by the transformation matrix.
   * The heading is the angle from y axis and increasing towards the x axis. Pitch is the rotation from the xy-plane. Positive pitch
   * angles are below the plane. Negative pitch angles are above the plane. The range is the distance from the center.
   *
   * In 2D, there must be a top down view. The camera will be placed above the center of the reference frame. The height above the
   * target will be the magnitude of the offset. The heading will be determined from the offset. If the heading cannot be
   * determined from the offset, the heading will be north.
   *
   * @param {Matrix4} transform The transformation matrix defining the reference frame.
   * @param {Cartesian3|HeadingPitchRange} [offset] The offset from the target in a reference frame centered at the target.
   *
   * @exception {DeveloperError} lookAtTransform is not supported while morphing.
   *
   * @example
   * // 1. Using a cartesian offset
   * const transform = Cesium.Transforms.eastNorthUpToFixedFrame(Cesium.Cartesian3.fromDegrees(-98.0, 40.0));
   * viewer.camera.lookAtTransform(transform, new Cesium.Cartesian3(0.0, -4790000.0, 3930000.0));
   *
   * // 2. Using a HeadingPitchRange offset
   * const transform = Cesium.Transforms.eastNorthUpToFixedFrame(Cesium.Cartesian3.fromDegrees(-72.0, 40.0));
   * const heading = Cesium.Math.toRadians(50.0);
   * const pitch = Cesium.Math.toRadians(-20.0);
   * const range = 5000.0;
   * viewer.camera.lookAtTransform(transform, new Cesium.HeadingPitchRange(heading, pitch, range));
   */
  Camera.prototype.lookAtTransform = function (transform, offset) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(transform)) {
      throw new DeveloperError("transform is required");
    }
    if (this._mode === SceneMode$1.MORPHING) {
      throw new DeveloperError(
        "lookAtTransform is not supported while morphing."
      );
    }
    //>>includeEnd('debug');

    this._setTransform(transform);
    if (!defined(offset)) {
      return;
    }

    let cartesianOffset;
    if (defined(offset.heading)) {
      cartesianOffset = offsetFromHeadingPitchRange(
        offset.heading,
        offset.pitch,
        offset.range
      );
    } else {
      cartesianOffset = offset;
    }

    if (this._mode === SceneMode$1.SCENE2D) {
      Cartesian2.clone(Cartesian2.ZERO, this.position);

      Cartesian3.negate(cartesianOffset, this.up);
      this.up.z = 0.0;

      if (Cartesian3.magnitudeSquared(this.up) < CesiumMath.EPSILON10) {
        Cartesian3.clone(Cartesian3.UNIT_Y, this.up);
      }

      Cartesian3.normalize(this.up, this.up);

      this._setTransform(Matrix4.IDENTITY);

      Cartesian3.negate(Cartesian3.UNIT_Z, this.direction);
      Cartesian3.cross(this.direction, this.up, this.right);
      Cartesian3.normalize(this.right, this.right);

      const frustum = this.frustum;
      const ratio = frustum.top / frustum.right;
      frustum.right = Cartesian3.magnitude(cartesianOffset) * 0.5;
      frustum.left = -frustum.right;
      frustum.top = ratio * frustum.right;
      frustum.bottom = -frustum.top;

      this._setTransform(transform);

      return;
    }

    Cartesian3.clone(cartesianOffset, this.position);
    Cartesian3.negate(this.position, this.direction);
    Cartesian3.normalize(this.direction, this.direction);
    Cartesian3.cross(this.direction, Cartesian3.UNIT_Z, this.right);

    if (Cartesian3.magnitudeSquared(this.right) < CesiumMath.EPSILON10) {
      Cartesian3.clone(Cartesian3.UNIT_X, this.right);
    }

    Cartesian3.normalize(this.right, this.right);
    Cartesian3.cross(this.right, this.direction, this.up);
    Cartesian3.normalize(this.up, this.up);

    this._adjustOrthographicFrustum(true);
  };

  const viewRectangle3DCartographic1 = new Cartographic();
  const viewRectangle3DCartographic2 = new Cartographic();
  const viewRectangle3DNorthEast = new Cartesian3();
  const viewRectangle3DSouthWest = new Cartesian3();
  const viewRectangle3DNorthWest = new Cartesian3();
  const viewRectangle3DSouthEast = new Cartesian3();
  const viewRectangle3DNorthCenter = new Cartesian3();
  const viewRectangle3DSouthCenter = new Cartesian3();
  const viewRectangle3DCenter = new Cartesian3();
  const viewRectangle3DEquator = new Cartesian3();
  const defaultRF = {
    direction: new Cartesian3(),
    right: new Cartesian3(),
    up: new Cartesian3(),
  };
  let viewRectangle3DEllipsoidGeodesic;

  function computeD(direction, upOrRight, corner, tanThetaOrPhi) {
    const opposite = Math.abs(Cartesian3.dot(upOrRight, corner));
    return opposite / tanThetaOrPhi - Cartesian3.dot(direction, corner);
  }

  function rectangleCameraPosition3D(camera, rectangle, result, updateCamera) {
    const ellipsoid = camera._projection.ellipsoid;
    const cameraRF = updateCamera ? camera : defaultRF;

    const north = rectangle.north;
    const south = rectangle.south;
    let east = rectangle.east;
    const west = rectangle.west;

    // If we go across the International Date Line
    if (west > east) {
      east += CesiumMath.TWO_PI;
    }

    // Find the midpoint latitude.
    //
    // EllipsoidGeodesic will fail if the north and south edges are very close to being on opposite sides of the ellipsoid.
    // Ideally we'd just call EllipsoidGeodesic.setEndPoints and let it throw when it detects this case, but sadly it doesn't
    // even look for this case in optimized builds, so we have to test for it here instead.
    //
    // Fortunately, this case can only happen (here) when north is very close to the north pole and south is very close to the south pole,
    // so handle it just by using 0 latitude as the center.  It's certainliy possible to use a smaller tolerance
    // than one degree here, but one degree is safe and putting the center at 0 latitude should be good enough for any
    // rectangle that spans 178+ of the 180 degrees of latitude.
    const longitude = (west + east) * 0.5;
    let latitude;
    if (
      south < -CesiumMath.PI_OVER_TWO + CesiumMath.RADIANS_PER_DEGREE &&
      north > CesiumMath.PI_OVER_TWO - CesiumMath.RADIANS_PER_DEGREE
    ) {
      latitude = 0.0;
    } else {
      const northCartographic = viewRectangle3DCartographic1;
      northCartographic.longitude = longitude;
      northCartographic.latitude = north;
      northCartographic.height = 0.0;

      const southCartographic = viewRectangle3DCartographic2;
      southCartographic.longitude = longitude;
      southCartographic.latitude = south;
      southCartographic.height = 0.0;

      let ellipsoidGeodesic = viewRectangle3DEllipsoidGeodesic;
      if (
        !defined(ellipsoidGeodesic) ||
        ellipsoidGeodesic.ellipsoid !== ellipsoid
      ) {
        viewRectangle3DEllipsoidGeodesic = ellipsoidGeodesic = new EllipsoidGeodesic(
          undefined,
          undefined,
          ellipsoid
        );
      }

      ellipsoidGeodesic.setEndPoints(northCartographic, southCartographic);
      latitude = ellipsoidGeodesic.interpolateUsingFraction(
        0.5,
        viewRectangle3DCartographic1
      ).latitude;
    }

    const centerCartographic = viewRectangle3DCartographic1;
    centerCartographic.longitude = longitude;
    centerCartographic.latitude = latitude;
    centerCartographic.height = 0.0;

    const center = ellipsoid.cartographicToCartesian(
      centerCartographic,
      viewRectangle3DCenter
    );

    const cart = viewRectangle3DCartographic1;
    cart.longitude = east;
    cart.latitude = north;
    const northEast = ellipsoid.cartographicToCartesian(
      cart,
      viewRectangle3DNorthEast
    );
    cart.longitude = west;
    const northWest = ellipsoid.cartographicToCartesian(
      cart,
      viewRectangle3DNorthWest
    );
    cart.longitude = longitude;
    const northCenter = ellipsoid.cartographicToCartesian(
      cart,
      viewRectangle3DNorthCenter
    );
    cart.latitude = south;
    const southCenter = ellipsoid.cartographicToCartesian(
      cart,
      viewRectangle3DSouthCenter
    );
    cart.longitude = east;
    const southEast = ellipsoid.cartographicToCartesian(
      cart,
      viewRectangle3DSouthEast
    );
    cart.longitude = west;
    const southWest = ellipsoid.cartographicToCartesian(
      cart,
      viewRectangle3DSouthWest
    );

    Cartesian3.subtract(northWest, center, northWest);
    Cartesian3.subtract(southEast, center, southEast);
    Cartesian3.subtract(northEast, center, northEast);
    Cartesian3.subtract(southWest, center, southWest);
    Cartesian3.subtract(northCenter, center, northCenter);
    Cartesian3.subtract(southCenter, center, southCenter);

    const direction = ellipsoid.geodeticSurfaceNormal(center, cameraRF.direction);
    Cartesian3.negate(direction, direction);
    const right = Cartesian3.cross(direction, Cartesian3.UNIT_Z, cameraRF.right);
    Cartesian3.normalize(right, right);
    const up = Cartesian3.cross(right, direction, cameraRF.up);

    let d;
    if (camera.frustum instanceof OrthographicFrustum) {
      const width = Math.max(
        Cartesian3.distance(northEast, northWest),
        Cartesian3.distance(southEast, southWest)
      );
      const height = Math.max(
        Cartesian3.distance(northEast, southEast),
        Cartesian3.distance(northWest, southWest)
      );

      let rightScalar;
      let topScalar;
      const ratio =
        camera.frustum._offCenterFrustum.right /
        camera.frustum._offCenterFrustum.top;
      const heightRatio = height * ratio;
      if (width > heightRatio) {
        rightScalar = width;
        topScalar = rightScalar / ratio;
      } else {
        topScalar = height;
        rightScalar = heightRatio;
      }

      d = Math.max(rightScalar, topScalar);
    } else {
      const tanPhi = Math.tan(camera.frustum.fovy * 0.5);
      const tanTheta = camera.frustum.aspectRatio * tanPhi;

      d = Math.max(
        computeD(direction, up, northWest, tanPhi),
        computeD(direction, up, southEast, tanPhi),
        computeD(direction, up, northEast, tanPhi),
        computeD(direction, up, southWest, tanPhi),
        computeD(direction, up, northCenter, tanPhi),
        computeD(direction, up, southCenter, tanPhi),
        computeD(direction, right, northWest, tanTheta),
        computeD(direction, right, southEast, tanTheta),
        computeD(direction, right, northEast, tanTheta),
        computeD(direction, right, southWest, tanTheta),
        computeD(direction, right, northCenter, tanTheta),
        computeD(direction, right, southCenter, tanTheta)
      );

      // If the rectangle crosses the equator, compute D at the equator, too, because that's the
      // widest part of the rectangle when projected onto the globe.
      if (south < 0 && north > 0) {
        const equatorCartographic = viewRectangle3DCartographic1;
        equatorCartographic.longitude = west;
        equatorCartographic.latitude = 0.0;
        equatorCartographic.height = 0.0;
        let equatorPosition = ellipsoid.cartographicToCartesian(
          equatorCartographic,
          viewRectangle3DEquator
        );
        Cartesian3.subtract(equatorPosition, center, equatorPosition);
        d = Math.max(
          d,
          computeD(direction, up, equatorPosition, tanPhi),
          computeD(direction, right, equatorPosition, tanTheta)
        );

        equatorCartographic.longitude = east;
        equatorPosition = ellipsoid.cartographicToCartesian(
          equatorCartographic,
          viewRectangle3DEquator
        );
        Cartesian3.subtract(equatorPosition, center, equatorPosition);
        d = Math.max(
          d,
          computeD(direction, up, equatorPosition, tanPhi),
          computeD(direction, right, equatorPosition, tanTheta)
        );
      }
    }

    return Cartesian3.add(
      center,
      Cartesian3.multiplyByScalar(direction, -d, viewRectangle3DEquator),
      result
    );
  }

  const viewRectangleCVCartographic = new Cartographic();
  const viewRectangleCVNorthEast = new Cartesian3();
  const viewRectangleCVSouthWest = new Cartesian3();
  function rectangleCameraPositionColumbusView(camera, rectangle, result) {
    const projection = camera._projection;
    if (rectangle.west > rectangle.east) {
      rectangle = Rectangle.MAX_VALUE;
    }
    const transform = camera._actualTransform;
    const invTransform = camera._actualInvTransform;

    const cart = viewRectangleCVCartographic;
    cart.longitude = rectangle.east;
    cart.latitude = rectangle.north;
    const northEast = projection.project(cart, viewRectangleCVNorthEast);
    Matrix4.multiplyByPoint(transform, northEast, northEast);
    Matrix4.multiplyByPoint(invTransform, northEast, northEast);

    cart.longitude = rectangle.west;
    cart.latitude = rectangle.south;
    const southWest = projection.project(cart, viewRectangleCVSouthWest);
    Matrix4.multiplyByPoint(transform, southWest, southWest);
    Matrix4.multiplyByPoint(invTransform, southWest, southWest);

    result.x = (northEast.x - southWest.x) * 0.5 + southWest.x;
    result.y = (northEast.y - southWest.y) * 0.5 + southWest.y;

    if (defined(camera.frustum.fovy)) {
      const tanPhi = Math.tan(camera.frustum.fovy * 0.5);
      const tanTheta = camera.frustum.aspectRatio * tanPhi;
      result.z =
        Math.max(
          (northEast.x - southWest.x) / tanTheta,
          (northEast.y - southWest.y) / tanPhi
        ) * 0.5;
    } else {
      const width = northEast.x - southWest.x;
      const height = northEast.y - southWest.y;
      result.z = Math.max(width, height);
    }

    return result;
  }

  const viewRectangle2DCartographic = new Cartographic();
  const viewRectangle2DNorthEast = new Cartesian3();
  const viewRectangle2DSouthWest = new Cartesian3();
  function rectangleCameraPosition2D(camera, rectangle, result) {
    const projection = camera._projection;

    // Account for the rectangle crossing the International Date Line in 2D mode
    let east = rectangle.east;
    if (rectangle.west > rectangle.east) {
      if (camera._scene.mapMode2D === MapMode2D$1.INFINITE_SCROLL) {
        east += CesiumMath.TWO_PI;
      } else {
        rectangle = Rectangle.MAX_VALUE;
        east = rectangle.east;
      }
    }

    let cart = viewRectangle2DCartographic;
    cart.longitude = east;
    cart.latitude = rectangle.north;
    const northEast = projection.project(cart, viewRectangle2DNorthEast);
    cart.longitude = rectangle.west;
    cart.latitude = rectangle.south;
    const southWest = projection.project(cart, viewRectangle2DSouthWest);

    const width = Math.abs(northEast.x - southWest.x) * 0.5;
    let height = Math.abs(northEast.y - southWest.y) * 0.5;

    let right, top;
    const ratio = camera.frustum.right / camera.frustum.top;
    const heightRatio = height * ratio;
    if (width > heightRatio) {
      right = width;
      top = right / ratio;
    } else {
      top = height;
      right = heightRatio;
    }

    height = Math.max(2.0 * right, 2.0 * top);

    result.x = (northEast.x - southWest.x) * 0.5 + southWest.x;
    result.y = (northEast.y - southWest.y) * 0.5 + southWest.y;

    cart = projection.unproject(result, cart);
    cart.height = height;
    result = projection.project(cart, result);

    return result;
  }

  /**
   * Get the camera position needed to view a rectangle on an ellipsoid or map
   *
   * @param {Rectangle} rectangle The rectangle to view.
   * @param {Cartesian3} [result] The camera position needed to view the rectangle
   * @returns {Cartesian3} The camera position needed to view the rectangle
   */
  Camera.prototype.getRectangleCameraCoordinates = function (rectangle, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(rectangle)) {
      throw new DeveloperError("rectangle is required");
    }
    //>>includeEnd('debug');
    const mode = this._mode;

    if (!defined(result)) {
      result = new Cartesian3();
    }

    if (mode === SceneMode$1.SCENE3D) {
      return rectangleCameraPosition3D(this, rectangle, result);
    } else if (mode === SceneMode$1.COLUMBUS_VIEW) {
      return rectangleCameraPositionColumbusView(this, rectangle, result);
    } else if (mode === SceneMode$1.SCENE2D) {
      return rectangleCameraPosition2D(this, rectangle, result);
    }

    return undefined;
  };

  const pickEllipsoid3DRay = new Ray();
  function pickEllipsoid3D(camera, windowPosition, ellipsoid, result) {
    ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
    const ray = camera.getPickRay(windowPosition, pickEllipsoid3DRay);
    const intersection = IntersectionTests.rayEllipsoid(ray, ellipsoid);
    if (!intersection) {
      return undefined;
    }

    const t = intersection.start > 0.0 ? intersection.start : intersection.stop;
    return Ray.getPoint(ray, t, result);
  }

  const pickEllipsoid2DRay = new Ray();
  function pickMap2D(camera, windowPosition, projection, result) {
    const ray = camera.getPickRay(windowPosition, pickEllipsoid2DRay);
    let position = ray.origin;
    position = Cartesian3.fromElements(position.y, position.z, 0.0, position);
    const cart = projection.unproject(position);

    if (
      cart.latitude < -CesiumMath.PI_OVER_TWO ||
      cart.latitude > CesiumMath.PI_OVER_TWO
    ) {
      return undefined;
    }

    return projection.ellipsoid.cartographicToCartesian(cart, result);
  }

  const pickEllipsoidCVRay = new Ray();
  function pickMapColumbusView(camera, windowPosition, projection, result) {
    const ray = camera.getPickRay(windowPosition, pickEllipsoidCVRay);
    const scalar = -ray.origin.x / ray.direction.x;
    Ray.getPoint(ray, scalar, result);

    const cart = projection.unproject(new Cartesian3(result.y, result.z, 0.0));

    if (
      cart.latitude < -CesiumMath.PI_OVER_TWO ||
      cart.latitude > CesiumMath.PI_OVER_TWO ||
      cart.longitude < -Math.PI ||
      cart.longitude > Math.PI
    ) {
      return undefined;
    }

    return projection.ellipsoid.cartographicToCartesian(cart, result);
  }

  /**
   * Pick an ellipsoid or map.
   *
   * @param {Cartesian2} windowPosition The x and y coordinates of a pixel.
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid to pick.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3 | undefined} If the ellipsoid or map was picked,
   * returns the point on the surface of the ellipsoid or map in world
   * coordinates. If the ellipsoid or map was not picked, returns undefined.
   *
   * @example
   * const canvas = viewer.scene.canvas;
   * const center = new Cesium.Cartesian2(canvas.clientWidth / 2.0, canvas.clientHeight / 2.0);
   * const ellipsoid = viewer.scene.globe.ellipsoid;
   * const result = viewer.camera.pickEllipsoid(center, ellipsoid);
   */
  Camera.prototype.pickEllipsoid = function (windowPosition, ellipsoid, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(windowPosition)) {
      throw new DeveloperError("windowPosition is required.");
    }
    //>>includeEnd('debug');

    const canvas = this._scene.canvas;
    if (canvas.clientWidth === 0 || canvas.clientHeight === 0) {
      return undefined;
    }

    if (!defined(result)) {
      result = new Cartesian3();
    }

    ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);

    if (this._mode === SceneMode$1.SCENE3D) {
      result = pickEllipsoid3D(this, windowPosition, ellipsoid, result);
    } else if (this._mode === SceneMode$1.SCENE2D) {
      result = pickMap2D(this, windowPosition, this._projection, result);
    } else if (this._mode === SceneMode$1.COLUMBUS_VIEW) {
      result = pickMapColumbusView(
        this,
        windowPosition,
        this._projection,
        result
      );
    } else {
      return undefined;
    }

    return result;
  };

  const pickPerspCenter = new Cartesian3();
  const pickPerspXDir = new Cartesian3();
  const pickPerspYDir = new Cartesian3();
  function getPickRayPerspective(camera, windowPosition, result) {
    const canvas = camera._scene.canvas;
    const width = canvas.clientWidth;
    const height = canvas.clientHeight;

    const tanPhi = Math.tan(camera.frustum.fovy * 0.5);
    const tanTheta = camera.frustum.aspectRatio * tanPhi;
    const near = camera.frustum.near;

    const x = (2.0 / width) * windowPosition.x - 1.0;
    const y = (2.0 / height) * (height - windowPosition.y) - 1.0;

    const position = camera.positionWC;
    Cartesian3.clone(position, result.origin);

    const nearCenter = Cartesian3.multiplyByScalar(
      camera.directionWC,
      near,
      pickPerspCenter
    );
    Cartesian3.add(position, nearCenter, nearCenter);
    const xDir = Cartesian3.multiplyByScalar(
      camera.rightWC,
      x * near * tanTheta,
      pickPerspXDir
    );
    const yDir = Cartesian3.multiplyByScalar(
      camera.upWC,
      y * near * tanPhi,
      pickPerspYDir
    );
    const direction = Cartesian3.add(nearCenter, xDir, result.direction);
    Cartesian3.add(direction, yDir, direction);
    Cartesian3.subtract(direction, position, direction);
    Cartesian3.normalize(direction, direction);

    return result;
  }

  const scratchDirection = new Cartesian3();

  function getPickRayOrthographic(camera, windowPosition, result) {
    const canvas = camera._scene.canvas;
    const width = canvas.clientWidth;
    const height = canvas.clientHeight;

    let frustum = camera.frustum;
    if (defined(frustum._offCenterFrustum)) {
      frustum = frustum._offCenterFrustum;
    }
    let x = (2.0 / width) * windowPosition.x - 1.0;
    x *= (frustum.right - frustum.left) * 0.5;
    let y = (2.0 / height) * (height - windowPosition.y) - 1.0;
    y *= (frustum.top - frustum.bottom) * 0.5;

    const origin = result.origin;
    Cartesian3.clone(camera.position, origin);

    Cartesian3.multiplyByScalar(camera.right, x, scratchDirection);
    Cartesian3.add(scratchDirection, origin, origin);
    Cartesian3.multiplyByScalar(camera.up, y, scratchDirection);
    Cartesian3.add(scratchDirection, origin, origin);

    Cartesian3.clone(camera.directionWC, result.direction);

    if (
      camera._mode === SceneMode$1.COLUMBUS_VIEW ||
      camera._mode === SceneMode$1.SCENE2D
    ) {
      Cartesian3.fromElements(
        result.origin.z,
        result.origin.x,
        result.origin.y,
        result.origin
      );
    }

    return result;
  }

  /**
   * Create a ray from the camera position through the pixel at <code>windowPosition</code>
   * in world coordinates.
   *
   * @param {Cartesian2} windowPosition The x and y coordinates of a pixel.
   * @param {Ray} [result] The object onto which to store the result.
   * @returns {Ray|undefined} Returns the {@link Cartesian3} position and direction of the ray, or undefined if the pick ray cannot be determined.
   */
  Camera.prototype.getPickRay = function (windowPosition, result) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(windowPosition)) {
      throw new DeveloperError("windowPosition is required.");
    }
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Ray();
    }

    const canvas = this._scene.canvas;
    if (canvas.clientWidth <= 0 || canvas.clientHeight <= 0) {
      return undefined;
    }

    const frustum = this.frustum;
    if (
      defined(frustum.aspectRatio) &&
      defined(frustum.fov) &&
      defined(frustum.near)
    ) {
      return getPickRayPerspective(this, windowPosition, result);
    }

    return getPickRayOrthographic(this, windowPosition, result);
  };

  const scratchToCenter = new Cartesian3();
  const scratchProj = new Cartesian3();

  /**
   * Return the distance from the camera to the front of the bounding sphere.
   *
   * @param {BoundingSphere} boundingSphere The bounding sphere in world coordinates.
   * @returns {Number} The distance to the bounding sphere.
   */
  Camera.prototype.distanceToBoundingSphere = function (boundingSphere) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(boundingSphere)) {
      throw new DeveloperError("boundingSphere is required.");
    }
    //>>includeEnd('debug');

    const toCenter = Cartesian3.subtract(
      this.positionWC,
      boundingSphere.center,
      scratchToCenter
    );
    const proj = Cartesian3.multiplyByScalar(
      this.directionWC,
      Cartesian3.dot(toCenter, this.directionWC),
      scratchProj
    );
    return Math.max(0.0, Cartesian3.magnitude(proj) - boundingSphere.radius);
  };

  const scratchPixelSize = new Cartesian2();

  /**
   * Return the pixel size in meters.
   *
   * @param {BoundingSphere} boundingSphere The bounding sphere in world coordinates.
   * @param {Number} drawingBufferWidth The drawing buffer width.
   * @param {Number} drawingBufferHeight The drawing buffer height.
   * @returns {Number} The pixel size in meters.
   */
  Camera.prototype.getPixelSize = function (
    boundingSphere,
    drawingBufferWidth,
    drawingBufferHeight
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(boundingSphere)) {
      throw new DeveloperError("boundingSphere is required.");
    }
    if (!defined(drawingBufferWidth)) {
      throw new DeveloperError("drawingBufferWidth is required.");
    }
    if (!defined(drawingBufferHeight)) {
      throw new DeveloperError("drawingBufferHeight is required.");
    }
    //>>includeEnd('debug');

    const distance = this.distanceToBoundingSphere(boundingSphere);
    const pixelSize = this.frustum.getPixelDimensions(
      drawingBufferWidth,
      drawingBufferHeight,
      distance,
      this._scene.pixelRatio,
      scratchPixelSize
    );
    return Math.max(pixelSize.x, pixelSize.y);
  };

  function createAnimationTemplateCV(
    camera,
    position,
    center,
    maxX,
    maxY,
    duration
  ) {
    const newPosition = Cartesian3.clone(position);

    if (center.y > maxX) {
      newPosition.y -= center.y - maxX;
    } else if (center.y < -maxX) {
      newPosition.y += -maxX - center.y;
    }

    if (center.z > maxY) {
      newPosition.z -= center.z - maxY;
    } else if (center.z < -maxY) {
      newPosition.z += -maxY - center.z;
    }

    function updateCV(value) {
      const interp = Cartesian3.lerp(
        position,
        newPosition,
        value.time,
        new Cartesian3()
      );
      camera.worldToCameraCoordinatesPoint(interp, camera.position);
    }
    return {
      easingFunction: EasingFunction$1.EXPONENTIAL_OUT,
      startObject: {
        time: 0.0,
      },
      stopObject: {
        time: 1.0,
      },
      duration: duration,
      update: updateCV,
    };
  }

  const normalScratch$1 = new Cartesian3();
  const centerScratch$1 = new Cartesian3();
  const posScratch = new Cartesian3();
  const scratchCartesian3Subtract = new Cartesian3();

  function createAnimationCV(camera, duration) {
    let position = camera.position;
    const direction = camera.direction;

    const normal = camera.worldToCameraCoordinatesVector(
      Cartesian3.UNIT_X,
      normalScratch$1
    );
    const scalar =
      -Cartesian3.dot(normal, position) / Cartesian3.dot(normal, direction);
    const center = Cartesian3.add(
      position,
      Cartesian3.multiplyByScalar(direction, scalar, centerScratch$1),
      centerScratch$1
    );
    camera.cameraToWorldCoordinatesPoint(center, center);

    position = camera.cameraToWorldCoordinatesPoint(camera.position, posScratch);

    const tanPhi = Math.tan(camera.frustum.fovy * 0.5);
    const tanTheta = camera.frustum.aspectRatio * tanPhi;
    const distToC = Cartesian3.magnitude(
      Cartesian3.subtract(position, center, scratchCartesian3Subtract)
    );
    const dWidth = tanTheta * distToC;
    const dHeight = tanPhi * distToC;

    const mapWidth = camera._maxCoord.x;
    const mapHeight = camera._maxCoord.y;

    const maxX = Math.max(dWidth - mapWidth, mapWidth);
    const maxY = Math.max(dHeight - mapHeight, mapHeight);

    if (
      position.z < -maxX ||
      position.z > maxX ||
      position.y < -maxY ||
      position.y > maxY
    ) {
      const translateX = center.y < -maxX || center.y > maxX;
      const translateY = center.z < -maxY || center.z > maxY;
      if (translateX || translateY) {
        return createAnimationTemplateCV(
          camera,
          position,
          center,
          maxX,
          maxY,
          duration
        );
      }
    }

    return undefined;
  }

  /**
   * Create an animation to move the map into view. This method is only valid for 2D and Columbus modes.
   *
   * @param {Number} duration The duration, in seconds, of the animation.
   * @returns {Object} The animation or undefined if the scene mode is 3D or the map is already ion view.
   *
   * @private
   */
  Camera.prototype.createCorrectPositionTween = function (duration) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(duration)) {
      throw new DeveloperError("duration is required.");
    }
    //>>includeEnd('debug');

    if (this._mode === SceneMode$1.COLUMBUS_VIEW) {
      return createAnimationCV(this, duration);
    }

    return undefined;
  };

  const scratchFlyToDestination = new Cartesian3();
  const newOptions = {
    destination: undefined,
    heading: undefined,
    pitch: undefined,
    roll: undefined,
    duration: undefined,
    complete: undefined,
    cancel: undefined,
    endTransform: undefined,
    maximumHeight: undefined,
    easingFunction: undefined,
  };

  /**
   * Cancels the current camera flight and leaves the camera at its current location.
   * If no flight is in progress, this this function does nothing.
   */
  Camera.prototype.cancelFlight = function () {
    if (defined(this._currentFlight)) {
      this._currentFlight.cancelTween();
      this._currentFlight = undefined;
    }
  };

  /**
   * Completes the current camera flight and moves the camera immediately to its final destination.
   * If no flight is in progress, this this function does nothing.
   */
  Camera.prototype.completeFlight = function () {
    if (defined(this._currentFlight)) {
      this._currentFlight.cancelTween();

      const options = {
        destination: undefined,
        orientation: {
          heading: undefined,
          pitch: undefined,
          roll: undefined,
        },
      };

      options.destination = newOptions.destination;
      options.orientation.heading = newOptions.heading;
      options.orientation.pitch = newOptions.pitch;
      options.orientation.roll = newOptions.roll;

      this.setView(options);

      if (defined(this._currentFlight.complete)) {
        this._currentFlight.complete();
      }

      this._currentFlight = undefined;
    }
  };

  /**
   * Flies the camera from its current position to a new position.
   *
   * @param {Object} options Object with the following properties:
   * @param {Cartesian3|Rectangle} options.destination The final position of the camera in WGS84 (world) coordinates or a rectangle that would be visible from a top-down view.
   * @param {Object} [options.orientation] An object that contains either direction and up properties or heading, pitch and roll properties. By default, the direction will point
   * towards the center of the frame in 3D and in the negative z direction in Columbus view. The up direction will point towards local north in 3D and in the positive
   * y direction in Columbus view.  Orientation is not used in 2D when in infinite scrolling mode.
   * @param {Number} [options.duration] The duration of the flight in seconds. If omitted, Cesium attempts to calculate an ideal duration based on the distance to be traveled by the flight.
   * @param {Camera.FlightCompleteCallback} [options.complete] The function to execute when the flight is complete.
   * @param {Camera.FlightCancelledCallback} [options.cancel] The function to execute if the flight is cancelled.
   * @param {Matrix4} [options.endTransform] Transform matrix representing the reference frame the camera will be in when the flight is completed.
   * @param {Number} [options.maximumHeight] The maximum height at the peak of the flight.
   * @param {Number} [options.pitchAdjustHeight] If camera flyes higher than that value, adjust pitch duiring the flight to look down, and keep Earth in viewport.
   * @param {Number} [options.flyOverLongitude] There are always two ways between 2 points on globe. This option force camera to choose fight direction to fly over that longitude.
   * @param {Number} [options.flyOverLongitudeWeight] Fly over the lon specifyed via flyOverLongitude only if that way is not longer than short way times flyOverLongitudeWeight.
   * @param {Boolean} [options.convert] Whether to convert the destination from world coordinates to scene coordinates (only relevant when not using 3D). Defaults to <code>true</code>.
   * @param {EasingFunction.Callback} [options.easingFunction] Controls how the time is interpolated over the duration of the flight.
   *
   * @exception {DeveloperError} If either direction or up is given, then both are required.
   *
   * @example
   * // 1. Fly to a position with a top-down view
   * viewer.camera.flyTo({
   *     destination : Cesium.Cartesian3.fromDegrees(-117.16, 32.71, 15000.0)
   * });
   *
   * // 2. Fly to a Rectangle with a top-down view
   * viewer.camera.flyTo({
   *     destination : Cesium.Rectangle.fromDegrees(west, south, east, north)
   * });
   *
   * // 3. Fly to a position with an orientation using unit vectors.
   * viewer.camera.flyTo({
   *     destination : Cesium.Cartesian3.fromDegrees(-122.19, 46.25, 5000.0),
   *     orientation : {
   *         direction : new Cesium.Cartesian3(-0.04231243104240401, -0.20123236049443421, -0.97862924300734),
   *         up : new Cesium.Cartesian3(-0.47934589305293746, -0.8553216253114552, 0.1966022179118339)
   *     }
   * });
   *
   * // 4. Fly to a position with an orientation using heading, pitch and roll.
   * viewer.camera.flyTo({
   *     destination : Cesium.Cartesian3.fromDegrees(-122.19, 46.25, 5000.0),
   *     orientation : {
   *         heading : Cesium.Math.toRadians(175.0),
   *         pitch : Cesium.Math.toRadians(-35.0),
   *         roll : 0.0
   *     }
   * });
   */
  Camera.prototype.flyTo = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    let destination = options.destination;
    //>>includeStart('debug', pragmas.debug);
    if (!defined(destination)) {
      throw new DeveloperError("destination is required.");
    }
    //>>includeEnd('debug');

    const mode = this._mode;
    if (mode === SceneMode$1.MORPHING) {
      return;
    }

    this.cancelFlight();

    let orientation = defaultValue(
      options.orientation,
      defaultValue.EMPTY_OBJECT
    );
    if (defined(orientation.direction)) {
      orientation = directionUpToHeadingPitchRoll(
        this,
        destination,
        orientation,
        scratchSetViewOptions.orientation
      );
    }

    if (defined(options.duration) && options.duration <= 0.0) {
      const setViewOptions = scratchSetViewOptions;
      setViewOptions.destination = options.destination;
      setViewOptions.orientation.heading = orientation.heading;
      setViewOptions.orientation.pitch = orientation.pitch;
      setViewOptions.orientation.roll = orientation.roll;
      setViewOptions.convert = options.convert;
      setViewOptions.endTransform = options.endTransform;
      this.setView(setViewOptions);
      if (typeof options.complete === "function") {
        options.complete();
      }
      return;
    }

    const isRectangle = defined(destination.west);
    if (isRectangle) {
      destination = this.getRectangleCameraCoordinates(
        destination,
        scratchFlyToDestination
      );
    }

    const that = this;
    /* eslint-disable-next-line prefer-const */
    let flightTween;

    newOptions.destination = destination;
    newOptions.heading = orientation.heading;
    newOptions.pitch = orientation.pitch;
    newOptions.roll = orientation.roll;
    newOptions.duration = options.duration;
    newOptions.complete = function () {
      if (flightTween === that._currentFlight) {
        that._currentFlight = undefined;
      }
      if (defined(options.complete)) {
        options.complete();
      }
    };
    newOptions.cancel = options.cancel;
    newOptions.endTransform = options.endTransform;
    newOptions.convert = isRectangle ? false : options.convert;
    newOptions.maximumHeight = options.maximumHeight;
    newOptions.pitchAdjustHeight = options.pitchAdjustHeight;
    newOptions.flyOverLongitude = options.flyOverLongitude;
    newOptions.flyOverLongitudeWeight = options.flyOverLongitudeWeight;
    newOptions.easingFunction = options.easingFunction;

    const scene = this._scene;
    const tweenOptions = CameraFlightPath.createTween(scene, newOptions);
    // If the camera doesn't actually need to go anywhere, duration
    // will be 0 and we can just complete the current flight.
    if (tweenOptions.duration === 0) {
      if (typeof tweenOptions.complete === "function") {
        tweenOptions.complete();
      }
      return;
    }
    flightTween = scene.tweens.add(tweenOptions);
    this._currentFlight = flightTween;

    // Save the final destination view information for the PRELOAD_FLIGHT pass.
    let preloadFlightCamera = this._scene.preloadFlightCamera;
    if (this._mode !== SceneMode$1.SCENE2D) {
      if (!defined(preloadFlightCamera)) {
        preloadFlightCamera = Camera.clone(this);
      }
      preloadFlightCamera.setView({
        destination: destination,
        orientation: orientation,
      });

      this._scene.preloadFlightCullingVolume = preloadFlightCamera.frustum.computeCullingVolume(
        preloadFlightCamera.positionWC,
        preloadFlightCamera.directionWC,
        preloadFlightCamera.upWC
      );
    }
  };

  function distanceToBoundingSphere3D(camera, radius) {
    const frustum = camera.frustum;
    const tanPhi = Math.tan(frustum.fovy * 0.5);
    const tanTheta = frustum.aspectRatio * tanPhi;
    return Math.max(radius / tanTheta, radius / tanPhi);
  }

  function distanceToBoundingSphere2D(camera, radius) {
    let frustum = camera.frustum;
    if (defined(frustum._offCenterFrustum)) {
      frustum = frustum._offCenterFrustum;
    }

    let right, top;
    const ratio = frustum.right / frustum.top;
    const heightRatio = radius * ratio;
    if (radius > heightRatio) {
      right = radius;
      top = right / ratio;
    } else {
      top = radius;
      right = heightRatio;
    }

    return Math.max(right, top) * 1.5;
  }

  const MINIMUM_ZOOM = 100.0;

  function adjustBoundingSphereOffset(camera, boundingSphere, offset) {
    offset = HeadingPitchRange.clone(
      defined(offset) ? offset : Camera.DEFAULT_OFFSET
    );

    const minimumZoom =
      camera._scene.screenSpaceCameraController.minimumZoomDistance;
    const maximumZoom =
      camera._scene.screenSpaceCameraController.maximumZoomDistance;
    const range = offset.range;
    if (!defined(range) || range === 0.0) {
      const radius = boundingSphere.radius;
      if (radius === 0.0) {
        offset.range = MINIMUM_ZOOM;
      } else if (
        camera.frustum instanceof OrthographicFrustum ||
        camera._mode === SceneMode$1.SCENE2D
      ) {
        offset.range = distanceToBoundingSphere2D(camera, radius);
      } else {
        offset.range = distanceToBoundingSphere3D(camera, radius);
      }
      offset.range = CesiumMath.clamp(offset.range, minimumZoom, maximumZoom);
    }

    return offset;
  }

  /**
   * Sets the camera so that the current view contains the provided bounding sphere.
   *
   * <p>The offset is heading/pitch/range in the local east-north-up reference frame centered at the center of the bounding sphere.
   * The heading and the pitch angles are defined in the local east-north-up reference frame.
   * The heading is the angle from y axis and increasing towards the x axis. Pitch is the rotation from the xy-plane. Positive pitch
   * angles are below the plane. Negative pitch angles are above the plane. The range is the distance from the center. If the range is
   * zero, a range will be computed such that the whole bounding sphere is visible.</p>
   *
   * <p>In 2D, there must be a top down view. The camera will be placed above the target looking down. The height above the
   * target will be the range. The heading will be determined from the offset. If the heading cannot be
   * determined from the offset, the heading will be north.</p>
   *
   * @param {BoundingSphere} boundingSphere The bounding sphere to view, in world coordinates.
   * @param {HeadingPitchRange} [offset] The offset from the target in the local east-north-up reference frame centered at the target.
   *
   * @exception {DeveloperError} viewBoundingSphere is not supported while morphing.
   */
  Camera.prototype.viewBoundingSphere = function (boundingSphere, offset) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(boundingSphere)) {
      throw new DeveloperError("boundingSphere is required.");
    }

    if (this._mode === SceneMode$1.MORPHING) {
      throw new DeveloperError(
        "viewBoundingSphere is not supported while morphing."
      );
    }
    //>>includeEnd('debug');

    offset = adjustBoundingSphereOffset(this, boundingSphere, offset);
    this.lookAt(boundingSphere.center, offset);
  };

  const scratchflyToBoundingSphereTransform = new Matrix4();
  const scratchflyToBoundingSphereDestination = new Cartesian3();
  const scratchflyToBoundingSphereDirection = new Cartesian3();
  const scratchflyToBoundingSphereUp = new Cartesian3();
  const scratchflyToBoundingSphereRight = new Cartesian3();
  const scratchFlyToBoundingSphereCart4 = new Cartesian4();
  const scratchFlyToBoundingSphereQuaternion = new Quaternion();
  const scratchFlyToBoundingSphereMatrix3 = new Matrix3();

  /**
   * Flies the camera to a location where the current view contains the provided bounding sphere.
   *
   * <p> The offset is heading/pitch/range in the local east-north-up reference frame centered at the center of the bounding sphere.
   * The heading and the pitch angles are defined in the local east-north-up reference frame.
   * The heading is the angle from y axis and increasing towards the x axis. Pitch is the rotation from the xy-plane. Positive pitch
   * angles are below the plane. Negative pitch angles are above the plane. The range is the distance from the center. If the range is
   * zero, a range will be computed such that the whole bounding sphere is visible.</p>
   *
   * <p>In 2D and Columbus View, there must be a top down view. The camera will be placed above the target looking down. The height above the
   * target will be the range. The heading will be aligned to local north.</p>
   *
   * @param {BoundingSphere} boundingSphere The bounding sphere to view, in world coordinates.
   * @param {Object} [options] Object with the following properties:
   * @param {Number} [options.duration] The duration of the flight in seconds. If omitted, Cesium attempts to calculate an ideal duration based on the distance to be traveled by the flight.
   * @param {HeadingPitchRange} [options.offset] The offset from the target in the local east-north-up reference frame centered at the target.
   * @param {Camera.FlightCompleteCallback} [options.complete] The function to execute when the flight is complete.
   * @param {Camera.FlightCancelledCallback} [options.cancel] The function to execute if the flight is cancelled.
   * @param {Matrix4} [options.endTransform] Transform matrix representing the reference frame the camera will be in when the flight is completed.
   * @param {Number} [options.maximumHeight] The maximum height at the peak of the flight.
   * @param {Number} [options.pitchAdjustHeight] If camera flyes higher than that value, adjust pitch duiring the flight to look down, and keep Earth in viewport.
   * @param {Number} [options.flyOverLongitude] There are always two ways between 2 points on globe. This option force camera to choose fight direction to fly over that longitude.
   * @param {Number} [options.flyOverLongitudeWeight] Fly over the lon specifyed via flyOverLongitude only if that way is not longer than short way times flyOverLongitudeWeight.
   * @param {EasingFunction.Callback} [options.easingFunction] Controls how the time is interpolated over the duration of the flight.
   */
  Camera.prototype.flyToBoundingSphere = function (boundingSphere, options) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(boundingSphere)) {
      throw new DeveloperError("boundingSphere is required.");
    }
    //>>includeEnd('debug');

    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const scene2D =
      this._mode === SceneMode$1.SCENE2D || this._mode === SceneMode$1.COLUMBUS_VIEW;
    this._setTransform(Matrix4.IDENTITY);
    const offset = adjustBoundingSphereOffset(
      this,
      boundingSphere,
      options.offset
    );

    let position;
    if (scene2D) {
      position = Cartesian3.multiplyByScalar(
        Cartesian3.UNIT_Z,
        offset.range,
        scratchflyToBoundingSphereDestination
      );
    } else {
      position = offsetFromHeadingPitchRange(
        offset.heading,
        offset.pitch,
        offset.range
      );
    }

    const transform = Transforms.eastNorthUpToFixedFrame(
      boundingSphere.center,
      Ellipsoid.WGS84,
      scratchflyToBoundingSphereTransform
    );
    Matrix4.multiplyByPoint(transform, position, position);

    let direction;
    let up;

    if (!scene2D) {
      direction = Cartesian3.subtract(
        boundingSphere.center,
        position,
        scratchflyToBoundingSphereDirection
      );
      Cartesian3.normalize(direction, direction);

      up = Matrix4.multiplyByPointAsVector(
        transform,
        Cartesian3.UNIT_Z,
        scratchflyToBoundingSphereUp
      );
      if (1.0 - Math.abs(Cartesian3.dot(direction, up)) < CesiumMath.EPSILON6) {
        const rotateQuat = Quaternion.fromAxisAngle(
          direction,
          offset.heading,
          scratchFlyToBoundingSphereQuaternion
        );
        const rotation = Matrix3.fromQuaternion(
          rotateQuat,
          scratchFlyToBoundingSphereMatrix3
        );

        Cartesian3.fromCartesian4(
          Matrix4.getColumn(transform, 1, scratchFlyToBoundingSphereCart4),
          up
        );
        Matrix3.multiplyByVector(rotation, up, up);
      }

      const right = Cartesian3.cross(
        direction,
        up,
        scratchflyToBoundingSphereRight
      );
      Cartesian3.cross(right, direction, up);
      Cartesian3.normalize(up, up);
    }

    this.flyTo({
      destination: position,
      orientation: {
        direction: direction,
        up: up,
      },
      duration: options.duration,
      complete: options.complete,
      cancel: options.cancel,
      endTransform: options.endTransform,
      maximumHeight: options.maximumHeight,
      easingFunction: options.easingFunction,
      flyOverLongitude: options.flyOverLongitude,
      flyOverLongitudeWeight: options.flyOverLongitudeWeight,
      pitchAdjustHeight: options.pitchAdjustHeight,
    });
  };

  const scratchCartesian3_1 = new Cartesian3();
  const scratchCartesian3_2 = new Cartesian3();
  const scratchCartesian3_3 = new Cartesian3();
  const scratchCartesian3_4 = new Cartesian3();
  const horizonPoints = [
    new Cartesian3(),
    new Cartesian3(),
    new Cartesian3(),
    new Cartesian3(),
  ];

  function computeHorizonQuad(camera, ellipsoid) {
    const radii = ellipsoid.radii;
    const p = camera.positionWC;

    // Find the corresponding position in the scaled space of the ellipsoid.
    const q = Cartesian3.multiplyComponents(
      ellipsoid.oneOverRadii,
      p,
      scratchCartesian3_1
    );

    const qMagnitude = Cartesian3.magnitude(q);
    const qUnit = Cartesian3.normalize(q, scratchCartesian3_2);

    // Determine the east and north directions at q.
    let eUnit;
    let nUnit;
    if (
      Cartesian3.equalsEpsilon(qUnit, Cartesian3.UNIT_Z, CesiumMath.EPSILON10)
    ) {
      eUnit = new Cartesian3(0, 1, 0);
      nUnit = new Cartesian3(0, 0, 1);
    } else {
      eUnit = Cartesian3.normalize(
        Cartesian3.cross(Cartesian3.UNIT_Z, qUnit, scratchCartesian3_3),
        scratchCartesian3_3
      );
      nUnit = Cartesian3.normalize(
        Cartesian3.cross(qUnit, eUnit, scratchCartesian3_4),
        scratchCartesian3_4
      );
    }

    // Determine the radius of the 'limb' of the ellipsoid.
    const wMagnitude = Math.sqrt(Cartesian3.magnitudeSquared(q) - 1.0);

    // Compute the center and offsets.
    const center = Cartesian3.multiplyByScalar(
      qUnit,
      1.0 / qMagnitude,
      scratchCartesian3_1
    );
    const scalar = wMagnitude / qMagnitude;
    const eastOffset = Cartesian3.multiplyByScalar(
      eUnit,
      scalar,
      scratchCartesian3_2
    );
    const northOffset = Cartesian3.multiplyByScalar(
      nUnit,
      scalar,
      scratchCartesian3_3
    );

    // A conservative measure for the longitudes would be to use the min/max longitudes of the bounding frustum.
    const upperLeft = Cartesian3.add(center, northOffset, horizonPoints[0]);
    Cartesian3.subtract(upperLeft, eastOffset, upperLeft);
    Cartesian3.multiplyComponents(radii, upperLeft, upperLeft);

    const lowerLeft = Cartesian3.subtract(center, northOffset, horizonPoints[1]);
    Cartesian3.subtract(lowerLeft, eastOffset, lowerLeft);
    Cartesian3.multiplyComponents(radii, lowerLeft, lowerLeft);

    const lowerRight = Cartesian3.subtract(center, northOffset, horizonPoints[2]);
    Cartesian3.add(lowerRight, eastOffset, lowerRight);
    Cartesian3.multiplyComponents(radii, lowerRight, lowerRight);

    const upperRight = Cartesian3.add(center, northOffset, horizonPoints[3]);
    Cartesian3.add(upperRight, eastOffset, upperRight);
    Cartesian3.multiplyComponents(radii, upperRight, upperRight);

    return horizonPoints;
  }

  const scratchPickCartesian2 = new Cartesian2();
  const scratchRectCartesian = new Cartesian3();
  const cartoArray = [
    new Cartographic(),
    new Cartographic(),
    new Cartographic(),
    new Cartographic(),
  ];
  function addToResult(x, y, index, camera, ellipsoid, computedHorizonQuad) {
    scratchPickCartesian2.x = x;
    scratchPickCartesian2.y = y;
    const r = camera.pickEllipsoid(
      scratchPickCartesian2,
      ellipsoid,
      scratchRectCartesian
    );
    if (defined(r)) {
      cartoArray[index] = ellipsoid.cartesianToCartographic(r, cartoArray[index]);
      return 1;
    }
    cartoArray[index] = ellipsoid.cartesianToCartographic(
      computedHorizonQuad[index],
      cartoArray[index]
    );
    return 0;
  }
  /**
   * Computes the approximate visible rectangle on the ellipsoid.
   *
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid that you want to know the visible region.
   * @param {Rectangle} [result] The rectangle in which to store the result
   *
   * @returns {Rectangle|undefined} The visible rectangle or undefined if the ellipsoid isn't visible at all.
   */
  Camera.prototype.computeViewRectangle = function (ellipsoid, result) {
    ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
    const cullingVolume = this.frustum.computeCullingVolume(
      this.positionWC,
      this.directionWC,
      this.upWC
    );
    const boundingSphere = new BoundingSphere(
      Cartesian3.ZERO,
      ellipsoid.maximumRadius
    );
    const visibility = cullingVolume.computeVisibility(boundingSphere);
    if (visibility === Intersect$1.OUTSIDE) {
      return undefined;
    }

    const canvas = this._scene.canvas;
    const width = canvas.clientWidth;
    const height = canvas.clientHeight;

    let successfulPickCount = 0;

    const computedHorizonQuad = computeHorizonQuad(this, ellipsoid);

    successfulPickCount += addToResult(
      0,
      0,
      0,
      this,
      ellipsoid,
      computedHorizonQuad
    );
    successfulPickCount += addToResult(
      0,
      height,
      1,
      this,
      ellipsoid,
      computedHorizonQuad
    );
    successfulPickCount += addToResult(
      width,
      height,
      2,
      this,
      ellipsoid,
      computedHorizonQuad
    );
    successfulPickCount += addToResult(
      width,
      0,
      3,
      this,
      ellipsoid,
      computedHorizonQuad
    );

    if (successfulPickCount < 2) {
      // If we have space non-globe in 3 or 4 corners then return the whole globe
      return Rectangle.MAX_VALUE;
    }

    result = Rectangle.fromCartographicArray(cartoArray, result);

    // Detect if we go over the poles
    let distance = 0;
    let lastLon = cartoArray[3].longitude;
    for (let i = 0; i < 4; ++i) {
      const lon = cartoArray[i].longitude;
      const diff = Math.abs(lon - lastLon);
      if (diff > CesiumMath.PI) {
        // Crossed the dateline
        distance += CesiumMath.TWO_PI - diff;
      } else {
        distance += diff;
      }

      lastLon = lon;
    }

    // We are over one of the poles so adjust the rectangle accordingly
    if (
      CesiumMath.equalsEpsilon(
        Math.abs(distance),
        CesiumMath.TWO_PI,
        CesiumMath.EPSILON9
      )
    ) {
      result.west = -CesiumMath.PI;
      result.east = CesiumMath.PI;
      if (cartoArray[0].latitude >= 0.0) {
        result.north = CesiumMath.PI_OVER_TWO;
      } else {
        result.south = -CesiumMath.PI_OVER_TWO;
      }
    }

    return result;
  };

  /**
   * Switches the frustum/projection to perspective.
   *
   * This function is a no-op in 2D which must always be orthographic.
   */
  Camera.prototype.switchToPerspectiveFrustum = function () {
    if (
      this._mode === SceneMode$1.SCENE2D ||
      this.frustum instanceof PerspectiveFrustum
    ) {
      return;
    }

    const scene = this._scene;
    this.frustum = new PerspectiveFrustum();
    this.frustum.aspectRatio =
      scene.drawingBufferWidth / scene.drawingBufferHeight;
    this.frustum.fov = CesiumMath.toRadians(60.0);
  };

  /**
   * Switches the frustum/projection to orthographic.
   *
   * This function is a no-op in 2D which will always be orthographic.
   */
  Camera.prototype.switchToOrthographicFrustum = function () {
    if (
      this._mode === SceneMode$1.SCENE2D ||
      this.frustum instanceof OrthographicFrustum
    ) {
      return;
    }

    // This must be called before changing the frustum because it uses the previous
    // frustum to reconstruct the world space position from the depth buffer.
    const frustumWidth = calculateOrthographicFrustumWidth(this);

    const scene = this._scene;
    this.frustum = new OrthographicFrustum();
    this.frustum.aspectRatio =
      scene.drawingBufferWidth / scene.drawingBufferHeight;
    this.frustum.width = frustumWidth;
  };

  /**
   * @private
   */
  Camera.clone = function (camera, result) {
    if (!defined(result)) {
      result = new Camera(camera._scene);
    }

    Cartesian3.clone(camera.position, result.position);
    Cartesian3.clone(camera.direction, result.direction);
    Cartesian3.clone(camera.up, result.up);
    Cartesian3.clone(camera.right, result.right);
    Matrix4.clone(camera._transform, result.transform);
    result._transformChanged = true;
    result.frustum = camera.frustum.clone();

    return result;
  };

  /**
   * Enumerates the available input for interacting with the camera.
   *
   * @enum {Number}
   */
  const CameraEventType = {
    /**
     * A left mouse button press followed by moving the mouse and releasing the button.
     *
     * @type {Number}
     * @constant
     */
    LEFT_DRAG: 0,

    /**
     *  A right mouse button press followed by moving the mouse and releasing the button.
     *
     * @type {Number}
     * @constant
     */
    RIGHT_DRAG: 1,

    /**
     *  A middle mouse button press followed by moving the mouse and releasing the button.
     *
     * @type {Number}
     * @constant
     */
    MIDDLE_DRAG: 2,

    /**
     * Scrolling the middle mouse button.
     *
     * @type {Number}
     * @constant
     */
    WHEEL: 3,

    /**
     * A two-finger touch on a touch surface.
     *
     * @type {Number}
     * @constant
     */
    PINCH: 4,
  };
  var CameraEventType$1 = Object.freeze(CameraEventType);

  function getKey$1(type, modifier) {
    let key = type;
    if (defined(modifier)) {
      key += `+${modifier}`;
    }
    return key;
  }

  function clonePinchMovement(pinchMovement, result) {
    Cartesian2.clone(
      pinchMovement.distance.startPosition,
      result.distance.startPosition
    );
    Cartesian2.clone(
      pinchMovement.distance.endPosition,
      result.distance.endPosition
    );

    Cartesian2.clone(
      pinchMovement.angleAndHeight.startPosition,
      result.angleAndHeight.startPosition
    );
    Cartesian2.clone(
      pinchMovement.angleAndHeight.endPosition,
      result.angleAndHeight.endPosition
    );
  }

  function listenToPinch(aggregator, modifier, canvas) {
    const key = getKey$1(CameraEventType$1.PINCH, modifier);

    const update = aggregator._update;
    const isDown = aggregator._isDown;
    const eventStartPosition = aggregator._eventStartPosition;
    const pressTime = aggregator._pressTime;
    const releaseTime = aggregator._releaseTime;

    update[key] = true;
    isDown[key] = false;
    eventStartPosition[key] = new Cartesian2();

    let movement = aggregator._movement[key];
    if (!defined(movement)) {
      movement = aggregator._movement[key] = {};
    }

    movement.distance = {
      startPosition: new Cartesian2(),
      endPosition: new Cartesian2(),
    };
    movement.angleAndHeight = {
      startPosition: new Cartesian2(),
      endPosition: new Cartesian2(),
    };
    movement.prevAngle = 0.0;

    aggregator._eventHandler.setInputAction(
      function (event) {
        aggregator._buttonsDown++;
        isDown[key] = true;
        pressTime[key] = new Date();
        // Compute center position and store as start point.
        Cartesian2.lerp(
          event.position1,
          event.position2,
          0.5,
          eventStartPosition[key]
        );
      },
      ScreenSpaceEventType$1.PINCH_START,
      modifier
    );

    aggregator._eventHandler.setInputAction(
      function () {
        aggregator._buttonsDown = Math.max(aggregator._buttonsDown - 1, 0);
        isDown[key] = false;
        releaseTime[key] = new Date();
      },
      ScreenSpaceEventType$1.PINCH_END,
      modifier
    );

    aggregator._eventHandler.setInputAction(
      function (mouseMovement) {
        if (isDown[key]) {
          // Aggregate several input events into a single animation frame.
          if (!update[key]) {
            Cartesian2.clone(
              mouseMovement.distance.endPosition,
              movement.distance.endPosition
            );
            Cartesian2.clone(
              mouseMovement.angleAndHeight.endPosition,
              movement.angleAndHeight.endPosition
            );
          } else {
            clonePinchMovement(mouseMovement, movement);
            update[key] = false;
            movement.prevAngle = movement.angleAndHeight.startPosition.x;
          }
          // Make sure our aggregation of angles does not "flip" over 360 degrees.
          let angle = movement.angleAndHeight.endPosition.x;
          const prevAngle = movement.prevAngle;
          const TwoPI = Math.PI * 2;
          while (angle >= prevAngle + Math.PI) {
            angle -= TwoPI;
          }
          while (angle < prevAngle - Math.PI) {
            angle += TwoPI;
          }
          movement.angleAndHeight.endPosition.x =
            (-angle * canvas.clientWidth) / 12;
          movement.angleAndHeight.startPosition.x =
            (-prevAngle * canvas.clientWidth) / 12;
        }
      },
      ScreenSpaceEventType$1.PINCH_MOVE,
      modifier
    );
  }

  function listenToWheel(aggregator, modifier) {
    const key = getKey$1(CameraEventType$1.WHEEL, modifier);

    const update = aggregator._update;
    update[key] = true;

    let movement = aggregator._movement[key];
    if (!defined(movement)) {
      movement = aggregator._movement[key] = {};
    }

    movement.startPosition = new Cartesian2();
    movement.endPosition = new Cartesian2();

    aggregator._eventHandler.setInputAction(
      function (delta) {
        // TODO: magic numbers
        const arcLength = 15.0 * CesiumMath.toRadians(delta);
        if (!update[key]) {
          movement.endPosition.y = movement.endPosition.y + arcLength;
        } else {
          Cartesian2.clone(Cartesian2.ZERO, movement.startPosition);
          movement.endPosition.x = 0.0;
          movement.endPosition.y = arcLength;
          update[key] = false;
        }
      },
      ScreenSpaceEventType$1.WHEEL,
      modifier
    );
  }

  function listenMouseButtonDownUp(aggregator, modifier, type) {
    const key = getKey$1(type, modifier);

    const isDown = aggregator._isDown;
    const eventStartPosition = aggregator._eventStartPosition;
    const pressTime = aggregator._pressTime;
    const releaseTime = aggregator._releaseTime;

    isDown[key] = false;
    eventStartPosition[key] = new Cartesian2();

    let lastMovement = aggregator._lastMovement[key];
    if (!defined(lastMovement)) {
      lastMovement = aggregator._lastMovement[key] = {
        startPosition: new Cartesian2(),
        endPosition: new Cartesian2(),
        valid: false,
      };
    }

    let down;
    let up;
    if (type === CameraEventType$1.LEFT_DRAG) {
      down = ScreenSpaceEventType$1.LEFT_DOWN;
      up = ScreenSpaceEventType$1.LEFT_UP;
    } else if (type === CameraEventType$1.RIGHT_DRAG) {
      down = ScreenSpaceEventType$1.RIGHT_DOWN;
      up = ScreenSpaceEventType$1.RIGHT_UP;
    } else if (type === CameraEventType$1.MIDDLE_DRAG) {
      down = ScreenSpaceEventType$1.MIDDLE_DOWN;
      up = ScreenSpaceEventType$1.MIDDLE_UP;
    }

    aggregator._eventHandler.setInputAction(
      function (event) {
        aggregator._buttonsDown++;
        lastMovement.valid = false;
        isDown[key] = true;
        pressTime[key] = new Date();
        Cartesian2.clone(event.position, eventStartPosition[key]);
      },
      down,
      modifier
    );

    aggregator._eventHandler.setInputAction(
      function () {
        aggregator._buttonsDown = Math.max(aggregator._buttonsDown - 1, 0);
        isDown[key] = false;
        releaseTime[key] = new Date();
      },
      up,
      modifier
    );
  }

  function cloneMouseMovement(mouseMovement, result) {
    Cartesian2.clone(mouseMovement.startPosition, result.startPosition);
    Cartesian2.clone(mouseMovement.endPosition, result.endPosition);
  }

  function listenMouseMove(aggregator, modifier) {
    const update = aggregator._update;
    const movement = aggregator._movement;
    const lastMovement = aggregator._lastMovement;
    const isDown = aggregator._isDown;

    for (const typeName in CameraEventType$1) {
      if (CameraEventType$1.hasOwnProperty(typeName)) {
        const type = CameraEventType$1[typeName];
        if (defined(type)) {
          const key = getKey$1(type, modifier);
          update[key] = true;

          if (!defined(aggregator._lastMovement[key])) {
            aggregator._lastMovement[key] = {
              startPosition: new Cartesian2(),
              endPosition: new Cartesian2(),
              valid: false,
            };
          }

          if (!defined(aggregator._movement[key])) {
            aggregator._movement[key] = {
              startPosition: new Cartesian2(),
              endPosition: new Cartesian2(),
            };
          }
        }
      }
    }

    aggregator._eventHandler.setInputAction(
      function (mouseMovement) {
        for (const typeName in CameraEventType$1) {
          if (CameraEventType$1.hasOwnProperty(typeName)) {
            const type = CameraEventType$1[typeName];
            if (defined(type)) {
              const key = getKey$1(type, modifier);
              if (isDown[key]) {
                if (!update[key]) {
                  Cartesian2.clone(
                    mouseMovement.endPosition,
                    movement[key].endPosition
                  );
                } else {
                  cloneMouseMovement(movement[key], lastMovement[key]);
                  lastMovement[key].valid = true;
                  cloneMouseMovement(mouseMovement, movement[key]);
                  update[key] = false;
                }
              }
            }
          }
        }

        Cartesian2.clone(
          mouseMovement.endPosition,
          aggregator._currentMousePosition
        );
      },
      ScreenSpaceEventType$1.MOUSE_MOVE,
      modifier
    );
  }

  /**
   * Aggregates input events. For example, suppose the following inputs are received between frames:
   * left mouse button down, mouse move, mouse move, left mouse button up. These events will be aggregated into
   * one event with a start and end position of the mouse.
   *
   * @alias CameraEventAggregator
   * @constructor
   *
   * @param {HTMLCanvasElement} [canvas=document] The element to handle events for.
   *
   * @see ScreenSpaceEventHandler
   */
  function CameraEventAggregator(canvas) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(canvas)) {
      throw new DeveloperError("canvas is required.");
    }
    //>>includeEnd('debug');

    this._eventHandler = new ScreenSpaceEventHandler(canvas);

    this._update = {};
    this._movement = {};
    this._lastMovement = {};
    this._isDown = {};
    this._eventStartPosition = {};
    this._pressTime = {};
    this._releaseTime = {};

    this._buttonsDown = 0;

    this._currentMousePosition = new Cartesian2();

    listenToWheel(this, undefined);
    listenToPinch(this, undefined, canvas);
    listenMouseButtonDownUp(this, undefined, CameraEventType$1.LEFT_DRAG);
    listenMouseButtonDownUp(this, undefined, CameraEventType$1.RIGHT_DRAG);
    listenMouseButtonDownUp(this, undefined, CameraEventType$1.MIDDLE_DRAG);
    listenMouseMove(this, undefined);

    for (const modifierName in KeyboardEventModifier$1) {
      if (KeyboardEventModifier$1.hasOwnProperty(modifierName)) {
        const modifier = KeyboardEventModifier$1[modifierName];
        if (defined(modifier)) {
          listenToWheel(this, modifier);
          listenToPinch(this, modifier, canvas);
          listenMouseButtonDownUp(this, modifier, CameraEventType$1.LEFT_DRAG);
          listenMouseButtonDownUp(this, modifier, CameraEventType$1.RIGHT_DRAG);
          listenMouseButtonDownUp(this, modifier, CameraEventType$1.MIDDLE_DRAG);
          listenMouseMove(this, modifier);
        }
      }
    }
  }

  Object.defineProperties(CameraEventAggregator.prototype, {
    /**
     * Gets the current mouse position.
     * @memberof CameraEventAggregator.prototype
     * @type {Cartesian2}
     */
    currentMousePosition: {
      get: function () {
        return this._currentMousePosition;
      },
    },

    /**
     * Gets whether any mouse button is down, a touch has started, or the wheel has been moved.
     * @memberof CameraEventAggregator.prototype
     * @type {Boolean}
     */
    anyButtonDown: {
      get: function () {
        const wheelMoved =
          !this._update[getKey$1(CameraEventType$1.WHEEL)] ||
          !this._update[
            getKey$1(CameraEventType$1.WHEEL, KeyboardEventModifier$1.SHIFT)
          ] ||
          !this._update[
            getKey$1(CameraEventType$1.WHEEL, KeyboardEventModifier$1.CTRL)
          ] ||
          !this._update[getKey$1(CameraEventType$1.WHEEL, KeyboardEventModifier$1.ALT)];
        return this._buttonsDown > 0 || wheelMoved;
      },
    },
  });

  /**
   * Gets if a mouse button down or touch has started and has been moved.
   *
   * @param {CameraEventType} type The camera event type.
   * @param {KeyboardEventModifier} [modifier] The keyboard modifier.
   * @returns {Boolean} Returns <code>true</code> if a mouse button down or touch has started and has been moved; otherwise, <code>false</code>
   */
  CameraEventAggregator.prototype.isMoving = function (type, modifier) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(type)) {
      throw new DeveloperError("type is required.");
    }
    //>>includeEnd('debug');

    const key = getKey$1(type, modifier);
    return !this._update[key];
  };

  /**
   * Gets the aggregated start and end position of the current event.
   *
   * @param {CameraEventType} type The camera event type.
   * @param {KeyboardEventModifier} [modifier] The keyboard modifier.
   * @returns {Object} An object with two {@link Cartesian2} properties: <code>startPosition</code> and <code>endPosition</code>.
   */
  CameraEventAggregator.prototype.getMovement = function (type, modifier) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(type)) {
      throw new DeveloperError("type is required.");
    }
    //>>includeEnd('debug');

    const key = getKey$1(type, modifier);
    const movement = this._movement[key];
    return movement;
  };

  /**
   * Gets the start and end position of the last move event (not the aggregated event).
   *
   * @param {CameraEventType} type The camera event type.
   * @param {KeyboardEventModifier} [modifier] The keyboard modifier.
   * @returns {Object|undefined} An object with two {@link Cartesian2} properties: <code>startPosition</code> and <code>endPosition</code> or <code>undefined</code>.
   */
  CameraEventAggregator.prototype.getLastMovement = function (type, modifier) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(type)) {
      throw new DeveloperError("type is required.");
    }
    //>>includeEnd('debug');

    const key = getKey$1(type, modifier);
    const lastMovement = this._lastMovement[key];
    if (lastMovement.valid) {
      return lastMovement;
    }

    return undefined;
  };

  /**
   * Gets whether the mouse button is down or a touch has started.
   *
   * @param {CameraEventType} type The camera event type.
   * @param {KeyboardEventModifier} [modifier] The keyboard modifier.
   * @returns {Boolean} Whether the mouse button is down or a touch has started.
   */
  CameraEventAggregator.prototype.isButtonDown = function (type, modifier) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(type)) {
      throw new DeveloperError("type is required.");
    }
    //>>includeEnd('debug');

    const key = getKey$1(type, modifier);
    return this._isDown[key];
  };

  /**
   * Gets the mouse position that started the aggregation.
   *
   * @param {CameraEventType} type The camera event type.
   * @param {KeyboardEventModifier} [modifier] The keyboard modifier.
   * @returns {Cartesian2} The mouse position.
   */
  CameraEventAggregator.prototype.getStartMousePosition = function (
    type,
    modifier
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(type)) {
      throw new DeveloperError("type is required.");
    }
    //>>includeEnd('debug');

    if (type === CameraEventType$1.WHEEL) {
      return this._currentMousePosition;
    }

    const key = getKey$1(type, modifier);
    return this._eventStartPosition[key];
  };

  /**
   * Gets the time the button was pressed or the touch was started.
   *
   * @param {CameraEventType} type The camera event type.
   * @param {KeyboardEventModifier} [modifier] The keyboard modifier.
   * @returns {Date} The time the button was pressed or the touch was started.
   */
  CameraEventAggregator.prototype.getButtonPressTime = function (type, modifier) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(type)) {
      throw new DeveloperError("type is required.");
    }
    //>>includeEnd('debug');

    const key = getKey$1(type, modifier);
    return this._pressTime[key];
  };

  /**
   * Gets the time the button was released or the touch was ended.
   *
   * @param {CameraEventType} type The camera event type.
   * @param {KeyboardEventModifier} [modifier] The keyboard modifier.
   * @returns {Date} The time the button was released or the touch was ended.
   */
  CameraEventAggregator.prototype.getButtonReleaseTime = function (
    type,
    modifier
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(type)) {
      throw new DeveloperError("type is required.");
    }
    //>>includeEnd('debug');

    const key = getKey$1(type, modifier);
    return this._releaseTime[key];
  };

  /**
   * Signals that all of the events have been handled and the aggregator should be reset to handle new events.
   */
  CameraEventAggregator.prototype.reset = function () {
    for (const name in this._update) {
      if (this._update.hasOwnProperty(name)) {
        this._update[name] = true;
      }
    }
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see CameraEventAggregator#destroy
   */
  CameraEventAggregator.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Removes mouse listeners held by this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * handler = handler && handler.destroy();
   *
   * @see CameraEventAggregator#isDestroyed
   */
  CameraEventAggregator.prototype.destroy = function () {
    this._eventHandler = this._eventHandler && this._eventHandler.destroy();
    return destroyObject(this);
  };

  /**
   * The content of a tile in a {@link Cesium3DTileset}.
   * <p>
   * Derived classes of this interface provide access to individual features in the tile.
   * Access derived objects through {@link Cesium3DTile#content}.
   * </p>
   * <p>
   * This type describes an interface and is not intended to be instantiated directly.
   * </p>
   *
   * @alias Cesium3DTileContent
   * @constructor
   */
  function Cesium3DTileContent() {
    /**
     * Gets or sets if any feature's property changed.  Used to
     * optimized applying a style when a feature's property changed.
     * <p>
     * This is used to implement the <code>Cesium3DTileContent</code> interface, but is
     * not part of the public Cesium API.
     * </p>
     *
     * @type {Boolean}
     *
     * @private
     */
    this.featurePropertiesDirty = false;
  }

  Object.defineProperties(Cesium3DTileContent.prototype, {
    /**
     * Gets the number of features in the tile.
     *
     * @memberof Cesium3DTileContent.prototype
     *
     * @type {Number}
     * @readonly
     */
    featuresLength: {
      // eslint-disable-next-line getter-return
      get: function () {
        DeveloperError.throwInstantiationError();
      },
    },

    /**
     * Gets the number of points in the tile.
     * <p>
     * Only applicable for tiles with Point Cloud content. This is different than {@link Cesium3DTileContent#featuresLength} which
     * equals the number of groups of points as distinguished by the <code>BATCH_ID</code> feature table semantic.
     * </p>
     *
     * @see {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/TileFormats/PointCloud#batched-points}
     *
     * @memberof Cesium3DTileContent.prototype
     *
     * @type {Number}
     * @readonly
     */
    pointsLength: {
      // eslint-disable-next-line getter-return
      get: function () {
        DeveloperError.throwInstantiationError();
      },
    },

    /**
     * Gets the number of triangles in the tile.
     *
     * @memberof Cesium3DTileContent.prototype
     *
     * @type {Number}
     * @readonly
     */
    trianglesLength: {
      // eslint-disable-next-line getter-return
      get: function () {
        DeveloperError.throwInstantiationError();
      },
    },

    /**
     * Gets the tile's geometry memory in bytes.
     *
     * @memberof Cesium3DTileContent.prototype
     *
     * @type {Number}
     * @readonly
     */
    geometryByteLength: {
      // eslint-disable-next-line getter-return
      get: function () {
        DeveloperError.throwInstantiationError();
      },
    },

    /**
     * Gets the tile's texture memory in bytes.
     *
     * @memberof Cesium3DTileContent.prototype
     *
     * @type {Number}
     * @readonly
     */
    texturesByteLength: {
      // eslint-disable-next-line getter-return
      get: function () {
        DeveloperError.throwInstantiationError();
      },
    },

    /**
     * Gets the amount of memory used by the batch table textures and any binary
     * metadata properties not accounted for in geometryByteLength or
     * texturesByteLength
     *
     * @memberof Cesium3DTileContent.prototype
     *
     * @type {Number}
     * @readonly
     */
    batchTableByteLength: {
      // eslint-disable-next-line getter-return
      get: function () {
        DeveloperError.throwInstantiationError();
      },
    },

    /**
     * Gets the array of {@link Cesium3DTileContent} objects for contents that contain other contents, such as composite tiles. The inner contents may in turn have inner contents, such as a composite tile that contains a composite tile.
     *
     * @see {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/TileFormats/Composite|Composite specification}
     *
     * @memberof Cesium3DTileContent.prototype
     *
     * @type {Array}
     * @readonly
     */
    innerContents: {
      // eslint-disable-next-line getter-return
      get: function () {
        DeveloperError.throwInstantiationError();
      },
    },

    /**
     * Gets the promise that will be resolved when the tile's content is ready to render.
     *
     * @memberof Cesium3DTileContent.prototype
     *
     * @type {Promise.<Cesium3DTileContent>}
     * @readonly
     */
    readyPromise: {
      // eslint-disable-next-line getter-return
      get: function () {
        DeveloperError.throwInstantiationError();
      },
    },

    /**
     * Gets the tileset for this tile.
     *
     * @memberof Cesium3DTileContent.prototype
     *
     * @type {Cesium3DTileset}
     * @readonly
     */
    tileset: {
      // eslint-disable-next-line getter-return
      get: function () {
        DeveloperError.throwInstantiationError();
      },
    },

    /**
     * Gets the tile containing this content.
     *
     * @memberof Cesium3DTileContent.prototype
     *
     * @type {Cesium3DTile}
     * @readonly
     */
    tile: {
      // eslint-disable-next-line getter-return
      get: function () {
        DeveloperError.throwInstantiationError();
      },
    },

    /**
     * Gets the url of the tile's content.
     * @memberof Cesium3DTileContent.prototype
     *
     * @type {String}
     * @readonly
     */
    url: {
      // eslint-disable-next-line getter-return
      get: function () {
        DeveloperError.throwInstantiationError();
      },
    },

    /**
     * Gets the batch table for this content.
     * <p>
     * This is used to implement the <code>Cesium3DTileContent</code> interface, but is
     * not part of the public Cesium API.
     * </p>
     *
     * @type {Cesium3DTileBatchTable}
     * @readonly
     *
     * @private
     */
    batchTable: {
      // eslint-disable-next-line getter-return
      get: function () {
        DeveloperError.throwInstantiationError();
      },
    },

    /**
     * Gets the metadata for this content, whether it is available explicitly or via
     * implicit tiling. If there is no metadata, this property should be undefined.
     * <p>
     * This is used to implement the <code>Cesium3DTileContent</code> interface, but is
     * not part of the public Cesium API.
     * </p>
     *
     * @type {ImplicitMetadataView|undefined}
     *
     * @private
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     */
    metadata: {
      // eslint-disable-next-line getter-return
      get: function () {
        DeveloperError.throwInstantiationError();
      },
      set: function (value) {
        DeveloperError.throwInstantiationError();
      },
    },

    /**
     * Gets the group for this content if the content has metadata (3D Tiles 1.1) or
     * if it uses the <code>3DTILES_metadata</code> extension. If neither are present,
     * this property should be undefined.
     * <p>
     * This is used to implement the <code>Cesium3DTileContent</code> interface, but is
     * not part of the public Cesium API.
     * </p>
     *
     * @type {Cesium3DTileContentGroup|undefined}
     *
     * @private
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     */
    group: {
      // eslint-disable-next-line getter-return
      get: function () {
        DeveloperError.throwInstantiationError();
      },
      set: function (value) {
        DeveloperError.throwInstantiationError();
      },
    },
  });

  /**
   * Returns whether the feature has this property.
   *
   * @param {Number} batchId The batchId for the feature.
   * @param {String} name The case-sensitive name of the property.
   * @returns {Boolean} <code>true</code> if the feature has this property; otherwise, <code>false</code>.
   */
  Cesium3DTileContent.prototype.hasProperty = function (batchId, name) {
    DeveloperError.throwInstantiationError();
  };

  /**
   * Returns the {@link Cesium3DTileFeature} object for the feature with the
   * given <code>batchId</code>.  This object is used to get and modify the
   * feature's properties.
   * <p>
   * Features in a tile are ordered by <code>batchId</code>, an index used to retrieve their metadata from the batch table.
   * </p>
   *
   * @see {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/TileFormats/BatchTable}.
   *
   * @param {Number} batchId The batchId for the feature.
   * @returns {Cesium3DTileFeature} The corresponding {@link Cesium3DTileFeature} object.
   *
   * @exception {DeveloperError} batchId must be between zero and {@link Cesium3DTileContent#featuresLength} - 1.
   */
  Cesium3DTileContent.prototype.getFeature = function (batchId) {
    DeveloperError.throwInstantiationError();
  };

  /**
       * Called when {@link Cesium3DTileset#debugColorizeTiles} changes.
       * <p>
       * This is used to implement the <code>Cesium3DTileContent</code> interface, but is
       * not part of the public Cesium API.
       * </p>
       *
       * @param {Boolean} enabled Whether to enable or disable debug settings.
       * @returns {Cesium3DTileFeature} The corresponding {@link Cesium3DTileFeature} object.

       * @private
       */
  Cesium3DTileContent.prototype.applyDebugSettings = function (enabled, color) {
    DeveloperError.throwInstantiationError();
  };

  /**
   * Apply a style to the content
   * <p>
   * This is used to implement the <code>Cesium3DTileContent</code> interface, but is
   * not part of the public Cesium API.
   * </p>
   *
   * @param {Cesium3DTileStyle} style The style.
   *
   * @private
   */
  Cesium3DTileContent.prototype.applyStyle = function (style) {
    DeveloperError.throwInstantiationError();
  };

  /**
   * Called by the tile during tileset traversal to get the draw commands needed to render this content.
   * When the tile's content is in the PROCESSING state, this creates WebGL resources to ultimately
   * move to the READY state.
   * <p>
   * This is used to implement the <code>Cesium3DTileContent</code> interface, but is
   * not part of the public Cesium API.
   * </p>
   *
   * @param {Cesium3DTileset} tileset The tileset containing this tile.
   * @param {FrameState} frameState The frame state.
   *
   * @private
   */
  Cesium3DTileContent.prototype.update = function (tileset, frameState) {
    DeveloperError.throwInstantiationError();
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   * <p>
   * This is used to implement the <code>Cesium3DTileContent</code> interface, but is
   * not part of the public Cesium API.
   * </p>
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see Cesium3DTileContent#destroy
   *
   * @private
   */
  Cesium3DTileContent.prototype.isDestroyed = function () {
    DeveloperError.throwInstantiationError();
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   * <p>
   * This is used to implement the <code>Cesium3DTileContent</code> interface, but is
   * not part of the public Cesium API.
   * </p>
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @example
   * content = content && content.destroy();
   *
   * @see Cesium3DTileContent#isDestroyed
   *
   * @private
   */
  Cesium3DTileContent.prototype.destroy = function () {
    DeveloperError.throwInstantiationError();
  };

  /**
   * The state for a 3D Tiles update pass.
   *
   * @private
   * @constructor
   */
  function Cesium3DTilePassState(options) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options", options);
    Check.typeOf.number("options.pass", options.pass);
    //>>includeEnd('debug');

    /**
     * The pass.
     *
     * @type {Cesium3DTilePass}
     */
    this.pass = options.pass;

    /**
     * An array of rendering commands to use instead of {@link FrameState.commandList} for the current pass.
     *
     * @type {DrawCommand[]}
     */
    this.commandList = options.commandList;

    /**
     * A camera to use instead of {@link FrameState.camera} for the current pass.
     *
     * @type {Camera}
     */
    this.camera = options.camera;

    /**
     * A culling volume to use instead of {@link FrameState.cullingVolume} for the current pass.
     *
     * @type {CullingVolume}
     */
    this.cullingVolume = options.cullingVolume;

    /**
     * A read-only property that indicates whether the pass is ready, i.e. all tiles needed by the pass are loaded.
     *
     * @type {Boolean}
     * @readonly
     * @default false
     */
    this.ready = false;
  }

  /**
   * An expression for a style applied to a {@link Cesium3DTileset}.
   * <p>
   * Evaluates a conditions expression defined using the
   * {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/Styling|3D Tiles Styling language}.
   * </p>
   * <p>
   * Implements the {@link StyleExpression} interface.
   * </p>
   *
   * @alias ConditionsExpression
   * @constructor
   *
   * @param {Object} [conditionsExpression] The conditions expression defined using the 3D Tiles Styling language.
   * @param {Object} [defines] Defines in the style.
   *
   * @example
   * const expression = new Cesium.ConditionsExpression({
   *     conditions : [
   *         ['${Area} > 10, 'color("#FF0000")'],
   *         ['${id} !== "1"', 'color("#00FF00")'],
   *         ['true', 'color("#FFFFFF")']
   *     ]
   * });
   * expression.evaluateColor(feature, result); // returns a Cesium.Color object
   */
  function ConditionsExpression(conditionsExpression, defines) {
    this._conditionsExpression = clone$1(conditionsExpression, true);
    this._conditions = conditionsExpression.conditions;
    this._runtimeConditions = undefined;

    setRuntime(this, defines);
  }

  Object.defineProperties(ConditionsExpression.prototype, {
    /**
     * Gets the conditions expression defined in the 3D Tiles Styling language.
     *
     * @memberof ConditionsExpression.prototype
     *
     * @type {Object}
     * @readonly
     *
     * @default undefined
     */
    conditionsExpression: {
      get: function () {
        return this._conditionsExpression;
      },
    },
  });

  function Statement(condition, expression) {
    this.condition = condition;
    this.expression = expression;
  }

  function setRuntime(expression, defines) {
    const runtimeConditions = [];
    const conditions = expression._conditions;
    if (!defined(conditions)) {
      return;
    }
    const length = conditions.length;
    for (let i = 0; i < length; ++i) {
      const statement = conditions[i];
      const cond = String(statement[0]);
      const condExpression = String(statement[1]);
      runtimeConditions.push(
        new Statement(
          new Expression(cond, defines),
          new Expression(condExpression, defines)
        )
      );
    }
    expression._runtimeConditions = runtimeConditions;
  }

  /**
   * Evaluates the result of an expression, optionally using the provided feature's properties. If the result of
   * the expression in the
   * {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/Styling|3D Tiles Styling language}
   * is of type <code>Boolean</code>, <code>Number</code>, or <code>String</code>, the corresponding JavaScript
   * primitive type will be returned. If the result is a <code>RegExp</code>, a Javascript <code>RegExp</code>
   * object will be returned. If the result is a <code>Cartesian2</code>, <code>Cartesian3</code>, or <code>Cartesian4</code>,
   * a {@link Cartesian2}, {@link Cartesian3}, or {@link Cartesian4} object will be returned. If the <code>result</code> argument is
   * a {@link Color}, the {@link Cartesian4} value is converted to a {@link Color} and then returned.
   *
   * @param {Cesium3DTileFeature} feature The feature whose properties may be used as variables in the expression.
   * @param {Object} [result] The object onto which to store the result.
   * @returns {Boolean|Number|String|RegExp|Cartesian2|Cartesian3|Cartesian4|Color} The result of evaluating the expression.
   */
  ConditionsExpression.prototype.evaluate = function (feature, result) {
    const conditions = this._runtimeConditions;
    if (!defined(conditions)) {
      return undefined;
    }
    const length = conditions.length;
    for (let i = 0; i < length; ++i) {
      const statement = conditions[i];
      if (statement.condition.evaluate(feature)) {
        return statement.expression.evaluate(feature, result);
      }
    }
  };

  /**
   * Evaluates the result of a Color expression, using the values defined by a feature.
   * <p>
   * This is equivalent to {@link ConditionsExpression#evaluate} but always returns a {@link Color} object.
   * </p>
   * @param {Cesium3DTileFeature} feature The feature whose properties may be used as variables in the expression.
   * @param {Color} [result] The object in which to store the result
   * @returns {Color} The modified result parameter or a new Color instance if one was not provided.
   */
  ConditionsExpression.prototype.evaluateColor = function (feature, result) {
    const conditions = this._runtimeConditions;
    if (!defined(conditions)) {
      return undefined;
    }
    const length = conditions.length;
    for (let i = 0; i < length; ++i) {
      const statement = conditions[i];
      if (statement.condition.evaluate(feature)) {
        return statement.expression.evaluateColor(feature, result);
      }
    }
  };

  /**
   * Gets the shader function for this expression.
   * Returns undefined if the shader function can't be generated from this expression.
   *
   * @param {String} functionSignature Signature of the generated function.
   * @param {Object} variableSubstitutionMap Maps variable names to shader variable names.
   * @param {Object} shaderState Stores information about the generated shader function, including whether it is translucent.
   * @param {String} returnType The return type of the generated function.
   *
   * @returns {String} The shader function.
   *
   * @private
   */
  ConditionsExpression.prototype.getShaderFunction = function (
    functionSignature,
    variableSubstitutionMap,
    shaderState,
    returnType
  ) {
    const conditions = this._runtimeConditions;
    if (!defined(conditions) || conditions.length === 0) {
      return undefined;
    }

    let shaderFunction = "";
    const length = conditions.length;
    for (let i = 0; i < length; ++i) {
      const statement = conditions[i];

      const condition = statement.condition.getShaderExpression(
        variableSubstitutionMap,
        shaderState
      );
      const expression = statement.expression.getShaderExpression(
        variableSubstitutionMap,
        shaderState
      );

      // Build the if/else chain from the list of conditions
      shaderFunction +=
        `    ${i === 0 ? "if" : "else if"} (${condition})\n` +
        `    {\n` +
        `        return ${expression};\n` +
        `    }\n`;
    }

    shaderFunction =
      `${returnType} ${functionSignature}\n` +
      `{\n${shaderFunction}    return ${returnType}(1.0);\n` + // Return a default value if no conditions are met
      `}\n`;

    return shaderFunction;
  };

  /**
   * Gets the variables used by the expression.
   *
   * @returns {String[]} The variables used by the expression.
   *
   * @private
   */
  ConditionsExpression.prototype.getVariables = function () {
    let variables = [];

    const conditions = this._runtimeConditions;
    if (!defined(conditions) || conditions.length === 0) {
      return variables;
    }

    const length = conditions.length;
    for (let i = 0; i < length; ++i) {
      const statement = conditions[i];
      variables.push.apply(variables, statement.condition.getVariables());
      variables.push.apply(variables, statement.expression.getVariables());
    }

    // Remove duplicates
    variables = variables.filter(function (variable, index, variables) {
      return variables.indexOf(variable) === index;
    });

    return variables;
  };

  /**
   * A style that is applied to a {@link Cesium3DTileset}.
   * <p>
   * Evaluates an expression defined using the
   * {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/Styling|3D Tiles Styling language}.
   * </p>
   *
   * @alias Cesium3DTileStyle
   * @constructor
   *
   * @param {Object} [style] An object defining a style.
   *
   * @example
   * tileset.style = new Cesium.Cesium3DTileStyle({
   *     color : {
   *         conditions : [
   *             ['${Height} >= 100', 'color("purple", 0.5)'],
   *             ['${Height} >= 50', 'color("red")'],
   *             ['true', 'color("blue")']
   *         ]
   *     },
   *     show : '${Height} > 0',
   *     meta : {
   *         description : '"Building id ${id} has height ${Height}."'
   *     }
   * });
   *
   * @example
   * tileset.style = new Cesium.Cesium3DTileStyle({
   *     color : 'vec4(${Temperature})',
   *     pointSize : '${Temperature} * 2.0'
   * });
   *
   * @see {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/Styling|3D Tiles Styling language}
   */
  function Cesium3DTileStyle(style) {
    this._style = {};
    this._ready = false;

    this._show = undefined;
    this._color = undefined;
    this._pointSize = undefined;
    this._pointOutlineColor = undefined;
    this._pointOutlineWidth = undefined;
    this._labelColor = undefined;
    this._labelOutlineColor = undefined;
    this._labelOutlineWidth = undefined;
    this._font = undefined;
    this._labelStyle = undefined;
    this._labelText = undefined;
    this._backgroundColor = undefined;
    this._backgroundPadding = undefined;
    this._backgroundEnabled = undefined;
    this._scaleByDistance = undefined;
    this._translucencyByDistance = undefined;
    this._distanceDisplayCondition = undefined;
    this._heightOffset = undefined;
    this._anchorLineEnabled = undefined;
    this._anchorLineColor = undefined;
    this._image = undefined;
    this._disableDepthTestDistance = undefined;
    this._horizontalOrigin = undefined;
    this._verticalOrigin = undefined;
    this._labelHorizontalOrigin = undefined;
    this._labelVerticalOrigin = undefined;
    this._meta = undefined;

    this._colorShaderFunction = undefined;
    this._showShaderFunction = undefined;
    this._pointSizeShaderFunction = undefined;
    this._colorShaderFunctionReady = false;
    this._showShaderFunctionReady = false;
    this._pointSizeShaderFunctionReady = false;

    this._colorShaderTranslucent = false;

    if (typeof style === "string" || style instanceof Resource) {
      //>>includeStart('debug', pragmas.debug);
      deprecationWarning(
        "Cesium3DTileStyle constructor",
        "string or Resource style parameter in the Cesium3DTileStyle constructor was deprecated in CesiumJS 1.94.  If loading a style from a url, use Cesium3DTileStyle.fromUrl instead."
      );
      //>>includeEnd('debug');

      const resource = Resource.createIfNeeded(style);
      const that = this;
      this._readyPromise = resource.fetchJson(style).then(function (styleJson) {
        setup(that, styleJson);
        return that;
      });
    } else {
      setup(this, style);
      this._readyPromise = Promise.resolve(this);
    }
  }

  function setup(that, styleJson) {
    styleJson = defaultValue(clone$1(styleJson, true), that._style);
    that._style = styleJson;

    that.show = styleJson.show;
    that.color = styleJson.color;
    that.pointSize = styleJson.pointSize;
    that.pointOutlineColor = styleJson.pointOutlineColor;
    that.pointOutlineWidth = styleJson.pointOutlineWidth;
    that.labelColor = styleJson.labelColor;
    that.labelOutlineColor = styleJson.labelOutlineColor;
    that.labelOutlineWidth = styleJson.labelOutlineWidth;
    that.labelStyle = styleJson.labelStyle;
    that.font = styleJson.font;
    that.labelText = styleJson.labelText;
    that.backgroundColor = styleJson.backgroundColor;
    that.backgroundPadding = styleJson.backgroundPadding;
    that.backgroundEnabled = styleJson.backgroundEnabled;
    that.scaleByDistance = styleJson.scaleByDistance;
    that.translucencyByDistance = styleJson.translucencyByDistance;
    that.distanceDisplayCondition = styleJson.distanceDisplayCondition;
    that.heightOffset = styleJson.heightOffset;
    that.anchorLineEnabled = styleJson.anchorLineEnabled;
    that.anchorLineColor = styleJson.anchorLineColor;
    that.image = styleJson.image;
    that.disableDepthTestDistance = styleJson.disableDepthTestDistance;
    that.horizontalOrigin = styleJson.horizontalOrigin;
    that.verticalOrigin = styleJson.verticalOrigin;
    that.labelHorizontalOrigin = styleJson.labelHorizontalOrigin;
    that.labelVerticalOrigin = styleJson.labelVerticalOrigin;

    const meta = {};
    if (defined(styleJson.meta)) {
      const defines = styleJson.defines;
      const metaJson = defaultValue(styleJson.meta, defaultValue.EMPTY_OBJECT);
      for (const property in metaJson) {
        if (metaJson.hasOwnProperty(property)) {
          meta[property] = new Expression(metaJson[property], defines);
        }
      }
    }

    that._meta = meta;

    that._ready = true;
  }

  function getExpression(tileStyle, value) {
    const defines = defaultValue(tileStyle._style, defaultValue.EMPTY_OBJECT)
      .defines;

    if (!defined(value)) {
      return undefined;
    } else if (typeof value === "boolean" || typeof value === "number") {
      return new Expression(String(value));
    } else if (typeof value === "string") {
      return new Expression(value, defines);
    } else if (defined(value.conditions)) {
      return new ConditionsExpression(value, defines);
    }
    return value;
  }

  function getJsonFromExpression(expression) {
    if (!defined(expression)) {
      return undefined;
    } else if (defined(expression.expression)) {
      return expression.expression;
    } else if (defined(expression.conditionsExpression)) {
      return clone$1(expression.conditionsExpression, true);
    }
    return expression;
  }

  Object.defineProperties(Cesium3DTileStyle.prototype, {
    /**
     * Gets the object defining the style using the
     * {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/Styling|3D Tiles Styling language}.
     *
     * @memberof Cesium3DTileStyle.prototype
     *
     * @type {Object}
     * @readonly
     *
     * @default {}
     *
     * @exception {DeveloperError} The style is not loaded.  Use Cesium3DTileStyle.readyPromise or wait for Cesium3DTileStyle.ready to be true.
     */
    style: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "The style is not loaded.  Use Cesium3DTileStyle.readyPromise or wait for Cesium3DTileStyle.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._style;
      },
    },

    /**
     * When <code>true</code>, the style is ready and its expressions can be evaluated.  When
     * a style is constructed with an object, as opposed to a url, this is <code>true</code> immediately.
     *
     * @memberof Cesium3DTileStyle.prototype
     *
     * @type {Boolean}
     * @readonly
     * @deprecated
     *
     * @default false
     */
    ready: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        deprecationWarning(
          "ready",
          "ready was deprecated in CesiumJS 1.94.  It will be removed in 1.96.  If loading a style from a url, use Cesium3DTileStyle.fromUrl instead."
        );
        //>>includeEnd('debug');
        return this._ready;
      },
    },

    /**
     * Gets the promise that will be resolved when the the style is ready and its expressions can be evaluated.
     *
     * @memberof Cesium3DTileStyle.prototype
     *
     * @type {Promise.<Cesium3DTileStyle>}
     * @readonly
     * @deprecated
     */
    readyPromise: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        deprecationWarning(
          "readyPromise",
          "readyPromise was deprecated in CesiumJS 1.94.  It will be removed in 1.96.  If loading a style from a url, use Cesium3DTileStyle.fromUrl instead."
        );
        //>>includeEnd('debug');
        return this._readyPromise;
      },
    },

    /**
     * Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>show</code> property. Alternatively a boolean, string, or object defining a show style can be used.
     * The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
     * <p>
     * The expression must return or convert to a <code>Boolean</code>.
     * </p>
     * <p>
     * This expression is applicable to all tile formats.
     * </p>
     *
     * @memberof Cesium3DTileStyle.prototype
     *
     * @type {StyleExpression}
     *
     * @exception {DeveloperError} The style is not loaded.  Use {@link Cesium3DTileStyle#readyPromise} or wait for {@link Cesium3DTileStyle#ready} to be true.
     *
     * @example
     * const style = new Cesium3DTileStyle({
     *     show : '(regExp("^Chest").test(${County})) && (${YearBuilt} >= 1970)'
     * });
     * style.show.evaluate(feature); // returns true or false depending on the feature's properties
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override show expression with a custom function
     * style.show = {
     *     evaluate : function(feature) {
     *         return true;
     *     }
     * };
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override show expression with a boolean
     * style.show = true;
     * };
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override show expression with a string
     * style.show = '${Height} > 0';
     * };
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override show expression with a condition
     * style.show = {
     *     conditions: [
     *         ['${height} > 2', 'false'],
     *         ['true', 'true']
     *     ];
     * };
     */
    show: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "The style is not loaded.  Use Cesium3DTileStyle.readyPromise or wait for Cesium3DTileStyle.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._show;
      },
      set: function (value) {
        this._show = getExpression(this, value);
        this._style.show = getJsonFromExpression(this._show);
        this._showShaderFunctionReady = false;
      },
    },

    /**
     * Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>color</code> property. Alternatively a string or object defining a color style can be used.
     * The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
     * <p>
     * The expression must return a <code>Color</code>.
     * </p>
     * <p>
     * This expression is applicable to all tile formats.
     * </p>
     *
     * @memberof Cesium3DTileStyle.prototype
     *
     * @type {StyleExpression}
     *
     * @exception {DeveloperError} The style is not loaded.  Use {@link Cesium3DTileStyle#readyPromise} or wait for {@link Cesium3DTileStyle#ready} to be true.
     *
     * @example
     * const style = new Cesium3DTileStyle({
     *     color : '(${Temperature} > 90) ? color("red") : color("white")'
     * });
     * style.color.evaluateColor(feature, result); // returns a Cesium.Color object
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override color expression with a custom function
     * style.color = {
     *     evaluateColor : function(feature, result) {
     *         return Cesium.Color.clone(Cesium.Color.WHITE, result);
     *     }
     * };
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override color expression with a string
     * style.color = 'color("blue")';
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override color expression with a condition
     * style.color = {
     *     conditions : [
     *         ['${height} > 2', 'color("cyan")'],
     *         ['true', 'color("blue")']
     *     ]
     * };
     */
    color: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "The style is not loaded.  Use Cesium3DTileStyle.readyPromise or wait for Cesium3DTileStyle.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._color;
      },
      set: function (value) {
        this._color = getExpression(this, value);
        this._style.color = getJsonFromExpression(this._color);
        this._colorShaderFunctionReady = false;
      },
    },

    /**
     * Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>pointSize</code> property. Alternatively a string or object defining a point size style can be used.
     * The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
     * <p>
     * The expression must return a <code>Number</code>.
     * </p>
     * <p>
     * This expression is only applicable to point features in a Vector tile or a Point Cloud tile.
     * </p>
     *
     * @memberof Cesium3DTileStyle.prototype
     *
     * @type {StyleExpression}
     *
     * @exception {DeveloperError} The style is not loaded.  Use {@link Cesium3DTileStyle#readyPromise} or wait for {@link Cesium3DTileStyle#ready} to be true.
     *
     * @example
     * const style = new Cesium3DTileStyle({
     *     pointSize : '(${Temperature} > 90) ? 2.0 : 1.0'
     * });
     * style.pointSize.evaluate(feature); // returns a Number
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override pointSize expression with a custom function
     * style.pointSize = {
     *     evaluate : function(feature) {
     *         return 1.0;
     *     }
     * };
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override pointSize expression with a number
     * style.pointSize = 1.0;
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override pointSize expression with a string
     * style.pointSize = '${height} / 10';
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override pointSize expression with a condition
     * style.pointSize =  {
     *     conditions : [
     *         ['${height} > 2', '1.0'],
     *         ['true', '2.0']
     *     ]
     * };
     */
    pointSize: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "The style is not loaded.  Use Cesium3DTileStyle.readyPromise or wait for Cesium3DTileStyle.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._pointSize;
      },
      set: function (value) {
        this._pointSize = getExpression(this, value);
        this._style.pointSize = getJsonFromExpression(this._pointSize);
        this._pointSizeShaderFunctionReady = false;
      },
    },

    /**
     * Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>pointOutlineColor</code> property. Alternatively a string or object defining a color style can be used.
     * The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
     * <p>
     * The expression must return a <code>Color</code>.
     * </p>
     * <p>
     * This expression is only applicable to point features in a Vector tile.
     * </p>
     *
     * @memberof Cesium3DTileStyle.prototype
     *
     * @type {StyleExpression}
     *
     * @exception {DeveloperError} The style is not loaded.  Use {@link Cesium3DTileStyle#readyPromise} or wait for {@link Cesium3DTileStyle#ready} to be true.
     *
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override pointOutlineColor expression with a string
     * style.pointOutlineColor = 'color("blue")';
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override pointOutlineColor expression with a condition
     * style.pointOutlineColor = {
     *     conditions : [
     *         ['${height} > 2', 'color("cyan")'],
     *         ['true', 'color("blue")']
     *     ]
     * };
     */
    pointOutlineColor: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "The style is not loaded.  Use Cesium3DTileStyle.readyPromise or wait for Cesium3DTileStyle.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._pointOutlineColor;
      },
      set: function (value) {
        this._pointOutlineColor = getExpression(this, value);
        this._style.pointOutlineColor = getJsonFromExpression(
          this._pointOutlineColor
        );
      },
    },

    /**
     * Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>pointOutlineWidth</code> property. Alternatively a string or object defining a number style can be used.
     * The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
     * <p>
     * The expression must return a <code>Number</code>.
     * </p>
     * <p>
     * This expression is only applicable to point features in a Vector tile.
     * </p>
     *
     * @memberof Cesium3DTileStyle.prototype
     *
     * @type {StyleExpression}
     *
     * @exception {DeveloperError} The style is not loaded.  Use {@link Cesium3DTileStyle#readyPromise} or wait for {@link Cesium3DTileStyle#ready} to be true.
     *
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override pointOutlineWidth expression with a string
     * style.pointOutlineWidth = '5';
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override pointOutlineWidth expression with a condition
     * style.pointOutlineWidth = {
     *     conditions : [
     *         ['${height} > 2', '5'],
     *         ['true', '0']
     *     ]
     * };
     */
    pointOutlineWidth: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "The style is not loaded.  Use Cesium3DTileStyle.readyPromise or wait for Cesium3DTileStyle.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._pointOutlineWidth;
      },
      set: function (value) {
        this._pointOutlineWidth = getExpression(this, value);
        this._style.pointOutlineWidth = getJsonFromExpression(
          this._pointOutlineWidth
        );
      },
    },

    /**
     * Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>labelColor</code> property. Alternatively a string or object defining a color style can be used.
     * The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
     * <p>
     * The expression must return a <code>Color</code>.
     * </p>
     * <p>
     * This expression is only applicable to point features in a Vector tile.
     * </p>
     *
     * @memberof Cesium3DTileStyle.prototype
     *
     * @type {StyleExpression}
     *
     * @exception {DeveloperError} The style is not loaded.  Use {@link Cesium3DTileStyle#readyPromise} or wait for {@link Cesium3DTileStyle#ready} to be true.
     *
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override labelColor expression with a string
     * style.labelColor = 'color("blue")';
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override labelColor expression with a condition
     * style.labelColor = {
     *     conditions : [
     *         ['${height} > 2', 'color("cyan")'],
     *         ['true', 'color("blue")']
     *     ]
     * };
     */
    labelColor: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "The style is not loaded.  Use Cesium3DTileStyle.readyPromise or wait for Cesium3DTileStyle.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._labelColor;
      },
      set: function (value) {
        this._labelColor = getExpression(this, value);
        this._style.labelColor = getJsonFromExpression(this._labelColor);
      },
    },

    /**
     * Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>labelOutlineColor</code> property. Alternatively a string or object defining a color style can be used.
     * The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
     * <p>
     * The expression must return a <code>Color</code>.
     * </p>
     * <p>
     * This expression is only applicable to point features in a Vector tile.
     * </p>
     *
     * @memberof Cesium3DTileStyle.prototype
     *
     * @type {StyleExpression}
     *
     * @exception {DeveloperError} The style is not loaded.  Use {@link Cesium3DTileStyle#readyPromise} or wait for {@link Cesium3DTileStyle#ready} to be true.
     *
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override labelOutlineColor expression with a string
     * style.labelOutlineColor = 'color("blue")';
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override labelOutlineColor expression with a condition
     * style.labelOutlineColor = {
     *     conditions : [
     *         ['${height} > 2', 'color("cyan")'],
     *         ['true', 'color("blue")']
     *     ]
     * };
     */
    labelOutlineColor: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "The style is not loaded.  Use Cesium3DTileStyle.readyPromise or wait for Cesium3DTileStyle.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._labelOutlineColor;
      },
      set: function (value) {
        this._labelOutlineColor = getExpression(this, value);
        this._style.labelOutlineColor = getJsonFromExpression(
          this._labelOutlineColor
        );
      },
    },

    /**
     * Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>labelOutlineWidth</code> property. Alternatively a string or object defining a number style can be used.
     * The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
     * <p>
     * The expression must return a <code>Number</code>.
     * </p>
     * <p>
     * This expression is only applicable to point features in a Vector tile.
     * </p>
     *
     * @memberof Cesium3DTileStyle.prototype
     *
     * @type {StyleExpression}
     *
     * @exception {DeveloperError} The style is not loaded.  Use {@link Cesium3DTileStyle#readyPromise} or wait for {@link Cesium3DTileStyle#ready} to be true.
     *
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override labelOutlineWidth expression with a string
     * style.labelOutlineWidth = '5';
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override labelOutlineWidth expression with a condition
     * style.labelOutlineWidth = {
     *     conditions : [
     *         ['${height} > 2', '5'],
     *         ['true', '0']
     *     ]
     * };
     */
    labelOutlineWidth: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "The style is not loaded.  Use Cesium3DTileStyle.readyPromise or wait for Cesium3DTileStyle.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._labelOutlineWidth;
      },
      set: function (value) {
        this._labelOutlineWidth = getExpression(this, value);
        this._style.labelOutlineWidth = getJsonFromExpression(
          this._labelOutlineWidth
        );
      },
    },

    /**
     * Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>font</code> property. Alternatively a string or object defining a string style can be used.
     * The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
     * <p>
     * The expression must return a <code>String</code>.
     * </p>
     * <p>
     * This expression is only applicable to point features in a Vector tile.
     * </p>
     *
     * @memberof Cesium3DTileStyle.prototype
     *
     * @type {StyleExpression}
     *
     * @exception {DeveloperError} The style is not loaded.  Use {@link Cesium3DTileStyle#readyPromise} or wait for {@link Cesium3DTileStyle#ready} to be true.
     *
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     *
     * @example
     * const style = new Cesium3DTileStyle({
     *     font : '(${Temperature} > 90) ? "30px Helvetica" : "24px Helvetica"'
     * });
     * style.font.evaluate(feature); // returns a String
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override font expression with a custom function
     * style.font = {
     *     evaluate : function(feature) {
     *         return '24px Helvetica';
     *     }
     * };
     */
    font: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "The style is not loaded.  Use Cesium3DTileStyle.readyPromise or wait for Cesium3DTileStyle.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._font;
      },
      set: function (value) {
        this._font = getExpression(this, value);
        this._style.font = getJsonFromExpression(this._font);
      },
    },

    /**
     * Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>label style</code> property. Alternatively a string or object defining a number style can be used.
     * The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
     * <p>
     * The expression must return a <code>LabelStyle</code>.
     * </p>
     * <p>
     * This expression is only applicable to point features in a Vector tile.
     * </p>
     *
     * @memberof Cesium3DTileStyle.prototype
     *
     * @type {StyleExpression}
     *
     * @exception {DeveloperError} The style is not loaded.  Use {@link Cesium3DTileStyle#readyPromise} or wait for {@link Cesium3DTileStyle#ready} to be true.
     *
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     *
     * @example
     * const style = new Cesium3DTileStyle({
     *     labelStyle : `(\${Temperature} > 90) ? ${LabelStyle.FILL_AND_OUTLINE} : ${LabelStyle.FILL}`
     * });
     * style.labelStyle.evaluate(feature); // returns a LabelStyle
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override labelStyle expression with a custom function
     * style.labelStyle = {
     *     evaluate : function(feature) {
     *         return LabelStyle.FILL;
     *     }
     * };
     */
    labelStyle: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "The style is not loaded.  Use Cesium3DTileStyle.readyPromise or wait for Cesium3DTileStyle.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._labelStyle;
      },
      set: function (value) {
        this._labelStyle = getExpression(this, value);
        this._style.labelStyle = getJsonFromExpression(this._labelStyle);
      },
    },

    /**
     * Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>labelText</code> property. Alternatively a string or object defining a string style can be used.
     * The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
     * <p>
     * The expression must return a <code>String</code>.
     * </p>
     * <p>
     * This expression is only applicable to point features in a Vector tile.
     * </p>
     *
     * @memberof Cesium3DTileStyle.prototype
     *
     * @type {StyleExpression}
     *
     * @exception {DeveloperError} The style is not loaded.  Use {@link Cesium3DTileStyle#readyPromise} or wait for {@link Cesium3DTileStyle#ready} to be true.
     *
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     *
     * @example
     * const style = new Cesium3DTileStyle({
     *     labelText : '(${Temperature} > 90) ? ">90" : "<=90"'
     * });
     * style.labelText.evaluate(feature); // returns a String
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override labelText expression with a custom function
     * style.labelText = {
     *     evaluate : function(feature) {
     *         return 'Example label text';
     *     }
     * };
     */
    labelText: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "The style is not loaded.  Use Cesium3DTileStyle.readyPromise or wait for Cesium3DTileStyle.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._labelText;
      },
      set: function (value) {
        this._labelText = getExpression(this, value);
        this._style.labelText = getJsonFromExpression(this._labelText);
      },
    },

    /**
     * Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>backgroundColor</code> property. Alternatively a string or object defining a color style can be used.
     * The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
     * <p>
     * The expression must return a <code>Color</code>.
     * </p>
     * <p>
     * This expression is only applicable to point features in a Vector tile.
     * </p>
     *
     * @memberof Cesium3DTileStyle.prototype
     *
     * @type {StyleExpression}
     *
     * @exception {DeveloperError} The style is not loaded.  Use {@link Cesium3DTileStyle#readyPromise} or wait for {@link Cesium3DTileStyle#ready} to be true.
     *
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override backgroundColor expression with a string
     * style.backgroundColor = 'color("blue")';
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override backgroundColor expression with a condition
     * style.backgroundColor = {
     *     conditions : [
     *         ['${height} > 2', 'color("cyan")'],
     *         ['true', 'color("blue")']
     *     ]
     * };
     */
    backgroundColor: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "The style is not loaded.  Use Cesium3DTileStyle.readyPromise or wait for Cesium3DTileStyle.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._backgroundColor;
      },
      set: function (value) {
        this._backgroundColor = getExpression(this, value);
        this._style.backgroundColor = getJsonFromExpression(
          this._backgroundColor
        );
      },
    },

    /**
     * Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>backgroundPadding</code> property. Alternatively a string or object defining a vec2 style can be used.
     * The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
     * <p>
     * The expression must return a <code>Cartesian2</code>.
     * </p>
     * <p>
     * This expression is only applicable to point features in a Vector tile.
     * </p>
     *
     * @memberof Cesium3DTileStyle.prototype
     *
     * @type {StyleExpression}
     *
     * @exception {DeveloperError} The style is not loaded.  Use {@link Cesium3DTileStyle#readyPromise} or wait for {@link Cesium3DTileStyle#ready} to be true.
     *
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override backgroundPadding expression with a string
     * style.backgroundPadding = 'vec2(5.0, 7.0)';
     * style.backgroundPadding.evaluate(feature); // returns a Cartesian2
     */
    backgroundPadding: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "The style is not loaded.  Use Cesium3DTileStyle.readyPromise or wait for Cesium3DTileStyle.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._backgroundPadding;
      },
      set: function (value) {
        this._backgroundPadding = getExpression(this, value);
        this._style.backgroundPadding = getJsonFromExpression(
          this._backgroundPadding
        );
      },
    },

    /**
     * Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>backgroundEnabled</code> property. Alternatively a string or object defining a boolean style can be used.
     * The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
     * <p>
     * The expression must return a <code>Boolean</code>.
     * </p>
     * <p>
     * This expression is only applicable to point features in a Vector tile.
     * </p>
     *
     * @memberof Cesium3DTileStyle.prototype
     *
     * @type {StyleExpression}
     *
     * @exception {DeveloperError} The style is not loaded.  Use {@link Cesium3DTileStyle#readyPromise} or wait for {@link Cesium3DTileStyle#ready} to be true.
     *
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override backgroundEnabled expression with a string
     * style.backgroundEnabled = 'true';
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override backgroundEnabled expression with a condition
     * style.backgroundEnabled = {
     *     conditions : [
     *         ['${height} > 2', 'true'],
     *         ['true', 'false']
     *     ]
     * };
     */
    backgroundEnabled: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "The style is not loaded.  Use Cesium3DTileStyle.readyPromise or wait for Cesium3DTileStyle.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._backgroundEnabled;
      },
      set: function (value) {
        this._backgroundEnabled = getExpression(this, value);
        this._style.backgroundEnabled = getJsonFromExpression(
          this._backgroundEnabled
        );
      },
    },

    /**
     * Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>scaleByDistance</code> property. Alternatively a string or object defining a vec4 style can be used.
     * The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
     * <p>
     * The expression must return a <code>Cartesian4</code>.
     * </p>
     * <p>
     * This expression is only applicable to point features in a Vector tile.
     * </p>
     *
     * @memberof Cesium3DTileStyle.prototype
     *
     * @type {StyleExpression}
     *
     * @exception {DeveloperError} The style is not loaded.  Use {@link Cesium3DTileStyle#readyPromise} or wait for {@link Cesium3DTileStyle#ready} to be true.
     *
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override scaleByDistance expression with a string
     * style.scaleByDistance = 'vec4(1.5e2, 2.0, 1.5e7, 0.5)';
     * style.scaleByDistance.evaluate(feature); // returns a Cartesian4
     */
    scaleByDistance: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "The style is not loaded.  Use Cesium3DTileStyle.readyPromise or wait for Cesium3DTileStyle.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._scaleByDistance;
      },
      set: function (value) {
        this._scaleByDistance = getExpression(this, value);
        this._style.scaleByDistance = getJsonFromExpression(
          this._scaleByDistance
        );
      },
    },

    /**
     * Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>translucencyByDistance</code> property. Alternatively a string or object defining a vec4 style can be used.
     * The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
     * <p>
     * The expression must return a <code>Cartesian4</code>.
     * </p>
     * <p>
     * This expression is only applicable to point features in a Vector tile.
     * </p>
     *
     * @memberof Cesium3DTileStyle.prototype
     *
     * @type {StyleExpression}
     *
     * @exception {DeveloperError} The style is not loaded.  Use {@link Cesium3DTileStyle#readyPromise} or wait for {@link Cesium3DTileStyle#ready} to be true.
     *
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override translucencyByDistance expression with a string
     * style.translucencyByDistance = 'vec4(1.5e2, 1.0, 1.5e7, 0.2)';
     * style.translucencyByDistance.evaluate(feature); // returns a Cartesian4
     */
    translucencyByDistance: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "The style is not loaded.  Use Cesium3DTileStyle.readyPromise or wait for Cesium3DTileStyle.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._translucencyByDistance;
      },
      set: function (value) {
        this._translucencyByDistance = getExpression(this, value);
        this._style.translucencyByDistance = getJsonFromExpression(
          this._translucencyByDistance
        );
      },
    },

    /**
     * Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>distanceDisplayCondition</code> property. Alternatively a string or object defining a vec2 style can be used.
     * The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
     * <p>
     * The expression must return a <code>Cartesian2</code>.
     * </p>
     * <p>
     * This expression is only applicable to point features in a Vector tile.
     * </p>
     *
     * @memberof Cesium3DTileStyle.prototype
     *
     * @type {StyleExpression}
     *
     * @exception {DeveloperError} The style is not loaded.  Use {@link Cesium3DTileStyle#readyPromise} or wait for {@link Cesium3DTileStyle#ready} to be true.
     *
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override distanceDisplayCondition expression with a string
     * style.distanceDisplayCondition = 'vec2(0.0, 5.5e6)';
     * style.distanceDisplayCondition.evaluate(feature); // returns a Cartesian2
     */
    distanceDisplayCondition: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "The style is not loaded.  Use Cesium3DTileStyle.readyPromise or wait for Cesium3DTileStyle.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._distanceDisplayCondition;
      },
      set: function (value) {
        this._distanceDisplayCondition = getExpression(this, value);
        this._style.distanceDisplayCondition = getJsonFromExpression(
          this._distanceDisplayCondition
        );
      },
    },

    /**
     * Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>heightOffset</code> property. Alternatively a string or object defining a number style can be used.
     * The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
     * <p>
     * The expression must return a <code>Number</code>.
     * </p>
     * <p>
     * This expression is only applicable to point features in a Vector tile.
     * </p>
     *
     * @memberof Cesium3DTileStyle.prototype
     *
     * @type {StyleExpression}
     *
     * @exception {DeveloperError} The style is not loaded.  Use {@link Cesium3DTileStyle#readyPromise} or wait for {@link Cesium3DTileStyle#ready} to be true.
     *
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override heightOffset expression with a string
     * style.heightOffset = '2.0';
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override heightOffset expression with a condition
     * style.heightOffset = {
     *     conditions : [
     *         ['${height} > 2', '4.0'],
     *         ['true', '2.0']
     *     ]
     * };
     */
    heightOffset: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "The style is not loaded.  Use Cesium3DTileStyle.readyPromise or wait for Cesium3DTileStyle.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._heightOffset;
      },
      set: function (value) {
        this._heightOffset = getExpression(this, value);
        this._style.heightOffset = getJsonFromExpression(this._heightOffset);
      },
    },

    /**
     * Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>anchorLineEnabled</code> property. Alternatively a string or object defining a boolean style can be used.
     * The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
     * <p>
     * The expression must return a <code>Boolean</code>.
     * </p>
     * <p>
     * This expression is only applicable to point features in a Vector tile.
     * </p>
     *
     * @memberof Cesium3DTileStyle.prototype
     *
     * @type {StyleExpression}
     *
     * @exception {DeveloperError} The style is not loaded.  Use {@link Cesium3DTileStyle#readyPromise} or wait for {@link Cesium3DTileStyle#ready} to be true.
     *
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override anchorLineEnabled expression with a string
     * style.anchorLineEnabled = 'true';
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override anchorLineEnabled expression with a condition
     * style.anchorLineEnabled = {
     *     conditions : [
     *         ['${height} > 2', 'true'],
     *         ['true', 'false']
     *     ]
     * };
     */
    anchorLineEnabled: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "The style is not loaded.  Use Cesium3DTileStyle.readyPromise or wait for Cesium3DTileStyle.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._anchorLineEnabled;
      },
      set: function (value) {
        this._anchorLineEnabled = getExpression(this, value);
        this._style.anchorLineEnabled = getJsonFromExpression(
          this._anchorLineEnabled
        );
      },
    },

    /**
     * Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>anchorLineColor</code> property. Alternatively a string or object defining a color style can be used.
     * The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
     * <p>
     * The expression must return a <code>Color</code>.
     * </p>
     * <p>
     * This expression is only applicable to point features in a Vector tile.
     * </p>
     *
     * @memberof Cesium3DTileStyle.prototype
     *
     * @type {StyleExpression}
     *
     * @exception {DeveloperError} The style is not loaded.  Use {@link Cesium3DTileStyle#readyPromise} or wait for {@link Cesium3DTileStyle#ready} to be true.
     *
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override anchorLineColor expression with a string
     * style.anchorLineColor = 'color("blue")';
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override anchorLineColor expression with a condition
     * style.anchorLineColor = {
     *     conditions : [
     *         ['${height} > 2', 'color("cyan")'],
     *         ['true', 'color("blue")']
     *     ]
     * };
     */
    anchorLineColor: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "The style is not loaded.  Use Cesium3DTileStyle.readyPromise or wait for Cesium3DTileStyle.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._anchorLineColor;
      },
      set: function (value) {
        this._anchorLineColor = getExpression(this, value);
        this._style.anchorLineColor = getJsonFromExpression(
          this._anchorLineColor
        );
      },
    },

    /**
     * Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>image</code> property. Alternatively a string or object defining a string style can be used.
     * The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
     * <p>
     * The expression must return a <code>String</code>.
     * </p>
     * <p>
     * This expression is only applicable to point features in a Vector tile.
     * </p>
     *
     * @memberof Cesium3DTileStyle.prototype
     *
     * @type {StyleExpression}
     *
     * @exception {DeveloperError} The style is not loaded.  Use {@link Cesium3DTileStyle#readyPromise} or wait for {@link Cesium3DTileStyle#ready} to be true.
     *
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     *
     * @example
     * const style = new Cesium3DTileStyle({
     *     image : '(${Temperature} > 90) ? "/url/to/image1" : "/url/to/image2"'
     * });
     * style.image.evaluate(feature); // returns a String
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override image expression with a custom function
     * style.image = {
     *     evaluate : function(feature) {
     *         return '/url/to/image';
     *     }
     * };
     */
    image: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "The style is not loaded.  Use Cesium3DTileStyle.readyPromise or wait for Cesium3DTileStyle.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._image;
      },
      set: function (value) {
        this._image = getExpression(this, value);
        this._style.image = getJsonFromExpression(this._image);
      },
    },

    /**
     * Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>disableDepthTestDistance</code> property. Alternatively a string or object defining a number style can be used.
     * The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
     * <p>
     * The expression must return a <code>Number</code>.
     * </p>
     * <p>
     * This expression is only applicable to point features in a Vector tile.
     * </p>
     *
     * @memberof Cesium3DTileStyle.prototype
     *
     * @type {StyleExpression}
     *
     * @exception {DeveloperError} The style is not loaded.  Use {@link Cesium3DTileStyle#readyPromise} or wait for {@link Cesium3DTileStyle#ready} to be true.
     *
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override disableDepthTestDistance expression with a string
     * style.disableDepthTestDistance = '1000.0';
     * style.disableDepthTestDistance.evaluate(feature); // returns a Number
     */
    disableDepthTestDistance: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "The style is not loaded.  Use Cesium3DTileStyle.readyPromise or wait for Cesium3DTileStyle.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._disableDepthTestDistance;
      },
      set: function (value) {
        this._disableDepthTestDistance = getExpression(this, value);
        this._style.disableDepthTestDistance = getJsonFromExpression(
          this._disableDepthTestDistance
        );
      },
    },

    /**
     * Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>horizontalOrigin</code> property. Alternatively a string or object defining a number style can be used.
     * The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
     * <p>
     * The expression must return a <code>HorizontalOrigin</code>.
     * </p>
     * <p>
     * This expression is only applicable to point features in a Vector tile.
     * </p>
     *
     * @memberof Cesium3DTileStyle.prototype
     *
     * @type {StyleExpression}
     *
     * @exception {DeveloperError} The style is not loaded.  Use {@link Cesium3DTileStyle#readyPromise} or wait for {@link Cesium3DTileStyle#ready} to be true.
     *
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     *
     * @example
     * const style = new Cesium3DTileStyle({
     *     horizontalOrigin : HorizontalOrigin.LEFT
     * });
     * style.horizontalOrigin.evaluate(feature); // returns a HorizontalOrigin
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override horizontalOrigin expression with a custom function
     * style.horizontalOrigin = {
     *     evaluate : function(feature) {
     *         return HorizontalOrigin.CENTER;
     *     }
     * };
     */
    horizontalOrigin: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "The style is not loaded.  Use Cesium3DTileStyle.readyPromise or wait for Cesium3DTileStyle.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._horizontalOrigin;
      },
      set: function (value) {
        this._horizontalOrigin = getExpression(this, value);
        this._style.horizontalOrigin = getJsonFromExpression(
          this._horizontalOrigin
        );
      },
    },

    /**
     * Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>verticalOrigin</code> property. Alternatively a string or object defining a number style can be used.
     * The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
     * <p>
     * The expression must return a <code>VerticalOrigin</code>.
     * </p>
     * <p>
     * This expression is only applicable to point features in a Vector tile.
     * </p>
     *
     * @memberof Cesium3DTileStyle.prototype
     *
     * @type {StyleExpression}
     *
     * @exception {DeveloperError} The style is not loaded.  Use {@link Cesium3DTileStyle#readyPromise} or wait for {@link Cesium3DTileStyle#ready} to be true.
     *
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     *
     * @example
     * const style = new Cesium3DTileStyle({
     *     verticalOrigin : VerticalOrigin.TOP
     * });
     * style.verticalOrigin.evaluate(feature); // returns a VerticalOrigin
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override verticalOrigin expression with a custom function
     * style.verticalOrigin = {
     *     evaluate : function(feature) {
     *         return VerticalOrigin.CENTER;
     *     }
     * };
     */
    verticalOrigin: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "The style is not loaded.  Use Cesium3DTileStyle.readyPromise or wait for Cesium3DTileStyle.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._verticalOrigin;
      },
      set: function (value) {
        this._verticalOrigin = getExpression(this, value);
        this._style.verticalOrigin = getJsonFromExpression(this._verticalOrigin);
      },
    },

    /**
           Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>labelHorizontalOrigin</code> property. Alternatively a string or object defining a number style can be used.
           * The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
           * <p>
           * The expression must return a <code>HorizontalOrigin</code>.
           * </p>
           * <p>
           * This expression is only applicable to point features in a Vector tile.
           * </p>
           *
           * @memberof Cesium3DTileStyle.prototype
           *
           * @type {StyleExpression}
           *
           * @exception {DeveloperError} The style is not loaded.  Use {@link Cesium3DTileStyle#readyPromise} or wait for {@link Cesium3DTileStyle#ready} to be true.
           *
           * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
           *
           * @example
           * const style = new Cesium3DTileStyle({
           *     labelHorizontalOrigin : HorizontalOrigin.LEFT
           * });
           * style.labelHorizontalOrigin.evaluate(feature); // returns a HorizontalOrigin
           *
           * @example
           * const style = new Cesium.Cesium3DTileStyle();
           * // Override labelHorizontalOrigin expression with a custom function
           * style.labelHorizontalOrigin = {
           *     evaluate : function(feature) {
           *         return HorizontalOrigin.CENTER;
           *     }
           * };
           */
    labelHorizontalOrigin: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "The style is not loaded.  Use Cesium3DTileStyle.readyPromise or wait for Cesium3DTileStyle.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._labelHorizontalOrigin;
      },
      set: function (value) {
        this._labelHorizontalOrigin = getExpression(this, value);
        this._style.labelHorizontalOrigin = getJsonFromExpression(
          this._labelHorizontalOrigin
        );
      },
    },

    /**
     * Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>labelVerticalOrigin</code> property. Alternatively a string or object defining a number style can be used.
     * The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
     * <p>
     * The expression must return a <code>VerticalOrigin</code>.
     * </p>
     * <p>
     * This expression is only applicable to point features in a Vector tile.
     * </p>
     *
     * @memberof Cesium3DTileStyle.prototype
     *
     * @type {StyleExpression}
     *
     * @exception {DeveloperError} The style is not loaded.  Use {@link Cesium3DTileStyle#readyPromise} or wait for {@link Cesium3DTileStyle#ready} to be true.
     *
     * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
     *
     * @example
     * const style = new Cesium3DTileStyle({
     *     labelVerticalOrigin : VerticalOrigin.TOP
     * });
     * style.labelVerticalOrigin.evaluate(feature); // returns a VerticalOrigin
     *
     * @example
     * const style = new Cesium.Cesium3DTileStyle();
     * // Override labelVerticalOrigin expression with a custom function
     * style.labelVerticalOrigin = {
     *     evaluate : function(feature) {
     *         return VerticalOrigin.CENTER;
     *     }
     * };
     */
    labelVerticalOrigin: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "The style is not loaded.  Use Cesium3DTileStyle.readyPromise or wait for Cesium3DTileStyle.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._labelVerticalOrigin;
      },
      set: function (value) {
        this._labelVerticalOrigin = getExpression(this, value);
        this._style.labelVerticalOrigin = getJsonFromExpression(
          this._labelVerticalOrigin
        );
      },
    },

    /**
     * Gets or sets the object containing application-specific expression that can be explicitly
     * evaluated, e.g., for display in a UI.
     *
     * @memberof Cesium3DTileStyle.prototype
     *
     * @type {StyleExpression}
     *
     * @exception {DeveloperError} The style is not loaded.  Use {@link Cesium3DTileStyle#readyPromise} or wait for {@link Cesium3DTileStyle#ready} to be true.
     *
     * @example
     * const style = new Cesium3DTileStyle({
     *     meta : {
     *         description : '"Building id ${id} has height ${Height}."'
     *     }
     * });
     * style.meta.description.evaluate(feature); // returns a String with the substituted variables
     */
    meta: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "The style is not loaded.  Use Cesium3DTileStyle.readyPromise or wait for Cesium3DTileStyle.ready to be true."
          );
        }
        //>>includeEnd('debug');

        return this._meta;
      },
      set: function (value) {
        this._meta = value;
      },
    },
  });

  /**
   * Asynchronously creates a Cesium3DTileStyle from a url.
   *
   * @param {Resource|String} url The url of the style to be loaded.
   *
   * @returns {Promise.<Cesium3DTileStyle>} A promise which resolves to the created style
   *
   * @private
   */
  Cesium3DTileStyle.fromUrl = function (url) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(url)) {
      throw new DeveloperError("url is required");
    }
    //>>includeEnd('debug');

    const resource = Resource.createIfNeeded(url);
    return resource.fetchJson(url).then(function (styleJson) {
      return new Cesium3DTileStyle(styleJson);
    });
  };

  /**
   * Gets the color shader function for this style.
   *
   * @param {String} functionSignature Signature of the generated function.
   * @param {Object} variableSubstitutionMap Maps variable names to shader variable names.
   * @param {Object} shaderState Stores information about the generated shader function, including whether it is translucent.
   *
   * @returns {String} The shader function.
   *
   * @private
   */
  Cesium3DTileStyle.prototype.getColorShaderFunction = function (
    functionSignature,
    variableSubstitutionMap,
    shaderState
  ) {
    if (this._colorShaderFunctionReady) {
      shaderState.translucent = this._colorShaderTranslucent;
      // Return the cached result, may be undefined
      return this._colorShaderFunction;
    }

    this._colorShaderFunctionReady = true;
    if (defined(this.color) && defined(this.color.getShaderFunction)) {
      this._colorShaderFunction = this.color.getShaderFunction(
        functionSignature,
        variableSubstitutionMap,
        shaderState,
        "vec4"
      );
    } else {
      this._colorShaderFunction = undefined;
    }

    this._colorShaderTranslucent = shaderState.translucent;
    return this._colorShaderFunction;
  };

  /**
   * Gets the show shader function for this style.
   *
   * @param {String} functionSignature Signature of the generated function.
   * @param {Object} variableSubstitutionMap Maps variable names to shader variable names.
   * @param {Object} shaderState Stores information about the generated shader function, including whether it is translucent.
   *
   * @returns {String} The shader function.
   *
   * @private
   */
  Cesium3DTileStyle.prototype.getShowShaderFunction = function (
    functionSignature,
    variableSubstitutionMap,
    shaderState
  ) {
    if (this._showShaderFunctionReady) {
      // Return the cached result, may be undefined
      return this._showShaderFunction;
    }

    this._showShaderFunctionReady = true;

    if (defined(this.show) && defined(this.show.getShaderFunction)) {
      this._showShaderFunction = this.show.getShaderFunction(
        functionSignature,
        variableSubstitutionMap,
        shaderState,
        "bool"
      );
    } else {
      this._showShaderFunction = undefined;
    }
    return this._showShaderFunction;
  };

  /**
   * Gets the pointSize shader function for this style.
   *
   * @param {String} functionSignature Signature of the generated function.
   * @param {Object} variableSubstitutionMap Maps variable names to shader variable names.
   * @param {Object} shaderState Stores information about the generated shader function, including whether it is translucent.
   *
   * @returns {String} The shader function.
   *
   * @private
   */
  Cesium3DTileStyle.prototype.getPointSizeShaderFunction = function (
    functionSignature,
    variableSubstitutionMap,
    shaderState
  ) {
    if (this._pointSizeShaderFunctionReady) {
      // Return the cached result, may be undefined
      return this._pointSizeShaderFunction;
    }

    this._pointSizeShaderFunctionReady = true;
    if (defined(this.pointSize) && defined(this.pointSize.getShaderFunction)) {
      this._pointSizeShaderFunction = this.pointSize.getShaderFunction(
        functionSignature,
        variableSubstitutionMap,
        shaderState,
        "float"
      );
    } else {
      this._pointSizeShaderFunction = undefined;
    }

    return this._pointSizeShaderFunction;
  };

  /**
   * Gets the variables used by the style.
   *
   * @returns {String[]} The variables used by the style.
   *
   * @private
   */
  Cesium3DTileStyle.prototype.getVariables = function () {
    let variables = [];

    if (defined(this.color) && defined(this.color.getVariables)) {
      variables.push.apply(variables, this.color.getVariables());
    }

    if (defined(this.show) && defined(this.show.getVariables)) {
      variables.push.apply(variables, this.show.getVariables());
    }

    if (defined(this.pointSize) && defined(this.pointSize.getVariables)) {
      variables.push.apply(variables, this.pointSize.getVariables());
    }

    // Remove duplicates
    variables = variables.filter(function (variable, index, variables) {
      return variables.indexOf(variable) === index;
    });

    return variables;
  };

  /**
   * A ParticleEmitter that emits particles from a circle.
   * Particles will be positioned within a circle and have initial velocities going along the z vector.
   *
   * @alias CircleEmitter
   * @constructor
   *
   * @param {Number} [radius=1.0] The radius of the circle in meters.
   */
  function CircleEmitter(radius) {
    radius = defaultValue(radius, 1.0);

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number.greaterThan("radius", radius, 0.0);
    //>>includeEnd('debug');

    this._radius = defaultValue(radius, 1.0);
  }

  Object.defineProperties(CircleEmitter.prototype, {
    /**
     * The radius of the circle in meters.
     * @memberof CircleEmitter.prototype
     * @type {Number}
     * @default 1.0
     */
    radius: {
      get: function () {
        return this._radius;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number.greaterThan("value", value, 0.0);
        //>>includeEnd('debug');
        this._radius = value;
      },
    },
  });

  /**
   * Initializes the given {@link Particle} by setting it's position and velocity.
   *
   * @private
   * @param {Particle} particle The particle to initialize.
   */
  CircleEmitter.prototype.emit = function (particle) {
    const theta = CesiumMath.randomBetween(0.0, CesiumMath.TWO_PI);
    const rad = CesiumMath.randomBetween(0.0, this._radius);

    const x = rad * Math.cos(theta);
    const y = rad * Math.sin(theta);
    const z = 0.0;

    particle.position = Cartesian3.fromElements(x, y, z, particle.position);
    particle.velocity = Cartesian3.clone(Cartesian3.UNIT_Z, particle.velocity);
  };

  /**
   * Specifies the type of the cloud that is added to a {@link CloudCollection} in {@link CloudCollection#add}.
   *
   * @enum {Number}
   */

  const CloudType = {
    /**
     * Cumulus cloud.
     *
     * @type {Number}
     * @constant
     */
    CUMULUS: 0,
  };

  /**
   * Validates that the provided cloud type is a valid {@link CloudType}
   *
   * @param {CloudType} cloudType The cloud type to validate.
   * @returns {Boolean} <code>true</code> if the provided cloud type is a valid value; otherwise, <code>false</code>.
   *
   * @example
   * if (!Cesium.CloudType.validate(cloudType)) {
   *   throw new Cesium.DeveloperError('cloudType must be a valid value.');
   * }
   */

  CloudType.validate = function (cloudType) {
    return cloudType === CloudType.CUMULUS;
  };

  var CloudType$1 = Object.freeze(CloudType);

  //This file is automatically rebuilt by the Cesium build process.
  var CloudCollectionFS = "uniform sampler2D u_noiseTexture;\n\
uniform vec3 u_noiseTextureDimensions;\n\
uniform float u_noiseDetail;\n\
varying vec2 v_offset;\n\
varying vec3 v_maximumSize;\n\
varying vec4 v_color;\n\
varying float v_slice;\n\
varying float v_brightness;\n\
float wrap(float value, float rangeLength) {\n\
if(value < 0.0) {\n\
float absValue = abs(value);\n\
float modValue = mod(absValue, rangeLength);\n\
return mod(rangeLength - modValue, rangeLength);\n\
}\n\
return mod(value, rangeLength);\n\
}\n\
vec3 wrapVec(vec3 value, float rangeLength) {\n\
return vec3(wrap(value.x, rangeLength),\n\
wrap(value.y, rangeLength),\n\
wrap(value.z, rangeLength));\n\
}\n\
float textureSliceWidth = u_noiseTextureDimensions.x;\n\
float noiseTextureRows = u_noiseTextureDimensions.y;\n\
float inverseNoiseTextureRows = u_noiseTextureDimensions.z;\n\
float textureSliceWidthSquared = textureSliceWidth * textureSliceWidth;\n\
vec2 inverseNoiseTextureDimensions = vec2(noiseTextureRows / textureSliceWidthSquared,\n\
inverseNoiseTextureRows / textureSliceWidth);\n\
vec2 voxelToUV(vec3 voxelIndex) {\n\
vec3 wrappedIndex = wrapVec(voxelIndex, textureSliceWidth);\n\
float column = mod(wrappedIndex.z, textureSliceWidth * inverseNoiseTextureRows);\n\
float row = floor(wrappedIndex.z / textureSliceWidth * noiseTextureRows);\n\
float xPixelCoord = wrappedIndex.x + column * textureSliceWidth;\n\
float yPixelCoord = wrappedIndex.y + row * textureSliceWidth;\n\
return vec2(xPixelCoord, yPixelCoord) * inverseNoiseTextureDimensions;\n\
}\n\
vec4 lerpSamplesX(vec3 voxelIndex, float x) {\n\
vec2 uv0 = voxelToUV(voxelIndex);\n\
vec2 uv1 = voxelToUV(voxelIndex + vec3(1.0, 0.0, 0.0));\n\
vec4 sample0 = texture2D(u_noiseTexture, uv0);\n\
vec4 sample1 = texture2D(u_noiseTexture, uv1);\n\
return mix(sample0, sample1, x);\n\
}\n\
vec4 sampleNoiseTexture(vec3 position) {\n\
vec3 recenteredPos = position + vec3(textureSliceWidth / 2.0);\n\
vec3 lerpValue = fract(recenteredPos);\n\
vec3 voxelIndex = floor(recenteredPos);\n\
vec4 xLerp00 = lerpSamplesX(voxelIndex, lerpValue.x);\n\
vec4 xLerp01 = lerpSamplesX(voxelIndex + vec3(0.0, 0.0, 1.0), lerpValue.x);\n\
vec4 xLerp10 = lerpSamplesX(voxelIndex + vec3(0.0, 1.0, 0.0), lerpValue.x);\n\
vec4 xLerp11 = lerpSamplesX(voxelIndex + vec3(0.0, 1.0, 1.0), lerpValue.x);\n\
vec4 yLerp0 = mix(xLerp00, xLerp10, lerpValue.y);\n\
vec4 yLerp1 = mix(xLerp01, xLerp11, lerpValue.y);\n\
return mix(yLerp0, yLerp1, lerpValue.z);\n\
}\n\
bool intersectSphere(vec3 origin, vec3 dir, float slice,\n\
out vec3 point, out vec3 normal) {\n\
float A = dot(dir, dir);\n\
float B = dot(origin, dir);\n\
float C = dot(origin, origin) - 0.25;\n\
float discriminant = (B * B) - (A * C);\n\
if(discriminant < 0.0) {\n\
return false;\n\
}\n\
float root = sqrt(discriminant);\n\
float t = (-B - root) / A;\n\
if(t < 0.0) {\n\
t = (-B + root) / A;\n\
}\n\
point = origin + t * dir;\n\
if(slice >= 0.0) {\n\
point.z = (slice / 2.0) - 0.5;\n\
if(length(point) > 0.5) {\n\
return false;\n\
}\n\
}\n\
normal = normalize(point);\n\
point -= czm_epsilon2 * normal;\n\
return true;\n\
}\n\
bool intersectEllipsoid(vec3 origin, vec3 dir, vec3 center, vec3 scale, float slice,\n\
out vec3 point, out vec3 normal) {\n\
if(scale.x <= 0.01 || scale.y < 0.01 || scale.z < 0.01) {\n\
return false;\n\
}\n\
vec3 o = (origin - center) / scale;\n\
vec3 d = dir / scale;\n\
vec3 p, n;\n\
bool intersected = intersectSphere(o, d, slice, p, n);\n\
if(intersected) {\n\
point = (p * scale) + center;\n\
normal = n;\n\
}\n\
return intersected;\n\
}\n\
vec2 phaseShift2D(vec2 p, vec2 freq) {\n\
return (czm_pi / 2.0) * sin(freq.yx * p.yx);\n\
}\n\
vec2 phaseShift3D(vec3 p, vec2 freq) {\n\
return phaseShift2D(p.xy, freq) + czm_pi * vec2(sin(freq.x * p.z));\n\
}\n\
const float T0    = 0.6;\n\
const float k     = 0.1;\n\
const float C0    = 0.8;\n\
const float FX0   = 0.6;\n\
const float FY0   = 0.6;\n\
const int octaves = 5;\n\
float T(vec3 point) {\n\
vec2 sum = vec2(0.0);\n\
float Ci = C0;\n\
vec2 FXY = vec2(FX0, FY0);\n\
vec2 PXY = vec2(0.0);\n\
for(int i = 1; i <= octaves; i++) {\n\
PXY = phaseShift3D(point, FXY);\n\
Ci *= 0.707;\n\
FXY *= 2.0;\n\
vec2 sinTerm = sin(FXY * point.xy + PXY);\n\
sum += Ci * sinTerm + vec2(T0);\n\
}\n\
return k * sum.x * sum.y;\n\
}\n\
const float a = 0.5;\n\
const float t = 0.4;\n\
const float s = 0.25;\n\
float I(float Id, float Is, float It) {\n\
return (1.0 - a) * ((1.0 - t) * ((1.0 - s) * Id + s * Is) + t * It) + a;\n\
}\n\
const vec3 lightDir = normalize(vec3(0.2, -1.0, 0.7));\n\
vec4 drawCloud(vec3 rayOrigin, vec3 rayDir, vec3 cloudCenter, vec3 cloudScale, float cloudSlice,\n\
float brightness) {\n\
vec3 cloudPoint, cloudNormal;\n\
if(!intersectEllipsoid(rayOrigin, rayDir, cloudCenter, cloudScale, cloudSlice,\n\
cloudPoint, cloudNormal)) {\n\
return vec4(0.0);\n\
}\n\
float Id = clamp(dot(cloudNormal, -lightDir), 0.0, 1.0);\n\
float Is = max(pow(dot(-lightDir, -rayDir), 2.0), 0.0);\n\
float It = T(cloudPoint);\n\
float intensity = I(Id, Is, It);\n\
vec3 color = vec3(intensity * clamp(brightness, 0.1, 1.0));\n\
vec4 noise = sampleNoiseTexture(u_noiseDetail * cloudPoint);\n\
float W = noise.x;\n\
float W2 = noise.y;\n\
float W3 = noise.z;\n\
float ndDot = clamp(dot(cloudNormal, -rayDir), 0.0, 1.0);\n\
float TR = pow(ndDot, 3.0) - W;\n\
TR *= 1.3;\n\
float minusDot = 0.5 - ndDot;\n\
TR -= min(minusDot * W2, 0.0);\n\
TR -= 0.8 * (minusDot + 0.25) * W3;\n\
float shading = mix(1.0 - 0.8 * W * W, 1.0, Id * TR);\n\
shading = clamp(shading + 0.2, 0.3, 1.0);\n\
vec3 finalColor = mix(vec3(0.5), shading * color, 1.15);\n\
return vec4(finalColor, clamp(TR, 0.0, 1.0)) * v_color;\n\
}\n\
void main() {\n\
#ifdef DEBUG_BILLBOARDS\n\
gl_FragColor = vec4(0.0, 0.5, 0.5, 1.0);\n\
#endif\n\
vec2 coordinate = v_maximumSize.xy * v_offset;\n\
vec3 ellipsoidScale = 0.82 * v_maximumSize;\n\
vec3 ellipsoidCenter = vec3(0.0);\n\
float zOffset = max(ellipsoidScale.z - 10.0, 0.0);\n\
vec3 eye = vec3(0, 0, -10.0 - zOffset);\n\
vec3 rayDir = normalize(vec3(coordinate, 1.0) - eye);\n\
vec3 rayOrigin = eye;\n\
#ifdef DEBUG_ELLIPSOIDS\n\
vec3 point, normal;\n\
if(intersectEllipsoid(rayOrigin, rayDir, ellipsoidCenter, ellipsoidScale, v_slice,\n\
point, normal)) {\n\
gl_FragColor = v_brightness * v_color;\n\
}\n\
#else\n\
#ifndef DEBUG_BILLBOARDS\n\
vec4 cloud = drawCloud(rayOrigin, rayDir,\n\
ellipsoidCenter, ellipsoidScale, v_slice, v_brightness);\n\
if(cloud.w < 0.01) {\n\
discard;\n\
}\n\
gl_FragColor = cloud;\n\
#endif\n\
#endif\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var CloudCollectionVS = "#ifdef INSTANCED\n\
attribute vec2 direction;\n\
#endif\n\
attribute vec4 positionHighAndScaleX;\n\
attribute vec4 positionLowAndScaleY;\n\
attribute vec4 packedAttribute0;\n\
attribute vec4 packedAttribute1;\n\
attribute vec4 color;\n\
varying vec2 v_offset;\n\
varying vec3 v_maximumSize;\n\
varying vec4 v_color;\n\
varying float v_slice;\n\
varying float v_brightness;\n\
void main() {\n\
vec3 positionHigh = positionHighAndScaleX.xyz;\n\
vec3 positionLow = positionLowAndScaleY.xyz;\n\
vec2 scale = vec2(positionHighAndScaleX.w, positionLowAndScaleY.w);\n\
float show = packedAttribute0.x;\n\
float brightness = packedAttribute0.y;\n\
vec2 coordinates = packedAttribute0.wz;\n\
vec3 maximumSize = packedAttribute1.xyz;\n\
float slice = packedAttribute1.w;\n\
#ifdef INSTANCED\n\
vec2 dir = direction;\n\
#else\n\
vec2 dir = coordinates;\n\
#endif\n\
vec2 offset = dir - vec2(0.5, 0.5);\n\
vec2 scaledOffset = scale * offset;\n\
vec4 p = czm_translateRelativeToEye(positionHigh, positionLow);\n\
vec4 positionEC = czm_modelViewRelativeToEye * p;\n\
positionEC.xy += scaledOffset;\n\
positionEC.xyz *= show;\n\
gl_Position = czm_projection * positionEC;\n\
v_offset = offset;\n\
v_maximumSize = maximumSize;\n\
v_color = color;\n\
v_slice = slice;\n\
v_brightness = brightness;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var CloudNoiseFS = "uniform vec3 u_noiseTextureDimensions;\n\
uniform float u_noiseDetail;\n\
uniform vec3 u_noiseOffset;\n\
varying vec2 v_position;\n\
float textureSliceWidth = u_noiseTextureDimensions.x;\n\
float inverseNoiseTextureRows = u_noiseTextureDimensions.z;\n\
float wrap(float value, float rangeLength) {\n\
if(value < 0.0) {\n\
float absValue = abs(value);\n\
float modValue = mod(absValue, rangeLength);\n\
return mod(rangeLength - modValue, rangeLength);\n\
}\n\
return mod(value, rangeLength);\n\
}\n\
vec3 wrapVec(vec3 value, float rangeLength) {\n\
return vec3(wrap(value.x, rangeLength),\n\
wrap(value.y, rangeLength),\n\
wrap(value.z, rangeLength));\n\
}\n\
vec3 random3(vec3 p) {\n\
float dot1 = dot(p, vec3(127.1, 311.7, 932.8));\n\
float dot2 = dot(p, vec3(269.5, 183.3, 421.4));\n\
return fract(vec3(sin(dot1 - dot2), cos(dot1 * dot2), dot1 * dot2));\n\
}\n\
vec3 getWorleyCellPoint(vec3 centerCell, vec3 offset, float freq) {\n\
vec3 cell = centerCell + offset;\n\
cell = wrapVec(cell, textureSliceWidth / u_noiseDetail);\n\
cell += floor(u_noiseOffset / u_noiseDetail);\n\
vec3 p = offset + random3(cell);\n\
return p;\n\
}\n\
float worleyNoise(vec3 p, float freq) {\n\
vec3 centerCell = floor(p * freq);\n\
vec3 pointInCell = fract(p * freq);\n\
float shortestDistance = 1000.0;\n\
for(float z = -1.0; z <= 1.0; z++) {\n\
for(float y = -1.0; y <= 1.0; y++) {\n\
for(float x = -1.0; x <= 1.0; x++) {\n\
vec3 offset = vec3(x, y, z);\n\
vec3 point = getWorleyCellPoint(centerCell, offset, freq);\n\
float distance = length(pointInCell - point);\n\
if(distance < shortestDistance) {\n\
shortestDistance = distance;\n\
}\n\
}\n\
}\n\
}\n\
return shortestDistance;\n\
}\n\
const float MAX_FBM_ITERATIONS = 10.0;\n\
float worleyFBMNoise(vec3 p, float octaves, float scale) {\n\
float noise = 0.0;\n\
float freq = 1.0;\n\
float persistence = 0.625;\n\
for(float i = 0.0; i < MAX_FBM_ITERATIONS; i++) {\n\
if(i >= octaves) {\n\
break;\n\
}\n\
noise += worleyNoise(p * scale, freq * scale) * persistence;\n\
persistence *= 0.5;\n\
freq *= 2.0;\n\
}\n\
return noise;\n\
}\n\
void main() {\n\
float x = mod(v_position.x, textureSliceWidth);\n\
float y = mod(v_position.y, textureSliceWidth);\n\
float sliceRow = floor(v_position.y / textureSliceWidth);\n\
float z = floor(v_position.x / textureSliceWidth) + sliceRow * inverseNoiseTextureRows * textureSliceWidth;\n\
vec3 position = vec3(x, y, z);\n\
position /= u_noiseDetail;\n\
float worley0 = clamp(worleyFBMNoise(position, 3.0, 1.0), 0.0, 1.0);\n\
float worley1 = clamp(worleyFBMNoise(position, 3.0, 2.0), 0.0, 1.0);\n\
float worley2 = clamp(worleyFBMNoise(position, 3.0, 3.0), 0.0, 1.0);\n\
gl_FragColor = vec4(worley0, worley1, worley2, 1.0);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var CloudNoiseVS = "uniform vec3 u_noiseTextureDimensions;\n\
attribute vec2 position;\n\
varying vec2 v_position;\n\
void main()\n\
{\n\
gl_Position = vec4(position, 0.1, 1.0);\n\
float textureSliceWidth = u_noiseTextureDimensions.x;\n\
float noiseTextureRows = u_noiseTextureDimensions.y;\n\
float inverseNoiseTextureRows = u_noiseTextureDimensions.z;\n\
vec2 transformedPos = (position * 0.5) + vec2(0.5);\n\
transformedPos *= textureSliceWidth;\n\
transformedPos.x *= textureSliceWidth * inverseNoiseTextureRows;\n\
transformedPos.y *= noiseTextureRows;\n\
v_position = transformedPos;\n\
}\n\
";

  /**
   * A cumulus cloud billboard positioned in the 3D scene, that is created and rendered using a {@link CloudCollection}.
   * A cloud is created and its initial properties are set by calling {@link CloudCollection#add}.
   * and {@link CloudCollection#remove}.
   * <br /><br />
   * <div align='center'>
   * <img src='Images/CumulusCloud.png' width='400' height='300' /><br />
   * Example cumulus clouds
   * </div>
   * @alias CumulusCloud
   *
   * @performance Similar to {@link Billboard}, reading a property, e.g., {@link CumulusCloud#show},
   * takes constant time. Assigning to a property is constant time but results in
   * CPU to GPU traffic when {@link CloudCollection#update} is called.  The per-cloud traffic is
   * the same regardless of how many properties were updated.  If most clouds in a collection need to be
   * updated, it may be more efficient to clear the collection with {@link CloudCollection#removeAll}
   * and add new clouds instead of modifying each one.
   *
   * @see CloudCollection
   * @see CloudCollection#add
   *
   * @internalConstructor
   * @class
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Cloud%20Parameters.html|Cesium Sandcastle Cloud Parameters Demo}
   */
  function CumulusCloud(options, cloudCollection) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    this._show = defaultValue(options.show, true);

    this._position = Cartesian3.clone(
      defaultValue(options.position, Cartesian3.ZERO)
    );

    if (!defined(options.scale) && defined(options.maximumSize)) {
      this._maximumSize = Cartesian3.clone(options.maximumSize);
      this._scale = new Cartesian2(this._maximumSize.x, this._maximumSize.y);
    } else {
      this._scale = Cartesian2.clone(
        defaultValue(options.scale, new Cartesian2(20.0, 12.0))
      );

      const defaultMaxSize = new Cartesian3(
        this._scale.x,
        this._scale.y,
        Math.min(this._scale.x, this._scale.y) / 1.5
      );
      this._maximumSize = Cartesian3.clone(
        defaultValue(options.maximumSize, defaultMaxSize)
      );
    }

    this._slice = defaultValue(options.slice, -1.0);
    this._color = Color.clone(defaultValue(options.color, Color.WHITE));
    this._brightness = defaultValue(options.brightness, 1.0);
    this._cloudCollection = cloudCollection;
    this._index = -1; // Used by CloudCollection
  }

  const SHOW_INDEX$1 = (CumulusCloud.SHOW_INDEX = 0);
  const POSITION_INDEX$1 = (CumulusCloud.POSITION_INDEX = 1);
  const SCALE_INDEX$1 = (CumulusCloud.SCALE_INDEX = 2);
  const MAXIMUM_SIZE_INDEX$1 = (CumulusCloud.MAXIMUM_SIZE_INDEX = 3);
  const SLICE_INDEX$1 = (CumulusCloud.SLICE_INDEX = 4);
  const BRIGHTNESS_INDEX$1 = (CumulusCloud.BRIGHTNESS_INDEX = 5);
  const COLOR_INDEX$1 = (CumulusCloud.COLOR_INDEX = 6);
  CumulusCloud.NUMBER_OF_PROPERTIES = 7;

  function makeDirty(cloud, propertyChanged) {
    const cloudCollection = cloud._cloudCollection;
    if (defined(cloudCollection)) {
      cloudCollection._updateCloud(cloud, propertyChanged);
      cloud._dirty = true;
    }
  }

  Object.defineProperties(CumulusCloud.prototype, {
    /**
     * Determines if this cumulus cloud will be shown.  Use this to hide or show a cloud, instead
     * of removing it and re-adding it to the collection.
     * @memberof CumulusCloud.prototype
     * @type {Boolean}
     * @default true
     */
    show: {
      get: function () {
        return this._show;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.bool("value", value);
        //>>includeEnd('debug');

        if (this._show !== value) {
          this._show = value;
          makeDirty(this, SHOW_INDEX$1);
        }
      },
    },

    /**
     * Gets or sets the Cartesian position of this cumulus cloud.
     * @memberof CumulusCloud.prototype
     * @type {Cartesian3}
     */
    position: {
      get: function () {
        return this._position;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug)
        Check.typeOf.object("value", value);
        //>>includeEnd('debug');

        const position = this._position;
        if (!Cartesian3.equals(position, value)) {
          Cartesian3.clone(value, position);
          makeDirty(this, POSITION_INDEX$1);
        }
      },
    },

    /**
     * <p>Gets or sets the scale of the cumulus cloud billboard in meters.
     * The <code>scale</code> property will affect the size of the billboard,
     * but not the cloud's actual appearance.</p>
     * <div align='center'>
     * <table border='0' cellpadding='5'><tr>
     * <td align='center'>
     *   <code>cloud.scale = new Cesium.Cartesian2(12, 8);</code><br/>
     *   <img src='Images/CumulusCloud.scalex12y8.png' width='250' height='158' />
     * </td>
     * <td align='center'>
     *   <code>cloud.scale = new Cesium.Cartesian2(24, 10);</code><br/>
     *   <img src='Images/CumulusCloud.scalex24y10.png' width='250' height='158' />
     * </td>
     * </tr></table>
     * </div>
     *
     * <p>To modify the cloud's appearance, modify its <code>maximumSize</code>
     * and <code>slice</code> properties.</p>
     * @memberof CumulusCloud.prototype
     * @type {Cartesian2}
     *
     * @see CumulusCloud#maximumSize
     * @see CumulusCloud#slice
     */
    scale: {
      get: function () {
        return this._scale;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug)
        Check.typeOf.object("value", value);
        //>>includeEnd('debug');

        const scale = this._scale;
        if (!Cartesian2.equals(scale, value)) {
          Cartesian2.clone(value, scale);
          makeDirty(this, SCALE_INDEX$1);
        }
      },
    },

    /**
     * <p>Gets or sets the maximum size of the cumulus cloud rendered on the billboard.
     * This defines a maximum ellipsoid volume that the cloud can appear in.
     * Rather than guaranteeing a specific size, this specifies a boundary for the
     * cloud to appear in, and changing it can affect the shape of the cloud.</p>
     * <p>Changing the z-value of <code>maximumSize</code> has the most dramatic effect
     * on the cloud's appearance because it changes the depth of the cloud, and thus the
     * positions at which the cloud-shaping texture is sampled.</p>
     * <div align='center'>
     * <table border='0' cellpadding='5'>
     * <tr>
     *   <td align='center'>
     *     <code>cloud.maximumSize = new Cesium.Cartesian3(14, 9, 10);</code><br/>
     *     <img src='Images/CumulusCloud.maximumSizex14y9z10.png' width='250' height='158' />
     *   </td>
     *   <td align='center'>
     *     <code>cloud.maximumSize.x = 25;</code><br/>
     *     <img src='Images/CumulusCloud.maximumSizex25.png' width='250' height='158' />
     *   </td>
     * </tr>
     * <tr>
     *   <td align='center'>
     *     <code>cloud.maximumSize.y = 5;</code><br/>
     *     <img src='Images/CumulusCloud.maximumSizey5.png' width='250' height='158' />
     *   </td>
     *   <td align='center'>
     *     <code>cloud.maximumSize.z = 17;</code><br/>
     *     <img src='Images/CumulusCloud.maximumSizez17.png' width='250' height='158' />
     *   </td>
     * </tr>
     * </table>
     * </div>
     *
     * <p>To modify the billboard's actual size, modify the cloud's <code>scale</code> property.</p>
     * @memberof CumulusCloud.prototype
     * @type {Cartesian3}
     *
     * @see CumulusCloud#scale
     */
    maximumSize: {
      get: function () {
        return this._maximumSize;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug)
        Check.typeOf.object("value", value);
        //>>includeEnd('debug');

        const maximumSize = this._maximumSize;
        if (!Cartesian3.equals(maximumSize, value)) {
          Cartesian3.clone(value, maximumSize);
          makeDirty(this, MAXIMUM_SIZE_INDEX$1);
        }
      },
    },
    /**
     * Sets the color of the cloud
     * @memberof CumulusCloud.prototype
     * @type {Color}
     * @default Color.WHITE
     */
    color: {
      get: function () {
        return this._color;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug)
        Check.typeOf.object("value", value);
        //>>includeEnd('debug');

        const color = this._color;
        if (!Color.equals(color, value)) {
          Color.clone(value, color);
          makeDirty(this, COLOR_INDEX$1);
        }
      },
    },
    /**
     * <p>Gets or sets the "slice" of the cloud that is rendered on the billboard, i.e.
     * the specific cross-section of the cloud chosen for the billboard's appearance.
     * Given a value between 0 and 1, the slice specifies how deeply into the cloud
     * to intersect based on its maximum size in the z-direction.</p>
     * <div align='center'>
     * <table border='0' cellpadding='5'><tr>
     * <td align='center'><code>cloud.slice = 0.32;</code><br/><img src='Images/CumulusCloud.slice0.32.png' width='250' height='158' /></td>
     * <td align='center'><code>cloud.slice = 0.5;</code><br/><img src='Images/CumulusCloud.slice0.5.png' width='250' height='158' /></td>
     * <td align='center'><code>cloud.slice = 0.6;</code><br/><img src='Images/CumulusCloud.slice0.6.png' width='250' height='158' /></td>
     * </tr></table>
     * </div>
     *
     * <br />
     * <p>Due to the nature in which this slice is calculated,
     * values below <code>0.2</code> may result in cross-sections that are too small,
     * and the edge of the ellipsoid will be visible. Similarly, values above <code>0.7</code>
     * will cause the cloud to appear smaller. Values outside the range <code>[0.1, 0.9]</code>
     * should be avoided entirely because they do not produce desirable results.</p>
     *
     * <div align='center'>
     * <table border='0' cellpadding='5'><tr>
     * <td align='center'><code>cloud.slice = 0.08;</code><br/><img src='Images/CumulusCloud.slice0.08.png' width='250' height='158' /></td>
     * <td align='center'><code>cloud.slice = 0.8;</code><br/><img src='Images/CumulusCloud.slice0.8.png' width='250' height='158' /></td>
     * </tr></table>
     * </div>
     *
     * <p>If <code>slice</code> is set to a negative number, the cloud will not render a cross-section.
     * Instead, it will render the outside of the ellipsoid that is visible. For clouds with
     * small values of `maximumSize.z`, this can produce good-looking results, but for larger
     * clouds, this can result in a cloud that is undesirably warped to the ellipsoid volume.</p>
     *
     * <div align='center'>
     * <table border='0' cellpadding='5'><tr>
     * <td align='center'>
     *  <code>cloud.slice = -1.0;<br/>cloud.maximumSize.z = 18;</code><br/>
     *  <img src='Images/CumulusCloud.slice-1z18.png' width='250' height='158' />
     * </td>
     * <td align='center'>
     *   <code>cloud.slice = -1.0;<br/>cloud.maximumSize.z = 30;</code><br/>
     *   <img src='Images/CumulusCloud.slice-1z30.png' width='250' height='158' /></td>
     * </tr></table>
     * </div>
     *
     * @memberof CumulusCloud.prototype
     * @type {Number}
     * @default -1.0
     */
    slice: {
      get: function () {
        return this._slice;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug)
        Check.typeOf.number("value", value);
        //>>includeEnd('debug');

        const slice = this._slice;
        if (slice !== value) {
          this._slice = value;
          makeDirty(this, SLICE_INDEX$1);
        }
      },
    },

    /**
     * Gets or sets the brightness of the cloud. This can be used to give clouds
     * a darker, grayer appearance.
     * <br /><br />
     * <div align='center'>
     * <table border='0' cellpadding='5'><tr>
     * <td align='center'><code>cloud.brightness = 1.0;</code><br/><img src='Images/CumulusCloud.brightness1.png' width='250' height='158' /></td>
     * <td align='center'><code>cloud.brightness = 0.6;</code><br/><img src='Images/CumulusCloud.brightness0.6.png' width='250' height='158' /></td>
     * <td align='center'><code>cloud.brightness = 0.0;</code><br/><img src='Images/CumulusCloud.brightness0.png' width='250' height='158' /></td>
     * </tr></table>
     * </div>
     * @memberof CumulusCloud.prototype
     * @type {Number}
     * @default 1.0
     */
    brightness: {
      get: function () {
        return this._brightness;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug)
        Check.typeOf.number("value", value);
        //>>includeEnd('debug');

        const brightness = this._brightness;
        if (brightness !== value) {
          this._brightness = value;
          makeDirty(this, BRIGHTNESS_INDEX$1);
        }
      },
    },
  });

  CumulusCloud.prototype._destroy = function () {
    this._cloudCollection = undefined;
  };

  let attributeLocations$1;
  const scratchTextureDimensions = new Cartesian3();

  const attributeLocationsBatched = {
    positionHighAndScaleX: 0,
    positionLowAndScaleY: 1,
    packedAttribute0: 2, // show, brightness, direction
    packedAttribute1: 3, // cloudSize, slice
    color: 4,
  };

  const attributeLocationsInstanced = {
    direction: 0,
    positionHighAndScaleX: 1,
    positionLowAndScaleY: 2,
    packedAttribute0: 3, // show, brightness
    packedAttribute1: 4, // cloudSize, slice
    color: 5,
  };

  const SHOW_INDEX = CumulusCloud.SHOW_INDEX;
  const POSITION_INDEX = CumulusCloud.POSITION_INDEX;
  const SCALE_INDEX = CumulusCloud.SCALE_INDEX;
  const MAXIMUM_SIZE_INDEX = CumulusCloud.MAXIMUM_SIZE_INDEX;
  const SLICE_INDEX = CumulusCloud.SLICE_INDEX;
  const BRIGHTNESS_INDEX = CumulusCloud.BRIGHTNESS_INDEX;
  const NUMBER_OF_PROPERTIES = CumulusCloud.NUMBER_OF_PROPERTIES;
  const COLOR_INDEX = CumulusCloud.COLOR_INDEX;

  /**
   * A renderable collection of clouds in the 3D scene.
   * <br /><br />
   * <div align='center'>
   * <img src='Images/CumulusCloud.png' width='400' height='300' /><br />
   * Example cumulus clouds
   * </div>
   * <br /><br />
   * Clouds are added and removed from the collection using {@link CloudCollection#add}
   * and {@link CloudCollection#remove}.
   * @alias CloudCollection
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Boolean} [options.show=true] Whether to display the clouds.
   * @param {Number} [options.noiseDetail=16.0] Desired amount of detail in the noise texture.
   * @param {Number} [options.noiseOffset=Cartesian3.ZERO] Desired translation of data in noise texture.
   * @param {Boolean} [options.debugBillboards=false] For debugging only. Determines if the billboards are rendered with an opaque color.
   * @param {Boolean} [options.debugEllipsoids=false] For debugging only. Determines if the clouds will be rendered as opaque ellipsoids.
   * @see CloudCollection#add
   * @see CloudCollection#remove
   * @see CumulusCloud
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Clouds.html|Cesium Sandcastle Clouds Demo}
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Cloud%20Parameters.html|Cesium Sandcastle Cloud Parameters Demo}
   *
   * @example
   * // Create a cloud collection with two cumulus clouds
   * const clouds = scene.primitives.add(new Cesium.CloudCollection());
   * clouds.add({
   *   position : new Cesium.Cartesian3(1.0, 2.0, 3.0),
   *   maximumSize: new Cesium.Cartesian3(20.0, 12.0, 8.0)
   * });
   * clouds.add({
   *   position : new Cesium.Cartesian3(4.0, 5.0, 6.0),
   *   maximumSize: new Cesium.Cartesian3(15.0, 9.0, 9.0),
   *   slice: 0.5
   * });
   *
   */
  function CloudCollection(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    this._clouds = [];
    this._cloudsToUpdate = [];
    this._cloudsToUpdateIndex = 0;
    this._cloudsRemoved = false;
    this._createVertexArray = false;

    this._propertiesChanged = new Uint32Array(NUMBER_OF_PROPERTIES);

    this._noiseTexture = undefined;
    this._textureSliceWidth = 128;
    this._noiseTextureRows = 4;

    /**
     * <p>
     * Controls the amount of detail captured in the precomputed noise texture
     * used to render the cumulus clouds. In order for the texture to be tileable,
     * this must be a power of two. For best results, set this to be a power of two
     * between <code>8.0</code> and <code>32.0</code> (inclusive).
     * </p>
     *
     * <div align='center'>
     * <table border='0' cellpadding='5'><tr>
     * <td align='center'>
     *   <code>clouds.noiseDetail = 8.0;</code><br/>
     *   <img src='Images/CloudCollection.noiseDetail8.png' width='250' height='158' />
     * </td>
     * <td align='center'>
     *   <code>clouds.noiseDetail = 32.0;</code><br/>
     *   <img src='Images/CloudCollection.noiseDetail32.png' width='250' height='158' />
     * </td>
     * </tr></table>
     * </div>
     *
     * @type {Number}
     *
     * @default 16.0
     */
    this.noiseDetail = defaultValue(options.noiseDetail, 16.0);

    /**
     * <p>
     * Applies a translation to noise texture coordinates to generate different data.
     * This can be modified if the default noise does not generate good-looking clouds.
     * </p>
     *
     * <div align='center'>
     * <table border='0' cellpadding='5'><tr>
     * <td align='center'>
     *   <code>default</code><br/>
     *   <img src='Images/CloudCollection.noiseOffsetdefault.png' width='250' height='158' />
     * </td>
     * <td align='center'>
     *   <code>clouds.noiseOffset = new Cesium.Cartesian3(10, 20, 10);</code><br/>
     *   <img src='Images/CloudCollection.noiseOffsetx10y20z10.png' width='250' height='158' />
     * </td>
     * </tr></table>
     * </div>
     * @type {Cartesian3}
     *
     * @default Cartesian3.ZERO
     */
    this.noiseOffset = Cartesian3.clone(
      defaultValue(options.noiseOffset, Cartesian3.ZERO)
    );

    this._loading = false;
    this._ready = false;

    const that = this;
    this._uniforms = {
      u_noiseTexture: function () {
        return that._noiseTexture;
      },
      u_noiseTextureDimensions: getNoiseTextureDimensions(that),
      u_noiseDetail: function () {
        return that.noiseDetail;
      },
    };

    this._vaNoise = undefined;
    this._spNoise = undefined;

    this._spCreated = false;
    this._sp = undefined;
    this._rs = undefined;

    /**
     * Determines if billboards in this collection will be shown.
     *
     * @type {Boolean}
     * @default true
     */
    this.show = defaultValue(options.show, true);

    this._colorCommands = [];

    /**
     * This property is for debugging only; it is not for production use nor is it optimized.
     * <p>
     * Renders the billboards with one opaque color for the sake of debugging.
     * </p>
     *
     * @type {Boolean}
     *
     * @default false
     */
    this.debugBillboards = defaultValue(options.debugBillboards, false);
    this._compiledDebugBillboards = false;

    /**
     * This property is for debugging only; it is not for production use nor is it optimized.
     * <p>
     * Draws the clouds as opaque, monochrome ellipsoids for the sake of debugging.
     * If <code>debugBillboards</code> is also true, then the ellipsoids will draw on top of the billboards.
     * </p>
     *
     * @type {Boolean}
     *
     * @default false
     */
    this.debugEllipsoids = defaultValue(options.debugEllipsoids, false);
    this._compiledDebugEllipsoids = false;
  }

  // Wraps useful texture metrics into a single vec3 for less overhead.
  function getNoiseTextureDimensions(collection) {
    return function () {
      scratchTextureDimensions.x = collection._textureSliceWidth;
      scratchTextureDimensions.y = collection._noiseTextureRows;
      scratchTextureDimensions.z = 1.0 / collection._noiseTextureRows;
      return scratchTextureDimensions;
    };
  }

  Object.defineProperties(CloudCollection.prototype, {
    /**
     * Returns the number of clouds in this collection.
     * @memberof CloudCollection.prototype
     * @type {Number}
     */
    length: {
      get: function () {
        removeClouds(this);
        return this._clouds.length;
      },
    },
  });

  function destroyClouds(clouds) {
    const length = clouds.length;
    for (let i = 0; i < length; ++i) {
      if (clouds[i]) {
        clouds[i]._destroy();
      }
    }
  }

  /**
   * Creates and adds a cloud with the specified initial properties to the collection.
   * The added cloud is returned so it can be modified or removed from the collection later.
   *
   * @param {Object}[options] A template describing the cloud's properties as shown in Example 1.
   * @returns {CumulusCloud} The cloud that was added to the collection.
   *
   * @performance Calling <code>add</code> is expected constant time.  However, the collection's vertex buffer
   * is rewritten - an <code>O(n)</code> operation that also incurs CPU to GPU overhead.  For
   * best performance, add as many clouds as possible before calling <code>update</code>.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * // Example 1:  Add a cumulus cloud, specifying all the default values.
   * const c = clouds.add({
   *   show : true,
   *   position : Cesium.Cartesian3.ZERO,
   *   scale : new Cesium.Cartesian2(20.0, 12.0),
   *   maximumSize: new Cesium.Cartesian3(20.0, 12.0, 12.0),
   *   slice: -1.0,
   *   cloudType : CloudType.CUMULUS
   * });
   *
   * @example
   * // Example 2:  Specify only the cloud's cartographic position.
   * const c = clouds.add({
   *   position : Cesium.Cartesian3.fromDegrees(longitude, latitude, height)
   * });
   *
   * @see CloudCollection#remove
   * @see CloudCollection#removeAll
   */
  CloudCollection.prototype.add = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const cloudType = defaultValue(options.cloudType, CloudType$1.CUMULUS);
    //>>includeStart('debug', pragmas.debug);
    if (!CloudType$1.validate(cloudType)) {
      throw new DeveloperError("invalid cloud type");
    }
    //>>includeEnd('debug');

    let cloud;
    if (cloudType === CloudType$1.CUMULUS) {
      cloud = new CumulusCloud(options, this);
      cloud._index = this._clouds.length;
      this._clouds.push(cloud);
      this._createVertexArray = true;
    }

    return cloud;
  };

  /**
   * Removes a cloud from the collection.
   *
   * @param {CumulusCloud} cloud The cloud to remove.
   * @returns {Boolean} <code>true</code> if the cloud was removed; <code>false</code> if the cloud was not found in the collection.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * const c = clouds.add(...);
   * clouds.remove(c);  // Returns true
   *
   * @see CloudCollection#add
   * @see CloudCollection#removeAll
   * @see CumulusCloud#show
   */
  CloudCollection.prototype.remove = function (cloud) {
    if (this.contains(cloud)) {
      this._clouds[cloud._index] = undefined; // Removed later in removeClouds()
      this._cloudsRemoved = true;
      this._createVertexArray = true;
      cloud._destroy();
      return true;
    }

    return false;
  };

  /**
   * Removes all clouds from the collection.
   *
   * @performance <code>O(n)</code>.  It is more efficient to remove all the clouds
   * from a collection and then add new ones than to create a new collection entirely.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @example
   * clouds.add(...);
   * clouds.add(...);
   * clouds.removeAll();
   *
   * @see CloudCollection#add
   * @see CloudCollection#remove
   */
  CloudCollection.prototype.removeAll = function () {
    destroyClouds(this._clouds);
    this._clouds = [];
    this._cloudsToUpdate = [];
    this._cloudsToUpdateIndex = 0;
    this._cloudsRemoved = false;

    this._createVertexArray = true;
  };

  function removeClouds(cloudCollection) {
    if (cloudCollection._cloudsRemoved) {
      cloudCollection._cloudsRemoved = false;

      const newClouds = [];
      const clouds = cloudCollection._clouds;
      const length = clouds.length;
      for (let i = 0, j = 0; i < length; ++i) {
        const cloud = clouds[i];
        if (defined(cloud)) {
          clouds._index = j++;
          newClouds.push(cloud);
        }
      }

      cloudCollection._clouds = newClouds;
    }
  }

  CloudCollection.prototype._updateCloud = function (cloud, propertyChanged) {
    if (!cloud._dirty) {
      this._cloudsToUpdate[this._cloudsToUpdateIndex++] = cloud;
    }

    ++this._propertiesChanged[propertyChanged];
  };

  /**
   * Check whether this collection contains a given cloud.
   *
   * @param {CumulusCloud} [cloud] The cloud to check for.
   * @returns {Boolean} true if this collection contains the cloud, false otherwise.
   *
   * @see CloudCollection#get
   */
  CloudCollection.prototype.contains = function (cloud) {
    return defined(cloud) && cloud._cloudCollection === this;
  };

  /**
   * Returns the cloud in the collection at the specified index. Indices are zero-based
   * and increase as clouds are added. Removing a cloud shifts all clouds after
   * it to the left, changing their indices. This function is commonly used with
   * {@link CloudCollection#length} to iterate over all the clouds in the collection.
   *
   * @param {Number} index The zero-based index of the cloud.
   * @returns {CumulusCloud} The cloud at the specified index.
   *
   * @performance Expected constant time. If clouds were removed from the collection and
   * {@link CloudCollection#update} was not called, an implicit <code>O(n)</code>
   * operation is performed.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * // Toggle the show property of every cloud in the collection
   * const len = clouds.length;
   * for (let i = 0; i < len; ++i) {
   *   const c = clouds.get(i);
   *   c.show = !c.show;
   * }
   *
   * @see CloudCollection#length
   */
  CloudCollection.prototype.get = function (index) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("index", index);
    //>>includeEnd('debug');

    removeClouds(this);
    return this._clouds[index];
  };

  const texturePositions = new Float32Array([
    -1.0,
    -1.0,
    1.0,
    -1.0,
    1.0,
    1.0,
    -1.0,
    1.0,
  ]);

  const textureIndices = new Uint16Array([0, 1, 2, 0, 2, 3]);

  function createTextureVA(context) {
    const positionBuffer = Buffer$1.createVertexBuffer({
      context: context,
      typedArray: texturePositions,
      usage: BufferUsage$1.STATIC_DRAW,
    });
    const indexBuffer = Buffer$1.createIndexBuffer({
      context: context,
      typedArray: textureIndices,
      usage: BufferUsage$1.STATIC_DRAW,
      indexDatatype: IndexDatatype$1.UNSIGNED_SHORT,
    });

    const attributes = [
      {
        index: 0,
        vertexBuffer: positionBuffer,
        componentsPerAttribute: 2,
        componentDatatype: ComponentDatatype$1.FLOAT,
      },
    ];

    return new VertexArray({
      context: context,
      attributes: attributes,
      indexBuffer: indexBuffer,
    });
  }

  let getIndexBuffer;

  function getIndexBufferBatched(context) {
    const sixteenK = 16 * 1024;

    let indexBuffer = context.cache.cloudCollection_indexBufferBatched;
    if (defined(indexBuffer)) {
      return indexBuffer;
    }

    // Subtract 6 because the last index is reserved for primitive restart.
    // https://www.khronos.org/registry/webgl/specs/latest/2.0/#5.18
    const length = sixteenK * 6 - 6;
    const indices = new Uint16Array(length);
    for (let i = 0, j = 0; i < length; i += 6, j += 4) {
      indices[i] = j;
      indices[i + 1] = j + 1;
      indices[i + 2] = j + 2;

      indices[i + 3] = j;
      indices[i + 4] = j + 2;
      indices[i + 5] = j + 3;
    }

    indexBuffer = Buffer$1.createIndexBuffer({
      context: context,
      typedArray: indices,
      usage: BufferUsage$1.STATIC_DRAW,
      indexDatatype: IndexDatatype$1.UNSIGNED_SHORT,
    });
    indexBuffer.vertexArrayDestroyable = false;
    context.cache.cloudCollection_indexBufferBatched = indexBuffer;
    return indexBuffer;
  }

  function getIndexBufferInstanced(context) {
    let indexBuffer = context.cache.cloudCollection_indexBufferInstanced;
    if (defined(indexBuffer)) {
      return indexBuffer;
    }

    indexBuffer = Buffer$1.createIndexBuffer({
      context: context,
      typedArray: new Uint16Array([0, 1, 2, 0, 2, 3]),
      usage: BufferUsage$1.STATIC_DRAW,
      indexDatatype: IndexDatatype$1.UNSIGNED_SHORT,
    });

    indexBuffer.vertexArrayDestroyable = false;
    context.cache.cloudCollection_indexBufferInstanced = indexBuffer;
    return indexBuffer;
  }

  function getVertexBufferInstanced(context) {
    let vertexBuffer = context.cache.cloudCollection_vertexBufferInstanced;
    if (defined(vertexBuffer)) {
      return vertexBuffer;
    }

    vertexBuffer = Buffer$1.createVertexBuffer({
      context: context,
      typedArray: new Float32Array([0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0]),
      usage: BufferUsage$1.STATIC_DRAW,
    });

    vertexBuffer.vertexArrayDestroyable = false;
    context.cache.cloudCollection_vertexBufferInstanced = vertexBuffer;
    return vertexBuffer;
  }

  function createVAF(context, numberOfClouds, instanced) {
    const attributes = [
      {
        index: attributeLocations$1.positionHighAndScaleX,
        componentsPerAttribute: 4,
        componentDatatype: ComponentDatatype$1.FLOAT,
        usage: BufferUsage$1.STATIC_DRAW,
      },
      {
        index: attributeLocations$1.positionLowAndScaleY,
        componentsPerAttribute: 4,
        componentDatatype: ComponentDatatype$1.FLOAT,
        usage: BufferUsage$1.STATIC_DRAW,
      },
      {
        index: attributeLocations$1.packedAttribute0,
        componentsPerAttribute: 4,
        componentDatatype: ComponentDatatype$1.FLOAT,
        usage: BufferUsage$1.STATIC_DRAW,
      },
      {
        index: attributeLocations$1.packedAttribute1,
        componentsPerAttribute: 4,
        componentDatatype: ComponentDatatype$1.FLOAT,
        usage: BufferUsage$1.STATIC_DRAW,
      },
      {
        index: attributeLocations$1.color,
        componentsPerAttribute: 4,
        componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
        normalize: true,
        usage: BufferUsage$1.STATIC_DRAW,
      },
    ];

    if (instanced) {
      attributes.push({
        index: attributeLocations$1.direction,
        componentsPerAttribute: 2,
        componentDatatype: ComponentDatatype$1.FLOAT,
        vertexBuffer: getVertexBufferInstanced(context),
      });
    }

    const sizeInVertices = instanced ? numberOfClouds : 4 * numberOfClouds;
    return new VertexArrayFacade(context, attributes, sizeInVertices, instanced);
  }

  const writePositionScratch = new EncodedCartesian3();

  function writePositionAndScale(cloudCollection, frameState, vafWriters, cloud) {
    let i;
    const positionHighWriter =
      vafWriters[attributeLocations$1.positionHighAndScaleX];
    const positionLowWriter = vafWriters[attributeLocations$1.positionLowAndScaleY];
    const position = cloud.position;

    EncodedCartesian3.fromCartesian(position, writePositionScratch);
    const scale = cloud.scale;

    const high = writePositionScratch.high;
    const low = writePositionScratch.low;

    if (cloudCollection._instanced) {
      i = cloud._index;
      positionHighWriter(i, high.x, high.y, high.z, scale.x);
      positionLowWriter(i, low.x, low.y, low.z, scale.y);
    } else {
      i = cloud._index * 4;
      positionHighWriter(i + 0, high.x, high.y, high.z, scale.x);
      positionHighWriter(i + 1, high.x, high.y, high.z, scale.x);
      positionHighWriter(i + 2, high.x, high.y, high.z, scale.x);
      positionHighWriter(i + 3, high.x, high.y, high.z, scale.x);

      positionLowWriter(i + 0, low.x, low.y, low.z, scale.y);
      positionLowWriter(i + 1, low.x, low.y, low.z, scale.y);
      positionLowWriter(i + 2, low.x, low.y, low.z, scale.y);
      positionLowWriter(i + 3, low.x, low.y, low.z, scale.y);
    }
  }

  function writePackedAttribute0(cloudCollection, frameState, vafWriters, cloud) {
    let i;
    const writer = vafWriters[attributeLocations$1.packedAttribute0];
    const show = cloud.show;
    const brightness = cloud.brightness;

    if (cloudCollection._instanced) {
      i = cloud._index;
      writer(i, show, brightness, 0.0, 0.0);
    } else {
      i = cloud._index * 4;
      writer(i + 0, show, brightness, 0.0, 0.0);
      writer(i + 1, show, brightness, 1.0, 0.0);
      writer(i + 2, show, brightness, 1.0, 1.0);
      writer(i + 3, show, brightness, 0.0, 1.0);
    }
  }

  function writePackedAttribute1(cloudCollection, frameState, vafWriters, cloud) {
    let i;
    const writer = vafWriters[attributeLocations$1.packedAttribute1];
    const maximumSize = cloud.maximumSize;
    const slice = cloud.slice;

    if (cloudCollection._instanced) {
      i = cloud._index;
      writer(i, maximumSize.x, maximumSize.y, maximumSize.z, slice);
    } else {
      i = cloud._index * 4;
      writer(i + 0, maximumSize.x, maximumSize.y, maximumSize.z, slice);
      writer(i + 1, maximumSize.x, maximumSize.y, maximumSize.z, slice);
      writer(i + 2, maximumSize.x, maximumSize.y, maximumSize.z, slice);
      writer(i + 3, maximumSize.x, maximumSize.y, maximumSize.z, slice);
    }
  }

  function writeColor(cloudCollection, frameState, vafWriters, cloud) {
    let i;
    const writer = vafWriters[attributeLocations$1.color];
    const color = cloud.color;
    const red = Color.floatToByte(color.red);
    const green = Color.floatToByte(color.green);
    const blue = Color.floatToByte(color.blue);
    const alpha = Color.floatToByte(color.alpha);

    if (cloudCollection._instanced) {
      i = cloud._index;
      writer(i, red, green, blue, alpha);
    } else {
      i = cloud._index * 4;
      writer(i + 0, red, green, blue, alpha);
      writer(i + 1, red, green, blue, alpha);
      writer(i + 2, red, green, blue, alpha);
      writer(i + 3, red, green, blue, alpha);
    }
  }
  function writeCloud(cloudCollection, frameState, vafWriters, cloud) {
    writePositionAndScale(cloudCollection, frameState, vafWriters, cloud);
    writePackedAttribute0(cloudCollection, frameState, vafWriters, cloud);
    writePackedAttribute1(cloudCollection, frameState, vafWriters, cloud);
    writeColor(cloudCollection, frameState, vafWriters, cloud);
  }

  function createNoiseTexture(cloudCollection, frameState, vsSource, fsSource) {
    const that = cloudCollection;

    const textureSliceWidth = that._textureSliceWidth;
    const noiseTextureRows = that._noiseTextureRows;
    //>>includeStart('debug', pragmas.debug);
    if (
      textureSliceWidth / noiseTextureRows < 1 ||
      textureSliceWidth % noiseTextureRows !== 0
    ) {
      throw new DeveloperError(
        "noiseTextureRows must evenly divide textureSliceWidth"
      );
    }
    //>>includeEnd('debug');

    const context = frameState.context;
    that._vaNoise = createTextureVA(context);
    that._spNoise = ShaderProgram.fromCache({
      context: context,
      vertexShaderSource: vsSource,
      fragmentShaderSource: fsSource,
      attributeLocations: {
        position: 0,
      },
    });

    const noiseDetail = that.noiseDetail;
    const noiseOffset = that.noiseOffset;

    that._noiseTexture = new Texture({
      context: context,
      width: (textureSliceWidth * textureSliceWidth) / noiseTextureRows,
      height: textureSliceWidth * noiseTextureRows,
      pixelDatatype: PixelDatatype$1.UNSIGNED_BYTE,
      pixelFormat: PixelFormat$1.RGBA,
      sampler: new Sampler({
        wrapS: TextureWrap$1.REPEAT,
        wrapT: TextureWrap$1.REPEAT,
        minificationFilter: TextureMinificationFilter$1.NEAREST,
        magnificationFilter: TextureMagnificationFilter$1.NEAREST,
      }),
    });

    const textureCommand = new ComputeCommand({
      vertexArray: that._vaNoise,
      shaderProgram: that._spNoise,
      outputTexture: that._noiseTexture,
      uniformMap: {
        u_noiseTextureDimensions: getNoiseTextureDimensions(that),
        u_noiseDetail: function () {
          return noiseDetail;
        },
        u_noiseOffset: function () {
          return noiseOffset;
        },
      },
      persists: false,
      owner: cloudCollection,
      postExecute: function (texture) {
        that._ready = true;
        that._loading = false;
      },
    });

    frameState.commandList.push(textureCommand);
    that._loading = true;
  }

  function createVertexArray(cloudCollection, frameState) {
    const that = cloudCollection;
    const context = frameState.context;
    that._createVertexArray = false;
    that._vaf = that._vaf && that._vaf.destroy();

    const clouds = cloudCollection._clouds;
    const cloudsLength = clouds.length;
    if (cloudsLength > 0) {
      that._vaf = createVAF(context, cloudsLength, that._instanced);
      const vafWriters = that._vaf.writers;

      let i;
      // Rewrite entire buffer if clouds were added or removed.
      for (i = 0; i < cloudsLength; ++i) {
        const cloud = clouds[i];
        writeCloud(cloudCollection, frameState, vafWriters, cloud);
      }

      // Different cloud collections share the same index buffer.
      that._vaf.commit(getIndexBuffer(context));
    }
  }

  const scratchWriterArray = [];

  function updateClouds(cloudCollection, frameState) {
    const context = frameState.context;
    const that = cloudCollection;
    const clouds = that._clouds;
    const cloudsLength = clouds.length;
    const cloudsToUpdate = that._cloudsToUpdate;
    const cloudsToUpdateLength = that._cloudsToUpdateIndex;

    const properties = that._propertiesChanged;

    const writers = scratchWriterArray;
    writers.length = 0;

    if (properties[POSITION_INDEX] || properties[SCALE_INDEX]) {
      writers.push(writePositionAndScale);
    }

    if (properties[SHOW_INDEX] || properties[BRIGHTNESS_INDEX]) {
      writers.push(writePackedAttribute0);
    }

    if (properties[MAXIMUM_SIZE_INDEX] || properties[SLICE_INDEX]) {
      writers.push(writePackedAttribute1);
    }

    if (properties[COLOR_INDEX]) {
      writers.push(writeColor);
    }

    const numWriters = writers.length;
    const vafWriters = that._vaf.writers;

    let i, c, w;
    if (cloudsToUpdateLength / cloudsLength > 0.1) {
      // Like BillboardCollection, if more than 10% of clouds change,
      // rewrite the entire buffer.

      for (i = 0; i < cloudsToUpdateLength; ++i) {
        c = cloudsToUpdate[i];
        c._dirty = false;

        for (w = 0; w < numWriters; ++w) {
          writers[w](cloudCollection, frameState, vafWriters, c);
        }
      }

      that._vaf.commit(getIndexBuffer(context));
    } else {
      for (i = 0; i < cloudsToUpdateLength; ++i) {
        c = cloudsToUpdate[i];
        c._dirty = false;

        for (w = 0; w < numWriters; ++w) {
          writers[w](cloudCollection, frameState, vafWriters, c);
        }

        if (that._instanced) {
          that._vaf.subCommit(c._index, 1);
        } else {
          that._vaf.subCommit(c._index * 4, 4);
        }
      }
      that._vaf.endSubCommits();
    }

    that._cloudsToUpdateIndex = 0;
  }

  function createShaderProgram(cloudCollection, frameState, vsSource, fsSource) {
    const context = frameState.context;
    const that = cloudCollection;
    const vs = new ShaderSource({
      defines: [],
      sources: [vsSource],
    });

    if (that._instanced) {
      vs.defines.push("INSTANCED");
    }

    const fs = new ShaderSource({
      defines: [],
      sources: [fsSource],
    });

    if (that.debugBillboards) {
      fs.defines.push("DEBUG_BILLBOARDS");
    }

    if (that.debugEllipsoids) {
      fs.defines.push("DEBUG_ELLIPSOIDS");
    }

    that._sp = ShaderProgram.replaceCache({
      context: context,
      shaderProgram: that._sp,
      vertexShaderSource: vs,
      fragmentShaderSource: fs,
      attributeLocations: attributeLocations$1,
    });

    that._rs = RenderState.fromCache({
      depthTest: {
        enabled: true,
        func: WebGLConstants$1.LESS,
      },
      depthMask: false,
      blending: BlendingState$1.ALPHA_BLEND,
    });

    that._spCreated = true;
    that._compiledDebugBillboards = that.debugBillboards;
    that._compiledDebugEllipsoids = that.debugEllipsoids;
  }

  function createDrawCommands(cloudCollection, frameState) {
    const that = cloudCollection;
    const pass = frameState.passes;
    const uniforms = that._uniforms;
    const commandList = frameState.commandList;
    if (pass.render) {
      const colorList = that._colorCommands;

      const va = that._vaf.va;
      const vaLength = va.length;
      colorList.length = vaLength;
      for (let i = 0; i < vaLength; i++) {
        let command = colorList[i];
        if (!defined(command)) {
          command = colorList[i] = new DrawCommand();
        }
        command.pass = Pass$1.TRANSLUCENT;
        command.owner = cloudCollection;
        command.uniformMap = uniforms;
        command.count = va[i].indicesCount;
        command.vertexArray = va[i].va;
        command.shaderProgram = that._sp;
        command.renderState = that._rs;
        if (that._instanced) {
          command.count = 6;
          command.instanceCount = that._clouds.length;
        }

        commandList.push(command);
      }
    }
  }

  /**
   * @private
   */
  CloudCollection.prototype.update = function (frameState) {
    removeClouds(this);
    if (!this.show) {
      return;
    }

    const debugging = this.debugBillboards || this.debugEllipsoids;
    this._ready = debugging ? true : defined(this._noiseTexture);

    if (!this._ready && !this._loading && !debugging) {
      createNoiseTexture(this, frameState, CloudNoiseVS, CloudNoiseFS);
    }

    this._instanced = frameState.context.instancedArrays;
    attributeLocations$1 = this._instanced
      ? attributeLocationsInstanced
      : attributeLocationsBatched;
    getIndexBuffer = this._instanced
      ? getIndexBufferInstanced
      : getIndexBufferBatched;

    const clouds = this._clouds;
    const cloudsLength = clouds.length;
    const cloudsToUpdate = this._cloudsToUpdate;
    const cloudsToUpdateLength = this._cloudsToUpdateIndex;

    if (this._createVertexArray) {
      createVertexArray(this, frameState);
    } else if (cloudsToUpdateLength > 0) {
      // Clouds were modified, but none were added or removed.
      updateClouds(this, frameState);
    }

    // If the number of total clouds ever shrinks considerably,
    // truncate cloudsToUpdate so that we free memory that
    // we are no longer using.
    if (cloudsToUpdateLength > cloudsLength * 1.5) {
      cloudsToUpdate.length = cloudsLength;
    }

    if (
      !defined(this._vaf) ||
      !defined(this._vaf.va) ||
      !this._ready & !debugging
    ) {
      return;
    }

    if (
      !this._spCreated ||
      this.debugBillboards !== this._compiledDebugBillboards ||
      this.debugEllipsoids !== this._compiledDebugEllipsoids
    ) {
      createShaderProgram(this, frameState, CloudCollectionVS, CloudCollectionFS);
    }

    createDrawCommands(this, frameState);
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see CloudCollection#destroy
   */
  CloudCollection.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * clouds = clouds && clouds.destroy();
   *
   * @see CloudCollection#isDestroyed
   */
  CloudCollection.prototype.destroy = function () {
    this._noiseTexture = this._noiseTexture && this._noiseTexture.destroy();
    this._sp = this._sp && this._sp.destroy();
    this._vaf = this._vaf && this._vaf.destroy();

    destroyClouds(this._clouds);

    return destroyObject(this);
  };

  const defaultAngle = CesiumMath.toRadians(30.0);

  /**
   * A ParticleEmitter that emits particles within a cone.
   * Particles will be positioned at the tip of the cone and have initial velocities going towards the base.
   *
   * @alias ConeEmitter
   * @constructor
   *
   * @param {Number} [angle=Cesium.Math.toRadians(30.0)] The angle of the cone in radians.
   */
  function ConeEmitter(angle) {
    this._angle = defaultValue(angle, defaultAngle);
  }

  Object.defineProperties(ConeEmitter.prototype, {
    /**
     * The angle of the cone in radians.
     * @memberof CircleEmitter.prototype
     * @type {Number}
     * @default Cesium.Math.toRadians(30.0)
     */
    angle: {
      get: function () {
        return this._angle;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number("value", value);
        //>>includeEnd('debug');
        this._angle = value;
      },
    },
  });

  /**
   * Initializes the given {Particle} by setting it's position and velocity.
   *
   * @private
   * @param {Particle} particle The particle to initialize
   */
  ConeEmitter.prototype.emit = function (particle) {
    const radius = Math.tan(this._angle);

    // Compute a random point on the cone's base
    const theta = CesiumMath.randomBetween(0.0, CesiumMath.TWO_PI);
    const rad = CesiumMath.randomBetween(0.0, radius);

    const x = rad * Math.cos(theta);
    const y = rad * Math.sin(theta);
    const z = 1.0;

    particle.velocity = Cartesian3.fromElements(x, y, z, particle.velocity);
    Cartesian3.normalize(particle.velocity, particle.velocity);
    particle.position = Cartesian3.clone(Cartesian3.ZERO, particle.position);
  };

  const mobileWidth = 576;
  const lightboxHeight = 100;
  const textColor = "#ffffff";
  const highlightColor$1 = "#48b";

  /**
   * Used to sort the credits by frequency of appearance
   * when they are later displayed.
   *
   * @alias CreditDisplay.CreditDisplayElement
   * @constructor
   *
   * @private
   */
  function CreditDisplayElement(credit, count) {
    this.credit = credit;
    this.count = defaultValue(count, 1);
  }

  function contains(credits, credit) {
    const len = credits.length;
    for (let i = 0; i < len; i++) {
      const existingCredit = credits[i];
      if (Credit.equals(existingCredit, credit)) {
        return true;
      }
    }
    return false;
  }

  function swapCesiumCredit(creditDisplay) {
    // We don't want to clutter the screen with the Cesium logo and the Cesium ion
    // logo at the same time. Since the ion logo is required, we just replace the
    // Cesium logo or add the logo if the Cesium one was removed.
    const previousCredit = creditDisplay._previousCesiumCredit;
    const currentCredit = creditDisplay._currentCesiumCredit;
    if (Credit.equals(currentCredit, previousCredit)) {
      return;
    }

    if (defined(previousCredit)) {
      creditDisplay._cesiumCreditContainer.removeChild(previousCredit.element);
    }
    if (defined(currentCredit)) {
      creditDisplay._cesiumCreditContainer.appendChild(currentCredit.element);
    }

    creditDisplay._previousCesiumCredit = currentCredit;
  }

  const delimiterClassName = "cesium-credit-delimiter";

  function createDelimiterElement(delimiter) {
    const delimiterElement = document.createElement("span");
    delimiterElement.textContent = delimiter;
    delimiterElement.className = delimiterClassName;
    return delimiterElement;
  }

  function createCreditElement(element, elementWrapperTagName) {
    // may need to wrap the credit in another element
    if (defined(elementWrapperTagName)) {
      const wrapper = document.createElement(elementWrapperTagName);
      wrapper._creditId = element._creditId;
      wrapper.appendChild(element);
      element = wrapper;
    }
    return element;
  }

  function displayCredits(container, credits, delimiter, elementWrapperTagName) {
    const childNodes = container.childNodes;
    let domIndex = -1;

    // Sort the credits such that more frequent credits appear first
    credits.sort(function (credit1, credit2) {
      return credit2.count - credit1.count;
    });

    for (let creditIndex = 0; creditIndex < credits.length; ++creditIndex) {
      const credit = credits[creditIndex].credit;
      if (defined(credit)) {
        domIndex = creditIndex;
        if (defined(delimiter)) {
          // credits may be separated by delimiters
          domIndex *= 2;
          if (creditIndex > 0) {
            const delimiterDomIndex = domIndex - 1;
            if (childNodes.length <= delimiterDomIndex) {
              container.appendChild(createDelimiterElement(delimiter));
            } else {
              const existingDelimiter = childNodes[delimiterDomIndex];
              if (existingDelimiter.className !== delimiterClassName) {
                container.replaceChild(
                  createDelimiterElement(delimiter),
                  existingDelimiter
                );
              }
            }
          }
        }

        const element = credit.element;

        // check to see if the correct credit is in the right place
        if (childNodes.length <= domIndex) {
          container.appendChild(
            createCreditElement(element, elementWrapperTagName)
          );
        } else {
          const existingElement = childNodes[domIndex];
          if (existingElement._creditId !== credit._id) {
            // not the right credit, swap it in
            container.replaceChild(
              createCreditElement(element, elementWrapperTagName),
              existingElement
            );
          }
        }
      }
    }

    // any remaining nodes in the container are unnecessary
    ++domIndex;
    while (domIndex < childNodes.length) {
      container.removeChild(childNodes[domIndex]);
    }
  }

  function styleLightboxContainer(that) {
    const lightboxCredits = that._lightboxCredits;
    const width = that.viewport.clientWidth;
    const height = that.viewport.clientHeight;
    if (width !== that._lastViewportWidth) {
      if (width < mobileWidth) {
        lightboxCredits.className =
          "cesium-credit-lightbox cesium-credit-lightbox-mobile";
        lightboxCredits.style.marginTop = "0";
      } else {
        lightboxCredits.className =
          "cesium-credit-lightbox cesium-credit-lightbox-expanded";
        lightboxCredits.style.marginTop = `${Math.floor(
        (height - lightboxCredits.clientHeight) * 0.5
      )}px`;
      }
      that._lastViewportWidth = width;
    }

    if (width >= mobileWidth && height !== that._lastViewportHeight) {
      lightboxCredits.style.marginTop = `${Math.floor(
      (height - lightboxCredits.clientHeight) * 0.5
    )}px`;
      that._lastViewportHeight = height;
    }
  }

  function addStyle(selector, styles) {
    let style = `${selector} {`;
    for (const attribute in styles) {
      if (styles.hasOwnProperty(attribute)) {
        style += `${attribute}: ${styles[attribute]}; `;
      }
    }
    style += " }\n";
    return style;
  }

  function appendCss() {
    let style = "";
    style += addStyle(".cesium-credit-lightbox-overlay", {
      display: "none",
      "z-index": "1", //must be at least 1 to draw over top other Cesium widgets
      position: "absolute",
      top: "0",
      left: "0",
      width: "100%",
      height: "100%",
      "background-color": "rgba(80, 80, 80, 0.8)",
    });

    style += addStyle(".cesium-credit-lightbox", {
      "background-color": "#303336",
      color: textColor,
      position: "relative",
      "min-height": `${lightboxHeight}px`,
      margin: "auto",
    });

    style += addStyle(
      ".cesium-credit-lightbox > ul > li a, .cesium-credit-lightbox > ul > li a:visited",
      {
        color: textColor,
      }
    );

    style += addStyle(".cesium-credit-lightbox > ul > li a:hover", {
      color: highlightColor$1,
    });

    style += addStyle(".cesium-credit-lightbox.cesium-credit-lightbox-expanded", {
      border: "1px solid #444",
      "border-radius": "5px",
      "max-width": "370px",
    });

    style += addStyle(".cesium-credit-lightbox.cesium-credit-lightbox-mobile", {
      height: "100%",
      width: "100%",
    });

    style += addStyle(".cesium-credit-lightbox-title", {
      padding: "20px 20px 0 20px",
    });

    style += addStyle(".cesium-credit-lightbox-close", {
      "font-size": "18pt",
      cursor: "pointer",
      position: "absolute",
      top: "0",
      right: "6px",
      color: textColor,
    });

    style += addStyle(".cesium-credit-lightbox-close:hover", {
      color: highlightColor$1,
    });

    style += addStyle(".cesium-credit-lightbox > ul", {
      margin: "0",
      padding: "12px 20px 12px 40px",
      "font-size": "13px",
    });

    style += addStyle(".cesium-credit-lightbox > ul > li", {
      "padding-bottom": "6px",
    });

    style += addStyle(".cesium-credit-lightbox > ul > li *", {
      padding: "0",
      margin: "0",
    });

    style += addStyle(".cesium-credit-expand-link", {
      "padding-left": "5px",
      cursor: "pointer",
      "text-decoration": "underline",
      color: textColor,
    });
    style += addStyle(".cesium-credit-expand-link:hover", {
      color: highlightColor$1,
    });

    style += addStyle(".cesium-credit-text", {
      color: textColor,
    });

    style += addStyle(
      ".cesium-credit-textContainer *, .cesium-credit-logoContainer *",
      {
        display: "inline",
      }
    );

    const head = document.head;
    const css = document.createElement("style");
    css.innerHTML = style;
    head.insertBefore(css, head.firstChild);
  }

  /**
   * The credit display is responsible for displaying credits on screen.
   *
   * @param {HTMLElement} container The HTML element where credits will be displayed
   * @param {String} [delimiter= ' • '] The string to separate text credits
   * @param {HTMLElement} [viewport=document.body] The HTML element that will contain the credits popup
   *
   * @alias CreditDisplay
   * @constructor
   *
   * @example
   * const creditDisplay = new Cesium.CreditDisplay(creditContainer);
   */
  function CreditDisplay(container, delimiter, viewport) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("container", container);
    //>>includeEnd('debug');
    const that = this;

    viewport = defaultValue(viewport, document.body);

    const lightbox = document.createElement("div");
    lightbox.className = "cesium-credit-lightbox-overlay";
    viewport.appendChild(lightbox);

    const lightboxCredits = document.createElement("div");
    lightboxCredits.className = "cesium-credit-lightbox";
    lightbox.appendChild(lightboxCredits);

    function hideLightbox(event) {
      if (lightboxCredits.contains(event.target)) {
        return;
      }
      that.hideLightbox();
    }
    lightbox.addEventListener("click", hideLightbox, false);

    const title = document.createElement("div");
    title.className = "cesium-credit-lightbox-title";
    title.textContent = "Data provided by:";
    lightboxCredits.appendChild(title);

    const closeButton = document.createElement("a");
    closeButton.onclick = this.hideLightbox.bind(this);
    closeButton.innerHTML = "&times;";
    closeButton.className = "cesium-credit-lightbox-close";
    lightboxCredits.appendChild(closeButton);

    const creditList = document.createElement("ul");
    lightboxCredits.appendChild(creditList);

    const cesiumCreditContainer = document.createElement("div");
    cesiumCreditContainer.className = "cesium-credit-logoContainer";
    cesiumCreditContainer.style.display = "inline";
    container.appendChild(cesiumCreditContainer);

    const screenContainer = document.createElement("div");
    screenContainer.className = "cesium-credit-textContainer";
    screenContainer.style.display = "inline";
    container.appendChild(screenContainer);

    const expandLink = document.createElement("a");
    expandLink.className = "cesium-credit-expand-link";
    expandLink.onclick = this.showLightbox.bind(this);
    expandLink.textContent = "Data attribution";
    container.appendChild(expandLink);

    appendCss();
    const cesiumCredit = Credit.clone(CreditDisplay.cesiumCredit);

    this._delimiter = defaultValue(delimiter, " • ");
    this._screenContainer = screenContainer;
    this._cesiumCreditContainer = cesiumCreditContainer;
    this._lastViewportHeight = undefined;
    this._lastViewportWidth = undefined;
    this._lightboxCredits = lightboxCredits;
    this._creditList = creditList;
    this._lightbox = lightbox;
    this._hideLightbox = hideLightbox;
    this._expandLink = expandLink;
    this._expanded = false;
    this._defaultCredits = [];
    this._cesiumCredit = cesiumCredit;
    this._previousCesiumCredit = undefined;
    this._currentCesiumCredit = cesiumCredit;
    this._creditDisplayElementPool = [];
    this._creditDisplayElementIndex = 0;

    this._currentFrameCredits = {
      screenCredits: new AssociativeArray(),
      lightboxCredits: new AssociativeArray(),
    };

    this._defaultCredit = undefined;

    this.viewport = viewport;

    /**
     * The HTML element where credits will be displayed.
     * @type {HTMLElement}
     */
    this.container = container;
  }

  function setCredit(creditDisplay, credits, credit, count) {
    count = defaultValue(count, 1);
    let creditDisplayElement = credits.get(credit.id);
    if (!defined(creditDisplayElement)) {
      const pool = creditDisplay._creditDisplayElementPool;
      const poolIndex = creditDisplay._creditDisplayElementPoolIndex;
      if (poolIndex < pool.length) {
        creditDisplayElement = pool[poolIndex];
        creditDisplayElement.credit = credit;
        creditDisplayElement.count = count;
      } else {
        creditDisplayElement = new CreditDisplayElement(credit, count);
        pool.push(creditDisplayElement);
      }
      ++creditDisplay._creditDisplayElementPoolIndex;
      credits.set(credit.id, creditDisplayElement);
    } else if (creditDisplayElement.count < Number.MAX_VALUE) {
      creditDisplayElement.count += count;
    }
  }
  /**
   * Adds a credit to the list of current credits to be displayed in the credit container
   *
   * @param {Credit} credit The credit to display
   */
  CreditDisplay.prototype.addCredit = function (credit) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("credit", credit);
    //>>includeEnd('debug');

    if (credit._isIon) {
      // If this is the an ion logo credit from the ion server
      // Juse use the default credit (which is identical) to avoid blinking
      if (!defined(this._defaultCredit)) {
        this._defaultCredit = Credit.clone(getDefaultCredit());
      }
      this._currentCesiumCredit = this._defaultCredit;
      return;
    }

    let credits;
    if (!credit.showOnScreen) {
      credits = this._currentFrameCredits.lightboxCredits;
    } else {
      credits = this._currentFrameCredits.screenCredits;
    }

    setCredit(this, credits, credit);
  };

  /**
   * Adds credits that will persist until they are removed
   *
   * @param {Credit} credit The credit to added to defaults
   */
  CreditDisplay.prototype.addDefaultCredit = function (credit) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("credit", credit);
    //>>includeEnd('debug');

    const defaultCredits = this._defaultCredits;
    if (!contains(defaultCredits, credit)) {
      defaultCredits.push(credit);
    }
  };

  /**
   * Removes a default credit
   *
   * @param {Credit} credit The credit to be removed from defaults
   */
  CreditDisplay.prototype.removeDefaultCredit = function (credit) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("credit", credit);
    //>>includeEnd('debug');

    const defaultCredits = this._defaultCredits;
    const index = defaultCredits.indexOf(credit);
    if (index !== -1) {
      defaultCredits.splice(index, 1);
    }
  };

  CreditDisplay.prototype.showLightbox = function () {
    this._lightbox.style.display = "block";
    this._expanded = true;
  };

  CreditDisplay.prototype.hideLightbox = function () {
    this._lightbox.style.display = "none";
    this._expanded = false;
  };

  /**
   * Updates the credit display before a new frame is rendered.
   */
  CreditDisplay.prototype.update = function () {
    if (this._expanded) {
      styleLightboxContainer(this);
    }
  };

  /**
   * Resets the credit display to a beginning of frame state, clearing out current credits.
   */
  CreditDisplay.prototype.beginFrame = function () {
    const currentFrameCredits = this._currentFrameCredits;
    this._creditDisplayElementPoolIndex = 0;

    const screenCredits = currentFrameCredits.screenCredits;
    screenCredits.removeAll();
    const defaultCredits = this._defaultCredits;
    for (let i = 0; i < defaultCredits.length; ++i) {
      const defaultCredit = defaultCredits[i];
      setCredit(this, screenCredits, defaultCredit, Number.MAX_VALUE);
    }

    currentFrameCredits.lightboxCredits.removeAll();

    if (!Credit.equals(CreditDisplay.cesiumCredit, this._cesiumCredit)) {
      this._cesiumCredit = Credit.clone(CreditDisplay.cesiumCredit);
    }
    this._currentCesiumCredit = this._cesiumCredit;
  };

  /**
   * Sets the credit display to the end of frame state, displaying credits from the last frame in the credit container.
   */
  CreditDisplay.prototype.endFrame = function () {
    const screenCredits = this._currentFrameCredits.screenCredits.values;
    displayCredits(
      this._screenContainer,
      screenCredits,
      this._delimiter,
      undefined
    );

    const lightboxCredits = this._currentFrameCredits.lightboxCredits.values;
    this._expandLink.style.display =
      lightboxCredits.length > 0 ? "inline" : "none";
    displayCredits(this._creditList, lightboxCredits, undefined, "li");

    swapCesiumCredit(this);
  };

  /**
   * Destroys the resources held by this object.  Destroying an object allows for deterministic
   * release of resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   */
  CreditDisplay.prototype.destroy = function () {
    this._lightbox.removeEventListener("click", this._hideLightbox, false);

    this.container.removeChild(this._cesiumCreditContainer);
    this.container.removeChild(this._screenContainer);
    this.container.removeChild(this._expandLink);
    this.viewport.removeChild(this._lightbox);

    return destroyObject(this);
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   */
  CreditDisplay.prototype.isDestroyed = function () {
    return false;
  };

  CreditDisplay._cesiumCredit = undefined;
  CreditDisplay._cesiumCreditInitialized = false;

  let defaultCredit$3;
  function getDefaultCredit() {
    if (!defined(defaultCredit$3)) {
      let logo = buildModuleUrl("Assets/Images/ion-credit.png");

      // When hosting in a WebView, the base URL scheme is file:// or ms-appx-web://
      // which is stripped out from the Credit's <img> tag; use the full path instead
      if (
        logo.indexOf("http://") !== 0 &&
        logo.indexOf("https://") !== 0 &&
        logo.indexOf("data:") !== 0
      ) {
        const logoUrl = new URI(logo);
        logo = logoUrl.path();
      }

      defaultCredit$3 = new Credit(
        `<a href="https://cesium.com/" target="_blank"><img src="${logo}" title="Cesium ion"/></a>`,
        true
      );
    }

    if (!CreditDisplay._cesiumCreditInitialized) {
      CreditDisplay._cesiumCredit = defaultCredit$3;
      CreditDisplay._cesiumCreditInitialized = true;
    }
    return defaultCredit$3;
  }

  Object.defineProperties(CreditDisplay, {
    /**
     * Gets or sets the Cesium logo credit.
     * @memberof CreditDisplay
     * @type {Credit}
     */
    cesiumCredit: {
      get: function () {
        getDefaultCredit();
        return CreditDisplay._cesiumCredit;
      },
      set: function (value) {
        CreditDisplay._cesiumCredit = value;
        CreditDisplay._cesiumCreditInitialized = true;
      },
    },
  });

  CreditDisplay.CreditDisplayElement = CreditDisplayElement;

  /**
   * Visualizes a vertex attribute by displaying it as a color for debugging.
   * <p>
   * Components for well-known unit-length vectors, i.e., <code>normal</code>,
   * <code>tangent</code>, and <code>bitangent</code>, are scaled and biased
   * from [-1.0, 1.0] to (-1.0, 1.0).
   * </p>
   *
   * @alias DebugAppearance
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {String} options.attributeName The name of the attribute to visualize.
   * @param {Boolean} [options.perInstanceAttribute=false] Boolean that determines whether this attribute is a per-instance geometry attribute.
   * @param {String} [options.glslDatatype='vec3'] The GLSL datatype of the attribute.  Supported datatypes are <code>float</code>, <code>vec2</code>, <code>vec3</code>, and <code>vec4</code>.
   * @param {String} [options.vertexShaderSource] Optional GLSL vertex shader source to override the default vertex shader.
   * @param {String} [options.fragmentShaderSource] Optional GLSL fragment shader source to override the default fragment shader.
   * @param {Object} [options.renderState] Optional render state to override the default render state.
   *
   * @exception {DeveloperError} options.glslDatatype must be float, vec2, vec3, or vec4.
   *
   * @example
   * const primitive = new Cesium.Primitive({
   *   geometryInstances : // ...
   *   appearance : new Cesium.DebugAppearance({
   *     attributeName : 'normal'
   *   })
   * });
   */
  function DebugAppearance(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const attributeName = options.attributeName;
    let perInstanceAttribute = options.perInstanceAttribute;

    //>>includeStart('debug', pragmas.debug);
    if (!defined(attributeName)) {
      throw new DeveloperError("options.attributeName is required.");
    }
    //>>includeEnd('debug');

    if (!defined(perInstanceAttribute)) {
      perInstanceAttribute = false;
    }

    let glslDatatype = defaultValue(options.glslDatatype, "vec3");
    const varyingName = `v_${attributeName}`;
    let getColor;

    // Well-known normalized vector attributes in VertexFormat
    if (
      attributeName === "normal" ||
      attributeName === "tangent" ||
      attributeName === "bitangent"
    ) {
      getColor = `vec4 getColor() { return vec4((${varyingName} + vec3(1.0)) * 0.5, 1.0); }\n`;
    } else {
      // All other attributes, both well-known and custom
      if (attributeName === "st") {
        glslDatatype = "vec2";
      }

      switch (glslDatatype) {
        case "float":
          getColor = `vec4 getColor() { return vec4(vec3(${varyingName}), 1.0); }\n`;
          break;
        case "vec2":
          getColor = `vec4 getColor() { return vec4(${varyingName}, 0.0, 1.0); }\n`;
          break;
        case "vec3":
          getColor = `vec4 getColor() { return vec4(${varyingName}, 1.0); }\n`;
          break;
        case "vec4":
          getColor = `vec4 getColor() { return ${varyingName}; }\n`;
          break;
        //>>includeStart('debug', pragmas.debug);
        default:
          throw new DeveloperError(
            "options.glslDatatype must be float, vec2, vec3, or vec4."
          );
        //>>includeEnd('debug');
      }
    }

    const vs =
      `${
      "attribute vec3 position3DHigh;\n" +
      "attribute vec3 position3DLow;\n" +
      "attribute float batchId;\n"
    }${
      perInstanceAttribute
        ? ""
        : `attribute ${glslDatatype} ${attributeName};\n`
    }varying ${glslDatatype} ${varyingName};\n` +
      `void main()\n` +
      `{\n` +
      `vec4 p = czm_translateRelativeToEye(position3DHigh, position3DLow);\n${
      perInstanceAttribute
        ? `${varyingName} = czm_batchTable_${attributeName}(batchId);\n`
        : `${varyingName} = ${attributeName};\n`
    }gl_Position = czm_modelViewProjectionRelativeToEye * p;\n` +
      `}`;
    const fs =
      `varying ${glslDatatype} ${varyingName};\n${getColor}\n` +
      `void main()\n` +
      `{\n` +
      `gl_FragColor = getColor();\n` +
      `}`;

    /**
     * This property is part of the {@link Appearance} interface, but is not
     * used by {@link DebugAppearance} since a fully custom fragment shader is used.
     *
     * @type Material
     *
     * @default undefined
     */
    this.material = undefined;

    /**
     * When <code>true</code>, the geometry is expected to appear translucent.
     *
     * @type {Boolean}
     *
     * @default false
     */
    this.translucent = defaultValue(options.translucent, false);

    this._vertexShaderSource = defaultValue(options.vertexShaderSource, vs);
    this._fragmentShaderSource = defaultValue(options.fragmentShaderSource, fs);
    this._renderState = Appearance.getDefaultRenderState(
      false,
      false,
      options.renderState
    );
    this._closed = defaultValue(options.closed, false);

    // Non-derived members

    this._attributeName = attributeName;
    this._glslDatatype = glslDatatype;
  }

  Object.defineProperties(DebugAppearance.prototype, {
    /**
     * The GLSL source code for the vertex shader.
     *
     * @memberof DebugAppearance.prototype
     *
     * @type {String}
     * @readonly
     */
    vertexShaderSource: {
      get: function () {
        return this._vertexShaderSource;
      },
    },

    /**
     * The GLSL source code for the fragment shader.  The full fragment shader
     * source is built procedurally taking into account the {@link DebugAppearance#material}.
     * Use {@link DebugAppearance#getFragmentShaderSource} to get the full source.
     *
     * @memberof DebugAppearance.prototype
     *
     * @type {String}
     * @readonly
     */
    fragmentShaderSource: {
      get: function () {
        return this._fragmentShaderSource;
      },
    },

    /**
     * The WebGL fixed-function state to use when rendering the geometry.
     *
     * @memberof DebugAppearance.prototype
     *
     * @type {Object}
     * @readonly
     */
    renderState: {
      get: function () {
        return this._renderState;
      },
    },

    /**
     * When <code>true</code>, the geometry is expected to be closed.
     *
     * @memberof DebugAppearance.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default false
     */
    closed: {
      get: function () {
        return this._closed;
      },
    },

    /**
     * The name of the attribute being visualized.
     *
     * @memberof DebugAppearance.prototype
     *
     * @type {String}
     * @readonly
     */
    attributeName: {
      get: function () {
        return this._attributeName;
      },
    },

    /**
     * The GLSL datatype of the attribute being visualized.
     *
     * @memberof DebugAppearance.prototype
     *
     * @type {String}
     * @readonly
     */
    glslDatatype: {
      get: function () {
        return this._glslDatatype;
      },
    },
  });

  /**
   * Returns the full GLSL fragment shader source, which for {@link DebugAppearance} is just
   * {@link DebugAppearance#fragmentShaderSource}.
   *
   * @function
   *
   * @returns {String} The full GLSL fragment shader source.
   */
  DebugAppearance.prototype.getFragmentShaderSource =
    Appearance.prototype.getFragmentShaderSource;

  /**
   * Determines if the geometry is translucent based on {@link DebugAppearance#translucent}.
   *
   * @function
   *
   * @returns {Boolean} <code>true</code> if the appearance is translucent.
   */
  DebugAppearance.prototype.isTranslucent = Appearance.prototype.isTranslucent;

  /**
   * Creates a render state.  This is not the final render state instance; instead,
   * it can contain a subset of render state properties identical to the render state
   * created in the context.
   *
   * @function
   *
   * @returns {Object} The render state.
   */
  DebugAppearance.prototype.getRenderState = Appearance.prototype.getRenderState;

  /**
   * Draws the outline of the camera's view frustum.
   *
   * @alias DebugCameraPrimitive
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Camera} options.camera The camera.
   * @param {Number[]} [options.frustumSplits] Distances to the near and far planes of the camera frustums. This overrides the camera's frustum near and far values.
   * @param {Color} [options.color=Color.CYAN] The color of the debug outline.
   * @param {Boolean} [options.updateOnChange=true] Whether the primitive updates when the underlying camera changes.
   * @param {Boolean} [options.show=true] Determines if this primitive will be shown.
   * @param {Object} [options.id] A user-defined object to return when the instance is picked with {@link Scene#pick}.
   *
   * @example
   * primitives.add(new Cesium.DebugCameraPrimitive({
   *   camera : camera,
   *   color : Cesium.Color.YELLOW
   * }));
   */
  function DebugCameraPrimitive(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    if (!defined(options.camera)) {
      throw new DeveloperError("options.camera is required.");
    }
    //>>includeEnd('debug');

    this._camera = options.camera;
    this._frustumSplits = options.frustumSplits;
    this._color = defaultValue(options.color, Color.CYAN);
    this._updateOnChange = defaultValue(options.updateOnChange, true);

    /**
     * Determines if this primitive will be shown.
     *
     * @type Boolean
     * @default true
     */
    this.show = defaultValue(options.show, true);

    /**
     * User-defined value returned when the primitive is picked.
     *
     * @type {*}
     * @default undefined
     *
     * @see Scene#pick
     */
    this.id = options.id;
    this._id = undefined;

    this._outlinePrimitives = [];
    this._planesPrimitives = [];
  }

  const scratchRight$2 = new Cartesian3();
  const scratchRotation = new Matrix3();
  const scratchOrientation = new Quaternion();
  const scratchPerspective = new PerspectiveFrustum();
  const scratchPerspectiveOffCenter = new PerspectiveOffCenterFrustum();
  const scratchOrthographic = new OrthographicFrustum();
  const scratchOrthographicOffCenter = new OrthographicOffCenterFrustum();

  const scratchColor$2 = new Color();
  const scratchSplits$1 = [1.0, 100000.0];

  /**
   * @private
   */
  DebugCameraPrimitive.prototype.update = function (frameState) {
    if (!this.show) {
      return;
    }

    const planesPrimitives = this._planesPrimitives;
    const outlinePrimitives = this._outlinePrimitives;
    let i;
    let length;

    if (this._updateOnChange) {
      // Recreate the primitive every frame
      length = planesPrimitives.length;
      for (i = 0; i < length; ++i) {
        outlinePrimitives[i] =
          outlinePrimitives[i] && outlinePrimitives[i].destroy();
        planesPrimitives[i] =
          planesPrimitives[i] && planesPrimitives[i].destroy();
      }
      planesPrimitives.length = 0;
      outlinePrimitives.length = 0;
    }

    if (planesPrimitives.length === 0) {
      const camera = this._camera;
      const cameraFrustum = camera.frustum;
      let frustum;
      if (cameraFrustum instanceof PerspectiveFrustum) {
        frustum = scratchPerspective;
      } else if (cameraFrustum instanceof PerspectiveOffCenterFrustum) {
        frustum = scratchPerspectiveOffCenter;
      } else if (cameraFrustum instanceof OrthographicFrustum) {
        frustum = scratchOrthographic;
      } else {
        frustum = scratchOrthographicOffCenter;
      }
      frustum = cameraFrustum.clone(frustum);

      let numFrustums;
      let frustumSplits = this._frustumSplits;
      if (!defined(frustumSplits) || frustumSplits.length <= 1) {
        // Use near and far planes if no splits created
        frustumSplits = scratchSplits$1;
        frustumSplits[0] = this._camera.frustum.near;
        frustumSplits[1] = this._camera.frustum.far;
        numFrustums = 1;
      } else {
        numFrustums = frustumSplits.length - 1;
      }

      const position = camera.positionWC;
      const direction = camera.directionWC;
      const up = camera.upWC;
      let right = camera.rightWC;
      right = Cartesian3.negate(right, scratchRight$2);

      const rotation = scratchRotation;
      Matrix3.setColumn(rotation, 0, right, rotation);
      Matrix3.setColumn(rotation, 1, up, rotation);
      Matrix3.setColumn(rotation, 2, direction, rotation);

      const orientation = Quaternion.fromRotationMatrix(
        rotation,
        scratchOrientation
      );

      planesPrimitives.length = outlinePrimitives.length = numFrustums;

      for (i = 0; i < numFrustums; ++i) {
        frustum.near = frustumSplits[i];
        frustum.far = frustumSplits[i + 1];

        planesPrimitives[i] = new Primitive$3({
          geometryInstances: new GeometryInstance({
            geometry: new FrustumGeometry({
              origin: position,
              orientation: orientation,
              frustum: frustum,
              _drawNearPlane: i === 0,
            }),
            attributes: {
              color: ColorGeometryInstanceAttribute.fromColor(
                Color.fromAlpha(this._color, 0.1, scratchColor$2)
              ),
            },
            id: this.id,
            pickPrimitive: this,
          }),
          appearance: new PerInstanceColorAppearance({
            translucent: true,
            flat: true,
          }),
          asynchronous: false,
        });

        outlinePrimitives[i] = new Primitive$3({
          geometryInstances: new GeometryInstance({
            geometry: new FrustumOutlineGeometry({
              origin: position,
              orientation: orientation,
              frustum: frustum,
              _drawNearPlane: i === 0,
            }),
            attributes: {
              color: ColorGeometryInstanceAttribute.fromColor(this._color),
            },
            id: this.id,
            pickPrimitive: this,
          }),
          appearance: new PerInstanceColorAppearance({
            translucent: false,
            flat: true,
          }),
          asynchronous: false,
        });
      }
    }

    length = planesPrimitives.length;
    for (i = 0; i < length; ++i) {
      outlinePrimitives[i].update(frameState);
      planesPrimitives[i].update(frameState);
    }
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <p>
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   * </p>
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see DebugCameraPrimitive#destroy
   */
  DebugCameraPrimitive.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <p>
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   * </p>
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @example
   * p = p && p.destroy();
   *
   * @see DebugCameraPrimitive#isDestroyed
   */
  DebugCameraPrimitive.prototype.destroy = function () {
    const length = this._planesPrimitives.length;
    for (let i = 0; i < length; ++i) {
      this._outlinePrimitives[i] =
        this._outlinePrimitives[i] && this._outlinePrimitives[i].destroy();
      this._planesPrimitives[i] =
        this._planesPrimitives[i] && this._planesPrimitives[i].destroy();
    }
    return destroyObject(this);
  };

  /**
   * @private
   */
  function DebugInspector() {
    this._cachedShowFrustumsShaders = {};
  }

  function getAttributeLocations(shaderProgram) {
    const attributeLocations = {};
    const attributes = shaderProgram.vertexAttributes;
    for (const a in attributes) {
      if (attributes.hasOwnProperty(a)) {
        attributeLocations[a] = attributes[a].index;
      }
    }

    return attributeLocations;
  }

  function createDebugShowFrustumsShaderProgram(scene, shaderProgram) {
    const context = scene.context;
    const sp = shaderProgram;
    const fs = sp.fragmentShaderSource.clone();

    const targets = [];
    fs.sources = fs.sources.map(function (source) {
      source = ShaderSource.replaceMain(source, "czm_Debug_main");
      const re = /gl_FragData\[(\d+)\]/g;
      let match;
      while ((match = re.exec(source)) !== null) {
        if (targets.indexOf(match[1]) === -1) {
          targets.push(match[1]);
        }
      }
      return source;
    });
    const length = targets.length;

    let newMain = "";
    newMain += "uniform vec3 debugShowCommandsColor;\n";
    newMain += "uniform vec3 debugShowFrustumsColor;\n";
    newMain += "void main() \n" + "{ \n" + "    czm_Debug_main(); \n";

    // set debugShowCommandsColor to Color(1.0, 1.0, 1.0, 1.0) to stop rendering scene.debugShowCommands
    // set debugShowFrustumsColor to Color(1.0, 1.0, 1.0, 1.0) to stop rendering scene.debugShowFrustums
    let i;
    if (length > 0) {
      for (i = 0; i < length; ++i) {
        newMain += `    gl_FragData[${targets[i]}].rgb *= debugShowCommandsColor;\n`;
        newMain += `    gl_FragData[${targets[i]}].rgb *= debugShowFrustumsColor;\n`;
      }
    } else {
      newMain += "    gl_FragColor.rgb *= debugShowCommandsColor;\n";
      newMain += "    gl_FragColor.rgb *= debugShowFrustumsColor;\n";
    }
    newMain += "}";

    fs.sources.push(newMain);

    const attributeLocations = getAttributeLocations(sp);

    return ShaderProgram.fromCache({
      context: context,
      vertexShaderSource: sp.vertexShaderSource,
      fragmentShaderSource: fs,
      attributeLocations: attributeLocations,
    });
  }

  const scratchFrustumColor = new Color();
  function createDebugShowFrustumsUniformMap(scene, command) {
    // setup uniform for the shader
    let debugUniformMap;
    if (!defined(command.uniformMap)) {
      debugUniformMap = {};
    } else {
      debugUniformMap = command.uniformMap;
    }

    if (
      defined(debugUniformMap.debugShowCommandsColor) ||
      defined(debugUniformMap.debugShowFrustumsColor)
    ) {
      return debugUniformMap;
    }

    debugUniformMap.debugShowCommandsColor = function () {
      if (!scene.debugShowCommands) {
        return Color.WHITE;
      }

      if (!defined(command._debugColor)) {
        command._debugColor = Color.fromRandom();
      }

      return command._debugColor;
    };

    debugUniformMap.debugShowFrustumsColor = function () {
      if (!scene.debugShowFrustums) {
        return Color.WHITE;
      }

      // Support up to three frustums.  If a command overlaps all
      // three, it's code is not changed.
      scratchFrustumColor.red =
        command.debugOverlappingFrustums & (1 << 0) ? 1.0 : 0.0;
      scratchFrustumColor.green =
        command.debugOverlappingFrustums & (1 << 1) ? 1.0 : 0.0;
      scratchFrustumColor.blue =
        command.debugOverlappingFrustums & (1 << 2) ? 1.0 : 0.0;
      scratchFrustumColor.alpha = 1.0;
      return scratchFrustumColor;
    };

    return debugUniformMap;
  }

  const scratchShowFrustumCommand = new DrawCommand();
  DebugInspector.prototype.executeDebugShowFrustumsCommand = function (
    scene,
    command,
    passState
  ) {
    // create debug command
    const shaderProgramId = command.shaderProgram.id;
    let debugShaderProgram = this._cachedShowFrustumsShaders[shaderProgramId];
    if (!defined(debugShaderProgram)) {
      debugShaderProgram = createDebugShowFrustumsShaderProgram(
        scene,
        command.shaderProgram
      );

      this._cachedShowFrustumsShaders[shaderProgramId] = debugShaderProgram;
    }

    const debugCommand = DrawCommand.shallowClone(
      command,
      scratchShowFrustumCommand
    );
    debugCommand.shaderProgram = debugShaderProgram;
    debugCommand.uniformMap = createDebugShowFrustumsUniformMap(scene, command);
    debugCommand.execute(scene.context, passState);
  };

  /**
   * Draws the axes of a reference frame defined by a matrix that transforms to world
   * coordinates, i.e., Earth's WGS84 coordinates.  The most prominent example is
   * a primitives <code>modelMatrix</code>.
   * <p>
   * The X axis is red; Y is green; and Z is blue.
   * </p>
   * <p>
   * This is for debugging only; it is not optimized for production use.
   * </p>
   *
   * @alias DebugModelMatrixPrimitive
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Number} [options.length=10000000.0] The length of the axes in meters.
   * @param {Number} [options.width=2.0] The width of the axes in pixels.
   * @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] The 4x4 matrix that defines the reference frame, i.e., origin plus axes, to visualize.
   * @param {Boolean} [options.show=true] Determines if this primitive will be shown.
   * @param {Object} [options.id] A user-defined object to return when the instance is picked with {@link Scene#pick}
   *
   * @example
   * primitives.add(new Cesium.DebugModelMatrixPrimitive({
   *   modelMatrix : primitive.modelMatrix,  // primitive to debug
   *   length : 100000.0,
   *   width : 10.0
   * }));
   */
  function DebugModelMatrixPrimitive(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    /**
     * The length of the axes in meters.
     *
     * @type {Number}
     * @default 10000000.0
     */
    this.length = defaultValue(options.length, 10000000.0);
    this._length = undefined;

    /**
     * The width of the axes in pixels.
     *
     * @type {Number}
     * @default 2.0
     */
    this.width = defaultValue(options.width, 2.0);
    this._width = undefined;

    /**
     * Determines if this primitive will be shown.
     *
     * @type Boolean
     * @default true
     */
    this.show = defaultValue(options.show, true);

    /**
     * The 4x4 matrix that defines the reference frame, i.e., origin plus axes, to visualize.
     *
     * @type {Matrix4}
     * @default {@link Matrix4.IDENTITY}
     */
    this.modelMatrix = Matrix4.clone(
      defaultValue(options.modelMatrix, Matrix4.IDENTITY)
    );
    this._modelMatrix = new Matrix4();

    /**
     * User-defined value returned when the primitive is picked.
     *
     * @type {*}
     * @default undefined
     *
     * @see Scene#pick
     */
    this.id = options.id;
    this._id = undefined;

    this._primitive = undefined;
  }

  /**
   * @private
   */
  DebugModelMatrixPrimitive.prototype.update = function (frameState) {
    if (!this.show) {
      return;
    }

    if (
      !defined(this._primitive) ||
      !Matrix4.equals(this._modelMatrix, this.modelMatrix) ||
      this._length !== this.length ||
      this._width !== this.width ||
      this._id !== this.id
    ) {
      this._modelMatrix = Matrix4.clone(this.modelMatrix, this._modelMatrix);
      this._length = this.length;
      this._width = this.width;
      this._id = this.id;

      if (defined(this._primitive)) {
        this._primitive.destroy();
      }

      // Workaround projecting (0, 0, 0)
      if (
        this.modelMatrix[12] === 0.0 &&
        this.modelMatrix[13] === 0.0 &&
        this.modelMatrix[14] === 0.0
      ) {
        this.modelMatrix[14] = 0.01;
      }

      const x = new GeometryInstance({
        geometry: new PolylineGeometry({
          positions: [Cartesian3.ZERO, Cartesian3.UNIT_X],
          width: this.width,
          vertexFormat: PolylineColorAppearance.VERTEX_FORMAT,
          colors: [Color.RED, Color.RED],
          arcType: ArcType$1.NONE,
        }),
        modelMatrix: Matrix4.multiplyByUniformScale(
          this.modelMatrix,
          this.length,
          new Matrix4()
        ),
        id: this.id,
        pickPrimitive: this,
      });
      const y = new GeometryInstance({
        geometry: new PolylineGeometry({
          positions: [Cartesian3.ZERO, Cartesian3.UNIT_Y],
          width: this.width,
          vertexFormat: PolylineColorAppearance.VERTEX_FORMAT,
          colors: [Color.GREEN, Color.GREEN],
          arcType: ArcType$1.NONE,
        }),
        modelMatrix: Matrix4.multiplyByUniformScale(
          this.modelMatrix,
          this.length,
          new Matrix4()
        ),
        id: this.id,
        pickPrimitive: this,
      });
      const z = new GeometryInstance({
        geometry: new PolylineGeometry({
          positions: [Cartesian3.ZERO, Cartesian3.UNIT_Z],
          width: this.width,
          vertexFormat: PolylineColorAppearance.VERTEX_FORMAT,
          colors: [Color.BLUE, Color.BLUE],
          arcType: ArcType$1.NONE,
        }),
        modelMatrix: Matrix4.multiplyByUniformScale(
          this.modelMatrix,
          this.length,
          new Matrix4()
        ),
        id: this.id,
        pickPrimitive: this,
      });

      this._primitive = new Primitive$3({
        geometryInstances: [x, y, z],
        appearance: new PolylineColorAppearance(),
        asynchronous: false,
      });
    }

    this._primitive.update(frameState);
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <p>
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   * </p>
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see DebugModelMatrixPrimitive#destroy
   */
  DebugModelMatrixPrimitive.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <p>
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   * </p>
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @example
   * p = p && p.destroy();
   *
   * @see DebugModelMatrixPrimitive#isDestroyed
   */
  DebugModelMatrixPrimitive.prototype.destroy = function () {
    this._primitive = this._primitive && this._primitive.destroy();
    return destroyObject(this);
  };

  //This file is automatically rebuilt by the Cesium build process.
  var DepthPlaneFS = "varying vec4 positionEC;\n\
void main()\n\
{\n\
vec3 position;\n\
vec3 direction;\n\
if (czm_orthographicIn3D == 1.0)\n\
{\n\
vec2 uv = (gl_FragCoord.xy -  czm_viewport.xy) / czm_viewport.zw;\n\
vec2 minPlane = vec2(czm_frustumPlanes.z, czm_frustumPlanes.y);\n\
vec2 maxPlane = vec2(czm_frustumPlanes.w, czm_frustumPlanes.x);\n\
position = vec3(mix(minPlane, maxPlane, uv), 0.0);\n\
direction = vec3(0.0, 0.0, -1.0);\n\
}\n\
else\n\
{\n\
position = vec3(0.0);\n\
direction = normalize(positionEC.xyz);\n\
}\n\
czm_ray ray = czm_ray(position, direction);\n\
vec3 ellipsoid_center = czm_view[3].xyz;\n\
czm_raySegment intersection = czm_rayEllipsoidIntersectionInterval(ray, ellipsoid_center, czm_ellipsoidInverseRadii);\n\
if (!czm_isEmpty(intersection))\n\
{\n\
gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0);\n\
}\n\
else\n\
{\n\
discard;\n\
}\n\
czm_writeLogDepth();\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var DepthPlaneVS = "attribute vec4 position;\n\
varying vec4 positionEC;\n\
void main()\n\
{\n\
positionEC = czm_modelView * position;\n\
gl_Position = czm_projection * positionEC;\n\
czm_vertexLogDepth();\n\
}\n\
";

  /**
   * @private
   */
  function DepthPlane(depthPlaneEllipsoidOffset) {
    this._rs = undefined;
    this._sp = undefined;
    this._va = undefined;
    this._command = undefined;
    this._mode = undefined;
    this._useLogDepth = false;
    this._ellipsoidOffset = defaultValue(depthPlaneEllipsoidOffset, 0);
  }

  const depthQuadScratch = FeatureDetection.supportsTypedArrays()
    ? new Float32Array(12)
    : [];
  const scratchCartesian1$1 = new Cartesian3();
  const scratchCartesian2$1 = new Cartesian3();
  const scratchCartesian3 = new Cartesian3();
  const scratchCartesian4$1 = new Cartesian3();
  const scratchCartesian5 = new Cartesian3();

  function computeDepthQuad(ellipsoid, frameState) {
    const radii = ellipsoid.radii;
    const camera = frameState.camera;
    let center, eastOffset, northOffset;

    if (camera.frustum instanceof OrthographicFrustum) {
      center = Cartesian3.ZERO;
      eastOffset = camera.rightWC;
      northOffset = camera.upWC;
    } else {
      const p = camera.positionWC;

      // Find the corresponding position in the scaled space of the ellipsoid.
      const q = Cartesian3.multiplyComponents(
        ellipsoid.oneOverRadii,
        p,
        scratchCartesian1$1
      );

      const qUnit = Cartesian3.normalize(q, scratchCartesian2$1);

      // Determine the east and north directions at q.
      const eUnit = Cartesian3.normalize(
        Cartesian3.cross(Cartesian3.UNIT_Z, q, scratchCartesian3),
        scratchCartesian3
      );
      const nUnit = Cartesian3.normalize(
        Cartesian3.cross(qUnit, eUnit, scratchCartesian4$1),
        scratchCartesian4$1
      );

      const qMagnitude = Cartesian3.magnitude(q);

      // Determine the radius of the 'limb' of the ellipsoid.
      const wMagnitude = Math.sqrt(qMagnitude * qMagnitude - 1.0);

      // Compute the center and offsets.
      center = Cartesian3.multiplyByScalar(
        qUnit,
        1.0 / qMagnitude,
        scratchCartesian1$1
      );
      const scalar = wMagnitude / qMagnitude;
      eastOffset = Cartesian3.multiplyByScalar(eUnit, scalar, scratchCartesian2$1);
      northOffset = Cartesian3.multiplyByScalar(nUnit, scalar, scratchCartesian3);
    }

    // A conservative measure for the longitudes would be to use the min/max longitudes of the bounding frustum.
    const upperLeft = Cartesian3.add(center, northOffset, scratchCartesian5);
    Cartesian3.subtract(upperLeft, eastOffset, upperLeft);
    Cartesian3.multiplyComponents(radii, upperLeft, upperLeft);
    Cartesian3.pack(upperLeft, depthQuadScratch, 0);

    const lowerLeft = Cartesian3.subtract(center, northOffset, scratchCartesian5);
    Cartesian3.subtract(lowerLeft, eastOffset, lowerLeft);
    Cartesian3.multiplyComponents(radii, lowerLeft, lowerLeft);
    Cartesian3.pack(lowerLeft, depthQuadScratch, 3);

    const upperRight = Cartesian3.add(center, northOffset, scratchCartesian5);
    Cartesian3.add(upperRight, eastOffset, upperRight);
    Cartesian3.multiplyComponents(radii, upperRight, upperRight);
    Cartesian3.pack(upperRight, depthQuadScratch, 6);

    const lowerRight = Cartesian3.subtract(
      center,
      northOffset,
      scratchCartesian5
    );
    Cartesian3.add(lowerRight, eastOffset, lowerRight);
    Cartesian3.multiplyComponents(radii, lowerRight, lowerRight);
    Cartesian3.pack(lowerRight, depthQuadScratch, 9);

    return depthQuadScratch;
  }

  DepthPlane.prototype.update = function (frameState) {
    this._mode = frameState.mode;
    if (frameState.mode !== SceneMode$1.SCENE3D) {
      return;
    }

    const context = frameState.context;

    // Allow offsetting the ellipsoid radius to address rendering artefacts below ellipsoid zero elevation.
    const radii = frameState.mapProjection.ellipsoid.radii;
    const ellipsoid = new Ellipsoid(
      radii.x + this._ellipsoidOffset,
      radii.y + this._ellipsoidOffset,
      radii.z + this._ellipsoidOffset
    );

    const useLogDepth = frameState.useLogDepth;

    if (!defined(this._command)) {
      this._rs = RenderState.fromCache({
        // Write depth, not color
        cull: {
          enabled: true,
        },
        depthTest: {
          enabled: true,
        },
        colorMask: {
          red: false,
          green: false,
          blue: false,
          alpha: false,
        },
      });

      this._command = new DrawCommand({
        renderState: this._rs,
        boundingVolume: new BoundingSphere(
          Cartesian3.ZERO,
          ellipsoid.maximumRadius
        ),
        pass: Pass$1.OPAQUE,
        owner: this,
      });
    }

    if (!defined(this._sp) || this._useLogDepth !== useLogDepth) {
      this._useLogDepth = useLogDepth;

      const vs = new ShaderSource({
        sources: [DepthPlaneVS],
      });
      const fs = new ShaderSource({
        sources: [DepthPlaneFS],
      });
      if (useLogDepth) {
        const extension =
          "#ifdef GL_EXT_frag_depth \n" +
          "#extension GL_EXT_frag_depth : enable \n" +
          "#endif \n\n";

        fs.sources.push(extension);
        fs.defines.push("LOG_DEPTH");
        vs.defines.push("LOG_DEPTH");
      }

      this._sp = ShaderProgram.replaceCache({
        shaderProgram: this._sp,
        context: context,
        vertexShaderSource: vs,
        fragmentShaderSource: fs,
        attributeLocations: {
          position: 0,
        },
      });

      this._command.shaderProgram = this._sp;
    }

    // update depth plane
    const depthQuad = computeDepthQuad(ellipsoid, frameState);

    // depth plane
    if (!defined(this._va)) {
      const geometry = new Geometry({
        attributes: {
          position: new GeometryAttribute({
            componentDatatype: ComponentDatatype$1.FLOAT,
            componentsPerAttribute: 3,
            values: depthQuad,
          }),
        },
        indices: [0, 1, 2, 2, 1, 3],
        primitiveType: PrimitiveType$1.TRIANGLES,
      });

      this._va = VertexArray.fromGeometry({
        context: context,
        geometry: geometry,
        attributeLocations: {
          position: 0,
        },
        bufferUsage: BufferUsage$1.DYNAMIC_DRAW,
      });

      this._command.vertexArray = this._va;
    } else {
      this._va.getAttribute(0).vertexBuffer.copyFromArrayView(depthQuad);
    }
  };

  DepthPlane.prototype.execute = function (context, passState) {
    if (this._mode === SceneMode$1.SCENE3D) {
      this._command.execute(context, passState);
    }
  };

  DepthPlane.prototype.isDestroyed = function () {
    return false;
  };

  DepthPlane.prototype.destroy = function () {
    this._sp = this._sp && this._sp.destroy();
    this._va = this._va && this._va.destroy();
  };

  /**
   * @private
   */
  function DerivedCommand() {}

  const fragDepthRegex = /\bgl_FragDepthEXT\b/;
  const discardRegex = /\bdiscard\b/;

  function getDepthOnlyShaderProgram$1(context, shaderProgram) {
    let shader = context.shaderCache.getDerivedShaderProgram(
      shaderProgram,
      "depthOnly"
    );
    if (!defined(shader)) {
      const attributeLocations = shaderProgram._attributeLocations;
      let fs = shaderProgram.fragmentShaderSource;

      let i;
      let writesDepthOrDiscards = false;
      const sources = fs.sources;
      let length = sources.length;
      for (i = 0; i < length; ++i) {
        if (fragDepthRegex.test(sources[i]) || discardRegex.test(sources[i])) {
          writesDepthOrDiscards = true;
          break;
        }
      }

      let usesLogDepth = false;
      const defines = fs.defines;
      length = defines.length;
      for (i = 0; i < length; ++i) {
        if (defines[i] === "LOG_DEPTH") {
          usesLogDepth = true;
          break;
        }
      }

      let source;
      if (!writesDepthOrDiscards && !usesLogDepth) {
        source =
          "void main() \n" + "{ \n" + "    gl_FragColor = vec4(1.0); \n" + "} \n";
        fs = new ShaderSource({
          sources: [source],
        });
      } else if (!writesDepthOrDiscards && usesLogDepth) {
        source =
          "#ifdef GL_EXT_frag_depth \n" +
          "#extension GL_EXT_frag_depth : enable \n" +
          "#endif \n\n" +
          "void main() \n" +
          "{ \n" +
          "    gl_FragColor = vec4(1.0); \n" +
          "    czm_writeLogDepth(); \n" +
          "} \n";
        fs = new ShaderSource({
          defines: ["LOG_DEPTH"],
          sources: [source],
        });
      }

      shader = context.shaderCache.createDerivedShaderProgram(
        shaderProgram,
        "depthOnly",
        {
          vertexShaderSource: shaderProgram.vertexShaderSource,
          fragmentShaderSource: fs,
          attributeLocations: attributeLocations,
        }
      );
    }

    return shader;
  }

  function getDepthOnlyRenderState(scene, renderState) {
    const cache = scene._depthOnlyRenderStateCache;
    let depthOnlyState = cache[renderState.id];
    if (!defined(depthOnlyState)) {
      const rs = RenderState.getState(renderState);
      rs.depthMask = true;
      rs.colorMask = {
        red: false,
        green: false,
        blue: false,
        alpha: false,
      };

      depthOnlyState = RenderState.fromCache(rs);
      cache[renderState.id] = depthOnlyState;
    }

    return depthOnlyState;
  }

  DerivedCommand.createDepthOnlyDerivedCommand = function (
    scene,
    command,
    context,
    result
  ) {
    // For a depth only pass, we bind a framebuffer with only a depth attachment (no color attachments),
    // do not write color, and write depth. If the fragment shader doesn't modify the fragment depth
    // or discard, the driver can replace the fragment shader with a pass-through shader. We're unsure if this
    // actually happens so we modify the shader to use a pass-through fragment shader.

    if (!defined(result)) {
      result = {};
    }

    let shader;
    let renderState;
    if (defined(result.depthOnlyCommand)) {
      shader = result.depthOnlyCommand.shaderProgram;
      renderState = result.depthOnlyCommand.renderState;
    }

    result.depthOnlyCommand = DrawCommand.shallowClone(
      command,
      result.depthOnlyCommand
    );

    if (!defined(shader) || result.shaderProgramId !== command.shaderProgram.id) {
      result.depthOnlyCommand.shaderProgram = getDepthOnlyShaderProgram$1(
        context,
        command.shaderProgram
      );
      result.depthOnlyCommand.renderState = getDepthOnlyRenderState(
        scene,
        command.renderState
      );
      result.shaderProgramId = command.shaderProgram.id;
    } else {
      result.depthOnlyCommand.shaderProgram = shader;
      result.depthOnlyCommand.renderState = renderState;
    }

    return result;
  };

  const writeLogDepthRegex = /\s+czm_writeLogDepth\(/;
  const vertexlogDepthRegex = /\s+czm_vertexLogDepth\(/;
  const extensionRegex = /\s*#extension\s+GL_EXT_frag_depth\s*:\s*enable/;

  function getLogDepthShaderProgram(context, shaderProgram) {
    let shader = context.shaderCache.getDerivedShaderProgram(
      shaderProgram,
      "logDepth"
    );
    if (!defined(shader)) {
      const attributeLocations = shaderProgram._attributeLocations;
      const vs = shaderProgram.vertexShaderSource.clone();
      const fs = shaderProgram.fragmentShaderSource.clone();

      vs.defines = defined(vs.defines) ? vs.defines.slice(0) : [];
      vs.defines.push("LOG_DEPTH");
      fs.defines = defined(fs.defines) ? fs.defines.slice(0) : [];
      fs.defines.push("LOG_DEPTH");

      let i;
      let logMain;
      let writesLogDepth = false;
      let sources = vs.sources;
      let length = sources.length;
      for (i = 0; i < length; ++i) {
        if (vertexlogDepthRegex.test(sources[i])) {
          writesLogDepth = true;
          break;
        }
      }

      if (!writesLogDepth) {
        for (i = 0; i < length; ++i) {
          sources[i] = ShaderSource.replaceMain(sources[i], "czm_log_depth_main");
        }

        logMain =
          "\n\n" +
          "void main() \n" +
          "{ \n" +
          "    czm_log_depth_main(); \n" +
          "    czm_vertexLogDepth(); \n" +
          "} \n";
        sources.push(logMain);
      }

      sources = fs.sources;
      length = sources.length;

      writesLogDepth = false;
      for (i = 0; i < length; ++i) {
        if (writeLogDepthRegex.test(sources[i])) {
          writesLogDepth = true;
        }
      }
      // This define indicates that a log depth value is written by the shader but doesn't use czm_writeLogDepth.
      if (fs.defines.indexOf("LOG_DEPTH_WRITE") !== -1) {
        writesLogDepth = true;
      }

      let addExtension = true;
      for (i = 0; i < length; ++i) {
        if (extensionRegex.test(sources[i])) {
          addExtension = false;
        }
      }

      let logSource = "";
      if (addExtension) {
        logSource +=
          "#ifdef GL_EXT_frag_depth \n" +
          "#extension GL_EXT_frag_depth : enable \n" +
          "#endif \n\n";
      }

      if (!writesLogDepth) {
        for (i = 0; i < length; i++) {
          sources[i] = ShaderSource.replaceMain(sources[i], "czm_log_depth_main");
        }

        logSource +=
          "\n" +
          "void main() \n" +
          "{ \n" +
          "    czm_log_depth_main(); \n" +
          "    czm_writeLogDepth(); \n" +
          "} \n";
      }

      sources.push(logSource);

      shader = context.shaderCache.createDerivedShaderProgram(
        shaderProgram,
        "logDepth",
        {
          vertexShaderSource: vs,
          fragmentShaderSource: fs,
          attributeLocations: attributeLocations,
        }
      );
    }

    return shader;
  }

  DerivedCommand.createLogDepthCommand = function (command, context, result) {
    if (!defined(result)) {
      result = {};
    }

    let shader;
    if (defined(result.command)) {
      shader = result.command.shaderProgram;
    }

    result.command = DrawCommand.shallowClone(command, result.command);

    if (!defined(shader) || result.shaderProgramId !== command.shaderProgram.id) {
      result.command.shaderProgram = getLogDepthShaderProgram(
        context,
        command.shaderProgram
      );
      result.shaderProgramId = command.shaderProgram.id;
    } else {
      result.command.shaderProgram = shader;
    }

    return result;
  };

  function getPickShaderProgram$1(context, shaderProgram, pickId) {
    let shader = context.shaderCache.getDerivedShaderProgram(
      shaderProgram,
      "pick"
    );
    if (!defined(shader)) {
      const attributeLocations = shaderProgram._attributeLocations;
      let fs = shaderProgram.fragmentShaderSource;

      const sources = fs.sources;
      const length = sources.length;

      const newMain =
        `${
        "void main() \n" +
        "{ \n" +
        "    czm_non_pick_main(); \n" +
        "    if (gl_FragColor.a == 0.0) { \n" +
        "        discard; \n" +
        "    } \n" +
        "    gl_FragColor = "
      }${pickId}; \n` + `} \n`;
      const newSources = new Array(length + 1);
      for (let i = 0; i < length; ++i) {
        newSources[i] = ShaderSource.replaceMain(sources[i], "czm_non_pick_main");
      }
      newSources[length] = newMain;
      fs = new ShaderSource({
        sources: newSources,
        defines: fs.defines,
      });
      shader = context.shaderCache.createDerivedShaderProgram(
        shaderProgram,
        "pick",
        {
          vertexShaderSource: shaderProgram.vertexShaderSource,
          fragmentShaderSource: fs,
          attributeLocations: attributeLocations,
        }
      );
    }

    return shader;
  }

  function getPickRenderState(scene, renderState) {
    const cache = scene.picking.pickRenderStateCache;
    let pickState = cache[renderState.id];
    if (!defined(pickState)) {
      const rs = RenderState.getState(renderState);
      rs.blending.enabled = false;

      // Turns on depth writing for opaque and translucent passes
      // Overlapping translucent geometry on the globe surface may exhibit z-fighting
      // during the pick pass which may not match the rendered scene. Once
      // terrain is on by default and ground primitives are used instead
      // this will become less of a problem.
      rs.depthMask = true;

      pickState = RenderState.fromCache(rs);
      cache[renderState.id] = pickState;
    }

    return pickState;
  }

  DerivedCommand.createPickDerivedCommand = function (
    scene,
    command,
    context,
    result
  ) {
    if (!defined(result)) {
      result = {};
    }

    let shader;
    let renderState;
    if (defined(result.pickCommand)) {
      shader = result.pickCommand.shaderProgram;
      renderState = result.pickCommand.renderState;
    }

    result.pickCommand = DrawCommand.shallowClone(command, result.pickCommand);

    if (!defined(shader) || result.shaderProgramId !== command.shaderProgram.id) {
      result.pickCommand.shaderProgram = getPickShaderProgram$1(
        context,
        command.shaderProgram,
        command.pickId
      );
      result.pickCommand.renderState = getPickRenderState(
        scene,
        command.renderState
      );
      result.shaderProgramId = command.shaderProgram.id;
    } else {
      result.pickCommand.shaderProgram = shader;
      result.pickCommand.renderState = renderState;
    }

    return result;
  };

  function getHdrShaderProgram(context, shaderProgram) {
    let shader = context.shaderCache.getDerivedShaderProgram(
      shaderProgram,
      "HDR"
    );
    if (!defined(shader)) {
      const attributeLocations = shaderProgram._attributeLocations;
      const vs = shaderProgram.vertexShaderSource.clone();
      const fs = shaderProgram.fragmentShaderSource.clone();

      vs.defines = defined(vs.defines) ? vs.defines.slice(0) : [];
      vs.defines.push("HDR");
      fs.defines = defined(fs.defines) ? fs.defines.slice(0) : [];
      fs.defines.push("HDR");

      shader = context.shaderCache.createDerivedShaderProgram(
        shaderProgram,
        "HDR",
        {
          vertexShaderSource: vs,
          fragmentShaderSource: fs,
          attributeLocations: attributeLocations,
        }
      );
    }

    return shader;
  }

  DerivedCommand.createHdrCommand = function (command, context, result) {
    if (!defined(result)) {
      result = {};
    }

    let shader;
    if (defined(result.command)) {
      shader = result.command.shaderProgram;
    }

    result.command = DrawCommand.shallowClone(command, result.command);

    if (!defined(shader) || result.shaderProgramId !== command.shaderProgram.id) {
      result.command.shaderProgram = getHdrShaderProgram(
        context,
        command.shaderProgram
      );
      result.shaderProgramId = command.shaderProgram.id;
    } else {
      result.command.shaderProgram = shader;
    }

    return result;
  };

  /**
   * @private
   */
  function DeviceOrientationCameraController(scene) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(scene)) {
      throw new DeveloperError("scene is required.");
    }
    //>>includeEnd('debug');

    this._scene = scene;

    this._lastAlpha = undefined;
    this._lastBeta = undefined;
    this._lastGamma = undefined;

    this._alpha = undefined;
    this._beta = undefined;
    this._gamma = undefined;

    const that = this;

    function callback(e) {
      const alpha = e.alpha;
      if (!defined(alpha)) {
        that._alpha = undefined;
        that._beta = undefined;
        that._gamma = undefined;
        return;
      }

      that._alpha = CesiumMath.toRadians(alpha);
      that._beta = CesiumMath.toRadians(e.beta);
      that._gamma = CesiumMath.toRadians(e.gamma);
    }

    window.addEventListener("deviceorientation", callback, false);

    this._removeListener = function () {
      window.removeEventListener("deviceorientation", callback, false);
    };
  }

  const scratchQuaternion1 = new Quaternion();
  const scratchQuaternion2 = new Quaternion();
  const scratchMatrix3 = new Matrix3();

  function rotate(camera, alpha, beta, gamma) {
    const direction = camera.direction;
    const right = camera.right;
    const up = camera.up;

    const bQuat = Quaternion.fromAxisAngle(direction, beta, scratchQuaternion2);
    const gQuat = Quaternion.fromAxisAngle(right, gamma, scratchQuaternion1);

    const rotQuat = Quaternion.multiply(gQuat, bQuat, gQuat);

    const aQuat = Quaternion.fromAxisAngle(up, alpha, scratchQuaternion2);
    Quaternion.multiply(aQuat, rotQuat, rotQuat);

    const matrix = Matrix3.fromQuaternion(rotQuat, scratchMatrix3);
    Matrix3.multiplyByVector(matrix, right, right);
    Matrix3.multiplyByVector(matrix, up, up);
    Matrix3.multiplyByVector(matrix, direction, direction);
  }

  DeviceOrientationCameraController.prototype.update = function () {
    if (!defined(this._alpha)) {
      return;
    }

    if (!defined(this._lastAlpha)) {
      this._lastAlpha = this._alpha;
      this._lastBeta = this._beta;
      this._lastGamma = this._gamma;
    }

    const a = this._lastAlpha - this._alpha;
    const b = this._lastBeta - this._beta;
    const g = this._lastGamma - this._gamma;

    rotate(this._scene.camera, -a, b, g);

    this._lastAlpha = this._alpha;
    this._lastBeta = this._beta;
    this._lastGamma = this._gamma;
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   */
  DeviceOrientationCameraController.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the resources held by this object.  Destroying an object allows for deterministic
   * release of resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   */
  DeviceOrientationCameraController.prototype.destroy = function () {
    this._removeListener();
    return destroyObject(this);
  };

  /**
   * A light that gets emitted in a single direction from infinitely far away.
   *
   * @param {Object} options Object with the following properties:
   * @param {Cartesian3} options.direction The direction in which light gets emitted.
   * @param {Color} [options.color=Color.WHITE] The color of the light.
   * @param {Number} [options.intensity=1.0] The intensity of the light.
   *
   * @exception {DeveloperError} options.direction cannot be zero-length
   *
   * @alias DirectionalLight
   * @constructor
   */
  function DirectionalLight(options) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options", options);
    Check.typeOf.object("options.direction", options.direction);
    if (Cartesian3.equals(options.direction, Cartesian3.ZERO)) {
      throw new DeveloperError("options.direction cannot be zero-length");
    }
    //>>includeEnd('debug');

    /**
     * The direction in which light gets emitted.
     * @type {Cartesian3}
     */
    this.direction = Cartesian3.clone(options.direction);

    /**
     * The color of the light.
     * @type {Color}
     * @default Color.WHITE
     */
    this.color = Color.clone(defaultValue(options.color, Color.WHITE));

    /**
     * The intensity of the light.
     * @type {Number}
     * @default 1.0
     */
    this.intensity = defaultValue(options.intensity, 1.0);
  }

  //This file is automatically rebuilt by the Cesium build process.
  var EllipsoidFS = "#ifdef WRITE_DEPTH\n\
#ifdef GL_EXT_frag_depth\n\
#extension GL_EXT_frag_depth : enable\n\
#endif\n\
#endif\n\
uniform vec3 u_radii;\n\
uniform vec3 u_oneOverEllipsoidRadiiSquared;\n\
varying vec3 v_positionEC;\n\
vec4 computeEllipsoidColor(czm_ray ray, float intersection, float side)\n\
{\n\
vec3 positionEC = czm_pointAlongRay(ray, intersection);\n\
vec3 positionMC = (czm_inverseModelView * vec4(positionEC, 1.0)).xyz;\n\
vec3 geodeticNormal = normalize(czm_geodeticSurfaceNormal(positionMC, vec3(0.0), u_oneOverEllipsoidRadiiSquared));\n\
vec3 sphericalNormal = normalize(positionMC / u_radii);\n\
vec3 normalMC = geodeticNormal * side;\n\
vec3 normalEC = normalize(czm_normal * normalMC);\n\
vec2 st = czm_ellipsoidWgs84TextureCoordinates(sphericalNormal);\n\
vec3 positionToEyeEC = -positionEC;\n\
czm_materialInput materialInput;\n\
materialInput.s = st.s;\n\
materialInput.st = st;\n\
materialInput.str = (positionMC + u_radii) / u_radii;\n\
materialInput.normalEC = normalEC;\n\
materialInput.tangentToEyeMatrix = czm_eastNorthUpToEyeCoordinates(positionMC, normalEC);\n\
materialInput.positionToEyeEC = positionToEyeEC;\n\
czm_material material = czm_getMaterial(materialInput);\n\
#ifdef ONLY_SUN_LIGHTING\n\
return czm_private_phong(normalize(positionToEyeEC), material, czm_sunDirectionEC);\n\
#else\n\
return czm_phong(normalize(positionToEyeEC), material, czm_lightDirectionEC);\n\
#endif\n\
}\n\
void main()\n\
{\n\
float maxRadius = max(u_radii.x, max(u_radii.y, u_radii.z)) * 1.5;\n\
vec3 direction = normalize(v_positionEC);\n\
vec3 ellipsoidCenter = czm_modelView[3].xyz;\n\
float t1 = -1.0;\n\
float t2 = -1.0;\n\
float b = -2.0 * dot(direction, ellipsoidCenter);\n\
float c = dot(ellipsoidCenter, ellipsoidCenter) - maxRadius * maxRadius;\n\
float discriminant = b * b - 4.0 * c;\n\
if (discriminant >= 0.0) {\n\
t1 = (-b - sqrt(discriminant)) * 0.5;\n\
t2 = (-b + sqrt(discriminant)) * 0.5;\n\
}\n\
if (t1 < 0.0 && t2 < 0.0) {\n\
discard;\n\
}\n\
float t = min(t1, t2);\n\
if (t < 0.0) {\n\
t = 0.0;\n\
}\n\
czm_ray ray = czm_ray(t * direction, direction);\n\
vec3 ellipsoid_inverseRadii = vec3(1.0 / u_radii.x, 1.0 / u_radii.y, 1.0 / u_radii.z);\n\
czm_raySegment intersection = czm_rayEllipsoidIntersectionInterval(ray, ellipsoidCenter, ellipsoid_inverseRadii);\n\
if (czm_isEmpty(intersection))\n\
{\n\
discard;\n\
}\n\
vec4 outsideFaceColor = (intersection.start != 0.0) ? computeEllipsoidColor(ray, intersection.start, 1.0) : vec4(0.0);\n\
vec4 insideFaceColor = (outsideFaceColor.a < 1.0) ? computeEllipsoidColor(ray, intersection.stop, -1.0) : vec4(0.0);\n\
gl_FragColor = mix(insideFaceColor, outsideFaceColor, outsideFaceColor.a);\n\
gl_FragColor.a = 1.0 - (1.0 - insideFaceColor.a) * (1.0 - outsideFaceColor.a);\n\
#ifdef WRITE_DEPTH\n\
#ifdef GL_EXT_frag_depth\n\
t = (intersection.start != 0.0) ? intersection.start : intersection.stop;\n\
vec3 positionEC = czm_pointAlongRay(ray, t);\n\
vec4 positionCC = czm_projection * vec4(positionEC, 1.0);\n\
#ifdef LOG_DEPTH\n\
czm_writeLogDepth(1.0 + positionCC.w);\n\
#else\n\
float z = positionCC.z / positionCC.w;\n\
float n = czm_depthRange.near;\n\
float f = czm_depthRange.far;\n\
gl_FragDepthEXT = (z * (f - n) + f + n) * 0.5;\n\
#endif\n\
#endif\n\
#endif\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var EllipsoidVS = "attribute vec3 position;\n\
uniform vec3 u_radii;\n\
varying vec3 v_positionEC;\n\
void main()\n\
{\n\
vec4 p = vec4(u_radii * position, 1.0);\n\
v_positionEC = (czm_modelView * p).xyz;\n\
gl_Position = czm_modelViewProjection * p;\n\
gl_Position.z = clamp(gl_Position.z, czm_depthRange.near, czm_depthRange.far);\n\
czm_vertexLogDepth();\n\
}\n\
";

  const attributeLocations = {
    position: 0,
  };

  /**
   * A renderable ellipsoid.  It can also draw spheres when the three {@link EllipsoidPrimitive#radii} components are equal.
   * <p>
   * This is only supported in 3D.  The ellipsoid is not shown in 2D or Columbus view.
   * </p>
   *
   * @alias EllipsoidPrimitive
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Cartesian3} [options.center=Cartesian3.ZERO] The center of the ellipsoid in the ellipsoid's model coordinates.
   * @param {Cartesian3} [options.radii] The radius of the ellipsoid along the <code>x</code>, <code>y</code>, and <code>z</code> axes in the ellipsoid's model coordinates.
   * @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] The 4x4 transformation matrix that transforms the ellipsoid from model to world coordinates.
   * @param {Boolean} [options.show=true] Determines if this primitive will be shown.
   * @param {Material} [options.material=Material.ColorType] The surface appearance of the primitive.
   * @param {Object} [options.id] A user-defined object to return when the instance is picked with {@link Scene#pick}
   * @param {Boolean} [options.debugShowBoundingVolume=false] For debugging only. Determines if this primitive's commands' bounding spheres are shown.
   *
   * @private
   */
  function EllipsoidPrimitive(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    /**
     * The center of the ellipsoid in the ellipsoid's model coordinates.
     * <p>
     * The default is {@link Cartesian3.ZERO}.
     * </p>
     *
     * @type {Cartesian3}
     * @default {@link Cartesian3.ZERO}
     *
     * @see EllipsoidPrimitive#modelMatrix
     */
    this.center = Cartesian3.clone(defaultValue(options.center, Cartesian3.ZERO));
    this._center = new Cartesian3();

    /**
     * The radius of the ellipsoid along the <code>x</code>, <code>y</code>, and <code>z</code> axes in the ellipsoid's model coordinates.
     * When these are the same, the ellipsoid is a sphere.
     * <p>
     * The default is <code>undefined</code>.  The ellipsoid is not drawn until a radii is provided.
     * </p>
     *
     * @type {Cartesian3}
     * @default undefined
     *
     *
     * @example
     * // A sphere with a radius of 2.0
     * e.radii = new Cesium.Cartesian3(2.0, 2.0, 2.0);
     *
     * @see EllipsoidPrimitive#modelMatrix
     */
    this.radii = Cartesian3.clone(options.radii);
    this._radii = new Cartesian3();

    this._oneOverEllipsoidRadiiSquared = new Cartesian3();
    this._boundingSphere = new BoundingSphere();

    /**
     * The 4x4 transformation matrix that transforms the ellipsoid from model to world coordinates.
     * When this is the identity matrix, the ellipsoid is drawn in world coordinates, i.e., Earth's WGS84 coordinates.
     * Local reference frames can be used by providing a different transformation matrix, like that returned
     * by {@link Transforms.eastNorthUpToFixedFrame}.
     *
     * @type {Matrix4}
     * @default {@link Matrix4.IDENTITY}
     *
     * @example
     * const origin = Cesium.Cartesian3.fromDegrees(-95.0, 40.0, 200000.0);
     * e.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(origin);
     */
    this.modelMatrix = Matrix4.clone(
      defaultValue(options.modelMatrix, Matrix4.IDENTITY)
    );
    this._modelMatrix = new Matrix4();
    this._computedModelMatrix = new Matrix4();

    /**
     * Determines if the ellipsoid primitive will be shown.
     *
     * @type {Boolean}
     * @default true
     */
    this.show = defaultValue(options.show, true);

    /**
     * The surface appearance of the ellipsoid.  This can be one of several built-in {@link Material} objects or a custom material, scripted with
     * {@link https://github.com/CesiumGS/cesium/wiki/Fabric|Fabric}.
     * <p>
     * The default material is <code>Material.ColorType</code>.
     * </p>
     *
     * @type {Material}
     * @default Material.fromType(Material.ColorType)
     *
     *
     * @example
     * // 1. Change the color of the default material to yellow
     * e.material.uniforms.color = new Cesium.Color(1.0, 1.0, 0.0, 1.0);
     *
     * // 2. Change material to horizontal stripes
     * e.material = Cesium.Material.fromType(Cesium.Material.StripeType);
     *
     * @see {@link https://github.com/CesiumGS/cesium/wiki/Fabric|Fabric}
     */
    this.material = defaultValue(
      options.material,
      Material$4.fromType(Material$4.ColorType)
    );
    this._material = undefined;
    this._translucent = undefined;

    /**
     * User-defined object returned when the ellipsoid is picked.
     *
     * @type Object
     *
     * @default undefined
     *
     * @see Scene#pick
     */
    this.id = options.id;
    this._id = undefined;

    /**
     * This property is for debugging only; it is not for production use nor is it optimized.
     * <p>
     * Draws the bounding sphere for each draw command in the primitive.
     * </p>
     *
     * @type {Boolean}
     *
     * @default false
     */
    this.debugShowBoundingVolume = defaultValue(
      options.debugShowBoundingVolume,
      false
    );

    /**
     * @private
     */
    this.onlySunLighting = defaultValue(options.onlySunLighting, false);
    this._onlySunLighting = false;

    /**
     * @private
     */
    this._depthTestEnabled = defaultValue(options.depthTestEnabled, true);

    this._useLogDepth = false;

    this._sp = undefined;
    this._rs = undefined;
    this._va = undefined;

    this._pickSP = undefined;
    this._pickId = undefined;

    this._colorCommand = new DrawCommand({
      owner: defaultValue(options._owner, this),
    });
    this._pickCommand = new DrawCommand({
      owner: defaultValue(options._owner, this),
      pickOnly: true,
    });

    const that = this;
    this._uniforms = {
      u_radii: function () {
        return that.radii;
      },
      u_oneOverEllipsoidRadiiSquared: function () {
        return that._oneOverEllipsoidRadiiSquared;
      },
    };

    this._pickUniforms = {
      czm_pickColor: function () {
        return that._pickId.color;
      },
    };
  }

  function getVertexArray(context) {
    let vertexArray = context.cache.ellipsoidPrimitive_vertexArray;

    if (defined(vertexArray)) {
      return vertexArray;
    }

    const geometry = BoxGeometry.createGeometry(
      BoxGeometry.fromDimensions({
        dimensions: new Cartesian3(2.0, 2.0, 2.0),
        vertexFormat: VertexFormat.POSITION_ONLY,
      })
    );

    vertexArray = VertexArray.fromGeometry({
      context: context,
      geometry: geometry,
      attributeLocations: attributeLocations,
      bufferUsage: BufferUsage$1.STATIC_DRAW,
      interleave: true,
    });

    context.cache.ellipsoidPrimitive_vertexArray = vertexArray;
    return vertexArray;
  }

  const logDepthExtension =
    "#ifdef GL_EXT_frag_depth \n" +
    "#extension GL_EXT_frag_depth : enable \n" +
    "#endif \n\n";

  /**
   * Called when {@link Viewer} or {@link CesiumWidget} render the scene to
   * get the draw commands needed to render this primitive.
   * <p>
   * Do not call this function directly.  This is documented just to
   * list the exceptions that may be propagated when the scene is rendered:
   * </p>
   *
   * @exception {DeveloperError} this.material must be defined.
   */
  EllipsoidPrimitive.prototype.update = function (frameState) {
    if (
      !this.show ||
      frameState.mode !== SceneMode$1.SCENE3D ||
      !defined(this.center) ||
      !defined(this.radii)
    ) {
      return;
    }

    //>>includeStart('debug', pragmas.debug);
    if (!defined(this.material)) {
      throw new DeveloperError("this.material must be defined.");
    }
    //>>includeEnd('debug');

    const context = frameState.context;
    const translucent = this.material.isTranslucent();
    const translucencyChanged = this._translucent !== translucent;

    if (!defined(this._rs) || translucencyChanged) {
      this._translucent = translucent;

      // If this render state is ever updated to use a non-default
      // depth range, the hard-coded values in EllipsoidVS.glsl need
      // to be updated as well.

      this._rs = RenderState.fromCache({
        // Cull front faces - not back faces - so the ellipsoid doesn't
        // disappear if the viewer enters the bounding box.
        cull: {
          enabled: true,
          face: CullFace$1.FRONT,
        },
        depthTest: {
          enabled: this._depthTestEnabled,
        },
        // Only write depth when EXT_frag_depth is supported since the depth for
        // the bounding box is wrong; it is not the true depth of the ray casted ellipsoid.
        depthMask: !translucent && context.fragmentDepth,
        blending: translucent ? BlendingState$1.ALPHA_BLEND : undefined,
      });
    }

    if (!defined(this._va)) {
      this._va = getVertexArray(context);
    }

    let boundingSphereDirty = false;

    const radii = this.radii;
    if (!Cartesian3.equals(this._radii, radii)) {
      Cartesian3.clone(radii, this._radii);

      const r = this._oneOverEllipsoidRadiiSquared;
      r.x = 1.0 / (radii.x * radii.x);
      r.y = 1.0 / (radii.y * radii.y);
      r.z = 1.0 / (radii.z * radii.z);

      boundingSphereDirty = true;
    }

    if (
      !Matrix4.equals(this.modelMatrix, this._modelMatrix) ||
      !Cartesian3.equals(this.center, this._center)
    ) {
      Matrix4.clone(this.modelMatrix, this._modelMatrix);
      Cartesian3.clone(this.center, this._center);

      // Translate model coordinates used for rendering such that the origin is the center of the ellipsoid.
      Matrix4.multiplyByTranslation(
        this.modelMatrix,
        this.center,
        this._computedModelMatrix
      );
      boundingSphereDirty = true;
    }

    if (boundingSphereDirty) {
      Cartesian3.clone(Cartesian3.ZERO, this._boundingSphere.center);
      this._boundingSphere.radius = Cartesian3.maximumComponent(radii);
      BoundingSphere.transform(
        this._boundingSphere,
        this._computedModelMatrix,
        this._boundingSphere
      );
    }

    const materialChanged = this._material !== this.material;
    this._material = this.material;
    this._material.update(context);

    const lightingChanged = this.onlySunLighting !== this._onlySunLighting;
    this._onlySunLighting = this.onlySunLighting;

    const useLogDepth = frameState.useLogDepth;
    const useLogDepthChanged = this._useLogDepth !== useLogDepth;
    this._useLogDepth = useLogDepth;

    const colorCommand = this._colorCommand;
    let vs;
    let fs;

    // Recompile shader when material, lighting, or translucency changes
    if (
      materialChanged ||
      lightingChanged ||
      translucencyChanged ||
      useLogDepthChanged
    ) {
      vs = new ShaderSource({
        sources: [EllipsoidVS],
      });
      fs = new ShaderSource({
        sources: [this.material.shaderSource, EllipsoidFS],
      });
      if (this.onlySunLighting) {
        fs.defines.push("ONLY_SUN_LIGHTING");
      }
      if (!translucent && context.fragmentDepth) {
        fs.defines.push("WRITE_DEPTH");
      }
      if (this._useLogDepth) {
        vs.defines.push("LOG_DEPTH");
        fs.defines.push("LOG_DEPTH");
        fs.sources.push(logDepthExtension);
      }

      this._sp = ShaderProgram.replaceCache({
        context: context,
        shaderProgram: this._sp,
        vertexShaderSource: vs,
        fragmentShaderSource: fs,
        attributeLocations: attributeLocations,
      });

      colorCommand.vertexArray = this._va;
      colorCommand.renderState = this._rs;
      colorCommand.shaderProgram = this._sp;
      colorCommand.uniformMap = combine$2(this._uniforms, this.material._uniforms);
      colorCommand.executeInClosestFrustum = translucent;
    }

    const commandList = frameState.commandList;
    const passes = frameState.passes;

    if (passes.render) {
      colorCommand.boundingVolume = this._boundingSphere;
      colorCommand.debugShowBoundingVolume = this.debugShowBoundingVolume;
      colorCommand.modelMatrix = this._computedModelMatrix;
      colorCommand.pass = translucent ? Pass$1.TRANSLUCENT : Pass$1.OPAQUE;

      commandList.push(colorCommand);
    }

    if (passes.pick) {
      const pickCommand = this._pickCommand;

      if (!defined(this._pickId) || this._id !== this.id) {
        this._id = this.id;
        this._pickId = this._pickId && this._pickId.destroy();
        this._pickId = context.createPickId({
          primitive: this,
          id: this.id,
        });
      }

      // Recompile shader when material changes
      if (
        materialChanged ||
        lightingChanged ||
        !defined(this._pickSP) ||
        useLogDepthChanged
      ) {
        vs = new ShaderSource({
          sources: [EllipsoidVS],
        });
        fs = new ShaderSource({
          sources: [this.material.shaderSource, EllipsoidFS],
          pickColorQualifier: "uniform",
        });
        if (this.onlySunLighting) {
          fs.defines.push("ONLY_SUN_LIGHTING");
        }
        if (!translucent && context.fragmentDepth) {
          fs.defines.push("WRITE_DEPTH");
        }
        if (this._useLogDepth) {
          vs.defines.push("LOG_DEPTH");
          fs.defines.push("LOG_DEPTH");
          fs.sources.push(logDepthExtension);
        }

        this._pickSP = ShaderProgram.replaceCache({
          context: context,
          shaderProgram: this._pickSP,
          vertexShaderSource: vs,
          fragmentShaderSource: fs,
          attributeLocations: attributeLocations,
        });

        pickCommand.vertexArray = this._va;
        pickCommand.renderState = this._rs;
        pickCommand.shaderProgram = this._pickSP;
        pickCommand.uniformMap = combine$2(
          combine$2(this._uniforms, this._pickUniforms),
          this.material._uniforms
        );
        pickCommand.executeInClosestFrustum = translucent;
      }

      pickCommand.boundingVolume = this._boundingSphere;
      pickCommand.modelMatrix = this._computedModelMatrix;
      pickCommand.pass = translucent ? Pass$1.TRANSLUCENT : Pass$1.OPAQUE;

      commandList.push(pickCommand);
    }
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see EllipsoidPrimitive#destroy
   */
  EllipsoidPrimitive.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * e = e && e.destroy();
   *
   * @see EllipsoidPrimitive#isDestroyed
   */
  EllipsoidPrimitive.prototype.destroy = function () {
    this._sp = this._sp && this._sp.destroy();
    this._pickSP = this._pickSP && this._pickSP.destroy();
    this._pickId = this._pickId && this._pickId.destroy();
    return destroyObject(this);
  };

  //This file is automatically rebuilt by the Cesium build process.
  var EllipsoidSurfaceAppearanceFS = "varying vec3 v_positionMC;\n\
varying vec3 v_positionEC;\n\
varying vec2 v_st;\n\
void main()\n\
{\n\
czm_materialInput materialInput;\n\
vec3 normalEC = normalize(czm_normal3D * czm_geodeticSurfaceNormal(v_positionMC, vec3(0.0), vec3(1.0)));\n\
#ifdef FACE_FORWARD\n\
normalEC = faceforward(normalEC, vec3(0.0, 0.0, 1.0), -normalEC);\n\
#endif\n\
materialInput.s = v_st.s;\n\
materialInput.st = v_st;\n\
materialInput.str = vec3(v_st, 0.0);\n\
materialInput.normalEC = normalEC;\n\
materialInput.tangentToEyeMatrix = czm_eastNorthUpToEyeCoordinates(v_positionMC, materialInput.normalEC);\n\
vec3 positionToEyeEC = -v_positionEC;\n\
materialInput.positionToEyeEC = positionToEyeEC;\n\
czm_material material = czm_getMaterial(materialInput);\n\
#ifdef FLAT\n\
gl_FragColor = vec4(material.diffuse + material.emission, material.alpha);\n\
#else\n\
gl_FragColor = czm_phong(normalize(positionToEyeEC), material, czm_lightDirectionEC);\n\
#endif\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var EllipsoidSurfaceAppearanceVS = "attribute vec3 position3DHigh;\n\
attribute vec3 position3DLow;\n\
attribute vec2 st;\n\
attribute float batchId;\n\
varying vec3 v_positionMC;\n\
varying vec3 v_positionEC;\n\
varying vec2 v_st;\n\
void main()\n\
{\n\
vec4 p = czm_computePosition();\n\
v_positionMC = position3DHigh + position3DLow;\n\
v_positionEC = (czm_modelViewRelativeToEye * p).xyz;\n\
v_st = st;\n\
gl_Position = czm_modelViewProjectionRelativeToEye * p;\n\
}\n\
";

  /**
   * An appearance for geometry on the surface of the ellipsoid like {@link PolygonGeometry}
   * and {@link RectangleGeometry}, which supports all materials like {@link MaterialAppearance}
   * with {@link MaterialAppearance.MaterialSupport.ALL}.  However, this appearance requires
   * fewer vertex attributes since the fragment shader can procedurally compute <code>normal</code>,
   * <code>tangent</code>, and <code>bitangent</code>.
   *
   * @alias EllipsoidSurfaceAppearance
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Boolean} [options.flat=false] When <code>true</code>, flat shading is used in the fragment shader, which means lighting is not taking into account.
   * @param {Boolean} [options.faceForward=options.aboveGround] When <code>true</code>, the fragment shader flips the surface normal as needed to ensure that the normal faces the viewer to avoid dark spots.  This is useful when both sides of a geometry should be shaded like {@link WallGeometry}.
   * @param {Boolean} [options.translucent=true] When <code>true</code>, the geometry is expected to appear translucent so {@link EllipsoidSurfaceAppearance#renderState} has alpha blending enabled.
   * @param {Boolean} [options.aboveGround=false] When <code>true</code>, the geometry is expected to be on the ellipsoid's surface - not at a constant height above it - so {@link EllipsoidSurfaceAppearance#renderState} has backface culling enabled.
   * @param {Material} [options.material=Material.ColorType] The material used to determine the fragment color.
   * @param {String} [options.vertexShaderSource] Optional GLSL vertex shader source to override the default vertex shader.
   * @param {String} [options.fragmentShaderSource] Optional GLSL fragment shader source to override the default fragment shader.
   * @param {Object} [options.renderState] Optional render state to override the default render state.
   *
   * @see {@link https://github.com/CesiumGS/cesium/wiki/Fabric|Fabric}
   *
   * @example
   * const primitive = new Cesium.Primitive({
   *   geometryInstances : new Cesium.GeometryInstance({
   *     geometry : new Cesium.PolygonGeometry({
   *       vertexFormat : Cesium.EllipsoidSurfaceAppearance.VERTEX_FORMAT,
   *       // ...
   *     })
   *   }),
   *   appearance : new Cesium.EllipsoidSurfaceAppearance({
   *     material : Cesium.Material.fromType('Stripe')
   *   })
   * });
   */
  function EllipsoidSurfaceAppearance(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const translucent = defaultValue(options.translucent, true);
    const aboveGround = defaultValue(options.aboveGround, false);

    /**
     * The material used to determine the fragment color.  Unlike other {@link EllipsoidSurfaceAppearance}
     * properties, this is not read-only, so an appearance's material can change on the fly.
     *
     * @type Material
     *
     * @default {@link Material.ColorType}
     *
     * @see {@link https://github.com/CesiumGS/cesium/wiki/Fabric|Fabric}
     */
    this.material = defined(options.material)
      ? options.material
      : Material$4.fromType(Material$4.ColorType);

    /**
     * When <code>true</code>, the geometry is expected to appear translucent.
     *
     * @type {Boolean}
     *
     * @default true
     */
    this.translucent = defaultValue(options.translucent, true);

    this._vertexShaderSource = defaultValue(
      options.vertexShaderSource,
      EllipsoidSurfaceAppearanceVS
    );
    this._fragmentShaderSource = defaultValue(
      options.fragmentShaderSource,
      EllipsoidSurfaceAppearanceFS
    );
    this._renderState = Appearance.getDefaultRenderState(
      translucent,
      !aboveGround,
      options.renderState
    );
    this._closed = false;

    // Non-derived members

    this._flat = defaultValue(options.flat, false);
    this._faceForward = defaultValue(options.faceForward, aboveGround);
    this._aboveGround = aboveGround;
  }

  Object.defineProperties(EllipsoidSurfaceAppearance.prototype, {
    /**
     * The GLSL source code for the vertex shader.
     *
     * @memberof EllipsoidSurfaceAppearance.prototype
     *
     * @type {String}
     * @readonly
     */
    vertexShaderSource: {
      get: function () {
        return this._vertexShaderSource;
      },
    },

    /**
     * The GLSL source code for the fragment shader.  The full fragment shader
     * source is built procedurally taking into account {@link EllipsoidSurfaceAppearance#material},
     * {@link EllipsoidSurfaceAppearance#flat}, and {@link EllipsoidSurfaceAppearance#faceForward}.
     * Use {@link EllipsoidSurfaceAppearance#getFragmentShaderSource} to get the full source.
     *
     * @memberof EllipsoidSurfaceAppearance.prototype
     *
     * @type {String}
     * @readonly
     */
    fragmentShaderSource: {
      get: function () {
        return this._fragmentShaderSource;
      },
    },

    /**
     * The WebGL fixed-function state to use when rendering the geometry.
     * <p>
     * The render state can be explicitly defined when constructing a {@link EllipsoidSurfaceAppearance}
     * instance, or it is set implicitly via {@link EllipsoidSurfaceAppearance#translucent}
     * and {@link EllipsoidSurfaceAppearance#aboveGround}.
     * </p>
     *
     * @memberof EllipsoidSurfaceAppearance.prototype
     *
     * @type {Object}
     * @readonly
     */
    renderState: {
      get: function () {
        return this._renderState;
      },
    },

    /**
     * When <code>true</code>, the geometry is expected to be closed so
     * {@link EllipsoidSurfaceAppearance#renderState} has backface culling enabled.
     * If the viewer enters the geometry, it will not be visible.
     *
     * @memberof EllipsoidSurfaceAppearance.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default false
     */
    closed: {
      get: function () {
        return this._closed;
      },
    },

    /**
     * The {@link VertexFormat} that this appearance instance is compatible with.
     * A geometry can have more vertex attributes and still be compatible - at a
     * potential performance cost - but it can't have less.
     *
     * @memberof EllipsoidSurfaceAppearance.prototype
     *
     * @type VertexFormat
     * @readonly
     *
     * @default {@link EllipsoidSurfaceAppearance.VERTEX_FORMAT}
     */
    vertexFormat: {
      get: function () {
        return EllipsoidSurfaceAppearance.VERTEX_FORMAT;
      },
    },

    /**
     * When <code>true</code>, flat shading is used in the fragment shader,
     * which means lighting is not taking into account.
     *
     * @memberof EllipsoidSurfaceAppearance.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default false
     */
    flat: {
      get: function () {
        return this._flat;
      },
    },

    /**
     * When <code>true</code>, the fragment shader flips the surface normal
     * as needed to ensure that the normal faces the viewer to avoid
     * dark spots.  This is useful when both sides of a geometry should be
     * shaded like {@link WallGeometry}.
     *
     * @memberof EllipsoidSurfaceAppearance.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default true
     */
    faceForward: {
      get: function () {
        return this._faceForward;
      },
    },

    /**
     * When <code>true</code>, the geometry is expected to be on the ellipsoid's
     * surface - not at a constant height above it - so {@link EllipsoidSurfaceAppearance#renderState}
     * has backface culling enabled.
     *
     *
     * @memberof EllipsoidSurfaceAppearance.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @default false
     */
    aboveGround: {
      get: function () {
        return this._aboveGround;
      },
    },
  });

  /**
   * The {@link VertexFormat} that all {@link EllipsoidSurfaceAppearance} instances
   * are compatible with, which requires only <code>position</code> and <code>st</code>
   * attributes.  Other attributes are procedurally computed in the fragment shader.
   *
   * @type VertexFormat
   *
   * @constant
   */
  EllipsoidSurfaceAppearance.VERTEX_FORMAT = VertexFormat.POSITION_AND_ST;

  /**
   * Procedurally creates the full GLSL fragment shader source.  For {@link EllipsoidSurfaceAppearance},
   * this is derived from {@link EllipsoidSurfaceAppearance#fragmentShaderSource}, {@link EllipsoidSurfaceAppearance#flat},
   * and {@link EllipsoidSurfaceAppearance#faceForward}.
   *
   * @function
   *
   * @returns {String} The full GLSL fragment shader source.
   */
  EllipsoidSurfaceAppearance.prototype.getFragmentShaderSource =
    Appearance.prototype.getFragmentShaderSource;

  /**
   * Determines if the geometry is translucent based on {@link EllipsoidSurfaceAppearance#translucent} and {@link Material#isTranslucent}.
   *
   * @function
   *
   * @returns {Boolean} <code>true</code> if the appearance is translucent.
   */
  EllipsoidSurfaceAppearance.prototype.isTranslucent =
    Appearance.prototype.isTranslucent;

  /**
   * Creates a render state.  This is not the final render state instance; instead,
   * it can contain a subset of render state properties identical to the render state
   * created in the context.
   *
   * @function
   *
   * @returns {Object} The render state.
   */
  EllipsoidSurfaceAppearance.prototype.getRenderState =
    Appearance.prototype.getRenderState;

  /**
   * Blends the atmosphere to geometry far from the camera for horizon views. Allows for additional
   * performance improvements by rendering less geometry and dispatching less terrain requests.
   *
   * @alias Fog
   * @constructor
   */
  function Fog() {
    /**
     * <code>true</code> if fog is enabled, <code>false</code> otherwise.
     * @type {Boolean}
     * @default true
     */
    this.enabled = true;
    /**
     * <code>true</code> if fog is renderable in shaders, <code>false</code> otherwise.
     * This allows to benefits from optimized tile loading strategy based on fog density without the actual visual rendering.
     * @type {Boolean}
     * @default true
     */
    this.renderable = true;
    /**
     * A scalar that determines the density of the fog. Terrain that is in full fog are culled.
     * The density of the fog increases as this number approaches 1.0 and becomes less dense as it approaches zero.
     * The more dense the fog is, the more aggressively the terrain is culled. For example, if the camera is a height of
     * 1000.0m above the ellipsoid, increasing the value to 3.0e-3 will cause many tiles close to the viewer be culled.
     * Decreasing the value will push the fog further from the viewer, but decrease performance as more of the terrain is rendered.
     * @type {Number}
     * @default 2.0e-4
     */
    this.density = 2.0e-4;
    /**
     * A factor used to increase the screen space error of terrain tiles when they are partially in fog. The effect is to reduce
     * the number of terrain tiles requested for rendering. If set to zero, the feature will be disabled. If the value is increased
     * for mountainous regions, less tiles will need to be requested, but the terrain meshes near the horizon may be a noticeably
     * lower resolution. If the value is increased in a relatively flat area, there will be little noticeable change on the horizon.
     * @type {Number}
     * @default 2.0
     */
    this.screenSpaceErrorFactor = 2.0;
    /**
     * The minimum brightness of the fog color from lighting. A value of 0.0 can cause the fog to be completely black. A value of 1.0 will not affect
     * the brightness at all.
     * @type {Number}
     * @default 0.03
     */
    this.minimumBrightness = 0.03;
  }

  // These values were found by sampling the density at certain views and finding at what point culled tiles impacted the view at the horizon.
  const heightsTable = [
    359.393,
    800.749,
    1275.6501,
    2151.1192,
    3141.7763,
    4777.5198,
    6281.2493,
    12364.307,
    15900.765,
    49889.0549,
    78026.8259,
    99260.7344,
    120036.3873,
    151011.0158,
    156091.1953,
    203849.3112,
    274866.9803,
    319916.3149,
    493552.0528,
    628733.5874,
  ];
  const densityTable = [
    2.0e-5,
    2.0e-4,
    1.0e-4,
    7.0e-5,
    5.0e-5,
    4.0e-5,
    3.0e-5,
    1.9e-5,
    1.0e-5,
    8.5e-6,
    6.2e-6,
    5.8e-6,
    5.3e-6,
    5.2e-6,
    5.1e-6,
    4.2e-6,
    4.0e-6,
    3.4e-6,
    2.6e-6,
    2.2e-6,
  ];

  // Scale densities by 1e6 to bring lowest value to ~1. Prevents divide by zero.
  for (let i = 0; i < densityTable.length; ++i) {
    densityTable[i] *= 1.0e6;
  }
  // Change range to [0, 1].
  const tableStartDensity = densityTable[1];
  const tableEndDensity = densityTable[densityTable.length - 1];
  for (let j = 0; j < densityTable.length; ++j) {
    densityTable[j] =
      (densityTable[j] - tableEndDensity) / (tableStartDensity - tableEndDensity);
  }

  let tableLastIndex = 0;

  function findInterval(height) {
    const heights = heightsTable;
    const length = heights.length;

    if (height < heights[0]) {
      tableLastIndex = 0;
      return tableLastIndex;
    } else if (height > heights[length - 1]) {
      tableLastIndex = length - 2;
      return tableLastIndex;
    }

    // Take advantage of temporal coherence by checking current, next and previous intervals
    // for containment of time.
    if (height >= heights[tableLastIndex]) {
      if (tableLastIndex + 1 < length && height < heights[tableLastIndex + 1]) {
        return tableLastIndex;
      } else if (
        tableLastIndex + 2 < length &&
        height < heights[tableLastIndex + 2]
      ) {
        ++tableLastIndex;
        return tableLastIndex;
      }
    } else if (tableLastIndex - 1 >= 0 && height >= heights[tableLastIndex - 1]) {
      --tableLastIndex;
      return tableLastIndex;
    }

    // The above failed so do a linear search.
    let i;
    for (i = 0; i < length - 2; ++i) {
      if (height >= heights[i] && height < heights[i + 1]) {
        break;
      }
    }

    tableLastIndex = i;
    return tableLastIndex;
  }

  const scratchPositionNormal$1 = new Cartesian3();

  Fog.prototype.update = function (frameState) {
    const enabled = (frameState.fog.enabled = this.enabled);
    if (!enabled) {
      return;
    }

    frameState.fog.renderable = this.renderable;

    const camera = frameState.camera;
    const positionCartographic = camera.positionCartographic;

    // Turn off fog in space.
    if (
      !defined(positionCartographic) ||
      positionCartographic.height > 800000.0 ||
      frameState.mode !== SceneMode$1.SCENE3D
    ) {
      frameState.fog.enabled = false;
      return;
    }

    const height = positionCartographic.height;
    const i = findInterval(height);
    const t = CesiumMath.clamp(
      (height - heightsTable[i]) / (heightsTable[i + 1] - heightsTable[i]),
      0.0,
      1.0
    );
    let density = CesiumMath.lerp(densityTable[i], densityTable[i + 1], t);

    // Again, scale value to be in the range of densityTable (prevents divide by zero) and change to new range.
    const startDensity = this.density * 1.0e6;
    const endDensity = (startDensity / tableStartDensity) * tableEndDensity;
    density = density * (startDensity - endDensity) * 1.0e-6;

    // Fade fog in as the camera tilts toward the horizon.
    const positionNormal = Cartesian3.normalize(
      camera.positionWC,
      scratchPositionNormal$1
    );
    const dot = Math.abs(Cartesian3.dot(camera.directionWC, positionNormal));
    density *= 1.0 - dot;

    frameState.fog.density = density;
    frameState.fog.sse = this.screenSpaceErrorFactor;
    frameState.fog.minimumBrightness = this.minimumBrightness;
  };

  /**
   * Monitors the frame rate (frames per second) in a {@link Scene} and raises an event if the frame rate is
   * lower than a threshold.  Later, if the frame rate returns to the required level, a separate event is raised.
   * To avoid creating multiple FrameRateMonitors for a single {@link Scene}, use {@link FrameRateMonitor.fromScene}
   * instead of constructing an instance explicitly.
   *
   * @alias FrameRateMonitor
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Scene} options.scene The Scene instance for which to monitor performance.
   * @param {Number} [options.samplingWindow=5.0] The length of the sliding window over which to compute the average frame rate, in seconds.
   * @param {Number} [options.quietPeriod=2.0] The length of time to wait at startup and each time the page becomes visible (i.e. when the user
   *        switches back to the tab) before starting to measure performance, in seconds.
   * @param {Number} [options.warmupPeriod=5.0] The length of the warmup period, in seconds.  During the warmup period, a separate
   *        (usually lower) frame rate is required.
   * @param {Number} [options.minimumFrameRateDuringWarmup=4] The minimum frames-per-second that are required for acceptable performance during
   *        the warmup period.  If the frame rate averages less than this during any samplingWindow during the warmupPeriod, the
   *        lowFrameRate event will be raised and the page will redirect to the redirectOnLowFrameRateUrl, if any.
   * @param {Number} [options.minimumFrameRateAfterWarmup=8] The minimum frames-per-second that are required for acceptable performance after
   *        the end of the warmup period.  If the frame rate averages less than this during any samplingWindow after the warmupPeriod, the
   *        lowFrameRate event will be raised and the page will redirect to the redirectOnLowFrameRateUrl, if any.
   */
  function FrameRateMonitor(options) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(options) || !defined(options.scene)) {
      throw new DeveloperError("options.scene is required.");
    }
    //>>includeEnd('debug');

    this._scene = options.scene;

    /**
     * Gets or sets the length of the sliding window over which to compute the average frame rate, in seconds.
     * @type {Number}
     */
    this.samplingWindow = defaultValue(
      options.samplingWindow,
      FrameRateMonitor.defaultSettings.samplingWindow
    );

    /**
     * Gets or sets the length of time to wait at startup and each time the page becomes visible (i.e. when the user
     * switches back to the tab) before starting to measure performance, in seconds.
     * @type {Number}
     */
    this.quietPeriod = defaultValue(
      options.quietPeriod,
      FrameRateMonitor.defaultSettings.quietPeriod
    );

    /**
     * Gets or sets the length of the warmup period, in seconds.  During the warmup period, a separate
     * (usually lower) frame rate is required.
     * @type {Number}
     */
    this.warmupPeriod = defaultValue(
      options.warmupPeriod,
      FrameRateMonitor.defaultSettings.warmupPeriod
    );

    /**
     * Gets or sets the minimum frames-per-second that are required for acceptable performance during
     * the warmup period.  If the frame rate averages less than this during any <code>samplingWindow</code> during the <code>warmupPeriod</code>, the
     * <code>lowFrameRate</code> event will be raised and the page will redirect to the <code>redirectOnLowFrameRateUrl</code>, if any.
     * @type {Number}
     */
    this.minimumFrameRateDuringWarmup = defaultValue(
      options.minimumFrameRateDuringWarmup,
      FrameRateMonitor.defaultSettings.minimumFrameRateDuringWarmup
    );

    /**
     * Gets or sets the minimum frames-per-second that are required for acceptable performance after
     * the end of the warmup period.  If the frame rate averages less than this during any <code>samplingWindow</code> after the <code>warmupPeriod</code>, the
     * <code>lowFrameRate</code> event will be raised and the page will redirect to the <code>redirectOnLowFrameRateUrl</code>, if any.
     * @type {Number}
     */
    this.minimumFrameRateAfterWarmup = defaultValue(
      options.minimumFrameRateAfterWarmup,
      FrameRateMonitor.defaultSettings.minimumFrameRateAfterWarmup
    );

    this._lowFrameRate = new Event();
    this._nominalFrameRate = new Event();

    this._frameTimes = [];
    this._needsQuietPeriod = true;
    this._quietPeriodEndTime = 0.0;
    this._warmupPeriodEndTime = 0.0;
    this._frameRateIsLow = false;
    this._lastFramesPerSecond = undefined;
    this._pauseCount = 0;

    const that = this;
    this._preUpdateRemoveListener = this._scene.preUpdate.addEventListener(
      function (scene, time) {
        update(that);
      }
    );

    this._hiddenPropertyName =
      document.hidden !== undefined
        ? "hidden"
        : document.mozHidden !== undefined
        ? "mozHidden"
        : document.msHidden !== undefined
        ? "msHidden"
        : document.webkitHidden !== undefined
        ? "webkitHidden"
        : undefined;

    const visibilityChangeEventName =
      document.hidden !== undefined
        ? "visibilitychange"
        : document.mozHidden !== undefined
        ? "mozvisibilitychange"
        : document.msHidden !== undefined
        ? "msvisibilitychange"
        : document.webkitHidden !== undefined
        ? "webkitvisibilitychange"
        : undefined;

    function visibilityChangeListener() {
      visibilityChanged(that);
    }

    this._visibilityChangeRemoveListener = undefined;
    if (defined(visibilityChangeEventName)) {
      document.addEventListener(
        visibilityChangeEventName,
        visibilityChangeListener,
        false
      );

      this._visibilityChangeRemoveListener = function () {
        document.removeEventListener(
          visibilityChangeEventName,
          visibilityChangeListener,
          false
        );
      };
    }
  }

  /**
   * The default frame rate monitoring settings.  These settings are used when {@link FrameRateMonitor.fromScene}
   * needs to create a new frame rate monitor, and for any settings that are not passed to the
   * {@link FrameRateMonitor} constructor.
   *
   * @memberof FrameRateMonitor
   * @type {Object}
   */
  FrameRateMonitor.defaultSettings = {
    samplingWindow: 5.0,
    quietPeriod: 2.0,
    warmupPeriod: 5.0,
    minimumFrameRateDuringWarmup: 4,
    minimumFrameRateAfterWarmup: 8,
  };

  /**
   * Gets the {@link FrameRateMonitor} for a given scene.  If the scene does not yet have
   * a {@link FrameRateMonitor}, one is created with the {@link FrameRateMonitor.defaultSettings}.
   *
   * @param {Scene} scene The scene for which to get the {@link FrameRateMonitor}.
   * @returns {FrameRateMonitor} The scene's {@link FrameRateMonitor}.
   */
  FrameRateMonitor.fromScene = function (scene) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(scene)) {
      throw new DeveloperError("scene is required.");
    }
    //>>includeEnd('debug');

    if (
      !defined(scene._frameRateMonitor) ||
      scene._frameRateMonitor.isDestroyed()
    ) {
      scene._frameRateMonitor = new FrameRateMonitor({
        scene: scene,
      });
    }

    return scene._frameRateMonitor;
  };

  Object.defineProperties(FrameRateMonitor.prototype, {
    /**
     * Gets the {@link Scene} instance for which to monitor performance.
     * @memberof FrameRateMonitor.prototype
     * @type {Scene}
     */
    scene: {
      get: function () {
        return this._scene;
      },
    },

    /**
     * Gets the event that is raised when a low frame rate is detected.  The function will be passed
     * the {@link Scene} instance as its first parameter and the average number of frames per second
     * over the sampling window as its second parameter.
     * @memberof FrameRateMonitor.prototype
     * @type {Event}
     */
    lowFrameRate: {
      get: function () {
        return this._lowFrameRate;
      },
    },

    /**
     * Gets the event that is raised when the frame rate returns to a normal level after having been low.
     * The function will be passed the {@link Scene} instance as its first parameter and the average
     * number of frames per second over the sampling window as its second parameter.
     * @memberof FrameRateMonitor.prototype
     * @type {Event}
     */
    nominalFrameRate: {
      get: function () {
        return this._nominalFrameRate;
      },
    },

    /**
     * Gets the most recently computed average frames-per-second over the last <code>samplingWindow</code>.
     * This property may be undefined if the frame rate has not been computed.
     * @memberof FrameRateMonitor.prototype
     * @type {Number}
     */
    lastFramesPerSecond: {
      get: function () {
        return this._lastFramesPerSecond;
      },
    },
  });

  /**
   * Pauses monitoring of the frame rate.  To resume monitoring, {@link FrameRateMonitor#unpause}
   * must be called once for each time this function is called.
   * @memberof FrameRateMonitor
   */
  FrameRateMonitor.prototype.pause = function () {
    ++this._pauseCount;
    if (this._pauseCount === 1) {
      this._frameTimes.length = 0;
      this._lastFramesPerSecond = undefined;
    }
  };

  /**
   * Resumes monitoring of the frame rate.  If {@link FrameRateMonitor#pause} was called
   * multiple times, this function must be called the same number of times in order to
   * actually resume monitoring.
   * @memberof FrameRateMonitor
   */
  FrameRateMonitor.prototype.unpause = function () {
    --this._pauseCount;
    if (this._pauseCount <= 0) {
      this._pauseCount = 0;
      this._needsQuietPeriod = true;
    }
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @memberof FrameRateMonitor
   *
   * @returns {Boolean} True if this object was destroyed; otherwise, false.
   *
   * @see FrameRateMonitor#destroy
   */
  FrameRateMonitor.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Unsubscribes this instance from all events it is listening to.
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @memberof FrameRateMonitor
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @see FrameRateMonitor#isDestroyed
   */
  FrameRateMonitor.prototype.destroy = function () {
    this._preUpdateRemoveListener();

    if (defined(this._visibilityChangeRemoveListener)) {
      this._visibilityChangeRemoveListener();
    }

    return destroyObject(this);
  };

  function update(monitor, time) {
    if (monitor._pauseCount > 0) {
      return;
    }

    const timeStamp = getTimestamp$1();

    if (monitor._needsQuietPeriod) {
      monitor._needsQuietPeriod = false;
      monitor._frameTimes.length = 0;
      monitor._quietPeriodEndTime =
        timeStamp + monitor.quietPeriod / TimeConstants$1.SECONDS_PER_MILLISECOND;
      monitor._warmupPeriodEndTime =
        monitor._quietPeriodEndTime +
        (monitor.warmupPeriod + monitor.samplingWindow) /
          TimeConstants$1.SECONDS_PER_MILLISECOND;
    } else if (timeStamp >= monitor._quietPeriodEndTime) {
      monitor._frameTimes.push(timeStamp);

      const beginningOfWindow =
        timeStamp -
        monitor.samplingWindow / TimeConstants$1.SECONDS_PER_MILLISECOND;

      if (
        monitor._frameTimes.length >= 2 &&
        monitor._frameTimes[0] <= beginningOfWindow
      ) {
        while (
          monitor._frameTimes.length >= 2 &&
          monitor._frameTimes[1] < beginningOfWindow
        ) {
          monitor._frameTimes.shift();
        }

        const averageTimeBetweenFrames =
          (timeStamp - monitor._frameTimes[0]) / (monitor._frameTimes.length - 1);

        monitor._lastFramesPerSecond = 1000.0 / averageTimeBetweenFrames;

        const maximumFrameTime =
          1000.0 /
          (timeStamp > monitor._warmupPeriodEndTime
            ? monitor.minimumFrameRateAfterWarmup
            : monitor.minimumFrameRateDuringWarmup);
        if (averageTimeBetweenFrames > maximumFrameTime) {
          if (!monitor._frameRateIsLow) {
            monitor._frameRateIsLow = true;
            monitor._needsQuietPeriod = true;
            monitor.lowFrameRate.raiseEvent(
              monitor.scene,
              monitor._lastFramesPerSecond
            );
          }
        } else if (monitor._frameRateIsLow) {
          monitor._frameRateIsLow = false;
          monitor._needsQuietPeriod = true;
          monitor.nominalFrameRate.raiseEvent(
            monitor.scene,
            monitor._lastFramesPerSecond
          );
        }
      }
    }
  }

  function visibilityChanged(monitor) {
    if (document[monitor._hiddenPropertyName]) {
      monitor.pause();
    } else {
      monitor.unpause();
    }
  }

  /**
   * State information about the current frame.  An instance of this class
   * is provided to update functions.
   *
   * @param {Context} context The rendering context
   * @param {CreditDisplay} creditDisplay Handles adding and removing credits from an HTML element
   * @param {JobScheduler} jobScheduler The job scheduler
   *
   * @alias FrameState
   * @constructor
   *
   * @private
   */
  function FrameState(context, creditDisplay, jobScheduler) {
    /**
     * The rendering context.
     *
     * @type {Context}
     */
    this.context = context;

    /**
     * An array of rendering commands.
     *
     * @type {DrawCommand[]}
     */
    this.commandList = [];

    /**
     * An array of shadow maps.
     * @type {ShadowMap[]}
     */
    this.shadowMaps = [];

    /**
     * The BRDF look up texture generator used for image-based lighting for PBR models
     * @type {BrdfLutGenerator}
     */
    this.brdfLutGenerator = undefined;

    /**
     * The environment map used for image-based lighting for PBR models
     * @type {CubeMap}
     */
    this.environmentMap = undefined;

    /**
     * The spherical harmonic coefficients used for image-based lighting for PBR models.
     * @type {Cartesian3[]}
     */
    this.sphericalHarmonicCoefficients = undefined;

    /**
     * The specular environment atlas used for image-based lighting for PBR models.
     * @type {Texture}
     */
    this.specularEnvironmentMaps = undefined;

    /**
     * The maximum level-of-detail of the specular environment atlas used for image-based lighting for PBR models.
     * @type {Number}
     */
    this.specularEnvironmentMapsMaximumLOD = undefined;

    /**
     * The current mode of the scene.
     *
     * @type {SceneMode}
     * @default {@link SceneMode.SCENE3D}
     */
    this.mode = SceneMode$1.SCENE3D;

    /**
     * The current morph transition time between 2D/Columbus View and 3D,
     * with 0.0 being 2D or Columbus View and 1.0 being 3D.
     *
     * @type {Number}
     */
    this.morphTime = SceneMode$1.getMorphTime(SceneMode$1.SCENE3D);

    /**
     * The current frame number.
     *
     * @type {Number}
     * @default 0
     */
    this.frameNumber = 0;

    /**
     * <code>true</code> if a new frame has been issued and the frame number has been updated.
     *
     * @type {Boolean}
     * @default false
     */
    this.newFrame = false;

    /**
     * The scene's current time.
     *
     * @type {JulianDate}
     * @default undefined
     */
    this.time = undefined;

    /**
     * The job scheduler.
     *
     * @type {JobScheduler}
     */
    this.jobScheduler = jobScheduler;

    /**
     * The map projection to use in 2D and Columbus View modes.
     *
     * @type {MapProjection}
     * @default undefined
     */
    this.mapProjection = undefined;

    /**
     * The current camera.
     *
     * @type {Camera}
     * @default undefined
     */
    this.camera = undefined;

    /**
     * Whether the camera is underground.
     *
     * @type {Boolean}
     * @default false
     */
    this.cameraUnderground = false;

    /**
     * The {@link GlobeTranslucencyState} object used by the scene.
     *
     * @type {GlobeTranslucencyState}
     * @default undefined
     */
    this.globeTranslucencyState = undefined;

    /**
     * The culling volume.
     *
     * @type {CullingVolume}
     * @default undefined
     */
    this.cullingVolume = undefined;

    /**
     * The current occluder.
     *
     * @type {Occluder}
     * @default undefined
     */
    this.occluder = undefined;

    /**
     * The maximum screen-space error used to drive level-of-detail refinement.  Higher
     * values will provide better performance but lower visual quality.
     *
     * @type {Number}
     * @default 2
     */
    this.maximumScreenSpaceError = undefined;

    /**
     * Ratio between a pixel and a density-independent pixel. Provides a standard unit of
     * measure for real pixel measurements appropriate to a particular device.
     *
     * @type {Number}
     * @default 1.0
     */
    this.pixelRatio = 1.0;

    /**
     * @typedef FrameState.Passes
     * @type {Object}
     * @property {Boolean} render <code>true</code> if the primitive should update for a render pass, <code>false</code> otherwise.
     * @property {Boolean} pick <code>true</code> if the primitive should update for a picking pass, <code>false</code> otherwise.
     * @property {Boolean} depth <code>true</code> if the primitive should update for a depth only pass, <code>false</code> otherwise.
     * @property {Boolean} postProcess <code>true</code> if the primitive should update for a per-feature post-process pass, <code>false</code> otherwise.
     * @property {Boolean} offscreen <code>true</code> if the primitive should update for an offscreen pass, <code>false</code> otherwise.
     */

    /**
     * @type {FrameState.Passes}
     */
    this.passes = {
      /**
       * @default false
       */
      render: false,
      /**
       * @default false
       */
      pick: false,
      /**
       * @default false
       */
      depth: false,
      /**
       * @default false
       */
      postProcess: false,
      /**
       * @default false
       */
      offscreen: false,
    };

    /**
     * The credit display.
     *
     * @type {CreditDisplay}
     */
    this.creditDisplay = creditDisplay;

    /**
     * An array of functions to be called at the end of the frame.  This array
     * will be cleared after each frame.
     * <p>
     * This allows queueing up events in <code>update</code> functions and
     * firing them at a time when the subscribers are free to change the
     * scene state, e.g., manipulate the camera, instead of firing events
     * directly in <code>update</code> functions.
     * </p>
     *
     * @type {FrameState.AfterRenderCallback[]}
     *
     * @example
     * frameState.afterRender.push(function() {
     *   // take some action, raise an event, etc.
     * });
     */
    this.afterRender = [];

    /**
     * Gets whether or not to optimize for 3D only.
     *
     * @type {Boolean}
     * @default false
     */
    this.scene3DOnly = false;

    /**
     * @typedef FrameState.Fog
     * @type {Object}
     * @property {Boolean} enabled <code>true</code> if fog is enabled, <code>false</code> otherwise.
     * @property {Number} density A positive number used to mix the color and fog color based on camera distance.
     * @property {Number} sse A scalar used to modify the screen space error of geometry partially in fog.
     * @property {Number} minimumBrightness The minimum brightness of terrain with fog applied.
     */

    /**
     * @type {FrameState.Fog}
     */

    this.fog = {
      /**
       * @default false
       */
      enabled: false,
      density: undefined,
      sse: undefined,
      minimumBrightness: undefined,
    };

    /**
     * A scalar used to exaggerate the terrain.
     * @type {Number}
     * @default 1.0
     */
    this.terrainExaggeration = 1.0;

    /**
     * The height relative to which terrain is exaggerated.
     * @type {Number}
     * @default 0.0
     */
    this.terrainExaggerationRelativeHeight = 0.0;

    /**
     * @typedef FrameState.ShadowState
     * @type {Object}
     * @property {Boolean} shadowsEnabled Whether there are any active shadow maps this frame.
     * @property {Boolean} lightShadowsEnabled Whether there are any active shadow maps that originate from light sources. Does not include shadow maps that are used for analytical purposes.
     * @property {ShadowMap[]} shadowMaps All shadow maps that are enabled this frame.
     * @property {ShadowMap[]} lightShadowMaps Shadow maps that originate from light sources. Does not include shadow maps that are used for analytical purposes. Only these shadow maps will be used to generate receive shadows shaders.
     * @property {Number} nearPlane The near plane of the scene's frustum commands. Used for fitting cascaded shadow maps.
     * @property {Number} farPlane The far plane of the scene's frustum commands. Used for fitting cascaded shadow maps.
     * @property {Number} closestObjectSize The size of the bounding volume that is closest to the camera. This is used to place more shadow detail near the object.
     * @property {Number} lastDirtyTime The time when a shadow map was last dirty
     * @property {Boolean} outOfView Whether the shadows maps are out of view this frame
     */

    /**
     * @type {FrameState.ShadowState}
     */

    this.shadowState = {
      /**
       * @default true
       */
      shadowsEnabled: true,
      shadowMaps: [],
      lightShadowMaps: [],
      /**
       * @default 1.0
       */
      nearPlane: 1.0,
      /**
       * @default 5000.0
       */
      farPlane: 5000.0,
      /**
       * @default 1000.0
       */
      closestObjectSize: 1000.0,
      /**
       * @default 0
       */
      lastDirtyTime: 0,
      /**
       * @default true
       */
      outOfView: true,
    };

    /**
     * The position of the splitter to use when rendering different things on either side of a splitter.
     * This value should be between 0.0 and 1.0 with 0 being the far left of the viewport and 1 being the far right of the viewport.
     * @type {Number}
     * @default 0.0
     */
    this.splitPosition = 0.0;

    /**
     * Distances to the near and far planes of the camera frustums
     * @type {Number[]}
     * @default []
     */
    this.frustumSplits = [];

    /**
     * The current scene background color
     *
     * @type {Color}
     */
    this.backgroundColor = undefined;

    /**
     * The light used to shade the scene.
     *
     * @type {Light}
     */
    this.light = undefined;

    /**
     * The distance from the camera at which to disable the depth test of billboards, labels and points
     * to, for example, prevent clipping against terrain. When set to zero, the depth test should always
     * be applied. When less than zero, the depth test should never be applied.
     * @type {Number}
     */
    this.minimumDisableDepthTestDistance = undefined;

    /**
     * When <code>false</code>, 3D Tiles will render normally. When <code>true</code>, classified 3D Tile geometry will render normally and
     * unclassified 3D Tile geometry will render with the color multiplied with {@link FrameState#invertClassificationColor}.
     * @type {Boolean}
     * @default false
     */
    this.invertClassification = false;

    /**
     * The highlight color of unclassified 3D Tile geometry when {@link FrameState#invertClassification} is <code>true</code>.
     * @type {Color}
     */
    this.invertClassificationColor = undefined;

    /**
     * Whether or not the scene uses a logarithmic depth buffer.
     *
     * @type {Boolean}
     * @default false
     */
    this.useLogDepth = false;

    /**
     * Additional state used to update 3D Tilesets.
     *
     * @type {Cesium3DTilePassState}
     */
    this.tilesetPassState = undefined;

    /**
     * The minimum terrain height out of all rendered terrain tiles. Used to improve culling for objects underneath the ellipsoid but above terrain.
     *
     * @type {Number}
     * @default 0.0
     */
    this.minimumTerrainHeight = 0.0;
  }

  /**
   * Defines a list of commands whose geometry are bound by near and far distances from the camera.
   * @alias FrustumCommands
   * @constructor
   *
   * @param {Number} [near=0.0] The lower bound or closest distance from the camera.
   * @param {Number} [far=0.0] The upper bound or farthest distance from the camera.
   *
   * @private
   */
  function FrustumCommands(near, far) {
    this.near = defaultValue(near, 0.0);
    this.far = defaultValue(far, 0.0);

    const numPasses = Pass$1.NUMBER_OF_PASSES;
    const commands = new Array(numPasses);
    const indices = new Array(numPasses);

    for (let i = 0; i < numPasses; ++i) {
      commands[i] = [];
      indices[i] = 0;
    }

    this.commands = commands;
    this.indices = indices;
  }

  /**
   * Describes the format in which to request GetFeatureInfo from a Web Map Service (WMS) server.
   *
   * @alias GetFeatureInfoFormat
   * @constructor
   *
   * @param {String} type The type of response to expect from a GetFeatureInfo request.  Valid
   *        values are 'json', 'xml', 'html', or 'text'.
   * @param {String} [format] The info format to request from the WMS server.  This is usually a
   *        MIME type such as 'application/json' or text/xml'.  If this parameter is not specified, the provider will request 'json'
   *        using 'application/json', 'xml' using 'text/xml', 'html' using 'text/html', and 'text' using 'text/plain'.
   * @param {Function} [callback] A function to invoke with the GetFeatureInfo response from the WMS server
   *        in order to produce an array of picked {@link ImageryLayerFeatureInfo} instances.  If this parameter is not specified,
   *        a default function for the type of response is used.
   */
  function GetFeatureInfoFormat(type, format, callback) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(type)) {
      throw new DeveloperError("type is required.");
    }
    //>>includeEnd('debug');

    this.type = type;

    if (!defined(format)) {
      if (type === "json") {
        format = "application/json";
      } else if (type === "xml") {
        format = "text/xml";
      } else if (type === "html") {
        format = "text/html";
      } else if (type === "text") {
        format = "text/plain";
      }
      //>>includeStart('debug', pragmas.debug);
      else {
        throw new DeveloperError(
          'format is required when type is not "json", "xml", "html", or "text".'
        );
      }
      //>>includeEnd('debug');
    }

    this.format = format;

    if (!defined(callback)) {
      if (type === "json") {
        callback = geoJsonToFeatureInfo;
      } else if (type === "xml") {
        callback = xmlToFeatureInfo;
      } else if (type === "html") {
        callback = textToFeatureInfo;
      } else if (type === "text") {
        callback = textToFeatureInfo;
      }
      //>>includeStart('debug', pragmas.debug);
      else {
        throw new DeveloperError(
          'callback is required when type is not "json", "xml", "html", or "text".'
        );
      }
      //>>includeEnd('debug');
    }

    this.callback = callback;
  }

  function geoJsonToFeatureInfo(json) {
    const result = [];

    const features = json.features;
    for (let i = 0; i < features.length; ++i) {
      const feature = features[i];

      const featureInfo = new ImageryLayerFeatureInfo();
      featureInfo.data = feature;
      featureInfo.properties = feature.properties;
      featureInfo.configureNameFromProperties(feature.properties);
      featureInfo.configureDescriptionFromProperties(feature.properties);

      // If this is a point feature, use the coordinates of the point.
      if (defined(feature.geometry) && feature.geometry.type === "Point") {
        const longitude = feature.geometry.coordinates[0];
        const latitude = feature.geometry.coordinates[1];
        featureInfo.position = Cartographic.fromDegrees(longitude, latitude);
      }

      result.push(featureInfo);
    }

    return result;
  }

  const mapInfoMxpNamespace = "http://www.mapinfo.com/mxp";
  const esriWmsNamespace = "http://www.esri.com/wms";
  const wfsNamespace = "http://www.opengis.net/wfs";
  const gmlNamespace = "http://www.opengis.net/gml";

  function xmlToFeatureInfo(xml) {
    const documentElement = xml.documentElement;
    if (
      documentElement.localName === "MultiFeatureCollection" &&
      documentElement.namespaceURI === mapInfoMxpNamespace
    ) {
      // This looks like a MapInfo MXP response
      return mapInfoXmlToFeatureInfo(xml);
    } else if (
      documentElement.localName === "FeatureInfoResponse" &&
      documentElement.namespaceURI === esriWmsNamespace
    ) {
      // This looks like an Esri WMS response
      return esriXmlToFeatureInfo(xml);
    } else if (
      documentElement.localName === "FeatureCollection" &&
      documentElement.namespaceURI === wfsNamespace
    ) {
      // This looks like a WFS/GML response.
      return gmlToFeatureInfo(xml);
    } else if (documentElement.localName === "ServiceExceptionReport") {
      // This looks like a WMS server error, so no features picked.
      throw new RuntimeError(
        new XMLSerializer().serializeToString(documentElement)
      );
    } else if (documentElement.localName === "msGMLOutput") {
      return msGmlToFeatureInfo(xml);
    } else {
      // Unknown response type, so just dump the XML itself into the description.
      return unknownXmlToFeatureInfo(xml);
    }
  }

  function mapInfoXmlToFeatureInfo(xml) {
    const result = [];

    const multiFeatureCollection = xml.documentElement;

    const features = multiFeatureCollection.getElementsByTagNameNS(
      mapInfoMxpNamespace,
      "Feature"
    );
    for (let featureIndex = 0; featureIndex < features.length; ++featureIndex) {
      const feature = features[featureIndex];

      const properties = {};

      const propertyElements = feature.getElementsByTagNameNS(
        mapInfoMxpNamespace,
        "Val"
      );
      for (
        let propertyIndex = 0;
        propertyIndex < propertyElements.length;
        ++propertyIndex
      ) {
        const propertyElement = propertyElements[propertyIndex];
        if (propertyElement.hasAttribute("ref")) {
          const name = propertyElement.getAttribute("ref");
          const value = propertyElement.textContent.trim();
          properties[name] = value;
        }
      }

      const featureInfo = new ImageryLayerFeatureInfo();
      featureInfo.data = feature;
      featureInfo.properties = properties;
      featureInfo.configureNameFromProperties(properties);
      featureInfo.configureDescriptionFromProperties(properties);
      result.push(featureInfo);
    }

    return result;
  }

  function esriXmlToFeatureInfo(xml) {
    const featureInfoResponse = xml.documentElement;
    const result = [];
    let properties;

    const features = featureInfoResponse.getElementsByTagNameNS("*", "FIELDS");
    if (features.length > 0) {
      // Standard esri format
      for (let featureIndex = 0; featureIndex < features.length; ++featureIndex) {
        const feature = features[featureIndex];

        properties = {};

        const propertyAttributes = feature.attributes;
        for (
          let attributeIndex = 0;
          attributeIndex < propertyAttributes.length;
          ++attributeIndex
        ) {
          const attribute = propertyAttributes[attributeIndex];
          properties[attribute.name] = attribute.value;
        }

        result.push(
          imageryLayerFeatureInfoFromDataAndProperties(feature, properties)
        );
      }
    } else {
      // Thredds format -- looks like esri, but instead of containing FIELDS, contains FeatureInfo element
      const featureInfoElements = featureInfoResponse.getElementsByTagNameNS(
        "*",
        "FeatureInfo"
      );
      for (
        let featureInfoElementIndex = 0;
        featureInfoElementIndex < featureInfoElements.length;
        ++featureInfoElementIndex
      ) {
        const featureInfoElement = featureInfoElements[featureInfoElementIndex];

        properties = {};

        // node.children is not supported in IE9-11, so use childNodes and check that child.nodeType is an element
        const featureInfoChildren = featureInfoElement.childNodes;
        for (
          let childIndex = 0;
          childIndex < featureInfoChildren.length;
          ++childIndex
        ) {
          const child = featureInfoChildren[childIndex];
          if (child.nodeType === Node.ELEMENT_NODE) {
            properties[child.localName] = child.textContent;
          }
        }

        result.push(
          imageryLayerFeatureInfoFromDataAndProperties(
            featureInfoElement,
            properties
          )
        );
      }
    }

    return result;
  }

  function gmlToFeatureInfo(xml) {
    const result = [];

    const featureCollection = xml.documentElement;

    const featureMembers = featureCollection.getElementsByTagNameNS(
      gmlNamespace,
      "featureMember"
    );
    for (
      let featureIndex = 0;
      featureIndex < featureMembers.length;
      ++featureIndex
    ) {
      const featureMember = featureMembers[featureIndex];

      const properties = {};
      getGmlPropertiesRecursively(featureMember, properties);
      result.push(
        imageryLayerFeatureInfoFromDataAndProperties(featureMember, properties)
      );
    }

    return result;
  }

  // msGmlToFeatureInfo is similar to gmlToFeatureInfo, but assumes different XML structure
  // eg. <msGMLOutput> <ABC_layer> <ABC_feature> <foo>bar</foo> ... </ABC_feature> </ABC_layer> </msGMLOutput>

  function msGmlToFeatureInfo(xml) {
    const result = [];

    // Find the first child. Except for IE, this would work:
    // const layer = xml.documentElement.children[0];
    let layer;
    const children = xml.documentElement.childNodes;
    for (let i = 0; i < children.length; i++) {
      if (children[i].nodeType === Node.ELEMENT_NODE) {
        layer = children[i];
        break;
      }
    }
    if (!defined(layer)) {
      throw new RuntimeError(
        "Unable to find first child of the feature info xml document"
      );
    }
    const featureMembers = layer.childNodes;
    for (
      let featureIndex = 0;
      featureIndex < featureMembers.length;
      ++featureIndex
    ) {
      const featureMember = featureMembers[featureIndex];
      if (featureMember.nodeType === Node.ELEMENT_NODE) {
        const properties = {};
        getGmlPropertiesRecursively(featureMember, properties);
        result.push(
          imageryLayerFeatureInfoFromDataAndProperties(featureMember, properties)
        );
      }
    }

    return result;
  }

  function getGmlPropertiesRecursively(gmlNode, properties) {
    let isSingleValue = true;

    for (let i = 0; i < gmlNode.childNodes.length; ++i) {
      const child = gmlNode.childNodes[i];

      if (child.nodeType === Node.ELEMENT_NODE) {
        isSingleValue = false;
      }

      if (
        child.localName === "Point" ||
        child.localName === "LineString" ||
        child.localName === "Polygon" ||
        child.localName === "boundedBy"
      ) {
        continue;
      }

      if (
        child.hasChildNodes() &&
        getGmlPropertiesRecursively(child, properties)
      ) {
        properties[child.localName] = child.textContent;
      }
    }

    return isSingleValue;
  }

  function imageryLayerFeatureInfoFromDataAndProperties(data, properties) {
    const featureInfo = new ImageryLayerFeatureInfo();
    featureInfo.data = data;
    featureInfo.properties = properties;
    featureInfo.configureNameFromProperties(properties);
    featureInfo.configureDescriptionFromProperties(properties);
    return featureInfo;
  }

  function unknownXmlToFeatureInfo(xml) {
    const xmlText = new XMLSerializer().serializeToString(xml);

    const element = document.createElement("div");
    const pre = document.createElement("pre");
    pre.textContent = xmlText;
    element.appendChild(pre);

    const featureInfo = new ImageryLayerFeatureInfo();
    featureInfo.data = xml;
    featureInfo.description = element.innerHTML;
    return [featureInfo];
  }

  const emptyBodyRegex = /<body>\s*<\/body>/im;
  const wmsServiceExceptionReportRegex = /<ServiceExceptionReport([\s\S]*)<\/ServiceExceptionReport>/im;
  const titleRegex = /<title>([\s\S]*)<\/title>/im;

  function textToFeatureInfo(text) {
    // If the text is HTML and it has an empty body tag, assume it means no features were found.
    if (emptyBodyRegex.test(text)) {
      return undefined;
    }

    // If this is a WMS exception report, treat it as "no features found" rather than showing
    // bogus feature info.
    if (wmsServiceExceptionReportRegex.test(text)) {
      return undefined;
    }

    // If the text has a <title> element, use it as the name.
    let name;
    const title = titleRegex.exec(text);
    if (title && title.length > 1) {
      name = title[1];
    }

    const featureInfo = new ImageryLayerFeatureInfo();
    featureInfo.name = name;
    featureInfo.description = text;
    featureInfo.data = text;
    return [featureInfo];
  }

  //This file is automatically rebuilt by the Cesium build process.
  var GlobeFS = "uniform vec4 u_initialColor;\n\
#if TEXTURE_UNITS > 0\n\
uniform sampler2D u_dayTextures[TEXTURE_UNITS];\n\
uniform vec4 u_dayTextureTranslationAndScale[TEXTURE_UNITS];\n\
uniform bool u_dayTextureUseWebMercatorT[TEXTURE_UNITS];\n\
#ifdef APPLY_ALPHA\n\
uniform float u_dayTextureAlpha[TEXTURE_UNITS];\n\
#endif\n\
#ifdef APPLY_DAY_NIGHT_ALPHA\n\
uniform float u_dayTextureNightAlpha[TEXTURE_UNITS];\n\
uniform float u_dayTextureDayAlpha[TEXTURE_UNITS];\n\
#endif\n\
#ifdef APPLY_SPLIT\n\
uniform float u_dayTextureSplit[TEXTURE_UNITS];\n\
#endif\n\
#ifdef APPLY_BRIGHTNESS\n\
uniform float u_dayTextureBrightness[TEXTURE_UNITS];\n\
#endif\n\
#ifdef APPLY_CONTRAST\n\
uniform float u_dayTextureContrast[TEXTURE_UNITS];\n\
#endif\n\
#ifdef APPLY_HUE\n\
uniform float u_dayTextureHue[TEXTURE_UNITS];\n\
#endif\n\
#ifdef APPLY_SATURATION\n\
uniform float u_dayTextureSaturation[TEXTURE_UNITS];\n\
#endif\n\
#ifdef APPLY_GAMMA\n\
uniform float u_dayTextureOneOverGamma[TEXTURE_UNITS];\n\
#endif\n\
#ifdef APPLY_IMAGERY_CUTOUT\n\
uniform vec4 u_dayTextureCutoutRectangles[TEXTURE_UNITS];\n\
#endif\n\
#ifdef APPLY_COLOR_TO_ALPHA\n\
uniform vec4 u_colorsToAlpha[TEXTURE_UNITS];\n\
#endif\n\
uniform vec4 u_dayTextureTexCoordsRectangle[TEXTURE_UNITS];\n\
#endif\n\
#ifdef SHOW_REFLECTIVE_OCEAN\n\
uniform sampler2D u_waterMask;\n\
uniform vec4 u_waterMaskTranslationAndScale;\n\
uniform float u_zoomedOutOceanSpecularIntensity;\n\
#endif\n\
#ifdef SHOW_OCEAN_WAVES\n\
uniform sampler2D u_oceanNormalMap;\n\
#endif\n\
#if defined(ENABLE_DAYNIGHT_SHADING) || defined(GROUND_ATMOSPHERE)\n\
uniform vec2 u_lightingFadeDistance;\n\
#endif\n\
#ifdef TILE_LIMIT_RECTANGLE\n\
uniform vec4 u_cartographicLimitRectangle;\n\
#endif\n\
#ifdef GROUND_ATMOSPHERE\n\
uniform vec2 u_nightFadeDistance;\n\
#endif\n\
#ifdef ENABLE_CLIPPING_PLANES\n\
uniform highp sampler2D u_clippingPlanes;\n\
uniform mat4 u_clippingPlanesMatrix;\n\
uniform vec4 u_clippingPlanesEdgeStyle;\n\
#endif\n\
#if defined(GROUND_ATMOSPHERE) || defined(FOG) && defined(DYNAMIC_ATMOSPHERE_LIGHTING) && (defined(ENABLE_VERTEX_LIGHTING) || defined(ENABLE_DAYNIGHT_SHADING))\n\
uniform float u_minimumBrightness;\n\
#endif\n\
#ifdef COLOR_CORRECT\n\
uniform vec3 u_hsbShift;\n\
#endif\n\
#ifdef HIGHLIGHT_FILL_TILE\n\
uniform vec4 u_fillHighlightColor;\n\
#endif\n\
#ifdef TRANSLUCENT\n\
uniform vec4 u_frontFaceAlphaByDistance;\n\
uniform vec4 u_backFaceAlphaByDistance;\n\
uniform vec4 u_translucencyRectangle;\n\
#endif\n\
#ifdef UNDERGROUND_COLOR\n\
uniform vec4 u_undergroundColor;\n\
uniform vec4 u_undergroundColorAlphaByDistance;\n\
#endif\n\
#ifdef ENABLE_VERTEX_LIGHTING\n\
uniform float u_lambertDiffuseMultiplier;\n\
#endif\n\
varying vec3 v_positionMC;\n\
varying vec3 v_positionEC;\n\
varying vec3 v_textureCoordinates;\n\
varying vec3 v_normalMC;\n\
varying vec3 v_normalEC;\n\
#ifdef APPLY_MATERIAL\n\
varying float v_height;\n\
varying float v_slope;\n\
varying float v_aspect;\n\
#endif\n\
#if defined(FOG) || defined(GROUND_ATMOSPHERE) || defined(UNDERGROUND_COLOR) || defined(TRANSLUCENT)\n\
varying float v_distance;\n\
#endif\n\
#if defined(GROUND_ATMOSPHERE) || defined(FOG)\n\
varying vec3 v_atmosphereRayleighColor;\n\
varying vec3 v_atmosphereMieColor;\n\
varying float v_atmosphereOpacity;\n\
#endif\n\
#if defined(UNDERGROUND_COLOR) || defined(TRANSLUCENT)\n\
float interpolateByDistance(vec4 nearFarScalar, float distance)\n\
{\n\
float startDistance = nearFarScalar.x;\n\
float startValue = nearFarScalar.y;\n\
float endDistance = nearFarScalar.z;\n\
float endValue = nearFarScalar.w;\n\
float t = clamp((distance - startDistance) / (endDistance - startDistance), 0.0, 1.0);\n\
return mix(startValue, endValue, t);\n\
}\n\
#endif\n\
#if defined(UNDERGROUND_COLOR) || defined(TRANSLUCENT) || defined(APPLY_MATERIAL)\n\
vec4 alphaBlend(vec4 sourceColor, vec4 destinationColor)\n\
{\n\
return sourceColor * vec4(sourceColor.aaa, 1.0) + destinationColor * (1.0 - sourceColor.a);\n\
}\n\
#endif\n\
#ifdef TRANSLUCENT\n\
bool inTranslucencyRectangle()\n\
{\n\
return\n\
v_textureCoordinates.x > u_translucencyRectangle.x &&\n\
v_textureCoordinates.x < u_translucencyRectangle.z &&\n\
v_textureCoordinates.y > u_translucencyRectangle.y &&\n\
v_textureCoordinates.y < u_translucencyRectangle.w;\n\
}\n\
#endif\n\
vec4 sampleAndBlend(\n\
vec4 previousColor,\n\
sampler2D textureToSample,\n\
vec2 tileTextureCoordinates,\n\
vec4 textureCoordinateRectangle,\n\
vec4 textureCoordinateTranslationAndScale,\n\
float textureAlpha,\n\
float textureNightAlpha,\n\
float textureDayAlpha,\n\
float textureBrightness,\n\
float textureContrast,\n\
float textureHue,\n\
float textureSaturation,\n\
float textureOneOverGamma,\n\
float split,\n\
vec4 colorToAlpha,\n\
float nightBlend)\n\
{\n\
vec2 alphaMultiplier = step(textureCoordinateRectangle.st, tileTextureCoordinates);\n\
textureAlpha = textureAlpha * alphaMultiplier.x * alphaMultiplier.y;\n\
alphaMultiplier = step(vec2(0.0), textureCoordinateRectangle.pq - tileTextureCoordinates);\n\
textureAlpha = textureAlpha * alphaMultiplier.x * alphaMultiplier.y;\n\
#if defined(APPLY_DAY_NIGHT_ALPHA) && defined(ENABLE_DAYNIGHT_SHADING)\n\
textureAlpha *= mix(textureDayAlpha, textureNightAlpha, nightBlend);\n\
#endif\n\
vec2 translation = textureCoordinateTranslationAndScale.xy;\n\
vec2 scale = textureCoordinateTranslationAndScale.zw;\n\
vec2 textureCoordinates = tileTextureCoordinates * scale + translation;\n\
vec4 value = texture2D(textureToSample, textureCoordinates);\n\
vec3 color = value.rgb;\n\
float alpha = value.a;\n\
#ifdef APPLY_COLOR_TO_ALPHA\n\
vec3 colorDiff = abs(color.rgb - colorToAlpha.rgb);\n\
colorDiff.r = max(max(colorDiff.r, colorDiff.g), colorDiff.b);\n\
alpha = czm_branchFreeTernary(colorDiff.r < colorToAlpha.a, 0.0, alpha);\n\
#endif\n\
#if !defined(APPLY_GAMMA)\n\
vec4 tempColor = czm_gammaCorrect(vec4(color, alpha));\n\
color = tempColor.rgb;\n\
alpha = tempColor.a;\n\
#else\n\
color = pow(color, vec3(textureOneOverGamma));\n\
#endif\n\
#ifdef APPLY_SPLIT\n\
float splitPosition = czm_splitPosition;\n\
if (split < 0.0 && gl_FragCoord.x > splitPosition) {\n\
alpha = 0.0;\n\
}\n\
else if (split > 0.0 && gl_FragCoord.x < splitPosition) {\n\
alpha = 0.0;\n\
}\n\
#endif\n\
#ifdef APPLY_BRIGHTNESS\n\
color = mix(vec3(0.0), color, textureBrightness);\n\
#endif\n\
#ifdef APPLY_CONTRAST\n\
color = mix(vec3(0.5), color, textureContrast);\n\
#endif\n\
#ifdef APPLY_HUE\n\
color = czm_hue(color, textureHue);\n\
#endif\n\
#ifdef APPLY_SATURATION\n\
color = czm_saturation(color, textureSaturation);\n\
#endif\n\
float sourceAlpha = alpha * textureAlpha;\n\
float outAlpha = mix(previousColor.a, 1.0, sourceAlpha);\n\
outAlpha += sign(outAlpha) - 1.0;\n\
vec3 outColor = mix(previousColor.rgb * previousColor.a, color, sourceAlpha) / outAlpha;\n\
return vec4(outColor, max(outAlpha, 0.0));\n\
}\n\
vec3 colorCorrect(vec3 rgb) {\n\
#ifdef COLOR_CORRECT\n\
vec3 hsb = czm_RGBToHSB(rgb);\n\
hsb.x += u_hsbShift.x;\n\
hsb.y = clamp(hsb.y + u_hsbShift.y, 0.0, 1.0);\n\
hsb.z = hsb.z > czm_epsilon7 ? hsb.z + u_hsbShift.z : 0.0;\n\
rgb = czm_HSBToRGB(hsb);\n\
#endif\n\
return rgb;\n\
}\n\
vec4 computeDayColor(vec4 initialColor, vec3 textureCoordinates, float nightBlend);\n\
vec4 computeWaterColor(vec3 positionEyeCoordinates, vec2 textureCoordinates, mat3 enuToEye, vec4 imageryColor, float specularMapValue, float fade);\n\
const float fExposure = 2.0;\n\
vec3 computeEllipsoidPosition()\n\
{\n\
float mpp = czm_metersPerPixel(vec4(0.0, 0.0, -czm_currentFrustum.x, 1.0), 1.0);\n\
vec2 xy = gl_FragCoord.xy / czm_viewport.zw * 2.0 - vec2(1.0);\n\
xy *= czm_viewport.zw * mpp * 0.5;\n\
vec3 direction = normalize(vec3(xy, -czm_currentFrustum.x));\n\
czm_ray ray = czm_ray(vec3(0.0), direction);\n\
vec3 ellipsoid_center = czm_view[3].xyz;\n\
czm_raySegment intersection = czm_rayEllipsoidIntersectionInterval(ray, ellipsoid_center, czm_ellipsoidInverseRadii);\n\
vec3 ellipsoidPosition = czm_pointAlongRay(ray, intersection.start);\n\
return (czm_inverseView * vec4(ellipsoidPosition, 1.0)).xyz;\n\
}\n\
void main()\n\
{\n\
#ifdef TILE_LIMIT_RECTANGLE\n\
if (v_textureCoordinates.x < u_cartographicLimitRectangle.x || u_cartographicLimitRectangle.z < v_textureCoordinates.x ||\n\
v_textureCoordinates.y < u_cartographicLimitRectangle.y || u_cartographicLimitRectangle.w < v_textureCoordinates.y)\n\
{\n\
discard;\n\
}\n\
#endif\n\
#ifdef ENABLE_CLIPPING_PLANES\n\
float clipDistance = clip(gl_FragCoord, u_clippingPlanes, u_clippingPlanesMatrix);\n\
#endif\n\
#if defined(SHOW_REFLECTIVE_OCEAN) || defined(ENABLE_DAYNIGHT_SHADING) || defined(HDR)\n\
vec3 normalMC = czm_geodeticSurfaceNormal(v_positionMC, vec3(0.0), vec3(1.0));\n\
vec3 normalEC = czm_normal3D * normalMC;\n\
#endif\n\
#if defined(APPLY_DAY_NIGHT_ALPHA) && defined(ENABLE_DAYNIGHT_SHADING)\n\
float nightBlend = 1.0 - clamp(czm_getLambertDiffuse(czm_lightDirectionEC, normalEC) * 5.0, 0.0, 1.0);\n\
#else\n\
float nightBlend = 0.0;\n\
#endif\n\
vec4 color = computeDayColor(u_initialColor, clamp(v_textureCoordinates, 0.0, 1.0), nightBlend);\n\
#ifdef SHOW_TILE_BOUNDARIES\n\
if (v_textureCoordinates.x < (1.0/256.0) || v_textureCoordinates.x > (255.0/256.0) ||\n\
v_textureCoordinates.y < (1.0/256.0) || v_textureCoordinates.y > (255.0/256.0))\n\
{\n\
color = vec4(1.0, 0.0, 0.0, 1.0);\n\
}\n\
#endif\n\
#if defined(ENABLE_DAYNIGHT_SHADING) || defined(GROUND_ATMOSPHERE)\n\
float cameraDist;\n\
if (czm_sceneMode == czm_sceneMode2D)\n\
{\n\
cameraDist = max(czm_frustumPlanes.x - czm_frustumPlanes.y, czm_frustumPlanes.w - czm_frustumPlanes.z) * 0.5;\n\
}\n\
else if (czm_sceneMode == czm_sceneModeColumbusView)\n\
{\n\
cameraDist = -czm_view[3].z;\n\
}\n\
else\n\
{\n\
cameraDist = length(czm_view[3]);\n\
}\n\
float fadeOutDist = u_lightingFadeDistance.x;\n\
float fadeInDist = u_lightingFadeDistance.y;\n\
if (czm_sceneMode != czm_sceneMode3D) {\n\
vec3 radii = czm_ellipsoidRadii;\n\
float maxRadii = max(radii.x, max(radii.y, radii.z));\n\
fadeOutDist -= maxRadii;\n\
fadeInDist -= maxRadii;\n\
}\n\
float fade = clamp((cameraDist - fadeOutDist) / (fadeInDist - fadeOutDist), 0.0, 1.0);\n\
#else\n\
float fade = 0.0;\n\
#endif\n\
#ifdef SHOW_REFLECTIVE_OCEAN\n\
vec2 waterMaskTranslation = u_waterMaskTranslationAndScale.xy;\n\
vec2 waterMaskScale = u_waterMaskTranslationAndScale.zw;\n\
vec2 waterMaskTextureCoordinates = v_textureCoordinates.xy * waterMaskScale + waterMaskTranslation;\n\
waterMaskTextureCoordinates.y = 1.0 - waterMaskTextureCoordinates.y;\n\
float mask = texture2D(u_waterMask, waterMaskTextureCoordinates).r;\n\
if (mask > 0.0)\n\
{\n\
mat3 enuToEye = czm_eastNorthUpToEyeCoordinates(v_positionMC, normalEC);\n\
vec2 ellipsoidTextureCoordinates = czm_ellipsoidWgs84TextureCoordinates(normalMC);\n\
vec2 ellipsoidFlippedTextureCoordinates = czm_ellipsoidWgs84TextureCoordinates(normalMC.zyx);\n\
vec2 textureCoordinates = mix(ellipsoidTextureCoordinates, ellipsoidFlippedTextureCoordinates, czm_morphTime * smoothstep(0.9, 0.95, normalMC.z));\n\
color = computeWaterColor(v_positionEC, textureCoordinates, enuToEye, color, mask, fade);\n\
}\n\
#endif\n\
#ifdef APPLY_MATERIAL\n\
czm_materialInput materialInput;\n\
materialInput.st = v_textureCoordinates.st;\n\
materialInput.normalEC = normalize(v_normalEC);\n\
materialInput.positionToEyeEC = -v_positionEC;\n\
materialInput.tangentToEyeMatrix = czm_eastNorthUpToEyeCoordinates(v_positionMC, normalize(v_normalEC));\n\
materialInput.slope = v_slope;\n\
materialInput.height = v_height;\n\
materialInput.aspect = v_aspect;\n\
czm_material material = czm_getMaterial(materialInput);\n\
vec4 materialColor = vec4(material.diffuse, material.alpha);\n\
color = alphaBlend(materialColor, color);\n\
#endif\n\
#ifdef ENABLE_VERTEX_LIGHTING\n\
float diffuseIntensity = clamp(czm_getLambertDiffuse(czm_lightDirectionEC, normalize(v_normalEC)) * u_lambertDiffuseMultiplier + 0.3, 0.0, 1.0);\n\
vec4 finalColor = vec4(color.rgb * czm_lightColor * diffuseIntensity, color.a);\n\
#elif defined(ENABLE_DAYNIGHT_SHADING)\n\
float diffuseIntensity = clamp(czm_getLambertDiffuse(czm_lightDirectionEC, normalEC) * 5.0 + 0.3, 0.0, 1.0);\n\
diffuseIntensity = mix(1.0, diffuseIntensity, fade);\n\
vec4 finalColor = vec4(color.rgb * czm_lightColor * diffuseIntensity, color.a);\n\
#else\n\
vec4 finalColor = color;\n\
#endif\n\
#ifdef ENABLE_CLIPPING_PLANES\n\
vec4 clippingPlanesEdgeColor = vec4(1.0);\n\
clippingPlanesEdgeColor.rgb = u_clippingPlanesEdgeStyle.rgb;\n\
float clippingPlanesEdgeWidth = u_clippingPlanesEdgeStyle.a;\n\
if (clipDistance < clippingPlanesEdgeWidth)\n\
{\n\
finalColor = clippingPlanesEdgeColor;\n\
}\n\
#endif\n\
#ifdef HIGHLIGHT_FILL_TILE\n\
finalColor = vec4(mix(finalColor.rgb, u_fillHighlightColor.rgb, u_fillHighlightColor.a), finalColor.a);\n\
#endif\n\
#if defined(DYNAMIC_ATMOSPHERE_LIGHTING_FROM_SUN)\n\
vec3 atmosphereLightDirection = czm_sunDirectionWC;\n\
#else\n\
vec3 atmosphereLightDirection = czm_lightDirectionWC;\n\
#endif\n\
#if defined(GROUND_ATMOSPHERE) || defined(FOG)\n\
if (!czm_backFacing())\n\
{\n\
bool dynamicLighting = false;\n\
#if defined(DYNAMIC_ATMOSPHERE_LIGHTING) && (defined(ENABLE_DAYNIGHT_SHADING) || defined(ENABLE_VERTEX_LIGHTING))\n\
dynamicLighting = true;\n\
#endif\n\
vec3 rayleighColor;\n\
vec3 mieColor;\n\
float opacity;\n\
vec3 positionWC;\n\
vec3 lightDirection;\n\
#ifdef PER_FRAGMENT_GROUND_ATMOSPHERE\n\
positionWC = computeEllipsoidPosition();\n\
lightDirection = czm_branchFreeTernary(dynamicLighting, atmosphereLightDirection, normalize(positionWC));\n\
computeAtmosphereScattering(\n\
positionWC,\n\
lightDirection,\n\
rayleighColor,\n\
mieColor,\n\
opacity\n\
);\n\
#else\n\
positionWC = v_positionMC;\n\
lightDirection = czm_branchFreeTernary(dynamicLighting, atmosphereLightDirection, normalize(positionWC));\n\
rayleighColor = v_atmosphereRayleighColor;\n\
mieColor = v_atmosphereMieColor;\n\
opacity = v_atmosphereOpacity;\n\
#endif\n\
rayleighColor = colorCorrect(rayleighColor);\n\
mieColor = colorCorrect(mieColor);\n\
vec4 groundAtmosphereColor = computeAtmosphereColor(positionWC, lightDirection, rayleighColor, mieColor, opacity);\n\
#ifdef FOG\n\
vec3 fogColor = groundAtmosphereColor.rgb;\n\
#if defined(DYNAMIC_ATMOSPHERE_LIGHTING) && (defined(ENABLE_VERTEX_LIGHTING) || defined(ENABLE_DAYNIGHT_SHADING))\n\
float darken = clamp(dot(normalize(czm_viewerPositionWC), atmosphereLightDirection), u_minimumBrightness, 1.0);\n\
fogColor *= darken;\n\
#endif\n\
#ifndef HDR\n\
fogColor.rgb = czm_acesTonemapping(fogColor.rgb);\n\
fogColor.rgb = czm_inverseGamma(fogColor.rgb);\n\
#endif\n\
const float modifier = 0.15;\n\
finalColor = vec4(czm_fog(v_distance, finalColor.rgb, fogColor.rgb, modifier), finalColor.a);\n\
#else\n\
const float transmittanceModifier = 0.5;\n\
float transmittance = transmittanceModifier + clamp(1.0 - groundAtmosphereColor.a, 0.0, 1.0);\n\
vec3 finalAtmosphereColor = finalColor.rgb + groundAtmosphereColor.rgb * transmittance;\n\
#if defined(DYNAMIC_ATMOSPHERE_LIGHTING) && (defined(ENABLE_VERTEX_LIGHTING) || defined(ENABLE_DAYNIGHT_SHADING))\n\
float fadeInDist = u_nightFadeDistance.x;\n\
float fadeOutDist = u_nightFadeDistance.y;\n\
float sunlitAtmosphereIntensity = clamp((cameraDist - fadeOutDist) / (fadeInDist - fadeOutDist), 0.05, 1.0);\n\
float darken = clamp(dot(normalize(positionWC), atmosphereLightDirection), 0.0, 1.0);\n\
vec3 darkenendGroundAtmosphereColor = mix(groundAtmosphereColor.rgb, finalAtmosphereColor.rgb, darken);\n\
finalAtmosphereColor = mix(darkenendGroundAtmosphereColor, finalAtmosphereColor, sunlitAtmosphereIntensity);\n\
#endif\n\
#ifndef HDR\n\
finalAtmosphereColor.rgb = vec3(1.0) - exp(-fExposure * finalAtmosphereColor.rgb);\n\
#else\n\
finalAtmosphereColor.rgb = czm_saturation(finalAtmosphereColor.rgb, 1.6);\n\
#endif\n\
finalColor.rgb = mix(finalColor.rgb, finalAtmosphereColor.rgb, fade);\n\
#endif\n\
}\n\
#endif\n\
#ifdef UNDERGROUND_COLOR\n\
if (czm_backFacing())\n\
{\n\
float distanceFromEllipsoid = max(czm_eyeHeight, 0.0);\n\
float distance = max(v_distance - distanceFromEllipsoid, 0.0);\n\
float blendAmount = interpolateByDistance(u_undergroundColorAlphaByDistance, distance);\n\
vec4 undergroundColor = vec4(u_undergroundColor.rgb, u_undergroundColor.a * blendAmount);\n\
finalColor = alphaBlend(undergroundColor, finalColor);\n\
}\n\
#endif\n\
#ifdef TRANSLUCENT\n\
if (inTranslucencyRectangle())\n\
{\n\
vec4 alphaByDistance = gl_FrontFacing ? u_frontFaceAlphaByDistance : u_backFaceAlphaByDistance;\n\
finalColor.a *= interpolateByDistance(alphaByDistance, v_distance);\n\
}\n\
#endif\n\
gl_FragColor =  finalColor;\n\
}\n\
#ifdef SHOW_REFLECTIVE_OCEAN\n\
float waveFade(float edge0, float edge1, float x)\n\
{\n\
float y = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0);\n\
return pow(1.0 - y, 5.0);\n\
}\n\
float linearFade(float edge0, float edge1, float x)\n\
{\n\
return clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0);\n\
}\n\
const float oceanFrequencyLowAltitude = 825000.0;\n\
const float oceanAnimationSpeedLowAltitude = 0.004;\n\
const float oceanOneOverAmplitudeLowAltitude = 1.0 / 2.0;\n\
const float oceanSpecularIntensity = 0.5;\n\
const float oceanFrequencyHighAltitude = 125000.0;\n\
const float oceanAnimationSpeedHighAltitude = 0.008;\n\
const float oceanOneOverAmplitudeHighAltitude = 1.0 / 2.0;\n\
vec4 computeWaterColor(vec3 positionEyeCoordinates, vec2 textureCoordinates, mat3 enuToEye, vec4 imageryColor, float maskValue, float fade)\n\
{\n\
vec3 positionToEyeEC = -positionEyeCoordinates;\n\
float positionToEyeECLength = length(positionToEyeEC);\n\
vec3 normalizedPositionToEyeEC = normalize(normalize(positionToEyeEC));\n\
float waveIntensity = waveFade(70000.0, 1000000.0, positionToEyeECLength);\n\
#ifdef SHOW_OCEAN_WAVES\n\
float time = czm_frameNumber * oceanAnimationSpeedHighAltitude;\n\
vec4 noise = czm_getWaterNoise(u_oceanNormalMap, textureCoordinates * oceanFrequencyHighAltitude, time, 0.0);\n\
vec3 normalTangentSpaceHighAltitude = vec3(noise.xy, noise.z * oceanOneOverAmplitudeHighAltitude);\n\
time = czm_frameNumber * oceanAnimationSpeedLowAltitude;\n\
noise = czm_getWaterNoise(u_oceanNormalMap, textureCoordinates * oceanFrequencyLowAltitude, time, 0.0);\n\
vec3 normalTangentSpaceLowAltitude = vec3(noise.xy, noise.z * oceanOneOverAmplitudeLowAltitude);\n\
float highAltitudeFade = linearFade(0.0, 60000.0, positionToEyeECLength);\n\
float lowAltitudeFade = 1.0 - linearFade(20000.0, 60000.0, positionToEyeECLength);\n\
vec3 normalTangentSpace =\n\
(highAltitudeFade * normalTangentSpaceHighAltitude) +\n\
(lowAltitudeFade * normalTangentSpaceLowAltitude);\n\
normalTangentSpace = normalize(normalTangentSpace);\n\
normalTangentSpace.xy *= waveIntensity;\n\
normalTangentSpace = normalize(normalTangentSpace);\n\
#else\n\
vec3 normalTangentSpace = vec3(0.0, 0.0, 1.0);\n\
#endif\n\
vec3 normalEC = enuToEye * normalTangentSpace;\n\
const vec3 waveHighlightColor = vec3(0.3, 0.45, 0.6);\n\
float diffuseIntensity = czm_getLambertDiffuse(czm_lightDirectionEC, normalEC) * maskValue;\n\
vec3 diffuseHighlight = waveHighlightColor * diffuseIntensity * (1.0 - fade);\n\
#ifdef SHOW_OCEAN_WAVES\n\
float tsPerturbationRatio = normalTangentSpace.z;\n\
vec3 nonDiffuseHighlight = mix(waveHighlightColor * 5.0 * (1.0 - tsPerturbationRatio), vec3(0.0), diffuseIntensity);\n\
#else\n\
vec3 nonDiffuseHighlight = vec3(0.0);\n\
#endif\n\
float specularIntensity = czm_getSpecular(czm_lightDirectionEC, normalizedPositionToEyeEC, normalEC, 10.0);\n\
float surfaceReflectance = mix(0.0, mix(u_zoomedOutOceanSpecularIntensity, oceanSpecularIntensity, waveIntensity), maskValue);\n\
float specular = specularIntensity * surfaceReflectance;\n\
#ifdef HDR\n\
specular *= 1.4;\n\
float e = 0.2;\n\
float d = 3.3;\n\
float c = 1.7;\n\
vec3 color = imageryColor.rgb + (c * (vec3(e) + imageryColor.rgb * d) * (diffuseHighlight + nonDiffuseHighlight + specular));\n\
#else\n\
vec3 color = imageryColor.rgb + diffuseHighlight + nonDiffuseHighlight + specular;\n\
#endif\n\
return vec4(color, imageryColor.a);\n\
}\n\
#endif // #ifdef SHOW_REFLECTIVE_OCEAN\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var GlobeVS = "#ifdef QUANTIZATION_BITS12\n\
attribute vec4 compressed0;\n\
attribute float compressed1;\n\
#else\n\
attribute vec4 position3DAndHeight;\n\
attribute vec4 textureCoordAndEncodedNormals;\n\
#endif\n\
#ifdef GEODETIC_SURFACE_NORMALS\n\
attribute vec3 geodeticSurfaceNormal;\n\
#endif\n\
#ifdef EXAGGERATION\n\
uniform vec2 u_terrainExaggerationAndRelativeHeight;\n\
#endif\n\
uniform vec3 u_center3D;\n\
uniform mat4 u_modifiedModelView;\n\
uniform mat4 u_modifiedModelViewProjection;\n\
uniform vec4 u_tileRectangle;\n\
uniform vec2 u_southAndNorthLatitude;\n\
uniform vec2 u_southMercatorYAndOneOverHeight;\n\
varying vec3 v_positionMC;\n\
varying vec3 v_positionEC;\n\
varying vec3 v_textureCoordinates;\n\
varying vec3 v_normalMC;\n\
varying vec3 v_normalEC;\n\
#ifdef APPLY_MATERIAL\n\
varying float v_slope;\n\
varying float v_aspect;\n\
varying float v_height;\n\
#endif\n\
#if defined(FOG) || defined(GROUND_ATMOSPHERE) || defined(UNDERGROUND_COLOR) || defined(TRANSLUCENT)\n\
varying float v_distance;\n\
#endif\n\
#if defined(FOG) || defined(GROUND_ATMOSPHERE)\n\
varying vec3 v_atmosphereRayleighColor;\n\
varying vec3 v_atmosphereMieColor;\n\
varying float v_atmosphereOpacity;\n\
#endif\n\
vec4 getPosition(vec3 position, float height, vec2 textureCoordinates);\n\
float get2DYPositionFraction(vec2 textureCoordinates);\n\
vec4 getPosition3DMode(vec3 position, float height, vec2 textureCoordinates)\n\
{\n\
return u_modifiedModelViewProjection * vec4(position, 1.0);\n\
}\n\
float get2DMercatorYPositionFraction(vec2 textureCoordinates)\n\
{\n\
const float maxTileWidth = 0.003068;\n\
float positionFraction = textureCoordinates.y;\n\
float southLatitude = u_southAndNorthLatitude.x;\n\
float northLatitude = u_southAndNorthLatitude.y;\n\
if (northLatitude - southLatitude > maxTileWidth)\n\
{\n\
float southMercatorY = u_southMercatorYAndOneOverHeight.x;\n\
float oneOverMercatorHeight = u_southMercatorYAndOneOverHeight.y;\n\
float currentLatitude = mix(southLatitude, northLatitude, textureCoordinates.y);\n\
currentLatitude = clamp(currentLatitude, -czm_webMercatorMaxLatitude, czm_webMercatorMaxLatitude);\n\
positionFraction = czm_latitudeToWebMercatorFraction(currentLatitude, southMercatorY, oneOverMercatorHeight);\n\
}\n\
return positionFraction;\n\
}\n\
float get2DGeographicYPositionFraction(vec2 textureCoordinates)\n\
{\n\
return textureCoordinates.y;\n\
}\n\
vec4 getPositionPlanarEarth(vec3 position, float height, vec2 textureCoordinates)\n\
{\n\
float yPositionFraction = get2DYPositionFraction(textureCoordinates);\n\
vec4 rtcPosition2D = vec4(height, mix(u_tileRectangle.st, u_tileRectangle.pq, vec2(textureCoordinates.x, yPositionFraction)), 1.0);\n\
return u_modifiedModelViewProjection * rtcPosition2D;\n\
}\n\
vec4 getPosition2DMode(vec3 position, float height, vec2 textureCoordinates)\n\
{\n\
return getPositionPlanarEarth(position, 0.0, textureCoordinates);\n\
}\n\
vec4 getPositionColumbusViewMode(vec3 position, float height, vec2 textureCoordinates)\n\
{\n\
return getPositionPlanarEarth(position, height, textureCoordinates);\n\
}\n\
vec4 getPositionMorphingMode(vec3 position, float height, vec2 textureCoordinates)\n\
{\n\
vec3 position3DWC = position + u_center3D;\n\
float yPositionFraction = get2DYPositionFraction(textureCoordinates);\n\
vec4 position2DWC = vec4(height, mix(u_tileRectangle.st, u_tileRectangle.pq, vec2(textureCoordinates.x, yPositionFraction)), 1.0);\n\
vec4 morphPosition = czm_columbusViewMorph(position2DWC, vec4(position3DWC, 1.0), czm_morphTime);\n\
return czm_modelViewProjection * morphPosition;\n\
}\n\
#ifdef QUANTIZATION_BITS12\n\
uniform vec2 u_minMaxHeight;\n\
uniform mat4 u_scaleAndBias;\n\
#endif\n\
void main()\n\
{\n\
#ifdef QUANTIZATION_BITS12\n\
vec2 xy = czm_decompressTextureCoordinates(compressed0.x);\n\
vec2 zh = czm_decompressTextureCoordinates(compressed0.y);\n\
vec3 position = vec3(xy, zh.x);\n\
float height = zh.y;\n\
vec2 textureCoordinates = czm_decompressTextureCoordinates(compressed0.z);\n\
height = height * (u_minMaxHeight.y - u_minMaxHeight.x) + u_minMaxHeight.x;\n\
position = (u_scaleAndBias * vec4(position, 1.0)).xyz;\n\
#if (defined(ENABLE_VERTEX_LIGHTING) || defined(GENERATE_POSITION_AND_NORMAL)) && defined(INCLUDE_WEB_MERCATOR_Y)\n\
float webMercatorT = czm_decompressTextureCoordinates(compressed0.w).x;\n\
float encodedNormal = compressed1;\n\
#elif defined(INCLUDE_WEB_MERCATOR_Y)\n\
float webMercatorT = czm_decompressTextureCoordinates(compressed0.w).x;\n\
float encodedNormal = 0.0;\n\
#elif defined(ENABLE_VERTEX_LIGHTING) || defined(GENERATE_POSITION_AND_NORMAL)\n\
float webMercatorT = textureCoordinates.y;\n\
float encodedNormal = compressed0.w;\n\
#else\n\
float webMercatorT = textureCoordinates.y;\n\
float encodedNormal = 0.0;\n\
#endif\n\
#else\n\
vec3 position = position3DAndHeight.xyz;\n\
float height = position3DAndHeight.w;\n\
vec2 textureCoordinates = textureCoordAndEncodedNormals.xy;\n\
#if (defined(ENABLE_VERTEX_LIGHTING) || defined(GENERATE_POSITION_AND_NORMAL) || defined(APPLY_MATERIAL)) && defined(INCLUDE_WEB_MERCATOR_Y)\n\
float webMercatorT = textureCoordAndEncodedNormals.z;\n\
float encodedNormal = textureCoordAndEncodedNormals.w;\n\
#elif defined(ENABLE_VERTEX_LIGHTING) || defined(GENERATE_POSITION_AND_NORMAL) || defined(APPLY_MATERIAL)\n\
float webMercatorT = textureCoordinates.y;\n\
float encodedNormal = textureCoordAndEncodedNormals.z;\n\
#elif defined(INCLUDE_WEB_MERCATOR_Y)\n\
float webMercatorT = textureCoordAndEncodedNormals.z;\n\
float encodedNormal = 0.0;\n\
#else\n\
float webMercatorT = textureCoordinates.y;\n\
float encodedNormal = 0.0;\n\
#endif\n\
#endif\n\
vec3 position3DWC = position + u_center3D;\n\
#ifdef GEODETIC_SURFACE_NORMALS\n\
vec3 ellipsoidNormal = geodeticSurfaceNormal;\n\
#else\n\
vec3 ellipsoidNormal = normalize(position3DWC);\n\
#endif\n\
#if defined(EXAGGERATION) && defined(GEODETIC_SURFACE_NORMALS)\n\
float exaggeration = u_terrainExaggerationAndRelativeHeight.x;\n\
float relativeHeight = u_terrainExaggerationAndRelativeHeight.y;\n\
float newHeight = (height - relativeHeight) * exaggeration + relativeHeight;\n\
float minRadius = min(min(czm_ellipsoidRadii.x, czm_ellipsoidRadii.y), czm_ellipsoidRadii.z);\n\
newHeight = max(newHeight, -minRadius);\n\
vec3 offset = ellipsoidNormal * (newHeight - height);\n\
position += offset;\n\
position3DWC += offset;\n\
height = newHeight;\n\
#endif\n\
gl_Position = getPosition(position, height, textureCoordinates);\n\
v_positionEC = (u_modifiedModelView * vec4(position, 1.0)).xyz;\n\
v_positionMC = position3DWC;\n\
v_textureCoordinates = vec3(textureCoordinates, webMercatorT);\n\
#if defined(ENABLE_VERTEX_LIGHTING) || defined(GENERATE_POSITION_AND_NORMAL) || defined(APPLY_MATERIAL)\n\
vec3 normalMC = czm_octDecode(encodedNormal);\n\
#if defined(EXAGGERATION) && defined(GEODETIC_SURFACE_NORMALS)\n\
vec3 projection = dot(normalMC, ellipsoidNormal) * ellipsoidNormal;\n\
vec3 rejection = normalMC - projection;\n\
normalMC = normalize(projection + rejection * exaggeration);\n\
#endif\n\
v_normalMC = normalMC;\n\
v_normalEC = czm_normal3D * v_normalMC;\n\
#endif\n\
#if defined(FOG) || (defined(GROUND_ATMOSPHERE) && !defined(PER_FRAGMENT_GROUND_ATMOSPHERE))\n\
bool dynamicLighting = false;\n\
#if defined(DYNAMIC_ATMOSPHERE_LIGHTING) && (defined(ENABLE_DAYNIGHT_SHADING) || defined(ENABLE_VERTEX_LIGHTING))\n\
dynamicLighting = true;\n\
#endif\n\
#if defined(DYNAMIC_ATMOSPHERE_LIGHTING_FROM_SUN)\n\
vec3 atmosphereLightDirection = czm_sunDirectionWC;\n\
#else\n\
vec3 atmosphereLightDirection = czm_lightDirectionWC;\n\
#endif\n\
vec3 lightDirection = czm_branchFreeTernary(dynamicLighting, atmosphereLightDirection, normalize(position3DWC));\n\
computeAtmosphereScattering(\n\
position3DWC,\n\
lightDirection,\n\
v_atmosphereRayleighColor,\n\
v_atmosphereMieColor,\n\
v_atmosphereOpacity\n\
);\n\
#endif\n\
#if defined(FOG) || defined(GROUND_ATMOSPHERE) || defined(UNDERGROUND_COLOR) || defined(TRANSLUCENT)\n\
v_distance = length((czm_modelView3D * vec4(position3DWC, 1.0)).xyz);\n\
#endif\n\
#ifdef APPLY_MATERIAL\n\
float northPoleZ = czm_ellipsoidRadii.z;\n\
vec3 northPolePositionMC = vec3(0.0, 0.0, northPoleZ);\n\
vec3 vectorEastMC = normalize(cross(northPolePositionMC - v_positionMC, ellipsoidNormal));\n\
float dotProd = abs(dot(ellipsoidNormal, v_normalMC));\n\
v_slope = acos(dotProd);\n\
vec3 normalRejected = ellipsoidNormal * dotProd;\n\
vec3 normalProjected = v_normalMC - normalRejected;\n\
vec3 aspectVector = normalize(normalProjected);\n\
v_aspect = acos(dot(aspectVector, vectorEastMC));\n\
float determ = dot(cross(vectorEastMC, aspectVector), ellipsoidNormal);\n\
v_aspect = czm_branchFreeTernary(determ < 0.0, 2.0 * czm_pi - v_aspect, v_aspect);\n\
v_height = height;\n\
#endif\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var AtmosphereCommon = "uniform vec3 u_radiiAndDynamicAtmosphereColor;\n\
uniform float u_atmosphereLightIntensity;\n\
uniform float u_atmosphereRayleighScaleHeight;\n\
uniform float u_atmosphereMieScaleHeight;\n\
uniform float u_atmosphereMieAnisotropy;\n\
uniform vec3 u_atmosphereRayleighCoefficient;\n\
uniform vec3 u_atmosphereMieCoefficient;\n\
const float ATMOSPHERE_THICKNESS = 111e3;\n\
const int PRIMARY_STEPS = 16;\n\
const int LIGHT_STEPS = 4;\n\
void computeScattering(\n\
czm_ray primaryRay,\n\
float primaryRayLength,\n\
vec3 lightDirection,\n\
float atmosphereInnerRadius,\n\
out vec3 rayleighColor,\n\
out vec3 mieColor,\n\
out float opacity\n\
) {\n\
rayleighColor = vec3(0.0);\n\
mieColor = vec3(0.0);\n\
opacity = 0.0;\n\
float atmosphereOuterRadius = atmosphereInnerRadius + ATMOSPHERE_THICKNESS;\n\
vec3 origin = vec3(0.0);\n\
czm_raySegment primaryRayAtmosphereIntersect = czm_raySphereIntersectionInterval(primaryRay, origin, atmosphereOuterRadius);\n\
if (primaryRayAtmosphereIntersect == czm_emptyRaySegment) {\n\
return;\n\
}\n\
primaryRayAtmosphereIntersect.start = max(primaryRayAtmosphereIntersect.start, 0.0);\n\
primaryRayAtmosphereIntersect.stop = min(primaryRayAtmosphereIntersect.stop, length(primaryRayLength));\n\
float rayStepLength = (primaryRayAtmosphereIntersect.stop - primaryRayAtmosphereIntersect.start) / float(PRIMARY_STEPS);\n\
float rayPositionLength = primaryRayAtmosphereIntersect.start;\n\
vec3 rayleighAccumulation = vec3(0.0);\n\
vec3 mieAccumulation = vec3(0.0);\n\
vec2 opticalDepth = vec2(0.0);\n\
vec2 heightScale = vec2(u_atmosphereRayleighScaleHeight, u_atmosphereMieScaleHeight);\n\
for (int i = 0; i < PRIMARY_STEPS; i++) {\n\
vec3 samplePosition = primaryRay.origin + primaryRay.direction * (rayPositionLength + rayStepLength);\n\
float sampleHeight = length(samplePosition) - atmosphereInnerRadius;\n\
vec2 sampleDensity = exp(-sampleHeight / heightScale) * rayStepLength;\n\
opticalDepth += sampleDensity;\n\
czm_ray lightRay = czm_ray(samplePosition, lightDirection);\n\
czm_raySegment lightRayAtmosphereIntersect = czm_raySphereIntersectionInterval(lightRay, origin, atmosphereOuterRadius);\n\
float lightStepLength = lightRayAtmosphereIntersect.stop / float(LIGHT_STEPS);\n\
float lightPositionLength = 0.0;\n\
vec2 lightOpticalDepth = vec2(0.0);\n\
for (int j = 0; j < LIGHT_STEPS; j++) {\n\
vec3 lightPosition = samplePosition + lightDirection * (lightPositionLength + lightStepLength * 0.5);\n\
float lightHeight = length(lightPosition) - atmosphereInnerRadius;\n\
lightOpticalDepth += exp(-lightHeight / heightScale) * lightStepLength;\n\
lightPositionLength += lightStepLength;\n\
}\n\
vec3 attenuation = exp(-((u_atmosphereMieCoefficient * (opticalDepth.y + lightOpticalDepth.y)) + (u_atmosphereRayleighCoefficient * (opticalDepth.x + lightOpticalDepth.x))));\n\
rayleighAccumulation += sampleDensity.x * attenuation;\n\
mieAccumulation += sampleDensity.y * attenuation;\n\
rayPositionLength += rayStepLength;\n\
}\n\
rayleighColor = u_atmosphereRayleighCoefficient * rayleighAccumulation;\n\
mieColor = u_atmosphereMieCoefficient * mieAccumulation;\n\
opacity = length(exp(-((u_atmosphereMieCoefficient * opticalDepth.y) + (u_atmosphereRayleighCoefficient * opticalDepth.x))));\n\
}\n\
vec4 computeAtmosphereColor(\n\
vec3 positionWC,\n\
vec3 lightDirection,\n\
vec3 rayleighColor,\n\
vec3 mieColor,\n\
float opacity\n\
) {\n\
vec3 cameraToPositionWC = positionWC - czm_viewerPositionWC;\n\
vec3 cameraToPositionWCDirection = normalize(cameraToPositionWC);\n\
float cosAngle = dot(cameraToPositionWCDirection, lightDirection);\n\
float cosAngleSq = cosAngle * cosAngle;\n\
float G = u_atmosphereMieAnisotropy;\n\
float GSq = G * G;\n\
float rayleighPhase = 3.0 / (50.2654824574) * (1.0 + cosAngleSq);\n\
float miePhase = 3.0 / (25.1327412287) * ((1.0 - GSq) * (cosAngleSq + 1.0)) / (pow(1.0 + GSq - 2.0 * cosAngle * G, 1.5) * (2.0 + GSq));\n\
vec3 rayleigh = rayleighPhase * rayleighColor;\n\
vec3 mie = miePhase * mieColor;\n\
vec3 color = (rayleigh + mie) * u_atmosphereLightIntensity;\n\
return vec4(color, opacity);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var GroundAtmosphere = "void computeAtmosphereScattering(vec3 positionWC, vec3 lightDirection, out vec3 rayleighColor, out vec3 mieColor, out float opacity) {\n\
vec3 cameraToPositionWC = positionWC - czm_viewerPositionWC;\n\
vec3 cameraToPositionWCDirection = normalize(cameraToPositionWC);\n\
czm_ray primaryRay = czm_ray(czm_viewerPositionWC, cameraToPositionWCDirection);\n\
float atmosphereInnerRadius = length(positionWC);\n\
computeScattering(\n\
primaryRay,\n\
length(cameraToPositionWC),\n\
lightDirection,\n\
atmosphereInnerRadius,\n\
rayleighColor,\n\
mieColor,\n\
opacity\n\
);\n\
}\n\
";

  function GlobeSurfaceShader(
    numberOfDayTextures,
    flags,
    material,
    shaderProgram,
    clippingShaderState
  ) {
    this.numberOfDayTextures = numberOfDayTextures;
    this.flags = flags;
    this.material = material;
    this.shaderProgram = shaderProgram;
    this.clippingShaderState = clippingShaderState;
  }

  /**
   * Manages the shaders used to shade the surface of a {@link Globe}.
   *
   * @alias GlobeSurfaceShaderSet
   * @private
   */
  function GlobeSurfaceShaderSet() {
    this.baseVertexShaderSource = undefined;
    this.baseFragmentShaderSource = undefined;

    this._shadersByTexturesFlags = [];

    this.material = undefined;
  }

  function getPositionMode(sceneMode) {
    const getPosition3DMode =
      "vec4 getPosition(vec3 position, float height, vec2 textureCoordinates) { return getPosition3DMode(position, height, textureCoordinates); }";
    const getPositionColumbusViewAnd2DMode =
      "vec4 getPosition(vec3 position, float height, vec2 textureCoordinates) { return getPositionColumbusViewMode(position, height, textureCoordinates); }";
    const getPositionMorphingMode =
      "vec4 getPosition(vec3 position, float height, vec2 textureCoordinates) { return getPositionMorphingMode(position, height, textureCoordinates); }";

    let positionMode;

    switch (sceneMode) {
      case SceneMode$1.SCENE3D:
        positionMode = getPosition3DMode;
        break;
      case SceneMode$1.SCENE2D:
      case SceneMode$1.COLUMBUS_VIEW:
        positionMode = getPositionColumbusViewAnd2DMode;
        break;
      case SceneMode$1.MORPHING:
        positionMode = getPositionMorphingMode;
        break;
    }

    return positionMode;
  }

  function get2DYPositionFraction(useWebMercatorProjection) {
    const get2DYPositionFractionGeographicProjection =
      "float get2DYPositionFraction(vec2 textureCoordinates) { return get2DGeographicYPositionFraction(textureCoordinates); }";
    const get2DYPositionFractionMercatorProjection =
      "float get2DYPositionFraction(vec2 textureCoordinates) { return get2DMercatorYPositionFraction(textureCoordinates); }";
    return useWebMercatorProjection
      ? get2DYPositionFractionMercatorProjection
      : get2DYPositionFractionGeographicProjection;
  }

  GlobeSurfaceShaderSet.prototype.getShaderProgram = function (options) {
    const frameState = options.frameState;
    const surfaceTile = options.surfaceTile;
    const numberOfDayTextures = options.numberOfDayTextures;
    const applyBrightness = options.applyBrightness;
    const applyContrast = options.applyContrast;
    const applyHue = options.applyHue;
    const applySaturation = options.applySaturation;
    const applyGamma = options.applyGamma;
    const applyAlpha = options.applyAlpha;
    const applyDayNightAlpha = options.applyDayNightAlpha;
    const applySplit = options.applySplit;
    const showReflectiveOcean = options.showReflectiveOcean;
    const showOceanWaves = options.showOceanWaves;
    const enableLighting = options.enableLighting;
    const dynamicAtmosphereLighting = options.dynamicAtmosphereLighting;
    const dynamicAtmosphereLightingFromSun =
      options.dynamicAtmosphereLightingFromSun;
    const showGroundAtmosphere = options.showGroundAtmosphere;
    const perFragmentGroundAtmosphere = options.perFragmentGroundAtmosphere;
    const hasVertexNormals = options.hasVertexNormals;
    const useWebMercatorProjection = options.useWebMercatorProjection;
    const enableFog = options.enableFog;
    const enableClippingPlanes = options.enableClippingPlanes;
    const clippingPlanes = options.clippingPlanes;
    const clippedByBoundaries = options.clippedByBoundaries;
    const hasImageryLayerCutout = options.hasImageryLayerCutout;
    const colorCorrect = options.colorCorrect;
    const highlightFillTile = options.highlightFillTile;
    const colorToAlpha = options.colorToAlpha;
    const hasGeodeticSurfaceNormals = options.hasGeodeticSurfaceNormals;
    const hasExaggeration = options.hasExaggeration;
    const showUndergroundColor = options.showUndergroundColor;
    const translucent = options.translucent;

    let quantization = 0;
    let quantizationDefine = "";

    const mesh = surfaceTile.renderedMesh;
    const terrainEncoding = mesh.encoding;
    const quantizationMode = terrainEncoding.quantization;
    if (quantizationMode === TerrainQuantization$1.BITS12) {
      quantization = 1;
      quantizationDefine = "QUANTIZATION_BITS12";
    }

    let cartographicLimitRectangleFlag = 0;
    let cartographicLimitRectangleDefine = "";
    if (clippedByBoundaries) {
      cartographicLimitRectangleFlag = 1;
      cartographicLimitRectangleDefine = "TILE_LIMIT_RECTANGLE";
    }

    let imageryCutoutFlag = 0;
    let imageryCutoutDefine = "";
    if (hasImageryLayerCutout) {
      imageryCutoutFlag = 1;
      imageryCutoutDefine = "APPLY_IMAGERY_CUTOUT";
    }

    const sceneMode = frameState.mode;
    const flags =
      sceneMode |
      (applyBrightness << 2) |
      (applyContrast << 3) |
      (applyHue << 4) |
      (applySaturation << 5) |
      (applyGamma << 6) |
      (applyAlpha << 7) |
      (showReflectiveOcean << 8) |
      (showOceanWaves << 9) |
      (enableLighting << 10) |
      (dynamicAtmosphereLighting << 11) |
      (dynamicAtmosphereLightingFromSun << 12) |
      (showGroundAtmosphere << 13) |
      (perFragmentGroundAtmosphere << 14) |
      (hasVertexNormals << 15) |
      (useWebMercatorProjection << 16) |
      (enableFog << 17) |
      (quantization << 18) |
      (applySplit << 19) |
      (enableClippingPlanes << 20) |
      (cartographicLimitRectangleFlag << 21) |
      (imageryCutoutFlag << 22) |
      (colorCorrect << 23) |
      (highlightFillTile << 24) |
      (colorToAlpha << 25) |
      (hasGeodeticSurfaceNormals << 26) |
      (hasExaggeration << 27) |
      (showUndergroundColor << 28) |
      (translucent << 29) |
      (applyDayNightAlpha << 30);

    let currentClippingShaderState = 0;
    if (defined(clippingPlanes) && clippingPlanes.length > 0) {
      currentClippingShaderState = enableClippingPlanes
        ? clippingPlanes.clippingPlanesState
        : 0;
    }
    let surfaceShader = surfaceTile.surfaceShader;
    if (
      defined(surfaceShader) &&
      surfaceShader.numberOfDayTextures === numberOfDayTextures &&
      surfaceShader.flags === flags &&
      surfaceShader.material === this.material &&
      surfaceShader.clippingShaderState === currentClippingShaderState
    ) {
      return surfaceShader.shaderProgram;
    }

    // New tile, or tile changed number of textures, flags, or clipping planes
    let shadersByFlags = this._shadersByTexturesFlags[numberOfDayTextures];
    if (!defined(shadersByFlags)) {
      shadersByFlags = this._shadersByTexturesFlags[numberOfDayTextures] = [];
    }

    surfaceShader = shadersByFlags[flags];
    if (
      !defined(surfaceShader) ||
      surfaceShader.material !== this.material ||
      surfaceShader.clippingShaderState !== currentClippingShaderState
    ) {
      // Cache miss - we've never seen this combination of numberOfDayTextures and flags before.
      const vs = this.baseVertexShaderSource.clone();
      const fs = this.baseFragmentShaderSource.clone();

      if (currentClippingShaderState !== 0) {
        fs.sources.unshift(
          getClippingFunction(clippingPlanes, frameState.context)
        ); // Need to go before GlobeFS
      }

      vs.defines.push(quantizationDefine);
      fs.defines.push(
        `TEXTURE_UNITS ${numberOfDayTextures}`,
        cartographicLimitRectangleDefine,
        imageryCutoutDefine
      );

      if (applyBrightness) {
        fs.defines.push("APPLY_BRIGHTNESS");
      }
      if (applyContrast) {
        fs.defines.push("APPLY_CONTRAST");
      }
      if (applyHue) {
        fs.defines.push("APPLY_HUE");
      }
      if (applySaturation) {
        fs.defines.push("APPLY_SATURATION");
      }
      if (applyGamma) {
        fs.defines.push("APPLY_GAMMA");
      }
      if (applyAlpha) {
        fs.defines.push("APPLY_ALPHA");
      }
      if (applyDayNightAlpha) {
        fs.defines.push("APPLY_DAY_NIGHT_ALPHA");
      }
      if (showReflectiveOcean) {
        fs.defines.push("SHOW_REFLECTIVE_OCEAN");
        vs.defines.push("SHOW_REFLECTIVE_OCEAN");
      }
      if (showOceanWaves) {
        fs.defines.push("SHOW_OCEAN_WAVES");
      }
      if (colorToAlpha) {
        fs.defines.push("APPLY_COLOR_TO_ALPHA");
      }
      if (showUndergroundColor) {
        vs.defines.push("UNDERGROUND_COLOR");
        fs.defines.push("UNDERGROUND_COLOR");
      }
      if (translucent) {
        vs.defines.push("TRANSLUCENT");
        fs.defines.push("TRANSLUCENT");
      }
      if (enableLighting) {
        if (hasVertexNormals) {
          vs.defines.push("ENABLE_VERTEX_LIGHTING");
          fs.defines.push("ENABLE_VERTEX_LIGHTING");
        } else {
          vs.defines.push("ENABLE_DAYNIGHT_SHADING");
          fs.defines.push("ENABLE_DAYNIGHT_SHADING");
        }
      }

      if (dynamicAtmosphereLighting) {
        vs.defines.push("DYNAMIC_ATMOSPHERE_LIGHTING");
        fs.defines.push("DYNAMIC_ATMOSPHERE_LIGHTING");
        if (dynamicAtmosphereLightingFromSun) {
          vs.defines.push("DYNAMIC_ATMOSPHERE_LIGHTING_FROM_SUN");
          fs.defines.push("DYNAMIC_ATMOSPHERE_LIGHTING_FROM_SUN");
        }
      }

      if (showGroundAtmosphere) {
        vs.defines.push("GROUND_ATMOSPHERE");
        fs.defines.push("GROUND_ATMOSPHERE");
        if (perFragmentGroundAtmosphere) {
          vs.defines.push("PER_FRAGMENT_GROUND_ATMOSPHERE");
          fs.defines.push("PER_FRAGMENT_GROUND_ATMOSPHERE");
        }
      }

      vs.defines.push("INCLUDE_WEB_MERCATOR_Y");
      fs.defines.push("INCLUDE_WEB_MERCATOR_Y");

      if (enableFog) {
        vs.defines.push("FOG");
        fs.defines.push("FOG");
      }

      if (applySplit) {
        fs.defines.push("APPLY_SPLIT");
      }

      if (enableClippingPlanes) {
        fs.defines.push("ENABLE_CLIPPING_PLANES");
      }

      if (colorCorrect) {
        fs.defines.push("COLOR_CORRECT");
      }

      if (highlightFillTile) {
        fs.defines.push("HIGHLIGHT_FILL_TILE");
      }

      if (hasGeodeticSurfaceNormals) {
        vs.defines.push("GEODETIC_SURFACE_NORMALS");
      }

      if (hasExaggeration) {
        vs.defines.push("EXAGGERATION");
      }

      let computeDayColor =
        "\
    vec4 computeDayColor(vec4 initialColor, vec3 textureCoordinates, float nightBlend)\n\
    {\n\
        vec4 color = initialColor;\n";

      if (hasImageryLayerCutout) {
        computeDayColor +=
          "\
        vec4 cutoutAndColorResult;\n\
        bool texelUnclipped;\n";
      }

      for (let i = 0; i < numberOfDayTextures; ++i) {
        if (hasImageryLayerCutout) {
          computeDayColor += `\
        cutoutAndColorResult = u_dayTextureCutoutRectangles[${i}];\n\
        texelUnclipped = v_textureCoordinates.x < cutoutAndColorResult.x || cutoutAndColorResult.z < v_textureCoordinates.x || v_textureCoordinates.y < cutoutAndColorResult.y || cutoutAndColorResult.w < v_textureCoordinates.y;\n\
        cutoutAndColorResult = sampleAndBlend(\n`;
        } else {
          computeDayColor += "\
        color = sampleAndBlend(\n";
        }
        computeDayColor += `\
            color,\n\
            u_dayTextures[${i}],\n\
            u_dayTextureUseWebMercatorT[${i}] ? textureCoordinates.xz : textureCoordinates.xy,\n\
            u_dayTextureTexCoordsRectangle[${i}],\n\
            u_dayTextureTranslationAndScale[${i}],\n\
            ${applyAlpha ? `u_dayTextureAlpha[${i}]` : "1.0"},\n\
            ${applyDayNightAlpha ? `u_dayTextureNightAlpha[${i}]` : "1.0"},\n${
        applyDayNightAlpha ? `u_dayTextureDayAlpha[${i}]` : "1.0"
      },\n${applyBrightness ? `u_dayTextureBrightness[${i}]` : "0.0"},\n\
            ${applyContrast ? `u_dayTextureContrast[${i}]` : "0.0"},\n\
            ${applyHue ? `u_dayTextureHue[${i}]` : "0.0"},\n\
            ${applySaturation ? `u_dayTextureSaturation[${i}]` : "0.0"},\n\
            ${applyGamma ? `u_dayTextureOneOverGamma[${i}]` : "0.0"},\n\
            ${applySplit ? `u_dayTextureSplit[${i}]` : "0.0"},\n\
            ${colorToAlpha ? `u_colorsToAlpha[${i}]` : "vec4(0.0)"},\n\
        nightBlend\
        );\n`;
        if (hasImageryLayerCutout) {
          computeDayColor +=
            "\
        color = czm_branchFreeTernary(texelUnclipped, cutoutAndColorResult, color);\n";
        }
      }

      computeDayColor += "\
        return color;\n\
    }";

      fs.sources.push(computeDayColor);

      vs.sources.push(getPositionMode(sceneMode));
      vs.sources.push(get2DYPositionFraction(useWebMercatorProjection));

      const shader = ShaderProgram.fromCache({
        context: frameState.context,
        vertexShaderSource: vs,
        fragmentShaderSource: fs,
        attributeLocations: terrainEncoding.getAttributeLocations(),
      });

      surfaceShader = shadersByFlags[flags] = new GlobeSurfaceShader(
        numberOfDayTextures,
        flags,
        this.material,
        shader,
        currentClippingShaderState
      );
    }

    surfaceTile.surfaceShader = surfaceShader;
    return surfaceShader.shaderProgram;
  };

  GlobeSurfaceShaderSet.prototype.destroy = function () {
    let flags;
    let shader;

    const shadersByTexturesFlags = this._shadersByTexturesFlags;
    for (const textureCount in shadersByTexturesFlags) {
      if (shadersByTexturesFlags.hasOwnProperty(textureCount)) {
        const shadersByFlags = shadersByTexturesFlags[textureCount];
        if (!defined(shadersByFlags)) {
          continue;
        }

        for (flags in shadersByFlags) {
          if (shadersByFlags.hasOwnProperty(flags)) {
            shader = shadersByFlags[flags];
            if (defined(shader)) {
              shader.shaderProgram.destroy();
            }
          }
        }
      }
    }

    return destroyObject(this);
  };

  /**
   * @private
   */
  const ImageryState = {
    UNLOADED: 0,
    TRANSITIONING: 1,
    RECEIVED: 2,
    TEXTURE_LOADED: 3,
    READY: 4,
    FAILED: 5,
    INVALID: 6,
    PLACEHOLDER: 7,
  };
  var ImageryState$1 = Object.freeze(ImageryState);

  /**
   * The state of a {@link QuadtreeTile} in the tile load pipeline.
   * @enum {Number}
   * @private
   */
  const QuadtreeTileLoadState = {
    /**
     * The tile is new and loading has not yet begun.
     * @type QuadtreeTileLoadState
     * @constant
     * @default 0
     */
    START: 0,

    /**
     * Loading is in progress.
     * @type QuadtreeTileLoadState
     * @constant
     * @default 1
     */
    LOADING: 1,

    /**
     * Loading is complete.
     * @type QuadtreeTileLoadState
     * @constant
     * @default 2
     */
    DONE: 2,

    /**
     * The tile has failed to load.
     * @type QuadtreeTileLoadState
     * @constant
     * @default 3
     */
    FAILED: 3,
  };
  var QuadtreeTileLoadState$1 = Object.freeze(QuadtreeTileLoadState);

  /**
   * @private
   */
  const TerrainState = {
    FAILED: 0,
    UNLOADED: 1,
    RECEIVING: 2,
    RECEIVED: 3,
    TRANSFORMING: 4,
    TRANSFORMED: 5,
    READY: 6,
  };
  var TerrainState$1 = Object.freeze(TerrainState);

  /**
   * Contains additional information about a {@link QuadtreeTile} of the globe's surface, and
   * encapsulates state transition logic for loading tiles.
   *
   * @constructor
   * @alias GlobeSurfaceTile
   * @private
   */
  function GlobeSurfaceTile() {
    /**
     * The {@link TileImagery} attached to this tile.
     * @type {TileImagery[]}
     * @default []
     */
    this.imagery = [];

    this.waterMaskTexture = undefined;
    this.waterMaskTranslationAndScale = new Cartesian4(0.0, 0.0, 1.0, 1.0);

    this.terrainData = undefined;
    this.vertexArray = undefined;

    /**
     * A bounding region used to estimate distance to the tile. The horizontal bounds are always tight-fitting,
     * but the `minimumHeight` and `maximumHeight` properties may be derived from the min/max of an ancestor tile
     * and be quite loose-fitting and thus very poor for estimating distance.
     * @type {TileBoundingRegion}
     */
    this.tileBoundingRegion = undefined;
    this.occludeePointInScaledSpace = new Cartesian3();
    this.boundingVolumeSourceTile = undefined;
    this.boundingVolumeIsFromMesh = false;

    this.terrainState = TerrainState$1.UNLOADED;
    this.mesh = undefined;
    this.fill = undefined;

    this.pickBoundingSphere = new BoundingSphere();

    this.surfaceShader = undefined;
    this.isClipped = true;

    this.clippedByBoundaries = false;
  }

  Object.defineProperties(GlobeSurfaceTile.prototype, {
    /**
     * Gets a value indicating whether or not this tile is eligible to be unloaded.
     * Typically, a tile is ineligible to be unloaded while an asynchronous operation,
     * such as a request for data, is in progress on it.  A tile will never be
     * unloaded while it is needed for rendering, regardless of the value of this
     * property.
     * @memberof GlobeSurfaceTile.prototype
     * @type {Boolean}
     */
    eligibleForUnloading: {
      get: function () {
        // Do not remove tiles that are transitioning or that have
        // imagery that is transitioning.
        const terrainState = this.terrainState;
        const loadingIsTransitioning =
          terrainState === TerrainState$1.RECEIVING ||
          terrainState === TerrainState$1.TRANSFORMING;

        let shouldRemoveTile = !loadingIsTransitioning;

        const imagery = this.imagery;
        for (let i = 0, len = imagery.length; shouldRemoveTile && i < len; ++i) {
          const tileImagery = imagery[i];
          shouldRemoveTile =
            !defined(tileImagery.loadingImagery) ||
            tileImagery.loadingImagery.state !== ImageryState$1.TRANSITIONING;
        }

        return shouldRemoveTile;
      },
    },

    /**
     * Gets the {@link TerrainMesh} that is used for rendering this tile, if any.
     * Returns the value of the {@link GlobeSurfaceTile#mesh} property if
     * {@link GlobeSurfaceTile#vertexArray} is defined. Otherwise, It returns the
     * {@link TerrainFillMesh#mesh} property of the {@link GlobeSurfaceTile#fill}.
     * If there is no fill, it returns undefined.
     *
     * @memberof GlobeSurfaceTile.prototype
     * @type {TerrainMesh}
     */
    renderedMesh: {
      get: function () {
        if (defined(this.vertexArray)) {
          return this.mesh;
        } else if (defined(this.fill)) {
          return this.fill.mesh;
        }
        return undefined;
      },
    },
  });

  const scratchCartographic$3 = new Cartographic();

  function getPosition(encoding, mode, projection, vertices, index, result) {
    let position = encoding.getExaggeratedPosition(vertices, index, result);

    if (defined(mode) && mode !== SceneMode$1.SCENE3D) {
      const ellipsoid = projection.ellipsoid;
      const positionCartographic = ellipsoid.cartesianToCartographic(
        position,
        scratchCartographic$3
      );
      position = projection.project(positionCartographic, result);
      position = Cartesian3.fromElements(
        position.z,
        position.x,
        position.y,
        result
      );
    }

    return position;
  }

  const scratchV0 = new Cartesian3();
  const scratchV1 = new Cartesian3();
  const scratchV2 = new Cartesian3();

  GlobeSurfaceTile.prototype.pick = function (
    ray,
    mode,
    projection,
    cullBackFaces,
    result
  ) {
    const mesh = this.renderedMesh;
    if (!defined(mesh)) {
      return undefined;
    }

    const vertices = mesh.vertices;
    const indices = mesh.indices;
    const encoding = mesh.encoding;
    const indicesLength = indices.length;

    let minT = Number.MAX_VALUE;

    for (let i = 0; i < indicesLength; i += 3) {
      const i0 = indices[i];
      const i1 = indices[i + 1];
      const i2 = indices[i + 2];

      const v0 = getPosition(encoding, mode, projection, vertices, i0, scratchV0);
      const v1 = getPosition(encoding, mode, projection, vertices, i1, scratchV1);
      const v2 = getPosition(encoding, mode, projection, vertices, i2, scratchV2);

      const t = IntersectionTests.rayTriangleParametric(
        ray,
        v0,
        v1,
        v2,
        cullBackFaces
      );
      if (defined(t) && t < minT && t >= 0.0) {
        minT = t;
      }
    }

    return minT !== Number.MAX_VALUE
      ? Ray.getPoint(ray, minT, result)
      : undefined;
  };

  GlobeSurfaceTile.prototype.freeResources = function () {
    if (defined(this.waterMaskTexture)) {
      --this.waterMaskTexture.referenceCount;
      if (this.waterMaskTexture.referenceCount === 0) {
        this.waterMaskTexture.destroy();
      }
      this.waterMaskTexture = undefined;
    }

    this.terrainData = undefined;

    this.terrainState = TerrainState$1.UNLOADED;
    this.mesh = undefined;
    this.fill = this.fill && this.fill.destroy();

    const imageryList = this.imagery;
    for (let i = 0, len = imageryList.length; i < len; ++i) {
      imageryList[i].freeResources();
    }
    this.imagery.length = 0;

    this.freeVertexArray();
  };

  GlobeSurfaceTile.prototype.freeVertexArray = function () {
    GlobeSurfaceTile._freeVertexArray(this.vertexArray);
    this.vertexArray = undefined;
    GlobeSurfaceTile._freeVertexArray(this.wireframeVertexArray);
    this.wireframeVertexArray = undefined;
  };

  GlobeSurfaceTile.initialize = function (
    tile,
    terrainProvider,
    imageryLayerCollection
  ) {
    let surfaceTile = tile.data;
    if (!defined(surfaceTile)) {
      surfaceTile = tile.data = new GlobeSurfaceTile();
    }

    if (tile.state === QuadtreeTileLoadState$1.START) {
      prepareNewTile(tile, terrainProvider, imageryLayerCollection);
      tile.state = QuadtreeTileLoadState$1.LOADING;
    }
  };

  GlobeSurfaceTile.processStateMachine = function (
    tile,
    frameState,
    terrainProvider,
    imageryLayerCollection,
    quadtree,
    vertexArraysToDestroy,
    terrainOnly
  ) {
    GlobeSurfaceTile.initialize(tile, terrainProvider, imageryLayerCollection);

    const surfaceTile = tile.data;

    if (tile.state === QuadtreeTileLoadState$1.LOADING) {
      processTerrainStateMachine(
        tile,
        frameState,
        terrainProvider,
        imageryLayerCollection,
        quadtree,
        vertexArraysToDestroy
      );
    }

    // From here down we're loading imagery, not terrain. We don't want to load imagery until
    // we're certain that the terrain tiles are actually visible, though. We'll load terrainOnly
    // in these scenarios:
    //   * our bounding volume isn't accurate so we're not certain this tile is really visible (see GlobeSurfaceTileProvider#loadTile).
    //   * we want to upsample from this tile but don't plan to render it (see processTerrainStateMachine).
    if (terrainOnly) {
      return;
    }

    const wasAlreadyRenderable = tile.renderable;

    // The terrain is renderable as soon as we have a valid vertex array.
    tile.renderable = defined(surfaceTile.vertexArray);

    // But it's not done loading until it's in the READY state.
    const isTerrainDoneLoading = surfaceTile.terrainState === TerrainState$1.READY;

    // If this tile's terrain and imagery are just upsampled from its parent, mark the tile as
    // upsampled only.  We won't refine a tile if its four children are upsampled only.
    tile.upsampledFromParent =
      defined(surfaceTile.terrainData) &&
      surfaceTile.terrainData.wasCreatedByUpsampling();

    const isImageryDoneLoading = surfaceTile.processImagery(
      tile,
      terrainProvider,
      frameState
    );

    if (isTerrainDoneLoading && isImageryDoneLoading) {
      const callbacks = tile._loadedCallbacks;
      const newCallbacks = {};
      for (const layerId in callbacks) {
        if (callbacks.hasOwnProperty(layerId)) {
          if (!callbacks[layerId](tile)) {
            newCallbacks[layerId] = callbacks[layerId];
          }
        }
      }
      tile._loadedCallbacks = newCallbacks;

      tile.state = QuadtreeTileLoadState$1.DONE;
    }

    // Once a tile is renderable, it stays renderable, because doing otherwise would
    // cause detail (or maybe even the entire globe) to vanish when adding a new
    // imagery layer. `GlobeSurfaceTileProvider._onLayerAdded` sets renderable to
    // false for all affected tiles that are not currently being rendered.
    if (wasAlreadyRenderable) {
      tile.renderable = true;
    }
  };

  GlobeSurfaceTile.prototype.processImagery = function (
    tile,
    terrainProvider,
    frameState,
    skipLoading
  ) {
    const surfaceTile = tile.data;
    let isUpsampledOnly = tile.upsampledFromParent;
    let isAnyTileLoaded = false;
    let isDoneLoading = true;

    // Transition imagery states
    const tileImageryCollection = surfaceTile.imagery;
    let i, len;
    for (i = 0, len = tileImageryCollection.length; i < len; ++i) {
      const tileImagery = tileImageryCollection[i];
      if (!defined(tileImagery.loadingImagery)) {
        isUpsampledOnly = false;
        continue;
      }

      if (tileImagery.loadingImagery.state === ImageryState$1.PLACEHOLDER) {
        const imageryLayer = tileImagery.loadingImagery.imageryLayer;
        if (imageryLayer.imageryProvider.ready) {
          // Remove the placeholder and add the actual skeletons (if any)
          // at the same position.  Then continue the loop at the same index.
          tileImagery.freeResources();
          tileImageryCollection.splice(i, 1);
          imageryLayer._createTileImagerySkeletons(tile, terrainProvider, i);
          --i;
          len = tileImageryCollection.length;
          continue;
        } else {
          isUpsampledOnly = false;
        }
      }

      const thisTileDoneLoading = tileImagery.processStateMachine(
        tile,
        frameState,
        skipLoading
      );
      isDoneLoading = isDoneLoading && thisTileDoneLoading;

      // The imagery is renderable as soon as we have any renderable imagery for this region.
      isAnyTileLoaded =
        isAnyTileLoaded ||
        thisTileDoneLoading ||
        defined(tileImagery.readyImagery);

      isUpsampledOnly =
        isUpsampledOnly &&
        defined(tileImagery.loadingImagery) &&
        (tileImagery.loadingImagery.state === ImageryState$1.FAILED ||
          tileImagery.loadingImagery.state === ImageryState$1.INVALID);
    }

    tile.upsampledFromParent = isUpsampledOnly;

    // Allow rendering if any available layers are loaded
    tile.renderable = tile.renderable && (isAnyTileLoaded || isDoneLoading);

    return isDoneLoading;
  };

  function toggleGeodeticSurfaceNormals(
    surfaceTile,
    enabled,
    ellipsoid,
    frameState
  ) {
    const renderedMesh = surfaceTile.renderedMesh;
    const vertexBuffer = renderedMesh.vertices;
    const encoding = renderedMesh.encoding;
    const vertexCount = vertexBuffer.length / encoding.stride;

    // Calculate the new stride and generate a new buffer
    // Clone the other encoding, toggle geodetic surface normals, then clone again to get updated stride
    let newEncoding = TerrainEncoding.clone(encoding);
    newEncoding.hasGeodeticSurfaceNormals = enabled;
    newEncoding = TerrainEncoding.clone(newEncoding);
    const newStride = newEncoding.stride;
    const newVertexBuffer = new Float32Array(vertexCount * newStride);

    if (enabled) {
      encoding.addGeodeticSurfaceNormals(
        vertexBuffer,
        newVertexBuffer,
        ellipsoid
      );
    } else {
      encoding.removeGeodeticSurfaceNormals(vertexBuffer, newVertexBuffer);
    }

    renderedMesh.vertices = newVertexBuffer;
    renderedMesh.stride = newStride;

    // delete the old vertex array (which deletes the vertex buffer attached to it), and create a new vertex array with the new vertex buffer
    const isFill = renderedMesh !== surfaceTile.mesh;
    if (isFill) {
      GlobeSurfaceTile._freeVertexArray(surfaceTile.fill.vertexArray);
      surfaceTile.fill.vertexArray = GlobeSurfaceTile._createVertexArrayForMesh(
        frameState.context,
        renderedMesh
      );
    } else {
      GlobeSurfaceTile._freeVertexArray(surfaceTile.vertexArray);
      surfaceTile.vertexArray = GlobeSurfaceTile._createVertexArrayForMesh(
        frameState.context,
        renderedMesh
      );
    }
    GlobeSurfaceTile._freeVertexArray(surfaceTile.wireframeVertexArray);
    surfaceTile.wireframeVertexArray = undefined;
  }

  GlobeSurfaceTile.prototype.addGeodeticSurfaceNormals = function (
    ellipsoid,
    frameState
  ) {
    toggleGeodeticSurfaceNormals(this, true, ellipsoid, frameState);
  };

  GlobeSurfaceTile.prototype.removeGeodeticSurfaceNormals = function (
    frameState
  ) {
    toggleGeodeticSurfaceNormals(this, false, undefined, frameState);
  };

  GlobeSurfaceTile.prototype.updateExaggeration = function (
    tile,
    frameState,
    quadtree
  ) {
    const surfaceTile = this;
    const mesh = surfaceTile.renderedMesh;
    if (mesh === undefined) {
      return;
    }

    // Check the tile's terrain encoding to see if it has been exaggerated yet
    const exaggeration = frameState.terrainExaggeration;
    const exaggerationRelativeHeight =
      frameState.terrainExaggerationRelativeHeight;
    const hasExaggerationScale = exaggeration !== 1.0;

    const encoding = mesh.encoding;
    const encodingExaggerationScaleChanged =
      encoding.exaggeration !== exaggeration;
    const encodingRelativeHeightChanged =
      encoding.exaggerationRelativeHeight !== exaggerationRelativeHeight;

    if (encodingExaggerationScaleChanged || encodingRelativeHeightChanged) {
      // Turning exaggeration scale on/off requires adding or removing geodetic surface normals
      // Relative height only translates, so it has no effect on normals
      if (encodingExaggerationScaleChanged) {
        if (hasExaggerationScale && !encoding.hasGeodeticSurfaceNormals) {
          const ellipsoid = tile.tilingScheme.ellipsoid;
          surfaceTile.addGeodeticSurfaceNormals(ellipsoid, frameState);
        } else if (!hasExaggerationScale && encoding.hasGeodeticSurfaceNormals) {
          surfaceTile.removeGeodeticSurfaceNormals(frameState);
        }
      }

      encoding.exaggeration = exaggeration;
      encoding.exaggerationRelativeHeight = exaggerationRelativeHeight;

      // Notify the quadtree that this tile's height has changed
      if (quadtree !== undefined) {
        quadtree._tileToUpdateHeights.push(tile);
        const customData = tile.customData;
        const customDataLength = customData.length;
        for (let i = 0; i < customDataLength; i++) {
          // Restart the level so that a height update is triggered
          const data = customData[i];
          data.level = -1;
        }
      }
    }
  };

  function prepareNewTile(tile, terrainProvider, imageryLayerCollection) {
    let available = terrainProvider.getTileDataAvailable(
      tile.x,
      tile.y,
      tile.level
    );

    if (!defined(available) && defined(tile.parent)) {
      // Provider doesn't know if this tile is available. Does the parent tile know?
      const parent = tile.parent;
      const parentSurfaceTile = parent.data;
      if (defined(parentSurfaceTile) && defined(parentSurfaceTile.terrainData)) {
        available = parentSurfaceTile.terrainData.isChildAvailable(
          parent.x,
          parent.y,
          tile.x,
          tile.y
        );
      }
    }

    if (available === false) {
      // This tile is not available, so mark it failed so we start upsampling right away.
      tile.data.terrainState = TerrainState$1.FAILED;
    }

    // Map imagery tiles to this terrain tile
    for (let i = 0, len = imageryLayerCollection.length; i < len; ++i) {
      const layer = imageryLayerCollection.get(i);
      if (layer.show) {
        layer._createTileImagerySkeletons(tile, terrainProvider);
      }
    }
  }

  function processTerrainStateMachine(
    tile,
    frameState,
    terrainProvider,
    imageryLayerCollection,
    quadtree,
    vertexArraysToDestroy
  ) {
    const surfaceTile = tile.data;

    // If this tile is FAILED, we'll need to upsample from the parent. If the parent isn't
    // ready for that, let's push it along.
    const parent = tile.parent;
    if (
      surfaceTile.terrainState === TerrainState$1.FAILED &&
      parent !== undefined
    ) {
      const parentReady =
        parent.data !== undefined &&
        parent.data.terrainData !== undefined &&
        parent.data.terrainData.canUpsample !== false;
      if (!parentReady) {
        GlobeSurfaceTile.processStateMachine(
          parent,
          frameState,
          terrainProvider,
          imageryLayerCollection,
          quadtree,
          vertexArraysToDestroy,
          true
        );
      }
    }

    if (surfaceTile.terrainState === TerrainState$1.FAILED) {
      upsample(
        surfaceTile,
        tile,
        frameState,
        terrainProvider,
        tile.x,
        tile.y,
        tile.level
      );
    }

    if (surfaceTile.terrainState === TerrainState$1.UNLOADED) {
      requestTileGeometry(
        surfaceTile,
        terrainProvider,
        tile.x,
        tile.y,
        tile.level
      );
    }

    if (surfaceTile.terrainState === TerrainState$1.RECEIVED) {
      transform(
        surfaceTile,
        frameState,
        terrainProvider,
        tile.x,
        tile.y,
        tile.level
      );
    }

    if (surfaceTile.terrainState === TerrainState$1.TRANSFORMED) {
      createResources$1(
        surfaceTile,
        frameState.context,
        terrainProvider,
        tile.x,
        tile.y,
        tile.level,
        vertexArraysToDestroy
      );

      // Update the tile's exaggeration in case the globe's exaggeration changed while the tile was being processed
      surfaceTile.updateExaggeration(tile, frameState, quadtree);
    }

    if (
      surfaceTile.terrainState >= TerrainState$1.RECEIVED &&
      surfaceTile.waterMaskTexture === undefined &&
      terrainProvider.hasWaterMask
    ) {
      const terrainData = surfaceTile.terrainData;
      if (terrainData.waterMask !== undefined) {
        createWaterMaskTextureIfNeeded(frameState.context, surfaceTile);
      } else {
        const sourceTile = surfaceTile._findAncestorTileWithTerrainData(tile);
        if (defined(sourceTile) && defined(sourceTile.data.waterMaskTexture)) {
          surfaceTile.waterMaskTexture = sourceTile.data.waterMaskTexture;
          ++surfaceTile.waterMaskTexture.referenceCount;
          surfaceTile._computeWaterMaskTranslationAndScale(
            tile,
            sourceTile,
            surfaceTile.waterMaskTranslationAndScale
          );
        }
      }
    }
  }

  function upsample(surfaceTile, tile, frameState, terrainProvider, x, y, level) {
    const parent = tile.parent;
    if (!parent) {
      // Trying to upsample from a root tile. No can do. This tile is a failure.
      tile.state = QuadtreeTileLoadState$1.FAILED;
      return;
    }

    const sourceData = parent.data.terrainData;
    const sourceX = parent.x;
    const sourceY = parent.y;
    const sourceLevel = parent.level;

    if (!defined(sourceData)) {
      // Parent is not available, so we can't upsample this tile yet.
      return;
    }

    const terrainDataPromise = sourceData.upsample(
      terrainProvider.tilingScheme,
      sourceX,
      sourceY,
      sourceLevel,
      x,
      y,
      level
    );
    if (!defined(terrainDataPromise)) {
      // The upsample request has been deferred - try again later.
      return;
    }

    surfaceTile.terrainState = TerrainState$1.RECEIVING;

    Promise.resolve(terrainDataPromise)
      .then(function (terrainData) {
        surfaceTile.terrainData = terrainData;
        surfaceTile.terrainState = TerrainState$1.RECEIVED;
      })
      .catch(function () {
        surfaceTile.terrainState = TerrainState$1.FAILED;
      });
  }

  function requestTileGeometry(surfaceTile, terrainProvider, x, y, level) {
    function success(terrainData) {
      surfaceTile.terrainData = terrainData;
      surfaceTile.terrainState = TerrainState$1.RECEIVED;
      surfaceTile.request = undefined;
    }

    function failure(error) {
      if (surfaceTile.request.state === RequestState$1.CANCELLED) {
        // Cancelled due to low priority - try again later.
        surfaceTile.terrainData = undefined;
        surfaceTile.terrainState = TerrainState$1.UNLOADED;
        surfaceTile.request = undefined;
        return;
      }

      // Initially assume failure.  handleError may retry, in which case the state will
      // change to RECEIVING or UNLOADED.
      surfaceTile.terrainState = TerrainState$1.FAILED;
      surfaceTile.request = undefined;

      const message = `Failed to obtain terrain tile X: ${x} Y: ${y} Level: ${level}. Error message: "${error}"`;
      terrainProvider._requestError = TileProviderError.handleError(
        terrainProvider._requestError,
        terrainProvider,
        terrainProvider.errorEvent,
        message,
        x,
        y,
        level,
        doRequest
      );
    }

    function doRequest() {
      // Request the terrain from the terrain provider.
      const request = new Request({
        throttle: false,
        throttleByServer: true,
        type: RequestType$1.TERRAIN,
      });
      surfaceTile.request = request;

      const requestPromise = terrainProvider.requestTileGeometry(
        x,
        y,
        level,
        request
      );

      // If the request method returns undefined (instead of a promise), the request
      // has been deferred.
      if (defined(requestPromise)) {
        surfaceTile.terrainState = TerrainState$1.RECEIVING;
        Promise.resolve(requestPromise)
          .then(function (terrainData) {
            success(terrainData);
          })
          .catch(function (e) {
            failure(e);
          });
      } else {
        // Deferred - try again later.
        surfaceTile.terrainState = TerrainState$1.UNLOADED;
        surfaceTile.request = undefined;
      }
    }

    doRequest();
  }

  const scratchCreateMeshOptions = {
    tilingScheme: undefined,
    x: 0,
    y: 0,
    level: 0,
    exaggeration: 1.0,
    exaggerationRelativeHeight: 0.0,
    throttle: true,
  };

  function transform(surfaceTile, frameState, terrainProvider, x, y, level) {
    const tilingScheme = terrainProvider.tilingScheme;

    const createMeshOptions = scratchCreateMeshOptions;
    createMeshOptions.tilingScheme = tilingScheme;
    createMeshOptions.x = x;
    createMeshOptions.y = y;
    createMeshOptions.level = level;
    createMeshOptions.exaggeration = frameState.terrainExaggeration;
    createMeshOptions.exaggerationRelativeHeight =
      frameState.terrainExaggerationRelativeHeight;
    createMeshOptions.throttle = true;

    const terrainData = surfaceTile.terrainData;
    const meshPromise = terrainData.createMesh(createMeshOptions);

    if (!defined(meshPromise)) {
      // Postponed.
      return;
    }

    surfaceTile.terrainState = TerrainState$1.TRANSFORMING;

    Promise.resolve(meshPromise)
      .then(function (mesh) {
        surfaceTile.mesh = mesh;
        surfaceTile.terrainState = TerrainState$1.TRANSFORMED;
      })
      .catch(function () {
        surfaceTile.terrainState = TerrainState$1.FAILED;
      });
  }

  GlobeSurfaceTile._createVertexArrayForMesh = function (context, mesh) {
    const typedArray = mesh.vertices;
    const buffer = Buffer$1.createVertexBuffer({
      context: context,
      typedArray: typedArray,
      usage: BufferUsage$1.STATIC_DRAW,
    });
    const attributes = mesh.encoding.getAttributes(buffer);

    const indexBuffers = mesh.indices.indexBuffers || {};
    let indexBuffer = indexBuffers[context.id];
    if (!defined(indexBuffer) || indexBuffer.isDestroyed()) {
      const indices = mesh.indices;
      indexBuffer = Buffer$1.createIndexBuffer({
        context: context,
        typedArray: indices,
        usage: BufferUsage$1.STATIC_DRAW,
        indexDatatype: IndexDatatype$1.fromSizeInBytes(indices.BYTES_PER_ELEMENT),
      });
      indexBuffer.vertexArrayDestroyable = false;
      indexBuffer.referenceCount = 1;
      indexBuffers[context.id] = indexBuffer;
      mesh.indices.indexBuffers = indexBuffers;
    } else {
      ++indexBuffer.referenceCount;
    }

    return new VertexArray({
      context: context,
      attributes: attributes,
      indexBuffer: indexBuffer,
    });
  };

  GlobeSurfaceTile._freeVertexArray = function (vertexArray) {
    if (defined(vertexArray)) {
      const indexBuffer = vertexArray.indexBuffer;

      if (!vertexArray.isDestroyed()) {
        vertexArray.destroy();
      }

      if (
        defined(indexBuffer) &&
        !indexBuffer.isDestroyed() &&
        defined(indexBuffer.referenceCount)
      ) {
        --indexBuffer.referenceCount;
        if (indexBuffer.referenceCount === 0) {
          indexBuffer.destroy();
        }
      }
    }
  };

  function createResources$1(
    surfaceTile,
    context,
    terrainProvider,
    x,
    y,
    level,
    vertexArraysToDestroy
  ) {
    surfaceTile.vertexArray = GlobeSurfaceTile._createVertexArrayForMesh(
      context,
      surfaceTile.mesh
    );
    surfaceTile.terrainState = TerrainState$1.READY;
    surfaceTile.fill =
      surfaceTile.fill && surfaceTile.fill.destroy(vertexArraysToDestroy);
  }

  function getContextWaterMaskData(context) {
    let data = context.cache.tile_waterMaskData;

    if (!defined(data)) {
      const allWaterTexture = Texture.create({
        context: context,
        pixelFormat: PixelFormat$1.LUMINANCE,
        pixelDatatype: PixelDatatype$1.UNSIGNED_BYTE,
        source: {
          arrayBufferView: new Uint8Array([255]),
          width: 1,
          height: 1,
        },
      });
      allWaterTexture.referenceCount = 1;

      const sampler = new Sampler({
        wrapS: TextureWrap$1.CLAMP_TO_EDGE,
        wrapT: TextureWrap$1.CLAMP_TO_EDGE,
        minificationFilter: TextureMinificationFilter$1.LINEAR,
        magnificationFilter: TextureMagnificationFilter$1.LINEAR,
      });

      data = {
        allWaterTexture: allWaterTexture,
        sampler: sampler,
        destroy: function () {
          this.allWaterTexture.destroy();
        },
      };

      context.cache.tile_waterMaskData = data;
    }

    return data;
  }

  function createWaterMaskTextureIfNeeded(context, surfaceTile) {
    const waterMask = surfaceTile.terrainData.waterMask;
    const waterMaskData = getContextWaterMaskData(context);
    let texture;

    const waterMaskLength = waterMask.length;
    if (waterMaskLength === 1) {
      // Length 1 means the tile is entirely land or entirely water.
      // A value of 0 indicates entirely land, a value of 1 indicates entirely water.
      if (waterMask[0] !== 0) {
        texture = waterMaskData.allWaterTexture;
      } else {
        // Leave the texture undefined if the tile is entirely land.
        return;
      }
    } else {
      const textureSize = Math.sqrt(waterMaskLength);
      texture = Texture.create({
        context: context,
        pixelFormat: PixelFormat$1.LUMINANCE,
        pixelDatatype: PixelDatatype$1.UNSIGNED_BYTE,
        source: {
          width: textureSize,
          height: textureSize,
          arrayBufferView: waterMask,
        },
        sampler: waterMaskData.sampler,
        flipY: false,
      });

      texture.referenceCount = 0;
    }

    ++texture.referenceCount;
    surfaceTile.waterMaskTexture = texture;

    Cartesian4.fromElements(
      0.0,
      0.0,
      1.0,
      1.0,
      surfaceTile.waterMaskTranslationAndScale
    );
  }

  GlobeSurfaceTile.prototype._findAncestorTileWithTerrainData = function (tile) {
    let sourceTile = tile.parent;

    while (
      defined(sourceTile) &&
      (!defined(sourceTile.data) ||
        !defined(sourceTile.data.terrainData) ||
        sourceTile.data.terrainData.wasCreatedByUpsampling())
    ) {
      sourceTile = sourceTile.parent;
    }

    return sourceTile;
  };

  GlobeSurfaceTile.prototype._computeWaterMaskTranslationAndScale = function (
    tile,
    sourceTile,
    result
  ) {
    const sourceTileRectangle = sourceTile.rectangle;
    const tileRectangle = tile.rectangle;
    const tileWidth = tileRectangle.width;
    const tileHeight = tileRectangle.height;

    const scaleX = tileWidth / sourceTileRectangle.width;
    const scaleY = tileHeight / sourceTileRectangle.height;
    result.x =
      (scaleX * (tileRectangle.west - sourceTileRectangle.west)) / tileWidth;
    result.y =
      (scaleY * (tileRectangle.south - sourceTileRectangle.south)) / tileHeight;
    result.z = scaleX;
    result.w = scaleY;

    return result;
  };

  //This file is automatically rebuilt by the Cesium build process.
  var ReprojectWebMercatorFS = "uniform sampler2D u_texture;\n\
varying vec2 v_textureCoordinates;\n\
void main()\n\
{\n\
gl_FragColor = texture2D(u_texture, v_textureCoordinates);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var ReprojectWebMercatorVS = "attribute vec4 position;\n\
attribute float webMercatorT;\n\
uniform vec2 u_textureDimensions;\n\
varying vec2 v_textureCoordinates;\n\
void main()\n\
{\n\
v_textureCoordinates = vec2(position.x, webMercatorT);\n\
gl_Position = czm_viewportOrthographic * (position * vec4(u_textureDimensions, 1.0, 1.0));\n\
}\n\
";

  /**
   * Stores details about a tile of imagery.
   *
   * @alias Imagery
   * @private
   */
  function Imagery(imageryLayer, x, y, level, rectangle) {
    this.imageryLayer = imageryLayer;
    this.x = x;
    this.y = y;
    this.level = level;
    this.request = undefined;

    if (level !== 0) {
      const parentX = (x / 2) | 0;
      const parentY = (y / 2) | 0;
      const parentLevel = level - 1;
      this.parent = imageryLayer.getImageryFromCache(
        parentX,
        parentY,
        parentLevel
      );
    }

    this.state = ImageryState$1.UNLOADED;
    this.imageUrl = undefined;
    this.image = undefined;
    this.texture = undefined;
    this.textureWebMercator = undefined;
    this.credits = undefined;
    this.referenceCount = 0;

    if (!defined(rectangle) && imageryLayer.imageryProvider.ready) {
      const tilingScheme = imageryLayer.imageryProvider.tilingScheme;
      rectangle = tilingScheme.tileXYToRectangle(x, y, level);
    }

    this.rectangle = rectangle;
  }
  Imagery.createPlaceholder = function (imageryLayer) {
    const result = new Imagery(imageryLayer, 0, 0, 0);
    result.addReference();
    result.state = ImageryState$1.PLACEHOLDER;
    return result;
  };

  Imagery.prototype.addReference = function () {
    ++this.referenceCount;
  };

  Imagery.prototype.releaseReference = function () {
    --this.referenceCount;

    if (this.referenceCount === 0) {
      this.imageryLayer.removeImageryFromCache(this);

      if (defined(this.parent)) {
        this.parent.releaseReference();
      }

      if (defined(this.image) && defined(this.image.destroy)) {
        this.image.destroy();
      }

      if (defined(this.texture)) {
        this.texture.destroy();
      }

      if (
        defined(this.textureWebMercator) &&
        this.texture !== this.textureWebMercator
      ) {
        this.textureWebMercator.destroy();
      }

      destroyObject(this);

      return 0;
    }

    return this.referenceCount;
  };

  Imagery.prototype.processStateMachine = function (
    frameState,
    needGeographicProjection,
    skipLoading
  ) {
    if (this.state === ImageryState$1.UNLOADED && !skipLoading) {
      this.state = ImageryState$1.TRANSITIONING;
      this.imageryLayer._requestImagery(this);
    }

    if (this.state === ImageryState$1.RECEIVED) {
      this.state = ImageryState$1.TRANSITIONING;
      this.imageryLayer._createTexture(frameState.context, this);
    }

    // If the imagery is already ready, but we need a geographic version and don't have it yet,
    // we still need to do the reprojection step. This can happen if the Web Mercator version
    // is fine initially, but the geographic one is needed later.
    const needsReprojection =
      this.state === ImageryState$1.READY &&
      needGeographicProjection &&
      !this.texture;

    if (this.state === ImageryState$1.TEXTURE_LOADED || needsReprojection) {
      this.state = ImageryState$1.TRANSITIONING;
      this.imageryLayer._reprojectTexture(
        frameState,
        this,
        needGeographicProjection
      );
    }
  };

  /**
   * The assocation between a terrain tile and an imagery tile.
   *
   * @alias TileImagery
   * @private
   *
   * @param {Imagery} imagery The imagery tile.
   * @param {Cartesian4} textureCoordinateRectangle The texture rectangle of the tile that is covered
   *        by the imagery, where X=west, Y=south, Z=east, W=north.
   * @param {Boolean} useWebMercatorT true to use the Web Mercator texture coordinates for this imagery tile.
   */
  function TileImagery(imagery, textureCoordinateRectangle, useWebMercatorT) {
    this.readyImagery = undefined;
    this.loadingImagery = imagery;
    this.textureCoordinateRectangle = textureCoordinateRectangle;
    this.textureTranslationAndScale = undefined;
    this.useWebMercatorT = useWebMercatorT;
  }

  /**
   * Frees the resources held by this instance.
   */
  TileImagery.prototype.freeResources = function () {
    if (defined(this.readyImagery)) {
      this.readyImagery.releaseReference();
    }

    if (defined(this.loadingImagery)) {
      this.loadingImagery.releaseReference();
    }
  };

  /**
   * Processes the load state machine for this instance.
   *
   * @param {Tile} tile The tile to which this instance belongs.
   * @param {FrameState} frameState The frameState.
   * @param {Boolean} skipLoading True to skip loading, e.g. new requests, creating textures. This function will
   *                  still synchronously process imagery that's already mostly ready to go, e.g. use textures
   *                  already loaded on ancestor tiles.
   * @returns {Boolean} True if this instance is done loading; otherwise, false.
   */
  TileImagery.prototype.processStateMachine = function (
    tile,
    frameState,
    skipLoading
  ) {
    const loadingImagery = this.loadingImagery;
    const imageryLayer = loadingImagery.imageryLayer;

    loadingImagery.processStateMachine(
      frameState,
      !this.useWebMercatorT,
      skipLoading
    );

    if (loadingImagery.state === ImageryState$1.READY) {
      if (defined(this.readyImagery)) {
        this.readyImagery.releaseReference();
      }
      this.readyImagery = this.loadingImagery;
      this.loadingImagery = undefined;
      this.textureTranslationAndScale = imageryLayer._calculateTextureTranslationAndScale(
        tile,
        this
      );
      return true; // done loading
    }

    // Find some ancestor imagery we can use while this imagery is still loading.
    let ancestor = loadingImagery.parent;
    let closestAncestorThatNeedsLoading;
    while (
      defined(ancestor) &&
      (ancestor.state !== ImageryState$1.READY ||
        (!this.useWebMercatorT && !defined(ancestor.texture)))
    ) {
      if (
        ancestor.state !== ImageryState$1.FAILED &&
        ancestor.state !== ImageryState$1.INVALID
      ) {
        // ancestor is still loading
        closestAncestorThatNeedsLoading =
          closestAncestorThatNeedsLoading || ancestor;
      }
      ancestor = ancestor.parent;
    }

    if (this.readyImagery !== ancestor) {
      if (defined(this.readyImagery)) {
        this.readyImagery.releaseReference();
      }

      this.readyImagery = ancestor;

      if (defined(ancestor)) {
        ancestor.addReference();
        this.textureTranslationAndScale = imageryLayer._calculateTextureTranslationAndScale(
          tile,
          this
        );
      }
    }

    if (
      loadingImagery.state === ImageryState$1.FAILED ||
      loadingImagery.state === ImageryState$1.INVALID
    ) {
      // The imagery tile is failed or invalid, so we'd like to use an ancestor instead.
      if (defined(closestAncestorThatNeedsLoading)) {
        // Push the ancestor's load process along a bit.  This is necessary because some ancestor imagery
        // tiles may not be attached directly to a terrain tile.  Such tiles will never load if
        // we don't do it here.
        closestAncestorThatNeedsLoading.processStateMachine(
          frameState,
          !this.useWebMercatorT,
          skipLoading
        );
        return false; // not done loading
      }
      // This imagery tile is failed or invalid, and we have the "best available" substitute.
      return true; // done loading
    }

    return false; // not done loading
  };

  /**
   * An imagery layer that displays tiled image data from a single imagery provider
   * on a {@link Globe}.
   *
   * @alias ImageryLayer
   * @constructor
   *
   * @param {ImageryProvider} imageryProvider The imagery provider to use.
   * @param {Object} [options] Object with the following properties:
   * @param {Rectangle} [options.rectangle=imageryProvider.rectangle] The rectangle of the layer.  This rectangle
   *        can limit the visible portion of the imagery provider.
   * @param {Number|Function} [options.alpha=1.0] The alpha blending value of this layer, from 0.0 to 1.0.
   *                          This can either be a simple number or a function with the signature
   *                          <code>function(frameState, layer, x, y, level)</code>.  The function is passed the
   *                          current frame state, this layer, and the x, y, and level coordinates of the
   *                          imagery tile for which the alpha is required, and it is expected to return
   *                          the alpha value to use for the tile.
   * @param {Number|Function} [options.nightAlpha=1.0] The alpha blending value of this layer on the night side of the globe, from 0.0 to 1.0.
   *                          This can either be a simple number or a function with the signature
   *                          <code>function(frameState, layer, x, y, level)</code>.  The function is passed the
   *                          current frame state, this layer, and the x, y, and level coordinates of the
   *                          imagery tile for which the alpha is required, and it is expected to return
   *                          the alpha value to use for the tile. This only takes effect when <code>enableLighting</code> is <code>true</code>.
   * @param {Number|Function} [options.dayAlpha=1.0] The alpha blending value of this layer on the day side of the globe, from 0.0 to 1.0.
   *                          This can either be a simple number or a function with the signature
   *                          <code>function(frameState, layer, x, y, level)</code>.  The function is passed the
   *                          current frame state, this layer, and the x, y, and level coordinates of the
   *                          imagery tile for which the alpha is required, and it is expected to return
   *                          the alpha value to use for the tile. This only takes effect when <code>enableLighting</code> is <code>true</code>.
   * @param {Number|Function} [options.brightness=1.0] The brightness of this layer.  1.0 uses the unmodified imagery
   *                          color.  Less than 1.0 makes the imagery darker while greater than 1.0 makes it brighter.
   *                          This can either be a simple number or a function with the signature
   *                          <code>function(frameState, layer, x, y, level)</code>.  The function is passed the
   *                          current frame state, this layer, and the x, y, and level coordinates of the
   *                          imagery tile for which the brightness is required, and it is expected to return
   *                          the brightness value to use for the tile.  The function is executed for every
   *                          frame and for every tile, so it must be fast.
   * @param {Number|Function} [options.contrast=1.0] The contrast of this layer.  1.0 uses the unmodified imagery color.
   *                          Less than 1.0 reduces the contrast while greater than 1.0 increases it.
   *                          This can either be a simple number or a function with the signature
   *                          <code>function(frameState, layer, x, y, level)</code>.  The function is passed the
   *                          current frame state, this layer, and the x, y, and level coordinates of the
   *                          imagery tile for which the contrast is required, and it is expected to return
   *                          the contrast value to use for the tile.  The function is executed for every
   *                          frame and for every tile, so it must be fast.
   * @param {Number|Function} [options.hue=0.0] The hue of this layer.  0.0 uses the unmodified imagery color.
   *                          This can either be a simple number or a function with the signature
   *                          <code>function(frameState, layer, x, y, level)</code>.  The function is passed the
   *                          current frame state, this layer, and the x, y, and level coordinates
   *                          of the imagery tile for which the hue is required, and it is expected to return
   *                          the contrast value to use for the tile.  The function is executed for every
   *                          frame and for every tile, so it must be fast.
   * @param {Number|Function} [options.saturation=1.0] The saturation of this layer.  1.0 uses the unmodified imagery color.
   *                          Less than 1.0 reduces the saturation while greater than 1.0 increases it.
   *                          This can either be a simple number or a function with the signature
   *                          <code>function(frameState, layer, x, y, level)</code>.  The function is passed the
   *                          current frame state, this layer, and the x, y, and level coordinates
   *                          of the imagery tile for which the saturation is required, and it is expected to return
   *                          the contrast value to use for the tile.  The function is executed for every
   *                          frame and for every tile, so it must be fast.
   * @param {Number|Function} [options.gamma=1.0] The gamma correction to apply to this layer.  1.0 uses the unmodified imagery color.
   *                          This can either be a simple number or a function with the signature
   *                          <code>function(frameState, layer, x, y, level)</code>.  The function is passed the
   *                          current frame state, this layer, and the x, y, and level coordinates of the
   *                          imagery tile for which the gamma is required, and it is expected to return
   *                          the gamma value to use for the tile.  The function is executed for every
   *                          frame and for every tile, so it must be fast.
   * @param {SplitDirection|Function} [options.splitDirection=SplitDirection.NONE] The {@link SplitDirection} split to apply to this layer.
   * @param {TextureMinificationFilter} [options.minificationFilter=TextureMinificationFilter.LINEAR] The
   *                                    texture minification filter to apply to this layer. Possible values
   *                                    are <code>TextureMinificationFilter.LINEAR</code> and
   *                                    <code>TextureMinificationFilter.NEAREST</code>.
   * @param {TextureMagnificationFilter} [options.magnificationFilter=TextureMagnificationFilter.LINEAR] The
   *                                     texture minification filter to apply to this layer. Possible values
   *                                     are <code>TextureMagnificationFilter.LINEAR</code> and
   *                                     <code>TextureMagnificationFilter.NEAREST</code>.
   * @param {Boolean} [options.show=true] True if the layer is shown; otherwise, false.
   * @param {Number} [options.maximumAnisotropy=maximum supported] The maximum anisotropy level to use
   *        for texture filtering.  If this parameter is not specified, the maximum anisotropy supported
   *        by the WebGL stack will be used.  Larger values make the imagery look better in horizon
   *        views.
   * @param {Number} [options.minimumTerrainLevel] The minimum terrain level-of-detail at which to show this imagery layer,
   *                 or undefined to show it at all levels.  Level zero is the least-detailed level.
   * @param {Number} [options.maximumTerrainLevel] The maximum terrain level-of-detail at which to show this imagery layer,
   *                 or undefined to show it at all levels.  Level zero is the least-detailed level.
   * @param {Rectangle} [options.cutoutRectangle] Cartographic rectangle for cutting out a portion of this ImageryLayer.
   * @param {Color} [options.colorToAlpha] Color to be used as alpha.
   * @param {Number} [options.colorToAlphaThreshold=0.004] Threshold for color-to-alpha.
   */
  function ImageryLayer(imageryProvider, options) {
    this._imageryProvider = imageryProvider;

    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    /**
     * The alpha blending value of this layer, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number}
     * @default 1.0
     */
    this.alpha = defaultValue(
      options.alpha,
      defaultValue(imageryProvider.defaultAlpha, 1.0)
    );

    /**
     * The alpha blending value of this layer on the night side of the globe, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque. This only takes effect when {@link Globe#enableLighting} is <code>true</code>.
     *
     * @type {Number}
     * @default 1.0
     */
    this.nightAlpha = defaultValue(
      options.nightAlpha,
      defaultValue(imageryProvider.defaultNightAlpha, 1.0)
    );

    /**
     * The alpha blending value of this layer on the day side of the globe, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque. This only takes effect when {@link Globe#enableLighting} is <code>true</code>.
     *
     * @type {Number}
     * @default 1.0
     */
    this.dayAlpha = defaultValue(
      options.dayAlpha,
      defaultValue(imageryProvider.defaultDayAlpha, 1.0)
    );

    /**
     * The brightness of this layer.  1.0 uses the unmodified imagery color.  Less than 1.0
     * makes the imagery darker while greater than 1.0 makes it brighter.
     *
     * @type {Number}
     * @default {@link ImageryLayer.DEFAULT_BRIGHTNESS}
     */
    this.brightness = defaultValue(
      options.brightness,
      defaultValue(
        imageryProvider.defaultBrightness,
        ImageryLayer.DEFAULT_BRIGHTNESS
      )
    );

    /**
     * The contrast of this layer.  1.0 uses the unmodified imagery color.  Less than 1.0 reduces
     * the contrast while greater than 1.0 increases it.
     *
     * @type {Number}
     * @default {@link ImageryLayer.DEFAULT_CONTRAST}
     */
    this.contrast = defaultValue(
      options.contrast,
      defaultValue(imageryProvider.defaultContrast, ImageryLayer.DEFAULT_CONTRAST)
    );

    /**
     * The hue of this layer in radians. 0.0 uses the unmodified imagery color.
     *
     * @type {Number}
     * @default {@link ImageryLayer.DEFAULT_HUE}
     */
    this.hue = defaultValue(
      options.hue,
      defaultValue(imageryProvider.defaultHue, ImageryLayer.DEFAULT_HUE)
    );

    /**
     * The saturation of this layer. 1.0 uses the unmodified imagery color. Less than 1.0 reduces the
     * saturation while greater than 1.0 increases it.
     *
     * @type {Number}
     * @default {@link ImageryLayer.DEFAULT_SATURATION}
     */
    this.saturation = defaultValue(
      options.saturation,
      defaultValue(
        imageryProvider.defaultSaturation,
        ImageryLayer.DEFAULT_SATURATION
      )
    );

    /**
     * The gamma correction to apply to this layer.  1.0 uses the unmodified imagery color.
     *
     * @type {Number}
     * @default {@link ImageryLayer.DEFAULT_GAMMA}
     */
    this.gamma = defaultValue(
      options.gamma,
      defaultValue(imageryProvider.defaultGamma, ImageryLayer.DEFAULT_GAMMA)
    );

    /**
     * The {@link SplitDirection} to apply to this layer.
     *
     * @type {SplitDirection}
     * @default {@link ImageryLayer.DEFAULT_SPLIT}
     */
    this.splitDirection = defaultValue(
      options.splitDirection,
      defaultValue(imageryProvider.defaultSplit, ImageryLayer.DEFAULT_SPLIT)
    );

    /**
     * The {@link TextureMinificationFilter} to apply to this layer.
     * Possible values are {@link TextureMinificationFilter.LINEAR} (the default)
     * and {@link TextureMinificationFilter.NEAREST}.
     *
     * To take effect, this property must be set immediately after adding the imagery layer.
     * Once a texture is loaded it won't be possible to change the texture filter used.
     *
     * @type {TextureMinificationFilter}
     * @default {@link ImageryLayer.DEFAULT_MINIFICATION_FILTER}
     */
    this.minificationFilter = defaultValue(
      options.minificationFilter,
      defaultValue(
        imageryProvider.defaultMinificationFilter,
        ImageryLayer.DEFAULT_MINIFICATION_FILTER
      )
    );

    /**
     * The {@link TextureMagnificationFilter} to apply to this layer.
     * Possible values are {@link TextureMagnificationFilter.LINEAR} (the default)
     * and {@link TextureMagnificationFilter.NEAREST}.
     *
     * To take effect, this property must be set immediately after adding the imagery layer.
     * Once a texture is loaded it won't be possible to change the texture filter used.
     *
     * @type {TextureMagnificationFilter}
     * @default {@link ImageryLayer.DEFAULT_MAGNIFICATION_FILTER}
     */
    this.magnificationFilter = defaultValue(
      options.magnificationFilter,
      defaultValue(
        imageryProvider.defaultMagnificationFilter,
        ImageryLayer.DEFAULT_MAGNIFICATION_FILTER
      )
    );

    /**
     * Determines if this layer is shown.
     *
     * @type {Boolean}
     * @default true
     */
    this.show = defaultValue(options.show, true);

    this._minimumTerrainLevel = options.minimumTerrainLevel;
    this._maximumTerrainLevel = options.maximumTerrainLevel;

    this._rectangle = defaultValue(options.rectangle, Rectangle.MAX_VALUE);
    this._maximumAnisotropy = options.maximumAnisotropy;

    this._imageryCache = {};

    this._skeletonPlaceholder = new TileImagery(Imagery.createPlaceholder(this));

    // The value of the show property on the last update.
    this._show = true;

    // The index of this layer in the ImageryLayerCollection.
    this._layerIndex = -1;

    // true if this is the base (lowest shown) layer.
    this._isBaseLayer = false;

    this._requestImageError = undefined;

    this._reprojectComputeCommands = [];

    /**
     * Rectangle cutout in this layer of imagery.
     *
     * @type {Rectangle}
     */
    this.cutoutRectangle = options.cutoutRectangle;

    /**
     * Color value that should be set to transparent.
     *
     * @type {Color}
     */
    this.colorToAlpha = options.colorToAlpha;

    /**
     * Normalized (0-1) threshold for color-to-alpha.
     *
     * @type {Number}
     */
    this.colorToAlphaThreshold = defaultValue(
      options.colorToAlphaThreshold,
      ImageryLayer.DEFAULT_APPLY_COLOR_TO_ALPHA_THRESHOLD
    );
  }

  Object.defineProperties(ImageryLayer.prototype, {
    /**
     * Gets the imagery provider for this layer.
     * @memberof ImageryLayer.prototype
     * @type {ImageryProvider}
     * @readonly
     */
    imageryProvider: {
      get: function () {
        return this._imageryProvider;
      },
    },

    /**
     * Gets the rectangle of this layer.  If this rectangle is smaller than the rectangle of the
     * {@link ImageryProvider}, only a portion of the imagery provider is shown.
     * @memberof ImageryLayer.prototype
     * @type {Rectangle}
     * @readonly
     */
    rectangle: {
      get: function () {
        return this._rectangle;
      },
    },
  });

  /**
   * This value is used as the default brightness for the imagery layer if one is not provided during construction
   * or by the imagery provider. This value does not modify the brightness of the imagery.
   * @type {Number}
   * @default 1.0
   */
  ImageryLayer.DEFAULT_BRIGHTNESS = 1.0;
  /**
   * This value is used as the default contrast for the imagery layer if one is not provided during construction
   * or by the imagery provider. This value does not modify the contrast of the imagery.
   * @type {Number}
   * @default 1.0
   */
  ImageryLayer.DEFAULT_CONTRAST = 1.0;
  /**
   * This value is used as the default hue for the imagery layer if one is not provided during construction
   * or by the imagery provider. This value does not modify the hue of the imagery.
   * @type {Number}
   * @default 0.0
   */
  ImageryLayer.DEFAULT_HUE = 0.0;
  /**
   * This value is used as the default saturation for the imagery layer if one is not provided during construction
   * or by the imagery provider. This value does not modify the saturation of the imagery.
   * @type {Number}
   * @default 1.0
   */
  ImageryLayer.DEFAULT_SATURATION = 1.0;
  /**
   * This value is used as the default gamma for the imagery layer if one is not provided during construction
   * or by the imagery provider. This value does not modify the gamma of the imagery.
   * @type {Number}
   * @default 1.0
   */
  ImageryLayer.DEFAULT_GAMMA = 1.0;

  /**
   * This value is used as the default split for the imagery layer if one is not provided during construction
   * or by the imagery provider.
   * @type {SplitDirection}
   * @default SplitDirection.NONE
   */
  ImageryLayer.DEFAULT_SPLIT = SplitDirection$1.NONE;

  /**
   * This value is used as the default texture minification filter for the imagery layer if one is not provided
   * during construction or by the imagery provider.
   * @type {TextureMinificationFilter}
   * @default TextureMinificationFilter.LINEAR
   */
  ImageryLayer.DEFAULT_MINIFICATION_FILTER = TextureMinificationFilter$1.LINEAR;

  /**
   * This value is used as the default texture magnification filter for the imagery layer if one is not provided
   * during construction or by the imagery provider.
   * @type {TextureMagnificationFilter}
   * @default TextureMagnificationFilter.LINEAR
   */
  ImageryLayer.DEFAULT_MAGNIFICATION_FILTER = TextureMagnificationFilter$1.LINEAR;

  /**
   * This value is used as the default threshold for color-to-alpha if one is not provided
   * during construction or by the imagery provider.
   * @type {Number}
   * @default 0.004
   */
  ImageryLayer.DEFAULT_APPLY_COLOR_TO_ALPHA_THRESHOLD = 0.004;

  /**
   * Gets a value indicating whether this layer is the base layer in the
   * {@link ImageryLayerCollection}.  The base layer is the one that underlies all
   * others.  It is special in that it is treated as if it has global rectangle, even if
   * it actually does not, by stretching the texels at the edges over the entire
   * globe.
   *
   * @returns {Boolean} true if this is the base layer; otherwise, false.
   */
  ImageryLayer.prototype.isBaseLayer = function () {
    return this._isBaseLayer;
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} True if this object was destroyed; otherwise, false.
   *
   * @see ImageryLayer#destroy
   */
  ImageryLayer.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * imageryLayer = imageryLayer && imageryLayer.destroy();
   *
   * @see ImageryLayer#isDestroyed
   */
  ImageryLayer.prototype.destroy = function () {
    return destroyObject(this);
  };

  const imageryBoundsScratch = new Rectangle();
  const tileImageryBoundsScratch = new Rectangle();
  const clippedRectangleScratch = new Rectangle();
  const terrainRectangleScratch = new Rectangle();

  /**
   * Computes the intersection of this layer's rectangle with the imagery provider's availability rectangle,
   * producing the overall bounds of imagery that can be produced by this layer.
   *
   * @returns {Promise.<Rectangle>} A promise to a rectangle which defines the overall bounds of imagery that can be produced by this layer.
   *
   * @example
   * // Zoom to an imagery layer.
   * imageryLayer.getViewableRectangle().then(function (rectangle) {
   *     return camera.flyTo({
   *         destination: rectangle
   *     });
   * });
   */
  ImageryLayer.prototype.getViewableRectangle = function () {
    const imageryProvider = this._imageryProvider;
    const rectangle = this._rectangle;
    return imageryProvider.readyPromise.then(function () {
      return Rectangle.intersection(imageryProvider.rectangle, rectangle);
    });
  };

  /**
   * Create skeletons for the imagery tiles that partially or completely overlap a given terrain
   * tile.
   *
   * @private
   *
   * @param {Tile} tile The terrain tile.
   * @param {TerrainProvider} terrainProvider The terrain provider associated with the terrain tile.
   * @param {Number} insertionPoint The position to insert new skeletons before in the tile's imagery list.
   * @returns {Boolean} true if this layer overlaps any portion of the terrain tile; otherwise, false.
   */
  ImageryLayer.prototype._createTileImagerySkeletons = function (
    tile,
    terrainProvider,
    insertionPoint
  ) {
    const surfaceTile = tile.data;

    if (
      defined(this._minimumTerrainLevel) &&
      tile.level < this._minimumTerrainLevel
    ) {
      return false;
    }
    if (
      defined(this._maximumTerrainLevel) &&
      tile.level > this._maximumTerrainLevel
    ) {
      return false;
    }

    const imageryProvider = this._imageryProvider;

    if (!defined(insertionPoint)) {
      insertionPoint = surfaceTile.imagery.length;
    }

    if (!imageryProvider.ready) {
      // The imagery provider is not ready, so we can't create skeletons, yet.
      // Instead, add a placeholder so that we'll know to create
      // the skeletons once the provider is ready.
      this._skeletonPlaceholder.loadingImagery.addReference();
      surfaceTile.imagery.splice(insertionPoint, 0, this._skeletonPlaceholder);
      return true;
    }

    // Use Web Mercator for our texture coordinate computations if this imagery layer uses
    // that projection and the terrain tile falls entirely inside the valid bounds of the
    // projection.
    const useWebMercatorT =
      imageryProvider.tilingScheme.projection instanceof WebMercatorProjection &&
      tile.rectangle.north < WebMercatorProjection.MaximumLatitude &&
      tile.rectangle.south > -WebMercatorProjection.MaximumLatitude;

    // Compute the rectangle of the imagery from this imageryProvider that overlaps
    // the geometry tile.  The ImageryProvider and ImageryLayer both have the
    // opportunity to constrain the rectangle.  The imagery TilingScheme's rectangle
    // always fully contains the ImageryProvider's rectangle.
    const imageryBounds = Rectangle.intersection(
      imageryProvider.rectangle,
      this._rectangle,
      imageryBoundsScratch
    );
    let rectangle = Rectangle.intersection(
      tile.rectangle,
      imageryBounds,
      tileImageryBoundsScratch
    );

    if (!defined(rectangle)) {
      // There is no overlap between this terrain tile and this imagery
      // provider.  Unless this is the base layer, no skeletons need to be created.
      // We stretch texels at the edge of the base layer over the entire globe.
      if (!this.isBaseLayer()) {
        return false;
      }

      const baseImageryRectangle = imageryBounds;
      const baseTerrainRectangle = tile.rectangle;
      rectangle = tileImageryBoundsScratch;

      if (baseTerrainRectangle.south >= baseImageryRectangle.north) {
        rectangle.north = rectangle.south = baseImageryRectangle.north;
      } else if (baseTerrainRectangle.north <= baseImageryRectangle.south) {
        rectangle.north = rectangle.south = baseImageryRectangle.south;
      } else {
        rectangle.south = Math.max(
          baseTerrainRectangle.south,
          baseImageryRectangle.south
        );
        rectangle.north = Math.min(
          baseTerrainRectangle.north,
          baseImageryRectangle.north
        );
      }

      if (baseTerrainRectangle.west >= baseImageryRectangle.east) {
        rectangle.west = rectangle.east = baseImageryRectangle.east;
      } else if (baseTerrainRectangle.east <= baseImageryRectangle.west) {
        rectangle.west = rectangle.east = baseImageryRectangle.west;
      } else {
        rectangle.west = Math.max(
          baseTerrainRectangle.west,
          baseImageryRectangle.west
        );
        rectangle.east = Math.min(
          baseTerrainRectangle.east,
          baseImageryRectangle.east
        );
      }
    }

    let latitudeClosestToEquator = 0.0;
    if (rectangle.south > 0.0) {
      latitudeClosestToEquator = rectangle.south;
    } else if (rectangle.north < 0.0) {
      latitudeClosestToEquator = rectangle.north;
    }

    // Compute the required level in the imagery tiling scheme.
    // The errorRatio should really be imagerySSE / terrainSSE rather than this hard-coded value.
    // But first we need configurable imagery SSE and we need the rendering to be able to handle more
    // images attached to a terrain tile than there are available texture units.  So that's for the future.
    const errorRatio = 1.0;
    const targetGeometricError =
      errorRatio * terrainProvider.getLevelMaximumGeometricError(tile.level);
    let imageryLevel = getLevelWithMaximumTexelSpacing(
      this,
      targetGeometricError,
      latitudeClosestToEquator
    );
    imageryLevel = Math.max(0, imageryLevel);
    const maximumLevel = imageryProvider.maximumLevel;
    if (imageryLevel > maximumLevel) {
      imageryLevel = maximumLevel;
    }

    if (defined(imageryProvider.minimumLevel)) {
      const minimumLevel = imageryProvider.minimumLevel;
      if (imageryLevel < minimumLevel) {
        imageryLevel = minimumLevel;
      }
    }

    const imageryTilingScheme = imageryProvider.tilingScheme;
    const northwestTileCoordinates = imageryTilingScheme.positionToTileXY(
      Rectangle.northwest(rectangle),
      imageryLevel
    );
    const southeastTileCoordinates = imageryTilingScheme.positionToTileXY(
      Rectangle.southeast(rectangle),
      imageryLevel
    );

    // If the southeast corner of the rectangle lies very close to the north or west side
    // of the southeast tile, we don't actually need the southernmost or easternmost
    // tiles.
    // Similarly, if the northwest corner of the rectangle lies very close to the south or east side
    // of the northwest tile, we don't actually need the northernmost or westernmost tiles.

    // We define "very close" as being within 1/512 of the width of the tile.
    let veryCloseX = tile.rectangle.width / 512.0;
    let veryCloseY = tile.rectangle.height / 512.0;

    const northwestTileRectangle = imageryTilingScheme.tileXYToRectangle(
      northwestTileCoordinates.x,
      northwestTileCoordinates.y,
      imageryLevel
    );
    if (
      Math.abs(northwestTileRectangle.south - tile.rectangle.north) <
        veryCloseY &&
      northwestTileCoordinates.y < southeastTileCoordinates.y
    ) {
      ++northwestTileCoordinates.y;
    }
    if (
      Math.abs(northwestTileRectangle.east - tile.rectangle.west) < veryCloseX &&
      northwestTileCoordinates.x < southeastTileCoordinates.x
    ) {
      ++northwestTileCoordinates.x;
    }

    const southeastTileRectangle = imageryTilingScheme.tileXYToRectangle(
      southeastTileCoordinates.x,
      southeastTileCoordinates.y,
      imageryLevel
    );
    if (
      Math.abs(southeastTileRectangle.north - tile.rectangle.south) <
        veryCloseY &&
      southeastTileCoordinates.y > northwestTileCoordinates.y
    ) {
      --southeastTileCoordinates.y;
    }
    if (
      Math.abs(southeastTileRectangle.west - tile.rectangle.east) < veryCloseX &&
      southeastTileCoordinates.x > northwestTileCoordinates.x
    ) {
      --southeastTileCoordinates.x;
    }

    // Create TileImagery instances for each imagery tile overlapping this terrain tile.
    // We need to do all texture coordinate computations in the imagery tile's tiling scheme.

    const terrainRectangle = Rectangle.clone(
      tile.rectangle,
      terrainRectangleScratch
    );
    let imageryRectangle = imageryTilingScheme.tileXYToRectangle(
      northwestTileCoordinates.x,
      northwestTileCoordinates.y,
      imageryLevel
    );
    let clippedImageryRectangle = Rectangle.intersection(
      imageryRectangle,
      imageryBounds,
      clippedRectangleScratch
    );

    let imageryTileXYToRectangle;
    if (useWebMercatorT) {
      imageryTilingScheme.rectangleToNativeRectangle(
        terrainRectangle,
        terrainRectangle
      );
      imageryTilingScheme.rectangleToNativeRectangle(
        imageryRectangle,
        imageryRectangle
      );
      imageryTilingScheme.rectangleToNativeRectangle(
        clippedImageryRectangle,
        clippedImageryRectangle
      );
      imageryTilingScheme.rectangleToNativeRectangle(
        imageryBounds,
        imageryBounds
      );
      imageryTileXYToRectangle = imageryTilingScheme.tileXYToNativeRectangle.bind(
        imageryTilingScheme
      );
      veryCloseX = terrainRectangle.width / 512.0;
      veryCloseY = terrainRectangle.height / 512.0;
    } else {
      imageryTileXYToRectangle = imageryTilingScheme.tileXYToRectangle.bind(
        imageryTilingScheme
      );
    }

    let minU;
    let maxU = 0.0;

    let minV = 1.0;
    let maxV;

    // If this is the northern-most or western-most tile in the imagery tiling scheme,
    // it may not start at the northern or western edge of the terrain tile.
    // Calculate where it does start.
    if (
      !this.isBaseLayer() &&
      Math.abs(clippedImageryRectangle.west - terrainRectangle.west) >= veryCloseX
    ) {
      maxU = Math.min(
        1.0,
        (clippedImageryRectangle.west - terrainRectangle.west) /
          terrainRectangle.width
      );
    }

    if (
      !this.isBaseLayer() &&
      Math.abs(clippedImageryRectangle.north - terrainRectangle.north) >=
        veryCloseY
    ) {
      minV = Math.max(
        0.0,
        (clippedImageryRectangle.north - terrainRectangle.south) /
          terrainRectangle.height
      );
    }

    const initialMinV = minV;

    for (
      let i = northwestTileCoordinates.x;
      i <= southeastTileCoordinates.x;
      i++
    ) {
      minU = maxU;

      imageryRectangle = imageryTileXYToRectangle(
        i,
        northwestTileCoordinates.y,
        imageryLevel
      );
      clippedImageryRectangle = Rectangle.simpleIntersection(
        imageryRectangle,
        imageryBounds,
        clippedRectangleScratch
      );

      if (!defined(clippedImageryRectangle)) {
        continue;
      }

      maxU = Math.min(
        1.0,
        (clippedImageryRectangle.east - terrainRectangle.west) /
          terrainRectangle.width
      );

      // If this is the eastern-most imagery tile mapped to this terrain tile,
      // and there are more imagery tiles to the east of this one, the maxU
      // should be 1.0 to make sure rounding errors don't make the last
      // image fall shy of the edge of the terrain tile.
      if (
        i === southeastTileCoordinates.x &&
        (this.isBaseLayer() ||
          Math.abs(clippedImageryRectangle.east - terrainRectangle.east) <
            veryCloseX)
      ) {
        maxU = 1.0;
      }

      minV = initialMinV;

      for (
        let j = northwestTileCoordinates.y;
        j <= southeastTileCoordinates.y;
        j++
      ) {
        maxV = minV;

        imageryRectangle = imageryTileXYToRectangle(i, j, imageryLevel);
        clippedImageryRectangle = Rectangle.simpleIntersection(
          imageryRectangle,
          imageryBounds,
          clippedRectangleScratch
        );

        if (!defined(clippedImageryRectangle)) {
          continue;
        }

        minV = Math.max(
          0.0,
          (clippedImageryRectangle.south - terrainRectangle.south) /
            terrainRectangle.height
        );

        // If this is the southern-most imagery tile mapped to this terrain tile,
        // and there are more imagery tiles to the south of this one, the minV
        // should be 0.0 to make sure rounding errors don't make the last
        // image fall shy of the edge of the terrain tile.
        if (
          j === southeastTileCoordinates.y &&
          (this.isBaseLayer() ||
            Math.abs(clippedImageryRectangle.south - terrainRectangle.south) <
              veryCloseY)
        ) {
          minV = 0.0;
        }

        const texCoordsRectangle = new Cartesian4(minU, minV, maxU, maxV);
        const imagery = this.getImageryFromCache(i, j, imageryLevel);
        surfaceTile.imagery.splice(
          insertionPoint,
          0,
          new TileImagery(imagery, texCoordsRectangle, useWebMercatorT)
        );
        ++insertionPoint;
      }
    }

    return true;
  };

  /**
   * Calculate the translation and scale for a particular {@link TileImagery} attached to a
   * particular terrain tile.
   *
   * @private
   *
   * @param {Tile} tile The terrain tile.
   * @param {TileImagery} tileImagery The imagery tile mapping.
   * @returns {Cartesian4} The translation and scale where X and Y are the translation and Z and W
   *          are the scale.
   */
  ImageryLayer.prototype._calculateTextureTranslationAndScale = function (
    tile,
    tileImagery
  ) {
    let imageryRectangle = tileImagery.readyImagery.rectangle;
    let terrainRectangle = tile.rectangle;

    if (tileImagery.useWebMercatorT) {
      const tilingScheme =
        tileImagery.readyImagery.imageryLayer.imageryProvider.tilingScheme;
      imageryRectangle = tilingScheme.rectangleToNativeRectangle(
        imageryRectangle,
        imageryBoundsScratch
      );
      terrainRectangle = tilingScheme.rectangleToNativeRectangle(
        terrainRectangle,
        terrainRectangleScratch
      );
    }

    const terrainWidth = terrainRectangle.width;
    const terrainHeight = terrainRectangle.height;

    const scaleX = terrainWidth / imageryRectangle.width;
    const scaleY = terrainHeight / imageryRectangle.height;
    return new Cartesian4(
      (scaleX * (terrainRectangle.west - imageryRectangle.west)) / terrainWidth,
      (scaleY * (terrainRectangle.south - imageryRectangle.south)) /
        terrainHeight,
      scaleX,
      scaleY
    );
  };

  /**
   * Request a particular piece of imagery from the imagery provider.  This method handles raising an
   * error event if the request fails, and retrying the request if necessary.
   *
   * @private
   *
   * @param {Imagery} imagery The imagery to request.
   */
  ImageryLayer.prototype._requestImagery = function (imagery) {
    const imageryProvider = this._imageryProvider;

    const that = this;

    function success(image) {
      if (!defined(image)) {
        return failure();
      }

      imagery.image = image;
      imagery.state = ImageryState$1.RECEIVED;
      imagery.request = undefined;

      TileProviderError.handleSuccess(that._requestImageError);
    }

    function failure(e) {
      if (imagery.request.state === RequestState$1.CANCELLED) {
        // Cancelled due to low priority - try again later.
        imagery.state = ImageryState$1.UNLOADED;
        imagery.request = undefined;
        return;
      }

      // Initially assume failure.  handleError may retry, in which case the state will
      // change to TRANSITIONING.
      imagery.state = ImageryState$1.FAILED;
      imagery.request = undefined;

      const message = `Failed to obtain image tile X: ${imagery.x} Y: ${imagery.y} Level: ${imagery.level}.`;
      that._requestImageError = TileProviderError.handleError(
        that._requestImageError,
        imageryProvider,
        imageryProvider.errorEvent,
        message,
        imagery.x,
        imagery.y,
        imagery.level,
        doRequest,
        e
      );
    }

    function doRequest() {
      const request = new Request({
        throttle: false,
        throttleByServer: true,
        type: RequestType$1.IMAGERY,
      });
      imagery.request = request;
      imagery.state = ImageryState$1.TRANSITIONING;
      const imagePromise = imageryProvider.requestImage(
        imagery.x,
        imagery.y,
        imagery.level,
        request
      );

      if (!defined(imagePromise)) {
        // Too many parallel requests, so postpone loading tile.
        imagery.state = ImageryState$1.UNLOADED;
        imagery.request = undefined;
        return;
      }

      if (defined(imageryProvider.getTileCredits)) {
        imagery.credits = imageryProvider.getTileCredits(
          imagery.x,
          imagery.y,
          imagery.level
        );
      }

      imagePromise
        .then(function (image) {
          success(image);
        })
        .catch(function (e) {
          failure(e);
        });
    }

    doRequest();
  };

  ImageryLayer.prototype._createTextureWebGL = function (context, imagery) {
    const sampler = new Sampler({
      minificationFilter: this.minificationFilter,
      magnificationFilter: this.magnificationFilter,
    });

    const image = imagery.image;

    if (defined(image.internalFormat)) {
      return new Texture({
        context: context,
        pixelFormat: image.internalFormat,
        width: image.width,
        height: image.height,
        source: {
          arrayBufferView: image.bufferView,
        },
        sampler: sampler,
      });
    }
    return new Texture({
      context: context,
      source: image,
      pixelFormat: this._imageryProvider.hasAlphaChannel
        ? PixelFormat$1.RGBA
        : PixelFormat$1.RGB,
      sampler: sampler,
    });
  };

  /**
   * Create a WebGL texture for a given {@link Imagery} instance.
   *
   * @private
   *
   * @param {Context} context The rendered context to use to create textures.
   * @param {Imagery} imagery The imagery for which to create a texture.
   */
  ImageryLayer.prototype._createTexture = function (context, imagery) {
    const imageryProvider = this._imageryProvider;
    const image = imagery.image;

    // If this imagery provider has a discard policy, use it to check if this
    // image should be discarded.
    if (defined(imageryProvider.tileDiscardPolicy)) {
      const discardPolicy = imageryProvider.tileDiscardPolicy;
      if (defined(discardPolicy)) {
        // If the discard policy is not ready yet, transition back to the
        // RECEIVED state and we'll try again next time.
        if (!discardPolicy.isReady()) {
          imagery.state = ImageryState$1.RECEIVED;
          return;
        }

        // Mark discarded imagery tiles invalid.  Parent imagery will be used instead.
        if (discardPolicy.shouldDiscardImage(image)) {
          imagery.state = ImageryState$1.INVALID;
          return;
        }
      }
    }

    //>>includeStart('debug', pragmas.debug);
    if (
      this.minificationFilter !== TextureMinificationFilter$1.NEAREST &&
      this.minificationFilter !== TextureMinificationFilter$1.LINEAR
    ) {
      throw new DeveloperError(
        "ImageryLayer minification filter must be NEAREST or LINEAR"
      );
    }
    //>>includeEnd('debug');

    // Imagery does not need to be discarded, so upload it to WebGL.
    const texture = this._createTextureWebGL(context, imagery);

    if (
      imageryProvider.tilingScheme.projection instanceof WebMercatorProjection
    ) {
      imagery.textureWebMercator = texture;
    } else {
      imagery.texture = texture;
    }
    imagery.image = undefined;
    imagery.state = ImageryState$1.TEXTURE_LOADED;
  };

  function getSamplerKey(
    minificationFilter,
    magnificationFilter,
    maximumAnisotropy
  ) {
    return `${minificationFilter}:${magnificationFilter}:${maximumAnisotropy}`;
  }

  ImageryLayer.prototype._finalizeReprojectTexture = function (context, texture) {
    let minificationFilter = this.minificationFilter;
    const magnificationFilter = this.magnificationFilter;
    const usesLinearTextureFilter =
      minificationFilter === TextureMinificationFilter$1.LINEAR &&
      magnificationFilter === TextureMagnificationFilter$1.LINEAR;
    // Use mipmaps if this texture has power-of-two dimensions.
    // In addition, mipmaps are only generated if the texture filters are both LINEAR.
    if (
      usesLinearTextureFilter &&
      !PixelFormat$1.isCompressedFormat(texture.pixelFormat) &&
      CesiumMath.isPowerOfTwo(texture.width) &&
      CesiumMath.isPowerOfTwo(texture.height)
    ) {
      minificationFilter = TextureMinificationFilter$1.LINEAR_MIPMAP_LINEAR;
      const maximumSupportedAnisotropy =
        ContextLimits.maximumTextureFilterAnisotropy;
      const maximumAnisotropy = Math.min(
        maximumSupportedAnisotropy,
        defaultValue(this._maximumAnisotropy, maximumSupportedAnisotropy)
      );
      const mipmapSamplerKey = getSamplerKey(
        minificationFilter,
        magnificationFilter,
        maximumAnisotropy
      );
      let mipmapSamplers = context.cache.imageryLayerMipmapSamplers;
      if (!defined(mipmapSamplers)) {
        mipmapSamplers = {};
        context.cache.imageryLayerMipmapSamplers = mipmapSamplers;
      }
      let mipmapSampler = mipmapSamplers[mipmapSamplerKey];
      if (!defined(mipmapSampler)) {
        mipmapSampler = mipmapSamplers[mipmapSamplerKey] = new Sampler({
          wrapS: TextureWrap$1.CLAMP_TO_EDGE,
          wrapT: TextureWrap$1.CLAMP_TO_EDGE,
          minificationFilter: minificationFilter,
          magnificationFilter: magnificationFilter,
          maximumAnisotropy: maximumAnisotropy,
        });
      }
      texture.generateMipmap(MipmapHint$1.NICEST);
      texture.sampler = mipmapSampler;
    } else {
      const nonMipmapSamplerKey = getSamplerKey(
        minificationFilter,
        magnificationFilter,
        0
      );
      let nonMipmapSamplers = context.cache.imageryLayerNonMipmapSamplers;
      if (!defined(nonMipmapSamplers)) {
        nonMipmapSamplers = {};
        context.cache.imageryLayerNonMipmapSamplers = nonMipmapSamplers;
      }
      let nonMipmapSampler = nonMipmapSamplers[nonMipmapSamplerKey];
      if (!defined(nonMipmapSampler)) {
        nonMipmapSampler = nonMipmapSamplers[nonMipmapSamplerKey] = new Sampler({
          wrapS: TextureWrap$1.CLAMP_TO_EDGE,
          wrapT: TextureWrap$1.CLAMP_TO_EDGE,
          minificationFilter: minificationFilter,
          magnificationFilter: magnificationFilter,
        });
      }
      texture.sampler = nonMipmapSampler;
    }
  };

  /**
   * Enqueues a command re-projecting a texture to a {@link GeographicProjection} on the next update, if necessary, and generate
   * mipmaps for the geographic texture.
   *
   * @private
   *
   * @param {FrameState} frameState The frameState.
   * @param {Imagery} imagery The imagery instance to reproject.
   * @param {Boolean} [needGeographicProjection=true] True to reproject to geographic, or false if Web Mercator is fine.
   */
  ImageryLayer.prototype._reprojectTexture = function (
    frameState,
    imagery,
    needGeographicProjection
  ) {
    const texture = imagery.textureWebMercator || imagery.texture;
    const rectangle = imagery.rectangle;
    const context = frameState.context;

    needGeographicProjection = defaultValue(needGeographicProjection, true);

    // Reproject this texture if it is not already in a geographic projection and
    // the pixels are more than 1e-5 radians apart.  The pixel spacing cutoff
    // avoids precision problems in the reprojection transformation while making
    // no noticeable difference in the georeferencing of the image.
    if (
      needGeographicProjection &&
      !(
        this._imageryProvider.tilingScheme.projection instanceof
        GeographicProjection
      ) &&
      rectangle.width / texture.width > 1e-5
    ) {
      const that = this;
      imagery.addReference();
      const computeCommand = new ComputeCommand({
        persists: true,
        owner: this,
        // Update render resources right before execution instead of now.
        // This allows different ImageryLayers to share the same vao and buffers.
        preExecute: function (command) {
          reprojectToGeographic(command, context, texture, imagery.rectangle);
        },
        postExecute: function (outputTexture) {
          imagery.texture = outputTexture;
          that._finalizeReprojectTexture(context, outputTexture);
          imagery.state = ImageryState$1.READY;
          imagery.releaseReference();
        },
        canceled: function () {
          imagery.state = ImageryState$1.TEXTURE_LOADED;
          imagery.releaseReference();
        },
      });
      this._reprojectComputeCommands.push(computeCommand);
    } else {
      if (needGeographicProjection) {
        imagery.texture = texture;
      }
      this._finalizeReprojectTexture(context, texture);
      imagery.state = ImageryState$1.READY;
    }
  };

  /**
   * Updates frame state to execute any queued texture re-projections.
   *
   * @private
   *
   * @param {FrameState} frameState The frameState.
   */
  ImageryLayer.prototype.queueReprojectionCommands = function (frameState) {
    const computeCommands = this._reprojectComputeCommands;
    const length = computeCommands.length;
    for (let i = 0; i < length; ++i) {
      frameState.commandList.push(computeCommands[i]);
    }
    computeCommands.length = 0;
  };

  /**
   * Cancels re-projection commands queued for the next frame.
   *
   * @private
   */
  ImageryLayer.prototype.cancelReprojections = function () {
    this._reprojectComputeCommands.forEach(function (command) {
      if (defined(command.canceled)) {
        command.canceled();
      }
    });
    this._reprojectComputeCommands.length = 0;
  };

  ImageryLayer.prototype.getImageryFromCache = function (
    x,
    y,
    level,
    imageryRectangle
  ) {
    const cacheKey = getImageryCacheKey(x, y, level);
    let imagery = this._imageryCache[cacheKey];

    if (!defined(imagery)) {
      imagery = new Imagery(this, x, y, level, imageryRectangle);
      this._imageryCache[cacheKey] = imagery;
    }

    imagery.addReference();
    return imagery;
  };

  ImageryLayer.prototype.removeImageryFromCache = function (imagery) {
    const cacheKey = getImageryCacheKey(imagery.x, imagery.y, imagery.level);
    delete this._imageryCache[cacheKey];
  };

  function getImageryCacheKey(x, y, level) {
    return JSON.stringify([x, y, level]);
  }

  const uniformMap = {
    u_textureDimensions: function () {
      return this.textureDimensions;
    },
    u_texture: function () {
      return this.texture;
    },

    textureDimensions: new Cartesian2(),
    texture: undefined,
  };

  const float32ArrayScratch = FeatureDetection.supportsTypedArrays()
    ? new Float32Array(2 * 64)
    : undefined;

  function reprojectToGeographic(command, context, texture, rectangle) {
    // This function has gone through a number of iterations, because GPUs are awesome.
    //
    // Originally, we had a very simple vertex shader and computed the Web Mercator texture coordinates
    // per-fragment in the fragment shader.  That worked well, except on mobile devices, because
    // fragment shaders have limited precision on many mobile devices.  The result was smearing artifacts
    // at medium zoom levels because different geographic texture coordinates would be reprojected to Web
    // Mercator as the same value.
    //
    // Our solution was to reproject to Web Mercator in the vertex shader instead of the fragment shader.
    // This required far more vertex data.  With fragment shader reprojection, we only needed a single quad.
    // But to achieve the same precision with vertex shader reprojection, we needed a vertex for each
    // output pixel.  So we used a grid of 256x256 vertices, because most of our imagery
    // tiles are 256x256.  Fortunately the grid could be created and uploaded to the GPU just once and
    // re-used for all reprojections, so the performance was virtually unchanged from our original fragment
    // shader approach.  See https://github.com/CesiumGS/cesium/pull/714.
    //
    // Over a year later, we noticed (https://github.com/CesiumGS/cesium/issues/2110)
    // that our reprojection code was creating a rare but severe artifact on some GPUs (Intel HD 4600
    // for one).  The problem was that the GLSL sin function on these GPUs had a discontinuity at fine scales in
    // a few places.
    //
    // We solved this by implementing a more reliable sin function based on the CORDIC algorithm
    // (https://github.com/CesiumGS/cesium/pull/2111).  Even though this was a fair
    // amount of code to be executing per vertex, the performance seemed to be pretty good on most GPUs.
    // Unfortunately, on some GPUs, the performance was absolutely terrible
    // (https://github.com/CesiumGS/cesium/issues/2258).
    //
    // So that brings us to our current solution, the one you see here.  Effectively, we compute the Web
    // Mercator texture coordinates on the CPU and store the T coordinate with each vertex (the S coordinate
    // is the same in Geographic and Web Mercator).  To make this faster, we reduced our reprojection mesh
    // to be only 2 vertices wide and 64 vertices high.  We should have reduced the width to 2 sooner,
    // because the extra vertices weren't buying us anything.  The height of 64 means we are technically
    // doing a slightly less accurate reprojection than we were before, but we can't see the difference
    // so it's worth the 4x speedup.

    let reproject = context.cache.imageryLayer_reproject;

    if (!defined(reproject)) {
      reproject = context.cache.imageryLayer_reproject = {
        vertexArray: undefined,
        shaderProgram: undefined,
        sampler: undefined,
        destroy: function () {
          if (defined(this.framebuffer)) {
            this.framebuffer.destroy();
          }
          if (defined(this.vertexArray)) {
            this.vertexArray.destroy();
          }
          if (defined(this.shaderProgram)) {
            this.shaderProgram.destroy();
          }
        },
      };

      const positions = new Float32Array(2 * 64 * 2);
      let index = 0;
      for (let j = 0; j < 64; ++j) {
        const y = j / 63.0;
        positions[index++] = 0.0;
        positions[index++] = y;
        positions[index++] = 1.0;
        positions[index++] = y;
      }

      const reprojectAttributeIndices = {
        position: 0,
        webMercatorT: 1,
      };

      const indices = TerrainProvider.getRegularGridIndices(2, 64);
      const indexBuffer = Buffer$1.createIndexBuffer({
        context: context,
        typedArray: indices,
        usage: BufferUsage$1.STATIC_DRAW,
        indexDatatype: IndexDatatype$1.UNSIGNED_SHORT,
      });

      reproject.vertexArray = new VertexArray({
        context: context,
        attributes: [
          {
            index: reprojectAttributeIndices.position,
            vertexBuffer: Buffer$1.createVertexBuffer({
              context: context,
              typedArray: positions,
              usage: BufferUsage$1.STATIC_DRAW,
            }),
            componentsPerAttribute: 2,
          },
          {
            index: reprojectAttributeIndices.webMercatorT,
            vertexBuffer: Buffer$1.createVertexBuffer({
              context: context,
              sizeInBytes: 64 * 2 * 4,
              usage: BufferUsage$1.STREAM_DRAW,
            }),
            componentsPerAttribute: 1,
          },
        ],
        indexBuffer: indexBuffer,
      });

      const vs = new ShaderSource({
        sources: [ReprojectWebMercatorVS],
      });

      reproject.shaderProgram = ShaderProgram.fromCache({
        context: context,
        vertexShaderSource: vs,
        fragmentShaderSource: ReprojectWebMercatorFS,
        attributeLocations: reprojectAttributeIndices,
      });

      reproject.sampler = new Sampler({
        wrapS: TextureWrap$1.CLAMP_TO_EDGE,
        wrapT: TextureWrap$1.CLAMP_TO_EDGE,
        minificationFilter: TextureMinificationFilter$1.LINEAR,
        magnificationFilter: TextureMagnificationFilter$1.LINEAR,
      });
    }

    texture.sampler = reproject.sampler;

    const width = texture.width;
    const height = texture.height;

    uniformMap.textureDimensions.x = width;
    uniformMap.textureDimensions.y = height;
    uniformMap.texture = texture;

    let sinLatitude = Math.sin(rectangle.south);
    const southMercatorY = 0.5 * Math.log((1 + sinLatitude) / (1 - sinLatitude));

    sinLatitude = Math.sin(rectangle.north);
    const northMercatorY = 0.5 * Math.log((1 + sinLatitude) / (1 - sinLatitude));
    const oneOverMercatorHeight = 1.0 / (northMercatorY - southMercatorY);

    const outputTexture = new Texture({
      context: context,
      width: width,
      height: height,
      pixelFormat: texture.pixelFormat,
      pixelDatatype: texture.pixelDatatype,
      preMultiplyAlpha: texture.preMultiplyAlpha,
    });

    // Allocate memory for the mipmaps.  Failure to do this before rendering
    // to the texture via the FBO, and calling generateMipmap later,
    // will result in the texture appearing blank.  I can't pretend to
    // understand exactly why this is.
    if (CesiumMath.isPowerOfTwo(width) && CesiumMath.isPowerOfTwo(height)) {
      outputTexture.generateMipmap(MipmapHint$1.NICEST);
    }

    const south = rectangle.south;
    const north = rectangle.north;

    const webMercatorT = float32ArrayScratch;

    let outputIndex = 0;
    for (let webMercatorTIndex = 0; webMercatorTIndex < 64; ++webMercatorTIndex) {
      const fraction = webMercatorTIndex / 63.0;
      const latitude = CesiumMath.lerp(south, north, fraction);
      sinLatitude = Math.sin(latitude);
      const mercatorY = 0.5 * Math.log((1.0 + sinLatitude) / (1.0 - sinLatitude));
      const mercatorFraction =
        (mercatorY - southMercatorY) * oneOverMercatorHeight;
      webMercatorT[outputIndex++] = mercatorFraction;
      webMercatorT[outputIndex++] = mercatorFraction;
    }

    reproject.vertexArray
      .getAttribute(1)
      .vertexBuffer.copyFromArrayView(webMercatorT);

    command.shaderProgram = reproject.shaderProgram;
    command.outputTexture = outputTexture;
    command.uniformMap = uniformMap;
    command.vertexArray = reproject.vertexArray;
  }

  /**
   * Gets the level with the specified world coordinate spacing between texels, or less.
   *
   * @param {ImageryLayer} layer The imagery layer to use.
   * @param {Number} texelSpacing The texel spacing for which to find a corresponding level.
   * @param {Number} latitudeClosestToEquator The latitude closest to the equator that we're concerned with.
   * @returns {Number} The level with the specified texel spacing or less.
   * @private
   */
  function getLevelWithMaximumTexelSpacing(
    layer,
    texelSpacing,
    latitudeClosestToEquator
  ) {
    // PERFORMANCE_IDEA: factor out the stuff that doesn't change.
    const imageryProvider = layer._imageryProvider;
    const tilingScheme = imageryProvider.tilingScheme;
    const ellipsoid = tilingScheme.ellipsoid;
    const latitudeFactor = !(
      layer._imageryProvider.tilingScheme.projection instanceof
      GeographicProjection
    )
      ? Math.cos(latitudeClosestToEquator)
      : 1.0;
    const tilingSchemeRectangle = tilingScheme.rectangle;
    const levelZeroMaximumTexelSpacing =
      (ellipsoid.maximumRadius * tilingSchemeRectangle.width * latitudeFactor) /
      (imageryProvider.tileWidth * tilingScheme.getNumberOfXTilesAtLevel(0));

    const twoToTheLevelPower = levelZeroMaximumTexelSpacing / texelSpacing;
    const level = Math.log(twoToTheLevelPower) / Math.log(2);
    const rounded = Math.round(level);
    return rounded | 0;
  }

  /**
   * Indicates what happened the last time this tile was visited for selection.
   * @private
   */
  const TileSelectionResult = {
    /**
     * There was no selection result, perhaps because the tile wasn't visited
     * last frame.
     */
    NONE: 0,

    /**
     * This tile was deemed not visible and culled.
     */
    CULLED: 1,

    /**
     * The tile was selected for rendering.
     */
    RENDERED: 2,

    /**
     * This tile did not meet the required screen-space error and was refined.
     */
    REFINED: 3,

    /**
     * This tile was originally rendered, but it got kicked out of the render list
     * in favor of an ancestor because it is not yet renderable.
     */
    RENDERED_AND_KICKED: 2 | 4,

    /**
     * This tile was originally refined, but its rendered descendants got kicked out of the
     * render list in favor of an ancestor because it is not yet renderable.
     */
    REFINED_AND_KICKED: 3 | 4,

    /**
     * This tile was culled because it was not visible, but it still needs to be loaded
     * and any heights on it need to be updated because the camera's position or the
     * camera's reference frame's origin falls inside this tile. Loading this tile
     * could affect the position of the camera if the camera is currently below
     * terrain or if it is tracking an object whose height is referenced to terrain.
     * And a change in the camera position may, in turn, affect what is culled.
     */
    CULLED_BUT_NEEDED: 1 | 8,

    /**
     * Determines if a selection result indicates that this tile or its descendants were
     * kicked from the render list. In other words, if it is <code>RENDERED_AND_KICKED</code>
     * or <code>REFINED_AND_KICKED</code>.
     *
     * @param {TileSelectionResult} value The selection result to test.
     * @returns {Boolean} true if the tile was kicked, no matter if it was originally rendered or refined.
     */
    wasKicked: function (value) {
      return value >= TileSelectionResult.RENDERED_AND_KICKED;
    },

    /**
     * Determines the original selection result prior to being kicked or CULLED_BUT_NEEDED.
     * If the tile wasn't kicked or CULLED_BUT_NEEDED, the original value is returned.
     * @param {TileSelectionResult} value The selection result.
     * @returns {TileSelectionResult} The original selection result prior to kicking.
     */
    originalResult: function (value) {
      return value & 3;
    },

    /**
     * Converts this selection result to a kick.
     * @param {TileSelectionResult} value The original selection result.
     * @returns {TileSelectionResult} The kicked form of the selection result.
     */
    kick: function (value) {
      return value | 4;
    },
  };

  function TerrainFillMesh(tile) {
    this.tile = tile;
    this.frameLastUpdated = undefined;
    this.westMeshes = []; // north to south (CCW)
    this.westTiles = [];
    this.southMeshes = []; // west to east (CCW)
    this.southTiles = [];
    this.eastMeshes = []; // south to north (CCW)
    this.eastTiles = [];
    this.northMeshes = []; // east to west (CCW)
    this.northTiles = [];
    this.southwestMesh = undefined;
    this.southwestTile = undefined;
    this.southeastMesh = undefined;
    this.southeastTile = undefined;
    this.northwestMesh = undefined;
    this.northwestTile = undefined;
    this.northeastMesh = undefined;
    this.northeastTile = undefined;
    this.changedThisFrame = true;
    this.visitedFrame = undefined;
    this.enqueuedFrame = undefined;
    this.mesh = undefined;
    this.vertexArray = undefined;
    this.waterMaskTexture = undefined;
    this.waterMaskTranslationAndScale = new Cartesian4();
  }

  TerrainFillMesh.prototype.update = function (
    tileProvider,
    frameState,
    vertexArraysToDestroy
  ) {
    if (this.changedThisFrame) {
      createFillMesh(tileProvider, frameState, this.tile, vertexArraysToDestroy);
      this.changedThisFrame = false;
    }
  };

  TerrainFillMesh.prototype.destroy = function (vertexArraysToDestroy) {
    this._destroyVertexArray(vertexArraysToDestroy);

    if (defined(this.waterMaskTexture)) {
      --this.waterMaskTexture.referenceCount;
      if (this.waterMaskTexture.referenceCount === 0) {
        this.waterMaskTexture.destroy();
      }
      this.waterMaskTexture = undefined;
    }

    return undefined;
  };

  TerrainFillMesh.prototype._destroyVertexArray = function (
    vertexArraysToDestroy
  ) {
    if (defined(this.vertexArray)) {
      if (defined(vertexArraysToDestroy)) {
        vertexArraysToDestroy.push(this.vertexArray);
      } else {
        GlobeSurfaceTile._freeVertexArray(this.vertexArray);
      }
      this.vertexArray = undefined;
    }
  };

  const traversalQueueScratch = new Queue();

  TerrainFillMesh.updateFillTiles = function (
    tileProvider,
    renderedTiles,
    frameState,
    vertexArraysToDestroy
  ) {
    // We want our fill tiles to look natural, which means they should align perfectly with
    // adjacent loaded tiles, and their edges that are not adjacent to loaded tiles should have
    // sensible heights (e.g. the average of the heights of loaded edges). Some fill tiles may
    // be adjacent only to other fill tiles, and in that case heights should be assigned fanning
    // outward from the loaded tiles so that there are no sudden changes in height.

    // We do this with a breadth-first traversal of the rendered tiles, starting with the loaded
    // ones. Graph nodes are tiles and graph edges connect to other rendered tiles that are spatially adjacent
    // to those tiles. As we visit each node, we propagate tile edges to adjacent tiles. If there's no data
    // for a tile edge,  we create an edge with an average height and then propagate it. If an edge is partially defined
    // (e.g. an edge is adjacent to multiple more-detailed tiles and only some of them are loaded), we
    // fill in the rest of the edge with the same height.
    const quadtree = tileProvider._quadtree;
    const levelZeroTiles = quadtree._levelZeroTiles;
    const lastSelectionFrameNumber = quadtree._lastSelectionFrameNumber;

    const traversalQueue = traversalQueueScratch;
    traversalQueue.clear();

    // Add the tiles with real geometry to the traversal queue.
    for (let i = 0; i < renderedTiles.length; ++i) {
      const renderedTile = renderedTiles[i];
      if (defined(renderedTile.data.vertexArray)) {
        traversalQueue.enqueue(renderedTiles[i]);
      }
    }

    let tile = traversalQueue.dequeue();

    while (tile !== undefined) {
      const tileToWest = tile.findTileToWest(levelZeroTiles);
      const tileToSouth = tile.findTileToSouth(levelZeroTiles);
      const tileToEast = tile.findTileToEast(levelZeroTiles);
      const tileToNorth = tile.findTileToNorth(levelZeroTiles);
      visitRenderedTiles(
        tileProvider,
        frameState,
        tile,
        tileToWest,
        lastSelectionFrameNumber,
        TileEdge.EAST,
        false,
        traversalQueue,
        vertexArraysToDestroy
      );
      visitRenderedTiles(
        tileProvider,
        frameState,
        tile,
        tileToSouth,
        lastSelectionFrameNumber,
        TileEdge.NORTH,
        false,
        traversalQueue,
        vertexArraysToDestroy
      );
      visitRenderedTiles(
        tileProvider,
        frameState,
        tile,
        tileToEast,
        lastSelectionFrameNumber,
        TileEdge.WEST,
        false,
        traversalQueue,
        vertexArraysToDestroy
      );
      visitRenderedTiles(
        tileProvider,
        frameState,
        tile,
        tileToNorth,
        lastSelectionFrameNumber,
        TileEdge.SOUTH,
        false,
        traversalQueue,
        vertexArraysToDestroy
      );

      const tileToNorthwest = tileToWest.findTileToNorth(levelZeroTiles);
      const tileToSouthwest = tileToWest.findTileToSouth(levelZeroTiles);
      const tileToNortheast = tileToEast.findTileToNorth(levelZeroTiles);
      const tileToSoutheast = tileToEast.findTileToSouth(levelZeroTiles);
      visitRenderedTiles(
        tileProvider,
        frameState,
        tile,
        tileToNorthwest,
        lastSelectionFrameNumber,
        TileEdge.SOUTHEAST,
        false,
        traversalQueue,
        vertexArraysToDestroy
      );
      visitRenderedTiles(
        tileProvider,
        frameState,
        tile,
        tileToNortheast,
        lastSelectionFrameNumber,
        TileEdge.SOUTHWEST,
        false,
        traversalQueue,
        vertexArraysToDestroy
      );
      visitRenderedTiles(
        tileProvider,
        frameState,
        tile,
        tileToSouthwest,
        lastSelectionFrameNumber,
        TileEdge.NORTHEAST,
        false,
        traversalQueue,
        vertexArraysToDestroy
      );
      visitRenderedTiles(
        tileProvider,
        frameState,
        tile,
        tileToSoutheast,
        lastSelectionFrameNumber,
        TileEdge.NORTHWEST,
        false,
        traversalQueue,
        vertexArraysToDestroy
      );

      tile = traversalQueue.dequeue();
    }
  };

  function visitRenderedTiles(
    tileProvider,
    frameState,
    sourceTile,
    startTile,
    currentFrameNumber,
    tileEdge,
    downOnly,
    traversalQueue,
    vertexArraysToDestroy
  ) {
    if (startTile === undefined) {
      // There are no tiles North or South of the poles.
      return;
    }

    let tile = startTile;
    while (
      tile &&
      (tile._lastSelectionResultFrame !== currentFrameNumber ||
        TileSelectionResult.wasKicked(tile._lastSelectionResult) ||
        TileSelectionResult.originalResult(tile._lastSelectionResult) ===
          TileSelectionResult.CULLED)
    ) {
      // This tile wasn't visited or it was visited and then kicked, so walk up to find the closest ancestor that was rendered.
      // We also walk up if the tile was culled, because if siblings were kicked an ancestor may have been rendered.
      if (downOnly) {
        return;
      }

      const parent = tile.parent;
      if (tileEdge >= TileEdge.NORTHWEST && parent !== undefined) {
        // When we're looking for a corner, verify that the parent tile is still relevant.
        // That is, the parent and child must share the corner in question.
        switch (tileEdge) {
          case TileEdge.NORTHWEST:
            tile = tile === parent.northwestChild ? parent : undefined;
            break;
          case TileEdge.NORTHEAST:
            tile = tile === parent.northeastChild ? parent : undefined;
            break;
          case TileEdge.SOUTHWEST:
            tile = tile === parent.southwestChild ? parent : undefined;
            break;
          case TileEdge.SOUTHEAST:
            tile = tile === parent.southeastChild ? parent : undefined;
            break;
        }
      } else {
        tile = parent;
      }
    }

    if (tile === undefined) {
      return;
    }

    if (tile._lastSelectionResult === TileSelectionResult.RENDERED) {
      if (defined(tile.data.vertexArray)) {
        // No further processing necessary for renderable tiles.
        return;
      }
      visitTile$1(
        tileProvider,
        frameState,
        sourceTile,
        tile,
        tileEdge,
        currentFrameNumber,
        traversalQueue,
        vertexArraysToDestroy
      );
      return;
    }

    if (
      TileSelectionResult.originalResult(startTile._lastSelectionResult) ===
      TileSelectionResult.CULLED
    ) {
      return;
    }

    // This tile was refined, so find rendered children, if any.
    // Visit the tiles in counter-clockwise order.
    switch (tileEdge) {
      case TileEdge.WEST:
        visitRenderedTiles(
          tileProvider,
          frameState,
          sourceTile,
          startTile.northwestChild,
          currentFrameNumber,
          tileEdge,
          true,
          traversalQueue,
          vertexArraysToDestroy
        );
        visitRenderedTiles(
          tileProvider,
          frameState,
          sourceTile,
          startTile.southwestChild,
          currentFrameNumber,
          tileEdge,
          true,
          traversalQueue,
          vertexArraysToDestroy
        );
        break;
      case TileEdge.EAST:
        visitRenderedTiles(
          tileProvider,
          frameState,
          sourceTile,
          startTile.southeastChild,
          currentFrameNumber,
          tileEdge,
          true,
          traversalQueue,
          vertexArraysToDestroy
        );
        visitRenderedTiles(
          tileProvider,
          frameState,
          sourceTile,
          startTile.northeastChild,
          currentFrameNumber,
          tileEdge,
          true,
          traversalQueue,
          vertexArraysToDestroy
        );
        break;
      case TileEdge.SOUTH:
        visitRenderedTiles(
          tileProvider,
          frameState,
          sourceTile,
          startTile.southwestChild,
          currentFrameNumber,
          tileEdge,
          true,
          traversalQueue,
          vertexArraysToDestroy
        );
        visitRenderedTiles(
          tileProvider,
          frameState,
          sourceTile,
          startTile.southeastChild,
          currentFrameNumber,
          tileEdge,
          true,
          traversalQueue,
          vertexArraysToDestroy
        );
        break;
      case TileEdge.NORTH:
        visitRenderedTiles(
          tileProvider,
          frameState,
          sourceTile,
          startTile.northeastChild,
          currentFrameNumber,
          tileEdge,
          true,
          traversalQueue,
          vertexArraysToDestroy
        );
        visitRenderedTiles(
          tileProvider,
          frameState,
          sourceTile,
          startTile.northwestChild,
          currentFrameNumber,
          tileEdge,
          true,
          traversalQueue,
          vertexArraysToDestroy
        );
        break;
      case TileEdge.NORTHWEST:
        visitRenderedTiles(
          tileProvider,
          frameState,
          sourceTile,
          startTile.northwestChild,
          currentFrameNumber,
          tileEdge,
          true,
          traversalQueue,
          vertexArraysToDestroy
        );
        break;
      case TileEdge.NORTHEAST:
        visitRenderedTiles(
          tileProvider,
          frameState,
          sourceTile,
          startTile.northeastChild,
          currentFrameNumber,
          tileEdge,
          true,
          traversalQueue,
          vertexArraysToDestroy
        );
        break;
      case TileEdge.SOUTHWEST:
        visitRenderedTiles(
          tileProvider,
          frameState,
          sourceTile,
          startTile.southwestChild,
          currentFrameNumber,
          tileEdge,
          true,
          traversalQueue,
          vertexArraysToDestroy
        );
        break;
      case TileEdge.SOUTHEAST:
        visitRenderedTiles(
          tileProvider,
          frameState,
          sourceTile,
          startTile.southeastChild,
          currentFrameNumber,
          tileEdge,
          true,
          traversalQueue,
          vertexArraysToDestroy
        );
        break;
      default:
        throw new DeveloperError("Invalid edge");
    }
  }

  function visitTile$1(
    tileProvider,
    frameState,
    sourceTile,
    destinationTile,
    tileEdge,
    frameNumber,
    traversalQueue,
    vertexArraysToDestroy
  ) {
    const destinationSurfaceTile = destinationTile.data;

    if (destinationSurfaceTile.fill === undefined) {
      destinationSurfaceTile.fill = new TerrainFillMesh(destinationTile);
    } else if (destinationSurfaceTile.fill.visitedFrame === frameNumber) {
      // Don't propagate edges to tiles that have already been visited this frame.
      return;
    }

    if (destinationSurfaceTile.fill.enqueuedFrame !== frameNumber) {
      // First time visiting this tile this frame, add it to the traversal queue.
      destinationSurfaceTile.fill.enqueuedFrame = frameNumber;
      destinationSurfaceTile.fill.changedThisFrame = false;
      traversalQueue.enqueue(destinationTile);
    }

    propagateEdge(
      tileProvider,
      frameState,
      sourceTile,
      destinationTile,
      tileEdge,
      vertexArraysToDestroy
    );
  }

  function propagateEdge(
    tileProvider,
    frameState,
    sourceTile,
    destinationTile,
    tileEdge,
    vertexArraysToDestroy
  ) {
    const destinationFill = destinationTile.data.fill;

    let sourceMesh;
    const sourceFill = sourceTile.data.fill;
    if (defined(sourceFill)) {
      sourceFill.visitedFrame = frameState.frameNumber;

      // Source is a fill, create/update it if necessary.
      if (sourceFill.changedThisFrame) {
        createFillMesh(
          tileProvider,
          frameState,
          sourceTile,
          vertexArraysToDestroy
        );
        sourceFill.changedThisFrame = false;
      }
      sourceMesh = sourceTile.data.fill.mesh;
    } else {
      sourceMesh = sourceTile.data.mesh;
    }

    let edgeMeshes;
    let edgeTiles;

    switch (tileEdge) {
      case TileEdge.WEST:
        edgeMeshes = destinationFill.westMeshes;
        edgeTiles = destinationFill.westTiles;
        break;
      case TileEdge.SOUTH:
        edgeMeshes = destinationFill.southMeshes;
        edgeTiles = destinationFill.southTiles;
        break;
      case TileEdge.EAST:
        edgeMeshes = destinationFill.eastMeshes;
        edgeTiles = destinationFill.eastTiles;
        break;
      case TileEdge.NORTH:
        edgeMeshes = destinationFill.northMeshes;
        edgeTiles = destinationFill.northTiles;
        break;
      // Corners are simpler.
      case TileEdge.NORTHWEST:
        destinationFill.changedThisFrame =
          destinationFill.changedThisFrame ||
          destinationFill.northwestMesh !== sourceMesh;
        destinationFill.northwestMesh = sourceMesh;
        destinationFill.northwestTile = sourceTile;
        return;
      case TileEdge.NORTHEAST:
        destinationFill.changedThisFrame =
          destinationFill.changedThisFrame ||
          destinationFill.northeastMesh !== sourceMesh;
        destinationFill.northeastMesh = sourceMesh;
        destinationFill.northeastTile = sourceTile;
        return;
      case TileEdge.SOUTHWEST:
        destinationFill.changedThisFrame =
          destinationFill.changedThisFrame ||
          destinationFill.southwestMesh !== sourceMesh;
        destinationFill.southwestMesh = sourceMesh;
        destinationFill.southwestTile = sourceTile;
        return;
      case TileEdge.SOUTHEAST:
        destinationFill.changedThisFrame =
          destinationFill.changedThisFrame ||
          destinationFill.southeastMesh !== sourceMesh;
        destinationFill.southeastMesh = sourceMesh;
        destinationFill.southeastTile = sourceTile;
        return;
    }

    if (sourceTile.level <= destinationTile.level) {
      // Source edge completely spans the destination edge.
      destinationFill.changedThisFrame =
        destinationFill.changedThisFrame ||
        edgeMeshes[0] !== sourceMesh ||
        edgeMeshes.length !== 1;
      edgeMeshes[0] = sourceMesh;
      edgeTiles[0] = sourceTile;
      edgeMeshes.length = 1;
      edgeTiles.length = 1;
      return;
    }

    // Source edge is a subset of the destination edge.
    // Figure out the range of meshes we're replacing.
    let startIndex, endIndex, existingTile, existingRectangle;
    const sourceRectangle = sourceTile.rectangle;

    let epsilon;
    const destinationRectangle = destinationTile.rectangle;

    switch (tileEdge) {
      case TileEdge.WEST:
        epsilon =
          (destinationRectangle.north - destinationRectangle.south) *
          CesiumMath.EPSILON5;

        for (startIndex = 0; startIndex < edgeTiles.length; ++startIndex) {
          existingTile = edgeTiles[startIndex];
          existingRectangle = existingTile.rectangle;
          if (
            CesiumMath.greaterThan(
              sourceRectangle.north,
              existingRectangle.south,
              epsilon
            )
          ) {
            break;
          }
        }
        for (endIndex = startIndex; endIndex < edgeTiles.length; ++endIndex) {
          existingTile = edgeTiles[endIndex];
          existingRectangle = existingTile.rectangle;
          if (
            CesiumMath.greaterThanOrEquals(
              sourceRectangle.south,
              existingRectangle.north,
              epsilon
            )
          ) {
            break;
          }
        }
        break;
      case TileEdge.SOUTH:
        epsilon =
          (destinationRectangle.east - destinationRectangle.west) *
          CesiumMath.EPSILON5;

        for (startIndex = 0; startIndex < edgeTiles.length; ++startIndex) {
          existingTile = edgeTiles[startIndex];
          existingRectangle = existingTile.rectangle;
          if (
            CesiumMath.lessThan(
              sourceRectangle.west,
              existingRectangle.east,
              epsilon
            )
          ) {
            break;
          }
        }
        for (endIndex = startIndex; endIndex < edgeTiles.length; ++endIndex) {
          existingTile = edgeTiles[endIndex];
          existingRectangle = existingTile.rectangle;
          if (
            CesiumMath.lessThanOrEquals(
              sourceRectangle.east,
              existingRectangle.west,
              epsilon
            )
          ) {
            break;
          }
        }
        break;
      case TileEdge.EAST:
        epsilon =
          (destinationRectangle.north - destinationRectangle.south) *
          CesiumMath.EPSILON5;

        for (startIndex = 0; startIndex < edgeTiles.length; ++startIndex) {
          existingTile = edgeTiles[startIndex];
          existingRectangle = existingTile.rectangle;
          if (
            CesiumMath.lessThan(
              sourceRectangle.south,
              existingRectangle.north,
              epsilon
            )
          ) {
            break;
          }
        }
        for (endIndex = startIndex; endIndex < edgeTiles.length; ++endIndex) {
          existingTile = edgeTiles[endIndex];
          existingRectangle = existingTile.rectangle;
          if (
            CesiumMath.lessThanOrEquals(
              sourceRectangle.north,
              existingRectangle.south,
              epsilon
            )
          ) {
            break;
          }
        }
        break;
      case TileEdge.NORTH:
        epsilon =
          (destinationRectangle.east - destinationRectangle.west) *
          CesiumMath.EPSILON5;

        for (startIndex = 0; startIndex < edgeTiles.length; ++startIndex) {
          existingTile = edgeTiles[startIndex];
          existingRectangle = existingTile.rectangle;
          if (
            CesiumMath.greaterThan(
              sourceRectangle.east,
              existingRectangle.west,
              epsilon
            )
          ) {
            break;
          }
        }
        for (endIndex = startIndex; endIndex < edgeTiles.length; ++endIndex) {
          existingTile = edgeTiles[endIndex];
          existingRectangle = existingTile.rectangle;
          if (
            CesiumMath.greaterThanOrEquals(
              sourceRectangle.west,
              existingRectangle.east,
              epsilon
            )
          ) {
            break;
          }
        }
        break;
    }

    if (endIndex - startIndex === 1) {
      destinationFill.changedThisFrame =
        destinationFill.changedThisFrame || edgeMeshes[startIndex] !== sourceMesh;
      edgeMeshes[startIndex] = sourceMesh;
      edgeTiles[startIndex] = sourceTile;
    } else {
      destinationFill.changedThisFrame = true;
      edgeMeshes.splice(startIndex, endIndex - startIndex, sourceMesh);
      edgeTiles.splice(startIndex, endIndex - startIndex, sourceTile);
    }
  }

  const cartographicScratch$1 = new Cartographic();
  const centerCartographicScratch = new Cartographic();
  const cartesianScratch = new Cartesian3();
  const normalScratch = new Cartesian3();
  const octEncodedNormalScratch = new Cartesian2();
  const uvScratch2 = new Cartesian2();
  const uvScratch = new Cartesian2();

  function HeightAndNormal() {
    this.height = 0.0;
    this.encodedNormal = new Cartesian2();
  }

  function fillMissingCorner(
    fill,
    ellipsoid,
    u,
    v,
    corner,
    adjacentCorner1,
    adjacentCorner2,
    oppositeCorner,
    vertex
  ) {
    if (defined(corner)) {
      return corner;
    }

    let height;

    if (defined(adjacentCorner1) && defined(adjacentCorner2)) {
      height = (adjacentCorner1.height + adjacentCorner2.height) * 0.5;
    } else if (defined(adjacentCorner1)) {
      height = adjacentCorner1.height;
    } else if (defined(adjacentCorner2)) {
      height = adjacentCorner2.height;
    } else if (defined(oppositeCorner)) {
      height = oppositeCorner.height;
    } else {
      const surfaceTile = fill.tile.data;
      const tileBoundingRegion = surfaceTile.tileBoundingRegion;
      let minimumHeight = 0.0;
      let maximumHeight = 0.0;
      if (defined(tileBoundingRegion)) {
        minimumHeight = tileBoundingRegion.minimumHeight;
        maximumHeight = tileBoundingRegion.maximumHeight;
      }
      height = (minimumHeight + maximumHeight) * 0.5;
    }

    getVertexWithHeightAtCorner(fill, ellipsoid, u, v, height, vertex);
    return vertex;
  }

  const heightRangeScratch = {
    minimumHeight: 0.0,
    maximumHeight: 0.0,
  };

  const scratchCenter$2 = new Cartesian3();
  const swVertexScratch = new HeightAndNormal();
  const seVertexScratch = new HeightAndNormal();
  const nwVertexScratch = new HeightAndNormal();
  const neVertexScratch = new HeightAndNormal();
  const heightmapBuffer =
    typeof Uint8Array !== "undefined" ? new Uint8Array(9 * 9) : undefined;

  const scratchCreateMeshSyncOptions = {
    tilingScheme: undefined,
    x: 0,
    y: 0,
    level: 0,
    exaggeration: 1.0,
    exaggerationRelativeHeight: 0.0,
  };
  function createFillMesh(tileProvider, frameState, tile, vertexArraysToDestroy) {
    GlobeSurfaceTile.initialize(
      tile,
      tileProvider.terrainProvider,
      tileProvider._imageryLayers
    );

    const surfaceTile = tile.data;
    const fill = surfaceTile.fill;
    const rectangle = tile.rectangle;

    const exaggeration = frameState.terrainExaggeration;
    const exaggerationRelativeHeight =
      frameState.terrainExaggerationRelativeHeight;
    const hasExaggeration = exaggeration !== 1.0;

    const ellipsoid = tile.tilingScheme.ellipsoid;

    let nwCorner = getCorner(
      fill,
      ellipsoid,
      0.0,
      1.0,
      fill.northwestTile,
      fill.northwestMesh,
      fill.northTiles,
      fill.northMeshes,
      fill.westTiles,
      fill.westMeshes,
      nwVertexScratch
    );
    let swCorner = getCorner(
      fill,
      ellipsoid,
      0.0,
      0.0,
      fill.southwestTile,
      fill.southwestMesh,
      fill.westTiles,
      fill.westMeshes,
      fill.southTiles,
      fill.southMeshes,
      swVertexScratch
    );
    let seCorner = getCorner(
      fill,
      ellipsoid,
      1.0,
      0.0,
      fill.southeastTile,
      fill.southeastMesh,
      fill.southTiles,
      fill.southMeshes,
      fill.eastTiles,
      fill.eastMeshes,
      seVertexScratch
    );
    let neCorner = getCorner(
      fill,
      ellipsoid,
      1.0,
      1.0,
      fill.northeastTile,
      fill.northeastMesh,
      fill.eastTiles,
      fill.eastMeshes,
      fill.northTiles,
      fill.northMeshes,
      neVertexScratch
    );

    nwCorner = fillMissingCorner(
      fill,
      ellipsoid,
      0.0,
      1.0,
      nwCorner,
      swCorner,
      neCorner,
      seCorner,
      nwVertexScratch
    );
    swCorner = fillMissingCorner(
      fill,
      ellipsoid,
      0.0,
      0.0,
      swCorner,
      nwCorner,
      seCorner,
      neCorner,
      swVertexScratch
    );
    seCorner = fillMissingCorner(
      fill,
      ellipsoid,
      1.0,
      1.0,
      seCorner,
      swCorner,
      neCorner,
      nwCorner,
      seVertexScratch
    );
    neCorner = fillMissingCorner(
      fill,
      ellipsoid,
      1.0,
      1.0,
      neCorner,
      seCorner,
      nwCorner,
      swCorner,
      neVertexScratch
    );

    const southwestHeight = swCorner.height;
    const southeastHeight = seCorner.height;
    const northwestHeight = nwCorner.height;
    const northeastHeight = neCorner.height;

    let minimumHeight = Math.min(
      southwestHeight,
      southeastHeight,
      northwestHeight,
      northeastHeight
    );
    let maximumHeight = Math.max(
      southwestHeight,
      southeastHeight,
      northwestHeight,
      northeastHeight
    );

    const middleHeight = (minimumHeight + maximumHeight) * 0.5;

    let i;
    let len;

    // For low-detail tiles, our usual fill tile approach will create tiles that
    // look really blocky because they don't have enough vertices to account for the
    // Earth's curvature. But the height range will also typically be well within
    // the allowed geometric error for those levels. So fill such tiles with a
    // constant-height heightmap.
    const geometricError = tileProvider.getLevelMaximumGeometricError(tile.level);
    const minCutThroughRadius = ellipsoid.maximumRadius - geometricError;
    let maxTileWidth =
      Math.acos(minCutThroughRadius / ellipsoid.maximumRadius) * 4.0;

    // When the tile width is greater than maxTileWidth as computed above, the error
    // of a normal fill tile from globe curvature alone will exceed the allowed geometric
    // error. Terrain won't change that much. However, we can allow more error than that.
    // A little blockiness during load is acceptable. For the WGS84 ellipsoid and
    // standard geometric error setup, the value here will have us use a heightmap
    // at levels 1, 2, and 3.
    maxTileWidth *= 1.5;

    if (
      rectangle.width > maxTileWidth &&
      maximumHeight - minimumHeight <= geometricError
    ) {
      const terrainData = new HeightmapTerrainData({
        width: 9,
        height: 9,
        buffer: heightmapBuffer,
        structure: {
          // Use the maximum as the constant height so that this tile's skirt
          // covers any cracks with adjacent tiles.
          heightOffset: maximumHeight,
        },
      });

      const createMeshSyncOptions = scratchCreateMeshSyncOptions;
      createMeshSyncOptions.tilingScheme = tile.tilingScheme;
      createMeshSyncOptions.x = tile.x;
      createMeshSyncOptions.y = tile.y;
      createMeshSyncOptions.level = tile.level;
      createMeshSyncOptions.exaggeration = exaggeration;
      createMeshSyncOptions.exaggerationRelativeHeight = exaggerationRelativeHeight;

      fill.mesh = terrainData._createMeshSync(createMeshSyncOptions);
    } else {
      const hasGeodeticSurfaceNormals = hasExaggeration;
      const centerCartographic = Rectangle.center(
        rectangle,
        centerCartographicScratch
      );
      centerCartographic.height = middleHeight;
      const center = ellipsoid.cartographicToCartesian(
        centerCartographic,
        scratchCenter$2
      );
      const encoding = new TerrainEncoding(
        center,
        undefined,
        undefined,
        undefined,
        undefined,
        true,
        true,
        hasGeodeticSurfaceNormals,
        exaggeration,
        exaggerationRelativeHeight
      );

      // At _most_, we have vertices for the 4 corners, plus 1 center, plus every adjacent edge vertex.
      // In reality there will be less most of the time, but close enough; better
      // to overestimate than to re-allocate/copy/traverse the vertices twice.
      // Also, we'll often be able to squeeze the index data into the extra space in the buffer.
      let maxVertexCount = 5;
      let meshes;

      meshes = fill.westMeshes;
      for (i = 0, len = meshes.length; i < len; ++i) {
        maxVertexCount += meshes[i].eastIndicesNorthToSouth.length;
      }

      meshes = fill.southMeshes;
      for (i = 0, len = meshes.length; i < len; ++i) {
        maxVertexCount += meshes[i].northIndicesWestToEast.length;
      }

      meshes = fill.eastMeshes;
      for (i = 0, len = meshes.length; i < len; ++i) {
        maxVertexCount += meshes[i].westIndicesSouthToNorth.length;
      }

      meshes = fill.northMeshes;
      for (i = 0, len = meshes.length; i < len; ++i) {
        maxVertexCount += meshes[i].southIndicesEastToWest.length;
      }

      const heightRange = heightRangeScratch;
      heightRange.minimumHeight = minimumHeight;
      heightRange.maximumHeight = maximumHeight;

      const stride = encoding.stride;
      let typedArray = new Float32Array(maxVertexCount * stride);

      let nextIndex = 0;
      const northwestIndex = nextIndex;
      nextIndex = addVertexWithComputedPosition(
        ellipsoid,
        rectangle,
        encoding,
        typedArray,
        nextIndex,
        0.0,
        1.0,
        nwCorner.height,
        nwCorner.encodedNormal,
        1.0,
        heightRange
      );
      nextIndex = addEdge(
        fill,
        ellipsoid,
        encoding,
        typedArray,
        nextIndex,
        fill.westTiles,
        fill.westMeshes,
        TileEdge.EAST,
        heightRange
      );
      const southwestIndex = nextIndex;
      nextIndex = addVertexWithComputedPosition(
        ellipsoid,
        rectangle,
        encoding,
        typedArray,
        nextIndex,
        0.0,
        0.0,
        swCorner.height,
        swCorner.encodedNormal,
        0.0,
        heightRange
      );
      nextIndex = addEdge(
        fill,
        ellipsoid,
        encoding,
        typedArray,
        nextIndex,
        fill.southTiles,
        fill.southMeshes,
        TileEdge.NORTH,
        heightRange
      );
      const southeastIndex = nextIndex;
      nextIndex = addVertexWithComputedPosition(
        ellipsoid,
        rectangle,
        encoding,
        typedArray,
        nextIndex,
        1.0,
        0.0,
        seCorner.height,
        seCorner.encodedNormal,
        0.0,
        heightRange
      );
      nextIndex = addEdge(
        fill,
        ellipsoid,
        encoding,
        typedArray,
        nextIndex,
        fill.eastTiles,
        fill.eastMeshes,
        TileEdge.WEST,
        heightRange
      );
      const northeastIndex = nextIndex;
      nextIndex = addVertexWithComputedPosition(
        ellipsoid,
        rectangle,
        encoding,
        typedArray,
        nextIndex,
        1.0,
        1.0,
        neCorner.height,
        neCorner.encodedNormal,
        1.0,
        heightRange
      );
      nextIndex = addEdge(
        fill,
        ellipsoid,
        encoding,
        typedArray,
        nextIndex,
        fill.northTiles,
        fill.northMeshes,
        TileEdge.SOUTH,
        heightRange
      );

      minimumHeight = heightRange.minimumHeight;
      maximumHeight = heightRange.maximumHeight;

      const obb = OrientedBoundingBox.fromRectangle(
        rectangle,
        minimumHeight,
        maximumHeight,
        tile.tilingScheme.ellipsoid
      );

      // Add a single vertex at the center of the tile.
      const southMercatorY = WebMercatorProjection.geodeticLatitudeToMercatorAngle(
        rectangle.south
      );
      const oneOverMercatorHeight =
        1.0 /
        (WebMercatorProjection.geodeticLatitudeToMercatorAngle(rectangle.north) -
          southMercatorY);
      const centerWebMercatorT =
        (WebMercatorProjection.geodeticLatitudeToMercatorAngle(
          centerCartographic.latitude
        ) -
          southMercatorY) *
        oneOverMercatorHeight;

      const geodeticSurfaceNormal = ellipsoid.geodeticSurfaceNormalCartographic(
        cartographicScratch$1,
        normalScratch
      );
      const centerEncodedNormal = AttributeCompression.octEncode(
        geodeticSurfaceNormal,
        octEncodedNormalScratch
      );

      const centerIndex = nextIndex;
      encoding.encode(
        typedArray,
        nextIndex * stride,
        obb.center,
        Cartesian2.fromElements(0.5, 0.5, uvScratch),
        middleHeight,
        centerEncodedNormal,
        centerWebMercatorT,
        geodeticSurfaceNormal
      );
      ++nextIndex;

      const vertexCount = nextIndex;

      const bytesPerIndex = vertexCount < 256 ? 1 : 2;
      const indexCount = (vertexCount - 1) * 3; // one triangle per edge vertex
      const indexDataBytes = indexCount * bytesPerIndex;
      const availableBytesInBuffer =
        (typedArray.length - vertexCount * stride) *
        Float32Array.BYTES_PER_ELEMENT;

      let indices;
      if (availableBytesInBuffer >= indexDataBytes) {
        // Store the index data in the same buffer as the vertex data.
        const startIndex = vertexCount * stride * Float32Array.BYTES_PER_ELEMENT;
        indices =
          vertexCount < 256
            ? new Uint8Array(typedArray.buffer, startIndex, indexCount)
            : new Uint16Array(typedArray.buffer, startIndex, indexCount);
      } else {
        // Allocate a new buffer for the index data.
        indices =
          vertexCount < 256
            ? new Uint8Array(indexCount)
            : new Uint16Array(indexCount);
      }

      typedArray = new Float32Array(typedArray.buffer, 0, vertexCount * stride);

      let indexOut = 0;
      for (i = 0; i < vertexCount - 2; ++i) {
        indices[indexOut++] = centerIndex;
        indices[indexOut++] = i;
        indices[indexOut++] = i + 1;
      }

      indices[indexOut++] = centerIndex;
      indices[indexOut++] = i;
      indices[indexOut++] = 0;

      const westIndicesSouthToNorth = [];
      for (i = southwestIndex; i >= northwestIndex; --i) {
        westIndicesSouthToNorth.push(i);
      }

      const southIndicesEastToWest = [];
      for (i = southeastIndex; i >= southwestIndex; --i) {
        southIndicesEastToWest.push(i);
      }

      const eastIndicesNorthToSouth = [];
      for (i = northeastIndex; i >= southeastIndex; --i) {
        eastIndicesNorthToSouth.push(i);
      }

      const northIndicesWestToEast = [];
      northIndicesWestToEast.push(0);
      for (i = centerIndex - 1; i >= northeastIndex; --i) {
        northIndicesWestToEast.push(i);
      }

      fill.mesh = new TerrainMesh(
        encoding.center,
        typedArray,
        indices,
        indexCount,
        vertexCount,
        minimumHeight,
        maximumHeight,
        BoundingSphere.fromOrientedBoundingBox(obb),
        computeOccludeePoint$1(
          tileProvider,
          obb.center,
          rectangle,
          minimumHeight,
          maximumHeight
        ),
        encoding.stride,
        obb,
        encoding,
        westIndicesSouthToNorth,
        southIndicesEastToWest,
        eastIndicesNorthToSouth,
        northIndicesWestToEast
      );
    }

    const context = frameState.context;

    fill._destroyVertexArray(vertexArraysToDestroy);

    fill.vertexArray = GlobeSurfaceTile._createVertexArrayForMesh(
      context,
      fill.mesh
    );
    surfaceTile.processImagery(
      tile,
      tileProvider.terrainProvider,
      frameState,
      true
    );

    const oldTexture = fill.waterMaskTexture;
    fill.waterMaskTexture = undefined;

    if (tileProvider.terrainProvider.hasWaterMask) {
      const waterSourceTile = surfaceTile._findAncestorTileWithTerrainData(tile);
      if (
        defined(waterSourceTile) &&
        defined(waterSourceTile.data.waterMaskTexture)
      ) {
        fill.waterMaskTexture = waterSourceTile.data.waterMaskTexture;
        ++fill.waterMaskTexture.referenceCount;
        surfaceTile._computeWaterMaskTranslationAndScale(
          tile,
          waterSourceTile,
          fill.waterMaskTranslationAndScale
        );
      }
    }

    if (defined(oldTexture)) {
      --oldTexture.referenceCount;
      if (oldTexture.referenceCount === 0) {
        oldTexture.destroy();
      }
    }
  }

  function addVertexWithComputedPosition(
    ellipsoid,
    rectangle,
    encoding,
    buffer,
    index,
    u,
    v,
    height,
    encodedNormal,
    webMercatorT,
    heightRange
  ) {
    const cartographic = cartographicScratch$1;
    cartographic.longitude = CesiumMath.lerp(rectangle.west, rectangle.east, u);
    cartographic.latitude = CesiumMath.lerp(rectangle.south, rectangle.north, v);
    cartographic.height = height;
    const position = ellipsoid.cartographicToCartesian(
      cartographic,
      cartesianScratch
    );

    let geodeticSurfaceNormal;
    if (encoding.hasGeodeticSurfaceNormals) {
      geodeticSurfaceNormal = ellipsoid.geodeticSurfaceNormal(
        position,
        normalScratch
      );
    }

    const uv = uvScratch2;
    uv.x = u;
    uv.y = v;

    encoding.encode(
      buffer,
      index * encoding.stride,
      position,
      uv,
      height,
      encodedNormal,
      webMercatorT,
      geodeticSurfaceNormal
    );

    heightRange.minimumHeight = Math.min(heightRange.minimumHeight, height);
    heightRange.maximumHeight = Math.max(heightRange.maximumHeight, height);

    return index + 1;
  }

  const sourceRectangleScratch = new Rectangle();

  function transformTextureCoordinates(
    sourceTile,
    targetTile,
    coordinates,
    result
  ) {
    let sourceRectangle = sourceTile.rectangle;
    const targetRectangle = targetTile.rectangle;

    // Handle transforming across the anti-meridian.
    if (
      targetTile.x === 0 &&
      coordinates.x === 1.0 &&
      sourceTile.x ===
        sourceTile.tilingScheme.getNumberOfXTilesAtLevel(sourceTile.level) - 1
    ) {
      sourceRectangle = Rectangle.clone(
        sourceTile.rectangle,
        sourceRectangleScratch
      );
      sourceRectangle.west -= CesiumMath.TWO_PI;
      sourceRectangle.east -= CesiumMath.TWO_PI;
    } else if (
      sourceTile.x === 0 &&
      coordinates.x === 0.0 &&
      targetTile.x ===
        targetTile.tilingScheme.getNumberOfXTilesAtLevel(targetTile.level) - 1
    ) {
      sourceRectangle = Rectangle.clone(
        sourceTile.rectangle,
        sourceRectangleScratch
      );
      sourceRectangle.west += CesiumMath.TWO_PI;
      sourceRectangle.east += CesiumMath.TWO_PI;
    }

    const sourceWidth = sourceRectangle.east - sourceRectangle.west;
    const umin = (targetRectangle.west - sourceRectangle.west) / sourceWidth;
    const umax = (targetRectangle.east - sourceRectangle.west) / sourceWidth;

    const sourceHeight = sourceRectangle.north - sourceRectangle.south;
    const vmin = (targetRectangle.south - sourceRectangle.south) / sourceHeight;
    const vmax = (targetRectangle.north - sourceRectangle.south) / sourceHeight;

    let u = (coordinates.x - umin) / (umax - umin);
    let v = (coordinates.y - vmin) / (vmax - vmin);

    // Ensure that coordinates very near the corners are at the corners.
    if (Math.abs(u) < Math.EPSILON5) {
      u = 0.0;
    } else if (Math.abs(u - 1.0) < Math.EPSILON5) {
      u = 1.0;
    }

    if (Math.abs(v) < Math.EPSILON5) {
      v = 0.0;
    } else if (Math.abs(v - 1.0) < Math.EPSILON5) {
      v = 1.0;
    }

    result.x = u;
    result.y = v;
    return result;
  }

  const encodedNormalScratch = new Cartesian2();

  function getVertexFromTileAtCorner(sourceMesh, sourceIndex, u, v, vertex) {
    const sourceEncoding = sourceMesh.encoding;
    const sourceVertices = sourceMesh.vertices;

    vertex.height = sourceEncoding.decodeHeight(sourceVertices, sourceIndex);

    if (sourceEncoding.hasVertexNormals) {
      sourceEncoding.getOctEncodedNormal(
        sourceVertices,
        sourceIndex,
        vertex.encodedNormal
      );
    } else {
      const normal = vertex.encodedNormal;
      normal.x = 0.0;
      normal.y = 0.0;
    }
  }

  const encodedNormalScratch2 = new Cartesian2();
  const cartesianScratch2 = new Cartesian3();

  function getInterpolatedVertexAtCorner(
    ellipsoid,
    sourceTile,
    targetTile,
    sourceMesh,
    previousIndex,
    nextIndex,
    u,
    v,
    interpolateU,
    vertex
  ) {
    const sourceEncoding = sourceMesh.encoding;
    const sourceVertices = sourceMesh.vertices;

    const previousUv = transformTextureCoordinates(
      sourceTile,
      targetTile,
      sourceEncoding.decodeTextureCoordinates(
        sourceVertices,
        previousIndex,
        uvScratch
      ),
      uvScratch
    );
    const nextUv = transformTextureCoordinates(
      sourceTile,
      targetTile,
      sourceEncoding.decodeTextureCoordinates(
        sourceVertices,
        nextIndex,
        uvScratch2
      ),
      uvScratch2
    );

    let ratio;
    if (interpolateU) {
      ratio = (u - previousUv.x) / (nextUv.x - previousUv.x);
    } else {
      ratio = (v - previousUv.y) / (nextUv.y - previousUv.y);
    }

    const height1 = sourceEncoding.decodeHeight(sourceVertices, previousIndex);
    const height2 = sourceEncoding.decodeHeight(sourceVertices, nextIndex);

    const targetRectangle = targetTile.rectangle;
    cartographicScratch$1.longitude = CesiumMath.lerp(
      targetRectangle.west,
      targetRectangle.east,
      u
    );
    cartographicScratch$1.latitude = CesiumMath.lerp(
      targetRectangle.south,
      targetRectangle.north,
      v
    );
    vertex.height = cartographicScratch$1.height = CesiumMath.lerp(
      height1,
      height2,
      ratio
    );

    let normal;
    if (sourceEncoding.hasVertexNormals) {
      const encodedNormal1 = sourceEncoding.getOctEncodedNormal(
        sourceVertices,
        previousIndex,
        encodedNormalScratch
      );
      const encodedNormal2 = sourceEncoding.getOctEncodedNormal(
        sourceVertices,
        nextIndex,
        encodedNormalScratch2
      );
      const normal1 = AttributeCompression.octDecode(
        encodedNormal1.x,
        encodedNormal1.y,
        cartesianScratch
      );
      const normal2 = AttributeCompression.octDecode(
        encodedNormal2.x,
        encodedNormal2.y,
        cartesianScratch2
      );
      normal = Cartesian3.lerp(normal1, normal2, ratio, cartesianScratch);
      Cartesian3.normalize(normal, normal);
      AttributeCompression.octEncode(normal, vertex.encodedNormal);
    } else {
      normal = ellipsoid.geodeticSurfaceNormalCartographic(
        cartographicScratch$1,
        cartesianScratch
      );
      AttributeCompression.octEncode(normal, vertex.encodedNormal);
    }
  }

  function getVertexWithHeightAtCorner(
    terrainFillMesh,
    ellipsoid,
    u,
    v,
    height,
    vertex
  ) {
    vertex.height = height;
    const normal = ellipsoid.geodeticSurfaceNormalCartographic(
      cartographicScratch$1,
      cartesianScratch
    );
    AttributeCompression.octEncode(normal, vertex.encodedNormal);
  }

  function getCorner(
    terrainFillMesh,
    ellipsoid,
    u,
    v,
    cornerTile,
    cornerMesh,
    previousEdgeTiles,
    previousEdgeMeshes,
    nextEdgeTiles,
    nextEdgeMeshes,
    vertex
  ) {
    const gotCorner =
      getCornerFromEdge(
        terrainFillMesh,
        ellipsoid,
        previousEdgeMeshes,
        previousEdgeTiles,
        false,
        u,
        v,
        vertex
      ) ||
      getCornerFromEdge(
        terrainFillMesh,
        ellipsoid,
        nextEdgeMeshes,
        nextEdgeTiles,
        true,
        u,
        v,
        vertex
      );
    if (gotCorner) {
      return vertex;
    }

    let vertexIndex;

    if (meshIsUsable(cornerTile, cornerMesh)) {
      // Corner mesh is valid, copy its corner vertex to this mesh.
      if (u === 0.0) {
        if (v === 0.0) {
          // southwest destination, northeast source
          vertexIndex = cornerMesh.eastIndicesNorthToSouth[0];
        } else {
          // northwest destination, southeast source
          vertexIndex = cornerMesh.southIndicesEastToWest[0];
        }
      } else if (v === 0.0) {
        // southeast destination, northwest source
        vertexIndex = cornerMesh.northIndicesWestToEast[0];
      } else {
        // northeast destination, southwest source
        vertexIndex = cornerMesh.westIndicesSouthToNorth[0];
      }
      getVertexFromTileAtCorner(cornerMesh, vertexIndex, u, v, vertex);
      return vertex;
    }

    // There is no precise vertex available from the corner or from either adjacent edge.
    // This is either because there are no tiles at all at the edges and corner, or
    // because the tiles at the edge are higher-level-number and don't extend all the way
    // to the corner.
    // Try to grab a height from the adjacent edges.
    let height;
    if (u === 0.0) {
      if (v === 0.0) {
        // southwest
        height = getClosestHeightToCorner(
          terrainFillMesh.westMeshes,
          terrainFillMesh.westTiles,
          TileEdge.EAST,
          terrainFillMesh.southMeshes,
          terrainFillMesh.southTiles,
          TileEdge.NORTH);
      } else {
        // northwest
        height = getClosestHeightToCorner(
          terrainFillMesh.northMeshes,
          terrainFillMesh.northTiles,
          TileEdge.SOUTH,
          terrainFillMesh.westMeshes,
          terrainFillMesh.westTiles,
          TileEdge.EAST);
      }
    } else if (v === 0.0) {
      // southeast
      height = getClosestHeightToCorner(
        terrainFillMesh.southMeshes,
        terrainFillMesh.southTiles,
        TileEdge.NORTH,
        terrainFillMesh.eastMeshes,
        terrainFillMesh.eastTiles,
        TileEdge.WEST);
    } else {
      // northeast
      height = getClosestHeightToCorner(
        terrainFillMesh.eastMeshes,
        terrainFillMesh.eastTiles,
        TileEdge.WEST,
        terrainFillMesh.northMeshes,
        terrainFillMesh.northTiles,
        TileEdge.SOUTH);
    }

    if (defined(height)) {
      getVertexWithHeightAtCorner(
        terrainFillMesh,
        ellipsoid,
        u,
        v,
        height,
        vertex
      );
      return vertex;
    }

    // No heights available that are closer than the adjacent corners.
    return undefined;
  }

  function getClosestHeightToCorner(
    previousMeshes,
    previousTiles,
    previousEdge,
    nextMeshes,
    nextTiles,
    nextEdge,
    u,
    v
  ) {
    const height1 = getNearestHeightOnEdge(
      previousMeshes,
      previousTiles,
      false,
      previousEdge);
    const height2 = getNearestHeightOnEdge(
      nextMeshes,
      nextTiles,
      true,
      nextEdge);
    if (defined(height1) && defined(height2)) {
      // It would be slightly better to do a weighted average of the two heights
      // based on their distance from the corner, but it shouldn't matter much in practice.
      return (height1 + height2) * 0.5;
    } else if (defined(height1)) {
      return height1;
    }
    return height2;
  }

  function addEdge(
    terrainFillMesh,
    ellipsoid,
    encoding,
    typedArray,
    nextIndex,
    edgeTiles,
    edgeMeshes,
    tileEdge,
    heightRange
  ) {
    for (let i = 0; i < edgeTiles.length; ++i) {
      nextIndex = addEdgeMesh(
        terrainFillMesh,
        ellipsoid,
        encoding,
        typedArray,
        nextIndex,
        edgeTiles[i],
        edgeMeshes[i],
        tileEdge,
        heightRange
      );
    }
    return nextIndex;
  }

  function addEdgeMesh(
    terrainFillMesh,
    ellipsoid,
    encoding,
    typedArray,
    nextIndex,
    edgeTile,
    edgeMesh,
    tileEdge,
    heightRange
  ) {
    // Handle copying edges across the anti-meridian.
    let sourceRectangle = edgeTile.rectangle;
    if (tileEdge === TileEdge.EAST && terrainFillMesh.tile.x === 0) {
      sourceRectangle = Rectangle.clone(
        edgeTile.rectangle,
        sourceRectangleScratch
      );
      sourceRectangle.west -= CesiumMath.TWO_PI;
      sourceRectangle.east -= CesiumMath.TWO_PI;
    } else if (tileEdge === TileEdge.WEST && edgeTile.x === 0) {
      sourceRectangle = Rectangle.clone(
        edgeTile.rectangle,
        sourceRectangleScratch
      );
      sourceRectangle.west += CesiumMath.TWO_PI;
      sourceRectangle.east += CesiumMath.TWO_PI;
    }

    const targetRectangle = terrainFillMesh.tile.rectangle;

    let lastU;
    let lastV;

    if (nextIndex > 0) {
      encoding.decodeTextureCoordinates(typedArray, nextIndex - 1, uvScratch);
      lastU = uvScratch.x;
      lastV = uvScratch.y;
    }

    let indices;
    let compareU;

    switch (tileEdge) {
      case TileEdge.WEST:
        indices = edgeMesh.westIndicesSouthToNorth;
        compareU = false;
        break;
      case TileEdge.NORTH:
        indices = edgeMesh.northIndicesWestToEast;
        compareU = true;
        break;
      case TileEdge.EAST:
        indices = edgeMesh.eastIndicesNorthToSouth;
        compareU = false;
        break;
      case TileEdge.SOUTH:
        indices = edgeMesh.southIndicesEastToWest;
        compareU = true;
        break;
    }

    const sourceTile = edgeTile;
    const targetTile = terrainFillMesh.tile;
    const sourceEncoding = edgeMesh.encoding;
    const sourceVertices = edgeMesh.vertices;
    const targetStride = encoding.stride;

    let southMercatorY;
    let oneOverMercatorHeight;
    if (sourceEncoding.hasWebMercatorT) {
      southMercatorY = WebMercatorProjection.geodeticLatitudeToMercatorAngle(
        targetRectangle.south
      );
      oneOverMercatorHeight =
        1.0 /
        (WebMercatorProjection.geodeticLatitudeToMercatorAngle(
          targetRectangle.north
        ) -
          southMercatorY);
    }

    for (let i = 0; i < indices.length; ++i) {
      const index = indices[i];

      const uv = sourceEncoding.decodeTextureCoordinates(
        sourceVertices,
        index,
        uvScratch
      );
      transformTextureCoordinates(sourceTile, targetTile, uv, uv);
      const u = uv.x;
      const v = uv.y;
      const uOrV = compareU ? u : v;

      if (uOrV < 0.0 || uOrV > 1.0) {
        // Vertex is outside the target tile - skip it.
        continue;
      }

      if (
        Math.abs(u - lastU) < CesiumMath.EPSILON5 &&
        Math.abs(v - lastV) < CesiumMath.EPSILON5
      ) {
        // Vertex is very close to the previous one - skip it.
        continue;
      }

      const nearlyEdgeU =
        Math.abs(u) < CesiumMath.EPSILON5 ||
        Math.abs(u - 1.0) < CesiumMath.EPSILON5;
      const nearlyEdgeV =
        Math.abs(v) < CesiumMath.EPSILON5 ||
        Math.abs(v - 1.0) < CesiumMath.EPSILON5;

      if (nearlyEdgeU && nearlyEdgeV) {
        // Corner vertex - skip it.
        continue;
      }

      const position = sourceEncoding.decodePosition(
        sourceVertices,
        index,
        cartesianScratch
      );
      const height = sourceEncoding.decodeHeight(sourceVertices, index);

      let normal;
      if (sourceEncoding.hasVertexNormals) {
        normal = sourceEncoding.getOctEncodedNormal(
          sourceVertices,
          index,
          octEncodedNormalScratch
        );
      } else {
        normal = octEncodedNormalScratch;
        normal.x = 0.0;
        normal.y = 0.0;
      }

      let webMercatorT = v;
      if (sourceEncoding.hasWebMercatorT) {
        const latitude = CesiumMath.lerp(
          targetRectangle.south,
          targetRectangle.north,
          v
        );
        webMercatorT =
          (WebMercatorProjection.geodeticLatitudeToMercatorAngle(latitude) -
            southMercatorY) *
          oneOverMercatorHeight;
      }

      let geodeticSurfaceNormal;
      if (encoding.hasGeodeticSurfaceNormals) {
        geodeticSurfaceNormal = ellipsoid.geodeticSurfaceNormal(
          position,
          normalScratch
        );
      }

      encoding.encode(
        typedArray,
        nextIndex * targetStride,
        position,
        uv,
        height,
        normal,
        webMercatorT,
        geodeticSurfaceNormal
      );

      heightRange.minimumHeight = Math.min(heightRange.minimumHeight, height);
      heightRange.maximumHeight = Math.max(heightRange.maximumHeight, height);

      ++nextIndex;
    }

    return nextIndex;
  }

  function getNearestHeightOnEdge(meshes, tiles, isNext, edge, u, v) {
    let meshStart;
    let meshEnd;
    let meshStep;

    if (isNext) {
      meshStart = 0;
      meshEnd = meshes.length;
      meshStep = 1;
    } else {
      meshStart = meshes.length - 1;
      meshEnd = -1;
      meshStep = -1;
    }

    for (
      let meshIndex = meshStart;
      meshIndex !== meshEnd;
      meshIndex += meshStep
    ) {
      const mesh = meshes[meshIndex];
      const tile = tiles[meshIndex];
      if (!meshIsUsable(tile, mesh)) {
        continue;
      }

      let indices;
      switch (edge) {
        case TileEdge.WEST:
          indices = mesh.westIndicesSouthToNorth;
          break;
        case TileEdge.SOUTH:
          indices = mesh.southIndicesEastToWest;
          break;
        case TileEdge.EAST:
          indices = mesh.eastIndicesNorthToSouth;
          break;
        case TileEdge.NORTH:
          indices = mesh.northIndicesWestToEast;
          break;
      }

      const index = indices[isNext ? 0 : indices.length - 1];
      if (defined(index)) {
        return mesh.encoding.decodeHeight(mesh.vertices, index);
      }
    }

    return undefined;
  }

  function meshIsUsable(tile, mesh) {
    return (
      defined(mesh) &&
      (!defined(tile.data.fill) || !tile.data.fill.changedThisFrame)
    );
  }

  function getCornerFromEdge(
    terrainFillMesh,
    ellipsoid,
    edgeMeshes,
    edgeTiles,
    isNext,
    u,
    v,
    vertex
  ) {
    let edgeVertices;
    let compareU;
    let increasing;
    let vertexIndexIndex;
    let vertexIndex;
    const sourceTile = edgeTiles[isNext ? 0 : edgeMeshes.length - 1];
    const sourceMesh = edgeMeshes[isNext ? 0 : edgeMeshes.length - 1];

    if (meshIsUsable(sourceTile, sourceMesh)) {
      // Previous mesh is valid, but we don't know yet if it covers this corner.
      if (u === 0.0) {
        if (v === 0.0) {
          // southwest
          edgeVertices = isNext
            ? sourceMesh.northIndicesWestToEast
            : sourceMesh.eastIndicesNorthToSouth;
          compareU = isNext;
          increasing = isNext;
        } else {
          // northwest
          edgeVertices = isNext
            ? sourceMesh.eastIndicesNorthToSouth
            : sourceMesh.southIndicesEastToWest;
          compareU = !isNext;
          increasing = false;
        }
      } else if (v === 0.0) {
        // southeast
        edgeVertices = isNext
          ? sourceMesh.westIndicesSouthToNorth
          : sourceMesh.northIndicesWestToEast;
        compareU = !isNext;
        increasing = true;
      } else {
        // northeast
        edgeVertices = isNext
          ? sourceMesh.southIndicesEastToWest
          : sourceMesh.westIndicesSouthToNorth;
        compareU = isNext;
        increasing = !isNext;
      }

      if (edgeVertices.length > 0) {
        // The vertex we want will very often be the first/last vertex so check that first.
        vertexIndexIndex = isNext ? 0 : edgeVertices.length - 1;
        vertexIndex = edgeVertices[vertexIndexIndex];
        sourceMesh.encoding.decodeTextureCoordinates(
          sourceMesh.vertices,
          vertexIndex,
          uvScratch
        );
        const targetUv = transformTextureCoordinates(
          sourceTile,
          terrainFillMesh.tile,
          uvScratch,
          uvScratch
        );
        if (targetUv.x === u && targetUv.y === v) {
          // Vertex is good!
          getVertexFromTileAtCorner(sourceMesh, vertexIndex, u, v, vertex);
          return true;
        }

        // The last vertex is not the one we need, try binary searching for the right one.
        vertexIndexIndex = binarySearch(edgeVertices, compareU ? u : v, function (
          vertexIndex,
          textureCoordinate
        ) {
          sourceMesh.encoding.decodeTextureCoordinates(
            sourceMesh.vertices,
            vertexIndex,
            uvScratch
          );
          const targetUv = transformTextureCoordinates(
            sourceTile,
            terrainFillMesh.tile,
            uvScratch,
            uvScratch
          );
          if (increasing) {
            if (compareU) {
              return targetUv.x - u;
            }
            return targetUv.y - v;
          } else if (compareU) {
            return u - targetUv.x;
          }
          return v - targetUv.y;
        });

        if (vertexIndexIndex < 0) {
          vertexIndexIndex = ~vertexIndexIndex;

          if (vertexIndexIndex > 0 && vertexIndexIndex < edgeVertices.length) {
            // The corner falls between two vertices, so interpolate between them.
            getInterpolatedVertexAtCorner(
              ellipsoid,
              sourceTile,
              terrainFillMesh.tile,
              sourceMesh,
              edgeVertices[vertexIndexIndex - 1],
              edgeVertices[vertexIndexIndex],
              u,
              v,
              compareU,
              vertex
            );
            return true;
          }
        } else {
          // Found a vertex that fits in the corner exactly.
          getVertexFromTileAtCorner(
            sourceMesh,
            edgeVertices[vertexIndexIndex],
            u,
            v,
            vertex
          );
          return true;
        }
      }
    }

    return false;
  }

  const cornerPositionsScratch$1 = [
    new Cartesian3(),
    new Cartesian3(),
    new Cartesian3(),
    new Cartesian3(),
  ];

  function computeOccludeePoint$1(
    tileProvider,
    center,
    rectangle,
    minimumHeight,
    maximumHeight,
    result
  ) {
    const ellipsoidalOccluder = tileProvider.quadtree._occluders.ellipsoid;
    const ellipsoid = ellipsoidalOccluder.ellipsoid;

    const cornerPositions = cornerPositionsScratch$1;
    Cartesian3.fromRadians(
      rectangle.west,
      rectangle.south,
      maximumHeight,
      ellipsoid,
      cornerPositions[0]
    );
    Cartesian3.fromRadians(
      rectangle.east,
      rectangle.south,
      maximumHeight,
      ellipsoid,
      cornerPositions[1]
    );
    Cartesian3.fromRadians(
      rectangle.west,
      rectangle.north,
      maximumHeight,
      ellipsoid,
      cornerPositions[2]
    );
    Cartesian3.fromRadians(
      rectangle.east,
      rectangle.north,
      maximumHeight,
      ellipsoid,
      cornerPositions[3]
    );

    return ellipsoidalOccluder.computeHorizonCullingPointPossiblyUnderEllipsoid(
      center,
      cornerPositions,
      minimumHeight,
      result
    );
  }

  /**
   * Provides quadtree tiles representing the surface of the globe.  This type is intended to be used
   * with {@link QuadtreePrimitive}.
   *
   * @alias GlobeSurfaceTileProvider
   * @constructor
   *
   * @param {TerrainProvider} options.terrainProvider The terrain provider that describes the surface geometry.
   * @param {ImageryLayerCollection} option.imageryLayers The collection of imagery layers describing the shading of the surface.
   * @param {GlobeSurfaceShaderSet} options.surfaceShaderSet The set of shaders used to render the surface.
   *
   * @private
   */
  function GlobeSurfaceTileProvider(options) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(options)) {
      throw new DeveloperError("options is required.");
    }
    if (!defined(options.terrainProvider)) {
      throw new DeveloperError("options.terrainProvider is required.");
    } else if (!defined(options.imageryLayers)) {
      throw new DeveloperError("options.imageryLayers is required.");
    } else if (!defined(options.surfaceShaderSet)) {
      throw new DeveloperError("options.surfaceShaderSet is required.");
    }
    //>>includeEnd('debug');

    this.lightingFadeOutDistance = 6500000.0;
    this.lightingFadeInDistance = 9000000.0;
    this.hasWaterMask = false;
    this.oceanNormalMap = undefined;
    this.zoomedOutOceanSpecularIntensity = 0.5;
    this.enableLighting = false;
    this.dynamicAtmosphereLighting = false;
    this.dynamicAtmosphereLightingFromSun = false;
    this.showGroundAtmosphere = false;
    this.shadows = ShadowMode$1.RECEIVE_ONLY;

    /**
     * The color to use to highlight terrain fill tiles. If undefined, fill tiles are not
     * highlighted at all. The alpha value is used to alpha blend with the tile's
     * actual color. Because terrain fill tiles do not represent the actual terrain surface,
     * it may be useful in some applications to indicate visually that they are not to be trusted.
     * @type {Color}
     * @default undefined
     */
    this.fillHighlightColor = undefined;

    this.hueShift = 0.0;
    this.saturationShift = 0.0;
    this.brightnessShift = 0.0;

    this.showSkirts = true;
    this.backFaceCulling = true;
    this.undergroundColor = undefined;
    this.undergroundColorAlphaByDistance = undefined;

    this.lambertDiffuseMultiplier = 0.0;

    this.materialUniformMap = undefined;
    this._materialUniformMap = undefined;

    this._quadtree = undefined;
    this._terrainProvider = options.terrainProvider;
    this._imageryLayers = options.imageryLayers;
    this._surfaceShaderSet = options.surfaceShaderSet;

    this._renderState = undefined;
    this._blendRenderState = undefined;
    this._disableCullingRenderState = undefined;
    this._disableCullingBlendRenderState = undefined;

    this._errorEvent = new Event();

    this._imageryLayers.layerAdded.addEventListener(
      GlobeSurfaceTileProvider.prototype._onLayerAdded,
      this
    );
    this._imageryLayers.layerRemoved.addEventListener(
      GlobeSurfaceTileProvider.prototype._onLayerRemoved,
      this
    );
    this._imageryLayers.layerMoved.addEventListener(
      GlobeSurfaceTileProvider.prototype._onLayerMoved,
      this
    );
    this._imageryLayers.layerShownOrHidden.addEventListener(
      GlobeSurfaceTileProvider.prototype._onLayerShownOrHidden,
      this
    );
    this._imageryLayersUpdatedEvent = new Event();

    this._layerOrderChanged = false;

    this._tilesToRenderByTextureCount = [];
    this._drawCommands = [];
    this._uniformMaps = [];
    this._usedDrawCommands = 0;

    this._vertexArraysToDestroy = [];

    this._debug = {
      wireframe: false,
      boundingSphereTile: undefined,
    };

    this._baseColor = undefined;
    this._firstPassInitialColor = undefined;
    this.baseColor = new Color(0.0, 0.0, 0.5, 1.0);

    /**
     * A property specifying a {@link ClippingPlaneCollection} used to selectively disable rendering on the outside of each plane.
     * @type {ClippingPlaneCollection}
     * @private
     */
    this._clippingPlanes = undefined;

    /**
     * A property specifying a {@link Rectangle} used to selectively limit terrain and imagery rendering.
     * @type {Rectangle}
     */
    this.cartographicLimitRectangle = Rectangle.clone(Rectangle.MAX_VALUE);

    this._hasLoadedTilesThisFrame = false;
    this._hasFillTilesThisFrame = false;

    this._oldTerrainExaggeration = undefined;
    this._oldTerrainExaggerationRelativeHeight = undefined;
  }

  Object.defineProperties(GlobeSurfaceTileProvider.prototype, {
    /**
     * Gets or sets the color of the globe when no imagery is available.
     * @memberof GlobeSurfaceTileProvider.prototype
     * @type {Color}
     */
    baseColor: {
      get: function () {
        return this._baseColor;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        this._baseColor = value;
        this._firstPassInitialColor = Cartesian4.fromColor(
          value,
          this._firstPassInitialColor
        );
      },
    },
    /**
     * Gets or sets the {@link QuadtreePrimitive} for which this provider is
     * providing tiles.  This property may be undefined if the provider is not yet associated
     * with a {@link QuadtreePrimitive}.
     * @memberof GlobeSurfaceTileProvider.prototype
     * @type {QuadtreePrimitive}
     */
    quadtree: {
      get: function () {
        return this._quadtree;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        this._quadtree = value;
      },
    },

    /**
     * Gets a value indicating whether or not the provider is ready for use.
     * @memberof GlobeSurfaceTileProvider.prototype
     * @type {Boolean}
     */
    ready: {
      get: function () {
        return (
          this._terrainProvider.ready &&
          (this._imageryLayers.length === 0 ||
            this._imageryLayers.get(0).imageryProvider.ready)
        );
      },
    },

    /**
     * Gets the tiling scheme used by the provider.  This property should
     * not be accessed before {@link GlobeSurfaceTileProvider#ready} returns true.
     * @memberof GlobeSurfaceTileProvider.prototype
     * @type {TilingScheme}
     */
    tilingScheme: {
      get: function () {
        return this._terrainProvider.tilingScheme;
      },
    },

    /**
     * Gets an event that is raised when the geometry provider encounters an asynchronous error.  By subscribing
     * to the event, you will be notified of the error and can potentially recover from it.  Event listeners
     * are passed an instance of {@link TileProviderError}.
     * @memberof GlobeSurfaceTileProvider.prototype
     * @type {Event}
     */
    errorEvent: {
      get: function () {
        return this._errorEvent;
      },
    },

    /**
     * Gets an event that is raised when an imagery layer is added, shown, hidden, moved, or removed.
     * @memberof GlobeSurfaceTileProvider.prototype
     * @type {Event}
     */
    imageryLayersUpdatedEvent: {
      get: function () {
        return this._imageryLayersUpdatedEvent;
      },
    },

    /**
     * Gets or sets the terrain provider that describes the surface geometry.
     * @memberof GlobeSurfaceTileProvider.prototype
     * @type {TerrainProvider}
     */
    terrainProvider: {
      get: function () {
        return this._terrainProvider;
      },
      set: function (terrainProvider) {
        if (this._terrainProvider === terrainProvider) {
          return;
        }

        //>>includeStart('debug', pragmas.debug);
        if (!defined(terrainProvider)) {
          throw new DeveloperError("terrainProvider is required.");
        }
        //>>includeEnd('debug');

        this._terrainProvider = terrainProvider;

        if (defined(this._quadtree)) {
          this._quadtree.invalidateAllTiles();
        }
      },
    },
    /**
     * The {@link ClippingPlaneCollection} used to selectively disable rendering the tileset.
     *
     * @type {ClippingPlaneCollection}
     *
     * @private
     */
    clippingPlanes: {
      get: function () {
        return this._clippingPlanes;
      },
      set: function (value) {
        ClippingPlaneCollection.setOwner(value, this, "_clippingPlanes");
      },
    },
  });

  function sortTileImageryByLayerIndex(a, b) {
    let aImagery = a.loadingImagery;
    if (!defined(aImagery)) {
      aImagery = a.readyImagery;
    }

    let bImagery = b.loadingImagery;
    if (!defined(bImagery)) {
      bImagery = b.readyImagery;
    }

    return aImagery.imageryLayer._layerIndex - bImagery.imageryLayer._layerIndex;
  }

  /**
   * Make updates to the tile provider that are not involved in rendering. Called before the render update cycle.
   */
  GlobeSurfaceTileProvider.prototype.update = function (frameState) {
    // update collection: imagery indices, base layers, raise layer show/hide event
    this._imageryLayers._update();
  };

  function updateCredits(surface, frameState) {
    const creditDisplay = frameState.creditDisplay;
    if (
      surface._terrainProvider.ready &&
      defined(surface._terrainProvider.credit)
    ) {
      creditDisplay.addCredit(surface._terrainProvider.credit);
    }

    const imageryLayers = surface._imageryLayers;
    for (let i = 0, len = imageryLayers.length; i < len; ++i) {
      const imageryProvider = imageryLayers.get(i).imageryProvider;
      if (imageryProvider.ready && defined(imageryProvider.credit)) {
        creditDisplay.addCredit(imageryProvider.credit);
      }
    }
  }

  /**
   * Called at the beginning of each render frame, before {@link QuadtreeTileProvider#showTileThisFrame}
   * @param {FrameState} frameState The frame state.
   */
  GlobeSurfaceTileProvider.prototype.initialize = function (frameState) {
    // update each layer for texture reprojection.
    this._imageryLayers.queueReprojectionCommands(frameState);

    if (this._layerOrderChanged) {
      this._layerOrderChanged = false;

      // Sort the TileImagery instances in each tile by the layer index.
      this._quadtree.forEachLoadedTile(function (tile) {
        tile.data.imagery.sort(sortTileImageryByLayerIndex);
      });
    }

    // Add credits for terrain and imagery providers.
    updateCredits(this, frameState);

    const vertexArraysToDestroy = this._vertexArraysToDestroy;
    const length = vertexArraysToDestroy.length;
    for (let j = 0; j < length; ++j) {
      GlobeSurfaceTile._freeVertexArray(vertexArraysToDestroy[j]);
    }
    vertexArraysToDestroy.length = 0;
  };

  /**
   * Called at the beginning of the update cycle for each render frame, before {@link QuadtreeTileProvider#showTileThisFrame}
   * or any other functions.
   *
   * @param {FrameState} frameState The frame state.
   */
  GlobeSurfaceTileProvider.prototype.beginUpdate = function (frameState) {
    const tilesToRenderByTextureCount = this._tilesToRenderByTextureCount;
    for (let i = 0, len = tilesToRenderByTextureCount.length; i < len; ++i) {
      const tiles = tilesToRenderByTextureCount[i];
      if (defined(tiles)) {
        tiles.length = 0;
      }
    }
    // update clipping planes
    const clippingPlanes = this._clippingPlanes;
    if (defined(clippingPlanes) && clippingPlanes.enabled) {
      clippingPlanes.update(frameState);
    }
    this._usedDrawCommands = 0;

    this._hasLoadedTilesThisFrame = false;
    this._hasFillTilesThisFrame = false;
  };

  /**
   * Called at the end of the update cycle for each render frame, after {@link QuadtreeTileProvider#showTileThisFrame}
   * and any other functions.
   *
   * @param {FrameState} frameState The frame state.
   */
  GlobeSurfaceTileProvider.prototype.endUpdate = function (frameState) {
    if (!defined(this._renderState)) {
      this._renderState = RenderState.fromCache({
        // Write color and depth
        cull: {
          enabled: true,
        },
        depthTest: {
          enabled: true,
          func: DepthFunction$1.LESS,
        },
      });

      this._blendRenderState = RenderState.fromCache({
        // Write color and depth
        cull: {
          enabled: true,
        },
        depthTest: {
          enabled: true,
          func: DepthFunction$1.LESS_OR_EQUAL,
        },
        blending: BlendingState$1.ALPHA_BLEND,
      });

      let rs = clone$1(this._renderState, true);
      rs.cull.enabled = false;
      this._disableCullingRenderState = RenderState.fromCache(rs);

      rs = clone$1(this._blendRenderState, true);
      rs.cull.enabled = false;
      this._disableCullingBlendRenderState = RenderState.fromCache(rs);
    }

    // If this frame has a mix of loaded and fill tiles, we need to propagate
    // loaded heights to the fill tiles.
    if (this._hasFillTilesThisFrame && this._hasLoadedTilesThisFrame) {
      TerrainFillMesh.updateFillTiles(
        this,
        this._quadtree._tilesToRender,
        frameState,
        this._vertexArraysToDestroy
      );
    }

    // When terrain exaggeration changes, all of the loaded tiles need to generate
    // geodetic surface normals so they can scale properly when rendered.
    // When exaggeration is reset, geodetic surface normals are removed to decrease
    // memory usage. Some tiles might have been constructed with the correct
    // exaggeration already, so skip over them.

    // If the geodetic surface normals can't be created because the tile doesn't
    // have a mesh, keep checking until the tile does have a mesh. This can happen
    // if the tile's mesh starts construction in a worker thread right before the
    // exaggeration changes.

    const quadtree = this.quadtree;
    const exaggeration = frameState.terrainExaggeration;
    const exaggerationRelativeHeight =
      frameState.terrainExaggerationRelativeHeight;
    const exaggerationChanged =
      this._oldTerrainExaggeration !== exaggeration ||
      this._oldTerrainExaggerationRelativeHeight !== exaggerationRelativeHeight;

    // Keep track of the next time there is a change in exaggeration
    this._oldTerrainExaggeration = exaggeration;
    this._oldTerrainExaggerationRelativeHeight = exaggerationRelativeHeight;

    if (exaggerationChanged) {
      quadtree.forEachLoadedTile(function (tile) {
        const surfaceTile = tile.data;
        surfaceTile.updateExaggeration(tile, frameState, quadtree);
      });
    }

    // Add the tile render commands to the command list, sorted by texture count.
    const tilesToRenderByTextureCount = this._tilesToRenderByTextureCount;
    for (
      let textureCountIndex = 0,
        textureCountLength = tilesToRenderByTextureCount.length;
      textureCountIndex < textureCountLength;
      ++textureCountIndex
    ) {
      const tilesToRender = tilesToRenderByTextureCount[textureCountIndex];
      if (!defined(tilesToRender)) {
        continue;
      }

      for (
        let tileIndex = 0, tileLength = tilesToRender.length;
        tileIndex < tileLength;
        ++tileIndex
      ) {
        const tile = tilesToRender[tileIndex];
        const tileBoundingRegion = tile.data.tileBoundingRegion;
        addDrawCommandsForTile(this, tile, frameState);
        frameState.minimumTerrainHeight = Math.min(
          frameState.minimumTerrainHeight,
          tileBoundingRegion.minimumHeight
        );
      }
    }
  };

  function pushCommand(command, frameState) {
    const globeTranslucencyState = frameState.globeTranslucencyState;
    if (globeTranslucencyState.translucent) {
      const isBlendCommand = command.renderState.blending.enabled;
      globeTranslucencyState.pushDerivedCommands(
        command,
        isBlendCommand,
        frameState
      );
    } else {
      frameState.commandList.push(command);
    }
  }

  /**
   * Adds draw commands for tiles rendered in the previous frame for a pick pass.
   *
   * @param {FrameState} frameState The frame state.
   */
  GlobeSurfaceTileProvider.prototype.updateForPick = function (frameState) {
    // Add the tile pick commands from the tiles drawn last frame.
    const drawCommands = this._drawCommands;
    for (let i = 0, length = this._usedDrawCommands; i < length; ++i) {
      pushCommand(drawCommands[i], frameState);
    }
  };

  /**
   * Cancels any imagery re-projections in the queue.
   */
  GlobeSurfaceTileProvider.prototype.cancelReprojections = function () {
    this._imageryLayers.cancelReprojections();
  };

  /**
   * Gets the maximum geometric error allowed in a tile at a given level, in meters.  This function should not be
   * called before {@link GlobeSurfaceTileProvider#ready} returns true.
   *
   * @param {Number} level The tile level for which to get the maximum geometric error.
   * @returns {Number} The maximum geometric error in meters.
   */
  GlobeSurfaceTileProvider.prototype.getLevelMaximumGeometricError = function (
    level
  ) {
    return this._terrainProvider.getLevelMaximumGeometricError(level);
  };

  /**
   * Loads, or continues loading, a given tile.  This function will continue to be called
   * until {@link QuadtreeTile#state} is no longer {@link QuadtreeTileLoadState#LOADING}.  This function should
   * not be called before {@link GlobeSurfaceTileProvider#ready} returns true.
   *
   * @param {FrameState} frameState The frame state.
   * @param {QuadtreeTile} tile The tile to load.
   *
   * @exception {DeveloperError} <code>loadTile</code> must not be called before the tile provider is ready.
   */
  GlobeSurfaceTileProvider.prototype.loadTile = function (frameState, tile) {
    // We don't want to load imagery until we're certain that the terrain tiles are actually visible.
    // So if our bounding volume isn't accurate because it came from another tile, load terrain only
    // initially. If we load some terrain and suddenly have a more accurate bounding volume and the
    // tile is _still_ visible, give the tile a chance to load imagery immediately rather than
    // waiting for next frame.

    let surfaceTile = tile.data;
    let terrainOnly = true;
    let terrainStateBefore;
    if (defined(surfaceTile)) {
      terrainOnly =
        surfaceTile.boundingVolumeSourceTile !== tile ||
        tile._lastSelectionResult === TileSelectionResult.CULLED_BUT_NEEDED;
      terrainStateBefore = surfaceTile.terrainState;
    }

    GlobeSurfaceTile.processStateMachine(
      tile,
      frameState,
      this.terrainProvider,
      this._imageryLayers,
      this.quadtree,
      this._vertexArraysToDestroy,
      terrainOnly
    );

    surfaceTile = tile.data;
    if (terrainOnly && terrainStateBefore !== tile.data.terrainState) {
      // Terrain state changed. If:
      // a) The tile is visible, and
      // b) The bounding volume is accurate (updated as a side effect of computing visibility)
      // Then we'll load imagery, too.
      if (
        this.computeTileVisibility(tile, frameState, this.quadtree.occluders) !==
          Visibility$1.NONE &&
        surfaceTile.boundingVolumeSourceTile === tile
      ) {
        terrainOnly = false;
        GlobeSurfaceTile.processStateMachine(
          tile,
          frameState,
          this.terrainProvider,
          this._imageryLayers,
          this.quadtree,
          this._vertexArraysToDestroy,
          terrainOnly
        );
      }
    }
  };

  const boundingSphereScratch$1 = new BoundingSphere();
  const rectangleIntersectionScratch = new Rectangle();
  const splitCartographicLimitRectangleScratch = new Rectangle();
  const rectangleCenterScratch = new Cartographic();

  // cartographicLimitRectangle may span the IDL, but tiles never will.
  function clipRectangleAntimeridian(tileRectangle, cartographicLimitRectangle) {
    if (cartographicLimitRectangle.west < cartographicLimitRectangle.east) {
      return cartographicLimitRectangle;
    }
    const splitRectangle = Rectangle.clone(
      cartographicLimitRectangle,
      splitCartographicLimitRectangleScratch
    );
    const tileCenter = Rectangle.center(tileRectangle, rectangleCenterScratch);
    if (tileCenter.longitude > 0.0) {
      splitRectangle.east = CesiumMath.PI;
    } else {
      splitRectangle.west = -CesiumMath.PI;
    }
    return splitRectangle;
  }

  function isUndergroundVisible(tileProvider, frameState) {
    if (frameState.cameraUnderground) {
      return true;
    }

    if (frameState.globeTranslucencyState.translucent) {
      return true;
    }

    if (tileProvider.backFaceCulling) {
      return false;
    }

    const clippingPlanes = tileProvider._clippingPlanes;
    if (defined(clippingPlanes) && clippingPlanes.enabled) {
      return true;
    }

    if (
      !Rectangle.equals(
        tileProvider.cartographicLimitRectangle,
        Rectangle.MAX_VALUE
      )
    ) {
      return true;
    }

    return false;
  }

  /**
   * Determines the visibility of a given tile.  The tile may be fully visible, partially visible, or not
   * visible at all.  Tiles that are renderable and are at least partially visible will be shown by a call
   * to {@link GlobeSurfaceTileProvider#showTileThisFrame}.
   *
   * @param {QuadtreeTile} tile The tile instance.
   * @param {FrameState} frameState The state information about the current frame.
   * @param {QuadtreeOccluders} occluders The objects that may occlude this tile.
   *
   * @returns {Visibility} Visibility.NONE if the tile is not visible,
   *                       Visibility.PARTIAL if the tile is partially visible, or
   *                       Visibility.FULL if the tile is fully visible.
   */
  GlobeSurfaceTileProvider.prototype.computeTileVisibility = function (
    tile,
    frameState,
    occluders
  ) {
    const distance = this.computeDistanceToTile(tile, frameState);
    tile._distance = distance;

    const undergroundVisible = isUndergroundVisible(this, frameState);

    if (frameState.fog.enabled && !undergroundVisible) {
      if (CesiumMath.fog(distance, frameState.fog.density) >= 1.0) {
        // Tile is completely in fog so return that it is not visible.
        return Visibility$1.NONE;
      }
    }

    const surfaceTile = tile.data;
    const tileBoundingRegion = surfaceTile.tileBoundingRegion;

    if (surfaceTile.boundingVolumeSourceTile === undefined) {
      // We have no idea where this tile is, so let's just call it partially visible.
      return Visibility$1.PARTIAL;
    }

    const cullingVolume = frameState.cullingVolume;
    let boundingVolume = tileBoundingRegion.boundingVolume;

    if (!defined(boundingVolume)) {
      boundingVolume = tileBoundingRegion.boundingSphere;
    }

    // Check if the tile is outside the limit area in cartographic space
    surfaceTile.clippedByBoundaries = false;
    const clippedCartographicLimitRectangle = clipRectangleAntimeridian(
      tile.rectangle,
      this.cartographicLimitRectangle
    );
    const areaLimitIntersection = Rectangle.simpleIntersection(
      clippedCartographicLimitRectangle,
      tile.rectangle,
      rectangleIntersectionScratch
    );
    if (!defined(areaLimitIntersection)) {
      return Visibility$1.NONE;
    }
    if (!Rectangle.equals(areaLimitIntersection, tile.rectangle)) {
      surfaceTile.clippedByBoundaries = true;
    }

    if (frameState.mode !== SceneMode$1.SCENE3D) {
      boundingVolume = boundingSphereScratch$1;
      BoundingSphere.fromRectangleWithHeights2D(
        tile.rectangle,
        frameState.mapProjection,
        tileBoundingRegion.minimumHeight,
        tileBoundingRegion.maximumHeight,
        boundingVolume
      );
      Cartesian3.fromElements(
        boundingVolume.center.z,
        boundingVolume.center.x,
        boundingVolume.center.y,
        boundingVolume.center
      );

      if (
        frameState.mode === SceneMode$1.MORPHING &&
        defined(surfaceTile.renderedMesh)
      ) {
        boundingVolume = BoundingSphere.union(
          tileBoundingRegion.boundingSphere,
          boundingVolume,
          boundingVolume
        );
      }
    }

    if (!defined(boundingVolume)) {
      return Visibility$1.PARTIAL;
    }

    const clippingPlanes = this._clippingPlanes;
    if (defined(clippingPlanes) && clippingPlanes.enabled) {
      const planeIntersection = clippingPlanes.computeIntersectionWithBoundingVolume(
        boundingVolume
      );
      tile.isClipped = planeIntersection !== Intersect$1.INSIDE;
      if (planeIntersection === Intersect$1.OUTSIDE) {
        return Visibility$1.NONE;
      }
    }

    let visibility;
    const intersection = cullingVolume.computeVisibility(boundingVolume);

    if (intersection === Intersect$1.OUTSIDE) {
      visibility = Visibility$1.NONE;
    } else if (intersection === Intersect$1.INTERSECTING) {
      visibility = Visibility$1.PARTIAL;
    } else if (intersection === Intersect$1.INSIDE) {
      visibility = Visibility$1.FULL;
    }

    if (visibility === Visibility$1.NONE) {
      return visibility;
    }

    const ortho3D =
      frameState.mode === SceneMode$1.SCENE3D &&
      frameState.camera.frustum instanceof OrthographicFrustum;
    if (
      frameState.mode === SceneMode$1.SCENE3D &&
      !ortho3D &&
      defined(occluders) &&
      !undergroundVisible
    ) {
      const occludeePointInScaledSpace = surfaceTile.occludeePointInScaledSpace;
      if (!defined(occludeePointInScaledSpace)) {
        return visibility;
      }

      if (
        occluders.ellipsoid.isScaledSpacePointVisiblePossiblyUnderEllipsoid(
          occludeePointInScaledSpace,
          tileBoundingRegion.minimumHeight
        )
      ) {
        return visibility;
      }

      return Visibility$1.NONE;
    }

    return visibility;
  };

  /**
   * Determines if the given tile can be refined
   * @param {QuadtreeTile} tile The tile to check.
   * @returns {boolean} True if the tile can be refined, false if it cannot.
   */
  GlobeSurfaceTileProvider.prototype.canRefine = function (tile) {
    // Only allow refinement it we know whether or not the children of this tile exist.
    // For a tileset with `availability`, we'll always be able to refine.
    // We can ask for availability of _any_ child tile because we only need to confirm
    // that we get a yes or no answer, it doesn't matter what the answer is.
    if (defined(tile.data.terrainData)) {
      return true;
    }
    const childAvailable = this.terrainProvider.getTileDataAvailable(
      tile.x * 2,
      tile.y * 2,
      tile.level + 1
    );
    return childAvailable !== undefined;
  };

  const readyImageryScratch = [];
  const canRenderTraversalStack = [];

  /**
   * Determines if the given not-fully-loaded tile can be rendered without losing detail that
   * was present last frame as a result of rendering descendant tiles. This method will only be
   * called if this tile's descendants were rendered last frame. If the tile is fully loaded,
   * it is assumed that this method will return true and it will not be called.
   * @param {QuadtreeTile} tile The tile to check.
   * @returns {boolean} True if the tile can be rendered without losing detail.
   */
  GlobeSurfaceTileProvider.prototype.canRenderWithoutLosingDetail = function (
    tile,
    frameState
  ) {
    const surfaceTile = tile.data;

    const readyImagery = readyImageryScratch;
    readyImagery.length = this._imageryLayers.length;

    let terrainReady = false;
    let initialImageryState = false;
    let imagery;

    if (defined(surfaceTile)) {
      // We can render even with non-ready terrain as long as all our rendered descendants
      // are missing terrain geometry too. i.e. if we rendered fills for more detailed tiles
      // last frame, it's ok to render a fill for this tile this frame.
      terrainReady = surfaceTile.terrainState === TerrainState$1.READY;

      // Initially assume all imagery layers are ready, unless imagery hasn't been initialized at all.
      initialImageryState = true;

      imagery = surfaceTile.imagery;
    }

    let i;
    let len;

    for (i = 0, len = readyImagery.length; i < len; ++i) {
      readyImagery[i] = initialImageryState;
    }

    if (defined(imagery)) {
      for (i = 0, len = imagery.length; i < len; ++i) {
        const tileImagery = imagery[i];
        const loadingImagery = tileImagery.loadingImagery;
        const isReady =
          !defined(loadingImagery) ||
          loadingImagery.state === ImageryState$1.FAILED ||
          loadingImagery.state === ImageryState$1.INVALID;
        const layerIndex = (
          tileImagery.loadingImagery || tileImagery.readyImagery
        ).imageryLayer._layerIndex;

        // For a layer to be ready, all tiles belonging to that layer must be ready.
        readyImagery[layerIndex] = isReady && readyImagery[layerIndex];
      }
    }

    const lastFrame = this.quadtree._lastSelectionFrameNumber;

    // Traverse the descendants looking for one with terrain or imagery that is not loaded on this tile.
    const stack = canRenderTraversalStack;
    stack.length = 0;
    stack.push(
      tile.southwestChild,
      tile.southeastChild,
      tile.northwestChild,
      tile.northeastChild
    );

    while (stack.length > 0) {
      const descendant = stack.pop();
      const lastFrameSelectionResult =
        descendant._lastSelectionResultFrame === lastFrame
          ? descendant._lastSelectionResult
          : TileSelectionResult.NONE;

      if (lastFrameSelectionResult === TileSelectionResult.RENDERED) {
        const descendantSurface = descendant.data;

        if (!defined(descendantSurface)) {
          // Descendant has no data, so it can't block rendering.
          continue;
        }

        if (
          !terrainReady &&
          descendant.data.terrainState === TerrainState$1.READY
        ) {
          // Rendered descendant has real terrain, but we don't. Rendering is blocked.
          return false;
        }

        const descendantImagery = descendant.data.imagery;
        for (i = 0, len = descendantImagery.length; i < len; ++i) {
          const descendantTileImagery = descendantImagery[i];
          const descendantLoadingImagery = descendantTileImagery.loadingImagery;
          const descendantIsReady =
            !defined(descendantLoadingImagery) ||
            descendantLoadingImagery.state === ImageryState$1.FAILED ||
            descendantLoadingImagery.state === ImageryState$1.INVALID;
          const descendantLayerIndex = (
            descendantTileImagery.loadingImagery ||
            descendantTileImagery.readyImagery
          ).imageryLayer._layerIndex;

          // If this imagery tile of a descendant is ready but the layer isn't ready in this tile,
          // then rendering is blocked.
          if (descendantIsReady && !readyImagery[descendantLayerIndex]) {
            return false;
          }
        }
      } else if (lastFrameSelectionResult === TileSelectionResult.REFINED) {
        stack.push(
          descendant.southwestChild,
          descendant.southeastChild,
          descendant.northwestChild,
          descendant.northeastChild
        );
      }
    }

    return true;
  };

  const tileDirectionScratch = new Cartesian3();

  /**
   * Determines the priority for loading this tile. Lower priority values load sooner.
   * @param {QuadtreeTile} tile The tile.
   * @param {FrameState} frameState The frame state.
   * @returns {Number} The load priority value.
   */
  GlobeSurfaceTileProvider.prototype.computeTileLoadPriority = function (
    tile,
    frameState
  ) {
    const surfaceTile = tile.data;
    if (surfaceTile === undefined) {
      return 0.0;
    }

    const obb = surfaceTile.tileBoundingRegion.boundingVolume;
    if (obb === undefined) {
      return 0.0;
    }

    const cameraPosition = frameState.camera.positionWC;
    const cameraDirection = frameState.camera.directionWC;
    const tileDirection = Cartesian3.subtract(
      obb.center,
      cameraPosition,
      tileDirectionScratch
    );
    const magnitude = Cartesian3.magnitude(tileDirection);
    if (magnitude < CesiumMath.EPSILON5) {
      return 0.0;
    }
    Cartesian3.divideByScalar(tileDirection, magnitude, tileDirection);
    return (
      (1.0 - Cartesian3.dot(tileDirection, cameraDirection)) * tile._distance
    );
  };

  const modifiedModelViewScratch = new Matrix4();
  const modifiedModelViewProjectionScratch = new Matrix4();
  const tileRectangleScratch = new Cartesian4();
  const localizedCartographicLimitRectangleScratch = new Cartesian4();
  const localizedTranslucencyRectangleScratch = new Cartesian4();
  const rtcScratch = new Cartesian3();
  const centerEyeScratch = new Cartesian3();
  const southwestScratch = new Cartesian3();
  const northeastScratch = new Cartesian3();

  /**
   * Shows a specified tile in this frame.  The provider can cause the tile to be shown by adding
   * render commands to the commandList, or use any other method as appropriate.  The tile is not
   * expected to be visible next frame as well, unless this method is called next frame, too.
   *
   * @param {QuadtreeTile} tile The tile instance.
   * @param {FrameState} frameState The state information of the current rendering frame.
   */
  GlobeSurfaceTileProvider.prototype.showTileThisFrame = function (
    tile,
    frameState
  ) {
    let readyTextureCount = 0;
    const tileImageryCollection = tile.data.imagery;
    for (let i = 0, len = tileImageryCollection.length; i < len; ++i) {
      const tileImagery = tileImageryCollection[i];
      if (
        defined(tileImagery.readyImagery) &&
        tileImagery.readyImagery.imageryLayer.alpha !== 0.0
      ) {
        ++readyTextureCount;
      }
    }

    let tileSet = this._tilesToRenderByTextureCount[readyTextureCount];
    if (!defined(tileSet)) {
      tileSet = [];
      this._tilesToRenderByTextureCount[readyTextureCount] = tileSet;
    }

    tileSet.push(tile);

    const surfaceTile = tile.data;
    if (!defined(surfaceTile.vertexArray)) {
      this._hasFillTilesThisFrame = true;
    } else {
      this._hasLoadedTilesThisFrame = true;
    }

    const debug = this._debug;
    ++debug.tilesRendered;
    debug.texturesRendered += readyTextureCount;
  };

  const cornerPositionsScratch = [
    new Cartesian3(),
    new Cartesian3(),
    new Cartesian3(),
    new Cartesian3(),
  ];

  function computeOccludeePoint(
    tileProvider,
    center,
    rectangle,
    minimumHeight,
    maximumHeight,
    result
  ) {
    const ellipsoidalOccluder = tileProvider.quadtree._occluders.ellipsoid;
    const ellipsoid = ellipsoidalOccluder.ellipsoid;

    const cornerPositions = cornerPositionsScratch;
    Cartesian3.fromRadians(
      rectangle.west,
      rectangle.south,
      maximumHeight,
      ellipsoid,
      cornerPositions[0]
    );
    Cartesian3.fromRadians(
      rectangle.east,
      rectangle.south,
      maximumHeight,
      ellipsoid,
      cornerPositions[1]
    );
    Cartesian3.fromRadians(
      rectangle.west,
      rectangle.north,
      maximumHeight,
      ellipsoid,
      cornerPositions[2]
    );
    Cartesian3.fromRadians(
      rectangle.east,
      rectangle.north,
      maximumHeight,
      ellipsoid,
      cornerPositions[3]
    );

    return ellipsoidalOccluder.computeHorizonCullingPointPossiblyUnderEllipsoid(
      center,
      cornerPositions,
      minimumHeight,
      result
    );
  }

  /**
   * Gets the distance from the camera to the closest point on the tile.  This is used for level-of-detail selection.
   *
   * @param {QuadtreeTile} tile The tile instance.
   * @param {FrameState} frameState The state information of the current rendering frame.
   *
   * @returns {Number} The distance from the camera to the closest point on the tile, in meters.
   */
  GlobeSurfaceTileProvider.prototype.computeDistanceToTile = function (
    tile,
    frameState
  ) {
    // The distance should be:
    // 1. the actual distance to the tight-fitting bounding volume, or
    // 2. a distance that is equal to or greater than the actual distance to the tight-fitting bounding volume.
    //
    // When we don't know the min/max heights for a tile, but we do know the min/max of an ancestor tile, we can
    // build a tight-fitting bounding volume horizontally, but not vertically. The min/max heights from the
    // ancestor will likely form a volume that is much bigger than it needs to be. This means that the volume may
    // be deemed to be much closer to the camera than it really is, causing us to select tiles that are too detailed.
    // Loading too-detailed tiles is super expensive, so we don't want to do that. We don't know where the child
    // tile really lies within the parent range of heights, but we _do_ know the child tile can't be any closer than
    // the ancestor height surface (min or max) that is _farthest away_ from the camera. So if we compute distance
    // based on that conservative metric, we may end up loading tiles that are not detailed enough, but that's much
    // better (faster) than loading tiles that are too detailed.

    updateTileBoundingRegion(tile, this, frameState);

    const surfaceTile = tile.data;
    const boundingVolumeSourceTile = surfaceTile.boundingVolumeSourceTile;
    if (boundingVolumeSourceTile === undefined) {
      // Can't find any min/max heights anywhere? Ok, let's just say the
      // tile is really far away so we'll load and render it rather than
      // refining.
      return 9999999999.0;
    }

    const tileBoundingRegion = surfaceTile.tileBoundingRegion;
    const min = tileBoundingRegion.minimumHeight;
    const max = tileBoundingRegion.maximumHeight;

    if (surfaceTile.boundingVolumeSourceTile !== tile) {
      const cameraHeight = frameState.camera.positionCartographic.height;
      const distanceToMin = Math.abs(cameraHeight - min);
      const distanceToMax = Math.abs(cameraHeight - max);
      if (distanceToMin > distanceToMax) {
        tileBoundingRegion.minimumHeight = min;
        tileBoundingRegion.maximumHeight = min;
      } else {
        tileBoundingRegion.minimumHeight = max;
        tileBoundingRegion.maximumHeight = max;
      }
    }

    const result = tileBoundingRegion.distanceToCamera(frameState);

    tileBoundingRegion.minimumHeight = min;
    tileBoundingRegion.maximumHeight = max;

    return result;
  };

  function updateTileBoundingRegion(tile, tileProvider, frameState) {
    let surfaceTile = tile.data;
    if (surfaceTile === undefined) {
      surfaceTile = tile.data = new GlobeSurfaceTile();
    }

    const ellipsoid = tile.tilingScheme.ellipsoid;
    if (surfaceTile.tileBoundingRegion === undefined) {
      surfaceTile.tileBoundingRegion = new TileBoundingRegion({
        computeBoundingVolumes: false,
        rectangle: tile.rectangle,
        ellipsoid: ellipsoid,
        minimumHeight: 0.0,
        maximumHeight: 0.0,
      });
    }

    const tileBoundingRegion = surfaceTile.tileBoundingRegion;
    const oldMinimumHeight = tileBoundingRegion.minimumHeight;
    const oldMaximumHeight = tileBoundingRegion.maximumHeight;
    let hasBoundingVolumesFromMesh = false;
    let sourceTile = tile;

    // Get min and max heights from the mesh.
    // If the mesh is not available, get them from the terrain data.
    // If the terrain data is not available either, get them from an ancestor.
    // If none of the ancestors are available, then there are no min and max heights for this tile at this time.
    const mesh = surfaceTile.mesh;
    const terrainData = surfaceTile.terrainData;
    if (
      mesh !== undefined &&
      mesh.minimumHeight !== undefined &&
      mesh.maximumHeight !== undefined
    ) {
      tileBoundingRegion.minimumHeight = mesh.minimumHeight;
      tileBoundingRegion.maximumHeight = mesh.maximumHeight;
      hasBoundingVolumesFromMesh = true;
    } else if (
      terrainData !== undefined &&
      terrainData._minimumHeight !== undefined &&
      terrainData._maximumHeight !== undefined
    ) {
      tileBoundingRegion.minimumHeight = terrainData._minimumHeight;
      tileBoundingRegion.maximumHeight = terrainData._maximumHeight;
    } else {
      // No accurate min/max heights available, so we're stuck with min/max heights from an ancestor tile.
      tileBoundingRegion.minimumHeight = Number.NaN;
      tileBoundingRegion.maximumHeight = Number.NaN;

      let ancestorTile = tile.parent;
      while (ancestorTile !== undefined) {
        const ancestorSurfaceTile = ancestorTile.data;
        if (ancestorSurfaceTile !== undefined) {
          const ancestorMesh = ancestorSurfaceTile.mesh;
          const ancestorTerrainData = ancestorSurfaceTile.terrainData;
          if (
            ancestorMesh !== undefined &&
            ancestorMesh.minimumHeight !== undefined &&
            ancestorMesh.maximumHeight !== undefined
          ) {
            tileBoundingRegion.minimumHeight = ancestorMesh.minimumHeight;
            tileBoundingRegion.maximumHeight = ancestorMesh.maximumHeight;
            break;
          } else if (
            ancestorTerrainData !== undefined &&
            ancestorTerrainData._minimumHeight !== undefined &&
            ancestorTerrainData._maximumHeight !== undefined
          ) {
            tileBoundingRegion.minimumHeight = ancestorTerrainData._minimumHeight;
            tileBoundingRegion.maximumHeight = ancestorTerrainData._maximumHeight;
            break;
          }
        }
        ancestorTile = ancestorTile.parent;
      }
      sourceTile = ancestorTile;
    }

    // Update bounding regions from the min and max heights
    if (sourceTile !== undefined) {
      const exaggeration = frameState.terrainExaggeration;
      const exaggerationRelativeHeight =
        frameState.terrainExaggerationRelativeHeight;
      const hasExaggeration = exaggeration !== 1.0;
      if (hasExaggeration) {
        hasBoundingVolumesFromMesh = false;
        tileBoundingRegion.minimumHeight = TerrainExaggeration.getHeight(
          tileBoundingRegion.minimumHeight,
          exaggeration,
          exaggerationRelativeHeight
        );
        tileBoundingRegion.maximumHeight = TerrainExaggeration.getHeight(
          tileBoundingRegion.maximumHeight,
          exaggeration,
          exaggerationRelativeHeight
        );
      }

      if (hasBoundingVolumesFromMesh) {
        if (!surfaceTile.boundingVolumeIsFromMesh) {
          tileBoundingRegion._orientedBoundingBox = OrientedBoundingBox.clone(
            mesh.orientedBoundingBox,
            tileBoundingRegion._orientedBoundingBox
          );
          tileBoundingRegion._boundingSphere = BoundingSphere.clone(
            mesh.boundingSphere3D,
            tileBoundingRegion._boundingSphere
          );
          surfaceTile.occludeePointInScaledSpace = Cartesian3.clone(
            mesh.occludeePointInScaledSpace,
            surfaceTile.occludeePointInScaledSpace
          );

          // If the occludee point is not defined, fallback to calculating it from the OBB
          if (!defined(surfaceTile.occludeePointInScaledSpace)) {
            surfaceTile.occludeePointInScaledSpace = computeOccludeePoint(
              tileProvider,
              tileBoundingRegion._orientedBoundingBox.center,
              tile.rectangle,
              tileBoundingRegion.minimumHeight,
              tileBoundingRegion.maximumHeight,
              surfaceTile.occludeePointInScaledSpace
            );
          }
        }
      } else {
        const needsBounds =
          tileBoundingRegion._orientedBoundingBox === undefined ||
          tileBoundingRegion._boundingSphere === undefined;
        const heightChanged =
          tileBoundingRegion.minimumHeight !== oldMinimumHeight ||
          tileBoundingRegion.maximumHeight !== oldMaximumHeight;
        if (heightChanged || needsBounds) {
          // Bounding volumes need to be recomputed in some circumstances
          tileBoundingRegion.computeBoundingVolumes(ellipsoid);
          surfaceTile.occludeePointInScaledSpace = computeOccludeePoint(
            tileProvider,
            tileBoundingRegion._orientedBoundingBox.center,
            tile.rectangle,
            tileBoundingRegion.minimumHeight,
            tileBoundingRegion.maximumHeight,
            surfaceTile.occludeePointInScaledSpace
          );
        }
      }
      surfaceTile.boundingVolumeSourceTile = sourceTile;
      surfaceTile.boundingVolumeIsFromMesh = hasBoundingVolumesFromMesh;
    } else {
      surfaceTile.boundingVolumeSourceTile = undefined;
      surfaceTile.boundingVolumeIsFromMesh = false;
    }
  }

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} True if this object was destroyed; otherwise, false.
   *
   * @see GlobeSurfaceTileProvider#destroy
   */
  GlobeSurfaceTileProvider.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * provider = provider && provider();
   *
   * @see GlobeSurfaceTileProvider#isDestroyed
   */
  GlobeSurfaceTileProvider.prototype.destroy = function () {
    this._tileProvider = this._tileProvider && this._tileProvider.destroy();
    this._clippingPlanes = this._clippingPlanes && this._clippingPlanes.destroy();

    return destroyObject(this);
  };

  function getTileReadyCallback(tileImageriesToFree, layer, terrainProvider) {
    return function (tile) {
      let tileImagery;
      let imagery;
      let startIndex = -1;
      const tileImageryCollection = tile.data.imagery;
      const length = tileImageryCollection.length;
      let i;
      for (i = 0; i < length; ++i) {
        tileImagery = tileImageryCollection[i];
        imagery = defaultValue(
          tileImagery.readyImagery,
          tileImagery.loadingImagery
        );
        if (imagery.imageryLayer === layer) {
          startIndex = i;
          break;
        }
      }

      if (startIndex !== -1) {
        const endIndex = startIndex + tileImageriesToFree;
        tileImagery = tileImageryCollection[endIndex];
        imagery = defined(tileImagery)
          ? defaultValue(tileImagery.readyImagery, tileImagery.loadingImagery)
          : undefined;
        if (!defined(imagery) || imagery.imageryLayer !== layer) {
          // Return false to keep the callback if we have to wait on the skeletons
          // Return true to remove the callback if something went wrong
          return !layer._createTileImagerySkeletons(
            tile,
            terrainProvider,
            endIndex
          );
        }

        for (i = startIndex; i < endIndex; ++i) {
          tileImageryCollection[i].freeResources();
        }

        tileImageryCollection.splice(startIndex, tileImageriesToFree);
      }

      return true; // Everything is done, so remove the callback
    };
  }

  GlobeSurfaceTileProvider.prototype._onLayerAdded = function (layer, index) {
    if (layer.show) {
      const terrainProvider = this._terrainProvider;

      const that = this;
      const imageryProvider = layer.imageryProvider;
      const tileImageryUpdatedEvent = this._imageryLayersUpdatedEvent;
      imageryProvider._reload = function () {
        // Clear the layer's cache
        layer._imageryCache = {};

        that._quadtree.forEachLoadedTile(function (tile) {
          // If this layer is still waiting to for the loaded callback, just return
          if (defined(tile._loadedCallbacks[layer._layerIndex])) {
            return;
          }

          let i;

          // Figure out how many TileImageries we will need to remove and where to insert new ones
          const tileImageryCollection = tile.data.imagery;
          const length = tileImageryCollection.length;
          let startIndex = -1;
          let tileImageriesToFree = 0;
          for (i = 0; i < length; ++i) {
            const tileImagery = tileImageryCollection[i];
            const imagery = defaultValue(
              tileImagery.readyImagery,
              tileImagery.loadingImagery
            );
            if (imagery.imageryLayer === layer) {
              if (startIndex === -1) {
                startIndex = i;
              }

              ++tileImageriesToFree;
            } else if (startIndex !== -1) {
              // iterated past the section of TileImageries belonging to this layer, no need to continue.
              break;
            }
          }

          if (startIndex === -1) {
            return;
          }

          // Insert immediately after existing TileImageries
          const insertionPoint = startIndex + tileImageriesToFree;

          // Create new TileImageries for all loaded tiles
          if (
            layer._createTileImagerySkeletons(
              tile,
              terrainProvider,
              insertionPoint
            )
          ) {
            // Add callback to remove old TileImageries when the new TileImageries are ready
            tile._loadedCallbacks[layer._layerIndex] = getTileReadyCallback(
              tileImageriesToFree,
              layer,
              terrainProvider
            );

            tile.state = QuadtreeTileLoadState$1.LOADING;
          }
        });
      };

      // create TileImageries for this layer for all previously loaded tiles
      this._quadtree.forEachLoadedTile(function (tile) {
        if (layer._createTileImagerySkeletons(tile, terrainProvider)) {
          tile.state = QuadtreeTileLoadState$1.LOADING;

          // Tiles that are not currently being rendered need to load the new layer before they're renderable.
          // We don't mark the rendered tiles non-renderable, though, because that would make the globe disappear.
          if (
            tile.level !== 0 &&
            (tile._lastSelectionResultFrame !==
              that.quadtree._lastSelectionFrameNumber ||
              tile._lastSelectionResult !== TileSelectionResult.RENDERED)
          ) {
            tile.renderable = false;
          }
        }
      });

      this._layerOrderChanged = true;
      tileImageryUpdatedEvent.raiseEvent();
    }
  };

  GlobeSurfaceTileProvider.prototype._onLayerRemoved = function (layer, index) {
    // destroy TileImagerys for this layer for all previously loaded tiles
    this._quadtree.forEachLoadedTile(function (tile) {
      const tileImageryCollection = tile.data.imagery;

      let startIndex = -1;
      let numDestroyed = 0;
      for (let i = 0, len = tileImageryCollection.length; i < len; ++i) {
        const tileImagery = tileImageryCollection[i];
        let imagery = tileImagery.loadingImagery;
        if (!defined(imagery)) {
          imagery = tileImagery.readyImagery;
        }
        if (imagery.imageryLayer === layer) {
          if (startIndex === -1) {
            startIndex = i;
          }

          tileImagery.freeResources();
          ++numDestroyed;
        } else if (startIndex !== -1) {
          // iterated past the section of TileImagerys belonging to this layer, no need to continue.
          break;
        }
      }

      if (startIndex !== -1) {
        tileImageryCollection.splice(startIndex, numDestroyed);
      }
    });

    if (defined(layer.imageryProvider)) {
      layer.imageryProvider._reload = undefined;
    }

    this._imageryLayersUpdatedEvent.raiseEvent();
  };

  GlobeSurfaceTileProvider.prototype._onLayerMoved = function (
    layer,
    newIndex,
    oldIndex
  ) {
    this._layerOrderChanged = true;
    this._imageryLayersUpdatedEvent.raiseEvent();
  };

  GlobeSurfaceTileProvider.prototype._onLayerShownOrHidden = function (
    layer,
    index,
    show
  ) {
    if (show) {
      this._onLayerAdded(layer, index);
    } else {
      this._onLayerRemoved(layer, index);
    }
  };

  const scratchClippingPlanesMatrix = new Matrix4();
  const scratchInverseTransposeClippingPlanesMatrix = new Matrix4();
  function createTileUniformMap(frameState, globeSurfaceTileProvider) {
    const uniformMap = {
      u_initialColor: function () {
        return this.properties.initialColor;
      },
      u_fillHighlightColor: function () {
        return this.properties.fillHighlightColor;
      },
      u_zoomedOutOceanSpecularIntensity: function () {
        return this.properties.zoomedOutOceanSpecularIntensity;
      },
      u_oceanNormalMap: function () {
        return this.properties.oceanNormalMap;
      },
      u_atmosphereLightIntensity: function () {
        return this.properties.atmosphereLightIntensity;
      },
      u_atmosphereRayleighCoefficient: function () {
        return this.properties.atmosphereRayleighCoefficient;
      },
      u_atmosphereMieCoefficient: function () {
        return this.properties.atmosphereMieCoefficient;
      },
      u_atmosphereRayleighScaleHeight: function () {
        return this.properties.atmosphereRayleighScaleHeight;
      },
      u_atmosphereMieScaleHeight: function () {
        return this.properties.atmosphereMieScaleHeight;
      },
      u_atmosphereMieAnisotropy: function () {
        return this.properties.atmosphereMieAnisotropy;
      },
      u_lightingFadeDistance: function () {
        return this.properties.lightingFadeDistance;
      },
      u_nightFadeDistance: function () {
        return this.properties.nightFadeDistance;
      },
      u_center3D: function () {
        return this.properties.center3D;
      },
      u_terrainExaggerationAndRelativeHeight: function () {
        return this.properties.terrainExaggerationAndRelativeHeight;
      },
      u_tileRectangle: function () {
        return this.properties.tileRectangle;
      },
      u_modifiedModelView: function () {
        const viewMatrix = frameState.context.uniformState.view;
        const centerEye = Matrix4.multiplyByPoint(
          viewMatrix,
          this.properties.rtc,
          centerEyeScratch
        );
        Matrix4.setTranslation(viewMatrix, centerEye, modifiedModelViewScratch);
        return modifiedModelViewScratch;
      },
      u_modifiedModelViewProjection: function () {
        const viewMatrix = frameState.context.uniformState.view;
        const projectionMatrix = frameState.context.uniformState.projection;
        const centerEye = Matrix4.multiplyByPoint(
          viewMatrix,
          this.properties.rtc,
          centerEyeScratch
        );
        Matrix4.setTranslation(
          viewMatrix,
          centerEye,
          modifiedModelViewProjectionScratch
        );
        Matrix4.multiply(
          projectionMatrix,
          modifiedModelViewProjectionScratch,
          modifiedModelViewProjectionScratch
        );
        return modifiedModelViewProjectionScratch;
      },
      u_dayTextures: function () {
        return this.properties.dayTextures;
      },
      u_dayTextureTranslationAndScale: function () {
        return this.properties.dayTextureTranslationAndScale;
      },
      u_dayTextureTexCoordsRectangle: function () {
        return this.properties.dayTextureTexCoordsRectangle;
      },
      u_dayTextureUseWebMercatorT: function () {
        return this.properties.dayTextureUseWebMercatorT;
      },
      u_dayTextureAlpha: function () {
        return this.properties.dayTextureAlpha;
      },
      u_dayTextureNightAlpha: function () {
        return this.properties.dayTextureNightAlpha;
      },
      u_dayTextureDayAlpha: function () {
        return this.properties.dayTextureDayAlpha;
      },
      u_dayTextureBrightness: function () {
        return this.properties.dayTextureBrightness;
      },
      u_dayTextureContrast: function () {
        return this.properties.dayTextureContrast;
      },
      u_dayTextureHue: function () {
        return this.properties.dayTextureHue;
      },
      u_dayTextureSaturation: function () {
        return this.properties.dayTextureSaturation;
      },
      u_dayTextureOneOverGamma: function () {
        return this.properties.dayTextureOneOverGamma;
      },
      u_dayIntensity: function () {
        return this.properties.dayIntensity;
      },
      u_southAndNorthLatitude: function () {
        return this.properties.southAndNorthLatitude;
      },
      u_southMercatorYAndOneOverHeight: function () {
        return this.properties.southMercatorYAndOneOverHeight;
      },
      u_waterMask: function () {
        return this.properties.waterMask;
      },
      u_waterMaskTranslationAndScale: function () {
        return this.properties.waterMaskTranslationAndScale;
      },
      u_minMaxHeight: function () {
        return this.properties.minMaxHeight;
      },
      u_scaleAndBias: function () {
        return this.properties.scaleAndBias;
      },
      u_dayTextureSplit: function () {
        return this.properties.dayTextureSplit;
      },
      u_dayTextureCutoutRectangles: function () {
        return this.properties.dayTextureCutoutRectangles;
      },
      u_clippingPlanes: function () {
        const clippingPlanes = globeSurfaceTileProvider._clippingPlanes;
        if (defined(clippingPlanes) && defined(clippingPlanes.texture)) {
          // Check in case clippingPlanes hasn't been updated yet.
          return clippingPlanes.texture;
        }
        return frameState.context.defaultTexture;
      },
      u_cartographicLimitRectangle: function () {
        return this.properties.localizedCartographicLimitRectangle;
      },
      u_clippingPlanesMatrix: function () {
        const clippingPlanes = globeSurfaceTileProvider._clippingPlanes;
        const transform = defined(clippingPlanes)
          ? Matrix4.multiply(
              frameState.context.uniformState.view,
              clippingPlanes.modelMatrix,
              scratchClippingPlanesMatrix
            )
          : Matrix4.IDENTITY;

        return Matrix4.inverseTranspose(
          transform,
          scratchInverseTransposeClippingPlanesMatrix
        );
      },
      u_clippingPlanesEdgeStyle: function () {
        const style = this.properties.clippingPlanesEdgeColor;
        style.alpha = this.properties.clippingPlanesEdgeWidth;
        return style;
      },
      u_minimumBrightness: function () {
        return frameState.fog.minimumBrightness;
      },
      u_hsbShift: function () {
        return this.properties.hsbShift;
      },
      u_colorsToAlpha: function () {
        return this.properties.colorsToAlpha;
      },
      u_frontFaceAlphaByDistance: function () {
        return this.properties.frontFaceAlphaByDistance;
      },
      u_backFaceAlphaByDistance: function () {
        return this.properties.backFaceAlphaByDistance;
      },
      u_translucencyRectangle: function () {
        return this.properties.localizedTranslucencyRectangle;
      },
      u_undergroundColor: function () {
        return this.properties.undergroundColor;
      },
      u_undergroundColorAlphaByDistance: function () {
        return this.properties.undergroundColorAlphaByDistance;
      },
      u_lambertDiffuseMultiplier: function () {
        return this.properties.lambertDiffuseMultiplier;
      },

      // make a separate object so that changes to the properties are seen on
      // derived commands that combine another uniform map with this one.
      properties: {
        initialColor: new Cartesian4(0.0, 0.0, 0.5, 1.0),
        fillHighlightColor: new Color(0.0, 0.0, 0.0, 0.0),
        zoomedOutOceanSpecularIntensity: 0.5,
        oceanNormalMap: undefined,
        lightingFadeDistance: new Cartesian2(6500000.0, 9000000.0),
        nightFadeDistance: new Cartesian2(10000000.0, 40000000.0),
        atmosphereLightIntensity: 10.0,
        atmosphereRayleighCoefficient: new Cartesian3(5.5e-6, 13.0e-6, 28.4e-6),
        atmosphereMieCoefficient: new Cartesian3(21e-6, 21e-6, 21e-6),
        atmosphereRayleighScaleHeight: 10000.0,
        atmosphereMieScaleHeight: 3200.0,
        atmosphereMieAnisotropy: 0.9,
        hsbShift: new Cartesian3(),

        center3D: undefined,
        rtc: new Cartesian3(),
        modifiedModelView: new Matrix4(),
        tileRectangle: new Cartesian4(),

        terrainExaggerationAndRelativeHeight: new Cartesian2(1.0, 0.0),

        dayTextures: [],
        dayTextureTranslationAndScale: [],
        dayTextureTexCoordsRectangle: [],
        dayTextureUseWebMercatorT: [],
        dayTextureAlpha: [],
        dayTextureNightAlpha: [],
        dayTextureDayAlpha: [],
        dayTextureBrightness: [],
        dayTextureContrast: [],
        dayTextureHue: [],
        dayTextureSaturation: [],
        dayTextureOneOverGamma: [],
        dayTextureSplit: [],
        dayTextureCutoutRectangles: [],
        dayIntensity: 0.0,
        colorsToAlpha: [],

        southAndNorthLatitude: new Cartesian2(),
        southMercatorYAndOneOverHeight: new Cartesian2(),

        waterMask: undefined,
        waterMaskTranslationAndScale: new Cartesian4(),

        minMaxHeight: new Cartesian2(),
        scaleAndBias: new Matrix4(),
        clippingPlanesEdgeColor: Color.clone(Color.WHITE),
        clippingPlanesEdgeWidth: 0.0,

        localizedCartographicLimitRectangle: new Cartesian4(),

        frontFaceAlphaByDistance: new Cartesian4(),
        backFaceAlphaByDistance: new Cartesian4(),
        localizedTranslucencyRectangle: new Cartesian4(),
        undergroundColor: Color.clone(Color.TRANSPARENT),
        undergroundColorAlphaByDistance: new Cartesian4(),
        lambertDiffuseMultiplier: 0.0,
      },
    };

    if (defined(globeSurfaceTileProvider.materialUniformMap)) {
      return combine$2(uniformMap, globeSurfaceTileProvider.materialUniformMap);
    }

    return uniformMap;
  }

  function createWireframeVertexArrayIfNecessary(context, provider, tile) {
    const surfaceTile = tile.data;

    let mesh;
    let vertexArray;

    if (defined(surfaceTile.vertexArray)) {
      mesh = surfaceTile.mesh;
      vertexArray = surfaceTile.vertexArray;
    } else if (
      defined(surfaceTile.fill) &&
      defined(surfaceTile.fill.vertexArray)
    ) {
      mesh = surfaceTile.fill.mesh;
      vertexArray = surfaceTile.fill.vertexArray;
    }

    if (!defined(mesh) || !defined(vertexArray)) {
      return;
    }

    if (defined(surfaceTile.wireframeVertexArray)) {
      if (surfaceTile.wireframeVertexArray.mesh === mesh) {
        return;
      }

      surfaceTile.wireframeVertexArray.destroy();
      surfaceTile.wireframeVertexArray = undefined;
    }

    surfaceTile.wireframeVertexArray = createWireframeVertexArray(
      context,
      vertexArray,
      mesh
    );
    surfaceTile.wireframeVertexArray.mesh = mesh;
  }

  /**
   * Creates a vertex array for wireframe rendering of a terrain tile.
   *
   * @private
   *
   * @param {Context} context The context in which to create the vertex array.
   * @param {VertexArray} vertexArray The existing, non-wireframe vertex array.  The new vertex array
   *                      will share vertex buffers with this existing one.
   * @param {TerrainMesh} terrainMesh The terrain mesh containing non-wireframe indices.
   * @returns {VertexArray} The vertex array for wireframe rendering.
   */
  function createWireframeVertexArray(context, vertexArray, terrainMesh) {
    const indices = terrainMesh.indices;

    const geometry = {
      indices: indices,
      primitiveType: PrimitiveType$1.TRIANGLES,
    };

    GeometryPipeline.toWireframe(geometry);

    const wireframeIndices = geometry.indices;
    const wireframeIndexBuffer = Buffer$1.createIndexBuffer({
      context: context,
      typedArray: wireframeIndices,
      usage: BufferUsage$1.STATIC_DRAW,
      indexDatatype: IndexDatatype$1.fromSizeInBytes(
        wireframeIndices.BYTES_PER_ELEMENT
      ),
    });
    return new VertexArray({
      context: context,
      attributes: vertexArray._attributes,
      indexBuffer: wireframeIndexBuffer,
    });
  }

  let getDebugOrientedBoundingBox;
  let getDebugBoundingSphere;
  let debugDestroyPrimitive;

  (function () {
    const instanceOBB = new GeometryInstance({
      geometry: BoxOutlineGeometry.fromDimensions({
        dimensions: new Cartesian3(2.0, 2.0, 2.0),
      }),
    });
    const instanceSphere = new GeometryInstance({
      geometry: new SphereOutlineGeometry({ radius: 1.0 }),
    });
    let modelMatrix = new Matrix4();
    let previousVolume;
    let primitive;

    function createDebugPrimitive(instance) {
      return new Primitive$3({
        geometryInstances: instance,
        appearance: new PerInstanceColorAppearance({
          translucent: false,
          flat: true,
        }),
        asynchronous: false,
      });
    }

    getDebugOrientedBoundingBox = function (obb, color) {
      if (obb === previousVolume) {
        return primitive;
      }
      debugDestroyPrimitive();

      previousVolume = obb;
      modelMatrix = Matrix4.fromRotationTranslation(
        obb.halfAxes,
        obb.center,
        modelMatrix
      );

      instanceOBB.modelMatrix = modelMatrix;
      instanceOBB.attributes.color = ColorGeometryInstanceAttribute.fromColor(
        color
      );

      primitive = createDebugPrimitive(instanceOBB);
      return primitive;
    };

    getDebugBoundingSphere = function (sphere, color) {
      if (sphere === previousVolume) {
        return primitive;
      }
      debugDestroyPrimitive();

      previousVolume = sphere;
      modelMatrix = Matrix4.fromTranslation(sphere.center, modelMatrix);
      modelMatrix = Matrix4.multiplyByUniformScale(
        modelMatrix,
        sphere.radius,
        modelMatrix
      );

      instanceSphere.modelMatrix = modelMatrix;
      instanceSphere.attributes.color = ColorGeometryInstanceAttribute.fromColor(
        color
      );

      primitive = createDebugPrimitive(instanceSphere);
      return primitive;
    };

    debugDestroyPrimitive = function () {
      if (defined(primitive)) {
        primitive.destroy();
        primitive = undefined;
        previousVolume = undefined;
      }
    };
  })();

  const otherPassesInitialColor = new Cartesian4(0.0, 0.0, 0.0, 0.0);
  const surfaceShaderSetOptionsScratch = {
    frameState: undefined,
    surfaceTile: undefined,
    numberOfDayTextures: undefined,
    applyBrightness: undefined,
    applyContrast: undefined,
    applyHue: undefined,
    applySaturation: undefined,
    applyGamma: undefined,
    applyAlpha: undefined,
    applyDayNightAlpha: undefined,
    applySplit: undefined,
    showReflectiveOcean: undefined,
    showOceanWaves: undefined,
    enableLighting: undefined,
    dynamicAtmosphereLighting: undefined,
    dynamicAtmosphereLightingFromSun: undefined,
    showGroundAtmosphere: undefined,
    perFragmentGroundAtmosphere: undefined,
    hasVertexNormals: undefined,
    useWebMercatorProjection: undefined,
    enableFog: undefined,
    enableClippingPlanes: undefined,
    clippingPlanes: undefined,
    clippedByBoundaries: undefined,
    hasImageryLayerCutout: undefined,
    colorCorrect: undefined,
    colorToAlpha: undefined,
    hasGeodeticSurfaceNormals: undefined,
    hasExaggeration: undefined,
  };

  const defaultUndergroundColor = Color.TRANSPARENT;
  const defaultUndergroundColorAlphaByDistance = new NearFarScalar();

  function addDrawCommandsForTile(tileProvider, tile, frameState) {
    const surfaceTile = tile.data;

    if (!defined(surfaceTile.vertexArray)) {
      if (surfaceTile.fill === undefined) {
        // No fill was created for this tile, probably because this tile is not connected to
        // any renderable tiles. So create a simple tile in the middle of the tile's possible
        // height range.
        surfaceTile.fill = new TerrainFillMesh(tile);
      }
      surfaceTile.fill.update(tileProvider, frameState);
    }

    const creditDisplay = frameState.creditDisplay;

    const terrainData = surfaceTile.terrainData;
    if (defined(terrainData) && defined(terrainData.credits)) {
      const tileCredits = terrainData.credits;
      for (
        let tileCreditIndex = 0, tileCreditLength = tileCredits.length;
        tileCreditIndex < tileCreditLength;
        ++tileCreditIndex
      ) {
        creditDisplay.addCredit(tileCredits[tileCreditIndex]);
      }
    }

    let maxTextures = ContextLimits.maximumTextureImageUnits;

    let waterMaskTexture = surfaceTile.waterMaskTexture;
    let waterMaskTranslationAndScale = surfaceTile.waterMaskTranslationAndScale;
    if (!defined(waterMaskTexture) && defined(surfaceTile.fill)) {
      waterMaskTexture = surfaceTile.fill.waterMaskTexture;
      waterMaskTranslationAndScale =
        surfaceTile.fill.waterMaskTranslationAndScale;
    }

    const cameraUnderground = frameState.cameraUnderground;

    const globeTranslucencyState = frameState.globeTranslucencyState;
    const translucent = globeTranslucencyState.translucent;
    const frontFaceAlphaByDistance =
      globeTranslucencyState.frontFaceAlphaByDistance;
    const backFaceAlphaByDistance =
      globeTranslucencyState.backFaceAlphaByDistance;
    const translucencyRectangle = globeTranslucencyState.rectangle;

    const undergroundColor = defaultValue(
      tileProvider.undergroundColor,
      defaultUndergroundColor
    );
    const undergroundColorAlphaByDistance = defaultValue(
      tileProvider.undergroundColorAlphaByDistance,
      defaultUndergroundColorAlphaByDistance
    );
    const showUndergroundColor =
      isUndergroundVisible(tileProvider, frameState) &&
      frameState.mode === SceneMode$1.SCENE3D &&
      undergroundColor.alpha > 0.0 &&
      (undergroundColorAlphaByDistance.nearValue > 0.0 ||
        undergroundColorAlphaByDistance.farValue > 0.0);

    const lambertDiffuseMultiplier = tileProvider.lambertDiffuseMultiplier;

    const showReflectiveOcean =
      tileProvider.hasWaterMask && defined(waterMaskTexture);
    const oceanNormalMap = tileProvider.oceanNormalMap;
    const showOceanWaves = showReflectiveOcean && defined(oceanNormalMap);
    const hasVertexNormals =
      tileProvider.terrainProvider.ready &&
      tileProvider.terrainProvider.hasVertexNormals;
    const enableFog =
      frameState.fog.enabled && frameState.fog.renderable && !cameraUnderground;
    const showGroundAtmosphere =
      tileProvider.showGroundAtmosphere && frameState.mode === SceneMode$1.SCENE3D;
    const castShadows =
      ShadowMode$1.castShadows(tileProvider.shadows) && !translucent;
    const receiveShadows =
      ShadowMode$1.receiveShadows(tileProvider.shadows) && !translucent;

    const hueShift = tileProvider.hueShift;
    const saturationShift = tileProvider.saturationShift;
    const brightnessShift = tileProvider.brightnessShift;

    let colorCorrect = !(
      CesiumMath.equalsEpsilon(hueShift, 0.0, CesiumMath.EPSILON7) &&
      CesiumMath.equalsEpsilon(saturationShift, 0.0, CesiumMath.EPSILON7) &&
      CesiumMath.equalsEpsilon(brightnessShift, 0.0, CesiumMath.EPSILON7)
    );

    let perFragmentGroundAtmosphere = false;
    if (showGroundAtmosphere) {
      const cameraDistance = Cartesian3.magnitude(frameState.camera.positionWC);
      const fadeOutDistance = tileProvider.nightFadeOutDistance;
      perFragmentGroundAtmosphere = cameraDistance > fadeOutDistance;
    }

    if (showReflectiveOcean) {
      --maxTextures;
    }
    if (showOceanWaves) {
      --maxTextures;
    }
    if (
      defined(frameState.shadowState) &&
      frameState.shadowState.shadowsEnabled
    ) {
      --maxTextures;
    }
    if (
      defined(tileProvider.clippingPlanes) &&
      tileProvider.clippingPlanes.enabled
    ) {
      --maxTextures;
    }

    maxTextures -= globeTranslucencyState.numberOfTextureUniforms;

    const mesh = surfaceTile.renderedMesh;
    let rtc = mesh.center;
    const encoding = mesh.encoding;
    const tileBoundingRegion = surfaceTile.tileBoundingRegion;

    const exaggeration = frameState.terrainExaggeration;
    const exaggerationRelativeHeight =
      frameState.terrainExaggerationRelativeHeight;
    const hasExaggeration = exaggeration !== 1.0;
    const hasGeodeticSurfaceNormals = encoding.hasGeodeticSurfaceNormals;

    // Not used in 3D.
    const tileRectangle = tileRectangleScratch;

    // Only used for Mercator projections.
    let southLatitude = 0.0;
    let northLatitude = 0.0;
    let southMercatorY = 0.0;
    let oneOverMercatorHeight = 0.0;

    let useWebMercatorProjection = false;

    if (frameState.mode !== SceneMode$1.SCENE3D) {
      const projection = frameState.mapProjection;
      const southwest = projection.project(
        Rectangle.southwest(tile.rectangle),
        southwestScratch
      );
      const northeast = projection.project(
        Rectangle.northeast(tile.rectangle),
        northeastScratch
      );

      tileRectangle.x = southwest.x;
      tileRectangle.y = southwest.y;
      tileRectangle.z = northeast.x;
      tileRectangle.w = northeast.y;

      // In 2D and Columbus View, use the center of the tile for RTC rendering.
      if (frameState.mode !== SceneMode$1.MORPHING) {
        rtc = rtcScratch;
        rtc.x = 0.0;
        rtc.y = (tileRectangle.z + tileRectangle.x) * 0.5;
        rtc.z = (tileRectangle.w + tileRectangle.y) * 0.5;
        tileRectangle.x -= rtc.y;
        tileRectangle.y -= rtc.z;
        tileRectangle.z -= rtc.y;
        tileRectangle.w -= rtc.z;
      }

      if (
        frameState.mode === SceneMode$1.SCENE2D &&
        encoding.quantization === TerrainQuantization$1.BITS12
      ) {
        // In 2D, the texture coordinates of the tile are interpolated over the rectangle to get the position in the vertex shader.
        // When the texture coordinates are quantized, error is introduced. This can be seen through the 1px wide cracking
        // between the quantized tiles in 2D. To compensate for the error, move the expand the rectangle in each direction by
        // half the error amount.
        const epsilon = (1.0 / (Math.pow(2.0, 12.0) - 1.0)) * 0.5;
        const widthEpsilon = (tileRectangle.z - tileRectangle.x) * epsilon;
        const heightEpsilon = (tileRectangle.w - tileRectangle.y) * epsilon;
        tileRectangle.x -= widthEpsilon;
        tileRectangle.y -= heightEpsilon;
        tileRectangle.z += widthEpsilon;
        tileRectangle.w += heightEpsilon;
      }

      if (projection instanceof WebMercatorProjection) {
        southLatitude = tile.rectangle.south;
        northLatitude = tile.rectangle.north;

        southMercatorY = WebMercatorProjection.geodeticLatitudeToMercatorAngle(
          southLatitude
        );

        oneOverMercatorHeight =
          1.0 /
          (WebMercatorProjection.geodeticLatitudeToMercatorAngle(northLatitude) -
            southMercatorY);

        useWebMercatorProjection = true;
      }
    }

    const surfaceShaderSetOptions = surfaceShaderSetOptionsScratch;
    surfaceShaderSetOptions.frameState = frameState;
    surfaceShaderSetOptions.surfaceTile = surfaceTile;
    surfaceShaderSetOptions.showReflectiveOcean = showReflectiveOcean;
    surfaceShaderSetOptions.showOceanWaves = showOceanWaves;
    surfaceShaderSetOptions.enableLighting = tileProvider.enableLighting;
    surfaceShaderSetOptions.dynamicAtmosphereLighting =
      tileProvider.dynamicAtmosphereLighting;
    surfaceShaderSetOptions.dynamicAtmosphereLightingFromSun =
      tileProvider.dynamicAtmosphereLightingFromSun;
    surfaceShaderSetOptions.showGroundAtmosphere = showGroundAtmosphere;
    surfaceShaderSetOptions.atmosphereLightIntensity =
      tileProvider.atmosphereLightIntensity;
    surfaceShaderSetOptions.atmosphereRayleighCoefficient =
      tileProvider.atmosphereRayleighCoefficient;
    surfaceShaderSetOptions.atmosphereMieCoefficient =
      tileProvider.atmosphereMieCoefficient;
    surfaceShaderSetOptions.atmosphereRayleighScaleHeight =
      tileProvider.atmosphereRayleighScaleHeight;
    surfaceShaderSetOptions.atmosphereMieScaleHeight =
      tileProvider.atmosphereMieScaleHeight;
    surfaceShaderSetOptions.atmosphereMieAnisotropy =
      tileProvider.atmosphereMieAnisotropy;
    surfaceShaderSetOptions.perFragmentGroundAtmosphere = perFragmentGroundAtmosphere;
    surfaceShaderSetOptions.hasVertexNormals = hasVertexNormals;
    surfaceShaderSetOptions.useWebMercatorProjection = useWebMercatorProjection;
    surfaceShaderSetOptions.clippedByBoundaries = surfaceTile.clippedByBoundaries;
    surfaceShaderSetOptions.hasGeodeticSurfaceNormals = hasGeodeticSurfaceNormals;
    surfaceShaderSetOptions.hasExaggeration = hasExaggeration;

    const tileImageryCollection = surfaceTile.imagery;
    let imageryIndex = 0;
    const imageryLen = tileImageryCollection.length;

    const showSkirts =
      tileProvider.showSkirts && !cameraUnderground && !translucent;
    const backFaceCulling =
      tileProvider.backFaceCulling && !cameraUnderground && !translucent;
    const firstPassRenderState = backFaceCulling
      ? tileProvider._renderState
      : tileProvider._disableCullingRenderState;
    const otherPassesRenderState = backFaceCulling
      ? tileProvider._blendRenderState
      : tileProvider._disableCullingBlendRenderState;
    let renderState = firstPassRenderState;

    let initialColor = tileProvider._firstPassInitialColor;

    const context = frameState.context;

    if (!defined(tileProvider._debug.boundingSphereTile)) {
      debugDestroyPrimitive();
    }

    const materialUniformMapChanged =
      tileProvider._materialUniformMap !== tileProvider.materialUniformMap;
    if (materialUniformMapChanged) {
      tileProvider._materialUniformMap = tileProvider.materialUniformMap;
      const drawCommandsLength = tileProvider._drawCommands.length;
      for (let i = 0; i < drawCommandsLength; ++i) {
        tileProvider._uniformMaps[i] = createTileUniformMap(
          frameState,
          tileProvider
        );
      }
    }

    do {
      let numberOfDayTextures = 0;

      let command;
      let uniformMap;

      if (tileProvider._drawCommands.length <= tileProvider._usedDrawCommands) {
        command = new DrawCommand();
        command.owner = tile;
        command.cull = false;
        command.boundingVolume = new BoundingSphere();
        command.orientedBoundingBox = undefined;

        uniformMap = createTileUniformMap(frameState, tileProvider);

        tileProvider._drawCommands.push(command);
        tileProvider._uniformMaps.push(uniformMap);
      } else {
        command = tileProvider._drawCommands[tileProvider._usedDrawCommands];
        uniformMap = tileProvider._uniformMaps[tileProvider._usedDrawCommands];
      }

      command.owner = tile;

      ++tileProvider._usedDrawCommands;

      if (tile === tileProvider._debug.boundingSphereTile) {
        const obb = tileBoundingRegion.boundingVolume;
        const boundingSphere = tileBoundingRegion.boundingSphere;
        // If a debug primitive already exists for this tile, it will not be
        // re-created, to avoid allocation every frame. If it were possible
        // to have more than one selected tile, this would have to change.
        if (defined(obb)) {
          getDebugOrientedBoundingBox(obb, Color.RED).update(frameState);
        } else if (defined(boundingSphere)) {
          getDebugBoundingSphere(boundingSphere, Color.RED).update(frameState);
        }
      }

      const uniformMapProperties = uniformMap.properties;
      Cartesian4.clone(initialColor, uniformMapProperties.initialColor);
      uniformMapProperties.oceanNormalMap = oceanNormalMap;
      uniformMapProperties.lightingFadeDistance.x =
        tileProvider.lightingFadeOutDistance;
      uniformMapProperties.lightingFadeDistance.y =
        tileProvider.lightingFadeInDistance;
      uniformMapProperties.nightFadeDistance.x =
        tileProvider.nightFadeOutDistance;
      uniformMapProperties.nightFadeDistance.y = tileProvider.nightFadeInDistance;
      uniformMapProperties.atmosphereLightIntensity =
        tileProvider.atmosphereLightIntensity;
      uniformMapProperties.atmosphereRayleighCoefficient =
        tileProvider.atmosphereRayleighCoefficient;
      uniformMapProperties.atmosphereMieCoefficient =
        tileProvider.atmosphereMieCoefficient;
      uniformMapProperties.atmosphereRayleighScaleHeight =
        tileProvider.atmosphereRayleighScaleHeight;
      uniformMapProperties.atmosphereMieScaleHeight =
        tileProvider.atmosphereMieScaleHeight;
      uniformMapProperties.atmosphereMieAnisotropy =
        tileProvider.atmosphereMieAnisotropy;
      uniformMapProperties.zoomedOutOceanSpecularIntensity =
        tileProvider.zoomedOutOceanSpecularIntensity;

      const frontFaceAlphaByDistanceFinal = cameraUnderground
        ? backFaceAlphaByDistance
        : frontFaceAlphaByDistance;
      const backFaceAlphaByDistanceFinal = cameraUnderground
        ? frontFaceAlphaByDistance
        : backFaceAlphaByDistance;

      if (defined(frontFaceAlphaByDistanceFinal)) {
        Cartesian4.fromElements(
          frontFaceAlphaByDistanceFinal.near,
          frontFaceAlphaByDistanceFinal.nearValue,
          frontFaceAlphaByDistanceFinal.far,
          frontFaceAlphaByDistanceFinal.farValue,
          uniformMapProperties.frontFaceAlphaByDistance
        );
        Cartesian4.fromElements(
          backFaceAlphaByDistanceFinal.near,
          backFaceAlphaByDistanceFinal.nearValue,
          backFaceAlphaByDistanceFinal.far,
          backFaceAlphaByDistanceFinal.farValue,
          uniformMapProperties.backFaceAlphaByDistance
        );
      }

      Cartesian4.fromElements(
        undergroundColorAlphaByDistance.near,
        undergroundColorAlphaByDistance.nearValue,
        undergroundColorAlphaByDistance.far,
        undergroundColorAlphaByDistance.farValue,
        uniformMapProperties.undergroundColorAlphaByDistance
      );
      Color.clone(undergroundColor, uniformMapProperties.undergroundColor);

      uniformMapProperties.lambertDiffuseMultiplier = lambertDiffuseMultiplier;

      const highlightFillTile =
        !defined(surfaceTile.vertexArray) &&
        defined(tileProvider.fillHighlightColor) &&
        tileProvider.fillHighlightColor.alpha > 0.0;
      if (highlightFillTile) {
        Color.clone(
          tileProvider.fillHighlightColor,
          uniformMapProperties.fillHighlightColor
        );
      }

      uniformMapProperties.terrainExaggerationAndRelativeHeight.x = exaggeration;
      uniformMapProperties.terrainExaggerationAndRelativeHeight.y = exaggerationRelativeHeight;

      uniformMapProperties.center3D = mesh.center;
      Cartesian3.clone(rtc, uniformMapProperties.rtc);

      Cartesian4.clone(tileRectangle, uniformMapProperties.tileRectangle);
      uniformMapProperties.southAndNorthLatitude.x = southLatitude;
      uniformMapProperties.southAndNorthLatitude.y = northLatitude;
      uniformMapProperties.southMercatorYAndOneOverHeight.x = southMercatorY;
      uniformMapProperties.southMercatorYAndOneOverHeight.y = oneOverMercatorHeight;

      // Convert tile limiter rectangle from cartographic to texture space using the tileRectangle.
      const localizedCartographicLimitRectangle = localizedCartographicLimitRectangleScratch;
      const cartographicLimitRectangle = clipRectangleAntimeridian(
        tile.rectangle,
        tileProvider.cartographicLimitRectangle
      );

      const localizedTranslucencyRectangle = localizedTranslucencyRectangleScratch;
      const clippedTranslucencyRectangle = clipRectangleAntimeridian(
        tile.rectangle,
        translucencyRectangle
      );

      Cartesian3.fromElements(
        hueShift,
        saturationShift,
        brightnessShift,
        uniformMapProperties.hsbShift
      );

      const cartographicTileRectangle = tile.rectangle;
      const inverseTileWidth = 1.0 / cartographicTileRectangle.width;
      const inverseTileHeight = 1.0 / cartographicTileRectangle.height;
      localizedCartographicLimitRectangle.x =
        (cartographicLimitRectangle.west - cartographicTileRectangle.west) *
        inverseTileWidth;
      localizedCartographicLimitRectangle.y =
        (cartographicLimitRectangle.south - cartographicTileRectangle.south) *
        inverseTileHeight;
      localizedCartographicLimitRectangle.z =
        (cartographicLimitRectangle.east - cartographicTileRectangle.west) *
        inverseTileWidth;
      localizedCartographicLimitRectangle.w =
        (cartographicLimitRectangle.north - cartographicTileRectangle.south) *
        inverseTileHeight;

      Cartesian4.clone(
        localizedCartographicLimitRectangle,
        uniformMapProperties.localizedCartographicLimitRectangle
      );

      localizedTranslucencyRectangle.x =
        (clippedTranslucencyRectangle.west - cartographicTileRectangle.west) *
        inverseTileWidth;
      localizedTranslucencyRectangle.y =
        (clippedTranslucencyRectangle.south - cartographicTileRectangle.south) *
        inverseTileHeight;
      localizedTranslucencyRectangle.z =
        (clippedTranslucencyRectangle.east - cartographicTileRectangle.west) *
        inverseTileWidth;
      localizedTranslucencyRectangle.w =
        (clippedTranslucencyRectangle.north - cartographicTileRectangle.south) *
        inverseTileHeight;

      Cartesian4.clone(
        localizedTranslucencyRectangle,
        uniformMapProperties.localizedTranslucencyRectangle
      );

      // For performance, use fog in the shader only when the tile is in fog.
      const applyFog =
        enableFog &&
        CesiumMath.fog(tile._distance, frameState.fog.density) >
          CesiumMath.EPSILON3;
      colorCorrect = colorCorrect && (applyFog || showGroundAtmosphere);

      let applyBrightness = false;
      let applyContrast = false;
      let applyHue = false;
      let applySaturation = false;
      let applyGamma = false;
      let applyAlpha = false;
      let applyDayNightAlpha = false;
      let applySplit = false;
      let applyCutout = false;
      let applyColorToAlpha = false;

      while (numberOfDayTextures < maxTextures && imageryIndex < imageryLen) {
        const tileImagery = tileImageryCollection[imageryIndex];
        const imagery = tileImagery.readyImagery;
        ++imageryIndex;

        if (!defined(imagery) || imagery.imageryLayer.alpha === 0.0) {
          continue;
        }

        const texture = tileImagery.useWebMercatorT
          ? imagery.textureWebMercator
          : imagery.texture;

        //>>includeStart('debug', pragmas.debug);
        if (!defined(texture)) {
          // Our "ready" texture isn't actually ready.  This should never happen.
          //
          // Side note: It IS possible for it to not be in the READY ImageryState, though.
          // This can happen when a single imagery tile is shared by two terrain tiles (common)
          // and one of them (A) needs a geographic version of the tile because it is near the poles,
          // and the other (B) does not.  B can and will transition the imagery tile to the READY state
          // without reprojecting to geographic.  Then, later, A will deem that same tile not-ready-yet
          // because it only has the Web Mercator texture, and flip it back to the TRANSITIONING state.
          // The imagery tile won't be in the READY state anymore, but it's still READY enough for B's
          // purposes.
          throw new DeveloperError("readyImagery is not actually ready!");
        }
        //>>includeEnd('debug');

        const imageryLayer = imagery.imageryLayer;

        if (!defined(tileImagery.textureTranslationAndScale)) {
          tileImagery.textureTranslationAndScale = imageryLayer._calculateTextureTranslationAndScale(
            tile,
            tileImagery
          );
        }

        uniformMapProperties.dayTextures[numberOfDayTextures] = texture;
        uniformMapProperties.dayTextureTranslationAndScale[numberOfDayTextures] =
          tileImagery.textureTranslationAndScale;
        uniformMapProperties.dayTextureTexCoordsRectangle[numberOfDayTextures] =
          tileImagery.textureCoordinateRectangle;
        uniformMapProperties.dayTextureUseWebMercatorT[numberOfDayTextures] =
          tileImagery.useWebMercatorT;

        uniformMapProperties.dayTextureAlpha[numberOfDayTextures] =
          imageryLayer.alpha;
        applyAlpha =
          applyAlpha ||
          uniformMapProperties.dayTextureAlpha[numberOfDayTextures] !== 1.0;

        uniformMapProperties.dayTextureNightAlpha[numberOfDayTextures] =
          imageryLayer.nightAlpha;
        applyDayNightAlpha =
          applyDayNightAlpha ||
          uniformMapProperties.dayTextureNightAlpha[numberOfDayTextures] !== 1.0;

        uniformMapProperties.dayTextureDayAlpha[numberOfDayTextures] =
          imageryLayer.dayAlpha;
        applyDayNightAlpha =
          applyDayNightAlpha ||
          uniformMapProperties.dayTextureDayAlpha[numberOfDayTextures] !== 1.0;

        uniformMapProperties.dayTextureBrightness[numberOfDayTextures] =
          imageryLayer.brightness;
        applyBrightness =
          applyBrightness ||
          uniformMapProperties.dayTextureBrightness[numberOfDayTextures] !==
            ImageryLayer.DEFAULT_BRIGHTNESS;

        uniformMapProperties.dayTextureContrast[numberOfDayTextures] =
          imageryLayer.contrast;
        applyContrast =
          applyContrast ||
          uniformMapProperties.dayTextureContrast[numberOfDayTextures] !==
            ImageryLayer.DEFAULT_CONTRAST;

        uniformMapProperties.dayTextureHue[numberOfDayTextures] =
          imageryLayer.hue;
        applyHue =
          applyHue ||
          uniformMapProperties.dayTextureHue[numberOfDayTextures] !==
            ImageryLayer.DEFAULT_HUE;

        uniformMapProperties.dayTextureSaturation[numberOfDayTextures] =
          imageryLayer.saturation;
        applySaturation =
          applySaturation ||
          uniformMapProperties.dayTextureSaturation[numberOfDayTextures] !==
            ImageryLayer.DEFAULT_SATURATION;

        uniformMapProperties.dayTextureOneOverGamma[numberOfDayTextures] =
          1.0 / imageryLayer.gamma;
        applyGamma =
          applyGamma ||
          uniformMapProperties.dayTextureOneOverGamma[numberOfDayTextures] !==
            1.0 / ImageryLayer.DEFAULT_GAMMA;

        uniformMapProperties.dayTextureSplit[numberOfDayTextures] =
          imageryLayer.splitDirection;
        applySplit =
          applySplit ||
          uniformMapProperties.dayTextureSplit[numberOfDayTextures] !== 0.0;

        // Update cutout rectangle
        let dayTextureCutoutRectangle =
          uniformMapProperties.dayTextureCutoutRectangles[numberOfDayTextures];
        if (!defined(dayTextureCutoutRectangle)) {
          dayTextureCutoutRectangle = uniformMapProperties.dayTextureCutoutRectangles[
            numberOfDayTextures
          ] = new Cartesian4();
        }

        Cartesian4.clone(Cartesian4.ZERO, dayTextureCutoutRectangle);
        if (defined(imageryLayer.cutoutRectangle)) {
          const cutoutRectangle = clipRectangleAntimeridian(
            cartographicTileRectangle,
            imageryLayer.cutoutRectangle
          );
          const intersection = Rectangle.simpleIntersection(
            cutoutRectangle,
            cartographicTileRectangle,
            rectangleIntersectionScratch
          );
          applyCutout = defined(intersection) || applyCutout;

          dayTextureCutoutRectangle.x =
            (cutoutRectangle.west - cartographicTileRectangle.west) *
            inverseTileWidth;
          dayTextureCutoutRectangle.y =
            (cutoutRectangle.south - cartographicTileRectangle.south) *
            inverseTileHeight;
          dayTextureCutoutRectangle.z =
            (cutoutRectangle.east - cartographicTileRectangle.west) *
            inverseTileWidth;
          dayTextureCutoutRectangle.w =
            (cutoutRectangle.north - cartographicTileRectangle.south) *
            inverseTileHeight;
        }

        // Update color to alpha
        let colorToAlpha =
          uniformMapProperties.colorsToAlpha[numberOfDayTextures];
        if (!defined(colorToAlpha)) {
          colorToAlpha = uniformMapProperties.colorsToAlpha[
            numberOfDayTextures
          ] = new Cartesian4();
        }

        const hasColorToAlpha =
          defined(imageryLayer.colorToAlpha) &&
          imageryLayer.colorToAlphaThreshold > 0.0;
        applyColorToAlpha = applyColorToAlpha || hasColorToAlpha;

        if (hasColorToAlpha) {
          const color = imageryLayer.colorToAlpha;
          colorToAlpha.x = color.red;
          colorToAlpha.y = color.green;
          colorToAlpha.z = color.blue;
          colorToAlpha.w = imageryLayer.colorToAlphaThreshold;
        } else {
          colorToAlpha.w = -1.0;
        }

        if (defined(imagery.credits)) {
          const credits = imagery.credits;
          for (
            let creditIndex = 0, creditLength = credits.length;
            creditIndex < creditLength;
            ++creditIndex
          ) {
            creditDisplay.addCredit(credits[creditIndex]);
          }
        }

        ++numberOfDayTextures;
      }

      // trim texture array to the used length so we don't end up using old textures
      // which might get destroyed eventually
      uniformMapProperties.dayTextures.length = numberOfDayTextures;
      uniformMapProperties.waterMask = waterMaskTexture;
      Cartesian4.clone(
        waterMaskTranslationAndScale,
        uniformMapProperties.waterMaskTranslationAndScale
      );

      uniformMapProperties.minMaxHeight.x = encoding.minimumHeight;
      uniformMapProperties.minMaxHeight.y = encoding.maximumHeight;
      Matrix4.clone(encoding.matrix, uniformMapProperties.scaleAndBias);

      // update clipping planes
      const clippingPlanes = tileProvider._clippingPlanes;
      const clippingPlanesEnabled =
        defined(clippingPlanes) && clippingPlanes.enabled && tile.isClipped;
      if (clippingPlanesEnabled) {
        uniformMapProperties.clippingPlanesEdgeColor = Color.clone(
          clippingPlanes.edgeColor,
          uniformMapProperties.clippingPlanesEdgeColor
        );
        uniformMapProperties.clippingPlanesEdgeWidth = clippingPlanes.edgeWidth;
      }

      surfaceShaderSetOptions.numberOfDayTextures = numberOfDayTextures;
      surfaceShaderSetOptions.applyBrightness = applyBrightness;
      surfaceShaderSetOptions.applyContrast = applyContrast;
      surfaceShaderSetOptions.applyHue = applyHue;
      surfaceShaderSetOptions.applySaturation = applySaturation;
      surfaceShaderSetOptions.applyGamma = applyGamma;
      surfaceShaderSetOptions.applyAlpha = applyAlpha;
      surfaceShaderSetOptions.applyDayNightAlpha = applyDayNightAlpha;
      surfaceShaderSetOptions.applySplit = applySplit;
      surfaceShaderSetOptions.enableFog = applyFog;
      surfaceShaderSetOptions.enableClippingPlanes = clippingPlanesEnabled;
      surfaceShaderSetOptions.clippingPlanes = clippingPlanes;
      surfaceShaderSetOptions.hasImageryLayerCutout = applyCutout;
      surfaceShaderSetOptions.colorCorrect = colorCorrect;
      surfaceShaderSetOptions.highlightFillTile = highlightFillTile;
      surfaceShaderSetOptions.colorToAlpha = applyColorToAlpha;
      surfaceShaderSetOptions.showUndergroundColor = showUndergroundColor;
      surfaceShaderSetOptions.translucent = translucent;

      let count = surfaceTile.renderedMesh.indices.length;
      if (!showSkirts) {
        count = surfaceTile.renderedMesh.indexCountWithoutSkirts;
      }

      command.shaderProgram = tileProvider._surfaceShaderSet.getShaderProgram(
        surfaceShaderSetOptions
      );
      command.castShadows = castShadows;
      command.receiveShadows = receiveShadows;
      command.renderState = renderState;
      command.primitiveType = PrimitiveType$1.TRIANGLES;
      command.vertexArray =
        surfaceTile.vertexArray || surfaceTile.fill.vertexArray;
      command.count = count;
      command.uniformMap = uniformMap;
      command.pass = Pass$1.GLOBE;

      if (tileProvider._debug.wireframe) {
        createWireframeVertexArrayIfNecessary(context, tileProvider, tile);
        if (defined(surfaceTile.wireframeVertexArray)) {
          command.vertexArray = surfaceTile.wireframeVertexArray;
          command.primitiveType = PrimitiveType$1.LINES;
          command.count = count * 2;
        }
      }

      let boundingVolume = command.boundingVolume;
      const orientedBoundingBox = command.orientedBoundingBox;

      if (frameState.mode !== SceneMode$1.SCENE3D) {
        BoundingSphere.fromRectangleWithHeights2D(
          tile.rectangle,
          frameState.mapProjection,
          tileBoundingRegion.minimumHeight,
          tileBoundingRegion.maximumHeight,
          boundingVolume
        );
        Cartesian3.fromElements(
          boundingVolume.center.z,
          boundingVolume.center.x,
          boundingVolume.center.y,
          boundingVolume.center
        );

        if (frameState.mode === SceneMode$1.MORPHING) {
          boundingVolume = BoundingSphere.union(
            tileBoundingRegion.boundingSphere,
            boundingVolume,
            boundingVolume
          );
        }
      } else {
        command.boundingVolume = BoundingSphere.clone(
          tileBoundingRegion.boundingSphere,
          boundingVolume
        );
        command.orientedBoundingBox = OrientedBoundingBox.clone(
          tileBoundingRegion.boundingVolume,
          orientedBoundingBox
        );
      }

      command.dirty = true;

      if (translucent) {
        globeTranslucencyState.updateDerivedCommands(command, frameState);
      }

      pushCommand(command, frameState);

      renderState = otherPassesRenderState;
      initialColor = otherPassesInitialColor;
    } while (imageryIndex < imageryLen);
  }

  /**
   * Properties for controlling globe translucency.
   *
   * @alias GlobeTranslucency
   * @constructor
   */
  function GlobeTranslucency() {
    this._enabled = false;
    this._frontFaceAlpha = 1.0;
    this._frontFaceAlphaByDistance = undefined;
    this._backFaceAlpha = 1.0;
    this._backFaceAlphaByDistance = undefined;
    this._rectangle = Rectangle.clone(Rectangle.MAX_VALUE);
  }

  Object.defineProperties(GlobeTranslucency.prototype, {
    /**
     * When true, the globe is rendered as a translucent surface.
     * <br /><br />
     * The alpha is computed by blending {@link Globe#material}, {@link Globe#imageryLayers},
     * and {@link Globe#baseColor}, all of which may contain translucency, and then multiplying by
     * {@link GlobeTranslucency#frontFaceAlpha} and {@link GlobeTranslucency#frontFaceAlphaByDistance} for front faces and
     * {@link GlobeTranslucency#backFaceAlpha} and {@link GlobeTranslucency#backFaceAlphaByDistance} for back faces.
     * When the camera is underground back faces and front faces are swapped, i.e. back-facing geometry
     * is considered front facing.
     * <br /><br />
     * Translucency is disabled by default.
     *
     * @memberof GlobeTranslucency.prototype
     *
     * @type {Boolean}
     * @default false
     *
     * @see GlobeTranslucency#frontFaceAlpha
     * @see GlobeTranslucency#frontFaceAlphaByDistance
     * @see GlobeTranslucency#backFaceAlpha
     * @see GlobeTranslucency#backFaceAlphaByDistance
     */
    enabled: {
      get: function () {
        return this._enabled;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.bool("enabled", value);
        //>>includeEnd('debug');
        this._enabled = value;
      },
    },

    /**
     * A constant translucency to apply to front faces of the globe.
     * <br /><br />
     * {@link GlobeTranslucency#enabled} must be set to true for this option to take effect.
     *
     * @memberof GlobeTranslucency.prototype
     *
     * @type {Number}
     * @default 1.0
     *
     * @see GlobeTranslucency#enabled
     * @see GlobeTranslucency#frontFaceAlphaByDistance
     *
     * @example
     * // Set front face translucency to 0.5.
     * globe.translucency.frontFaceAlpha = 0.5;
     * globe.translucency.enabled = true;
     */
    frontFaceAlpha: {
      get: function () {
        return this._frontFaceAlpha;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number.greaterThanOrEquals("frontFaceAlpha", value, 0.0);
        Check.typeOf.number.lessThanOrEquals("frontFaceAlpha", value, 1.0);
        //>>includeEnd('debug');
        this._frontFaceAlpha = value;
      },
    },
    /**
     * Gets or sets near and far translucency properties of front faces of the globe based on the distance to the camera.
     * The translucency will interpolate between the {@link NearFarScalar#nearValue} and
     * {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds
     * of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}.
     * Outside of these ranges the translucency remains clamped to the nearest bound.  If undefined,
     * frontFaceAlphaByDistance will be disabled.
     * <br /><br />
     * {@link GlobeTranslucency#enabled} must be set to true for this option to take effect.
     *
     * @memberof GlobeTranslucency.prototype
     *
     * @type {NearFarScalar}
     * @default undefined
     *
     * @see GlobeTranslucency#enabled
     * @see GlobeTranslucency#frontFaceAlpha
     *
     * @example
     * // Example 1.
     * // Set front face translucency to 0.5 when the
     * // camera is 1500 meters from the surface and 1.0
     * // as the camera distance approaches 8.0e6 meters.
     * globe.translucency.frontFaceAlphaByDistance = new Cesium.NearFarScalar(1.5e2, 0.5, 8.0e6, 1.0);
     * globe.translucency.enabled = true;
     *
     * @example
     * // Example 2.
     * // Disable front face translucency by distance
     * globe.translucency.frontFaceAlphaByDistance = undefined;
     */
    frontFaceAlphaByDistance: {
      get: function () {
        return this._frontFaceAlphaByDistance;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (defined(value) && value.far < value.near) {
          throw new DeveloperError(
            "far distance must be greater than near distance."
          );
        }
        //>>includeEnd('debug');
        this._frontFaceAlphaByDistance = NearFarScalar.clone(
          value,
          this._frontFaceAlphaByDistance
        );
      },
    },

    /**
     * A constant translucency to apply to back faces of the globe.
     * <br /><br />
     * {@link GlobeTranslucency#enabled} must be set to true for this option to take effect.
     *
     * @memberof GlobeTranslucency.prototype
     *
     * @type {Number}
     * @default 1.0
     *
     * @see GlobeTranslucency#enabled
     * @see GlobeTranslucency#backFaceAlphaByDistance
     *
     * @example
     * // Set back face translucency to 0.5.
     * globe.translucency.backFaceAlpha = 0.5;
     * globe.translucency.enabled = true;
     */
    backFaceAlpha: {
      get: function () {
        return this._backFaceAlpha;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number.greaterThanOrEquals("backFaceAlpha", value, 0.0);
        Check.typeOf.number.lessThanOrEquals("backFaceAlpha", value, 1.0);
        //>>includeEnd('debug');
        this._backFaceAlpha = value;
      },
    },
    /**
     * Gets or sets near and far translucency properties of back faces of the globe based on the distance to the camera.
     * The translucency will interpolate between the {@link NearFarScalar#nearValue} and
     * {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds
     * of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}.
     * Outside of these ranges the translucency remains clamped to the nearest bound.  If undefined,
     * backFaceAlphaByDistance will be disabled.
     * <br /><br />
     * {@link GlobeTranslucency#enabled} must be set to true for this option to take effect.
     *
     * @memberof GlobeTranslucency.prototype
     *
     * @type {NearFarScalar}
     * @default undefined
     *
     * @see GlobeTranslucency#enabled
     * @see GlobeTranslucency#backFaceAlpha
     *
     * @example
     * // Example 1.
     * // Set back face translucency to 0.5 when the
     * // camera is 1500 meters from the surface and 1.0
     * // as the camera distance approaches 8.0e6 meters.
     * globe.translucency.backFaceAlphaByDistance = new Cesium.NearFarScalar(1.5e2, 0.5, 8.0e6, 1.0);
     * globe.translucency.enabled = true;
     *
     * @example
     * // Example 2.
     * // Disable back face translucency by distance
     * globe.translucency.backFaceAlphaByDistance = undefined;
     */
    backFaceAlphaByDistance: {
      get: function () {
        return this._backFaceAlphaByDistance;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (defined(value) && value.far < value.near) {
          throw new DeveloperError(
            "far distance must be greater than near distance."
          );
        }
        //>>includeEnd('debug');
        this._backFaceAlphaByDistance = NearFarScalar.clone(
          value,
          this._backFaceAlphaByDistance
        );
      },
    },

    /**
     * A property specifying a {@link Rectangle} used to limit translucency to a cartographic area.
     * Defaults to the maximum extent of cartographic coordinates.
     *
     * @memberof GlobeTranslucency.prototype
     *
     * @type {Rectangle}
     * @default {@link Rectangle.MAX_VALUE}
     */
    rectangle: {
      get: function () {
        return this._rectangle;
      },
      set: function (value) {
        if (!defined(value)) {
          value = Rectangle.clone(Rectangle.MAX_VALUE);
        }
        Rectangle.clone(value, this._rectangle);
      },
    },
  });

  /**
   * An ordered collection of imagery layers.
   *
   * @alias ImageryLayerCollection
   * @constructor
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Imagery%20Adjustment.html|Cesium Sandcastle Imagery Adjustment Demo}
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Imagery%20Layers%20Manipulation.html|Cesium Sandcastle Imagery Manipulation Demo}
   */
  function ImageryLayerCollection() {
    this._layers = [];

    /**
     * An event that is raised when a layer is added to the collection.  Event handlers are passed the layer that
     * was added and the index at which it was added.
     * @type {Event}
     * @default Event()
     */
    this.layerAdded = new Event();

    /**
     * An event that is raised when a layer is removed from the collection.  Event handlers are passed the layer that
     * was removed and the index from which it was removed.
     * @type {Event}
     * @default Event()
     */
    this.layerRemoved = new Event();

    /**
     * An event that is raised when a layer changes position in the collection.  Event handlers are passed the layer that
     * was moved, its new index after the move, and its old index prior to the move.
     * @type {Event}
     * @default Event()
     */
    this.layerMoved = new Event();

    /**
     * An event that is raised when a layer is shown or hidden by setting the
     * {@link ImageryLayer#show} property.  Event handlers are passed a reference to this layer,
     * the index of the layer in the collection, and a flag that is true if the layer is now
     * shown or false if it is now hidden.
     *
     * @type {Event}
     * @default Event()
     */
    this.layerShownOrHidden = new Event();
  }

  Object.defineProperties(ImageryLayerCollection.prototype, {
    /**
     * Gets the number of layers in this collection.
     * @memberof ImageryLayerCollection.prototype
     * @type {Number}
     */
    length: {
      get: function () {
        return this._layers.length;
      },
    },
  });

  /**
   * Adds a layer to the collection.
   *
   * @param {ImageryLayer} layer the layer to add.
   * @param {Number} [index] the index to add the layer at.  If omitted, the layer will
   *                         be added on top of all existing layers.
   *
   * @exception {DeveloperError} index, if supplied, must be greater than or equal to zero and less than or equal to the number of the layers.
   */
  ImageryLayerCollection.prototype.add = function (layer, index) {
    const hasIndex = defined(index);

    //>>includeStart('debug', pragmas.debug);
    if (!defined(layer)) {
      throw new DeveloperError("layer is required.");
    }
    if (hasIndex) {
      if (index < 0) {
        throw new DeveloperError("index must be greater than or equal to zero.");
      } else if (index > this._layers.length) {
        throw new DeveloperError(
          "index must be less than or equal to the number of layers."
        );
      }
    }
    //>>includeEnd('debug');

    if (!hasIndex) {
      index = this._layers.length;
      this._layers.push(layer);
    } else {
      this._layers.splice(index, 0, layer);
    }

    this._update();
    this.layerAdded.raiseEvent(layer, index);
  };

  /**
   * Creates a new layer using the given ImageryProvider and adds it to the collection.
   *
   * @param {ImageryProvider} imageryProvider the imagery provider to create a new layer for.
   * @param {Number} [index] the index to add the layer at.  If omitted, the layer will
   *                         added on top of all existing layers.
   * @returns {ImageryLayer} The newly created layer.
   */
  ImageryLayerCollection.prototype.addImageryProvider = function (
    imageryProvider,
    index
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(imageryProvider)) {
      throw new DeveloperError("imageryProvider is required.");
    }
    //>>includeEnd('debug');

    const layer = new ImageryLayer(imageryProvider);
    this.add(layer, index);
    return layer;
  };

  /**
   * Removes a layer from this collection, if present.
   *
   * @param {ImageryLayer} layer The layer to remove.
   * @param {Boolean} [destroy=true] whether to destroy the layers in addition to removing them.
   * @returns {Boolean} true if the layer was in the collection and was removed,
   *                    false if the layer was not in the collection.
   */
  ImageryLayerCollection.prototype.remove = function (layer, destroy) {
    destroy = defaultValue(destroy, true);

    const index = this._layers.indexOf(layer);
    if (index !== -1) {
      this._layers.splice(index, 1);

      this._update();

      this.layerRemoved.raiseEvent(layer, index);

      if (destroy) {
        layer.destroy();
      }

      return true;
    }

    return false;
  };

  /**
   * Removes all layers from this collection.
   *
   * @param {Boolean} [destroy=true] whether to destroy the layers in addition to removing them.
   */
  ImageryLayerCollection.prototype.removeAll = function (destroy) {
    destroy = defaultValue(destroy, true);

    const layers = this._layers;
    for (let i = 0, len = layers.length; i < len; i++) {
      const layer = layers[i];
      this.layerRemoved.raiseEvent(layer, i);

      if (destroy) {
        layer.destroy();
      }
    }

    this._layers = [];
  };

  /**
   * Checks to see if the collection contains a given layer.
   *
   * @param {ImageryLayer} layer the layer to check for.
   *
   * @returns {Boolean} true if the collection contains the layer, false otherwise.
   */
  ImageryLayerCollection.prototype.contains = function (layer) {
    return this.indexOf(layer) !== -1;
  };

  /**
   * Determines the index of a given layer in the collection.
   *
   * @param {ImageryLayer} layer The layer to find the index of.
   *
   * @returns {Number} The index of the layer in the collection, or -1 if the layer does not exist in the collection.
   */
  ImageryLayerCollection.prototype.indexOf = function (layer) {
    return this._layers.indexOf(layer);
  };

  /**
   * Gets a layer by index from the collection.
   *
   * @param {Number} index the index to retrieve.
   *
   * @returns {ImageryLayer} The imagery layer at the given index.
   */
  ImageryLayerCollection.prototype.get = function (index) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(index)) {
      throw new DeveloperError("index is required.");
    }
    //>>includeEnd('debug');

    return this._layers[index];
  };

  function getLayerIndex(layers, layer) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(layer)) {
      throw new DeveloperError("layer is required.");
    }
    //>>includeEnd('debug');

    const index = layers.indexOf(layer);

    //>>includeStart('debug', pragmas.debug);
    if (index === -1) {
      throw new DeveloperError("layer is not in this collection.");
    }
    //>>includeEnd('debug');

    return index;
  }

  function swapLayers(collection, i, j) {
    const arr = collection._layers;
    i = CesiumMath.clamp(i, 0, arr.length - 1);
    j = CesiumMath.clamp(j, 0, arr.length - 1);

    if (i === j) {
      return;
    }

    const temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;

    collection._update();

    collection.layerMoved.raiseEvent(temp, j, i);
  }

  /**
   * Raises a layer up one position in the collection.
   *
   * @param {ImageryLayer} layer the layer to move.
   *
   * @exception {DeveloperError} layer is not in this collection.
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   */
  ImageryLayerCollection.prototype.raise = function (layer) {
    const index = getLayerIndex(this._layers, layer);
    swapLayers(this, index, index + 1);
  };

  /**
   * Lowers a layer down one position in the collection.
   *
   * @param {ImageryLayer} layer the layer to move.
   *
   * @exception {DeveloperError} layer is not in this collection.
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   */
  ImageryLayerCollection.prototype.lower = function (layer) {
    const index = getLayerIndex(this._layers, layer);
    swapLayers(this, index, index - 1);
  };

  /**
   * Raises a layer to the top of the collection.
   *
   * @param {ImageryLayer} layer the layer to move.
   *
   * @exception {DeveloperError} layer is not in this collection.
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   */
  ImageryLayerCollection.prototype.raiseToTop = function (layer) {
    const index = getLayerIndex(this._layers, layer);
    if (index === this._layers.length - 1) {
      return;
    }
    this._layers.splice(index, 1);
    this._layers.push(layer);

    this._update();

    this.layerMoved.raiseEvent(layer, this._layers.length - 1, index);
  };

  /**
   * Lowers a layer to the bottom of the collection.
   *
   * @param {ImageryLayer} layer the layer to move.
   *
   * @exception {DeveloperError} layer is not in this collection.
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   */
  ImageryLayerCollection.prototype.lowerToBottom = function (layer) {
    const index = getLayerIndex(this._layers, layer);
    if (index === 0) {
      return;
    }
    this._layers.splice(index, 1);
    this._layers.splice(0, 0, layer);

    this._update();

    this.layerMoved.raiseEvent(layer, 0, index);
  };

  const applicableRectangleScratch = new Rectangle();

  function pickImageryHelper(scene, pickedLocation, pickFeatures, callback) {
    // Find the terrain tile containing the picked location.
    const tilesToRender = scene.globe._surface._tilesToRender;
    let pickedTile;

    for (
      let textureIndex = 0;
      !defined(pickedTile) && textureIndex < tilesToRender.length;
      ++textureIndex
    ) {
      const tile = tilesToRender[textureIndex];
      if (Rectangle.contains(tile.rectangle, pickedLocation)) {
        pickedTile = tile;
      }
    }

    if (!defined(pickedTile)) {
      return;
    }

    // Pick against all attached imagery tiles containing the pickedLocation.
    const imageryTiles = pickedTile.data.imagery;

    for (let i = imageryTiles.length - 1; i >= 0; --i) {
      const terrainImagery = imageryTiles[i];
      const imagery = terrainImagery.readyImagery;
      if (!defined(imagery)) {
        continue;
      }
      const provider = imagery.imageryLayer.imageryProvider;
      if (pickFeatures && !defined(provider.pickFeatures)) {
        continue;
      }

      if (!Rectangle.contains(imagery.rectangle, pickedLocation)) {
        continue;
      }

      // If this imagery came from a parent, it may not be applicable to its entire rectangle.
      // Check the textureCoordinateRectangle.
      const applicableRectangle = applicableRectangleScratch;

      const epsilon = 1 / 1024; // 1/4 of a pixel in a typical 256x256 tile.
      applicableRectangle.west = CesiumMath.lerp(
        pickedTile.rectangle.west,
        pickedTile.rectangle.east,
        terrainImagery.textureCoordinateRectangle.x - epsilon
      );
      applicableRectangle.east = CesiumMath.lerp(
        pickedTile.rectangle.west,
        pickedTile.rectangle.east,
        terrainImagery.textureCoordinateRectangle.z + epsilon
      );
      applicableRectangle.south = CesiumMath.lerp(
        pickedTile.rectangle.south,
        pickedTile.rectangle.north,
        terrainImagery.textureCoordinateRectangle.y - epsilon
      );
      applicableRectangle.north = CesiumMath.lerp(
        pickedTile.rectangle.south,
        pickedTile.rectangle.north,
        terrainImagery.textureCoordinateRectangle.w + epsilon
      );
      if (!Rectangle.contains(applicableRectangle, pickedLocation)) {
        continue;
      }

      callback(imagery);
    }
  }

  /**
   * Determines the imagery layers that are intersected by a pick ray. To compute a pick ray from a
   * location on the screen, use {@link Camera.getPickRay}.
   *
   * @param {Ray} ray The ray to test for intersection.
   * @param {Scene} scene The scene.
   * @return {ImageryLayer[]|undefined} An array that includes all of
   *                                 the layers that are intersected by a given pick ray. Undefined if
   *                                 no layers are selected.
   *
   */
  ImageryLayerCollection.prototype.pickImageryLayers = function (ray, scene) {
    // Find the picked location on the globe.
    const pickedPosition = scene.globe.pick(ray, scene);
    if (!defined(pickedPosition)) {
      return;
    }

    const pickedLocation = scene.globe.ellipsoid.cartesianToCartographic(
      pickedPosition
    );

    const imageryLayers = [];

    pickImageryHelper(scene, pickedLocation, false, function (imagery) {
      imageryLayers.push(imagery.imageryLayer);
    });

    if (imageryLayers.length === 0) {
      return undefined;
    }

    return imageryLayers;
  };

  /**
   * Asynchronously determines the imagery layer features that are intersected by a pick ray.  The intersected imagery
   * layer features are found by invoking {@link ImageryProvider#pickFeatures} for each imagery layer tile intersected
   * by the pick ray.  To compute a pick ray from a location on the screen, use {@link Camera.getPickRay}.
   *
   * @param {Ray} ray The ray to test for intersection.
   * @param {Scene} scene The scene.
   * @return {Promise.<ImageryLayerFeatureInfo[]>|undefined} A promise that resolves to an array of features intersected by the pick ray.
   *                                             If it can be quickly determined that no features are intersected (for example,
   *                                             because no active imagery providers support {@link ImageryProvider#pickFeatures}
   *                                             or because the pick ray does not intersect the surface), this function will
   *                                             return undefined.
   *
   * @example
   * const pickRay = viewer.camera.getPickRay(windowPosition);
   * const featuresPromise = viewer.imageryLayers.pickImageryLayerFeatures(pickRay, viewer.scene);
   * if (!Cesium.defined(featuresPromise)) {
   *     console.log('No features picked.');
   * } else {
   *     Promise.resolve(featuresPromise).then(function(features) {
   *         // This function is called asynchronously when the list if picked features is available.
   *         console.log(`Number of features: ${features.length}`);
   *         if (features.length > 0) {
   *             console.log(`First feature name: ${features[0].name}`);
   *         }
   *     });
   * }
   */
  ImageryLayerCollection.prototype.pickImageryLayerFeatures = function (
    ray,
    scene
  ) {
    // Find the picked location on the globe.
    const pickedPosition = scene.globe.pick(ray, scene);
    if (!defined(pickedPosition)) {
      return;
    }

    const pickedLocation = scene.globe.ellipsoid.cartesianToCartographic(
      pickedPosition
    );

    const promises = [];
    const imageryLayers = [];

    pickImageryHelper(scene, pickedLocation, true, function (imagery) {
      const provider = imagery.imageryLayer.imageryProvider;
      const promise = provider.pickFeatures(
        imagery.x,
        imagery.y,
        imagery.level,
        pickedLocation.longitude,
        pickedLocation.latitude
      );
      if (defined(promise)) {
        promises.push(promise);
        imageryLayers.push(imagery.imageryLayer);
      }
    });

    if (promises.length === 0) {
      return undefined;
    }
    return Promise.all(promises).then(function (results) {
      const features = [];
      for (let resultIndex = 0; resultIndex < results.length; ++resultIndex) {
        const result = results[resultIndex];
        const image = imageryLayers[resultIndex];
        if (defined(result) && result.length > 0) {
          for (
            let featureIndex = 0;
            featureIndex < result.length;
            ++featureIndex
          ) {
            const feature = result[featureIndex];
            feature.imageryLayer = image;
            // For features without a position, use the picked location.
            if (!defined(feature.position)) {
              feature.position = pickedLocation;
            }
            features.push(feature);
          }
        }
      }
      return features;
    });
  };

  /**
   * Updates frame state to execute any queued texture re-projections.
   *
   * @private
   *
   * @param {FrameState} frameState The frameState.
   */
  ImageryLayerCollection.prototype.queueReprojectionCommands = function (
    frameState
  ) {
    const layers = this._layers;
    for (let i = 0, len = layers.length; i < len; ++i) {
      layers[i].queueReprojectionCommands(frameState);
    }
  };

  /**
   * Cancels re-projection commands queued for the next frame.
   *
   * @private
   */
  ImageryLayerCollection.prototype.cancelReprojections = function () {
    const layers = this._layers;
    for (let i = 0, len = layers.length; i < len; ++i) {
      layers[i].cancelReprojections();
    }
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} true if this object was destroyed; otherwise, false.
   *
   * @see ImageryLayerCollection#destroy
   */
  ImageryLayerCollection.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by all layers in this collection.  Explicitly destroying this
   * object allows for deterministic release of WebGL resources, instead of relying on the garbage
   * collector.
   * <br /><br />
   * Once this object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * layerCollection = layerCollection && layerCollection.destroy();
   *
   * @see ImageryLayerCollection#isDestroyed
   */
  ImageryLayerCollection.prototype.destroy = function () {
    this.removeAll(true);
    return destroyObject(this);
  };

  ImageryLayerCollection.prototype._update = function () {
    let isBaseLayer = true;
    const layers = this._layers;
    let layersShownOrHidden;
    let layer;
    let i, len;
    for (i = 0, len = layers.length; i < len; ++i) {
      layer = layers[i];

      layer._layerIndex = i;

      if (layer.show) {
        layer._isBaseLayer = isBaseLayer;
        isBaseLayer = false;
      } else {
        layer._isBaseLayer = false;
      }

      if (layer.show !== layer._show) {
        if (defined(layer._show)) {
          if (!defined(layersShownOrHidden)) {
            layersShownOrHidden = [];
          }
          layersShownOrHidden.push(layer);
        }
        layer._show = layer.show;
      }
    }

    if (defined(layersShownOrHidden)) {
      for (i = 0, len = layersShownOrHidden.length; i < len; ++i) {
        layer = layersShownOrHidden[i];
        this.layerShownOrHidden.raiseEvent(layer, layer._layerIndex, layer.show);
      }
    }
  };

  /**
   * A set of occluders that can be used to test quadtree tiles for occlusion.
   *
   * @alias QuadtreeOccluders
   * @constructor
   * @private
   *
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid that potentially occludes tiles.
   */
  function QuadtreeOccluders(options) {
    this._ellipsoid = new EllipsoidalOccluder(options.ellipsoid, Cartesian3.ZERO);
  }

  Object.defineProperties(QuadtreeOccluders.prototype, {
    /**
     * Gets the {@link EllipsoidalOccluder} that can be used to determine if a point is
     * occluded by an {@link Ellipsoid}.
     * @type {EllipsoidalOccluder}
     * @memberof QuadtreeOccluders.prototype
     */
    ellipsoid: {
      get: function () {
        return this._ellipsoid;
      },
    },
  });

  /**
   * A single tile in a {@link QuadtreePrimitive}.
   *
   * @alias QuadtreeTile
   * @constructor
   * @private
   *
   * @param {Number} options.level The level of the tile in the quadtree.
   * @param {Number} options.x The X coordinate of the tile in the quadtree.  0 is the westernmost tile.
   * @param {Number} options.y The Y coordinate of the tile in the quadtree.  0 is the northernmost tile.
   * @param {TilingScheme} options.tilingScheme The tiling scheme in which this tile exists.
   * @param {QuadtreeTile} [options.parent] This tile's parent, or undefined if this is a root tile.
   */
  function QuadtreeTile(options) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(options)) {
      throw new DeveloperError("options is required.");
    }
    if (!defined(options.x)) {
      throw new DeveloperError("options.x is required.");
    } else if (!defined(options.y)) {
      throw new DeveloperError("options.y is required.");
    } else if (options.x < 0 || options.y < 0) {
      throw new DeveloperError(
        "options.x and options.y must be greater than or equal to zero."
      );
    }
    if (!defined(options.level)) {
      throw new DeveloperError(
        "options.level is required and must be greater than or equal to zero."
      );
    }
    if (!defined(options.tilingScheme)) {
      throw new DeveloperError("options.tilingScheme is required.");
    }
    //>>includeEnd('debug');

    this._tilingScheme = options.tilingScheme;
    this._x = options.x;
    this._y = options.y;
    this._level = options.level;
    this._parent = options.parent;
    this._rectangle = this._tilingScheme.tileXYToRectangle(
      this._x,
      this._y,
      this._level
    );

    this._southwestChild = undefined;
    this._southeastChild = undefined;
    this._northwestChild = undefined;
    this._northeastChild = undefined;

    // TileReplacementQueue gets/sets these private properties.
    this.replacementPrevious = undefined;
    this.replacementNext = undefined;

    // The distance from the camera to this tile, updated when the tile is selected
    // for rendering.  We can get rid of this if we have a better way to sort by
    // distance - for example, by using the natural ordering of a quadtree.
    // QuadtreePrimitive gets/sets this private property.
    this._distance = 0.0;
    this._loadPriority = 0.0;

    this._customData = [];
    this._frameUpdated = undefined;
    this._lastSelectionResult = TileSelectionResult.NONE;
    this._lastSelectionResultFrame = undefined;
    this._loadedCallbacks = {};

    /**
     * Gets or sets the current state of the tile in the tile load pipeline.
     * @type {QuadtreeTileLoadState}
     * @default {@link QuadtreeTileLoadState.START}
     */
    this.state = QuadtreeTileLoadState$1.START;

    /**
     * Gets or sets a value indicating whether or not the tile is currently renderable.
     * @type {Boolean}
     * @default false
     */
    this.renderable = false;

    /**
     * Gets or set a value indicating whether or not the tile was entirely upsampled from its
     * parent tile.  If all four children of a parent tile were upsampled from the parent,
     * we will render the parent instead of the children even if the LOD indicates that
     * the children would be preferable.
     * @type {Boolean}
     * @default false
     */
    this.upsampledFromParent = false;

    /**
     * Gets or sets the additional data associated with this tile.  The exact content is specific to the
     * {@link QuadtreeTileProvider}.
     * @type {Object}
     * @default undefined
     */
    this.data = undefined;
  }

  /**
   * Creates a rectangular set of tiles for level of detail zero, the coarsest, least detailed level.
   *
   * @memberof QuadtreeTile
   *
   * @param {TilingScheme} tilingScheme The tiling scheme for which the tiles are to be created.
   * @returns {QuadtreeTile[]} An array containing the tiles at level of detail zero, starting with the
   * tile in the northwest corner and followed by the tile (if any) to its east.
   */
  QuadtreeTile.createLevelZeroTiles = function (tilingScheme) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(tilingScheme)) {
      throw new DeveloperError("tilingScheme is required.");
    }
    //>>includeEnd('debug');

    const numberOfLevelZeroTilesX = tilingScheme.getNumberOfXTilesAtLevel(0);
    const numberOfLevelZeroTilesY = tilingScheme.getNumberOfYTilesAtLevel(0);

    const result = new Array(numberOfLevelZeroTilesX * numberOfLevelZeroTilesY);

    let index = 0;
    for (let y = 0; y < numberOfLevelZeroTilesY; ++y) {
      for (let x = 0; x < numberOfLevelZeroTilesX; ++x) {
        result[index++] = new QuadtreeTile({
          tilingScheme: tilingScheme,
          x: x,
          y: y,
          level: 0,
        });
      }
    }

    return result;
  };

  QuadtreeTile.prototype._updateCustomData = function (
    frameNumber,
    added,
    removed
  ) {
    let customData = this.customData;

    let i;
    let data;
    let rectangle;

    if (defined(added) && defined(removed)) {
      customData = customData.filter(function (value) {
        return removed.indexOf(value) === -1;
      });
      this._customData = customData;

      rectangle = this._rectangle;
      for (i = 0; i < added.length; ++i) {
        data = added[i];
        if (Rectangle.contains(rectangle, data.positionCartographic)) {
          customData.push(data);
        }
      }

      this._frameUpdated = frameNumber;
    } else {
      // interior or leaf tile, update from parent
      const parent = this._parent;
      if (defined(parent) && this._frameUpdated !== parent._frameUpdated) {
        customData.length = 0;

        rectangle = this._rectangle;
        const parentCustomData = parent.customData;
        for (i = 0; i < parentCustomData.length; ++i) {
          data = parentCustomData[i];
          if (Rectangle.contains(rectangle, data.positionCartographic)) {
            customData.push(data);
          }
        }

        this._frameUpdated = parent._frameUpdated;
      }
    }
  };

  Object.defineProperties(QuadtreeTile.prototype, {
    /**
     * Gets the tiling scheme used to tile the surface.
     * @memberof QuadtreeTile.prototype
     * @type {TilingScheme}
     */
    tilingScheme: {
      get: function () {
        return this._tilingScheme;
      },
    },

    /**
     * Gets the tile X coordinate.
     * @memberof QuadtreeTile.prototype
     * @type {Number}
     */
    x: {
      get: function () {
        return this._x;
      },
    },

    /**
     * Gets the tile Y coordinate.
     * @memberof QuadtreeTile.prototype
     * @type {Number}
     */
    y: {
      get: function () {
        return this._y;
      },
    },

    /**
     * Gets the level-of-detail, where zero is the coarsest, least-detailed.
     * @memberof QuadtreeTile.prototype
     * @type {Number}
     */
    level: {
      get: function () {
        return this._level;
      },
    },

    /**
     * Gets the parent tile of this tile.
     * @memberof QuadtreeTile.prototype
     * @type {QuadtreeTile}
     */
    parent: {
      get: function () {
        return this._parent;
      },
    },

    /**
     * Gets the cartographic rectangle of the tile, with north, south, east and
     * west properties in radians.
     * @memberof QuadtreeTile.prototype
     * @type {Rectangle}
     */
    rectangle: {
      get: function () {
        return this._rectangle;
      },
    },

    /**
     * An array of tiles that is at the next level of the tile tree.
     * @memberof QuadtreeTile.prototype
     * @type {QuadtreeTile[]}
     */
    children: {
      get: function () {
        return [
          this.northwestChild,
          this.northeastChild,
          this.southwestChild,
          this.southeastChild,
        ];
      },
    },

    /**
     * Gets the southwest child tile.
     * @memberof QuadtreeTile.prototype
     * @type {QuadtreeTile}
     */
    southwestChild: {
      get: function () {
        if (!defined(this._southwestChild)) {
          this._southwestChild = new QuadtreeTile({
            tilingScheme: this.tilingScheme,
            x: this.x * 2,
            y: this.y * 2 + 1,
            level: this.level + 1,
            parent: this,
          });
        }
        return this._southwestChild;
      },
    },

    /**
     * Gets the southeast child tile.
     * @memberof QuadtreeTile.prototype
     * @type {QuadtreeTile}
     */
    southeastChild: {
      get: function () {
        if (!defined(this._southeastChild)) {
          this._southeastChild = new QuadtreeTile({
            tilingScheme: this.tilingScheme,
            x: this.x * 2 + 1,
            y: this.y * 2 + 1,
            level: this.level + 1,
            parent: this,
          });
        }
        return this._southeastChild;
      },
    },

    /**
     * Gets the northwest child tile.
     * @memberof QuadtreeTile.prototype
     * @type {QuadtreeTile}
     */
    northwestChild: {
      get: function () {
        if (!defined(this._northwestChild)) {
          this._northwestChild = new QuadtreeTile({
            tilingScheme: this.tilingScheme,
            x: this.x * 2,
            y: this.y * 2,
            level: this.level + 1,
            parent: this,
          });
        }
        return this._northwestChild;
      },
    },

    /**
     * Gets the northeast child tile.
     * @memberof QuadtreeTile.prototype
     * @type {QuadtreeTile}
     */
    northeastChild: {
      get: function () {
        if (!defined(this._northeastChild)) {
          this._northeastChild = new QuadtreeTile({
            tilingScheme: this.tilingScheme,
            x: this.x * 2 + 1,
            y: this.y * 2,
            level: this.level + 1,
            parent: this,
          });
        }
        return this._northeastChild;
      },
    },

    /**
     * An array of objects associated with this tile.
     * @memberof QuadtreeTile.prototype
     * @type {Array}
     */
    customData: {
      get: function () {
        return this._customData;
      },
    },

    /**
     * Gets a value indicating whether or not this tile needs further loading.
     * This property will return true if the {@link QuadtreeTile#state} is
     * <code>START</code> or <code>LOADING</code>.
     * @memberof QuadtreeTile.prototype
     * @type {Boolean}
     */
    needsLoading: {
      get: function () {
        return this.state < QuadtreeTileLoadState$1.DONE;
      },
    },

    /**
     * Gets a value indicating whether or not this tile is eligible to be unloaded.
     * Typically, a tile is ineligible to be unloaded while an asynchronous operation,
     * such as a request for data, is in progress on it.  A tile will never be
     * unloaded while it is needed for rendering, regardless of the value of this
     * property.  If {@link QuadtreeTile#data} is defined and has an
     * <code>eligibleForUnloading</code> property, the value of that property is returned.
     * Otherwise, this property returns true.
     * @memberof QuadtreeTile.prototype
     * @type {Boolean}
     */
    eligibleForUnloading: {
      get: function () {
        let result = true;

        if (defined(this.data)) {
          result = this.data.eligibleForUnloading;
          if (!defined(result)) {
            result = true;
          }
        }

        return result;
      },
    },
  });

  QuadtreeTile.prototype.findLevelZeroTile = function (levelZeroTiles, x, y) {
    const xTiles = this.tilingScheme.getNumberOfXTilesAtLevel(0);
    if (x < 0) {
      x += xTiles;
    } else if (x >= xTiles) {
      x -= xTiles;
    }

    if (y < 0 || y >= this.tilingScheme.getNumberOfYTilesAtLevel(0)) {
      return undefined;
    }

    return levelZeroTiles.filter(function (tile) {
      return tile.x === x && tile.y === y;
    })[0];
  };

  QuadtreeTile.prototype.findTileToWest = function (levelZeroTiles) {
    const parent = this.parent;
    if (parent === undefined) {
      return this.findLevelZeroTile(levelZeroTiles, this.x - 1, this.y);
    }

    if (parent.southeastChild === this) {
      return parent.southwestChild;
    } else if (parent.northeastChild === this) {
      return parent.northwestChild;
    }

    const westOfParent = parent.findTileToWest(levelZeroTiles);
    if (westOfParent === undefined) {
      return undefined;
    } else if (parent.southwestChild === this) {
      return westOfParent.southeastChild;
    }
    return westOfParent.northeastChild;
  };

  QuadtreeTile.prototype.findTileToEast = function (levelZeroTiles) {
    const parent = this.parent;
    if (parent === undefined) {
      return this.findLevelZeroTile(levelZeroTiles, this.x + 1, this.y);
    }

    if (parent.southwestChild === this) {
      return parent.southeastChild;
    } else if (parent.northwestChild === this) {
      return parent.northeastChild;
    }

    const eastOfParent = parent.findTileToEast(levelZeroTiles);
    if (eastOfParent === undefined) {
      return undefined;
    } else if (parent.southeastChild === this) {
      return eastOfParent.southwestChild;
    }
    return eastOfParent.northwestChild;
  };

  QuadtreeTile.prototype.findTileToSouth = function (levelZeroTiles) {
    const parent = this.parent;
    if (parent === undefined) {
      return this.findLevelZeroTile(levelZeroTiles, this.x, this.y + 1);
    }

    if (parent.northwestChild === this) {
      return parent.southwestChild;
    } else if (parent.northeastChild === this) {
      return parent.southeastChild;
    }

    const southOfParent = parent.findTileToSouth(levelZeroTiles);
    if (southOfParent === undefined) {
      return undefined;
    } else if (parent.southwestChild === this) {
      return southOfParent.northwestChild;
    }
    return southOfParent.northeastChild;
  };

  QuadtreeTile.prototype.findTileToNorth = function (levelZeroTiles) {
    const parent = this.parent;
    if (parent === undefined) {
      return this.findLevelZeroTile(levelZeroTiles, this.x, this.y - 1);
    }

    if (parent.southwestChild === this) {
      return parent.northwestChild;
    } else if (parent.southeastChild === this) {
      return parent.northeastChild;
    }

    const northOfParent = parent.findTileToNorth(levelZeroTiles);
    if (northOfParent === undefined) {
      return undefined;
    } else if (parent.northwestChild === this) {
      return northOfParent.southwestChild;
    }
    return northOfParent.southeastChild;
  };

  /**
   * Frees the resources associated with this tile and returns it to the <code>START</code>
   * {@link QuadtreeTileLoadState}.  If the {@link QuadtreeTile#data} property is defined and it
   * has a <code>freeResources</code> method, the method will be invoked.
   *
   * @memberof QuadtreeTile
   */
  QuadtreeTile.prototype.freeResources = function () {
    this.state = QuadtreeTileLoadState$1.START;
    this.renderable = false;
    this.upsampledFromParent = false;

    if (defined(this.data) && defined(this.data.freeResources)) {
      this.data.freeResources();
    }

    freeTile(this._southwestChild);
    this._southwestChild = undefined;
    freeTile(this._southeastChild);
    this._southeastChild = undefined;
    freeTile(this._northwestChild);
    this._northwestChild = undefined;
    freeTile(this._northeastChild);
    this._northeastChild = undefined;
  };

  function freeTile(tile) {
    if (defined(tile)) {
      tile.freeResources();
    }
  }

  /**
   * A priority queue of tiles to be replaced, if necessary, to make room for new tiles.  The queue
   * is implemented as a linked list.
   *
   * @alias TileReplacementQueue
   * @private
   */
  function TileReplacementQueue() {
    this.head = undefined;
    this.tail = undefined;
    this.count = 0;
    this._lastBeforeStartOfFrame = undefined;
  }

  /**
   * Marks the start of the render frame.  Tiles before (closer to the head) this tile in the
   * list were used last frame and must not be unloaded.
   */
  TileReplacementQueue.prototype.markStartOfRenderFrame = function () {
    this._lastBeforeStartOfFrame = this.head;
  };

  /**
   * Reduces the size of the queue to a specified size by unloading the least-recently used
   * tiles.  Tiles that were used last frame will not be unloaded, even if that puts the number
   * of tiles above the specified maximum.
   *
   * @param {Number} maximumTiles The maximum number of tiles in the queue.
   */
  TileReplacementQueue.prototype.trimTiles = function (maximumTiles) {
    let tileToTrim = this.tail;
    let keepTrimming = true;
    while (
      keepTrimming &&
      defined(this._lastBeforeStartOfFrame) &&
      this.count > maximumTiles &&
      defined(tileToTrim)
    ) {
      // Stop trimming after we process the last tile not used in the
      // current frame.
      keepTrimming = tileToTrim !== this._lastBeforeStartOfFrame;

      const previous = tileToTrim.replacementPrevious;

      if (tileToTrim.eligibleForUnloading) {
        tileToTrim.freeResources();
        remove(this, tileToTrim);
      }

      tileToTrim = previous;
    }
  };

  function remove(tileReplacementQueue, item) {
    const previous = item.replacementPrevious;
    const next = item.replacementNext;

    if (item === tileReplacementQueue._lastBeforeStartOfFrame) {
      tileReplacementQueue._lastBeforeStartOfFrame = next;
    }

    if (item === tileReplacementQueue.head) {
      tileReplacementQueue.head = next;
    } else {
      previous.replacementNext = next;
    }

    if (item === tileReplacementQueue.tail) {
      tileReplacementQueue.tail = previous;
    } else {
      next.replacementPrevious = previous;
    }

    item.replacementPrevious = undefined;
    item.replacementNext = undefined;

    --tileReplacementQueue.count;
  }

  /**
   * Marks a tile as rendered this frame and moves it before the first tile that was not rendered
   * this frame.
   *
   * @param {TileReplacementQueue} item The tile that was rendered.
   */
  TileReplacementQueue.prototype.markTileRendered = function (item) {
    const head = this.head;
    if (head === item) {
      if (item === this._lastBeforeStartOfFrame) {
        this._lastBeforeStartOfFrame = item.replacementNext;
      }
      return;
    }

    ++this.count;

    if (!defined(head)) {
      // no other tiles in the list
      item.replacementPrevious = undefined;
      item.replacementNext = undefined;
      this.head = item;
      this.tail = item;
      return;
    }

    if (defined(item.replacementPrevious) || defined(item.replacementNext)) {
      // tile already in the list, remove from its current location
      remove(this, item);
    }

    item.replacementPrevious = undefined;
    item.replacementNext = head;
    head.replacementPrevious = item;

    this.head = item;
  };

  /**
   * Renders massive sets of data by utilizing level-of-detail and culling.  The globe surface is divided into
   * a quadtree of tiles with large, low-detail tiles at the root and small, high-detail tiles at the leaves.
   * The set of tiles to render is selected by projecting an estimate of the geometric error in a tile onto
   * the screen to estimate screen-space error, in pixels, which must be below a user-specified threshold.
   * The actual content of the tiles is arbitrary and is specified using a {@link QuadtreeTileProvider}.
   *
   * @alias QuadtreePrimitive
   * @constructor
   * @private
   *
   * @param {QuadtreeTileProvider} options.tileProvider The tile provider that loads, renders, and estimates
   *        the distance to individual tiles.
   * @param {Number} [options.maximumScreenSpaceError=2] The maximum screen-space error, in pixels, that is allowed.
   *        A higher maximum error will render fewer tiles and improve performance, while a lower
   *        value will improve visual quality.
   * @param {Number} [options.tileCacheSize=100] The maximum number of tiles that will be retained in the tile cache.
   *        Note that tiles will never be unloaded if they were used for rendering the last
   *        frame, so the actual number of resident tiles may be higher.  The value of
   *        this property will not affect visual quality.
   */
  function QuadtreePrimitive(options) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(options) || !defined(options.tileProvider)) {
      throw new DeveloperError("options.tileProvider is required.");
    }
    if (defined(options.tileProvider.quadtree)) {
      throw new DeveloperError(
        "A QuadtreeTileProvider can only be used with a single QuadtreePrimitive"
      );
    }
    //>>includeEnd('debug');

    this._tileProvider = options.tileProvider;
    this._tileProvider.quadtree = this;

    this._debug = {
      enableDebugOutput: false,

      maxDepth: 0,
      maxDepthVisited: 0,
      tilesVisited: 0,
      tilesCulled: 0,
      tilesRendered: 0,
      tilesWaitingForChildren: 0,

      lastMaxDepth: -1,
      lastMaxDepthVisited: -1,
      lastTilesVisited: -1,
      lastTilesCulled: -1,
      lastTilesRendered: -1,
      lastTilesWaitingForChildren: -1,

      suspendLodUpdate: false,
    };

    const tilingScheme = this._tileProvider.tilingScheme;
    const ellipsoid = tilingScheme.ellipsoid;

    this._tilesToRender = [];
    this._tileLoadQueueHigh = []; // high priority tiles are preventing refinement
    this._tileLoadQueueMedium = []; // medium priority tiles are being rendered
    this._tileLoadQueueLow = []; // low priority tiles were refined past or are non-visible parts of quads.
    this._tileReplacementQueue = new TileReplacementQueue();
    this._levelZeroTiles = undefined;
    this._loadQueueTimeSlice = 5.0;
    this._tilesInvalidated = false;

    this._addHeightCallbacks = [];
    this._removeHeightCallbacks = [];

    this._tileToUpdateHeights = [];
    this._lastTileIndex = 0;
    this._updateHeightsTimeSlice = 2.0;

    // If a culled tile contains _cameraPositionCartographic or _cameraReferenceFrameOriginCartographic, it will be marked
    // TileSelectionResult.CULLED_BUT_NEEDED and added to the list of tiles to update heights,
    // even though it is not rendered.
    // These are updated each frame in `selectTilesForRendering`.
    this._cameraPositionCartographic = undefined;
    this._cameraReferenceFrameOriginCartographic = undefined;

    /**
     * Gets or sets the maximum screen-space error, in pixels, that is allowed.
     * A higher maximum error will render fewer tiles and improve performance, while a lower
     * value will improve visual quality.
     * @type {Number}
     * @default 2
     */
    this.maximumScreenSpaceError = defaultValue(
      options.maximumScreenSpaceError,
      2
    );

    /**
     * Gets or sets the maximum number of tiles that will be retained in the tile cache.
     * Note that tiles will never be unloaded if they were used for rendering the last
     * frame, so the actual number of resident tiles may be higher.  The value of
     * this property will not affect visual quality.
     * @type {Number}
     * @default 100
     */
    this.tileCacheSize = defaultValue(options.tileCacheSize, 100);

    /**
     * Gets or sets the number of loading descendant tiles that is considered "too many".
     * If a tile has too many loading descendants, that tile will be loaded and rendered before any of
     * its descendants are loaded and rendered. This means more feedback for the user that something
     * is happening at the cost of a longer overall load time. Setting this to 0 will cause each
     * tile level to be loaded successively, significantly increasing load time. Setting it to a large
     * number (e.g. 1000) will minimize the number of tiles that are loaded but tend to make
     * detail appear all at once after a long wait.
     * @type {Number}
     * @default 20
     */
    this.loadingDescendantLimit = 20;

    /**
     * Gets or sets a value indicating whether the ancestors of rendered tiles should be preloaded.
     * Setting this to true optimizes the zoom-out experience and provides more detail in
     * newly-exposed areas when panning. The down side is that it requires loading more tiles.
     * @type {Boolean}
     * @default true
     */
    this.preloadAncestors = true;

    /**
     * Gets or sets a value indicating whether the siblings of rendered tiles should be preloaded.
     * Setting this to true causes tiles with the same parent as a rendered tile to be loaded, even
     * if they are culled. Setting this to true may provide a better panning experience at the
     * cost of loading more tiles.
     * @type {Boolean}
     * @default false
     */
    this.preloadSiblings = false;

    this._occluders = new QuadtreeOccluders({
      ellipsoid: ellipsoid,
    });

    this._tileLoadProgressEvent = new Event();
    this._lastTileLoadQueueLength = 0;

    this._lastSelectionFrameNumber = undefined;
  }

  Object.defineProperties(QuadtreePrimitive.prototype, {
    /**
     * Gets the provider of {@link QuadtreeTile} instances for this quadtree.
     * @type {QuadtreeTile}
     * @memberof QuadtreePrimitive.prototype
     */
    tileProvider: {
      get: function () {
        return this._tileProvider;
      },
    },
    /**
     * Gets an event that's raised when the length of the tile load queue has changed since the last render frame.  When the load queue is empty,
     * all terrain and imagery for the current view have been loaded.  The event passes the new length of the tile load queue.
     *
     * @memberof QuadtreePrimitive.prototype
     * @type {Event}
     */
    tileLoadProgressEvent: {
      get: function () {
        return this._tileLoadProgressEvent;
      },
    },

    occluders: {
      get: function () {
        return this._occluders;
      },
    },
  });

  /**
   * Invalidates and frees all the tiles in the quadtree.  The tiles must be reloaded
   * before they can be displayed.
   *
   * @memberof QuadtreePrimitive
   */
  QuadtreePrimitive.prototype.invalidateAllTiles = function () {
    this._tilesInvalidated = true;
  };

  function invalidateAllTiles(primitive) {
    // Clear the replacement queue
    const replacementQueue = primitive._tileReplacementQueue;
    replacementQueue.head = undefined;
    replacementQueue.tail = undefined;
    replacementQueue.count = 0;

    clearTileLoadQueue(primitive);

    // Free and recreate the level zero tiles.
    const levelZeroTiles = primitive._levelZeroTiles;
    if (defined(levelZeroTiles)) {
      for (let i = 0; i < levelZeroTiles.length; ++i) {
        const tile = levelZeroTiles[i];
        const customData = tile.customData;
        const customDataLength = customData.length;

        for (let j = 0; j < customDataLength; ++j) {
          const data = customData[j];
          data.level = 0;
          primitive._addHeightCallbacks.push(data);
        }

        levelZeroTiles[i].freeResources();
      }
    }

    primitive._levelZeroTiles = undefined;

    primitive._tileProvider.cancelReprojections();
  }

  /**
   * Invokes a specified function for each {@link QuadtreeTile} that is partially
   * or completely loaded.
   *
   * @param {Function} tileFunction The function to invoke for each loaded tile.  The
   *        function is passed a reference to the tile as its only parameter.
   */
  QuadtreePrimitive.prototype.forEachLoadedTile = function (tileFunction) {
    let tile = this._tileReplacementQueue.head;
    while (defined(tile)) {
      if (tile.state !== QuadtreeTileLoadState$1.START) {
        tileFunction(tile);
      }
      tile = tile.replacementNext;
    }
  };

  /**
   * Invokes a specified function for each {@link QuadtreeTile} that was rendered
   * in the most recent frame.
   *
   * @param {Function} tileFunction The function to invoke for each rendered tile.  The
   *        function is passed a reference to the tile as its only parameter.
   */
  QuadtreePrimitive.prototype.forEachRenderedTile = function (tileFunction) {
    const tilesRendered = this._tilesToRender;
    for (let i = 0, len = tilesRendered.length; i < len; ++i) {
      tileFunction(tilesRendered[i]);
    }
  };

  /**
   * Calls the callback when a new tile is rendered that contains the given cartographic. The only parameter
   * is the cartesian position on the tile.
   *
   * @param {Cartographic} cartographic The cartographic position.
   * @param {Function} callback The function to be called when a new tile is loaded containing cartographic.
   * @returns {Function} The function to remove this callback from the quadtree.
   */
  QuadtreePrimitive.prototype.updateHeight = function (cartographic, callback) {
    const primitive = this;
    const object = {
      positionOnEllipsoidSurface: undefined,
      positionCartographic: cartographic,
      level: -1,
      callback: callback,
    };

    object.removeFunc = function () {
      const addedCallbacks = primitive._addHeightCallbacks;
      const length = addedCallbacks.length;
      for (let i = 0; i < length; ++i) {
        if (addedCallbacks[i] === object) {
          addedCallbacks.splice(i, 1);
          break;
        }
      }
      primitive._removeHeightCallbacks.push(object);
      if (object.callback) {
        object.callback = undefined;
      }
    };

    primitive._addHeightCallbacks.push(object);
    return object.removeFunc;
  };

  /**
   * Updates the tile provider imagery and continues to process the tile load queue.
   * @private
   */
  QuadtreePrimitive.prototype.update = function (frameState) {
    if (defined(this._tileProvider.update)) {
      this._tileProvider.update(frameState);
    }
  };

  function clearTileLoadQueue(primitive) {
    const debug = primitive._debug;
    debug.maxDepth = 0;
    debug.maxDepthVisited = 0;
    debug.tilesVisited = 0;
    debug.tilesCulled = 0;
    debug.tilesRendered = 0;
    debug.tilesWaitingForChildren = 0;

    primitive._tileLoadQueueHigh.length = 0;
    primitive._tileLoadQueueMedium.length = 0;
    primitive._tileLoadQueueLow.length = 0;
  }

  /**
   * Initializes values for a new render frame and prepare the tile load queue.
   * @private
   */
  QuadtreePrimitive.prototype.beginFrame = function (frameState) {
    const passes = frameState.passes;
    if (!passes.render) {
      return;
    }

    if (this._tilesInvalidated) {
      invalidateAllTiles(this);
      this._tilesInvalidated = false;
    }

    // Gets commands for any texture re-projections
    this._tileProvider.initialize(frameState);

    clearTileLoadQueue(this);

    if (this._debug.suspendLodUpdate) {
      return;
    }

    this._tileReplacementQueue.markStartOfRenderFrame();
  };

  /**
   * Selects new tiles to load based on the frame state and creates render commands.
   * @private
   */
  QuadtreePrimitive.prototype.render = function (frameState) {
    const passes = frameState.passes;
    const tileProvider = this._tileProvider;

    if (passes.render) {
      tileProvider.beginUpdate(frameState);

      selectTilesForRendering(this, frameState);
      createRenderCommandsForSelectedTiles(this, frameState);

      tileProvider.endUpdate(frameState);
    }

    if (passes.pick && this._tilesToRender.length > 0) {
      tileProvider.updateForPick(frameState);
    }
  };

  /**
   * Checks if the load queue length has changed since the last time we raised a queue change event - if so, raises
   * a new change event at the end of the render cycle.
   * @private
   */
  function updateTileLoadProgress(primitive, frameState) {
    const currentLoadQueueLength =
      primitive._tileLoadQueueHigh.length +
      primitive._tileLoadQueueMedium.length +
      primitive._tileLoadQueueLow.length;

    if (
      currentLoadQueueLength !== primitive._lastTileLoadQueueLength ||
      primitive._tilesInvalidated
    ) {
      frameState.afterRender.push(
        Event.prototype.raiseEvent.bind(
          primitive._tileLoadProgressEvent,
          currentLoadQueueLength
        )
      );
      primitive._lastTileLoadQueueLength = currentLoadQueueLength;
    }

    const debug = primitive._debug;
    if (debug.enableDebugOutput && !debug.suspendLodUpdate) {
      debug.maxDepth = primitive._tilesToRender.reduce(function (max, tile) {
        return Math.max(max, tile.level);
      }, -1);
      debug.tilesRendered = primitive._tilesToRender.length;

      if (
        debug.tilesVisited !== debug.lastTilesVisited ||
        debug.tilesRendered !== debug.lastTilesRendered ||
        debug.tilesCulled !== debug.lastTilesCulled ||
        debug.maxDepth !== debug.lastMaxDepth ||
        debug.tilesWaitingForChildren !== debug.lastTilesWaitingForChildren ||
        debug.maxDepthVisited !== debug.lastMaxDepthVisited
      ) {
        console.log(
          `Visited ${debug.tilesVisited}, Rendered: ${debug.tilesRendered}, Culled: ${debug.tilesCulled}, Max Depth Rendered: ${debug.maxDepth}, Max Depth Visited: ${debug.maxDepthVisited}, Waiting for children: ${debug.tilesWaitingForChildren}`
        );

        debug.lastTilesVisited = debug.tilesVisited;
        debug.lastTilesRendered = debug.tilesRendered;
        debug.lastTilesCulled = debug.tilesCulled;
        debug.lastMaxDepth = debug.maxDepth;
        debug.lastTilesWaitingForChildren = debug.tilesWaitingForChildren;
        debug.lastMaxDepthVisited = debug.maxDepthVisited;
      }
    }
  }

  /**
   * Updates terrain heights.
   * @private
   */
  QuadtreePrimitive.prototype.endFrame = function (frameState) {
    const passes = frameState.passes;
    if (!passes.render || frameState.mode === SceneMode$1.MORPHING) {
      // Only process the load queue for a single pass.
      // Don't process the load queue or update heights during the morph flights.
      return;
    }

    // Load/create resources for terrain and imagery. Prepare texture re-projections for the next frame.
    processTileLoadQueue(this, frameState);
    updateHeights(this, frameState);
    updateTileLoadProgress(this, frameState);
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @memberof QuadtreePrimitive
   *
   * @returns {Boolean} True if this object was destroyed; otherwise, false.
   *
   * @see QuadtreePrimitive#destroy
   */
  QuadtreePrimitive.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @memberof QuadtreePrimitive
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * primitive = primitive && primitive.destroy();
   *
   * @see QuadtreePrimitive#isDestroyed
   */
  QuadtreePrimitive.prototype.destroy = function () {
    this._tileProvider = this._tileProvider && this._tileProvider.destroy();
  };

  let comparisonPoint;
  const centerScratch = new Cartographic();
  function compareDistanceToPoint(a, b) {
    let center = Rectangle.center(a.rectangle, centerScratch);
    const alon = center.longitude - comparisonPoint.longitude;
    const alat = center.latitude - comparisonPoint.latitude;

    center = Rectangle.center(b.rectangle, centerScratch);
    const blon = center.longitude - comparisonPoint.longitude;
    const blat = center.latitude - comparisonPoint.latitude;

    return alon * alon + alat * alat - (blon * blon + blat * blat);
  }

  const cameraOriginScratch = new Cartesian3();
  let rootTraversalDetails = [];

  function selectTilesForRendering(primitive, frameState) {
    const debug = primitive._debug;
    if (debug.suspendLodUpdate) {
      return;
    }

    // Clear the render list.
    const tilesToRender = primitive._tilesToRender;
    tilesToRender.length = 0;

    // We can't render anything before the level zero tiles exist.
    let i;
    const tileProvider = primitive._tileProvider;
    if (!defined(primitive._levelZeroTiles)) {
      if (tileProvider.ready) {
        const tilingScheme = tileProvider.tilingScheme;
        primitive._levelZeroTiles = QuadtreeTile.createLevelZeroTiles(
          tilingScheme
        );
        const numberOfRootTiles = primitive._levelZeroTiles.length;
        if (rootTraversalDetails.length < numberOfRootTiles) {
          rootTraversalDetails = new Array(numberOfRootTiles);
          for (i = 0; i < numberOfRootTiles; ++i) {
            if (rootTraversalDetails[i] === undefined) {
              rootTraversalDetails[i] = new TraversalDetails();
            }
          }
        }
      } else {
        // Nothing to do until the provider is ready.
        return;
      }
    }

    primitive._occluders.ellipsoid.cameraPosition = frameState.camera.positionWC;

    let tile;
    const levelZeroTiles = primitive._levelZeroTiles;
    const occluders =
      levelZeroTiles.length > 1 ? primitive._occluders : undefined;

    // Sort the level zero tiles by the distance from the center to the camera.
    // The level zero tiles aren't necessarily a nice neat quad, so we can't use the
    // quadtree ordering we use elsewhere in the tree
    comparisonPoint = frameState.camera.positionCartographic;
    levelZeroTiles.sort(compareDistanceToPoint);

    const customDataAdded = primitive._addHeightCallbacks;
    const customDataRemoved = primitive._removeHeightCallbacks;
    const frameNumber = frameState.frameNumber;

    let len;
    if (customDataAdded.length > 0 || customDataRemoved.length > 0) {
      for (i = 0, len = levelZeroTiles.length; i < len; ++i) {
        tile = levelZeroTiles[i];
        tile._updateCustomData(frameNumber, customDataAdded, customDataRemoved);
      }

      customDataAdded.length = 0;
      customDataRemoved.length = 0;
    }

    const camera = frameState.camera;

    primitive._cameraPositionCartographic = camera.positionCartographic;
    const cameraFrameOrigin = Matrix4.getTranslation(
      camera.transform,
      cameraOriginScratch
    );
    primitive._cameraReferenceFrameOriginCartographic = primitive.tileProvider.tilingScheme.ellipsoid.cartesianToCartographic(
      cameraFrameOrigin,
      primitive._cameraReferenceFrameOriginCartographic
    );

    // Traverse in depth-first, near-to-far order.
    for (i = 0, len = levelZeroTiles.length; i < len; ++i) {
      tile = levelZeroTiles[i];
      primitive._tileReplacementQueue.markTileRendered(tile);
      if (!tile.renderable) {
        queueTileLoad(primitive, primitive._tileLoadQueueHigh, tile, frameState);
        ++debug.tilesWaitingForChildren;
      } else {
        visitIfVisible(
          primitive,
          tile,
          tileProvider,
          frameState,
          occluders,
          false,
          rootTraversalDetails[i]
        );
      }
    }

    primitive._lastSelectionFrameNumber = frameNumber;
  }

  function queueTileLoad(primitive, queue, tile, frameState) {
    if (!tile.needsLoading) {
      return;
    }

    if (primitive.tileProvider.computeTileLoadPriority !== undefined) {
      tile._loadPriority = primitive.tileProvider.computeTileLoadPriority(
        tile,
        frameState
      );
    }
    queue.push(tile);
  }

  /**
   * Tracks details of traversing a tile while selecting tiles for rendering.
   * @alias TraversalDetails
   * @constructor
   * @private
   */
  function TraversalDetails() {
    /**
     * True if all selected (i.e. not culled or refined) tiles in this tile's subtree
     * are renderable. If the subtree is renderable, we'll render it; no drama.
     */
    this.allAreRenderable = true;

    /**
     * True if any tiles in this tile's subtree were rendered last frame. If any
     * were, we must render the subtree rather than this tile, because rendering
     * this tile would cause detail to vanish that was visible last frame, and
     * that's no good.
     */
    this.anyWereRenderedLastFrame = false;

    /**
     * Counts the number of selected tiles in this tile's subtree that are
     * not yet ready to be rendered because they need more loading. Note that
     * this value will _not_ necessarily be zero when
     * {@link TraversalDetails#allAreRenderable} is true, for subtle reasons.
     * When {@link TraversalDetails#allAreRenderable} and
     * {@link TraversalDetails#anyWereRenderedLastFrame} are both false, we
     * will render this tile instead of any tiles in its subtree and
     * the `allAreRenderable` value for this tile will reflect only whether _this_
     * tile is renderable. The `notYetRenderableCount` value, however, will still
     * reflect the total number of tiles that we are waiting on, including the
     * ones that we're not rendering. `notYetRenderableCount` is only reset
     * when a subtree is removed from the render queue because the
     * `notYetRenderableCount` exceeds the
     * {@link QuadtreePrimitive#loadingDescendantLimit}.
     */
    this.notYetRenderableCount = 0;
  }

  function TraversalQuadDetails() {
    this.southwest = new TraversalDetails();
    this.southeast = new TraversalDetails();
    this.northwest = new TraversalDetails();
    this.northeast = new TraversalDetails();
  }

  TraversalQuadDetails.prototype.combine = function (result) {
    const southwest = this.southwest;
    const southeast = this.southeast;
    const northwest = this.northwest;
    const northeast = this.northeast;

    result.allAreRenderable =
      southwest.allAreRenderable &&
      southeast.allAreRenderable &&
      northwest.allAreRenderable &&
      northeast.allAreRenderable;
    result.anyWereRenderedLastFrame =
      southwest.anyWereRenderedLastFrame ||
      southeast.anyWereRenderedLastFrame ||
      northwest.anyWereRenderedLastFrame ||
      northeast.anyWereRenderedLastFrame;
    result.notYetRenderableCount =
      southwest.notYetRenderableCount +
      southeast.notYetRenderableCount +
      northwest.notYetRenderableCount +
      northeast.notYetRenderableCount;
  };

  const traversalQuadsByLevel = new Array(31); // level 30 tiles are ~2cm wide at the equator, should be good enough.
  for (let i = 0; i < traversalQuadsByLevel.length; ++i) {
    traversalQuadsByLevel[i] = new TraversalQuadDetails();
  }

  /**
   * Visits a tile for possible rendering. When we call this function with a tile:
   *
   *    * the tile has been determined to be visible (possibly based on a bounding volume that is not very tight-fitting)
   *    * its parent tile does _not_ meet the SSE (unless ancestorMeetsSse=true, see comments below)
   *    * the tile may or may not be renderable
   *
   * @private
   *
   * @param {Primitive} primitive The QuadtreePrimitive.
   * @param {FrameState} frameState The frame state.
   * @param {QuadtreeTile} tile The tile to visit
   * @param {Boolean} ancestorMeetsSse True if a tile higher in the tile tree already met the SSE and we're refining further only
   *                  to maintain detail while that higher tile loads.
   * @param {TraversalDetails} traveralDetails On return, populated with details of how the traversal of this tile went.
   */
  function visitTile(
    primitive,
    frameState,
    tile,
    ancestorMeetsSse,
    traversalDetails
  ) {
    const debug = primitive._debug;

    ++debug.tilesVisited;

    primitive._tileReplacementQueue.markTileRendered(tile);
    tile._updateCustomData(frameState.frameNumber);

    if (tile.level > debug.maxDepthVisited) {
      debug.maxDepthVisited = tile.level;
    }

    const meetsSse =
      screenSpaceError(primitive, frameState, tile) <
      primitive.maximumScreenSpaceError;

    const southwestChild = tile.southwestChild;
    const southeastChild = tile.southeastChild;
    const northwestChild = tile.northwestChild;
    const northeastChild = tile.northeastChild;

    const lastFrame = primitive._lastSelectionFrameNumber;
    const lastFrameSelectionResult =
      tile._lastSelectionResultFrame === lastFrame
        ? tile._lastSelectionResult
        : TileSelectionResult.NONE;

    const tileProvider = primitive.tileProvider;

    if (meetsSse || ancestorMeetsSse) {
      // This tile (or an ancestor) is the one we want to render this frame, but we'll do different things depending
      // on the state of this tile and on what we did _last_ frame.

      // We can render it if _any_ of the following are true:
      // 1. We rendered it (or kicked it) last frame.
      // 2. This tile was culled last frame, or it wasn't even visited because an ancestor was culled.
      // 3. The tile is completely done loading.
      // 4. a) Terrain is ready, and
      //    b) All necessary imagery is ready. Necessary imagery is imagery that was rendered with this tile
      //       or any descendants last frame. Such imagery is required because rendering this tile without
      //       it would cause detail to disappear.
      //
      // Determining condition 4 is more expensive, so we check the others first.
      //
      // Note that even if we decide to render a tile here, it may later get "kicked" in favor of an ancestor.

      const oneRenderedLastFrame =
        TileSelectionResult.originalResult(lastFrameSelectionResult) ===
        TileSelectionResult.RENDERED;
      const twoCulledOrNotVisited =
        TileSelectionResult.originalResult(lastFrameSelectionResult) ===
          TileSelectionResult.CULLED ||
        lastFrameSelectionResult === TileSelectionResult.NONE;
      const threeCompletelyLoaded = tile.state === QuadtreeTileLoadState$1.DONE;

      let renderable =
        oneRenderedLastFrame || twoCulledOrNotVisited || threeCompletelyLoaded;

      if (!renderable) {
        // Check the more expensive condition 4 above. This requires details of the thing
        // we're rendering (e.g. the globe surface), so delegate it to the tile provider.
        if (defined(tileProvider.canRenderWithoutLosingDetail)) {
          renderable = tileProvider.canRenderWithoutLosingDetail(tile);
        }
      }

      if (renderable) {
        // Only load this tile if it (not just an ancestor) meets the SSE.
        if (meetsSse) {
          queueTileLoad(
            primitive,
            primitive._tileLoadQueueMedium,
            tile,
            frameState
          );
        }
        addTileToRenderList(primitive, tile);

        traversalDetails.allAreRenderable = tile.renderable;
        traversalDetails.anyWereRenderedLastFrame =
          lastFrameSelectionResult === TileSelectionResult.RENDERED;
        traversalDetails.notYetRenderableCount = tile.renderable ? 0 : 1;

        tile._lastSelectionResultFrame = frameState.frameNumber;
        tile._lastSelectionResult = TileSelectionResult.RENDERED;

        if (!traversalDetails.anyWereRenderedLastFrame) {
          // Tile is newly-rendered this frame, so update its heights.
          primitive._tileToUpdateHeights.push(tile);
        }

        return;
      }

      // Otherwise, we can't render this tile (or its fill) because doing so would cause detail to disappear
      // that was visible last frame. Instead, keep rendering any still-visible descendants that were rendered
      // last frame and render fills for newly-visible descendants. E.g. if we were rendering level 15 last
      // frame but this frame we want level 14 and the closest renderable level <= 14 is 0, rendering level
      // zero would be pretty jarring so instead we keep rendering level 15 even though its SSE is better
      // than required. So fall through to continue traversal...
      ancestorMeetsSse = true;

      // Load this blocker tile with high priority, but only if this tile (not just an ancestor) meets the SSE.
      if (meetsSse) {
        queueTileLoad(primitive, primitive._tileLoadQueueHigh, tile, frameState);
      }
    }

    if (tileProvider.canRefine(tile)) {
      const allAreUpsampled =
        southwestChild.upsampledFromParent &&
        southeastChild.upsampledFromParent &&
        northwestChild.upsampledFromParent &&
        northeastChild.upsampledFromParent;

      if (allAreUpsampled) {
        // No point in rendering the children because they're all upsampled.  Render this tile instead.
        addTileToRenderList(primitive, tile);

        // Rendered tile that's not waiting on children loads with medium priority.
        queueTileLoad(
          primitive,
          primitive._tileLoadQueueMedium,
          tile,
          frameState
        );

        // Make sure we don't unload the children and forget they're upsampled.
        primitive._tileReplacementQueue.markTileRendered(southwestChild);
        primitive._tileReplacementQueue.markTileRendered(southeastChild);
        primitive._tileReplacementQueue.markTileRendered(northwestChild);
        primitive._tileReplacementQueue.markTileRendered(northeastChild);

        traversalDetails.allAreRenderable = tile.renderable;
        traversalDetails.anyWereRenderedLastFrame =
          lastFrameSelectionResult === TileSelectionResult.RENDERED;
        traversalDetails.notYetRenderableCount = tile.renderable ? 0 : 1;

        tile._lastSelectionResultFrame = frameState.frameNumber;
        tile._lastSelectionResult = TileSelectionResult.RENDERED;

        if (!traversalDetails.anyWereRenderedLastFrame) {
          // Tile is newly-rendered this frame, so update its heights.
          primitive._tileToUpdateHeights.push(tile);
        }

        return;
      }

      // SSE is not good enough, so refine.
      tile._lastSelectionResultFrame = frameState.frameNumber;
      tile._lastSelectionResult = TileSelectionResult.REFINED;

      const firstRenderedDescendantIndex = primitive._tilesToRender.length;
      const loadIndexLow = primitive._tileLoadQueueLow.length;
      const loadIndexMedium = primitive._tileLoadQueueMedium.length;
      const loadIndexHigh = primitive._tileLoadQueueHigh.length;
      const tilesToUpdateHeightsIndex = primitive._tileToUpdateHeights.length;

      // No need to add the children to the load queue because they'll be added (if necessary) when they're visited.
      visitVisibleChildrenNearToFar(
        primitive,
        southwestChild,
        southeastChild,
        northwestChild,
        northeastChild,
        frameState,
        ancestorMeetsSse,
        traversalDetails
      );

      // If no descendant tiles were added to the render list by the function above, it means they were all
      // culled even though this tile was deemed visible. That's pretty common.

      if (firstRenderedDescendantIndex !== primitive._tilesToRender.length) {
        // At least one descendant tile was added to the render list.
        // The traversalDetails tell us what happened while visiting the children.

        const allAreRenderable = traversalDetails.allAreRenderable;
        const anyWereRenderedLastFrame =
          traversalDetails.anyWereRenderedLastFrame;
        const notYetRenderableCount = traversalDetails.notYetRenderableCount;
        let queuedForLoad = false;

        if (!allAreRenderable && !anyWereRenderedLastFrame) {
          // Some of our descendants aren't ready to render yet, and none were rendered last frame,
          // so kick them all out of the render list and render this tile instead. Continue to load them though!

          // Mark the rendered descendants and their ancestors - up to this tile - as kicked.
          const renderList = primitive._tilesToRender;
          for (let i = firstRenderedDescendantIndex; i < renderList.length; ++i) {
            let workTile = renderList[i];
            while (
              workTile !== undefined &&
              workTile._lastSelectionResult !== TileSelectionResult.KICKED &&
              workTile !== tile
            ) {
              workTile._lastSelectionResult = TileSelectionResult.kick(
                workTile._lastSelectionResult
              );
              workTile = workTile.parent;
            }
          }

          // Remove all descendants from the render list and add this tile.
          primitive._tilesToRender.length = firstRenderedDescendantIndex;
          primitive._tileToUpdateHeights.length = tilesToUpdateHeightsIndex;
          addTileToRenderList(primitive, tile);

          tile._lastSelectionResult = TileSelectionResult.RENDERED;

          // If we're waiting on heaps of descendants, the above will take too long. So in that case,
          // load this tile INSTEAD of loading any of the descendants, and tell the up-level we're only waiting
          // on this tile. Keep doing this until we actually manage to render this tile.
          const wasRenderedLastFrame =
            lastFrameSelectionResult === TileSelectionResult.RENDERED;
          if (
            !wasRenderedLastFrame &&
            notYetRenderableCount > primitive.loadingDescendantLimit
          ) {
            // Remove all descendants from the load queues.
            primitive._tileLoadQueueLow.length = loadIndexLow;
            primitive._tileLoadQueueMedium.length = loadIndexMedium;
            primitive._tileLoadQueueHigh.length = loadIndexHigh;
            queueTileLoad(
              primitive,
              primitive._tileLoadQueueMedium,
              tile,
              frameState
            );
            traversalDetails.notYetRenderableCount = tile.renderable ? 0 : 1;
            queuedForLoad = true;
          }

          traversalDetails.allAreRenderable = tile.renderable;
          traversalDetails.anyWereRenderedLastFrame = wasRenderedLastFrame;

          if (!wasRenderedLastFrame) {
            // Tile is newly-rendered this frame, so update its heights.
            primitive._tileToUpdateHeights.push(tile);
          }

          ++debug.tilesWaitingForChildren;
        }

        if (primitive.preloadAncestors && !queuedForLoad) {
          queueTileLoad(primitive, primitive._tileLoadQueueLow, tile, frameState);
        }
      }

      return;
    }

    tile._lastSelectionResultFrame = frameState.frameNumber;
    tile._lastSelectionResult = TileSelectionResult.RENDERED;

    // We'd like to refine but can't because we have no availability data for this tile's children,
    // so we have no idea if refinining would involve a load or an upsample. We'll have to finish
    // loading this tile first in order to find that out, so load this refinement blocker with
    // high priority.
    addTileToRenderList(primitive, tile);
    queueTileLoad(primitive, primitive._tileLoadQueueHigh, tile, frameState);

    traversalDetails.allAreRenderable = tile.renderable;
    traversalDetails.anyWereRenderedLastFrame =
      lastFrameSelectionResult === TileSelectionResult.RENDERED;
    traversalDetails.notYetRenderableCount = tile.renderable ? 0 : 1;
  }

  function visitVisibleChildrenNearToFar(
    primitive,
    southwest,
    southeast,
    northwest,
    northeast,
    frameState,
    ancestorMeetsSse,
    traversalDetails
  ) {
    const cameraPosition = frameState.camera.positionCartographic;
    const tileProvider = primitive._tileProvider;
    const occluders = primitive._occluders;

    const quadDetails = traversalQuadsByLevel[southwest.level];
    const southwestDetails = quadDetails.southwest;
    const southeastDetails = quadDetails.southeast;
    const northwestDetails = quadDetails.northwest;
    const northeastDetails = quadDetails.northeast;

    if (cameraPosition.longitude < southwest.rectangle.east) {
      if (cameraPosition.latitude < southwest.rectangle.north) {
        // Camera in southwest quadrant
        visitIfVisible(
          primitive,
          southwest,
          tileProvider,
          frameState,
          occluders,
          ancestorMeetsSse,
          southwestDetails
        );
        visitIfVisible(
          primitive,
          southeast,
          tileProvider,
          frameState,
          occluders,
          ancestorMeetsSse,
          southeastDetails
        );
        visitIfVisible(
          primitive,
          northwest,
          tileProvider,
          frameState,
          occluders,
          ancestorMeetsSse,
          northwestDetails
        );
        visitIfVisible(
          primitive,
          northeast,
          tileProvider,
          frameState,
          occluders,
          ancestorMeetsSse,
          northeastDetails
        );
      } else {
        // Camera in northwest quadrant
        visitIfVisible(
          primitive,
          northwest,
          tileProvider,
          frameState,
          occluders,
          ancestorMeetsSse,
          northwestDetails
        );
        visitIfVisible(
          primitive,
          southwest,
          tileProvider,
          frameState,
          occluders,
          ancestorMeetsSse,
          southwestDetails
        );
        visitIfVisible(
          primitive,
          northeast,
          tileProvider,
          frameState,
          occluders,
          ancestorMeetsSse,
          northeastDetails
        );
        visitIfVisible(
          primitive,
          southeast,
          tileProvider,
          frameState,
          occluders,
          ancestorMeetsSse,
          southeastDetails
        );
      }
    } else if (cameraPosition.latitude < southwest.rectangle.north) {
      // Camera southeast quadrant
      visitIfVisible(
        primitive,
        southeast,
        tileProvider,
        frameState,
        occluders,
        ancestorMeetsSse,
        southeastDetails
      );
      visitIfVisible(
        primitive,
        southwest,
        tileProvider,
        frameState,
        occluders,
        ancestorMeetsSse,
        southwestDetails
      );
      visitIfVisible(
        primitive,
        northeast,
        tileProvider,
        frameState,
        occluders,
        ancestorMeetsSse,
        northeastDetails
      );
      visitIfVisible(
        primitive,
        northwest,
        tileProvider,
        frameState,
        occluders,
        ancestorMeetsSse,
        northwestDetails
      );
    } else {
      // Camera in northeast quadrant
      visitIfVisible(
        primitive,
        northeast,
        tileProvider,
        frameState,
        occluders,
        ancestorMeetsSse,
        northeastDetails
      );
      visitIfVisible(
        primitive,
        northwest,
        tileProvider,
        frameState,
        occluders,
        ancestorMeetsSse,
        northwestDetails
      );
      visitIfVisible(
        primitive,
        southeast,
        tileProvider,
        frameState,
        occluders,
        ancestorMeetsSse,
        southeastDetails
      );
      visitIfVisible(
        primitive,
        southwest,
        tileProvider,
        frameState,
        occluders,
        ancestorMeetsSse,
        southwestDetails
      );
    }

    quadDetails.combine(traversalDetails);
  }

  function containsNeededPosition(primitive, tile) {
    const rectangle = tile.rectangle;
    return (
      (defined(primitive._cameraPositionCartographic) &&
        Rectangle.contains(rectangle, primitive._cameraPositionCartographic)) ||
      (defined(primitive._cameraReferenceFrameOriginCartographic) &&
        Rectangle.contains(
          rectangle,
          primitive._cameraReferenceFrameOriginCartographic
        ))
    );
  }

  function visitIfVisible(
    primitive,
    tile,
    tileProvider,
    frameState,
    occluders,
    ancestorMeetsSse,
    traversalDetails
  ) {
    if (
      tileProvider.computeTileVisibility(tile, frameState, occluders) !==
      Visibility$1.NONE
    ) {
      return visitTile(
        primitive,
        frameState,
        tile,
        ancestorMeetsSse,
        traversalDetails
      );
    }

    ++primitive._debug.tilesCulled;
    primitive._tileReplacementQueue.markTileRendered(tile);

    traversalDetails.allAreRenderable = true;
    traversalDetails.anyWereRenderedLastFrame = false;
    traversalDetails.notYetRenderableCount = 0;

    if (containsNeededPosition(primitive, tile)) {
      // Load the tile(s) that contains the camera's position and
      // the origin of its reference frame with medium priority.
      // But we only need to load until the terrain is available, no need to load imagery.
      if (!defined(tile.data) || !defined(tile.data.vertexArray)) {
        queueTileLoad(
          primitive,
          primitive._tileLoadQueueMedium,
          tile,
          frameState
        );
      }

      const lastFrame = primitive._lastSelectionFrameNumber;
      const lastFrameSelectionResult =
        tile._lastSelectionResultFrame === lastFrame
          ? tile._lastSelectionResult
          : TileSelectionResult.NONE;
      if (
        lastFrameSelectionResult !== TileSelectionResult.CULLED_BUT_NEEDED &&
        lastFrameSelectionResult !== TileSelectionResult.RENDERED
      ) {
        primitive._tileToUpdateHeights.push(tile);
      }

      tile._lastSelectionResult = TileSelectionResult.CULLED_BUT_NEEDED;
    } else if (primitive.preloadSiblings || tile.level === 0) {
      // Load culled level zero tiles with low priority.
      // For all other levels, only load culled tiles if preloadSiblings is enabled.
      queueTileLoad(primitive, primitive._tileLoadQueueLow, tile, frameState);
      tile._lastSelectionResult = TileSelectionResult.CULLED;
    } else {
      tile._lastSelectionResult = TileSelectionResult.CULLED;
    }

    tile._lastSelectionResultFrame = frameState.frameNumber;
  }

  function screenSpaceError(primitive, frameState, tile) {
    if (
      frameState.mode === SceneMode$1.SCENE2D ||
      frameState.camera.frustum instanceof OrthographicFrustum ||
      frameState.camera.frustum instanceof OrthographicOffCenterFrustum
    ) {
      return screenSpaceError2D(primitive, frameState, tile);
    }

    const maxGeometricError = primitive._tileProvider.getLevelMaximumGeometricError(
      tile.level
    );

    const distance = tile._distance;
    const height = frameState.context.drawingBufferHeight;
    const sseDenominator = frameState.camera.frustum.sseDenominator;

    let error = (maxGeometricError * height) / (distance * sseDenominator);

    if (frameState.fog.enabled) {
      error -=
        CesiumMath.fog(distance, frameState.fog.density) * frameState.fog.sse;
    }

    error /= frameState.pixelRatio;

    return error;
  }

  function screenSpaceError2D(primitive, frameState, tile) {
    const camera = frameState.camera;
    let frustum = camera.frustum;
    if (defined(frustum._offCenterFrustum)) {
      frustum = frustum._offCenterFrustum;
    }

    const context = frameState.context;
    const width = context.drawingBufferWidth;
    const height = context.drawingBufferHeight;

    const maxGeometricError = primitive._tileProvider.getLevelMaximumGeometricError(
      tile.level
    );
    const pixelSize =
      Math.max(frustum.top - frustum.bottom, frustum.right - frustum.left) /
      Math.max(width, height);
    let error = maxGeometricError / pixelSize;

    if (frameState.fog.enabled && frameState.mode !== SceneMode$1.SCENE2D) {
      error -=
        CesiumMath.fog(tile._distance, frameState.fog.density) *
        frameState.fog.sse;
    }

    error /= frameState.pixelRatio;

    return error;
  }

  function addTileToRenderList(primitive, tile) {
    primitive._tilesToRender.push(tile);
  }

  function processTileLoadQueue(primitive, frameState) {
    const tileLoadQueueHigh = primitive._tileLoadQueueHigh;
    const tileLoadQueueMedium = primitive._tileLoadQueueMedium;
    const tileLoadQueueLow = primitive._tileLoadQueueLow;

    if (
      tileLoadQueueHigh.length === 0 &&
      tileLoadQueueMedium.length === 0 &&
      tileLoadQueueLow.length === 0
    ) {
      return;
    }

    // Remove any tiles that were not used this frame beyond the number
    // we're allowed to keep.
    primitive._tileReplacementQueue.trimTiles(primitive.tileCacheSize);

    const endTime = getTimestamp$1() + primitive._loadQueueTimeSlice;
    const tileProvider = primitive._tileProvider;

    let didSomeLoading = processSinglePriorityLoadQueue(
      primitive,
      frameState,
      tileProvider,
      endTime,
      tileLoadQueueHigh,
      false
    );
    didSomeLoading = processSinglePriorityLoadQueue(
      primitive,
      frameState,
      tileProvider,
      endTime,
      tileLoadQueueMedium,
      didSomeLoading
    );
    processSinglePriorityLoadQueue(
      primitive,
      frameState,
      tileProvider,
      endTime,
      tileLoadQueueLow,
      didSomeLoading
    );
  }

  function sortByLoadPriority(a, b) {
    return a._loadPriority - b._loadPriority;
  }

  function processSinglePriorityLoadQueue(
    primitive,
    frameState,
    tileProvider,
    endTime,
    loadQueue,
    didSomeLoading
  ) {
    if (tileProvider.computeTileLoadPriority !== undefined) {
      loadQueue.sort(sortByLoadPriority);
    }

    for (
      let i = 0, len = loadQueue.length;
      i < len && (getTimestamp$1() < endTime || !didSomeLoading);
      ++i
    ) {
      const tile = loadQueue[i];
      primitive._tileReplacementQueue.markTileRendered(tile);
      tileProvider.loadTile(frameState, tile);
      didSomeLoading = true;
    }

    return didSomeLoading;
  }

  const scratchRay = new Ray();
  const scratchCartographic$2 = new Cartographic();
  const scratchPosition$1 = new Cartesian3();
  const scratchArray$1 = [];

  function updateHeights(primitive, frameState) {
    if (!primitive.tileProvider.ready) {
      return;
    }

    const tryNextFrame = scratchArray$1;
    tryNextFrame.length = 0;
    const tilesToUpdateHeights = primitive._tileToUpdateHeights;

    const startTime = getTimestamp$1();
    const timeSlice = primitive._updateHeightsTimeSlice;
    const endTime = startTime + timeSlice;

    const mode = frameState.mode;
    const projection = frameState.mapProjection;
    const ellipsoid = primitive.tileProvider.tilingScheme.ellipsoid;
    let i;

    while (tilesToUpdateHeights.length > 0) {
      const tile = tilesToUpdateHeights[0];
      if (!defined(tile.data) || !defined(tile.data.mesh)) {
        // Tile isn't loaded enough yet, so try again next frame if this tile is still
        // being rendered.
        const selectionResult =
          tile._lastSelectionResultFrame === primitive._lastSelectionFrameNumber
            ? tile._lastSelectionResult
            : TileSelectionResult.NONE;
        if (
          selectionResult === TileSelectionResult.RENDERED ||
          selectionResult === TileSelectionResult.CULLED_BUT_NEEDED
        ) {
          tryNextFrame.push(tile);
        }
        tilesToUpdateHeights.shift();
        primitive._lastTileIndex = 0;
        continue;
      }
      const customData = tile.customData;
      const customDataLength = customData.length;

      let timeSliceMax = false;
      for (i = primitive._lastTileIndex; i < customDataLength; ++i) {
        const data = customData[i];

        // No need to run this code when the tile is upsampled, because the height will be the same as its parent.
        const terrainData = tile.data.terrainData;
        const upsampledGeometryFromParent =
          defined(terrainData) && terrainData.wasCreatedByUpsampling();

        if (tile.level > data.level && !upsampledGeometryFromParent) {
          if (!defined(data.positionOnEllipsoidSurface)) {
            // cartesian has to be on the ellipsoid surface for `ellipsoid.geodeticSurfaceNormal`
            data.positionOnEllipsoidSurface = Cartesian3.fromRadians(
              data.positionCartographic.longitude,
              data.positionCartographic.latitude,
              0.0,
              ellipsoid
            );
          }

          if (mode === SceneMode$1.SCENE3D) {
            const surfaceNormal = ellipsoid.geodeticSurfaceNormal(
              data.positionOnEllipsoidSurface,
              scratchRay.direction
            );

            // compute origin point

            // Try to find the intersection point between the surface normal and z-axis.
            // minimum height (-11500.0) for the terrain set, need to get this information from the terrain provider
            const rayOrigin = ellipsoid.getSurfaceNormalIntersectionWithZAxis(
              data.positionOnEllipsoidSurface,
              11500.0,
              scratchRay.origin
            );

            // Theoretically, not with Earth datums, the intersection point can be outside the ellipsoid
            if (!defined(rayOrigin)) {
              // intersection point is outside the ellipsoid, try other value
              // minimum height (-11500.0) for the terrain set, need to get this information from the terrain provider
              let minimumHeight = 0.0;
              if (defined(tile.data.tileBoundingRegion)) {
                minimumHeight = tile.data.tileBoundingRegion.minimumHeight;
              }
              const magnitude = Math.min(minimumHeight, -11500.0);

              // multiply by the *positive* value of the magnitude
              const vectorToMinimumPoint = Cartesian3.multiplyByScalar(
                surfaceNormal,
                Math.abs(magnitude) + 1,
                scratchPosition$1
              );
              Cartesian3.subtract(
                data.positionOnEllipsoidSurface,
                vectorToMinimumPoint,
                scratchRay.origin
              );
            }
          } else {
            Cartographic.clone(data.positionCartographic, scratchCartographic$2);

            // minimum height for the terrain set, need to get this information from the terrain provider
            scratchCartographic$2.height = -11500.0;
            projection.project(scratchCartographic$2, scratchPosition$1);
            Cartesian3.fromElements(
              scratchPosition$1.z,
              scratchPosition$1.x,
              scratchPosition$1.y,
              scratchPosition$1
            );
            Cartesian3.clone(scratchPosition$1, scratchRay.origin);
            Cartesian3.clone(Cartesian3.UNIT_X, scratchRay.direction);
          }

          const position = tile.data.pick(
            scratchRay,
            mode,
            projection,
            false,
            scratchPosition$1
          );
          if (defined(position)) {
            if (defined(data.callback)) {
              data.callback(position);
            }
            data.level = tile.level;
          }
        }

        if (getTimestamp$1() >= endTime) {
          timeSliceMax = true;
          break;
        }
      }

      if (timeSliceMax) {
        primitive._lastTileIndex = i;
        break;
      } else {
        primitive._lastTileIndex = 0;
        tilesToUpdateHeights.shift();
      }
    }
    for (i = 0; i < tryNextFrame.length; i++) {
      tilesToUpdateHeights.push(tryNextFrame[i]);
    }
  }

  function createRenderCommandsForSelectedTiles(primitive, frameState) {
    const tileProvider = primitive._tileProvider;
    const tilesToRender = primitive._tilesToRender;

    for (let i = 0, len = tilesToRender.length; i < len; ++i) {
      const tile = tilesToRender[i];
      tileProvider.showTileThisFrame(tile, frameState);
    }
  }

  /**
   * The globe rendered in the scene, including its terrain ({@link Globe#terrainProvider})
   * and imagery layers ({@link Globe#imageryLayers}).  Access the globe using {@link Scene#globe}.
   *
   * @alias Globe
   * @constructor
   *
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] Determines the size and shape of the
   * globe.
   */
  function Globe(ellipsoid) {
    ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
    const terrainProvider = new EllipsoidTerrainProvider({
      ellipsoid: ellipsoid,
    });
    const imageryLayerCollection = new ImageryLayerCollection();

    this._ellipsoid = ellipsoid;
    this._imageryLayerCollection = imageryLayerCollection;

    this._surfaceShaderSet = new GlobeSurfaceShaderSet();
    this._material = undefined;

    this._surface = new QuadtreePrimitive({
      tileProvider: new GlobeSurfaceTileProvider({
        terrainProvider: terrainProvider,
        imageryLayers: imageryLayerCollection,
        surfaceShaderSet: this._surfaceShaderSet,
      }),
    });

    this._terrainProvider = terrainProvider;
    this._terrainProviderChanged = new Event();

    this._undergroundColor = Color.clone(Color.BLACK);
    this._undergroundColorAlphaByDistance = new NearFarScalar(
      ellipsoid.maximumRadius / 1000.0,
      0.0,
      ellipsoid.maximumRadius / 5.0,
      1.0
    );

    this._translucency = new GlobeTranslucency();

    makeShadersDirty(this);

    /**
     * Determines if the globe will be shown.
     *
     * @type {Boolean}
     * @default true
     */
    this.show = true;

    this._oceanNormalMapResourceDirty = true;
    this._oceanNormalMapResource = new Resource({
      url: buildModuleUrl("Assets/Textures/waterNormalsSmall.jpg"),
    });

    /**
     * The maximum screen-space error used to drive level-of-detail refinement.  Higher
     * values will provide better performance but lower visual quality.
     *
     * @type {Number}
     * @default 2
     */
    this.maximumScreenSpaceError = 2;

    /**
     * The size of the terrain tile cache, expressed as a number of tiles.  Any additional
     * tiles beyond this number will be freed, as long as they aren't needed for rendering
     * this frame.  A larger number will consume more memory but will show detail faster
     * when, for example, zooming out and then back in.
     *
     * @type {Number}
     * @default 100
     */
    this.tileCacheSize = 100;

    /**
     * Gets or sets the number of loading descendant tiles that is considered "too many".
     * If a tile has too many loading descendants, that tile will be loaded and rendered before any of
     * its descendants are loaded and rendered. This means more feedback for the user that something
     * is happening at the cost of a longer overall load time. Setting this to 0 will cause each
     * tile level to be loaded successively, significantly increasing load time. Setting it to a large
     * number (e.g. 1000) will minimize the number of tiles that are loaded but tend to make
     * detail appear all at once after a long wait.
     * @type {Number}
     * @default 20
     */
    this.loadingDescendantLimit = 20;

    /**
     * Gets or sets a value indicating whether the ancestors of rendered tiles should be preloaded.
     * Setting this to true optimizes the zoom-out experience and provides more detail in
     * newly-exposed areas when panning. The down side is that it requires loading more tiles.
     * @type {Boolean}
     * @default true
     */
    this.preloadAncestors = true;

    /**
     * Gets or sets a value indicating whether the siblings of rendered tiles should be preloaded.
     * Setting this to true causes tiles with the same parent as a rendered tile to be loaded, even
     * if they are culled. Setting this to true may provide a better panning experience at the
     * cost of loading more tiles.
     * @type {Boolean}
     * @default false
     */
    this.preloadSiblings = false;

    /**
     * The color to use to highlight terrain fill tiles. If undefined, fill tiles are not
     * highlighted at all. The alpha value is used to alpha blend with the tile's
     * actual color. Because terrain fill tiles do not represent the actual terrain surface,
     * it may be useful in some applications to indicate visually that they are not to be trusted.
     * @type {Color}
     * @default undefined
     */
    this.fillHighlightColor = undefined;

    /**
     * Enable lighting the globe with the scene's light source.
     *
     * @type {Boolean}
     * @default false
     */
    this.enableLighting = false;

    /**
     * A multiplier to adjust terrain lambert lighting.
     * This number is multiplied by the result of <code>czm_getLambertDiffuse</code> in GlobeFS.glsl.
     * This only takes effect when <code>enableLighting</code> is <code>true</code>.
     *
     * @type {Number}
     * @default 0.9
     */
    this.lambertDiffuseMultiplier = 0.9;

    /**
     * Enable dynamic lighting effects on atmosphere and fog. This only takes effect
     * when <code>enableLighting</code> is <code>true</code>.
     *
     * @type {Boolean}
     * @default true
     */
    this.dynamicAtmosphereLighting = true;

    /**
     * Whether dynamic atmosphere lighting uses the sun direction instead of the scene's
     * light direction. This only takes effect when <code>enableLighting</code> and
     * <code>dynamicAtmosphereLighting</code> are <code>true</code>.
     *
     * @type {Boolean}
     * @default false
     */
    this.dynamicAtmosphereLightingFromSun = false;

    /**
     * Enable the ground atmosphere, which is drawn over the globe when viewed from a distance between <code>lightingFadeInDistance</code> and <code>lightingFadeOutDistance</code>.
     *
     * @type {Boolean}
     * @default true
     */
    this.showGroundAtmosphere = true;

    /**
     * The intensity of the light that is used for computing the ground atmosphere color.
     *
     * @type {Number}
     * @default 10.0
     */
    this.atmosphereLightIntensity = 10.0;

    /**
     * The Rayleigh scattering coefficient used in the atmospheric scattering equations for the ground atmosphere.
     *
     * @type {Cartesian3}
     * @default Cartesian3(5.5e-6, 13.0e-6, 28.4e-6)
     */
    this.atmosphereRayleighCoefficient = new Cartesian3(5.5e-6, 13.0e-6, 28.4e-6);

    /**
     * The Mie scattering coefficient used in the atmospheric scattering equations for the ground atmosphere.
     *
     * @type {Cartesian3}
     * @default Cartesian3(21e-6, 21e-6, 21e-6)
     */
    this.atmosphereMieCoefficient = new Cartesian3(21e-6, 21e-6, 21e-6);

    /**
     * The Rayleigh scale height used in the atmospheric scattering equations for the ground atmosphere, in meters.
     *
     * @type {Number}
     * @default 10000.0
     */
    this.atmosphereRayleighScaleHeight = 10000.0;

    /**
     * The Mie scale height used in the atmospheric scattering equations for the ground atmosphere, in meters.
     *
     * @type {Number}
     * @default 3200.0
     */
    this.atmosphereMieScaleHeight = 3200.0;

    /**
     * The anisotropy of the medium to consider for Mie scattering.
     * <p>
     * Valid values are between -1.0 and 1.0.
     * </p>
     * @type {Number}
     * @default 0.9
     */
    this.atmosphereMieAnisotropy = 0.9;

    /**
     * The distance where everything becomes lit. This only takes effect
     * when <code>enableLighting</code> or <code>showGroundAtmosphere</code> is <code>true</code>.
     *
     * @type {Number}
     * @default 10000000.0
     */
    this.lightingFadeOutDistance = 1.0e7;

    /**
     * The distance where lighting resumes. This only takes effect
     * when <code>enableLighting</code> or <code>showGroundAtmosphere</code> is <code>true</code>.
     *
     * @type {Number}
     * @default 20000000.0
     */
    this.lightingFadeInDistance = 2.0e7;

    /**
     * The distance where the darkness of night from the ground atmosphere fades out to a lit ground atmosphere.
     * This only takes effect when <code>showGroundAtmosphere</code>, <code>enableLighting</code>, and
     * <code>dynamicAtmosphereLighting</code> are <code>true</code>.
     *
     * @type {Number}
     * @default 10000000.0
     */
    this.nightFadeOutDistance = 1.0e7;

    /**
     * The distance where the darkness of night from the ground atmosphere fades in to an unlit ground atmosphere.
     * This only takes effect when <code>showGroundAtmosphere</code>, <code>enableLighting</code>, and
     * <code>dynamicAtmosphereLighting</code> are <code>true</code>.
     *
     * @type {Number}
     * @default 50000000.0
     */
    this.nightFadeInDistance = 5.0e7;

    /**
     * True if an animated wave effect should be shown in areas of the globe
     * covered by water; otherwise, false.  This property is ignored if the
     * <code>terrainProvider</code> does not provide a water mask.
     *
     * @type {Boolean}
     * @default true
     */
    this.showWaterEffect = true;

    /**
     * True if primitives such as billboards, polylines, labels, etc. should be depth-tested
     * against the terrain surface, or false if such primitives should always be drawn on top
     * of terrain unless they're on the opposite side of the globe.  The disadvantage of depth
     * testing primitives against terrain is that slight numerical noise or terrain level-of-detail
     * switched can sometimes make a primitive that should be on the surface disappear underneath it.
     *
     * @type {Boolean}
     * @default false
     *
     */
    this.depthTestAgainstTerrain = false;

    /**
     * Determines whether the globe casts or receives shadows from light sources. Setting the globe
     * to cast shadows may impact performance since the terrain is rendered again from the light's perspective.
     * Currently only terrain that is in view casts shadows. By default the globe does not cast shadows.
     *
     * @type {ShadowMode}
     * @default ShadowMode.RECEIVE_ONLY
     */
    this.shadows = ShadowMode$1.RECEIVE_ONLY;

    /**
     * The hue shift to apply to the atmosphere. Defaults to 0.0 (no shift).
     * A hue shift of 1.0 indicates a complete rotation of the hues available.
     * @type {Number}
     * @default 0.0
     */
    this.atmosphereHueShift = 0.0;

    /**
     * The saturation shift to apply to the atmosphere. Defaults to 0.0 (no shift).
     * A saturation shift of -1.0 is monochrome.
     * @type {Number}
     * @default 0.0
     */
    this.atmosphereSaturationShift = 0.0;

    /**
     * The brightness shift to apply to the atmosphere. Defaults to 0.0 (no shift).
     * A brightness shift of -1.0 is complete darkness, which will let space show through.
     * @type {Number}
     * @default 0.0
     */
    this.atmosphereBrightnessShift = 0.0;

    /**
     * A scalar used to exaggerate the terrain. Defaults to <code>1.0</code> (no exaggeration).
     * A value of <code>2.0</code> scales the terrain by 2x.
     * A value of <code>0.0</code> makes the terrain completely flat.
     * Note that terrain exaggeration will not modify any other primitive as they are positioned relative to the ellipsoid.
     * @type {Number}
     * @default 1.0
     */
    this.terrainExaggeration = 1.0;

    /**
     * The height from which terrain is exaggerated. Defaults to <code>0.0</code> (scaled relative to ellipsoid surface).
     * Terrain that is above this height will scale upwards and terrain that is below this height will scale downwards.
     * Note that terrain exaggeration will not modify any other primitive as they are positioned relative to the ellipsoid.
     * If {@link Globe#terrainExaggeration} is <code>1.0</code> this value will have no effect.
     * @type {Number}
     * @default 0.0
     */
    this.terrainExaggerationRelativeHeight = 0.0;

    /**
     * Whether to show terrain skirts. Terrain skirts are geometry extending downwards from a tile's edges used to hide seams between neighboring tiles.
     * Skirts are always hidden when the camera is underground or translucency is enabled.
     *
     * @type {Boolean}
     * @default true
     */
    this.showSkirts = true;

    /**
     * Whether to cull back-facing terrain. Back faces are not culled when the camera is underground or translucency is enabled.
     *
     * @type {Boolean}
     * @default true
     */
    this.backFaceCulling = true;

    this._oceanNormalMap = undefined;
    this._zoomedOutOceanSpecularIntensity = undefined;
  }

  Object.defineProperties(Globe.prototype, {
    /**
     * Gets an ellipsoid describing the shape of this globe.
     * @memberof Globe.prototype
     * @type {Ellipsoid}
     */
    ellipsoid: {
      get: function () {
        return this._ellipsoid;
      },
    },
    /**
     * Gets the collection of image layers that will be rendered on this globe.
     * @memberof Globe.prototype
     * @type {ImageryLayerCollection}
     */
    imageryLayers: {
      get: function () {
        return this._imageryLayerCollection;
      },
    },
    /**
     * Gets an event that's raised when an imagery layer is added, shown, hidden, moved, or removed.
     *
     * @memberof Globe.prototype
     * @type {Event}
     * @readonly
     */
    imageryLayersUpdatedEvent: {
      get: function () {
        return this._surface.tileProvider.imageryLayersUpdatedEvent;
      },
    },
    /**
     * Returns <code>true</code> when the tile load queue is empty, <code>false</code> otherwise.  When the load queue is empty,
     * all terrain and imagery for the current view have been loaded.
     * @memberof Globe.prototype
     * @type {Boolean}
     * @readonly
     */
    tilesLoaded: {
      get: function () {
        if (!defined(this._surface)) {
          return true;
        }
        return (
          this._surface.tileProvider.ready &&
          this._surface._tileLoadQueueHigh.length === 0 &&
          this._surface._tileLoadQueueMedium.length === 0 &&
          this._surface._tileLoadQueueLow.length === 0
        );
      },
    },
    /**
     * Gets or sets the color of the globe when no imagery is available.
     * @memberof Globe.prototype
     * @type {Color}
     */
    baseColor: {
      get: function () {
        return this._surface.tileProvider.baseColor;
      },
      set: function (value) {
        this._surface.tileProvider.baseColor = value;
      },
    },
    /**
     * A property specifying a {@link ClippingPlaneCollection} used to selectively disable rendering on the outside of each plane.
     *
     * @memberof Globe.prototype
     * @type {ClippingPlaneCollection}
     */
    clippingPlanes: {
      get: function () {
        return this._surface.tileProvider.clippingPlanes;
      },
      set: function (value) {
        this._surface.tileProvider.clippingPlanes = value;
      },
    },
    /**
     * A property specifying a {@link Rectangle} used to limit globe rendering to a cartographic area.
     * Defaults to the maximum extent of cartographic coordinates.
     *
     * @memberof Globe.prototype
     * @type {Rectangle}
     * @default {@link Rectangle.MAX_VALUE}
     */
    cartographicLimitRectangle: {
      get: function () {
        return this._surface.tileProvider.cartographicLimitRectangle;
      },
      set: function (value) {
        if (!defined(value)) {
          value = Rectangle.clone(Rectangle.MAX_VALUE);
        }
        this._surface.tileProvider.cartographicLimitRectangle = value;
      },
    },
    /**
     * The normal map to use for rendering waves in the ocean.  Setting this property will
     * only have an effect if the configured terrain provider includes a water mask.
     * @memberof Globe.prototype
     * @type {String}
     * @default buildModuleUrl('Assets/Textures/waterNormalsSmall.jpg')
     */
    oceanNormalMapUrl: {
      get: function () {
        return this._oceanNormalMapResource.url;
      },
      set: function (value) {
        this._oceanNormalMapResource.url = value;
        this._oceanNormalMapResourceDirty = true;
      },
    },
    /**
     * The terrain provider providing surface geometry for this globe.
     * @type {TerrainProvider}
     *
     * @memberof Globe.prototype
     * @type {TerrainProvider}
     *
     */
    terrainProvider: {
      get: function () {
        return this._terrainProvider;
      },
      set: function (value) {
        if (value !== this._terrainProvider) {
          this._terrainProvider = value;
          this._terrainProviderChanged.raiseEvent(value);
          if (defined(this._material)) {
            makeShadersDirty(this);
          }
        }
      },
    },
    /**
     * Gets an event that's raised when the terrain provider is changed
     *
     * @memberof Globe.prototype
     * @type {Event}
     * @readonly
     */
    terrainProviderChanged: {
      get: function () {
        return this._terrainProviderChanged;
      },
    },
    /**
     * Gets an event that's raised when the length of the tile load queue has changed since the last render frame.  When the load queue is empty,
     * all terrain and imagery for the current view have been loaded.  The event passes the new length of the tile load queue.
     *
     * @memberof Globe.prototype
     * @type {Event}
     */
    tileLoadProgressEvent: {
      get: function () {
        return this._surface.tileLoadProgressEvent;
      },
    },

    /**
     * Gets or sets the material appearance of the Globe.  This can be one of several built-in {@link Material} objects or a custom material, scripted with
     * {@link https://github.com/CesiumGS/cesium/wiki/Fabric|Fabric}.
     * @memberof Globe.prototype
     * @type {Material | undefined}
     */
    material: {
      get: function () {
        return this._material;
      },
      set: function (material) {
        if (this._material !== material) {
          this._material = material;
          makeShadersDirty(this);
        }
      },
    },

    /**
     * The color to render the back side of the globe when the camera is underground or the globe is translucent,
     * blended with the globe color based on the camera's distance.
     * <br /><br />
     * To disable underground coloring, set <code>undergroundColor</code> to <code>undefined</code>.
     *
     * @memberof Globe.prototype
     * @type {Color}
     * @default {@link Color.BLACK}
     *
     * @see Globe#undergroundColorAlphaByDistance
     */
    undergroundColor: {
      get: function () {
        return this._undergroundColor;
      },
      set: function (value) {
        this._undergroundColor = Color.clone(value, this._undergroundColor);
      },
    },

    /**
     * Gets or sets the near and far distance for blending {@link Globe#undergroundColor} with the globe color.
     * The alpha will interpolate between the {@link NearFarScalar#nearValue} and
     * {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds
     * of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}.
     * Outside of these ranges the alpha remains clamped to the nearest bound. If undefined,
     * the underground color will not be blended with the globe color.
     * <br /> <br />
     * When the camera is above the ellipsoid the distance is computed from the nearest
     * point on the ellipsoid instead of the camera's position.
     *
     * @memberof Globe.prototype
     * @type {NearFarScalar}
     *
     * @see Globe#undergroundColor
     *
     */
    undergroundColorAlphaByDistance: {
      get: function () {
        return this._undergroundColorAlphaByDistance;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (defined(value) && value.far < value.near) {
          throw new DeveloperError(
            "far distance must be greater than near distance."
          );
        }
        //>>includeEnd('debug');
        this._undergroundColorAlphaByDistance = NearFarScalar.clone(
          value,
          this._undergroundColorAlphaByDistance
        );
      },
    },

    /**
     * Properties for controlling globe translucency.
     *
     * @memberof Globe.prototype
     * @type {GlobeTranslucency}
     */
    translucency: {
      get: function () {
        return this._translucency;
      },
    },
  });

  function makeShadersDirty(globe) {
    const defines = [];

    const requireNormals =
      defined(globe._material) &&
      (globe._material.shaderSource.match(/slope/) ||
        globe._material.shaderSource.match("normalEC"));

    const fragmentSources = [AtmosphereCommon, GroundAtmosphere];
    if (
      defined(globe._material) &&
      (!requireNormals || globe._terrainProvider.requestVertexNormals)
    ) {
      fragmentSources.push(globe._material.shaderSource);
      defines.push("APPLY_MATERIAL");
      globe._surface._tileProvider.materialUniformMap = globe._material._uniforms;
    } else {
      globe._surface._tileProvider.materialUniformMap = undefined;
    }
    fragmentSources.push(GlobeFS);

    globe._surfaceShaderSet.baseVertexShaderSource = new ShaderSource({
      sources: [AtmosphereCommon, GroundAtmosphere, GlobeVS],
      defines: defines,
    });

    globe._surfaceShaderSet.baseFragmentShaderSource = new ShaderSource({
      sources: fragmentSources,
      defines: defines,
    });
    globe._surfaceShaderSet.material = globe._material;
  }

  function createComparePickTileFunction(rayOrigin) {
    return function (a, b) {
      const aDist = BoundingSphere.distanceSquaredTo(
        a.pickBoundingSphere,
        rayOrigin
      );
      const bDist = BoundingSphere.distanceSquaredTo(
        b.pickBoundingSphere,
        rayOrigin
      );

      return aDist - bDist;
    };
  }

  const scratchArray = [];
  const scratchSphereIntersectionResult = {
    start: 0.0,
    stop: 0.0,
  };

  /**
   * Find an intersection between a ray and the globe surface that was rendered. The ray must be given in world coordinates.
   *
   * @param {Ray} ray The ray to test for intersection.
   * @param {Scene} scene The scene.
   * @param {Boolean} [cullBackFaces=true] Set to true to not pick back faces.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3|undefined} The intersection or <code>undefined</code> if none was found.  The returned position is in projected coordinates for 2D and Columbus View.
   *
   * @private
   */
  Globe.prototype.pickWorldCoordinates = function (
    ray,
    scene,
    cullBackFaces,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(ray)) {
      throw new DeveloperError("ray is required");
    }
    if (!defined(scene)) {
      throw new DeveloperError("scene is required");
    }
    //>>includeEnd('debug');

    cullBackFaces = defaultValue(cullBackFaces, true);

    const mode = scene.mode;
    const projection = scene.mapProjection;

    const sphereIntersections = scratchArray;
    sphereIntersections.length = 0;

    const tilesToRender = this._surface._tilesToRender;
    let length = tilesToRender.length;

    let tile;
    let i;

    for (i = 0; i < length; ++i) {
      tile = tilesToRender[i];
      const surfaceTile = tile.data;

      if (!defined(surfaceTile)) {
        continue;
      }

      let boundingVolume = surfaceTile.pickBoundingSphere;
      if (mode !== SceneMode$1.SCENE3D) {
        surfaceTile.pickBoundingSphere = boundingVolume = BoundingSphere.fromRectangleWithHeights2D(
          tile.rectangle,
          projection,
          surfaceTile.tileBoundingRegion.minimumHeight,
          surfaceTile.tileBoundingRegion.maximumHeight,
          boundingVolume
        );
        Cartesian3.fromElements(
          boundingVolume.center.z,
          boundingVolume.center.x,
          boundingVolume.center.y,
          boundingVolume.center
        );
      } else if (defined(surfaceTile.renderedMesh)) {
        BoundingSphere.clone(
          surfaceTile.tileBoundingRegion.boundingSphere,
          boundingVolume
        );
      } else {
        // So wait how did we render this thing then? It shouldn't be possible to get here.
        continue;
      }

      const boundingSphereIntersection = IntersectionTests.raySphere(
        ray,
        boundingVolume,
        scratchSphereIntersectionResult
      );
      if (defined(boundingSphereIntersection)) {
        sphereIntersections.push(surfaceTile);
      }
    }

    sphereIntersections.sort(createComparePickTileFunction(ray.origin));

    let intersection;
    length = sphereIntersections.length;
    for (i = 0; i < length; ++i) {
      intersection = sphereIntersections[i].pick(
        ray,
        scene.mode,
        scene.mapProjection,
        cullBackFaces,
        result
      );
      if (defined(intersection)) {
        break;
      }
    }

    return intersection;
  };

  const cartoScratch = new Cartographic();
  /**
   * Find an intersection between a ray and the globe surface that was rendered. The ray must be given in world coordinates.
   *
   * @param {Ray} ray The ray to test for intersection.
   * @param {Scene} scene The scene.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3|undefined} The intersection or <code>undefined</code> if none was found.
   *
   * @example
   * // find intersection of ray through a pixel and the globe
   * const ray = viewer.camera.getPickRay(windowCoordinates);
   * const intersection = globe.pick(ray, scene);
   */
  Globe.prototype.pick = function (ray, scene, result) {
    result = this.pickWorldCoordinates(ray, scene, true, result);
    if (defined(result) && scene.mode !== SceneMode$1.SCENE3D) {
      result = Cartesian3.fromElements(result.y, result.z, result.x, result);
      const carto = scene.mapProjection.unproject(result, cartoScratch);
      result = scene.globe.ellipsoid.cartographicToCartesian(carto, result);
    }

    return result;
  };

  const scratchGetHeightCartesian = new Cartesian3();
  const scratchGetHeightIntersection = new Cartesian3();
  const scratchGetHeightCartographic = new Cartographic();
  const scratchGetHeightRay = new Ray();

  function tileIfContainsCartographic(tile, cartographic) {
    return defined(tile) && Rectangle.contains(tile.rectangle, cartographic)
      ? tile
      : undefined;
  }

  /**
   * Get the height of the surface at a given cartographic.
   *
   * @param {Cartographic} cartographic The cartographic for which to find the height.
   * @returns {Number|undefined} The height of the cartographic or undefined if it could not be found.
   */
  Globe.prototype.getHeight = function (cartographic) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(cartographic)) {
      throw new DeveloperError("cartographic is required");
    }
    //>>includeEnd('debug');

    const levelZeroTiles = this._surface._levelZeroTiles;
    if (!defined(levelZeroTiles)) {
      return;
    }

    let tile;
    let i;

    const length = levelZeroTiles.length;
    for (i = 0; i < length; ++i) {
      tile = levelZeroTiles[i];
      if (Rectangle.contains(tile.rectangle, cartographic)) {
        break;
      }
    }

    if (i >= length) {
      return undefined;
    }

    let tileWithMesh = tile;

    while (defined(tile)) {
      tile =
        tileIfContainsCartographic(tile._southwestChild, cartographic) ||
        tileIfContainsCartographic(tile._southeastChild, cartographic) ||
        tileIfContainsCartographic(tile._northwestChild, cartographic) ||
        tile._northeastChild;

      if (
        defined(tile) &&
        defined(tile.data) &&
        defined(tile.data.renderedMesh)
      ) {
        tileWithMesh = tile;
      }
    }

    tile = tileWithMesh;

    // This tile was either rendered or culled.
    // It is sometimes useful to get a height from a culled tile,
    // e.g. when we're getting a height in order to place a billboard
    // on terrain, and the camera is looking at that same billboard.
    // The culled tile must have a valid mesh, though.
    if (
      !defined(tile) ||
      !defined(tile.data) ||
      !defined(tile.data.renderedMesh)
    ) {
      // Tile was not rendered (culled).
      return undefined;
    }

    const projection = this._surface._tileProvider.tilingScheme.projection;
    const ellipsoid = this._surface._tileProvider.tilingScheme.ellipsoid;

    //cartesian has to be on the ellipsoid surface for `ellipsoid.geodeticSurfaceNormal`
    const cartesian = Cartesian3.fromRadians(
      cartographic.longitude,
      cartographic.latitude,
      0.0,
      ellipsoid,
      scratchGetHeightCartesian
    );

    const ray = scratchGetHeightRay;
    const surfaceNormal = ellipsoid.geodeticSurfaceNormal(
      cartesian,
      ray.direction
    );

    // Try to find the intersection point between the surface normal and z-axis.
    // minimum height (-11500.0) for the terrain set, need to get this information from the terrain provider
    const rayOrigin = ellipsoid.getSurfaceNormalIntersectionWithZAxis(
      cartesian,
      11500.0,
      ray.origin
    );

    // Theoretically, not with Earth datums, the intersection point can be outside the ellipsoid
    if (!defined(rayOrigin)) {
      // intersection point is outside the ellipsoid, try other value
      // minimum height (-11500.0) for the terrain set, need to get this information from the terrain provider
      let minimumHeight;
      if (defined(tile.data.tileBoundingRegion)) {
        minimumHeight = tile.data.tileBoundingRegion.minimumHeight;
      }
      const magnitude = Math.min(defaultValue(minimumHeight, 0.0), -11500.0);

      // multiply by the *positive* value of the magnitude
      const vectorToMinimumPoint = Cartesian3.multiplyByScalar(
        surfaceNormal,
        Math.abs(magnitude) + 1,
        scratchGetHeightIntersection
      );
      Cartesian3.subtract(cartesian, vectorToMinimumPoint, ray.origin);
    }

    const intersection = tile.data.pick(
      ray,
      undefined,
      projection,
      false,
      scratchGetHeightIntersection
    );
    if (!defined(intersection)) {
      return undefined;
    }

    return ellipsoid.cartesianToCartographic(
      intersection,
      scratchGetHeightCartographic
    ).height;
  };

  /**
   * @private
   */
  Globe.prototype.update = function (frameState) {
    if (!this.show) {
      return;
    }

    if (frameState.passes.render) {
      this._surface.update(frameState);
    }
  };

  /**
   * @private
   */
  Globe.prototype.beginFrame = function (frameState) {
    const surface = this._surface;
    const tileProvider = surface.tileProvider;
    const terrainProvider = this.terrainProvider;
    const hasWaterMask =
      this.showWaterEffect &&
      terrainProvider.ready &&
      terrainProvider.hasWaterMask;

    if (hasWaterMask && this._oceanNormalMapResourceDirty) {
      // url changed, load new normal map asynchronously
      this._oceanNormalMapResourceDirty = false;
      const oceanNormalMapResource = this._oceanNormalMapResource;
      const oceanNormalMapUrl = oceanNormalMapResource.url;
      if (defined(oceanNormalMapUrl)) {
        const that = this;
        oceanNormalMapResource.fetchImage().then(function (image) {
          if (oceanNormalMapUrl !== that._oceanNormalMapResource.url) {
            // url changed while we were loading
            return;
          }

          that._oceanNormalMap =
            that._oceanNormalMap && that._oceanNormalMap.destroy();
          that._oceanNormalMap = new Texture({
            context: frameState.context,
            source: image,
          });
        });
      } else {
        this._oceanNormalMap =
          this._oceanNormalMap && this._oceanNormalMap.destroy();
      }
    }

    const pass = frameState.passes;
    const mode = frameState.mode;

    if (pass.render) {
      if (this.showGroundAtmosphere) {
        this._zoomedOutOceanSpecularIntensity = 0.4;
      } else {
        this._zoomedOutOceanSpecularIntensity = 0.5;
      }

      surface.maximumScreenSpaceError = this.maximumScreenSpaceError;
      surface.tileCacheSize = this.tileCacheSize;
      surface.loadingDescendantLimit = this.loadingDescendantLimit;
      surface.preloadAncestors = this.preloadAncestors;
      surface.preloadSiblings = this.preloadSiblings;

      tileProvider.terrainProvider = this.terrainProvider;
      tileProvider.lightingFadeOutDistance = this.lightingFadeOutDistance;
      tileProvider.lightingFadeInDistance = this.lightingFadeInDistance;
      tileProvider.nightFadeOutDistance = this.nightFadeOutDistance;
      tileProvider.nightFadeInDistance = this.nightFadeInDistance;
      tileProvider.zoomedOutOceanSpecularIntensity =
        mode === SceneMode$1.SCENE3D ? this._zoomedOutOceanSpecularIntensity : 0.0;
      tileProvider.hasWaterMask = hasWaterMask;
      tileProvider.oceanNormalMap = this._oceanNormalMap;
      tileProvider.enableLighting = this.enableLighting;
      tileProvider.dynamicAtmosphereLighting = this.dynamicAtmosphereLighting;
      tileProvider.dynamicAtmosphereLightingFromSun = this.dynamicAtmosphereLightingFromSun;
      tileProvider.showGroundAtmosphere = this.showGroundAtmosphere;
      tileProvider.atmosphereLightIntensity = this.atmosphereLightIntensity;
      tileProvider.atmosphereRayleighCoefficient = this.atmosphereRayleighCoefficient;
      tileProvider.atmosphereMieCoefficient = this.atmosphereMieCoefficient;
      tileProvider.atmosphereRayleighScaleHeight = this.atmosphereRayleighScaleHeight;
      tileProvider.atmosphereMieScaleHeight = this.atmosphereMieScaleHeight;
      tileProvider.atmosphereMieAnisotropy = this.atmosphereMieAnisotropy;
      tileProvider.shadows = this.shadows;
      tileProvider.hueShift = this.atmosphereHueShift;
      tileProvider.saturationShift = this.atmosphereSaturationShift;
      tileProvider.brightnessShift = this.atmosphereBrightnessShift;
      tileProvider.fillHighlightColor = this.fillHighlightColor;
      tileProvider.showSkirts = this.showSkirts;
      tileProvider.backFaceCulling = this.backFaceCulling;
      tileProvider.undergroundColor = this._undergroundColor;
      tileProvider.undergroundColorAlphaByDistance = this._undergroundColorAlphaByDistance;
      tileProvider.lambertDiffuseMultiplier = this.lambertDiffuseMultiplier;
      surface.beginFrame(frameState);
    }
  };

  /**
   * @private
   */
  Globe.prototype.render = function (frameState) {
    if (!this.show) {
      return;
    }

    if (defined(this._material)) {
      this._material.update(frameState.context);
    }

    this._surface.render(frameState);
  };

  /**
   * @private
   */
  Globe.prototype.endFrame = function (frameState) {
    if (!this.show) {
      return;
    }

    if (frameState.passes.render) {
      this._surface.endFrame(frameState);
    }
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} True if this object was destroyed; otherwise, false.
   *
   * @see Globe#destroy
   */
  Globe.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * globe = globe && globe.destroy();
   *
   * @see Globe#isDestroyed
   */
  Globe.prototype.destroy = function () {
    this._surfaceShaderSet =
      this._surfaceShaderSet && this._surfaceShaderSet.destroy();
    this._surface = this._surface && this._surface.destroy();
    this._oceanNormalMap = this._oceanNormalMap && this._oceanNormalMap.destroy();
    return destroyObject(this);
  };

  //This file is automatically rebuilt by the Cesium build process.
  var PassThrough = "uniform sampler2D colorTexture;\n\
varying vec2 v_textureCoordinates;\n\
void main()\n\
{\n\
gl_FragColor = texture2D(colorTexture, v_textureCoordinates);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var PassThroughDepth = "uniform highp sampler2D u_depthTexture;\n\
varying vec2 v_textureCoordinates;\n\
void main()\n\
{\n\
gl_FragColor = czm_packDepth(texture2D(u_depthTexture, v_textureCoordinates).r);\n\
}\n\
";

  /**
   * @private
   */
  function GlobeDepth() {
    this._picking = false;
    this._numSamples = 1;
    this._tempCopyDepthTexture = undefined;

    this._pickColorFramebuffer = new FramebufferManager({
      depthStencil: true,
      supportsDepthTexture: true,
    });
    this._outputFramebuffer = new FramebufferManager({
      depthStencil: true,
      supportsDepthTexture: true,
    });
    this._copyDepthFramebuffer = new FramebufferManager();
    this._tempCopyDepthFramebuffer = new FramebufferManager();
    this._updateDepthFramebuffer = new FramebufferManager({
      createColorAttachments: false,
      createDepthAttachments: false,
      depthStencil: true,
    });

    this._clearGlobeColorCommand = undefined;
    this._copyColorCommand = undefined;
    this._copyDepthCommand = undefined;
    this._tempCopyDepthCommand = undefined;
    this._updateDepthCommand = undefined;

    this._viewport = new BoundingRectangle();
    this._rs = undefined;
    this._rsBlend = undefined;
    this._rsUpdate = undefined;

    this._useScissorTest = false;
    this._scissorRectangle = undefined;

    this._useHdr = undefined;
    this._clearGlobeDepth = undefined;
  }

  Object.defineProperties(GlobeDepth.prototype, {
    colorFramebufferManager: {
      get: function () {
        return this._picking
          ? this._pickColorFramebuffer
          : this._outputFramebuffer;
      },
    },
    framebuffer: {
      get: function () {
        return this.colorFramebufferManager.framebuffer;
      },
    },
    depthStencilTexture: {
      get: function () {
        return this.colorFramebufferManager.getDepthStencilTexture();
      },
    },
    picking: {
      get: function () {
        return this._picking;
      },
      set: function (value) {
        this._picking = value;
      },
    },
  });

  function destroyFramebuffers$2(globeDepth) {
    globeDepth._pickColorFramebuffer.destroy();
    globeDepth._outputFramebuffer.destroy();
    globeDepth._copyDepthFramebuffer.destroy();
    globeDepth._tempCopyDepthFramebuffer.destroy();
    globeDepth._updateDepthFramebuffer.destroy();
  }

  function updateCopyCommands$1(globeDepth, context, width, height, passState) {
    globeDepth._viewport.width = width;
    globeDepth._viewport.height = height;

    const useScissorTest = !BoundingRectangle.equals(
      globeDepth._viewport,
      passState.viewport
    );
    let updateScissor = useScissorTest !== globeDepth._useScissorTest;
    globeDepth._useScissorTest = useScissorTest;

    if (
      !BoundingRectangle.equals(globeDepth._scissorRectangle, passState.viewport)
    ) {
      globeDepth._scissorRectangle = BoundingRectangle.clone(
        passState.viewport,
        globeDepth._scissorRectangle
      );
      updateScissor = true;
    }

    if (
      !defined(globeDepth._rs) ||
      !BoundingRectangle.equals(globeDepth._viewport, globeDepth._rs.viewport) ||
      updateScissor
    ) {
      globeDepth._rs = RenderState.fromCache({
        viewport: globeDepth._viewport,
        scissorTest: {
          enabled: globeDepth._useScissorTest,
          rectangle: globeDepth._scissorRectangle,
        },
      });
      globeDepth._rsBlend = RenderState.fromCache({
        viewport: globeDepth._viewport,
        scissorTest: {
          enabled: globeDepth._useScissorTest,
          rectangle: globeDepth._scissorRectangle,
        },
        blending: BlendingState$1.ALPHA_BLEND,
      });

      // Copy packed depth only if the 3D Tiles bit is set
      globeDepth._rsUpdate = RenderState.fromCache({
        viewport: globeDepth._viewport,
        scissorTest: {
          enabled: globeDepth._useScissorTest,
          rectangle: globeDepth._scissorRectangle,
        },
        stencilTest: {
          enabled: true,
          frontFunction: StencilFunction$1.EQUAL,
          frontOperation: {
            fail: StencilOperation$1.KEEP,
            zFail: StencilOperation$1.KEEP,
            zPass: StencilOperation$1.KEEP,
          },
          backFunction: StencilFunction$1.NEVER,
          reference: StencilConstants$1.CESIUM_3D_TILE_MASK,
          mask: StencilConstants$1.CESIUM_3D_TILE_MASK,
        },
      });
    }

    if (!defined(globeDepth._copyDepthCommand)) {
      globeDepth._copyDepthCommand = context.createViewportQuadCommand(
        PassThroughDepth,
        {
          uniformMap: {
            u_depthTexture: function () {
              return globeDepth.colorFramebufferManager.getDepthStencilTexture();
            },
          },
          owner: globeDepth,
        }
      );
    }

    globeDepth._copyDepthCommand.framebuffer =
      globeDepth._copyDepthFramebuffer.framebuffer;
    globeDepth._copyDepthCommand.renderState = globeDepth._rs;

    if (!defined(globeDepth._copyColorCommand)) {
      globeDepth._copyColorCommand = context.createViewportQuadCommand(
        PassThrough,
        {
          uniformMap: {
            colorTexture: function () {
              return globeDepth.colorFramebufferManager.getColorTexture();
            },
          },
          owner: globeDepth,
        }
      );
    }

    globeDepth._copyColorCommand.renderState = globeDepth._rs;

    if (!defined(globeDepth._tempCopyDepthCommand)) {
      globeDepth._tempCopyDepthCommand = context.createViewportQuadCommand(
        PassThroughDepth,
        {
          uniformMap: {
            u_depthTexture: function () {
              return globeDepth._tempCopyDepthTexture;
            },
          },
          owner: globeDepth,
        }
      );
    }

    globeDepth._tempCopyDepthCommand.framebuffer =
      globeDepth._tempCopyDepthFramebuffer.framebuffer;
    globeDepth._tempCopyDepthCommand.renderState = globeDepth._rs;

    if (!defined(globeDepth._updateDepthCommand)) {
      globeDepth._updateDepthCommand = context.createViewportQuadCommand(
        PassThrough,
        {
          uniformMap: {
            colorTexture: function () {
              return globeDepth._tempCopyDepthFramebuffer.getColorTexture();
            },
          },
          owner: globeDepth,
        }
      );
    }

    globeDepth._updateDepthCommand.framebuffer =
      globeDepth._updateDepthFramebuffer.framebuffer;
    globeDepth._updateDepthCommand.renderState = globeDepth._rsUpdate;

    if (!defined(globeDepth._clearGlobeColorCommand)) {
      globeDepth._clearGlobeColorCommand = new ClearCommand({
        color: new Color(0.0, 0.0, 0.0, 0.0),
        stencil: 0.0,
        owner: globeDepth,
      });
    }

    globeDepth._clearGlobeColorCommand.framebuffer = globeDepth.framebuffer;
  }

  GlobeDepth.prototype.update = function (
    context,
    passState,
    viewport,
    numSamples,
    hdr,
    clearGlobeDepth
  ) {
    const width = viewport.width;
    const height = viewport.height;

    const pixelDatatype = hdr
      ? context.halfFloatingPointTexture
        ? PixelDatatype$1.HALF_FLOAT
        : PixelDatatype$1.FLOAT
      : PixelDatatype$1.UNSIGNED_BYTE;
    this._numSamples = numSamples;
    if (this.picking) {
      this._pickColorFramebuffer.update(context, width, height);
    } else {
      this._outputFramebuffer.update(
        context,
        width,
        height,
        numSamples,
        pixelDatatype
      );
    }
    this._copyDepthFramebuffer.update(context, width, height);
    updateCopyCommands$1(this, context, width, height, passState);
    context.uniformState.globeDepthTexture = undefined;

    this._useHdr = hdr;
    this._clearGlobeDepth = clearGlobeDepth;
  };

  GlobeDepth.prototype.prepareColorTextures = function (context, blitStencil) {
    if (!this.picking && this._numSamples > 1) {
      this._outputFramebuffer.prepareTextures(context, blitStencil);
    }
  };

  GlobeDepth.prototype.executeCopyDepth = function (context, passState) {
    if (defined(this._copyDepthCommand)) {
      this.prepareColorTextures(context);
      this._copyDepthCommand.execute(context, passState);
      context.uniformState.globeDepthTexture = this._copyDepthFramebuffer.getColorTexture();
    }
  };

  GlobeDepth.prototype.executeUpdateDepth = function (
    context,
    passState,
    clearGlobeDepth,
    depthTexture
  ) {
    const depthTextureToCopy = defined(depthTexture)
      ? depthTexture
      : passState.framebuffer.depthStencilTexture;
    if (
      clearGlobeDepth ||
      depthTextureToCopy !== this.colorFramebufferManager.getDepthStencilTexture()
    ) {
      // First copy the depth to a temporary globe depth texture, then update the
      // main globe depth texture where the stencil bit for 3D Tiles is set.
      // This preserves the original globe depth except where 3D Tiles is rendered.
      // The additional texture and framebuffer resources are created on demand.
      if (defined(this._updateDepthCommand)) {
        if (
          !defined(this._updateDepthFramebuffer.framebuffer) ||
          this._updateDepthFramebuffer.getDepthStencilTexture() !==
            depthTextureToCopy ||
          this._updateDepthFramebuffer.getColorTexture() !==
            this._copyDepthFramebuffer.getColorTexture()
        ) {
          const width = this._copyDepthFramebuffer.getColorTexture().width;
          const height = this._copyDepthFramebuffer.getColorTexture().height;
          this._tempCopyDepthFramebuffer.destroy();
          this._tempCopyDepthFramebuffer.update(context, width, height);

          const colorTexture = this._copyDepthFramebuffer.getColorTexture();
          this._updateDepthFramebuffer.setColorTexture(colorTexture, 0);
          this._updateDepthFramebuffer.setDepthStencilTexture(depthTextureToCopy);
          this._updateDepthFramebuffer.update(context, width, height);

          updateCopyCommands$1(this, context, width, height, passState);
        }
        this._tempCopyDepthTexture = depthTextureToCopy;
        this._tempCopyDepthCommand.execute(context, passState);
        this._updateDepthCommand.execute(context, passState);
      }
      return;
    }

    // Fast path - the depth texture can be copied normally.
    if (defined(this._copyDepthCommand)) {
      this._copyDepthCommand.execute(context, passState);
    }
  };

  GlobeDepth.prototype.executeCopyColor = function (context, passState) {
    if (defined(this._copyColorCommand)) {
      this._copyColorCommand.execute(context, passState);
    }
  };

  GlobeDepth.prototype.clear = function (context, passState, clearColor) {
    const clear = this._clearGlobeColorCommand;
    if (defined(clear)) {
      Color.clone(clearColor, clear.color);
      this.colorFramebufferManager.clear(context, clear, passState);
    }
  };

  GlobeDepth.prototype.isDestroyed = function () {
    return false;
  };

  GlobeDepth.prototype.destroy = function () {
    destroyFramebuffers$2(this);

    if (defined(this._copyColorCommand)) {
      this._copyColorCommand.shaderProgram = this._copyColorCommand.shaderProgram.destroy();
    }

    if (defined(this._copyDepthCommand)) {
      this._copyDepthCommand.shaderProgram = this._copyDepthCommand.shaderProgram.destroy();
    }

    if (defined(this._tempCopyDepthCommand)) {
      this._tempCopyDepthCommand.shaderProgram = this._tempCopyDepthCommand.shaderProgram.destroy();
    }

    if (defined(this._updateDepthCommand)) {
      this._updateDepthCommand.shaderProgram = this._updateDepthCommand.shaderProgram.destroy();
    }

    return destroyObject(this);
  };

  /**
   * @private
   */
  function GlobeTranslucencyFramebuffer() {
    this._framebuffer = new FramebufferManager({
      depthStencil: true,
      supportsDepthTexture: true,
    });
    this._packedDepthFramebuffer = new FramebufferManager();

    this._renderState = undefined;

    this._packedDepthCommand = undefined;
    this._clearCommand = undefined;

    this._viewport = new BoundingRectangle();
    this._useScissorTest = false;
    this._scissorRectangle = undefined;
    this._useHdr = undefined;
  }

  Object.defineProperties(GlobeTranslucencyFramebuffer.prototype, {
    // Exposed for testing
    classificationTexture: {
      get: function () {
        return this._framebuffer.getColorTexture();
      },
    },
    classificationFramebuffer: {
      get: function () {
        return this._framebuffer.framebuffer;
      },
    },
    // Exposed for testing
    packedDepthFramebuffer: {
      get: function () {
        return this._packedDepthFramebuffer.framebuffer;
      },
    },
    depthStencilTexture: {
      get: function () {
        return this._framebuffer.getDepthStencilTexture();
      },
    },
    // Exposed for testing
    depthStencilRenderbuffer: {
      get: function () {
        return this._framebuffer.getDepthStencilRenderbuffer();
      },
    },
    packedDepthTexture: {
      get: function () {
        return this._packedDepthFramebuffer.getColorTexture();
      },
    },
  });

  function destroyResources$3(globeTranslucency) {
    globeTranslucency._framebuffer.destroy();
    globeTranslucency._packedDepthFramebuffer.destroy();
  }

  function updateResources$1(globeTranslucency, context, width, height, hdr) {
    const pixelDatatype = hdr
      ? context.halfFloatingPointTexture
        ? PixelDatatype$1.HALF_FLOAT
        : PixelDatatype$1.FLOAT
      : PixelDatatype$1.UNSIGNED_BYTE;
    globeTranslucency._framebuffer.update(
      context,
      width,
      height,
      1,
      pixelDatatype
    );
    globeTranslucency._packedDepthFramebuffer.update(context, width, height);
  }

  function updateCommands(globeTranslucency, context, width, height, passState) {
    globeTranslucency._viewport.width = width;
    globeTranslucency._viewport.height = height;

    const useScissorTest = !BoundingRectangle.equals(
      globeTranslucency._viewport,
      passState.viewport
    );
    let updateScissor = useScissorTest !== globeTranslucency._useScissorTest;
    globeTranslucency._useScissorTest = useScissorTest;

    if (
      !BoundingRectangle.equals(
        globeTranslucency._scissorRectangle,
        passState.viewport
      )
    ) {
      globeTranslucency._scissorRectangle = BoundingRectangle.clone(
        passState.viewport,
        globeTranslucency._scissorRectangle
      );
      updateScissor = true;
    }

    if (
      !defined(globeTranslucency._renderState) ||
      !BoundingRectangle.equals(
        globeTranslucency._viewport,
        globeTranslucency._renderState.viewport
      ) ||
      updateScissor
    ) {
      globeTranslucency._renderState = RenderState.fromCache({
        viewport: globeTranslucency._viewport,
        scissorTest: {
          enabled: globeTranslucency._useScissorTest,
          rectangle: globeTranslucency._scissorRectangle,
        },
      });
    }

    if (!defined(globeTranslucency._packedDepthCommand)) {
      globeTranslucency._packedDepthCommand = context.createViewportQuadCommand(
        PassThroughDepth,
        {
          uniformMap: {
            u_depthTexture: function () {
              return globeTranslucency.depthStencilTexture;
            },
          },
          owner: globeTranslucency,
        }
      );
    }

    if (!defined(globeTranslucency._clearCommand)) {
      globeTranslucency._clearCommand = new ClearCommand({
        color: new Color(0.0, 0.0, 0.0, 0.0),
        depth: 1.0,
        stencil: 0.0,
        owner: globeTranslucency,
      });
    }

    globeTranslucency._packedDepthCommand.framebuffer =
      globeTranslucency._packedDepthFramebuffer.framebuffer;
    globeTranslucency._packedDepthCommand.renderState =
      globeTranslucency._renderState;
    globeTranslucency._clearCommand.framebuffer =
      globeTranslucency.classificationFramebuffer;
    globeTranslucency._clearCommand.renderState = globeTranslucency._renderState;
  }

  GlobeTranslucencyFramebuffer.prototype.updateAndClear = function (
    hdr,
    viewport,
    context,
    passState
  ) {
    const width = viewport.width;
    const height = viewport.height;

    updateResources$1(this, context, width, height, hdr);
    updateCommands(this, context, width, height, passState);

    this._useHdr = hdr;
  };

  GlobeTranslucencyFramebuffer.prototype.clearClassification = function (
    context,
    passState
  ) {
    this._clearCommand.execute(context, passState);
  };

  GlobeTranslucencyFramebuffer.prototype.packDepth = function (
    context,
    passState
  ) {
    this._packedDepthCommand.execute(context, passState);
    return this.packedDepthTexture;
  };

  GlobeTranslucencyFramebuffer.prototype.isDestroyed = function () {
    return false;
  };

  GlobeTranslucencyFramebuffer.prototype.destroy = function () {
    destroyResources$3(this);
    return destroyObject(this);
  };

  const DerivedCommandType = {
    OPAQUE_FRONT_FACE: 0,
    OPAQUE_BACK_FACE: 1,
    DEPTH_ONLY_FRONT_FACE: 2,
    DEPTH_ONLY_BACK_FACE: 3,
    DEPTH_ONLY_FRONT_AND_BACK_FACE: 4,
    TRANSLUCENT_FRONT_FACE: 5,
    TRANSLUCENT_BACK_FACE: 6,
    TRANSLUCENT_FRONT_FACE_MANUAL_DEPTH_TEST: 7,
    TRANSLUCENT_BACK_FACE_MANUAL_DEPTH_TEST: 8,
    PICK_FRONT_FACE: 9,
    PICK_BACK_FACE: 10,
    DERIVED_COMMANDS_MAXIMUM_LENGTH: 11,
  };

  const derivedCommandsMaximumLength =
    DerivedCommandType.DERIVED_COMMANDS_MAXIMUM_LENGTH;

  const DerivedCommandNames = [
    "opaqueFrontFaceCommand",
    "opaqueBackFaceCommand",
    "depthOnlyFrontFaceCommand",
    "depthOnlyBackFaceCommand",
    "depthOnlyFrontAndBackFaceCommand",
    "translucentFrontFaceCommand",
    "translucentBackFaceCommand",
    "translucentFrontFaceManualDepthTestCommand",
    "translucentBackFaceManualDepthTestCommand",
    "pickFrontFaceCommand",
    "pickBackFaceCommand",
  ];

  /**
   * @private
   */
  function GlobeTranslucencyState() {
    this._frontFaceAlphaByDistance = new NearFarScalar(0.0, 1.0, 0.0, 1.0);
    this._backFaceAlphaByDistance = new NearFarScalar(0.0, 1.0, 0.0, 1.0);

    this._frontFaceTranslucent = false;
    this._backFaceTranslucent = false;
    this._requiresManualDepthTest = false;
    this._sunVisibleThroughGlobe = false;
    this._environmentVisible = false;
    this._useDepthPlane = false;
    this._numberOfTextureUniforms = 0;
    this._globeTranslucencyFramebuffer = undefined;
    this._rectangle = Rectangle.clone(Rectangle.MAX_VALUE);

    this._derivedCommandKey = 0;
    this._derivedCommandsDirty = false;
    this._derivedCommandPacks = undefined;

    this._derivedCommandTypes = new Array(derivedCommandsMaximumLength);
    this._derivedBlendCommandTypes = new Array(derivedCommandsMaximumLength);
    this._derivedPickCommandTypes = new Array(derivedCommandsMaximumLength);
    this._derivedCommandTypesToUpdate = new Array(derivedCommandsMaximumLength);

    this._derivedCommandsLength = 0;
    this._derivedBlendCommandsLength = 0;
    this._derivedPickCommandsLength = 0;
    this._derivedCommandsToUpdateLength = 0;
  }

  Object.defineProperties(GlobeTranslucencyState.prototype, {
    frontFaceAlphaByDistance: {
      get: function () {
        return this._frontFaceAlphaByDistance;
      },
    },
    backFaceAlphaByDistance: {
      get: function () {
        return this._backFaceAlphaByDistance;
      },
    },
    translucent: {
      get: function () {
        return this._frontFaceTranslucent;
      },
    },
    sunVisibleThroughGlobe: {
      get: function () {
        return this._sunVisibleThroughGlobe;
      },
    },
    environmentVisible: {
      get: function () {
        return this._environmentVisible;
      },
    },
    useDepthPlane: {
      get: function () {
        return this._useDepthPlane;
      },
    },
    numberOfTextureUniforms: {
      get: function () {
        return this._numberOfTextureUniforms;
      },
    },
    rectangle: {
      get: function () {
        return this._rectangle;
      },
    },
  });

  GlobeTranslucencyState.prototype.update = function (scene) {
    const globe = scene.globe;
    if (!defined(globe) || !globe.show) {
      this._frontFaceTranslucent = false;
      this._backFaceTranslucent = false;
      this._sunVisibleThroughGlobe = true;
      this._environmentVisible = true;
      this._useDepthPlane = false;
      return;
    }

    this._frontFaceAlphaByDistance = updateAlphaByDistance(
      globe.translucency.enabled,
      globe.translucency.frontFaceAlpha,
      globe.translucency.frontFaceAlphaByDistance,
      this._frontFaceAlphaByDistance
    );
    this._backFaceAlphaByDistance = updateAlphaByDistance(
      globe.translucency.enabled,
      globe.translucency.backFaceAlpha,
      globe.translucency.backFaceAlphaByDistance,
      this._backFaceAlphaByDistance
    );

    this._frontFaceTranslucent = isFaceTranslucent(
      globe.translucency.enabled,
      this._frontFaceAlphaByDistance,
      globe
    );
    this._backFaceTranslucent = isFaceTranslucent(
      globe.translucency.enabled,
      this._backFaceAlphaByDistance,
      globe
    );

    this._requiresManualDepthTest = requiresManualDepthTest(this, scene, globe);

    this._sunVisibleThroughGlobe = isSunVisibleThroughGlobe(this, scene);
    this._environmentVisible = isEnvironmentVisible(this, scene);
    this._useDepthPlane = useDepthPlane(this, scene);
    this._numberOfTextureUniforms = getNumberOfTextureUniforms(this);

    this._rectangle = Rectangle.clone(
      globe.translucency.rectangle,
      this._rectangle
    );

    gatherDerivedCommandRequirements(this, scene);
  };

  function updateAlphaByDistance(enabled, alpha, alphaByDistance, result) {
    if (!enabled) {
      result.nearValue = 1.0;
      result.farValue = 1.0;
      return result;
    }

    if (!defined(alphaByDistance)) {
      result.nearValue = alpha;
      result.farValue = alpha;
      return result;
    }

    NearFarScalar.clone(alphaByDistance, result);
    result.nearValue *= alpha;
    result.farValue *= alpha;
    return result;
  }

  function isFaceTranslucent(translucencyEnabled, alphaByDistance, globe) {
    return (
      translucencyEnabled &&
      (globe.baseColor.alpha < 1.0 ||
        alphaByDistance.nearValue < 1.0 ||
        alphaByDistance.farValue < 1.0)
    );
  }

  function isSunVisibleThroughGlobe(state, scene) {
    // The sun is visible through the globe if the front and back faces are translucent when above ground
    // or if front faces are translucent when below ground
    const frontTranslucent = state._frontFaceTranslucent;
    const backTranslucent = state._backFaceTranslucent;
    return frontTranslucent && (scene.cameraUnderground || backTranslucent);
  }

  function isEnvironmentVisible(state, scene) {
    // The environment is visible if the camera is above ground or underground with translucency
    return !scene.cameraUnderground || state._frontFaceTranslucent;
  }

  function useDepthPlane(state, scene) {
    // Use the depth plane when the camera is above ground and the globe is opaque
    return !scene.cameraUnderground && !state._frontFaceTranslucent;
  }

  function requiresManualDepthTest(state, scene, globe) {
    return (
      state._frontFaceTranslucent &&
      !state._backFaceTranslucent &&
      !globe.depthTestAgainstTerrain &&
      scene.mode !== SceneMode$1.SCENE2D &&
      scene.context.depthTexture
    );
  }

  function getNumberOfTextureUniforms(state) {
    let numberOfTextureUniforms = 0;

    if (state._frontFaceTranslucent) {
      ++numberOfTextureUniforms; // classification texture
    }

    if (state._requiresManualDepthTest) {
      ++numberOfTextureUniforms; // czm_globeDepthTexture for manual depth testing
    }

    return numberOfTextureUniforms;
  }

  function gatherDerivedCommandRequirements(state, scene) {
    state._derivedCommandsLength = getDerivedCommandTypes(
      state,
      scene,
      false,
      false,
      state._derivedCommandTypes
    );

    state._derivedBlendCommandsLength = getDerivedCommandTypes(
      state,
      scene,
      true,
      false,
      state._derivedBlendCommandTypes
    );

    state._derivedPickCommandsLength = getDerivedCommandTypes(
      state,
      scene,
      false,
      true,
      state._derivedPickCommandTypes
    );

    let i;

    let derivedCommandKey = 0;
    for (i = 0; i < state._derivedCommandsLength; ++i) {
      derivedCommandKey |= 1 << state._derivedCommandTypes[i];
    }
    for (i = 0; i < state._derivedBlendCommandsLength; ++i) {
      derivedCommandKey |= 1 << state._derivedBlendCommandTypes[i];
    }
    for (i = 0; i < state._derivedPickCommandsLength; ++i) {
      derivedCommandKey |= 1 << state._derivedPickCommandTypes[i];
    }

    let derivedCommandsToUpdateLength = 0;
    for (i = 0; i < derivedCommandsMaximumLength; ++i) {
      if ((derivedCommandKey & (1 << i)) > 0) {
        state._derivedCommandTypesToUpdate[derivedCommandsToUpdateLength++] = i;
      }
    }
    state._derivedCommandsToUpdateLength = derivedCommandsToUpdateLength;

    const derivedCommandsDirty = derivedCommandKey !== state._derivedCommandKey;
    state._derivedCommandKey = derivedCommandKey;
    state._derivedCommandsDirty = derivedCommandsDirty;

    if (!defined(state._derivedCommandPacks) && state._frontFaceTranslucent) {
      state._derivedCommandPacks = createDerivedCommandPacks();
    }
  }

  function getDerivedCommandTypes(
    state,
    scene,
    isBlendCommand,
    isPickCommand,
    types
  ) {
    let length = 0;

    const frontTranslucent = state._frontFaceTranslucent;
    const backTranslucent = state._backFaceTranslucent;

    if (!frontTranslucent) {
      // Don't use derived commands if the globe is opaque
      return length;
    }

    const cameraUnderground = scene.cameraUnderground;
    const requiresManualDepthTest = state._requiresManualDepthTest;

    const translucentFrontFaceCommandType = isPickCommand
      ? DerivedCommandType.PICK_FRONT_FACE
      : requiresManualDepthTest
      ? DerivedCommandType.TRANSLUCENT_FRONT_FACE_MANUAL_DEPTH_TEST
      : DerivedCommandType.TRANSLUCENT_FRONT_FACE;

    const translucentBackFaceCommandType = isPickCommand
      ? DerivedCommandType.PICK_BACK_FACE
      : requiresManualDepthTest
      ? DerivedCommandType.TRANSLUCENT_BACK_FACE_MANUAL_DEPTH_TEST
      : DerivedCommandType.TRANSLUCENT_BACK_FACE;

    if (scene.mode === SceneMode$1.SCENE2D) {
      types[length++] = DerivedCommandType.DEPTH_ONLY_FRONT_FACE;
      types[length++] = translucentFrontFaceCommandType;
      return length;
    }

    if (backTranslucent) {
      // Push depth-only command for classification. Blend commands do not need to write depth.
      // Push translucent commands for front and back faces.
      if (!isBlendCommand) {
        types[length++] = DerivedCommandType.DEPTH_ONLY_FRONT_AND_BACK_FACE;
      }
      if (cameraUnderground) {
        types[length++] = translucentFrontFaceCommandType;
        types[length++] = translucentBackFaceCommandType;
      } else {
        types[length++] = translucentBackFaceCommandType;
        types[length++] = translucentFrontFaceCommandType;
      }
    } else {
      // Push opaque command for the face that appears in back.
      // Push depth-only command and translucent command for the face that appears in front.
      // eslint-disable-next-line no-lonely-if
      if (cameraUnderground) {
        if (!isBlendCommand) {
          types[length++] = DerivedCommandType.DEPTH_ONLY_BACK_FACE;
        }
        types[length++] = DerivedCommandType.OPAQUE_FRONT_FACE;
        types[length++] = translucentBackFaceCommandType;
      } else {
        if (!isBlendCommand) {
          types[length++] = DerivedCommandType.DEPTH_ONLY_FRONT_FACE;
        }
        types[length++] = DerivedCommandType.OPAQUE_BACK_FACE;
        types[length++] = translucentFrontFaceCommandType;
      }
    }

    return length;
  }

  function removeDefine(defines, defineToRemove) {
    const index = defines.indexOf(defineToRemove);
    if (index > -1) {
      defines.splice(index, 1);
    }
  }

  function hasDefine(defines, define) {
    return defines.indexOf(define) > -1;
  }

  function getOpaqueFrontFaceShaderProgram(vs, fs) {
    removeDefine(vs.defines, "TRANSLUCENT");
    removeDefine(fs.defines, "TRANSLUCENT");
  }

  function getOpaqueBackFaceShaderProgram(vs, fs) {
    removeDefine(vs.defines, "GROUND_ATMOSPHERE");
    removeDefine(fs.defines, "GROUND_ATMOSPHERE");
    removeDefine(vs.defines, "FOG");
    removeDefine(fs.defines, "FOG");
    removeDefine(vs.defines, "TRANSLUCENT");
    removeDefine(fs.defines, "TRANSLUCENT");
  }

  function getDepthOnlyShaderProgram(vs, fs) {
    if (
      hasDefine(fs.defines, "TILE_LIMIT_RECTANGLE") ||
      hasDefine(fs.defines, "ENABLE_CLIPPING_PLANES")
    ) {
      // Need to execute the full shader if discard is called
      return;
    }

    const depthOnlyShader =
      "void main() \n" + "{ \n" + "    gl_FragColor = vec4(1.0); \n" + "} \n";

    fs.sources = [depthOnlyShader];
  }

  function getTranslucentShaderProgram$1(vs, fs) {
    const sources = fs.sources;
    const length = sources.length;
    for (let i = 0; i < length; ++i) {
      sources[i] = ShaderSource.replaceMain(
        sources[i],
        "czm_globe_translucency_main"
      );
    }

    const globeTranslucencyMain =
      "\n\n" +
      "uniform sampler2D u_classificationTexture; \n" +
      "void main() \n" +
      "{ \n" +
      "    vec2 st = gl_FragCoord.xy / czm_viewport.zw; \n" +
      "#ifdef MANUAL_DEPTH_TEST \n" +
      "    float logDepthOrDepth = czm_unpackDepth(texture2D(czm_globeDepthTexture, st)); \n" +
      "    if (logDepthOrDepth != 0.0) \n" +
      "    { \n" +
      "        vec4 eyeCoordinate = czm_windowToEyeCoordinates(gl_FragCoord.xy, logDepthOrDepth); \n" +
      "        float depthEC = eyeCoordinate.z / eyeCoordinate.w; \n" +
      "        if (v_positionEC.z < depthEC) \n" +
      "        { \n" +
      "            discard; \n" +
      "        } \n" +
      "    } \n" +
      "#endif \n" +
      "    czm_globe_translucency_main(); \n" +
      "    vec4 classificationColor = texture2D(u_classificationTexture, st); \n" +
      "    if (classificationColor.a > 0.0) \n" +
      "    { \n" +
      "        // Reverse premultiplication process to get the correct composited result of the classification primitives \n" +
      "        classificationColor.rgb /= classificationColor.a; \n" +
      "    } \n" +
      "    gl_FragColor = classificationColor * vec4(classificationColor.aaa, 1.0) + gl_FragColor * (1.0 - classificationColor.a); \n" +
      "} \n";

    sources.push(globeTranslucencyMain);
  }

  function getTranslucentBackFaceShaderProgram(vs, fs) {
    getTranslucentShaderProgram$1(vs, fs);
    removeDefine(vs.defines, "GROUND_ATMOSPHERE");
    removeDefine(fs.defines, "GROUND_ATMOSPHERE");
    removeDefine(vs.defines, "FOG");
    removeDefine(fs.defines, "FOG");
  }

  function getTranslucentFrontFaceManualDepthTestShaderProgram(vs, fs) {
    getTranslucentShaderProgram$1(vs, fs);
    vs.defines.push("GENERATE_POSITION");
    fs.defines.push("MANUAL_DEPTH_TEST");
  }

  function getTranslucentBackFaceManualDepthTestShaderProgram(vs, fs) {
    getTranslucentBackFaceShaderProgram(vs, fs);
    vs.defines.push("GENERATE_POSITION");
    fs.defines.push("MANUAL_DEPTH_TEST");
  }

  function getPickShaderProgram(vs, fs) {
    const pickShader =
      "uniform sampler2D u_classificationTexture; \n" +
      "void main() \n" +
      "{ \n" +
      "    vec2 st = gl_FragCoord.xy / czm_viewport.zw; \n" +
      "    vec4 pickColor = texture2D(u_classificationTexture, st); \n" +
      "    if (pickColor == vec4(0.0)) \n" +
      "    { \n" +
      "        discard; \n" +
      "    } \n" +
      "    gl_FragColor = pickColor; \n" +
      "} \n";

    fs.sources = [pickShader];
  }

  function getDerivedShaderProgram(
    context,
    shaderProgram,
    derivedShaderProgram,
    shaderProgramDirty,
    getShaderProgramFunction,
    cacheName
  ) {
    if (!defined(getShaderProgramFunction)) {
      return shaderProgram;
    }

    if (!shaderProgramDirty && defined(derivedShaderProgram)) {
      return derivedShaderProgram;
    }

    let shader = context.shaderCache.getDerivedShaderProgram(
      shaderProgram,
      cacheName
    );
    if (!defined(shader)) {
      const attributeLocations = shaderProgram._attributeLocations;
      const vs = shaderProgram.vertexShaderSource.clone();
      const fs = shaderProgram.fragmentShaderSource.clone();
      vs.defines = defined(vs.defines) ? vs.defines.slice(0) : [];
      fs.defines = defined(fs.defines) ? fs.defines.slice(0) : [];

      getShaderProgramFunction(vs, fs);

      shader = context.shaderCache.createDerivedShaderProgram(
        shaderProgram,
        cacheName,
        {
          vertexShaderSource: vs,
          fragmentShaderSource: fs,
          attributeLocations: attributeLocations,
        }
      );
    }

    return shader;
  }

  function getOpaqueFrontFaceRenderState(renderState) {
    renderState.cull.face = CullFace$1.BACK;
    renderState.cull.enabled = true;
  }

  function getOpaqueBackFaceRenderState(renderState) {
    renderState.cull.face = CullFace$1.FRONT;
    renderState.cull.enabled = true;
  }

  function getDepthOnlyFrontFaceRenderState(renderState) {
    renderState.cull.face = CullFace$1.BACK;
    renderState.cull.enabled = true;
    renderState.colorMask = {
      red: false,
      green: false,
      blue: false,
      alpha: false,
    };
  }

  function getDepthOnlyBackFaceRenderState(renderState) {
    renderState.cull.face = CullFace$1.FRONT;
    renderState.cull.enabled = true;
    renderState.colorMask = {
      red: false,
      green: false,
      blue: false,
      alpha: false,
    };
  }

  function getDepthOnlyFrontAndBackFaceRenderState(renderState) {
    renderState.cull.enabled = false;
    renderState.colorMask = {
      red: false,
      green: false,
      blue: false,
      alpha: false,
    };
  }

  function getTranslucentFrontFaceRenderState(renderState) {
    renderState.cull.face = CullFace$1.BACK;
    renderState.cull.enabled = true;
    renderState.depthMask = false;
    renderState.blending = BlendingState$1.ALPHA_BLEND;
  }

  function getTranslucentBackFaceRenderState(renderState) {
    renderState.cull.face = CullFace$1.FRONT;
    renderState.cull.enabled = true;
    renderState.depthMask = false;
    renderState.blending = BlendingState$1.ALPHA_BLEND;
  }

  function getPickFrontFaceRenderState(renderState) {
    renderState.cull.face = CullFace$1.BACK;
    renderState.cull.enabled = true;
    renderState.blending.enabled = false;
  }

  function getPickBackFaceRenderState(renderState) {
    renderState.cull.face = CullFace$1.FRONT;
    renderState.cull.enabled = true;
    renderState.blending.enabled = false;
  }

  function getDerivedRenderState(
    renderState,
    derivedRenderState,
    renderStateDirty,
    getRenderStateFunction,
    cache
  ) {
    if (!defined(getRenderStateFunction)) {
      return renderState;
    }

    if (!renderStateDirty && defined(derivedRenderState)) {
      return derivedRenderState;
    }

    let cachedRenderState = cache[renderState.id];
    if (!defined(cachedRenderState)) {
      const rs = RenderState.getState(renderState);
      getRenderStateFunction(rs);
      cachedRenderState = RenderState.fromCache(rs);
      cache[renderState.id] = cachedRenderState;
    }

    return cachedRenderState;
  }

  function getTranslucencyUniformMap(state) {
    return {
      u_classificationTexture: function () {
        return state._globeTranslucencyFramebuffer.classificationTexture;
      },
    };
  }

  function getDerivedUniformMap(
    state,
    uniformMap,
    derivedUniformMap,
    uniformMapDirty,
    getDerivedUniformMapFunction
  ) {
    if (!defined(getDerivedUniformMapFunction)) {
      return uniformMap;
    }

    if (!uniformMapDirty && defined(derivedUniformMap)) {
      return derivedUniformMap;
    }

    return combine$2(uniformMap, getDerivedUniformMapFunction(state), false);
  }

  function DerivedCommandPack(options) {
    this.pass = options.pass;
    this.pickOnly = options.pickOnly;
    this.getShaderProgramFunction = options.getShaderProgramFunction;
    this.getRenderStateFunction = options.getRenderStateFunction;
    this.getUniformMapFunction = options.getUniformMapFunction;
    this.renderStateCache = {};
  }

  function createDerivedCommandPacks() {
    return [
      // opaqueFrontFaceCommand
      new DerivedCommandPack({
        pass: Pass$1.GLOBE,
        pickOnly: false,
        getShaderProgramFunction: getOpaqueFrontFaceShaderProgram,
        getRenderStateFunction: getOpaqueFrontFaceRenderState,
        getUniformMapFunction: undefined,
      }),
      // opaqueBackFaceCommand
      new DerivedCommandPack({
        pass: Pass$1.GLOBE,
        pickOnly: false,
        getShaderProgramFunction: getOpaqueBackFaceShaderProgram,
        getRenderStateFunction: getOpaqueBackFaceRenderState,
        getUniformMapFunction: undefined,
      }),
      // depthOnlyFrontFaceCommand
      new DerivedCommandPack({
        pass: Pass$1.GLOBE,
        pickOnly: false,
        getShaderProgramFunction: getDepthOnlyShaderProgram,
        getRenderStateFunction: getDepthOnlyFrontFaceRenderState,
        getUniformMapFunction: undefined,
      }),
      // depthOnlyBackFaceCommand
      new DerivedCommandPack({
        pass: Pass$1.GLOBE,
        pickOnly: false,
        getShaderProgramFunction: getDepthOnlyShaderProgram,
        getRenderStateFunction: getDepthOnlyBackFaceRenderState,
        getUniformMapFunction: undefined,
      }),
      // depthOnlyFrontAndBackFaceCommand
      new DerivedCommandPack({
        pass: Pass$1.GLOBE,
        pickOnly: false,
        getShaderProgramFunction: getDepthOnlyShaderProgram,
        getRenderStateFunction: getDepthOnlyFrontAndBackFaceRenderState,
        getUniformMapFunction: undefined,
      }),
      // translucentFrontFaceCommand
      new DerivedCommandPack({
        pass: Pass$1.TRANSLUCENT,
        pickOnly: false,
        getShaderProgramFunction: getTranslucentShaderProgram$1,
        getRenderStateFunction: getTranslucentFrontFaceRenderState,
        getUniformMapFunction: getTranslucencyUniformMap,
      }),
      // translucentBackFaceCommand
      new DerivedCommandPack({
        pass: Pass$1.TRANSLUCENT,
        pickOnly: false,
        getShaderProgramFunction: getTranslucentBackFaceShaderProgram,
        getRenderStateFunction: getTranslucentBackFaceRenderState,
        getUniformMapFunction: getTranslucencyUniformMap,
      }),
      // translucentFrontFaceManualDepthTestCommand
      new DerivedCommandPack({
        pass: Pass$1.TRANSLUCENT,
        pickOnly: false,
        getShaderProgramFunction: getTranslucentFrontFaceManualDepthTestShaderProgram,
        getRenderStateFunction: getTranslucentFrontFaceRenderState,
        getUniformMapFunction: getTranslucencyUniformMap,
      }),
      // translucentBackFaceManualDepthTestCommand
      new DerivedCommandPack({
        pass: Pass$1.TRANSLUCENT,
        pickOnly: false,
        getShaderProgramFunction: getTranslucentBackFaceManualDepthTestShaderProgram,
        getRenderStateFunction: getTranslucentBackFaceRenderState,
        getUniformMapFunction: getTranslucencyUniformMap,
      }),
      // pickFrontFaceCommand
      new DerivedCommandPack({
        pass: Pass$1.TRANSLUCENT,
        pickOnly: true,
        getShaderProgramFunction: getPickShaderProgram,
        getRenderStateFunction: getPickFrontFaceRenderState,
        getUniformMapFunction: getTranslucencyUniformMap,
      }),
      // pickBackFaceCommand
      new DerivedCommandPack({
        pass: Pass$1.TRANSLUCENT,
        pickOnly: true,
        getShaderProgramFunction: getPickShaderProgram,
        getRenderStateFunction: getPickBackFaceRenderState,
        getUniformMapFunction: getTranslucencyUniformMap,
      }),
    ];
  }

  const derivedCommandNames = new Array(derivedCommandsMaximumLength);
  const derivedCommandPacks = new Array(derivedCommandsMaximumLength);

  GlobeTranslucencyState.prototype.updateDerivedCommands = function (
    command,
    frameState
  ) {
    const derivedCommandTypes = this._derivedCommandTypesToUpdate;
    const derivedCommandsLength = this._derivedCommandsToUpdateLength;

    if (derivedCommandsLength === 0) {
      return;
    }

    for (let i = 0; i < derivedCommandsLength; ++i) {
      derivedCommandPacks[i] = this._derivedCommandPacks[derivedCommandTypes[i]];
      derivedCommandNames[i] = DerivedCommandNames[derivedCommandTypes[i]];
    }

    updateDerivedCommands$1(
      this,
      command,
      derivedCommandsLength,
      derivedCommandTypes,
      derivedCommandNames,
      derivedCommandPacks,
      frameState
    );
  };

  function updateDerivedCommands$1(
    state,
    command,
    derivedCommandsLength,
    derivedCommandTypes,
    derivedCommandNames,
    derivedCommandPacks,
    frameState
  ) {
    let derivedCommandsObject = command.derivedCommands.globeTranslucency;
    const derivedCommandsDirty = state._derivedCommandsDirty;

    if (
      command.dirty ||
      !defined(derivedCommandsObject) ||
      derivedCommandsDirty
    ) {
      command.dirty = false;

      if (!defined(derivedCommandsObject)) {
        derivedCommandsObject = {};
        command.derivedCommands.globeTranslucency = derivedCommandsObject;
      }

      const frameNumber = frameState.frameNumber;

      const uniformMapDirtyFrame = defaultValue(
        derivedCommandsObject.uniformMapDirtyFrame,
        0
      );
      const shaderProgramDirtyFrame = defaultValue(
        derivedCommandsObject.shaderProgramDirtyFrame,
        0
      );
      const renderStateDirtyFrame = defaultValue(
        derivedCommandsObject.renderStateDirtyFrame,
        0
      );

      const uniformMapDirty =
        derivedCommandsObject.uniformMap !== command.uniformMap;

      const shaderProgramDirty =
        derivedCommandsObject.shaderProgramId !== command.shaderProgram.id;

      const renderStateDirty =
        derivedCommandsObject.renderStateId !== command.renderState.id;

      if (uniformMapDirty) {
        derivedCommandsObject.uniformMapDirtyFrame = frameNumber;
      }
      if (shaderProgramDirty) {
        derivedCommandsObject.shaderProgramDirtyFrame = frameNumber;
      }
      if (renderStateDirty) {
        derivedCommandsObject.renderStateDirtyFrame = frameNumber;
      }

      derivedCommandsObject.uniformMap = command.uniformMap;
      derivedCommandsObject.shaderProgramId = command.shaderProgram.id;
      derivedCommandsObject.renderStateId = command.renderState.id;

      for (let i = 0; i < derivedCommandsLength; ++i) {
        const derivedCommandPack = derivedCommandPacks[i];
        const derivedCommandType = derivedCommandTypes[i];
        const derivedCommandName = derivedCommandNames[i];
        let derivedCommand = derivedCommandsObject[derivedCommandName];

        let derivedUniformMap;
        let derivedShaderProgram;
        let derivedRenderState;

        if (defined(derivedCommand)) {
          derivedUniformMap = derivedCommand.uniformMap;
          derivedShaderProgram = derivedCommand.shaderProgram;
          derivedRenderState = derivedCommand.renderState;
        } else {
          derivedUniformMap = undefined;
          derivedShaderProgram = undefined;
          derivedRenderState = undefined;
        }

        derivedCommand = DrawCommand.shallowClone(command, derivedCommand);
        derivedCommandsObject[derivedCommandName] = derivedCommand;

        const derivedUniformMapDirtyFrame = defaultValue(
          derivedCommand.derivedCommands.uniformMapDirtyFrame,
          0
        );
        const derivedShaderProgramDirtyFrame = defaultValue(
          derivedCommand.derivedCommands.shaderProgramDirtyFrame,
          0
        );
        const derivedRenderStateDirtyFrame = defaultValue(
          derivedCommand.derivedCommands.renderStateDirtyFrame,
          0
        );

        const derivedUniformMapDirty =
          uniformMapDirty || derivedUniformMapDirtyFrame < uniformMapDirtyFrame;
        const derivedShaderProgramDirty =
          shaderProgramDirty ||
          derivedShaderProgramDirtyFrame < shaderProgramDirtyFrame;
        const derivedRenderStateDirty =
          renderStateDirty ||
          derivedRenderStateDirtyFrame < renderStateDirtyFrame;

        if (derivedUniformMapDirty) {
          derivedCommand.derivedCommands.uniformMapDirtyFrame = frameNumber;
        }
        if (derivedShaderProgramDirty) {
          derivedCommand.derivedCommands.shaderProgramDirtyFrame = frameNumber;
        }
        if (derivedRenderStateDirty) {
          derivedCommand.derivedCommands.renderStateDirtyFrame = frameNumber;
        }

        derivedCommand.derivedCommands.type = derivedCommandType;
        derivedCommand.pass = derivedCommandPack.pass;
        derivedCommand.pickOnly = derivedCommandPack.pickOnly;
        derivedCommand.uniformMap = getDerivedUniformMap(
          state,
          command.uniformMap,
          derivedUniformMap,
          derivedUniformMapDirty,
          derivedCommandPack.getUniformMapFunction
        );
        derivedCommand.shaderProgram = getDerivedShaderProgram(
          frameState.context,
          command.shaderProgram,
          derivedShaderProgram,
          derivedShaderProgramDirty,
          derivedCommandPack.getShaderProgramFunction,
          derivedCommandName
        );
        derivedCommand.renderState = getDerivedRenderState(
          command.renderState,
          derivedRenderState,
          derivedRenderStateDirty,
          derivedCommandPack.getRenderStateFunction,
          derivedCommandPack.renderStateCache
        );
      }
    }
  }

  GlobeTranslucencyState.prototype.pushDerivedCommands = function (
    command,
    isBlendCommand,
    frameState
  ) {
    const picking = frameState.passes.pick;
    if (picking && isBlendCommand) {
      // No need to push blend commands in the pick pass
      return;
    }

    let derivedCommandTypes = this._derivedCommandTypes;
    let derivedCommandsLength = this._derivedCommandsLength;

    if (picking) {
      derivedCommandTypes = this._derivedPickCommandTypes;
      derivedCommandsLength = this._derivedPickCommandsLength;
    } else if (isBlendCommand) {
      derivedCommandTypes = this._derivedBlendCommandTypes;
      derivedCommandsLength = this._derivedBlendCommandsLength;
    }

    if (derivedCommandsLength === 0) {
      // No derived commands to push so just push the globe command
      frameState.commandList.push(command);
      return;
    }

    // Push derived commands
    const derivedCommands = command.derivedCommands.globeTranslucency;
    for (let i = 0; i < derivedCommandsLength; ++i) {
      const derivedCommandName = DerivedCommandNames[derivedCommandTypes[i]];
      frameState.commandList.push(derivedCommands[derivedCommandName]);
    }
  };

  function executeCommandsMatchingType(
    commands,
    commandsLength,
    executeCommandFunction,
    scene,
    context,
    passState,
    types
  ) {
    for (let i = 0; i < commandsLength; ++i) {
      const command = commands[i];
      const type = command.derivedCommands.type;
      if (!defined(types) || types.indexOf(type) > -1) {
        executeCommandFunction(command, scene, context, passState);
      }
    }
  }

  function executeCommands$1(
    commands,
    commandsLength,
    executeCommandFunction,
    scene,
    context,
    passState
  ) {
    for (let i = 0; i < commandsLength; ++i) {
      executeCommandFunction(commands[i], scene, context, passState);
    }
  }

  const opaqueTypes = [
    DerivedCommandType.OPAQUE_FRONT_FACE,
    DerivedCommandType.OPAQUE_BACK_FACE,
  ];
  const depthOnlyTypes = [
    DerivedCommandType.DEPTH_ONLY_FRONT_FACE,
    DerivedCommandType.DEPTH_ONLY_BACK_FACE,
    DerivedCommandType.DEPTH_ONLY_FRONT_AND_BACK_FACE,
  ];

  GlobeTranslucencyState.prototype.executeGlobeCommands = function (
    frustumCommands,
    executeCommandFunction,
    globeTranslucencyFramebuffer,
    scene,
    passState
  ) {
    const context = scene.context;
    const globeCommands = frustumCommands.commands[Pass$1.GLOBE];
    const globeCommandsLength = frustumCommands.indices[Pass$1.GLOBE];

    if (globeCommandsLength === 0) {
      return;
    }

    this._globeTranslucencyFramebuffer = globeTranslucencyFramebuffer;
    globeTranslucencyFramebuffer.clearClassification(context, passState);

    // Render opaque commands like normal
    executeCommandsMatchingType(
      globeCommands,
      globeCommandsLength,
      executeCommandFunction,
      scene,
      context,
      passState,
      opaqueTypes
    );
  };

  GlobeTranslucencyState.prototype.executeGlobeClassificationCommands = function (
    frustumCommands,
    executeCommandFunction,
    globeTranslucencyFramebuffer,
    scene,
    passState
  ) {
    const context = scene.context;
    const globeCommands = frustumCommands.commands[Pass$1.GLOBE];
    const globeCommandsLength = frustumCommands.indices[Pass$1.GLOBE];
    const classificationCommands =
      frustumCommands.commands[Pass$1.TERRAIN_CLASSIFICATION];
    const classificationCommandsLength =
      frustumCommands.indices[Pass$1.TERRAIN_CLASSIFICATION];

    if (globeCommandsLength === 0 || classificationCommandsLength === 0) {
      return;
    }

    const frontTranslucent = this._frontFaceTranslucent;
    const backTranslucent = this._backFaceTranslucent;

    if (!frontTranslucent || !backTranslucent) {
      // Render classification on opaque faces like normal
      executeCommands$1(
        classificationCommands,
        classificationCommandsLength,
        executeCommandFunction,
        scene,
        context,
        passState
      );
    }

    if (!frontTranslucent && !backTranslucent) {
      // No translucent commands to render. Skip translucent classification.
      return;
    }

    this._globeTranslucencyFramebuffer = globeTranslucencyFramebuffer;

    const originalGlobeDepthTexture = context.uniformState.globeDepthTexture;
    const originalFramebuffer = passState.framebuffer;

    // Render to internal framebuffer and get the first depth peel
    passState.framebuffer =
      globeTranslucencyFramebuffer.classificationFramebuffer;

    executeCommandsMatchingType(
      globeCommands,
      globeCommandsLength,
      executeCommandFunction,
      scene,
      context,
      passState,
      depthOnlyTypes
    );

    if (context.depthTexture) {
      // Pack depth into separate texture for ground polylines and textured ground primitives
      const packedDepthTexture = globeTranslucencyFramebuffer.packDepth(
        context,
        passState
      );
      context.uniformState.globeDepthTexture = packedDepthTexture;
    }

    // Render classification on translucent faces
    executeCommands$1(
      classificationCommands,
      classificationCommandsLength,
      executeCommandFunction,
      scene,
      context,
      passState
    );

    // Unset temporary state
    context.uniformState.globeDepthTexture = originalGlobeDepthTexture;
    passState.framebuffer = originalFramebuffer;
  };

  /**
   * @private
   */
  function GoogleEarthEnterpriseDiscardPolicy() {
    this._image = new Image();
  }

  /**
   * Determines if the discard policy is ready to process images.
   * @returns {Boolean} True if the discard policy is ready to process images; otherwise, false.
   */
  GoogleEarthEnterpriseDiscardPolicy.prototype.isReady = function () {
    return true;
  };

  /**
   * Given a tile image, decide whether to discard that image.
   *
   * @param {HTMLImageElement} image An image to test.
   * @returns {Boolean} True if the image should be discarded; otherwise, false.
   */
  GoogleEarthEnterpriseDiscardPolicy.prototype.shouldDiscardImage = function (
    image
  ) {
    return image === this._image;
  };

  /**
   * @typedef {Object} GoogleEarthEnterpriseImageryProvider.ConstructorOptions
   *
   * Initialization options for the GoogleEarthEnterpriseImageryProvider constructor
   *
   * @property {Resource|String} url The url of the Google Earth Enterprise server hosting the imagery.
   * @property {GoogleEarthEnterpriseMetadata} metadata A metadata object that can be used to share metadata requests with a GoogleEarthEnterpriseTerrainProvider.
   * @property {Ellipsoid} [ellipsoid] The ellipsoid.  If not specified, the WGS84 ellipsoid is used.
   * @property {TileDiscardPolicy} [tileDiscardPolicy] The policy that determines if a tile
   *        is invalid and should be discarded. If this value is not specified, a default
   *        is to discard tiles that fail to download.
   * @property {Credit|String} [credit] A credit for the data source, which is displayed on the canvas.
   */

  /**
   * Provides tiled imagery using the Google Earth Enterprise REST API.
   *
   * Notes: This provider is for use with the 3D Earth API of Google Earth Enterprise,
   *        {@link GoogleEarthEnterpriseMapsProvider} should be used with 2D Maps API.
   *
   * @alias GoogleEarthEnterpriseImageryProvider
   * @constructor
   *
   * @param {GoogleEarthEnterpriseImageryProvider.ConstructorOptions} options Object describing initialization options
   *
   * @see GoogleEarthEnterpriseTerrainProvider
   * @see ArcGisMapServerImageryProvider
   * @see GoogleEarthEnterpriseMapsProvider
   * @see OpenStreetMapImageryProvider
   * @see SingleTileImageryProvider
   * @see TileMapServiceImageryProvider
   * @see WebMapServiceImageryProvider
   * @see WebMapTileServiceImageryProvider
   * @see UrlTemplateImageryProvider
   *
   *
   * @example
   * const geeMetadata = new GoogleEarthEnterpriseMetadata('http://www.example.com');
   * const gee = new Cesium.GoogleEarthEnterpriseImageryProvider({
   *     metadata : geeMetadata
   * });
   *
   * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
   */
  function GoogleEarthEnterpriseImageryProvider(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    if (!(defined(options.url) || defined(options.metadata))) {
      throw new DeveloperError("options.url or options.metadata is required.");
    }
    //>>includeEnd('debug');

    /**
     * The default alpha blending value of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultAlpha = undefined;

    /**
     * The default alpha blending value on the night side of the globe of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultNightAlpha = undefined;

    /**
     * The default alpha blending value on the day side of the globe of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultDayAlpha = undefined;

    /**
     * The default brightness of this provider.  1.0 uses the unmodified imagery color.  Less than 1.0
     * makes the imagery darker while greater than 1.0 makes it brighter.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultBrightness = undefined;

    /**
     * The default contrast of this provider.  1.0 uses the unmodified imagery color.  Less than 1.0 reduces
     * the contrast while greater than 1.0 increases it.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultContrast = undefined;

    /**
     * The default hue of this provider in radians. 0.0 uses the unmodified imagery color.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultHue = undefined;

    /**
     * The default saturation of this provider. 1.0 uses the unmodified imagery color. Less than 1.0 reduces the
     * saturation while greater than 1.0 increases it.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultSaturation = undefined;

    /**
     * The default gamma correction to apply to this provider.  1.0 uses the unmodified imagery color.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultGamma = undefined;

    /**
     * The default texture minification filter to apply to this provider.
     *
     * @type {TextureMinificationFilter}
     * @default undefined
     */
    this.defaultMinificationFilter = undefined;

    /**
     * The default texture magnification filter to apply to this provider.
     *
     * @type {TextureMagnificationFilter}
     * @default undefined
     */
    this.defaultMagnificationFilter = undefined;

    let metadata;
    if (defined(options.metadata)) {
      metadata = options.metadata;
    } else {
      const resource = Resource.createIfNeeded(options.url);
      metadata = new GoogleEarthEnterpriseMetadata(resource);
    }
    this._metadata = metadata;
    this._tileDiscardPolicy = options.tileDiscardPolicy;

    this._tilingScheme = new GeographicTilingScheme({
      numberOfLevelZeroTilesX: 2,
      numberOfLevelZeroTilesY: 2,
      rectangle: new Rectangle(
        -CesiumMath.PI,
        -CesiumMath.PI,
        CesiumMath.PI,
        CesiumMath.PI
      ),
      ellipsoid: options.ellipsoid,
    });

    let credit = options.credit;
    if (typeof credit === "string") {
      credit = new Credit(credit);
    }
    this._credit = credit;

    this._tileWidth = 256;
    this._tileHeight = 256;
    this._maximumLevel = 23;

    // Install the default tile discard policy if none has been supplied.
    if (!defined(this._tileDiscardPolicy)) {
      this._tileDiscardPolicy = new GoogleEarthEnterpriseDiscardPolicy();
    }

    this._errorEvent = new Event();

    this._ready = false;
    const that = this;
    let metadataError;
    this._readyPromise = metadata.readyPromise
      .then(function (result) {
        if (!metadata.imageryPresent) {
          const e = new RuntimeError(
            `The server ${metadata.url} doesn't have imagery`
          );
          metadataError = TileProviderError.handleError(
            metadataError,
            that,
            that._errorEvent,
            e.message,
            undefined,
            undefined,
            undefined,
            e
          );
          return Promise.reject(e);
        }

        TileProviderError.handleSuccess(metadataError);
        that._ready = result;
        return result;
      })
      .catch(function (e) {
        metadataError = TileProviderError.handleError(
          metadataError,
          that,
          that._errorEvent,
          e.message,
          undefined,
          undefined,
          undefined,
          e
        );
        return Promise.reject(e);
      });
  }

  Object.defineProperties(GoogleEarthEnterpriseImageryProvider.prototype, {
    /**
     * Gets the name of the Google Earth Enterprise server url hosting the imagery.
     * @memberof GoogleEarthEnterpriseImageryProvider.prototype
     * @type {String}
     * @readonly
     */
    url: {
      get: function () {
        return this._metadata.url;
      },
    },

    /**
     * Gets the proxy used by this provider.
     * @memberof GoogleEarthEnterpriseImageryProvider.prototype
     * @type {Proxy}
     * @readonly
     */
    proxy: {
      get: function () {
        return this._metadata.proxy;
      },
    },

    /**
     * Gets the width of each tile, in pixels. This function should
     * not be called before {@link GoogleEarthEnterpriseImageryProvider#ready} returns true.
     * @memberof GoogleEarthEnterpriseImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    tileWidth: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "tileWidth must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._tileWidth;
      },
    },

    /**
     * Gets the height of each tile, in pixels.  This function should
     * not be called before {@link GoogleEarthEnterpriseImageryProvider#ready} returns true.
     * @memberof GoogleEarthEnterpriseImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    tileHeight: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "tileHeight must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._tileHeight;
      },
    },

    /**
     * Gets the maximum level-of-detail that can be requested.  This function should
     * not be called before {@link GoogleEarthEnterpriseImageryProvider#ready} returns true.
     * @memberof GoogleEarthEnterpriseImageryProvider.prototype
     * @type {Number|undefined}
     * @readonly
     */
    maximumLevel: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "maximumLevel must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._maximumLevel;
      },
    },

    /**
     * Gets the minimum level-of-detail that can be requested.  This function should
     * not be called before {@link GoogleEarthEnterpriseImageryProvider#ready} returns true.
     * @memberof GoogleEarthEnterpriseImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    minimumLevel: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "minimumLevel must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return 0;
      },
    },

    /**
     * Gets the tiling scheme used by this provider.  This function should
     * not be called before {@link GoogleEarthEnterpriseImageryProvider#ready} returns true.
     * @memberof GoogleEarthEnterpriseImageryProvider.prototype
     * @type {TilingScheme}
     * @readonly
     */
    tilingScheme: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "tilingScheme must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._tilingScheme;
      },
    },

    /**
     * Gets the rectangle, in radians, of the imagery provided by this instance.  This function should
     * not be called before {@link GoogleEarthEnterpriseImageryProvider#ready} returns true.
     * @memberof GoogleEarthEnterpriseImageryProvider.prototype
     * @type {Rectangle}
     * @readonly
     */
    rectangle: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "rectangle must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._tilingScheme.rectangle;
      },
    },

    /**
     * Gets the tile discard policy.  If not undefined, the discard policy is responsible
     * for filtering out "missing" tiles via its shouldDiscardImage function.  If this function
     * returns undefined, no tiles are filtered.  This function should
     * not be called before {@link GoogleEarthEnterpriseImageryProvider#ready} returns true.
     * @memberof GoogleEarthEnterpriseImageryProvider.prototype
     * @type {TileDiscardPolicy}
     * @readonly
     */
    tileDiscardPolicy: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "tileDiscardPolicy must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._tileDiscardPolicy;
      },
    },

    /**
     * Gets an event that is raised when the imagery provider encounters an asynchronous error.  By subscribing
     * to the event, you will be notified of the error and can potentially recover from it.  Event listeners
     * are passed an instance of {@link TileProviderError}.
     * @memberof GoogleEarthEnterpriseImageryProvider.prototype
     * @type {Event}
     * @readonly
     */
    errorEvent: {
      get: function () {
        return this._errorEvent;
      },
    },

    /**
     * Gets a value indicating whether or not the provider is ready for use.
     * @memberof GoogleEarthEnterpriseImageryProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    ready: {
      get: function () {
        return this._ready;
      },
    },

    /**
     * Gets a promise that resolves to true when the provider is ready for use.
     * @memberof GoogleEarthEnterpriseImageryProvider.prototype
     * @type {Promise.<Boolean>}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._readyPromise;
      },
    },

    /**
     * Gets the credit to display when this imagery provider is active.  Typically this is used to credit
     * the source of the imagery.  This function should not be called before {@link GoogleEarthEnterpriseImageryProvider#ready} returns true.
     * @memberof GoogleEarthEnterpriseImageryProvider.prototype
     * @type {Credit}
     * @readonly
     */
    credit: {
      get: function () {
        return this._credit;
      },
    },

    /**
     * Gets a value indicating whether or not the images provided by this imagery provider
     * include an alpha channel.  If this property is false, an alpha channel, if present, will
     * be ignored.  If this property is true, any images without an alpha channel will be treated
     * as if their alpha is 1.0 everywhere.  Setting this property to false reduces memory usage
     * and texture upload time.
     * @memberof GoogleEarthEnterpriseImageryProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    hasAlphaChannel: {
      get: function () {
        return false;
      },
    },
  });

  /**
   * Gets the credits to be displayed when a given tile is displayed.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level;
   * @returns {Credit[]} The credits to be displayed when the tile is displayed.
   *
   * @exception {DeveloperError} <code>getTileCredits</code> must not be called before the imagery provider is ready.
   */
  GoogleEarthEnterpriseImageryProvider.prototype.getTileCredits = function (
    x,
    y,
    level
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!this._ready) {
      throw new DeveloperError(
        "getTileCredits must not be called before the imagery provider is ready."
      );
    }
    //>>includeEnd('debug');

    const metadata = this._metadata;
    const info = metadata.getTileInformation(x, y, level);
    if (defined(info)) {
      const credit = metadata.providers[info.imageryProvider];
      if (defined(credit)) {
        return [credit];
      }
    }

    return undefined;
  };

  /**
   * Requests the image for a given tile.  This function should
   * not be called before {@link GoogleEarthEnterpriseImageryProvider#ready} returns true.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level.
   * @param {Request} [request] The request object. Intended for internal use only.
   * @returns {Promise.<ImageryTypes>|undefined} A promise for the image that will resolve when the image is available, or
   *          undefined if there are too many active requests to the server, and the request should be retried later.
   *
   * @exception {DeveloperError} <code>requestImage</code> must not be called before the imagery provider is ready.
   */
  GoogleEarthEnterpriseImageryProvider.prototype.requestImage = function (
    x,
    y,
    level,
    request
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!this._ready) {
      throw new DeveloperError(
        "requestImage must not be called before the imagery provider is ready."
      );
    }
    //>>includeEnd('debug');

    const invalidImage = this._tileDiscardPolicy._image; // Empty image or undefined depending on discard policy
    const metadata = this._metadata;
    const quadKey = GoogleEarthEnterpriseMetadata.tileXYToQuadKey(x, y, level);
    const info = metadata.getTileInformation(x, y, level);
    if (!defined(info)) {
      if (metadata.isValid(quadKey)) {
        const metadataRequest = new Request({
          throttle: request.throttle,
          throttleByServer: request.throttleByServer,
          type: request.type,
          priorityFunction: request.priorityFunction,
        });
        metadata.populateSubtree(x, y, level, metadataRequest);
        return undefined; // No metadata so return undefined so we can be loaded later
      }
      return Promise.resolve(invalidImage); // Image doesn't exist
    }

    if (!info.hasImagery()) {
      // Already have info and there isn't any imagery here
      return Promise.resolve(invalidImage);
    }
    const promise = buildImageResource$1(
      this,
      info,
      x,
      y,
      level,
      request
    ).fetchArrayBuffer();
    if (!defined(promise)) {
      return undefined; // Throttled
    }

    return promise.then(function (image) {
      decodeGoogleEarthEnterpriseData(metadata.key, image);
      let a = new Uint8Array(image);
      let type;

      const protoImagery = metadata.protoImagery;
      if (!defined(protoImagery) || !protoImagery) {
        type = getImageType(a);
      }

      if (!defined(type) && (!defined(protoImagery) || protoImagery)) {
        const message = decodeEarthImageryPacket(a);
        type = message.imageType;
        a = message.imageData;
      }

      if (!defined(type) || !defined(a)) {
        return invalidImage;
      }

      return loadImageFromTypedArray({
        uint8Array: a,
        format: type,
        flipY: true,
      });
    });
  };

  /**
   * Picking features is not currently supported by this imagery provider, so this function simply returns
   * undefined.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level.
   * @param {Number} longitude The longitude at which to pick features.
   * @param {Number} latitude  The latitude at which to pick features.
   * @return {undefined} Undefined since picking is not supported.
   */
  GoogleEarthEnterpriseImageryProvider.prototype.pickFeatures = function (
    x,
    y,
    level,
    longitude,
    latitude
  ) {
    return undefined;
  };

  //
  // Functions to handle imagery packets
  //
  function buildImageResource$1(imageryProvider, info, x, y, level, request) {
    const quadKey = GoogleEarthEnterpriseMetadata.tileXYToQuadKey(x, y, level);
    let version = info.imageryVersion;
    version = defined(version) && version > 0 ? version : 1;

    return imageryProvider._metadata.resource.getDerivedResource({
      url: `flatfile?f1-0${quadKey}-i.${version.toString()}`,
      request: request,
    });
  }

  // Detects if a Uint8Array is a JPEG or PNG
  function getImageType(image) {
    const jpeg = "JFIF";
    if (
      image[6] === jpeg.charCodeAt(0) &&
      image[7] === jpeg.charCodeAt(1) &&
      image[8] === jpeg.charCodeAt(2) &&
      image[9] === jpeg.charCodeAt(3)
    ) {
      return "image/jpeg";
    }

    const png = "PNG";
    if (
      image[1] === png.charCodeAt(0) &&
      image[2] === png.charCodeAt(1) &&
      image[3] === png.charCodeAt(2)
    ) {
      return "image/png";
    }

    return undefined;
  }

  // Decodes an Imagery protobuf into the message
  // Partially generated with the help of protobuf.js static generator
  function decodeEarthImageryPacket(data) {
    const reader = protobuf$1.Reader.create(data);
    const end = reader.len;
    const message = {};
    while (reader.pos < end) {
      const tag = reader.uint32();
      let copyrightIds;
      switch (tag >>> 3) {
        case 1:
          message.imageType = reader.uint32();
          break;
        case 2:
          message.imageData = reader.bytes();
          break;
        case 3:
          message.alphaType = reader.uint32();
          break;
        case 4:
          message.imageAlpha = reader.bytes();
          break;
        case 5:
          copyrightIds = message.copyrightIds;
          if (!defined(copyrightIds)) {
            copyrightIds = message.copyrightIds = [];
          }
          if ((tag & 7) === 2) {
            const end2 = reader.uint32() + reader.pos;
            while (reader.pos < end2) {
              copyrightIds.push(reader.uint32());
            }
          } else {
            copyrightIds.push(reader.uint32());
          }
          break;
        default:
          reader.skipType(tag & 7);
          break;
      }
    }

    const imageType = message.imageType;
    if (defined(imageType)) {
      switch (imageType) {
        case 0:
          message.imageType = "image/jpeg";
          break;
        case 4:
          message.imageType = "image/png";
          break;
        default:
          throw new RuntimeError(
            "GoogleEarthEnterpriseImageryProvider: Unsupported image type."
          );
      }
    }

    const alphaType = message.alphaType;
    if (defined(alphaType) && alphaType !== 0) {
      console.log(
        "GoogleEarthEnterpriseImageryProvider: External alpha not supported."
      );
      delete message.alphaType;
      delete message.imageAlpha;
    }

    return message;
  }

  /**
   * @typedef {Object} GoogleEarthEnterpriseMapsProvider.ConstructorOptions
   *
   * Initialization options for the GoogleEarthEnterpriseMapsProvider constructor
   *
   * @property {Resource|String} url The url of the Google Earth server hosting the imagery.
   * @property {Number} channel The channel (id) to be used when requesting data from the server.
   *        The channel number can be found by looking at the json file located at:
   *        earth.localdomain/default_map/query?request=Json&vars=geeServerDefs The /default_map path may
   *        differ depending on your Google Earth Enterprise server configuration. Look for the "id" that
   *        is associated with a "ImageryMaps" requestType. There may be more than one id available.
   *        Example:
   *        {
   *          layers: [
   *            {
   *              id: 1002,
   *              requestType: "ImageryMaps"
   *            },
   *            {
   *              id: 1007,
   *              requestType: "VectorMapsRaster"
   *            }
   *          ]
   *        }
   * @property {String} [path="/default_map"] The path of the Google Earth server hosting the imagery.
   * @property {Number} [maximumLevel] The maximum level-of-detail supported by the Google Earth
   *        Enterprise server, or undefined if there is no limit.
   * @property {TileDiscardPolicy} [tileDiscardPolicy] The policy that determines if a tile
   *        is invalid and should be discarded. To ensure that no tiles are discarded, construct and pass
   *        a {@link NeverTileDiscardPolicy} for this parameter.
   * @property {Ellipsoid} [ellipsoid] The ellipsoid.  If not specified, the WGS84 ellipsoid is used.
   */

  /**
   * Provides tiled imagery using the Google Earth Imagery API.
   *
   * Notes: This imagery provider does not work with the public Google Earth servers. It works with the
   *        Google Earth Enterprise Server.
   *
   *        By default the Google Earth Enterprise server does not set the
   *        {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing} headers. You can either
   *        use a proxy server which adds these headers, or in the /opt/google/gehttpd/conf/gehttpd.conf
   *        and add the 'Header set Access-Control-Allow-Origin "*"' option to the '&lt;Directory /&gt;' and
   *        '&lt;Directory "/opt/google/gehttpd/htdocs"&gt;' directives.
   *
   *        This provider is for use with 2D Maps API as part of Google Earth Enterprise. For 3D Earth API uses, it
   *        is necessary to use {@link GoogleEarthEnterpriseImageryProvider}
   *
   * @alias GoogleEarthEnterpriseMapsProvider
   * @constructor
   *
   * @param {GoogleEarthEnterpriseMapsProvider.ConstructorOptions} options Object describing initialization options
   *
   * @exception {RuntimeError} Could not find layer with channel (id) of <code>options.channel</code>.
   * @exception {RuntimeError} Could not find a version in channel (id) <code>options.channel</code>.
   * @exception {RuntimeError} Unsupported projection <code>data.projection</code>.
   *
   * @see ArcGisMapServerImageryProvider
   * @see BingMapsImageryProvider
   * @see OpenStreetMapImageryProvider
   * @see SingleTileImageryProvider
   * @see TileMapServiceImageryProvider
   * @see WebMapServiceImageryProvider
   * @see WebMapTileServiceImageryProvider
   * @see UrlTemplateImageryProvider
   *
   *
   * @example
   * const google = new Cesium.GoogleEarthEnterpriseMapsProvider({
   *     url : 'https://earth.localdomain',
   *     channel : 1008
   * });
   *
   * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
   */
  function GoogleEarthEnterpriseMapsProvider(options) {
    options = defaultValue(options, {});

    //>>includeStart('debug', pragmas.debug);
    if (!defined(options.url)) {
      throw new DeveloperError("options.url is required.");
    }
    if (!defined(options.channel)) {
      throw new DeveloperError("options.channel is required.");
    }
    //>>includeEnd('debug');

    /**
     * The default alpha blending value of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultAlpha = undefined;

    /**
     * The default alpha blending value on the night side of the globe of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultNightAlpha = undefined;

    /**
     * The default alpha blending value on the day side of the globe of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultDayAlpha = undefined;

    /**
     * The default brightness of this provider.  1.0 uses the unmodified imagery color.  Less than 1.0
     * makes the imagery darker while greater than 1.0 makes it brighter.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultBrightness = undefined;

    /**
     * The default contrast of this provider.  1.0 uses the unmodified imagery color.  Less than 1.0 reduces
     * the contrast while greater than 1.0 increases it.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultContrast = undefined;

    /**
     * The default hue of this provider in radians. 0.0 uses the unmodified imagery color.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultHue = undefined;

    /**
     * The default saturation of this provider. 1.0 uses the unmodified imagery color. Less than 1.0 reduces the
     * saturation while greater than 1.0 increases it.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultSaturation = undefined;

    /**
     * The default gamma correction to apply to this provider.  1.0 uses the unmodified imagery color.
     *
     * @type {Number|undefined}
     * @default 1.9
     */
    this.defaultGamma = 1.9;

    /**
     * The default texture minification filter to apply to this provider.
     *
     * @type {TextureMinificationFilter}
     * @default undefined
     */
    this.defaultMinificationFilter = undefined;

    /**
     * The default texture magnification filter to apply to this provider.
     *
     * @type {TextureMagnificationFilter}
     * @default undefined
     */
    this.defaultMagnificationFilter = undefined;

    const url = options.url;
    const path = defaultValue(options.path, "/default_map");

    const resource = Resource.createIfNeeded(url).getDerivedResource({
      // We used to just append path to url, so now that we do proper URI resolution, removed the /
      url: path[0] === "/" ? path.substring(1) : path,
    });

    resource.appendForwardSlash();

    this._resource = resource;
    this._url = url;
    this._path = path;
    this._tileDiscardPolicy = options.tileDiscardPolicy;
    this._channel = options.channel;
    this._requestType = "ImageryMaps";
    this._credit = new Credit(
      `<a href="http://www.google.com/enterprise/mapsearth/products/earthenterprise.html"><img src="${GoogleEarthEnterpriseMapsProvider.logoUrl}" title="Google Imagery"/></a>`
    );

    this._tilingScheme = undefined;

    this._version = undefined;

    this._tileWidth = 256;
    this._tileHeight = 256;
    this._maximumLevel = options.maximumLevel;

    this._errorEvent = new Event();

    this._ready = false;
    this._readyPromise = defer();

    const metadataResource = resource.getDerivedResource({
      url: "query",
      queryParameters: {
        request: "Json",
        vars: "geeServerDefs",
        is2d: "t",
      },
    });
    const that = this;
    let metadataError;

    function metadataSuccess(text) {
      let data;

      // The Google Earth server sends malformed JSON data currently...
      try {
        // First, try parsing it like normal in case a future version sends correctly formatted JSON
        data = JSON.parse(text);
      } catch (e) {
        // Quote object strings manually, then try parsing again
        data = JSON.parse(
          text.replace(/([\[\{,])[\n\r ]*([A-Za-z0-9]+)[\n\r ]*:/g, '$1"$2":')
        );
      }

      let layer;
      for (let i = 0; i < data.layers.length; i++) {
        if (data.layers[i].id === that._channel) {
          layer = data.layers[i];
          break;
        }
      }

      let message;

      if (!defined(layer)) {
        message = `Could not find layer with channel (id) of ${that._channel}.`;
        metadataError = TileProviderError.handleError(
          metadataError,
          that,
          that._errorEvent,
          message,
          undefined,
          undefined,
          undefined,
          requestMetadata
        );
        throw new RuntimeError(message);
      }

      if (!defined(layer.version)) {
        message = `Could not find a version in channel (id) ${that._channel}.`;
        metadataError = TileProviderError.handleError(
          metadataError,
          that,
          that._errorEvent,
          message,
          undefined,
          undefined,
          undefined,
          requestMetadata
        );
        throw new RuntimeError(message);
      }
      that._version = layer.version;

      if (defined(data.projection) && data.projection === "flat") {
        that._tilingScheme = new GeographicTilingScheme({
          numberOfLevelZeroTilesX: 2,
          numberOfLevelZeroTilesY: 2,
          rectangle: new Rectangle(-Math.PI, -Math.PI, Math.PI, Math.PI),
          ellipsoid: options.ellipsoid,
        });
        // Default to mercator projection when projection is undefined
      } else if (!defined(data.projection) || data.projection === "mercator") {
        that._tilingScheme = new WebMercatorTilingScheme({
          numberOfLevelZeroTilesX: 2,
          numberOfLevelZeroTilesY: 2,
          ellipsoid: options.ellipsoid,
        });
      } else {
        message = `Unsupported projection ${data.projection}.`;
        metadataError = TileProviderError.handleError(
          metadataError,
          that,
          that._errorEvent,
          message,
          undefined,
          undefined,
          undefined,
          requestMetadata
        );
        throw new RuntimeError(message);
      }

      that._ready = true;
      that._readyPromise.resolve(true);
      TileProviderError.handleSuccess(metadataError);
    }

    function metadataFailure(e) {
      const message = defaultValue(
        e.message,
        `An error occurred while accessing ${metadataResource.url}.`
      );
      metadataError = TileProviderError.handleError(
        metadataError,
        that,
        that._errorEvent,
        message,
        undefined,
        undefined,
        undefined,
        requestMetadata
      );
      that._readyPromise.reject(new RuntimeError(message));
    }

    function requestMetadata() {
      metadataResource
        .fetchText()
        .then(function (text) {
          metadataSuccess(text);
        })
        .catch(function (e) {
          metadataFailure(e);
        });
    }

    requestMetadata();
  }

  Object.defineProperties(GoogleEarthEnterpriseMapsProvider.prototype, {
    /**
     * Gets the URL of the Google Earth MapServer.
     * @memberof GoogleEarthEnterpriseMapsProvider.prototype
     * @type {String}
     * @readonly
     */
    url: {
      get: function () {
        return this._url;
      },
    },

    /**
     * Gets the url path of the data on the Google Earth server.
     * @memberof GoogleEarthEnterpriseMapsProvider.prototype
     * @type {String}
     * @readonly
     */
    path: {
      get: function () {
        return this._path;
      },
    },

    /**
     * Gets the proxy used by this provider.
     * @memberof GoogleEarthEnterpriseMapsProvider.prototype
     * @type {Proxy}
     * @readonly
     */
    proxy: {
      get: function () {
        return this._resource.proxy;
      },
    },

    /**
     * Gets the imagery channel (id) currently being used.
     * @memberof GoogleEarthEnterpriseMapsProvider.prototype
     * @type {Number}
     * @readonly
     */
    channel: {
      get: function () {
        return this._channel;
      },
    },

    /**
     * Gets the width of each tile, in pixels. This function should
     * not be called before {@link GoogleEarthEnterpriseMapsProvider#ready} returns true.
     * @memberof GoogleEarthEnterpriseMapsProvider.prototype
     * @type {Number}
     * @readonly
     */
    tileWidth: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "tileWidth must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._tileWidth;
      },
    },

    /**
     * Gets the height of each tile, in pixels.  This function should
     * not be called before {@link GoogleEarthEnterpriseMapsProvider#ready} returns true.
     * @memberof GoogleEarthEnterpriseMapsProvider.prototype
     * @type {Number}
     * @readonly
     */
    tileHeight: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "tileHeight must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._tileHeight;
      },
    },

    /**
     * Gets the maximum level-of-detail that can be requested.  This function should
     * not be called before {@link GoogleEarthEnterpriseMapsProvider#ready} returns true.
     * @memberof GoogleEarthEnterpriseMapsProvider.prototype
     * @type {Number|undefined}
     * @readonly
     */
    maximumLevel: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "maximumLevel must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._maximumLevel;
      },
    },

    /**
     * Gets the minimum level-of-detail that can be requested.  This function should
     * not be called before {@link GoogleEarthEnterpriseMapsProvider#ready} returns true.
     * @memberof GoogleEarthEnterpriseMapsProvider.prototype
     * @type {Number}
     * @readonly
     */
    minimumLevel: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "minimumLevel must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return 0;
      },
    },

    /**
     * Gets the tiling scheme used by this provider.  This function should
     * not be called before {@link GoogleEarthEnterpriseMapsProvider#ready} returns true.
     * @memberof GoogleEarthEnterpriseMapsProvider.prototype
     * @type {TilingScheme}
     * @readonly
     */
    tilingScheme: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "tilingScheme must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._tilingScheme;
      },
    },

    /**
     * Gets the version of the data used by this provider.  This function should
     * not be called before {@link GoogleEarthEnterpriseMapsProvider#ready} returns true.
     * @memberof GoogleEarthEnterpriseMapsProvider.prototype
     * @type {Number}
     * @readonly
     */
    version: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "version must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._version;
      },
    },

    /**
     * Gets the type of data that is being requested from the provider.  This function should
     * not be called before {@link GoogleEarthEnterpriseMapsProvider#ready} returns true.
     * @memberof GoogleEarthEnterpriseMapsProvider.prototype
     * @type {String}
     * @readonly
     */
    requestType: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "requestType must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._requestType;
      },
    },
    /**
     * Gets the rectangle, in radians, of the imagery provided by this instance.  This function should
     * not be called before {@link GoogleEarthEnterpriseMapsProvider#ready} returns true.
     * @memberof GoogleEarthEnterpriseMapsProvider.prototype
     * @type {Rectangle}
     * @readonly
     */
    rectangle: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "rectangle must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._tilingScheme.rectangle;
      },
    },

    /**
     * Gets the tile discard policy.  If not undefined, the discard policy is responsible
     * for filtering out "missing" tiles via its shouldDiscardImage function.  If this function
     * returns undefined, no tiles are filtered.  This function should
     * not be called before {@link GoogleEarthEnterpriseMapsProvider#ready} returns true.
     * @memberof GoogleEarthEnterpriseMapsProvider.prototype
     * @type {TileDiscardPolicy}
     * @readonly
     */
    tileDiscardPolicy: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "tileDiscardPolicy must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._tileDiscardPolicy;
      },
    },

    /**
     * Gets an event that is raised when the imagery provider encounters an asynchronous error.  By subscribing
     * to the event, you will be notified of the error and can potentially recover from it.  Event listeners
     * are passed an instance of {@link TileProviderError}.
     * @memberof GoogleEarthEnterpriseMapsProvider.prototype
     * @type {Event}
     * @readonly
     */
    errorEvent: {
      get: function () {
        return this._errorEvent;
      },
    },

    /**
     * Gets a value indicating whether or not the provider is ready for use.
     * @memberof GoogleEarthEnterpriseMapsProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    ready: {
      get: function () {
        return this._ready;
      },
    },

    /**
     * Gets a promise that resolves to true when the provider is ready for use.
     * @memberof GoogleEarthEnterpriseMapsProvider.prototype
     * @type {Promise.<Boolean>}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._readyPromise.promise;
      },
    },

    /**
     * Gets the credit to display when this imagery provider is active.  Typically this is used to credit
     * the source of the imagery.  This function should not be called before {@link GoogleEarthEnterpriseMapsProvider#ready} returns true.
     * @memberof GoogleEarthEnterpriseMapsProvider.prototype
     * @type {Credit}
     * @readonly
     */
    credit: {
      get: function () {
        return this._credit;
      },
    },

    /**
     * Gets a value indicating whether or not the images provided by this imagery provider
     * include an alpha channel.  If this property is false, an alpha channel, if present, will
     * be ignored.  If this property is true, any images without an alpha channel will be treated
     * as if their alpha is 1.0 everywhere.  When this property is false, memory usage
     * and texture upload time are reduced.
     * @memberof GoogleEarthEnterpriseMapsProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    hasAlphaChannel: {
      get: function () {
        return true;
      },
    },
  });

  /**
   * Gets the credits to be displayed when a given tile is displayed.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level;
   * @returns {Credit[]} The credits to be displayed when the tile is displayed.
   *
   * @exception {DeveloperError} <code>getTileCredits</code> must not be called before the imagery provider is ready.
   */
  GoogleEarthEnterpriseMapsProvider.prototype.getTileCredits = function (
    x,
    y,
    level
  ) {
    return undefined;
  };

  /**
   * Requests the image for a given tile.  This function should
   * not be called before {@link GoogleEarthEnterpriseMapsProvider#ready} returns true.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level.
   * @param {Request} [request] The request object. Intended for internal use only.
   * @returns {Promise.<ImageryTypes>|undefined} A promise for the image that will resolve when the image is available, or
   *          undefined if there are too many active requests to the server, and the request should be retried later.
   *
   * @exception {DeveloperError} <code>requestImage</code> must not be called before the imagery provider is ready.
   */
  GoogleEarthEnterpriseMapsProvider.prototype.requestImage = function (
    x,
    y,
    level,
    request
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!this._ready) {
      throw new DeveloperError(
        "requestImage must not be called before the imagery provider is ready."
      );
    }
    //>>includeEnd('debug');

    const resource = this._resource.getDerivedResource({
      url: "query",
      request: request,
      queryParameters: {
        request: this._requestType,
        channel: this._channel,
        version: this._version,
        x: x,
        y: y,
        z: level + 1, // Google Earth starts with a zoom level of 1, not 0
      },
    });

    return ImageryProvider.loadImage(this, resource);
  };

  /**
   * Picking features is not currently supported by this imagery provider, so this function simply returns
   * undefined.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level.
   * @param {Number} longitude The longitude at which to pick features.
   * @param {Number} latitude  The latitude at which to pick features.
   * @return {undefined} Undefined since picking is not supported.
   */
  GoogleEarthEnterpriseMapsProvider.prototype.pickFeatures = function (
    x,
    y,
    level,
    longitude,
    latitude
  ) {
    return undefined;
  };

  GoogleEarthEnterpriseMapsProvider._logoUrl = undefined;

  Object.defineProperties(GoogleEarthEnterpriseMapsProvider, {
    /**
     * Gets or sets the URL to the Google Earth logo for display in the credit.
     * @memberof GoogleEarthEnterpriseMapsProvider
     * @type {String}
     */
    logoUrl: {
      get: function () {
        if (!defined(GoogleEarthEnterpriseMapsProvider._logoUrl)) {
          GoogleEarthEnterpriseMapsProvider._logoUrl = buildModuleUrl(
            "Assets/Images/google_earth_credit.png"
          );
        }
        return GoogleEarthEnterpriseMapsProvider._logoUrl;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.defined("value", value);
        //>>includeEnd('debug');

        GoogleEarthEnterpriseMapsProvider._logoUrl = value;
      },
    },
  });

  const defaultColor = new Color(1.0, 1.0, 1.0, 0.4);
  const defaultGlowColor = new Color(0.0, 1.0, 0.0, 0.05);
  const defaultBackgroundColor = new Color(0.0, 0.5, 0.0, 0.2);

  /**
   * @typedef {Object} GridImageryProvider.ConstructorOptions
   *
   * Initialization options for the GridImageryProvider constructor
   *
   * @property {TilingScheme} [tilingScheme=new GeographicTilingScheme()] The tiling scheme for which to draw tiles.
   * @property {Ellipsoid} [ellipsoid] The ellipsoid.  If the tilingScheme is specified,
   *                    this parameter is ignored and the tiling scheme's ellipsoid is used instead. If neither
   *                    parameter is specified, the WGS84 ellipsoid is used.
   * @property {Number} [cells=8] The number of grids cells.
   * @property {Color} [color=Color(1.0, 1.0, 1.0, 0.4)] The color to draw grid lines.
   * @property {Color} [glowColor=Color(0.0, 1.0, 0.0, 0.05)] The color to draw glow for grid lines.
   * @property {Number} [glowWidth=6] The width of lines used for rendering the line glow effect.
   * @property {Color} [backgroundColor=Color(0.0, 0.5, 0.0, 0.2)] Background fill color.
   * @property {Number} [tileWidth=256] The width of the tile for level-of-detail selection purposes.
   * @property {Number} [tileHeight=256] The height of the tile for level-of-detail selection purposes.
   * @property {Number} [canvasSize=256] The size of the canvas used for rendering.
   */

  /**
   * An {@link ImageryProvider} that draws a wireframe grid on every tile with controllable background and glow.
   * May be useful for custom rendering effects or debugging terrain.
   *
   * @alias GridImageryProvider
   * @constructor
   * @param {GridImageryProvider.ConstructorOptions} options Object describing initialization options
   *
   */
  function GridImageryProvider(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    /**
     * The default alpha blending value of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultAlpha = undefined;

    /**
     * The default alpha blending value on the night side of the globe of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultNightAlpha = undefined;

    /**
     * The default alpha blending value on the day side of the globe of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultDayAlpha = undefined;

    /**
     * The default brightness of this provider.  1.0 uses the unmodified imagery color.  Less than 1.0
     * makes the imagery darker while greater than 1.0 makes it brighter.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultBrightness = undefined;

    /**
     * The default contrast of this provider.  1.0 uses the unmodified imagery color.  Less than 1.0 reduces
     * the contrast while greater than 1.0 increases it.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultContrast = undefined;

    /**
     * The default hue of this provider in radians. 0.0 uses the unmodified imagery color.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultHue = undefined;

    /**
     * The default saturation of this provider. 1.0 uses the unmodified imagery color. Less than 1.0 reduces the
     * saturation while greater than 1.0 increases it.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultSaturation = undefined;

    /**
     * The default gamma correction to apply to this provider.  1.0 uses the unmodified imagery color.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultGamma = undefined;

    /**
     * The default texture minification filter to apply to this provider.
     *
     * @type {TextureMinificationFilter}
     * @default undefined
     */
    this.defaultMinificationFilter = undefined;

    /**
     * The default texture magnification filter to apply to this provider.
     *
     * @type {TextureMagnificationFilter}
     * @default undefined
     */
    this.defaultMagnificationFilter = undefined;

    this._tilingScheme = defined(options.tilingScheme)
      ? options.tilingScheme
      : new GeographicTilingScheme({ ellipsoid: options.ellipsoid });
    this._cells = defaultValue(options.cells, 8);
    this._color = defaultValue(options.color, defaultColor);
    this._glowColor = defaultValue(options.glowColor, defaultGlowColor);
    this._glowWidth = defaultValue(options.glowWidth, 6);
    this._backgroundColor = defaultValue(
      options.backgroundColor,
      defaultBackgroundColor
    );
    this._errorEvent = new Event();

    this._tileWidth = defaultValue(options.tileWidth, 256);
    this._tileHeight = defaultValue(options.tileHeight, 256);

    // A little larger than tile size so lines are sharper
    // Note: can't be too much difference otherwise texture blowout
    this._canvasSize = defaultValue(options.canvasSize, 256);

    // We only need a single canvas since all tiles will be the same
    this._canvas = this._createGridCanvas();

    this._readyPromise = Promise.resolve(true);
  }

  Object.defineProperties(GridImageryProvider.prototype, {
    /**
     * Gets the proxy used by this provider.
     * @memberof GridImageryProvider.prototype
     * @type {Proxy}
     * @readonly
     */
    proxy: {
      get: function () {
        return undefined;
      },
    },

    /**
     * Gets the width of each tile, in pixels. This function should
     * not be called before {@link GridImageryProvider#ready} returns true.
     * @memberof GridImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    tileWidth: {
      get: function () {
        return this._tileWidth;
      },
    },

    /**
     * Gets the height of each tile, in pixels.  This function should
     * not be called before {@link GridImageryProvider#ready} returns true.
     * @memberof GridImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    tileHeight: {
      get: function () {
        return this._tileHeight;
      },
    },

    /**
     * Gets the maximum level-of-detail that can be requested.  This function should
     * not be called before {@link GridImageryProvider#ready} returns true.
     * @memberof GridImageryProvider.prototype
     * @type {Number|undefined}
     * @readonly
     */
    maximumLevel: {
      get: function () {
        return undefined;
      },
    },

    /**
     * Gets the minimum level-of-detail that can be requested.  This function should
     * not be called before {@link GridImageryProvider#ready} returns true.
     * @memberof GridImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    minimumLevel: {
      get: function () {
        return undefined;
      },
    },

    /**
     * Gets the tiling scheme used by this provider.  This function should
     * not be called before {@link GridImageryProvider#ready} returns true.
     * @memberof GridImageryProvider.prototype
     * @type {TilingScheme}
     * @readonly
     */
    tilingScheme: {
      get: function () {
        return this._tilingScheme;
      },
    },

    /**
     * Gets the rectangle, in radians, of the imagery provided by this instance.  This function should
     * not be called before {@link GridImageryProvider#ready} returns true.
     * @memberof GridImageryProvider.prototype
     * @type {Rectangle}
     * @readonly
     */
    rectangle: {
      get: function () {
        return this._tilingScheme.rectangle;
      },
    },

    /**
     * Gets the tile discard policy.  If not undefined, the discard policy is responsible
     * for filtering out "missing" tiles via its shouldDiscardImage function.  If this function
     * returns undefined, no tiles are filtered.  This function should
     * not be called before {@link GridImageryProvider#ready} returns true.
     * @memberof GridImageryProvider.prototype
     * @type {TileDiscardPolicy}
     * @readonly
     */
    tileDiscardPolicy: {
      get: function () {
        return undefined;
      },
    },

    /**
     * Gets an event that is raised when the imagery provider encounters an asynchronous error.  By subscribing
     * to the event, you will be notified of the error and can potentially recover from it.  Event listeners
     * are passed an instance of {@link TileProviderError}.
     * @memberof GridImageryProvider.prototype
     * @type {Event}
     * @readonly
     */
    errorEvent: {
      get: function () {
        return this._errorEvent;
      },
    },

    /**
     * Gets a value indicating whether or not the provider is ready for use.
     * @memberof GridImageryProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    ready: {
      get: function () {
        return true;
      },
    },

    /**
     * Gets a promise that resolves to true when the provider is ready for use.
     * @memberof GridImageryProvider.prototype
     * @type {Promise.<Boolean>}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._readyPromise;
      },
    },

    /**
     * Gets the credit to display when this imagery provider is active.  Typically this is used to credit
     * the source of the imagery.  This function should not be called before {@link GridImageryProvider#ready} returns true.
     * @memberof GridImageryProvider.prototype
     * @type {Credit}
     * @readonly
     */
    credit: {
      get: function () {
        return undefined;
      },
    },

    /**
     * Gets a value indicating whether or not the images provided by this imagery provider
     * include an alpha channel.  If this property is false, an alpha channel, if present, will
     * be ignored.  If this property is true, any images without an alpha channel will be treated
     * as if their alpha is 1.0 everywhere.  When this property is false, memory usage
     * and texture upload time are reduced.
     * @memberof GridImageryProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    hasAlphaChannel: {
      get: function () {
        return true;
      },
    },
  });

  /**
   * Draws a grid of lines into a canvas.
   */
  GridImageryProvider.prototype._drawGrid = function (context) {
    const minPixel = 0;
    const maxPixel = this._canvasSize;
    for (let x = 0; x <= this._cells; ++x) {
      const nx = x / this._cells;
      const val = 1 + nx * (maxPixel - 1);

      context.moveTo(val, minPixel);
      context.lineTo(val, maxPixel);
      context.moveTo(minPixel, val);
      context.lineTo(maxPixel, val);
    }
    context.stroke();
  };

  /**
   * Render a grid into a canvas with background and glow
   */
  GridImageryProvider.prototype._createGridCanvas = function () {
    const canvas = document.createElement("canvas");
    canvas.width = this._canvasSize;
    canvas.height = this._canvasSize;
    const minPixel = 0;
    const maxPixel = this._canvasSize;

    const context = canvas.getContext("2d");

    // Fill the background
    const cssBackgroundColor = this._backgroundColor.toCssColorString();
    context.fillStyle = cssBackgroundColor;
    context.fillRect(minPixel, minPixel, maxPixel, maxPixel);

    // Glow for grid lines
    const cssGlowColor = this._glowColor.toCssColorString();
    context.strokeStyle = cssGlowColor;
    // Wide
    context.lineWidth = this._glowWidth;
    context.strokeRect(minPixel, minPixel, maxPixel, maxPixel);
    this._drawGrid(context);
    // Narrow
    context.lineWidth = this._glowWidth * 0.5;
    context.strokeRect(minPixel, minPixel, maxPixel, maxPixel);
    this._drawGrid(context);

    // Grid lines
    const cssColor = this._color.toCssColorString();
    // Border
    context.strokeStyle = cssColor;
    context.lineWidth = 2;
    context.strokeRect(minPixel, minPixel, maxPixel, maxPixel);
    // Inner
    context.lineWidth = 1;
    this._drawGrid(context);

    return canvas;
  };

  /**
   * Gets the credits to be displayed when a given tile is displayed.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level;
   * @returns {Credit[]} The credits to be displayed when the tile is displayed.
   *
   * @exception {DeveloperError} <code>getTileCredits</code> must not be called before the imagery provider is ready.
   */
  GridImageryProvider.prototype.getTileCredits = function (x, y, level) {
    return undefined;
  };

  /**
   * Requests the image for a given tile.  This function should
   * not be called before {@link GridImageryProvider#ready} returns true.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level.
   * @param {Request} [request] The request object. Intended for internal use only.
   * @returns {Promise.<HTMLCanvasElement>} The resolved image as a Canvas DOM object.
   */
  GridImageryProvider.prototype.requestImage = function (x, y, level, request) {
    return Promise.resolve(this._canvas);
  };

  /**
   * Picking features is not currently supported by this imagery provider, so this function simply returns
   * undefined.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level.
   * @param {Number} longitude The longitude at which to pick features.
   * @param {Number} latitude  The latitude at which to pick features.
   * @return {undefined} Undefined since picking is not supported.
   */
  GridImageryProvider.prototype.pickFeatures = function (
    x,
    y,
    level,
    longitude,
    latitude
  ) {
    return undefined;
  };

  /**
   * @private
   */
  function InvertClassification() {
    this._numSamples = 1;
    this.previousFramebuffer = undefined;
    this._previousFramebuffer = undefined;

    this._depthStencilTexture = undefined;
    this._depthStencilRenderbuffer = undefined;
    this._fbo = new FramebufferManager({
      depthStencil: true,
      createDepthAttachments: false,
    });
    this._fboClassified = new FramebufferManager({
      depthStencil: true,
      createDepthAttachments: false,
    });

    this._rsUnclassified = undefined;
    this._rsClassified = undefined;

    this._unclassifiedCommand = undefined;
    this._classifiedCommand = undefined;
    this._translucentCommand = undefined;

    this._clearColorCommand = new ClearCommand({
      color: new Color(0.0, 0.0, 0.0, 0.0),
      owner: this,
    });
    this._clearCommand = new ClearCommand({
      color: new Color(0.0, 0.0, 0.0, 0.0),
      depth: 1.0,
      stencil: 0,
    });

    const that = this;
    this._uniformMap = {
      colorTexture: function () {
        return that._fbo.getColorTexture();
      },
      depthTexture: function () {
        return that._depthStencilTexture;
      },
      classifiedTexture: function () {
        return that._fboClassified.getColorTexture();
      },
    };
  }

  Object.defineProperties(InvertClassification.prototype, {
    unclassifiedCommand: {
      get: function () {
        return this._unclassifiedCommand;
      },
    },
  });

  InvertClassification.isTranslucencySupported = function (context) {
    return context.depthTexture && context.fragmentDepth;
  };

  const rsUnclassified = {
    depthMask: false,
    stencilTest: {
      enabled: true,
      frontFunction: StencilFunction$1.EQUAL,
      frontOperation: {
        fail: StencilOperation$1.KEEP,
        zFail: StencilOperation$1.KEEP,
        zPass: StencilOperation$1.KEEP,
      },
      backFunction: StencilFunction$1.NEVER,
      reference: 0,
      mask: StencilConstants$1.CLASSIFICATION_MASK,
    },
    blending: BlendingState$1.ALPHA_BLEND,
  };

  const rsClassified = {
    depthMask: false,
    stencilTest: {
      enabled: true,
      frontFunction: StencilFunction$1.NOT_EQUAL,
      frontOperation: {
        fail: StencilOperation$1.KEEP,
        zFail: StencilOperation$1.KEEP,
        zPass: StencilOperation$1.KEEP,
      },
      backFunction: StencilFunction$1.NEVER,
      reference: 0,
      mask: StencilConstants$1.CLASSIFICATION_MASK,
    },
    blending: BlendingState$1.ALPHA_BLEND,
  };

  // Set the 3D Tiles bit when rendering back into the scene's framebuffer. This is only needed if
  // invert classification does not use the scene's depth-stencil texture, which is the case if the invert
  // classification color is translucent.
  const rsDefault = {
    depthMask: true,
    depthTest: {
      enabled: true,
    },
    stencilTest: StencilConstants$1.setCesium3DTileBit(),
    stencilMask: StencilConstants$1.CESIUM_3D_TILE_MASK,
    blending: BlendingState$1.ALPHA_BLEND,
  };

  const translucentFS =
    "#extension GL_EXT_frag_depth : enable\n" +
    "uniform sampler2D colorTexture;\n" +
    "uniform sampler2D depthTexture;\n" +
    "uniform sampler2D classifiedTexture;\n" +
    "varying vec2 v_textureCoordinates;\n" +
    "void main()\n" +
    "{\n" +
    "    vec4 color = texture2D(colorTexture, v_textureCoordinates);\n" +
    "    if (color.a == 0.0)\n" +
    "    {\n" +
    "        discard;\n" +
    "    }\n" +
    "    bool isClassified = all(equal(texture2D(classifiedTexture, v_textureCoordinates), vec4(0.0)));\n" +
    "#ifdef UNCLASSIFIED\n" +
    "    vec4 highlightColor = czm_invertClassificationColor;\n" +
    "    if (isClassified)\n" +
    "    {\n" +
    "        discard;\n" +
    "    }\n" +
    "#else\n" +
    "    vec4 highlightColor = vec4(1.0);\n" +
    "    if (!isClassified)\n" +
    "    {\n" +
    "        discard;\n" +
    "    }\n" +
    "#endif\n" +
    "    gl_FragColor = color * highlightColor;\n" +
    "    gl_FragDepthEXT = texture2D(depthTexture, v_textureCoordinates).r;\n" +
    "}\n";

  const opaqueFS =
    "uniform sampler2D colorTexture;\n" +
    "varying vec2 v_textureCoordinates;\n" +
    "void main()\n" +
    "{\n" +
    "    vec4 color = texture2D(colorTexture, v_textureCoordinates);\n" +
    "    if (color.a == 0.0)\n" +
    "    {\n" +
    "        discard;\n" +
    "    }\n" +
    "#ifdef UNCLASSIFIED\n" +
    "    gl_FragColor = color * czm_invertClassificationColor;\n" +
    "#else\n" +
    "    gl_FragColor = color;\n" +
    "#endif\n" +
    "}\n";

  InvertClassification.prototype.update = function (
    context,
    numSamples,
    globeFramebuffer
  ) {
    const texture = this._fbo.getColorTexture();
    const previousFramebufferChanged =
      this.previousFramebuffer !== this._previousFramebuffer;
    this._previousFramebuffer = this.previousFramebuffer;
    const samplesChanged = this._numSamples !== numSamples;

    const width = context.drawingBufferWidth;
    const height = context.drawingBufferHeight;
    const textureChanged =
      !defined(texture) || texture.width !== width || texture.height !== height;

    if (textureChanged || previousFramebufferChanged || samplesChanged) {
      this._numSamples = numSamples;
      this._depthStencilTexture =
        this._depthStencilTexture && this._depthStencilTexture.destroy();
      this._depthStencilRenderbuffer =
        this._depthStencilRenderbuffer &&
        this._depthStencilRenderbuffer.destroy();

      if (!defined(this._previousFramebuffer)) {
        this._depthStencilTexture = new Texture({
          context: context,
          width: width,
          height: height,
          pixelFormat: PixelFormat$1.DEPTH_STENCIL,
          pixelDatatype: PixelDatatype$1.UNSIGNED_INT_24_8,
        });
        if (numSamples > 1) {
          this._depthStencilRenderbuffer = new Renderbuffer({
            context: context,
            width: width,
            height: height,
            format: RenderbufferFormat$1.DEPTH24_STENCIL8,
            numSamples: numSamples,
          });
        }
      }
    }

    if (
      !defined(this._fbo.framebuffer) ||
      textureChanged ||
      previousFramebufferChanged ||
      samplesChanged
    ) {
      this._fbo.destroy();
      this._fboClassified.destroy();

      let depthStencilTexture;
      let depthStencilRenderbuffer;
      if (defined(this._previousFramebuffer)) {
        depthStencilTexture = globeFramebuffer.getDepthStencilTexture();
        depthStencilRenderbuffer = globeFramebuffer.getDepthStencilRenderbuffer();
      } else {
        depthStencilTexture = this._depthStencilTexture;
        depthStencilRenderbuffer = this._depthStencilRenderbuffer;
      }

      this._fbo.setDepthStencilTexture(depthStencilTexture);
      if (defined(depthStencilRenderbuffer)) {
        this._fbo.setDepthStencilRenderbuffer(depthStencilRenderbuffer);
      }
      this._fbo.update(context, width, height, numSamples);

      if (!defined(this._previousFramebuffer)) {
        this._fboClassified.setDepthStencilTexture(depthStencilTexture);
        this._fboClassified.update(context, width, height);
      }
    }

    if (!defined(this._rsUnclassified)) {
      this._rsUnclassified = RenderState.fromCache(rsUnclassified);
      this._rsClassified = RenderState.fromCache(rsClassified);
      this._rsDefault = RenderState.fromCache(rsDefault);
    }

    if (
      !defined(this._unclassifiedCommand) ||
      previousFramebufferChanged ||
      samplesChanged
    ) {
      if (defined(this._unclassifiedCommand)) {
        this._unclassifiedCommand.shaderProgram =
          this._unclassifiedCommand.shaderProgram &&
          this._unclassifiedCommand.shaderProgram.destroy();
        this._classifiedCommand.shaderProgram =
          this._classifiedCommand.shaderProgram &&
          this._classifiedCommand.shaderProgram.destroy();
      }

      const fs = defined(this._previousFramebuffer) ? opaqueFS : translucentFS;
      const unclassifiedFSSource = new ShaderSource({
        defines: ["UNCLASSIFIED"],
        sources: [fs],
      });
      const classifiedFSSource = new ShaderSource({
        sources: [fs],
      });
      this._unclassifiedCommand = context.createViewportQuadCommand(
        unclassifiedFSSource,
        {
          renderState: defined(this._previousFramebuffer)
            ? this._rsUnclassified
            : this._rsDefault,
          uniformMap: this._uniformMap,
          owner: this,
        }
      );
      this._classifiedCommand = context.createViewportQuadCommand(
        classifiedFSSource,
        {
          renderState: defined(this._previousFramebuffer)
            ? this._rsClassified
            : this._rsDefault,
          uniformMap: this._uniformMap,
          owner: this,
        }
      );

      if (defined(this._translucentCommand)) {
        this._translucentCommand.shaderProgram =
          this._translucentCommand.shaderProgram &&
          this._translucentCommand.shaderProgram.destroy();
      }
      if (!defined(this._previousFramebuffer)) {
        this._translucentCommand = context.createViewportQuadCommand(
          PassThrough,
          {
            renderState: this._rsUnclassified,
            uniformMap: this._uniformMap,
            owner: this,
          }
        );
      }
    }
  };

  InvertClassification.prototype.prepareTextures = function (
    context,
    blitStencil
  ) {
    if (this._fbo._numSamples > 1) {
      this._fbo.prepareTextures(context, blitStencil);
    }
  };

  InvertClassification.prototype.clear = function (context, passState) {
    if (defined(this._previousFramebuffer)) {
      this._fbo.clear(context, this._clearColorCommand, passState);
    } else {
      this._fbo.clear(context, this._clearCommand, passState);
      this._fboClassified.clear(context, this._clearCommand, passState);
    }
  };

  InvertClassification.prototype.executeClassified = function (
    context,
    passState
  ) {
    if (!defined(this._previousFramebuffer)) {
      const framebuffer = passState.framebuffer;

      this.prepareTextures(context, true);
      passState.framebuffer = this._fboClassified.framebuffer;
      this._translucentCommand.execute(context, passState);

      passState.framebuffer = framebuffer;
    }
    this._classifiedCommand.execute(context, passState);
  };

  InvertClassification.prototype.executeUnclassified = function (
    context,
    passState
  ) {
    this._unclassifiedCommand.execute(context, passState);
  };

  InvertClassification.prototype.isDestroyed = function () {
    return false;
  };

  InvertClassification.prototype.destroy = function () {
    this._fbo.destroy();
    this._fboClassified.destroy();
    this._depthStencilTexture =
      this._depthStencilTexture && this._depthStencilTexture.destroy();
    this._depthStencilRenderbuffer =
      this._depthStencilRenderbuffer && this._depthStencilRenderbuffer.destroy();

    if (defined(this._unclassifiedCommand)) {
      this._unclassifiedCommand.shaderProgram =
        this._unclassifiedCommand.shaderProgram &&
        this._unclassifiedCommand.shaderProgram.destroy();
      this._classifiedCommand.shaderProgram =
        this._classifiedCommand.shaderProgram &&
        this._classifiedCommand.shaderProgram.destroy();
    }

    return destroyObject(this);
  };

  const templateRegex = /{[^}]+}/g;

  const tags = {
    x: xTag,
    y: yTag,
    z: zTag,
    s: sTag,
    reverseX: reverseXTag,
    reverseY: reverseYTag,
    reverseZ: reverseZTag,
    westDegrees: westDegreesTag,
    southDegrees: southDegreesTag,
    eastDegrees: eastDegreesTag,
    northDegrees: northDegreesTag,
    westProjected: westProjectedTag,
    southProjected: southProjectedTag,
    eastProjected: eastProjectedTag,
    northProjected: northProjectedTag,
    width: widthTag,
    height: heightTag,
  };

  const pickFeaturesTags = combine$2(tags, {
    i: iTag,
    j: jTag,
    reverseI: reverseITag,
    reverseJ: reverseJTag,
    longitudeDegrees: longitudeDegreesTag,
    latitudeDegrees: latitudeDegreesTag,
    longitudeProjected: longitudeProjectedTag,
    latitudeProjected: latitudeProjectedTag,
    format: formatTag,
  });

  /**
   * @typedef {Object} UrlTemplateImageryProvider.ConstructorOptions
   *
   * Initialization options for the UrlTemplateImageryProvider constructor
   *
   * @property {Promise.<Object>|Object} [options] Object with the following properties:
   * @property {Resource|String} url  The URL template to use to request tiles.  It has the following keywords:
   * <ul>
   *     <li><code>{z}</code>: The level of the tile in the tiling scheme.  Level zero is the root of the quadtree pyramid.</li>
   *     <li><code>{x}</code>: The tile X coordinate in the tiling scheme, where 0 is the Westernmost tile.</li>
   *     <li><code>{y}</code>: The tile Y coordinate in the tiling scheme, where 0 is the Northernmost tile.</li>
   *     <li><code>{s}</code>: One of the available subdomains, used to overcome browser limits on the number of simultaneous requests per host.</li>
   *     <li><code>{reverseX}</code>: The tile X coordinate in the tiling scheme, where 0 is the Easternmost tile.</li>
   *     <li><code>{reverseY}</code>: The tile Y coordinate in the tiling scheme, where 0 is the Southernmost tile.</li>
   *     <li><code>{reverseZ}</code>: The level of the tile in the tiling scheme, where level zero is the maximum level of the quadtree pyramid.  In order to use reverseZ, maximumLevel must be defined.</li>
   *     <li><code>{westDegrees}</code>: The Western edge of the tile in geodetic degrees.</li>
   *     <li><code>{southDegrees}</code>: The Southern edge of the tile in geodetic degrees.</li>
   *     <li><code>{eastDegrees}</code>: The Eastern edge of the tile in geodetic degrees.</li>
   *     <li><code>{northDegrees}</code>: The Northern edge of the tile in geodetic degrees.</li>
   *     <li><code>{westProjected}</code>: The Western edge of the tile in projected coordinates of the tiling scheme.</li>
   *     <li><code>{southProjected}</code>: The Southern edge of the tile in projected coordinates of the tiling scheme.</li>
   *     <li><code>{eastProjected}</code>: The Eastern edge of the tile in projected coordinates of the tiling scheme.</li>
   *     <li><code>{northProjected}</code>: The Northern edge of the tile in projected coordinates of the tiling scheme.</li>
   *     <li><code>{width}</code>: The width of each tile in pixels.</li>
   *     <li><code>{height}</code>: The height of each tile in pixels.</li>
   * </ul>
   * @property {Resource|String} [pickFeaturesUrl] The URL template to use to pick features.  If this property is not specified,
   *                 {@link UrlTemplateImageryProvider#pickFeatures} will immediately returned undefined, indicating no
   *                 features picked.  The URL template supports all of the keywords supported by the <code>url</code>
   *                 parameter, plus the following:
   * <ul>
   *     <li><code>{i}</code>: The pixel column (horizontal coordinate) of the picked position, where the Westernmost pixel is 0.</li>
   *     <li><code>{j}</code>: The pixel row (vertical coordinate) of the picked position, where the Northernmost pixel is 0.</li>
   *     <li><code>{reverseI}</code>: The pixel column (horizontal coordinate) of the picked position, where the Easternmost pixel is 0.</li>
   *     <li><code>{reverseJ}</code>: The pixel row (vertical coordinate) of the picked position, where the Southernmost pixel is 0.</li>
   *     <li><code>{longitudeDegrees}</code>: The longitude of the picked position in degrees.</li>
   *     <li><code>{latitudeDegrees}</code>: The latitude of the picked position in degrees.</li>
   *     <li><code>{longitudeProjected}</code>: The longitude of the picked position in the projected coordinates of the tiling scheme.</li>
   *     <li><code>{latitudeProjected}</code>: The latitude of the picked position in the projected coordinates of the tiling scheme.</li>
   *     <li><code>{format}</code>: The format in which to get feature information, as specified in the {@link GetFeatureInfoFormat}.</li>
   * </ul>
   * @property {Object} [urlSchemeZeroPadding] Gets the URL scheme zero padding for each tile coordinate. The format is '000' where
   * each coordinate will be padded on the left with zeros to match the width of the passed string of zeros. e.g. Setting:
   * urlSchemeZeroPadding : { '{x}' : '0000'}
   * will cause an 'x' value of 12 to return the string '0012' for {x} in the generated URL.
   * It the passed object has the following keywords:
   * <ul>
   *  <li> <code>{z}</code>: The zero padding for the level of the tile in the tiling scheme.</li>
   *  <li> <code>{x}</code>: The zero padding for the tile X coordinate in the tiling scheme.</li>
   *  <li> <code>{y}</code>: The zero padding for the the tile Y coordinate in the tiling scheme.</li>
   *  <li> <code>{reverseX}</code>: The zero padding for the tile reverseX coordinate in the tiling scheme.</li>
   *  <li> <code>{reverseY}</code>: The zero padding for the tile reverseY coordinate in the tiling scheme.</li>
   *  <li> <code>{reverseZ}</code>: The zero padding for the reverseZ coordinate of the tile in the tiling scheme.</li>
   * </ul>
   * @property {String|String[]} [subdomains='abc'] The subdomains to use for the <code>{s}</code> placeholder in the URL template.
   *                          If this parameter is a single string, each character in the string is a subdomain.  If it is
   *                          an array, each element in the array is a subdomain.
   * @property {Credit|String} [credit=''] A credit for the data source, which is displayed on the canvas.
   * @property {Number} [minimumLevel=0] The minimum level-of-detail supported by the imagery provider.  Take care when specifying
   *                 this that the number of tiles at the minimum level is small, such as four or less.  A larger number is likely
   *                 to result in rendering problems.
   * @property {Number} [maximumLevel] The maximum level-of-detail supported by the imagery provider, or undefined if there is no limit.
   * @property {Rectangle} [rectangle=Rectangle.MAX_VALUE] The rectangle, in radians, covered by the image.
   * @property {TilingScheme} [tilingScheme=WebMercatorTilingScheme] The tiling scheme specifying how the ellipsoidal
   * surface is broken into tiles.  If this parameter is not provided, a {@link WebMercatorTilingScheme}
   * is used.
   * @property {Ellipsoid} [ellipsoid] The ellipsoid.  If the tilingScheme is specified,
   *                    this parameter is ignored and the tiling scheme's ellipsoid is used instead. If neither
   *                    parameter is specified, the WGS84 ellipsoid is used.
   * @property {Number} [tileWidth=256] Pixel width of image tiles.
   * @property {Number} [tileHeight=256] Pixel height of image tiles.
   * @property {Boolean} [hasAlphaChannel=true] true if the images provided by this imagery provider
   *                  include an alpha channel; otherwise, false.  If this property is false, an alpha channel, if
   *                  present, will be ignored.  If this property is true, any images without an alpha channel will
   *                  be treated as if their alpha is 1.0 everywhere.  When this property is false, memory usage
   *                  and texture upload time are potentially reduced.
   * @property {GetFeatureInfoFormat[]} [getFeatureInfoFormats] The formats in which to get feature information at a
   *                                 specific location when {@link UrlTemplateImageryProvider#pickFeatures} is invoked.  If this
   *                                 parameter is not specified, feature picking is disabled.
   * @property {Boolean} [enablePickFeatures=true] If true, {@link UrlTemplateImageryProvider#pickFeatures} will
   *        request the <code>pickFeaturesUrl</code> and attempt to interpret the features included in the response.  If false,
   *        {@link UrlTemplateImageryProvider#pickFeatures} will immediately return undefined (indicating no pickable
   *        features) without communicating with the server.  Set this property to false if you know your data
   *        source does not support picking features or if you don't want this provider's features to be pickable. Note
   *        that this can be dynamically overridden by modifying the {@link UriTemplateImageryProvider#enablePickFeatures}
   *        property.
   * @property {Object} [customTags] Allow to replace custom keywords in the URL template. The object must have strings as keys and functions as values.
   */

  /**
   * Provides imagery by requesting tiles using a specified URL template.
   *
   * @alias UrlTemplateImageryProvider
   * @constructor
   *
   * @param {UrlTemplateImageryProvider.ConstructorOptions} options Object describing initialization options
   *
   * @example
   * // Access Natural Earth II imagery, which uses a TMS tiling scheme and Geographic (EPSG:4326) project
   * const tms = new Cesium.UrlTemplateImageryProvider({
   *     url : Cesium.buildModuleUrl('Assets/Textures/NaturalEarthII') + '/{z}/{x}/{reverseY}.jpg',
   *     credit : '© Analytical Graphics, Inc.',
   *     tilingScheme : new Cesium.GeographicTilingScheme(),
   *     maximumLevel : 5
   * });
   * // Access the CartoDB Positron basemap, which uses an OpenStreetMap-like tiling scheme.
   * const positron = new Cesium.UrlTemplateImageryProvider({
   *     url : 'http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png',
   *     credit : 'Map tiles by CartoDB, under CC BY 3.0. Data by OpenStreetMap, under ODbL.'
   * });
   * // Access a Web Map Service (WMS) server.
   * const wms = new Cesium.UrlTemplateImageryProvider({
   *    url : 'https://programs.communications.gov.au/geoserver/ows?tiled=true&' +
   *          'transparent=true&format=image%2Fpng&exceptions=application%2Fvnd.ogc.se_xml&' +
   *          'styles=&service=WMS&version=1.1.1&request=GetMap&' +
   *          'layers=public%3AMyBroadband_Availability&srs=EPSG%3A3857&' +
   *          'bbox={westProjected}%2C{southProjected}%2C{eastProjected}%2C{northProjected}&' +
   *          'width=256&height=256',
   *    rectangle : Cesium.Rectangle.fromDegrees(96.799393, -43.598214999057824, 153.63925700000001, -9.2159219997013)
   * });
   * // Using custom tags in your template url.
   * const custom = new Cesium.UrlTemplateImageryProvider({
   *    url : 'https://yoururl/{Time}/{z}/{y}/{x}.png',
   *    customTags : {
   *        Time: function(imageryProvider, x, y, level) {
   *            return '20171231'
   *        }
   *    }
   * });
   *
   * @see ArcGisMapServerImageryProvider
   * @see BingMapsImageryProvider
   * @see GoogleEarthEnterpriseMapsProvider
   * @see OpenStreetMapImageryProvider
   * @see SingleTileImageryProvider
   * @see TileMapServiceImageryProvider
   * @see WebMapServiceImageryProvider
   * @see WebMapTileServiceImageryProvider
   */
  function UrlTemplateImageryProvider(options) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(options)) {
      throw new DeveloperError("options is required.");
    }
    if (!defined(options.then) && !defined(options.url)) {
      throw new DeveloperError("options is required.");
    }
    //>>includeEnd('debug');

    this._errorEvent = new Event();

    this._resource = undefined;
    this._urlSchemeZeroPadding = undefined;
    this._pickFeaturesResource = undefined;
    this._tileWidth = undefined;
    this._tileHeight = undefined;
    this._maximumLevel = undefined;
    this._minimumLevel = undefined;
    this._tilingScheme = undefined;
    this._rectangle = undefined;
    this._tileDiscardPolicy = undefined;
    this._credit = undefined;
    this._hasAlphaChannel = undefined;
    this._readyPromise = undefined;
    this._tags = undefined;
    this._pickFeaturesTags = undefined;

    /**
     * The default alpha blending value of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultAlpha = undefined;

    /**
     * The default alpha blending value on the night side of the globe of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultNightAlpha = undefined;

    /**
     * The default alpha blending value on the day side of the globe of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultDayAlpha = undefined;

    /**
     * The default brightness of this provider.  1.0 uses the unmodified imagery color.  Less than 1.0
     * makes the imagery darker while greater than 1.0 makes it brighter.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultBrightness = undefined;

    /**
     * The default contrast of this provider.  1.0 uses the unmodified imagery color.  Less than 1.0 reduces
     * the contrast while greater than 1.0 increases it.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultContrast = undefined;

    /**
     * The default hue of this provider in radians. 0.0 uses the unmodified imagery color.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultHue = undefined;

    /**
     * The default saturation of this provider. 1.0 uses the unmodified imagery color. Less than 1.0 reduces the
     * saturation while greater than 1.0 increases it.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultSaturation = undefined;

    /**
     * The default gamma correction to apply to this provider.  1.0 uses the unmodified imagery color.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultGamma = undefined;

    /**
     * The default texture minification filter to apply to this provider.
     *
     * @type {TextureMinificationFilter}
     * @default undefined
     */
    this.defaultMinificationFilter = undefined;

    /**
     * The default texture magnification filter to apply to this provider.
     *
     * @type {TextureMagnificationFilter}
     * @default undefined
     */
    this.defaultMagnificationFilter = undefined;

    /**
     * Gets or sets a value indicating whether feature picking is enabled.  If true, {@link UrlTemplateImageryProvider#pickFeatures} will
     * request the <code>options.pickFeaturesUrl</code> and attempt to interpret the features included in the response.  If false,
     * {@link UrlTemplateImageryProvider#pickFeatures} will immediately return undefined (indicating no pickable
     * features) without communicating with the server.  Set this property to false if you know your data
     * source does not support picking features or if you don't want this provider's features to be pickable.
     * @type {Boolean}
     * @default true
     */
    this.enablePickFeatures = true;

    this.reinitialize(options);
  }

  Object.defineProperties(UrlTemplateImageryProvider.prototype, {
    /**
     * Gets the URL template to use to request tiles.  It has the following keywords:
     * <ul>
     *  <li> <code>{z}</code>: The level of the tile in the tiling scheme.  Level zero is the root of the quadtree pyramid.</li>
     *  <li> <code>{x}</code>: The tile X coordinate in the tiling scheme, where 0 is the Westernmost tile.</li>
     *  <li> <code>{y}</code>: The tile Y coordinate in the tiling scheme, where 0 is the Northernmost tile.</li>
     *  <li> <code>{s}</code>: One of the available subdomains, used to overcome browser limits on the number of simultaneous requests per host.</li>
     *  <li> <code>{reverseX}</code>: The tile X coordinate in the tiling scheme, where 0 is the Easternmost tile.</li>
     *  <li> <code>{reverseY}</code>: The tile Y coordinate in the tiling scheme, where 0 is the Southernmost tile.</li>
     *  <li> <code>{reverseZ}</code>: The level of the tile in the tiling scheme, where level zero is the maximum level of the quadtree pyramid.  In order to use reverseZ, maximumLevel must be defined.</li>
     *  <li> <code>{westDegrees}</code>: The Western edge of the tile in geodetic degrees.</li>
     *  <li> <code>{southDegrees}</code>: The Southern edge of the tile in geodetic degrees.</li>
     *  <li> <code>{eastDegrees}</code>: The Eastern edge of the tile in geodetic degrees.</li>
     *  <li> <code>{northDegrees}</code>: The Northern edge of the tile in geodetic degrees.</li>
     *  <li> <code>{westProjected}</code>: The Western edge of the tile in projected coordinates of the tiling scheme.</li>
     *  <li> <code>{southProjected}</code>: The Southern edge of the tile in projected coordinates of the tiling scheme.</li>
     *  <li> <code>{eastProjected}</code>: The Eastern edge of the tile in projected coordinates of the tiling scheme.</li>
     *  <li> <code>{northProjected}</code>: The Northern edge of the tile in projected coordinates of the tiling scheme.</li>
     *  <li> <code>{width}</code>: The width of each tile in pixels.</li>
     *  <li> <code>{height}</code>: The height of each tile in pixels.</li>
     * </ul>
     * @memberof UrlTemplateImageryProvider.prototype
     * @type {String}
     * @readonly
     */
    url: {
      get: function () {
        return this._resource.url;
      },
    },

    /**
     * Gets the URL scheme zero padding for each tile coordinate. The format is '000' where each coordinate will be padded on
     * the left with zeros to match the width of the passed string of zeros. e.g. Setting:
     * urlSchemeZeroPadding : { '{x}' : '0000'}
     * will cause an 'x' value of 12 to return the string '0012' for {x} in the generated URL.
     * It has the following keywords:
     * <ul>
     *  <li> <code>{z}</code>: The zero padding for the level of the tile in the tiling scheme.</li>
     *  <li> <code>{x}</code>: The zero padding for the tile X coordinate in the tiling scheme.</li>
     *  <li> <code>{y}</code>: The zero padding for the the tile Y coordinate in the tiling scheme.</li>
     *  <li> <code>{reverseX}</code>: The zero padding for the tile reverseX coordinate in the tiling scheme.</li>
     *  <li> <code>{reverseY}</code>: The zero padding for the tile reverseY coordinate in the tiling scheme.</li>
     *  <li> <code>{reverseZ}</code>: The zero padding for the reverseZ coordinate of the tile in the tiling scheme.</li>
     * </ul>
     * @memberof UrlTemplateImageryProvider.prototype
     * @type {Object}
     * @readonly
     */
    urlSchemeZeroPadding: {
      get: function () {
        return this._urlSchemeZeroPadding;
      },
    },

    /**
     * Gets the URL template to use to use to pick features.  If this property is not specified,
     * {@link UrlTemplateImageryProvider#pickFeatures} will immediately return undefined, indicating no
     * features picked.  The URL template supports all of the keywords supported by the
     * {@link UrlTemplateImageryProvider#url} property, plus the following:
     * <ul>
     *     <li><code>{i}</code>: The pixel column (horizontal coordinate) of the picked position, where the Westernmost pixel is 0.</li>
     *     <li><code>{j}</code>: The pixel row (vertical coordinate) of the picked position, where the Northernmost pixel is 0.</li>
     *     <li><code>{reverseI}</code>: The pixel column (horizontal coordinate) of the picked position, where the Easternmost pixel is 0.</li>
     *     <li><code>{reverseJ}</code>: The pixel row (vertical coordinate) of the picked position, where the Southernmost pixel is 0.</li>
     *     <li><code>{longitudeDegrees}</code>: The longitude of the picked position in degrees.</li>
     *     <li><code>{latitudeDegrees}</code>: The latitude of the picked position in degrees.</li>
     *     <li><code>{longitudeProjected}</code>: The longitude of the picked position in the projected coordinates of the tiling scheme.</li>
     *     <li><code>{latitudeProjected}</code>: The latitude of the picked position in the projected coordinates of the tiling scheme.</li>
     *     <li><code>{format}</code>: The format in which to get feature information, as specified in the {@link GetFeatureInfoFormat}.</li>
     * </ul>
     * @memberof UrlTemplateImageryProvider.prototype
     * @type {String}
     * @readonly
     */
    pickFeaturesUrl: {
      get: function () {
        return this._pickFeaturesResource.url;
      },
    },

    /**
     * Gets the proxy used by this provider.
     * @memberof UrlTemplateImageryProvider.prototype
     * @type {Proxy}
     * @readonly
     * @default undefined
     */
    proxy: {
      get: function () {
        return this._resource.proxy;
      },
    },

    /**
     * Gets the width of each tile, in pixels. This function should
     * not be called before {@link UrlTemplateImageryProvider#ready} returns true.
     * @memberof UrlTemplateImageryProvider.prototype
     * @type {Number}
     * @readonly
     * @default 256
     */
    tileWidth: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this.ready) {
          throw new DeveloperError(
            "tileWidth must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');
        return this._tileWidth;
      },
    },

    /**
     * Gets the height of each tile, in pixels.  This function should
     * not be called before {@link UrlTemplateImageryProvider#ready} returns true.
     * @memberof UrlTemplateImageryProvider.prototype
     * @type {Number}
     * @readonly
     * @default 256
     */
    tileHeight: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this.ready) {
          throw new DeveloperError(
            "tileHeight must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');
        return this._tileHeight;
      },
    },

    /**
     * Gets the maximum level-of-detail that can be requested, or undefined if there is no limit.
     * This function should not be called before {@link UrlTemplateImageryProvider#ready} returns true.
     * @memberof UrlTemplateImageryProvider.prototype
     * @type {Number|undefined}
     * @readonly
     * @default undefined
     */
    maximumLevel: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this.ready) {
          throw new DeveloperError(
            "maximumLevel must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');
        return this._maximumLevel;
      },
    },

    /**
     * Gets the minimum level-of-detail that can be requested.  This function should
     * not be called before {@link UrlTemplateImageryProvider#ready} returns true.
     * @memberof UrlTemplateImageryProvider.prototype
     * @type {Number}
     * @readonly
     * @default 0
     */
    minimumLevel: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this.ready) {
          throw new DeveloperError(
            "minimumLevel must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');
        return this._minimumLevel;
      },
    },

    /**
     * Gets the tiling scheme used by this provider.  This function should
     * not be called before {@link UrlTemplateImageryProvider#ready} returns true.
     * @memberof UrlTemplateImageryProvider.prototype
     * @type {TilingScheme}
     * @readonly
     * @default new WebMercatorTilingScheme()
     */
    tilingScheme: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this.ready) {
          throw new DeveloperError(
            "tilingScheme must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');
        return this._tilingScheme;
      },
    },

    /**
     * Gets the rectangle, in radians, of the imagery provided by this instance.  This function should
     * not be called before {@link UrlTemplateImageryProvider#ready} returns true.
     * @memberof UrlTemplateImageryProvider.prototype
     * @type {Rectangle}
     * @readonly
     * @default tilingScheme.rectangle
     */
    rectangle: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this.ready) {
          throw new DeveloperError(
            "rectangle must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');
        return this._rectangle;
      },
    },

    /**
     * Gets the tile discard policy.  If not undefined, the discard policy is responsible
     * for filtering out "missing" tiles via its shouldDiscardImage function.  If this function
     * returns undefined, no tiles are filtered.  This function should
     * not be called before {@link UrlTemplateImageryProvider#ready} returns true.
     * @memberof UrlTemplateImageryProvider.prototype
     * @type {TileDiscardPolicy}
     * @readonly
     * @default undefined
     */
    tileDiscardPolicy: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this.ready) {
          throw new DeveloperError(
            "tileDiscardPolicy must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');
        return this._tileDiscardPolicy;
      },
    },

    /**
     * Gets an event that is raised when the imagery provider encounters an asynchronous error.  By subscribing
     * to the event, you will be notified of the error and can potentially recover from it.  Event listeners
     * are passed an instance of {@link TileProviderError}.
     * @memberof UrlTemplateImageryProvider.prototype
     * @type {Event}
     * @readonly
     */
    errorEvent: {
      get: function () {
        return this._errorEvent;
      },
    },

    /**
     * Gets a value indicating whether or not the provider is ready for use.
     * @memberof UrlTemplateImageryProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    ready: {
      get: function () {
        return defined(this._resource);
      },
    },

    /**
     * Gets a promise that resolves to true when the provider is ready for use.
     * @memberof UrlTemplateImageryProvider.prototype
     * @type {Promise.<Boolean>}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._readyPromise;
      },
    },

    /**
     * Gets the credit to display when this imagery provider is active.  Typically this is used to credit
     * the source of the imagery.  This function should not be called before {@link UrlTemplateImageryProvider#ready} returns true.
     * @memberof UrlTemplateImageryProvider.prototype
     * @type {Credit}
     * @readonly
     * @default undefined
     */
    credit: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this.ready) {
          throw new DeveloperError(
            "credit must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');
        return this._credit;
      },
    },

    /**
     * Gets a value indicating whether or not the images provided by this imagery provider
     * include an alpha channel.  If this property is false, an alpha channel, if present, will
     * be ignored.  If this property is true, any images without an alpha channel will be treated
     * as if their alpha is 1.0 everywhere.  When this property is false, memory usage
     * and texture upload time are reduced.  This function should
     * not be called before {@link ImageryProvider#ready} returns true.
     * @memberof UrlTemplateImageryProvider.prototype
     * @type {Boolean}
     * @readonly
     * @default true
     */
    hasAlphaChannel: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this.ready) {
          throw new DeveloperError(
            "hasAlphaChannel must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');
        return this._hasAlphaChannel;
      },
    },
  });

  /**
   * Reinitializes this instance.  Reinitializing an instance already in use is supported, but it is not
   * recommended because existing tiles provided by the imagery provider will not be updated.
   *
   * @param {Promise.<Object>|Object} options Any of the options that may be passed to the {@link UrlTemplateImageryProvider} constructor.
   */
  UrlTemplateImageryProvider.prototype.reinitialize = function (options) {
    const that = this;
    that._readyPromise = Promise.resolve(options).then(function (properties) {
      //>>includeStart('debug', pragmas.debug);
      if (!defined(properties)) {
        throw new DeveloperError("options is required.");
      }
      if (!defined(properties.url)) {
        throw new DeveloperError("options.url is required.");
      }
      //>>includeEnd('debug');

      const customTags = properties.customTags;
      const allTags = combine$2(tags, customTags);
      const allPickFeaturesTags = combine$2(pickFeaturesTags, customTags);
      const resource = Resource.createIfNeeded(properties.url);
      const pickFeaturesResource = Resource.createIfNeeded(
        properties.pickFeaturesUrl
      );

      that.enablePickFeatures = defaultValue(
        properties.enablePickFeatures,
        that.enablePickFeatures
      );
      that._urlSchemeZeroPadding = defaultValue(
        properties.urlSchemeZeroPadding,
        that.urlSchemeZeroPadding
      );
      that._tileDiscardPolicy = properties.tileDiscardPolicy;
      that._getFeatureInfoFormats = properties.getFeatureInfoFormats;

      that._subdomains = properties.subdomains;
      if (Array.isArray(that._subdomains)) {
        that._subdomains = that._subdomains.slice();
      } else if (defined(that._subdomains) && that._subdomains.length > 0) {
        that._subdomains = that._subdomains.split("");
      } else {
        that._subdomains = ["a", "b", "c"];
      }

      that._tileWidth = defaultValue(properties.tileWidth, 256);
      that._tileHeight = defaultValue(properties.tileHeight, 256);
      that._minimumLevel = defaultValue(properties.minimumLevel, 0);
      that._maximumLevel = properties.maximumLevel;
      that._tilingScheme = defaultValue(
        properties.tilingScheme,
        new WebMercatorTilingScheme({ ellipsoid: properties.ellipsoid })
      );
      that._rectangle = defaultValue(
        properties.rectangle,
        that._tilingScheme.rectangle
      );
      that._rectangle = Rectangle.intersection(
        that._rectangle,
        that._tilingScheme.rectangle
      );
      that._hasAlphaChannel = defaultValue(properties.hasAlphaChannel, true);

      let credit = properties.credit;
      if (typeof credit === "string") {
        credit = new Credit(credit);
      }
      that._credit = credit;

      that._resource = resource;
      that._tags = allTags;
      that._pickFeaturesResource = pickFeaturesResource;
      that._pickFeaturesTags = allPickFeaturesTags;

      return true;
    });
  };

  /**
   * Gets the credits to be displayed when a given tile is displayed.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level;
   * @returns {Credit[]} The credits to be displayed when the tile is displayed.
   *
   * @exception {DeveloperError} <code>getTileCredits</code> must not be called before the imagery provider is ready.
   */
  UrlTemplateImageryProvider.prototype.getTileCredits = function (x, y, level) {
    //>>includeStart('debug', pragmas.debug);
    if (!this.ready) {
      throw new DeveloperError(
        "getTileCredits must not be called before the imagery provider is ready."
      );
    }
    //>>includeEnd('debug');
    return undefined;
  };

  /**
   * Requests the image for a given tile.  This function should
   * not be called before {@link UrlTemplateImageryProvider#ready} returns true.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level.
   * @param {Request} [request] The request object. Intended for internal use only.
   * @returns {Promise.<ImageryTypes>|undefined} A promise for the image that will resolve when the image is available, or
   *          undefined if there are too many active requests to the server, and the request should be retried later.
   */
  UrlTemplateImageryProvider.prototype.requestImage = function (
    x,
    y,
    level,
    request
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!this.ready) {
      throw new DeveloperError(
        "requestImage must not be called before the imagery provider is ready."
      );
    }
    //>>includeEnd('debug');
    return ImageryProvider.loadImage(
      this,
      buildImageResource(this, x, y, level, request)
    );
  };

  /**
   * Asynchronously determines what features, if any, are located at a given longitude and latitude within
   * a tile.  This function should not be called before {@link ImageryProvider#ready} returns true.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level.
   * @param {Number} longitude The longitude at which to pick features.
   * @param {Number} latitude  The latitude at which to pick features.
   * @return {Promise.<ImageryLayerFeatureInfo[]>|undefined} A promise for the picked features that will resolve when the asynchronous
   *                   picking completes.  The resolved value is an array of {@link ImageryLayerFeatureInfo}
   *                   instances.  The array may be empty if no features are found at the given location.
   *                   It may also be undefined if picking is not supported.
   */
  UrlTemplateImageryProvider.prototype.pickFeatures = function (
    x,
    y,
    level,
    longitude,
    latitude
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!this.ready) {
      throw new DeveloperError(
        "pickFeatures must not be called before the imagery provider is ready."
      );
    }
    //>>includeEnd('debug');

    if (
      !this.enablePickFeatures ||
      !defined(this._pickFeaturesResource) ||
      this._getFeatureInfoFormats.length === 0
    ) {
      return undefined;
    }

    let formatIndex = 0;

    const that = this;

    function handleResponse(format, data) {
      return format.callback(data);
    }

    function doRequest() {
      if (formatIndex >= that._getFeatureInfoFormats.length) {
        // No valid formats, so no features picked.
        return Promise.resolve([]);
      }

      const format = that._getFeatureInfoFormats[formatIndex];
      const resource = buildPickFeaturesResource(
        that,
        x,
        y,
        level,
        longitude,
        latitude,
        format.format
      );

      ++formatIndex;

      if (format.type === "json") {
        return resource.fetchJson().then(format.callback).catch(doRequest);
      } else if (format.type === "xml") {
        return resource.fetchXML().then(format.callback).catch(doRequest);
      } else if (format.type === "text" || format.type === "html") {
        return resource.fetchText().then(format.callback).catch(doRequest);
      }
      return resource
        .fetch({
          responseType: format.format,
        })
        .then(handleResponse.bind(undefined, format))
        .catch(doRequest);
    }

    return doRequest();
  };

  let degreesScratchComputed = false;
  const degreesScratch = new Rectangle();
  let projectedScratchComputed = false;
  const projectedScratch = new Rectangle();

  function buildImageResource(imageryProvider, x, y, level, request) {
    degreesScratchComputed = false;
    projectedScratchComputed = false;

    const resource = imageryProvider._resource;
    const url = resource.getUrlComponent(true);
    const allTags = imageryProvider._tags;
    const templateValues = {};

    const match = url.match(templateRegex);
    if (defined(match)) {
      match.forEach(function (tag) {
        const key = tag.substring(1, tag.length - 1); //strip {}
        if (defined(allTags[key])) {
          templateValues[key] = allTags[key](imageryProvider, x, y, level);
        }
      });
    }

    return resource.getDerivedResource({
      request: request,
      templateValues: templateValues,
    });
  }

  let ijScratchComputed = false;
  const ijScratch = new Cartesian2();
  let longitudeLatitudeProjectedScratchComputed = false;

  function buildPickFeaturesResource(
    imageryProvider,
    x,
    y,
    level,
    longitude,
    latitude,
    format
  ) {
    degreesScratchComputed = false;
    projectedScratchComputed = false;
    ijScratchComputed = false;
    longitudeLatitudeProjectedScratchComputed = false;

    const resource = imageryProvider._pickFeaturesResource;
    const url = resource.getUrlComponent(true);
    const allTags = imageryProvider._pickFeaturesTags;
    const templateValues = {};
    const match = url.match(templateRegex);
    if (defined(match)) {
      match.forEach(function (tag) {
        const key = tag.substring(1, tag.length - 1); //strip {}
        if (defined(allTags[key])) {
          templateValues[key] = allTags[key](
            imageryProvider,
            x,
            y,
            level,
            longitude,
            latitude,
            format
          );
        }
      });
    }

    return resource.getDerivedResource({
      templateValues: templateValues,
    });
  }

  function padWithZerosIfNecessary(imageryProvider, key, value) {
    if (
      imageryProvider &&
      imageryProvider.urlSchemeZeroPadding &&
      imageryProvider.urlSchemeZeroPadding.hasOwnProperty(key)
    ) {
      const paddingTemplate = imageryProvider.urlSchemeZeroPadding[key];
      if (typeof paddingTemplate === "string") {
        const paddingTemplateWidth = paddingTemplate.length;
        if (paddingTemplateWidth > 1) {
          value =
            value.length >= paddingTemplateWidth
              ? value
              : new Array(
                  paddingTemplateWidth - value.toString().length + 1
                ).join("0") + value;
        }
      }
    }
    return value;
  }

  function xTag(imageryProvider, x, y, level) {
    return padWithZerosIfNecessary(imageryProvider, "{x}", x);
  }

  function reverseXTag(imageryProvider, x, y, level) {
    const reverseX =
      imageryProvider.tilingScheme.getNumberOfXTilesAtLevel(level) - x - 1;
    return padWithZerosIfNecessary(imageryProvider, "{reverseX}", reverseX);
  }

  function yTag(imageryProvider, x, y, level) {
    return padWithZerosIfNecessary(imageryProvider, "{y}", y);
  }

  function reverseYTag(imageryProvider, x, y, level) {
    const reverseY =
      imageryProvider.tilingScheme.getNumberOfYTilesAtLevel(level) - y - 1;
    return padWithZerosIfNecessary(imageryProvider, "{reverseY}", reverseY);
  }

  function reverseZTag(imageryProvider, x, y, level) {
    const maximumLevel = imageryProvider.maximumLevel;
    const reverseZ =
      defined(maximumLevel) && level < maximumLevel
        ? maximumLevel - level - 1
        : level;
    return padWithZerosIfNecessary(imageryProvider, "{reverseZ}", reverseZ);
  }

  function zTag(imageryProvider, x, y, level) {
    return padWithZerosIfNecessary(imageryProvider, "{z}", level);
  }

  function sTag(imageryProvider, x, y, level) {
    const index = (x + y + level) % imageryProvider._subdomains.length;
    return imageryProvider._subdomains[index];
  }

  function computeDegrees(imageryProvider, x, y, level) {
    if (degreesScratchComputed) {
      return;
    }

    imageryProvider.tilingScheme.tileXYToRectangle(x, y, level, degreesScratch);
    degreesScratch.west = CesiumMath.toDegrees(degreesScratch.west);
    degreesScratch.south = CesiumMath.toDegrees(degreesScratch.south);
    degreesScratch.east = CesiumMath.toDegrees(degreesScratch.east);
    degreesScratch.north = CesiumMath.toDegrees(degreesScratch.north);

    degreesScratchComputed = true;
  }

  function westDegreesTag(imageryProvider, x, y, level) {
    computeDegrees(imageryProvider, x, y, level);
    return degreesScratch.west;
  }

  function southDegreesTag(imageryProvider, x, y, level) {
    computeDegrees(imageryProvider, x, y, level);
    return degreesScratch.south;
  }

  function eastDegreesTag(imageryProvider, x, y, level) {
    computeDegrees(imageryProvider, x, y, level);
    return degreesScratch.east;
  }

  function northDegreesTag(imageryProvider, x, y, level) {
    computeDegrees(imageryProvider, x, y, level);
    return degreesScratch.north;
  }

  function computeProjected(imageryProvider, x, y, level) {
    if (projectedScratchComputed) {
      return;
    }

    imageryProvider.tilingScheme.tileXYToNativeRectangle(
      x,
      y,
      level,
      projectedScratch
    );

    projectedScratchComputed = true;
  }

  function westProjectedTag(imageryProvider, x, y, level) {
    computeProjected(imageryProvider, x, y, level);
    return projectedScratch.west;
  }

  function southProjectedTag(imageryProvider, x, y, level) {
    computeProjected(imageryProvider, x, y, level);
    return projectedScratch.south;
  }

  function eastProjectedTag(imageryProvider, x, y, level) {
    computeProjected(imageryProvider, x, y, level);
    return projectedScratch.east;
  }

  function northProjectedTag(imageryProvider, x, y, level) {
    computeProjected(imageryProvider, x, y, level);
    return projectedScratch.north;
  }

  function widthTag(imageryProvider, x, y, level) {
    return imageryProvider.tileWidth;
  }

  function heightTag(imageryProvider, x, y, level) {
    return imageryProvider.tileHeight;
  }

  function iTag(imageryProvider, x, y, level, longitude, latitude, format) {
    computeIJ(imageryProvider, x, y, level, longitude, latitude);
    return ijScratch.x;
  }

  function jTag(imageryProvider, x, y, level, longitude, latitude, format) {
    computeIJ(imageryProvider, x, y, level, longitude, latitude);
    return ijScratch.y;
  }

  function reverseITag(
    imageryProvider,
    x,
    y,
    level,
    longitude,
    latitude,
    format
  ) {
    computeIJ(imageryProvider, x, y, level, longitude, latitude);
    return imageryProvider.tileWidth - ijScratch.x - 1;
  }

  function reverseJTag(
    imageryProvider,
    x,
    y,
    level,
    longitude,
    latitude,
    format
  ) {
    computeIJ(imageryProvider, x, y, level, longitude, latitude);
    return imageryProvider.tileHeight - ijScratch.y - 1;
  }

  const rectangleScratch = new Rectangle();
  const longitudeLatitudeProjectedScratch = new Cartesian3();

  function computeIJ(imageryProvider, x, y, level, longitude, latitude, format) {
    if (ijScratchComputed) {
      return;
    }

    computeLongitudeLatitudeProjected(
      imageryProvider,
      x,
      y,
      level,
      longitude,
      latitude
    );
    const projected = longitudeLatitudeProjectedScratch;

    const rectangle = imageryProvider.tilingScheme.tileXYToNativeRectangle(
      x,
      y,
      level,
      rectangleScratch
    );
    ijScratch.x =
      ((imageryProvider.tileWidth * (projected.x - rectangle.west)) /
        rectangle.width) |
      0;
    ijScratch.y =
      ((imageryProvider.tileHeight * (rectangle.north - projected.y)) /
        rectangle.height) |
      0;
    ijScratchComputed = true;
  }

  function longitudeDegreesTag(
    imageryProvider,
    x,
    y,
    level,
    longitude,
    latitude,
    format
  ) {
    return CesiumMath.toDegrees(longitude);
  }

  function latitudeDegreesTag(
    imageryProvider,
    x,
    y,
    level,
    longitude,
    latitude,
    format
  ) {
    return CesiumMath.toDegrees(latitude);
  }

  function longitudeProjectedTag(
    imageryProvider,
    x,
    y,
    level,
    longitude,
    latitude,
    format
  ) {
    computeLongitudeLatitudeProjected(
      imageryProvider,
      x,
      y,
      level,
      longitude,
      latitude
    );
    return longitudeLatitudeProjectedScratch.x;
  }

  function latitudeProjectedTag(
    imageryProvider,
    x,
    y,
    level,
    longitude,
    latitude,
    format
  ) {
    computeLongitudeLatitudeProjected(
      imageryProvider,
      x,
      y,
      level,
      longitude,
      latitude
    );
    return longitudeLatitudeProjectedScratch.y;
  }

  const cartographicScratch = new Cartographic();

  function computeLongitudeLatitudeProjected(
    imageryProvider,
    x,
    y,
    level,
    longitude,
    latitude,
    format
  ) {
    if (longitudeLatitudeProjectedScratchComputed) {
      return;
    }

    if (imageryProvider.tilingScheme.projection instanceof GeographicProjection) {
      longitudeLatitudeProjectedScratch.x = CesiumMath.toDegrees(longitude);
      longitudeLatitudeProjectedScratch.y = CesiumMath.toDegrees(latitude);
    } else {
      const cartographic = cartographicScratch;
      cartographic.longitude = longitude;
      cartographic.latitude = latitude;
      imageryProvider.tilingScheme.projection.project(
        cartographic,
        longitudeLatitudeProjectedScratch
      );
    }

    longitudeLatitudeProjectedScratchComputed = true;
  }

  function formatTag(imageryProvider, x, y, level, longitude, latitude, format) {
    return format;
  }

  /**
   * @typedef {Object} TileMapServiceImageryProvider.ConstructorOptions
   *
   * Initialization options for the TileMapServiceImageryProvider constructor
   *
   * @property {Resource|String|Promise<Resource>|Promise<String>} [url='.'] Path to image tiles on server.
   * @property {String} [fileExtension='png'] The file extension for images on the server.
   * @property {Credit|String} [credit=''] A credit for the data source, which is displayed on the canvas.
   * @property {Number} [minimumLevel=0] The minimum level-of-detail supported by the imagery provider.  Take care when specifying
   *                 this that the number of tiles at the minimum level is small, such as four or less.  A larger number is likely
   *                 to result in rendering problems.
   * @property {Number} [maximumLevel] The maximum level-of-detail supported by the imagery provider, or undefined if there is no limit.
   * @property {Rectangle} [rectangle=Rectangle.MAX_VALUE] The rectangle, in radians, covered by the image.
   * @property {TilingScheme} [tilingScheme] The tiling scheme specifying how the ellipsoidal
   * surface is broken into tiles.  If this parameter is not provided, a {@link WebMercatorTilingScheme}
   * is used.
   * @property {Ellipsoid} [ellipsoid] The ellipsoid.  If the tilingScheme is specified,
   *                    this parameter is ignored and the tiling scheme's ellipsoid is used instead. If neither
   *                    parameter is specified, the WGS84 ellipsoid is used.
   * @property {Number} [tileWidth=256] Pixel width of image tiles.
   * @property {Number} [tileHeight=256] Pixel height of image tiles.
   * @property {Boolean} [flipXY] Older versions of gdal2tiles.py flipped X and Y values in tilemapresource.xml.
   * Specifying this option will do the same, allowing for loading of these incorrect tilesets.
   */

  /**
   * An imagery provider that provides tiled imagery as generated by
   * {@link http://www.maptiler.org/|MapTiler}, {@link http://www.klokan.cz/projects/gdal2tiles/|GDAL2Tiles}, etc.
   *
   * @alias TileMapServiceImageryProvider
   * @constructor
   * @extends UrlTemplateImageryProvider
   *
   * @param {TileMapServiceImageryProvider.ConstructorOptions} options Object describing initialization options
   *
   * @see ArcGisMapServerImageryProvider
   * @see BingMapsImageryProvider
   * @see GoogleEarthEnterpriseMapsProvider
   * @see OpenStreetMapImageryProvider
   * @see SingleTileImageryProvider
   * @see WebMapServiceImageryProvider
   * @see WebMapTileServiceImageryProvider
   * @see UrlTemplateImageryProvider
   *
   * @example
   * const tms = new Cesium.TileMapServiceImageryProvider({
   *    url : '../images/cesium_maptiler/Cesium_Logo_Color',
   *    fileExtension: 'png',
   *    maximumLevel: 4,
   *    rectangle: new Cesium.Rectangle(
   *        Cesium.Math.toRadians(-120.0),
   *        Cesium.Math.toRadians(20.0),
   *        Cesium.Math.toRadians(-60.0),
   *        Cesium.Math.toRadians(40.0))
   * });
   */
  function TileMapServiceImageryProvider(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    if (!defined(options.url)) {
      throw new DeveloperError("options.url is required.");
    }
    //>>includeEnd('debug');

    const deferred = defer();
    UrlTemplateImageryProvider.call(this, deferred.promise);

    this._tmsResource = undefined;
    this._xmlResource = undefined;
    this._options = options;
    this._deferred = deferred;
    this._metadataError = undefined;

    this._metadataSuccess = this._metadataSuccess.bind(this);
    this._metadataFailure = this._metadataFailure.bind(this);
    this._requestMetadata = this._requestMetadata.bind(this);

    let resource;
    const that = this;
    Promise.resolve(options.url)
      .then(function (url) {
        resource = Resource.createIfNeeded(url);
        resource.appendForwardSlash();

        that._tmsResource = resource;
        that._xmlResource = resource.getDerivedResource({
          url: "tilemapresource.xml",
        });

        that._requestMetadata();
      })
      .catch(function (e) {
        deferred.reject(e);
      });
  }

  if (defined(Object.create)) {
    TileMapServiceImageryProvider.prototype = Object.create(
      UrlTemplateImageryProvider.prototype
    );
    TileMapServiceImageryProvider.prototype.constructor = TileMapServiceImageryProvider;
  }

  TileMapServiceImageryProvider.prototype._requestMetadata = function () {
    // Try to load remaining parameters from XML
    this._xmlResource
      .fetchXML()
      .then(this._metadataSuccess)
      .catch(this._metadataFailure);
  };

  /**
   * Mutates the properties of a given rectangle so it does not extend outside of the given tiling scheme's rectangle
   * @private
   */
  function confineRectangleToTilingScheme(rectangle, tilingScheme) {
    if (rectangle.west < tilingScheme.rectangle.west) {
      rectangle.west = tilingScheme.rectangle.west;
    }
    if (rectangle.east > tilingScheme.rectangle.east) {
      rectangle.east = tilingScheme.rectangle.east;
    }
    if (rectangle.south < tilingScheme.rectangle.south) {
      rectangle.south = tilingScheme.rectangle.south;
    }
    if (rectangle.north > tilingScheme.rectangle.north) {
      rectangle.north = tilingScheme.rectangle.north;
    }
    return rectangle;
  }

  function calculateSafeMinimumDetailLevel(
    tilingScheme,
    rectangle,
    minimumLevel
  ) {
    // Check the number of tiles at the minimum level.  If it's more than four,
    // try requesting the lower levels anyway, because starting at the higher minimum
    // level will cause too many tiles to be downloaded and rendered.
    const swTile = tilingScheme.positionToTileXY(
      Rectangle.southwest(rectangle),
      minimumLevel
    );
    const neTile = tilingScheme.positionToTileXY(
      Rectangle.northeast(rectangle),
      minimumLevel
    );
    const tileCount =
      (Math.abs(neTile.x - swTile.x) + 1) * (Math.abs(neTile.y - swTile.y) + 1);
    if (tileCount > 4) {
      return 0;
    }
    return minimumLevel;
  }

  TileMapServiceImageryProvider.prototype._metadataSuccess = function (xml) {
    const tileFormatRegex = /tileformat/i;
    const tileSetRegex = /tileset/i;
    const tileSetsRegex = /tilesets/i;
    const bboxRegex = /boundingbox/i;
    let format, bbox, tilesets;
    const tilesetsList = []; //list of TileSets
    const xmlResource = this._xmlResource;
    let metadataError = this._metadataError;
    const deferred = this._deferred;
    const requestMetadata = this._requestMetadata;

    // Allowing options properties (already copied to that) to override XML values

    // Iterate XML Document nodes for properties
    const nodeList = xml.childNodes[0].childNodes;
    for (let i = 0; i < nodeList.length; i++) {
      if (tileFormatRegex.test(nodeList.item(i).nodeName)) {
        format = nodeList.item(i);
      } else if (tileSetsRegex.test(nodeList.item(i).nodeName)) {
        tilesets = nodeList.item(i); // Node list of TileSets
        const tileSetNodes = nodeList.item(i).childNodes;
        // Iterate the nodes to find all TileSets
        for (let j = 0; j < tileSetNodes.length; j++) {
          if (tileSetRegex.test(tileSetNodes.item(j).nodeName)) {
            // Add them to tilesets list
            tilesetsList.push(tileSetNodes.item(j));
          }
        }
      } else if (bboxRegex.test(nodeList.item(i).nodeName)) {
        bbox = nodeList.item(i);
      }
    }

    let message;
    if (!defined(tilesets) || !defined(bbox)) {
      message = `Unable to find expected tilesets or bbox attributes in ${xmlResource.url}.`;
      metadataError = TileProviderError.handleError(
        metadataError,
        this,
        this.errorEvent,
        message,
        undefined,
        undefined,
        undefined,
        requestMetadata
      );
      if (!metadataError.retry) {
        deferred.reject(new RuntimeError(message));
      }
      this._metadataError = metadataError;
      return;
    }

    const options = this._options;
    const fileExtension = defaultValue(
      options.fileExtension,
      format.getAttribute("extension")
    );
    const tileWidth = defaultValue(
      options.tileWidth,
      parseInt(format.getAttribute("width"), 10)
    );
    const tileHeight = defaultValue(
      options.tileHeight,
      parseInt(format.getAttribute("height"), 10)
    );
    let minimumLevel = defaultValue(
      options.minimumLevel,
      parseInt(tilesetsList[0].getAttribute("order"), 10)
    );
    const maximumLevel = defaultValue(
      options.maximumLevel,
      parseInt(tilesetsList[tilesetsList.length - 1].getAttribute("order"), 10)
    );
    const tilingSchemeName = tilesets.getAttribute("profile");
    let tilingScheme = options.tilingScheme;

    if (!defined(tilingScheme)) {
      if (
        tilingSchemeName === "geodetic" ||
        tilingSchemeName === "global-geodetic"
      ) {
        tilingScheme = new GeographicTilingScheme({
          ellipsoid: options.ellipsoid,
        });
      } else if (
        tilingSchemeName === "mercator" ||
        tilingSchemeName === "global-mercator"
      ) {
        tilingScheme = new WebMercatorTilingScheme({
          ellipsoid: options.ellipsoid,
        });
      } else {
        message = `${xmlResource.url}specifies an unsupported profile attribute, ${tilingSchemeName}.`;
        metadataError = TileProviderError.handleError(
          metadataError,
          this,
          this.errorEvent,
          message,
          undefined,
          undefined,
          undefined,
          requestMetadata
        );
        if (!metadataError.retry) {
          deferred.reject(new RuntimeError(message));
        }
        this._metadataError = metadataError;
        return;
      }
    }

    // rectangle handling
    let rectangle = Rectangle.clone(options.rectangle);

    if (!defined(rectangle)) {
      let sw;
      let ne;
      let swXY;
      let neXY;

      // In older versions of gdal x and y values were flipped, which is why we check for an option to flip
      // the values here as well. Unfortunately there is no way to autodetect whether flipping is needed.
      const flipXY = defaultValue(options.flipXY, false);
      if (flipXY) {
        swXY = new Cartesian2(
          parseFloat(bbox.getAttribute("miny")),
          parseFloat(bbox.getAttribute("minx"))
        );
        neXY = new Cartesian2(
          parseFloat(bbox.getAttribute("maxy")),
          parseFloat(bbox.getAttribute("maxx"))
        );
      } else {
        swXY = new Cartesian2(
          parseFloat(bbox.getAttribute("minx")),
          parseFloat(bbox.getAttribute("miny"))
        );
        neXY = new Cartesian2(
          parseFloat(bbox.getAttribute("maxx")),
          parseFloat(bbox.getAttribute("maxy"))
        );
      }

      // Determine based on the profile attribute if this tileset was generated by gdal2tiles.py, which
      // uses 'mercator' and 'geodetic' profiles, or by a tool compliant with the TMS standard, which is
      // 'global-mercator' and 'global-geodetic' profiles. In the gdal2Tiles case, X and Y are always in
      // geodetic degrees.
      const isGdal2tiles =
        tilingSchemeName === "geodetic" || tilingSchemeName === "mercator";
      if (
        tilingScheme.projection instanceof GeographicProjection ||
        isGdal2tiles
      ) {
        sw = Cartographic.fromDegrees(swXY.x, swXY.y);
        ne = Cartographic.fromDegrees(neXY.x, neXY.y);
      } else {
        const projection = tilingScheme.projection;
        sw = projection.unproject(swXY);
        ne = projection.unproject(neXY);
      }

      rectangle = new Rectangle(
        sw.longitude,
        sw.latitude,
        ne.longitude,
        ne.latitude
      );
    }

    // The rectangle must not be outside the bounds allowed by the tiling scheme.
    rectangle = confineRectangleToTilingScheme(rectangle, tilingScheme);
    // clamp our minimum detail level to something that isn't going to request a ridiculous number of tiles
    minimumLevel = calculateSafeMinimumDetailLevel(
      tilingScheme,
      rectangle,
      minimumLevel
    );

    const templateResource = this._tmsResource.getDerivedResource({
      url: `{z}/{x}/{reverseY}.${fileExtension}`,
    });

    deferred.resolve({
      url: templateResource,
      tilingScheme: tilingScheme,
      rectangle: rectangle,
      tileWidth: tileWidth,
      tileHeight: tileHeight,
      minimumLevel: minimumLevel,
      maximumLevel: maximumLevel,
      tileDiscardPolicy: options.tileDiscardPolicy,
      credit: options.credit,
    });
  };

  TileMapServiceImageryProvider.prototype._metadataFailure = function (error) {
    // Can't load XML, still allow options and defaults
    const options = this._options;
    const fileExtension = defaultValue(options.fileExtension, "png");
    const tileWidth = defaultValue(options.tileWidth, 256);
    const tileHeight = defaultValue(options.tileHeight, 256);
    const maximumLevel = options.maximumLevel;
    const tilingScheme = defined(options.tilingScheme)
      ? options.tilingScheme
      : new WebMercatorTilingScheme({ ellipsoid: options.ellipsoid });

    let rectangle = defaultValue(options.rectangle, tilingScheme.rectangle);
    // The rectangle must not be outside the bounds allowed by the tiling scheme.
    rectangle = confineRectangleToTilingScheme(rectangle, tilingScheme);

    // make sure we use a safe minimum detail level, so we don't request a ridiculous number of tiles
    const minimumLevel = calculateSafeMinimumDetailLevel(
      tilingScheme,
      rectangle,
      options.minimumLevel
    );

    const templateResource = this._tmsResource.getDerivedResource({
      url: `{z}/{x}/{reverseY}.${fileExtension}`,
    });

    this._deferred.resolve({
      url: templateResource,
      tilingScheme: tilingScheme,
      rectangle: rectangle,
      tileWidth: tileWidth,
      tileHeight: tileHeight,
      minimumLevel: minimumLevel,
      maximumLevel: maximumLevel,
      tileDiscardPolicy: options.tileDiscardPolicy,
      credit: options.credit,
    });
  };

  const trailingSlashRegex$1 = /\/$/;
  const defaultCredit$2 = new Credit(
    '&copy; <a href="https://www.mapbox.com/about/maps/">Mapbox</a> &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> <strong><a href="https://www.mapbox.com/map-feedback/">Improve this map</a></strong>'
  );

  /**
   * @typedef {Object} MapboxImageryProvider.ConstructorOptions
   *
   * Initialization options for the MapboxImageryProvider constructor
   *
   * @property {String} [url='https://api.mapbox.com/v4/'] The Mapbox server url.
   * @property {String} mapId The Mapbox Map ID.
   * @property {String} accessToken The public access token for the imagery.
   * @property {String} [format='png'] The format of the image request.
   * @property {Ellipsoid} [ellipsoid] The ellipsoid.  If not specified, the WGS84 ellipsoid is used.
   * @property {Number} [minimumLevel=0] The minimum level-of-detail supported by the imagery provider.  Take care when specifying
   *                 this that the number of tiles at the minimum level is small, such as four or less.  A larger number is likely
   *                 to result in rendering problems.
   * @property {Number} [maximumLevel] The maximum level-of-detail supported by the imagery provider, or undefined if there is no limit.
   * @property {Rectangle} [rectangle=Rectangle.MAX_VALUE] The rectangle, in radians, covered by the image.
   * @property {Credit|String} [credit] A credit for the data source, which is displayed on the canvas.
   */

  /**
   * Provides tiled imagery hosted by Mapbox.
   *
   * @alias MapboxImageryProvider
   * @constructor
   *
   * @param {MapboxImageryProvider.ConstructorOptions} options Object describing initialization options
   *
   * @example
   * // Mapbox tile provider
   * const mapbox = new Cesium.MapboxImageryProvider({
   *     mapId: 'mapbox.streets',
   *     accessToken: 'thisIsMyAccessToken'
   * });
   *
   * @see {@link https://www.mapbox.com/developers/api/maps/#tiles}
   * @see {@link https://www.mapbox.com/developers/api/#access-tokens}
   */
  function MapboxImageryProvider(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const mapId = options.mapId;
    //>>includeStart('debug', pragmas.debug);
    if (!defined(mapId)) {
      throw new DeveloperError("options.mapId is required.");
    }
    //>>includeEnd('debug');

    const accessToken = options.accessToken;
    //>>includeStart('debug', pragmas.debug);
    if (!defined(accessToken)) {
      throw new DeveloperError("options.accessToken is required.");
    }
    //>>includeEnd('debug');

    /**
     * The default alpha blending value of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultAlpha = undefined;

    /**
     * The default alpha blending value on the night side of the globe of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultNightAlpha = undefined;

    /**
     * The default alpha blending value on the day side of the globe of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultDayAlpha = undefined;

    /**
     * The default brightness of this provider.  1.0 uses the unmodified imagery color.  Less than 1.0
     * makes the imagery darker while greater than 1.0 makes it brighter.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultBrightness = undefined;

    /**
     * The default contrast of this provider.  1.0 uses the unmodified imagery color.  Less than 1.0 reduces
     * the contrast while greater than 1.0 increases it.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultContrast = undefined;

    /**
     * The default hue of this provider in radians. 0.0 uses the unmodified imagery color.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultHue = undefined;

    /**
     * The default saturation of this provider. 1.0 uses the unmodified imagery color. Less than 1.0 reduces the
     * saturation while greater than 1.0 increases it.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultSaturation = undefined;

    /**
     * The default gamma correction to apply to this provider.  1.0 uses the unmodified imagery color.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultGamma = undefined;

    /**
     * The default texture minification filter to apply to this provider.
     *
     * @type {TextureMinificationFilter}
     * @default undefined
     */
    this.defaultMinificationFilter = undefined;

    /**
     * The default texture magnification filter to apply to this provider.
     *
     * @type {TextureMagnificationFilter}
     * @default undefined
     */
    this.defaultMagnificationFilter = undefined;

    const resource = Resource.createIfNeeded(
      defaultValue(options.url, "https://{s}.tiles.mapbox.com/v4/")
    );

    this._mapId = mapId;
    this._accessToken = accessToken;

    let format = defaultValue(options.format, "png");
    if (!/\./.test(format)) {
      format = `.${format}`;
    }
    this._format = format;

    let templateUrl = resource.getUrlComponent();
    if (!trailingSlashRegex$1.test(templateUrl)) {
      templateUrl += "/";
    }
    templateUrl += `${mapId}/{z}/{x}/{y}${this._format}`;
    resource.url = templateUrl;

    resource.setQueryParameters({
      access_token: accessToken,
    });

    let credit;
    if (defined(options.credit)) {
      credit = options.credit;
      if (typeof credit === "string") {
        credit = new Credit(credit);
      }
    } else {
      credit = defaultCredit$2;
    }

    this._resource = resource;
    this._imageryProvider = new UrlTemplateImageryProvider({
      url: resource,
      credit: credit,
      ellipsoid: options.ellipsoid,
      minimumLevel: options.minimumLevel,
      maximumLevel: options.maximumLevel,
      rectangle: options.rectangle,
    });
  }

  Object.defineProperties(MapboxImageryProvider.prototype, {
    /**
     * Gets the URL of the Mapbox server.
     * @memberof MapboxImageryProvider.prototype
     * @type {String}
     * @readonly
     */
    url: {
      get: function () {
        return this._imageryProvider.url;
      },
    },

    /**
     * Gets a value indicating whether or not the provider is ready for use.
     * @memberof MapboxImageryProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    ready: {
      get: function () {
        return this._imageryProvider.ready;
      },
    },

    /**
     * Gets a promise that resolves to true when the provider is ready for use.
     * @memberof MapboxImageryProvider.prototype
     * @type {Promise.<Boolean>}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._imageryProvider.readyPromise;
      },
    },

    /**
     * Gets the rectangle, in radians, of the imagery provided by the instance.  This function should
     * not be called before {@link MapboxImageryProvider#ready} returns true.
     * @memberof MapboxImageryProvider.prototype
     * @type {Rectangle}
     * @readonly
     */
    rectangle: {
      get: function () {
        return this._imageryProvider.rectangle;
      },
    },

    /**
     * Gets the width of each tile, in pixels.  This function should
     * not be called before {@link MapboxImageryProvider#ready} returns true.
     * @memberof MapboxImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    tileWidth: {
      get: function () {
        return this._imageryProvider.tileWidth;
      },
    },

    /**
     * Gets the height of each tile, in pixels.  This function should
     * not be called before {@link MapboxImageryProvider#ready} returns true.
     * @memberof MapboxImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    tileHeight: {
      get: function () {
        return this._imageryProvider.tileHeight;
      },
    },

    /**
     * Gets the maximum level-of-detail that can be requested.  This function should
     * not be called before {@link MapboxImageryProvider#ready} returns true.
     * @memberof MapboxImageryProvider.prototype
     * @type {Number|undefined}
     * @readonly
     */
    maximumLevel: {
      get: function () {
        return this._imageryProvider.maximumLevel;
      },
    },

    /**
     * Gets the minimum level-of-detail that can be requested.  This function should
     * not be called before {@link MapboxImageryProvider#ready} returns true. Generally,
     * a minimum level should only be used when the rectangle of the imagery is small
     * enough that the number of tiles at the minimum level is small.  An imagery
     * provider with more than a few tiles at the minimum level will lead to
     * rendering problems.
     * @memberof MapboxImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    minimumLevel: {
      get: function () {
        return this._imageryProvider.minimumLevel;
      },
    },

    /**
     * Gets the tiling scheme used by the provider.  This function should
     * not be called before {@link MapboxImageryProvider#ready} returns true.
     * @memberof MapboxImageryProvider.prototype
     * @type {TilingScheme}
     * @readonly
     */
    tilingScheme: {
      get: function () {
        return this._imageryProvider.tilingScheme;
      },
    },

    /**
     * Gets the tile discard policy.  If not undefined, the discard policy is responsible
     * for filtering out "missing" tiles via its shouldDiscardImage function.  If this function
     * returns undefined, no tiles are filtered.  This function should
     * not be called before {@link MapboxImageryProvider#ready} returns true.
     * @memberof MapboxImageryProvider.prototype
     * @type {TileDiscardPolicy}
     * @readonly
     */
    tileDiscardPolicy: {
      get: function () {
        return this._imageryProvider.tileDiscardPolicy;
      },
    },

    /**
     * Gets an event that is raised when the imagery provider encounters an asynchronous error..  By subscribing
     * to the event, you will be notified of the error and can potentially recover from it.  Event listeners
     * are passed an instance of {@link TileProviderError}.
     * @memberof MapboxImageryProvider.prototype
     * @type {Event}
     * @readonly
     */
    errorEvent: {
      get: function () {
        return this._imageryProvider.errorEvent;
      },
    },

    /**
     * Gets the credit to display when this imagery provider is active.  Typically this is used to credit
     * the source of the imagery. This function should
     * not be called before {@link MapboxImageryProvider#ready} returns true.
     * @memberof MapboxImageryProvider.prototype
     * @type {Credit}
     * @readonly
     */
    credit: {
      get: function () {
        return this._imageryProvider.credit;
      },
    },

    /**
     * Gets the proxy used by this provider.
     * @memberof MapboxImageryProvider.prototype
     * @type {Proxy}
     * @readonly
     */
    proxy: {
      get: function () {
        return this._imageryProvider.proxy;
      },
    },

    /**
     * Gets a value indicating whether or not the images provided by this imagery provider
     * include an alpha channel.  If this property is false, an alpha channel, if present, will
     * be ignored.  If this property is true, any images without an alpha channel will be treated
     * as if their alpha is 1.0 everywhere.  When this property is false, memory usage
     * and texture upload time are reduced.
     * @memberof MapboxImageryProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    hasAlphaChannel: {
      get: function () {
        return this._imageryProvider.hasAlphaChannel;
      },
    },
  });

  /**
   * Gets the credits to be displayed when a given tile is displayed.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level;
   * @returns {Credit[]} The credits to be displayed when the tile is displayed.
   *
   * @exception {DeveloperError} <code>getTileCredits</code> must not be called before the imagery provider is ready.
   */
  MapboxImageryProvider.prototype.getTileCredits = function (x, y, level) {
    return undefined;
  };

  /**
   * Requests the image for a given tile.  This function should
   * not be called before {@link MapboxImageryProvider#ready} returns true.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level.
   * @param {Request} [request] The request object. Intended for internal use only.
   * @returns {Promise.<ImageryTypes>|undefined} A promise for the image that will resolve when the image is available, or
   *          undefined if there are too many active requests to the server, and the request should be retried later.
   *
   * @exception {DeveloperError} <code>requestImage</code> must not be called before the imagery provider is ready.
   */
  MapboxImageryProvider.prototype.requestImage = function (x, y, level, request) {
    return this._imageryProvider.requestImage(x, y, level, request);
  };

  /**
   * Asynchronously determines what features, if any, are located at a given longitude and latitude within
   * a tile.  This function should not be called before {@link MapboxImageryProvider#ready} returns true.
   * This function is optional, so it may not exist on all ImageryProviders.
   *
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level.
   * @param {Number} longitude The longitude at which to pick features.
   * @param {Number} latitude  The latitude at which to pick features.
   * @return {Promise.<ImageryLayerFeatureInfo[]>|undefined} A promise for the picked features that will resolve when the asynchronous
   *                   picking completes.  The resolved value is an array of {@link ImageryLayerFeatureInfo}
   *                   instances.  The array may be empty if no features are found at the given location.
   *                   It may also be undefined if picking is not supported.
   *
   * @exception {DeveloperError} <code>pickFeatures</code> must not be called before the imagery provider is ready.
   */
  MapboxImageryProvider.prototype.pickFeatures = function (
    x,
    y,
    level,
    longitude,
    latitude
  ) {
    return this._imageryProvider.pickFeatures(x, y, level, longitude, latitude);
  };

  // Exposed for tests
  MapboxImageryProvider._defaultCredit = defaultCredit$2;

  /**
   * @typedef {Object} SingleTileImageryProvider.ConstructorOptions
   *
   * Initialization options for the SingleTileImageryProvider constructor
   *
   * @property {Resource|String} url The url for the tile.
   * @property {Rectangle} [rectangle=Rectangle.MAX_VALUE] The rectangle, in radians, covered by the image.
   * @property {Credit|String} [credit] A credit for the data source, which is displayed on the canvas.
   * @property {Ellipsoid} [ellipsoid] The ellipsoid.  If not specified, the WGS84 ellipsoid is used.
   */

  /**
   * Provides a single, top-level imagery tile.  The single image is assumed to use a
   * {@link GeographicTilingScheme}.
   *
   * @alias SingleTileImageryProvider
   * @constructor
   *
   * @param {SingleTileImageryProvider.ConstructorOptions} options Object describing initialization options
   *
   * @see ArcGisMapServerImageryProvider
   * @see BingMapsImageryProvider
   * @see GoogleEarthEnterpriseMapsProvider
   * @see OpenStreetMapImageryProvider
   * @see TileMapServiceImageryProvider
   * @see WebMapServiceImageryProvider
   * @see WebMapTileServiceImageryProvider
   * @see UrlTemplateImageryProvider
   */
  function SingleTileImageryProvider(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    //>>includeStart('debug', pragmas.debug);
    if (!defined(options.url)) {
      throw new DeveloperError("options.url is required.");
    }
    //>>includeEnd('debug');

    /**
     * The default alpha blending value of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultAlpha = undefined;

    /**
     * The default alpha blending value on the night side of the globe of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultNightAlpha = undefined;

    /**
     * The default alpha blending value on the day side of the globe of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultDayAlpha = undefined;

    /**
     * The default brightness of this provider.  1.0 uses the unmodified imagery color.  Less than 1.0
     * makes the imagery darker while greater than 1.0 makes it brighter.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultBrightness = undefined;

    /**
     * The default contrast of this provider.  1.0 uses the unmodified imagery color.  Less than 1.0 reduces
     * the contrast while greater than 1.0 increases it.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultContrast = undefined;

    /**
     * The default hue of this provider in radians. 0.0 uses the unmodified imagery color.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultHue = undefined;

    /**
     * The default saturation of this provider. 1.0 uses the unmodified imagery color. Less than 1.0 reduces the
     * saturation while greater than 1.0 increases it.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultSaturation = undefined;

    /**
     * The default gamma correction to apply to this provider.  1.0 uses the unmodified imagery color.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultGamma = undefined;

    /**
     * The default texture minification filter to apply to this provider.
     *
     * @type {TextureMinificationFilter}
     * @default undefined
     */
    this.defaultMinificationFilter = undefined;

    /**
     * The default texture magnification filter to apply to this provider.
     *
     * @type {TextureMagnificationFilter}
     * @default undefined
     */
    this.defaultMagnificationFilter = undefined;

    const resource = Resource.createIfNeeded(options.url);

    const rectangle = defaultValue(options.rectangle, Rectangle.MAX_VALUE);
    const tilingScheme = new GeographicTilingScheme({
      rectangle: rectangle,
      numberOfLevelZeroTilesX: 1,
      numberOfLevelZeroTilesY: 1,
      ellipsoid: options.ellipsoid,
    });
    this._tilingScheme = tilingScheme;
    this._resource = resource;
    this._image = undefined;
    this._texture = undefined;
    this._tileWidth = 0;
    this._tileHeight = 0;

    this._errorEvent = new Event();

    this._ready = false;
    this._readyPromise = defer();

    let credit = options.credit;
    if (typeof credit === "string") {
      credit = new Credit(credit);
    }
    this._credit = credit;

    const that = this;
    let error;

    function success(image) {
      that._image = image;
      that._tileWidth = image.width;
      that._tileHeight = image.height;
      that._ready = true;
      that._readyPromise.resolve(true);
      TileProviderError.handleSuccess(that._errorEvent);
    }

    function failure(e) {
      const message = `Failed to load image ${resource.url}.`;
      error = TileProviderError.handleError(
        error,
        that,
        that._errorEvent,
        message,
        0,
        0,
        0,
        doRequest,
        e
      );
      if (!error.retry) {
        that._readyPromise.reject(new RuntimeError(message));
      }
    }

    function doRequest() {
      ImageryProvider.loadImage(null, resource).then(success).catch(failure);
    }

    doRequest();
  }

  Object.defineProperties(SingleTileImageryProvider.prototype, {
    /**
     * Gets the URL of the single, top-level imagery tile.
     * @memberof SingleTileImageryProvider.prototype
     * @type {String}
     * @readonly
     */
    url: {
      get: function () {
        return this._resource.url;
      },
    },

    /**
     * Gets the proxy used by this provider.
     * @memberof SingleTileImageryProvider.prototype
     * @type {Proxy}
     * @readonly
     */
    proxy: {
      get: function () {
        return this._resource.proxy;
      },
    },

    /**
     * Gets the width of each tile, in pixels. This function should
     * not be called before {@link SingleTileImageryProvider#ready} returns true.
     * @memberof SingleTileImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    tileWidth: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "tileWidth must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._tileWidth;
      },
    },

    /**
     * Gets the height of each tile, in pixels.  This function should
     * not be called before {@link SingleTileImageryProvider#ready} returns true.
     * @memberof SingleTileImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    tileHeight: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "tileHeight must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._tileHeight;
      },
    },

    /**
     * Gets the maximum level-of-detail that can be requested.  This function should
     * not be called before {@link SingleTileImageryProvider#ready} returns true.
     * @memberof SingleTileImageryProvider.prototype
     * @type {Number|undefined}
     * @readonly
     */
    maximumLevel: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "maximumLevel must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return 0;
      },
    },

    /**
     * Gets the minimum level-of-detail that can be requested.  This function should
     * not be called before {@link SingleTileImageryProvider#ready} returns true.
     * @memberof SingleTileImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    minimumLevel: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "minimumLevel must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return 0;
      },
    },

    /**
     * Gets the tiling scheme used by this provider.  This function should
     * not be called before {@link SingleTileImageryProvider#ready} returns true.
     * @memberof SingleTileImageryProvider.prototype
     * @type {TilingScheme}
     * @readonly
     */
    tilingScheme: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "tilingScheme must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return this._tilingScheme;
      },
    },

    /**
     * Gets the rectangle, in radians, of the imagery provided by this instance.  This function should
     * not be called before {@link SingleTileImageryProvider#ready} returns true.
     * @memberof SingleTileImageryProvider.prototype
     * @type {Rectangle}
     * @readonly
     */
    rectangle: {
      get: function () {
        return this._tilingScheme.rectangle;
      },
    },

    /**
     * Gets the tile discard policy.  If not undefined, the discard policy is responsible
     * for filtering out "missing" tiles via its shouldDiscardImage function.  If this function
     * returns undefined, no tiles are filtered.  This function should
     * not be called before {@link SingleTileImageryProvider#ready} returns true.
     * @memberof SingleTileImageryProvider.prototype
     * @type {TileDiscardPolicy}
     * @readonly
     */
    tileDiscardPolicy: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "tileDiscardPolicy must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');

        return undefined;
      },
    },

    /**
     * Gets an event that is raised when the imagery provider encounters an asynchronous error.  By subscribing
     * to the event, you will be notified of the error and can potentially recover from it.  Event listeners
     * are passed an instance of {@link TileProviderError}.
     * @memberof SingleTileImageryProvider.prototype
     * @type {Event}
     * @readonly
     */
    errorEvent: {
      get: function () {
        return this._errorEvent;
      },
    },

    /**
     * Gets a value indicating whether or not the provider is ready for use.
     * @memberof SingleTileImageryProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    ready: {
      get: function () {
        return this._ready;
      },
    },

    /**
     * Gets a promise that resolves to true when the provider is ready for use.
     * @memberof SingleTileImageryProvider.prototype
     * @type {Promise.<Boolean>}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._readyPromise.promise;
      },
    },

    /**
     * Gets the credit to display when this imagery provider is active.  Typically this is used to credit
     * the source of the imagery.  This function should not be called before {@link SingleTileImageryProvider#ready} returns true.
     * @memberof SingleTileImageryProvider.prototype
     * @type {Credit}
     * @readonly
     */
    credit: {
      get: function () {
        return this._credit;
      },
    },

    /**
     * Gets a value indicating whether or not the images provided by this imagery provider
     * include an alpha channel.  If this property is false, an alpha channel, if present, will
     * be ignored.  If this property is true, any images without an alpha channel will be treated
     * as if their alpha is 1.0 everywhere.  When this property is false, memory usage
     * and texture upload time are reduced.
     * @memberof SingleTileImageryProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    hasAlphaChannel: {
      get: function () {
        return true;
      },
    },
  });

  /**
   * Gets the credits to be displayed when a given tile is displayed.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level;
   * @returns {Credit[]} The credits to be displayed when the tile is displayed.
   *
   * @exception {DeveloperError} <code>getTileCredits</code> must not be called before the imagery provider is ready.
   */
  SingleTileImageryProvider.prototype.getTileCredits = function (x, y, level) {
    return undefined;
  };

  /**
   * Requests the image for a given tile.  This function should
   * not be called before {@link SingleTileImageryProvider#ready} returns true.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level.
   * @param {Request} [request] The request object. Intended for internal use only.
   * @returns {Promise.<ImageryTypes>|undefined} The resolved image
   *
   * @exception {DeveloperError} <code>requestImage</code> must not be called before the imagery provider is ready.
   */
  SingleTileImageryProvider.prototype.requestImage = function (
    x,
    y,
    level,
    request
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!this._ready) {
      throw new DeveloperError(
        "requestImage must not be called before the imagery provider is ready."
      );
    }
    //>>includeEnd('debug');

    if (!defined(this._image)) {
      return;
    }

    return Promise.resolve(this._image);
  };

  /**
   * Picking features is not currently supported by this imagery provider, so this function simply returns
   * undefined.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level.
   * @param {Number} longitude The longitude at which to pick features.
   * @param {Number} latitude  The latitude at which to pick features.
   * @return {undefined} Undefined since picking is not supported.
   */
  SingleTileImageryProvider.prototype.pickFeatures = function (
    x,
    y,
    level,
    longitude,
    latitude
  ) {
    return undefined;
  };

  /**
   * Provides functionality for ImageryProviders that have time dynamic imagery
   *
   * @alias TimeDynamicImagery
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Clock} options.clock A Clock instance that is used when determining the value for the time dimension. Required when <code>options.times</code> is specified.
   * @param {TimeIntervalCollection} options.times TimeIntervalCollection with its <code>data</code> property being an object containing time dynamic dimension and their values.
   * @param {Function} options.requestImageFunction A function that will request imagery tiles.
   * @param {Function} options.reloadFunction A function that will be called when all imagery tiles need to be reloaded.
   */
  function TimeDynamicImagery(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.clock", options.clock);
    Check.typeOf.object("options.times", options.times);
    Check.typeOf.func(
      "options.requestImageFunction",
      options.requestImageFunction
    );
    Check.typeOf.func("options.reloadFunction", options.reloadFunction);
    //>>includeEnd('debug');

    this._tileCache = {};
    this._tilesRequestedForInterval = [];

    const clock = (this._clock = options.clock);
    this._times = options.times;
    this._requestImageFunction = options.requestImageFunction;
    this._reloadFunction = options.reloadFunction;
    this._currentIntervalIndex = -1;

    clock.onTick.addEventListener(this._clockOnTick, this);
    this._clockOnTick(clock);
  }

  Object.defineProperties(TimeDynamicImagery.prototype, {
    /**
     * Gets or sets a clock that is used to get keep the time used for time dynamic parameters.
     * @memberof TimeDynamicImagery.prototype
     * @type {Clock}
     */
    clock: {
      get: function () {
        return this._clock;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        if (this._clock !== value) {
          this._clock = value;
          this._clockOnTick(value);
          this._reloadFunction();
        }
      },
    },
    /**
     * Gets or sets a time interval collection.
     * @memberof TimeDynamicImagery.prototype
     * @type {TimeIntervalCollection}
     */
    times: {
      get: function () {
        return this._times;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value)) {
          throw new DeveloperError("value is required.");
        }
        //>>includeEnd('debug');

        if (this._times !== value) {
          this._times = value;
          this._clockOnTick(this._clock);
          this._reloadFunction();
        }
      },
    },
    /**
     * Gets the current interval.
     * @memberof TimeDynamicImagery.prototype
     * @type {TimeInterval}
     */
    currentInterval: {
      get: function () {
        return this._times.get(this._currentIntervalIndex);
      },
    },
  });

  /**
   * Gets the tile from the cache if its available.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level.
   * @param {Request} [request] The request object. Intended for internal use only.
   *
   * @returns {Promise.<HTMLImageElement>|undefined} A promise for the image that will resolve when the image is available, or
   *          undefined if the tile is not in the cache.
   */
  TimeDynamicImagery.prototype.getFromCache = function (x, y, level, request) {
    const key = getKey(x, y, level);
    let result;
    const cache = this._tileCache[this._currentIntervalIndex];
    if (defined(cache) && defined(cache[key])) {
      const item = cache[key];
      result = item.promise.catch(function (e) {
        // Set the correct state in case it was cancelled
        request.state = item.request.state;
        throw e;
      });
      delete cache[key];
    }

    return result;
  };

  /**
   * Checks if the next interval is approaching and will start preload the tile if necessary. Otherwise it will
   * just add the tile to a list to preload when we approach the next interval.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level.
   * @param {Request} [request] The request object. Intended for internal use only.
   */
  TimeDynamicImagery.prototype.checkApproachingInterval = function (
    x,
    y,
    level,
    request
  ) {
    const key = getKey(x, y, level);
    const tilesRequestedForInterval = this._tilesRequestedForInterval;

    // If we are approaching an interval, preload this tile in the next interval
    const approachingInterval = getApproachingInterval(this);
    const tile = {
      key: key,
      // Determines priority based on camera distance to the tile.
      // Since the imagery regardless of time will be attached to the same tile we can just steal it.
      priorityFunction: request.priorityFunction,
    };
    if (
      !defined(approachingInterval) ||
      !addToCache(this, tile, approachingInterval)
    ) {
      // Add to recent request list if we aren't approaching and interval or the request was throttled
      tilesRequestedForInterval.push(tile);
    }

    // Don't let the tile list get out of hand
    if (tilesRequestedForInterval.length >= 512) {
      tilesRequestedForInterval.splice(0, 256);
    }
  };

  TimeDynamicImagery.prototype._clockOnTick = function (clock) {
    const time = clock.currentTime;
    const times = this._times;
    const index = times.indexOf(time);
    const currentIntervalIndex = this._currentIntervalIndex;

    if (index !== currentIntervalIndex) {
      // Cancel all outstanding requests and clear out caches not from current time interval
      const currentCache = this._tileCache[currentIntervalIndex];
      for (const t in currentCache) {
        if (currentCache.hasOwnProperty(t)) {
          currentCache[t].request.cancel();
        }
      }
      delete this._tileCache[currentIntervalIndex];
      this._tilesRequestedForInterval = [];

      this._currentIntervalIndex = index;
      this._reloadFunction();

      return;
    }

    const approachingInterval = getApproachingInterval(this);
    if (defined(approachingInterval)) {
      // Start loading recent tiles from end of this._tilesRequestedForInterval
      //  We keep preloading until we hit a throttling limit.
      const tilesRequested = this._tilesRequestedForInterval;
      let success = true;
      while (success) {
        if (tilesRequested.length === 0) {
          break;
        }

        const tile = tilesRequested.pop();
        success = addToCache(this, tile, approachingInterval);
        if (!success) {
          tilesRequested.push(tile);
        }
      }
    }
  };

  function getKey(x, y, level) {
    return `${x}-${y}-${level}`;
  }

  function getKeyElements(key) {
    const s = key.split("-");
    if (s.length !== 3) {
      return undefined;
    }

    return {
      x: Number(s[0]),
      y: Number(s[1]),
      level: Number(s[2]),
    };
  }

  function getApproachingInterval(that) {
    const times = that._times;
    if (!defined(times)) {
      return undefined;
    }
    const clock = that._clock;
    const time = clock.currentTime;
    const isAnimating = clock.canAnimate && clock.shouldAnimate;
    const multiplier = clock.multiplier;

    if (!isAnimating && multiplier !== 0) {
      return undefined;
    }

    let seconds;
    let index = times.indexOf(time);
    if (index < 0) {
      return undefined;
    }

    const interval = times.get(index);
    if (multiplier > 0) {
      // animating forward
      seconds = JulianDate.secondsDifference(interval.stop, time);
      ++index;
    } else {
      //backwards
      seconds = JulianDate.secondsDifference(interval.start, time); // Will be negative
      --index;
    }
    seconds /= multiplier; // Will always be positive

    // Less than 5 wall time seconds
    return index >= 0 && seconds <= 5.0 ? times.get(index) : undefined;
  }

  function addToCache(that, tile, interval) {
    const index = that._times.indexOf(interval.start);
    const tileCache = that._tileCache;
    let intervalTileCache = tileCache[index];
    if (!defined(intervalTileCache)) {
      intervalTileCache = tileCache[index] = {};
    }

    const key = tile.key;
    if (defined(intervalTileCache[key])) {
      return true; // Already in the cache
    }

    const keyElements = getKeyElements(key);
    const request = new Request({
      throttle: false,
      throttleByServer: true,
      type: RequestType$1.IMAGERY,
      priorityFunction: tile.priorityFunction,
    });
    const promise = that._requestImageFunction(
      keyElements.x,
      keyElements.y,
      keyElements.level,
      request,
      interval
    );
    if (!defined(promise)) {
      return false;
    }

    intervalTileCache[key] = {
      promise: promise,
      request: request,
    };

    return true;
  }

  /**
   * EPSG codes known to include reverse axis orders, but are not within 4000-5000.
   *
   * @type {number[]}
   */
  const includesReverseAxis = [
    3034, // ETRS89-extended / LCC Europe
    3035, // ETRS89-extended / LAEA Europe
    3042, // ETRS89 / UTM zone 30N (N-E)
    3043, // ETRS89 / UTM zone 31N (N-E)
    3044, // ETRS89 / UTM zone 32N (N-E)
  ];

  /**
   * EPSG codes known to not include reverse axis orders, and are within 4000-5000.
   *
   * @type {number[]}
   */
  const excludesReverseAxis = [
    4471, // Mayotte
    4559, // French Antilles
  ];

  /**
   * @typedef {Object} WebMapServiceImageryProvider.ConstructorOptions
   *
   * Initialization options for the WebMapServiceImageryProvider constructor
   *
   * @property {Resource|String} url The URL of the WMS service. The URL supports the same keywords as the {@link UrlTemplateImageryProvider}.
   * @property {String} layers The layers to include, separated by commas.
   * @property {Object} [parameters=WebMapServiceImageryProvider.DefaultParameters] Additional parameters to pass to the WMS server in the GetMap URL.
   * @property {Object} [getFeatureInfoParameters=WebMapServiceImageryProvider.GetFeatureInfoDefaultParameters] Additional parameters to pass to the WMS server in the GetFeatureInfo URL.
   * @property {Boolean} [enablePickFeatures=true] If true, {@link WebMapServiceImageryProvider#pickFeatures} will invoke
   *        the GetFeatureInfo operation on the WMS server and return the features included in the response.  If false,
   *        {@link WebMapServiceImageryProvider#pickFeatures} will immediately return undefined (indicating no pickable features)
   *        without communicating with the server.  Set this property to false if you know your WMS server does not support
   *        GetFeatureInfo or if you don't want this provider's features to be pickable. Note that this can be dynamically
   *        overridden by modifying the WebMapServiceImageryProvider#enablePickFeatures property.
   * @property {GetFeatureInfoFormat[]} [getFeatureInfoFormats=WebMapServiceImageryProvider.DefaultGetFeatureInfoFormats] The formats
   *        in which to try WMS GetFeatureInfo requests.
   * @property {Rectangle} [rectangle=Rectangle.MAX_VALUE] The rectangle of the layer.
   * @property {TilingScheme} [tilingScheme=new GeographicTilingScheme()] The tiling scheme to use to divide the world into tiles.
   * @property {Ellipsoid} [ellipsoid] The ellipsoid.  If the tilingScheme is specified,
   *        this parameter is ignored and the tiling scheme's ellipsoid is used instead. If neither
   *        parameter is specified, the WGS84 ellipsoid is used.
   * @property {Number} [tileWidth=256] The width of each tile in pixels.
   * @property {Number} [tileHeight=256] The height of each tile in pixels.
   * @property {Number} [minimumLevel=0] The minimum level-of-detail supported by the imagery provider.  Take care when
   *        specifying this that the number of tiles at the minimum level is small, such as four or less.  A larger number is
   *        likely to result in rendering problems.
   * @property {Number} [maximumLevel] The maximum level-of-detail supported by the imagery provider, or undefined if there is no limit.
   *        If not specified, there is no limit.
   * @property {String} [crs] CRS specification, for use with WMS specification >= 1.3.0.
   * @property {String} [srs] SRS specification, for use with WMS specification 1.1.0 or 1.1.1
   * @property {Credit|String} [credit] A credit for the data source, which is displayed on the canvas.
   * @property {String|String[]} [subdomains='abc'] The subdomains to use for the <code>{s}</code> placeholder in the URL template.
   *                          If this parameter is a single string, each character in the string is a subdomain.  If it is
   *                          an array, each element in the array is a subdomain.
   * @property {Clock} [clock] A Clock instance that is used when determining the value for the time dimension. Required when `times` is specified.
   * @property {TimeIntervalCollection} [times] TimeIntervalCollection with its data property being an object containing time dynamic dimension and their values.
   * @property {Resource|String} [getFeatureInfoUrl] The getFeatureInfo URL of the WMS service. If the property is not defined then we use the property value of url.
   */

  /**
   * Provides tiled imagery hosted by a Web Map Service (WMS) server.
   *
   * @alias WebMapServiceImageryProvider
   * @constructor
   *
   * @param {WebMapServiceImageryProvider.ConstructorOptions} options Object describing initialization options
   *
   * @see ArcGisMapServerImageryProvider
   * @see BingMapsImageryProvider
   * @see GoogleEarthEnterpriseMapsProvider
   * @see OpenStreetMapImageryProvider
   * @see SingleTileImageryProvider
   * @see TileMapServiceImageryProvider
   * @see WebMapTileServiceImageryProvider
   * @see UrlTemplateImageryProvider
   *
   * @see {@link http://resources.esri.com/help/9.3/arcgisserver/apis/rest/|ArcGIS Server REST API}
   * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
   *
   * @example
   * const provider = new Cesium.WebMapServiceImageryProvider({
   *     url : 'https://sampleserver1.arcgisonline.com/ArcGIS/services/Specialty/ESRI_StatesCitiesRivers_USA/MapServer/WMSServer',
   *     layers : '0',
   *     proxy: new Cesium.DefaultProxy('/proxy/')
   * });
   *
   * viewer.imageryLayers.addImageryProvider(provider);
   */
  function WebMapServiceImageryProvider(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    if (!defined(options.url)) {
      throw new DeveloperError("options.url is required.");
    }
    if (!defined(options.layers)) {
      throw new DeveloperError("options.layers is required.");
    }
    //>>includeEnd('debug');

    if (defined(options.times) && !defined(options.clock)) {
      throw new DeveloperError(
        "options.times was specified, so options.clock is required."
      );
    }

    /**
     * The default alpha blending value of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultAlpha = undefined;

    /**
     * The default alpha blending value on the night side of the globe of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultNightAlpha = undefined;

    /**
     * The default alpha blending value on the day side of the globe of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultDayAlpha = undefined;

    /**
     * The default brightness of this provider.  1.0 uses the unmodified imagery color.  Less than 1.0
     * makes the imagery darker while greater than 1.0 makes it brighter.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultBrightness = undefined;

    /**
     * The default contrast of this provider.  1.0 uses the unmodified imagery color.  Less than 1.0 reduces
     * the contrast while greater than 1.0 increases it.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultContrast = undefined;

    /**
     * The default hue of this provider in radians. 0.0 uses the unmodified imagery color.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultHue = undefined;

    /**
     * The default saturation of this provider. 1.0 uses the unmodified imagery color. Less than 1.0 reduces the
     * saturation while greater than 1.0 increases it.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultSaturation = undefined;

    /**
     * The default gamma correction to apply to this provider.  1.0 uses the unmodified imagery color.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultGamma = undefined;

    /**
     * The default texture minification filter to apply to this provider.
     *
     * @type {TextureMinificationFilter}
     * @default undefined
     */
    this.defaultMinificationFilter = undefined;

    /**
     * The default texture magnification filter to apply to this provider.
     *
     * @type {TextureMagnificationFilter}
     * @default undefined
     */
    this.defaultMagnificationFilter = undefined;

    this._getFeatureInfoUrl = defaultValue(
      options.getFeatureInfoUrl,
      options.url
    );

    const resource = Resource.createIfNeeded(options.url);
    const pickFeatureResource = Resource.createIfNeeded(this._getFeatureInfoUrl);

    resource.setQueryParameters(
      WebMapServiceImageryProvider.DefaultParameters,
      true
    );
    pickFeatureResource.setQueryParameters(
      WebMapServiceImageryProvider.GetFeatureInfoDefaultParameters,
      true
    );

    if (defined(options.parameters)) {
      resource.setQueryParameters(objectToLowercase(options.parameters));
    }

    if (defined(options.getFeatureInfoParameters)) {
      pickFeatureResource.setQueryParameters(
        objectToLowercase(options.getFeatureInfoParameters)
      );
    }

    const that = this;
    this._reload = undefined;
    if (defined(options.times)) {
      this._timeDynamicImagery = new TimeDynamicImagery({
        clock: options.clock,
        times: options.times,
        requestImageFunction: function (x, y, level, request, interval) {
          return requestImage$1(that, x, y, level, request, interval);
        },
        reloadFunction: function () {
          if (defined(that._reload)) {
            that._reload();
          }
        },
      });
    }

    const parameters = {};
    parameters.layers = options.layers;
    parameters.bbox =
      "{westProjected},{southProjected},{eastProjected},{northProjected}";
    parameters.width = "{width}";
    parameters.height = "{height}";

    // Use SRS or CRS based on the WMS version.
    if (parseFloat(resource.queryParameters.version) >= 1.3) {
      // Use CRS with 1.3.0 and going forward.
      // For GeographicTilingScheme, use CRS:84 vice EPSG:4326 to specify lon, lat (x, y) ordering for
      // bbox requests.
      parameters.crs = defaultValue(
        options.crs,
        options.tilingScheme &&
          options.tilingScheme.projection instanceof WebMercatorProjection
          ? "EPSG:3857"
          : "CRS:84"
      );

      // The axis order in previous versions of the WMS specifications was to always use easting (x or lon ) and northing (y or
      // lat). WMS 1.3.0 specifies that, depending on the particular CRS, the x axis may or may not be oriented West-to-East,
      // and the y axis may or may not be oriented South-to-North. The WMS portrayal operation shall account for axis order.
      // This affects some of the EPSG codes that were commonly used such as ESPG:4326. The current implementation
      // makes sure that coordinates passed to the server (as part of the GetMap BBOX parameter) as well as those advertised
      // in the capabilities document reflect the inverse axe orders for EPSG codes between 4000 and 5000.
      //  - Taken from Section 9.1.3 of https://download.osgeo.org/mapserver/docs/MapServer-56.pdf
      const parts = parameters.crs.split(":");
      if (parts[0] === "EPSG" && parts.length === 2) {
        const code = Number(parts[1]);
        if (
          (code >= 4000 && code < 5000 && !excludesReverseAxis.includes(code)) ||
          includesReverseAxis.includes(code)
        ) {
          parameters.bbox =
            "{southProjected},{westProjected},{northProjected},{eastProjected}";
        }
      }
    } else {
      // SRS for WMS 1.1.0 or 1.1.1.
      parameters.srs = defaultValue(
        options.srs,
        options.tilingScheme &&
          options.tilingScheme.projection instanceof WebMercatorProjection
          ? "EPSG:3857"
          : "EPSG:4326"
      );
    }

    resource.setQueryParameters(parameters, true);
    pickFeatureResource.setQueryParameters(parameters, true);

    const pickFeatureParams = {
      query_layers: options.layers,
      info_format: "{format}",
    };
    // use correct pixel coordinate identifier based on version
    if (parseFloat(pickFeatureResource.queryParameters.version) >= 1.3) {
      pickFeatureParams.i = "{i}";
      pickFeatureParams.j = "{j}";
    } else {
      pickFeatureParams.x = "{i}";
      pickFeatureParams.y = "{j}";
    }
    pickFeatureResource.setQueryParameters(pickFeatureParams, true);

    this._resource = resource;
    this._pickFeaturesResource = pickFeatureResource;
    this._layers = options.layers;

    // Let UrlTemplateImageryProvider do the actual URL building.
    this._tileProvider = new UrlTemplateImageryProvider({
      url: resource,
      pickFeaturesUrl: pickFeatureResource,
      tilingScheme: defaultValue(
        options.tilingScheme,
        new GeographicTilingScheme({ ellipsoid: options.ellipsoid })
      ),
      rectangle: options.rectangle,
      tileWidth: options.tileWidth,
      tileHeight: options.tileHeight,
      minimumLevel: options.minimumLevel,
      maximumLevel: options.maximumLevel,
      subdomains: options.subdomains,
      tileDiscardPolicy: options.tileDiscardPolicy,
      credit: options.credit,
      getFeatureInfoFormats: defaultValue(
        options.getFeatureInfoFormats,
        WebMapServiceImageryProvider.DefaultGetFeatureInfoFormats
      ),
      enablePickFeatures: options.enablePickFeatures,
    });
  }

  function requestImage$1(imageryProvider, col, row, level, request, interval) {
    const dynamicIntervalData = defined(interval) ? interval.data : undefined;
    const tileProvider = imageryProvider._tileProvider;

    if (defined(dynamicIntervalData)) {
      // We set the query parameters within the tile provider, because it is managing the query.
      tileProvider._resource.setQueryParameters(dynamicIntervalData);
    }
    return tileProvider.requestImage(col, row, level, request);
  }

  function pickFeatures(
    imageryProvider,
    x,
    y,
    level,
    longitude,
    latitude,
    interval
  ) {
    const dynamicIntervalData = defined(interval) ? interval.data : undefined;
    const tileProvider = imageryProvider._tileProvider;

    if (defined(dynamicIntervalData)) {
      // We set the query parameters within the tile provider, because it is managing the query.
      tileProvider._pickFeaturesResource.setQueryParameters(dynamicIntervalData);
    }
    return tileProvider.pickFeatures(x, y, level, longitude, latitude);
  }

  Object.defineProperties(WebMapServiceImageryProvider.prototype, {
    /**
     * Gets the URL of the WMS server.
     * @memberof WebMapServiceImageryProvider.prototype
     * @type {String}
     * @readonly
     */
    url: {
      get: function () {
        return this._resource._url;
      },
    },

    /**
     * Gets the proxy used by this provider.
     * @memberof WebMapServiceImageryProvider.prototype
     * @type {Proxy}
     * @readonly
     */
    proxy: {
      get: function () {
        return this._resource.proxy;
      },
    },

    /**
     * Gets the names of the WMS layers, separated by commas.
     * @memberof WebMapServiceImageryProvider.prototype
     * @type {String}
     * @readonly
     */
    layers: {
      get: function () {
        return this._layers;
      },
    },

    /**
     * Gets the width of each tile, in pixels. This function should
     * not be called before {@link WebMapServiceImageryProvider#ready} returns true.
     * @memberof WebMapServiceImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    tileWidth: {
      get: function () {
        return this._tileProvider.tileWidth;
      },
    },

    /**
     * Gets the height of each tile, in pixels.  This function should
     * not be called before {@link WebMapServiceImageryProvider#ready} returns true.
     * @memberof WebMapServiceImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    tileHeight: {
      get: function () {
        return this._tileProvider.tileHeight;
      },
    },

    /**
     * Gets the maximum level-of-detail that can be requested.  This function should
     * not be called before {@link WebMapServiceImageryProvider#ready} returns true.
     * @memberof WebMapServiceImageryProvider.prototype
     * @type {Number|undefined}
     * @readonly
     */
    maximumLevel: {
      get: function () {
        return this._tileProvider.maximumLevel;
      },
    },

    /**
     * Gets the minimum level-of-detail that can be requested.  This function should
     * not be called before {@link WebMapServiceImageryProvider#ready} returns true.
     * @memberof WebMapServiceImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    minimumLevel: {
      get: function () {
        return this._tileProvider.minimumLevel;
      },
    },

    /**
     * Gets the tiling scheme used by this provider.  This function should
     * not be called before {@link WebMapServiceImageryProvider#ready} returns true.
     * @memberof WebMapServiceImageryProvider.prototype
     * @type {TilingScheme}
     * @readonly
     */
    tilingScheme: {
      get: function () {
        return this._tileProvider.tilingScheme;
      },
    },

    /**
     * Gets the rectangle, in radians, of the imagery provided by this instance.  This function should
     * not be called before {@link WebMapServiceImageryProvider#ready} returns true.
     * @memberof WebMapServiceImageryProvider.prototype
     * @type {Rectangle}
     * @readonly
     */
    rectangle: {
      get: function () {
        return this._tileProvider.rectangle;
      },
    },

    /**
     * Gets the tile discard policy.  If not undefined, the discard policy is responsible
     * for filtering out "missing" tiles via its shouldDiscardImage function.  If this function
     * returns undefined, no tiles are filtered.  This function should
     * not be called before {@link WebMapServiceImageryProvider#ready} returns true.
     * @memberof WebMapServiceImageryProvider.prototype
     * @type {TileDiscardPolicy}
     * @readonly
     */
    tileDiscardPolicy: {
      get: function () {
        return this._tileProvider.tileDiscardPolicy;
      },
    },

    /**
     * Gets an event that is raised when the imagery provider encounters an asynchronous error.  By subscribing
     * to the event, you will be notified of the error and can potentially recover from it.  Event listeners
     * are passed an instance of {@link TileProviderError}.
     * @memberof WebMapServiceImageryProvider.prototype
     * @type {Event}
     * @readonly
     */
    errorEvent: {
      get: function () {
        return this._tileProvider.errorEvent;
      },
    },

    /**
     * Gets a value indicating whether or not the provider is ready for use.
     * @memberof WebMapServiceImageryProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    ready: {
      get: function () {
        return this._tileProvider.ready;
      },
    },

    /**
     * Gets a promise that resolves to true when the provider is ready for use.
     * @memberof WebMapServiceImageryProvider.prototype
     * @type {Promise.<Boolean>}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._tileProvider.readyPromise;
      },
    },

    /**
     * Gets the credit to display when this imagery provider is active.  Typically this is used to credit
     * the source of the imagery.  This function should not be called before {@link WebMapServiceImageryProvider#ready} returns true.
     * @memberof WebMapServiceImageryProvider.prototype
     * @type {Credit}
     * @readonly
     */
    credit: {
      get: function () {
        return this._tileProvider.credit;
      },
    },

    /**
     * Gets a value indicating whether or not the images provided by this imagery provider
     * include an alpha channel.  If this property is false, an alpha channel, if present, will
     * be ignored.  If this property is true, any images without an alpha channel will be treated
     * as if their alpha is 1.0 everywhere.  When this property is false, memory usage
     * and texture upload time are reduced.
     * @memberof WebMapServiceImageryProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    hasAlphaChannel: {
      get: function () {
        return this._tileProvider.hasAlphaChannel;
      },
    },

    /**
     * Gets or sets a value indicating whether feature picking is enabled.  If true, {@link WebMapServiceImageryProvider#pickFeatures} will
     * invoke the <code>GetFeatureInfo</code> service on the WMS server and attempt to interpret the features included in the response.  If false,
     * {@link WebMapServiceImageryProvider#pickFeatures} will immediately return undefined (indicating no pickable
     * features) without communicating with the server.  Set this property to false if you know your data
     * source does not support picking features or if you don't want this provider's features to be pickable.
     * @memberof WebMapServiceImageryProvider.prototype
     * @type {Boolean}
     * @default true
     */
    enablePickFeatures: {
      get: function () {
        return this._tileProvider.enablePickFeatures;
      },
      set: function (enablePickFeatures) {
        this._tileProvider.enablePickFeatures = enablePickFeatures;
      },
    },

    /**
     * Gets or sets a clock that is used to get keep the time used for time dynamic parameters.
     * @memberof WebMapServiceImageryProvider.prototype
     * @type {Clock}
     */
    clock: {
      get: function () {
        return this._timeDynamicImagery.clock;
      },
      set: function (value) {
        this._timeDynamicImagery.clock = value;
      },
    },
    /**
     * Gets or sets a time interval collection that is used to get time dynamic parameters. The data of each
     * TimeInterval is an object containing the keys and values of the properties that are used during
     * tile requests.
     * @memberof WebMapServiceImageryProvider.prototype
     * @type {TimeIntervalCollection}
     */
    times: {
      get: function () {
        return this._timeDynamicImagery.times;
      },
      set: function (value) {
        this._timeDynamicImagery.times = value;
      },
    },

    /**
     * Gets the getFeatureInfo URL of the WMS server.
     * @memberof WebMapServiceImageryProvider.prototype
     * @type {Resource|String}
     * @readonly
     */
    getFeatureInfoUrl: {
      get: function () {
        return this._getFeatureInfoUrl;
      },
    },
  });

  /**
   * Gets the credits to be displayed when a given tile is displayed.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level;
   * @returns {Credit[]} The credits to be displayed when the tile is displayed.
   *
   * @exception {DeveloperError} <code>getTileCredits</code> must not be called before the imagery provider is ready.
   */
  WebMapServiceImageryProvider.prototype.getTileCredits = function (x, y, level) {
    return this._tileProvider.getTileCredits(x, y, level);
  };

  /**
   * Requests the image for a given tile.  This function should
   * not be called before {@link WebMapServiceImageryProvider#ready} returns true.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level.
   * @param {Request} [request] The request object. Intended for internal use only.
   * @returns {Promise.<ImageryTypes>|undefined} A promise for the image that will resolve when the image is available, or
   *          undefined if there are too many active requests to the server, and the request should be retried later.
   *
   * @exception {DeveloperError} <code>requestImage</code> must not be called before the imagery provider is ready.
   */
  WebMapServiceImageryProvider.prototype.requestImage = function (
    x,
    y,
    level,
    request
  ) {
    let result;
    const timeDynamicImagery = this._timeDynamicImagery;
    let currentInterval;

    // Try and load from cache
    if (defined(timeDynamicImagery)) {
      currentInterval = timeDynamicImagery.currentInterval;
      result = timeDynamicImagery.getFromCache(x, y, level, request);
    }

    // Couldn't load from cache
    if (!defined(result)) {
      result = requestImage$1(this, x, y, level, request, currentInterval);
    }

    // If we are approaching an interval, preload this tile in the next interval
    if (defined(result) && defined(timeDynamicImagery)) {
      timeDynamicImagery.checkApproachingInterval(x, y, level, request);
    }

    return result;
  };

  /**
   * Asynchronously determines what features, if any, are located at a given longitude and latitude within
   * a tile.  This function should not be called before {@link ImageryProvider#ready} returns true.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level.
   * @param {Number} longitude The longitude at which to pick features.
   * @param {Number} latitude  The latitude at which to pick features.
   * @return {Promise.<ImageryLayerFeatureInfo[]>|undefined} A promise for the picked features that will resolve when the asynchronous
   *                   picking completes.  The resolved value is an array of {@link ImageryLayerFeatureInfo}
   *                   instances.  The array may be empty if no features are found at the given location.
   *
   * @exception {DeveloperError} <code>pickFeatures</code> must not be called before the imagery provider is ready.
   */
  WebMapServiceImageryProvider.prototype.pickFeatures = function (
    x,
    y,
    level,
    longitude,
    latitude
  ) {
    const timeDynamicImagery = this._timeDynamicImagery;
    const currentInterval = defined(timeDynamicImagery)
      ? timeDynamicImagery.currentInterval
      : undefined;

    return pickFeatures(this, x, y, level, longitude, latitude, currentInterval);
  };

  /**
   * The default parameters to include in the WMS URL to obtain images.  The values are as follows:
   *    service=WMS
   *    version=1.1.1
   *    request=GetMap
   *    styles=
   *    format=image/jpeg
   *
   * @constant
   * @type {Object}
   */
  WebMapServiceImageryProvider.DefaultParameters = Object.freeze({
    service: "WMS",
    version: "1.1.1",
    request: "GetMap",
    styles: "",
    format: "image/jpeg",
  });

  /**
   * The default parameters to include in the WMS URL to get feature information.  The values are as follows:
   *     service=WMS
   *     version=1.1.1
   *     request=GetFeatureInfo
   *
   * @constant
   * @type {Object}
   */
  WebMapServiceImageryProvider.GetFeatureInfoDefaultParameters = Object.freeze({
    service: "WMS",
    version: "1.1.1",
    request: "GetFeatureInfo",
  });

  WebMapServiceImageryProvider.DefaultGetFeatureInfoFormats = Object.freeze([
    Object.freeze(new GetFeatureInfoFormat("json", "application/json")),
    Object.freeze(new GetFeatureInfoFormat("xml", "text/xml")),
    Object.freeze(new GetFeatureInfoFormat("text", "text/html")),
  ]);

  function objectToLowercase(obj) {
    const result = {};
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        result[key.toLowerCase()] = obj[key];
      }
    }
    return result;
  }

  const defaultParameters = Object.freeze({
    service: "WMTS",
    version: "1.0.0",
    request: "GetTile",
  });

  /**
   * @typedef {Object} WebMapTileServiceImageryProvider.ConstructorOptions
   *
   * Initialization options for the WebMapTileServiceImageryProvider constructor
   *
   * @property {Resource|String} url The base URL for the WMTS GetTile operation (for KVP-encoded requests) or the tile-URL template (for RESTful requests). The tile-URL template should contain the following variables: &#123;style&#125;, &#123;TileMatrixSet&#125;, &#123;TileMatrix&#125;, &#123;TileRow&#125;, &#123;TileCol&#125;. The first two are optional if actual values are hardcoded or not required by the server. The &#123;s&#125; keyword may be used to specify subdomains.
   * @property {String} [format='image/jpeg'] The MIME type for images to retrieve from the server.
   * @property {String} layer The layer name for WMTS requests.
   * @property {String} style The style name for WMTS requests.
   * @property {String} tileMatrixSetID The identifier of the TileMatrixSet to use for WMTS requests.
   * @property {Array} [tileMatrixLabels] A list of identifiers in the TileMatrix to use for WMTS requests, one per TileMatrix level.
   * @property {Clock} [clock] A Clock instance that is used when determining the value for the time dimension. Required when `times` is specified.
   * @property {TimeIntervalCollection} [times] TimeIntervalCollection with its <code>data</code> property being an object containing time dynamic dimension and their values.
   * @property {Object} [dimensions] A object containing static dimensions and their values.
   * @property {Number} [tileWidth=256] The tile width in pixels.
   * @property {Number} [tileHeight=256] The tile height in pixels.
   * @property {TilingScheme} [tilingScheme] The tiling scheme corresponding to the organization of the tiles in the TileMatrixSet.
   * @property {Rectangle} [rectangle=Rectangle.MAX_VALUE] The rectangle covered by the layer.
   * @property {Number} [minimumLevel=0] The minimum level-of-detail supported by the imagery provider.
   * @property {Number} [maximumLevel] The maximum level-of-detail supported by the imagery provider, or undefined if there is no limit.
   * @property {Ellipsoid} [ellipsoid] The ellipsoid.  If not specified, the WGS84 ellipsoid is used.
   * @property {Credit|String} [credit] A credit for the data source, which is displayed on the canvas.
   * @property {String|String[]} [subdomains='abc'] The subdomains to use for the <code>{s}</code> placeholder in the URL template.
   *                          If this parameter is a single string, each character in the string is a subdomain.  If it is
   *                          an array, each element in the array is a subdomain.
   */

  /**
   * Provides tiled imagery served by {@link http://www.opengeospatial.org/standards/wmts|WMTS 1.0.0} compliant servers.
   * This provider supports HTTP KVP-encoded and RESTful GetTile requests, but does not yet support the SOAP encoding.
   *
   * @alias WebMapTileServiceImageryProvider
   * @constructor
   *
   * @param {WebMapTileServiceImageryProvider.ConstructorOptions} options Object describing initialization options
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Web%20Map%20Tile%20Service%20with%20Time.html|Cesium Sandcastle Web Map Tile Service with Time Demo}
   *
   * @example
   * // Example 1. USGS shaded relief tiles (KVP)
   * const shadedRelief1 = new Cesium.WebMapTileServiceImageryProvider({
   *     url : 'http://basemap.nationalmap.gov/arcgis/rest/services/USGSShadedReliefOnly/MapServer/WMTS',
   *     layer : 'USGSShadedReliefOnly',
   *     style : 'default',
   *     format : 'image/jpeg',
   *     tileMatrixSetID : 'default028mm',
   *     // tileMatrixLabels : ['default028mm:0', 'default028mm:1', 'default028mm:2' ...],
   *     maximumLevel: 19,
   *     credit : new Cesium.Credit('U. S. Geological Survey')
   * });
   * viewer.imageryLayers.addImageryProvider(shadedRelief1);
   *
   * @example
   * // Example 2. USGS shaded relief tiles (RESTful)
   * const shadedRelief2 = new Cesium.WebMapTileServiceImageryProvider({
   *     url : 'http://basemap.nationalmap.gov/arcgis/rest/services/USGSShadedReliefOnly/MapServer/WMTS/tile/1.0.0/USGSShadedReliefOnly/{Style}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.jpg',
   *     layer : 'USGSShadedReliefOnly',
   *     style : 'default',
   *     format : 'image/jpeg',
   *     tileMatrixSetID : 'default028mm',
   *     maximumLevel: 19,
   *     credit : new Cesium.Credit('U. S. Geological Survey')
   * });
   * viewer.imageryLayers.addImageryProvider(shadedRelief2);
   *
   * @example
   * // Example 3. NASA time dynamic weather data (RESTful)
   * const times = Cesium.TimeIntervalCollection.fromIso8601({
   *     iso8601: '2015-07-30/2017-06-16/P1D',
   *     dataCallback: function dataCallback(interval, index) {
   *         return {
   *             Time: Cesium.JulianDate.toIso8601(interval.start)
   *         };
   *     }
   * });
   * const weather = new Cesium.WebMapTileServiceImageryProvider({
   *     url : 'https://gibs.earthdata.nasa.gov/wmts/epsg4326/best/AMSR2_Snow_Water_Equivalent/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png',
   *     layer : 'AMSR2_Snow_Water_Equivalent',
   *     style : 'default',
   *     tileMatrixSetID : '2km',
   *     maximumLevel : 5,
   *     format : 'image/png',
   *     clock: clock,
   *     times: times,
   *     credit : new Cesium.Credit('NASA Global Imagery Browse Services for EOSDIS')
   * });
   * viewer.imageryLayers.addImageryProvider(weather);
   *
   * @see ArcGisMapServerImageryProvider
   * @see BingMapsImageryProvider
   * @see GoogleEarthEnterpriseMapsProvider
   * @see OpenStreetMapImageryProvider
   * @see SingleTileImageryProvider
   * @see TileMapServiceImageryProvider
   * @see WebMapServiceImageryProvider
   * @see UrlTemplateImageryProvider
   */
  function WebMapTileServiceImageryProvider(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    if (!defined(options.url)) {
      throw new DeveloperError("options.url is required.");
    }
    if (!defined(options.layer)) {
      throw new DeveloperError("options.layer is required.");
    }
    if (!defined(options.style)) {
      throw new DeveloperError("options.style is required.");
    }
    if (!defined(options.tileMatrixSetID)) {
      throw new DeveloperError("options.tileMatrixSetID is required.");
    }
    if (defined(options.times) && !defined(options.clock)) {
      throw new DeveloperError(
        "options.times was specified, so options.clock is required."
      );
    }
    //>>includeEnd('debug');

    /**
     * The default alpha blending value of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultAlpha = undefined;

    /**
     * The default alpha blending value on the night side of the globe of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultNightAlpha = undefined;

    /**
     * The default alpha blending value on the day side of the globe of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultDayAlpha = undefined;

    /**
     * The default brightness of this provider.  1.0 uses the unmodified imagery color.  Less than 1.0
     * makes the imagery darker while greater than 1.0 makes it brighter.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultBrightness = undefined;

    /**
     * The default contrast of this provider.  1.0 uses the unmodified imagery color.  Less than 1.0 reduces
     * the contrast while greater than 1.0 increases it.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultContrast = undefined;

    /**
     * The default hue of this provider in radians. 0.0 uses the unmodified imagery color.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultHue = undefined;

    /**
     * The default saturation of this provider. 1.0 uses the unmodified imagery color. Less than 1.0 reduces the
     * saturation while greater than 1.0 increases it.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultSaturation = undefined;

    /**
     * The default gamma correction to apply to this provider.  1.0 uses the unmodified imagery color.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultGamma = undefined;

    /**
     * The default texture minification filter to apply to this provider.
     *
     * @type {TextureMinificationFilter}
     * @default undefined
     */
    this.defaultMinificationFilter = undefined;

    /**
     * The default texture magnification filter to apply to this provider.
     *
     * @type {TextureMagnificationFilter}
     * @default undefined
     */
    this.defaultMagnificationFilter = undefined;

    const resource = Resource.createIfNeeded(options.url);

    const style = options.style;
    const tileMatrixSetID = options.tileMatrixSetID;
    const url = resource.url;

    const bracketMatch = url.match(/{/g);
    if (
      !defined(bracketMatch) ||
      (bracketMatch.length === 1 && /{s}/.test(url))
    ) {
      resource.setQueryParameters(defaultParameters);
      this._useKvp = true;
    } else {
      const templateValues = {
        style: style,
        Style: style,
        TileMatrixSet: tileMatrixSetID,
      };

      resource.setTemplateValues(templateValues);
      this._useKvp = false;
    }

    this._resource = resource;
    this._layer = options.layer;
    this._style = style;
    this._tileMatrixSetID = tileMatrixSetID;
    this._tileMatrixLabels = options.tileMatrixLabels;
    this._format = defaultValue(options.format, "image/jpeg");
    this._tileDiscardPolicy = options.tileDiscardPolicy;

    this._tilingScheme = defined(options.tilingScheme)
      ? options.tilingScheme
      : new WebMercatorTilingScheme({ ellipsoid: options.ellipsoid });
    this._tileWidth = defaultValue(options.tileWidth, 256);
    this._tileHeight = defaultValue(options.tileHeight, 256);

    this._minimumLevel = defaultValue(options.minimumLevel, 0);
    this._maximumLevel = options.maximumLevel;

    this._rectangle = defaultValue(
      options.rectangle,
      this._tilingScheme.rectangle
    );
    this._dimensions = options.dimensions;

    const that = this;
    this._reload = undefined;
    if (defined(options.times)) {
      this._timeDynamicImagery = new TimeDynamicImagery({
        clock: options.clock,
        times: options.times,
        requestImageFunction: function (x, y, level, request, interval) {
          return requestImage(that, x, y, level, request, interval);
        },
        reloadFunction: function () {
          if (defined(that._reload)) {
            that._reload();
          }
        },
      });
    }

    this._readyPromise = Promise.resolve(true);

    // Check the number of tiles at the minimum level.  If it's more than four,
    // throw an exception, because starting at the higher minimum
    // level will cause too many tiles to be downloaded and rendered.
    const swTile = this._tilingScheme.positionToTileXY(
      Rectangle.southwest(this._rectangle),
      this._minimumLevel
    );
    const neTile = this._tilingScheme.positionToTileXY(
      Rectangle.northeast(this._rectangle),
      this._minimumLevel
    );
    const tileCount =
      (Math.abs(neTile.x - swTile.x) + 1) * (Math.abs(neTile.y - swTile.y) + 1);
    //>>includeStart('debug', pragmas.debug);
    if (tileCount > 4) {
      throw new DeveloperError(
        `The imagery provider's rectangle and minimumLevel indicate that there are ${tileCount} tiles at the minimum level. Imagery providers with more than four tiles at the minimum level are not supported.`
      );
    }
    //>>includeEnd('debug');

    this._errorEvent = new Event();

    const credit = options.credit;
    this._credit = typeof credit === "string" ? new Credit(credit) : credit;

    this._subdomains = options.subdomains;
    if (Array.isArray(this._subdomains)) {
      this._subdomains = this._subdomains.slice();
    } else if (defined(this._subdomains) && this._subdomains.length > 0) {
      this._subdomains = this._subdomains.split("");
    } else {
      this._subdomains = ["a", "b", "c"];
    }
  }

  function requestImage(imageryProvider, col, row, level, request, interval) {
    const labels = imageryProvider._tileMatrixLabels;
    const tileMatrix = defined(labels) ? labels[level] : level.toString();
    const subdomains = imageryProvider._subdomains;
    const staticDimensions = imageryProvider._dimensions;
    const dynamicIntervalData = defined(interval) ? interval.data : undefined;

    let resource;
    let templateValues;
    if (!imageryProvider._useKvp) {
      templateValues = {
        TileMatrix: tileMatrix,
        TileRow: row.toString(),
        TileCol: col.toString(),
        s: subdomains[(col + row + level) % subdomains.length],
      };

      resource = imageryProvider._resource.getDerivedResource({
        request: request,
      });
      resource.setTemplateValues(templateValues);

      if (defined(staticDimensions)) {
        resource.setTemplateValues(staticDimensions);
      }

      if (defined(dynamicIntervalData)) {
        resource.setTemplateValues(dynamicIntervalData);
      }
    } else {
      // build KVP request
      let query = {};
      query.tilematrix = tileMatrix;
      query.layer = imageryProvider._layer;
      query.style = imageryProvider._style;
      query.tilerow = row;
      query.tilecol = col;
      query.tilematrixset = imageryProvider._tileMatrixSetID;
      query.format = imageryProvider._format;

      if (defined(staticDimensions)) {
        query = combine$2(query, staticDimensions);
      }

      if (defined(dynamicIntervalData)) {
        query = combine$2(query, dynamicIntervalData);
      }

      templateValues = {
        s: subdomains[(col + row + level) % subdomains.length],
      };

      resource = imageryProvider._resource.getDerivedResource({
        queryParameters: query,
        request: request,
      });
      resource.setTemplateValues(templateValues);
    }

    return ImageryProvider.loadImage(imageryProvider, resource);
  }

  Object.defineProperties(WebMapTileServiceImageryProvider.prototype, {
    /**
     * Gets the URL of the service hosting the imagery.
     * @memberof WebMapTileServiceImageryProvider.prototype
     * @type {String}
     * @readonly
     */
    url: {
      get: function () {
        return this._resource.url;
      },
    },

    /**
     * Gets the proxy used by this provider.
     * @memberof WebMapTileServiceImageryProvider.prototype
     * @type {Proxy}
     * @readonly
     */
    proxy: {
      get: function () {
        return this._resource.proxy;
      },
    },

    /**
     * Gets the width of each tile, in pixels. This function should
     * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true.
     * @memberof WebMapTileServiceImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    tileWidth: {
      get: function () {
        return this._tileWidth;
      },
    },

    /**
     * Gets the height of each tile, in pixels.  This function should
     * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true.
     * @memberof WebMapTileServiceImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    tileHeight: {
      get: function () {
        return this._tileHeight;
      },
    },

    /**
     * Gets the maximum level-of-detail that can be requested.  This function should
     * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true.
     * @memberof WebMapTileServiceImageryProvider.prototype
     * @type {Number|undefined}
     * @readonly
     */
    maximumLevel: {
      get: function () {
        return this._maximumLevel;
      },
    },

    /**
     * Gets the minimum level-of-detail that can be requested.  This function should
     * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true.
     * @memberof WebMapTileServiceImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    minimumLevel: {
      get: function () {
        return this._minimumLevel;
      },
    },

    /**
     * Gets the tiling scheme used by this provider.  This function should
     * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true.
     * @memberof WebMapTileServiceImageryProvider.prototype
     * @type {TilingScheme}
     * @readonly
     */
    tilingScheme: {
      get: function () {
        return this._tilingScheme;
      },
    },

    /**
     * Gets the rectangle, in radians, of the imagery provided by this instance.  This function should
     * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true.
     * @memberof WebMapTileServiceImageryProvider.prototype
     * @type {Rectangle}
     * @readonly
     */
    rectangle: {
      get: function () {
        return this._rectangle;
      },
    },

    /**
     * Gets the tile discard policy.  If not undefined, the discard policy is responsible
     * for filtering out "missing" tiles via its shouldDiscardImage function.  If this function
     * returns undefined, no tiles are filtered.  This function should
     * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true.
     * @memberof WebMapTileServiceImageryProvider.prototype
     * @type {TileDiscardPolicy}
     * @readonly
     */
    tileDiscardPolicy: {
      get: function () {
        return this._tileDiscardPolicy;
      },
    },

    /**
     * Gets an event that is raised when the imagery provider encounters an asynchronous error.  By subscribing
     * to the event, you will be notified of the error and can potentially recover from it.  Event listeners
     * are passed an instance of {@link TileProviderError}.
     * @memberof WebMapTileServiceImageryProvider.prototype
     * @type {Event}
     * @readonly
     */
    errorEvent: {
      get: function () {
        return this._errorEvent;
      },
    },

    /**
     * Gets the mime type of images returned by this imagery provider.
     * @memberof WebMapTileServiceImageryProvider.prototype
     * @type {String}
     * @readonly
     */
    format: {
      get: function () {
        return this._format;
      },
    },

    /**
     * Gets a value indicating whether or not the provider is ready for use.
     * @memberof WebMapTileServiceImageryProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    ready: {
      value: true,
    },

    /**
     * Gets a promise that resolves to true when the provider is ready for use.
     * @memberof WebMapTileServiceImageryProvider.prototype
     * @type {Promise.<Boolean>}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._readyPromise;
      },
    },

    /**
     * Gets the credit to display when this imagery provider is active.  Typically this is used to credit
     * the source of the imagery.  This function should not be called before {@link WebMapTileServiceImageryProvider#ready} returns true.
     * @memberof WebMapTileServiceImageryProvider.prototype
     * @type {Credit}
     * @readonly
     */
    credit: {
      get: function () {
        return this._credit;
      },
    },

    /**
     * Gets a value indicating whether or not the images provided by this imagery provider
     * include an alpha channel.  If this property is false, an alpha channel, if present, will
     * be ignored.  If this property is true, any images without an alpha channel will be treated
     * as if their alpha is 1.0 everywhere.  When this property is false, memory usage
     * and texture upload time are reduced.
     * @memberof WebMapTileServiceImageryProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    hasAlphaChannel: {
      get: function () {
        return true;
      },
    },
    /**
     * Gets or sets a clock that is used to get keep the time used for time dynamic parameters.
     * @memberof WebMapTileServiceImageryProvider.prototype
     * @type {Clock}
     */
    clock: {
      get: function () {
        return this._timeDynamicImagery.clock;
      },
      set: function (value) {
        this._timeDynamicImagery.clock = value;
      },
    },
    /**
     * Gets or sets a time interval collection that is used to get time dynamic parameters. The data of each
     * TimeInterval is an object containing the keys and values of the properties that are used during
     * tile requests.
     * @memberof WebMapTileServiceImageryProvider.prototype
     * @type {TimeIntervalCollection}
     */
    times: {
      get: function () {
        return this._timeDynamicImagery.times;
      },
      set: function (value) {
        this._timeDynamicImagery.times = value;
      },
    },
    /**
     * Gets or sets an object that contains static dimensions and their values.
     * @memberof WebMapTileServiceImageryProvider.prototype
     * @type {Object}
     */
    dimensions: {
      get: function () {
        return this._dimensions;
      },
      set: function (value) {
        if (this._dimensions !== value) {
          this._dimensions = value;
          if (defined(this._reload)) {
            this._reload();
          }
        }
      },
    },
  });

  /**
   * Gets the credits to be displayed when a given tile is displayed.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level;
   * @returns {Credit[]} The credits to be displayed when the tile is displayed.
   *
   * @exception {DeveloperError} <code>getTileCredits</code> must not be called before the imagery provider is ready.
   */
  WebMapTileServiceImageryProvider.prototype.getTileCredits = function (
    x,
    y,
    level
  ) {
    return undefined;
  };

  /**
   * Requests the image for a given tile.  This function should
   * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level.
   * @param {Request} [request] The request object. Intended for internal use only.
   * @returns {Promise.<ImageryTypes>|undefined} A promise for the image that will resolve when the image is available, or
   *          undefined if there are too many active requests to the server, and the request should be retried later.
   *
   * @exception {DeveloperError} <code>requestImage</code> must not be called before the imagery provider is ready.
   */
  WebMapTileServiceImageryProvider.prototype.requestImage = function (
    x,
    y,
    level,
    request
  ) {
    let result;
    const timeDynamicImagery = this._timeDynamicImagery;
    let currentInterval;

    // Try and load from cache
    if (defined(timeDynamicImagery)) {
      currentInterval = timeDynamicImagery.currentInterval;
      result = timeDynamicImagery.getFromCache(x, y, level, request);
    }

    // Couldn't load from cache
    if (!defined(result)) {
      result = requestImage(this, x, y, level, request, currentInterval);
    }

    // If we are approaching an interval, preload this tile in the next interval
    if (defined(result) && defined(timeDynamicImagery)) {
      timeDynamicImagery.checkApproachingInterval(x, y, level, request);
    }

    return result;
  };

  /**
   * Picking features is not currently supported by this imagery provider, so this function simply returns
   * undefined.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level.
   * @param {Number} longitude The longitude at which to pick features.
   * @param {Number} latitude  The latitude at which to pick features.
   * @return {undefined} Undefined since picking is not supported.
   */
  WebMapTileServiceImageryProvider.prototype.pickFeatures = function (
    x,
    y,
    level,
    longitude,
    latitude
  ) {
    return undefined;
  };

  function createFactory(Type) {
    return function (options) {
      return new Type(options);
    };
  }

  // These values are the list of supported external imagery
  // assets in the Cesium ion beta. They are subject to change.
  const ImageryProviderMapping = {
    ARCGIS_MAPSERVER: createFactory(ArcGisMapServerImageryProvider),
    BING: createFactory(BingMapsImageryProvider),
    GOOGLE_EARTH: createFactory(GoogleEarthEnterpriseMapsProvider),
    MAPBOX: createFactory(MapboxImageryProvider),
    SINGLE_TILE: createFactory(SingleTileImageryProvider),
    TMS: createFactory(TileMapServiceImageryProvider),
    URL_TEMPLATE: createFactory(UrlTemplateImageryProvider),
    WMS: createFactory(WebMapServiceImageryProvider),
    WMTS: createFactory(WebMapTileServiceImageryProvider),
  };

  /**
   * @typedef {Object} IonImageryProvider.ConstructorOptions
   *
   * Initialization options for the TileMapServiceImageryProvider constructor
   *
   * @property {Number} assetId An ion imagery asset ID
   * @property {String} [accessToken=Ion.defaultAccessToken] The access token to use.
   * @property {String|Resource} [server=Ion.defaultServer] The resource to the Cesium ion API server.
   */

  /**
   * Provides tiled imagery using the Cesium ion REST API.
   *
   * @alias IonImageryProvider
   * @constructor
   *
   * @param {IonImageryProvider.ConstructorOptions} options Object describing initialization options
   *
   * @example
   * viewer.imageryLayers.addImageryProvider(new Cesium.IonImageryProvider({ assetId : 23489024 }));
   */
  function IonImageryProvider(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const assetId = options.assetId;
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number("options.assetId", assetId);
    //>>includeEnd('debug');

    /**
     * The default alpha blending value of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultAlpha = undefined;

    /**
     * The default alpha blending value on the night side of the globe of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultNightAlpha = undefined;

    /**
     * The default alpha blending value on the day side of the globe of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultDayAlpha = undefined;

    /**
     * The default brightness of this provider.  1.0 uses the unmodified imagery color.  Less than 1.0
     * makes the imagery darker while greater than 1.0 makes it brighter.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultBrightness = undefined;

    /**
     * The default contrast of this provider.  1.0 uses the unmodified imagery color.  Less than 1.0 reduces
     * the contrast while greater than 1.0 increases it.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultContrast = undefined;

    /**
     * The default hue of this provider in radians. 0.0 uses the unmodified imagery color.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultHue = undefined;

    /**
     * The default saturation of this provider. 1.0 uses the unmodified imagery color. Less than 1.0 reduces the
     * saturation while greater than 1.0 increases it.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultSaturation = undefined;

    /**
     * The default gamma correction to apply to this provider.  1.0 uses the unmodified imagery color.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultGamma = undefined;

    /**
     * The default texture minification filter to apply to this provider.
     *
     * @type {TextureMinificationFilter}
     * @default undefined
     */
    this.defaultMinificationFilter = undefined;

    /**
     * The default texture magnification filter to apply to this provider.
     *
     * @type {TextureMagnificationFilter}
     * @default undefined
     */
    this.defaultMagnificationFilter = undefined;

    this._ready = false;
    this._tileCredits = undefined;
    this._errorEvent = new Event();

    const that = this;
    const endpointResource = IonResource._createEndpointResource(
      assetId,
      options
    );

    // A simple cache to avoid making repeated requests to ion for endpoints we've
    // already retrieved. This exists mainly to support Bing caching to reduce
    // world imagery sessions, but provides a small boost of performance in general
    // if constantly reloading assets
    const cacheKey =
      options.assetId.toString() + options.accessToken + options.server;
    let promise = IonImageryProvider._endpointCache[cacheKey];
    if (!defined(promise)) {
      promise = endpointResource.fetchJson();
      IonImageryProvider._endpointCache[cacheKey] = promise;
    }

    this._readyPromise = promise.then(function (endpoint) {
      if (endpoint.type !== "IMAGERY") {
        return Promise.reject(
          new RuntimeError(`Cesium ion asset ${assetId} is not an imagery asset.`)
        );
      }

      let imageryProvider;
      const externalType = endpoint.externalType;
      if (!defined(externalType)) {
        imageryProvider = new TileMapServiceImageryProvider({
          url: new IonResource(endpoint, endpointResource),
        });
      } else {
        const factory = ImageryProviderMapping[externalType];

        if (!defined(factory)) {
          return Promise.reject(
            new RuntimeError(
              `Unrecognized Cesium ion imagery type: ${externalType}`
            )
          );
        }
        imageryProvider = factory(endpoint.options);
      }

      that._tileCredits = IonResource.getCreditsFromEndpoint(
        endpoint,
        endpointResource
      );

      imageryProvider.errorEvent.addEventListener(function (tileProviderError) {
        //Propagate the errorEvent but set the provider to this instance instead
        //of the inner instance.
        tileProviderError.provider = that;
        that._errorEvent.raiseEvent(tileProviderError);
      });

      that._imageryProvider = imageryProvider;
      return imageryProvider.readyPromise.then(function () {
        that._ready = true;
        return true;
      });
    });
  }

  Object.defineProperties(IonImageryProvider.prototype, {
    /**
     * Gets a value indicating whether or not the provider is ready for use.
     * @memberof IonImageryProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    ready: {
      get: function () {
        return this._ready;
      },
    },

    /**
     * Gets a promise that resolves to true when the provider is ready for use.
     * @memberof IonImageryProvider.prototype
     * @type {Promise.<Boolean>}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._readyPromise;
      },
    },

    /**
     * Gets the rectangle, in radians, of the imagery provided by the instance.  This function should
     * not be called before {@link IonImageryProvider#ready} returns true.
     * @memberof IonImageryProvider.prototype
     * @type {Rectangle}
     * @readonly
     */
    rectangle: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "tileHeight must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');
        return this._imageryProvider.rectangle;
      },
    },

    /**
     * Gets the width of each tile, in pixels.  This function should
     * not be called before {@link IonImageryProvider#ready} returns true.
     * @memberof IonImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    tileWidth: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "tileWidth must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');
        return this._imageryProvider.tileWidth;
      },
    },

    /**
     * Gets the height of each tile, in pixels.  This function should
     * not be called before {@link IonImageryProvider#ready} returns true.
     * @memberof IonImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    tileHeight: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "tileHeight must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');
        return this._imageryProvider.tileHeight;
      },
    },

    /**
     * Gets the maximum level-of-detail that can be requested.  This function should
     * not be called before {@link IonImageryProvider#ready} returns true.
     * @memberof IonImageryProvider.prototype
     * @type {Number|undefined}
     * @readonly
     */
    maximumLevel: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "maximumLevel must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');
        return this._imageryProvider.maximumLevel;
      },
    },

    /**
     * Gets the minimum level-of-detail that can be requested.  This function should
     * not be called before {@link IonImageryProvider#ready} returns true. Generally,
     * a minimum level should only be used when the rectangle of the imagery is small
     * enough that the number of tiles at the minimum level is small.  An imagery
     * provider with more than a few tiles at the minimum level will lead to
     * rendering problems.
     * @memberof IonImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    minimumLevel: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "minimumLevel must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');
        return this._imageryProvider.minimumLevel;
      },
    },

    /**
     * Gets the tiling scheme used by the provider.  This function should
     * not be called before {@link IonImageryProvider#ready} returns true.
     * @memberof IonImageryProvider.prototype
     * @type {TilingScheme}
     * @readonly
     */
    tilingScheme: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "tilingScheme must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');
        return this._imageryProvider.tilingScheme;
      },
    },

    /**
     * Gets the tile discard policy.  If not undefined, the discard policy is responsible
     * for filtering out "missing" tiles via its shouldDiscardImage function.  If this function
     * returns undefined, no tiles are filtered.  This function should
     * not be called before {@link IonImageryProvider#ready} returns true.
     * @memberof IonImageryProvider.prototype
     * @type {TileDiscardPolicy}
     * @readonly
     */
    tileDiscardPolicy: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "tileDiscardPolicy must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');
        return this._imageryProvider.tileDiscardPolicy;
      },
    },

    /**
     * Gets an event that is raised when the imagery provider encounters an asynchronous error.  By subscribing
     * to the event, you will be notified of the error and can potentially recover from it.  Event listeners
     * are passed an instance of {@link TileProviderError}.
     * @memberof IonImageryProvider.prototype
     * @type {Event}
     * @readonly
     */
    errorEvent: {
      get: function () {
        return this._errorEvent;
      },
    },

    /**
     * Gets the credit to display when this imagery provider is active.  Typically this is used to credit
     * the source of the imagery. This function should
     * not be called before {@link IonImageryProvider#ready} returns true.
     * @memberof IonImageryProvider.prototype
     * @type {Credit}
     * @readonly
     */
    credit: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "credit must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');
        return this._imageryProvider.credit;
      },
    },

    /**
     * Gets a value indicating whether or not the images provided by this imagery provider
     * include an alpha channel.  If this property is false, an alpha channel, if present, will
     * be ignored.  If this property is true, any images without an alpha channel will be treated
     * as if their alpha is 1.0 everywhere.  When this property is false, memory usage
     * and texture upload time are reduced.
     * @memberof IonImageryProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    hasAlphaChannel: {
      get: function () {
        //>>includeStart('debug', pragmas.debug);
        if (!this._ready) {
          throw new DeveloperError(
            "hasAlphaChannel must not be called before the imagery provider is ready."
          );
        }
        //>>includeEnd('debug');
        return this._imageryProvider.hasAlphaChannel;
      },

      /**
       * Gets the proxy used by this provider.
       * @memberof IonImageryProvider.prototype
       * @type {Proxy}
       * @readonly
       * @default undefined
       */
      proxy: {
        get: function () {
          return undefined;
        },
      },
    },
  });

  /**
   * Gets the credits to be displayed when a given tile is displayed.
   * @function
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level;
   * @returns {Credit[]} The credits to be displayed when the tile is displayed.
   *
   * @exception {DeveloperError} <code>getTileCredits</code> must not be called before the imagery provider is ready.
   */
  IonImageryProvider.prototype.getTileCredits = function (x, y, level) {
    //>>includeStart('debug', pragmas.debug);
    if (!this._ready) {
      throw new DeveloperError(
        "getTileCredits must not be called before the imagery provider is ready."
      );
    }
    //>>includeEnd('debug');

    const innerCredits = this._imageryProvider.getTileCredits(x, y, level);
    if (!defined(innerCredits)) {
      return this._tileCredits;
    }

    return this._tileCredits.concat(innerCredits);
  };

  /**
   * Requests the image for a given tile.  This function should
   * not be called before {@link IonImageryProvider#ready} returns true.
   * @function
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level.
   * @param {Request} [request] The request object. Intended for internal use only.
   * @returns {Promise.<ImageryTypes>|undefined} A promise for the image that will resolve when the image is available, or
   *          undefined if there are too many active requests to the server, and the request should be retried later.
   *
   * @exception {DeveloperError} <code>requestImage</code> must not be called before the imagery provider is ready.
   */
  IonImageryProvider.prototype.requestImage = function (x, y, level, request) {
    //>>includeStart('debug', pragmas.debug);
    if (!this._ready) {
      throw new DeveloperError(
        "requestImage must not be called before the imagery provider is ready."
      );
    }
    //>>includeEnd('debug');
    return this._imageryProvider.requestImage(x, y, level, request);
  };

  /**
   * Asynchronously determines what features, if any, are located at a given longitude and latitude within
   * a tile.  This function should not be called before {@link IonImageryProvider#ready} returns true.
   * This function is optional, so it may not exist on all ImageryProviders.
   *
   * @function
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level.
   * @param {Number} longitude The longitude at which to pick features.
   * @param {Number} latitude  The latitude at which to pick features.
   * @return {Promise.<ImageryLayerFeatureInfo[]>|undefined} A promise for the picked features that will resolve when the asynchronous
   *                   picking completes.  The resolved value is an array of {@link ImageryLayerFeatureInfo}
   *                   instances.  The array may be empty if no features are found at the given location.
   *                   It may also be undefined if picking is not supported.
   *
   * @exception {DeveloperError} <code>pickFeatures</code> must not be called before the imagery provider is ready.
   */
  IonImageryProvider.prototype.pickFeatures = function (
    x,
    y,
    level,
    longitude,
    latitude
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!this._ready) {
      throw new DeveloperError(
        "pickFeatures must not be called before the imagery provider is ready."
      );
    }
    //>>includeEnd('debug');
    return this._imageryProvider.pickFeatures(x, y, level, longitude, latitude);
  };

  //exposed for testing
  IonImageryProvider._endpointCache = {};

  // Note, these values map directly to ion asset ids.

  /**
   * The types of imagery provided by {@link createWorldImagery}.
   *
   * @enum {Number}
   */
  const IonWorldImageryStyle = {
    /**
     * Aerial imagery.
     *
     * @type {Number}
     * @constant
     */
    AERIAL: 2,

    /**
     * Aerial imagery with a road overlay.
     *
     * @type {Number}
     * @constant
     */
    AERIAL_WITH_LABELS: 3,

    /**
     * Roads without additional imagery.
     *
     * @type {Number}
     * @constant
     */
    ROAD: 4,
  };
  var IonWorldImageryStyle$1 = Object.freeze(IonWorldImageryStyle);

  /**
   *
   * @private
   * @constructor
   */
  function JobTypeBudget(total) {
    /**
     * Total budget, in milliseconds, allowed for one frame
     */
    this._total = total;

    /**
     * Time, in milliseconds, used so far during this frame
     */
    this.usedThisFrame = 0.0;

    /**
     * Time, in milliseconds, that other job types stole this frame
     */
    this.stolenFromMeThisFrame = 0.0;

    /**
     * Indicates if this job type was starved this frame, i.e., a job
     * tried to run but didn't have budget
     */
    this.starvedThisFrame = false;

    /**
     * Indicates if this job was starved last frame.  This prevents it
     * from being stolen from this frame.
     */
    this.starvedLastFrame = false;
  }

  Object.defineProperties(JobTypeBudget.prototype, {
    total: {
      get: function () {
        return this._total;
      },
    },
  });

  /**
   * Engine for time slicing jobs during a frame to amortize work over multiple frames.  This supports:
   * <ul>
   *   <li>
   *     Separate budgets for different job types, e.g., texture, shader program, and buffer creation.  This
   *     allows all job types to make progress each frame.
   *   </li>
   *   <li>
   *     Stealing from other jobs type budgets if they were not exhausted in the previous frame.  This allows
   *     using the entire budget for all job types each frame even if, for example, all the jobs are the same type.
   *   </li>
   *   <li>
   *     Guaranteed progress on all job types each frame, even if it means exceeding the total budget for the frame.
   *     This prevents, for example, several expensive texture uploads over many frames from prevent a shader compile.
   *   </li>
   * </ul>
   *
   * @private
   */
  function JobScheduler(budgets) {
    //>>includeStart('debug', pragmas.debug);
    if (defined(budgets) && budgets.length !== JobType$1.NUMBER_OF_JOB_TYPES) {
      throw new DeveloperError(
        "A budget must be specified for each job type; budgets.length should equal JobType.NUMBER_OF_JOB_TYPES."
      );
    }
    //>>includeEnd('debug');

    // Total for defaults is half of of one frame at 10 fps
    const jobBudgets = new Array(JobType$1.NUMBER_OF_JOB_TYPES);
    jobBudgets[JobType$1.TEXTURE] = new JobTypeBudget(
      defined(budgets) ? budgets[JobType$1.TEXTURE] : 10.0
    );
    // On cache miss, this most likely only allows one shader compile per frame
    jobBudgets[JobType$1.PROGRAM] = new JobTypeBudget(
      defined(budgets) ? budgets[JobType$1.PROGRAM] : 10.0
    );
    jobBudgets[JobType$1.BUFFER] = new JobTypeBudget(
      defined(budgets) ? budgets[JobType$1.BUFFER] : 30.0
    );

    const length = jobBudgets.length;
    let i;

    let totalBudget = 0.0;
    for (i = 0; i < length; ++i) {
      totalBudget += jobBudgets[i].total;
    }

    const executedThisFrame = new Array(length);
    for (i = 0; i < length; ++i) {
      executedThisFrame[i] = false;
    }

    this._totalBudget = totalBudget;
    this._totalUsedThisFrame = 0.0;
    this._budgets = jobBudgets;
    this._executedThisFrame = executedThisFrame;
  }

  // For unit testing
  JobScheduler.getTimestamp = getTimestamp$1;

  Object.defineProperties(JobScheduler.prototype, {
    totalBudget: {
      get: function () {
        return this._totalBudget;
      },
    },
  });

  JobScheduler.prototype.disableThisFrame = function () {
    // Prevent jobs from running this frame
    this._totalUsedThisFrame = this._totalBudget;
  };

  JobScheduler.prototype.resetBudgets = function () {
    const budgets = this._budgets;
    const length = budgets.length;
    for (let i = 0; i < length; ++i) {
      const budget = budgets[i];
      budget.starvedLastFrame = budget.starvedThisFrame;
      budget.starvedThisFrame = false;
      budget.usedThisFrame = 0.0;
      budget.stolenFromMeThisFrame = 0.0;
    }
    this._totalUsedThisFrame = 0.0;
  };

  JobScheduler.prototype.execute = function (job, jobType) {
    const budgets = this._budgets;
    const budget = budgets[jobType];

    // This ensures each job type makes progress each frame by executing at least once
    const progressThisFrame = this._executedThisFrame[jobType];

    if (this._totalUsedThisFrame >= this._totalBudget && progressThisFrame) {
      // No budget left this frame for jobs of any type
      budget.starvedThisFrame = true;
      return false;
    }

    let stolenBudget;

    if (budget.usedThisFrame + budget.stolenFromMeThisFrame >= budget.total) {
      // No budget remaining for jobs of this type. Try to steal from other job types.
      const length = budgets.length;
      let i;
      for (i = 0; i < length; ++i) {
        stolenBudget = budgets[i];

        // Steal from this budget if it has time left and it wasn't starved last fame
        if (
          stolenBudget.usedThisFrame + stolenBudget.stolenFromMeThisFrame <
            stolenBudget.total &&
          !stolenBudget.starvedLastFrame
        ) {
          break;
        }
      }

      if (i === length && progressThisFrame) {
        // No other job types can give up their budget this frame, and
        // this job type already progressed this frame
        return false;
      }

      if (progressThisFrame) {
        // It is considered "starved" even if it executes using stolen time so that
        // next frame, no other job types can steal time from it.
        budget.starvedThisFrame = true;
      }
    }

    const startTime = JobScheduler.getTimestamp();
    job.execute();
    const duration = JobScheduler.getTimestamp() - startTime;

    // Track both time remaining for this job type and all jobs
    // so budget stealing does send us way over the total budget.
    this._totalUsedThisFrame += duration;

    if (stolenBudget) {
      stolenBudget.stolenFromMeThisFrame += duration;
    } else {
      budget.usedThisFrame += duration;
    }
    this._executedThisFrame[jobType] = true;

    return true;
  };

  /**
   * A light source. This type describes an interface and is not intended to be instantiated directly. Together, <code>color</code> and <code>intensity</code> produce a high-dynamic-range light color. <code>intensity</code> can also be used individually to dim or brighten the light without changing the hue.
   *
   * @alias Light
   * @constructor
   *
   * @see DirectionalLight
   * @see SunLight
   */
  function Light() {}

  Object.defineProperties(Light.prototype, {
    /**
     * The color of the light.
     * @memberof Light.prototype
     * @type {Color}
     */
    color: {
      get: DeveloperError.throwInstantiationError,
    },

    /**
     * The intensity controls the strength of the light. <code>intensity</code> has a minimum value of 0.0 and no maximum value.
     * @memberof Light.prototype
     * @type {Number}
     */
    intensity: {
      get: DeveloperError.throwInstantiationError,
    },
  });

  const trailingSlashRegex = /\/$/;
  const defaultCredit$1 = new Credit(
    '&copy; <a href="https://www.mapbox.com/about/maps/">Mapbox</a> &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> <strong><a href="https://www.mapbox.com/map-feedback/">Improve this map</a></strong>'
  );

  /**
   * @typedef {Object} MapboxStyleImageryProvider.ConstructorOptions
   *
   * Initialization options for the MapboxStyleImageryProvider constructor
   *
   * @property {Resource|String} [url='https://api.mapbox.com/styles/v1/'] The Mapbox server url.
   * @property {String} [username='mapbox'] The username of the map account.
   * @property {String} styleId The Mapbox Style ID.
   * @property {String} accessToken The public access token for the imagery.
   * @property {Number} [tilesize=512] The size of the image tiles.
   * @property {Boolean} [scaleFactor] Determines if tiles are rendered at a @2x scale factor.
   * @property {Ellipsoid} [ellipsoid] The ellipsoid.  If not specified, the WGS84 ellipsoid is used.
   * @property {Number} [minimumLevel=0] The minimum level-of-detail supported by the imagery provider.  Take care when specifying
   *                 this that the number of tiles at the minimum level is small, such as four or less.  A larger number is likely
   *                 to result in rendering problems.
   * @property {Number} [maximumLevel] The maximum level-of-detail supported by the imagery provider, or undefined if there is no limit.
   * @property {Rectangle} [rectangle=Rectangle.MAX_VALUE] The rectangle, in radians, covered by the image.
   * @property {Credit|String} [credit] A credit for the data source, which is displayed on the canvas.
   */

  /**
   * Provides tiled imagery hosted by Mapbox.
   *
   * @alias MapboxStyleImageryProvider
   * @constructor
   *
   * @param {MapboxStyleImageryProvider.ConstructorOptions} options Object describing initialization options
   *
   * @example
   * // Mapbox style provider
   * const mapbox = new Cesium.MapboxStyleImageryProvider({
   *     styleId: 'streets-v11',
   *     accessToken: 'thisIsMyAccessToken'
   * });
   *
   * @see {@link https://docs.mapbox.com/api/maps/#styles}
   * @see {@link https://docs.mapbox.com/api/#access-tokens-and-token-scopes}
   */
  function MapboxStyleImageryProvider(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const styleId = options.styleId;
    //>>includeStart('debug', pragmas.debug);
    if (!defined(styleId)) {
      throw new DeveloperError("options.styleId is required.");
    }
    //>>includeEnd('debug');

    const accessToken = options.accessToken;
    //>>includeStart('debug', pragmas.debug);
    if (!defined(accessToken)) {
      throw new DeveloperError("options.accessToken is required.");
    }
    //>>includeEnd('debug');

    /**
     * The default alpha blending value of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultAlpha = undefined;

    /**
     * The default alpha blending value on the night side of the globe of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultNightAlpha = undefined;

    /**
     * The default alpha blending value on the day side of the globe of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultDayAlpha = undefined;

    /**
     * The default brightness of this provider.  1.0 uses the unmodified imagery color.  Less than 1.0
     * makes the imagery darker while greater than 1.0 makes it brighter.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultBrightness = undefined;

    /**
     * The default contrast of this provider.  1.0 uses the unmodified imagery color.  Less than 1.0 reduces
     * the contrast while greater than 1.0 increases it.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultContrast = undefined;

    /**
     * The default hue of this provider in radians. 0.0 uses the unmodified imagery color.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultHue = undefined;

    /**
     * The default saturation of this provider. 1.0 uses the unmodified imagery color. Less than 1.0 reduces the
     * saturation while greater than 1.0 increases it.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultSaturation = undefined;

    /**
     * The default gamma correction to apply to this provider.  1.0 uses the unmodified imagery color.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultGamma = undefined;

    /**
     * The default texture minification filter to apply to this provider.
     *
     * @type {TextureMinificationFilter}
     * @default undefined
     */
    this.defaultMinificationFilter = undefined;

    /**
     * The default texture magnification filter to apply to this provider.
     *
     * @type {TextureMagnificationFilter}
     * @default undefined
     */
    this.defaultMagnificationFilter = undefined;

    const resource = Resource.createIfNeeded(
      defaultValue(options.url, "https://api.mapbox.com/styles/v1/")
    );

    this._styleId = styleId;
    this._accessToken = accessToken;

    const tilesize = defaultValue(options.tilesize, 512);
    this._tilesize = tilesize;

    const username = defaultValue(options.username, "mapbox");
    this._username = username;

    const scaleFactor = defined(options.scaleFactor) ? "@2x" : "";

    let templateUrl = resource.getUrlComponent();
    if (!trailingSlashRegex.test(templateUrl)) {
      templateUrl += "/";
    }
    templateUrl += `${this._username}/${styleId}/tiles/${this._tilesize}/{z}/{x}/{y}${scaleFactor}`;
    resource.url = templateUrl;

    resource.setQueryParameters({
      access_token: accessToken,
    });

    let credit;
    if (defined(options.credit)) {
      credit = options.credit;
      if (typeof credit === "string") {
        credit = new Credit(credit);
      }
    } else {
      credit = defaultCredit$1;
    }

    this._resource = resource;
    this._imageryProvider = new UrlTemplateImageryProvider({
      url: resource,
      credit: credit,
      ellipsoid: options.ellipsoid,
      minimumLevel: options.minimumLevel,
      maximumLevel: options.maximumLevel,
      rectangle: options.rectangle,
    });
  }

  Object.defineProperties(MapboxStyleImageryProvider.prototype, {
    /**
     * Gets the URL of the Mapbox server.
     * @memberof MapboxStyleImageryProvider.prototype
     * @type {String}
     * @readonly
     */
    url: {
      get: function () {
        return this._imageryProvider.url;
      },
    },

    /**
     * Gets a value indicating whether or not the provider is ready for use.
     * @memberof MapboxStyleImageryProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    ready: {
      get: function () {
        return this._imageryProvider.ready;
      },
    },

    /**
     * Gets a promise that resolves to true when the provider is ready for use.
     * @memberof MapboxStyleImageryProvider.prototype
     * @type {Promise.<Boolean>}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._imageryProvider.readyPromise;
      },
    },

    /**
     * Gets the rectangle, in radians, of the imagery provided by the instance.  This function should
     * not be called before {@link MapboxStyleImageryProvider#ready} returns true.
     * @memberof MapboxStyleImageryProvider.prototype
     * @type {Rectangle}
     * @readonly
     */
    rectangle: {
      get: function () {
        return this._imageryProvider.rectangle;
      },
    },

    /**
     * Gets the width of each tile, in pixels.  This function should
     * not be called before {@link MapboxStyleImageryProvider#ready} returns true.
     * @memberof MapboxStyleImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    tileWidth: {
      get: function () {
        return this._imageryProvider.tileWidth;
      },
    },

    /**
     * Gets the height of each tile, in pixels.  This function should
     * not be called before {@link MapboxStyleImageryProvider#ready} returns true.
     * @memberof MapboxStyleImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    tileHeight: {
      get: function () {
        return this._imageryProvider.tileHeight;
      },
    },

    /**
     * Gets the maximum level-of-detail that can be requested.  This function should
     * not be called before {@link MapboxStyleImageryProvider#ready} returns true.
     * @memberof MapboxStyleImageryProvider.prototype
     * @type {Number|undefined}
     * @readonly
     */
    maximumLevel: {
      get: function () {
        return this._imageryProvider.maximumLevel;
      },
    },

    /**
     * Gets the minimum level-of-detail that can be requested.  This function should
     * not be called before {@link MapboxStyleImageryProvider#ready} returns true. Generally,
     * a minimum level should only be used when the rectangle of the imagery is small
     * enough that the number of tiles at the minimum level is small.  An imagery
     * provider with more than a few tiles at the minimum level will lead to
     * rendering problems.
     * @memberof MapboxStyleImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    minimumLevel: {
      get: function () {
        return this._imageryProvider.minimumLevel;
      },
    },

    /**
     * Gets the tiling scheme used by the provider.  This function should
     * not be called before {@link MapboxStyleImageryProvider#ready} returns true.
     * @memberof MapboxStyleImageryProvider.prototype
     * @type {TilingScheme}
     * @readonly
     */
    tilingScheme: {
      get: function () {
        return this._imageryProvider.tilingScheme;
      },
    },

    /**
     * Gets the tile discard policy.  If not undefined, the discard policy is responsible
     * for filtering out "missing" tiles via its shouldDiscardImage function.  If this function
     * returns undefined, no tiles are filtered.  This function should
     * not be called before {@link MapboxStyleImageryProvider#ready} returns true.
     * @memberof MapboxStyleImageryProvider.prototype
     * @type {TileDiscardPolicy}
     * @readonly
     */
    tileDiscardPolicy: {
      get: function () {
        return this._imageryProvider.tileDiscardPolicy;
      },
    },

    /**
     * Gets an event that is raised when the imagery provider encounters an asynchronous error..  By subscribing
     * to the event, you will be notified of the error and can potentially recover from it.  Event listeners
     * are passed an instance of {@link TileProviderError}.
     * @memberof MapboxStyleImageryProvider.prototype
     * @type {Event}
     * @readonly
     */
    errorEvent: {
      get: function () {
        return this._imageryProvider.errorEvent;
      },
    },

    /**
     * Gets the credit to display when this imagery provider is active.  Typically this is used to credit
     * the source of the imagery. This function should
     * not be called before {@link MapboxStyleImageryProvider#ready} returns true.
     * @memberof MapboxStyleImageryProvider.prototype
     * @type {Credit}
     * @readonly
     */
    credit: {
      get: function () {
        return this._imageryProvider.credit;
      },
    },

    /**
     * Gets the proxy used by this provider.
     * @memberof MapboxStyleImageryProvider.prototype
     * @type {Proxy}
     * @readonly
     */
    proxy: {
      get: function () {
        return this._imageryProvider.proxy;
      },
    },

    /**
     * Gets a value indicating whether or not the images provided by this imagery provider
     * include an alpha channel.  If this property is false, an alpha channel, if present, will
     * be ignored.  If this property is true, any images without an alpha channel will be treated
     * as if their alpha is 1.0 everywhere.  When this property is false, memory usage
     * and texture upload time are reduced.
     * @memberof MapboxStyleImageryProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    hasAlphaChannel: {
      get: function () {
        return this._imageryProvider.hasAlphaChannel;
      },
    },
  });

  /**
   * Gets the credits to be displayed when a given tile is displayed.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level;
   * @returns {Credit[]} The credits to be displayed when the tile is displayed.
   *
   * @exception {DeveloperError} <code>getTileCredits</code> must not be called before the imagery provider is ready.
   */
  MapboxStyleImageryProvider.prototype.getTileCredits = function (x, y, level) {
    return undefined;
  };

  /**
   * Requests the image for a given tile.  This function should
   * not be called before {@link MapboxStyleImageryProvider#ready} returns true.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level.
   * @param {Request} [request] The request object. Intended for internal use only.
   * @returns {Promise.<ImageryTypes>|undefined} A promise for the image that will resolve when the image is available, or
   *          undefined if there are too many active requests to the server, and the request should be retried later.
   *
   * @exception {DeveloperError} <code>requestImage</code> must not be called before the imagery provider is ready.
   */
  MapboxStyleImageryProvider.prototype.requestImage = function (
    x,
    y,
    level,
    request
  ) {
    return this._imageryProvider.requestImage(x, y, level, request);
  };

  /**
   * Asynchronously determines what features, if any, are located at a given longitude and latitude within
   * a tile.  This function should not be called before {@link MapboxStyleImageryProvider#ready} returns true.
   * This function is optional, so it may not exist on all ImageryProviders.
   *
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level.
   * @param {Number} longitude The longitude at which to pick features.
   * @param {Number} latitude  The latitude at which to pick features.
   * @return {Promise.<ImageryLayerFeatureInfo[]>|undefined} A promise for the picked features that will resolve when the asynchronous
   *                   picking completes.  The resolved value is an array of {@link ImageryLayerFeatureInfo}
   *                   instances.  The array may be empty if no features are found at the given location.
   *                   It may also be undefined if picking is not supported.
   *
   * @exception {DeveloperError} <code>pickFeatures</code> must not be called before the imagery provider is ready.
   */
  MapboxStyleImageryProvider.prototype.pickFeatures = function (
    x,
    y,
    level,
    longitude,
    latitude
  ) {
    return this._imageryProvider.pickFeatures(x, y, level, longitude, latitude);
  };

  // Exposed for tests
  MapboxStyleImageryProvider._defaultCredit = defaultCredit$1;

  /**
   * Draws the Moon in 3D.
   * @alias Moon
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Boolean} [options.show=true] Determines whether the moon will be rendered.
   * @param {String} [options.textureUrl=buildModuleUrl('Assets/Textures/moonSmall.jpg')] The moon texture.
   * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.MOON] The moon ellipsoid.
   * @param {Boolean} [options.onlySunLighting=true] Use the sun as the only light source.
   *
   *
   * @example
   * scene.moon = new Cesium.Moon();
   *
   * @see Scene#moon
   */
  function Moon(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    let url = options.textureUrl;
    if (!defined(url)) {
      url = buildModuleUrl("Assets/Textures/moonSmall.jpg");
    }

    /**
     * Determines if the moon will be shown.
     *
     * @type {Boolean}
     * @default true
     */
    this.show = defaultValue(options.show, true);

    /**
     * The moon texture.
     * @type {String}
     * @default buildModuleUrl('Assets/Textures/moonSmall.jpg')
     */
    this.textureUrl = url;

    this._ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.MOON);

    /**
     * Use the sun as the only light source.
     * @type {Boolean}
     * @default true
     */
    this.onlySunLighting = defaultValue(options.onlySunLighting, true);

    this._ellipsoidPrimitive = new EllipsoidPrimitive({
      radii: this.ellipsoid.radii,
      material: Material$4.fromType(Material$4.ImageType),
      depthTestEnabled: false,
      _owner: this,
    });
    this._ellipsoidPrimitive.material.translucent = false;

    this._axes = new IauOrientationAxes();
  }

  Object.defineProperties(Moon.prototype, {
    /**
     * Get the ellipsoid that defines the shape of the moon.
     *
     * @memberof Moon.prototype
     *
     * @type {Ellipsoid}
     * @readonly
     *
     * @default {@link Ellipsoid.MOON}
     */
    ellipsoid: {
      get: function () {
        return this._ellipsoid;
      },
    },
  });

  const icrfToFixed = new Matrix3();
  const rotationScratch = new Matrix3();
  const translationScratch = new Cartesian3();
  const scratchCommandList = [];

  /**
   * @private
   */
  Moon.prototype.update = function (frameState) {
    if (!this.show) {
      return;
    }

    const ellipsoidPrimitive = this._ellipsoidPrimitive;
    ellipsoidPrimitive.material.uniforms.image = this.textureUrl;
    ellipsoidPrimitive.onlySunLighting = this.onlySunLighting;

    const date = frameState.time;
    if (!defined(Transforms.computeIcrfToFixedMatrix(date, icrfToFixed))) {
      Transforms.computeTemeToPseudoFixedMatrix(date, icrfToFixed);
    }

    const rotation = this._axes.evaluate(date, rotationScratch);
    Matrix3.transpose(rotation, rotation);
    Matrix3.multiply(icrfToFixed, rotation, rotation);

    const translation = Simon1994PlanetaryPositions.computeMoonPositionInEarthInertialFrame(
      date,
      translationScratch
    );
    Matrix3.multiplyByVector(icrfToFixed, translation, translation);

    Matrix4.fromRotationTranslation(
      rotation,
      translation,
      ellipsoidPrimitive.modelMatrix
    );

    const savedCommandList = frameState.commandList;
    frameState.commandList = scratchCommandList;
    scratchCommandList.length = 0;
    ellipsoidPrimitive.update(frameState);
    frameState.commandList = savedCommandList;
    return scratchCommandList.length === 1 ? scratchCommandList[0] : undefined;
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see Moon#destroy
   */
  Moon.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * moon = moon && moon.destroy();
   *
   * @see Moon#isDestroyed
   */
  Moon.prototype.destroy = function () {
    this._ellipsoidPrimitive =
      this._ellipsoidPrimitive && this._ellipsoidPrimitive.destroy();
    return destroyObject(this);
  };

  /**
   * A {@link TileDiscardPolicy} specifying that tile images should never be discard.
   *
   * @alias NeverTileDiscardPolicy
   * @constructor
   *
   * @see DiscardMissingTileImagePolicy
   */
  function NeverTileDiscardPolicy(options) {}

  /**
   * Determines if the discard policy is ready to process images.
   * @returns {Boolean} True if the discard policy is ready to process images; otherwise, false.
   */
  NeverTileDiscardPolicy.prototype.isReady = function () {
    return true;
  };

  /**
   * Given a tile image, decide whether to discard that image.
   *
   * @param {HTMLImageElement} image An image to test.
   * @returns {Boolean} True if the image should be discarded; otherwise, false.
   */
  NeverTileDiscardPolicy.prototype.shouldDiscardImage = function (image) {
    return false;
  };

  //This file is automatically rebuilt by the Cesium build process.
  var AdjustTranslucentFS = "#ifdef MRT\n\
#extension GL_EXT_draw_buffers : enable\n\
#endif\n\
uniform vec4 u_bgColor;\n\
uniform sampler2D u_depthTexture;\n\
varying vec2 v_textureCoordinates;\n\
void main()\n\
{\n\
if (texture2D(u_depthTexture, v_textureCoordinates).r < 1.0)\n\
{\n\
#ifdef MRT\n\
gl_FragData[0] = u_bgColor;\n\
gl_FragData[1] = vec4(u_bgColor.a);\n\
#else\n\
gl_FragColor = u_bgColor;\n\
#endif\n\
return;\n\
}\n\
discard;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var CompositeOITFS = "uniform sampler2D u_opaque;\n\
uniform sampler2D u_accumulation;\n\
uniform sampler2D u_revealage;\n\
varying vec2 v_textureCoordinates;\n\
void main()\n\
{\n\
vec4 opaque = texture2D(u_opaque, v_textureCoordinates);\n\
vec4 accum = texture2D(u_accumulation, v_textureCoordinates);\n\
float r = texture2D(u_revealage, v_textureCoordinates).r;\n\
#ifdef MRT\n\
vec4 transparent = vec4(accum.rgb / clamp(r, 1e-4, 5e4), accum.a);\n\
#else\n\
vec4 transparent = vec4(accum.rgb / clamp(accum.a, 1e-4, 5e4), r);\n\
#endif\n\
gl_FragColor = (1.0 - transparent.a) * transparent + transparent.a * opaque;\n\
if (opaque != czm_backgroundColor)\n\
{\n\
gl_FragColor.a = 1.0;\n\
}\n\
}\n\
";

  /**
   * @private
   */
  function OIT(context) {
    this._numSamples = 1;
    // We support multipass for the Chrome D3D9 backend and ES 2.0 on mobile.
    this._translucentMultipassSupport = false;
    this._translucentMRTSupport = false;

    const extensionsSupported =
      context.colorBufferFloat && context.depthTexture && context.floatBlend;
    this._translucentMRTSupport = context.drawBuffers && extensionsSupported;
    this._translucentMultipassSupport =
      !this._translucentMRTSupport && extensionsSupported;

    this._opaqueFBO = undefined;
    this._opaqueTexture = undefined;
    this._depthStencilTexture = undefined;

    this._accumulationTexture = undefined;

    this._translucentFBO = new FramebufferManager({
      colorAttachmentsLength: this._translucentMRTSupport ? 2 : 1,
      createColorAttachments: false,
      createDepthAttachments: false,
      depth: true,
    });
    this._alphaFBO = new FramebufferManager({
      createColorAttachments: false,
      createDepthAttachments: false,
      depth: true,
    });

    this._adjustTranslucentFBO = new FramebufferManager({
      colorAttachmentsLength: this._translucentMRTSupport ? 2 : 1,
      createColorAttachments: false,
    });
    this._adjustAlphaFBO = new FramebufferManager({
      createColorAttachments: false,
    });

    this._opaqueClearCommand = new ClearCommand({
      color: new Color(0.0, 0.0, 0.0, 0.0),
      owner: this,
    });
    this._translucentMRTClearCommand = new ClearCommand({
      color: new Color(0.0, 0.0, 0.0, 1.0),
      owner: this,
    });
    this._translucentMultipassClearCommand = new ClearCommand({
      color: new Color(0.0, 0.0, 0.0, 0.0),
      owner: this,
    });
    this._alphaClearCommand = new ClearCommand({
      color: new Color(1.0, 1.0, 1.0, 1.0),
      owner: this,
    });

    this._translucentRenderStateCache = {};
    this._alphaRenderStateCache = {};

    this._compositeCommand = undefined;
    this._adjustTranslucentCommand = undefined;
    this._adjustAlphaCommand = undefined;

    this._viewport = new BoundingRectangle();
    this._rs = undefined;

    this._useScissorTest = false;
    this._scissorRectangle = undefined;

    this._useHDR = false;
  }

  function destroyTextures$1(oit) {
    oit._accumulationTexture =
      oit._accumulationTexture &&
      !oit._accumulationTexture.isDestroyed() &&
      oit._accumulationTexture.destroy();
    oit._revealageTexture =
      oit._revealageTexture &&
      !oit._revealageTexture.isDestroyed() &&
      oit._revealageTexture.destroy();
  }

  function destroyFramebuffers$1(oit) {
    oit._translucentFBO.destroy();
    oit._alphaFBO.destroy();
    oit._adjustTranslucentFBO.destroy();
    oit._adjustAlphaFBO.destroy();
  }

  function destroyResources$2(oit) {
    destroyTextures$1(oit);
    destroyFramebuffers$1(oit);
  }

  function updateTextures$1(oit, context, width, height) {
    destroyTextures$1(oit);

    oit._accumulationTexture = new Texture({
      context: context,
      width: width,
      height: height,
      pixelFormat: PixelFormat$1.RGBA,
      pixelDatatype: PixelDatatype$1.FLOAT,
    });

    // Use zeroed arraybuffer instead of null to initialize texture
    // to workaround Firefox. Only needed for the second color attachment.
    const source = new Float32Array(width * height * 4);
    oit._revealageTexture = new Texture({
      context: context,
      pixelFormat: PixelFormat$1.RGBA,
      pixelDatatype: PixelDatatype$1.FLOAT,
      source: {
        arrayBufferView: source,
        width: width,
        height: height,
      },
      flipY: false,
    });
  }

  function updateFramebuffers$3(oit, context) {
    destroyFramebuffers$1(oit);

    const completeFBO = WebGLConstants$1.FRAMEBUFFER_COMPLETE;
    let supported = true;

    const width = oit._accumulationTexture.width;
    const height = oit._accumulationTexture.height;

    // if MRT is supported, attempt to make an FBO with multiple color attachments
    if (oit._translucentMRTSupport) {
      oit._translucentFBO.setColorTexture(oit._accumulationTexture, 0);
      oit._translucentFBO.setColorTexture(oit._revealageTexture, 1);
      oit._translucentFBO.setDepthStencilTexture(oit._depthStencilTexture);
      oit._translucentFBO.update(context, width, height);

      oit._adjustTranslucentFBO.setColorTexture(oit._accumulationTexture, 0);
      oit._adjustTranslucentFBO.setColorTexture(oit._revealageTexture, 1);
      oit._adjustTranslucentFBO.update(context, width, height);

      if (
        oit._translucentFBO.status !== completeFBO ||
        oit._adjustTranslucentFBO.status !== completeFBO
      ) {
        destroyFramebuffers$1(oit);
        oit._translucentMRTSupport = false;
      }
    }

    // either MRT isn't supported or FBO creation failed, attempt multipass
    if (!oit._translucentMRTSupport) {
      oit._translucentFBO.setColorTexture(oit._accumulationTexture);
      oit._translucentFBO.setDepthStencilTexture(oit._depthStencilTexture);
      oit._translucentFBO.update(context, width, height);

      oit._alphaFBO.setColorTexture(oit._revealageTexture);
      oit._alphaFBO.setDepthStencilTexture(oit._depthStencilTexture);
      oit._alphaFBO.update(context, width, height);

      oit._adjustTranslucentFBO.setColorTexture(oit._accumulationTexture);
      oit._adjustTranslucentFBO.update(context, width, height);

      oit._adjustAlphaFBO.setColorTexture(oit._revealageTexture);
      oit._adjustAlphaFBO.update(context, width, height);

      const translucentComplete = oit._translucentFBO.status === completeFBO;
      const alphaComplete = oit._alphaFBO.status === completeFBO;
      const adjustTranslucentComplete =
        oit._adjustTranslucentFBO.status === completeFBO;
      const adjustAlphaComplete = oit._adjustAlphaFBO.status === completeFBO;
      if (
        !translucentComplete ||
        !alphaComplete ||
        !adjustTranslucentComplete ||
        !adjustAlphaComplete
      ) {
        destroyResources$2(oit);
        oit._translucentMultipassSupport = false;
        supported = false;
      }
    }

    return supported;
  }

  OIT.prototype.update = function (
    context,
    passState,
    framebuffer,
    useHDR,
    numSamples
  ) {
    if (!this.isSupported()) {
      return;
    }

    this._opaqueFBO = framebuffer;
    this._opaqueTexture = framebuffer.getColorTexture(0);
    this._depthStencilTexture = framebuffer.getDepthStencilTexture();

    const width = this._opaqueTexture.width;
    const height = this._opaqueTexture.height;

    const accumulationTexture = this._accumulationTexture;
    const textureChanged =
      !defined(accumulationTexture) ||
      accumulationTexture.width !== width ||
      accumulationTexture.height !== height ||
      useHDR !== this._useHDR;
    const samplesChanged = this._numSamples !== numSamples;

    if (textureChanged || samplesChanged) {
      this._numSamples = numSamples;
      updateTextures$1(this, context, width, height);
    }

    if (
      !defined(this._translucentFBO.framebuffer) ||
      textureChanged ||
      samplesChanged
    ) {
      if (!updateFramebuffers$3(this, context)) {
        // framebuffer creation failed
        return;
      }
    }

    this._useHDR = useHDR;

    const that = this;
    let fs;
    let uniformMap;

    if (!defined(this._compositeCommand)) {
      fs = new ShaderSource({
        sources: [CompositeOITFS],
      });
      if (this._translucentMRTSupport) {
        fs.defines.push("MRT");
      }

      uniformMap = {
        u_opaque: function () {
          return that._opaqueTexture;
        },
        u_accumulation: function () {
          return that._accumulationTexture;
        },
        u_revealage: function () {
          return that._revealageTexture;
        },
      };
      this._compositeCommand = context.createViewportQuadCommand(fs, {
        uniformMap: uniformMap,
        owner: this,
      });
    }

    if (!defined(this._adjustTranslucentCommand)) {
      if (this._translucentMRTSupport) {
        fs = new ShaderSource({
          defines: ["MRT"],
          sources: [AdjustTranslucentFS],
        });

        uniformMap = {
          u_bgColor: function () {
            return that._translucentMRTClearCommand.color;
          },
          u_depthTexture: function () {
            return that._depthStencilTexture;
          },
        };

        this._adjustTranslucentCommand = context.createViewportQuadCommand(fs, {
          uniformMap: uniformMap,
          owner: this,
        });
      } else if (this._translucentMultipassSupport) {
        fs = new ShaderSource({
          sources: [AdjustTranslucentFS],
        });

        uniformMap = {
          u_bgColor: function () {
            return that._translucentMultipassClearCommand.color;
          },
          u_depthTexture: function () {
            return that._depthStencilTexture;
          },
        };

        this._adjustTranslucentCommand = context.createViewportQuadCommand(fs, {
          uniformMap: uniformMap,
          owner: this,
        });

        uniformMap = {
          u_bgColor: function () {
            return that._alphaClearCommand.color;
          },
          u_depthTexture: function () {
            return that._depthStencilTexture;
          },
        };

        this._adjustAlphaCommand = context.createViewportQuadCommand(fs, {
          uniformMap: uniformMap,
          owner: this,
        });
      }
    }

    this._viewport.width = width;
    this._viewport.height = height;

    const useScissorTest = !BoundingRectangle.equals(
      this._viewport,
      passState.viewport
    );
    let updateScissor = useScissorTest !== this._useScissorTest;
    this._useScissorTest = useScissorTest;

    if (!BoundingRectangle.equals(this._scissorRectangle, passState.viewport)) {
      this._scissorRectangle = BoundingRectangle.clone(
        passState.viewport,
        this._scissorRectangle
      );
      updateScissor = true;
    }

    if (
      !defined(this._rs) ||
      !BoundingRectangle.equals(this._viewport, this._rs.viewport) ||
      updateScissor
    ) {
      this._rs = RenderState.fromCache({
        viewport: this._viewport,
        scissorTest: {
          enabled: this._useScissorTest,
          rectangle: this._scissorRectangle,
        },
      });
    }

    if (defined(this._compositeCommand)) {
      this._compositeCommand.renderState = this._rs;
    }

    if (this._adjustTranslucentCommand) {
      this._adjustTranslucentCommand.renderState = this._rs;
    }

    if (defined(this._adjustAlphaCommand)) {
      this._adjustAlphaCommand.renderState = this._rs;
    }
  };

  const translucentMRTBlend = {
    enabled: true,
    color: new Color(0.0, 0.0, 0.0, 0.0),
    equationRgb: BlendEquation$1.ADD,
    equationAlpha: BlendEquation$1.ADD,
    functionSourceRgb: BlendFunction$1.ONE,
    functionDestinationRgb: BlendFunction$1.ONE,
    functionSourceAlpha: BlendFunction$1.ZERO,
    functionDestinationAlpha: BlendFunction$1.ONE_MINUS_SOURCE_ALPHA,
  };

  const translucentColorBlend = {
    enabled: true,
    color: new Color(0.0, 0.0, 0.0, 0.0),
    equationRgb: BlendEquation$1.ADD,
    equationAlpha: BlendEquation$1.ADD,
    functionSourceRgb: BlendFunction$1.ONE,
    functionDestinationRgb: BlendFunction$1.ONE,
    functionSourceAlpha: BlendFunction$1.ONE,
    functionDestinationAlpha: BlendFunction$1.ONE,
  };

  const translucentAlphaBlend = {
    enabled: true,
    color: new Color(0.0, 0.0, 0.0, 0.0),
    equationRgb: BlendEquation$1.ADD,
    equationAlpha: BlendEquation$1.ADD,
    functionSourceRgb: BlendFunction$1.ZERO,
    functionDestinationRgb: BlendFunction$1.ONE_MINUS_SOURCE_ALPHA,
    functionSourceAlpha: BlendFunction$1.ZERO,
    functionDestinationAlpha: BlendFunction$1.ONE_MINUS_SOURCE_ALPHA,
  };

  function getTranslucentRenderState(
    context,
    translucentBlending,
    cache,
    renderState
  ) {
    let translucentState = cache[renderState.id];
    if (!defined(translucentState)) {
      const rs = RenderState.getState(renderState);
      rs.depthMask = false;
      rs.blending = translucentBlending;

      translucentState = RenderState.fromCache(rs);
      cache[renderState.id] = translucentState;
    }

    return translucentState;
  }

  function getTranslucentMRTRenderState(oit, context, renderState) {
    return getTranslucentRenderState(
      context,
      translucentMRTBlend,
      oit._translucentRenderStateCache,
      renderState
    );
  }

  function getTranslucentColorRenderState(oit, context, renderState) {
    return getTranslucentRenderState(
      context,
      translucentColorBlend,
      oit._translucentRenderStateCache,
      renderState
    );
  }

  function getTranslucentAlphaRenderState(oit, context, renderState) {
    return getTranslucentRenderState(
      context,
      translucentAlphaBlend,
      oit._alphaRenderStateCache,
      renderState
    );
  }

  const mrtShaderSource =
    "    vec3 Ci = czm_gl_FragColor.rgb * czm_gl_FragColor.a;\n" +
    "    float ai = czm_gl_FragColor.a;\n" +
    "    float wzi = czm_alphaWeight(ai);\n" +
    "    gl_FragData[0] = vec4(Ci * wzi, ai);\n" +
    "    gl_FragData[1] = vec4(ai * wzi);\n";

  const colorShaderSource =
    "    vec3 Ci = czm_gl_FragColor.rgb * czm_gl_FragColor.a;\n" +
    "    float ai = czm_gl_FragColor.a;\n" +
    "    float wzi = czm_alphaWeight(ai);\n" +
    "    gl_FragColor = vec4(Ci, ai) * wzi;\n";

  const alphaShaderSource =
    "    float ai = czm_gl_FragColor.a;\n" + "    gl_FragColor = vec4(ai);\n";

  function getTranslucentShaderProgram(context, shaderProgram, keyword, source) {
    let shader = context.shaderCache.getDerivedShaderProgram(
      shaderProgram,
      keyword
    );
    if (!defined(shader)) {
      const attributeLocations = shaderProgram._attributeLocations;

      const fs = shaderProgram.fragmentShaderSource.clone();

      fs.sources = fs.sources.map(function (source) {
        source = ShaderSource.replaceMain(source, "czm_translucent_main");
        source = source.replace(/gl_FragColor/g, "czm_gl_FragColor");
        source = source.replace(/\bdiscard\b/g, "czm_discard = true");
        source = source.replace(/czm_phong/g, "czm_translucentPhong");
        return source;
      });

      // Discarding the fragment in main is a workaround for ANGLE D3D9
      // shader compilation errors.

      fs.sources.splice(
        0,
        0,
        `${
        source.indexOf("gl_FragData") !== -1
          ? "#extension GL_EXT_draw_buffers : enable \n"
          : ""
      }vec4 czm_gl_FragColor;\n` + `bool czm_discard = false;\n`
      );

      fs.sources.push(
        `${
        "void main()\n" +
        "{\n" +
        "    czm_translucent_main();\n" +
        "    if (czm_discard)\n" +
        "    {\n" +
        "        discard;\n" +
        "    }\n"
      }${source}}\n`
      );

      shader = context.shaderCache.createDerivedShaderProgram(
        shaderProgram,
        keyword,
        {
          vertexShaderSource: shaderProgram.vertexShaderSource,
          fragmentShaderSource: fs,
          attributeLocations: attributeLocations,
        }
      );
    }

    return shader;
  }

  function getTranslucentMRTShaderProgram(context, shaderProgram) {
    return getTranslucentShaderProgram(
      context,
      shaderProgram,
      "translucentMRT",
      mrtShaderSource
    );
  }

  function getTranslucentColorShaderProgram(context, shaderProgram) {
    return getTranslucentShaderProgram(
      context,
      shaderProgram,
      "translucentMultipass",
      colorShaderSource
    );
  }

  function getTranslucentAlphaShaderProgram(context, shaderProgram) {
    return getTranslucentShaderProgram(
      context,
      shaderProgram,
      "alphaMultipass",
      alphaShaderSource
    );
  }

  OIT.prototype.createDerivedCommands = function (command, context, result) {
    if (!defined(result)) {
      result = {};
    }

    if (this._translucentMRTSupport) {
      let translucentShader;
      let translucentRenderState;
      if (defined(result.translucentCommand)) {
        translucentShader = result.translucentCommand.shaderProgram;
        translucentRenderState = result.translucentCommand.renderState;
      }

      result.translucentCommand = DrawCommand.shallowClone(
        command,
        result.translucentCommand
      );

      if (
        !defined(translucentShader) ||
        result.shaderProgramId !== command.shaderProgram.id
      ) {
        result.translucentCommand.shaderProgram = getTranslucentMRTShaderProgram(
          context,
          command.shaderProgram
        );
        result.translucentCommand.renderState = getTranslucentMRTRenderState(
          this,
          context,
          command.renderState
        );
        result.shaderProgramId = command.shaderProgram.id;
      } else {
        result.translucentCommand.shaderProgram = translucentShader;
        result.translucentCommand.renderState = translucentRenderState;
      }
    } else {
      let colorShader;
      let colorRenderState;
      let alphaShader;
      let alphaRenderState;
      if (defined(result.translucentCommand)) {
        colorShader = result.translucentCommand.shaderProgram;
        colorRenderState = result.translucentCommand.renderState;
        alphaShader = result.alphaCommand.shaderProgram;
        alphaRenderState = result.alphaCommand.renderState;
      }

      result.translucentCommand = DrawCommand.shallowClone(
        command,
        result.translucentCommand
      );
      result.alphaCommand = DrawCommand.shallowClone(
        command,
        result.alphaCommand
      );

      if (
        !defined(colorShader) ||
        result.shaderProgramId !== command.shaderProgram.id
      ) {
        result.translucentCommand.shaderProgram = getTranslucentColorShaderProgram(
          context,
          command.shaderProgram
        );
        result.translucentCommand.renderState = getTranslucentColorRenderState(
          this,
          context,
          command.renderState
        );
        result.alphaCommand.shaderProgram = getTranslucentAlphaShaderProgram(
          context,
          command.shaderProgram
        );
        result.alphaCommand.renderState = getTranslucentAlphaRenderState(
          this,
          context,
          command.renderState
        );
        result.shaderProgramId = command.shaderProgram.id;
      } else {
        result.translucentCommand.shaderProgram = colorShader;
        result.translucentCommand.renderState = colorRenderState;
        result.alphaCommand.shaderProgram = alphaShader;
        result.alphaCommand.renderState = alphaRenderState;
      }
    }

    return result;
  };

  function executeTranslucentCommandsSortedMultipass(
    oit,
    scene,
    executeFunction,
    passState,
    commands,
    invertClassification
  ) {
    let command;
    let derivedCommand;
    let j;

    const context = scene.context;
    const useLogDepth = scene.frameState.useLogDepth;
    const useHdr = scene._hdr;
    const framebuffer = passState.framebuffer;
    const length = commands.length;

    const lightShadowsEnabled = scene.frameState.shadowState.lightShadowsEnabled;

    passState.framebuffer = oit._adjustTranslucentFBO.framebuffer;
    oit._adjustTranslucentCommand.execute(context, passState);
    passState.framebuffer = oit._adjustAlphaFBO.framebuffer;
    oit._adjustAlphaCommand.execute(context, passState);

    const debugFramebuffer = oit._opaqueFBO.framebuffer;
    passState.framebuffer = oit._translucentFBO.framebuffer;

    for (j = 0; j < length; ++j) {
      command = commands[j];
      command = useLogDepth ? command.derivedCommands.logDepth.command : command;
      command = useHdr ? command.derivedCommands.hdr.command : command;
      derivedCommand =
        lightShadowsEnabled && command.receiveShadows
          ? command.derivedCommands.oit.shadows.translucentCommand
          : command.derivedCommands.oit.translucentCommand;
      executeFunction(
        derivedCommand,
        scene,
        context,
        passState,
        debugFramebuffer
      );
    }

    if (defined(invertClassification)) {
      command = invertClassification.unclassifiedCommand;
      derivedCommand =
        lightShadowsEnabled && command.receiveShadows
          ? command.derivedCommands.oit.shadows.translucentCommand
          : command.derivedCommands.oit.translucentCommand;
      executeFunction(
        derivedCommand,
        scene,
        context,
        passState,
        debugFramebuffer
      );
    }

    passState.framebuffer = oit._alphaFBO.framebuffer;

    for (j = 0; j < length; ++j) {
      command = commands[j];
      command = useLogDepth ? command.derivedCommands.logDepth.command : command;
      command = useHdr ? command.derivedCommands.hdr.command : command;
      derivedCommand =
        lightShadowsEnabled && command.receiveShadows
          ? command.derivedCommands.oit.shadows.alphaCommand
          : command.derivedCommands.oit.alphaCommand;
      executeFunction(
        derivedCommand,
        scene,
        context,
        passState,
        debugFramebuffer
      );
    }

    if (defined(invertClassification)) {
      command = invertClassification.unclassifiedCommand;
      derivedCommand =
        lightShadowsEnabled && command.receiveShadows
          ? command.derivedCommands.oit.shadows.alphaCommand
          : command.derivedCommands.oit.alphaCommand;
      executeFunction(
        derivedCommand,
        scene,
        context,
        passState,
        debugFramebuffer
      );
    }

    passState.framebuffer = framebuffer;
  }

  function executeTranslucentCommandsSortedMRT(
    oit,
    scene,
    executeFunction,
    passState,
    commands,
    invertClassification
  ) {
    const context = scene.context;
    const useLogDepth = scene.frameState.useLogDepth;
    const useHdr = scene._hdr;
    const framebuffer = passState.framebuffer;
    const length = commands.length;

    const lightShadowsEnabled = scene.frameState.shadowState.lightShadowsEnabled;

    passState.framebuffer = oit._adjustTranslucentFBO.framebuffer;
    oit._adjustTranslucentCommand.execute(context, passState);

    const debugFramebuffer = oit._opaqueFBO.framebuffer;
    passState.framebuffer = oit._translucentFBO.framebuffer;

    let command;
    let derivedCommand;

    for (let j = 0; j < length; ++j) {
      command = commands[j];
      command = useLogDepth ? command.derivedCommands.logDepth.command : command;
      command = useHdr ? command.derivedCommands.hdr.command : command;
      derivedCommand =
        lightShadowsEnabled && command.receiveShadows
          ? command.derivedCommands.oit.shadows.translucentCommand
          : command.derivedCommands.oit.translucentCommand;
      executeFunction(
        derivedCommand,
        scene,
        context,
        passState,
        debugFramebuffer
      );
    }

    if (defined(invertClassification)) {
      command = invertClassification.unclassifiedCommand;
      derivedCommand =
        lightShadowsEnabled && command.receiveShadows
          ? command.derivedCommands.oit.shadows.translucentCommand
          : command.derivedCommands.oit.translucentCommand;
      executeFunction(
        derivedCommand,
        scene,
        context,
        passState,
        debugFramebuffer
      );
    }

    passState.framebuffer = framebuffer;
  }

  OIT.prototype.executeCommands = function (
    scene,
    executeFunction,
    passState,
    commands,
    invertClassification
  ) {
    if (this._translucentMRTSupport) {
      executeTranslucentCommandsSortedMRT(
        this,
        scene,
        executeFunction,
        passState,
        commands,
        invertClassification
      );
      return;
    }

    executeTranslucentCommandsSortedMultipass(
      this,
      scene,
      executeFunction,
      passState,
      commands,
      invertClassification
    );
  };

  OIT.prototype.execute = function (context, passState) {
    this._compositeCommand.execute(context, passState);
  };

  OIT.prototype.clear = function (context, passState, clearColor) {
    const framebuffer = passState.framebuffer;

    passState.framebuffer = this._opaqueFBO.framebuffer;
    Color.clone(clearColor, this._opaqueClearCommand.color);
    this._opaqueClearCommand.execute(context, passState);

    passState.framebuffer = this._translucentFBO.framebuffer;
    const translucentClearCommand = this._translucentMRTSupport
      ? this._translucentMRTClearCommand
      : this._translucentMultipassClearCommand;
    translucentClearCommand.execute(context, passState);

    if (this._translucentMultipassSupport) {
      passState.framebuffer = this._alphaFBO.framebuffer;
      this._alphaClearCommand.execute(context, passState);
    }

    passState.framebuffer = framebuffer;
  };

  OIT.prototype.isSupported = function () {
    return this._translucentMRTSupport || this._translucentMultipassSupport;
  };

  OIT.prototype.isDestroyed = function () {
    return false;
  };

  OIT.prototype.destroy = function () {
    destroyResources$2(this);

    if (defined(this._compositeCommand)) {
      this._compositeCommand.shaderProgram =
        this._compositeCommand.shaderProgram &&
        this._compositeCommand.shaderProgram.destroy();
    }

    if (defined(this._adjustTranslucentCommand)) {
      this._adjustTranslucentCommand.shaderProgram =
        this._adjustTranslucentCommand.shaderProgram &&
        this._adjustTranslucentCommand.shaderProgram.destroy();
    }

    if (defined(this._adjustAlphaCommand)) {
      this._adjustAlphaCommand.shaderProgram =
        this._adjustAlphaCommand.shaderProgram &&
        this._adjustAlphaCommand.shaderProgram.destroy();
    }

    return destroyObject(this);
  };

  const defaultCredit = new Credit(
    "MapQuest, Open Street Map and contributors, CC-BY-SA"
  );

  /**
   * @typedef {Object} OpenStreetMapImageryProvider.ConstructorOptions
   *
   * Initialization options for the OpenStreetMapImageryProvider constructor
   *
   * @property {String} [url='https://a.tile.openstreetmap.org'] The OpenStreetMap server url.
   * @property {String} [fileExtension='png'] The file extension for images on the server.
   * @property {Rectangle} [rectangle=Rectangle.MAX_VALUE] The rectangle of the layer.
   * @property {Number} [minimumLevel=0] The minimum level-of-detail supported by the imagery provider.
   * @property {Number} [maximumLevel] The maximum level-of-detail supported by the imagery provider, or undefined if there is no limit.
   * @property {Ellipsoid} [ellipsoid] The ellipsoid.  If not specified, the WGS84 ellipsoid is used.
   * @property {Credit|String} [credit='MapQuest, Open Street Map and contributors, CC-BY-SA'] A credit for the data source, which is displayed on the canvas.
   */

  /**
   * An imagery provider that provides tiled imagery hosted by OpenStreetMap
   * or another provider of Slippy tiles.  The default url connects to OpenStreetMap's volunteer-run
   * servers, so you must conform to their
   * {@link http://wiki.openstreetmap.org/wiki/Tile_usage_policy|Tile Usage Policy}.
   *
   * @alias OpenStreetMapImageryProvider
   * @constructor
   * @extends UrlTemplateImageryProvider
   *
   * @param {OpenStreetMapImageryProvider.ConstructorOptions} options Object describing initialization options
   * @exception {DeveloperError} The rectangle and minimumLevel indicate that there are more than four tiles at the minimum level. Imagery providers with more than four tiles at the minimum level are not supported.
   *
   * @see ArcGisMapServerImageryProvider
   * @see BingMapsImageryProvider
   * @see GoogleEarthEnterpriseMapsProvider
   * @see SingleTileImageryProvider
   * @see TileMapServiceImageryProvider
   * @see WebMapServiceImageryProvider
   * @see WebMapTileServiceImageryProvider
   * @see UrlTemplateImageryProvider
   *
   * @example
   * const osm = new Cesium.OpenStreetMapImageryProvider({
   *     url : 'https://a.tile.openstreetmap.org/'
   * });
   *
   * @see {@link http://wiki.openstreetmap.org/wiki/Main_Page|OpenStreetMap Wiki}
   * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
   */
  function OpenStreetMapImageryProvider(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const resource = Resource.createIfNeeded(
      defaultValue(options.url, "https://a.tile.openstreetmap.org/")
    );
    resource.appendForwardSlash();
    resource.url += `{z}/{x}/{y}.${defaultValue(options.fileExtension, "png")}`;

    const tilingScheme = new WebMercatorTilingScheme({
      ellipsoid: options.ellipsoid,
    });

    const tileWidth = 256;
    const tileHeight = 256;

    const minimumLevel = defaultValue(options.minimumLevel, 0);
    const maximumLevel = options.maximumLevel;

    const rectangle = defaultValue(options.rectangle, tilingScheme.rectangle);

    // Check the number of tiles at the minimum level.  If it's more than four,
    // throw an exception, because starting at the higher minimum
    // level will cause too many tiles to be downloaded and rendered.
    const swTile = tilingScheme.positionToTileXY(
      Rectangle.southwest(rectangle),
      minimumLevel
    );
    const neTile = tilingScheme.positionToTileXY(
      Rectangle.northeast(rectangle),
      minimumLevel
    );
    const tileCount =
      (Math.abs(neTile.x - swTile.x) + 1) * (Math.abs(neTile.y - swTile.y) + 1);
    //>>includeStart('debug', pragmas.debug);
    if (tileCount > 4) {
      throw new DeveloperError(
        `The rectangle and minimumLevel indicate that there are ${tileCount} tiles at the minimum level. Imagery providers with more than four tiles at the minimum level are not supported.`
      );
    }
    //>>includeEnd('debug');

    let credit = defaultValue(options.credit, defaultCredit);
    if (typeof credit === "string") {
      credit = new Credit(credit);
    }

    UrlTemplateImageryProvider.call(this, {
      url: resource,
      credit: credit,
      tilingScheme: tilingScheme,
      tileWidth: tileWidth,
      tileHeight: tileHeight,
      minimumLevel: minimumLevel,
      maximumLevel: maximumLevel,
      rectangle: rectangle,
    });
  }

  if (defined(Object.create)) {
    OpenStreetMapImageryProvider.prototype = Object.create(
      UrlTemplateImageryProvider.prototype
    );
    OpenStreetMapImageryProvider.prototype.constructor = OpenStreetMapImageryProvider;
  }

  const defaultSize = new Cartesian2(1.0, 1.0);

  /**
   * A particle emitted by a {@link ParticleSystem}.
   *
   * @alias Particle
   * @constructor
   *
   * @param {Object} options An object with the following properties:
   * @param {Number} [options.mass=1.0] The mass of the particle in kilograms.
   * @param {Cartesian3} [options.position=Cartesian3.ZERO] The initial position of the particle in world coordinates.
   * @param {Cartesian3} [options.velocity=Cartesian3.ZERO] The velocity vector of the particle in world coordinates.
   * @param {Number} [options.life=Number.MAX_VALUE] The life of the particle in seconds.
   * @param {Object} [options.image] The URI, HTMLImageElement, or HTMLCanvasElement to use for the billboard.
   * @param {Color} [options.startColor=Color.WHITE] The color of a particle when it is born.
   * @param {Color} [options.endColor=Color.WHITE] The color of a particle when it dies.
   * @param {Number} [options.startScale=1.0] The scale of the particle when it is born.
   * @param {Number} [options.endScale=1.0] The scale of the particle when it dies.
   * @param {Cartesian2} [options.imageSize=new Cartesian2(1.0, 1.0)] The dimensions, width by height, to scale the particle image in pixels.
   */
  function Particle(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    /**
     * The mass of the particle in kilograms.
     * @type {Number}
     * @default 1.0
     */
    this.mass = defaultValue(options.mass, 1.0);
    /**
     * The positon of the particle in world coordinates.
     * @type {Cartesian3}
     * @default Cartesian3.ZERO
     */
    this.position = Cartesian3.clone(
      defaultValue(options.position, Cartesian3.ZERO)
    );
    /**
     * The velocity of the particle in world coordinates.
     * @type {Cartesian3}
     * @default Cartesian3.ZERO
     */
    this.velocity = Cartesian3.clone(
      defaultValue(options.velocity, Cartesian3.ZERO)
    );
    /**
     * The life of the particle in seconds.
     * @type {Number}
     * @default Number.MAX_VALUE
     */
    this.life = defaultValue(options.life, Number.MAX_VALUE);
    /**
     * The image to use for the particle.
     * @type {Object}
     * @default undefined
     */
    this.image = options.image;
    /**
     * The color of the particle when it is born.
     * @type {Color}
     * @default Color.WHITE
     */
    this.startColor = Color.clone(defaultValue(options.startColor, Color.WHITE));
    /**
     * The color of the particle when it dies.
     * @type {Color}
     * @default Color.WHITE
     */
    this.endColor = Color.clone(defaultValue(options.endColor, Color.WHITE));
    /**
     * the scale of the particle when it is born.
     * @type {Number}
     * @default 1.0
     */
    this.startScale = defaultValue(options.startScale, 1.0);
    /**
     * The scale of the particle when it dies.
     * @type {Number}
     * @default 1.0
     */
    this.endScale = defaultValue(options.endScale, 1.0);
    /**
     * The dimensions, width by height, to scale the particle image in pixels.
     * @type {Cartesian2}
     * @default new Cartesian(1.0, 1.0)
     */
    this.imageSize = Cartesian2.clone(
      defaultValue(options.imageSize, defaultSize)
    );

    this._age = 0.0;
    this._normalizedAge = 0.0;

    // used by ParticleSystem
    this._billboard = undefined;
  }

  Object.defineProperties(Particle.prototype, {
    /**
     * Gets the age of the particle in seconds.
     * @memberof Particle.prototype
     * @type {Number}
     */
    age: {
      get: function () {
        return this._age;
      },
    },
    /**
     * Gets the age normalized to a value in the range [0.0, 1.0].
     * @memberof Particle.prototype
     * @type {Number}
     */
    normalizedAge: {
      get: function () {
        return this._normalizedAge;
      },
    },
  });

  const deltaScratch = new Cartesian3();

  /**
   * @private
   */
  Particle.prototype.update = function (dt, particleUpdateFunction) {
    // Apply the velocity
    Cartesian3.multiplyByScalar(this.velocity, dt, deltaScratch);
    Cartesian3.add(this.position, deltaScratch, this.position);

    // Update any forces.
    if (defined(particleUpdateFunction)) {
      particleUpdateFunction(this, dt);
    }

    // Age the particle
    this._age += dt;

    // Compute the normalized age.
    if (this.life === Number.MAX_VALUE) {
      this._normalizedAge = 0.0;
    } else {
      this._normalizedAge = this._age / this.life;
    }

    // If this particle is older than it's lifespan then die.
    return this._age <= this.life;
  };

  /**
   * Represents a burst of {@link Particle}s from a {@link ParticleSystem} at a given time in the systems lifetime.
   *
   * @alias ParticleBurst
   * @constructor
   *
   * @param {Object} [options] An object with the following properties:
   * @param {Number} [options.time=0.0] The time in seconds after the beginning of the particle system's lifetime that the burst will occur.
   * @param {Number} [options.minimum=0.0] The minimum number of particles emmitted in the burst.
   * @param {Number} [options.maximum=50.0] The maximum number of particles emitted in the burst.
   */
  function ParticleBurst(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    /**
     * The time in seconds after the beginning of the particle system's lifetime that the burst will occur.
     * @type {Number}
     * @default 0.0
     */
    this.time = defaultValue(options.time, 0.0);
    /**
     * The minimum number of particles emitted.
     * @type {Number}
     * @default 0.0
     */
    this.minimum = defaultValue(options.minimum, 0.0);
    /**
     * The maximum number of particles emitted.
     * @type {Number}
     * @default 50.0
     */
    this.maximum = defaultValue(options.maximum, 50.0);

    this._complete = false;
  }

  Object.defineProperties(ParticleBurst.prototype, {
    /**
     * <code>true</code> if the burst has been completed; <code>false</code> otherwise.
     * @memberof ParticleBurst.prototype
     * @type {Boolean}
     */
    complete: {
      get: function () {
        return this._complete;
      },
    },
  });

  /**
   * <p>
   * An object that initializes a {@link Particle} from a {@link ParticleSystem}.
   * </p>
   * <p>
   * This type describes an interface and is not intended to be instantiated directly.
   * </p>
   *
   * @alias ParticleEmitter
   * @constructor
   *
   * @see BoxEmitter
   * @see CircleEmitter
   * @see ConeEmitter
   * @see SphereEmitter
   */
  function ParticleEmitter(options) {
    //>>includeStart('debug', pragmas.debug);
    throw new DeveloperError(
      "This type should not be instantiated directly.  Instead, use BoxEmitter, CircleEmitter, ConeEmitter or SphereEmitter."
    );
    //>>includeEnd('debug');
  }

  /**
   * Initializes the given {Particle} by setting it's position and velocity.
   *
   * @private
   * @param {Particle} The particle to initialize
   */
  ParticleEmitter.prototype.emit = function (particle) {
    DeveloperError.throwInstantiationError();
  };

  const defaultImageSize = new Cartesian2(1.0, 1.0);

  /**
   * A ParticleSystem manages the updating and display of a collection of particles.
   *
   * @alias ParticleSystem
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Boolean} [options.show=true] Whether to display the particle system.
   * @param {ParticleSystem.updateCallback} [options.updateCallback] The callback function to be called each frame to update a particle.
   * @param {ParticleEmitter} [options.emitter=new CircleEmitter(0.5)] The particle emitter for this system.
   * @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] The 4x4 transformation matrix that transforms the particle system from model to world coordinates.
   * @param {Matrix4} [options.emitterModelMatrix=Matrix4.IDENTITY] The 4x4 transformation matrix that transforms the particle system emitter within the particle systems local coordinate system.
   * @param {Number} [options.emissionRate=5] The number of particles to emit per second.
   * @param {ParticleBurst[]} [options.bursts] An array of {@link ParticleBurst}, emitting bursts of particles at periodic times.
   * @param {Boolean} [options.loop=true] Whether the particle system should loop its bursts when it is complete.
   * @param {Number} [options.scale=1.0] Sets the scale to apply to the image of the particle for the duration of its particleLife.
   * @param {Number} [options.startScale] The initial scale to apply to the image of the particle at the beginning of its life.
   * @param {Number} [options.endScale] The final scale to apply to the image of the particle at the end of its life.
   * @param {Color} [options.color=Color.WHITE] Sets the color of a particle for the duration of its particleLife.
   * @param {Color} [options.startColor] The color of the particle at the beginning of its life.
   * @param {Color} [options.endColor] The color of the particle at the end of its life.
   * @param {Object} [options.image] The URI, HTMLImageElement, or HTMLCanvasElement to use for the billboard.
   * @param {Cartesian2} [options.imageSize=new Cartesian2(1.0, 1.0)] If set, overrides the minimumImageSize and maximumImageSize inputs that scale the particle image's dimensions in pixels.
   * @param {Cartesian2} [options.minimumImageSize] Sets the minimum bound, width by height, above which to randomly scale the particle image's dimensions in pixels.
   * @param {Cartesian2} [options.maximumImageSize] Sets the maximum bound, width by height, below which to randomly scale the particle image's dimensions in pixels.
   * @param {Boolean} [options.sizeInMeters] Sets if the size of particles is in meters or pixels. <code>true</code> to size the particles in meters; otherwise, the size is in pixels.
   * @param {Number} [options.speed=1.0] If set, overrides the minimumSpeed and maximumSpeed inputs with this value.
   * @param {Number} [options.minimumSpeed] Sets the minimum bound in meters per second above which a particle's actual speed will be randomly chosen.
   * @param {Number} [options.maximumSpeed] Sets the maximum bound in meters per second below which a particle's actual speed will be randomly chosen.
   * @param {Number} [options.lifetime=Number.MAX_VALUE] How long the particle system will emit particles, in seconds.
   * @param {Number} [options.particleLife=5.0] If set, overrides the minimumParticleLife and maximumParticleLife inputs with this value.
   * @param {Number} [options.minimumParticleLife] Sets the minimum bound in seconds for the possible duration of a particle's life above which a particle's actual life will be randomly chosen.
   * @param {Number} [options.maximumParticleLife] Sets the maximum bound in seconds for the possible duration of a particle's life below which a particle's actual life will be randomly chosen.
   * @param {Number} [options.mass=1.0] Sets the minimum and maximum mass of particles in kilograms.
   * @param {Number} [options.minimumMass] Sets the minimum bound for the mass of a particle in kilograms. A particle's actual mass will be chosen as a random amount above this value.
   * @param {Number} [options.maximumMass] Sets the maximum mass of particles in kilograms. A particle's actual mass will be chosen as a random amount below this value.
   * @demo {@link https://cesium.com/learn/cesiumjs-learn/cesiumjs-particle-systems/|Particle Systems Tutorial}
   * @demo {@link https://sandcastle.cesium.com/?src=Particle%20System.html&label=Showcases|Particle Systems Tutorial Demo}
   * @demo {@link https://sandcastle.cesium.com/?src=Particle%20System%20Fireworks.html&label=Showcases|Particle Systems Fireworks Demo}
   */
  function ParticleSystem(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    /**
     * Whether to display the particle system.
     * @type {Boolean}
     * @default true
     */
    this.show = defaultValue(options.show, true);

    /**
     * An array of force callbacks. The callback is passed a {@link Particle} and the difference from the last time
     * @type {ParticleSystem.updateCallback}
     * @default undefined
     */
    this.updateCallback = options.updateCallback;

    /**
     * Whether the particle system should loop it's bursts when it is complete.
     * @type {Boolean}
     * @default true
     */
    this.loop = defaultValue(options.loop, true);

    /**
     * The URI, HTMLImageElement, or HTMLCanvasElement to use for the billboard.
     * @type {Object}
     * @default undefined
     */
    this.image = defaultValue(options.image, undefined);

    let emitter = options.emitter;
    if (!defined(emitter)) {
      emitter = new CircleEmitter(0.5);
    }
    this._emitter = emitter;

    this._bursts = options.bursts;

    this._modelMatrix = Matrix4.clone(
      defaultValue(options.modelMatrix, Matrix4.IDENTITY)
    );
    this._emitterModelMatrix = Matrix4.clone(
      defaultValue(options.emitterModelMatrix, Matrix4.IDENTITY)
    );
    this._matrixDirty = true;
    this._combinedMatrix = new Matrix4();

    this._startColor = Color.clone(
      defaultValue(options.color, defaultValue(options.startColor, Color.WHITE))
    );
    this._endColor = Color.clone(
      defaultValue(options.color, defaultValue(options.endColor, Color.WHITE))
    );

    this._startScale = defaultValue(
      options.scale,
      defaultValue(options.startScale, 1.0)
    );
    this._endScale = defaultValue(
      options.scale,
      defaultValue(options.endScale, 1.0)
    );

    this._emissionRate = defaultValue(options.emissionRate, 5.0);

    this._minimumSpeed = defaultValue(
      options.speed,
      defaultValue(options.minimumSpeed, 1.0)
    );
    this._maximumSpeed = defaultValue(
      options.speed,
      defaultValue(options.maximumSpeed, 1.0)
    );

    this._minimumParticleLife = defaultValue(
      options.particleLife,
      defaultValue(options.minimumParticleLife, 5.0)
    );
    this._maximumParticleLife = defaultValue(
      options.particleLife,
      defaultValue(options.maximumParticleLife, 5.0)
    );

    this._minimumMass = defaultValue(
      options.mass,
      defaultValue(options.minimumMass, 1.0)
    );
    this._maximumMass = defaultValue(
      options.mass,
      defaultValue(options.maximumMass, 1.0)
    );

    this._minimumImageSize = Cartesian2.clone(
      defaultValue(
        options.imageSize,
        defaultValue(options.minimumImageSize, defaultImageSize)
      )
    );
    this._maximumImageSize = Cartesian2.clone(
      defaultValue(
        options.imageSize,
        defaultValue(options.maximumImageSize, defaultImageSize)
      )
    );

    this._sizeInMeters = defaultValue(options.sizeInMeters, false);

    this._lifetime = defaultValue(options.lifetime, Number.MAX_VALUE);

    this._billboardCollection = undefined;
    this._particles = [];

    // An array of available particles that we can reuse instead of allocating new.
    this._particlePool = [];

    this._previousTime = undefined;
    this._currentTime = 0.0;
    this._carryOver = 0.0;

    this._complete = new Event();
    this._isComplete = false;

    this._updateParticlePool = true;
    this._particleEstimate = 0;
  }

  Object.defineProperties(ParticleSystem.prototype, {
    /**
     * The particle emitter for this
     * @memberof ParticleSystem.prototype
     * @type {ParticleEmitter}
     * @default CircleEmitter
     */
    emitter: {
      get: function () {
        return this._emitter;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.defined("value", value);
        //>>includeEnd('debug');
        this._emitter = value;
      },
    },
    /**
     * An array of {@link ParticleBurst}, emitting bursts of particles at periodic times.
     * @memberof ParticleSystem.prototype
     * @type {ParticleBurst[]}
     * @default undefined
     */
    bursts: {
      get: function () {
        return this._bursts;
      },
      set: function (value) {
        this._bursts = value;
        this._updateParticlePool = true;
      },
    },
    /**
     * The 4x4 transformation matrix that transforms the particle system from model to world coordinates.
     * @memberof ParticleSystem.prototype
     * @type {Matrix4}
     * @default Matrix4.IDENTITY
     */
    modelMatrix: {
      get: function () {
        return this._modelMatrix;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.defined("value", value);
        //>>includeEnd('debug');
        this._matrixDirty =
          this._matrixDirty || !Matrix4.equals(this._modelMatrix, value);
        Matrix4.clone(value, this._modelMatrix);
      },
    },
    /**
     * The 4x4 transformation matrix that transforms the particle system emitter within the particle systems local coordinate system.
     * @memberof ParticleSystem.prototype
     * @type {Matrix4}
     * @default Matrix4.IDENTITY
     */
    emitterModelMatrix: {
      get: function () {
        return this._emitterModelMatrix;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.defined("value", value);
        //>>includeEnd('debug');
        this._matrixDirty =
          this._matrixDirty || !Matrix4.equals(this._emitterModelMatrix, value);
        Matrix4.clone(value, this._emitterModelMatrix);
      },
    },
    /**
     * The color of the particle at the beginning of its life.
     * @memberof ParticleSystem.prototype
     * @type {Color}
     * @default Color.WHITE
     */
    startColor: {
      get: function () {
        return this._startColor;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.defined("value", value);
        //>>includeEnd('debug');
        Color.clone(value, this._startColor);
      },
    },
    /**
     * The color of the particle at the end of its life.
     * @memberof ParticleSystem.prototype
     * @type {Color}
     * @default Color.WHITE
     */
    endColor: {
      get: function () {
        return this._endColor;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.defined("value", value);
        //>>includeEnd('debug');
        Color.clone(value, this._endColor);
      },
    },
    /**
     * The initial scale to apply to the image of the particle at the beginning of its life.
     * @memberof ParticleSystem.prototype
     * @type {Number}
     * @default 1.0
     */
    startScale: {
      get: function () {
        return this._startScale;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number.greaterThanOrEquals("value", value, 0.0);
        //>>includeEnd('debug');
        this._startScale = value;
      },
    },
    /**
     * The final scale to apply to the image of the particle at the end of its life.
     * @memberof ParticleSystem.prototype
     * @type {Number}
     * @default 1.0
     */
    endScale: {
      get: function () {
        return this._endScale;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number.greaterThanOrEquals("value", value, 0.0);
        //>>includeEnd('debug');
        this._endScale = value;
      },
    },
    /**
     * The number of particles to emit per second.
     * @memberof ParticleSystem.prototype
     * @type {Number}
     * @default 5
     */
    emissionRate: {
      get: function () {
        return this._emissionRate;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number.greaterThanOrEquals("value", value, 0.0);
        //>>includeEnd('debug');
        this._emissionRate = value;
        this._updateParticlePool = true;
      },
    },
    /**
     * Sets the minimum bound in meters per second above which a particle's actual speed will be randomly chosen.
     * @memberof ParticleSystem.prototype
     * @type {Number}
     * @default 1.0
     */
    minimumSpeed: {
      get: function () {
        return this._minimumSpeed;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number.greaterThanOrEquals("value", value, 0.0);
        //>>includeEnd('debug');
        this._minimumSpeed = value;
      },
    },
    /**
     * Sets the maximum bound in meters per second below which a particle's actual speed will be randomly chosen.
     * @memberof ParticleSystem.prototype
     * @type {Number}
     * @default 1.0
     */
    maximumSpeed: {
      get: function () {
        return this._maximumSpeed;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number.greaterThanOrEquals("value", value, 0.0);
        //>>includeEnd('debug');
        this._maximumSpeed = value;
      },
    },
    /**
     * Sets the minimum bound in seconds for the possible duration of a particle's life above which a particle's actual life will be randomly chosen.
     * @memberof ParticleSystem.prototype
     * @type {Number}
     * @default 5.0
     */
    minimumParticleLife: {
      get: function () {
        return this._minimumParticleLife;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number.greaterThanOrEquals("value", value, 0.0);
        //>>includeEnd('debug');
        this._minimumParticleLife = value;
      },
    },
    /**
     * Sets the maximum bound in seconds for the possible duration of a particle's life below which a particle's actual life will be randomly chosen.
     * @memberof ParticleSystem.prototype
     * @type {Number}
     * @default 5.0
     */
    maximumParticleLife: {
      get: function () {
        return this._maximumParticleLife;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number.greaterThanOrEquals("value", value, 0.0);
        //>>includeEnd('debug');
        this._maximumParticleLife = value;
        this._updateParticlePool = true;
      },
    },
    /**
     * Sets the minimum mass of particles in kilograms.
     * @memberof ParticleSystem.prototype
     * @type {Number}
     * @default 1.0
     */
    minimumMass: {
      get: function () {
        return this._minimumMass;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number.greaterThanOrEquals("value", value, 0.0);
        //>>includeEnd('debug');
        this._minimumMass = value;
      },
    },
    /**
     * Sets the maximum mass of particles in kilograms.
     * @memberof ParticleSystem.prototype
     * @type {Number}
     * @default 1.0
     */
    maximumMass: {
      get: function () {
        return this._maximumMass;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number.greaterThanOrEquals("value", value, 0.0);
        //>>includeEnd('debug');
        this._maximumMass = value;
      },
    },
    /**
     * Sets the minimum bound, width by height, above which to randomly scale the particle image's dimensions in pixels.
     * @memberof ParticleSystem.prototype
     * @type {Cartesian2}
     * @default new Cartesian2(1.0, 1.0)
     */
    minimumImageSize: {
      get: function () {
        return this._minimumImageSize;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.object("value", value);
        Check.typeOf.number.greaterThanOrEquals("value.x", value.x, 0.0);
        Check.typeOf.number.greaterThanOrEquals("value.y", value.y, 0.0);
        //>>includeEnd('debug');
        this._minimumImageSize = value;
      },
    },
    /**
     * Sets the maximum bound, width by height, below which to randomly scale the particle image's dimensions in pixels.
     * @memberof ParticleSystem.prototype
     * @type {Cartesian2}
     * @default new Cartesian2(1.0, 1.0)
     */
    maximumImageSize: {
      get: function () {
        return this._maximumImageSize;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.object("value", value);
        Check.typeOf.number.greaterThanOrEquals("value.x", value.x, 0.0);
        Check.typeOf.number.greaterThanOrEquals("value.y", value.y, 0.0);
        //>>includeEnd('debug');
        this._maximumImageSize = value;
      },
    },
    /**
     * Gets or sets if the particle size is in meters or pixels. <code>true</code> to size particles in meters; otherwise, the size is in pixels.
     * @memberof ParticleSystem.prototype
     * @type {Boolean}
     * @default false
     */
    sizeInMeters: {
      get: function () {
        return this._sizeInMeters;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.bool("value", value);
        //>>includeEnd('debug');
        this._sizeInMeters = value;
      },
    },
    /**
     * How long the particle system will emit particles, in seconds.
     * @memberof ParticleSystem.prototype
     * @type {Number}
     * @default Number.MAX_VALUE
     */
    lifetime: {
      get: function () {
        return this._lifetime;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number.greaterThanOrEquals("value", value, 0.0);
        //>>includeEnd('debug');
        this._lifetime = value;
      },
    },
    /**
     * Fires an event when the particle system has reached the end of its lifetime.
     * @memberof ParticleSystem.prototype
     * @type {Event}
     */
    complete: {
      get: function () {
        return this._complete;
      },
    },
    /**
     * When <code>true</code>, the particle system has reached the end of its lifetime; <code>false</code> otherwise.
     * @memberof ParticleSystem.prototype
     * @type {Boolean}
     */
    isComplete: {
      get: function () {
        return this._isComplete;
      },
    },
  });

  function updateParticlePool(system) {
    const emissionRate = system._emissionRate;
    const life = system._maximumParticleLife;

    let burstAmount = 0;
    const bursts = system._bursts;
    if (defined(bursts)) {
      const length = bursts.length;
      for (let i = 0; i < length; ++i) {
        burstAmount += bursts[i].maximum;
      }
    }

    const billboardCollection = system._billboardCollection;
    const image = system.image;

    const particleEstimate = Math.ceil(emissionRate * life + burstAmount);
    const particles = system._particles;
    const particlePool = system._particlePool;
    const numToAdd = Math.max(
      particleEstimate - particles.length - particlePool.length,
      0
    );

    for (let j = 0; j < numToAdd; ++j) {
      const particle = new Particle();
      particle._billboard = billboardCollection.add({
        image: image,
      });
      particlePool.push(particle);
    }

    system._particleEstimate = particleEstimate;
  }

  function getOrCreateParticle(system) {
    // Try to reuse an existing particle from the pool.
    let particle = system._particlePool.pop();
    if (!defined(particle)) {
      // Create a new one
      particle = new Particle();
    }
    return particle;
  }

  function addParticleToPool(system, particle) {
    system._particlePool.push(particle);
  }

  function freeParticlePool(system) {
    const particles = system._particles;
    const particlePool = system._particlePool;
    const billboardCollection = system._billboardCollection;

    const numParticles = particles.length;
    const numInPool = particlePool.length;
    const estimate = system._particleEstimate;

    const start = numInPool - Math.max(estimate - numParticles - numInPool, 0);
    for (let i = start; i < numInPool; ++i) {
      const p = particlePool[i];
      billboardCollection.remove(p._billboard);
    }
    particlePool.length = start;
  }

  function removeBillboard(particle) {
    if (defined(particle._billboard)) {
      particle._billboard.show = false;
    }
  }

  function updateBillboard(system, particle) {
    let billboard = particle._billboard;
    if (!defined(billboard)) {
      billboard = particle._billboard = system._billboardCollection.add({
        image: particle.image,
      });
    }
    billboard.width = particle.imageSize.x;
    billboard.height = particle.imageSize.y;
    billboard.position = particle.position;
    billboard.sizeInMeters = system.sizeInMeters;
    billboard.show = true;

    // Update the color
    const r = CesiumMath.lerp(
      particle.startColor.red,
      particle.endColor.red,
      particle.normalizedAge
    );
    const g = CesiumMath.lerp(
      particle.startColor.green,
      particle.endColor.green,
      particle.normalizedAge
    );
    const b = CesiumMath.lerp(
      particle.startColor.blue,
      particle.endColor.blue,
      particle.normalizedAge
    );
    const a = CesiumMath.lerp(
      particle.startColor.alpha,
      particle.endColor.alpha,
      particle.normalizedAge
    );
    billboard.color = new Color(r, g, b, a);

    // Update the scale
    billboard.scale = CesiumMath.lerp(
      particle.startScale,
      particle.endScale,
      particle.normalizedAge
    );
  }

  function addParticle(system, particle) {
    particle.startColor = Color.clone(system._startColor, particle.startColor);
    particle.endColor = Color.clone(system._endColor, particle.endColor);
    particle.startScale = system._startScale;
    particle.endScale = system._endScale;
    particle.image = system.image;
    particle.life = CesiumMath.randomBetween(
      system._minimumParticleLife,
      system._maximumParticleLife
    );
    particle.mass = CesiumMath.randomBetween(
      system._minimumMass,
      system._maximumMass
    );
    particle.imageSize.x = CesiumMath.randomBetween(
      system._minimumImageSize.x,
      system._maximumImageSize.x
    );
    particle.imageSize.y = CesiumMath.randomBetween(
      system._minimumImageSize.y,
      system._maximumImageSize.y
    );

    // Reset the normalizedAge and age in case the particle was reused.
    particle._normalizedAge = 0.0;
    particle._age = 0.0;

    const speed = CesiumMath.randomBetween(
      system._minimumSpeed,
      system._maximumSpeed
    );
    Cartesian3.multiplyByScalar(particle.velocity, speed, particle.velocity);

    system._particles.push(particle);
  }

  function calculateNumberToEmit(system, dt) {
    // This emitter is finished if it exceeds it's lifetime.
    if (system._isComplete) {
      return 0;
    }

    dt = CesiumMath.mod(dt, system._lifetime);

    // Compute the number of particles to emit based on the emissionRate.
    const v = dt * system._emissionRate;
    let numToEmit = Math.floor(v);
    system._carryOver += v - numToEmit;
    if (system._carryOver > 1.0) {
      numToEmit++;
      system._carryOver -= 1.0;
    }

    // Apply any bursts
    if (defined(system.bursts)) {
      const length = system.bursts.length;
      for (let i = 0; i < length; i++) {
        const burst = system.bursts[i];
        const currentTime = system._currentTime;
        if (defined(burst) && !burst._complete && currentTime > burst.time) {
          numToEmit += CesiumMath.randomBetween(burst.minimum, burst.maximum);
          burst._complete = true;
        }
      }
    }

    return numToEmit;
  }

  const rotatedVelocityScratch = new Cartesian3();

  /**
   * @private
   */
  ParticleSystem.prototype.update = function (frameState) {
    if (!this.show) {
      return;
    }

    if (!defined(this._billboardCollection)) {
      this._billboardCollection = new BillboardCollection();
    }

    if (this._updateParticlePool) {
      updateParticlePool(this);
      this._updateParticlePool = false;
    }

    // Compute the frame time
    let dt = 0.0;
    if (this._previousTime) {
      dt = JulianDate.secondsDifference(frameState.time, this._previousTime);
    }

    if (dt < 0.0) {
      dt = 0.0;
    }

    const particles = this._particles;
    const emitter = this._emitter;
    const updateCallback = this.updateCallback;

    let i;
    let particle;

    // update particles and remove dead particles
    let length = particles.length;
    for (i = 0; i < length; ++i) {
      particle = particles[i];
      if (!particle.update(dt, updateCallback)) {
        removeBillboard(particle);
        // Add the particle back to the pool so it can be reused.
        addParticleToPool(this, particle);
        particles[i] = particles[length - 1];
        --i;
        --length;
      } else {
        updateBillboard(this, particle);
      }
    }
    particles.length = length;

    const numToEmit = calculateNumberToEmit(this, dt);

    if (numToEmit > 0 && defined(emitter)) {
      // Compute the final model matrix by combining the particle systems model matrix and the emitter matrix.
      if (this._matrixDirty) {
        this._combinedMatrix = Matrix4.multiply(
          this.modelMatrix,
          this.emitterModelMatrix,
          this._combinedMatrix
        );
        this._matrixDirty = false;
      }

      const combinedMatrix = this._combinedMatrix;

      for (i = 0; i < numToEmit; i++) {
        // Create a new particle.
        particle = getOrCreateParticle(this);

        // Let the emitter initialize the particle.
        this._emitter.emit(particle);

        //For the velocity we need to add it to the original position and then multiply by point.
        Cartesian3.add(
          particle.position,
          particle.velocity,
          rotatedVelocityScratch
        );
        Matrix4.multiplyByPoint(
          combinedMatrix,
          rotatedVelocityScratch,
          rotatedVelocityScratch
        );

        // Change the position to be in world coordinates
        particle.position = Matrix4.multiplyByPoint(
          combinedMatrix,
          particle.position,
          particle.position
        );

        // Orient the velocity in world space as well.
        Cartesian3.subtract(
          rotatedVelocityScratch,
          particle.position,
          particle.velocity
        );
        Cartesian3.normalize(particle.velocity, particle.velocity);

        // Add the particle to the system.
        addParticle(this, particle);
        updateBillboard(this, particle);
      }
    }

    this._billboardCollection.update(frameState);
    this._previousTime = JulianDate.clone(frameState.time, this._previousTime);
    this._currentTime += dt;

    if (
      this._lifetime !== Number.MAX_VALUE &&
      this._currentTime > this._lifetime
    ) {
      if (this.loop) {
        this._currentTime = CesiumMath.mod(this._currentTime, this._lifetime);
        if (this.bursts) {
          const burstLength = this.bursts.length;
          // Reset any bursts
          for (i = 0; i < burstLength; i++) {
            this.bursts[i]._complete = false;
          }
        }
      } else {
        this._isComplete = true;
        this._complete.raiseEvent(this);
      }
    }

    // free particles in the pool and release billboard GPU memory
    if (frameState.frameNumber % 120 === 0) {
      freeParticlePool(this);
    }
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see ParticleSystem#destroy
   */
  ParticleSystem.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @see ParticleSystem#isDestroyed
   */
  ParticleSystem.prototype.destroy = function () {
    this._billboardCollection =
      this._billboardCollection && this._billboardCollection.destroy();
    return destroyObject(this);
  };

  /**
   * @private
   */
  function PerformanceDisplay(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const container = getElement(options.container);
    //>>includeStart('debug', pragmas.debug);
    if (!defined(container)) {
      throw new DeveloperError("container is required");
    }
    //>>includeEnd('debug');

    this._container = container;

    const display = document.createElement("div");
    display.className = "cesium-performanceDisplay";
    const fpsElement = document.createElement("div");
    fpsElement.className = "cesium-performanceDisplay-fps";
    this._fpsText = document.createTextNode("");
    fpsElement.appendChild(this._fpsText);
    const msElement = document.createElement("div");
    msElement.className = "cesium-performanceDisplay-ms";
    this._msText = document.createTextNode("");
    msElement.appendChild(this._msText);
    display.appendChild(msElement);
    display.appendChild(fpsElement);
    this._container.appendChild(display);

    this._lastFpsSampleTime = getTimestamp$1();
    this._lastMsSampleTime = getTimestamp$1();
    this._fpsFrameCount = 0;
    this._msFrameCount = 0;

    this._throttled = false;
    const throttledElement = document.createElement("div");
    throttledElement.className = "cesium-performanceDisplay-throttled";
    this._throttledText = document.createTextNode("");
    throttledElement.appendChild(this._throttledText);
    display.appendChild(throttledElement);
  }

  Object.defineProperties(PerformanceDisplay.prototype, {
    /**
     * The display should indicate the FPS is being throttled.
     * @memberof PerformanceDisplay.prototype
     *
     * @type {Boolean}
     */
    throttled: {
      get: function () {
        return this._throttled;
      },
      set: function (value) {
        if (this._throttled === value) {
          return;
        }

        if (value) {
          this._throttledText.nodeValue = "(throttled)";
        } else {
          this._throttledText.nodeValue = "";
        }

        this._throttled = value;
      },
    },
  });

  /**
   * Update the display.  This function should only be called once per frame, because
   * each call records a frame in the internal buffer and redraws the display.
   *
   * @param {Boolean} [renderedThisFrame=true] If provided, the FPS count will only update and display if true.
   */
  PerformanceDisplay.prototype.update = function (renderedThisFrame) {
    const time = getTimestamp$1();
    const updateDisplay = defaultValue(renderedThisFrame, true);

    this._fpsFrameCount++;
    const fpsElapsedTime = time - this._lastFpsSampleTime;
    if (fpsElapsedTime > 1000) {
      let fps = "N/A";
      if (updateDisplay) {
        fps = ((this._fpsFrameCount * 1000) / fpsElapsedTime) | 0;
      }

      this._fpsText.nodeValue = `${fps} FPS`;
      this._lastFpsSampleTime = time;
      this._fpsFrameCount = 0;
    }

    this._msFrameCount++;
    const msElapsedTime = time - this._lastMsSampleTime;
    if (msElapsedTime > 200) {
      let ms = "N/A";
      if (updateDisplay) {
        ms = (msElapsedTime / this._msFrameCount).toFixed(2);
      }

      this._msText.nodeValue = `${ms} MS`;
      this._lastMsSampleTime = time;
      this._msFrameCount = 0;
    }
  };

  /**
   * Destroys the WebGL resources held by this object.
   */
  PerformanceDisplay.prototype.destroy = function () {
    return destroyObject(this);
  };

  /**
   * @private
   */
  function PickDepth() {
    this._framebuffer = new FramebufferManager();

    this._textureToCopy = undefined;
    this._copyDepthCommand = undefined;
  }

  Object.defineProperties(PickDepth.prototype, {
    framebuffer: {
      get: function () {
        return this._framebuffer.framebuffer;
      },
    },
  });

  function updateFramebuffers$2(pickDepth, context, depthTexture) {
    const width = depthTexture.width;
    const height = depthTexture.height;
    pickDepth._framebuffer.update(context, width, height);
  }

  function updateCopyCommands(pickDepth, context, depthTexture) {
    if (!defined(pickDepth._copyDepthCommand)) {
      const fs =
        "uniform highp sampler2D u_texture;\n" +
        "varying vec2 v_textureCoordinates;\n" +
        "void main()\n" +
        "{\n" +
        "    gl_FragColor = czm_packDepth(texture2D(u_texture, v_textureCoordinates).r);\n" +
        "}\n";
      pickDepth._copyDepthCommand = context.createViewportQuadCommand(fs, {
        renderState: RenderState.fromCache(),
        uniformMap: {
          u_texture: function () {
            return pickDepth._textureToCopy;
          },
        },
        owner: pickDepth,
      });
    }

    pickDepth._textureToCopy = depthTexture;
    pickDepth._copyDepthCommand.framebuffer = pickDepth.framebuffer;
  }

  PickDepth.prototype.update = function (context, depthTexture) {
    updateFramebuffers$2(this, context, depthTexture);
    updateCopyCommands(this, context, depthTexture);
  };

  const scratchPackedDepth = new Cartesian4();
  const packedDepthScale = new Cartesian4(
    1.0,
    1.0 / 255.0,
    1.0 / 65025.0,
    1.0 / 16581375.0
  );

  PickDepth.prototype.getDepth = function (context, x, y) {
    // If this function is called before the framebuffer is created, the depth is undefined.
    if (!defined(this.framebuffer)) {
      return undefined;
    }

    const pixels = context.readPixels({
      x: x,
      y: y,
      width: 1,
      height: 1,
      framebuffer: this.framebuffer,
    });

    const packedDepth = Cartesian4.unpack(pixels, 0, scratchPackedDepth);
    Cartesian4.divideByScalar(packedDepth, 255.0, packedDepth);
    return Cartesian4.dot(packedDepth, packedDepthScale);
  };

  PickDepth.prototype.executeCopyDepth = function (context, passState) {
    this._copyDepthCommand.execute(context, passState);
  };

  PickDepth.prototype.isDestroyed = function () {
    return false;
  };

  PickDepth.prototype.destroy = function () {
    this._framebuffer.destroy();
    if (defined(this._copyDepthCommand)) {
      this._copyDepthCommand.shaderProgram =
        defined(this._copyDepthCommand.shaderProgram) &&
        this._copyDepthCommand.shaderProgram.destroy();
    }

    return destroyObject(this);
  };

  /**
   * @private
   */
  function PickDepthFramebuffer() {
    this._framebuffer = new FramebufferManager({
      color: false,
      depthStencil: true,
      supportsDepthTexture: true,
    });
    this._passState = undefined;
  }

  Object.defineProperties(PickDepthFramebuffer.prototype, {
    framebuffer: {
      get: function () {
        return this._framebuffer.framebuffer;
      },
    },
  });

  function destroyResources$1(pickDepth) {
    pickDepth._framebuffer.destroy();
  }

  function createResources(pickDepth, context) {
    const width = context.drawingBufferWidth;
    const height = context.drawingBufferHeight;

    pickDepth._framebuffer.update(context, width, height);

    const passState = new PassState(context);
    passState.blendingEnabled = false;
    passState.scissorTest = {
      enabled: true,
      rectangle: new BoundingRectangle(),
    };
    passState.viewport = new BoundingRectangle();
    pickDepth._passState = passState;
  }

  PickDepthFramebuffer.prototype.update = function (
    context,
    drawingBufferPosition,
    viewport
  ) {
    const width = viewport.width;
    const height = viewport.height;

    if (this._framebuffer.isDirty(width, height)) {
      createResources(this, context);
    }

    const framebuffer = this.framebuffer;
    const passState = this._passState;
    passState.framebuffer = framebuffer;
    passState.viewport.width = width;
    passState.viewport.height = height;
    passState.scissorTest.rectangle.x = drawingBufferPosition.x;
    passState.scissorTest.rectangle.y = height - drawingBufferPosition.y;
    passState.scissorTest.rectangle.width = 1;
    passState.scissorTest.rectangle.height = 1;

    return passState;
  };

  PickDepthFramebuffer.prototype.isDestroyed = function () {
    return false;
  };

  PickDepthFramebuffer.prototype.destroy = function () {
    destroyResources$1(this);
    return destroyObject(this);
  };

  /**
   * @private
   */
  function PickFramebuffer(context) {
    // Override per-command states
    const passState = new PassState(context);
    passState.blendingEnabled = false;
    passState.scissorTest = {
      enabled: true,
      rectangle: new BoundingRectangle(),
    };
    passState.viewport = new BoundingRectangle();

    this._context = context;
    this._fb = new FramebufferManager({
      depthStencil: true,
    });
    this._passState = passState;
    this._width = 0;
    this._height = 0;
  }
  PickFramebuffer.prototype.begin = function (screenSpaceRectangle, viewport) {
    const context = this._context;
    const width = viewport.width;
    const height = viewport.height;

    BoundingRectangle.clone(
      screenSpaceRectangle,
      this._passState.scissorTest.rectangle
    );

    // Create or recreate renderbuffers and framebuffer used for picking
    this._width = width;
    this._height = height;
    this._fb.update(context, width, height);
    this._passState.framebuffer = this._fb.framebuffer;

    this._passState.viewport.width = width;
    this._passState.viewport.height = height;

    return this._passState;
  };

  const colorScratch = new Color();

  PickFramebuffer.prototype.end = function (screenSpaceRectangle) {
    const width = defaultValue(screenSpaceRectangle.width, 1.0);
    const height = defaultValue(screenSpaceRectangle.height, 1.0);

    const context = this._context;
    const pixels = context.readPixels({
      x: screenSpaceRectangle.x,
      y: screenSpaceRectangle.y,
      width: width,
      height: height,
      framebuffer: this._fb.framebuffer,
    });

    const max = Math.max(width, height);
    const length = max * max;
    const halfWidth = Math.floor(width * 0.5);
    const halfHeight = Math.floor(height * 0.5);

    let x = 0;
    let y = 0;
    let dx = 0;
    let dy = -1;

    // Spiral around the center pixel, this is a workaround until
    // we can access the depth buffer on all browsers.

    // The region does not have to square and the dimensions do not have to be odd, but
    // loop iterations would be wasted. Prefer square regions where the size is odd.
    for (let i = 0; i < length; ++i) {
      if (
        -halfWidth <= x &&
        x <= halfWidth &&
        -halfHeight <= y &&
        y <= halfHeight
      ) {
        const index = 4 * ((halfHeight - y) * width + x + halfWidth);

        colorScratch.red = Color.byteToFloat(pixels[index]);
        colorScratch.green = Color.byteToFloat(pixels[index + 1]);
        colorScratch.blue = Color.byteToFloat(pixels[index + 2]);
        colorScratch.alpha = Color.byteToFloat(pixels[index + 3]);

        const object = context.getObjectByPickColor(colorScratch);
        if (defined(object)) {
          return object;
        }
      }

      // if (top right || bottom left corners) || (top left corner) || (bottom right corner + (1, 0))
      // change spiral direction
      if (x === y || (x < 0 && -x === y) || (x > 0 && x === 1 - y)) {
        const temp = dx;
        dx = -dy;
        dy = temp;
      }

      x += dx;
      y += dy;
    }

    return undefined;
  };

  PickFramebuffer.prototype.isDestroyed = function () {
    return false;
  };

  PickFramebuffer.prototype.destroy = function () {
    this._fb.destroy();
    return destroyObject(this);
  };

  /**
   * @private
   */
  function SceneFramebuffer() {
    this._numSamples = 1;
    this._colorFramebuffer = new FramebufferManager({
      depthStencil: true,
      supportsDepthTexture: true,
    });
    this._idFramebuffer = new FramebufferManager({
      depthStencil: true,
      supportsDepthTexture: true,
    });

    this._idClearColor = new Color(0.0, 0.0, 0.0, 0.0);

    this._clearCommand = new ClearCommand({
      color: new Color(0.0, 0.0, 0.0, 0.0),
      depth: 1.0,
      owner: this,
    });
  }

  function destroyResources(post) {
    post._colorFramebuffer.destroy();
    post._idFramebuffer.destroy();
  }

  Object.defineProperties(SceneFramebuffer.prototype, {
    framebuffer: {
      get: function () {
        return this._colorFramebuffer.framebuffer;
      },
    },
    idFramebuffer: {
      get: function () {
        return this._idFramebuffer.framebuffer;
      },
    },
    depthStencilTexture: {
      get: function () {
        return this._colorFramebuffer.getDepthStencilTexture();
      },
    },
  });

  SceneFramebuffer.prototype.update = function (
    context,
    viewport,
    hdr,
    numSamples
  ) {
    const width = viewport.width;
    const height = viewport.height;
    const pixelDatatype = hdr
      ? context.halfFloatingPointTexture
        ? PixelDatatype$1.HALF_FLOAT
        : PixelDatatype$1.FLOAT
      : PixelDatatype$1.UNSIGNED_BYTE;
    this._numSamples = numSamples;
    this._colorFramebuffer.update(
      context,
      width,
      height,
      numSamples,
      pixelDatatype
    );
    this._idFramebuffer.update(context, width, height);
  };

  SceneFramebuffer.prototype.clear = function (context, passState, clearColor) {
    Color.clone(clearColor, this._clearCommand.color);
    Color.clone(this._idClearColor, this._clearCommand.color);
    this._colorFramebuffer.clear(context, this._clearCommand, passState);
    this._idFramebuffer.clear(context, this._clearCommand, passState);
  };

  SceneFramebuffer.prototype.getFramebuffer = function () {
    return this._colorFramebuffer.framebuffer;
  };

  SceneFramebuffer.prototype.getIdFramebuffer = function () {
    return this._idFramebuffer.framebuffer;
  };

  SceneFramebuffer.prototype.prepareColorTextures = function (context) {
    if (this._numSamples > 1) {
      this._colorFramebuffer.prepareTextures(context);
    }
  };

  SceneFramebuffer.prototype.isDestroyed = function () {
    return false;
  };

  SceneFramebuffer.prototype.destroy = function () {
    destroyResources(this);
    return destroyObject(this);
  };

  /**
   * @private
   */
  function ShadowMapShader() {}

  ShadowMapShader.getShadowCastShaderKeyword = function (
    isPointLight,
    isTerrain,
    usesDepthTexture,
    isOpaque
  ) {
    return `castShadow ${isPointLight} ${isTerrain} ${usesDepthTexture} ${isOpaque}`;
  };

  ShadowMapShader.createShadowCastVertexShader = function (
    vs,
    isPointLight,
    isTerrain
  ) {
    const defines = vs.defines.slice(0);
    const sources = vs.sources.slice(0);

    defines.push("SHADOW_MAP");

    if (isTerrain) {
      defines.push("GENERATE_POSITION");
    }

    const positionVaryingName = ShaderSource.findPositionVarying(vs);
    const hasPositionVarying = defined(positionVaryingName);

    if (isPointLight && !hasPositionVarying) {
      const length = sources.length;
      for (let j = 0; j < length; ++j) {
        sources[j] = ShaderSource.replaceMain(sources[j], "czm_shadow_cast_main");
      }

      const shadowVS =
        "varying vec3 v_positionEC; \n" +
        "void main() \n" +
        "{ \n" +
        "    czm_shadow_cast_main(); \n" +
        "    v_positionEC = (czm_inverseProjection * gl_Position).xyz; \n" +
        "}";
      sources.push(shadowVS);
    }

    return new ShaderSource({
      defines: defines,
      sources: sources,
    });
  };

  ShadowMapShader.createShadowCastFragmentShader = function (
    fs,
    isPointLight,
    usesDepthTexture,
    opaque
  ) {
    const defines = fs.defines.slice(0);
    const sources = fs.sources.slice(0);

    defines.push("SHADOW_MAP");

    let positionVaryingName = ShaderSource.findPositionVarying(fs);
    const hasPositionVarying = defined(positionVaryingName);
    if (!hasPositionVarying) {
      positionVaryingName = "v_positionEC";
    }

    const length = sources.length;
    for (let i = 0; i < length; ++i) {
      sources[i] = ShaderSource.replaceMain(sources[i], "czm_shadow_cast_main");
    }

    let fsSource = "";

    if (isPointLight) {
      if (!hasPositionVarying) {
        fsSource += "varying vec3 v_positionEC; \n";
      }
      fsSource += "uniform vec4 shadowMap_lightPositionEC; \n";
    }

    if (opaque) {
      fsSource += "void main() \n" + "{ \n";
    } else {
      fsSource +=
        "void main() \n" +
        "{ \n" +
        "    czm_shadow_cast_main(); \n" +
        "    if (gl_FragColor.a == 0.0) \n" +
        "    { \n" +
        "       discard; \n" +
        "    } \n";
    }

    if (isPointLight) {
      fsSource +=
        `    float distance = length(${positionVaryingName}); \n` +
        `    if (distance >= shadowMap_lightPositionEC.w) \n` +
        `    { \n` +
        `        discard; \n` +
        `    } \n` +
        `    distance /= shadowMap_lightPositionEC.w; // radius \n` +
        `    gl_FragColor = czm_packDepth(distance); \n`;
    } else if (usesDepthTexture) {
      fsSource += "    gl_FragColor = vec4(1.0); \n";
    } else {
      fsSource += "    gl_FragColor = czm_packDepth(gl_FragCoord.z); \n";
    }

    fsSource += "} \n";

    sources.push(fsSource);

    return new ShaderSource({
      defines: defines,
      sources: sources,
    });
  };

  ShadowMapShader.getShadowReceiveShaderKeyword = function (
    shadowMap,
    castShadows,
    isTerrain,
    hasTerrainNormal
  ) {
    const usesDepthTexture = shadowMap._usesDepthTexture;
    const polygonOffsetSupported = shadowMap._polygonOffsetSupported;
    const isPointLight = shadowMap._isPointLight;
    const isSpotLight = shadowMap._isSpotLight;
    const hasCascades = shadowMap._numberOfCascades > 1;
    const debugCascadeColors = shadowMap.debugCascadeColors;
    const softShadows = shadowMap.softShadows;

    return `receiveShadow ${usesDepthTexture}${polygonOffsetSupported}${isPointLight}${isSpotLight}${hasCascades}${debugCascadeColors}${softShadows}${castShadows}${isTerrain}${hasTerrainNormal}`;
  };

  ShadowMapShader.createShadowReceiveVertexShader = function (
    vs,
    isTerrain,
    hasTerrainNormal
  ) {
    const defines = vs.defines.slice(0);
    const sources = vs.sources.slice(0);

    defines.push("SHADOW_MAP");

    if (isTerrain) {
      if (hasTerrainNormal) {
        defines.push("GENERATE_POSITION_AND_NORMAL");
      } else {
        defines.push("GENERATE_POSITION");
      }
    }

    return new ShaderSource({
      defines: defines,
      sources: sources,
    });
  };

  ShadowMapShader.createShadowReceiveFragmentShader = function (
    fs,
    shadowMap,
    castShadows,
    isTerrain,
    hasTerrainNormal
  ) {
    const normalVaryingName = ShaderSource.findNormalVarying(fs);
    const hasNormalVarying =
      (!isTerrain && defined(normalVaryingName)) ||
      (isTerrain && hasTerrainNormal);

    const positionVaryingName = ShaderSource.findPositionVarying(fs);
    const hasPositionVarying = defined(positionVaryingName);

    const usesDepthTexture = shadowMap._usesDepthTexture;
    const polygonOffsetSupported = shadowMap._polygonOffsetSupported;
    const isPointLight = shadowMap._isPointLight;
    const isSpotLight = shadowMap._isSpotLight;
    const hasCascades = shadowMap._numberOfCascades > 1;
    const debugCascadeColors = shadowMap.debugCascadeColors;
    const softShadows = shadowMap.softShadows;
    const bias = isPointLight
      ? shadowMap._pointBias
      : isTerrain
      ? shadowMap._terrainBias
      : shadowMap._primitiveBias;

    const defines = fs.defines.slice(0);
    const sources = fs.sources.slice(0);

    const length = sources.length;
    for (let i = 0; i < length; ++i) {
      sources[i] = ShaderSource.replaceMain(
        sources[i],
        "czm_shadow_receive_main"
      );
    }

    if (isPointLight) {
      defines.push("USE_CUBE_MAP_SHADOW");
    } else if (usesDepthTexture) {
      defines.push("USE_SHADOW_DEPTH_TEXTURE");
    }

    if (softShadows && !isPointLight) {
      defines.push("USE_SOFT_SHADOWS");
    }

    // Enable day-night shading so that the globe is dark when the light is below the horizon
    if (hasCascades && castShadows && isTerrain) {
      if (hasNormalVarying) {
        defines.push("ENABLE_VERTEX_LIGHTING");
      } else {
        defines.push("ENABLE_DAYNIGHT_SHADING");
      }
    }

    if (castShadows && bias.normalShading && hasNormalVarying) {
      defines.push("USE_NORMAL_SHADING");
      if (bias.normalShadingSmooth > 0.0) {
        defines.push("USE_NORMAL_SHADING_SMOOTH");
      }
    }

    let fsSource = "";

    if (isPointLight) {
      fsSource += "uniform samplerCube shadowMap_textureCube; \n";
    } else {
      fsSource += "uniform sampler2D shadowMap_texture; \n";
    }

    let returnPositionEC;
    if (hasPositionVarying) {
      returnPositionEC = `    return vec4(${positionVaryingName}, 1.0); \n`;
    } else {
      returnPositionEC =
        "#ifndef LOG_DEPTH \n" +
        "    return czm_windowToEyeCoordinates(gl_FragCoord); \n" +
        "#else \n" +
        "    return vec4(v_logPositionEC, 1.0); \n" +
        "#endif \n";
    }

    fsSource +=
      `${
      "uniform mat4 shadowMap_matrix; \n" +
      "uniform vec3 shadowMap_lightDirectionEC; \n" +
      "uniform vec4 shadowMap_lightPositionEC; \n" +
      "uniform vec4 shadowMap_normalOffsetScaleDistanceMaxDistanceAndDarkness; \n" +
      "uniform vec4 shadowMap_texelSizeDepthBiasAndNormalShadingSmooth; \n" +
      "#ifdef LOG_DEPTH \n" +
      "varying vec3 v_logPositionEC; \n" +
      "#endif \n" +
      "vec4 getPositionEC() \n" +
      "{ \n"
    }${returnPositionEC}} \n` +
      `vec3 getNormalEC() \n` +
      `{ \n${
      hasNormalVarying
        ? `    return normalize(${normalVaryingName}); \n`
        : "    return vec3(1.0); \n"
    }} \n` +
      // Offset the shadow position in the direction of the normal for perpendicular and back faces
      `void applyNormalOffset(inout vec4 positionEC, vec3 normalEC, float nDotL) \n` +
      `{ \n${
      bias.normalOffset && hasNormalVarying
        ? "    float normalOffset = shadowMap_normalOffsetScaleDistanceMaxDistanceAndDarkness.x; \n" +
          "    float normalOffsetScale = 1.0 - nDotL; \n" +
          "    vec3 offset = normalOffset * normalOffsetScale * normalEC; \n" +
          "    positionEC.xyz += offset; \n"
        : ""
    }} \n`;

    fsSource +=
      "void main() \n" +
      "{ \n" +
      "    czm_shadow_receive_main(); \n" +
      "    vec4 positionEC = getPositionEC(); \n" +
      "    vec3 normalEC = getNormalEC(); \n" +
      "    float depth = -positionEC.z; \n";

    fsSource +=
      "    czm_shadowParameters shadowParameters; \n" +
      "    shadowParameters.texelStepSize = shadowMap_texelSizeDepthBiasAndNormalShadingSmooth.xy; \n" +
      "    shadowParameters.depthBias = shadowMap_texelSizeDepthBiasAndNormalShadingSmooth.z; \n" +
      "    shadowParameters.normalShadingSmooth = shadowMap_texelSizeDepthBiasAndNormalShadingSmooth.w; \n" +
      "    shadowParameters.darkness = shadowMap_normalOffsetScaleDistanceMaxDistanceAndDarkness.w; \n";

    if (isTerrain) {
      // Scale depth bias based on view distance to reduce z-fighting in distant terrain
      fsSource += "    shadowParameters.depthBias *= max(depth * 0.01, 1.0); \n";
    } else if (!polygonOffsetSupported) {
      // If polygon offset isn't supported push the depth back based on view, however this
      // causes light leaking at further away views
      fsSource +=
        "    shadowParameters.depthBias *= mix(1.0, 100.0, depth * 0.0015); \n";
    }

    if (isPointLight) {
      fsSource +=
        "    vec3 directionEC = positionEC.xyz - shadowMap_lightPositionEC.xyz; \n" +
        "    float distance = length(directionEC); \n" +
        "    directionEC = normalize(directionEC); \n" +
        "    float radius = shadowMap_lightPositionEC.w; \n" +
        "    // Stop early if the fragment is beyond the point light radius \n" +
        "    if (distance > radius) \n" +
        "    { \n" +
        "        return; \n" +
        "    } \n" +
        "    vec3 directionWC  = czm_inverseViewRotation * directionEC; \n" +
        "    shadowParameters.depth = distance / radius; \n" +
        "    shadowParameters.nDotL = clamp(dot(normalEC, -directionEC), 0.0, 1.0); \n" +
        "    shadowParameters.texCoords = directionWC; \n" +
        "    float visibility = czm_shadowVisibility(shadowMap_textureCube, shadowParameters); \n";
    } else if (isSpotLight) {
      fsSource +=
        "    vec3 directionEC = normalize(positionEC.xyz - shadowMap_lightPositionEC.xyz); \n" +
        "    float nDotL = clamp(dot(normalEC, -directionEC), 0.0, 1.0); \n" +
        "    applyNormalOffset(positionEC, normalEC, nDotL); \n" +
        "    vec4 shadowPosition = shadowMap_matrix * positionEC; \n" +
        "    // Spot light uses a perspective projection, so perform the perspective divide \n" +
        "    shadowPosition /= shadowPosition.w; \n" +
        "    // Stop early if the fragment is not in the shadow bounds \n" +
        "    if (any(lessThan(shadowPosition.xyz, vec3(0.0))) || any(greaterThan(shadowPosition.xyz, vec3(1.0)))) \n" +
        "    { \n" +
        "        return; \n" +
        "    } \n" +
        "    shadowParameters.texCoords = shadowPosition.xy; \n" +
        "    shadowParameters.depth = shadowPosition.z; \n" +
        "    shadowParameters.nDotL = nDotL; \n" +
        "    float visibility = czm_shadowVisibility(shadowMap_texture, shadowParameters); \n";
    } else if (hasCascades) {
      fsSource += `${
      "    float maxDepth = shadowMap_cascadeSplits[1].w; \n" +
      "    // Stop early if the eye depth exceeds the last cascade \n" +
      "    if (depth > maxDepth) \n" +
      "    { \n" +
      "        return; \n" +
      "    } \n" +
      "    // Get the cascade based on the eye-space depth \n" +
      "    vec4 weights = czm_cascadeWeights(depth); \n" +
      "    // Apply normal offset \n" +
      "    float nDotL = clamp(dot(normalEC, shadowMap_lightDirectionEC), 0.0, 1.0); \n" +
      "    applyNormalOffset(positionEC, normalEC, nDotL); \n" +
      "    // Transform position into the cascade \n" +
      "    vec4 shadowPosition = czm_cascadeMatrix(weights) * positionEC; \n" +
      "    // Get visibility \n" +
      "    shadowParameters.texCoords = shadowPosition.xy; \n" +
      "    shadowParameters.depth = shadowPosition.z; \n" +
      "    shadowParameters.nDotL = nDotL; \n" +
      "    float visibility = czm_shadowVisibility(shadowMap_texture, shadowParameters); \n" +
      "    // Fade out shadows that are far away \n" +
      "    float shadowMapMaximumDistance = shadowMap_normalOffsetScaleDistanceMaxDistanceAndDarkness.z; \n" +
      "    float fade = max((depth - shadowMapMaximumDistance * 0.8) / (shadowMapMaximumDistance * 0.2), 0.0); \n" +
      "    visibility = mix(visibility, 1.0, fade); \n"
    }${
      debugCascadeColors
        ? "    // Draw cascade colors for debugging \n" +
          "    gl_FragColor *= czm_cascadeColor(weights); \n"
        : ""
    }`;
    } else {
      fsSource +=
        "    float nDotL = clamp(dot(normalEC, shadowMap_lightDirectionEC), 0.0, 1.0); \n" +
        "    applyNormalOffset(positionEC, normalEC, nDotL); \n" +
        "    vec4 shadowPosition = shadowMap_matrix * positionEC; \n" +
        "    // Stop early if the fragment is not in the shadow bounds \n" +
        "    if (any(lessThan(shadowPosition.xyz, vec3(0.0))) || any(greaterThan(shadowPosition.xyz, vec3(1.0)))) \n" +
        "    { \n" +
        "        return; \n" +
        "    } \n" +
        "    shadowParameters.texCoords = shadowPosition.xy; \n" +
        "    shadowParameters.depth = shadowPosition.z; \n" +
        "    shadowParameters.nDotL = nDotL; \n" +
        "    float visibility = czm_shadowVisibility(shadowMap_texture, shadowParameters); \n";
    }

    fsSource += "    gl_FragColor.rgb *= visibility; \n" + "} \n";

    sources.push(fsSource);

    return new ShaderSource({
      defines: defines,
      sources: sources,
    });
  };

  /**
   * Use {@link Viewer#shadowMap} to get the scene's shadow map. Do not construct this directly.
   *
   * <p>
   * The normalOffset bias pushes the shadows forward slightly, and may be disabled
   * for applications that require ultra precise shadows.
   * </p>
   *
   * @alias ShadowMap
   * @internalConstructor
   * @class
   *
   * @param {Object} options An object containing the following properties:
   * @param {Camera} options.lightCamera A camera representing the light source.
   * @param {Boolean} [options.enabled=true] Whether the shadow map is enabled.
   * @param {Boolean} [options.isPointLight=false] Whether the light source is a point light. Point light shadows do not use cascades.
   * @param {Number} [options.pointLightRadius=100.0] Radius of the point light.
   * @param {Boolean} [options.cascadesEnabled=true] Use multiple shadow maps to cover different partitions of the view frustum.
   * @param {Number} [options.numberOfCascades=4] The number of cascades to use for the shadow map. Supported values are one and four.
   * @param {Number} [options.maximumDistance=5000.0] The maximum distance used for generating cascaded shadows. Lower values improve shadow quality.
   * @param {Number} [options.size=2048] The width and height, in pixels, of each shadow map.
   * @param {Boolean} [options.softShadows=false] Whether percentage-closer-filtering is enabled for producing softer shadows.
   * @param {Number} [options.darkness=0.3] The shadow darkness.
   * @param {Boolean} [options.normalOffset=true] Whether a normal bias is applied to shadows.
   * @param {Boolean} [options.fadingEnabled=true] Whether shadows start to fade out once the light gets closer to the horizon.
   *
   * @exception {DeveloperError} Only one or four cascades are supported.
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Shadows.html|Cesium Sandcastle Shadows Demo}
   */
  function ShadowMap(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    // options.context is an undocumented option
    const context = options.context;

    //>>includeStart('debug', pragmas.debug);
    if (!defined(context)) {
      throw new DeveloperError("context is required.");
    }
    if (!defined(options.lightCamera)) {
      throw new DeveloperError("lightCamera is required.");
    }
    if (
      defined(options.numberOfCascades) &&
      options.numberOfCascades !== 1 &&
      options.numberOfCascades !== 4
    ) {
      throw new DeveloperError("Only one or four cascades are supported.");
    }
    //>>includeEnd('debug');

    this._enabled = defaultValue(options.enabled, true);
    this._softShadows = defaultValue(options.softShadows, false);
    this._normalOffset = defaultValue(options.normalOffset, true);
    this.dirty = true;

    /**
     * Specifies whether the shadow map originates from a light source. Shadow maps that are used for analytical
     * purposes should set this to false so as not to affect scene rendering.
     *
     * @private
     */
    this.fromLightSource = defaultValue(options.fromLightSource, true);

    /**
     * Determines the darkness of the shadows.
     *
     * @type {Number}
     * @default 0.3
     */
    this.darkness = defaultValue(options.darkness, 0.3);
    this._darkness = this.darkness;

    /**
     * Determines whether shadows start to fade out once the light gets closer to the horizon.
     *
     * @type {Boolean}
     * @default true
     */
    this.fadingEnabled = defaultValue(options.fadingEnabled, true);

    /**
     * Determines the maximum distance of the shadow map. Only applicable for cascaded shadows. Larger distances may result in lower quality shadows.
     *
     * @type {Number}
     * @default 5000.0
     */
    this.maximumDistance = defaultValue(options.maximumDistance, 5000.0);

    this._outOfView = false;
    this._outOfViewPrevious = false;
    this._needsUpdate = true;

    // In IE11 and Edge polygon offset is not functional.
    // TODO : Also disabled for instances of Firefox and Chrome running ANGLE that do not support depth textures.
    // Re-enable once https://github.com/CesiumGS/cesium/issues/4560 is resolved.
    let polygonOffsetSupported = true;
    if (
      FeatureDetection.isInternetExplorer() ||
      FeatureDetection.isEdge() ||
      ((FeatureDetection.isChrome() || FeatureDetection.isFirefox()) &&
        FeatureDetection.isWindows() &&
        !context.depthTexture)
    ) {
      polygonOffsetSupported = false;
    }
    this._polygonOffsetSupported = polygonOffsetSupported;

    this._terrainBias = {
      polygonOffset: polygonOffsetSupported,
      polygonOffsetFactor: 1.1,
      polygonOffsetUnits: 4.0,
      normalOffset: this._normalOffset,
      normalOffsetScale: 0.5,
      normalShading: true,
      normalShadingSmooth: 0.3,
      depthBias: 0.0001,
    };

    this._primitiveBias = {
      polygonOffset: polygonOffsetSupported,
      polygonOffsetFactor: 1.1,
      polygonOffsetUnits: 4.0,
      normalOffset: this._normalOffset,
      normalOffsetScale: 0.1,
      normalShading: true,
      normalShadingSmooth: 0.05,
      depthBias: 0.00002,
    };

    this._pointBias = {
      polygonOffset: false,
      polygonOffsetFactor: 1.1,
      polygonOffsetUnits: 4.0,
      normalOffset: this._normalOffset,
      normalOffsetScale: 0.0,
      normalShading: true,
      normalShadingSmooth: 0.1,
      depthBias: 0.0005,
    };

    // Framebuffer resources
    this._depthAttachment = undefined;
    this._colorAttachment = undefined;

    // Uniforms
    this._shadowMapMatrix = new Matrix4();
    this._shadowMapTexture = undefined;
    this._lightDirectionEC = new Cartesian3();
    this._lightPositionEC = new Cartesian4();
    this._distance = 0.0;

    this._lightCamera = options.lightCamera;
    this._shadowMapCamera = new ShadowMapCamera();
    this._shadowMapCullingVolume = undefined;
    this._sceneCamera = undefined;
    this._boundingSphere = new BoundingSphere();

    this._isPointLight = defaultValue(options.isPointLight, false);
    this._pointLightRadius = defaultValue(options.pointLightRadius, 100.0);

    this._cascadesEnabled = this._isPointLight
      ? false
      : defaultValue(options.cascadesEnabled, true);
    this._numberOfCascades = !this._cascadesEnabled
      ? 0
      : defaultValue(options.numberOfCascades, 4);
    this._fitNearFar = true;
    this._maximumCascadeDistances = [25.0, 150.0, 700.0, Number.MAX_VALUE];

    this._textureSize = new Cartesian2();

    this._isSpotLight = false;
    if (this._cascadesEnabled) {
      // Cascaded shadows are always orthographic. The frustum dimensions are calculated on the fly.
      this._shadowMapCamera.frustum = new OrthographicOffCenterFrustum();
    } else if (defined(this._lightCamera.frustum.fov)) {
      // If the light camera uses a perspective frustum, then the light source is a spot light
      this._isSpotLight = true;
    }

    // Uniforms
    this._cascadeSplits = [new Cartesian4(), new Cartesian4()];
    this._cascadeMatrices = [
      new Matrix4(),
      new Matrix4(),
      new Matrix4(),
      new Matrix4(),
    ];
    this._cascadeDistances = new Cartesian4();

    let numberOfPasses;
    if (this._isPointLight) {
      numberOfPasses = 6; // One shadow map for each direction
    } else if (!this._cascadesEnabled) {
      numberOfPasses = 1;
    } else {
      numberOfPasses = this._numberOfCascades;
    }

    this._passes = new Array(numberOfPasses);
    for (let i = 0; i < numberOfPasses; ++i) {
      this._passes[i] = new ShadowPass(context);
    }

    this.debugShow = false;
    this.debugFreezeFrame = false;
    this._debugFreezeFrame = false;
    this._debugCascadeColors = false;
    this._debugLightFrustum = undefined;
    this._debugCameraFrustum = undefined;
    this._debugCascadeFrustums = new Array(this._numberOfCascades);
    this._debugShadowViewCommand = undefined;

    this._usesDepthTexture = context.depthTexture;

    if (this._isPointLight) {
      this._usesDepthTexture = false;
    }

    // Create render states for shadow casters
    this._primitiveRenderState = undefined;
    this._terrainRenderState = undefined;
    this._pointRenderState = undefined;
    createRenderStates(this);

    // For clearing the shadow map texture every frame
    this._clearCommand = new ClearCommand({
      depth: 1.0,
      color: new Color(),
    });

    this._clearPassState = new PassState(context);

    this._size = defaultValue(options.size, 2048);
    this.size = this._size;
  }

  /**
   * Global maximum shadow distance used to prevent far off receivers from extending
   * the shadow far plane. This helps set a tighter near/far when viewing objects from space.
   *
   * @private
   */
  ShadowMap.MAXIMUM_DISTANCE = 20000.0;

  function ShadowPass(context) {
    this.camera = new ShadowMapCamera();
    this.passState = new PassState(context);
    this.framebuffer = undefined;
    this.textureOffsets = undefined;
    this.commandList = [];
    this.cullingVolume = undefined;
  }

  function createRenderState(colorMask, bias) {
    return RenderState.fromCache({
      cull: {
        enabled: true,
        face: CullFace$1.BACK,
      },
      depthTest: {
        enabled: true,
      },
      colorMask: {
        red: colorMask,
        green: colorMask,
        blue: colorMask,
        alpha: colorMask,
      },
      depthMask: true,
      polygonOffset: {
        enabled: bias.polygonOffset,
        factor: bias.polygonOffsetFactor,
        units: bias.polygonOffsetUnits,
      },
    });
  }

  function createRenderStates(shadowMap) {
    // Enable the color mask if the shadow map is backed by a color texture, e.g. when depth textures aren't supported
    const colorMask = !shadowMap._usesDepthTexture;
    shadowMap._primitiveRenderState = createRenderState(
      colorMask,
      shadowMap._primitiveBias
    );
    shadowMap._terrainRenderState = createRenderState(
      colorMask,
      shadowMap._terrainBias
    );
    shadowMap._pointRenderState = createRenderState(
      colorMask,
      shadowMap._pointBias
    );
  }

  /**
   * @private
   */
  ShadowMap.prototype.debugCreateRenderStates = function () {
    createRenderStates(this);
  };

  Object.defineProperties(ShadowMap.prototype, {
    /**
     * Determines if the shadow map will be shown.
     *
     * @memberof ShadowMap.prototype
     * @type {Boolean}
     * @default true
     */
    enabled: {
      get: function () {
        return this._enabled;
      },
      set: function (value) {
        this.dirty = this._enabled !== value;
        this._enabled = value;
      },
    },

    /**
     * Determines if a normal bias will be applied to shadows.
     *
     * @memberof ShadowMap.prototype
     * @type {Boolean}
     * @default true
     */
    normalOffset: {
      get: function () {
        return this._normalOffset;
      },
      set: function (value) {
        this.dirty = this._normalOffset !== value;
        this._normalOffset = value;
        this._terrainBias.normalOffset = value;
        this._primitiveBias.normalOffset = value;
        this._pointBias.normalOffset = value;
      },
    },

    /**
     * Determines if soft shadows are enabled. Uses pcf filtering which requires more texture reads and may hurt performance.
     *
     * @memberof ShadowMap.prototype
     * @type {Boolean}
     * @default false
     */
    softShadows: {
      get: function () {
        return this._softShadows;
      },
      set: function (value) {
        this.dirty = this._softShadows !== value;
        this._softShadows = value;
      },
    },

    /**
     * The width and height, in pixels, of each shadow map.
     *
     * @memberof ShadowMap.prototype
     * @type {Number}
     * @default 2048
     */
    size: {
      get: function () {
        return this._size;
      },
      set: function (value) {
        resize(this, value);
      },
    },

    /**
     * Whether the shadow map is out of view of the scene camera.
     *
     * @memberof ShadowMap.prototype
     * @type {Boolean}
     * @readonly
     * @private
     */
    outOfView: {
      get: function () {
        return this._outOfView;
      },
    },

    /**
     * The culling volume of the shadow frustum.
     *
     * @memberof ShadowMap.prototype
     * @type {CullingVolume}
     * @readonly
     * @private
     */
    shadowMapCullingVolume: {
      get: function () {
        return this._shadowMapCullingVolume;
      },
    },

    /**
     * The passes used for rendering shadows. Each face of a point light or each cascade for a cascaded shadow map is a separate pass.
     *
     * @memberof ShadowMap.prototype
     * @type {ShadowPass[]}
     * @readonly
     * @private
     */
    passes: {
      get: function () {
        return this._passes;
      },
    },

    /**
     * Whether the light source is a point light.
     *
     * @memberof ShadowMap.prototype
     * @type {Boolean}
     * @readonly
     * @private
     */
    isPointLight: {
      get: function () {
        return this._isPointLight;
      },
    },

    /**
     * Debug option for visualizing the cascades by color.
     *
     * @memberof ShadowMap.prototype
     * @type {Boolean}
     * @default false
     * @private
     */
    debugCascadeColors: {
      get: function () {
        return this._debugCascadeColors;
      },
      set: function (value) {
        this.dirty = this._debugCascadeColors !== value;
        this._debugCascadeColors = value;
      },
    },
  });

  function destroyFramebuffer(shadowMap) {
    const length = shadowMap._passes.length;
    for (let i = 0; i < length; ++i) {
      const pass = shadowMap._passes[i];
      const framebuffer = pass.framebuffer;
      if (defined(framebuffer) && !framebuffer.isDestroyed()) {
        framebuffer.destroy();
      }
      pass.framebuffer = undefined;
    }

    // Destroy the framebuffer attachments
    shadowMap._depthAttachment =
      shadowMap._depthAttachment && shadowMap._depthAttachment.destroy();
    shadowMap._colorAttachment =
      shadowMap._colorAttachment && shadowMap._colorAttachment.destroy();
  }

  function createFramebufferColor(shadowMap, context) {
    const depthRenderbuffer = new Renderbuffer({
      context: context,
      width: shadowMap._textureSize.x,
      height: shadowMap._textureSize.y,
      format: RenderbufferFormat$1.DEPTH_COMPONENT16,
    });

    const colorTexture = new Texture({
      context: context,
      width: shadowMap._textureSize.x,
      height: shadowMap._textureSize.y,
      pixelFormat: PixelFormat$1.RGBA,
      pixelDatatype: PixelDatatype$1.UNSIGNED_BYTE,
      sampler: Sampler.NEAREST,
    });

    const framebuffer = new Framebuffer({
      context: context,
      depthRenderbuffer: depthRenderbuffer,
      colorTextures: [colorTexture],
      destroyAttachments: false,
    });

    const length = shadowMap._passes.length;
    for (let i = 0; i < length; ++i) {
      const pass = shadowMap._passes[i];
      pass.framebuffer = framebuffer;
      pass.passState.framebuffer = framebuffer;
    }

    shadowMap._shadowMapTexture = colorTexture;
    shadowMap._depthAttachment = depthRenderbuffer;
    shadowMap._colorAttachment = colorTexture;
  }

  function createFramebufferDepth(shadowMap, context) {
    const depthStencilTexture = new Texture({
      context: context,
      width: shadowMap._textureSize.x,
      height: shadowMap._textureSize.y,
      pixelFormat: PixelFormat$1.DEPTH_STENCIL,
      pixelDatatype: PixelDatatype$1.UNSIGNED_INT_24_8,
      sampler: Sampler.NEAREST,
    });

    const framebuffer = new Framebuffer({
      context: context,
      depthStencilTexture: depthStencilTexture,
      destroyAttachments: false,
    });

    const length = shadowMap._passes.length;
    for (let i = 0; i < length; ++i) {
      const pass = shadowMap._passes[i];
      pass.framebuffer = framebuffer;
      pass.passState.framebuffer = framebuffer;
    }

    shadowMap._shadowMapTexture = depthStencilTexture;
    shadowMap._depthAttachment = depthStencilTexture;
  }

  function createFramebufferCube(shadowMap, context) {
    const depthRenderbuffer = new Renderbuffer({
      context: context,
      width: shadowMap._textureSize.x,
      height: shadowMap._textureSize.y,
      format: RenderbufferFormat$1.DEPTH_COMPONENT16,
    });

    const cubeMap = new CubeMap({
      context: context,
      width: shadowMap._textureSize.x,
      height: shadowMap._textureSize.y,
      pixelFormat: PixelFormat$1.RGBA,
      pixelDatatype: PixelDatatype$1.UNSIGNED_BYTE,
      sampler: Sampler.NEAREST,
    });

    const faces = [
      cubeMap.negativeX,
      cubeMap.negativeY,
      cubeMap.negativeZ,
      cubeMap.positiveX,
      cubeMap.positiveY,
      cubeMap.positiveZ,
    ];

    for (let i = 0; i < 6; ++i) {
      const framebuffer = new Framebuffer({
        context: context,
        depthRenderbuffer: depthRenderbuffer,
        colorTextures: [faces[i]],
        destroyAttachments: false,
      });
      const pass = shadowMap._passes[i];
      pass.framebuffer = framebuffer;
      pass.passState.framebuffer = framebuffer;
    }

    shadowMap._shadowMapTexture = cubeMap;
    shadowMap._depthAttachment = depthRenderbuffer;
    shadowMap._colorAttachment = cubeMap;
  }

  function createFramebuffer(shadowMap, context) {
    if (shadowMap._isPointLight) {
      createFramebufferCube(shadowMap, context);
    } else if (shadowMap._usesDepthTexture) {
      createFramebufferDepth(shadowMap, context);
    } else {
      createFramebufferColor(shadowMap, context);
    }
  }

  function checkFramebuffer(shadowMap, context) {
    // Attempt to make an FBO with only a depth texture. If it fails, fallback to a color texture.
    if (
      shadowMap._usesDepthTexture &&
      shadowMap._passes[0].framebuffer.status !==
        WebGLConstants$1.FRAMEBUFFER_COMPLETE
    ) {
      shadowMap._usesDepthTexture = false;
      createRenderStates(shadowMap);
      destroyFramebuffer(shadowMap);
      createFramebuffer(shadowMap, context);
    }
  }

  function updateFramebuffer(shadowMap, context) {
    if (
      !defined(shadowMap._passes[0].framebuffer) ||
      shadowMap._shadowMapTexture.width !== shadowMap._textureSize.x
    ) {
      destroyFramebuffer(shadowMap);
      createFramebuffer(shadowMap, context);
      checkFramebuffer(shadowMap, context);
      clearFramebuffer(shadowMap, context);
    }
  }

  function clearFramebuffer(shadowMap, context, shadowPass) {
    shadowPass = defaultValue(shadowPass, 0);
    if (shadowMap._isPointLight || shadowPass === 0) {
      shadowMap._clearCommand.framebuffer =
        shadowMap._passes[shadowPass].framebuffer;
      shadowMap._clearCommand.execute(context, shadowMap._clearPassState);
    }
  }

  function resize(shadowMap, size) {
    shadowMap._size = size;
    const passes = shadowMap._passes;
    const numberOfPasses = passes.length;
    const textureSize = shadowMap._textureSize;

    if (shadowMap._isPointLight) {
      size =
        ContextLimits.maximumCubeMapSize >= size
          ? size
          : ContextLimits.maximumCubeMapSize;
      textureSize.x = size;
      textureSize.y = size;
      const faceViewport = new BoundingRectangle(0, 0, size, size);
      passes[0].passState.viewport = faceViewport;
      passes[1].passState.viewport = faceViewport;
      passes[2].passState.viewport = faceViewport;
      passes[3].passState.viewport = faceViewport;
      passes[4].passState.viewport = faceViewport;
      passes[5].passState.viewport = faceViewport;
    } else if (numberOfPasses === 1) {
      // +----+
      // |  1 |
      // +----+
      size =
        ContextLimits.maximumTextureSize >= size
          ? size
          : ContextLimits.maximumTextureSize;
      textureSize.x = size;
      textureSize.y = size;
      passes[0].passState.viewport = new BoundingRectangle(0, 0, size, size);
    } else if (numberOfPasses === 4) {
      // +----+----+
      // |  3 |  4 |
      // +----+----+
      // |  1 |  2 |
      // +----+----+
      size =
        ContextLimits.maximumTextureSize >= size * 2
          ? size
          : ContextLimits.maximumTextureSize / 2;
      textureSize.x = size * 2;
      textureSize.y = size * 2;
      passes[0].passState.viewport = new BoundingRectangle(0, 0, size, size);
      passes[1].passState.viewport = new BoundingRectangle(size, 0, size, size);
      passes[2].passState.viewport = new BoundingRectangle(0, size, size, size);
      passes[3].passState.viewport = new BoundingRectangle(
        size,
        size,
        size,
        size
      );
    }

    // Update clear pass state
    shadowMap._clearPassState.viewport = new BoundingRectangle(
      0,
      0,
      textureSize.x,
      textureSize.y
    );

    // Transforms shadow coordinates [0, 1] into the pass's region of the texture
    for (let i = 0; i < numberOfPasses; ++i) {
      const pass = passes[i];
      const viewport = pass.passState.viewport;
      const biasX = viewport.x / textureSize.x;
      const biasY = viewport.y / textureSize.y;
      const scaleX = viewport.width / textureSize.x;
      const scaleY = viewport.height / textureSize.y;
      pass.textureOffsets = new Matrix4(
        scaleX,
        0.0,
        0.0,
        biasX,
        0.0,
        scaleY,
        0.0,
        biasY,
        0.0,
        0.0,
        1.0,
        0.0,
        0.0,
        0.0,
        0.0,
        1.0
      );
    }
  }

  const scratchViewport = new BoundingRectangle();

  function createDebugShadowViewCommand(shadowMap, context) {
    let fs;
    if (shadowMap._isPointLight) {
      fs =
        "uniform samplerCube shadowMap_textureCube; \n" +
        "varying vec2 v_textureCoordinates; \n" +
        "void main() \n" +
        "{ \n" +
        "    vec2 uv = v_textureCoordinates; \n" +
        "    vec3 dir; \n" +
        " \n" +
        "    if (uv.y < 0.5) \n" +
        "    { \n" +
        "        if (uv.x < 0.333) \n" +
        "        { \n" +
        "            dir.x = -1.0; \n" +
        "            dir.y = uv.x * 6.0 - 1.0; \n" +
        "            dir.z = uv.y * 4.0 - 1.0; \n" +
        "        } \n" +
        "        else if (uv.x < 0.666) \n" +
        "        { \n" +
        "            dir.y = -1.0; \n" +
        "            dir.x = uv.x * 6.0 - 3.0; \n" +
        "            dir.z = uv.y * 4.0 - 1.0; \n" +
        "        } \n" +
        "        else \n" +
        "        { \n" +
        "            dir.z = -1.0; \n" +
        "            dir.x = uv.x * 6.0 - 5.0; \n" +
        "            dir.y = uv.y * 4.0 - 1.0; \n" +
        "        } \n" +
        "    } \n" +
        "    else \n" +
        "    { \n" +
        "        if (uv.x < 0.333) \n" +
        "        { \n" +
        "            dir.x = 1.0; \n" +
        "            dir.y = uv.x * 6.0 - 1.0; \n" +
        "            dir.z = uv.y * 4.0 - 3.0; \n" +
        "        } \n" +
        "        else if (uv.x < 0.666) \n" +
        "        { \n" +
        "            dir.y = 1.0; \n" +
        "            dir.x = uv.x * 6.0 - 3.0; \n" +
        "            dir.z = uv.y * 4.0 - 3.0; \n" +
        "        } \n" +
        "        else \n" +
        "        { \n" +
        "            dir.z = 1.0; \n" +
        "            dir.x = uv.x * 6.0 - 5.0; \n" +
        "            dir.y = uv.y * 4.0 - 3.0; \n" +
        "        } \n" +
        "    } \n" +
        " \n" +
        "    float shadow = czm_unpackDepth(textureCube(shadowMap_textureCube, dir)); \n" +
        "    gl_FragColor = vec4(vec3(shadow), 1.0); \n" +
        "} \n";
    } else {
      fs =
        `${
        "uniform sampler2D shadowMap_texture; \n" +
        "varying vec2 v_textureCoordinates; \n" +
        "void main() \n" +
        "{ \n"
      }${
        shadowMap._usesDepthTexture
          ? "    float shadow = texture2D(shadowMap_texture, v_textureCoordinates).r; \n"
          : "    float shadow = czm_unpackDepth(texture2D(shadowMap_texture, v_textureCoordinates)); \n"
      }    gl_FragColor = vec4(vec3(shadow), 1.0); \n` + `} \n`;
    }

    const drawCommand = context.createViewportQuadCommand(fs, {
      uniformMap: {
        shadowMap_texture: function () {
          return shadowMap._shadowMapTexture;
        },
        shadowMap_textureCube: function () {
          return shadowMap._shadowMapTexture;
        },
      },
    });
    drawCommand.pass = Pass$1.OVERLAY;
    return drawCommand;
  }

  function updateDebugShadowViewCommand(shadowMap, frameState) {
    // Draws the shadow map on the bottom-right corner of the screen
    const context = frameState.context;
    const screenWidth = frameState.context.drawingBufferWidth;
    const screenHeight = frameState.context.drawingBufferHeight;
    const size = Math.min(screenWidth, screenHeight) * 0.3;

    const viewport = scratchViewport;
    viewport.x = screenWidth - size;
    viewport.y = 0;
    viewport.width = size;
    viewport.height = size;

    let debugCommand = shadowMap._debugShadowViewCommand;
    if (!defined(debugCommand)) {
      debugCommand = createDebugShadowViewCommand(shadowMap, context);
      shadowMap._debugShadowViewCommand = debugCommand;
    }

    // Get a new RenderState for the updated viewport size
    if (
      !defined(debugCommand.renderState) ||
      !BoundingRectangle.equals(debugCommand.renderState.viewport, viewport)
    ) {
      debugCommand.renderState = RenderState.fromCache({
        viewport: BoundingRectangle.clone(viewport),
      });
    }

    frameState.commandList.push(shadowMap._debugShadowViewCommand);
  }

  const frustumCornersNDC = new Array(8);
  frustumCornersNDC[0] = new Cartesian4(-1.0, -1.0, -1.0, 1.0);
  frustumCornersNDC[1] = new Cartesian4(1.0, -1.0, -1.0, 1.0);
  frustumCornersNDC[2] = new Cartesian4(1.0, 1.0, -1.0, 1.0);
  frustumCornersNDC[3] = new Cartesian4(-1.0, 1.0, -1.0, 1.0);
  frustumCornersNDC[4] = new Cartesian4(-1.0, -1.0, 1.0, 1.0);
  frustumCornersNDC[5] = new Cartesian4(1.0, -1.0, 1.0, 1.0);
  frustumCornersNDC[6] = new Cartesian4(1.0, 1.0, 1.0, 1.0);
  frustumCornersNDC[7] = new Cartesian4(-1.0, 1.0, 1.0, 1.0);

  const scratchMatrix = new Matrix4();
  const scratchFrustumCorners = new Array(8);
  for (let i = 0; i < 8; ++i) {
    scratchFrustumCorners[i] = new Cartesian4();
  }

  function createDebugPointLight(modelMatrix, color) {
    const box = new GeometryInstance({
      geometry: new BoxOutlineGeometry({
        minimum: new Cartesian3(-0.5, -0.5, -0.5),
        maximum: new Cartesian3(0.5, 0.5, 0.5),
      }),
      attributes: {
        color: ColorGeometryInstanceAttribute.fromColor(color),
      },
    });

    const sphere = new GeometryInstance({
      geometry: new SphereOutlineGeometry({
        radius: 0.5,
      }),
      attributes: {
        color: ColorGeometryInstanceAttribute.fromColor(color),
      },
    });

    return new Primitive$3({
      geometryInstances: [box, sphere],
      appearance: new PerInstanceColorAppearance({
        translucent: false,
        flat: true,
      }),
      asynchronous: false,
      modelMatrix: modelMatrix,
    });
  }

  const debugOutlineColors = [Color.RED, Color.GREEN, Color.BLUE, Color.MAGENTA];
  const scratchScale = new Cartesian3();

  function applyDebugSettings(shadowMap, frameState) {
    updateDebugShadowViewCommand(shadowMap, frameState);

    const enterFreezeFrame =
      shadowMap.debugFreezeFrame && !shadowMap._debugFreezeFrame;
    shadowMap._debugFreezeFrame = shadowMap.debugFreezeFrame;

    // Draw scene camera in freeze frame mode
    if (shadowMap.debugFreezeFrame) {
      if (enterFreezeFrame) {
        // Recreate debug camera when entering freeze frame mode
        shadowMap._debugCameraFrustum =
          shadowMap._debugCameraFrustum &&
          shadowMap._debugCameraFrustum.destroy();
        shadowMap._debugCameraFrustum = new DebugCameraPrimitive({
          camera: shadowMap._sceneCamera,
          color: Color.CYAN,
          updateOnChange: false,
        });
      }
      shadowMap._debugCameraFrustum.update(frameState);
    }

    if (shadowMap._cascadesEnabled) {
      // Draw cascades only in freeze frame mode
      if (shadowMap.debugFreezeFrame) {
        if (enterFreezeFrame) {
          // Recreate debug frustum when entering freeze frame mode
          shadowMap._debugLightFrustum =
            shadowMap._debugLightFrustum &&
            shadowMap._debugLightFrustum.destroy();
          shadowMap._debugLightFrustum = new DebugCameraPrimitive({
            camera: shadowMap._shadowMapCamera,
            color: Color.YELLOW,
            updateOnChange: false,
          });
        }
        shadowMap._debugLightFrustum.update(frameState);

        for (let i = 0; i < shadowMap._numberOfCascades; ++i) {
          if (enterFreezeFrame) {
            // Recreate debug frustum when entering freeze frame mode
            shadowMap._debugCascadeFrustums[i] =
              shadowMap._debugCascadeFrustums[i] &&
              shadowMap._debugCascadeFrustums[i].destroy();
            shadowMap._debugCascadeFrustums[i] = new DebugCameraPrimitive({
              camera: shadowMap._passes[i].camera,
              color: debugOutlineColors[i],
              updateOnChange: false,
            });
          }
          shadowMap._debugCascadeFrustums[i].update(frameState);
        }
      }
    } else if (shadowMap._isPointLight) {
      if (!defined(shadowMap._debugLightFrustum) || shadowMap._needsUpdate) {
        const translation = shadowMap._shadowMapCamera.positionWC;
        const rotation = Quaternion.IDENTITY;
        const uniformScale = shadowMap._pointLightRadius * 2.0;
        const scale = Cartesian3.fromElements(
          uniformScale,
          uniformScale,
          uniformScale,
          scratchScale
        );
        const modelMatrix = Matrix4.fromTranslationQuaternionRotationScale(
          translation,
          rotation,
          scale,
          scratchMatrix
        );

        shadowMap._debugLightFrustum =
          shadowMap._debugLightFrustum && shadowMap._debugLightFrustum.destroy();
        shadowMap._debugLightFrustum = createDebugPointLight(
          modelMatrix,
          Color.YELLOW
        );
      }
      shadowMap._debugLightFrustum.update(frameState);
    } else {
      if (!defined(shadowMap._debugLightFrustum) || shadowMap._needsUpdate) {
        shadowMap._debugLightFrustum = new DebugCameraPrimitive({
          camera: shadowMap._shadowMapCamera,
          color: Color.YELLOW,
          updateOnChange: false,
        });
      }
      shadowMap._debugLightFrustum.update(frameState);
    }
  }

  function ShadowMapCamera() {
    this.viewMatrix = new Matrix4();
    this.inverseViewMatrix = new Matrix4();
    this.frustum = undefined;
    this.positionCartographic = new Cartographic();
    this.positionWC = new Cartesian3();
    this.directionWC = Cartesian3.clone(Cartesian3.UNIT_Z);
    this.upWC = Cartesian3.clone(Cartesian3.UNIT_Y);
    this.rightWC = Cartesian3.clone(Cartesian3.UNIT_X);
    this.viewProjectionMatrix = new Matrix4();
  }

  ShadowMapCamera.prototype.clone = function (camera) {
    Matrix4.clone(camera.viewMatrix, this.viewMatrix);
    Matrix4.clone(camera.inverseViewMatrix, this.inverseViewMatrix);
    this.frustum = camera.frustum.clone(this.frustum);
    Cartographic.clone(camera.positionCartographic, this.positionCartographic);
    Cartesian3.clone(camera.positionWC, this.positionWC);
    Cartesian3.clone(camera.directionWC, this.directionWC);
    Cartesian3.clone(camera.upWC, this.upWC);
    Cartesian3.clone(camera.rightWC, this.rightWC);
  };

  // Converts from NDC space to texture space
  const scaleBiasMatrix = new Matrix4(
    0.5,
    0.0,
    0.0,
    0.5,
    0.0,
    0.5,
    0.0,
    0.5,
    0.0,
    0.0,
    0.5,
    0.5,
    0.0,
    0.0,
    0.0,
    1.0
  );

  ShadowMapCamera.prototype.getViewProjection = function () {
    const view = this.viewMatrix;
    const projection = this.frustum.projectionMatrix;
    Matrix4.multiply(projection, view, this.viewProjectionMatrix);
    Matrix4.multiply(
      scaleBiasMatrix,
      this.viewProjectionMatrix,
      this.viewProjectionMatrix
    );
    return this.viewProjectionMatrix;
  };

  const scratchSplits = new Array(5);
  const scratchFrustum = new PerspectiveFrustum();
  const scratchCascadeDistances = new Array(4);
  const scratchMin = new Cartesian3();
  const scratchMax = new Cartesian3();

  function computeCascades(shadowMap, frameState) {
    const shadowMapCamera = shadowMap._shadowMapCamera;
    const sceneCamera = shadowMap._sceneCamera;
    const cameraNear = sceneCamera.frustum.near;
    const cameraFar = sceneCamera.frustum.far;
    const numberOfCascades = shadowMap._numberOfCascades;

    // Split cascades. Use a mix of linear and log splits.
    let i;
    const range = cameraFar - cameraNear;
    const ratio = cameraFar / cameraNear;

    let lambda = 0.9;
    let clampCascadeDistances = false;

    // When the camera is close to a relatively small model, provide more detail in the closer cascades.
    // If the camera is near or inside a large model, such as the root tile of a city, then use the default values.
    // To get the most accurate cascade splits we would need to find the min and max values from the depth texture.
    if (frameState.shadowState.closestObjectSize < 200.0) {
      clampCascadeDistances = true;
      lambda = 0.9;
    }

    const cascadeDistances = scratchCascadeDistances;
    const splits = scratchSplits;
    splits[0] = cameraNear;
    splits[numberOfCascades] = cameraFar;

    // Find initial splits
    for (i = 0; i < numberOfCascades; ++i) {
      const p = (i + 1) / numberOfCascades;
      const logScale = cameraNear * Math.pow(ratio, p);
      const uniformScale = cameraNear + range * p;
      const split = CesiumMath.lerp(uniformScale, logScale, lambda);
      splits[i + 1] = split;
      cascadeDistances[i] = split - splits[i];
    }

    if (clampCascadeDistances) {
      // Clamp each cascade to its maximum distance
      for (i = 0; i < numberOfCascades; ++i) {
        cascadeDistances[i] = Math.min(
          cascadeDistances[i],
          shadowMap._maximumCascadeDistances[i]
        );
      }

      // Recompute splits
      let distance = splits[0];
      for (i = 0; i < numberOfCascades - 1; ++i) {
        distance += cascadeDistances[i];
        splits[i + 1] = distance;
      }
    }

    Cartesian4.unpack(splits, 0, shadowMap._cascadeSplits[0]);
    Cartesian4.unpack(splits, 1, shadowMap._cascadeSplits[1]);
    Cartesian4.unpack(cascadeDistances, 0, shadowMap._cascadeDistances);

    const shadowFrustum = shadowMapCamera.frustum;
    const left = shadowFrustum.left;
    const right = shadowFrustum.right;
    const bottom = shadowFrustum.bottom;
    const top = shadowFrustum.top;
    const near = shadowFrustum.near;
    const far = shadowFrustum.far;

    const position = shadowMapCamera.positionWC;
    const direction = shadowMapCamera.directionWC;
    const up = shadowMapCamera.upWC;

    const cascadeSubFrustum = sceneCamera.frustum.clone(scratchFrustum);
    const shadowViewProjection = shadowMapCamera.getViewProjection();

    for (i = 0; i < numberOfCascades; ++i) {
      // Find the bounding box of the camera sub-frustum in shadow map texture space
      cascadeSubFrustum.near = splits[i];
      cascadeSubFrustum.far = splits[i + 1];
      const viewProjection = Matrix4.multiply(
        cascadeSubFrustum.projectionMatrix,
        sceneCamera.viewMatrix,
        scratchMatrix
      );
      const inverseViewProjection = Matrix4.inverse(
        viewProjection,
        scratchMatrix
      );
      const shadowMapMatrix = Matrix4.multiply(
        shadowViewProjection,
        inverseViewProjection,
        scratchMatrix
      );

      // Project each corner from camera NDC space to shadow map texture space. Min and max will be from 0 to 1.
      const min = Cartesian3.fromElements(
        Number.MAX_VALUE,
        Number.MAX_VALUE,
        Number.MAX_VALUE,
        scratchMin
      );
      const max = Cartesian3.fromElements(
        -Number.MAX_VALUE,
        -Number.MAX_VALUE,
        -Number.MAX_VALUE,
        scratchMax
      );

      for (let k = 0; k < 8; ++k) {
        const corner = Cartesian4.clone(
          frustumCornersNDC[k],
          scratchFrustumCorners[k]
        );
        Matrix4.multiplyByVector(shadowMapMatrix, corner, corner);
        Cartesian3.divideByScalar(corner, corner.w, corner); // Handle the perspective divide
        Cartesian3.minimumByComponent(corner, min, min);
        Cartesian3.maximumByComponent(corner, max, max);
      }

      // Limit light-space coordinates to the [0, 1] range
      min.x = Math.max(min.x, 0.0);
      min.y = Math.max(min.y, 0.0);
      min.z = 0.0; // Always start cascade frustum at the top of the light frustum to capture objects in the light's path
      max.x = Math.min(max.x, 1.0);
      max.y = Math.min(max.y, 1.0);
      max.z = Math.min(max.z, 1.0);

      const pass = shadowMap._passes[i];
      const cascadeCamera = pass.camera;
      cascadeCamera.clone(shadowMapCamera); // PERFORMANCE_IDEA : could do a shallow clone for all properties except the frustum

      const frustum = cascadeCamera.frustum;
      frustum.left = left + min.x * (right - left);
      frustum.right = left + max.x * (right - left);
      frustum.bottom = bottom + min.y * (top - bottom);
      frustum.top = bottom + max.y * (top - bottom);
      frustum.near = near + min.z * (far - near);
      frustum.far = near + max.z * (far - near);

      pass.cullingVolume = cascadeCamera.frustum.computeCullingVolume(
        position,
        direction,
        up
      );

      // Transforms from eye space to the cascade's texture space
      const cascadeMatrix = shadowMap._cascadeMatrices[i];
      Matrix4.multiply(
        cascadeCamera.getViewProjection(),
        sceneCamera.inverseViewMatrix,
        cascadeMatrix
      );
      Matrix4.multiply(pass.textureOffsets, cascadeMatrix, cascadeMatrix);
    }
  }

  const scratchLightView = new Matrix4();
  const scratchRight$1 = new Cartesian3();
  const scratchUp$1 = new Cartesian3();
  const scratchTranslation = new Cartesian3();

  function fitShadowMapToScene(shadowMap, frameState) {
    const shadowMapCamera = shadowMap._shadowMapCamera;
    const sceneCamera = shadowMap._sceneCamera;

    // 1. First find a tight bounding box in light space that contains the entire camera frustum.
    const viewProjection = Matrix4.multiply(
      sceneCamera.frustum.projectionMatrix,
      sceneCamera.viewMatrix,
      scratchMatrix
    );
    const inverseViewProjection = Matrix4.inverse(viewProjection, scratchMatrix);

    // Start to construct the light view matrix. Set translation later once the bounding box is found.
    const lightDir = shadowMapCamera.directionWC;
    let lightUp = sceneCamera.directionWC; // Align shadows to the camera view.
    if (Cartesian3.equalsEpsilon(lightDir, lightUp, CesiumMath.EPSILON10)) {
      lightUp = sceneCamera.upWC;
    }
    const lightRight = Cartesian3.cross(lightDir, lightUp, scratchRight$1);
    lightUp = Cartesian3.cross(lightRight, lightDir, scratchUp$1); // Recalculate up now that right is derived
    Cartesian3.normalize(lightUp, lightUp);
    Cartesian3.normalize(lightRight, lightRight);
    const lightPosition = Cartesian3.fromElements(
      0.0,
      0.0,
      0.0,
      scratchTranslation
    );

    let lightView = Matrix4.computeView(
      lightPosition,
      lightDir,
      lightUp,
      lightRight,
      scratchLightView
    );
    const cameraToLight = Matrix4.multiply(
      lightView,
      inverseViewProjection,
      scratchMatrix
    );

    // Project each corner from NDC space to light view space, and calculate a min and max in light view space
    const min = Cartesian3.fromElements(
      Number.MAX_VALUE,
      Number.MAX_VALUE,
      Number.MAX_VALUE,
      scratchMin
    );
    const max = Cartesian3.fromElements(
      -Number.MAX_VALUE,
      -Number.MAX_VALUE,
      -Number.MAX_VALUE,
      scratchMax
    );

    for (let i = 0; i < 8; ++i) {
      const corner = Cartesian4.clone(
        frustumCornersNDC[i],
        scratchFrustumCorners[i]
      );
      Matrix4.multiplyByVector(cameraToLight, corner, corner);
      Cartesian3.divideByScalar(corner, corner.w, corner); // Handle the perspective divide
      Cartesian3.minimumByComponent(corner, min, min);
      Cartesian3.maximumByComponent(corner, max, max);
    }

    // 2. Set bounding box back to include objects in the light's view
    max.z += 1000.0; // Note: in light space, a positive number is behind the camera
    min.z -= 10.0; // Extend the shadow volume forward slightly to avoid problems right at the edge

    // 3. Adjust light view matrix so that it is centered on the bounding volume
    const translation = scratchTranslation;
    translation.x = -(0.5 * (min.x + max.x));
    translation.y = -(0.5 * (min.y + max.y));
    translation.z = -max.z;

    const translationMatrix = Matrix4.fromTranslation(translation, scratchMatrix);
    lightView = Matrix4.multiply(translationMatrix, lightView, lightView);

    // 4. Create an orthographic frustum that covers the bounding box extents
    const halfWidth = 0.5 * (max.x - min.x);
    const halfHeight = 0.5 * (max.y - min.y);
    const depth = max.z - min.z;

    const frustum = shadowMapCamera.frustum;
    frustum.left = -halfWidth;
    frustum.right = halfWidth;
    frustum.bottom = -halfHeight;
    frustum.top = halfHeight;
    frustum.near = 0.01;
    frustum.far = depth;

    // 5. Update the shadow map camera
    Matrix4.clone(lightView, shadowMapCamera.viewMatrix);
    Matrix4.inverse(lightView, shadowMapCamera.inverseViewMatrix);
    Matrix4.getTranslation(
      shadowMapCamera.inverseViewMatrix,
      shadowMapCamera.positionWC
    );
    frameState.mapProjection.ellipsoid.cartesianToCartographic(
      shadowMapCamera.positionWC,
      shadowMapCamera.positionCartographic
    );
    Cartesian3.clone(lightDir, shadowMapCamera.directionWC);
    Cartesian3.clone(lightUp, shadowMapCamera.upWC);
    Cartesian3.clone(lightRight, shadowMapCamera.rightWC);
  }

  const directions = [
    new Cartesian3(-1.0, 0.0, 0.0),
    new Cartesian3(0.0, -1.0, 0.0),
    new Cartesian3(0.0, 0.0, -1.0),
    new Cartesian3(1.0, 0.0, 0.0),
    new Cartesian3(0.0, 1.0, 0.0),
    new Cartesian3(0.0, 0.0, 1.0),
  ];

  const ups = [
    new Cartesian3(0.0, -1.0, 0.0),
    new Cartesian3(0.0, 0.0, -1.0),
    new Cartesian3(0.0, -1.0, 0.0),
    new Cartesian3(0.0, -1.0, 0.0),
    new Cartesian3(0.0, 0.0, 1.0),
    new Cartesian3(0.0, -1.0, 0.0),
  ];

  const rights = [
    new Cartesian3(0.0, 0.0, 1.0),
    new Cartesian3(1.0, 0.0, 0.0),
    new Cartesian3(-1.0, 0.0, 0.0),
    new Cartesian3(0.0, 0.0, -1.0),
    new Cartesian3(1.0, 0.0, 0.0),
    new Cartesian3(1.0, 0.0, 0.0),
  ];

  function computeOmnidirectional(shadowMap, frameState) {
    // All sides share the same frustum
    const frustum = new PerspectiveFrustum();
    frustum.fov = CesiumMath.PI_OVER_TWO;
    frustum.near = 1.0;
    frustum.far = shadowMap._pointLightRadius;
    frustum.aspectRatio = 1.0;

    for (let i = 0; i < 6; ++i) {
      const camera = shadowMap._passes[i].camera;
      camera.positionWC = shadowMap._shadowMapCamera.positionWC;
      camera.positionCartographic = frameState.mapProjection.ellipsoid.cartesianToCartographic(
        camera.positionWC,
        camera.positionCartographic
      );
      camera.directionWC = directions[i];
      camera.upWC = ups[i];
      camera.rightWC = rights[i];

      Matrix4.computeView(
        camera.positionWC,
        camera.directionWC,
        camera.upWC,
        camera.rightWC,
        camera.viewMatrix
      );
      Matrix4.inverse(camera.viewMatrix, camera.inverseViewMatrix);

      camera.frustum = frustum;
    }
  }

  const scratchCartesian1 = new Cartesian3();
  const scratchCartesian2 = new Cartesian3();
  const scratchBoundingSphere = new BoundingSphere();
  const scratchCenter$1 = scratchBoundingSphere.center;

  function checkVisibility(shadowMap, frameState) {
    const sceneCamera = shadowMap._sceneCamera;
    const shadowMapCamera = shadowMap._shadowMapCamera;

    const boundingSphere = scratchBoundingSphere;

    // Check whether the shadow map is in view and needs to be updated
    if (shadowMap._cascadesEnabled) {
      // If the nearest shadow receiver is further than the shadow map's maximum distance then the shadow map is out of view.
      if (sceneCamera.frustum.near >= shadowMap.maximumDistance) {
        shadowMap._outOfView = true;
        shadowMap._needsUpdate = false;
        return;
      }

      // If the light source is below the horizon then the shadow map is out of view
      const surfaceNormal = frameState.mapProjection.ellipsoid.geodeticSurfaceNormal(
        sceneCamera.positionWC,
        scratchCartesian1
      );
      const lightDirection = Cartesian3.negate(
        shadowMapCamera.directionWC,
        scratchCartesian2
      );
      const dot = Cartesian3.dot(surfaceNormal, lightDirection);
      if (shadowMap.fadingEnabled) {
        // Shadows start to fade out once the light gets closer to the horizon.
        // At this point the globe uses vertex lighting alone to darken the surface.
        const darknessAmount = CesiumMath.clamp(dot / 0.1, 0.0, 1.0);
        shadowMap._darkness = CesiumMath.lerp(
          1.0,
          shadowMap.darkness,
          darknessAmount
        );
      } else {
        shadowMap._darkness = shadowMap.darkness;
      }

      if (dot < 0.0) {
        shadowMap._outOfView = true;
        shadowMap._needsUpdate = false;
        return;
      }

      // By default cascaded shadows need to update and are always in view
      shadowMap._needsUpdate = true;
      shadowMap._outOfView = false;
    } else if (shadowMap._isPointLight) {
      // Sphere-frustum intersection test
      boundingSphere.center = shadowMapCamera.positionWC;
      boundingSphere.radius = shadowMap._pointLightRadius;
      shadowMap._outOfView =
        frameState.cullingVolume.computeVisibility(boundingSphere) ===
        Intersect$1.OUTSIDE;
      shadowMap._needsUpdate =
        !shadowMap._outOfView &&
        !shadowMap._boundingSphere.equals(boundingSphere);
      BoundingSphere.clone(boundingSphere, shadowMap._boundingSphere);
    } else {
      // Simplify frustum-frustum intersection test as a sphere-frustum test
      const frustumRadius = shadowMapCamera.frustum.far / 2.0;
      const frustumCenter = Cartesian3.add(
        shadowMapCamera.positionWC,
        Cartesian3.multiplyByScalar(
          shadowMapCamera.directionWC,
          frustumRadius,
          scratchCenter$1
        ),
        scratchCenter$1
      );
      boundingSphere.center = frustumCenter;
      boundingSphere.radius = frustumRadius;
      shadowMap._outOfView =
        frameState.cullingVolume.computeVisibility(boundingSphere) ===
        Intersect$1.OUTSIDE;
      shadowMap._needsUpdate =
        !shadowMap._outOfView &&
        !shadowMap._boundingSphere.equals(boundingSphere);
      BoundingSphere.clone(boundingSphere, shadowMap._boundingSphere);
    }
  }

  function updateCameras(shadowMap, frameState) {
    const camera = frameState.camera; // The actual camera in the scene
    const lightCamera = shadowMap._lightCamera; // The external camera representing the light source
    const sceneCamera = shadowMap._sceneCamera; // Clone of camera, with clamped near and far planes
    const shadowMapCamera = shadowMap._shadowMapCamera; // Camera representing the shadow volume, initially cloned from lightCamera

    // Clone light camera into the shadow map camera
    if (shadowMap._cascadesEnabled) {
      Cartesian3.clone(lightCamera.directionWC, shadowMapCamera.directionWC);
    } else if (shadowMap._isPointLight) {
      Cartesian3.clone(lightCamera.positionWC, shadowMapCamera.positionWC);
    } else {
      shadowMapCamera.clone(lightCamera);
    }

    // Get the light direction in eye coordinates
    const lightDirection = shadowMap._lightDirectionEC;
    Matrix4.multiplyByPointAsVector(
      camera.viewMatrix,
      shadowMapCamera.directionWC,
      lightDirection
    );
    Cartesian3.normalize(lightDirection, lightDirection);
    Cartesian3.negate(lightDirection, lightDirection);

    // Get the light position in eye coordinates
    Matrix4.multiplyByPoint(
      camera.viewMatrix,
      shadowMapCamera.positionWC,
      shadowMap._lightPositionEC
    );
    shadowMap._lightPositionEC.w = shadowMap._pointLightRadius;

    // Get the near and far of the scene camera
    let near;
    let far;
    if (shadowMap._fitNearFar) {
      // shadowFar can be very large, so limit to shadowMap.maximumDistance
      // Push the far plane slightly further than the near plane to avoid degenerate frustum
      near = Math.min(
        frameState.shadowState.nearPlane,
        shadowMap.maximumDistance
      );
      far = Math.min(frameState.shadowState.farPlane, shadowMap.maximumDistance);
      far = Math.max(far, near + 1.0);
    } else {
      near = camera.frustum.near;
      far = shadowMap.maximumDistance;
    }

    shadowMap._sceneCamera = Camera.clone(camera, sceneCamera);
    camera.frustum.clone(shadowMap._sceneCamera.frustum);
    shadowMap._sceneCamera.frustum.near = near;
    shadowMap._sceneCamera.frustum.far = far;
    shadowMap._distance = far - near;

    checkVisibility(shadowMap, frameState);

    if (!shadowMap._outOfViewPrevious && shadowMap._outOfView) {
      shadowMap._needsUpdate = true;
    }
    shadowMap._outOfViewPrevious = shadowMap._outOfView;
  }

  /**
   * @private
   */
  ShadowMap.prototype.update = function (frameState) {
    updateCameras(this, frameState);

    if (this._needsUpdate) {
      updateFramebuffer(this, frameState.context);

      if (this._isPointLight) {
        computeOmnidirectional(this, frameState);
      }

      if (this._cascadesEnabled) {
        fitShadowMapToScene(this, frameState);

        if (this._numberOfCascades > 1) {
          computeCascades(this, frameState);
        }
      }

      if (!this._isPointLight) {
        // Compute the culling volume
        const shadowMapCamera = this._shadowMapCamera;
        const position = shadowMapCamera.positionWC;
        const direction = shadowMapCamera.directionWC;
        const up = shadowMapCamera.upWC;
        this._shadowMapCullingVolume = shadowMapCamera.frustum.computeCullingVolume(
          position,
          direction,
          up
        );

        if (this._passes.length === 1) {
          // Since there is only one pass, use the shadow map camera as the pass camera.
          this._passes[0].camera.clone(shadowMapCamera);
        }
      } else {
        this._shadowMapCullingVolume = CullingVolume.fromBoundingSphere(
          this._boundingSphere
        );
      }
    }

    if (this._passes.length === 1) {
      // Transforms from eye space to shadow texture space.
      // Always requires an update since the scene camera constantly changes.
      const inverseView = this._sceneCamera.inverseViewMatrix;
      Matrix4.multiply(
        this._shadowMapCamera.getViewProjection(),
        inverseView,
        this._shadowMapMatrix
      );
    }

    if (this.debugShow) {
      applyDebugSettings(this, frameState);
    }
  };

  /**
   * @private
   */
  ShadowMap.prototype.updatePass = function (context, shadowPass) {
    clearFramebuffer(this, context, shadowPass);
  };

  const scratchTexelStepSize = new Cartesian2();

  function combineUniforms(shadowMap, uniforms, isTerrain) {
    const bias = shadowMap._isPointLight
      ? shadowMap._pointBias
      : isTerrain
      ? shadowMap._terrainBias
      : shadowMap._primitiveBias;

    const mapUniforms = {
      shadowMap_texture: function () {
        return shadowMap._shadowMapTexture;
      },
      shadowMap_textureCube: function () {
        return shadowMap._shadowMapTexture;
      },
      shadowMap_matrix: function () {
        return shadowMap._shadowMapMatrix;
      },
      shadowMap_cascadeSplits: function () {
        return shadowMap._cascadeSplits;
      },
      shadowMap_cascadeMatrices: function () {
        return shadowMap._cascadeMatrices;
      },
      shadowMap_lightDirectionEC: function () {
        return shadowMap._lightDirectionEC;
      },
      shadowMap_lightPositionEC: function () {
        return shadowMap._lightPositionEC;
      },
      shadowMap_cascadeDistances: function () {
        return shadowMap._cascadeDistances;
      },
      shadowMap_texelSizeDepthBiasAndNormalShadingSmooth: function () {
        const texelStepSize = scratchTexelStepSize;
        texelStepSize.x = 1.0 / shadowMap._textureSize.x;
        texelStepSize.y = 1.0 / shadowMap._textureSize.y;

        return Cartesian4.fromElements(
          texelStepSize.x,
          texelStepSize.y,
          bias.depthBias,
          bias.normalShadingSmooth,
          this.combinedUniforms1
        );
      },
      shadowMap_normalOffsetScaleDistanceMaxDistanceAndDarkness: function () {
        return Cartesian4.fromElements(
          bias.normalOffsetScale,
          shadowMap._distance,
          shadowMap.maximumDistance,
          shadowMap._darkness,
          this.combinedUniforms2
        );
      },

      combinedUniforms1: new Cartesian4(),
      combinedUniforms2: new Cartesian4(),
    };

    return combine$2(uniforms, mapUniforms, false);
  }

  function createCastDerivedCommand(
    shadowMap,
    shadowsDirty,
    command,
    context,
    oldShaderId,
    result
  ) {
    let castShader;
    let castRenderState;
    let castUniformMap;
    if (defined(result)) {
      castShader = result.shaderProgram;
      castRenderState = result.renderState;
      castUniformMap = result.uniformMap;
    }

    result = DrawCommand.shallowClone(command, result);
    result.castShadows = true;
    result.receiveShadows = false;

    if (
      !defined(castShader) ||
      oldShaderId !== command.shaderProgram.id ||
      shadowsDirty
    ) {
      const shaderProgram = command.shaderProgram;

      const isTerrain = command.pass === Pass$1.GLOBE;
      const isOpaque = command.pass !== Pass$1.TRANSLUCENT;
      const isPointLight = shadowMap._isPointLight;
      const usesDepthTexture = shadowMap._usesDepthTexture;

      const keyword = ShadowMapShader.getShadowCastShaderKeyword(
        isPointLight,
        isTerrain,
        usesDepthTexture,
        isOpaque
      );
      castShader = context.shaderCache.getDerivedShaderProgram(
        shaderProgram,
        keyword
      );
      if (!defined(castShader)) {
        const vertexShaderSource = shaderProgram.vertexShaderSource;
        const fragmentShaderSource = shaderProgram.fragmentShaderSource;

        const castVS = ShadowMapShader.createShadowCastVertexShader(
          vertexShaderSource,
          isPointLight,
          isTerrain
        );
        const castFS = ShadowMapShader.createShadowCastFragmentShader(
          fragmentShaderSource,
          isPointLight,
          usesDepthTexture,
          isOpaque
        );

        castShader = context.shaderCache.createDerivedShaderProgram(
          shaderProgram,
          keyword,
          {
            vertexShaderSource: castVS,
            fragmentShaderSource: castFS,
            attributeLocations: shaderProgram._attributeLocations,
          }
        );
      }

      castRenderState = shadowMap._primitiveRenderState;
      if (isPointLight) {
        castRenderState = shadowMap._pointRenderState;
      } else if (isTerrain) {
        castRenderState = shadowMap._terrainRenderState;
      }

      // Modify the render state for commands that do not use back-face culling, e.g. flat textured walls
      const cullEnabled = command.renderState.cull.enabled;
      if (!cullEnabled) {
        castRenderState = clone$1(castRenderState, false);
        castRenderState.cull = clone$1(castRenderState.cull, false);
        castRenderState.cull.enabled = false;
        castRenderState = RenderState.fromCache(castRenderState);
      }

      castUniformMap = combineUniforms(shadowMap, command.uniformMap, isTerrain);
    }

    result.shaderProgram = castShader;
    result.renderState = castRenderState;
    result.uniformMap = castUniformMap;

    return result;
  }

  ShadowMap.createReceiveDerivedCommand = function (
    lightShadowMaps,
    command,
    shadowsDirty,
    context,
    result
  ) {
    if (!defined(result)) {
      result = {};
    }

    const lightShadowMapsEnabled = lightShadowMaps.length > 0;
    const shaderProgram = command.shaderProgram;
    const vertexShaderSource = shaderProgram.vertexShaderSource;
    const fragmentShaderSource = shaderProgram.fragmentShaderSource;
    const isTerrain = command.pass === Pass$1.GLOBE;

    let hasTerrainNormal = false;
    if (isTerrain) {
      hasTerrainNormal =
        command.owner.data.renderedMesh.encoding.hasVertexNormals;
    }

    if (command.receiveShadows && lightShadowMapsEnabled) {
      // Only generate a receiveCommand if there is a shadow map originating from a light source.
      let receiveShader;
      let receiveUniformMap;
      if (defined(result.receiveCommand)) {
        receiveShader = result.receiveCommand.shaderProgram;
        receiveUniformMap = result.receiveCommand.uniformMap;
      }

      result.receiveCommand = DrawCommand.shallowClone(
        command,
        result.receiveCommand
      );
      result.castShadows = false;
      result.receiveShadows = true;

      // If castShadows changed, recompile the receive shadows shader. The normal shading technique simulates
      // self-shadowing so it should be turned off if castShadows is false.
      const castShadowsDirty =
        result.receiveShaderCastShadows !== command.castShadows;
      const shaderDirty =
        result.receiveShaderProgramId !== command.shaderProgram.id;

      if (
        !defined(receiveShader) ||
        shaderDirty ||
        shadowsDirty ||
        castShadowsDirty
      ) {
        const keyword = ShadowMapShader.getShadowReceiveShaderKeyword(
          lightShadowMaps[0],
          command.castShadows,
          isTerrain,
          hasTerrainNormal
        );
        receiveShader = context.shaderCache.getDerivedShaderProgram(
          shaderProgram,
          keyword
        );
        if (!defined(receiveShader)) {
          const receiveVS = ShadowMapShader.createShadowReceiveVertexShader(
            vertexShaderSource,
            isTerrain,
            hasTerrainNormal
          );
          const receiveFS = ShadowMapShader.createShadowReceiveFragmentShader(
            fragmentShaderSource,
            lightShadowMaps[0],
            command.castShadows,
            isTerrain,
            hasTerrainNormal
          );

          receiveShader = context.shaderCache.createDerivedShaderProgram(
            shaderProgram,
            keyword,
            {
              vertexShaderSource: receiveVS,
              fragmentShaderSource: receiveFS,
              attributeLocations: shaderProgram._attributeLocations,
            }
          );
        }

        receiveUniformMap = combineUniforms(
          lightShadowMaps[0],
          command.uniformMap,
          isTerrain
        );
      }

      result.receiveCommand.shaderProgram = receiveShader;
      result.receiveCommand.uniformMap = receiveUniformMap;
      result.receiveShaderProgramId = command.shaderProgram.id;
      result.receiveShaderCastShadows = command.castShadows;
    }

    return result;
  };

  ShadowMap.createCastDerivedCommand = function (
    shadowMaps,
    command,
    shadowsDirty,
    context,
    result
  ) {
    if (!defined(result)) {
      result = {};
    }

    if (command.castShadows) {
      let castCommands = result.castCommands;
      if (!defined(castCommands)) {
        castCommands = result.castCommands = [];
      }

      const oldShaderId = result.castShaderProgramId;

      const shadowMapLength = shadowMaps.length;
      castCommands.length = shadowMapLength;

      for (let i = 0; i < shadowMapLength; ++i) {
        castCommands[i] = createCastDerivedCommand(
          shadowMaps[i],
          shadowsDirty,
          command,
          context,
          oldShaderId,
          castCommands[i]
        );
      }

      result.castShaderProgramId = command.shaderProgram.id;
    }

    return result;
  };

  /**
   * @private
   */
  ShadowMap.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * @private
   */
  ShadowMap.prototype.destroy = function () {
    destroyFramebuffer(this);

    this._debugLightFrustum =
      this._debugLightFrustum && this._debugLightFrustum.destroy();
    this._debugCameraFrustum =
      this._debugCameraFrustum && this._debugCameraFrustum.destroy();
    this._debugShadowViewCommand =
      this._debugShadowViewCommand &&
      this._debugShadowViewCommand.shaderProgram &&
      this._debugShadowViewCommand.shaderProgram.destroy();

    for (let i = 0; i < this._numberOfCascades; ++i) {
      this._debugCascadeFrustums[i] =
        this._debugCascadeFrustums[i] && this._debugCascadeFrustums[i].destroy();
    }

    return destroyObject(this);
  };

  //This file is automatically rebuilt by the Cesium build process.
  var CompareAndPackTranslucentDepth = "uniform sampler2D u_opaqueDepthTexture;\n\
uniform sampler2D u_translucentDepthTexture;\n\
varying vec2 v_textureCoordinates;\n\
void main()\n\
{\n\
float opaqueDepth = texture2D(u_opaqueDepthTexture, v_textureCoordinates).r;\n\
float translucentDepth = texture2D(u_translucentDepthTexture, v_textureCoordinates).r;\n\
translucentDepth = czm_branchFreeTernary(translucentDepth > opaqueDepth, 1.0, translucentDepth);\n\
gl_FragColor = czm_packDepth(translucentDepth);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var CompositeTranslucentClassification = "uniform sampler2D colorTexture;\n\
#ifdef DEBUG_SHOW_DEPTH\n\
uniform sampler2D u_packedTranslucentDepth;\n\
#endif\n\
varying vec2 v_textureCoordinates;\n\
void main()\n\
{\n\
#ifdef DEBUG_SHOW_DEPTH\n\
if (v_textureCoordinates.x < 0.5)\n\
{\n\
gl_FragColor.rgb = vec3(czm_unpackDepth(texture2D(u_packedTranslucentDepth, v_textureCoordinates)));\n\
gl_FragColor.a = 1.0;\n\
}\n\
#else\n\
vec4 color = texture2D(colorTexture, v_textureCoordinates);\n\
#ifdef PICK\n\
if (color == vec4(0.0))\n\
{\n\
discard;\n\
}\n\
#else\n\
color.rgb /= color.a;\n\
#endif\n\
gl_FragColor = color;\n\
#endif\n\
}\n\
";

  /**
   * Handles buffers, drawing, and deriving commands needed for classifying translucent 3D Tiles.
   * Uses a depth texture, so classification on translucent 3D Tiles is not available in Internet Explorer.
   *
   * @private
   */
  function TranslucentTileClassification(context) {
    this._drawClassificationFBO = new FramebufferManager({
      createDepthAttachments: false,
    });
    this._accumulationFBO = new FramebufferManager({
      createDepthAttachments: false,
    });
    this._packFBO = new FramebufferManager();

    this._opaqueDepthStencilTexture = undefined;

    // Reference to either colorTexture or accumulationTexture
    this._textureToComposite = undefined;

    this._translucentDepthStencilTexture = undefined;

    this._packDepthCommand = undefined;
    this._accumulateCommand = undefined;
    this._compositeCommand = undefined;
    this._copyCommand = undefined;

    this._clearColorCommand = new ClearCommand({
      color: new Color(0.0, 0.0, 0.0, 0.0),
      owner: this,
    });

    this._clearDepthStencilCommand = new ClearCommand({
      depth: 1.0,
      stencil: 0,
      owner: this,
    });

    this._supported = context.depthTexture;

    this._viewport = new BoundingRectangle();
    this._rsDepth = undefined;
    this._rsAccumulate = undefined;
    this._rsComp = undefined;
    this._useScissorTest = undefined;
    this._scissorRectangle = undefined;

    this._hasTranslucentDepth = false;
    this._frustumsDrawn = 0;
  }

  Object.defineProperties(TranslucentTileClassification.prototype, {
    /**
     * Gets whether or not translucent depth was rendered.
     * @memberof TranslucentTileClassification.prototype
     *
     * @type {Boolean}
     * @readonly
     */
    hasTranslucentDepth: {
      get: function () {
        return this._hasTranslucentDepth;
      },
    },
  });

  function destroyTextures(transpClass) {
    transpClass._textureToComposite = undefined;

    transpClass._translucentDepthStencilTexture =
      transpClass._translucentDepthStencilTexture &&
      !transpClass._translucentDepthStencilTexture.isDestroyed() &&
      transpClass._translucentDepthStencilTexture.destroy();
  }

  function destroyFramebuffers(transpClass) {
    transpClass._drawClassificationFBO.destroy();
    transpClass._accumulationFBO.destroy();
    transpClass._packFBO.destroy();
  }

  function updateTextures(transpClass, context, width, height) {
    destroyTextures(transpClass);

    transpClass._translucentDepthStencilTexture = new Texture({
      context: context,
      width: width,
      height: height,
      pixelFormat: PixelFormat$1.DEPTH_STENCIL,
      pixelDatatype: PixelDatatype$1.UNSIGNED_INT_24_8,
      sampler: Sampler.NEAREST,
    });
  }

  function updateFramebuffers$1(transpClass, context, width, height) {
    destroyFramebuffers(transpClass);
    transpClass._drawClassificationFBO.setDepthStencilTexture(
      transpClass._translucentDepthStencilTexture
    );
    transpClass._drawClassificationFBO.update(context, width, height);

    transpClass._accumulationFBO.setDepthStencilTexture(
      transpClass._translucentDepthStencilTexture
    );
    transpClass._accumulationFBO.update(context, width, height);

    transpClass._packFBO.update(context, width, height);
  }

  function updateResources(
    transpClass,
    context,
    passState,
    globeDepthStencilTexture
  ) {
    if (!transpClass.isSupported()) {
      return;
    }

    transpClass._opaqueDepthStencilTexture = globeDepthStencilTexture;

    const width = transpClass._opaqueDepthStencilTexture.width;
    const height = transpClass._opaqueDepthStencilTexture.height;
    if (transpClass._drawClassificationFBO.isDirty(width, height)) {
      updateTextures(transpClass, context, width, height);
      updateFramebuffers$1(transpClass, context, width, height);
    }

    let fs;
    let uniformMap;

    if (!defined(transpClass._packDepthCommand)) {
      fs = new ShaderSource({
        sources: [CompareAndPackTranslucentDepth],
      });

      uniformMap = {
        u_opaqueDepthTexture: function () {
          return transpClass._opaqueDepthStencilTexture;
        },
        u_translucentDepthTexture: function () {
          return transpClass._translucentDepthStencilTexture;
        },
      };

      transpClass._packDepthCommand = context.createViewportQuadCommand(fs, {
        uniformMap: uniformMap,
        owner: transpClass,
      });
    }

    if (!defined(transpClass._compositeCommand)) {
      fs = new ShaderSource({
        sources: [CompositeTranslucentClassification],
      });

      uniformMap = {
        colorTexture: function () {
          return transpClass._textureToComposite;
        },
      };

      transpClass._compositeCommand = context.createViewportQuadCommand(fs, {
        uniformMap: uniformMap,
        owner: transpClass,
      });

      const compositeCommand = transpClass._compositeCommand;
      const compositeProgram = compositeCommand.shaderProgram;
      const compositePickProgram = context.shaderCache.createDerivedShaderProgram(
        compositeProgram,
        "pick",
        {
          vertexShaderSource: compositeProgram.vertexShaderSource,
          fragmentShaderSource: new ShaderSource({
            sources: fs.sources,
            defines: ["PICK"],
          }),
          attributeLocations: compositeProgram._attributeLocations,
        }
      );
      const compositePickCommand = DrawCommand.shallowClone(compositeCommand);
      compositePickCommand.shaderProgram = compositePickProgram;
      compositeCommand.derivedCommands.pick = compositePickCommand;
    }

    if (!defined(transpClass._copyCommand)) {
      fs = new ShaderSource({
        sources: [CompositeTranslucentClassification],
      });

      uniformMap = {
        colorTexture: function () {
          return transpClass._drawClassificationFBO.getColorTexture();
        },
      };

      transpClass._copyCommand = context.createViewportQuadCommand(fs, {
        uniformMap: uniformMap,
        owner: transpClass,
      });
    }

    if (!defined(transpClass._accumulateCommand)) {
      fs = new ShaderSource({
        sources: [CompositeTranslucentClassification],
      });

      uniformMap = {
        colorTexture: function () {
          return transpClass._drawClassificationFBO.getColorTexture();
        },
      };

      transpClass._accumulateCommand = context.createViewportQuadCommand(fs, {
        uniformMap: uniformMap,
        owner: transpClass,
      });
    }

    transpClass._viewport.width = width;
    transpClass._viewport.height = height;

    const useScissorTest = !BoundingRectangle.equals(
      transpClass._viewport,
      passState.viewport
    );
    let updateScissor = useScissorTest !== transpClass._useScissorTest;
    transpClass._useScissorTest = useScissorTest;

    if (
      !BoundingRectangle.equals(transpClass._scissorRectangle, passState.viewport)
    ) {
      transpClass._scissorRectangle = BoundingRectangle.clone(
        passState.viewport,
        transpClass._scissorRectangle
      );
      updateScissor = true;
    }

    if (
      !defined(transpClass._rsDepth) ||
      !BoundingRectangle.equals(
        transpClass._viewport,
        transpClass._rsDepth.viewport
      ) ||
      updateScissor
    ) {
      transpClass._rsDepth = RenderState.fromCache({
        viewport: transpClass._viewport,
        scissorTest: {
          enabled: transpClass._useScissorTest,
          rectangle: transpClass._scissorRectangle,
        },
      });
    }

    if (defined(transpClass._packDepthCommand)) {
      transpClass._packDepthCommand.renderState = transpClass._rsDepth;
    }

    if (
      !defined(transpClass._rsAccumulate) ||
      !BoundingRectangle.equals(
        transpClass._viewport,
        transpClass._rsAccumulate.viewport
      ) ||
      updateScissor
    ) {
      transpClass._rsAccumulate = RenderState.fromCache({
        viewport: transpClass._viewport,
        scissorTest: {
          enabled: transpClass._useScissorTest,
          rectangle: transpClass._scissorRectangle,
        },
        stencilTest: {
          enabled: true,
          frontFunction: StencilFunction$1.EQUAL,
          reference: StencilConstants$1.CESIUM_3D_TILE_MASK,
        },
      });
    }

    if (defined(transpClass._accumulateCommand)) {
      transpClass._accumulateCommand.renderState = transpClass._rsAccumulate;
    }

    if (
      !defined(transpClass._rsComp) ||
      !BoundingRectangle.equals(
        transpClass._viewport,
        transpClass._rsComp.viewport
      ) ||
      updateScissor
    ) {
      transpClass._rsComp = RenderState.fromCache({
        viewport: transpClass._viewport,
        scissorTest: {
          enabled: transpClass._useScissorTest,
          rectangle: transpClass._scissorRectangle,
        },
        blending: BlendingState$1.ALPHA_BLEND,
      });
    }

    if (defined(transpClass._compositeCommand)) {
      transpClass._compositeCommand.renderState = transpClass._rsComp;
      transpClass._compositeCommand.derivedCommands.pick.renderState =
        transpClass._rsComp;
    }
  }

  TranslucentTileClassification.prototype.executeTranslucentCommands = function (
    scene,
    executeCommand,
    passState,
    commands,
    globeDepthStencilTexture
  ) {
    // Check for translucent commands that should be classified
    const length = commands.length;
    let command;
    let i;

    const useLogDepth = scene.frameState.useLogDepth;
    const context = scene.context;
    const framebuffer = passState.framebuffer;

    for (i = 0; i < length; ++i) {
      command = commands[i];
      command = useLogDepth ? command.derivedCommands.logDepth.command : command;

      if (command.depthForTranslucentClassification) {
        this._hasTranslucentDepth = true;
        break;
      }
    }

    if (!this._hasTranslucentDepth) {
      return;
    }

    updateResources(this, context, passState, globeDepthStencilTexture);

    // Get translucent depth
    passState.framebuffer = this._drawClassificationFBO.framebuffer;

    // Clear depth for multifrustum
    this._clearDepthStencilCommand.execute(context, passState);

    for (i = 0; i < length; ++i) {
      command = commands[i];
      command = useLogDepth ? command.derivedCommands.logDepth.command : command;

      if (!command.depthForTranslucentClassification) {
        continue;
      }

      // Depth-only commands are created for all translucent 3D Tiles commands
      const depthOnlyCommand = command.derivedCommands.depth.depthOnlyCommand;
      executeCommand(depthOnlyCommand, scene, context, passState);
    }

    this._frustumsDrawn += this._hasTranslucentDepth ? 1 : 0;

    // Pack depth if any translucent depth commands were performed
    if (this._hasTranslucentDepth) {
      passState.framebuffer = this._packFBO.framebuffer;
      this._packDepthCommand.execute(context, passState);
    }

    passState.framebuffer = framebuffer;
  };

  TranslucentTileClassification.prototype.executeClassificationCommands = function (
    scene,
    executeCommand,
    passState,
    frustumCommands
  ) {
    if (!this._hasTranslucentDepth) {
      return;
    }

    const context = scene.context;
    const us = context.uniformState;
    const framebuffer = passState.framebuffer;

    if (this._frustumsDrawn === 2) {
      // copy classification from first frustum
      passState.framebuffer = this._accumulationFBO.framebuffer;
      this._copyCommand.execute(context, passState);
    }

    passState.framebuffer = this._drawClassificationFBO.framebuffer;
    if (this._frustumsDrawn > 1) {
      this._clearColorCommand.execute(context, passState);
    }

    us.updatePass(Pass$1.CESIUM_3D_TILE_CLASSIFICATION);
    const swapGlobeDepth = us.globeDepthTexture;
    us.globeDepthTexture = this._packFBO.getColorTexture();
    const commands = frustumCommands.commands[Pass$1.CESIUM_3D_TILE_CLASSIFICATION];
    const length = frustumCommands.indices[Pass$1.CESIUM_3D_TILE_CLASSIFICATION];
    for (let i = 0; i < length; ++i) {
      executeCommand(commands[i], scene, context, passState);
    }

    us.globeDepthTexture = swapGlobeDepth;
    passState.framebuffer = framebuffer;

    if (this._frustumsDrawn === 1) {
      return;
    }

    passState.framebuffer = this._accumulationFBO.framebuffer;
    this._accumulateCommand.execute(context, passState);

    passState.framebuffer = framebuffer;
  };

  TranslucentTileClassification.prototype.execute = function (scene, passState) {
    if (!this._hasTranslucentDepth) {
      return;
    }
    if (this._frustumsDrawn === 1) {
      this._textureToComposite = this._drawClassificationFBO.getColorTexture();
    } else {
      this._textureToComposite = this._accumulationFBO.getColorTexture();
    }

    const command = scene.frameState.passes.pick
      ? this._compositeCommand.derivedCommands.pick
      : this._compositeCommand;
    command.execute(scene.context, passState);

    clear(this, scene, passState);
  };

  function clear(translucentTileClassification, scene, passState) {
    if (!translucentTileClassification._hasTranslucentDepth) {
      return;
    }

    const framebuffer = passState.framebuffer;

    passState.framebuffer =
      translucentTileClassification._drawClassificationFBO.framebuffer;
    translucentTileClassification._clearColorCommand.execute(
      scene._context,
      passState
    );

    passState.framebuffer = framebuffer;

    if (translucentTileClassification._frustumsDrawn > 1) {
      passState.framebuffer =
        translucentTileClassification._accumulationFBO.framebuffer;
      translucentTileClassification._clearColorCommand.execute(
        scene._context,
        passState
      );
    }

    translucentTileClassification._hasTranslucentDepth = false;
    translucentTileClassification._frustumsDrawn = 0;
  }

  TranslucentTileClassification.prototype.isSupported = function () {
    return this._supported;
  };

  TranslucentTileClassification.prototype.isDestroyed = function () {
    return false;
  };

  TranslucentTileClassification.prototype.destroy = function () {
    destroyTextures(this);
    destroyFramebuffers(this);

    if (defined(this._compositeCommand)) {
      this._compositeCommand.shaderProgram =
        this._compositeCommand.shaderProgram &&
        this._compositeCommand.shaderProgram.destroy();
    }

    if (defined(this._packDepthCommand)) {
      this._packDepthCommand.shaderProgram =
        this._packDepthCommand.shaderProgram &&
        this._packDepthCommand.shaderProgram.destroy();
    }
    return destroyObject(this);
  };

  function CommandExtent() {
    this.command = undefined;
    this.near = undefined;
    this.far = undefined;
  }

  /**
   * @private
   */
  function View(scene, camera, viewport) {
    const context = scene.context;

    let globeDepth;
    if (context.depthTexture) {
      globeDepth = new GlobeDepth();
    }

    let oit;
    if (scene._useOIT && context.depthTexture) {
      oit = new OIT(context);
    }

    const passState = new PassState(context);
    passState.viewport = BoundingRectangle.clone(viewport);

    this.camera = camera;
    this._cameraClone = Camera.clone(camera);
    this._cameraStartFired = false;
    this._cameraMovedTime = undefined;

    this.viewport = viewport;
    this.passState = passState;
    this.pickFramebuffer = new PickFramebuffer(context);
    this.pickDepthFramebuffer = new PickDepthFramebuffer();
    this.sceneFramebuffer = new SceneFramebuffer();
    this.globeDepth = globeDepth;
    this.globeTranslucencyFramebuffer = new GlobeTranslucencyFramebuffer();
    this.oit = oit;
    this.translucentTileClassification = new TranslucentTileClassification(
      context
    );
    this.pickDepths = [];
    this.frustumCommandsList = [];
    this.debugFrustumStatistics = undefined;

    // Array of all commands that get rendered into frustums along with their near / far values.
    // Acts similar to a ManagedArray.
    this._commandExtents = [];
  }

  const scratchPosition0 = new Cartesian3();
  const scratchPosition1 = new Cartesian3();
  function maxComponent(a, b) {
    const x = Math.max(Math.abs(a.x), Math.abs(b.x));
    const y = Math.max(Math.abs(a.y), Math.abs(b.y));
    const z = Math.max(Math.abs(a.z), Math.abs(b.z));
    return Math.max(Math.max(x, y), z);
  }

  function cameraEqual(camera0, camera1, epsilon) {
    const scalar =
      1 / Math.max(1, maxComponent(camera0.position, camera1.position));
    Cartesian3.multiplyByScalar(camera0.position, scalar, scratchPosition0);
    Cartesian3.multiplyByScalar(camera1.position, scalar, scratchPosition1);
    return (
      Cartesian3.equalsEpsilon(scratchPosition0, scratchPosition1, epsilon) &&
      Cartesian3.equalsEpsilon(camera0.direction, camera1.direction, epsilon) &&
      Cartesian3.equalsEpsilon(camera0.up, camera1.up, epsilon) &&
      Cartesian3.equalsEpsilon(camera0.right, camera1.right, epsilon) &&
      Matrix4.equalsEpsilon(camera0.transform, camera1.transform, epsilon) &&
      camera0.frustum.equalsEpsilon(camera1.frustum, epsilon)
    );
  }

  View.prototype.checkForCameraUpdates = function (scene) {
    const camera = this.camera;
    const cameraClone = this._cameraClone;
    if (!cameraEqual(camera, cameraClone, CesiumMath.EPSILON15)) {
      if (!this._cameraStartFired) {
        camera.moveStart.raiseEvent();
        this._cameraStartFired = true;
      }
      this._cameraMovedTime = getTimestamp$1();
      Camera.clone(camera, cameraClone);

      return true;
    }

    if (
      this._cameraStartFired &&
      getTimestamp$1() - this._cameraMovedTime > scene.cameraEventWaitTime
    ) {
      camera.moveEnd.raiseEvent();
      this._cameraStartFired = false;
    }

    return false;
  };

  function updateFrustums(view, scene, near, far) {
    const frameState = scene.frameState;
    const camera = frameState.camera;
    const farToNearRatio = frameState.useLogDepth
      ? scene.logarithmicDepthFarToNearRatio
      : scene.farToNearRatio;
    const is2D = scene.mode === SceneMode$1.SCENE2D;
    const nearToFarDistance2D = scene.nearToFarDistance2D;

    // Extend the far plane slightly further to prevent geometry clipping against the far plane.
    far *= 1.0 + CesiumMath.EPSILON2;

    // The computed near plane must be between the user defined near and far planes.
    // The computed far plane must between the user defined far and computed near.
    // This will handle the case where the computed near plane is further than the user defined far plane.
    near = Math.min(Math.max(near, camera.frustum.near), camera.frustum.far);
    far = Math.max(Math.min(far, camera.frustum.far), near);

    let numFrustums;
    if (is2D) {
      // The multifrustum for 2D is uniformly distributed. To avoid z-fighting in 2D,
      // the camera is moved to just before the frustum and the frustum depth is scaled
      // to be in [1.0, nearToFarDistance2D].
      far = Math.min(far, camera.position.z + scene.nearToFarDistance2D);
      near = Math.min(near, far);
      numFrustums = Math.ceil(
        Math.max(1.0, far - near) / scene.nearToFarDistance2D
      );
    } else {
      // The multifrustum for 3D/CV is non-uniformly distributed.
      numFrustums = Math.ceil(Math.log(far / near) / Math.log(farToNearRatio));
    }

    const frustumCommandsList = view.frustumCommandsList;
    frustumCommandsList.length = numFrustums;
    for (let m = 0; m < numFrustums; ++m) {
      let curNear;
      let curFar;

      if (is2D) {
        curNear = Math.min(
          far - nearToFarDistance2D,
          near + m * nearToFarDistance2D
        );
        curFar = Math.min(far, curNear + nearToFarDistance2D);
      } else {
        curNear = Math.max(near, Math.pow(farToNearRatio, m) * near);
        curFar = Math.min(far, farToNearRatio * curNear);
      }
      let frustumCommands = frustumCommandsList[m];
      if (!defined(frustumCommands)) {
        frustumCommands = frustumCommandsList[m] = new FrustumCommands(
          curNear,
          curFar
        );
      } else {
        frustumCommands.near = curNear;
        frustumCommands.far = curFar;
      }
    }
  }

  function insertIntoBin(view, scene, command, commandNear, commandFar) {
    if (scene.debugShowFrustums) {
      command.debugOverlappingFrustums = 0;
    }

    const frustumCommandsList = view.frustumCommandsList;
    const length = frustumCommandsList.length;

    for (let i = 0; i < length; ++i) {
      const frustumCommands = frustumCommandsList[i];
      const curNear = frustumCommands.near;
      const curFar = frustumCommands.far;

      if (commandNear > curFar) {
        continue;
      }

      if (commandFar < curNear) {
        break;
      }

      const pass = command.pass;
      const index = frustumCommands.indices[pass]++;
      frustumCommands.commands[pass][index] = command;

      if (scene.debugShowFrustums) {
        command.debugOverlappingFrustums |= 1 << i;
      }

      if (command.executeInClosestFrustum) {
        break;
      }
    }

    if (scene.debugShowFrustums) {
      const cf = view.debugFrustumStatistics.commandsInFrustums;
      cf[command.debugOverlappingFrustums] = defined(
        cf[command.debugOverlappingFrustums]
      )
        ? cf[command.debugOverlappingFrustums] + 1
        : 1;
      ++view.debugFrustumStatistics.totalCommands;
    }

    scene.updateDerivedCommands(command);
  }

  const scratchCullingVolume$1 = new CullingVolume();
  const scratchNearFarInterval = new Interval();

  View.prototype.createPotentiallyVisibleSet = function (scene) {
    const frameState = scene.frameState;
    const camera = frameState.camera;
    const direction = camera.directionWC;
    const position = camera.positionWC;

    const computeList = scene._computeCommandList;
    const overlayList = scene._overlayCommandList;
    const commandList = frameState.commandList;

    if (scene.debugShowFrustums) {
      this.debugFrustumStatistics = {
        totalCommands: 0,
        commandsInFrustums: {},
      };
    }

    const frustumCommandsList = this.frustumCommandsList;
    const numberOfFrustums = frustumCommandsList.length;
    const numberOfPasses = Pass$1.NUMBER_OF_PASSES;
    for (let n = 0; n < numberOfFrustums; ++n) {
      for (let p = 0; p < numberOfPasses; ++p) {
        frustumCommandsList[n].indices[p] = 0;
      }
    }

    computeList.length = 0;
    overlayList.length = 0;

    const commandExtents = this._commandExtents;
    const commandExtentCapacity = commandExtents.length;
    let commandExtentCount = 0;

    let near = +Number.MAX_VALUE;
    let far = -Number.MAX_VALUE;

    const shadowsEnabled = frameState.shadowState.shadowsEnabled;
    let shadowNear = +Number.MAX_VALUE;
    let shadowFar = -Number.MAX_VALUE;
    let shadowClosestObjectSize = Number.MAX_VALUE;

    const occluder =
      frameState.mode === SceneMode$1.SCENE3D ? frameState.occluder : undefined;
    let cullingVolume = frameState.cullingVolume;

    // get user culling volume minus the far plane.
    const planes = scratchCullingVolume$1.planes;
    for (let k = 0; k < 5; ++k) {
      planes[k] = cullingVolume.planes[k];
    }
    cullingVolume = scratchCullingVolume$1;

    const length = commandList.length;
    for (let i = 0; i < length; ++i) {
      const command = commandList[i];
      const pass = command.pass;

      if (pass === Pass$1.COMPUTE) {
        computeList.push(command);
      } else if (pass === Pass$1.OVERLAY) {
        overlayList.push(command);
      } else {
        let commandNear;
        let commandFar;

        const boundingVolume = command.boundingVolume;
        if (defined(boundingVolume)) {
          if (!scene.isVisible(command, cullingVolume, occluder)) {
            continue;
          }

          const nearFarInterval = boundingVolume.computePlaneDistances(
            position,
            direction,
            scratchNearFarInterval
          );
          commandNear = nearFarInterval.start;
          commandFar = nearFarInterval.stop;
          near = Math.min(near, commandNear);
          far = Math.max(far, commandFar);

          // Compute a tight near and far plane for commands that receive shadows. This helps compute
          // good splits for cascaded shadow maps. Ignore commands that exceed the maximum distance.
          // When moving the camera low LOD globe tiles begin to load, whose bounding volumes
          // throw off the near/far fitting for the shadow map. Only update for globe tiles that the
          // camera isn't inside.
          if (
            shadowsEnabled &&
            command.receiveShadows &&
            commandNear < ShadowMap.MAXIMUM_DISTANCE &&
            !(pass === Pass$1.GLOBE && commandNear < -100.0 && commandFar > 100.0)
          ) {
            // Get the smallest bounding volume the camera is near. This is used to place more shadow detail near the object.
            const size = commandFar - commandNear;
            if (pass !== Pass$1.GLOBE && commandNear < 100.0) {
              shadowClosestObjectSize = Math.min(shadowClosestObjectSize, size);
            }
            shadowNear = Math.min(shadowNear, commandNear);
            shadowFar = Math.max(shadowFar, commandFar);
          }
        } else if (command instanceof ClearCommand) {
          // Clear commands don't need a bounding volume - just add the clear to all frustums.
          commandNear = camera.frustum.near;
          commandFar = camera.frustum.far;
        } else {
          // If command has no bounding volume we need to use the camera's
          // worst-case near and far planes to avoid clipping something important.
          commandNear = camera.frustum.near;
          commandFar = camera.frustum.far;
          near = Math.min(near, commandNear);
          far = Math.max(far, commandFar);
        }

        let extent = commandExtents[commandExtentCount];
        if (!defined(extent)) {
          extent = commandExtents[commandExtentCount] = new CommandExtent();
        }
        extent.command = command;
        extent.near = commandNear;
        extent.far = commandFar;
        commandExtentCount++;
      }
    }

    if (shadowsEnabled) {
      shadowNear = Math.min(
        Math.max(shadowNear, camera.frustum.near),
        camera.frustum.far
      );
      shadowFar = Math.max(Math.min(shadowFar, camera.frustum.far), shadowNear);
    }

    // Use the computed near and far for shadows
    if (shadowsEnabled) {
      frameState.shadowState.nearPlane = shadowNear;
      frameState.shadowState.farPlane = shadowFar;
      frameState.shadowState.closestObjectSize = shadowClosestObjectSize;
    }

    updateFrustums(this, scene, near, far);

    let c;
    let ce;

    for (c = 0; c < commandExtentCount; c++) {
      ce = commandExtents[c];
      insertIntoBin(this, scene, ce.command, ce.near, ce.far);
    }

    // Dereference old commands
    if (commandExtentCount < commandExtentCapacity) {
      for (c = commandExtentCount; c < commandExtentCapacity; c++) {
        ce = commandExtents[c];
        if (!defined(ce.command)) {
          // If the command is undefined, it's assumed that all
          // subsequent commmands were set to undefined as well,
          // so no need to loop over them all
          break;
        }
        ce.command = undefined;
      }
    }

    const numFrustums = frustumCommandsList.length;
    const frustumSplits = frameState.frustumSplits;
    frustumSplits.length = numFrustums + 1;
    for (let j = 0; j < numFrustums; ++j) {
      frustumSplits[j] = frustumCommandsList[j].near;
      if (j === numFrustums - 1) {
        frustumSplits[j + 1] = frustumCommandsList[j].far;
      }
    }
  };

  View.prototype.destroy = function () {
    this.pickFramebuffer = this.pickFramebuffer && this.pickFramebuffer.destroy();
    this.pickDepthFramebuffer =
      this.pickDepthFramebuffer && this.pickDepthFramebuffer.destroy();
    this.sceneFramebuffer =
      this.sceneFramebuffer && this.sceneFramebuffer.destroy();
    this.globeDepth = this.globeDepth && this.globeDepth.destroy();
    this.oit = this.oit && this.oit.destroy();
    this.translucentTileClassification =
      this.translucentTileClassification &&
      this.translucentTileClassification.destroy();
    this.globeTranslucencyFramebuffer =
      this.globeTranslucencyFramebuffer &&
      this.globeTranslucencyFramebuffer.destroy();

    let i;
    const pickDepths = this.pickDepths;
    const length = pickDepths.length;
    for (i = 0; i < length; ++i) {
      pickDepths[i].destroy();
    }
  };

  const offscreenDefaultWidth = 0.1;

  const mostDetailedPreloadTilesetPassState = new Cesium3DTilePassState({
    pass: Cesium3DTilePass$1.MOST_DETAILED_PRELOAD,
  });

  const mostDetailedPickTilesetPassState = new Cesium3DTilePassState({
    pass: Cesium3DTilePass$1.MOST_DETAILED_PICK,
  });

  const pickTilesetPassState = new Cesium3DTilePassState({
    pass: Cesium3DTilePass$1.PICK,
  });

  /**
   * @private
   */
  function Picking(scene) {
    this._mostDetailedRayPicks = [];
    this.pickRenderStateCache = {};
    this._pickPositionCache = {};
    this._pickPositionCacheDirty = false;

    const pickOffscreenViewport = new BoundingRectangle(0, 0, 1, 1);
    const pickOffscreenCamera = new Camera(scene);
    pickOffscreenCamera.frustum = new OrthographicFrustum({
      width: offscreenDefaultWidth,
      aspectRatio: 1.0,
      near: 0.1,
    });

    this._pickOffscreenView = new View(
      scene,
      pickOffscreenCamera,
      pickOffscreenViewport
    );
  }

  Picking.prototype.update = function () {
    this._pickPositionCacheDirty = true;
  };

  Picking.prototype.getPickDepth = function (scene, index) {
    const pickDepths = scene.view.pickDepths;
    let pickDepth = pickDepths[index];
    if (!defined(pickDepth)) {
      pickDepth = new PickDepth();
      pickDepths[index] = pickDepth;
    }
    return pickDepth;
  };

  const scratchOrthoPickingFrustum = new OrthographicOffCenterFrustum();
  const scratchOrthoOrigin = new Cartesian3();
  const scratchOrthoDirection = new Cartesian3();
  const scratchOrthoPixelSize = new Cartesian2();
  const scratchOrthoPickVolumeMatrix4 = new Matrix4();

  function getPickOrthographicCullingVolume(
    scene,
    drawingBufferPosition,
    width,
    height,
    viewport
  ) {
    const camera = scene.camera;
    let frustum = camera.frustum;
    if (defined(frustum._offCenterFrustum)) {
      frustum = frustum._offCenterFrustum;
    }

    let x = (2.0 * (drawingBufferPosition.x - viewport.x)) / viewport.width - 1.0;
    x *= (frustum.right - frustum.left) * 0.5;
    let y =
      (2.0 * (viewport.height - drawingBufferPosition.y - viewport.y)) /
        viewport.height -
      1.0;
    y *= (frustum.top - frustum.bottom) * 0.5;

    const transform = Matrix4.clone(
      camera.transform,
      scratchOrthoPickVolumeMatrix4
    );
    camera._setTransform(Matrix4.IDENTITY);

    const origin = Cartesian3.clone(camera.position, scratchOrthoOrigin);
    Cartesian3.multiplyByScalar(camera.right, x, scratchOrthoDirection);
    Cartesian3.add(scratchOrthoDirection, origin, origin);
    Cartesian3.multiplyByScalar(camera.up, y, scratchOrthoDirection);
    Cartesian3.add(scratchOrthoDirection, origin, origin);

    camera._setTransform(transform);

    if (scene.mode === SceneMode$1.SCENE2D) {
      Cartesian3.fromElements(origin.z, origin.x, origin.y, origin);
    }

    const pixelSize = frustum.getPixelDimensions(
      viewport.width,
      viewport.height,
      1.0,
      1.0,
      scratchOrthoPixelSize
    );

    const ortho = scratchOrthoPickingFrustum;
    ortho.right = pixelSize.x * 0.5;
    ortho.left = -ortho.right;
    ortho.top = pixelSize.y * 0.5;
    ortho.bottom = -ortho.top;
    ortho.near = frustum.near;
    ortho.far = frustum.far;

    return ortho.computeCullingVolume(origin, camera.directionWC, camera.upWC);
  }

  const scratchPerspPickingFrustum = new PerspectiveOffCenterFrustum();
  const scratchPerspPixelSize = new Cartesian2();

  function getPickPerspectiveCullingVolume(
    scene,
    drawingBufferPosition,
    width,
    height,
    viewport
  ) {
    const camera = scene.camera;
    const frustum = camera.frustum;
    const near = frustum.near;

    const tanPhi = Math.tan(frustum.fovy * 0.5);
    const tanTheta = frustum.aspectRatio * tanPhi;

    const x =
      (2.0 * (drawingBufferPosition.x - viewport.x)) / viewport.width - 1.0;
    const y =
      (2.0 * (viewport.height - drawingBufferPosition.y - viewport.y)) /
        viewport.height -
      1.0;

    const xDir = x * near * tanTheta;
    const yDir = y * near * tanPhi;

    const pixelSize = frustum.getPixelDimensions(
      viewport.width,
      viewport.height,
      1.0,
      1.0,
      scratchPerspPixelSize
    );
    const pickWidth = pixelSize.x * width * 0.5;
    const pickHeight = pixelSize.y * height * 0.5;

    const offCenter = scratchPerspPickingFrustum;
    offCenter.top = yDir + pickHeight;
    offCenter.bottom = yDir - pickHeight;
    offCenter.right = xDir + pickWidth;
    offCenter.left = xDir - pickWidth;
    offCenter.near = near;
    offCenter.far = frustum.far;

    return offCenter.computeCullingVolume(
      camera.positionWC,
      camera.directionWC,
      camera.upWC
    );
  }

  function getPickCullingVolume(
    scene,
    drawingBufferPosition,
    width,
    height,
    viewport
  ) {
    const frustum = scene.camera.frustum;
    if (
      frustum instanceof OrthographicFrustum ||
      frustum instanceof OrthographicOffCenterFrustum
    ) {
      return getPickOrthographicCullingVolume(
        scene,
        drawingBufferPosition,
        width,
        height,
        viewport
      );
    }

    return getPickPerspectiveCullingVolume(
      scene,
      drawingBufferPosition,
      width,
      height,
      viewport
    );
  }

  // pick rectangle width and height, assumed odd
  let scratchRectangleWidth = 3.0;
  let scratchRectangleHeight = 3.0;
  let scratchRectangle = new BoundingRectangle(
    0.0,
    0.0,
    scratchRectangleWidth,
    scratchRectangleHeight
  );
  const scratchPosition = new Cartesian2();
  const scratchColorZero = new Color(0.0, 0.0, 0.0, 0.0);

  Picking.prototype.pick = function (scene, windowPosition, width, height) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(windowPosition)) {
      throw new DeveloperError("windowPosition is undefined.");
    }
    //>>includeEnd('debug');

    scratchRectangleWidth = defaultValue(width, 3.0);
    scratchRectangleHeight = defaultValue(height, scratchRectangleWidth);

    const context = scene.context;
    const us = context.uniformState;
    const frameState = scene.frameState;

    const view = scene.defaultView;
    scene.view = view;

    const viewport = view.viewport;
    viewport.x = 0;
    viewport.y = 0;
    viewport.width = context.drawingBufferWidth;
    viewport.height = context.drawingBufferHeight;

    let passState = view.passState;
    passState.viewport = BoundingRectangle.clone(viewport, passState.viewport);

    const drawingBufferPosition = SceneTransforms.transformWindowToDrawingBuffer(
      scene,
      windowPosition,
      scratchPosition
    );

    scene.jobScheduler.disableThisFrame();

    scene.updateFrameState();
    frameState.cullingVolume = getPickCullingVolume(
      scene,
      drawingBufferPosition,
      scratchRectangleWidth,
      scratchRectangleHeight,
      viewport
    );
    frameState.invertClassification = false;
    frameState.passes.pick = true;
    frameState.tilesetPassState = pickTilesetPassState;

    us.update(frameState);

    scene.updateEnvironment();

    scratchRectangle.x =
      drawingBufferPosition.x - (scratchRectangleWidth - 1.0) * 0.5;
    scratchRectangle.y =
      scene.drawingBufferHeight -
      drawingBufferPosition.y -
      (scratchRectangleHeight - 1.0) * 0.5;
    scratchRectangle.width = scratchRectangleWidth;
    scratchRectangle.height = scratchRectangleHeight;
    passState = view.pickFramebuffer.begin(scratchRectangle, view.viewport);

    scene.updateAndExecuteCommands(passState, scratchColorZero);
    scene.resolveFramebuffers(passState);

    const object = view.pickFramebuffer.end(scratchRectangle);
    context.endFrame();
    return object;
  };

  function renderTranslucentDepthForPick(scene, drawingBufferPosition) {
    // PERFORMANCE_IDEA: render translucent only and merge with the previous frame
    const context = scene.context;
    const frameState = scene.frameState;
    const environmentState = scene.environmentState;

    const view = scene.defaultView;
    scene.view = view;

    const viewport = view.viewport;
    viewport.x = 0;
    viewport.y = 0;
    viewport.width = context.drawingBufferWidth;
    viewport.height = context.drawingBufferHeight;

    let passState = view.passState;
    passState.viewport = BoundingRectangle.clone(viewport, passState.viewport);

    scene.clearPasses(frameState.passes);
    frameState.passes.pick = true;
    frameState.passes.depth = true;
    frameState.cullingVolume = getPickCullingVolume(
      scene,
      drawingBufferPosition,
      1,
      1,
      viewport
    );
    frameState.tilesetPassState = pickTilesetPassState;

    scene.updateEnvironment();
    environmentState.renderTranslucentDepthForPick = true;
    passState = view.pickDepthFramebuffer.update(
      context,
      drawingBufferPosition,
      viewport
    );

    scene.updateAndExecuteCommands(passState, scratchColorZero);
    scene.resolveFramebuffers(passState);

    context.endFrame();
  }

  const scratchPerspectiveFrustum$1 = new PerspectiveFrustum();
  const scratchPerspectiveOffCenterFrustum$1 = new PerspectiveOffCenterFrustum();
  const scratchOrthographicFrustum$1 = new OrthographicFrustum();
  const scratchOrthographicOffCenterFrustum$1 = new OrthographicOffCenterFrustum();

  Picking.prototype.pickPositionWorldCoordinates = function (
    scene,
    windowPosition,
    result
  ) {
    if (!scene.useDepthPicking) {
      return undefined;
    }

    //>>includeStart('debug', pragmas.debug);
    if (!defined(windowPosition)) {
      throw new DeveloperError("windowPosition is undefined.");
    }
    if (!scene.context.depthTexture) {
      throw new DeveloperError(
        "Picking from the depth buffer is not supported. Check pickPositionSupported."
      );
    }
    //>>includeEnd('debug');

    const cacheKey = windowPosition.toString();

    if (this._pickPositionCacheDirty) {
      this._pickPositionCache = {};
      this._pickPositionCacheDirty = false;
    } else if (this._pickPositionCache.hasOwnProperty(cacheKey)) {
      return Cartesian3.clone(this._pickPositionCache[cacheKey], result);
    }

    const frameState = scene.frameState;
    const context = scene.context;
    const uniformState = context.uniformState;

    const view = scene.defaultView;
    scene.view = view;

    const drawingBufferPosition = SceneTransforms.transformWindowToDrawingBuffer(
      scene,
      windowPosition,
      scratchPosition
    );
    if (scene.pickTranslucentDepth) {
      renderTranslucentDepthForPick(scene, drawingBufferPosition);
    } else {
      scene.updateFrameState();
      uniformState.update(frameState);
      scene.updateEnvironment();
    }
    drawingBufferPosition.y = scene.drawingBufferHeight - drawingBufferPosition.y;

    const camera = scene.camera;

    // Create a working frustum from the original camera frustum.
    let frustum;
    if (defined(camera.frustum.fov)) {
      frustum = camera.frustum.clone(scratchPerspectiveFrustum$1);
    } else if (defined(camera.frustum.infiniteProjectionMatrix)) {
      frustum = camera.frustum.clone(scratchPerspectiveOffCenterFrustum$1);
    } else if (defined(camera.frustum.width)) {
      frustum = camera.frustum.clone(scratchOrthographicFrustum$1);
    } else {
      frustum = camera.frustum.clone(scratchOrthographicOffCenterFrustum$1);
    }

    const frustumCommandsList = view.frustumCommandsList;
    const numFrustums = frustumCommandsList.length;
    for (let i = 0; i < numFrustums; ++i) {
      const pickDepth = this.getPickDepth(scene, i);
      const depth = pickDepth.getDepth(
        context,
        drawingBufferPosition.x,
        drawingBufferPosition.y
      );
      if (!defined(depth)) {
        continue;
      }
      if (depth > 0.0 && depth < 1.0) {
        const renderedFrustum = frustumCommandsList[i];
        let height2D;
        if (scene.mode === SceneMode$1.SCENE2D) {
          height2D = camera.position.z;
          camera.position.z = height2D - renderedFrustum.near + 1.0;
          frustum.far = Math.max(1.0, renderedFrustum.far - renderedFrustum.near);
          frustum.near = 1.0;
          uniformState.update(frameState);
          uniformState.updateFrustum(frustum);
        } else {
          frustum.near =
            renderedFrustum.near *
            (i !== 0 ? scene.opaqueFrustumNearOffset : 1.0);
          frustum.far = renderedFrustum.far;
          uniformState.updateFrustum(frustum);
        }

        result = SceneTransforms.drawingBufferToWgs84Coordinates(
          scene,
          drawingBufferPosition,
          depth,
          result
        );

        if (scene.mode === SceneMode$1.SCENE2D) {
          camera.position.z = height2D;
          uniformState.update(frameState);
        }

        this._pickPositionCache[cacheKey] = Cartesian3.clone(result);
        return result;
      }
    }

    this._pickPositionCache[cacheKey] = undefined;
    return undefined;
  };

  const scratchPickPositionCartographic = new Cartographic();

  Picking.prototype.pickPosition = function (scene, windowPosition, result) {
    result = this.pickPositionWorldCoordinates(scene, windowPosition, result);
    if (defined(result) && scene.mode !== SceneMode$1.SCENE3D) {
      Cartesian3.fromElements(result.y, result.z, result.x, result);

      const projection = scene.mapProjection;
      const ellipsoid = projection.ellipsoid;

      const cart = projection.unproject(result, scratchPickPositionCartographic);
      ellipsoid.cartographicToCartesian(cart, result);
    }

    return result;
  };

  function drillPick(limit, pickCallback) {
    // PERFORMANCE_IDEA: This function calls each primitive's update for each pass. Instead
    // we could update the primitive once, and then just execute their commands for each pass,
    // and cull commands for picked primitives.  e.g., base on the command's owner.
    let i;
    let attributes;
    const result = [];
    const pickedPrimitives = [];
    const pickedAttributes = [];
    const pickedFeatures = [];
    if (!defined(limit)) {
      limit = Number.MAX_VALUE;
    }

    let pickedResult = pickCallback();
    while (defined(pickedResult)) {
      const object = pickedResult.object;
      const position = pickedResult.position;
      const exclude = pickedResult.exclude;

      if (defined(position) && !defined(object)) {
        result.push(pickedResult);
        break;
      }

      if (!defined(object) || !defined(object.primitive)) {
        break;
      }

      if (!exclude) {
        result.push(pickedResult);
        if (0 >= --limit) {
          break;
        }
      }

      const primitive = object.primitive;
      let hasShowAttribute = false;

      // If the picked object has a show attribute, use it.
      if (typeof primitive.getGeometryInstanceAttributes === "function") {
        if (defined(object.id)) {
          attributes = primitive.getGeometryInstanceAttributes(object.id);
          if (defined(attributes) && defined(attributes.show)) {
            hasShowAttribute = true;
            attributes.show = ShowGeometryInstanceAttribute.toValue(
              false,
              attributes.show
            );
            pickedAttributes.push(attributes);
          }
        }
      }

      if (object instanceof Cesium3DTileFeature) {
        hasShowAttribute = true;
        object.show = false;
        pickedFeatures.push(object);
      }

      // Otherwise, hide the entire primitive
      if (!hasShowAttribute) {
        primitive.show = false;
        pickedPrimitives.push(primitive);
      }

      pickedResult = pickCallback();
    }

    // Unhide everything we hid while drill picking
    for (i = 0; i < pickedPrimitives.length; ++i) {
      pickedPrimitives[i].show = true;
    }

    for (i = 0; i < pickedAttributes.length; ++i) {
      attributes = pickedAttributes[i];
      attributes.show = ShowGeometryInstanceAttribute.toValue(
        true,
        attributes.show
      );
    }

    for (i = 0; i < pickedFeatures.length; ++i) {
      pickedFeatures[i].show = true;
    }

    return result;
  }

  Picking.prototype.drillPick = function (
    scene,
    windowPosition,
    limit,
    width,
    height
  ) {
    const that = this;
    const pickCallback = function () {
      const object = that.pick(scene, windowPosition, width, height);
      if (defined(object)) {
        return {
          object: object,
          position: undefined,
          exclude: false,
        };
      }
    };
    const objects = drillPick(limit, pickCallback);
    return objects.map(function (element) {
      return element.object;
    });
  };

  const scratchRight = new Cartesian3();
  const scratchUp = new Cartesian3();

  function MostDetailedRayPick(ray, width, tilesets) {
    this.ray = ray;
    this.width = width;
    this.tilesets = tilesets;
    this.ready = false;
    this.deferred = defer();
    this.promise = this.deferred.promise;
  }

  function updateOffscreenCameraFromRay(picking, ray, width, camera) {
    const direction = ray.direction;
    const orthogonalAxis = Cartesian3.mostOrthogonalAxis(direction, scratchRight);
    const right = Cartesian3.cross(direction, orthogonalAxis, scratchRight);
    const up = Cartesian3.cross(direction, right, scratchUp);

    camera.position = ray.origin;
    camera.direction = direction;
    camera.up = up;
    camera.right = right;

    camera.frustum.width = defaultValue(width, offscreenDefaultWidth);
    return camera.frustum.computeCullingVolume(
      camera.positionWC,
      camera.directionWC,
      camera.upWC
    );
  }

  function updateMostDetailedRayPick(picking, scene, rayPick) {
    const frameState = scene.frameState;

    const ray = rayPick.ray;
    const width = rayPick.width;
    const tilesets = rayPick.tilesets;

    const camera = picking._pickOffscreenView.camera;
    const cullingVolume = updateOffscreenCameraFromRay(
      picking,
      ray,
      width,
      camera
    );

    const tilesetPassState = mostDetailedPreloadTilesetPassState;
    tilesetPassState.camera = camera;
    tilesetPassState.cullingVolume = cullingVolume;

    let ready = true;
    const tilesetsLength = tilesets.length;
    for (let i = 0; i < tilesetsLength; ++i) {
      const tileset = tilesets[i];
      if (tileset.show && scene.primitives.contains(tileset)) {
        // Only update tilesets that are still contained in the scene's primitive collection and are still visible
        // Update tilesets continually until all tilesets are ready. This way tiles are never removed from the cache.
        tileset.updateForPass(frameState, tilesetPassState);
        ready = ready && tilesetPassState.ready;
      }
    }

    if (ready) {
      rayPick.deferred.resolve();
    }

    return ready;
  }

  Picking.prototype.updateMostDetailedRayPicks = function (scene) {
    // Modifies array during iteration
    const rayPicks = this._mostDetailedRayPicks;
    for (let i = 0; i < rayPicks.length; ++i) {
      if (updateMostDetailedRayPick(this, scene, rayPicks[i])) {
        rayPicks.splice(i--, 1);
      }
    }
  };

  function getTilesets(primitives, objectsToExclude, tilesets) {
    const length = primitives.length;
    for (let i = 0; i < length; ++i) {
      const primitive = primitives.get(i);
      if (primitive.show) {
        if (defined(primitive.isCesium3DTileset)) {
          if (
            !defined(objectsToExclude) ||
            objectsToExclude.indexOf(primitive) === -1
          ) {
            tilesets.push(primitive);
          }
        } else if (primitive instanceof PrimitiveCollection) {
          getTilesets(primitive, objectsToExclude, tilesets);
        }
      }
    }
  }

  function launchMostDetailedRayPick(
    picking,
    scene,
    ray,
    objectsToExclude,
    width,
    callback
  ) {
    const tilesets = [];
    getTilesets(scene.primitives, objectsToExclude, tilesets);
    if (tilesets.length === 0) {
      return Promise.resolve(callback());
    }

    const rayPick = new MostDetailedRayPick(ray, width, tilesets);
    picking._mostDetailedRayPicks.push(rayPick);
    return rayPick.promise.then(function () {
      return callback();
    });
  }

  function isExcluded(object, objectsToExclude) {
    if (
      !defined(object) ||
      !defined(objectsToExclude) ||
      objectsToExclude.length === 0
    ) {
      return false;
    }
    return (
      objectsToExclude.indexOf(object) > -1 ||
      objectsToExclude.indexOf(object.primitive) > -1 ||
      objectsToExclude.indexOf(object.id) > -1
    );
  }

  function getRayIntersection(
    picking,
    scene,
    ray,
    objectsToExclude,
    width,
    requirePosition,
    mostDetailed
  ) {
    const context = scene.context;
    const uniformState = context.uniformState;
    const frameState = scene.frameState;

    const view = picking._pickOffscreenView;
    scene.view = view;

    updateOffscreenCameraFromRay(picking, ray, width, view.camera);

    scratchRectangle = BoundingRectangle.clone(view.viewport, scratchRectangle);

    const passState = view.pickFramebuffer.begin(scratchRectangle, view.viewport);

    scene.jobScheduler.disableThisFrame();

    scene.updateFrameState();
    frameState.invertClassification = false;
    frameState.passes.pick = true;
    frameState.passes.offscreen = true;

    if (mostDetailed) {
      frameState.tilesetPassState = mostDetailedPickTilesetPassState;
    } else {
      frameState.tilesetPassState = pickTilesetPassState;
    }

    uniformState.update(frameState);

    scene.updateEnvironment();
    scene.updateAndExecuteCommands(passState, scratchColorZero);
    scene.resolveFramebuffers(passState);

    let position;
    const object = view.pickFramebuffer.end(scratchRectangle);

    if (scene.context.depthTexture) {
      const numFrustums = view.frustumCommandsList.length;
      for (let i = 0; i < numFrustums; ++i) {
        const pickDepth = picking.getPickDepth(scene, i);
        const depth = pickDepth.getDepth(context, 0, 0);
        if (!defined(depth)) {
          continue;
        }
        if (depth > 0.0 && depth < 1.0) {
          const renderedFrustum = view.frustumCommandsList[i];
          const near =
            renderedFrustum.near *
            (i !== 0 ? scene.opaqueFrustumNearOffset : 1.0);
          const far = renderedFrustum.far;
          const distance = near + depth * (far - near);
          position = Ray.getPoint(ray, distance);
          break;
        }
      }
    }

    scene.view = scene.defaultView;
    context.endFrame();

    if (defined(object) || defined(position)) {
      return {
        object: object,
        position: position,
        exclude:
          (!defined(position) && requirePosition) ||
          isExcluded(object, objectsToExclude),
      };
    }
  }

  function getRayIntersections(
    picking,
    scene,
    ray,
    limit,
    objectsToExclude,
    width,
    requirePosition,
    mostDetailed
  ) {
    const pickCallback = function () {
      return getRayIntersection(
        picking,
        scene,
        ray,
        objectsToExclude,
        width,
        requirePosition,
        mostDetailed
      );
    };
    return drillPick(limit, pickCallback);
  }

  function pickFromRay(
    picking,
    scene,
    ray,
    objectsToExclude,
    width,
    requirePosition,
    mostDetailed
  ) {
    const results = getRayIntersections(
      picking,
      scene,
      ray,
      1,
      objectsToExclude,
      width,
      requirePosition,
      mostDetailed
    );
    if (results.length > 0) {
      return results[0];
    }
  }

  function drillPickFromRay(
    picking,
    scene,
    ray,
    limit,
    objectsToExclude,
    width,
    requirePosition,
    mostDetailed
  ) {
    return getRayIntersections(
      picking,
      scene,
      ray,
      limit,
      objectsToExclude,
      width,
      requirePosition,
      mostDetailed
    );
  }

  function deferPromiseUntilPostRender(scene, promise) {
    // Resolve promise after scene's postRender in case entities are created when the promise resolves.
    // Entities can't be created between viewer._onTick and viewer._postRender.
    const deferred = defer();
    promise
      .then(function (result) {
        const removeCallback = scene.postRender.addEventListener(function () {
          deferred.resolve(result);
          removeCallback();
        });
        scene.requestRender();
      })
      .catch(function (error) {
        deferred.reject(error);
      });
    return deferred.promise;
  }

  Picking.prototype.pickFromRay = function (scene, ray, objectsToExclude, width) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("ray", ray);
    if (scene.mode !== SceneMode$1.SCENE3D) {
      throw new DeveloperError(
        "Ray intersections are only supported in 3D mode."
      );
    }
    //>>includeEnd('debug');

    return pickFromRay(this, scene, ray, objectsToExclude, width, false, false);
  };

  Picking.prototype.drillPickFromRay = function (
    scene,
    ray,
    limit,
    objectsToExclude,
    width
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("ray", ray);
    if (scene.mode !== SceneMode$1.SCENE3D) {
      throw new DeveloperError(
        "Ray intersections are only supported in 3D mode."
      );
    }
    //>>includeEnd('debug');

    return drillPickFromRay(
      this,
      scene,
      ray,
      limit,
      objectsToExclude,
      width,
      false,
      false
    );
  };

  Picking.prototype.pickFromRayMostDetailed = function (
    scene,
    ray,
    objectsToExclude,
    width
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("ray", ray);
    if (scene.mode !== SceneMode$1.SCENE3D) {
      throw new DeveloperError(
        "Ray intersections are only supported in 3D mode."
      );
    }
    //>>includeEnd('debug');

    const that = this;
    ray = Ray.clone(ray);
    objectsToExclude = defined(objectsToExclude)
      ? objectsToExclude.slice()
      : objectsToExclude;
    return deferPromiseUntilPostRender(
      scene,
      launchMostDetailedRayPick(
        that,
        scene,
        ray,
        objectsToExclude,
        width,
        function () {
          return pickFromRay(
            that,
            scene,
            ray,
            objectsToExclude,
            width,
            false,
            true
          );
        }
      )
    );
  };

  Picking.prototype.drillPickFromRayMostDetailed = function (
    scene,
    ray,
    limit,
    objectsToExclude,
    width
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("ray", ray);
    if (scene.mode !== SceneMode$1.SCENE3D) {
      throw new DeveloperError(
        "Ray intersections are only supported in 3D mode."
      );
    }
    //>>includeEnd('debug');

    const that = this;
    ray = Ray.clone(ray);
    objectsToExclude = defined(objectsToExclude)
      ? objectsToExclude.slice()
      : objectsToExclude;
    return deferPromiseUntilPostRender(
      scene,
      launchMostDetailedRayPick(
        that,
        scene,
        ray,
        objectsToExclude,
        width,
        function () {
          return drillPickFromRay(
            that,
            scene,
            ray,
            limit,
            objectsToExclude,
            width,
            false,
            true
          );
        }
      )
    );
  };

  const scratchSurfacePosition = new Cartesian3();
  const scratchSurfaceNormal$1 = new Cartesian3();
  const scratchSurfaceRay = new Ray();
  const scratchCartographic$1 = new Cartographic();

  function getRayForSampleHeight(scene, cartographic) {
    const globe = scene.globe;
    const ellipsoid = defined(globe)
      ? globe.ellipsoid
      : scene.mapProjection.ellipsoid;
    const height = ApproximateTerrainHeights._defaultMaxTerrainHeight;
    const surfaceNormal = ellipsoid.geodeticSurfaceNormalCartographic(
      cartographic,
      scratchSurfaceNormal$1
    );
    const surfacePosition = Cartographic.toCartesian(
      cartographic,
      ellipsoid,
      scratchSurfacePosition
    );
    const surfaceRay = scratchSurfaceRay;
    surfaceRay.origin = surfacePosition;
    surfaceRay.direction = surfaceNormal;
    const ray = new Ray();
    Ray.getPoint(surfaceRay, height, ray.origin);
    Cartesian3.negate(surfaceNormal, ray.direction);
    return ray;
  }

  function getRayForClampToHeight(scene, cartesian) {
    const globe = scene.globe;
    const ellipsoid = defined(globe)
      ? globe.ellipsoid
      : scene.mapProjection.ellipsoid;
    const cartographic = Cartographic.fromCartesian(
      cartesian,
      ellipsoid,
      scratchCartographic$1
    );
    return getRayForSampleHeight(scene, cartographic);
  }

  function getHeightFromCartesian(scene, cartesian) {
    const globe = scene.globe;
    const ellipsoid = defined(globe)
      ? globe.ellipsoid
      : scene.mapProjection.ellipsoid;
    const cartographic = Cartographic.fromCartesian(
      cartesian,
      ellipsoid,
      scratchCartographic$1
    );
    return cartographic.height;
  }

  function sampleHeightMostDetailed(
    picking,
    scene,
    cartographic,
    objectsToExclude,
    width
  ) {
    const ray = getRayForSampleHeight(scene, cartographic);
    return launchMostDetailedRayPick(
      picking,
      scene,
      ray,
      objectsToExclude,
      width,
      function () {
        const pickResult = pickFromRay(
          picking,
          scene,
          ray,
          objectsToExclude,
          width,
          true,
          true
        );
        if (defined(pickResult)) {
          return getHeightFromCartesian(scene, pickResult.position);
        }
      }
    );
  }

  function clampToHeightMostDetailed(
    picking,
    scene,
    cartesian,
    objectsToExclude,
    width,
    result
  ) {
    const ray = getRayForClampToHeight(scene, cartesian);
    return launchMostDetailedRayPick(
      picking,
      scene,
      ray,
      objectsToExclude,
      width,
      function () {
        const pickResult = pickFromRay(
          picking,
          scene,
          ray,
          objectsToExclude,
          width,
          true,
          true
        );
        if (defined(pickResult)) {
          return Cartesian3.clone(pickResult.position, result);
        }
      }
    );
  }

  Picking.prototype.sampleHeight = function (
    scene,
    position,
    objectsToExclude,
    width
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("position", position);
    if (scene.mode !== SceneMode$1.SCENE3D) {
      throw new DeveloperError("sampleHeight is only supported in 3D mode.");
    }
    if (!scene.sampleHeightSupported) {
      throw new DeveloperError(
        "sampleHeight requires depth texture support. Check sampleHeightSupported."
      );
    }
    //>>includeEnd('debug');

    const ray = getRayForSampleHeight(scene, position);
    const pickResult = pickFromRay(
      this,
      scene,
      ray,
      objectsToExclude,
      width,
      true,
      false
    );
    if (defined(pickResult)) {
      return getHeightFromCartesian(scene, pickResult.position);
    }
  };

  Picking.prototype.clampToHeight = function (
    scene,
    cartesian,
    objectsToExclude,
    width,
    result
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("cartesian", cartesian);
    if (scene.mode !== SceneMode$1.SCENE3D) {
      throw new DeveloperError("clampToHeight is only supported in 3D mode.");
    }
    if (!scene.clampToHeightSupported) {
      throw new DeveloperError(
        "clampToHeight requires depth texture support. Check clampToHeightSupported."
      );
    }
    //>>includeEnd('debug');

    const ray = getRayForClampToHeight(scene, cartesian);
    const pickResult = pickFromRay(
      this,
      scene,
      ray,
      objectsToExclude,
      width,
      true,
      false
    );
    if (defined(pickResult)) {
      return Cartesian3.clone(pickResult.position, result);
    }
  };

  Picking.prototype.sampleHeightMostDetailed = function (
    scene,
    positions,
    objectsToExclude,
    width
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("positions", positions);
    if (scene.mode !== SceneMode$1.SCENE3D) {
      throw new DeveloperError(
        "sampleHeightMostDetailed is only supported in 3D mode."
      );
    }
    if (!scene.sampleHeightSupported) {
      throw new DeveloperError(
        "sampleHeightMostDetailed requires depth texture support. Check sampleHeightSupported."
      );
    }
    //>>includeEnd('debug');

    objectsToExclude = defined(objectsToExclude)
      ? objectsToExclude.slice()
      : objectsToExclude;
    const length = positions.length;
    const promises = new Array(length);
    for (let i = 0; i < length; ++i) {
      promises[i] = sampleHeightMostDetailed(
        this,
        scene,
        positions[i],
        objectsToExclude,
        width
      );
    }
    return deferPromiseUntilPostRender(
      scene,
      Promise.all(promises).then(function (heights) {
        const length = heights.length;
        for (let i = 0; i < length; ++i) {
          positions[i].height = heights[i];
        }
        return positions;
      })
    );
  };

  Picking.prototype.clampToHeightMostDetailed = function (
    scene,
    cartesians,
    objectsToExclude,
    width
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("cartesians", cartesians);
    if (scene.mode !== SceneMode$1.SCENE3D) {
      throw new DeveloperError(
        "clampToHeightMostDetailed is only supported in 3D mode."
      );
    }
    if (!scene.clampToHeightSupported) {
      throw new DeveloperError(
        "clampToHeightMostDetailed requires depth texture support. Check clampToHeightSupported."
      );
    }
    //>>includeEnd('debug');

    objectsToExclude = defined(objectsToExclude)
      ? objectsToExclude.slice()
      : objectsToExclude;
    const length = cartesians.length;
    const promises = new Array(length);
    for (let i = 0; i < length; ++i) {
      promises[i] = clampToHeightMostDetailed(
        this,
        scene,
        cartesians[i],
        objectsToExclude,
        width,
        cartesians[i]
      );
    }
    return deferPromiseUntilPostRender(
      scene,
      Promise.all(promises).then(function (clampedCartesians) {
        const length = clampedCartesians.length;
        for (let i = 0; i < length; ++i) {
          cartesians[i] = clampedCartesians[i];
        }
        return cartesians;
      })
    );
  };

  Picking.prototype.destroy = function () {
    this._pickOffscreenView =
      this._pickOffscreenView && this._pickOffscreenView.destroy();
  };

  /**
   * Determines how input texture to a {@link PostProcessStage} is sampled.
   *
   * @enum {Number}
   */
  const PostProcessStageSampleMode = {
    /**
     * Samples the texture by returning the closest texel.
     *
     * @type {Number}
     * @constant
     */
    NEAREST: 0,
    /**
     * Samples the texture through bi-linear interpolation of the four nearest texels.
     *
     * @type {Number}
     * @constant
     */
    LINEAR: 1,
  };

  /**
   * Runs a post-process stage on either the texture rendered by the scene or the output of a previous post-process stage.
   *
   * @alias PostProcessStage
   * @constructor
   *
   * @param {Object} options An object with the following properties:
   * @param {String} options.fragmentShader The fragment shader to use. The default <code>sampler2D</code> uniforms are <code>colorTexture</code> and <code>depthTexture</code>. The color texture is the output of rendering the scene or the previous stage. The depth texture is the output from rendering the scene. The shader should contain one or both uniforms. There is also a <code>vec2</code> varying named <code>v_textureCoordinates</code> that can be used to sample the textures.
   * @param {Object} [options.uniforms] An object whose properties will be used to set the shaders uniforms. The properties can be constant values or a function. A constant value can also be a URI, data URI, or HTML element to use as a texture.
   * @param {Number} [options.textureScale=1.0] A number in the range (0.0, 1.0] used to scale the texture dimensions. A scale of 1.0 will render this post-process stage  to a texture the size of the viewport.
   * @param {Boolean} [options.forcePowerOfTwo=false] Whether or not to force the texture dimensions to be both equal powers of two. The power of two will be the next power of two of the minimum of the dimensions.
   * @param {PostProcessStageSampleMode} [options.sampleMode=PostProcessStageSampleMode.NEAREST] How to sample the input color texture.
   * @param {PixelFormat} [options.pixelFormat=PixelFormat.RGBA] The color pixel format of the output texture.
   * @param {PixelDatatype} [options.pixelDatatype=PixelDatatype.UNSIGNED_BYTE] The pixel data type of the output texture.
   * @param {Color} [options.clearColor=Color.BLACK] The color to clear the output texture to.
   * @param {BoundingRectangle} [options.scissorRectangle] The rectangle to use for the scissor test.
   * @param {String} [options.name=createGuid()] The unique name of this post-process stage for reference by other stages in a composite. If a name is not supplied, a GUID will be generated.
   *
   * @exception {DeveloperError} options.textureScale must be greater than 0.0 and less than or equal to 1.0.
   * @exception {DeveloperError} options.pixelFormat must be a color format.
   * @exception {DeveloperError} When options.pixelDatatype is FLOAT, this WebGL implementation must support the OES_texture_float extension.  Check context.floatingPointTexture.
   *
   * @see PostProcessStageComposite
   *
   * @example
   * // Simple stage to change the color
   * const fs =`
   *     uniform sampler2D colorTexture;
   *     varying vec2 v_textureCoordinates;
   *     uniform float scale;
   *     uniform vec3 offset;
   *     void main() {
   *         vec4 color = texture2D(colorTexture, v_textureCoordinates);
   *         gl_FragColor = vec4(color.rgb * scale + offset, 1.0);
   *     }`;
   * scene.postProcessStages.add(new Cesium.PostProcessStage({
   *     fragmentShader : fs,
   *     uniforms : {
   *         scale : 1.1,
   *         offset : function() {
   *             return new Cesium.Cartesian3(0.1, 0.2, 0.3);
   *         }
   *     }
   * }));
   *
   * @example
   * // Simple stage to change the color of what is selected.
   * // If czm_selected returns true, the current fragment belongs to geometry in the selected array.
   * const fs =`
   *     uniform sampler2D colorTexture;
   *     varying vec2 v_textureCoordinates;
   *     uniform vec4 highlight;
   *     void main() {
   *         vec4 color = texture2D(colorTexture, v_textureCoordinates);
   *         if (czm_selected()) {
   *             vec3 highlighted = highlight.a * highlight.rgb + (1.0 - highlight.a) * color.rgb;
   *             gl_FragColor = vec4(highlighted, 1.0);
   *         } else {
   *             gl_FragColor = color;
   *         }
   *     }`;
   * const stage = scene.postProcessStages.add(new Cesium.PostProcessStage({
   *     fragmentShader : fs,
   *     uniforms : {
   *         highlight : function() {
   *             return new Cesium.Color(1.0, 0.0, 0.0, 0.5);
   *         }
   *     }
   * }));
   * stage.selected = [cesium3DTileFeature];
   */
  function PostProcessStage(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const fragmentShader = options.fragmentShader;
    const textureScale = defaultValue(options.textureScale, 1.0);
    const pixelFormat = defaultValue(options.pixelFormat, PixelFormat$1.RGBA);

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("options.fragmentShader", fragmentShader);
    Check.typeOf.number.greaterThan("options.textureScale", textureScale, 0.0);
    Check.typeOf.number.lessThanOrEquals(
      "options.textureScale",
      textureScale,
      1.0
    );
    if (!PixelFormat$1.isColorFormat(pixelFormat)) {
      throw new DeveloperError("options.pixelFormat must be a color format.");
    }
    //>>includeEnd('debug');

    this._fragmentShader = fragmentShader;
    this._uniforms = options.uniforms;
    this._textureScale = textureScale;
    this._forcePowerOfTwo = defaultValue(options.forcePowerOfTwo, false);
    this._sampleMode = defaultValue(
      options.sampleMode,
      PostProcessStageSampleMode.NEAREST
    );
    this._pixelFormat = pixelFormat;
    this._pixelDatatype = defaultValue(
      options.pixelDatatype,
      PixelDatatype$1.UNSIGNED_BYTE
    );
    this._clearColor = defaultValue(options.clearColor, Color.BLACK);

    this._uniformMap = undefined;
    this._command = undefined;

    this._colorTexture = undefined;
    this._depthTexture = undefined;
    this._idTexture = undefined;

    this._actualUniforms = {};
    this._dirtyUniforms = [];
    this._texturesToRelease = [];
    this._texturesToCreate = [];
    this._texturePromise = undefined;

    const passState = new PassState();
    passState.scissorTest = {
      enabled: true,
      rectangle: defined(options.scissorRectangle)
        ? BoundingRectangle.clone(options.scissorRectangle)
        : new BoundingRectangle(),
    };
    this._passState = passState;

    this._ready = false;

    let name = options.name;
    if (!defined(name)) {
      name = createGuid();
    }
    this._name = name;

    this._logDepthChanged = undefined;
    this._useLogDepth = undefined;

    this._selectedIdTexture = undefined;
    this._selected = undefined;
    this._selectedShadow = undefined;
    this._parentSelected = undefined;
    this._parentSelectedShadow = undefined;
    this._combinedSelected = undefined;
    this._combinedSelectedShadow = undefined;
    this._selectedLength = 0;
    this._parentSelectedLength = 0;
    this._selectedDirty = true;

    // set by PostProcessStageCollection
    this._textureCache = undefined;
    this._index = undefined;

    /**
     * Whether or not to execute this post-process stage when ready.
     *
     * @type {Boolean}
     */
    this.enabled = true;
    this._enabled = true;
  }

  Object.defineProperties(PostProcessStage.prototype, {
    /**
     * Determines if this post-process stage is ready to be executed. A stage is only executed when both <code>ready</code>
     * and {@link PostProcessStage#enabled} are <code>true</code>. A stage will not be ready while it is waiting on textures
     * to load.
     *
     * @memberof PostProcessStage.prototype
     * @type {Boolean}
     * @readonly
     */
    ready: {
      get: function () {
        return this._ready;
      },
    },
    /**
     * The unique name of this post-process stage for reference by other stages in a {@link PostProcessStageComposite}.
     *
     * @memberof PostProcessStage.prototype
     * @type {String}
     * @readonly
     */
    name: {
      get: function () {
        return this._name;
      },
    },
    /**
     * The fragment shader to use when execute this post-process stage.
     * <p>
     * The shader must contain a sampler uniform declaration for <code>colorTexture</code>, <code>depthTexture</code>,
     * or both.
     * </p>
     * <p>
     * The shader must contain a <code>vec2</code> varying declaration for <code>v_textureCoordinates</code> for sampling
     * the texture uniforms.
     * </p>
     *
     * @memberof PostProcessStage.prototype
     * @type {String}
     * @readonly
     */
    fragmentShader: {
      get: function () {
        return this._fragmentShader;
      },
    },
    /**
     * An object whose properties are used to set the uniforms of the fragment shader.
     * <p>
     * The object property values can be either a constant or a function. The function will be called
     * each frame before the post-process stage is executed.
     * </p>
     * <p>
     * A constant value can also be a URI to an image, a data URI, or an HTML element that can be used as a texture, such as HTMLImageElement or HTMLCanvasElement.
     * </p>
     * <p>
     * If this post-process stage is part of a {@link PostProcessStageComposite} that does not execute in series, the constant value can also be
     * the name of another stage in a composite. This will set the uniform to the output texture the stage with that name.
     * </p>
     *
     * @memberof PostProcessStage.prototype
     * @type {Object}
     * @readonly
     */
    uniforms: {
      get: function () {
        return this._uniforms;
      },
    },
    /**
     * A number in the range (0.0, 1.0] used to scale the output texture dimensions. A scale of 1.0 will render this post-process stage to a texture the size of the viewport.
     *
     * @memberof PostProcessStage.prototype
     * @type {Number}
     * @readonly
     */
    textureScale: {
      get: function () {
        return this._textureScale;
      },
    },
    /**
     * Whether or not to force the output texture dimensions to be both equal powers of two. The power of two will be the next power of two of the minimum of the dimensions.
     *
     * @memberof PostProcessStage.prototype
     * @type {Number}
     * @readonly
     */
    forcePowerOfTwo: {
      get: function () {
        return this._forcePowerOfTwo;
      },
    },
    /**
     * How to sample the input color texture.
     *
     * @memberof PostProcessStage.prototype
     * @type {PostProcessStageSampleMode}
     * @readonly
     */
    sampleMode: {
      get: function () {
        return this._sampleMode;
      },
    },
    /**
     * The color pixel format of the output texture.
     *
     * @memberof PostProcessStage.prototype
     * @type {PixelFormat}
     * @readonly
     */
    pixelFormat: {
      get: function () {
        return this._pixelFormat;
      },
    },
    /**
     * The pixel data type of the output texture.
     *
     * @memberof PostProcessStage.prototype
     * @type {PixelDatatype}
     * @readonly
     */
    pixelDatatype: {
      get: function () {
        return this._pixelDatatype;
      },
    },
    /**
     * The color to clear the output texture to.
     *
     * @memberof PostProcessStage.prototype
     * @type {Color}
     * @readonly
     */
    clearColor: {
      get: function () {
        return this._clearColor;
      },
    },
    /**
     * The {@link BoundingRectangle} to use for the scissor test. A default bounding rectangle will disable the scissor test.
     *
     * @memberof PostProcessStage.prototype
     * @type {BoundingRectangle}
     * @readonly
     */
    scissorRectangle: {
      get: function () {
        return this._passState.scissorTest.rectangle;
      },
    },
    /**
     * A reference to the texture written to when executing this post process stage.
     *
     * @memberof PostProcessStage.prototype
     * @type {Texture}
     * @readonly
     * @private
     */
    outputTexture: {
      get: function () {
        if (defined(this._textureCache)) {
          const framebuffer = this._textureCache.getFramebuffer(this._name);
          if (defined(framebuffer)) {
            return framebuffer.getColorTexture(0);
          }
        }
        return undefined;
      },
    },
    /**
     * The features selected for applying the post-process.
     * <p>
     * In the fragment shader, use <code>czm_selected</code> to determine whether or not to apply the post-process
     * stage to that fragment. For example:
     * <code>
     * if (czm_selected(v_textureCoordinates)) {
     *     // apply post-process stage
     * } else {
     *     gl_FragColor = texture2D(colorTexture, v_textureCoordinates);
     * }
     * </code>
     * </p>
     *
     * @memberof PostProcessStage.prototype
     * @type {Array}
     */
    selected: {
      get: function () {
        return this._selected;
      },
      set: function (value) {
        this._selected = value;
      },
    },
    /**
     * @private
     */
    parentSelected: {
      get: function () {
        return this._parentSelected;
      },
      set: function (value) {
        this._parentSelected = value;
      },
    },
  });

  const depthTextureRegex = /uniform\s+sampler2D\s+depthTexture/g;

  /**
   * @private
   */
  PostProcessStage.prototype._isSupported = function (context) {
    return !depthTextureRegex.test(this._fragmentShader) || context.depthTexture;
  };

  function getUniformValueGetterAndSetter(stage, uniforms, name) {
    const currentValue = uniforms[name];
    if (
      typeof currentValue === "string" ||
      currentValue instanceof HTMLCanvasElement ||
      currentValue instanceof HTMLImageElement ||
      currentValue instanceof HTMLVideoElement ||
      currentValue instanceof ImageData
    ) {
      stage._dirtyUniforms.push(name);
    }

    return {
      get: function () {
        return uniforms[name];
      },
      set: function (value) {
        const currentValue = uniforms[name];
        uniforms[name] = value;

        const actualUniforms = stage._actualUniforms;
        const actualValue = actualUniforms[name];
        if (
          defined(actualValue) &&
          actualValue !== currentValue &&
          actualValue instanceof Texture &&
          !defined(stage._textureCache.getStageByName(name))
        ) {
          stage._texturesToRelease.push(actualValue);
          delete actualUniforms[name];
          delete actualUniforms[`${name}Dimensions`];
        }

        if (currentValue instanceof Texture) {
          stage._texturesToRelease.push(currentValue);
        }

        if (
          typeof value === "string" ||
          value instanceof HTMLCanvasElement ||
          value instanceof HTMLImageElement ||
          value instanceof HTMLVideoElement ||
          value instanceof ImageData
        ) {
          stage._dirtyUniforms.push(name);
        } else {
          actualUniforms[name] = value;
        }
      },
    };
  }

  function getUniformMapFunction(stage, name) {
    return function () {
      const value = stage._actualUniforms[name];
      if (typeof value === "function") {
        return value();
      }
      return value;
    };
  }

  function getUniformMapDimensionsFunction(uniformMap, name) {
    return function () {
      const texture = uniformMap[name]();
      if (defined(texture)) {
        return texture.dimensions;
      }
      return undefined;
    };
  }

  function createUniformMap(stage) {
    if (defined(stage._uniformMap)) {
      return;
    }

    const uniformMap = {};
    const newUniforms = {};
    const uniforms = stage._uniforms;
    const actualUniforms = stage._actualUniforms;
    for (const name in uniforms) {
      if (uniforms.hasOwnProperty(name)) {
        if (typeof uniforms[name] !== "function") {
          uniformMap[name] = getUniformMapFunction(stage, name);
          newUniforms[name] = getUniformValueGetterAndSetter(
            stage,
            uniforms,
            name
          );
        } else {
          uniformMap[name] = uniforms[name];
          newUniforms[name] = uniforms[name];
        }

        actualUniforms[name] = uniforms[name];

        const value = uniformMap[name]();
        if (
          typeof value === "string" ||
          value instanceof Texture ||
          value instanceof HTMLImageElement ||
          value instanceof HTMLCanvasElement ||
          value instanceof HTMLVideoElement
        ) {
          uniformMap[`${name}Dimensions`] = getUniformMapDimensionsFunction(
            uniformMap,
            name
          );
        }
      }
    }

    stage._uniforms = {};
    Object.defineProperties(stage._uniforms, newUniforms);

    stage._uniformMap = combine$2(uniformMap, {
      colorTexture: function () {
        return stage._colorTexture;
      },
      colorTextureDimensions: function () {
        return stage._colorTexture.dimensions;
      },
      depthTexture: function () {
        return stage._depthTexture;
      },
      depthTextureDimensions: function () {
        return stage._depthTexture.dimensions;
      },
      czm_idTexture: function () {
        return stage._idTexture;
      },
      czm_selectedIdTexture: function () {
        return stage._selectedIdTexture;
      },
      czm_selectedIdTextureStep: function () {
        return 1.0 / stage._selectedIdTexture.width;
      },
    });
  }

  function createDrawCommand(stage, context) {
    if (
      defined(stage._command) &&
      !stage._logDepthChanged &&
      !stage._selectedDirty
    ) {
      return;
    }

    let fs = stage._fragmentShader;
    if (defined(stage._selectedIdTexture)) {
      const width = stage._selectedIdTexture.width;

      fs = fs.replace(/varying\s+vec2\s+v_textureCoordinates;/g, "");
      fs =
        `${
        "#define CZM_SELECTED_FEATURE \n" +
        "uniform sampler2D czm_idTexture; \n" +
        "uniform sampler2D czm_selectedIdTexture; \n" +
        "uniform float czm_selectedIdTextureStep; \n" +
        "varying vec2 v_textureCoordinates; \n" +
        "bool czm_selected(vec2 offset) \n" +
        "{ \n" +
        "    bool selected = false;\n" +
        "    vec4 id = texture2D(czm_idTexture, v_textureCoordinates + offset); \n" +
        "    for (int i = 0; i < "
      }${width}; ++i) \n` +
        `    { \n` +
        `        vec4 selectedId = texture2D(czm_selectedIdTexture, vec2((float(i) + 0.5) * czm_selectedIdTextureStep, 0.5)); \n` +
        `        if (all(equal(id, selectedId))) \n` +
        `        { \n` +
        `            return true; \n` +
        `        } \n` +
        `    } \n` +
        `    return false; \n` +
        `} \n\n` +
        `bool czm_selected() \n` +
        `{ \n` +
        `    return czm_selected(vec2(0.0)); \n` +
        `} \n\n${fs}`;
    }

    const fragmentShader = new ShaderSource({
      defines: [stage._useLogDepth ? "LOG_DEPTH" : ""],
      sources: [fs],
    });
    stage._command = context.createViewportQuadCommand(fragmentShader, {
      uniformMap: stage._uniformMap,
      owner: stage,
    });
  }

  function createSampler(stage) {
    const mode = stage._sampleMode;

    let minFilter;
    let magFilter;

    if (mode === PostProcessStageSampleMode.LINEAR) {
      minFilter = TextureMinificationFilter$1.LINEAR;
      magFilter = TextureMagnificationFilter$1.LINEAR;
    } else {
      minFilter = TextureMinificationFilter$1.NEAREST;
      magFilter = TextureMagnificationFilter$1.NEAREST;
    }

    const sampler = stage._sampler;
    if (
      !defined(sampler) ||
      sampler.minificationFilter !== minFilter ||
      sampler.magnificationFilter !== magFilter
    ) {
      stage._sampler = new Sampler({
        wrapS: TextureWrap$1.CLAMP_TO_EDGE,
        wrapT: TextureWrap$1.CLAMP_TO_EDGE,
        minificationFilter: minFilter,
        magnificationFilter: magFilter,
      });
    }
  }

  function createLoadImageFunction(stage, name) {
    return function (image) {
      stage._texturesToCreate.push({
        name: name,
        source: image,
      });
    };
  }

  function createStageOutputTextureFunction(stage, name) {
    return function () {
      return stage._textureCache.getOutputTexture(name);
    };
  }

  function updateUniformTextures(stage, context) {
    let i;
    let texture;
    let name;

    const texturesToRelease = stage._texturesToRelease;
    let length = texturesToRelease.length;
    for (i = 0; i < length; ++i) {
      texture = texturesToRelease[i];
      texture = texture && texture.destroy();
    }
    texturesToRelease.length = 0;

    const texturesToCreate = stage._texturesToCreate;
    length = texturesToCreate.length;
    for (i = 0; i < length; ++i) {
      const textureToCreate = texturesToCreate[i];
      name = textureToCreate.name;
      const source = textureToCreate.source;
      stage._actualUniforms[name] = new Texture({
        context: context,
        source: source,
      });
    }
    texturesToCreate.length = 0;

    const dirtyUniforms = stage._dirtyUniforms;
    if (dirtyUniforms.length === 0 && !defined(stage._texturePromise)) {
      stage._ready = true;
      return;
    }

    if (dirtyUniforms.length === 0 || defined(stage._texturePromise)) {
      return;
    }

    length = dirtyUniforms.length;
    const uniforms = stage._uniforms;
    const promises = [];
    for (i = 0; i < length; ++i) {
      name = dirtyUniforms[i];
      const stageNameUrlOrImage = uniforms[name];
      const stageWithName = stage._textureCache.getStageByName(
        stageNameUrlOrImage
      );
      if (defined(stageWithName)) {
        stage._actualUniforms[name] = createStageOutputTextureFunction(
          stage,
          stageNameUrlOrImage
        );
      } else if (typeof stageNameUrlOrImage === "string") {
        const resource = new Resource({
          url: stageNameUrlOrImage,
        });

        promises.push(
          resource.fetchImage().then(createLoadImageFunction(stage, name))
        );
      } else {
        stage._texturesToCreate.push({
          name: name,
          source: stageNameUrlOrImage,
        });
      }
    }

    dirtyUniforms.length = 0;

    if (promises.length > 0) {
      stage._ready = false;
      stage._texturePromise = Promise.all(promises).then(function () {
        stage._ready = true;
        stage._texturePromise = undefined;
      });
    } else {
      stage._ready = true;
    }
  }

  function releaseResources$1(stage) {
    if (defined(stage._command)) {
      stage._command.shaderProgram =
        stage._command.shaderProgram && stage._command.shaderProgram.destroy();
      stage._command = undefined;
    }

    stage._selectedIdTexture =
      stage._selectedIdTexture && stage._selectedIdTexture.destroy();

    const textureCache = stage._textureCache;
    if (!defined(textureCache)) {
      return;
    }

    const uniforms = stage._uniforms;
    const actualUniforms = stage._actualUniforms;
    for (const name in actualUniforms) {
      if (actualUniforms.hasOwnProperty(name)) {
        if (actualUniforms[name] instanceof Texture) {
          if (!defined(textureCache.getStageByName(uniforms[name]))) {
            actualUniforms[name].destroy();
          }
          stage._dirtyUniforms.push(name);
        }
      }
    }
  }

  function isSelectedTextureDirty$1(stage) {
    let length = defined(stage._selected) ? stage._selected.length : 0;
    const parentLength = defined(stage._parentSelected)
      ? stage._parentSelected
      : 0;
    let dirty =
      stage._selected !== stage._selectedShadow ||
      length !== stage._selectedLength;
    dirty =
      dirty ||
      stage._parentSelected !== stage._parentSelectedShadow ||
      parentLength !== stage._parentSelectedLength;

    if (defined(stage._selected) && defined(stage._parentSelected)) {
      stage._combinedSelected = stage._selected.concat(stage._parentSelected);
    } else if (defined(stage._parentSelected)) {
      stage._combinedSelected = stage._parentSelected;
    } else {
      stage._combinedSelected = stage._selected;
    }

    if (!dirty && defined(stage._combinedSelected)) {
      if (!defined(stage._combinedSelectedShadow)) {
        return true;
      }

      length = stage._combinedSelected.length;
      for (let i = 0; i < length; ++i) {
        if (stage._combinedSelected[i] !== stage._combinedSelectedShadow[i]) {
          return true;
        }
      }
    }
    return dirty;
  }

  function createSelectedTexture(stage, context) {
    if (!stage._selectedDirty) {
      return;
    }

    stage._selectedIdTexture =
      stage._selectedIdTexture && stage._selectedIdTexture.destroy();
    stage._selectedIdTexture = undefined;

    const features = stage._combinedSelected;
    if (!defined(features)) {
      return;
    }

    let i;
    let feature;

    let textureLength = 0;
    const length = features.length;
    for (i = 0; i < length; ++i) {
      feature = features[i];
      if (defined(feature.pickIds)) {
        textureLength += feature.pickIds.length;
      } else if (defined(feature.pickId)) {
        ++textureLength;
      }
    }

    if (length === 0 || textureLength === 0) {
      // max pick id is reserved
      const empty = new Uint8Array(4);
      empty[0] = 255;
      empty[1] = 255;
      empty[2] = 255;
      empty[3] = 255;

      stage._selectedIdTexture = new Texture({
        context: context,
        pixelFormat: PixelFormat$1.RGBA,
        pixelDatatype: PixelDatatype$1.UNSIGNED_BYTE,
        source: {
          arrayBufferView: empty,
          width: 1,
          height: 1,
        },
        sampler: Sampler.NEAREST,
      });
      return;
    }

    let pickColor;
    let offset = 0;
    const ids = new Uint8Array(textureLength * 4);
    for (i = 0; i < length; ++i) {
      feature = features[i];
      if (defined(feature.pickIds)) {
        const pickIds = feature.pickIds;
        const pickIdsLength = pickIds.length;
        for (let j = 0; j < pickIdsLength; ++j) {
          pickColor = pickIds[j].color;
          ids[offset] = Color.floatToByte(pickColor.red);
          ids[offset + 1] = Color.floatToByte(pickColor.green);
          ids[offset + 2] = Color.floatToByte(pickColor.blue);
          ids[offset + 3] = Color.floatToByte(pickColor.alpha);
          offset += 4;
        }
      } else if (defined(feature.pickId)) {
        pickColor = feature.pickId.color;
        ids[offset] = Color.floatToByte(pickColor.red);
        ids[offset + 1] = Color.floatToByte(pickColor.green);
        ids[offset + 2] = Color.floatToByte(pickColor.blue);
        ids[offset + 3] = Color.floatToByte(pickColor.alpha);
        offset += 4;
      }
    }

    stage._selectedIdTexture = new Texture({
      context: context,
      pixelFormat: PixelFormat$1.RGBA,
      pixelDatatype: PixelDatatype$1.UNSIGNED_BYTE,
      source: {
        arrayBufferView: ids,
        width: textureLength,
        height: 1,
      },
      sampler: Sampler.NEAREST,
    });
  }

  /**
   * A function that will be called before execute. Used to create WebGL resources and load any textures.
   * @param {Context} context The context.
   * @param {Boolean} useLogDepth Whether the scene uses a logarithmic depth buffer.
   * @private
   */
  PostProcessStage.prototype.update = function (context, useLogDepth) {
    if (this.enabled !== this._enabled && !this.enabled) {
      releaseResources$1(this);
    }

    this._enabled = this.enabled;
    if (!this._enabled) {
      return;
    }

    this._logDepthChanged = useLogDepth !== this._useLogDepth;
    this._useLogDepth = useLogDepth;

    this._selectedDirty = isSelectedTextureDirty$1(this);

    this._selectedShadow = this._selected;
    this._parentSelectedShadow = this._parentSelected;
    this._combinedSelectedShadow = this._combinedSelected;
    this._selectedLength = defined(this._selected) ? this._selected.length : 0;
    this._parentSelectedLength = defined(this._parentSelected)
      ? this._parentSelected.length
      : 0;

    createSelectedTexture(this, context);
    createUniformMap(this);
    updateUniformTextures(this, context);
    createDrawCommand(this, context);
    createSampler(this);

    this._selectedDirty = false;

    if (!this._ready) {
      return;
    }

    const framebuffer = this._textureCache.getFramebuffer(this._name);
    this._command.framebuffer = framebuffer;

    if (!defined(framebuffer)) {
      return;
    }

    const colorTexture = framebuffer.getColorTexture(0);
    let renderState;
    if (
      colorTexture.width !== context.drawingBufferWidth ||
      colorTexture.height !== context.drawingBufferHeight
    ) {
      renderState = this._renderState;
      if (
        !defined(renderState) ||
        colorTexture.width !== renderState.viewport.width ||
        colorTexture.height !== renderState.viewport.height
      ) {
        this._renderState = RenderState.fromCache({
          viewport: new BoundingRectangle(
            0,
            0,
            colorTexture.width,
            colorTexture.height
          ),
        });
      }
    }

    this._command.renderState = renderState;
  };

  /**
   * Executes the post-process stage. The color texture is the texture rendered to by the scene or from the previous stage.
   * @param {Context} context The context.
   * @param {Texture} colorTexture The input color texture.
   * @param {Texture} depthTexture The input depth texture.
   * @param {Texture} idTexture The id texture.
   * @private
   */
  PostProcessStage.prototype.execute = function (
    context,
    colorTexture,
    depthTexture,
    idTexture
  ) {
    if (
      !defined(this._command) ||
      !defined(this._command.framebuffer) ||
      !this._ready ||
      !this._enabled
    ) {
      return;
    }

    this._colorTexture = colorTexture;
    this._depthTexture = depthTexture;
    this._idTexture = idTexture;

    if (!Sampler.equals(this._colorTexture.sampler, this._sampler)) {
      this._colorTexture.sampler = this._sampler;
    }

    const passState =
      this.scissorRectangle.width > 0 && this.scissorRectangle.height > 0
        ? this._passState
        : undefined;
    if (defined(passState)) {
      passState.context = context;
    }

    this._command.execute(context, passState);
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <p>
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   * </p>
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see PostProcessStage#destroy
   */
  PostProcessStage.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <p>
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   * </p>
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @see PostProcessStage#isDestroyed
   */
  PostProcessStage.prototype.destroy = function () {
    releaseResources$1(this);
    return destroyObject(this);
  };

  //This file is automatically rebuilt by the Cesium build process.
  var AcesTonemapping = "uniform sampler2D colorTexture;\n\
varying vec2 v_textureCoordinates;\n\
#ifdef AUTO_EXPOSURE\n\
uniform sampler2D autoExposure;\n\
#endif\n\
void main()\n\
{\n\
vec4 fragmentColor = texture2D(colorTexture, v_textureCoordinates);\n\
vec3 color = fragmentColor.rgb;\n\
#ifdef AUTO_EXPOSURE\n\
color /= texture2D(autoExposure, vec2(0.5)).r;\n\
#endif\n\
color = czm_acesTonemapping(color);\n\
color = czm_inverseGamma(color);\n\
gl_FragColor = vec4(color, fragmentColor.a);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var AmbientOcclusionGenerate = "uniform sampler2D randomTexture;\n\
uniform sampler2D depthTexture;\n\
uniform float intensity;\n\
uniform float bias;\n\
uniform float lengthCap;\n\
uniform float stepSize;\n\
uniform float frustumLength;\n\
varying vec2 v_textureCoordinates;\n\
vec4 clipToEye(vec2 uv, float depth)\n\
{\n\
vec2 xy = vec2((uv.x * 2.0 - 1.0), ((1.0 - uv.y) * 2.0 - 1.0));\n\
vec4 posEC = czm_inverseProjection * vec4(xy, depth, 1.0);\n\
posEC = posEC / posEC.w;\n\
return posEC;\n\
}\n\
vec3 getNormalXEdge(vec3 posInCamera, float depthU, float depthD, float depthL, float depthR, vec2 pixelSize)\n\
{\n\
vec4 posInCameraUp = clipToEye(v_textureCoordinates - vec2(0.0, pixelSize.y), depthU);\n\
vec4 posInCameraDown = clipToEye(v_textureCoordinates + vec2(0.0, pixelSize.y), depthD);\n\
vec4 posInCameraLeft = clipToEye(v_textureCoordinates - vec2(pixelSize.x, 0.0), depthL);\n\
vec4 posInCameraRight = clipToEye(v_textureCoordinates + vec2(pixelSize.x, 0.0), depthR);\n\
vec3 up = posInCamera.xyz - posInCameraUp.xyz;\n\
vec3 down = posInCameraDown.xyz - posInCamera.xyz;\n\
vec3 left = posInCamera.xyz - posInCameraLeft.xyz;\n\
vec3 right = posInCameraRight.xyz - posInCamera.xyz;\n\
vec3 DX = length(left) < length(right) ? left : right;\n\
vec3 DY = length(up) < length(down) ? up : down;\n\
return normalize(cross(DY, DX));\n\
}\n\
void main(void)\n\
{\n\
float depth = czm_readDepth(depthTexture, v_textureCoordinates);\n\
vec4 posInCamera = clipToEye(v_textureCoordinates, depth);\n\
if (posInCamera.z > frustumLength)\n\
{\n\
gl_FragColor = vec4(1.0);\n\
return;\n\
}\n\
vec2 pixelSize = czm_pixelRatio / czm_viewport.zw;\n\
float depthU = czm_readDepth(depthTexture, v_textureCoordinates - vec2(0.0, pixelSize.y));\n\
float depthD = czm_readDepth(depthTexture, v_textureCoordinates + vec2(0.0, pixelSize.y));\n\
float depthL = czm_readDepth(depthTexture, v_textureCoordinates - vec2(pixelSize.x, 0.0));\n\
float depthR = czm_readDepth(depthTexture, v_textureCoordinates + vec2(pixelSize.x, 0.0));\n\
vec3 normalInCamera = getNormalXEdge(posInCamera.xyz, depthU, depthD, depthL, depthR, pixelSize);\n\
float ao = 0.0;\n\
vec2 sampleDirection = vec2(1.0, 0.0);\n\
float gapAngle = 90.0 * czm_radiansPerDegree;\n\
float randomVal = texture2D(randomTexture, v_textureCoordinates).x;\n\
for (int i = 0; i < 4; i++)\n\
{\n\
float newGapAngle = gapAngle * (float(i) + randomVal);\n\
float cosVal = cos(newGapAngle);\n\
float sinVal = sin(newGapAngle);\n\
vec2 rotatedSampleDirection = vec2(cosVal * sampleDirection.x - sinVal * sampleDirection.y, sinVal * sampleDirection.x + cosVal * sampleDirection.y);\n\
float localAO = 0.0;\n\
float localStepSize = stepSize;\n\
for (int j = 0; j < 6; j++)\n\
{\n\
vec2 newCoords = v_textureCoordinates + rotatedSampleDirection * localStepSize * pixelSize;\n\
if(newCoords.x > 1.0 || newCoords.y > 1.0 || newCoords.x < 0.0 || newCoords.y < 0.0)\n\
{\n\
break;\n\
}\n\
float stepDepthInfo = czm_readDepth(depthTexture, newCoords);\n\
vec4 stepPosInCamera = clipToEye(newCoords, stepDepthInfo);\n\
vec3 diffVec = stepPosInCamera.xyz - posInCamera.xyz;\n\
float len = length(diffVec);\n\
if (len > lengthCap)\n\
{\n\
break;\n\
}\n\
float dotVal = clamp(dot(normalInCamera, normalize(diffVec)), 0.0, 1.0 );\n\
float weight = len / lengthCap;\n\
weight = 1.0 - weight * weight;\n\
if (dotVal < bias)\n\
{\n\
dotVal = 0.0;\n\
}\n\
localAO = max(localAO, dotVal * weight);\n\
localStepSize += stepSize;\n\
}\n\
ao += localAO;\n\
}\n\
ao /= 4.0;\n\
ao = 1.0 - clamp(ao, 0.0, 1.0);\n\
ao = pow(ao, intensity);\n\
gl_FragColor = vec4(vec3(ao), 1.0);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var AmbientOcclusionModulate = "uniform sampler2D colorTexture;\n\
uniform sampler2D ambientOcclusionTexture;\n\
uniform bool ambientOcclusionOnly;\n\
varying vec2 v_textureCoordinates;\n\
void main(void)\n\
{\n\
vec3 color = texture2D(colorTexture, v_textureCoordinates).rgb;\n\
vec3 ao = texture2D(ambientOcclusionTexture, v_textureCoordinates).rgb;\n\
gl_FragColor.rgb = ambientOcclusionOnly ? ao : ao * color;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var BlackAndWhite = "uniform sampler2D colorTexture;\n\
uniform float gradations;\n\
varying vec2 v_textureCoordinates;\n\
void main(void)\n\
{\n\
vec3 rgb = texture2D(colorTexture, v_textureCoordinates).rgb;\n\
#ifdef CZM_SELECTED_FEATURE\n\
if (czm_selected()) {\n\
gl_FragColor = vec4(rgb, 1.0);\n\
return;\n\
}\n\
#endif\n\
float luminance = czm_luminance(rgb);\n\
float darkness = luminance * gradations;\n\
darkness = (darkness - fract(darkness)) / gradations;\n\
gl_FragColor = vec4(vec3(darkness), 1.0);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var BloomComposite = "uniform sampler2D colorTexture;\n\
uniform sampler2D bloomTexture;\n\
uniform bool glowOnly;\n\
varying vec2 v_textureCoordinates;\n\
void main(void)\n\
{\n\
vec4 color = texture2D(colorTexture, v_textureCoordinates);\n\
#ifdef CZM_SELECTED_FEATURE\n\
if (czm_selected()) {\n\
gl_FragColor = color;\n\
return;\n\
}\n\
#endif\n\
vec4 bloom = texture2D(bloomTexture, v_textureCoordinates);\n\
gl_FragColor = glowOnly ? bloom : bloom + color;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var Brightness = "uniform sampler2D colorTexture;\n\
uniform float brightness;\n\
varying vec2 v_textureCoordinates;\n\
void main(void)\n\
{\n\
vec3 rgb = texture2D(colorTexture, v_textureCoordinates).rgb;\n\
vec3 target = vec3(0.0);\n\
gl_FragColor = vec4(mix(target, rgb, brightness), 1.0);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var ContrastBias = "uniform sampler2D colorTexture;\n\
uniform float contrast;\n\
uniform float brightness;\n\
varying vec2 v_textureCoordinates;\n\
void main(void)\n\
{\n\
vec3 sceneColor = texture2D(colorTexture, v_textureCoordinates).xyz;\n\
sceneColor = czm_RGBToHSB(sceneColor);\n\
sceneColor.z += brightness;\n\
sceneColor = czm_HSBToRGB(sceneColor);\n\
float factor = (259.0 * (contrast + 255.0)) / (255.0 * (259.0 - contrast));\n\
sceneColor = factor * (sceneColor - vec3(0.5)) + vec3(0.5);\n\
gl_FragColor = vec4(sceneColor, 1.0);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var DepthOfField = "uniform sampler2D colorTexture;\n\
uniform sampler2D blurTexture;\n\
uniform sampler2D depthTexture;\n\
uniform float focalDistance;\n\
varying vec2 v_textureCoordinates;\n\
vec4 toEye(vec2 uv, float depth)\n\
{\n\
vec2 xy = vec2((uv.x * 2.0 - 1.0), ((1.0 - uv.y) * 2.0 - 1.0));\n\
vec4 posInCamera = czm_inverseProjection * vec4(xy, depth, 1.0);\n\
posInCamera = posInCamera / posInCamera.w;\n\
return posInCamera;\n\
}\n\
float computeDepthBlur(float depth)\n\
{\n\
float f;\n\
if (depth < focalDistance)\n\
{\n\
f = (focalDistance - depth) / (focalDistance - czm_currentFrustum.x);\n\
}\n\
else\n\
{\n\
f = (depth - focalDistance) / (czm_currentFrustum.y - focalDistance);\n\
f = pow(f, 0.1);\n\
}\n\
f *= f;\n\
f = clamp(f, 0.0, 1.0);\n\
return pow(f, 0.5);\n\
}\n\
void main(void)\n\
{\n\
float depth = czm_readDepth(depthTexture, v_textureCoordinates);\n\
vec4 posInCamera = toEye(v_textureCoordinates, depth);\n\
float d = computeDepthBlur(-posInCamera.z);\n\
gl_FragColor = mix(texture2D(colorTexture, v_textureCoordinates), texture2D(blurTexture, v_textureCoordinates), d);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var DepthView = "uniform sampler2D depthTexture;\n\
varying vec2 v_textureCoordinates;\n\
void main(void)\n\
{\n\
float depth = czm_readDepth(depthTexture, v_textureCoordinates);\n\
gl_FragColor = vec4(vec3(depth), 1.0);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var EdgeDetection = "uniform sampler2D depthTexture;\n\
uniform float length;\n\
uniform vec4 color;\n\
varying vec2 v_textureCoordinates;\n\
void main(void)\n\
{\n\
float directions[3];\n\
directions[0] = -1.0;\n\
directions[1] = 0.0;\n\
directions[2] = 1.0;\n\
float scalars[3];\n\
scalars[0] = 3.0;\n\
scalars[1] = 10.0;\n\
scalars[2] = 3.0;\n\
float padx = czm_pixelRatio / czm_viewport.z;\n\
float pady = czm_pixelRatio / czm_viewport.w;\n\
#ifdef CZM_SELECTED_FEATURE\n\
bool selected = false;\n\
for (int i = 0; i < 3; ++i)\n\
{\n\
float dir = directions[i];\n\
selected = selected || czm_selected(vec2(-padx, dir * pady));\n\
selected = selected || czm_selected(vec2(padx, dir * pady));\n\
selected = selected || czm_selected(vec2(dir * padx, -pady));\n\
selected = selected || czm_selected(vec2(dir * padx, pady));\n\
if (selected)\n\
{\n\
break;\n\
}\n\
}\n\
if (!selected)\n\
{\n\
gl_FragColor = vec4(color.rgb, 0.0);\n\
return;\n\
}\n\
#endif\n\
float horizEdge = 0.0;\n\
float vertEdge = 0.0;\n\
for (int i = 0; i < 3; ++i)\n\
{\n\
float dir = directions[i];\n\
float scale = scalars[i];\n\
horizEdge -= texture2D(depthTexture, v_textureCoordinates + vec2(-padx, dir * pady)).x * scale;\n\
horizEdge += texture2D(depthTexture, v_textureCoordinates + vec2(padx, dir * pady)).x * scale;\n\
vertEdge -= texture2D(depthTexture, v_textureCoordinates + vec2(dir * padx, -pady)).x * scale;\n\
vertEdge += texture2D(depthTexture, v_textureCoordinates + vec2(dir * padx, pady)).x * scale;\n\
}\n\
float len = sqrt(horizEdge * horizEdge + vertEdge * vertEdge);\n\
gl_FragColor = vec4(color.rgb, len > length ? color.a : 0.0);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var FilmicTonemapping = "uniform sampler2D colorTexture;\n\
varying vec2 v_textureCoordinates;\n\
#ifdef AUTO_EXPOSURE\n\
uniform sampler2D autoExposure;\n\
#endif\n\
void main()\n\
{\n\
vec4 fragmentColor = texture2D(colorTexture, v_textureCoordinates);\n\
vec3 color = fragmentColor.rgb;\n\
#ifdef AUTO_EXPOSURE\n\
float exposure = texture2D(autoExposure, vec2(0.5)).r;\n\
color /= exposure;\n\
#endif\n\
const float A = 0.22;\n\
const float B = 0.30;\n\
const float C = 0.10;\n\
const float D = 0.20;\n\
const float E = 0.01;\n\
const float F = 0.30;\n\
const float white = 11.2;\n\
vec3 c = ((color * (A * color + C * B) + D * E) / (color * ( A * color + B) + D * F)) - E / F;\n\
float w = ((white * (A * white + C * B) + D * E) / (white * ( A * white + B) + D * F)) - E / F;\n\
c = czm_inverseGamma(c / w);\n\
gl_FragColor = vec4(c, fragmentColor.a);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var FXAA = "varying vec2 v_textureCoordinates;\n\
uniform sampler2D colorTexture;\n\
const float fxaaQualitySubpix = 0.5;\n\
const float fxaaQualityEdgeThreshold = 0.125;\n\
const float fxaaQualityEdgeThresholdMin = 0.0833;\n\
void main()\n\
{\n\
vec2 fxaaQualityRcpFrame = vec2(1.0) / czm_viewport.zw;\n\
vec4 color = FxaaPixelShader(\n\
v_textureCoordinates,\n\
colorTexture,\n\
fxaaQualityRcpFrame,\n\
fxaaQualitySubpix,\n\
fxaaQualityEdgeThreshold,\n\
fxaaQualityEdgeThresholdMin);\n\
float alpha = texture2D(colorTexture, v_textureCoordinates).a;\n\
gl_FragColor = vec4(color.rgb, alpha);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var GaussianBlur1D = "#define SAMPLES 8\n\
uniform float delta;\n\
uniform float sigma;\n\
uniform float direction;\n\
uniform sampler2D colorTexture;\n\
#ifdef USE_STEP_SIZE\n\
uniform float stepSize;\n\
#else\n\
uniform vec2 step;\n\
#endif\n\
varying vec2 v_textureCoordinates;\n\
void main()\n\
{\n\
vec2 st = v_textureCoordinates;\n\
vec2 dir = vec2(1.0 - direction, direction);\n\
#ifdef USE_STEP_SIZE\n\
vec2 step = vec2(stepSize * (czm_pixelRatio / czm_viewport.zw));\n\
#else\n\
vec2 step = step;\n\
#endif\n\
vec3 g;\n\
g.x = 1.0 / (sqrt(czm_twoPi) * sigma);\n\
g.y = exp((-0.5 * delta * delta) / (sigma * sigma));\n\
g.z = g.y * g.y;\n\
vec4 result = texture2D(colorTexture, st) * g.x;\n\
for (int i = 1; i < SAMPLES; ++i)\n\
{\n\
g.xy *= g.yz;\n\
vec2 offset = float(i) * dir * step;\n\
result += texture2D(colorTexture, st - offset) * g.x;\n\
result += texture2D(colorTexture, st + offset) * g.x;\n\
}\n\
gl_FragColor = result;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var LensFlare = "uniform sampler2D colorTexture;\n\
uniform sampler2D dirtTexture;\n\
uniform sampler2D starTexture;\n\
uniform vec2 dirtTextureDimensions;\n\
uniform float distortion;\n\
uniform float ghostDispersal;\n\
uniform float haloWidth;\n\
uniform float dirtAmount;\n\
uniform float earthRadius;\n\
uniform float intensity;\n\
varying vec2 v_textureCoordinates;\n\
#define DISTANCE_TO_SPACE 6500000.0\n\
vec4 getNDCFromWC(vec3 WC, float earthRadius)\n\
{\n\
vec4 positionEC = czm_view * vec4(WC, 1.0);\n\
positionEC = vec4(positionEC.x + earthRadius, positionEC.y, positionEC.z, 1.0);\n\
vec4 positionWC = czm_eyeToWindowCoordinates(positionEC);\n\
return czm_viewportOrthographic * vec4(positionWC.xy, -positionWC.z, 1.0);\n\
}\n\
float isInEarth(vec2 texcoord, vec2 sceneSize)\n\
{\n\
vec2 NDC = texcoord * 2.0 - 1.0;\n\
vec4 earthPosSC = getNDCFromWC(vec3(0.0), 0.0);\n\
vec4 earthPosSCEdge = getNDCFromWC(vec3(0.0), earthRadius * 1.5);\n\
NDC.xy -= earthPosSC.xy;\n\
float X = abs(NDC.x) * sceneSize.x;\n\
float Y = abs(NDC.y) * sceneSize.y;\n\
return clamp(0.0, 1.0, max(sqrt(X * X + Y * Y) / max(abs(earthPosSCEdge.x * sceneSize.x), 1.0) - 0.8 , 0.0));\n\
}\n\
vec4 textureDistorted(sampler2D tex, vec2 texcoord, vec2 direction, vec3 distortion, bool isSpace)\n\
{\n\
vec2 sceneSize = czm_viewport.zw;\n\
vec3 color;\n\
if(isSpace)\n\
{\n\
color.r = isInEarth(texcoord + direction * distortion.r, sceneSize) * texture2D(tex, texcoord + direction * distortion.r).r;\n\
color.g = isInEarth(texcoord + direction * distortion.g, sceneSize) * texture2D(tex, texcoord + direction * distortion.g).g;\n\
color.b = isInEarth(texcoord + direction * distortion.b, sceneSize) * texture2D(tex, texcoord + direction * distortion.b).b;\n\
}\n\
else\n\
{\n\
color.r = texture2D(tex, texcoord + direction * distortion.r).r;\n\
color.g = texture2D(tex, texcoord + direction * distortion.g).g;\n\
color.b = texture2D(tex, texcoord + direction * distortion.b).b;\n\
}\n\
return vec4(clamp(color, 0.0, 1.0), 0.0);\n\
}\n\
void main(void)\n\
{\n\
vec4 originalColor = texture2D(colorTexture, v_textureCoordinates);\n\
vec3 rgb = originalColor.rgb;\n\
bool isSpace = length(czm_viewerPositionWC.xyz) > DISTANCE_TO_SPACE;\n\
vec4 sunPos = czm_morphTime == 1.0 ? vec4(czm_sunPositionWC, 1.0) : vec4(czm_sunPositionColumbusView.zxy, 1.0);\n\
vec4 sunPositionEC = czm_view * sunPos;\n\
vec4 sunPositionWC = czm_eyeToWindowCoordinates(sunPositionEC);\n\
sunPos = czm_viewportOrthographic * vec4(sunPositionWC.xy, -sunPositionWC.z, 1.0);\n\
if(!isSpace || !((sunPos.x >= -1.1 && sunPos.x <= 1.1) && (sunPos.y >= -1.1 && sunPos.y <= 1.1)))\n\
{\n\
gl_FragColor = originalColor;\n\
return;\n\
}\n\
vec2 texcoord = vec2(1.0) - v_textureCoordinates;\n\
vec2 pixelSize = czm_pixelRatio / czm_viewport.zw;\n\
vec2 invPixelSize = 1.0 / pixelSize;\n\
vec3 distortionVec = pixelSize.x * vec3(-distortion, 0.0, distortion);\n\
vec2 ghostVec = (vec2(0.5) - texcoord) * ghostDispersal;\n\
vec3 direction = normalize(vec3(ghostVec, 0.0));\n\
vec4 result = vec4(0.0);\n\
vec4 ghost = vec4(0.0);\n\
for (int i = 0; i < 4; ++i)\n\
{\n\
vec2 offset = fract(texcoord + ghostVec * float(i));\n\
ghost += textureDistorted(colorTexture, offset, direction.xy, distortionVec, isSpace);\n\
}\n\
result += ghost;\n\
vec2 haloVec = normalize(ghostVec) * haloWidth;\n\
float weightForHalo = length(vec2(0.5) - fract(texcoord + haloVec)) / length(vec2(0.5));\n\
weightForHalo = pow(1.0 - weightForHalo, 5.0);\n\
result += textureDistorted(colorTexture, texcoord + haloVec, direction.xy, distortionVec, isSpace) * weightForHalo * 1.5;\n\
vec2 dirtTexCoords = (v_textureCoordinates * invPixelSize) / dirtTextureDimensions;\n\
if (dirtTexCoords.x > 1.0)\n\
{\n\
dirtTexCoords.x = mod(floor(dirtTexCoords.x), 2.0) == 1.0 ? 1.0 - fract(dirtTexCoords.x) :  fract(dirtTexCoords.x);\n\
}\n\
if (dirtTexCoords.y > 1.0)\n\
{\n\
dirtTexCoords.y = mod(floor(dirtTexCoords.y), 2.0) == 1.0 ? 1.0 - fract(dirtTexCoords.y) :  fract(dirtTexCoords.y);\n\
}\n\
result += dirtAmount * texture2D(dirtTexture, dirtTexCoords);\n\
float camrot = czm_view[0].z + czm_view[1].y;\n\
float cosValue = cos(camrot);\n\
float sinValue = sin(camrot);\n\
mat3 rotation = mat3(\n\
cosValue, -sinValue, 0.0,\n\
sinValue, cosValue, 0.0,\n\
0.0, 0.0, 1.0\n\
);\n\
vec3 st1 = vec3(v_textureCoordinates * 2.0 - vec2(1.0), 1.0);\n\
vec3 st2 = vec3((rotation * st1).xy, 1.0);\n\
vec3 st3 = st2 * 0.5 + vec3(0.5);\n\
vec2 lensStarTexcoord = st3.xy;\n\
float weightForLensFlare = length(vec3(sunPos.xy, 0.0));\n\
float oneMinusWeightForLensFlare = max(1.0 - weightForLensFlare, 0.0);\n\
if (!isSpace)\n\
{\n\
result *= oneMinusWeightForLensFlare * intensity * 0.2;\n\
}\n\
else\n\
{\n\
result *= oneMinusWeightForLensFlare * intensity;\n\
result *= texture2D(starTexture, lensStarTexcoord) * pow(weightForLensFlare, 1.0) * max((1.0 - length(vec3(st1.xy, 0.0))), 0.0) * 2.0;\n\
}\n\
result += texture2D(colorTexture, v_textureCoordinates);\n\
gl_FragColor = result;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var ModifiedReinhardTonemapping = "uniform sampler2D colorTexture;\n\
uniform vec3 white;\n\
varying vec2 v_textureCoordinates;\n\
#ifdef AUTO_EXPOSURE\n\
uniform sampler2D autoExposure;\n\
#endif\n\
void main()\n\
{\n\
vec4 fragmentColor = texture2D(colorTexture, v_textureCoordinates);\n\
vec3 color = fragmentColor.rgb;\n\
#ifdef AUTO_EXPOSURE\n\
float exposure = texture2D(autoExposure, vec2(0.5)).r;\n\
color /= exposure;\n\
#endif\n\
color = (color * (1.0 + color / white)) / (1.0 + color);\n\
color = czm_inverseGamma(color);\n\
gl_FragColor = vec4(color, fragmentColor.a);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var NightVision = "uniform sampler2D colorTexture;\n\
varying vec2 v_textureCoordinates;\n\
float rand(vec2 co)\n\
{\n\
return fract(sin(dot(co.xy ,vec2(12.9898, 78.233))) * 43758.5453);\n\
}\n\
void main(void)\n\
{\n\
float noiseValue = rand(v_textureCoordinates + sin(czm_frameNumber)) * 0.1;\n\
vec3 rgb = texture2D(colorTexture, v_textureCoordinates).rgb;\n\
vec3 green = vec3(0.0, 1.0, 0.0);\n\
gl_FragColor = vec4((noiseValue + rgb) * green, 1.0);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var ReinhardTonemapping = "uniform sampler2D colorTexture;\n\
varying vec2 v_textureCoordinates;\n\
#ifdef AUTO_EXPOSURE\n\
uniform sampler2D autoExposure;\n\
#endif\n\
void main()\n\
{\n\
vec4 fragmentColor = texture2D(colorTexture, v_textureCoordinates);\n\
vec3 color = fragmentColor.rgb;\n\
#ifdef AUTO_EXPOSURE\n\
float exposure = texture2D(autoExposure, vec2(0.5)).r;\n\
color /= exposure;\n\
#endif\n\
color = color / (1.0 + color);\n\
color = czm_inverseGamma(color);\n\
gl_FragColor = vec4(color, fragmentColor.a);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var Silhouette = "uniform sampler2D colorTexture;\n\
uniform sampler2D silhouetteTexture;\n\
varying vec2 v_textureCoordinates;\n\
void main(void)\n\
{\n\
vec4 silhouetteColor = texture2D(silhouetteTexture, v_textureCoordinates);\n\
vec4 color = texture2D(colorTexture, v_textureCoordinates);\n\
gl_FragColor = mix(color, silhouetteColor, silhouetteColor.a);\n\
}\n\
";

  /**
   * @license
   * Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *  * Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *  * Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in the
   *    documentation and/or other materials provided with the distribution.
   *  * Neither the name of NVIDIA CORPORATION nor the names of its
   *    contributors may be used to endorse or promote products derived
   *    from this software without specific prior written permission.
   *
   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
   * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
   * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
   * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   */
  //This file is automatically rebuilt by the Cesium build process.
  var FXAA3_11 = "#if (FXAA_QUALITY_PRESET == 10)\n\
#define FXAA_QUALITY_PS 3\n\
#define FXAA_QUALITY_P0 1.5\n\
#define FXAA_QUALITY_P1 3.0\n\
#define FXAA_QUALITY_P2 12.0\n\
#endif\n\
#if (FXAA_QUALITY_PRESET == 11)\n\
#define FXAA_QUALITY_PS 4\n\
#define FXAA_QUALITY_P0 1.0\n\
#define FXAA_QUALITY_P1 1.5\n\
#define FXAA_QUALITY_P2 3.0\n\
#define FXAA_QUALITY_P3 12.0\n\
#endif\n\
#if (FXAA_QUALITY_PRESET == 12)\n\
#define FXAA_QUALITY_PS 5\n\
#define FXAA_QUALITY_P0 1.0\n\
#define FXAA_QUALITY_P1 1.5\n\
#define FXAA_QUALITY_P2 2.0\n\
#define FXAA_QUALITY_P3 4.0\n\
#define FXAA_QUALITY_P4 12.0\n\
#endif\n\
#if (FXAA_QUALITY_PRESET == 13)\n\
#define FXAA_QUALITY_PS 6\n\
#define FXAA_QUALITY_P0 1.0\n\
#define FXAA_QUALITY_P1 1.5\n\
#define FXAA_QUALITY_P2 2.0\n\
#define FXAA_QUALITY_P3 2.0\n\
#define FXAA_QUALITY_P4 4.0\n\
#define FXAA_QUALITY_P5 12.0\n\
#endif\n\
#if (FXAA_QUALITY_PRESET == 14)\n\
#define FXAA_QUALITY_PS 7\n\
#define FXAA_QUALITY_P0 1.0\n\
#define FXAA_QUALITY_P1 1.5\n\
#define FXAA_QUALITY_P2 2.0\n\
#define FXAA_QUALITY_P3 2.0\n\
#define FXAA_QUALITY_P4 2.0\n\
#define FXAA_QUALITY_P5 4.0\n\
#define FXAA_QUALITY_P6 12.0\n\
#endif\n\
#if (FXAA_QUALITY_PRESET == 15)\n\
#define FXAA_QUALITY_PS 8\n\
#define FXAA_QUALITY_P0 1.0\n\
#define FXAA_QUALITY_P1 1.5\n\
#define FXAA_QUALITY_P2 2.0\n\
#define FXAA_QUALITY_P3 2.0\n\
#define FXAA_QUALITY_P4 2.0\n\
#define FXAA_QUALITY_P5 2.0\n\
#define FXAA_QUALITY_P6 4.0\n\
#define FXAA_QUALITY_P7 12.0\n\
#endif\n\
#if (FXAA_QUALITY_PRESET == 20)\n\
#define FXAA_QUALITY_PS 3\n\
#define FXAA_QUALITY_P0 1.5\n\
#define FXAA_QUALITY_P1 2.0\n\
#define FXAA_QUALITY_P2 8.0\n\
#endif\n\
#if (FXAA_QUALITY_PRESET == 21)\n\
#define FXAA_QUALITY_PS 4\n\
#define FXAA_QUALITY_P0 1.0\n\
#define FXAA_QUALITY_P1 1.5\n\
#define FXAA_QUALITY_P2 2.0\n\
#define FXAA_QUALITY_P3 8.0\n\
#endif\n\
#if (FXAA_QUALITY_PRESET == 22)\n\
#define FXAA_QUALITY_PS 5\n\
#define FXAA_QUALITY_P0 1.0\n\
#define FXAA_QUALITY_P1 1.5\n\
#define FXAA_QUALITY_P2 2.0\n\
#define FXAA_QUALITY_P3 2.0\n\
#define FXAA_QUALITY_P4 8.0\n\
#endif\n\
#if (FXAA_QUALITY_PRESET == 23)\n\
#define FXAA_QUALITY_PS 6\n\
#define FXAA_QUALITY_P0 1.0\n\
#define FXAA_QUALITY_P1 1.5\n\
#define FXAA_QUALITY_P2 2.0\n\
#define FXAA_QUALITY_P3 2.0\n\
#define FXAA_QUALITY_P4 2.0\n\
#define FXAA_QUALITY_P5 8.0\n\
#endif\n\
#if (FXAA_QUALITY_PRESET == 24)\n\
#define FXAA_QUALITY_PS 7\n\
#define FXAA_QUALITY_P0 1.0\n\
#define FXAA_QUALITY_P1 1.5\n\
#define FXAA_QUALITY_P2 2.0\n\
#define FXAA_QUALITY_P3 2.0\n\
#define FXAA_QUALITY_P4 2.0\n\
#define FXAA_QUALITY_P5 3.0\n\
#define FXAA_QUALITY_P6 8.0\n\
#endif\n\
#if (FXAA_QUALITY_PRESET == 25)\n\
#define FXAA_QUALITY_PS 8\n\
#define FXAA_QUALITY_P0 1.0\n\
#define FXAA_QUALITY_P1 1.5\n\
#define FXAA_QUALITY_P2 2.0\n\
#define FXAA_QUALITY_P3 2.0\n\
#define FXAA_QUALITY_P4 2.0\n\
#define FXAA_QUALITY_P5 2.0\n\
#define FXAA_QUALITY_P6 4.0\n\
#define FXAA_QUALITY_P7 8.0\n\
#endif\n\
#if (FXAA_QUALITY_PRESET == 26)\n\
#define FXAA_QUALITY_PS 9\n\
#define FXAA_QUALITY_P0 1.0\n\
#define FXAA_QUALITY_P1 1.5\n\
#define FXAA_QUALITY_P2 2.0\n\
#define FXAA_QUALITY_P3 2.0\n\
#define FXAA_QUALITY_P4 2.0\n\
#define FXAA_QUALITY_P5 2.0\n\
#define FXAA_QUALITY_P6 2.0\n\
#define FXAA_QUALITY_P7 4.0\n\
#define FXAA_QUALITY_P8 8.0\n\
#endif\n\
#if (FXAA_QUALITY_PRESET == 27)\n\
#define FXAA_QUALITY_PS 10\n\
#define FXAA_QUALITY_P0 1.0\n\
#define FXAA_QUALITY_P1 1.5\n\
#define FXAA_QUALITY_P2 2.0\n\
#define FXAA_QUALITY_P3 2.0\n\
#define FXAA_QUALITY_P4 2.0\n\
#define FXAA_QUALITY_P5 2.0\n\
#define FXAA_QUALITY_P6 2.0\n\
#define FXAA_QUALITY_P7 2.0\n\
#define FXAA_QUALITY_P8 4.0\n\
#define FXAA_QUALITY_P9 8.0\n\
#endif\n\
#if (FXAA_QUALITY_PRESET == 28)\n\
#define FXAA_QUALITY_PS 11\n\
#define FXAA_QUALITY_P0 1.0\n\
#define FXAA_QUALITY_P1 1.5\n\
#define FXAA_QUALITY_P2 2.0\n\
#define FXAA_QUALITY_P3 2.0\n\
#define FXAA_QUALITY_P4 2.0\n\
#define FXAA_QUALITY_P5 2.0\n\
#define FXAA_QUALITY_P6 2.0\n\
#define FXAA_QUALITY_P7 2.0\n\
#define FXAA_QUALITY_P8 2.0\n\
#define FXAA_QUALITY_P9 4.0\n\
#define FXAA_QUALITY_P10 8.0\n\
#endif\n\
#if (FXAA_QUALITY_PRESET == 29)\n\
#define FXAA_QUALITY_PS 12\n\
#define FXAA_QUALITY_P0 1.0\n\
#define FXAA_QUALITY_P1 1.5\n\
#define FXAA_QUALITY_P2 2.0\n\
#define FXAA_QUALITY_P3 2.0\n\
#define FXAA_QUALITY_P4 2.0\n\
#define FXAA_QUALITY_P5 2.0\n\
#define FXAA_QUALITY_P6 2.0\n\
#define FXAA_QUALITY_P7 2.0\n\
#define FXAA_QUALITY_P8 2.0\n\
#define FXAA_QUALITY_P9 2.0\n\
#define FXAA_QUALITY_P10 4.0\n\
#define FXAA_QUALITY_P11 8.0\n\
#endif\n\
#if (FXAA_QUALITY_PRESET == 39)\n\
#define FXAA_QUALITY_PS 12\n\
#define FXAA_QUALITY_P0 1.0\n\
#define FXAA_QUALITY_P1 1.0\n\
#define FXAA_QUALITY_P2 1.0\n\
#define FXAA_QUALITY_P3 1.0\n\
#define FXAA_QUALITY_P4 1.0\n\
#define FXAA_QUALITY_P5 1.5\n\
#define FXAA_QUALITY_P6 2.0\n\
#define FXAA_QUALITY_P7 2.0\n\
#define FXAA_QUALITY_P8 2.0\n\
#define FXAA_QUALITY_P9 2.0\n\
#define FXAA_QUALITY_P10 4.0\n\
#define FXAA_QUALITY_P11 8.0\n\
#endif\n\
#define FxaaBool bool\n\
#define FxaaFloat float\n\
#define FxaaFloat2 vec2\n\
#define FxaaFloat3 vec3\n\
#define FxaaFloat4 vec4\n\
#define FxaaHalf float\n\
#define FxaaHalf2 vec2\n\
#define FxaaHalf3 vec3\n\
#define FxaaHalf4 vec4\n\
#define FxaaInt2 vec2\n\
#define FxaaTex sampler2D\n\
#define FxaaSat(x) clamp(x, 0.0, 1.0)\n\
#define FxaaTexTop(t, p) texture2D(t, p)\n\
#define FxaaTexOff(t, p, o, r) texture2D(t, p + (o * r))\n\
FxaaFloat FxaaLuma(FxaaFloat4 rgba) { return rgba.y; }\n\
FxaaFloat4 FxaaPixelShader(\n\
FxaaFloat2 pos,\n\
FxaaTex tex,\n\
FxaaFloat2 fxaaQualityRcpFrame,\n\
FxaaFloat fxaaQualitySubpix,\n\
FxaaFloat fxaaQualityEdgeThreshold,\n\
FxaaFloat fxaaQualityEdgeThresholdMin\n\
) {\n\
FxaaFloat2 posM;\n\
posM.x = pos.x;\n\
posM.y = pos.y;\n\
FxaaFloat4 rgbyM = FxaaTexTop(tex, posM);\n\
#define lumaM rgbyM.y\n\
FxaaFloat lumaS = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 0, 1), fxaaQualityRcpFrame.xy));\n\
FxaaFloat lumaE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 1, 0), fxaaQualityRcpFrame.xy));\n\
FxaaFloat lumaN = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 0,-1), fxaaQualityRcpFrame.xy));\n\
FxaaFloat lumaW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, 0), fxaaQualityRcpFrame.xy));\n\
FxaaFloat maxSM = max(lumaS, lumaM);\n\
FxaaFloat minSM = min(lumaS, lumaM);\n\
FxaaFloat maxESM = max(lumaE, maxSM);\n\
FxaaFloat minESM = min(lumaE, minSM);\n\
FxaaFloat maxWN = max(lumaN, lumaW);\n\
FxaaFloat minWN = min(lumaN, lumaW);\n\
FxaaFloat rangeMax = max(maxWN, maxESM);\n\
FxaaFloat rangeMin = min(minWN, minESM);\n\
FxaaFloat rangeMaxScaled = rangeMax * fxaaQualityEdgeThreshold;\n\
FxaaFloat range = rangeMax - rangeMin;\n\
FxaaFloat rangeMaxClamped = max(fxaaQualityEdgeThresholdMin, rangeMaxScaled);\n\
FxaaBool earlyExit = range < rangeMaxClamped;\n\
if(earlyExit)\n\
return rgbyM;\n\
FxaaFloat lumaNW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1,-1), fxaaQualityRcpFrame.xy));\n\
FxaaFloat lumaSE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 1, 1), fxaaQualityRcpFrame.xy));\n\
FxaaFloat lumaNE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 1,-1), fxaaQualityRcpFrame.xy));\n\
FxaaFloat lumaSW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, 1), fxaaQualityRcpFrame.xy));\n\
FxaaFloat lumaNS = lumaN + lumaS;\n\
FxaaFloat lumaWE = lumaW + lumaE;\n\
FxaaFloat subpixRcpRange = 1.0/range;\n\
FxaaFloat subpixNSWE = lumaNS + lumaWE;\n\
FxaaFloat edgeHorz1 = (-2.0 * lumaM) + lumaNS;\n\
FxaaFloat edgeVert1 = (-2.0 * lumaM) + lumaWE;\n\
FxaaFloat lumaNESE = lumaNE + lumaSE;\n\
FxaaFloat lumaNWNE = lumaNW + lumaNE;\n\
FxaaFloat edgeHorz2 = (-2.0 * lumaE) + lumaNESE;\n\
FxaaFloat edgeVert2 = (-2.0 * lumaN) + lumaNWNE;\n\
FxaaFloat lumaNWSW = lumaNW + lumaSW;\n\
FxaaFloat lumaSWSE = lumaSW + lumaSE;\n\
FxaaFloat edgeHorz4 = (abs(edgeHorz1) * 2.0) + abs(edgeHorz2);\n\
FxaaFloat edgeVert4 = (abs(edgeVert1) * 2.0) + abs(edgeVert2);\n\
FxaaFloat edgeHorz3 = (-2.0 * lumaW) + lumaNWSW;\n\
FxaaFloat edgeVert3 = (-2.0 * lumaS) + lumaSWSE;\n\
FxaaFloat edgeHorz = abs(edgeHorz3) + edgeHorz4;\n\
FxaaFloat edgeVert = abs(edgeVert3) + edgeVert4;\n\
FxaaFloat subpixNWSWNESE = lumaNWSW + lumaNESE;\n\
FxaaFloat lengthSign = fxaaQualityRcpFrame.x;\n\
FxaaBool horzSpan = edgeHorz >= edgeVert;\n\
FxaaFloat subpixA = subpixNSWE * 2.0 + subpixNWSWNESE;\n\
if(!horzSpan) lumaN = lumaW;\n\
if(!horzSpan) lumaS = lumaE;\n\
if(horzSpan) lengthSign = fxaaQualityRcpFrame.y;\n\
FxaaFloat subpixB = (subpixA * (1.0/12.0)) - lumaM;\n\
FxaaFloat gradientN = lumaN - lumaM;\n\
FxaaFloat gradientS = lumaS - lumaM;\n\
FxaaFloat lumaNN = lumaN + lumaM;\n\
FxaaFloat lumaSS = lumaS + lumaM;\n\
FxaaBool pairN = abs(gradientN) >= abs(gradientS);\n\
FxaaFloat gradient = max(abs(gradientN), abs(gradientS));\n\
if(pairN) lengthSign = -lengthSign;\n\
FxaaFloat subpixC = FxaaSat(abs(subpixB) * subpixRcpRange);\n\
FxaaFloat2 posB;\n\
posB.x = posM.x;\n\
posB.y = posM.y;\n\
FxaaFloat2 offNP;\n\
offNP.x = (!horzSpan) ? 0.0 : fxaaQualityRcpFrame.x;\n\
offNP.y = ( horzSpan) ? 0.0 : fxaaQualityRcpFrame.y;\n\
if(!horzSpan) posB.x += lengthSign * 0.5;\n\
if( horzSpan) posB.y += lengthSign * 0.5;\n\
FxaaFloat2 posN;\n\
posN.x = posB.x - offNP.x * FXAA_QUALITY_P0;\n\
posN.y = posB.y - offNP.y * FXAA_QUALITY_P0;\n\
FxaaFloat2 posP;\n\
posP.x = posB.x + offNP.x * FXAA_QUALITY_P0;\n\
posP.y = posB.y + offNP.y * FXAA_QUALITY_P0;\n\
FxaaFloat subpixD = ((-2.0)*subpixC) + 3.0;\n\
FxaaFloat lumaEndN = FxaaLuma(FxaaTexTop(tex, posN));\n\
FxaaFloat subpixE = subpixC * subpixC;\n\
FxaaFloat lumaEndP = FxaaLuma(FxaaTexTop(tex, posP));\n\
if(!pairN) lumaNN = lumaSS;\n\
FxaaFloat gradientScaled = gradient * 1.0/4.0;\n\
FxaaFloat lumaMM = lumaM - lumaNN * 0.5;\n\
FxaaFloat subpixF = subpixD * subpixE;\n\
FxaaBool lumaMLTZero = lumaMM < 0.0;\n\
lumaEndN -= lumaNN * 0.5;\n\
lumaEndP -= lumaNN * 0.5;\n\
FxaaBool doneN = abs(lumaEndN) >= gradientScaled;\n\
FxaaBool doneP = abs(lumaEndP) >= gradientScaled;\n\
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P1;\n\
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P1;\n\
FxaaBool doneNP = (!doneN) || (!doneP);\n\
if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P1;\n\
if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P1;\n\
if(doneNP) {\n\
if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n\
if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n\
if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n\
if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n\
doneN = abs(lumaEndN) >= gradientScaled;\n\
doneP = abs(lumaEndP) >= gradientScaled;\n\
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P2;\n\
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P2;\n\
doneNP = (!doneN) || (!doneP);\n\
if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P2;\n\
if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P2;\n\
#if (FXAA_QUALITY_PS > 3)\n\
if(doneNP) {\n\
if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n\
if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n\
if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n\
if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n\
doneN = abs(lumaEndN) >= gradientScaled;\n\
doneP = abs(lumaEndP) >= gradientScaled;\n\
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P3;\n\
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P3;\n\
doneNP = (!doneN) || (!doneP);\n\
if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P3;\n\
if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P3;\n\
#if (FXAA_QUALITY_PS > 4)\n\
if(doneNP) {\n\
if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n\
if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n\
if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n\
if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n\
doneN = abs(lumaEndN) >= gradientScaled;\n\
doneP = abs(lumaEndP) >= gradientScaled;\n\
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P4;\n\
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P4;\n\
doneNP = (!doneN) || (!doneP);\n\
if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P4;\n\
if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P4;\n\
#if (FXAA_QUALITY_PS > 5)\n\
if(doneNP) {\n\
if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n\
if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n\
if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n\
if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n\
doneN = abs(lumaEndN) >= gradientScaled;\n\
doneP = abs(lumaEndP) >= gradientScaled;\n\
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P5;\n\
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P5;\n\
doneNP = (!doneN) || (!doneP);\n\
if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P5;\n\
if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P5;\n\
#if (FXAA_QUALITY_PS > 6)\n\
if(doneNP) {\n\
if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n\
if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n\
if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n\
if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n\
doneN = abs(lumaEndN) >= gradientScaled;\n\
doneP = abs(lumaEndP) >= gradientScaled;\n\
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P6;\n\
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P6;\n\
doneNP = (!doneN) || (!doneP);\n\
if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P6;\n\
if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P6;\n\
#if (FXAA_QUALITY_PS > 7)\n\
if(doneNP) {\n\
if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n\
if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n\
if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n\
if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n\
doneN = abs(lumaEndN) >= gradientScaled;\n\
doneP = abs(lumaEndP) >= gradientScaled;\n\
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P7;\n\
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P7;\n\
doneNP = (!doneN) || (!doneP);\n\
if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P7;\n\
if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P7;\n\
#if (FXAA_QUALITY_PS > 8)\n\
if(doneNP) {\n\
if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n\
if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n\
if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n\
if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n\
doneN = abs(lumaEndN) >= gradientScaled;\n\
doneP = abs(lumaEndP) >= gradientScaled;\n\
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P8;\n\
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P8;\n\
doneNP = (!doneN) || (!doneP);\n\
if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P8;\n\
if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P8;\n\
#if (FXAA_QUALITY_PS > 9)\n\
if(doneNP) {\n\
if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n\
if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n\
if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n\
if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n\
doneN = abs(lumaEndN) >= gradientScaled;\n\
doneP = abs(lumaEndP) >= gradientScaled;\n\
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P9;\n\
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P9;\n\
doneNP = (!doneN) || (!doneP);\n\
if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P9;\n\
if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P9;\n\
#if (FXAA_QUALITY_PS > 10)\n\
if(doneNP) {\n\
if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n\
if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n\
if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n\
if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n\
doneN = abs(lumaEndN) >= gradientScaled;\n\
doneP = abs(lumaEndP) >= gradientScaled;\n\
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P10;\n\
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P10;\n\
doneNP = (!doneN) || (!doneP);\n\
if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P10;\n\
if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P10;\n\
#if (FXAA_QUALITY_PS > 11)\n\
if(doneNP) {\n\
if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n\
if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n\
if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n\
if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n\
doneN = abs(lumaEndN) >= gradientScaled;\n\
doneP = abs(lumaEndP) >= gradientScaled;\n\
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P11;\n\
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P11;\n\
doneNP = (!doneN) || (!doneP);\n\
if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P11;\n\
if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P11;\n\
#if (FXAA_QUALITY_PS > 12)\n\
if(doneNP) {\n\
if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n\
if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n\
if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n\
if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n\
doneN = abs(lumaEndN) >= gradientScaled;\n\
doneP = abs(lumaEndP) >= gradientScaled;\n\
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P12;\n\
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P12;\n\
doneNP = (!doneN) || (!doneP);\n\
if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P12;\n\
if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P12;\n\
}\n\
#endif\n\
}\n\
#endif\n\
}\n\
#endif\n\
}\n\
#endif\n\
}\n\
#endif\n\
}\n\
#endif\n\
}\n\
#endif\n\
}\n\
#endif\n\
}\n\
#endif\n\
}\n\
#endif\n\
}\n\
FxaaFloat dstN = posM.x - posN.x;\n\
FxaaFloat dstP = posP.x - posM.x;\n\
if(!horzSpan) dstN = posM.y - posN.y;\n\
if(!horzSpan) dstP = posP.y - posM.y;\n\
FxaaBool goodSpanN = (lumaEndN < 0.0) != lumaMLTZero;\n\
FxaaFloat spanLength = (dstP + dstN);\n\
FxaaBool goodSpanP = (lumaEndP < 0.0) != lumaMLTZero;\n\
FxaaFloat spanLengthRcp = 1.0/spanLength;\n\
FxaaBool directionN = dstN < dstP;\n\
FxaaFloat dst = min(dstN, dstP);\n\
FxaaBool goodSpan = directionN ? goodSpanN : goodSpanP;\n\
FxaaFloat subpixG = subpixF * subpixF;\n\
FxaaFloat pixelOffset = (dst * (-spanLengthRcp)) + 0.5;\n\
FxaaFloat subpixH = subpixG * fxaaQualitySubpix;\n\
FxaaFloat pixelOffsetGood = goodSpan ? pixelOffset : 0.0;\n\
FxaaFloat pixelOffsetSubpix = max(pixelOffsetGood, subpixH);\n\
if(!horzSpan) posM.x += pixelOffsetSubpix * lengthSign;\n\
if( horzSpan) posM.y += pixelOffsetSubpix * lengthSign;\n\
return FxaaFloat4(FxaaTexTop(tex, posM).xyz, lumaM);\n\
}\n\
";

  /**
   * A collection of {@link PostProcessStage}s or other post-process composite stages that execute together logically.
   * <p>
   * All stages are executed in the order of the array. The input texture changes based on the value of <code>inputPreviousStageTexture</code>.
   * If <code>inputPreviousStageTexture</code> is <code>true</code>, the input to each stage is the output texture rendered to by the scene or of the stage that executed before it.
   * If <code>inputPreviousStageTexture</code> is <code>false</code>, the input texture is the same for each stage in the composite. The input texture is the texture rendered to by the scene
   * or the output texture of the previous stage.
   * </p>
   *
   * @alias PostProcessStageComposite
   * @constructor
   *
   * @param {Object} options An object with the following properties:
   * @param {Array} options.stages An array of {@link PostProcessStage}s or composites to be executed in order.
   * @param {Boolean} [options.inputPreviousStageTexture=true] Whether to execute each post-process stage where the input to one stage is the output of the previous. Otherwise, the input to each contained stage is the output of the stage that executed before the composite.
   * @param {String} [options.name=createGuid()] The unique name of this post-process stage for reference by other composites. If a name is not supplied, a GUID will be generated.
   * @param {Object} [options.uniforms] An alias to the uniforms of post-process stages.
   *
   * @exception {DeveloperError} options.stages.length must be greater than 0.0.
   *
   * @see PostProcessStage
   *
   * @example
   * // Example 1: separable blur filter
   * // The input to blurXDirection is the texture rendered to by the scene or the output of the previous stage.
   * // The input to blurYDirection is the texture rendered to by blurXDirection.
   * scene.postProcessStages.add(new Cesium.PostProcessStageComposite({
   *     stages : [blurXDirection, blurYDirection]
   * }));
   *
   * @example
   * // Example 2: referencing the output of another post-process stage
   * scene.postProcessStages.add(new Cesium.PostProcessStageComposite({
   *     inputPreviousStageTexture : false,
   *     stages : [
   *         // The same as Example 1.
   *         new Cesium.PostProcessStageComposite({
   *             inputPreviousStageTexture : true
   *             stages : [blurXDirection, blurYDirection],
   *             name : 'blur'
   *         }),
   *         // The input texture for this stage is the same input texture to blurXDirection since inputPreviousStageTexture is false
   *         new Cesium.PostProcessStage({
   *             fragmentShader : compositeShader,
   *             uniforms : {
   *                 blurTexture : 'blur' // The output of the composite with name 'blur' (the texture that blurYDirection rendered to).
   *             }
   *         })
   *     ]
   * });
   *
   * @example
   * // Example 3: create a uniform alias
   * const uniforms = {};
   * Cesium.defineProperties(uniforms, {
   *     filterSize : {
   *         get : function() {
   *             return blurXDirection.uniforms.filterSize;
   *         },
   *         set : function(value) {
   *             blurXDirection.uniforms.filterSize = blurYDirection.uniforms.filterSize = value;
   *         }
   *     }
   * });
   * scene.postProcessStages.add(new Cesium.PostProcessStageComposite({
   *     stages : [blurXDirection, blurYDirection],
   *     uniforms : uniforms
   * }));
   */
  function PostProcessStageComposite(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    Check.defined("options.stages", options.stages);
    Check.typeOf.number.greaterThan(
      "options.stages.length",
      options.stages.length,
      0
    );
    //>>includeEnd('debug');

    this._stages = options.stages;
    this._inputPreviousStageTexture = defaultValue(
      options.inputPreviousStageTexture,
      true
    );

    let name = options.name;
    if (!defined(name)) {
      name = createGuid();
    }
    this._name = name;

    this._uniforms = options.uniforms;

    // used by PostProcessStageCollection
    this._textureCache = undefined;
    this._index = undefined;

    this._selected = undefined;
    this._selectedShadow = undefined;
    this._parentSelected = undefined;
    this._parentSelectedShadow = undefined;
    this._combinedSelected = undefined;
    this._combinedSelectedShadow = undefined;
    this._selectedLength = 0;
    this._parentSelectedLength = 0;
    this._selectedDirty = true;
  }

  Object.defineProperties(PostProcessStageComposite.prototype, {
    /**
     * Determines if this post-process stage is ready to be executed.
     *
     * @memberof PostProcessStageComposite.prototype
     * @type {Boolean}
     * @readonly
     */
    ready: {
      get: function () {
        const stages = this._stages;
        const length = stages.length;
        for (let i = 0; i < length; ++i) {
          if (!stages[i].ready) {
            return false;
          }
        }
        return true;
      },
    },
    /**
     * The unique name of this post-process stage for reference by other stages in a PostProcessStageComposite.
     *
     * @memberof PostProcessStageComposite.prototype
     * @type {String}
     * @readonly
     */
    name: {
      get: function () {
        return this._name;
      },
    },
    /**
     * Whether or not to execute this post-process stage when ready.
     *
     * @memberof PostProcessStageComposite.prototype
     * @type {Boolean}
     */
    enabled: {
      get: function () {
        return this._stages[0].enabled;
      },
      set: function (value) {
        const stages = this._stages;
        const length = stages.length;
        for (let i = 0; i < length; ++i) {
          stages[i].enabled = value;
        }
      },
    },
    /**
     * An alias to the uniform values of the post-process stages. May be <code>undefined</code>; in which case, get each stage to set uniform values.
     * @memberof PostProcessStageComposite.prototype
     * @type {Object}
     */
    uniforms: {
      get: function () {
        return this._uniforms;
      },
    },
    /**
     * All post-process stages are executed in the order of the array. The input texture changes based on the value of <code>inputPreviousStageTexture</code>.
     * If <code>inputPreviousStageTexture</code> is <code>true</code>, the input to each stage is the output texture rendered to by the scene or of the stage that executed before it.
     * If <code>inputPreviousStageTexture</code> is <code>false</code>, the input texture is the same for each stage in the composite. The input texture is the texture rendered to by the scene
     * or the output texture of the previous stage.
     *
     * @memberof PostProcessStageComposite.prototype
     * @type {Boolean}
     * @readonly
     */
    inputPreviousStageTexture: {
      get: function () {
        return this._inputPreviousStageTexture;
      },
    },
    /**
     * The number of post-process stages in this composite.
     *
     * @memberof PostProcessStageComposite.prototype
     * @type {Number}
     * @readonly
     */
    length: {
      get: function () {
        return this._stages.length;
      },
    },
    /**
     * The features selected for applying the post-process.
     *
     * @memberof PostProcessStageComposite.prototype
     * @type {Array}
     */
    selected: {
      get: function () {
        return this._selected;
      },
      set: function (value) {
        this._selected = value;
      },
    },
    /**
     * @private
     */
    parentSelected: {
      get: function () {
        return this._parentSelected;
      },
      set: function (value) {
        this._parentSelected = value;
      },
    },
  });

  /**
   * @private
   */
  PostProcessStageComposite.prototype._isSupported = function (context) {
    const stages = this._stages;
    const length = stages.length;
    for (let i = 0; i < length; ++i) {
      if (!stages[i]._isSupported(context)) {
        return false;
      }
    }
    return true;
  };

  /**
   * Gets the post-process stage at <code>index</code>
   *
   * @param {Number} index The index of the post-process stage or composite.
   * @return {PostProcessStage|PostProcessStageComposite} The post-process stage or composite at index.
   *
   * @exception {DeveloperError} index must be greater than or equal to 0.
   * @exception {DeveloperError} index must be less than {@link PostProcessStageComposite#length}.
   */
  PostProcessStageComposite.prototype.get = function (index) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number.greaterThanOrEquals("index", index, 0);
    Check.typeOf.number.lessThan("index", index, this.length);
    //>>includeEnd('debug');
    return this._stages[index];
  };

  function isSelectedTextureDirty(stage) {
    let length = defined(stage._selected) ? stage._selected.length : 0;
    const parentLength = defined(stage._parentSelected)
      ? stage._parentSelected
      : 0;
    let dirty =
      stage._selected !== stage._selectedShadow ||
      length !== stage._selectedLength;
    dirty =
      dirty ||
      stage._parentSelected !== stage._parentSelectedShadow ||
      parentLength !== stage._parentSelectedLength;

    if (defined(stage._selected) && defined(stage._parentSelected)) {
      stage._combinedSelected = stage._selected.concat(stage._parentSelected);
    } else if (defined(stage._parentSelected)) {
      stage._combinedSelected = stage._parentSelected;
    } else {
      stage._combinedSelected = stage._selected;
    }

    if (!dirty && defined(stage._combinedSelected)) {
      if (!defined(stage._combinedSelectedShadow)) {
        return true;
      }

      length = stage._combinedSelected.length;
      for (let i = 0; i < length; ++i) {
        if (stage._combinedSelected[i] !== stage._combinedSelectedShadow[i]) {
          return true;
        }
      }
    }
    return dirty;
  }

  /**
   * A function that will be called before execute. Updates each post-process stage in the composite.
   * @param {Context} context The context.
   * @param {Boolean} useLogDepth Whether the scene uses a logarithmic depth buffer.
   * @private
   */
  PostProcessStageComposite.prototype.update = function (context, useLogDepth) {
    this._selectedDirty = isSelectedTextureDirty(this);

    this._selectedShadow = this._selected;
    this._parentSelectedShadow = this._parentSelected;
    this._combinedSelectedShadow = this._combinedSelected;
    this._selectedLength = defined(this._selected) ? this._selected.length : 0;
    this._parentSelectedLength = defined(this._parentSelected)
      ? this._parentSelected.length
      : 0;

    const stages = this._stages;
    const length = stages.length;
    for (let i = 0; i < length; ++i) {
      const stage = stages[i];
      if (this._selectedDirty) {
        stage.parentSelected = this._combinedSelected;
      }
      stage.update(context, useLogDepth);
    }
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <p>
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   * </p>
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see PostProcessStageComposite#destroy
   */
  PostProcessStageComposite.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <p>
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   * </p>
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @see PostProcessStageComposite#isDestroyed
   */
  PostProcessStageComposite.prototype.destroy = function () {
    const stages = this._stages;
    const length = stages.length;
    for (let i = 0; i < length; ++i) {
      stages[i].destroy();
    }
    return destroyObject(this);
  };

  /**
   * Contains functions for creating common post-process stages.
   *
   * @namespace PostProcessStageLibrary
   */
  const PostProcessStageLibrary = {};

  function createBlur(name) {
    const delta = 1.0;
    const sigma = 2.0;
    const stepSize = 1.0;

    const blurShader = `#define USE_STEP_SIZE\n${GaussianBlur1D}`;
    const blurX = new PostProcessStage({
      name: `${name}_x_direction`,
      fragmentShader: blurShader,
      uniforms: {
        delta: delta,
        sigma: sigma,
        stepSize: stepSize,
        direction: 0.0,
      },
      sampleMode: PostProcessStageSampleMode.LINEAR,
    });
    const blurY = new PostProcessStage({
      name: `${name}_y_direction`,
      fragmentShader: blurShader,
      uniforms: {
        delta: delta,
        sigma: sigma,
        stepSize: stepSize,
        direction: 1.0,
      },
      sampleMode: PostProcessStageSampleMode.LINEAR,
    });

    const uniforms = {};
    Object.defineProperties(uniforms, {
      delta: {
        get: function () {
          return blurX.uniforms.delta;
        },
        set: function (value) {
          const blurXUniforms = blurX.uniforms;
          const blurYUniforms = blurY.uniforms;
          blurXUniforms.delta = blurYUniforms.delta = value;
        },
      },
      sigma: {
        get: function () {
          return blurX.uniforms.sigma;
        },
        set: function (value) {
          const blurXUniforms = blurX.uniforms;
          const blurYUniforms = blurY.uniforms;
          blurXUniforms.sigma = blurYUniforms.sigma = value;
        },
      },
      stepSize: {
        get: function () {
          return blurX.uniforms.stepSize;
        },
        set: function (value) {
          const blurXUniforms = blurX.uniforms;
          const blurYUniforms = blurY.uniforms;
          blurXUniforms.stepSize = blurYUniforms.stepSize = value;
        },
      },
    });
    return new PostProcessStageComposite({
      name: name,
      stages: [blurX, blurY],
      uniforms: uniforms,
    });
  }

  /**
   * Creates a post-process stage that applies a Gaussian blur to the input texture. This stage is usually applied in conjunction with another stage.
   * <p>
   * This stage has the following uniforms: <code>delta</code>, <code>sigma</code>, and <code>stepSize</code>.
   * </p>
   * <p>
   * <code>delta</code> and <code>sigma</code> are used to compute the weights of a Gaussian filter. The equation is <code>exp((-0.5 * delta * delta) / (sigma * sigma))</code>.
   * The default value for <code>delta</code> is <code>1.0</code>. The default value for <code>sigma</code> is <code>2.0</code>.
   * <code>stepSize</code> is the distance to the next texel. The default is <code>1.0</code>.
   * </p>
   * @return {PostProcessStageComposite} A post-process stage that applies a Gaussian blur to the input texture.
   */
  PostProcessStageLibrary.createBlurStage = function () {
    return createBlur("czm_blur");
  };

  /**
   * Creates a post-process stage that applies a depth of field effect.
   * <p>
   * Depth of field simulates camera focus. Objects in the scene that are in focus
   * will be clear whereas objects not in focus will be blurred.
   * </p>
   * <p>
   * This stage has the following uniforms: <code>focalDistance</code>, <code>delta</code>, <code>sigma</code>, and <code>stepSize</code>.
   * </p>
   * <p>
   * <code>focalDistance</code> is the distance in meters from the camera to set the camera focus.
   * </p>
   * <p>
   * <code>delta</code>, <code>sigma</code>, and <code>stepSize</code> are the same properties as {@link PostProcessStageLibrary#createBlurStage}.
   * The blur is applied to the areas out of focus.
   * </p>
   * @return {PostProcessStageComposite} A post-process stage that applies a depth of field effect.
   */
  PostProcessStageLibrary.createDepthOfFieldStage = function () {
    const blur = createBlur("czm_depth_of_field_blur");
    const dof = new PostProcessStage({
      name: "czm_depth_of_field_composite",
      fragmentShader: DepthOfField,
      uniforms: {
        focalDistance: 5.0,
        blurTexture: blur.name,
      },
    });

    const uniforms = {};
    Object.defineProperties(uniforms, {
      focalDistance: {
        get: function () {
          return dof.uniforms.focalDistance;
        },
        set: function (value) {
          dof.uniforms.focalDistance = value;
        },
      },
      delta: {
        get: function () {
          return blur.uniforms.delta;
        },
        set: function (value) {
          blur.uniforms.delta = value;
        },
      },
      sigma: {
        get: function () {
          return blur.uniforms.sigma;
        },
        set: function (value) {
          blur.uniforms.sigma = value;
        },
      },
      stepSize: {
        get: function () {
          return blur.uniforms.stepSize;
        },
        set: function (value) {
          blur.uniforms.stepSize = value;
        },
      },
    });
    return new PostProcessStageComposite({
      name: "czm_depth_of_field",
      stages: [blur, dof],
      inputPreviousStageTexture: false,
      uniforms: uniforms,
    });
  };

  /**
   * Whether or not a depth of field stage is supported.
   * <p>
   * This stage requires the WEBGL_depth_texture extension.
   * </p>
   *
   * @param {Scene} scene The scene.
   * @return {Boolean} Whether this post process stage is supported.
   *
   * @see {Context#depthTexture}
   * @see {@link http://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/|WEBGL_depth_texture}
   */
  PostProcessStageLibrary.isDepthOfFieldSupported = function (scene) {
    return scene.context.depthTexture;
  };

  /**
   * Creates a post-process stage that detects edges.
   * <p>
   * Writes the color to the output texture with alpha set to 1.0 when it is on an edge.
   * </p>
   * <p>
   * This stage has the following uniforms: <code>color</code> and <code>length</code>
   * </p>
   * <ul>
   * <li><code>color</code> is the color of the highlighted edge. The default is {@link Color#BLACK}.</li>
   * <li><code>length</code> is the length of the edges in pixels. The default is <code>0.5</code>.</li>
   * </ul>
   * <p>
   * This stage is not supported in 2D.
   * </p>
   * @return {PostProcessStage} A post-process stage that applies an edge detection effect.
   *
   * @example
   * // multiple silhouette effects
   * const yellowEdge = Cesium.PostProcessLibrary.createEdgeDetectionStage();
   * yellowEdge.uniforms.color = Cesium.Color.YELLOW;
   * yellowEdge.selected = [feature0];
   *
   * const greenEdge = Cesium.PostProcessLibrary.createEdgeDetectionStage();
   * greenEdge.uniforms.color = Cesium.Color.LIME;
   * greenEdge.selected = [feature1];
   *
   * // draw edges around feature0 and feature1
   * postProcessStages.add(Cesium.PostProcessLibrary.createSilhouetteStage([yellowEdge, greenEdge]);
   */
  PostProcessStageLibrary.createEdgeDetectionStage = function () {
    // unique name generated on call so more than one effect can be added
    const name = createGuid();
    return new PostProcessStage({
      name: `czm_edge_detection_${name}`,
      fragmentShader: EdgeDetection,
      uniforms: {
        length: 0.25,
        color: Color.clone(Color.BLACK),
      },
    });
  };

  /**
   * Whether or not an edge detection stage is supported.
   * <p>
   * This stage requires the WEBGL_depth_texture extension.
   * </p>
   *
   * @param {Scene} scene The scene.
   * @return {Boolean} Whether this post process stage is supported.
   *
   * @see {Context#depthTexture}
   * @see {@link http://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/|WEBGL_depth_texture}
   */
  PostProcessStageLibrary.isEdgeDetectionSupported = function (scene) {
    return scene.context.depthTexture;
  };

  function getSilhouetteEdgeDetection(edgeDetectionStages) {
    if (!defined(edgeDetectionStages)) {
      return PostProcessStageLibrary.createEdgeDetectionStage();
    }

    const edgeDetection = new PostProcessStageComposite({
      name: "czm_edge_detection_multiple",
      stages: edgeDetectionStages,
      inputPreviousStageTexture: false,
    });

    const compositeUniforms = {};
    let fsDecl = "";
    let fsLoop = "";
    for (let i = 0; i < edgeDetectionStages.length; ++i) {
      fsDecl += `uniform sampler2D edgeTexture${i}; \n`;
      fsLoop +=
        `        vec4 edge${i} = texture2D(edgeTexture${i}, v_textureCoordinates); \n` +
        `        if (edge${i}.a > 0.0) \n` +
        `        { \n` +
        `            color = edge${i}; \n` +
        `            break; \n` +
        `        } \n`;
      compositeUniforms[`edgeTexture${i}`] = edgeDetectionStages[i].name;
    }

    const fs =
      `${fsDecl}varying vec2 v_textureCoordinates; \n` +
      `void main() { \n` +
      `    vec4 color = vec4(0.0); \n` +
      `    for (int i = 0; i < ${edgeDetectionStages.length}; i++) \n` +
      `    { \n${fsLoop}    } \n` +
      `    gl_FragColor = color; \n` +
      `} \n`;

    const edgeComposite = new PostProcessStage({
      name: "czm_edge_detection_combine",
      fragmentShader: fs,
      uniforms: compositeUniforms,
    });
    return new PostProcessStageComposite({
      name: "czm_edge_detection_composite",
      stages: [edgeDetection, edgeComposite],
    });
  }

  /**
   * Creates a post-process stage that applies a silhouette effect.
   * <p>
   * A silhouette effect composites the color from the edge detection pass with input color texture.
   * </p>
   * <p>
   * This stage has the following uniforms when <code>edgeDetectionStages</code> is <code>undefined</code>: <code>color</code> and <code>length</code>
   * </p>
   * <p>
   * <code>color</code> is the color of the highlighted edge. The default is {@link Color#BLACK}.
   * <code>length</code> is the length of the edges in pixels. The default is <code>0.5</code>.
   * </p>
   * @param {PostProcessStage[]} [edgeDetectionStages] An array of edge detection post process stages.
   * @return {PostProcessStageComposite} A post-process stage that applies a silhouette effect.
   */
  PostProcessStageLibrary.createSilhouetteStage = function (edgeDetectionStages) {
    const edgeDetection = getSilhouetteEdgeDetection(edgeDetectionStages);
    const silhouetteProcess = new PostProcessStage({
      name: "czm_silhouette_color_edges",
      fragmentShader: Silhouette,
      uniforms: {
        silhouetteTexture: edgeDetection.name,
      },
    });

    return new PostProcessStageComposite({
      name: "czm_silhouette",
      stages: [edgeDetection, silhouetteProcess],
      inputPreviousStageTexture: false,
      uniforms: edgeDetection.uniforms,
    });
  };

  /**
   * Whether or not a silhouette stage is supported.
   * <p>
   * This stage requires the WEBGL_depth_texture extension.
   * </p>
   *
   * @param {Scene} scene The scene.
   * @return {Boolean} Whether this post process stage is supported.
   *
   * @see {Context#depthTexture}
   * @see {@link http://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/|WEBGL_depth_texture}
   */
  PostProcessStageLibrary.isSilhouetteSupported = function (scene) {
    return scene.context.depthTexture;
  };

  /**
   * Creates a post-process stage that applies a bloom effect to the input texture.
   * <p>
   * A bloom effect adds glow effect, makes bright areas brighter, and dark areas darker.
   * </p>
   * <p>
   * This post-process stage has the following uniforms: <code>contrast</code>, <code>brightness</code>, <code>glowOnly</code>,
   * <code>delta</code>, <code>sigma</code>, and <code>stepSize</code>.
   * </p>
   * <ul>
   * <li><code>contrast</code> is a scalar value in the range [-255.0, 255.0] and affects the contract of the effect. The default value is <code>128.0</code>.</li>
   * <li><code>brightness</code> is a scalar value. The input texture RGB value is converted to hue, saturation, and brightness (HSB) then this value is
   * added to the brightness. The default value is <code>-0.3</code>.</li>
   * <li><code>glowOnly</code> is a boolean value. When <code>true</code>, only the glow effect will be shown. When <code>false</code>, the glow will be added to the input texture.
   * The default value is <code>false</code>. This is a debug option for viewing the effects when changing the other uniform values.</li>
   * </ul>
   * <p>
   * <code>delta</code>, <code>sigma</code>, and <code>stepSize</code> are the same properties as {@link PostProcessStageLibrary#createBlurStage}.
   * </p>
   * @return {PostProcessStageComposite} A post-process stage to applies a bloom effect.
   *
   * @private
   */
  PostProcessStageLibrary.createBloomStage = function () {
    const contrastBias = new PostProcessStage({
      name: "czm_bloom_contrast_bias",
      fragmentShader: ContrastBias,
      uniforms: {
        contrast: 128.0,
        brightness: -0.3,
      },
    });
    const blur = createBlur("czm_bloom_blur");
    const generateComposite = new PostProcessStageComposite({
      name: "czm_bloom_contrast_bias_blur",
      stages: [contrastBias, blur],
    });

    const bloomComposite = new PostProcessStage({
      name: "czm_bloom_generate_composite",
      fragmentShader: BloomComposite,
      uniforms: {
        glowOnly: false,
        bloomTexture: generateComposite.name,
      },
    });

    const uniforms = {};
    Object.defineProperties(uniforms, {
      glowOnly: {
        get: function () {
          return bloomComposite.uniforms.glowOnly;
        },
        set: function (value) {
          bloomComposite.uniforms.glowOnly = value;
        },
      },
      contrast: {
        get: function () {
          return contrastBias.uniforms.contrast;
        },
        set: function (value) {
          contrastBias.uniforms.contrast = value;
        },
      },
      brightness: {
        get: function () {
          return contrastBias.uniforms.brightness;
        },
        set: function (value) {
          contrastBias.uniforms.brightness = value;
        },
      },
      delta: {
        get: function () {
          return blur.uniforms.delta;
        },
        set: function (value) {
          blur.uniforms.delta = value;
        },
      },
      sigma: {
        get: function () {
          return blur.uniforms.sigma;
        },
        set: function (value) {
          blur.uniforms.sigma = value;
        },
      },
      stepSize: {
        get: function () {
          return blur.uniforms.stepSize;
        },
        set: function (value) {
          blur.uniforms.stepSize = value;
        },
      },
    });

    return new PostProcessStageComposite({
      name: "czm_bloom",
      stages: [generateComposite, bloomComposite],
      inputPreviousStageTexture: false,
      uniforms: uniforms,
    });
  };

  /**
   * Creates a post-process stage that Horizon-based Ambient Occlusion (HBAO) to the input texture.
   * <p>
   * Ambient occlusion simulates shadows from ambient light. These shadows would always be present when the
   * surface receives light and regardless of the light's position.
   * </p>
   * <p>
   * The uniforms have the following properties: <code>intensity</code>, <code>bias</code>, <code>lengthCap</code>,
   * <code>stepSize</code>, <code>frustumLength</code>, <code>randomTexture</code>, <code>ambientOcclusionOnly</code>,
   * <code>delta</code>, <code>sigma</code>, and <code>blurStepSize</code>.
   * </p>
   * <ul>
   * <li><code>intensity</code> is a scalar value used to lighten or darken the shadows exponentially. Higher values make the shadows darker. The default value is <code>3.0</code>.</li>
   * <li><code>bias</code> is a scalar value representing an angle in radians. If the dot product between the normal of the sample and the vector to the camera is less than this value,
   * sampling stops in the current direction. This is used to remove shadows from near planar edges. The default value is <code>0.1</code>.</li>
   * <li><code>lengthCap</code> is a scalar value representing a length in meters. If the distance from the current sample to first sample is greater than this value,
   * sampling stops in the current direction. The default value is <code>0.26</code>.</li>
   * <li><code>stepSize</code> is a scalar value indicating the distance to the next texel sample in the current direction. The default value is <code>1.95</code>.</li>
   * <li><code>frustumLength</code> is a scalar value in meters. If the current fragment has a distance from the camera greater than this value, ambient occlusion is not computed for the fragment.
   * The default value is <code>1000.0</code>.</li>
   * <li><code>randomTexture</code> is a texture where the red channel is a random value in [0.0, 1.0]. The default value is <code>undefined</code>. This texture needs to be set.</li>
   * <li><code>ambientOcclusionOnly</code> is a boolean value. When <code>true</code>, only the shadows generated are written to the output. When <code>false</code>, the input texture is modulated
   * with the ambient occlusion. This is a useful debug option for seeing the effects of changing the uniform values. The default value is <code>false</code>.</li>
   * </ul>
   * <p>
   * <code>delta</code>, <code>sigma</code>, and <code>blurStepSize</code> are the same properties as {@link PostProcessStageLibrary#createBlurStage}.
   * The blur is applied to the shadows generated from the image to make them smoother.
   * </p>
   * @return {PostProcessStageComposite} A post-process stage that applies an ambient occlusion effect.
   *
   * @private
   */
  PostProcessStageLibrary.createAmbientOcclusionStage = function () {
    const generate = new PostProcessStage({
      name: "czm_ambient_occlusion_generate",
      fragmentShader: AmbientOcclusionGenerate,
      uniforms: {
        intensity: 3.0,
        bias: 0.1,
        lengthCap: 0.26,
        stepSize: 1.95,
        frustumLength: 1000.0,
        randomTexture: undefined,
      },
    });
    const blur = createBlur("czm_ambient_occlusion_blur");
    blur.uniforms.stepSize = 0.86;
    const generateAndBlur = new PostProcessStageComposite({
      name: "czm_ambient_occlusion_generate_blur",
      stages: [generate, blur],
    });

    const ambientOcclusionModulate = new PostProcessStage({
      name: "czm_ambient_occlusion_composite",
      fragmentShader: AmbientOcclusionModulate,
      uniforms: {
        ambientOcclusionOnly: false,
        ambientOcclusionTexture: generateAndBlur.name,
      },
    });

    const uniforms = {};
    Object.defineProperties(uniforms, {
      intensity: {
        get: function () {
          return generate.uniforms.intensity;
        },
        set: function (value) {
          generate.uniforms.intensity = value;
        },
      },
      bias: {
        get: function () {
          return generate.uniforms.bias;
        },
        set: function (value) {
          generate.uniforms.bias = value;
        },
      },
      lengthCap: {
        get: function () {
          return generate.uniforms.lengthCap;
        },
        set: function (value) {
          generate.uniforms.lengthCap = value;
        },
      },
      stepSize: {
        get: function () {
          return generate.uniforms.stepSize;
        },
        set: function (value) {
          generate.uniforms.stepSize = value;
        },
      },
      frustumLength: {
        get: function () {
          return generate.uniforms.frustumLength;
        },
        set: function (value) {
          generate.uniforms.frustumLength = value;
        },
      },
      randomTexture: {
        get: function () {
          return generate.uniforms.randomTexture;
        },
        set: function (value) {
          generate.uniforms.randomTexture = value;
        },
      },
      delta: {
        get: function () {
          return blur.uniforms.delta;
        },
        set: function (value) {
          blur.uniforms.delta = value;
        },
      },
      sigma: {
        get: function () {
          return blur.uniforms.sigma;
        },
        set: function (value) {
          blur.uniforms.sigma = value;
        },
      },
      blurStepSize: {
        get: function () {
          return blur.uniforms.stepSize;
        },
        set: function (value) {
          blur.uniforms.stepSize = value;
        },
      },
      ambientOcclusionOnly: {
        get: function () {
          return ambientOcclusionModulate.uniforms.ambientOcclusionOnly;
        },
        set: function (value) {
          ambientOcclusionModulate.uniforms.ambientOcclusionOnly = value;
        },
      },
    });

    return new PostProcessStageComposite({
      name: "czm_ambient_occlusion",
      stages: [generateAndBlur, ambientOcclusionModulate],
      inputPreviousStageTexture: false,
      uniforms: uniforms,
    });
  };

  /**
   * Whether or not an ambient occlusion stage is supported.
   * <p>
   * This stage requires the WEBGL_depth_texture extension.
   * </p>
   *
   * @param {Scene} scene The scene.
   * @return {Boolean} Whether this post process stage is supported.
   *
   * @see {Context#depthTexture}
   * @see {@link http://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/|WEBGL_depth_texture}
   */
  PostProcessStageLibrary.isAmbientOcclusionSupported = function (scene) {
    return scene.context.depthTexture;
  };

  const fxaaFS = `#define FXAA_QUALITY_PRESET 39 \n${FXAA3_11}\n${FXAA}`;

  /**
   * Creates a post-process stage that applies Fast Approximate Anti-aliasing (FXAA) to the input texture.
   * @return {PostProcessStage} A post-process stage that applies Fast Approximate Anti-aliasing to the input texture.
   *
   * @private
   */
  PostProcessStageLibrary.createFXAAStage = function () {
    return new PostProcessStage({
      name: "czm_FXAA",
      fragmentShader: fxaaFS,
      sampleMode: PostProcessStageSampleMode.LINEAR,
    });
  };

  /**
   * Creates a post-process stage that applies ACES tonemapping operator.
   * @param {Boolean} useAutoExposure Whether or not to use auto-exposure.
   * @return {PostProcessStage} A post-process stage that applies ACES tonemapping operator.
   * @private
   */
  PostProcessStageLibrary.createAcesTonemappingStage = function (
    useAutoExposure
  ) {
    let fs = useAutoExposure ? "#define AUTO_EXPOSURE\n" : "";
    fs += AcesTonemapping;
    return new PostProcessStage({
      name: "czm_aces",
      fragmentShader: fs,
      uniforms: {
        autoExposure: undefined,
      },
    });
  };

  /**
   * Creates a post-process stage that applies filmic tonemapping operator.
   * @param {Boolean} useAutoExposure Whether or not to use auto-exposure.
   * @return {PostProcessStage} A post-process stage that applies filmic tonemapping operator.
   * @private
   */
  PostProcessStageLibrary.createFilmicTonemappingStage = function (
    useAutoExposure
  ) {
    let fs = useAutoExposure ? "#define AUTO_EXPOSURE\n" : "";
    fs += FilmicTonemapping;
    return new PostProcessStage({
      name: "czm_filmic",
      fragmentShader: fs,
      uniforms: {
        autoExposure: undefined,
      },
    });
  };

  /**
   * Creates a post-process stage that applies Reinhard tonemapping operator.
   * @param {Boolean} useAutoExposure Whether or not to use auto-exposure.
   * @return {PostProcessStage} A post-process stage that applies Reinhard tonemapping operator.
   * @private
   */
  PostProcessStageLibrary.createReinhardTonemappingStage = function (
    useAutoExposure
  ) {
    let fs = useAutoExposure ? "#define AUTO_EXPOSURE\n" : "";
    fs += ReinhardTonemapping;
    return new PostProcessStage({
      name: "czm_reinhard",
      fragmentShader: fs,
      uniforms: {
        autoExposure: undefined,
      },
    });
  };

  /**
   * Creates a post-process stage that applies modified Reinhard tonemapping operator.
   * @param {Boolean} useAutoExposure Whether or not to use auto-exposure.
   * @return {PostProcessStage} A post-process stage that applies modified Reinhard tonemapping operator.
   * @private
   */
  PostProcessStageLibrary.createModifiedReinhardTonemappingStage = function (
    useAutoExposure
  ) {
    let fs = useAutoExposure ? "#define AUTO_EXPOSURE\n" : "";
    fs += ModifiedReinhardTonemapping;
    return new PostProcessStage({
      name: "czm_modified_reinhard",
      fragmentShader: fs,
      uniforms: {
        white: Color.WHITE,
        autoExposure: undefined,
      },
    });
  };

  /**
   * Creates a post-process stage that finds the average luminance of the input texture.
   * @return {PostProcessStage} A post-process stage that finds the average luminance of the input texture.
   * @private
   */
  PostProcessStageLibrary.createAutoExposureStage = function () {
    return new AutoExposure();
  };

  /**
   * Creates a post-process stage that renders the input texture with black and white gradations.
   * <p>
   * This stage has one uniform value, <code>gradations</code>, which scales the luminance of each pixel.
   * </p>
   * @return {PostProcessStage} A post-process stage that renders the input texture with black and white gradations.
   */
  PostProcessStageLibrary.createBlackAndWhiteStage = function () {
    return new PostProcessStage({
      name: "czm_black_and_white",
      fragmentShader: BlackAndWhite,
      uniforms: {
        gradations: 5.0,
      },
    });
  };

  /**
   * Creates a post-process stage that saturates the input texture.
   * <p>
   * This stage has one uniform value, <code>brightness</code>, which scales the saturation of each pixel.
   * </p>
   * @return {PostProcessStage} A post-process stage that saturates the input texture.
   */
  PostProcessStageLibrary.createBrightnessStage = function () {
    return new PostProcessStage({
      name: "czm_brightness",
      fragmentShader: Brightness,
      uniforms: {
        brightness: 0.5,
      },
    });
  };

  /**
   * Creates a post-process stage that adds a night vision effect to the input texture.
   * @return {PostProcessStage} A post-process stage that adds a night vision effect to the input texture.
   */
  PostProcessStageLibrary.createNightVisionStage = function () {
    return new PostProcessStage({
      name: "czm_night_vision",
      fragmentShader: NightVision,
    });
  };

  /**
   * Creates a post-process stage that replaces the input color texture with a black and white texture representing the fragment depth at each pixel.
   * @return {PostProcessStage} A post-process stage that replaces the input color texture with a black and white texture representing the fragment depth at each pixel.
   *
   * @private
   */
  PostProcessStageLibrary.createDepthViewStage = function () {
    return new PostProcessStage({
      name: "czm_depth_view",
      fragmentShader: DepthView,
    });
  };

  /**
   * Creates a post-process stage that applies an effect simulating light flaring a camera lens.
   * <p>
   * This stage has the following uniforms: <code>dirtTexture</code>, <code>starTexture</code>, <code>intensity</code>, <code>distortion</code>, <code>ghostDispersal</code>,
   * <code>haloWidth</code>, <code>dirtAmount</code>, and <code>earthRadius</code>.
   * <ul>
   * <li><code>dirtTexture</code> is a texture sampled to simulate dirt on the lens.</li>
   * <li><code>starTexture</code> is the texture sampled for the star pattern of the flare.</li>
   * <li><code>intensity</code> is a scalar multiplied by the result of the lens flare. The default value is <code>2.0</code>.</li>
   * <li><code>distortion</code> is a scalar value that affects the chromatic effect distortion. The default value is <code>10.0</code>.</li>
   * <li><code>ghostDispersal</code> is a scalar indicating how far the halo effect is from the center of the texture. The default value is <code>0.4</code>.</li>
   * <li><code>haloWidth</code> is a scalar representing the width of the halo  from the ghost dispersal. The default value is <code>0.4</code>.</li>
   * <li><code>dirtAmount</code> is a scalar representing the amount of dirt on the lens. The default value is <code>0.4</code>.</li>
   * <li><code>earthRadius</code> is the maximum radius of the earth. The default value is <code>Ellipsoid.WGS84.maximumRadius</code>.</li>
   * </ul>
   * </p>
   * @return {PostProcessStage} A post-process stage for applying a lens flare effect.
   */
  PostProcessStageLibrary.createLensFlareStage = function () {
    return new PostProcessStage({
      name: "czm_lens_flare",
      fragmentShader: LensFlare,
      uniforms: {
        dirtTexture: buildModuleUrl("Assets/Textures/LensFlare/DirtMask.jpg"),
        starTexture: buildModuleUrl("Assets/Textures/LensFlare/StarBurst.jpg"),
        intensity: 2.0,
        distortion: 10.0,
        ghostDispersal: 0.4,
        haloWidth: 0.4,
        dirtAmount: 0.4,
        earthRadius: Ellipsoid.WGS84.maximumRadius,
      },
    });
  };

  /**
   * Creates a minimal amount of textures and framebuffers.
   *
   * @alias PostProcessStageTextureCache
   * @constructor
   *
   * @param {PostProcessStageCollection} postProcessStageCollection The post process collection.
   *
   * @private
   */
  function PostProcessStageTextureCache(postProcessStageCollection) {
    this._collection = postProcessStageCollection;

    this._framebuffers = [];
    this._stageNameToFramebuffer = {};

    this._width = undefined;
    this._height = undefined;
    this._updateDependencies = false;
  }

  function getLastStageName(stage) {
    while (defined(stage.length)) {
      stage = stage.get(stage.length - 1);
    }
    return stage.name;
  }

  function getStageDependencies(
    collection,
    context,
    dependencies,
    stage,
    previousName
  ) {
    if (!stage.enabled || !stage._isSupported(context)) {
      return previousName;
    }

    const stageDependencies = (dependencies[stage.name] = {});
    if (defined(previousName)) {
      const previous = collection.getStageByName(previousName);
      stageDependencies[getLastStageName(previous)] = true;
    }
    const uniforms = stage.uniforms;
    if (defined(uniforms)) {
      const uniformNames = Object.getOwnPropertyNames(uniforms);
      const uniformNamesLength = uniformNames.length;
      for (let i = 0; i < uniformNamesLength; ++i) {
        const value = uniforms[uniformNames[i]];
        if (typeof value === "string") {
          const dependent = collection.getStageByName(value);
          if (defined(dependent)) {
            stageDependencies[getLastStageName(dependent)] = true;
          }
        }
      }
    }

    return stage.name;
  }

  function getCompositeDependencies(
    collection,
    context,
    dependencies,
    composite,
    previousName
  ) {
    if (
      (defined(composite.enabled) && !composite.enabled) ||
      (defined(composite._isSupported) && !composite._isSupported(context))
    ) {
      return previousName;
    }

    const originalDependency = previousName;

    const inSeries =
      !defined(composite.inputPreviousStageTexture) ||
      composite.inputPreviousStageTexture;
    let currentName = previousName;
    const length = composite.length;
    for (let i = 0; i < length; ++i) {
      const stage = composite.get(i);
      if (defined(stage.length)) {
        currentName = getCompositeDependencies(
          collection,
          context,
          dependencies,
          stage,
          previousName
        );
      } else {
        currentName = getStageDependencies(
          collection,
          context,
          dependencies,
          stage,
          previousName
        );
      }
      // Stages in a series only depend on the previous stage
      if (inSeries) {
        previousName = currentName;
      }
    }

    // Stages not in a series depend on every stage executed before it since it could reference it as a uniform.
    // This prevents looking at the dependencies of each stage in the composite, but might create more framebuffers than necessary.
    // In practice, there are only 2-3 stages in these composites.
    let j;
    let name;
    if (!inSeries) {
      for (j = 1; j < length; ++j) {
        name = getLastStageName(composite.get(j));
        const currentDependencies = dependencies[name];
        for (let k = 0; k < j; ++k) {
          currentDependencies[getLastStageName(composite.get(k))] = true;
        }
      }
    } else {
      for (j = 1; j < length; ++j) {
        name = getLastStageName(composite.get(j));
        if (!defined(dependencies[name])) {
          dependencies[name] = {};
        }
        dependencies[name][originalDependency] = true;
      }
    }

    return currentName;
  }

  function getDependencies(collection, context) {
    const dependencies = {};

    if (defined(collection.ambientOcclusion)) {
      const ao = collection.ambientOcclusion;
      const bloom = collection.bloom;
      const tonemapping = collection._tonemapping;
      const fxaa = collection.fxaa;

      let previousName = getCompositeDependencies(
        collection,
        context,
        dependencies,
        ao,
        undefined
      );
      previousName = getCompositeDependencies(
        collection,
        context,
        dependencies,
        bloom,
        previousName
      );
      previousName = getStageDependencies(
        collection,
        context,
        dependencies,
        tonemapping,
        previousName
      );
      previousName = getCompositeDependencies(
        collection,
        context,
        dependencies,
        collection,
        previousName
      );
      getStageDependencies(collection, context, dependencies, fxaa, previousName);
    } else {
      getCompositeDependencies(
        collection,
        context,
        dependencies,
        collection,
        undefined
      );
    }

    return dependencies;
  }

  function getFramebuffer(cache, stageName, dependencies) {
    const collection = cache._collection;
    const stage = collection.getStageByName(stageName);

    const textureScale = stage._textureScale;
    const forcePowerOfTwo = stage._forcePowerOfTwo;
    const pixelFormat = stage._pixelFormat;
    const pixelDatatype = stage._pixelDatatype;
    const clearColor = stage._clearColor;

    let i;
    let framebuffer;
    const framebuffers = cache._framebuffers;
    const length = framebuffers.length;
    for (i = 0; i < length; ++i) {
      framebuffer = framebuffers[i];

      if (
        textureScale !== framebuffer.textureScale ||
        forcePowerOfTwo !== framebuffer.forcePowerOfTwo ||
        pixelFormat !== framebuffer.pixelFormat ||
        pixelDatatype !== framebuffer.pixelDatatype ||
        !Color.equals(clearColor, framebuffer.clearColor)
      ) {
        continue;
      }

      const stageNames = framebuffer.stages;
      const stagesLength = stageNames.length;
      let foundConflict = false;
      for (let j = 0; j < stagesLength; ++j) {
        if (dependencies[stageNames[j]]) {
          foundConflict = true;
          break;
        }
      }

      if (!foundConflict) {
        break;
      }
    }

    if (defined(framebuffer) && i < length) {
      framebuffer.stages.push(stageName);
      return framebuffer;
    }

    framebuffer = {
      textureScale: textureScale,
      forcePowerOfTwo: forcePowerOfTwo,
      pixelFormat: pixelFormat,
      pixelDatatype: pixelDatatype,
      clearColor: clearColor,
      stages: [stageName],
      buffer: new FramebufferManager({
        pixelFormat: pixelFormat,
        pixelDatatype: pixelDatatype,
      }),
      clear: undefined,
    };

    framebuffers.push(framebuffer);
    return framebuffer;
  }

  function createFramebuffers(cache, context) {
    const dependencies = getDependencies(cache._collection, context);
    for (const stageName in dependencies) {
      if (dependencies.hasOwnProperty(stageName)) {
        cache._stageNameToFramebuffer[stageName] = getFramebuffer(
          cache,
          stageName,
          dependencies[stageName]
        );
      }
    }
  }

  function releaseResources(cache) {
    const framebuffers = cache._framebuffers;
    const length = framebuffers.length;
    for (let i = 0; i < length; ++i) {
      const framebuffer = framebuffers[i];
      framebuffer.buffer.destroy();
    }
  }

  function updateFramebuffers(cache, context) {
    const width = cache._width;
    const height = cache._height;

    const framebuffers = cache._framebuffers;
    const length = framebuffers.length;
    for (let i = 0; i < length; ++i) {
      const framebuffer = framebuffers[i];

      const scale = framebuffer.textureScale;
      let textureWidth = Math.ceil(width * scale);
      let textureHeight = Math.ceil(height * scale);

      let size = Math.min(textureWidth, textureHeight);
      if (framebuffer.forcePowerOfTwo) {
        if (!CesiumMath.isPowerOfTwo(size)) {
          size = CesiumMath.nextPowerOfTwo(size);
        }
        textureWidth = size;
        textureHeight = size;
      }

      framebuffer.buffer.update(context, textureWidth, textureHeight);
      framebuffer.clear = new ClearCommand({
        color: framebuffer.clearColor,
        framebuffer: framebuffer.buffer.framebuffer,
      });
    }
  }

  PostProcessStageTextureCache.prototype.updateDependencies = function () {
    this._updateDependencies = true;
  };

  /**
   * Called before the stages in the collection are executed. Creates the minimum amount of framebuffers for a post-process collection.
   *
   * @param {Context} context The context.
   */
  PostProcessStageTextureCache.prototype.update = function (context) {
    const collection = this._collection;
    const updateDependencies = this._updateDependencies;
    const aoEnabled =
      defined(collection.ambientOcclusion) &&
      collection.ambientOcclusion.enabled &&
      collection.ambientOcclusion._isSupported(context);
    const bloomEnabled =
      defined(collection.bloom) &&
      collection.bloom.enabled &&
      collection.bloom._isSupported(context);
    const tonemappingEnabled =
      defined(collection._tonemapping) &&
      collection._tonemapping.enabled &&
      collection._tonemapping._isSupported(context);
    const fxaaEnabled =
      defined(collection.fxaa) &&
      collection.fxaa.enabled &&
      collection.fxaa._isSupported(context);
    const needsCheckDimensionsUpdate =
      !defined(collection._activeStages) ||
      collection._activeStages.length > 0 ||
      aoEnabled ||
      bloomEnabled ||
      tonemappingEnabled ||
      fxaaEnabled;
    if (
      updateDependencies ||
      (!needsCheckDimensionsUpdate && this._framebuffers.length > 0)
    ) {
      releaseResources(this);
      this._framebuffers.length = 0;
      this._stageNameToFramebuffer = {};
      this._width = undefined;
      this._height = undefined;
    }

    if (!updateDependencies && !needsCheckDimensionsUpdate) {
      return;
    }

    if (this._framebuffers.length === 0) {
      createFramebuffers(this, context);
    }

    const width = context.drawingBufferWidth;
    const height = context.drawingBufferHeight;
    const dimensionsChanged = this._width !== width || this._height !== height;
    if (!updateDependencies && !dimensionsChanged) {
      return;
    }

    this._width = width;
    this._height = height;
    this._updateDependencies = false;
    releaseResources(this);
    updateFramebuffers(this, context);
  };

  /**
   * Clears all of the framebuffers.
   *
   * @param {Context} context The context.
   */
  PostProcessStageTextureCache.prototype.clear = function (context) {
    const framebuffers = this._framebuffers;
    for (let i = 0; i < framebuffers.length; ++i) {
      framebuffers[i].clear.execute(context);
    }
  };

  /**
   * Gets the stage with the given name.
   * @param {String} name The name of the stage.
   * @return {PostProcessStage|PostProcessStageComposite}
   */
  PostProcessStageTextureCache.prototype.getStageByName = function (name) {
    return this._collection.getStageByName(name);
  };

  /**
   * Gets the output texture for a stage with the given name.
   * @param {String} name The name of the stage.
   * @return {Texture|undefined} The output texture of the stage with the given name.
   */
  PostProcessStageTextureCache.prototype.getOutputTexture = function (name) {
    return this._collection.getOutputTexture(name);
  };

  /**
   * Gets the framebuffer for a stage with the given name.
   *
   * @param {String} name The name of the stage.
   * @return {Framebuffer|undefined} The framebuffer for the stage with the given name.
   */
  PostProcessStageTextureCache.prototype.getFramebuffer = function (name) {
    const framebuffer = this._stageNameToFramebuffer[name];
    if (!defined(framebuffer)) {
      return undefined;
    }
    return framebuffer.buffer.framebuffer;
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <p>
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   * </p>
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see PostProcessStageTextureCache#destroy
   */
  PostProcessStageTextureCache.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <p>
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   * </p>
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @see PostProcessStageTextureCache#isDestroyed
   */
  PostProcessStageTextureCache.prototype.destroy = function () {
    releaseResources(this);
    return destroyObject(this);
  };

  /**
   * A tonemapping algorithm when rendering with high dynamic range.
   *
   * @enum {Number}
   * @private
   */
  const Tonemapper = {
    /**
     * Use the Reinhard tonemapping operator.
     *
     * @type {Number}
     * @constant
     */
    REINHARD: 0,

    /**
     * Use the modified Reinhard tonemapping operator.
     *
     * @type {Number}
     * @constant
     */
    MODIFIED_REINHARD: 1,

    /**
     * Use the Filmic tonemapping operator.
     *
     * @type {Number}
     * @constant
     */
    FILMIC: 2,

    /**
     * Use the ACES tonemapping operator.
     *
     * @type {Number}
     * @constant
     */
    ACES: 3,

    /**
     * @private
     */
    validate: function (tonemapper) {
      return (
        tonemapper === Tonemapper.REINHARD ||
        tonemapper === Tonemapper.MODIFIED_REINHARD ||
        tonemapper === Tonemapper.FILMIC ||
        tonemapper === Tonemapper.ACES
      );
    },
  };
  var Tonemapper$1 = Object.freeze(Tonemapper);

  const stackScratch = [];

  /**
   * A collection of {@link PostProcessStage}s and/or {@link PostProcessStageComposite}s.
   * <p>
   * The input texture for each post-process stage is the texture rendered to by the scene or the texture rendered
   * to by the previous stage in the collection.
   * </p>
   * <p>
   * If the ambient occlusion or bloom stages are enabled, they will execute before all other stages.
   * </p>
   * <p>
   * If the FXAA stage is enabled, it will execute after all other stages.
   * </p>
   *
   * @alias PostProcessStageCollection
   * @constructor
   */
  function PostProcessStageCollection() {
    const fxaa = PostProcessStageLibrary.createFXAAStage();
    const ao = PostProcessStageLibrary.createAmbientOcclusionStage();
    const bloom = PostProcessStageLibrary.createBloomStage();

    // Auto-exposure is currently disabled because most shaders output a value in [0.0, 1.0].
    // Some shaders, such as the atmosphere and ground atmosphere, output values slightly over 1.0.
    this._autoExposureEnabled = false;
    this._autoExposure = PostProcessStageLibrary.createAutoExposureStage();
    this._tonemapping = undefined;
    this._tonemapper = undefined;

    // set tonemapper and tonemapping
    this.tonemapper = Tonemapper$1.ACES;

    const tonemapping = this._tonemapping;

    fxaa.enabled = false;
    ao.enabled = false;
    bloom.enabled = false;
    tonemapping.enabled = false; // will be enabled if necessary in update

    const textureCache = new PostProcessStageTextureCache(this);

    const stageNames = {};
    const stack = stackScratch;
    stack.push(fxaa, ao, bloom, tonemapping);
    while (stack.length > 0) {
      const stage = stack.pop();
      stageNames[stage.name] = stage;
      stage._textureCache = textureCache;

      const length = stage.length;
      if (defined(length)) {
        for (let i = 0; i < length; ++i) {
          stack.push(stage.get(i));
        }
      }
    }

    this._stages = [];
    this._activeStages = [];
    this._previousActiveStages = [];

    this._randomTexture = undefined; // For AO

    const that = this;
    ao.uniforms.randomTexture = function () {
      return that._randomTexture;
    };

    this._ao = ao;
    this._bloom = bloom;
    this._fxaa = fxaa;

    this._aoEnabled = undefined;
    this._bloomEnabled = undefined;
    this._tonemappingEnabled = undefined;
    this._fxaaEnabled = undefined;

    this._activeStagesChanged = false;
    this._stagesRemoved = false;
    this._textureCacheDirty = false;

    this._stageNames = stageNames;
    this._textureCache = textureCache;
  }

  Object.defineProperties(PostProcessStageCollection.prototype, {
    /**
     * Determines if all of the post-process stages in the collection are ready to be executed.
     *
     * @memberof PostProcessStageCollection.prototype
     * @type {Boolean}
     * @readonly
     */
    ready: {
      get: function () {
        let readyAndEnabled = false;
        const stages = this._stages;
        const length = stages.length;
        for (let i = length - 1; i >= 0; --i) {
          const stage = stages[i];
          readyAndEnabled = readyAndEnabled || (stage.ready && stage.enabled);
        }

        const fxaa = this._fxaa;
        const ao = this._ao;
        const bloom = this._bloom;
        const tonemapping = this._tonemapping;

        readyAndEnabled = readyAndEnabled || (fxaa.ready && fxaa.enabled);
        readyAndEnabled = readyAndEnabled || (ao.ready && ao.enabled);
        readyAndEnabled = readyAndEnabled || (bloom.ready && bloom.enabled);
        readyAndEnabled =
          readyAndEnabled || (tonemapping.ready && tonemapping.enabled);

        return readyAndEnabled;
      },
    },
    /**
     * A post-process stage for Fast Approximate Anti-aliasing.
     * <p>
     * When enabled, this stage will execute after all others.
     * </p>
     *
     * @memberof PostProcessStageCollection.prototype
     * @type {PostProcessStage}
     * @readonly
     */
    fxaa: {
      get: function () {
        return this._fxaa;
      },
    },
    /**
     * A post-process stage that applies Horizon-based Ambient Occlusion (HBAO) to the input texture.
     * <p>
     * Ambient occlusion simulates shadows from ambient light. These shadows would always be present when the
     * surface receives light and regardless of the light's position.
     * </p>
     * <p>
     * The uniforms have the following properties: <code>intensity</code>, <code>bias</code>, <code>lengthCap</code>,
     * <code>stepSize</code>, <code>frustumLength</code>, <code>ambientOcclusionOnly</code>,
     * <code>delta</code>, <code>sigma</code>, and <code>blurStepSize</code>.
     * </p>
     * <ul>
     * <li><code>intensity</code> is a scalar value used to lighten or darken the shadows exponentially. Higher values make the shadows darker. The default value is <code>3.0</code>.</li>
     *
     * <li><code>bias</code> is a scalar value representing an angle in radians. If the dot product between the normal of the sample and the vector to the camera is less than this value,
     * sampling stops in the current direction. This is used to remove shadows from near planar edges. The default value is <code>0.1</code>.</li>
     *
     * <li><code>lengthCap</code> is a scalar value representing a length in meters. If the distance from the current sample to first sample is greater than this value,
     * sampling stops in the current direction. The default value is <code>0.26</code>.</li>
     *
     * <li><code>stepSize</code> is a scalar value indicating the distance to the next texel sample in the current direction. The default value is <code>1.95</code>.</li>
     *
     * <li><code>frustumLength</code> is a scalar value in meters. If the current fragment has a distance from the camera greater than this value, ambient occlusion is not computed for the fragment.
     * The default value is <code>1000.0</code>.</li>
     *
     * <li><code>ambientOcclusionOnly</code> is a boolean value. When <code>true</code>, only the shadows generated are written to the output. When <code>false</code>, the input texture is modulated
     * with the ambient occlusion. This is a useful debug option for seeing the effects of changing the uniform values. The default value is <code>false</code>.</li>
     * </ul>
     * <p>
     * <code>delta</code>, <code>sigma</code>, and <code>blurStepSize</code> are the same properties as {@link PostProcessStageLibrary#createBlurStage}.
     * The blur is applied to the shadows generated from the image to make them smoother.
     * </p>
     * <p>
     * When enabled, this stage will execute before all others.
     * </p>
     *
     * @memberof PostProcessStageCollection.prototype
     * @type {PostProcessStageComposite}
     * @readonly
     */
    ambientOcclusion: {
      get: function () {
        return this._ao;
      },
    },
    /**
     * A post-process stage for a bloom effect.
     * <p>
     * A bloom effect adds glow effect, makes bright areas brighter, and dark areas darker.
     * </p>
     * <p>
     * This stage has the following uniforms: <code>contrast</code>, <code>brightness</code>, <code>glowOnly</code>,
     * <code>delta</code>, <code>sigma</code>, and <code>stepSize</code>.
     * </p>
     * <ul>
     * <li><code>contrast</code> is a scalar value in the range [-255.0, 255.0] and affects the contract of the effect. The default value is <code>128.0</code>.</li>
     *
     * <li><code>brightness</code> is a scalar value. The input texture RGB value is converted to hue, saturation, and brightness (HSB) then this value is
     * added to the brightness. The default value is <code>-0.3</code>.</li>
     *
     * <li><code>glowOnly</code> is a boolean value. When <code>true</code>, only the glow effect will be shown. When <code>false</code>, the glow will be added to the input texture.
     * The default value is <code>false</code>. This is a debug option for viewing the effects when changing the other uniform values.</li>
     * </ul>
     * <p>
     * <code>delta</code>, <code>sigma</code>, and <code>stepSize</code> are the same properties as {@link PostProcessStageLibrary#createBlurStage}.
     * The blur is applied to the shadows generated from the image to make them smoother.
     * </p>
     * <p>
     * When enabled, this stage will execute before all others.
     * </p>
     *
     * @memberOf PostProcessStageCollection.prototype
     * @type {PostProcessStageComposite}
     * @readonly
     */
    bloom: {
      get: function () {
        return this._bloom;
      },
    },
    /**
     * The number of post-process stages in this collection.
     *
     * @memberof PostProcessStageCollection.prototype
     * @type {Number}
     * @readonly
     */
    length: {
      get: function () {
        removeStages(this);
        return this._stages.length;
      },
    },
    /**
     * A reference to the last texture written to when executing the post-process stages in this collection.
     *
     * @memberof PostProcessStageCollection.prototype
     * @type {Texture}
     * @readonly
     * @private
     */
    outputTexture: {
      get: function () {
        const fxaa = this._fxaa;
        if (fxaa.enabled && fxaa.ready) {
          return this.getOutputTexture(fxaa.name);
        }

        const stages = this._stages;
        const length = stages.length;
        for (let i = length - 1; i >= 0; --i) {
          const stage = stages[i];
          if (defined(stage) && stage.ready && stage.enabled) {
            return this.getOutputTexture(stage.name);
          }
        }

        const tonemapping = this._tonemapping;
        if (tonemapping.enabled && tonemapping.ready) {
          return this.getOutputTexture(tonemapping.name);
        }

        const bloom = this._bloom;
        if (bloom.enabled && bloom.ready) {
          return this.getOutputTexture(bloom.name);
        }

        const ao = this._ao;
        if (ao.enabled && ao.ready) {
          return this.getOutputTexture(ao.name);
        }

        return undefined;
      },
    },
    /**
     * Whether the collection has a stage that has selected features.
     *
     * @memberof PostProcessStageCollection.prototype
     * @type {Boolean}
     * @readonly
     * @private
     */
    hasSelected: {
      get: function () {
        const stages = this._stages.slice();
        while (stages.length > 0) {
          const stage = stages.pop();
          if (!defined(stage)) {
            continue;
          }
          if (defined(stage.selected)) {
            return true;
          }
          const length = stage.length;
          if (defined(length)) {
            for (let i = 0; i < length; ++i) {
              stages.push(stage.get(i));
            }
          }
        }
        return false;
      },
    },

    /**
     * Gets and sets the tonemapping algorithm used when rendering with high dynamic range.
     *
     * @memberof PostProcessStageCollection.prototype
     * @type {Tonemapper}
     * @private
     */
    tonemapper: {
      get: function () {
        return this._tonemapper;
      },
      set: function (value) {
        if (this._tonemapper === value) {
          return;
        }
        //>>includeStart('debug', pragmas.debug);
        if (!Tonemapper$1.validate(value)) {
          throw new DeveloperError("tonemapper was set to an invalid value.");
        }
        //>>includeEnd('debug');

        if (defined(this._tonemapping)) {
          delete this._stageNames[this._tonemapping.name];
          this._tonemapping.destroy();
        }

        const useAutoExposure = this._autoExposureEnabled;
        let tonemapper;

        switch (value) {
          case Tonemapper$1.REINHARD:
            tonemapper = PostProcessStageLibrary.createReinhardTonemappingStage(
              useAutoExposure
            );
            break;
          case Tonemapper$1.MODIFIED_REINHARD:
            tonemapper = PostProcessStageLibrary.createModifiedReinhardTonemappingStage(
              useAutoExposure
            );
            break;
          case Tonemapper$1.FILMIC:
            tonemapper = PostProcessStageLibrary.createFilmicTonemappingStage(
              useAutoExposure
            );
            break;
          default:
            tonemapper = PostProcessStageLibrary.createAcesTonemappingStage(
              useAutoExposure
            );
            break;
        }

        if (useAutoExposure) {
          const autoexposure = this._autoExposure;
          tonemapper.uniforms.autoExposure = function () {
            return autoexposure.outputTexture;
          };
        }

        this._tonemapper = value;
        this._tonemapping = tonemapper;

        if (defined(this._stageNames)) {
          this._stageNames[tonemapper.name] = tonemapper;
          tonemapper._textureCache = this._textureCache;
        }

        this._textureCacheDirty = true;
      },
    },
  });

  function removeStages(collection) {
    if (!collection._stagesRemoved) {
      return;
    }

    collection._stagesRemoved = false;

    const newStages = [];
    const stages = collection._stages;
    const length = stages.length;
    for (let i = 0, j = 0; i < length; ++i) {
      const stage = stages[i];
      if (stage) {
        stage._index = j++;
        newStages.push(stage);
      }
    }

    collection._stages = newStages;
  }

  /**
   * Adds the post-process stage to the collection.
   *
   * @param {PostProcessStage|PostProcessStageComposite} stage The post-process stage to add to the collection.
   * @return {PostProcessStage|PostProcessStageComposite} The post-process stage that was added to the collection.
   *
   * @exception {DeveloperError} The post-process stage has already been added to the collection or does not have a unique name.
   */
  PostProcessStageCollection.prototype.add = function (stage) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("stage", stage);
    //>>includeEnd('debug');

    const stageNames = this._stageNames;

    const stack = stackScratch;
    stack.push(stage);
    while (stack.length > 0) {
      const currentStage = stack.pop();
      //>>includeStart('debug', pragmas.debug);
      if (defined(stageNames[currentStage.name])) {
        throw new DeveloperError(
          `${currentStage.name} has already been added to the collection or does not have a unique name.`
        );
      }
      //>>includeEnd('debug');
      stageNames[currentStage.name] = currentStage;
      currentStage._textureCache = this._textureCache;

      const length = currentStage.length;
      if (defined(length)) {
        for (let i = 0; i < length; ++i) {
          stack.push(currentStage.get(i));
        }
      }
    }

    const stages = this._stages;
    stage._index = stages.length;
    stages.push(stage);
    this._textureCacheDirty = true;
    return stage;
  };

  /**
   * Removes a post-process stage from the collection and destroys it.
   *
   * @param {PostProcessStage|PostProcessStageComposite} stage The post-process stage to remove from the collection.
   * @return {Boolean} Whether the post-process stage was removed.
   */
  PostProcessStageCollection.prototype.remove = function (stage) {
    if (!this.contains(stage)) {
      return false;
    }

    const stageNames = this._stageNames;

    const stack = stackScratch;
    stack.push(stage);
    while (stack.length > 0) {
      const currentStage = stack.pop();
      delete stageNames[currentStage.name];

      const length = currentStage.length;
      if (defined(length)) {
        for (let i = 0; i < length; ++i) {
          stack.push(currentStage.get(i));
        }
      }
    }

    this._stages[stage._index] = undefined;
    this._stagesRemoved = true;
    this._textureCacheDirty = true;
    stage._index = undefined;
    stage._textureCache = undefined;
    stage.destroy();
    return true;
  };

  /**
   * Returns whether the collection contains a post-process stage.
   *
   * @param {PostProcessStage|PostProcessStageComposite} stage The post-process stage.
   * @return {Boolean} Whether the collection contains the post-process stage.
   */
  PostProcessStageCollection.prototype.contains = function (stage) {
    return (
      defined(stage) &&
      defined(stage._index) &&
      stage._textureCache === this._textureCache
    );
  };

  /**
   * Gets the post-process stage at <code>index</code>.
   *
   * @param {Number} index The index of the post-process stage.
   * @return {PostProcessStage|PostProcessStageComposite} The post-process stage at index.
   */
  PostProcessStageCollection.prototype.get = function (index) {
    removeStages(this);
    const stages = this._stages;
    //>>includeStart('debug', pragmas.debug);
    const length = stages.length;
    Check.typeOf.number.greaterThanOrEquals("stages length", length, 0);
    Check.typeOf.number.greaterThanOrEquals("index", index, 0);
    Check.typeOf.number.lessThan("index", index, length);
    //>>includeEnd('debug');
    return stages[index];
  };

  /**
   * Removes all post-process stages from the collection and destroys them.
   */
  PostProcessStageCollection.prototype.removeAll = function () {
    const stages = this._stages;
    const length = stages.length;
    for (let i = 0; i < length; ++i) {
      this.remove(stages[i]);
    }
    stages.length = 0;
  };

  /**
   * Gets a post-process stage in the collection by its name.
   *
   * @param {String} name The name of the post-process stage.
   * @return {PostProcessStage|PostProcessStageComposite} The post-process stage.
   *
   * @private
   */
  PostProcessStageCollection.prototype.getStageByName = function (name) {
    return this._stageNames[name];
  };

  /**
   * Called before the post-process stages in the collection are executed. Calls update for each stage and creates WebGL resources.
   *
   * @param {Context} context The context.
   * @param {Boolean} useLogDepth Whether the scene uses a logarithmic depth buffer.
   *
   * @private
   */
  PostProcessStageCollection.prototype.update = function (
    context,
    useLogDepth,
    useHdr
  ) {
    removeStages(this);

    const previousActiveStages = this._activeStages;
    const activeStages = (this._activeStages = this._previousActiveStages);
    this._previousActiveStages = previousActiveStages;

    const stages = this._stages;
    let length = (activeStages.length = stages.length);

    let i;
    let stage;
    let count = 0;
    for (i = 0; i < length; ++i) {
      stage = stages[i];
      if (stage.ready && stage.enabled && stage._isSupported(context)) {
        activeStages[count++] = stage;
      }
    }

    activeStages.length = count;

    let activeStagesChanged = count !== previousActiveStages.length;
    if (!activeStagesChanged) {
      for (i = 0; i < count; ++i) {
        if (activeStages[i] !== previousActiveStages[i]) {
          activeStagesChanged = true;
          break;
        }
      }
    }

    const ao = this._ao;
    const bloom = this._bloom;
    const autoexposure = this._autoExposure;
    const tonemapping = this._tonemapping;
    const fxaa = this._fxaa;

    tonemapping.enabled = useHdr;

    const aoEnabled = ao.enabled && ao._isSupported(context);
    const bloomEnabled = bloom.enabled && bloom._isSupported(context);
    const tonemappingEnabled =
      tonemapping.enabled && tonemapping._isSupported(context);
    const fxaaEnabled = fxaa.enabled && fxaa._isSupported(context);

    if (
      activeStagesChanged ||
      this._textureCacheDirty ||
      aoEnabled !== this._aoEnabled ||
      bloomEnabled !== this._bloomEnabled ||
      tonemappingEnabled !== this._tonemappingEnabled ||
      fxaaEnabled !== this._fxaaEnabled
    ) {
      // The number of stages to execute has changed.
      // Update dependencies and recreate framebuffers.
      this._textureCache.updateDependencies();

      this._aoEnabled = aoEnabled;
      this._bloomEnabled = bloomEnabled;
      this._tonemappingEnabled = tonemappingEnabled;
      this._fxaaEnabled = fxaaEnabled;
      this._textureCacheDirty = false;
    }

    if (defined(this._randomTexture) && !aoEnabled) {
      this._randomTexture.destroy();
      this._randomTexture = undefined;
    }

    if (!defined(this._randomTexture) && aoEnabled) {
      length = 256 * 256 * 3;
      const random = new Uint8Array(length);
      for (i = 0; i < length; i += 3) {
        random[i] = Math.floor(Math.random() * 255.0);
      }

      this._randomTexture = new Texture({
        context: context,
        pixelFormat: PixelFormat$1.RGB,
        pixelDatatype: PixelDatatype$1.UNSIGNED_BYTE,
        source: {
          arrayBufferView: random,
          width: 256,
          height: 256,
        },
        sampler: new Sampler({
          wrapS: TextureWrap$1.REPEAT,
          wrapT: TextureWrap$1.REPEAT,
          minificationFilter: TextureMinificationFilter$1.NEAREST,
          magnificationFilter: TextureMagnificationFilter$1.NEAREST,
        }),
      });
    }

    this._textureCache.update(context);

    fxaa.update(context, useLogDepth);
    ao.update(context, useLogDepth);
    bloom.update(context, useLogDepth);
    tonemapping.update(context, useLogDepth);

    if (this._autoExposureEnabled) {
      autoexposure.update(context, useLogDepth);
    }

    length = stages.length;
    for (i = 0; i < length; ++i) {
      stages[i].update(context, useLogDepth);
    }

    count = 0;
    for (i = 0; i < length; ++i) {
      stage = stages[i];
      if (stage.ready && stage.enabled && stage._isSupported(context)) {
        count++;
      }
    }

    activeStagesChanged = count !== activeStages.length;
    if (activeStagesChanged) {
      this.update(context, useLogDepth, useHdr);
    }
  };

  /**
   * Clears all of the framebuffers used by the stages.
   *
   * @param {Context} context The context.
   *
   * @private
   */
  PostProcessStageCollection.prototype.clear = function (context) {
    this._textureCache.clear(context);

    if (this._autoExposureEnabled) {
      this._autoExposure.clear(context);
    }
  };

  function getOutputTexture(stage) {
    while (defined(stage.length)) {
      stage = stage.get(stage.length - 1);
    }
    return stage.outputTexture;
  }

  /**
   * Gets the output texture of a stage with the given name.
   *
   * @param {String} stageName The name of the stage.
   * @return {Texture|undefined} The texture rendered to by the stage with the given name.
   *
   * @private
   */
  PostProcessStageCollection.prototype.getOutputTexture = function (stageName) {
    const stage = this.getStageByName(stageName);
    if (!defined(stage)) {
      return undefined;
    }
    return getOutputTexture(stage);
  };

  function execute(stage, context, colorTexture, depthTexture, idTexture) {
    if (defined(stage.execute)) {
      stage.execute(context, colorTexture, depthTexture, idTexture);
      return;
    }

    const length = stage.length;
    let i;

    if (stage.inputPreviousStageTexture) {
      execute(stage.get(0), context, colorTexture, depthTexture, idTexture);
      for (i = 1; i < length; ++i) {
        execute(
          stage.get(i),
          context,
          getOutputTexture(stage.get(i - 1)),
          depthTexture,
          idTexture
        );
      }
    } else {
      for (i = 0; i < length; ++i) {
        execute(stage.get(i), context, colorTexture, depthTexture, idTexture);
      }
    }
  }

  /**
   * Executes all ready and enabled stages in the collection.
   *
   * @param {Context} context The context.
   * @param {Texture} colorTexture The color texture rendered to by the scene.
   * @param {Texture} depthTexture The depth texture written to by the scene.
   * @param {Texture} idTexture The id texture written to by the scene.
   *
   * @private
   */
  PostProcessStageCollection.prototype.execute = function (
    context,
    colorTexture,
    depthTexture,
    idTexture
  ) {
    const activeStages = this._activeStages;
    const length = activeStages.length;
    const fxaa = this._fxaa;
    const ao = this._ao;
    const bloom = this._bloom;
    const autoexposure = this._autoExposure;
    const tonemapping = this._tonemapping;

    const aoEnabled = ao.enabled && ao._isSupported(context);
    const bloomEnabled = bloom.enabled && bloom._isSupported(context);
    const autoExposureEnabled = this._autoExposureEnabled;
    const tonemappingEnabled =
      tonemapping.enabled && tonemapping._isSupported(context);
    const fxaaEnabled = fxaa.enabled && fxaa._isSupported(context);

    if (
      !fxaaEnabled &&
      !aoEnabled &&
      !bloomEnabled &&
      !tonemappingEnabled &&
      length === 0
    ) {
      return;
    }

    let initialTexture = colorTexture;
    if (aoEnabled && ao.ready) {
      execute(ao, context, initialTexture, depthTexture, idTexture);
      initialTexture = getOutputTexture(ao);
    }
    if (bloomEnabled && bloom.ready) {
      execute(bloom, context, initialTexture, depthTexture, idTexture);
      initialTexture = getOutputTexture(bloom);
    }
    if (autoExposureEnabled && autoexposure.ready) {
      execute(autoexposure, context, initialTexture, depthTexture, idTexture);
    }
    if (tonemappingEnabled && tonemapping.ready) {
      execute(tonemapping, context, initialTexture, depthTexture, idTexture);
      initialTexture = getOutputTexture(tonemapping);
    }

    let lastTexture = initialTexture;

    if (length > 0) {
      execute(activeStages[0], context, initialTexture, depthTexture, idTexture);
      for (let i = 1; i < length; ++i) {
        execute(
          activeStages[i],
          context,
          getOutputTexture(activeStages[i - 1]),
          depthTexture,
          idTexture
        );
      }
      lastTexture = getOutputTexture(activeStages[length - 1]);
    }

    if (fxaaEnabled && fxaa.ready) {
      execute(fxaa, context, lastTexture, depthTexture, idTexture);
    }
  };

  /**
   * Copies the output of all executed stages to the color texture of a framebuffer.
   *
   * @param {Context} context The context.
   * @param {Framebuffer} framebuffer The framebuffer to copy to.
   *
   * @private
   */
  PostProcessStageCollection.prototype.copy = function (context, framebuffer) {
    if (!defined(this._copyColorCommand)) {
      const that = this;
      this._copyColorCommand = context.createViewportQuadCommand(PassThrough, {
        uniformMap: {
          colorTexture: function () {
            return that.outputTexture;
          },
        },
        owner: this,
      });
    }

    this._copyColorCommand.framebuffer = framebuffer;
    this._copyColorCommand.execute(context);
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <p>
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   * </p>
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see PostProcessStageCollection#destroy
   */
  PostProcessStageCollection.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <p>
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   * </p>
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @see PostProcessStageCollection#isDestroyed
   */
  PostProcessStageCollection.prototype.destroy = function () {
    this._fxaa.destroy();
    this._ao.destroy();
    this._bloom.destroy();
    this._autoExposure.destroy();
    this._tonemapping.destroy();
    this.removeAll();
    this._textureCache = this._textureCache && this._textureCache.destroy();
    return destroyObject(this);
  };

  /**
   * Provides general quadtree tiles to be displayed on or near the surface of an ellipsoid.  It is intended to be
   * used with the {@link QuadtreePrimitive}.  This type describes an interface and is not intended to be
   * instantiated directly.
   *
   * @alias QuadtreeTileProvider
   * @constructor
   * @private
   */
  function QuadtreeTileProvider() {
    DeveloperError.throwInstantiationError();
  }

  /**
   * Computes the default geometric error for level zero of the quadtree.
   *
   * @memberof QuadtreeTileProvider
   *
   * @param {TilingScheme} tilingScheme The tiling scheme for which to compute the geometric error.
   * @returns {Number} The maximum geometric error at level zero, in meters.
   */
  QuadtreeTileProvider.computeDefaultLevelZeroMaximumGeometricError = function (
    tilingScheme
  ) {
    return (
      (tilingScheme.ellipsoid.maximumRadius * 2 * Math.PI * 0.25) /
      (65 * tilingScheme.getNumberOfXTilesAtLevel(0))
    );
  };

  Object.defineProperties(QuadtreeTileProvider.prototype, {
    /**
     * Gets or sets the {@link QuadtreePrimitive} for which this provider is
     * providing tiles.
     * @memberof QuadtreeTileProvider.prototype
     * @type {QuadtreePrimitive}
     */
    quadtree: {
      get: DeveloperError.throwInstantiationError,
      set: DeveloperError.throwInstantiationError,
    },

    /**
     * Gets a value indicating whether or not the provider is ready for use.
     * @memberof QuadtreeTileProvider.prototype
     * @type {Boolean}
     */
    ready: {
      get: DeveloperError.throwInstantiationError,
    },

    /**
     * Gets the tiling scheme used by the provider.  This property should
     * not be accessed before {@link QuadtreeTileProvider#ready} returns true.
     * @memberof QuadtreeTileProvider.prototype
     * @type {TilingScheme}
     */
    tilingScheme: {
      get: DeveloperError.throwInstantiationError,
    },

    /**
     * Gets an event that is raised when the geometry provider encounters an asynchronous error.  By subscribing
     * to the event, you will be notified of the error and can potentially recover from it.  Event listeners
     * are passed an instance of {@link TileProviderError}.
     * @memberof QuadtreeTileProvider.prototype
     * @type {Event}
     */
    errorEvent: {
      get: DeveloperError.throwInstantiationError,
    },
  });

  /**
   * Called at the beginning of the update cycle, regardless of id a new frame is being rendered, before {@link QuadtreeTileProvider#beginUpdate}
   * @memberof QuadtreeTileProvider
   * @function
   *
   * @param {Context} context The rendering context.
   * @param {FrameState} frameState The frame state.
   */
  QuadtreeTileProvider.prototype.update = DeveloperError.throwInstantiationError;

  /**
   * Called at the beginning of the update cycle for each render frame, before {@link QuadtreeTileProvider#showTileThisFrame}
   * or any other functions.
   * @memberof QuadtreeTileProvider
   * @function
   *
   * @param {Context} context The rendering context.
   * @param {FrameState} frameState The frame state.
   * @param {DrawCommand[]} commandList An array of rendering commands.  This method may push
   *        commands into this array.
   */
  QuadtreeTileProvider.prototype.beginUpdate =
    DeveloperError.throwInstantiationError;

  /**
   * Called at the end of the update cycle for each render frame, after {@link QuadtreeTileProvider#showTileThisFrame}
   * and any other functions.
   * @memberof QuadtreeTileProvider
   * @function
   *
   * @param {Context} context The rendering context.
   * @param {FrameState} frameState The frame state.
   * @param {DrawCommand[]} commandList An array of rendering commands.  This method may push
   *        commands into this array.
   */
  QuadtreeTileProvider.prototype.endUpdate =
    DeveloperError.throwInstantiationError;

  /**
   * Gets the maximum geometric error allowed in a tile at a given level, in meters.  This function should not be
   * called before {@link QuadtreeTileProvider#ready} returns true.
   *
   * @see QuadtreeTileProvider#computeDefaultLevelZeroMaximumGeometricError
   *
   * @memberof QuadtreeTileProvider
   * @function
   *
   * @param {Number} level The tile level for which to get the maximum geometric error.
   * @returns {Number} The maximum geometric error in meters.
   */
  QuadtreeTileProvider.prototype.getLevelMaximumGeometricError =
    DeveloperError.throwInstantiationError;

  /**
   * Loads, or continues loading, a given tile.  This function will continue to be called
   * until {@link QuadtreeTile#state} is no longer {@link QuadtreeTileLoadState#LOADING}.  This function should
   * not be called before {@link QuadtreeTileProvider#ready} returns true.
   *
   * @memberof QuadtreeTileProvider
   * @function
   *
   * @param {Context} context The rendering context.
   * @param {FrameState} frameState The frame state.
   * @param {QuadtreeTile} tile The tile to load.
   *
   * @exception {DeveloperError} <code>loadTile</code> must not be called before the tile provider is ready.
   */
  QuadtreeTileProvider.prototype.loadTile =
    DeveloperError.throwInstantiationError;

  /**
   * Determines the visibility of a given tile.  The tile may be fully visible, partially visible, or not
   * visible at all.  Tiles that are renderable and are at least partially visible will be shown by a call
   * to {@link QuadtreeTileProvider#showTileThisFrame}.
   *
   * @memberof QuadtreeTileProvider
   *
   * @param {QuadtreeTile} tile The tile instance.
   * @param {FrameState} frameState The state information about the current frame.
   * @param {QuadtreeOccluders} occluders The objects that may occlude this tile.
   *
   * @returns {Visibility} The visibility of the tile.
   */
  QuadtreeTileProvider.prototype.computeTileVisibility =
    DeveloperError.throwInstantiationError;

  /**
   * Shows a specified tile in this frame.  The provider can cause the tile to be shown by adding
   * render commands to the commandList, or use any other method as appropriate.  The tile is not
   * expected to be visible next frame as well, unless this method is call next frame, too.
   *
   * @memberof QuadtreeTileProvider
   * @function
   *
   * @param {QuadtreeTile} tile The tile instance.
   * @param {Context} context The rendering context.
   * @param {FrameState} frameState The state information of the current rendering frame.
   * @param {DrawCommand[]} commandList The list of rendering commands.  This method may add additional commands to this list.
   */
  QuadtreeTileProvider.prototype.showTileThisFrame =
    DeveloperError.throwInstantiationError;

  /**
   * Gets the distance from the camera to the closest point on the tile.  This is used for level-of-detail selection.
   *
   * @memberof QuadtreeTileProvider
   * @function
   *
   * @param {QuadtreeTile} tile The tile instance.
   * @param {FrameState} frameState The state information of the current rendering frame.
   *
   * @returns {Number} The distance from the camera to the closest point on the tile, in meters.
   */
  QuadtreeTileProvider.prototype.computeDistanceToTile =
    DeveloperError.throwInstantiationError;

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @memberof QuadtreeTileProvider
   *
   * @returns {Boolean} True if this object was destroyed; otherwise, false.
   *
   * @see QuadtreeTileProvider#destroy
   */
  QuadtreeTileProvider.prototype.isDestroyed =
    DeveloperError.throwInstantiationError;

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @memberof QuadtreeTileProvider
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * provider = provider && provider();
   *
   * @see QuadtreeTileProvider#isDestroyed
   */
  QuadtreeTileProvider.prototype.destroy = DeveloperError.throwInstantiationError;

  /**
   * @private
   */
  function SceneTransitioner(scene) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("scene", scene);
    //>>includeEnd('debug');

    this._scene = scene;
    this._currentTweens = [];
    this._morphHandler = undefined;
    this._morphCancelled = false;
    this._completeMorph = undefined;
    this._morphToOrthographic = false;
  }

  SceneTransitioner.prototype.completeMorph = function () {
    if (defined(this._completeMorph)) {
      this._completeMorph();
    }
  };

  SceneTransitioner.prototype.morphTo2D = function (duration, ellipsoid) {
    if (defined(this._completeMorph)) {
      this._completeMorph();
    }

    const scene = this._scene;
    this._previousMode = scene.mode;
    this._morphToOrthographic =
      scene.camera.frustum instanceof OrthographicFrustum;

    if (
      this._previousMode === SceneMode$1.SCENE2D ||
      this._previousMode === SceneMode$1.MORPHING
    ) {
      return;
    }
    this._scene.morphStart.raiseEvent(
      this,
      this._previousMode,
      SceneMode$1.SCENE2D,
      true
    );

    scene._mode = SceneMode$1.MORPHING;
    scene.camera._setTransform(Matrix4.IDENTITY);

    if (this._previousMode === SceneMode$1.COLUMBUS_VIEW) {
      morphFromColumbusViewTo2D(this, duration);
    } else {
      morphFrom3DTo2D(this, duration, ellipsoid);
    }

    if (duration === 0.0 && defined(this._completeMorph)) {
      this._completeMorph();
    }
  };

  const scratchToCVPosition = new Cartesian3();
  const scratchToCVDirection = new Cartesian3();
  const scratchToCVUp = new Cartesian3();
  const scratchToCVPosition2D = new Cartesian3();
  const scratchToCVDirection2D = new Cartesian3();
  const scratchToCVUp2D = new Cartesian3();
  const scratchToCVSurfacePosition = new Cartesian3();
  const scratchToCVCartographic = new Cartographic();
  const scratchToCVToENU = new Matrix4();
  const scratchToCVFrustumPerspective = new PerspectiveFrustum();
  const scratchToCVFrustumOrthographic = new OrthographicFrustum();
  const scratchToCVCamera = {
    position: undefined,
    direction: undefined,
    up: undefined,
    position2D: undefined,
    direction2D: undefined,
    up2D: undefined,
    frustum: undefined,
  };

  SceneTransitioner.prototype.morphToColumbusView = function (
    duration,
    ellipsoid
  ) {
    if (defined(this._completeMorph)) {
      this._completeMorph();
    }

    const scene = this._scene;
    this._previousMode = scene.mode;

    if (
      this._previousMode === SceneMode$1.COLUMBUS_VIEW ||
      this._previousMode === SceneMode$1.MORPHING
    ) {
      return;
    }
    this._scene.morphStart.raiseEvent(
      this,
      this._previousMode,
      SceneMode$1.COLUMBUS_VIEW,
      true
    );

    scene.camera._setTransform(Matrix4.IDENTITY);

    let position = scratchToCVPosition;
    const direction = scratchToCVDirection;
    const up = scratchToCVUp;

    if (duration > 0.0) {
      position.x = 0.0;
      position.y = -1.0;
      position.z = 1.0;
      position = Cartesian3.multiplyByScalar(
        Cartesian3.normalize(position, position),
        5.0 * ellipsoid.maximumRadius,
        position
      );

      Cartesian3.negate(Cartesian3.normalize(position, direction), direction);
      Cartesian3.cross(Cartesian3.UNIT_X, direction, up);
    } else {
      const camera = scene.camera;
      if (this._previousMode === SceneMode$1.SCENE2D) {
        Cartesian3.clone(camera.position, position);
        position.z = camera.frustum.right - camera.frustum.left;
        Cartesian3.negate(Cartesian3.UNIT_Z, direction);
        Cartesian3.clone(Cartesian3.UNIT_Y, up);
      } else {
        Cartesian3.clone(camera.positionWC, position);
        Cartesian3.clone(camera.directionWC, direction);
        Cartesian3.clone(camera.upWC, up);

        const surfacePoint = ellipsoid.scaleToGeodeticSurface(
          position,
          scratchToCVSurfacePosition
        );
        const toENU = Transforms.eastNorthUpToFixedFrame(
          surfacePoint,
          ellipsoid,
          scratchToCVToENU
        );
        Matrix4.inverseTransformation(toENU, toENU);

        scene.mapProjection.project(
          ellipsoid.cartesianToCartographic(position, scratchToCVCartographic),
          position
        );
        Matrix4.multiplyByPointAsVector(toENU, direction, direction);
        Matrix4.multiplyByPointAsVector(toENU, up, up);
      }
    }

    let frustum;
    if (this._morphToOrthographic) {
      frustum = scratchToCVFrustumOrthographic;
      frustum.width = scene.camera.frustum.right - scene.camera.frustum.left;
      frustum.aspectRatio = scene.drawingBufferWidth / scene.drawingBufferHeight;
    } else {
      frustum = scratchToCVFrustumPerspective;
      frustum.aspectRatio = scene.drawingBufferWidth / scene.drawingBufferHeight;
      frustum.fov = CesiumMath.toRadians(60.0);
    }

    const cameraCV = scratchToCVCamera;
    cameraCV.position = position;
    cameraCV.direction = direction;
    cameraCV.up = up;
    cameraCV.frustum = frustum;

    const complete = completeColumbusViewCallback(cameraCV);
    createMorphHandler(this, complete);

    if (this._previousMode === SceneMode$1.SCENE2D) {
      morphFrom2DToColumbusView(this, duration, cameraCV, complete);
    } else {
      cameraCV.position2D = Matrix4.multiplyByPoint(
        Camera.TRANSFORM_2D,
        position,
        scratchToCVPosition2D
      );
      cameraCV.direction2D = Matrix4.multiplyByPointAsVector(
        Camera.TRANSFORM_2D,
        direction,
        scratchToCVDirection2D
      );
      cameraCV.up2D = Matrix4.multiplyByPointAsVector(
        Camera.TRANSFORM_2D,
        up,
        scratchToCVUp2D
      );

      scene._mode = SceneMode$1.MORPHING;
      morphFrom3DToColumbusView(this, duration, cameraCV, complete);
    }

    if (duration === 0.0 && defined(this._completeMorph)) {
      this._completeMorph();
    }
  };

  const scratchCVTo3DCamera = {
    position: new Cartesian3(),
    direction: new Cartesian3(),
    up: new Cartesian3(),
    frustum: undefined,
  };
  const scratch2DTo3DFrustumPersp = new PerspectiveFrustum();

  SceneTransitioner.prototype.morphTo3D = function (duration, ellipsoid) {
    if (defined(this._completeMorph)) {
      this._completeMorph();
    }

    const scene = this._scene;
    this._previousMode = scene.mode;

    if (
      this._previousMode === SceneMode$1.SCENE3D ||
      this._previousMode === SceneMode$1.MORPHING
    ) {
      return;
    }
    this._scene.morphStart.raiseEvent(
      this,
      this._previousMode,
      SceneMode$1.SCENE3D,
      true
    );

    scene._mode = SceneMode$1.MORPHING;
    scene.camera._setTransform(Matrix4.IDENTITY);

    if (this._previousMode === SceneMode$1.SCENE2D) {
      morphFrom2DTo3D(this, duration, ellipsoid);
    } else {
      let camera3D;
      if (duration > 0.0) {
        camera3D = scratchCVTo3DCamera;
        Cartesian3.fromDegrees(
          0.0,
          0.0,
          5.0 * ellipsoid.maximumRadius,
          ellipsoid,
          camera3D.position
        );
        Cartesian3.negate(camera3D.position, camera3D.direction);
        Cartesian3.normalize(camera3D.direction, camera3D.direction);
        Cartesian3.clone(Cartesian3.UNIT_Z, camera3D.up);
      } else {
        camera3D = getColumbusViewTo3DCamera(this, ellipsoid);
      }

      let frustum;
      const camera = scene.camera;
      if (camera.frustum instanceof OrthographicFrustum) {
        frustum = camera.frustum.clone();
      } else {
        frustum = scratch2DTo3DFrustumPersp;
        frustum.aspectRatio =
          scene.drawingBufferWidth / scene.drawingBufferHeight;
        frustum.fov = CesiumMath.toRadians(60.0);
      }
      camera3D.frustum = frustum;

      const complete = complete3DCallback(camera3D);
      createMorphHandler(this, complete);

      morphFromColumbusViewTo3D(this, duration, camera3D, complete);
    }

    if (duration === 0.0 && defined(this._completeMorph)) {
      this._completeMorph();
    }
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   */
  SceneTransitioner.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @example
   * transitioner = transitioner && transitioner.destroy();
   */
  SceneTransitioner.prototype.destroy = function () {
    destroyMorphHandler(this);
    return destroyObject(this);
  };

  function createMorphHandler(transitioner, completeMorphFunction) {
    if (transitioner._scene.completeMorphOnUserInput) {
      transitioner._morphHandler = new ScreenSpaceEventHandler(
        transitioner._scene.canvas
      );

      const completeMorph = function () {
        transitioner._morphCancelled = true;
        transitioner._scene.camera.cancelFlight();
        completeMorphFunction(transitioner);
      };
      transitioner._completeMorph = completeMorph;
      transitioner._morphHandler.setInputAction(
        completeMorph,
        ScreenSpaceEventType$1.LEFT_DOWN
      );
      transitioner._morphHandler.setInputAction(
        completeMorph,
        ScreenSpaceEventType$1.MIDDLE_DOWN
      );
      transitioner._morphHandler.setInputAction(
        completeMorph,
        ScreenSpaceEventType$1.RIGHT_DOWN
      );
      transitioner._morphHandler.setInputAction(
        completeMorph,
        ScreenSpaceEventType$1.WHEEL
      );
    }
  }

  function destroyMorphHandler(transitioner) {
    const tweens = transitioner._currentTweens;
    for (let i = 0; i < tweens.length; ++i) {
      tweens[i].cancelTween();
    }
    transitioner._currentTweens.length = 0;
    transitioner._morphHandler =
      transitioner._morphHandler && transitioner._morphHandler.destroy();
  }

  const scratchCVTo3DCartographic = new Cartographic();
  const scratchCVTo3DSurfacePoint = new Cartesian3();
  const scratchCVTo3DFromENU = new Matrix4();

  function getColumbusViewTo3DCamera(transitioner, ellipsoid) {
    const scene = transitioner._scene;
    const camera = scene.camera;

    const camera3D = scratchCVTo3DCamera;
    const position = camera3D.position;
    const direction = camera3D.direction;
    const up = camera3D.up;

    const positionCarto = scene.mapProjection.unproject(
      camera.position,
      scratchCVTo3DCartographic
    );
    ellipsoid.cartographicToCartesian(positionCarto, position);
    const surfacePoint = ellipsoid.scaleToGeodeticSurface(
      position,
      scratchCVTo3DSurfacePoint
    );

    const fromENU = Transforms.eastNorthUpToFixedFrame(
      surfacePoint,
      ellipsoid,
      scratchCVTo3DFromENU
    );

    Matrix4.multiplyByPointAsVector(fromENU, camera.direction, direction);
    Matrix4.multiplyByPointAsVector(fromENU, camera.up, up);

    return camera3D;
  }

  const scratchCVTo3DStartPos = new Cartesian3();
  const scratchCVTo3DStartDir = new Cartesian3();
  const scratchCVTo3DStartUp = new Cartesian3();
  const scratchCVTo3DEndPos = new Cartesian3();
  const scratchCVTo3DEndDir = new Cartesian3();
  const scratchCVTo3DEndUp = new Cartesian3();

  function morphFromColumbusViewTo3D(
    transitioner,
    duration,
    endCamera,
    complete
  ) {
    duration *= 0.5;

    const scene = transitioner._scene;
    const camera = scene.camera;

    const startPos = Cartesian3.clone(camera.position, scratchCVTo3DStartPos);
    const startDir = Cartesian3.clone(camera.direction, scratchCVTo3DStartDir);
    const startUp = Cartesian3.clone(camera.up, scratchCVTo3DStartUp);

    const endPos = Matrix4.multiplyByPoint(
      Camera.TRANSFORM_2D_INVERSE,
      endCamera.position,
      scratchCVTo3DEndPos
    );
    const endDir = Matrix4.multiplyByPointAsVector(
      Camera.TRANSFORM_2D_INVERSE,
      endCamera.direction,
      scratchCVTo3DEndDir
    );
    const endUp = Matrix4.multiplyByPointAsVector(
      Camera.TRANSFORM_2D_INVERSE,
      endCamera.up,
      scratchCVTo3DEndUp
    );

    function update(value) {
      columbusViewMorph(startPos, endPos, value.time, camera.position);
      columbusViewMorph(startDir, endDir, value.time, camera.direction);
      columbusViewMorph(startUp, endUp, value.time, camera.up);
      Cartesian3.cross(camera.direction, camera.up, camera.right);
      Cartesian3.normalize(camera.right, camera.right);
    }

    const tween = scene.tweens.add({
      duration: duration,
      easingFunction: EasingFunction$1.QUARTIC_OUT,
      startObject: {
        time: 0.0,
      },
      stopObject: {
        time: 1.0,
      },
      update: update,
      complete: function () {
        addMorphTimeAnimations(transitioner, scene, 0.0, 1.0, duration, complete);
      },
    });
    transitioner._currentTweens.push(tween);
  }

  const scratch2DTo3DFrustumOrtho = new OrthographicFrustum();
  const scratch3DToCVStartPos = new Cartesian3();
  const scratch3DToCVStartDir = new Cartesian3();
  const scratch3DToCVStartUp = new Cartesian3();
  const scratch3DToCVEndPos = new Cartesian3();
  const scratch3DToCVEndDir = new Cartesian3();
  const scratch3DToCVEndUp = new Cartesian3();

  function morphFrom2DTo3D(transitioner, duration, ellipsoid) {
    duration /= 3.0;

    const scene = transitioner._scene;
    const camera = scene.camera;

    let camera3D;
    if (duration > 0.0) {
      camera3D = scratchCVTo3DCamera;
      Cartesian3.fromDegrees(
        0.0,
        0.0,
        5.0 * ellipsoid.maximumRadius,
        ellipsoid,
        camera3D.position
      );
      Cartesian3.negate(camera3D.position, camera3D.direction);
      Cartesian3.normalize(camera3D.direction, camera3D.direction);
      Cartesian3.clone(Cartesian3.UNIT_Z, camera3D.up);
    } else {
      camera.position.z = camera.frustum.right - camera.frustum.left;

      camera3D = getColumbusViewTo3DCamera(transitioner, ellipsoid);
    }

    let frustum;
    if (transitioner._morphToOrthographic) {
      frustum = scratch2DTo3DFrustumOrtho;
      frustum.aspectRatio = scene.drawingBufferWidth / scene.drawingBufferHeight;
      frustum.width = camera.frustum.right - camera.frustum.left;
    } else {
      frustum = scratch2DTo3DFrustumPersp;
      frustum.aspectRatio = scene.drawingBufferWidth / scene.drawingBufferHeight;
      frustum.fov = CesiumMath.toRadians(60.0);
    }

    camera3D.frustum = frustum;

    const complete = complete3DCallback(camera3D);
    createMorphHandler(transitioner, complete);

    let morph;
    if (transitioner._morphToOrthographic) {
      morph = function () {
        morphFromColumbusViewTo3D(transitioner, duration, camera3D, complete);
      };
    } else {
      morph = function () {
        morphOrthographicToPerspective(
          transitioner,
          duration,
          camera3D,
          function () {
            morphFromColumbusViewTo3D(transitioner, duration, camera3D, complete);
          }
        );
      };
    }

    if (duration > 0.0) {
      scene._mode = SceneMode$1.SCENE2D;
      camera.flyTo({
        duration: duration,
        destination: Cartesian3.fromDegrees(
          0.0,
          0.0,
          5.0 * ellipsoid.maximumRadius,
          ellipsoid,
          scratch3DToCVEndPos
        ),
        complete: function () {
          scene._mode = SceneMode$1.MORPHING;
          morph();
        },
      });
    } else {
      morph();
    }
  }

  function columbusViewMorph(startPosition, endPosition, time, result) {
    // Just linear for now.
    return Cartesian3.lerp(startPosition, endPosition, time, result);
  }

  function morphPerspectiveToOrthographic(
    transitioner,
    duration,
    endCamera,
    updateHeight,
    complete
  ) {
    const scene = transitioner._scene;
    const camera = scene.camera;

    if (camera.frustum instanceof OrthographicFrustum) {
      return;
    }

    const startFOV = camera.frustum.fov;
    const endFOV = CesiumMath.RADIANS_PER_DEGREE * 0.5;
    const d = endCamera.position.z * Math.tan(startFOV * 0.5);
    camera.frustum.far = d / Math.tan(endFOV * 0.5) + 10000000.0;

    function update(value) {
      camera.frustum.fov = CesiumMath.lerp(startFOV, endFOV, value.time);
      const height = d / Math.tan(camera.frustum.fov * 0.5);
      updateHeight(camera, height);
    }
    const tween = scene.tweens.add({
      duration: duration,
      easingFunction: EasingFunction$1.QUARTIC_OUT,
      startObject: {
        time: 0.0,
      },
      stopObject: {
        time: 1.0,
      },
      update: update,
      complete: function () {
        camera.frustum = endCamera.frustum.clone();
        complete(transitioner);
      },
    });
    transitioner._currentTweens.push(tween);
  }

  const scratchCVTo2DStartPos = new Cartesian3();
  const scratchCVTo2DStartDir = new Cartesian3();
  const scratchCVTo2DStartUp = new Cartesian3();
  const scratchCVTo2DEndPos = new Cartesian3();
  const scratchCVTo2DEndDir = new Cartesian3();
  const scratchCVTo2DEndUp = new Cartesian3();
  const scratchCVTo2DFrustum = new OrthographicOffCenterFrustum();
  const scratchCVTo2DRay = new Ray();
  const scratchCVTo2DPickPos = new Cartesian3();
  const scratchCVTo2DCamera = {
    position: undefined,
    direction: undefined,
    up: undefined,
    frustum: undefined,
  };

  function morphFromColumbusViewTo2D(transitioner, duration) {
    duration *= 0.5;

    const scene = transitioner._scene;
    const camera = scene.camera;

    const startPos = Cartesian3.clone(camera.position, scratchCVTo2DStartPos);
    const startDir = Cartesian3.clone(camera.direction, scratchCVTo2DStartDir);
    const startUp = Cartesian3.clone(camera.up, scratchCVTo2DStartUp);

    const endDir = Cartesian3.negate(Cartesian3.UNIT_Z, scratchCVTo2DEndDir);
    const endUp = Cartesian3.clone(Cartesian3.UNIT_Y, scratchCVTo2DEndUp);

    const endPos = scratchCVTo2DEndPos;

    if (duration > 0.0) {
      Cartesian3.clone(Cartesian3.ZERO, scratchCVTo2DEndPos);
      endPos.z = 5.0 * scene.mapProjection.ellipsoid.maximumRadius;
    } else {
      Cartesian3.clone(startPos, scratchCVTo2DEndPos);

      const ray = scratchCVTo2DRay;
      Matrix4.multiplyByPoint(Camera.TRANSFORM_2D, startPos, ray.origin);
      Matrix4.multiplyByPointAsVector(
        Camera.TRANSFORM_2D,
        startDir,
        ray.direction
      );

      const globe = scene.globe;
      if (defined(globe)) {
        const pickPos = globe.pickWorldCoordinates(
          ray,
          scene,
          true,
          scratchCVTo2DPickPos
        );
        if (defined(pickPos)) {
          Matrix4.multiplyByPoint(Camera.TRANSFORM_2D_INVERSE, pickPos, endPos);
          endPos.z += Cartesian3.distance(startPos, endPos);
        }
      }
    }

    const frustum = scratchCVTo2DFrustum;
    frustum.right = endPos.z * 0.5;
    frustum.left = -frustum.right;
    frustum.top =
      frustum.right * (scene.drawingBufferHeight / scene.drawingBufferWidth);
    frustum.bottom = -frustum.top;

    const camera2D = scratchCVTo2DCamera;
    camera2D.position = endPos;
    camera2D.direction = endDir;
    camera2D.up = endUp;
    camera2D.frustum = frustum;

    const complete = complete2DCallback(camera2D);
    createMorphHandler(transitioner, complete);

    function updateCV(value) {
      columbusViewMorph(startPos, endPos, value.time, camera.position);
      columbusViewMorph(startDir, endDir, value.time, camera.direction);
      columbusViewMorph(startUp, endUp, value.time, camera.up);
      Cartesian3.cross(camera.direction, camera.up, camera.right);
      Cartesian3.normalize(camera.right, camera.right);
      camera._adjustOrthographicFrustum(true);
    }

    function updateHeight(camera, height) {
      camera.position.z = height;
    }

    const tween = scene.tweens.add({
      duration: duration,
      easingFunction: EasingFunction$1.QUARTIC_OUT,
      startObject: {
        time: 0.0,
      },
      stopObject: {
        time: 1.0,
      },
      update: updateCV,
      complete: function () {
        morphPerspectiveToOrthographic(
          transitioner,
          duration,
          camera2D,
          updateHeight,
          complete
        );
      },
    });
    transitioner._currentTweens.push(tween);
  }

  const scratch3DTo2DCartographic = new Cartographic();
  const scratch3DTo2DCamera = {
    position: new Cartesian3(),
    direction: new Cartesian3(),
    up: new Cartesian3(),
    position2D: new Cartesian3(),
    direction2D: new Cartesian3(),
    up2D: new Cartesian3(),
    frustum: new OrthographicOffCenterFrustum(),
  };
  const scratch3DTo2DEndCamera = {
    position: new Cartesian3(),
    direction: new Cartesian3(),
    up: new Cartesian3(),
    frustum: undefined,
  };
  const scratch3DTo2DPickPosition = new Cartesian3();
  const scratch3DTo2DRay = new Ray();
  const scratch3DTo2DToENU = new Matrix4();
  const scratch3DTo2DSurfacePoint = new Cartesian3();

  function morphFrom3DTo2D(transitioner, duration, ellipsoid) {
    duration *= 0.5;

    const scene = transitioner._scene;
    const camera = scene.camera;
    const camera2D = scratch3DTo2DCamera;

    if (duration > 0.0) {
      Cartesian3.clone(Cartesian3.ZERO, camera2D.position);
      camera2D.position.z = 5.0 * ellipsoid.maximumRadius;
      Cartesian3.negate(Cartesian3.UNIT_Z, camera2D.direction);
      Cartesian3.clone(Cartesian3.UNIT_Y, camera2D.up);
    } else {
      ellipsoid.cartesianToCartographic(
        camera.positionWC,
        scratch3DTo2DCartographic
      );
      scene.mapProjection.project(scratch3DTo2DCartographic, camera2D.position);

      Cartesian3.negate(Cartesian3.UNIT_Z, camera2D.direction);
      Cartesian3.clone(Cartesian3.UNIT_Y, camera2D.up);

      const ray = scratch3DTo2DRay;
      Cartesian3.clone(camera2D.position2D, ray.origin);
      const rayDirection = Cartesian3.clone(camera.directionWC, ray.direction);
      const surfacePoint = ellipsoid.scaleToGeodeticSurface(
        camera.positionWC,
        scratch3DTo2DSurfacePoint
      );
      const toENU = Transforms.eastNorthUpToFixedFrame(
        surfacePoint,
        ellipsoid,
        scratch3DTo2DToENU
      );
      Matrix4.inverseTransformation(toENU, toENU);
      Matrix4.multiplyByPointAsVector(toENU, rayDirection, rayDirection);
      Matrix4.multiplyByPointAsVector(
        Camera.TRANSFORM_2D,
        rayDirection,
        rayDirection
      );

      const globe = scene.globe;
      if (defined(globe)) {
        const pickedPos = globe.pickWorldCoordinates(
          ray,
          scene,
          true,
          scratch3DTo2DPickPosition
        );
        if (defined(pickedPos)) {
          const height = Cartesian3.distance(camera2D.position2D, pickedPos);
          pickedPos.x += height;
          Cartesian3.clone(pickedPos, camera2D.position2D);
        }
      }
    }

    function updateHeight(camera, height) {
      camera.position.x = height;
    }

    Matrix4.multiplyByPoint(
      Camera.TRANSFORM_2D,
      camera2D.position,
      camera2D.position2D
    );
    Matrix4.multiplyByPointAsVector(
      Camera.TRANSFORM_2D,
      camera2D.direction,
      camera2D.direction2D
    );
    Matrix4.multiplyByPointAsVector(
      Camera.TRANSFORM_2D,
      camera2D.up,
      camera2D.up2D
    );

    const frustum = camera2D.frustum;
    frustum.right = camera2D.position.z * 0.5;
    frustum.left = -frustum.right;
    frustum.top =
      frustum.right * (scene.drawingBufferHeight / scene.drawingBufferWidth);
    frustum.bottom = -frustum.top;

    const endCamera = scratch3DTo2DEndCamera;
    Matrix4.multiplyByPoint(
      Camera.TRANSFORM_2D_INVERSE,
      camera2D.position2D,
      endCamera.position
    );
    Cartesian3.clone(camera2D.direction, endCamera.direction);
    Cartesian3.clone(camera2D.up, endCamera.up);
    endCamera.frustum = frustum;

    const complete = complete2DCallback(endCamera);
    createMorphHandler(transitioner, complete);

    function completeCallback() {
      morphPerspectiveToOrthographic(
        transitioner,
        duration,
        camera2D,
        updateHeight,
        complete
      );
    }
    morphFrom3DToColumbusView(transitioner, duration, camera2D, completeCallback);
  }

  function morphOrthographicToPerspective(
    transitioner,
    duration,
    cameraCV,
    complete
  ) {
    const scene = transitioner._scene;
    const camera = scene.camera;

    const height = camera.frustum.right - camera.frustum.left;
    camera.frustum = cameraCV.frustum.clone();

    const endFOV = camera.frustum.fov;
    const startFOV = CesiumMath.RADIANS_PER_DEGREE * 0.5;
    const d = height * Math.tan(endFOV * 0.5);
    camera.frustum.far = d / Math.tan(startFOV * 0.5) + 10000000.0;
    camera.frustum.fov = startFOV;

    function update(value) {
      camera.frustum.fov = CesiumMath.lerp(startFOV, endFOV, value.time);
      camera.position.z = d / Math.tan(camera.frustum.fov * 0.5);
    }
    const tween = scene.tweens.add({
      duration: duration,
      easingFunction: EasingFunction$1.QUARTIC_OUT,
      startObject: {
        time: 0.0,
      },
      stopObject: {
        time: 1.0,
      },
      update: update,
      complete: function () {
        complete(transitioner);
      },
    });
    transitioner._currentTweens.push(tween);
  }

  function morphFrom2DToColumbusView(transitioner, duration, cameraCV, complete) {
    duration *= 0.5;

    const scene = transitioner._scene;
    const camera = scene.camera;

    const endPos = Cartesian3.clone(cameraCV.position, scratch3DToCVEndPos);
    const endDir = Cartesian3.clone(cameraCV.direction, scratch3DToCVEndDir);
    const endUp = Cartesian3.clone(cameraCV.up, scratch3DToCVEndUp);

    scene._mode = SceneMode$1.MORPHING;

    function morph() {
      camera.frustum = cameraCV.frustum.clone();

      const startPos = Cartesian3.clone(camera.position, scratch3DToCVStartPos);
      const startDir = Cartesian3.clone(camera.direction, scratch3DToCVStartDir);
      const startUp = Cartesian3.clone(camera.up, scratch3DToCVStartUp);
      startPos.z = endPos.z;

      function update(value) {
        columbusViewMorph(startPos, endPos, value.time, camera.position);
        columbusViewMorph(startDir, endDir, value.time, camera.direction);
        columbusViewMorph(startUp, endUp, value.time, camera.up);
        Cartesian3.cross(camera.direction, camera.up, camera.right);
        Cartesian3.normalize(camera.right, camera.right);
      }
      const tween = scene.tweens.add({
        duration: duration,
        easingFunction: EasingFunction$1.QUARTIC_OUT,
        startObject: {
          time: 0.0,
        },
        stopObject: {
          time: 1.0,
        },
        update: update,
        complete: function () {
          complete(transitioner);
        },
      });
      transitioner._currentTweens.push(tween);
    }

    if (transitioner._morphToOrthographic) {
      morph();
    } else {
      morphOrthographicToPerspective(transitioner, 0.0, cameraCV, morph);
    }
  }

  function morphFrom3DToColumbusView(
    transitioner,
    duration,
    endCamera,
    complete
  ) {
    const scene = transitioner._scene;
    const camera = scene.camera;

    const startPos = Cartesian3.clone(camera.position, scratch3DToCVStartPos);
    const startDir = Cartesian3.clone(camera.direction, scratch3DToCVStartDir);
    const startUp = Cartesian3.clone(camera.up, scratch3DToCVStartUp);

    const endPos = Cartesian3.clone(endCamera.position2D, scratch3DToCVEndPos);
    const endDir = Cartesian3.clone(endCamera.direction2D, scratch3DToCVEndDir);
    const endUp = Cartesian3.clone(endCamera.up2D, scratch3DToCVEndUp);

    function update(value) {
      columbusViewMorph(startPos, endPos, value.time, camera.position);
      columbusViewMorph(startDir, endDir, value.time, camera.direction);
      columbusViewMorph(startUp, endUp, value.time, camera.up);
      Cartesian3.cross(camera.direction, camera.up, camera.right);
      Cartesian3.normalize(camera.right, camera.right);
      camera._adjustOrthographicFrustum(true);
    }
    const tween = scene.tweens.add({
      duration: duration,
      easingFunction: EasingFunction$1.QUARTIC_OUT,
      startObject: {
        time: 0.0,
      },
      stopObject: {
        time: 1.0,
      },
      update: update,
      complete: function () {
        addMorphTimeAnimations(transitioner, scene, 1.0, 0.0, duration, complete);
      },
    });
    transitioner._currentTweens.push(tween);
  }

  function addMorphTimeAnimations(
    transitioner,
    scene,
    start,
    stop,
    duration,
    complete
  ) {
    // Later, this will be linear and each object will adjust, if desired, in its vertex shader.
    const options = {
      object: scene,
      property: "morphTime",
      startValue: start,
      stopValue: stop,
      duration: duration,
      easingFunction: EasingFunction$1.QUARTIC_OUT,
    };

    if (defined(complete)) {
      options.complete = function () {
        complete(transitioner);
      };
    }

    const tween = scene.tweens.addProperty(options);
    transitioner._currentTweens.push(tween);
  }

  function complete3DCallback(camera3D) {
    return function (transitioner) {
      const scene = transitioner._scene;
      scene._mode = SceneMode$1.SCENE3D;
      scene.morphTime = SceneMode$1.getMorphTime(SceneMode$1.SCENE3D);

      destroyMorphHandler(transitioner);

      const camera = scene.camera;
      if (
        transitioner._previousMode !== SceneMode$1.MORPHING ||
        transitioner._morphCancelled
      ) {
        transitioner._morphCancelled = false;

        Cartesian3.clone(camera3D.position, camera.position);
        Cartesian3.clone(camera3D.direction, camera.direction);
        Cartesian3.clone(camera3D.up, camera.up);
        Cartesian3.cross(camera.direction, camera.up, camera.right);
        Cartesian3.normalize(camera.right, camera.right);

        camera.frustum = camera3D.frustum.clone();
      }

      const frustum = camera.frustum;
      if (scene.frameState.useLogDepth) {
        frustum.near = 0.1;
        frustum.far = 10000000000.0;
      }

      const wasMorphing = defined(transitioner._completeMorph);
      transitioner._completeMorph = undefined;
      scene.camera.update(scene.mode);
      transitioner._scene.morphComplete.raiseEvent(
        transitioner,
        transitioner._previousMode,
        SceneMode$1.SCENE3D,
        wasMorphing
      );
    };
  }

  function complete2DCallback(camera2D) {
    return function (transitioner) {
      const scene = transitioner._scene;

      scene._mode = SceneMode$1.SCENE2D;
      scene.morphTime = SceneMode$1.getMorphTime(SceneMode$1.SCENE2D);

      destroyMorphHandler(transitioner);

      const camera = scene.camera;
      Cartesian3.clone(camera2D.position, camera.position);
      camera.position.z = scene.mapProjection.ellipsoid.maximumRadius * 2.0;
      Cartesian3.clone(camera2D.direction, camera.direction);
      Cartesian3.clone(camera2D.up, camera.up);
      Cartesian3.cross(camera.direction, camera.up, camera.right);
      Cartesian3.normalize(camera.right, camera.right);
      camera.frustum = camera2D.frustum.clone();

      const wasMorphing = defined(transitioner._completeMorph);
      transitioner._completeMorph = undefined;
      scene.camera.update(scene.mode);
      transitioner._scene.morphComplete.raiseEvent(
        transitioner,
        transitioner._previousMode,
        SceneMode$1.SCENE2D,
        wasMorphing
      );
    };
  }

  function completeColumbusViewCallback(cameraCV) {
    return function (transitioner) {
      const scene = transitioner._scene;
      scene._mode = SceneMode$1.COLUMBUS_VIEW;
      scene.morphTime = SceneMode$1.getMorphTime(SceneMode$1.COLUMBUS_VIEW);

      destroyMorphHandler(transitioner);

      const camera = scene.camera;
      if (
        transitioner._previousModeMode !== SceneMode$1.MORPHING ||
        transitioner._morphCancelled
      ) {
        transitioner._morphCancelled = false;

        Cartesian3.clone(cameraCV.position, camera.position);
        Cartesian3.clone(cameraCV.direction, camera.direction);
        Cartesian3.clone(cameraCV.up, camera.up);
        Cartesian3.cross(camera.direction, camera.up, camera.right);
        Cartesian3.normalize(camera.right, camera.right);
      }

      const frustum = camera.frustum;
      if (scene.frameState.useLogDepth) {
        frustum.near = 0.1;
        frustum.far = 10000000000.0;
      }

      const wasMorphing = defined(transitioner._completeMorph);
      transitioner._completeMorph = undefined;
      scene.camera.update(scene.mode);
      transitioner._scene.morphComplete.raiseEvent(
        transitioner,
        transitioner._previousMode,
        SceneMode$1.COLUMBUS_VIEW,
        wasMorphing
      );
    };
  }

  /**
   * A tween is an animation that interpolates the properties of two objects using an {@link EasingFunction}.  Create
   * one using {@link Scene#tweens} and {@link TweenCollection#add} and related add functions.
   *
   * @alias Tween
   * @constructor
   *
   * @private
   */
  function Tween(
    tweens,
    tweenjs,
    startObject,
    stopObject,
    duration,
    delay,
    easingFunction,
    update,
    complete,
    cancel
  ) {
    this._tweens = tweens;
    this._tweenjs = tweenjs;

    this._startObject = clone$1(startObject);
    this._stopObject = clone$1(stopObject);

    this._duration = duration;
    this._delay = delay;
    this._easingFunction = easingFunction;

    this._update = update;
    this._complete = complete;

    /**
     * The callback to call if the tween is canceled either because {@link Tween#cancelTween}
     * was called or because the tween was removed from the collection.
     *
     * @type {TweenCollection.TweenCancelledCallback}
     */
    this.cancel = cancel;

    /**
     * @private
     */
    this.needsStart = true;
  }

  Object.defineProperties(Tween.prototype, {
    /**
     * An object with properties for initial values of the tween.  The properties of this object are changed during the tween's animation.
     * @memberof Tween.prototype
     *
     * @type {Object}
     * @readonly
     */
    startObject: {
      get: function () {
        return this._startObject;
      },
    },

    /**
     * An object with properties for the final values of the tween.
     * @memberof Tween.prototype
     *
     * @type {Object}
     * @readonly
     */
    stopObject: {
      get: function () {
        return this._stopObject;
      },
    },

    /**
     * The duration, in seconds, for the tween.  The tween is automatically removed from the collection when it stops.
     * @memberof Tween.prototype
     *
     * @type {Number}
     * @readonly
     */
    duration: {
      get: function () {
        return this._duration;
      },
    },

    /**
     * The delay, in seconds, before the tween starts animating.
     * @memberof Tween.prototype
     *
     * @type {Number}
     * @readonly
     */
    delay: {
      get: function () {
        return this._delay;
      },
    },

    /**
     * Determines the curve for animtion.
     * @memberof Tween.prototype
     *
     * @type {EasingFunction}
     * @readonly
     */
    easingFunction: {
      get: function () {
        return this._easingFunction;
      },
    },

    /**
     * The callback to call at each animation update (usually tied to the a rendered frame).
     * @memberof Tween.prototype
     *
     * @type {TweenCollection.TweenUpdateCallback}
     * @readonly
     */
    update: {
      get: function () {
        return this._update;
      },
    },

    /**
     * The callback to call when the tween finishes animating.
     * @memberof Tween.prototype
     *
     * @type {TweenCollection.TweenCompleteCallback}
     * @readonly
     */
    complete: {
      get: function () {
        return this._complete;
      },
    },

    /**
     * @memberof Tween.prototype
     *
     * @private
     */
    tweenjs: {
      get: function () {
        return this._tweenjs;
      },
    },
  });

  /**
   * Cancels the tween calling the {@link Tween#cancel} callback if one exists.  This
   * has no effect if the tween finished or was already canceled.
   */
  Tween.prototype.cancelTween = function () {
    this._tweens.remove(this);
  };

  /**
   * A collection of tweens for animating properties.  Commonly accessed using {@link Scene#tweens}.
   *
   * @alias TweenCollection
   * @constructor
   *
   * @private
   */
  function TweenCollection() {
    this._tweens = [];
  }

  Object.defineProperties(TweenCollection.prototype, {
    /**
     * The number of tweens in the collection.
     * @memberof TweenCollection.prototype
     *
     * @type {Number}
     * @readonly
     */
    length: {
      get: function () {
        return this._tweens.length;
      },
    },
  });

  /**
   * Creates a tween for animating between two sets of properties.  The tween starts animating at the next call to {@link TweenCollection#update}, which
   * is implicit when {@link Viewer} or {@link CesiumWidget} render the scene.
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Object} options.startObject An object with properties for initial values of the tween.  The properties of this object are changed during the tween's animation.
   * @param {Object} options.stopObject An object with properties for the final values of the tween.
   * @param {Number} options.duration The duration, in seconds, for the tween.  The tween is automatically removed from the collection when it stops.
   * @param {Number} [options.delay=0.0] The delay, in seconds, before the tween starts animating.
   * @param {EasingFunction} [options.easingFunction=EasingFunction.LINEAR_NONE] Determines the curve for animtion.
   * @param {TweenCollection.TweenUpdateCallback} [options.update] The callback to call at each animation update (usually tied to the a rendered frame).
   * @param {TweenCollection.TweenCompleteCallback} [options.complete] The callback to call when the tween finishes animating.
   * @param {TweenCollection.TweenCancelledCallback} [options.cancel] The callback to call if the tween is canceled either because {@link Tween#cancelTween} was called or because the tween was removed from the collection.
   * @returns {Tween} The tween.
   *
   * @exception {DeveloperError} options.duration must be positive.
   */
  TweenCollection.prototype.add = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    if (!defined(options.startObject) || !defined(options.stopObject)) {
      throw new DeveloperError(
        "options.startObject and options.stopObject are required."
      );
    }

    if (!defined(options.duration) || options.duration < 0.0) {
      throw new DeveloperError(
        "options.duration is required and must be positive."
      );
    }
    //>>includeEnd('debug');

    if (options.duration === 0.0) {
      if (defined(options.complete)) {
        options.complete();
      }
      return new Tween(this);
    }

    const duration = options.duration / TimeConstants$1.SECONDS_PER_MILLISECOND;
    const delayInSeconds = defaultValue(options.delay, 0.0);
    const delay = delayInSeconds / TimeConstants$1.SECONDS_PER_MILLISECOND;
    const easingFunction = defaultValue(
      options.easingFunction,
      EasingFunction$1.LINEAR_NONE
    );

    const value = options.startObject;
    const tweenjs = new Tween$1.Tween(value);
    tweenjs.to(clone$1(options.stopObject), duration);
    tweenjs.delay(delay);
    tweenjs.easing(easingFunction);
    if (defined(options.update)) {
      tweenjs.onUpdate(function () {
        options.update(value);
      });
    }
    tweenjs.onComplete(defaultValue(options.complete, null));
    tweenjs.repeat(defaultValue(options._repeat, 0.0));

    const tween = new Tween(
      this,
      tweenjs,
      options.startObject,
      options.stopObject,
      options.duration,
      delayInSeconds,
      easingFunction,
      options.update,
      options.complete,
      options.cancel
    );
    this._tweens.push(tween);
    return tween;
  };

  /**
   * Creates a tween for animating a scalar property on the given object.  The tween starts animating at the next call to {@link TweenCollection#update}, which
   * is implicit when {@link Viewer} or {@link CesiumWidget} render the scene.
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Object} options.object The object containing the property to animate.
   * @param {String} options.property The name of the property to animate.
   * @param {Number} options.startValue The initial value.
   * @param {Number} options.stopValue The final value.
   * @param {Number} [options.duration=3.0] The duration, in seconds, for the tween.  The tween is automatically removed from the collection when it stops.
   * @param {Number} [options.delay=0.0] The delay, in seconds, before the tween starts animating.
   * @param {EasingFunction} [options.easingFunction=EasingFunction.LINEAR_NONE] Determines the curve for animtion.
   * @param {TweenCollection.TweenUpdateCallback} [options.update] The callback to call at each animation update (usually tied to the a rendered frame).
   * @param {TweenCollection.TweenCompleteCallback} [options.complete] The callback to call when the tween finishes animating.
   * @param {TweenCollection.TweenCancelledCallback} [options.cancel] The callback to call if the tween is canceled either because {@link Tween#cancelTween} was called or because the tween was removed from the collection.
   * @returns {Tween} The tween.
   *
   * @exception {DeveloperError} options.object must have the specified property.
   * @exception {DeveloperError} options.duration must be positive.
   */
  TweenCollection.prototype.addProperty = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const object = options.object;
    const property = options.property;
    const startValue = options.startValue;
    const stopValue = options.stopValue;

    //>>includeStart('debug', pragmas.debug);
    if (!defined(object) || !defined(options.property)) {
      throw new DeveloperError(
        "options.object and options.property are required."
      );
    }
    if (!defined(object[property])) {
      throw new DeveloperError(
        "options.object must have the specified property."
      );
    }
    if (!defined(startValue) || !defined(stopValue)) {
      throw new DeveloperError(
        "options.startValue and options.stopValue are required."
      );
    }
    //>>includeEnd('debug');

    function update(value) {
      object[property] = value.value;
    }

    return this.add({
      startObject: {
        value: startValue,
      },
      stopObject: {
        value: stopValue,
      },
      duration: defaultValue(options.duration, 3.0),
      delay: options.delay,
      easingFunction: options.easingFunction,
      update: update,
      complete: options.complete,
      cancel: options.cancel,
      _repeat: options._repeat,
    });
  };

  /**
   * Creates a tween for animating the alpha of all color uniforms on a {@link Material}.  The tween starts animating at the next call to {@link TweenCollection#update}, which
   * is implicit when {@link Viewer} or {@link CesiumWidget} render the scene.
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Material} options.material The material to animate.
   * @param {Number} [options.startValue=0.0] The initial alpha value.
   * @param {Number} [options.stopValue=1.0] The final alpha value.
   * @param {Number} [options.duration=3.0] The duration, in seconds, for the tween.  The tween is automatically removed from the collection when it stops.
   * @param {Number} [options.delay=0.0] The delay, in seconds, before the tween starts animating.
   * @param {EasingFunction} [options.easingFunction=EasingFunction.LINEAR_NONE] Determines the curve for animtion.
   * @param {TweenCollection.TweenUpdateCallback} [options.update] The callback to call at each animation update (usually tied to the a rendered frame).
   * @param {TweenCollection.TweenCompleteCallback} [options.complete] The callback to call when the tween finishes animating.
   * @param {TweenCollection.TweenCancelledCallback} [options.cancel] The callback to call if the tween is canceled either because {@link Tween#cancelTween} was called or because the tween was removed from the collection.
   * @returns {Tween} The tween.
   *
   * @exception {DeveloperError} material has no properties with alpha components.
   * @exception {DeveloperError} options.duration must be positive.
   */
  TweenCollection.prototype.addAlpha = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const material = options.material;

    //>>includeStart('debug', pragmas.debug);
    if (!defined(material)) {
      throw new DeveloperError("options.material is required.");
    }
    //>>includeEnd('debug');

    const properties = [];

    for (const property in material.uniforms) {
      if (
        material.uniforms.hasOwnProperty(property) &&
        defined(material.uniforms[property]) &&
        defined(material.uniforms[property].alpha)
      ) {
        properties.push(property);
      }
    }

    //>>includeStart('debug', pragmas.debug);
    if (properties.length === 0) {
      throw new DeveloperError(
        "material has no properties with alpha components."
      );
    }
    //>>includeEnd('debug');

    function update(value) {
      const length = properties.length;
      for (let i = 0; i < length; ++i) {
        material.uniforms[properties[i]].alpha = value.alpha;
      }
    }

    return this.add({
      startObject: {
        alpha: defaultValue(options.startValue, 0.0), // Default to fade in
      },
      stopObject: {
        alpha: defaultValue(options.stopValue, 1.0),
      },
      duration: defaultValue(options.duration, 3.0),
      delay: options.delay,
      easingFunction: options.easingFunction,
      update: update,
      complete: options.complete,
      cancel: options.cancel,
    });
  };

  /**
   * Creates a tween for animating the offset uniform of a {@link Material}.  The tween starts animating at the next call to {@link TweenCollection#update}, which
   * is implicit when {@link Viewer} or {@link CesiumWidget} render the scene.
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Material} options.material The material to animate.
   * @param {Number} options.startValue The initial alpha value.
   * @param {Number} options.stopValue The final alpha value.
   * @param {Number} [options.duration=3.0] The duration, in seconds, for the tween.  The tween is automatically removed from the collection when it stops.
   * @param {Number} [options.delay=0.0] The delay, in seconds, before the tween starts animating.
   * @param {EasingFunction} [options.easingFunction=EasingFunction.LINEAR_NONE] Determines the curve for animtion.
   * @param {TweenCollection.TweenUpdateCallback} [options.update] The callback to call at each animation update (usually tied to the a rendered frame).
   * @param {TweenCollection.TweenCancelledCallback} [options.cancel] The callback to call if the tween is canceled either because {@link Tween#cancelTween} was called or because the tween was removed from the collection.
   * @returns {Tween} The tween.
   *
   * @exception {DeveloperError} material.uniforms must have an offset property.
   * @exception {DeveloperError} options.duration must be positive.
   */
  TweenCollection.prototype.addOffsetIncrement = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const material = options.material;

    //>>includeStart('debug', pragmas.debug);
    if (!defined(material)) {
      throw new DeveloperError("material is required.");
    }
    if (!defined(material.uniforms.offset)) {
      throw new DeveloperError("material.uniforms must have an offset property.");
    }
    //>>includeEnd('debug');

    const uniforms = material.uniforms;
    return this.addProperty({
      object: uniforms,
      property: "offset",
      startValue: uniforms.offset,
      stopValue: uniforms.offset + 1,
      duration: options.duration,
      delay: options.delay,
      easingFunction: options.easingFunction,
      update: options.update,
      cancel: options.cancel,
      _repeat: Infinity,
    });
  };

  /**
   * Removes a tween from the collection.
   * <p>
   * This calls the {@link Tween#cancel} callback if the tween has one.
   * </p>
   *
   * @param {Tween} tween The tween to remove.
   * @returns {Boolean} <code>true</code> if the tween was removed; <code>false</code> if the tween was not found in the collection.
   */
  TweenCollection.prototype.remove = function (tween) {
    if (!defined(tween)) {
      return false;
    }

    const index = this._tweens.indexOf(tween);
    if (index !== -1) {
      tween.tweenjs.stop();
      if (defined(tween.cancel)) {
        tween.cancel();
      }
      this._tweens.splice(index, 1);
      return true;
    }

    return false;
  };

  /**
   * Removes all tweens from the collection.
   * <p>
   * This calls the {@link Tween#cancel} callback for each tween that has one.
   * </p>
   */
  TweenCollection.prototype.removeAll = function () {
    const tweens = this._tweens;

    for (let i = 0; i < tweens.length; ++i) {
      const tween = tweens[i];
      tween.tweenjs.stop();
      if (defined(tween.cancel)) {
        tween.cancel();
      }
    }
    tweens.length = 0;
  };

  /**
   * Determines whether this collection contains a given tween.
   *
   * @param {Tween} tween The tween to check for.
   * @returns {Boolean} <code>true</code> if this collection contains the tween, <code>false</code> otherwise.
   */
  TweenCollection.prototype.contains = function (tween) {
    return defined(tween) && this._tweens.indexOf(tween) !== -1;
  };

  /**
   * Returns the tween in the collection at the specified index.  Indices are zero-based
   * and increase as tweens are added.  Removing a tween shifts all tweens after
   * it to the left, changing their indices.  This function is commonly used to iterate over
   * all the tween in the collection.
   *
   * @param {Number} index The zero-based index of the tween.
   * @returns {Tween} The tween at the specified index.
   *
   * @example
   * // Output the duration of all the tweens in the collection.
   * const tweens = scene.tweens;
   * const length = tweens.length;
   * for (let i = 0; i < length; ++i) {
   *   console.log(tweens.get(i).duration);
   * }
   */
  TweenCollection.prototype.get = function (index) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(index)) {
      throw new DeveloperError("index is required.");
    }
    //>>includeEnd('debug');

    return this._tweens[index];
  };

  /**
   * Updates the tweens in the collection to be at the provide time.  When a tween finishes, it is removed
   * from the collection.
   *
   * @param {Number} [time=getTimestamp()] The time in seconds.  By default tweens are synced to the system clock.
   */
  TweenCollection.prototype.update = function (time) {
    const tweens = this._tweens;

    let i = 0;
    time = defined(time)
      ? time / TimeConstants$1.SECONDS_PER_MILLISECOND
      : getTimestamp$1();
    while (i < tweens.length) {
      const tween = tweens[i];
      const tweenjs = tween.tweenjs;

      if (tween.needsStart) {
        tween.needsStart = false;
        tweenjs.start(time);
      } else if (tweenjs.update(time)) {
        i++;
      } else {
        tweenjs.stop();
        tweens.splice(i, 1);
      }
    }
  };

  /**
   * Modifies the camera position and orientation based on mouse input to a canvas.
   * @alias ScreenSpaceCameraController
   * @constructor
   *
   * @param {Scene} scene The scene.
   */
  function ScreenSpaceCameraController(scene) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(scene)) {
      throw new DeveloperError("scene is required.");
    }
    //>>includeEnd('debug');

    /**
     * If true, inputs are allowed conditionally with the flags enableTranslate, enableZoom,
     * enableRotate, enableTilt, and enableLook.  If false, all inputs are disabled.
     *
     * NOTE: This setting is for temporary use cases, such as camera flights and
     * drag-selection of regions (see Picking demo).  It is typically set to false at the
     * start of such events, and set true on completion.  To keep inputs disabled
     * past the end of camera flights, you must use the other booleans (enableTranslate,
     * enableZoom, enableRotate, enableTilt, and enableLook).
     * @type {Boolean}
     * @default true
     */
    this.enableInputs = true;
    /**
     * If true, allows the user to pan around the map.  If false, the camera stays locked at the current position.
     * This flag only applies in 2D and Columbus view modes.
     * @type {Boolean}
     * @default true
     */
    this.enableTranslate = true;
    /**
     * If true, allows the user to zoom in and out.  If false, the camera is locked to the current distance from the ellipsoid.
     * @type {Boolean}
     * @default true
     */
    this.enableZoom = true;
    /**
     * If true, allows the user to rotate the world which translates the user's position.
     * This flag only applies in 2D and 3D.
     * @type {Boolean}
     * @default true
     */
    this.enableRotate = true;
    /**
     * If true, allows the user to tilt the camera.  If false, the camera is locked to the current heading.
     * This flag only applies in 3D and Columbus view.
     * @type {Boolean}
     * @default true
     */
    this.enableTilt = true;
    /**
     * If true, allows the user to use free-look. If false, the camera view direction can only be changed through translating
     * or rotating. This flag only applies in 3D and Columbus view modes.
     * @type {Boolean}
     * @default true
     */
    this.enableLook = true;
    /**
     * A parameter in the range <code>[0, 1)</code> used to determine how long
     * the camera will continue to spin because of inertia.
     * With value of zero, the camera will have no inertia.
     * @type {Number}
     * @default 0.9
     */
    this.inertiaSpin = 0.9;
    /**
     * A parameter in the range <code>[0, 1)</code> used to determine how long
     * the camera will continue to translate because of inertia.
     * With value of zero, the camera will have no inertia.
     * @type {Number}
     * @default 0.9
     */
    this.inertiaTranslate = 0.9;
    /**
     * A parameter in the range <code>[0, 1)</code> used to determine how long
     * the camera will continue to zoom because of inertia.
     * With value of zero, the camera will have no inertia.
     * @type {Number}
     * @default 0.8
     */
    this.inertiaZoom = 0.8;
    /**
     * A parameter in the range <code>[0, 1)</code> used to limit the range
     * of various user inputs to a percentage of the window width/height per animation frame.
     * This helps keep the camera under control in low-frame-rate situations.
     * @type {Number}
     * @default 0.1
     */
    this.maximumMovementRatio = 0.1;
    /**
     * Sets the duration, in seconds, of the bounce back animations in 2D and Columbus view.
     * @type {Number}
     * @default 3.0
     */
    this.bounceAnimationTime = 3.0;
    /**
     * The minimum magnitude, in meters, of the camera position when zooming. Defaults to 1.0.
     * @type {Number}
     * @default 1.0
     */
    this.minimumZoomDistance = 1.0;
    /**
     * The maximum magnitude, in meters, of the camera position when zooming. Defaults to positive infinity.
     * @type {Number}
     * @default {@link Number.POSITIVE_INFINITY}
     */
    this.maximumZoomDistance = Number.POSITIVE_INFINITY;
    /**
     * The input that allows the user to pan around the map. This only applies in 2D and Columbus view modes.
     * <p>
     * The type came be a {@link CameraEventType}, <code>undefined</code>, an object with <code>eventType</code>
     * and <code>modifier</code> properties with types <code>CameraEventType</code> and {@link KeyboardEventModifier},
     * or an array of any of the preceding.
     * </p>
     * @type {CameraEventType|Array|undefined}
     * @default {@link CameraEventType.LEFT_DRAG}
     */
    this.translateEventTypes = CameraEventType$1.LEFT_DRAG;
    /**
     * The input that allows the user to zoom in/out.
     * <p>
     * The type came be a {@link CameraEventType}, <code>undefined</code>, an object with <code>eventType</code>
     * and <code>modifier</code> properties with types <code>CameraEventType</code> and {@link KeyboardEventModifier},
     * or an array of any of the preceding.
     * </p>
     * @type {CameraEventType|Array|undefined}
     * @default [{@link CameraEventType.RIGHT_DRAG}, {@link CameraEventType.WHEEL}, {@link CameraEventType.PINCH}]
     */
    this.zoomEventTypes = [
      CameraEventType$1.RIGHT_DRAG,
      CameraEventType$1.WHEEL,
      CameraEventType$1.PINCH,
    ];
    /**
     * The input that allows the user to rotate around the globe or another object. This only applies in 3D and Columbus view modes.
     * <p>
     * The type came be a {@link CameraEventType}, <code>undefined</code>, an object with <code>eventType</code>
     * and <code>modifier</code> properties with types <code>CameraEventType</code> and {@link KeyboardEventModifier},
     * or an array of any of the preceding.
     * </p>
     * @type {CameraEventType|Array|undefined}
     * @default {@link CameraEventType.LEFT_DRAG}
     */
    this.rotateEventTypes = CameraEventType$1.LEFT_DRAG;
    /**
     * The input that allows the user to tilt in 3D and Columbus view or twist in 2D.
     * <p>
     * The type came be a {@link CameraEventType}, <code>undefined</code>, an object with <code>eventType</code>
     * and <code>modifier</code> properties with types <code>CameraEventType</code> and {@link KeyboardEventModifier},
     * or an array of any of the preceding.
     * </p>
     * @type {CameraEventType|Array|undefined}
     * @default [{@link CameraEventType.MIDDLE_DRAG}, {@link CameraEventType.PINCH}, {
     *     eventType : {@link CameraEventType.LEFT_DRAG},
     *     modifier : {@link KeyboardEventModifier.CTRL}
     * }, {
     *     eventType : {@link CameraEventType.RIGHT_DRAG},
     *     modifier : {@link KeyboardEventModifier.CTRL}
     * }]
     */
    this.tiltEventTypes = [
      CameraEventType$1.MIDDLE_DRAG,
      CameraEventType$1.PINCH,
      {
        eventType: CameraEventType$1.LEFT_DRAG,
        modifier: KeyboardEventModifier$1.CTRL,
      },
      {
        eventType: CameraEventType$1.RIGHT_DRAG,
        modifier: KeyboardEventModifier$1.CTRL,
      },
    ];
    /**
     * The input that allows the user to change the direction the camera is viewing. This only applies in 3D and Columbus view modes.
     * <p>
     * The type came be a {@link CameraEventType}, <code>undefined</code>, an object with <code>eventType</code>
     * and <code>modifier</code> properties with types <code>CameraEventType</code> and {@link KeyboardEventModifier},
     * or an array of any of the preceding.
     * </p>
     * @type {CameraEventType|Array|undefined}
     * @default { eventType : {@link CameraEventType.LEFT_DRAG}, modifier : {@link KeyboardEventModifier.SHIFT} }
     */
    this.lookEventTypes = {
      eventType: CameraEventType$1.LEFT_DRAG,
      modifier: KeyboardEventModifier$1.SHIFT,
    };
    /**
     * The minimum height the camera must be before picking the terrain instead of the ellipsoid.
     * @type {Number}
     * @default 150000.0
     */
    this.minimumPickingTerrainHeight = 150000.0;
    this._minimumPickingTerrainHeight = this.minimumPickingTerrainHeight;
    /**
     * The minimum height the camera must be before testing for collision with terrain.
     * @type {Number}
     * @default 15000.0
     */
    this.minimumCollisionTerrainHeight = 15000.0;
    this._minimumCollisionTerrainHeight = this.minimumCollisionTerrainHeight;
    /**
     * The minimum height the camera must be before switching from rotating a track ball to
     * free look when clicks originate on the sky or in space.
     * @type {Number}
     * @default 7500000.0
     */
    this.minimumTrackBallHeight = 7500000.0;
    this._minimumTrackBallHeight = this.minimumTrackBallHeight;
    /**
     * Enables or disables camera collision detection with terrain.
     * @type {Boolean}
     * @default true
     */
    this.enableCollisionDetection = true;

    this._scene = scene;
    this._globe = undefined;
    this._ellipsoid = undefined;

    this._aggregator = new CameraEventAggregator(scene.canvas);

    this._lastInertiaSpinMovement = undefined;
    this._lastInertiaZoomMovement = undefined;
    this._lastInertiaTranslateMovement = undefined;
    this._lastInertiaTiltMovement = undefined;

    // Zoom disables tilt, spin, and translate inertia
    // Tilt disables spin and translate inertia
    this._inertiaDisablers = {
      _lastInertiaZoomMovement: [
        "_lastInertiaSpinMovement",
        "_lastInertiaTranslateMovement",
        "_lastInertiaTiltMovement",
      ],
      _lastInertiaTiltMovement: [
        "_lastInertiaSpinMovement",
        "_lastInertiaTranslateMovement",
      ],
    };

    this._tweens = new TweenCollection();
    this._tween = undefined;

    this._horizontalRotationAxis = undefined;

    this._tiltCenterMousePosition = new Cartesian2(-1.0, -1.0);
    this._tiltCenter = new Cartesian3();
    this._rotateMousePosition = new Cartesian2(-1.0, -1.0);
    this._rotateStartPosition = new Cartesian3();
    this._strafeStartPosition = new Cartesian3();
    this._strafeMousePosition = new Cartesian2();
    this._strafeEndMousePosition = new Cartesian2();
    this._zoomMouseStart = new Cartesian2(-1.0, -1.0);
    this._zoomWorldPosition = new Cartesian3();
    this._useZoomWorldPosition = false;
    this._tiltCVOffMap = false;
    this._looking = false;
    this._rotating = false;
    this._strafing = false;
    this._zoomingOnVector = false;
    this._zoomingUnderground = false;
    this._rotatingZoom = false;
    this._adjustedHeightForTerrain = false;
    this._cameraUnderground = false;

    const projection = scene.mapProjection;
    this._maxCoord = projection.project(
      new Cartographic(Math.PI, CesiumMath.PI_OVER_TWO)
    );

    // Constants, Make any of these public?
    this._zoomFactor = 5.0;
    this._rotateFactor = undefined;
    this._rotateRateRangeAdjustment = undefined;
    this._maximumRotateRate = 1.77;
    this._minimumRotateRate = 1.0 / 5000.0;
    this._minimumZoomRate = 20.0;
    this._maximumZoomRate = 5906376272000.0; // distance from the Sun to Pluto in meters.
    this._minimumUndergroundPickDistance = 2000.0;
    this._maximumUndergroundPickDistance = 10000.0;
  }

  function decay(time, coefficient) {
    if (time < 0) {
      return 0.0;
    }

    const tau = (1.0 - coefficient) * 25.0;
    return Math.exp(-tau * time);
  }

  function sameMousePosition(movement) {
    return Cartesian2.equalsEpsilon(
      movement.startPosition,
      movement.endPosition,
      CesiumMath.EPSILON14
    );
  }

  // If the time between mouse down and mouse up is not between
  // these thresholds, the camera will not move with inertia.
  // This value is probably dependent on the browser and/or the
  // hardware. Should be investigated further.
  const inertiaMaxClickTimeThreshold = 0.4;

  function maintainInertia(
    aggregator,
    type,
    modifier,
    decayCoef,
    action,
    object,
    lastMovementName
  ) {
    let movementState = object[lastMovementName];
    if (!defined(movementState)) {
      movementState = object[lastMovementName] = {
        startPosition: new Cartesian2(),
        endPosition: new Cartesian2(),
        motion: new Cartesian2(),
        inertiaEnabled: true,
      };
    }

    const ts = aggregator.getButtonPressTime(type, modifier);
    const tr = aggregator.getButtonReleaseTime(type, modifier);

    const threshold = ts && tr && (tr.getTime() - ts.getTime()) / 1000.0;
    const now = new Date();
    const fromNow = tr && (now.getTime() - tr.getTime()) / 1000.0;

    if (ts && tr && threshold < inertiaMaxClickTimeThreshold) {
      const d = decay(fromNow, decayCoef);

      const lastMovement = aggregator.getLastMovement(type, modifier);
      if (
        !defined(lastMovement) ||
        sameMousePosition(lastMovement) ||
        !movementState.inertiaEnabled
      ) {
        return;
      }

      movementState.motion.x =
        (lastMovement.endPosition.x - lastMovement.startPosition.x) * 0.5;
      movementState.motion.y =
        (lastMovement.endPosition.y - lastMovement.startPosition.y) * 0.5;

      movementState.startPosition = Cartesian2.clone(
        lastMovement.startPosition,
        movementState.startPosition
      );

      movementState.endPosition = Cartesian2.multiplyByScalar(
        movementState.motion,
        d,
        movementState.endPosition
      );
      movementState.endPosition = Cartesian2.add(
        movementState.startPosition,
        movementState.endPosition,
        movementState.endPosition
      );

      // If value from the decreasing exponential function is close to zero,
      // the end coordinates may be NaN.
      if (
        isNaN(movementState.endPosition.x) ||
        isNaN(movementState.endPosition.y) ||
        Cartesian2.distance(
          movementState.startPosition,
          movementState.endPosition
        ) < 0.5
      ) {
        return;
      }

      if (!aggregator.isButtonDown(type, modifier)) {
        const startPosition = aggregator.getStartMousePosition(type, modifier);
        action(object, startPosition, movementState);
      }
    }
  }

  function activateInertia(controller, inertiaStateName) {
    if (defined(inertiaStateName)) {
      // Re-enable inertia if it was disabled
      let movementState = controller[inertiaStateName];
      if (defined(movementState)) {
        movementState.inertiaEnabled = true;
      }
      // Disable inertia on other movements
      const inertiasToDisable = controller._inertiaDisablers[inertiaStateName];
      if (defined(inertiasToDisable)) {
        const length = inertiasToDisable.length;
        for (let i = 0; i < length; ++i) {
          movementState = controller[inertiasToDisable[i]];
          if (defined(movementState)) {
            movementState.inertiaEnabled = false;
          }
        }
      }
    }
  }

  const scratchEventTypeArray = [];

  function reactToInput(
    controller,
    enabled,
    eventTypes,
    action,
    inertiaConstant,
    inertiaStateName
  ) {
    if (!defined(eventTypes)) {
      return;
    }

    const aggregator = controller._aggregator;

    if (!Array.isArray(eventTypes)) {
      scratchEventTypeArray[0] = eventTypes;
      eventTypes = scratchEventTypeArray;
    }

    const length = eventTypes.length;
    for (let i = 0; i < length; ++i) {
      const eventType = eventTypes[i];
      const type = defined(eventType.eventType) ? eventType.eventType : eventType;
      const modifier = eventType.modifier;

      const movement =
        aggregator.isMoving(type, modifier) &&
        aggregator.getMovement(type, modifier);
      const startPosition = aggregator.getStartMousePosition(type, modifier);

      if (controller.enableInputs && enabled) {
        if (movement) {
          action(controller, startPosition, movement);
          activateInertia(controller, inertiaStateName);
        } else if (inertiaConstant < 1.0) {
          maintainInertia(
            aggregator,
            type,
            modifier,
            inertiaConstant,
            action,
            controller,
            inertiaStateName
          );
        }
      }
    }
  }

  const scratchZoomPickRay = new Ray();
  const scratchPickCartesian$1 = new Cartesian3();
  const scratchZoomOffset = new Cartesian2();
  const scratchZoomDirection = new Cartesian3();
  const scratchCenterPixel = new Cartesian2();
  const scratchCenterPosition = new Cartesian3();
  const scratchPositionNormal = new Cartesian3();
  const scratchPickNormal = new Cartesian3();
  const scratchZoomAxis = new Cartesian3();
  const scratchCameraPositionNormal = new Cartesian3();

  // Scratch variables used in zooming algorithm
  const scratchTargetNormal = new Cartesian3();
  const scratchCameraPosition = new Cartesian3();
  const scratchCameraUpNormal = new Cartesian3();
  const scratchCameraRightNormal = new Cartesian3();
  const scratchForwardNormal = new Cartesian3();
  const scratchPositionToTarget = new Cartesian3();
  const scratchPositionToTargetNormal = new Cartesian3();
  const scratchPan = new Cartesian3();
  const scratchCenterMovement = new Cartesian3();
  const scratchCenter = new Cartesian3();
  const scratchCartesian = new Cartesian3();
  const scratchCartesianTwo = new Cartesian3();
  const scratchCartesianThree = new Cartesian3();
  const scratchZoomViewOptions = {
    orientation: new HeadingPitchRoll(),
  };

  function handleZoom(
    object,
    startPosition,
    movement,
    zoomFactor,
    distanceMeasure,
    unitPositionDotDirection
  ) {
    let percentage = 1.0;
    if (defined(unitPositionDotDirection)) {
      percentage = CesiumMath.clamp(
        Math.abs(unitPositionDotDirection),
        0.25,
        1.0
      );
    }

    const diff = movement.endPosition.y - movement.startPosition.y;

    // distanceMeasure should be the height above the ellipsoid.
    // When approaching the surface, the zoomRate slows and stops minimumZoomDistance above it.
    const approachingSurface = diff > 0;
    const minHeight = approachingSurface
      ? object.minimumZoomDistance * percentage
      : 0;
    const maxHeight = object.maximumZoomDistance;

    const minDistance = distanceMeasure - minHeight;
    let zoomRate = zoomFactor * minDistance;
    zoomRate = CesiumMath.clamp(
      zoomRate,
      object._minimumZoomRate,
      object._maximumZoomRate
    );

    let rangeWindowRatio = diff / object._scene.canvas.clientHeight;
    rangeWindowRatio = Math.min(rangeWindowRatio, object.maximumMovementRatio);
    let distance = zoomRate * rangeWindowRatio;

    if (
      object.enableCollisionDetection ||
      object.minimumZoomDistance === 0.0 ||
      !defined(object._globe) // look-at mode
    ) {
      if (distance > 0.0 && Math.abs(distanceMeasure - minHeight) < 1.0) {
        return;
      }

      if (distance < 0.0 && Math.abs(distanceMeasure - maxHeight) < 1.0) {
        return;
      }

      if (distanceMeasure - distance < minHeight) {
        distance = distanceMeasure - minHeight - 1.0;
      } else if (distanceMeasure - distance > maxHeight) {
        distance = distanceMeasure - maxHeight;
      }
    }

    const scene = object._scene;
    const camera = scene.camera;
    const mode = scene.mode;

    const orientation = scratchZoomViewOptions.orientation;
    orientation.heading = camera.heading;
    orientation.pitch = camera.pitch;
    orientation.roll = camera.roll;

    if (camera.frustum instanceof OrthographicFrustum) {
      if (Math.abs(distance) > 0.0) {
        camera.zoomIn(distance);
        camera._adjustOrthographicFrustum();
      }
      return;
    }

    const sameStartPosition = Cartesian2.equals(
      startPosition,
      object._zoomMouseStart
    );
    let zoomingOnVector = object._zoomingOnVector;
    let rotatingZoom = object._rotatingZoom;
    let pickedPosition;

    if (!sameStartPosition) {
      object._zoomMouseStart = Cartesian2.clone(
        startPosition,
        object._zoomMouseStart
      );

      if (defined(object._globe)) {
        if (mode === SceneMode$1.SCENE2D) {
          pickedPosition = camera.getPickRay(startPosition, scratchZoomPickRay)
            .origin;
          pickedPosition = Cartesian3.fromElements(
            pickedPosition.y,
            pickedPosition.z,
            pickedPosition.x
          );
        } else {
          pickedPosition = pickGlobe(object, startPosition, scratchPickCartesian$1);
        }
      }
      if (defined(pickedPosition)) {
        object._useZoomWorldPosition = true;
        object._zoomWorldPosition = Cartesian3.clone(
          pickedPosition,
          object._zoomWorldPosition
        );
      } else {
        object._useZoomWorldPosition = false;
      }

      zoomingOnVector = object._zoomingOnVector = false;
      rotatingZoom = object._rotatingZoom = false;
      object._zoomingUnderground = object._cameraUnderground;
    }

    if (!object._useZoomWorldPosition) {
      camera.zoomIn(distance);
      return;
    }

    let zoomOnVector = mode === SceneMode$1.COLUMBUS_VIEW;

    if (camera.positionCartographic.height < 2000000) {
      rotatingZoom = true;
    }

    if (!sameStartPosition || rotatingZoom) {
      if (mode === SceneMode$1.SCENE2D) {
        const worldPosition = object._zoomWorldPosition;
        const endPosition = camera.position;

        if (
          !Cartesian3.equals(worldPosition, endPosition) &&
          camera.positionCartographic.height < object._maxCoord.x * 2.0
        ) {
          const savedX = camera.position.x;

          const direction = Cartesian3.subtract(
            worldPosition,
            endPosition,
            scratchZoomDirection
          );
          Cartesian3.normalize(direction, direction);

          const d =
            (Cartesian3.distance(worldPosition, endPosition) * distance) /
            (camera.getMagnitude() * 0.5);
          camera.move(direction, d * 0.5);

          if (
            (camera.position.x < 0.0 && savedX > 0.0) ||
            (camera.position.x > 0.0 && savedX < 0.0)
          ) {
            pickedPosition = camera.getPickRay(startPosition, scratchZoomPickRay)
              .origin;
            pickedPosition = Cartesian3.fromElements(
              pickedPosition.y,
              pickedPosition.z,
              pickedPosition.x
            );
            object._zoomWorldPosition = Cartesian3.clone(
              pickedPosition,
              object._zoomWorldPosition
            );
          }
        }
      } else if (mode === SceneMode$1.SCENE3D) {
        const cameraPositionNormal = Cartesian3.normalize(
          camera.position,
          scratchCameraPositionNormal
        );
        if (
          object._cameraUnderground ||
          object._zoomingUnderground ||
          (camera.positionCartographic.height < 3000.0 &&
            Math.abs(Cartesian3.dot(camera.direction, cameraPositionNormal)) <
              0.6)
        ) {
          zoomOnVector = true;
        } else {
          const canvas = scene.canvas;

          const centerPixel = scratchCenterPixel;
          centerPixel.x = canvas.clientWidth / 2;
          centerPixel.y = canvas.clientHeight / 2;
          const centerPosition = pickGlobe(
            object,
            centerPixel,
            scratchCenterPosition
          );
          // If centerPosition is not defined, it means the globe does not cover the center position of screen

          if (!defined(centerPosition)) {
            zoomOnVector = true;
          } else if (camera.positionCartographic.height < 1000000) {
            // The math in the else block assumes the camera
            // points toward the earth surface, so we check it here.
            // Theoretically, we should check for 90 degree, but it doesn't behave well when parallel
            // to the earth surface
            if (Cartesian3.dot(camera.direction, cameraPositionNormal) >= -0.5) {
              zoomOnVector = true;
            } else {
              const cameraPosition = scratchCameraPosition;
              Cartesian3.clone(camera.position, cameraPosition);
              const target = object._zoomWorldPosition;

              let targetNormal = scratchTargetNormal;

              targetNormal = Cartesian3.normalize(target, targetNormal);

              if (Cartesian3.dot(targetNormal, cameraPositionNormal) < 0.0) {
                return;
              }

              const center = scratchCenter;
              const forward = scratchForwardNormal;
              Cartesian3.clone(camera.direction, forward);
              Cartesian3.add(
                cameraPosition,
                Cartesian3.multiplyByScalar(forward, 1000, scratchCartesian),
                center
              );

              const positionToTarget = scratchPositionToTarget;
              const positionToTargetNormal = scratchPositionToTargetNormal;
              Cartesian3.subtract(target, cameraPosition, positionToTarget);

              Cartesian3.normalize(positionToTarget, positionToTargetNormal);

              const alphaDot = Cartesian3.dot(
                cameraPositionNormal,
                positionToTargetNormal
              );
              if (alphaDot >= 0.0) {
                // We zoomed past the target, and this zoom is not valid anymore.
                // This line causes the next zoom movement to pick a new starting point.
                object._zoomMouseStart.x = -1;
                return;
              }
              const alpha = Math.acos(-alphaDot);
              const cameraDistance = Cartesian3.magnitude(cameraPosition);
              const targetDistance = Cartesian3.magnitude(target);
              const remainingDistance = cameraDistance - distance;
              const positionToTargetDistance = Cartesian3.magnitude(
                positionToTarget
              );

              const gamma = Math.asin(
                CesiumMath.clamp(
                  (positionToTargetDistance / targetDistance) * Math.sin(alpha),
                  -1.0,
                  1.0
                )
              );
              const delta = Math.asin(
                CesiumMath.clamp(
                  (remainingDistance / targetDistance) * Math.sin(alpha),
                  -1.0,
                  1.0
                )
              );
              const beta = gamma - delta + alpha;

              const up = scratchCameraUpNormal;
              Cartesian3.normalize(cameraPosition, up);
              let right = scratchCameraRightNormal;
              right = Cartesian3.cross(positionToTargetNormal, up, right);
              right = Cartesian3.normalize(right, right);

              Cartesian3.normalize(
                Cartesian3.cross(up, right, scratchCartesian),
                forward
              );

              // Calculate new position to move to
              Cartesian3.multiplyByScalar(
                Cartesian3.normalize(center, scratchCartesian),
                Cartesian3.magnitude(center) - distance,
                center
              );
              Cartesian3.normalize(cameraPosition, cameraPosition);
              Cartesian3.multiplyByScalar(
                cameraPosition,
                remainingDistance,
                cameraPosition
              );

              // Pan
              const pMid = scratchPan;
              Cartesian3.multiplyByScalar(
                Cartesian3.add(
                  Cartesian3.multiplyByScalar(
                    up,
                    Math.cos(beta) - 1,
                    scratchCartesianTwo
                  ),
                  Cartesian3.multiplyByScalar(
                    forward,
                    Math.sin(beta),
                    scratchCartesianThree
                  ),
                  scratchCartesian
                ),
                remainingDistance,
                pMid
              );
              Cartesian3.add(cameraPosition, pMid, cameraPosition);

              Cartesian3.normalize(center, up);
              Cartesian3.normalize(
                Cartesian3.cross(up, right, scratchCartesian),
                forward
              );

              const cMid = scratchCenterMovement;
              Cartesian3.multiplyByScalar(
                Cartesian3.add(
                  Cartesian3.multiplyByScalar(
                    up,
                    Math.cos(beta) - 1,
                    scratchCartesianTwo
                  ),
                  Cartesian3.multiplyByScalar(
                    forward,
                    Math.sin(beta),
                    scratchCartesianThree
                  ),
                  scratchCartesian
                ),
                Cartesian3.magnitude(center),
                cMid
              );
              Cartesian3.add(center, cMid, center);

              // Update camera

              // Set new position
              Cartesian3.clone(cameraPosition, camera.position);

              // Set new direction
              Cartesian3.normalize(
                Cartesian3.subtract(center, cameraPosition, scratchCartesian),
                camera.direction
              );
              Cartesian3.clone(camera.direction, camera.direction);

              // Set new right & up vectors
              Cartesian3.cross(camera.direction, camera.up, camera.right);
              Cartesian3.cross(camera.right, camera.direction, camera.up);

              camera.setView(scratchZoomViewOptions);
              return;
            }
          } else {
            const positionNormal = Cartesian3.normalize(
              centerPosition,
              scratchPositionNormal
            );
            const pickedNormal = Cartesian3.normalize(
              object._zoomWorldPosition,
              scratchPickNormal
            );
            const dotProduct = Cartesian3.dot(pickedNormal, positionNormal);

            if (dotProduct > 0.0 && dotProduct < 1.0) {
              const angle = CesiumMath.acosClamped(dotProduct);
              const axis = Cartesian3.cross(
                pickedNormal,
                positionNormal,
                scratchZoomAxis
              );

              const denom =
                Math.abs(angle) > CesiumMath.toRadians(20.0)
                  ? camera.positionCartographic.height * 0.75
                  : camera.positionCartographic.height - distance;
              const scalar = distance / denom;
              camera.rotate(axis, angle * scalar);
            }
          }
        }
      }

      object._rotatingZoom = !zoomOnVector;
    }

    if ((!sameStartPosition && zoomOnVector) || zoomingOnVector) {
      let ray;
      const zoomMouseStart = SceneTransforms.wgs84ToWindowCoordinates(
        scene,
        object._zoomWorldPosition,
        scratchZoomOffset
      );
      if (
        mode !== SceneMode$1.COLUMBUS_VIEW &&
        Cartesian2.equals(startPosition, object._zoomMouseStart) &&
        defined(zoomMouseStart)
      ) {
        ray = camera.getPickRay(zoomMouseStart, scratchZoomPickRay);
      } else {
        ray = camera.getPickRay(startPosition, scratchZoomPickRay);
      }

      const rayDirection = ray.direction;
      if (mode === SceneMode$1.COLUMBUS_VIEW || mode === SceneMode$1.SCENE2D) {
        Cartesian3.fromElements(
          rayDirection.y,
          rayDirection.z,
          rayDirection.x,
          rayDirection
        );
      }

      camera.move(rayDirection, distance);

      object._zoomingOnVector = true;
    } else {
      camera.zoomIn(distance);
    }

    if (!object._cameraUnderground) {
      camera.setView(scratchZoomViewOptions);
    }
  }

  const translate2DStart = new Ray();
  const translate2DEnd = new Ray();
  const scratchTranslateP0 = new Cartesian3();

  function translate2D(controller, startPosition, movement) {
    const scene = controller._scene;
    const camera = scene.camera;
    let start = camera.getPickRay(movement.startPosition, translate2DStart)
      .origin;
    let end = camera.getPickRay(movement.endPosition, translate2DEnd).origin;

    start = Cartesian3.fromElements(start.y, start.z, start.x, start);
    end = Cartesian3.fromElements(end.y, end.z, end.x, end);

    const direction = Cartesian3.subtract(start, end, scratchTranslateP0);
    const distance = Cartesian3.magnitude(direction);

    if (distance > 0.0) {
      Cartesian3.normalize(direction, direction);
      camera.move(direction, distance);
    }
  }

  function zoom2D(controller, startPosition, movement) {
    if (defined(movement.distance)) {
      movement = movement.distance;
    }

    const scene = controller._scene;
    const camera = scene.camera;

    handleZoom(
      controller,
      startPosition,
      movement,
      controller._zoomFactor,
      camera.getMagnitude()
    );
  }

  const twist2DStart = new Cartesian2();
  const twist2DEnd = new Cartesian2();

  function twist2D(controller, startPosition, movement) {
    if (defined(movement.angleAndHeight)) {
      singleAxisTwist2D(controller, startPosition, movement.angleAndHeight);
      return;
    }

    const scene = controller._scene;
    const camera = scene.camera;
    const canvas = scene.canvas;
    const width = canvas.clientWidth;
    const height = canvas.clientHeight;

    let start = twist2DStart;
    start.x = (2.0 / width) * movement.startPosition.x - 1.0;
    start.y = (2.0 / height) * (height - movement.startPosition.y) - 1.0;
    start = Cartesian2.normalize(start, start);

    let end = twist2DEnd;
    end.x = (2.0 / width) * movement.endPosition.x - 1.0;
    end.y = (2.0 / height) * (height - movement.endPosition.y) - 1.0;
    end = Cartesian2.normalize(end, end);

    let startTheta = CesiumMath.acosClamped(start.x);
    if (start.y < 0) {
      startTheta = CesiumMath.TWO_PI - startTheta;
    }
    let endTheta = CesiumMath.acosClamped(end.x);
    if (end.y < 0) {
      endTheta = CesiumMath.TWO_PI - endTheta;
    }
    const theta = endTheta - startTheta;

    camera.twistRight(theta);
  }

  function singleAxisTwist2D(controller, startPosition, movement) {
    let rotateRate =
      controller._rotateFactor * controller._rotateRateRangeAdjustment;

    if (rotateRate > controller._maximumRotateRate) {
      rotateRate = controller._maximumRotateRate;
    }

    if (rotateRate < controller._minimumRotateRate) {
      rotateRate = controller._minimumRotateRate;
    }

    const scene = controller._scene;
    const camera = scene.camera;
    const canvas = scene.canvas;

    let phiWindowRatio =
      (movement.endPosition.x - movement.startPosition.x) / canvas.clientWidth;
    phiWindowRatio = Math.min(phiWindowRatio, controller.maximumMovementRatio);

    const deltaPhi = rotateRate * phiWindowRatio * Math.PI * 4.0;

    camera.twistRight(deltaPhi);
  }

  function update2D(controller) {
    const rotatable2D = controller._scene.mapMode2D === MapMode2D$1.ROTATE;
    if (!Matrix4.equals(Matrix4.IDENTITY, controller._scene.camera.transform)) {
      reactToInput(
        controller,
        controller.enableZoom,
        controller.zoomEventTypes,
        zoom2D,
        controller.inertiaZoom,
        "_lastInertiaZoomMovement"
      );
      if (rotatable2D) {
        reactToInput(
          controller,
          controller.enableRotate,
          controller.translateEventTypes,
          twist2D,
          controller.inertiaSpin,
          "_lastInertiaSpinMovement"
        );
      }
    } else {
      reactToInput(
        controller,
        controller.enableTranslate,
        controller.translateEventTypes,
        translate2D,
        controller.inertiaTranslate,
        "_lastInertiaTranslateMovement"
      );
      reactToInput(
        controller,
        controller.enableZoom,
        controller.zoomEventTypes,
        zoom2D,
        controller.inertiaZoom,
        "_lastInertiaZoomMovement"
      );
      if (rotatable2D) {
        reactToInput(
          controller,
          controller.enableRotate,
          controller.tiltEventTypes,
          twist2D,
          controller.inertiaSpin,
          "_lastInertiaTiltMovement"
        );
      }
    }
  }

  const pickGlobeScratchRay = new Ray();
  const scratchDepthIntersection = new Cartesian3();
  const scratchRayIntersection = new Cartesian3();

  function pickGlobe(controller, mousePosition, result) {
    const scene = controller._scene;
    const globe = controller._globe;
    const camera = scene.camera;

    if (!defined(globe)) {
      return undefined;
    }

    const cullBackFaces = !controller._cameraUnderground;

    let depthIntersection;
    if (scene.pickPositionSupported) {
      depthIntersection = scene.pickPositionWorldCoordinates(
        mousePosition,
        scratchDepthIntersection
      );
    }

    const ray = camera.getPickRay(mousePosition, pickGlobeScratchRay);
    const rayIntersection = globe.pickWorldCoordinates(
      ray,
      scene,
      cullBackFaces,
      scratchRayIntersection
    );

    const pickDistance = defined(depthIntersection)
      ? Cartesian3.distance(depthIntersection, camera.positionWC)
      : Number.POSITIVE_INFINITY;
    const rayDistance = defined(rayIntersection)
      ? Cartesian3.distance(rayIntersection, camera.positionWC)
      : Number.POSITIVE_INFINITY;

    if (pickDistance < rayDistance) {
      return Cartesian3.clone(depthIntersection, result);
    }

    return Cartesian3.clone(rayIntersection, result);
  }

  const scratchDistanceCartographic = new Cartographic();

  function getDistanceFromSurface(controller) {
    const ellipsoid = controller._ellipsoid;
    const scene = controller._scene;
    const camera = scene.camera;
    const mode = scene.mode;

    let height = 0.0;
    if (mode === SceneMode$1.SCENE3D) {
      const cartographic = ellipsoid.cartesianToCartographic(
        camera.position,
        scratchDistanceCartographic
      );
      if (defined(cartographic)) {
        height = cartographic.height;
      }
    } else {
      height = camera.position.z;
    }
    const globeHeight = defaultValue(controller._scene.globeHeight, 0.0);
    const distanceFromSurface = Math.abs(globeHeight - height);
    return distanceFromSurface;
  }

  const scratchSurfaceNormal = new Cartesian3();

  function getZoomDistanceUnderground(controller, ray) {
    const origin = ray.origin;
    const direction = ray.direction;
    const distanceFromSurface = getDistanceFromSurface(controller);

    // Weight zoom distance based on how strongly the pick ray is pointing inward.
    // Geocentric normal is accurate enough for these purposes
    const surfaceNormal = Cartesian3.normalize(origin, scratchSurfaceNormal);
    let strength = Math.abs(Cartesian3.dot(surfaceNormal, direction));
    strength = Math.max(strength, 0.5) * 2.0;
    return distanceFromSurface * strength;
  }

  function getTiltCenterUnderground(controller, ray, pickedPosition, result) {
    let distance = Cartesian3.distance(ray.origin, pickedPosition);
    const distanceFromSurface = getDistanceFromSurface(controller);

    const maximumDistance = CesiumMath.clamp(
      distanceFromSurface * 5.0,
      controller._minimumUndergroundPickDistance,
      controller._maximumUndergroundPickDistance
    );

    if (distance > maximumDistance) {
      // Simulate look-at behavior by tilting around a small invisible sphere
      distance = Math.min(distance, distanceFromSurface / 5.0);
      distance = Math.max(distance, 100.0);
    }

    return Ray.getPoint(ray, distance, result);
  }

  function getStrafeStartPositionUnderground(
    controller,
    ray,
    pickedPosition,
    result
  ) {
    let distance;
    if (!defined(pickedPosition)) {
      distance = getDistanceFromSurface(controller);
    } else {
      distance = Cartesian3.distance(ray.origin, pickedPosition);
      if (distance > controller._maximumUndergroundPickDistance) {
        // If the picked position is too far away set the strafe speed based on the
        // camera's height from the globe surface
        distance = getDistanceFromSurface(controller);
      }
    }

    return Ray.getPoint(ray, distance, result);
  }

  const scratchInertialDelta = new Cartesian2();

  function continueStrafing(controller, movement) {
    // Update the end position continually based on the inertial delta
    const originalEndPosition = movement.endPosition;
    const inertialDelta = Cartesian2.subtract(
      movement.endPosition,
      movement.startPosition,
      scratchInertialDelta
    );
    const endPosition = controller._strafeEndMousePosition;
    Cartesian2.add(endPosition, inertialDelta, endPosition);
    movement.endPosition = endPosition;
    strafe(controller, movement, controller._strafeStartPosition);
    movement.endPosition = originalEndPosition;
  }

  const translateCVStartRay = new Ray();
  const translateCVEndRay = new Ray();
  const translateCVStartPos = new Cartesian3();
  const translateCVEndPos = new Cartesian3();
  const translateCVDifference = new Cartesian3();
  const translateCVOrigin = new Cartesian3();
  const translateCVPlane = new Plane(Cartesian3.UNIT_X, 0.0);
  const translateCVStartMouse = new Cartesian2();
  const translateCVEndMouse = new Cartesian2();

  function translateCV(controller, startPosition, movement) {
    if (!Cartesian3.equals(startPosition, controller._translateMousePosition)) {
      controller._looking = false;
    }

    if (!Cartesian3.equals(startPosition, controller._strafeMousePosition)) {
      controller._strafing = false;
    }

    if (controller._looking) {
      look3D(controller, startPosition, movement);
      return;
    }

    if (controller._strafing) {
      continueStrafing(controller, movement);
      return;
    }

    const scene = controller._scene;
    const camera = scene.camera;
    const cameraUnderground = controller._cameraUnderground;
    const startMouse = Cartesian2.clone(
      movement.startPosition,
      translateCVStartMouse
    );
    const endMouse = Cartesian2.clone(movement.endPosition, translateCVEndMouse);
    let startRay = camera.getPickRay(startMouse, translateCVStartRay);

    const origin = Cartesian3.clone(Cartesian3.ZERO, translateCVOrigin);
    const normal = Cartesian3.UNIT_X;

    let globePos;
    if (camera.position.z < controller._minimumPickingTerrainHeight) {
      globePos = pickGlobe(controller, startMouse, translateCVStartPos);
      if (defined(globePos)) {
        origin.x = globePos.x;
      }
    }

    if (
      cameraUnderground ||
      (origin.x > camera.position.z && defined(globePos))
    ) {
      let pickPosition = globePos;
      if (cameraUnderground) {
        pickPosition = getStrafeStartPositionUnderground(
          controller,
          startRay,
          globePos,
          translateCVStartPos
        );
      }
      Cartesian2.clone(startPosition, controller._strafeMousePosition);
      Cartesian2.clone(startPosition, controller._strafeEndMousePosition);
      Cartesian3.clone(pickPosition, controller._strafeStartPosition);
      controller._strafing = true;
      strafe(controller, movement, controller._strafeStartPosition);
      return;
    }

    const plane = Plane.fromPointNormal(origin, normal, translateCVPlane);

    startRay = camera.getPickRay(startMouse, translateCVStartRay);
    const startPlanePos = IntersectionTests.rayPlane(
      startRay,
      plane,
      translateCVStartPos
    );

    const endRay = camera.getPickRay(endMouse, translateCVEndRay);
    const endPlanePos = IntersectionTests.rayPlane(
      endRay,
      plane,
      translateCVEndPos
    );

    if (!defined(startPlanePos) || !defined(endPlanePos)) {
      controller._looking = true;
      look3D(controller, startPosition, movement);
      Cartesian2.clone(startPosition, controller._translateMousePosition);
      return;
    }

    const diff = Cartesian3.subtract(
      startPlanePos,
      endPlanePos,
      translateCVDifference
    );
    const temp = diff.x;
    diff.x = diff.y;
    diff.y = diff.z;
    diff.z = temp;
    const mag = Cartesian3.magnitude(diff);
    if (mag > CesiumMath.EPSILON6) {
      Cartesian3.normalize(diff, diff);
      camera.move(diff, mag);
    }
  }

  const rotateCVWindowPos = new Cartesian2();
  const rotateCVWindowRay = new Ray();
  const rotateCVCenter = new Cartesian3();
  const rotateCVVerticalCenter = new Cartesian3();
  const rotateCVTransform = new Matrix4();
  const rotateCVVerticalTransform = new Matrix4();
  const rotateCVOrigin = new Cartesian3();
  const rotateCVPlane = new Plane(Cartesian3.UNIT_X, 0.0);
  const rotateCVCartesian3 = new Cartesian3();
  const rotateCVCart = new Cartographic();
  const rotateCVOldTransform = new Matrix4();
  const rotateCVQuaternion = new Quaternion();
  const rotateCVMatrix = new Matrix3();
  const tilt3DCartesian3 = new Cartesian3();

  function rotateCV(controller, startPosition, movement) {
    if (defined(movement.angleAndHeight)) {
      movement = movement.angleAndHeight;
    }

    if (!Cartesian2.equals(startPosition, controller._tiltCenterMousePosition)) {
      controller._tiltCVOffMap = false;
      controller._looking = false;
    }

    if (controller._looking) {
      look3D(controller, startPosition, movement);
      return;
    }

    const scene = controller._scene;
    const camera = scene.camera;

    if (
      controller._tiltCVOffMap ||
      !controller.onMap() ||
      Math.abs(camera.position.z) > controller._minimumPickingTerrainHeight
    ) {
      controller._tiltCVOffMap = true;
      rotateCVOnPlane(controller, startPosition, movement);
    } else {
      rotateCVOnTerrain(controller, startPosition, movement);
    }
  }

  function rotateCVOnPlane(controller, startPosition, movement) {
    const scene = controller._scene;
    const camera = scene.camera;
    const canvas = scene.canvas;

    const windowPosition = rotateCVWindowPos;
    windowPosition.x = canvas.clientWidth / 2;
    windowPosition.y = canvas.clientHeight / 2;
    const ray = camera.getPickRay(windowPosition, rotateCVWindowRay);
    const normal = Cartesian3.UNIT_X;

    const position = ray.origin;
    const direction = ray.direction;
    let scalar;
    const normalDotDirection = Cartesian3.dot(normal, direction);
    if (Math.abs(normalDotDirection) > CesiumMath.EPSILON6) {
      scalar = -Cartesian3.dot(normal, position) / normalDotDirection;
    }

    if (!defined(scalar) || scalar <= 0.0) {
      controller._looking = true;
      look3D(controller, startPosition, movement);
      Cartesian2.clone(startPosition, controller._tiltCenterMousePosition);
      return;
    }

    const center = Cartesian3.multiplyByScalar(direction, scalar, rotateCVCenter);
    Cartesian3.add(position, center, center);

    const projection = scene.mapProjection;
    const ellipsoid = projection.ellipsoid;

    Cartesian3.fromElements(center.y, center.z, center.x, center);
    const cart = projection.unproject(center, rotateCVCart);
    ellipsoid.cartographicToCartesian(cart, center);

    const transform = Transforms.eastNorthUpToFixedFrame(
      center,
      ellipsoid,
      rotateCVTransform
    );

    const oldGlobe = controller._globe;
    const oldEllipsoid = controller._ellipsoid;
    controller._globe = undefined;
    controller._ellipsoid = Ellipsoid.UNIT_SPHERE;
    controller._rotateFactor = 1.0;
    controller._rotateRateRangeAdjustment = 1.0;

    const oldTransform = Matrix4.clone(camera.transform, rotateCVOldTransform);
    camera._setTransform(transform);

    rotate3D(controller, startPosition, movement, Cartesian3.UNIT_Z);

    camera._setTransform(oldTransform);
    controller._globe = oldGlobe;
    controller._ellipsoid = oldEllipsoid;

    const radius = oldEllipsoid.maximumRadius;
    controller._rotateFactor = 1.0 / radius;
    controller._rotateRateRangeAdjustment = radius;
  }

  function rotateCVOnTerrain(controller, startPosition, movement) {
    const scene = controller._scene;
    const camera = scene.camera;
    const cameraUnderground = controller._cameraUnderground;

    let center;
    let ray;
    const normal = Cartesian3.UNIT_X;

    if (Cartesian2.equals(startPosition, controller._tiltCenterMousePosition)) {
      center = Cartesian3.clone(controller._tiltCenter, rotateCVCenter);
    } else {
      if (camera.position.z < controller._minimumPickingTerrainHeight) {
        center = pickGlobe(controller, startPosition, rotateCVCenter);
      }

      if (!defined(center)) {
        ray = camera.getPickRay(startPosition, rotateCVWindowRay);
        const position = ray.origin;
        const direction = ray.direction;

        let scalar;
        const normalDotDirection = Cartesian3.dot(normal, direction);
        if (Math.abs(normalDotDirection) > CesiumMath.EPSILON6) {
          scalar = -Cartesian3.dot(normal, position) / normalDotDirection;
        }

        if (!defined(scalar) || scalar <= 0.0) {
          controller._looking = true;
          look3D(controller, startPosition, movement);
          Cartesian2.clone(startPosition, controller._tiltCenterMousePosition);
          return;
        }

        center = Cartesian3.multiplyByScalar(direction, scalar, rotateCVCenter);
        Cartesian3.add(position, center, center);
      }

      if (cameraUnderground) {
        if (!defined(ray)) {
          ray = camera.getPickRay(startPosition, rotateCVWindowRay);
        }
        getTiltCenterUnderground(controller, ray, center, center);
      }

      Cartesian2.clone(startPosition, controller._tiltCenterMousePosition);
      Cartesian3.clone(center, controller._tiltCenter);
    }

    const canvas = scene.canvas;

    const windowPosition = rotateCVWindowPos;
    windowPosition.x = canvas.clientWidth / 2;
    windowPosition.y = controller._tiltCenterMousePosition.y;
    ray = camera.getPickRay(windowPosition, rotateCVWindowRay);

    const origin = Cartesian3.clone(Cartesian3.ZERO, rotateCVOrigin);
    origin.x = center.x;

    const plane = Plane.fromPointNormal(origin, normal, rotateCVPlane);
    const verticalCenter = IntersectionTests.rayPlane(
      ray,
      plane,
      rotateCVVerticalCenter
    );

    const projection = camera._projection;
    const ellipsoid = projection.ellipsoid;

    Cartesian3.fromElements(center.y, center.z, center.x, center);
    let cart = projection.unproject(center, rotateCVCart);
    ellipsoid.cartographicToCartesian(cart, center);

    const transform = Transforms.eastNorthUpToFixedFrame(
      center,
      ellipsoid,
      rotateCVTransform
    );

    let verticalTransform;
    if (defined(verticalCenter)) {
      Cartesian3.fromElements(
        verticalCenter.y,
        verticalCenter.z,
        verticalCenter.x,
        verticalCenter
      );
      cart = projection.unproject(verticalCenter, rotateCVCart);
      ellipsoid.cartographicToCartesian(cart, verticalCenter);

      verticalTransform = Transforms.eastNorthUpToFixedFrame(
        verticalCenter,
        ellipsoid,
        rotateCVVerticalTransform
      );
    } else {
      verticalTransform = transform;
    }

    const oldGlobe = controller._globe;
    const oldEllipsoid = controller._ellipsoid;
    controller._globe = undefined;
    controller._ellipsoid = Ellipsoid.UNIT_SPHERE;
    controller._rotateFactor = 1.0;
    controller._rotateRateRangeAdjustment = 1.0;

    let constrainedAxis = Cartesian3.UNIT_Z;

    const oldTransform = Matrix4.clone(camera.transform, rotateCVOldTransform);
    camera._setTransform(transform);

    const tangent = Cartesian3.cross(
      Cartesian3.UNIT_Z,
      Cartesian3.normalize(camera.position, rotateCVCartesian3),
      rotateCVCartesian3
    );
    const dot = Cartesian3.dot(camera.right, tangent);

    rotate3D(controller, startPosition, movement, constrainedAxis, false, true);

    camera._setTransform(verticalTransform);
    if (dot < 0.0) {
      const movementDelta = movement.startPosition.y - movement.endPosition.y;
      if (
        (cameraUnderground && movementDelta < 0.0) ||
        (!cameraUnderground && movementDelta > 0.0)
      ) {
        // Prevent camera from flipping past the up axis
        constrainedAxis = undefined;
      }

      const oldConstrainedAxis = camera.constrainedAxis;
      camera.constrainedAxis = undefined;

      rotate3D(controller, startPosition, movement, constrainedAxis, true, false);

      camera.constrainedAxis = oldConstrainedAxis;
    } else {
      rotate3D(controller, startPosition, movement, constrainedAxis, true, false);
    }

    if (defined(camera.constrainedAxis)) {
      const right = Cartesian3.cross(
        camera.direction,
        camera.constrainedAxis,
        tilt3DCartesian3
      );
      if (
        !Cartesian3.equalsEpsilon(right, Cartesian3.ZERO, CesiumMath.EPSILON6)
      ) {
        if (Cartesian3.dot(right, camera.right) < 0.0) {
          Cartesian3.negate(right, right);
        }

        Cartesian3.cross(right, camera.direction, camera.up);
        Cartesian3.cross(camera.direction, camera.up, camera.right);

        Cartesian3.normalize(camera.up, camera.up);
        Cartesian3.normalize(camera.right, camera.right);
      }
    }

    camera._setTransform(oldTransform);
    controller._globe = oldGlobe;
    controller._ellipsoid = oldEllipsoid;

    const radius = oldEllipsoid.maximumRadius;
    controller._rotateFactor = 1.0 / radius;
    controller._rotateRateRangeAdjustment = radius;

    const originalPosition = Cartesian3.clone(
      camera.positionWC,
      rotateCVCartesian3
    );

    if (controller.enableCollisionDetection) {
      adjustHeightForTerrain(controller);
    }

    if (!Cartesian3.equals(camera.positionWC, originalPosition)) {
      camera._setTransform(verticalTransform);
      camera.worldToCameraCoordinatesPoint(originalPosition, originalPosition);

      const magSqrd = Cartesian3.magnitudeSquared(originalPosition);
      if (Cartesian3.magnitudeSquared(camera.position) > magSqrd) {
        Cartesian3.normalize(camera.position, camera.position);
        Cartesian3.multiplyByScalar(
          camera.position,
          Math.sqrt(magSqrd),
          camera.position
        );
      }

      const angle = Cartesian3.angleBetween(originalPosition, camera.position);
      const axis = Cartesian3.cross(
        originalPosition,
        camera.position,
        originalPosition
      );
      Cartesian3.normalize(axis, axis);

      const quaternion = Quaternion.fromAxisAngle(
        axis,
        angle,
        rotateCVQuaternion
      );
      const rotation = Matrix3.fromQuaternion(quaternion, rotateCVMatrix);
      Matrix3.multiplyByVector(rotation, camera.direction, camera.direction);
      Matrix3.multiplyByVector(rotation, camera.up, camera.up);
      Cartesian3.cross(camera.direction, camera.up, camera.right);
      Cartesian3.cross(camera.right, camera.direction, camera.up);

      camera._setTransform(oldTransform);
    }
  }

  const zoomCVWindowPos = new Cartesian2();
  const zoomCVWindowRay = new Ray();
  const zoomCVIntersection = new Cartesian3();

  function zoomCV(controller, startPosition, movement) {
    if (defined(movement.distance)) {
      movement = movement.distance;
    }

    const scene = controller._scene;
    const camera = scene.camera;
    const canvas = scene.canvas;

    const cameraUnderground = controller._cameraUnderground;

    let windowPosition;

    if (cameraUnderground) {
      windowPosition = startPosition;
    } else {
      windowPosition = zoomCVWindowPos;
      windowPosition.x = canvas.clientWidth / 2;
      windowPosition.y = canvas.clientHeight / 2;
    }

    const ray = camera.getPickRay(windowPosition, zoomCVWindowRay);
    const position = ray.origin;
    const direction = ray.direction;
    const height = camera.position.z;

    let intersection;
    if (height < controller._minimumPickingTerrainHeight) {
      intersection = pickGlobe(controller, windowPosition, zoomCVIntersection);
    }

    let distance;
    if (defined(intersection)) {
      distance = Cartesian3.distance(position, intersection);
    }

    if (cameraUnderground) {
      const distanceUnderground = getZoomDistanceUnderground(
        controller,
        ray);
      if (defined(distance)) {
        distance = Math.min(distance, distanceUnderground);
      } else {
        distance = distanceUnderground;
      }
    }

    if (!defined(distance)) {
      const normal = Cartesian3.UNIT_X;
      distance =
        -Cartesian3.dot(normal, position) / Cartesian3.dot(normal, direction);
    }

    handleZoom(
      controller,
      startPosition,
      movement,
      controller._zoomFactor,
      distance
    );
  }

  function updateCV(controller) {
    const scene = controller._scene;
    const camera = scene.camera;

    if (!Matrix4.equals(Matrix4.IDENTITY, camera.transform)) {
      reactToInput(
        controller,
        controller.enableRotate,
        controller.rotateEventTypes,
        rotate3D,
        controller.inertiaSpin,
        "_lastInertiaSpinMovement"
      );
      reactToInput(
        controller,
        controller.enableZoom,
        controller.zoomEventTypes,
        zoom3D,
        controller.inertiaZoom,
        "_lastInertiaZoomMovement"
      );
    } else {
      const tweens = controller._tweens;

      if (controller._aggregator.anyButtonDown) {
        tweens.removeAll();
      }

      reactToInput(
        controller,
        controller.enableTilt,
        controller.tiltEventTypes,
        rotateCV,
        controller.inertiaSpin,
        "_lastInertiaTiltMovement"
      );
      reactToInput(
        controller,
        controller.enableTranslate,
        controller.translateEventTypes,
        translateCV,
        controller.inertiaTranslate,
        "_lastInertiaTranslateMovement"
      );
      reactToInput(
        controller,
        controller.enableZoom,
        controller.zoomEventTypes,
        zoomCV,
        controller.inertiaZoom,
        "_lastInertiaZoomMovement"
      );
      reactToInput(
        controller,
        controller.enableLook,
        controller.lookEventTypes,
        look3D
      );

      if (
        !controller._aggregator.anyButtonDown &&
        !tweens.contains(controller._tween)
      ) {
        const tween = camera.createCorrectPositionTween(
          controller.bounceAnimationTime
        );
        if (defined(tween)) {
          controller._tween = tweens.add(tween);
        }
      }

      tweens.update();
    }
  }

  const scratchStrafeRay = new Ray();
  const scratchStrafePlane = new Plane(Cartesian3.UNIT_X, 0.0);
  const scratchStrafeIntersection = new Cartesian3();
  const scratchStrafeDirection = new Cartesian3();
  const scratchMousePos = new Cartesian3();

  function strafe(controller, movement, strafeStartPosition) {
    const scene = controller._scene;
    const camera = scene.camera;

    const ray = camera.getPickRay(movement.endPosition, scratchStrafeRay);

    let direction = Cartesian3.clone(camera.direction, scratchStrafeDirection);
    if (scene.mode === SceneMode$1.COLUMBUS_VIEW) {
      Cartesian3.fromElements(direction.z, direction.x, direction.y, direction);
    }

    const plane = Plane.fromPointNormal(
      strafeStartPosition,
      direction,
      scratchStrafePlane
    );
    const intersection = IntersectionTests.rayPlane(
      ray,
      plane,
      scratchStrafeIntersection
    );
    if (!defined(intersection)) {
      return;
    }

    direction = Cartesian3.subtract(strafeStartPosition, intersection, direction);
    if (scene.mode === SceneMode$1.COLUMBUS_VIEW) {
      Cartesian3.fromElements(direction.y, direction.z, direction.x, direction);
    }

    Cartesian3.add(camera.position, direction, camera.position);
  }

  const spin3DPick = new Cartesian3();
  const scratchCartographic = new Cartographic();
  const scratchRadii = new Cartesian3();
  const scratchEllipsoid = new Ellipsoid();
  const scratchLookUp = new Cartesian3();
  const scratchNormal = new Cartesian3();

  function spin3D(controller, startPosition, movement) {
    const scene = controller._scene;
    const camera = scene.camera;
    const cameraUnderground = controller._cameraUnderground;
    let ellipsoid = controller._ellipsoid;

    if (!Matrix4.equals(camera.transform, Matrix4.IDENTITY)) {
      rotate3D(controller, startPosition, movement);
      return;
    }

    let magnitude;
    let radii;

    const up = ellipsoid.geodeticSurfaceNormal(camera.position, scratchLookUp);

    if (Cartesian2.equals(startPosition, controller._rotateMousePosition)) {
      if (controller._looking) {
        look3D(controller, startPosition, movement, up);
      } else if (controller._rotating) {
        rotate3D(controller, startPosition, movement);
      } else if (controller._strafing) {
        continueStrafing(controller, movement);
      } else {
        if (
          Cartesian3.magnitude(camera.position) <
          Cartesian3.magnitude(controller._rotateStartPosition)
        ) {
          // Pan action is no longer valid if camera moves below the pan ellipsoid
          return;
        }
        magnitude = Cartesian3.magnitude(controller._rotateStartPosition);
        radii = scratchRadii;
        radii.x = radii.y = radii.z = magnitude;
        ellipsoid = Ellipsoid.fromCartesian3(radii, scratchEllipsoid);
        pan3D(controller, startPosition, movement, ellipsoid);
      }
      return;
    }
    controller._looking = false;
    controller._rotating = false;
    controller._strafing = false;

    const height = ellipsoid.cartesianToCartographic(
      camera.positionWC,
      scratchCartographic
    ).height;
    const globe = controller._globe;

    if (defined(globe) && height < controller._minimumPickingTerrainHeight) {
      const mousePos = pickGlobe(
        controller,
        movement.startPosition,
        scratchMousePos
      );
      if (defined(mousePos)) {
        let strafing = false;
        const ray = camera.getPickRay(
          movement.startPosition,
          pickGlobeScratchRay
        );

        if (cameraUnderground) {
          strafing = true;
          getStrafeStartPositionUnderground(controller, ray, mousePos, mousePos);
        } else {
          const normal = ellipsoid.geodeticSurfaceNormal(mousePos, scratchNormal);
          const tangentPick =
            Math.abs(Cartesian3.dot(ray.direction, normal)) < 0.05;

          if (tangentPick) {
            strafing = true;
          } else {
            strafing =
              Cartesian3.magnitude(camera.position) <
              Cartesian3.magnitude(mousePos);
          }
        }

        if (strafing) {
          Cartesian2.clone(startPosition, controller._strafeEndMousePosition);
          Cartesian3.clone(mousePos, controller._strafeStartPosition);
          controller._strafing = true;
          strafe(controller, movement, controller._strafeStartPosition);
        } else {
          magnitude = Cartesian3.magnitude(mousePos);
          radii = scratchRadii;
          radii.x = radii.y = radii.z = magnitude;
          ellipsoid = Ellipsoid.fromCartesian3(radii, scratchEllipsoid);
          pan3D(controller, startPosition, movement, ellipsoid);

          Cartesian3.clone(mousePos, controller._rotateStartPosition);
        }
      } else {
        controller._looking = true;
        look3D(controller, startPosition, movement, up);
      }
    } else if (
      defined(
        camera.pickEllipsoid(
          movement.startPosition,
          controller._ellipsoid,
          spin3DPick
        )
      )
    ) {
      pan3D(controller, startPosition, movement, controller._ellipsoid);
      Cartesian3.clone(spin3DPick, controller._rotateStartPosition);
    } else if (height > controller._minimumTrackBallHeight) {
      controller._rotating = true;
      rotate3D(controller, startPosition, movement);
    } else {
      controller._looking = true;
      look3D(controller, startPosition, movement, up);
    }

    Cartesian2.clone(startPosition, controller._rotateMousePosition);
  }

  function rotate3D(
    controller,
    startPosition,
    movement,
    constrainedAxis,
    rotateOnlyVertical,
    rotateOnlyHorizontal
  ) {
    rotateOnlyVertical = defaultValue(rotateOnlyVertical, false);
    rotateOnlyHorizontal = defaultValue(rotateOnlyHorizontal, false);

    const scene = controller._scene;
    const camera = scene.camera;
    const canvas = scene.canvas;

    const oldAxis = camera.constrainedAxis;
    if (defined(constrainedAxis)) {
      camera.constrainedAxis = constrainedAxis;
    }

    const rho = Cartesian3.magnitude(camera.position);
    let rotateRate =
      controller._rotateFactor * (rho - controller._rotateRateRangeAdjustment);

    if (rotateRate > controller._maximumRotateRate) {
      rotateRate = controller._maximumRotateRate;
    }

    if (rotateRate < controller._minimumRotateRate) {
      rotateRate = controller._minimumRotateRate;
    }

    let phiWindowRatio =
      (movement.startPosition.x - movement.endPosition.x) / canvas.clientWidth;
    let thetaWindowRatio =
      (movement.startPosition.y - movement.endPosition.y) / canvas.clientHeight;
    phiWindowRatio = Math.min(phiWindowRatio, controller.maximumMovementRatio);
    thetaWindowRatio = Math.min(
      thetaWindowRatio,
      controller.maximumMovementRatio
    );

    const deltaPhi = rotateRate * phiWindowRatio * Math.PI * 2.0;
    const deltaTheta = rotateRate * thetaWindowRatio * Math.PI;

    if (!rotateOnlyVertical) {
      camera.rotateRight(deltaPhi);
    }

    if (!rotateOnlyHorizontal) {
      camera.rotateUp(deltaTheta);
    }

    camera.constrainedAxis = oldAxis;
  }

  const pan3DP0 = Cartesian4.clone(Cartesian4.UNIT_W);
  const pan3DP1 = Cartesian4.clone(Cartesian4.UNIT_W);
  const pan3DTemp0 = new Cartesian3();
  const pan3DTemp1 = new Cartesian3();
  const pan3DTemp2 = new Cartesian3();
  const pan3DTemp3 = new Cartesian3();
  const pan3DStartMousePosition = new Cartesian2();
  const pan3DEndMousePosition = new Cartesian2();

  function pan3D(controller, startPosition, movement, ellipsoid) {
    const scene = controller._scene;
    const camera = scene.camera;

    const startMousePosition = Cartesian2.clone(
      movement.startPosition,
      pan3DStartMousePosition
    );
    const endMousePosition = Cartesian2.clone(
      movement.endPosition,
      pan3DEndMousePosition
    );

    let p0 = camera.pickEllipsoid(startMousePosition, ellipsoid, pan3DP0);
    let p1 = camera.pickEllipsoid(endMousePosition, ellipsoid, pan3DP1);

    if (!defined(p0) || !defined(p1)) {
      controller._rotating = true;
      rotate3D(controller, startPosition, movement);
      return;
    }

    p0 = camera.worldToCameraCoordinates(p0, p0);
    p1 = camera.worldToCameraCoordinates(p1, p1);

    if (!defined(camera.constrainedAxis)) {
      Cartesian3.normalize(p0, p0);
      Cartesian3.normalize(p1, p1);
      const dot = Cartesian3.dot(p0, p1);
      const axis = Cartesian3.cross(p0, p1, pan3DTemp0);

      if (
        dot < 1.0 &&
        !Cartesian3.equalsEpsilon(axis, Cartesian3.ZERO, CesiumMath.EPSILON14)
      ) {
        // dot is in [0, 1]
        const angle = Math.acos(dot);
        camera.rotate(axis, angle);
      }
    } else {
      const basis0 = camera.constrainedAxis;
      const basis1 = Cartesian3.mostOrthogonalAxis(basis0, pan3DTemp0);
      Cartesian3.cross(basis1, basis0, basis1);
      Cartesian3.normalize(basis1, basis1);
      const basis2 = Cartesian3.cross(basis0, basis1, pan3DTemp1);

      const startRho = Cartesian3.magnitude(p0);
      const startDot = Cartesian3.dot(basis0, p0);
      const startTheta = Math.acos(startDot / startRho);
      const startRej = Cartesian3.multiplyByScalar(basis0, startDot, pan3DTemp2);
      Cartesian3.subtract(p0, startRej, startRej);
      Cartesian3.normalize(startRej, startRej);

      const endRho = Cartesian3.magnitude(p1);
      const endDot = Cartesian3.dot(basis0, p1);
      const endTheta = Math.acos(endDot / endRho);
      const endRej = Cartesian3.multiplyByScalar(basis0, endDot, pan3DTemp3);
      Cartesian3.subtract(p1, endRej, endRej);
      Cartesian3.normalize(endRej, endRej);

      let startPhi = Math.acos(Cartesian3.dot(startRej, basis1));
      if (Cartesian3.dot(startRej, basis2) < 0) {
        startPhi = CesiumMath.TWO_PI - startPhi;
      }

      let endPhi = Math.acos(Cartesian3.dot(endRej, basis1));
      if (Cartesian3.dot(endRej, basis2) < 0) {
        endPhi = CesiumMath.TWO_PI - endPhi;
      }

      const deltaPhi = startPhi - endPhi;

      let east;
      if (
        Cartesian3.equalsEpsilon(basis0, camera.position, CesiumMath.EPSILON2)
      ) {
        east = camera.right;
      } else {
        east = Cartesian3.cross(basis0, camera.position, pan3DTemp0);
      }

      const planeNormal = Cartesian3.cross(basis0, east, pan3DTemp0);
      const side0 = Cartesian3.dot(
        planeNormal,
        Cartesian3.subtract(p0, basis0, pan3DTemp1)
      );
      const side1 = Cartesian3.dot(
        planeNormal,
        Cartesian3.subtract(p1, basis0, pan3DTemp1)
      );

      let deltaTheta;
      if (side0 > 0 && side1 > 0) {
        deltaTheta = endTheta - startTheta;
      } else if (side0 > 0 && side1 <= 0) {
        if (Cartesian3.dot(camera.position, basis0) > 0) {
          deltaTheta = -startTheta - endTheta;
        } else {
          deltaTheta = startTheta + endTheta;
        }
      } else {
        deltaTheta = startTheta - endTheta;
      }

      camera.rotateRight(deltaPhi);
      camera.rotateUp(deltaTheta);
    }
  }

  const zoom3DUnitPosition = new Cartesian3();
  const zoom3DCartographic = new Cartographic();

  function zoom3D(controller, startPosition, movement) {
    if (defined(movement.distance)) {
      movement = movement.distance;
    }

    const ellipsoid = controller._ellipsoid;
    const scene = controller._scene;
    const camera = scene.camera;
    const canvas = scene.canvas;

    const cameraUnderground = controller._cameraUnderground;

    let windowPosition;

    if (cameraUnderground) {
      windowPosition = startPosition;
    } else {
      windowPosition = zoomCVWindowPos;
      windowPosition.x = canvas.clientWidth / 2;
      windowPosition.y = canvas.clientHeight / 2;
    }

    const ray = camera.getPickRay(windowPosition, zoomCVWindowRay);

    let intersection;
    const height = ellipsoid.cartesianToCartographic(
      camera.position,
      zoom3DCartographic
    ).height;
    if (height < controller._minimumPickingTerrainHeight) {
      intersection = pickGlobe(controller, windowPosition, zoomCVIntersection);
    }

    let distance;
    if (defined(intersection)) {
      distance = Cartesian3.distance(ray.origin, intersection);
    }

    if (cameraUnderground) {
      const distanceUnderground = getZoomDistanceUnderground(
        controller,
        ray);
      if (defined(distance)) {
        distance = Math.min(distance, distanceUnderground);
      } else {
        distance = distanceUnderground;
      }
    }

    if (!defined(distance)) {
      distance = height;
    }

    const unitPosition = Cartesian3.normalize(
      camera.position,
      zoom3DUnitPosition
    );
    handleZoom(
      controller,
      startPosition,
      movement,
      controller._zoomFactor,
      distance,
      Cartesian3.dot(unitPosition, camera.direction)
    );
  }

  const tilt3DWindowPos = new Cartesian2();
  const tilt3DRay = new Ray();
  const tilt3DCenter = new Cartesian3();
  const tilt3DVerticalCenter = new Cartesian3();
  const tilt3DTransform = new Matrix4();
  const tilt3DVerticalTransform = new Matrix4();
  const tilt3DOldTransform = new Matrix4();
  const tilt3DQuaternion = new Quaternion();
  const tilt3DMatrix = new Matrix3();
  const tilt3DCart = new Cartographic();
  const tilt3DLookUp = new Cartesian3();

  function tilt3D(controller, startPosition, movement) {
    const scene = controller._scene;
    const camera = scene.camera;

    if (!Matrix4.equals(camera.transform, Matrix4.IDENTITY)) {
      return;
    }

    if (defined(movement.angleAndHeight)) {
      movement = movement.angleAndHeight;
    }

    if (!Cartesian2.equals(startPosition, controller._tiltCenterMousePosition)) {
      controller._tiltOnEllipsoid = false;
      controller._looking = false;
    }

    if (controller._looking) {
      const up = controller._ellipsoid.geodeticSurfaceNormal(
        camera.position,
        tilt3DLookUp
      );
      look3D(controller, startPosition, movement, up);
      return;
    }

    const ellipsoid = controller._ellipsoid;
    const cartographic = ellipsoid.cartesianToCartographic(
      camera.position,
      tilt3DCart
    );

    if (
      controller._tiltOnEllipsoid ||
      cartographic.height > controller._minimumCollisionTerrainHeight
    ) {
      controller._tiltOnEllipsoid = true;
      tilt3DOnEllipsoid(controller, startPosition, movement);
    } else {
      tilt3DOnTerrain(controller, startPosition, movement);
    }
  }

  const tilt3DOnEllipsoidCartographic = new Cartographic();

  function tilt3DOnEllipsoid(controller, startPosition, movement) {
    const ellipsoid = controller._ellipsoid;
    const scene = controller._scene;
    const camera = scene.camera;
    const minHeight = controller.minimumZoomDistance * 0.25;
    const height = ellipsoid.cartesianToCartographic(
      camera.positionWC,
      tilt3DOnEllipsoidCartographic
    ).height;
    if (
      height - minHeight - 1.0 < CesiumMath.EPSILON3 &&
      movement.endPosition.y - movement.startPosition.y < 0
    ) {
      return;
    }

    const canvas = scene.canvas;

    const windowPosition = tilt3DWindowPos;
    windowPosition.x = canvas.clientWidth / 2;
    windowPosition.y = canvas.clientHeight / 2;
    const ray = camera.getPickRay(windowPosition, tilt3DRay);

    let center;
    const intersection = IntersectionTests.rayEllipsoid(ray, ellipsoid);
    if (defined(intersection)) {
      center = Ray.getPoint(ray, intersection.start, tilt3DCenter);
    } else if (height > controller._minimumTrackBallHeight) {
      const grazingAltitudeLocation = IntersectionTests.grazingAltitudeLocation(
        ray,
        ellipsoid
      );
      if (!defined(grazingAltitudeLocation)) {
        return;
      }
      const grazingAltitudeCart = ellipsoid.cartesianToCartographic(
        grazingAltitudeLocation,
        tilt3DCart
      );
      grazingAltitudeCart.height = 0.0;
      center = ellipsoid.cartographicToCartesian(
        grazingAltitudeCart,
        tilt3DCenter
      );
    } else {
      controller._looking = true;
      const up = controller._ellipsoid.geodeticSurfaceNormal(
        camera.position,
        tilt3DLookUp
      );
      look3D(controller, startPosition, movement, up);
      Cartesian2.clone(startPosition, controller._tiltCenterMousePosition);
      return;
    }

    const transform = Transforms.eastNorthUpToFixedFrame(
      center,
      ellipsoid,
      tilt3DTransform
    );

    const oldGlobe = controller._globe;
    const oldEllipsoid = controller._ellipsoid;
    controller._globe = undefined;
    controller._ellipsoid = Ellipsoid.UNIT_SPHERE;
    controller._rotateFactor = 1.0;
    controller._rotateRateRangeAdjustment = 1.0;

    const oldTransform = Matrix4.clone(camera.transform, tilt3DOldTransform);
    camera._setTransform(transform);

    rotate3D(controller, startPosition, movement, Cartesian3.UNIT_Z);

    camera._setTransform(oldTransform);
    controller._globe = oldGlobe;
    controller._ellipsoid = oldEllipsoid;

    const radius = oldEllipsoid.maximumRadius;
    controller._rotateFactor = 1.0 / radius;
    controller._rotateRateRangeAdjustment = radius;
  }

  function tilt3DOnTerrain(controller, startPosition, movement) {
    const ellipsoid = controller._ellipsoid;
    const scene = controller._scene;
    const camera = scene.camera;
    const cameraUnderground = controller._cameraUnderground;

    let center;
    let ray;
    let intersection;

    if (Cartesian2.equals(startPosition, controller._tiltCenterMousePosition)) {
      center = Cartesian3.clone(controller._tiltCenter, tilt3DCenter);
    } else {
      center = pickGlobe(controller, startPosition, tilt3DCenter);

      if (!defined(center)) {
        ray = camera.getPickRay(startPosition, tilt3DRay);
        intersection = IntersectionTests.rayEllipsoid(ray, ellipsoid);
        if (!defined(intersection)) {
          const cartographic = ellipsoid.cartesianToCartographic(
            camera.position,
            tilt3DCart
          );
          if (cartographic.height <= controller._minimumTrackBallHeight) {
            controller._looking = true;
            const up = controller._ellipsoid.geodeticSurfaceNormal(
              camera.position,
              tilt3DLookUp
            );
            look3D(controller, startPosition, movement, up);
            Cartesian2.clone(startPosition, controller._tiltCenterMousePosition);
          }
          return;
        }
        center = Ray.getPoint(ray, intersection.start, tilt3DCenter);
      }

      if (cameraUnderground) {
        if (!defined(ray)) {
          ray = camera.getPickRay(startPosition, tilt3DRay);
        }
        getTiltCenterUnderground(controller, ray, center, center);
      }

      Cartesian2.clone(startPosition, controller._tiltCenterMousePosition);
      Cartesian3.clone(center, controller._tiltCenter);
    }

    const canvas = scene.canvas;

    const windowPosition = tilt3DWindowPos;
    windowPosition.x = canvas.clientWidth / 2;
    windowPosition.y = controller._tiltCenterMousePosition.y;
    ray = camera.getPickRay(windowPosition, tilt3DRay);

    const mag = Cartesian3.magnitude(center);
    const radii = Cartesian3.fromElements(mag, mag, mag, scratchRadii);
    const newEllipsoid = Ellipsoid.fromCartesian3(radii, scratchEllipsoid);

    intersection = IntersectionTests.rayEllipsoid(ray, newEllipsoid);
    if (!defined(intersection)) {
      return;
    }

    const t =
      Cartesian3.magnitude(ray.origin) > mag
        ? intersection.start
        : intersection.stop;
    const verticalCenter = Ray.getPoint(ray, t, tilt3DVerticalCenter);

    const transform = Transforms.eastNorthUpToFixedFrame(
      center,
      ellipsoid,
      tilt3DTransform
    );
    const verticalTransform = Transforms.eastNorthUpToFixedFrame(
      verticalCenter,
      newEllipsoid,
      tilt3DVerticalTransform
    );

    const oldGlobe = controller._globe;
    const oldEllipsoid = controller._ellipsoid;
    controller._globe = undefined;
    controller._ellipsoid = Ellipsoid.UNIT_SPHERE;
    controller._rotateFactor = 1.0;
    controller._rotateRateRangeAdjustment = 1.0;

    let constrainedAxis = Cartesian3.UNIT_Z;

    const oldTransform = Matrix4.clone(camera.transform, tilt3DOldTransform);
    camera._setTransform(verticalTransform);

    const tangent = Cartesian3.cross(
      verticalCenter,
      camera.positionWC,
      tilt3DCartesian3
    );
    const dot = Cartesian3.dot(camera.rightWC, tangent);

    if (dot < 0.0) {
      const movementDelta = movement.startPosition.y - movement.endPosition.y;
      if (
        (cameraUnderground && movementDelta < 0.0) ||
        (!cameraUnderground && movementDelta > 0.0)
      ) {
        // Prevent camera from flipping past the up axis
        constrainedAxis = undefined;
      }

      const oldConstrainedAxis = camera.constrainedAxis;
      camera.constrainedAxis = undefined;

      rotate3D(controller, startPosition, movement, constrainedAxis, true, false);

      camera.constrainedAxis = oldConstrainedAxis;
    } else {
      rotate3D(controller, startPosition, movement, constrainedAxis, true, false);
    }

    camera._setTransform(transform);
    rotate3D(controller, startPosition, movement, constrainedAxis, false, true);

    if (defined(camera.constrainedAxis)) {
      const right = Cartesian3.cross(
        camera.direction,
        camera.constrainedAxis,
        tilt3DCartesian3
      );
      if (
        !Cartesian3.equalsEpsilon(right, Cartesian3.ZERO, CesiumMath.EPSILON6)
      ) {
        if (Cartesian3.dot(right, camera.right) < 0.0) {
          Cartesian3.negate(right, right);
        }

        Cartesian3.cross(right, camera.direction, camera.up);
        Cartesian3.cross(camera.direction, camera.up, camera.right);

        Cartesian3.normalize(camera.up, camera.up);
        Cartesian3.normalize(camera.right, camera.right);
      }
    }

    camera._setTransform(oldTransform);
    controller._globe = oldGlobe;
    controller._ellipsoid = oldEllipsoid;

    const radius = oldEllipsoid.maximumRadius;
    controller._rotateFactor = 1.0 / radius;
    controller._rotateRateRangeAdjustment = radius;

    const originalPosition = Cartesian3.clone(
      camera.positionWC,
      tilt3DCartesian3
    );

    if (controller.enableCollisionDetection) {
      adjustHeightForTerrain(controller);
    }

    if (!Cartesian3.equals(camera.positionWC, originalPosition)) {
      camera._setTransform(verticalTransform);
      camera.worldToCameraCoordinatesPoint(originalPosition, originalPosition);

      const magSqrd = Cartesian3.magnitudeSquared(originalPosition);
      if (Cartesian3.magnitudeSquared(camera.position) > magSqrd) {
        Cartesian3.normalize(camera.position, camera.position);
        Cartesian3.multiplyByScalar(
          camera.position,
          Math.sqrt(magSqrd),
          camera.position
        );
      }

      const angle = Cartesian3.angleBetween(originalPosition, camera.position);
      const axis = Cartesian3.cross(
        originalPosition,
        camera.position,
        originalPosition
      );
      Cartesian3.normalize(axis, axis);

      const quaternion = Quaternion.fromAxisAngle(axis, angle, tilt3DQuaternion);
      const rotation = Matrix3.fromQuaternion(quaternion, tilt3DMatrix);
      Matrix3.multiplyByVector(rotation, camera.direction, camera.direction);
      Matrix3.multiplyByVector(rotation, camera.up, camera.up);
      Cartesian3.cross(camera.direction, camera.up, camera.right);
      Cartesian3.cross(camera.right, camera.direction, camera.up);

      camera._setTransform(oldTransform);
    }
  }

  const look3DStartPos = new Cartesian2();
  const look3DEndPos = new Cartesian2();
  const look3DStartRay = new Ray();
  const look3DEndRay = new Ray();
  const look3DNegativeRot = new Cartesian3();
  const look3DTan = new Cartesian3();

  function look3D(controller, startPosition, movement, rotationAxis) {
    const scene = controller._scene;
    const camera = scene.camera;

    const startPos = look3DStartPos;
    startPos.x = movement.startPosition.x;
    startPos.y = 0.0;
    const endPos = look3DEndPos;
    endPos.x = movement.endPosition.x;
    endPos.y = 0.0;

    let startRay = camera.getPickRay(startPos, look3DStartRay);
    let endRay = camera.getPickRay(endPos, look3DEndRay);
    let angle = 0.0;
    let start;
    let end;

    if (camera.frustum instanceof OrthographicFrustum) {
      start = startRay.origin;
      end = endRay.origin;

      Cartesian3.add(camera.direction, start, start);
      Cartesian3.add(camera.direction, end, end);

      Cartesian3.subtract(start, camera.position, start);
      Cartesian3.subtract(end, camera.position, end);

      Cartesian3.normalize(start, start);
      Cartesian3.normalize(end, end);
    } else {
      start = startRay.direction;
      end = endRay.direction;
    }

    let dot = Cartesian3.dot(start, end);
    if (dot < 1.0) {
      // dot is in [0, 1]
      angle = Math.acos(dot);
    }

    angle = movement.startPosition.x > movement.endPosition.x ? -angle : angle;

    const horizontalRotationAxis = controller._horizontalRotationAxis;
    if (defined(rotationAxis)) {
      camera.look(rotationAxis, -angle);
    } else if (defined(horizontalRotationAxis)) {
      camera.look(horizontalRotationAxis, -angle);
    } else {
      camera.lookLeft(angle);
    }

    startPos.x = 0.0;
    startPos.y = movement.startPosition.y;
    endPos.x = 0.0;
    endPos.y = movement.endPosition.y;

    startRay = camera.getPickRay(startPos, look3DStartRay);
    endRay = camera.getPickRay(endPos, look3DEndRay);
    angle = 0.0;

    if (camera.frustum instanceof OrthographicFrustum) {
      start = startRay.origin;
      end = endRay.origin;

      Cartesian3.add(camera.direction, start, start);
      Cartesian3.add(camera.direction, end, end);

      Cartesian3.subtract(start, camera.position, start);
      Cartesian3.subtract(end, camera.position, end);

      Cartesian3.normalize(start, start);
      Cartesian3.normalize(end, end);
    } else {
      start = startRay.direction;
      end = endRay.direction;
    }

    dot = Cartesian3.dot(start, end);
    if (dot < 1.0) {
      // dot is in [0, 1]
      angle = Math.acos(dot);
    }
    angle = movement.startPosition.y > movement.endPosition.y ? -angle : angle;

    rotationAxis = defaultValue(rotationAxis, horizontalRotationAxis);
    if (defined(rotationAxis)) {
      const direction = camera.direction;
      const negativeRotationAxis = Cartesian3.negate(
        rotationAxis,
        look3DNegativeRot
      );
      const northParallel = Cartesian3.equalsEpsilon(
        direction,
        rotationAxis,
        CesiumMath.EPSILON2
      );
      const southParallel = Cartesian3.equalsEpsilon(
        direction,
        negativeRotationAxis,
        CesiumMath.EPSILON2
      );
      if (!northParallel && !southParallel) {
        dot = Cartesian3.dot(direction, rotationAxis);
        let angleToAxis = CesiumMath.acosClamped(dot);
        if (angle > 0 && angle > angleToAxis) {
          angle = angleToAxis - CesiumMath.EPSILON4;
        }

        dot = Cartesian3.dot(direction, negativeRotationAxis);
        angleToAxis = CesiumMath.acosClamped(dot);
        if (angle < 0 && -angle > angleToAxis) {
          angle = -angleToAxis + CesiumMath.EPSILON4;
        }

        const tangent = Cartesian3.cross(rotationAxis, direction, look3DTan);
        camera.look(tangent, angle);
      } else if ((northParallel && angle < 0) || (southParallel && angle > 0)) {
        camera.look(camera.right, -angle);
      }
    } else {
      camera.lookUp(angle);
    }
  }

  function update3D(controller) {
    reactToInput(
      controller,
      controller.enableRotate,
      controller.rotateEventTypes,
      spin3D,
      controller.inertiaSpin,
      "_lastInertiaSpinMovement"
    );
    reactToInput(
      controller,
      controller.enableZoom,
      controller.zoomEventTypes,
      zoom3D,
      controller.inertiaZoom,
      "_lastInertiaZoomMovement"
    );
    reactToInput(
      controller,
      controller.enableTilt,
      controller.tiltEventTypes,
      tilt3D,
      controller.inertiaSpin,
      "_lastInertiaTiltMovement"
    );
    reactToInput(
      controller,
      controller.enableLook,
      controller.lookEventTypes,
      look3D
    );
  }

  const scratchAdjustHeightTransform = new Matrix4();
  const scratchAdjustHeightCartographic = new Cartographic();

  function adjustHeightForTerrain(controller) {
    controller._adjustedHeightForTerrain = true;

    const scene = controller._scene;
    const mode = scene.mode;
    const globe = scene.globe;

    if (
      !defined(globe) ||
      mode === SceneMode$1.SCENE2D ||
      mode === SceneMode$1.MORPHING
    ) {
      return;
    }

    const camera = scene.camera;
    const ellipsoid = globe.ellipsoid;
    const projection = scene.mapProjection;

    let transform;
    let mag;
    if (!Matrix4.equals(camera.transform, Matrix4.IDENTITY)) {
      transform = Matrix4.clone(camera.transform, scratchAdjustHeightTransform);
      mag = Cartesian3.magnitude(camera.position);
      camera._setTransform(Matrix4.IDENTITY);
    }

    const cartographic = scratchAdjustHeightCartographic;
    if (mode === SceneMode$1.SCENE3D) {
      ellipsoid.cartesianToCartographic(camera.position, cartographic);
    } else {
      projection.unproject(camera.position, cartographic);
    }

    let heightUpdated = false;
    if (cartographic.height < controller._minimumCollisionTerrainHeight) {
      const globeHeight = controller._scene.globeHeight;
      if (defined(globeHeight)) {
        const height = globeHeight + controller.minimumZoomDistance;
        if (cartographic.height < height) {
          cartographic.height = height;
          if (mode === SceneMode$1.SCENE3D) {
            ellipsoid.cartographicToCartesian(cartographic, camera.position);
          } else {
            projection.project(cartographic, camera.position);
          }
          heightUpdated = true;
        }
      }
    }

    if (defined(transform)) {
      camera._setTransform(transform);
      if (heightUpdated) {
        Cartesian3.normalize(camera.position, camera.position);
        Cartesian3.negate(camera.position, camera.direction);
        Cartesian3.multiplyByScalar(
          camera.position,
          Math.max(mag, controller.minimumZoomDistance),
          camera.position
        );
        Cartesian3.normalize(camera.direction, camera.direction);
        Cartesian3.cross(camera.direction, camera.up, camera.right);
        Cartesian3.cross(camera.right, camera.direction, camera.up);
      }
    }
  }

  /**
   * @private
   */
  ScreenSpaceCameraController.prototype.onMap = function () {
    const scene = this._scene;
    const mode = scene.mode;
    const camera = scene.camera;

    if (mode === SceneMode$1.COLUMBUS_VIEW) {
      return (
        Math.abs(camera.position.x) - this._maxCoord.x < 0 &&
        Math.abs(camera.position.y) - this._maxCoord.y < 0
      );
    }

    return true;
  };

  const scratchPreviousPosition = new Cartesian3();
  const scratchPreviousDirection = new Cartesian3();

  /**
   * @private
   */
  ScreenSpaceCameraController.prototype.update = function () {
    const scene = this._scene;
    const camera = scene.camera;
    const globe = scene.globe;
    const mode = scene.mode;

    if (!Matrix4.equals(camera.transform, Matrix4.IDENTITY)) {
      this._globe = undefined;
      this._ellipsoid = Ellipsoid.UNIT_SPHERE;
    } else {
      this._globe = globe;
      this._ellipsoid = defined(this._globe)
        ? this._globe.ellipsoid
        : scene.mapProjection.ellipsoid;
    }

    const exaggeration = defined(this._globe)
      ? this._globe.terrainExaggeration
      : 1.0;
    const exaggerationRelativeHeight = defined(this._globe)
      ? this._globe.terrainExaggerationRelativeHeight
      : 0.0;
    this._minimumCollisionTerrainHeight = TerrainExaggeration.getHeight(
      this.minimumCollisionTerrainHeight,
      exaggeration,
      exaggerationRelativeHeight
    );
    this._minimumPickingTerrainHeight = TerrainExaggeration.getHeight(
      this.minimumPickingTerrainHeight,
      exaggeration,
      exaggerationRelativeHeight
    );
    this._minimumTrackBallHeight = TerrainExaggeration.getHeight(
      this.minimumTrackBallHeight,
      exaggeration,
      exaggerationRelativeHeight
    );

    this._cameraUnderground = scene.cameraUnderground && defined(this._globe);

    const radius = this._ellipsoid.maximumRadius;
    this._rotateFactor = 1.0 / radius;
    this._rotateRateRangeAdjustment = radius;

    this._adjustedHeightForTerrain = false;
    const previousPosition = Cartesian3.clone(
      camera.positionWC,
      scratchPreviousPosition
    );
    const previousDirection = Cartesian3.clone(
      camera.directionWC,
      scratchPreviousDirection
    );

    if (mode === SceneMode$1.SCENE2D) {
      update2D(this);
    } else if (mode === SceneMode$1.COLUMBUS_VIEW) {
      this._horizontalRotationAxis = Cartesian3.UNIT_Z;
      updateCV(this);
    } else if (mode === SceneMode$1.SCENE3D) {
      this._horizontalRotationAxis = undefined;
      update3D(this);
    }

    if (this.enableCollisionDetection && !this._adjustedHeightForTerrain) {
      // Adjust the camera height if the camera moved at all (user input or inertia) and an action didn't already adjust the camera height
      const cameraChanged =
        !Cartesian3.equals(previousPosition, camera.positionWC) ||
        !Cartesian3.equals(previousDirection, camera.directionWC);
      if (cameraChanged) {
        adjustHeightForTerrain(this);
      }
    }

    this._aggregator.reset();
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see ScreenSpaceCameraController#destroy
   */
  ScreenSpaceCameraController.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Removes mouse listeners held by this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * controller = controller && controller.destroy();
   *
   * @see ScreenSpaceCameraController#isDestroyed
   */
  ScreenSpaceCameraController.prototype.destroy = function () {
    this._tweens.removeAll();
    this._aggregator = this._aggregator && this._aggregator.destroy();
    return destroyObject(this);
  };

  //This file is automatically rebuilt by the Cesium build process.
  var AdditiveBlend = "uniform sampler2D colorTexture;\n\
uniform sampler2D colorTexture2;\n\
uniform vec2 center;\n\
uniform float radius;\n\
varying vec2 v_textureCoordinates;\n\
void main()\n\
{\n\
vec4 color0 = texture2D(colorTexture, v_textureCoordinates);\n\
vec4 color1 = texture2D(colorTexture2, v_textureCoordinates);\n\
float x = length(gl_FragCoord.xy - center) / radius;\n\
float t = smoothstep(0.5, 0.8, x);\n\
gl_FragColor = mix(color0 + color1, color1, t);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var BrightPass = "uniform sampler2D colorTexture;\n\
uniform float avgLuminance;\n\
uniform float threshold;\n\
uniform float offset;\n\
varying vec2 v_textureCoordinates;\n\
float key(float avg)\n\
{\n\
float guess = 1.5 - (1.5 / (avg * 0.1 + 1.0));\n\
return max(0.0, guess) + 0.1;\n\
}\n\
void main()\n\
{\n\
vec4 color = texture2D(colorTexture, v_textureCoordinates);\n\
vec3 xyz = czm_RGBToXYZ(color.rgb);\n\
float luminance = xyz.r;\n\
float scaledLum = key(avgLuminance) * luminance / avgLuminance;\n\
float brightLum = max(scaledLum - threshold, 0.0);\n\
float brightness = brightLum / (offset + brightLum);\n\
xyz.r = brightness;\n\
gl_FragColor = vec4(czm_XYZToRGB(xyz), 1.0);\n\
}\n\
";

  function SunPostProcess() {
    this._sceneFramebuffer = new SceneFramebuffer();

    const scale = 0.125;
    const stages = new Array(6);

    stages[0] = new PostProcessStage({
      fragmentShader: PassThrough,
      textureScale: scale,
      forcePowerOfTwo: true,
      sampleMode: PostProcessStageSampleMode.LINEAR,
    });

    const brightPass = (stages[1] = new PostProcessStage({
      fragmentShader: BrightPass,
      uniforms: {
        avgLuminance: 0.5, // A guess at the average luminance across the entire scene
        threshold: 0.25,
        offset: 0.1,
      },
      textureScale: scale,
      forcePowerOfTwo: true,
    }));

    const that = this;
    this._delta = 1.0;
    this._sigma = 2.0;
    this._blurStep = new Cartesian2();

    stages[2] = new PostProcessStage({
      fragmentShader: GaussianBlur1D,
      uniforms: {
        step: function () {
          that._blurStep.x = that._blurStep.y =
            1.0 / brightPass.outputTexture.width;
          return that._blurStep;
        },
        delta: function () {
          return that._delta;
        },
        sigma: function () {
          return that._sigma;
        },
        direction: 0.0,
      },
      textureScale: scale,
      forcePowerOfTwo: true,
    });

    stages[3] = new PostProcessStage({
      fragmentShader: GaussianBlur1D,
      uniforms: {
        step: function () {
          that._blurStep.x = that._blurStep.y =
            1.0 / brightPass.outputTexture.width;
          return that._blurStep;
        },
        delta: function () {
          return that._delta;
        },
        sigma: function () {
          return that._sigma;
        },
        direction: 1.0,
      },
      textureScale: scale,
      forcePowerOfTwo: true,
    });

    stages[4] = new PostProcessStage({
      fragmentShader: PassThrough,
      sampleMode: PostProcessStageSampleMode.LINEAR,
    });

    this._uCenter = new Cartesian2();
    this._uRadius = undefined;

    stages[5] = new PostProcessStage({
      fragmentShader: AdditiveBlend,
      uniforms: {
        center: function () {
          return that._uCenter;
        },
        radius: function () {
          return that._uRadius;
        },
        colorTexture2: function () {
          return that._sceneFramebuffer.framebuffer.getColorTexture(0);
        },
      },
    });

    this._stages = new PostProcessStageComposite({
      stages: stages,
    });

    const textureCache = new PostProcessStageTextureCache(this);
    const length = stages.length;
    for (let i = 0; i < length; ++i) {
      stages[i]._textureCache = textureCache;
    }

    this._textureCache = textureCache;
    this.length = stages.length;
  }

  SunPostProcess.prototype.get = function (index) {
    return this._stages.get(index);
  };

  SunPostProcess.prototype.getStageByName = function (name) {
    const length = this._stages.length;
    for (let i = 0; i < length; ++i) {
      const stage = this._stages.get(i);
      if (stage.name === name) {
        return stage;
      }
    }
    return undefined;
  };

  const sunPositionECScratch = new Cartesian4();
  const sunPositionWCScratch = new Cartesian2();
  const sizeScratch = new Cartesian2();
  const postProcessMatrix4Scratch = new Matrix4();

  function updateSunPosition(postProcess, context, viewport) {
    const us = context.uniformState;
    const sunPosition = us.sunPositionWC;
    const viewMatrix = us.view;
    const viewProjectionMatrix = us.viewProjection;
    const projectionMatrix = us.projection;

    // create up sampled render state
    let viewportTransformation = Matrix4.computeViewportTransformation(
      viewport,
      0.0,
      1.0,
      postProcessMatrix4Scratch
    );
    const sunPositionEC = Matrix4.multiplyByPoint(
      viewMatrix,
      sunPosition,
      sunPositionECScratch
    );
    let sunPositionWC = Transforms.pointToGLWindowCoordinates(
      viewProjectionMatrix,
      viewportTransformation,
      sunPosition,
      sunPositionWCScratch
    );

    sunPositionEC.x += CesiumMath.SOLAR_RADIUS;
    const limbWC = Transforms.pointToGLWindowCoordinates(
      projectionMatrix,
      viewportTransformation,
      sunPositionEC,
      sunPositionEC
    );
    const sunSize =
      Cartesian2.magnitude(Cartesian2.subtract(limbWC, sunPositionWC, limbWC)) *
      30.0 *
      2.0;

    const size = sizeScratch;
    size.x = sunSize;
    size.y = sunSize;

    postProcess._uCenter = Cartesian2.clone(sunPositionWC, postProcess._uCenter);
    postProcess._uRadius = Math.max(size.x, size.y) * 0.15;

    const width = context.drawingBufferWidth;
    const height = context.drawingBufferHeight;

    const stages = postProcess._stages;
    const firstStage = stages.get(0);

    const downSampleWidth = firstStage.outputTexture.width;
    const downSampleHeight = firstStage.outputTexture.height;

    const downSampleViewport = new BoundingRectangle();
    downSampleViewport.width = downSampleWidth;
    downSampleViewport.height = downSampleHeight;

    // create down sampled render state
    viewportTransformation = Matrix4.computeViewportTransformation(
      downSampleViewport,
      0.0,
      1.0,
      postProcessMatrix4Scratch
    );
    sunPositionWC = Transforms.pointToGLWindowCoordinates(
      viewProjectionMatrix,
      viewportTransformation,
      sunPosition,
      sunPositionWCScratch
    );

    size.x *= downSampleWidth / width;
    size.y *= downSampleHeight / height;

    const scissorRectangle = firstStage.scissorRectangle;
    scissorRectangle.x = Math.max(sunPositionWC.x - size.x * 0.5, 0.0);
    scissorRectangle.y = Math.max(sunPositionWC.y - size.y * 0.5, 0.0);
    scissorRectangle.width = Math.min(size.x, width);
    scissorRectangle.height = Math.min(size.y, height);

    for (let i = 1; i < 4; ++i) {
      BoundingRectangle.clone(scissorRectangle, stages.get(i).scissorRectangle);
    }
  }

  SunPostProcess.prototype.clear = function (context, passState, clearColor) {
    this._sceneFramebuffer.clear(context, passState, clearColor);
    this._textureCache.clear(context);
  };

  SunPostProcess.prototype.update = function (passState) {
    const context = passState.context;
    const viewport = passState.viewport;

    const sceneFramebuffer = this._sceneFramebuffer;
    sceneFramebuffer.update(context, viewport);
    const framebuffer = sceneFramebuffer.framebuffer;

    this._textureCache.update(context);
    this._stages.update(context, false);

    updateSunPosition(this, context, viewport);

    return framebuffer;
  };

  SunPostProcess.prototype.execute = function (context) {
    const colorTexture = this._sceneFramebuffer.framebuffer.getColorTexture(0);
    const stages = this._stages;
    const length = stages.length;
    stages.get(0).execute(context, colorTexture);
    for (let i = 1; i < length; ++i) {
      stages.get(i).execute(context, stages.get(i - 1).outputTexture);
    }
  };

  SunPostProcess.prototype.copy = function (context, framebuffer) {
    if (!defined(this._copyColorCommand)) {
      const that = this;
      this._copyColorCommand = context.createViewportQuadCommand(PassThrough, {
        uniformMap: {
          colorTexture: function () {
            return that._stages.get(that._stages.length - 1).outputTexture;
          },
        },
        owner: this,
      });
    }

    this._copyColorCommand.framebuffer = framebuffer;
    this._copyColorCommand.execute(context);
  };

  SunPostProcess.prototype.isDestroyed = function () {
    return false;
  };

  SunPostProcess.prototype.destroy = function () {
    this._textureCache.destroy();
    this._stages.destroy();
    return destroyObject(this);
  };

  const requestRenderAfterFrame = function (scene) {
    return function () {
      scene.frameState.afterRender.push(function () {
        scene.requestRender();
      });
    };
  };

  /**
   * The container for all 3D graphical objects and state in a Cesium virtual scene.  Generally,
   * a scene is not created directly; instead, it is implicitly created by {@link CesiumWidget}.
   * <p>
   * <em><code>contextOptions</code> parameter details:</em>
   * </p>
   * <p>
   * The default values are:
   * <code>
   * {
   *   webgl : {
   *     alpha : false,
   *     depth : true,
   *     stencil : false,
   *     antialias : true,
   *     powerPreference: 'high-performance',
   *     premultipliedAlpha : true,
   *     preserveDrawingBuffer : false,
   *     failIfMajorPerformanceCaveat : false
   *   },
   *   allowTextureFilterAnisotropic : true
   * }
   * </code>
   * </p>
   * <p>
   * The <code>webgl</code> property corresponds to the {@link http://www.khronos.org/registry/webgl/specs/latest/#5.2|WebGLContextAttributes}
   * object used to create the WebGL context.
   * </p>
   * <p>
   * <code>webgl.alpha</code> defaults to false, which can improve performance compared to the standard WebGL default
   * of true.  If an application needs to composite Cesium above other HTML elements using alpha-blending, set
   * <code>webgl.alpha</code> to true.
   * </p>
   * <p>
   * The other <code>webgl</code> properties match the WebGL defaults for {@link http://www.khronos.org/registry/webgl/specs/latest/#5.2|WebGLContextAttributes}.
   * </p>
   * <p>
   * <code>allowTextureFilterAnisotropic</code> defaults to true, which enables anisotropic texture filtering when the
   * WebGL extension is supported.  Setting this to false will improve performance, but hurt visual quality, especially for horizon views.
   * </p>
   *
   * @alias Scene
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {HTMLCanvasElement} options.canvas The HTML canvas element to create the scene for.
   * @param {Object} [options.contextOptions] Context and WebGL creation properties.  See details above.
   * @param {Element} [options.creditContainer] The HTML element in which the credits will be displayed.
   * @param {Element} [options.creditViewport] The HTML element in which to display the credit popup.  If not specified, the viewport will be a added as a sibling of the canvas.
   * @param {MapProjection} [options.mapProjection=new GeographicProjection()] The map projection to use in 2D and Columbus View modes.
   * @param {Boolean} [options.orderIndependentTranslucency=true] If true and the configuration supports it, use order independent translucency.
   * @param {Boolean} [options.scene3DOnly=false] If true, optimizes memory use and performance for 3D mode but disables the ability to use 2D or Columbus View.
   * @param {Boolean} [options.shadows=false] Determines if shadows are cast by light sources.
   * @param {MapMode2D} [options.mapMode2D=MapMode2D.INFINITE_SCROLL] Determines if the 2D map is rotatable or can be scrolled infinitely in the horizontal direction.
   * @param {Boolean} [options.requestRenderMode=false] If true, rendering a frame will only occur when needed as determined by changes within the scene. Enabling improves performance of the application, but requires using {@link Scene#requestRender} to render a new frame explicitly in this mode. This will be necessary in many cases after making changes to the scene in other parts of the API. See {@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|Improving Performance with Explicit Rendering}.
   * @param {Number} [options.maximumRenderTimeChange=0.0] If requestRenderMode is true, this value defines the maximum change in simulation time allowed before a render is requested. See {@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|Improving Performance with Explicit Rendering}.
   * @param {Number} [depthPlaneEllipsoidOffset=0.0] Adjust the DepthPlane to address rendering artefacts below ellipsoid zero elevation.
   * @param {Number} [options.msaaSamples=1] If provided, this value controls the rate of multisample antialiasing. Typical multisampling rates are 2, 4, and sometimes 8 samples per pixel. Higher sampling rates of MSAA may impact performance in exchange for improved visual quality. This value only applies to WebGL2 contexts that support multisample render targets.
   *
   * @see CesiumWidget
   * @see {@link http://www.khronos.org/registry/webgl/specs/latest/#5.2|WebGLContextAttributes}
   *
   * @exception {DeveloperError} options and options.canvas are required.
   *
   * @example
   * // Create scene without anisotropic texture filtering
   * const scene = new Cesium.Scene({
   *   canvas : canvas,
   *   contextOptions : {
   *     allowTextureFilterAnisotropic : false
   *   }
   * });
   */
  function Scene(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const canvas = options.canvas;
    let creditContainer = options.creditContainer;
    let creditViewport = options.creditViewport;

    let contextOptions = clone$1(options.contextOptions);
    if (!defined(contextOptions)) {
      contextOptions = {};
    }
    if (!defined(contextOptions.webgl)) {
      contextOptions.webgl = {};
    }
    contextOptions.webgl.powerPreference = defaultValue(
      contextOptions.webgl.powerPreference,
      "high-performance"
    );

    //>>includeStart('debug', pragmas.debug);
    if (!defined(canvas)) {
      throw new DeveloperError("options and options.canvas are required.");
    }
    //>>includeEnd('debug');
    const hasCreditContainer = defined(creditContainer);
    const context = new Context(canvas, contextOptions);
    if (!hasCreditContainer) {
      creditContainer = document.createElement("div");
      creditContainer.style.position = "absolute";
      creditContainer.style.bottom = "0";
      creditContainer.style["text-shadow"] = "0 0 2px #000000";
      creditContainer.style.color = "#ffffff";
      creditContainer.style["font-size"] = "10px";
      creditContainer.style["padding-right"] = "5px";
      canvas.parentNode.appendChild(creditContainer);
    }
    if (!defined(creditViewport)) {
      creditViewport = canvas.parentNode;
    }

    this._id = createGuid();
    this._jobScheduler = new JobScheduler();
    this._frameState = new FrameState(
      context,
      new CreditDisplay(creditContainer, " • ", creditViewport),
      this._jobScheduler
    );
    this._frameState.scene3DOnly = defaultValue(options.scene3DOnly, false);
    this._removeCreditContainer = !hasCreditContainer;
    this._creditContainer = creditContainer;

    this._canvas = canvas;
    this._context = context;
    this._computeEngine = new ComputeEngine(context);
    this._globe = undefined;
    this._globeTranslucencyState = new GlobeTranslucencyState();
    this._primitives = new PrimitiveCollection();
    this._groundPrimitives = new PrimitiveCollection();

    this._globeHeight = undefined;
    this._cameraUnderground = false;

    this._logDepthBuffer = context.fragmentDepth;
    this._logDepthBufferDirty = true;

    this._tweens = new TweenCollection();

    this._shaderFrameCount = 0;

    this._sunPostProcess = undefined;

    this._computeCommandList = [];
    this._overlayCommandList = [];

    this._useOIT = defaultValue(options.orderIndependentTranslucency, true);
    this._executeOITFunction = undefined;

    this._depthPlane = new DepthPlane(options.depthPlaneEllipsoidOffset);

    this._clearColorCommand = new ClearCommand({
      color: new Color(),
      stencil: 0,
      owner: this,
    });
    this._depthClearCommand = new ClearCommand({
      depth: 1.0,
      owner: this,
    });
    this._stencilClearCommand = new ClearCommand({
      stencil: 0,
    });
    this._classificationStencilClearCommand = new ClearCommand({
      stencil: 0,
      renderState: RenderState.fromCache({
        stencilMask: StencilConstants$1.CLASSIFICATION_MASK,
      }),
    });

    this._depthOnlyRenderStateCache = {};

    this._transitioner = new SceneTransitioner(this);

    this._preUpdate = new Event();
    this._postUpdate = new Event();

    this._renderError = new Event();
    this._preRender = new Event();
    this._postRender = new Event();

    this._minimumDisableDepthTestDistance = 0.0;
    this._debugInspector = new DebugInspector();

    this._msaaSamples = defaultValue(options.msaaSamples, 1);

    /**
     * Exceptions occurring in <code>render</code> are always caught in order to raise the
     * <code>renderError</code> event.  If this property is true, the error is rethrown
     * after the event is raised.  If this property is false, the <code>render</code> function
     * returns normally after raising the event.
     *
     * @type {Boolean}
     * @default false
     */
    this.rethrowRenderErrors = false;

    /**
     * Determines whether or not to instantly complete the
     * scene transition animation on user input.
     *
     * @type {Boolean}
     * @default true
     */
    this.completeMorphOnUserInput = true;

    /**
     * The event fired at the beginning of a scene transition.
     * @type {Event}
     * @default Event()
     */
    this.morphStart = new Event();

    /**
     * The event fired at the completion of a scene transition.
     * @type {Event}
     * @default Event()
     */
    this.morphComplete = new Event();

    /**
     * The {@link SkyBox} used to draw the stars.
     *
     * @type {SkyBox}
     * @default undefined
     *
     * @see Scene#backgroundColor
     */
    this.skyBox = undefined;

    /**
     * The sky atmosphere drawn around the globe.
     *
     * @type {SkyAtmosphere}
     * @default undefined
     */
    this.skyAtmosphere = undefined;

    /**
     * The {@link Sun}.
     *
     * @type {Sun}
     * @default undefined
     */
    this.sun = undefined;

    /**
     * Uses a bloom filter on the sun when enabled.
     *
     * @type {Boolean}
     * @default true
     */
    this.sunBloom = true;
    this._sunBloom = undefined;

    /**
     * The {@link Moon}
     *
     * @type Moon
     * @default undefined
     */
    this.moon = undefined;

    /**
     * The background color, which is only visible if there is no sky box, i.e., {@link Scene#skyBox} is undefined.
     *
     * @type {Color}
     * @default {@link Color.BLACK}
     *
     * @see Scene#skyBox
     */
    this.backgroundColor = Color.clone(Color.BLACK);

    this._mode = SceneMode$1.SCENE3D;

    this._mapProjection = defined(options.mapProjection)
      ? options.mapProjection
      : new GeographicProjection();

    /**
     * The current morph transition time between 2D/Columbus View and 3D,
     * with 0.0 being 2D or Columbus View and 1.0 being 3D.
     *
     * @type {Number}
     * @default 1.0
     */
    this.morphTime = 1.0;

    /**
     * The far-to-near ratio of the multi-frustum when using a normal depth buffer.
     * <p>
     * This value is used to create the near and far values for each frustum of the multi-frustum. It is only used
     * when {@link Scene#logarithmicDepthBuffer} is <code>false</code>. When <code>logarithmicDepthBuffer</code> is
     * <code>true</code>, use {@link Scene#logarithmicDepthFarToNearRatio}.
     * </p>
     *
     * @type {Number}
     * @default 1000.0
     */
    this.farToNearRatio = 1000.0;

    /**
     * The far-to-near ratio of the multi-frustum when using a logarithmic depth buffer.
     * <p>
     * This value is used to create the near and far values for each frustum of the multi-frustum. It is only used
     * when {@link Scene#logarithmicDepthBuffer} is <code>true</code>. When <code>logarithmicDepthBuffer</code> is
     * <code>false</code>, use {@link Scene#farToNearRatio}.
     * </p>
     *
     * @type {Number}
     * @default 1e9
     */
    this.logarithmicDepthFarToNearRatio = 1e9;

    /**
     * Determines the uniform depth size in meters of each frustum of the multifrustum in 2D. If a primitive or model close
     * to the surface shows z-fighting, decreasing this will eliminate the artifact, but decrease performance. On the
     * other hand, increasing this will increase performance but may cause z-fighting among primitives close to the surface.
     *
     * @type {Number}
     * @default 1.75e6
     */
    this.nearToFarDistance2D = 1.75e6;

    /**
     * This property is for debugging only; it is not for production use.
     * <p>
     * A function that determines what commands are executed.  As shown in the examples below,
     * the function receives the command's <code>owner</code> as an argument, and returns a boolean indicating if the
     * command should be executed.
     * </p>
     * <p>
     * The default is <code>undefined</code>, indicating that all commands are executed.
     * </p>
     *
     * @type Function
     *
     * @default undefined
     *
     * @example
     * // Do not execute any commands.
     * scene.debugCommandFilter = function(command) {
     *     return false;
     * };
     *
     * // Execute only the billboard's commands.  That is, only draw the billboard.
     * const billboards = new Cesium.BillboardCollection();
     * scene.debugCommandFilter = function(command) {
     *     return command.owner === billboards;
     * };
     */
    this.debugCommandFilter = undefined;

    /**
     * This property is for debugging only; it is not for production use.
     * <p>
     * When <code>true</code>, commands are randomly shaded.  This is useful
     * for performance analysis to see what parts of a scene or model are
     * command-dense and could benefit from batching.
     * </p>
     *
     * @type Boolean
     *
     * @default false
     */
    this.debugShowCommands = false;

    /**
     * This property is for debugging only; it is not for production use.
     * <p>
     * When <code>true</code>, commands are shaded based on the frustums they
     * overlap.  Commands in the closest frustum are tinted red, commands in
     * the next closest are green, and commands in the farthest frustum are
     * blue.  If a command overlaps more than one frustum, the color components
     * are combined, e.g., a command overlapping the first two frustums is tinted
     * yellow.
     * </p>
     *
     * @type Boolean
     *
     * @default false
     */
    this.debugShowFrustums = false;

    /**
     * This property is for debugging only; it is not for production use.
     * <p>
     * Displays frames per second and time between frames.
     * </p>
     *
     * @type Boolean
     *
     * @default false
     */
    this.debugShowFramesPerSecond = false;

    /**
     * This property is for debugging only; it is not for production use.
     * <p>
     * Indicates which frustum will have depth information displayed.
     * </p>
     *
     * @type Number
     *
     * @default 1
     */
    this.debugShowDepthFrustum = 1;

    /**
     * This property is for debugging only; it is not for production use.
     * <p>
     * When <code>true</code>, draws outlines to show the boundaries of the camera frustums
     * </p>
     *
     * @type Boolean
     *
     * @default false
     */
    this.debugShowFrustumPlanes = false;
    this._debugShowFrustumPlanes = false;
    this._debugFrustumPlanes = undefined;

    /**
     * When <code>true</code>, enables picking using the depth buffer.
     *
     * @type Boolean
     * @default true
     */
    this.useDepthPicking = true;

    /**
     * When <code>true</code>, enables picking translucent geometry using the depth buffer. Note that {@link Scene#useDepthPicking} must also be true for enabling this to work.
     *
     * <p>
     * There is a decrease in performance when enabled. There are extra draw calls to write depth for
     * translucent geometry.
     * </p>
     *
     * @example
     * // picking the position of a translucent primitive
     * viewer.screenSpaceEventHandler.setInputAction(function onLeftClick(movement) {
     *      const pickedFeature = viewer.scene.pick(movement.position);
     *      if (!Cesium.defined(pickedFeature)) {
     *          // nothing picked
     *          return;
     *      }
     *      const worldPosition = viewer.scene.pickPosition(movement.position);
     * }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
     *
     * @type {Boolean}
     * @default false
     */
    this.pickTranslucentDepth = false;

    /**
     * The time in milliseconds to wait before checking if the camera has not moved and fire the cameraMoveEnd event.
     * @type {Number}
     * @default 500.0
     * @private
     */
    this.cameraEventWaitTime = 500.0;

    /**
     * Blends the atmosphere to geometry far from the camera for horizon views. Allows for additional
     * performance improvements by rendering less geometry and dispatching less terrain requests.
     * @type {Fog}
     */
    this.fog = new Fog();

    this._shadowMapCamera = new Camera(this);

    /**
     * The shadow map for the scene's light source. When enabled, models, primitives, and the globe may cast and receive shadows.
     * @type {ShadowMap}
     */
    this.shadowMap = new ShadowMap({
      context: context,
      lightCamera: this._shadowMapCamera,
      enabled: defaultValue(options.shadows, false),
    });

    /**
     * When <code>false</code>, 3D Tiles will render normally. When <code>true</code>, classified 3D Tile geometry will render normally and
     * unclassified 3D Tile geometry will render with the color multiplied by {@link Scene#invertClassificationColor}.
     * @type {Boolean}
     * @default false
     */
    this.invertClassification = false;

    /**
     * The highlight color of unclassified 3D Tile geometry when {@link Scene#invertClassification} is <code>true</code>.
     * <p>When the color's alpha is less than 1.0, the unclassified portions of the 3D Tiles will not blend correctly with the classified positions of the 3D Tiles.</p>
     * <p>Also, when the color's alpha is less than 1.0, the WEBGL_depth_texture and EXT_frag_depth WebGL extensions must be supported.</p>
     * @type {Color}
     * @default Color.WHITE
     */
    this.invertClassificationColor = Color.clone(Color.WHITE);

    this._actualInvertClassificationColor = Color.clone(
      this._invertClassificationColor
    );
    this._invertClassification = new InvertClassification();

    /**
     * The focal length for use when with cardboard or WebVR.
     * @type {Number}
     */
    this.focalLength = undefined;

    /**
     * The eye separation distance in meters for use with cardboard or WebVR.
     * @type {Number}
     */
    this.eyeSeparation = undefined;

    /**
     * Post processing effects applied to the final render.
     * @type {PostProcessStageCollection}
     */
    this.postProcessStages = new PostProcessStageCollection();

    this._brdfLutGenerator = new BrdfLutGenerator();

    this._performanceDisplay = undefined;
    this._debugVolume = undefined;

    this._screenSpaceCameraController = new ScreenSpaceCameraController(this);
    this._cameraUnderground = false;
    this._mapMode2D = defaultValue(options.mapMode2D, MapMode2D$1.INFINITE_SCROLL);

    // Keeps track of the state of a frame. FrameState is the state across
    // the primitives of the scene. This state is for internally keeping track
    // of celestial and environment effects that need to be updated/rendered in
    // a certain order as well as updating/tracking framebuffer usage.
    this._environmentState = {
      skyBoxCommand: undefined,
      skyAtmosphereCommand: undefined,
      sunDrawCommand: undefined,
      sunComputeCommand: undefined,
      moonCommand: undefined,

      isSunVisible: false,
      isMoonVisible: false,
      isReadyForAtmosphere: false,
      isSkyAtmosphereVisible: false,

      clearGlobeDepth: false,
      useDepthPlane: false,
      renderTranslucentDepthForPick: false,

      originalFramebuffer: undefined,
      useGlobeDepthFramebuffer: false,
      useOIT: false,
      useInvertClassification: false,
      usePostProcess: false,
      usePostProcessSelected: false,
      useWebVR: false,
    };

    this._useWebVR = false;
    this._cameraVR = undefined;
    this._aspectRatioVR = undefined;

    /**
     * When <code>true</code>, rendering a frame will only occur when needed as determined by changes within the scene.
     * Enabling improves performance of the application, but requires using {@link Scene#requestRender}
     * to render a new frame explicitly in this mode. This will be necessary in many cases after making changes
     * to the scene in other parts of the API.
     *
     * @see {@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|Improving Performance with Explicit Rendering}
     * @see Scene#maximumRenderTimeChange
     * @see Scene#requestRender
     *
     * @type {Boolean}
     * @default false
     */
    this.requestRenderMode = defaultValue(options.requestRenderMode, false);
    this._renderRequested = true;

    /**
     * If {@link Scene#requestRenderMode} is <code>true</code>, this value defines the maximum change in
     * simulation time allowed before a render is requested. Lower values increase the number of frames rendered
     * and higher values decrease the number of frames rendered. If <code>undefined</code>, changes to
     * the simulation time will never request a render.
     * This value impacts the rate of rendering for changes in the scene like lighting, entity property updates,
     * and animations.
     *
     * @see {@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|Improving Performance with Explicit Rendering}
     * @see Scene#requestRenderMode
     *
     * @type {Number}
     * @default 0.0
     */
    this.maximumRenderTimeChange = defaultValue(
      options.maximumRenderTimeChange,
      0.0
    );
    this._lastRenderTime = undefined;
    this._frameRateMonitor = undefined;

    this._removeRequestListenerCallback = RequestScheduler.requestCompletedEvent.addEventListener(
      requestRenderAfterFrame(this)
    );
    this._removeTaskProcessorListenerCallback = TaskProcessor.taskCompletedEvent.addEventListener(
      requestRenderAfterFrame(this)
    );
    this._removeGlobeCallbacks = [];

    const viewport = new BoundingRectangle(
      0,
      0,
      context.drawingBufferWidth,
      context.drawingBufferHeight
    );
    const camera = new Camera(this);

    if (this._logDepthBuffer) {
      camera.frustum.near = 0.1;
      camera.frustum.far = 10000000000.0;
    }

    /**
     * The camera view for the scene camera flight destination. Used for preloading flight destination tiles.
     * @type {Camera}
     * @private
     */
    this.preloadFlightCamera = new Camera(this);

    /**
     * The culling volume for the scene camera flight destination. Used for preloading flight destination tiles.
     * @type {CullingVolume}
     * @private
     */
    this.preloadFlightCullingVolume = undefined;

    this._picking = new Picking(this);
    this._defaultView = new View(this, camera, viewport);
    this._view = this._defaultView;

    this._hdr = undefined;
    this._hdrDirty = undefined;
    this.highDynamicRange = false;
    this.gamma = 2.2;

    /**
     * The spherical harmonic coefficients for image-based lighting of PBR models.
     * @type {Cartesian3[]}
     */
    this.sphericalHarmonicCoefficients = undefined;

    /**
     * The url to the KTX2 file containing the specular environment map and convoluted mipmaps for image-based lighting of PBR models.
     * @type {String}
     */
    this.specularEnvironmentMaps = undefined;
    this._specularEnvironmentMapAtlas = undefined;

    /**
     * The light source for shading. Defaults to a directional light from the Sun.
     * @type {Light}
     */
    this.light = new SunLight();

    // Give frameState, camera, and screen space camera controller initial state before rendering
    updateFrameNumber(this, 0.0, JulianDate.now());
    this.updateFrameState();
    this.initializeFrame();
  }

  function updateGlobeListeners(scene, globe) {
    for (let i = 0; i < scene._removeGlobeCallbacks.length; ++i) {
      scene._removeGlobeCallbacks[i]();
    }
    scene._removeGlobeCallbacks.length = 0;

    const removeGlobeCallbacks = [];
    if (defined(globe)) {
      removeGlobeCallbacks.push(
        globe.imageryLayersUpdatedEvent.addEventListener(
          requestRenderAfterFrame(scene)
        )
      );
      removeGlobeCallbacks.push(
        globe.terrainProviderChanged.addEventListener(
          requestRenderAfterFrame(scene)
        )
      );
    }
    scene._removeGlobeCallbacks = removeGlobeCallbacks;
  }

  Object.defineProperties(Scene.prototype, {
    /**
     * Gets the canvas element to which this scene is bound.
     * @memberof Scene.prototype
     *
     * @type {HTMLCanvasElement}
     * @readonly
     */
    canvas: {
      get: function () {
        return this._canvas;
      },
    },

    /**
     * The drawingBufferHeight of the underlying GL context.
     * @memberof Scene.prototype
     *
     * @type {Number}
     * @readonly
     *
     * @see {@link https://www.khronos.org/registry/webgl/specs/1.0/#DOM-WebGLRenderingContext-drawingBufferHeight|drawingBufferHeight}
     */
    drawingBufferHeight: {
      get: function () {
        return this._context.drawingBufferHeight;
      },
    },

    /**
     * The drawingBufferHeight of the underlying GL context.
     * @memberof Scene.prototype
     *
     * @type {Number}
     * @readonly
     *
     * @see {@link https://www.khronos.org/registry/webgl/specs/1.0/#DOM-WebGLRenderingContext-drawingBufferHeight|drawingBufferHeight}
     */
    drawingBufferWidth: {
      get: function () {
        return this._context.drawingBufferWidth;
      },
    },

    /**
     * The maximum aliased line width, in pixels, supported by this WebGL implementation.  It will be at least one.
     * @memberof Scene.prototype
     *
     * @type {Number}
     * @readonly
     *
     * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with <code>ALIASED_LINE_WIDTH_RANGE</code>.
     */
    maximumAliasedLineWidth: {
      get: function () {
        return ContextLimits.maximumAliasedLineWidth;
      },
    },

    /**
     * The maximum length in pixels of one edge of a cube map, supported by this WebGL implementation.  It will be at least 16.
     * @memberof Scene.prototype
     *
     * @type {Number}
     * @readonly
     *
     * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with <code>GL_MAX_CUBE_MAP_TEXTURE_SIZE</code>.
     */
    maximumCubeMapSize: {
      get: function () {
        return ContextLimits.maximumCubeMapSize;
      },
    },

    /**
     * Returns <code>true</code> if the {@link Scene#pickPosition} function is supported.
     * @memberof Scene.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @see Scene#pickPosition
     */
    pickPositionSupported: {
      get: function () {
        return this._context.depthTexture;
      },
    },

    /**
     * Returns <code>true</code> if the {@link Scene#sampleHeight} and {@link Scene#sampleHeightMostDetailed} functions are supported.
     * @memberof Scene.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @see Scene#sampleHeight
     * @see Scene#sampleHeightMostDetailed
     */
    sampleHeightSupported: {
      get: function () {
        return this._context.depthTexture;
      },
    },

    /**
     * Returns <code>true</code> if the {@link Scene#clampToHeight} and {@link Scene#clampToHeightMostDetailed} functions are supported.
     * @memberof Scene.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @see Scene#clampToHeight
     * @see Scene#clampToHeightMostDetailed
     */
    clampToHeightSupported: {
      get: function () {
        return this._context.depthTexture;
      },
    },

    /**
     * Returns <code>true</code> if the {@link Scene#invertClassification} is supported.
     * @memberof Scene.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @see Scene#invertClassification
     */
    invertClassificationSupported: {
      get: function () {
        return this._context.depthTexture;
      },
    },

    /**
     * Returns <code>true</code> if specular environment maps are supported.
     * @memberof Scene.prototype
     *
     * @type {Boolean}
     * @readonly
     *
     * @see Scene#specularEnvironmentMaps
     */
    specularEnvironmentMapsSupported: {
      get: function () {
        return OctahedralProjectedCubeMap.isSupported(this._context);
      },
    },

    /**
     * Gets or sets the depth-test ellipsoid.
     * @memberof Scene.prototype
     *
     * @type {Globe}
     */
    globe: {
      get: function () {
        return this._globe;
      },

      set: function (globe) {
        this._globe = this._globe && this._globe.destroy();
        this._globe = globe;

        updateGlobeListeners(this, globe);
      },
    },

    /**
     * Gets the collection of primitives.
     * @memberof Scene.prototype
     *
     * @type {PrimitiveCollection}
     * @readonly
     */
    primitives: {
      get: function () {
        return this._primitives;
      },
    },

    /**
     * Gets the collection of ground primitives.
     * @memberof Scene.prototype
     *
     * @type {PrimitiveCollection}
     * @readonly
     */
    groundPrimitives: {
      get: function () {
        return this._groundPrimitives;
      },
    },

    /**
     * Gets or sets the camera.
     * @memberof Scene.prototype
     *
     * @type {Camera}
     * @readonly
     */
    camera: {
      get: function () {
        return this._view.camera;
      },
      set: function (camera) {
        // For internal use only. Documentation is still @readonly.
        this._view.camera = camera;
      },
    },

    /**
     * Gets or sets the view.
     * @memberof Scene.prototype
     *
     * @type {View}
     * @readonly
     *
     * @private
     */
    view: {
      get: function () {
        return this._view;
      },
      set: function (view) {
        // For internal use only. Documentation is still @readonly.
        this._view = view;
      },
    },

    /**
     * Gets the default view.
     * @memberof Scene.prototype
     *
     * @type {View}
     * @readonly
     *
     * @private
     */
    defaultView: {
      get: function () {
        return this._defaultView;
      },
    },

    /**
     * Gets picking functions and state
     * @memberof Scene.prototype
     *
     * @type {Picking}
     * @readonly
     *
     * @private
     */
    picking: {
      get: function () {
        return this._picking;
      },
    },

    /**
     * Gets the controller for camera input handling.
     * @memberof Scene.prototype
     *
     * @type {ScreenSpaceCameraController}
     * @readonly
     */
    screenSpaceCameraController: {
      get: function () {
        return this._screenSpaceCameraController;
      },
    },

    /**
     * Get the map projection to use in 2D and Columbus View modes.
     * @memberof Scene.prototype
     *
     * @type {MapProjection}
     * @readonly
     *
     * @default new GeographicProjection()
     */
    mapProjection: {
      get: function () {
        return this._mapProjection;
      },
    },

    /**
     * Gets the job scheduler
     * @memberof Scene.prototype
     * @type {JobScheduler}
     * @readonly
     *
     * @private
     */
    jobScheduler: {
      get: function () {
        return this._jobScheduler;
      },
    },

    /**
     * Gets state information about the current scene. If called outside of a primitive's <code>update</code>
     * function, the previous frame's state is returned.
     * @memberof Scene.prototype
     *
     * @type {FrameState}
     * @readonly
     *
     * @private
     */
    frameState: {
      get: function () {
        return this._frameState;
      },
    },

    /**
     * Gets the environment state.
     * @memberof Scene.prototype
     *
     * @type {EnvironmentState}
     * @readonly
     *
     * @private
     */
    environmentState: {
      get: function () {
        return this._environmentState;
      },
    },

    /**
     * Gets the collection of tweens taking place in the scene.
     * @memberof Scene.prototype
     *
     * @type {TweenCollection}
     * @readonly
     *
     * @private
     */
    tweens: {
      get: function () {
        return this._tweens;
      },
    },

    /**
     * Gets the collection of image layers that will be rendered on the globe.
     * @memberof Scene.prototype
     *
     * @type {ImageryLayerCollection}
     * @readonly
     */
    imageryLayers: {
      get: function () {
        if (!defined(this.globe)) {
          return undefined;
        }

        return this.globe.imageryLayers;
      },
    },

    /**
     * The terrain provider providing surface geometry for the globe.
     * @memberof Scene.prototype
     *
     * @type {TerrainProvider}
     */
    terrainProvider: {
      get: function () {
        if (!defined(this.globe)) {
          return undefined;
        }

        return this.globe.terrainProvider;
      },
      set: function (terrainProvider) {
        if (defined(this.globe)) {
          this.globe.terrainProvider = terrainProvider;
        }
      },
    },

    /**
     * Gets an event that's raised when the terrain provider is changed
     * @memberof Scene.prototype
     *
     * @type {Event}
     * @readonly
     */
    terrainProviderChanged: {
      get: function () {
        if (!defined(this.globe)) {
          return undefined;
        }

        return this.globe.terrainProviderChanged;
      },
    },

    /**
     * Gets the event that will be raised before the scene is updated or rendered.  Subscribers to the event
     * receive the Scene instance as the first parameter and the current time as the second parameter.
     * @memberof Scene.prototype
     *
     * @see {@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|Improving Performance with Explicit Rendering}
     * @see Scene#postUpdate
     * @see Scene#preRender
     * @see Scene#postRender
     *
     * @type {Event}
     * @readonly
     */
    preUpdate: {
      get: function () {
        return this._preUpdate;
      },
    },

    /**
     * Gets the event that will be raised immediately after the scene is updated and before the scene is rendered.
     * Subscribers to the event receive the Scene instance as the first parameter and the current time as the second
     * parameter.
     * @memberof Scene.prototype
     *
     * @see {@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|Improving Performance with Explicit Rendering}
     * @see Scene#preUpdate
     * @see Scene#preRender
     * @see Scene#postRender
     *
     * @type {Event}
     * @readonly
     */
    postUpdate: {
      get: function () {
        return this._postUpdate;
      },
    },

    /**
     * Gets the event that will be raised when an error is thrown inside the <code>render</code> function.
     * The Scene instance and the thrown error are the only two parameters passed to the event handler.
     * By default, errors are not rethrown after this event is raised, but that can be changed by setting
     * the <code>rethrowRenderErrors</code> property.
     * @memberof Scene.prototype
     *
     * @type {Event}
     * @readonly
     */
    renderError: {
      get: function () {
        return this._renderError;
      },
    },

    /**
     * Gets the event that will be raised after the scene is updated and immediately before the scene is rendered.
     * Subscribers to the event receive the Scene instance as the first parameter and the current time as the second
     * parameter.
     * @memberof Scene.prototype
     *
     * @see {@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|Improving Performance with Explicit Rendering}
     * @see Scene#preUpdate
     * @see Scene#postUpdate
     * @see Scene#postRender
     *
     * @type {Event}
     * @readonly
     */
    preRender: {
      get: function () {
        return this._preRender;
      },
    },

    /**
     * Gets the event that will be raised immediately after the scene is rendered.  Subscribers to the event
     * receive the Scene instance as the first parameter and the current time as the second parameter.
     * @memberof Scene.prototype
     *
     * @see {@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|Improving Performance with Explicit Rendering}
     * @see Scene#preUpdate
     * @see Scene#postUpdate
     * @see Scene#postRender
     *
     * @type {Event}
     * @readonly
     */
    postRender: {
      get: function () {
        return this._postRender;
      },
    },

    /**
     * Gets the simulation time when the scene was last rendered. Returns undefined if the scene has not yet been
     * rendered.
     * @memberof Scene.prototype
     *
     * @type {JulianDate}
     * @readonly
     */
    lastRenderTime: {
      get: function () {
        return this._lastRenderTime;
      },
    },

    /**
     * @memberof Scene.prototype
     * @private
     * @readonly
     */
    context: {
      get: function () {
        return this._context;
      },
    },

    /**
     * This property is for debugging only; it is not for production use.
     * <p>
     * When {@link Scene.debugShowFrustums} is <code>true</code>, this contains
     * properties with statistics about the number of command execute per frustum.
     * <code>totalCommands</code> is the total number of commands executed, ignoring
     * overlap. <code>commandsInFrustums</code> is an array with the number of times
     * commands are executed redundantly, e.g., how many commands overlap two or
     * three frustums.
     * </p>
     *
     * @memberof Scene.prototype
     *
     * @type {Object}
     * @readonly
     *
     * @default undefined
     */
    debugFrustumStatistics: {
      get: function () {
        return this._view.debugFrustumStatistics;
      },
    },

    /**
     * Gets whether or not the scene is optimized for 3D only viewing.
     * @memberof Scene.prototype
     * @type {Boolean}
     * @readonly
     */
    scene3DOnly: {
      get: function () {
        return this._frameState.scene3DOnly;
      },
    },

    /**
     * Gets whether or not the scene has order independent translucency enabled.
     * Note that this only reflects the original construction option, and there are
     * other factors that could prevent OIT from functioning on a given system configuration.
     * @memberof Scene.prototype
     * @type {Boolean}
     * @readonly
     */
    orderIndependentTranslucency: {
      get: function () {
        return this._useOIT;
      },
    },

    /**
     * Gets the unique identifier for this scene.
     * @memberof Scene.prototype
     * @type {String}
     * @readonly
     */
    id: {
      get: function () {
        return this._id;
      },
    },

    /**
     * Gets or sets the current mode of the scene.
     * @memberof Scene.prototype
     * @type {SceneMode}
     * @default {@link SceneMode.SCENE3D}
     */
    mode: {
      get: function () {
        return this._mode;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (this.scene3DOnly && value !== SceneMode$1.SCENE3D) {
          throw new DeveloperError(
            "Only SceneMode.SCENE3D is valid when scene3DOnly is true."
          );
        }
        //>>includeEnd('debug');
        if (value === SceneMode$1.SCENE2D) {
          this.morphTo2D(0);
        } else if (value === SceneMode$1.SCENE3D) {
          this.morphTo3D(0);
        } else if (value === SceneMode$1.COLUMBUS_VIEW) {
          this.morphToColumbusView(0);
          //>>includeStart('debug', pragmas.debug);
        } else {
          throw new DeveloperError(
            "value must be a valid SceneMode enumeration."
          );
          //>>includeEnd('debug');
        }
        this._mode = value;
      },
    },

    /**
     * Gets the number of frustums used in the last frame.
     * @memberof Scene.prototype
     * @type {FrustumCommands[]}
     *
     * @private
     */
    frustumCommandsList: {
      get: function () {
        return this._view.frustumCommandsList;
      },
    },

    /**
     * Gets the number of frustums used in the last frame.
     * @memberof Scene.prototype
     * @type {Number}
     *
     * @private
     */
    numberOfFrustums: {
      get: function () {
        return this._view.frustumCommandsList.length;
      },
    },

    /**
     * When <code>true</code>, splits the scene into two viewports with steroscopic views for the left and right eyes.
     * Used for cardboard and WebVR.
     * @memberof Scene.prototype
     * @type {Boolean}
     * @default false
     */
    useWebVR: {
      get: function () {
        return this._useWebVR;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (this.camera.frustum instanceof OrthographicFrustum) {
          throw new DeveloperError(
            "VR is unsupported with an orthographic projection."
          );
        }
        //>>includeEnd('debug');
        this._useWebVR = value;
        if (this._useWebVR) {
          this._frameState.creditDisplay.container.style.visibility = "hidden";
          this._cameraVR = new Camera(this);
          if (!defined(this._deviceOrientationCameraController)) {
            this._deviceOrientationCameraController = new DeviceOrientationCameraController(
              this
            );
          }

          this._aspectRatioVR = this.camera.frustum.aspectRatio;
        } else {
          this._frameState.creditDisplay.container.style.visibility = "visible";
          this._cameraVR = undefined;
          this._deviceOrientationCameraController =
            this._deviceOrientationCameraController &&
            !this._deviceOrientationCameraController.isDestroyed() &&
            this._deviceOrientationCameraController.destroy();

          this.camera.frustum.aspectRatio = this._aspectRatioVR;
          this.camera.frustum.xOffset = 0.0;
        }
      },
    },

    /**
     * Determines if the 2D map is rotatable or can be scrolled infinitely in the horizontal direction.
     * @memberof Scene.prototype
     * @type {MapMode2D}
     * @readonly
     */
    mapMode2D: {
      get: function () {
        return this._mapMode2D;
      },
    },

    /**
     * Gets or sets the position of the splitter within the viewport.  Valid values are between 0.0 and 1.0.
     * @memberof Scene.prototype
     *
     * @type {Number}
     */
    splitPosition: {
      get: function () {
        return this._frameState.splitPosition;
      },
      set: function (value) {
        this._frameState.splitPosition = value;
      },
    },

    /**
     * The distance from the camera at which to disable the depth test of billboards, labels and points
     * to, for example, prevent clipping against terrain. When set to zero, the depth test should always
     * be applied. When less than zero, the depth test should never be applied. Setting the disableDepthTestDistance
     * property of a billboard, label or point will override this value.
     * @memberof Scene.prototype
     * @type {Number}
     * @default 0.0
     */
    minimumDisableDepthTestDistance: {
      get: function () {
        return this._minimumDisableDepthTestDistance;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(value) || value < 0.0) {
          throw new DeveloperError(
            "minimumDisableDepthTestDistance must be greater than or equal to 0.0."
          );
        }
        //>>includeEnd('debug');
        this._minimumDisableDepthTestDistance = value;
      },
    },

    /**
     * Whether or not to use a logarithmic depth buffer. Enabling this option will allow for less frustums in the multi-frustum,
     * increasing performance. This property relies on fragmentDepth being supported.
     * @memberof Scene.prototype
     * @type {Boolean}
     */
    logarithmicDepthBuffer: {
      get: function () {
        return this._logDepthBuffer;
      },
      set: function (value) {
        value = this._context.fragmentDepth && value;
        if (this._logDepthBuffer !== value) {
          this._logDepthBuffer = value;
          this._logDepthBufferDirty = true;
        }
      },
    },

    /**
     * The value used for gamma correction. This is only used when rendering with high dynamic range.
     * @memberof Scene.prototype
     * @type {Number}
     * @default 2.2
     */
    gamma: {
      get: function () {
        return this._context.uniformState.gamma;
      },
      set: function (value) {
        this._context.uniformState.gamma = value;
      },
    },

    /**
     * Whether or not to use high dynamic range rendering.
     * @memberof Scene.prototype
     * @type {Boolean}
     * @default false
     */
    highDynamicRange: {
      get: function () {
        return this._hdr;
      },
      set: function (value) {
        const context = this._context;
        const hdr =
          value &&
          context.depthTexture &&
          (context.colorBufferFloat || context.colorBufferHalfFloat);
        this._hdrDirty = hdr !== this._hdr;
        this._hdr = hdr;
      },
    },

    /**
     * Whether or not high dynamic range rendering is supported.
     * @memberof Scene.prototype
     * @type {Boolean}
     * @readonly
     * @default true
     */
    highDynamicRangeSupported: {
      get: function () {
        const context = this._context;
        return (
          context.depthTexture &&
          (context.colorBufferFloat || context.colorBufferHalfFloat)
        );
      },
    },

    /**
     * Whether or not the camera is underneath the globe.
     * @memberof Scene.prototype
     * @type {Boolean}
     * @readonly
     * @default false
     */
    cameraUnderground: {
      get: function () {
        return this._cameraUnderground;
      },
    },

    /**
     * The sample rate of multisample antialiasing (values greater than 1 enable MSAA).
     * @memberof Scene.prototype
     * @type {Number}
     * @default 1
     */
    msaaSamples: {
      get: function () {
        return this._msaaSamples;
      },
      set: function (value) {
        value = Math.min(value, ContextLimits.maximumSamples);
        this._msaaSamples = value;
      },
    },

    /**
     * Returns <code>true</code> if the Scene's context supports MSAA.
     * @memberof Scene.prototype
     * @type {Boolean}
     * @readonly
     */
    msaaSupported: {
      get: function () {
        return this._context.msaa;
      },
    },

    /**
     * Ratio between a pixel and a density-independent pixel. Provides a standard unit of
     * measure for real pixel measurements appropriate to a particular device.
     *
     * @memberof Scene.prototype
     * @type {Number}
     * @default 1.0
     * @private
     */
    pixelRatio: {
      get: function () {
        return this._frameState.pixelRatio;
      },
      set: function (value) {
        this._frameState.pixelRatio = value;
      },
    },

    /**
     * @private
     */
    opaqueFrustumNearOffset: {
      get: function () {
        return 0.9999;
      },
    },

    /**
     * @private
     */
    globeHeight: {
      get: function () {
        return this._globeHeight;
      },
    },
  });

  /**
   * Determines if a compressed texture format is supported.
   * @param {String} format The texture format. May be the name of the format or the WebGL extension name, e.g. s3tc or WEBGL_compressed_texture_s3tc.
   * @return {boolean} Whether or not the format is supported.
   */
  Scene.prototype.getCompressedTextureFormatSupported = function (format) {
    const context = this.context;
    return (
      ((format === "WEBGL_compressed_texture_s3tc" || format === "s3tc") &&
        context.s3tc) ||
      ((format === "WEBGL_compressed_texture_pvrtc" || format === "pvrtc") &&
        context.pvrtc) ||
      ((format === "WEBGL_compressed_texture_etc" || format === "etc") &&
        context.etc) ||
      ((format === "WEBGL_compressed_texture_etc1" || format === "etc1") &&
        context.etc1) ||
      ((format === "WEBGL_compressed_texture_astc" || format === "astc") &&
        context.astc) ||
      ((format === "EXT_texture_compression_bptc" || format === "bc7") &&
        context.bc7)
    );
  };

  function updateDerivedCommands(scene, command, shadowsDirty) {
    const frameState = scene._frameState;
    const context = scene._context;
    const oit = scene._view.oit;
    const lightShadowMaps = frameState.shadowState.lightShadowMaps;
    const lightShadowsEnabled = frameState.shadowState.lightShadowsEnabled;

    let derivedCommands = command.derivedCommands;

    if (defined(command.pickId)) {
      derivedCommands.picking = DerivedCommand.createPickDerivedCommand(
        scene,
        command,
        context,
        derivedCommands.picking
      );
    }

    if (!command.pickOnly) {
      derivedCommands.depth = DerivedCommand.createDepthOnlyDerivedCommand(
        scene,
        command,
        context,
        derivedCommands.depth
      );
    }

    derivedCommands.originalCommand = command;

    if (scene._hdr) {
      derivedCommands.hdr = DerivedCommand.createHdrCommand(
        command,
        context,
        derivedCommands.hdr
      );
      command = derivedCommands.hdr.command;
      derivedCommands = command.derivedCommands;
    }

    if (lightShadowsEnabled && command.receiveShadows) {
      derivedCommands.shadows = ShadowMap.createReceiveDerivedCommand(
        lightShadowMaps,
        command,
        shadowsDirty,
        context,
        derivedCommands.shadows
      );
    }

    if (command.pass === Pass$1.TRANSLUCENT && defined(oit) && oit.isSupported()) {
      if (lightShadowsEnabled && command.receiveShadows) {
        derivedCommands.oit = defined(derivedCommands.oit)
          ? derivedCommands.oit
          : {};
        derivedCommands.oit.shadows = oit.createDerivedCommands(
          derivedCommands.shadows.receiveCommand,
          context,
          derivedCommands.oit.shadows
        );
      } else {
        derivedCommands.oit = oit.createDerivedCommands(
          command,
          context,
          derivedCommands.oit
        );
      }
    }
  }

  /**
   * @private
   */
  Scene.prototype.updateDerivedCommands = function (command) {
    if (!defined(command.derivedCommands)) {
      // Is not a DrawCommand
      return;
    }

    const frameState = this._frameState;
    const context = this._context;

    // Update derived commands when any shadow maps become dirty
    let shadowsDirty = false;
    const lastDirtyTime = frameState.shadowState.lastDirtyTime;
    if (command.lastDirtyTime !== lastDirtyTime) {
      command.lastDirtyTime = lastDirtyTime;
      command.dirty = true;
      shadowsDirty = true;
    }

    const useLogDepth = frameState.useLogDepth;
    const useHdr = this._hdr;
    const derivedCommands = command.derivedCommands;
    const hasLogDepthDerivedCommands = defined(derivedCommands.logDepth);
    const hasHdrCommands = defined(derivedCommands.hdr);
    const hasDerivedCommands = defined(derivedCommands.originalCommand);
    const needsLogDepthDerivedCommands =
      useLogDepth && !hasLogDepthDerivedCommands;
    const needsHdrCommands = useHdr && !hasHdrCommands;
    const needsDerivedCommands = (!useLogDepth || !useHdr) && !hasDerivedCommands;
    command.dirty =
      command.dirty ||
      needsLogDepthDerivedCommands ||
      needsHdrCommands ||
      needsDerivedCommands;

    if (command.dirty) {
      command.dirty = false;

      const shadowMaps = frameState.shadowState.shadowMaps;
      const shadowsEnabled = frameState.shadowState.shadowsEnabled;
      if (shadowsEnabled && command.castShadows) {
        derivedCommands.shadows = ShadowMap.createCastDerivedCommand(
          shadowMaps,
          command,
          shadowsDirty,
          context,
          derivedCommands.shadows
        );
      }

      if (hasLogDepthDerivedCommands || needsLogDepthDerivedCommands) {
        derivedCommands.logDepth = DerivedCommand.createLogDepthCommand(
          command,
          context,
          derivedCommands.logDepth
        );
        updateDerivedCommands(
          this,
          derivedCommands.logDepth.command,
          shadowsDirty
        );
      }
      if (hasDerivedCommands || needsDerivedCommands) {
        updateDerivedCommands(this, command, shadowsDirty);
      }
    }
  };

  const renderTilesetPassState = new Cesium3DTilePassState({
    pass: Cesium3DTilePass$1.RENDER,
  });

  const preloadTilesetPassState = new Cesium3DTilePassState({
    pass: Cesium3DTilePass$1.PRELOAD,
  });

  const preloadFlightTilesetPassState = new Cesium3DTilePassState({
    pass: Cesium3DTilePass$1.PRELOAD_FLIGHT,
  });

  const requestRenderModeDeferCheckPassState = new Cesium3DTilePassState({
    pass: Cesium3DTilePass$1.REQUEST_RENDER_MODE_DEFER_CHECK,
  });

  const scratchOccluderBoundingSphere = new BoundingSphere();
  let scratchOccluder;

  function getOccluder(scene) {
    // TODO: The occluder is the top-level globe. When we add
    //       support for multiple central bodies, this should be the closest one.
    const globe = scene.globe;
    if (
      scene._mode === SceneMode$1.SCENE3D &&
      defined(globe) &&
      globe.show &&
      !scene._cameraUnderground &&
      !scene._globeTranslucencyState.translucent
    ) {
      const ellipsoid = globe.ellipsoid;
      const minimumTerrainHeight = scene.frameState.minimumTerrainHeight;
      scratchOccluderBoundingSphere.radius =
        ellipsoid.minimumRadius + minimumTerrainHeight;
      scratchOccluder = Occluder.fromBoundingSphere(
        scratchOccluderBoundingSphere,
        scene.camera.positionWC,
        scratchOccluder
      );
      return scratchOccluder;
    }

    return undefined;
  }

  /**
   * @private
   */
  Scene.prototype.clearPasses = function (passes) {
    passes.render = false;
    passes.pick = false;
    passes.depth = false;
    passes.postProcess = false;
    passes.offscreen = false;
  };

  function updateFrameNumber(scene, frameNumber, time) {
    const frameState = scene._frameState;
    frameState.frameNumber = frameNumber;
    frameState.time = JulianDate.clone(time, frameState.time);
  }

  /**
   * @private
   */
  Scene.prototype.updateFrameState = function () {
    const camera = this.camera;

    const frameState = this._frameState;
    frameState.commandList.length = 0;
    frameState.shadowMaps.length = 0;
    frameState.brdfLutGenerator = this._brdfLutGenerator;
    frameState.environmentMap = this.skyBox && this.skyBox._cubeMap;
    frameState.mode = this._mode;
    frameState.morphTime = this.morphTime;
    frameState.mapProjection = this.mapProjection;
    frameState.camera = camera;
    frameState.cullingVolume = camera.frustum.computeCullingVolume(
      camera.positionWC,
      camera.directionWC,
      camera.upWC
    );
    frameState.occluder = getOccluder(this);
    frameState.minimumTerrainHeight = 0.0;
    frameState.minimumDisableDepthTestDistance = this._minimumDisableDepthTestDistance;
    frameState.invertClassification = this.invertClassification;
    frameState.useLogDepth =
      this._logDepthBuffer &&
      !(
        this.camera.frustum instanceof OrthographicFrustum ||
        this.camera.frustum instanceof OrthographicOffCenterFrustum
      );
    frameState.light = this.light;
    frameState.cameraUnderground = this._cameraUnderground;
    frameState.globeTranslucencyState = this._globeTranslucencyState;

    if (defined(this.globe)) {
      frameState.terrainExaggeration = this.globe.terrainExaggeration;
      frameState.terrainExaggerationRelativeHeight = this.globe.terrainExaggerationRelativeHeight;
    }

    if (
      defined(this._specularEnvironmentMapAtlas) &&
      this._specularEnvironmentMapAtlas.ready
    ) {
      frameState.specularEnvironmentMaps = this._specularEnvironmentMapAtlas.texture;
      frameState.specularEnvironmentMapsMaximumLOD = this._specularEnvironmentMapAtlas.maximumMipmapLevel;
    } else {
      frameState.specularEnvironmentMaps = undefined;
      frameState.specularEnvironmentMapsMaximumLOD = undefined;
    }

    frameState.sphericalHarmonicCoefficients = this.sphericalHarmonicCoefficients;

    this._actualInvertClassificationColor = Color.clone(
      this.invertClassificationColor,
      this._actualInvertClassificationColor
    );
    if (!InvertClassification.isTranslucencySupported(this._context)) {
      this._actualInvertClassificationColor.alpha = 1.0;
    }

    frameState.invertClassificationColor = this._actualInvertClassificationColor;

    if (defined(this.globe)) {
      frameState.maximumScreenSpaceError = this.globe.maximumScreenSpaceError;
    } else {
      frameState.maximumScreenSpaceError = 2;
    }

    this.clearPasses(frameState.passes);

    frameState.tilesetPassState = undefined;
  };

  /**
   * @private
   */
  Scene.prototype.isVisible = function (command, cullingVolume, occluder) {
    return (
      defined(command) &&
      (!defined(command.boundingVolume) ||
        !command.cull ||
        (cullingVolume.computeVisibility(command.boundingVolume) !==
          Intersect$1.OUTSIDE &&
          (!defined(occluder) ||
            !command.occlude ||
            !command.boundingVolume.isOccluded(occluder))))
    );
  };

  let transformFrom2D = new Matrix4(
    0.0,
    0.0,
    1.0,
    0.0,
    1.0,
    0.0,
    0.0,
    0.0,
    0.0,
    1.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    1.0
  );
  transformFrom2D = Matrix4.inverseTransformation(
    transformFrom2D,
    transformFrom2D
  );

  function debugShowBoundingVolume(command, scene, passState, debugFramebuffer) {
    // Debug code to draw bounding volume for command.  Not optimized!
    // Assumes bounding volume is a bounding sphere or box
    const frameState = scene._frameState;
    const context = frameState.context;
    const boundingVolume = command.boundingVolume;

    if (defined(scene._debugVolume)) {
      scene._debugVolume.destroy();
    }

    let geometry;

    let center = Cartesian3.clone(boundingVolume.center);
    if (frameState.mode !== SceneMode$1.SCENE3D) {
      center = Matrix4.multiplyByPoint(transformFrom2D, center, center);
      const projection = frameState.mapProjection;
      const centerCartographic = projection.unproject(center);
      center = projection.ellipsoid.cartographicToCartesian(centerCartographic);
    }

    if (defined(boundingVolume.radius)) {
      const radius = boundingVolume.radius;

      geometry = GeometryPipeline.toWireframe(
        EllipsoidGeometry.createGeometry(
          new EllipsoidGeometry({
            radii: new Cartesian3(radius, radius, radius),
            vertexFormat: PerInstanceColorAppearance.FLAT_VERTEX_FORMAT,
          })
        )
      );

      scene._debugVolume = new Primitive$3({
        geometryInstances: new GeometryInstance({
          geometry: geometry,
          modelMatrix: Matrix4.fromTranslation(center),
          attributes: {
            color: new ColorGeometryInstanceAttribute(1.0, 0.0, 0.0, 1.0),
          },
        }),
        appearance: new PerInstanceColorAppearance({
          flat: true,
          translucent: false,
        }),
        asynchronous: false,
      });
    } else {
      const halfAxes = boundingVolume.halfAxes;

      geometry = GeometryPipeline.toWireframe(
        BoxGeometry.createGeometry(
          BoxGeometry.fromDimensions({
            dimensions: new Cartesian3(2.0, 2.0, 2.0),
            vertexFormat: PerInstanceColorAppearance.FLAT_VERTEX_FORMAT,
          })
        )
      );

      scene._debugVolume = new Primitive$3({
        geometryInstances: new GeometryInstance({
          geometry: geometry,
          modelMatrix: Matrix4.fromRotationTranslation(
            halfAxes,
            center,
            new Matrix4()
          ),
          attributes: {
            color: new ColorGeometryInstanceAttribute(1.0, 0.0, 0.0, 1.0),
          },
        }),
        appearance: new PerInstanceColorAppearance({
          flat: true,
          translucent: false,
        }),
        asynchronous: false,
      });
    }

    const savedCommandList = frameState.commandList;
    const commandList = (frameState.commandList = []);
    scene._debugVolume.update(frameState);

    command = commandList[0];

    if (frameState.useLogDepth) {
      const logDepth = DerivedCommand.createLogDepthCommand(command, context);
      command = logDepth.command;
    }

    let framebuffer;
    if (defined(debugFramebuffer)) {
      framebuffer = passState.framebuffer;
      passState.framebuffer = debugFramebuffer;
    }

    command.execute(context, passState);

    if (defined(framebuffer)) {
      passState.framebuffer = framebuffer;
    }

    frameState.commandList = savedCommandList;
  }

  function executeCommand(command, scene, context, passState, debugFramebuffer) {
    const frameState = scene._frameState;

    if (defined(scene.debugCommandFilter) && !scene.debugCommandFilter(command)) {
      return;
    }

    if (command instanceof ClearCommand) {
      command.execute(context, passState);
      return;
    }

    if (command.debugShowBoundingVolume && defined(command.boundingVolume)) {
      debugShowBoundingVolume(command, scene, passState, debugFramebuffer);
    }

    if (frameState.useLogDepth && defined(command.derivedCommands.logDepth)) {
      command = command.derivedCommands.logDepth.command;
    }

    const passes = frameState.passes;
    if (
      !passes.pick &&
      !passes.depth &&
      scene._hdr &&
      defined(command.derivedCommands) &&
      defined(command.derivedCommands.hdr)
    ) {
      command = command.derivedCommands.hdr.command;
    }

    if (passes.pick || passes.depth) {
      if (
        passes.pick &&
        !passes.depth &&
        defined(command.derivedCommands.picking)
      ) {
        command = command.derivedCommands.picking.pickCommand;
        command.execute(context, passState);
        return;
      } else if (defined(command.derivedCommands.depth)) {
        command = command.derivedCommands.depth.depthOnlyCommand;
        command.execute(context, passState);
        return;
      }
    }

    if (scene.debugShowCommands || scene.debugShowFrustums) {
      scene._debugInspector.executeDebugShowFrustumsCommand(
        scene,
        command,
        passState
      );
      return;
    }

    if (
      frameState.shadowState.lightShadowsEnabled &&
      command.receiveShadows &&
      defined(command.derivedCommands.shadows)
    ) {
      // If the command receives shadows, execute the derived shadows command.
      // Some commands, such as OIT derived commands, do not have derived shadow commands themselves
      // and instead shadowing is built-in. In this case execute the command regularly below.
      command.derivedCommands.shadows.receiveCommand.execute(context, passState);
    } else {
      command.execute(context, passState);
    }
  }

  function executeIdCommand(command, scene, context, passState) {
    const frameState = scene._frameState;
    let derivedCommands = command.derivedCommands;
    if (!defined(derivedCommands)) {
      return;
    }

    if (frameState.useLogDepth && defined(derivedCommands.logDepth)) {
      command = derivedCommands.logDepth.command;
    }

    derivedCommands = command.derivedCommands;
    if (defined(derivedCommands.picking)) {
      command = derivedCommands.picking.pickCommand;
      command.execute(context, passState);
    } else if (defined(derivedCommands.depth)) {
      command = derivedCommands.depth.depthOnlyCommand;
      command.execute(context, passState);
    }
  }

  function backToFront(a, b, position) {
    return (
      b.boundingVolume.distanceSquaredTo(position) -
      a.boundingVolume.distanceSquaredTo(position)
    );
  }

  function frontToBack(a, b, position) {
    // When distances are equal equal favor sorting b before a. This gives render priority to commands later in the list.
    return (
      a.boundingVolume.distanceSquaredTo(position) -
      b.boundingVolume.distanceSquaredTo(position) +
      CesiumMath.EPSILON12
    );
  }

  function executeTranslucentCommandsBackToFront(
    scene,
    executeFunction,
    passState,
    commands,
    invertClassification
  ) {
    const context = scene.context;

    mergeSort(commands, backToFront, scene.camera.positionWC);

    if (defined(invertClassification)) {
      executeFunction(
        invertClassification.unclassifiedCommand,
        scene,
        context,
        passState
      );
    }

    const length = commands.length;
    for (let i = 0; i < length; ++i) {
      executeFunction(commands[i], scene, context, passState);
    }
  }

  function executeTranslucentCommandsFrontToBack(
    scene,
    executeFunction,
    passState,
    commands,
    invertClassification
  ) {
    const context = scene.context;

    mergeSort(commands, frontToBack, scene.camera.positionWC);

    if (defined(invertClassification)) {
      executeFunction(
        invertClassification.unclassifiedCommand,
        scene,
        context,
        passState
      );
    }

    const length = commands.length;
    for (let i = 0; i < length; ++i) {
      executeFunction(commands[i], scene, context, passState);
    }
  }

  const scratchPerspectiveFrustum = new PerspectiveFrustum();
  const scratchPerspectiveOffCenterFrustum = new PerspectiveOffCenterFrustum();
  const scratchOrthographicFrustum = new OrthographicFrustum();
  const scratchOrthographicOffCenterFrustum = new OrthographicOffCenterFrustum();

  function executeCommands(scene, passState) {
    const camera = scene.camera;
    const context = scene.context;
    const frameState = scene.frameState;
    const us = context.uniformState;

    us.updateCamera(camera);

    // Create a working frustum from the original camera frustum.
    let frustum;
    if (defined(camera.frustum.fov)) {
      frustum = camera.frustum.clone(scratchPerspectiveFrustum);
    } else if (defined(camera.frustum.infiniteProjectionMatrix)) {
      frustum = camera.frustum.clone(scratchPerspectiveOffCenterFrustum);
    } else if (defined(camera.frustum.width)) {
      frustum = camera.frustum.clone(scratchOrthographicFrustum);
    } else {
      frustum = camera.frustum.clone(scratchOrthographicOffCenterFrustum);
    }

    // Ideally, we would render the sky box and atmosphere last for
    // early-z, but we would have to draw it in each frustum
    frustum.near = camera.frustum.near;
    frustum.far = camera.frustum.far;
    us.updateFrustum(frustum);
    us.updatePass(Pass$1.ENVIRONMENT);

    const passes = frameState.passes;
    const picking = passes.pick;
    const environmentState = scene._environmentState;
    const view = scene._view;
    const renderTranslucentDepthForPick =
      environmentState.renderTranslucentDepthForPick;
    const useWebVR = environmentState.useWebVR;

    // Do not render environment primitives during a pick pass since they do not generate picking commands.
    if (!picking) {
      const skyBoxCommand = environmentState.skyBoxCommand;
      if (defined(skyBoxCommand)) {
        executeCommand(skyBoxCommand, scene, context, passState);
      }

      if (environmentState.isSkyAtmosphereVisible) {
        executeCommand(
          environmentState.skyAtmosphereCommand,
          scene,
          context,
          passState
        );
      }

      if (environmentState.isSunVisible) {
        environmentState.sunDrawCommand.execute(context, passState);
        if (scene.sunBloom && !useWebVR) {
          let framebuffer;
          if (environmentState.useGlobeDepthFramebuffer) {
            framebuffer = view.globeDepth.framebuffer;
          } else if (environmentState.usePostProcess) {
            framebuffer = view.sceneFramebuffer.framebuffer;
          } else {
            framebuffer = environmentState.originalFramebuffer;
          }
          scene._sunPostProcess.execute(context);
          scene._sunPostProcess.copy(context, framebuffer);
          passState.framebuffer = framebuffer;
        }
      }

      // Moon can be seen through the atmosphere, since the sun is rendered after the atmosphere.
      if (environmentState.isMoonVisible) {
        environmentState.moonCommand.execute(context, passState);
      }
    }

    // Determine how translucent surfaces will be handled.
    let executeTranslucentCommands;
    if (environmentState.useOIT) {
      if (!defined(scene._executeOITFunction)) {
        scene._executeOITFunction = function (
          scene,
          executeFunction,
          passState,
          commands,
          invertClassification
        ) {
          view.globeDepth.prepareColorTextures(context);
          view.oit.executeCommands(
            scene,
            executeFunction,
            passState,
            commands,
            invertClassification
          );
        };
      }
      executeTranslucentCommands = scene._executeOITFunction;
    } else if (passes.render) {
      executeTranslucentCommands = executeTranslucentCommandsBackToFront;
    } else {
      executeTranslucentCommands = executeTranslucentCommandsFrontToBack;
    }

    const frustumCommandsList = view.frustumCommandsList;
    const numFrustums = frustumCommandsList.length;

    const clearGlobeDepth = environmentState.clearGlobeDepth;
    const useDepthPlane = environmentState.useDepthPlane;
    const globeTranslucencyState = scene._globeTranslucencyState;
    const globeTranslucent = globeTranslucencyState.translucent;
    const globeTranslucencyFramebuffer = scene._view.globeTranslucencyFramebuffer;
    const clearDepth = scene._depthClearCommand;
    const clearStencil = scene._stencilClearCommand;
    const clearClassificationStencil = scene._classificationStencilClearCommand;
    const depthPlane = scene._depthPlane;
    const usePostProcessSelected = environmentState.usePostProcessSelected;

    const height2D = camera.position.z;

    // Execute commands in each frustum in back to front order
    let j;
    for (let i = 0; i < numFrustums; ++i) {
      const index = numFrustums - i - 1;
      const frustumCommands = frustumCommandsList[index];

      if (scene.mode === SceneMode$1.SCENE2D) {
        // To avoid z-fighting in 2D, move the camera to just before the frustum
        // and scale the frustum depth to be in [1.0, nearToFarDistance2D].
        camera.position.z = height2D - frustumCommands.near + 1.0;
        frustum.far = Math.max(1.0, frustumCommands.far - frustumCommands.near);
        frustum.near = 1.0;
        us.update(frameState);
        us.updateFrustum(frustum);
      } else {
        // Avoid tearing artifacts between adjacent frustums in the opaque passes
        frustum.near =
          index !== 0
            ? frustumCommands.near * scene.opaqueFrustumNearOffset
            : frustumCommands.near;
        frustum.far = frustumCommands.far;
        us.updateFrustum(frustum);
      }

      clearDepth.execute(context, passState);

      if (context.stencilBuffer) {
        clearStencil.execute(context, passState);
      }

      us.updatePass(Pass$1.GLOBE);
      let commands = frustumCommands.commands[Pass$1.GLOBE];
      let length = frustumCommands.indices[Pass$1.GLOBE];

      if (globeTranslucent) {
        globeTranslucencyState.executeGlobeCommands(
          frustumCommands,
          executeCommand,
          globeTranslucencyFramebuffer,
          scene,
          passState
        );
      } else {
        for (j = 0; j < length; ++j) {
          executeCommand(commands[j], scene, context, passState);
        }
      }

      const globeDepth = view.globeDepth;
      if (defined(globeDepth) && environmentState.useGlobeDepthFramebuffer) {
        globeDepth.executeCopyDepth(context, passState);
      }

      // Draw terrain classification
      if (!environmentState.renderTranslucentDepthForPick) {
        us.updatePass(Pass$1.TERRAIN_CLASSIFICATION);
        commands = frustumCommands.commands[Pass$1.TERRAIN_CLASSIFICATION];
        length = frustumCommands.indices[Pass$1.TERRAIN_CLASSIFICATION];

        if (globeTranslucent) {
          globeTranslucencyState.executeGlobeClassificationCommands(
            frustumCommands,
            executeCommand,
            globeTranslucencyFramebuffer,
            scene,
            passState
          );
        } else {
          for (j = 0; j < length; ++j) {
            executeCommand(commands[j], scene, context, passState);
          }
        }
      }

      if (clearGlobeDepth) {
        clearDepth.execute(context, passState);
        if (useDepthPlane) {
          depthPlane.execute(context, passState);
        }
      }

      if (
        !environmentState.useInvertClassification ||
        picking ||
        environmentState.renderTranslucentDepthForPick
      ) {
        // Common/fastest path. Draw 3D Tiles and classification normally.

        // Draw 3D Tiles
        us.updatePass(Pass$1.CESIUM_3D_TILE);
        commands = frustumCommands.commands[Pass$1.CESIUM_3D_TILE];
        length = frustumCommands.indices[Pass$1.CESIUM_3D_TILE];
        for (j = 0; j < length; ++j) {
          executeCommand(commands[j], scene, context, passState);
        }

        if (length > 0) {
          if (defined(globeDepth) && environmentState.useGlobeDepthFramebuffer) {
            // When clearGlobeDepth is true, executeUpdateDepth needs
            // a globe depth texture with resolved stencil bits.
            globeDepth.prepareColorTextures(context, clearGlobeDepth);
            globeDepth.executeUpdateDepth(
              context,
              passState,
              clearGlobeDepth,
              globeDepth.depthStencilTexture
            );
          }

          // Draw classifications. Modifies 3D Tiles color.
          if (!environmentState.renderTranslucentDepthForPick) {
            us.updatePass(Pass$1.CESIUM_3D_TILE_CLASSIFICATION);
            commands =
              frustumCommands.commands[Pass$1.CESIUM_3D_TILE_CLASSIFICATION];
            length = frustumCommands.indices[Pass$1.CESIUM_3D_TILE_CLASSIFICATION];
            for (j = 0; j < length; ++j) {
              executeCommand(commands[j], scene, context, passState);
            }
          }
        }
      } else {
        // When the invert classification color is opaque:
        //    Main FBO (FBO1):                   Main_Color   + Main_DepthStencil
        //    Invert classification FBO (FBO2) : Invert_Color + Main_DepthStencil
        //
        //    1. Clear FBO2 color to vec4(0.0) for each frustum
        //    2. Draw 3D Tiles to FBO2
        //    3. Draw classification to FBO2
        //    4. Fullscreen pass to FBO1, draw Invert_Color when:
        //           * Main_DepthStencil has the stencil bit set > 0 (classified)
        //    5. Fullscreen pass to FBO1, draw Invert_Color * czm_invertClassificationColor when:
        //           * Main_DepthStencil has stencil bit set to 0 (unclassified) and
        //           * Invert_Color !== vec4(0.0)
        //
        // When the invert classification color is translucent:
        //    Main FBO (FBO1):                  Main_Color         + Main_DepthStencil
        //    Invert classification FBO (FBO2): Invert_Color       + Invert_DepthStencil
        //    IsClassified FBO (FBO3):          IsClassified_Color + Invert_DepthStencil
        //
        //    1. Clear FBO2 and FBO3 color to vec4(0.0), stencil to 0, and depth to 1.0
        //    2. Draw 3D Tiles to FBO2
        //    3. Draw classification to FBO2
        //    4. Fullscreen pass to FBO3, draw any color when
        //           * Invert_DepthStencil has the stencil bit set > 0 (classified)
        //    5. Fullscreen pass to FBO1, draw Invert_Color when:
        //           * Invert_Color !== vec4(0.0) and
        //           * IsClassified_Color !== vec4(0.0)
        //    6. Fullscreen pass to FBO1, draw Invert_Color * czm_invertClassificationColor when:
        //           * Invert_Color !== vec4(0.0) and
        //           * IsClassified_Color === vec4(0.0)
        //
        // NOTE: Step six when translucent invert color occurs after the TRANSLUCENT pass
        //
        scene._invertClassification.clear(context, passState);

        const opaqueClassificationFramebuffer = passState.framebuffer;
        passState.framebuffer = scene._invertClassification._fbo.framebuffer;

        // Draw normally
        us.updatePass(Pass$1.CESIUM_3D_TILE);
        commands = frustumCommands.commands[Pass$1.CESIUM_3D_TILE];
        length = frustumCommands.indices[Pass$1.CESIUM_3D_TILE];
        for (j = 0; j < length; ++j) {
          executeCommand(commands[j], scene, context, passState);
        }

        if (defined(globeDepth) && environmentState.useGlobeDepthFramebuffer) {
          scene._invertClassification.prepareTextures(context);
          globeDepth.executeUpdateDepth(
            context,
            passState,
            clearGlobeDepth,
            scene._invertClassification._fbo.getDepthStencilTexture()
          );
        }

        // Set stencil
        us.updatePass(Pass$1.CESIUM_3D_TILE_CLASSIFICATION_IGNORE_SHOW);
        commands =
          frustumCommands.commands[
            Pass$1.CESIUM_3D_TILE_CLASSIFICATION_IGNORE_SHOW
          ];
        length =
          frustumCommands.indices[Pass$1.CESIUM_3D_TILE_CLASSIFICATION_IGNORE_SHOW];
        for (j = 0; j < length; ++j) {
          executeCommand(commands[j], scene, context, passState);
        }

        passState.framebuffer = opaqueClassificationFramebuffer;

        // Fullscreen pass to copy classified fragments
        scene._invertClassification.executeClassified(context, passState);
        if (frameState.invertClassificationColor.alpha === 1.0) {
          // Fullscreen pass to copy unclassified fragments when alpha == 1.0
          scene._invertClassification.executeUnclassified(context, passState);
        }

        // Clear stencil set by the classification for the next classification pass
        if (length > 0 && context.stencilBuffer) {
          clearClassificationStencil.execute(context, passState);
        }

        // Draw style over classification.
        us.updatePass(Pass$1.CESIUM_3D_TILE_CLASSIFICATION);
        commands = frustumCommands.commands[Pass$1.CESIUM_3D_TILE_CLASSIFICATION];
        length = frustumCommands.indices[Pass$1.CESIUM_3D_TILE_CLASSIFICATION];
        for (j = 0; j < length; ++j) {
          executeCommand(commands[j], scene, context, passState);
        }
      }

      if (length > 0 && context.stencilBuffer) {
        clearStencil.execute(context, passState);
      }

      us.updatePass(Pass$1.OPAQUE);
      commands = frustumCommands.commands[Pass$1.OPAQUE];
      length = frustumCommands.indices[Pass$1.OPAQUE];
      for (j = 0; j < length; ++j) {
        executeCommand(commands[j], scene, context, passState);
      }

      if (index !== 0 && scene.mode !== SceneMode$1.SCENE2D) {
        // Do not overlap frustums in the translucent pass to avoid blending artifacts
        frustum.near = frustumCommands.near;
        us.updateFrustum(frustum);
      }

      let invertClassification;
      if (
        !picking &&
        environmentState.useInvertClassification &&
        frameState.invertClassificationColor.alpha < 1.0
      ) {
        // Fullscreen pass to copy unclassified fragments when alpha < 1.0.
        // Not executed when undefined.
        invertClassification = scene._invertClassification;
      }

      us.updatePass(Pass$1.TRANSLUCENT);
      commands = frustumCommands.commands[Pass$1.TRANSLUCENT];
      commands.length = frustumCommands.indices[Pass$1.TRANSLUCENT];
      executeTranslucentCommands(
        scene,
        executeCommand,
        passState,
        commands,
        invertClassification
      );

      // Classification for translucent 3D Tiles
      const has3DTilesClassificationCommands =
        frustumCommands.indices[Pass$1.CESIUM_3D_TILE_CLASSIFICATION] > 0;
      if (
        has3DTilesClassificationCommands &&
        view.translucentTileClassification.isSupported()
      ) {
        view.translucentTileClassification.executeTranslucentCommands(
          scene,
          executeCommand,
          passState,
          commands,
          globeDepth.depthStencilTexture
        );
        view.translucentTileClassification.executeClassificationCommands(
          scene,
          executeCommand,
          passState,
          frustumCommands
        );
      }

      if (
        context.depthTexture &&
        scene.useDepthPicking &&
        (environmentState.useGlobeDepthFramebuffer ||
          renderTranslucentDepthForPick)
      ) {
        // PERFORMANCE_IDEA: Use MRT to avoid the extra copy.
        const depthStencilTexture = globeDepth.depthStencilTexture;
        const pickDepth = scene._picking.getPickDepth(scene, index);
        pickDepth.update(context, depthStencilTexture);
        pickDepth.executeCopyDepth(context, passState);
      }

      if (picking || !usePostProcessSelected) {
        continue;
      }

      const originalFramebuffer = passState.framebuffer;
      passState.framebuffer = view.sceneFramebuffer.getIdFramebuffer();

      // reset frustum
      frustum.near =
        index !== 0
          ? frustumCommands.near * scene.opaqueFrustumNearOffset
          : frustumCommands.near;
      frustum.far = frustumCommands.far;
      us.updateFrustum(frustum);

      us.updatePass(Pass$1.GLOBE);
      commands = frustumCommands.commands[Pass$1.GLOBE];
      length = frustumCommands.indices[Pass$1.GLOBE];

      if (globeTranslucent) {
        globeTranslucencyState.executeGlobeCommands(
          frustumCommands,
          executeIdCommand,
          globeTranslucencyFramebuffer,
          scene,
          passState
        );
      } else {
        for (j = 0; j < length; ++j) {
          executeIdCommand(commands[j], scene, context, passState);
        }
      }

      if (clearGlobeDepth) {
        clearDepth.framebuffer = passState.framebuffer;
        clearDepth.execute(context, passState);
        clearDepth.framebuffer = undefined;
      }

      if (clearGlobeDepth && useDepthPlane) {
        depthPlane.execute(context, passState);
      }

      us.updatePass(Pass$1.CESIUM_3D_TILE);
      commands = frustumCommands.commands[Pass$1.CESIUM_3D_TILE];
      length = frustumCommands.indices[Pass$1.CESIUM_3D_TILE];
      for (j = 0; j < length; ++j) {
        executeIdCommand(commands[j], scene, context, passState);
      }

      us.updatePass(Pass$1.OPAQUE);
      commands = frustumCommands.commands[Pass$1.OPAQUE];
      length = frustumCommands.indices[Pass$1.OPAQUE];
      for (j = 0; j < length; ++j) {
        executeIdCommand(commands[j], scene, context, passState);
      }

      us.updatePass(Pass$1.TRANSLUCENT);
      commands = frustumCommands.commands[Pass$1.TRANSLUCENT];
      length = frustumCommands.indices[Pass$1.TRANSLUCENT];
      for (j = 0; j < length; ++j) {
        executeIdCommand(commands[j], scene, context, passState);
      }

      passState.framebuffer = originalFramebuffer;
    }
  }

  function executeComputeCommands(scene) {
    const us = scene.context.uniformState;
    us.updatePass(Pass$1.COMPUTE);

    const sunComputeCommand = scene._environmentState.sunComputeCommand;
    if (defined(sunComputeCommand)) {
      sunComputeCommand.execute(scene._computeEngine);
    }

    const commandList = scene._computeCommandList;
    const length = commandList.length;
    for (let i = 0; i < length; ++i) {
      commandList[i].execute(scene._computeEngine);
    }
  }

  function executeOverlayCommands(scene, passState) {
    const us = scene.context.uniformState;
    us.updatePass(Pass$1.OVERLAY);

    const context = scene.context;
    const commandList = scene._overlayCommandList;
    const length = commandList.length;
    for (let i = 0; i < length; ++i) {
      commandList[i].execute(context, passState);
    }
  }

  function insertShadowCastCommands(scene, commandList, shadowMap) {
    const shadowVolume = shadowMap.shadowMapCullingVolume;
    const isPointLight = shadowMap.isPointLight;
    const passes = shadowMap.passes;
    const numberOfPasses = passes.length;

    const length = commandList.length;
    for (let i = 0; i < length; ++i) {
      const command = commandList[i];
      scene.updateDerivedCommands(command);

      if (
        command.castShadows &&
        (command.pass === Pass$1.GLOBE ||
          command.pass === Pass$1.CESIUM_3D_TILE ||
          command.pass === Pass$1.OPAQUE ||
          command.pass === Pass$1.TRANSLUCENT)
      ) {
        if (scene.isVisible(command, shadowVolume)) {
          if (isPointLight) {
            for (let k = 0; k < numberOfPasses; ++k) {
              passes[k].commandList.push(command);
            }
          } else if (numberOfPasses === 1) {
            passes[0].commandList.push(command);
          } else {
            let wasVisible = false;
            // Loop over cascades from largest to smallest
            for (let j = numberOfPasses - 1; j >= 0; --j) {
              const cascadeVolume = passes[j].cullingVolume;
              if (scene.isVisible(command, cascadeVolume)) {
                passes[j].commandList.push(command);
                wasVisible = true;
              } else if (wasVisible) {
                // If it was visible in the previous cascade but now isn't
                // then there is no need to check any more cascades
                break;
              }
            }
          }
        }
      }
    }
  }

  function executeShadowMapCastCommands(scene) {
    const frameState = scene.frameState;
    const shadowMaps = frameState.shadowState.shadowMaps;
    const shadowMapLength = shadowMaps.length;

    if (!frameState.shadowState.shadowsEnabled) {
      return;
    }

    const context = scene.context;
    const uniformState = context.uniformState;

    for (let i = 0; i < shadowMapLength; ++i) {
      const shadowMap = shadowMaps[i];
      if (shadowMap.outOfView) {
        continue;
      }

      // Reset the command lists
      const passes = shadowMap.passes;
      const numberOfPasses = passes.length;
      for (let j = 0; j < numberOfPasses; ++j) {
        passes[j].commandList.length = 0;
      }

      // Insert the primitive/model commands into the command lists
      const sceneCommands = scene.frameState.commandList;
      insertShadowCastCommands(scene, sceneCommands, shadowMap);

      for (let j = 0; j < numberOfPasses; ++j) {
        const pass = shadowMap.passes[j];
        uniformState.updateCamera(pass.camera);
        shadowMap.updatePass(context, j);
        const numberOfCommands = pass.commandList.length;
        for (let k = 0; k < numberOfCommands; ++k) {
          const command = pass.commandList[k];
          // Set the correct pass before rendering into the shadow map because some shaders
          // conditionally render based on whether the pass is translucent or opaque.
          uniformState.updatePass(command.pass);
          executeCommand(
            command.derivedCommands.shadows.castCommands[i],
            scene,
            context,
            pass.passState
          );
        }
      }
    }
  }

  const scratchEyeTranslation = new Cartesian3();

  /**
   * @private
   */
  Scene.prototype.updateAndExecuteCommands = function (
    passState,
    backgroundColor
  ) {
    const frameState = this._frameState;
    const mode = frameState.mode;
    const useWebVR = this._environmentState.useWebVR;

    if (useWebVR) {
      executeWebVRCommands(this, passState, backgroundColor);
    } else if (
      mode !== SceneMode$1.SCENE2D ||
      this._mapMode2D === MapMode2D$1.ROTATE
    ) {
      executeCommandsInViewport(true, this, passState, backgroundColor);
    } else {
      updateAndClearFramebuffers(this, passState, backgroundColor);
      execute2DViewportCommands(this, passState);
    }
  };

  function executeWebVRCommands(scene, passState, backgroundColor) {
    const view = scene._view;
    const camera = view.camera;
    const environmentState = scene._environmentState;
    const renderTranslucentDepthForPick =
      environmentState.renderTranslucentDepthForPick;

    updateAndClearFramebuffers(scene, passState, backgroundColor);

    updateAndRenderPrimitives(scene);

    view.createPotentiallyVisibleSet(scene);

    executeComputeCommands(scene);

    if (!renderTranslucentDepthForPick) {
      executeShadowMapCastCommands(scene);
    }

    // Based on Calculating Stereo pairs by Paul Bourke
    // http://paulbourke.net/stereographics/stereorender/
    const viewport = passState.viewport;
    viewport.x = 0;
    viewport.y = 0;
    viewport.width = viewport.width * 0.5;

    const savedCamera = Camera.clone(camera, scene._cameraVR);
    savedCamera.frustum = camera.frustum;

    const near = camera.frustum.near;
    const fo = near * defaultValue(scene.focalLength, 5.0);
    const eyeSeparation = defaultValue(scene.eyeSeparation, fo / 30.0);
    const eyeTranslation = Cartesian3.multiplyByScalar(
      savedCamera.right,
      eyeSeparation * 0.5,
      scratchEyeTranslation
    );

    camera.frustum.aspectRatio = viewport.width / viewport.height;

    const offset = (0.5 * eyeSeparation * near) / fo;

    Cartesian3.add(savedCamera.position, eyeTranslation, camera.position);
    camera.frustum.xOffset = offset;

    executeCommands(scene, passState);

    viewport.x = viewport.width;

    Cartesian3.subtract(savedCamera.position, eyeTranslation, camera.position);
    camera.frustum.xOffset = -offset;

    executeCommands(scene, passState);

    Camera.clone(savedCamera, camera);
  }

  const scratch2DViewportCartographic = new Cartographic(
    Math.PI,
    CesiumMath.PI_OVER_TWO
  );
  const scratch2DViewportMaxCoord = new Cartesian3();
  const scratch2DViewportSavedPosition = new Cartesian3();
  const scratch2DViewportTransform = new Matrix4();
  const scratch2DViewportCameraTransform = new Matrix4();
  const scratch2DViewportEyePoint = new Cartesian3();
  const scratch2DViewportWindowCoords = new Cartesian3();
  const scratch2DViewport = new BoundingRectangle();

  function execute2DViewportCommands(scene, passState) {
    const context = scene.context;
    const frameState = scene.frameState;
    const camera = scene.camera;

    const originalViewport = passState.viewport;
    const viewport = BoundingRectangle.clone(originalViewport, scratch2DViewport);
    passState.viewport = viewport;

    const maxCartographic = scratch2DViewportCartographic;
    const maxCoord = scratch2DViewportMaxCoord;

    const projection = scene.mapProjection;
    projection.project(maxCartographic, maxCoord);

    const position = Cartesian3.clone(
      camera.position,
      scratch2DViewportSavedPosition
    );
    const transform = Matrix4.clone(
      camera.transform,
      scratch2DViewportCameraTransform
    );
    const frustum = camera.frustum.clone();

    camera._setTransform(Matrix4.IDENTITY);

    const viewportTransformation = Matrix4.computeViewportTransformation(
      viewport,
      0.0,
      1.0,
      scratch2DViewportTransform
    );
    const projectionMatrix = camera.frustum.projectionMatrix;

    const x = camera.positionWC.y;
    const eyePoint = Cartesian3.fromElements(
      CesiumMath.sign(x) * maxCoord.x - x,
      0.0,
      -camera.positionWC.x,
      scratch2DViewportEyePoint
    );
    const windowCoordinates = Transforms.pointToGLWindowCoordinates(
      projectionMatrix,
      viewportTransformation,
      eyePoint,
      scratch2DViewportWindowCoords
    );

    windowCoordinates.x = Math.floor(windowCoordinates.x);

    const viewportX = viewport.x;
    const viewportWidth = viewport.width;

    if (
      x === 0.0 ||
      windowCoordinates.x <= viewportX ||
      windowCoordinates.x >= viewportX + viewportWidth
    ) {
      executeCommandsInViewport(true, scene, passState);
    } else if (
      Math.abs(viewportX + viewportWidth * 0.5 - windowCoordinates.x) < 1.0
    ) {
      viewport.width = windowCoordinates.x - viewport.x;

      camera.position.x *= CesiumMath.sign(camera.position.x);

      camera.frustum.right = 0.0;

      frameState.cullingVolume = camera.frustum.computeCullingVolume(
        camera.positionWC,
        camera.directionWC,
        camera.upWC
      );
      context.uniformState.update(frameState);

      executeCommandsInViewport(true, scene, passState);

      viewport.x = windowCoordinates.x;

      camera.position.x = -camera.position.x;

      camera.frustum.right = -camera.frustum.left;
      camera.frustum.left = 0.0;

      frameState.cullingVolume = camera.frustum.computeCullingVolume(
        camera.positionWC,
        camera.directionWC,
        camera.upWC
      );
      context.uniformState.update(frameState);

      executeCommandsInViewport(false, scene, passState);
    } else if (windowCoordinates.x > viewportX + viewportWidth * 0.5) {
      viewport.width = windowCoordinates.x - viewportX;

      const right = camera.frustum.right;
      camera.frustum.right = maxCoord.x - x;

      frameState.cullingVolume = camera.frustum.computeCullingVolume(
        camera.positionWC,
        camera.directionWC,
        camera.upWC
      );
      context.uniformState.update(frameState);

      executeCommandsInViewport(true, scene, passState);

      viewport.x = windowCoordinates.x;
      viewport.width = viewportX + viewportWidth - windowCoordinates.x;

      camera.position.x = -camera.position.x;

      camera.frustum.left = -camera.frustum.right;
      camera.frustum.right = right - camera.frustum.right * 2.0;

      frameState.cullingVolume = camera.frustum.computeCullingVolume(
        camera.positionWC,
        camera.directionWC,
        camera.upWC
      );
      context.uniformState.update(frameState);

      executeCommandsInViewport(false, scene, passState);
    } else {
      viewport.x = windowCoordinates.x;
      viewport.width = viewportX + viewportWidth - windowCoordinates.x;

      const left = camera.frustum.left;
      camera.frustum.left = -maxCoord.x - x;

      frameState.cullingVolume = camera.frustum.computeCullingVolume(
        camera.positionWC,
        camera.directionWC,
        camera.upWC
      );
      context.uniformState.update(frameState);

      executeCommandsInViewport(true, scene, passState);

      viewport.x = viewportX;
      viewport.width = windowCoordinates.x - viewportX;

      camera.position.x = -camera.position.x;

      camera.frustum.right = -camera.frustum.left;
      camera.frustum.left = left - camera.frustum.left * 2.0;

      frameState.cullingVolume = camera.frustum.computeCullingVolume(
        camera.positionWC,
        camera.directionWC,
        camera.upWC
      );
      context.uniformState.update(frameState);

      executeCommandsInViewport(false, scene, passState);
    }

    camera._setTransform(transform);
    Cartesian3.clone(position, camera.position);
    camera.frustum = frustum.clone();
    passState.viewport = originalViewport;
  }

  function executeCommandsInViewport(
    firstViewport,
    scene,
    passState,
    backgroundColor
  ) {
    const environmentState = scene._environmentState;
    const view = scene._view;
    const renderTranslucentDepthForPick =
      environmentState.renderTranslucentDepthForPick;

    if (!firstViewport) {
      scene.frameState.commandList.length = 0;
    }

    updateAndRenderPrimitives(scene);

    view.createPotentiallyVisibleSet(scene);

    if (firstViewport) {
      if (defined(backgroundColor)) {
        updateAndClearFramebuffers(scene, passState, backgroundColor);
      }
      executeComputeCommands(scene);
      if (!renderTranslucentDepthForPick) {
        executeShadowMapCastCommands(scene);
      }
    }

    executeCommands(scene, passState);
  }

  const scratchCullingVolume = new CullingVolume();

  /**
   * @private
   */
  Scene.prototype.updateEnvironment = function () {
    const frameState = this._frameState;
    const view = this._view;

    // Update celestial and terrestrial environment effects.
    const environmentState = this._environmentState;
    const renderPass = frameState.passes.render;
    const offscreenPass = frameState.passes.offscreen;
    const skyAtmosphere = this.skyAtmosphere;
    const globe = this.globe;
    const globeTranslucencyState = this._globeTranslucencyState;

    if (
      !renderPass ||
      (this._mode !== SceneMode$1.SCENE2D &&
        view.camera.frustum instanceof OrthographicFrustum) ||
      !globeTranslucencyState.environmentVisible
    ) {
      environmentState.skyAtmosphereCommand = undefined;
      environmentState.skyBoxCommand = undefined;
      environmentState.sunDrawCommand = undefined;
      environmentState.sunComputeCommand = undefined;
      environmentState.moonCommand = undefined;
    } else {
      if (defined(skyAtmosphere)) {
        if (defined(globe)) {
          skyAtmosphere.setDynamicAtmosphereColor(
            globe.enableLighting && globe.dynamicAtmosphereLighting,
            globe.dynamicAtmosphereLightingFromSun
          );
          environmentState.isReadyForAtmosphere =
            environmentState.isReadyForAtmosphere ||
            globe._surface._tilesToRender.length > 0;
        }
        environmentState.skyAtmosphereCommand = skyAtmosphere.update(
          frameState,
          globe
        );
        if (defined(environmentState.skyAtmosphereCommand)) {
          this.updateDerivedCommands(environmentState.skyAtmosphereCommand);
        }
      } else {
        environmentState.skyAtmosphereCommand = undefined;
      }

      environmentState.skyBoxCommand = defined(this.skyBox)
        ? this.skyBox.update(frameState, this._hdr)
        : undefined;
      const sunCommands = defined(this.sun)
        ? this.sun.update(frameState, view.passState, this._hdr)
        : undefined;
      environmentState.sunDrawCommand = defined(sunCommands)
        ? sunCommands.drawCommand
        : undefined;
      environmentState.sunComputeCommand = defined(sunCommands)
        ? sunCommands.computeCommand
        : undefined;
      environmentState.moonCommand = defined(this.moon)
        ? this.moon.update(frameState)
        : undefined;
    }

    const clearGlobeDepth = (environmentState.clearGlobeDepth =
      defined(globe) &&
      globe.show &&
      (!globe.depthTestAgainstTerrain || this.mode === SceneMode$1.SCENE2D));
    const useDepthPlane = (environmentState.useDepthPlane =
      clearGlobeDepth &&
      this.mode === SceneMode$1.SCENE3D &&
      globeTranslucencyState.useDepthPlane);
    if (useDepthPlane) {
      // Update the depth plane that is rendered in 3D when the primitives are
      // not depth tested against terrain so primitives on the backface
      // of the globe are not picked.
      this._depthPlane.update(frameState);
    }

    environmentState.renderTranslucentDepthForPick = false;
    environmentState.useWebVR =
      this._useWebVR && this.mode !== SceneMode$1.SCENE2D && !offscreenPass;

    const occluder =
      frameState.mode === SceneMode$1.SCENE3D &&
      !globeTranslucencyState.sunVisibleThroughGlobe
        ? frameState.occluder
        : undefined;
    let cullingVolume = frameState.cullingVolume;

    // get user culling volume minus the far plane.
    const planes = scratchCullingVolume.planes;
    for (let k = 0; k < 5; ++k) {
      planes[k] = cullingVolume.planes[k];
    }
    cullingVolume = scratchCullingVolume;

    // Determine visibility of celestial and terrestrial environment effects.
    environmentState.isSkyAtmosphereVisible =
      defined(environmentState.skyAtmosphereCommand) &&
      environmentState.isReadyForAtmosphere;
    environmentState.isSunVisible = this.isVisible(
      environmentState.sunDrawCommand,
      cullingVolume,
      occluder
    );
    environmentState.isMoonVisible = this.isVisible(
      environmentState.moonCommand,
      cullingVolume,
      occluder
    );

    const envMaps = this.specularEnvironmentMaps;
    let envMapAtlas = this._specularEnvironmentMapAtlas;
    if (
      defined(envMaps) &&
      (!defined(envMapAtlas) || envMapAtlas.url !== envMaps)
    ) {
      envMapAtlas = envMapAtlas && envMapAtlas.destroy();
      this._specularEnvironmentMapAtlas = new OctahedralProjectedCubeMap(envMaps);
    } else if (!defined(envMaps) && defined(envMapAtlas)) {
      envMapAtlas.destroy();
      this._specularEnvironmentMapAtlas = undefined;
    }

    if (defined(this._specularEnvironmentMapAtlas)) {
      this._specularEnvironmentMapAtlas.update(frameState);
    }
  };

  function updateDebugFrustumPlanes(scene) {
    const frameState = scene._frameState;
    if (scene.debugShowFrustumPlanes !== scene._debugShowFrustumPlanes) {
      if (scene.debugShowFrustumPlanes) {
        scene._debugFrustumPlanes = new DebugCameraPrimitive({
          camera: scene.camera,
          updateOnChange: false,
          frustumSplits: frameState.frustumSplits,
        });
      } else {
        scene._debugFrustumPlanes =
          scene._debugFrustumPlanes && scene._debugFrustumPlanes.destroy();
      }
      scene._debugShowFrustumPlanes = scene.debugShowFrustumPlanes;
    }

    if (defined(scene._debugFrustumPlanes)) {
      scene._debugFrustumPlanes.update(frameState);
    }
  }

  function updateShadowMaps(scene) {
    const frameState = scene._frameState;
    const shadowMaps = frameState.shadowMaps;
    const length = shadowMaps.length;

    const shadowsEnabled =
      length > 0 && !frameState.passes.pick && scene.mode === SceneMode$1.SCENE3D;
    if (shadowsEnabled !== frameState.shadowState.shadowsEnabled) {
      // Update derived commands when shadowsEnabled changes
      ++frameState.shadowState.lastDirtyTime;
      frameState.shadowState.shadowsEnabled = shadowsEnabled;
    }

    frameState.shadowState.lightShadowsEnabled = false;

    if (!shadowsEnabled) {
      return;
    }

    // Check if the shadow maps are different than the shadow maps last frame.
    // If so, the derived commands need to be updated.
    for (let j = 0; j < length; ++j) {
      if (shadowMaps[j] !== frameState.shadowState.shadowMaps[j]) {
        ++frameState.shadowState.lastDirtyTime;
        break;
      }
    }

    frameState.shadowState.shadowMaps.length = 0;
    frameState.shadowState.lightShadowMaps.length = 0;

    for (let i = 0; i < length; ++i) {
      const shadowMap = shadowMaps[i];
      shadowMap.update(frameState);

      frameState.shadowState.shadowMaps.push(shadowMap);

      if (shadowMap.fromLightSource) {
        frameState.shadowState.lightShadowMaps.push(shadowMap);
        frameState.shadowState.lightShadowsEnabled = true;
      }

      if (shadowMap.dirty) {
        ++frameState.shadowState.lastDirtyTime;
        shadowMap.dirty = false;
      }
    }
  }

  function updateAndRenderPrimitives(scene) {
    const frameState = scene._frameState;

    scene._groundPrimitives.update(frameState);
    scene._primitives.update(frameState);

    updateDebugFrustumPlanes(scene);
    updateShadowMaps(scene);

    if (scene._globe) {
      scene._globe.render(frameState);
    }
  }

  function updateAndClearFramebuffers(scene, passState, clearColor) {
    const context = scene._context;
    const frameState = scene._frameState;
    const environmentState = scene._environmentState;
    const view = scene._view;

    const passes = scene._frameState.passes;
    const picking = passes.pick;
    if (defined(view.globeDepth)) {
      view.globeDepth.picking = picking;
    }
    const useWebVR = environmentState.useWebVR;

    // Preserve the reference to the original framebuffer.
    environmentState.originalFramebuffer = passState.framebuffer;

    // Manage sun bloom post-processing effect.
    if (defined(scene.sun) && scene.sunBloom !== scene._sunBloom) {
      if (scene.sunBloom && !useWebVR) {
        scene._sunPostProcess = new SunPostProcess();
      } else if (defined(scene._sunPostProcess)) {
        scene._sunPostProcess = scene._sunPostProcess.destroy();
      }

      scene._sunBloom = scene.sunBloom;
    } else if (!defined(scene.sun) && defined(scene._sunPostProcess)) {
      scene._sunPostProcess = scene._sunPostProcess.destroy();
      scene._sunBloom = false;
    }

    // Clear the pass state framebuffer.
    const clear = scene._clearColorCommand;
    Color.clone(clearColor, clear.color);
    clear.execute(context, passState);

    // Update globe depth rendering based on the current context and clear the globe depth framebuffer.
    // Globe depth is copied for the pick pass to support picking batched geometries in GroundPrimitives.
    const useGlobeDepthFramebuffer = (environmentState.useGlobeDepthFramebuffer = defined(
      view.globeDepth
    ));
    if (useGlobeDepthFramebuffer) {
      view.globeDepth.update(
        context,
        passState,
        view.viewport,
        scene.msaaSamples,
        scene._hdr,
        environmentState.clearGlobeDepth
      );
      view.globeDepth.clear(context, passState, clearColor);
    }

    // If supported, configure OIT to use the globe depth framebuffer and clear the OIT framebuffer.
    const oit = view.oit;
    const useOIT = (environmentState.useOIT =
      !picking && defined(oit) && oit.isSupported());
    if (useOIT) {
      oit.update(
        context,
        passState,
        view.globeDepth.colorFramebufferManager,
        scene._hdr,
        scene.msaaSamples
      );
      oit.clear(context, passState, clearColor);
      environmentState.useOIT = oit.isSupported();
    }

    const postProcess = scene.postProcessStages;
    let usePostProcess = (environmentState.usePostProcess =
      !picking &&
      (scene._hdr ||
        postProcess.length > 0 ||
        postProcess.ambientOcclusion.enabled ||
        postProcess.fxaa.enabled ||
        postProcess.bloom.enabled));
    environmentState.usePostProcessSelected = false;
    if (usePostProcess) {
      view.sceneFramebuffer.update(
        context,
        view.viewport,
        scene._hdr,
        scene.msaaSamples
      );
      view.sceneFramebuffer.clear(context, passState, clearColor);

      postProcess.update(context, frameState.useLogDepth, scene._hdr);
      postProcess.clear(context);

      usePostProcess = environmentState.usePostProcess = postProcess.ready;
      environmentState.usePostProcessSelected =
        usePostProcess && postProcess.hasSelected;
    }

    if (environmentState.isSunVisible && scene.sunBloom && !useWebVR) {
      passState.framebuffer = scene._sunPostProcess.update(passState);
      scene._sunPostProcess.clear(context, passState, clearColor);
    } else if (useGlobeDepthFramebuffer) {
      passState.framebuffer = view.globeDepth.framebuffer;
    } else if (usePostProcess) {
      passState.framebuffer = view.sceneFramebuffer.framebuffer;
    }

    if (defined(passState.framebuffer)) {
      clear.execute(context, passState);
    }

    const useInvertClassification = (environmentState.useInvertClassification =
      !picking && defined(passState.framebuffer) && scene.invertClassification);
    if (useInvertClassification) {
      let depthFramebuffer;
      if (scene.frameState.invertClassificationColor.alpha === 1.0) {
        if (environmentState.useGlobeDepthFramebuffer) {
          depthFramebuffer = view.globeDepth.framebuffer;
        }
      }

      if (defined(depthFramebuffer) || context.depthTexture) {
        scene._invertClassification.previousFramebuffer = depthFramebuffer;
        scene._invertClassification.update(
          context,
          scene.msaaSamples,
          view.globeDepth.colorFramebufferManager
        );
        scene._invertClassification.clear(context, passState);

        if (scene.frameState.invertClassificationColor.alpha < 1.0 && useOIT) {
          const command = scene._invertClassification.unclassifiedCommand;
          const derivedCommands = command.derivedCommands;
          derivedCommands.oit = oit.createDerivedCommands(
            command,
            context,
            derivedCommands.oit
          );
        }
      } else {
        environmentState.useInvertClassification = false;
      }
    }

    if (scene._globeTranslucencyState.translucent) {
      view.globeTranslucencyFramebuffer.updateAndClear(
        scene._hdr,
        view.viewport,
        context,
        passState
      );
    }
  }

  /**
   * @private
   */
  Scene.prototype.resolveFramebuffers = function (passState) {
    const context = this._context;
    const environmentState = this._environmentState;
    const view = this._view;
    const globeDepth = view.globeDepth;
    if (defined(globeDepth)) {
      globeDepth.prepareColorTextures(context);
    }

    const useOIT = environmentState.useOIT;
    const useGlobeDepthFramebuffer = environmentState.useGlobeDepthFramebuffer;
    const usePostProcess = environmentState.usePostProcess;

    const defaultFramebuffer = environmentState.originalFramebuffer;
    const globeFramebuffer = useGlobeDepthFramebuffer
      ? globeDepth.colorFramebufferManager
      : undefined;
    const sceneFramebuffer = view.sceneFramebuffer._colorFramebuffer;
    const idFramebuffer = view.sceneFramebuffer.idFramebuffer;

    if (useOIT) {
      passState.framebuffer = usePostProcess
        ? sceneFramebuffer.framebuffer
        : defaultFramebuffer;
      view.oit.execute(context, passState);
    }

    const translucentTileClassification = view.translucentTileClassification;
    if (
      translucentTileClassification.hasTranslucentDepth &&
      translucentTileClassification.isSupported()
    ) {
      translucentTileClassification.execute(this, passState);
    }

    if (usePostProcess) {
      view.sceneFramebuffer.prepareColorTextures(context);
      let inputFramebuffer = sceneFramebuffer;
      if (useGlobeDepthFramebuffer && !useOIT) {
        inputFramebuffer = globeFramebuffer;
      }

      const postProcess = this.postProcessStages;
      const colorTexture = inputFramebuffer.getColorTexture(0);
      const idTexture = idFramebuffer.getColorTexture(0);
      const depthTexture = defaultValue(
        globeFramebuffer,
        sceneFramebuffer
      ).getDepthStencilTexture();
      postProcess.execute(context, colorTexture, depthTexture, idTexture);
      postProcess.copy(context, defaultFramebuffer);
    }

    if (!useOIT && !usePostProcess && useGlobeDepthFramebuffer) {
      passState.framebuffer = defaultFramebuffer;
      globeDepth.executeCopyColor(context, passState);
    }
  };

  function callAfterRenderFunctions(scene) {
    // Functions are queued up during primitive update and executed here in case
    // the function modifies scene state that should remain constant over the frame.
    const functions = scene._frameState.afterRender;
    for (let i = 0, length = functions.length; i < length; ++i) {
      functions[i]();
      scene.requestRender();
    }

    functions.length = 0;
  }

  function getGlobeHeight(scene) {
    const globe = scene._globe;
    const camera = scene.camera;
    const cartographic = camera.positionCartographic;
    if (defined(globe) && globe.show && defined(cartographic)) {
      return globe.getHeight(cartographic);
    }
    return undefined;
  }

  function isCameraUnderground(scene) {
    const camera = scene.camera;
    const mode = scene._mode;
    const globe = scene.globe;
    const cameraController = scene._screenSpaceCameraController;
    const cartographic = camera.positionCartographic;

    if (!defined(cartographic)) {
      return false;
    }

    if (!cameraController.onMap() && cartographic.height < 0.0) {
      // The camera can go off the map while in Columbus View.
      // Make a best guess as to whether it's underground by checking if its height is less than zero.
      return true;
    }

    if (
      !defined(globe) ||
      !globe.show ||
      mode === SceneMode$1.SCENE2D ||
      mode === SceneMode$1.MORPHING
    ) {
      return false;
    }

    const globeHeight = scene._globeHeight;
    return defined(globeHeight) && cartographic.height < globeHeight;
  }

  /**
   * @private
   */
  Scene.prototype.initializeFrame = function () {
    // Destroy released shaders and textures once every 120 frames to avoid thrashing the cache
    if (this._shaderFrameCount++ === 120) {
      this._shaderFrameCount = 0;
      this._context.shaderCache.destroyReleasedShaderPrograms();
      this._context.textureCache.destroyReleasedTextures();
    }

    this._tweens.update();

    this._globeHeight = getGlobeHeight(this);
    this._cameraUnderground = isCameraUnderground(this);
    this._globeTranslucencyState.update(this);

    this._screenSpaceCameraController.update();
    if (defined(this._deviceOrientationCameraController)) {
      this._deviceOrientationCameraController.update();
    }

    this.camera.update(this._mode);
    this.camera._updateCameraChanged();
  };

  function updateDebugShowFramesPerSecond(scene, renderedThisFrame) {
    if (scene.debugShowFramesPerSecond) {
      if (!defined(scene._performanceDisplay)) {
        const performanceContainer = document.createElement("div");
        performanceContainer.className =
          "cesium-performanceDisplay-defaultContainer";
        const container = scene._canvas.parentNode;
        container.appendChild(performanceContainer);
        const performanceDisplay = new PerformanceDisplay({
          container: performanceContainer,
        });
        scene._performanceDisplay = performanceDisplay;
        scene._performanceContainer = performanceContainer;
      }

      scene._performanceDisplay.throttled = scene.requestRenderMode;
      scene._performanceDisplay.update(renderedThisFrame);
    } else if (defined(scene._performanceDisplay)) {
      scene._performanceDisplay =
        scene._performanceDisplay && scene._performanceDisplay.destroy();
      scene._performanceContainer.parentNode.removeChild(
        scene._performanceContainer
      );
    }
  }

  function prePassesUpdate(scene) {
    scene._jobScheduler.resetBudgets();

    const frameState = scene._frameState;
    const primitives = scene.primitives;
    primitives.prePassesUpdate(frameState);

    if (defined(scene.globe)) {
      scene.globe.update(frameState);
    }

    scene._picking.update();
    frameState.creditDisplay.update();
  }

  function postPassesUpdate(scene) {
    const frameState = scene._frameState;
    const primitives = scene.primitives;
    primitives.postPassesUpdate(frameState);

    RequestScheduler.update();
  }

  const scratchBackgroundColor = new Color();

  function render(scene) {
    const frameState = scene._frameState;

    const context = scene.context;
    const us = context.uniformState;

    const view = scene._defaultView;
    scene._view = view;

    scene.updateFrameState();
    frameState.passes.render = true;
    frameState.passes.postProcess = scene.postProcessStages.hasSelected;
    frameState.tilesetPassState = renderTilesetPassState;

    let backgroundColor = defaultValue(scene.backgroundColor, Color.BLACK);
    if (scene._hdr) {
      backgroundColor = Color.clone(backgroundColor, scratchBackgroundColor);
      backgroundColor.red = Math.pow(backgroundColor.red, scene.gamma);
      backgroundColor.green = Math.pow(backgroundColor.green, scene.gamma);
      backgroundColor.blue = Math.pow(backgroundColor.blue, scene.gamma);
    }
    frameState.backgroundColor = backgroundColor;

    scene.fog.update(frameState);

    us.update(frameState);

    const shadowMap = scene.shadowMap;
    if (defined(shadowMap) && shadowMap.enabled) {
      if (!defined(scene.light) || scene.light instanceof SunLight) {
        // Negate the sun direction so that it is from the Sun, not to the Sun
        Cartesian3.negate(us.sunDirectionWC, scene._shadowMapCamera.direction);
      } else {
        Cartesian3.clone(scene.light.direction, scene._shadowMapCamera.direction);
      }
      frameState.shadowMaps.push(shadowMap);
    }

    scene._computeCommandList.length = 0;
    scene._overlayCommandList.length = 0;

    const viewport = view.viewport;
    viewport.x = 0;
    viewport.y = 0;
    viewport.width = context.drawingBufferWidth;
    viewport.height = context.drawingBufferHeight;

    const passState = view.passState;
    passState.framebuffer = undefined;
    passState.blendingEnabled = undefined;
    passState.scissorTest = undefined;
    passState.viewport = BoundingRectangle.clone(viewport, passState.viewport);

    if (defined(scene.globe)) {
      scene.globe.beginFrame(frameState);
    }

    scene.updateEnvironment();
    scene.updateAndExecuteCommands(passState, backgroundColor);
    scene.resolveFramebuffers(passState);

    passState.framebuffer = undefined;
    executeOverlayCommands(scene, passState);

    if (defined(scene.globe)) {
      scene.globe.endFrame(frameState);

      if (!scene.globe.tilesLoaded) {
        scene._renderRequested = true;
      }
    }

    context.endFrame();
  }

  function tryAndCatchError(scene, functionToExecute) {
    try {
      functionToExecute(scene);
    } catch (error) {
      scene._renderError.raiseEvent(scene, error);

      if (scene.rethrowRenderErrors) {
        throw error;
      }
    }
  }

  function updateMostDetailedRayPicks(scene) {
    return scene._picking.updateMostDetailedRayPicks(scene);
  }

  /**
   * Update and render the scene. It is usually not necessary to call this function
   * directly because {@link CesiumWidget} or {@link Viewer} do it automatically.
   * @param {JulianDate} [time] The simulation time at which to render.
   */
  Scene.prototype.render = function (time) {
    /**
     *
     * Pre passes update. Execute any pass invariant code that should run before the passes here.
     *
     */
    this._preUpdate.raiseEvent(this, time);

    const frameState = this._frameState;
    frameState.newFrame = false;

    if (!defined(time)) {
      time = JulianDate.now();
    }

    // Determine if shouldRender
    const cameraChanged = this._view.checkForCameraUpdates(this);
    let shouldRender =
      !this.requestRenderMode ||
      this._renderRequested ||
      cameraChanged ||
      this._logDepthBufferDirty ||
      this._hdrDirty ||
      this.mode === SceneMode$1.MORPHING;
    if (
      !shouldRender &&
      defined(this.maximumRenderTimeChange) &&
      defined(this._lastRenderTime)
    ) {
      const difference = Math.abs(
        JulianDate.secondsDifference(this._lastRenderTime, time)
      );
      shouldRender = shouldRender || difference > this.maximumRenderTimeChange;
    }

    if (shouldRender) {
      this._lastRenderTime = JulianDate.clone(time, this._lastRenderTime);
      this._renderRequested = false;
      this._logDepthBufferDirty = false;
      this._hdrDirty = false;

      const frameNumber = CesiumMath.incrementWrap(
        frameState.frameNumber,
        15000000.0,
        1.0
      );
      updateFrameNumber(this, frameNumber, time);
      frameState.newFrame = true;
    }

    tryAndCatchError(this, prePassesUpdate);

    /**
     *
     * Passes update. Add any passes here
     *
     */
    if (this.primitives.show) {
      tryAndCatchError(this, updateMostDetailedRayPicks);
      tryAndCatchError(this, updatePreloadPass);
      tryAndCatchError(this, updatePreloadFlightPass);
      if (!shouldRender) {
        tryAndCatchError(this, updateRequestRenderModeDeferCheckPass);
      }
    }

    this._postUpdate.raiseEvent(this, time);

    if (shouldRender) {
      this._preRender.raiseEvent(this, time);
      frameState.creditDisplay.beginFrame();
      tryAndCatchError(this, render);
    }

    /**
     *
     * Post passes update. Execute any pass invariant code that should run after the passes here.
     *
     */
    updateDebugShowFramesPerSecond(this, shouldRender);
    tryAndCatchError(this, postPassesUpdate);

    // Often used to trigger events (so don't want in trycatch) that the user might be subscribed to. Things like the tile load events, ready promises, etc.
    // We don't want those events to resolve during the render loop because the events might add new primitives
    callAfterRenderFunctions(this);

    if (shouldRender) {
      this._postRender.raiseEvent(this, time);
      frameState.creditDisplay.endFrame();
    }
  };

  /**
   * Update and render the scene. Always forces a new render frame regardless of whether a render was
   * previously requested.
   * @param {JulianDate} [time] The simulation time at which to render.
   *
   * @private
   */
  Scene.prototype.forceRender = function (time) {
    this._renderRequested = true;
    this.render(time);
  };

  /**
   * Requests a new rendered frame when {@link Scene#requestRenderMode} is set to <code>true</code>.
   * The render rate will not exceed the {@link CesiumWidget#targetFrameRate}.
   *
   * @see Scene#requestRenderMode
   */
  Scene.prototype.requestRender = function () {
    this._renderRequested = true;
  };

  /**
   * @private
   */
  Scene.prototype.clampLineWidth = function (width) {
    return Math.max(
      ContextLimits.minimumAliasedLineWidth,
      Math.min(width, ContextLimits.maximumAliasedLineWidth)
    );
  };

  /**
   * Returns an object with a `primitive` property that contains the first (top) primitive in the scene
   * at a particular window coordinate or undefined if nothing is at the location. Other properties may
   * potentially be set depending on the type of primitive and may be used to further identify the picked object.
   * <p>
   * When a feature of a 3D Tiles tileset is picked, <code>pick</code> returns a {@link Cesium3DTileFeature} object.
   * </p>
   *
   * @example
   * // On mouse over, color the feature yellow.
   * handler.setInputAction(function(movement) {
   *     const feature = scene.pick(movement.endPosition);
   *     if (feature instanceof Cesium.Cesium3DTileFeature) {
   *         feature.color = Cesium.Color.YELLOW;
   *     }
   * }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
   *
   * @param {Cartesian2} windowPosition Window coordinates to perform picking on.
   * @param {Number} [width=3] Width of the pick rectangle.
   * @param {Number} [height=3] Height of the pick rectangle.
   * @returns {Object} Object containing the picked primitive.
   */
  Scene.prototype.pick = function (windowPosition, width, height) {
    return this._picking.pick(this, windowPosition, width, height);
  };

  /**
   * Returns the cartesian position reconstructed from the depth buffer and window position.
   * The returned position is in world coordinates. Used internally by camera functions to
   * prevent conversion to projected 2D coordinates and then back.
   * <p>
   * Set {@link Scene#pickTranslucentDepth} to <code>true</code> to include the depth of
   * translucent primitives; otherwise, this essentially picks through translucent primitives.
   * </p>
   *
   * @private
   *
   * @param {Cartesian2} windowPosition Window coordinates to perform picking on.
   * @param {Cartesian3} [result] The object on which to restore the result.
   * @returns {Cartesian3} The cartesian position in world coordinates.
   *
   * @exception {DeveloperError} Picking from the depth buffer is not supported. Check pickPositionSupported.
   */
  Scene.prototype.pickPositionWorldCoordinates = function (
    windowPosition,
    result
  ) {
    return this._picking.pickPositionWorldCoordinates(
      this,
      windowPosition,
      result
    );
  };

  /**
   * Returns the cartesian position reconstructed from the depth buffer and window position.
   * <p>
   * The position reconstructed from the depth buffer in 2D may be slightly different from those
   * reconstructed in 3D and Columbus view. This is caused by the difference in the distribution
   * of depth values of perspective and orthographic projection.
   * </p>
   * <p>
   * Set {@link Scene#pickTranslucentDepth} to <code>true</code> to include the depth of
   * translucent primitives; otherwise, this essentially picks through translucent primitives.
   * </p>
   *
   * @param {Cartesian2} windowPosition Window coordinates to perform picking on.
   * @param {Cartesian3} [result] The object on which to restore the result.
   * @returns {Cartesian3} The cartesian position.
   *
   * @exception {DeveloperError} Picking from the depth buffer is not supported. Check pickPositionSupported.
   */
  Scene.prototype.pickPosition = function (windowPosition, result) {
    return this._picking.pickPosition(this, windowPosition, result);
  };

  /**
   * Returns a list of objects, each containing a `primitive` property, for all primitives at
   * a particular window coordinate position. Other properties may also be set depending on the
   * type of primitive and may be used to further identify the picked object. The primitives in
   * the list are ordered by their visual order in the scene (front to back).
   *
   * @param {Cartesian2} windowPosition Window coordinates to perform picking on.
   * @param {Number} [limit] If supplied, stop drilling after collecting this many picks.
   * @param {Number} [width=3] Width of the pick rectangle.
   * @param {Number} [height=3] Height of the pick rectangle.
   * @returns {Array.<*>} Array of objects, each containing 1 picked primitives.
   *
   * @exception {DeveloperError} windowPosition is undefined.
   *
   * @example
   * const pickedObjects = scene.drillPick(new Cesium.Cartesian2(100.0, 200.0));
   *
   * @see Scene#pick
   */
  Scene.prototype.drillPick = function (windowPosition, limit, width, height) {
    return this._picking.drillPick(this, windowPosition, limit, width, height);
  };

  function updatePreloadPass(scene) {
    const frameState = scene._frameState;
    preloadTilesetPassState.camera = frameState.camera;
    preloadTilesetPassState.cullingVolume = frameState.cullingVolume;

    const primitives = scene.primitives;
    primitives.updateForPass(frameState, preloadTilesetPassState);
  }

  function updatePreloadFlightPass(scene) {
    const frameState = scene._frameState;
    const camera = frameState.camera;
    if (!camera.canPreloadFlight()) {
      return;
    }

    preloadFlightTilesetPassState.camera = scene.preloadFlightCamera;
    preloadFlightTilesetPassState.cullingVolume =
      scene.preloadFlightCullingVolume;

    const primitives = scene.primitives;
    primitives.updateForPass(frameState, preloadFlightTilesetPassState);
  }

  function updateRequestRenderModeDeferCheckPass(scene) {
    // Check if any ignored requests are ready to go (to wake rendering up again)
    scene.primitives.updateForPass(
      scene._frameState,
      requestRenderModeDeferCheckPassState
    );
  }

  /**
   * Returns an object containing the first object intersected by the ray and the position of intersection,
   * or <code>undefined</code> if there were no intersections. The intersected object has a <code>primitive</code>
   * property that contains the intersected primitive. Other properties may be set depending on the type of primitive
   * and may be used to further identify the picked object. The ray must be given in world coordinates.
   * <p>
   * This function only picks globe tiles and 3D Tiles that are rendered in the current view. Picks all other
   * primitives regardless of their visibility.
   * </p>
   *
   * @private
   *
   * @param {Ray} ray The ray.
   * @param {Object[]} [objectsToExclude] A list of primitives, entities, or 3D Tiles features to exclude from the ray intersection.
   * @param {Number} [width=0.1] Width of the intersection volume in meters.
   * @returns {Object} An object containing the object and position of the first intersection.
   *
   * @exception {DeveloperError} Ray intersections are only supported in 3D mode.
   */
  Scene.prototype.pickFromRay = function (ray, objectsToExclude, width) {
    return this._picking.pickFromRay(this, ray, objectsToExclude, width);
  };

  /**
   * Returns a list of objects, each containing the object intersected by the ray and the position of intersection.
   * The intersected object has a <code>primitive</code> property that contains the intersected primitive. Other
   * properties may also be set depending on the type of primitive and may be used to further identify the picked object.
   * The primitives in the list are ordered by first intersection to last intersection. The ray must be given in
   * world coordinates.
   * <p>
   * This function only picks globe tiles and 3D Tiles that are rendered in the current view. Picks all other
   * primitives regardless of their visibility.
   * </p>
   *
   * @private
   *
   * @param {Ray} ray The ray.
   * @param {Number} [limit=Number.MAX_VALUE] If supplied, stop finding intersections after this many intersections.
   * @param {Object[]} [objectsToExclude] A list of primitives, entities, or 3D Tiles features to exclude from the ray intersection.
   * @param {Number} [width=0.1] Width of the intersection volume in meters.
   * @returns {Object[]} List of objects containing the object and position of each intersection.
   *
   * @exception {DeveloperError} Ray intersections are only supported in 3D mode.
   */
  Scene.prototype.drillPickFromRay = function (
    ray,
    limit,
    objectsToExclude,
    width
  ) {
    return this._picking.drillPickFromRay(
      this,
      ray,
      limit,
      objectsToExclude,
      width
    );
  };

  /**
   * Initiates an asynchronous {@link Scene#pickFromRay} request using the maximum level of detail for 3D Tilesets
   * regardless of visibility.
   *
   * @private
   *
   * @param {Ray} ray The ray.
   * @param {Object[]} [objectsToExclude] A list of primitives, entities, or 3D Tiles features to exclude from the ray intersection.
   * @param {Number} [width=0.1] Width of the intersection volume in meters.
   * @returns {Promise.<Object>} A promise that resolves to an object containing the object and position of the first intersection.
   *
   * @exception {DeveloperError} Ray intersections are only supported in 3D mode.
   */
  Scene.prototype.pickFromRayMostDetailed = function (
    ray,
    objectsToExclude,
    width
  ) {
    return this._picking.pickFromRayMostDetailed(
      this,
      ray,
      objectsToExclude,
      width
    );
  };

  /**
   * Initiates an asynchronous {@link Scene#drillPickFromRay} request using the maximum level of detail for 3D Tilesets
   * regardless of visibility.
   *
   * @private
   *
   * @param {Ray} ray The ray.
   * @param {Number} [limit=Number.MAX_VALUE] If supplied, stop finding intersections after this many intersections.
   * @param {Object[]} [objectsToExclude] A list of primitives, entities, or 3D Tiles features to exclude from the ray intersection.
   * @param {Number} [width=0.1] Width of the intersection volume in meters.
   * @returns {Promise.<Object[]>} A promise that resolves to a list of objects containing the object and position of each intersection.
   *
   * @exception {DeveloperError} Ray intersections are only supported in 3D mode.
   */
  Scene.prototype.drillPickFromRayMostDetailed = function (
    ray,
    limit,
    objectsToExclude,
    width
  ) {
    return this._picking.drillPickFromRayMostDetailed(
      this,
      ray,
      limit,
      objectsToExclude,
      width
    );
  };

  /**
   * Returns the height of scene geometry at the given cartographic position or <code>undefined</code> if there was no
   * scene geometry to sample height from. The height of the input position is ignored. May be used to clamp objects to
   * the globe, 3D Tiles, or primitives in the scene.
   * <p>
   * This function only samples height from globe tiles and 3D Tiles that are rendered in the current view. Samples height
   * from all other primitives regardless of their visibility.
   * </p>
   *
   * @param {Cartographic} position The cartographic position to sample height from.
   * @param {Object[]} [objectsToExclude] A list of primitives, entities, or 3D Tiles features to not sample height from.
   * @param {Number} [width=0.1] Width of the intersection volume in meters.
   * @returns {Number} The height. This may be <code>undefined</code> if there was no scene geometry to sample height from.
   *
   * @example
   * const position = new Cesium.Cartographic(-1.31968, 0.698874);
   * const height = viewer.scene.sampleHeight(position);
   * console.log(height);
   *
   * @see Scene#clampToHeight
   * @see Scene#clampToHeightMostDetailed
   * @see Scene#sampleHeightMostDetailed
   *
   * @exception {DeveloperError} sampleHeight is only supported in 3D mode.
   * @exception {DeveloperError} sampleHeight requires depth texture support. Check sampleHeightSupported.
   */
  Scene.prototype.sampleHeight = function (position, objectsToExclude, width) {
    return this._picking.sampleHeight(this, position, objectsToExclude, width);
  };

  /**
   * Clamps the given cartesian position to the scene geometry along the geodetic surface normal. Returns the
   * clamped position or <code>undefined</code> if there was no scene geometry to clamp to. May be used to clamp
   * objects to the globe, 3D Tiles, or primitives in the scene.
   * <p>
   * This function only clamps to globe tiles and 3D Tiles that are rendered in the current view. Clamps to
   * all other primitives regardless of their visibility.
   * </p>
   *
   * @param {Cartesian3} cartesian The cartesian position.
   * @param {Object[]} [objectsToExclude] A list of primitives, entities, or 3D Tiles features to not clamp to.
   * @param {Number} [width=0.1] Width of the intersection volume in meters.
   * @param {Cartesian3} [result] An optional object to return the clamped position.
   * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided. This may be <code>undefined</code> if there was no scene geometry to clamp to.
   *
   * @example
   * // Clamp an entity to the underlying scene geometry
   * const position = entity.position.getValue(Cesium.JulianDate.now());
   * entity.position = viewer.scene.clampToHeight(position);
   *
   * @see Scene#sampleHeight
   * @see Scene#sampleHeightMostDetailed
   * @see Scene#clampToHeightMostDetailed
   *
   * @exception {DeveloperError} clampToHeight is only supported in 3D mode.
   * @exception {DeveloperError} clampToHeight requires depth texture support. Check clampToHeightSupported.
   */
  Scene.prototype.clampToHeight = function (
    cartesian,
    objectsToExclude,
    width,
    result
  ) {
    return this._picking.clampToHeight(
      this,
      cartesian,
      objectsToExclude,
      width,
      result
    );
  };

  /**
   * Initiates an asynchronous {@link Scene#sampleHeight} query for an array of {@link Cartographic} positions
   * using the maximum level of detail for 3D Tilesets in the scene. The height of the input positions is ignored.
   * Returns a promise that is resolved when the query completes. Each point height is modified in place.
   * If a height cannot be determined because no geometry can be sampled at that location, or another error occurs,
   * the height is set to undefined.
   *
   * @param {Cartographic[]} positions The cartographic positions to update with sampled heights.
   * @param {Object[]} [objectsToExclude] A list of primitives, entities, or 3D Tiles features to not sample height from.
   * @param {Number} [width=0.1] Width of the intersection volume in meters.
   * @returns {Promise.<Cartographic[]>} A promise that resolves to the provided list of positions when the query has completed.
   *
   * @example
   * const positions = [
   *     new Cesium.Cartographic(-1.31968, 0.69887),
   *     new Cesium.Cartographic(-1.10489, 0.83923)
   * ];
   * const promise = viewer.scene.sampleHeightMostDetailed(positions);
   * promise.then(function(updatedPosition) {
   *     // positions[0].height and positions[1].height have been updated.
   *     // updatedPositions is just a reference to positions.
   * }
   *
   * @see Scene#sampleHeight
   *
   * @exception {DeveloperError} sampleHeightMostDetailed is only supported in 3D mode.
   * @exception {DeveloperError} sampleHeightMostDetailed requires depth texture support. Check sampleHeightSupported.
   */
  Scene.prototype.sampleHeightMostDetailed = function (
    positions,
    objectsToExclude,
    width
  ) {
    return this._picking.sampleHeightMostDetailed(
      this,
      positions,
      objectsToExclude,
      width
    );
  };

  /**
   * Initiates an asynchronous {@link Scene#clampToHeight} query for an array of {@link Cartesian3} positions
   * using the maximum level of detail for 3D Tilesets in the scene. Returns a promise that is resolved when
   * the query completes. Each position is modified in place. If a position cannot be clamped because no geometry
   * can be sampled at that location, or another error occurs, the element in the array is set to undefined.
   *
   * @param {Cartesian3[]} cartesians The cartesian positions to update with clamped positions.
   * @param {Object[]} [objectsToExclude] A list of primitives, entities, or 3D Tiles features to not clamp to.
   * @param {Number} [width=0.1] Width of the intersection volume in meters.
   * @returns {Promise.<Cartesian3[]>} A promise that resolves to the provided list of positions when the query has completed.
   *
   * @example
   * const cartesians = [
   *     entities[0].position.getValue(Cesium.JulianDate.now()),
   *     entities[1].position.getValue(Cesium.JulianDate.now())
   * ];
   * const promise = viewer.scene.clampToHeightMostDetailed(cartesians);
   * promise.then(function(updatedCartesians) {
   *     entities[0].position = updatedCartesians[0];
   *     entities[1].position = updatedCartesians[1];
   * }
   *
   * @see Scene#clampToHeight
   *
   * @exception {DeveloperError} clampToHeightMostDetailed is only supported in 3D mode.
   * @exception {DeveloperError} clampToHeightMostDetailed requires depth texture support. Check clampToHeightSupported.
   */
  Scene.prototype.clampToHeightMostDetailed = function (
    cartesians,
    objectsToExclude,
    width
  ) {
    return this._picking.clampToHeightMostDetailed(
      this,
      cartesians,
      objectsToExclude,
      width
    );
  };

  /**
   * Transforms a position in cartesian coordinates to canvas coordinates.  This is commonly used to place an
   * HTML element at the same screen position as an object in the scene.
   *
   * @param {Cartesian3} position The position in cartesian coordinates.
   * @param {Cartesian2} [result] An optional object to return the input position transformed to canvas coordinates.
   * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.  This may be <code>undefined</code> if the input position is near the center of the ellipsoid.
   *
   * @example
   * // Output the canvas position of longitude/latitude (0, 0) every time the mouse moves.
   * const scene = widget.scene;
   * const ellipsoid = scene.globe.ellipsoid;
   * const position = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
   * const handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
   * handler.setInputAction(function(movement) {
   *     console.log(scene.cartesianToCanvasCoordinates(position));
   * }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
   */
  Scene.prototype.cartesianToCanvasCoordinates = function (position, result) {
    return SceneTransforms.wgs84ToWindowCoordinates(this, position, result);
  };

  /**
   * Instantly completes an active transition.
   */
  Scene.prototype.completeMorph = function () {
    this._transitioner.completeMorph();
  };

  /**
   * Asynchronously transitions the scene to 2D.
   * @param {Number} [duration=2.0] The amount of time, in seconds, for transition animations to complete.
   */
  Scene.prototype.morphTo2D = function (duration) {
    let ellipsoid;
    const globe = this.globe;
    if (defined(globe)) {
      ellipsoid = globe.ellipsoid;
    } else {
      ellipsoid = this.mapProjection.ellipsoid;
    }
    duration = defaultValue(duration, 2.0);
    this._transitioner.morphTo2D(duration, ellipsoid);
  };

  /**
   * Asynchronously transitions the scene to Columbus View.
   * @param {Number} [duration=2.0] The amount of time, in seconds, for transition animations to complete.
   */
  Scene.prototype.morphToColumbusView = function (duration) {
    let ellipsoid;
    const globe = this.globe;
    if (defined(globe)) {
      ellipsoid = globe.ellipsoid;
    } else {
      ellipsoid = this.mapProjection.ellipsoid;
    }
    duration = defaultValue(duration, 2.0);
    this._transitioner.morphToColumbusView(duration, ellipsoid);
  };

  /**
   * Asynchronously transitions the scene to 3D.
   * @param {Number} [duration=2.0] The amount of time, in seconds, for transition animations to complete.
   */
  Scene.prototype.morphTo3D = function (duration) {
    let ellipsoid;
    const globe = this.globe;
    if (defined(globe)) {
      ellipsoid = globe.ellipsoid;
    } else {
      ellipsoid = this.mapProjection.ellipsoid;
    }
    duration = defaultValue(duration, 2.0);
    this._transitioner.morphTo3D(duration, ellipsoid);
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see Scene#destroy
   */
  Scene.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * scene = scene && scene.destroy();
   *
   * @see Scene#isDestroyed
   */
  Scene.prototype.destroy = function () {
    this._tweens.removeAll();
    this._computeEngine = this._computeEngine && this._computeEngine.destroy();
    this._screenSpaceCameraController =
      this._screenSpaceCameraController &&
      this._screenSpaceCameraController.destroy();
    this._deviceOrientationCameraController =
      this._deviceOrientationCameraController &&
      !this._deviceOrientationCameraController.isDestroyed() &&
      this._deviceOrientationCameraController.destroy();
    this._primitives = this._primitives && this._primitives.destroy();
    this._groundPrimitives =
      this._groundPrimitives && this._groundPrimitives.destroy();
    this._globe = this._globe && this._globe.destroy();
    this.skyBox = this.skyBox && this.skyBox.destroy();
    this.skyAtmosphere = this.skyAtmosphere && this.skyAtmosphere.destroy();
    this._debugSphere = this._debugSphere && this._debugSphere.destroy();
    this.sun = this.sun && this.sun.destroy();
    this._sunPostProcess = this._sunPostProcess && this._sunPostProcess.destroy();
    this._depthPlane = this._depthPlane && this._depthPlane.destroy();
    this._transitioner = this._transitioner && this._transitioner.destroy();
    this._debugFrustumPlanes =
      this._debugFrustumPlanes && this._debugFrustumPlanes.destroy();
    this._brdfLutGenerator =
      this._brdfLutGenerator && this._brdfLutGenerator.destroy();
    this._picking = this._picking && this._picking.destroy();

    this._defaultView = this._defaultView && this._defaultView.destroy();
    this._view = undefined;

    if (this._removeCreditContainer) {
      this._canvas.parentNode.removeChild(this._creditContainer);
    }

    this.postProcessStages =
      this.postProcessStages && this.postProcessStages.destroy();

    this._context = this._context && this._context.destroy();
    this._frameState.creditDisplay =
      this._frameState.creditDisplay && this._frameState.creditDisplay.destroy();

    if (defined(this._performanceDisplay)) {
      this._performanceDisplay =
        this._performanceDisplay && this._performanceDisplay.destroy();
      this._performanceContainer.parentNode.removeChild(
        this._performanceContainer
      );
    }

    this._removeRequestListenerCallback();
    this._removeTaskProcessorListenerCallback();
    for (let i = 0; i < this._removeGlobeCallbacks.length; ++i) {
      this._removeGlobeCallbacks[i]();
    }
    this._removeGlobeCallbacks.length = 0;

    return destroyObject(this);
  };

  //This file is automatically rebuilt by the Cesium build process.
  var SkyAtmosphereCommon = "float interpolateByDistance(vec4 nearFarScalar, float distance)\n\
{\n\
float startDistance = nearFarScalar.x;\n\
float startValue = nearFarScalar.y;\n\
float endDistance = nearFarScalar.z;\n\
float endValue = nearFarScalar.w;\n\
float t = clamp((distance - startDistance) / (endDistance - startDistance), 0.0, 1.0);\n\
return mix(startValue, endValue, t);\n\
}\n\
vec3 getLightDirection(vec3 positionWC)\n\
{\n\
float lightEnum = u_radiiAndDynamicAtmosphereColor.z;\n\
vec3 lightDirection =\n\
positionWC * float(lightEnum == 0.0) +\n\
czm_lightDirectionWC * float(lightEnum == 1.0) +\n\
czm_sunDirectionWC * float(lightEnum == 2.0);\n\
return normalize(lightDirection);\n\
}\n\
void computeAtmosphereScattering(vec3 positionWC, vec3 lightDirection, out vec3 rayleighColor, out vec3 mieColor, out float opacity, out float underTranslucentGlobe)\n\
{\n\
float ellipsoidRadiiDifference = czm_ellipsoidRadii.x - czm_ellipsoidRadii.z;\n\
float distanceAdjustMin = czm_ellipsoidRadii.x / 4.0;\n\
float distanceAdjustMax = czm_ellipsoidRadii.x;\n\
float distanceAdjustModifier = ellipsoidRadiiDifference / 2.0;\n\
float distanceAdjust = distanceAdjustModifier * clamp((czm_eyeHeight - distanceAdjustMin) / (distanceAdjustMax - distanceAdjustMin), 0.0, 1.0);\n\
float radiusAdjust = (ellipsoidRadiiDifference / 4.0) + distanceAdjust;\n\
float atmosphereInnerRadius = (length(czm_viewerPositionWC) - czm_eyeHeight) - radiusAdjust;\n\
vec3 cameraToPositionWC = positionWC - czm_viewerPositionWC;\n\
vec3 cameraToPositionWCDirection = normalize(cameraToPositionWC);\n\
czm_ray primaryRay = czm_ray(czm_viewerPositionWC, cameraToPositionWCDirection);\n\
underTranslucentGlobe = 0.0;\n\
#if defined(GLOBE_TRANSLUCENT)\n\
czm_raySegment primaryRayEarthIntersect = czm_raySphereIntersectionInterval(primaryRay, vec3(0.0), atmosphereInnerRadius + radiusAdjust);\n\
if (primaryRayEarthIntersect.start > 0.0 && primaryRayEarthIntersect.stop > 0.0) {\n\
vec3 direction = normalize(positionWC);\n\
czm_ray ellipsoidRay = czm_ray(positionWC, -direction);\n\
czm_raySegment ellipsoidIntersection = czm_rayEllipsoidIntersectionInterval(ellipsoidRay, vec3(0.0), czm_ellipsoidInverseRadii);\n\
vec3 onEarth = positionWC - (direction * ellipsoidIntersection.start);\n\
float angle = dot(normalize(czm_viewerPositionWC), normalize(onEarth));\n\
opacity = interpolateByDistance(vec4(0.0, 1.0, czm_ellipsoidRadii.x, 0.0), length(czm_viewerPositionWC - onEarth));\n\
vec3 horizonColor = vec3(0.1, 0.2, 0.3);\n\
vec3 nearColor = vec3(0.0);\n\
rayleighColor = mix(nearColor, horizonColor, exp(-angle) * opacity);\n\
underTranslucentGlobe = 1.0;\n\
return;\n\
}\n\
#endif\n\
computeScattering(\n\
primaryRay,\n\
length(cameraToPositionWC),\n\
lightDirection,\n\
atmosphereInnerRadius,\n\
rayleighColor,\n\
mieColor,\n\
opacity\n\
);\n\
float cameraHeight = czm_eyeHeight + atmosphereInnerRadius;\n\
float atmosphereOuterRadius = atmosphereInnerRadius + ATMOSPHERE_THICKNESS;\n\
opacity = clamp((atmosphereOuterRadius - cameraHeight) / (atmosphereOuterRadius - atmosphereInnerRadius), 0.0, 1.0);\n\
float nightAlpha = (u_radiiAndDynamicAtmosphereColor.z != 0.0) ? clamp(dot(normalize(positionWC), lightDirection), 0.0, 1.0) : 1.0;\n\
opacity *= pow(nightAlpha, 0.5);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var SkyAtmosphereFS = "varying vec3 v_outerPositionWC;\n\
uniform vec3 u_hsbShift;\n\
#ifndef PER_FRAGMENT_ATMOSPHERE\n\
varying vec3 v_mieColor;\n\
varying vec3 v_rayleighColor;\n\
varying float v_opacity;\n\
varying float v_translucent;\n\
#endif\n\
void main (void)\n\
{\n\
vec3 lightDirection = getLightDirection(v_outerPositionWC);\n\
vec3 mieColor;\n\
vec3 rayleighColor;\n\
float opacity;\n\
float translucent;\n\
#ifdef PER_FRAGMENT_ATMOSPHERE\n\
computeAtmosphereScattering(\n\
v_outerPositionWC,\n\
lightDirection,\n\
rayleighColor,\n\
mieColor,\n\
opacity,\n\
translucent\n\
);\n\
#else\n\
mieColor = v_mieColor;\n\
rayleighColor = v_rayleighColor;\n\
opacity = v_opacity;\n\
translucent = v_translucent;\n\
#endif\n\
vec4 color = computeAtmosphereColor(v_outerPositionWC, lightDirection, rayleighColor, mieColor, opacity);\n\
#ifndef HDR\n\
color.rgb = czm_acesTonemapping(color.rgb);\n\
color.rgb = czm_inverseGamma(color.rgb);\n\
#endif\n\
#ifdef COLOR_CORRECT\n\
vec3 hsb = czm_RGBToHSB(color.rgb);\n\
hsb.x += u_hsbShift.x;\n\
hsb.y = clamp(hsb.y + u_hsbShift.y, 0.0, 1.0);\n\
hsb.z = hsb.z > czm_epsilon7 ? hsb.z + u_hsbShift.z : 0.0;\n\
color.rgb = czm_HSBToRGB(hsb);\n\
#endif\n\
if (translucent == 0.0) {\n\
color.a = mix(color.b, 1.0, color.a) * smoothstep(0.0, 1.0, czm_morphTime);\n\
}\n\
gl_FragColor = color;\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var SkyAtmosphereVS = "attribute vec4 position;\n\
varying vec3 v_outerPositionWC;\n\
#ifndef PER_FRAGMENT_ATMOSPHERE\n\
varying vec3 v_mieColor;\n\
varying vec3 v_rayleighColor;\n\
varying float v_opacity;\n\
varying float v_translucent;\n\
#endif\n\
void main(void)\n\
{\n\
vec4 positionWC = czm_model * position;\n\
vec3 lightDirection = getLightDirection(positionWC.xyz);\n\
#ifndef PER_FRAGMENT_ATMOSPHERE\n\
computeAtmosphereScattering(\n\
positionWC.xyz,\n\
lightDirection,\n\
v_rayleighColor,\n\
v_mieColor,\n\
v_opacity,\n\
v_translucent\n\
);\n\
#endif\n\
v_outerPositionWC = positionWC.xyz;\n\
gl_Position = czm_modelViewProjection * position;\n\
}\n\
";

  /**
   * An atmosphere drawn around the limb of the provided ellipsoid. Based on
   * {@link http://nishitalab.org/user/nis/cdrom/sig93_nis.pdf|Display of The Earth Taking Into Account Atmospheric Scattering}.
   * <p>
   * This is only supported in 3D. Atmosphere is faded out when morphing to 2D or Columbus view.
   * </p>
   *
   * @alias SkyAtmosphere
   * @constructor
   *
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid that the atmosphere is drawn around.
   *
   * @example
   * scene.skyAtmosphere = new Cesium.SkyAtmosphere();
   *
   * @see Scene.skyAtmosphere
   */
  function SkyAtmosphere(ellipsoid) {
    ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);

    /**
     * Determines if the atmosphere is shown.
     *
     * @type {Boolean}
     * @default true
     */
    this.show = true;

    /**
     * Compute atmosphere per-fragment instead of per-vertex.
     * This produces better looking atmosphere with a slight performance penalty.
     *
     * @type {Boolean}
     * @default false
     */
    this.perFragmentAtmosphere = false;

    this._ellipsoid = ellipsoid;

    const outerEllipsoidScale = 1.025;
    const scaleVector = Cartesian3.multiplyByScalar(
      ellipsoid.radii,
      outerEllipsoidScale,
      new Cartesian3()
    );
    this._scaleMatrix = Matrix4.fromScale(scaleVector);
    this._modelMatrix = new Matrix4();

    this._command = new DrawCommand({
      owner: this,
      modelMatrix: this._modelMatrix,
    });
    this._spSkyFromSpace = undefined;
    this._spSkyFromAtmosphere = undefined;

    this._flags = undefined;

    /**
     * The intensity of the light that is used for computing the sky atmosphere color.
     *
     * @type {Number}
     * @default 50.0
     */
    this.atmosphereLightIntensity = 50.0;

    /**
     * The Rayleigh scattering coefficient used in the atmospheric scattering equations for the sky atmosphere.
     *
     * @type {Cartesian3}
     * @default Cartesian3(5.5e-6, 13.0e-6, 28.4e-6)
     */
    this.atmosphereRayleighCoefficient = new Cartesian3(5.5e-6, 13.0e-6, 28.4e-6);

    /**
     * The Mie scattering coefficient used in the atmospheric scattering equations for the sky atmosphere.
     *
     * @type {Cartesian3}
     * @default Cartesian3(21e-6, 21e-6, 21e-6)
     */
    this.atmosphereMieCoefficient = new Cartesian3(21e-6, 21e-6, 21e-6);

    /**
     * The Rayleigh scale height used in the atmospheric scattering equations for the sky atmosphere, in meters.
     *
     * @type {Number}
     * @default 10000.0
     */
    this.atmosphereRayleighScaleHeight = 10000.0;

    /**
     * The Mie scale height used in the atmospheric scattering equations for the sky atmosphere, in meters.
     *
     * @type {Number}
     * @default 3200.0
     */
    this.atmosphereMieScaleHeight = 3200.0;

    /**
     * The anisotropy of the medium to consider for Mie scattering.
     * <p>
     * Valid values are between -1.0 and 1.0.
     * </p>
     * @type {Number}
     * @default 0.9
     */
    this.atmosphereMieAnisotropy = 0.9;

    /**
     * The hue shift to apply to the atmosphere. Defaults to 0.0 (no shift).
     * A hue shift of 1.0 indicates a complete rotation of the hues available.
     * @type {Number}
     * @default 0.0
     */
    this.hueShift = 0.0;

    /**
     * The saturation shift to apply to the atmosphere. Defaults to 0.0 (no shift).
     * A saturation shift of -1.0 is monochrome.
     * @type {Number}
     * @default 0.0
     */
    this.saturationShift = 0.0;

    /**
     * The brightness shift to apply to the atmosphere. Defaults to 0.0 (no shift).
     * A brightness shift of -1.0 is complete darkness, which will let space show through.
     * @type {Number}
     * @default 0.0
     */
    this.brightnessShift = 0.0;

    this._hueSaturationBrightness = new Cartesian3();

    // outer radius, inner radius, dynamic atmosphere color flag
    const radiiAndDynamicAtmosphereColor = new Cartesian3();

    radiiAndDynamicAtmosphereColor.x =
      ellipsoid.maximumRadius * outerEllipsoidScale;
    radiiAndDynamicAtmosphereColor.y = ellipsoid.maximumRadius;

    // Toggles whether the sun position is used. 0 treats the sun as always directly overhead.
    radiiAndDynamicAtmosphereColor.z = 0;

    this._radiiAndDynamicAtmosphereColor = radiiAndDynamicAtmosphereColor;

    const that = this;

    this._command.uniformMap = {
      u_radiiAndDynamicAtmosphereColor: function () {
        return that._radiiAndDynamicAtmosphereColor;
      },
      u_hsbShift: function () {
        that._hueSaturationBrightness.x = that.hueShift;
        that._hueSaturationBrightness.y = that.saturationShift;
        that._hueSaturationBrightness.z = that.brightnessShift;
        return that._hueSaturationBrightness;
      },
      u_atmosphereLightIntensity: function () {
        return that.atmosphereLightIntensity;
      },
      u_atmosphereRayleighCoefficient: function () {
        return that.atmosphereRayleighCoefficient;
      },
      u_atmosphereMieCoefficient: function () {
        return that.atmosphereMieCoefficient;
      },
      u_atmosphereRayleighScaleHeight: function () {
        return that.atmosphereRayleighScaleHeight;
      },
      u_atmosphereMieScaleHeight: function () {
        return that.atmosphereMieScaleHeight;
      },
      u_atmosphereMieAnisotropy: function () {
        return that.atmosphereMieAnisotropy;
      },
    };
  }

  Object.defineProperties(SkyAtmosphere.prototype, {
    /**
     * Gets the ellipsoid the atmosphere is drawn around.
     * @memberof SkyAtmosphere.prototype
     *
     * @type {Ellipsoid}
     * @readonly
     */
    ellipsoid: {
      get: function () {
        return this._ellipsoid;
      },
    },
  });

  /**
   * @private
   */
  SkyAtmosphere.prototype.setDynamicAtmosphereColor = function (
    enableLighting,
    useSunDirection
  ) {
    const lightEnum = enableLighting ? (useSunDirection ? 2.0 : 1.0) : 0.0;
    this._radiiAndDynamicAtmosphereColor.z = lightEnum;
  };

  const scratchModelMatrix$1 = new Matrix4();

  /**
   * @private
   */
  SkyAtmosphere.prototype.update = function (frameState, globe) {
    if (!this.show) {
      return undefined;
    }

    const mode = frameState.mode;
    if (mode !== SceneMode$1.SCENE3D && mode !== SceneMode$1.MORPHING) {
      return undefined;
    }

    // The atmosphere is only rendered during the render pass; it is not pickable, it doesn't cast shadows, etc.
    if (!frameState.passes.render) {
      return undefined;
    }

    // Align the ellipsoid geometry so it always faces the same direction as the
    // camera to reduce artifacts when rendering atmosphere per-vertex
    const rotationMatrix = Matrix4.fromRotationTranslation(
      frameState.context.uniformState.inverseViewRotation,
      Cartesian3.ZERO,
      scratchModelMatrix$1
    );
    const rotationOffsetMatrix = Matrix4.multiplyTransformation(
      rotationMatrix,
      Axis$1.Y_UP_TO_Z_UP,
      scratchModelMatrix$1
    );
    const modelMatrix = Matrix4.multiply(
      this._scaleMatrix,
      rotationOffsetMatrix,
      scratchModelMatrix$1
    );
    Matrix4.clone(modelMatrix, this._modelMatrix);

    const context = frameState.context;

    const colorCorrect = hasColorCorrection(this);
    const translucent = frameState.globeTranslucencyState.translucent;
    const perFragmentAtmosphere =
      this.perFragmentAtmosphere || translucent || !defined(globe) || !globe.show;

    const command = this._command;

    if (!defined(command.vertexArray)) {
      const geometry = EllipsoidGeometry.createGeometry(
        new EllipsoidGeometry({
          radii: new Cartesian3(1.0, 1.0, 1.0),
          slicePartitions: 256,
          stackPartitions: 256,
          vertexFormat: VertexFormat.POSITION_ONLY,
        })
      );
      command.vertexArray = VertexArray.fromGeometry({
        context: context,
        geometry: geometry,
        attributeLocations: GeometryPipeline.createAttributeLocations(geometry),
        bufferUsage: BufferUsage$1.STATIC_DRAW,
      });
      command.renderState = RenderState.fromCache({
        cull: {
          enabled: true,
          face: CullFace$1.FRONT,
        },
        blending: BlendingState$1.ALPHA_BLEND,
        depthMask: false,
      });
    }

    const flags =
      colorCorrect | (perFragmentAtmosphere << 2) | (translucent << 3);

    if (flags !== this._flags) {
      this._flags = flags;

      const defines = [];

      if (colorCorrect) {
        defines.push("COLOR_CORRECT");
      }

      if (perFragmentAtmosphere) {
        defines.push("PER_FRAGMENT_ATMOSPHERE");
      }

      if (translucent) {
        defines.push("GLOBE_TRANSLUCENT");
      }

      const vs = new ShaderSource({
        defines: defines,
        sources: [AtmosphereCommon, SkyAtmosphereCommon, SkyAtmosphereVS],
      });

      const fs = new ShaderSource({
        defines: defines,
        sources: [AtmosphereCommon, SkyAtmosphereCommon, SkyAtmosphereFS],
      });

      this._spSkyAtmosphere = ShaderProgram.fromCache({
        context: context,
        vertexShaderSource: vs,
        fragmentShaderSource: fs,
      });

      command.shaderProgram = this._spSkyAtmosphere;
    }

    return command;
  };

  function hasColorCorrection(skyAtmosphere) {
    return !(
      CesiumMath.equalsEpsilon(
        skyAtmosphere.hueShift,
        0.0,
        CesiumMath.EPSILON7
      ) &&
      CesiumMath.equalsEpsilon(
        skyAtmosphere.saturationShift,
        0.0,
        CesiumMath.EPSILON7
      ) &&
      CesiumMath.equalsEpsilon(
        skyAtmosphere.brightnessShift,
        0.0,
        CesiumMath.EPSILON7
      )
    );
  }

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see SkyAtmosphere#destroy
   */
  SkyAtmosphere.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * skyAtmosphere = skyAtmosphere && skyAtmosphere.destroy();
   *
   * @see SkyAtmosphere#isDestroyed
   */
  SkyAtmosphere.prototype.destroy = function () {
    const command = this._command;
    command.vertexArray = command.vertexArray && command.vertexArray.destroy();
    this._spSkyAtmosphere =
      this._spSkyAtmosphere && this._spSkyAtmosphere.destroy();
    return destroyObject(this);
  };

  //This file is automatically rebuilt by the Cesium build process.
  var SkyBoxFS = "uniform samplerCube u_cubeMap;\n\
varying vec3 v_texCoord;\n\
void main()\n\
{\n\
vec4 color = textureCube(u_cubeMap, normalize(v_texCoord));\n\
gl_FragColor = vec4(czm_gammaCorrect(color).rgb, czm_morphTime);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var SkyBoxVS = "attribute vec3 position;\n\
varying vec3 v_texCoord;\n\
void main()\n\
{\n\
vec3 p = czm_viewRotation * (czm_temeToPseudoFixed * (czm_entireFrustum.y * position));\n\
gl_Position = czm_projection * vec4(p, 1.0);\n\
v_texCoord = position.xyz;\n\
}\n\
";

  /**
   * A sky box around the scene to draw stars.  The sky box is defined using the True Equator Mean Equinox (TEME) axes.
   * <p>
   * This is only supported in 3D.  The sky box is faded out when morphing to 2D or Columbus view.  The size of
   * the sky box must not exceed {@link Scene#maximumCubeMapSize}.
   * </p>
   *
   * @alias SkyBox
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Object} [options.sources] The source URL or <code>Image</code> object for each of the six cube map faces.  See the example below.
   * @param {Boolean} [options.show=true] Determines if this primitive will be shown.
   *
   *
   * @example
   * scene.skyBox = new Cesium.SkyBox({
   *   sources : {
   *     positiveX : 'skybox_px.png',
   *     negativeX : 'skybox_nx.png',
   *     positiveY : 'skybox_py.png',
   *     negativeY : 'skybox_ny.png',
   *     positiveZ : 'skybox_pz.png',
   *     negativeZ : 'skybox_nz.png'
   *   }
   * });
   *
   * @see Scene#skyBox
   * @see Transforms.computeTemeToPseudoFixedMatrix
   */
  function SkyBox(options) {
    /**
     * The sources used to create the cube map faces: an object
     * with <code>positiveX</code>, <code>negativeX</code>, <code>positiveY</code>,
     * <code>negativeY</code>, <code>positiveZ</code>, and <code>negativeZ</code> properties.
     * These can be either URLs or <code>Image</code> objects.
     *
     * @type Object
     * @default undefined
     */
    this.sources = options.sources;
    this._sources = undefined;

    /**
     * Determines if the sky box will be shown.
     *
     * @type {Boolean}
     * @default true
     */
    this.show = defaultValue(options.show, true);

    this._command = new DrawCommand({
      modelMatrix: Matrix4.clone(Matrix4.IDENTITY),
      owner: this,
    });
    this._cubeMap = undefined;

    this._attributeLocations = undefined;
    this._useHdr = undefined;
  }

  /**
   * Called when {@link Viewer} or {@link CesiumWidget} render the scene to
   * get the draw commands needed to render this primitive.
   * <p>
   * Do not call this function directly.  This is documented just to
   * list the exceptions that may be propagated when the scene is rendered:
   * </p>
   *
   * @exception {DeveloperError} this.sources is required and must have positiveX, negativeX, positiveY, negativeY, positiveZ, and negativeZ properties.
   * @exception {DeveloperError} this.sources properties must all be the same type.
   */
  SkyBox.prototype.update = function (frameState, useHdr) {
    const that = this;

    if (!this.show) {
      return undefined;
    }

    if (
      frameState.mode !== SceneMode$1.SCENE3D &&
      frameState.mode !== SceneMode$1.MORPHING
    ) {
      return undefined;
    }

    // The sky box is only rendered during the render pass; it is not pickable, it doesn't cast shadows, etc.
    if (!frameState.passes.render) {
      return undefined;
    }

    const context = frameState.context;

    if (this._sources !== this.sources) {
      this._sources = this.sources;
      const sources = this.sources;

      //>>includeStart('debug', pragmas.debug);
      if (
        !defined(sources.positiveX) ||
        !defined(sources.negativeX) ||
        !defined(sources.positiveY) ||
        !defined(sources.negativeY) ||
        !defined(sources.positiveZ) ||
        !defined(sources.negativeZ)
      ) {
        throw new DeveloperError(
          "this.sources is required and must have positiveX, negativeX, positiveY, negativeY, positiveZ, and negativeZ properties."
        );
      }

      if (
        typeof sources.positiveX !== typeof sources.negativeX ||
        typeof sources.positiveX !== typeof sources.positiveY ||
        typeof sources.positiveX !== typeof sources.negativeY ||
        typeof sources.positiveX !== typeof sources.positiveZ ||
        typeof sources.positiveX !== typeof sources.negativeZ
      ) {
        throw new DeveloperError(
          "this.sources properties must all be the same type."
        );
      }
      //>>includeEnd('debug');

      if (typeof sources.positiveX === "string") {
        // Given urls for cube-map images.  Load them.
        loadCubeMap(context, this._sources).then(function (cubeMap) {
          that._cubeMap = that._cubeMap && that._cubeMap.destroy();
          that._cubeMap = cubeMap;
        });
      } else {
        this._cubeMap = this._cubeMap && this._cubeMap.destroy();
        this._cubeMap = new CubeMap({
          context: context,
          source: sources,
        });
      }
    }

    const command = this._command;

    if (!defined(command.vertexArray)) {
      command.uniformMap = {
        u_cubeMap: function () {
          return that._cubeMap;
        },
      };

      const geometry = BoxGeometry.createGeometry(
        BoxGeometry.fromDimensions({
          dimensions: new Cartesian3(2.0, 2.0, 2.0),
          vertexFormat: VertexFormat.POSITION_ONLY,
        })
      );
      const attributeLocations = (this._attributeLocations = GeometryPipeline.createAttributeLocations(
        geometry
      ));

      command.vertexArray = VertexArray.fromGeometry({
        context: context,
        geometry: geometry,
        attributeLocations: attributeLocations,
        bufferUsage: BufferUsage$1.STATIC_DRAW,
      });

      command.renderState = RenderState.fromCache({
        blending: BlendingState$1.ALPHA_BLEND,
      });
    }

    if (!defined(command.shaderProgram) || this._useHdr !== useHdr) {
      const fs = new ShaderSource({
        defines: [useHdr ? "HDR" : ""],
        sources: [SkyBoxFS],
      });
      command.shaderProgram = ShaderProgram.fromCache({
        context: context,
        vertexShaderSource: SkyBoxVS,
        fragmentShaderSource: fs,
        attributeLocations: this._attributeLocations,
      });
      this._useHdr = useHdr;
    }

    if (!defined(this._cubeMap)) {
      return undefined;
    }

    return command;
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see SkyBox#destroy
   */
  SkyBox.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * skyBox = skyBox && skyBox.destroy();
   *
   * @see SkyBox#isDestroyed
   */
  SkyBox.prototype.destroy = function () {
    const command = this._command;
    command.vertexArray = command.vertexArray && command.vertexArray.destroy();
    command.shaderProgram =
      command.shaderProgram && command.shaderProgram.destroy();
    this._cubeMap = this._cubeMap && this._cubeMap.destroy();
    return destroyObject(this);
  };

  /**
   * A ParticleEmitter that emits particles within a sphere.
   * Particles will be positioned randomly within the sphere and have initial velocities emanating from the center of the sphere.
   *
   * @alias SphereEmitter
   * @constructor
   *
   * @param {Number} [radius=1.0] The radius of the sphere in meters.
   */
  function SphereEmitter(radius) {
    radius = defaultValue(radius, 1.0);

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number.greaterThan("radius", radius, 0.0);
    //>>includeEnd('debug');

    this._radius = defaultValue(radius, 1.0);
  }

  Object.defineProperties(SphereEmitter.prototype, {
    /**
     * The radius of the sphere in meters.
     * @memberof SphereEmitter.prototype
     * @type {Number}
     * @default 1.0
     */
    radius: {
      get: function () {
        return this._radius;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number.greaterThan("value", value, 0.0);
        //>>includeEnd('debug');
        this._radius = value;
      },
    },
  });

  /**
   * Initializes the given {Particle} by setting it's position and velocity.
   *
   * @private
   * @param {Particle} particle The particle to initialize
   */
  SphereEmitter.prototype.emit = function (particle) {
    const theta = CesiumMath.randomBetween(0.0, CesiumMath.TWO_PI);
    const phi = CesiumMath.randomBetween(0.0, CesiumMath.PI);
    const rad = CesiumMath.randomBetween(0.0, this._radius);

    const x = rad * Math.cos(theta) * Math.sin(phi);
    const y = rad * Math.sin(theta) * Math.sin(phi);
    const z = rad * Math.cos(phi);

    particle.position = Cartesian3.fromElements(x, y, z, particle.position);
    particle.velocity = Cartesian3.normalize(
      particle.position,
      particle.velocity
    );
  };

  /**
   * An expression for a style applied to a {@link Cesium3DTileset}.
   * <p>
   * Derived classes of this interface evaluate expressions in the
   * {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/Styling|3D Tiles Styling language}.
   * </p>
   * <p>
   * This type describes an interface and is not intended to be instantiated directly.
   * </p>
   *
   * @alias StyleExpression
   * @constructor
   *
   * @see Expression
   * @see ConditionsExpression
   */
  function StyleExpression() {}

  /**
   * Evaluates the result of an expression, optionally using the provided feature's properties. If the result of
   * the expression in the
   * {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/Styling|3D Tiles Styling language}
   * is of type <code>Boolean</code>, <code>Number</code>, or <code>String</code>, the corresponding JavaScript
   * primitive type will be returned. If the result is a <code>RegExp</code>, a Javascript <code>RegExp</code>
   * object will be returned. If the result is a <code>Cartesian2</code>, <code>Cartesian3</code>, or <code>Cartesian4</code>,
   * a {@link Cartesian2}, {@link Cartesian3}, or {@link Cartesian4} object will be returned. If the <code>result</code> argument is
   * a {@link Color}, the {@link Cartesian4} value is converted to a {@link Color} and then returned.
   *
   * @param {Cesium3DTileFeature} feature The feature whose properties may be used as variables in the expression.
   * @param {Object} [result] The object onto which to store the result.
   * @returns {Boolean|Number|String|RegExp|Cartesian2|Cartesian3|Cartesian4|Color} The result of evaluating the expression.
   */
  StyleExpression.prototype.evaluate = function (feature, result) {
    DeveloperError.throwInstantiationError();
  };

  /**
   * Evaluates the result of a Color expression, optionally using the provided feature's properties.
   * <p>
   * This is equivalent to {@link StyleExpression#evaluate} but always returns a {@link Color} object.
   * </p>
   *
   * @param {Cesium3DTileFeature} feature The feature whose properties may be used as variables in the expression.
   * @param {Color} [result] The object in which to store the result.
   * @returns {Color} The modified result parameter or a new Color instance if one was not provided.
   */
  StyleExpression.prototype.evaluateColor = function (feature, result) {
    DeveloperError.throwInstantiationError();
  };

  /**
   * Gets the shader function for this expression.
   * Returns undefined if the shader function can't be generated from this expression.
   *
   * @param {String} functionSignature Signature of the generated function.
   * @param {Object} variableSubstitutionMap Maps variable names to shader variable names.
   * @param {Object} shaderState Stores information about the generated shader function, including whether it is translucent.
   * @param {String} returnType The return type of the generated function.
   *
   * @returns {String} The shader function.
   *
   * @private
   */
  StyleExpression.prototype.getShaderFunction = function (
    functionSignature,
    variableSubstitutionMap,
    shaderState,
    returnType
  ) {
    DeveloperError.throwInstantiationError();
  };

  /**
   * Gets the variables used by the expression.
   *
   * @returns {String[]} The variables used by the expression.
   *
   * @private
   */
  StyleExpression.prototype.getVariables = function () {
    DeveloperError.throwInstantiationError();
  };

  //This file is automatically rebuilt by the Cesium build process.
  var SunFS = "uniform sampler2D u_texture;\n\
varying vec2 v_textureCoordinates;\n\
void main()\n\
{\n\
vec4 color = texture2D(u_texture, v_textureCoordinates);\n\
gl_FragColor = czm_gammaCorrect(color);\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var SunTextureFS = "uniform float u_radiusTS;\n\
varying vec2 v_textureCoordinates;\n\
vec2 rotate(vec2 p, vec2 direction)\n\
{\n\
return vec2(p.x * direction.x - p.y * direction.y, p.x * direction.y + p.y * direction.x);\n\
}\n\
vec4 addBurst(vec2 position, vec2 direction, float lengthScalar)\n\
{\n\
vec2 rotatedPosition = rotate(position, direction) * vec2(25.0, 0.75);\n\
float radius = length(rotatedPosition) * lengthScalar;\n\
float burst = 1.0 - smoothstep(0.0, 0.55, radius);\n\
return vec4(burst);\n\
}\n\
void main()\n\
{\n\
float lengthScalar = 2.0 / sqrt(2.0);\n\
vec2 position = v_textureCoordinates - vec2(0.5);\n\
float radius = length(position) * lengthScalar;\n\
float surface = step(radius, u_radiusTS);\n\
vec4 color = vec4(vec2(1.0), surface + 0.2, surface);\n\
float glow = 1.0 - smoothstep(0.0, 0.55, radius);\n\
color.ba += mix(vec2(0.0), vec2(1.0), glow) * 0.75;\n\
vec4 burst = vec4(0.0);\n\
burst += 0.4 * addBurst(position, vec2(0.38942,  0.92106), lengthScalar);\n\
burst += 0.4 * addBurst(position, vec2(0.99235,  0.12348), lengthScalar);\n\
burst += 0.4 * addBurst(position, vec2(0.60327, -0.79754), lengthScalar);\n\
burst += 0.3 * addBurst(position, vec2(0.31457,  0.94924), lengthScalar);\n\
burst += 0.3 * addBurst(position, vec2(0.97931,  0.20239), lengthScalar);\n\
burst += 0.3 * addBurst(position, vec2(0.66507, -0.74678), lengthScalar);\n\
color += clamp(burst, vec4(0.0), vec4(1.0)) * 0.15;\n\
gl_FragColor = clamp(color, vec4(0.0), vec4(1.0));\n\
}\n\
";

  //This file is automatically rebuilt by the Cesium build process.
  var SunVS = "attribute vec2 direction;\n\
uniform float u_size;\n\
varying vec2 v_textureCoordinates;\n\
void main()\n\
{\n\
vec4 position;\n\
if (czm_morphTime == 1.0)\n\
{\n\
position = vec4(czm_sunPositionWC, 1.0);\n\
}\n\
else\n\
{\n\
position = vec4(czm_sunPositionColumbusView.zxy, 1.0);\n\
}\n\
vec4 positionEC = czm_view * position;\n\
vec4 positionWC = czm_eyeToWindowCoordinates(positionEC);\n\
vec2 halfSize = vec2(u_size * 0.5);\n\
halfSize *= ((direction * 2.0) - 1.0);\n\
gl_Position = czm_viewportOrthographic * vec4(positionWC.xy + halfSize, -positionWC.z, 1.0);\n\
v_textureCoordinates = direction;\n\
}\n\
";

  /**
   * Draws a sun billboard.
   * <p>This is only supported in 3D and Columbus view.</p>
   *
   * @alias Sun
   * @constructor
   *
   *
   * @example
   * scene.sun = new Cesium.Sun();
   *
   * @see Scene#sun
   */
  function Sun() {
    /**
     * Determines if the sun will be shown.
     *
     * @type {Boolean}
     * @default true
     */
    this.show = true;

    this._drawCommand = new DrawCommand({
      primitiveType: PrimitiveType$1.TRIANGLES,
      boundingVolume: new BoundingSphere(),
      owner: this,
    });
    this._commands = {
      drawCommand: this._drawCommand,
      computeCommand: undefined,
    };
    this._boundingVolume = new BoundingSphere();
    this._boundingVolume2D = new BoundingSphere();

    this._texture = undefined;
    this._drawingBufferWidth = undefined;
    this._drawingBufferHeight = undefined;
    this._radiusTS = undefined;
    this._size = undefined;

    this.glowFactor = 1.0;
    this._glowFactorDirty = false;

    this._useHdr = undefined;

    const that = this;
    this._uniformMap = {
      u_texture: function () {
        return that._texture;
      },
      u_size: function () {
        return that._size;
      },
    };
  }

  Object.defineProperties(Sun.prototype, {
    /**
     * Gets or sets a number that controls how "bright" the Sun's lens flare appears
     * to be.  Zero shows just the Sun's disc without any flare.
     * Use larger values for a more pronounced flare around the Sun.
     *
     * @memberof Sun.prototype
     * @type {Number}
     * @default 1.0
     */
    glowFactor: {
      get: function () {
        return this._glowFactor;
      },
      set: function (glowFactor) {
        glowFactor = Math.max(glowFactor, 0.0);
        this._glowFactor = glowFactor;
        this._glowFactorDirty = true;
      },
    },
  });

  const scratchPositionWC = new Cartesian2();
  const scratchLimbWC = new Cartesian2();
  const scratchPositionEC = new Cartesian4();
  const scratchCartesian4 = new Cartesian4();

  /**
   * @private
   */
  Sun.prototype.update = function (frameState, passState, useHdr) {
    if (!this.show) {
      return undefined;
    }

    const mode = frameState.mode;
    if (mode === SceneMode$1.SCENE2D || mode === SceneMode$1.MORPHING) {
      return undefined;
    }

    if (!frameState.passes.render) {
      return undefined;
    }

    const context = frameState.context;
    const drawingBufferWidth = passState.viewport.width;
    const drawingBufferHeight = passState.viewport.height;

    if (
      !defined(this._texture) ||
      drawingBufferWidth !== this._drawingBufferWidth ||
      drawingBufferHeight !== this._drawingBufferHeight ||
      this._glowFactorDirty ||
      useHdr !== this._useHdr
    ) {
      this._texture = this._texture && this._texture.destroy();
      this._drawingBufferWidth = drawingBufferWidth;
      this._drawingBufferHeight = drawingBufferHeight;
      this._glowFactorDirty = false;
      this._useHdr = useHdr;

      let size = Math.max(drawingBufferWidth, drawingBufferHeight);
      size = Math.pow(2.0, Math.ceil(Math.log(size) / Math.log(2.0)) - 2.0);

      // The size computed above can be less than 1.0 if size < 4.0. This will probably
      // never happen in practice, but does in the tests. Clamp to 1.0 to prevent WebGL
      // errors in the tests.
      size = Math.max(1.0, size);

      const pixelDatatype = useHdr
        ? context.halfFloatingPointTexture
          ? PixelDatatype$1.HALF_FLOAT
          : PixelDatatype$1.FLOAT
        : PixelDatatype$1.UNSIGNED_BYTE;
      this._texture = new Texture({
        context: context,
        width: size,
        height: size,
        pixelFormat: PixelFormat$1.RGBA,
        pixelDatatype: pixelDatatype,
      });

      this._glowLengthTS = this._glowFactor * 5.0;
      this._radiusTS = (1.0 / (1.0 + 2.0 * this._glowLengthTS)) * 0.5;

      const that = this;
      const uniformMap = {
        u_radiusTS: function () {
          return that._radiusTS;
        },
      };

      this._commands.computeCommand = new ComputeCommand({
        fragmentShaderSource: SunTextureFS,
        outputTexture: this._texture,
        uniformMap: uniformMap,
        persists: false,
        owner: this,
        postExecute: function () {
          that._commands.computeCommand = undefined;
        },
      });
    }

    const drawCommand = this._drawCommand;

    if (!defined(drawCommand.vertexArray)) {
      const attributeLocations = {
        direction: 0,
      };

      const directions = new Uint8Array(4 * 2);
      directions[0] = 0;
      directions[1] = 0;

      directions[2] = 255;
      directions[3] = 0.0;

      directions[4] = 255;
      directions[5] = 255;

      directions[6] = 0.0;
      directions[7] = 255;

      const vertexBuffer = Buffer$1.createVertexBuffer({
        context: context,
        typedArray: directions,
        usage: BufferUsage$1.STATIC_DRAW,
      });
      const attributes = [
        {
          index: attributeLocations.direction,
          vertexBuffer: vertexBuffer,
          componentsPerAttribute: 2,
          normalize: true,
          componentDatatype: ComponentDatatype$1.UNSIGNED_BYTE,
        },
      ];
      // Workaround Internet Explorer 11.0.8 lack of TRIANGLE_FAN
      const indexBuffer = Buffer$1.createIndexBuffer({
        context: context,
        typedArray: new Uint16Array([0, 1, 2, 0, 2, 3]),
        usage: BufferUsage$1.STATIC_DRAW,
        indexDatatype: IndexDatatype$1.UNSIGNED_SHORT,
      });
      drawCommand.vertexArray = new VertexArray({
        context: context,
        attributes: attributes,
        indexBuffer: indexBuffer,
      });

      drawCommand.shaderProgram = ShaderProgram.fromCache({
        context: context,
        vertexShaderSource: SunVS,
        fragmentShaderSource: SunFS,
        attributeLocations: attributeLocations,
      });

      drawCommand.renderState = RenderState.fromCache({
        blending: BlendingState$1.ALPHA_BLEND,
      });
      drawCommand.uniformMap = this._uniformMap;
    }

    const sunPosition = context.uniformState.sunPositionWC;
    const sunPositionCV = context.uniformState.sunPositionColumbusView;

    const boundingVolume = this._boundingVolume;
    const boundingVolume2D = this._boundingVolume2D;

    Cartesian3.clone(sunPosition, boundingVolume.center);
    boundingVolume2D.center.x = sunPositionCV.z;
    boundingVolume2D.center.y = sunPositionCV.x;
    boundingVolume2D.center.z = sunPositionCV.y;

    boundingVolume.radius =
      CesiumMath.SOLAR_RADIUS + CesiumMath.SOLAR_RADIUS * this._glowLengthTS;
    boundingVolume2D.radius = boundingVolume.radius;

    if (mode === SceneMode$1.SCENE3D) {
      BoundingSphere.clone(boundingVolume, drawCommand.boundingVolume);
    } else if (mode === SceneMode$1.COLUMBUS_VIEW) {
      BoundingSphere.clone(boundingVolume2D, drawCommand.boundingVolume);
    }

    const position = SceneTransforms.computeActualWgs84Position(
      frameState,
      sunPosition,
      scratchCartesian4
    );

    const dist = Cartesian3.magnitude(
      Cartesian3.subtract(position, frameState.camera.position, scratchCartesian4)
    );
    const projMatrix = context.uniformState.projection;

    const positionEC = scratchPositionEC;
    positionEC.x = 0;
    positionEC.y = 0;
    positionEC.z = -dist;
    positionEC.w = 1;

    const positionCC = Matrix4.multiplyByVector(
      projMatrix,
      positionEC,
      scratchCartesian4
    );
    const positionWC = SceneTransforms.clipToGLWindowCoordinates(
      passState.viewport,
      positionCC,
      scratchPositionWC
    );

    positionEC.x = CesiumMath.SOLAR_RADIUS;
    const limbCC = Matrix4.multiplyByVector(
      projMatrix,
      positionEC,
      scratchCartesian4
    );
    const limbWC = SceneTransforms.clipToGLWindowCoordinates(
      passState.viewport,
      limbCC,
      scratchLimbWC
    );

    this._size = Cartesian2.magnitude(
      Cartesian2.subtract(limbWC, positionWC, scratchCartesian4)
    );
    this._size = 2.0 * this._size * (1.0 + 2.0 * this._glowLengthTS);
    this._size = Math.ceil(this._size);

    return this._commands;
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see Sun#destroy
   */
  Sun.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * sun = sun && sun.destroy();
   *
   *  @see Sun#isDestroyed
   */
  Sun.prototype.destroy = function () {
    const command = this._drawCommand;
    command.vertexArray = command.vertexArray && command.vertexArray.destroy();
    command.shaderProgram =
      command.shaderProgram && command.shaderProgram.destroy();

    this._texture = this._texture && this._texture.destroy();

    return destroyObject(this);
  };

  /**
   * Defines a bounding volume for a tile. This type describes an interface
   * and is not intended to be instantiated directly.
   *
   * @alias TileBoundingVolume
   * @constructor
   *
   * @see TileBoundingRegion
   * @see TileBoundingSphere
   * @see TileOrientedBoundingBox
   *
   * @private
   */
  function TileBoundingVolume() {}

  /**
   * The underlying bounding volume.
   *
   * @type {Object}
   * @readonly
   */
  TileBoundingVolume.prototype.boundingVolume = undefined;

  /**
   * The underlying bounding sphere.
   *
   * @type {BoundingSphere}
   * @readonly
   */
  TileBoundingVolume.prototype.boundingSphere = undefined;

  /**
   * Calculates the distance between the tile and the camera.
   *
   * @param {FrameState} frameState The frame state.
   * @return {Number} The distance between the tile and the camera, in meters.
   *                  Returns 0.0 if the camera is inside the tile.
   */
  TileBoundingVolume.prototype.distanceToCamera = function (frameState) {
    DeveloperError.throwInstantiationError();
  };

  /**
   * Determines which side of a plane this volume is located.
   *
   * @param {Plane} plane The plane to test against.
   * @returns {Intersect} {@link Intersect.INSIDE} if the entire volume is on the side of the plane
   *                      the normal is pointing, {@link Intersect.OUTSIDE} if the entire volume is
   *                      on the opposite side, and {@link Intersect.INTERSECTING} if the volume
   *                      intersects the plane.
   */
  TileBoundingVolume.prototype.intersectPlane = function (plane) {
    DeveloperError.throwInstantiationError();
  };

  /**
   * Creates a debug primitive that shows the outline of the tile bounding
   * volume.
   *
   * @param {Color} color The desired color of the primitive's mesh
   * @return {Primitive}
   */
  TileBoundingVolume.prototype.createDebugVolume = function (color) {
    DeveloperError.throwInstantiationError();
  };

  /**
   * @typedef {Object} TileCoordinatesImageryProvider.ConstructorOptions
   *
   * Initialization options for the TileCoordinatesImageryProvider constructor
   *
   * @property {TilingScheme} [tilingScheme=new GeographicTilingScheme()] The tiling scheme for which to draw tiles.
   * @property {Ellipsoid} [ellipsoid] The ellipsoid.  If the tilingScheme is specified,
   *                    this parameter is ignored and the tiling scheme's ellipsoid is used instead. If neither
   *                    parameter is specified, the WGS84 ellipsoid is used.
   * @property {Color} [color=Color.YELLOW] The color to draw the tile box and label.
   * @property {Number} [tileWidth=256] The width of the tile for level-of-detail selection purposes.
   * @property {Number} [tileHeight=256] The height of the tile for level-of-detail selection purposes.
   */

  /**
   * An {@link ImageryProvider} that draws a box around every rendered tile in the tiling scheme, and draws
   * a label inside it indicating the X, Y, Level coordinates of the tile.  This is mostly useful for
   * debugging terrain and imagery rendering problems.
   *
   * @alias TileCoordinatesImageryProvider
   * @constructor
   *
   * @param {TileCoordinatesImageryProvider.ConstructorOptions} [options] Object describing initialization options
   */
  function TileCoordinatesImageryProvider(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    this._tilingScheme = defined(options.tilingScheme)
      ? options.tilingScheme
      : new GeographicTilingScheme({ ellipsoid: options.ellipsoid });
    this._color = defaultValue(options.color, Color.YELLOW);
    this._errorEvent = new Event();
    this._tileWidth = defaultValue(options.tileWidth, 256);
    this._tileHeight = defaultValue(options.tileHeight, 256);
    this._readyPromise = Promise.resolve(true);

    /**
     * The default alpha blending value of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultAlpha = undefined;

    /**
     * The default alpha blending value on the night side of the globe of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultNightAlpha = undefined;

    /**
     * The default alpha blending value on the day side of the globe of this provider, with 0.0 representing fully transparent and
     * 1.0 representing fully opaque.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultDayAlpha = undefined;

    /**
     * The default brightness of this provider.  1.0 uses the unmodified imagery color.  Less than 1.0
     * makes the imagery darker while greater than 1.0 makes it brighter.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultBrightness = undefined;

    /**
     * The default contrast of this provider.  1.0 uses the unmodified imagery color.  Less than 1.0 reduces
     * the contrast while greater than 1.0 increases it.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultContrast = undefined;

    /**
     * The default hue of this provider in radians. 0.0 uses the unmodified imagery color.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultHue = undefined;

    /**
     * The default saturation of this provider. 1.0 uses the unmodified imagery color. Less than 1.0 reduces the
     * saturation while greater than 1.0 increases it.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultSaturation = undefined;

    /**
     * The default gamma correction to apply to this provider.  1.0 uses the unmodified imagery color.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.defaultGamma = undefined;

    /**
     * The default texture minification filter to apply to this provider.
     *
     * @type {TextureMinificationFilter}
     * @default undefined
     */
    this.defaultMinificationFilter = undefined;

    /**
     * The default texture magnification filter to apply to this provider.
     *
     * @type {TextureMagnificationFilter}
     * @default undefined
     */
    this.defaultMagnificationFilter = undefined;
  }

  Object.defineProperties(TileCoordinatesImageryProvider.prototype, {
    /**
     * Gets the proxy used by this provider.
     * @memberof TileCoordinatesImageryProvider.prototype
     * @type {Proxy}
     * @readonly
     */
    proxy: {
      get: function () {
        return undefined;
      },
    },

    /**
     * Gets the width of each tile, in pixels. This function should
     * not be called before {@link TileCoordinatesImageryProvider#ready} returns true.
     * @memberof TileCoordinatesImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    tileWidth: {
      get: function () {
        return this._tileWidth;
      },
    },

    /**
     * Gets the height of each tile, in pixels.  This function should
     * not be called before {@link TileCoordinatesImageryProvider#ready} returns true.
     * @memberof TileCoordinatesImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    tileHeight: {
      get: function () {
        return this._tileHeight;
      },
    },

    /**
     * Gets the maximum level-of-detail that can be requested.  This function should
     * not be called before {@link TileCoordinatesImageryProvider#ready} returns true.
     * @memberof TileCoordinatesImageryProvider.prototype
     * @type {Number|undefined}
     * @readonly
     */
    maximumLevel: {
      get: function () {
        return undefined;
      },
    },

    /**
     * Gets the minimum level-of-detail that can be requested.  This function should
     * not be called before {@link TileCoordinatesImageryProvider#ready} returns true.
     * @memberof TileCoordinatesImageryProvider.prototype
     * @type {Number}
     * @readonly
     */
    minimumLevel: {
      get: function () {
        return undefined;
      },
    },

    /**
     * Gets the tiling scheme used by this provider.  This function should
     * not be called before {@link TileCoordinatesImageryProvider#ready} returns true.
     * @memberof TileCoordinatesImageryProvider.prototype
     * @type {TilingScheme}
     * @readonly
     */
    tilingScheme: {
      get: function () {
        return this._tilingScheme;
      },
    },

    /**
     * Gets the rectangle, in radians, of the imagery provided by this instance.  This function should
     * not be called before {@link TileCoordinatesImageryProvider#ready} returns true.
     * @memberof TileCoordinatesImageryProvider.prototype
     * @type {Rectangle}
     * @readonly
     */
    rectangle: {
      get: function () {
        return this._tilingScheme.rectangle;
      },
    },

    /**
     * Gets the tile discard policy.  If not undefined, the discard policy is responsible
     * for filtering out "missing" tiles via its shouldDiscardImage function.  If this function
     * returns undefined, no tiles are filtered.  This function should
     * not be called before {@link TileCoordinatesImageryProvider#ready} returns true.
     * @memberof TileCoordinatesImageryProvider.prototype
     * @type {TileDiscardPolicy}
     * @readonly
     */
    tileDiscardPolicy: {
      get: function () {
        return undefined;
      },
    },

    /**
     * Gets an event that is raised when the imagery provider encounters an asynchronous error.  By subscribing
     * to the event, you will be notified of the error and can potentially recover from it.  Event listeners
     * are passed an instance of {@link TileProviderError}.
     * @memberof TileCoordinatesImageryProvider.prototype
     * @type {Event}
     * @readonly
     */
    errorEvent: {
      get: function () {
        return this._errorEvent;
      },
    },

    /**
     * Gets a value indicating whether or not the provider is ready for use.
     * @memberof TileCoordinatesImageryProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    ready: {
      get: function () {
        return true;
      },
    },

    /**
     * Gets a promise that resolves to true when the provider is ready for use.
     * @memberof TileCoordinatesImageryProvider.prototype
     * @type {Promise.<Boolean>}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._readyPromise;
      },
    },

    /**
     * Gets the credit to display when this imagery provider is active.  Typically this is used to credit
     * the source of the imagery.  This function should not be called before {@link TileCoordinatesImageryProvider#ready} returns true.
     * @memberof TileCoordinatesImageryProvider.prototype
     * @type {Credit}
     * @readonly
     */
    credit: {
      get: function () {
        return undefined;
      },
    },

    /**
     * Gets a value indicating whether or not the images provided by this imagery provider
     * include an alpha channel.  If this property is false, an alpha channel, if present, will
     * be ignored.  If this property is true, any images without an alpha channel will be treated
     * as if their alpha is 1.0 everywhere.  Setting this property to false reduces memory usage
     * and texture upload time.
     * @memberof TileCoordinatesImageryProvider.prototype
     * @type {Boolean}
     * @readonly
     */
    hasAlphaChannel: {
      get: function () {
        return true;
      },
    },
  });

  /**
   * Gets the credits to be displayed when a given tile is displayed.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level;
   * @returns {Credit[]} The credits to be displayed when the tile is displayed.
   *
   * @exception {DeveloperError} <code>getTileCredits</code> must not be called before the imagery provider is ready.
   */
  TileCoordinatesImageryProvider.prototype.getTileCredits = function (
    x,
    y,
    level
  ) {
    return undefined;
  };

  /**
   * Requests the image for a given tile.  This function should
   * not be called before {@link TileCoordinatesImageryProvider#ready} returns true.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level.
   * @param {Request} [request] The request object. Intended for internal use only.
   * @returns {Promise.<HTMLCanvasElement>} The resolved image as a Canvas DOM object.
   */
  TileCoordinatesImageryProvider.prototype.requestImage = function (
    x,
    y,
    level,
    request
  ) {
    const canvas = document.createElement("canvas");
    canvas.width = 256;
    canvas.height = 256;
    const context = canvas.getContext("2d");

    const cssColor = this._color.toCssColorString();

    context.strokeStyle = cssColor;
    context.lineWidth = 2;
    context.strokeRect(1, 1, 255, 255);

    context.font = "bold 25px Arial";
    context.textAlign = "center";
    context.fillStyle = cssColor;
    context.fillText(`L: ${level}`, 124, 86);
    context.fillText(`X: ${x}`, 124, 136);
    context.fillText(`Y: ${y}`, 124, 186);

    return Promise.resolve(canvas);
  };

  /**
   * Picking features is not currently supported by this imagery provider, so this function simply returns
   * undefined.
   *
   * @param {Number} x The tile X coordinate.
   * @param {Number} y The tile Y coordinate.
   * @param {Number} level The tile level.
   * @param {Number} longitude The longitude at which to pick features.
   * @param {Number} latitude  The latitude at which to pick features.
   * @return {undefined} Undefined since picking is not supported.
   */
  TileCoordinatesImageryProvider.prototype.pickFeatures = function (
    x,
    y,
    level,
    longitude,
    latitude
  ) {
    return undefined;
  };

  /**
   * A policy for discarding tile images according to some criteria.  This type describes an
   * interface and is not intended to be instantiated directly.
   *
   * @alias TileDiscardPolicy
   * @constructor
   *
   * @see DiscardMissingTileImagePolicy
   * @see NeverTileDiscardPolicy
   */
  function TileDiscardPolicy(options) {
    DeveloperError.throwInstantiationError();
  }

  /**
   * Determines if the discard policy is ready to process images.
   * @function
   *
   * @returns {Boolean} True if the discard policy is ready to process images; otherwise, false.
   */
  TileDiscardPolicy.prototype.isReady = DeveloperError.throwInstantiationError;

  /**
   * Given a tile image, decide whether to discard that image.
   * @function
   *
   * @param {HTMLImageElement} image An image to test.
   * @returns {Boolean} True if the image should be discarded; otherwise, false.
   */
  TileDiscardPolicy.prototype.shouldDiscardImage =
    DeveloperError.throwInstantiationError;

  /**
   * @private
   */
  const TileState = {
    START: 0,
    LOADING: 1,
    READY: 2,
    UPSAMPLED_ONLY: 3,
  };
  var TileState$1 = Object.freeze(TileState);

  /**
   * Provides playback of time-dynamic point cloud data.
   * <p>
   * Point cloud frames are prefetched in intervals determined by the average frame load time and the current clock speed.
   * If intermediate frames cannot be loaded in time to meet playback speed, they will be skipped. If frames are sufficiently
   * small or the clock is sufficiently slow then no frames will be skipped.
   * </p>
   *
   * @alias TimeDynamicPointCloud
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Clock} options.clock A {@link Clock} instance that is used when determining the value for the time dimension.
   * @param {TimeIntervalCollection} options.intervals A {@link TimeIntervalCollection} with its data property being an object containing a <code>uri</code> to a 3D Tiles Point Cloud tile and an optional <code>transform</code>.
   * @param {Boolean} [options.show=true] Determines if the point cloud will be shown.
   * @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] A 4x4 transformation matrix that transforms the point cloud.
   * @param {ShadowMode} [options.shadows=ShadowMode.ENABLED] Determines whether the point cloud casts or receives shadows from light sources.
   * @param {Number} [options.maximumMemoryUsage=256] The maximum amount of memory in MB that can be used by the point cloud.
   * @param {Object} [options.shading] Options for constructing a {@link PointCloudShading} object to control point attenuation and eye dome lighting.
   * @param {Cesium3DTileStyle} [options.style] The style, defined using the {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/Styling|3D Tiles Styling language}, applied to each point in the point cloud.
   * @param {ClippingPlaneCollection} [options.clippingPlanes] The {@link ClippingPlaneCollection} used to selectively disable rendering the point cloud.
   */
  function TimeDynamicPointCloud(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.clock", options.clock);
    Check.typeOf.object("options.intervals", options.intervals);
    //>>includeEnd('debug');

    /**
     * Determines if the point cloud will be shown.
     *
     * @type {Boolean}
     * @default true
     */
    this.show = defaultValue(options.show, true);

    /**
     * A 4x4 transformation matrix that transforms the point cloud.
     *
     * @type {Matrix4}
     * @default Matrix4.IDENTITY
     */
    this.modelMatrix = Matrix4.clone(
      defaultValue(options.modelMatrix, Matrix4.IDENTITY)
    );

    /**
     * Determines whether the point cloud casts or receives shadows from light sources.
     * <p>
     * Enabling shadows has a performance impact. A point cloud that casts shadows must be rendered twice, once from the camera and again from the light's point of view.
     * </p>
     * <p>
     * Shadows are rendered only when {@link Viewer#shadows} is <code>true</code>.
     * </p>
     *
     * @type {ShadowMode}
     * @default ShadowMode.ENABLED
     */
    this.shadows = defaultValue(options.shadows, ShadowMode$1.ENABLED);

    /**
     * The maximum amount of GPU memory (in MB) that may be used to cache point cloud frames.
     * <p>
     * Frames that are not being loaded or rendered are unloaded to enforce this.
     * </p>
     * <p>
     * If decreasing this value results in unloading tiles, the tiles are unloaded the next frame.
     * </p>
     *
     * @type {Number}
     * @default 256
     *
     * @see TimeDynamicPointCloud#totalMemoryUsageInBytes
     */
    this.maximumMemoryUsage = defaultValue(options.maximumMemoryUsage, 256);

    /**
     * Options for controlling point size based on geometric error and eye dome lighting.
     * @type {PointCloudShading}
     */
    this.shading = new PointCloudShading(options.shading);

    /**
     * The style, defined using the
     * {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/Styling|3D Tiles Styling language},
     * applied to each point in the point cloud.
     * <p>
     * Assign <code>undefined</code> to remove the style, which will restore the visual
     * appearance of the point cloud to its default when no style was applied.
     * </p>
     *
     * @type {Cesium3DTileStyle}
     *
     * @example
     * pointCloud.style = new Cesium.Cesium3DTileStyle({
     *    color : {
     *        conditions : [
     *            ['${Classification} === 0', 'color("purple", 0.5)'],
     *            ['${Classification} === 1', 'color("red")'],
     *            ['true', '${COLOR}']
     *        ]
     *    },
     *    show : '${Classification} !== 2'
     * });
     *
     * @see {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/Styling|3D Tiles Styling language}
     */
    this.style = options.style;

    /**
     * The event fired to indicate that a frame failed to load. A frame may fail to load if the
     * request for its uri fails or processing fails due to invalid content.
     * <p>
     * If there are no event listeners, error messages will be logged to the console.
     * </p>
     * <p>
     * The error object passed to the listener contains two properties:
     * <ul>
     * <li><code>uri</code>: the uri of the failed frame.</li>
     * <li><code>message</code>: the error message.</li>
     * </ul>
     *
     * @type {Event}
     * @default new Event()
     *
     * @example
     * pointCloud.frameFailed.addEventListener(function(error) {
     *     console.log(`An error occurred loading frame: ${error.uri}`);
     *     console.log(`Error: ${error.message}`);
     * });
     */
    this.frameFailed = new Event();

    /**
     * The event fired to indicate that a new frame was rendered.
     * <p>
     * The time dynamic point cloud {@link TimeDynamicPointCloud} is passed to the event listener.
     * </p>
     * @type {Event}
     * @default new Event()
     *
     * @example
     * pointCloud.frameChanged.addEventListener(function(timeDynamicPointCloud) {
     *     viewer.camera.viewBoundingSphere(timeDynamicPointCloud.boundingSphere);
     * });
     */
    this.frameChanged = new Event();

    this._clock = options.clock;
    this._intervals = options.intervals;
    this._clippingPlanes = undefined;
    this.clippingPlanes = options.clippingPlanes; // Call setter
    this._pointCloudEyeDomeLighting = new PointCloudEyeDomeLighting();
    this._loadTimestamp = undefined;
    this._clippingPlanesState = 0;
    this._styleDirty = false;
    this._pickId = undefined;
    this._totalMemoryUsageInBytes = 0;
    this._frames = [];
    this._previousInterval = undefined;
    this._nextInterval = undefined;
    this._lastRenderedFrame = undefined;
    this._clockMultiplier = 0.0;
    this._resolveReadyPromise = undefined;
    const that = this;
    this._readyPromise = new Promise(function (resolve) {
      that._resolveReadyPromise = resolve;
    });

    // For calculating average load time of the last N frames
    this._runningSum = 0.0;
    this._runningLength = 0;
    this._runningIndex = 0;
    this._runningSamples = new Array(5).fill(0.0);
    this._runningAverage = 0.0;
  }

  Object.defineProperties(TimeDynamicPointCloud.prototype, {
    /**
     * The {@link ClippingPlaneCollection} used to selectively disable rendering the point cloud.
     *
     * @memberof TimeDynamicPointCloud.prototype
     *
     * @type {ClippingPlaneCollection}
     */
    clippingPlanes: {
      get: function () {
        return this._clippingPlanes;
      },
      set: function (value) {
        ClippingPlaneCollection.setOwner(value, this, "_clippingPlanes");
      },
    },

    /**
     * The total amount of GPU memory in bytes used by the point cloud.
     *
     * @memberof TimeDynamicPointCloud.prototype
     *
     * @type {Number}
     * @readonly
     *
     * @see TimeDynamicPointCloud#maximumMemoryUsage
     */
    totalMemoryUsageInBytes: {
      get: function () {
        return this._totalMemoryUsageInBytes;
      },
    },

    /**
     * The bounding sphere of the frame being rendered. Returns <code>undefined</code> if no frame is being rendered.
     *
     * @memberof TimeDynamicPointCloud.prototype
     *
     * @type {BoundingSphere}
     * @readonly
     */
    boundingSphere: {
      get: function () {
        if (defined(this._lastRenderedFrame)) {
          return this._lastRenderedFrame.pointCloud.boundingSphere;
        }
        return undefined;
      },
    },

    /**
     * Gets the promise that will be resolved when the point cloud renders a frame for the first time.
     *
     * @memberof TimeDynamicPointCloud.prototype
     *
     * @type {Promise.<TimeDynamicPointCloud>}
     * @readonly
     */
    readyPromise: {
      get: function () {
        return this._readyPromise;
      },
    },
  });

  function getFragmentShaderLoaded(fs) {
    return `uniform vec4 czm_pickColor;\n${fs}`;
  }

  function getUniformMapLoaded(stream) {
    return function (uniformMap) {
      return combine$2(uniformMap, {
        czm_pickColor: function () {
          return stream._pickId.color;
        },
      });
    };
  }

  function getPickIdLoaded() {
    return "czm_pickColor";
  }

  /**
   * Marks the point cloud's {@link TimeDynamicPointCloud#style} as dirty, which forces all
   * points to re-evaluate the style in the next frame.
   */
  TimeDynamicPointCloud.prototype.makeStyleDirty = function () {
    this._styleDirty = true;
  };

  /**
   * Exposed for testing.
   *
   * @private
   */
  TimeDynamicPointCloud.prototype._getAverageLoadTime = function () {
    if (this._runningLength === 0) {
      // Before any frames have loaded make a best guess about the average load time
      return 0.05;
    }
    return this._runningAverage;
  };

  const scratchDate = new JulianDate();

  function getClockMultiplier(that) {
    const clock = that._clock;
    const isAnimating = clock.canAnimate && clock.shouldAnimate;
    const multiplier = clock.multiplier;
    return isAnimating ? multiplier : 0.0;
  }

  function getIntervalIndex(that, interval) {
    return that._intervals.indexOf(interval.start);
  }

  function getNextInterval(that, currentInterval) {
    const intervals = that._intervals;
    const clock = that._clock;
    const multiplier = getClockMultiplier(that);

    if (multiplier === 0.0) {
      return undefined;
    }

    const averageLoadTime = that._getAverageLoadTime();
    const time = JulianDate.addSeconds(
      clock.currentTime,
      averageLoadTime * multiplier,
      scratchDate
    );
    let index = intervals.indexOf(time);

    const currentIndex = getIntervalIndex(that, currentInterval);
    if (index === currentIndex) {
      if (multiplier >= 0) {
        ++index;
      } else {
        --index;
      }
    }

    // Returns undefined if not in range
    return intervals.get(index);
  }

  function getCurrentInterval(that) {
    const intervals = that._intervals;
    const clock = that._clock;
    const time = clock.currentTime;
    const index = intervals.indexOf(time);

    // Returns undefined if not in range
    return intervals.get(index);
  }

  function reachedInterval(that, currentInterval, nextInterval) {
    const multiplier = getClockMultiplier(that);
    const currentIndex = getIntervalIndex(that, currentInterval);
    const nextIndex = getIntervalIndex(that, nextInterval);

    if (multiplier >= 0) {
      return currentIndex >= nextIndex;
    }
    return currentIndex <= nextIndex;
  }

  function handleFrameFailure(that, uri) {
    return function (error) {
      const message = defined(error.message) ? error.message : error.toString();
      if (that.frameFailed.numberOfListeners > 0) {
        that.frameFailed.raiseEvent({
          uri: uri,
          message: message,
        });
      } else {
        console.log(`A frame failed to load: ${uri}`);
        console.log(`Error: ${message}`);
      }
    };
  }

  function requestFrame(that, interval, frameState) {
    const index = getIntervalIndex(that, interval);
    const frames = that._frames;
    let frame = frames[index];
    if (!defined(frame)) {
      const transformArray = interval.data.transform;
      const transform = defined(transformArray)
        ? Matrix4.fromArray(transformArray)
        : undefined;
      const uri = interval.data.uri;
      frame = {
        pointCloud: undefined,
        transform: transform,
        timestamp: getTimestamp$1(),
        sequential: true,
        ready: false,
        touchedFrameNumber: frameState.frameNumber,
      };
      frames[index] = frame;
      Resource.fetchArrayBuffer({
        url: uri,
      })
        .then(function (arrayBuffer) {
          // PERFORMANCE_IDEA: share a memory pool, render states, shaders, and other resources among all
          // frames. Each frame just needs an index/offset into the pool.
          frame.pointCloud = new PointCloud({
            arrayBuffer: arrayBuffer,
            cull: true,
            fragmentShaderLoaded: getFragmentShaderLoaded,
            uniformMapLoaded: getUniformMapLoaded(that),
            pickIdLoaded: getPickIdLoaded,
          });
          return frame.pointCloud.readyPromise;
        })
        .catch(handleFrameFailure(that, uri));
    }
    return frame;
  }

  function updateAverageLoadTime(that, loadTime) {
    that._runningSum += loadTime;
    that._runningSum -= that._runningSamples[that._runningIndex];
    that._runningSamples[that._runningIndex] = loadTime;
    that._runningLength = Math.min(
      that._runningLength + 1,
      that._runningSamples.length
    );
    that._runningIndex = (that._runningIndex + 1) % that._runningSamples.length;
    that._runningAverage = that._runningSum / that._runningLength;
  }

  function prepareFrame(that, frame, updateState, frameState) {
    if (frame.touchedFrameNumber < frameState.frameNumber - 1) {
      // If this frame was not loaded in sequential updates then it can't be used it for calculating the average load time.
      // For example: selecting a frame on the timeline, selecting another frame before the request finishes, then selecting this frame later.
      frame.sequential = false;
    }

    const pointCloud = frame.pointCloud;

    if (defined(pointCloud) && !frame.ready) {
      // Call update to prepare renderer resources. Don't render anything yet.
      const commandList = frameState.commandList;
      const lengthBeforeUpdate = commandList.length;
      renderFrame(that, frame, updateState, frameState);

      if (pointCloud.ready) {
        // Point cloud became ready this update
        frame.ready = true;
        that._totalMemoryUsageInBytes += pointCloud.geometryByteLength;
        commandList.length = lengthBeforeUpdate; // Don't allow preparing frame to insert commands.
        if (frame.sequential) {
          // Update the values used to calculate average load time
          const loadTime = (getTimestamp$1() - frame.timestamp) / 1000.0;
          updateAverageLoadTime(that, loadTime);
        }
      }
    }

    frame.touchedFrameNumber = frameState.frameNumber;
  }

  const scratchModelMatrix = new Matrix4();

  function getGeometricError(that, pointCloud) {
    const shading = that.shading;
    if (defined(shading) && defined(shading.baseResolution)) {
      return shading.baseResolution;
    } else if (defined(pointCloud.boundingSphere)) {
      return CesiumMath.cbrt(
        pointCloud.boundingSphere.volume() / pointCloud.pointsLength
      );
    }
    return 0.0;
  }

  function getMaximumAttenuation(that) {
    const shading = that.shading;
    if (defined(shading) && defined(shading.maximumAttenuation)) {
      return shading.maximumAttenuation;
    }

    // Return a hardcoded maximum attenuation. For a tileset this would instead be the maximum screen space error.
    return 10.0;
  }

  const defaultShading = new PointCloudShading();

  function renderFrame(that, frame, updateState, frameState) {
    const shading = defaultValue(that.shading, defaultShading);
    const pointCloud = frame.pointCloud;
    const transform = defaultValue(frame.transform, Matrix4.IDENTITY);
    pointCloud.modelMatrix = Matrix4.multiplyTransformation(
      that.modelMatrix,
      transform,
      scratchModelMatrix
    );
    pointCloud.style = that.style;
    pointCloud.time = updateState.timeSinceLoad;
    pointCloud.shadows = that.shadows;
    pointCloud.clippingPlanes = that._clippingPlanes;
    pointCloud.isClipped = updateState.isClipped;
    pointCloud.attenuation = shading.attenuation;
    pointCloud.backFaceCulling = shading.backFaceCulling;
    pointCloud.normalShading = shading.normalShading;
    pointCloud.geometricError = getGeometricError(that, pointCloud);
    pointCloud.geometricErrorScale = shading.geometricErrorScale;
    pointCloud.maximumAttenuation = getMaximumAttenuation(that);

    pointCloud.update(frameState);
    frame.touchedFrameNumber = frameState.frameNumber;
  }

  function loadFrame(that, interval, updateState, frameState) {
    const frame = requestFrame(that, interval, frameState);
    prepareFrame(that, frame, updateState, frameState);
  }

  function getUnloadCondition(frameState) {
    return function (frame) {
      // Unload all frames that aren't currently being loaded or rendered
      return frame.touchedFrameNumber < frameState.frameNumber;
    };
  }

  function unloadFrames(that, unloadCondition) {
    const frames = that._frames;
    const length = frames.length;
    for (let i = 0; i < length; ++i) {
      const frame = frames[i];
      if (defined(frame)) {
        if (!defined(unloadCondition) || unloadCondition(frame)) {
          const pointCloud = frame.pointCloud;
          if (frame.ready) {
            that._totalMemoryUsageInBytes -= pointCloud.geometryByteLength;
          }
          if (defined(pointCloud)) {
            pointCloud.destroy();
          }
          if (frame === that._lastRenderedFrame) {
            that._lastRenderedFrame = undefined;
          }
          frames[i] = undefined;
        }
      }
    }
  }

  function getFrame(that, interval) {
    const index = getIntervalIndex(that, interval);
    const frame = that._frames[index];
    if (defined(frame) && frame.ready) {
      return frame;
    }
  }

  function updateInterval(that, interval, frame, updateState, frameState) {
    if (defined(frame)) {
      if (frame.ready) {
        return true;
      }
      loadFrame(that, interval, updateState, frameState);
      return frame.ready;
    }
    return false;
  }

  function getNearestReadyInterval(
    that,
    previousInterval,
    currentInterval,
    updateState,
    frameState
  ) {
    let i;
    let interval;
    let frame;
    const intervals = that._intervals;
    const frames = that._frames;
    const currentIndex = getIntervalIndex(that, currentInterval);
    const previousIndex = getIntervalIndex(that, previousInterval);

    if (currentIndex >= previousIndex) {
      // look backwards
      for (i = currentIndex; i >= previousIndex; --i) {
        interval = intervals.get(i);
        frame = frames[i];
        if (updateInterval(that, interval, frame, updateState, frameState)) {
          return interval;
        }
      }
    } else {
      // look forwards
      for (i = currentIndex; i <= previousIndex; ++i) {
        interval = intervals.get(i);
        frame = frames[i];
        if (updateInterval(that, interval, frame, updateState, frameState)) {
          return interval;
        }
      }
    }

    // If no intervals are ready return the previous interval
    return previousInterval;
  }

  function setFramesDirty(that, clippingPlanesDirty, styleDirty) {
    const frames = that._frames;
    const framesLength = frames.length;
    for (let i = 0; i < framesLength; ++i) {
      const frame = frames[i];
      if (defined(frame) && defined(frame.pointCloud)) {
        frame.pointCloud.clippingPlanesDirty = clippingPlanesDirty;
        frame.pointCloud.styleDirty = styleDirty;
      }
    }
  }

  const updateState = {
    timeSinceLoad: 0,
    isClipped: false,
    clippingPlanesDirty: false,
  };

  /**
   * @private
   */
  TimeDynamicPointCloud.prototype.update = function (frameState) {
    if (frameState.mode === SceneMode$1.MORPHING) {
      return;
    }

    if (!this.show) {
      return;
    }

    if (!defined(this._pickId)) {
      this._pickId = frameState.context.createPickId({
        primitive: this,
      });
    }

    if (!defined(this._loadTimestamp)) {
      this._loadTimestamp = JulianDate.clone(frameState.time);
    }

    // For styling
    const timeSinceLoad = Math.max(
      JulianDate.secondsDifference(frameState.time, this._loadTimestamp) * 1000,
      0.0
    );

    // Update clipping planes
    const clippingPlanes = this._clippingPlanes;
    let clippingPlanesState = 0;
    let clippingPlanesDirty = false;
    const isClipped = defined(clippingPlanes) && clippingPlanes.enabled;

    if (isClipped) {
      clippingPlanes.update(frameState);
      clippingPlanesState = clippingPlanes.clippingPlanesState;
    }

    if (this._clippingPlanesState !== clippingPlanesState) {
      this._clippingPlanesState = clippingPlanesState;
      clippingPlanesDirty = true;
    }

    const styleDirty = this._styleDirty;
    this._styleDirty = false;

    if (clippingPlanesDirty || styleDirty) {
      setFramesDirty(this, clippingPlanesDirty, styleDirty);
    }

    updateState.timeSinceLoad = timeSinceLoad;
    updateState.isClipped = isClipped;

    const shading = this.shading;
    const eyeDomeLighting = this._pointCloudEyeDomeLighting;

    const commandList = frameState.commandList;
    const lengthBeforeUpdate = commandList.length;

    let previousInterval = this._previousInterval;
    let nextInterval = this._nextInterval;
    const currentInterval = getCurrentInterval(this);

    if (!defined(currentInterval)) {
      return;
    }

    let clockMultiplierChanged = false;
    const clockMultiplier = getClockMultiplier(this);
    const clockPaused = clockMultiplier === 0;
    if (clockMultiplier !== this._clockMultiplier) {
      clockMultiplierChanged = true;
      this._clockMultiplier = clockMultiplier;
    }

    if (!defined(previousInterval) || clockPaused) {
      previousInterval = currentInterval;
    }

    if (
      !defined(nextInterval) ||
      clockMultiplierChanged ||
      reachedInterval(this, currentInterval, nextInterval)
    ) {
      nextInterval = getNextInterval(this, currentInterval);
    }

    previousInterval = getNearestReadyInterval(
      this,
      previousInterval,
      currentInterval,
      updateState,
      frameState
    );
    let frame = getFrame(this, previousInterval);

    if (!defined(frame)) {
      // The frame is not ready to render. This can happen when the simulation starts or when scrubbing the timeline
      // to a frame that hasn't loaded yet. Just render the last rendered frame in its place until it finishes loading.
      loadFrame(this, previousInterval, updateState, frameState);
      frame = this._lastRenderedFrame;
    }

    if (defined(frame)) {
      renderFrame(this, frame, updateState, frameState);
    }

    if (defined(nextInterval)) {
      // Start loading the next frame
      loadFrame(this, nextInterval, updateState, frameState);
    }

    const that = this;
    if (defined(frame) && !defined(this._lastRenderedFrame)) {
      frameState.afterRender.push(function () {
        that._resolveReadyPromise(that);
      });
    }

    if (defined(frame) && frame !== this._lastRenderedFrame) {
      if (that.frameChanged.numberOfListeners > 0) {
        frameState.afterRender.push(function () {
          that.frameChanged.raiseEvent(that);
        });
      }
    }

    this._previousInterval = previousInterval;
    this._nextInterval = nextInterval;
    this._lastRenderedFrame = frame;

    const totalMemoryUsageInBytes = this._totalMemoryUsageInBytes;
    const maximumMemoryUsageInBytes = this.maximumMemoryUsage * 1024 * 1024;

    if (totalMemoryUsageInBytes > maximumMemoryUsageInBytes) {
      unloadFrames(this, getUnloadCondition(frameState));
    }

    const lengthAfterUpdate = commandList.length;
    const addedCommandsLength = lengthAfterUpdate - lengthBeforeUpdate;

    if (
      defined(shading) &&
      shading.attenuation &&
      shading.eyeDomeLighting &&
      addedCommandsLength > 0
    ) {
      eyeDomeLighting.update(
        frameState,
        lengthBeforeUpdate,
        shading,
        this.boundingSphere
      );
    }
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
   *
   * @see TimeDynamicPointCloud#destroy
   */
  TimeDynamicPointCloud.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @example
   * pointCloud = pointCloud && pointCloud.destroy();
   *
   * @see TimeDynamicPointCloud#isDestroyed
   */
  TimeDynamicPointCloud.prototype.destroy = function () {
    unloadFrames(this);
    this._clippingPlanes = this._clippingPlanes && this._clippingPlanes.destroy();
    this._pickId = this._pickId && this._pickId.destroy();
    return destroyObject(this);
  };

  //This file is automatically rebuilt by the Cesium build process.
  var ViewportQuadFS = "varying vec2 v_textureCoordinates;\n\
void main()\n\
{\n\
czm_materialInput materialInput;\n\
materialInput.s = v_textureCoordinates.s;\n\
materialInput.st = v_textureCoordinates;\n\
materialInput.str = vec3(v_textureCoordinates, 0.0);\n\
materialInput.normalEC = vec3(0.0, 0.0, -1.0);\n\
czm_material material = czm_getMaterial(materialInput);\n\
gl_FragColor = vec4(material.diffuse + material.emission, material.alpha);\n\
}\n\
";

  /**
   * A viewport aligned quad.
   *
   * @alias ViewportQuad
   * @constructor
   *
   * @param {BoundingRectangle} [rectangle] The {@link BoundingRectangle} defining the quad's position within the viewport.
   * @param {Material} [material] The {@link Material} defining the surface appearance of the viewport quad.
   *
   * @example
   * const viewportQuad = new Cesium.ViewportQuad(new Cesium.BoundingRectangle(0, 0, 80, 40));
   * viewportQuad.material.uniforms.color = new Cesium.Color(1.0, 0.0, 0.0, 1.0);
   */
  function ViewportQuad(rectangle, material) {
    /**
     * Determines if the viewport quad primitive will be shown.
     *
     * @type {Boolean}
     * @default true
     */
    this.show = true;

    if (!defined(rectangle)) {
      rectangle = new BoundingRectangle();
    }

    /**
     * The BoundingRectangle defining the quad's position within the viewport.
     *
     * @type {BoundingRectangle}
     *
     * @example
     * viewportQuad.rectangle = new Cesium.BoundingRectangle(0, 0, 80, 40);
     */
    this.rectangle = BoundingRectangle.clone(rectangle);

    if (!defined(material)) {
      material = Material$4.fromType(Material$4.ColorType, {
        color: new Color(1.0, 1.0, 1.0, 1.0),
      });
    }

    /**
     * The surface appearance of the viewport quad.  This can be one of several built-in {@link Material} objects or a custom material, scripted with
     * {@link https://github.com/CesiumGS/cesium/wiki/Fabric|Fabric}.
     * <p>
     * The default material is <code>Material.ColorType</code>.
     * </p>
     *
     * @type Material
     *
     * @example
     * // 1. Change the color of the default material to yellow
     * viewportQuad.material.uniforms.color = new Cesium.Color(1.0, 1.0, 0.0, 1.0);
     *
     * // 2. Change material to horizontal stripes
     * viewportQuad.material = Cesium.Material.fromType(Cesium.Material.StripeType);
     *
     * @see {@link https://github.com/CesiumGS/cesium/wiki/Fabric|Fabric}
     */
    this.material = material;
    this._material = undefined;

    this._overlayCommand = undefined;
    this._rs = undefined;
  }

  /**
   * Called when {@link Viewer} or {@link CesiumWidget} render the scene to
   * get the draw commands needed to render this primitive.
   * <p>
   * Do not call this function directly.  This is documented just to
   * list the exceptions that may be propagated when the scene is rendered:
   * </p>
   *
   * @exception {DeveloperError} this.material must be defined.
   * @exception {DeveloperError} this.rectangle must be defined.
   */
  ViewportQuad.prototype.update = function (frameState) {
    if (!this.show) {
      return;
    }

    //>>includeStart('debug', pragmas.debug);
    if (!defined(this.material)) {
      throw new DeveloperError("this.material must be defined.");
    }
    if (!defined(this.rectangle)) {
      throw new DeveloperError("this.rectangle must be defined.");
    }
    //>>includeEnd('debug');

    const rs = this._rs;
    if (!defined(rs) || !BoundingRectangle.equals(rs.viewport, this.rectangle)) {
      this._rs = RenderState.fromCache({
        blending: BlendingState$1.ALPHA_BLEND,
        viewport: this.rectangle,
      });
    }

    const pass = frameState.passes;
    if (pass.render) {
      const context = frameState.context;

      if (this._material !== this.material || !defined(this._overlayCommand)) {
        // Recompile shader when material changes
        this._material = this.material;

        if (defined(this._overlayCommand)) {
          this._overlayCommand.shaderProgram.destroy();
        }

        const fs = new ShaderSource({
          sources: [this._material.shaderSource, ViewportQuadFS],
        });
        this._overlayCommand = context.createViewportQuadCommand(fs, {
          renderState: this._rs,
          uniformMap: this._material._uniforms,
          owner: this,
        });
        this._overlayCommand.pass = Pass$1.OVERLAY;
      }

      this._material.update(context);

      this._overlayCommand.renderState = this._rs;
      this._overlayCommand.uniformMap = this._material._uniforms;
      frameState.commandList.push(this._overlayCommand);
    }
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} True if this object was destroyed; otherwise, false.
   *
   * @see ViewportQuad#destroy
   */
  ViewportQuad.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   *
   * @example
   * quad = quad && quad.destroy();
   *
   * @see ViewportQuad#isDestroyed
   */
  ViewportQuad.prototype.destroy = function () {
    if (defined(this._overlayCommand)) {
      this._overlayCommand.shaderProgram =
        this._overlayCommand.shaderProgram &&
        this._overlayCommand.shaderProgram.destroy();
    }
    return destroyObject(this);
  };

  /**
   * Computes the final camera location to view a rectangle adjusted for the current terrain.
   * If the terrain does not support availability, the height above the ellipsoid is used.
   *
   * @param {Rectangle} rectangle The rectangle being zoomed to.
   * @param {Scene} scene The scene being used.
   *
   * @returns {Cartographic} The optimal location to place the camera so that the entire rectangle is in view.
   *
   * @private
   */
  function computeFlyToLocationForRectangle(rectangle, scene) {
    const terrainProvider = scene.terrainProvider;
    const mapProjection = scene.mapProjection;
    const ellipsoid = mapProjection.ellipsoid;

    let positionWithoutTerrain;
    const tmp = scene.camera.getRectangleCameraCoordinates(rectangle);
    if (scene.mode === SceneMode$1.SCENE3D) {
      positionWithoutTerrain = ellipsoid.cartesianToCartographic(tmp);
    } else {
      positionWithoutTerrain = mapProjection.unproject(tmp);
    }

    if (!defined(terrainProvider)) {
      return Promise.resolve(positionWithoutTerrain);
    }

    return terrainProvider.readyPromise.then(function () {
      const availability = terrainProvider.availability;

      if (!defined(availability) || scene.mode === SceneMode$1.SCENE2D) {
        return positionWithoutTerrain;
      }

      const cartographics = [
        Rectangle.center(rectangle),
        Rectangle.southeast(rectangle),
        Rectangle.southwest(rectangle),
        Rectangle.northeast(rectangle),
        Rectangle.northwest(rectangle),
      ];

      return computeFlyToLocationForRectangle
        ._sampleTerrainMostDetailed(terrainProvider, cartographics)
        .then(function (positionsOnTerrain) {
          const maxHeight = positionsOnTerrain.reduce(function (
            currentMax,
            item
          ) {
            return Math.max(item.height, currentMax);
          },
          -Number.MAX_VALUE);

          const finalPosition = positionWithoutTerrain;
          finalPosition.height += maxHeight;
          return finalPosition;
        });
    });
  }

  //Exposed for testing.
  computeFlyToLocationForRectangle._sampleTerrainMostDetailed = sampleTerrainMostDetailed;

  const scratchColor$1 = new Color();
  const scratchColorAbove = new Color();
  const scratchColorBelow = new Color();
  const scratchColorBlend = new Color();
  const scratchPackedFloat = new Cartesian4();
  const scratchColorBytes = new Uint8Array(4);

  function lerpEntryColor(height, entryBefore, entryAfter, result) {
    const lerpFactor =
      entryBefore.height === entryAfter.height
        ? 0.0
        : (height - entryBefore.height) /
          (entryAfter.height - entryBefore.height);
    return Color.lerp(entryBefore.color, entryAfter.color, lerpFactor, result);
  }

  function createNewEntry(height, color) {
    return {
      height: height,
      color: Color.clone(color),
    };
  }

  function removeDuplicates(entries) {
    // This function expects entries to be sorted from lowest to highest.

    // Remove entries that have the same height as before and after.
    entries = entries.filter(function (entry, index, array) {
      const hasPrev = index > 0;
      const hasNext = index < array.length - 1;

      const sameHeightAsPrev = hasPrev
        ? entry.height === array[index - 1].height
        : true;
      const sameHeightAsNext = hasNext
        ? entry.height === array[index + 1].height
        : true;

      const keep = !sameHeightAsPrev || !sameHeightAsNext;
      return keep;
    });

    // Remove entries that have the same color as before and after.
    entries = entries.filter(function (entry, index, array) {
      const hasPrev = index > 0;
      const hasNext = index < array.length - 1;

      const sameColorAsPrev = hasPrev
        ? Color.equals(entry.color, array[index - 1].color)
        : false;
      const sameColorAsNext = hasNext
        ? Color.equals(entry.color, array[index + 1].color)
        : false;

      const keep = !sameColorAsPrev || !sameColorAsNext;
      return keep;
    });

    // Also remove entries that have the same height AND color as the entry before.
    entries = entries.filter(function (entry, index, array) {
      const hasPrev = index > 0;

      const sameColorAsPrev = hasPrev
        ? Color.equals(entry.color, array[index - 1].color)
        : false;

      const sameHeightAsPrev = hasPrev
        ? entry.height === array[index - 1].height
        : true;

      const keep = !sameColorAsPrev || !sameHeightAsPrev;
      return keep;
    });

    return entries;
  }

  function preprocess(layers) {
    let i, j;

    const layeredEntries = [];

    const layersLength = layers.length;
    for (i = 0; i < layersLength; i++) {
      const layer = layers[i];
      const entriesOrig = layer.entries;
      const entriesLength = entriesOrig.length;

      //>>includeStart('debug', pragmas.debug);
      if (!Array.isArray(entriesOrig) || entriesLength === 0) {
        throw new DeveloperError("entries must be an array with size > 0.");
      }
      //>>includeEnd('debug');

      let entries = [];

      for (j = 0; j < entriesLength; j++) {
        const entryOrig = entriesOrig[j];

        //>>includeStart('debug', pragmas.debug);
        if (!defined(entryOrig.height)) {
          throw new DeveloperError("entry requires a height.");
        }
        if (!defined(entryOrig.color)) {
          throw new DeveloperError("entry requires a color.");
        }
        //>>includeEnd('debug');

        const height = CesiumMath.clamp(
          entryOrig.height,
          createElevationBandMaterial._minimumHeight,
          createElevationBandMaterial._maximumHeight
        );

        // premultiplied alpha
        const color = Color.clone(entryOrig.color, scratchColor$1);
        color.red *= color.alpha;
        color.green *= color.alpha;
        color.blue *= color.alpha;

        entries.push(createNewEntry(height, color));
      }

      let sortedAscending = true;
      let sortedDescending = true;
      for (j = 0; j < entriesLength - 1; j++) {
        const currEntry = entries[j + 0];
        const nextEntry = entries[j + 1];

        sortedAscending = sortedAscending && currEntry.height <= nextEntry.height;
        sortedDescending =
          sortedDescending && currEntry.height >= nextEntry.height;
      }

      // When the array is fully descending, reverse it.
      if (sortedDescending) {
        entries = entries.reverse();
      } else if (!sortedAscending) {
        // Stable sort from lowest to greatest height.
        mergeSort(entries, function (a, b) {
          return CesiumMath.sign(a.height - b.height);
        });
      }

      let extendDownwards = defaultValue(layer.extendDownwards, false);
      let extendUpwards = defaultValue(layer.extendUpwards, false);

      // Interpret a single entry to extend all the way up and down.
      if (entries.length === 1 && !extendDownwards && !extendUpwards) {
        extendDownwards = true;
        extendUpwards = true;
      }

      if (extendDownwards) {
        entries.splice(
          0,
          0,
          createNewEntry(
            createElevationBandMaterial._minimumHeight,
            entries[0].color
          )
        );
      }
      if (extendUpwards) {
        entries.splice(
          entries.length,
          0,
          createNewEntry(
            createElevationBandMaterial._maximumHeight,
            entries[entries.length - 1].color
          )
        );
      }

      entries = removeDuplicates(entries);

      layeredEntries.push(entries);
    }

    return layeredEntries;
  }

  function createLayeredEntries(layers) {
    // clean up the input data and check for errors
    const layeredEntries = preprocess(layers);

    let entriesAccumNext = [];
    let entriesAccumCurr = [];
    let i;

    function addEntry(height, color) {
      entriesAccumNext.push(createNewEntry(height, color));
    }
    function addBlendEntry(height, a, b) {
      let result = Color.multiplyByScalar(b, 1.0 - a.alpha, scratchColorBlend);
      result = Color.add(result, a, result);
      addEntry(height, result);
    }

    // alpha blend new layers on top of old ones
    const layerLength = layeredEntries.length;
    for (i = 0; i < layerLength; i++) {
      const entries = layeredEntries[i];
      let idx = 0;
      let accumIdx = 0;

      // swap the arrays
      entriesAccumCurr = entriesAccumNext;
      entriesAccumNext = [];

      const entriesLength = entries.length;
      const entriesAccumLength = entriesAccumCurr.length;
      while (idx < entriesLength || accumIdx < entriesAccumLength) {
        const entry = idx < entriesLength ? entries[idx] : undefined;
        const prevEntry = idx > 0 ? entries[idx - 1] : undefined;
        const nextEntry = idx < entriesLength - 1 ? entries[idx + 1] : undefined;

        const entryAccum =
          accumIdx < entriesAccumLength ? entriesAccumCurr[accumIdx] : undefined;
        const prevEntryAccum =
          accumIdx > 0 ? entriesAccumCurr[accumIdx - 1] : undefined;
        const nextEntryAccum =
          accumIdx < entriesAccumLength - 1
            ? entriesAccumCurr[accumIdx + 1]
            : undefined;

        if (
          defined(entry) &&
          defined(entryAccum) &&
          entry.height === entryAccum.height
        ) {
          // New entry directly on top of accum entry
          const isSplitAccum =
            defined(nextEntryAccum) &&
            entryAccum.height === nextEntryAccum.height;
          const isStartAccum = !defined(prevEntryAccum);
          const isEndAccum = !defined(nextEntryAccum);

          const isSplit = defined(nextEntry) && entry.height === nextEntry.height;
          const isStart = !defined(prevEntry);
          const isEnd = !defined(nextEntry);

          if (isSplitAccum) {
            if (isSplit) {
              addBlendEntry(entry.height, entry.color, entryAccum.color);
              addBlendEntry(entry.height, nextEntry.color, nextEntryAccum.color);
            } else if (isStart) {
              addEntry(entry.height, entryAccum.color);
              addBlendEntry(entry.height, entry.color, nextEntryAccum.color);
            } else if (isEnd) {
              addBlendEntry(entry.height, entry.color, entryAccum.color);
              addEntry(entry.height, nextEntryAccum.color);
            } else {
              addBlendEntry(entry.height, entry.color, entryAccum.color);
              addBlendEntry(entry.height, entry.color, nextEntryAccum.color);
            }
          } else if (isStartAccum) {
            if (isSplit) {
              addEntry(entry.height, entry.color);
              addBlendEntry(entry.height, nextEntry.color, entryAccum.color);
            } else if (isEnd) {
              addEntry(entry.height, entry.color);
              addEntry(entry.height, entryAccum.color);
            } else if (isStart) {
              addBlendEntry(entry.height, entry.color, entryAccum.color);
            } else {
              addEntry(entry.height, entry.color);
              addBlendEntry(entry.height, entry.color, entryAccum.color);
            }
          } else if (isEndAccum) {
            if (isSplit) {
              addBlendEntry(entry.height, entry.color, entryAccum.color);
              addEntry(entry.height, nextEntry.color);
            } else if (isStart) {
              addEntry(entry.height, entryAccum.color);
              addEntry(entry.height, entry.color);
            } else if (isEnd) {
              addBlendEntry(entry.height, entry.color, entryAccum.color);
            } else {
              addBlendEntry(entry.height, entry.color, entryAccum.color);
              addEntry(entry.height, entry.color);
            }
          } else {
            // eslint-disable-next-line no-lonely-if
            if (isSplit) {
              addBlendEntry(entry.height, entry.color, entryAccum.color);
              addBlendEntry(entry.height, nextEntry.color, entryAccum.color);
            } else if (isStart) {
              addEntry(entry.height, entryAccum.color);
              addBlendEntry(entry.height, entry.color, entryAccum.color);
            } else if (isEnd) {
              addBlendEntry(entry.height, entry.color, entryAccum.color);
              addEntry(entry.height, entryAccum.color);
            } else {
              addBlendEntry(entry.height, entry.color, entryAccum.color);
            }
          }
          idx += isSplit ? 2 : 1;
          accumIdx += isSplitAccum ? 2 : 1;
        } else if (
          defined(entry) &&
          defined(entryAccum) &&
          defined(prevEntryAccum) &&
          entry.height < entryAccum.height
        ) {
          // New entry between two accum entries
          const colorBelow = lerpEntryColor(
            entry.height,
            prevEntryAccum,
            entryAccum,
            scratchColorBelow
          );

          if (!defined(prevEntry)) {
            addEntry(entry.height, colorBelow);
            addBlendEntry(entry.height, entry.color, colorBelow);
          } else if (!defined(nextEntry)) {
            addBlendEntry(entry.height, entry.color, colorBelow);
            addEntry(entry.height, colorBelow);
          } else {
            addBlendEntry(entry.height, entry.color, colorBelow);
          }
          idx++;
        } else if (
          defined(entryAccum) &&
          defined(entry) &&
          defined(prevEntry) &&
          entryAccum.height < entry.height
        ) {
          // Accum entry between two new entries
          const colorAbove = lerpEntryColor(
            entryAccum.height,
            prevEntry,
            entry,
            scratchColorAbove
          );

          if (!defined(prevEntryAccum)) {
            addEntry(entryAccum.height, colorAbove);
            addBlendEntry(entryAccum.height, colorAbove, entryAccum.color);
          } else if (!defined(nextEntryAccum)) {
            addBlendEntry(entryAccum.height, colorAbove, entryAccum.color);
            addEntry(entryAccum.height, colorAbove);
          } else {
            addBlendEntry(entryAccum.height, colorAbove, entryAccum.color);
          }
          accumIdx++;
        } else if (
          defined(entry) &&
          (!defined(entryAccum) || entry.height < entryAccum.height)
        ) {
          // New entry completely before or completely after accum entries
          if (
            defined(entryAccum) &&
            !defined(prevEntryAccum) &&
            !defined(nextEntry)
          ) {
            // Insert blank gap between last entry and first accum entry
            addEntry(entry.height, entry.color);
            addEntry(entry.height, createElevationBandMaterial._emptyColor);
            addEntry(entryAccum.height, createElevationBandMaterial._emptyColor);
          } else if (
            !defined(entryAccum) &&
            defined(prevEntryAccum) &&
            !defined(prevEntry)
          ) {
            // Insert blank gap between last accum entry and first entry
            addEntry(
              prevEntryAccum.height,
              createElevationBandMaterial._emptyColor
            );
            addEntry(entry.height, createElevationBandMaterial._emptyColor);
            addEntry(entry.height, entry.color);
          } else {
            addEntry(entry.height, entry.color);
          }
          idx++;
        } else if (
          defined(entryAccum) &&
          (!defined(entry) || entryAccum.height < entry.height)
        ) {
          // Accum entry completely before or completely after new entries
          addEntry(entryAccum.height, entryAccum.color);
          accumIdx++;
        }
      }
    }

    // one final cleanup pass in case duplicate colors show up in the final result
    const allEntries = removeDuplicates(entriesAccumNext);
    return allEntries;
  }

  /**
   * @typedef createElevationBandMaterialEntry
   *
   * @property {Number} height The height.
   * @property {Color} color The color at this height.
   */
  /**
   * @typedef createElevationBandMaterialBand
   *
   * @property {createElevationBandMaterialEntry[]} entries A list of elevation entries. They will automatically be sorted from lowest to highest. If there is only one entry and <code>extendsDownards</code> and <code>extendUpwards</code> are both <code>false</code>, they will both be set to <code>true</code>.
   * @property {Boolean} [extendDownwards=false] If <code>true</code>, the band's minimum elevation color will extend infinitely downwards.
   * @property {Boolean} [extendUpwards=false] If <code>true</code>, the band's maximum elevation color will extend infinitely upwards.
   */

  /**
   * Creates a {@link Material} that combines multiple layers of color/gradient bands and maps them to terrain heights.
   *
   * The shader does a binary search over all the heights to find out which colors are above and below a given height, and
   * interpolates between them for the final color. This material supports hundreds of entries relatively cheaply.
   *
   * @function createElevationBandMaterial
   *
   * @param {Object} options Object with the following properties:
   * @param {Scene} options.scene The scene where the visualization is taking place.
   * @param {createElevationBandMaterialBand[]} options.layers A list of bands ordered from lowest to highest precedence.
   * @returns {Material} A new {@link Material} instance.
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Elevation%20Band%20Material.html|Cesium Sandcastle Elevation Band Demo}
   *
   * @example
   * scene.globe.material = Cesium.createElevationBandMaterial({
   *     scene : scene,
   *     layers : [{
   *         entries : [{
   *             height : 4200.0,
   *             color : new Cesium.Color(0.0, 0.0, 0.0, 1.0)
   *         }, {
   *             height : 8848.0,
   *             color : new Cesium.Color(1.0, 1.0, 1.0, 1.0)
   *         }],
   *         extendDownwards : true,
   *         extendUpwards : true,
   *     }, {
   *         entries : [{
   *             height : 7000.0,
   *             color : new Cesium.Color(1.0, 0.0, 0.0, 0.5)
   *         }, {
   *             height : 7100.0,
   *             color : new Cesium.Color(1.0, 0.0, 0.0, 0.5)
   *         }]
   *     }]
   * });
   */
  function createElevationBandMaterial(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const scene = options.scene;
    const layers = options.layers;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("options.scene", scene);
    Check.defined("options.layers", layers);
    Check.typeOf.number.greaterThan("options.layers.length", layers.length, 0);
    //>>includeEnd('debug');

    const entries = createLayeredEntries(layers);
    const entriesLength = entries.length;
    let i;

    let heightTexBuffer;
    let heightTexDatatype;
    let heightTexFormat;

    const isPackedHeight = !createElevationBandMaterial._useFloatTexture(
      scene.context
    );
    if (isPackedHeight) {
      heightTexDatatype = PixelDatatype$1.UNSIGNED_BYTE;
      heightTexFormat = PixelFormat$1.RGBA;
      heightTexBuffer = new Uint8Array(entriesLength * 4);
      for (i = 0; i < entriesLength; i++) {
        Cartesian4.packFloat(entries[i].height, scratchPackedFloat);
        Cartesian4.pack(scratchPackedFloat, heightTexBuffer, i * 4);
      }
    } else {
      heightTexDatatype = PixelDatatype$1.FLOAT;
      heightTexFormat = PixelFormat$1.LUMINANCE;
      heightTexBuffer = new Float32Array(entriesLength);
      for (i = 0; i < entriesLength; i++) {
        heightTexBuffer[i] = entries[i].height;
      }
    }

    const heightsTex = Texture.create({
      context: scene.context,
      pixelFormat: heightTexFormat,
      pixelDatatype: heightTexDatatype,
      source: {
        arrayBufferView: heightTexBuffer,
        width: entriesLength,
        height: 1,
      },
      sampler: new Sampler({
        wrapS: TextureWrap$1.CLAMP_TO_EDGE,
        wrapT: TextureWrap$1.CLAMP_TO_EDGE,
        minificationFilter: TextureMinificationFilter$1.NEAREST,
        magnificationFilter: TextureMagnificationFilter$1.NEAREST,
      }),
    });

    const colorsArray = new Uint8Array(entriesLength * 4);
    for (i = 0; i < entriesLength; i++) {
      const color = entries[i].color;
      color.toBytes(scratchColorBytes);
      colorsArray[i * 4 + 0] = scratchColorBytes[0];
      colorsArray[i * 4 + 1] = scratchColorBytes[1];
      colorsArray[i * 4 + 2] = scratchColorBytes[2];
      colorsArray[i * 4 + 3] = scratchColorBytes[3];
    }

    const colorsTex = Texture.create({
      context: scene.context,
      pixelFormat: PixelFormat$1.RGBA,
      pixelDatatype: PixelDatatype$1.UNSIGNED_BYTE,
      source: {
        arrayBufferView: colorsArray,
        width: entriesLength,
        height: 1,
      },
      sampler: new Sampler({
        wrapS: TextureWrap$1.CLAMP_TO_EDGE,
        wrapT: TextureWrap$1.CLAMP_TO_EDGE,
        minificationFilter: TextureMinificationFilter$1.LINEAR,
        magnificationFilter: TextureMagnificationFilter$1.LINEAR,
      }),
    });

    const material = Material$4.fromType("ElevationBand", {
      heights: heightsTex,
      colors: colorsTex,
    });
    return material;
  }

  /**
   * Function for checking if the context will allow floating point textures for heights.
   *
   * @param {Context} context The {@link Context}.
   * @returns {Boolean} <code>true</code> if floating point textures can be used for heights.
   * @private
   */
  createElevationBandMaterial._useFloatTexture = function (context) {
    return context.floatingPointTexture;
  };

  /**
   * This is the height that gets stored in the texture when using extendUpwards.
   * There's nothing special about it, it's just a really big number.
   * @private
   */
  createElevationBandMaterial._maximumHeight = +5906376425472;

  /**
   * This is the height that gets stored in the texture when using extendDownwards.
   * There's nothing special about it, it's just a really big number.
   * @private
   */
  createElevationBandMaterial._minimumHeight = -5906376425472;

  /**
   * Color used to create empty space in the color texture
   * @private
   */
  createElevationBandMaterial._emptyColor = new Color(0.0, 0.0, 0.0, 0.0);

  /**
   * Creates a {@link Cesium3DTileset} instance for the
   * {@link https://cesium.com/content/cesium-osm-buildings/|Cesium OSM Buildings}
   * tileset.
   *
   * @function
   *
   * @param {Object} [options] Construction options. Any options allowed by the {@link Cesium3DTileset} constructor
   *        may be specified here. In addition to those, the following properties are supported:
   * @param {Color} [options.defaultColor=Color.WHITE] The default color to use for buildings
   *        that do not have a color. This parameter is ignored if <code>options.style</code> is specified.
   * @param {Cesium3DTileStyle} [options.style] The style to use with the tileset. If not
   *        specified, a default style is used which gives each building or building part a
   *        color inferred from its OpenStreetMap <code>tags</code>. If no color can be inferred,
   *        <code>options.defaultColor</code> is used.
   * @param {Boolean} [options.showOutline=true] Whether to show outlines around buildings. When true,
   *        outlines are displayed. When false, outlines are not displayed.
   * @returns {Cesium3DTileset}
   *
   * @see Ion
   *
   * @example
   * // Create Cesium OSM Buildings with default styling
   * const viewer = new Cesium.Viewer('cesiumContainer');
   * viewer.scene.primitives.add(Cesium.createOsmBuildings());
   *
   * @example
   * // Create Cesium OSM Buildings with a custom style highlighting
   * // schools and hospitals.
   * viewer.scene.primitives.add(Cesium.createOsmBuildings({
   *   style: new Cesium.Cesium3DTileStyle({
   *     color: {
   *       conditions: [
   *         ["${feature['building']} === 'hospital'", "color('#0000FF')"],
   *         ["${feature['building']} === 'school'", "color('#00FF00')"],
   *         [true, "color('#ffffff')"]
   *       ]
   *     }
   *   })
   * }));
   */
  function createOsmBuildings(options) {
    options = combine$2(options, {
      url: IonResource.fromAssetId(96188),
    });

    const tileset = new Cesium3DTileset(options);

    let style = options.style;

    if (!defined(style)) {
      const color = defaultValue(
        options.defaultColor,
        Color.WHITE
      ).toCssColorString();
      style = new Cesium3DTileStyle({
        color: `Boolean(\${feature['cesium#color']}) ? color(\${feature['cesium#color']}) : ${color}`,
      });
    }

    tileset.style = style;

    return tileset;
  }

  /**
   * Creates a {@link Primitive} to visualize well-known vector vertex attributes:
   * <code>normal</code>, <code>tangent</code>, and <code>bitangent</code>.  Normal
   * is red; tangent is green; and bitangent is blue.  If an attribute is not
   * present, it is not drawn.
   *
   * @function
   *
   * @param {Object} options Object with the following properties:
   * @param {Geometry} options.geometry The <code>Geometry</code> instance with the attribute.
   * @param {Number} [options.length=10000.0] The length of each line segment in meters.  This can be negative to point the vector in the opposite direction.
   * @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] The model matrix that transforms to transform the geometry from model to world coordinates.
   * @returns {Primitive} A new <code>Primitive</code> instance with geometry for the vectors.
   *
   * @example
   * scene.primitives.add(Cesium.createTangentSpaceDebugPrimitive({
   *    geometry : instance.geometry,
   *    length : 100000.0,
   *    modelMatrix : instance.modelMatrix
   * }));
   */
  function createTangentSpaceDebugPrimitive(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const instances = [];
    let geometry = options.geometry;

    //>>includeStart('debug', pragmas.debug);
    if (!defined(geometry)) {
      throw new DeveloperError("options.geometry is required.");
    }
    //>>includeEnd('debug');

    if (!defined(geometry.attributes) || !defined(geometry.primitiveType)) {
      // to create the debug lines, we need the computed attributes.
      // compute them if they are undefined.
      geometry = geometry.constructor.createGeometry(geometry);
    }

    const attributes = geometry.attributes;
    const modelMatrix = Matrix4.clone(
      defaultValue(options.modelMatrix, Matrix4.IDENTITY)
    );
    const length = defaultValue(options.length, 10000.0);

    if (defined(attributes.normal)) {
      instances.push(
        new GeometryInstance({
          geometry: GeometryPipeline.createLineSegmentsForVectors(
            geometry,
            "normal",
            length
          ),
          attributes: {
            color: new ColorGeometryInstanceAttribute(1.0, 0.0, 0.0, 1.0),
          },
          modelMatrix: modelMatrix,
        })
      );
    }

    if (defined(attributes.tangent)) {
      instances.push(
        new GeometryInstance({
          geometry: GeometryPipeline.createLineSegmentsForVectors(
            geometry,
            "tangent",
            length
          ),
          attributes: {
            color: new ColorGeometryInstanceAttribute(0.0, 1.0, 0.0, 1.0),
          },
          modelMatrix: modelMatrix,
        })
      );
    }

    if (defined(attributes.bitangent)) {
      instances.push(
        new GeometryInstance({
          geometry: GeometryPipeline.createLineSegmentsForVectors(
            geometry,
            "bitangent",
            length
          ),
          attributes: {
            color: new ColorGeometryInstanceAttribute(0.0, 0.0, 1.0, 1.0),
          },
          modelMatrix: modelMatrix,
        })
      );
    }

    if (instances.length > 0) {
      return new Primitive$3({
        asynchronous: false,
        geometryInstances: instances,
        appearance: new PerInstanceColorAppearance({
          flat: true,
          translucent: false,
        }),
      });
    }

    return undefined;
  }

  /**
   * Creates an {@link IonImageryProvider} instance for ion's default global base imagery layer, currently Bing Maps.
   *
   * @function
   *
   * @param {Object} [options] Object with the following properties:
   * @param {IonWorldImageryStyle} [options.style=IonWorldImageryStyle] The style of base imagery, only AERIAL, AERIAL_WITH_LABELS, and ROAD are currently supported.
   * @returns {IonImageryProvider}
   *
   * @see Ion
   *
   * @example
   * // Create Cesium World Terrain with default settings
   * const viewer = new Cesium.Viewer('cesiumContainer', {
   *     imageryProvider : Cesium.createWorldImagery();
   * });
   *
   * @example
   * // Create Cesium World Terrain with water and normals.
   * const viewer = new Cesium.Viewer('cesiumContainer', {
   *     imageryProvider : Cesium.createWorldImagery({
   *         style: Cesium.IonWorldImageryStyle.AERIAL_WITH_LABELS
   *     })
   * });
   *
   */
  function createWorldImagery(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    const style = defaultValue(options.style, IonWorldImageryStyle$1.AERIAL);
    return new IonImageryProvider({
      assetId: style,
    });
  }

  var oldValue;
  if (typeof ko !== 'undefined') {
      oldValue = ko;
  }

  (function(){
  /*!
   * Knockout JavaScript library v3.5.1
   * (c) The Knockout.js team - http://knockoutjs.com/
   * License: MIT (http://www.opensource.org/licenses/mit-license.php)
   */

  (function() {(function(n){var A=this||(0, eval)("this"),w=A.document,R=A.navigator,v=A.jQuery,H=A.JSON;v||"undefined"===typeof jQuery||(v=jQuery);(function(n){n(A.ko={});})(function(S,T){function K(a,c){return null===a||typeof a in W?a===c:!1}function X(b,c){var d;return function(){d||(d=a.a.setTimeout(function(){d=n;b();},c));}}function Y(b,c){var d;return function(){clearTimeout(d);
  d=a.a.setTimeout(b,c);}}function Z(a,c){c&&"change"!==c?"beforeChange"===c?this.pc(a):this.gb(a,c):this.qc(a);}function aa(a,c){null!==c&&c.s&&c.s();}function ba(a,c){var d=this.qd,e=d[r];e.ra||(this.Qb&&this.mb[c]?(d.uc(c,a,this.mb[c]),this.mb[c]=null,--this.Qb):e.I[c]||d.uc(c,a,e.J?{da:a}:d.$c(a)),a.Ja&&a.gd());}var a="undefined"!==typeof S?S:{};a.b=function(b,c){for(var d=b.split("."),e=a,f=0;f<d.length-1;f++)e=e[d[f]];e[d[d.length-1]]=c;};a.L=function(a,c,d){a[c]=d;};a.version="3.5.1";a.b("version",
  a.version);a.options={deferUpdates:!1,useOnlyNativeEvents:!1,foreachHidesDestroyed:!1};a.a=function(){function b(a,b){for(var c in a)f.call(a,c)&&b(c,a[c]);}function c(a,b){if(b)for(var c in b)f.call(b,c)&&(a[c]=b[c]);return a}function d(a,b){a.__proto__=b;return a}function e(b,c,d,e){var l=b[c].match(q)||[];a.a.D(d.match(q),function(b){a.a.Na(l,b,e);});b[c]=l.join(" ");}var f=Object.prototype.hasOwnProperty,g={__proto__:[]}instanceof Array,h="function"===typeof Symbol,m={},k={};m[R&&/Firefox\/2/i.test(R.userAgent)?
  "KeyboardEvent":"UIEvents"]=["keyup","keydown","keypress"];m.MouseEvents="click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave".split(" ");b(m,function(a,b){if(b.length)for(var c=0,d=b.length;c<d;c++)k[b[c]]=a;});var l={propertychange:!0},p=w&&function(){for(var a=3,b=w.createElement("div"),c=b.getElementsByTagName("i");b.innerHTML="\x3c!--[if gt IE "+ ++a+"]><i></i><![endif]--\x3e",c[0];);return 4<a?a:n}(),q=/\S+/g,t;return {Jc:["authenticity_token",/^__RequestVerificationToken(_.*)?$/],
  D:function(a,b,c){for(var d=0,e=a.length;d<e;d++)b.call(c,a[d],d,a);},A:"function"==typeof Array.prototype.indexOf?function(a,b){return Array.prototype.indexOf.call(a,b)}:function(a,b){for(var c=0,d=a.length;c<d;c++)if(a[c]===b)return c;return -1},Lb:function(a,b,c){for(var d=0,e=a.length;d<e;d++)if(b.call(c,a[d],d,a))return a[d];return n},Pa:function(b,c){var d=a.a.A(b,c);0<d?b.splice(d,1):0===d&&b.shift();},wc:function(b){var c=[];b&&a.a.D(b,function(b){0>a.a.A(c,b)&&c.push(b);});return c},Mb:function(a,
  b,c){var d=[];if(a)for(var e=0,l=a.length;e<l;e++)d.push(b.call(c,a[e],e));return d},jb:function(a,b,c){var d=[];if(a)for(var e=0,l=a.length;e<l;e++)b.call(c,a[e],e)&&d.push(a[e]);return d},Nb:function(a,b){if(b instanceof Array)a.push.apply(a,b);else for(var c=0,d=b.length;c<d;c++)a.push(b[c]);return a},Na:function(b,c,d){var e=a.a.A(a.a.bc(b),c);0>e?d&&b.push(c):d||b.splice(e,1);},Ba:g,extend:c,setPrototypeOf:d,Ab:g?d:c,P:b,Ga:function(a,b,c){if(!a)return a;var d={},e;for(e in a)f.call(a,e)&&(d[e]=
  b.call(c,a[e],e,a));return d},Tb:function(b){for(;b.firstChild;)a.removeNode(b.firstChild);},Yb:function(b){b=a.a.la(b);for(var c=(b[0]&&b[0].ownerDocument||w).createElement("div"),d=0,e=b.length;d<e;d++)c.appendChild(a.oa(b[d]));return c},Ca:function(b,c){for(var d=0,e=b.length,l=[];d<e;d++){var k=b[d].cloneNode(!0);l.push(c?a.oa(k):k);}return l},va:function(b,c){a.a.Tb(b);if(c)for(var d=0,e=c.length;d<e;d++)b.appendChild(c[d]);},Xc:function(b,c){var d=b.nodeType?[b]:b;if(0<d.length){for(var e=d[0],
  l=e.parentNode,k=0,f=c.length;k<f;k++)l.insertBefore(c[k],e);k=0;for(f=d.length;k<f;k++)a.removeNode(d[k]);}},Ua:function(a,b){if(a.length){for(b=8===b.nodeType&&b.parentNode||b;a.length&&a[0].parentNode!==b;)a.splice(0,1);for(;1<a.length&&a[a.length-1].parentNode!==b;)a.length--;if(1<a.length){var c=a[0],d=a[a.length-1];for(a.length=0;c!==d;)a.push(c),c=c.nextSibling;a.push(d);}}return a},Zc:function(a,b){7>p?a.setAttribute("selected",b):a.selected=b;},Db:function(a){return null===a||a===n?"":a.trim?
  a.trim():a.toString().replace(/^[\s\xa0]+|[\s\xa0]+$/g,"")},Ud:function(a,b){a=a||"";return b.length>a.length?!1:a.substring(0,b.length)===b},vd:function(a,b){if(a===b)return !0;if(11===a.nodeType)return !1;if(b.contains)return b.contains(1!==a.nodeType?a.parentNode:a);if(b.compareDocumentPosition)return 16==(b.compareDocumentPosition(a)&16);for(;a&&a!=b;)a=a.parentNode;return !!a},Sb:function(b){return a.a.vd(b,b.ownerDocument.documentElement)},kd:function(b){return !!a.a.Lb(b,a.a.Sb)},R:function(a){return a&&
  a.tagName&&a.tagName.toLowerCase()},Ac:function(b){return a.onError?function(){try{return b.apply(this,arguments)}catch(c){throw a.onError&&a.onError(c),c;}}:b},setTimeout:function(b,c){return setTimeout(a.a.Ac(b),c)},Gc:function(b){setTimeout(function(){a.onError&&a.onError(b);throw b;},0);},B:function(b,c,d){var e=a.a.Ac(d);d=l[c];if(a.options.useOnlyNativeEvents||d||!v)if(d||"function"!=typeof b.addEventListener)if("undefined"!=typeof b.attachEvent){var k=function(a){e.call(b,a);},f="on"+c;b.attachEvent(f,
  k);a.a.K.za(b,function(){b.detachEvent(f,k);});}else throw Error("Browser doesn't support addEventListener or attachEvent");else b.addEventListener(c,e,!1);else t||(t="function"==typeof v(b).on?"on":"bind"),v(b)[t](c,e);},Fb:function(b,c){if(!b||!b.nodeType)throw Error("element must be a DOM node when calling triggerEvent");var d;"input"===a.a.R(b)&&b.type&&"click"==c.toLowerCase()?(d=b.type,d="checkbox"==d||"radio"==d):d=!1;if(a.options.useOnlyNativeEvents||!v||d)if("function"==typeof w.createEvent)if("function"==
  typeof b.dispatchEvent)d=w.createEvent(k[c]||"HTMLEvents"),d.initEvent(c,!0,!0,A,0,0,0,0,0,!1,!1,!1,!1,0,b),b.dispatchEvent(d);else throw Error("The supplied element doesn't support dispatchEvent");else if(d&&b.click)b.click();else if("undefined"!=typeof b.fireEvent)b.fireEvent("on"+c);else throw Error("Browser doesn't support triggering events");else v(b).trigger(c);},f:function(b){return a.O(b)?b():b},bc:function(b){return a.O(b)?b.v():b},Eb:function(b,c,d){var l;c&&("object"===typeof b.classList?
  (l=b.classList[d?"add":"remove"],a.a.D(c.match(q),function(a){l.call(b.classList,a);})):"string"===typeof b.className.baseVal?e(b.className,"baseVal",c,d):e(b,"className",c,d));},Bb:function(b,c){var d=a.a.f(c);if(null===d||d===n)d="";var e=a.h.firstChild(b);!e||3!=e.nodeType||a.h.nextSibling(e)?a.h.va(b,[b.ownerDocument.createTextNode(d)]):e.data=d;a.a.Ad(b);},Yc:function(a,b){a.name=b;if(7>=p)try{var c=a.name.replace(/[&<>'"]/g,function(a){return "&#"+a.charCodeAt(0)+";"});a.mergeAttributes(w.createElement("<input name='"+
  c+"'/>"),!1);}catch(d){}},Ad:function(a){9<=p&&(a=1==a.nodeType?a:a.parentNode,a.style&&(a.style.zoom=a.style.zoom));},wd:function(a){if(p){var b=a.style.width;a.style.width=0;a.style.width=b;}},Pd:function(b,c){b=a.a.f(b);c=a.a.f(c);for(var d=[],e=b;e<=c;e++)d.push(e);return d},la:function(a){for(var b=[],c=0,d=a.length;c<d;c++)b.push(a[c]);return b},Da:function(a){return h?Symbol(a):a},Zd:6===p,$d:7===p,W:p,Lc:function(b,c){for(var d=a.a.la(b.getElementsByTagName("input")).concat(a.a.la(b.getElementsByTagName("textarea"))),
  e="string"==typeof c?function(a){return a.name===c}:function(a){return c.test(a.name)},l=[],k=d.length-1;0<=k;k--)e(d[k])&&l.push(d[k]);return l},Nd:function(b){return "string"==typeof b&&(b=a.a.Db(b))?H&&H.parse?H.parse(b):(new Function("return "+b))():null},hc:function(b,c,d){if(!H||!H.stringify)throw Error("Cannot find JSON.stringify(). Some browsers (e.g., IE < 8) don't support it natively, but you can overcome this by adding a script reference to json2.js, downloadable from http://www.json.org/json2.js");
  return H.stringify(a.a.f(b),c,d)},Od:function(c,d,e){e=e||{};var l=e.params||{},k=e.includeFields||this.Jc,f=c;if("object"==typeof c&&"form"===a.a.R(c))for(var f=c.action,h=k.length-1;0<=h;h--)for(var g=a.a.Lc(c,k[h]),m=g.length-1;0<=m;m--)l[g[m].name]=g[m].value;d=a.a.f(d);var p=w.createElement("form");p.style.display="none";p.action=f;p.method="post";for(var q in d)c=w.createElement("input"),c.type="hidden",c.name=q,c.value=a.a.hc(a.a.f(d[q])),p.appendChild(c);b(l,function(a,b){var c=w.createElement("input");
  c.type="hidden";c.name=a;c.value=b;p.appendChild(c);});w.body.appendChild(p);e.submitter?e.submitter(p):p.submit();setTimeout(function(){p.parentNode.removeChild(p);},0);}}}();a.b("utils",a.a);a.b("utils.arrayForEach",a.a.D);a.b("utils.arrayFirst",a.a.Lb);a.b("utils.arrayFilter",a.a.jb);a.b("utils.arrayGetDistinctValues",a.a.wc);a.b("utils.arrayIndexOf",a.a.A);a.b("utils.arrayMap",a.a.Mb);a.b("utils.arrayPushAll",a.a.Nb);a.b("utils.arrayRemoveItem",a.a.Pa);a.b("utils.cloneNodes",a.a.Ca);a.b("utils.createSymbolOrString",
  a.a.Da);a.b("utils.extend",a.a.extend);a.b("utils.fieldsIncludedWithJsonPost",a.a.Jc);a.b("utils.getFormFields",a.a.Lc);a.b("utils.objectMap",a.a.Ga);a.b("utils.peekObservable",a.a.bc);a.b("utils.postJson",a.a.Od);a.b("utils.parseJson",a.a.Nd);a.b("utils.registerEventHandler",a.a.B);a.b("utils.stringifyJson",a.a.hc);a.b("utils.range",a.a.Pd);a.b("utils.toggleDomNodeCssClass",a.a.Eb);a.b("utils.triggerEvent",a.a.Fb);a.b("utils.unwrapObservable",a.a.f);a.b("utils.objectForEach",a.a.P);a.b("utils.addOrRemoveItem",
  a.a.Na);a.b("utils.setTextContent",a.a.Bb);a.b("unwrap",a.a.f);Function.prototype.bind||(Function.prototype.bind=function(a){var c=this;if(1===arguments.length)return function(){return c.apply(a,arguments)};var d=Array.prototype.slice.call(arguments,1);return function(){var e=d.slice(0);e.push.apply(e,arguments);return c.apply(a,e)}});a.a.g=new function(){var b=0,c="__ko__"+(new Date).getTime(),d={},e,f;a.a.W?(e=function(a,e){var f=a[c];if(!f||"null"===f||!d[f]){if(!e)return n;f=a[c]="ko"+b++;d[f]=
  {};}return d[f]},f=function(a){var b=a[c];return b?(delete d[b],a[c]=null,!0):!1}):(e=function(a,b){var d=a[c];!d&&b&&(d=a[c]={});return d},f=function(a){return a[c]?(delete a[c],!0):!1});return {get:function(a,b){var c=e(a,!1);return c&&c[b]},set:function(a,b,c){(a=e(a,c!==n))&&(a[b]=c);},Ub:function(a,b,c){a=e(a,!0);return a[b]||(a[b]=c)},clear:f,Z:function(){return b++ +c}}};a.b("utils.domData",a.a.g);a.b("utils.domData.clear",a.a.g.clear);a.a.K=new function(){function b(b,c){var d=a.a.g.get(b,e);
  d===n&&c&&(d=[],a.a.g.set(b,e,d));return d}function c(c){var e=b(c,!1);if(e)for(var e=e.slice(0),k=0;k<e.length;k++)e[k](c);a.a.g.clear(c);a.a.K.cleanExternalData(c);g[c.nodeType]&&d(c.childNodes,!0);}function d(b,d){for(var e=[],l,f=0;f<b.length;f++)if(!d||8===b[f].nodeType)if(c(e[e.length]=l=b[f]),b[f]!==l)for(;f--&&-1==a.a.A(e,b[f]););}var e=a.a.g.Z(),f={1:!0,8:!0,9:!0},g={1:!0,9:!0};return {za:function(a,c){if("function"!=typeof c)throw Error("Callback must be a function");b(a,!0).push(c);},yb:function(c,
  d){var f=b(c,!1);f&&(a.a.Pa(f,d),0==f.length&&a.a.g.set(c,e,n));},oa:function(b){a.u.G(function(){f[b.nodeType]&&(c(b),g[b.nodeType]&&d(b.getElementsByTagName("*")));});return b},removeNode:function(b){a.oa(b);b.parentNode&&b.parentNode.removeChild(b);},cleanExternalData:function(a){v&&"function"==typeof v.cleanData&&v.cleanData([a]);}}};a.oa=a.a.K.oa;a.removeNode=a.a.K.removeNode;a.b("cleanNode",a.oa);a.b("removeNode",a.removeNode);a.b("utils.domNodeDisposal",a.a.K);a.b("utils.domNodeDisposal.addDisposeCallback",
  a.a.K.za);a.b("utils.domNodeDisposal.removeDisposeCallback",a.a.K.yb);(function(){var b=[0,"",""],c=[1,"<table>","</table>"],d=[3,"<table><tbody><tr>","</tr></tbody></table>"],e=[1,"<select multiple='multiple'>","</select>"],f={thead:c,tbody:c,tfoot:c,tr:[2,"<table><tbody>","</tbody></table>"],td:d,th:d,option:e,optgroup:e},g=8>=a.a.W;a.a.ua=function(c,d){var e;if(v)if(v.parseHTML)e=v.parseHTML(c,d)||[];else {if((e=v.clean([c],d))&&e[0]){for(var l=e[0];l.parentNode&&11!==l.parentNode.nodeType;)l=l.parentNode;
  l.parentNode&&l.parentNode.removeChild(l);}}else {(e=d)||(e=w);var l=e.parentWindow||e.defaultView||A,p=a.a.Db(c).toLowerCase(),q=e.createElement("div"),t;t=(p=p.match(/^(?:\x3c!--.*?--\x3e\s*?)*?<([a-z]+)[\s>]/))&&f[p[1]]||b;p=t[0];t="ignored<div>"+t[1]+c+t[2]+"</div>";"function"==typeof l.innerShiv?q.appendChild(l.innerShiv(t)):(g&&e.body.appendChild(q),q.innerHTML=t,g&&q.parentNode.removeChild(q));for(;p--;)q=q.lastChild;e=a.a.la(q.lastChild.childNodes);}return e};a.a.Md=function(b,c){var d=a.a.ua(b,
  c);return d.length&&d[0].parentElement||a.a.Yb(d)};a.a.fc=function(b,c){a.a.Tb(b);c=a.a.f(c);if(null!==c&&c!==n)if("string"!=typeof c&&(c=c.toString()),v)v(b).html(c);else for(var d=a.a.ua(c,b.ownerDocument),e=0;e<d.length;e++)b.appendChild(d[e]);};})();a.b("utils.parseHtmlFragment",a.a.ua);a.b("utils.setHtml",a.a.fc);a.aa=function(){function b(c,e){if(c)if(8==c.nodeType){var f=a.aa.Uc(c.nodeValue);null!=f&&e.push({ud:c,Kd:f});}else if(1==c.nodeType)for(var f=0,g=c.childNodes,h=g.length;f<h;f++)b(g[f],
  e);}var c={};return {Xb:function(a){if("function"!=typeof a)throw Error("You can only pass a function to ko.memoization.memoize()");var b=(4294967296*(1+Math.random())|0).toString(16).substring(1)+(4294967296*(1+Math.random())|0).toString(16).substring(1);c[b]=a;return "\x3c!--[ko_memo:"+b+"]--\x3e"},bd:function(a,b){var f=c[a];if(f===n)throw Error("Couldn't find any memo with ID "+a+". Perhaps it's already been unmemoized.");try{return f.apply(null,b||[]),!0}finally{delete c[a];}},cd:function(c,e){var f=
  [];b(c,f);for(var g=0,h=f.length;g<h;g++){var m=f[g].ud,k=[m];e&&a.a.Nb(k,e);a.aa.bd(f[g].Kd,k);m.nodeValue="";m.parentNode&&m.parentNode.removeChild(m);}},Uc:function(a){return (a=a.match(/^\[ko_memo\:(.*?)\]$/))?a[1]:null}}}();a.b("memoization",a.aa);a.b("memoization.memoize",a.aa.Xb);a.b("memoization.unmemoize",a.aa.bd);a.b("memoization.parseMemoText",a.aa.Uc);a.b("memoization.unmemoizeDomNodeAndDescendants",a.aa.cd);a.na=function(){function b(){if(f)for(var b=f,c=0,d;h<f;)if(d=e[h++]){if(h>b){if(5E3<=
  ++c){h=f;a.a.Gc(Error("'Too much recursion' after processing "+c+" task groups."));break}b=f;}try{d();}catch(p){a.a.Gc(p);}}}function c(){b();h=f=e.length=0;}var d,e=[],f=0,g=1,h=0;A.MutationObserver?d=function(a){var b=w.createElement("div");(new MutationObserver(a)).observe(b,{attributes:!0});return function(){b.classList.toggle("foo");}}(c):d=w&&"onreadystatechange"in w.createElement("script")?function(a){var b=w.createElement("script");b.onreadystatechange=function(){b.onreadystatechange=null;w.documentElement.removeChild(b);
  b=null;a();};w.documentElement.appendChild(b);}:function(a){setTimeout(a,0);};return {scheduler:d,zb:function(b){f||a.na.scheduler(c);e[f++]=b;return g++},cancel:function(a){a=a-(g-f);a>=h&&a<f&&(e[a]=null);},resetForTesting:function(){var a=f-h;h=f=e.length=0;return a},Sd:b}}();a.b("tasks",a.na);a.b("tasks.schedule",a.na.zb);a.b("tasks.runEarly",a.na.Sd);a.Ta={throttle:function(b,c){b.throttleEvaluation=c;var d=null;return a.$({read:b,write:function(e){clearTimeout(d);d=a.a.setTimeout(function(){b(e);},
  c);}})},rateLimit:function(a,c){var d,e,f;"number"==typeof c?d=c:(d=c.timeout,e=c.method);a.Hb=!1;f="function"==typeof e?e:"notifyWhenChangesStop"==e?Y:X;a.ub(function(a){return f(a,d,c)});},deferred:function(b,c){if(!0!==c)throw Error("The 'deferred' extender only accepts the value 'true', because it is not supported to turn deferral off once enabled.");b.Hb||(b.Hb=!0,b.ub(function(c){var e,f=!1;return function(){if(!f){a.na.cancel(e);e=a.na.zb(c);try{f=!0,b.notifySubscribers(n,"dirty");}finally{f=
  !1;}}}}));},notify:function(a,c){a.equalityComparer="always"==c?null:K;}};var W={undefined:1,"boolean":1,number:1,string:1};a.b("extenders",a.Ta);a.ic=function(b,c,d){this.da=b;this.lc=c;this.mc=d;this.Ib=!1;this.fb=this.Jb=null;a.L(this,"dispose",this.s);a.L(this,"disposeWhenNodeIsRemoved",this.l);};a.ic.prototype.s=function(){this.Ib||(this.fb&&a.a.K.yb(this.Jb,this.fb),this.Ib=!0,this.mc(),this.da=this.lc=this.mc=this.Jb=this.fb=null);};a.ic.prototype.l=function(b){this.Jb=b;a.a.K.za(b,this.fb=this.s.bind(this));};
  a.T=function(){a.a.Ab(this,D);D.qb(this);};var D={qb:function(a){a.U={change:[]};a.sc=1;},subscribe:function(b,c,d){var e=this;d=d||"change";var f=new a.ic(e,c?b.bind(c):b,function(){a.a.Pa(e.U[d],f);e.hb&&e.hb(d);});e.Qa&&e.Qa(d);e.U[d]||(e.U[d]=[]);e.U[d].push(f);return f},notifySubscribers:function(b,c){c=c||"change";"change"===c&&this.Gb();if(this.Wa(c)){var d="change"===c&&this.ed||this.U[c].slice(0);try{a.u.xc();for(var e=0,f;f=d[e];++e)f.Ib||f.lc(b);}finally{a.u.end();}}},ob:function(){return this.sc},
  Dd:function(a){return this.ob()!==a},Gb:function(){++this.sc;},ub:function(b){var c=this,d=a.O(c),e,f,g,h,m;c.gb||(c.gb=c.notifySubscribers,c.notifySubscribers=Z);var k=b(function(){c.Ja=!1;d&&h===c&&(h=c.nc?c.nc():c());var a=f||m&&c.sb(g,h);m=f=e=!1;a&&c.gb(g=h);});c.qc=function(a,b){b&&c.Ja||(m=!b);c.ed=c.U.change.slice(0);c.Ja=e=!0;h=a;k();};c.pc=function(a){e||(g=a,c.gb(a,"beforeChange"));};c.rc=function(){m=!0;};c.gd=function(){c.sb(g,c.v(!0))&&(f=!0);};},Wa:function(a){return this.U[a]&&this.U[a].length},
  Bd:function(b){if(b)return this.U[b]&&this.U[b].length||0;var c=0;a.a.P(this.U,function(a,b){"dirty"!==a&&(c+=b.length);});return c},sb:function(a,c){return !this.equalityComparer||!this.equalityComparer(a,c)},toString:function(){return "[object Object]"},extend:function(b){var c=this;b&&a.a.P(b,function(b,e){var f=a.Ta[b];"function"==typeof f&&(c=f(c,e)||c);});return c}};a.L(D,"init",D.qb);a.L(D,"subscribe",D.subscribe);a.L(D,"extend",D.extend);a.L(D,"getSubscriptionsCount",D.Bd);a.a.Ba&&a.a.setPrototypeOf(D,
  Function.prototype);a.T.fn=D;a.Qc=function(a){return null!=a&&"function"==typeof a.subscribe&&"function"==typeof a.notifySubscribers};a.b("subscribable",a.T);a.b("isSubscribable",a.Qc);a.S=a.u=function(){function b(a){d.push(e);e=a;}function c(){e=d.pop();}var d=[],e,f=0;return {xc:b,end:c,cc:function(b){if(e){if(!a.Qc(b))throw Error("Only subscribable things can act as dependencies");e.od.call(e.pd,b,b.fd||(b.fd=++f));}},G:function(a,d,e){try{return b(),a.apply(d,e||[])}finally{c();}},qa:function(){if(e)return e.o.qa()},
  Va:function(){if(e)return e.o.Va()},Ya:function(){if(e)return e.Ya},o:function(){if(e)return e.o}}}();a.b("computedContext",a.S);a.b("computedContext.getDependenciesCount",a.S.qa);a.b("computedContext.getDependencies",a.S.Va);a.b("computedContext.isInitial",a.S.Ya);a.b("computedContext.registerDependency",a.S.cc);a.b("ignoreDependencies",a.Yd=a.u.G);var I=a.a.Da("_latestValue");a.ta=function(b){function c(){if(0<arguments.length)return c.sb(c[I],arguments[0])&&(c.ya(),c[I]=arguments[0],c.xa()),this;
  a.u.cc(c);return c[I]}c[I]=b;a.a.Ba||a.a.extend(c,a.T.fn);a.T.fn.qb(c);a.a.Ab(c,F);a.options.deferUpdates&&a.Ta.deferred(c,!0);return c};var F={equalityComparer:K,v:function(){return this[I]},xa:function(){this.notifySubscribers(this[I],"spectate");this.notifySubscribers(this[I]);},ya:function(){this.notifySubscribers(this[I],"beforeChange");}};a.a.Ba&&a.a.setPrototypeOf(F,a.T.fn);var G=a.ta.Ma="__ko_proto__";F[G]=a.ta;a.O=function(b){if((b="function"==typeof b&&b[G])&&b!==F[G]&&b!==a.o.fn[G])throw Error("Invalid object that looks like an observable; possibly from another Knockout instance");
  return !!b};a.Za=function(b){return "function"==typeof b&&(b[G]===F[G]||b[G]===a.o.fn[G]&&b.Nc)};a.b("observable",a.ta);a.b("isObservable",a.O);a.b("isWriteableObservable",a.Za);a.b("isWritableObservable",a.Za);a.b("observable.fn",F);a.L(F,"peek",F.v);a.L(F,"valueHasMutated",F.xa);a.L(F,"valueWillMutate",F.ya);a.Ha=function(b){b=b||[];if("object"!=typeof b||!("length"in b))throw Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");b=a.ta(b);a.a.Ab(b,
  a.Ha.fn);return b.extend({trackArrayChanges:!0})};a.Ha.fn={remove:function(b){for(var c=this.v(),d=[],e="function"!=typeof b||a.O(b)?function(a){return a===b}:b,f=0;f<c.length;f++){var g=c[f];if(e(g)){0===d.length&&this.ya();if(c[f]!==g)throw Error("Array modified during remove; cannot remove item");d.push(g);c.splice(f,1);f--;}}d.length&&this.xa();return d},removeAll:function(b){if(b===n){var c=this.v(),d=c.slice(0);this.ya();c.splice(0,c.length);this.xa();return d}return b?this.remove(function(c){return 0<=
  a.a.A(b,c)}):[]},destroy:function(b){var c=this.v(),d="function"!=typeof b||a.O(b)?function(a){return a===b}:b;this.ya();for(var e=c.length-1;0<=e;e--){var f=c[e];d(f)&&(f._destroy=!0);}this.xa();},destroyAll:function(b){return b===n?this.destroy(function(){return !0}):b?this.destroy(function(c){return 0<=a.a.A(b,c)}):[]},indexOf:function(b){var c=this();return a.a.A(c,b)},replace:function(a,c){var d=this.indexOf(a);0<=d&&(this.ya(),this.v()[d]=c,this.xa());},sorted:function(a){var c=this().slice(0);
  return a?c.sort(a):c.sort()},reversed:function(){return this().slice(0).reverse()}};a.a.Ba&&a.a.setPrototypeOf(a.Ha.fn,a.ta.fn);a.a.D("pop push reverse shift sort splice unshift".split(" "),function(b){a.Ha.fn[b]=function(){var a=this.v();this.ya();this.zc(a,b,arguments);var d=a[b].apply(a,arguments);this.xa();return d===a?this:d};});a.a.D(["slice"],function(b){a.Ha.fn[b]=function(){var a=this();return a[b].apply(a,arguments)};});a.Pc=function(b){return a.O(b)&&"function"==typeof b.remove&&"function"==
  typeof b.push};a.b("observableArray",a.Ha);a.b("isObservableArray",a.Pc);a.Ta.trackArrayChanges=function(b,c){function d(){function c(){if(m){var d=[].concat(b.v()||[]),e;if(b.Wa("arrayChange")){if(!f||1<m)f=a.a.Pb(k,d,b.Ob);e=f;}k=d;f=null;m=0;e&&e.length&&b.notifySubscribers(e,"arrayChange");}}e?c():(e=!0,h=b.subscribe(function(){++m;},null,"spectate"),k=[].concat(b.v()||[]),f=null,g=b.subscribe(c));}b.Ob={};c&&"object"==typeof c&&a.a.extend(b.Ob,c);b.Ob.sparse=!0;if(!b.zc){var e=!1,f=null,g,h,m=0,
  k,l=b.Qa,p=b.hb;b.Qa=function(a){l&&l.call(b,a);"arrayChange"===a&&d();};b.hb=function(a){p&&p.call(b,a);"arrayChange"!==a||b.Wa("arrayChange")||(g&&g.s(),h&&h.s(),h=g=null,e=!1,k=n);};b.zc=function(b,c,d){function l(a,b,c){return k[k.length]={status:a,value:b,index:c}}if(e&&!m){var k=[],p=b.length,g=d.length,h=0;switch(c){case "push":h=p;case "unshift":for(c=0;c<g;c++)l("added",d[c],h+c);break;case "pop":h=p-1;case "shift":p&&l("deleted",b[h],h);break;case "splice":c=Math.min(Math.max(0,0>d[0]?p+d[0]:
  d[0]),p);for(var p=1===g?p:Math.min(c+(d[1]||0),p),g=c+g-2,h=Math.max(p,g),U=[],L=[],n=2;c<h;++c,++n)c<p&&L.push(l("deleted",b[c],c)),c<g&&U.push(l("added",d[n],c));a.a.Kc(L,U);break;default:return}f=k;}};}};var r=a.a.Da("_state");a.o=a.$=function(b,c,d){function e(){if(0<arguments.length){if("function"===typeof f)f.apply(g.nb,arguments);else throw Error("Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters.");return this}g.ra||
  a.u.cc(e);(g.ka||g.J&&e.Xa())&&e.ha();return g.X}"object"===typeof b?d=b:(d=d||{},b&&(d.read=b));if("function"!=typeof d.read)throw Error("Pass a function that returns the value of the ko.computed");var f=d.write,g={X:n,sa:!0,ka:!0,rb:!1,jc:!1,ra:!1,wb:!1,J:!1,Wc:d.read,nb:c||d.owner,l:d.disposeWhenNodeIsRemoved||d.l||null,Sa:d.disposeWhen||d.Sa,Rb:null,I:{},V:0,Ic:null};e[r]=g;e.Nc="function"===typeof f;a.a.Ba||a.a.extend(e,a.T.fn);a.T.fn.qb(e);a.a.Ab(e,C);d.pure?(g.wb=!0,g.J=!0,a.a.extend(e,da)):
  d.deferEvaluation&&a.a.extend(e,ea);a.options.deferUpdates&&a.Ta.deferred(e,!0);g.l&&(g.jc=!0,g.l.nodeType||(g.l=null));g.J||d.deferEvaluation||e.ha();g.l&&e.ja()&&a.a.K.za(g.l,g.Rb=function(){e.s();});return e};var C={equalityComparer:K,qa:function(){return this[r].V},Va:function(){var b=[];a.a.P(this[r].I,function(a,d){b[d.Ka]=d.da;});return b},Vb:function(b){if(!this[r].V)return !1;var c=this.Va();return -1!==a.a.A(c,b)?!0:!!a.a.Lb(c,function(a){return a.Vb&&a.Vb(b)})},uc:function(a,c,d){if(this[r].wb&&
  c===this)throw Error("A 'pure' computed must not be called recursively");this[r].I[a]=d;d.Ka=this[r].V++;d.La=c.ob();},Xa:function(){var a,c,d=this[r].I;for(a in d)if(Object.prototype.hasOwnProperty.call(d,a)&&(c=d[a],this.Ia&&c.da.Ja||c.da.Dd(c.La)))return !0},Jd:function(){this.Ia&&!this[r].rb&&this.Ia(!1);},ja:function(){var a=this[r];return a.ka||0<a.V},Rd:function(){this.Ja?this[r].ka&&(this[r].sa=!0):this.Hc();},$c:function(a){if(a.Hb){var c=a.subscribe(this.Jd,this,"dirty"),d=a.subscribe(this.Rd,
  this);return {da:a,s:function(){c.s();d.s();}}}return a.subscribe(this.Hc,this)},Hc:function(){var b=this,c=b.throttleEvaluation;c&&0<=c?(clearTimeout(this[r].Ic),this[r].Ic=a.a.setTimeout(function(){b.ha(!0);},c)):b.Ia?b.Ia(!0):b.ha(!0);},ha:function(b){var c=this[r],d=c.Sa,e=!1;if(!c.rb&&!c.ra){if(c.l&&!a.a.Sb(c.l)||d&&d()){if(!c.jc){this.s();return}}else c.jc=!1;c.rb=!0;try{e=this.zd(b);}finally{c.rb=!1;}return e}},zd:function(b){var c=this[r],d=!1,e=c.wb?n:!c.V,d={qd:this,mb:c.I,Qb:c.V};a.u.xc({pd:d,
  od:ba,o:this,Ya:e});c.I={};c.V=0;var f=this.yd(c,d);c.V?d=this.sb(c.X,f):(this.s(),d=!0);d&&(c.J?this.Gb():this.notifySubscribers(c.X,"beforeChange"),c.X=f,this.notifySubscribers(c.X,"spectate"),!c.J&&b&&this.notifySubscribers(c.X),this.rc&&this.rc());e&&this.notifySubscribers(c.X,"awake");return d},yd:function(b,c){try{var d=b.Wc;return b.nb?d.call(b.nb):d()}finally{a.u.end(),c.Qb&&!b.J&&a.a.P(c.mb,aa),b.sa=b.ka=!1;}},v:function(a){var c=this[r];(c.ka&&(a||!c.V)||c.J&&this.Xa())&&this.ha();return c.X},
  ub:function(b){a.T.fn.ub.call(this,b);this.nc=function(){this[r].J||(this[r].sa?this.ha():this[r].ka=!1);return this[r].X};this.Ia=function(a){this.pc(this[r].X);this[r].ka=!0;a&&(this[r].sa=!0);this.qc(this,!a);};},s:function(){var b=this[r];!b.J&&b.I&&a.a.P(b.I,function(a,b){b.s&&b.s();});b.l&&b.Rb&&a.a.K.yb(b.l,b.Rb);b.I=n;b.V=0;b.ra=!0;b.sa=!1;b.ka=!1;b.J=!1;b.l=n;b.Sa=n;b.Wc=n;this.Nc||(b.nb=n);}},da={Qa:function(b){var c=this,d=c[r];if(!d.ra&&d.J&&"change"==b){d.J=!1;if(d.sa||c.Xa())d.I=null,d.V=
  0,c.ha()&&c.Gb();else {var e=[];a.a.P(d.I,function(a,b){e[b.Ka]=a;});a.a.D(e,function(a,b){var e=d.I[a],m=c.$c(e.da);m.Ka=b;m.La=e.La;d.I[a]=m;});c.Xa()&&c.ha()&&c.Gb();}d.ra||c.notifySubscribers(d.X,"awake");}},hb:function(b){var c=this[r];c.ra||"change"!=b||this.Wa("change")||(a.a.P(c.I,function(a,b){b.s&&(c.I[a]={da:b.da,Ka:b.Ka,La:b.La},b.s());}),c.J=!0,this.notifySubscribers(n,"asleep"));},ob:function(){var b=this[r];b.J&&(b.sa||this.Xa())&&this.ha();return a.T.fn.ob.call(this)}},ea={Qa:function(a){"change"!=
  a&&"beforeChange"!=a||this.v();}};a.a.Ba&&a.a.setPrototypeOf(C,a.T.fn);var N=a.ta.Ma;C[N]=a.o;a.Oc=function(a){return "function"==typeof a&&a[N]===C[N]};a.Fd=function(b){return a.Oc(b)&&b[r]&&b[r].wb};a.b("computed",a.o);a.b("dependentObservable",a.o);a.b("isComputed",a.Oc);a.b("isPureComputed",a.Fd);a.b("computed.fn",C);a.L(C,"peek",C.v);a.L(C,"dispose",C.s);a.L(C,"isActive",C.ja);a.L(C,"getDependenciesCount",C.qa);a.L(C,"getDependencies",C.Va);a.xb=function(b,c){if("function"===typeof b)return a.o(b,
  c,{pure:!0});b=a.a.extend({},b);b.pure=!0;return a.o(b,c)};a.b("pureComputed",a.xb);(function(){function b(a,f,g){g=g||new d;a=f(a);if("object"!=typeof a||null===a||a===n||a instanceof RegExp||a instanceof Date||a instanceof String||a instanceof Number||a instanceof Boolean)return a;var h=a instanceof Array?[]:{};g.save(a,h);c(a,function(c){var d=f(a[c]);switch(typeof d){case "boolean":case "number":case "string":case "function":h[c]=d;break;case "object":case "undefined":var l=g.get(d);h[c]=l!==
  n?l:b(d,f,g);}});return h}function c(a,b){if(a instanceof Array){for(var c=0;c<a.length;c++)b(c);"function"==typeof a.toJSON&&b("toJSON");}else for(c in a)b(c);}function d(){this.keys=[];this.values=[];}a.ad=function(c){if(0==arguments.length)throw Error("When calling ko.toJS, pass the object you want to convert.");return b(c,function(b){for(var c=0;a.O(b)&&10>c;c++)b=b();return b})};a.toJSON=function(b,c,d){b=a.ad(b);return a.a.hc(b,c,d)};d.prototype={constructor:d,save:function(b,c){var d=a.a.A(this.keys,
  b);0<=d?this.values[d]=c:(this.keys.push(b),this.values.push(c));},get:function(b){b=a.a.A(this.keys,b);return 0<=b?this.values[b]:n}};})();a.b("toJS",a.ad);a.b("toJSON",a.toJSON);a.Wd=function(b,c,d){function e(c){var e=a.xb(b,d).extend({ma:"always"}),h=e.subscribe(function(a){a&&(h.s(),c(a));});e.notifySubscribers(e.v());return h}return "function"!==typeof Promise||c?e(c.bind(d)):new Promise(e)};a.b("when",a.Wd);(function(){a.w={M:function(b){switch(a.a.R(b)){case "option":return !0===b.__ko__hasDomDataOptionValue__?
  a.a.g.get(b,a.c.options.$b):7>=a.a.W?b.getAttributeNode("value")&&b.getAttributeNode("value").specified?b.value:b.text:b.value;case "select":return 0<=b.selectedIndex?a.w.M(b.options[b.selectedIndex]):n;default:return b.value}},cb:function(b,c,d){switch(a.a.R(b)){case "option":"string"===typeof c?(a.a.g.set(b,a.c.options.$b,n),"__ko__hasDomDataOptionValue__"in b&&delete b.__ko__hasDomDataOptionValue__,b.value=c):(a.a.g.set(b,a.c.options.$b,c),b.__ko__hasDomDataOptionValue__=!0,b.value="number"===
  typeof c?c:"");break;case "select":if(""===c||null===c)c=n;for(var e=-1,f=0,g=b.options.length,h;f<g;++f)if(h=a.w.M(b.options[f]),h==c||""===h&&c===n){e=f;break}if(d||0<=e||c===n&&1<b.size)b.selectedIndex=e,6===a.a.W&&a.a.setTimeout(function(){b.selectedIndex=e;},0);break;default:if(null===c||c===n)c="";b.value=c;}}};})();a.b("selectExtensions",a.w);a.b("selectExtensions.readValue",a.w.M);a.b("selectExtensions.writeValue",a.w.cb);a.m=function(){function b(b){b=a.a.Db(b);123===b.charCodeAt(0)&&(b=b.slice(1,
  -1));b+="\n,";var c=[],d=b.match(e),p,q=[],h=0;if(1<d.length){for(var x=0,B;B=d[x];++x){var u=B.charCodeAt(0);if(44===u){if(0>=h){c.push(p&&q.length?{key:p,value:q.join("")}:{unknown:p||q.join("")});p=h=0;q=[];continue}}else if(58===u){if(!h&&!p&&1===q.length){p=q.pop();continue}}else if(47===u&&1<B.length&&(47===B.charCodeAt(1)||42===B.charCodeAt(1)))continue;else 47===u&&x&&1<B.length?(u=d[x-1].match(f))&&!g[u[0]]&&(b=b.substr(b.indexOf(B)+1),d=b.match(e),x=-1,B="/"):40===u||123===u||91===u?++h:
  41===u||125===u||93===u?--h:p||q.length||34!==u&&39!==u||(B=B.slice(1,-1));q.push(B);}if(0<h)throw Error("Unbalanced parentheses, braces, or brackets");}return c}var c=["true","false","null","undefined"],d=/^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i,e=RegExp("\"(?:\\\\.|[^\"])*\"|'(?:\\\\.|[^'])*'|`(?:\\\\.|[^`])*`|/\\*(?:[^*]|\\*+[^*/])*\\*+/|//.*\n|/(?:\\\\.|[^/])+/w*|[^\\s:,/][^,\"'`{}()/:[\\]]*[^\\s,\"'`{}()/:[\\]]|[^\\s]","g"),f=/[\])"'A-Za-z0-9_$]+$/,g={"in":1,"return":1,"typeof":1},
  h={};return {Ra:[],wa:h,ac:b,vb:function(e,f){function l(b,e){var f;if(!x){var k=a.getBindingHandler(b);if(k&&k.preprocess&&!(e=k.preprocess(e,b,l)))return;if(k=h[b])f=e,0<=a.a.A(c,f)?f=!1:(k=f.match(d),f=null===k?!1:k[1]?"Object("+k[1]+")"+k[2]:f),k=f;k&&q.push("'"+("string"==typeof h[b]?h[b]:b)+"':function(_z){"+f+"=_z}");}g&&(e="function(){return "+e+" }");p.push("'"+b+"':"+e);}f=f||{};var p=[],q=[],g=f.valueAccessors,x=f.bindingParams,B="string"===typeof e?b(e):e;a.a.D(B,function(a){l(a.key||a.unknown,
  a.value);});q.length&&l("_ko_property_writers","{"+q.join(",")+" }");return p.join(",")},Id:function(a,b){for(var c=0;c<a.length;c++)if(a[c].key==b)return !0;return !1},eb:function(b,c,d,e,f){if(b&&a.O(b))!a.Za(b)||f&&b.v()===e||b(e);else if((b=c.get("_ko_property_writers"))&&b[d])b[d](e);}}}();a.b("expressionRewriting",a.m);a.b("expressionRewriting.bindingRewriteValidators",a.m.Ra);a.b("expressionRewriting.parseObjectLiteral",a.m.ac);a.b("expressionRewriting.preProcessBindings",a.m.vb);a.b("expressionRewriting._twoWayBindings",
  a.m.wa);a.b("jsonExpressionRewriting",a.m);a.b("jsonExpressionRewriting.insertPropertyAccessorsIntoJson",a.m.vb);(function(){function b(a){return 8==a.nodeType&&g.test(f?a.text:a.nodeValue)}function c(a){return 8==a.nodeType&&h.test(f?a.text:a.nodeValue)}function d(d,e){for(var f=d,h=1,g=[];f=f.nextSibling;){if(c(f)&&(a.a.g.set(f,k,!0),h--,0===h))return g;g.push(f);b(f)&&h++;}if(!e)throw Error("Cannot find closing comment tag to match: "+d.nodeValue);return null}function e(a,b){var c=d(a,b);return c?
  0<c.length?c[c.length-1].nextSibling:a.nextSibling:null}var f=w&&"\x3c!--test--\x3e"===w.createComment("test").text,g=f?/^\x3c!--\s*ko(?:\s+([\s\S]+))?\s*--\x3e$/:/^\s*ko(?:\s+([\s\S]+))?\s*$/,h=f?/^\x3c!--\s*\/ko\s*--\x3e$/:/^\s*\/ko\s*$/,m={ul:!0,ol:!0},k="__ko_matchedEndComment__";a.h={ea:{},childNodes:function(a){return b(a)?d(a):a.childNodes},Ea:function(c){if(b(c)){c=a.h.childNodes(c);for(var d=0,e=c.length;d<e;d++)a.removeNode(c[d]);}else a.a.Tb(c);},va:function(c,d){if(b(c)){a.h.Ea(c);for(var e=
  c.nextSibling,f=0,k=d.length;f<k;f++)e.parentNode.insertBefore(d[f],e);}else a.a.va(c,d);},Vc:function(a,c){var d;b(a)?(d=a.nextSibling,a=a.parentNode):d=a.firstChild;d?c!==d&&a.insertBefore(c,d):a.appendChild(c);},Wb:function(c,d,e){e?(e=e.nextSibling,b(c)&&(c=c.parentNode),e?d!==e&&c.insertBefore(d,e):c.appendChild(d)):a.h.Vc(c,d);},firstChild:function(a){if(b(a))return !a.nextSibling||c(a.nextSibling)?null:a.nextSibling;if(a.firstChild&&c(a.firstChild))throw Error("Found invalid end comment, as the first child of "+
  a);return a.firstChild},nextSibling:function(d){b(d)&&(d=e(d));if(d.nextSibling&&c(d.nextSibling)){var f=d.nextSibling;if(c(f)&&!a.a.g.get(f,k))throw Error("Found end comment without a matching opening comment, as child of "+d);return null}return d.nextSibling},Cd:b,Vd:function(a){return (a=(f?a.text:a.nodeValue).match(g))?a[1]:null},Sc:function(d){if(m[a.a.R(d)]){var f=d.firstChild;if(f){do if(1===f.nodeType){var k;k=f.firstChild;var h=null;if(k){do if(h)h.push(k);else if(b(k)){var g=e(k,!0);g?k=
  g:h=[k];}else c(k)&&(h=[k]);while(k=k.nextSibling)}if(k=h)for(h=f.nextSibling,g=0;g<k.length;g++)h?d.insertBefore(k[g],h):d.appendChild(k[g]);}while(f=f.nextSibling)}}}};})();a.b("virtualElements",a.h);a.b("virtualElements.allowedBindings",a.h.ea);a.b("virtualElements.emptyNode",a.h.Ea);a.b("virtualElements.insertAfter",a.h.Wb);a.b("virtualElements.prepend",a.h.Vc);a.b("virtualElements.setDomNodeChildren",a.h.va);(function(){a.ga=function(){this.nd={};};a.a.extend(a.ga.prototype,{nodeHasBindings:function(b){switch(b.nodeType){case 1:return null!=
  b.getAttribute("data-bind")||a.j.getComponentNameForNode(b);case 8:return a.h.Cd(b);default:return !1}},getBindings:function(b,c){var d=this.getBindingsString(b,c),d=d?this.parseBindingsString(d,c,b):null;return a.j.tc(d,b,c,!1)},getBindingAccessors:function(b,c){var d=this.getBindingsString(b,c),d=d?this.parseBindingsString(d,c,b,{valueAccessors:!0}):null;return a.j.tc(d,b,c,!0)},getBindingsString:function(b){switch(b.nodeType){case 1:return b.getAttribute("data-bind");case 8:return a.h.Vd(b);default:return null}},
  parseBindingsString:function(b,c,d,e){try{var f=this.nd,g=b+(e&&e.valueAccessors||""),h;if(!(h=f[g])){var m,k="with($context){with($data||{}){return{"+a.m.vb(b,e)+"}}}";m=new Function("$context","$element",k);h=f[g]=m;}return h(c,d)}catch(l){throw l.message="Unable to parse bindings.\nBindings value: "+b+"\nMessage: "+l.message,l;}}});a.ga.instance=new a.ga;})();a.b("bindingProvider",a.ga);(function(){function b(b){var c=(b=a.a.g.get(b,z))&&b.N;c&&(b.N=null,c.Tc());}function c(c,d,e){this.node=c;this.yc=
  d;this.kb=[];this.H=!1;d.N||a.a.K.za(c,b);e&&e.N&&(e.N.kb.push(c),this.Kb=e);}function d(a){return function(){return a}}function e(a){return a()}function f(b){return a.a.Ga(a.u.G(b),function(a,c){return function(){return b()[c]}})}function g(b,c,e){return "function"===typeof b?f(b.bind(null,c,e)):a.a.Ga(b,d)}function h(a,b){return f(this.getBindings.bind(this,a,b))}function m(b,c){var d=a.h.firstChild(c);if(d){var e,f=a.ga.instance,l=f.preprocessNode;if(l){for(;e=d;)d=a.h.nextSibling(e),l.call(f,e);
  d=a.h.firstChild(c);}for(;e=d;)d=a.h.nextSibling(e),k(b,e);}a.i.ma(c,a.i.H);}function k(b,c){var d=b,e=1===c.nodeType;e&&a.h.Sc(c);if(e||a.ga.instance.nodeHasBindings(c))d=p(c,null,b).bindingContextForDescendants;d&&!u[a.a.R(c)]&&m(d,c);}function l(b){var c=[],d={},e=[];a.a.P(b,function ca(f){if(!d[f]){var k=a.getBindingHandler(f);k&&(k.after&&(e.push(f),a.a.D(k.after,function(c){if(b[c]){if(-1!==a.a.A(e,c))throw Error("Cannot combine the following bindings, because they have a cyclic dependency: "+e.join(", "));
  ca(c);}}),e.length--),c.push({key:f,Mc:k}));d[f]=!0;}});return c}function p(b,c,d){var f=a.a.g.Ub(b,z,{}),k=f.hd;if(!c){if(k)throw Error("You cannot apply bindings multiple times to the same element.");f.hd=!0;}k||(f.context=d);f.Zb||(f.Zb={});var g;if(c&&"function"!==typeof c)g=c;else {var p=a.ga.instance,q=p.getBindingAccessors||h,m=a.$(function(){if(g=c?c(d,b):q.call(p,b,d)){if(d[t])d[t]();if(d[B])d[B]();}return g},null,{l:b});g&&m.ja()||(m=null);}var x=d,u;if(g){var J=function(){return a.a.Ga(m?m():
  g,e)},r=m?function(a){return function(){return e(m()[a])}}:function(a){return g[a]};J.get=function(a){return g[a]&&e(r(a))};J.has=function(a){return a in g};a.i.H in g&&a.i.subscribe(b,a.i.H,function(){var c=(0, g[a.i.H])();if(c){var d=a.h.childNodes(b);d.length&&c(d,a.Ec(d[0]));}});a.i.pa in g&&(x=a.i.Cb(b,d),a.i.subscribe(b,a.i.pa,function(){var c=(0, g[a.i.pa])();c&&a.h.firstChild(b)&&c(b);}));f=l(g);a.a.D(f,function(c){var d=c.Mc.init,e=c.Mc.update,f=c.key;if(8===b.nodeType&&!a.h.ea[f])throw Error("The binding '"+
  f+"' cannot be used with virtual elements");try{"function"==typeof d&&a.u.G(function(){var a=d(b,r(f),J,x.$data,x);if(a&&a.controlsDescendantBindings){if(u!==n)throw Error("Multiple bindings ("+u+" and "+f+") are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.");u=f;}}),"function"==typeof e&&a.$(function(){e(b,r(f),J,x.$data,x);},null,{l:b});}catch(k){throw k.message='Unable to process binding "'+f+": "+g[f]+'"\nMessage: '+k.message,
  k;}});}f=u===n;return {shouldBindDescendants:f,bindingContextForDescendants:f&&x}}function q(b,c){return b&&b instanceof a.fa?b:new a.fa(b,n,n,c)}var t=a.a.Da("_subscribable"),x=a.a.Da("_ancestorBindingInfo"),B=a.a.Da("_dataDependency");a.c={};var u={script:!0,textarea:!0,template:!0};a.getBindingHandler=function(b){return a.c[b]};var J={};a.fa=function(b,c,d,e,f){function k(){var b=p?h():h,f=a.a.f(b);c?(a.a.extend(l,c),x in c&&(l[x]=c[x])):(l.$parents=[],l.$root=f,l.ko=a);l[t]=q;g?f=l.$data:(l.$rawData=
  b,l.$data=f);d&&(l[d]=f);e&&e(l,c,f);if(c&&c[t]&&!a.S.o().Vb(c[t]))c[t]();m&&(l[B]=m);return l.$data}var l=this,g=b===J,h=g?n:b,p="function"==typeof h&&!a.O(h),q,m=f&&f.dataDependency;f&&f.exportDependencies?k():(q=a.xb(k),q.v(),q.ja()?q.equalityComparer=null:l[t]=n);};a.fa.prototype.createChildContext=function(b,c,d,e){!e&&c&&"object"==typeof c&&(e=c,c=e.as,d=e.extend);if(c&&e&&e.noChildContext){var f="function"==typeof b&&!a.O(b);return new a.fa(J,this,null,function(a){d&&d(a);a[c]=f?b():b;},e)}return new a.fa(b,
  this,c,function(a,b){a.$parentContext=b;a.$parent=b.$data;a.$parents=(b.$parents||[]).slice(0);a.$parents.unshift(a.$parent);d&&d(a);},e)};a.fa.prototype.extend=function(b,c){return new a.fa(J,this,null,function(c){a.a.extend(c,"function"==typeof b?b(c):b);},c)};var z=a.a.g.Z();c.prototype.Tc=function(){this.Kb&&this.Kb.N&&this.Kb.N.sd(this.node);};c.prototype.sd=function(b){a.a.Pa(this.kb,b);!this.kb.length&&this.H&&this.Cc();};c.prototype.Cc=function(){this.H=!0;this.yc.N&&!this.kb.length&&(this.yc.N=
  null,a.a.K.yb(this.node,b),a.i.ma(this.node,a.i.pa),this.Tc());};a.i={H:"childrenComplete",pa:"descendantsComplete",subscribe:function(b,c,d,e,f){var k=a.a.g.Ub(b,z,{});k.Fa||(k.Fa=new a.T);f&&f.notifyImmediately&&k.Zb[c]&&a.u.G(d,e,[b]);return k.Fa.subscribe(d,e,c)},ma:function(b,c){var d=a.a.g.get(b,z);if(d&&(d.Zb[c]=!0,d.Fa&&d.Fa.notifySubscribers(b,c),c==a.i.H))if(d.N)d.N.Cc();else if(d.N===n&&d.Fa&&d.Fa.Wa(a.i.pa))throw Error("descendantsComplete event not supported for bindings on this node");
  },Cb:function(b,d){var e=a.a.g.Ub(b,z,{});e.N||(e.N=new c(b,e,d[x]));return d[x]==e?d:d.extend(function(a){a[x]=e;})}};a.Td=function(b){return (b=a.a.g.get(b,z))&&b.context};a.ib=function(b,c,d){1===b.nodeType&&a.h.Sc(b);return p(b,c,q(d))};a.ld=function(b,c,d){d=q(d);return a.ib(b,g(c,d,b),d)};a.Oa=function(a,b){1!==b.nodeType&&8!==b.nodeType||m(q(a),b);};a.vc=function(a,b,c){!v&&A.jQuery&&(v=A.jQuery);if(2>arguments.length){if(b=w.body,!b)throw Error("ko.applyBindings: could not find document.body; has the document been loaded?");
  }else if(!b||1!==b.nodeType&&8!==b.nodeType)throw Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");k(q(a,c),b);};a.Dc=function(b){return !b||1!==b.nodeType&&8!==b.nodeType?n:a.Td(b)};a.Ec=function(b){return (b=a.Dc(b))?b.$data:n};a.b("bindingHandlers",a.c);a.b("bindingEvent",a.i);a.b("bindingEvent.subscribe",a.i.subscribe);a.b("bindingEvent.startPossiblyAsyncContentBinding",a.i.Cb);a.b("applyBindings",a.vc);a.b("applyBindingsToDescendants",a.Oa);
  a.b("applyBindingAccessorsToNode",a.ib);a.b("applyBindingsToNode",a.ld);a.b("contextFor",a.Dc);a.b("dataFor",a.Ec);})();(function(b){function c(c,e){var k=Object.prototype.hasOwnProperty.call(f,c)?f[c]:b,l;k?k.subscribe(e):(k=f[c]=new a.T,k.subscribe(e),d(c,function(b,d){var e=!(!d||!d.synchronous);g[c]={definition:b,Gd:e};delete f[c];l||e?k.notifySubscribers(b):a.na.zb(function(){k.notifySubscribers(b);});}),l=!0);}function d(a,b){e("getConfig",[a],function(c){c?e("loadComponent",[a,c],function(a){b(a,
  c);}):b(null,null);});}function e(c,d,f,l){l||(l=a.j.loaders.slice(0));var g=l.shift();if(g){var q=g[c];if(q){var t=!1;if(q.apply(g,d.concat(function(a){t?f(null):null!==a?f(a):e(c,d,f,l);}))!==b&&(t=!0,!g.suppressLoaderExceptions))throw Error("Component loaders must supply values by invoking the callback, not by returning values synchronously.");}else e(c,d,f,l);}else f(null);}var f={},g={};a.j={get:function(d,e){var f=Object.prototype.hasOwnProperty.call(g,d)?g[d]:b;f?f.Gd?a.u.G(function(){e(f.definition);}):
  a.na.zb(function(){e(f.definition);}):c(d,e);},Bc:function(a){delete g[a];},oc:e};a.j.loaders=[];a.b("components",a.j);a.b("components.get",a.j.get);a.b("components.clearCachedDefinition",a.j.Bc);})();(function(){function b(b,c,d,e){function g(){0===--B&&e(h);}var h={},B=2,u=d.template;d=d.viewModel;u?f(c,u,function(c){a.j.oc("loadTemplate",[b,c],function(a){h.template=a;g();});}):g();d?f(c,d,function(c){a.j.oc("loadViewModel",[b,c],function(a){h[m]=a;g();});}):g();}function c(a,b,d){if("function"===typeof b)d(function(a){return new b(a)});
  else if("function"===typeof b[m])d(b[m]);else if("instance"in b){var e=b.instance;d(function(){return e});}else "viewModel"in b?c(a,b.viewModel,d):a("Unknown viewModel value: "+b);}function d(b){switch(a.a.R(b)){case "script":return a.a.ua(b.text);case "textarea":return a.a.ua(b.value);case "template":if(e(b.content))return a.a.Ca(b.content.childNodes)}return a.a.Ca(b.childNodes)}function e(a){return A.DocumentFragment?a instanceof DocumentFragment:a&&11===a.nodeType}function f(a,b,c){"string"===typeof b.require?
  T||A.require?(T||A.require)([b.require],function(a){a&&"object"===typeof a&&a.Xd&&a["default"]&&(a=a["default"]);c(a);}):a("Uses require, but no AMD loader is present"):c(b);}function g(a){return function(b){throw Error("Component '"+a+"': "+b);}}var h={};a.j.register=function(b,c){if(!c)throw Error("Invalid configuration for "+b);if(a.j.tb(b))throw Error("Component "+b+" is already registered");h[b]=c;};a.j.tb=function(a){return Object.prototype.hasOwnProperty.call(h,a)};a.j.unregister=function(b){delete h[b];
  a.j.Bc(b);};a.j.Fc={getConfig:function(b,c){c(a.j.tb(b)?h[b]:null);},loadComponent:function(a,c,d){var e=g(a);f(e,c,function(c){b(a,e,c,d);});},loadTemplate:function(b,c,f){b=g(b);if("string"===typeof c)f(a.a.ua(c));else if(c instanceof Array)f(c);else if(e(c))f(a.a.la(c.childNodes));else if(c.element)if(c=c.element,A.HTMLElement?c instanceof HTMLElement:c&&c.tagName&&1===c.nodeType)f(d(c));else if("string"===typeof c){var h=w.getElementById(c);h?f(d(h)):b("Cannot find element with ID "+c);}else b("Unknown element type: "+
  c);else b("Unknown template value: "+c);},loadViewModel:function(a,b,d){c(g(a),b,d);}};var m="createViewModel";a.b("components.register",a.j.register);a.b("components.isRegistered",a.j.tb);a.b("components.unregister",a.j.unregister);a.b("components.defaultLoader",a.j.Fc);a.j.loaders.push(a.j.Fc);a.j.dd=h;})();(function(){function b(b,e){var f=b.getAttribute("params");if(f){var f=c.parseBindingsString(f,e,b,{valueAccessors:!0,bindingParams:!0}),f=a.a.Ga(f,function(c){return a.o(c,null,{l:b})}),g=a.a.Ga(f,
  function(c){var e=c.v();return c.ja()?a.o({read:function(){return a.a.f(c())},write:a.Za(e)&&function(a){c()(a);},l:b}):e});Object.prototype.hasOwnProperty.call(g,"$raw")||(g.$raw=f);return g}return {$raw:{}}}a.j.getComponentNameForNode=function(b){var c=a.a.R(b);if(a.j.tb(c)&&(-1!=c.indexOf("-")||"[object HTMLUnknownElement]"==""+b||8>=a.a.W&&b.tagName===c))return c};a.j.tc=function(c,e,f,g){if(1===e.nodeType){var h=a.j.getComponentNameForNode(e);if(h){c=c||{};if(c.component)throw Error('Cannot use the "component" binding on a custom element matching a component');
  var m={name:h,params:b(e,f)};c.component=g?function(){return m}:m;}}return c};var c=new a.ga;9>a.a.W&&(a.j.register=function(a){return function(b){return a.apply(this,arguments)}}(a.j.register),w.createDocumentFragment=function(b){return function(){var c=b();a.j.dd;return c}}(w.createDocumentFragment));})();(function(){function b(b,c,d){c=c.template;if(!c)throw Error("Component '"+b+"' has no template");b=a.a.Ca(c);a.h.va(d,b);}function c(a,b,c){var d=a.createViewModel;return d?d.call(a,
  b,c):b}var d=0;a.c.component={init:function(e,f,g,h,m){function k(){var a=l&&l.dispose;"function"===typeof a&&a.call(l);q&&q.s();p=l=q=null;}var l,p,q,t=a.a.la(a.h.childNodes(e));a.h.Ea(e);a.a.K.za(e,k);a.o(function(){var g=a.a.f(f()),h,u;"string"===typeof g?h=g:(h=a.a.f(g.name),u=a.a.f(g.params));if(!h)throw Error("No component name specified");var n=a.i.Cb(e,m),z=p=++d;a.j.get(h,function(d){if(p===z){k();if(!d)throw Error("Unknown component '"+h+"'");b(h,d,e);var f=c(d,u,{element:e,templateNodes:t});
  d=n.createChildContext(f,{extend:function(a){a.$component=f;a.$componentTemplateNodes=t;}});f&&f.koDescendantsComplete&&(q=a.i.subscribe(e,a.i.pa,f.koDescendantsComplete,f));l=f;a.Oa(d,e);}});},null,{l:e});return {controlsDescendantBindings:!0}}};a.h.ea.component=!0;})();var V={"class":"className","for":"htmlFor"};a.c.attr={update:function(b,c){var d=a.a.f(c())||{};a.a.P(d,function(c,d){d=a.a.f(d);var g=c.indexOf(":"),g="lookupNamespaceURI"in b&&0<g&&b.lookupNamespaceURI(c.substr(0,g)),h=!1===d||null===
  d||d===n;h?g?b.removeAttributeNS(g,c):b.removeAttribute(c):d=d.toString();8>=a.a.W&&c in V?(c=V[c],h?b.removeAttribute(c):b[c]=d):h||(g?b.setAttributeNS(g,c,d):b.setAttribute(c,d));"name"===c&&a.a.Yc(b,h?"":d);});}};(function(){a.c.checked={after:["value","attr"],init:function(b,c,d){function e(){var e=b.checked,f=g();if(!a.S.Ya()&&(e||!m&&!a.S.qa())){var k=a.u.G(c);if(l){var q=p?k.v():k,z=t;t=f;z!==f?e&&(a.a.Na(q,f,!0),a.a.Na(q,z,!1)):a.a.Na(q,f,e);p&&a.Za(k)&&k(q);}else h&&(f===n?f=e:e||(f=n)),a.m.eb(k,
  d,"checked",f,!0);}}function f(){var d=a.a.f(c()),e=g();l?(b.checked=0<=a.a.A(d,e),t=e):b.checked=h&&e===n?!!d:g()===d;}var g=a.xb(function(){if(d.has("checkedValue"))return a.a.f(d.get("checkedValue"));if(q)return d.has("value")?a.a.f(d.get("value")):b.value}),h="checkbox"==b.type,m="radio"==b.type;if(h||m){var k=c(),l=h&&a.a.f(k)instanceof Array,p=!(l&&k.push&&k.splice),q=m||l,t=l?g():n;m&&!b.name&&a.c.uniqueName.init(b,function(){return !0});a.o(e,null,{l:b});a.a.B(b,"click",e);a.o(f,null,{l:b});
  k=n;}}};a.m.wa.checked=!0;a.c.checkedValue={update:function(b,c){b.value=a.a.f(c());}};})();a.c["class"]={update:function(b,c){var d=a.a.Db(a.a.f(c()));a.a.Eb(b,b.__ko__cssValue,!1);b.__ko__cssValue=d;a.a.Eb(b,d,!0);}};a.c.css={update:function(b,c){var d=a.a.f(c());null!==d&&"object"==typeof d?a.a.P(d,function(c,d){d=a.a.f(d);a.a.Eb(b,c,d);}):a.c["class"].update(b,c);}};a.c.enable={update:function(b,c){var d=a.a.f(c());d&&b.disabled?b.removeAttribute("disabled"):d||b.disabled||(b.disabled=!0);}};a.c.disable=
  {update:function(b,c){a.c.enable.update(b,function(){return !a.a.f(c())});}};a.c.event={init:function(b,c,d,e,f){var g=c()||{};a.a.P(g,function(g){"string"==typeof g&&a.a.B(b,g,function(b){var k,l=c()[g];if(l){try{var p=a.a.la(arguments);e=f.$data;p.unshift(e);k=l.apply(e,p);}finally{!0!==k&&(b.preventDefault?b.preventDefault():b.returnValue=!1);}!1===d.get(g+"Bubble")&&(b.cancelBubble=!0,b.stopPropagation&&b.stopPropagation());}});});}};a.c.foreach={Rc:function(b){return function(){var c=b(),d=a.a.bc(c);
  if(!d||"number"==typeof d.length)return {foreach:c,templateEngine:a.ba.Ma};a.a.f(c);return {foreach:d.data,as:d.as,noChildContext:d.noChildContext,includeDestroyed:d.includeDestroyed,afterAdd:d.afterAdd,beforeRemove:d.beforeRemove,afterRender:d.afterRender,beforeMove:d.beforeMove,afterMove:d.afterMove,templateEngine:a.ba.Ma}}},init:function(b,c){return a.c.template.init(b,a.c.foreach.Rc(c))},update:function(b,c,d,e,f){return a.c.template.update(b,a.c.foreach.Rc(c),d,e,f)}};a.m.Ra.foreach=!1;a.h.ea.foreach=
  !0;a.c.hasfocus={init:function(b,c,d){function e(e){b.__ko_hasfocusUpdating=!0;var f=b.ownerDocument;if("activeElement"in f){var g;try{g=f.activeElement;}catch(l){g=f.body;}e=g===b;}f=c();a.m.eb(f,d,"hasfocus",e,!0);b.__ko_hasfocusLastValue=e;b.__ko_hasfocusUpdating=!1;}var f=e.bind(null,!0),g=e.bind(null,!1);a.a.B(b,"focus",f);a.a.B(b,"focusin",f);a.a.B(b,"blur",g);a.a.B(b,"focusout",g);b.__ko_hasfocusLastValue=!1;},update:function(b,c){var d=!!a.a.f(c());b.__ko_hasfocusUpdating||b.__ko_hasfocusLastValue===
  d||(d?b.focus():b.blur(),!d&&b.__ko_hasfocusLastValue&&b.ownerDocument.body.focus(),a.u.G(a.a.Fb,null,[b,d?"focusin":"focusout"]));}};a.m.wa.hasfocus=!0;a.c.hasFocus=a.c.hasfocus;a.m.wa.hasFocus="hasfocus";a.c.html={init:function(){return {controlsDescendantBindings:!0}},update:function(b,c){a.a.fc(b,c());}};(function(){function b(b,d,e){a.c[b]={init:function(b,c,h,m,k){var l,p,q={},t,x,n;if(d){m=h.get("as");var u=h.get("noChildContext");n=!(m&&u);q={as:m,noChildContext:u,exportDependencies:n};}x=(t=
  "render"==h.get("completeOn"))||h.has(a.i.pa);a.o(function(){var h=a.a.f(c()),m=!e!==!h,u=!p,r;if(n||m!==l){x&&(k=a.i.Cb(b,k));if(m){if(!d||n)q.dataDependency=a.S.o();r=d?k.createChildContext("function"==typeof h?h:c,q):a.S.qa()?k.extend(null,q):k;}u&&a.S.qa()&&(p=a.a.Ca(a.h.childNodes(b),!0));m?(u||a.h.va(b,a.a.Ca(p)),a.Oa(r,b)):(a.h.Ea(b),t||a.i.ma(b,a.i.H));l=m;}},null,{l:b});return {controlsDescendantBindings:!0}}};a.m.Ra[b]=!1;a.h.ea[b]=!0;}b("if");b("ifnot",!1,!0);b("with",!0);})();a.c.let={init:function(b,
  c,d,e,f){c=f.extend(c);a.Oa(c,b);return {controlsDescendantBindings:!0}}};a.h.ea.let=!0;var Q={};a.c.options={init:function(b){if("select"!==a.a.R(b))throw Error("options binding applies only to SELECT elements");for(;0<b.length;)b.remove(0);return {controlsDescendantBindings:!0}},update:function(b,c,d){function e(){return a.a.jb(b.options,function(a){return a.selected})}function f(a,b,c){var d=typeof b;return "function"==d?b(a):"string"==d?a[b]:c}function g(c,d){if(x&&l)a.i.ma(b,a.i.H);else if(t.length){var e=
  0<=a.a.A(t,a.w.M(d[0]));a.a.Zc(d[0],e);x&&!e&&a.u.G(a.a.Fb,null,[b,"change"]);}}var h=b.multiple,m=0!=b.length&&h?b.scrollTop:null,k=a.a.f(c()),l=d.get("valueAllowUnset")&&d.has("value"),p=d.get("optionsIncludeDestroyed");c={};var q,t=[];l||(h?t=a.a.Mb(e(),a.w.M):0<=b.selectedIndex&&t.push(a.w.M(b.options[b.selectedIndex])));k&&("undefined"==typeof k.length&&(k=[k]),q=a.a.jb(k,function(b){return p||b===n||null===b||!a.a.f(b._destroy)}),d.has("optionsCaption")&&(k=a.a.f(d.get("optionsCaption")),null!==
  k&&k!==n&&q.unshift(Q)));var x=!1;c.beforeRemove=function(a){b.removeChild(a);};k=g;d.has("optionsAfterRender")&&"function"==typeof d.get("optionsAfterRender")&&(k=function(b,c){g(0,c);a.u.G(d.get("optionsAfterRender"),null,[c[0],b!==Q?b:n]);});a.a.ec(b,q,function(c,e,g){g.length&&(t=!l&&g[0].selected?[a.w.M(g[0])]:[],x=!0);e=b.ownerDocument.createElement("option");c===Q?(a.a.Bb(e,d.get("optionsCaption")),a.w.cb(e,n)):(g=f(c,d.get("optionsValue"),c),a.w.cb(e,a.a.f(g)),c=f(c,d.get("optionsText"),g),
  a.a.Bb(e,c));return [e]},c,k);if(!l){var B;h?B=t.length&&e().length<t.length:B=t.length&&0<=b.selectedIndex?a.w.M(b.options[b.selectedIndex])!==t[0]:t.length||0<=b.selectedIndex;B&&a.u.G(a.a.Fb,null,[b,"change"]);}(l||a.S.Ya())&&a.i.ma(b,a.i.H);a.a.wd(b);m&&20<Math.abs(m-b.scrollTop)&&(b.scrollTop=m);}};a.c.options.$b=a.a.g.Z();a.c.selectedOptions={init:function(b,c,d){function e(){var e=c(),f=[];a.a.D(b.getElementsByTagName("option"),function(b){b.selected&&f.push(a.w.M(b));});a.m.eb(e,d,"selectedOptions",
  f);}function f(){var d=a.a.f(c()),e=b.scrollTop;d&&"number"==typeof d.length&&a.a.D(b.getElementsByTagName("option"),function(b){var c=0<=a.a.A(d,a.w.M(b));b.selected!=c&&a.a.Zc(b,c);});b.scrollTop=e;}if("select"!=a.a.R(b))throw Error("selectedOptions binding applies only to SELECT elements");var g;a.i.subscribe(b,a.i.H,function(){g?e():(a.a.B(b,"change",e),g=a.o(f,null,{l:b}));},null,{notifyImmediately:!0});},update:function(){}};a.m.wa.selectedOptions=!0;a.c.style={update:function(b,c){var d=a.a.f(c()||
  {});a.a.P(d,function(c,d){d=a.a.f(d);if(null===d||d===n||!1===d)d="";if(v)v(b).css(c,d);else if(/^--/.test(c))b.style.setProperty(c,d);else {c=c.replace(/-(\w)/g,function(a,b){return b.toUpperCase()});var g=b.style[c];b.style[c]=d;d===g||b.style[c]!=g||isNaN(d)||(b.style[c]=d+"px");}});}};a.c.submit={init:function(b,c,d,e,f){if("function"!=typeof c())throw Error("The value for a submit binding must be a function");a.a.B(b,"submit",function(a){var d,e=c();try{d=e.call(f.$data,b);}finally{!0!==d&&(a.preventDefault?
  a.preventDefault():a.returnValue=!1);}});}};a.c.text={init:function(){return {controlsDescendantBindings:!0}},update:function(b,c){a.a.Bb(b,c());}};a.h.ea.text=!0;(function(){if(A&&A.navigator){var b=function(a){if(a)return parseFloat(a[1])},c=A.navigator.userAgent,d,e,f,g,h;(d=A.opera&&A.opera.version&&parseInt(A.opera.version()))||(h=b(c.match(/Edge\/([^ ]+)$/)))||b(c.match(/Chrome\/([^ ]+)/))||(e=b(c.match(/Version\/([^ ]+) Safari/)))||(f=b(c.match(/Firefox\/([^ ]+)/)))||(g=a.a.W||b(c.match(/MSIE ([^ ]+)/)))||
  (g=b(c.match(/rv:([^ )]+)/)));}if(8<=g&&10>g)var m=a.a.g.Z(),k=a.a.g.Z(),l=function(b){var c=this.activeElement;(c=c&&a.a.g.get(c,k))&&c(b);},p=function(b,c){var d=b.ownerDocument;a.a.g.get(d,m)||(a.a.g.set(d,m,!0),a.a.B(d,"selectionchange",l));a.a.g.set(b,k,c);};a.c.textInput={init:function(b,c,k){function l(c,d){a.a.B(b,c,d);}function m(){var d=a.a.f(c());if(null===d||d===n)d="";L!==n&&d===L?a.a.setTimeout(m,4):b.value!==d&&(y=!0,b.value=d,y=!1,v=b.value);}function r(){w||(L=b.value,w=a.a.setTimeout(z,
  4));}function z(){clearTimeout(w);L=w=n;var d=b.value;v!==d&&(v=d,a.m.eb(c(),k,"textInput",d));}var v=b.value,w,L,A=9==a.a.W?r:z,y=!1;g&&l("keypress",z);11>g&&l("propertychange",function(a){y||"value"!==a.propertyName||A();});8==g&&(l("keyup",z),l("keydown",z));p&&(p(b,A),l("dragend",r));(!g||9<=g)&&l("input",A);5>e&&"textarea"===a.a.R(b)?(l("keydown",r),l("paste",r),l("cut",r)):11>d?l("keydown",r):4>f?(l("DOMAutoComplete",z),l("dragdrop",z),l("drop",z)):h&&"number"===b.type&&l("keydown",r);l("change",
  z);l("blur",z);a.o(m,null,{l:b});}};a.m.wa.textInput=!0;a.c.textinput={preprocess:function(a,b,c){c("textInput",a);}};})();a.c.uniqueName={init:function(b,c){if(c()){var d="ko_unique_"+ ++a.c.uniqueName.rd;a.a.Yc(b,d);}}};a.c.uniqueName.rd=0;a.c.using={init:function(b,c,d,e,f){var g;d.has("as")&&(g={as:d.get("as"),noChildContext:d.get("noChildContext")});c=f.createChildContext(c,g);a.Oa(c,b);return {controlsDescendantBindings:!0}}};a.h.ea.using=!0;a.c.value={init:function(b,c,d){var e=a.a.R(b),f="input"==
  e;if(!f||"checkbox"!=b.type&&"radio"!=b.type){var g=[],h=d.get("valueUpdate"),m=!1,k=null;h&&("string"==typeof h?g=[h]:g=a.a.wc(h),a.a.Pa(g,"change"));var l=function(){k=null;m=!1;var e=c(),f=a.w.M(b);a.m.eb(e,d,"value",f);};!a.a.W||!f||"text"!=b.type||"off"==b.autocomplete||b.form&&"off"==b.form.autocomplete||-1!=a.a.A(g,"propertychange")||(a.a.B(b,"propertychange",function(){m=!0;}),a.a.B(b,"focus",function(){m=!1;}),a.a.B(b,"blur",function(){m&&l();}));a.a.D(g,function(c){var d=l;a.a.Ud(c,"after")&&
  (d=function(){k=a.w.M(b);a.a.setTimeout(l,0);},c=c.substring(5));a.a.B(b,c,d);});var p;p=f&&"file"==b.type?function(){var d=a.a.f(c());null===d||d===n||""===d?b.value="":a.u.G(l);}:function(){var f=a.a.f(c()),g=a.w.M(b);if(null!==k&&f===k)a.a.setTimeout(p,0);else if(f!==g||g===n)"select"===e?(g=d.get("valueAllowUnset"),a.w.cb(b,f,g),g||f===a.w.M(b)||a.u.G(l)):a.w.cb(b,f);};if("select"===e){var q;a.i.subscribe(b,a.i.H,function(){q?d.get("valueAllowUnset")?p():l():(a.a.B(b,"change",l),q=a.o(p,null,{l:b}));},
  null,{notifyImmediately:!0});}else a.a.B(b,"change",l),a.o(p,null,{l:b});}else a.ib(b,{checkedValue:c});},update:function(){}};a.m.wa.value=!0;a.c.visible={update:function(b,c){var d=a.a.f(c()),e="none"!=b.style.display;d&&!e?b.style.display="":!d&&e&&(b.style.display="none");}};a.c.hidden={update:function(b,c){a.c.visible.update(b,function(){return !a.a.f(c())});}};(function(b){a.c[b]={init:function(c,d,e,f,g){return a.c.event.init.call(this,c,function(){var a={};a[b]=d();return a},e,f,g)}};})("click");
  a.ca=function(){};a.ca.prototype.renderTemplateSource=function(){throw Error("Override renderTemplateSource");};a.ca.prototype.createJavaScriptEvaluatorBlock=function(){throw Error("Override createJavaScriptEvaluatorBlock");};a.ca.prototype.makeTemplateSource=function(b,c){if("string"==typeof b){c=c||w;var d=c.getElementById(b);if(!d)throw Error("Cannot find template with ID "+b);return new a.C.F(d)}if(1==b.nodeType||8==b.nodeType)return new a.C.ia(b);throw Error("Unknown template type: "+b);};a.ca.prototype.renderTemplate=
  function(a,c,d,e){a=this.makeTemplateSource(a,e);return this.renderTemplateSource(a,c,d,e)};a.ca.prototype.isTemplateRewritten=function(a,c){return !1===this.allowTemplateRewriting?!0:this.makeTemplateSource(a,c).data("isRewritten")};a.ca.prototype.rewriteTemplate=function(a,c,d){a=this.makeTemplateSource(a,d);c=c(a.text());a.text(c);a.data("isRewritten",!0);};a.b("templateEngine",a.ca);a.kc=function(){function b(b,c,d,h){b=a.m.ac(b);for(var m=a.m.Ra,k=0;k<b.length;k++){var l=b[k].key;if(Object.prototype.hasOwnProperty.call(m,
  l)){var p=m[l];if("function"===typeof p){if(l=p(b[k].value))throw Error(l);}else if(!p)throw Error("This template engine does not support the '"+l+"' binding within its templates");}}d="ko.__tr_ambtns(function($context,$element){return(function(){return{ "+a.m.vb(b,{valueAccessors:!0})+" } })()},'"+d.toLowerCase()+"')";return h.createJavaScriptEvaluatorBlock(d)+c}var c=/(<([a-z]+\d*)(?:\s+(?!data-bind\s*=\s*)[a-z0-9\-]+(?:=(?:\"[^\"]*\"|\'[^\']*\'|[^>]*))?)*\s+)data-bind\s*=\s*(["'])([\s\S]*?)\3/gi,
  d=/\x3c!--\s*ko\b\s*([\s\S]*?)\s*--\x3e/g;return {xd:function(b,c,d){c.isTemplateRewritten(b,d)||c.rewriteTemplate(b,function(b){return a.kc.Ld(b,c)},d);},Ld:function(a,f){return a.replace(c,function(a,c,d,e,l){return b(l,c,d,f)}).replace(d,function(a,c){return b(c,"\x3c!-- ko --\x3e","#comment",f)})},md:function(b,c){return a.aa.Xb(function(d,h){var m=d.nextSibling;m&&m.nodeName.toLowerCase()===c&&a.ib(m,b,h);})}}}();a.b("__tr_ambtns",a.kc.md);(function(){a.C={};a.C.F=function(b){if(this.F=b){var c=
  a.a.R(b);this.ab="script"===c?1:"textarea"===c?2:"template"==c&&b.content&&11===b.content.nodeType?3:4;}};a.C.F.prototype.text=function(){var b=1===this.ab?"text":2===this.ab?"value":"innerHTML";if(0==arguments.length)return this.F[b];var c=arguments[0];"innerHTML"===b?a.a.fc(this.F,c):this.F[b]=c;};var b=a.a.g.Z()+"_";a.C.F.prototype.data=function(c){if(1===arguments.length)return a.a.g.get(this.F,b+c);a.a.g.set(this.F,b+c,arguments[1]);};var c=a.a.g.Z();a.C.F.prototype.nodes=function(){var b=this.F;
  if(0==arguments.length){var e=a.a.g.get(b,c)||{},f=e.lb||(3===this.ab?b.content:4===this.ab?b:n);if(!f||e.jd){var g=this.text();g&&g!==e.bb&&(f=a.a.Md(g,b.ownerDocument),a.a.g.set(b,c,{lb:f,bb:g,jd:!0}));}return f}e=arguments[0];this.ab!==n&&this.text("");a.a.g.set(b,c,{lb:e});};a.C.ia=function(a){this.F=a;};a.C.ia.prototype=new a.C.F;a.C.ia.prototype.constructor=a.C.ia;a.C.ia.prototype.text=function(){if(0==arguments.length){var b=a.a.g.get(this.F,c)||{};b.bb===n&&b.lb&&(b.bb=b.lb.innerHTML);return b.bb}a.a.g.set(this.F,
  c,{bb:arguments[0]});};a.b("templateSources",a.C);a.b("templateSources.domElement",a.C.F);a.b("templateSources.anonymousTemplate",a.C.ia);})();(function(){function b(b,c,d){var e;for(c=a.h.nextSibling(c);b&&(e=b)!==c;)b=a.h.nextSibling(e),d(e,b);}function c(c,d){if(c.length){var e=c[0],f=c[c.length-1],g=e.parentNode,h=a.ga.instance,m=h.preprocessNode;if(m){b(e,f,function(a,b){var c=a.previousSibling,d=m.call(h,a);d&&(a===e&&(e=d[0]||b),a===f&&(f=d[d.length-1]||c));});c.length=0;if(!e)return;e===f?c.push(e):
  (c.push(e,f),a.a.Ua(c,g));}b(e,f,function(b){1!==b.nodeType&&8!==b.nodeType||a.vc(d,b);});b(e,f,function(b){1!==b.nodeType&&8!==b.nodeType||a.aa.cd(b,[d]);});a.a.Ua(c,g);}}function d(a){return a.nodeType?a:0<a.length?a[0]:null}function e(b,e,f,h,m){m=m||{};var n=(b&&d(b)||f||{}).ownerDocument,B=m.templateEngine||g;a.kc.xd(f,B,n);f=B.renderTemplate(f,h,m,n);if("number"!=typeof f.length||0<f.length&&"number"!=typeof f[0].nodeType)throw Error("Template engine must return an array of DOM nodes");n=!1;switch(e){case "replaceChildren":a.h.va(b,
  f);n=!0;break;case "replaceNode":a.a.Xc(b,f);n=!0;break;case "ignoreTargetNode":break;default:throw Error("Unknown renderMode: "+e);}n&&(c(f,h),m.afterRender&&a.u.G(m.afterRender,null,[f,h[m.as||"$data"]]),"replaceChildren"==e&&a.i.ma(b,a.i.H));return f}function f(b,c,d){return a.O(b)?b():"function"===typeof b?b(c,d):b}var g;a.gc=function(b){if(b!=n&&!(b instanceof a.ca))throw Error("templateEngine must inherit from ko.templateEngine");g=b;};a.dc=function(b,c,h,m,t){h=h||{};if((h.templateEngine||g)==
  n)throw Error("Set a template engine before calling renderTemplate");t=t||"replaceChildren";if(m){var x=d(m);return a.$(function(){var g=c&&c instanceof a.fa?c:new a.fa(c,null,null,null,{exportDependencies:!0}),n=f(b,g.$data,g),g=e(m,t,n,g,h);"replaceNode"==t&&(m=g,x=d(m));},null,{Sa:function(){return !x||!a.a.Sb(x)},l:x&&"replaceNode"==t?x.parentNode:x})}return a.aa.Xb(function(d){a.dc(b,c,h,d,"replaceNode");})};a.Qd=function(b,d,g,h,m){function x(b,c){a.u.G(a.a.ec,null,[h,b,u,g,r,c]);a.i.ma(h,a.i.H);}
  function r(a,b){c(b,v);g.afterRender&&g.afterRender(b,a);v=null;}function u(a,c){v=m.createChildContext(a,{as:z,noChildContext:g.noChildContext,extend:function(a){a.$index=c;z&&(a[z+"Index"]=c);}});var d=f(b,a,v);return e(h,"ignoreTargetNode",d,v,g)}var v,z=g.as,w=!1===g.includeDestroyed||a.options.foreachHidesDestroyed&&!g.includeDestroyed;if(w||g.beforeRemove||!a.Pc(d))return a.$(function(){var b=a.a.f(d)||[];"undefined"==typeof b.length&&(b=[b]);w&&(b=a.a.jb(b,function(b){return b===n||null===b||
  !a.a.f(b._destroy)}));x(b);},null,{l:h});x(d.v());var A=d.subscribe(function(a){x(d(),a);},null,"arrayChange");A.l(h);return A};var h=a.a.g.Z(),m=a.a.g.Z();a.c.template={init:function(b,c){var d=a.a.f(c());if("string"==typeof d||"name"in d)a.h.Ea(b);else if("nodes"in d){d=d.nodes||[];if(a.O(d))throw Error('The "nodes" option must be a plain, non-observable array.');var e=d[0]&&d[0].parentNode;e&&a.a.g.get(e,m)||(e=a.a.Yb(d),a.a.g.set(e,m,!0));(new a.C.ia(b)).nodes(e);}else if(d=a.h.childNodes(b),0<d.length)e=
  a.a.Yb(d),(new a.C.ia(b)).nodes(e);else throw Error("Anonymous template defined, but no template content was provided");return {controlsDescendantBindings:!0}},update:function(b,c,d,e,f){var g=c();c=a.a.f(g);d=!0;e=null;"string"==typeof c?c={}:(g="name"in c?c.name:b,"if"in c&&(d=a.a.f(c["if"])),d&&"ifnot"in c&&(d=!a.a.f(c.ifnot)),d&&!g&&(d=!1));"foreach"in c?e=a.Qd(g,d&&c.foreach||[],c,b,f):d?(d=f,"data"in c&&(d=f.createChildContext(c.data,{as:c.as,noChildContext:c.noChildContext,exportDependencies:!0})),
  e=a.dc(g,d,c,b)):a.h.Ea(b);f=e;(c=a.a.g.get(b,h))&&"function"==typeof c.s&&c.s();a.a.g.set(b,h,!f||f.ja&&!f.ja()?n:f);}};a.m.Ra.template=function(b){b=a.m.ac(b);return 1==b.length&&b[0].unknown||a.m.Id(b,"name")?null:"This template engine does not support anonymous templates nested within its templates"};a.h.ea.template=!0;})();a.b("setTemplateEngine",a.gc);a.b("renderTemplate",a.dc);a.a.Kc=function(a,c,d){if(a.length&&c.length){var e,f,g,h,m;for(e=f=0;(!d||e<d)&&(h=a[f]);++f){for(g=0;m=c[g];++g)if(h.value===
  m.value){h.moved=m.index;m.moved=h.index;c.splice(g,1);e=g=0;break}e+=g;}}};a.a.Pb=function(){function b(b,d,e,f,g){var h=Math.min,m=Math.max,k=[],l,p=b.length,q,n=d.length,r=n-p||1,v=p+n+1,u,w,z;for(l=0;l<=p;l++)for(w=u,k.push(u=[]),z=h(n,l+r),q=m(0,l-1);q<=z;q++)u[q]=q?l?b[l-1]===d[q-1]?w[q-1]:h(w[q]||v,u[q-1]||v)+1:q+1:l+1;h=[];m=[];r=[];l=p;for(q=n;l||q;)n=k[l][q]-1,q&&n===k[l][q-1]?m.push(h[h.length]={status:e,value:d[--q],index:q}):l&&n===k[l-1][q]?r.push(h[h.length]={status:f,value:b[--l],index:l}):
  (--q,--l,g.sparse||h.push({status:"retained",value:d[q]}));a.a.Kc(r,m,!g.dontLimitMoves&&10*p);return h.reverse()}return function(a,d,e){e="boolean"===typeof e?{dontLimitMoves:e}:e||{};a=a||[];d=d||[];return a.length<d.length?b(a,d,"added","deleted",e):b(d,a,"deleted","added",e)}}();a.b("utils.compareArrays",a.a.Pb);(function(){function b(b,c,d,h,m){var k=[],l=a.$(function(){var l=c(d,m,a.a.Ua(k,b))||[];0<k.length&&(a.a.Xc(k,l),h&&a.u.G(h,null,[d,l,m]));k.length=0;a.a.Nb(k,l);},null,{l:b,Sa:function(){return !a.a.kd(k)}});
  return {Y:k,$:l.ja()?l:n}}var c=a.a.g.Z(),d=a.a.g.Z();a.a.ec=function(e,f,g,h,m,k){function l(b){y={Aa:b,pb:a.ta(w++)};v.push(y);r||F.push(y);}function p(b){y=t[b];w!==y.pb.v()&&D.push(y);y.pb(w++);a.a.Ua(y.Y,e);v.push(y);}function q(b,c){if(b)for(var d=0,e=c.length;d<e;d++)a.a.D(c[d].Y,function(a){b(a,d,c[d].Aa);});}f=f||[];"undefined"==typeof f.length&&(f=[f]);h=h||{};var t=a.a.g.get(e,c),r=!t,v=[],u=0,w=0,z=[],A=[],C=[],D=[],F=[],y,I=0;if(r)a.a.D(f,l);else {if(!k||t&&t._countWaitingForRemove){var E=
  a.a.Mb(t,function(a){return a.Aa});k=a.a.Pb(E,f,{dontLimitMoves:h.dontLimitMoves,sparse:!0});}for(var E=0,G,H,K;G=k[E];E++)switch(H=G.moved,K=G.index,G.status){case "deleted":for(;u<K;)p(u++);H===n&&(y=t[u],y.$&&(y.$.s(),y.$=n),a.a.Ua(y.Y,e).length&&(h.beforeRemove&&(v.push(y),I++,y.Aa===d?y=null:C.push(y)),y&&z.push.apply(z,y.Y)));u++;break;case "added":for(;w<K;)p(u++);H!==n?(A.push(v.length),p(H)):l(G.value);}for(;w<f.length;)p(u++);v._countWaitingForRemove=I;}a.a.g.set(e,c,v);q(h.beforeMove,D);a.a.D(z,
  h.beforeRemove?a.oa:a.removeNode);var M,O,P;try{P=e.ownerDocument.activeElement;}catch(N){}if(A.length)for(;(E=A.shift())!=n;){y=v[E];for(M=n;E;)if((O=v[--E].Y)&&O.length){M=O[O.length-1];break}for(f=0;u=y.Y[f];M=u,f++)a.h.Wb(e,u,M);}for(E=0;y=v[E];E++){y.Y||a.a.extend(y,b(e,g,y.Aa,m,y.pb));for(f=0;u=y.Y[f];M=u,f++)a.h.Wb(e,u,M);!y.Ed&&m&&(m(y.Aa,y.Y,y.pb),y.Ed=!0,M=y.Y[y.Y.length-1]);}P&&e.ownerDocument.activeElement!=P&&P.focus();q(h.beforeRemove,C);for(E=0;E<C.length;++E)C[E].Aa=d;q(h.afterMove,D);
  q(h.afterAdd,F);};})();a.b("utils.setDomNodeChildrenFromArrayMapping",a.a.ec);a.ba=function(){this.allowTemplateRewriting=!1;};a.ba.prototype=new a.ca;a.ba.prototype.constructor=a.ba;a.ba.prototype.renderTemplateSource=function(b,c,d,e){if(c=(9>a.a.W?0:b.nodes)?b.nodes():null)return a.a.la(c.cloneNode(!0).childNodes);b=b.text();return a.a.ua(b,e)};a.ba.Ma=new a.ba;a.gc(a.ba.Ma);a.b("nativeTemplateEngine",a.ba);(function(){a.$a=function(){var a=this.Hd=function(){if(!v||!v.tmpl)return 0;try{if(0<=v.tmpl.tag.tmpl.open.toString().indexOf("__"))return 2}catch(a){}return 1}();
  this.renderTemplateSource=function(b,e,f,g){g=g||w;f=f||{};if(2>a)throw Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");var h=b.data("precompiled");h||(h=b.text()||"",h=v.template(null,"{{ko_with $item.koBindingContext}}"+h+"{{/ko_with}}"),b.data("precompiled",h));b=[e.$data];e=v.extend({koBindingContext:e},f.templateOptions);e=v.tmpl(h,b,e);e.appendTo(g.createElement("div"));v.fragments={};return e};this.createJavaScriptEvaluatorBlock=function(a){return "{{ko_code ((function() { return "+
  a+" })()) }}"};this.addTemplate=function(a,b){w.write("<script type='text/html' id='"+a+"'>"+b+"\x3c/script>");};0<a&&(v.tmpl.tag.ko_code={open:"__.push($1 || '');"},v.tmpl.tag.ko_with={open:"with($1) {",close:"} "});};a.$a.prototype=new a.ca;a.$a.prototype.constructor=a.$a;var b=new a.$a;0<b.Hd&&a.gc(b);a.b("jqueryTmplTemplateEngine",a.$a);})();});})();})();

  })();

  // Avoid polluting the global scope.
  var knockout = ko;
  if (typeof window !== 'undefined') {
      ko = window.ko;
      if (typeof oldValue !== 'undefined') {
          window.ko = oldValue;
      } else {
          delete window.ko;
      }
  } else {
      ko = global.ko;
      if (typeof oldValue !== 'undefined') {
          global.ko = oldValue;
      } else {
          delete global.ko;
      }
  }

  /**
   * @license
   * Knockout ES5 plugin - https://github.com/SteveSanderson/knockout-es5
   * Copyright (c) Steve Sanderson
   * MIT license
   */

      var OBSERVABLES_PROPERTY = '__knockoutObservables';
      var SUBSCRIBABLE_PROPERTY = '__knockoutSubscribable';

      // Model tracking
      // --------------
      //
      // This is the central feature of Knockout-ES5. We augment model objects by converting properties
      // into ES5 getter/setter pairs that read/write an underlying Knockout observable. This means you can
      // use plain JavaScript syntax to read/write the property while still getting the full benefits of
      // Knockout's automatic dependency detection and notification triggering.
      //
      // For comparison, here's Knockout ES3-compatible syntax:
      //
      //     var firstNameLength = myModel.user().firstName().length; // Read
      //     myModel.user().firstName('Bert'); // Write
      //
      // ... versus Knockout-ES5 syntax:
      //
      //     var firstNameLength = myModel.user.firstName.length; // Read
      //     myModel.user.firstName = 'Bert'; // Write

      // `ko.track(model)` converts each property on the given model object into a getter/setter pair that
      // wraps a Knockout observable. Optionally specify an array of property names to wrap; otherwise we
      // wrap all properties. If any of the properties are already observables, we replace them with
      // ES5 getter/setter pairs that wrap your original observable instances. In the case of readonly
      // ko.computed properties, we simply do not define a setter (so attempted writes will be ignored,
      // which is how ES5 readonly properties normally behave).
      //
      // By design, this does *not* recursively walk child object properties, because making literally
      // everything everywhere independently observable is usually unhelpful. When you do want to track
      // child object properties independently, define your own class for those child objects and put
      // a separate ko.track call into its constructor --- this gives you far more control.
      function track(obj, propertyNames) {
          if (!obj /*|| typeof obj !== 'object'*/) {
              throw new Error('When calling ko.track, you must pass an object as the first parameter.');
          }

          var ko = this,
              allObservablesForObject = getAllObservablesForObject(obj, true);
          propertyNames = propertyNames || Object.getOwnPropertyNames(obj);

          propertyNames.forEach(function(propertyName) {
              // Skip storage properties
              if (propertyName === OBSERVABLES_PROPERTY || propertyName === SUBSCRIBABLE_PROPERTY) {
                  return;
              }
              // Skip properties that are already tracked
              if (propertyName in allObservablesForObject) {
                  return;
              }

              var origValue = obj[propertyName],
                  isArray = origValue instanceof Array,
                  observable = ko.isObservable(origValue) ? origValue
                                                : isArray ? ko.observableArray(origValue)
                                                          : ko.observable(origValue);

              Object.defineProperty(obj, propertyName, {
                  configurable: true,
                  enumerable: true,
                  get: observable,
                  set: ko.isWriteableObservable(observable) ? observable : undefined
              });

              allObservablesForObject[propertyName] = observable;

              if (isArray) {
                  notifyWhenPresentOrFutureArrayValuesMutate(ko, observable);
              }
          });

          return obj;
      }

      // Gets or creates the hidden internal key-value collection of observables corresponding to
      // properties on the model object.
      function getAllObservablesForObject(obj, createIfNotDefined) {
          var result = obj[OBSERVABLES_PROPERTY];
          if (!result && createIfNotDefined) {
              result = {};
              Object.defineProperty(obj, OBSERVABLES_PROPERTY, {
                  value : result
              });
          }
          return result;
      }

      // Computed properties
      // -------------------
      //
      // The preceding code is already sufficient to upgrade ko.computed model properties to ES5
      // getter/setter pairs (or in the case of readonly ko.computed properties, just a getter).
      // These then behave like a regular property with a getter function, except they are smarter:
      // your evaluator is only invoked when one of its dependencies changes. The result is cached
      // and used for all evaluations until the next time a dependency changes).
      //
      // However, instead of forcing developers to declare a ko.computed property explicitly, it's
      // nice to offer a utility function that declares a computed getter directly.

      // Implements `ko.defineProperty`
      function defineComputedProperty(obj, propertyName, evaluatorOrOptions) {
          var ko = this,
              computedOptions = { owner: obj, deferEvaluation: true };

          if (typeof evaluatorOrOptions === 'function') {
              computedOptions.read = evaluatorOrOptions;
          } else {
              if ('value' in evaluatorOrOptions) {
                  throw new Error('For ko.defineProperty, you must not specify a "value" for the property. You must provide a "get" function.');
              }

              if (typeof evaluatorOrOptions.get !== 'function') {
                  throw new Error('For ko.defineProperty, the third parameter must be either an evaluator function, or an options object containing a function called "get".');
              }

              computedOptions.read = evaluatorOrOptions.get;
              computedOptions.write = evaluatorOrOptions.set;
          }

          obj[propertyName] = ko.computed(computedOptions);
          track.call(ko, obj, [propertyName]);
          return obj;
      }

      // Array handling
      // --------------
      //
      // Arrays are special, because unlike other property types, they have standard mutator functions
      // (`push`/`pop`/`splice`/etc.) and it's desirable to trigger a change notification whenever one of
      // those mutator functions is invoked.
      //
      // Traditionally, Knockout handles this by putting special versions of `push`/`pop`/etc. on observable
      // arrays that mutate the underlying array and then trigger a notification. That approach doesn't
      // work for Knockout-ES5 because properties now return the underlying arrays, so the mutator runs
      // in the context of the underlying array, not any particular observable:
      //
      //     // Operates on the underlying array value
      //     myModel.someCollection.push('New value');
      //
      // To solve this, Knockout-ES5 detects array values, and modifies them as follows:
      //  1. Associates a hidden subscribable with each array instance that it encounters
      //  2. Intercepts standard mutators (`push`/`pop`/etc.) and makes them trigger the subscribable
      // Then, for model properties whose values are arrays, the property's underlying observable
      // subscribes to the array subscribable, so it can trigger a change notification after mutation.

      // Given an observable that underlies a model property, watch for any array value that might
      // be assigned as the property value, and hook into its change events
      function notifyWhenPresentOrFutureArrayValuesMutate(ko, observable) {
          var watchingArraySubscription = null;
          ko.computed(function () {
              // Unsubscribe to any earlier array instance
              if (watchingArraySubscription) {
                  watchingArraySubscription.dispose();
                  watchingArraySubscription = null;
              }

              // Subscribe to the new array instance
              var newArrayInstance = observable();
              if (newArrayInstance instanceof Array) {
                  watchingArraySubscription = startWatchingArrayInstance(ko, observable, newArrayInstance);
              }
          });
      }

      // Listens for array mutations, and when they happen, cause the observable to fire notifications.
      // This is used to make model properties of type array fire notifications when the array changes.
      // Returns a subscribable that can later be disposed.
      function startWatchingArrayInstance(ko, observable, arrayInstance) {
          var subscribable = getSubscribableForArray(ko, arrayInstance);
          return subscribable.subscribe(observable);
      }

      // Gets or creates a subscribable that fires after each array mutation
      function getSubscribableForArray(ko, arrayInstance) {
          var subscribable = arrayInstance[SUBSCRIBABLE_PROPERTY];
          if (!subscribable) {
              subscribable = new ko.subscribable();
              Object.defineProperty(arrayInstance, SUBSCRIBABLE_PROPERTY, {
                  value : subscribable
              });

              var notificationPauseSignal = {};
              wrapStandardArrayMutators(arrayInstance, subscribable, notificationPauseSignal);
              addKnockoutArrayMutators(ko, arrayInstance, subscribable, notificationPauseSignal);
          }

          return subscribable;
      }

      // After each array mutation, fires a notification on the given subscribable
      function wrapStandardArrayMutators(arrayInstance, subscribable, notificationPauseSignal) {
          ['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'].forEach(function(fnName) {
              var origMutator = arrayInstance[fnName];
              arrayInstance[fnName] = function() {
                  var result = origMutator.apply(this, arguments);
                  if (notificationPauseSignal.pause !== true) {
                      subscribable.notifySubscribers(this);
                  }
                  return result;
              };
          });
      }

      // Adds Knockout's additional array mutation functions to the array
      function addKnockoutArrayMutators(ko, arrayInstance, subscribable, notificationPauseSignal) {
          ['remove', 'removeAll', 'destroy', 'destroyAll', 'replace'].forEach(function(fnName) {
              // Make it a non-enumerable property for consistency with standard Array functions
              Object.defineProperty(arrayInstance, fnName, {
                  enumerable: false,
                  value: function() {
                      var result;

                      // These additional array mutators are built using the underlying push/pop/etc.
                      // mutators, which are wrapped to trigger notifications. But we don't want to
                      // trigger multiple notifications, so pause the push/pop/etc. wrappers and
                      // delivery only one notification at the end of the process.
                      notificationPauseSignal.pause = true;
                      try {
                          // Creates a temporary observableArray that can perform the operation.
                          result = ko.observableArray.fn[fnName].apply(ko.observableArray(arrayInstance), arguments);
                      }
                      finally {
                          notificationPauseSignal.pause = false;
                      }
                      subscribable.notifySubscribers(arrayInstance);
                      return result;
                  }
              });
          });
      }

      // Static utility functions
      // ------------------------
      //
      // Since Knockout-ES5 sets up properties that return values, not observables, you can't
      // trivially subscribe to the underlying observables (e.g., `someProperty.subscribe(...)`),
      // or tell them that object values have mutated, etc. To handle this, we set up some
      // extra utility functions that can return or work with the underlying observables.

      // Returns the underlying observable associated with a model property (or `null` if the
      // model or property doesn't exist, or isn't associated with an observable). This means
      // you can subscribe to the property, e.g.:
      //
      //     ko.getObservable(model, 'propertyName')
      //       .subscribe(function(newValue) { ... });
      function getObservable(obj, propertyName) {
          if (!obj /*|| typeof obj !== 'object'*/) {
              return null;
          }

          var allObservablesForObject = getAllObservablesForObject(obj, false);
          return (allObservablesForObject && allObservablesForObject[propertyName]) || null;
      }

      // Causes a property's associated observable to fire a change notification. Useful when
      // the property value is a complex object and you've modified a child property.
      function valueHasMutated(obj, propertyName) {
          var observable = getObservable(obj, propertyName);

          if (observable) {
              observable.valueHasMutated();
          }
      }

      // Extends a Knockout instance with Knockout-ES5 functionality
      function attachToKo(ko) {
          ko.track = track;
          ko.getObservable = getObservable;
          ko.valueHasMutated = valueHasMutated;
          ko.defineProperty = defineComputedProperty;
      }

      var knockout_es5 = {
          attachToKo : attachToKo
      };

  const svgNS$1 = "http://www.w3.org/2000/svg";
  const svgClassName = "cesium-svgPath-svg";

  /**
   * A Knockout binding handler that creates a DOM element for a single SVG path.
   * This binding handler will be registered as cesiumSvgPath.
   *
   * <p>
   * The parameter to this binding is an object with the following properties:
   * </p>
   *
   * <ul>
   * <li>path: The SVG path as a string.</li>
   * <li>width: The width of the SVG path with no transformations applied.</li>
   * <li>height: The height of the SVG path with no transformations applied.</li>
   * <li>css: Optional. A string containing additional CSS classes to apply to the SVG. 'cesium-svgPath-svg' is always applied.</li>
   * </ul>
   *
   * @namespace SvgPathBindingHandler
   *
   * @example
   * // Create an SVG as a child of a div
   * <div data-bind="cesiumSvgPath: { path: 'M 100 100 L 300 100 L 200 300 z', width: 28, height: 28 }"></div>
   *
   * // parameters can be observable from the view model
   * <div data-bind="cesiumSvgPath: { path: currentPath, width: currentWidth, height: currentHeight }"></div>
   *
   * // or the whole object can be observable from the view model
   * <div data-bind="cesiumSvgPath: svgPathOptions"></div>
   */
  const SvgPathBindingHandler = {
    /**
     * @function
     */
    register: function (knockout) {
      knockout.bindingHandlers.cesiumSvgPath = {
        init: function (element, valueAccessor) {
          const svg = document.createElementNS(svgNS$1, "svg:svg");
          svg.setAttribute("class", svgClassName);

          const pathElement = document.createElementNS(svgNS$1, "path");
          svg.appendChild(pathElement);

          knockout.virtualElements.setDomNodeChildren(element, [svg]);

          knockout.computed({
            read: function () {
              const value = knockout.unwrap(valueAccessor());

              pathElement.setAttribute("d", knockout.unwrap(value.path));

              const pathWidth = knockout.unwrap(value.width);
              const pathHeight = knockout.unwrap(value.height);

              svg.setAttribute("width", pathWidth);
              svg.setAttribute("height", pathHeight);
              svg.setAttribute("viewBox", `0 0 ${pathWidth} ${pathHeight}`);

              if (value.css) {
                svg.setAttribute(
                  "class",
                  `${svgClassName} ${knockout.unwrap(value.css)}`
                );
              }
            },
            disposeWhenNodeIsRemoved: element,
          });

          return {
            controlsDescendantBindings: true,
          };
        },
      };

      knockout.virtualElements.allowedBindings.cesiumSvgPath = true;
    },
  };

  // install the Knockout-ES5 plugin
  knockout_es5.attachToKo(knockout);

  // Register all Cesium binding handlers
  SvgPathBindingHandler.register(knockout);

  /* This file is automatically rebuilt by the Cesium build process. */
  const e=[171,75,84,88,32,50,48,187,13,10,26,10];var n,i,s,a,r,o,l,f;!function(t){t[t.NONE=0]="NONE",t[t.BASISLZ=1]="BASISLZ",t[t.ZSTD=2]="ZSTD",t[t.ZLIB=3]="ZLIB";}(n||(n={})),function(t){t[t.BASICFORMAT=0]="BASICFORMAT";}(i||(i={})),function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.ETC1S=163]="ETC1S",t[t.UASTC=166]="UASTC";}(s||(s={})),function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.SRGB=1]="SRGB";}(a||(a={})),function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.LINEAR=1]="LINEAR",t[t.SRGB=2]="SRGB",t[t.ITU=3]="ITU",t[t.NTSC=4]="NTSC",t[t.SLOG=5]="SLOG",t[t.SLOG2=6]="SLOG2";}(r||(r={})),function(t){t[t.ALPHA_STRAIGHT=0]="ALPHA_STRAIGHT",t[t.ALPHA_PREMULTIPLIED=1]="ALPHA_PREMULTIPLIED";}(o||(o={})),function(t){t[t.RGB=0]="RGB",t[t.RRR=3]="RRR",t[t.GGG=4]="GGG",t[t.AAA=15]="AAA";}(l||(l={})),function(t){t[t.RGB=0]="RGB",t[t.RGBA=3]="RGBA",t[t.RRR=4]="RRR",t[t.RRRG=5]="RRRG";}(f||(f={}));class U{constructor(){this.vkFormat=0,this.typeSize=1,this.pixelWidth=0,this.pixelHeight=0,this.pixelDepth=0,this.layerCount=0,this.faceCount=1,this.supercompressionScheme=n.NONE,this.levels=[],this.dataFormatDescriptor=[{vendorId:0,descriptorType:i.BASICFORMAT,versionNumber:2,descriptorBlockSize:40,colorModel:s.UNSPECIFIED,colorPrimaries:a.SRGB,transferFunction:a.SRGB,flags:o.ALPHA_STRAIGHT,texelBlockDimension:{x:4,y:4,z:1,w:1},bytesPlane:[],samples:[]}],this.keyValue={},this.globalData=null;}}class c{constructor(t,e,n,i){this._dataView=new DataView(t.buffer,t.byteOffset+e,n),this._littleEndian=i,this._offset=0;}_nextUint8(){const t=this._dataView.getUint8(this._offset);return this._offset+=1,t}_nextUint16(){const t=this._dataView.getUint16(this._offset,this._littleEndian);return this._offset+=2,t}_nextUint32(){const t=this._dataView.getUint32(this._offset,this._littleEndian);return this._offset+=4,t}_nextUint64(){const t=this._dataView.getUint32(this._offset,this._littleEndian)+2**32*this._dataView.getUint32(this._offset+4,this._littleEndian);return this._offset+=8,t}_skip(t){return this._offset+=t,this}_scan(t,e=0){const n=this._offset;let i=0;for(;this._dataView.getUint8(this._offset)!==e&&i<t;)i++,this._offset++;return i<t&&this._offset++,new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+n,i)}}function _(t){return "undefined"!=typeof TextDecoder?(new TextDecoder).decode(t):Buffer.from(t).toString("utf8")}function p(t){const n=new Uint8Array(t.buffer,t.byteOffset,e.length);if(n[0]!==e[0]||n[1]!==e[1]||n[2]!==e[2]||n[3]!==e[3]||n[4]!==e[4]||n[5]!==e[5]||n[6]!==e[6]||n[7]!==e[7]||n[8]!==e[8]||n[9]!==e[9]||n[10]!==e[10]||n[11]!==e[11])throw new Error("Missing KTX 2.0 identifier.");const i=new U,s=17*Uint32Array.BYTES_PER_ELEMENT,a=new c(t,e.length,s,!0);i.vkFormat=a._nextUint32(),i.typeSize=a._nextUint32(),i.pixelWidth=a._nextUint32(),i.pixelHeight=a._nextUint32(),i.pixelDepth=a._nextUint32(),i.layerCount=a._nextUint32(),i.faceCount=a._nextUint32();const r=a._nextUint32();i.supercompressionScheme=a._nextUint32();const o=a._nextUint32(),l=a._nextUint32(),f=a._nextUint32(),h=a._nextUint32(),g=a._nextUint64(),p=a._nextUint64(),x=new c(t,e.length+s,3*r*8,!0);for(let e=0;e<r;e++)i.levels.push({levelData:new Uint8Array(t.buffer,t.byteOffset+x._nextUint64(),x._nextUint64()),uncompressedByteLength:x._nextUint64()});const u=new c(t,o,l,!0),y={vendorId:u._skip(4)._nextUint16(),descriptorType:u._nextUint16(),versionNumber:u._nextUint16(),descriptorBlockSize:u._nextUint16(),colorModel:u._nextUint8(),colorPrimaries:u._nextUint8(),transferFunction:u._nextUint8(),flags:u._nextUint8(),texelBlockDimension:{x:u._nextUint8()+1,y:u._nextUint8()+1,z:u._nextUint8()+1,w:u._nextUint8()+1},bytesPlane:[u._nextUint8(),u._nextUint8(),u._nextUint8(),u._nextUint8(),u._nextUint8(),u._nextUint8(),u._nextUint8(),u._nextUint8()],samples:[]},D=(y.descriptorBlockSize/4-6)/4;for(let t=0;t<D;t++)y.samples[t]={bitOffset:u._nextUint16(),bitLength:u._nextUint8(),channelID:u._nextUint8(),samplePosition:[u._nextUint8(),u._nextUint8(),u._nextUint8(),u._nextUint8()],sampleLower:u._nextUint32(),sampleUpper:u._nextUint32()};i.dataFormatDescriptor.length=0,i.dataFormatDescriptor.push(y);const b=new c(t,f,h,!0);for(;b._offset<h;){const t=b._nextUint32(),e=b._scan(t),n=_(e),s=b._scan(t-e.byteLength);i.keyValue[n]=n.match(/^ktx/i)?_(s):s,b._offset%4&&b._skip(4-b._offset%4);}if(p<=0)return i;const d=new c(t,g,p,!0),B=d._nextUint16(),w=d._nextUint16(),A=d._nextUint32(),S=d._nextUint32(),m=d._nextUint32(),L=d._nextUint32(),I=[];for(let t=0;t<r;t++)I.push({imageFlags:d._nextUint32(),rgbSliceByteOffset:d._nextUint32(),rgbSliceByteLength:d._nextUint32(),alphaSliceByteOffset:d._nextUint32(),alphaSliceByteLength:d._nextUint32()});const R=g+d._offset,E=R+A,T=E+S,O=T+m,P=new Uint8Array(t.buffer,t.byteOffset+R,A),C=new Uint8Array(t.buffer,t.byteOffset+E,S),F=new Uint8Array(t.buffer,t.byteOffset+T,m),G=new Uint8Array(t.buffer,t.byteOffset+O,L);return i.globalData={endpointCount:B,selectorCount:w,imageDescs:I,endpointsData:P,selectorsData:C,tablesData:F,extendedData:G},i}

  /* This file is automatically rebuilt by the Cesium build process. */

  var LercDecode = createCommonjsModule(function (module) {
  /* jshint forin: false, bitwise: false */
  /*
  Copyright 2015-2018 Esri

  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.

  A copy of the license and additional notices are located with the
  source distribution at:

  http://github.com/Esri/lerc/

  Contributors:  Johannes Schmid, (LERC v1)
                 Chayanika Khatua, (LERC v1)
                 Wenxue Ju (LERC v1, v2.x)
  */

  /* Copyright 2015-2018 Esri. 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 @preserve */

  /**
   * a module for decoding LERC blobs
   * @module Lerc
   */
  (function() {
    //the original LercDecode for Version 1
    var LercDecode = (function() {

      // WARNING: This decoder version can only read old version 1 Lerc blobs. Use with caution.

      // Note: currently, this module only has an implementation for decoding LERC data, not encoding. The name of
      // the class was chosen to be future proof.

      var CntZImage = {};

      CntZImage.defaultNoDataValue = -3.4027999387901484e+38; // smallest Float32 value

      /**
       * Decode a LERC byte stream and return an object containing the pixel data and some required and optional
       * information about it, such as the image's width and height.
       *
       * @param {ArrayBuffer} input The LERC input byte stream
       * @param {object} [options] Decoding options, containing any of the following properties:
       * @config {number} [inputOffset = 0]
       *        Skip the first inputOffset bytes of the input byte stream. A valid LERC file is expected at that position.
       * @config {Uint8Array} [encodedMask = null]
       *        If specified, the decoder will not read mask information from the input and use the specified encoded
       *        mask data instead. Mask header/data must not be present in the LERC byte stream in this case.
       * @config {number} [noDataValue = LercCode.defaultNoDataValue]
       *        Pixel value to use for masked pixels.
       * @config {ArrayBufferView|Array} [pixelType = Float32Array]
       *        The desired type of the pixelData array in the return value. Note that it is the caller's responsibility to
       *        provide an appropriate noDataValue if the default pixelType is overridden.
       * @config {boolean} [returnMask = false]
       *        If true, the return value will contain a maskData property of type Uint8Array which has one element per
       *        pixel, the value of which is 1 or 0 depending on whether that pixel's data is present or masked. If the
       *        input LERC data does not contain a mask, maskData will not be returned.
       * @config {boolean} [returnEncodedMask = false]
       *        If true, the return value will contain a encodedMaskData property, which can be passed into encode() as
       *        encodedMask.
       * @config {boolean} [returnFileInfo = false]
       *        If true, the return value will have a fileInfo property that contains metadata obtained from the
       *        LERC headers and the decoding process.
       * @config {boolean} [computeUsedBitDepths = false]
       *        If true, the fileInfo property in the return value will contain the set of all block bit depths
       *        encountered during decoding. Will only have an effect if returnFileInfo option is true.
       * @returns {{width, height, pixelData, minValue, maxValue, noDataValue, maskData, encodedMaskData, fileInfo}}
       */
      CntZImage.decode = function(input, options) {
        options = options || {};

        var skipMask = options.encodedMaskData || (options.encodedMaskData === null);
        var parsedData = parse(input, options.inputOffset || 0, skipMask);

        var noDataValue = (options.noDataValue !== null) ? options.noDataValue : CntZImage.defaultNoDataValue;

        var uncompressedData = uncompressPixelValues(parsedData, options.pixelType || Float32Array,
          options.encodedMaskData, noDataValue, options.returnMask);

        var result = {
          width: parsedData.width,
          height: parsedData.height,
          pixelData: uncompressedData.resultPixels,
          minValue: uncompressedData.minValue,
          maxValue: parsedData.pixels.maxValue,
          noDataValue: noDataValue
        };

        if (uncompressedData.resultMask) {
          result.maskData = uncompressedData.resultMask;
        }

        if (options.returnEncodedMask && parsedData.mask) {
          result.encodedMaskData = parsedData.mask.bitset ? parsedData.mask.bitset : null;
        }

        if (options.returnFileInfo) {
          result.fileInfo = formatFileInfo(parsedData);
          if (options.computeUsedBitDepths) {
            result.fileInfo.bitDepths = computeUsedBitDepths(parsedData);
          }
        }

        return result;
      };

      var uncompressPixelValues = function(data, TypedArrayClass, maskBitset, noDataValue, storeDecodedMask) {
        var blockIdx = 0;
        var numX = data.pixels.numBlocksX;
        var numY = data.pixels.numBlocksY;
        var blockWidth = Math.floor(data.width / numX);
        var blockHeight = Math.floor(data.height / numY);
        var scale = 2 * data.maxZError;
        var minValue = Number.MAX_VALUE, currentValue;
        maskBitset = maskBitset || ((data.mask) ? data.mask.bitset : null);

        var resultPixels, resultMask;
        resultPixels = new TypedArrayClass(data.width * data.height);
        if (storeDecodedMask && maskBitset) {
          resultMask = new Uint8Array(data.width * data.height);
        }
        var blockDataBuffer = new Float32Array(blockWidth * blockHeight);

        var xx, yy;
        for (var y = 0; y <= numY; y++) {
          var thisBlockHeight = (y !== numY) ? blockHeight : (data.height % numY);
          if (thisBlockHeight === 0) {
            continue;
          }
          for (var x = 0; x <= numX; x++) {
            var thisBlockWidth = (x !== numX) ? blockWidth : (data.width % numX);
            if (thisBlockWidth === 0) {
              continue;
            }

            var outPtr = y * data.width * blockHeight + x * blockWidth;
            var outStride = data.width - thisBlockWidth;

            var block = data.pixels.blocks[blockIdx];

            var blockData, blockPtr, constValue;
            if (block.encoding < 2) {
              // block is either uncompressed or bit-stuffed (encodings 0 and 1)
              if (block.encoding === 0) {
                // block is uncompressed
                blockData = block.rawData;
              } else {
                // block is bit-stuffed
                unstuff(block.stuffedData, block.bitsPerPixel, block.numValidPixels, block.offset, scale, blockDataBuffer, data.pixels.maxValue);
                blockData = blockDataBuffer;
              }
              blockPtr = 0;
            }
            else if (block.encoding === 2) {
              // block is all 0
              constValue = 0;
            }
            else {
              // block has constant value (encoding === 3)
              constValue = block.offset;
            }

            var maskByte;
            if (maskBitset) {
              for (yy = 0; yy < thisBlockHeight; yy++) {
                if (outPtr & 7) {
                  //
                  maskByte = maskBitset[outPtr >> 3];
                  maskByte <<= outPtr & 7;
                }
                for (xx = 0; xx < thisBlockWidth; xx++) {
                  if (!(outPtr & 7)) {
                    // read next byte from mask
                    maskByte = maskBitset[outPtr >> 3];
                  }
                  if (maskByte & 128) {
                    // pixel data present
                    if (resultMask) {
                      resultMask[outPtr] = 1;
                    }
                    currentValue = (block.encoding < 2) ? blockData[blockPtr++] : constValue;
                    minValue = minValue > currentValue ? currentValue : minValue;
                    resultPixels[outPtr++] = currentValue;
                  } else {
                    // pixel data not present
                    if (resultMask) {
                      resultMask[outPtr] = 0;
                    }
                    resultPixels[outPtr++] = noDataValue;
                  }
                  maskByte <<= 1;
                }
                outPtr += outStride;
              }
            } else {
              // mask not present, simply copy block over
              if (block.encoding < 2) {
                // duplicating this code block for performance reasons
                // blockData case:
                for (yy = 0; yy < thisBlockHeight; yy++) {
                  for (xx = 0; xx < thisBlockWidth; xx++) {
                    currentValue = blockData[blockPtr++];
                    minValue = minValue > currentValue ? currentValue : minValue;
                    resultPixels[outPtr++] = currentValue;
                  }
                  outPtr += outStride;
                }
              }
              else {
                // constValue case:
                minValue = minValue > constValue ? constValue : minValue;
                for (yy = 0; yy < thisBlockHeight; yy++) {
                  for (xx = 0; xx < thisBlockWidth; xx++) {
                    resultPixels[outPtr++] = constValue;
                  }
                  outPtr += outStride;
                }
              }
            }
            if ((block.encoding === 1) && (blockPtr !== block.numValidPixels)) {
              throw "Block and Mask do not match";
            }
            blockIdx++;
          }
        }

        return {
          resultPixels: resultPixels,
          resultMask: resultMask,
          minValue: minValue
        };
      };

      var formatFileInfo = function(data) {
        return {
          "fileIdentifierString": data.fileIdentifierString,
          "fileVersion": data.fileVersion,
          "imageType": data.imageType,
          "height": data.height,
          "width": data.width,
          "maxZError": data.maxZError,
          "eofOffset": data.eofOffset,
          "mask": data.mask ? {
            "numBlocksX": data.mask.numBlocksX,
            "numBlocksY": data.mask.numBlocksY,
            "numBytes": data.mask.numBytes,
            "maxValue": data.mask.maxValue
          } : null,
          "pixels": {
            "numBlocksX": data.pixels.numBlocksX,
            "numBlocksY": data.pixels.numBlocksY,
            "numBytes": data.pixels.numBytes,
            "maxValue": data.pixels.maxValue,
            "noDataValue": data.noDataValue
          }
        };
      };

      var computeUsedBitDepths = function(data) {
        var numBlocks = data.pixels.numBlocksX * data.pixels.numBlocksY;
        var bitDepths = {};
        for (var i = 0; i < numBlocks; i++) {
          var block = data.pixels.blocks[i];
          if (block.encoding === 0) {
            bitDepths.float32 = true;
          } else if (block.encoding === 1) {
            bitDepths[block.bitsPerPixel] = true;
          } else {
            bitDepths[0] = true;
          }
        }

        return Object.keys(bitDepths);
      };

      var parse = function(input, fp, skipMask) {
        var data = {};

        // File header
        var fileIdView = new Uint8Array(input, fp, 10);
        data.fileIdentifierString = String.fromCharCode.apply(null, fileIdView);
        if (data.fileIdentifierString.trim() !== "CntZImage") {
          throw "Unexpected file identifier string: " + data.fileIdentifierString;
        }
        fp += 10;
        var view = new DataView(input, fp, 24);
        data.fileVersion = view.getInt32(0, true);
        data.imageType = view.getInt32(4, true);
        data.height = view.getUint32(8, true);
        data.width = view.getUint32(12, true);
        data.maxZError = view.getFloat64(16, true);
        fp += 24;

        // Mask Header
        if (!skipMask) {
          view = new DataView(input, fp, 16);
          data.mask = {};
          data.mask.numBlocksY = view.getUint32(0, true);
          data.mask.numBlocksX = view.getUint32(4, true);
          data.mask.numBytes = view.getUint32(8, true);
          data.mask.maxValue = view.getFloat32(12, true);
          fp += 16;

          // Mask Data
          if (data.mask.numBytes > 0) {
            var bitset = new Uint8Array(Math.ceil(data.width * data.height / 8));
            view = new DataView(input, fp, data.mask.numBytes);
            var cnt = view.getInt16(0, true);
            var ip = 2, op = 0;
            do {
              if (cnt > 0) {
                while (cnt--) { bitset[op++] = view.getUint8(ip++); }
              } else {
                var val = view.getUint8(ip++);
                cnt = -cnt;
                while (cnt--) { bitset[op++] = val; }
              }
              cnt = view.getInt16(ip, true);
              ip += 2;
            } while (ip < data.mask.numBytes);
            if ((cnt !== -32768) || (op < bitset.length)) {
              throw "Unexpected end of mask RLE encoding";
            }
            data.mask.bitset = bitset;
            fp += data.mask.numBytes;
          }
          else if ((data.mask.numBytes | data.mask.numBlocksY | data.mask.maxValue) === 0) {  // Special case, all nodata
            data.mask.bitset = new Uint8Array(Math.ceil(data.width * data.height / 8));
          }
        }

        // Pixel Header
        view = new DataView(input, fp, 16);
        data.pixels = {};
        data.pixels.numBlocksY = view.getUint32(0, true);
        data.pixels.numBlocksX = view.getUint32(4, true);
        data.pixels.numBytes = view.getUint32(8, true);
        data.pixels.maxValue = view.getFloat32(12, true);
        fp += 16;

        var numBlocksX = data.pixels.numBlocksX;
        var numBlocksY = data.pixels.numBlocksY;
        // the number of blocks specified in the header does not take into account the blocks at the end of
        // each row/column with a special width/height that make the image complete in case the width is not
        // evenly divisible by the number of blocks.
        var actualNumBlocksX = numBlocksX + ((data.width % numBlocksX) > 0 ? 1 : 0);
        var actualNumBlocksY = numBlocksY + ((data.height % numBlocksY) > 0 ? 1 : 0);
        data.pixels.blocks = new Array(actualNumBlocksX * actualNumBlocksY);
        var blockI = 0;
        for (var blockY = 0; blockY < actualNumBlocksY; blockY++) {
          for (var blockX = 0; blockX < actualNumBlocksX; blockX++) {

            // Block
            var size = 0;
            var bytesLeft = input.byteLength - fp;
            view = new DataView(input, fp, Math.min(10, bytesLeft));
            var block = {};
            data.pixels.blocks[blockI++] = block;
            var headerByte = view.getUint8(0); size++;
            block.encoding = headerByte & 63;
            if (block.encoding > 3) {
              throw "Invalid block encoding (" + block.encoding + ")";
            }
            if (block.encoding === 2) {
              fp++;
              continue;
            }
            if ((headerByte !== 0) && (headerByte !== 2)) {
              headerByte >>= 6;
              block.offsetType = headerByte;
              if (headerByte === 2) {
                block.offset = view.getInt8(1); size++;
              } else if (headerByte === 1) {
                block.offset = view.getInt16(1, true); size += 2;
              } else if (headerByte === 0) {
                block.offset = view.getFloat32(1, true); size += 4;
              } else {
                throw "Invalid block offset type";
              }

              if (block.encoding === 1) {
                headerByte = view.getUint8(size); size++;
                block.bitsPerPixel = headerByte & 63;
                headerByte >>= 6;
                block.numValidPixelsType = headerByte;
                if (headerByte === 2) {
                  block.numValidPixels = view.getUint8(size); size++;
                } else if (headerByte === 1) {
                  block.numValidPixels = view.getUint16(size, true); size += 2;
                } else if (headerByte === 0) {
                  block.numValidPixels = view.getUint32(size, true); size += 4;
                } else {
                  throw "Invalid valid pixel count type";
                }
              }
            }
            fp += size;

            if (block.encoding === 3) {
              continue;
            }

            var arrayBuf, store8;
            if (block.encoding === 0) {
              var numPixels = (data.pixels.numBytes - 1) / 4;
              if (numPixels !== Math.floor(numPixels)) {
                throw "uncompressed block has invalid length";
              }
              arrayBuf = new ArrayBuffer(numPixels * 4);
              store8 = new Uint8Array(arrayBuf);
              store8.set(new Uint8Array(input, fp, numPixels * 4));
              var rawData = new Float32Array(arrayBuf);
              block.rawData = rawData;
              fp += numPixels * 4;
            } else if (block.encoding === 1) {
              var dataBytes = Math.ceil(block.numValidPixels * block.bitsPerPixel / 8);
              var dataWords = Math.ceil(dataBytes / 4);
              arrayBuf = new ArrayBuffer(dataWords * 4);
              store8 = new Uint8Array(arrayBuf);
              store8.set(new Uint8Array(input, fp, dataBytes));
              block.stuffedData = new Uint32Array(arrayBuf);
              fp += dataBytes;
            }
          }
        }
        data.eofOffset = fp;
        return data;
      };

      var unstuff = function(src, bitsPerPixel, numPixels, offset, scale, dest, maxValue) {
        var bitMask = (1 << bitsPerPixel) - 1;
        var i = 0, o;
        var bitsLeft = 0;
        var n, buffer;
        var nmax = Math.ceil((maxValue - offset) / scale);
        // get rid of trailing bytes that are already part of next block
        var numInvalidTailBytes = src.length * 4 - Math.ceil(bitsPerPixel * numPixels / 8);
        src[src.length - 1] <<= 8 * numInvalidTailBytes;

        for (o = 0; o < numPixels; o++) {
          if (bitsLeft === 0) {
            buffer = src[i++];
            bitsLeft = 32;
          }
          if (bitsLeft >= bitsPerPixel) {
            n = (buffer >>> (bitsLeft - bitsPerPixel)) & bitMask;
            bitsLeft -= bitsPerPixel;
          } else {
            var missingBits = (bitsPerPixel - bitsLeft);
            n = ((buffer & bitMask) << missingBits) & bitMask;
            buffer = src[i++];
            bitsLeft = 32 - missingBits;
            n += (buffer >>> bitsLeft);
          }
          //pixel values may exceed max due to quantization
          dest[o] = n < nmax ? offset + n * scale : maxValue;
        }
        return dest;
      };

      return CntZImage;
    })();

    //version 2. Supports 2.1, 2.2, 2.3
    var Lerc2Decode = (function() {
      // Note: currently, this module only has an implementation for decoding LERC data, not encoding. The name of
      // the class was chosen to be future proof, following LercDecode.

      /*****************************************
      * private static class bitsutffer used by Lerc2Decode
      *******************************************/
      var BitStuffer = {
        //methods ending with 2 are for the new byte order used by Lerc2.3 and above.
        //originalUnstuff is used to unpack Huffman code table. code is duplicated to unstuffx for performance reasons.
        unstuff: function(src, dest, bitsPerPixel, numPixels, lutArr, offset, scale, maxValue) {
          var bitMask = (1 << bitsPerPixel) - 1;
          var i = 0, o;
          var bitsLeft = 0;
          var n, buffer, missingBits, nmax;

          // get rid of trailing bytes that are already part of next block
          var numInvalidTailBytes = src.length * 4 - Math.ceil(bitsPerPixel * numPixels / 8);
          src[src.length - 1] <<= 8 * numInvalidTailBytes;
          if (lutArr) {
            for (o = 0; o < numPixels; o++) {
              if (bitsLeft === 0) {
                buffer = src[i++];
                bitsLeft = 32;
              }
              if (bitsLeft >= bitsPerPixel) {
                n = (buffer >>> (bitsLeft - bitsPerPixel)) & bitMask;
                bitsLeft -= bitsPerPixel;
              }
              else {
                missingBits = (bitsPerPixel - bitsLeft);
                n = ((buffer & bitMask) << missingBits) & bitMask;
                buffer = src[i++];
                bitsLeft = 32 - missingBits;
                n += (buffer >>> bitsLeft);
              }
              dest[o] = lutArr[n];//offset + lutArr[n] * scale;
            }
          }
          else {
            nmax = Math.ceil((maxValue - offset) / scale);
            for (o = 0; o < numPixels; o++) {
              if (bitsLeft === 0) {
                buffer = src[i++];
                bitsLeft = 32;
              }
              if (bitsLeft >= bitsPerPixel) {
                n = (buffer >>> (bitsLeft - bitsPerPixel)) & bitMask;
                bitsLeft -= bitsPerPixel;
              }
              else {
                missingBits = (bitsPerPixel - bitsLeft);
                n = ((buffer & bitMask) << missingBits) & bitMask;
                buffer = src[i++];
                bitsLeft = 32 - missingBits;
                n += (buffer >>> bitsLeft);
              }
              //pixel values may exceed max due to quantization
              dest[o] = n < nmax ? offset + n * scale : maxValue;
            }
          }
        },

        unstuffLUT: function(src, bitsPerPixel, numPixels, offset, scale, maxValue) {
          var bitMask = (1 << bitsPerPixel) - 1;
          var i = 0, o = 0, missingBits = 0, bitsLeft = 0, n = 0;
          var buffer;
          var dest = [];

          // get rid of trailing bytes that are already part of next block
          var numInvalidTailBytes = src.length * 4 - Math.ceil(bitsPerPixel * numPixels / 8);
          src[src.length - 1] <<= 8 * numInvalidTailBytes;

          var nmax = Math.ceil((maxValue - offset) / scale);
          for (o = 0; o < numPixels; o++) {
            if (bitsLeft === 0) {
              buffer = src[i++];
              bitsLeft = 32;
            }
            if (bitsLeft >= bitsPerPixel) {
              n = (buffer >>> (bitsLeft - bitsPerPixel)) & bitMask;
              bitsLeft -= bitsPerPixel;
            } else {
              missingBits = (bitsPerPixel - bitsLeft);
              n = ((buffer & bitMask) << missingBits) & bitMask;
              buffer = src[i++];
              bitsLeft = 32 - missingBits;
              n += (buffer >>> bitsLeft);
            }
            //dest.push(n);
            dest[o] = n < nmax ? offset + n * scale : maxValue;
          }
          dest.unshift(offset);//1st one
          return dest;
        },

        unstuff2: function(src, dest, bitsPerPixel, numPixels, lutArr, offset, scale, maxValue) {
          var bitMask = (1 << bitsPerPixel) - 1;
          var i = 0, o;
          var bitsLeft = 0, bitPos = 0;
          var n, buffer, missingBits;
          if (lutArr) {
            for (o = 0; o < numPixels; o++) {
              if (bitsLeft === 0) {
                buffer = src[i++];
                bitsLeft = 32;
                bitPos = 0;
              }
              if (bitsLeft >= bitsPerPixel) {
                n = ((buffer >>> bitPos) & bitMask);
                bitsLeft -= bitsPerPixel;
                bitPos += bitsPerPixel;
              } else {
                missingBits = (bitsPerPixel - bitsLeft);
                n = (buffer >>> bitPos) & bitMask;
                buffer = src[i++];
                bitsLeft = 32 - missingBits;
                n |= (buffer & ((1 << missingBits) - 1)) << (bitsPerPixel - missingBits);
                bitPos = missingBits;
              }
              dest[o] = lutArr[n];
            }
          }
          else {
            var nmax = Math.ceil((maxValue - offset) / scale);
            for (o = 0; o < numPixels; o++) {
              if (bitsLeft === 0) {
                buffer = src[i++];
                bitsLeft = 32;
                bitPos = 0;
              }
              if (bitsLeft >= bitsPerPixel) {
                //no unsigned left shift
                n = ((buffer >>> bitPos) & bitMask);
                bitsLeft -= bitsPerPixel;
                bitPos += bitsPerPixel;
              } else {
                missingBits = (bitsPerPixel - bitsLeft);
                n = (buffer >>> bitPos) & bitMask;//((buffer & bitMask) << missingBits) & bitMask;
                buffer = src[i++];
                bitsLeft = 32 - missingBits;
                n |= (buffer & ((1 << missingBits) - 1)) << (bitsPerPixel - missingBits);
                bitPos = missingBits;
              }
              //pixel values may exceed max due to quantization
              dest[o] = n < nmax ? offset + n * scale : maxValue;
            }
          }
          return dest;
        },

        unstuffLUT2: function(src, bitsPerPixel, numPixels, offset, scale, maxValue) {
          var bitMask = (1 << bitsPerPixel) - 1;
          var i = 0, o = 0, missingBits = 0, bitsLeft = 0, n = 0, bitPos = 0;
          var buffer;
          var dest = [];
          var nmax = Math.ceil((maxValue - offset) / scale);
          for (o = 0; o < numPixels; o++) {
            if (bitsLeft === 0) {
              buffer = src[i++];
              bitsLeft = 32;
              bitPos = 0;
            }
            if (bitsLeft >= bitsPerPixel) {
              //no unsigned left shift
              n = ((buffer >>> bitPos) & bitMask);
              bitsLeft -= bitsPerPixel;
              bitPos += bitsPerPixel;
            } else {
              missingBits = (bitsPerPixel - bitsLeft);
              n = (buffer >>> bitPos) & bitMask;//((buffer & bitMask) << missingBits) & bitMask;
              buffer = src[i++];
              bitsLeft = 32 - missingBits;
              n |= (buffer & ((1 << missingBits) - 1)) << (bitsPerPixel - missingBits);
              bitPos = missingBits;
            }
            //dest.push(n);
            dest[o] = n < nmax ? offset + n * scale : maxValue;
          }
          dest.unshift(offset);
          return dest;
        },

        originalUnstuff: function(src, dest, bitsPerPixel, numPixels) {
          var bitMask = (1 << bitsPerPixel) - 1;
          var i = 0, o;
          var bitsLeft = 0;
          var n, buffer, missingBits;

          // get rid of trailing bytes that are already part of next block
          var numInvalidTailBytes = src.length * 4 - Math.ceil(bitsPerPixel * numPixels / 8);
          src[src.length - 1] <<= 8 * numInvalidTailBytes;

          for (o = 0; o < numPixels; o++) {
            if (bitsLeft === 0) {
              buffer = src[i++];
              bitsLeft = 32;
            }
            if (bitsLeft >= bitsPerPixel) {
              n = (buffer >>> (bitsLeft - bitsPerPixel)) & bitMask;
              bitsLeft -= bitsPerPixel;
            }
            else {
              missingBits = (bitsPerPixel - bitsLeft);
              n = ((buffer & bitMask) << missingBits) & bitMask;
              buffer = src[i++];
              bitsLeft = 32 - missingBits;
              n += (buffer >>> bitsLeft);
            }
            dest[o] = n;
          }
          return dest;
        },

        originalUnstuff2: function(src, dest, bitsPerPixel, numPixels) {
          var bitMask = (1 << bitsPerPixel) - 1;
          var i = 0, o;
          var bitsLeft = 0, bitPos = 0;
          var n, buffer, missingBits;
          //micro-optimizations
          for (o = 0; o < numPixels; o++) {
            if (bitsLeft === 0) {
              buffer = src[i++];
              bitsLeft = 32;
              bitPos = 0;
            }
            if (bitsLeft >= bitsPerPixel) {
              //no unsigned left shift
              n = ((buffer >>> bitPos) & bitMask);
              bitsLeft -= bitsPerPixel;
              bitPos += bitsPerPixel;
            } else {
              missingBits = (bitsPerPixel - bitsLeft);
              n = (buffer >>> bitPos) & bitMask;//((buffer & bitMask) << missingBits) & bitMask;
              buffer = src[i++];
              bitsLeft = 32 - missingBits;
              n |= (buffer & ((1 << missingBits) - 1)) << (bitsPerPixel - missingBits);
              bitPos = missingBits;
            }
            dest[o] = n;
          }
          return dest;
        }
      };

      /*****************************************
      *private static class used by Lerc2Decode
      ******************************************/
      var Lerc2Helpers = {
        HUFFMAN_LUT_BITS_MAX: 12, //use 2^12 lut, treat it like constant
        computeChecksumFletcher32: function(input) {

          var sum1 = 0xffff, sum2 = 0xffff;
          var len = input.length;
          var words = Math.floor(len / 2);
          var i = 0;
          while (words) {
            var tlen = (words >= 359) ? 359 : words;
            words -= tlen;
            do {
              sum1 += (input[i++] << 8);
              sum2 += sum1 += input[i++];
            } while (--tlen);

            sum1 = (sum1 & 0xffff) + (sum1 >>> 16);
            sum2 = (sum2 & 0xffff) + (sum2 >>> 16);
          }

          // add the straggler byte if it exists
          if (len & 1) {
            sum2 += sum1 += (input[i] << 8);
          }
          // second reduction step to reduce sums to 16 bits
          sum1 = (sum1 & 0xffff) + (sum1 >>> 16);
          sum2 = (sum2 & 0xffff) + (sum2 >>> 16);

          return (sum2 << 16 | sum1) >>> 0;
        },

        readHeaderInfo: function(input, data) {
          var ptr = data.ptr;
          var fileIdView = new Uint8Array(input, ptr, 6);
          var headerInfo = {};
          headerInfo.fileIdentifierString = String.fromCharCode.apply(null, fileIdView);
          if (headerInfo.fileIdentifierString.lastIndexOf("Lerc2", 0) !== 0) {
            throw "Unexpected file identifier string (expect Lerc2 ): " + headerInfo.fileIdentifierString;
          }
          ptr += 6;
          var view = new DataView(input, ptr, 8);
          var fileVersion = view.getInt32(0, true);
          headerInfo.fileVersion = fileVersion;
          ptr += 4;
          if (fileVersion >= 3) {
            headerInfo.checksum = view.getUint32(4, true); //nrows
            ptr += 4;
          }

          //keys start from here
          view = new DataView(input, ptr, 12);
          headerInfo.height = view.getUint32(0, true); //nrows
          headerInfo.width = view.getUint32(4, true); //ncols
          ptr += 8;
          if (fileVersion >= 4) {
            headerInfo.numDims = view.getUint32(8, true);
            ptr += 4;
          }
          else {
            headerInfo.numDims = 1;
          }

          view = new DataView(input, ptr, 40);
          headerInfo.numValidPixel = view.getUint32(0, true);
          headerInfo.microBlockSize = view.getInt32(4, true);
          headerInfo.blobSize = view.getInt32(8, true);
          headerInfo.imageType = view.getInt32(12, true);

          headerInfo.maxZError = view.getFloat64(16, true);
          headerInfo.zMin = view.getFloat64(24, true);
          headerInfo.zMax = view.getFloat64(32, true);
          ptr += 40;
          data.headerInfo = headerInfo;
          data.ptr = ptr;

          var checksum, keyLength;
          if (fileVersion >= 3) {
            keyLength = fileVersion >= 4 ? 52 : 48;
            checksum = this.computeChecksumFletcher32(new Uint8Array(input, ptr - keyLength, headerInfo.blobSize - 14));
            if (checksum !== headerInfo.checksum) {
              throw "Checksum failed.";
            }
          }
          return true;
        },

        checkMinMaxRanges: function(input, data) {
          var headerInfo = data.headerInfo;
          var OutPixelTypeArray = this.getDataTypeArray(headerInfo.imageType);
          var rangeBytes = headerInfo.numDims * this.getDataTypeSize(headerInfo.imageType);
          var minValues = this.readSubArray(input, data.ptr, OutPixelTypeArray, rangeBytes);
          var maxValues = this.readSubArray(input, data.ptr + rangeBytes, OutPixelTypeArray, rangeBytes);
          data.ptr += (2 * rangeBytes);
          var i, equal = true;
          for (i = 0; i < headerInfo.numDims; i++) {
            if (minValues[i] !== maxValues[i]) {
              equal = false;
              break;
            }
          }
          headerInfo.minValues = minValues;
          headerInfo.maxValues = maxValues;
          return equal;
        },

        readSubArray: function(input, ptr, OutPixelTypeArray, numBytes) {
          var rawData;
          if (OutPixelTypeArray === Uint8Array) {
            rawData = new Uint8Array(input, ptr, numBytes);
          }
          else {
            var arrayBuf = new ArrayBuffer(numBytes);
            var store8 = new Uint8Array(arrayBuf);
            store8.set(new Uint8Array(input, ptr, numBytes));
            rawData = new OutPixelTypeArray(arrayBuf);
          }
          return rawData;
        },

        readMask: function(input, data) {
          var ptr = data.ptr;
          var headerInfo = data.headerInfo;
          var numPixels = headerInfo.width * headerInfo.height;
          var numValidPixel = headerInfo.numValidPixel;

          var view = new DataView(input, ptr, 4);
          var mask = {};
          mask.numBytes = view.getUint32(0, true);
          ptr += 4;

          // Mask Data
          if ((0 === numValidPixel || numPixels === numValidPixel) && 0 !== mask.numBytes) {
            throw ("invalid mask");
          }
          var bitset, resultMask;
          if (numValidPixel === 0) {
            bitset = new Uint8Array(Math.ceil(numPixels / 8));
            mask.bitset = bitset;
            resultMask = new Uint8Array(numPixels);
            data.pixels.resultMask = resultMask;
            ptr += mask.numBytes;
          }// ????? else if (data.mask.numBytes > 0 && data.mask.numBytes< data.numValidPixel) {
          else if (mask.numBytes > 0) {
            bitset = new Uint8Array(Math.ceil(numPixels / 8));
            view = new DataView(input, ptr, mask.numBytes);
            var cnt = view.getInt16(0, true);
            var ip = 2, op = 0, val = 0;
            do {
              if (cnt > 0) {
                while (cnt--) { bitset[op++] = view.getUint8(ip++); }
              } else {
                val = view.getUint8(ip++);
                cnt = -cnt;
                while (cnt--) { bitset[op++] = val; }
              }
              cnt = view.getInt16(ip, true);
              ip += 2;
            } while (ip < mask.numBytes);
            if ((cnt !== -32768) || (op < bitset.length)) {
              throw "Unexpected end of mask RLE encoding";
            }

            resultMask = new Uint8Array(numPixels);
            var mb = 0, k = 0;

            for (k = 0; k < numPixels; k++) {
              if (k & 7) {
                mb = bitset[k >> 3];
                mb <<= k & 7;
              }
              else {
                mb = bitset[k >> 3];
              }
              if (mb & 128) {
                resultMask[k] = 1;
              }
            }
            data.pixels.resultMask = resultMask;

            mask.bitset = bitset;
            ptr += mask.numBytes;
          }
          data.ptr = ptr;
          data.mask = mask;
          return true;
        },

        readDataOneSweep: function(input, data, OutPixelTypeArray) {
          var ptr = data.ptr;
          var headerInfo = data.headerInfo;
          var numDims = headerInfo.numDims;
          var numPixels = headerInfo.width * headerInfo.height;
          var imageType = headerInfo.imageType;
          var numBytes = headerInfo.numValidPixel * Lerc2Helpers.getDataTypeSize(imageType) * numDims;
          //data.pixels.numBytes = numBytes;
          var rawData;
          var mask = data.pixels.resultMask;
          if (OutPixelTypeArray === Uint8Array) {
            rawData = new Uint8Array(input, ptr, numBytes);
          }
          else {
            var arrayBuf = new ArrayBuffer(numBytes);
            var store8 = new Uint8Array(arrayBuf);
            store8.set(new Uint8Array(input, ptr, numBytes));
            rawData = new OutPixelTypeArray(arrayBuf);
          }
          if (rawData.length === numPixels * numDims) {
            data.pixels.resultPixels = rawData;
          }
          else  //mask
          {
            data.pixels.resultPixels = new OutPixelTypeArray(numPixels * numDims);
            var z = 0, k = 0, i = 0, nStart = 0;
            if (numDims > 1) {
              for (i=0; i < numDims; i++) {
                nStart = i * numPixels;
                for (k = 0; k < numPixels; k++) {
                  if (mask[k]) {
                    data.pixels.resultPixels[nStart + k] = rawData[z++];
                  }
                }
              }
            }
            else {
              for (k = 0; k < numPixels; k++) {
                if (mask[k]) {
                  data.pixels.resultPixels[k] = rawData[z++];
                }
              }
            }
          }
          ptr += numBytes;
          data.ptr = ptr;       //return data;
          return true;
        },

        readHuffmanTree: function(input, data) {
          var BITS_MAX = this.HUFFMAN_LUT_BITS_MAX; //8 is slow for the large test image
          //var size_max = 1 << BITS_MAX;
          /* ************************
           * reading code table
           *************************/
          var view = new DataView(input, data.ptr, 16);
          data.ptr += 16;
          var version = view.getInt32(0, true);
          if (version < 2) {
            throw "unsupported Huffman version";
          }
          var size = view.getInt32(4, true);
          var i0 = view.getInt32(8, true);
          var i1 = view.getInt32(12, true);
          if (i0 >= i1) {
            return false;
          }
          var blockDataBuffer = new Uint32Array(i1 - i0);
          Lerc2Helpers.decodeBits(input, data, blockDataBuffer);
          var codeTable = []; //size
          var i, j, k, len;

          for (i = i0; i < i1; i++) {
            j = i - (i < size ? 0 : size);//wrap around
            codeTable[j] = { first: blockDataBuffer[i - i0], second: null };
          }

          var dataBytes = input.byteLength - data.ptr;
          var dataWords = Math.ceil(dataBytes / 4);
          var arrayBuf = new ArrayBuffer(dataWords * 4);
          var store8 = new Uint8Array(arrayBuf);
          store8.set(new Uint8Array(input, data.ptr, dataBytes));
          var stuffedData = new Uint32Array(arrayBuf); //must start from x*4
          var bitPos = 0, word, srcPtr = 0;
          word = stuffedData[0];
          for (i = i0; i < i1; i++) {
            j = i - (i < size ? 0 : size);//wrap around
            len = codeTable[j].first;
            if (len > 0) {
              codeTable[j].second = (word << bitPos) >>> (32 - len);

              if (32 - bitPos >= len) {
                bitPos += len;
                if (bitPos === 32) {
                  bitPos = 0;
                  srcPtr++;
                  word = stuffedData[srcPtr];
                }
              }
              else {
                bitPos += len - 32;
                srcPtr++;
                word = stuffedData[srcPtr];
                codeTable[j].second |= word >>> (32 - bitPos);
              }
            }
          }

          //finished reading code table

          /* ************************
           * building lut
           *************************/
          var numBitsLUT = 0, numBitsLUTQick = 0;
          var tree = new TreeNode();
          for (i = 0; i < codeTable.length; i++) {
            if (codeTable[i] !== undefined) {
              numBitsLUT = Math.max(numBitsLUT, codeTable[i].first);
            }
          }
          if (numBitsLUT >= BITS_MAX) {
            numBitsLUTQick = BITS_MAX;
          }
          else {
            numBitsLUTQick = numBitsLUT;
          }
          if (numBitsLUT >= 30) {
            console.log("WARning, large NUM LUT BITS IS " + numBitsLUT);
          }
          var decodeLut = [], entry, code, numEntries, jj, currentBit, node;
          for (i = i0; i < i1; i++) {
            j = i - (i < size ? 0 : size);//wrap around
            len = codeTable[j].first;
            if (len > 0) {
              entry = [len, j];
              if (len <= numBitsLUTQick) {
                code = codeTable[j].second << (numBitsLUTQick - len);
                numEntries = 1 << (numBitsLUTQick - len);
                for (k = 0; k < numEntries; k++) {
                  decodeLut[code | k] = entry;
                }
              }
              else {
                //build tree
                code = codeTable[j].second;
                node = tree;
                for (jj = len - 1; jj >= 0; jj--) {
                  currentBit = code >>> jj & 1; //no left shift as length could be 30,31
                  if (currentBit) {
                    if (!node.right) {
                      node.right = new TreeNode();
                    }
                    node = node.right;
                  }
                  else {
                    if (!node.left) {
                      node.left = new TreeNode();
                    }
                    node = node.left;
                  }
                  if (jj === 0 && !node.val) {
                    node.val = entry[1];
                  }
                }
              }
            }
          }
          return {
            decodeLut: decodeLut,
            numBitsLUTQick: numBitsLUTQick,
            numBitsLUT: numBitsLUT,
            tree: tree,
            stuffedData: stuffedData,
            srcPtr: srcPtr,
            bitPos: bitPos
          };
        },

        readHuffman: function(input, data, OutPixelTypeArray) {
          var headerInfo = data.headerInfo;
          var numDims = headerInfo.numDims;
          var height = data.headerInfo.height;
          var width = data.headerInfo.width;
          var numPixels = width * height;
          //var size_max = 1 << BITS_MAX;
          /* ************************
           * reading huffman structure info
           *************************/
          var huffmanInfo = this.readHuffmanTree(input, data);
          var decodeLut = huffmanInfo.decodeLut;
          var tree = huffmanInfo.tree;
          //stuffedData includes huffman headers
          var stuffedData = huffmanInfo.stuffedData;
          var srcPtr = huffmanInfo.srcPtr;
          var bitPos = huffmanInfo.bitPos;
          var numBitsLUTQick = huffmanInfo.numBitsLUTQick;
          var numBitsLUT = huffmanInfo.numBitsLUT;
          var offset = data.headerInfo.imageType === 0 ? 128 : 0;
          /*************************
          *  decode
          ***************************/
          var node, val, delta, mask = data.pixels.resultMask, valTmp, valTmpQuick, currentBit;
          var i, j, k, ii;
          var prevVal = 0;
          if (bitPos > 0) {
            srcPtr++;
            bitPos = 0;
          }
          var word = stuffedData[srcPtr];
          var deltaEncode = data.encodeMode === 1;
          var resultPixelsAllDim = new OutPixelTypeArray(numPixels * numDims);
          var resultPixels = resultPixelsAllDim;
          var iDim;
          for (iDim = 0; iDim < headerInfo.numDims; iDim++) {
            if (numDims > 1) {
              //get the mem block of current dimension
              resultPixels = new OutPixelTypeArray(resultPixelsAllDim.buffer, numPixels * iDim, numPixels);
              prevVal = 0;
            }
            if (data.headerInfo.numValidPixel === width * height) { //all valid
              for (k = 0, i = 0; i < height; i++) {
                for (j = 0; j < width; j++, k++) {
                  val = 0;
                  valTmp = (word << bitPos) >>> (32 - numBitsLUTQick);
                  valTmpQuick = valTmp;// >>> deltaBits;
                  if (32 - bitPos < numBitsLUTQick) {
                    valTmp |= ((stuffedData[srcPtr + 1]) >>> (64 - bitPos - numBitsLUTQick));
                    valTmpQuick = valTmp;// >>> deltaBits;
                  }
                  if (decodeLut[valTmpQuick])    // if there, move the correct number of bits and done
                  {
                    val = decodeLut[valTmpQuick][1];
                    bitPos += decodeLut[valTmpQuick][0];
                  }
                  else {
                    valTmp = (word << bitPos) >>> (32 - numBitsLUT);
                    valTmpQuick = valTmp;// >>> deltaBits;
                    if (32 - bitPos < numBitsLUT) {
                      valTmp |= ((stuffedData[srcPtr + 1]) >>> (64 - bitPos - numBitsLUT));
                      valTmpQuick = valTmp;// >>> deltaBits;
                    }
                    node = tree;
                    for (ii = 0; ii < numBitsLUT; ii++) {
                      currentBit = valTmp >>> (numBitsLUT - ii - 1) & 1;
                      node = currentBit ? node.right : node.left;
                      if (!(node.left || node.right)) {
                        val = node.val;
                        bitPos = bitPos + ii + 1;
                        break;
                      }
                    }
                  }

                  if (bitPos >= 32) {
                    bitPos -= 32;
                    srcPtr++;
                    word = stuffedData[srcPtr];
                  }

                  delta = val - offset;
                  if (deltaEncode) {
                    if (j > 0) {
                      delta += prevVal;    // use overflow
                    }
                    else if (i > 0) {
                      delta += resultPixels[k - width];
                    }
                    else {
                      delta += prevVal;
                    }
                    delta &= 0xFF; //overflow
                    resultPixels[k] = delta;//overflow
                    prevVal = delta;
                  }
                  else {
                    resultPixels[k] = delta;
                  }
                }
              }
            }
            else { //not all valid, use mask
              for (k = 0, i = 0; i < height; i++) {
                for (j = 0; j < width; j++, k++) {
                  if (mask[k]) {
                    val = 0;
                    valTmp = (word << bitPos) >>> (32 - numBitsLUTQick);
                    valTmpQuick = valTmp;// >>> deltaBits;
                    if (32 - bitPos < numBitsLUTQick) {
                      valTmp |= ((stuffedData[srcPtr + 1]) >>> (64 - bitPos - numBitsLUTQick));
                      valTmpQuick = valTmp;// >>> deltaBits;
                    }
                    if (decodeLut[valTmpQuick])    // if there, move the correct number of bits and done
                    {
                      val = decodeLut[valTmpQuick][1];
                      bitPos += decodeLut[valTmpQuick][0];
                    }
                    else {
                      valTmp = (word << bitPos) >>> (32 - numBitsLUT);
                      valTmpQuick = valTmp;// >>> deltaBits;
                      if (32 - bitPos < numBitsLUT) {
                        valTmp |= ((stuffedData[srcPtr + 1]) >>> (64 - bitPos - numBitsLUT));
                        valTmpQuick = valTmp;// >>> deltaBits;
                      }
                      node = tree;
                      for (ii = 0; ii < numBitsLUT; ii++) {
                        currentBit = valTmp >>> (numBitsLUT - ii - 1) & 1;
                        node = currentBit ? node.right : node.left;
                        if (!(node.left || node.right)) {
                          val = node.val;
                          bitPos = bitPos + ii + 1;
                          break;
                        }
                      }
                    }

                    if (bitPos >= 32) {
                      bitPos -= 32;
                      srcPtr++;
                      word = stuffedData[srcPtr];
                    }

                    delta = val - offset;
                    if (deltaEncode) {
                      if (j > 0 && mask[k - 1]) {
                        delta += prevVal;    // use overflow
                      }
                      else if (i > 0 && mask[k - width]) {
                        delta += resultPixels[k - width];
                      }
                      else {
                        delta += prevVal;
                      }

                      delta &= 0xFF; //overflow
                      resultPixels[k] = delta;//overflow
                      prevVal = delta;
                    }
                    else {
                      resultPixels[k] = delta;
                    }
                  }
                }
              }
            }
            data.ptr = data.ptr + (srcPtr + 1) * 4 + (bitPos > 0 ? 4 : 0);
          }
          data.pixels.resultPixels = resultPixelsAllDim;
        },

        decodeBits: function(input, data, blockDataBuffer, offset, iDim) {
          {
            //bitstuff encoding is 3
            var headerInfo = data.headerInfo;
            var fileVersion = headerInfo.fileVersion;
            //var block = {};
            var blockPtr = 0;
            var view = new DataView(input, data.ptr, 5);//to do
            var headerByte = view.getUint8(0);
            blockPtr++;
            var bits67 = headerByte >> 6;
            var n = (bits67 === 0) ? 4 : 3 - bits67;
            var doLut = (headerByte & 32) > 0 ? true : false;//5th bit
            var numBits = headerByte & 31;
            var numElements = 0;
            if (n === 1) {
              numElements = view.getUint8(blockPtr); blockPtr++;
            } else if (n === 2) {
              numElements = view.getUint16(blockPtr, true); blockPtr += 2;
            } else if (n === 4) {
              numElements = view.getUint32(blockPtr, true); blockPtr += 4;
            } else {
              throw "Invalid valid pixel count type";
            }
            //fix: huffman codes are bit stuffed, but not bound by data's max value, so need to use originalUnstuff
            //offset = offset || 0;
            var scale = 2 * headerInfo.maxZError;
            var stuffedData, arrayBuf, store8, dataBytes, dataWords;
            var lutArr, lutData, lutBytes, bitsPerPixel;
            var zMax = headerInfo.numDims > 1 ? headerInfo.maxValues[iDim] : headerInfo.zMax;
            if (doLut) {
              data.counter.lut++;
              lutBytes = view.getUint8(blockPtr);
              blockPtr++;
              dataBytes = Math.ceil((lutBytes - 1) * numBits / 8);
              dataWords = Math.ceil(dataBytes / 4);
              arrayBuf = new ArrayBuffer(dataWords * 4);
              store8 = new Uint8Array(arrayBuf);

              data.ptr += blockPtr;
              store8.set(new Uint8Array(input, data.ptr, dataBytes));

              lutData = new Uint32Array(arrayBuf);
              data.ptr += dataBytes;

              bitsPerPixel = 0;
              while ((lutBytes - 1) >>> bitsPerPixel) {
                bitsPerPixel++;
              }
              dataBytes = Math.ceil(numElements * bitsPerPixel / 8);
              dataWords = Math.ceil(dataBytes / 4);
              arrayBuf = new ArrayBuffer(dataWords * 4);
              store8 = new Uint8Array(arrayBuf);
              store8.set(new Uint8Array(input, data.ptr, dataBytes));
              stuffedData = new Uint32Array(arrayBuf);
              data.ptr += dataBytes;
              if (fileVersion >= 3) {
                lutArr = BitStuffer.unstuffLUT2(lutData, numBits, lutBytes - 1, offset, scale, zMax);
              }
              else {
                lutArr = BitStuffer.unstuffLUT(lutData, numBits, lutBytes - 1, offset, scale, zMax);
              }
              //lutArr.unshift(0);
              if (fileVersion >= 3) {
                //BitStuffer.unstuff2(block, blockDataBuffer, headerInfo.zMax);
                BitStuffer.unstuff2(stuffedData, blockDataBuffer, bitsPerPixel, numElements, lutArr);
              }
              else {
                BitStuffer.unstuff(stuffedData, blockDataBuffer, bitsPerPixel, numElements, lutArr);
              }
            }
            else {
              //console.debug("bitstuffer");
              data.counter.bitstuffer++;
              bitsPerPixel = numBits;
              data.ptr += blockPtr;
              if (bitsPerPixel > 0) {
                dataBytes = Math.ceil(numElements * bitsPerPixel / 8);
                dataWords = Math.ceil(dataBytes / 4);
                arrayBuf = new ArrayBuffer(dataWords * 4);
                store8 = new Uint8Array(arrayBuf);
                store8.set(new Uint8Array(input, data.ptr, dataBytes));
                stuffedData = new Uint32Array(arrayBuf);
                data.ptr += dataBytes;
                if (fileVersion >= 3) {
                  if (offset == null) {
                    BitStuffer.originalUnstuff2(stuffedData, blockDataBuffer, bitsPerPixel, numElements);
                  }
                  else {
                    BitStuffer.unstuff2(stuffedData, blockDataBuffer, bitsPerPixel, numElements, false, offset, scale, zMax);
                  }
                }
                else {
                  if (offset == null) {
                    BitStuffer.originalUnstuff(stuffedData, blockDataBuffer, bitsPerPixel, numElements);
                  }
                  else {
                    BitStuffer.unstuff(stuffedData, blockDataBuffer, bitsPerPixel, numElements, false, offset, scale, zMax);
                  }
                }
              }
            }
          }

        },

        readTiles: function(input, data, OutPixelTypeArray) {
          var headerInfo = data.headerInfo;
          var width = headerInfo.width;
          var height = headerInfo.height;
          var microBlockSize = headerInfo.microBlockSize;
          var imageType = headerInfo.imageType;
          var dataTypeSize = Lerc2Helpers.getDataTypeSize(imageType);
          var numBlocksX = Math.ceil(width / microBlockSize);
          var numBlocksY = Math.ceil(height / microBlockSize);
          data.pixels.numBlocksY = numBlocksY;
          data.pixels.numBlocksX = numBlocksX;
          data.pixels.ptr = 0;
          var row = 0, col = 0, blockY = 0, blockX = 0, thisBlockHeight = 0, thisBlockWidth = 0, bytesLeft = 0, headerByte = 0, bits67 = 0, testCode = 0, outPtr = 0, outStride = 0, numBytes = 0, bytesleft = 0, z = 0, blockPtr = 0;
          var view, block, arrayBuf, store8, rawData;
          var blockEncoding;
          var blockDataBuffer = new OutPixelTypeArray(microBlockSize * microBlockSize);
          var lastBlockHeight = (height % microBlockSize) || microBlockSize;
          var lastBlockWidth = (width % microBlockSize) || microBlockSize;
          var offsetType, offset;
          var numDims = headerInfo.numDims, iDim;
          var mask = data.pixels.resultMask;
          var resultPixels = data.pixels.resultPixels;
          for (blockY = 0; blockY < numBlocksY; blockY++) {
            thisBlockHeight = (blockY !== numBlocksY - 1) ? microBlockSize : lastBlockHeight;
            for (blockX = 0; blockX < numBlocksX; blockX++) {
              //console.debug("y" + blockY + " x" + blockX);
              thisBlockWidth = (blockX !== numBlocksX - 1) ? microBlockSize : lastBlockWidth;

              outPtr = blockY * width * microBlockSize + blockX * microBlockSize;
              outStride = width - thisBlockWidth;


              for (iDim = 0; iDim < numDims; iDim++) {
                if (numDims > 1) {
                  resultPixels = new OutPixelTypeArray(data.pixels.resultPixels.buffer, width * height * iDim * dataTypeSize, width * height);
                }
                bytesLeft = input.byteLength - data.ptr;
                view = new DataView(input, data.ptr, Math.min(10, bytesLeft));
                block = {};
                blockPtr = 0;
                headerByte = view.getUint8(0);
                blockPtr++;
                bits67 = (headerByte >> 6) & 0xFF;
                testCode = (headerByte >> 2) & 15;    // use bits 2345 for integrity check
                if (testCode !== (((blockX * microBlockSize) >> 3) & 15)) {
                  throw "integrity issue";
                  //return false;
                }

                blockEncoding = headerByte & 3;
                if (blockEncoding > 3) {
                  data.ptr += blockPtr;
                  throw "Invalid block encoding (" + blockEncoding + ")";
                }
                else if (blockEncoding === 2) { //constant 0
                  data.counter.constant++;
                  data.ptr += blockPtr;
                  continue;
                }
                else if (blockEncoding === 0) {  //uncompressed
                  data.counter.uncompressed++;
                  data.ptr += blockPtr;
                  numBytes = thisBlockHeight * thisBlockWidth * dataTypeSize;
                  bytesleft = input.byteLength - data.ptr;
                  numBytes = numBytes < bytesleft ? numBytes : bytesleft;
                  //bit alignment
                  arrayBuf = new ArrayBuffer((numBytes % dataTypeSize) === 0 ? numBytes : (numBytes + dataTypeSize - numBytes % dataTypeSize));
                  store8 = new Uint8Array(arrayBuf);
                  store8.set(new Uint8Array(input, data.ptr, numBytes));
                  rawData = new OutPixelTypeArray(arrayBuf);
                  z = 0;
                  if (mask) {
                    for (row = 0; row < thisBlockHeight; row++) {
                      for (col = 0; col < thisBlockWidth; col++) {
                        if (mask[outPtr]) {
                          resultPixels[outPtr] = rawData[z++];
                        }
                        outPtr++;
                      }
                      outPtr += outStride;
                    }
                  }
                  else {//all valid
                    for (row = 0; row < thisBlockHeight; row++) {
                      for (col = 0; col < thisBlockWidth; col++) {
                        resultPixels[outPtr++] = rawData[z++];
                      }
                      outPtr += outStride;
                    }
                  }
                  data.ptr += z * dataTypeSize;
                }
                else { //1 or 3
                  offsetType = Lerc2Helpers.getDataTypeUsed(imageType, bits67);
                  offset = Lerc2Helpers.getOnePixel(block, blockPtr, offsetType, view);
                  blockPtr += Lerc2Helpers.getDataTypeSize(offsetType);
                  if (blockEncoding === 3) //constant offset value
                  {
                    data.ptr += blockPtr;
                    data.counter.constantoffset++;
                    //you can delete the following resultMask case in favor of performance because val is constant and users use nodata mask, otherwise nodatavalue post processing handles it too.
                    //while the above statement is true, we're not doing it as we want to keep invalid pixel value at 0 rather than arbitrary values
                    if (mask) {
                      for (row = 0; row < thisBlockHeight; row++) {
                        for (col = 0; col < thisBlockWidth; col++) {
                          if (mask[outPtr]) {
                            resultPixels[outPtr] = offset;
                          }
                          outPtr++;
                        }
                        outPtr += outStride;
                      }
                    }
                    else {
                      for (row = 0; row < thisBlockHeight; row++) {
                        for (col = 0; col < thisBlockWidth; col++) {
                          resultPixels[outPtr++] = offset;
                        }
                        outPtr += outStride;
                      }
                    }
                  }
                  else { //bitstuff encoding is 3
                    data.ptr += blockPtr;
                    //heavy lifting
                    Lerc2Helpers.decodeBits(input, data, blockDataBuffer, offset, iDim);
                    blockPtr = 0;
                    if (mask) {
                      for (row = 0; row < thisBlockHeight; row++) {
                        for (col = 0; col < thisBlockWidth; col++) {
                          if (mask[outPtr]) {
                            resultPixels[outPtr] = blockDataBuffer[blockPtr++];
                          }
                          outPtr++;
                        }
                        outPtr += outStride;
                      }
                    }
                    else {
                      for (row = 0; row < thisBlockHeight; row++) {
                        for (col = 0; col < thisBlockWidth; col++) {
                          resultPixels[outPtr++] = blockDataBuffer[blockPtr++];
                        }
                        outPtr += outStride;
                      }
                    }
                  }
                }
              }
            }
          }
        },

        /*****************
        *  private methods (helper methods)
        *****************/

        formatFileInfo: function(data) {
          return {
            "fileIdentifierString": data.headerInfo.fileIdentifierString,
            "fileVersion": data.headerInfo.fileVersion,
            "imageType": data.headerInfo.imageType,
            "height": data.headerInfo.height,
            "width": data.headerInfo.width,
            "numValidPixel": data.headerInfo.numValidPixel,
            "microBlockSize": data.headerInfo.microBlockSize,
            "blobSize": data.headerInfo.blobSize,
            "maxZError": data.headerInfo.maxZError,
            "pixelType": Lerc2Helpers.getPixelType(data.headerInfo.imageType),
            "eofOffset": data.eofOffset,
            "mask": data.mask ? {
              "numBytes": data.mask.numBytes
            } : null,
            "pixels": {
              "numBlocksX": data.pixels.numBlocksX,
              "numBlocksY": data.pixels.numBlocksY,
              //"numBytes": data.pixels.numBytes,
              "maxValue": data.headerInfo.zMax,
              "minValue": data.headerInfo.zMin,
              "noDataValue": data.noDataValue
            }
          };
        },

        constructConstantSurface: function(data) {
          var val = data.headerInfo.zMax;
          var numDims =  data.headerInfo.numDims;
          var numPixels = data.headerInfo.height * data.headerInfo.width;
          var numPixelAllDims = numPixels * numDims;
          var i=0, k = 0, nStart=0;
          var mask = data.pixels.resultMask;
          if (mask) {
            if (numDims > 1) {
              for (i=0; i < numDims; i++) {
                nStart = i * numPixels;
                for (k = 0; k < numPixels; k++) {
                  if (mask[k]) {
                    data.pixels.resultPixels[nStart + k] = val;
                  }
                }
              }
            }
            else {
              for (k = 0; k < numPixels; k++) {
                if (mask[k]) {
                  data.pixels.resultPixels[k] = val;
                }
              }
            }
          }
          else {
            if (data.pixels.resultPixels.fill) {
              data.pixels.resultPixels.fill(val);
            }
            else {
              for (k = 0; k < numPixelAllDims; k++) {
                data.pixels.resultPixels[k] = val;
              }
            }
          }
          return;
        },

        getDataTypeArray: function(t) {
          var tp;
          switch (t) {
            case 0: //char
              tp = Int8Array;
              break;
            case 1: //byte
              tp = Uint8Array;
              break;
            case 2: //short
              tp = Int16Array;
              break;
            case 3: //ushort
              tp = Uint16Array;
              break;
            case 4:
              tp = Int32Array;
              break;
            case 5:
              tp = Uint32Array;
              break;
            case 6:
              tp = Float32Array;
              break;
            case 7:
              tp = Float64Array;
              break;
            default:
              tp = Float32Array;
          }
          return tp;
        },

        getPixelType: function(t) {
          var tp;
          switch (t) {
            case 0: //char
              tp = "S8";
              break;
            case 1: //byte
              tp = "U8";
              break;
            case 2: //short
              tp = "S16";
              break;
            case 3: //ushort
              tp = "U16";
              break;
            case 4:
              tp = "S32";
              break;
            case 5:
              tp = "U32";
              break;
            case 6:
              tp = "F32";
              break;
            case 7:
              tp = "F64"; //not supported
              break;
            default:
              tp = "F32";
          }
          return tp;
        },

        isValidPixelValue: function(t, val) {
          if (val == null) {
            return false;
          }
          var isValid;
          switch (t) {
            case 0: //char
              isValid = val >= -128 && val <= 127;
              break;
            case 1: //byte  (unsigned char)
              isValid = val >= 0 && val <= 255;
              break;
            case 2: //short
              isValid = val >= -32768 && val <= 32767;
              break;
            case 3: //ushort
              isValid = val >= 0 && val <= 65536;
              break;
            case 4: //int 32
              isValid = val >= -2147483648 && val <= 2147483647;
              break;
            case 5: //uinit 32
              isValid = val >= 0 && val <= 4294967296;
              break;
            case 6:
              isValid = val >= -3.4027999387901484e+38 && val <= 3.4027999387901484e+38;
              break;
            case 7:
              isValid = val >= 5e-324 && val <= 1.7976931348623157e+308;
              break;
            default:
              isValid = false;
          }
          return isValid;
        },

        getDataTypeSize: function(t) {
          var s = 0;
          switch (t) {
            case 0: //ubyte
            case 1: //byte
              s = 1;
              break;
            case 2: //short
            case 3: //ushort
              s = 2;
              break;
            case 4:
            case 5:
            case 6:
              s = 4;
              break;
            case 7:
              s = 8;
              break;
            default:
              s = t;
          }
          return s;
        },

        getDataTypeUsed: function(dt, tc) {
          var t = dt;
          switch (dt) {
            case 2: //short
            case 4: //long
              t = dt - tc;
              break;
            case 3: //ushort
            case 5: //ulong
              t = dt - 2 * tc;
              break;
            case 6: //float
              if (0 === tc) {
                t = dt;
              }
              else if (1 === tc) {
                t = 2;
              }
              else {
                t = 1;//byte
              }
              break;
            case 7: //double
              if (0 === tc) {
                t = dt;
              }
              else {
                t = dt - 2 * tc + 1;
              }
              break;
            default:
              t = dt;
              break;
          }
          return t;
        },

        getOnePixel: function(block, blockPtr, offsetType, view) {
          var temp = 0;
          switch (offsetType) {
            case 0: //char
              temp = view.getInt8(blockPtr);
              break;
            case 1: //byte
              temp = view.getUint8(blockPtr);
              break;
            case 2:
              temp = view.getInt16(blockPtr, true);
              break;
            case 3:
              temp = view.getUint16(blockPtr, true);
              break;
            case 4:
              temp = view.getInt32(blockPtr, true);
              break;
            case 5:
              temp = view.getUInt32(blockPtr, true);
              break;
            case 6:
              temp = view.getFloat32(blockPtr, true);
              break;
            case 7:
              //temp = view.getFloat64(blockPtr, true);
              //blockPtr += 8;
              //lerc2 encoding doesnt handle float 64, force to float32???
              temp = view.getFloat64(blockPtr, true);
              break;
            default:
              throw ("the decoder does not understand this pixel type");
          }
          return temp;
        }
      };

      /***************************************************
      *private class for a tree node. Huffman code is in Lerc2Helpers
      ****************************************************/
      var TreeNode = function(val, left, right) {
        this.val = val;
        this.left = left;
        this.right = right;
      };

      var Lerc2Decode = {
        /*
        * ********removed options compared to LERC1. We can bring some of them back if needed.
         * removed pixel type. LERC2 is typed and doesn't require user to give pixel type
         * changed encodedMaskData to maskData. LERC2 's js version make it faster to use maskData directly.
         * removed returnMask. mask is used by LERC2 internally and is cost free. In case of user input mask, it's returned as well and has neglible cost.
         * removed nodatavalue. Because LERC2 pixels are typed, nodatavalue will sacrify a useful value for many types (8bit, 16bit) etc,
         *       user has to be knowledgable enough about raster and their data to avoid usability issues. so nodata value is simply removed now.
         *       We can add it back later if their's a clear requirement.
         * removed encodedMask. This option was not implemented in LercDecode. It can be done after decoding (less efficient)
         * removed computeUsedBitDepths.
         *
         *
         * response changes compared to LERC1
         * 1. encodedMaskData is not available
         * 2. noDataValue is optional (returns only if user's noDataValue is with in the valid data type range)
         * 3. maskData is always available
        */
        /*****************
        *  public properties
        ******************/
        //HUFFMAN_LUT_BITS_MAX: 12, //use 2^12 lut, not configurable

        /*****************
        *  public methods
        *****************/

        /**
         * Decode a LERC2 byte stream and return an object containing the pixel data and optional metadata.
         *
         * @param {ArrayBuffer} input The LERC input byte stream
         * @param {object} [options] options Decoding options
         * @param {number} [options.inputOffset] The number of bytes to skip in the input byte stream. A valid LERC file is expected at that position
         * @param {boolean} [options.returnFileInfo] If true, the return value will have a fileInfo property that contains metadata obtained from the LERC headers and the decoding process
         */
        decode: function(/*byte array*/ input, /*object*/ options) {
          //currently there's a bug in the sparse array, so please do not set to false
          options = options || {};
          var noDataValue = options.noDataValue;

          //initialize
          var i = 0, data = {};
          data.ptr = options.inputOffset || 0;
          data.pixels = {};

          // File header
          if (!Lerc2Helpers.readHeaderInfo(input, data)) ;
          var headerInfo = data.headerInfo;
          var fileVersion = headerInfo.fileVersion;
          var OutPixelTypeArray = Lerc2Helpers.getDataTypeArray(headerInfo.imageType);

          // Mask Header
          Lerc2Helpers.readMask(input, data);
          if (headerInfo.numValidPixel !== headerInfo.width * headerInfo.height && !data.pixels.resultMask) {
            data.pixels.resultMask = options.maskData;
          }

          var numPixels = headerInfo.width * headerInfo.height;
          data.pixels.resultPixels = new OutPixelTypeArray(numPixels * headerInfo.numDims);

          data.counter = {
            onesweep: 0,
            uncompressed: 0,
            lut: 0,
            bitstuffer: 0,
            constant: 0,
            constantoffset: 0
          };
          if (headerInfo.numValidPixel !== 0) {
            //not tested
            if (headerInfo.zMax === headerInfo.zMin) //constant surface
            {
              Lerc2Helpers.constructConstantSurface(data);
            }
            else if (fileVersion >= 4 && Lerc2Helpers.checkMinMaxRanges(input, data)) {
              Lerc2Helpers.constructConstantSurface(data);
            }
            else {
              var view = new DataView(input, data.ptr, 2);
              var bReadDataOneSweep = view.getUint8(0);
              data.ptr++;
              if (bReadDataOneSweep) {
                //console.debug("OneSweep");
                Lerc2Helpers.readDataOneSweep(input, data, OutPixelTypeArray);
              }
              else {
                //lerc2.1: //bitstuffing + lut
                //lerc2.2: //bitstuffing + lut + huffman
                //lerc2.3: new bitstuffer
                if (fileVersion > 1 && headerInfo.imageType <= 1 && Math.abs(headerInfo.maxZError - 0.5) < 0.00001) {
                  //this is 2.x plus 8 bit (unsigned and signed) data, possiblity of Huffman
                  var flagHuffman = view.getUint8(1);
                  data.ptr++;
                  data.encodeMode = flagHuffman;
                  if (flagHuffman > 2 || (fileVersion < 4 && flagHuffman > 1)) {
                    throw "Invalid Huffman flag " + flagHuffman;
                  }
                  if (flagHuffman) {//1 - delta Huffman, 2 - Huffman
                    //console.log("Huffman");
                    Lerc2Helpers.readHuffman(input, data, OutPixelTypeArray);
                  }
                  else {
                    //console.log("Tiles");
                    Lerc2Helpers.readTiles(input, data, OutPixelTypeArray);
                  }
                }
                else { //lerc2.x non-8 bit data
                  //console.log("Tiles");
                  Lerc2Helpers.readTiles(input, data, OutPixelTypeArray);
                }
              }
            }
          }

          data.eofOffset = data.ptr;
          var diff;
          if (options.inputOffset) {
            diff = data.headerInfo.blobSize + options.inputOffset - data.ptr;
            if (Math.abs(diff) >= 1) {
              //console.debug("incorrect eof: dataptr " + data.ptr + " offset " + options.inputOffset + " blobsize " + data.headerInfo.blobSize + " diff: " + diff);
              data.eofOffset = options.inputOffset + data.headerInfo.blobSize;
            }
          }
          else {
            diff = data.headerInfo.blobSize - data.ptr;
            if (Math.abs(diff) >= 1) {
              //console.debug("incorrect first band eof: dataptr " + data.ptr + " blobsize " + data.headerInfo.blobSize + " diff: " + diff);
              data.eofOffset = data.headerInfo.blobSize;
            }
          }

          var result = {
            width: headerInfo.width,
            height: headerInfo.height,
            pixelData: data.pixels.resultPixels,
            minValue: headerInfo.zMin,
            maxValue: headerInfo.zMax,
            validPixelCount: headerInfo.numValidPixel,
            dimCount: headerInfo.numDims,
            dimStats: {
              minValues: headerInfo.minValues,
              maxValues: headerInfo.maxValues
            },
            maskData: data.pixels.resultMask
            //noDataValue: noDataValue
          };

          //we should remove this if there's no existing client
          //optional noDataValue processing, it's user's responsiblity
          if (data.pixels.resultMask && Lerc2Helpers.isValidPixelValue(headerInfo.imageType, noDataValue)) {
            var mask = data.pixels.resultMask;
            for (i = 0; i < numPixels; i++) {
              if (!mask[i]) {
                result.pixelData[i] = noDataValue;
              }
            }
            result.noDataValue = noDataValue;
          }
          data.noDataValue = noDataValue;
          if (options.returnFileInfo) {
            result.fileInfo = Lerc2Helpers.formatFileInfo(data);
          }
          return result;
        },

        getBandCount: function(/*byte array*/ input) {
          var count = 0;
          var i = 0;
          var temp = {};
          temp.ptr = 0;
          temp.pixels = {};
          while (i < input.byteLength - 58) {
            Lerc2Helpers.readHeaderInfo(input, temp);
            i += temp.headerInfo.blobSize;
            count++;
            temp.ptr = i;
          }
          return count;
        }
      };

      return Lerc2Decode;
    })();

    var isPlatformLittleEndian = (function() {
      var a = new ArrayBuffer(4);
      var b = new Uint8Array(a);
      var c = new Uint32Array(a);
      c[0] = 1;
      return b[0] === 1;
    })();

    var Lerc = {
      /************wrapper**********************************************/
      /**
       * A wrapper for decoding both LERC1 and LERC2 byte streams capable of handling multiband pixel blocks for various pixel types.
       *
       * @alias module:Lerc
       * @param {ArrayBuffer} input The LERC input byte stream
       * @param {object} [options] The decoding options below are optional.
       * @param {number} [options.inputOffset] The number of bytes to skip in the input byte stream. A valid Lerc file is expected at that position.
       * @param {string} [options.pixelType] (LERC1 only) Default value is F32. Valid pixel types for input are U8/S8/S16/U16/S32/U32/F32.
       * @param {number} [options.noDataValue] (LERC1 only). It is recommended to use the returned mask instead of setting this value.
       * @returns {{width, height, pixels, pixelType, mask, statistics}}
         * @property {number} width Width of decoded image.
         * @property {number} height Height of decoded image.
         * @property {array} pixels [band1, band2, …] Each band is a typed array of width*height.
         * @property {string} pixelType The type of pixels represented in the output.
         * @property {mask} mask Typed array with a size of width*height, or null if all pixels are valid.
         * @property {array} statistics [statistics_band1, statistics_band2, …] Each element is a statistics object representing min and max values
      **/
      decode: function(encodedData, options) {
        if (!isPlatformLittleEndian) {
          throw "Big endian system is not supported.";
        }
        options = options || {};
        var inputOffset = options.inputOffset || 0;
        var fileIdView = new Uint8Array(encodedData, inputOffset, 10);
        var fileIdentifierString = String.fromCharCode.apply(null, fileIdView);
        var lerc, majorVersion;
        if (fileIdentifierString.trim() === "CntZImage") {
          lerc = LercDecode;
          majorVersion = 1;
        }
        else if (fileIdentifierString.substring(0, 5) === "Lerc2") {
          lerc = Lerc2Decode;
          majorVersion = 2;
        }
        else {
          throw "Unexpected file identifier string: " + fileIdentifierString;
        }

        var iPlane = 0, eof = encodedData.byteLength - 10, encodedMaskData, bandMasks = [], bandMask, maskData;
        var decodedPixelBlock = {
          width: 0,
          height: 0,
          pixels: [],
          pixelType: options.pixelType,
          mask: null,
          statistics: []
        };

        while (inputOffset < eof) {
          var result = lerc.decode(encodedData, {
            inputOffset: inputOffset,//for both lerc1 and lerc2
            encodedMaskData: encodedMaskData,//lerc1 only
            maskData: maskData,//lerc2 only
            returnMask: iPlane === 0 ? true : false,//lerc1 only
            returnEncodedMask: iPlane === 0 ? true : false,//lerc1 only
            returnFileInfo: true,//for both lerc1 and lerc2
            pixelType: options.pixelType || null,//lerc1 only
            noDataValue: options.noDataValue || null//lerc1 only
          });

          inputOffset = result.fileInfo.eofOffset;
          if (iPlane === 0) {
            encodedMaskData = result.encodedMaskData;//lerc1
            maskData = result.maskData;//lerc2
            decodedPixelBlock.width = result.width;
            decodedPixelBlock.height = result.height;
            decodedPixelBlock.dimCount = result.dimCount || 1;
            //decodedPixelBlock.dimStats = decodedPixelBlock.dimStats;
            decodedPixelBlock.pixelType = result.pixelType || result.fileInfo.pixelType;
            decodedPixelBlock.mask = result.maskData;
          }
          if (majorVersion >1 && result.fileInfo.mask && result.fileInfo.mask.numBytes > 0) {
            bandMasks.push(result.maskData);
          }

          iPlane++;
          decodedPixelBlock.pixels.push(result.pixelData);
          decodedPixelBlock.statistics.push({
            minValue: result.minValue,
            maxValue: result.maxValue,
            noDataValue: result.noDataValue,
            dimStats: result.dimStats
          });
        }
        var i, j, numPixels;
        if (majorVersion > 1 && bandMasks.length > 1) {
          numPixels = decodedPixelBlock.width * decodedPixelBlock.height;
          decodedPixelBlock.bandMasks = bandMasks;
          maskData = new Uint8Array(numPixels);
          maskData.set(bandMasks[0]);
          for (i = 1; i < bandMasks.length; i++) {
            bandMask = bandMasks[i];
            for (j = 0; j < numPixels; j++) {
              maskData[j] = maskData[j] & bandMask[j];
            }
          }
          decodedPixelBlock.maskData = maskData;
        }

        return decodedPixelBlock;
      }
    };

    if (module.exports) {/* jshint ignore:line */
      //commonJS module 1.0/1.1/1.1.1 systems, such as nodeJS
      //http://wiki.commonjs.org/wiki/Modules
      module.exports = Lerc;/* jshint ignore:line */
    }
    else {
      //assign to this, most likely window
      this.Lerc = Lerc;
    }

  })();
  });

  /* This file is automatically rebuilt by the Cesium build process. */
  var media = {
    webm: 'data:video/webm;base64,GkXfo0AgQoaBAUL3gQFC8oEEQvOBCEKCQAR3ZWJtQoeBAkKFgQIYU4BnQI0VSalmQCgq17FAAw9CQE2AQAZ3aGFtbXlXQUAGd2hhbW15RIlACECPQAAAAAAAFlSua0AxrkAu14EBY8WBAZyBACK1nEADdW5khkAFVl9WUDglhohAA1ZQOIOBAeBABrCBCLqBCB9DtnVAIueBAKNAHIEAAIAwAQCdASoIAAgAAUAmJaQAA3AA/vz0AAA=',
    mp4: 'data:video/mp4;base64, '
  };

  const { webm, mp4 } = media;

  // Detect iOS browsers < version 10
  const oldIOS = typeof navigator !== 'undefined' && parseFloat(
    ('' + (/CPU.*OS ([0-9_]{3,4})[0-9_]{0,1}|(CPU like).*AppleWebKit.*Mobile/i.exec(navigator.userAgent) || [0, ''])[1])
      .replace('undefined', '3_2').replace('_', '.').replace('_', '')
  ) < 10 && !window.MSStream;

  class NoSleep {
    constructor () {
      if (oldIOS) {
        this.noSleepTimer = null;
      } else {
        // Set up no sleep video element
        this.noSleepVideo = document.createElement('video');

        this.noSleepVideo.setAttribute('muted', '');
        this.noSleepVideo.setAttribute('title', 'No Sleep');
        this.noSleepVideo.setAttribute('playsinline', '');

        this._addSourceToVideo(this.noSleepVideo, 'webm', webm);
        this._addSourceToVideo(this.noSleepVideo, 'mp4', mp4);

        this.noSleepVideo.addEventListener('loadedmetadata', () => {
          if (this.noSleepVideo.duration <= 1) { // webm source
            this.noSleepVideo.setAttribute('loop', '');
          } else { // mp4 source
            this.noSleepVideo.addEventListener('timeupdate', () => {
              if (this.noSleepVideo.currentTime > 0.5) {
                this.noSleepVideo.currentTime = Math.random();
              }
            });
          }
        });
      }
    }

    _addSourceToVideo (element, type, dataURI) {
      var source = document.createElement('source');
      source.src = dataURI;
      source.type = `video/${type}`;
      element.appendChild(source);
    }

    enable () {
      if (oldIOS) {
        this.disable();
        console.warn(`
        NoSleep enabled for older iOS devices. This can interrupt
        active or long-running network requests from completing successfully.
        See https://github.com/richtr/NoSleep.js/issues/15 for more details.
      `);
        this.noSleepTimer = window.setInterval(() => {
          if (!document.hidden) {
            window.location.href = window.location.href.split('#')[0];
            window.setTimeout(window.stop, 0);
          }
        }, 15000);
      } else {
        this.noSleepVideo.play();
      }
    }

    disable () {
      if (oldIOS) {
        if (this.noSleepTimer) {
          console.warn(`
          NoSleep now disabled for older iOS devices.
        `);
          window.clearInterval(this.noSleepTimer);
          this.noSleepTimer = null;
        }
      } else {
        this.noSleepVideo.pause();
      }
    }
  }
  var src = NoSleep;

  /* This file is automatically rebuilt by the Cesium build process. */

  var common = createCommonjsModule(function (module, exports) {


  var TYPED_OK =  (typeof Uint8Array !== 'undefined') &&
                  (typeof Uint16Array !== 'undefined') &&
                  (typeof Int32Array !== 'undefined');

  function _has(obj, key) {
    return Object.prototype.hasOwnProperty.call(obj, key);
  }

  exports.assign = function (obj /*from1, from2, from3, ...*/) {
    var sources = Array.prototype.slice.call(arguments, 1);
    while (sources.length) {
      var source = sources.shift();
      if (!source) { continue; }

      if (typeof source !== 'object') {
        throw new TypeError(source + 'must be non-object');
      }

      for (var p in source) {
        if (_has(source, p)) {
          obj[p] = source[p];
        }
      }
    }

    return obj;
  };


  // reduce buffer size, avoiding mem copy
  exports.shrinkBuf = function (buf, size) {
    if (buf.length === size) { return buf; }
    if (buf.subarray) { return buf.subarray(0, size); }
    buf.length = size;
    return buf;
  };


  var fnTyped = {
    arraySet: function (dest, src, src_offs, len, dest_offs) {
      if (src.subarray && dest.subarray) {
        dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
        return;
      }
      // Fallback to ordinary array
      for (var i = 0; i < len; i++) {
        dest[dest_offs + i] = src[src_offs + i];
      }
    },
    // Join array of chunks to single array.
    flattenChunks: function (chunks) {
      var i, l, len, pos, chunk, result;

      // calculate data length
      len = 0;
      for (i = 0, l = chunks.length; i < l; i++) {
        len += chunks[i].length;
      }

      // join chunks
      result = new Uint8Array(len);
      pos = 0;
      for (i = 0, l = chunks.length; i < l; i++) {
        chunk = chunks[i];
        result.set(chunk, pos);
        pos += chunk.length;
      }

      return result;
    }
  };

  var fnUntyped = {
    arraySet: function (dest, src, src_offs, len, dest_offs) {
      for (var i = 0; i < len; i++) {
        dest[dest_offs + i] = src[src_offs + i];
      }
    },
    // Join array of chunks to single array.
    flattenChunks: function (chunks) {
      return [].concat.apply([], chunks);
    }
  };


  // Enable/Disable typed arrays use, for testing
  //
  exports.setTyped = function (on) {
    if (on) {
      exports.Buf8  = Uint8Array;
      exports.Buf16 = Uint16Array;
      exports.Buf32 = Int32Array;
      exports.assign(exports, fnTyped);
    } else {
      exports.Buf8  = Array;
      exports.Buf16 = Array;
      exports.Buf32 = Array;
      exports.assign(exports, fnUntyped);
    }
  };

  exports.setTyped(TYPED_OK);
  });

  // Note: adler32 takes 12% for level 0 and 2% for level 6.
  // It isn't worth it to make additional optimizations as in original.
  // Small size is preferable.

  // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  //
  // This software is provided 'as-is', without any express or implied
  // warranty. In no event will the authors be held liable for any damages
  // arising from the use of this software.
  //
  // Permission is granted to anyone to use this software for any purpose,
  // including commercial applications, and to alter it and redistribute it
  // freely, subject to the following restrictions:
  //
  // 1. The origin of this software must not be misrepresented; you must not
  //   claim that you wrote the original software. If you use this software
  //   in a product, an acknowledgment in the product documentation would be
  //   appreciated but is not required.
  // 2. Altered source versions must be plainly marked as such, and must not be
  //   misrepresented as being the original software.
  // 3. This notice may not be removed or altered from any source distribution.

  function adler32(adler, buf, len, pos) {
    var s1 = (adler & 0xffff) |0,
        s2 = ((adler >>> 16) & 0xffff) |0,
        n = 0;

    while (len !== 0) {
      // Set limit ~ twice less than 5552, to keep
      // s2 in 31-bits, because we force signed ints.
      // in other case %= will fail.
      n = len > 2000 ? 2000 : len;
      len -= n;

      do {
        s1 = (s1 + buf[pos++]) |0;
        s2 = (s2 + s1) |0;
      } while (--n);

      s1 %= 65521;
      s2 %= 65521;
    }

    return (s1 | (s2 << 16)) |0;
  }


  var adler32_1 = adler32;

  // Note: we can't get significant speed boost here.
  // So write code to minimize size - no pregenerated tables
  // and array tools dependencies.

  // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  //
  // This software is provided 'as-is', without any express or implied
  // warranty. In no event will the authors be held liable for any damages
  // arising from the use of this software.
  //
  // Permission is granted to anyone to use this software for any purpose,
  // including commercial applications, and to alter it and redistribute it
  // freely, subject to the following restrictions:
  //
  // 1. The origin of this software must not be misrepresented; you must not
  //   claim that you wrote the original software. If you use this software
  //   in a product, an acknowledgment in the product documentation would be
  //   appreciated but is not required.
  // 2. Altered source versions must be plainly marked as such, and must not be
  //   misrepresented as being the original software.
  // 3. This notice may not be removed or altered from any source distribution.

  // Use ordinary array, since untyped makes no boost here
  function makeTable() {
    var c, table = [];

    for (var n = 0; n < 256; n++) {
      c = n;
      for (var k = 0; k < 8; k++) {
        c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
      }
      table[n] = c;
    }

    return table;
  }

  // Create table on load. Just 255 signed longs. Not a problem.
  var crcTable = makeTable();


  function crc32(crc, buf, len, pos) {
    var t = crcTable,
        end = pos + len;

    crc ^= -1;

    for (var i = pos; i < end; i++) {
      crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
    }

    return (crc ^ (-1)); // >>> 0;
  }


  var crc32_1 = crc32;

  // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  //
  // This software is provided 'as-is', without any express or implied
  // warranty. In no event will the authors be held liable for any damages
  // arising from the use of this software.
  //
  // Permission is granted to anyone to use this software for any purpose,
  // including commercial applications, and to alter it and redistribute it
  // freely, subject to the following restrictions:
  //
  // 1. The origin of this software must not be misrepresented; you must not
  //   claim that you wrote the original software. If you use this software
  //   in a product, an acknowledgment in the product documentation would be
  //   appreciated but is not required.
  // 2. Altered source versions must be plainly marked as such, and must not be
  //   misrepresented as being the original software.
  // 3. This notice may not be removed or altered from any source distribution.

  // See state defs from inflate.js
  var BAD$1 = 30;       /* got a data error -- remain here until reset */
  var TYPE$1 = 12;      /* i: waiting for type bits, including last-flag bit */

  /*
     Decode literal, length, and distance codes and write out the resulting
     literal and match bytes until either not enough input or output is
     available, an end-of-block is encountered, or a data error is encountered.
     When large enough input and output buffers are supplied to inflate(), for
     example, a 16K input buffer and a 64K output buffer, more than 95% of the
     inflate execution time is spent in this routine.

     Entry assumptions:

          state.mode === LEN
          strm.avail_in >= 6
          strm.avail_out >= 258
          start >= strm.avail_out
          state.bits < 8

     On return, state.mode is one of:

          LEN -- ran out of enough output space or enough available input
          TYPE -- reached end of block code, inflate() to interpret next block
          BAD -- error in block data

     Notes:

      - The maximum input bits used by a length/distance pair is 15 bits for the
        length code, 5 bits for the length extra, 15 bits for the distance code,
        and 13 bits for the distance extra.  This totals 48 bits, or six bytes.
        Therefore if strm.avail_in >= 6, then there is enough input to avoid
        checking for available input while decoding.

      - The maximum bytes that a single length/distance pair can output is 258
        bytes, which is the maximum length that can be coded.  inflate_fast()
        requires strm.avail_out >= 258 for each loop to avoid checking for
        output space.
   */
  var inffast = function inflate_fast(strm, start) {
    var state;
    var _in;                    /* local strm.input */
    var last;                   /* have enough input while in < last */
    var _out;                   /* local strm.output */
    var beg;                    /* inflate()'s initial strm.output */
    var end;                    /* while out < end, enough space available */
  //#ifdef INFLATE_STRICT
    var dmax;                   /* maximum distance from zlib header */
  //#endif
    var wsize;                  /* window size or zero if not using window */
    var whave;                  /* valid bytes in the window */
    var wnext;                  /* window write index */
    // Use `s_window` instead `window`, avoid conflict with instrumentation tools
    var s_window;               /* allocated sliding window, if wsize != 0 */
    var hold;                   /* local strm.hold */
    var bits;                   /* local strm.bits */
    var lcode;                  /* local strm.lencode */
    var dcode;                  /* local strm.distcode */
    var lmask;                  /* mask for first level of length codes */
    var dmask;                  /* mask for first level of distance codes */
    var here;                   /* retrieved table entry */
    var op;                     /* code bits, operation, extra bits, or */
                                /*  window position, window bytes to copy */
    var len;                    /* match length, unused bytes */
    var dist;                   /* match distance */
    var from;                   /* where to copy match from */
    var from_source;


    var input, output; // JS specific, because we have no pointers

    /* copy state to local variables */
    state = strm.state;
    //here = state.here;
    _in = strm.next_in;
    input = strm.input;
    last = _in + (strm.avail_in - 5);
    _out = strm.next_out;
    output = strm.output;
    beg = _out - (start - strm.avail_out);
    end = _out + (strm.avail_out - 257);
  //#ifdef INFLATE_STRICT
    dmax = state.dmax;
  //#endif
    wsize = state.wsize;
    whave = state.whave;
    wnext = state.wnext;
    s_window = state.window;
    hold = state.hold;
    bits = state.bits;
    lcode = state.lencode;
    dcode = state.distcode;
    lmask = (1 << state.lenbits) - 1;
    dmask = (1 << state.distbits) - 1;


    /* decode literals and length/distances until end-of-block or not enough
       input data or output space */

    top:
    do {
      if (bits < 15) {
        hold += input[_in++] << bits;
        bits += 8;
        hold += input[_in++] << bits;
        bits += 8;
      }

      here = lcode[hold & lmask];

      dolen:
      for (;;) { // Goto emulation
        op = here >>> 24/*here.bits*/;
        hold >>>= op;
        bits -= op;
        op = (here >>> 16) & 0xff/*here.op*/;
        if (op === 0) {                          /* literal */
          //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
          //        "inflate:         literal '%c'\n" :
          //        "inflate:         literal 0x%02x\n", here.val));
          output[_out++] = here & 0xffff/*here.val*/;
        }
        else if (op & 16) {                     /* length base */
          len = here & 0xffff/*here.val*/;
          op &= 15;                           /* number of extra bits */
          if (op) {
            if (bits < op) {
              hold += input[_in++] << bits;
              bits += 8;
            }
            len += hold & ((1 << op) - 1);
            hold >>>= op;
            bits -= op;
          }
          //Tracevv((stderr, "inflate:         length %u\n", len));
          if (bits < 15) {
            hold += input[_in++] << bits;
            bits += 8;
            hold += input[_in++] << bits;
            bits += 8;
          }
          here = dcode[hold & dmask];

          dodist:
          for (;;) { // goto emulation
            op = here >>> 24/*here.bits*/;
            hold >>>= op;
            bits -= op;
            op = (here >>> 16) & 0xff/*here.op*/;

            if (op & 16) {                      /* distance base */
              dist = here & 0xffff/*here.val*/;
              op &= 15;                       /* number of extra bits */
              if (bits < op) {
                hold += input[_in++] << bits;
                bits += 8;
                if (bits < op) {
                  hold += input[_in++] << bits;
                  bits += 8;
                }
              }
              dist += hold & ((1 << op) - 1);
  //#ifdef INFLATE_STRICT
              if (dist > dmax) {
                strm.msg = 'invalid distance too far back';
                state.mode = BAD$1;
                break top;
              }
  //#endif
              hold >>>= op;
              bits -= op;
              //Tracevv((stderr, "inflate:         distance %u\n", dist));
              op = _out - beg;                /* max distance in output */
              if (dist > op) {                /* see if copy from window */
                op = dist - op;               /* distance back in window */
                if (op > whave) {
                  if (state.sane) {
                    strm.msg = 'invalid distance too far back';
                    state.mode = BAD$1;
                    break top;
                  }

  // (!) This block is disabled in zlib defaults,
  // don't enable it for binary compatibility
  //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  //                if (len <= op - whave) {
  //                  do {
  //                    output[_out++] = 0;
  //                  } while (--len);
  //                  continue top;
  //                }
  //                len -= op - whave;
  //                do {
  //                  output[_out++] = 0;
  //                } while (--op > whave);
  //                if (op === 0) {
  //                  from = _out - dist;
  //                  do {
  //                    output[_out++] = output[from++];
  //                  } while (--len);
  //                  continue top;
  //                }
  //#endif
                }
                from = 0; // window index
                from_source = s_window;
                if (wnext === 0) {           /* very common case */
                  from += wsize - op;
                  if (op < len) {         /* some from window */
                    len -= op;
                    do {
                      output[_out++] = s_window[from++];
                    } while (--op);
                    from = _out - dist;  /* rest from output */
                    from_source = output;
                  }
                }
                else if (wnext < op) {      /* wrap around window */
                  from += wsize + wnext - op;
                  op -= wnext;
                  if (op < len) {         /* some from end of window */
                    len -= op;
                    do {
                      output[_out++] = s_window[from++];
                    } while (--op);
                    from = 0;
                    if (wnext < len) {  /* some from start of window */
                      op = wnext;
                      len -= op;
                      do {
                        output[_out++] = s_window[from++];
                      } while (--op);
                      from = _out - dist;      /* rest from output */
                      from_source = output;
                    }
                  }
                }
                else {                      /* contiguous in window */
                  from += wnext - op;
                  if (op < len) {         /* some from window */
                    len -= op;
                    do {
                      output[_out++] = s_window[from++];
                    } while (--op);
                    from = _out - dist;  /* rest from output */
                    from_source = output;
                  }
                }
                while (len > 2) {
                  output[_out++] = from_source[from++];
                  output[_out++] = from_source[from++];
                  output[_out++] = from_source[from++];
                  len -= 3;
                }
                if (len) {
                  output[_out++] = from_source[from++];
                  if (len > 1) {
                    output[_out++] = from_source[from++];
                  }
                }
              }
              else {
                from = _out - dist;          /* copy direct from output */
                do {                        /* minimum length is three */
                  output[_out++] = output[from++];
                  output[_out++] = output[from++];
                  output[_out++] = output[from++];
                  len -= 3;
                } while (len > 2);
                if (len) {
                  output[_out++] = output[from++];
                  if (len > 1) {
                    output[_out++] = output[from++];
                  }
                }
              }
            }
            else if ((op & 64) === 0) {          /* 2nd level distance code */
              here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
              continue dodist;
            }
            else {
              strm.msg = 'invalid distance code';
              state.mode = BAD$1;
              break top;
            }

            break; // need to emulate goto via "continue"
          }
        }
        else if ((op & 64) === 0) {              /* 2nd level length code */
          here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
          continue dolen;
        }
        else if (op & 32) {                     /* end-of-block */
          //Tracevv((stderr, "inflate:         end of block\n"));
          state.mode = TYPE$1;
          break top;
        }
        else {
          strm.msg = 'invalid literal/length code';
          state.mode = BAD$1;
          break top;
        }

        break; // need to emulate goto via "continue"
      }
    } while (_in < last && _out < end);

    /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
    len = bits >> 3;
    _in -= len;
    bits -= len << 3;
    hold &= (1 << bits) - 1;

    /* update state and return */
    strm.next_in = _in;
    strm.next_out = _out;
    strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
    strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
    state.hold = hold;
    state.bits = bits;
    return;
  };

  // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  //
  // This software is provided 'as-is', without any express or implied
  // warranty. In no event will the authors be held liable for any damages
  // arising from the use of this software.
  //
  // Permission is granted to anyone to use this software for any purpose,
  // including commercial applications, and to alter it and redistribute it
  // freely, subject to the following restrictions:
  //
  // 1. The origin of this software must not be misrepresented; you must not
  //   claim that you wrote the original software. If you use this software
  //   in a product, an acknowledgment in the product documentation would be
  //   appreciated but is not required.
  // 2. Altered source versions must be plainly marked as such, and must not be
  //   misrepresented as being the original software.
  // 3. This notice may not be removed or altered from any source distribution.



  var MAXBITS = 15;
  var ENOUGH_LENS$1 = 852;
  var ENOUGH_DISTS$1 = 592;
  //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);

  var CODES$1 = 0;
  var LENS$1 = 1;
  var DISTS$1 = 2;

  var lbase = [ /* Length codes 257..285 base */
    3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
    35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  ];

  var lext = [ /* Length codes 257..285 extra */
    16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
    19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  ];

  var dbase = [ /* Distance codes 0..29 base */
    1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
    257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
    8193, 12289, 16385, 24577, 0, 0
  ];

  var dext = [ /* Distance codes 0..29 extra */
    16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
    23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
    28, 28, 29, 29, 64, 64
  ];

  var inftrees = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  {
    var bits = opts.bits;
        //here = opts.here; /* table entry for duplication */

    var len = 0;               /* a code's length in bits */
    var sym = 0;               /* index of code symbols */
    var min = 0, max = 0;          /* minimum and maximum code lengths */
    var root = 0;              /* number of index bits for root table */
    var curr = 0;              /* number of index bits for current table */
    var drop = 0;              /* code bits to drop for sub-table */
    var left = 0;                   /* number of prefix codes available */
    var used = 0;              /* code entries in table used */
    var huff = 0;              /* Huffman code */
    var incr;              /* for incrementing code, index */
    var fill;              /* index for replicating entries */
    var low;               /* low bits for current root entry */
    var mask;              /* mask for low root bits */
    var next;             /* next available space in table */
    var base = null;     /* base value table to use */
    var base_index = 0;
  //  var shoextra;    /* extra bits table to use */
    var end;                    /* use base and extra for symbol > end */
    var count = new common.Buf16(MAXBITS + 1); //[MAXBITS+1];    /* number of codes of each length */
    var offs = new common.Buf16(MAXBITS + 1); //[MAXBITS+1];     /* offsets in table for each length */
    var extra = null;
    var extra_index = 0;

    var here_bits, here_op, here_val;

    /*
     Process a set of code lengths to create a canonical Huffman code.  The
     code lengths are lens[0..codes-1].  Each length corresponds to the
     symbols 0..codes-1.  The Huffman code is generated by first sorting the
     symbols by length from short to long, and retaining the symbol order
     for codes with equal lengths.  Then the code starts with all zero bits
     for the first code of the shortest length, and the codes are integer
     increments for the same length, and zeros are appended as the length
     increases.  For the deflate format, these bits are stored backwards
     from their more natural integer increment ordering, and so when the
     decoding tables are built in the large loop below, the integer codes
     are incremented backwards.

     This routine assumes, but does not check, that all of the entries in
     lens[] are in the range 0..MAXBITS.  The caller must assure this.
     1..MAXBITS is interpreted as that code length.  zero means that that
     symbol does not occur in this code.

     The codes are sorted by computing a count of codes for each length,
     creating from that a table of starting indices for each length in the
     sorted table, and then entering the symbols in order in the sorted
     table.  The sorted table is work[], with that space being provided by
     the caller.

     The length counts are used for other purposes as well, i.e. finding
     the minimum and maximum length codes, determining if there are any
     codes at all, checking for a valid set of lengths, and looking ahead
     at length counts to determine sub-table sizes when building the
     decoding tables.
     */

    /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
    for (len = 0; len <= MAXBITS; len++) {
      count[len] = 0;
    }
    for (sym = 0; sym < codes; sym++) {
      count[lens[lens_index + sym]]++;
    }

    /* bound code lengths, force root to be within code lengths */
    root = bits;
    for (max = MAXBITS; max >= 1; max--) {
      if (count[max] !== 0) { break; }
    }
    if (root > max) {
      root = max;
    }
    if (max === 0) {                     /* no symbols to code at all */
      //table.op[opts.table_index] = 64;  //here.op = (var char)64;    /* invalid code marker */
      //table.bits[opts.table_index] = 1;   //here.bits = (var char)1;
      //table.val[opts.table_index++] = 0;   //here.val = (var short)0;
      table[table_index++] = (1 << 24) | (64 << 16) | 0;


      //table.op[opts.table_index] = 64;
      //table.bits[opts.table_index] = 1;
      //table.val[opts.table_index++] = 0;
      table[table_index++] = (1 << 24) | (64 << 16) | 0;

      opts.bits = 1;
      return 0;     /* no symbols, but wait for decoding to report error */
    }
    for (min = 1; min < max; min++) {
      if (count[min] !== 0) { break; }
    }
    if (root < min) {
      root = min;
    }

    /* check for an over-subscribed or incomplete set of lengths */
    left = 1;
    for (len = 1; len <= MAXBITS; len++) {
      left <<= 1;
      left -= count[len];
      if (left < 0) {
        return -1;
      }        /* over-subscribed */
    }
    if (left > 0 && (type === CODES$1 || max !== 1)) {
      return -1;                      /* incomplete set */
    }

    /* generate offsets into symbol table for each length for sorting */
    offs[1] = 0;
    for (len = 1; len < MAXBITS; len++) {
      offs[len + 1] = offs[len] + count[len];
    }

    /* sort symbols by length, by symbol order within each length */
    for (sym = 0; sym < codes; sym++) {
      if (lens[lens_index + sym] !== 0) {
        work[offs[lens[lens_index + sym]]++] = sym;
      }
    }

    /*
     Create and fill in decoding tables.  In this loop, the table being
     filled is at next and has curr index bits.  The code being used is huff
     with length len.  That code is converted to an index by dropping drop
     bits off of the bottom.  For codes where len is less than drop + curr,
     those top drop + curr - len bits are incremented through all values to
     fill the table with replicated entries.

     root is the number of index bits for the root table.  When len exceeds
     root, sub-tables are created pointed to by the root entry with an index
     of the low root bits of huff.  This is saved in low to check for when a
     new sub-table should be started.  drop is zero when the root table is
     being filled, and drop is root when sub-tables are being filled.

     When a new sub-table is needed, it is necessary to look ahead in the
     code lengths to determine what size sub-table is needed.  The length
     counts are used for this, and so count[] is decremented as codes are
     entered in the tables.

     used keeps track of how many table entries have been allocated from the
     provided *table space.  It is checked for LENS and DIST tables against
     the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
     the initial root table size constants.  See the comments in inftrees.h
     for more information.

     sym increments through all symbols, and the loop terminates when
     all codes of length max, i.e. all codes, have been processed.  This
     routine permits incomplete codes, so another loop after this one fills
     in the rest of the decoding tables with invalid code markers.
     */

    /* set up for code type */
    // poor man optimization - use if-else instead of switch,
    // to avoid deopts in old v8
    if (type === CODES$1) {
      base = extra = work;    /* dummy value--not used */
      end = 19;

    } else if (type === LENS$1) {
      base = lbase;
      base_index -= 257;
      extra = lext;
      extra_index -= 257;
      end = 256;

    } else {                    /* DISTS */
      base = dbase;
      extra = dext;
      end = -1;
    }

    /* initialize opts for loop */
    huff = 0;                   /* starting code */
    sym = 0;                    /* starting code symbol */
    len = min;                  /* starting code length */
    next = table_index;              /* current table to fill in */
    curr = root;                /* current table index bits */
    drop = 0;                   /* current bits to drop from code for index */
    low = -1;                   /* trigger new sub-table when len > root */
    used = 1 << root;          /* use root table entries */
    mask = used - 1;            /* mask for comparing low */

    /* check available table space */
    if ((type === LENS$1 && used > ENOUGH_LENS$1) ||
      (type === DISTS$1 && used > ENOUGH_DISTS$1)) {
      return 1;
    }

    /* process all codes and make table entries */
    for (;;) {
      /* create table entry */
      here_bits = len - drop;
      if (work[sym] < end) {
        here_op = 0;
        here_val = work[sym];
      }
      else if (work[sym] > end) {
        here_op = extra[extra_index + work[sym]];
        here_val = base[base_index + work[sym]];
      }
      else {
        here_op = 32 + 64;         /* end of block */
        here_val = 0;
      }

      /* replicate for those indices with low len bits equal to huff */
      incr = 1 << (len - drop);
      fill = 1 << curr;
      min = fill;                 /* save offset to next table */
      do {
        fill -= incr;
        table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
      } while (fill !== 0);

      /* backwards increment the len-bit code huff */
      incr = 1 << (len - 1);
      while (huff & incr) {
        incr >>= 1;
      }
      if (incr !== 0) {
        huff &= incr - 1;
        huff += incr;
      } else {
        huff = 0;
      }

      /* go to next symbol, update count, len */
      sym++;
      if (--count[len] === 0) {
        if (len === max) { break; }
        len = lens[lens_index + work[sym]];
      }

      /* create new sub-table if needed */
      if (len > root && (huff & mask) !== low) {
        /* if first time, transition to sub-tables */
        if (drop === 0) {
          drop = root;
        }

        /* increment past last table */
        next += min;            /* here min is 1 << curr */

        /* determine length of next table */
        curr = len - drop;
        left = 1 << curr;
        while (curr + drop < max) {
          left -= count[curr + drop];
          if (left <= 0) { break; }
          curr++;
          left <<= 1;
        }

        /* check for enough space */
        used += 1 << curr;
        if ((type === LENS$1 && used > ENOUGH_LENS$1) ||
          (type === DISTS$1 && used > ENOUGH_DISTS$1)) {
          return 1;
        }

        /* point entry in root table to sub-table */
        low = huff & mask;
        /*table.op[low] = curr;
        table.bits[low] = root;
        table.val[low] = next - opts.table_index;*/
        table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
      }
    }

    /* fill in remaining table entry if code is incomplete (guaranteed to have
     at most one remaining entry, since if the code is incomplete, the
     maximum code length that was allowed to get this far is one bit) */
    if (huff !== 0) {
      //table.op[next + huff] = 64;            /* invalid code marker */
      //table.bits[next + huff] = len - drop;
      //table.val[next + huff] = 0;
      table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
    }

    /* set return parameters */
    //opts.table_index += used;
    opts.bits = root;
    return 0;
  };

  // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  //
  // This software is provided 'as-is', without any express or implied
  // warranty. In no event will the authors be held liable for any damages
  // arising from the use of this software.
  //
  // Permission is granted to anyone to use this software for any purpose,
  // including commercial applications, and to alter it and redistribute it
  // freely, subject to the following restrictions:
  //
  // 1. The origin of this software must not be misrepresented; you must not
  //   claim that you wrote the original software. If you use this software
  //   in a product, an acknowledgment in the product documentation would be
  //   appreciated but is not required.
  // 2. Altered source versions must be plainly marked as such, and must not be
  //   misrepresented as being the original software.
  // 3. This notice may not be removed or altered from any source distribution.







  var CODES = 0;
  var LENS = 1;
  var DISTS = 2;

  /* Public constants ==========================================================*/
  /* ===========================================================================*/


  /* Allowed flush values; see deflate() and inflate() below for details */
  //var Z_NO_FLUSH      = 0;
  //var Z_PARTIAL_FLUSH = 1;
  //var Z_SYNC_FLUSH    = 2;
  //var Z_FULL_FLUSH    = 3;
  var Z_FINISH        = 4;
  var Z_BLOCK         = 5;
  var Z_TREES         = 6;


  /* Return codes for the compression/decompression functions. Negative values
   * are errors, positive values are used for special but normal events.
   */
  var Z_OK            = 0;
  var Z_STREAM_END    = 1;
  var Z_NEED_DICT     = 2;
  //var Z_ERRNO         = -1;
  var Z_STREAM_ERROR  = -2;
  var Z_DATA_ERROR    = -3;
  var Z_MEM_ERROR     = -4;
  var Z_BUF_ERROR     = -5;
  //var Z_VERSION_ERROR = -6;

  /* The deflate compression method */
  var Z_DEFLATED  = 8;


  /* STATES ====================================================================*/
  /* ===========================================================================*/


  var    HEAD = 1;       /* i: waiting for magic header */
  var    FLAGS = 2;      /* i: waiting for method and flags (gzip) */
  var    TIME = 3;       /* i: waiting for modification time (gzip) */
  var    OS = 4;         /* i: waiting for extra flags and operating system (gzip) */
  var    EXLEN = 5;      /* i: waiting for extra length (gzip) */
  var    EXTRA = 6;      /* i: waiting for extra bytes (gzip) */
  var    NAME = 7;       /* i: waiting for end of file name (gzip) */
  var    COMMENT = 8;    /* i: waiting for end of comment (gzip) */
  var    HCRC = 9;       /* i: waiting for header crc (gzip) */
  var    DICTID = 10;    /* i: waiting for dictionary check value */
  var    DICT = 11;      /* waiting for inflateSetDictionary() call */
  var        TYPE = 12;      /* i: waiting for type bits, including last-flag bit */
  var        TYPEDO = 13;    /* i: same, but skip check to exit inflate on new block */
  var        STORED = 14;    /* i: waiting for stored size (length and complement) */
  var        COPY_ = 15;     /* i/o: same as COPY below, but only first time in */
  var        COPY = 16;      /* i/o: waiting for input or output to copy stored block */
  var        TABLE = 17;     /* i: waiting for dynamic block table lengths */
  var        LENLENS = 18;   /* i: waiting for code length code lengths */
  var        CODELENS = 19;  /* i: waiting for length/lit and distance code lengths */
  var            LEN_ = 20;      /* i: same as LEN below, but only first time in */
  var            LEN = 21;       /* i: waiting for length/lit/eob code */
  var            LENEXT = 22;    /* i: waiting for length extra bits */
  var            DIST = 23;      /* i: waiting for distance code */
  var            DISTEXT = 24;   /* i: waiting for distance extra bits */
  var            MATCH = 25;     /* o: waiting for output space to copy string */
  var            LIT = 26;       /* o: waiting for output space to write literal */
  var    CHECK = 27;     /* i: waiting for 32-bit check value */
  var    LENGTH = 28;    /* i: waiting for 32-bit length (gzip) */
  var    DONE = 29;      /* finished check, done -- remain here until reset */
  var    BAD = 30;       /* got a data error -- remain here until reset */
  var    MEM = 31;       /* got an inflate() memory error -- remain here until reset */
  var    SYNC = 32;      /* looking for synchronization bytes to restart inflate() */

  /* ===========================================================================*/



  var ENOUGH_LENS = 852;
  var ENOUGH_DISTS = 592;
  //var ENOUGH =  (ENOUGH_LENS+ENOUGH_DISTS);

  var MAX_WBITS = 15;
  /* 32K LZ77 window */
  var DEF_WBITS = MAX_WBITS;


  function zswap32(q) {
    return  (((q >>> 24) & 0xff) +
            ((q >>> 8) & 0xff00) +
            ((q & 0xff00) << 8) +
            ((q & 0xff) << 24));
  }


  function InflateState() {
    this.mode = 0;             /* current inflate mode */
    this.last = false;          /* true if processing last block */
    this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip */
    this.havedict = false;      /* true if dictionary provided */
    this.flags = 0;             /* gzip header method and flags (0 if zlib) */
    this.dmax = 0;              /* zlib header max distance (INFLATE_STRICT) */
    this.check = 0;             /* protected copy of check value */
    this.total = 0;             /* protected copy of output count */
    // TODO: may be {}
    this.head = null;           /* where to save gzip header information */

    /* sliding window */
    this.wbits = 0;             /* log base 2 of requested window size */
    this.wsize = 0;             /* window size or zero if not using window */
    this.whave = 0;             /* valid bytes in the window */
    this.wnext = 0;             /* window write index */
    this.window = null;         /* allocated sliding window, if needed */

    /* bit accumulator */
    this.hold = 0;              /* input bit accumulator */
    this.bits = 0;              /* number of bits in "in" */

    /* for string and stored block copying */
    this.length = 0;            /* literal or length of data to copy */
    this.offset = 0;            /* distance back to copy string from */

    /* for table and code decoding */
    this.extra = 0;             /* extra bits needed */

    /* fixed and dynamic code tables */
    this.lencode = null;          /* starting table for length/literal codes */
    this.distcode = null;         /* starting table for distance codes */
    this.lenbits = 0;           /* index bits for lencode */
    this.distbits = 0;          /* index bits for distcode */

    /* dynamic table building */
    this.ncode = 0;             /* number of code length code lengths */
    this.nlen = 0;              /* number of length code lengths */
    this.ndist = 0;             /* number of distance code lengths */
    this.have = 0;              /* number of code lengths in lens[] */
    this.next = null;              /* next available space in codes[] */

    this.lens = new common.Buf16(320); /* temporary storage for code lengths */
    this.work = new common.Buf16(288); /* work area for code table building */

    /*
     because we don't have pointers in js, we use lencode and distcode directly
     as buffers so we don't need codes
    */
    //this.codes = new utils.Buf32(ENOUGH);       /* space for code tables */
    this.lendyn = null;              /* dynamic table for length/literal codes (JS specific) */
    this.distdyn = null;             /* dynamic table for distance codes (JS specific) */
    this.sane = 0;                   /* if false, allow invalid distance too far */
    this.back = 0;                   /* bits back of last unprocessed length/lit */
    this.was = 0;                    /* initial length of match */
  }

  function inflateResetKeep(strm) {
    var state;

    if (!strm || !strm.state) { return Z_STREAM_ERROR; }
    state = strm.state;
    strm.total_in = strm.total_out = state.total = 0;
    strm.msg = ''; /*Z_NULL*/
    if (state.wrap) {       /* to support ill-conceived Java test suite */
      strm.adler = state.wrap & 1;
    }
    state.mode = HEAD;
    state.last = 0;
    state.havedict = 0;
    state.dmax = 32768;
    state.head = null/*Z_NULL*/;
    state.hold = 0;
    state.bits = 0;
    //state.lencode = state.distcode = state.next = state.codes;
    state.lencode = state.lendyn = new common.Buf32(ENOUGH_LENS);
    state.distcode = state.distdyn = new common.Buf32(ENOUGH_DISTS);

    state.sane = 1;
    state.back = -1;
    //Tracev((stderr, "inflate: reset\n"));
    return Z_OK;
  }

  function inflateReset(strm) {
    var state;

    if (!strm || !strm.state) { return Z_STREAM_ERROR; }
    state = strm.state;
    state.wsize = 0;
    state.whave = 0;
    state.wnext = 0;
    return inflateResetKeep(strm);

  }

  function inflateReset2(strm, windowBits) {
    var wrap;
    var state;

    /* get the state */
    if (!strm || !strm.state) { return Z_STREAM_ERROR; }
    state = strm.state;

    /* extract wrap request from windowBits parameter */
    if (windowBits < 0) {
      wrap = 0;
      windowBits = -windowBits;
    }
    else {
      wrap = (windowBits >> 4) + 1;
      if (windowBits < 48) {
        windowBits &= 15;
      }
    }

    /* set number of window bits, free window if different */
    if (windowBits && (windowBits < 8 || windowBits > 15)) {
      return Z_STREAM_ERROR;
    }
    if (state.window !== null && state.wbits !== windowBits) {
      state.window = null;
    }

    /* update state and reset the rest of it */
    state.wrap = wrap;
    state.wbits = windowBits;
    return inflateReset(strm);
  }

  function inflateInit2(strm, windowBits) {
    var ret;
    var state;

    if (!strm) { return Z_STREAM_ERROR; }
    //strm.msg = Z_NULL;                 /* in case we return an error */

    state = new InflateState();

    //if (state === Z_NULL) return Z_MEM_ERROR;
    //Tracev((stderr, "inflate: allocated\n"));
    strm.state = state;
    state.window = null/*Z_NULL*/;
    ret = inflateReset2(strm, windowBits);
    if (ret !== Z_OK) {
      strm.state = null/*Z_NULL*/;
    }
    return ret;
  }

  function inflateInit(strm) {
    return inflateInit2(strm, DEF_WBITS);
  }


  /*
   Return state with length and distance decoding tables and index sizes set to
   fixed code decoding.  Normally this returns fixed tables from inffixed.h.
   If BUILDFIXED is defined, then instead this routine builds the tables the
   first time it's called, and returns those tables the first time and
   thereafter.  This reduces the size of the code by about 2K bytes, in
   exchange for a little execution time.  However, BUILDFIXED should not be
   used for threaded applications, since the rewriting of the tables and virgin
   may not be thread-safe.
   */
  var virgin = true;

  var lenfix, distfix; // We have no pointers in JS, so keep tables separate

  function fixedtables(state) {
    /* build fixed huffman tables if first call (may not be thread safe) */
    if (virgin) {
      var sym;

      lenfix = new common.Buf32(512);
      distfix = new common.Buf32(32);

      /* literal/length table */
      sym = 0;
      while (sym < 144) { state.lens[sym++] = 8; }
      while (sym < 256) { state.lens[sym++] = 9; }
      while (sym < 280) { state.lens[sym++] = 7; }
      while (sym < 288) { state.lens[sym++] = 8; }

      inftrees(LENS,  state.lens, 0, 288, lenfix,   0, state.work, { bits: 9 });

      /* distance table */
      sym = 0;
      while (sym < 32) { state.lens[sym++] = 5; }

      inftrees(DISTS, state.lens, 0, 32,   distfix, 0, state.work, { bits: 5 });

      /* do this just once */
      virgin = false;
    }

    state.lencode = lenfix;
    state.lenbits = 9;
    state.distcode = distfix;
    state.distbits = 5;
  }


  /*
   Update the window with the last wsize (normally 32K) bytes written before
   returning.  If window does not exist yet, create it.  This is only called
   when a window is already in use, or when output has been written during this
   inflate call, but the end of the deflate stream has not been reached yet.
   It is also called to create a window for dictionary data when a dictionary
   is loaded.

   Providing output buffers larger than 32K to inflate() should provide a speed
   advantage, since only the last 32K of output is copied to the sliding window
   upon return from inflate(), and since all distances after the first 32K of
   output will fall in the output data, making match copies simpler and faster.
   The advantage may be dependent on the size of the processor's data caches.
   */
  function updatewindow(strm, src, end, copy) {
    var dist;
    var state = strm.state;

    /* if it hasn't been done already, allocate space for the window */
    if (state.window === null) {
      state.wsize = 1 << state.wbits;
      state.wnext = 0;
      state.whave = 0;

      state.window = new common.Buf8(state.wsize);
    }

    /* copy state->wsize or less output bytes into the circular window */
    if (copy >= state.wsize) {
      common.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
      state.wnext = 0;
      state.whave = state.wsize;
    }
    else {
      dist = state.wsize - state.wnext;
      if (dist > copy) {
        dist = copy;
      }
      //zmemcpy(state->window + state->wnext, end - copy, dist);
      common.arraySet(state.window, src, end - copy, dist, state.wnext);
      copy -= dist;
      if (copy) {
        //zmemcpy(state->window, end - copy, copy);
        common.arraySet(state.window, src, end - copy, copy, 0);
        state.wnext = copy;
        state.whave = state.wsize;
      }
      else {
        state.wnext += dist;
        if (state.wnext === state.wsize) { state.wnext = 0; }
        if (state.whave < state.wsize) { state.whave += dist; }
      }
    }
    return 0;
  }

  function inflate$1(strm, flush) {
    var state;
    var input, output;          // input/output buffers
    var next;                   /* next input INDEX */
    var put;                    /* next output INDEX */
    var have, left;             /* available input and output */
    var hold;                   /* bit buffer */
    var bits;                   /* bits in bit buffer */
    var _in, _out;              /* save starting available input and output */
    var copy;                   /* number of stored or match bytes to copy */
    var from;                   /* where to copy match bytes from */
    var from_source;
    var here = 0;               /* current decoding table entry */
    var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
    //var last;                   /* parent table entry */
    var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
    var len;                    /* length to copy for repeats, bits to drop */
    var ret;                    /* return code */
    var hbuf = new common.Buf8(4);    /* buffer for gzip header crc calculation */
    var opts;

    var n; // temporary var for NEED_BITS

    var order = /* permutation of code lengths */
      [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];


    if (!strm || !strm.state || !strm.output ||
        (!strm.input && strm.avail_in !== 0)) {
      return Z_STREAM_ERROR;
    }

    state = strm.state;
    if (state.mode === TYPE) { state.mode = TYPEDO; }    /* skip check */


    //--- LOAD() ---
    put = strm.next_out;
    output = strm.output;
    left = strm.avail_out;
    next = strm.next_in;
    input = strm.input;
    have = strm.avail_in;
    hold = state.hold;
    bits = state.bits;
    //---

    _in = have;
    _out = left;
    ret = Z_OK;

    inf_leave: // goto emulation
    for (;;) {
      switch (state.mode) {
        case HEAD:
          if (state.wrap === 0) {
            state.mode = TYPEDO;
            break;
          }
          //=== NEEDBITS(16);
          while (bits < 16) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          if ((state.wrap & 2) && hold === 0x8b1f) {  /* gzip header */
            state.check = 0/*crc32(0L, Z_NULL, 0)*/;
            //=== CRC2(state.check, hold);
            hbuf[0] = hold & 0xff;
            hbuf[1] = (hold >>> 8) & 0xff;
            state.check = crc32_1(state.check, hbuf, 2, 0);
            //===//

            //=== INITBITS();
            hold = 0;
            bits = 0;
            //===//
            state.mode = FLAGS;
            break;
          }
          state.flags = 0;           /* expect zlib header */
          if (state.head) {
            state.head.done = false;
          }
          if (!(state.wrap & 1) ||   /* check if zlib header allowed */
            (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
            strm.msg = 'incorrect header check';
            state.mode = BAD;
            break;
          }
          if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
            strm.msg = 'unknown compression method';
            state.mode = BAD;
            break;
          }
          //--- DROPBITS(4) ---//
          hold >>>= 4;
          bits -= 4;
          //---//
          len = (hold & 0x0f)/*BITS(4)*/ + 8;
          if (state.wbits === 0) {
            state.wbits = len;
          }
          else if (len > state.wbits) {
            strm.msg = 'invalid window size';
            state.mode = BAD;
            break;
          }
          state.dmax = 1 << len;
          //Tracev((stderr, "inflate:   zlib header ok\n"));
          strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
          state.mode = hold & 0x200 ? DICTID : TYPE;
          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
          break;
        case FLAGS:
          //=== NEEDBITS(16); */
          while (bits < 16) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          state.flags = hold;
          if ((state.flags & 0xff) !== Z_DEFLATED) {
            strm.msg = 'unknown compression method';
            state.mode = BAD;
            break;
          }
          if (state.flags & 0xe000) {
            strm.msg = 'unknown header flags set';
            state.mode = BAD;
            break;
          }
          if (state.head) {
            state.head.text = ((hold >> 8) & 1);
          }
          if (state.flags & 0x0200) {
            //=== CRC2(state.check, hold);
            hbuf[0] = hold & 0xff;
            hbuf[1] = (hold >>> 8) & 0xff;
            state.check = crc32_1(state.check, hbuf, 2, 0);
            //===//
          }
          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
          state.mode = TIME;
          /* falls through */
        case TIME:
          //=== NEEDBITS(32); */
          while (bits < 32) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          if (state.head) {
            state.head.time = hold;
          }
          if (state.flags & 0x0200) {
            //=== CRC4(state.check, hold)
            hbuf[0] = hold & 0xff;
            hbuf[1] = (hold >>> 8) & 0xff;
            hbuf[2] = (hold >>> 16) & 0xff;
            hbuf[3] = (hold >>> 24) & 0xff;
            state.check = crc32_1(state.check, hbuf, 4, 0);
            //===
          }
          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
          state.mode = OS;
          /* falls through */
        case OS:
          //=== NEEDBITS(16); */
          while (bits < 16) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          if (state.head) {
            state.head.xflags = (hold & 0xff);
            state.head.os = (hold >> 8);
          }
          if (state.flags & 0x0200) {
            //=== CRC2(state.check, hold);
            hbuf[0] = hold & 0xff;
            hbuf[1] = (hold >>> 8) & 0xff;
            state.check = crc32_1(state.check, hbuf, 2, 0);
            //===//
          }
          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
          state.mode = EXLEN;
          /* falls through */
        case EXLEN:
          if (state.flags & 0x0400) {
            //=== NEEDBITS(16); */
            while (bits < 16) {
              if (have === 0) { break inf_leave; }
              have--;
              hold += input[next++] << bits;
              bits += 8;
            }
            //===//
            state.length = hold;
            if (state.head) {
              state.head.extra_len = hold;
            }
            if (state.flags & 0x0200) {
              //=== CRC2(state.check, hold);
              hbuf[0] = hold & 0xff;
              hbuf[1] = (hold >>> 8) & 0xff;
              state.check = crc32_1(state.check, hbuf, 2, 0);
              //===//
            }
            //=== INITBITS();
            hold = 0;
            bits = 0;
            //===//
          }
          else if (state.head) {
            state.head.extra = null/*Z_NULL*/;
          }
          state.mode = EXTRA;
          /* falls through */
        case EXTRA:
          if (state.flags & 0x0400) {
            copy = state.length;
            if (copy > have) { copy = have; }
            if (copy) {
              if (state.head) {
                len = state.head.extra_len - state.length;
                if (!state.head.extra) {
                  // Use untyped array for more convenient processing later
                  state.head.extra = new Array(state.head.extra_len);
                }
                common.arraySet(
                  state.head.extra,
                  input,
                  next,
                  // extra field is limited to 65536 bytes
                  // - no need for additional size check
                  copy,
                  /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
                  len
                );
                //zmemcpy(state.head.extra + len, next,
                //        len + copy > state.head.extra_max ?
                //        state.head.extra_max - len : copy);
              }
              if (state.flags & 0x0200) {
                state.check = crc32_1(state.check, input, copy, next);
              }
              have -= copy;
              next += copy;
              state.length -= copy;
            }
            if (state.length) { break inf_leave; }
          }
          state.length = 0;
          state.mode = NAME;
          /* falls through */
        case NAME:
          if (state.flags & 0x0800) {
            if (have === 0) { break inf_leave; }
            copy = 0;
            do {
              // TODO: 2 or 1 bytes?
              len = input[next + copy++];
              /* use constant limit because in js we should not preallocate memory */
              if (state.head && len &&
                  (state.length < 65536 /*state.head.name_max*/)) {
                state.head.name += String.fromCharCode(len);
              }
            } while (len && copy < have);

            if (state.flags & 0x0200) {
              state.check = crc32_1(state.check, input, copy, next);
            }
            have -= copy;
            next += copy;
            if (len) { break inf_leave; }
          }
          else if (state.head) {
            state.head.name = null;
          }
          state.length = 0;
          state.mode = COMMENT;
          /* falls through */
        case COMMENT:
          if (state.flags & 0x1000) {
            if (have === 0) { break inf_leave; }
            copy = 0;
            do {
              len = input[next + copy++];
              /* use constant limit because in js we should not preallocate memory */
              if (state.head && len &&
                  (state.length < 65536 /*state.head.comm_max*/)) {
                state.head.comment += String.fromCharCode(len);
              }
            } while (len && copy < have);
            if (state.flags & 0x0200) {
              state.check = crc32_1(state.check, input, copy, next);
            }
            have -= copy;
            next += copy;
            if (len) { break inf_leave; }
          }
          else if (state.head) {
            state.head.comment = null;
          }
          state.mode = HCRC;
          /* falls through */
        case HCRC:
          if (state.flags & 0x0200) {
            //=== NEEDBITS(16); */
            while (bits < 16) {
              if (have === 0) { break inf_leave; }
              have--;
              hold += input[next++] << bits;
              bits += 8;
            }
            //===//
            if (hold !== (state.check & 0xffff)) {
              strm.msg = 'header crc mismatch';
              state.mode = BAD;
              break;
            }
            //=== INITBITS();
            hold = 0;
            bits = 0;
            //===//
          }
          if (state.head) {
            state.head.hcrc = ((state.flags >> 9) & 1);
            state.head.done = true;
          }
          strm.adler = state.check = 0;
          state.mode = TYPE;
          break;
        case DICTID:
          //=== NEEDBITS(32); */
          while (bits < 32) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          strm.adler = state.check = zswap32(hold);
          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
          state.mode = DICT;
          /* falls through */
        case DICT:
          if (state.havedict === 0) {
            //--- RESTORE() ---
            strm.next_out = put;
            strm.avail_out = left;
            strm.next_in = next;
            strm.avail_in = have;
            state.hold = hold;
            state.bits = bits;
            //---
            return Z_NEED_DICT;
          }
          strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
          state.mode = TYPE;
          /* falls through */
        case TYPE:
          if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
          /* falls through */
        case TYPEDO:
          if (state.last) {
            //--- BYTEBITS() ---//
            hold >>>= bits & 7;
            bits -= bits & 7;
            //---//
            state.mode = CHECK;
            break;
          }
          //=== NEEDBITS(3); */
          while (bits < 3) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          state.last = (hold & 0x01)/*BITS(1)*/;
          //--- DROPBITS(1) ---//
          hold >>>= 1;
          bits -= 1;
          //---//

          switch ((hold & 0x03)/*BITS(2)*/) {
            case 0:                             /* stored block */
              //Tracev((stderr, "inflate:     stored block%s\n",
              //        state.last ? " (last)" : ""));
              state.mode = STORED;
              break;
            case 1:                             /* fixed block */
              fixedtables(state);
              //Tracev((stderr, "inflate:     fixed codes block%s\n",
              //        state.last ? " (last)" : ""));
              state.mode = LEN_;             /* decode codes */
              if (flush === Z_TREES) {
                //--- DROPBITS(2) ---//
                hold >>>= 2;
                bits -= 2;
                //---//
                break inf_leave;
              }
              break;
            case 2:                             /* dynamic block */
              //Tracev((stderr, "inflate:     dynamic codes block%s\n",
              //        state.last ? " (last)" : ""));
              state.mode = TABLE;
              break;
            case 3:
              strm.msg = 'invalid block type';
              state.mode = BAD;
          }
          //--- DROPBITS(2) ---//
          hold >>>= 2;
          bits -= 2;
          //---//
          break;
        case STORED:
          //--- BYTEBITS() ---// /* go to byte boundary */
          hold >>>= bits & 7;
          bits -= bits & 7;
          //---//
          //=== NEEDBITS(32); */
          while (bits < 32) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
            strm.msg = 'invalid stored block lengths';
            state.mode = BAD;
            break;
          }
          state.length = hold & 0xffff;
          //Tracev((stderr, "inflate:       stored length %u\n",
          //        state.length));
          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
          state.mode = COPY_;
          if (flush === Z_TREES) { break inf_leave; }
          /* falls through */
        case COPY_:
          state.mode = COPY;
          /* falls through */
        case COPY:
          copy = state.length;
          if (copy) {
            if (copy > have) { copy = have; }
            if (copy > left) { copy = left; }
            if (copy === 0) { break inf_leave; }
            //--- zmemcpy(put, next, copy); ---
            common.arraySet(output, input, next, copy, put);
            //---//
            have -= copy;
            next += copy;
            left -= copy;
            put += copy;
            state.length -= copy;
            break;
          }
          //Tracev((stderr, "inflate:       stored end\n"));
          state.mode = TYPE;
          break;
        case TABLE:
          //=== NEEDBITS(14); */
          while (bits < 14) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
          //--- DROPBITS(5) ---//
          hold >>>= 5;
          bits -= 5;
          //---//
          state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
          //--- DROPBITS(5) ---//
          hold >>>= 5;
          bits -= 5;
          //---//
          state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
          //--- DROPBITS(4) ---//
          hold >>>= 4;
          bits -= 4;
          //---//
  //#ifndef PKZIP_BUG_WORKAROUND
          if (state.nlen > 286 || state.ndist > 30) {
            strm.msg = 'too many length or distance symbols';
            state.mode = BAD;
            break;
          }
  //#endif
          //Tracev((stderr, "inflate:       table sizes ok\n"));
          state.have = 0;
          state.mode = LENLENS;
          /* falls through */
        case LENLENS:
          while (state.have < state.ncode) {
            //=== NEEDBITS(3);
            while (bits < 3) {
              if (have === 0) { break inf_leave; }
              have--;
              hold += input[next++] << bits;
              bits += 8;
            }
            //===//
            state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
            //--- DROPBITS(3) ---//
            hold >>>= 3;
            bits -= 3;
            //---//
          }
          while (state.have < 19) {
            state.lens[order[state.have++]] = 0;
          }
          // We have separate tables & no pointers. 2 commented lines below not needed.
          //state.next = state.codes;
          //state.lencode = state.next;
          // Switch to use dynamic table
          state.lencode = state.lendyn;
          state.lenbits = 7;

          opts = { bits: state.lenbits };
          ret = inftrees(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
          state.lenbits = opts.bits;

          if (ret) {
            strm.msg = 'invalid code lengths set';
            state.mode = BAD;
            break;
          }
          //Tracev((stderr, "inflate:       code lengths ok\n"));
          state.have = 0;
          state.mode = CODELENS;
          /* falls through */
        case CODELENS:
          while (state.have < state.nlen + state.ndist) {
            for (;;) {
              here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
              here_bits = here >>> 24;
              here_op = (here >>> 16) & 0xff;
              here_val = here & 0xffff;

              if ((here_bits) <= bits) { break; }
              //--- PULLBYTE() ---//
              if (have === 0) { break inf_leave; }
              have--;
              hold += input[next++] << bits;
              bits += 8;
              //---//
            }
            if (here_val < 16) {
              //--- DROPBITS(here.bits) ---//
              hold >>>= here_bits;
              bits -= here_bits;
              //---//
              state.lens[state.have++] = here_val;
            }
            else {
              if (here_val === 16) {
                //=== NEEDBITS(here.bits + 2);
                n = here_bits + 2;
                while (bits < n) {
                  if (have === 0) { break inf_leave; }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                //===//
                //--- DROPBITS(here.bits) ---//
                hold >>>= here_bits;
                bits -= here_bits;
                //---//
                if (state.have === 0) {
                  strm.msg = 'invalid bit length repeat';
                  state.mode = BAD;
                  break;
                }
                len = state.lens[state.have - 1];
                copy = 3 + (hold & 0x03);//BITS(2);
                //--- DROPBITS(2) ---//
                hold >>>= 2;
                bits -= 2;
                //---//
              }
              else if (here_val === 17) {
                //=== NEEDBITS(here.bits + 3);
                n = here_bits + 3;
                while (bits < n) {
                  if (have === 0) { break inf_leave; }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                //===//
                //--- DROPBITS(here.bits) ---//
                hold >>>= here_bits;
                bits -= here_bits;
                //---//
                len = 0;
                copy = 3 + (hold & 0x07);//BITS(3);
                //--- DROPBITS(3) ---//
                hold >>>= 3;
                bits -= 3;
                //---//
              }
              else {
                //=== NEEDBITS(here.bits + 7);
                n = here_bits + 7;
                while (bits < n) {
                  if (have === 0) { break inf_leave; }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                //===//
                //--- DROPBITS(here.bits) ---//
                hold >>>= here_bits;
                bits -= here_bits;
                //---//
                len = 0;
                copy = 11 + (hold & 0x7f);//BITS(7);
                //--- DROPBITS(7) ---//
                hold >>>= 7;
                bits -= 7;
                //---//
              }
              if (state.have + copy > state.nlen + state.ndist) {
                strm.msg = 'invalid bit length repeat';
                state.mode = BAD;
                break;
              }
              while (copy--) {
                state.lens[state.have++] = len;
              }
            }
          }

          /* handle error breaks in while */
          if (state.mode === BAD) { break; }

          /* check for end-of-block code (better have one) */
          if (state.lens[256] === 0) {
            strm.msg = 'invalid code -- missing end-of-block';
            state.mode = BAD;
            break;
          }

          /* build code tables -- note: do not change the lenbits or distbits
             values here (9 and 6) without reading the comments in inftrees.h
             concerning the ENOUGH constants, which depend on those values */
          state.lenbits = 9;

          opts = { bits: state.lenbits };
          ret = inftrees(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
          // We have separate tables & no pointers. 2 commented lines below not needed.
          // state.next_index = opts.table_index;
          state.lenbits = opts.bits;
          // state.lencode = state.next;

          if (ret) {
            strm.msg = 'invalid literal/lengths set';
            state.mode = BAD;
            break;
          }

          state.distbits = 6;
          //state.distcode.copy(state.codes);
          // Switch to use dynamic table
          state.distcode = state.distdyn;
          opts = { bits: state.distbits };
          ret = inftrees(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
          // We have separate tables & no pointers. 2 commented lines below not needed.
          // state.next_index = opts.table_index;
          state.distbits = opts.bits;
          // state.distcode = state.next;

          if (ret) {
            strm.msg = 'invalid distances set';
            state.mode = BAD;
            break;
          }
          //Tracev((stderr, 'inflate:       codes ok\n'));
          state.mode = LEN_;
          if (flush === Z_TREES) { break inf_leave; }
          /* falls through */
        case LEN_:
          state.mode = LEN;
          /* falls through */
        case LEN:
          if (have >= 6 && left >= 258) {
            //--- RESTORE() ---
            strm.next_out = put;
            strm.avail_out = left;
            strm.next_in = next;
            strm.avail_in = have;
            state.hold = hold;
            state.bits = bits;
            //---
            inffast(strm, _out);
            //--- LOAD() ---
            put = strm.next_out;
            output = strm.output;
            left = strm.avail_out;
            next = strm.next_in;
            input = strm.input;
            have = strm.avail_in;
            hold = state.hold;
            bits = state.bits;
            //---

            if (state.mode === TYPE) {
              state.back = -1;
            }
            break;
          }
          state.back = 0;
          for (;;) {
            here = state.lencode[hold & ((1 << state.lenbits) - 1)];  /*BITS(state.lenbits)*/
            here_bits = here >>> 24;
            here_op = (here >>> 16) & 0xff;
            here_val = here & 0xffff;

            if (here_bits <= bits) { break; }
            //--- PULLBYTE() ---//
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
            //---//
          }
          if (here_op && (here_op & 0xf0) === 0) {
            last_bits = here_bits;
            last_op = here_op;
            last_val = here_val;
            for (;;) {
              here = state.lencode[last_val +
                      ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
              here_bits = here >>> 24;
              here_op = (here >>> 16) & 0xff;
              here_val = here & 0xffff;

              if ((last_bits + here_bits) <= bits) { break; }
              //--- PULLBYTE() ---//
              if (have === 0) { break inf_leave; }
              have--;
              hold += input[next++] << bits;
              bits += 8;
              //---//
            }
            //--- DROPBITS(last.bits) ---//
            hold >>>= last_bits;
            bits -= last_bits;
            //---//
            state.back += last_bits;
          }
          //--- DROPBITS(here.bits) ---//
          hold >>>= here_bits;
          bits -= here_bits;
          //---//
          state.back += here_bits;
          state.length = here_val;
          if (here_op === 0) {
            //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
            //        "inflate:         literal '%c'\n" :
            //        "inflate:         literal 0x%02x\n", here.val));
            state.mode = LIT;
            break;
          }
          if (here_op & 32) {
            //Tracevv((stderr, "inflate:         end of block\n"));
            state.back = -1;
            state.mode = TYPE;
            break;
          }
          if (here_op & 64) {
            strm.msg = 'invalid literal/length code';
            state.mode = BAD;
            break;
          }
          state.extra = here_op & 15;
          state.mode = LENEXT;
          /* falls through */
        case LENEXT:
          if (state.extra) {
            //=== NEEDBITS(state.extra);
            n = state.extra;
            while (bits < n) {
              if (have === 0) { break inf_leave; }
              have--;
              hold += input[next++] << bits;
              bits += 8;
            }
            //===//
            state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
            //--- DROPBITS(state.extra) ---//
            hold >>>= state.extra;
            bits -= state.extra;
            //---//
            state.back += state.extra;
          }
          //Tracevv((stderr, "inflate:         length %u\n", state.length));
          state.was = state.length;
          state.mode = DIST;
          /* falls through */
        case DIST:
          for (;;) {
            here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
            here_bits = here >>> 24;
            here_op = (here >>> 16) & 0xff;
            here_val = here & 0xffff;

            if ((here_bits) <= bits) { break; }
            //--- PULLBYTE() ---//
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
            //---//
          }
          if ((here_op & 0xf0) === 0) {
            last_bits = here_bits;
            last_op = here_op;
            last_val = here_val;
            for (;;) {
              here = state.distcode[last_val +
                      ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
              here_bits = here >>> 24;
              here_op = (here >>> 16) & 0xff;
              here_val = here & 0xffff;

              if ((last_bits + here_bits) <= bits) { break; }
              //--- PULLBYTE() ---//
              if (have === 0) { break inf_leave; }
              have--;
              hold += input[next++] << bits;
              bits += 8;
              //---//
            }
            //--- DROPBITS(last.bits) ---//
            hold >>>= last_bits;
            bits -= last_bits;
            //---//
            state.back += last_bits;
          }
          //--- DROPBITS(here.bits) ---//
          hold >>>= here_bits;
          bits -= here_bits;
          //---//
          state.back += here_bits;
          if (here_op & 64) {
            strm.msg = 'invalid distance code';
            state.mode = BAD;
            break;
          }
          state.offset = here_val;
          state.extra = (here_op) & 15;
          state.mode = DISTEXT;
          /* falls through */
        case DISTEXT:
          if (state.extra) {
            //=== NEEDBITS(state.extra);
            n = state.extra;
            while (bits < n) {
              if (have === 0) { break inf_leave; }
              have--;
              hold += input[next++] << bits;
              bits += 8;
            }
            //===//
            state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
            //--- DROPBITS(state.extra) ---//
            hold >>>= state.extra;
            bits -= state.extra;
            //---//
            state.back += state.extra;
          }
  //#ifdef INFLATE_STRICT
          if (state.offset > state.dmax) {
            strm.msg = 'invalid distance too far back';
            state.mode = BAD;
            break;
          }
  //#endif
          //Tracevv((stderr, "inflate:         distance %u\n", state.offset));
          state.mode = MATCH;
          /* falls through */
        case MATCH:
          if (left === 0) { break inf_leave; }
          copy = _out - left;
          if (state.offset > copy) {         /* copy from window */
            copy = state.offset - copy;
            if (copy > state.whave) {
              if (state.sane) {
                strm.msg = 'invalid distance too far back';
                state.mode = BAD;
                break;
              }
  // (!) This block is disabled in zlib defaults,
  // don't enable it for binary compatibility
  //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  //          Trace((stderr, "inflate.c too far\n"));
  //          copy -= state.whave;
  //          if (copy > state.length) { copy = state.length; }
  //          if (copy > left) { copy = left; }
  //          left -= copy;
  //          state.length -= copy;
  //          do {
  //            output[put++] = 0;
  //          } while (--copy);
  //          if (state.length === 0) { state.mode = LEN; }
  //          break;
  //#endif
            }
            if (copy > state.wnext) {
              copy -= state.wnext;
              from = state.wsize - copy;
            }
            else {
              from = state.wnext - copy;
            }
            if (copy > state.length) { copy = state.length; }
            from_source = state.window;
          }
          else {                              /* copy from output */
            from_source = output;
            from = put - state.offset;
            copy = state.length;
          }
          if (copy > left) { copy = left; }
          left -= copy;
          state.length -= copy;
          do {
            output[put++] = from_source[from++];
          } while (--copy);
          if (state.length === 0) { state.mode = LEN; }
          break;
        case LIT:
          if (left === 0) { break inf_leave; }
          output[put++] = state.length;
          left--;
          state.mode = LEN;
          break;
        case CHECK:
          if (state.wrap) {
            //=== NEEDBITS(32);
            while (bits < 32) {
              if (have === 0) { break inf_leave; }
              have--;
              // Use '|' instead of '+' to make sure that result is signed
              hold |= input[next++] << bits;
              bits += 8;
            }
            //===//
            _out -= left;
            strm.total_out += _out;
            state.total += _out;
            if (_out) {
              strm.adler = state.check =
                  /*UPDATE(state.check, put - _out, _out);*/
                  (state.flags ? crc32_1(state.check, output, _out, put - _out) : adler32_1(state.check, output, _out, put - _out));

            }
            _out = left;
            // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
            if ((state.flags ? hold : zswap32(hold)) !== state.check) {
              strm.msg = 'incorrect data check';
              state.mode = BAD;
              break;
            }
            //=== INITBITS();
            hold = 0;
            bits = 0;
            //===//
            //Tracev((stderr, "inflate:   check matches trailer\n"));
          }
          state.mode = LENGTH;
          /* falls through */
        case LENGTH:
          if (state.wrap && state.flags) {
            //=== NEEDBITS(32);
            while (bits < 32) {
              if (have === 0) { break inf_leave; }
              have--;
              hold += input[next++] << bits;
              bits += 8;
            }
            //===//
            if (hold !== (state.total & 0xffffffff)) {
              strm.msg = 'incorrect length check';
              state.mode = BAD;
              break;
            }
            //=== INITBITS();
            hold = 0;
            bits = 0;
            //===//
            //Tracev((stderr, "inflate:   length matches trailer\n"));
          }
          state.mode = DONE;
          /* falls through */
        case DONE:
          ret = Z_STREAM_END;
          break inf_leave;
        case BAD:
          ret = Z_DATA_ERROR;
          break inf_leave;
        case MEM:
          return Z_MEM_ERROR;
        case SYNC:
          /* falls through */
        default:
          return Z_STREAM_ERROR;
      }
    }

    // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"

    /*
       Return from inflate(), updating the total counts and the check value.
       If there was no progress during the inflate() call, return a buffer
       error.  Call updatewindow() to create and/or update the window state.
       Note: a memory error from inflate() is non-recoverable.
     */

    //--- RESTORE() ---
    strm.next_out = put;
    strm.avail_out = left;
    strm.next_in = next;
    strm.avail_in = have;
    state.hold = hold;
    state.bits = bits;
    //---

    if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
                        (state.mode < CHECK || flush !== Z_FINISH))) {
      if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ;
    }
    _in -= strm.avail_in;
    _out -= strm.avail_out;
    strm.total_in += _in;
    strm.total_out += _out;
    state.total += _out;
    if (state.wrap && _out) {
      strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
        (state.flags ? crc32_1(state.check, output, _out, strm.next_out - _out) : adler32_1(state.check, output, _out, strm.next_out - _out));
    }
    strm.data_type = state.bits + (state.last ? 64 : 0) +
                      (state.mode === TYPE ? 128 : 0) +
                      (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
    if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
      ret = Z_BUF_ERROR;
    }
    return ret;
  }

  function inflateEnd(strm) {

    if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
      return Z_STREAM_ERROR;
    }

    var state = strm.state;
    if (state.window) {
      state.window = null;
    }
    strm.state = null;
    return Z_OK;
  }

  function inflateGetHeader(strm, head) {
    var state;

    /* check state */
    if (!strm || !strm.state) { return Z_STREAM_ERROR; }
    state = strm.state;
    if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }

    /* save header structure */
    state.head = head;
    head.done = false;
    return Z_OK;
  }

  function inflateSetDictionary(strm, dictionary) {
    var dictLength = dictionary.length;

    var state;
    var dictid;
    var ret;

    /* check state */
    if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
    state = strm.state;

    if (state.wrap !== 0 && state.mode !== DICT) {
      return Z_STREAM_ERROR;
    }

    /* check for correct dictionary identifier */
    if (state.mode === DICT) {
      dictid = 1; /* adler32(0, null, 0)*/
      /* dictid = adler32(dictid, dictionary, dictLength); */
      dictid = adler32_1(dictid, dictionary, dictLength, 0);
      if (dictid !== state.check) {
        return Z_DATA_ERROR;
      }
    }
    /* copy dictionary to window using updatewindow(), which will amend the
     existing dictionary if appropriate */
    ret = updatewindow(strm, dictionary, dictLength, dictLength);
    if (ret) {
      state.mode = MEM;
      return Z_MEM_ERROR;
    }
    state.havedict = 1;
    // Tracev((stderr, "inflate:   dictionary set\n"));
    return Z_OK;
  }

  var inflateReset_1 = inflateReset;
  var inflateReset2_1 = inflateReset2;
  var inflateResetKeep_1 = inflateResetKeep;
  var inflateInit_1 = inflateInit;
  var inflateInit2_1 = inflateInit2;
  var inflate_2$1 = inflate$1;
  var inflateEnd_1 = inflateEnd;
  var inflateGetHeader_1 = inflateGetHeader;
  var inflateSetDictionary_1 = inflateSetDictionary;
  var inflateInfo = 'pako inflate (from Nodeca project)';

  /* Not implemented
  exports.inflateCopy = inflateCopy;
  exports.inflateGetDictionary = inflateGetDictionary;
  exports.inflateMark = inflateMark;
  exports.inflatePrime = inflatePrime;
  exports.inflateSync = inflateSync;
  exports.inflateSyncPoint = inflateSyncPoint;
  exports.inflateUndermine = inflateUndermine;
  */

  var inflate_1$1 = {
  	inflateReset: inflateReset_1,
  	inflateReset2: inflateReset2_1,
  	inflateResetKeep: inflateResetKeep_1,
  	inflateInit: inflateInit_1,
  	inflateInit2: inflateInit2_1,
  	inflate: inflate_2$1,
  	inflateEnd: inflateEnd_1,
  	inflateGetHeader: inflateGetHeader_1,
  	inflateSetDictionary: inflateSetDictionary_1,
  	inflateInfo: inflateInfo
  };

  // Quick check if we can use fast array to bin string conversion
  //
  // - apply(Array) can fail on Android 2.2
  // - apply(Uint8Array) can fail on iOS 5.1 Safari
  //
  var STR_APPLY_OK = true;
  var STR_APPLY_UIA_OK = true;

  try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }
  try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }


  // Table with utf8 lengths (calculated by first byte of sequence)
  // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  // because max possible codepoint is 0x10ffff
  var _utf8len = new common.Buf8(256);
  for (var q = 0; q < 256; q++) {
    _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  }
  _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start


  // convert string to array (typed, when possible)
  var string2buf = function (str) {
    var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;

    // count binary size
    for (m_pos = 0; m_pos < str_len; m_pos++) {
      c = str.charCodeAt(m_pos);
      if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
        c2 = str.charCodeAt(m_pos + 1);
        if ((c2 & 0xfc00) === 0xdc00) {
          c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
          m_pos++;
        }
      }
      buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
    }

    // allocate buffer
    buf = new common.Buf8(buf_len);

    // convert
    for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
      c = str.charCodeAt(m_pos);
      if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
        c2 = str.charCodeAt(m_pos + 1);
        if ((c2 & 0xfc00) === 0xdc00) {
          c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
          m_pos++;
        }
      }
      if (c < 0x80) {
        /* one byte */
        buf[i++] = c;
      } else if (c < 0x800) {
        /* two bytes */
        buf[i++] = 0xC0 | (c >>> 6);
        buf[i++] = 0x80 | (c & 0x3f);
      } else if (c < 0x10000) {
        /* three bytes */
        buf[i++] = 0xE0 | (c >>> 12);
        buf[i++] = 0x80 | (c >>> 6 & 0x3f);
        buf[i++] = 0x80 | (c & 0x3f);
      } else {
        /* four bytes */
        buf[i++] = 0xf0 | (c >>> 18);
        buf[i++] = 0x80 | (c >>> 12 & 0x3f);
        buf[i++] = 0x80 | (c >>> 6 & 0x3f);
        buf[i++] = 0x80 | (c & 0x3f);
      }
    }

    return buf;
  };

  // Helper (used in 2 places)
  function buf2binstring(buf, len) {
    // On Chrome, the arguments in a function call that are allowed is `65534`.
    // If the length of the buffer is smaller than that, we can use this optimization,
    // otherwise we will take a slower path.
    if (len < 65534) {
      if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
        return String.fromCharCode.apply(null, common.shrinkBuf(buf, len));
      }
    }

    var result = '';
    for (var i = 0; i < len; i++) {
      result += String.fromCharCode(buf[i]);
    }
    return result;
  }


  // Convert byte array to binary string
  var buf2binstring_1 = function (buf) {
    return buf2binstring(buf, buf.length);
  };


  // Convert binary string (typed, when possible)
  var binstring2buf = function (str) {
    var buf = new common.Buf8(str.length);
    for (var i = 0, len = buf.length; i < len; i++) {
      buf[i] = str.charCodeAt(i);
    }
    return buf;
  };


  // convert array to string
  var buf2string = function (buf, max) {
    var i, out, c, c_len;
    var len = max || buf.length;

    // Reserve max possible length (2 words per char)
    // NB: by unknown reasons, Array is significantly faster for
    //     String.fromCharCode.apply than Uint16Array.
    var utf16buf = new Array(len * 2);

    for (out = 0, i = 0; i < len;) {
      c = buf[i++];
      // quick process ascii
      if (c < 0x80) { utf16buf[out++] = c; continue; }

      c_len = _utf8len[c];
      // skip 5 & 6 byte codes
      if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }

      // apply mask on first byte
      c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
      // join the rest
      while (c_len > 1 && i < len) {
        c = (c << 6) | (buf[i++] & 0x3f);
        c_len--;
      }

      // terminated by end of string?
      if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }

      if (c < 0x10000) {
        utf16buf[out++] = c;
      } else {
        c -= 0x10000;
        utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
        utf16buf[out++] = 0xdc00 | (c & 0x3ff);
      }
    }

    return buf2binstring(utf16buf, out);
  };


  // Calculate max possible position in utf8 buffer,
  // that will not break sequence. If that's not possible
  // - (very small limits) return max size as is.
  //
  // buf[] - utf8 bytes array
  // max   - length limit (mandatory);
  var utf8border = function (buf, max) {
    var pos;

    max = max || buf.length;
    if (max > buf.length) { max = buf.length; }

    // go back from last position, until start of sequence found
    pos = max - 1;
    while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }

    // Very small and broken sequence,
    // return max, because we should return something anyway.
    if (pos < 0) { return max; }

    // If we came to start of buffer - that means buffer is too small,
    // return max too.
    if (pos === 0) { return max; }

    return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  };

  var strings = {
  	string2buf: string2buf,
  	buf2binstring: buf2binstring_1,
  	binstring2buf: binstring2buf,
  	buf2string: buf2string,
  	utf8border: utf8border
  };

  // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  //
  // This software is provided 'as-is', without any express or implied
  // warranty. In no event will the authors be held liable for any damages
  // arising from the use of this software.
  //
  // Permission is granted to anyone to use this software for any purpose,
  // including commercial applications, and to alter it and redistribute it
  // freely, subject to the following restrictions:
  //
  // 1. The origin of this software must not be misrepresented; you must not
  //   claim that you wrote the original software. If you use this software
  //   in a product, an acknowledgment in the product documentation would be
  //   appreciated but is not required.
  // 2. Altered source versions must be plainly marked as such, and must not be
  //   misrepresented as being the original software.
  // 3. This notice may not be removed or altered from any source distribution.

  var constants = {

    /* Allowed flush values; see deflate() and inflate() below for details */
    Z_NO_FLUSH:         0,
    Z_PARTIAL_FLUSH:    1,
    Z_SYNC_FLUSH:       2,
    Z_FULL_FLUSH:       3,
    Z_FINISH:           4,
    Z_BLOCK:            5,
    Z_TREES:            6,

    /* Return codes for the compression/decompression functions. Negative values
    * are errors, positive values are used for special but normal events.
    */
    Z_OK:               0,
    Z_STREAM_END:       1,
    Z_NEED_DICT:        2,
    Z_ERRNO:           -1,
    Z_STREAM_ERROR:    -2,
    Z_DATA_ERROR:      -3,
    //Z_MEM_ERROR:     -4,
    Z_BUF_ERROR:       -5,
    //Z_VERSION_ERROR: -6,

    /* compression levels */
    Z_NO_COMPRESSION:         0,
    Z_BEST_SPEED:             1,
    Z_BEST_COMPRESSION:       9,
    Z_DEFAULT_COMPRESSION:   -1,


    Z_FILTERED:               1,
    Z_HUFFMAN_ONLY:           2,
    Z_RLE:                    3,
    Z_FIXED:                  4,
    Z_DEFAULT_STRATEGY:       0,

    /* Possible values of the data_type field (though see inflate()) */
    Z_BINARY:                 0,
    Z_TEXT:                   1,
    //Z_ASCII:                1, // = Z_TEXT (deprecated)
    Z_UNKNOWN:                2,

    /* The deflate compression method */
    Z_DEFLATED:               8
    //Z_NULL:                 null // Use -1 or null inline, depending on var type
  };

  // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  //
  // This software is provided 'as-is', without any express or implied
  // warranty. In no event will the authors be held liable for any damages
  // arising from the use of this software.
  //
  // Permission is granted to anyone to use this software for any purpose,
  // including commercial applications, and to alter it and redistribute it
  // freely, subject to the following restrictions:
  //
  // 1. The origin of this software must not be misrepresented; you must not
  //   claim that you wrote the original software. If you use this software
  //   in a product, an acknowledgment in the product documentation would be
  //   appreciated but is not required.
  // 2. Altered source versions must be plainly marked as such, and must not be
  //   misrepresented as being the original software.
  // 3. This notice may not be removed or altered from any source distribution.

  var messages = {
    2:      'need dictionary',     /* Z_NEED_DICT       2  */
    1:      'stream end',          /* Z_STREAM_END      1  */
    0:      '',                    /* Z_OK              0  */
    '-1':   'file error',          /* Z_ERRNO         (-1) */
    '-2':   'stream error',        /* Z_STREAM_ERROR  (-2) */
    '-3':   'data error',          /* Z_DATA_ERROR    (-3) */
    '-4':   'insufficient memory', /* Z_MEM_ERROR     (-4) */
    '-5':   'buffer error',        /* Z_BUF_ERROR     (-5) */
    '-6':   'incompatible version' /* Z_VERSION_ERROR (-6) */
  };

  // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  //
  // This software is provided 'as-is', without any express or implied
  // warranty. In no event will the authors be held liable for any damages
  // arising from the use of this software.
  //
  // Permission is granted to anyone to use this software for any purpose,
  // including commercial applications, and to alter it and redistribute it
  // freely, subject to the following restrictions:
  //
  // 1. The origin of this software must not be misrepresented; you must not
  //   claim that you wrote the original software. If you use this software
  //   in a product, an acknowledgment in the product documentation would be
  //   appreciated but is not required.
  // 2. Altered source versions must be plainly marked as such, and must not be
  //   misrepresented as being the original software.
  // 3. This notice may not be removed or altered from any source distribution.

  function ZStream() {
    /* next input byte */
    this.input = null; // JS specific, because we have no pointers
    this.next_in = 0;
    /* number of bytes available at input */
    this.avail_in = 0;
    /* total number of input bytes read so far */
    this.total_in = 0;
    /* next output byte should be put there */
    this.output = null; // JS specific, because we have no pointers
    this.next_out = 0;
    /* remaining free space at output */
    this.avail_out = 0;
    /* total number of bytes output so far */
    this.total_out = 0;
    /* last error message, NULL if no error */
    this.msg = ''/*Z_NULL*/;
    /* not visible by applications */
    this.state = null;
    /* best guess about the data type: binary or text */
    this.data_type = 2/*Z_UNKNOWN*/;
    /* adler32 value of the uncompressed data */
    this.adler = 0;
  }

  var zstream = ZStream;

  // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  //
  // This software is provided 'as-is', without any express or implied
  // warranty. In no event will the authors be held liable for any damages
  // arising from the use of this software.
  //
  // Permission is granted to anyone to use this software for any purpose,
  // including commercial applications, and to alter it and redistribute it
  // freely, subject to the following restrictions:
  //
  // 1. The origin of this software must not be misrepresented; you must not
  //   claim that you wrote the original software. If you use this software
  //   in a product, an acknowledgment in the product documentation would be
  //   appreciated but is not required.
  // 2. Altered source versions must be plainly marked as such, and must not be
  //   misrepresented as being the original software.
  // 3. This notice may not be removed or altered from any source distribution.

  function GZheader() {
    /* true if compressed data believed to be text */
    this.text       = 0;
    /* modification time */
    this.time       = 0;
    /* extra flags (not used when writing a gzip file) */
    this.xflags     = 0;
    /* operating system */
    this.os         = 0;
    /* pointer to extra field or Z_NULL if none */
    this.extra      = null;
    /* extra field length (valid if extra != Z_NULL) */
    this.extra_len  = 0; // Actually, we don't need it in JS,
                         // but leave for few code modifications

    //
    // Setup limits is not necessary because in js we should not preallocate memory
    // for inflate use constant limit in 65536 bytes
    //

    /* space at extra (only when reading header) */
    // this.extra_max  = 0;
    /* pointer to zero-terminated file name or Z_NULL */
    this.name       = '';
    /* space at name (only when reading header) */
    // this.name_max   = 0;
    /* pointer to zero-terminated comment or Z_NULL */
    this.comment    = '';
    /* space at comment (only when reading header) */
    // this.comm_max   = 0;
    /* true if there was or will be a header crc */
    this.hcrc       = 0;
    /* true when done reading gzip header (not used when writing a gzip file) */
    this.done       = false;
  }

  var gzheader = GZheader;

  var toString = Object.prototype.toString;

  /**
   * class Inflate
   *
   * Generic JS-style wrapper for zlib calls. If you don't need
   * streaming behaviour - use more simple functions: [[inflate]]
   * and [[inflateRaw]].
   **/

  /* internal
   * inflate.chunks -> Array
   *
   * Chunks of output data, if [[Inflate#onData]] not overridden.
   **/

  /**
   * Inflate.result -> Uint8Array|Array|String
   *
   * Uncompressed result, generated by default [[Inflate#onData]]
   * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
   * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
   * push a chunk with explicit flush (call [[Inflate#push]] with
   * `Z_SYNC_FLUSH` param).
   **/

  /**
   * Inflate.err -> Number
   *
   * Error code after inflate finished. 0 (Z_OK) on success.
   * Should be checked if broken data possible.
   **/

  /**
   * Inflate.msg -> String
   *
   * Error message, if [[Inflate.err]] != 0
   **/


  /**
   * new Inflate(options)
   * - options (Object): zlib inflate options.
   *
   * Creates new inflator instance with specified params. Throws exception
   * on bad params. Supported options:
   *
   * - `windowBits`
   * - `dictionary`
   *
   * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
   * for more information on these.
   *
   * Additional options, for internal needs:
   *
   * - `chunkSize` - size of generated data chunks (16K by default)
   * - `raw` (Boolean) - do raw inflate
   * - `to` (String) - if equal to 'string', then result will be converted
   *   from utf8 to utf16 (javascript) string. When string output requested,
   *   chunk length can differ from `chunkSize`, depending on content.
   *
   * By default, when no options set, autodetect deflate/gzip data format via
   * wrapper header.
   *
   * ##### Example:
   *
   * ```javascript
   * var pako = require('pako')
   *   , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
   *   , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
   *
   * var inflate = new pako.Inflate({ level: 3});
   *
   * inflate.push(chunk1, false);
   * inflate.push(chunk2, true);  // true -> last chunk
   *
   * if (inflate.err) { throw new Error(inflate.err); }
   *
   * console.log(inflate.result);
   * ```
   **/
  function Inflate(options) {
    if (!(this instanceof Inflate)) return new Inflate(options);

    this.options = common.assign({
      chunkSize: 16384,
      windowBits: 0,
      to: ''
    }, options || {});

    var opt = this.options;

    // Force window size for `raw` data, if not set directly,
    // because we have no header for autodetect.
    if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
      opt.windowBits = -opt.windowBits;
      if (opt.windowBits === 0) { opt.windowBits = -15; }
    }

    // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
    if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
        !(options && options.windowBits)) {
      opt.windowBits += 32;
    }

    // Gzip header has no info about windows size, we can do autodetect only
    // for deflate. So, if window size not set, force it to max when gzip possible
    if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
      // bit 3 (16) -> gzipped data
      // bit 4 (32) -> autodetect gzip/deflate
      if ((opt.windowBits & 15) === 0) {
        opt.windowBits |= 15;
      }
    }

    this.err    = 0;      // error code, if happens (0 = Z_OK)
    this.msg    = '';     // error message
    this.ended  = false;  // used to avoid multiple onEnd() calls
    this.chunks = [];     // chunks of compressed data

    this.strm   = new zstream();
    this.strm.avail_out = 0;

    var status  = inflate_1$1.inflateInit2(
      this.strm,
      opt.windowBits
    );

    if (status !== constants.Z_OK) {
      throw new Error(messages[status]);
    }

    this.header = new gzheader();

    inflate_1$1.inflateGetHeader(this.strm, this.header);

    // Setup dictionary
    if (opt.dictionary) {
      // Convert data if needed
      if (typeof opt.dictionary === 'string') {
        opt.dictionary = strings.string2buf(opt.dictionary);
      } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
        opt.dictionary = new Uint8Array(opt.dictionary);
      }
      if (opt.raw) { //In raw mode we need to set the dictionary early
        status = inflate_1$1.inflateSetDictionary(this.strm, opt.dictionary);
        if (status !== constants.Z_OK) {
          throw new Error(messages[status]);
        }
      }
    }
  }

  /**
   * Inflate#push(data[, mode]) -> Boolean
   * - data (Uint8Array|Array|ArrayBuffer|String): input data
   * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
   *   See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
   *
   * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
   * new output chunks. Returns `true` on success. The last data block must have
   * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
   * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
   * can use mode Z_SYNC_FLUSH, keeping the decompression context.
   *
   * On fail call [[Inflate#onEnd]] with error code and return false.
   *
   * We strongly recommend to use `Uint8Array` on input for best speed (output
   * format is detected automatically). Also, don't skip last param and always
   * use the same type in your code (boolean or number). That will improve JS speed.
   *
   * For regular `Array`-s make sure all elements are [0..255].
   *
   * ##### Example
   *
   * ```javascript
   * push(chunk, false); // push one of data chunks
   * ...
   * push(chunk, true);  // push last chunk
   * ```
   **/
  Inflate.prototype.push = function (data, mode) {
    var strm = this.strm;
    var chunkSize = this.options.chunkSize;
    var dictionary = this.options.dictionary;
    var status, _mode;
    var next_out_utf8, tail, utf8str;

    // Flag to properly process Z_BUF_ERROR on testing inflate call
    // when we check that all output data was flushed.
    var allowBufError = false;

    if (this.ended) { return false; }
    _mode = (mode === ~~mode) ? mode : ((mode === true) ? constants.Z_FINISH : constants.Z_NO_FLUSH);

    // Convert data if needed
    if (typeof data === 'string') {
      // Only binary strings can be decompressed on practice
      strm.input = strings.binstring2buf(data);
    } else if (toString.call(data) === '[object ArrayBuffer]') {
      strm.input = new Uint8Array(data);
    } else {
      strm.input = data;
    }

    strm.next_in = 0;
    strm.avail_in = strm.input.length;

    do {
      if (strm.avail_out === 0) {
        strm.output = new common.Buf8(chunkSize);
        strm.next_out = 0;
        strm.avail_out = chunkSize;
      }

      status = inflate_1$1.inflate(strm, constants.Z_NO_FLUSH);    /* no bad return value */

      if (status === constants.Z_NEED_DICT && dictionary) {
        status = inflate_1$1.inflateSetDictionary(this.strm, dictionary);
      }

      if (status === constants.Z_BUF_ERROR && allowBufError === true) {
        status = constants.Z_OK;
        allowBufError = false;
      }

      if (status !== constants.Z_STREAM_END && status !== constants.Z_OK) {
        this.onEnd(status);
        this.ended = true;
        return false;
      }

      if (strm.next_out) {
        if (strm.avail_out === 0 || status === constants.Z_STREAM_END || (strm.avail_in === 0 && (_mode === constants.Z_FINISH || _mode === constants.Z_SYNC_FLUSH))) {

          if (this.options.to === 'string') {

            next_out_utf8 = strings.utf8border(strm.output, strm.next_out);

            tail = strm.next_out - next_out_utf8;
            utf8str = strings.buf2string(strm.output, next_out_utf8);

            // move tail
            strm.next_out = tail;
            strm.avail_out = chunkSize - tail;
            if (tail) { common.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }

            this.onData(utf8str);

          } else {
            this.onData(common.shrinkBuf(strm.output, strm.next_out));
          }
        }
      }

      // When no more input data, we should check that internal inflate buffers
      // are flushed. The only way to do it when avail_out = 0 - run one more
      // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
      // Here we set flag to process this error properly.
      //
      // NOTE. Deflate does not return error in this case and does not needs such
      // logic.
      if (strm.avail_in === 0 && strm.avail_out === 0) {
        allowBufError = true;
      }

    } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== constants.Z_STREAM_END);

    if (status === constants.Z_STREAM_END) {
      _mode = constants.Z_FINISH;
    }

    // Finalize on the last chunk.
    if (_mode === constants.Z_FINISH) {
      status = inflate_1$1.inflateEnd(this.strm);
      this.onEnd(status);
      this.ended = true;
      return status === constants.Z_OK;
    }

    // callback interim results if Z_SYNC_FLUSH.
    if (_mode === constants.Z_SYNC_FLUSH) {
      this.onEnd(constants.Z_OK);
      strm.avail_out = 0;
      return true;
    }

    return true;
  };


  /**
   * Inflate#onData(chunk) -> Void
   * - chunk (Uint8Array|Array|String): output data. Type of array depends
   *   on js engine support. When string output requested, each chunk
   *   will be string.
   *
   * By default, stores data blocks in `chunks[]` property and glue
   * those in `onEnd`. Override this handler, if you need another behaviour.
   **/
  Inflate.prototype.onData = function (chunk) {
    this.chunks.push(chunk);
  };


  /**
   * Inflate#onEnd(status) -> Void
   * - status (Number): inflate status. 0 (Z_OK) on success,
   *   other if not.
   *
   * Called either after you tell inflate that the input stream is
   * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
   * or if an error happened. By default - join collected chunks,
   * free memory and fill `results` / `err` properties.
   **/
  Inflate.prototype.onEnd = function (status) {
    // On success - join
    if (status === constants.Z_OK) {
      if (this.options.to === 'string') {
        // Glue & convert here, until we teach pako to send
        // utf8 aligned strings to onData
        this.result = this.chunks.join('');
      } else {
        this.result = common.flattenChunks(this.chunks);
      }
    }
    this.chunks = [];
    this.err = status;
    this.msg = this.strm.msg;
  };


  /**
   * inflate(data[, options]) -> Uint8Array|Array|String
   * - data (Uint8Array|Array|String): input data to decompress.
   * - options (Object): zlib inflate options.
   *
   * Decompress `data` with inflate/ungzip and `options`. Autodetect
   * format via wrapper header by default. That's why we don't provide
   * separate `ungzip` method.
   *
   * Supported options are:
   *
   * - windowBits
   *
   * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
   * for more information.
   *
   * Sugar (options):
   *
   * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
   *   negative windowBits implicitly.
   * - `to` (String) - if equal to 'string', then result will be converted
   *   from utf8 to utf16 (javascript) string. When string output requested,
   *   chunk length can differ from `chunkSize`, depending on content.
   *
   *
   * ##### Example:
   *
   * ```javascript
   * var pako = require('pako')
   *   , input = pako.deflate([1,2,3,4,5,6,7,8,9])
   *   , output;
   *
   * try {
   *   output = pako.inflate(input);
   * } catch (err)
   *   console.log(err);
   * }
   * ```
   **/
  function inflate(input, options) {
    var inflator = new Inflate(options);

    inflator.push(input, true);

    // That will never happens, if you don't cheat with options :)
    if (inflator.err) { throw inflator.msg || messages[inflator.err]; }

    return inflator.result;
  }


  /**
   * inflateRaw(data[, options]) -> Uint8Array|Array|String
   * - data (Uint8Array|Array|String): input data to decompress.
   * - options (Object): zlib inflate options.
   *
   * The same as [[inflate]], but creates raw data, without wrapper
   * (header and adler32 crc).
   **/
  function inflateRaw(input, options) {
    options = options || {};
    options.raw = true;
    return inflate(input, options);
  }


  /**
   * ungzip(data[, options]) -> Uint8Array|Array|String
   * - data (Uint8Array|Array|String): input data to decompress.
   * - options (Object): zlib inflate options.
   *
   * Just shortcut to [[inflate]], because it autodetects format
   * by header.content. Done for convenience.
   **/


  var Inflate_1 = Inflate;
  var inflate_2 = inflate;
  var inflateRaw_1 = inflateRaw;
  var ungzip  = inflate;

  var inflate_1 = {
  	Inflate: Inflate_1,
  	inflate: inflate_2,
  	inflateRaw: inflateRaw_1,
  	ungzip: ungzip
  };

  /**
   * A view model which exposes a {@link Clock} for user interfaces.
   * @alias ClockViewModel
   * @constructor
   *
   * @param {Clock} [clock] The clock object wrapped by this view model, if undefined a new instance will be created.
   *
   * @see Clock
   */
  function ClockViewModel(clock) {
    if (!defined(clock)) {
      clock = new Clock();
    }
    this._clock = clock;

    this._eventHelper = new EventHelper();
    this._eventHelper.add(clock.onTick, this.synchronize, this);

    /**
     * Gets the current system time.
     * This property is observable.
     * @type {JulianDate}
     */
    this.systemTime = knockout.observable(JulianDate.now());
    this.systemTime.equalityComparer = JulianDate.equals;

    /**
     * Gets or sets the start time of the clock.
     * See {@link Clock#startTime}.
     * This property is observable.
     * @type {JulianDate}
     */
    this.startTime = knockout.observable(clock.startTime);
    this.startTime.equalityComparer = JulianDate.equals;
    this.startTime.subscribe(function (value) {
      clock.startTime = value;
      this.synchronize();
    }, this);

    /**
     * Gets or sets the stop time of the clock.
     * See {@link Clock#stopTime}.
     * This property is observable.
     * @type {JulianDate}
     */
    this.stopTime = knockout.observable(clock.stopTime);
    this.stopTime.equalityComparer = JulianDate.equals;
    this.stopTime.subscribe(function (value) {
      clock.stopTime = value;
      this.synchronize();
    }, this);

    /**
     * Gets or sets the current time.
     * See {@link Clock#currentTime}.
     * This property is observable.
     * @type {JulianDate}
     */
    this.currentTime = knockout.observable(clock.currentTime);
    this.currentTime.equalityComparer = JulianDate.equals;
    this.currentTime.subscribe(function (value) {
      clock.currentTime = value;
      this.synchronize();
    }, this);

    /**
     * Gets or sets the clock multiplier.
     * See {@link Clock#multiplier}.
     * This property is observable.
     * @type {Number}
     */
    this.multiplier = knockout.observable(clock.multiplier);
    this.multiplier.subscribe(function (value) {
      clock.multiplier = value;
      this.synchronize();
    }, this);

    /**
     * Gets or sets the clock step setting.
     * See {@link Clock#clockStep}.
     * This property is observable.
     * @type {ClockStep}
     */
    this.clockStep = knockout.observable(clock.clockStep);
    this.clockStep.subscribe(function (value) {
      clock.clockStep = value;
      this.synchronize();
    }, this);

    /**
     * Gets or sets the clock range setting.
     * See {@link Clock#clockRange}.
     * This property is observable.
     * @type {ClockRange}
     */
    this.clockRange = knockout.observable(clock.clockRange);
    this.clockRange.subscribe(function (value) {
      clock.clockRange = value;
      this.synchronize();
    }, this);

    /**
     * Gets or sets whether the clock can animate.
     * See {@link Clock#canAnimate}.
     * This property is observable.
     * @type {Boolean}
     */
    this.canAnimate = knockout.observable(clock.canAnimate);
    this.canAnimate.subscribe(function (value) {
      clock.canAnimate = value;
      this.synchronize();
    }, this);

    /**
     * Gets or sets whether the clock should animate.
     * See {@link Clock#shouldAnimate}.
     * This property is observable.
     * @type {Boolean}
     */
    this.shouldAnimate = knockout.observable(clock.shouldAnimate);
    this.shouldAnimate.subscribe(function (value) {
      clock.shouldAnimate = value;
      this.synchronize();
    }, this);

    knockout.track(this, [
      "systemTime",
      "startTime",
      "stopTime",
      "currentTime",
      "multiplier",
      "clockStep",
      "clockRange",
      "canAnimate",
      "shouldAnimate",
    ]);
  }

  Object.defineProperties(ClockViewModel.prototype, {
    /**
     * Gets the underlying Clock.
     * @memberof ClockViewModel.prototype
     * @type {Clock}
     */
    clock: {
      get: function () {
        return this._clock;
      },
    },
  });

  /**
   * Updates the view model with the contents of the underlying clock.
   * Can be called to force an update of the viewModel if the underlying
   * clock has changed and <code>Clock.tick</code> has not yet been called.
   */
  ClockViewModel.prototype.synchronize = function () {
    const clock = this._clock;

    this.systemTime = JulianDate.now();
    this.startTime = clock.startTime;
    this.stopTime = clock.stopTime;
    this.currentTime = clock.currentTime;
    this.multiplier = clock.multiplier;
    this.clockStep = clock.clockStep;
    this.clockRange = clock.clockRange;
    this.canAnimate = clock.canAnimate;
    this.shouldAnimate = clock.shouldAnimate;
  };

  /**
   * @returns {Boolean} true if the object has been destroyed, false otherwise.
   */
  ClockViewModel.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the view model.  Should be called to
   * properly clean up the view model when it is no longer needed.
   */
  ClockViewModel.prototype.destroy = function () {
    this._eventHelper.removeAll();

    destroyObject(this);
  };

  /**
   * A Command is a function with an extra <code>canExecute</code> observable property to determine
   * whether the command can be executed.  When executed, a Command function will check the
   * value of <code>canExecute</code> and throw if false.
   *
   * This type describes an interface and is not intended to be instantiated directly.
   * See {@link createCommand} to create a command from a function.
   *
   * @alias Command
   * @constructor
   */
  function Command() {
    /**
     * Gets whether this command can currently be executed.  This property is observable.
     * @type {Boolean}
     * @default undefined
     */
    this.canExecute = undefined;

    /**
     * Gets an event which is raised before the command executes, the event
     * is raised with an object containing two properties: a <code>cancel</code> property,
     * which if set to false by the listener will prevent the command from being executed, and
     * an <code>args</code> property, which is the array of arguments being passed to the command.
     * @type {Event}
     * @default undefined
     */
    this.beforeExecute = undefined;

    /**
     * Gets an event which is raised after the command executes, the event
     * is raised with the return value of the command as its only parameter.
     * @type {Event}
     * @default undefined
     */
    this.afterExecute = undefined;

    DeveloperError.throwInstantiationError();
  }

  /**
   * A static class with helper functions used by the CesiumInspector and Cesium3DTilesInspector
   * @private
   */
  const InspectorShared = {};

  /**
   * Creates a checkbox component
   * @param {String} labelText The text to display in the checkbox label
   * @param {String} checkedBinding The name of the variable used for checked binding
   * @param {String} [enableBinding] The name of the variable used for enable binding
   * @return {Element}
   */
  InspectorShared.createCheckbox = function (
    labelText,
    checkedBinding,
    enableBinding
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("labelText", labelText);
    Check.typeOf.string("checkedBinding", checkedBinding);
    //>>includeEnd('debug');
    const checkboxContainer = document.createElement("div");
    const checkboxLabel = document.createElement("label");
    const checkboxInput = document.createElement("input");
    checkboxInput.type = "checkbox";

    let binding = `checked: ${checkedBinding}`;
    if (defined(enableBinding)) {
      binding += `, enable: ${enableBinding}`;
    }
    checkboxInput.setAttribute("data-bind", binding);
    checkboxLabel.appendChild(checkboxInput);
    checkboxLabel.appendChild(document.createTextNode(labelText));
    checkboxContainer.appendChild(checkboxLabel);
    return checkboxContainer;
  };

  /**
   * Creates a section element
   * @param {Element} panel The parent element
   * @param {String} headerText The text to display at the top of the section
   * @param {String} sectionVisibleBinding The name of the variable used for visible binding
   * @param {String} toggleSectionVisibilityBinding The name of the function used to toggle visibility
   * @return {Element}
   */
  InspectorShared.createSection = function (
    panel,
    headerText,
    sectionVisibleBinding,
    toggleSectionVisibilityBinding
  ) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("panel", panel);
    Check.typeOf.string("headerText", headerText);
    Check.typeOf.string("sectionVisibleBinding", sectionVisibleBinding);
    Check.typeOf.string(
      "toggleSectionVisibilityBinding",
      toggleSectionVisibilityBinding
    );
    //>>includeEnd('debug');
    const section = document.createElement("div");
    section.className = "cesium-cesiumInspector-section";
    section.setAttribute(
      "data-bind",
      `css: { "cesium-cesiumInspector-section-collapsed": !${sectionVisibleBinding} }`
    );
    panel.appendChild(section);

    const sectionHeader = document.createElement("h3");
    sectionHeader.className = "cesium-cesiumInspector-sectionHeader";
    sectionHeader.appendChild(document.createTextNode(headerText));
    sectionHeader.setAttribute(
      "data-bind",
      `click: ${toggleSectionVisibilityBinding}`
    );
    section.appendChild(sectionHeader);

    const sectionContent = document.createElement("div");
    sectionContent.className = "cesium-cesiumInspector-sectionContent";
    section.appendChild(sectionContent);
    return sectionContent;
  };

  /**
   * A view model which exposes the properties of a toggle button.
   * @alias ToggleButtonViewModel
   * @constructor
   *
   * @param {Command} command The command which will be executed when the button is toggled.
   * @param {Object} [options] Object with the following properties:
   * @param {Boolean} [options.toggled=false] A boolean indicating whether the button should be initially toggled.
   * @param {String} [options.tooltip=''] A string containing the button's tooltip.
   */
  function ToggleButtonViewModel(command, options) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(command)) {
      throw new DeveloperError("command is required.");
    }
    //>>includeEnd('debug');

    this._command = command;

    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    /**
     * Gets or sets whether the button is currently toggled.  This property is observable.
     * @type {Boolean}
     * @default false
     */
    this.toggled = defaultValue(options.toggled, false);

    /**
     * Gets or sets the button's tooltip.  This property is observable.
     * @type {String}
     * @default ''
     */
    this.tooltip = defaultValue(options.tooltip, "");

    knockout.track(this, ["toggled", "tooltip"]);
  }

  Object.defineProperties(ToggleButtonViewModel.prototype, {
    /**
     * Gets the command which will be executed when the button is toggled.
     * @memberof ToggleButtonViewModel.prototype
     * @type {Command}
     */
    command: {
      get: function () {
        return this._command;
      },
    },
  });

  /**
   * Create a Command from a given function, for use with ViewModels.
   *
   * A Command is a function with an extra <code>canExecute</code> observable property to determine
   * whether the command can be executed.  When executed, a Command function will check the
   * value of <code>canExecute</code> and throw if false.  It also provides events for when
   * a command has been or is about to be executed.
   *
   * @function
   *
   * @param {Function} func The function to execute.
   * @param {Boolean} [canExecute=true] A boolean indicating whether the function can currently be executed.
   */
  function createCommand(func, canExecute) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(func)) {
      throw new DeveloperError("func is required.");
    }
    //>>includeEnd('debug');

    canExecute = defaultValue(canExecute, true);

    const beforeExecute = new Event();
    const afterExecute = new Event();

    function command() {
      //>>includeStart('debug', pragmas.debug);
      if (!command.canExecute) {
        throw new DeveloperError("Cannot execute command, canExecute is false.");
      }
      //>>includeEnd('debug');

      const commandInfo = {
        args: arguments,
        cancel: false,
      };

      let result;
      beforeExecute.raiseEvent(commandInfo);
      if (!commandInfo.cancel) {
        result = func.apply(null, arguments);
        afterExecute.raiseEvent(result);
      }
      return result;
    }

    command.canExecute = canExecute;
    knockout.track(command, ["canExecute"]);

    Object.defineProperties(command, {
      beforeExecute: {
        value: beforeExecute,
      },
      afterExecute: {
        value: afterExecute,
      },
    });

    return command;
  }

  /**
   * Subscribe to a Knockout observable ES5 property, and immediately fire
   * the callback with the current value of the property.
   *
   * @private
   *
   * @function subscribeAndEvaluate
   *
   * @param {Object} owner The object containing the observable property.
   * @param {String} observablePropertyName The name of the observable property.
   * @param {Function} callback The callback function.
   * @param {Object} [target] The value of this in the callback function.
   * @param {String} [event='change'] The name of the event to receive notification for.
   * @returns The subscription object from Knockout which can be used to dispose the subscription later.
   */
  function subscribeAndEvaluate(
    owner,
    observablePropertyName,
    callback,
    target,
    event
  ) {
    callback.call(target, owner[observablePropertyName]);
    return knockout
      .getObservable(owner, observablePropertyName)
      .subscribe(callback, target, event);
  }

  /**
   * An enum of the basic GLSL uniform types. These can be used with
   * {@link CustomShader} to declare user-defined uniforms.
   *
   * @enum {String}
   *
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  const UniformType = {
    /**
     * A single floating point value.
     *
     * @type {String}
     * @constant
     */
    FLOAT: "float",
    /**
     * A vector of 2 floating point values.
     *
     * @type {String}
     * @constant
     */
    VEC2: "vec2",
    /**
     * A vector of 3 floating point values.
     *
     * @type {String}
     * @constant
     */
    VEC3: "vec3",
    /**
     * A vector of 4 floating point values.
     *
     * @type {String}
     * @constant
     */
    VEC4: "vec4",
    /**
     * A single integer value
     *
     * @type {String}
     * @constant
     */
    INT: "int",
    /**
     * A vector of 2 integer values.
     *
     * @type {String}
     * @constant
     */
    INT_VEC2: "ivec2",
    /**
     * A vector of 3 integer values.
     *
     * @type {String}
     * @constant
     */
    INT_VEC3: "ivec3",
    /**
     * A vector of 4 integer values.
     *
     * @type {String}
     * @constant
     */
    INT_VEC4: "ivec4",
    /**
     * A single boolean value.
     *
     * @type {String}
     * @constant
     */
    BOOL: "bool",
    /**
     * A vector of 2 boolean values.
     *
     * @type {String}
     * @constant
     */
    BOOL_VEC2: "bvec2",
    /**
     * A vector of 3 boolean values.
     *
     * @type {String}
     * @constant
     */
    BOOL_VEC3: "bvec3",
    /**
     * A vector of 4 boolean values.
     *
     * @type {String}
     * @constant
     */
    BOOL_VEC4: "bvec4",
    /**
     * A 2x2 matrix of floating point values.
     *
     * @type {String}
     * @constant
     */
    MAT2: "mat2",
    /**
     * A 3x3 matrix of floating point values.
     *
     * @type {String}
     * @constant
     */
    MAT3: "mat2",
    /**
     * A 3x3 matrix of floating point values.
     *
     * @type {String}
     * @constant
     */
    MAT4: "mat4",
    /**
     * A 2D sampled texture.
     * @type {String}
     * @constant
     */
    SAMPLER_2D: "sampler2D",
    SAMPLER_CUBE: "samplerCube",
  };

  var UniformType$1 = Object.freeze(UniformType);

  /**
   * An object to manage loading textures
   *
   * @alias TextureManager
   * @constructor
   *
   * @private
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function TextureManager() {
    this._defaultTexture = undefined;
    this._textures = {};
    this._loadedImages = [];

    // Keep track of the last time update() was called to avoid
    // calling update() twice.
    this._lastUpdatedFrame = -1;
  }

  /**
   * Get one of the loaded textures
   * @param {String} textureId The unique ID of the texture loaded by {@link TextureManager#loadTexture2D}
   * @return {Texture} The texture or <code>undefined</code> if no texture exists
   */
  TextureManager.prototype.getTexture = function (textureId) {
    return this._textures[textureId];
  };

  function fetchTexture2D(textureManager, textureId, textureUniform) {
    textureUniform.resource
      .fetchImage()
      .then(function (image) {
        textureManager._loadedImages.push({
          id: textureId,
          image: image,
          textureUniform: textureUniform,
        });
      })
      .catch(function () {
        const texture = textureManager._textures[textureId];
        if (defined(texture) && texture !== textureManager._defaultTexture) {
          texture.destroy();
        }

        textureManager._textures[textureId] = textureManager._defaultTexture;
      });
  }

  /**
   * Load a texture 2D asynchronously. Note that {@link TextureManager#update}
   * must be called in the render loop to finish processing the textures.
   *
   * @param {String} textureId A unique ID to identify this texture.
   * @param {TextureUniform} textureUniform A description of the texture
   *
   * @private
   */
  TextureManager.prototype.loadTexture2D = function (textureId, textureUniform) {
    if (defined(textureUniform.typedArray)) {
      this._loadedImages.push({
        id: textureId,
        textureUniform: textureUniform,
      });
    } else {
      fetchTexture2D(this, textureId, textureUniform);
    }
  };

  function createTexture(textureManager, loadedImage, context) {
    const { id, textureUniform, image } = loadedImage;

    // If the context is WebGL1, and the sampler needs mipmaps or repeating
    // boundary conditions, the image may need to be resized first
    const texture = context.webgl2
      ? getTextureAndMips(textureUniform, image, context)
      : getWebGL1Texture(textureUniform, image, context);

    // Destroy the old texture once the new one is loaded for more seamless
    // transitions between values
    const oldTexture = textureManager._textures[id];
    if (defined(oldTexture) && oldTexture !== context.defaultTexture) {
      oldTexture.destroy();
    }
    textureManager._textures[id] = texture;
  }

  function getTextureAndMips(textureUniform, image, context) {
    const { typedArray, sampler } = textureUniform;

    const texture = defined(typedArray)
      ? getTextureFromTypedArray(textureUniform, context)
      : new Texture({ context, source: image, sampler });

    if (samplerRequiresMipmap(sampler)) texture.generateMipmap();

    return texture;
  }

  function getWebGL1Texture(textureUniform, image, context) {
    const { typedArray, sampler } = textureUniform;

    // WebGL1 requires power-of-two texture dimensions for mipmapping and REPEAT wrap modes
    const needMipmap = samplerRequiresMipmap(sampler);

    const samplerRepeats =
      sampler.wrapS === TextureWrap$1.REPEAT ||
      sampler.wrapS === TextureWrap$1.MIRRORED_REPEAT ||
      sampler.wrapT === TextureWrap$1.REPEAT ||
      sampler.wrapT === TextureWrap$1.MIRRORED_REPEAT;

    const { width, height } = defined(typedArray) ? textureUniform : image;
    const isPowerOfTwo = [width, height].every(CesiumMath.isPowerOfTwo);
    const requiresResize = (needMipmap || samplerRepeats) && !isPowerOfTwo;

    if (!requiresResize) {
      return getTextureAndMips(textureUniform, image, context);
    } else if (!defined(typedArray)) {
      const resizedImage = resizeImageToNextPowerOfTwo(image);
      return getTextureAndMips(textureUniform, resizedImage, context);
    } else if (textureUniform.pixelDatatype === PixelDatatype$1.UNSIGNED_BYTE) {
      const imageFromArray = getImageFromTypedArray(typedArray, width, height);
      const resizedImage = resizeImageToNextPowerOfTwo(imageFromArray);
      return getTextureAndMips({ sampler }, resizedImage, context);
    }

    // typedArray is non-power-of-two but can't be resized. Warn and return raw texture (no mipmaps)
    if (needMipmap) {
      console.warn(
        "Texture requires resizing for mipmaps but pixelDataType cannot be resized. The texture may be rendered incorrectly."
      );
    } else if (samplerRepeats) {
      console.warn(
        "Texture requires resizing for wrapping but pixelDataType cannot be resized. The texture may be rendered incorrectly."
      );
    }
    return getTextureFromTypedArray(textureUniform, context);
  }

  function samplerRequiresMipmap(sampler) {
    return [
      TextureMinificationFilter$1.NEAREST_MIPMAP_NEAREST,
      TextureMinificationFilter$1.NEAREST_MIPMAP_LINEAR,
      TextureMinificationFilter$1.LINEAR_MIPMAP_NEAREST,
      TextureMinificationFilter$1.LINEAR_MIPMAP_LINEAR,
    ].includes(sampler.minificationFilter);
  }

  function getTextureFromTypedArray(textureUniform, context) {
    const {
      pixelFormat,
      pixelDatatype,
      width,
      height,
      typedArray: arrayBufferView,
      sampler,
    } = textureUniform;

    return new Texture({
      context,
      pixelFormat,
      pixelDatatype,
      source: { arrayBufferView, width, height },
      sampler,
      flipY: false,
    });
  }

  TextureManager.prototype.update = function (frameState) {
    // update only needs to be called once a frame.
    if (frameState.frameNumber === this._lastUpdatedFrame) {
      return;
    }
    this._lastUpdatedFrame = frameState.frameNumber;

    const context = frameState.context;
    this._defaultTexture = context.defaultTexture;

    // If any images were loaded since the last frame, create Textures
    // for them and store in the uniform dictionary
    const loadedImages = this._loadedImages;
    for (let i = 0; i < loadedImages.length; i++) {
      const loadedImage = loadedImages[i];
      createTexture(this, loadedImage, context);
    }
    loadedImages.length = 0;
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} True if this object was destroyed; otherwise, false.
   *
   * @see TextureManager#destroy
   * @private
   */
  TextureManager.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @example
   * textureManager = textureManager && textureManager.destroy();
   *
   * @see TextureManager#isDestroyed
   * @private
   */
  TextureManager.prototype.destroy = function () {
    const textures = this._textures;
    for (const texture in textures) {
      if (textures.hasOwnProperty(texture)) {
        const instance = textures[texture];
        if (instance !== this._defaultTexture) {
          instance.destroy();
        }
      }
    }
    return destroyObject(this);
  };

  /**
   * An object describing a uniform, its type, and an initial value
   *
   * @typedef {Object} UniformSpecifier
   * @property {UniformType} type The Glsl type of the uniform.
   * @property {Boolean|Number|Cartesian2|Cartesian3|Cartesian4|Matrix2|Matrix3|Matrix4|TextureUniform} value The initial value of the uniform
   *
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */

  /**
   * A set of variables parsed from the user-defined shader code. These can be
   * used for optimizations when generating the overall shader. Though they are
   * represented as JS objects, the intended use is like a set, so only the
   * existence of keys matter. The values will always be <code>true</code> if
   * defined. This data structure is used because:
   * <ul>
   *   <li>We cannot yet use ES6 Set objects</li>
   *   <li>Using a dictionary automatically de-duplicates variable names</li>
   *   <li>Queries such as <code>variableSet.hasOwnProperty("position")</code> are straightforward</li>
   * </ul>
   * @typedef {Object<String, Boolean>} VariableSet
   * @private
   */

  /**
   * Variable sets parsed from the user-defined vertex shader text.
   * @typedef {Object} VertexVariableSets
   * @property {VariableSet} attributeSet A set of all unique attributes used in the vertex shader via the <code>vsInput.attributes</code> struct.
   * @property {VariableSet} featureIdSet A set of all unique feature ID sets used in the vertex shader via the <code>vsInput.featureIds</code> struct.
   * @property {VariableSet} metadataSet A set of all unique metadata properties used in the vertex shader via the <code>vsInput.metadata</code> struct.
   * @private
   */

  /**
   * Variable sets parsed from the user-defined fragment shader text.
   * @typedef {Object} FragmentVariableSets
   * @property {VariableSet} attributeSet A set of all unique attributes used in the fragment shader via the <code>fsInput.attributes</code> struct
   * @property {VariableSet} featureIdSet A set of all unique feature ID sets used in the fragment shader via the <code>fsInput.featureIds</code> struct.
   * @property {VariableSet} metadataSet A set of all unique metadata properties used in the fragment shader via the <code>fsInput.metadata</code> struct.
   * @property {VariableSet} materialSet A set of all material variables such as diffuse, specular or alpha that are used in the fragment shader via the <code>material</code> struct.
   * @private
   */

  /**
   * A user defined GLSL shader used with {@link ModelExperimental} as well
   * as {@link Cesium3DTileset}.
   * <p>
   * If texture uniforms are used, additional resource management must be done:
   * </p>
   * <ul>
   *   <li>
   *      The <code>update</code> function must be called each frame. When a
   *      custom shader is passed to a {@link ModelExperimental} or a
   *      {@link Cesium3DTileset}, this step is handled automaticaly
   *   </li>
   *   <li>
   *      {@link CustomShader#destroy} must be called when the custom shader is
   *      no longer needed to clean up GPU resources properly. The application
   *      is responsible for calling this method.
   *   </li>
   * </ul>
   * <p>
   * To enable the use of {@link ModelExperimental} in {@link Cesium3DTileset}, set {@link ExperimentalFeatures.enableModelExperimental} to <code>true</code> or tileset.enableModelExperimental to <code>true</code>.
   * </p>
   * <p>
   * See the {@link https://github.com/CesiumGS/cesium/tree/main/Documentation/CustomShaderGuide|Custom Shader Guide} for more detailed documentation.
   * </p>
   *
   * @param {Object} options An object with the following options
   * @param {CustomShaderMode} [options.mode=CustomShaderMode.MODIFY_MATERIAL] The custom shader mode, which determines how the custom shader code is inserted into the fragment shader.
   * @param {LightingModel} [options.lightingModel] The lighting model (e.g. PBR or unlit). If present, this overrides the default lighting for the model.
   * @param {Boolean} [options.isTranslucent=false] If set, the model will be rendered as translucent. This overrides the default settings for the model.
   * @param {Object.<String, UniformSpecifier>} [options.uniforms] A dictionary for user-defined uniforms. The key is the uniform name that will appear in the GLSL code. The value is an object that describes the uniform type and initial value
   * @param {Object.<String, VaryingType>} [options.varyings] A dictionary for declaring additional GLSL varyings used in the shader. The key is the varying name that will appear in the GLSL code. The value is the data type of the varying. For each varying, the declaration will be added to the top of the shader automatically. The caller is responsible for assigning a value in the vertex shader and using the value in the fragment shader.
   * @param {String} [options.vertexShaderText] The custom vertex shader as a string of GLSL code. It must include a GLSL function called vertexMain. See the example for the expected signature. If not specified, the custom vertex shader step will be skipped in the computed vertex shader.
   * @param {String} [options.fragmentShaderText] The custom fragment shader as a string of GLSL code. It must include a GLSL function called fragmentMain. See the example for the expected signature. If not specified, the custom fragment shader step will be skipped in the computed fragment shader.
   *
   * @alias CustomShader
   * @constructor
   *
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   *
   * @example
   * const customShader = new CustomShader({
   *   uniforms: {
   *     u_colorIndex: {
   *       type: Cesium.UniformType.FLOAT,
   *       value: 1.0
   *     },
   *     u_normalMap: {
   *       type: Cesium.UniformType.SAMPLER_2D,
   *       value: new Cesium.TextureUniform({
   *         url: "http://example.com/normal.png"
   *       })
   *     }
   *   },
   *   varyings: {
   *     v_selectedColor: Cesium.VaryingType.VEC3
   *   },
   *   vertexShaderText: `
   *   void vertexMain(VertexInput vsInput, inout czm_modelVertexOutput vsOutput) {
   *     v_selectedColor = mix(vsInput.attributes.color_0, vsInput.attributes.color_1, u_colorIndex);
   *     vsOutput.positionMC += 0.1 * vsInput.attributes.normal;
   *   }
   *   `,
   *   fragmentShaderText: `
   *   void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
   *     material.normal = texture2D(u_normalMap, fsInput.attributes.texCoord_0);
   *     material.diffuse = v_selectedColor;
   *   }
   *   `
   * });
   */
  function CustomShader(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    /**
     * A value determining how the custom shader interacts with the overall
     * fragment shader. This is used by {@link CustomShaderPipelineStage}
     *
     * @type {CustomShaderMode}
     * @readonly
     */
    this.mode = defaultValue(options.mode, CustomShaderMode$1.MODIFY_MATERIAL);
    /**
     * The lighting model to use when using the custom shader.
     * This is used by {@link CustomShaderPipelineStage}
     *
     * @type {LightingModel}
     * @readonly
     */
    this.lightingModel = options.lightingModel;
    /**
     * Additional uniforms as declared by the user.
     *
     * @type {Object.<String, UniformSpecifier>}
     * @readonly
     */
    this.uniforms = defaultValue(options.uniforms, defaultValue.EMPTY_OBJECT);
    /**
     * Additional varyings as declared by the user.
     * This is used by {@link CustomShaderPipelineStage}
     *
     * @type {Object.<String, VaryingType>}
     * @readonly
     */
    this.varyings = defaultValue(options.varyings, defaultValue.EMPTY_OBJECT);
    /**
     * The user-defined GLSL code for the vertex shader
     *
     * @type {String}
     * @readonly
     */
    this.vertexShaderText = options.vertexShaderText;
    /**
     * The user-defined GLSL code for the fragment shader
     *
     * @type {String}
     * @readonly
     */
    this.fragmentShaderText = options.fragmentShaderText;
    /**
     * Whether the shader should be rendered as translucent
     *
     * @type {Boolean}
     * @readonly
     */
    this.isTranslucent = defaultValue(options.isTranslucent, false);

    /**
     * texture uniforms require some asynchronous processing. This is delegated
     * to a texture manager.
     *
     * @type {TextureManager}
     * @readonly
     * @private
     */
    this._textureManager = new TextureManager();
    /**
     * The default texture (from the {@link Context}) to use while textures
     * are loading
     *
     * @type {Texture}
     * @readonly
     * @private
     */
    this._defaultTexture = undefined;
    /**
     * The map of uniform names to a function that returns a value. This map
     * is combined with the overall uniform map used by the {@link DrawCommand}
     *
     * @type {Object.<String, Function>}
     * @readonly
     * @private
     */
    this.uniformMap = buildUniformMap(this);

    /**
     * A collection of variables used in <code>vertexShaderText</code>. This
     * is used only for optimizations in {@link CustomShaderPipelineStage}.
     * @type {VertexVariableSets}
     * @private
     */
    this.usedVariablesVertex = {
      attributeSet: {},
      featureIdSet: {},
      metadataSet: {},
    };
    /**
     * A collection of variables used in <code>fragmentShaderText</code>. This
     * is used only for optimizations in {@link CustomShaderPipelineStage}.
     * @type {FragmentVariableSets}
     * @private
     */
    this.usedVariablesFragment = {
      attributeSet: {},
      featureIdSet: {},
      metadataSet: {},
      materialSet: {},
    };

    findUsedVariables(this);
    validateBuiltinVariables(this);
  }

  function buildUniformMap(customShader) {
    const uniforms = customShader.uniforms;
    const uniformMap = {};
    for (const uniformName in uniforms) {
      if (uniforms.hasOwnProperty(uniformName)) {
        const uniform = uniforms[uniformName];
        const type = uniform.type;
        //>>includeStart('debug', pragmas.debug);
        if (type === UniformType$1.SAMPLER_CUBE) {
          throw new DeveloperError(
            "CustomShader does not support samplerCube uniforms"
          );
        }
        //>>includeEnd('debug');

        if (type === UniformType$1.SAMPLER_2D) {
          customShader._textureManager.loadTexture2D(uniformName, uniform.value);
          uniformMap[uniformName] = createUniformTexture2DFunction(
            customShader,
            uniformName
          );
        } else {
          uniformMap[uniformName] = createUniformFunction(
            customShader,
            uniformName
          );
        }
      }
    }
    return uniformMap;
  }

  function createUniformTexture2DFunction(customShader, uniformName) {
    return function () {
      return defaultValue(
        customShader._textureManager.getTexture(uniformName),
        customShader._defaultTexture
      );
    };
  }

  function createUniformFunction(customShader, uniformName) {
    return function () {
      return customShader.uniforms[uniformName].value;
    };
  }

  function getVariables(shaderText, regex, outputSet) {
    let match;
    while ((match = regex.exec(shaderText)) !== null) {
      const variableName = match[1];

      // Using a dictionary like a set. The value doesn't
      // matter, as this will only be used for queries such as
      // if (set.hasOwnProperty(variableName)) { ... }
      outputSet[variableName] = true;
    }
  }

  function findUsedVariables(customShader) {
    const attributeRegex = /[vf]sInput\.attributes\.(\w+)/g;
    const featureIdRegex = /[vf]sInput\.featureIds\.(\w+)/g;
    const metadataRegex = /[vf]sInput\.metadata.(\w+)/g;
    let attributeSet;

    const vertexShaderText = customShader.vertexShaderText;
    if (defined(vertexShaderText)) {
      attributeSet = customShader.usedVariablesVertex.attributeSet;
      getVariables(vertexShaderText, attributeRegex, attributeSet);

      attributeSet = customShader.usedVariablesVertex.featureIdSet;
      getVariables(vertexShaderText, featureIdRegex, attributeSet);

      attributeSet = customShader.usedVariablesVertex.metadataSet;
      getVariables(vertexShaderText, metadataRegex, attributeSet);
    }

    const fragmentShaderText = customShader.fragmentShaderText;
    if (defined(fragmentShaderText)) {
      attributeSet = customShader.usedVariablesFragment.attributeSet;
      getVariables(fragmentShaderText, attributeRegex, attributeSet);

      attributeSet = customShader.usedVariablesFragment.featureIdSet;
      getVariables(fragmentShaderText, featureIdRegex, attributeSet);

      attributeSet = customShader.usedVariablesFragment.metadataSet;
      getVariables(fragmentShaderText, metadataRegex, attributeSet);

      const materialRegex = /material\.(\w+)/g;
      const materialSet = customShader.usedVariablesFragment.materialSet;
      getVariables(fragmentShaderText, materialRegex, materialSet);
    }
  }

  function expandCoordinateAbbreviations(variableName) {
    const modelCoordinatesRegex = /^.*MC$/;
    const worldCoordinatesRegex = /^.*WC$/;
    const eyeCoordinatesRegex = /^.*EC$/;

    if (modelCoordinatesRegex.test(variableName)) {
      return `${variableName} (model coordinates)`;
    }

    if (worldCoordinatesRegex.test(variableName)) {
      return `${variableName} (Cartesian world coordinates)`;
    }

    if (eyeCoordinatesRegex.test(variableName)) {
      return `${variableName} (eye coordinates)`;
    }

    return variableName;
  }

  function validateVariableUsage(
    variableSet,
    incorrectVariable,
    correctVariable,
    vertexOrFragment
  ) {
    if (variableSet.hasOwnProperty(incorrectVariable)) {
      const message = `${expandCoordinateAbbreviations(
      incorrectVariable
    )} is not available in the ${vertexOrFragment} shader. Did you mean ${expandCoordinateAbbreviations(
      correctVariable
    )} instead?`;
      throw new DeveloperError(message);
    }
  }

  function validateBuiltinVariables(customShader) {
    const attributesVS = customShader.usedVariablesVertex.attributeSet;

    // names without MC/WC/EC are ambiguous
    validateVariableUsage(attributesVS, "position", "positionMC", "vertex");
    validateVariableUsage(attributesVS, "normal", "normalMC", "vertex");
    validateVariableUsage(attributesVS, "tangent", "tangentMC", "vertex");
    validateVariableUsage(attributesVS, "bitangent", "bitangentMC", "vertex");

    // world and eye coordinate positions are only available in the fragment shader.
    validateVariableUsage(attributesVS, "positionWC", "positionMC", "vertex");
    validateVariableUsage(attributesVS, "positionEC", "positionMC", "vertex");

    // normal, tangent and bitangent are in model coordinates in the vertex shader
    validateVariableUsage(attributesVS, "normalEC", "normalMC", "vertex");
    validateVariableUsage(attributesVS, "tangentEC", "tangentMC", "vertex");
    validateVariableUsage(attributesVS, "bitangentEC", "bitangentMC", "vertex");

    const attributesFS = customShader.usedVariablesFragment.attributeSet;

    // names without MC/WC/EC are ambiguous
    validateVariableUsage(attributesFS, "position", "positionEC", "fragment");
    validateVariableUsage(attributesFS, "normal", "normalEC", "fragment");
    validateVariableUsage(attributesFS, "tangent", "tangentEC", "fragment");
    validateVariableUsage(attributesFS, "bitangent", "bitangentEC", "fragment");

    // normal, tangent, and bitangent are in eye coordinates in the fragment
    // shader.
    validateVariableUsage(attributesFS, "normalMC", "normalEC", "fragment");
    validateVariableUsage(attributesFS, "tangentMC", "tangentEC", "fragment");
    validateVariableUsage(attributesFS, "bitangentMC", "bitangentEC", "fragment");
  }

  /**
   * Update the value of a uniform declared in the shader
   * @param {String} uniformName The GLSL name of the uniform. This must match one of the uniforms declared in the constructor
   * @param {Boolean|Number|Cartesian2|Cartesian3|Cartesian4|Matrix2|Matrix3|Matrix4|String|Resource} value The new value of the uniform.
   */
  CustomShader.prototype.setUniform = function (uniformName, value) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.string("uniformName", uniformName);
    Check.defined("value", value);
    if (!defined(this.uniforms[uniformName])) {
      throw new DeveloperError(
        `Uniform ${uniformName} must be declared in the CustomShader constructor.`
      );
    }
    //>>includeEnd('debug');
    const uniform = this.uniforms[uniformName];
    if (uniform.type === UniformType$1.SAMPLER_2D) {
      // Textures are loaded asynchronously
      this._textureManager.loadTexture2D(uniformName, value);
    } else if (defined(value.clone)) {
      // clone Cartesian and Matrix types.
      uniform.value = value.clone(uniform.value);
    } else {
      uniform.value = value;
    }
  };

  CustomShader.prototype.update = function (frameState) {
    this._defaultTexture = frameState.context.defaultTexture;
    this._textureManager.update(frameState);
  };

  /**
   * Returns true if this object was destroyed; otherwise, false.
   * <br /><br />
   * If this object was destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
   *
   * @returns {Boolean} True if this object was destroyed; otherwise, false.
   *
   * @see CustomShader#destroy
   * @private
   */
  CustomShader.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
   * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
   * <br /><br />
   * Once an object is destroyed, it should not be used; calling any function other than
   * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
   * assign the return value (<code>undefined</code>) to the object as done in the example.
   *
   * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
   *
   * @example
   * customShader = customShader && customShader.destroy();
   *
   * @see CustomShader#isDestroyed
   * @private
   */
  CustomShader.prototype.destroy = function () {
    this._textureManager = this._textureManager && this._textureManager.destroy();
    destroyObject(this);
  };

  /**
   * A simple struct that serves as a value of a <code>sampler2D</code>-valued
   * uniform. This is used with {@link CustomShader} and {@link TextureManager}
   *
   * @param {Object} options An object with the following properties:
   * @param {Uint8Array} [options.typedArray] A typed array storing the contents of a texture. Values are stored in row-major order. Since WebGL uses a y-up convention for textures, rows are listed from bottom to top.
   * @param {Number} [options.width] The width of the image. Required when options.typedArray is present
   * @param {Number} [options.height] The height of the image. Required when options.typedArray is present.
   * @param {String|Resource} [options.url] A URL string or resource pointing to a texture image.
   * @param {Boolean} [options.repeat=true] When defined, the texture sampler will be set to wrap in both directions
   * @param {PixelFormat} [options.pixelFormat=PixelFormat.RGBA] When options.typedArray is defined, this is used to determine the pixel format of the texture
   * @param {PixelDatatype} [options.pixelDatatype=PixelDatatype.UNSIGNED_BYTE] When options.typedArray is defined, this is the data type of pixel values in the typed array.
   * @param {TextureMinificationFilter} [options.minificationFilter=TextureMinificationFilter.LINEAR] The minification filter of the texture sampler.
   * @param {TextureMagnificationFilter} [options.magnificationFilter=TextureMagnificationFilter.LINEAR] The magnification filter of the texture sampler.
   * @param {Number} [options.maximumAnisotropy=1.0] The maximum anisotropy of the texture sampler
   *
   * @alias TextureUniform
   * @constructor
   *
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  function TextureUniform(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    //>>includeStart('debug', pragmas.debug);
    const hasTypedArray = defined(options.typedArray);
    const hasUrl = defined(options.url);
    if (hasTypedArray === hasUrl) {
      throw new DeveloperError(
        "exactly one of options.typedArray, options.url must be defined"
      );
    }
    if (hasTypedArray && (!defined(options.width) || !defined(options.height))) {
      throw new DeveloperError(
        "options.width and options.height are required when options.typedArray is defined"
      );
    }
    //>>includeEnd('debug');

    this.typedArray = options.typedArray;
    this.width = options.width;
    this.height = options.height;
    this.pixelFormat = defaultValue(options.pixelFormat, PixelFormat$1.RGBA);
    this.pixelDatatype = defaultValue(
      options.pixelDatatype,
      PixelDatatype$1.UNSIGNED_BYTE
    );

    let resource = options.url;
    if (typeof resource === "string") {
      resource = Resource.createIfNeeded(resource);
    }
    this.resource = resource;

    const repeat = defaultValue(options.repeat, true);
    const wrap = repeat ? TextureWrap$1.REPEAT : TextureWrap$1.CLAMP_TO_EDGE;
    this.sampler = new Sampler({
      wrapS: wrap,
      wrapT: wrap,
      minificationFilter: options.minificationFilter,
      magnificationFilter: options.magnificationFilter,
      maximumAnisotropy: options.maximumAnisotropy,
    });
  }

  /**
   * An enum for the GLSL varying types. These can be used for declaring varyings
   * in {@link CustomShader}
   *
   * @enum {String}
   *
   * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
   */
  const VaryingType = {
    /**
     * A single floating point value.
     *
     * @type {String}
     * @constant
     */
    FLOAT: "float",
    /**
     * A vector of 2 floating point values.
     *
     * @type {String}
     * @constant
     */
    VEC2: "vec2",
    /**
     * A vector of 3 floating point values.
     *
     * @type {String}
     * @constant
     */
    VEC3: "vec3",
    /**
     * A vector of 4 floating point values.
     *
     * @type {String}
     * @constant
     */
    VEC4: "vec4",
    /**
     * A 2x2 matrix of floating point values.
     *
     * @type {String}
     * @constant
     */
    MAT2: "mat2",
    /**
     * A 3x3 matrix of floating point values.
     *
     * @type {String}
     * @constant
     */
    MAT3: "mat2",
    /**
     * A 3x3 matrix of floating point values.
     *
     * @type {String}
     * @constant
     */
    MAT4: "mat4",
  };

  var VaryingType$1 = Object.freeze(VaryingType);

  //This file is automatically rebuilt by the Cesium build process.
  var DepthViewPacked = "uniform sampler2D u_depthTexture;\n\
varying vec2 v_textureCoordinates;\n\
void main()\n\
{\n\
float z_window = czm_unpackDepth(texture2D(u_depthTexture, v_textureCoordinates));\n\
z_window = czm_reverseLogDepth(z_window);\n\
float n_range = czm_depthRange.near;\n\
float f_range = czm_depthRange.far;\n\
float z_ndc = (2.0 * z_window - n_range - f_range) / (f_range - n_range);\n\
float scale = pow(z_ndc * 0.5 + 0.5, 8.0);\n\
gl_FragColor = vec4(mix(vec3(0.0), vec3(1.0), scale), 1.0);\n\
}\n\
";

  const svgNS = "http://www.w3.org/2000/svg";
  const xlinkNS = "http://www.w3.org/1999/xlink";

  let widgetForDrag;

  const gradientEnabledColor0 = Color.fromCssColorString(
    "rgba(247,250,255,0.384)"
  );
  const gradientEnabledColor1 = Color.fromCssColorString(
    "rgba(143,191,255,0.216)"
  );
  const gradientEnabledColor2 = Color.fromCssColorString(
    "rgba(153,197,255,0.098)"
  );
  const gradientEnabledColor3 = Color.fromCssColorString(
    "rgba(255,255,255,0.086)"
  );

  const gradientDisabledColor0 = Color.fromCssColorString(
    "rgba(255,255,255,0.267)"
  );
  const gradientDisabledColor1 = Color.fromCssColorString("rgba(255,255,255,0)");

  const gradientKnobColor = Color.fromCssColorString("rgba(66,67,68,0.3)");
  const gradientPointerColor = Color.fromCssColorString("rgba(0,0,0,0.5)");

  function getElementColor(element) {
    return Color.fromCssColorString(
      window.getComputedStyle(element).getPropertyValue("color")
    );
  }

  const svgIconsById = {
    animation_pathReset: {
      tagName: "path",
      transform: "translate(16,16) scale(0.85) translate(-16,-16)",
      d:
        "M24.316,5.318,9.833,13.682,9.833,5.5,5.5,5.5,5.5,25.5,9.833,25.5,9.833,17.318,24.316,25.682z",
    },
    animation_pathPause: {
      tagName: "path",
      transform: "translate(16,16) scale(0.85) translate(-16,-16)",
      d: "M13,5.5,7.5,5.5,7.5,25.5,13,25.5zM24.5,5.5,19,5.5,19,25.5,24.5,25.5z",
    },
    animation_pathPlay: {
      tagName: "path",
      transform: "translate(16,16) scale(0.85) translate(-16,-16)",
      d: "M6.684,25.682L24.316,15.5L6.684,5.318V25.682z",
    },
    animation_pathPlayReverse: {
      tagName: "path",
      transform: "translate(16,16) scale(-0.85,0.85) translate(-16,-16)",
      d: "M6.684,25.682L24.316,15.5L6.684,5.318V25.682z",
    },
    animation_pathLoop: {
      tagName: "path",
      transform: "translate(16,16) scale(0.85) translate(-16,-16)",
      d:
        "M24.249,15.499c-0.009,4.832-3.918,8.741-8.75,8.75c-2.515,0-4.768-1.064-6.365-2.763l2.068-1.442l-7.901-3.703l0.744,8.694l2.193-1.529c2.244,2.594,5.562,4.242,9.26,4.242c6.767,0,12.249-5.482,12.249-12.249H24.249zM15.499,6.75c2.516,0,4.769,1.065,6.367,2.764l-2.068,1.443l7.901,3.701l-0.746-8.693l-2.192,1.529c-2.245-2.594-5.562-4.245-9.262-4.245C8.734,3.25,3.25,8.734,3.249,15.499H6.75C6.758,10.668,10.668,6.758,15.499,6.75z",
    },
    animation_pathClock: {
      tagName: "path",
      transform: "translate(16,16) scale(0.85) translate(-16,-15.5)",
      d:
        "M15.5,2.374C8.251,2.375,2.376,8.251,2.374,15.5C2.376,22.748,8.251,28.623,15.5,28.627c7.249-0.004,13.124-5.879,13.125-13.127C28.624,8.251,22.749,2.375,15.5,2.374zM15.5,25.623C9.909,25.615,5.385,21.09,5.375,15.5C5.385,9.909,9.909,5.384,15.5,5.374c5.59,0.01,10.115,4.535,10.124,10.125C25.615,21.09,21.091,25.615,15.5,25.623zM8.625,15.5c-0.001-0.552-0.448-0.999-1.001-1c-0.553,0-1,0.448-1,1c0,0.553,0.449,1,1,1C8.176,16.5,8.624,16.053,8.625,15.5zM8.179,18.572c-0.478,0.277-0.642,0.889-0.365,1.367c0.275,0.479,0.889,0.641,1.365,0.365c0.479-0.275,0.643-0.887,0.367-1.367C9.27,18.461,8.658,18.297,8.179,18.572zM9.18,10.696c-0.479-0.276-1.09-0.112-1.366,0.366s-0.111,1.09,0.365,1.366c0.479,0.276,1.09,0.113,1.367-0.366C9.821,11.584,9.657,10.973,9.18,10.696zM22.822,12.428c0.478-0.275,0.643-0.888,0.366-1.366c-0.275-0.478-0.89-0.642-1.366-0.366c-0.479,0.278-0.642,0.89-0.366,1.367C21.732,12.54,22.344,12.705,22.822,12.428zM12.062,21.455c-0.478-0.275-1.089-0.111-1.366,0.367c-0.275,0.479-0.111,1.09,0.366,1.365c0.478,0.277,1.091,0.111,1.365-0.365C12.704,22.344,12.54,21.732,12.062,21.455zM12.062,9.545c0.479-0.276,0.642-0.888,0.366-1.366c-0.276-0.478-0.888-0.642-1.366-0.366s-0.642,0.888-0.366,1.366C10.973,9.658,11.584,9.822,12.062,9.545zM22.823,18.572c-0.48-0.275-1.092-0.111-1.367,0.365c-0.275,0.479-0.112,1.092,0.367,1.367c0.477,0.275,1.089,0.113,1.365-0.365C23.464,19.461,23.3,18.848,22.823,18.572zM19.938,7.813c-0.477-0.276-1.091-0.111-1.365,0.366c-0.275,0.48-0.111,1.091,0.366,1.367s1.089,0.112,1.366-0.366C20.581,8.702,20.418,8.089,19.938,7.813zM23.378,14.5c-0.554,0.002-1.001,0.45-1.001,1c0.001,0.552,0.448,1,1.001,1c0.551,0,1-0.447,1-1C24.378,14.949,23.929,14.5,23.378,14.5zM15.501,6.624c-0.552,0-1,0.448-1,1l-0.466,7.343l-3.004,1.96c-0.478,0.277-0.642,0.889-0.365,1.365c0.275,0.479,0.889,0.643,1.365,0.367l3.305-1.676C15.39,16.99,15.444,17,15.501,17c0.828,0,1.5-0.671,1.5-1.5l-0.5-7.876C16.501,7.072,16.053,6.624,15.501,6.624zM15.501,22.377c-0.552,0-1,0.447-1,1s0.448,1,1,1s1-0.447,1-1S16.053,22.377,15.501,22.377zM18.939,21.455c-0.479,0.277-0.643,0.889-0.366,1.367c0.275,0.477,0.888,0.643,1.366,0.365c0.478-0.275,0.642-0.889,0.366-1.365C20.028,21.344,19.417,21.18,18.939,21.455z",
    },
    animation_pathWingButton: {
      tagName: "path",
      d:
        "m 4.5,0.5 c -2.216,0 -4,1.784 -4,4 l 0,24 c 0,2.216 1.784,4 4,4 l 13.71875,0 C 22.478584,27.272785 27.273681,22.511272 32.5,18.25 l 0,-13.75 c 0,-2.216 -1.784,-4 -4,-4 l -24,0 z",
    },
    animation_pathPointer: {
      tagName: "path",
      d: "M-15,-65,-15,-55,15,-55,15,-65,0,-95z",
    },
    animation_pathSwooshFX: {
      tagName: "path",
      d:
        "m 85,0 c 0,16.617 -4.813944,35.356 -13.131081,48.4508 h 6.099803 c 8.317138,-13.0948 13.13322,-28.5955 13.13322,-45.2124 0,-46.94483 -38.402714,-85.00262 -85.7743869,-85.00262 -1.0218522,0 -2.0373001,0.0241 -3.0506131,0.0589 45.958443,1.59437 82.723058,35.77285 82.723058,81.70532 z",
    },
  };

  //Dynamically builds an SVG element from a JSON object.
  function svgFromObject(obj) {
    const ele = document.createElementNS(svgNS, obj.tagName);
    for (const field in obj) {
      if (obj.hasOwnProperty(field) && field !== "tagName") {
        if (field === "children") {
          const len = obj.children.length;
          for (let i = 0; i < len; ++i) {
            ele.appendChild(svgFromObject(obj.children[i]));
          }
        } else if (field.indexOf("xlink:") === 0) {
          ele.setAttributeNS(xlinkNS, field.substring(6), obj[field]);
        } else if (field === "textContent") {
          ele.textContent = obj[field];
        } else {
          ele.setAttribute(field, obj[field]);
        }
      }
    }
    return ele;
  }

  function svgText(x, y, msg) {
    const text = document.createElementNS(svgNS, "text");
    text.setAttribute("x", x);
    text.setAttribute("y", y);
    text.setAttribute("class", "cesium-animation-svgText");

    const tspan = document.createElementNS(svgNS, "tspan");
    tspan.textContent = msg;
    text.appendChild(tspan);
    return text;
  }

  function setShuttleRingPointer(shuttleRingPointer, knobOuter, angle) {
    shuttleRingPointer.setAttribute(
      "transform",
      `translate(100,100) rotate(${angle})`
    );
    knobOuter.setAttribute("transform", `rotate(${angle})`);
  }

  const makeColorStringScratch = new Color();
  function makeColorString(background, gradient) {
    const gradientAlpha = gradient.alpha;
    const backgroundAlpha = 1.0 - gradientAlpha;
    makeColorStringScratch.red =
      background.red * backgroundAlpha + gradient.red * gradientAlpha;
    makeColorStringScratch.green =
      background.green * backgroundAlpha + gradient.green * gradientAlpha;
    makeColorStringScratch.blue =
      background.blue * backgroundAlpha + gradient.blue * gradientAlpha;
    return makeColorStringScratch.toCssColorString();
  }

  function rectButton(x, y, path) {
    const iconInfo = svgIconsById[path];

    const button = {
      tagName: "g",
      class: "cesium-animation-rectButton",
      transform: `translate(${x},${y})`,
      children: [
        {
          tagName: "rect",
          class: "cesium-animation-buttonGlow",
          width: 32,
          height: 32,
          rx: 2,
          ry: 2,
        },
        {
          tagName: "rect",
          class: "cesium-animation-buttonMain",
          width: 32,
          height: 32,
          rx: 4,
          ry: 4,
        },
        {
          class: "cesium-animation-buttonPath",
          id: path,
          tagName: iconInfo.tagName,
          transform: iconInfo.transform,
          d: iconInfo.d,
        },
        {
          tagName: "title",
          textContent: "",
        },
      ],
    };
    return svgFromObject(button);
  }

  function wingButton(x, y, path) {
    const buttonIconInfo = svgIconsById[path];
    const wingIconInfo = svgIconsById["animation_pathWingButton"];

    const button = {
      tagName: "g",
      class: "cesium-animation-rectButton",
      transform: `translate(${x},${y})`,
      children: [
        {
          class: "cesium-animation-buttonGlow",
          id: "animation_pathWingButton",
          tagName: wingIconInfo.tagName,
          d: wingIconInfo.d,
        },
        {
          class: "cesium-animation-buttonMain",
          id: "animation_pathWingButton",
          tagName: wingIconInfo.tagName,
          d: wingIconInfo.d,
        },
        {
          class: "cesium-animation-buttonPath",
          id: path,
          tagName: buttonIconInfo.tagName,
          transform: buttonIconInfo.transform,
          d: buttonIconInfo.d,
        },
        {
          tagName: "title",
          textContent: "",
        },
      ],
    };
    return svgFromObject(button);
  }

  function setShuttleRingFromMouseOrTouch(widget, e) {
    const viewModel = widget._viewModel;
    const shuttleRingDragging = viewModel.shuttleRingDragging;

    if (shuttleRingDragging && widgetForDrag !== widget) {
      return;
    }

    if (
      e.type === "mousedown" ||
      (shuttleRingDragging && e.type === "mousemove") ||
      (e.type === "touchstart" && e.touches.length === 1) ||
      (shuttleRingDragging && e.type === "touchmove" && e.touches.length === 1)
    ) {
      const centerX = widget._centerX;
      const centerY = widget._centerY;
      const svg = widget._svgNode;
      const rect = svg.getBoundingClientRect();
      let clientX;
      let clientY;
      if (e.type === "touchstart" || e.type === "touchmove") {
        clientX = e.touches[0].clientX;
        clientY = e.touches[0].clientY;
      } else {
        clientX = e.clientX;
        clientY = e.clientY;
      }

      if (
        !shuttleRingDragging &&
        (clientX > rect.right ||
          clientX < rect.left ||
          clientY < rect.top ||
          clientY > rect.bottom)
      ) {
        return;
      }

      const pointerRect = widget._shuttleRingPointer.getBoundingClientRect();

      const x = clientX - centerX - rect.left;
      const y = clientY - centerY - rect.top;

      let angle = (Math.atan2(y, x) * 180) / Math.PI + 90;
      if (angle > 180) {
        angle -= 360;
      }
      const shuttleRingAngle = viewModel.shuttleRingAngle;
      if (
        shuttleRingDragging ||
        (clientX < pointerRect.right &&
          clientX > pointerRect.left &&
          clientY > pointerRect.top &&
          clientY < pointerRect.bottom)
      ) {
        widgetForDrag = widget;
        viewModel.shuttleRingDragging = true;
        viewModel.shuttleRingAngle = angle;
      } else if (angle < shuttleRingAngle) {
        viewModel.slower();
      } else if (angle > shuttleRingAngle) {
        viewModel.faster();
      }
      e.preventDefault();
    } else {
      if (widget === widgetForDrag) {
        widgetForDrag = undefined;
      }
      viewModel.shuttleRingDragging = false;
    }
  }

  //This is a private class for treating an SVG element like a button.
  //If we ever need a general purpose SVG button, we can make this generic.
  function SvgButton(svgElement, viewModel) {
    this._viewModel = viewModel;
    this.svgElement = svgElement;
    this._enabled = undefined;
    this._toggled = undefined;

    const that = this;
    this._clickFunction = function () {
      const command = that._viewModel.command;
      if (command.canExecute) {
        command();
      }
    };

    svgElement.addEventListener("click", this._clickFunction, true);

    //TODO: Since the animation widget uses SVG and has no HTML backing,
    //we need to wire everything up manually.  Knockout can supposedly
    //bind to SVG, so we we figure that out we can modify our SVG
    //to include the binding information directly.

    this._subscriptions = [
      //
      subscribeAndEvaluate(viewModel, "toggled", this.setToggled, this), //
      subscribeAndEvaluate(viewModel, "tooltip", this.setTooltip, this), //
      subscribeAndEvaluate(
        viewModel.command,
        "canExecute",
        this.setEnabled,
        this
      ),
    ];
  }

  SvgButton.prototype.destroy = function () {
    this.svgElement.removeEventListener("click", this._clickFunction, true);
    const subscriptions = this._subscriptions;
    for (let i = 0, len = subscriptions.length; i < len; i++) {
      subscriptions[i].dispose();
    }
    destroyObject(this);
  };

  SvgButton.prototype.isDestroyed = function () {
    return false;
  };

  SvgButton.prototype.setEnabled = function (enabled) {
    if (this._enabled !== enabled) {
      this._enabled = enabled;

      if (!enabled) {
        this.svgElement.setAttribute("class", "cesium-animation-buttonDisabled");
        return;
      }

      if (this._toggled) {
        this.svgElement.setAttribute(
          "class",
          "cesium-animation-rectButton cesium-animation-buttonToggled"
        );
        return;
      }

      this.svgElement.setAttribute("class", "cesium-animation-rectButton");
    }
  };

  SvgButton.prototype.setToggled = function (toggled) {
    if (this._toggled !== toggled) {
      this._toggled = toggled;

      if (this._enabled) {
        if (toggled) {
          this.svgElement.setAttribute(
            "class",
            "cesium-animation-rectButton cesium-animation-buttonToggled"
          );
        } else {
          this.svgElement.setAttribute("class", "cesium-animation-rectButton");
        }
      }
    }
  };

  SvgButton.prototype.setTooltip = function (tooltip) {
    this.svgElement.getElementsByTagName("title")[0].textContent = tooltip;
  };

  /**
   * <span style="display: block; text-align: center;">
   * <img src="Images/AnimationWidget.png" width="211" height="142" alt="" />
   * <br />Animation widget
   * </span>
   * <br /><br />
   * The Animation widget provides buttons for play, pause, and reverse, along with the
   * current time and date, surrounded by a "shuttle ring" for controlling the speed of animation.
   * <br /><br />
   * The "shuttle ring" concept is borrowed from video editing, where typically a
   * "jog wheel" can be rotated to move past individual animation frames very slowly, and
   * a surrounding shuttle ring can be twisted to control direction and speed of fast playback.
   * Cesium typically treats time as continuous (not broken into pre-defined animation frames),
   * so this widget offers no jog wheel.  Instead, the shuttle ring is capable of both fast and
   * very slow playback.  Click and drag the shuttle ring pointer itself (shown above in green),
   * or click in the rest of the ring area to nudge the pointer to the next preset speed in that direction.
   * <br /><br />
   * The Animation widget also provides a "realtime" button (in the upper-left) that keeps
   * animation time in sync with the end user's system clock, typically displaying
   * "today" or "right now."  This mode is not available in {@link ClockRange.CLAMPED} or
   * {@link ClockRange.LOOP_STOP} mode if the current time is outside of {@link Clock}'s startTime and endTime.
   *
   * @alias Animation
   * @constructor
   *
   * @param {Element|String} container The DOM element or ID that will contain the widget.
   * @param {AnimationViewModel} viewModel The view model used by this widget.
   *
   * @exception {DeveloperError} Element with id "container" does not exist in the document.
   *
   *
   * @example
   * // In HTML head, include a link to Animation.css stylesheet,
   * // and in the body, include: <div id="animationContainer"></div>
   *
   * const clock = new Cesium.Clock();
   * const clockViewModel = new Cesium.ClockViewModel(clock);
   * const viewModel = new Cesium.AnimationViewModel(clockViewModel);
   * const widget = new Cesium.Animation('animationContainer', viewModel);
   *
   * function tick() {
   *     clock.tick();
   *     Cesium.requestAnimationFrame(tick);
   * }
   * Cesium.requestAnimationFrame(tick);
   *
   * @see AnimationViewModel
   * @see Clock
   */
  function Animation(container, viewModel) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(container)) {
      throw new DeveloperError("container is required.");
    }
    if (!defined(viewModel)) {
      throw new DeveloperError("viewModel is required.");
    }
    //>>includeEnd('debug');

    container = getElement(container);
    this._viewModel = viewModel;
    this._container = container;
    this._centerX = 0;
    this._centerY = 0;
    this._defsElement = undefined;
    this._svgNode = undefined;
    this._topG = undefined;
    this._lastHeight = undefined;
    this._lastWidth = undefined;

    const ownerDocument = container.ownerDocument;

    // Firefox requires SVG references to be included directly, not imported from external CSS.
    // Also, CSS minifiers get confused by this being in an external CSS file.
    const cssStyle = document.createElement("style");
    cssStyle.textContent =
      ".cesium-animation-rectButton .cesium-animation-buttonGlow { filter: url(#animation_blurred); }\
.cesium-animation-rectButton .cesium-animation-buttonMain { fill: url(#animation_buttonNormal); }\
.cesium-animation-buttonToggled .cesium-animation-buttonMain { fill: url(#animation_buttonToggled); }\
.cesium-animation-rectButton:hover .cesium-animation-buttonMain { fill: url(#animation_buttonHovered); }\
.cesium-animation-buttonDisabled .cesium-animation-buttonMain { fill: url(#animation_buttonDisabled); }\
.cesium-animation-shuttleRingG .cesium-animation-shuttleRingSwoosh { fill: url(#animation_shuttleRingSwooshGradient); }\
.cesium-animation-shuttleRingG:hover .cesium-animation-shuttleRingSwoosh { fill: url(#animation_shuttleRingSwooshHovered); }\
.cesium-animation-shuttleRingPointer { fill: url(#animation_shuttleRingPointerGradient); }\
.cesium-animation-shuttleRingPausePointer { fill: url(#animation_shuttleRingPointerPaused); }\
.cesium-animation-knobOuter { fill: url(#animation_knobOuter); }\
.cesium-animation-knobInner { fill: url(#animation_knobInner); }";

    ownerDocument.head.insertBefore(cssStyle, ownerDocument.head.childNodes[0]);

    const themeEle = document.createElement("div");
    themeEle.className = "cesium-animation-theme";
    themeEle.innerHTML =
      '<div class="cesium-animation-themeNormal"></div>\
<div class="cesium-animation-themeHover"></div>\
<div class="cesium-animation-themeSelect"></div>\
<div class="cesium-animation-themeDisabled"></div>\
<div class="cesium-animation-themeKnob"></div>\
<div class="cesium-animation-themePointer"></div>\
<div class="cesium-animation-themeSwoosh"></div>\
<div class="cesium-animation-themeSwooshHover"></div>';

    this._theme = themeEle;
    this._themeNormal = themeEle.childNodes[0];
    this._themeHover = themeEle.childNodes[1];
    this._themeSelect = themeEle.childNodes[2];
    this._themeDisabled = themeEle.childNodes[3];
    this._themeKnob = themeEle.childNodes[4];
    this._themePointer = themeEle.childNodes[5];
    this._themeSwoosh = themeEle.childNodes[6];
    this._themeSwooshHover = themeEle.childNodes[7];

    const svg = document.createElementNS(svgNS, "svg:svg");
    this._svgNode = svg;

    // Define the XLink namespace that SVG uses
    svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", xlinkNS);

    const topG = document.createElementNS(svgNS, "g");
    this._topG = topG;

    this._realtimeSVG = new SvgButton(
      wingButton(3, 4, "animation_pathClock"),
      viewModel.playRealtimeViewModel
    );
    this._playReverseSVG = new SvgButton(
      rectButton(44, 99, "animation_pathPlayReverse"),
      viewModel.playReverseViewModel
    );
    this._playForwardSVG = new SvgButton(
      rectButton(124, 99, "animation_pathPlay"),
      viewModel.playForwardViewModel
    );
    this._pauseSVG = new SvgButton(
      rectButton(84, 99, "animation_pathPause"),
      viewModel.pauseViewModel
    );

    const buttonsG = document.createElementNS(svgNS, "g");
    buttonsG.appendChild(this._realtimeSVG.svgElement);
    buttonsG.appendChild(this._playReverseSVG.svgElement);
    buttonsG.appendChild(this._playForwardSVG.svgElement);
    buttonsG.appendChild(this._pauseSVG.svgElement);

    const shuttleRingBackPanel = svgFromObject({
      tagName: "circle",
      class: "cesium-animation-shuttleRingBack",
      cx: 100,
      cy: 100,
      r: 99,
    });
    this._shuttleRingBackPanel = shuttleRingBackPanel;

    const swooshIconInfo = svgIconsById["animation_pathSwooshFX"];
    const shuttleRingPointerIconInfo = svgIconsById["animation_pathPointer"];

    const shuttleRingSwooshG = svgFromObject({
      tagName: "g",
      class: "cesium-animation-shuttleRingSwoosh",
      children: [
        {
          tagName: swooshIconInfo.tagName,
          transform: "translate(100,97) scale(-1,1)",
          id: "animation_pathSwooshFX",
          d: swooshIconInfo.d,
        },
        {
          tagName: swooshIconInfo.tagName,
          transform: "translate(100,97)",
          id: "animation_pathSwooshFX",
          d: swooshIconInfo.d,
        },
        {
          tagName: "line",
          x1: 100,
          y1: 8,
          x2: 100,
          y2: 22,
        },
      ],
    });
    this._shuttleRingSwooshG = shuttleRingSwooshG;

    this._shuttleRingPointer = svgFromObject({
      class: "cesium-animation-shuttleRingPointer",
      id: "animation_pathPointer",
      tagName: shuttleRingPointerIconInfo.tagName,
      d: shuttleRingPointerIconInfo.d,
    });

    const knobG = svgFromObject({
      tagName: "g",
      transform: "translate(100,100)",
    });

    this._knobOuter = svgFromObject({
      tagName: "circle",
      class: "cesium-animation-knobOuter",
      cx: 0,
      cy: 0,
      r: 71,
    });

    const knobInnerAndShieldSize = 61;

    const knobInner = svgFromObject({
      tagName: "circle",
      class: "cesium-animation-knobInner",
      cx: 0,
      cy: 0,
      r: knobInnerAndShieldSize,
    });

    this._knobDate = svgText(0, -24, "");
    this._knobTime = svgText(0, -7, "");
    this._knobStatus = svgText(0, -41, "");

    // widget shield catches clicks on the knob itself (even while DOM elements underneath are changing).
    const knobShield = svgFromObject({
      tagName: "circle",
      class: "cesium-animation-blank",
      cx: 0,
      cy: 0,
      r: knobInnerAndShieldSize,
    });

    const shuttleRingBackG = document.createElementNS(svgNS, "g");
    shuttleRingBackG.setAttribute("class", "cesium-animation-shuttleRingG");

    container.appendChild(themeEle);
    topG.appendChild(shuttleRingBackG);
    topG.appendChild(knobG);
    topG.appendChild(buttonsG);

    shuttleRingBackG.appendChild(shuttleRingBackPanel);
    shuttleRingBackG.appendChild(shuttleRingSwooshG);
    shuttleRingBackG.appendChild(this._shuttleRingPointer);

    knobG.appendChild(this._knobOuter);
    knobG.appendChild(knobInner);
    knobG.appendChild(this._knobDate);
    knobG.appendChild(this._knobTime);
    knobG.appendChild(this._knobStatus);
    knobG.appendChild(knobShield);

    svg.appendChild(topG);
    container.appendChild(svg);

    const that = this;
    function mouseCallback(e) {
      setShuttleRingFromMouseOrTouch(that, e);
    }
    this._mouseCallback = mouseCallback;

    shuttleRingBackPanel.addEventListener("mousedown", mouseCallback, true);
    shuttleRingBackPanel.addEventListener("touchstart", mouseCallback, true);
    shuttleRingSwooshG.addEventListener("mousedown", mouseCallback, true);
    shuttleRingSwooshG.addEventListener("touchstart", mouseCallback, true);
    ownerDocument.addEventListener("mousemove", mouseCallback, true);
    ownerDocument.addEventListener("touchmove", mouseCallback, true);
    ownerDocument.addEventListener("mouseup", mouseCallback, true);
    ownerDocument.addEventListener("touchend", mouseCallback, true);
    ownerDocument.addEventListener("touchcancel", mouseCallback, true);
    this._shuttleRingPointer.addEventListener("mousedown", mouseCallback, true);
    this._shuttleRingPointer.addEventListener("touchstart", mouseCallback, true);
    this._knobOuter.addEventListener("mousedown", mouseCallback, true);
    this._knobOuter.addEventListener("touchstart", mouseCallback, true);

    //TODO: Since the animation widget uses SVG and has no HTML backing,
    //we need to wire everything up manually.  Knockout can supposedly
    //bind to SVG, so we we figure that out we can modify our SVG
    //to include the binding information directly.

    const timeNode = this._knobTime.childNodes[0];
    const dateNode = this._knobDate.childNodes[0];
    const statusNode = this._knobStatus.childNodes[0];
    let isPaused;
    this._subscriptions = [
      //
      subscribeAndEvaluate(viewModel.pauseViewModel, "toggled", function (value) {
        if (isPaused !== value) {
          isPaused = value;
          if (isPaused) {
            that._shuttleRingPointer.setAttribute(
              "class",
              "cesium-animation-shuttleRingPausePointer"
            );
          } else {
            that._shuttleRingPointer.setAttribute(
              "class",
              "cesium-animation-shuttleRingPointer"
            );
          }
        }
      }),

      subscribeAndEvaluate(viewModel, "shuttleRingAngle", function (value) {
        setShuttleRingPointer(that._shuttleRingPointer, that._knobOuter, value);
      }),

      subscribeAndEvaluate(viewModel, "dateLabel", function (value) {
        if (dateNode.textContent !== value) {
          dateNode.textContent = value;
        }
      }),

      subscribeAndEvaluate(viewModel, "timeLabel", function (value) {
        if (timeNode.textContent !== value) {
          timeNode.textContent = value;
        }
      }),

      subscribeAndEvaluate(viewModel, "multiplierLabel", function (value) {
        if (statusNode.textContent !== value) {
          statusNode.textContent = value;
        }
      }),
    ];

    this.applyThemeChanges();
    this.resize();
  }

  Object.defineProperties(Animation.prototype, {
    /**
     * Gets the parent container.
     *
     * @memberof Animation.prototype
     * @type {Element}
     * @readonly
     */
    container: {
      get: function () {
        return this._container;
      },
    },

    /**
     * Gets the view model.
     *
     * @memberof Animation.prototype
     * @type {AnimationViewModel}
     * @readonly
     */
    viewModel: {
      get: function () {
        return this._viewModel;
      },
    },
  });

  /**
   * @returns {Boolean} true if the object has been destroyed, false otherwise.
   */
  Animation.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the animation widget.  Should be called if permanently
   * removing the widget from layout.
   */
  Animation.prototype.destroy = function () {
    if (defined(this._observer)) {
      this._observer.disconnect();
      this._observer = undefined;
    }

    const doc = this._container.ownerDocument;

    const mouseCallback = this._mouseCallback;
    this._shuttleRingBackPanel.removeEventListener(
      "mousedown",
      mouseCallback,
      true
    );
    this._shuttleRingBackPanel.removeEventListener(
      "touchstart",
      mouseCallback,
      true
    );
    this._shuttleRingSwooshG.removeEventListener(
      "mousedown",
      mouseCallback,
      true
    );
    this._shuttleRingSwooshG.removeEventListener(
      "touchstart",
      mouseCallback,
      true
    );
    doc.removeEventListener("mousemove", mouseCallback, true);
    doc.removeEventListener("touchmove", mouseCallback, true);
    doc.removeEventListener("mouseup", mouseCallback, true);
    doc.removeEventListener("touchend", mouseCallback, true);
    doc.removeEventListener("touchcancel", mouseCallback, true);
    this._shuttleRingPointer.removeEventListener(
      "mousedown",
      mouseCallback,
      true
    );
    this._shuttleRingPointer.removeEventListener(
      "touchstart",
      mouseCallback,
      true
    );
    this._knobOuter.removeEventListener("mousedown", mouseCallback, true);
    this._knobOuter.removeEventListener("touchstart", mouseCallback, true);

    this._container.removeChild(this._svgNode);
    this._container.removeChild(this._theme);
    this._realtimeSVG.destroy();
    this._playReverseSVG.destroy();
    this._playForwardSVG.destroy();
    this._pauseSVG.destroy();

    const subscriptions = this._subscriptions;
    for (let i = 0, len = subscriptions.length; i < len; i++) {
      subscriptions[i].dispose();
    }

    return destroyObject(this);
  };

  /**
   * Resizes the widget to match the container size.
   * This function should be called whenever the container size is changed.
   */
  Animation.prototype.resize = function () {
    const parentWidth = this._container.clientWidth;
    const parentHeight = this._container.clientHeight;
    if (parentWidth === this._lastWidth && parentHeight === this._lastHeight) {
      return;
    }

    const svg = this._svgNode;

    //The width and height as the SVG was originally drawn.
    const baseWidth = 200;
    const baseHeight = 132;

    let width = parentWidth;
    let height = parentHeight;

    if (parentWidth === 0 && parentHeight === 0) {
      width = baseWidth;
      height = baseHeight;
    } else if (parentWidth === 0) {
      height = parentHeight;
      width = baseWidth * (parentHeight / baseHeight);
    } else if (parentHeight === 0) {
      width = parentWidth;
      height = baseHeight * (parentWidth / baseWidth);
    }

    const scaleX = width / baseWidth;
    const scaleY = height / baseHeight;

    svg.style.cssText = `width: ${width}px; height: ${height}px; position: absolute; bottom: 0; left: 0; overflow: hidden;`;
    svg.setAttribute("width", width);
    svg.setAttribute("height", height);
    svg.setAttribute("viewBox", `0 0 ${width} ${height}`);

    this._topG.setAttribute("transform", `scale(${scaleX},${scaleY})`);

    this._centerX = Math.max(1, 100.0 * scaleX);
    this._centerY = Math.max(1, 100.0 * scaleY);

    this._lastHeight = parentWidth;
    this._lastWidth = parentHeight;
  };

  /**
   * Updates the widget to reflect any modified CSS rules for theming.
   *
   * @example
   * //Switch to the cesium-lighter theme.
   * document.body.className = 'cesium-lighter';
   * animation.applyThemeChanges();
   */
  Animation.prototype.applyThemeChanges = function () {
    // Since we rely on computed styles for themeing, we can't actually
    // do anything if the container has not yet been added to the DOM.
    // Set up an observer to be notified when it is added and apply
    // the changes at that time.

    const doc = this._container.ownerDocument;

    if (!doc.body.contains(this._container)) {
      if (defined(this._observer)) {
        //Already listening.
        return;
      }
      const that = this;
      that._observer = new MutationObserver(function () {
        if (doc.body.contains(that._container)) {
          that._observer.disconnect();
          that._observer = undefined;
          that.applyThemeChanges();
        }
      });
      that._observer.observe(doc, { childList: true, subtree: true });
      return;
    }

    const buttonNormalBackColor = getElementColor(this._themeNormal);
    const buttonHoverBackColor = getElementColor(this._themeHover);
    const buttonToggledBackColor = getElementColor(this._themeSelect);
    const buttonDisabledBackColor = getElementColor(this._themeDisabled);
    const knobBackColor = getElementColor(this._themeKnob);
    const pointerColor = getElementColor(this._themePointer);
    const swooshColor = getElementColor(this._themeSwoosh);
    const swooshHoverColor = getElementColor(this._themeSwooshHover);

    const defsElement = svgFromObject({
      tagName: "defs",
      children: [
        {
          id: "animation_buttonNormal",
          tagName: "linearGradient",
          x1: "50%",
          y1: "0%",
          x2: "50%",
          y2: "100%",
          children: [
            //add a 'stop-opacity' field to make translucent.
            {
              tagName: "stop",
              offset: "0%",
              "stop-color": makeColorString(
                buttonNormalBackColor,
                gradientEnabledColor0
              ),
            },
            {
              tagName: "stop",
              offset: "12%",
              "stop-color": makeColorString(
                buttonNormalBackColor,
                gradientEnabledColor1
              ),
            },
            {
              tagName: "stop",
              offset: "46%",
              "stop-color": makeColorString(
                buttonNormalBackColor,
                gradientEnabledColor2
              ),
            },
            {
              tagName: "stop",
              offset: "81%",
              "stop-color": makeColorString(
                buttonNormalBackColor,
                gradientEnabledColor3
              ),
            },
          ],
        },
        {
          id: "animation_buttonHovered",
          tagName: "linearGradient",
          x1: "50%",
          y1: "0%",
          x2: "50%",
          y2: "100%",
          children: [
            {
              tagName: "stop",
              offset: "0%",
              "stop-color": makeColorString(
                buttonHoverBackColor,
                gradientEnabledColor0
              ),
            },
            {
              tagName: "stop",
              offset: "12%",
              "stop-color": makeColorString(
                buttonHoverBackColor,
                gradientEnabledColor1
              ),
            },
            {
              tagName: "stop",
              offset: "46%",
              "stop-color": makeColorString(
                buttonHoverBackColor,
                gradientEnabledColor2
              ),
            },
            {
              tagName: "stop",
              offset: "81%",
              "stop-color": makeColorString(
                buttonHoverBackColor,
                gradientEnabledColor3
              ),
            },
          ],
        },
        {
          id: "animation_buttonToggled",
          tagName: "linearGradient",
          x1: "50%",
          y1: "0%",
          x2: "50%",
          y2: "100%",
          children: [
            {
              tagName: "stop",
              offset: "0%",
              "stop-color": makeColorString(
                buttonToggledBackColor,
                gradientEnabledColor0
              ),
            },
            {
              tagName: "stop",
              offset: "12%",
              "stop-color": makeColorString(
                buttonToggledBackColor,
                gradientEnabledColor1
              ),
            },
            {
              tagName: "stop",
              offset: "46%",
              "stop-color": makeColorString(
                buttonToggledBackColor,
                gradientEnabledColor2
              ),
            },
            {
              tagName: "stop",
              offset: "81%",
              "stop-color": makeColorString(
                buttonToggledBackColor,
                gradientEnabledColor3
              ),
            },
          ],
        },
        {
          id: "animation_buttonDisabled",
          tagName: "linearGradient",
          x1: "50%",
          y1: "0%",
          x2: "50%",
          y2: "100%",
          children: [
            {
              tagName: "stop",
              offset: "0%",
              "stop-color": makeColorString(
                buttonDisabledBackColor,
                gradientDisabledColor0
              ),
            },
            {
              tagName: "stop",
              offset: "75%",
              "stop-color": makeColorString(
                buttonDisabledBackColor,
                gradientDisabledColor1
              ),
            },
          ],
        },
        {
          id: "animation_blurred",
          tagName: "filter",
          width: "200%",
          height: "200%",
          x: "-50%",
          y: "-50%",
          children: [
            {
              tagName: "feGaussianBlur",
              stdDeviation: 4,
              in: "SourceGraphic",
            },
          ],
        },
        {
          id: "animation_shuttleRingSwooshGradient",
          tagName: "linearGradient",
          x1: "50%",
          y1: "0%",
          x2: "50%",
          y2: "100%",
          children: [
            {
              tagName: "stop",
              offset: "0%",
              "stop-opacity": 0.2,
              "stop-color": swooshColor.toCssColorString(),
            },
            {
              tagName: "stop",
              offset: "85%",
              "stop-opacity": 0.85,
              "stop-color": swooshColor.toCssColorString(),
            },
            {
              tagName: "stop",
              offset: "95%",
              "stop-opacity": 0.05,
              "stop-color": swooshColor.toCssColorString(),
            },
          ],
        },
        {
          id: "animation_shuttleRingSwooshHovered",
          tagName: "linearGradient",
          x1: "50%",
          y1: "0%",
          x2: "50%",
          y2: "100%",
          children: [
            {
              tagName: "stop",
              offset: "0%",
              "stop-opacity": 0.2,
              "stop-color": swooshHoverColor.toCssColorString(),
            },
            {
              tagName: "stop",
              offset: "85%",
              "stop-opacity": 0.85,
              "stop-color": swooshHoverColor.toCssColorString(),
            },
            {
              tagName: "stop",
              offset: "95%",
              "stop-opacity": 0.05,
              "stop-color": swooshHoverColor.toCssColorString(),
            },
          ],
        },
        {
          id: "animation_shuttleRingPointerGradient",
          tagName: "linearGradient",
          x1: "0%",
          y1: "50%",
          x2: "100%",
          y2: "50%",
          children: [
            {
              tagName: "stop",
              offset: "0%",
              "stop-color": pointerColor.toCssColorString(),
            },
            {
              tagName: "stop",
              offset: "40%",
              "stop-color": pointerColor.toCssColorString(),
            },
            {
              tagName: "stop",
              offset: "60%",
              "stop-color": makeColorString(pointerColor, gradientPointerColor),
            },
            {
              tagName: "stop",
              offset: "100%",
              "stop-color": makeColorString(pointerColor, gradientPointerColor),
            },
          ],
        },
        {
          id: "animation_shuttleRingPointerPaused",
          tagName: "linearGradient",
          x1: "0%",
          y1: "50%",
          x2: "100%",
          y2: "50%",
          children: [
            {
              tagName: "stop",
              offset: "0%",
              "stop-color": "#CCC",
            },
            {
              tagName: "stop",
              offset: "40%",
              "stop-color": "#CCC",
            },
            {
              tagName: "stop",
              offset: "60%",
              "stop-color": "#555",
            },
            {
              tagName: "stop",
              offset: "100%",
              "stop-color": "#555",
            },
          ],
        },
        {
          id: "animation_knobOuter",
          tagName: "linearGradient",
          x1: "20%",
          y1: "0%",
          x2: "90%",
          y2: "100%",
          children: [
            {
              tagName: "stop",
              offset: "5%",
              "stop-color": makeColorString(knobBackColor, gradientEnabledColor0),
            },
            {
              tagName: "stop",
              offset: "60%",
              "stop-color": makeColorString(knobBackColor, gradientKnobColor),
            },
            {
              tagName: "stop",
              offset: "85%",
              "stop-color": makeColorString(knobBackColor, gradientEnabledColor1),
            },
          ],
        },
        {
          id: "animation_knobInner",
          tagName: "linearGradient",
          x1: "20%",
          y1: "0%",
          x2: "90%",
          y2: "100%",
          children: [
            {
              tagName: "stop",
              offset: "5%",
              "stop-color": makeColorString(knobBackColor, gradientKnobColor),
            },
            {
              tagName: "stop",
              offset: "60%",
              "stop-color": makeColorString(knobBackColor, gradientEnabledColor0),
            },
            {
              tagName: "stop",
              offset: "85%",
              "stop-color": makeColorString(knobBackColor, gradientEnabledColor3),
            },
          ],
        },
      ],
    });

    if (!defined(this._defsElement)) {
      this._svgNode.appendChild(defsElement);
    } else {
      this._svgNode.replaceChild(defsElement, this._defsElement);
    }
    this._defsElement = defsElement;
  };

  const monthNames = [
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "Jun",
    "Jul",
    "Aug",
    "Sep",
    "Oct",
    "Nov",
    "Dec",
  ];
  const realtimeShuttleRingAngle = 15;
  const maxShuttleRingAngle = 105;

  function numberComparator(left, right) {
    return left - right;
  }

  function getTypicalMultiplierIndex(multiplier, shuttleRingTicks) {
    const index = binarySearch(shuttleRingTicks, multiplier, numberComparator);
    return index < 0 ? ~index : index;
  }

  function angleToMultiplier(angle, shuttleRingTicks) {
    //Use a linear scale for -1 to 1 between -15 < angle < 15 degrees
    if (Math.abs(angle) <= realtimeShuttleRingAngle) {
      return angle / realtimeShuttleRingAngle;
    }

    const minp = realtimeShuttleRingAngle;
    const maxp = maxShuttleRingAngle;
    let maxv;
    const minv = 0;
    let scale;
    if (angle > 0) {
      maxv = Math.log(shuttleRingTicks[shuttleRingTicks.length - 1]);
      scale = (maxv - minv) / (maxp - minp);
      return Math.exp(minv + scale * (angle - minp));
    }

    maxv = Math.log(-shuttleRingTicks[0]);
    scale = (maxv - minv) / (maxp - minp);
    return -Math.exp(minv + scale * (Math.abs(angle) - minp));
  }

  function multiplierToAngle(multiplier, shuttleRingTicks, clockViewModel) {
    if (clockViewModel.clockStep === ClockStep$1.SYSTEM_CLOCK) {
      return realtimeShuttleRingAngle;
    }

    if (Math.abs(multiplier) <= 1) {
      return multiplier * realtimeShuttleRingAngle;
    }

    const fastedMultipler = shuttleRingTicks[shuttleRingTicks.length - 1];
    if (multiplier > fastedMultipler) {
      multiplier = fastedMultipler;
    } else if (multiplier < -fastedMultipler) {
      multiplier = -fastedMultipler;
    }

    const minp = realtimeShuttleRingAngle;
    const maxp = maxShuttleRingAngle;
    let maxv;
    const minv = 0;
    let scale;

    if (multiplier > 0) {
      maxv = Math.log(fastedMultipler);
      scale = (maxv - minv) / (maxp - minp);
      return (Math.log(multiplier) - minv) / scale + minp;
    }

    maxv = Math.log(-shuttleRingTicks[0]);
    scale = (maxv - minv) / (maxp - minp);
    return -((Math.log(Math.abs(multiplier)) - minv) / scale + minp);
  }

  /**
   * The view model for the {@link Animation} widget.
   * @alias AnimationViewModel
   * @constructor
   *
   * @param {ClockViewModel} clockViewModel The ClockViewModel instance to use.
   *
   * @see Animation
   */
  function AnimationViewModel(clockViewModel) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(clockViewModel)) {
      throw new DeveloperError("clockViewModel is required.");
    }
    //>>includeEnd('debug');

    const that = this;
    this._clockViewModel = clockViewModel;
    this._allShuttleRingTicks = [];
    this._dateFormatter = AnimationViewModel.defaultDateFormatter;
    this._timeFormatter = AnimationViewModel.defaultTimeFormatter;

    /**
     * Gets or sets whether the shuttle ring is currently being dragged.  This property is observable.
     * @type {Boolean}
     * @default false
     */
    this.shuttleRingDragging = false;

    /**
     * Gets or sets whether dragging the shuttle ring should cause the multiplier
     * to snap to the defined tick values rather than interpolating between them.
     * This property is observable.
     * @type {Boolean}
     * @default false
     */
    this.snapToTicks = false;

    knockout.track(this, [
      "_allShuttleRingTicks",
      "_dateFormatter",
      "_timeFormatter",
      "shuttleRingDragging",
      "snapToTicks",
    ]);

    this._sortedFilteredPositiveTicks = [];

    this.setShuttleRingTicks(AnimationViewModel.defaultTicks);

    /**
     * Gets the string representation of the current time.  This property is observable.
     * @type {String}
     */
    this.timeLabel = undefined;
    knockout.defineProperty(this, "timeLabel", function () {
      return that._timeFormatter(that._clockViewModel.currentTime, that);
    });

    /**
     * Gets the string representation of the current date.  This property is observable.
     * @type {String}
     */
    this.dateLabel = undefined;
    knockout.defineProperty(this, "dateLabel", function () {
      return that._dateFormatter(that._clockViewModel.currentTime, that);
    });

    /**
     * Gets the string representation of the current multiplier.  This property is observable.
     * @type {String}
     */
    this.multiplierLabel = undefined;
    knockout.defineProperty(this, "multiplierLabel", function () {
      const clockViewModel = that._clockViewModel;
      if (clockViewModel.clockStep === ClockStep$1.SYSTEM_CLOCK) {
        return "Today";
      }

      const multiplier = clockViewModel.multiplier;

      //If it's a whole number, just return it.
      if (multiplier % 1 === 0) {
        return `${multiplier.toFixed(0)}x`;
      }

      //Convert to decimal string and remove any trailing zeroes
      return `${multiplier.toFixed(3).replace(/0{0,3}$/, "")}x`;
    });

    /**
     * Gets or sets the current shuttle ring angle.  This property is observable.
     * @type {Number}
     */
    this.shuttleRingAngle = undefined;
    knockout.defineProperty(this, "shuttleRingAngle", {
      get: function () {
        return multiplierToAngle(
          clockViewModel.multiplier,
          that._allShuttleRingTicks,
          clockViewModel
        );
      },
      set: function (angle) {
        angle = Math.max(
          Math.min(angle, maxShuttleRingAngle),
          -maxShuttleRingAngle
        );
        const ticks = that._allShuttleRingTicks;

        const clockViewModel = that._clockViewModel;
        clockViewModel.clockStep = ClockStep$1.SYSTEM_CLOCK_MULTIPLIER;

        //If we are at the max angle, simply return the max value in either direction.
        if (Math.abs(angle) === maxShuttleRingAngle) {
          clockViewModel.multiplier =
            angle > 0 ? ticks[ticks.length - 1] : ticks[0];
          return;
        }

        let multiplier = angleToMultiplier(angle, ticks);
        if (that.snapToTicks) {
          multiplier = ticks[getTypicalMultiplierIndex(multiplier, ticks)];
        } else if (multiplier !== 0) {
          const positiveMultiplier = Math.abs(multiplier);

          if (positiveMultiplier > 100) {
            const numDigits = positiveMultiplier.toFixed(0).length - 2;
            const divisor = Math.pow(10, numDigits);
            multiplier = (Math.round(multiplier / divisor) * divisor) | 0;
          } else if (positiveMultiplier > realtimeShuttleRingAngle) {
            multiplier = Math.round(multiplier);
          } else if (positiveMultiplier > 1) {
            multiplier = +multiplier.toFixed(1);
          } else if (positiveMultiplier > 0) {
            multiplier = +multiplier.toFixed(2);
          }
        }
        clockViewModel.multiplier = multiplier;
      },
    });

    this._canAnimate = undefined;
    knockout.defineProperty(this, "_canAnimate", function () {
      const clockViewModel = that._clockViewModel;
      const clockRange = clockViewModel.clockRange;

      if (that.shuttleRingDragging || clockRange === ClockRange$1.UNBOUNDED) {
        return true;
      }

      const multiplier = clockViewModel.multiplier;
      const currentTime = clockViewModel.currentTime;
      const startTime = clockViewModel.startTime;

      let result = false;
      if (clockRange === ClockRange$1.LOOP_STOP) {
        result =
          JulianDate.greaterThan(currentTime, startTime) ||
          (currentTime.equals(startTime) && multiplier > 0);
      } else {
        const stopTime = clockViewModel.stopTime;
        result =
          (JulianDate.greaterThan(currentTime, startTime) &&
            JulianDate.lessThan(currentTime, stopTime)) || //
          (currentTime.equals(startTime) && multiplier > 0) || //
          (currentTime.equals(stopTime) && multiplier < 0);
      }

      if (!result) {
        clockViewModel.shouldAnimate = false;
      }
      return result;
    });

    this._isSystemTimeAvailable = undefined;
    knockout.defineProperty(this, "_isSystemTimeAvailable", function () {
      const clockViewModel = that._clockViewModel;
      const clockRange = clockViewModel.clockRange;
      if (clockRange === ClockRange$1.UNBOUNDED) {
        return true;
      }

      const systemTime = clockViewModel.systemTime;
      return (
        JulianDate.greaterThanOrEquals(systemTime, clockViewModel.startTime) &&
        JulianDate.lessThanOrEquals(systemTime, clockViewModel.stopTime)
      );
    });

    this._isAnimating = undefined;
    knockout.defineProperty(this, "_isAnimating", function () {
      return (
        that._clockViewModel.shouldAnimate &&
        (that._canAnimate || that.shuttleRingDragging)
      );
    });

    const pauseCommand = createCommand(function () {
      const clockViewModel = that._clockViewModel;
      if (clockViewModel.shouldAnimate) {
        clockViewModel.shouldAnimate = false;
      } else if (that._canAnimate) {
        clockViewModel.shouldAnimate = true;
      }
    });

    this._pauseViewModel = new ToggleButtonViewModel(pauseCommand, {
      toggled: knockout.computed(function () {
        return !that._isAnimating;
      }),
      tooltip: "Pause",
    });

    const playReverseCommand = createCommand(function () {
      const clockViewModel = that._clockViewModel;
      const multiplier = clockViewModel.multiplier;
      if (multiplier > 0) {
        clockViewModel.multiplier = -multiplier;
      }
      clockViewModel.shouldAnimate = true;
    });

    this._playReverseViewModel = new ToggleButtonViewModel(playReverseCommand, {
      toggled: knockout.computed(function () {
        return that._isAnimating && clockViewModel.multiplier < 0;
      }),
      tooltip: "Play Reverse",
    });

    const playForwardCommand = createCommand(function () {
      const clockViewModel = that._clockViewModel;
      const multiplier = clockViewModel.multiplier;
      if (multiplier < 0) {
        clockViewModel.multiplier = -multiplier;
      }
      clockViewModel.shouldAnimate = true;
    });

    this._playForwardViewModel = new ToggleButtonViewModel(playForwardCommand, {
      toggled: knockout.computed(function () {
        return (
          that._isAnimating &&
          clockViewModel.multiplier > 0 &&
          clockViewModel.clockStep !== ClockStep$1.SYSTEM_CLOCK
        );
      }),
      tooltip: "Play Forward",
    });

    const playRealtimeCommand = createCommand(function () {
      that._clockViewModel.clockStep = ClockStep$1.SYSTEM_CLOCK;
    }, knockout.getObservable(this, "_isSystemTimeAvailable"));

    this._playRealtimeViewModel = new ToggleButtonViewModel(playRealtimeCommand, {
      toggled: knockout.computed(function () {
        return clockViewModel.clockStep === ClockStep$1.SYSTEM_CLOCK;
      }),
      tooltip: knockout.computed(function () {
        return that._isSystemTimeAvailable
          ? "Today (real-time)"
          : "Current time not in range";
      }),
    });

    this._slower = createCommand(function () {
      const clockViewModel = that._clockViewModel;
      const shuttleRingTicks = that._allShuttleRingTicks;
      const multiplier = clockViewModel.multiplier;
      const index = getTypicalMultiplierIndex(multiplier, shuttleRingTicks) - 1;
      if (index >= 0) {
        clockViewModel.multiplier = shuttleRingTicks[index];
      }
    });

    this._faster = createCommand(function () {
      const clockViewModel = that._clockViewModel;
      const shuttleRingTicks = that._allShuttleRingTicks;
      const multiplier = clockViewModel.multiplier;
      const index = getTypicalMultiplierIndex(multiplier, shuttleRingTicks) + 1;
      if (index < shuttleRingTicks.length) {
        clockViewModel.multiplier = shuttleRingTicks[index];
      }
    });
  }

  /**
   * Gets or sets the default date formatter used by new instances.
   *
   * @member
   * @type {AnimationViewModel.DateFormatter}
   */
  AnimationViewModel.defaultDateFormatter = function (date, viewModel) {
    const gregorianDate = JulianDate.toGregorianDate(date);
    return `${monthNames[gregorianDate.month - 1]} ${gregorianDate.day} ${
    gregorianDate.year
  }`;
  };

  /**
   * Gets or sets the default array of known clock multipliers associated with new instances of the shuttle ring.
   * @type {Number[]}
   */
  AnimationViewModel.defaultTicks = [
    //
    0.001,
    0.002,
    0.005,
    0.01,
    0.02,
    0.05,
    0.1,
    0.25,
    0.5,
    1.0,
    2.0,
    5.0,
    10.0, //
    15.0,
    30.0,
    60.0,
    120.0,
    300.0,
    600.0,
    900.0,
    1800.0,
    3600.0,
    7200.0,
    14400.0, //
    21600.0,
    43200.0,
    86400.0,
    172800.0,
    345600.0,
    604800.0,
  ];

  /**
   * Gets or sets the default time formatter used by new instances.
   *
   * @member
   * @type {AnimationViewModel.TimeFormatter}
   */
  AnimationViewModel.defaultTimeFormatter = function (date, viewModel) {
    const gregorianDate = JulianDate.toGregorianDate(date);
    const millisecond = Math.round(gregorianDate.millisecond);
    if (Math.abs(viewModel._clockViewModel.multiplier) < 1) {
      return `${gregorianDate.hour
      .toString()
      .padStart(2, "0")}:${gregorianDate.minute
      .toString()
      .padStart(2, "0")}:${gregorianDate.second
      .toString()
      .padStart(2, "0")}.${millisecond.toString().padStart(3, "0")}`;
    }
    return `${gregorianDate.hour
    .toString()
    .padStart(2, "0")}:${gregorianDate.minute
    .toString()
    .padStart(2, "0")}:${gregorianDate.second.toString().padStart(2, "0")} UTC`;
  };

  /**
   * Gets a copy of the array of positive known clock multipliers to associate with the shuttle ring.
   *
   * @returns {Number[]} The array of known clock multipliers associated with the shuttle ring.
   */
  AnimationViewModel.prototype.getShuttleRingTicks = function () {
    return this._sortedFilteredPositiveTicks.slice(0);
  };

  /**
   * Sets the array of positive known clock multipliers to associate with the shuttle ring.
   * These values will have negative equivalents created for them and sets both the minimum
   * and maximum range of values for the shuttle ring as well as the values that are snapped
   * to when a single click is made.  The values need not be in order, as they will be sorted
   * automatically, and duplicate values will be removed.
   *
   * @param {Number[]} positiveTicks The list of known positive clock multipliers to associate with the shuttle ring.
   */
  AnimationViewModel.prototype.setShuttleRingTicks = function (positiveTicks) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(positiveTicks)) {
      throw new DeveloperError("positiveTicks is required.");
    }
    //>>includeEnd('debug');

    let i;
    let len;
    let tick;

    const hash = {};
    const sortedFilteredPositiveTicks = this._sortedFilteredPositiveTicks;
    sortedFilteredPositiveTicks.length = 0;
    for (i = 0, len = positiveTicks.length; i < len; ++i) {
      tick = positiveTicks[i];
      //filter duplicates
      if (!hash.hasOwnProperty(tick)) {
        hash[tick] = true;
        sortedFilteredPositiveTicks.push(tick);
      }
    }
    sortedFilteredPositiveTicks.sort(numberComparator);

    const allTicks = [];
    for (len = sortedFilteredPositiveTicks.length, i = len - 1; i >= 0; --i) {
      tick = sortedFilteredPositiveTicks[i];
      if (tick !== 0) {
        allTicks.push(-tick);
      }
    }
    Array.prototype.push.apply(allTicks, sortedFilteredPositiveTicks);

    this._allShuttleRingTicks = allTicks;
  };

  Object.defineProperties(AnimationViewModel.prototype, {
    /**
     * Gets a command that decreases the speed of animation.
     * @memberof AnimationViewModel.prototype
     * @type {Command}
     */
    slower: {
      get: function () {
        return this._slower;
      },
    },

    /**
     * Gets a command that increases the speed of animation.
     * @memberof AnimationViewModel.prototype
     * @type {Command}
     */
    faster: {
      get: function () {
        return this._faster;
      },
    },

    /**
     * Gets the clock view model.
     * @memberof AnimationViewModel.prototype
     *
     * @type {ClockViewModel}
     */
    clockViewModel: {
      get: function () {
        return this._clockViewModel;
      },
    },

    /**
     * Gets the pause toggle button view model.
     * @memberof AnimationViewModel.prototype
     *
     * @type {ToggleButtonViewModel}
     */
    pauseViewModel: {
      get: function () {
        return this._pauseViewModel;
      },
    },

    /**
     * Gets the reverse toggle button view model.
     * @memberof AnimationViewModel.prototype
     *
     * @type {ToggleButtonViewModel}
     */
    playReverseViewModel: {
      get: function () {
        return this._playReverseViewModel;
      },
    },

    /**
     * Gets the play toggle button view model.
     * @memberof AnimationViewModel.prototype
     *
     * @type {ToggleButtonViewModel}
     */
    playForwardViewModel: {
      get: function () {
        return this._playForwardViewModel;
      },
    },

    /**
     * Gets the realtime toggle button view model.
     * @memberof AnimationViewModel.prototype
     *
     * @type {ToggleButtonViewModel}
     */
    playRealtimeViewModel: {
      get: function () {
        return this._playRealtimeViewModel;
      },
    },

    /**
     * Gets or sets the function which formats a date for display.
     * @memberof AnimationViewModel.prototype
     *
     * @type {AnimationViewModel.DateFormatter}
     * @default AnimationViewModel.defaultDateFormatter
     */
    dateFormatter: {
      //TODO:@exception {DeveloperError} dateFormatter must be a function.
      get: function () {
        return this._dateFormatter;
      },
      set: function (dateFormatter) {
        //>>includeStart('debug', pragmas.debug);
        if (typeof dateFormatter !== "function") {
          throw new DeveloperError("dateFormatter must be a function");
        }
        //>>includeEnd('debug');

        this._dateFormatter = dateFormatter;
      },
    },

    /**
     * Gets or sets the function which formats a time for display.
     * @memberof AnimationViewModel.prototype
     *
     * @type {AnimationViewModel.TimeFormatter}
     * @default AnimationViewModel.defaultTimeFormatter
     */
    timeFormatter: {
      //TODO:@exception {DeveloperError} timeFormatter must be a function.
      get: function () {
        return this._timeFormatter;
      },
      set: function (timeFormatter) {
        //>>includeStart('debug', pragmas.debug);
        if (typeof timeFormatter !== "function") {
          throw new DeveloperError("timeFormatter must be a function");
        }
        //>>includeEnd('debug');

        this._timeFormatter = timeFormatter;
      },
    },
  });

  //Currently exposed for tests.
  AnimationViewModel._maxShuttleRingAngle = maxShuttleRingAngle;
  AnimationViewModel._realtimeShuttleRingAngle = realtimeShuttleRingAngle;

  /**
   * The view model for {@link BaseLayerPicker}.
   * @alias BaseLayerPickerViewModel
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Globe} options.globe The Globe to use.
   * @param {ProviderViewModel[]} [options.imageryProviderViewModels=[]] The array of ProviderViewModel instances to use for imagery.
   * @param {ProviderViewModel} [options.selectedImageryProviderViewModel] The view model for the current base imagery layer, if not supplied the first available imagery layer is used.
   * @param {ProviderViewModel[]} [options.terrainProviderViewModels=[]] The array of ProviderViewModel instances to use for terrain.
   * @param {ProviderViewModel} [options.selectedTerrainProviderViewModel] The view model for the current base terrain layer, if not supplied the first available terrain layer is used.
   *
   * @exception {DeveloperError} imageryProviderViewModels must be an array.
   * @exception {DeveloperError} terrainProviderViewModels must be an array.
   */
  function BaseLayerPickerViewModel(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const globe = options.globe;
    const imageryProviderViewModels = defaultValue(
      options.imageryProviderViewModels,
      []
    );
    const terrainProviderViewModels = defaultValue(
      options.terrainProviderViewModels,
      []
    );

    //>>includeStart('debug', pragmas.debug);
    if (!defined(globe)) {
      throw new DeveloperError("globe is required");
    }
    //>>includeEnd('debug');

    this._globe = globe;

    /**
     * Gets or sets an array of ProviderViewModel instances available for imagery selection.
     * This property is observable.
     * @type {ProviderViewModel[]}
     */
    this.imageryProviderViewModels = imageryProviderViewModels.slice(0);

    /**
     * Gets or sets an array of ProviderViewModel instances available for terrain selection.
     * This property is observable.
     * @type {ProviderViewModel[]}
     */
    this.terrainProviderViewModels = terrainProviderViewModels.slice(0);

    /**
     * Gets or sets whether the imagery selection drop-down is currently visible.
     * @type {Boolean}
     * @default false
     */
    this.dropDownVisible = false;

    knockout.track(this, [
      "imageryProviderViewModels",
      "terrainProviderViewModels",
      "dropDownVisible",
    ]);

    const imageryObservable = knockout.getObservable(
      this,
      "imageryProviderViewModels"
    );
    const imageryProviders = knockout.pureComputed(function () {
      const providers = imageryObservable();
      const categories = {};
      let i;
      for (i = 0; i < providers.length; i++) {
        const provider = providers[i];
        const category = provider.category;
        if (defined(categories[category])) {
          categories[category].push(provider);
        } else {
          categories[category] = [provider];
        }
      }
      const allCategoryNames = Object.keys(categories);

      const result = [];
      for (i = 0; i < allCategoryNames.length; i++) {
        const name = allCategoryNames[i];
        result.push({
          name: name,
          providers: categories[name],
        });
      }
      return result;
    });
    this._imageryProviders = imageryProviders;

    const terrainObservable = knockout.getObservable(
      this,
      "terrainProviderViewModels"
    );
    const terrainProviders = knockout.pureComputed(function () {
      const providers = terrainObservable();
      const categories = {};
      let i;
      for (i = 0; i < providers.length; i++) {
        const provider = providers[i];
        const category = provider.category;
        if (defined(categories[category])) {
          categories[category].push(provider);
        } else {
          categories[category] = [provider];
        }
      }
      const allCategoryNames = Object.keys(categories);

      const result = [];
      for (i = 0; i < allCategoryNames.length; i++) {
        const name = allCategoryNames[i];
        result.push({
          name: name,
          providers: categories[name],
        });
      }
      return result;
    });
    this._terrainProviders = terrainProviders;

    /**
     * Gets the button tooltip.  This property is observable.
     * @type {String}
     */
    this.buttonTooltip = undefined;
    knockout.defineProperty(this, "buttonTooltip", function () {
      const selectedImagery = this.selectedImagery;
      const selectedTerrain = this.selectedTerrain;

      const imageryTip = defined(selectedImagery)
        ? selectedImagery.name
        : undefined;
      const terrainTip = defined(selectedTerrain)
        ? selectedTerrain.name
        : undefined;

      if (defined(imageryTip) && defined(terrainTip)) {
        return `${imageryTip}\n${terrainTip}`;
      } else if (defined(imageryTip)) {
        return imageryTip;
      }
      return terrainTip;
    });

    /**
     * Gets the button background image.  This property is observable.
     * @type {String}
     */
    this.buttonImageUrl = undefined;
    knockout.defineProperty(this, "buttonImageUrl", function () {
      const selectedImagery = this.selectedImagery;
      if (defined(selectedImagery)) {
        return selectedImagery.iconUrl;
      }
    });

    /**
     * Gets or sets the currently selected imagery.  This property is observable.
     * @type {ProviderViewModel}
     * @default undefined
     */
    this.selectedImagery = undefined;
    const selectedImageryViewModel = knockout.observable();

    this._currentImageryProviders = [];
    knockout.defineProperty(this, "selectedImagery", {
      get: function () {
        return selectedImageryViewModel();
      },
      set: function (value) {
        if (selectedImageryViewModel() === value) {
          this.dropDownVisible = false;
          return;
        }

        let i;
        const currentImageryProviders = this._currentImageryProviders;
        const currentImageryProvidersLength = currentImageryProviders.length;
        const imageryLayers = this._globe.imageryLayers;
        let hadExistingBaseLayer = false;
        for (i = 0; i < currentImageryProvidersLength; i++) {
          const layersLength = imageryLayers.length;
          for (let x = 0; x < layersLength; x++) {
            const layer = imageryLayers.get(x);
            if (layer.imageryProvider === currentImageryProviders[i]) {
              imageryLayers.remove(layer);
              hadExistingBaseLayer = true;
              break;
            }
          }
        }

        if (defined(value)) {
          const newProviders = value.creationCommand();
          if (Array.isArray(newProviders)) {
            const newProvidersLength = newProviders.length;
            for (i = newProvidersLength - 1; i >= 0; i--) {
              imageryLayers.addImageryProvider(newProviders[i], 0);
            }
            this._currentImageryProviders = newProviders.slice(0);
          } else {
            this._currentImageryProviders = [newProviders];
            if (hadExistingBaseLayer) {
              imageryLayers.addImageryProvider(newProviders, 0);
            } else {
              const baseLayer = imageryLayers.get(0);
              if (defined(baseLayer)) {
                imageryLayers.remove(baseLayer);
              }
              imageryLayers.addImageryProvider(newProviders, 0);
            }
          }
        }
        selectedImageryViewModel(value);
        this.dropDownVisible = false;
      },
    });

    /**
     * Gets or sets the currently selected terrain.  This property is observable.
     * @type {ProviderViewModel}
     * @default undefined
     */
    this.selectedTerrain = undefined;
    const selectedTerrainViewModel = knockout.observable();

    knockout.defineProperty(this, "selectedTerrain", {
      get: function () {
        return selectedTerrainViewModel();
      },
      set: function (value) {
        if (selectedTerrainViewModel() === value) {
          this.dropDownVisible = false;
          return;
        }

        let newProvider;
        if (defined(value)) {
          newProvider = value.creationCommand();
        }

        this._globe.depthTestAgainstTerrain = !(
          newProvider instanceof EllipsoidTerrainProvider
        );
        this._globe.terrainProvider = newProvider;
        selectedTerrainViewModel(value);
        this.dropDownVisible = false;
      },
    });

    const that = this;
    this._toggleDropDown = createCommand(function () {
      that.dropDownVisible = !that.dropDownVisible;
    });

    this.selectedImagery = defaultValue(
      options.selectedImageryProviderViewModel,
      imageryProviderViewModels[0]
    );
    this.selectedTerrain = defaultValue(
      options.selectedTerrainProviderViewModel,
      terrainProviderViewModels[0]
    );
  }

  Object.defineProperties(BaseLayerPickerViewModel.prototype, {
    /**
     * Gets the command to toggle the visibility of the drop down.
     * @memberof BaseLayerPickerViewModel.prototype
     *
     * @type {Command}
     */
    toggleDropDown: {
      get: function () {
        return this._toggleDropDown;
      },
    },

    /**
     * Gets the globe.
     * @memberof BaseLayerPickerViewModel.prototype
     *
     * @type {Globe}
     */
    globe: {
      get: function () {
        return this._globe;
      },
    },
  });

  /**
   * <span style="display: block; text-align: center;">
   * <img src="Images/BaseLayerPicker.png" width="264" height="287" alt="" />
   * <br />BaseLayerPicker with its drop-panel open.
   * </span>
   * <br /><br />
   * The BaseLayerPicker is a single button widget that displays a panel of available imagery and
   * terrain providers.  When imagery is selected, the corresponding imagery layer is created and inserted
   * as the base layer of the imagery collection; removing the existing base.  When terrain is selected,
   * it replaces the current terrain provider.  Each item in the available providers list contains a name,
   * a representative icon, and a tooltip to display more information when hovered. The list is initially
   * empty, and must be configured before use, as illustrated in the below example.
   *
   * @alias BaseLayerPicker
   * @constructor
   *
   * @param {Element|String} container The parent HTML container node or ID for this widget.
   * @param {Object} options Object with the following properties:
   * @param {Globe} options.globe The Globe to use.
   * @param {ProviderViewModel[]} [options.imageryProviderViewModels=[]] The array of ProviderViewModel instances to use for imagery.
   * @param {ProviderViewModel} [options.selectedImageryProviderViewModel] The view model for the current base imagery layer, if not supplied the first available imagery layer is used.
   * @param {ProviderViewModel[]} [options.terrainProviderViewModels=[]] The array of ProviderViewModel instances to use for terrain.
   * @param {ProviderViewModel} [options.selectedTerrainProviderViewModel] The view model for the current base terrain layer, if not supplied the first available terrain layer is used.
   *
   * @exception {DeveloperError} Element with id "container" does not exist in the document.
   *
   *
   * @example
   * // In HTML head, include a link to the BaseLayerPicker.css stylesheet,
   * // and in the body, include: <div id="baseLayerPickerContainer"
   * //   style="position:absolute;top:24px;right:24px;width:38px;height:38px;"></div>
   *
   * //Create the list of available providers we would like the user to select from.
   * //This example uses 3, OpenStreetMap, The Black Marble, and a single, non-streaming world image.
   * const imageryViewModels = [];
   * imageryViewModels.push(new Cesium.ProviderViewModel({
   *      name : 'Open\u00adStreet\u00adMap',
   *      iconUrl : Cesium.buildModuleUrl('Widgets/Images/ImageryProviders/openStreetMap.png'),
   *      tooltip : 'OpenStreetMap (OSM) is a collaborative project to create a free editable \
   * map of the world.\nhttp://www.openstreetmap.org',
   *      creationFunction : function() {
   *          return new Cesium.OpenStreetMapImageryProvider({
   *              url : 'https://a.tile.openstreetmap.org/'
   *          });
   *      }
   *  }));
   *
   *  imageryViewModels.push(new Cesium.ProviderViewModel({
   *      name : 'Earth at Night',
   *      iconUrl : Cesium.buildModuleUrl('Widgets/Images/ImageryProviders/blackMarble.png'),
   *      tooltip : 'The lights of cities and villages trace the outlines of civilization \
   * in this global view of the Earth at night as seen by NASA/NOAA\'s Suomi NPP satellite.',
   *      creationFunction : function() {
   *          return new Cesium.IonImageryProvider({ assetId: 3812 });
   *      }
   *  }));
   *
   *  imageryViewModels.push(new Cesium.ProviderViewModel({
   *      name : 'Natural Earth\u00a0II',
   *      iconUrl : Cesium.buildModuleUrl('Widgets/Images/ImageryProviders/naturalEarthII.png'),
   *      tooltip : 'Natural Earth II, darkened for contrast.\nhttp://www.naturalearthdata.com/',
   *      creationFunction : function() {
   *          return new Cesium.TileMapServiceImageryProvider({
   *              url : Cesium.buildModuleUrl('Assets/Textures/NaturalEarthII')
   *          });
   *      }
   *  }));
   *
   * //Create a CesiumWidget without imagery, if you haven't already done so.
   * const cesiumWidget = new Cesium.CesiumWidget('cesiumContainer', { imageryProvider: false });
   *
   * //Finally, create the baseLayerPicker widget using our view models.
   * const layers = cesiumWidget.imageryLayers;
   * const baseLayerPicker = new Cesium.BaseLayerPicker('baseLayerPickerContainer', {
   *     globe : cesiumWidget.scene.globe,
   *     imageryProviderViewModels : imageryViewModels
   * });
   *
   * @see TerrainProvider
   * @see ImageryProvider
   * @see ImageryLayerCollection
   */
  function BaseLayerPicker(container, options) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(container)) {
      throw new DeveloperError("container is required.");
    }
    //>>includeEnd('debug');

    container = getElement(container);

    const viewModel = new BaseLayerPickerViewModel(options);

    const element = document.createElement("button");
    element.type = "button";
    element.className = "cesium-button cesium-toolbar-button";
    element.setAttribute(
      "data-bind",
      "\
attr: { title: buttonTooltip },\
click: toggleDropDown"
    );
    container.appendChild(element);

    const imgElement = document.createElement("img");
    imgElement.setAttribute("draggable", "false");
    imgElement.className = "cesium-baseLayerPicker-selected";
    imgElement.setAttribute(
      "data-bind",
      "\
attr: { src: buttonImageUrl }, visible: !!buttonImageUrl"
    );
    element.appendChild(imgElement);

    const dropPanel = document.createElement("div");
    dropPanel.className = "cesium-baseLayerPicker-dropDown";
    dropPanel.setAttribute(
      "data-bind",
      '\
css: { "cesium-baseLayerPicker-dropDown-visible" : dropDownVisible }'
    );
    container.appendChild(dropPanel);

    const imageryTitle = document.createElement("div");
    imageryTitle.className = "cesium-baseLayerPicker-sectionTitle";
    imageryTitle.setAttribute(
      "data-bind",
      "visible: imageryProviderViewModels.length > 0"
    );
    imageryTitle.innerHTML = "Imagery";
    dropPanel.appendChild(imageryTitle);

    const imagerySection = document.createElement("div");
    imagerySection.className = "cesium-baseLayerPicker-section";
    imagerySection.setAttribute("data-bind", "foreach: _imageryProviders");
    dropPanel.appendChild(imagerySection);

    const imageryCategories = document.createElement("div");
    imageryCategories.className = "cesium-baseLayerPicker-category";
    imagerySection.appendChild(imageryCategories);

    const categoryTitle = document.createElement("div");
    categoryTitle.className = "cesium-baseLayerPicker-categoryTitle";
    categoryTitle.setAttribute("data-bind", "text: name");
    imageryCategories.appendChild(categoryTitle);

    const imageryChoices = document.createElement("div");
    imageryChoices.className = "cesium-baseLayerPicker-choices";
    imageryChoices.setAttribute("data-bind", "foreach: providers");
    imageryCategories.appendChild(imageryChoices);

    const imageryProvider = document.createElement("div");
    imageryProvider.className = "cesium-baseLayerPicker-item";
    imageryProvider.setAttribute(
      "data-bind",
      '\
css: { "cesium-baseLayerPicker-selectedItem" : $data === $parents[1].selectedImagery },\
attr: { title: tooltip },\
visible: creationCommand.canExecute,\
click: function($data) { $parents[1].selectedImagery = $data; }'
    );
    imageryChoices.appendChild(imageryProvider);

    const providerIcon = document.createElement("img");
    providerIcon.className = "cesium-baseLayerPicker-itemIcon";
    providerIcon.setAttribute("data-bind", "attr: { src: iconUrl }");
    providerIcon.setAttribute("draggable", "false");
    imageryProvider.appendChild(providerIcon);

    const providerLabel = document.createElement("div");
    providerLabel.className = "cesium-baseLayerPicker-itemLabel";
    providerLabel.setAttribute("data-bind", "text: name");
    imageryProvider.appendChild(providerLabel);

    const terrainTitle = document.createElement("div");
    terrainTitle.className = "cesium-baseLayerPicker-sectionTitle";
    terrainTitle.setAttribute(
      "data-bind",
      "visible: terrainProviderViewModels.length > 0"
    );
    terrainTitle.innerHTML = "Terrain";
    dropPanel.appendChild(terrainTitle);

    const terrainSection = document.createElement("div");
    terrainSection.className = "cesium-baseLayerPicker-section";
    terrainSection.setAttribute("data-bind", "foreach: _terrainProviders");
    dropPanel.appendChild(terrainSection);

    const terrainCategories = document.createElement("div");
    terrainCategories.className = "cesium-baseLayerPicker-category";
    terrainSection.appendChild(terrainCategories);

    const terrainCategoryTitle = document.createElement("div");
    terrainCategoryTitle.className = "cesium-baseLayerPicker-categoryTitle";
    terrainCategoryTitle.setAttribute("data-bind", "text: name");
    terrainCategories.appendChild(terrainCategoryTitle);

    const terrainChoices = document.createElement("div");
    terrainChoices.className = "cesium-baseLayerPicker-choices";
    terrainChoices.setAttribute("data-bind", "foreach: providers");
    terrainCategories.appendChild(terrainChoices);

    const terrainProvider = document.createElement("div");
    terrainProvider.className = "cesium-baseLayerPicker-item";
    terrainProvider.setAttribute(
      "data-bind",
      '\
css: { "cesium-baseLayerPicker-selectedItem" : $data === $parents[1].selectedTerrain },\
attr: { title: tooltip },\
visible: creationCommand.canExecute,\
click: function($data) { $parents[1].selectedTerrain = $data; }'
    );
    terrainChoices.appendChild(terrainProvider);

    const terrainProviderIcon = document.createElement("img");
    terrainProviderIcon.className = "cesium-baseLayerPicker-itemIcon";
    terrainProviderIcon.setAttribute("data-bind", "attr: { src: iconUrl }");
    terrainProviderIcon.setAttribute("draggable", "false");
    terrainProvider.appendChild(terrainProviderIcon);

    const terrainProviderLabel = document.createElement("div");
    terrainProviderLabel.className = "cesium-baseLayerPicker-itemLabel";
    terrainProviderLabel.setAttribute("data-bind", "text: name");
    terrainProvider.appendChild(terrainProviderLabel);

    knockout.applyBindings(viewModel, element);
    knockout.applyBindings(viewModel, dropPanel);

    this._viewModel = viewModel;
    this._container = container;
    this._element = element;
    this._dropPanel = dropPanel;

    this._closeDropDown = function (e) {
      if (!(element.contains(e.target) || dropPanel.contains(e.target))) {
        viewModel.dropDownVisible = false;
      }
    };

    if (FeatureDetection.supportsPointerEvents()) {
      document.addEventListener("pointerdown", this._closeDropDown, true);
    } else {
      document.addEventListener("mousedown", this._closeDropDown, true);
      document.addEventListener("touchstart", this._closeDropDown, true);
    }
  }

  Object.defineProperties(BaseLayerPicker.prototype, {
    /**
     * Gets the parent container.
     * @memberof BaseLayerPicker.prototype
     *
     * @type {Element}
     */
    container: {
      get: function () {
        return this._container;
      },
    },

    /**
     * Gets the view model.
     * @memberof BaseLayerPicker.prototype
     *
     * @type {BaseLayerPickerViewModel}
     */
    viewModel: {
      get: function () {
        return this._viewModel;
      },
    },
  });

  /**
   * @returns {Boolean} true if the object has been destroyed, false otherwise.
   */
  BaseLayerPicker.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the widget.  Should be called if permanently
   * removing the widget from layout.
   */
  BaseLayerPicker.prototype.destroy = function () {
    if (FeatureDetection.supportsPointerEvents()) {
      document.removeEventListener("pointerdown", this._closeDropDown, true);
    } else {
      document.removeEventListener("mousedown", this._closeDropDown, true);
      document.removeEventListener("touchstart", this._closeDropDown, true);
    }

    knockout.cleanNode(this._element);
    knockout.cleanNode(this._dropPanel);
    this._container.removeChild(this._element);
    this._container.removeChild(this._dropPanel);
    return destroyObject(this);
  };

  /**
   * A view model that represents each item in the {@link BaseLayerPicker}.
   *
   * @alias ProviderViewModel
   * @constructor
   *
   * @param {Object} options The object containing all parameters.
   * @param {String} options.name The name of the layer.
   * @param {String} options.tooltip The tooltip to show when the item is moused over.
   * @param {String} options.iconUrl An icon representing the layer.
   * @param {String} [options.category] A category for the layer.
   * @param {ProviderViewModel.CreationFunction|Command} options.creationFunction A function or Command
   *        that creates one or more providers which will be added to the globe when this item is selected.
   *
   * @see BaseLayerPicker
   * @see ImageryProvider
   * @see TerrainProvider
   */
  function ProviderViewModel(options) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(options.name)) {
      throw new DeveloperError("options.name is required.");
    }
    if (!defined(options.tooltip)) {
      throw new DeveloperError("options.tooltip is required.");
    }
    if (!defined(options.iconUrl)) {
      throw new DeveloperError("options.iconUrl is required.");
    }
    if (typeof options.creationFunction !== "function") {
      throw new DeveloperError("options.creationFunction is required.");
    }
    //>>includeEnd('debug');

    let creationCommand = options.creationFunction;
    if (!defined(creationCommand.canExecute)) {
      creationCommand = createCommand(creationCommand);
    }

    this._creationCommand = creationCommand;

    /**
     * Gets the display name.  This property is observable.
     * @type {String}
     */
    this.name = options.name;

    /**
     * Gets the tooltip.  This property is observable.
     * @type {String}
     */
    this.tooltip = options.tooltip;

    /**
     * Gets the icon.  This property is observable.
     * @type {String}
     */
    this.iconUrl = options.iconUrl;

    this._category = defaultValue(options.category, "");

    knockout.track(this, ["name", "tooltip", "iconUrl"]);
  }

  Object.defineProperties(ProviderViewModel.prototype, {
    /**
     * Gets the Command that creates one or more providers which will be added to
     * the globe when this item is selected.
     * @memberof ProviderViewModel.prototype
     * @memberof ProviderViewModel.prototype
     * @type {Command}
     * @readonly
     */
    creationCommand: {
      get: function () {
        return this._creationCommand;
      },
    },

    /**
     * Gets the category
     * @type {String}
     * @memberof ProviderViewModel.prototype
     * @readonly
     */
    category: {
      get: function () {
        return this._category;
      },
    },
  });

  /**
   * @private
   */
  function createDefaultImageryProviderViewModels() {
    const providerViewModels = [];
    providerViewModels.push(
      new ProviderViewModel({
        name: "Bing Maps Aerial",
        iconUrl: buildModuleUrl("Widgets/Images/ImageryProviders/bingAerial.png"),
        tooltip: "Bing Maps aerial imagery, provided by Cesium ion",
        category: "Cesium ion",
        creationFunction: function () {
          return createWorldImagery({
            style: IonWorldImageryStyle$1.AERIAL,
          });
        },
      })
    );

    providerViewModels.push(
      new ProviderViewModel({
        name: "Bing Maps Aerial with Labels",
        iconUrl: buildModuleUrl(
          "Widgets/Images/ImageryProviders/bingAerialLabels.png"
        ),
        tooltip: "Bing Maps aerial imagery with labels, provided by Cesium ion",
        category: "Cesium ion",
        creationFunction: function () {
          return createWorldImagery({
            style: IonWorldImageryStyle$1.AERIAL_WITH_LABELS,
          });
        },
      })
    );

    providerViewModels.push(
      new ProviderViewModel({
        name: "Bing Maps Roads",
        iconUrl: buildModuleUrl("Widgets/Images/ImageryProviders/bingRoads.png"),
        tooltip: "Bing Maps standard road maps, provided by Cesium ion",
        category: "Cesium ion",
        creationFunction: function () {
          return createWorldImagery({
            style: IonWorldImageryStyle$1.ROAD,
          });
        },
      })
    );

    providerViewModels.push(
      new ProviderViewModel({
        name: "ESRI World Imagery",
        iconUrl: buildModuleUrl(
          "Widgets/Images/ImageryProviders/esriWorldImagery.png"
        ),
        tooltip:
          "\
World Imagery provides one meter or better satellite and aerial imagery in many parts of the world and lower resolution \
satellite imagery worldwide.  The map includes NASA Blue Marble: Next Generation 500m resolution imagery at small scales \
(above 1:1,000,000), i-cubed 15m eSAT imagery at medium-to-large scales (down to 1:70,000) for the world, and USGS 15m Landsat \
imagery for Antarctica. The map features 0.3m resolution imagery in the continental United States and 0.6m resolution imagery in \
parts of Western Europe from DigitalGlobe. In other parts of the world, 1 meter resolution imagery is available from GeoEye IKONOS, \
i-cubed Nationwide Prime, Getmapping, AeroGRID, IGN Spain, and IGP Portugal.  Additionally, imagery at different resolutions has been \
contributed by the GIS User Community.\nhttp://www.esri.com",
        category: "Other",
        creationFunction: function () {
          return new ArcGisMapServerImageryProvider({
            url:
              "https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer",
            enablePickFeatures: false,
          });
        },
      })
    );

    providerViewModels.push(
      new ProviderViewModel({
        name: "ESRI World Street Map",
        iconUrl: buildModuleUrl(
          "Widgets/Images/ImageryProviders/esriWorldStreetMap.png"
        ),
        tooltip:
          "\
This worldwide street map presents highway-level data for the world. Street-level data includes the United States; much of \
Canada; Japan; most countries in Europe; Australia and New Zealand; India; parts of South America including Argentina, Brazil, \
Chile, Colombia, and Venezuela; Ghana; and parts of southern Africa including Botswana, Lesotho, Namibia, South Africa, and Swaziland.\n\
http://www.esri.com",
        category: "Other",
        creationFunction: function () {
          return new ArcGisMapServerImageryProvider({
            url:
              "https://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer",
            enablePickFeatures: false,
          });
        },
      })
    );

    providerViewModels.push(
      new ProviderViewModel({
        name: "ESRI National Geographic",
        iconUrl: buildModuleUrl(
          "Widgets/Images/ImageryProviders/esriNationalGeographic.png"
        ),
        tooltip:
          "\
This web map contains the National Geographic World Map service. This map service is designed to be used as a general reference map \
for informational and educational purposes as well as a basemap by GIS professionals and other users for creating web maps and web \
mapping applications.\nhttp://www.esri.com",
        category: "Other",
        creationFunction: function () {
          return new ArcGisMapServerImageryProvider({
            url:
              "https://services.arcgisonline.com/ArcGIS/rest/services/NatGeo_World_Map/MapServer/",
            enablePickFeatures: false,
          });
        },
      })
    );

    providerViewModels.push(
      new ProviderViewModel({
        name: "Open\u00adStreet\u00adMap",
        iconUrl: buildModuleUrl(
          "Widgets/Images/ImageryProviders/openStreetMap.png"
        ),
        tooltip:
          "OpenStreetMap (OSM) is a collaborative project to create a free editable map \
of the world.\nhttp://www.openstreetmap.org",
        category: "Other",
        creationFunction: function () {
          return new OpenStreetMapImageryProvider({
            url: "https://a.tile.openstreetmap.org/",
          });
        },
      })
    );

    providerViewModels.push(
      new ProviderViewModel({
        name: "Stamen Watercolor",
        iconUrl: buildModuleUrl(
          "Widgets/Images/ImageryProviders/stamenWatercolor.png"
        ),
        tooltip:
          "Reminiscent of hand drawn maps, Stamen watercolor maps apply raster effect \
area washes and organic edges over a paper texture to add warm pop to any map.\nhttp://maps.stamen.com",
        category: "Other",
        creationFunction: function () {
          return new OpenStreetMapImageryProvider({
            url: "https://stamen-tiles.a.ssl.fastly.net/watercolor/",
            credit:
              "Map tiles by Stamen Design, under CC BY 3.0. Data by OpenStreetMap, under CC BY SA.",
          });
        },
      })
    );

    providerViewModels.push(
      new ProviderViewModel({
        name: "Stamen Toner",
        iconUrl: buildModuleUrl(
          "Widgets/Images/ImageryProviders/stamenToner.png"
        ),
        tooltip: "A high contrast black and white map.\nhttp://maps.stamen.com",
        category: "Other",
        creationFunction: function () {
          return new OpenStreetMapImageryProvider({
            url: "https://stamen-tiles.a.ssl.fastly.net/toner/",
            credit:
              "Map tiles by Stamen Design, under CC BY 3.0. Data by OpenStreetMap, under CC BY SA.",
          });
        },
      })
    );

    providerViewModels.push(
      new ProviderViewModel({
        name: "Sentinel-2",
        iconUrl: buildModuleUrl("Widgets/Images/ImageryProviders/sentinel-2.png"),
        tooltip:
          "Sentinel-2 cloudless by EOX IT Services GmbH (Contains modified Copernicus Sentinel data 2016 and 2017).",
        category: "Cesium ion",
        creationFunction: function () {
          return new IonImageryProvider({ assetId: 3954 });
        },
      })
    );

    providerViewModels.push(
      new ProviderViewModel({
        name: "Blue Marble",
        iconUrl: buildModuleUrl("Widgets/Images/ImageryProviders/blueMarble.png"),
        tooltip: "Blue Marble Next Generation July, 2004 imagery from NASA.",
        category: "Cesium ion",
        creationFunction: function () {
          return new IonImageryProvider({ assetId: 3845 });
        },
      })
    );

    providerViewModels.push(
      new ProviderViewModel({
        name: "Earth at night",
        iconUrl: buildModuleUrl(
          "Widgets/Images/ImageryProviders/earthAtNight.png"
        ),
        tooltip:
          "The Earth at night, also known as The Black Marble, is a 500 meter resolution global composite imagery layer released by NASA.",
        category: "Cesium ion",
        creationFunction: function () {
          return new IonImageryProvider({ assetId: 3812 });
        },
      })
    );

    providerViewModels.push(
      new ProviderViewModel({
        name: "Natural Earth\u00a0II",
        iconUrl: buildModuleUrl(
          "Widgets/Images/ImageryProviders/naturalEarthII.png"
        ),
        tooltip:
          "Natural Earth II, darkened for contrast.\nhttp://www.naturalearthdata.com/",
        category: "Cesium ion",
        creationFunction: function () {
          return new TileMapServiceImageryProvider({
            url: buildModuleUrl("Assets/Textures/NaturalEarthII"),
          });
        },
      })
    );

    return providerViewModels;
  }

  /**
   * @private
   */
  function createDefaultTerrainProviderViewModels() {
    const providerViewModels = [];
    providerViewModels.push(
      new ProviderViewModel({
        name: "WGS84 Ellipsoid",
        iconUrl: buildModuleUrl("Widgets/Images/TerrainProviders/Ellipsoid.png"),
        tooltip: "WGS84 standard ellipsoid, also known as EPSG:4326",
        category: "Cesium ion",
        creationFunction: function () {
          return new EllipsoidTerrainProvider();
        },
      })
    );

    providerViewModels.push(
      new ProviderViewModel({
        name: "Cesium World Terrain",
        iconUrl: buildModuleUrl(
          "Widgets/Images/TerrainProviders/CesiumWorldTerrain.png"
        ),
        tooltip:
          "High-resolution global terrain tileset curated from several datasources and hosted by Cesium ion",
        category: "Cesium ion",
        creationFunction: function () {
          return createWorldTerrain({
            requestWaterMask: true,
            requestVertexNormals: true,
          });
        },
      })
    );

    return providerViewModels;
  }

  function getPickTileset(viewModel) {
    return function (e) {
      const pick = viewModel._scene.pick(e.position);
      if (defined(pick) && pick.primitive instanceof Cesium3DTileset) {
        viewModel.tileset = pick.primitive;
      }
      viewModel.pickActive = false;
    };
  }

  function selectTilesetOnHover(viewModel, value) {
    if (value) {
      viewModel._eventHandler.setInputAction(function (e) {
        const pick = viewModel._scene.pick(e.endPosition);
        if (defined(pick) && pick.primitive instanceof Cesium3DTileset) {
          viewModel.tileset = pick.primitive;
        }
      }, ScreenSpaceEventType$1.MOUSE_MOVE);
    } else {
      viewModel._eventHandler.removeInputAction(ScreenSpaceEventType$1.MOUSE_MOVE);

      // Restore hover-over selection to its current value
      // eslint-disable-next-line no-self-assign
      viewModel.picking = viewModel.picking;
    }
  }

  const stringOptions = {
    maximumFractionDigits: 3,
  };

  function formatMemoryString(memorySizeInBytes) {
    const memoryInMegabytes = memorySizeInBytes / 1048576;
    if (memoryInMegabytes < 1.0) {
      return memoryInMegabytes.toLocaleString(undefined, stringOptions);
    }
    return Math.round(memoryInMegabytes).toLocaleString();
  }

  function getStatistics(tileset, isPick) {
    if (!defined(tileset)) {
      return "";
    }

    const statistics = isPick
      ? tileset._statisticsPerPass[Cesium3DTilePass$1.PICK]
      : tileset._statisticsPerPass[Cesium3DTilePass$1.RENDER];

    // Since the pick pass uses a smaller frustum around the pixel of interest,
    // the statistics will be different than the normal render pass.
    let s = '<ul class="cesium-cesiumInspector-statistics">';
    s +=
      // --- Rendering statistics
      `<li><strong>Visited: </strong>${statistics.visited.toLocaleString()}</li>` +
      // Number of commands returned is likely to be higher than the number of tiles selected
      // because of tiles that create multiple commands.
      `<li><strong>Selected: </strong>${statistics.selected.toLocaleString()}</li>` +
      // Number of commands executed is likely to be higher because of commands overlapping
      // multiple frustums.
      `<li><strong>Commands: </strong>${statistics.numberOfCommands.toLocaleString()}</li>`;
    s += "</ul>";
    if (!isPick) {
      s += '<ul class="cesium-cesiumInspector-statistics">';
      s +=
        // --- Cache/loading statistics
        `<li><strong>Requests: </strong>${statistics.numberOfPendingRequests.toLocaleString()}</li>` +
        `<li><strong>Attempted: </strong>${statistics.numberOfAttemptedRequests.toLocaleString()}</li>` +
        `<li><strong>Processing: </strong>${statistics.numberOfTilesProcessing.toLocaleString()}</li>` +
        `<li><strong>Content Ready: </strong>${statistics.numberOfTilesWithContentReady.toLocaleString()}</li>` +
        // Total number of tiles includes tiles without content, so "Ready" may never reach
        // "Total."  Total also will increase when a tile with a tileset JSON content is loaded.
        `<li><strong>Total: </strong>${statistics.numberOfTilesTotal.toLocaleString()}</li>`;
      s += "</ul>";
      s += '<ul class="cesium-cesiumInspector-statistics">';
      s +=
        // --- Features statistics
        `<li><strong>Features Selected: </strong>${statistics.numberOfFeaturesSelected.toLocaleString()}</li>` +
        `<li><strong>Features Loaded: </strong>${statistics.numberOfFeaturesLoaded.toLocaleString()}</li>` +
        `<li><strong>Points Selected: </strong>${statistics.numberOfPointsSelected.toLocaleString()}</li>` +
        `<li><strong>Points Loaded: </strong>${statistics.numberOfPointsLoaded.toLocaleString()}</li>` +
        `<li><strong>Triangles Selected: </strong>${statistics.numberOfTrianglesSelected.toLocaleString()}</li>`;
      s += "</ul>";
      s += '<ul class="cesium-cesiumInspector-statistics">';
      s +=
        // --- Styling statistics
        `<li><strong>Tiles styled: </strong>${statistics.numberOfTilesStyled.toLocaleString()}</li>` +
        `<li><strong>Features styled: </strong>${statistics.numberOfFeaturesStyled.toLocaleString()}</li>`;
      s += "</ul>";
      s += '<ul class="cesium-cesiumInspector-statistics">';
      s +=
        // --- Optimization statistics
        `<li><strong>Children Union Culled: </strong>${statistics.numberOfTilesCulledWithChildrenUnion.toLocaleString()}</li>`;
      s += "</ul>";
      s += '<ul class="cesium-cesiumInspector-statistics">';
      s +=
        // --- Memory statistics
        `<li><strong>Geometry Memory (MB): </strong>${formatMemoryString(
        statistics.geometryByteLength
      )}</li>` +
        `<li><strong>Texture Memory (MB): </strong>${formatMemoryString(
        statistics.texturesByteLength
      )}</li>` +
        `<li><strong>Batch Table Memory (MB): </strong>${formatMemoryString(
        statistics.batchTableByteLength
      )}</li>`;
      s += "</ul>";
    }
    return s;
  }

  function getResourceCacheStatistics() {
    const statistics = ResourceCache.statistics;

    return `
  <ul class="cesium-cesiumInspector-statistics">
    <li><strong>Geometry Memory (MB): </strong>${formatMemoryString(
      statistics.geometryByteLength
    )}</li>
    <li><strong>Texture Memory (MB): </strong>${formatMemoryString(
      statistics.texturesByteLength
    )}</li>
  </ul>
  `;
  }

  const colorBlendModes = [
    {
      text: "Highlight",
      value: Cesium3DTileColorBlendMode$1.HIGHLIGHT,
    },
    {
      text: "Replace",
      value: Cesium3DTileColorBlendMode$1.REPLACE,
    },
    {
      text: "Mix",
      value: Cesium3DTileColorBlendMode$1.MIX,
    },
  ];

  const highlightColor = new Color(1.0, 1.0, 0.0, 0.4);
  const scratchColor = new Color();
  const oldColor = new Color();

  /**
   * The view model for {@link Cesium3DTilesInspector}.
   * @alias Cesium3DTilesInspectorViewModel
   * @constructor
   *
   * @param {Scene} scene The scene instance to use.
   * @param {HTMLElement} performanceContainer The container for the performance display
   */
  function Cesium3DTilesInspectorViewModel(scene, performanceContainer) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("scene", scene);
    Check.typeOf.object("performanceContainer", performanceContainer);
    //>>includeEnd('debug');

    const that = this;
    const canvas = scene.canvas;
    this._eventHandler = new ScreenSpaceEventHandler(canvas);
    this._scene = scene;
    this._performanceContainer = performanceContainer;
    this._canvas = canvas;

    this._performanceDisplay = new PerformanceDisplay({
      container: performanceContainer,
    });

    this._statisticsText = "";
    this._pickStatisticsText = "";
    this._resourceCacheStatisticsText = "";
    this._editorError = "";

    /**
     * Gets or sets the flag to enable performance display.  This property is observable.
     *
     * @type {Boolean}
     * @default false
     */
    this.performance = false;

    /**
     * Gets or sets the flag to show statistics.  This property is observable.
     *
     * @type {Boolean}
     * @default true
     */
    this.showStatistics = true;

    /**
     * Gets or sets the flag to show pick statistics.  This property is observable.
     *
     * @type {Boolean}
     * @default true
     */
    this.showPickStatistics = true;

    /**
     * Gets or sets the flag to show resource cache statistics. This property is
     * observable.
     *
     * @type {Boolean}
     * @default false
     */
    this.showResourceCacheStatistics = false;

    /**
     * Gets or sets the flag to show the inspector.  This property is observable.
     *
     * @type {Boolean}
     * @default true
     */
    this.inspectorVisible = true;

    /**
     * Gets or sets the flag to show the tileset section.  This property is observable.
     *
     * @type {Boolean}
     * @default false
     */
    this.tilesetVisible = false;

    /**
     * Gets or sets the flag to show the display section.  This property is observable.
     *
     * @type {Boolean}
     * @default false
     */
    this.displayVisible = false;

    /**
     * Gets or sets the flag to show the update section.  This property is observable.
     *
     * @type {Boolean}
     * @default false
     */
    this.updateVisible = false;

    /**
     * Gets or sets the flag to show the logging section.  This property is observable.
     *
     * @type {Boolean}
     * @default false
     */
    this.loggingVisible = false;

    /**
     * Gets or sets the flag to show the style section.  This property is observable.
     *
     * @type {Boolean}
     * @default false
     */
    this.styleVisible = false;

    /**
     * Gets or sets the flag to show the tile info section.  This property is observable.
     *
     * @type {Boolean}
     * @default false
     */
    this.tileDebugLabelsVisible = false;

    /**
     * Gets or sets the flag to show the optimization info section. This property is observable.
     *
     * @type {Boolean}
     * @default false;
     */
    this.optimizationVisible = false;

    /**
     * Gets or sets the JSON for the tileset style.  This property is observable.
     *
     * @type {String}
     * @default '{}'
     */
    this.styleString = "{}";

    this._tileset = undefined;
    this._feature = undefined;
    this._tile = undefined;

    knockout.track(this, [
      "performance",
      "inspectorVisible",
      "_statisticsText",
      "_pickStatisticsText",
      "_resourceCacheStatisticsText",
      "_editorError",
      "showPickStatistics",
      "showStatistics",
      "showResourceCacheStatistics",
      "tilesetVisible",
      "displayVisible",
      "updateVisible",
      "loggingVisible",
      "styleVisible",
      "optimizationVisible",
      "tileDebugLabelsVisible",
      "styleString",
      "_feature",
      "_tile",
    ]);

    this._properties = knockout.observable({});
    /**
     * Gets the names of the properties in the tileset.  This property is observable.
     * @type {String[]}
     * @readonly
     */
    this.properties = [];
    knockout.defineProperty(this, "properties", function () {
      const names = [];
      const properties = that._properties();
      for (const prop in properties) {
        if (properties.hasOwnProperty(prop)) {
          names.push(prop);
        }
      }
      return names;
    });

    const dynamicScreenSpaceError = knockout.observable();
    knockout.defineProperty(this, "dynamicScreenSpaceError", {
      get: function () {
        return dynamicScreenSpaceError();
      },
      set: function (value) {
        dynamicScreenSpaceError(value);
        if (defined(that._tileset)) {
          that._tileset.dynamicScreenSpaceError = value;
        }
      },
    });
    /**
     * Gets or sets the flag to enable dynamic screen space error.  This property is observable.
     *
     * @type {Boolean}
     * @default false
     */
    this.dynamicScreenSpaceError = false;

    const colorBlendMode = knockout.observable();
    knockout.defineProperty(this, "colorBlendMode", {
      get: function () {
        return colorBlendMode();
      },
      set: function (value) {
        colorBlendMode(value);
        if (defined(that._tileset)) {
          that._tileset.colorBlendMode = value;
          that._scene.requestRender();
        }
      },
    });
    /**
     * Gets or sets the color blend mode.  This property is observable.
     *
     * @type {Cesium3DTileColorBlendMode}
     * @default Cesium3DTileColorBlendMode.HIGHLIGHT
     */
    this.colorBlendMode = Cesium3DTileColorBlendMode$1.HIGHLIGHT;

    const showOnlyPickedTileDebugLabel = knockout.observable();
    const picking = knockout.observable();
    knockout.defineProperty(this, "picking", {
      get: function () {
        return picking();
      },
      set: function (value) {
        picking(value);
        if (value) {
          that._eventHandler.setInputAction(function (e) {
            const picked = scene.pick(e.endPosition);
            if (picked instanceof Cesium3DTileFeature) {
              // Picked a feature
              that.feature = picked;
              that.tile = picked.content.tile;
            } else if (defined(picked) && defined(picked.content)) {
              // Picked a tile
              that.feature = undefined;
              that.tile = picked.content.tile;
            } else {
              // Picked nothing
              that.feature = undefined;
              that.tile = undefined;
            }
            if (!defined(that._tileset)) {
              return;
            }
            if (
              showOnlyPickedTileDebugLabel &&
              defined(picked) &&
              defined(picked.content)
            ) {
              let position;
              if (scene.pickPositionSupported) {
                position = scene.pickPosition(e.endPosition);
                if (defined(position)) {
                  that._tileset.debugPickPosition = position;
                }
              }
              that._tileset.debugPickedTile = picked.content.tile;
            } else {
              that._tileset.debugPickedTile = undefined;
            }
            that._scene.requestRender();
          }, ScreenSpaceEventType$1.MOUSE_MOVE);
        } else {
          that.feature = undefined;
          that.tile = undefined;
          that._eventHandler.removeInputAction(ScreenSpaceEventType$1.MOUSE_MOVE);
        }
      },
    });
    /**
     * Gets or sets the flag to enable picking.  This property is observable.
     *
     * @type {Boolean}
     * @default true
     */
    this.picking = true;

    const colorize = knockout.observable();
    knockout.defineProperty(this, "colorize", {
      get: function () {
        return colorize();
      },
      set: function (value) {
        colorize(value);
        if (defined(that._tileset)) {
          that._tileset.debugColorizeTiles = value;
          that._scene.requestRender();
        }
      },
    });
    /**
     * Gets or sets the flag to colorize tiles.  This property is observable.
     *
     * @type {Boolean}
     * @default false
     */
    this.colorize = false;

    const wireframe = knockout.observable();
    knockout.defineProperty(this, "wireframe", {
      get: function () {
        return wireframe();
      },
      set: function (value) {
        wireframe(value);
        if (defined(that._tileset)) {
          that._tileset.debugWireframe = value;
          that._scene.requestRender();
        }
      },
    });
    /**
     * Gets or sets the flag to draw with wireframe.  This property is observable.
     *
     * @type {Boolean}
     * @default false
     */
    this.wireframe = false;

    const showBoundingVolumes = knockout.observable();
    knockout.defineProperty(this, "showBoundingVolumes", {
      get: function () {
        return showBoundingVolumes();
      },
      set: function (value) {
        showBoundingVolumes(value);
        if (defined(that._tileset)) {
          that._tileset.debugShowBoundingVolume = value;
          that._scene.requestRender();
        }
      },
    });
    /**
     * Gets or sets the flag to show bounding volumes.  This property is observable.
     *
     * @type {Boolean}
     * @default false
     */
    this.showBoundingVolumes = false;

    const showContentBoundingVolumes = knockout.observable();
    knockout.defineProperty(this, "showContentBoundingVolumes", {
      get: function () {
        return showContentBoundingVolumes();
      },
      set: function (value) {
        showContentBoundingVolumes(value);
        if (defined(that._tileset)) {
          that._tileset.debugShowContentBoundingVolume = value;
          that._scene.requestRender();
        }
      },
    });
    /**
     * Gets or sets the flag to show content volumes.  This property is observable.
     *
     * @type {Boolean}
     * @default false
     */
    this.showContentBoundingVolumes = false;

    const showRequestVolumes = knockout.observable();
    knockout.defineProperty(this, "showRequestVolumes", {
      get: function () {
        return showRequestVolumes();
      },
      set: function (value) {
        showRequestVolumes(value);
        if (defined(that._tileset)) {
          that._tileset.debugShowViewerRequestVolume = value;
          that._scene.requestRender();
        }
      },
    });
    /**
     * Gets or sets the flag to show request volumes.  This property is observable.
     *
     * @type {Boolean}
     * @default false
     */
    this.showRequestVolumes = false;

    const freezeFrame = knockout.observable();
    knockout.defineProperty(this, "freezeFrame", {
      get: function () {
        return freezeFrame();
      },
      set: function (value) {
        freezeFrame(value);
        if (defined(that._tileset)) {
          that._tileset.debugFreezeFrame = value;
          that._scene.debugShowFrustumPlanes = value;
          that._scene.requestRender();
        }
      },
    });
    /**
     * Gets or sets the flag to suspend updates.  This property is observable.
     *
     * @type {Boolean}
     * @default false
     */
    this.freezeFrame = false;

    knockout.defineProperty(this, "showOnlyPickedTileDebugLabel", {
      get: function () {
        return showOnlyPickedTileDebugLabel();
      },
      set: function (value) {
        showOnlyPickedTileDebugLabel(value);
        if (defined(that._tileset)) {
          that._tileset.debugPickedTileLabelOnly = value;
          that._scene.requestRender();
        }
      },
    });
    /**
     * Gets or sets the flag to show debug labels only for the currently picked tile.  This property is observable.
     *
     * @type {Boolean}
     * @default false
     */
    this.showOnlyPickedTileDebugLabel = false;

    const showGeometricError = knockout.observable();
    knockout.defineProperty(this, "showGeometricError", {
      get: function () {
        return showGeometricError();
      },
      set: function (value) {
        showGeometricError(value);
        if (defined(that._tileset)) {
          that._tileset.debugShowGeometricError = value;
          that._scene.requestRender();
        }
      },
    });
    /**
     * Gets or sets the flag to show tile geometric error.  This property is observable.
     *
     * @type {Boolean}
     * @default false
     */
    this.showGeometricError = false;

    const showRenderingStatistics = knockout.observable();
    knockout.defineProperty(this, "showRenderingStatistics", {
      get: function () {
        return showRenderingStatistics();
      },
      set: function (value) {
        showRenderingStatistics(value);
        if (defined(that._tileset)) {
          that._tileset.debugShowRenderingStatistics = value;
          that._scene.requestRender();
        }
      },
    });
    /**
     * Displays the number of commands, points, triangles and features used per tile.  This property is observable.
     *
     * @type {Boolean}
     * @default false
     */
    this.showRenderingStatistics = false;

    const showMemoryUsage = knockout.observable();
    knockout.defineProperty(this, "showMemoryUsage", {
      get: function () {
        return showMemoryUsage();
      },
      set: function (value) {
        showMemoryUsage(value);
        if (defined(that._tileset)) {
          that._tileset.debugShowMemoryUsage = value;
          that._scene.requestRender();
        }
      },
    });
    /**
     * Displays the memory used per tile.  This property is observable.
     *
     * @type {Boolean}
     * @default false
     */
    this.showMemoryUsage = false;

    const showUrl = knockout.observable();
    knockout.defineProperty(this, "showUrl", {
      get: function () {
        return showUrl();
      },
      set: function (value) {
        showUrl(value);
        if (defined(that._tileset)) {
          that._tileset.debugShowUrl = value;
          that._scene.requestRender();
        }
      },
    });
    /**
     * Gets or sets the flag to show the tile url.  This property is observable.
     *
     * @type {Boolean}
     * @default false
     */
    this.showUrl = false;

    const maximumScreenSpaceError = knockout.observable();
    knockout.defineProperty(this, "maximumScreenSpaceError", {
      get: function () {
        return maximumScreenSpaceError();
      },
      set: function (value) {
        value = Number(value);
        if (!isNaN(value)) {
          maximumScreenSpaceError(value);
          if (defined(that._tileset)) {
            that._tileset.maximumScreenSpaceError = value;
          }
        }
      },
    });
    /**
     * Gets or sets the maximum screen space error.  This property is observable.
     *
     * @type {Number}
     * @default 16
     */
    this.maximumScreenSpaceError = 16;

    const dynamicScreenSpaceErrorDensity = knockout.observable();
    knockout.defineProperty(this, "dynamicScreenSpaceErrorDensity", {
      get: function () {
        return dynamicScreenSpaceErrorDensity();
      },
      set: function (value) {
        value = Number(value);
        if (!isNaN(value)) {
          dynamicScreenSpaceErrorDensity(value);
          if (defined(that._tileset)) {
            that._tileset.dynamicScreenSpaceErrorDensity = value;
          }
        }
      },
    });
    /**
     * Gets or sets the dynamic screen space error density.  This property is observable.
     *
     * @type {Number}
     * @default 0.00278
     */
    this.dynamicScreenSpaceErrorDensity = 0.00278;

    /**
     * Gets or sets the dynamic screen space error density slider value.
     * This allows the slider to be exponential because values tend to be closer to 0 than 1.
     * This property is observable.
     *
     * @type {Number}
     * @default 0.00278
     */
    this.dynamicScreenSpaceErrorDensitySliderValue = undefined;
    knockout.defineProperty(this, "dynamicScreenSpaceErrorDensitySliderValue", {
      get: function () {
        return Math.pow(dynamicScreenSpaceErrorDensity(), 1 / 6);
      },
      set: function (value) {
        dynamicScreenSpaceErrorDensity(Math.pow(value, 6));
      },
    });

    const dynamicScreenSpaceErrorFactor = knockout.observable();
    knockout.defineProperty(this, "dynamicScreenSpaceErrorFactor", {
      get: function () {
        return dynamicScreenSpaceErrorFactor();
      },
      set: function (value) {
        value = Number(value);
        if (!isNaN(value)) {
          dynamicScreenSpaceErrorFactor(value);
          if (defined(that._tileset)) {
            that._tileset.dynamicScreenSpaceErrorFactor = value;
          }
        }
      },
    });
    /**
     * Gets or sets the dynamic screen space error factor.  This property is observable.
     *
     * @type {Number}
     * @default 4.0
     */
    this.dynamicScreenSpaceErrorFactor = 4.0;

    const pickTileset = getPickTileset(this);
    const pickActive = knockout.observable();
    knockout.defineProperty(this, "pickActive", {
      get: function () {
        return pickActive();
      },
      set: function (value) {
        pickActive(value);
        if (value) {
          that._eventHandler.setInputAction(
            pickTileset,
            ScreenSpaceEventType$1.LEFT_CLICK
          );
        } else {
          that._eventHandler.removeInputAction(ScreenSpaceEventType$1.LEFT_CLICK);
        }
      },
    });

    const pointCloudShading = knockout.observable();
    knockout.defineProperty(this, "pointCloudShading", {
      get: function () {
        return pointCloudShading();
      },
      set: function (value) {
        pointCloudShading(value);
        if (defined(that._tileset)) {
          that._tileset.pointCloudShading.attenuation = value;
        }
      },
    });
    /**
     * Gets or sets the flag to enable point cloud shading. This property is observable.
     *
     * @type {Boolean}
     * @default false
     */
    this.pointCloudShading = false;

    const geometricErrorScale = knockout.observable();
    knockout.defineProperty(this, "geometricErrorScale", {
      get: function () {
        return geometricErrorScale();
      },
      set: function (value) {
        value = Number(value);
        if (!isNaN(value)) {
          geometricErrorScale(value);
          if (defined(that._tileset)) {
            that._tileset.pointCloudShading.geometricErrorScale = value;
          }
        }
      },
    });
    /**
     * Gets or sets the geometric error scale.  This property is observable.
     *
     * @type {Number}
     * @default 1.0
     */
    this.geometricErrorScale = 1.0;

    const maximumAttenuation = knockout.observable();
    knockout.defineProperty(this, "maximumAttenuation", {
      get: function () {
        return maximumAttenuation();
      },
      set: function (value) {
        value = Number(value);
        if (!isNaN(value)) {
          maximumAttenuation(value);
          if (defined(that._tileset)) {
            that._tileset.pointCloudShading.maximumAttenuation =
              value === 0 ? undefined : value;
          }
        }
      },
    });
    /**
     * Gets or sets the maximum attenuation.  This property is observable.
     *
     * @type {Number}
     * @default 0
     */
    this.maximumAttenuation = 0;

    const baseResolution = knockout.observable();
    knockout.defineProperty(this, "baseResolution", {
      get: function () {
        return baseResolution();
      },
      set: function (value) {
        value = Number(value);
        if (!isNaN(value)) {
          baseResolution(value);
          if (defined(that._tileset)) {
            that._tileset.pointCloudShading.baseResolution =
              value === 0 ? undefined : value;
          }
        }
      },
    });
    /**
     * Gets or sets the base resolution.  This property is observable.
     *
     * @type {Number}
     * @default 0
     */
    this.baseResolution = 0;

    const eyeDomeLighting = knockout.observable();
    knockout.defineProperty(this, "eyeDomeLighting", {
      get: function () {
        return eyeDomeLighting();
      },
      set: function (value) {
        eyeDomeLighting(value);
        if (defined(that._tileset)) {
          that._tileset.pointCloudShading.eyeDomeLighting = value;
        }
      },
    });
    /**
     * Gets or sets the flag to enable eye dome lighting. This property is observable.
     *
     * @type {Boolean}
     * @default false
     */
    this.eyeDomeLighting = false;

    const eyeDomeLightingStrength = knockout.observable();
    knockout.defineProperty(this, "eyeDomeLightingStrength", {
      get: function () {
        return eyeDomeLightingStrength();
      },
      set: function (value) {
        value = Number(value);
        if (!isNaN(value)) {
          eyeDomeLightingStrength(value);
          if (defined(that._tileset)) {
            that._tileset.pointCloudShading.eyeDomeLightingStrength = value;
          }
        }
      },
    });
    /**
     * Gets or sets the eye dome lighting strength.  This property is observable.
     *
     * @type {Number}
     * @default 1.0
     */
    this.eyeDomeLightingStrength = 1.0;

    const eyeDomeLightingRadius = knockout.observable();
    knockout.defineProperty(this, "eyeDomeLightingRadius", {
      get: function () {
        return eyeDomeLightingRadius();
      },
      set: function (value) {
        value = Number(value);
        if (!isNaN(value)) {
          eyeDomeLightingRadius(value);
          if (defined(that._tileset)) {
            that._tileset.pointCloudShading.eyeDomeLightingRadius = value;
          }
        }
      },
    });
    /**
     * Gets or sets the eye dome lighting radius.  This property is observable.
     *
     * @type {Number}
     * @default 1.0
     */
    this.eyeDomeLightingRadius = 1.0;

    /**
     * Gets or sets the pick state
     *
     * @type {Boolean}
     * @default false
     */
    this.pickActive = false;

    const skipLevelOfDetail = knockout.observable();
    knockout.defineProperty(this, "skipLevelOfDetail", {
      get: function () {
        return skipLevelOfDetail();
      },
      set: function (value) {
        skipLevelOfDetail(value);
        if (defined(that._tileset)) {
          that._tileset.skipLevelOfDetail = value;
        }
      },
    });
    /**
     * Gets or sets the flag to determine if level of detail skipping should be applied during the traversal.
     * This property is observable.
     * @type {Boolean}
     * @default true
     */
    this.skipLevelOfDetail = true;

    const skipScreenSpaceErrorFactor = knockout.observable();
    knockout.defineProperty(this, "skipScreenSpaceErrorFactor", {
      get: function () {
        return skipScreenSpaceErrorFactor();
      },
      set: function (value) {
        value = Number(value);
        if (!isNaN(value)) {
          skipScreenSpaceErrorFactor(value);
          if (defined(that._tileset)) {
            that._tileset.skipScreenSpaceErrorFactor = value;
          }
        }
      },
    });
    /**
     * Gets or sets the multiplier defining the minimum screen space error to skip. This property is observable.
     * @type {Number}
     * @default 16
     */
    this.skipScreenSpaceErrorFactor = 16;

    const baseScreenSpaceError = knockout.observable();
    knockout.defineProperty(this, "baseScreenSpaceError", {
      get: function () {
        return baseScreenSpaceError();
      },
      set: function (value) {
        value = Number(value);
        if (!isNaN(value)) {
          baseScreenSpaceError(value);
          if (defined(that._tileset)) {
            that._tileset.baseScreenSpaceError = value;
          }
        }
      },
    });
    /**
     * Gets or sets the screen space error that must be reached before skipping levels of detail. This property is observable.
     * @type {Number}
     * @default 1024
     */
    this.baseScreenSpaceError = 1024;

    const skipLevels = knockout.observable();
    knockout.defineProperty(this, "skipLevels", {
      get: function () {
        return skipLevels();
      },
      set: function (value) {
        value = Number(value);
        if (!isNaN(value)) {
          skipLevels(value);
          if (defined(that._tileset)) {
            that._tileset.skipLevels = value;
          }
        }
      },
    });
    /**
     * Gets or sets the constant defining the minimum number of levels to skip when loading tiles. This property is observable.
     * @type {Number}
     * @default 1
     */
    this.skipLevels = 1;

    const immediatelyLoadDesiredLevelOfDetail = knockout.observable();
    knockout.defineProperty(this, "immediatelyLoadDesiredLevelOfDetail", {
      get: function () {
        return immediatelyLoadDesiredLevelOfDetail();
      },
      set: function (value) {
        immediatelyLoadDesiredLevelOfDetail(value);
        if (defined(that._tileset)) {
          that._tileset.immediatelyLoadDesiredLevelOfDetail = value;
        }
      },
    });
    /**
     * Gets or sets the flag which, when true, only tiles that meet the maximum screen space error will ever be downloaded.
     * This property is observable.
     * @type {Boolean}
     * @default false
     */
    this.immediatelyLoadDesiredLevelOfDetail = false;

    const loadSiblings = knockout.observable();
    knockout.defineProperty(this, "loadSiblings", {
      get: function () {
        return loadSiblings();
      },
      set: function (value) {
        loadSiblings(value);
        if (defined(that._tileset)) {
          that._tileset.loadSiblings = value;
        }
      },
    });
    /**
     * Gets or sets the flag which determines whether siblings of visible tiles are always downloaded during traversal.
     * This property is observable
     * @type {Boolean}
     * @default false
     */
    this.loadSiblings = false;

    this._style = undefined;
    this._shouldStyle = false;
    this._definedProperties = [
      "properties",
      "dynamicScreenSpaceError",
      "colorBlendMode",
      "picking",
      "colorize",
      "wireframe",
      "showBoundingVolumes",
      "showContentBoundingVolumes",
      "showRequestVolumes",
      "freezeFrame",
      "maximumScreenSpaceError",
      "dynamicScreenSpaceErrorDensity",
      "baseScreenSpaceError",
      "skipScreenSpaceErrorFactor",
      "skipLevelOfDetail",
      "skipLevels",
      "immediatelyLoadDesiredLevelOfDetail",
      "loadSiblings",
      "dynamicScreenSpaceErrorDensitySliderValue",
      "dynamicScreenSpaceErrorFactor",
      "pickActive",
      "showOnlyPickedTileDebugLabel",
      "showGeometricError",
      "showRenderingStatistics",
      "showMemoryUsage",
      "showUrl",
      "pointCloudShading",
      "geometricErrorScale",
      "maximumAttenuation",
      "baseResolution",
      "eyeDomeLighting",
      "eyeDomeLightingStrength",
      "eyeDomeLightingRadius",
    ];
    this._removePostRenderEvent = scene.postRender.addEventListener(function () {
      that._update();
    });

    if (!defined(this._tileset)) {
      selectTilesetOnHover(this, true);
    }
  }

  Object.defineProperties(Cesium3DTilesInspectorViewModel.prototype, {
    /**
     * Gets the scene
     * @memberof Cesium3DTilesInspectorViewModel.prototype
     * @type {Scene}
     * @readonly
     */
    scene: {
      get: function () {
        return this._scene;
      },
    },
    /**
     * Gets the performance container
     * @memberof Cesium3DTilesInspectorViewModel.prototype
     * @type {HTMLElement}
     * @readonly
     */
    performanceContainer: {
      get: function () {
        return this._performanceContainer;
      },
    },

    /**
     * Gets the statistics text.  This property is observable.
     * @memberof Cesium3DTilesInspectorViewModel.prototype
     * @type {String}
     * @readonly
     */
    statisticsText: {
      get: function () {
        return this._statisticsText;
      },
    },
    /**
     * Gets the pick statistics text.  This property is observable.
     * @memberof Cesium3DTilesInspectorViewModel.prototype
     * @type {String}
     * @readonly
     */
    pickStatisticsText: {
      get: function () {
        return this._pickStatisticsText;
      },
    },

    /**
     * Gets the resource cache statistics text. This property is observable.
     * @memberof Cesium3DTilesInspectorViewModel.prototype
     * @type {String}
     * @readonly
     */
    resourceCacheStatisticsText: {
      get: function () {
        return this._resourceCacheStatisticsText;
      },
    },

    /**
     * Gets the available blend modes
     * @memberof Cesium3DTilesInspectorViewModel.prototype
     * @type {Object[]}
     * @readonly
     */
    colorBlendModes: {
      get: function () {
        return colorBlendModes;
      },
    },

    /**
     * Gets the editor error message
     * @memberof Cesium3DTilesInspectorViewModel.prototype
     * @type {String}
     * @readonly
     */
    editorError: {
      get: function () {
        return this._editorError;
      },
    },

    /**
     * Gets or sets the tileset of the view model.
     * @memberof Cesium3DTilesInspectorViewModel.prototype
     * @type {Cesium3DTileset}
     */
    tileset: {
      get: function () {
        return this._tileset;
      },
      set: function (tileset) {
        this._tileset = tileset;
        this._style = undefined;
        this.styleString = "{}";
        this.feature = undefined;
        this.tile = undefined;

        if (defined(tileset)) {
          const that = this;
          tileset.readyPromise.then(function (t) {
            if (!that.isDestroyed()) {
              that._properties(t.properties);
            }
          });

          // update tileset with existing settings
          const settings = [
            "colorize",
            "wireframe",
            "showBoundingVolumes",
            "showContentBoundingVolumes",
            "showRequestVolumes",
            "freezeFrame",
            "showOnlyPickedTileDebugLabel",
            "showGeometricError",
            "showRenderingStatistics",
            "showMemoryUsage",
            "showUrl",
          ];
          const length = settings.length;
          for (let i = 0; i < length; ++i) {
            const setting = settings[i];
            //eslint-disable-next-line no-self-assign
            this[setting] = this[setting];
          }

          // update view model with existing tileset settings
          this.maximumScreenSpaceError = tileset.maximumScreenSpaceError;
          this.dynamicScreenSpaceError = tileset.dynamicScreenSpaceError;
          this.dynamicScreenSpaceErrorDensity =
            tileset.dynamicScreenSpaceErrorDensity;
          this.dynamicScreenSpaceErrorFactor =
            tileset.dynamicScreenSpaceErrorFactor;
          this.colorBlendMode = tileset.colorBlendMode;
          this.skipLevelOfDetail = tileset.skipLevelOfDetail;
          this.skipScreenSpaceErrorFactor = tileset.skipScreenSpaceErrorFactor;
          this.baseScreenSpaceError = tileset.baseScreenSpaceError;
          this.skipLevels = tileset.skipLevels;
          this.immediatelyLoadDesiredLevelOfDetail =
            tileset.immediatelyLoadDesiredLevelOfDetail;
          this.loadSiblings = tileset.loadSiblings;

          const pointCloudShading = tileset.pointCloudShading;
          this.pointCloudShading = pointCloudShading.attenuation;
          this.geometricErrorScale = pointCloudShading.geometricErrorScale;
          this.maximumAttenuation = pointCloudShading.maximumAttenuation
            ? pointCloudShading.maximumAttenuation
            : 0.0;
          this.baseResolution = pointCloudShading.baseResolution
            ? pointCloudShading.baseResolution
            : 0.0;
          this.eyeDomeLighting = pointCloudShading.eyeDomeLighting;
          this.eyeDomeLightingStrength =
            pointCloudShading.eyeDomeLightingStrength;
          this.eyeDomeLightingRadius = pointCloudShading.eyeDomeLightingRadius;

          this._scene.requestRender();
        } else {
          this._properties({});
        }

        this._statisticsText = getStatistics(tileset, false);
        this._pickStatisticsText = getStatistics(tileset, true);
        this._resourceCacheStatisticsText = getResourceCacheStatistics();
        selectTilesetOnHover(this, false);
      },
    },

    /**
     * Gets the current feature of the view model.
     * @memberof Cesium3DTilesInspectorViewModel.prototype
     * @type {Cesium3DTileFeature}
     */
    feature: {
      get: function () {
        return this._feature;
      },
      set: function (feature) {
        if (this._feature === feature) {
          return;
        }
        const currentFeature = this._feature;
        if (defined(currentFeature) && !currentFeature.content.isDestroyed()) {
          // Restore original color to feature that is no longer selected
          if (!this.colorize && defined(this._style)) {
            currentFeature.color = defined(this._style.color)
              ? this._style.color.evaluateColor(currentFeature, scratchColor)
              : Color.WHITE;
          } else {
            currentFeature.color = oldColor;
          }
          this._scene.requestRender();
        }
        if (defined(feature)) {
          // Highlight new feature
          Color.clone(feature.color, oldColor);
          feature.color = highlightColor;
          this._scene.requestRender();
        }
        this._feature = feature;
      },
    },

    /**
     * Gets the current tile of the view model
     * @memberof Cesium3DTilesInspectorViewModel.prototype
     * @type {Cesium3DTile}
     */
    tile: {
      get: function () {
        return this._tile;
      },
      set: function (tile) {
        if (this._tile === tile) {
          return;
        }
        const currentTile = this._tile;

        if (
          defined(currentTile) &&
          !currentTile.isDestroyed() &&
          !hasFeatures(currentTile.content)
        ) {
          // Restore original color to tile that is no longer selected
          currentTile.color = oldColor;
          this._scene.requestRender();
        }

        if (defined(tile) && !hasFeatures(tile.content)) {
          // Highlight new tile
          Color.clone(tile.color, oldColor);
          tile.color = highlightColor;
          this._scene.requestRender();
        }
        this._tile = tile;
      },
    },
  });

  function hasFeatures(content) {
    if (!defined(content)) {
      return false;
    }

    if (content.featuresLength > 0) {
      return true;
    }
    const innerContents = content.innerContents;
    if (defined(innerContents)) {
      const length = innerContents.length;
      for (let i = 0; i < length; ++i) {
        if (!hasFeatures(innerContents[i])) {
          return false;
        }
      }
      return true;
    }
    return false;
  }

  /**
   * Toggles the pick tileset mode
   */
  Cesium3DTilesInspectorViewModel.prototype.togglePickTileset = function () {
    this.pickActive = !this.pickActive;
  };

  /**
   * Toggles the inspector visibility
   */
  Cesium3DTilesInspectorViewModel.prototype.toggleInspector = function () {
    this.inspectorVisible = !this.inspectorVisible;
  };

  /**
   * Toggles the visibility of the tileset section
   */
  Cesium3DTilesInspectorViewModel.prototype.toggleTileset = function () {
    this.tilesetVisible = !this.tilesetVisible;
  };

  /**
   * Toggles the visibility of the display section
   */
  Cesium3DTilesInspectorViewModel.prototype.toggleDisplay = function () {
    this.displayVisible = !this.displayVisible;
  };

  /**
   * Toggles the visibility of the update section
   */
  Cesium3DTilesInspectorViewModel.prototype.toggleUpdate = function () {
    this.updateVisible = !this.updateVisible;
  };

  /**
   * Toggles the visibility of the logging section
   */
  Cesium3DTilesInspectorViewModel.prototype.toggleLogging = function () {
    this.loggingVisible = !this.loggingVisible;
  };

  /**
   * Toggles the visibility of the style section
   */
  Cesium3DTilesInspectorViewModel.prototype.toggleStyle = function () {
    this.styleVisible = !this.styleVisible;
  };

  /**
   * Toggles the visibility of the tile Debug Info section
   */
  Cesium3DTilesInspectorViewModel.prototype.toggleTileDebugLabels = function () {
    this.tileDebugLabelsVisible = !this.tileDebugLabelsVisible;
  };

  /**
   * Toggles the visibility of the optimization section
   */
  Cesium3DTilesInspectorViewModel.prototype.toggleOptimization = function () {
    this.optimizationVisible = !this.optimizationVisible;
  };

  /**
   * Trims tile cache
   */
  Cesium3DTilesInspectorViewModel.prototype.trimTilesCache = function () {
    if (defined(this._tileset)) {
      this._tileset.trimLoadedTiles();
    }
  };

  /**
   * Compiles the style in the style editor.
   */
  Cesium3DTilesInspectorViewModel.prototype.compileStyle = function () {
    const tileset = this._tileset;
    if (!defined(tileset) || this.styleString === JSON.stringify(tileset.style)) {
      return;
    }
    this._editorError = "";
    try {
      if (this.styleString.length === 0) {
        this.styleString = "{}";
      }
      this._style = new Cesium3DTileStyle(JSON.parse(this.styleString));
      this._shouldStyle = true;
      this._scene.requestRender();
    } catch (err) {
      this._editorError = err.toString();
    }

    // set feature again so pick coloring is set
    this.feature = this._feature;
    this.tile = this._tile;
  };

  /**
   * Handles key press events on the style editor.
   */
  Cesium3DTilesInspectorViewModel.prototype.styleEditorKeyPress = function (
    sender,
    event
  ) {
    if (event.keyCode === 9) {
      //tab
      event.preventDefault();
      const textArea = event.target;
      const start = textArea.selectionStart;
      const end = textArea.selectionEnd;
      let newEnd = end;
      const selected = textArea.value.slice(start, end);
      const lines = selected.split("\n");
      const length = lines.length;
      let i;
      if (!event.shiftKey) {
        for (i = 0; i < length; ++i) {
          lines[i] = `  ${lines[i]}`;
          newEnd += 2;
        }
      } else {
        for (i = 0; i < length; ++i) {
          if (lines[i][0] === " ") {
            if (lines[i][1] === " ") {
              lines[i] = lines[i].substr(2);
              newEnd -= 2;
            } else {
              lines[i] = lines[i].substr(1);
              newEnd -= 1;
            }
          }
        }
      }
      const newText = lines.join("\n");
      textArea.value =
        textArea.value.slice(0, start) + newText + textArea.value.slice(end);
      textArea.selectionStart = start !== end ? start : newEnd;
      textArea.selectionEnd = newEnd;
    } else if (event.ctrlKey && (event.keyCode === 10 || event.keyCode === 13)) {
      //ctrl + enter
      this.compileStyle();
    }
    return true;
  };

  /**
   * Updates the values of view model
   * @private
   */
  Cesium3DTilesInspectorViewModel.prototype._update = function () {
    const tileset = this._tileset;

    if (this.performance) {
      this._performanceDisplay.update();
    }

    if (defined(tileset)) {
      if (tileset.isDestroyed()) {
        this.tile = undefined;
        this.feature = undefined;
        this.tileset = undefined;
        return;
      }

      const style = tileset.style;
      if (this._style !== tileset.style) {
        if (this._shouldStyle) {
          tileset.style = this._style;
          this._shouldStyle = false;
        } else {
          this._style = style;
          this.styleString = JSON.stringify(style.style, null, "  ");
        }
      }
    }
    if (this.showStatistics) {
      this._statisticsText = getStatistics(tileset, false);
      this._pickStatisticsText = getStatistics(tileset, true);
      this._resourceCacheStatisticsText = getResourceCacheStatistics();
    }
  };

  /**
   * @returns {Boolean} true if the object has been destroyed, false otherwise.
   */
  Cesium3DTilesInspectorViewModel.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the widget.  Should be called if permanently
   * removing the widget from layout.
   */
  Cesium3DTilesInspectorViewModel.prototype.destroy = function () {
    this._eventHandler.destroy();
    this._removePostRenderEvent();

    const that = this;
    this._definedProperties.forEach(function (property) {
      knockout.getObservable(that, property).dispose();
    });

    return destroyObject(this);
  };

  /**
   * Generates an HTML string of the statistics
   *
   * @function
   * @param {Cesium3DTileset} tileset The tileset
   * @param {Boolean} isPick Whether this is getting the statistics for the pick pass
   * @returns {String} The formatted statistics
   */
  Cesium3DTilesInspectorViewModel.getStatistics = getStatistics;

  /**
   * Inspector widget to aid in debugging 3D Tiles
   *
   * @alias Cesium3DTilesInspector
   * @constructor
   *
   * @param {Element|String} container The DOM element or ID that will contain the widget.
   * @param {Scene} scene the Scene instance to use.
   */
  function Cesium3DTilesInspector(container, scene) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("container", container);
    Check.typeOf.object("scene", scene);
    //>>includeEnd('debug');

    container = getElement(container);
    const element = document.createElement("div");
    const performanceContainer = document.createElement("div");
    performanceContainer.setAttribute("data-bind", "visible: performance");
    const viewModel = new Cesium3DTilesInspectorViewModel(
      scene,
      performanceContainer
    );

    this._viewModel = viewModel;
    this._container = container;
    this._element = element;

    const text = document.createElement("div");
    text.textContent = "3D Tiles Inspector";
    text.className = "cesium-cesiumInspector-button";
    text.setAttribute("data-bind", "click: toggleInspector");
    element.appendChild(text);
    element.className = "cesium-cesiumInspector cesium-3DTilesInspector";
    element.setAttribute(
      "data-bind",
      'css: { "cesium-cesiumInspector-visible" : inspectorVisible, "cesium-cesiumInspector-hidden" : !inspectorVisible}'
    );
    container.appendChild(element);

    const panel = document.createElement("div");
    this._panel = panel;
    panel.className = "cesium-cesiumInspector-dropDown";
    element.appendChild(panel);

    const createSection = InspectorShared.createSection;
    const createCheckbox = InspectorShared.createCheckbox;

    const tilesetPanelContents = createSection(
      panel,
      "Tileset",
      "tilesetVisible",
      "toggleTileset"
    );
    const displayPanelContents = createSection(
      panel,
      "Display",
      "displayVisible",
      "toggleDisplay"
    );
    const updatePanelContents = createSection(
      panel,
      "Update",
      "updateVisible",
      "toggleUpdate"
    );
    const loggingPanelContents = createSection(
      panel,
      "Logging",
      "loggingVisible",
      "toggleLogging"
    );
    const tileDebugLabelsPanelContents = createSection(
      panel,
      "Tile Debug Labels",
      "tileDebugLabelsVisible",
      "toggleTileDebugLabels"
    );
    const stylePanelContents = createSection(
      panel,
      "Style",
      "styleVisible",
      "toggleStyle"
    );
    const optimizationPanelContents = createSection(
      panel,
      "Optimization",
      "optimizationVisible",
      "toggleOptimization"
    );

    const properties = document.createElement("div");
    properties.className = "field-group";
    const propertiesLabel = document.createElement("label");
    propertiesLabel.className = "field-label";
    propertiesLabel.appendChild(document.createTextNode("Properties: "));
    const propertiesField = document.createElement("div");
    propertiesField.setAttribute("data-bind", "text: properties");
    properties.appendChild(propertiesLabel);
    properties.appendChild(propertiesField);
    tilesetPanelContents.appendChild(properties);
    tilesetPanelContents.appendChild(
      makeButton("togglePickTileset", "Pick Tileset", "pickActive")
    );
    tilesetPanelContents.appendChild(
      makeButton("trimTilesCache", "Trim Tiles Cache")
    );
    tilesetPanelContents.appendChild(createCheckbox("Enable Picking", "picking"));

    displayPanelContents.appendChild(createCheckbox("Colorize", "colorize"));
    displayPanelContents.appendChild(createCheckbox("Wireframe", "wireframe"));
    displayPanelContents.appendChild(
      createCheckbox("Bounding Volumes", "showBoundingVolumes")
    );
    displayPanelContents.appendChild(
      createCheckbox("Content Volumes", "showContentBoundingVolumes")
    );
    displayPanelContents.appendChild(
      createCheckbox("Request Volumes", "showRequestVolumes")
    );

    displayPanelContents.appendChild(
      createCheckbox("Point Cloud Shading", "pointCloudShading")
    );
    const pointCloudShadingContainer = document.createElement("div");
    pointCloudShadingContainer.setAttribute(
      "data-bind",
      "visible: pointCloudShading"
    );
    pointCloudShadingContainer.appendChild(
      makeRangeInput("geometricErrorScale", 0, 2, 0.01, "Geometric Error Scale")
    );
    pointCloudShadingContainer.appendChild(
      makeRangeInput("maximumAttenuation", 0, 32, 1, "Maximum Attenuation")
    );
    pointCloudShadingContainer.appendChild(
      makeRangeInput("baseResolution", 0, 1, 0.01, "Base Resolution")
    );
    pointCloudShadingContainer.appendChild(
      createCheckbox("Eye Dome Lighting (EDL)", "eyeDomeLighting")
    );
    displayPanelContents.appendChild(pointCloudShadingContainer);

    const edlContainer = document.createElement("div");
    edlContainer.setAttribute("data-bind", "visible: eyeDomeLighting");
    edlContainer.appendChild(
      makeRangeInput("eyeDomeLightingStrength", 0, 2.0, 0.1, "EDL Strength")
    );
    edlContainer.appendChild(
      makeRangeInput("eyeDomeLightingRadius", 0, 4.0, 0.1, "EDL Radius")
    );
    pointCloudShadingContainer.appendChild(edlContainer);

    updatePanelContents.appendChild(
      createCheckbox("Freeze Frame", "freezeFrame")
    );
    updatePanelContents.appendChild(
      createCheckbox("Dynamic Screen Space Error", "dynamicScreenSpaceError")
    );
    const sseContainer = document.createElement("div");
    sseContainer.appendChild(
      makeRangeInput(
        "maximumScreenSpaceError",
        0,
        128,
        1,
        "Maximum Screen Space Error"
      )
    );
    updatePanelContents.appendChild(sseContainer);
    const dynamicScreenSpaceErrorContainer = document.createElement("div");
    dynamicScreenSpaceErrorContainer.setAttribute(
      "data-bind",
      "visible: dynamicScreenSpaceError"
    );
    dynamicScreenSpaceErrorContainer.appendChild(
      makeRangeInput(
        "dynamicScreenSpaceErrorDensitySliderValue",
        0,
        1,
        0.005,
        "Screen Space Error Density",
        "dynamicScreenSpaceErrorDensity"
      )
    );
    dynamicScreenSpaceErrorContainer.appendChild(
      makeRangeInput(
        "dynamicScreenSpaceErrorFactor",
        1,
        10,
        0.1,
        "Screen Space Error Factor"
      )
    );
    updatePanelContents.appendChild(dynamicScreenSpaceErrorContainer);

    loggingPanelContents.appendChild(
      createCheckbox("Performance", "performance")
    );
    loggingPanelContents.appendChild(performanceContainer);
    loggingPanelContents.appendChild(
      createCheckbox("Statistics", "showStatistics")
    );
    const statistics = document.createElement("div");
    statistics.className = "cesium-3dTilesInspector-statistics";
    statistics.setAttribute(
      "data-bind",
      "html: statisticsText, visible: showStatistics"
    );
    loggingPanelContents.appendChild(statistics);
    loggingPanelContents.appendChild(
      createCheckbox("Pick Statistics", "showPickStatistics")
    );
    const pickStatistics = document.createElement("div");
    pickStatistics.className = "cesium-3dTilesInspector-statistics";
    pickStatistics.setAttribute(
      "data-bind",
      "html: pickStatisticsText, visible: showPickStatistics"
    );
    loggingPanelContents.appendChild(pickStatistics);
    loggingPanelContents.appendChild(
      createCheckbox("Resource Cache Statistics", "showResourceCacheStatistics")
    );
    const resourceCacheStatistics = document.createElement("div");
    resourceCacheStatistics.className = "cesium-3dTilesInspector-statistics";
    resourceCacheStatistics.setAttribute(
      "data-bind",
      "html: resourceCacheStatisticsText, visible: showResourceCacheStatistics"
    );
    loggingPanelContents.appendChild(resourceCacheStatistics);

    const stylePanelEditor = document.createElement("div");
    stylePanelContents.appendChild(stylePanelEditor);
    stylePanelEditor.appendChild(document.createTextNode("Color Blend Mode: "));
    const blendDropdown = document.createElement("select");
    blendDropdown.setAttribute(
      "data-bind",
      "options: colorBlendModes, " +
        'optionsText: "text", ' +
        'optionsValue: "value", ' +
        "value: colorBlendMode"
    );
    stylePanelEditor.appendChild(blendDropdown);
    const styleEditor = document.createElement("textarea");
    styleEditor.setAttribute(
      "data-bind",
      "textInput: styleString, event: { keydown: styleEditorKeyPress }"
    );
    stylePanelEditor.className = "cesium-cesiumInspector-styleEditor";
    stylePanelEditor.appendChild(styleEditor);
    const closeStylesBtn = makeButton("compileStyle", "Compile (Ctrl+Enter)");
    stylePanelEditor.appendChild(closeStylesBtn);
    const errorBox = document.createElement("div");
    errorBox.className = "cesium-cesiumInspector-error";
    errorBox.setAttribute("data-bind", "text: editorError");
    stylePanelEditor.appendChild(errorBox);

    tileDebugLabelsPanelContents.appendChild(
      createCheckbox("Show Picked Only", "showOnlyPickedTileDebugLabel")
    );
    tileDebugLabelsPanelContents.appendChild(
      createCheckbox("Geometric Error", "showGeometricError")
    );
    tileDebugLabelsPanelContents.appendChild(
      createCheckbox("Rendering Statistics", "showRenderingStatistics")
    );
    tileDebugLabelsPanelContents.appendChild(
      createCheckbox("Memory Usage (MB)", "showMemoryUsage")
    );
    tileDebugLabelsPanelContents.appendChild(createCheckbox("Url", "showUrl"));

    optimizationPanelContents.appendChild(
      createCheckbox("Skip Tile LODs", "skipLevelOfDetail")
    );
    const skipScreenSpaceErrorFactorContainer = document.createElement("div");
    skipScreenSpaceErrorFactorContainer.appendChild(
      makeRangeInput("skipScreenSpaceErrorFactor", 1, 50, 1, "Skip SSE Factor")
    );
    optimizationPanelContents.appendChild(skipScreenSpaceErrorFactorContainer);
    const baseScreenSpaceError = document.createElement("div");
    baseScreenSpaceError.appendChild(
      makeRangeInput(
        "baseScreenSpaceError",
        0,
        4096,
        1,
        "SSE before skipping LOD"
      )
    );
    optimizationPanelContents.appendChild(baseScreenSpaceError);
    const skipLevelsContainer = document.createElement("div");
    skipLevelsContainer.appendChild(
      makeRangeInput("skipLevels", 0, 10, 1, "Min. levels to skip")
    );
    optimizationPanelContents.appendChild(skipLevelsContainer);
    optimizationPanelContents.appendChild(
      createCheckbox(
        "Load only tiles that meet the max SSE.",
        "immediatelyLoadDesiredLevelOfDetail"
      )
    );
    optimizationPanelContents.appendChild(
      createCheckbox("Load siblings of visible tiles", "loadSiblings")
    );

    knockout.applyBindings(viewModel, element);
  }

  Object.defineProperties(Cesium3DTilesInspector.prototype, {
    /**
     * Gets the parent container.
     * @memberof Cesium3DTilesInspector.prototype
     *
     * @type {Element}
     */
    container: {
      get: function () {
        return this._container;
      },
    },

    /**
     * Gets the view model.
     * @memberof Cesium3DTilesInspector.prototype
     *
     * @type {Cesium3DTilesInspectorViewModel}
     */
    viewModel: {
      get: function () {
        return this._viewModel;
      },
    },
  });

  /**
   * @returns {Boolean} true if the object has been destroyed, false otherwise.
   */
  Cesium3DTilesInspector.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the widget.  Should be called if permanently
   * removing the widget from layout.
   */
  Cesium3DTilesInspector.prototype.destroy = function () {
    knockout.cleanNode(this._element);
    this._container.removeChild(this._element);
    this.viewModel.destroy();

    return destroyObject(this);
  };

  function makeRangeInput(property, min, max, step, text, displayProperty) {
    displayProperty = defaultValue(displayProperty, property);
    const input = document.createElement("input");
    input.setAttribute("data-bind", `value: ${displayProperty}`);
    input.type = "number";

    const slider = document.createElement("input");
    slider.type = "range";
    slider.min = min;
    slider.max = max;
    slider.step = step;
    slider.setAttribute("data-bind", `valueUpdate: "input", value: ${property}`);

    const wrapper = document.createElement("div");
    wrapper.appendChild(slider);

    const container = document.createElement("div");
    container.className = "cesium-cesiumInspector-slider";
    container.appendChild(document.createTextNode(text));
    container.appendChild(input);
    container.appendChild(wrapper);

    return container;
  }

  function makeButton(action, text, active) {
    const button = document.createElement("button");
    button.type = "button";
    button.textContent = text;
    button.className = "cesium-cesiumInspector-pickButton";
    let binding = `click: ${action}`;
    if (defined(active)) {
      binding += `, css: {"cesium-cesiumInspector-pickButtonHighlight" : ${active}}`;
    }
    button.setAttribute("data-bind", binding);

    return button;
  }

  function frustumStatisticsToString(statistics) {
    let str;
    if (defined(statistics)) {
      str = "Command Statistics";
      const com = statistics.commandsInFrustums;
      for (const n in com) {
        if (com.hasOwnProperty(n)) {
          let num = parseInt(n, 10);
          let s;
          if (num === 7) {
            s = "1, 2 and 3";
          } else {
            const f = [];
            for (let i = 2; i >= 0; i--) {
              const p = Math.pow(2, i);
              if (num >= p) {
                f.push(i + 1);
                num -= p;
              }
            }
            s = f.reverse().join(" and ");
          }
          str += `<br>&nbsp;&nbsp;&nbsp;&nbsp;${com[n]} in frustum ${s}`;
        }
      }
      str += `<br>Total: ${statistics.totalCommands}`;
    }

    return str;
  }

  function boundDepthFrustum(lower, upper, proposed) {
    let bounded = Math.min(proposed, upper);
    bounded = Math.max(bounded, lower);
    return bounded;
  }

  const scratchPickRay = new Ray();
  const scratchPickCartesian = new Cartesian3();

  /**
   * The view model for {@link CesiumInspector}.
   * @alias CesiumInspectorViewModel
   * @constructor
   *
   * @param {Scene} scene The scene instance to use.
   * @param {Element} performanceContainer The instance to use for performance container.
   */
  function CesiumInspectorViewModel(scene, performanceContainer) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(scene)) {
      throw new DeveloperError("scene is required");
    }

    if (!defined(performanceContainer)) {
      throw new DeveloperError("performanceContainer is required");
    }
    //>>includeEnd('debug');

    const that = this;
    const canvas = scene.canvas;
    const eventHandler = new ScreenSpaceEventHandler(canvas);
    this._eventHandler = eventHandler;
    this._scene = scene;
    this._canvas = canvas;
    this._primitive = undefined;
    this._tile = undefined;
    this._modelMatrixPrimitive = undefined;
    this._performanceDisplay = undefined;
    this._performanceContainer = performanceContainer;

    const globe = this._scene.globe;
    globe.depthTestAgainstTerrain = true;

    /**
     * Gets or sets the show frustums state.  This property is observable.
     * @type {Boolean}
     * @default false
     */
    this.frustums = false;

    /**
     * Gets or sets the show frustum planes state.  This property is observable.
     * @type {Boolean}
     * @default false
     */
    this.frustumPlanes = false;

    /**
     * Gets or sets the show performance display state.  This property is observable.
     * @type {Boolean}
     * @default false
     */
    this.performance = false;

    /**
     * Gets or sets the shader cache text.  This property is observable.
     * @type {String}
     * @default ''
     */
    this.shaderCacheText = "";

    /**
     * Gets or sets the show primitive bounding sphere state.  This property is observable.
     * @type {Boolean}
     * @default false
     */
    this.primitiveBoundingSphere = false;

    /**
     * Gets or sets the show primitive reference frame state.  This property is observable.
     * @type {Boolean}
     * @default false
     */
    this.primitiveReferenceFrame = false;

    /**
     * Gets or sets the filter primitive state.  This property is observable.
     * @type {Boolean}
     * @default false
     */
    this.filterPrimitive = false;

    /**
     * Gets or sets the show tile bounding sphere state.  This property is observable.
     * @type {Boolean}
     * @default false
     */
    this.tileBoundingSphere = false;

    /**
     * Gets or sets the filter tile state.  This property is observable.
     * @type {Boolean}
     * @default false
     */
    this.filterTile = false;

    /**
     * Gets or sets the show wireframe state.  This property is observable.
     * @type {Boolean}
     * @default false
     */
    this.wireframe = false;

    /**
     * Gets or sets the index of the depth frustum to display.  This property is observable.
     * @type {Number}
     * @default 1
     */
    this.depthFrustum = 1;
    this._numberOfFrustums = 1;

    /**
     * Gets or sets the suspend updates state.  This property is observable.
     * @type {Boolean}
     * @default false
     */
    this.suspendUpdates = false;

    /**
     * Gets or sets the show tile coordinates state.  This property is observable.
     * @type {Boolean}
     * @default false
     */
    this.tileCoordinates = false;

    /**
     * Gets or sets the frustum statistic text.  This property is observable.
     * @type {String}
     * @default ''
     */
    this.frustumStatisticText = false;

    /**
     * Gets or sets the selected tile information text.  This property is observable.
     * @type {String}
     * @default ''
     */
    this.tileText = "";

    /**
     * Gets if a primitive has been selected.  This property is observable.
     * @type {Boolean}
     * @default false
     */
    this.hasPickedPrimitive = false;

    /**
     * Gets if a tile has been selected.  This property is observable
     * @type {Boolean}
     * @default false
     */
    this.hasPickedTile = false;

    /**
     * Gets if the picking primitive command is active.  This property is observable.
     * @type {Boolean}
     * @default false
     */
    this.pickPrimitiveActive = false;

    /**
     * Gets if the picking tile command is active.  This property is observable.
     * @type {Boolean}
     * @default false
     */
    this.pickTileActive = false;

    /**
     * Gets or sets if the cesium inspector drop down is visible.  This property is observable.
     * @type {Boolean}
     * @default true
     */
    this.dropDownVisible = true;

    /**
     * Gets or sets if the general section is visible.  This property is observable.
     * @type {Boolean}
     * @default true
     */
    this.generalVisible = true;

    /**
     * Gets or sets if the primitive section is visible.  This property is observable.
     * @type {Boolean}
     * @default false
     */
    this.primitivesVisible = false;

    /**
     * Gets or sets if the terrain section is visible.  This property is observable.
     * @type {Boolean}
     * @default false
     */
    this.terrainVisible = false;

    /**
     * Gets or sets the index of the depth frustum text.  This property is observable.
     * @type {String}
     * @default ''
     */
    this.depthFrustumText = "";

    knockout.track(this, [
      "frustums",
      "frustumPlanes",
      "performance",
      "shaderCacheText",
      "primitiveBoundingSphere",
      "primitiveReferenceFrame",
      "filterPrimitive",
      "tileBoundingSphere",
      "filterTile",
      "wireframe",
      "depthFrustum",
      "suspendUpdates",
      "tileCoordinates",
      "frustumStatisticText",
      "tileText",
      "hasPickedPrimitive",
      "hasPickedTile",
      "pickPrimitiveActive",
      "pickTileActive",
      "dropDownVisible",
      "generalVisible",
      "primitivesVisible",
      "terrainVisible",
      "depthFrustumText",
    ]);

    this._toggleDropDown = createCommand(function () {
      that.dropDownVisible = !that.dropDownVisible;
    });

    this._toggleGeneral = createCommand(function () {
      that.generalVisible = !that.generalVisible;
    });

    this._togglePrimitives = createCommand(function () {
      that.primitivesVisible = !that.primitivesVisible;
    });

    this._toggleTerrain = createCommand(function () {
      that.terrainVisible = !that.terrainVisible;
    });

    this._frustumsSubscription = knockout
      .getObservable(this, "frustums")
      .subscribe(function (val) {
        that._scene.debugShowFrustums = val;
        that._scene.requestRender();
      });

    this._frustumPlanesSubscription = knockout
      .getObservable(this, "frustumPlanes")
      .subscribe(function (val) {
        that._scene.debugShowFrustumPlanes = val;
        that._scene.requestRender();
      });

    this._performanceSubscription = knockout
      .getObservable(this, "performance")
      .subscribe(function (val) {
        if (val) {
          that._performanceDisplay = new PerformanceDisplay({
            container: that._performanceContainer,
          });
        } else {
          that._performanceContainer.innerHTML = "";
        }
      });

    this._showPrimitiveBoundingSphere = createCommand(function () {
      that._primitive.debugShowBoundingVolume = that.primitiveBoundingSphere;
      that._scene.requestRender();
      return true;
    });

    this._primitiveBoundingSphereSubscription = knockout
      .getObservable(this, "primitiveBoundingSphere")
      .subscribe(function () {
        that._showPrimitiveBoundingSphere();
      });

    this._showPrimitiveReferenceFrame = createCommand(function () {
      if (that.primitiveReferenceFrame) {
        const modelMatrix = that._primitive.modelMatrix;
        that._modelMatrixPrimitive = new DebugModelMatrixPrimitive({
          modelMatrix: modelMatrix,
        });
        that._scene.primitives.add(that._modelMatrixPrimitive);
      } else if (defined(that._modelMatrixPrimitive)) {
        that._scene.primitives.remove(that._modelMatrixPrimitive);
        that._modelMatrixPrimitive = undefined;
      }
      that._scene.requestRender();
      return true;
    });

    this._primitiveReferenceFrameSubscription = knockout
      .getObservable(this, "primitiveReferenceFrame")
      .subscribe(function () {
        that._showPrimitiveReferenceFrame();
      });

    this._doFilterPrimitive = createCommand(function () {
      if (that.filterPrimitive) {
        that._scene.debugCommandFilter = function (command) {
          if (
            defined(that._modelMatrixPrimitive) &&
            command.owner === that._modelMatrixPrimitive._primitive
          ) {
            return true;
          } else if (defined(that._primitive)) {
            return (
              command.owner === that._primitive ||
              command.owner === that._primitive._billboardCollection ||
              command.owner.primitive === that._primitive
            );
          }
          return false;
        };
      } else {
        that._scene.debugCommandFilter = undefined;
      }
      return true;
    });

    this._filterPrimitiveSubscription = knockout
      .getObservable(this, "filterPrimitive")
      .subscribe(function () {
        that._doFilterPrimitive();
        that._scene.requestRender();
      });

    this._wireframeSubscription = knockout
      .getObservable(this, "wireframe")
      .subscribe(function (val) {
        globe._surface.tileProvider._debug.wireframe = val;
        that._scene.requestRender();
      });

    this._depthFrustumSubscription = knockout
      .getObservable(this, "depthFrustum")
      .subscribe(function (val) {
        that._scene.debugShowDepthFrustum = val;
        that._scene.requestRender();
      });

    this._incrementDepthFrustum = createCommand(function () {
      const next = that.depthFrustum + 1;
      that.depthFrustum = boundDepthFrustum(1, that._numberOfFrustums, next);
      that._scene.requestRender();
      return true;
    });

    this._decrementDepthFrustum = createCommand(function () {
      const next = that.depthFrustum - 1;
      that.depthFrustum = boundDepthFrustum(1, that._numberOfFrustums, next);
      that._scene.requestRender();
      return true;
    });

    this._suspendUpdatesSubscription = knockout
      .getObservable(this, "suspendUpdates")
      .subscribe(function (val) {
        globe._surface._debug.suspendLodUpdate = val;
        if (!val) {
          that.filterTile = false;
        }
      });

    let tileBoundariesLayer;
    this._showTileCoordinates = createCommand(function () {
      if (that.tileCoordinates && !defined(tileBoundariesLayer)) {
        tileBoundariesLayer = scene.imageryLayers.addImageryProvider(
          new TileCoordinatesImageryProvider({
            tilingScheme: scene.terrainProvider.tilingScheme,
          })
        );
      } else if (!that.tileCoordinates && defined(tileBoundariesLayer)) {
        scene.imageryLayers.remove(tileBoundariesLayer);
        tileBoundariesLayer = undefined;
      }
      return true;
    });

    this._tileCoordinatesSubscription = knockout
      .getObservable(this, "tileCoordinates")
      .subscribe(function () {
        that._showTileCoordinates();
        that._scene.requestRender();
      });

    this._tileBoundingSphereSubscription = knockout
      .getObservable(this, "tileBoundingSphere")
      .subscribe(function () {
        that._showTileBoundingSphere();
        that._scene.requestRender();
      });

    this._showTileBoundingSphere = createCommand(function () {
      if (that.tileBoundingSphere) {
        globe._surface.tileProvider._debug.boundingSphereTile = that._tile;
      } else {
        globe._surface.tileProvider._debug.boundingSphereTile = undefined;
      }
      that._scene.requestRender();
      return true;
    });

    this._doFilterTile = createCommand(function () {
      if (!that.filterTile) {
        that.suspendUpdates = false;
      } else {
        that.suspendUpdates = true;

        globe._surface._tilesToRender = [];

        if (defined(that._tile) && that._tile.renderable) {
          globe._surface._tilesToRender.push(that._tile);
        }
      }
      return true;
    });

    this._filterTileSubscription = knockout
      .getObservable(this, "filterTile")
      .subscribe(function () {
        that.doFilterTile();
        that._scene.requestRender();
      });

    function pickPrimitive(e) {
      const newPick = that._scene.pick({
        x: e.position.x,
        y: e.position.y,
      });
      if (defined(newPick)) {
        that.primitive = defined(newPick.collection)
          ? newPick.collection
          : newPick.primitive;
      }

      that._scene.requestRender();
      that.pickPrimitiveActive = false;
    }

    this._pickPrimitive = createCommand(function () {
      that.pickPrimitiveActive = !that.pickPrimitiveActive;
    });

    this._pickPrimitiveActiveSubscription = knockout
      .getObservable(this, "pickPrimitiveActive")
      .subscribe(function (val) {
        if (val) {
          eventHandler.setInputAction(
            pickPrimitive,
            ScreenSpaceEventType$1.LEFT_CLICK
          );
        } else {
          eventHandler.removeInputAction(ScreenSpaceEventType$1.LEFT_CLICK);
        }
      });

    function selectTile(e) {
      let selectedTile;
      const ellipsoid = globe.ellipsoid;

      const ray = that._scene.camera.getPickRay(e.position, scratchPickRay);
      const cartesian = globe.pick(ray, that._scene, scratchPickCartesian);

      if (defined(cartesian)) {
        const cartographic = ellipsoid.cartesianToCartographic(cartesian);
        const tilesRendered =
          globe._surface.tileProvider._tilesToRenderByTextureCount;
        for (
          let textureCount = 0;
          !selectedTile && textureCount < tilesRendered.length;
          ++textureCount
        ) {
          const tilesRenderedByTextureCount = tilesRendered[textureCount];
          if (!defined(tilesRenderedByTextureCount)) {
            continue;
          }

          for (
            let tileIndex = 0;
            !selectedTile && tileIndex < tilesRenderedByTextureCount.length;
            ++tileIndex
          ) {
            const tile = tilesRenderedByTextureCount[tileIndex];
            if (Rectangle.contains(tile.rectangle, cartographic)) {
              selectedTile = tile;
            }
          }
        }
      }

      that.tile = selectedTile;

      that.pickTileActive = false;
    }

    this._pickTile = createCommand(function () {
      that.pickTileActive = !that.pickTileActive;
    });

    this._pickTileActiveSubscription = knockout
      .getObservable(this, "pickTileActive")
      .subscribe(function (val) {
        if (val) {
          eventHandler.setInputAction(
            selectTile,
            ScreenSpaceEventType$1.LEFT_CLICK
          );
        } else {
          eventHandler.removeInputAction(ScreenSpaceEventType$1.LEFT_CLICK);
        }
      });

    this._removePostRenderEvent = scene.postRender.addEventListener(function () {
      that._update();
    });
  }

  Object.defineProperties(CesiumInspectorViewModel.prototype, {
    /**
     * Gets the scene to control.
     * @memberof CesiumInspectorViewModel.prototype
     *
     * @type {Scene}
     */
    scene: {
      get: function () {
        return this._scene;
      },
    },

    /**
     * Gets the container of the PerformanceDisplay
     * @memberof CesiumInspectorViewModel.prototype
     *
     * @type {Element}
     */
    performanceContainer: {
      get: function () {
        return this._performanceContainer;
      },
    },

    /**
     * Gets the command to toggle the visibility of the drop down.
     * @memberof CesiumInspectorViewModel.prototype
     *
     * @type {Command}
     */
    toggleDropDown: {
      get: function () {
        return this._toggleDropDown;
      },
    },

    /**
     * Gets the command to toggle the visibility of a BoundingSphere for a primitive
     * @memberof CesiumInspectorViewModel.prototype
     *
     * @type {Command}
     */
    showPrimitiveBoundingSphere: {
      get: function () {
        return this._showPrimitiveBoundingSphere;
      },
    },

    /**
     * Gets the command to toggle the visibility of a {@link DebugModelMatrixPrimitive} for the model matrix of a primitive
     * @memberof CesiumInspectorViewModel.prototype
     *
     * @type {Command}
     */
    showPrimitiveReferenceFrame: {
      get: function () {
        return this._showPrimitiveReferenceFrame;
      },
    },

    /**
     * Gets the command to toggle a filter that renders only a selected primitive
     * @memberof CesiumInspectorViewModel.prototype
     *
     * @type {Command}
     */
    doFilterPrimitive: {
      get: function () {
        return this._doFilterPrimitive;
      },
    },

    /**
     * Gets the command to increment the depth frustum index to be shown
     * @memberof CesiumInspectorViewModel.prototype
     *
     * @type {Command}
     */
    incrementDepthFrustum: {
      get: function () {
        return this._incrementDepthFrustum;
      },
    },

    /**
     * Gets the command to decrement the depth frustum index to be shown
     * @memberof CesiumInspectorViewModel.prototype
     *
     * @type {Command}
     */
    decrementDepthFrustum: {
      get: function () {
        return this._decrementDepthFrustum;
      },
    },

    /**
     * Gets the command to toggle the visibility of tile coordinates
     * @memberof CesiumInspectorViewModel.prototype
     *
     * @type {Command}
     */
    showTileCoordinates: {
      get: function () {
        return this._showTileCoordinates;
      },
    },

    /**
     * Gets the command to toggle the visibility of a BoundingSphere for a selected tile
     * @memberof CesiumInspectorViewModel.prototype
     *
     * @type {Command}
     */
    showTileBoundingSphere: {
      get: function () {
        return this._showTileBoundingSphere;
      },
    },

    /**
     * Gets the command to toggle a filter that renders only a selected tile
     * @memberof CesiumInspectorViewModel.prototype
     *
     * @type {Command}
     */
    doFilterTile: {
      get: function () {
        return this._doFilterTile;
      },
    },

    /**
     * Gets the command to expand and collapse the general section
     * @memberof CesiumInspectorViewModel.prototype
     *
     * @type {Command}
     */
    toggleGeneral: {
      get: function () {
        return this._toggleGeneral;
      },
    },

    /**
     * Gets the command to expand and collapse the primitives section
     * @memberof CesiumInspectorViewModel.prototype
     *
     * @type {Command}
     */
    togglePrimitives: {
      get: function () {
        return this._togglePrimitives;
      },
    },

    /**
     * Gets the command to expand and collapse the terrain section
     * @memberof CesiumInspectorViewModel.prototype
     *
     * @type {Command}
     */
    toggleTerrain: {
      get: function () {
        return this._toggleTerrain;
      },
    },

    /**
     * Gets the command to pick a primitive
     * @memberof CesiumInspectorViewModel.prototype
     *
     * @type {Command}
     */
    pickPrimitive: {
      get: function () {
        return this._pickPrimitive;
      },
    },

    /**
     * Gets the command to pick a tile
     * @memberof CesiumInspectorViewModel.prototype
     *
     * @type {Command}
     */
    pickTile: {
      get: function () {
        return this._pickTile;
      },
    },

    /**
     * Gets the command to pick a tile
     * @memberof CesiumInspectorViewModel.prototype
     *
     * @type {Command}
     */
    selectParent: {
      get: function () {
        const that = this;
        return createCommand(function () {
          that.tile = that.tile.parent;
        });
      },
    },

    /**
     * Gets the command to pick a tile
     * @memberof CesiumInspectorViewModel.prototype
     *
     * @type {Command}
     */
    selectNW: {
      get: function () {
        const that = this;
        return createCommand(function () {
          that.tile = that.tile.northwestChild;
        });
      },
    },

    /**
     * Gets the command to pick a tile
     * @memberof CesiumInspectorViewModel.prototype
     *
     * @type {Command}
     */
    selectNE: {
      get: function () {
        const that = this;
        return createCommand(function () {
          that.tile = that.tile.northeastChild;
        });
      },
    },

    /**
     * Gets the command to pick a tile
     * @memberof CesiumInspectorViewModel.prototype
     *
     * @type {Command}
     */
    selectSW: {
      get: function () {
        const that = this;
        return createCommand(function () {
          that.tile = that.tile.southwestChild;
        });
      },
    },

    /**
     * Gets the command to pick a tile
     * @memberof CesiumInspectorViewModel.prototype
     *
     * @type {Command}
     */
    selectSE: {
      get: function () {
        const that = this;
        return createCommand(function () {
          that.tile = that.tile.southeastChild;
        });
      },
    },

    /**
     * Gets or sets the current selected primitive
     * @memberof CesiumInspectorViewModel.prototype
     *
     * @type {Command}
     */
    primitive: {
      get: function () {
        return this._primitive;
      },
      set: function (newPrimitive) {
        const oldPrimitive = this._primitive;
        if (newPrimitive !== oldPrimitive) {
          this.hasPickedPrimitive = true;
          if (defined(oldPrimitive)) {
            oldPrimitive.debugShowBoundingVolume = false;
          }
          this._scene.debugCommandFilter = undefined;
          if (defined(this._modelMatrixPrimitive)) {
            this._scene.primitives.remove(this._modelMatrixPrimitive);
            this._modelMatrixPrimitive = undefined;
          }
          this._primitive = newPrimitive;
          newPrimitive.show = false;
          setTimeout(function () {
            newPrimitive.show = true;
          }, 50);
          this.showPrimitiveBoundingSphere();
          this.showPrimitiveReferenceFrame();
          this.doFilterPrimitive();
        }
      },
    },

    /**
     * Gets or sets the current selected tile
     * @memberof CesiumInspectorViewModel.prototype
     *
     * @type {Command}
     */
    tile: {
      get: function () {
        return this._tile;
      },
      set: function (newTile) {
        if (defined(newTile)) {
          this.hasPickedTile = true;
          const oldTile = this._tile;
          if (newTile !== oldTile) {
            this.tileText = `L: ${newTile.level} X: ${newTile.x} Y: ${newTile.y}`;
            this.tileText += `<br>SW corner: ${newTile.rectangle.west}, ${newTile.rectangle.south}`;
            this.tileText += `<br>NE corner: ${newTile.rectangle.east}, ${newTile.rectangle.north}`;
            const data = newTile.data;
            if (defined(data) && defined(data.tileBoundingRegion)) {
              this.tileText += `<br>Min: ${data.tileBoundingRegion.minimumHeight} Max: ${data.tileBoundingRegion.maximumHeight}`;
            } else {
              this.tileText += "<br>(Tile is not loaded)";
            }
          }
          this._tile = newTile;
          this.showTileBoundingSphere();
          this.doFilterTile();
        } else {
          this.hasPickedTile = false;
          this._tile = undefined;
        }
      },
    },
  });

  /**
   * Updates the view model
   * @private
   */
  CesiumInspectorViewModel.prototype._update = function () {
    if (this.frustums) {
      this.frustumStatisticText = frustumStatisticsToString(
        this._scene.debugFrustumStatistics
      );
    }

    // Determine the number of frustums being used.
    const numberOfFrustums = this._scene.numberOfFrustums;
    this._numberOfFrustums = numberOfFrustums;
    // Bound the frustum to be displayed.
    this.depthFrustum = boundDepthFrustum(1, numberOfFrustums, this.depthFrustum);
    // Update the displayed text.
    this.depthFrustumText = `${this.depthFrustum} of ${numberOfFrustums}`;

    if (this.performance) {
      this._performanceDisplay.update();
    }
    if (this.primitiveReferenceFrame) {
      this._modelMatrixPrimitive.modelMatrix = this._primitive.modelMatrix;
    }

    this.shaderCacheText = `Cached shaders: ${this._scene.context.shaderCache.numberOfShaders}`;
  };

  /**
   * @returns {Boolean} true if the object has been destroyed, false otherwise.
   */
  CesiumInspectorViewModel.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the widget.  Should be called if permanently
   * removing the widget from layout.
   */
  CesiumInspectorViewModel.prototype.destroy = function () {
    this._eventHandler.destroy();
    this._removePostRenderEvent();
    this._frustumsSubscription.dispose();
    this._frustumPlanesSubscription.dispose();
    this._performanceSubscription.dispose();
    this._primitiveBoundingSphereSubscription.dispose();
    this._primitiveReferenceFrameSubscription.dispose();
    this._filterPrimitiveSubscription.dispose();
    this._wireframeSubscription.dispose();
    this._depthFrustumSubscription.dispose();
    this._suspendUpdatesSubscription.dispose();
    this._tileCoordinatesSubscription.dispose();
    this._tileBoundingSphereSubscription.dispose();
    this._filterTileSubscription.dispose();
    this._pickPrimitiveActiveSubscription.dispose();
    this._pickTileActiveSubscription.dispose();
    return destroyObject(this);
  };

  /**
   * Inspector widget to aid in debugging
   *
   * @alias CesiumInspector
   * @constructor
   *
   * @param {Element|String} container The DOM element or ID that will contain the widget.
   * @param {Scene} scene The Scene instance to use.
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Cesium%20Inspector.html|Cesium Sandcastle Cesium Inspector Demo}
   */
  function CesiumInspector(container, scene) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(container)) {
      throw new DeveloperError("container is required.");
    }

    if (!defined(scene)) {
      throw new DeveloperError("scene is required.");
    }
    //>>includeEnd('debug');

    container = getElement(container);

    const performanceContainer = document.createElement("div");

    const viewModel = new CesiumInspectorViewModel(scene, performanceContainer);
    this._viewModel = viewModel;
    this._container = container;

    const element = document.createElement("div");
    this._element = element;
    const text = document.createElement("div");
    text.textContent = "Cesium Inspector";
    text.className = "cesium-cesiumInspector-button";
    text.setAttribute("data-bind", "click: toggleDropDown");
    element.appendChild(text);
    element.className = "cesium-cesiumInspector";
    element.setAttribute(
      "data-bind",
      'css: { "cesium-cesiumInspector-visible" : dropDownVisible, "cesium-cesiumInspector-hidden" : !dropDownVisible }'
    );
    container.appendChild(this._element);

    const panel = document.createElement("div");
    this._panel = panel;
    panel.className = "cesium-cesiumInspector-dropDown";
    element.appendChild(panel);

    const createSection = InspectorShared.createSection;
    const createCheckbox = InspectorShared.createCheckbox;

    // General
    const generalSection = createSection(
      panel,
      "General",
      "generalVisible",
      "toggleGeneral"
    );

    const debugShowFrustums = createCheckbox("Show Frustums", "frustums");
    const frustumStatistics = document.createElement("div");
    frustumStatistics.className = "cesium-cesiumInspector-frustumStatistics";
    frustumStatistics.setAttribute(
      "data-bind",
      "visible: frustums, html: frustumStatisticText"
    );
    debugShowFrustums.appendChild(frustumStatistics);
    generalSection.appendChild(debugShowFrustums);

    generalSection.appendChild(
      createCheckbox("Show Frustum Planes", "frustumPlanes")
    );
    generalSection.appendChild(
      createCheckbox("Performance Display", "performance")
    );

    performanceContainer.className = "cesium-cesiumInspector-performanceDisplay";
    generalSection.appendChild(performanceContainer);

    const shaderCacheDisplay = document.createElement("div");
    shaderCacheDisplay.className = "cesium-cesiumInspector-shaderCache";
    shaderCacheDisplay.setAttribute("data-bind", "html: shaderCacheText");
    generalSection.appendChild(shaderCacheDisplay);

    const depthFrustum = document.createElement("div");
    generalSection.appendChild(depthFrustum);

    // Use a span with HTML binding so that we can indent with non-breaking spaces.
    const gLabel = document.createElement("span");
    gLabel.setAttribute(
      "data-bind",
      'html: "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Frustum:"'
    );
    depthFrustum.appendChild(gLabel);

    const gText = document.createElement("span");
    gText.setAttribute("data-bind", "text: depthFrustumText");
    depthFrustum.appendChild(gText);

    const gMinusButton = document.createElement("input");
    gMinusButton.type = "button";
    gMinusButton.value = "-";
    gMinusButton.className = "cesium-cesiumInspector-pickButton";
    gMinusButton.setAttribute("data-bind", "click: decrementDepthFrustum");
    depthFrustum.appendChild(gMinusButton);

    const gPlusButton = document.createElement("input");
    gPlusButton.type = "button";
    gPlusButton.value = "+";
    gPlusButton.className = "cesium-cesiumInspector-pickButton";
    gPlusButton.setAttribute("data-bind", "click: incrementDepthFrustum");
    depthFrustum.appendChild(gPlusButton);

    // Primitives
    const primSection = createSection(
      panel,
      "Primitives",
      "primitivesVisible",
      "togglePrimitives"
    );
    const pickPrimRequired = document.createElement("div");
    pickPrimRequired.className = "cesium-cesiumInspector-pickSection";
    primSection.appendChild(pickPrimRequired);

    const pickPrimitiveButton = document.createElement("input");
    pickPrimitiveButton.type = "button";
    pickPrimitiveButton.value = "Pick a primitive";
    pickPrimitiveButton.className = "cesium-cesiumInspector-pickButton";
    pickPrimitiveButton.setAttribute(
      "data-bind",
      'css: {"cesium-cesiumInspector-pickButtonHighlight" : pickPrimitiveActive}, click: pickPrimitive'
    );
    let buttonWrap = document.createElement("div");
    buttonWrap.className = "cesium-cesiumInspector-center";
    buttonWrap.appendChild(pickPrimitiveButton);
    pickPrimRequired.appendChild(buttonWrap);

    pickPrimRequired.appendChild(
      createCheckbox(
        "Show bounding sphere",
        "primitiveBoundingSphere",
        "hasPickedPrimitive"
      )
    );
    pickPrimRequired.appendChild(
      createCheckbox(
        "Show reference frame",
        "primitiveReferenceFrame",
        "hasPickedPrimitive"
      )
    );

    this._primitiveOnly = createCheckbox(
      "Show only selected",
      "filterPrimitive",
      "hasPickedPrimitive"
    );
    pickPrimRequired.appendChild(this._primitiveOnly);

    // Terrain
    const terrainSection = createSection(
      panel,
      "Terrain",
      "terrainVisible",
      "toggleTerrain"
    );
    const pickTileRequired = document.createElement("div");
    pickTileRequired.className = "cesium-cesiumInspector-pickSection";
    terrainSection.appendChild(pickTileRequired);
    const pickTileButton = document.createElement("input");
    pickTileButton.type = "button";
    pickTileButton.value = "Pick a tile";
    pickTileButton.className = "cesium-cesiumInspector-pickButton";
    pickTileButton.setAttribute(
      "data-bind",
      'css: {"cesium-cesiumInspector-pickButtonHighlight" : pickTileActive}, click: pickTile'
    );
    buttonWrap = document.createElement("div");
    buttonWrap.appendChild(pickTileButton);
    buttonWrap.className = "cesium-cesiumInspector-center";
    pickTileRequired.appendChild(buttonWrap);
    const tileInfo = document.createElement("div");
    pickTileRequired.appendChild(tileInfo);
    const parentTile = document.createElement("input");
    parentTile.type = "button";
    parentTile.value = "Parent";
    parentTile.className = "cesium-cesiumInspector-pickButton";
    parentTile.setAttribute("data-bind", "click: selectParent");
    const nwTile = document.createElement("input");
    nwTile.type = "button";
    nwTile.value = "NW";
    nwTile.className = "cesium-cesiumInspector-pickButton";
    nwTile.setAttribute("data-bind", "click: selectNW");
    const neTile = document.createElement("input");
    neTile.type = "button";
    neTile.value = "NE";
    neTile.className = "cesium-cesiumInspector-pickButton";
    neTile.setAttribute("data-bind", "click: selectNE");
    const swTile = document.createElement("input");
    swTile.type = "button";
    swTile.value = "SW";
    swTile.className = "cesium-cesiumInspector-pickButton";
    swTile.setAttribute("data-bind", "click: selectSW");
    const seTile = document.createElement("input");
    seTile.type = "button";
    seTile.value = "SE";
    seTile.className = "cesium-cesiumInspector-pickButton";
    seTile.setAttribute("data-bind", "click: selectSE");

    const tileText = document.createElement("div");
    tileText.className = "cesium-cesiumInspector-tileText";
    tileInfo.className = "cesium-cesiumInspector-frustumStatistics";
    tileInfo.appendChild(tileText);
    tileInfo.setAttribute("data-bind", "visible: hasPickedTile");
    tileText.setAttribute("data-bind", "html: tileText");

    const relativeText = document.createElement("div");
    relativeText.className = "cesium-cesiumInspector-relativeText";
    relativeText.textContent = "Select relative:";
    tileInfo.appendChild(relativeText);

    const table = document.createElement("table");
    const tr1 = document.createElement("tr");
    const tr2 = document.createElement("tr");
    const td1 = document.createElement("td");
    td1.appendChild(parentTile);
    const td2 = document.createElement("td");
    td2.appendChild(nwTile);
    const td3 = document.createElement("td");
    td3.appendChild(neTile);
    tr1.appendChild(td1);
    tr1.appendChild(td2);
    tr1.appendChild(td3);
    const td4 = document.createElement("td");
    const td5 = document.createElement("td");
    td5.appendChild(swTile);
    const td6 = document.createElement("td");
    td6.appendChild(seTile);
    tr2.appendChild(td4);
    tr2.appendChild(td5);
    tr2.appendChild(td6);
    table.appendChild(tr1);
    table.appendChild(tr2);

    tileInfo.appendChild(table);

    pickTileRequired.appendChild(
      createCheckbox(
        "Show bounding volume",
        "tileBoundingSphere",
        "hasPickedTile"
      )
    );
    pickTileRequired.appendChild(
      createCheckbox("Show only selected", "filterTile", "hasPickedTile")
    );

    terrainSection.appendChild(createCheckbox("Wireframe", "wireframe"));
    terrainSection.appendChild(
      createCheckbox("Suspend LOD update", "suspendUpdates")
    );
    terrainSection.appendChild(
      createCheckbox("Show tile coordinates", "tileCoordinates")
    );

    knockout.applyBindings(viewModel, this._element);
  }

  Object.defineProperties(CesiumInspector.prototype, {
    /**
     * Gets the parent container.
     * @memberof CesiumInspector.prototype
     *
     * @type {Element}
     */
    container: {
      get: function () {
        return this._container;
      },
    },

    /**
     * Gets the view model.
     * @memberof CesiumInspector.prototype
     *
     * @type {CesiumInspectorViewModel}
     */
    viewModel: {
      get: function () {
        return this._viewModel;
      },
    },
  });

  /**
   * @returns {Boolean} true if the object has been destroyed, false otherwise.
   */
  CesiumInspector.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the widget.  Should be called if permanently
   * removing the widget from layout.
   */
  CesiumInspector.prototype.destroy = function () {
    knockout.cleanNode(this._element);
    this._container.removeChild(this._element);
    this.viewModel.destroy();

    return destroyObject(this);
  };

  function getDefaultSkyBoxUrl(suffix) {
    return buildModuleUrl(`Assets/Textures/SkyBox/tycho2t3_80_${suffix}.jpg`);
  }

  function startRenderLoop(widget) {
    widget._renderLoopRunning = true;

    let lastFrameTime = 0;
    function render(frameTime) {
      if (widget.isDestroyed()) {
        return;
      }

      if (widget._useDefaultRenderLoop) {
        try {
          const targetFrameRate = widget._targetFrameRate;
          if (!defined(targetFrameRate)) {
            widget.resize();
            widget.render();
            requestAnimationFramePolyFill(render);
          } else {
            const interval = 1000.0 / targetFrameRate;
            const delta = frameTime - lastFrameTime;

            if (delta > interval) {
              widget.resize();
              widget.render();
              lastFrameTime = frameTime - (delta % interval);
            }
            requestAnimationFramePolyFill(render);
          }
        } catch (error) {
          widget._useDefaultRenderLoop = false;
          widget._renderLoopRunning = false;
          if (widget._showRenderLoopErrors) {
            const title =
              "An error occurred while rendering.  Rendering has stopped.";
            widget.showErrorPanel(title, undefined, error);
          }
        }
      } else {
        widget._renderLoopRunning = false;
      }
    }

    requestAnimationFramePolyFill(render);
  }

  function configurePixelRatio(widget) {
    let pixelRatio = widget._useBrowserRecommendedResolution
      ? 1.0
      : window.devicePixelRatio;
    pixelRatio *= widget._resolutionScale;
    if (defined(widget._scene)) {
      widget._scene.pixelRatio = pixelRatio;
    }

    return pixelRatio;
  }

  function configureCanvasSize(widget) {
    const canvas = widget._canvas;
    let width = canvas.clientWidth;
    let height = canvas.clientHeight;
    const pixelRatio = configurePixelRatio(widget);

    widget._canvasClientWidth = width;
    widget._canvasClientHeight = height;

    width *= pixelRatio;
    height *= pixelRatio;

    canvas.width = width;
    canvas.height = height;

    widget._canRender = width !== 0 && height !== 0;
    widget._lastDevicePixelRatio = window.devicePixelRatio;
  }

  function configureCameraFrustum(widget) {
    const canvas = widget._canvas;
    const width = canvas.width;
    const height = canvas.height;
    if (width !== 0 && height !== 0) {
      const frustum = widget._scene.camera.frustum;
      if (defined(frustum.aspectRatio)) {
        frustum.aspectRatio = width / height;
      } else {
        frustum.top = frustum.right * (height / width);
        frustum.bottom = -frustum.top;
      }
    }
  }

  /**
   * A widget containing a Cesium scene.
   *
   * @alias CesiumWidget
   * @constructor
   *
   * @param {Element|String} container The DOM element or ID that will contain the widget.
   * @param {Object} [options] Object with the following properties:
   * @param {Clock} [options.clock=new Clock()] The clock to use to control current time.
   * @param {ImageryProvider | false} [options.imageryProvider=createWorldImagery()] The imagery provider to serve as the base layer. If set to <code>false</code>, no imagery provider will be added.
   * @param {TerrainProvider} [options.terrainProvider=new EllipsoidTerrainProvider] The terrain provider.
   * @param {SkyBox| false} [options.skyBox] The skybox used to render the stars.  When <code>undefined</code>, the default stars are used. If set to <code>false</code>, no skyBox, Sun, or Moon will be added.
   * @param {SkyAtmosphere | false} [options.skyAtmosphere] Blue sky, and the glow around the Earth's limb.  Set to <code>false</code> to turn it off.
   * @param {SceneMode} [options.sceneMode=SceneMode.SCENE3D] The initial scene mode.
   * @param {Boolean} [options.scene3DOnly=false] When <code>true</code>, each geometry instance will only be rendered in 3D to save GPU memory.
   * @param {Boolean} [options.orderIndependentTranslucency=true] If true and the configuration supports it, use order independent translucency.
   * @param {MapProjection} [options.mapProjection=new GeographicProjection()] The map projection to use in 2D and Columbus View modes.
   * @param {Globe | false} [options.globe=new Globe(mapProjection.ellipsoid)] The globe to use in the scene.  If set to <code>false</code>, no globe will be added.
   * @param {Boolean} [options.useDefaultRenderLoop=true] True if this widget should control the render loop, false otherwise.
   * @param {Boolean} [options.useBrowserRecommendedResolution=true] If true, render at the browser's recommended resolution and ignore <code>window.devicePixelRatio</code>.
   * @param {Number} [options.targetFrameRate] The target frame rate when using the default render loop.
   * @param {Boolean} [options.showRenderLoopErrors=true] If true, this widget will automatically display an HTML panel to the user containing the error, if a render loop error occurs.
   * @param {Object} [options.contextOptions] Context and WebGL creation properties corresponding to <code>options</code> passed to {@link Scene}.
   * @param {Element|String} [options.creditContainer] The DOM element or ID that will contain the {@link CreditDisplay}.  If not specified, the credits are added
   *        to the bottom of the widget itself.
   * @param {Element|String} [options.creditViewport] The DOM element or ID that will contain the credit pop up created by the {@link CreditDisplay}.  If not specified, it will appear over the widget itself.
   * @param {Boolean} [options.shadows=false] Determines if shadows are cast by light sources.
   * @param {ShadowMode} [options.terrainShadows=ShadowMode.RECEIVE_ONLY] Determines if the terrain casts or receives shadows from light sources.
   * @param {MapMode2D} [options.mapMode2D=MapMode2D.INFINITE_SCROLL] Determines if the 2D map is rotatable or can be scrolled infinitely in the horizontal direction.
   * @param {Boolean} [options.requestRenderMode=false] If true, rendering a frame will only occur when needed as determined by changes within the scene. Enabling improves performance of the application, but requires using {@link Scene#requestRender} to render a new frame explicitly in this mode. This will be necessary in many cases after making changes to the scene in other parts of the API. See {@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|Improving Performance with Explicit Rendering}.
   * @param {Number} [options.maximumRenderTimeChange=0.0] If requestRenderMode is true, this value defines the maximum change in simulation time allowed before a render is requested. See {@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|Improving Performance with Explicit Rendering}.
   * @param {Number} [options.msaaSamples=1] If provided, this value controls the rate of multisample antialiasing. Typical multisampling rates are 2, 4, and sometimes 8 samples per pixel. Higher sampling rates of MSAA may impact performance in exchange for improved visual quality. This value only applies to WebGL2 contexts that support multisample render targets.
   *
   * @exception {DeveloperError} Element with id "container" does not exist in the document.
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Cesium%20Widget.html|Cesium Sandcastle Cesium Widget Demo}
   *
   * @example
   * // For each example, include a link to CesiumWidget.css stylesheet in HTML head,
   * // and in the body, include: <div id="cesiumContainer"></div>
   *
   * //Widget with no terrain and default Bing Maps imagery provider.
   * const widget = new Cesium.CesiumWidget('cesiumContainer');
   *
   * //Widget with ion imagery and Cesium World Terrain.
   * const widget2 = new Cesium.CesiumWidget('cesiumContainer', {
   *     imageryProvider : Cesium.createWorldImagery(),
   *     terrainProvider : Cesium.createWorldTerrain(),
   *     skyBox : new Cesium.SkyBox({
   *         sources : {
   *           positiveX : 'stars/TychoSkymapII.t3_08192x04096_80_px.jpg',
   *           negativeX : 'stars/TychoSkymapII.t3_08192x04096_80_mx.jpg',
   *           positiveY : 'stars/TychoSkymapII.t3_08192x04096_80_py.jpg',
   *           negativeY : 'stars/TychoSkymapII.t3_08192x04096_80_my.jpg',
   *           positiveZ : 'stars/TychoSkymapII.t3_08192x04096_80_pz.jpg',
   *           negativeZ : 'stars/TychoSkymapII.t3_08192x04096_80_mz.jpg'
   *         }
   *     }),
   *     // Show Columbus View map with Web Mercator projection
   *     sceneMode : Cesium.SceneMode.COLUMBUS_VIEW,
   *     mapProjection : new Cesium.WebMercatorProjection()
   * });
   */
  function CesiumWidget(container, options) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(container)) {
      throw new DeveloperError("container is required.");
    }
    //>>includeEnd('debug');

    container = getElement(container);

    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //Configure the widget DOM elements
    const element = document.createElement("div");
    element.className = "cesium-widget";
    container.appendChild(element);

    const canvas = document.createElement("canvas");
    const supportsImageRenderingPixelated = FeatureDetection.supportsImageRenderingPixelated();
    this._supportsImageRenderingPixelated = supportsImageRenderingPixelated;
    if (supportsImageRenderingPixelated) {
      canvas.style.imageRendering = FeatureDetection.imageRenderingValue();
    }

    canvas.oncontextmenu = function () {
      return false;
    };
    canvas.onselectstart = function () {
      return false;
    };

    // Interacting with a canvas does not automatically blur the previously focused element.
    // This leads to unexpected interaction if the last element was an input field.
    // For example, clicking the mouse wheel could lead to the value in  the field changing
    // unexpectedly. The solution is to blur whatever has focus as soon as canvas interaction begins.
    function blurActiveElement() {
      if (canvas !== canvas.ownerDocument.activeElement) {
        canvas.ownerDocument.activeElement.blur();
      }
    }
    canvas.addEventListener("mousedown", blurActiveElement);
    canvas.addEventListener("pointerdown", blurActiveElement);

    element.appendChild(canvas);

    const innerCreditContainer = document.createElement("div");
    innerCreditContainer.className = "cesium-widget-credits";

    const creditContainer = defined(options.creditContainer)
      ? getElement(options.creditContainer)
      : element;
    creditContainer.appendChild(innerCreditContainer);

    const creditViewport = defined(options.creditViewport)
      ? getElement(options.creditViewport)
      : element;

    const showRenderLoopErrors = defaultValue(options.showRenderLoopErrors, true);

    const useBrowserRecommendedResolution = defaultValue(
      options.useBrowserRecommendedResolution,
      true
    );

    this._element = element;
    this._container = container;
    this._canvas = canvas;
    this._canvasClientWidth = 0;
    this._canvasClientHeight = 0;
    this._lastDevicePixelRatio = 0;
    this._creditViewport = creditViewport;
    this._creditContainer = creditContainer;
    this._innerCreditContainer = innerCreditContainer;
    this._canRender = false;
    this._renderLoopRunning = false;
    this._showRenderLoopErrors = showRenderLoopErrors;
    this._resolutionScale = 1.0;
    this._useBrowserRecommendedResolution = useBrowserRecommendedResolution;
    this._forceResize = false;
    this._clock = defined(options.clock) ? options.clock : new Clock();

    configureCanvasSize(this);

    try {
      const scene = new Scene({
        canvas: canvas,
        contextOptions: options.contextOptions,
        creditContainer: innerCreditContainer,
        creditViewport: creditViewport,
        mapProjection: options.mapProjection,
        orderIndependentTranslucency: options.orderIndependentTranslucency,
        scene3DOnly: defaultValue(options.scene3DOnly, false),
        shadows: options.shadows,
        mapMode2D: options.mapMode2D,
        requestRenderMode: options.requestRenderMode,
        maximumRenderTimeChange: options.maximumRenderTimeChange,
        depthPlaneEllipsoidOffset: options.depthPlaneEllipsoidOffset,
        msaaSamples: options.msaaSamples,
      });
      this._scene = scene;

      scene.camera.constrainedAxis = Cartesian3.UNIT_Z;

      configurePixelRatio(this);
      configureCameraFrustum(this);

      const ellipsoid = defaultValue(
        scene.mapProjection.ellipsoid,
        Ellipsoid.WGS84
      );

      let globe = options.globe;
      if (!defined(globe)) {
        globe = new Globe(ellipsoid);
      }
      if (globe !== false) {
        scene.globe = globe;
        scene.globe.shadows = defaultValue(
          options.terrainShadows,
          ShadowMode$1.RECEIVE_ONLY
        );
      }

      let skyBox = options.skyBox;
      if (!defined(skyBox)) {
        skyBox = new SkyBox({
          sources: {
            positiveX: getDefaultSkyBoxUrl("px"),
            negativeX: getDefaultSkyBoxUrl("mx"),
            positiveY: getDefaultSkyBoxUrl("py"),
            negativeY: getDefaultSkyBoxUrl("my"),
            positiveZ: getDefaultSkyBoxUrl("pz"),
            negativeZ: getDefaultSkyBoxUrl("mz"),
          },
        });
      }
      if (skyBox !== false) {
        scene.skyBox = skyBox;
        scene.sun = new Sun();
        scene.moon = new Moon();
      }

      // Blue sky, and the glow around the Earth's limb.
      let skyAtmosphere = options.skyAtmosphere;
      if (!defined(skyAtmosphere)) {
        skyAtmosphere = new SkyAtmosphere(ellipsoid);
      }
      if (skyAtmosphere !== false) {
        scene.skyAtmosphere = skyAtmosphere;
      }

      //Set the base imagery layer
      let imageryProvider =
        options.globe === false ? false : options.imageryProvider;
      if (!defined(imageryProvider)) {
        imageryProvider = createWorldImagery();
      }

      if (imageryProvider !== false) {
        scene.imageryLayers.addImageryProvider(imageryProvider);
      }

      //Set the terrain provider if one is provided.
      if (defined(options.terrainProvider) && options.globe !== false) {
        scene.terrainProvider = options.terrainProvider;
      }

      this._screenSpaceEventHandler = new ScreenSpaceEventHandler(canvas);

      if (defined(options.sceneMode)) {
        if (options.sceneMode === SceneMode$1.SCENE2D) {
          this._scene.morphTo2D(0);
        }
        if (options.sceneMode === SceneMode$1.COLUMBUS_VIEW) {
          this._scene.morphToColumbusView(0);
        }
      }

      this._useDefaultRenderLoop = undefined;
      this.useDefaultRenderLoop = defaultValue(
        options.useDefaultRenderLoop,
        true
      );

      this._targetFrameRate = undefined;
      this.targetFrameRate = options.targetFrameRate;

      const that = this;
      this._onRenderError = function (scene, error) {
        that._useDefaultRenderLoop = false;
        that._renderLoopRunning = false;
        if (that._showRenderLoopErrors) {
          const title =
            "An error occurred while rendering.  Rendering has stopped.";
          that.showErrorPanel(title, undefined, error);
        }
      };
      scene.renderError.addEventListener(this._onRenderError);
    } catch (error) {
      if (showRenderLoopErrors) {
        const title = "Error constructing CesiumWidget.";
        const message =
          'Visit <a href="http://get.webgl.org">http://get.webgl.org</a> to verify that your web browser and hardware support WebGL.  Consider trying a different web browser or updating your video drivers.  Detailed error information is below:';
        this.showErrorPanel(title, message, error);
      }
      throw error;
    }
  }

  Object.defineProperties(CesiumWidget.prototype, {
    /**
     * Gets the parent container.
     * @memberof CesiumWidget.prototype
     *
     * @type {Element}
     * @readonly
     */
    container: {
      get: function () {
        return this._container;
      },
    },

    /**
     * Gets the canvas.
     * @memberof CesiumWidget.prototype
     *
     * @type {HTMLCanvasElement}
     * @readonly
     */
    canvas: {
      get: function () {
        return this._canvas;
      },
    },

    /**
     * Gets the credit container.
     * @memberof CesiumWidget.prototype
     *
     * @type {Element}
     * @readonly
     */
    creditContainer: {
      get: function () {
        return this._creditContainer;
      },
    },

    /**
     * Gets the credit viewport
     * @memberof CesiumWidget.prototype
     *
     * @type {Element}
     * @readonly
     */
    creditViewport: {
      get: function () {
        return this._creditViewport;
      },
    },

    /**
     * Gets the scene.
     * @memberof CesiumWidget.prototype
     *
     * @type {Scene}
     * @readonly
     */
    scene: {
      get: function () {
        return this._scene;
      },
    },

    /**
     * Gets the collection of image layers that will be rendered on the globe.
     * @memberof CesiumWidget.prototype
     *
     * @type {ImageryLayerCollection}
     * @readonly
     */
    imageryLayers: {
      get: function () {
        return this._scene.imageryLayers;
      },
    },

    /**
     * The terrain provider providing surface geometry for the globe.
     * @memberof CesiumWidget.prototype
     *
     * @type {TerrainProvider}
     */
    terrainProvider: {
      get: function () {
        return this._scene.terrainProvider;
      },
      set: function (terrainProvider) {
        this._scene.terrainProvider = terrainProvider;
      },
    },

    /**
     * Gets the camera.
     * @memberof CesiumWidget.prototype
     *
     * @type {Camera}
     * @readonly
     */
    camera: {
      get: function () {
        return this._scene.camera;
      },
    },

    /**
     * Gets the clock.
     * @memberof CesiumWidget.prototype
     *
     * @type {Clock}
     * @readonly
     */
    clock: {
      get: function () {
        return this._clock;
      },
    },

    /**
     * Gets the screen space event handler.
     * @memberof CesiumWidget.prototype
     *
     * @type {ScreenSpaceEventHandler}
     * @readonly
     */
    screenSpaceEventHandler: {
      get: function () {
        return this._screenSpaceEventHandler;
      },
    },

    /**
     * Gets or sets the target frame rate of the widget when <code>useDefaultRenderLoop</code>
     * is true. If undefined, the browser's {@link requestAnimationFrame} implementation
     * determines the frame rate.  If defined, this value must be greater than 0.  A value higher
     * than the underlying requestAnimationFrame implementation will have no effect.
     * @memberof CesiumWidget.prototype
     *
     * @type {Number}
     */
    targetFrameRate: {
      get: function () {
        return this._targetFrameRate;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (value <= 0) {
          throw new DeveloperError(
            "targetFrameRate must be greater than 0, or undefined."
          );
        }
        //>>includeEnd('debug');
        this._targetFrameRate = value;
      },
    },

    /**
     * Gets or sets whether or not this widget should control the render loop.
     * If set to true the widget will use {@link requestAnimationFrame} to
     * perform rendering and resizing of the widget, as well as drive the
     * simulation clock. If set to false, you must manually call the
     * <code>resize</code>, <code>render</code> methods as part of a custom
     * render loop.  If an error occurs during rendering, {@link Scene}'s
     * <code>renderError</code> event will be raised and this property
     * will be set to false.  It must be set back to true to continue rendering
     * after the error.
     * @memberof CesiumWidget.prototype
     *
     * @type {Boolean}
     */
    useDefaultRenderLoop: {
      get: function () {
        return this._useDefaultRenderLoop;
      },
      set: function (value) {
        if (this._useDefaultRenderLoop !== value) {
          this._useDefaultRenderLoop = value;
          if (value && !this._renderLoopRunning) {
            startRenderLoop(this);
          }
        }
      },
    },

    /**
     * Gets or sets a scaling factor for rendering resolution.  Values less than 1.0 can improve
     * performance on less powerful devices while values greater than 1.0 will render at a higher
     * resolution and then scale down, resulting in improved visual fidelity.
     * For example, if the widget is laid out at a size of 640x480, setting this value to 0.5
     * will cause the scene to be rendered at 320x240 and then scaled up while setting
     * it to 2.0 will cause the scene to be rendered at 1280x960 and then scaled down.
     * @memberof CesiumWidget.prototype
     *
     * @type {Number}
     * @default 1.0
     */
    resolutionScale: {
      get: function () {
        return this._resolutionScale;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (value <= 0) {
          throw new DeveloperError("resolutionScale must be greater than 0.");
        }
        //>>includeEnd('debug');
        if (this._resolutionScale !== value) {
          this._resolutionScale = value;
          this._forceResize = true;
        }
      },
    },

    /**
     * Boolean flag indicating if the browser's recommended resolution is used.
     * If true, the browser's device pixel ratio is ignored and 1.0 is used instead,
     * effectively rendering based on CSS pixels instead of device pixels. This can improve
     * performance on less powerful devices that have high pixel density. When false, rendering
     * will be in device pixels. {@link CesiumWidget#resolutionScale} will still take effect whether
     * this flag is true or false.
     * @memberof CesiumWidget.prototype
     *
     * @type {Boolean}
     * @default true
     */
    useBrowserRecommendedResolution: {
      get: function () {
        return this._useBrowserRecommendedResolution;
      },
      set: function (value) {
        if (this._useBrowserRecommendedResolution !== value) {
          this._useBrowserRecommendedResolution = value;
          this._forceResize = true;
        }
      },
    },
  });

  /**
   * Show an error panel to the user containing a title and a longer error message,
   * which can be dismissed using an OK button.  This panel is displayed automatically
   * when a render loop error occurs, if showRenderLoopErrors was not false when the
   * widget was constructed.
   *
   * @param {String} title The title to be displayed on the error panel.  This string is interpreted as text.
   * @param {String} [message] A helpful, user-facing message to display prior to the detailed error information.  This string is interpreted as HTML.
   * @param {String} [error] The error to be displayed on the error panel.  This string is formatted using {@link formatError} and then displayed as text.
   */
  CesiumWidget.prototype.showErrorPanel = function (title, message, error) {
    const element = this._element;
    const overlay = document.createElement("div");
    overlay.className = "cesium-widget-errorPanel";

    const content = document.createElement("div");
    content.className = "cesium-widget-errorPanel-content";
    overlay.appendChild(content);

    const errorHeader = document.createElement("div");
    errorHeader.className = "cesium-widget-errorPanel-header";
    errorHeader.appendChild(document.createTextNode(title));
    content.appendChild(errorHeader);

    const errorPanelScroller = document.createElement("div");
    errorPanelScroller.className = "cesium-widget-errorPanel-scroll";
    content.appendChild(errorPanelScroller);
    function resizeCallback() {
      errorPanelScroller.style.maxHeight = `${Math.max(
      Math.round(element.clientHeight * 0.9 - 100),
      30
    )}px`;
    }
    resizeCallback();
    if (defined(window.addEventListener)) {
      window.addEventListener("resize", resizeCallback, false);
    }

    const hasMessage = defined(message);
    const hasError = defined(error);

    if (hasMessage || hasError) {
      const errorMessage = document.createElement("div");
      errorMessage.className = "cesium-widget-errorPanel-message";
      errorPanelScroller.appendChild(errorMessage);

      if (hasError) {
        let errorDetails = formatError(error);
        if (!hasMessage) {
          if (typeof error === "string") {
            error = new Error(error);
          }

          message = formatError({
            name: error.name,
            message: error.message,
          });
          errorDetails = error.stack;
        }

        //IE8 does not have a console object unless the dev tools are open.
        if (typeof console !== "undefined") {
          console.error(`${title}\n${message}\n${errorDetails}`);
        }

        const errorMessageDetails = document.createElement("div");
        errorMessageDetails.className =
          "cesium-widget-errorPanel-message-details collapsed";

        const moreDetails = document.createElement("span");
        moreDetails.className = "cesium-widget-errorPanel-more-details";
        moreDetails.appendChild(document.createTextNode("See more..."));
        errorMessageDetails.appendChild(moreDetails);

        errorMessageDetails.onclick = function (e) {
          errorMessageDetails.removeChild(moreDetails);
          errorMessageDetails.appendChild(document.createTextNode(errorDetails));
          errorMessageDetails.className =
            "cesium-widget-errorPanel-message-details";
          content.className = "cesium-widget-errorPanel-content expanded";
          errorMessageDetails.onclick = undefined;
        };

        errorPanelScroller.appendChild(errorMessageDetails);
      }

      errorMessage.innerHTML = `<p>${message}</p>`;
    }

    const buttonPanel = document.createElement("div");
    buttonPanel.className = "cesium-widget-errorPanel-buttonPanel";
    content.appendChild(buttonPanel);

    const okButton = document.createElement("button");
    okButton.setAttribute("type", "button");
    okButton.className = "cesium-button";
    okButton.appendChild(document.createTextNode("OK"));
    okButton.onclick = function () {
      if (defined(resizeCallback) && defined(window.removeEventListener)) {
        window.removeEventListener("resize", resizeCallback, false);
      }
      element.removeChild(overlay);
    };

    buttonPanel.appendChild(okButton);

    element.appendChild(overlay);
  };

  /**
   * @returns {Boolean} true if the object has been destroyed, false otherwise.
   */
  CesiumWidget.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the widget.  Should be called if permanently
   * removing the widget from layout.
   */
  CesiumWidget.prototype.destroy = function () {
    if (defined(this._scene)) {
      this._scene.renderError.removeEventListener(this._onRenderError);
      this._scene = this._scene.destroy();
    }
    this._container.removeChild(this._element);
    this._creditContainer.removeChild(this._innerCreditContainer);
    destroyObject(this);
  };

  /**
   * Updates the canvas size, camera aspect ratio, and viewport size.
   * This function is called automatically as needed unless
   * <code>useDefaultRenderLoop</code> is set to false.
   */
  CesiumWidget.prototype.resize = function () {
    const canvas = this._canvas;
    if (
      !this._forceResize &&
      this._canvasClientWidth === canvas.clientWidth &&
      this._canvasClientHeight === canvas.clientHeight &&
      this._lastDevicePixelRatio === window.devicePixelRatio
    ) {
      return;
    }
    this._forceResize = false;

    configureCanvasSize(this);
    configureCameraFrustum(this);

    this._scene.requestRender();
  };

  /**
   * Renders the scene.  This function is called automatically
   * unless <code>useDefaultRenderLoop</code> is set to false;
   */
  CesiumWidget.prototype.render = function () {
    if (this._canRender) {
      this._scene.initializeFrame();
      const currentTime = this._clock.tick();
      this._scene.render(currentTime);
    } else {
      this._clock.tick();
    }
  };

  /**
   * The view model for {@link FullscreenButton}.
   * @alias FullscreenButtonViewModel
   * @constructor
   *
   * @param {Element|String} [fullscreenElement=document.body] The element or id to be placed into fullscreen mode.
   * @param {Element|String} [container] The DOM element or ID that will contain the widget.
   */
  function FullscreenButtonViewModel(fullscreenElement, container) {
    if (!defined(container)) {
      container = document.body;
    }

    container = getElement(container);

    const that = this;

    const tmpIsFullscreen = knockout.observable(Fullscreen.fullscreen);
    const tmpIsEnabled = knockout.observable(Fullscreen.enabled);
    const ownerDocument = container.ownerDocument;

    /**
     * Gets whether or not fullscreen mode is active.  This property is observable.
     *
     * @type {Boolean}
     */
    this.isFullscreen = undefined;
    knockout.defineProperty(this, "isFullscreen", {
      get: function () {
        return tmpIsFullscreen();
      },
    });

    /**
     * Gets or sets whether or not fullscreen functionality should be enabled.  This property is observable.
     *
     * @type {Boolean}
     * @see Fullscreen.enabled
     */
    this.isFullscreenEnabled = undefined;
    knockout.defineProperty(this, "isFullscreenEnabled", {
      get: function () {
        return tmpIsEnabled();
      },
      set: function (value) {
        tmpIsEnabled(value && Fullscreen.enabled);
      },
    });

    /**
     * Gets the tooltip.  This property is observable.
     *
     * @type {String}
     */
    this.tooltip = undefined;
    knockout.defineProperty(this, "tooltip", function () {
      if (!this.isFullscreenEnabled) {
        return "Full screen unavailable";
      }
      return tmpIsFullscreen() ? "Exit full screen" : "Full screen";
    });

    this._command = createCommand(function () {
      if (Fullscreen.fullscreen) {
        Fullscreen.exitFullscreen();
      } else {
        Fullscreen.requestFullscreen(that._fullscreenElement);
      }
    }, knockout.getObservable(this, "isFullscreenEnabled"));

    this._fullscreenElement = defaultValue(
      getElement(fullscreenElement),
      ownerDocument.body
    );

    this._callback = function () {
      tmpIsFullscreen(Fullscreen.fullscreen);
    };
    ownerDocument.addEventListener(Fullscreen.changeEventName, this._callback);
  }

  Object.defineProperties(FullscreenButtonViewModel.prototype, {
    /**
     * Gets or sets the HTML element to place into fullscreen mode when the
     * corresponding button is pressed.
     * @memberof FullscreenButtonViewModel.prototype
     *
     * @type {Element}
     */
    fullscreenElement: {
      //TODO:@exception {DeveloperError} value must be a valid HTML Element.
      get: function () {
        return this._fullscreenElement;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!(value instanceof Element)) {
          throw new DeveloperError("value must be a valid Element.");
        }
        //>>includeEnd('debug');

        this._fullscreenElement = value;
      },
    },

    /**
     * Gets the Command to toggle fullscreen mode.
     * @memberof FullscreenButtonViewModel.prototype
     *
     * @type {Command}
     */
    command: {
      get: function () {
        return this._command;
      },
    },
  });

  /**
   * @returns {Boolean} true if the object has been destroyed, false otherwise.
   */
  FullscreenButtonViewModel.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the view model.  Should be called to
   * properly clean up the view model when it is no longer needed.
   */
  FullscreenButtonViewModel.prototype.destroy = function () {
    document.removeEventListener(Fullscreen.changeEventName, this._callback);
    destroyObject(this);
  };

  const enterFullScreenPath =
    "M 83.96875 17.5625 L 83.96875 17.59375 L 76.65625 24.875 L 97.09375 24.96875 L 76.09375 45.96875 L 81.9375 51.8125 L 102.78125 30.9375 L 102.875 51.15625 L 110.15625 43.875 L 110.1875 17.59375 L 83.96875 17.5625 z M 44.125 17.59375 L 17.90625 17.625 L 17.9375 43.90625 L 25.21875 51.1875 L 25.3125 30.96875 L 46.15625 51.8125 L 52 45.96875 L 31 25 L 51.4375 24.90625 L 44.125 17.59375 z M 46.0625 76.03125 L 25.1875 96.875 L 25.09375 76.65625 L 17.8125 83.9375 L 17.8125 110.21875 L 44 110.25 L 51.3125 102.9375 L 30.90625 102.84375 L 51.875 81.875 L 46.0625 76.03125 z M 82 76.15625 L 76.15625 82 L 97.15625 103 L 76.71875 103.0625 L 84.03125 110.375 L 110.25 110.34375 L 110.21875 84.0625 L 102.9375 76.8125 L 102.84375 97 L 82 76.15625 z";
  const exitFullScreenPath =
    "M 104.34375 17.5625 L 83.5 38.4375 L 83.40625 18.21875 L 76.125 25.5 L 76.09375 51.78125 L 102.3125 51.8125 L 102.3125 51.78125 L 109.625 44.5 L 89.1875 44.40625 L 110.1875 23.40625 L 104.34375 17.5625 z M 23.75 17.59375 L 17.90625 23.4375 L 38.90625 44.4375 L 18.5 44.53125 L 25.78125 51.8125 L 52 51.78125 L 51.96875 25.53125 L 44.6875 18.25 L 44.625 38.46875 L 23.75 17.59375 z M 25.6875 76.03125 L 18.375 83.3125 L 38.78125 83.40625 L 17.8125 104.40625 L 23.625 110.25 L 44.5 89.375 L 44.59375 109.59375 L 51.875 102.3125 L 51.875 76.0625 L 25.6875 76.03125 z M 102.375 76.15625 L 76.15625 76.1875 L 76.1875 102.4375 L 83.46875 109.71875 L 83.5625 89.53125 L 104.40625 110.375 L 110.25 104.53125 L 89.25 83.53125 L 109.6875 83.46875 L 102.375 76.15625 z";

  /**
   * A single button widget for toggling fullscreen mode.
   *
   * @alias FullscreenButton
   * @constructor
   *
   * @param {Element|String} container The DOM element or ID that will contain the widget.
   * @param {Element|String} [fullscreenElement=document.body] The element or id to be placed into fullscreen mode.
   *
   * @exception {DeveloperError} Element with id "container" does not exist in the document.
   *
   * @see Fullscreen
   */
  function FullscreenButton(container, fullscreenElement) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(container)) {
      throw new DeveloperError("container is required.");
    }
    //>>includeEnd('debug');

    container = getElement(container);

    const viewModel = new FullscreenButtonViewModel(fullscreenElement, container);

    viewModel._exitFullScreenPath = exitFullScreenPath;
    viewModel._enterFullScreenPath = enterFullScreenPath;

    const element = document.createElement("button");
    element.type = "button";
    element.className = "cesium-button cesium-fullscreenButton";
    element.setAttribute(
      "data-bind",
      "\
attr: { title: tooltip },\
click: command,\
enable: isFullscreenEnabled,\
cesiumSvgPath: { path: isFullscreen ? _exitFullScreenPath : _enterFullScreenPath, width: 128, height: 128 }"
    );

    container.appendChild(element);

    knockout.applyBindings(viewModel, element);

    this._container = container;
    this._viewModel = viewModel;
    this._element = element;
  }

  Object.defineProperties(FullscreenButton.prototype, {
    /**
     * Gets the parent container.
     * @memberof FullscreenButton.prototype
     *
     * @type {Element}
     */
    container: {
      get: function () {
        return this._container;
      },
    },

    /**
     * Gets the view model.
     * @memberof FullscreenButton.prototype
     *
     * @type {FullscreenButtonViewModel}
     */
    viewModel: {
      get: function () {
        return this._viewModel;
      },
    },
  });

  /**
   * @returns {Boolean} true if the object has been destroyed, false otherwise.
   */
  FullscreenButton.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the widget.  Should be called if permanently
   * removing the widget from layout.
   */
  FullscreenButton.prototype.destroy = function () {
    this._viewModel.destroy();

    knockout.cleanNode(this._element);
    this._container.removeChild(this._element);

    return destroyObject(this);
  };

  // The height we use if geocoding to a specific point instead of an rectangle.
  const DEFAULT_HEIGHT = 1000;

  /**
   * The view model for the {@link Geocoder} widget.
   * @alias GeocoderViewModel
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Scene} options.scene The Scene instance to use.
   * @param {GeocoderService[]} [options.geocoderServices] Geocoder services to use for geocoding queries.
   *        If more than one are supplied, suggestions will be gathered for the geocoders that support it,
   *        and if no suggestion is selected the result from the first geocoder service wil be used.
   * @param {Number} [options.flightDuration] The duration of the camera flight to an entered location, in seconds.
   * @param {Geocoder.DestinationFoundFunction} [options.destinationFound=GeocoderViewModel.flyToDestination] A callback function that is called after a successful geocode.  If not supplied, the default behavior is to fly the camera to the result destination.
   */
  function GeocoderViewModel(options) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(options) || !defined(options.scene)) {
      throw new DeveloperError("options.scene is required.");
    }
    //>>includeEnd('debug');

    if (defined(options.geocoderServices)) {
      this._geocoderServices = options.geocoderServices;
    } else {
      this._geocoderServices = [
        new CartographicGeocoderService(),
        new IonGeocoderService({ scene: options.scene }),
      ];
    }

    this._viewContainer = options.container;
    this._scene = options.scene;
    this._flightDuration = options.flightDuration;
    this._searchText = "";
    this._isSearchInProgress = false;
    this._geocodePromise = undefined;
    this._complete = new Event();
    this._suggestions = [];
    this._selectedSuggestion = undefined;
    this._showSuggestions = true;

    this._handleArrowDown = handleArrowDown;
    this._handleArrowUp = handleArrowUp;

    const that = this;

    this._suggestionsVisible = knockout.pureComputed(function () {
      const suggestions = knockout.getObservable(that, "_suggestions");
      const suggestionsNotEmpty = suggestions().length > 0;
      const showSuggestions = knockout.getObservable(that, "_showSuggestions")();
      return suggestionsNotEmpty && showSuggestions;
    });

    this._searchCommand = createCommand(function (geocodeType) {
      geocodeType = defaultValue(geocodeType, GeocodeType$1.SEARCH);
      that._focusTextbox = false;
      if (defined(that._selectedSuggestion)) {
        that.activateSuggestion(that._selectedSuggestion);
        return false;
      }
      that.hideSuggestions();
      if (that.isSearchInProgress) {
        cancelGeocode(that);
      } else {
        geocode(that, that._geocoderServices, geocodeType);
      }
    });

    this.deselectSuggestion = function () {
      that._selectedSuggestion = undefined;
    };

    this.handleKeyDown = function (data, event) {
      const downKey =
        event.key === "ArrowDown" || event.key === "Down" || event.keyCode === 40;
      const upKey =
        event.key === "ArrowUp" || event.key === "Up" || event.keyCode === 38;
      if (downKey || upKey) {
        event.preventDefault();
      }

      return true;
    };

    this.handleKeyUp = function (data, event) {
      const downKey =
        event.key === "ArrowDown" || event.key === "Down" || event.keyCode === 40;
      const upKey =
        event.key === "ArrowUp" || event.key === "Up" || event.keyCode === 38;
      const enterKey = event.key === "Enter" || event.keyCode === 13;
      if (upKey) {
        handleArrowUp(that);
      } else if (downKey) {
        handleArrowDown(that);
      } else if (enterKey) {
        that._searchCommand();
      }
      return true;
    };

    this.activateSuggestion = function (data) {
      that.hideSuggestions();
      that._searchText = data.displayName;
      const destination = data.destination;
      clearSuggestions(that);
      that.destinationFound(that, destination);
    };

    this.hideSuggestions = function () {
      that._showSuggestions = false;
      that._selectedSuggestion = undefined;
    };

    this.showSuggestions = function () {
      that._showSuggestions = true;
    };

    this.handleMouseover = function (data, event) {
      if (data !== that._selectedSuggestion) {
        that._selectedSuggestion = data;
      }
    };

    /**
     * Gets or sets a value indicating if this instance should always show its text input field.
     *
     * @type {Boolean}
     * @default false
     */
    this.keepExpanded = false;

    /**
     * True if the geocoder should query as the user types to autocomplete
     * @type {Boolean}
     * @default true
     */
    this.autoComplete = defaultValue(options.autocomplete, true);

    /**
     * Gets and sets the command called when a geocode destination is found
     * @type {Geocoder.DestinationFoundFunction}
     */
    this.destinationFound = defaultValue(
      options.destinationFound,
      GeocoderViewModel.flyToDestination
    );

    this._focusTextbox = false;

    knockout.track(this, [
      "_searchText",
      "_isSearchInProgress",
      "keepExpanded",
      "_suggestions",
      "_selectedSuggestion",
      "_showSuggestions",
      "_focusTextbox",
    ]);

    const searchTextObservable = knockout.getObservable(this, "_searchText");
    searchTextObservable.extend({ rateLimit: { timeout: 500 } });
    this._suggestionSubscription = searchTextObservable.subscribe(function () {
      GeocoderViewModel._updateSearchSuggestions(that);
    });
    /**
     * Gets a value indicating whether a search is currently in progress.  This property is observable.
     *
     * @type {Boolean}
     */
    this.isSearchInProgress = undefined;
    knockout.defineProperty(this, "isSearchInProgress", {
      get: function () {
        return this._isSearchInProgress;
      },
    });

    /**
     * Gets or sets the text to search for.  The text can be an address, or longitude, latitude,
     * and optional height, where longitude and latitude are in degrees and height is in meters.
     *
     * @type {String}
     */
    this.searchText = undefined;
    knockout.defineProperty(this, "searchText", {
      get: function () {
        if (this.isSearchInProgress) {
          return "Searching...";
        }

        return this._searchText;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (typeof value !== "string") {
          throw new DeveloperError("value must be a valid string.");
        }
        //>>includeEnd('debug');
        this._searchText = value;
      },
    });

    /**
     * Gets or sets the the duration of the camera flight in seconds.
     * A value of zero causes the camera to instantly switch to the geocoding location.
     * The duration will be computed based on the distance when undefined.
     *
     * @type {Number|undefined}
     * @default undefined
     */
    this.flightDuration = undefined;
    knockout.defineProperty(this, "flightDuration", {
      get: function () {
        return this._flightDuration;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (defined(value) && value < 0) {
          throw new DeveloperError("value must be positive.");
        }
        //>>includeEnd('debug');

        this._flightDuration = value;
      },
    });
  }

  Object.defineProperties(GeocoderViewModel.prototype, {
    /**
     * Gets the event triggered on flight completion.
     * @memberof GeocoderViewModel.prototype
     *
     * @type {Event}
     */
    complete: {
      get: function () {
        return this._complete;
      },
    },

    /**
     * Gets the scene to control.
     * @memberof GeocoderViewModel.prototype
     *
     * @type {Scene}
     */
    scene: {
      get: function () {
        return this._scene;
      },
    },

    /**
     * Gets the Command that is executed when the button is clicked.
     * @memberof GeocoderViewModel.prototype
     *
     * @type {Command}
     */
    search: {
      get: function () {
        return this._searchCommand;
      },
    },

    /**
     * Gets the currently selected geocoder search suggestion
     * @memberof GeocoderViewModel.prototype
     *
     * @type {Object}
     */
    selectedSuggestion: {
      get: function () {
        return this._selectedSuggestion;
      },
    },

    /**
     * Gets the list of geocoder search suggestions
     * @memberof GeocoderViewModel.prototype
     *
     * @type {Object[]}
     */
    suggestions: {
      get: function () {
        return this._suggestions;
      },
    },
  });

  /**
   * Destroys the widget.  Should be called if permanently
   * removing the widget from layout.
   */
  GeocoderViewModel.prototype.destroy = function () {
    this._suggestionSubscription.dispose();
  };

  function handleArrowUp(viewModel) {
    if (viewModel._suggestions.length === 0) {
      return;
    }
    const currentIndex = viewModel._suggestions.indexOf(
      viewModel._selectedSuggestion
    );
    if (currentIndex === -1 || currentIndex === 0) {
      viewModel._selectedSuggestion = undefined;
      return;
    }
    const next = currentIndex - 1;
    viewModel._selectedSuggestion = viewModel._suggestions[next];
    GeocoderViewModel._adjustSuggestionsScroll(viewModel, next);
  }

  function handleArrowDown(viewModel) {
    if (viewModel._suggestions.length === 0) {
      return;
    }
    const numberOfSuggestions = viewModel._suggestions.length;
    const currentIndex = viewModel._suggestions.indexOf(
      viewModel._selectedSuggestion
    );
    const next = (currentIndex + 1) % numberOfSuggestions;
    viewModel._selectedSuggestion = viewModel._suggestions[next];

    GeocoderViewModel._adjustSuggestionsScroll(viewModel, next);
  }

  function computeFlyToLocationForCartographic(cartographic, terrainProvider) {
    const availability = defined(terrainProvider)
      ? terrainProvider.availability
      : undefined;

    if (!defined(availability)) {
      cartographic.height += DEFAULT_HEIGHT;
      return Promise.resolve(cartographic);
    }

    return sampleTerrainMostDetailed(terrainProvider, [cartographic]).then(
      function (positionOnTerrain) {
        cartographic = positionOnTerrain[0];
        cartographic.height += DEFAULT_HEIGHT;
        return cartographic;
      }
    );
  }

  function flyToDestination(viewModel, destination) {
    const scene = viewModel._scene;
    const mapProjection = scene.mapProjection;
    const ellipsoid = mapProjection.ellipsoid;

    const camera = scene.camera;
    const terrainProvider = scene.terrainProvider;
    let finalDestination = destination;

    let promise;
    if (destination instanceof Rectangle) {
      // Some geocoders return a Rectangle of zero width/height, treat it like a point instead.
      if (
        CesiumMath.equalsEpsilon(
          destination.south,
          destination.north,
          CesiumMath.EPSILON7
        ) &&
        CesiumMath.equalsEpsilon(
          destination.east,
          destination.west,
          CesiumMath.EPSILON7
        )
      ) {
        // destination is now a Cartographic
        destination = Rectangle.center(destination);
      } else {
        promise = computeFlyToLocationForRectangle(destination, scene);
      }
    } else {
      // destination is a Cartesian3
      destination = ellipsoid.cartesianToCartographic(destination);
    }

    if (!defined(promise)) {
      promise = computeFlyToLocationForCartographic(destination, terrainProvider);
    }

    return promise
      .then(function (result) {
        finalDestination = ellipsoid.cartographicToCartesian(result);
      })
      .finally(function () {
        // Whether terrain querying succeeded or not, fly to the destination.
        camera.flyTo({
          destination: finalDestination,
          complete: function () {
            viewModel._complete.raiseEvent();
          },
          duration: viewModel._flightDuration,
          endTransform: Matrix4.IDENTITY,
        });
      });
  }

  function chainPromise(promise, geocoderService, query, geocodeType) {
    return promise.then(function (result) {
      if (
        defined(result) &&
        result.state === "fulfilled" &&
        result.value.length > 0
      ) {
        return result;
      }
      const nextPromise = geocoderService
        .geocode(query, geocodeType)
        .then(function (result) {
          return { state: "fulfilled", value: result };
        })
        .catch(function (err) {
          return { state: "rejected", reason: err };
        });

      return nextPromise;
    });
  }

  function geocode(viewModel, geocoderServices, geocodeType) {
    const query = viewModel._searchText;

    if (hasOnlyWhitespace(query)) {
      viewModel.showSuggestions();
      return;
    }

    viewModel._isSearchInProgress = true;

    let promise = Promise.resolve();
    for (let i = 0; i < geocoderServices.length; i++) {
      promise = chainPromise(promise, geocoderServices[i], query, geocodeType);
    }

    viewModel._geocodePromise = promise;
    promise.then(function (result) {
      if (promise.cancel) {
        return;
      }
      viewModel._isSearchInProgress = false;

      const geocoderResults = result.value;
      if (
        result.state === "fulfilled" &&
        defined(geocoderResults) &&
        geocoderResults.length > 0
      ) {
        viewModel._searchText = geocoderResults[0].displayName;
        viewModel.destinationFound(viewModel, geocoderResults[0].destination);
        return;
      }
      viewModel._searchText = `${query} (not found)`;
    });
  }

  function adjustSuggestionsScroll(viewModel, focusedItemIndex) {
    const container = getElement(viewModel._viewContainer);
    const searchResults = container.getElementsByClassName("search-results")[0];
    const listItems = container.getElementsByTagName("li");
    const element = listItems[focusedItemIndex];

    if (focusedItemIndex === 0) {
      searchResults.scrollTop = 0;
      return;
    }

    const offsetTop = element.offsetTop;
    if (offsetTop + element.clientHeight > searchResults.clientHeight) {
      searchResults.scrollTop = offsetTop + element.clientHeight;
    } else if (offsetTop < searchResults.scrollTop) {
      searchResults.scrollTop = offsetTop;
    }
  }

  function cancelGeocode(viewModel) {
    viewModel._isSearchInProgress = false;
    if (defined(viewModel._geocodePromise)) {
      viewModel._geocodePromise.cancel = true;
      viewModel._geocodePromise = undefined;
    }
  }

  function hasOnlyWhitespace(string) {
    return /^\s*$/.test(string);
  }

  function clearSuggestions(viewModel) {
    knockout.getObservable(viewModel, "_suggestions").removeAll();
  }

  function updateSearchSuggestions(viewModel) {
    if (!viewModel.autoComplete) {
      return;
    }

    const query = viewModel._searchText;

    clearSuggestions(viewModel);
    if (hasOnlyWhitespace(query)) {
      return;
    }

    let promise = Promise.resolve([]);
    viewModel._geocoderServices.forEach(function (service) {
      promise = promise.then(function (results) {
        if (results.length >= 5) {
          return results;
        }
        return service
          .geocode(query, GeocodeType$1.AUTOCOMPLETE)
          .then(function (newResults) {
            results = results.concat(newResults);
            return results;
          });
      });
    });
    return promise.then(function (results) {
      const suggestions = viewModel._suggestions;
      for (let i = 0; i < results.length; i++) {
        suggestions.push(results[i]);
      }
    });
  }

  /**
   * A function to fly to the destination found by a successful geocode.
   * @type {Geocoder.DestinationFoundFunction}
   */
  GeocoderViewModel.flyToDestination = flyToDestination;

  //exposed for testing
  GeocoderViewModel._updateSearchSuggestions = updateSearchSuggestions;
  GeocoderViewModel._adjustSuggestionsScroll = adjustSuggestionsScroll;

  const startSearchPath =
    "M29.772,26.433l-7.126-7.126c0.96-1.583,1.523-3.435,1.524-5.421C24.169,8.093,19.478,3.401,13.688,3.399C7.897,3.401,3.204,8.093,3.204,13.885c0,5.789,4.693,10.481,10.484,10.481c1.987,0,3.839-0.563,5.422-1.523l7.128,7.127L29.772,26.433zM7.203,13.885c0.006-3.582,2.903-6.478,6.484-6.486c3.579,0.008,6.478,2.904,6.484,6.486c-0.007,3.58-2.905,6.476-6.484,6.484C10.106,20.361,7.209,17.465,7.203,13.885z";
  const stopSearchPath =
    "M24.778,21.419 19.276,15.917 24.777,10.415 21.949,7.585 16.447,13.087 10.945,7.585 8.117,10.415 13.618,15.917 8.116,21.419 10.946,24.248 16.447,18.746 21.948,24.248z";

  /**
   * A widget for finding addresses and landmarks, and flying the camera to them.  Geocoding is
   * performed using {@link https://cesium.com/cesium-ion/|Cesium ion}.
   *
   * @alias Geocoder
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Element|String} options.container The DOM element or ID that will contain the widget.
   * @param {Scene} options.scene The Scene instance to use.
   * @param {GeocoderService[]} [options.geocoderServices] The geocoder services to be used
   * @param {Boolean} [options.autoComplete = true] True if the geocoder should query as the user types to autocomplete
   * @param {Number} [options.flightDuration=1.5] The duration of the camera flight to an entered location, in seconds.
   * @param {Geocoder.DestinationFoundFunction} [options.destinationFound=GeocoderViewModel.flyToDestination] A callback function that is called after a successful geocode.  If not supplied, the default behavior is to fly the camera to the result destination.
   */
  function Geocoder(options) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(options) || !defined(options.container)) {
      throw new DeveloperError("options.container is required.");
    }
    if (!defined(options.scene)) {
      throw new DeveloperError("options.scene is required.");
    }
    //>>includeEnd('debug');

    const container = getElement(options.container);
    const viewModel = new GeocoderViewModel(options);

    viewModel._startSearchPath = startSearchPath;
    viewModel._stopSearchPath = stopSearchPath;

    const form = document.createElement("form");
    form.setAttribute("data-bind", "submit: search");

    const textBox = document.createElement("input");
    textBox.type = "search";
    textBox.className = "cesium-geocoder-input";
    textBox.setAttribute("placeholder", "Enter an address or landmark...");
    textBox.setAttribute(
      "data-bind",
      '\
textInput: searchText,\
disable: isSearchInProgress,\
event: { keyup: handleKeyUp, keydown: handleKeyDown, mouseover: deselectSuggestion },\
css: { "cesium-geocoder-input-wide" : keepExpanded || searchText.length > 0 },\
hasFocus: _focusTextbox'
    );

    this._onTextBoxFocus = function () {
      // as of 2016-10-19, setTimeout is required to ensure that the
      // text is focused on Safari 10
      setTimeout(function () {
        textBox.select();
      }, 0);
    };

    textBox.addEventListener("focus", this._onTextBoxFocus, false);
    form.appendChild(textBox);
    this._textBox = textBox;

    const searchButton = document.createElement("span");
    searchButton.className = "cesium-geocoder-searchButton";
    searchButton.setAttribute(
      "data-bind",
      "\
click: search,\
cesiumSvgPath: { path: isSearchInProgress ? _stopSearchPath : _startSearchPath, width: 32, height: 32 }"
    );
    form.appendChild(searchButton);

    container.appendChild(form);

    const searchSuggestionsContainer = document.createElement("div");
    searchSuggestionsContainer.className = "search-results";
    searchSuggestionsContainer.setAttribute(
      "data-bind",
      "visible: _suggestionsVisible"
    );

    const suggestionsList = document.createElement("ul");
    suggestionsList.setAttribute("data-bind", "foreach: _suggestions");
    const suggestions = document.createElement("li");
    suggestionsList.appendChild(suggestions);
    suggestions.setAttribute(
      "data-bind",
      "text: $data.displayName, \
click: $parent.activateSuggestion, \
event: { mouseover: $parent.handleMouseover}, \
css: { active: $data === $parent._selectedSuggestion }"
    );

    searchSuggestionsContainer.appendChild(suggestionsList);
    container.appendChild(searchSuggestionsContainer);

    knockout.applyBindings(viewModel, form);
    knockout.applyBindings(viewModel, searchSuggestionsContainer);

    this._container = container;
    this._searchSuggestionsContainer = searchSuggestionsContainer;
    this._viewModel = viewModel;
    this._form = form;

    this._onInputBegin = function (e) {
      // e.target will not be correct if we are inside of the Shadow DOM
      // and contains will always fail. To retrieve the correct target,
      // we need to access the first element of the composedPath.
      // This allows us to use shadow DOM if it exists and fall
      // back to legacy behavior if its not being used.

      let target = e.target;
      if (typeof e.composedPath === "function") {
        target = e.composedPath()[0];
      }

      if (!container.contains(target)) {
        viewModel._focusTextbox = false;
        viewModel.hideSuggestions();
      }
    };

    this._onInputEnd = function (e) {
      viewModel._focusTextbox = true;
      viewModel.showSuggestions();
    };

    //We subscribe to both begin and end events in order to give the text box
    //focus no matter where on the widget is clicked.

    if (FeatureDetection.supportsPointerEvents()) {
      document.addEventListener("pointerdown", this._onInputBegin, true);
      container.addEventListener("pointerup", this._onInputEnd, true);
      container.addEventListener("pointercancel", this._onInputEnd, true);
    } else {
      document.addEventListener("mousedown", this._onInputBegin, true);
      container.addEventListener("mouseup", this._onInputEnd, true);
      document.addEventListener("touchstart", this._onInputBegin, true);
      container.addEventListener("touchend", this._onInputEnd, true);
      container.addEventListener("touchcancel", this._onInputEnd, true);
    }
  }

  Object.defineProperties(Geocoder.prototype, {
    /**
     * Gets the parent container.
     * @memberof Geocoder.prototype
     *
     * @type {Element}
     */
    container: {
      get: function () {
        return this._container;
      },
    },

    /**
     * Gets the parent container.
     * @memberof Geocoder.prototype
     *
     * @type {Element}
     */
    searchSuggestionsContainer: {
      get: function () {
        return this._searchSuggestionsContainer;
      },
    },

    /**
     * Gets the view model.
     * @memberof Geocoder.prototype
     *
     * @type {GeocoderViewModel}
     */
    viewModel: {
      get: function () {
        return this._viewModel;
      },
    },
  });

  /**
   * @returns {Boolean} true if the object has been destroyed, false otherwise.
   */
  Geocoder.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the widget.  Should be called if permanently
   * removing the widget from layout.
   */
  Geocoder.prototype.destroy = function () {
    const container = this._container;
    if (FeatureDetection.supportsPointerEvents()) {
      document.removeEventListener("pointerdown", this._onInputBegin, true);
      container.removeEventListener("pointerup", this._onInputEnd, true);
    } else {
      document.removeEventListener("mousedown", this._onInputBegin, true);
      container.removeEventListener("mouseup", this._onInputEnd, true);
      document.removeEventListener("touchstart", this._onInputBegin, true);
      container.removeEventListener("touchend", this._onInputEnd, true);
    }
    this._viewModel.destroy();
    knockout.cleanNode(this._form);
    knockout.cleanNode(this._searchSuggestionsContainer);
    container.removeChild(this._form);
    container.removeChild(this._searchSuggestionsContainer);
    this._textBox.removeEventListener("focus", this._onTextBoxFocus, false);

    return destroyObject(this);
  };

  /**
   * The view model for {@link HomeButton}.
   * @alias HomeButtonViewModel
   * @constructor
   *
   * @param {Scene} scene The scene instance to use.
   * @param {Number} [duration] The duration of the camera flight in seconds.
   */
  function HomeButtonViewModel(scene, duration) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(scene)) {
      throw new DeveloperError("scene is required.");
    }
    //>>includeEnd('debug');

    this._scene = scene;
    this._duration = duration;

    const that = this;
    this._command = createCommand(function () {
      that._scene.camera.flyHome(that._duration);
    });

    /**
     * Gets or sets the tooltip.  This property is observable.
     *
     * @type {String}
     */
    this.tooltip = "View Home";

    knockout.track(this, ["tooltip"]);
  }

  Object.defineProperties(HomeButtonViewModel.prototype, {
    /**
     * Gets the scene to control.
     * @memberof HomeButtonViewModel.prototype
     *
     * @type {Scene}
     */
    scene: {
      get: function () {
        return this._scene;
      },
    },

    /**
     * Gets the Command that is executed when the button is clicked.
     * @memberof HomeButtonViewModel.prototype
     *
     * @type {Command}
     */
    command: {
      get: function () {
        return this._command;
      },
    },

    /**
     * Gets or sets the the duration of the camera flight in seconds.
     * A value of zero causes the camera to instantly switch to home view.
     * The duration will be computed based on the distance when undefined.
     * @memberof HomeButtonViewModel.prototype
     *
     * @type {Number|undefined}
     */
    duration: {
      get: function () {
        return this._duration;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (defined(value) && value < 0) {
          throw new DeveloperError("value must be positive.");
        }
        //>>includeEnd('debug');

        this._duration = value;
      },
    },
  });

  /**
   * A single button widget for returning to the default camera view of the current scene.
   *
   * @alias HomeButton
   * @constructor
   *
   * @param {Element|String} container The DOM element or ID that will contain the widget.
   * @param {Scene} scene The Scene instance to use.
   * @param {Number} [duration] The time, in seconds, it takes to complete the camera flight home.
   */
  function HomeButton(container, scene, duration) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(container)) {
      throw new DeveloperError("container is required.");
    }
    //>>includeEnd('debug');

    container = getElement(container);

    const viewModel = new HomeButtonViewModel(scene, duration);

    viewModel._svgPath =
      "M14,4l-10,8.75h20l-4.25-3.7188v-4.6562h-2.812v2.1875l-2.938-2.5625zm-7.0938,9.906v10.094h14.094v-10.094h-14.094zm2.1876,2.313h3.3122v4.25h-3.3122v-4.25zm5.8442,1.281h3.406v6.438h-3.406v-6.438z";

    const element = document.createElement("button");
    element.type = "button";
    element.className = "cesium-button cesium-toolbar-button cesium-home-button";
    element.setAttribute(
      "data-bind",
      "\
attr: { title: tooltip },\
click: command,\
cesiumSvgPath: { path: _svgPath, width: 28, height: 28 }"
    );

    container.appendChild(element);

    knockout.applyBindings(viewModel, element);

    this._container = container;
    this._viewModel = viewModel;
    this._element = element;
  }

  Object.defineProperties(HomeButton.prototype, {
    /**
     * Gets the parent container.
     * @memberof HomeButton.prototype
     *
     * @type {Element}
     */
    container: {
      get: function () {
        return this._container;
      },
    },

    /**
     * Gets the view model.
     * @memberof HomeButton.prototype
     *
     * @type {HomeButtonViewModel}
     */
    viewModel: {
      get: function () {
        return this._viewModel;
      },
    },
  });

  /**
   * @returns {Boolean} true if the object has been destroyed, false otherwise.
   */
  HomeButton.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the widget.  Should be called if permanently
   * removing the widget from layout.
   */
  HomeButton.prototype.destroy = function () {
    knockout.cleanNode(this._element);
    this._container.removeChild(this._element);

    return destroyObject(this);
  };

  const cameraEnabledPath =
    "M 13.84375 7.03125 C 11.412798 7.03125 9.46875 8.975298 9.46875 11.40625 L 9.46875 11.59375 L 2.53125 7.21875 L 2.53125 24.0625 L 9.46875 19.6875 C 9.4853444 22.104033 11.423165 24.0625 13.84375 24.0625 L 25.875 24.0625 C 28.305952 24.0625 30.28125 22.087202 30.28125 19.65625 L 30.28125 11.40625 C 30.28125 8.975298 28.305952 7.03125 25.875 7.03125 L 13.84375 7.03125 z";
  const cameraDisabledPath =
    "M 27.34375 1.65625 L 5.28125 27.9375 L 8.09375 30.3125 L 30.15625 4.03125 L 27.34375 1.65625 z M 13.84375 7.03125 C 11.412798 7.03125 9.46875 8.975298 9.46875 11.40625 L 9.46875 11.59375 L 2.53125 7.21875 L 2.53125 24.0625 L 9.46875 19.6875 C 9.4724893 20.232036 9.5676108 20.7379 9.75 21.21875 L 21.65625 7.03125 L 13.84375 7.03125 z M 28.21875 7.71875 L 14.53125 24.0625 L 25.875 24.0625 C 28.305952 24.0625 30.28125 22.087202 30.28125 19.65625 L 30.28125 11.40625 C 30.28125 9.8371439 29.456025 8.4902779 28.21875 7.71875 z";

  /**
   * The view model for {@link InfoBox}.
   * @alias InfoBoxViewModel
   * @constructor
   */
  function InfoBoxViewModel() {
    this._cameraClicked = new Event();
    this._closeClicked = new Event();

    /**
     * Gets or sets the maximum height of the info box in pixels.  This property is observable.
     * @type {Number}
     */
    this.maxHeight = 500;

    /**
     * Gets or sets whether the camera tracking icon is enabled.
     * @type {Boolean}
     */
    this.enableCamera = false;

    /**
     * Gets or sets the status of current camera tracking of the selected object.
     * @type {Boolean}
     */
    this.isCameraTracking = false;

    /**
     * Gets or sets the visibility of the info box.
     * @type {Boolean}
     */
    this.showInfo = false;

    /**
     * Gets or sets the title text in the info box.
     * @type {String}
     */
    this.titleText = "";

    /**
     * Gets or sets the description HTML for the info box.
     * @type {String}
     */
    this.description = "";

    knockout.track(this, [
      "showInfo",
      "titleText",
      "description",
      "maxHeight",
      "enableCamera",
      "isCameraTracking",
    ]);

    this._loadingIndicatorHtml =
      '<div class="cesium-infoBox-loadingContainer"><span class="cesium-infoBox-loading"></span></div>';

    /**
     * Gets the SVG path of the camera icon, which can change to be "crossed out" or not.
     * @type {String}
     */
    this.cameraIconPath = undefined;
    knockout.defineProperty(this, "cameraIconPath", {
      get: function () {
        return !this.enableCamera || this.isCameraTracking
          ? cameraDisabledPath
          : cameraEnabledPath;
      },
    });

    knockout.defineProperty(this, "_bodyless", {
      get: function () {
        return !defined(this.description) || this.description.length === 0;
      },
    });
  }

  /**
   * Gets the maximum height of sections within the info box, minus an offset, in CSS-ready form.
   * @param {Number} offset The offset in pixels.
   * @returns {String}
   */
  InfoBoxViewModel.prototype.maxHeightOffset = function (offset) {
    return `${this.maxHeight - offset}px`;
  };

  Object.defineProperties(InfoBoxViewModel.prototype, {
    /**
     * Gets an {@link Event} that is fired when the user clicks the camera icon.
     * @memberof InfoBoxViewModel.prototype
     * @type {Event}
     */
    cameraClicked: {
      get: function () {
        return this._cameraClicked;
      },
    },
    /**
     * Gets an {@link Event} that is fired when the user closes the info box.
     * @memberof InfoBoxViewModel.prototype
     * @type {Event}
     */
    closeClicked: {
      get: function () {
        return this._closeClicked;
      },
    },
  });

  /**
   * A widget for displaying information or a description.
   *
   * @alias InfoBox
   * @constructor
   *
   * @param {Element|String} container The DOM element or ID that will contain the widget.
   *
   * @exception {DeveloperError} Element with id "container" does not exist in the document.
   */
  function InfoBox(container) {
    //>>includeStart('debug', pragmas.debug);
    Check.defined("container", container);
    //>>includeEnd('debug')

    container = getElement(container);

    const infoElement = document.createElement("div");
    infoElement.className = "cesium-infoBox";
    infoElement.setAttribute(
      "data-bind",
      '\
css: { "cesium-infoBox-visible" : showInfo, "cesium-infoBox-bodyless" : _bodyless }'
    );
    container.appendChild(infoElement);

    const titleElement = document.createElement("div");
    titleElement.className = "cesium-infoBox-title";
    titleElement.setAttribute("data-bind", "text: titleText");
    infoElement.appendChild(titleElement);

    const cameraElement = document.createElement("button");
    cameraElement.type = "button";
    cameraElement.className = "cesium-button cesium-infoBox-camera";
    cameraElement.setAttribute(
      "data-bind",
      '\
attr: { title: "Focus camera on object" },\
click: function () { cameraClicked.raiseEvent(this); },\
enable: enableCamera,\
cesiumSvgPath: { path: cameraIconPath, width: 32, height: 32 }'
    );
    infoElement.appendChild(cameraElement);

    const closeElement = document.createElement("button");
    closeElement.type = "button";
    closeElement.className = "cesium-infoBox-close";
    closeElement.setAttribute(
      "data-bind",
      "\
click: function () { closeClicked.raiseEvent(this); }"
    );
    closeElement.innerHTML = "&times;";
    infoElement.appendChild(closeElement);

    const frame = document.createElement("iframe");
    frame.className = "cesium-infoBox-iframe";
    frame.setAttribute("sandbox", "allow-same-origin allow-popups allow-forms"); //allow-pointer-lock allow-scripts allow-top-navigation
    frame.setAttribute(
      "data-bind",
      "style : { maxHeight : maxHeightOffset(40) }"
    );
    frame.setAttribute("allowfullscreen", true);
    infoElement.appendChild(frame);

    const viewModel = new InfoBoxViewModel();
    knockout.applyBindings(viewModel, infoElement);

    this._container = container;
    this._element = infoElement;
    this._frame = frame;
    this._viewModel = viewModel;
    this._descriptionSubscription = undefined;

    const that = this;
    //We can't actually add anything into the frame until the load event is fired
    frame.addEventListener("load", function () {
      const frameDocument = frame.contentDocument;

      //We inject default css into the content iframe,
      //end users can remove it or add their own via the exposed frame property.
      const cssLink = frameDocument.createElement("link");
      cssLink.href = buildModuleUrl("Widgets/InfoBox/InfoBoxDescription.css");
      cssLink.rel = "stylesheet";
      cssLink.type = "text/css";

      //div to use for description content.
      const frameContent = frameDocument.createElement("div");
      frameContent.className = "cesium-infoBox-description";

      frameDocument.head.appendChild(cssLink);
      frameDocument.body.appendChild(frameContent);

      //We manually subscribe to the description event rather than through a binding for two reasons.
      //1. It's an easy way to ensure order of operation so that we can adjust the height.
      //2. Knockout does not bind to elements inside of an iFrame, so we would have to apply a second binding
      //   model anyway.
      that._descriptionSubscription = subscribeAndEvaluate(
        viewModel,
        "description",
        function (value) {
          // Set the frame to small height, force vertical scroll bar to appear, and text to wrap accordingly.
          frame.style.height = "5px";
          frameContent.innerHTML = value;

          //If the snippet is a single element, then use its background
          //color for the body of the InfoBox. This makes the padding match
          //the content and produces much nicer results.
          let background = null;
          const firstElementChild = frameContent.firstElementChild;
          if (
            firstElementChild !== null &&
            frameContent.childNodes.length === 1
          ) {
            const style = window.getComputedStyle(firstElementChild);
            if (style !== null) {
              const backgroundColor = style["background-color"];
              const color = Color.fromCssColorString(backgroundColor);
              if (defined(color) && color.alpha !== 0) {
                background = style["background-color"];
              }
            }
          }
          infoElement.style["background-color"] = background;

          // Measure and set the new custom height, based on text wrapped above.
          const height = frameContent.getBoundingClientRect().height;
          frame.style.height = `${height}px`;
        }
      );
    });

    //Chrome does not send the load event unless we explicitly set a src
    frame.setAttribute("src", "about:blank");
  }

  Object.defineProperties(InfoBox.prototype, {
    /**
     * Gets the parent container.
     * @memberof InfoBox.prototype
     *
     * @type {Element}
     */
    container: {
      get: function () {
        return this._container;
      },
    },

    /**
     * Gets the view model.
     * @memberof InfoBox.prototype
     *
     * @type {InfoBoxViewModel}
     */
    viewModel: {
      get: function () {
        return this._viewModel;
      },
    },

    /**
     * Gets the iframe used to display the description.
     * @memberof InfoBox.prototype
     *
     * @type {HTMLIFrameElement}
     */
    frame: {
      get: function () {
        return this._frame;
      },
    },
  });

  /**
   * @returns {Boolean} true if the object has been destroyed, false otherwise.
   */
  InfoBox.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the widget.  Should be called if permanently
   * removing the widget from layout.
   */
  InfoBox.prototype.destroy = function () {
    const container = this._container;
    knockout.cleanNode(this._element);
    container.removeChild(this._element);

    if (defined(this._descriptionSubscription)) {
      this._descriptionSubscription.dispose();
    }

    return destroyObject(this);
  };

  /**
   * The view model for {@link NavigationHelpButton}.
   * @alias NavigationHelpButtonViewModel
   * @constructor
   */
  function NavigationHelpButtonViewModel() {
    /**
     * Gets or sets whether the instructions are currently shown.  This property is observable.
     * @type {Boolean}
     * @default false
     */
    this.showInstructions = false;

    const that = this;
    this._command = createCommand(function () {
      that.showInstructions = !that.showInstructions;
    });
    this._showClick = createCommand(function () {
      that._touch = false;
    });
    this._showTouch = createCommand(function () {
      that._touch = true;
    });

    this._touch = false;

    /**
     * Gets or sets the tooltip.  This property is observable.
     *
     * @type {String}
     */
    this.tooltip = "Navigation Instructions";

    knockout.track(this, ["tooltip", "showInstructions", "_touch"]);
  }

  Object.defineProperties(NavigationHelpButtonViewModel.prototype, {
    /**
     * Gets the Command that is executed when the button is clicked.
     * @memberof NavigationHelpButtonViewModel.prototype
     *
     * @type {Command}
     */
    command: {
      get: function () {
        return this._command;
      },
    },

    /**
     * Gets the Command that is executed when the mouse instructions should be shown.
     * @memberof NavigationHelpButtonViewModel.prototype
     *
     * @type {Command}
     */
    showClick: {
      get: function () {
        return this._showClick;
      },
    },

    /**
     * Gets the Command that is executed when the touch instructions should be shown.
     * @memberof NavigationHelpButtonViewModel.prototype
     *
     * @type {Command}
     */
    showTouch: {
      get: function () {
        return this._showTouch;
      },
    },
  });

  /**
   * <p>The NavigationHelpButton is a single button widget for displaying instructions for
   * navigating the globe with the mouse.</p><p style="clear: both;"></p><br/>
   *
   * @alias NavigationHelpButton
   * @constructor
   *
   * @param {Object} options Object with the following properties:
   * @param {Element|String} options.container The DOM element or ID that will contain the widget.
   * @param {Boolean} [options.instructionsInitiallyVisible=false] True if the navigation instructions should initially be visible; otherwise, false.
   *
   * @exception {DeveloperError} Element with id "container" does not exist in the document.
   *
   * @example
   * // In HTML head, include a link to the NavigationHelpButton.css stylesheet,
   * // and in the body, include: <div id="navigationHelpButtonContainer"></div>
   *
   * const navigationHelpButton = new Cesium.NavigationHelpButton({
   *     container : 'navigationHelpButtonContainer'
   * });
   */
  function NavigationHelpButton(options) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(options) || !defined(options.container)) {
      throw new DeveloperError("options.container is required.");
    }
    //>>includeEnd('debug');

    const container = getElement(options.container);

    const viewModel = new NavigationHelpButtonViewModel();

    const showInsructionsDefault = defaultValue(
      options.instructionsInitiallyVisible,
      false
    );
    viewModel.showInstructions = showInsructionsDefault;

    viewModel._svgPath =
      "M16,1.466C7.973,1.466,1.466,7.973,1.466,16c0,8.027,6.507,14.534,14.534,14.534c8.027,0,14.534-6.507,14.534-14.534C30.534,7.973,24.027,1.466,16,1.466z M17.328,24.371h-2.707v-2.596h2.707V24.371zM17.328,19.003v0.858h-2.707v-1.057c0-3.19,3.63-3.696,3.63-5.963c0-1.034-0.924-1.826-2.134-1.826c-1.254,0-2.354,0.924-2.354,0.924l-1.541-1.915c0,0,1.519-1.584,4.137-1.584c2.487,0,4.796,1.54,4.796,4.136C21.156,16.208,17.328,16.627,17.328,19.003z";

    const wrapper = document.createElement("span");
    wrapper.className = "cesium-navigationHelpButton-wrapper";
    container.appendChild(wrapper);

    const button = document.createElement("button");
    button.type = "button";
    button.className =
      "cesium-button cesium-toolbar-button cesium-navigation-help-button";
    button.setAttribute(
      "data-bind",
      "\
attr: { title: tooltip },\
click: command,\
cesiumSvgPath: { path: _svgPath, width: 32, height: 32 }"
    );
    wrapper.appendChild(button);

    const instructionContainer = document.createElement("div");
    instructionContainer.className = "cesium-navigation-help";
    instructionContainer.setAttribute(
      "data-bind",
      'css: { "cesium-navigation-help-visible" : showInstructions}'
    );
    wrapper.appendChild(instructionContainer);

    const mouseButton = document.createElement("button");
    mouseButton.type = "button";
    mouseButton.className =
      "cesium-navigation-button cesium-navigation-button-left";
    mouseButton.setAttribute(
      "data-bind",
      'click: showClick, css: {"cesium-navigation-button-selected": !_touch, "cesium-navigation-button-unselected": _touch}'
    );
    const mouseIcon = document.createElement("img");
    mouseIcon.src = buildModuleUrl("Widgets/Images/NavigationHelp/Mouse.svg");
    mouseIcon.className = "cesium-navigation-button-icon";
    mouseIcon.style.width = "25px";
    mouseIcon.style.height = "25px";
    mouseButton.appendChild(mouseIcon);
    mouseButton.appendChild(document.createTextNode("Mouse"));

    const touchButton = document.createElement("button");
    touchButton.type = "button";
    touchButton.className =
      "cesium-navigation-button cesium-navigation-button-right";
    touchButton.setAttribute(
      "data-bind",
      'click: showTouch, css: {"cesium-navigation-button-selected": _touch, "cesium-navigation-button-unselected": !_touch}'
    );
    const touchIcon = document.createElement("img");
    touchIcon.src = buildModuleUrl("Widgets/Images/NavigationHelp/Touch.svg");
    touchIcon.className = "cesium-navigation-button-icon";
    touchIcon.style.width = "25px";
    touchIcon.style.height = "25px";
    touchButton.appendChild(touchIcon);
    touchButton.appendChild(document.createTextNode("Touch"));

    instructionContainer.appendChild(mouseButton);
    instructionContainer.appendChild(touchButton);

    const clickInstructions = document.createElement("div");
    clickInstructions.className =
      "cesium-click-navigation-help cesium-navigation-help-instructions";
    clickInstructions.setAttribute(
      "data-bind",
      'css: { "cesium-click-navigation-help-visible" : !_touch}'
    );
    clickInstructions.innerHTML = `\
            <table>\
                <tr>\
                    <td><img src="${buildModuleUrl(
                      "Widgets/Images/NavigationHelp/MouseLeft.svg"
                    )}" width="48" height="48" /></td>\
                    <td>\
                        <div class="cesium-navigation-help-pan">Pan view</div>\
                        <div class="cesium-navigation-help-details">Left click + drag</div>\
                    </td>\
                </tr>\
                <tr>\
                    <td><img src="${buildModuleUrl(
                      "Widgets/Images/NavigationHelp/MouseRight.svg"
                    )}" width="48" height="48" /></td>\
                    <td>\
                        <div class="cesium-navigation-help-zoom">Zoom view</div>\
                        <div class="cesium-navigation-help-details">Right click + drag, or</div>\
                        <div class="cesium-navigation-help-details">Mouse wheel scroll</div>\
                    </td>\
                </tr>\
                <tr>\
                    <td><img src="${buildModuleUrl(
                      "Widgets/Images/NavigationHelp/MouseMiddle.svg"
                    )}" width="48" height="48" /></td>\
                    <td>\
                        <div class="cesium-navigation-help-rotate">Rotate view</div>\
                        <div class="cesium-navigation-help-details">Middle click + drag, or</div>\
                        <div class="cesium-navigation-help-details">CTRL + Left/Right click + drag</div>\
                    </td>\
                </tr>\
            </table>`;

    instructionContainer.appendChild(clickInstructions);

    const touchInstructions = document.createElement("div");
    touchInstructions.className =
      "cesium-touch-navigation-help cesium-navigation-help-instructions";
    touchInstructions.setAttribute(
      "data-bind",
      'css: { "cesium-touch-navigation-help-visible" : _touch}'
    );
    touchInstructions.innerHTML = `\
            <table>\
                <tr>\
                    <td><img src="${buildModuleUrl(
                      "Widgets/Images/NavigationHelp/TouchDrag.svg"
                    )}" width="70" height="48" /></td>\
                    <td>\
                        <div class="cesium-navigation-help-pan">Pan view</div>\
                        <div class="cesium-navigation-help-details">One finger drag</div>\
                    </td>\
                </tr>\
                <tr>\
                    <td><img src="${buildModuleUrl(
                      "Widgets/Images/NavigationHelp/TouchZoom.svg"
                    )}" width="70" height="48" /></td>\
                    <td>\
                        <div class="cesium-navigation-help-zoom">Zoom view</div>\
                        <div class="cesium-navigation-help-details">Two finger pinch</div>\
                    </td>\
                </tr>\
                <tr>\
                    <td><img src="${buildModuleUrl(
                      "Widgets/Images/NavigationHelp/TouchTilt.svg"
                    )}" width="70" height="48" /></td>\
                    <td>\
                        <div class="cesium-navigation-help-rotate">Tilt view</div>\
                        <div class="cesium-navigation-help-details">Two finger drag, same direction</div>\
                    </td>\
                </tr>\
                <tr>\
                    <td><img src="${buildModuleUrl(
                      "Widgets/Images/NavigationHelp/TouchRotate.svg"
                    )}" width="70" height="48" /></td>\
                    <td>\
                        <div class="cesium-navigation-help-tilt">Rotate view</div>\
                        <div class="cesium-navigation-help-details">Two finger drag, opposite direction</div>\
                    </td>\
                </tr>\
            </table>`;

    instructionContainer.appendChild(touchInstructions);

    knockout.applyBindings(viewModel, wrapper);

    this._container = container;
    this._viewModel = viewModel;
    this._wrapper = wrapper;

    this._closeInstructions = function (e) {
      if (!wrapper.contains(e.target)) {
        viewModel.showInstructions = false;
      }
    };

    if (FeatureDetection.supportsPointerEvents()) {
      document.addEventListener("pointerdown", this._closeInstructions, true);
    } else {
      document.addEventListener("mousedown", this._closeInstructions, true);
      document.addEventListener("touchstart", this._closeInstructions, true);
    }
  }

  Object.defineProperties(NavigationHelpButton.prototype, {
    /**
     * Gets the parent container.
     * @memberof NavigationHelpButton.prototype
     *
     * @type {Element}
     */
    container: {
      get: function () {
        return this._container;
      },
    },

    /**
     * Gets the view model.
     * @memberof NavigationHelpButton.prototype
     *
     * @type {NavigationHelpButtonViewModel}
     */
    viewModel: {
      get: function () {
        return this._viewModel;
      },
    },
  });

  /**
   * @returns {Boolean} true if the object has been destroyed, false otherwise.
   */
  NavigationHelpButton.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the widget.  Should be called if permanently
   * removing the widget from layout.
   */
  NavigationHelpButton.prototype.destroy = function () {
    if (FeatureDetection.supportsPointerEvents()) {
      document.removeEventListener("pointerdown", this._closeInstructions, true);
    } else {
      document.removeEventListener("mousedown", this._closeInstructions, true);
      document.removeEventListener("touchstart", this._closeInstructions, true);
    }

    knockout.cleanNode(this._wrapper);
    this._container.removeChild(this._wrapper);

    return destroyObject(this);
  };

  /**
   * The view model for {@link PerformanceWatchdog}.
   *
   * @alias PerformanceWatchdogViewModel
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Scene} options.scene The Scene instance for which to monitor performance.
   * @param {String} [options.lowFrameRateMessage='This application appears to be performing poorly on your system.  Please try using a different web browser or updating your video drivers.'] The
   *        message to display when a low frame rate is detected.  The message is interpeted as HTML, so make sure
   *        it comes from a trusted source so that your application is not vulnerable to cross-site scripting attacks.
   */
  function PerformanceWatchdogViewModel(options) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(options) || !defined(options.scene)) {
      throw new DeveloperError("options.scene is required.");
    }
    //>>includeEnd('debug');

    this._scene = options.scene;

    /**
     * Gets or sets the message to display when a low frame rate is detected.  This string will be interpreted as HTML.
     * @type {String}
     */
    this.lowFrameRateMessage = defaultValue(
      options.lowFrameRateMessage,
      "This application appears to be performing poorly on your system.  Please try using a different web browser or updating your video drivers."
    );

    /**
     * Gets or sets a value indicating whether the low frame rate message has previously been dismissed by the user.  If it has
     * been dismissed, the message will not be redisplayed, no matter the frame rate.
     * @type {Boolean}
     */
    this.lowFrameRateMessageDismissed = false;

    /**
     * Gets or sets a value indicating whether the low frame rate message is currently being displayed.
     * @type {Boolean}
     */
    this.showingLowFrameRateMessage = false;

    knockout.track(this, [
      "lowFrameRateMessage",
      "lowFrameRateMessageDismissed",
      "showingLowFrameRateMessage",
    ]);

    const that = this;
    this._dismissMessage = createCommand(function () {
      that.showingLowFrameRateMessage = false;
      that.lowFrameRateMessageDismissed = true;
    });

    const monitor = FrameRateMonitor.fromScene(options.scene);

    this._unsubscribeLowFrameRate = monitor.lowFrameRate.addEventListener(
      function () {
        if (!that.lowFrameRateMessageDismissed) {
          that.showingLowFrameRateMessage = true;
        }
      }
    );

    this._unsubscribeNominalFrameRate = monitor.nominalFrameRate.addEventListener(
      function () {
        that.showingLowFrameRateMessage = false;
      }
    );
  }

  Object.defineProperties(PerformanceWatchdogViewModel.prototype, {
    /**
     * Gets the {@link Scene} instance for which to monitor performance.
     * @memberof PerformanceWatchdogViewModel.prototype
     * @type {Scene}
     */
    scene: {
      get: function () {
        return this._scene;
      },
    },

    /**
     * Gets a command that dismisses the low frame rate message.  Once it is dismissed, the message
     * will not be redisplayed.
     * @memberof PerformanceWatchdogViewModel.prototype
     * @type {Command}
     */
    dismissMessage: {
      get: function () {
        return this._dismissMessage;
      },
    },
  });

  PerformanceWatchdogViewModel.prototype.destroy = function () {
    this._unsubscribeLowFrameRate();
    this._unsubscribeNominalFrameRate();

    return destroyObject(this);
  };

  /**
   * Monitors performance of the application and displays a message if poor performance is detected.
   *
   * @alias PerformanceWatchdog
   * @constructor
   *
   * @param {Object} [options] Object with the following properties:
   * @param {Element|String} options.container The DOM element or ID that will contain the widget.
   * @param {Scene} options.scene The {@link Scene} for which to monitor performance.
   * @param {String} [options.lowFrameRateMessage='This application appears to be performing poorly on your system.  Please try using a different web browser or updating your video drivers.'] The
   *        message to display when a low frame rate is detected.  The message is interpeted as HTML, so make sure
   *        it comes from a trusted source so that your application is not vulnerable to cross-site scripting attacks.
   */
  function PerformanceWatchdog(options) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(options) || !defined(options.container)) {
      throw new DeveloperError("options.container is required.");
    }
    if (!defined(options.scene)) {
      throw new DeveloperError("options.scene is required.");
    }
    //>>includeEnd('debug');

    const container = getElement(options.container);

    const viewModel = new PerformanceWatchdogViewModel(options);

    const element = document.createElement("div");
    element.className = "cesium-performance-watchdog-message-area";
    element.setAttribute("data-bind", "visible: showingLowFrameRateMessage");

    const dismissButton = document.createElement("button");
    dismissButton.setAttribute("type", "button");
    dismissButton.className = "cesium-performance-watchdog-message-dismiss";
    dismissButton.innerHTML = "&times;";
    dismissButton.setAttribute("data-bind", "click: dismissMessage");
    element.appendChild(dismissButton);

    const message = document.createElement("div");
    message.className = "cesium-performance-watchdog-message";
    message.setAttribute("data-bind", "html: lowFrameRateMessage");
    element.appendChild(message);

    container.appendChild(element);

    knockout.applyBindings(viewModel, element);

    this._container = container;
    this._viewModel = viewModel;
    this._element = element;
  }

  Object.defineProperties(PerformanceWatchdog.prototype, {
    /**
     * Gets the parent container.
     * @memberof PerformanceWatchdog.prototype
     *
     * @type {Element}
     */
    container: {
      get: function () {
        return this._container;
      },
    },

    /**
     * Gets the view model.
     * @memberof PerformanceWatchdog.prototype
     *
     * @type {PerformanceWatchdogViewModel}
     */
    viewModel: {
      get: function () {
        return this._viewModel;
      },
    },
  });

  /**
   * @memberof PerformanceWatchdog
   * @returns {Boolean} true if the object has been destroyed, false otherwise.
   */
  PerformanceWatchdog.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the widget.  Should be called if permanently
   * removing the widget from layout.
   * @memberof PerformanceWatchdog
   */
  PerformanceWatchdog.prototype.destroy = function () {
    this._viewModel.destroy();
    knockout.cleanNode(this._element);
    this._container.removeChild(this._element);

    return destroyObject(this);
  };

  /**
   * The view model for {@link ProjectionPicker}.
   * @alias ProjectionPickerViewModel
   * @constructor
   *
   * @param {Scene} scene The Scene to switch projections.
   */
  function ProjectionPickerViewModel(scene) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(scene)) {
      throw new DeveloperError("scene is required.");
    }
    //>>includeEnd('debug');

    this._scene = scene;
    this._orthographic = scene.camera.frustum instanceof OrthographicFrustum;
    this._flightInProgress = false;

    /**
     * Gets or sets whether the button drop-down is currently visible.  This property is observable.
     * @type {Boolean}
     * @default false
     */
    this.dropDownVisible = false;

    /**
     * Gets or sets the perspective projection tooltip.  This property is observable.
     * @type {String}
     * @default 'Perspective Projection'
     */
    this.tooltipPerspective = "Perspective Projection";

    /**
     * Gets or sets the orthographic projection tooltip.  This property is observable.
     * @type {String}
     * @default 'Orthographic Projection'
     */
    this.tooltipOrthographic = "Orthographic Projection";

    /**
     * Gets the currently active tooltip.  This property is observable.
     * @type {String}
     */
    this.selectedTooltip = undefined;

    /**
     * Gets or sets the current SceneMode.  This property is observable.
     * @type {SceneMode}
     */
    this.sceneMode = scene.mode;

    knockout.track(this, [
      "_orthographic",
      "_flightInProgress",
      "sceneMode",
      "dropDownVisible",
      "tooltipPerspective",
      "tooltipOrthographic",
    ]);

    const that = this;
    knockout.defineProperty(this, "selectedTooltip", function () {
      if (that._orthographic) {
        return that.tooltipOrthographic;
      }
      return that.tooltipPerspective;
    });

    this._toggleDropDown = createCommand(function () {
      if (that.sceneMode === SceneMode$1.SCENE2D || that._flightInProgress) {
        return;
      }

      that.dropDownVisible = !that.dropDownVisible;
    });

    this._eventHelper = new EventHelper();
    this._eventHelper.add(scene.morphComplete, function (
      transitioner,
      oldMode,
      newMode,
      isMorphing
    ) {
      that.sceneMode = newMode;
      that._orthographic =
        newMode === SceneMode$1.SCENE2D ||
        that._scene.camera.frustum instanceof OrthographicFrustum;
    });
    this._eventHelper.add(scene.preRender, function () {
      that._flightInProgress = defined(scene.camera._currentFlight);
    });

    this._switchToPerspective = createCommand(function () {
      if (that.sceneMode === SceneMode$1.SCENE2D) {
        return;
      }

      that._scene.camera.switchToPerspectiveFrustum();
      that._orthographic = false;
      that.dropDownVisible = false;
    });

    this._switchToOrthographic = createCommand(function () {
      if (that.sceneMode === SceneMode$1.SCENE2D) {
        return;
      }

      that._scene.camera.switchToOrthographicFrustum();
      that._orthographic = true;
      that.dropDownVisible = false;
    });

    //Used by knockout
    this._sceneMode = SceneMode$1;
  }

  Object.defineProperties(ProjectionPickerViewModel.prototype, {
    /**
     * Gets the scene
     * @memberof ProjectionPickerViewModel.prototype
     * @type {Scene}
     */
    scene: {
      get: function () {
        return this._scene;
      },
    },

    /**
     * Gets the command to toggle the drop down box.
     * @memberof ProjectionPickerViewModel.prototype
     *
     * @type {Command}
     */
    toggleDropDown: {
      get: function () {
        return this._toggleDropDown;
      },
    },

    /**
     * Gets the command to switch to a perspective projection.
     * @memberof ProjectionPickerViewModel.prototype
     *
     * @type {Command}
     */
    switchToPerspective: {
      get: function () {
        return this._switchToPerspective;
      },
    },

    /**
     * Gets the command to switch to orthographic projection.
     * @memberof ProjectionPickerViewModel.prototype
     *
     * @type {Command}
     */
    switchToOrthographic: {
      get: function () {
        return this._switchToOrthographic;
      },
    },

    /**
     * Gets whether the scene is currently using an orthographic projection.
     * @memberof ProjectionPickerViewModel.prototype
     *
     * @type {Command}
     */
    isOrthographicProjection: {
      get: function () {
        return this._orthographic;
      },
    },
  });

  /**
   * @returns {Boolean} true if the object has been destroyed, false otherwise.
   */
  ProjectionPickerViewModel.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the view model.
   */
  ProjectionPickerViewModel.prototype.destroy = function () {
    this._eventHelper.removeAll();
    destroyObject(this);
  };

  const perspectivePath =
    "M 28.15625,10.4375 9.125,13.21875 13.75,43.25 41.75,55.09375 50.8125,37 54.5,11.9375 z m 0.125,3 19.976451,0.394265 L 43.03125,16.875 22.6875,14.28125 z M 50.971746,15.705477 47.90625,36.03125 42.53125,46 44.84375,19.3125 z M 12.625,16.03125 l 29.15625,3.6875 -2.65625,31 L 16.4375,41.125 z";
  const orthographicPath =
    "m 31.560594,6.5254438 -20.75,12.4687502 0.1875,24.5625 22.28125,11.8125 19.5,-12 0.65625,-0.375 0,-0.75 0.0312,-23.21875 z m 0.0625,3.125 16.65625,9.5000002 -16.125,10.28125 -17.34375,-9.71875 z m 18.96875,11.1875002 0.15625,20.65625 -17.46875,10.59375 0.15625,-20.28125 z m -37.0625,1.25 17.21875,9.625 -0.15625,19.21875 -16.9375,-9 z";

  /**
   * The ProjectionPicker is a single button widget for switching between perspective and orthographic projections.
   *
   * @alias ProjectionPicker
   * @constructor
   *
   * @param {Element|String} container The DOM element or ID that will contain the widget.
   * @param {Scene} scene The Scene instance to use.
   *
   * @exception {DeveloperError} Element with id "container" does not exist in the document.
   *
   * @example
   * // In HTML head, include a link to the ProjectionPicker.css stylesheet,
   * // and in the body, include: <div id="projectionPickerContainer"></div>
   * // Note: This code assumes you already have a Scene instance.
   *
   * const projectionPicker = new Cesium.ProjectionPicker('projectionPickerContainer', scene);
   */
  function ProjectionPicker(container, scene) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(container)) {
      throw new DeveloperError("container is required.");
    }
    if (!defined(scene)) {
      throw new DeveloperError("scene is required.");
    }
    //>>includeEnd('debug');

    container = getElement(container);

    const viewModel = new ProjectionPickerViewModel(scene);

    viewModel._perspectivePath = perspectivePath;
    viewModel._orthographicPath = orthographicPath;

    const wrapper = document.createElement("span");
    wrapper.className = "cesium-projectionPicker-wrapper cesium-toolbar-button";
    container.appendChild(wrapper);

    const button = document.createElement("button");
    button.type = "button";
    button.className = "cesium-button cesium-toolbar-button";
    button.setAttribute(
      "data-bind",
      '\
css: { "cesium-projectionPicker-buttonPerspective": !_orthographic,\
       "cesium-projectionPicker-buttonOrthographic": _orthographic,\
       "cesium-button-disabled" : sceneMode === _sceneMode.SCENE2D || _flightInProgress, \
       "cesium-projectionPicker-selected": dropDownVisible },\
attr: { title: selectedTooltip },\
click: toggleDropDown'
    );
    button.innerHTML =
      '\
<!-- ko cesiumSvgPath: { path: _perspectivePath, width: 64, height: 64, css: "cesium-projectionPicker-iconPerspective" } --><!-- /ko -->\
<!-- ko cesiumSvgPath: { path: _orthographicPath, width: 64, height: 64, css: "cesium-projectionPicker-iconOrthographic" } --><!-- /ko -->';
    wrapper.appendChild(button);

    const perspectiveButton = document.createElement("button");
    perspectiveButton.type = "button";
    perspectiveButton.className =
      "cesium-button cesium-toolbar-button cesium-projectionPicker-dropDown-icon";
    perspectiveButton.setAttribute(
      "data-bind",
      '\
css: { "cesium-projectionPicker-visible" : (dropDownVisible && _orthographic),\
       "cesium-projectionPicker-none" : !_orthographic,\
       "cesium-projectionPicker-hidden" : !dropDownVisible },\
attr: { title: tooltipPerspective },\
click: switchToPerspective,\
cesiumSvgPath: { path: _perspectivePath, width: 64, height: 64 }'
    );
    wrapper.appendChild(perspectiveButton);

    const orthographicButton = document.createElement("button");
    orthographicButton.type = "button";
    orthographicButton.className =
      "cesium-button cesium-toolbar-button cesium-projectionPicker-dropDown-icon";
    orthographicButton.setAttribute(
      "data-bind",
      '\
css: { "cesium-projectionPicker-visible" : (dropDownVisible && !_orthographic),\
       "cesium-projectionPicker-none" : _orthographic,\
       "cesium-projectionPicker-hidden" : !dropDownVisible},\
attr: { title: tooltipOrthographic },\
click: switchToOrthographic,\
cesiumSvgPath: { path: _orthographicPath, width: 64, height: 64 }'
    );
    wrapper.appendChild(orthographicButton);

    knockout.applyBindings(viewModel, wrapper);

    this._viewModel = viewModel;
    this._container = container;
    this._wrapper = wrapper;

    this._closeDropDown = function (e) {
      if (!wrapper.contains(e.target)) {
        viewModel.dropDownVisible = false;
      }
    };
    if (FeatureDetection.supportsPointerEvents()) {
      document.addEventListener("pointerdown", this._closeDropDown, true);
    } else {
      document.addEventListener("mousedown", this._closeDropDown, true);
      document.addEventListener("touchstart", this._closeDropDown, true);
    }
  }

  Object.defineProperties(ProjectionPicker.prototype, {
    /**
     * Gets the parent container.
     * @memberof ProjectionPicker.prototype
     *
     * @type {Element}
     */
    container: {
      get: function () {
        return this._container;
      },
    },

    /**
     * Gets the view model.
     * @memberof ProjectionPicker.prototype
     *
     * @type {ProjectionPickerViewModel}
     */
    viewModel: {
      get: function () {
        return this._viewModel;
      },
    },
  });

  /**
   * @returns {Boolean} true if the object has been destroyed, false otherwise.
   */
  ProjectionPicker.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the widget.  Should be called if permanently
   * removing the widget from layout.
   */
  ProjectionPicker.prototype.destroy = function () {
    this._viewModel.destroy();

    if (FeatureDetection.supportsPointerEvents()) {
      document.removeEventListener("pointerdown", this._closeDropDown, true);
    } else {
      document.removeEventListener("mousedown", this._closeDropDown, true);
      document.removeEventListener("touchstart", this._closeDropDown, true);
    }

    knockout.cleanNode(this._wrapper);
    this._container.removeChild(this._wrapper);

    return destroyObject(this);
  };

  /**
   * The view model for {@link SceneModePicker}.
   * @alias SceneModePickerViewModel
   * @constructor
   *
   * @param {Scene} scene The Scene to morph
   * @param {Number} [duration=2.0] The duration of scene morph animations, in seconds
   */
  function SceneModePickerViewModel(scene, duration) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(scene)) {
      throw new DeveloperError("scene is required.");
    }
    //>>includeEnd('debug');

    this._scene = scene;

    const that = this;

    const morphStart = function (transitioner, oldMode, newMode, isMorphing) {
      that.sceneMode = newMode;
      that.dropDownVisible = false;
    };

    this._eventHelper = new EventHelper();
    this._eventHelper.add(scene.morphStart, morphStart);

    this._duration = defaultValue(duration, 2.0);

    /**
     * Gets or sets the current SceneMode.  This property is observable.
     * @type {SceneMode}
     */
    this.sceneMode = scene.mode;

    /**
     * Gets or sets whether the button drop-down is currently visible.  This property is observable.
     * @type {Boolean}
     * @default false
     */
    this.dropDownVisible = false;

    /**
     * Gets or sets the 2D tooltip.  This property is observable.
     * @type {String}
     * @default '2D'
     */
    this.tooltip2D = "2D";

    /**
     * Gets or sets the 3D tooltip.  This property is observable.
     * @type {String}
     * @default '3D'
     */
    this.tooltip3D = "3D";

    /**
     * Gets or sets the Columbus View tooltip.  This property is observable.
     * @type {String}
     * @default 'Columbus View'
     */
    this.tooltipColumbusView = "Columbus View";

    knockout.track(this, [
      "sceneMode",
      "dropDownVisible",
      "tooltip2D",
      "tooltip3D",
      "tooltipColumbusView",
    ]);

    /**
     * Gets the currently active tooltip.  This property is observable.
     * @type {String}
     */
    this.selectedTooltip = undefined;
    knockout.defineProperty(this, "selectedTooltip", function () {
      const mode = that.sceneMode;
      if (mode === SceneMode$1.SCENE2D) {
        return that.tooltip2D;
      }
      if (mode === SceneMode$1.SCENE3D) {
        return that.tooltip3D;
      }
      return that.tooltipColumbusView;
    });

    this._toggleDropDown = createCommand(function () {
      that.dropDownVisible = !that.dropDownVisible;
    });

    this._morphTo2D = createCommand(function () {
      scene.morphTo2D(that._duration);
    });

    this._morphTo3D = createCommand(function () {
      scene.morphTo3D(that._duration);
    });

    this._morphToColumbusView = createCommand(function () {
      scene.morphToColumbusView(that._duration);
    });

    //Used by knockout
    this._sceneMode = SceneMode$1;
  }

  Object.defineProperties(SceneModePickerViewModel.prototype, {
    /**
     * Gets the scene
     * @memberof SceneModePickerViewModel.prototype
     * @type {Scene}
     */
    scene: {
      get: function () {
        return this._scene;
      },
    },

    /**
     * Gets or sets the the duration of scene mode transition animations in seconds.
     * A value of zero causes the scene to instantly change modes.
     * @memberof SceneModePickerViewModel.prototype
     * @type {Number}
     */
    duration: {
      get: function () {
        return this._duration;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (value < 0.0) {
          throw new DeveloperError("duration value must be positive.");
        }
        //>>includeEnd('debug');

        this._duration = value;
      },
    },

    /**
     * Gets the command to toggle the drop down box.
     * @memberof SceneModePickerViewModel.prototype
     *
     * @type {Command}
     */
    toggleDropDown: {
      get: function () {
        return this._toggleDropDown;
      },
    },

    /**
     * Gets the command to morph to 2D.
     * @memberof SceneModePickerViewModel.prototype
     *
     * @type {Command}
     */
    morphTo2D: {
      get: function () {
        return this._morphTo2D;
      },
    },

    /**
     * Gets the command to morph to 3D.
     * @memberof SceneModePickerViewModel.prototype
     *
     * @type {Command}
     */
    morphTo3D: {
      get: function () {
        return this._morphTo3D;
      },
    },

    /**
     * Gets the command to morph to Columbus View.
     * @memberof SceneModePickerViewModel.prototype
     *
     * @type {Command}
     */
    morphToColumbusView: {
      get: function () {
        return this._morphToColumbusView;
      },
    },
  });

  /**
   * @returns {Boolean} true if the object has been destroyed, false otherwise.
   */
  SceneModePickerViewModel.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the view model.
   */
  SceneModePickerViewModel.prototype.destroy = function () {
    this._eventHelper.removeAll();

    destroyObject(this);
  };

  const globePath =
    "m 32.401392,4.9330437 c -7.087603,0 -14.096095,2.884602 -19.10793,7.8946843 -5.0118352,5.010083 -7.9296167,11.987468 -7.9296167,19.072999 0,7.085531 2.9177815,14.097848 7.9296167,19.107931 4.837653,4.835961 11.541408,7.631372 18.374354,7.82482 0.05712,0.01231 0.454119,0.139729 0.454119,0.139729 l 0.03493,-0.104797 c 0.08246,7.84e-4 0.162033,0.03493 0.244525,0.03493 0.08304,0 0.161515,-0.03414 0.244526,-0.03493 l 0.03493,0.104797 c 0,0 0.309474,-0.129487 0.349323,-0.139729 6.867765,-0.168094 13.582903,-2.965206 18.444218,-7.82482 2.558195,-2.5573 4.551081,-5.638134 5.903547,-8.977584 1.297191,-3.202966 2.02607,-6.661489 2.02607,-10.130347 0,-6.237309 -2.366261,-12.31219 -6.322734,-17.116794 -0.0034,-0.02316 0.0049,-0.04488 0,-0.06986 -0.01733,-0.08745 -0.104529,-0.278855 -0.104797,-0.279458 -5.31e-4,-0.0012 -0.522988,-0.628147 -0.523984,-0.62878 \
        -3.47e-4,-2.2e-4 -0.133444,-0.03532 -0.244525,-0.06987 C 51.944299,13.447603 51.751076,13.104317 51.474391,12.827728 46.462556,7.8176457 39.488996,4.9330437 32.401392,4.9330437 z m -2.130866,3.5281554 0.104797,9.6762289 c -4.111695,-0.08361 -7.109829,-0.423664 -9.257041,-0.943171 1.198093,-2.269271 2.524531,-4.124404 3.91241,-5.414496 2.167498,-2.0147811 3.950145,-2.8540169 5.239834,-3.3185619 z m 2.794579,0 c 1.280302,0.4754953 3.022186,1.3285948 5.065173,3.2486979 1.424667,1.338973 2.788862,3.303645 3.982275,5.728886 -2.29082,0.403367 -5.381258,0.621049 -8.942651,0.698645 L 33.065105,8.4611991 z m 5.728886,0.2445256 c 4.004072,1.1230822 7.793098,3.1481363 10.724195,6.0782083 0.03468,0.03466 0.07033,0.06991 0.104797,0.104797 -0.45375,0.313891 -0.923054,0.663002 -1.956205,1.082899 -0.647388,0.263114 -1.906242,0.477396 -2.829511,0.733577 -1.382296,-2.988132 \
        -3.027146,-5.368585 -4.785716,-7.0213781 -0.422866,-0.397432 -0.835818,-0.6453247 -1.25756,-0.9781032 z m -15.33525,0.7685092 c -0.106753,0.09503 -0.207753,0.145402 -0.31439,0.244526 -1.684973,1.5662541 -3.298068,3.8232211 -4.680919,6.5672591 -0.343797,-0.14942 -1.035052,-0.273198 -1.292493,-0.419186 -0.956528,-0.542427 -1.362964,-1.022024 -1.537018,-1.292493 -0.0241,-0.03745 -0.01868,-0.0401 -0.03493,-0.06986 2.250095,-2.163342 4.948824,-3.869984 7.859752,-5.0302421 z m -9.641296,7.0912431 c 0.464973,0.571618 0.937729,1.169056 1.956205,1.746612 0.349907,0.198425 1.107143,0.335404 1.537018,0.523983 -1.20166,3.172984 -1.998037,7.051901 -2.165798,11.772162 C 14.256557,30.361384 12.934823,30.161483 12.280427,29.90959 10.644437,29.279855 9.6888882,28.674891 9.1714586,28.267775 8.6540289,27.860658 8.6474751,27.778724 8.6474751,27.778724 l -0.069864,0.03493 C 9.3100294,23.691285 \
        11.163248,19.798527 13.817445,16.565477 z m 37.552149,0.523984 c 2.548924,3.289983 4.265057,7.202594 4.890513,11.318043 -0.650428,0.410896 -1.756876,1.001936 -3.563088,1.606882 -1.171552,0.392383 -3.163859,0.759153 -4.960377,1.117832 -0.04367,-4.752703 -0.784809,-8.591423 -1.88634,-11.807094 0.917574,-0.263678 2.170552,-0.486495 2.864443,-0.76851 1.274693,-0.518066 2.003942,-1.001558 2.654849,-1.467153 z m -31.439008,2.619917 c 2.487341,0.672766 5.775813,1.137775 10.479669,1.222628 l 0.104797,10.689263 0,0.03493 0,0.733577 c -5.435005,-0.09059 -9.512219,-0.519044 -12.610536,-1.117831 0.106127,-4.776683 0.879334,-8.55791 2.02607,-11.562569 z m 23.264866,0.31439 c 1.073459,3.067541 1.833795,6.821314 1.816476,11.702298 -3.054474,0.423245 -7.062018,0.648559 -11.702298,0.698644 l 0,-0.838373 -0.104796,-10.654331 c 4.082416,-0.0864 7.404468,-0.403886 9.990618,-0.908238 z \
        M 8.2632205,30.922625 c 0.7558676,0.510548 1.5529563,1.013339 3.0041715,1.57195 0.937518,0.360875 2.612202,0.647642 3.91241,0.978102 0.112814,3.85566 0.703989,7.107756 1.606883,9.920754 -1.147172,-0.324262 -2.644553,-0.640648 -3.423359,-0.978102 -1.516688,-0.657177 -2.386627,-1.287332 -2.864443,-1.71168 -0.477816,-0.424347 -0.489051,-0.489051 -0.489051,-0.489051 L 9.8002387,40.319395 C 8.791691,37.621767 8.1584238,34.769583 8.1584238,31.900727 c 0,-0.330153 0.090589,-0.648169 0.1047967,-0.978102 z m 48.2763445,0.419186 c 0.0047,0.188973 0.06986,0.36991 0.06986,0.558916 0,2.938869 -0.620228,5.873558 -1.676747,8.628261 -0.07435,0.07583 -0.06552,0.07411 -0.454119,0.349323 -0.606965,0.429857 -1.631665,1.042044 -3.318562,1.676747 -1.208528,0.454713 -3.204964,0.850894 -5.135038,1.25756 0.84593,-2.765726 1.41808,-6.005357 1.606883,-9.815957 2.232369,-0.413371 4.483758,-0.840201 \
        5.938479,-1.327425 1.410632,-0.472457 2.153108,-0.89469 2.96924,-1.327425 z m -38.530252,2.864443 c 3.208141,0.56697 7.372279,0.898588 12.575603,0.978103 l 0.174662,9.885821 c -4.392517,-0.06139 -8.106722,-0.320566 -10.863925,-0.803441 -1.051954,-2.664695 -1.692909,-6.043794 -1.88634,-10.060483 z m 26.793022,0.31439 c -0.246298,3.923551 -0.877762,7.263679 -1.816476,9.885822 -2.561957,0.361954 -5.766249,0.560708 -9.431703,0.62878 l -0.174661,-9.815957 c 4.491734,-0.04969 8.334769,-0.293032 11.42284,-0.698645 z M 12.035901,44.860585 c 0.09977,0.04523 0.105535,0.09465 0.209594,0.139729 1.337656,0.579602 3.441099,1.058072 5.589157,1.537018 1.545042,3.399208 3.548524,5.969402 5.589157,7.789888 -3.034411,-1.215537 -5.871615,-3.007978 -8.174142,-5.309699 -1.245911,-1.245475 -2.271794,-2.662961 -3.213766,-4.156936 z m 40.69605,0 c -0.941972,1.493975 -1.967855,2.911461 \
        -3.213765,4.156936 -2.74253,2.741571 -6.244106,4.696717 -9.955686,5.868615 0.261347,-0.241079 0.507495,-0.394491 0.768509,-0.663713 1.674841,-1.727516 3.320792,-4.181056 4.645987,-7.265904 2.962447,-0.503021 5.408965,-1.122293 7.161107,-1.781544 0.284034,-0.106865 0.337297,-0.207323 0.593848,-0.31439 z m -31.404076,2.305527 c 2.645807,0.376448 5.701178,0.649995 9.466635,0.698645 l 0.139729,7.789888 c -1.38739,-0.480844 -3.316218,-1.29837 -5.659022,-3.388427 -1.388822,-1.238993 -2.743668,-3.0113 -3.947342,-5.100106 z m 20.365491,0.104797 c -1.04872,2.041937 -2.174337,3.779068 -3.353494,4.995309 -1.853177,1.911459 -3.425515,2.82679 -4.611055,3.353494 l -0.139729,-7.789887 c 3.13091,-0.05714 5.728238,-0.278725 8.104278,-0.558916 z";
  const flatMapPath =
    "m 2.9825053,17.550598 0,1.368113 0,26.267766 0,1.368113 1.36811,0 54.9981397,0 1.36811,0 0,-1.368113 0,-26.267766 0,-1.368113 -1.36811,0 -54.9981397,0 -1.36811,0 z m 2.73623,2.736226 10.3292497,0 0,10.466063 -10.3292497,0 0,-10.466063 z m 13.0654697,0 11.69737,0 0,10.466063 -11.69737,0 0,-10.466063 z m 14.43359,0 11.69737,0 0,10.466063 -11.69737,0 0,-10.466063 z m 14.43359,0 10.32926,0 0,10.466063 -10.32926,0 0,-10.466063 z m -41.9326497,13.202288 10.3292497,0 0,10.329252 -10.3292497,0 0,-10.329252 z m 13.0654697,0 11.69737,0 0,10.329252 -11.69737,0 0,-10.329252 z m 14.43359,0 11.69737,0 0,10.329252 -11.69737,0 0,-10.329252 z m 14.43359,0 10.32926,0 0,10.329252 -10.32926,0 0,-10.329252 z";
  const columbusViewPath =
    "m 14.723969,17.675598 -0.340489,0.817175 -11.1680536,26.183638 -0.817175,1.872692 2.076986,0 54.7506996,0 2.07698,0 -0.81717,-1.872692 -11.16805,-26.183638 -0.34049,-0.817175 -0.91933,0 -32.414586,0 -0.919322,0 z m 1.838643,2.723916 6.196908,0 -2.928209,10.418977 -7.729111,0 4.460412,-10.418977 z m 9.02297,0 4.903049,0 0,10.418977 -7.831258,0 2.928209,-10.418977 z m 7.626964,0 5.584031,0 2.62176,10.418977 -8.205791,0 0,-10.418977 z m 8.410081,0 5.51593,0 4.46042,10.418977 -7.38863,0 -2.58772,-10.418977 z m -30.678091,13.142892 8.103649,0 -2.89416,10.282782 -9.6018026,0 4.3923136,-10.282782 z m 10.929711,0 8.614384,0 0,10.282782 -11.508544,0 2.89416,-10.282782 z m 11.338299,0 8.852721,0 2.58772,10.282782 -11.440441,0 0,-10.282782 z m 11.678781,0 7.86531,0 4.39231,10.282782 -9.6699,0 -2.58772,-10.282782 z";

  /**
   * <img src="Images/sceneModePicker.png" style="float: left; margin-right: 10px;" width="44" height="116" />
   * <p>The SceneModePicker is a single button widget for switching between scene modes;
   * shown to the left in its expanded state. Programatic switching of scene modes will
   * be automatically reflected in the widget as long as the specified Scene
   * is used to perform the change.</p><p style="clear: both;"></p><br/>
   *
   * @alias SceneModePicker
   * @constructor
   *
   * @param {Element|String} container The DOM element or ID that will contain the widget.
   * @param {Scene} scene The Scene instance to use.
   * @param {Number} [duration=2.0] The time, in seconds, it takes for the scene to transition.
   *
   * @exception {DeveloperError} Element with id "container" does not exist in the document.
   *
   * @example
   * // In HTML head, include a link to the SceneModePicker.css stylesheet,
   * // and in the body, include: <div id="sceneModePickerContainer"></div>
   * // Note: This code assumes you already have a Scene instance.
   *
   * const sceneModePicker = new Cesium.SceneModePicker('sceneModePickerContainer', scene);
   */
  function SceneModePicker(container, scene, duration) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(container)) {
      throw new DeveloperError("container is required.");
    }
    if (!defined(scene)) {
      throw new DeveloperError("scene is required.");
    }
    //>>includeEnd('debug');

    container = getElement(container);

    const viewModel = new SceneModePickerViewModel(scene, duration);

    viewModel._globePath = globePath;
    viewModel._flatMapPath = flatMapPath;
    viewModel._columbusViewPath = columbusViewPath;

    const wrapper = document.createElement("span");
    wrapper.className = "cesium-sceneModePicker-wrapper cesium-toolbar-button";
    container.appendChild(wrapper);

    const button = document.createElement("button");
    button.type = "button";
    button.className = "cesium-button cesium-toolbar-button";
    button.setAttribute(
      "data-bind",
      '\
css: { "cesium-sceneModePicker-button2D": sceneMode === _sceneMode.SCENE2D,\
       "cesium-sceneModePicker-button3D": sceneMode === _sceneMode.SCENE3D,\
       "cesium-sceneModePicker-buttonColumbusView": sceneMode === _sceneMode.COLUMBUS_VIEW,\
       "cesium-sceneModePicker-selected": dropDownVisible },\
attr: { title: selectedTooltip },\
click: toggleDropDown'
    );
    button.innerHTML =
      '\
<!-- ko cesiumSvgPath: { path: _globePath, width: 64, height: 64, css: "cesium-sceneModePicker-slide-svg cesium-sceneModePicker-icon3D" } --><!-- /ko -->\
<!-- ko cesiumSvgPath: { path: _flatMapPath, width: 64, height: 64, css: "cesium-sceneModePicker-slide-svg cesium-sceneModePicker-icon2D" } --><!-- /ko -->\
<!-- ko cesiumSvgPath: { path: _columbusViewPath, width: 64, height: 64, css: "cesium-sceneModePicker-slide-svg cesium-sceneModePicker-iconColumbusView" } --><!-- /ko -->';
    wrapper.appendChild(button);

    const morphTo3DButton = document.createElement("button");
    morphTo3DButton.type = "button";
    morphTo3DButton.className =
      "cesium-button cesium-toolbar-button cesium-sceneModePicker-dropDown-icon";
    morphTo3DButton.setAttribute(
      "data-bind",
      '\
css: { "cesium-sceneModePicker-visible" : (dropDownVisible && (sceneMode !== _sceneMode.SCENE3D)) || (!dropDownVisible && (sceneMode === _sceneMode.SCENE3D)),\
       "cesium-sceneModePicker-none" : sceneMode === _sceneMode.SCENE3D,\
       "cesium-sceneModePicker-hidden" : !dropDownVisible },\
attr: { title: tooltip3D },\
click: morphTo3D,\
cesiumSvgPath: { path: _globePath, width: 64, height: 64 }'
    );
    wrapper.appendChild(morphTo3DButton);

    const morphTo2DButton = document.createElement("button");
    morphTo2DButton.type = "button";
    morphTo2DButton.className =
      "cesium-button cesium-toolbar-button cesium-sceneModePicker-dropDown-icon";
    morphTo2DButton.setAttribute(
      "data-bind",
      '\
css: { "cesium-sceneModePicker-visible" : (dropDownVisible && (sceneMode !== _sceneMode.SCENE2D)),\
       "cesium-sceneModePicker-none" : sceneMode === _sceneMode.SCENE2D,\
       "cesium-sceneModePicker-hidden" : !dropDownVisible },\
attr: { title: tooltip2D },\
click: morphTo2D,\
cesiumSvgPath: { path: _flatMapPath, width: 64, height: 64 }'
    );
    wrapper.appendChild(morphTo2DButton);

    const morphToCVButton = document.createElement("button");
    morphToCVButton.type = "button";
    morphToCVButton.className =
      "cesium-button cesium-toolbar-button cesium-sceneModePicker-dropDown-icon";
    morphToCVButton.setAttribute(
      "data-bind",
      '\
css: { "cesium-sceneModePicker-visible" : (dropDownVisible && (sceneMode !== _sceneMode.COLUMBUS_VIEW)) || (!dropDownVisible && (sceneMode === _sceneMode.COLUMBUS_VIEW)),\
       "cesium-sceneModePicker-none" : sceneMode === _sceneMode.COLUMBUS_VIEW,\
       "cesium-sceneModePicker-hidden" : !dropDownVisible},\
attr: { title: tooltipColumbusView },\
click: morphToColumbusView,\
cesiumSvgPath: { path: _columbusViewPath, width: 64, height: 64 }'
    );
    wrapper.appendChild(morphToCVButton);

    knockout.applyBindings(viewModel, wrapper);

    this._viewModel = viewModel;
    this._container = container;
    this._wrapper = wrapper;

    this._closeDropDown = function (e) {
      if (!wrapper.contains(e.target)) {
        viewModel.dropDownVisible = false;
      }
    };
    if (FeatureDetection.supportsPointerEvents()) {
      document.addEventListener("pointerdown", this._closeDropDown, true);
    } else {
      document.addEventListener("mousedown", this._closeDropDown, true);
      document.addEventListener("touchstart", this._closeDropDown, true);
    }
  }

  Object.defineProperties(SceneModePicker.prototype, {
    /**
     * Gets the parent container.
     * @memberof SceneModePicker.prototype
     *
     * @type {Element}
     */
    container: {
      get: function () {
        return this._container;
      },
    },

    /**
     * Gets the view model.
     * @memberof SceneModePicker.prototype
     *
     * @type {SceneModePickerViewModel}
     */
    viewModel: {
      get: function () {
        return this._viewModel;
      },
    },
  });

  /**
   * @returns {Boolean} true if the object has been destroyed, false otherwise.
   */
  SceneModePicker.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the widget.  Should be called if permanently
   * removing the widget from layout.
   */
  SceneModePicker.prototype.destroy = function () {
    this._viewModel.destroy();

    if (FeatureDetection.supportsPointerEvents()) {
      document.removeEventListener("pointerdown", this._closeDropDown, true);
    } else {
      document.removeEventListener("mousedown", this._closeDropDown, true);
      document.removeEventListener("touchstart", this._closeDropDown, true);
    }

    knockout.cleanNode(this._wrapper);
    this._container.removeChild(this._wrapper);

    return destroyObject(this);
  };

  const screenSpacePos = new Cartesian2();
  const offScreen = "-1000px";

  /**
   * The view model for {@link SelectionIndicator}.
   * @alias SelectionIndicatorViewModel
   * @constructor
   *
   * @param {Scene} scene The scene instance to use for screen-space coordinate conversion.
   * @param {Element} selectionIndicatorElement The element containing all elements that make up the selection indicator.
   * @param {Element} container The DOM element that contains the widget.
   */
  function SelectionIndicatorViewModel(
    scene,
    selectionIndicatorElement,
    container
  ) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(scene)) {
      throw new DeveloperError("scene is required.");
    }

    if (!defined(selectionIndicatorElement)) {
      throw new DeveloperError("selectionIndicatorElement is required.");
    }

    if (!defined(container)) {
      throw new DeveloperError("container is required.");
    }
    //>>includeEnd('debug')

    this._scene = scene;
    this._screenPositionX = offScreen;
    this._screenPositionY = offScreen;
    this._tweens = scene.tweens;
    this._container = defaultValue(container, document.body);
    this._selectionIndicatorElement = selectionIndicatorElement;
    this._scale = 1;

    /**
     * Gets or sets the world position of the object for which to display the selection indicator.
     * @type {Cartesian3}
     */
    this.position = undefined;

    /**
     * Gets or sets the visibility of the selection indicator.
     * @type {Boolean}
     */
    this.showSelection = false;

    knockout.track(this, [
      "position",
      "_screenPositionX",
      "_screenPositionY",
      "_scale",
      "showSelection",
    ]);

    /**
     * Gets the visibility of the position indicator.  This can be false even if an
     * object is selected, when the selected object has no position.
     * @type {Boolean}
     */
    this.isVisible = undefined;
    knockout.defineProperty(this, "isVisible", {
      get: function () {
        return this.showSelection && defined(this.position);
      },
    });

    knockout.defineProperty(this, "_transform", {
      get: function () {
        return `scale(${this._scale})`;
      },
    });

    /**
     * Gets or sets the function for converting the world position of the object to the screen space position.
     *
     * @member
     * @type {SelectionIndicatorViewModel.ComputeScreenSpacePosition}
     * @default SceneTransforms.wgs84ToWindowCoordinates
     *
     * @example
     * selectionIndicatorViewModel.computeScreenSpacePosition = function(position, result) {
     *     return Cesium.SceneTransforms.wgs84ToWindowCoordinates(scene, position, result);
     * };
     */
    this.computeScreenSpacePosition = function (position, result) {
      return SceneTransforms.wgs84ToWindowCoordinates(scene, position, result);
    };
  }

  /**
   * Updates the view of the selection indicator to match the position and content properties of the view model.
   * This function should be called as part of the render loop.
   */
  SelectionIndicatorViewModel.prototype.update = function () {
    if (this.showSelection && defined(this.position)) {
      const screenPosition = this.computeScreenSpacePosition(
        this.position,
        screenSpacePos
      );
      if (!defined(screenPosition)) {
        this._screenPositionX = offScreen;
        this._screenPositionY = offScreen;
      } else {
        const container = this._container;
        const containerWidth = container.parentNode.clientWidth;
        const containerHeight = container.parentNode.clientHeight;
        const indicatorSize = this._selectionIndicatorElement.clientWidth;
        const halfSize = indicatorSize * 0.5;

        screenPosition.x =
          Math.min(
            Math.max(screenPosition.x, -indicatorSize),
            containerWidth + indicatorSize
          ) - halfSize;
        screenPosition.y =
          Math.min(
            Math.max(screenPosition.y, -indicatorSize),
            containerHeight + indicatorSize
          ) - halfSize;

        this._screenPositionX = `${Math.floor(screenPosition.x + 0.25)}px`;
        this._screenPositionY = `${Math.floor(screenPosition.y + 0.25)}px`;
      }
    }
  };

  /**
   * Animate the indicator to draw attention to the selection.
   */
  SelectionIndicatorViewModel.prototype.animateAppear = function () {
    this._tweens.addProperty({
      object: this,
      property: "_scale",
      startValue: 2,
      stopValue: 1,
      duration: 0.8,
      easingFunction: EasingFunction$1.EXPONENTIAL_OUT,
    });
  };

  /**
   * Animate the indicator to release the selection.
   */
  SelectionIndicatorViewModel.prototype.animateDepart = function () {
    this._tweens.addProperty({
      object: this,
      property: "_scale",
      startValue: this._scale,
      stopValue: 1.5,
      duration: 0.8,
      easingFunction: EasingFunction$1.EXPONENTIAL_OUT,
    });
  };

  Object.defineProperties(SelectionIndicatorViewModel.prototype, {
    /**
     * Gets the HTML element containing the selection indicator.
     * @memberof SelectionIndicatorViewModel.prototype
     *
     * @type {Element}
     */
    container: {
      get: function () {
        return this._container;
      },
    },

    /**
     * Gets the HTML element that holds the selection indicator.
     * @memberof SelectionIndicatorViewModel.prototype
     *
     * @type {Element}
     */
    selectionIndicatorElement: {
      get: function () {
        return this._selectionIndicatorElement;
      },
    },

    /**
     * Gets the scene being used.
     * @memberof SelectionIndicatorViewModel.prototype
     *
     * @type {Scene}
     */
    scene: {
      get: function () {
        return this._scene;
      },
    },
  });

  /**
   * A widget for displaying an indicator on a selected object.
   *
   * @alias SelectionIndicator
   * @constructor
   *
   * @param {Element|String} container The DOM element or ID that will contain the widget.
   * @param {Scene} scene The Scene instance to use.
   *
   * @exception {DeveloperError} Element with id "container" does not exist in the document.
   */
  function SelectionIndicator(container, scene) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(container)) {
      throw new DeveloperError("container is required.");
    }
    //>>includeEnd('debug')

    container = getElement(container);

    this._container = container;

    const el = document.createElement("div");
    el.className = "cesium-selection-wrapper";
    el.setAttribute(
      "data-bind",
      '\
style: { "top" : _screenPositionY, "left" : _screenPositionX },\
css: { "cesium-selection-wrapper-visible" : isVisible }'
    );
    container.appendChild(el);
    this._element = el;

    const svgNS = "http://www.w3.org/2000/svg";
    const path =
      "M -34 -34 L -34 -11.25 L -30 -15.25 L -30 -30 L -15.25 -30 L -11.25 -34 L -34 -34 z M 11.25 -34 L 15.25 -30 L 30 -30 L 30 -15.25 L 34 -11.25 L 34 -34 L 11.25 -34 z M -34 11.25 L -34 34 L -11.25 34 L -15.25 30 L -30 30 L -30 15.25 L -34 11.25 z M 34 11.25 L 30 15.25 L 30 30 L 15.25 30 L 11.25 34 L 34 34 L 34 11.25 z";

    const svg = document.createElementNS(svgNS, "svg:svg");
    svg.setAttribute("width", 160);
    svg.setAttribute("height", 160);
    svg.setAttribute("viewBox", "0 0 160 160");

    const group = document.createElementNS(svgNS, "g");
    group.setAttribute("transform", "translate(80,80)");
    svg.appendChild(group);

    const pathElement = document.createElementNS(svgNS, "path");
    pathElement.setAttribute("data-bind", "attr: { transform: _transform }");
    pathElement.setAttribute("d", path);
    group.appendChild(pathElement);

    el.appendChild(svg);

    const viewModel = new SelectionIndicatorViewModel(
      scene,
      this._element,
      this._container
    );
    this._viewModel = viewModel;

    knockout.applyBindings(this._viewModel, this._element);
  }

  Object.defineProperties(SelectionIndicator.prototype, {
    /**
     * Gets the parent container.
     * @memberof SelectionIndicator.prototype
     *
     * @type {Element}
     */
    container: {
      get: function () {
        return this._container;
      },
    },

    /**
     * Gets the view model.
     * @memberof SelectionIndicator.prototype
     *
     * @type {SelectionIndicatorViewModel}
     */
    viewModel: {
      get: function () {
        return this._viewModel;
      },
    },
  });

  /**
   * @returns {Boolean} true if the object has been destroyed, false otherwise.
   */
  SelectionIndicator.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the widget.  Should be called if permanently
   * removing the widget from layout.
   */
  SelectionIndicator.prototype.destroy = function () {
    const container = this._container;
    knockout.cleanNode(this._element);
    container.removeChild(this._element);
    return destroyObject(this);
  };

  /**
   * @private
   */
  function TimelineHighlightRange(color, heightInPx, base) {
    this._color = color;
    this._height = heightInPx;
    this._base = defaultValue(base, 0);
  }

  TimelineHighlightRange.prototype.getHeight = function () {
    return this._height;
  };

  TimelineHighlightRange.prototype.getBase = function () {
    return this._base;
  };

  TimelineHighlightRange.prototype.getStartTime = function () {
    return this._start;
  };

  TimelineHighlightRange.prototype.getStopTime = function () {
    return this._stop;
  };

  TimelineHighlightRange.prototype.setRange = function (start, stop) {
    this._start = start;
    this._stop = stop;
  };

  TimelineHighlightRange.prototype.render = function (renderState) {
    let range = "";
    if (this._start && this._stop && this._color) {
      const highlightStart = JulianDate.secondsDifference(
        this._start,
        renderState.epochJulian
      );
      let highlightLeft = Math.round(
        renderState.timeBarWidth * renderState.getAlpha(highlightStart)
      );
      const highlightStop = JulianDate.secondsDifference(
        this._stop,
        renderState.epochJulian
      );
      let highlightWidth =
        Math.round(
          renderState.timeBarWidth * renderState.getAlpha(highlightStop)
        ) - highlightLeft;
      if (highlightLeft < 0) {
        highlightWidth += highlightLeft;
        highlightLeft = 0;
      }
      if (highlightLeft + highlightWidth > renderState.timeBarWidth) {
        highlightWidth = renderState.timeBarWidth - highlightLeft;
      }
      if (highlightWidth > 0) {
        range = `<span class="cesium-timeline-highlight" style="left: ${highlightLeft.toString()}px; width: ${highlightWidth.toString()}px; bottom: ${this._base.toString()}px; height: ${
        this._height
      }px; background-color: ${this._color};"></span>`;
      }
    }
    return range;
  };

  /**
   * @private
   */
  function TimelineTrack(interval, pixelHeight, color, backgroundColor) {
    this.interval = interval;
    this.height = pixelHeight;
    this.color = color || new Color(0.5, 0.5, 0.5, 1.0);
    this.backgroundColor = backgroundColor || new Color(0.0, 0.0, 0.0, 0.0);
  }

  TimelineTrack.prototype.render = function (context, renderState) {
    const startInterval = this.interval.start;
    const stopInterval = this.interval.stop;

    const spanStart = renderState.startJulian;
    const spanStop = JulianDate.addSeconds(
      renderState.startJulian,
      renderState.duration,
      new JulianDate()
    );

    if (
      JulianDate.lessThan(startInterval, spanStart) &&
      JulianDate.greaterThan(stopInterval, spanStop)
    ) {
      //The track takes up the entire visible span.
      context.fillStyle = this.color.toCssColorString();
      context.fillRect(0, renderState.y, renderState.timeBarWidth, this.height);
    } else if (
      JulianDate.lessThanOrEquals(startInterval, spanStop) &&
      JulianDate.greaterThanOrEquals(stopInterval, spanStart)
    ) {
      //The track only takes up some of the visible span, compute that span.
      let x;
      let start, stop;
      for (x = 0; x < renderState.timeBarWidth; ++x) {
        const currentTime = JulianDate.addSeconds(
          renderState.startJulian,
          (x / renderState.timeBarWidth) * renderState.duration,
          new JulianDate()
        );
        if (
          !defined(start) &&
          JulianDate.greaterThanOrEquals(currentTime, startInterval)
        ) {
          start = x;
        } else if (
          !defined(stop) &&
          JulianDate.greaterThanOrEquals(currentTime, stopInterval)
        ) {
          stop = x;
        }
      }

      context.fillStyle = this.backgroundColor.toCssColorString();
      context.fillRect(0, renderState.y, renderState.timeBarWidth, this.height);

      if (defined(start)) {
        if (!defined(stop)) {
          stop = renderState.timeBarWidth;
        }
        context.fillStyle = this.color.toCssColorString();
        context.fillRect(
          start,
          renderState.y,
          Math.max(stop - start, 1),
          this.height
        );
      }
    }
  };

  let timelineWheelDelta = 1e12;

  const timelineMouseMode = {
    none: 0,
    scrub: 1,
    slide: 2,
    zoom: 3,
    touchOnly: 4,
  };
  const timelineTouchMode = {
    none: 0,
    scrub: 1,
    slideZoom: 2,
    singleTap: 3,
    ignore: 4,
  };

  const timelineTicScales = [
    0.001,
    0.002,
    0.005,
    0.01,
    0.02,
    0.05,
    0.1,
    0.25,
    0.5,
    1.0,
    2.0,
    5.0,
    10.0,
    15.0,
    30.0,
    60.0, // 1min
    120.0, // 2min
    300.0, // 5min
    600.0, // 10min
    900.0, // 15min
    1800.0, // 30min
    3600.0, // 1hr
    7200.0, // 2hr
    14400.0, // 4hr
    21600.0, // 6hr
    43200.0, // 12hr
    86400.0, // 24hr
    172800.0, // 2days
    345600.0, // 4days
    604800.0, // 7days
    1296000.0, // 15days
    2592000.0, // 30days
    5184000.0, // 60days
    7776000.0, // 90days
    15552000.0, // 180days
    31536000.0, // 365days
    63072000.0, // 2years
    126144000.0, // 4years
    157680000.0, // 5years
    315360000.0, // 10years
    630720000.0, // 20years
    1261440000.0, // 40years
    1576800000.0, // 50years
    3153600000.0, // 100years
    6307200000.0, // 200years
    12614400000.0, // 400years
    15768000000.0, // 500years
    31536000000.0, // 1000years
  ];

  const timelineMonthNames = [
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "Jun",
    "Jul",
    "Aug",
    "Sep",
    "Oct",
    "Nov",
    "Dec",
  ];

  /**
   * The Timeline is a widget for displaying and controlling the current scene time.
   * @alias Timeline
   * @constructor
   *
   * @param {Element} container The parent HTML container node for this widget.
   * @param {Clock} clock The clock to use.
   */
  function Timeline(container, clock) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(container)) {
      throw new DeveloperError("container is required.");
    }
    if (!defined(clock)) {
      throw new DeveloperError("clock is required.");
    }
    //>>includeEnd('debug');

    container = getElement(container);

    const ownerDocument = container.ownerDocument;

    /**
     * Gets the parent container.
     * @type {Element}
     */
    this.container = container;

    const topDiv = ownerDocument.createElement("div");
    topDiv.className = "cesium-timeline-main";
    container.appendChild(topDiv);
    this._topDiv = topDiv;

    this._endJulian = undefined;
    this._epochJulian = undefined;
    this._lastXPos = undefined;
    this._scrubElement = undefined;
    this._startJulian = undefined;
    this._timeBarSecondsSpan = undefined;
    this._clock = clock;
    this._scrubJulian = clock.currentTime;
    this._mainTicSpan = -1;
    this._mouseMode = timelineMouseMode.none;
    this._touchMode = timelineTouchMode.none;
    this._touchState = {
      centerX: 0,
      spanX: 0,
    };
    this._mouseX = 0;
    this._timelineDrag = 0;
    this._timelineDragLocation = undefined;
    this._lastHeight = undefined;
    this._lastWidth = undefined;

    this._topDiv.innerHTML =
      '<div class="cesium-timeline-bar"></div><div class="cesium-timeline-trackContainer">' +
      '<canvas class="cesium-timeline-tracks" width="10" height="1">' +
      '</canvas></div><div class="cesium-timeline-needle"></div><span class="cesium-timeline-ruler"></span>';
    this._timeBarEle = this._topDiv.childNodes[0];
    this._trackContainer = this._topDiv.childNodes[1];
    this._trackListEle = this._topDiv.childNodes[1].childNodes[0];
    this._needleEle = this._topDiv.childNodes[2];
    this._rulerEle = this._topDiv.childNodes[3];
    this._context = this._trackListEle.getContext("2d");

    this._trackList = [];
    this._highlightRanges = [];

    this.zoomTo(clock.startTime, clock.stopTime);

    this._onMouseDown = createMouseDownCallback(this);
    this._onMouseUp = createMouseUpCallback(this);
    this._onMouseMove = createMouseMoveCallback(this);
    this._onMouseWheel = createMouseWheelCallback(this);
    this._onTouchStart = createTouchStartCallback(this);
    this._onTouchMove = createTouchMoveCallback(this);
    this._onTouchEnd = createTouchEndCallback(this);

    const timeBarEle = this._timeBarEle;
    ownerDocument.addEventListener("mouseup", this._onMouseUp, false);
    ownerDocument.addEventListener("mousemove", this._onMouseMove, false);
    timeBarEle.addEventListener("mousedown", this._onMouseDown, false);
    timeBarEle.addEventListener("DOMMouseScroll", this._onMouseWheel, false); // Mozilla mouse wheel
    timeBarEle.addEventListener("mousewheel", this._onMouseWheel, false);
    timeBarEle.addEventListener("touchstart", this._onTouchStart, false);
    timeBarEle.addEventListener("touchmove", this._onTouchMove, false);
    timeBarEle.addEventListener("touchend", this._onTouchEnd, false);
    timeBarEle.addEventListener("touchcancel", this._onTouchEnd, false);

    this._topDiv.oncontextmenu = function () {
      return false;
    };

    clock.onTick.addEventListener(this.updateFromClock, this);
    this.updateFromClock();
  }

  /**
   * @private
   */
  Timeline.prototype.addEventListener = function (type, listener, useCapture) {
    this._topDiv.addEventListener(type, listener, useCapture);
  };

  /**
   * @private
   */
  Timeline.prototype.removeEventListener = function (type, listener, useCapture) {
    this._topDiv.removeEventListener(type, listener, useCapture);
  };

  /**
   * @returns {Boolean} true if the object has been destroyed, false otherwise.
   */
  Timeline.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the widget.  Should be called if permanently
   * removing the widget from layout.
   */
  Timeline.prototype.destroy = function () {
    this._clock.onTick.removeEventListener(this.updateFromClock, this);

    const doc = this.container.ownerDocument;
    doc.removeEventListener("mouseup", this._onMouseUp, false);
    doc.removeEventListener("mousemove", this._onMouseMove, false);

    const timeBarEle = this._timeBarEle;
    timeBarEle.removeEventListener("mousedown", this._onMouseDown, false);
    timeBarEle.removeEventListener("DOMMouseScroll", this._onMouseWheel, false); // Mozilla mouse wheel
    timeBarEle.removeEventListener("mousewheel", this._onMouseWheel, false);
    timeBarEle.removeEventListener("touchstart", this._onTouchStart, false);
    timeBarEle.removeEventListener("touchmove", this._onTouchMove, false);
    timeBarEle.removeEventListener("touchend", this._onTouchEnd, false);
    timeBarEle.removeEventListener("touchcancel", this._onTouchEnd, false);
    this.container.removeChild(this._topDiv);
    destroyObject(this);
  };

  /**
   * @private
   */
  Timeline.prototype.addHighlightRange = function (color, heightInPx, base) {
    const newHighlightRange = new TimelineHighlightRange(color, heightInPx, base);
    this._highlightRanges.push(newHighlightRange);
    this.resize();
    return newHighlightRange;
  };

  /**
   * @private
   */
  Timeline.prototype.addTrack = function (
    interval,
    heightInPx,
    color,
    backgroundColor
  ) {
    const newTrack = new TimelineTrack(
      interval,
      heightInPx,
      color,
      backgroundColor
    );
    this._trackList.push(newTrack);
    this._lastHeight = undefined;
    this.resize();
    return newTrack;
  };

  /**
   * Sets the view to the provided times.
   *
   * @param {JulianDate} startTime The start time.
   * @param {JulianDate} stopTime The stop time.
   */
  Timeline.prototype.zoomTo = function (startTime, stopTime) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(startTime)) {
      throw new DeveloperError("startTime is required.");
    }
    if (!defined(stopTime)) {
      throw new DeveloperError("stopTime is required");
    }
    if (JulianDate.lessThanOrEquals(stopTime, startTime)) {
      throw new DeveloperError("Start time must come before end time.");
    }
    //>>includeEnd('debug');

    this._startJulian = startTime;
    this._endJulian = stopTime;
    this._timeBarSecondsSpan = JulianDate.secondsDifference(stopTime, startTime);

    // If clock is not unbounded, clamp timeline range to clock.
    if (this._clock && this._clock.clockRange !== ClockRange$1.UNBOUNDED) {
      const clockStart = this._clock.startTime;
      const clockEnd = this._clock.stopTime;
      const clockSpan = JulianDate.secondsDifference(clockEnd, clockStart);
      const startOffset = JulianDate.secondsDifference(
        clockStart,
        this._startJulian
      );
      const endOffset = JulianDate.secondsDifference(clockEnd, this._endJulian);

      if (this._timeBarSecondsSpan >= clockSpan) {
        // if new duration longer than clock range duration, clamp to full range.
        this._timeBarSecondsSpan = clockSpan;
        this._startJulian = this._clock.startTime;
        this._endJulian = this._clock.stopTime;
      } else if (startOffset > 0) {
        // if timeline start is before clock start, shift right
        this._endJulian = JulianDate.addSeconds(
          this._endJulian,
          startOffset,
          new JulianDate()
        );
        this._startJulian = clockStart;
        this._timeBarSecondsSpan = JulianDate.secondsDifference(
          this._endJulian,
          this._startJulian
        );
      } else if (endOffset < 0) {
        // if timeline end is after clock end, shift left
        this._startJulian = JulianDate.addSeconds(
          this._startJulian,
          endOffset,
          new JulianDate()
        );
        this._endJulian = clockEnd;
        this._timeBarSecondsSpan = JulianDate.secondsDifference(
          this._endJulian,
          this._startJulian
        );
      }
    }

    this._makeTics();

    const evt = document.createEvent("Event");
    evt.initEvent("setzoom", true, true);
    evt.startJulian = this._startJulian;
    evt.endJulian = this._endJulian;
    evt.epochJulian = this._epochJulian;
    evt.totalSpan = this._timeBarSecondsSpan;
    evt.mainTicSpan = this._mainTicSpan;
    this._topDiv.dispatchEvent(evt);
  };

  /**
   * @private
   */
  Timeline.prototype.zoomFrom = function (amount) {
    let centerSec = JulianDate.secondsDifference(
      this._scrubJulian,
      this._startJulian
    );
    if (amount > 1 || centerSec < 0 || centerSec > this._timeBarSecondsSpan) {
      centerSec = this._timeBarSecondsSpan * 0.5;
    } else {
      centerSec += centerSec - this._timeBarSecondsSpan * 0.5;
    }
    const centerSecFlip = this._timeBarSecondsSpan - centerSec;
    this.zoomTo(
      JulianDate.addSeconds(
        this._startJulian,
        centerSec - centerSec * amount,
        new JulianDate()
      ),
      JulianDate.addSeconds(
        this._endJulian,
        centerSecFlip * amount - centerSecFlip,
        new JulianDate()
      )
    );
  };

  function twoDigits(num) {
    return num < 10 ? `0${num.toString()}` : num.toString();
  }

  /**
   * @private
   */
  Timeline.prototype.makeLabel = function (time) {
    const gregorian = JulianDate.toGregorianDate(time);
    const millisecond = gregorian.millisecond;
    let millisecondString = " UTC";
    if (millisecond > 0 && this._timeBarSecondsSpan < 3600) {
      millisecondString = Math.floor(millisecond).toString();
      while (millisecondString.length < 3) {
        millisecondString = `0${millisecondString}`;
      }
      millisecondString = `.${millisecondString}`;
    }

    return `${timelineMonthNames[gregorian.month - 1]} ${gregorian.day} ${
    gregorian.year
  } ${twoDigits(gregorian.hour)}:${twoDigits(gregorian.minute)}:${twoDigits(
    gregorian.second
  )}${millisecondString}`;
  };

  /**
   * @private
   */
  Timeline.prototype.smallestTicInPixels = 7.0;

  /**
   * @private
   */
  Timeline.prototype._makeTics = function () {
    const timeBar = this._timeBarEle;

    const seconds = JulianDate.secondsDifference(
      this._scrubJulian,
      this._startJulian
    );
    const xPos = Math.round(
      (seconds * this._topDiv.clientWidth) / this._timeBarSecondsSpan
    );
    const scrubX = xPos - 8;
    let tic;
    const widget = this;

    this._needleEle.style.left = `${xPos.toString()}px`;

    let tics = "";

    const minimumDuration = 0.01;
    const maximumDuration = 31536000000.0; // ~1000 years
    const epsilon = 1e-10;

    // If time step size is known, enter it here...
    let minSize = 0;

    let duration = this._timeBarSecondsSpan;
    if (duration < minimumDuration) {
      duration = minimumDuration;
      this._timeBarSecondsSpan = minimumDuration;
      this._endJulian = JulianDate.addSeconds(
        this._startJulian,
        minimumDuration,
        new JulianDate()
      );
    } else if (duration > maximumDuration) {
      duration = maximumDuration;
      this._timeBarSecondsSpan = maximumDuration;
      this._endJulian = JulianDate.addSeconds(
        this._startJulian,
        maximumDuration,
        new JulianDate()
      );
    }

    let timeBarWidth = this._timeBarEle.clientWidth;
    if (timeBarWidth < 10) {
      timeBarWidth = 10;
    }
    const startJulian = this._startJulian;

    // epsilonTime: a small fraction of one pixel width of the timeline, measured in seconds.
    const epsilonTime = Math.min((duration / timeBarWidth) * 1e-5, 0.4);

    // epochJulian: a nearby time to be considered "zero seconds", should be a round-ish number by human standards.
    let epochJulian;
    const gregorianDate = JulianDate.toGregorianDate(startJulian);
    if (duration > 315360000) {
      // 3650+ days visible, epoch is start of the first visible century.
      epochJulian = JulianDate.fromDate(
        new Date(Date.UTC(Math.floor(gregorianDate.year / 100) * 100, 0))
      );
    } else if (duration > 31536000) {
      // 365+ days visible, epoch is start of the first visible decade.
      epochJulian = JulianDate.fromDate(
        new Date(Date.UTC(Math.floor(gregorianDate.year / 10) * 10, 0))
      );
    } else if (duration > 86400) {
      // 1+ day(s) visible, epoch is start of the year.
      epochJulian = JulianDate.fromDate(
        new Date(Date.UTC(gregorianDate.year, 0))
      );
    } else {
      // Less than a day on timeline, epoch is midnight of the visible day.
      epochJulian = JulianDate.fromDate(
        new Date(
          Date.UTC(gregorianDate.year, gregorianDate.month, gregorianDate.day)
        )
      );
    }

    // startTime: Seconds offset of the left side of the timeline from epochJulian.
    const startTime = JulianDate.secondsDifference(
      this._startJulian,
      JulianDate.addSeconds(epochJulian, epsilonTime, new JulianDate())
    );
    // endTime: Seconds offset of the right side of the timeline from epochJulian.
    let endTime = startTime + duration;
    this._epochJulian = epochJulian;

    function getStartTic(ticScale) {
      return Math.floor(startTime / ticScale) * ticScale;
    }

    function getNextTic(tic, ticScale) {
      return Math.ceil(tic / ticScale + 0.5) * ticScale;
    }

    function getAlpha(time) {
      return (time - startTime) / duration;
    }

    function remainder(x, y) {
      //return x % y;
      return x - y * Math.round(x / y);
    }

    // Width in pixels of a typical label, plus padding
    this._rulerEle.innerHTML = this.makeLabel(
      JulianDate.addSeconds(this._endJulian, -minimumDuration, new JulianDate())
    );
    let sampleWidth = this._rulerEle.offsetWidth + 20;
    if (sampleWidth < 30) {
      // Workaround an apparent IE bug with measuring the width after going full-screen from inside an iframe.
      sampleWidth = 180;
    }

    const origMinSize = minSize;
    minSize -= epsilon;

    const renderState = {
      startTime: startTime,
      startJulian: startJulian,
      epochJulian: epochJulian,
      duration: duration,
      timeBarWidth: timeBarWidth,
      getAlpha: getAlpha,
    };
    this._highlightRanges.forEach(function (highlightRange) {
      tics += highlightRange.render(renderState);
    });

    // Calculate tic mark label spacing in the TimeBar.
    let mainTic = 0.0,
      subTic = 0.0,
      tinyTic = 0.0;
    // Ideal labeled tic as percentage of zoom interval
    let idealTic = sampleWidth / timeBarWidth;
    if (idealTic > 1.0) {
      // Clamp to width of window, for thin windows.
      idealTic = 1.0;
    }
    // Ideal labeled tic size in seconds
    idealTic *= this._timeBarSecondsSpan;
    let ticIndex = -1,
      smallestIndex = -1;

    const ticScaleLen = timelineTicScales.length;
    let i;
    for (i = 0; i < ticScaleLen; ++i) {
      const sc = timelineTicScales[i];
      ++ticIndex;
      mainTic = sc;
      // Find acceptable main tic size not smaller than ideal size.
      if (sc > idealTic && sc > minSize) {
        break;
      }
      if (
        smallestIndex < 0 &&
        timeBarWidth * (sc / this._timeBarSecondsSpan) >= this.smallestTicInPixels
      ) {
        smallestIndex = ticIndex;
      }
    }
    if (ticIndex > 0) {
      while (ticIndex > 0) {
        // Compute sub-tic size that evenly divides main tic.
        --ticIndex;
        if (Math.abs(remainder(mainTic, timelineTicScales[ticIndex])) < 0.00001) {
          if (timelineTicScales[ticIndex] >= minSize) {
            subTic = timelineTicScales[ticIndex];
          }
          break;
        }
      }

      if (smallestIndex >= 0) {
        while (smallestIndex < ticIndex) {
          // Compute tiny tic size that evenly divides sub-tic.
          if (
            Math.abs(remainder(subTic, timelineTicScales[smallestIndex])) <
              0.00001 &&
            timelineTicScales[smallestIndex] >= minSize
          ) {
            tinyTic = timelineTicScales[smallestIndex];
            break;
          }
          ++smallestIndex;
        }
      }
    }

    minSize = origMinSize;
    if (
      minSize > epsilon &&
      tinyTic < 0.00001 &&
      Math.abs(minSize - mainTic) > epsilon
    ) {
      tinyTic = minSize;
      if (minSize <= mainTic + epsilon) {
        subTic = 0.0;
      }
    }

    let lastTextLeft = -999999,
      textWidth;
    if (timeBarWidth * (tinyTic / this._timeBarSecondsSpan) >= 3.0) {
      for (
        tic = getStartTic(tinyTic);
        tic <= endTime;
        tic = getNextTic(tic, tinyTic)
      ) {
        tics += `<span class="cesium-timeline-ticTiny" style="left: ${Math.round(
        timeBarWidth * getAlpha(tic)
      ).toString()}px;"></span>`;
      }
    }
    if (timeBarWidth * (subTic / this._timeBarSecondsSpan) >= 3.0) {
      for (
        tic = getStartTic(subTic);
        tic <= endTime;
        tic = getNextTic(tic, subTic)
      ) {
        tics += `<span class="cesium-timeline-ticSub" style="left: ${Math.round(
        timeBarWidth * getAlpha(tic)
      ).toString()}px;"></span>`;
      }
    }
    if (timeBarWidth * (mainTic / this._timeBarSecondsSpan) >= 2.0) {
      this._mainTicSpan = mainTic;
      endTime += mainTic;
      tic = getStartTic(mainTic);
      const leapSecond = JulianDate.computeTaiMinusUtc(epochJulian);
      while (tic <= endTime) {
        let ticTime = JulianDate.addSeconds(
          startJulian,
          tic - startTime,
          new JulianDate()
        );
        if (mainTic > 2.1) {
          const ticLeap = JulianDate.computeTaiMinusUtc(ticTime);
          if (Math.abs(ticLeap - leapSecond) > 0.1) {
            tic += ticLeap - leapSecond;
            ticTime = JulianDate.addSeconds(
              startJulian,
              tic - startTime,
              new JulianDate()
            );
          }
        }
        const ticLeft = Math.round(timeBarWidth * getAlpha(tic));
        const ticLabel = this.makeLabel(ticTime);
        this._rulerEle.innerHTML = ticLabel;
        textWidth = this._rulerEle.offsetWidth;
        if (textWidth < 10) {
          // IE iframe fullscreen sampleWidth workaround, continued.
          textWidth = sampleWidth;
        }
        const labelLeft = ticLeft - (textWidth / 2 - 1);
        if (labelLeft > lastTextLeft) {
          lastTextLeft = labelLeft + textWidth + 5;
          tics +=
            `<span class="cesium-timeline-ticMain" style="left: ${ticLeft.toString()}px;"></span>` +
            `<span class="cesium-timeline-ticLabel" style="left: ${labelLeft.toString()}px;">${ticLabel}</span>`;
        } else {
          tics += `<span class="cesium-timeline-ticSub" style="left: ${ticLeft.toString()}px;"></span>`;
        }
        tic = getNextTic(tic, mainTic);
      }
    } else {
      this._mainTicSpan = -1;
    }

    tics += `<span class="cesium-timeline-icon16" style="left:${scrubX}px;bottom:0;background-position: 0 0;"></span>`;
    timeBar.innerHTML = tics;
    this._scrubElement = timeBar.lastChild;

    // Clear track canvas.
    this._context.clearRect(
      0,
      0,
      this._trackListEle.width,
      this._trackListEle.height
    );

    renderState.y = 0;
    this._trackList.forEach(function (track) {
      track.render(widget._context, renderState);
      renderState.y += track.height;
    });
  };

  /**
   * @private
   */
  Timeline.prototype.updateFromClock = function () {
    this._scrubJulian = this._clock.currentTime;
    const scrubElement = this._scrubElement;
    if (defined(this._scrubElement)) {
      const seconds = JulianDate.secondsDifference(
        this._scrubJulian,
        this._startJulian
      );
      const xPos = Math.round(
        (seconds * this._topDiv.clientWidth) / this._timeBarSecondsSpan
      );

      if (this._lastXPos !== xPos) {
        this._lastXPos = xPos;

        scrubElement.style.left = `${xPos - 8}px`;
        this._needleEle.style.left = `${xPos}px`;
      }
    }
    if (defined(this._timelineDragLocation)) {
      this._setTimeBarTime(
        this._timelineDragLocation,
        (this._timelineDragLocation * this._timeBarSecondsSpan) /
          this._topDiv.clientWidth
      );
      this.zoomTo(
        JulianDate.addSeconds(
          this._startJulian,
          this._timelineDrag,
          new JulianDate()
        ),
        JulianDate.addSeconds(
          this._endJulian,
          this._timelineDrag,
          new JulianDate()
        )
      );
    }
  };

  /**
   * @private
   */
  Timeline.prototype._setTimeBarTime = function (xPos, seconds) {
    xPos = Math.round(xPos);
    this._scrubJulian = JulianDate.addSeconds(
      this._startJulian,
      seconds,
      new JulianDate()
    );
    if (this._scrubElement) {
      const scrubX = xPos - 8;
      this._scrubElement.style.left = `${scrubX.toString()}px`;
      this._needleEle.style.left = `${xPos.toString()}px`;
    }

    const evt = document.createEvent("Event");
    evt.initEvent("settime", true, true);
    evt.clientX = xPos;
    evt.timeSeconds = seconds;
    evt.timeJulian = this._scrubJulian;
    evt.clock = this._clock;
    this._topDiv.dispatchEvent(evt);
  };

  function createMouseDownCallback(timeline) {
    return function (e) {
      if (timeline._mouseMode !== timelineMouseMode.touchOnly) {
        if (e.button === 0) {
          timeline._mouseMode = timelineMouseMode.scrub;
          if (timeline._scrubElement) {
            timeline._scrubElement.style.backgroundPosition = "-16px 0";
          }
          timeline._onMouseMove(e);
        } else {
          timeline._mouseX = e.clientX;
          if (e.button === 2) {
            timeline._mouseMode = timelineMouseMode.zoom;
          } else {
            timeline._mouseMode = timelineMouseMode.slide;
          }
        }
      }
      e.preventDefault();
    };
  }

  function createMouseUpCallback(timeline) {
    return function (e) {
      timeline._mouseMode = timelineMouseMode.none;
      if (timeline._scrubElement) {
        timeline._scrubElement.style.backgroundPosition = "0 0";
      }
      timeline._timelineDrag = 0;
      timeline._timelineDragLocation = undefined;
    };
  }

  function createMouseMoveCallback(timeline) {
    return function (e) {
      let dx;
      if (timeline._mouseMode === timelineMouseMode.scrub) {
        e.preventDefault();
        const x = e.clientX - timeline._topDiv.getBoundingClientRect().left;

        if (x < 0) {
          timeline._timelineDragLocation = 0;
          timeline._timelineDrag = -0.01 * timeline._timeBarSecondsSpan;
        } else if (x > timeline._topDiv.clientWidth) {
          timeline._timelineDragLocation = timeline._topDiv.clientWidth;
          timeline._timelineDrag = 0.01 * timeline._timeBarSecondsSpan;
        } else {
          timeline._timelineDragLocation = undefined;
          timeline._setTimeBarTime(
            x,
            (x * timeline._timeBarSecondsSpan) / timeline._topDiv.clientWidth
          );
        }
      } else if (timeline._mouseMode === timelineMouseMode.slide) {
        dx = timeline._mouseX - e.clientX;
        timeline._mouseX = e.clientX;
        if (dx !== 0) {
          const dsec =
            (dx * timeline._timeBarSecondsSpan) / timeline._topDiv.clientWidth;
          timeline.zoomTo(
            JulianDate.addSeconds(timeline._startJulian, dsec, new JulianDate()),
            JulianDate.addSeconds(timeline._endJulian, dsec, new JulianDate())
          );
        }
      } else if (timeline._mouseMode === timelineMouseMode.zoom) {
        dx = timeline._mouseX - e.clientX;
        timeline._mouseX = e.clientX;
        if (dx !== 0) {
          timeline.zoomFrom(Math.pow(1.01, dx));
        }
      }
    };
  }

  function createMouseWheelCallback(timeline) {
    return function (e) {
      let dy = e.wheelDeltaY || e.wheelDelta || -e.detail;
      timelineWheelDelta = Math.max(
        Math.min(Math.abs(dy), timelineWheelDelta),
        1
      );
      dy /= timelineWheelDelta;
      timeline.zoomFrom(Math.pow(1.05, -dy));
    };
  }

  function createTouchStartCallback(timeline) {
    return function (e) {
      const len = e.touches.length;
      let seconds, xPos;
      const leftX = timeline._topDiv.getBoundingClientRect().left;
      e.preventDefault();
      timeline._mouseMode = timelineMouseMode.touchOnly;
      if (len === 1) {
        seconds = JulianDate.secondsDifference(
          timeline._scrubJulian,
          timeline._startJulian
        );
        xPos = Math.round(
          (seconds * timeline._topDiv.clientWidth) /
            timeline._timeBarSecondsSpan +
            leftX
        );
        if (Math.abs(e.touches[0].clientX - xPos) < 50) {
          timeline._touchMode = timelineTouchMode.scrub;
          if (timeline._scrubElement) {
            timeline._scrubElement.style.backgroundPosition =
              len === 1 ? "-16px 0" : "0 0";
          }
        } else {
          timeline._touchMode = timelineTouchMode.singleTap;
          timeline._touchState.centerX = e.touches[0].clientX - leftX;
        }
      } else if (len === 2) {
        timeline._touchMode = timelineTouchMode.slideZoom;
        timeline._touchState.centerX =
          (e.touches[0].clientX + e.touches[1].clientX) * 0.5 - leftX;
        timeline._touchState.spanX = Math.abs(
          e.touches[0].clientX - e.touches[1].clientX
        );
      } else {
        timeline._touchMode = timelineTouchMode.ignore;
      }
    };
  }

  function createTouchEndCallback(timeline) {
    return function (e) {
      const len = e.touches.length,
        leftX = timeline._topDiv.getBoundingClientRect().left;
      if (timeline._touchMode === timelineTouchMode.singleTap) {
        timeline._touchMode = timelineTouchMode.scrub;
        timeline._onTouchMove(e);
      } else if (timeline._touchMode === timelineTouchMode.scrub) {
        timeline._onTouchMove(e);
      }
      timeline._mouseMode = timelineMouseMode.touchOnly;
      if (len !== 1) {
        timeline._touchMode =
          len > 0 ? timelineTouchMode.ignore : timelineTouchMode.none;
      } else if (timeline._touchMode === timelineTouchMode.slideZoom) {
        timeline._touchState.centerX = e.touches[0].clientX - leftX;
      }
      if (timeline._scrubElement) {
        timeline._scrubElement.style.backgroundPosition = "0 0";
      }
    };
  }

  function createTouchMoveCallback(timeline) {
    return function (e) {
      let dx,
        x,
        len,
        newCenter,
        newSpan,
        newStartTime,
        zoom = 1;
      const leftX = timeline._topDiv.getBoundingClientRect().left;
      if (timeline._touchMode === timelineTouchMode.singleTap) {
        timeline._touchMode = timelineTouchMode.slideZoom;
      }
      timeline._mouseMode = timelineMouseMode.touchOnly;
      if (timeline._touchMode === timelineTouchMode.scrub) {
        e.preventDefault();
        if (e.changedTouches.length === 1) {
          x = e.changedTouches[0].clientX - leftX;
          if (x >= 0 && x <= timeline._topDiv.clientWidth) {
            timeline._setTimeBarTime(
              x,
              (x * timeline._timeBarSecondsSpan) / timeline._topDiv.clientWidth
            );
          }
        }
      } else if (timeline._touchMode === timelineTouchMode.slideZoom) {
        len = e.touches.length;
        if (len === 2) {
          newCenter = (e.touches[0].clientX + e.touches[1].clientX) * 0.5 - leftX;
          newSpan = Math.abs(e.touches[0].clientX - e.touches[1].clientX);
        } else if (len === 1) {
          newCenter = e.touches[0].clientX - leftX;
          newSpan = 0;
        }

        if (defined(newCenter)) {
          if (newSpan > 0 && timeline._touchState.spanX > 0) {
            // Zoom and slide
            zoom = timeline._touchState.spanX / newSpan;
            newStartTime = JulianDate.addSeconds(
              timeline._startJulian,
              (timeline._touchState.centerX * timeline._timeBarSecondsSpan -
                newCenter * timeline._timeBarSecondsSpan * zoom) /
                timeline._topDiv.clientWidth,
              new JulianDate()
            );
          } else {
            // Slide to newCenter
            dx = timeline._touchState.centerX - newCenter;
            newStartTime = JulianDate.addSeconds(
              timeline._startJulian,
              (dx * timeline._timeBarSecondsSpan) / timeline._topDiv.clientWidth,
              new JulianDate()
            );
          }

          timeline.zoomTo(
            newStartTime,
            JulianDate.addSeconds(
              newStartTime,
              timeline._timeBarSecondsSpan * zoom,
              new JulianDate()
            )
          );
          timeline._touchState.centerX = newCenter;
          timeline._touchState.spanX = newSpan;
        }
      }
    };
  }

  /**
   * Resizes the widget to match the container size.
   */
  Timeline.prototype.resize = function () {
    const width = this.container.clientWidth;
    const height = this.container.clientHeight;

    if (width === this._lastWidth && height === this._lastHeight) {
      return;
    }

    this._trackContainer.style.height = `${height}px`;

    let trackListHeight = 1;
    this._trackList.forEach(function (track) {
      trackListHeight += track.height;
    });
    this._trackListEle.style.height = `${trackListHeight.toString()}px`;
    this._trackListEle.width = this._trackListEle.clientWidth;
    this._trackListEle.height = trackListHeight;
    this._makeTics();

    this._lastXPos = undefined;
    this._lastWidth = width;
    this._lastHeight = height;
  };

  function lockScreen(orientation) {
    let locked = false;
    const screen = window.screen;
    if (defined(screen)) {
      if (defined(screen.lockOrientation)) {
        locked = screen.lockOrientation(orientation);
      } else if (defined(screen.mozLockOrientation)) {
        locked = screen.mozLockOrientation(orientation);
      } else if (defined(screen.msLockOrientation)) {
        locked = screen.msLockOrientation(orientation);
      } else if (defined(screen.orientation && screen.orientation.lock)) {
        locked = screen.orientation.lock(orientation);
      }
    }
    return locked;
  }

  function unlockScreen() {
    const screen = window.screen;
    if (defined(screen)) {
      if (defined(screen.unlockOrientation)) {
        screen.unlockOrientation();
      } else if (defined(screen.mozUnlockOrientation)) {
        screen.mozUnlockOrientation();
      } else if (defined(screen.msUnlockOrientation)) {
        screen.msUnlockOrientation();
      } else if (defined(screen.orientation && screen.orientation.unlock)) {
        screen.orientation.unlock();
      }
    }
  }

  function toggleVR(viewModel, scene, isVRMode, isOrthographic) {
    if (isOrthographic()) {
      return;
    }

    if (isVRMode()) {
      scene.useWebVR = false;
      if (viewModel._locked) {
        unlockScreen();
        viewModel._locked = false;
      }
      viewModel._noSleep.disable();
      Fullscreen.exitFullscreen();
      isVRMode(false);
    } else {
      if (!Fullscreen.fullscreen) {
        Fullscreen.requestFullscreen(viewModel._vrElement);
      }
      viewModel._noSleep.enable();
      if (!viewModel._locked) {
        viewModel._locked = lockScreen("landscape");
      }
      scene.useWebVR = true;
      isVRMode(true);
    }
  }

  /**
   * The view model for {@link VRButton}.
   * @alias VRButtonViewModel
   * @constructor
   *
   * @param {Scene} scene The scene.
   * @param {Element|String} [vrElement=document.body] The element or id to be placed into VR mode.
   */
  function VRButtonViewModel(scene, vrElement) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(scene)) {
      throw new DeveloperError("scene is required.");
    }
    //>>includeEnd('debug');

    const that = this;

    const isEnabled = knockout.observable(Fullscreen.enabled);
    const isVRMode = knockout.observable(false);

    /**
     * Gets whether or not VR mode is active.
     *
     * @type {Boolean}
     */
    this.isVRMode = undefined;
    knockout.defineProperty(this, "isVRMode", {
      get: function () {
        return isVRMode();
      },
    });

    /**
     * Gets or sets whether or not VR functionality should be enabled.
     *
     * @type {Boolean}
     * @see Fullscreen.enabled
     */
    this.isVREnabled = undefined;
    knockout.defineProperty(this, "isVREnabled", {
      get: function () {
        return isEnabled();
      },
      set: function (value) {
        isEnabled(value && Fullscreen.enabled);
      },
    });

    /**
     * Gets the tooltip.  This property is observable.
     *
     * @type {String}
     */
    this.tooltip = undefined;
    knockout.defineProperty(this, "tooltip", function () {
      if (!isEnabled()) {
        return "VR mode is unavailable";
      }
      return isVRMode() ? "Exit VR mode" : "Enter VR mode";
    });

    const isOrthographic = knockout.observable(false);

    this._isOrthographic = undefined;
    knockout.defineProperty(this, "_isOrthographic", {
      get: function () {
        return isOrthographic();
      },
    });

    this._eventHelper = new EventHelper();
    this._eventHelper.add(scene.preRender, function () {
      isOrthographic(scene.camera.frustum instanceof OrthographicFrustum);
    });

    this._locked = false;
    this._noSleep = new src();

    this._command = createCommand(function () {
      toggleVR(that, scene, isVRMode, isOrthographic);
    }, knockout.getObservable(this, "isVREnabled"));

    this._vrElement = defaultValue(getElement(vrElement), document.body);

    this._callback = function () {
      if (!Fullscreen.fullscreen && isVRMode()) {
        scene.useWebVR = false;
        if (that._locked) {
          unlockScreen();
          that._locked = false;
        }
        that._noSleep.disable();
        isVRMode(false);
      }
    };
    document.addEventListener(Fullscreen.changeEventName, this._callback);
  }

  Object.defineProperties(VRButtonViewModel.prototype, {
    /**
     * Gets or sets the HTML element to place into VR mode when the
     * corresponding button is pressed.
     * @memberof VRButtonViewModel.prototype
     *
     * @type {Element}
     */
    vrElement: {
      //TODO:@exception {DeveloperError} value must be a valid HTML Element.
      get: function () {
        return this._vrElement;
      },
      set: function (value) {
        //>>includeStart('debug', pragmas.debug);
        if (!(value instanceof Element)) {
          throw new DeveloperError("value must be a valid Element.");
        }
        //>>includeEnd('debug');

        this._vrElement = value;
      },
    },

    /**
     * Gets the Command to toggle VR mode.
     * @memberof VRButtonViewModel.prototype
     *
     * @type {Command}
     */
    command: {
      get: function () {
        return this._command;
      },
    },
  });

  /**
   * @returns {Boolean} true if the object has been destroyed, false otherwise.
   */
  VRButtonViewModel.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the view model.  Should be called to
   * properly clean up the view model when it is no longer needed.
   */
  VRButtonViewModel.prototype.destroy = function () {
    this._eventHelper.removeAll();
    document.removeEventListener(Fullscreen.changeEventName, this._callback);
    destroyObject(this);
  };

  const enterVRPath =
    "M 5.3125 6.375 C 4.008126 6.375 2.96875 7.4141499 2.96875 8.71875 L 2.96875 19.5 C 2.96875 20.8043 4.008126 21.875 5.3125 21.875 L 13.65625 21.875 C 13.71832 20.0547 14.845166 18.59375 16.21875 18.59375 C 17.592088 18.59375 18.71881 20.0552 18.78125 21.875 L 27.09375 21.875 C 28.398125 21.875 29.4375 20.8043 29.4375 19.5 L 29.4375 8.71875 C 29.4375 7.4141499 28.398125 6.375 27.09375 6.375 L 5.3125 6.375 z M 9.625 10.4375 C 11.55989 10.4375 13.125 12.03385 13.125 13.96875 C 13.125 15.90365 11.55989 17.46875 9.625 17.46875 C 7.69011 17.46875 6.125 15.90365 6.125 13.96875 C 6.125 12.03385 7.69011 10.4375 9.625 10.4375 z M 22.46875 10.4375 C 24.40364 10.4375 25.96875 12.03385 25.96875 13.96875 C 25.96875 15.90365 24.40364 17.46875 22.46875 17.46875 C 20.53386 17.46875 18.96875 15.90365 18.96875 13.96875 C 18.96875 12.03385 20.53386 10.4375 22.46875 10.4375 z";
  const exitVRPath =
    "M 25.770585,2.4552065 C 15.72282,13.962707 10.699956,19.704407 8.1768352,22.580207 c -1.261561,1.4379 -1.902282,2.1427 -2.21875,2.5 -0.141624,0.1599 -0.208984,0.2355 -0.25,0.2813 l 0.6875,0.75 c 10e-5,-10e-5 0.679191,0.727 0.6875,0.7187 0.01662,-0.016 0.02451,-0.024 0.03125,-0.031 0.01348,-0.014 0.04013,-0.038 0.0625,-0.062 0.04474,-0.05 0.120921,-0.1315 0.28125,-0.3126 0.320657,-0.3619 0.956139,-1.0921 2.2187499,-2.5312 2.5252219,-2.8781 7.5454589,-8.6169 17.5937499,-20.1250005 l -1.5,-1.3125 z m -20.5624998,3.9063 c -1.304375,0 -2.34375,1.0391 -2.34375,2.3437 l 0,10.8125005 c 0,1.3043 1.039375,2.375 2.34375,2.375 l 2.25,0 c 1.9518039,-2.2246 7.4710958,-8.5584 13.5624998,-15.5312005 l -15.8124998,0 z m 21.1249998,0 c -1.855467,2.1245 -2.114296,2.4005 -3.59375,4.0936995 1.767282,0.1815 3.15625,1.685301 3.15625,3.500001 0,1.9349 -1.56511,3.5 -3.5,3.5 -1.658043,0 -3.043426,-1.1411 -3.40625,-2.6875 -1.089617,1.2461 -2.647139,2.9988 -3.46875,3.9375 0.191501,-0.062 0.388502,-0.094 0.59375,-0.094 1.373338,0 2.50006,1.4614 2.5625,3.2812 l 8.3125,0 c 1.304375,0 2.34375,-1.0707 2.34375,-2.375 l 0,-10.8125005 c 0,-1.3046 -1.039375,-2.3437 -2.34375,-2.3437 l -0.65625,0 z M 9.5518351,10.423906 c 1.9348899,0 3.4999999,1.596401 3.4999999,3.531301 0,1.9349 -1.56511,3.5 -3.4999999,3.5 -1.9348899,0 -3.4999999,-1.5651 -3.4999999,-3.5 0,-1.9349 1.56511,-3.531301 3.4999999,-3.531301 z m 4.2187499,10.312601 c -0.206517,0.2356 -0.844218,0.9428 -1.03125,1.1562 l 0.8125,0 c 0.01392,-0.4081 0.107026,-0.7968 0.21875,-1.1562 z";

  /**
   * A single button widget for toggling vr mode.
   *
   * @alias VRButton
   * @constructor
   *
   * @param {Element|String} container The DOM element or ID that will contain the widget.
   * @param {Scene} scene The scene.
   * @param {Element|String} [vrElement=document.body] The element or id to be placed into vr mode.
   *
   * @exception {DeveloperError} Element with id "container" does not exist in the document.
   */
  function VRButton(container, scene, vrElement) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(container)) {
      throw new DeveloperError("container is required.");
    }
    if (!defined(scene)) {
      throw new DeveloperError("scene is required.");
    }
    //>>includeEnd('debug');

    container = getElement(container);

    const viewModel = new VRButtonViewModel(scene, vrElement);

    viewModel._exitVRPath = exitVRPath;
    viewModel._enterVRPath = enterVRPath;

    const element = document.createElement("button");
    element.type = "button";
    element.className = "cesium-button cesium-vrButton";
    element.setAttribute(
      "data-bind",
      '\
css: { "cesium-button-disabled" : _isOrthographic }, \
attr: { title: tooltip },\
click: command,\
enable: isVREnabled,\
cesiumSvgPath: { path: isVRMode ? _exitVRPath : _enterVRPath, width: 32, height: 32 }'
    );

    container.appendChild(element);

    knockout.applyBindings(viewModel, element);

    this._container = container;
    this._viewModel = viewModel;
    this._element = element;
  }

  Object.defineProperties(VRButton.prototype, {
    /**
     * Gets the parent container.
     * @memberof VRButton.prototype
     *
     * @type {Element}
     */
    container: {
      get: function () {
        return this._container;
      },
    },

    /**
     * Gets the view model.
     * @memberof VRButton.prototype
     *
     * @type {VRButtonViewModel}
     */
    viewModel: {
      get: function () {
        return this._viewModel;
      },
    },
  });

  /**
   * @returns {Boolean} true if the object has been destroyed, false otherwise.
   */
  VRButton.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the widget.  Should be called if permanently
   * removing the widget from layout.
   */
  VRButton.prototype.destroy = function () {
    this._viewModel.destroy();

    knockout.cleanNode(this._element);
    this._container.removeChild(this._element);

    return destroyObject(this);
  };

  const boundingSphereScratch = new BoundingSphere();

  function onTimelineScrubfunction(e) {
    const clock = e.clock;
    clock.currentTime = e.timeJulian;
    clock.shouldAnimate = false;
  }

  function getCesium3DTileFeatureDescription(feature) {
    const propertyIds = feature.getPropertyIds();

    let html = "";
    propertyIds.forEach(function (propertyId) {
      const value = feature.getProperty(propertyId);
      if (defined(value)) {
        html += `<tr><th>${propertyId}</th><td>${value}</td></tr>`;
      }
    });

    if (html.length > 0) {
      html = `<table class="cesium-infoBox-defaultTable"><tbody>${html}</tbody></table>`;
    }

    return html;
  }

  function getCesium3DTileFeatureName(feature) {
    // We need to iterate all property IDs to find potential
    // candidates, but since we prefer some property IDs
    // over others, we store them in an indexed array
    // and then use the first defined element in the array
    // as the preferred choice.

    let i;
    const possibleIds = [];
    const propertyIds = feature.getPropertyIds();
    for (i = 0; i < propertyIds.length; i++) {
      const propertyId = propertyIds[i];
      if (/^name$/i.test(propertyId)) {
        possibleIds[0] = feature.getProperty(propertyId);
      } else if (/name/i.test(propertyId)) {
        possibleIds[1] = feature.getProperty(propertyId);
      } else if (/^title$/i.test(propertyId)) {
        possibleIds[2] = feature.getProperty(propertyId);
      } else if (/^(id|identifier)$/i.test(propertyId)) {
        possibleIds[3] = feature.getProperty(propertyId);
      } else if (/element/i.test(propertyId)) {
        possibleIds[4] = feature.getProperty(propertyId);
      } else if (/(id|identifier)$/i.test(propertyId)) {
        possibleIds[5] = feature.getProperty(propertyId);
      }
    }

    const length = possibleIds.length;
    for (i = 0; i < length; i++) {
      const item = possibleIds[i];
      if (defined(item) && item !== "") {
        return item;
      }
    }
    return "Unnamed Feature";
  }

  function pickEntity(viewer, e) {
    const picked = viewer.scene.pick(e.position);
    if (defined(picked)) {
      const id = defaultValue(picked.id, picked.primitive.id);
      if (id instanceof Entity) {
        return id;
      }

      if (picked instanceof Cesium3DTileFeature) {
        return new Entity({
          name: getCesium3DTileFeatureName(picked),
          description: getCesium3DTileFeatureDescription(picked),
          feature: picked,
        });
      }
    }

    // No regular entity picked.  Try picking features from imagery layers.
    if (defined(viewer.scene.globe)) {
      return pickImageryLayerFeature(viewer, e.position);
    }
  }

  const scratchStopTime = new JulianDate();

  function trackDataSourceClock(timeline, clock, dataSource) {
    if (defined(dataSource)) {
      const dataSourceClock = dataSource.clock;
      if (defined(dataSourceClock)) {
        dataSourceClock.getValue(clock);
        if (defined(timeline)) {
          const startTime = dataSourceClock.startTime;
          let stopTime = dataSourceClock.stopTime;
          // When the start and stop times are equal, set the timeline to the shortest interval
          // starting at the start time. This prevents an invalid timeline configuration.
          if (JulianDate.equals(startTime, stopTime)) {
            stopTime = JulianDate.addSeconds(
              startTime,
              CesiumMath.EPSILON2,
              scratchStopTime
            );
          }
          timeline.updateFromClock();
          timeline.zoomTo(startTime, stopTime);
        }
      }
    }
  }

  const cartesian3Scratch = new Cartesian3();

  function pickImageryLayerFeature(viewer, windowPosition) {
    const scene = viewer.scene;
    const pickRay = scene.camera.getPickRay(windowPosition);
    const imageryLayerFeaturePromise = scene.imageryLayers.pickImageryLayerFeatures(
      pickRay,
      scene
    );
    if (!defined(imageryLayerFeaturePromise)) {
      return;
    }

    // Imagery layer feature picking is asynchronous, so put up a message while loading.
    const loadingMessage = new Entity({
      id: "Loading...",
      description: "Loading feature information...",
    });

    imageryLayerFeaturePromise.then(
      function (features) {
        // Has this async pick been superseded by a later one?
        if (viewer.selectedEntity !== loadingMessage) {
          return;
        }

        if (!defined(features) || features.length === 0) {
          viewer.selectedEntity = createNoFeaturesEntity();
          return;
        }

        // Select the first feature.
        const feature = features[0];

        const entity = new Entity({
          id: feature.name,
          description: feature.description,
        });

        if (defined(feature.position)) {
          const ecfPosition = viewer.scene.globe.ellipsoid.cartographicToCartesian(
            feature.position,
            cartesian3Scratch
          );
          entity.position = new ConstantPositionProperty(ecfPosition);
        }

        viewer.selectedEntity = entity;
      },
      function () {
        // Has this async pick been superseded by a later one?
        if (viewer.selectedEntity !== loadingMessage) {
          return;
        }
        viewer.selectedEntity = createNoFeaturesEntity();
      }
    );

    return loadingMessage;
  }

  function createNoFeaturesEntity() {
    return new Entity({
      id: "None",
      description: "No features found.",
    });
  }

  function enableVRUI(viewer, enabled) {
    const geocoder = viewer._geocoder;
    const homeButton = viewer._homeButton;
    const sceneModePicker = viewer._sceneModePicker;
    const projectionPicker = viewer._projectionPicker;
    const baseLayerPicker = viewer._baseLayerPicker;
    const animation = viewer._animation;
    const timeline = viewer._timeline;
    const fullscreenButton = viewer._fullscreenButton;
    const infoBox = viewer._infoBox;
    const selectionIndicator = viewer._selectionIndicator;

    const visibility = enabled ? "hidden" : "visible";

    if (defined(geocoder)) {
      geocoder.container.style.visibility = visibility;
    }
    if (defined(homeButton)) {
      homeButton.container.style.visibility = visibility;
    }
    if (defined(sceneModePicker)) {
      sceneModePicker.container.style.visibility = visibility;
    }
    if (defined(projectionPicker)) {
      projectionPicker.container.style.visibility = visibility;
    }
    if (defined(baseLayerPicker)) {
      baseLayerPicker.container.style.visibility = visibility;
    }
    if (defined(animation)) {
      animation.container.style.visibility = visibility;
    }
    if (defined(timeline)) {
      timeline.container.style.visibility = visibility;
    }
    if (
      defined(fullscreenButton) &&
      fullscreenButton.viewModel.isFullscreenEnabled
    ) {
      fullscreenButton.container.style.visibility = visibility;
    }
    if (defined(infoBox)) {
      infoBox.container.style.visibility = visibility;
    }
    if (defined(selectionIndicator)) {
      selectionIndicator.container.style.visibility = visibility;
    }

    if (viewer._container) {
      const right =
        enabled || !defined(fullscreenButton)
          ? 0
          : fullscreenButton.container.clientWidth;
      viewer._vrButton.container.style.right = `${right}px`;

      viewer.forceResize();
    }
  }

  /**
   * @typedef {Object} Viewer.ConstructorOptions
   *
   * Initialization options for the Viewer constructor
   *
   * @property {Boolean} [animation=true] If set to false, the Animation widget will not be created.
   * @property {Boolean} [baseLayerPicker=true] If set to false, the BaseLayerPicker widget will not be created.
   * @property {Boolean} [fullscreenButton=true] If set to false, the FullscreenButton widget will not be created.
   * @property {Boolean} [vrButton=false] If set to true, the VRButton widget will be created.
   * @property {Boolean|GeocoderService[]} [geocoder=true] If set to false, the Geocoder widget will not be created.
   * @property {Boolean} [homeButton=true] If set to false, the HomeButton widget will not be created.
   * @property {Boolean} [infoBox=true] If set to false, the InfoBox widget will not be created.
   * @property {Boolean} [sceneModePicker=true] If set to false, the SceneModePicker widget will not be created.
   * @property {Boolean} [selectionIndicator=true] If set to false, the SelectionIndicator widget will not be created.
   * @property {Boolean} [timeline=true] If set to false, the Timeline widget will not be created.
   * @property {Boolean} [navigationHelpButton=true] If set to false, the navigation help button will not be created.
   * @property {Boolean} [navigationInstructionsInitiallyVisible=true] True if the navigation instructions should initially be visible, or false if the should not be shown until the user explicitly clicks the button.
   * @property {Boolean} [scene3DOnly=false] When <code>true</code>, each geometry instance will only be rendered in 3D to save GPU memory.
   * @property {Boolean} [shouldAnimate=false] <code>true</code> if the clock should attempt to advance simulation time by default, <code>false</code> otherwise.  This option takes precedence over setting {@link Viewer#clockViewModel}.
   * @property {ClockViewModel} [clockViewModel=new ClockViewModel(clock)] The clock view model to use to control current time.
   * @property {ProviderViewModel} [selectedImageryProviderViewModel] The view model for the current base imagery layer, if not supplied the first available base layer is used.  This value is only valid if `baseLayerPicker` is set to true.
   * @property {ProviderViewModel[]} [imageryProviderViewModels=createDefaultImageryProviderViewModels()] The array of ProviderViewModels to be selectable from the BaseLayerPicker.  This value is only valid if `baseLayerPicker` is set to true.
   * @property {ProviderViewModel} [selectedTerrainProviderViewModel] The view model for the current base terrain layer, if not supplied the first available base layer is used.  This value is only valid if `baseLayerPicker` is set to true.
   * @property {ProviderViewModel[]} [terrainProviderViewModels=createDefaultTerrainProviderViewModels()] The array of ProviderViewModels to be selectable from the BaseLayerPicker.  This value is only valid if `baseLayerPicker` is set to true.
   * @property {ImageryProvider} [imageryProvider=createWorldImagery()] The imagery provider to use.  This value is only valid if `baseLayerPicker` is set to false.
   * @property {TerrainProvider} [terrainProvider=new EllipsoidTerrainProvider()] The terrain provider to use
   * @property {SkyBox|false} [skyBox] The skybox used to render the stars.  When <code>undefined</code>, the default stars are used. If set to <code>false</code>, no skyBox, Sun, or Moon will be added.
   * @property {SkyAtmosphere|false} [skyAtmosphere] Blue sky, and the glow around the Earth's limb.  Set to <code>false</code> to turn it off.
   * @property {Element|String} [fullscreenElement=document.body] The element or id to be placed into fullscreen mode when the full screen button is pressed.
   * @property {Boolean} [useDefaultRenderLoop=true] True if this widget should control the render loop, false otherwise.
   * @property {Number} [targetFrameRate] The target frame rate when using the default render loop.
   * @property {Boolean} [showRenderLoopErrors=true] If true, this widget will automatically display an HTML panel to the user containing the error, if a render loop error occurs.
   * @property {Boolean} [useBrowserRecommendedResolution=true] If true, render at the browser's recommended resolution and ignore <code>window.devicePixelRatio</code>.
   * @property {Boolean} [automaticallyTrackDataSourceClocks=true] If true, this widget will automatically track the clock settings of newly added DataSources, updating if the DataSource's clock changes.  Set this to false if you want to configure the clock independently.
   * @property {Object} [contextOptions] Context and WebGL creation properties corresponding to <code>options</code> passed to {@link Scene}.
   * @property {SceneMode} [sceneMode=SceneMode.SCENE3D] The initial scene mode.
   * @property {MapProjection} [mapProjection=new GeographicProjection()] The map projection to use in 2D and Columbus View modes.
   * @property {Globe|false} [globe=new Globe(mapProjection.ellipsoid)] The globe to use in the scene.  If set to <code>false</code>, no globe will be added.
   * @property {Boolean} [orderIndependentTranslucency=true] If true and the configuration supports it, use order independent translucency.
   * @property {Element|String} [creditContainer] The DOM element or ID that will contain the {@link CreditDisplay}.  If not specified, the credits are added to the bottom of the widget itself.
   * @property {Element|String} [creditViewport] The DOM element or ID that will contain the credit pop up created by the {@link CreditDisplay}.  If not specified, it will appear over the widget itself.
   * @property {DataSourceCollection} [dataSources=new DataSourceCollection()] The collection of data sources visualized by the widget.  If this parameter is provided,
   *                               the instance is assumed to be owned by the caller and will not be destroyed when the viewer is destroyed.
   * @property {Boolean} [shadows=false] Determines if shadows are cast by light sources.
   * @property {ShadowMode} [terrainShadows=ShadowMode.RECEIVE_ONLY] Determines if the terrain casts or receives shadows from light sources.
   * @property {MapMode2D} [mapMode2D=MapMode2D.INFINITE_SCROLL] Determines if the 2D map is rotatable or can be scrolled infinitely in the horizontal direction.
   * @property {Boolean} [projectionPicker=false] If set to true, the ProjectionPicker widget will be created.
   * @property {Boolean} [requestRenderMode=false] If true, rendering a frame will only occur when needed as determined by changes within the scene. Enabling reduces the CPU/GPU usage of your application and uses less battery on mobile, but requires using {@link Scene#requestRender} to render a new frame explicitly in this mode. This will be necessary in many cases after making changes to the scene in other parts of the API. See {@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|Improving Performance with Explicit Rendering}.
   * @property {Number} [maximumRenderTimeChange=0.0] If requestRenderMode is true, this value defines the maximum change in simulation time allowed before a render is requested. See {@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|Improving Performance with Explicit Rendering}.
   * @property {Number} [depthPlaneEllipsoidOffset=0.0] Adjust the DepthPlane to address rendering artefacts below ellipsoid zero elevation.
   * @property {Number} [msaaSamples=1] If provided, this value controls the rate of multisample antialiasing. Typical multisampling rates are 2, 4, and sometimes 8 samples per pixel. Higher sampling rates of MSAA may impact performance in exchange for improved visual quality. This value only applies to WebGL2 contexts that support multisample render targets.
   */

  /**
   * A base widget for building applications.  It composites all of the standard Cesium widgets into one reusable package.
   * The widget can always be extended by using mixins, which add functionality useful for a variety of applications.
   *
   * @alias Viewer
   * @constructor
   *
   * @param {Element|String} container The DOM element or ID that will contain the widget.
   * @param {Viewer.ConstructorOptions} [options] Object describing initialization options
   *
   * @exception {DeveloperError} Element with id "container" does not exist in the document.
   * @exception {DeveloperError} options.selectedImageryProviderViewModel is not available when not using the BaseLayerPicker widget, specify options.imageryProvider instead.
   * @exception {DeveloperError} options.selectedTerrainProviderViewModel is not available when not using the BaseLayerPicker widget, specify options.terrainProvider instead.
   *
   * @see Animation
   * @see BaseLayerPicker
   * @see CesiumWidget
   * @see FullscreenButton
   * @see HomeButton
   * @see SceneModePicker
   * @see Timeline
   * @see viewerDragDropMixin
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Hello%20World.html|Cesium Sandcastle Hello World Demo}
   *
   * @example
   * //Initialize the viewer widget with several custom options and mixins.
   * const viewer = new Cesium.Viewer('cesiumContainer', {
   *     //Start in Columbus Viewer
   *     sceneMode : Cesium.SceneMode.COLUMBUS_VIEW,
   *     //Use Cesium World Terrain
   *     terrainProvider : Cesium.createWorldTerrain(),
   *     //Hide the base layer picker
   *     baseLayerPicker : false,
   *     //Use OpenStreetMaps
   *     imageryProvider : new Cesium.OpenStreetMapImageryProvider({
   *         url : 'https://a.tile.openstreetmap.org/'
   *     }),
   *     skyBox : new Cesium.SkyBox({
   *         sources : {
   *           positiveX : 'stars/TychoSkymapII.t3_08192x04096_80_px.jpg',
   *           negativeX : 'stars/TychoSkymapII.t3_08192x04096_80_mx.jpg',
   *           positiveY : 'stars/TychoSkymapII.t3_08192x04096_80_py.jpg',
   *           negativeY : 'stars/TychoSkymapII.t3_08192x04096_80_my.jpg',
   *           positiveZ : 'stars/TychoSkymapII.t3_08192x04096_80_pz.jpg',
   *           negativeZ : 'stars/TychoSkymapII.t3_08192x04096_80_mz.jpg'
   *         }
   *     }),
   *     // Show Columbus View map with Web Mercator projection
   *     mapProjection : new Cesium.WebMercatorProjection()
   * });
   *
   * //Add basic drag and drop functionality
   * viewer.extend(Cesium.viewerDragDropMixin);
   *
   * //Show a pop-up alert if we encounter an error when processing a dropped file
   * viewer.dropError.addEventListener(function(dropHandler, name, error) {
   *     console.log(error);
   *     window.alert(error);
   * });
   */
  function Viewer(container, options) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(container)) {
      throw new DeveloperError("container is required.");
    }
    //>>includeEnd('debug');

    container = getElement(container);
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const createBaseLayerPicker =
      (!defined(options.globe) || options.globe !== false) &&
      (!defined(options.baseLayerPicker) || options.baseLayerPicker !== false);

    //>>includeStart('debug', pragmas.debug);
    // If not using BaseLayerPicker, selectedImageryProviderViewModel is an invalid option
    if (
      !createBaseLayerPicker &&
      defined(options.selectedImageryProviderViewModel)
    ) {
      throw new DeveloperError(
        "options.selectedImageryProviderViewModel is not available when not using the BaseLayerPicker widget. \
Either specify options.imageryProvider instead or set options.baseLayerPicker to true."
      );
    }

    // If not using BaseLayerPicker, selectedTerrainProviderViewModel is an invalid option
    if (
      !createBaseLayerPicker &&
      defined(options.selectedTerrainProviderViewModel)
    ) {
      throw new DeveloperError(
        "options.selectedTerrainProviderViewModel is not available when not using the BaseLayerPicker widget. \
Either specify options.terrainProvider instead or set options.baseLayerPicker to true."
      );
    }
    //>>includeEnd('debug')

    const that = this;

    const viewerContainer = document.createElement("div");
    viewerContainer.className = "cesium-viewer";
    container.appendChild(viewerContainer);

    // Cesium widget container
    const cesiumWidgetContainer = document.createElement("div");
    cesiumWidgetContainer.className = "cesium-viewer-cesiumWidgetContainer";
    viewerContainer.appendChild(cesiumWidgetContainer);

    // Bottom container
    const bottomContainer = document.createElement("div");
    bottomContainer.className = "cesium-viewer-bottom";

    viewerContainer.appendChild(bottomContainer);

    const scene3DOnly = defaultValue(options.scene3DOnly, false);

    let clock;
    let clockViewModel;
    let destroyClockViewModel = false;
    if (defined(options.clockViewModel)) {
      clockViewModel = options.clockViewModel;
      clock = clockViewModel.clock;
    } else {
      clock = new Clock();
      clockViewModel = new ClockViewModel(clock);
      destroyClockViewModel = true;
    }

    if (defined(options.shouldAnimate)) {
      clock.shouldAnimate = options.shouldAnimate;
    }

    // Cesium widget
    const cesiumWidget = new CesiumWidget(cesiumWidgetContainer, {
      imageryProvider:
        createBaseLayerPicker || defined(options.imageryProvider)
          ? false
          : undefined,
      clock: clock,
      skyBox: options.skyBox,
      skyAtmosphere: options.skyAtmosphere,
      sceneMode: options.sceneMode,
      mapProjection: options.mapProjection,
      globe: options.globe,
      orderIndependentTranslucency: options.orderIndependentTranslucency,
      contextOptions: options.contextOptions,
      useDefaultRenderLoop: options.useDefaultRenderLoop,
      targetFrameRate: options.targetFrameRate,
      showRenderLoopErrors: options.showRenderLoopErrors,
      useBrowserRecommendedResolution: options.useBrowserRecommendedResolution,
      creditContainer: defined(options.creditContainer)
        ? options.creditContainer
        : bottomContainer,
      creditViewport: options.creditViewport,
      scene3DOnly: scene3DOnly,
      shadows: options.shadows,
      terrainShadows: options.terrainShadows,
      mapMode2D: options.mapMode2D,
      requestRenderMode: options.requestRenderMode,
      maximumRenderTimeChange: options.maximumRenderTimeChange,
      depthPlaneEllipsoidOffset: options.depthPlaneEllipsoidOffset,
      msaaSamples: options.msaaSamples,
    });

    let dataSourceCollection = options.dataSources;
    let destroyDataSourceCollection = false;
    if (!defined(dataSourceCollection)) {
      dataSourceCollection = new DataSourceCollection();
      destroyDataSourceCollection = true;
    }

    const scene = cesiumWidget.scene;

    const dataSourceDisplay = new DataSourceDisplay({
      scene: scene,
      dataSourceCollection: dataSourceCollection,
    });

    const eventHelper = new EventHelper();

    eventHelper.add(clock.onTick, Viewer.prototype._onTick, this);
    eventHelper.add(scene.morphStart, Viewer.prototype._clearTrackedObject, this);

    // Selection Indicator
    let selectionIndicator;
    if (
      !defined(options.selectionIndicator) ||
      options.selectionIndicator !== false
    ) {
      const selectionIndicatorContainer = document.createElement("div");
      selectionIndicatorContainer.className =
        "cesium-viewer-selectionIndicatorContainer";
      viewerContainer.appendChild(selectionIndicatorContainer);
      selectionIndicator = new SelectionIndicator(
        selectionIndicatorContainer,
        scene
      );
    }

    // Info Box
    let infoBox;
    if (!defined(options.infoBox) || options.infoBox !== false) {
      const infoBoxContainer = document.createElement("div");
      infoBoxContainer.className = "cesium-viewer-infoBoxContainer";
      viewerContainer.appendChild(infoBoxContainer);
      infoBox = new InfoBox(infoBoxContainer);

      const infoBoxViewModel = infoBox.viewModel;
      eventHelper.add(
        infoBoxViewModel.cameraClicked,
        Viewer.prototype._onInfoBoxCameraClicked,
        this
      );
      eventHelper.add(
        infoBoxViewModel.closeClicked,
        Viewer.prototype._onInfoBoxClockClicked,
        this
      );
    }

    // Main Toolbar
    const toolbar = document.createElement("div");
    toolbar.className = "cesium-viewer-toolbar";
    viewerContainer.appendChild(toolbar);

    // Geocoder
    let geocoder;
    if (!defined(options.geocoder) || options.geocoder !== false) {
      const geocoderContainer = document.createElement("div");
      geocoderContainer.className = "cesium-viewer-geocoderContainer";
      toolbar.appendChild(geocoderContainer);
      let geocoderService;
      if (defined(options.geocoder) && typeof options.geocoder !== "boolean") {
        geocoderService = Array.isArray(options.geocoder)
          ? options.geocoder
          : [options.geocoder];
      }
      geocoder = new Geocoder({
        container: geocoderContainer,
        geocoderServices: geocoderService,
        scene: scene,
      });
      // Subscribe to search so that we can clear the trackedEntity when it is clicked.
      eventHelper.add(
        geocoder.viewModel.search.beforeExecute,
        Viewer.prototype._clearObjects,
        this
      );
    }

    // HomeButton
    let homeButton;
    if (!defined(options.homeButton) || options.homeButton !== false) {
      homeButton = new HomeButton(toolbar, scene);
      if (defined(geocoder)) {
        eventHelper.add(homeButton.viewModel.command.afterExecute, function () {
          const viewModel = geocoder.viewModel;
          viewModel.searchText = "";
          if (viewModel.isSearchInProgress) {
            viewModel.search();
          }
        });
      }
      // Subscribe to the home button beforeExecute event so that we can clear the trackedEntity.
      eventHelper.add(
        homeButton.viewModel.command.beforeExecute,
        Viewer.prototype._clearTrackedObject,
        this
      );
    }

    // SceneModePicker
    // By default, we silently disable the scene mode picker if scene3DOnly is true,
    // but if sceneModePicker is explicitly set to true, throw an error.
    //>>includeStart('debug', pragmas.debug);
    if (options.sceneModePicker === true && scene3DOnly) {
      throw new DeveloperError(
        "options.sceneModePicker is not available when options.scene3DOnly is set to true."
      );
    }
    //>>includeEnd('debug');

    let sceneModePicker;
    if (
      !scene3DOnly &&
      (!defined(options.sceneModePicker) || options.sceneModePicker !== false)
    ) {
      sceneModePicker = new SceneModePicker(toolbar, scene);
    }

    let projectionPicker;
    if (options.projectionPicker) {
      projectionPicker = new ProjectionPicker(toolbar, scene);
    }

    // BaseLayerPicker
    let baseLayerPicker;
    let baseLayerPickerDropDown;
    if (createBaseLayerPicker) {
      const imageryProviderViewModels = defaultValue(
        options.imageryProviderViewModels,
        createDefaultImageryProviderViewModels()
      );
      const terrainProviderViewModels = defaultValue(
        options.terrainProviderViewModels,
        createDefaultTerrainProviderViewModels()
      );

      baseLayerPicker = new BaseLayerPicker(toolbar, {
        globe: scene.globe,
        imageryProviderViewModels: imageryProviderViewModels,
        selectedImageryProviderViewModel:
          options.selectedImageryProviderViewModel,
        terrainProviderViewModels: terrainProviderViewModels,
        selectedTerrainProviderViewModel:
          options.selectedTerrainProviderViewModel,
      });

      //Grab the dropdown for resize code.
      const elements = toolbar.getElementsByClassName(
        "cesium-baseLayerPicker-dropDown"
      );
      baseLayerPickerDropDown = elements[0];
    }

    // These need to be set after the BaseLayerPicker is created in order to take effect
    if (defined(options.imageryProvider) && options.imageryProvider !== false) {
      if (createBaseLayerPicker) {
        baseLayerPicker.viewModel.selectedImagery = undefined;
      }
      scene.imageryLayers.removeAll();
      scene.imageryLayers.addImageryProvider(options.imageryProvider);
    }
    if (defined(options.terrainProvider)) {
      if (createBaseLayerPicker) {
        baseLayerPicker.viewModel.selectedTerrain = undefined;
      }
      scene.terrainProvider = options.terrainProvider;
    }

    // Navigation Help Button
    let navigationHelpButton;
    if (
      !defined(options.navigationHelpButton) ||
      options.navigationHelpButton !== false
    ) {
      let showNavHelp = true;
      try {
        //window.localStorage is null if disabled in Firefox or undefined in browsers with implementation
        if (defined(window.localStorage)) {
          const hasSeenNavHelp = window.localStorage.getItem(
            "cesium-hasSeenNavHelp"
          );
          if (defined(hasSeenNavHelp) && Boolean(hasSeenNavHelp)) {
            showNavHelp = false;
          } else {
            window.localStorage.setItem("cesium-hasSeenNavHelp", "true");
          }
        }
      } catch (e) {
        //Accessing window.localStorage throws if disabled in Chrome
        //window.localStorage.setItem throws if in Safari private browsing mode or in any browser if we are over quota.
      }
      navigationHelpButton = new NavigationHelpButton({
        container: toolbar,
        instructionsInitiallyVisible: defaultValue(
          options.navigationInstructionsInitiallyVisible,
          showNavHelp
        ),
      });
    }

    // Animation
    let animation;
    if (!defined(options.animation) || options.animation !== false) {
      const animationContainer = document.createElement("div");
      animationContainer.className = "cesium-viewer-animationContainer";
      viewerContainer.appendChild(animationContainer);
      animation = new Animation(
        animationContainer,
        new AnimationViewModel(clockViewModel)
      );
    }

    // Timeline
    let timeline;
    if (!defined(options.timeline) || options.timeline !== false) {
      const timelineContainer = document.createElement("div");
      timelineContainer.className = "cesium-viewer-timelineContainer";
      viewerContainer.appendChild(timelineContainer);
      timeline = new Timeline(timelineContainer, clock);
      timeline.addEventListener("settime", onTimelineScrubfunction, false);
      timeline.zoomTo(clock.startTime, clock.stopTime);
    }

    // Fullscreen
    let fullscreenButton;
    let fullscreenSubscription;
    let fullscreenContainer;
    if (
      !defined(options.fullscreenButton) ||
      options.fullscreenButton !== false
    ) {
      fullscreenContainer = document.createElement("div");
      fullscreenContainer.className = "cesium-viewer-fullscreenContainer";
      viewerContainer.appendChild(fullscreenContainer);
      fullscreenButton = new FullscreenButton(
        fullscreenContainer,
        options.fullscreenElement
      );

      //Subscribe to fullscreenButton.viewModel.isFullscreenEnabled so
      //that we can hide/show the button as well as size the timeline.
      fullscreenSubscription = subscribeAndEvaluate(
        fullscreenButton.viewModel,
        "isFullscreenEnabled",
        function (isFullscreenEnabled) {
          fullscreenContainer.style.display = isFullscreenEnabled
            ? "block"
            : "none";
          if (defined(timeline)) {
            timeline.container.style.right = `${fullscreenContainer.clientWidth}px`;
            timeline.resize();
          }
        }
      );
    }

    // VR
    let vrButton;
    let vrSubscription;
    let vrModeSubscription;
    if (options.vrButton) {
      const vrContainer = document.createElement("div");
      vrContainer.className = "cesium-viewer-vrContainer";
      viewerContainer.appendChild(vrContainer);
      vrButton = new VRButton(vrContainer, scene, options.fullScreenElement);

      vrSubscription = subscribeAndEvaluate(
        vrButton.viewModel,
        "isVREnabled",
        function (isVREnabled) {
          vrContainer.style.display = isVREnabled ? "block" : "none";
          if (defined(fullscreenButton)) {
            vrContainer.style.right = `${fullscreenContainer.clientWidth}px`;
          }
          if (defined(timeline)) {
            timeline.container.style.right = `${vrContainer.clientWidth}px`;
            timeline.resize();
          }
        }
      );

      vrModeSubscription = subscribeAndEvaluate(
        vrButton.viewModel,
        "isVRMode",
        function (isVRMode) {
          enableVRUI(that, isVRMode);
        }
      );
    }

    //Assign all properties to this instance.  No "this" assignments should
    //take place above this line.
    this._baseLayerPickerDropDown = baseLayerPickerDropDown;
    this._fullscreenSubscription = fullscreenSubscription;
    this._vrSubscription = vrSubscription;
    this._vrModeSubscription = vrModeSubscription;
    this._dataSourceChangedListeners = {};
    this._automaticallyTrackDataSourceClocks = defaultValue(
      options.automaticallyTrackDataSourceClocks,
      true
    );
    this._container = container;
    this._bottomContainer = bottomContainer;
    this._element = viewerContainer;
    this._cesiumWidget = cesiumWidget;
    this._selectionIndicator = selectionIndicator;
    this._infoBox = infoBox;
    this._dataSourceCollection = dataSourceCollection;
    this._destroyDataSourceCollection = destroyDataSourceCollection;
    this._dataSourceDisplay = dataSourceDisplay;
    this._clockViewModel = clockViewModel;
    this._destroyClockViewModel = destroyClockViewModel;
    this._toolbar = toolbar;
    this._homeButton = homeButton;
    this._sceneModePicker = sceneModePicker;
    this._projectionPicker = projectionPicker;
    this._baseLayerPicker = baseLayerPicker;
    this._navigationHelpButton = navigationHelpButton;
    this._animation = animation;
    this._timeline = timeline;
    this._fullscreenButton = fullscreenButton;
    this._vrButton = vrButton;
    this._geocoder = geocoder;
    this._eventHelper = eventHelper;
    this._lastWidth = 0;
    this._lastHeight = 0;
    this._allowDataSourcesToSuspendAnimation = true;
    this._entityView = undefined;
    this._enableInfoOrSelection = defined(infoBox) || defined(selectionIndicator);
    this._clockTrackedDataSource = undefined;
    this._trackedEntity = undefined;
    this._needTrackedEntityUpdate = false;
    this._selectedEntity = undefined;
    this._zoomIsFlight = false;
    this._zoomTarget = undefined;
    this._zoomPromise = undefined;
    this._zoomOptions = undefined;
    this._selectedEntityChanged = new Event();
    this._trackedEntityChanged = new Event();

    knockout.track(this, [
      "_trackedEntity",
      "_selectedEntity",
      "_clockTrackedDataSource",
    ]);

    //Listen to data source events in order to track clock changes.
    eventHelper.add(
      dataSourceCollection.dataSourceAdded,
      Viewer.prototype._onDataSourceAdded,
      this
    );
    eventHelper.add(
      dataSourceCollection.dataSourceRemoved,
      Viewer.prototype._onDataSourceRemoved,
      this
    );

    // Prior to each render, check if anything needs to be resized.
    eventHelper.add(scene.postUpdate, Viewer.prototype.resize, this);
    eventHelper.add(scene.postRender, Viewer.prototype._postRender, this);

    // We need to subscribe to the data sources and collections so that we can clear the
    // tracked object when it is removed from the scene.
    // Subscribe to current data sources
    const dataSourceLength = dataSourceCollection.length;
    for (let i = 0; i < dataSourceLength; i++) {
      this._dataSourceAdded(dataSourceCollection, dataSourceCollection.get(i));
    }
    this._dataSourceAdded(undefined, dataSourceDisplay.defaultDataSource);

    // Hook up events so that we can subscribe to future sources.
    eventHelper.add(
      dataSourceCollection.dataSourceAdded,
      Viewer.prototype._dataSourceAdded,
      this
    );
    eventHelper.add(
      dataSourceCollection.dataSourceRemoved,
      Viewer.prototype._dataSourceRemoved,
      this
    );

    // Subscribe to left clicks and zoom to the picked object.
    function pickAndTrackObject(e) {
      const entity = pickEntity(that, e);
      if (defined(entity)) {
        //Only track the entity if it has a valid position at the current time.
        if (
          Property.getValueOrUndefined(entity.position, that.clock.currentTime)
        ) {
          that.trackedEntity = entity;
        } else {
          that.zoomTo(entity);
        }
      } else if (defined(that.trackedEntity)) {
        that.trackedEntity = undefined;
      }
    }

    function pickAndSelectObject(e) {
      that.selectedEntity = pickEntity(that, e);
    }

    cesiumWidget.screenSpaceEventHandler.setInputAction(
      pickAndSelectObject,
      ScreenSpaceEventType$1.LEFT_CLICK
    );
    cesiumWidget.screenSpaceEventHandler.setInputAction(
      pickAndTrackObject,
      ScreenSpaceEventType$1.LEFT_DOUBLE_CLICK
    );
  }

  Object.defineProperties(Viewer.prototype, {
    /**
     * Gets the parent container.
     * @memberof Viewer.prototype
     * @type {Element}
     * @readonly
     */
    container: {
      get: function () {
        return this._container;
      },
    },

    /**
     * Gets the DOM element for the area at the bottom of the window containing the
     * {@link CreditDisplay} and potentially other things.
     * @memberof Viewer.prototype
     * @type {Element}
     * @readonly
     */
    bottomContainer: {
      get: function () {
        return this._bottomContainer;
      },
    },

    /**
     * Gets the CesiumWidget.
     * @memberof Viewer.prototype
     * @type {CesiumWidget}
     * @readonly
     */
    cesiumWidget: {
      get: function () {
        return this._cesiumWidget;
      },
    },

    /**
     * Gets the selection indicator.
     * @memberof Viewer.prototype
     * @type {SelectionIndicator}
     * @readonly
     */
    selectionIndicator: {
      get: function () {
        return this._selectionIndicator;
      },
    },

    /**
     * Gets the info box.
     * @memberof Viewer.prototype
     * @type {InfoBox}
     * @readonly
     */
    infoBox: {
      get: function () {
        return this._infoBox;
      },
    },

    /**
     * Gets the Geocoder.
     * @memberof Viewer.prototype
     * @type {Geocoder}
     * @readonly
     */
    geocoder: {
      get: function () {
        return this._geocoder;
      },
    },

    /**
     * Gets the HomeButton.
     * @memberof Viewer.prototype
     * @type {HomeButton}
     * @readonly
     */
    homeButton: {
      get: function () {
        return this._homeButton;
      },
    },

    /**
     * Gets the SceneModePicker.
     * @memberof Viewer.prototype
     * @type {SceneModePicker}
     * @readonly
     */
    sceneModePicker: {
      get: function () {
        return this._sceneModePicker;
      },
    },

    /**
     * Gets the ProjectionPicker.
     * @memberof Viewer.prototype
     * @type {ProjectionPicker}
     * @readonly
     */
    projectionPicker: {
      get: function () {
        return this._projectionPicker;
      },
    },

    /**
     * Gets the BaseLayerPicker.
     * @memberof Viewer.prototype
     * @type {BaseLayerPicker}
     * @readonly
     */
    baseLayerPicker: {
      get: function () {
        return this._baseLayerPicker;
      },
    },

    /**
     * Gets the NavigationHelpButton.
     * @memberof Viewer.prototype
     * @type {NavigationHelpButton}
     * @readonly
     */
    navigationHelpButton: {
      get: function () {
        return this._navigationHelpButton;
      },
    },

    /**
     * Gets the Animation widget.
     * @memberof Viewer.prototype
     * @type {Animation}
     * @readonly
     */
    animation: {
      get: function () {
        return this._animation;
      },
    },

    /**
     * Gets the Timeline widget.
     * @memberof Viewer.prototype
     * @type {Timeline}
     * @readonly
     */
    timeline: {
      get: function () {
        return this._timeline;
      },
    },

    /**
     * Gets the FullscreenButton.
     * @memberof Viewer.prototype
     * @type {FullscreenButton}
     * @readonly
     */
    fullscreenButton: {
      get: function () {
        return this._fullscreenButton;
      },
    },

    /**
     * Gets the VRButton.
     * @memberof Viewer.prototype
     * @type {VRButton}
     * @readonly
     */
    vrButton: {
      get: function () {
        return this._vrButton;
      },
    },

    /**
     * Gets the display used for {@link DataSource} visualization.
     * @memberof Viewer.prototype
     * @type {DataSourceDisplay}
     * @readonly
     */
    dataSourceDisplay: {
      get: function () {
        return this._dataSourceDisplay;
      },
    },

    /**
     * Gets the collection of entities not tied to a particular data source.
     * This is a shortcut to [dataSourceDisplay.defaultDataSource.entities]{@link Viewer#dataSourceDisplay}.
     * @memberof Viewer.prototype
     * @type {EntityCollection}
     * @readonly
     */
    entities: {
      get: function () {
        return this._dataSourceDisplay.defaultDataSource.entities;
      },
    },

    /**
     * Gets the set of {@link DataSource} instances to be visualized.
     * @memberof Viewer.prototype
     * @type {DataSourceCollection}
     * @readonly
     */
    dataSources: {
      get: function () {
        return this._dataSourceCollection;
      },
    },

    /**
     * Gets the canvas.
     * @memberof Viewer.prototype
     * @type {HTMLCanvasElement}
     * @readonly
     */
    canvas: {
      get: function () {
        return this._cesiumWidget.canvas;
      },
    },

    /**
     * Gets the scene.
     * @memberof Viewer.prototype
     * @type {Scene}
     * @readonly
     */
    scene: {
      get: function () {
        return this._cesiumWidget.scene;
      },
    },

    /**
     * Determines if shadows are cast by light sources.
     * @memberof Viewer.prototype
     * @type {Boolean}
     */
    shadows: {
      get: function () {
        return this.scene.shadowMap.enabled;
      },
      set: function (value) {
        this.scene.shadowMap.enabled = value;
      },
    },

    /**
     * Determines if the terrain casts or shadows from light sources.
     * @memberof Viewer.prototype
     * @type {ShadowMode}
     */
    terrainShadows: {
      get: function () {
        return this.scene.globe.shadows;
      },
      set: function (value) {
        this.scene.globe.shadows = value;
      },
    },

    /**
     * Get the scene's shadow map
     * @memberof Viewer.prototype
     * @type {ShadowMap}
     * @readonly
     */
    shadowMap: {
      get: function () {
        return this.scene.shadowMap;
      },
    },

    /**
     * Gets the collection of image layers that will be rendered on the globe.
     * @memberof Viewer.prototype
     *
     * @type {ImageryLayerCollection}
     * @readonly
     */
    imageryLayers: {
      get: function () {
        return this.scene.imageryLayers;
      },
    },

    /**
     * The terrain provider providing surface geometry for the globe.
     * @memberof Viewer.prototype
     *
     * @type {TerrainProvider}
     */
    terrainProvider: {
      get: function () {
        return this.scene.terrainProvider;
      },
      set: function (terrainProvider) {
        this.scene.terrainProvider = terrainProvider;
      },
    },

    /**
     * Gets the camera.
     * @memberof Viewer.prototype
     *
     * @type {Camera}
     * @readonly
     */
    camera: {
      get: function () {
        return this.scene.camera;
      },
    },

    /**
     * Gets the post-process stages.
     * @memberof Viewer.prototype
     *
     * @type {PostProcessStageCollection}
     * @readonly
     */
    postProcessStages: {
      get: function () {
        return this.scene.postProcessStages;
      },
    },

    /**
     * Gets the clock.
     * @memberof Viewer.prototype
     * @type {Clock}
     * @readonly
     */
    clock: {
      get: function () {
        return this._clockViewModel.clock;
      },
    },

    /**
     * Gets the clock view model.
     * @memberof Viewer.prototype
     * @type {ClockViewModel}
     * @readonly
     */
    clockViewModel: {
      get: function () {
        return this._clockViewModel;
      },
    },

    /**
     * Gets the screen space event handler.
     * @memberof Viewer.prototype
     * @type {ScreenSpaceEventHandler}
     * @readonly
     */
    screenSpaceEventHandler: {
      get: function () {
        return this._cesiumWidget.screenSpaceEventHandler;
      },
    },

    /**
     * Gets or sets the target frame rate of the widget when <code>useDefaultRenderLoop</code>
     * is true. If undefined, the browser's {@link requestAnimationFrame} implementation
     * determines the frame rate.  If defined, this value must be greater than 0.  A value higher
     * than the underlying requestAnimationFrame implementation will have no effect.
     * @memberof Viewer.prototype
     *
     * @type {Number}
     */
    targetFrameRate: {
      get: function () {
        return this._cesiumWidget.targetFrameRate;
      },
      set: function (value) {
        this._cesiumWidget.targetFrameRate = value;
      },
    },

    /**
     * Gets or sets whether or not this widget should control the render loop.
     * If set to true the widget will use {@link requestAnimationFrame} to
     * perform rendering and resizing of the widget, as well as drive the
     * simulation clock. If set to false, you must manually call the
     * <code>resize</code>, <code>render</code> methods
     * as part of a custom render loop.  If an error occurs during rendering, {@link Scene}'s
     * <code>renderError</code> event will be raised and this property
     * will be set to false.  It must be set back to true to continue rendering
     * after the error.
     * @memberof Viewer.prototype
     *
     * @type {Boolean}
     */
    useDefaultRenderLoop: {
      get: function () {
        return this._cesiumWidget.useDefaultRenderLoop;
      },
      set: function (value) {
        this._cesiumWidget.useDefaultRenderLoop = value;
      },
    },

    /**
     * Gets or sets a scaling factor for rendering resolution.  Values less than 1.0 can improve
     * performance on less powerful devices while values greater than 1.0 will render at a higher
     * resolution and then scale down, resulting in improved visual fidelity.
     * For example, if the widget is laid out at a size of 640x480, setting this value to 0.5
     * will cause the scene to be rendered at 320x240 and then scaled up while setting
     * it to 2.0 will cause the scene to be rendered at 1280x960 and then scaled down.
     * @memberof Viewer.prototype
     *
     * @type {Number}
     * @default 1.0
     */
    resolutionScale: {
      get: function () {
        return this._cesiumWidget.resolutionScale;
      },
      set: function (value) {
        this._cesiumWidget.resolutionScale = value;
      },
    },

    /**
     * Boolean flag indicating if the browser's recommended resolution is used.
     * If true, the browser's device pixel ratio is ignored and 1.0 is used instead,
     * effectively rendering based on CSS pixels instead of device pixels. This can improve
     * performance on less powerful devices that have high pixel density. When false, rendering
     * will be in device pixels. {@link Viewer#resolutionScale} will still take effect whether
     * this flag is true or false.
     * @memberof Viewer.prototype
     *
     * @type {Boolean}
     * @default true
     */
    useBrowserRecommendedResolution: {
      get: function () {
        return this._cesiumWidget.useBrowserRecommendedResolution;
      },
      set: function (value) {
        this._cesiumWidget.useBrowserRecommendedResolution = value;
      },
    },

    /**
     * Gets or sets whether or not data sources can temporarily pause
     * animation in order to avoid showing an incomplete picture to the user.
     * For example, if asynchronous primitives are being processed in the
     * background, the clock will not advance until the geometry is ready.
     *
     * @memberof Viewer.prototype
     *
     * @type {Boolean}
     */
    allowDataSourcesToSuspendAnimation: {
      get: function () {
        return this._allowDataSourcesToSuspendAnimation;
      },
      set: function (value) {
        this._allowDataSourcesToSuspendAnimation = value;
      },
    },

    /**
     * Gets or sets the Entity instance currently being tracked by the camera.
     * @memberof Viewer.prototype
     * @type {Entity | undefined}
     */
    trackedEntity: {
      get: function () {
        return this._trackedEntity;
      },
      set: function (value) {
        if (this._trackedEntity !== value) {
          this._trackedEntity = value;

          //Cancel any pending zoom
          cancelZoom(this);

          const scene = this.scene;
          const sceneMode = scene.mode;

          //Stop tracking
          if (!defined(value) || !defined(value.position)) {
            this._needTrackedEntityUpdate = false;
            if (
              sceneMode === SceneMode$1.COLUMBUS_VIEW ||
              sceneMode === SceneMode$1.SCENE2D
            ) {
              scene.screenSpaceCameraController.enableTranslate = true;
            }

            if (
              sceneMode === SceneMode$1.COLUMBUS_VIEW ||
              sceneMode === SceneMode$1.SCENE3D
            ) {
              scene.screenSpaceCameraController.enableTilt = true;
            }

            this._entityView = undefined;
            this.camera.lookAtTransform(Matrix4.IDENTITY);
          } else {
            //We can't start tracking immediately, so we set a flag and start tracking
            //when the bounding sphere is ready (most likely next frame).
            this._needTrackedEntityUpdate = true;
          }

          this._trackedEntityChanged.raiseEvent(value);
          this.scene.requestRender();
        }
      },
    },
    /**
     * Gets or sets the object instance for which to display a selection indicator.
     *
     * If a user interactively picks a Cesium3DTilesFeature instance, then this property
     * will contain a transient Entity instance with a property named "feature" that is
     * the instance that was picked.
     * @memberof Viewer.prototype
     * @type {Entity | undefined}
     */
    selectedEntity: {
      get: function () {
        return this._selectedEntity;
      },
      set: function (value) {
        if (this._selectedEntity !== value) {
          this._selectedEntity = value;
          const selectionIndicatorViewModel = defined(this._selectionIndicator)
            ? this._selectionIndicator.viewModel
            : undefined;
          if (defined(value)) {
            if (defined(selectionIndicatorViewModel)) {
              selectionIndicatorViewModel.animateAppear();
            }
          } else if (defined(selectionIndicatorViewModel)) {
            // Leave the info text in place here, it is needed during the exit animation.
            selectionIndicatorViewModel.animateDepart();
          }
          this._selectedEntityChanged.raiseEvent(value);
        }
      },
    },
    /**
     * Gets the event that is raised when the selected entity changes.
     * @memberof Viewer.prototype
     * @type {Event}
     * @readonly
     */
    selectedEntityChanged: {
      get: function () {
        return this._selectedEntityChanged;
      },
    },
    /**
     * Gets the event that is raised when the tracked entity changes.
     * @memberof Viewer.prototype
     * @type {Event}
     * @readonly
     */
    trackedEntityChanged: {
      get: function () {
        return this._trackedEntityChanged;
      },
    },
    /**
     * Gets or sets the data source to track with the viewer's clock.
     * @memberof Viewer.prototype
     * @type {DataSource}
     */
    clockTrackedDataSource: {
      get: function () {
        return this._clockTrackedDataSource;
      },
      set: function (value) {
        if (this._clockTrackedDataSource !== value) {
          this._clockTrackedDataSource = value;
          trackDataSourceClock(this._timeline, this.clock, value);
        }
      },
    },
  });

  /**
   * Extends the base viewer functionality with the provided mixin.
   * A mixin may add additional properties, functions, or other behavior
   * to the provided viewer instance.
   *
   * @param {Viewer.ViewerMixin} mixin The Viewer mixin to add to this instance.
   * @param {Object} [options] The options object to be passed to the mixin function.
   *
   * @see viewerDragDropMixin
   */
  Viewer.prototype.extend = function (mixin, options) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(mixin)) {
      throw new DeveloperError("mixin is required.");
    }
    //>>includeEnd('debug')

    mixin(this, options);
  };

  /**
   * Resizes the widget to match the container size.
   * This function is called automatically as needed unless
   * <code>useDefaultRenderLoop</code> is set to false.
   */
  Viewer.prototype.resize = function () {
    const cesiumWidget = this._cesiumWidget;
    const container = this._container;
    const width = container.clientWidth;
    const height = container.clientHeight;
    const animationExists = defined(this._animation);
    const timelineExists = defined(this._timeline);

    cesiumWidget.resize();

    if (width === this._lastWidth && height === this._lastHeight) {
      return;
    }

    const panelMaxHeight = height - 125;
    const baseLayerPickerDropDown = this._baseLayerPickerDropDown;

    if (defined(baseLayerPickerDropDown)) {
      baseLayerPickerDropDown.style.maxHeight = `${panelMaxHeight}px`;
    }

    if (defined(this._geocoder)) {
      const geocoderSuggestions = this._geocoder.searchSuggestionsContainer;
      geocoderSuggestions.style.maxHeight = `${panelMaxHeight}px`;
    }

    if (defined(this._infoBox)) {
      this._infoBox.viewModel.maxHeight = panelMaxHeight;
    }

    const timeline = this._timeline;
    let animationContainer;
    let animationWidth = 0;
    let creditLeft = 0;
    let creditBottom = 0;

    if (
      animationExists &&
      window.getComputedStyle(this._animation.container).visibility !== "hidden"
    ) {
      const lastWidth = this._lastWidth;
      animationContainer = this._animation.container;
      if (width > 900) {
        animationWidth = 169;
        if (lastWidth <= 900) {
          animationContainer.style.width = "169px";
          animationContainer.style.height = "112px";
          this._animation.resize();
        }
      } else if (width >= 600) {
        animationWidth = 136;
        if (lastWidth < 600 || lastWidth > 900) {
          animationContainer.style.width = "136px";
          animationContainer.style.height = "90px";
          this._animation.resize();
        }
      } else {
        animationWidth = 106;
        if (lastWidth > 600 || lastWidth === 0) {
          animationContainer.style.width = "106px";
          animationContainer.style.height = "70px";
          this._animation.resize();
        }
      }
      creditLeft = animationWidth + 5;
    }

    if (
      timelineExists &&
      window.getComputedStyle(this._timeline.container).visibility !== "hidden"
    ) {
      const fullscreenButton = this._fullscreenButton;
      const vrButton = this._vrButton;
      const timelineContainer = timeline.container;
      const timelineStyle = timelineContainer.style;

      creditBottom = timelineContainer.clientHeight + 3;
      timelineStyle.left = `${animationWidth}px`;

      let pixels = 0;
      if (defined(fullscreenButton)) {
        pixels += fullscreenButton.container.clientWidth;
      }
      if (defined(vrButton)) {
        pixels += vrButton.container.clientWidth;
      }

      timelineStyle.right = `${pixels}px`;
      timeline.resize();
    }

    this._bottomContainer.style.left = `${creditLeft}px`;
    this._bottomContainer.style.bottom = `${creditBottom}px`;

    this._lastWidth = width;
    this._lastHeight = height;
  };

  /**
   * This forces the widget to re-think its layout, including
   * widget sizes and credit placement.
   */
  Viewer.prototype.forceResize = function () {
    this._lastWidth = 0;
    this.resize();
  };

  /**
   * Renders the scene.  This function is called automatically
   * unless <code>useDefaultRenderLoop</code> is set to false;
   */
  Viewer.prototype.render = function () {
    this._cesiumWidget.render();
  };

  /**
   * @returns {Boolean} true if the object has been destroyed, false otherwise.
   */
  Viewer.prototype.isDestroyed = function () {
    return false;
  };

  /**
   * Destroys the widget.  Should be called if permanently
   * removing the widget from layout.
   */
  Viewer.prototype.destroy = function () {
    let i;

    this.screenSpaceEventHandler.removeInputAction(
      ScreenSpaceEventType$1.LEFT_CLICK
    );
    this.screenSpaceEventHandler.removeInputAction(
      ScreenSpaceEventType$1.LEFT_DOUBLE_CLICK
    );

    // Unsubscribe from data sources
    const dataSources = this.dataSources;
    const dataSourceLength = dataSources.length;
    for (i = 0; i < dataSourceLength; i++) {
      this._dataSourceRemoved(dataSources, dataSources.get(i));
    }
    this._dataSourceRemoved(undefined, this._dataSourceDisplay.defaultDataSource);

    this._container.removeChild(this._element);
    this._element.removeChild(this._toolbar);

    this._eventHelper.removeAll();

    if (defined(this._geocoder)) {
      this._geocoder = this._geocoder.destroy();
    }

    if (defined(this._homeButton)) {
      this._homeButton = this._homeButton.destroy();
    }

    if (defined(this._sceneModePicker)) {
      this._sceneModePicker = this._sceneModePicker.destroy();
    }

    if (defined(this._projectionPicker)) {
      this._projectionPicker = this._projectionPicker.destroy();
    }

    if (defined(this._baseLayerPicker)) {
      this._baseLayerPicker = this._baseLayerPicker.destroy();
    }

    if (defined(this._animation)) {
      this._element.removeChild(this._animation.container);
      this._animation = this._animation.destroy();
    }

    if (defined(this._timeline)) {
      this._timeline.removeEventListener(
        "settime",
        onTimelineScrubfunction,
        false
      );
      this._element.removeChild(this._timeline.container);
      this._timeline = this._timeline.destroy();
    }

    if (defined(this._fullscreenButton)) {
      this._fullscreenSubscription.dispose();
      this._element.removeChild(this._fullscreenButton.container);
      this._fullscreenButton = this._fullscreenButton.destroy();
    }

    if (defined(this._vrButton)) {
      this._vrSubscription.dispose();
      this._vrModeSubscription.dispose();
      this._element.removeChild(this._vrButton.container);
      this._vrButton = this._vrButton.destroy();
    }

    if (defined(this._infoBox)) {
      this._element.removeChild(this._infoBox.container);
      this._infoBox = this._infoBox.destroy();
    }

    if (defined(this._selectionIndicator)) {
      this._element.removeChild(this._selectionIndicator.container);
      this._selectionIndicator = this._selectionIndicator.destroy();
    }

    if (this._destroyClockViewModel) {
      this._clockViewModel = this._clockViewModel.destroy();
    }
    this._dataSourceDisplay = this._dataSourceDisplay.destroy();
    this._cesiumWidget = this._cesiumWidget.destroy();

    if (this._destroyDataSourceCollection) {
      this._dataSourceCollection = this._dataSourceCollection.destroy();
    }

    return destroyObject(this);
  };

  /**
   * @private
   */
  Viewer.prototype._dataSourceAdded = function (
    dataSourceCollection,
    dataSource
  ) {
    const entityCollection = dataSource.entities;
    entityCollection.collectionChanged.addEventListener(
      Viewer.prototype._onEntityCollectionChanged,
      this
    );
  };

  /**
   * @private
   */
  Viewer.prototype._dataSourceRemoved = function (
    dataSourceCollection,
    dataSource
  ) {
    const entityCollection = dataSource.entities;
    entityCollection.collectionChanged.removeEventListener(
      Viewer.prototype._onEntityCollectionChanged,
      this
    );

    if (defined(this.trackedEntity)) {
      if (
        entityCollection.getById(this.trackedEntity.id) === this.trackedEntity
      ) {
        this.trackedEntity = undefined;
      }
    }

    if (defined(this.selectedEntity)) {
      if (
        entityCollection.getById(this.selectedEntity.id) === this.selectedEntity
      ) {
        this.selectedEntity = undefined;
      }
    }
  };

  /**
   * @private
   */
  Viewer.prototype._onTick = function (clock) {
    const time = clock.currentTime;

    const isUpdated = this._dataSourceDisplay.update(time);
    if (this._allowDataSourcesToSuspendAnimation) {
      this._clockViewModel.canAnimate = isUpdated;
    }

    const entityView = this._entityView;
    if (defined(entityView)) {
      const trackedEntity = this._trackedEntity;
      const trackedState = this._dataSourceDisplay.getBoundingSphere(
        trackedEntity,
        false,
        boundingSphereScratch
      );
      if (trackedState === BoundingSphereState$1.DONE) {
        entityView.update(time, boundingSphereScratch);
      }
    }

    let position;
    let enableCamera = false;
    const selectedEntity = this.selectedEntity;
    const showSelection = defined(selectedEntity) && this._enableInfoOrSelection;

    if (
      showSelection &&
      selectedEntity.isShowing &&
      selectedEntity.isAvailable(time)
    ) {
      const state = this._dataSourceDisplay.getBoundingSphere(
        selectedEntity,
        true,
        boundingSphereScratch
      );
      if (state !== BoundingSphereState$1.FAILED) {
        position = boundingSphereScratch.center;
      } else if (defined(selectedEntity.position)) {
        position = selectedEntity.position.getValue(time, position);
      }
      enableCamera = defined(position);
    }

    const selectionIndicatorViewModel = defined(this._selectionIndicator)
      ? this._selectionIndicator.viewModel
      : undefined;
    if (defined(selectionIndicatorViewModel)) {
      selectionIndicatorViewModel.position = Cartesian3.clone(
        position,
        selectionIndicatorViewModel.position
      );
      selectionIndicatorViewModel.showSelection = showSelection && enableCamera;
      selectionIndicatorViewModel.update();
    }

    const infoBoxViewModel = defined(this._infoBox)
      ? this._infoBox.viewModel
      : undefined;
    if (defined(infoBoxViewModel)) {
      infoBoxViewModel.showInfo = showSelection;
      infoBoxViewModel.enableCamera = enableCamera;
      infoBoxViewModel.isCameraTracking =
        this.trackedEntity === this.selectedEntity;

      if (showSelection) {
        infoBoxViewModel.titleText = defaultValue(
          selectedEntity.name,
          selectedEntity.id
        );
        infoBoxViewModel.description = Property.getValueOrDefault(
          selectedEntity.description,
          time,
          ""
        );
      } else {
        infoBoxViewModel.titleText = "";
        infoBoxViewModel.description = "";
      }
    }
  };

  /**
   * @private
   */
  Viewer.prototype._onEntityCollectionChanged = function (
    collection,
    added,
    removed
  ) {
    const length = removed.length;
    for (let i = 0; i < length; i++) {
      const removedObject = removed[i];
      if (this.trackedEntity === removedObject) {
        this.trackedEntity = undefined;
      }
      if (this.selectedEntity === removedObject) {
        this.selectedEntity = undefined;
      }
    }
  };

  /**
   * @private
   */
  Viewer.prototype._onInfoBoxCameraClicked = function (infoBoxViewModel) {
    if (
      infoBoxViewModel.isCameraTracking &&
      this.trackedEntity === this.selectedEntity
    ) {
      this.trackedEntity = undefined;
    } else {
      const selectedEntity = this.selectedEntity;
      const position = selectedEntity.position;
      if (defined(position)) {
        this.trackedEntity = this.selectedEntity;
      } else {
        this.zoomTo(this.selectedEntity);
      }
    }
  };

  /**
   * @private
   */
  Viewer.prototype._clearTrackedObject = function () {
    this.trackedEntity = undefined;
  };

  /**
   * @private
   */
  Viewer.prototype._onInfoBoxClockClicked = function (infoBoxViewModel) {
    this.selectedEntity = undefined;
  };

  /**
   * @private
   */
  Viewer.prototype._clearObjects = function () {
    this.trackedEntity = undefined;
    this.selectedEntity = undefined;
  };

  /**
   * @private
   */
  Viewer.prototype._onDataSourceChanged = function (dataSource) {
    if (this.clockTrackedDataSource === dataSource) {
      trackDataSourceClock(this.timeline, this.clock, dataSource);
    }
  };

  /**
   * @private
   */
  Viewer.prototype._onDataSourceAdded = function (
    dataSourceCollection,
    dataSource
  ) {
    if (this._automaticallyTrackDataSourceClocks) {
      this.clockTrackedDataSource = dataSource;
    }
    const id = dataSource.entities.id;
    const removalFunc = this._eventHelper.add(
      dataSource.changedEvent,
      Viewer.prototype._onDataSourceChanged,
      this
    );
    this._dataSourceChangedListeners[id] = removalFunc;
  };

  /**
   * @private
   */
  Viewer.prototype._onDataSourceRemoved = function (
    dataSourceCollection,
    dataSource
  ) {
    const resetClock = this.clockTrackedDataSource === dataSource;
    const id = dataSource.entities.id;
    this._dataSourceChangedListeners[id]();
    this._dataSourceChangedListeners[id] = undefined;
    if (resetClock) {
      const numDataSources = dataSourceCollection.length;
      if (this._automaticallyTrackDataSourceClocks && numDataSources > 0) {
        this.clockTrackedDataSource = dataSourceCollection.get(
          numDataSources - 1
        );
      } else {
        this.clockTrackedDataSource = undefined;
      }
    }
  };

  /**
   * Asynchronously sets the camera to view the provided entity, entities, or data source.
   * If the data source is still in the process of loading or the visualization is otherwise still loading,
   * this method waits for the data to be ready before performing the zoom.
   *
   * <p>The offset is heading/pitch/range in the local east-north-up reference frame centered at the center of the bounding sphere.
   * The heading and the pitch angles are defined in the local east-north-up reference frame.
   * The heading is the angle from y axis and increasing towards the x axis. Pitch is the rotation from the xy-plane. Positive pitch
   * angles are above the plane. Negative pitch angles are below the plane. The range is the distance from the center. If the range is
   * zero, a range will be computed such that the whole bounding sphere is visible.</p>
   *
   * <p>In 2D, there must be a top down view. The camera will be placed above the target looking down. The height above the
   * target will be the range. The heading will be determined from the offset. If the heading cannot be
   * determined from the offset, the heading will be north.</p>
   *
   * @param {Entity|Entity[]|EntityCollection|DataSource|ImageryLayer|Cesium3DTileset|TimeDynamicPointCloud|Promise.<Entity|Entity[]|EntityCollection|DataSource|ImageryLayer|Cesium3DTileset|TimeDynamicPointCloud>} target The entity, array of entities, entity collection, data source, Cesium3DTileset, point cloud, or imagery layer to view. You can also pass a promise that resolves to one of the previously mentioned types.
   * @param {HeadingPitchRange} [offset] The offset from the center of the entity in the local east-north-up reference frame.
   * @returns {Promise.<Boolean>} A Promise that resolves to true if the zoom was successful or false if the target is not currently visualized in the scene or the zoom was cancelled.
   */
  Viewer.prototype.zoomTo = function (target, offset) {
    const options = {
      offset: offset,
    };
    return zoomToOrFly(this, target, options, false);
  };

  /**
   * Flies the camera to the provided entity, entities, or data source.
   * If the data source is still in the process of loading or the visualization is otherwise still loading,
   * this method waits for the data to be ready before performing the flight.
   *
   * <p>The offset is heading/pitch/range in the local east-north-up reference frame centered at the center of the bounding sphere.
   * The heading and the pitch angles are defined in the local east-north-up reference frame.
   * The heading is the angle from y axis and increasing towards the x axis. Pitch is the rotation from the xy-plane. Positive pitch
   * angles are above the plane. Negative pitch angles are below the plane. The range is the distance from the center. If the range is
   * zero, a range will be computed such that the whole bounding sphere is visible.</p>
   *
   * <p>In 2D, there must be a top down view. The camera will be placed above the target looking down. The height above the
   * target will be the range. The heading will be determined from the offset. If the heading cannot be
   * determined from the offset, the heading will be north.</p>
   *
   * @param {Entity|Entity[]|EntityCollection|DataSource|ImageryLayer|Cesium3DTileset|TimeDynamicPointCloud|Promise.<Entity|Entity[]|EntityCollection|DataSource|ImageryLayer|Cesium3DTileset|TimeDynamicPointCloud>} target The entity, array of entities, entity collection, data source, Cesium3DTileset, point cloud, or imagery layer to view. You can also pass a promise that resolves to one of the previously mentioned types.
   * @param {Object} [options] Object with the following properties:
   * @param {Number} [options.duration=3.0] The duration of the flight in seconds.
   * @param {Number} [options.maximumHeight] The maximum height at the peak of the flight.
   * @param {HeadingPitchRange} [options.offset] The offset from the target in the local east-north-up reference frame centered at the target.
   * @returns {Promise.<Boolean>} A Promise that resolves to true if the flight was successful or false if the target is not currently visualized in the scene or the flight was cancelled. //TODO: Cleanup entity mentions
   */
  Viewer.prototype.flyTo = function (target, options) {
    return zoomToOrFly(this, target, options, true);
  };

  function zoomToOrFly(that, zoomTarget, options, isFlight) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(zoomTarget)) {
      throw new DeveloperError("zoomTarget is required.");
    }
    //>>includeEnd('debug');

    cancelZoom(that);

    //We can't actually perform the zoom until all visualization is ready and
    //bounding spheres have been computed.  Therefore we create and return
    //a deferred which will be resolved as part of the post-render step in the
    //frame that actually performs the zoom
    const zoomPromise = defer();
    that._zoomPromise = zoomPromise;
    that._zoomIsFlight = isFlight;
    that._zoomOptions = options;

    Promise.resolve(zoomTarget).then(function (zoomTarget) {
      //Only perform the zoom if it wasn't cancelled before the promise resolved.
      if (that._zoomPromise !== zoomPromise) {
        return;
      }

      //If the zoom target is a rectangular imagery in an ImageLayer
      if (zoomTarget instanceof ImageryLayer) {
        zoomTarget
          .getViewableRectangle()
          .then(function (rectangle) {
            return computeFlyToLocationForRectangle(rectangle, that.scene);
          })
          .then(function (position) {
            //Only perform the zoom if it wasn't cancelled before the promise was resolved
            if (that._zoomPromise === zoomPromise) {
              that._zoomTarget = position;
            }
          });
        return;
      }

      //If the zoom target is a Cesium3DTileset
      if (zoomTarget instanceof Cesium3DTileset) {
        that._zoomTarget = zoomTarget;
        return;
      }

      //If the zoom target is a TimeDynamicPointCloud
      if (zoomTarget instanceof TimeDynamicPointCloud) {
        that._zoomTarget = zoomTarget;
        return;
      }

      //If the zoom target is a data source, and it's in the middle of loading, wait for it to finish loading.
      if (zoomTarget.isLoading && defined(zoomTarget.loadingEvent)) {
        const removeEvent = zoomTarget.loadingEvent.addEventListener(function () {
          removeEvent();

          //Only perform the zoom if it wasn't cancelled before the data source finished.
          if (that._zoomPromise === zoomPromise) {
            that._zoomTarget = zoomTarget.entities.values.slice(0);
          }
        });
        return;
      }

      //Zoom target is already an array, just copy it and return.
      if (Array.isArray(zoomTarget)) {
        that._zoomTarget = zoomTarget.slice(0);
        return;
      }

      //If zoomTarget is an EntityCollection, this will retrieve the array
      zoomTarget = defaultValue(zoomTarget.values, zoomTarget);

      //If zoomTarget is a DataSource, this will retrieve the array.
      if (defined(zoomTarget.entities)) {
        zoomTarget = zoomTarget.entities.values;
      }

      //Zoom target is already an array, just copy it and return.
      if (Array.isArray(zoomTarget)) {
        that._zoomTarget = zoomTarget.slice(0);
      } else {
        //Single entity
        that._zoomTarget = [zoomTarget];
      }
    });

    that.scene.requestRender();
    return zoomPromise.promise;
  }

  function clearZoom(viewer) {
    viewer._zoomPromise = undefined;
    viewer._zoomTarget = undefined;
    viewer._zoomOptions = undefined;
  }

  function cancelZoom(viewer) {
    const zoomPromise = viewer._zoomPromise;
    if (defined(zoomPromise)) {
      clearZoom(viewer);
      zoomPromise.resolve(false);
    }
  }

  /**
   * @private
   */
  Viewer.prototype._postRender = function () {
    updateZoomTarget(this);
    updateTrackedEntity(this);
  };

  function updateZoomTarget(viewer) {
    const target = viewer._zoomTarget;
    if (!defined(target) || viewer.scene.mode === SceneMode$1.MORPHING) {
      return;
    }

    const scene = viewer.scene;
    const camera = scene.camera;
    const zoomPromise = viewer._zoomPromise;
    const zoomOptions = defaultValue(viewer._zoomOptions, {});
    let options;

    // If zoomTarget was Cesium3DTileset
    if (target instanceof Cesium3DTileset) {
      return target.readyPromise.then(function () {
        const boundingSphere = target.boundingSphere;
        // If offset was originally undefined then give it base value instead of empty object
        if (!defined(zoomOptions.offset)) {
          zoomOptions.offset = new HeadingPitchRange(
            0.0,
            -0.5,
            boundingSphere.radius
          );
        }

        options = {
          offset: zoomOptions.offset,
          duration: zoomOptions.duration,
          maximumHeight: zoomOptions.maximumHeight,
          complete: function () {
            zoomPromise.resolve(true);
          },
          cancel: function () {
            zoomPromise.resolve(false);
          },
        };

        if (viewer._zoomIsFlight) {
          camera.flyToBoundingSphere(target.boundingSphere, options);
        } else {
          camera.viewBoundingSphere(boundingSphere, zoomOptions.offset);
          camera.lookAtTransform(Matrix4.IDENTITY);

          // Finish the promise
          zoomPromise.resolve(true);
        }

        clearZoom(viewer);
      });
    }

    // If zoomTarget was TimeDynamicPointCloud
    if (target instanceof TimeDynamicPointCloud) {
      return target.readyPromise.then(function () {
        const boundingSphere = target.boundingSphere;
        // If offset was originally undefined then give it base value instead of empty object
        if (!defined(zoomOptions.offset)) {
          zoomOptions.offset = new HeadingPitchRange(
            0.0,
            -0.5,
            boundingSphere.radius
          );
        }

        options = {
          offset: zoomOptions.offset,
          duration: zoomOptions.duration,
          maximumHeight: zoomOptions.maximumHeight,
          complete: function () {
            zoomPromise.resolve(true);
          },
          cancel: function () {
            zoomPromise.resolve(false);
          },
        };

        if (viewer._zoomIsFlight) {
          camera.flyToBoundingSphere(boundingSphere, options);
        } else {
          camera.viewBoundingSphere(boundingSphere, zoomOptions.offset);
          camera.lookAtTransform(Matrix4.IDENTITY);

          // Finish the promise
          zoomPromise.resolve(true);
        }

        clearZoom(viewer);
      });
    }

    // If zoomTarget was an ImageryLayer
    if (target instanceof Cartographic) {
      options = {
        destination: scene.mapProjection.ellipsoid.cartographicToCartesian(
          target
        ),
        duration: zoomOptions.duration,
        maximumHeight: zoomOptions.maximumHeight,
        complete: function () {
          zoomPromise.resolve(true);
        },
        cancel: function () {
          zoomPromise.resolve(false);
        },
      };

      if (viewer._zoomIsFlight) {
        camera.flyTo(options);
      } else {
        camera.setView(options);
        zoomPromise.resolve(true);
      }
      clearZoom(viewer);
      return;
    }

    const entities = target;

    const boundingSpheres = [];
    for (let i = 0, len = entities.length; i < len; i++) {
      const state = viewer._dataSourceDisplay.getBoundingSphere(
        entities[i],
        false,
        boundingSphereScratch
      );

      if (state === BoundingSphereState$1.PENDING) {
        return;
      } else if (state !== BoundingSphereState$1.FAILED) {
        boundingSpheres.push(BoundingSphere.clone(boundingSphereScratch));
      }
    }

    if (boundingSpheres.length === 0) {
      cancelZoom(viewer);
      return;
    }

    //Stop tracking the current entity.
    viewer.trackedEntity = undefined;

    const boundingSphere = BoundingSphere.fromBoundingSpheres(boundingSpheres);

    if (!viewer._zoomIsFlight) {
      camera.viewBoundingSphere(boundingSphere, zoomOptions.offset);
      camera.lookAtTransform(Matrix4.IDENTITY);
      clearZoom(viewer);
      zoomPromise.resolve(true);
    } else {
      clearZoom(viewer);
      camera.flyToBoundingSphere(boundingSphere, {
        duration: zoomOptions.duration,
        maximumHeight: zoomOptions.maximumHeight,
        complete: function () {
          zoomPromise.resolve(true);
        },
        cancel: function () {
          zoomPromise.resolve(false);
        },
        offset: zoomOptions.offset,
      });
    }
  }

  function updateTrackedEntity(viewer) {
    if (!viewer._needTrackedEntityUpdate) {
      return;
    }

    const trackedEntity = viewer._trackedEntity;
    const currentTime = viewer.clock.currentTime;

    //Verify we have a current position at this time. This is only triggered if a position
    //has become undefined after trackedEntity is set but before the boundingSphere has been
    //computed. In this case, we will track the entity once it comes back into existence.
    const currentPosition = Property.getValueOrUndefined(
      trackedEntity.position,
      currentTime
    );

    if (!defined(currentPosition)) {
      return;
    }

    const scene = viewer.scene;

    const state = viewer._dataSourceDisplay.getBoundingSphere(
      trackedEntity,
      false,
      boundingSphereScratch
    );
    if (state === BoundingSphereState$1.PENDING) {
      return;
    }

    const sceneMode = scene.mode;
    if (
      sceneMode === SceneMode$1.COLUMBUS_VIEW ||
      sceneMode === SceneMode$1.SCENE2D
    ) {
      scene.screenSpaceCameraController.enableTranslate = false;
    }

    if (
      sceneMode === SceneMode$1.COLUMBUS_VIEW ||
      sceneMode === SceneMode$1.SCENE3D
    ) {
      scene.screenSpaceCameraController.enableTilt = false;
    }

    const bs =
      state !== BoundingSphereState$1.FAILED ? boundingSphereScratch : undefined;
    viewer._entityView = new EntityView(
      trackedEntity,
      scene,
      scene.mapProjection.ellipsoid
    );
    viewer._entityView.update(currentTime, bs);
    viewer._needTrackedEntityUpdate = false;
  }

  /**
   * A mixin which adds the {@link Cesium3DTilesInspector} widget to the {@link Viewer} widget.
   * Rather than being called directly, this function is normally passed as
   * a parameter to {@link Viewer#extend}, as shown in the example below.
   * @function
   *
   * @param {Viewer} viewer The viewer instance.
   *
   * @example
   * const viewer = new Cesium.Viewer('cesiumContainer');
   * viewer.extend(Cesium.viewerCesium3DTilesInspectorMixin);
   */
  function viewerCesium3DTilesInspectorMixin(viewer) {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object("viewer", viewer);
    //>>includeEnd('debug');

    const container = document.createElement("div");
    container.className = "cesium-viewer-cesium3DTilesInspectorContainer";
    viewer.container.appendChild(container);
    const cesium3DTilesInspector = new Cesium3DTilesInspector(
      container,
      viewer.scene
    );

    Object.defineProperties(viewer, {
      cesium3DTilesInspector: {
        get: function () {
          return cesium3DTilesInspector;
        },
      },
    });
  }

  /**
   * A mixin which adds the CesiumInspector widget to the Viewer widget.
   * Rather than being called directly, this function is normally passed as
   * a parameter to {@link Viewer#extend}, as shown in the example below.
   * @function
   *
   * @param {Viewer} viewer The viewer instance.
   *
   * @exception {DeveloperError} viewer is required.
   *
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Cesium%20Inspector.html|Cesium Sandcastle Cesium Inspector Demo}
   *
   * @example
   * const viewer = new Cesium.Viewer('cesiumContainer');
   * viewer.extend(Cesium.viewerCesiumInspectorMixin);
   */
  function viewerCesiumInspectorMixin(viewer) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(viewer)) {
      throw new DeveloperError("viewer is required.");
    }
    //>>includeEnd('debug');

    const cesiumInspectorContainer = document.createElement("div");
    cesiumInspectorContainer.className = "cesium-viewer-cesiumInspectorContainer";
    viewer.container.appendChild(cesiumInspectorContainer);
    const cesiumInspector = new CesiumInspector(
      cesiumInspectorContainer,
      viewer.scene
    );

    Object.defineProperties(viewer, {
      cesiumInspector: {
        get: function () {
          return cesiumInspector;
        },
      },
    });
  }

  /**
   * A mixin which adds default drag and drop support for CZML files to the Viewer widget.
   * Rather than being called directly, this function is normally passed as
   * a parameter to {@link Viewer#extend}, as shown in the example below.
   * @function viewerDragDropMixin

   * @param {Viewer} viewer The viewer instance.
   * @param {Object} [options] Object with the following properties:
   * @param {Element|String} [options.dropTarget=viewer.container] The DOM element which will serve as the drop target.
   * @param {Boolean} [options.clearOnDrop=true] When true, dropping files will clear all existing data sources first, when false, new data sources will be loaded after the existing ones.
   * @param {Boolean} [options.flyToOnDrop=true] When true, dropping files will fly to the data source once it is loaded.
   * @param {Boolean} [options.clampToGround=true] When true, datasources are clamped to the ground.
   * @param {Proxy} [options.proxy] The proxy to be used for KML network links.
   *
   * @exception {DeveloperError} Element with id <options.dropTarget> does not exist in the document.
   * @exception {DeveloperError} dropTarget is already defined by another mixin.
   * @exception {DeveloperError} dropEnabled is already defined by another mixin.
   * @exception {DeveloperError} dropError is already defined by another mixin.
   * @exception {DeveloperError} clearOnDrop is already defined by another mixin.
   *
   * @example
   * // Add basic drag and drop support and pop up an alert window on error.
   * const viewer = new Cesium.Viewer('cesiumContainer');
   * viewer.extend(Cesium.viewerDragDropMixin);
   * viewer.dropError.addEventListener(function(viewerArg, source, error) {
   *     window.alert('Error processing ' + source + ':' + error);
   * });
   */
  function viewerDragDropMixin(viewer, options) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(viewer)) {
      throw new DeveloperError("viewer is required.");
    }
    if (viewer.hasOwnProperty("dropTarget")) {
      throw new DeveloperError("dropTarget is already defined by another mixin.");
    }
    if (viewer.hasOwnProperty("dropEnabled")) {
      throw new DeveloperError(
        "dropEnabled is already defined by another mixin."
      );
    }
    if (viewer.hasOwnProperty("dropError")) {
      throw new DeveloperError("dropError is already defined by another mixin.");
    }
    if (viewer.hasOwnProperty("clearOnDrop")) {
      throw new DeveloperError(
        "clearOnDrop is already defined by another mixin."
      );
    }
    if (viewer.hasOwnProperty("flyToOnDrop")) {
      throw new DeveloperError(
        "flyToOnDrop is already defined by another mixin."
      );
    }
    //>>includeEnd('debug');

    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    //Local variables to be closed over by defineProperties.
    let dropEnabled = true;
    let flyToOnDrop = defaultValue(options.flyToOnDrop, true);
    const dropError = new Event();
    let clearOnDrop = defaultValue(options.clearOnDrop, true);
    let dropTarget = defaultValue(options.dropTarget, viewer.container);
    let clampToGround = defaultValue(options.clampToGround, true);
    let proxy = options.proxy;

    dropTarget = getElement(dropTarget);

    Object.defineProperties(viewer, {
      /**
       * Gets or sets the element to serve as the drop target.
       * @memberof viewerDragDropMixin.prototype
       * @type {Element}
       */
      dropTarget: {
        //TODO See https://github.com/CesiumGS/cesium/issues/832
        get: function () {
          return dropTarget;
        },
        set: function (value) {
          //>>includeStart('debug', pragmas.debug);
          if (!defined(value)) {
            throw new DeveloperError("value is required.");
          }
          //>>includeEnd('debug');

          unsubscribe(dropTarget, handleDrop);
          dropTarget = value;
          subscribe(dropTarget, handleDrop);
        },
      },

      /**
       * Gets or sets a value indicating if drag and drop support is enabled.
       * @memberof viewerDragDropMixin.prototype
       * @type {Element}
       */
      dropEnabled: {
        get: function () {
          return dropEnabled;
        },
        set: function (value) {
          if (value !== dropEnabled) {
            if (value) {
              subscribe(dropTarget, handleDrop);
            } else {
              unsubscribe(dropTarget, handleDrop);
            }
            dropEnabled = value;
          }
        },
      },

      /**
       * Gets the event that will be raised when an error is encountered during drop processing.
       * @memberof viewerDragDropMixin.prototype
       * @type {Event}
       */
      dropError: {
        get: function () {
          return dropError;
        },
      },

      /**
       * Gets or sets a value indicating if existing data sources should be cleared before adding the newly dropped sources.
       * @memberof viewerDragDropMixin.prototype
       * @type {Boolean}
       */
      clearOnDrop: {
        get: function () {
          return clearOnDrop;
        },
        set: function (value) {
          clearOnDrop = value;
        },
      },

      /**
       * Gets or sets a value indicating if the camera should fly to the data source after it is loaded.
       * @memberof viewerDragDropMixin.prototype
       * @type {Boolean}
       */
      flyToOnDrop: {
        get: function () {
          return flyToOnDrop;
        },
        set: function (value) {
          flyToOnDrop = value;
        },
      },

      /**
       * Gets or sets the proxy to be used for KML.
       * @memberof viewerDragDropMixin.prototype
       * @type {Proxy}
       */
      proxy: {
        get: function () {
          return proxy;
        },
        set: function (value) {
          proxy = value;
        },
      },

      /**
       * Gets or sets a value indicating if the datasources should be clamped to the ground
       * @memberof viewerDragDropMixin.prototype
       * @type {Boolean}
       */
      clampToGround: {
        get: function () {
          return clampToGround;
        },
        set: function (value) {
          clampToGround = value;
        },
      },
    });

    function handleDrop(event) {
      stop(event);

      if (clearOnDrop) {
        viewer.entities.removeAll();
        viewer.dataSources.removeAll();
      }

      const files = event.dataTransfer.files;
      const length = files.length;
      for (let i = 0; i < length; i++) {
        const file = files[i];
        const reader = new FileReader();
        reader.onload = createOnLoadCallback(viewer, file, proxy, clampToGround);
        reader.onerror = createDropErrorCallback(viewer, file);
        reader.readAsText(file);
      }
    }

    //Enable drop by default;
    subscribe(dropTarget, handleDrop);

    //Wrap the destroy function to make sure all events are unsubscribed from
    viewer.destroy = wrapFunction(viewer, viewer.destroy, function () {
      viewer.dropEnabled = false;
    });

    //Specs need access to handleDrop
    viewer._handleDrop = handleDrop;
  }

  function stop(event) {
    event.stopPropagation();
    event.preventDefault();
  }

  function unsubscribe(dropTarget, handleDrop) {
    const currentTarget = dropTarget;
    if (defined(currentTarget)) {
      currentTarget.removeEventListener("drop", handleDrop, false);
      currentTarget.removeEventListener("dragenter", stop, false);
      currentTarget.removeEventListener("dragover", stop, false);
      currentTarget.removeEventListener("dragexit", stop, false);
    }
  }

  function subscribe(dropTarget, handleDrop) {
    dropTarget.addEventListener("drop", handleDrop, false);
    dropTarget.addEventListener("dragenter", stop, false);
    dropTarget.addEventListener("dragover", stop, false);
    dropTarget.addEventListener("dragexit", stop, false);
  }

  function createOnLoadCallback(viewer, file, proxy, clampToGround) {
    const scene = viewer.scene;
    return function (evt) {
      const fileName = file.name;
      try {
        let loadPromise;

        if (/\.czml$/i.test(fileName)) {
          loadPromise = CzmlDataSource.load(JSON.parse(evt.target.result), {
            sourceUri: fileName,
          });
        } else if (
          /\.geojson$/i.test(fileName) ||
          /\.json$/i.test(fileName) ||
          /\.topojson$/i.test(fileName)
        ) {
          loadPromise = GeoJsonDataSource.load(JSON.parse(evt.target.result), {
            sourceUri: fileName,
            clampToGround: clampToGround,
          });
        } else if (/\.(kml|kmz)$/i.test(fileName)) {
          loadPromise = KmlDataSource.load(file, {
            sourceUri: fileName,
            proxy: proxy,
            camera: scene.camera,
            canvas: scene.canvas,
            clampToGround: clampToGround,
            screenOverlayContainer: viewer.container,
          });
        } else if (/\.gpx$/i.test(fileName)) {
          loadPromise = GpxDataSource.load(file, {
            sourceUri: fileName,
            proxy: proxy,
          });
        } else {
          viewer.dropError.raiseEvent(
            viewer,
            fileName,
            `Unrecognized file: ${fileName}`
          );
          return;
        }

        if (defined(loadPromise)) {
          viewer.dataSources
            .add(loadPromise)
            .then(function (dataSource) {
              if (viewer.flyToOnDrop) {
                viewer.flyTo(dataSource);
              }
            })
            .catch(function (error) {
              viewer.dropError.raiseEvent(viewer, fileName, error);
            });
        }
      } catch (error) {
        viewer.dropError.raiseEvent(viewer, fileName, error);
      }
    };
  }

  function createDropErrorCallback(viewer, file) {
    return function (evt) {
      viewer.dropError.raiseEvent(viewer, file.name, evt.target.error);
    };
  }

  /**
   * A mixin which adds the {@link PerformanceWatchdog} widget to the {@link Viewer} widget.
   * Rather than being called directly, this function is normally passed as
   * a parameter to {@link Viewer#extend}, as shown in the example below.
   * @function
   *
   * @param {Viewer} viewer The viewer instance.
   * @param {Object} [options] An object with properties.
   * @param {String} [options.lowFrameRateMessage='This application appears to be performing poorly on your system.  Please try using a different web browser or updating your video drivers.'] The
   *        message to display when a low frame rate is detected.  The message is interpeted as HTML, so make sure
   *        it comes from a trusted source so that your application is not vulnerable to cross-site scripting attacks.
   *
   * @exception {DeveloperError} viewer is required.
   *
   * @example
   * const viewer = new Cesium.Viewer('cesiumContainer');
   * viewer.extend(Cesium.viewerPerformanceWatchdogMixin, {
   *     lowFrameRateMessage : 'Why is this going so <em>slowly</em>?'
   * });
   */
  function viewerPerformanceWatchdogMixin(viewer, options) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(viewer)) {
      throw new DeveloperError("viewer is required.");
    }
    //>>includeEnd('debug');

    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    const performanceWatchdog = new PerformanceWatchdog({
      scene: viewer.scene,
      container: viewer.bottomContainer,
      lowFrameRateMessage: options.lowFrameRateMessage,
    });

    Object.defineProperties(viewer, {
      performanceWatchdog: {
        get: function () {
          return performanceWatchdog;
        },
      },
    });
  }

  // createXXXGeometry functions may return Geometry or a Promise that resolves to Geometry
  // if the function requires access to ApproximateTerrainHeights.
  // For fully synchronous functions, just wrapping the function call in a Promise doesn't
  // handle errors correctly, hence try-catch
  function callAndWrap(workerFunction, parameters, transferableObjects) {
    let resultOrPromise;
    try {
      resultOrPromise = workerFunction(parameters, transferableObjects);
      return resultOrPromise; // errors handled by Promise
    } catch (e) {
      return Promise.reject(e);
    }
  }

  /**
   * Creates an adapter function to allow a calculation function to operate as a Web Worker,
   * paired with TaskProcessor, to receive tasks and return results.
   *
   * @function createTaskProcessorWorker
   *
   * @param {createTaskProcessorWorker.WorkerFunction} workerFunction The calculation function,
   *        which takes parameters and returns a result.
   * @returns {createTaskProcessorWorker.TaskProcessorWorkerFunction} A function that adapts the
   *          calculation function to work as a Web Worker onmessage listener with TaskProcessor.
   *
   *
   * @example
   * function doCalculation(parameters, transferableObjects) {
   *   // calculate some result using the inputs in parameters
   *   return result;
   * }
   *
   * return Cesium.createTaskProcessorWorker(doCalculation);
   * // the resulting function is compatible with TaskProcessor
   *
   * @see TaskProcessor
   * @see {@link http://www.w3.org/TR/workers/|Web Workers}
   * @see {@link http://www.w3.org/TR/html5/common-dom-interfaces.html#transferable-objects|Transferable objects}
   */
  function createTaskProcessorWorker(workerFunction) {
    let postMessage;

    return function (event) {
      const data = event.data;

      const transferableObjects = [];
      const responseMessage = {
        id: data.id,
        result: undefined,
        error: undefined,
      };

      return Promise.resolve(
        callAndWrap(workerFunction, data.parameters, transferableObjects)
      )
        .then(function (result) {
          responseMessage.result = result;
        })
        .catch(function (e) {
          if (e instanceof Error) {
            // Errors can't be posted in a message, copy the properties
            responseMessage.error = {
              name: e.name,
              message: e.message,
              stack: e.stack,
            };
          } else {
            responseMessage.error = e;
          }
        })
        .finally(function () {
          if (!defined(postMessage)) {
            postMessage = defaultValue(self.webkitPostMessage, self.postMessage);
          }

          if (!data.canTransferArrayBuffer) {
            transferableObjects.length = 0;
          }

          try {
            postMessage(responseMessage, transferableObjects);
          } catch (e) {
            // something went wrong trying to post the message, post a simpler
            // error that we can be sure will be cloneable
            responseMessage.result = undefined;
            responseMessage.error = `postMessage failed with error: ${formatError(
            e
          )}\n  with responseMessage: ${JSON.stringify(responseMessage)}`;
            postMessage(responseMessage);
          }
        });
    };
  }

  const VERSION = '1.95';

  exports.AlphaMode = AlphaMode$1;
  exports.AlphaPipelineStage = AlphaPipelineStage;
  exports.Animation = Animation;
  exports.AnimationViewModel = AnimationViewModel;
  exports.Appearance = Appearance;
  exports.ApproximateTerrainHeights = ApproximateTerrainHeights;
  exports.ArcGISTiledElevationTerrainProvider = ArcGISTiledElevationTerrainProvider;
  exports.ArcGisMapServerImageryProvider = ArcGisMapServerImageryProvider;
  exports.ArcType = ArcType$1;
  exports.ArticulationStageType = ArticulationStageType$1;
  exports.AssociativeArray = AssociativeArray;
  exports.AttributeCompression = AttributeCompression;
  exports.AttributeType = AttributeType$1;
  exports.AutoExposure = AutoExposure;
  exports.Autolinker = Autolinker;
  exports.AutomaticUniforms = AutomaticUniforms;
  exports.Axis = Axis$1;
  exports.AxisAlignedBoundingBox = AxisAlignedBoundingBox;
  exports.B3dmLoader = B3dmLoader;
  exports.B3dmParser = B3dmParser;
  exports.BaseLayerPicker = BaseLayerPicker;
  exports.BaseLayerPickerViewModel = BaseLayerPickerViewModel;
  exports.BatchTable = BatchTable;
  exports.BatchTableHierarchy = BatchTableHierarchy;
  exports.BatchTexture = BatchTexture;
  exports.BatchTexturePipelineStage = BatchTexturePipelineStage;
  exports.Batched3DModel3DTileContent = Batched3DModel3DTileContent;
  exports.Billboard = Billboard;
  exports.BillboardCollection = BillboardCollection;
  exports.BillboardGraphics = BillboardGraphics;
  exports.BillboardVisualizer = BillboardVisualizer;
  exports.BingMapsGeocoderService = BingMapsGeocoderService;
  exports.BingMapsImageryProvider = BingMapsImageryProvider;
  exports.BingMapsStyle = BingMapsStyle$1;
  exports.BlendEquation = BlendEquation$1;
  exports.BlendFunction = BlendFunction$1;
  exports.BlendOption = BlendOption$1;
  exports.BlendingState = BlendingState$1;
  exports.BoundingRectangle = BoundingRectangle;
  exports.BoundingSphere = BoundingSphere;
  exports.BoundingSphereState = BoundingSphereState$1;
  exports.BoxEmitter = BoxEmitter;
  exports.BoxGeometry = BoxGeometry;
  exports.BoxGeometryUpdater = BoxGeometryUpdater;
  exports.BoxGraphics = BoxGraphics;
  exports.BoxOutlineGeometry = BoxOutlineGeometry;
  exports.BrdfLutGenerator = BrdfLutGenerator;
  exports.Buffer = Buffer$1;
  exports.BufferLoader = BufferLoader;
  exports.BufferUsage = BufferUsage$1;
  exports.CPUStylingPipelineStage = CPUStylingPipelineStage;
  exports.CallbackProperty = CallbackProperty;
  exports.Camera = Camera;
  exports.CameraEventAggregator = CameraEventAggregator;
  exports.CameraEventType = CameraEventType$1;
  exports.CameraFlightPath = CameraFlightPath;
  exports.Cartesian2 = Cartesian2;
  exports.Cartesian3 = Cartesian3;
  exports.Cartesian4 = Cartesian4;
  exports.Cartographic = Cartographic;
  exports.CartographicGeocoderService = CartographicGeocoderService;
  exports.CatmullRomSpline = CatmullRomSpline;
  exports.Cesium3DContentGroup = Cesium3DContentGroup;
  exports.Cesium3DTile = Cesium3DTile;
  exports.Cesium3DTileBatchTable = Cesium3DTileBatchTable;
  exports.Cesium3DTileColorBlendMode = Cesium3DTileColorBlendMode$1;
  exports.Cesium3DTileContent = Cesium3DTileContent;
  exports.Cesium3DTileContentFactory = Cesium3DTileContentFactory;
  exports.Cesium3DTileContentState = Cesium3DTileContentState$1;
  exports.Cesium3DTileContentType = Cesium3DTileContentType$1;
  exports.Cesium3DTileFeature = Cesium3DTileFeature;
  exports.Cesium3DTileFeatureTable = Cesium3DTileFeatureTable;
  exports.Cesium3DTileOptimizationHint = Cesium3DTileOptimizationHint$1;
  exports.Cesium3DTileOptimizations = Cesium3DTileOptimizations;
  exports.Cesium3DTilePass = Cesium3DTilePass$1;
  exports.Cesium3DTilePassState = Cesium3DTilePassState;
  exports.Cesium3DTilePointFeature = Cesium3DTilePointFeature;
  exports.Cesium3DTileRefine = Cesium3DTileRefine$1;
  exports.Cesium3DTileStyle = Cesium3DTileStyle;
  exports.Cesium3DTileStyleEngine = Cesium3DTileStyleEngine;
  exports.Cesium3DTilesInspector = Cesium3DTilesInspector;
  exports.Cesium3DTilesInspectorViewModel = Cesium3DTilesInspectorViewModel;
  exports.Cesium3DTileset = Cesium3DTileset;
  exports.Cesium3DTilesetCache = Cesium3DTilesetCache;
  exports.Cesium3DTilesetGraphics = Cesium3DTilesetGraphics;
  exports.Cesium3DTilesetHeatmap = Cesium3DTilesetHeatmap;
  exports.Cesium3DTilesetMetadata = Cesium3DTilesetMetadata;
  exports.Cesium3DTilesetMostDetailedTraversal = Cesium3DTilesetMostDetailedTraversal;
  exports.Cesium3DTilesetStatistics = Cesium3DTilesetStatistics;
  exports.Cesium3DTilesetTraversal = Cesium3DTilesetTraversal;
  exports.Cesium3DTilesetVisualizer = Cesium3DTilesetVisualizer;
  exports.CesiumInspector = CesiumInspector;
  exports.CesiumInspectorViewModel = CesiumInspectorViewModel;
  exports.CesiumTerrainProvider = CesiumTerrainProvider;
  exports.CesiumWidget = CesiumWidget;
  exports.Check = Check;
  exports.CheckerboardMaterialProperty = CheckerboardMaterialProperty;
  exports.CircleEmitter = CircleEmitter;
  exports.CircleGeometry = CircleGeometry;
  exports.CircleOutlineGeometry = CircleOutlineGeometry;
  exports.ClassificationModel = ClassificationModel;
  exports.ClassificationPrimitive = ClassificationPrimitive;
  exports.ClassificationType = ClassificationType$1;
  exports.ClearCommand = ClearCommand;
  exports.ClippingPlane = ClippingPlane;
  exports.ClippingPlaneCollection = ClippingPlaneCollection;
  exports.Clock = Clock;
  exports.ClockRange = ClockRange$1;
  exports.ClockStep = ClockStep$1;
  exports.ClockViewModel = ClockViewModel;
  exports.CloudCollection = CloudCollection;
  exports.CloudType = CloudType$1;
  exports.Color = Color;
  exports.ColorBlendMode = ColorBlendMode$1;
  exports.ColorGeometryInstanceAttribute = ColorGeometryInstanceAttribute;
  exports.ColorMaterialProperty = ColorMaterialProperty;
  exports.Command = Command;
  exports.ComponentDatatype = ComponentDatatype$1;
  exports.Composite3DTileContent = Composite3DTileContent;
  exports.CompositeEntityCollection = CompositeEntityCollection;
  exports.CompositeMaterialProperty = CompositeMaterialProperty;
  exports.CompositePositionProperty = CompositePositionProperty;
  exports.CompositeProperty = CompositeProperty;
  exports.CompressedTextureBuffer = CompressedTextureBuffer;
  exports.ComputeCommand = ComputeCommand;
  exports.ComputeEngine = ComputeEngine;
  exports.ConditionsExpression = ConditionsExpression;
  exports.ConeEmitter = ConeEmitter;
  exports.ConstantPositionProperty = ConstantPositionProperty;
  exports.ConstantProperty = ConstantProperty;
  exports.ConstantSpline = ConstantSpline;
  exports.ContentMetadata = ContentMetadata;
  exports.Context = Context;
  exports.ContextLimits = ContextLimits;
  exports.CoplanarPolygonGeometry = CoplanarPolygonGeometry;
  exports.CoplanarPolygonGeometryLibrary = CoplanarPolygonGeometryLibrary;
  exports.CoplanarPolygonOutlineGeometry = CoplanarPolygonOutlineGeometry;
  exports.CornerType = CornerType$1;
  exports.CorridorGeometry = CorridorGeometry;
  exports.CorridorGeometryLibrary = CorridorGeometryLibrary;
  exports.CorridorGeometryUpdater = CorridorGeometryUpdater;
  exports.CorridorGraphics = CorridorGraphics;
  exports.CorridorOutlineGeometry = CorridorOutlineGeometry;
  exports.Credit = Credit;
  exports.CreditDisplay = CreditDisplay;
  exports.CubeMap = CubeMap;
  exports.CubeMapFace = CubeMapFace;
  exports.CubicRealPolynomial = CubicRealPolynomial;
  exports.CullFace = CullFace$1;
  exports.CullingVolume = CullingVolume;
  exports.CumulusCloud = CumulusCloud;
  exports.CustomDataSource = CustomDataSource;
  exports.CustomHeightmapTerrainProvider = CustomHeightmapTerrainProvider;
  exports.CustomShader = CustomShader;
  exports.CustomShaderMode = CustomShaderMode$1;
  exports.CustomShaderPipelineStage = CustomShaderPipelineStage;
  exports.CylinderGeometry = CylinderGeometry;
  exports.CylinderGeometryLibrary = CylinderGeometryLibrary;
  exports.CylinderGeometryUpdater = CylinderGeometryUpdater;
  exports.CylinderGraphics = CylinderGraphics;
  exports.CylinderOutlineGeometry = CylinderOutlineGeometry;
  exports.CzmlDataSource = CzmlDataSource;
  exports.DataSource = DataSource;
  exports.DataSourceClock = DataSourceClock;
  exports.DataSourceCollection = DataSourceCollection;
  exports.DataSourceDisplay = DataSourceDisplay;
  exports.DebugAppearance = DebugAppearance;
  exports.DebugCameraPrimitive = DebugCameraPrimitive;
  exports.DebugInspector = DebugInspector;
  exports.DebugModelMatrixPrimitive = DebugModelMatrixPrimitive;
  exports.DefaultProxy = DefaultProxy;
  exports.DepthFunction = DepthFunction$1;
  exports.DepthPlane = DepthPlane;
  exports.DequantizationPipelineStage = DequantizationPipelineStage;
  exports.DerivedCommand = DerivedCommand;
  exports.DeveloperError = DeveloperError;
  exports.DeviceOrientationCameraController = DeviceOrientationCameraController;
  exports.DirectionalLight = DirectionalLight;
  exports.DiscardEmptyTileImagePolicy = DiscardEmptyTileImagePolicy;
  exports.DiscardMissingTileImagePolicy = DiscardMissingTileImagePolicy;
  exports.DistanceDisplayCondition = DistanceDisplayCondition;
  exports.DistanceDisplayConditionGeometryInstanceAttribute = DistanceDisplayConditionGeometryInstanceAttribute;
  exports.DoubleEndedPriorityQueue = DoubleEndedPriorityQueue;
  exports.DoublyLinkedList = DoublyLinkedList;
  exports.DracoLoader = DracoLoader;
  exports.DrawCommand = DrawCommand;
  exports.DynamicGeometryBatch = DynamicGeometryBatch;
  exports.DynamicGeometryUpdater = DynamicGeometryUpdater$1;
  exports.EarthOrientationParameters = EarthOrientationParameters;
  exports.EarthOrientationParametersSample = EarthOrientationParametersSample;
  exports.EasingFunction = EasingFunction$1;
  exports.EllipseGeometry = EllipseGeometry;
  exports.EllipseGeometryLibrary = EllipseGeometryLibrary;
  exports.EllipseGeometryUpdater = EllipseGeometryUpdater;
  exports.EllipseGraphics = EllipseGraphics;
  exports.EllipseOutlineGeometry = EllipseOutlineGeometry;
  exports.Ellipsoid = Ellipsoid;
  exports.EllipsoidGeodesic = EllipsoidGeodesic;
  exports.EllipsoidGeometry = EllipsoidGeometry;
  exports.EllipsoidGeometryUpdater = EllipsoidGeometryUpdater;
  exports.EllipsoidGraphics = EllipsoidGraphics;
  exports.EllipsoidOutlineGeometry = EllipsoidOutlineGeometry;
  exports.EllipsoidPrimitive = EllipsoidPrimitive;
  exports.EllipsoidRhumbLine = EllipsoidRhumbLine;
  exports.EllipsoidSurfaceAppearance = EllipsoidSurfaceAppearance;
  exports.EllipsoidTangentPlane = EllipsoidTangentPlane;
  exports.EllipsoidTerrainProvider = EllipsoidTerrainProvider;
  exports.EllipsoidalOccluder = EllipsoidalOccluder;
  exports.Empty3DTileContent = Empty3DTileContent;
  exports.EncodedCartesian3 = EncodedCartesian3;
  exports.Entity = Entity;
  exports.EntityCluster = EntityCluster;
  exports.EntityCollection = EntityCollection;
  exports.EntityView = EntityView;
  exports.Event = Event;
  exports.EventHelper = EventHelper;
  exports.ExperimentalFeatures = ExperimentalFeatures;
  exports.Expression = Expression;
  exports.ExpressionNodeType = ExpressionNodeType$1;
  exports.ExtrapolationType = ExtrapolationType$1;
  exports.FeatureDetection = FeatureDetection;
  exports.FeatureIdPipelineStage = FeatureIdPipelineStage;
  exports.Fog = Fog;
  exports.ForEach = ForEach;
  exports.FrameRateMonitor = FrameRateMonitor;
  exports.FrameState = FrameState;
  exports.Framebuffer = Framebuffer;
  exports.FramebufferManager = FramebufferManager;
  exports.FrustumCommands = FrustumCommands;
  exports.FrustumGeometry = FrustumGeometry;
  exports.FrustumOutlineGeometry = FrustumOutlineGeometry;
  exports.Fullscreen = Fullscreen;
  exports.FullscreenButton = FullscreenButton;
  exports.FullscreenButtonViewModel = FullscreenButtonViewModel;
  exports.GeoJsonDataSource = GeoJsonDataSource;
  exports.GeoJsonLoader = GeoJsonLoader;
  exports.GeocodeType = GeocodeType$1;
  exports.Geocoder = Geocoder;
  exports.GeocoderService = GeocoderService;
  exports.GeocoderViewModel = GeocoderViewModel;
  exports.GeographicProjection = GeographicProjection;
  exports.GeographicTilingScheme = GeographicTilingScheme;
  exports.Geometry = Geometry;
  exports.Geometry3DTileContent = Geometry3DTileContent;
  exports.GeometryAttribute = GeometryAttribute;
  exports.GeometryAttributes = GeometryAttributes;
  exports.GeometryFactory = GeometryFactory;
  exports.GeometryInstance = GeometryInstance;
  exports.GeometryInstanceAttribute = GeometryInstanceAttribute;
  exports.GeometryOffsetAttribute = GeometryOffsetAttribute$1;
  exports.GeometryPipeline = GeometryPipeline;
  exports.GeometryPipelineStage = GeometryPipelineStage;
  exports.GeometryType = GeometryType$1;
  exports.GeometryUpdater = GeometryUpdater;
  exports.GeometryVisualizer = GeometryVisualizer;
  exports.GetFeatureInfoFormat = GetFeatureInfoFormat;
  exports.Globe = Globe;
  exports.GlobeDepth = GlobeDepth;
  exports.GlobeSurfaceShaderSet = GlobeSurfaceShaderSet;
  exports.GlobeSurfaceTile = GlobeSurfaceTile;
  exports.GlobeSurfaceTileProvider = GlobeSurfaceTileProvider;
  exports.GlobeTranslucency = GlobeTranslucency;
  exports.GlobeTranslucencyFramebuffer = GlobeTranslucencyFramebuffer;
  exports.GlobeTranslucencyState = GlobeTranslucencyState;
  exports.GltfBufferViewLoader = GltfBufferViewLoader;
  exports.GltfDracoLoader = GltfDracoLoader;
  exports.GltfImageLoader = GltfImageLoader;
  exports.GltfIndexBufferLoader = GltfIndexBufferLoader;
  exports.GltfJsonLoader = GltfJsonLoader;
  exports.GltfLoader = GltfLoader;
  exports.GltfLoaderUtil = GltfLoaderUtil;
  exports.GltfStructuralMetadataLoader = GltfStructuralMetadataLoader;
  exports.GltfTextureLoader = GltfTextureLoader;
  exports.GltfVertexBufferLoader = GltfVertexBufferLoader;
  exports.GoogleEarthEnterpriseImageryProvider = GoogleEarthEnterpriseImageryProvider;
  exports.GoogleEarthEnterpriseMapsProvider = GoogleEarthEnterpriseMapsProvider;
  exports.GoogleEarthEnterpriseMetadata = GoogleEarthEnterpriseMetadata;
  exports.GoogleEarthEnterpriseTerrainData = GoogleEarthEnterpriseTerrainData;
  exports.GoogleEarthEnterpriseTerrainProvider = GoogleEarthEnterpriseTerrainProvider;
  exports.GoogleEarthEnterpriseTileInformation = GoogleEarthEnterpriseTileInformation;
  exports.GpxDataSource = GpxDataSource;
  exports.GregorianDate = GregorianDate;
  exports.GridImageryProvider = GridImageryProvider;
  exports.GridMaterialProperty = GridMaterialProperty;
  exports.GroundGeometryUpdater = GroundGeometryUpdater;
  exports.GroundPolylineGeometry = GroundPolylineGeometry;
  exports.GroundPolylinePrimitive = GroundPolylinePrimitive;
  exports.GroundPrimitive = GroundPrimitive;
  exports.GroupMetadata = GroupMetadata;
  exports.HeadingPitchRange = HeadingPitchRange;
  exports.HeadingPitchRoll = HeadingPitchRoll;
  exports.Heap = Heap;
  exports.HeightReference = HeightReference$1;
  exports.HeightmapEncoding = HeightmapEncoding$1;
  exports.HeightmapTerrainData = HeightmapTerrainData;
  exports.HeightmapTessellator = HeightmapTessellator;
  exports.HermitePolynomialApproximation = HermitePolynomialApproximation;
  exports.HermiteSpline = HermiteSpline;
  exports.HilbertOrder = HilbertOrder;
  exports.HomeButton = HomeButton;
  exports.HomeButtonViewModel = HomeButtonViewModel;
  exports.HorizontalOrigin = HorizontalOrigin$1;
  exports.I3dmLoader = I3dmLoader;
  exports.I3dmParser = I3dmParser;
  exports.Iau2000Orientation = Iau2000Orientation;
  exports.Iau2006XysData = Iau2006XysData;
  exports.Iau2006XysSample = Iau2006XysSample;
  exports.IauOrientationAxes = IauOrientationAxes;
  exports.IauOrientationParameters = IauOrientationParameters;
  exports.ImageBasedLighting = ImageBasedLighting;
  exports.ImageBasedLightingPipelineStage = ImageBasedLightingPipelineStage;
  exports.ImageMaterialProperty = ImageMaterialProperty;
  exports.Imagery = Imagery;
  exports.ImageryLayer = ImageryLayer;
  exports.ImageryLayerCollection = ImageryLayerCollection;
  exports.ImageryLayerFeatureInfo = ImageryLayerFeatureInfo;
  exports.ImageryProvider = ImageryProvider;
  exports.ImageryState = ImageryState$1;
  exports.Implicit3DTileContent = Implicit3DTileContent;
  exports.ImplicitAvailabilityBitstream = ImplicitAvailabilityBitstream;
  exports.ImplicitMetadataView = ImplicitMetadataView;
  exports.ImplicitSubdivisionScheme = ImplicitSubdivisionScheme$1;
  exports.ImplicitSubtree = ImplicitSubtree;
  exports.ImplicitSubtreeMetadata = ImplicitSubtreeMetadata;
  exports.ImplicitTileCoordinates = ImplicitTileCoordinates;
  exports.ImplicitTileset = ImplicitTileset;
  exports.IndexDatatype = IndexDatatype$1;
  exports.InfoBox = InfoBox;
  exports.InfoBoxViewModel = InfoBoxViewModel;
  exports.InspectorShared = InspectorShared;
  exports.InstanceAttributeSemantic = InstanceAttributeSemantic$1;
  exports.Instanced3DModel3DTileContent = Instanced3DModel3DTileContent;
  exports.InstancingPipelineStage = InstancingPipelineStage;
  exports.InterpolationAlgorithm = InterpolationAlgorithm;
  exports.InterpolationType = InterpolationType$1;
  exports.Intersect = Intersect$1;
  exports.IntersectionTests = IntersectionTests;
  exports.Intersections2D = Intersections2D;
  exports.Interval = Interval;
  exports.InvertClassification = InvertClassification;
  exports.Ion = Ion;
  exports.IonGeocoderService = IonGeocoderService;
  exports.IonImageryProvider = IonImageryProvider;
  exports.IonResource = IonResource;
  exports.IonWorldImageryStyle = IonWorldImageryStyle$1;
  exports.Iso8601 = Iso8601;
  exports.JobScheduler = JobScheduler;
  exports.JobType = JobType$1;
  exports.JsonMetadataTable = JsonMetadataTable;
  exports.JulianDate = JulianDate;
  exports.KTX2Transcoder = KTX2Transcoder;
  exports.KeyboardEventModifier = KeyboardEventModifier$1;
  exports.KmlCamera = KmlCamera;
  exports.KmlDataSource = KmlDataSource;
  exports.KmlLookAt = KmlLookAt;
  exports.KmlTour = KmlTour;
  exports.KmlTourFlyTo = KmlTourFlyTo;
  exports.KmlTourWait = KmlTourWait;
  exports.Label = Label;
  exports.LabelCollection = LabelCollection;
  exports.LabelGraphics = LabelGraphics;
  exports.LabelStyle = LabelStyle$1;
  exports.LabelVisualizer = LabelVisualizer;
  exports.LagrangePolynomialApproximation = LagrangePolynomialApproximation;
  exports.LeapSecond = LeapSecond;
  exports.Light = Light;
  exports.LightingModel = LightingModel$1;
  exports.LightingPipelineStage = LightingPipelineStage;
  exports.LinearApproximation = LinearApproximation;
  exports.LinearSpline = LinearSpline;
  exports.ManagedArray = ManagedArray;
  exports.MapMode2D = MapMode2D$1;
  exports.MapProjection = MapProjection;
  exports.MapboxImageryProvider = MapboxImageryProvider;
  exports.MapboxStyleImageryProvider = MapboxStyleImageryProvider;
  exports.Material = Material$4;
  exports.MaterialAppearance = MaterialAppearance;
  exports.MaterialPipelineStage = MaterialPipelineStage;
  exports.MaterialProperty = MaterialProperty;
  exports.Math = CesiumMath;
  exports.Matrix2 = Matrix2;
  exports.Matrix3 = Matrix3;
  exports.Matrix4 = Matrix4;
  exports.MetadataClass = MetadataClass;
  exports.MetadataClassProperty = MetadataClassProperty;
  exports.MetadataComponentType = MetadataComponentType$1;
  exports.MetadataEntity = MetadataEntity;
  exports.MetadataEnum = MetadataEnum;
  exports.MetadataEnumValue = MetadataEnumValue;
  exports.MetadataPipelineStage = MetadataPipelineStage;
  exports.MetadataSchema = MetadataSchema;
  exports.MetadataSchemaLoader = MetadataSchemaLoader;
  exports.MetadataSemantic = MetadataSemantic$1;
  exports.MetadataTable = MetadataTable;
  exports.MetadataTableProperty = MetadataTableProperty;
  exports.MetadataType = MetadataType$1;
  exports.MipmapHint = MipmapHint$1;
  exports.Model = Model;
  exports.ModelAlphaOptions = ModelAlphaOptions;
  exports.ModelAnimation = ModelAnimation;
  exports.ModelAnimationCache = ModelAnimationCache;
  exports.ModelAnimationCollection = ModelAnimationCollection;
  exports.ModelAnimationLoop = ModelAnimationLoop$1;
  exports.ModelAnimationState = ModelAnimationState;
  exports.ModelClippingPlanesPipelineStage = ModelClippingPlanesPipelineStage;
  exports.ModelColorPipelineStage = ModelColorPipelineStage;
  exports.ModelComponents = ModelComponents;
  exports.ModelExperimental = ModelExperimental;
  exports.ModelExperimental3DTileContent = ModelExperimental3DTileContent;
  exports.ModelExperimentalAnimation = ModelExperimentalAnimation;
  exports.ModelExperimentalAnimationChannel = ModelExperimentalAnimationChannel;
  exports.ModelExperimentalAnimationCollection = ModelExperimentalAnimationCollection;
  exports.ModelExperimentalArticulation = ModelExperimentalArticulation;
  exports.ModelExperimentalArticulationStage = ModelExperimentalArticulationStage;
  exports.ModelExperimentalDrawCommand = ModelExperimentalDrawCommand;
  exports.ModelExperimentalNode = ModelExperimentalNode;
  exports.ModelExperimentalPrimitive = ModelExperimentalPrimitive;
  exports.ModelExperimentalSceneGraph = ModelExperimentalSceneGraph;
  exports.ModelExperimentalSkin = ModelExperimentalSkin;
  exports.ModelExperimentalStatistics = ModelExperimentalStatistics;
  exports.ModelExperimentalType = ModelExperimentalType$1;
  exports.ModelExperimentalUtility = ModelExperimentalUtility;
  exports.ModelFeature = ModelFeature;
  exports.ModelFeatureTable = ModelFeatureTable;
  exports.ModelGraphics = ModelGraphics;
  exports.ModelInstance = ModelInstance;
  exports.ModelInstanceCollection = ModelInstanceCollection;
  exports.ModelLightingOptions = ModelLightingOptions;
  exports.ModelLoadResources = ModelLoadResources;
  exports.ModelMaterial = ModelMaterial;
  exports.ModelMatrixUpdateStage = ModelMatrixUpdateStage;
  exports.ModelMesh = ModelMesh;
  exports.ModelNode = ModelNode;
  exports.ModelOutlineLoader = ModelOutlineLoader;
  exports.ModelRenderResources = ModelRenderResources;
  exports.ModelSilhouettePipelineStage = ModelSilhouettePipelineStage;
  exports.ModelSplitterPipelineStage = ModelSplitterPipelineStage;
  exports.ModelUtility = ModelUtility;
  exports.ModelVisualizer = ModelVisualizer;
  exports.Moon = Moon;
  exports.MorphTargetsPipelineStage = MorphTargetsPipelineStage;
  exports.MorphWeightSpline = MorphWeightSpline;
  exports.MortonOrder = MortonOrder;
  exports.Multiple3DTileContent = Multiple3DTileContent;
  exports.MultisampleFramebuffer = MultisampleFramebuffer;
  exports.NavigationHelpButton = NavigationHelpButton;
  exports.NavigationHelpButtonViewModel = NavigationHelpButtonViewModel;
  exports.NearFarScalar = NearFarScalar;
  exports.NeverTileDiscardPolicy = NeverTileDiscardPolicy;
  exports.NodeRenderResources = NodeRenderResources;
  exports.NodeStatisticsPipelineStage = NodeStatisticsPipelineStage;
  exports.NodeTransformationProperty = NodeTransformationProperty;
  exports.OIT = OIT;
  exports.Occluder = Occluder;
  exports.OctahedralProjectedCubeMap = OctahedralProjectedCubeMap;
  exports.OffsetGeometryInstanceAttribute = OffsetGeometryInstanceAttribute;
  exports.OpenCageGeocoderService = OpenCageGeocoderService;
  exports.OpenStreetMapImageryProvider = OpenStreetMapImageryProvider;
  exports.OrderedGroundPrimitiveCollection = OrderedGroundPrimitiveCollection;
  exports.OrientedBoundingBox = OrientedBoundingBox;
  exports.OrthographicFrustum = OrthographicFrustum;
  exports.OrthographicOffCenterFrustum = OrthographicOffCenterFrustum;
  exports.Packable = Packable;
  exports.PackableForInterpolation = PackableForInterpolation;
  exports.Particle = Particle;
  exports.ParticleBurst = ParticleBurst;
  exports.ParticleEmitter = ParticleEmitter;
  exports.ParticleSystem = ParticleSystem;
  exports.Pass = Pass$1;
  exports.PassState = PassState;
  exports.PathGraphics = PathGraphics;
  exports.PathVisualizer = PathVisualizer;
  exports.PeliasGeocoderService = PeliasGeocoderService;
  exports.PerInstanceColorAppearance = PerInstanceColorAppearance;
  exports.PerformanceDisplay = PerformanceDisplay;
  exports.PerformanceWatchdog = PerformanceWatchdog;
  exports.PerformanceWatchdogViewModel = PerformanceWatchdogViewModel;
  exports.PerspectiveFrustum = PerspectiveFrustum;
  exports.PerspectiveOffCenterFrustum = PerspectiveOffCenterFrustum;
  exports.PickDepth = PickDepth;
  exports.PickDepthFramebuffer = PickDepthFramebuffer;
  exports.PickFramebuffer = PickFramebuffer;
  exports.Picking = Picking;
  exports.PickingPipelineStage = PickingPipelineStage;
  exports.PinBuilder = PinBuilder;
  exports.PixelDatatype = PixelDatatype$1;
  exports.PixelFormat = PixelFormat$1;
  exports.Plane = Plane;
  exports.PlaneGeometry = PlaneGeometry;
  exports.PlaneGeometryUpdater = PlaneGeometryUpdater;
  exports.PlaneGraphics = PlaneGraphics;
  exports.PlaneOutlineGeometry = PlaneOutlineGeometry;
  exports.PntsLoader = PntsLoader;
  exports.PntsParser = PntsParser;
  exports.PointCloud = PointCloud;
  exports.PointCloud3DTileContent = PointCloud3DTileContent;
  exports.PointCloudAttenuationPipelineStage = PointCloudAttenuationPipelineStage;
  exports.PointCloudEyeDomeLighting = PointCloudEyeDomeLighting;
  exports.PointCloudShading = PointCloudShading;
  exports.PointGraphics = PointGraphics;
  exports.PointPrimitive = PointPrimitive;
  exports.PointPrimitiveCollection = PointPrimitiveCollection;
  exports.PointVisualizer = PointVisualizer;
  exports.PolygonGeometry = PolygonGeometry;
  exports.PolygonGeometryLibrary = PolygonGeometryLibrary;
  exports.PolygonGeometryUpdater = PolygonGeometryUpdater;
  exports.PolygonGraphics = PolygonGraphics;
  exports.PolygonHierarchy = PolygonHierarchy;
  exports.PolygonOutlineGeometry = PolygonOutlineGeometry;
  exports.PolygonPipeline = PolygonPipeline;
  exports.Polyline = Polyline;
  exports.PolylineArrowMaterialProperty = PolylineArrowMaterialProperty;
  exports.PolylineCollection = PolylineCollection;
  exports.PolylineColorAppearance = PolylineColorAppearance;
  exports.PolylineDashMaterialProperty = PolylineDashMaterialProperty;
  exports.PolylineGeometry = PolylineGeometry;
  exports.PolylineGeometryUpdater = PolylineGeometryUpdater;
  exports.PolylineGlowMaterialProperty = PolylineGlowMaterialProperty;
  exports.PolylineGraphics = PolylineGraphics;
  exports.PolylineMaterialAppearance = PolylineMaterialAppearance;
  exports.PolylineOutlineMaterialProperty = PolylineOutlineMaterialProperty;
  exports.PolylinePipeline = PolylinePipeline;
  exports.PolylineVisualizer = PolylineVisualizer;
  exports.PolylineVolumeGeometry = PolylineVolumeGeometry;
  exports.PolylineVolumeGeometryLibrary = PolylineVolumeGeometryLibrary;
  exports.PolylineVolumeGeometryUpdater = PolylineVolumeGeometryUpdater;
  exports.PolylineVolumeGraphics = PolylineVolumeGraphics;
  exports.PolylineVolumeOutlineGeometry = PolylineVolumeOutlineGeometry;
  exports.PositionProperty = PositionProperty;
  exports.PositionPropertyArray = PositionPropertyArray;
  exports.PostProcessStage = PostProcessStage;
  exports.PostProcessStageCollection = PostProcessStageCollection;
  exports.PostProcessStageComposite = PostProcessStageComposite;
  exports.PostProcessStageLibrary = PostProcessStageLibrary;
  exports.PostProcessStageSampleMode = PostProcessStageSampleMode;
  exports.PostProcessStageTextureCache = PostProcessStageTextureCache;
  exports.Primitive = Primitive$3;
  exports.PrimitiveCollection = PrimitiveCollection;
  exports.PrimitivePipeline = PrimitivePipeline;
  exports.PrimitiveRenderResources = PrimitiveRenderResources;
  exports.PrimitiveState = PrimitiveState$1;
  exports.PrimitiveStatisticsPipelineStage = PrimitiveStatisticsPipelineStage;
  exports.PrimitiveType = PrimitiveType$1;
  exports.ProjectionPicker = ProjectionPicker;
  exports.ProjectionPickerViewModel = ProjectionPickerViewModel;
  exports.Property = Property;
  exports.PropertyArray = PropertyArray;
  exports.PropertyAttribute = PropertyAttribute;
  exports.PropertyAttributeProperty = PropertyAttributeProperty;
  exports.PropertyBag = PropertyBag;
  exports.PropertyTable = PropertyTable;
  exports.PropertyTexture = PropertyTexture;
  exports.PropertyTextureProperty = PropertyTextureProperty;
  exports.ProviderViewModel = ProviderViewModel;
  exports.Proxy = Proxy$1;
  exports.QuadraticRealPolynomial = QuadraticRealPolynomial;
  exports.QuadtreeOccluders = QuadtreeOccluders;
  exports.QuadtreePrimitive = QuadtreePrimitive;
  exports.QuadtreeTile = QuadtreeTile;
  exports.QuadtreeTileLoadState = QuadtreeTileLoadState$1;
  exports.QuadtreeTileProvider = QuadtreeTileProvider;
  exports.QuantizedMeshTerrainData = QuantizedMeshTerrainData;
  exports.QuarticRealPolynomial = QuarticRealPolynomial;
  exports.Quaternion = Quaternion;
  exports.QuaternionSpline = QuaternionSpline;
  exports.Queue = Queue;
  exports.Ray = Ray;
  exports.Rectangle = Rectangle;
  exports.RectangleCollisionChecker = RectangleCollisionChecker;
  exports.RectangleGeometry = RectangleGeometry;
  exports.RectangleGeometryLibrary = RectangleGeometryLibrary;
  exports.RectangleGeometryUpdater = RectangleGeometryUpdater;
  exports.RectangleGraphics = RectangleGraphics;
  exports.RectangleOutlineGeometry = RectangleOutlineGeometry;
  exports.ReferenceFrame = ReferenceFrame$1;
  exports.ReferenceProperty = ReferenceProperty;
  exports.RenderState = RenderState;
  exports.Renderbuffer = Renderbuffer;
  exports.RenderbufferFormat = RenderbufferFormat$1;
  exports.Request = Request;
  exports.RequestErrorEvent = RequestErrorEvent;
  exports.RequestScheduler = RequestScheduler;
  exports.RequestState = RequestState$1;
  exports.RequestType = RequestType$1;
  exports.Resource = Resource;
  exports.ResourceCache = ResourceCache;
  exports.ResourceCacheKey = ResourceCacheKey;
  exports.ResourceCacheStatistics = ResourceCacheStatistics;
  exports.ResourceLoader = ResourceLoader;
  exports.ResourceLoaderState = ResourceLoaderState$1;
  exports.Rotation = Rotation;
  exports.RuntimeError = RuntimeError;
  exports.S2Cell = S2Cell;
  exports.SDFSettings = SDFSettings$1;
  exports.SampledPositionProperty = SampledPositionProperty;
  exports.SampledProperty = SampledProperty;
  exports.Sampler = Sampler;
  exports.ScaledPositionProperty = ScaledPositionProperty;
  exports.Scene = Scene;
  exports.SceneFramebuffer = SceneFramebuffer;
  exports.SceneMode = SceneMode$1;
  exports.SceneMode2DPipelineStage = SceneMode2DPipelineStage;
  exports.SceneModePicker = SceneModePicker;
  exports.SceneModePickerViewModel = SceneModePickerViewModel;
  exports.SceneTransforms = SceneTransforms;
  exports.SceneTransitioner = SceneTransitioner;
  exports.ScreenSpaceCameraController = ScreenSpaceCameraController;
  exports.ScreenSpaceEventHandler = ScreenSpaceEventHandler;
  exports.ScreenSpaceEventType = ScreenSpaceEventType$1;
  exports.SelectedFeatureIdPipelineStage = SelectedFeatureIdPipelineStage;
  exports.SelectionIndicator = SelectionIndicator;
  exports.SelectionIndicatorViewModel = SelectionIndicatorViewModel;
  exports.ShaderBuilder = ShaderBuilder;
  exports.ShaderCache = ShaderCache;
  exports.ShaderDestination = ShaderDestination$1;
  exports.ShaderFunction = ShaderFunction;
  exports.ShaderProgram = ShaderProgram;
  exports.ShaderSource = ShaderSource;
  exports.ShaderStruct = ShaderStruct;
  exports.ShadowMap = ShadowMap;
  exports.ShadowMapShader = ShadowMapShader;
  exports.ShadowMode = ShadowMode$1;
  exports.ShadowVolumeAppearance = ShadowVolumeAppearance;
  exports.ShowGeometryInstanceAttribute = ShowGeometryInstanceAttribute;
  exports.Simon1994PlanetaryPositions = Simon1994PlanetaryPositions;
  exports.SimplePolylineGeometry = SimplePolylineGeometry;
  exports.SingleTileImageryProvider = SingleTileImageryProvider;
  exports.SkinningPipelineStage = SkinningPipelineStage;
  exports.SkyAtmosphere = SkyAtmosphere;
  exports.SkyBox = SkyBox;
  exports.SphereEmitter = SphereEmitter;
  exports.SphereGeometry = SphereGeometry;
  exports.SphereOutlineGeometry = SphereOutlineGeometry;
  exports.Spherical = Spherical;
  exports.Spline = Spline;
  exports.SplitDirection = SplitDirection$1;
  exports.Splitter = Splitter;
  exports.StaticGeometryColorBatch = StaticGeometryColorBatch;
  exports.StaticGeometryPerMaterialBatch = StaticGeometryPerMaterialBatch;
  exports.StaticGroundGeometryColorBatch = StaticGroundGeometryColorBatch;
  exports.StaticGroundGeometryPerMaterialBatch = StaticGroundGeometryPerMaterialBatch;
  exports.StaticGroundPolylinePerMaterialBatch = StaticGroundPolylinePerMaterialBatch;
  exports.StaticOutlineGeometryBatch = StaticOutlineGeometryBatch;
  exports.StencilConstants = StencilConstants$1;
  exports.StencilFunction = StencilFunction$1;
  exports.StencilOperation = StencilOperation$1;
  exports.SteppedSpline = SteppedSpline$1;
  exports.StripeMaterialProperty = StripeMaterialProperty;
  exports.StripeOrientation = StripeOrientation$1;
  exports.StructuralMetadata = StructuralMetadata;
  exports.StyleCommandsNeeded = StyleCommandsNeeded$1;
  exports.StyleExpression = StyleExpression;
  exports.Sun = Sun;
  exports.SunLight = SunLight;
  exports.SunPostProcess = SunPostProcess;
  exports.SupportedImageFormats = SupportedImageFormats;
  exports.SvgPathBindingHandler = SvgPathBindingHandler;
  exports.TaskProcessor = TaskProcessor;
  exports.TerrainData = TerrainData;
  exports.TerrainEncoding = TerrainEncoding;
  exports.TerrainExaggeration = TerrainExaggeration;
  exports.TerrainFillMesh = TerrainFillMesh;
  exports.TerrainMesh = TerrainMesh;
  exports.TerrainOffsetProperty = TerrainOffsetProperty;
  exports.TerrainProvider = TerrainProvider;
  exports.TerrainQuantization = TerrainQuantization$1;
  exports.TerrainState = TerrainState$1;
  exports.Texture = Texture;
  exports.TextureAtlas = TextureAtlas;
  exports.TextureCache = TextureCache;
  exports.TextureMagnificationFilter = TextureMagnificationFilter$1;
  exports.TextureManager = TextureManager;
  exports.TextureMinificationFilter = TextureMinificationFilter$1;
  exports.TextureUniform = TextureUniform;
  exports.TextureWrap = TextureWrap$1;
  exports.TileAvailability = TileAvailability;
  exports.TileBoundingRegion = TileBoundingRegion;
  exports.TileBoundingS2Cell = TileBoundingS2Cell;
  exports.TileBoundingSphere = TileBoundingSphere;
  exports.TileBoundingVolume = TileBoundingVolume;
  exports.TileCoordinatesImageryProvider = TileCoordinatesImageryProvider;
  exports.TileDiscardPolicy = TileDiscardPolicy;
  exports.TileEdge = TileEdge;
  exports.TileImagery = TileImagery;
  exports.TileMapServiceImageryProvider = TileMapServiceImageryProvider;
  exports.TileMetadata = TileMetadata;
  exports.TileOrientedBoundingBox = TileOrientedBoundingBox;
  exports.TileProviderError = TileProviderError;
  exports.TileReplacementQueue = TileReplacementQueue;
  exports.TileSelectionResult = TileSelectionResult;
  exports.TileState = TileState$1;
  exports.Tileset3DTileContent = Tileset3DTileContent;
  exports.TilesetMetadata = TilesetMetadata;
  exports.TilingScheme = TilingScheme;
  exports.TimeConstants = TimeConstants$1;
  exports.TimeDynamicImagery = TimeDynamicImagery;
  exports.TimeDynamicPointCloud = TimeDynamicPointCloud;
  exports.TimeInterval = TimeInterval;
  exports.TimeIntervalCollection = TimeIntervalCollection;
  exports.TimeIntervalCollectionPositionProperty = TimeIntervalCollectionPositionProperty;
  exports.TimeIntervalCollectionProperty = TimeIntervalCollectionProperty;
  exports.TimeStandard = TimeStandard$1;
  exports.Timeline = Timeline;
  exports.TimelineHighlightRange = TimelineHighlightRange;
  exports.TimelineTrack = TimelineTrack;
  exports.Tipsify = Tipsify;
  exports.ToggleButtonViewModel = ToggleButtonViewModel;
  exports.Tonemapper = Tonemapper$1;
  exports.Transforms = Transforms;
  exports.TranslationRotationScale = TranslationRotationScale;
  exports.TranslucentTileClassification = TranslucentTileClassification;
  exports.TridiagonalSystemSolver = TridiagonalSystemSolver;
  exports.TrustedServers = TrustedServers;
  exports.Tween = Tween$1;
  exports.TweenCollection = TweenCollection;
  exports.UniformState = UniformState;
  exports.UniformType = UniformType$1;
  exports.Uri = URI;
  exports.UrlTemplateImageryProvider = UrlTemplateImageryProvider;
  exports.VERSION = VERSION;
  exports.VRButton = VRButton;
  exports.VRButtonViewModel = VRButtonViewModel;
  exports.VRTheWorldTerrainProvider = VRTheWorldTerrainProvider;
  exports.VaryingType = VaryingType$1;
  exports.Vector3DTileBatch = Vector3DTileBatch;
  exports.Vector3DTileClampedPolylines = Vector3DTileClampedPolylines;
  exports.Vector3DTileContent = Vector3DTileContent;
  exports.Vector3DTileGeometry = Vector3DTileGeometry;
  exports.Vector3DTilePoints = Vector3DTilePoints;
  exports.Vector3DTilePolygons = Vector3DTilePolygons;
  exports.Vector3DTilePolylines = Vector3DTilePolylines;
  exports.Vector3DTilePrimitive = Vector3DTilePrimitive;
  exports.VelocityOrientationProperty = VelocityOrientationProperty;
  exports.VelocityVectorProperty = VelocityVectorProperty;
  exports.VertexArray = VertexArray;
  exports.VertexArrayFacade = VertexArrayFacade;
  exports.VertexAttributeSemantic = VertexAttributeSemantic$1;
  exports.VertexFormat = VertexFormat;
  exports.VerticalOrigin = VerticalOrigin$1;
  exports.VideoSynchronizer = VideoSynchronizer;
  exports.View = View;
  exports.Viewer = Viewer;
  exports.ViewportQuad = ViewportQuad;
  exports.Visibility = Visibility$1;
  exports.Visualizer = Visualizer;
  exports.VulkanConstants = VulkanConstants$1;
  exports.WallGeometry = WallGeometry;
  exports.WallGeometryLibrary = WallGeometryLibrary;
  exports.WallGeometryUpdater = WallGeometryUpdater;
  exports.WallGraphics = WallGraphics;
  exports.WallOutlineGeometry = WallOutlineGeometry;
  exports.WebGLConstants = WebGLConstants$1;
  exports.WebMapServiceImageryProvider = WebMapServiceImageryProvider;
  exports.WebMapTileServiceImageryProvider = WebMapTileServiceImageryProvider;
  exports.WebMercatorProjection = WebMercatorProjection;
  exports.WebMercatorTilingScheme = WebMercatorTilingScheme;
  exports.WindingOrder = WindingOrder$1;
  exports.WireframeIndexGenerator = WireframeIndexGenerator;
  exports.WireframePipelineStage = WireframePipelineStage;
  exports._shadersAcesTonemappingStage = AcesTonemapping;
  exports._shadersAdditiveBlend = AdditiveBlend;
  exports._shadersAdjustTranslucentFS = AdjustTranslucentFS;
  exports._shadersAllMaterialAppearanceFS = AllMaterialAppearanceFS;
  exports._shadersAllMaterialAppearanceVS = AllMaterialAppearanceVS;
  exports._shadersAmbientOcclusionGenerate = AmbientOcclusionGenerate;
  exports._shadersAmbientOcclusionModulate = AmbientOcclusionModulate;
  exports._shadersAspectRampMaterial = AspectRampMaterial;
  exports._shadersAtmosphereCommon = AtmosphereCommon;
  exports._shadersBasicMaterialAppearanceFS = BasicMaterialAppearanceFS;
  exports._shadersBasicMaterialAppearanceVS = BasicMaterialAppearanceVS;
  exports._shadersBillboardCollectionFS = BillboardCollectionFS;
  exports._shadersBillboardCollectionVS = BillboardCollectionVS;
  exports._shadersBlackAndWhite = BlackAndWhite;
  exports._shadersBloomComposite = BloomComposite;
  exports._shadersBrdfLutGeneratorFS = BrdfLutGeneratorFS;
  exports._shadersBrightPass = BrightPass;
  exports._shadersBrightness = Brightness;
  exports._shadersBumpMapMaterial = BumpMapMaterial;
  exports._shadersCPUStylingStageFS = CPUStylingStageFS;
  exports._shadersCPUStylingStageVS = CPUStylingStageVS;
  exports._shadersCheckerboardMaterial = CheckerboardMaterial;
  exports._shadersCloudCollectionFS = CloudCollectionFS;
  exports._shadersCloudCollectionVS = CloudCollectionVS;
  exports._shadersCloudNoiseFS = CloudNoiseFS;
  exports._shadersCloudNoiseVS = CloudNoiseVS;
  exports._shadersCompareAndPackTranslucentDepth = CompareAndPackTranslucentDepth;
  exports._shadersCompositeOITFS = CompositeOITFS;
  exports._shadersCompositeTranslucentClassification = CompositeTranslucentClassification;
  exports._shadersContrastBias = ContrastBias;
  exports._shadersCustomShaderStageFS = CustomShaderStageFS;
  exports._shadersCustomShaderStageVS = CustomShaderStageVS;
  exports._shadersCzmBuiltins = CzmBuiltins;
  exports._shadersDepthOfField = DepthOfField;
  exports._shadersDepthPlaneFS = DepthPlaneFS;
  exports._shadersDepthPlaneVS = DepthPlaneVS;
  exports._shadersDepthView = DepthView;
  exports._shadersDepthViewPacked = DepthViewPacked;
  exports._shadersDotMaterial = DotMaterial;
  exports._shadersEdgeDetection = EdgeDetection;
  exports._shadersElevationBandMaterial = ElevationBandMaterial;
  exports._shadersElevationContourMaterial = ElevationContourMaterial;
  exports._shadersElevationRampMaterial = ElevationRampMaterial;
  exports._shadersEllipsoidFS = EllipsoidFS;
  exports._shadersEllipsoidSurfaceAppearanceFS = EllipsoidSurfaceAppearanceFS;
  exports._shadersEllipsoidSurfaceAppearanceVS = EllipsoidSurfaceAppearanceVS;
  exports._shadersEllipsoidVS = EllipsoidVS;
  exports._shadersFXAA = FXAA;
  exports._shadersFXAA3_11 = FXAA3_11;
  exports._shadersFadeMaterial = FadeMaterial;
  exports._shadersFeatureIdStageFS = FeatureIdStageFS;
  exports._shadersFeatureIdStageVS = FeatureIdStageVS;
  exports._shadersFilmicTonemapping = FilmicTonemapping;
  exports._shadersGaussianBlur1D = GaussianBlur1D;
  exports._shadersGeometryStageFS = GeometryStageFS;
  exports._shadersGeometryStageVS = GeometryStageVS;
  exports._shadersGlobeFS = GlobeFS;
  exports._shadersGlobeVS = GlobeVS;
  exports._shadersGridMaterial = GridMaterial;
  exports._shadersGroundAtmosphere = GroundAtmosphere;
  exports._shadersHSBToRGB = czm_HSBToRGB;
  exports._shadersHSLToRGB = czm_HSLToRGB;
  exports._shadersImageBasedLightingStageFS = ImageBasedLightingStageFS;
  exports._shadersInstancingStageCommon = InstancingStageCommon;
  exports._shadersInstancingStageVS = InstancingStageVS;
  exports._shadersLegacyInstancingStageVS = LegacyInstancingStageVS;
  exports._shadersLensFlare = LensFlare;
  exports._shadersLightingStageFS = LightingStageFS;
  exports._shadersMaterialStageFS = MaterialStageFS;
  exports._shadersMetadataStageFS = MetadataStageFS;
  exports._shadersMetadataStageVS = MetadataStageVS;
  exports._shadersModelClippingPlanesStageFS = ModelClippingPlanesStageFS;
  exports._shadersModelColorStageFS = ModelColorStageFS;
  exports._shadersModelExperimentalFS = ModelExperimentalFS;
  exports._shadersModelExperimentalVS = ModelExperimentalVS;
  exports._shadersModelSilhouetteStageFS = ModelSilhouetteStageFS;
  exports._shadersModelSilhouetteStageVS = ModelSilhouetteStageVS;
  exports._shadersModelSplitterStageFS = ModelSplitterStageFS;
  exports._shadersModifiedReinhardTonemapping = ModifiedReinhardTonemapping;
  exports._shadersMorphTargetsStageVS = MorphTargetsStageVS;
  exports._shadersNightVision = NightVision;
  exports._shadersNormalMapMaterial = NormalMapMaterial;
  exports._shadersOctahedralProjectionAtlasFS = OctahedralProjectionAtlasFS;
  exports._shadersOctahedralProjectionFS = OctahedralProjectionFS;
  exports._shadersOctahedralProjectionVS = OctahedralProjectionVS;
  exports._shadersPassThrough = PassThrough;
  exports._shadersPassThroughDepth = PassThroughDepth;
  exports._shadersPerInstanceColorAppearanceFS = PerInstanceColorAppearanceFS;
  exports._shadersPerInstanceColorAppearanceVS = PerInstanceColorAppearanceVS;
  exports._shadersPerInstanceFlatColorAppearanceFS = PerInstanceFlatColorAppearanceFS;
  exports._shadersPerInstanceFlatColorAppearanceVS = PerInstanceFlatColorAppearanceVS;
  exports._shadersPointCloudAttenuationStageVS = PointCloudAttenuationStageVS;
  exports._shadersPointCloudEyeDomeLighting = PointCloudEyeDomeLightingShader;
  exports._shadersPointPrimitiveCollectionFS = PointPrimitiveCollectionFS;
  exports._shadersPointPrimitiveCollectionVS = PointPrimitiveCollectionVS;
  exports._shadersPolylineArrowMaterial = PolylineArrowMaterial;
  exports._shadersPolylineColorAppearanceVS = PolylineColorAppearanceVS;
  exports._shadersPolylineCommon = PolylineCommon;
  exports._shadersPolylineDashMaterial = PolylineDashMaterial;
  exports._shadersPolylineFS = PolylineFS$1;
  exports._shadersPolylineGlowMaterial = PolylineGlowMaterial;
  exports._shadersPolylineMaterialAppearanceVS = PolylineMaterialAppearanceVS;
  exports._shadersPolylineOutlineMaterial = PolylineOutlineMaterial;
  exports._shadersPolylineShadowVolumeFS = PolylineShadowVolumeFS;
  exports._shadersPolylineShadowVolumeMorphFS = PolylineShadowVolumeMorphFS;
  exports._shadersPolylineShadowVolumeMorphVS = PolylineShadowVolumeMorphVS;
  exports._shadersPolylineShadowVolumeVS = PolylineShadowVolumeVS;
  exports._shadersPolylineVS = PolylineVS;
  exports._shadersRGBToHSB = czm_RGBToHSB;
  exports._shadersRGBToHSL = czm_RGBToHSL;
  exports._shadersRGBToXYZ = czm_RGBToXYZ;
  exports._shadersReinhardTonemapping = ReinhardTonemapping;
  exports._shadersReprojectWebMercatorFS = ReprojectWebMercatorFS;
  exports._shadersReprojectWebMercatorVS = ReprojectWebMercatorVS;
  exports._shadersRimLightingMaterial = RimLightingMaterial;
  exports._shadersSelectedFeatureIdStageCommon = SelectedFeatureIdStageCommon;
  exports._shadersShadowVolumeAppearanceFS = ShadowVolumeAppearanceFS;
  exports._shadersShadowVolumeAppearanceVS = ShadowVolumeAppearanceVS;
  exports._shadersShadowVolumeFS = ShadowVolumeFS;
  exports._shadersSilhouette = Silhouette;
  exports._shadersSkinningStageVS = SkinningStageVS;
  exports._shadersSkyAtmosphereCommon = SkyAtmosphereCommon;
  exports._shadersSkyAtmosphereFS = SkyAtmosphereFS;
  exports._shadersSkyAtmosphereVS = SkyAtmosphereVS;
  exports._shadersSkyBoxFS = SkyBoxFS;
  exports._shadersSkyBoxVS = SkyBoxVS;
  exports._shadersSlopeRampMaterial = SlopeRampMaterial;
  exports._shadersStripeMaterial = StripeMaterial;
  exports._shadersSunFS = SunFS;
  exports._shadersSunTextureFS = SunTextureFS;
  exports._shadersSunVS = SunVS;
  exports._shadersTexturedMaterialAppearanceFS = TexturedMaterialAppearanceFS;
  exports._shadersTexturedMaterialAppearanceVS = TexturedMaterialAppearanceVS;
  exports._shadersVector3DTileClampedPolylinesFS = Vector3DTileClampedPolylinesFS;
  exports._shadersVector3DTileClampedPolylinesVS = Vector3DTileClampedPolylinesVS;
  exports._shadersVector3DTilePolylinesVS = Vector3DTilePolylinesVS;
  exports._shadersVectorTileVS = VectorTileVS;
  exports._shadersViewportQuadFS = ViewportQuadFS;
  exports._shadersViewportQuadVS = ViewportQuadVS;
  exports._shadersWater = WaterMaterial;
  exports._shadersXYZToRGB = czm_XYZToRGB;
  exports._shadersacesTonemapping = czm_acesTonemapping;
  exports._shadersalphaWeight = czm_alphaWeight;
  exports._shadersantialias = czm_antialias;
  exports._shadersapproximateSphericalCoordinates = czm_approximateSphericalCoordinates;
  exports._shadersbackFacing = czm_backFacing;
  exports._shadersbranchFreeTernary = czm_branchFreeTernary;
  exports._shaderscascadeColor = czm_cascadeColor;
  exports._shaderscascadeDistance = czm_cascadeDistance;
  exports._shaderscascadeMatrix = czm_cascadeMatrix;
  exports._shaderscascadeWeights = czm_cascadeWeights;
  exports._shaderscolumbusViewMorph = czm_columbusViewMorph;
  exports._shaderscomputePosition = czm_computePosition;
  exports._shaderscosineAndSine = czm_cosineAndSine;
  exports._shadersdecompressTextureCoordinates = czm_decompressTextureCoordinates;
  exports._shadersdefaultPbrMaterial = czm_defaultPbrMaterial;
  exports._shadersdegreesPerRadian = czm_degreesPerRadian;
  exports._shadersdepthClamp = czm_depthClamp;
  exports._shadersdepthRange = czm_depthRange;
  exports._shadersdepthRangeStruct = czm_depthRangeStruct;
  exports._shaderseastNorthUpToEyeCoordinates = czm_eastNorthUpToEyeCoordinates;
  exports._shadersellipsoidContainsPoint = czm_ellipsoidContainsPoint;
  exports._shadersellipsoidWgs84TextureCoordinates = czm_ellipsoidWgs84TextureCoordinates;
  exports._shadersepsilon1 = czm_epsilon1;
  exports._shadersepsilon2 = czm_epsilon2;
  exports._shadersepsilon3 = czm_epsilon3;
  exports._shadersepsilon4 = czm_epsilon4;
  exports._shadersepsilon5 = czm_epsilon5;
  exports._shadersepsilon6 = czm_epsilon6;
  exports._shadersepsilon7 = czm_epsilon7;
  exports._shadersequalsEpsilon = czm_equalsEpsilon;
  exports._shaderseyeOffset = czm_eyeOffset;
  exports._shaderseyeToWindowCoordinates = czm_eyeToWindowCoordinates;
  exports._shadersfastApproximateAtan = czm_fastApproximateAtan;
  exports._shadersfog = czm_fog;
  exports._shadersgammaCorrect = czm_gammaCorrect;
  exports._shadersgeodeticSurfaceNormal = czm_geodeticSurfaceNormal;
  exports._shadersgetDefaultMaterial = czm_getDefaultMaterial;
  exports._shadersgetLambertDiffuse = czm_getLambertDiffuse;
  exports._shadersgetSpecular = czm_getSpecular;
  exports._shadersgetWaterNoise = czm_getWaterNoise;
  exports._shadershue = czm_hue;
  exports._shadersinfinity = czm_infinity;
  exports._shadersinverseGamma = czm_inverseGamma;
  exports._shadersisEmpty = czm_isEmpty;
  exports._shadersisFull = czm_isFull;
  exports._shaderslatitudeToWebMercatorFraction = czm_latitudeToWebMercatorFraction;
  exports._shaderslineDistance = czm_lineDistance;
  exports._shaderslinearToSrgb = czm_linearToSrgb;
  exports._shadersluminance = czm_luminance;
  exports._shadersmaterial = czm_material;
  exports._shadersmaterialInput = czm_materialInput;
  exports._shadersmetersPerPixel = czm_metersPerPixel;
  exports._shadersmodelMaterial = czm_modelMaterial;
  exports._shadersmodelToWindowCoordinates = czm_modelToWindowCoordinates;
  exports._shadersmodelVertexOutput = czm_modelVertexOutput;
  exports._shadersmultiplyWithColorBalance = czm_multiplyWithColorBalance;
  exports._shadersnearFarScalar = czm_nearFarScalar;
  exports._shadersoctDecode = czm_octDecode;
  exports._shadersoneOverPi = czm_oneOverPi;
  exports._shadersoneOverTwoPi = czm_oneOverTwoPi;
  exports._shaderspackDepth = czm_packDepth;
  exports._shaderspassCesium3DTile = czm_passCesium3DTile;
  exports._shaderspassCesium3DTileClassification = czm_passCesium3DTileClassification;
  exports._shaderspassCesium3DTileClassificationIgnoreShow = czm_passCesium3DTileClassificationIgnoreShow;
  exports._shaderspassClassification = czm_passClassification;
  exports._shaderspassCompute = czm_passCompute;
  exports._shaderspassEnvironment = czm_passEnvironment;
  exports._shaderspassGlobe = czm_passGlobe;
  exports._shaderspassOpaque = czm_passOpaque;
  exports._shaderspassOverlay = czm_passOverlay;
  exports._shaderspassTerrainClassification = czm_passTerrainClassification;
  exports._shaderspassTranslucent = czm_passTranslucent;
  exports._shaderspbrLighting = czm_pbrLighting;
  exports._shaderspbrMetallicRoughnessMaterial = czm_pbrMetallicRoughnessMaterial;
  exports._shaderspbrParameters = czm_pbrParameters;
  exports._shaderspbrSpecularGlossinessMaterial = czm_pbrSpecularGlossinessMaterial;
  exports._shadersphong = czm_phong;
  exports._shaderspi = czm_pi;
  exports._shaderspiOverFour = czm_piOverFour;
  exports._shaderspiOverSix = czm_piOverSix;
  exports._shaderspiOverThree = czm_piOverThree;
  exports._shaderspiOverTwo = czm_piOverTwo;
  exports._shadersplaneDistance = czm_planeDistance;
  exports._shaderspointAlongRay = czm_pointAlongRay;
  exports._shadersradiansPerDegree = czm_radiansPerDegree;
  exports._shadersray = czm_ray;
  exports._shadersrayEllipsoidIntersectionInterval = czm_rayEllipsoidIntersectionInterval;
  exports._shadersraySegment = czm_raySegment;
  exports._shadersraySphereIntersectionInterval = czm_raySphereIntersectionInterval;
  exports._shadersreadDepth = czm_readDepth;
  exports._shadersreadNonPerspective = czm_readNonPerspective;
  exports._shadersreverseLogDepth = czm_reverseLogDepth;
  exports._shadersround = czm_round;
  exports._shaderssampleOctahedralProjection = czm_sampleOctahedralProjection;
  exports._shaderssaturation = czm_saturation;
  exports._shaderssceneMode2D = czm_sceneMode2D;
  exports._shaderssceneMode3D = czm_sceneMode3D;
  exports._shaderssceneModeColumbusView = czm_sceneModeColumbusView;
  exports._shaderssceneModeMorphing = czm_sceneModeMorphing;
  exports._shadersshadowDepthCompare = czm_shadowDepthCompare;
  exports._shadersshadowParameters = czm_shadowParameters;
  exports._shadersshadowVisibility = czm_shadowVisibility;
  exports._shaderssignNotZero = czm_signNotZero;
  exports._shaderssolarRadius = czm_solarRadius;
  exports._shaderssphericalHarmonics = czm_sphericalHarmonics;
  exports._shaderssrgbToLinear = czm_srgbToLinear;
  exports._shaderstangentToEyeSpaceMatrix = czm_tangentToEyeSpaceMatrix;
  exports._shadersthreePiOver2 = czm_threePiOver2;
  exports._shaderstransformPlane = czm_transformPlane;
  exports._shaderstranslateRelativeToEye = czm_translateRelativeToEye;
  exports._shaderstranslucentPhong = czm_translucentPhong;
  exports._shaderstranspose = czm_transpose;
  exports._shaderstwoPi = czm_twoPi;
  exports._shadersunpackDepth = czm_unpackDepth;
  exports._shadersunpackFloat = czm_unpackFloat;
  exports._shadersunpackUint = czm_unpackUint;
  exports._shadersvalueTransform = czm_valueTransform;
  exports._shadersvertexLogDepth = czm_vertexLogDepth;
  exports._shaderswebMercatorMaxLatitude = czm_webMercatorMaxLatitude;
  exports._shaderswindowToEyeCoordinates = czm_windowToEyeCoordinates;
  exports._shaderswriteDepthClamp = czm_writeDepthClamp;
  exports._shaderswriteLogDepth = czm_writeLogDepth;
  exports._shaderswriteNonPerspective = czm_writeNonPerspective;
  exports.addBuffer = addBuffer;
  exports.addDefaults = addDefaults;
  exports.addExtensionsRequired = addExtensionsRequired;
  exports.addExtensionsUsed = addExtensionsUsed;
  exports.addPipelineExtras = addPipelineExtras;
  exports.addToArray = addToArray;
  exports.appendForwardSlash = appendForwardSlash;
  exports.arrayRemoveDuplicates = arrayRemoveDuplicates;
  exports.barycentricCoordinates = barycentricCoordinates;
  exports.binarySearch = binarySearch;
  exports.bitmap_sdf = bitmapSdf;
  exports.buildDrawCommand = buildDrawCommand;
  exports.buildModuleUrl = buildModuleUrl;
  exports.cancelAnimationFrame = cancelAnimationFramePolyfill;
  exports.clone = clone$1;
  exports.combine = combine$2;
  exports.computeFlyToLocationForRectangle = computeFlyToLocationForRectangle;
  exports.createBillboardPointCallback = createBillboardPointCallback;
  exports.createCommand = createCommand;
  exports.createDefaultImageryProviderViewModels = createDefaultImageryProviderViewModels;
  exports.createDefaultTerrainProviderViewModels = createDefaultTerrainProviderViewModels;
  exports.createElevationBandMaterial = createElevationBandMaterial;
  exports.createGuid = createGuid;
  exports.createMaterialPropertyDescriptor = createMaterialPropertyDescriptor;
  exports.createOsmBuildings = createOsmBuildings;
  exports.createPropertyDescriptor = createPropertyDescriptor;
  exports.createRawPropertyDescriptor = createRawPropertyDescriptor;
  exports.createTangentSpaceDebugPrimitive = createTangentSpaceDebugPrimitive;
  exports.createTaskProcessorWorker = createTaskProcessorWorker;
  exports.createUniform = createUniform;
  exports.createUniformArray = createUniformArray;
  exports.createWorldImagery = createWorldImagery;
  exports.createWorldTerrain = createWorldTerrain;
  exports.decodeGoogleEarthEnterpriseData = decodeGoogleEarthEnterpriseData;
  exports.decodeVectorPolylinePositions = decodeVectorPolylinePositions;
  exports.defaultValue = defaultValue;
  exports.defer = defer;
  exports.defined = defined;
  exports.deprecationWarning = deprecationWarning;
  exports.destroyObject = destroyObject;
  exports.dompurify = purify;
  exports.earcut = earcut_1;
  exports.exportKml = exportKml;
  exports.findAccessorMinMax = findAccessorMinMax;
  exports.findContentMetadata = findContentMetadata;
  exports.findGroupMetadata = findGroupMetadata;
  exports.findTileMetadata = findTileMetadata;
  exports.forEachTextureInMaterial = forEachTextureInMaterial;
  exports.formatError = formatError;
  exports.freezeRenderState = freezeRenderState;
  exports.getAbsoluteUri = getAbsoluteUri;
  exports.getAccessorByteStride = getAccessorByteStride;
  exports.getBaseUri = getBaseUri;
  exports.getBinaryAccessor = getBinaryAccessor;
  exports.getClipAndStyleCode = getClipAndStyleCode;
  exports.getClippingFunction = getClippingFunction;
  exports.getComponentReader = getComponentReader;
  exports.getElement = getElement;
  exports.getExtensionFromUri = getExtensionFromUri;
  exports.getFilenameFromUri = getFilenameFromUri;
  exports.getImageFromTypedArray = getImageFromTypedArray;
  exports.getImagePixels = getImagePixels;
  exports.getJsonFromTypedArray = getJsonFromTypedArray;
  exports.getMagic = getMagic;
  exports.getStringFromTypedArray = getStringFromTypedArray;
  exports.getTimestamp = getTimestamp$1;
  exports.grapheme_splitter = graphemeSplitter;
  exports.hasExtension = hasExtension;
  exports.heightReferenceOnEntityPropertyChanged = heightReferenceOnEntityPropertyChanged;
  exports.isBitSet = isBitSet;
  exports.isBlobUri = isBlobUri;
  exports.isCrossOriginUrl = isCrossOriginUrl;
  exports.isDataUri = isDataUri;
  exports.isLeapYear = isLeapYear;
  exports.jsep = jsep;
  exports.kdbush = KDBush;
  exports.knockout = knockout;
  exports.knockout_3_5_1 = knockout;
  exports.knockout_es5 = knockout_es5;
  exports.ktx_parse = p;
  exports.lerc = LercDecode;
  exports.loadAndExecuteScript = loadAndExecuteScript;
  exports.loadCubeMap = loadCubeMap;
  exports.loadImageFromTypedArray = loadImageFromTypedArray;
  exports.loadKTX2 = loadKTX2;
  exports.mergeSort = mergeSort;
  exports.mersenne_twister = mersenneTwister;
  exports.meshoptimizer = MeshoptDecoder;
  exports.modernizeShader = modernizeShader;
  exports.moveTechniqueRenderStates = moveTechniqueRenderStates;
  exports.moveTechniquesToExtension = moveTechniquesToExtension;
  exports.nosleep = src;
  exports.numberOfComponentsForType = numberOfComponentsForType;
  exports.objectToQuery = objectToQuery;
  exports.oneTimeWarning = oneTimeWarning;
  exports.pako = inflate_1;
  exports.parseBatchTable = parseBatchTable;
  exports.parseBoundingVolumeSemantics = parseBoundingVolumeSemantics;
  exports.parseFeatureMetadataLegacy = parseFeatureMetadataLegacy;
  exports.parseGlb = parseGlb;
  exports.parseResponseHeaders = parseResponseHeaders;
  exports.parseStructuralMetadata = parseStructuralMetadata;
  exports.pointInsideTriangle = pointInsideTriangle;
  exports.preprocess3DTileContent = preprocess3DTileContent;
  exports.processModelMaterialsCommon = processModelMaterialsCommon;
  exports.processPbrMaterials = processPbrMaterials;
  exports.protobufjs = protobuf$1;
  exports.queryToObject = queryToObject;
  exports.rbush = RBush;
  exports.readAccessorPacked = readAccessorPacked;
  exports.removeExtensionsRequired = removeExtensionsRequired;
  exports.removeExtensionsUsed = removeExtensionsUsed;
  exports.removePipelineExtras = removePipelineExtras;
  exports.removeUnusedElements = removeUnusedElements;
  exports.requestAnimationFrame = requestAnimationFramePolyFill;
  exports.resizeImageToNextPowerOfTwo = resizeImageToNextPowerOfTwo;
  exports.sampleTerrain = sampleTerrain;
  exports.sampleTerrainMostDetailed = sampleTerrainMostDetailed;
  exports.scaleToGeodeticSurface = scaleToGeodeticSurface;
  exports.subdivideArray = subdivideArray;
  exports.subscribeAndEvaluate = subscribeAndEvaluate;
  exports.topojson = index;
  exports.updateAccessorComponentTypes = updateAccessorComponentTypes;
  exports.updateVersion = updateVersion;
  exports.usesExtension = usesExtension;
  exports.viewerCesium3DTilesInspectorMixin = viewerCesium3DTilesInspectorMixin;
  exports.viewerCesiumInspectorMixin = viewerCesiumInspectorMixin;
  exports.viewerDragDropMixin = viewerDragDropMixin;
  exports.viewerPerformanceWatchdogMixin = viewerPerformanceWatchdogMixin;
  exports.webGLConstantToGlslType = webGLConstantToGlslType;
  exports.wrapFunction = wrapFunction;
  exports.writeTextToCanvas = writeTextToCanvas;
  exports.zip = zipNoWorker;

  Object.defineProperty(exports, '__esModule', { value: true });

}));
//# sourceMappingURL=Cesium.js.map
